diff --git a/.github/workflows/logical-mixer-fast.yml b/.github/workflows/logical-mixer-fast.yml index d0621622d..0313dc7cf 100644 --- a/.github/workflows/logical-mixer-fast.yml +++ b/.github/workflows/logical-mixer-fast.yml @@ -4,6 +4,10 @@ on: paths: - 'engine/core/DeviceIndependentMixerSession.h' - 'engine/core/DynamicChannelRoster.h' + - 'engine/core/DynamicPreparedMixerBlock.h' + - 'engine/core/DynamicAcceptedSession.h' + - 'engine/core/DynamicNativeSessionPublisher.h' + - 'tests/dynamic_accepted_session_test.cpp' - 'tests/device_independent_mixer_session_test.cpp' - '.github/workflows/logical-mixer-fast.yml' workflow_dispatch: @@ -19,3 +23,9 @@ jobs: tests/device_independent_mixer_session_test.cpp \ -o /tmp/arsonmix-logical-test /tmp/arsonmix-logical-test + - name: Compile and run native PCM gain, PRE/POST and SEND regressions (no JUCE) + run: | + c++ -std=c++20 -O1 -Wall -Wextra -Werror -I. \ + tests/dynamic_accepted_session_test.cpp \ + -o /tmp/arsonmix-dynamic-pcm-test + /tmp/arsonmix-dynamic-pcm-test diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 946c7d9dc..8cfff013f 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -185,8 +185,32 @@ jobs: "$RUNNER_TEMP/armix-first-run-policy" node --test tests/native_first_run_bootstrap_contract.test.mjs node --test tests/rc_operator_workflow_contract.test.mjs tests/workstream_coordination_contract.test.mjs tests/ci_workflow_efficiency_test.mjs tests/chat_ci_dispatch_contract.test.mjs tests/approved_native_m2_contract.test.cjs tests/native_artifact_packaging_contract.test.mjs tests/windows_installer_contract_test.mjs tests/live_graph_contract_test.mjs tests/native_caption_wire_geometry_contract.test.cjs + # Simulate Windows CP1252 before allocating MSVC: the native + # inspector Python child must explicitly select UTF-8. + PYTHONIOENCODING=cp1252 node --test --test-name-pattern="WIRE inspector controls PRIMARY BUS" tests/approved_native_m2_contract.test.cjs python -m unittest discover -s tests -p approved_native_gui_bundle_test.py -v python -m unittest discover -s scripts/tests -p test_factoryfx_release_bundle.py -v + # Portable ChannelId PCM routing MUST be checked in under a minute, + # before allocating a Windows JUCE/MSVC runner (93-CTest suite). + - name: Native ChannelId pre/post and fader PCM golden (Linux no JUCE) + run: | + g++ -std=c++20 -O2 -Wall -Wextra -Werror tests/mixer_routing_plan_test.cpp -o "$RUNNER_TEMP/armix-native-routing-pcm" + "$RUNNER_TEMP/armix-native-routing-pcm" + # LMS has a portable JUCE-free DSP kernel. Catch an actual PCM or + # allocation regression in seconds before paying for Windows MSVC. + - name: LMS prepared crossover / EQ / speaker matrix PCM preflight + if: ${{ github.event_name == 'pull_request' && hashFiles('tests/lms_prepared_speaker_pcm_test.cpp') != '' }} + run: | + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/lms_prepared_speaker_pcm_test.cpp -o "$RUNNER_TEMP/armix-lms-pcm" + "$RUNNER_TEMP/armix-lms-pcm" + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/lms_synthetic_realtime_budget_test.cpp -o "$RUNNER_TEMP/armix-lms-rt" + "$RUNNER_TEMP/armix-lms-rt" + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/lms_native_output_reservation_test.cpp -o "$RUNNER_TEMP/armix-lms-port-guard" + "$RUNNER_TEMP/armix-lms-port-guard" + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/lms_native_postfx_main_witness_test.cpp -o "$RUNNER_TEMP/armix-lms-post-main" + "$RUNNER_TEMP/armix-lms-post-main" + g++ -std=c++20 -O2 -DNDEBUG -fno-fast-math -Wall -Wextra -Werror tests/lms_native_draft_ack_readback_test.cpp -o "$RUNNER_TEMP/armix-lms-ack" + "$RUNNER_TEMP/armix-lms-ack" - name: WaveShell JUCE 8 class-index regression (source-aware) shell: bash run: | diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 68e525359..bffa9f73a 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -110,12 +110,14 @@ jobs: 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 + node --check site/preview-v2/assets/mixer-native-sonku.js + g++ -std=c++20 -O2 -Wall -Wextra -pedantic tests/sonku_spatial_core_test.cpp -o /tmp/armix-sonku-core-smoke + /tmp/armix-sonku-core-smoke python tests/native_peq_assembly_test.py python tests/native_v60_fader_assembly_contract.py python tests/approved_operator_ux_smoke.py python scripts/build_ui_css.py --check python tests/gui_baseline_lock_test.py - python tests/mixer_physical_keys_contract.py python tests/brand_icon_contract_test.py python tests/brand_package_files_test.py python tests/css_v28_restore.py @@ -188,6 +190,81 @@ jobs: if-no-files-found: ignore retention-days: 7 + sonku-preview: + name: 8D-SonKu native insert/editor Chromium FAT (desktop and narrow) + needs: quick + # Both 8D-SonKu and SOF native-owner PRs share ONE actual Chromium runner. + # Preserve fast-only checks for unrelated GUI and engine branches. + if: ${{ (github.event_name == 'pull_request' && (startsWith(github.head_ref, 'feat/8d-sonku-') || startsWith(github.head_ref, 'feat/sonku-p1-') || startsWith(github.head_ref, 'test/sof-native-') || startsWith(github.head_ref, 'integration/sof-sonku-main-') || startsWith(github.head_ref, 'fix/native-wire-inspector-') || (startsWith(github.head_ref, 'integration/sonku-m4-wire-') || startsWith(github.head_ref, 'integration/sonku-m4-guitar-picker-') || startsWith(github.head_ref, 'fix/sonku-')))) || (github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/heads/feat/8d-sonku-') && inputs.expected_sha != '') }} + runs-on: ubuntu-latest + timeout-minutes: 12 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && inputs.expected_sha != '' && inputs.expected_sha || github.sha }} + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install scoped Chromium only + run: | + python -m pip install playwright + python -m playwright install --with-deps chromium + - name: Actual native picker insert, ACK/readback, editor open, UI controls + run: python tests/approved_native_sonku_smoke.py + # Same Chromium installation and same native-only GUI assembler. + # Fast scoped SOF qualification runs on the existing SonKu integration + # job (zero additional browser runners and zero Windows recompiles). + - name: Native SOF PRE/POST, SEND ON, EdgeId gain and ACK/readback Chromium + run: python tests/approved_native_sof_chromium_smoke.py + - name: Native WIRE Inspector rejected gain and exact EdgeId ACK rollback (real Chromium) + run: python tests/approved_native_wire_gain_smoke.py + - name: Integrated V65 WIRE motion, SOF and actual native WIRE regression + if: ${{ github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/sof-sonku-main-') }} + run: | + python tests/pages_v60_fader_wire_tactile_smoke.py + python tests/approved_native_wire_gain_smoke.py + python tests/sof_contextual_console_smoke.py + - name: Render original 8D-SonKu headphone candidate through exact native HRTF + run: | + g++ -std=c++20 -O2 -Wall -Wextra -pedantic tools/sonku_offline_listening.cpp -o /tmp/sonku-listening + /tmp/sonku-listening sonku-listening + g++ -std=c++20 -O2 -Wall -Wextra -pedantic tests/sonku_early_reflections_test.cpp -o /tmp/sonku-room-test + /tmp/sonku-room-test + g++ -std=c++20 -O2 -Wall -Wextra -pedantic tests/sonku_musical_reverb_test.cpp -o /tmp/sonku-fdn-test + /tmp/sonku-fdn-test + - name: SonKu same-runner realtime CPU comparison (informational, not a release pass) + run: | + g++ -std=c++20 -O2 -Wall -Wextra -pedantic tools/sonku_rt_benchmark.cpp -o /tmp/sonku-rt-bench + /tmp/sonku-rt-bench + python tests/sonku_offline_demo_contract.py sonku-listening + - name: Publish 8D-SonKu reproducible listening WAVs and blind answer key + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ArSonMix-SonKu-Headphone-Audio-${{ github.run_id }} + path: sonku-listening/* + if-no-files-found: ignore + retention-days: 14 + - name: Keep verified 8D-SonKu editor screenshots + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ArSonMix-SonKu-Editor-${{ github.run_id }} + path: arsonmix-sonku-editor-*.png + if-no-files-found: ignore + retention-days: 7 + - name: Keep native SOF accepted-state desktop and narrow screenshots + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ArSonMix-SOF-PCM-Bridge-${{ github.run_id }} + path: | + arsonmix-native-sof-*.png + arsonmix-v60-*.png + native-wire-gain-*.png + if-no-files-found: ignore + retention-days: 7 + vocal-throw-preview: name: Vocal Throw native editor desktop/mobile Chromium FAT needs: quick @@ -280,7 +357,9 @@ jobs: name: Full Chromium /preview/ visual and interaction qualification # Draft edits are cheap; ChatGPT milestone comments dispatch this full suite. needs: quick - if: ${{ github.event_name != 'pull_request' }} + # Scoped SonKu exact-SHA milestone gets its own shorter visual + pointer FAT. + # Do not also run the full generic Chromium suite for the same manual SHA. + if: ${{ github.event_name != 'pull_request' && !(github.event_name == 'workflow_dispatch' && startsWith(github.ref, 'refs/heads/feat/8d-sonku-') && inputs.expected_sha != '') }} runs-on: ubuntu-latest timeout-minutes: 20 steps: @@ -333,6 +412,11 @@ jobs: python -m pip install --upgrade pip python -m pip install playwright python -m playwright install --with-deps chromium + # LMS Browser FAT is additive only when this feature exists in the + # exact checked-out source. Never test a separate or prototype renderer. + - name: LMS five-workspace crossover / matrix / EQ / geometry Chromium + if: ${{ hashFiles('tests/pages_lms_five_workspaces_smoke.py') != '' }} + run: python tests/pages_lms_five_workspaces_smoke.py - name: Verify opt-in actual /preview/ GUI profiling, default OFF run: python tests/approved_gui_perf_stage_a_smoke.py - name: Validate Stage B native meter dirty-write / authoritative Pages parity @@ -369,6 +453,8 @@ jobs: run: python tests/approved_native_wire_gain_smoke.py - name: Stage D one runtime CSSOM and actual stylesheet network count run: python tests/approved_css_stage_d_single_bundle_smoke.py + - name: Contextual GAIN/FX and Sends-on-Faders browser workflow + run: python tests/sof_contextual_console_smoke.py - name: V60 real Chromium tactile fader and selected full-span WIRE run: python tests/pages_v60_fader_wire_tactile_smoke.py - name: Stage C rendered CSS parity (original vs compiled, three viewports + hover) @@ -650,6 +736,7 @@ jobs: name: arsonmix-gui-current-smoke path: | pages-wire-main-*.png + pages-lms-*.png pages-v53-fx-rail-*.png pages-v51-portrait-meter-*.png pages-fader-rollback-*.png diff --git a/CMakeLists.txt b/CMakeLists.txt index d28a16cb7..e7a805180 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -77,10 +77,62 @@ message(STATUS "${ARMIX_GUI_BUNDLE_LOG}") file(GLOB_RECURSE ARMIX_APPROVED_GUI_BINARIES CONFIGURE_DEPENDS "${ARMIX_APPROVED_GUI_DIR}/assets/*") list(SORT ARMIX_APPROVED_GUI_BINARIES) -# Original Guitar FX artwork is embedded ONLY for the installed JUCE -# plugin editor; it never becomes a second /preview/ or runtime file path. +# Generate only the active, independent Guitar FX hardware layers before +# globs are evaluated. Never embed deprecated prototype pictures or pictures +# of non-playable modules (no chorus/reverb/etc in this native rig). +# All ON/OFF layers use identical geometry and are drawn inside fixed bounds. +find_program(ARMIX_GUITAR_NODE_EXECUTABLE NAMES node REQUIRED) +execute_process( + COMMAND "${ARMIX_GUITAR_NODE_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/build_guitar_fx_layered_assets.mjs" + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + RESULT_VARIABLE ARMIX_GUITAR_ART_RESULT + OUTPUT_VARIABLE ARMIX_GUITAR_ART_LOG + ERROR_VARIABLE ARMIX_GUITAR_ART_ERROR) +if(NOT ARMIX_GUITAR_ART_RESULT EQUAL 0) + message(FATAL_ERROR "Guitar FX layer generation failed: ${ARMIX_GUITAR_ART_ERROR}") +endif() +message(STATUS "${ARMIX_GUITAR_ART_LOG}") +# Optional hi-resolution artist layers are copied on top of the deterministic +# fallback *at configure time*, never loaded at runtime from user paths. +# Art approval adds the 12 PNGs to artist-source/; the source/audio contract +# remains unchanged. The shipped binary contains embedded PNG bytes only. +set(ARMIX_GUITAR_ART_SOURCE_DIR + "${CMAKE_CURRENT_SOURCE_DIR}/design-references/guitar-fx/artist-source" + CACHE PATH "Optional approved photo-real Guitar FX artist PNG source") +if(IS_DIRECTORY "${ARMIX_GUITAR_ART_SOURCE_DIR}") + # Reject incomplete/misaligned artist exports before CMake embeds them. + # A changed ON/OFF silhouette or outer frame would cause visible flicker. + execute_process( + COMMAND "${ARMIX_GUITAR_NODE_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/validate_guitar_fx_artist_source.mjs" + "${ARMIX_GUITAR_ART_SOURCE_DIR}" + RESULT_VARIABLE ARMIX_GUITAR_ART_CHECK_RESULT + OUTPUT_VARIABLE ARMIX_GUITAR_ART_CHECK_LOG + ERROR_VARIABLE ARMIX_GUITAR_ART_CHECK_ERROR) + if(NOT ARMIX_GUITAR_ART_CHECK_RESULT EQUAL 0) + message(FATAL_ERROR + "Invalid Guitar FX artist layers: ${ARMIX_GUITAR_ART_CHECK_ERROR}") + endif() + message(STATUS "${ARMIX_GUITAR_ART_CHECK_LOG}") + foreach(ARMIX_GFX_ASSET + gfx-amp-head.png gfx-cabinet.png gfx-pedal-gate-body.png + gfx-pedal-drive-body.png gfx-knob.png gfx-switch-off.png + gfx-switch-on.png gfx-button-off.png gfx-button-on.png + gfx-panel.png gfx-stomp-off.png gfx-stomp-on.png) + if(NOT EXISTS "${ARMIX_GUITAR_ART_SOURCE_DIR}/${ARMIX_GFX_ASSET}") + message(FATAL_ERROR "Incomplete approved Guitar FX art source: ${ARMIX_GFX_ASSET}") + endif() + configure_file( + "${ARMIX_GUITAR_ART_SOURCE_DIR}/${ARMIX_GFX_ASSET}" + "${CMAKE_CURRENT_SOURCE_DIR}/design-references/guitar-fx/assets/${ARMIX_GFX_ASSET}" + COPYONLY) + endforeach() + message(STATUS "Guitar FX approved layered artist art selected") +else() + message(STATUS "Guitar FX deterministic layered fallback selected") +endif() file(GLOB ARMIX_GUITAR_SKIN_PNGS CONFIGURE_DEPENDS - "${CMAKE_CURRENT_SOURCE_DIR}/design-references/guitar-fx/assets/*.png") + "${CMAKE_CURRENT_SOURCE_DIR}/design-references/guitar-fx/assets/gfx-*.png") list(SORT ARMIX_GUITAR_SKIN_PNGS) juce_add_binary_data(ARMixAssets SOURCES "${ARMIX_APPROVED_GUI_DIR}/index.html" ${ARMIX_APPROVED_GUI_BINARIES} @@ -88,7 +140,7 @@ juce_add_binary_data(ARMixAssets SOURCES "${ARMIX_BRAND_DIR}/arsonmix-256.png") target_include_directories(ARMixConsole PRIVATE "${ARMIX_APPROVED_GUI_DIR}") -target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h engine/builtin_fx/HarmonyDsp.h engine/builtin_fx/HarmonyMusicKey.h engine/builtin_fx/ChannelHarmonyProcessor.h src/VstOrbitController.h engine/core/MixerRoutingPlan.h engine/core/ChannelRoutingContract.h engine/core/ChannelSendPlan.h engine/core/AuxBusPlan.h engine/core/PreparedMixerBlock.h engine/core/MasterOutputMonoPolicy.h engine/core/LiveChannelFxGraph.h engine/core/PreparedNativeMixerSession.h engine/core/NativeDryRouteCommand.h engine/core/RealtimeRoutePublisher.h engine/device/LiveInputPortRegistry.h src/LiveDryRoutingLab.h engine/core/OrbitPhase.h engine/core/OrbitControlPolicy.h engine/core/OrbitMotion.h engine/core/OrbitDistanceMapping.h engine/core/DearVrPolarPolicy.h src/PluginCatalog.h src/NativeFxParameterHotkey.h src/FactoryFxRegistry.h src/PluginVault.h src/PortableWorkspace.h src/StudioBackup.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/NativeShowSchema.h src/NativeDryShowRecall.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/core/CallbackCadenceEvidence.h engine/diagnostics/CrackleEvidenceWindow.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/PeriodCapabilityEvidence.h engine/device/SessionLifecycle.h engine/device/WasapiCapabilityProbe.h engine/device/JuceIndependentClockDevice.h engine/device/LiveSecondaryOutputDevice.h engine/core/LiveOutputRouteGate.h engine/device/ClockBridgeSizing.h engine/device/IndependentStreamFormatFence.h engine/device/DirectRestoreBackoff.h engine/device/IndependentStreamWatchdog.h engine/device/BridgeContinuityGate.h engine/device/EndpointIdentityPolicy.h engine/device/WasapiEndpointIdentityGuard.h engine/device/AsioStartupPolicy.h engine/device/AsioPriorityDeviceManager.h engine/device/JuceActivePortSnapshot.h engine/device/AsioRegistrationPolicy.h engine/device/AsioRegistryIdentityProbe.h engine/device/DirectRouteFence.h) +target_sources(ARMixConsole PRIVATE src/Main.cpp src/LiveAudioEngine.h engine/builtin_fx/HarmonyDsp.h engine/builtin_fx/HarmonyMusicKey.h engine/builtin_fx/ChannelHarmonyProcessor.h engine/builtin_fx/SonKuSpatialProcessor.h engine/builtin_fx/sonku/SonKuSpatialCore.h engine/builtin_fx/sonku/SonKuMeasuredHrir.h src/VstOrbitController.h engine/core/MixerRoutingPlan.h engine/core/ChannelRoutingContract.h engine/core/ChannelSendPlan.h engine/core/AuxBusPlan.h engine/core/PreparedMixerBlock.h engine/core/MasterOutputMonoPolicy.h engine/core/LiveChannelFxGraph.h engine/core/PreparedNativeMixerSession.h engine/core/NativeDryRouteCommand.h engine/core/RealtimeRoutePublisher.h engine/device/LiveInputPortRegistry.h src/LiveDryRoutingLab.h engine/core/OrbitPhase.h engine/core/OrbitControlPolicy.h engine/core/OrbitMotion.h engine/core/OrbitDistanceMapping.h engine/core/DearVrPolarPolicy.h src/PluginCatalog.h src/NativeFxParameterHotkey.h src/FactoryFxRegistry.h src/PluginVault.h src/PortableWorkspace.h src/StudioBackup.h src/DiagnosticsRecorder.h src/StereoPan.h src/NativePresetArchive.h src/NativeShowSchema.h src/NativeDryShowRecall.h src/VstBusLayout.h src/LiveGraphHandoff.h src/DiagnosticTone.h engine/core/RealtimeHealthHistogram.h engine/core/CallbackCadenceEvidence.h engine/diagnostics/CrackleEvidenceWindow.h engine/device/AdaptiveClockBridge.h engine/device/AudioProfilePolicy.h engine/device/PeriodCapabilityEvidence.h engine/device/SessionLifecycle.h engine/device/WasapiCapabilityProbe.h engine/device/JuceIndependentClockDevice.h engine/device/LiveSecondaryOutputDevice.h engine/core/LiveOutputRouteGate.h engine/device/ClockBridgeSizing.h engine/device/IndependentStreamFormatFence.h engine/device/DirectRestoreBackoff.h engine/device/IndependentStreamWatchdog.h engine/device/BridgeContinuityGate.h engine/device/EndpointIdentityPolicy.h engine/device/WasapiEndpointIdentityGuard.h engine/device/AsioStartupPolicy.h engine/device/AsioPriorityDeviceManager.h engine/device/JuceActivePortSnapshot.h engine/device/AsioRegistrationPolicy.h engine/device/AsioRegistryIdentityProbe.h engine/device/DirectRouteFence.h) # Explicit UTF-8 source decoding: native channel icons are Unicode, and # MSVC's machine-specific ANSI source charset corrupts emoji literals. # Limit the flag to C++ (not Windows .rc/resource compilation). @@ -166,6 +218,39 @@ target_link_libraries(ARMixConsole PRIVATE include(CTest) if(BUILD_TESTING) + # LMS M2: portable native DSP kernel, prepared off-RT and exercised with + # actual PCM blocks. This is NOT a second mixer callback or device graph. + add_executable(ARMixSpeakerPcmTests tests/lms_prepared_speaker_pcm_test.cpp + engine/lms/PreparedSpeakerSystem.h) + target_compile_features(ARMixSpeakerPcmTests PRIVATE cxx_std_20) + add_test(NAME LMSNativeLR4MultisectionVerifiedOutputsAndDelay + COMMAND ARMixSpeakerPcmTests) + add_executable(ARMixSpeakerDraftAckReadbackTests + tests/lms_native_draft_ack_readback_test.cpp + engine/core/DynamicNativeSessionPublisher.h + engine/lms/NativeSpeakerOutputReservation.h) + target_compile_features(ARMixSpeakerDraftAckReadbackTests PRIVATE cxx_std_20) + add_test(NAME LMSNativeSameGraphDesignAckReadbackAndStaleRevocation + COMMAND ARMixSpeakerDraftAckReadbackTests) + add_executable(ARMixSpeakerPostFxMainWitnessTests + tests/lms_native_postfx_main_witness_test.cpp + engine/lms/PreparedSpeakerSystem.h + engine/core/DynamicNativeSessionPublisher.h) + target_compile_features(ARMixSpeakerPostFxMainWitnessTests PRIVATE cxx_std_20) + add_test(NAME LMSOneAcceptedNativeMainFxToEightWayShadowPcm + COMMAND ARMixSpeakerPostFxMainWitnessTests) + add_executable(ARMixSpeakerOutputReservationTests + tests/lms_native_output_reservation_test.cpp + engine/lms/NativeSpeakerOutputReservation.h + engine/lms/PreparedSpeakerSystem.h) + target_compile_features(ARMixSpeakerOutputReservationTests PRIVATE cxx_std_20) + add_test(NAME LMSNativeAcceptedChannelIdExclusiveAsioOutputGuard + COMMAND ARMixSpeakerOutputReservationTests) + add_executable(ARMixSpeakerRealtimeTests tests/lms_synthetic_realtime_budget_test.cpp + engine/lms/PreparedSpeakerSystem.h) + target_compile_features(ARMixSpeakerRealtimeTests PRIVATE cxx_std_20) + add_test(NAME LMSNativeFourWayStereoZeroCallbackHeap + COMMAND ARMixSpeakerRealtimeTests) juce_add_console_app(ARMixFactoryFxRegistryTests PRODUCT_NAME "ArSonMix Factory FX Integrity Tests") target_sources(ARMixFactoryFxRegistryTests PRIVATE tests/factory_fx_registry_test.cpp src/FactoryFxRegistry.h) target_link_libraries(ARMixFactoryFxRegistryTests PRIVATE juce::juce_core juce::juce_cryptography juce::juce_recommended_config_flags) @@ -205,6 +290,18 @@ if(BUILD_TESTING) add_test(NAME BuiltInFxUserPresetFourRealJuceAdaptersAndColdReopen COMMAND ARMixBuiltInFxAcceptedSnapshotTests) + # Native 8D-SonKu non-JUCE measured-HRIR PCM and deterministic orbit fixture. + add_executable(ARMixSonKuCoreTests tests/sonku_spatial_core_test.cpp) + target_compile_features(ARMixSonKuCoreTests PRIVATE cxx_std_20) + add_test(NAME NativeSonKuMeasuredBinauralDirectionalAndChunkParity COMMAND ARMixSonKuCoreTests) + # Real JUCE processor: audio-applied ACK, v1/v2 state, corruption fences. + juce_add_console_app(ARMixSonKuNativeStateTests PRODUCT_NAME "ArSonMix SonKu Native State Tests") + target_sources(ARMixSonKuNativeStateTests PRIVATE tests/sonku_native_state_test.cpp) + target_link_libraries(ARMixSonKuNativeStateTests PRIVATE + juce::juce_audio_processors juce::juce_recommended_config_flags) + target_compile_features(ARMixSonKuNativeStateTests PRIVATE cxx_std_20) + add_test(NAME NativeSonKuSessionV1V2AndAudioAppliedAck + COMMAND ARMixSonKuNativeStateTests) # Pure control-plane first-run routing selection: no JUCE, drivers, # WASAPI activation or callback dependencies. Full Windows CTest gate. add_executable(ARMixFirstRunEndpointPolicyTests diff --git a/design-references/guitar-fx/PRODUCTION_LAYERED_ART_CONTRACT.md b/design-references/guitar-fx/PRODUCTION_LAYERED_ART_CONTRACT.md new file mode 100644 index 000000000..9ef28bec2 --- /dev/null +++ b/design-references/guitar-fx/PRODUCTION_LAYERED_ART_CONTRACT.md @@ -0,0 +1,42 @@ +# Guitar FX — Production Layered PNG Contract + +This is the authoritative asset contract for the **existing native JUCE** Guitar FX Rig editor. The PCM graph, A/B presets, .smix restore, and hardware input routing stay unchanged. This is not a second plugin or WebView. + +## Required production layers + +Place all 12 artist-approved **RGBA (8-bit, non-interlaced) PNG** images in `design-references/guitar-fx/artist-source/` using the exact following names and canvas dimensions: + +| File | Canvas | Composited purpose | +|---|---|---| +| gfx-amp-head.png | 720×300 | Amp body without rotary controls | +| gfx-cabinet.png | 720×300 | Speaker cabinet body | +| gfx-pedal-gate-body.png | 300×420 | Gate enclosure and EMPTY mounting wells | +| gfx-pedal-drive-body.png | 300×420 | Overdrive enclosure with EMPTY control and footswitch wells | +| gfx-knob.png | 120×120 | Independent rotary control image | +| gfx-switch-off.png | 200×74 | Fixed-housing OFF bitmap | +| gfx-switch-on.png | 200×74 | SAME housing and alpha shape, ON bitmap | +| gfx-button-off.png | 280×80 | Shared GUI button inactive | +| gfx-button-on.png | 280×80 | Shared GUI button selected, same frame | +| gfx-panel.png | 800×330 | Empty reusable GUI chassis/background | +| gfx-stomp-off.png | 110×110 | Independent pedal switch OFF | +| gfx-stomp-on.png | 110×110 | Same geometry pedal switch ON | + +**On/off anti-flicker is a hard build gate:** identical canvas; byte-identical full alpha channel; byte-identical RGB around the outer shell. Only the **internal thumb/LED/face** may change; `scripts/validate_guitar_fx_artist_source.mjs` executes at CMake configure and rejects mismatched exports before embedding. Toggle/press/hover never resizes controls; the JUCE LookAndFeel adds small dynamic visual feedback on the inset only. + +**Never bake parameters into bodies.** The bodies contain mechanical wells but no working knob, no ON/OFF position, no labels, and no active DSP indicators. One composited `juce::Slider` lives over each actual DSP knob, and one `juce::TextButton` lives over the pedal footswitch. Gate has three real controls (Threshold/Hold/Release); Drive currently has one real drive control; Amplifier has three (Gain/Tone/Master); Cabinet has no invented rotary control. + +## Packaging / clean-up boundary + +CMake builds deterministic original PNG fallbacks when `artist-source/` is absent and embeds only `design-references/guitar-fx/assets/gfx-*.png`. All prior `pedal-chorus.png`, `pedal-reverb.png`, `pedal-delay.png`, old baked `pedal-gate.png` / `pedal-overdrive.png`, and other concept PNGs remain for the archived design prototype but are **not shipped** into the native application. Do not delete assets used by the historical prototype or other applications. + +A photo-real package must be copied into the named `artist-source/` folder **and committed** before a release can claim that the generated photography-based artwork is included. A green build using only deterministic fallbacks is NOT proof the previous chat-generated photoreal source images were embedded. + +## Verification + +```bash +node scripts/build_guitar_fx_layered_assets.mjs +node --test tests/guitar_fx_assets_contract.test.mjs +node scripts/validate_guitar_fx_artist_source.mjs design-references/guitar-fx/artist-source +``` + +Then inspect a Windows JUCE screenshot for all four focuses, test independent knob rotation, ON/OFF toggle and hover/pressed states, and confirm Guitar FX remains in FX Picker. Real Hi-Z guitar/ASIO sound is a separate field acceptance. diff --git a/design-references/guitar-fx/artist-source/gfx-amp-head.png b/design-references/guitar-fx/artist-source/gfx-amp-head.png new file mode 100644 index 000000000..27f970ca4 Binary files /dev/null and b/design-references/guitar-fx/artist-source/gfx-amp-head.png differ diff --git a/design-references/guitar-fx/artist-source/gfx-button-off.png b/design-references/guitar-fx/artist-source/gfx-button-off.png new file mode 100644 index 000000000..a49b2243d Binary files /dev/null and b/design-references/guitar-fx/artist-source/gfx-button-off.png differ diff --git a/design-references/guitar-fx/artist-source/gfx-button-on.png b/design-references/guitar-fx/artist-source/gfx-button-on.png new file mode 100644 index 000000000..9d785f116 Binary files /dev/null and b/design-references/guitar-fx/artist-source/gfx-button-on.png differ diff --git a/design-references/guitar-fx/artist-source/gfx-cabinet.png b/design-references/guitar-fx/artist-source/gfx-cabinet.png new file mode 100644 index 000000000..e329ce096 Binary files /dev/null and b/design-references/guitar-fx/artist-source/gfx-cabinet.png differ diff --git a/design-references/guitar-fx/artist-source/gfx-knob.png b/design-references/guitar-fx/artist-source/gfx-knob.png new file mode 100644 index 000000000..8e16274d8 Binary files /dev/null and b/design-references/guitar-fx/artist-source/gfx-knob.png differ diff --git a/design-references/guitar-fx/artist-source/gfx-panel.png b/design-references/guitar-fx/artist-source/gfx-panel.png new file mode 100644 index 000000000..eaf3836f6 Binary files /dev/null and b/design-references/guitar-fx/artist-source/gfx-panel.png differ diff --git a/design-references/guitar-fx/artist-source/gfx-pedal-drive-body.png b/design-references/guitar-fx/artist-source/gfx-pedal-drive-body.png new file mode 100644 index 000000000..d2c86e36f Binary files /dev/null and b/design-references/guitar-fx/artist-source/gfx-pedal-drive-body.png differ diff --git a/design-references/guitar-fx/artist-source/gfx-pedal-gate-body.png b/design-references/guitar-fx/artist-source/gfx-pedal-gate-body.png new file mode 100644 index 000000000..b0c0a0f43 Binary files /dev/null and b/design-references/guitar-fx/artist-source/gfx-pedal-gate-body.png differ diff --git a/design-references/guitar-fx/artist-source/gfx-stomp-off.png b/design-references/guitar-fx/artist-source/gfx-stomp-off.png new file mode 100644 index 000000000..06a1b2fe6 Binary files /dev/null and b/design-references/guitar-fx/artist-source/gfx-stomp-off.png differ diff --git a/design-references/guitar-fx/artist-source/gfx-stomp-on.png b/design-references/guitar-fx/artist-source/gfx-stomp-on.png new file mode 100644 index 000000000..f31d7cb0e Binary files /dev/null and b/design-references/guitar-fx/artist-source/gfx-stomp-on.png differ diff --git a/design-references/guitar-fx/artist-source/gfx-switch-off.png b/design-references/guitar-fx/artist-source/gfx-switch-off.png new file mode 100644 index 000000000..225c57160 Binary files /dev/null and b/design-references/guitar-fx/artist-source/gfx-switch-off.png differ diff --git a/design-references/guitar-fx/artist-source/gfx-switch-on.png b/design-references/guitar-fx/artist-source/gfx-switch-on.png new file mode 100644 index 000000000..ec7f8bf64 Binary files /dev/null and b/design-references/guitar-fx/artist-source/gfx-switch-on.png differ diff --git a/docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md b/docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md new file mode 100644 index 000000000..fc17bc3c1 --- /dev/null +++ b/docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md @@ -0,0 +1,157 @@ +# 8D-SonKu — Architecture Requirements & Decisions (ARD) +Version: 0.1 / proposed engineering architecture / 2026-11-12 +Status: architecture design only, NOT implemented or physically audio-tested. +Repository audited: `masarray/arsonmix@1d84474661e1798b4a2f03bd8e6c9fbd7e1fb1fc`. +Guidance: root `AGENTS.md`, `docs/architecture/README.md`, `docs/architecture/FEATURE_EXTENSION_PLAYBOOK.md`. + +## A. Architecture invariants / avoid naive implementation +1. Reuse ONE existing JUCE AudioIODeviceCallback and authoritative ChannelId/EdgeId PCM graph. This FX is an `AudioProcessor`/lease, not a new device/monitor/mixer/transport/JS audio engine. +2. Build high-quality *true binaural rendering*, not a panning simulator. Spatial localization = direction-dependent L/R HRTF/HRIR (ITD, ILD, pinna/torso spectral cues); acoustics = source-dependent early reflections + diffuse late reverb; effective externalization must be listening-tested. +3. Separation of concerns: independent pure motion math; dataset/backend; HRTF renderer; distance/direct-room; JUCE adapter; native editor; host session/preset adapter. No new global FX framework or per-plugin `Main.cpp` switch. +4. CONTROL thread does lookup, file IO, HRTF resample/precompute, immutable trajectory compilation, graph creation and release, validation/serialization; RT callback consumes only ready bounded storage and atomic mailbox/snapshot. +5. Preserve session/FX lease ID/graph revision/device epoch, existing rack bypass and accepted ACK/readback. Never show success from browser intent alone. Preserve old graph on failed prepare. +6. Prototype third-party HRTF facilities with a **replaceable backend seam**, benchmark before choosing a shipping dependency. Do not ship a known-unlicensed HRTF dataset/BRIR. + +## B. Existing verified seams (live source) +| Existing owner | Correct 8D-SonKu integration | +| --- | --- | +| `src/NativeBuiltInFx.h` | One catalog entry `armix.builtin.8d-sonku.v1` with generic `prepareNativeBuiltInFx`, verified sample-rate/frame constraints. **Do not** edit Harmonice identity. | +| `engine/builtin_fx/BuiltInFxCatalog.h` | Optional canonical identity constant only; do not fork a second runtime registration registry. | +| `engine/builtin_fx/ChannelCompressorProcessor.h` etc. | Pattern for prepared `juce::AudioProcessor`, state validation, realtime control envelopes and metering. Not permission to copy DSP code or duplicate a transport. | +| `engine/core/LiveChannelFxGraph.h` / `DynamicChannelFxLeaseBank.h` | Reuse stable instances, move/reorder, prepared processing, bypass/PDC and retirement. | +| `engine/core/OrbitMotion.h`, `OrbitPhase.h`, `OrbitControlPolicy.h` | Existing pure vendor-VST parameter-orbit utilities: reuse conceptual phase/shape/test mathematics if suitable; **do not** treat VST-normalized positions as physical HRTF coordinates, or route through dearVR vendor parameter UI. | +| `src/NativeMixerSessionFxRestore.h`, `src/NativeMixerSessionStore.h` | Reuse generic native FX serialization and .smix roundtrip, schema/version validation. | +| `web/approved-native-bridge.js`, `web/approved-native-contract.js`, `site/preview-*/` assembled /preview/ | Native editor commands, accepted events and UI embedded in the one approved renderer. No second alternate GUI. | +| `tests/**`, `CMakeLists.txt` | Add targeted DSP/contract/native-host tests, not a duplicate full CI pipeline. | + +## C. Proposed modular source ownership — descriptive paths, NOT files already written +``` +engine/builtin_fx/sonku/ + SonKuTypes.h // bounded state v1, source IDs, typed params, no UI + SonKuMotion.h // sample-clock phase, circle/ellipse geometry, easing + SonKuPathCompiler.h // CONTROL-only compile of path to fixed arc-length LUT + SonKuHrtfBank.h // immutable prepared HRIRs, orientation/metadata, lifetime + SonKuSpatialRenderer.h // bounded 1 or 2 emitter binaural direct sound + SonKuDistance.h // attenuation, coloration, direct/reflection ratio + SonKuRoom.h // prepared early reflections + stereo FDN late reverb + SonKuCore.h // processor-owned state + subblock render orchestration +engine/builtin_fx/SonKuSpatialProcessor.h // JUCE native built-in FX adapter +tests/sonku_*_test.cpp // pure math, audio impulse, host/session +site/.../assets/mixer-native-sonku.js // integrated assembled GUI editor ONLY +docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md +docs/ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md +``` +Keep source count proportional to actual responsibilities: start with `SonKuMotion`, `SonKuSpatialRenderer`, `SonKuCore`, `SonKuSpatialProcessor`; split a file only when it has independently tested ownership. Avoid heavy template frameworks, abstract factories or duplicate plugin-host layers. + +## D. Signal flow / ownership +``` +Existing FX insert / accepted ChannelId graph + Stereo or Mono PCM + -> input policy (mono=one emitter; stereo=L/R virtual emitters) + -> sample-clock motion + source physical positions (no UI timer) + -> prepared HRTF direction-dependent L/R direct filters + -> distance gain/spectral shaping -> direct binaural ear sum + -> optional source-dependent early reflections (bounded delay taps) + -> optional shared stereo FDN / diffuse late tail + -> spatial wet / dry equal-loudness blend + output trim + -> normal channel FX rack/fader/WIRE/BUS/MAIN hardware outputs +``` +`SonKuCore` is exactly one internal processor graph under existing host. No new ASIO/WASAPI owner. Early reflections must be based on room source/listener geometry, not a stereo-delay trick erroneously branded as realistic 3D. + +## E. Coordinate and motion contract (unit correctness) +- Listener at origin, head fixed forward = +Y on top-down display; X positive right; Z positive up. Azimuth 0° FRONT, +90° RIGHT, ±180° REAR, -90° LEFT; positive azimuth = clockwise on the top-down graphic. +- For azimuth theta and radius r: `x=r*sin(theta)`, `y=r*cos(theta)`; `z=r*sin(elevation)` as appropriate when elevation is added. Treat physically meaningful meters separately from UI normalized radius. Avoid confusing legacy `OrbitMotionPoint.distance` normalized 0..1 VST parameter with meters. +- Two virtual objects for stereo: input L mapped to object L, input R mapped to object R with **linked** phase and user-defined angular spread by default; independent motion is optional later. One mono input maps to one emitter by default; never create two independent "speakers" from mono without explicit user enable. +- Sample-clock rotation: phase increments from the **number of rendered samples** and an explicit samples-per-revolution or tempo-linked beat count. Persist rotation state when stopping/starting according to documented pause/resume policy; modulo wrap is seamless. +- GUI head/source position is a low-rate non-authoritative snapshot. GUI render 30–60 FPS only for display; no JS setInterval audio steering. Drag requests are bounded and reconciled to native accepted state. +- Circle/ellipse mathematical evaluation is O(1); editable cubic path is compiled off-RT into bounded arc-length LUT (e.g. 1024 sample points; capacity/precision benchmarked) for approximately uniform audible velocity. Sample-clock phase indexing/interpolation O(1) in callback. +- Speed/radius/position/width changes are smoothed. Orbit shape switching uses clickless parameter morph or short position/filter crossfade, not an instantaneous HRTF impulse jump. + +## F. HRTF renderer design and algorithm decision +- Input: 1/2 mono source streams. Each prepared emitter produces **both left and right ear outputs** via direction-dependent HRIR and ITD; sum into stereo with calibrated gain and adequate headroom. Plain equal-power panning is permitted only as an explicitly labelled non-binaural diagnostic baseline. +- Use `SOFA SimpleFreeFieldHRIR` as interoperable dataset input. Validation, dataset version/attribution/redistribution permission and resampling happen before publication; missing/corrupt/unsupported SOFA fails closed to a known safe preset or rejects the new prepared instance, never parsing in callback. +- Backend decision **OPEN pending benchmark**: (A) Valve Steam Audio CPU binaural API with vetted thread/allocation/latency behavior and Apache-2.0 distribution, or (B) small deterministic native FIR/partitioned renderer driven by licensed SOFA HRIR and libmysofa (BSD-3-Clause) control-side loader. Do not commit to either from marketing alone. Benchmark direction interpolation, per-block cost, allocations and timbral artifacts before adopting. +- Sample-cost sanity: 2 sources x 2 ears x 128 FIR taps x 48,000 samples/sec = 24.576 million MAC/sec before interpolation/room/overheads. This arithmetic is an approximate *cost model*, not measured project performance. +- HRTF orientation interpolation: choose smoothly interpolated HRIR/ITD, not abrupt nearest-direction jumps. Evaluate minimum-phase and explicit ITD separation vs direct HRIR interpolation to reduce artifacts. Filter update at bounded audio subblock rate (candidate 16–64 samples), with time-domain crossfade/smoothing where needed, not reloading HRIR each audio sample. +- No HRTF dataset guarantees all users can localize front/back. Provide HRTF selection and listening calibration as a product path, rather than exaggerated fixed spectral EQ. Avoid the claim that a static generic HRTF alone will always externalize. + +## G. Acoustic space / room model +- Stage M1 has no room dependencies; truthful static HRTF must work first. M3 adds first-order shoebox/image-source reflections for limited virtual wall surfaces, using prepared delay lengths/gains/lowpass and direction-dependent early spatial cues. Parameter updates are staged and smoothed. +- One efficient **stereo shared FDN** reverb per FX instance; preallocated lines and diffusion/damping, no per-object long convolution tail by default. Keep time-varying early reflection contribution and late diffuse field separate. +- Head-relative source distance affects direct level, spectral/air cues where justified, and direct-to-reverberant ratio. Avoid pure exponential rolloff that only makes source quieter but never more external. +- `Room Mix=0` eliminates room components while preserving HRTF direct sound. Clear/retain reverb tail bypass behavior explicitly: preserve tail when power off only if host has a supported continuous-bypass contract; otherwise short fade to dry with no unbounded rendering. +- A premium measured long BRIR convolution mode is P2/offline until CPU, latency/PDC, license and user outcome justify it. No realtime ray tracing in initial shipping engine. + +## H. Realtime and lifecycle rules +- CONTROL owns `prepareToPlay`, process format validation, preallocated working buffers, HRTF dataset load/resample, path LUT compilation, preset state parse/migration, deferred destruction and editor lifetime. RT processing is fixed-size, exception-avoiding and free of memory allocations, filesystem, locks, logging, network, JS and dynamic HRTF object creation. +- Rely on existing `RealtimeNativeFxControl` / bounded queues and generic FX lease/revision fences. No new global queue infrastructure unless existing API cannot satisfy bounded state. Parameter burst must coalesce/reject safely and never corrupt accepted control state. +- Publish changed heavy objects as immutable prepared structures at safe graph/FX control boundary; old object lifetime must outlive callback readers. No destroying old HRTF/FDN in callback. Fast continuous parameters should use the existing per-processor realtime control route, not rebuild FX graph on every knob tick. +- Set finite parameter ranges; clamp only well-defined input controls; invalid NaN/Inf, malformed number, impossible size/rate, stale slot/epoch, incompatible mono/stereo and absent HRTF produce explicit negative ACK or deterministic fallback. Never silently reinterpret a rejected request as completed. +- FX process: handle arbitrary block segmentation up to host prepared maximum, silence, 0 frames if called, mono input or stereo channel, denormal flush, tail reset, rapid wet/dry, pause/restart, sample-rate reprepare. Processor publishes true `getLatencySamples`; if host PDC insufficient, disallow selected heavy quality mode until safe. +- Proper host rack bypass returns dry under existing contract. In a spatial mix, doubling dry+binaural may cause comb filtering; use a perceptually appropriate crossfade and test both mono fold and peaks. +- On device loss, logical state survives, no "Monitor Off" gate introduced by the effect. Reprepare once for new epoch. Never bind to physical pins or create a separate device callback. + +## I. Stable model and serialization +```text +SonKuStateV1: + catalogId="armix.builtin.8d-sonku.v1"; schemaVersion=1 + enabled; spatialMix; outputTrimDb + inputMode {autoMono,linkedStereo,independentStereo} + positionA/B {azimuthDeg,elevationDeg,distanceMeters} + motion {staticOrOrbit,shape,phase,periodSeconds,direction,startAngle,spreadDeg} + shape {circleRadius,ellipseAxes,advancedControlPoints[bounded]} + hrtf {profileId,qualityMode} + room {presetId,earlyLevel,lateLevel,decaySeconds,roomMix} +``` +Exact accepted native state serialization uses bounded versioned binary/typed codec, with finite/range validation and deterministic default migration. Persist pose/path and source identities, **not** executable code, HRTF sample arrays, detector history, live device identity or transient GUI pointer state. `.smix` retains effect state using generic existing FX restore; separate `.armixfx` user presets use the shared future preset library, not localStorage or plugin-owned session files. Stable FX instance identity follows move/reorder; no new ChannelId. +Acceptance = validated control ACK + accepted DSP readback for installed graph; logical-only status does not claim PCM. No GUI-only simulated audio engine. + +## J. Testing matrix (targeted and low-waste) +| Test layer | Minimum contract | +| --- | --- | +| Pure motion tests | 0/90/180/-90 direction, CW/CCW, wrap continuity, phase partition independence, varied block sizes, ellipse and arbitrary path arc-length consistency. | +| HRTF dataset tests | SOFA orientation, sample rate resample, stereo ear ordering, 0 vs 180 HRIR not swapped, front/rear directional spectral distinction, invalid/out-of-license dataset path. | +| DSP PCM tests | Static impulse per cardinal direction, ITD/ILD bounded, no NaN/denormal/clip on test fixtures, dry bypass, wet gain, silent input and arbitrary chunk sizes. | +| Motion audio tests | Direction reversal, stop/resume, tempo change, shape edit, rapid phase 0/1 crossing, front-rear interpolation without clicks. | +| Room tests | Early reflection delays/gains respond to source position; room dry, tail behavior, FDN stability/decay, no runaway feedback; source near/far clarity. | +| Host integration | Real native insert on CH05 and BUS, rack bypass, other FX order, source-only/WIRE, .smix restore, FX move identity, device epoch/rebind, negative ACK state unchanged. | +| UX | Approved /preview/ editor screenshot at tested sizes; drag/click/keyboard hit zones; accepted readback and failure; no Chrome context menu or separate preview. | +| Performance | Bench p50/p95/p99 on documented hardware at 44.1/48/96k, 64–512 frames, 1/2/4 FX instances, allocation observer, actual ASIO XRUN/crackle FAT. | +| Perceptual | Volume-matched blind 4-direction localization, confusion matrix, externalization/distance/timbre rating on diverse headphones/listeners, generic vs selected HRTF. | + +A synthetic PCM green test is not a real listening PASS. Keep docs-only PR without expensive CI; M1 native code gets fast tests then one exact-SHA native or FAT lane where justified. + +## K. Design decision log / unresolved evidence +| Decision | State | Exit evidence | +| --- | --- | --- | +| Single existing native JUCE FX ownership | FIXED | Existing source and architecture governance. | +| Physical azimuth and 2-emitter semantic model | PROPOSED | DSP phase/IR tests and usability review. | +| Steam Audio CPU backend vs SOFA-native FIR | OPEN | Comparable CPU, fidelity, latency, license, callback safety benchmarks on reference rig. | +| HRTF dataset packaging | BLOCKED on license | Individual dataset license, redistribution, attribution and version pin. Source-code license does not license dataset. | +| Room FDN and early reflection algorithm | PROPOSED | Offline impulse/perceptual A/B and CPU profile. | +| Editor graphical path precision and gesture contract | P1/P2 staged | Real browser/native integration, pointer screenshots and accepted event tests. | +| Performance threshold / sample-rate range | PROVISIONAL | Exact-SHA compiled native CPU and physical hardware evidence. | +| Absolute claim of 3D externalization quality | NOT PROVEN | Multiple-listener headphone tests meeting PRD gates. | + +## L. First implementation PR plan (after R0 documents) +One coherent M1 PR should add: minimal pure `SonKuMotion`, real prepared directional HRTF renderer, native `SonKuSpatialProcessor`, single `NativeBuiltInFx.h` registry entry, focused DSP PCM/host bypass/restore tests; touch approved GUI only when first audible insert is actually wired. Do not add CMake build cost, duplicate backends, empty scaffolding classes, fake front/back loudness or a second callback. Any feature not audible/testable stays out of M1. + +See [PRD](PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md), [research](RESEARCH_8D_SONKU_SPATIAL_AUDIO_20261112.md). + +## Top-down visual orientation (2026-11-13 owner-approved) +The new photographed/illustrated blue listener-bust image is viewed from above with the person's face pointing to the BOTTOM of the SVG stage. Do **not** change DSP azimuth signs to match screen coordinates. Visual screen coordinates are X right, Y down, and **perspective-ellipse (presentation-only)** projection is `screenX = centerX - rx * sin(azimuth)`, `screenY = centerY + ry * cos(azimuth)`, with current stage `centerX=200`, `centerY=174`, `rx=148`, `ry=83`. Acoustic FRONT=0° appears bottom, REAR=180° appears top, RIGHT=+90° appears screen-left, LEFT=-90° appears screen-right (anatomical right/left looking over the listener, not screen-side shorthand). Pointer inverse is `atan2((centerX - x)/rx, (y - centerY)/ry)` and all changes still flow through the installed native FX ACK/readback; asset is only one passive GUI raster. The source PNG is `site/preview-v2/assets/sonku-listener-top.png` and is copied unchanged into the **one approved compiled /preview/** and native JUCE binary resource bundle. The asset is a preoptimized transparent 128px indexed PNG (8162 bytes; copy verbatim, no runtime SVG filters beyond the scoped drop-shadow). No DSP, HRTF dataset, routing, or extra HTML renderer changes. + +## 2026-11-13 — locked premium spatial editor geometry and control contract (M4 UX) +This record supersedes the earlier **round/circular stage UI** and radial 2D marker presentation. It does **not** alter audio parameter semantics, HRTF filter response, or stereo PCM channel assignment. + +- **Unified perspective**: one perspective-flattened elliptical orbit is split into far (REAR) and near (FRONT) SVG paths. The far dashed arc must be painted **before** the passive blue listener PNG, and the near highlighted arc **after** the PNG, making the ring appear to pass in front of the lower bust. This is painter occlusion, not 3D ray tracing. Original source image remains `site/preview-v2/assets/sonku-listener-top.png`; no copyrighted product asset cloning. +- **True acoustic coordinates**: 0° front, +90° listener right / screen left, 180° rear, -90° listener left / screen right. The ellipse is a **visual projection only**. The native HRIR and `SonKuSpatialCore` use the same, unchanged angle. Do not apply the ellipse's `rx/ry` ratio inside audio convolution. +- **Two visible independent source monitors**: at zero (or near-zero) stereo spread, both emitters share the same true acoustic anchor. The GUI draws *two studio monitor glyphs* with a symmetric, continuous tangential offset sufficient to remain separately clickable and links them to the true anchor with subtle tethers. Store actual anchor separately from displayed coordinates, and always pass the actual azimuth to native SPSC settings. On spread >0 markers return smoothly toward true positions; **never silently alter native spread** just to separate SVG icons. +- **Control surface**: dark satin/brushed plugin-editor finish; compact metal-look four rotary controls REVOLUTION/SPREAD/SPATIAL MIX/OUTPUT TRIM. Keep native HTML range inputs for keyboard and assistive access. UI pointer vertical drag updates only draft value; exactly ONE native edit request is sent on release, ACK/readback authority unchanged. Double click returns to the documented default. Never let the pointer-only visual dial claim applied DSP. +- **No extra renderer or CSS owner**: add to existing one /preview/ editor and existing `mixer-fx-rack.css`, maintaining exactly 18 CSS owner links. No WebAudio, DSP JS clone, extra callback or CPU-intensive continuous 3D scene. +- **Verification evidence**: Chromium assembled native GUI two viewport screenshots, actual FX picker insertion and ACK/readback, four acoustic directions, front/rear painter order, both monitors visible at 0° spread, real mouse drag to FRONT, rotary drag with one typed native request. Exact SHA `4652a744ab4ae01b1ceca58bb6c3d7e372eb420a`, [UI run](https://github.com/masarray/arsonmix/actions/runs/43342451656), [two screenshots](https://github.com/masarray/arsonmix/actions/runs/43342451656/artifacts/13999089726). +- **Release gate**: browser FAT uses simulated JUCE events. It is not physical binaural localization or installed Windows/ASIO FAT, and the PR must be reconciled with advancing `main` before any public release. + + +## 2026-11-13 — V2 spatial externalization architecture +See docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md. Experimental room processing is opt-in and OFF in native JUCE until qualified with headphone A/B. Fixed bounded image-source early reflections retain the same single PCM authority; future ITD-aligned HRIR implementation is a separate stage. diff --git a/docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md b/docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md new file mode 100644 index 000000000..c69633c38 --- /dev/null +++ b/docs/PRD_8D_SONKU_SPATIAL_AUDIO_20261112.md @@ -0,0 +1,106 @@ +# 8D-SonKu — Product Requirements Document (PRD) +Version: 0.1 / research and implementation-ready requirements / 2026-11-12 +Product: ArSonMix internal built-in FX. Status: PROPOSED; NOT implemented, acoustically verified, or field-qualified. +Owner intent: convincing **front, rear, left, right, distance, externalization and moving 360-degree binaural sonic space**, not a stereo auto-pan illusion. +Naming boundary: **Harmonice remains the independent Vocal Harmony effect**. 8D-SonKu is its own brand, catalog ID, DSP, state and editor. + +## 1. Product outcome and truth +An operator inserts 8D-SonKu on an ordinary mono or stereo mixer channel, selects a spatial movement preset, hears convincing binaural sound external to the head over headphones, sees a top-down listener/head and two moving source icons when stereo is selected, changes the orbit path by dragging it, controls speed and direction, and optionally selects a virtual acoustic room. All audible effects must run in the **ONE** native ArSonMix JUCE PCM callback/accepted FX graph; browser /preview/ is only presentation. Do not claim 3D realism merely because speaker dots move. Front/back discrimination, smooth motion, distance and listening tests are gates. + +## 2. Target users / jobs to be done +- Singer/performer: one-click spatial vocal motion without opening a routing wizard or losing live monitoring. +- Music producer / stream creator: exciting stereo or mono sound motion at a controlled pace, in a selected acoustic room. +- Sound designer: freeform positioning, path shape, movement automation and repeatable saved presets. +- Advanced mixer operator: reliable CPU load, true rack bypass, state recall, sample-accurate timeline-based motion where provided, mono-compatible fallback. + +## 3. Primary journey (P0) +1. Select existing CH or BUS -> FX Rack -> add "8D-SonKu" from verified native built-in FX picker. +2. Processor is prepared on CONTROL side, installed via existing FX lease. No device restart, special ARM/Monitor action, or second audio output. +3. Open the FX editor: head+headphones centered in large compact top-down visual; FRONT above, REAR below, LEFT and RIGHT explicitly marked. Stereo: independent L/R source glyphs, not physical speakers. Mono: one source glyph, or linked duplicated glyphs only when explicitly enabled. +4. Choose `Circle 360°` -> `Play motion`. Hear movement front -> right -> rear -> left, not just left/right loudness. +5. Drag source to change start location; drag orbit handles to adjust radius/ellipse; adjust revolution time, clockwise/counterclockwise, source spread, distance and wet amount. Editable advanced path is phase P2. +6. Choose virtual space (e.g. Dry/Open, Small Studio, Live Room, Large Hall), independently adjusting early reflections and late reverb via a simple Room Mix. Default room must enhance localization without drowning direct signal. +7. Toggle rack power/bypass, save/open .smix, reorder FX, switch input/device and reopen: same accepted state, no unsolicited route/graph reset. Audio is truthful only when physical route is installed. + +## 4. Scope and priority +| ID | Priority | Requirement / operator-visible acceptance | +| --- | --- | --- | +| PR-01 | P0 | Verified native built-in FX picker entry `8D-SonKu`, stable `armix.builtin.8d-sonku.v1` identity, independent of Harmonice. | +| PR-02 | P0 | Genuine HRTF binaural direct sound for mono input and two virtual emitters for stereo input, stereo output to headphones. No mere equal-power pan marketed as 3D. | +| PR-03 | P0 | Clear independent FRONT(0), RIGHT(+90), REAR(180), LEFT(-90) static positions; direct positioning works when orbit stopped. | +| PR-04 | P0 | Orbit phase advances from the **audio sample clock**, not browser animation frames. Adjustable period, CW/CCW, start angle and stable pause/resume. | +| PR-05 | P0 | Compact top-down GUI shows listener/head with headphones, two stereo source glyphs following audible phase, draggable start points, circle radius/ellipse handles. GUI never drives PCM timing. | +| PR-06 | P0 | Smoothed position/HRTF/distance changes: no audible zipper, clicks or sudden dry/wet discontinuities; bypass remains safe with room tail policy documented. | +| PR-07 | P0 | Dry/direct vs spatial wet and output trim, conservative gain/headroom; quality checked on actual headphones. Mono and silence behave deterministically. | +| PR-08 | P0 | Native prepare, editable parameter ACK/readback, .smix roundtrip, FX bypass, move/reorder, graph revision/device epoch protection. No new callback or second master. | +| PR-09 | P0 | Headphone playback is clearly communicated. Speaker listening is not promised to provide spatial externalization. No false "headphone detected" claim. | +| PR-10 | P1 | Preset acoustic spaces: Dry/Open, Small Studio, Live Room, Hall; moving-source-aware early reflections, shared algorithmic diffuse reverb and controllable Room Mix. Original, not copied dearVR presets/IRs. | +| PR-11 | P1 | Subjective HRTF audition/calibration: front/rear/left/right examples and a small verified/licensed HRTF profile set with user choice; no assumption one generic HRTF fits everyone. | +| PR-12 | P1 | MIDI/host tempo sync where a reliable timeline exists; otherwise manual seconds-per-revolution remains fully functional. No inferred/fake BPM or GUI timer as audio clock. | +| PR-13 | P1 | Linked stereo orbit as default; independent per-emitter motion as an advanced choice. Preserve L/R source identity, controllable spread and downmix compatibility. | +| PR-14 | P2 | User-editable freeform closed Bézier path (bounded control points), normalized arc-length traversal and undo/reset; saved in plugin state. | +| PR-15 | P2 | Elevation/vertical orbit and optional genuine listener head tracking, only after basic horizontal externalization proves successful. | +| PR-16 | P2 | Offline high-quality HRTF/room rendering and user preset integration through shared native built-in FX preset service when it is production-ready. | + +### Default settings (candidate; tuning required) +- Stereo Linked Orbit / Circle; 12 s per revolution; clockwise; headphone output; room Small Studio with restrained room mix. +- Source separation adjustable; center-front reference is azimuth 0 deg. Direct signal has priority over reflections/reverb. No hidden automatic head movement, no listener-mode auto-switch on device selection. +- `Dry` preset must actually disable room reflections/reverb while retaining directional HRTF; FX bypass must actually return unprocessed input through the host's normal bypass contract. +- All candidate defaults may change after loudness-matched listening validation, not through arbitrary visual tuning. + +## 5. UX contract (compact and premium, no bulky cards) +- Main editor: restrained header with name / power / preset, **dominant circular trajectory stage**, head illustration, two small luminous L/R source glyphs, directional marks. Distinguish source positions and listener orientation; do not display two "hardware output speakers". +- Right/bottom secondary controls: `Motion: [Static | Orbit]`, `Shape: Circle / Ellipse`, `Speed: seconds per revolution`, `Direction: CW/CCW`, `Spread`, `Distance`, `Spatial Mix`, `Room preset`, `Room Mix`. Show only relevant fields. Use shared approved UI tokens, compact typography and appropriate control affordances. +- Dragging trajectory or source shows preview locally, then sends a bounded, validated native intent; accepted state/graph drives authoritative visible controls. Pending/rejected actions must be distinguishable without false audio claims. +- No default Chrome context menu, no new topbar mode, no new public /preview-v2/ product page. Exact native assembled /preview/ remains authoritative. +- Keyboard: pointer-free selection, arrow nudge, Enter accept, Escape cancel, Reset path; touch targets tested for mouse/touch and small windows. +- Static mode is first-class: pure front/rear placement must not require motion playing. Make A/B evaluation possible. + +## 6. Nonfunctional requirements (measured, not assumed) +- Realtime: zero heap allocation, file IO, blocking lock, plugin scanning, HRTF parsing or GUI/JS communication inside PCM callback. Prepare on control side. No per-frame browser timer driving sound. +- Audio format: initial 44.1/48/96 kHz at 64/128/256/512 frames; later 32..192 kHz subject to actual DSP test. Unsupported formats reject **before** publication and preserve previously accepted graph. +- Deadline design budget at 48k/128 (2.667 ms callback period): **candidate** one instance 99th-percentile DSP <= 10% of block period on a published reference CPU, and 4 instances combined <= 30%. Update limits after genuine profiling, SIMD and device tests; percentages are engineering goals, not measured results. +- No unreported lookahead or unexpected host latency. If selected renderer incurs algorithmic latency, report and compensate via existing native PDC or reject until safe. Do not silently claim "zero latency". +- Deterministic offline replay for fixed rate/path/seed; callback partition invariance; finite outputs under silence, full-scale, denormals, corrupt/rejected state, repeated device reprepare and sample-rate changes. +- Explicit user-level latency, CPU quality and wet gain behavior; preserve independent ASIO primary / secondary stream bridge; do not alter device manager for this FX. + +## 7. Perceptual release gates +- Objective: compare rendered HRTF/BRIR IRs, ITD/ILD and spectral cues, front-vs-rear distinctness, filter transitions, delay continuity, loudness and clipping against ground-truth target/known datasets. +- Blind headphone listening: static positions front/rear/left/right; randomized order and matched volume on multiple real listeners, multiple headphone models, both generic and selected HRTF. Capture confusion matrix (especially front/rear), perceived externalization and distance (1–5), tone coloration and preference. +- Candidate target **after HRTF selection**: >=75% correct front-vs-rear discrimination across eligible test listeners and median >=4/5 for externalization; report participant count, confidence interval and individual failures. This is an aspirational gate and may need revision; never report it as achieved without listening data. +- Motion: sound follows 360-degree path in listening test; no perceived discontinuities at angle wrap, ellipse extrema, direction reversal or period changes. Mono-fold and bypass A/B must not create destructive artifacts. +- Tests don't certify physical ASIO FAT. Release needs measured callback p95/p99, Xruns/crackles, device reconnect and headphone listening evidence. + +## 8. Product boundaries / anti-requirements +No dearVR binary/source/reverb preset copying, unlicensed HRTF dataset distribution, false Dolby Atmos claim, full 3D ray-traced room by default, second JUCE AudioIODeviceCallback, new routing gate, automatic mic hardware rebind, hidden monitor switch, AI model, GPU dependency, speculative "all listeners" perfection, or replacing existing Harmonice Vocal Harmony. + +## 9. Delivery milestones +- **R0 (this document):** verified references, PRD, ARD, repository seam, risks, performance and perceptual gates. **No claim of audible implementation.** +- **M1:** real 4-direction static two-emitter HRTF PCM core + native built-in insert, prepared state/latency/bypass, synthetic impulse and callback stress tests. Hardware/device unchanged. +- **M2:** phase-clock 360° linked orbit, circle/ellipse geometry, host parameter control, deterministic offline A/B PCM and static/moving audio fixtures. +- **M3:** original early reflections + shared FDN room presets, self-consistent distance, filter smoothing, loudness matching and real headphones front/back qualification. +- **M4:** native approved /preview/ editor + drag path UX, accepted ACK/readback, session restore, responsive screenshot/gesture qualification. +- **M5:** HRTF selection/calibration, independent stereo paths and advanced paths if proven useful, benchmark/tune CPU, integrated selective native/GUI CI and independent physical ASIO FAT. +- One scoped PR per meaningful *working* vertical milestone where practical. Docs-only change gets diff/references audit, no Windows CI dispatch. + +## 10. Acceptance for first audible milestone (M1) +1. Insert native 8D-SonKu on CH05 -> FRONT input is processed to an actual stereo output path with measurable HRTF left/right filters, normal channel route and monitoring untouched. +2. 0/90/180/270 azimuth outputs are distinguishable in generated PCM/IR and finite; input silence remains silence, mono and stereo semantics are explicit. +3. Rack OFF produces tested dry behavior with bounded transition; restart and .smix restore retain settings or fail closed with no corrupted graph. +4. Deterministic callback tests at varied frames; no heap allocation/blocking in processBlock. +5. **No "3D verified" badge until blind headphone front/rear listening succeeds.** + +See: [ARD](ARD_8D_SONKU_BINAURAL_ENGINE_20261112.md), [research evidence](RESEARCH_8D_SONKU_SPATIAL_AUDIO_20261112.md), and existing [feature playbook](architecture/FEATURE_EXTENSION_PLAYBOOK.md). + +## 2026-11-13 — verified spatial UX acceptance refinements +For the owner's approved top-side-head PNG, the plugin shall present an **elliptical 3D-implied orbital plane** rather than a 2D circle. The rear orbit must visually pass **behind** the head, and the foreground orbit must pass **in front of** the lower bust. This is a UI projection, **not** an audio-path or 8-channel expansion. + +Both L and R studio monitor speakers must remain separately visible and individually interactive even when **Stereo Spread = 0°**. If acoustic positions coincide, graphical disambiguation must be clearly presentation-only; their identical native azimuths and original channel routing remain unchanged. FRONT remains the bottom of the stage; anatomical RIGHT is screen-left, anatomical LEFT screen-right. + +The editor must feel like a compact hardware-grade audio plugin, with tactile rotary controls and clear numeric readouts, not large web-style cards or anonymous browser sliders. Rotary pointer gestures must be bounded and single-commit; keyboard focus, range semantics and double-click default restoration remain accessible. Do not imitate or redistribute commercial plugin skins. + +Acceptance evidence on the real compiled native HTML bundle must cover correct Z-order, actual PNG load, two separately visible monitors at 0° spread, correct four-direction mapping, mouse drag to FRONT, knob edit single native queue/ACK and desktop/narrow screenshots. Do not translate GUI PASS into a claim of verified binaural headphone localization. + + +## 2026-11-13 — perceptual acceptance and UX guardrails +User reports correct 8/8 blind positions and 4/4 known, but insufficient FRONT/REAR distance and uneven perceived motion. Preserve the correct azimuth signs and build same-input, level-checked original-vs-V2 headphone WAVs first. No extra controls or labels before sound is validated. A future SPACE knob must be compact, discoverable and backed by native typed ACK/readback and compatible session migration; default must remain user-test-proven rather than arbitrary reverb. diff --git a/docs/RESEARCH_8D_SONKU_SPATIAL_AUDIO_20261112.md b/docs/RESEARCH_8D_SONKU_SPATIAL_AUDIO_20261112.md new file mode 100644 index 000000000..4c454c128 --- /dev/null +++ b/docs/RESEARCH_8D_SONKU_SPATIAL_AUDIO_20261112.md @@ -0,0 +1,62 @@ +# 8D-SonKu — Technical & Perceptual Research Evidence +Date: 2026-11-12. Status: desktop research, not first-hand FFT/CPU/ASIO/listener evidence. Scope: lawful independent internal FX, not copying dearVR code/IRs. + +## Sources and what they do / do not prove +1. **dearVR PRO 2 official manual (Jan 2024)**: https://files.plugin-alliance.com/products/dearvr-pro-2/dearvr-pro-2_manual.pdf + - Chapters 1–3 identify HRTF binaural directions, distance, coordinate input, early reflections with source position, late reverberation and 46 virtual acoustic presets. Product also admits front/back confusion and importance of head motion. + - **Implication**: reference UX and acoustic *requirements*, not a license or recipe to replicate proprietary algorithms, graphics or impulse responses. +2. **Steam Audio SDK C API guide and HRTF**: https://valvesoftware.github.io/steam-audio/doc/capi/guide.html ; https://valvesoftware.github.io/steam-audio/doc/capi/hrtf.html ; https://github.com/ValveSoftware/steam-audio + - HRTF is a direction-dependent pair of L/R filters. Bilinear directional interpolation is smoother than nearest (at higher cost). Expensive HRTF construction must happen outside audio thread. Reflections can be much heavier. Open source Apache-2.0 code, source distributions/NOTICE obligations to review. + - **Implication**: engineering reference and possible tested backend; NOT proof its runtime is allocation-free under ArSonMix callback or compatible with every supported small ASIO buffer. +3. **SOFA / AES69**: https://www.sofacoustics.org/ ; https://www.sofacoustics.org/mediawiki/index.php/SimpleFreeFieldHRIR + - Standard interoperability format for HRTF and spatial room IR; orientation, coordinates and receiver ordering are defined by convention. + - **Implication**: establish data contract, reject unsupported data and explicitly check dataset redistribution license before bundling. +4. **libmysofa**: https://github.com/hoene/libmysofa + - Provides C SOFA file reading/resampling/interpolation tools, code under BSD-3-Clause (with third-party/component and dataset license review). + - **Implication**: useful OFF-RT dataset reader, not a complete optimized spatial/room renderer. +5. **Auditory localization practical review (2024)**: https://www.frontiersin.org/journals/psychology/articles/10.3389/fpsyg.2024.1408073/full + - Generic/non-individualized HRTFs commonly produce front/back confusion; reverberation sometimes improves localization but findings vary. + - **Implication**: cannot market front/back realism as universal or solve it solely by adding more reverb. +6. **Frontal binaural externalization study (Aug 2026)**: https://pmc.ncbi.nlm.nih.gov/articles/PMC13451706/ + - Reports improvements in externalization via level and strategic early-reflection adjustment of non-individualized binaural room IRs. + - **Implication**: source-dependent early reflections/direct-to-reverb relationship should be evaluated with blinded listening, not only acoustic numerics. +7. **2025 room-based binaural conference study**: https://pub.dega-akustik.de/DAS-DAGA_2025/files/upload/paper/397.pdf + - Discusses plausible binaural room rendering from direct sound, limited early reflections and common late reverb. Full ray tracing is not an initial requirement. + - **Implication**: prototype a bounded hybrid acoustic room without complex real-time geometry ray tracing. + +## Evidence weighting / developer decision +- HIGH confidence: HRTF binaural left/right processing is needed for positional cues; moving HRTF should use smooth interpolation; sample-domain motion must be audio-clock-based; real acoustic reflections matter to externalization; native callback ownership follows one existing JUCE graph. +- MEDIUM confidence: two short-HRIR emitter paths + bounded early reflections + one FDN can achieve desirable CPU efficiency; requires prototype benchmarks and psychoacoustic evaluation. +- NOT ESTABLISHED: 8D-SonKu front-back headphone discrimination quality, CPU and latency on user's rig, shipped dataset license, relative quality vs dearVR, HRTF profile that fits all listeners. + +## Early technical trade-offs to measure +| Candidate | Why consider | Risk / experiment | +| --- | --- | --- | +| Steam Audio CPU HRTF backend | Mature direction-dependent engine, documented interpolation, supported SOFA | Native dependency packaging, callback behavior at 64/128 frames, cost with 2 emitters; benchmark and license inventory. | +| Native FIR/FFT backend + libmysofa control loader | Precise fixed-size RT contract, full ownership, little per-plugin binary weight | Needs rigorously tested orientation/delay/interpolation, spectral coloration and front/back listening. | +| Full room ray tracing | Rich physical scene potential | Not justified for static compact room presets; CPU, geometry tooling and render cost excessive for initial internal FX. | +| First-order reflections + FDN | Bounded CPU and sufficient initial room plausibility candidate | Need physically credible delay/direction/gain and real externalization verification. | + +## Required benchmark / audio lab protocol +- Fix auditable sample files: impulses/noise/voice/music stem, mono and stereo, seeded deterministic motion; record reference input/processing gain, profile and filter lengths. +- Run same 4-direction and rotating trajectory through both candidate HRTF renderers; compare transfer IRs, ITD, spectral errors, CPU p99, quality at buffer 64/128/256, at 44.1/48/96 kHz. Verify callbacks don't allocate. +- Choose one initially verified, **individually redistributable** HRTF dataset; document version, listener/ear orientation, source elevation coverage, SHA256, license/attribution. +- Blind headphone listening test includes multiple HRTF profiles and several headphone/listener combinations, not just developer's own ears. Record front/rear confusion, externalization, distance, timbral coloration, clicks and preference; compare with normal stereo pan as baseline. +- Avoid misleading use of the term "8D": technical output remains **2-channel binaural** with a dynamic 3D sound field, not 8 physical audio channels. + +## Repo-specific verified orientation +- `src/NativeBuiltInFx.h` registers built-in processors independently: Parametric EQ, Compressor, Harmonice, Vocal Throw. +- `engine/core/OrbitMotion.h` is vendor-VST normalized orbit geometry, **not** the native HRIR spatializer and **not** physical-meter mapping. +- `engine/core/LiveChannelFxGraph.h` reuses processor instances across mixer graph revisions and does not require duplicating a JUCE callback. +- `docs/architecture/FEATURE_EXTENSION_PLAYBOOK.md` describes narrow built-in FX path, typed control, verified native insert, session state, bounded CI. +- No `8D-SonKu` implementation was found in default-branch repository code search at the above audit checkpoint; this is not a guarantee that future PRs won't add it. + +## Design recommendation +R0: publish PRD and ARD (this branch). M1: implement true 4-direction native HRTF core with one stable insert identity, PCM tests and safe bypass. M2: add sample-driven orbit. M3: real room. M4: premium path editor, calibration. Gate perfection claims on measured listening evidence. + +## UI references audited 2026-11-13 (form principles only) +- [Waves Nx Virtual Mix Room user guide](https://assets.wavescdn.com/pdf/plugins/nx.pdf): a human-head-centric visual with speaker icons makes orientation and left/right scene intent recognizable. Adapt **human + monitors**, not Waves' copyrighted artwork or skin. +- [Sound Particles Energy Panner 2](https://soundparticles.com/products/energypanner/overview/): the moving-source visualization is the main interaction canvas; source paths, controls and stereo distribution are visually connected. Adapt **one central spatial display** and visible source markers. +- [dearVR PRO 2](https://spaes.org/dearVR-PRO-2): direct graphical XYZ positioning illustrates why direction should be interactive rather than a hidden numerical parameter. 8D-SonKu M1 stays horizontal 0° elevation; do not advertise full XYZ elevation or personalized distance room simulation absent DSP. + +The adapted user experience is **not** based on reverse-engineering any proprietary plugin GUI. Use the already-owner-approved blue bust asset, original SVG perspective ellipse, original mini studio-monitor vector controls and native JUCE/HTML range inputs. Preserve acoustic coordinate signs and distinguish display separation from true source azimuth. See the M4 contract in the ARD and PRD. diff --git a/docs/SONKU_M4_NATIVE_SPACE_RELEASE_CANDIDATE_20261113.md b/docs/SONKU_M4_NATIVE_SPACE_RELEASE_CANDIDATE_20261113.md new file mode 100644 index 000000000..30812dd94 --- /dev/null +++ b/docs/SONKU_M4_NATIVE_SPACE_RELEASE_CANDIDATE_20261113.md @@ -0,0 +1,71 @@ +# SonKu M4 — Native SPACE / musical ambience release candidate +2026-11-13 | Draft stacked on #643 → #629 → #606 | NOT public release + +## Why this is a vertical product slice +Operator opens **8D-SonKu** from the real FX rack and selects OFF / SQUARE / +CHAMBER / LARGE. Two small sliders control source distance and musical +AMBIENCE. A single `nativeSonKuSet` message flows through the existing +device-epoch, graph-revision, exact ChannelId, instance lease, native queue, +JUCE processing callback and completion. The GUI only displays APPLIED after +matching callback ACK and accepted DSP readback. No WebAudio, browser PCM, +fake owner or duplicated audio callback. + +Room map: +- OFF: original direct KEMAR HRIR; no ER or late FDN work, v1-compatible. +- SQUARE: 7.2 × 7.2 m, max radius 3.1 m, short Studio Glue decay ~0.78 s. +- CHAMBER: 14.4 × 14.4 m, max radius 6.7 m, Airy decay ~1.28 s. +- LARGE: 28.8 × 28.8 m, max radius 10 m, restrained decay ~2.05 s. +RoomAmount is fixed to the previously tested 0.55 when user first enables +a scene. For each scene, the direct path uses 1.6 / sourceDistance pressure, +the eight first-order wall paths use 1.6 / reflectedPath pressure, and the +diffuse tail is wet-only. The exact approved HRIR azimuth and orbit geometry +are unchanged. + +## Realtime invariants +- All 8× per-line FDN feedback gains and damping coefficients for these + presets are computed on `prepare()` and selected without exp(), new/delete, + locks, device restart, or blocking calls in the callback. +- Coefficients and wet levels slew on the sample clock; existing ER fractional + delays and gains slew too, with geometry recalculated only every 64 samples. +- Reenable after disabled room uses a validity horizon on the existing fixed + 8192-sample ER rings; reenable on FDN uses a horizon on the existing 4096- + frame rings. No ~64/128 KiB buffer clears in a live edit. +- FX graph owns bypass/retire/reorder/routing; SonKu never installs its own + audio device or hidden monitoring gate. +- Multiple instances have independent fixed memory; no static mutable DSP. + +## Persistence and backward compatibility +`SonKuSpatialProcessor` serializes SONK version 2, exactly 46 bytes with +old 30-byte v1 restore supported. New state carries `spacePreset`, +`sourceDistanceMeters`, `roomAmount`, `ambience`. Legacy v1 restores as +room OFF; malformed v2 is rejected atomically; the last accepted edit is +only persisted after audio-applied completion. Accepted snapshot schema=2 +returns exactly the stored state. Existing GUI transport v1 fields may omit +new controls and default OFF. + +## What still blocks public release +1. CI: source contract, native no-JUCE PCM, Chromium actual WebView2-assembled + controls, exact-SHA Windows MSVC/CTest, multi-instance restore and restart. +2. Confirm no clicks/glitches on OFF→LARGE→SQUARE, rapid slider changes, rack + bypass, graph remove, save/open .smix, device swap, and stereo-only policy. +3. Human headphone A/B: compare approved Square reference, Studio Glue, Airy + and M4 scene presets with music + voice (front/rear distance, flutter, + metallic coloration, decay masking); adjust only after evidence. +4. Reconcile parent #606 (latest main) → #629 → #643 → this M4 without + dropping independent WIRE, GUI, updater and FX progress. Do not promote + public release based on Linux offline/Chromium mocks alone. + +## Explicit physical limits +2D first-order 4-wall image model; no height/floor/ceiling, personalized +HRTF, frequency-calibrated air absorption, true measured BRIR, later +higher-order bounces or physically fitted RT60. LARGE is a musical scene +preset, not a certified geometry-based hall reverb. Accurate propagation +delay of the direct path is not modeled, for low latency. + +## References (concepts only) +- Allen–Berkley image-source method: JASA 65(4), 1979, DOI 10.1121/1.382599 +- Valve Steam Audio core guide: direct distance and room reflections are + separate stages; no vendor code copied. + https://github.com/ValveSoftware/steam-audio/blob/master/core/doc/guide.rst +- JUCE AudioProcessor: processBlock realtime cautions and bypass semantics. + https://docs.juce.com/master/classjuce_1_1AudioProcessor.html diff --git a/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md new file mode 100644 index 000000000..d61993276 --- /dev/null +++ b/docs/SONKU_V2_EXTERNALIZATION_DECISION_20261113.md @@ -0,0 +1,53 @@ +# 8D-SonKu V2 — Externalization & Natural Orbit Architecture +2026-11-13 | Experimental stage M1 | Based on PR #606 baseline + +## Confirmed user observations +- Headphone listener reports correct directions, 4/4 known and 8/8 blind. +- FRONT/REAR are too thin/near-head and motion through both median-plane axes lacks realistic depth. +- This is a perceptual report, NOT a measured distance, CPU benchmark or proof of identical HRTF fit for all listeners. + +## Technical research and prior art (no code or skin copying) +- Allen & Berkley (1979), Image Method for Efficiently Simulating Small-Room Acoustics, JASA 65(4), DOI 10.1121/1.382599 — geometrical mirror-image first-order acoustic paths and time-of-flight. +- Steam Audio core guide: https://github.com/ValveSoftware/steam-audio/blob/master/core/doc/guide.rst — direct binaural HRTF, room reflections and distance effects are separate, testable stages. +- 3D Tune-In Audio Toolkit: https://github.com/3DTune-In/3dti_AudioToolkit — ITD-independent HRIR interpolation and acoustic parallax are mature solutions, *research for later M2*, not implemented here. +- Frontal externalization BRIR study: https://pmc.ncbi.nlm.nih.gov/articles/PMC13451706/ — altered early reflections and direct/reflected ratio can improve front externalization for some listeners, not a guaranteed result on all headphones. + +## Current implementation decision: split M1 from the other acoustic stages +Keep SonKuSpatialCore and native JUCE/PCM graph as one authoritative processor; no new DSP engine, new device callback, JS audio path, thread, blocking call, file access or dynamic callback allocation. Add SonKuEarlyReflections as a fixed-memory, first-order image-source *experimental* room stage. Amount=0 by default and guarantees identical previously qualified native PCM. Amount=.55 generates *offline-only* A/B comparison WAVs using the exact original source samples and direct KEMAR HRIR. Do not publish this as a new default until blind headphone tests support it. + +### Bounded acoustic model (M1) +- Room width 6.4m, depth 8.0m, listener centered, 2 sources at 1.6m rotating on the horizontal ring. +- Four first-order wall images per source (left, right, front, rear), hence eight reflected paths. +- Delay in samples = (distance from image - direct source distance) / 343m/s × sample rate, plus a small symmetric ear baseline to create directional ITD; gains = wall reflectivity × directDistance/pathDistance × fixed safety factor. +- Mild source low-pass, ear-directional ITD/ILD approximation; NOT HRTF-convolved reflected signals or FDN reverb. +- Fixed 8192-frame power-of-two ring for each source (~64KiB total) and fractional-delay interpolation; geometry updates every 64 frames while delay and gains smoothly follow per-sample. +- Works at 44.1/48k; conservative fixed delay bounds; original direct HRTF FIR, stereo dry, spatialMix, outputTrim, ASIO and native ACK/readback remain untouched. +- One C++ unit gate, one exact-core integration parity test, two A/B WAV comparisons and a bounded CPU comparison before Windows FAT. + +## Staged next steps (NOT yet delivered) +M2: ITD/time-aligned measured HRIR preprocessing + fractional ear delay, grid-point identity and phase/ILD regression; no generic "phase aligned" switch without proving source accuracy. +M3: if needed, prepared HRTF-filtered reflections with bounded convolution and room distance parameter. +M4: only after successful listening trials, a compact SPACE control with native typed lease, accepted ACK/readback, versioned session schema and a calibrated default. No extra user-facing page. +M5: optional low-cost FDN late reverb, several HRTF profiles / calibration and head tracking after measured CPU and perceptual evidence. + +## Listening gate +Compare the legacy source-accurate 4-direction WAV and 10s orbit with two V2 files rendered from EXACT same input samples. Match perceived level, listen on headphones with OS virtualization off. Measure 8-direction mapping, front/rear distance, orbit continuity, colorations, metallic echoes and time-varying flutter. If room worsens direction or sound quality, keep amount=0. CI PCM PASS alone does not prove spatial externalization. + +## 2026-11-13 listener feedback and two-turn orbit gate +Listener recognizes direction but describes a noncircular perceived orbit: RIGHT → FRONT is pleasing, yet FRONT/RIGHT/REAR continuity feels incomplete and FRONT subjectively nearer. The room is **rectangular 6.4 × 8 m**, so reflected image distances and directional/temporal profiles vary across axes. This is one plausible contributor, not a proven cause; non-individual HRTF and ITD-inconsistent HRIR interpolation remain other hypotheses. + +The offline evaluation now renders a **single uninterrupted 20-second, 2 × 360° clockwise trajectory** (10 seconds/turn) for both legacy direct HRTF and rectangular-room A/B. Only fade in at time 0 and fade out at 20 seconds; no fade/reset/offset at the 10-second boundary. Landmarks: FRONT 0/10/20s; RIGHT 2.5/12.5; REAR 5/15; LEFT 7.5/17.5. PCM tests verify 960,000 frames, non-silent seam, fixed rate and output sign, and C++ end-of-two-turn phase closure. Do not market a verified circular perceptual effect until headphone evaluation. + +## 2026-11-13 — rectangular vs symmetric-room controlled comparison +The report of an elliptical/unequal-distance orbit does NOT prove a room-model bug. Alongside V1 direct HRTF and the existing rectangular 6.4×8m image-source room, a third A/B WAV uses a square 7.2×7.2m room with all wall reflectivities identical. The emitted direct HRTF, sample clock, source waveform and 2×360° motion remain identical. The square wall layout has fourfold rotational geometry and tests whether wall distance contributes to perceived asymmetry; it is NOT a circular room or a promised perceptual cure. C++ tests check left/right mirror of the reflected impulse. A/B only, original native default remains OFF. + +## 2026-11-13 — independent reversed-motion listening probes +In response to asymmetrical perceived naturalness of RIGHT→FRONT vs FRONT→RIGHT, add three CCW two-turn WAVs alongside the three clockwise versions. All six are 20 seconds, use the exact same deterministic original noise, same native HRTF and DSP sample clock, and have no loop seam. Clockwise: FRONT → RIGHT → REAR → LEFT → FRONT. Counterclockwise: FRONT → LEFT → REAR → RIGHT → FRONT. This allows listening comparison of RIGHT→FRONT (CCW at 7.5–10 and 17.5–20 seconds) with FRONT→RIGHT (CW at 0–2.5 and 10–12.5 seconds), and tests whether perceptual asymmetry reverses with source rotation direction. No additional live motion modes, no UI changes, no assertion of physically circular perception. + +## 2026-11-13 — listener-approved Square Orbit checkpoint and musical late reverb M2 +The owner has listened to and approved the **square-room orbit as perceptually circular**. Its exact base code is pinned at `checkpoint/8d-sonku-square-orbit-approved-20261113` (`3a74b0273c7a7e13d5d2614183d19995eb12ad57`); this immutable evaluation milestone must not be overwritten by reverb experiments. There already are eight bounded 1st-order wall-reflection paths (four per source), but **there was no late reverb**. + +New *opt-in offline candidate*, original `SonKuMusicalReverb.h`: 8 noncommensurate delays with a normalized Hadamard orthogonal feedback matrix, per-line RT60 feedback gains prepared for 44.1/48k, damping low-pass in the loop, stereo decorrelated output, 12ms wet ramp, and at least 43ms to first late energy. Max delay ring 8×4096 floats (~128KiB) with no dynamic PCM buffer, FFT, allpass resonator cascade, or per-sample trigonometry/exp. Two listening-only presets: Studio Glue (RT60 ~0.78s; 5.9kHz damping) and Airy Chamber (RT60 ~1.28s; 7kHz). Wet amount .42 for controlled A/B is intentionally modest and **OFF in the native plugin**. Square early reflections remain exactly as approved, with no room-size or HRTF clock modification. Compare baseline square with Studio Glue and Airy Chamber 20s 2-turn WAVs, using same source, latency, level trim, azimuth and direct HRIR. C++ tests validate stable impulse energy, late onset, stereo width, RT60 decay, byte-exact disabled state and PCM partition parity. No GUI knob, session upgrade or public release until listener feedback and physical Windows audio qualification. FDN theory: Stautner/Puckette (1982), Jot/Chaigne (1991), and practical low-metallic density guidance from Valhalla DSP; original GPL-compatible implementation, no copied commercial source. + +## 2026-11-13 — original musical-content A/B +Because broadband noise cannot reveal whether a late reverb is pleasing on music, the exact core offline renderer now also creates a deterministic 20-second synthetic plucked-tone motif, repeated identically once per 360° orbit, under the same Square ER. Three WAVs: baseline late OFF; Studio Glue RT60≈0.78s; Airy Chamber RT60≈1.28s. The melody is originally generated test material, with no copyrighted recordings. Envelope fades within each note to avoid spurious onset clicks. C++ and Python gates verify correct WAV format, PCM non-identity between presets and no clipping. This remains a **perceptual candidate**, not an assertion of musical quality. diff --git a/docs/SONKU_V4_DISTANCE_SPACE_DECISION_20261113.md b/docs/SONKU_V4_DISTANCE_SPACE_DECISION_20261113.md new file mode 100644 index 000000000..d02cfea11 --- /dev/null +++ b/docs/SONKU_V4_DISTANCE_SPACE_DECISION_20261113.md @@ -0,0 +1,73 @@ +# 8D-SonKu V4 — independent source-distance and large-room candidate +2026-11-13 | offline headphone experiment | stacked on approved Square + V3 FDN PR #629 + +## Baseline lock / non-goals +The owner approved a 7.2 × 7.2 m Square Orbit at 1.6 m emitter radius. +Checkpoint `3a74b0273c7a7e13d5d2614183d19995eb12ad57` must not move. +Do NOT modify any HRIR coefficients, direction signs, native SonKu controls, +V3 reverb presets, production JUCE state, mixer WIRE routing, or public Pages. + +## Why ROOM SIZE and SOURCE DISTANCE are NOT the same parameter +- **Room dimensions:** move virtual image walls, which changes first reflection + arrival times and amplitude by source-to-listener path distance. +- **Source distance:** changes relative direct energy (reference pressure 1.6/r), + while each reflected path is independently scaled with 1.6/path. The 1.6 m + reference is unchanged, including EXACT original floating-point operation order. +- **Diffuse late reverb:** not physically equivalent to either quantity. The + existing Studio Glue (0.78 s) and Airy Chamber (1.28 s) are deliberately OFF + in new distance/room A/B tracks. A large "hall" RT60 must be separately + modeled, calibrated and listened to; do not fake hall size with one longer tail. + +## Engine changes and realtime constraints +- `SonKuEarlyReflections::setGeometry({width,depth,distance})` controls an + unpublished, inactive processor only. Geometry is bounded to 5–40 m per + dimension, source distance 1.6–10 m, >0.5 m wall clearance and worst image + path within the existing 8192-frame circular delay ring at 48 kHz. +- First-order image-source paths still use 2 emitters × 4 walls, 64-frame + geometry cadence, fractional-delay taps, smoothed delays and gains. No ray + tracing, FFT, new thread, host callback, heap or IO in `process()`. +- `SonKuSpatialCore` applies reference-distance gain ONLY to direct measured + HRTF when an experimental non-reference geometry is configured; reflections + use absolute reflected path pressure and the existing FDN stage is unchanged. +- This is NOT a full physical BRIR: no floor/ceiling, higher-order reflections, + occlusion, calibrated high-frequency air absorption, direct time-of-flight, + personalized pinna model, dynamic head tracking or release-qualified tail. +- No GUI/bridge/lease/session edits; ALL production instances remain legacy + geometry with direct gain=1 and the approved PCM arithmetic unchanged. + +## Matched-source audition matrix (two 10-second 360° revolutions) +The existing `sonku-v2-square-orbit-cw-2x.wav` remains the reference. + +| WAV stem | Width × depth | Emission radius | Late reverb | Intended comparison | +| --- | --- | --- | --- | --- | +| v2-square | 7.2 × 7.2 m | 1.6 m | OFF | Owner-approved | +| v4-spacious-near | 14.4 × 14.4 m | 1.6 m | OFF | Room dimension only | +| v4-spacious-far | 14.4 × 14.4 m | 5.0 m | OFF | Distance only vs spacious-near | +| v4-large-near | 28.8 × 28.8 m | 1.6 m | OFF | Larger room without moving source | +| v4-large-far | 28.8 × 28.8 m | 8.0 m | OFF | Distance only vs large-near | + +All render the same deterministic noise, source stereo, azimuth path, +KEMAR HRIR, wet setting and trim. Files are NOT normalized: distant samples +are truly quieter. For localization evaluation match perceived monitoring +loudness safely and separately evaluate the physical level change. +Headphones only; disable OS spatial enhancement. + +## Gates +1. Legacy default Square vs explicit identical geometry: byte-exact early + reflection and full native-core PCM under both 44.1/48k. +2. Larger room first-echo onset must move later, beyond the reference. +3. Distant direct field must approximate 1.6/r with ER OFF; reject invalid, + nonfinite, too-small, out-of-wall geometry and active edits. +4. Complete WAV formats, continuous 2-turn seam, non-silent tails, + direction signs, parity, amplitude safety and same-runner CPU telemetry. +5. Listener A/B judgment and Windows ASIO hardware tests are separate, + necessary release gates. No native GUI control or installer promotion yet. + +## Research +- Allen and Berkley, JASA 65(4), 943–950 (1979), DOI 10.1121/1.382599: + first-order image-source paths for rectangular rooms. +- Valve Steam Audio core guide, direct distance attenuation and reflection + model as separate signal-processing stages: + https://github.com/ValveSoftware/steam-audio/blob/master/core/doc/guide.rst + +No external code or proprietary impulse responses copied. diff --git a/docs/THIRD_PARTY_8D_SONKU_HRTF.md b/docs/THIRD_PARTY_8D_SONKU_HRTF.md new file mode 100644 index 000000000..2fe6caa3c --- /dev/null +++ b/docs/THIRD_PARTY_8D_SONKU_HRTF.md @@ -0,0 +1,31 @@ +# 8D-SonKu measured HRIR redistribution and attribution +Date 2026-11-12. Source: 8D-SonKu `SonKuMeasuredHrir.h`. +- Original HRIR measurements: Bill Gardner and Keith Martin, MIT Media Laboratory, 1994. MIT KEMAR (0° elevation). +- MIT Media Laboratory terms are reported in the OpenAL Soft MIT_KEMAR.def: free of charge without usage restrictions provided original authors are cited. https://github.com/kcat/openal-soft/blob/master/utils/MIT_KEMAR.def +- C table format and 44.1/48 kHz processed 128/140-tap values derived from **Aristotel Digenis, MIT HRTF C Library**, https://github.com/jhonmark/mit-hrtf-lib (MIT license; copyright 2007 Aristotel Digenis; repository LICENSE copyright 2014 greekgoddj). +- Source path: `source/normal/mit_hrtf_normal_44100.h` and `source/normal/mit_hrtf_normal_48000.h`; only the 0° elevation 0–180° at 5° spacing; 44.1 kHz rows zero-padded to 140; negative 180..360 by ear symmetry. +- **These are general-purpose nonindividualized HRIRs**. Front/rear externalization is NOT guaranteed. No dearVR code or IR is used. + +MIT License (MIT) +Copyright (c) 2014 greekgoddj +Copyright (c) 2007 Aristotel Digenis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Packaging gate: ensure this attribution/license is included in release distribution notices; source-only doc is not enough to certify an installer. Dataset provenance should be independently legal-reviewed before any commercial redistribution claim. diff --git a/engine/builtin_fx/GuitarRigEditor.h b/engine/builtin_fx/GuitarRigEditor.h index 4e4ae9f8e..895db093b 100644 --- a/engine/builtin_fx/GuitarRigEditor.h +++ b/engine/builtin_fx/GuitarRigEditor.h @@ -36,6 +36,32 @@ class GuitarRigEditor final : public juce::AudioProcessorEditor, juce::RectanglePlacement::centred); } }; + struct SkinButtons final : juce::LookAndFeel_V4 { + juce::Image off,on; + void drawButtonBackground(juce::Graphics& g,juce::Button& button, + const juce::Colour&,bool hovered,bool down) override { + // ON and OFF are pixel-aligned full-frame skins. Hover and + // pressed feedback tint the inset face, NEVER the housing + // geometry, so even rapid mouse interaction cannot flicker. + const auto& bitmap=button.getToggleState()?on:off; + if(bitmap.isValid())g.drawImageWithin(bitmap,0,0,button.getWidth(), + button.getHeight(),juce::RectanglePlacement::stretchToFit); + else juce::LookAndFeel_V4::drawButtonBackground(g,button, + juce::Colour::fromRGB(38,42,47),hovered,down); + if(!button.isEnabled())return; + if(hovered||down) { + auto face=juce::Rectangle( + 6.f,5.f,static_cast(button.getWidth()-12), + static_cast(button.getHeight()-10)); + if(face.getWidth()>4.f&&face.getHeight()>4.f) { + g.setColour(down?juce::Colours::black.withAlpha(0.20f): + juce::Colour::fromRGB(255,197,116).withAlpha(0.12f)); + g.fillRoundedRectangle(face, + std::min(face.getHeight()*0.45f,11.f)); + } + } + } + }; public: explicit GuitarRigEditor(GuitarRigProcessor& processor) : juce::AudioProcessorEditor(processor),processor_(processor) { @@ -52,6 +78,9 @@ class GuitarRigEditor final : public juce::AudioProcessorEditor, accepted_=draft_; loadArt(); knobsLook_.image=knob_; + buttonLook_.off=buttonOff_;buttonLook_.on=buttonOn_; + switchLook_.off=switchOff_;switchLook_.on=switchOn_; + stompLook_.off=stompOff_;stompLook_.on=stompOn_; setSize(1060,640); for(std::size_t i=0;i(i)); }; @@ -71,6 +102,8 @@ class GuitarRigEditor final : public juce::AudioProcessorEditor, } for(std::size_t i=0;i<4;++i){ library_[i].setButtonText(armix::guitarfx::factoryToneNames[i]); + library_[i].setLookAndFeel(&buttonLook_); + library_[i].setClickingTogglesState(false); library_[i].onClick=[this,i]{ const int id=static_cast(i)+1; preset_.setSelectedId(id,juce::dontSendNotification); @@ -81,11 +114,15 @@ class GuitarRigEditor final : public juce::AudioProcessorEditor, for(std::size_t i=0;i<4;++i){ const auto* name=names_[i]; focusButtons_[i].setButtonText(name); + focusButtons_[i].setLookAndFeel(&buttonLook_); + focusButtons_[i].setClickingTogglesState(false); focusButtons_[i].onClick=[this,i]{ focus_=i;refreshWidgets();repaint(); }; addAndMakeVisible(focusButtons_[i]); - power_[i].setButtonText("ON"); + power_[i].setButtonText(""); + power_[i].setTooltip(juce::String("Toggle ")+name); + power_[i].setLookAndFeel(&switchLook_); power_[i].setClickingTogglesState(false); power_[i].onClick=[this,i]{ if(draft_.count<=i)return; @@ -107,6 +144,14 @@ class GuitarRigEditor final : public juce::AudioProcessorEditor, }; addAndMakeVisible(sliders_[i]); } + // A second ON/OFF hit target on the physical pedal footwell + // forwards the SAME DSP intent as its top-row toggle. + stomp_.setButtonText(""); + stomp_.setLookAndFeel(&stompLook_); + stomp_.onClick=[this]{ + if(focus_<2 && draft_.count>focus_)power_[focus_].triggerClick(); + }; + addAndMakeVisible(stomp_); status_.setJustificationType(juce::Justification::centredRight); status_.setColour(juce::Label::textColourId, juce::Colour::fromRGB(213,170,112)); @@ -133,6 +178,11 @@ class GuitarRigEditor final : public juce::AudioProcessorEditor, if(id) (void)processor_.queueProgram(bankDrafts_[target],id,target); } for(auto& slider:sliders_)slider.setLookAndFeel(nullptr); + for(auto& b:focusButtons_)b.setLookAndFeel(nullptr); + for(auto& b:power_)b.setLookAndFeel(nullptr); + for(auto& b:library_)b.setLookAndFeel(nullptr); + for(auto& b:bankButtons_)b.setLookAndFeel(nullptr); + stomp_.setLookAndFeel(nullptr); } void paint(juce::Graphics& g) override { g.fillAll(juce::Colour::fromRGB(18,21,26)); @@ -157,35 +207,44 @@ class GuitarRigEditor final : public juce::AudioProcessorEditor, juce::Justification::centredLeft); g.drawText("FACTORY TONES",18,177,171,24, juce::Justification::centredLeft); - // Focus shell deliberately uses only ONE major visual device. - const auto stage=juce::Rectangle(226,177,getWidth()-250,286); - g.setColour(juce::Colour::fromRGB(36,39,44)); - g.fillRoundedRectangle(stage.toFloat(),12.f); - g.setColour(juce::Colour::fromRGB(72,70,67)); - g.drawRoundedRectangle(stage.toFloat(),12.f,1.f); - const auto hero=focus_==2?amp_:focus_==3?cab_:focus_==0?gate_:pedal_; - const auto art=stage.reduced(20,20); + // Reusable PNG frame; the hardware BODY has empty mounting wells. + // Every knob/stomp is its own JUCE interactive child on top, never + // baked into a pedal JPG/PNG and never a decorative fake parameter. + const auto stage=juce::Rectangle(226,177,getWidth()-250,365); + if(panel_.isValid())g.drawImageWithin(panel_,stage.getX(),stage.getY(), + stage.getWidth(),stage.getHeight(), + juce::RectanglePlacement::stretchToFit); + else { + g.setColour(juce::Colour::fromRGB(30,33,37)); + g.fillRoundedRectangle(stage.toFloat(),12.f); + } + const auto& hero=focus_==2?amp_:focus_==3?cab_:focus_==0?gate_:pedal_; + const auto art=artBounds(); if(hero.isValid()) - g.drawImageWithin(hero,art.getX(),art.getY(),art.getWidth(), - art.getHeight(),juce::RectanglePlacement::centred); + g.drawImageWithin(hero,juce::roundToInt(art.getX()), + juce::roundToInt(art.getY()),juce::roundToInt(art.getWidth()), + juce::roundToInt(art.getHeight()), + juce::RectanglePlacement::centred); else { - g.setColour(juce::Colour::fromRGB(71,62,54)); - g.fillRoundedRectangle(art.toFloat().reduced(25.f,14.f),15.f); - g.setColour(gold); - g.setFont(juce::Font(juce::FontOptions(26.f))); - g.drawText(names_[focus_],art,juce::Justification::centred); + g.setColour(juce::Colour::fromRGB(59,48,40)); + g.fillRoundedRectangle(art,12.f); } - // Bitmap artwork never contains parameter legends or live values. g.setColour(gold); - g.setFont(juce::Font(juce::FontOptions(14.f))); - g.drawText(names_[focus_],246,184,290,27, + g.setFont(juce::Font(juce::FontOptions(13.f))); + g.drawText(names_[focus_],246,184,242,26, juce::Justification::centredLeft); - g.setColour(muted); - g.setFont(juce::Font(juce::FontOptions(12.f))); + // Labels and live DSP values are always vector text drawn by JUCE; + // no PNG text or hidden controls underneath the art. + g.setFont(juce::Font(juce::FontOptions(11.f))); for(std::size_t i=0;i(i)*188; - g.drawText(controlNames_[focus_][i],cx-40,549,110,22, - juce::Justification::centred); + const bool amp=focus_==2; + const int x=amp?juce::roundToInt(knobBounds(i).getCentreX())-65:840; + const int y=amp?519:244+static_cast(i)*64; + const int ox=amp?x:840; + g.setColour(muted); + g.drawText(controlNames_[focus_][i],ox,y,130,18, + amp?juce::Justification::centred: + juce::Justification::centredLeft); g.setColour(gold); const float normalized=draft_.blocks[focus_].values[i]; juce::String reading; @@ -196,14 +255,14 @@ class GuitarRigEditor final : public juce::AudioProcessorEditor, else if(focus_==0 && i==2) reading=juce::String(12.f+228.f*normalized,0)+" ms"; else reading=juce::String(normalized*100.f,0)+"%"; - g.drawText(reading,cx-40,570,110,18, - juce::Justification::centred); - g.setColour(muted); + g.drawText(reading,ox,y+18,130,18, + amp?juce::Justification::centred: + juce::Justification::centredLeft); } if(focus_==3){ - g.setFont(juce::Font(juce::FontOptions(12.f))); - g.drawText("65-TAP CABINET FIR · 32-SAMPLE CAB / 48-SAMPLE FX PDC", - 305,495,570,29,juce::Justification::centred); + g.setColour(muted); + g.drawText("65-TAP CABINET FIR · FIXED 48-SAMPLE FX PDC", + 316,532,600,24,juce::Justification::centred); } g.setColour(juce::Colour::fromRGB(51,57,65)); g.fillRect(205,getHeight()-37,getWidth()-205,37); @@ -245,11 +304,12 @@ class GuitarRigEditor final : public juce::AudioProcessorEditor, } for(std::size_t i=0;i<4;++i){ const int x=228+static_cast(i)*199; - focusButtons_[i].setBounds(x,104,151,39); - power_[i].setBounds(x+155,108,38,30); + focusButtons_[i].setBounds(x,104,137,39); + power_[i].setBounds(x+141,107,51,32); } + stomp_.setBounds(stompBounds()); for(std::size_t i=0;i<3;++i) - sliders_[i].setBounds(259+static_cast(i)*188,473,116,80); + sliders_[i].setBounds(knobBounds(i)); } private: void timerCallback() override { @@ -292,55 +352,92 @@ class GuitarRigEditor final : public juce::AudioProcessorEditor, } void loadArt() { #if defined(ARMIX_GFX_EMBED_PNG_SKINS) - // JUCE Image uses reference-counted image storage. Decoding 5 PNGs + // JUCE Image uses reference-counted image storage. Decoding 12 PNGs // on every floating editor reopen is avoidable startup work; the // first UI creation populates this thread-safe function-local cache // and later editors only share image handles. No audio-thread IO. - static const std::array skins=[] { - return std::array{ - juce::ImageFileFormat::loadFrom( - BinaryData::ampheadclassa_png, - static_cast(BinaryData::ampheadclassa_pngSize)), - juce::ImageFileFormat::loadFrom( - BinaryData::cabinetdual12_png, - static_cast(BinaryData::cabinetdual12_pngSize)), - juce::ImageFileFormat::loadFrom( - BinaryData::pedalgate_png, - static_cast(BinaryData::pedalgate_pngSize)), - juce::ImageFileFormat::loadFrom( - BinaryData::pedaloverdrive_png, - static_cast(BinaryData::pedaloverdrive_pngSize)), - juce::ImageFileFormat::loadFrom( - BinaryData::knobbrushedmetal_png, - static_cast(BinaryData::knobbrushedmetal_pngSize)) + static const std::array skins=[] { + return std::array{ + juce::ImageFileFormat::loadFrom(BinaryData::gfxamphead_png, + static_cast(BinaryData::gfxamphead_pngSize)), + juce::ImageFileFormat::loadFrom(BinaryData::gfxcabinet_png, + static_cast(BinaryData::gfxcabinet_pngSize)), + juce::ImageFileFormat::loadFrom(BinaryData::gfxpedalgatebody_png, + static_cast(BinaryData::gfxpedalgatebody_pngSize)), + juce::ImageFileFormat::loadFrom(BinaryData::gfxpedaldrivebody_png, + static_cast(BinaryData::gfxpedaldrivebody_pngSize)), + juce::ImageFileFormat::loadFrom(BinaryData::gfxknob_png, + static_cast(BinaryData::gfxknob_pngSize)), + juce::ImageFileFormat::loadFrom(BinaryData::gfxswitchoff_png, + static_cast(BinaryData::gfxswitchoff_pngSize)), + juce::ImageFileFormat::loadFrom(BinaryData::gfxswitchon_png, + static_cast(BinaryData::gfxswitchon_pngSize)), + juce::ImageFileFormat::loadFrom(BinaryData::gfxbuttonoff_png, + static_cast(BinaryData::gfxbuttonoff_pngSize)), + juce::ImageFileFormat::loadFrom(BinaryData::gfxbuttonon_png, + static_cast(BinaryData::gfxbuttonon_pngSize)), + juce::ImageFileFormat::loadFrom(BinaryData::gfxpanel_png, + static_cast(BinaryData::gfxpanel_pngSize)), + juce::ImageFileFormat::loadFrom(BinaryData::gfxstompoff_png, + static_cast(BinaryData::gfxstompoff_pngSize)), + juce::ImageFileFormat::loadFrom(BinaryData::gfxstompon_png, + static_cast(BinaryData::gfxstompon_pngSize)) }; }(); - amp_=skins[0];cab_=skins[1];gate_=skins[2]; - pedal_=skins[3];knob_=skins[4]; + amp_=skins[0];cab_=skins[1];gate_=skins[2];pedal_=skins[3]; + knob_=skins[4];switchOff_=skins[5];switchOn_=skins[6]; + buttonOff_=skins[7];buttonOn_=skins[8];panel_=skins[9]; + stompOff_=skins[10];stompOn_=skins[11]; #endif } + juce::Rectangle artBounds() const { + // Stable exact positioning shared by bitmap and hit-testing. + const bool pedal=focus_<2; + const float width=pedal?237.f:720.f; + const float height=pedal?332.f:300.f; + return {631.f-width*.5f,190.f+(332.f-height)*.5f,width,height}; + } + juce::Rectangle knobBounds(std::size_t i) const { + const auto a=artBounds(); + float nx=.5f,ny=.74f; + if(focus_==0){ + nx=i==0?.31f:i==1?.69f:.50f; + ny=i==2?.38f:.28f; + }else if(focus_==1){nx=.50f;ny=.38f;} + else {nx=i==0?.30f:i==1?.50f:.70f;ny=.73f;} + const int cx=juce::roundToInt(a.getX()+a.getWidth()*nx); + const int cy=juce::roundToInt(a.getY()+a.getHeight()*ny); + return {cx-34,cy-34,68,68}; + } + juce::Rectangle stompBounds() const { + const auto a=artBounds(); + const int x=juce::roundToInt(a.getX()+a.getWidth()*.5f); + const int y=juce::roundToInt(a.getY()+a.getHeight()*.82f); + return {x-29,y-29,58,58}; + } std::size_t activeControlCount() const noexcept { return focus_==3?0u:(focus_==0||focus_==2)?3u:1u; } void refreshWidgets(){ refreshing_=true; - for(std::size_t i=0;i<2;++i){ - bankButtons_[i].setColour(juce::TextButton::buttonColourId, - i==selectedBank_?juce::Colour::fromRGB(119,79,40): - juce::Colour::fromRGB(43,49,55)); - } + for(std::size_t i=0;i<2;++i) + bankButtons_[i].setToggleState(i==selectedBank_, + juce::dontSendNotification); for(std::size_t i=0;i<4;++i){ - library_[i].setColour(juce::TextButton::buttonColourId, - selectedPreset_==static_cast(i)+1? - juce::Colour::fromRGB(91,67,43): - juce::Colour::fromRGB(39,44,50)); - power_[i].setButtonText(draft_.blocks[i].enabled?"ON":"OFF"); - focusButtons_[i].setColour(juce::TextButton::buttonColourId, - i==focus_?juce::Colour::fromRGB(93,67,43): - juce::Colour::fromRGB(49,55,61)); + library_[i].setToggleState(selectedPreset_==static_cast(i)+1, + juce::dontSendNotification); + power_[i].setToggleState(draft_.blocks[i].enabled, + juce::dontSendNotification); + focusButtons_[i].setToggleState(i==focus_, + juce::dontSendNotification); } + stomp_.setVisible(focus_<2); + stomp_.setToggleState(draft_.blocks[focus_].enabled, + juce::dontSendNotification); + stomp_.setBounds(stompBounds()); for(std::size_t i=0;i<3;++i){ sliders_[i].setVisible(i focusButtons_{}; diff --git a/engine/builtin_fx/SonKuSpatialProcessor.h b/engine/builtin_fx/SonKuSpatialProcessor.h new file mode 100644 index 000000000..2412d6c87 --- /dev/null +++ b/engine/builtin_fx/SonKuSpatialProcessor.h @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "sonku/SonKuSpatialCore.h" +#include "FxSpsc.h" +#include "../core/RealtimeNativeFxControl.h" +#include +#include +#include + +// Built-in insert only; JUCE VST3 packaging is a separate adapter/quality gate. +// Existing FX instance owns bypass, MIDI scratch, ChannelId, PDC and retirement. +namespace armix::builtin_fx { +class SonKuSpatialProcessor final : public juce::AudioProcessor, + public armix::mixer::RealtimeNativeFxControl { +public: + static constexpr const char* catalogIdentity="armix.builtin.8d-sonku.v1"; + struct Completion {std::uint64_t requestId=0;armix::sonku::Settings settings{};bool applied=false;}; + SonKuSpatialProcessor() + : juce::AudioProcessor(BusesProperties() + .withInput("Input",juce::AudioChannelSet::stereo(),true) + .withOutput("Output",juce::AudioChannelSet::stereo(),true)) {} + const juce::String getName() const override {return "8D-SonKu";} + bool acceptsMidi() const override {return false;} + bool producesMidi() const override {return false;} + bool isMidiEffect() const override {return false;} + // Conservative bounded tail for the longest enabled room program. OFF + // still performs no FDN work; this reports potential host tail ownership. + double getTailLengthSeconds() const override {return 2.6;} + 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 rate,int) override { + ready_=core_.prepare(rate); + observedAzimuthDegrees_.store(accepted_.startAzimuthDegrees,std::memory_order_relaxed); + if(ready_)ready_=core_.setSettings(accepted_); + } + void releaseResources() override {ready_=false;} + void processBlock(juce::AudioBuffer& pcm,juce::MidiBuffer&) override { + juce::ScopedNoDenormals noDenormals; + if(!ready_||pcm.getNumChannels()<2||pcm.getNumSamples()<=0)return; + consumeRealtimeEdits(); + core_.process(pcm.getWritePointer(0),pcm.getWritePointer(1),pcm.getNumSamples()); + observedAzimuthDegrees_.store(static_cast(core_.azimuthDegrees()), + std::memory_order_relaxed); + } + void processBlock(juce::AudioBuffer&,juce::MidiBuffer&) override {} + void consumeRealtimeEdits() noexcept override { + Edit next; + if(!ready_||!complete_.canPush()||!queue_.pop(next))return; + const bool ok=core_.setSettings(next.settings); + complete_.push({next.requestId,next.settings,ok}); + } + // Control thread: returns QUEUED, not accepted/applied. Host native ACK + // is permitted only after corresponding completion/readback. + bool queueSettings(const armix::sonku::Settings& next,std::uint64_t requestId) noexcept { + return ready_&&requestId&&armix::sonku::valid(next) + &&queue_.push(Edit{requestId,next}); + } + bool pollCompletion(Completion& done) noexcept { + if(!complete_.pop(done))return false; + if(done.applied)accepted_=done.settings; + return true; + } + armix::sonku::Settings acceptedSettings() const noexcept {return accepted_;} + bool isReady() const noexcept {return ready_;} + float observedAzimuthDegrees() const noexcept { + return observedAzimuthDegrees_.load(std::memory_order_relaxed); + } + void sealForRealtime() noexcept override {published_=true;} + bool stateSnapshotQuiescent() const noexcept override { + return queue_.empty()&&complete_.empty(); + } + // CONTROL only; state is accepted, not speculative or PCM-owned. + void getStateInformation(juce::MemoryBlock& dest) override { + juce::MemoryOutputStream out(dest,false); + out.writeInt(0x534F4E4B); // SONK + out.writeInt(2); + out.writeFloat(accepted_.startAzimuthDegrees); + out.writeFloat(accepted_.revolutionSeconds); + out.writeFloat(accepted_.stereoSpreadDegrees); + out.writeFloat(accepted_.spatialMix); + out.writeFloat(accepted_.outputTrim); + out.writeByte(accepted_.moving?1:0); + out.writeByte(accepted_.clockwise?1:0); + out.writeInt(accepted_.spacePreset); + out.writeFloat(accepted_.sourceDistanceMeters); + out.writeFloat(accepted_.roomAmount); + out.writeFloat(accepted_.ambience); + } + bool restoreUnpublishedState(const void* data,int size) { + if(published_||!data||(size!=30&&size!=46)|| + !queue_.empty()||!complete_.empty())return false; + juce::MemoryInputStream in(data,static_cast(size),false); + if(in.readInt()!=0x534F4E4B)return false; + const int version=in.readInt(); + if((version!=1&&version!=2)|| + (version==1&&size!=30)||(version==2&&size!=46))return false; + armix::sonku::Settings next{}; + next.startAzimuthDegrees=in.readFloat(); + next.revolutionSeconds=in.readFloat(); + next.stereoSpreadDegrees=in.readFloat(); + next.spatialMix=in.readFloat(); + next.outputTrim=in.readFloat(); + const int moving=in.readByte(),clockwise=in.readByte(); + if(moving>1||clockwise>1)return false; + next.moving=moving!=0; + next.clockwise=clockwise!=0; + if(version==2) { + next.spacePreset=in.readInt(); + next.sourceDistanceMeters=in.readFloat(); + next.roomAmount=in.readFloat(); + next.ambience=in.readFloat(); + } + // Old v1 .smix restores to HRTF-only. New v2 carries the acoustic + // scene, but never allows malformed/partial state into live PCM. + if(!in.isExhausted())return false; + if(!armix::sonku::valid(next))return false; + if(ready_&&!core_.setSettings(next))return false; + accepted_=next; + return true; + } + void setStateInformation(const void* data,int size) override { + (void)restoreUnpublishedState(data,size); + } +private: + struct Edit {std::uint64_t requestId=0;armix::sonku::Settings settings{};}; + armix::sonku::SonKuSpatialCore core_{}; + FxSpsc queue_{}; + FxSpsc complete_{}; + armix::sonku::Settings accepted_{}; + std::atomic observedAzimuthDegrees_{0.f}; + bool ready_=false; + bool published_=false; +}; +} // namespace armix::builtin_fx diff --git a/engine/builtin_fx/sonku/SonKuEarlyReflections.h b/engine/builtin_fx/sonku/SonKuEarlyReflections.h new file mode 100644 index 000000000..92aeebf05 --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuEarlyReflections.h @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include + +// Bounded, first-order image-source room for headphone externalization trials. +// Reflection image geometry follows Allen & Berkley (JASA, 1979), not +// randomized stereo delays. The ears use lightweight ITD/ILD approximation; +// this is NOT an HRTF-convolved reflection / arbitrary geometry simulation. +// No allocation, locks, worker, I/O, FFT or second device callback. +namespace armix::sonku { +enum class SonKuRoomShape : std::uint8_t { Rectangular=0, Square=1 }; +// Offline-only center-listener geometry. Width/depth are full room spans; +// the source moves on a horizontal ring at distanceMeters from the listener. +// No realtime mutation or native state schema is published by this experiment. +struct SonKuRoomGeometry { + float widthMeters=7.2f,depthMeters=7.2f,distanceMeters=1.6f; +}; +class SonKuEarlyReflections final { +public: + struct Ears {float left=0.f,right=0.f;}; + static constexpr int wallCount=4; + static constexpr int sourceCount=2; + static constexpr int ringFrames=8192; + static constexpr int geometryInterval=64; + bool prepare(double rate) noexcept { + ready_=false; + if(!std::isfinite(rate) || (std::abs(rate-44100.)>.1 && + std::abs(rate-48000.)>.1))return false; + rate_=static_cast(rate); + delaySlew_=static_cast(1.-std::exp(-1./(rate*0.024))); + gainSlew_=static_cast(1.-std::exp(-1./(rate*0.012))); + amountSlew_=static_cast(1.-std::exp(-1./(rate*0.010))); + reset(); + ready_=true; + return true; + } + void reset() noexcept { + for(auto& h:history_)h.fill(0.f); + lowpass_.fill(0.f); + for(auto& paths:tap_)for(auto& p:paths)p=Tap{}; + write_=0;untilGeometry_=0;primed_=false;validFrames_=0; + amount_=0.f; + } + // Deliberately experimental and OFF by default. Legacy 8/8 direction + // baseline stays bit-identical. A/B is set on an unpublished/offline core + // until headphone, CPU and device gates approve native publication. + bool setAmount(float value) noexcept { + if(!std::isfinite(value)||value<0.f||value>1.f)return false; + if(amountTarget_==0.f&&amount_==0.f&&value>0.f)reset(); + amountTarget_=value; + return true; + } + // Offline experiment only. Reject shape edits while effect is active. + bool setShape(SonKuRoomShape shape) noexcept { + if(shape!=SonKuRoomShape::Rectangular && shape!=SonKuRoomShape::Square) + return false; + if(active())return false; + shape_=shape; + custom_=false; // restores the exact legacy square/rectangle semantics + untilGeometry_=0; + primed_=false; + return true; + } + // Evaluated on an unpublished, inactive DSP instance only. Width up to + // 40m is safely contained in the existing 8192-frame delay rings at 48k. + static bool validGeometry(const SonKuRoomGeometry& g) noexcept { + if(!std::isfinite(g.widthMeters)||!std::isfinite(g.depthMeters)|| + !std::isfinite(g.distanceMeters))return false; + if(g.widthMeters<5.f||g.depthMeters<5.f|| + g.widthMeters>40.f||g.depthMeters>40.f|| + g.distanceMeters<1.6f||g.distanceMeters>10.f|| + 2.f*(g.distanceMeters+.5f)>std::min(g.widthMeters,g.depthMeters)) + return false; + const float longest=std::max(g.widthMeters,g.depthMeters)+g.distanceMeters; + const float largestPath=std::sqrt(longest*longest+ + g.distanceMeters*g.distanceMeters); + return (largestPath-g.distanceMeters)*48000.f/343.f+32.f < + static_cast(ringFrames-3); + } + bool setGeometry(const SonKuRoomGeometry& g) noexcept { + if(active()||!validGeometry(g))return false; + geometry_=g; + custom_=true; + shape_=SonKuRoomShape::Square; // consistent 0.70 walls, not rectangle + untilGeometry_=0; + primed_=false; + return true; + } + // Caller validates geometry on CONTROL side before queuing the POD edit. + // Audio-side update only changes targets for existing 64-frame image + // geometry updates; old path taps smoothly move, never clear big rings. + bool setRealtimeRoom(const SonKuRoomGeometry& g,float amount, + bool enabled) noexcept { + if(!std::isfinite(amount)||amount<0.f||amount>1.f)return false; + if(enabled && !validGeometry(g))return false; + if(!active() && enabled && amount>0.f){ + validFrames_=0; lowpass_.fill(0.f); + } + if(enabled){ + geometry_=g;custom_=true;shape_=SonKuRoomShape::Square; + }else{ + custom_=false;shape_=SonKuRoomShape::Square; + } + realtimeMode_=true; + amountTarget_=enabled?amount:0.f; + untilGeometry_=0; + return true; + } + float relativeDistanceGain() const noexcept { + return custom_?1.6f/geometry_.distanceMeters:1.f; + } + SonKuRoomShape shape() const noexcept {return shape_;} + bool active() const noexcept {return ready_&&(amount_>0.f||amountTarget_>0.f);} + float targetAmount() const noexcept {return amountTarget_;} + Ears process(float left,float right,double azimuth,float spread) noexcept { + if(!active())return {}; + if(untilGeometry_==0){ + updateGeometry(azimuth,spread); + untilGeometry_=geometryInterval; + } + const float x[2]{std::isfinite(left)?left:0.f, + std::isfinite(right)?right:0.f}; + for(int s=0;s(ringFrames-3)); + const int integer=static_cast(bounded); + // Avoid re-reading a stale tail after the user disabled and later + // re-enabled the ROOM. Entire 64 KiB ring never needs RT clearing. + if(realtimeMode_&&validFrames_<=integer+1)return 0.f; + const float fract=bounded-static_cast(integer); + const int i0=(write_-integer)&(ringFrames-1); + const int i1=(i0-1)&(ringFrames-1); + return history_[source][i0]*(1.f-fract)+history_[source][i1]*fract; + } + void updateGeometry(double azimuth,float spread) noexcept { + constexpr float pi=3.14159265358979323846f; + const float sourceDistance=custom_?geometry_.distanceMeters:1.60f; + // Preserve the approved 7.2m/1.6m path exactly when custom_ is false. + // A wider room changes physical image paths, not KEMAR azimuth signs. + const float halfWidth=custom_?geometry_.widthMeters*.5f: + ((shape_==SonKuRoomShape::Square)?3.60f:3.20f); + const float halfDepth=custom_?geometry_.depthMeters*.5f: + ((shape_==SonKuRoomShape::Square)?3.60f:4.00f); + constexpr float speedOfSound=343.f; + constexpr float earHalfTime=.00031f; // max +/-0.31ms + constexpr std::array rectangular{.74f,.74f,.67f,.67f}; + constexpr std::array square{.70f,.70f,.70f,.70f}; + const auto& walls=(shape_==SonKuRoomShape::Square)?square:rectangular; + for(int source=0;source(azimuth) + +(source==0?-.5f:.5f)*spread; + const float rad=degrees*(pi/180.f); + const float sx=sourceDistance*std::sin(rad); + const float sy=sourceDistance*std::cos(rad); + const std::array,wallCount> images{{ + {{-2.f*halfWidth-sx,sy}},{{2.f*halfWidth-sx,sy}}, + {{sx,2.f*halfDepth-sy}},{{sx,-2.f*halfDepth-sy}} + }}; + for(int wall=0;wall(ringFrames-3)); + tap.targetDelayR=std::clamp(common-earDelta,1.f, + static_cast(ringFrames-3)); + tap.targetGainL=level*(1.f-.13f*directionX); + tap.targetGainR=level*(1.f+.13f*directionX); + if(!primed_){ + tap.delayL=tap.targetDelayL; + tap.delayR=tap.targetDelayR; + tap.gainL=tap.targetGainL; + tap.gainR=tap.targetGainR; + } + } + } + primed_=true; + } + static_assert((ringFrames&(ringFrames-1))==0); + std::array,sourceCount> history_{}; + std::array,sourceCount> tap_{}; + std::array lowpass_{}; + float rate_=0.f,delaySlew_=0.f,gainSlew_=0.f,amountSlew_=0.f; + float amount_=0.f,amountTarget_=0.f; + int write_=0,untilGeometry_=0,validFrames_=0; + bool realtimeMode_=false; + SonKuRoomShape shape_=SonKuRoomShape::Rectangular; + SonKuRoomGeometry geometry_{}; + bool custom_=false,ready_=false,primed_=false; +}; +} // namespace armix::sonku diff --git a/engine/builtin_fx/sonku/SonKuMeasuredHrir.h b/engine/builtin_fx/sonku/SonKuMeasuredHrir.h new file mode 100644 index 000000000..0116db498 --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuMeasuredHrir.h @@ -0,0 +1,317 @@ +// SPDX-License-Identifier: MIT +// 8D-SonKu horizontal HRIR bank from the MIT KEMAR measured dataset. +// Original measurements: Bill Gardner and Keith Martin, MIT Media Laboratory (1994). +// Source tables: Aristotel Digenis, MIT HRTF C Library (MIT), 2007, +// https://github.com/jhonmark/mit-hrtf-lib, source/normal/mit_hrtf_normal_{44100,48000}.h. +// Extracted ORIGINAL 0-elevation measurements every 5 degrees from 0 to 180. +// For negative azimuth the opposite-ear symmetric measurement is used. +// Taps: 128 at 44.1k, 140 at 48k. 44.1k rows are zero padded to 140. +// See docs/THIRD_PARTY_8D_SONKU_HRTF.md for attribution and dataset limitations. +#pragma once +#include + +namespace armix::sonku::hrir { +inline constexpr int directions = 37; +inline constexpr int taps = 140; +inline constexpr int spacingDegrees = 5; +inline constexpr std::int16_t normal44100[directions][2][taps] = { + { // 0 degrees, measured left/right ears + {5,-6,19,-24,39,-56,74,-101,120,-137,161,30,5321,6066,-6762,-253,195,-5129,7285,5986,2332,11785,11069,-6536,-5109,4539,-8167,-13539,-2026,-1365,-7336,-1277,3012,80,1084,4212,3286,1359,2467,1543,-905,-191,1215,-587,-1697,-1097,-1235,-2135,-2711,-2422,-2046,-1331,-253,114,194,681,1310,1375,929,696,553,151,-244,-225,-474,-819,-699,-736,-921,-736,-542,-605,-447,-73,76,157,352,549,419,112,-34,-6,-104,-306,-273,-311,-395,-292,-165,-175,-147,-5,-60,-246,-136,59,57,16,36,-37,-145,-119,-153,-195,-179,-216,-240,-128,25,74,12,-44,-33,-95,-202,-185,-158,-192,-162,-83,-51,-27,-21,-53,-58,-38,-56,-58,0,0,0,0,0,0,0,0,0,0,0,0}, + {5,-6,19,-24,39,-56,74,-101,120,-137,161,30,5321,6066,-6762,-253,195,-5129,7285,5986,2332,11785,11069,-6536,-5109,4539,-8167,-13539,-2026,-1365,-7336,-1277,3012,80,1084,4212,3286,1359,2467,1543,-905,-191,1215,-587,-1697,-1097,-1235,-2135,-2711,-2422,-2046,-1331,-253,114,194,681,1310,1375,929,696,553,151,-244,-225,-474,-819,-699,-736,-921,-736,-542,-605,-447,-73,76,157,352,549,419,112,-34,-6,-104,-306,-273,-311,-395,-292,-165,-175,-147,-5,-60,-246,-136,59,57,16,36,-37,-145,-119,-153,-195,-179,-216,-240,-128,25,74,12,-44,-33,-95,-202,-185,-158,-192,-162,-83,-51,-27,-21,-53,-58,-38,-56,-58,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 5 degrees, measured left/right ears + {-1,4,0,9,-17,31,-48,59,-82,100,-120,144,124,5029,4987,-5784,203,-165,-4327,6301,5304,2584,10535,9884,-5043,-4165,3342,-7205,-11684,-2271,-1535,-6311,-1339,2340,228,891,3388,2860,1253,2102,1665,-451,-167,1228,-110,-1537,-1189,-1189,-2285,-2652,-1955,-1617,-1236,-238,345,377,410,786,1062,741,424,342,104,-203,-242,-469,-759,-662,-638,-838,-690,-432,-431,-324,-5,167,209,308,381,277,40,-124,-103,-183,-294,-200,-214,-305,-227,-113,-176,-159,-40,-96,-219,-115,42,5,-34,-14,-88,-152,-120,-120,-145,-152,-185,-186,-89,10,71,37,-20,-42,-113,-200,-190,-172,-205,-174,-107,-84,-75,-50,-51,-54,-43,-28,0,0,0,0,0,0,0,0,0,0,0,0}, + {-9,28,-33,50,-68,76,-95,97,-103,117,-77,4475,8319,-6512,-2471,1694,-6346,6855,7572,1717,11669,13632,-6063,-7855,5529,-6589,-15651,-3317,-262,-7887,-2624,3606,261,481,4499,4182,1486,2647,2101,-1007,-712,1128,-439,-1753,-1114,-1140,-2033,-2692,-2747,-2572,-1744,-611,-248,160,1123,1601,1606,1176,901,742,343,-144,-241,-429,-821,-735,-738,-992,-842,-634,-688,-586,-196,-12,69,324,552,531,254,70,54,-35,-278,-231,-246,-479,-430,-218,-218,-206,-34,-40,-244,-148,121,103,41,66,15,-109,-86,-144,-236,-210,-254,-291,-200,-32,58,17,-43,-49,-69,-175,-166,-132,-194,-160,-91,-46,-16,20,-13,-56,-35,-56,-79,-54,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 10 degrees, measured left/right ears + {-5,4,0,-1,10,-14,23,-33,45,-65,82,-100,125,241,4833,3891,-4977,550,-574,-3424,5604,4722,2826,9638,8663,-4177,-3422,2433,-6438,-10180,-2218,-1611,-5553,-1207,1918,217,617,2911,2499,1048,2059,1742,-261,-86,1061,-58,-1214,-1103,-1375,-2287,-2278,-1604,-1466,-1062,-162,408,517,387,406,559,471,301,182,-88,-225,-191,-488,-759,-604,-591,-726,-526,-253,-235,-159,77,172,196,198,229,136,-41,-158,-179,-237,-297,-145,-137,-245,-218,-120,-122,-147,-73,-114,-201,-101,28,7,-60,-50,-96,-156,-127,-130,-151,-139,-142,-157,-94,22,86,39,-37,-67,-115,-173,-166,-191,-228,-191,-132,-101,-82,-56,-68,-55,-25,0,0,0,0,0,0,0,0,0,0,0,0}, + {30,-35,47,-51,57,-64,42,-13,1,-19,3352,10248,-5107,-5417,2920,-7065,5977,9294,1284,11548,15887,-4951,-10580,5574,-4914,-16853,-4781,271,-7837,-3814,3714,529,50,4282,4959,1899,2762,2696,-790,-1627,784,416,-1762,-1378,-1042,-2020,-2777,-2909,-2987,-2390,-1198,-282,467,1281,1726,1921,1515,1067,798,407,-40,-143,-377,-880,-782,-706,-1032,-938,-658,-783,-744,-279,-42,44,273,534,609,381,134,49,-6,-216,-202,-226,-448,-450,-310,-310,-318,-104,-43,-201,-128,147,190,115,116,43,-108,-106,-120,-219,-237,-278,-351,-274,-100,18,4,-69,-57,-59,-133,-130,-103,-173,-172,-96,-60,-17,44,10,-46,-40,-64,-86,-55,-83,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 15 degrees, measured left/right ears + {0,-4,3,0,1,4,-6,15,-28,37,-53,61,-77,103,296,4436,3255,-4257,615,-606,-2884,4961,4285,2777,8719,7845,-3382,-2995,2063,-5557,-8960,-2127,-1590,-4954,-1251,1531,-23,386,2554,2111,1101,2129,1720,-153,0,886,-123,-907,-917,-1407,-2026,-1989,-1603,-1331,-843,-99,318,381,266,247,277,195,119,14,-127,-234,-226,-409,-686,-580,-490,-516,-303,-126,-135,-98,53,122,95,106,145,68,-110,-204,-178,-246,-269,-156,-139,-211,-162,-88,-142,-139,-91,-121,-193,-86,37,5,-30,-62,-126,-179,-154,-160,-158,-109,-121,-121,-68,14,49,-1,-54,-80,-94,-140,-165,-200,-240,-187,-133,-115,-93,-65,-60,-60,0,0,0,0,0,0,0,0,0,0,0,0}, + {-9,24,-28,9,15,-68,114,-159,157,1906,11331,-1596,-9067,3308,-6516,3499,11412,1368,10570,18210,-2316,-13403,4333,-2415,-17790,-6712,950,-7503,-5274,3878,868,-535,3844,5524,2372,2762,3568,-817,-2583,927,1213,-1738,-1318,-1049,-2274,-2834,-2872,-3655,-3383,-1395,134,668,1145,1743,2270,1893,1212,846,473,-19,-144,-288,-841,-836,-740,-1065,-970,-626,-834,-861,-363,-45,19,230,544,683,426,130,84,71,-183,-211,-179,-446,-482,-350,-393,-407,-130,-11,-177,-166,167,282,207,157,61,-84,-89,-103,-251,-259,-292,-391,-343,-150,9,8,-85,-99,-46,-109,-126,-52,-130,-163,-108,-63,-26,35,25,-44,-52,-58,-83,-58,-60,-56,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 20 degrees, measured left/right ears + {0,-3,-3,5,-2,0,4,-4,13,-22,33,-44,50,-59,85,296,3966,2877,-3622,604,-554,-2447,4344,3827,2660,7781,7257,-2615,-2613,1904,-4638,-7875,-2071,-1516,-4536,-1344,1056,-250,281,2156,1991,1253,2003,1656,-4,35,759,-62,-704,-718,-1233,-1858,-1890,-1506,-1126,-738,-244,-6,141,288,231,35,-69,-32,2,-90,-227,-236,-326,-478,-439,-421,-376,-205,-116,-130,-118,11,80,69,65,71,-12,-142,-206,-165,-199,-262,-180,-138,-181,-159,-101,-139,-147,-70,-74,-153,-83,37,9,-63,-69,-135,-195,-171,-155,-133,-104,-96,-104,-74,-25,-3,-23,-61,-50,-77,-135,-151,-170,-189,-184,-135,-120,-101,-74,-75,0,0,0,0,0,0,0,0,0,0,0,0}, + {-13,30,-53,84,-158,220,-277,310,642,10739,3684,-11622,1257,-4219,330,12241,2626,9368,19370,1873,-14620,1031,170,-17051,-9850,650,-5506,-7085,3039,2132,-954,2823,5676,3408,2479,3581,-427,-2623,625,1731,-1079,-1518,-1025,-2175,-3056,-3210,-4328,-4292,-1291,845,417,857,2001,2550,2081,1235,931,628,60,-205,-324,-825,-839,-739,-1122,-1056,-629,-749,-903,-422,-18,-40,188,561,704,453,168,40,68,-70,-174,-163,-472,-587,-459,-400,-383,-156,-3,-151,-189,125,335,279,199,98,-57,-87,-107,-244,-291,-317,-445,-433,-200,8,52,-65,-107,-82,-117,-125,-61,-102,-154,-86,-61,-44,15,7,-60,-91,-74,-64,-15,-12,-47,12,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 25 degrees, measured left/right ears + {-3,1,0,-3,2,0,2,5,-3,12,-19,30,-38,42,-41,75,249,3435,2693,-2995,444,-342,-2078,3599,3487,2443,6818,6852,-1797,-2263,1812,-3643,-6898,-2102,-1489,-4128,-1546,531,-285,194,1903,1904,1229,1914,1598,124,102,789,86,-641,-749,-1046,-1587,-1702,-1338,-1186,-949,-510,-179,44,147,110,-47,-128,-43,109,-17,-199,-124,-180,-355,-359,-405,-437,-246,-94,-141,-128,28,65,1,0,37,-25,-134,-167,-144,-197,-241,-175,-161,-205,-161,-115,-135,-111,-24,-30,-115,-79,-9,-40,-77,-69,-121,-173,-165,-148,-128,-105,-115,-136,-93,-31,-15,-47,-64,-42,-61,-109,-112,-116,-153,-165,-153,-146,-124,-81,0,0,0,0,0,0,0,0,0,0,0,0}, + {49,-90,126,-185,220,-250,300,-80,8246,9401,-10742,-3750,-1443,-2112,11413,4195,8007,20168,6210,-13329,-2849,1281,-14734,-12249,-1934,-3679,-6860,916,2799,-355,2145,4913,4205,2802,2451,7,-1226,-125,1588,89,-1474,-1337,-1770,-2870,-4332,-5136,-4118,-1217,620,417,888,2025,2678,2270,1305,910,733,254,-248,-366,-743,-934,-795,-1081,-1151,-720,-667,-805,-436,5,-39,104,519,759,549,141,-22,20,17,-130,-164,-450,-672,-526,-389,-349,-179,-13,-88,-190,48,330,342,252,112,-32,-93,-113,-231,-290,-336,-489,-495,-258,-24,83,2,-91,-95,-109,-134,-95,-99,-148,-98,-60,-40,-8,-8,-76,-137,-113,-51,23,62,25,9,-22,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 30 degrees, measured left/right ears + {-1,-2,1,-1,-2,0,1,0,3,-4,10,-16,25,-35,34,-26,59,174,2875,2628,-2396,212,-20,-1838,2842,3193,2169,5876,6521,-874,-1972,1757,-2635,-6051,-2259,-1399,-3721,-1934,203,-143,51,1544,1839,1285,1754,1560,354,307,745,-15,-687,-655,-756,-1267,-1622,-1571,-1376,-1067,-672,-381,-162,-10,67,96,50,81,186,88,-55,-53,-177,-401,-422,-423,-478,-324,-119,-93,-108,-41,-8,-30,8,70,9,-116,-183,-155,-182,-232,-184,-178,-222,-199,-129,-109,-76,-2,-15,-95,-89,-47,-68,-91,-77,-109,-147,-152,-160,-148,-127,-138,-149,-97,-49,-40,-54,-58,-38,-40,-63,-75,-97,-139,-168,-166,-155,-125,0,0,0,0,0,0,0,0,0,0,0,0}, + {-65,85,-117,100,-100,107,-157,4677,12934,-5141,-9586,-972,-2570,8977,6064,6250,19976,11079,-10305,-6181,1512,-11966,-13688,-4953,-3551,-6196,-818,3198,-66,1850,5051,4266,1809,2270,1211,-1101,-287,1686,563,-1166,-1149,-1491,-3100,-5226,-5550,-3397,-1384,-319,476,1295,1982,2404,2350,1609,1049,670,251,-214,-311,-611,-995,-932,-1025,-1243,-862,-599,-623,-443,-105,31,174,513,740,572,157,5,-44,-70,-161,-172,-390,-628,-521,-368,-347,-202,-21,-56,-183,-2,318,353,279,157,-30,-152,-121,-199,-292,-325,-481,-538,-326,-60,94,62,-45,-103,-119,-142,-86,-73,-163,-150,-90,-46,-18,-5,-72,-152,-159,-77,42,117,87,35,-6,-44,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 35 degrees, measured left/right ears + {-3,0,-1,0,0,-2,0,2,0,3,-5,12,-17,22,-28,28,-13,36,121,2283,2615,-1775,-73,332,-1610,2066,2898,1941,4912,6214,164,-1667,1611,-1674,-5234,-2466,-1244,-3387,-2203,39,-195,-124,1323,1811,1317,1635,1665,603,220,512,30,-480,-464,-717,-1348,-1716,-1646,-1440,-1277,-910,-511,-248,-13,231,383,284,222,269,190,-22,-143,-276,-488,-488,-471,-474,-345,-170,-103,-147,-65,24,36,30,71,43,-112,-185,-159,-168,-215,-200,-197,-244,-204,-117,-104,-74,10,14,-90,-104,-54,-78,-98,-90,-105,-139,-140,-133,-153,-158,-165,-145,-97,-78,-47,-41,-41,-17,-10,-44,-73,-82,-119,-148,-160,-159,0,0,0,0,0,0,0,0,0,0,0,0}, + {-6,13,-58,96,-144,148,1528,12621,3199,-12132,-4199,-1915,6430,6976,5100,18832,14721,-5820,-7357,343,-9073,-13237,-8202,-5108,-5012,-2836,2363,1290,1597,4907,4717,599,1874,2887,-834,-870,1474,1074,-709,-801,-1332,-3625,-5797,-5224,-2845,-1719,-1026,267,1511,2036,2060,2231,1905,1350,686,111,-244,-226,-523,-939,-982,-1111,-1263,-1004,-552,-488,-448,-236,90,347,567,712,544,204,37,-104,-233,-254,-147,-318,-578,-486,-339,-282,-196,-48,-64,-135,-28,239,364,310,182,-29,-192,-169,-214,-284,-298,-406,-530,-424,-121,112,142,-11,-108,-125,-141,-92,-68,-149,-179,-144,-87,-19,2,-68,-148,-165,-86,26,109,119,62,14,-28,16,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 40 degrees, measured left/right ears + {0,-1,0,0,0,1,-2,-1,3,-1,3,-3,9,-15,19,-23,23,-11,32,64,1704,2606,-1159,-368,674,-1357,1267,2618,1758,3952,5906,1266,-1385,1318,-719,-4408,-2659,-1035,-3008,-2534,-258,-108,-178,1085,1849,1423,1519,1554,662,200,475,252,-420,-770,-968,-1289,-1649,-1784,-1648,-1398,-937,-463,-147,159,461,579,495,322,264,163,-107,-294,-414,-526,-548,-508,-472,-379,-231,-130,-88,-6,73,56,35,68,40,-80,-176,-160,-169,-243,-237,-210,-227,-196,-123,-90,-74,-14,-8,-78,-99,-77,-75,-107,-87,-87,-117,-126,-151,-164,-171,-154,-156,-130,-81,-41,-20,-26,-6,-5,-37,-68,-82,-110,-142,-149,0,0,0,0,0,0,0,0,0,0,0,0}, + {75,-153,216,-272,345,-135,8950,10715,-9302,-9242,-2445,4537,7486,3612,17326,18210,-2091,-7364,186,-7004,-12302,-8904,-8213,-5348,-3181,492,1039,2289,5605,3804,258,2443,3347,-213,-632,577,961,-27,-291,-1474,-4251,-5740,-4601,-2843,-2035,-1026,146,1135,1918,1955,2034,1985,1633,843,28,-250,-213,-526,-889,-911,-1170,-1382,-1084,-501,-478,-458,-189,159,368,636,774,572,216,-26,-180,-325,-255,-177,-314,-522,-449,-288,-267,-185,0,-8,-83,-89,139,313,349,258,-24,-242,-251,-231,-298,-272,-317,-494,-468,-190,101,196,55,-75,-141,-141,-99,-75,-153,-211,-181,-130,-37,8,-34,-130,-173,-76,23,83,113,68,19,-29,4,77,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 45 degrees, measured left/right ears + {3,0,0,0,-1,1,1,-2,1,3,-3,7,-2,7,-8,16,-11,14,3,23,26,1190,2492,-524,-605,932,-1059,514,2319,1624,3100,5520,2294,-1072,997,163,-3476,-2673,-1059,-2833,-2648,-385,-54,-165,997,1838,1304,1268,1556,901,306,277,-20,-654,-961,-1016,-1282,-1729,-1872,-1616,-1257,-758,-276,21,345,622,696,540,329,206,4,-257,-417,-460,-565,-589,-533,-491,-364,-194,-64,-43,24,76,68,62,55,31,-55,-146,-192,-222,-256,-232,-188,-200,-186,-123,-102,-101,-55,-30,-70,-93,-49,-50,-82,-80,-70,-104,-148,-153,-159,-160,-176,-160,-123,-80,-26,-6,-1,-9,-11,-51,-82,-86,-109,-117,0,0,0,0,0,0,0,0,0,0,0,0}, + {-80,98,-104,109,-198,3827,14044,-1104,-13286,-4944,2536,7775,2651,13546,22171,2592,-7664,-94,-4166,-11388,-8443,-9890,-7349,-3719,-1140,553,1452,5620,3898,670,2462,3901,933,-410,61,579,408,-349,-1609,-4459,-5358,-4162,-3138,-2239,-1008,447,919,1299,1772,2000,1891,1684,1122,166,-220,-317,-465,-851,-956,-1093,-1502,-1270,-562,-355,-426,-171,230,406,620,771,657,233,-111,-221,-343,-262,-201,-289,-481,-457,-287,-280,-193,46,97,-11,-92,5,205,358,312,31,-249,-331,-296,-319,-262,-256,-429,-489,-284,47,224,131,-22,-133,-159,-108,-67,-138,-242,-253,-204,-77,10,-11,-90,-152,-95,18,87,98,58,0,-46,-30,53,92,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 50 degrees, measured left/right ears + {1,1,1,1,0,0,-1,-1,-1,-2,2,-2,3,-3,3,-6,7,-1,1,12,10,9,747,2260,103,-744,1051,-714,-144,1972,1545,2383,5004,3125,-616,738,1029,-2558,-2945,-1183,-2355,-2606,-596,104,-57,716,1561,1332,1353,1629,845,-215,-202,-104,-757,-1181,-1159,-1234,-1600,-1707,-1372,-959,-504,-116,175,448,627,662,471,215,32,-145,-367,-494,-488,-586,-618,-514,-412,-292,-131,-29,-53,0,100,95,34,35,29,-75,-183,-212,-214,-244,-230,-181,-193,-195,-148,-130,-130,-77,-25,-51,-74,-27,-27,-76,-69,-65,-126,-161,-153,-167,-183,-167,-148,-116,-73,-23,-5,-28,-38,-48,-67,-86,-73,-70,0,0,0,0,0,0,0,0,0,0,0,0}, + {-96,168,-246,290,244,10999,9628,-12128,-10351,547,6972,3446,7597,23880,10153,-7427,-1538,-865,-9970,-8329,-8904,-10121,-4762,-2397,-495,572,3954,3746,1495,2713,4449,2307,8,439,104,409,-230,-2171,-4597,-4793,-3754,-3650,-2555,-809,539,944,1060,1387,1743,1783,1674,1321,447,-118,-326,-434,-754,-995,-1134,-1529,-1487,-762,-235,-320,-156,239,496,582,709,701,285,-71,-179,-339,-392,-228,-163,-382,-526,-371,-266,-182,7,164,78,-28,-41,89,297,349,141,-221,-371,-348,-349,-291,-216,-326,-489,-384,-42,204,210,45,-105,-160,-115,-36,-90,-215,-296,-293,-185,-43,28,-22,-103,-124,-12,109,128,94,-7,-96,-95,35,110,57,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 55 degrees, measured left/right ears + {1,1,2,1,1,1,0,-1,0,0,0,1,-1,2,-2,2,-1,5,4,-5,21,-1,11,399,1909,685,-722,1001,-340,-640,1559,1503,1854,4345,3741,223,596,1292,-1735,-2800,-1278,-1916,-2420,-721,103,-165,562,1625,1563,1162,898,295,-403,-371,-385,-996,-1211,-1014,-982,-1280,-1353,-1047,-633,-284,-55,190,413,523,475,301,87,-138,-266,-398,-511,-523,-551,-517,-412,-303,-227,-125,-45,-47,13,67,68,25,-2,-19,-101,-161,-193,-202,-245,-249,-192,-195,-201,-165,-127,-112,-68,-35,-44,-45,-14,-19,-63,-66,-91,-125,-149,-165,-174,-172,-145,-135,-111,-87,-66,-51,-52,-46,-40,-46,-56,-54,0,0,0,0,0,0,0,0,0,0,0,0}, + {63,-70,90,-186,4017,15164,-1500,-16415,-3671,5699,5243,2443,19749,19864,-4110,-4649,1667,-6431,-9200,-7348,-10924,-6855,-3354,-1780,138,1055,3014,2356,2050,4273,4804,1149,292,689,558,-411,-2446,-4389,-4981,-3722,-3745,-3060,-940,567,1031,1071,1177,1420,1684,1536,1323,856,75,-276,-395,-624,-926,-1199,-1631,-1656,-966,-354,-227,-94,206,539,612,569,673,521,41,-210,-257,-461,-344,-133,-245,-502,-458,-275,-231,-55,187,181,25,-73,14,245,340,239,-102,-392,-421,-377,-311,-213,-245,-431,-462,-195,132,255,111,-55,-141,-140,-44,-27,-136,-271,-340,-314,-169,-16,24,-41,-120,-60,96,165,143,46,-98,-153,-83,74,114,37,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 60 degrees, measured left/right ears + {-1,0,0,1,1,1,0,-1,-2,-2,-1,-1,-1,-1,-1,-2,-3,5,1,2,-10,28,-5,5,173,1467,1149,-504,779,-1,-913,1112,1459,1525,3749,4211,901,289,1577,-695,-2590,-1450,-1407,-2205,-1031,74,213,695,1286,1002,365,372,99,-661,-748,-526,-835,-983,-675,-570,-863,-1007,-716,-418,-264,-109,92,251,305,269,114,-79,-225,-302,-419,-487,-428,-402,-398,-313,-232,-210,-140,-60,-37,-33,3,36,-12,-41,-46,-86,-136,-197,-219,-252,-255,-196,-181,-174,-139,-111,-104,-74,-32,-41,-40,-17,-26,-57,-76,-73,-109,-149,-161,-175,-157,-147,-153,-148,-130,-86,-53,-27,-20,-16,-33,-57,0,0,0,0,0,0,0,0,0,0,0,0}, + {153,-244,324,-131,9824,12990,-12926,-13589,3455,6825,1523,9742,25761,6266,-8315,1161,-941,-8698,-7135,-9485,-9865,-3944,-2898,-758,-669,850,2563,1673,3089,5304,3869,1065,1087,1004,172,-2393,-4211,-4831,-4396,-3896,-3667,-1570,497,1113,1027,1145,1253,1507,1485,1294,1094,428,-166,-266,-461,-930,-1131,-1509,-1826,-1398,-594,-162,-67,180,405,586,571,606,686,336,-104,-269,-373,-463,-236,-170,-398,-476,-345,-260,-173,122,256,115,-32,-60,123,341,344,73,-310,-491,-437,-327,-223,-180,-321,-483,-395,-36,241,200,23,-109,-157,-88,21,-34,-191,-318,-378,-290,-117,-8,-11,-85,-100,45,181,174,114,-17,-138,-141,-25,88,62,12,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 65 degrees, measured left/right ears + {3,3,3,5,4,5,5,4,4,3,5,6,6,5,8,3,9,4,15,7,6,13,33,-7,14,68,1006,1434,-91,448,262,-880,645,1492,1627,2900,3888,1910,610,1588,93,-2078,-1605,-1214,-1796,-813,330,169,-20,336,510,36,-234,-390,-689,-601,-423,-516,-448,-199,-203,-509,-704,-562,-368,-349,-282,-76,49,79,45,-23,-136,-263,-292,-290,-308,-294,-281,-275,-228,-183,-197,-158,-78,-68,-83,-42,-8,-18,-38,-53,-73,-127,-188,-220,-224,-202,-159,-127,-129,-119,-103,-81,-65,-48,-31,-36,-16,-11,-27,-42,-56,-88,-138,-158,-172,-180,-170,-161,-146,-112,-60,-22,0,3,-17,-37,0,0,0,0,0,0,0,0,0,0,0,0}, + {116,-197,199,1378,14950,5372,-19967,-6418,7991,4281,1581,19625,21034,-5281,-4670,3557,-4224,-8157,-7258,-10748,-7080,-2874,-1888,-1374,-1997,1924,1988,1334,4082,5609,2772,1277,2142,1182,-1426,-4062,-4262,-4627,-4506,-4236,-2753,-287,1134,1251,922,1093,1424,1531,1260,1237,870,60,-242,-186,-693,-1262,-1334,-1574,-1763,-1186,-339,-5,70,283,478,504,600,813,607,92,-159,-210,-486,-445,-152,-240,-487,-462,-268,-241,-58,230,232,35,-55,7,212,366,284,-92,-443,-483,-406,-268,-158,-179,-394,-516,-291,83,258,131,-44,-163,-139,5,41,-67,-256,-369,-352,-222,-70,-18,-55,-129,-41,141,186,146,87,-35,-149,-93,45,51,12,-17,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 70 degrees, measured left/right ears + {0,0,0,0,1,2,2,1,2,0,-1,1,0,-1,3,1,-1,6,-6,14,-1,5,13,13,-4,2,27,582,1472,412,136,368,-565,544,1366,1104,2198,3875,2902,1000,1347,693,-1521,-1674,-638,-901,-980,-566,-618,-597,-193,-81,-620,-730,-345,-285,-368,-153,33,76,143,7,-340,-562,-556,-506,-563,-480,-298,-218,-137,-105,-110,-176,-200,-141,-129,-188,-214,-180,-194,-207,-208,-223,-198,-173,-143,-133,-96,-43,-53,-67,-80,-82,-128,-193,-189,-169,-149,-135,-129,-125,-126,-101,-113,-106,-73,-43,-17,-22,-15,-31,-36,-65,-124,-163,-198,-198,-197,-179,-164,-132,-86,-69,-36,-15,-19,-43,0,0,0,0,0,0,0,0,0,0,0,0}, + {-21,20,-133,4195,17381,-4118,-21438,1073,9223,1060,6071,25499,10798,-10026,461,3363,-6039,-7571,-8292,-10271,-4770,-2198,-1740,-3303,-1736,2919,1340,1522,4909,4985,1921,2061,2341,610,-2608,-4305,-4037,-4558,-4691,-4142,-1769,392,1286,1097,801,1103,1553,1468,1219,1207,536,-103,-156,-300,-992,-1356,-1398,-1683,-1613,-886,-190,-60,67,355,514,466,682,921,486,-56,-119,-259,-545,-333,-116,-364,-573,-435,-276,-207,77,296,152,-17,-28,75,250,335,157,-248,-482,-438,-330,-213,-147,-246,-483,-518,-171,187,209,31,-113,-179,-103,41,27,-129,-303,-396,-326,-166,-32,-26,-107,-145,-10,156,158,135,54,-84,-129,-22,76,28,-43,-97,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 75 degrees, measured left/right ears + {0,0,-1,-1,0,0,1,1,2,1,0,0,0,0,0,0,-1,0,3,-6,15,3,-6,19,13,-5,-3,13,281,1330,919,-10,608,124,-172,806,1366,1921,3496,3618,1507,1019,1166,-322,-1081,-599,-1161,-1951,-1450,-952,-1068,-996,-737,-762,-571,-28,155,108,249,464,488,307,7,-309,-535,-692,-730,-753,-702,-536,-380,-253,-178,-102,-54,-24,-5,-21,-85,-132,-125,-160,-223,-249,-276,-279,-234,-180,-158,-137,-92,-71,-83,-87,-88,-91,-107,-128,-120,-130,-135,-121,-127,-139,-148,-136,-100,-55,-25,-24,-25,-27,-35,-72,-104,-134,-173,-194,-203,-183,-166,-134,-114,-114,-83,-53,-27,-40,0,0,0,0,0,0,0,0,0,0,0,0}, + {-176,270,-431,7424,17046,-12260,-19326,6706,8448,-860,12085,26119,906,-9926,4561,2537,-7126,-7332,-8828,-9327,-3011,-1682,-3033,-4861,-363,3199,664,2396,5348,3856,1557,2657,1952,-509,-2916,-3470,-3705,-4904,-4686,-3371,-1263,460,1243,830,603,1200,1647,1337,1257,1215,278,-239,-24,-350,-1199,-1358,-1420,-1720,-1466,-625,-136,-175,-44,435,542,463,775,920,411,-82,-85,-355,-518,-168,-125,-501,-628,-385,-280,-168,198,295,83,-48,13,114,272,320,29,-357,-479,-344,-221,-160,-170,-343,-546,-443,-43,232,124,-51,-161,-180,-53,54,9,-174,-338,-390,-273,-102,12,-9,-160,-183,26,178,155,103,17,-106,-84,69,88,-18,-94,-129,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 80 degrees, measured left/right ears + {0,-1,-1,-1,-1,-1,0,-1,1,0,0,-1,0,2,0,0,-1,-1,1,1,1,11,1,-2,30,9,-14,-11,-1,160,1113,1465,446,194,27,-13,824,1278,1675,3090,3838,2251,1515,1957,403,-1510,-1616,-1695,-2315,-2118,-1638,-1552,-1347,-850,-464,-165,368,668,559,572,732,644,261,-118,-385,-653,-874,-963,-944,-852,-653,-459,-288,-83,35,101,101,78,53,-29,-72,-121,-188,-296,-320,-295,-307,-264,-232,-196,-165,-115,-87,-93,-53,-14,-14,-68,-103,-105,-121,-137,-148,-158,-169,-150,-113,-91,-62,-38,-28,-49,-63,-69,-91,-110,-143,-172,-188,-174,-156,-161,-148,-131,-124,-107,-69,-33,0,0,0,0,0,0,0,0,0,0,0,0}, + {-280,436,-554,10004,15367,-17574,-16314,10087,7182,-1280,16883,23784,-6108,-7995,7633,1713,-8023,-6816,-8944,-8650,-1614,-1581,-5004,-5627,1340,2906,-126,3603,5662,2695,1429,2905,1021,-1463,-2472,-2527,-3575,-4844,-4278,-3046,-880,539,749,487,639,1193,1491,1301,1400,1071,64,-199,99,-414,-1178,-1325,-1501,-1686,-1315,-484,-174,-271,-105,406,519,489,841,915,316,-58,-80,-402,-447,-70,-153,-602,-636,-351,-258,-117,231,250,19,-60,23,122,300,283,-49,-426,-454,-270,-161,-106,-187,-414,-594,-378,53,222,54,-125,-220,-191,-18,70,-36,-215,-358,-354,-207,-57,23,-52,-197,-175,61,178,122,74,-21,-116,-59,93,75,-45,-109,-165,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 85 degrees, measured left/right ears + {1,0,-1,-1,-1,0,0,0,1,2,2,1,1,1,0,1,-2,-1,0,3,3,-4,14,8,7,23,2,-30,-9,54,293,1401,1473,-87,212,798,226,514,1106,1445,2691,4504,3838,1831,1138,-114,-2028,-2186,-2022,-2869,-2806,-1941,-1483,-1233,-654,-23,360,743,1022,905,727,744,554,114,-338,-596,-786,-1048,-1112,-1025,-908,-687,-390,-120,44,148,191,168,111,82,21,-110,-191,-249,-305,-325,-318,-320,-316,-267,-211,-173,-114,-43,-17,4,35,7,-49,-87,-116,-130,-149,-163,-170,-157,-130,-113,-104,-90,-51,-37,-62,-74,-88,-101,-113,-125,-152,-165,-145,-157,-167,-163,-154,-130,-78,-25,0,0,0,0,0,0,0,0,0,0,0,0}, + {-329,516,-589,11258,14119,-20135,-14312,11778,6384,-1031,19298,21206,-10200,-6273,10222,1278,-8867,-5915,-8809,-8480,-558,-1790,-7025,-5650,2667,2098,-277,4354,5522,2451,1296,2619,90,-1921,-1853,-1920,-3506,-4399,-3570,-2943,-842,600,487,-9,558,1256,1225,1215,1499,963,-88,-101,268,-424,-1121,-1201,-1503,-1740,-1185,-358,-256,-345,-125,336,464,514,865,889,281,-53,-84,-379,-393,-22,-170,-633,-599,-303,-232,-91,254,179,-56,-69,22,144,300,251,-91,-421,-420,-253,-110,-45,-167,-455,-614,-333,98,220,2,-179,-261,-198,-4,65,-51,-234,-337,-307,-184,-31,26,-72,-192,-142,66,173,135,56,-58,-150,-56,93,77,-38,-125,-183,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 90 degrees, measured left/right ears + {0,-1,-1,-1,-1,-1,-1,0,-1,1,0,-1,1,0,-1,0,-3,-2,-2,3,1,-3,5,17,8,1,14,-17,-17,142,652,557,356,1077,804,509,932,639,379,581,1414,3573,5326,3672,748,-99,-453,-1911,-2745,-2775,-3069,-2714,-1804,-1237,-863,-252,404,726,1007,1192,1025,678,534,361,-178,-598,-774,-892,-1080,-1175,-1030,-821,-496,-222,-30,127,197,220,167,118,30,-50,-129,-220,-251,-323,-346,-341,-344,-352,-298,-175,-99,-45,-14,15,41,37,-16,-73,-89,-103,-130,-168,-193,-164,-147,-163,-151,-116,-74,-54,-51,-73,-98,-93,-104,-114,-126,-133,-138,-155,-170,-195,-172,-112,-56,-26,0,0,0,0,0,0,0,0,0,0,0,0}, + {-335,531,-666,11016,14274,-20450,-14263,12368,6401,-801,19447,19852,-12004,-5756,12468,1733,-9639,-5131,-8237,-8810,85,-2066,-8668,-5494,3117,1712,-260,4570,5301,2338,1627,2189,-842,-1992,-1338,-1702,-3319,-3868,-3063,-2585,-812,342,377,-215,265,1103,1114,1065,1393,929,-46,-95,322,-262,-1020,-1130,-1409,-1717,-1222,-280,-226,-397,-211,273,410,477,842,837,272,-36,-70,-360,-378,3,-131,-616,-560,-251,-219,-103,254,128,-151,-100,40,131,284,246,-105,-429,-382,-195,-60,-30,-174,-450,-620,-324,100,208,-37,-213,-289,-228,-13,73,-31,-230,-347,-326,-174,2,46,-72,-203,-152,84,193,130,18,-104,-176,-72,82,65,-52,-127,-156,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 95 degrees, measured left/right ears + {-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,1,0,0,1,-1,-3,-2,-2,2,-3,1,6,11,9,12,-10,-2,49,554,765,-72,-138,776,1294,1027,825,1467,1419,-467,26,2826,4048,3905,2227,55,-618,-625,-1994,-3244,-3004,-2552,-2270,-1626,-746,-351,-7,597,984,1137,1103,862,493,290,-9,-454,-774,-829,-853,-1084,-1087,-841,-556,-363,-162,37,146,197,150,86,47,19,-45,-155,-243,-300,-311,-351,-396,-373,-294,-183,-111,-58,-24,7,18,6,-21,-52,-38,-56,-128,-171,-187,-200,-199,-175,-154,-144,-109,-87,-76,-61,-71,-100,-124,-125,-108,-110,-132,-155,-164,-164,-151,-100,-46,-28,0,0,0,0,0,0,0,0,0,0,0,0}, + {-302,463,-692,9276,15697,-18346,-16300,11923,7260,-853,17710,19991,-11665,-6850,14080,3568,-10173,-4957,-7112,-9372,91,-2034,-9688,-5798,2744,2048,-209,4127,5276,2409,1691,2229,-1291,-2356,-868,-1539,-3133,-3529,-2644,-2285,-687,297,79,-390,276,862,797,991,1299,836,16,-51,310,-144,-877,-985,-1340,-1652,-1221,-308,-179,-379,-300,197,373,431,767,758,274,-18,-46,-329,-390,8,-54,-538,-531,-232,-174,-132,204,113,-172,-177,-1,117,257,252,-88,-394,-344,-157,-36,-8,-172,-446,-595,-321,67,182,-38,-240,-327,-231,-6,96,-31,-262,-368,-325,-158,27,68,-79,-203,-129,94,182,102,-7,-105,-187,-108,35,40,-37,-102,-136,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 100 degrees, measured left/right ears + {1,0,-1,-1,0,0,0,0,0,0,0,1,2,1,3,1,1,-1,1,1,-1,4,10,5,14,11,6,-2,443,965,148,-379,298,587,543,1101,1862,2206,1974,24,-1028,1320,2929,2420,2028,1455,-37,-819,-904,-2089,-2978,-2560,-2038,-1748,-1055,-440,-237,178,790,1023,923,828,643,267,-76,-342,-602,-694,-747,-827,-891,-803,-608,-452,-276,-106,33,66,48,81,95,74,-1,-110,-204,-240,-267,-354,-390,-310,-221,-199,-146,-69,-30,-35,-42,-25,-14,-21,-29,-46,-86,-153,-207,-215,-192,-161,-148,-162,-157,-109,-70,-65,-75,-88,-114,-123,-114,-118,-124,-110,-104,-111,-97,-81,-52,-30,0,0,0,0,0,0,0,0,0,0,0,0}, + {-180,258,-491,6236,17321,-13108,-19957,9776,9141,-1047,14315,21126,-8941,-9433,14288,7077,-9974,-5756,-5587,-9782,-719,-1488,-10054,-6717,1744,2686,44,3280,5205,2694,1794,2172,-1098,-2599,-885,-1305,-2716,-3507,-2489,-1874,-715,308,108,-540,38,840,683,705,1133,916,48,-141,294,-9,-777,-853,-1190,-1572,-1227,-300,-154,-365,-300,123,294,362,696,716,264,-41,-9,-247,-404,-33,47,-447,-503,-233,-145,-154,165,130,-173,-202,-66,63,218,284,-7,-338,-331,-149,-11,27,-148,-420,-596,-339,45,183,-40,-259,-307,-224,-2,89,-44,-271,-358,-290,-166,-6,78,-25,-146,-129,47,143,117,21,-110,-208,-147,25,51,-22,-83,-111,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 105 degrees, measured left/right ears + {1,0,2,1,0,2,0,0,1,0,0,0,0,2,1,1,1,1,0,1,-2,13,-1,9,14,13,1,296,1079,478,-494,97,562,321,323,1018,2638,3235,1501,194,-118,-60,773,1232,1123,1205,1073,92,-864,-1083,-1578,-2313,-2070,-1364,-1182,-932,-485,5,370,586,728,692,562,286,-46,-316,-420,-469,-568,-630,-632,-624,-610,-512,-344,-262,-206,-105,3,52,83,84,-8,-85,-133,-178,-259,-279,-251,-246,-219,-174,-128,-111,-106,-86,-79,-42,-10,-41,-67,-59,-76,-142,-174,-174,-165,-159,-175,-185,-166,-119,-83,-86,-93,-85,-91,-124,-140,-124,-90,-53,-46,-48,-61,-61,-57,-55,0,0,0,0,0,0,0,0,0,0,0,0}, + {32,-98,33,2623,17173,-4233,-23233,4501,11818,-564,9169,22076,-3299,-12545,11944,11845,-7956,-7704,-4056,-9512,-2548,-526,-9555,-8195,191,3086,575,2252,5006,3126,1858,2324,-581,-2892,-936,-1073,-2339,-3313,-2694,-1699,-709,264,138,-424,-173,598,742,684,827,863,256,-228,77,116,-647,-818,-1049,-1380,-1228,-397,-58,-312,-340,47,260,263,572,708,309,-98,-18,-144,-373,-126,120,-327,-517,-267,-133,-152,102,166,-154,-240,-100,1,157,304,82,-262,-343,-156,-13,45,-121,-381,-563,-413,-18,171,9,-240,-287,-227,-93,51,6,-192,-344,-346,-209,-41,109,37,-135,-178,-10,156,128,6,-127,-199,-146,7,59,-9,-75,-83,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 110 degrees, measured left/right ears + {0,0,1,1,1,1,0,0,0,0,-1,1,0,0,3,1,1,2,3,-4,4,11,-2,10,14,10,170,1106,889,-544,-176,636,335,79,727,2240,2955,2065,1332,715,114,-278,-904,-439,458,640,896,923,246,-565,-822,-1032,-1411,-1497,-1243,-1053,-812,-310,-30,125,333,479,372,127,14,-93,-251,-317,-317,-378,-475,-472,-460,-469,-505,-455,-319,-226,-85,-19,-5,3,-12,-55,-126,-121,-107,-146,-186,-190,-167,-152,-130,-165,-171,-130,-78,-60,-88,-79,-106,-120,-95,-82,-98,-121,-141,-187,-206,-180,-148,-135,-119,-100,-99,-98,-120,-132,-114,-82,-60,-34,-10,-4,-18,-48,-73,-97,0,0,0,0,0,0,0,0,0,0,0,0}, + {223,-394,520,-23,13468,6429,-22276,-4648,13466,2211,2993,20576,5183,-14015,6317,16063,-2923,-10018,-3656,-7877,-5137,-52,-7700,-9750,-2074,2987,1310,1264,4505,3730,1959,2359,551,-3014,-1640,-485,-1837,-3210,-2920,-1694,-873,163,204,-306,-256,454,682,696,801,764,333,-166,-132,63,-530,-810,-897,-1185,-1189,-537,-1,-167,-350,-120,258,227,417,663,432,-91,-100,-42,-292,-225,101,-177,-532,-348,-125,-129,23,182,-85,-259,-128,20,101,260,167,-152,-319,-190,-34,25,-80,-304,-511,-478,-130,153,92,-164,-299,-304,-144,70,98,-124,-352,-399,-238,-28,80,19,-127,-160,-27,127,95,-7,-76,-139,-150,-22,75,29,-46,-69,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 115 degrees, measured left/right ears + {1,1,1,3,1,2,2,0,1,0,1,2,-1,1,3,1,2,3,5,-4,9,2,11,5,27,72,1032,1344,-434,-554,636,448,-30,519,2287,3259,1959,887,939,874,118,-942,-1297,-1181,-674,194,581,827,1121,557,-247,-187,-357,-1170,-1492,-1103,-770,-780,-539,-215,-61,35,67,11,41,122,25,-118,-148,-160,-276,-353,-380,-465,-530,-510,-390,-283,-233,-161,-111,-87,-92,-68,-13,24,7,-70,-136,-116,-94,-139,-172,-172,-169,-158,-130,-118,-148,-175,-157,-111,-81,-62,-43,-74,-140,-196,-195,-165,-150,-130,-127,-125,-122,-132,-135,-109,-66,-42,-34,-25,5,23,-3,-49,-98,-124,0,0,0,0,0,0,0,0,0,0,0,0}, + {190,-300,390,-558,6871,13993,-13693,-14945,10424,7614,-1319,14160,14286,-10705,-1801,16939,4937,-10370,-5564,-5169,-7056,-1350,-4800,-10104,-5201,1957,2247,513,3459,4362,2352,2092,1744,-2038,-2832,-561,-864,-2810,-3358,-1833,-993,-211,183,-90,-315,268,767,672,705,874,496,-187,-268,-25,-457,-898,-792,-945,-1129,-734,-16,-20,-269,-248,153,256,278,574,543,25,-182,0,-178,-305,-17,-66,-505,-448,-160,-117,-75,155,33,-217,-155,29,95,177,208,-21,-267,-243,-92,-8,-59,-229,-430,-522,-246,96,140,-149,-310,-271,-138,56,89,-78,-297,-347,-268,-134,-18,10,-61,-133,-96,37,84,40,-17,-92,-143,-55,87,77,-13,-66,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 120 degrees, measured left/right ears + {1,1,1,3,2,1,0,-1,0,0,1,1,-1,2,1,2,1,8,-3,9,-5,16,-4,39,23,869,1751,-115,-974,491,641,-129,313,2483,3671,2096,886,829,354,33,-471,-1274,-1339,-1105,-1065,-584,303,927,1071,1131,1055,429,-153,-517,-1041,-1184,-982,-928,-914,-684,-477,-405,-328,-68,155,210,227,149,48,-26,-130,-311,-390,-395,-414,-451,-467,-402,-332,-280,-279,-246,-84,51,71,59,40,3,-44,-71,-74,-96,-143,-175,-183,-188,-188,-215,-243,-217,-151,-95,-84,-48,-39,-87,-134,-164,-162,-150,-137,-126,-126,-154,-167,-142,-108,-69,-47,-42,-20,7,10,-4,-30,-69,-110,-134,0,0,0,0,0,0,0,0,0,0,0,0}, + {-50,113,-206,216,1171,13676,555,-19514,563,12151,148,3983,18232,-526,-8836,12129,12970,-6087,-9157,-3437,-6534,-4268,-2879,-8152,-8001,-820,2973,593,1769,4478,3303,1818,2120,-29,-3106,-1674,-415,-1759,-3343,-2450,-1183,-511,-64,-45,-134,29,698,819,646,806,807,34,-443,-220,-262,-904,-921,-785,-954,-899,-238,102,-144,-241,7,265,176,409,613,257,-175,-42,-55,-327,-214,-46,-389,-555,-271,-123,-147,53,142,-91,-157,5,107,139,207,80,-178,-294,-167,-63,-53,-172,-345,-484,-367,-71,52,-55,-200,-195,-170,-57,54,20,-156,-329,-356,-242,-85,11,-49,-164,-170,-7,110,68,11,-47,-97,-69,70,104,12,-47,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 125 degrees, measured left/right ears + {1,1,2,1,1,0,-1,0,-1,-1,-2,-1,1,-2,1,-4,8,-6,6,-5,10,-3,26,16,674,2053,375,-1359,205,826,-130,79,2608,4260,2342,783,934,328,-298,-961,-1665,-1263,-954,-1099,-907,-600,95,721,984,1417,1577,957,120,-267,-376,-852,-1215,-1099,-1054,-1104,-1001,-818,-500,-100,145,253,329,379,254,4,-129,-197,-287,-328,-373,-426,-465,-459,-440,-468,-378,-158,-28,12,33,72,68,11,12,26,-20,-95,-124,-177,-198,-205,-268,-308,-281,-182,-149,-126,-71,-56,-84,-132,-131,-128,-112,-100,-119,-143,-164,-154,-157,-134,-85,-54,-45,-42,-6,0,-23,-46,-74,-97,-119,-129,0,0,0,0,0,0,0,0,0,0,0,0}, + {-133,219,-310,363,-484,6637,11530,-12096,-11947,9746,6944,-2743,11676,12332,-8032,1950,16447,3166,-10723,-5212,-3657,-6464,-3678,-5239,-8365,-4691,1952,1751,200,3497,4288,2294,1657,1541,-1550,-2673,-1016,-1004,-2505,-2864,-1675,-962,-297,-172,-75,0,465,892,744,703,914,460,-357,-456,-186,-611,-1060,-887,-829,-881,-569,5,12,-136,-72,229,193,154,499,547,42,-134,-7,-256,-402,-166,-224,-585,-477,-174,-144,-91,145,86,-79,-17,108,120,182,146,-75,-277,-267,-124,-62,-114,-275,-427,-505,-295,11,80,-89,-204,-206,-118,57,102,-94,-329,-372,-262,-158,-100,-92,-159,-167,-56,90,99,35,-7,-39,-51,21,100,55,-39,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 130 degrees, measured left/right ears + {1,2,2,1,0,-1,0,-1,1,-1,-2,1,-2,4,-3,4,1,2,0,6,6,13,25,491,2248,998,-1646,-247,980,-54,-140,2737,4890,2625,728,1083,310,-510,-1069,-2132,-1997,-1179,-946,-921,-564,130,197,283,1146,1550,1162,943,642,135,-223,-496,-869,-1276,-1327,-1332,-1395,-1040,-470,-172,5,284,473,342,234,171,13,-130,-215,-288,-400,-413,-411,-506,-558,-392,-207,-165,-139,-60,35,26,12,81,115,77,-18,-103,-144,-160,-166,-236,-310,-306,-255,-187,-150,-124,-95,-99,-129,-160,-126,-76,-52,-65,-119,-159,-166,-137,-111,-87,-73,-66,-42,-31,-30,-45,-72,-92,-109,-106,-104,-112,0,0,0,0,0,0,0,0,0,0,0,0}, + {41,-81,130,-211,249,578,10869,3222,-15834,-1745,11507,324,-319,15663,4010,-6362,10895,12916,-5579,-9573,-2103,-5075,-6442,-3962,-6442,-7069,-1401,2459,230,1220,4572,3461,1486,1665,646,-2148,-1921,-1013,-1697,-2638,-2082,-1339,-951,-314,-93,-36,217,793,912,702,813,803,55,-500,-284,-270,-892,-1019,-863,-849,-792,-290,75,-8,-69,122,300,115,222,543,408,-49,-55,-124,-443,-396,-178,-412,-628,-361,-144,-157,47,221,65,-22,93,156,141,169,41,-184,-308,-186,-62,-92,-261,-430,-470,-364,-95,49,-52,-172,-145,-54,6,34,-34,-199,-315,-329,-238,-190,-144,-103,-130,-110,27,135,81,31,27,-10,-18,72,87,-30,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 135 degrees, measured left/right ears + {3,0,0,-1,-1,-1,-1,-1,-1,-3,1,-1,0,-2,2,2,-3,2,-5,17,-7,44,337,2314,1682,-1770,-816,1054,49,-333,2888,5560,2932,611,1246,436,-771,-1212,-2378,-2558,-1502,-1221,-1253,-635,354,521,340,796,1073,911,796,724,682,481,5,-340,-625,-1128,-1554,-1588,-1318,-923,-611,-282,-3,157,309,357,325,248,66,-87,-189,-307,-390,-432,-425,-398,-364,-283,-219,-229,-178,-128,-95,-25,86,148,95,17,-47,-120,-148,-118,-160,-250,-288,-250,-202,-201,-176,-140,-150,-168,-171,-149,-98,-42,-39,-96,-147,-147,-119,-100,-65,-47,-68,-86,-73,-56,-81,-112,-129,-131,-116,-102,-93,-98,0,0,0,0,0,0,0,0,0,0,0,0}, + {53,-79,97,-111,113,-199,3242,11060,-4614,-12920,5621,8287,-4177,4946,15135,-1389,-652,14743,5605,-9948,-5477,-1440,-7134,-5995,-4086,-6973,-4891,757,1513,-237,2632,4731,2396,1121,1575,-215,-2089,-1375,-1318,-2096,-2299,-1618,-1313,-957,-284,-76,21,483,955,855,717,840,549,-154,-396,-191,-501,-988,-892,-836,-870,-642,-135,37,-7,28,256,288,153,331,463,160,-93,-21,-275,-541,-356,-268,-572,-569,-239,-134,-83,188,224,47,58,167,142,117,116,-59,-219,-218,-152,-187,-238,-289,-358,-404,-309,-121,-21,-50,-65,-53,-49,-6,1,-98,-267,-348,-313,-221,-155,-106,-106,-121,-32,98,125,72,52,37,-16,-11,48,20,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 140 degrees, measured left/right ears + {1,0,-1,-2,-1,-1,-1,0,-2,-1,0,0,0,-1,5,-5,8,-13,22,-17,58,225,2314,2352,-1737,-1447,1055,205,-546,3039,6299,3275,487,1381,554,-971,-1323,-2607,-3085,-1806,-1346,-1490,-1001,176,741,572,1081,1325,628,278,511,497,364,409,345,-199,-751,-1025,-1380,-1436,-1038,-779,-647,-487,-133,126,197,336,308,159,50,-41,-238,-363,-301,-240,-317,-336,-213,-191,-251,-265,-225,-180,-126,-12,90,85,30,-32,-116,-123,-76,-105,-199,-223,-168,-163,-187,-190,-174,-191,-210,-193,-169,-113,-53,-55,-119,-146,-126,-93,-39,-6,-24,-76,-102,-90,-84,-110,-142,-142,-144,-138,-106,-86,-85,-99,0,0,0,0,0,0,0,0,0,0,0,0}, + {-53,80,-115,141,-196,239,-232,5809,8409,-9083,-7461,8812,2867,-4882,9929,12148,-3026,5152,13618,-1474,-9506,-1812,-3273,-8477,-4734,-4574,-6767,-2597,1477,434,261,3838,3984,1568,1185,1198,-806,-1769,-1142,-1529,-2025,-2033,-1514,-1325,-830,-350,-180,166,726,949,739,785,834,375,-198,-285,-248,-688,-957,-754,-734,-800,-576,-106,-23,-16,138,347,267,197,373,282,-87,-130,-34,-363,-558,-352,-377,-604,-417,-124,-120,-40,234,203,83,120,135,66,102,105,-92,-262,-251,-161,-164,-229,-337,-430,-442,-266,-47,6,-59,-48,-14,-25,-53,-97,-198,-295,-303,-238,-172,-154,-112,-93,-60,23,107,107,64,43,-8,-50,-9,29,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 145 degrees, measured left/right ears + {0,-3,-3,-2,-3,-1,-2,-2,-3,0,-1,0,-3,6,-11,14,-21,27,-30,63,148,2273,2986,-1603,-2110,969,404,-747,3204,7097,3560,353,1607,644,-1294,-1416,-2702,-3620,-2176,-1401,-1714,-1267,126,706,476,1263,1651,883,361,253,91,66,133,216,165,-215,-753,-1057,-935,-752,-783,-842,-662,-375,-175,-20,97,155,113,41,-52,-185,-155,-78,-165,-272,-238,-138,-134,-218,-261,-238,-212,-194,-132,-39,-2,-23,-61,-102,-117,-79,-91,-153,-164,-114,-105,-147,-155,-143,-181,-228,-214,-192,-146,-105,-116,-154,-171,-147,-75,13,42,-1,-83,-129,-120,-102,-116,-145,-157,-164,-159,-122,-90,-86,-103,-116,0,0,0,0,0,0,0,0,0,0,0,0}, + {9,-34,48,-76,101,-152,179,257,7360,4906,-10277,-2066,8086,-1866,-2476,12847,8769,-1897,8775,9430,-5509,-6458,-596,-6036,-8041,-3689,-5399,-5574,-1078,1226,-25,1254,4379,2897,1093,1282,869,-1211,-1481,-986,-1441,-1846,-1874,-1503,-1417,-729,-453,-264,270,837,904,695,841,863,325,-211,-237,-343,-796,-800,-612,-675,-718,-459,-164,-95,57,223,323,168,187,331,167,-216,-210,-147,-400,-447,-300,-422,-535,-264,-76,-123,7,232,168,102,128,91,20,61,12,-109,-146,-126,-174,-273,-342,-390,-410,-360,-191,-39,-3,-31,-28,-53,-90,-118,-143,-194,-227,-228,-206,-181,-136,-68,-46,-25,44,94,64,28,4,-26,-44,-12,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 150 degrees, measured left/right ears + {-1,-3,-1,-2,-3,-1,-3,-3,0,-2,4,-6,9,-15,15,-24,33,-35,62,91,2210,3574,-1358,-2763,770,650,-923,3330,7987,3846,133,1870,869,-1697,-1634,-2693,-4095,-2571,-1447,-1896,-1506,42,780,486,1227,1797,1047,406,463,212,-273,-257,-45,-114,-362,-435,-638,-703,-429,-401,-514,-560,-423,-293,-275,-155,-67,-118,-246,-188,-50,10,-14,-58,-141,-190,-84,-62,-131,-182,-173,-209,-259,-167,-68,-116,-165,-117,-135,-163,-94,-65,-121,-138,-87,-90,-122,-78,-71,-130,-161,-183,-196,-176,-153,-170,-217,-212,-149,-66,13,54,5,-94,-150,-133,-93,-90,-123,-159,-169,-157,-124,-97,-101,-111,-114,-97,0,0,0,0,0,0,0,0,0,0,0,0}, + {12,-10,-4,13,-37,50,-85,74,950,7867,1849,-9158,1426,5057,-4049,887,13529,6462,370,9442,4968,-6182,-3565,-1722,-7774,-6503,-3670,-5692,-4085,-498,733,169,2294,4138,1968,914,1340,438,-1328,-1182,-998,-1139,-1581,-1764,-1641,-1508,-711,-549,-325,300,858,879,729,872,880,320,-209,-228,-373,-755,-689,-575,-609,-621,-334,-132,-101,49,140,157,63,160,218,24,-210,-162,-219,-450,-352,-200,-380,-412,-176,-96,-148,30,191,119,110,87,-36,-37,120,106,-32,-147,-195,-257,-305,-344,-392,-385,-286,-128,-57,-60,-58,-55,-97,-129,-113,-106,-149,-190,-211,-187,-151,-86,-32,-24,-16,23,46,16,8,-8,-56,-60,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 155 degrees, measured left/right ears + {-3,-2,-2,-1,0,-3,-2,3,-1,4,-6,11,-17,18,-25,32,-30,59,53,2133,4095,-1033,-3363,486,882,-1043,3412,8902,4175,-138,2127,1154,-2057,-1998,-2646,-4467,-3080,-1446,-2013,-1779,11,867,431,1269,2000,1120,360,460,325,-162,-293,-333,-458,-599,-678,-722,-585,-208,11,-82,-164,-155,-211,-299,-244,-260,-477,-531,-264,-119,-152,-24,37,-66,-131,-29,57,-38,-118,-116,-153,-200,-149,-99,-147,-186,-216,-288,-283,-106,-15,-121,-157,-107,-75,-75,-46,-10,-41,-84,-125,-181,-194,-162,-172,-226,-240,-190,-100,-10,23,-46,-151,-175,-119,-58,-55,-93,-140,-164,-144,-116,-101,-106,-130,-133,-101,-48,0,0,0,0,0,0,0,0,0,0,0,0}, + {-12,25,-27,18,-17,3,3,-20,-1,1592,7638,-111,-7013,2433,1929,-3859,3438,12907,5687,2213,8024,2063,-4940,-2265,-3677,-7768,-5243,-4241,-5200,-2976,-453,442,708,2916,3463,1454,1060,1126,-52,-1064,-952,-1025,-905,-1249,-1584,-1892,-1574,-779,-671,-289,362,793,791,824,983,826,245,-86,-112,-444,-713,-569,-529,-535,-489,-241,-103,-79,-78,-52,-23,-66,50,138,31,-108,-36,-217,-469,-327,-140,-237,-258,-174,-172,-154,43,118,5,17,69,72,84,108,30,-75,-138,-195,-265,-309,-321,-298,-312,-289,-210,-123,-74,-59,-50,-99,-115,-96,-87,-121,-154,-169,-150,-103,-54,-23,-18,-12,7,-4,-18,-19,-18,-39,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 160 degrees, measured left/right ears + {-3,-2,-1,-2,-3,-4,2,0,6,-7,13,-18,18,-26,33,-31,62,31,2076,4538,-694,-3863,125,1086,-1108,3465,9851,4533,-442,2386,1455,-2365,-2425,-2708,-4694,-3586,-1558,-2067,-2044,21,992,405,1256,2133,1326,389,372,312,-253,-298,-203,-589,-884,-853,-1098,-948,-139,313,225,93,222,196,-71,-218,-356,-491,-517,-526,-473,-285,-83,-68,-214,-161,103,155,21,-38,-29,-83,-150,-119,-21,-71,-207,-280,-369,-370,-210,-90,-143,-189,-108,-63,-80,-11,54,37,-44,-119,-170,-146,-97,-120,-190,-252,-222,-142,-65,-53,-128,-222,-232,-131,-31,-10,-46,-108,-143,-127,-92,-87,-119,-148,-154,-121,-54,13,0,0,0,0,0,0,0,0,0,0,0,0}, + {14,-19,30,-36,32,-41,34,-40,39,-56,2069,7034,-871,-5114,1662,78,-2586,4577,12065,6021,2867,5913,1004,-3390,-2567,-4944,-6779,-4927,-4609,-4278,-2404,-700,670,1176,2735,2954,1495,1042,713,-136,-892,-843,-839,-829,-1109,-1354,-1942,-1762,-965,-612,-154,318,602,746,917,1035,808,239,-21,-101,-406,-607,-461,-417,-463,-431,-271,-196,-155,-173,-227,-215,-158,-20,147,110,2,8,-164,-361,-292,-159,-193,-153,-145,-239,-276,-83,69,66,90,68,36,52,56,0,-72,-127,-174,-225,-238,-256,-288,-361,-360,-273,-160,-66,-21,-41,-108,-118,-91,-70,-66,-100,-145,-138,-94,-34,-1,-5,-44,-51,-45,-45,-19,-23,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 165 degrees, measured left/right ears + {-3,1,-2,-2,-3,2,-3,6,-8,13,-21,16,-26,29,-31,59,20,2032,4908,-346,-4252,-263,1214,-1103,3449,10731,5022,-762,2602,1787,-2635,-2836,-2829,-4931,-4038,-1695,-2086,-2344,-54,1240,408,1222,2282,1424,470,408,271,-359,-410,-247,-529,-936,-1204,-1254,-930,-420,6,275,407,474,410,215,74,28,-218,-637,-714,-554,-427,-335,-329,-333,-242,-26,95,96,49,77,38,-92,-21,78,-26,-204,-258,-349,-421,-286,-178,-260,-266,-127,-70,-51,42,84,27,-46,-103,-129,-96,-23,-19,-127,-221,-240,-202,-152,-134,-165,-270,-303,-196,-47,13,-13,-59,-104,-93,-68,-73,-108,-144,-164,-145,-78,-3,21,0,0,0,0,0,0,0,0,0,0,0,0}, + {-4,13,-19,29,-38,35,-52,54,-65,74,-81,2340,6389,-772,-4101,326,-368,-1382,4633,11636,6713,2408,4127,1228,-2521,-3486,-5084,-5900,-5111,-4471,-3390,-2254,-882,1068,1431,2227,2514,1790,1059,339,-86,-756,-847,-603,-666,-1186,-1434,-1700,-1669,-1231,-605,52,214,383,750,977,1027,723,297,56,-114,-322,-415,-333,-317,-461,-587,-409,-289,-278,-329,-258,-211,-214,-33,208,206,86,34,-175,-282,-156,-109,-239,-292,-235,-228,-244,-85,55,94,65,-16,-61,-18,69,75,-3,-93,-150,-196,-229,-267,-316,-389,-395,-309,-159,-62,-32,-50,-99,-103,-64,-21,-36,-96,-134,-127,-75,-11,4,-33,-88,-93,-77,-53,-32,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 170 degrees, measured left/right ears + {0,0,-3,-4,3,-4,6,-7,15,-22,17,-27,29,-34,55,16,2040,5198,-74,-4511,-618,1244,-1042,3455,11471,5594,-986,2739,2102,-2853,-3279,-2952,-5120,-4545,-1892,-2034,-2546,-207,1406,519,1203,2421,1590,452,376,311,-359,-510,-271,-726,-1295,-1055,-1107,-1130,-624,-136,145,256,490,494,415,613,535,-51,-485,-523,-554,-639,-569,-453,-523,-517,-194,30,48,39,56,73,72,129,179,58,-121,-240,-370,-442,-306,-176,-285,-363,-232,-103,-62,46,90,-6,-69,-68,-49,-26,23,32,-46,-143,-226,-267,-242,-192,-214,-318,-348,-229,-68,-7,-18,-42,-64,-58,-30,-35,-92,-137,-146,-139,-105,-36,-3,-39,0,0,0,0,0,0,0,0,0,0,0,0}, + {3,-5,11,-12,25,-34,33,-47,53,-67,82,-70,2399,5921,-320,-3942,-720,9,-754,4209,11699,7209,1325,3101,1895,-2433,-4150,-4608,-5429,-5330,-4030,-2675,-2383,-853,1413,1386,1795,2264,1839,1128,446,-293,-660,-684,-591,-560,-1227,-1541,-1602,-1376,-1105,-719,-68,269,405,672,849,870,752,404,145,-16,-225,-317,-297,-356,-567,-741,-574,-369,-360,-401,-274,-127,-63,77,242,229,117,42,-135,-303,-219,-116,-173,-300,-316,-257,-210,-50,37,14,-73,-77,-21,34,107,121,68,-59,-162,-229,-266,-268,-303,-384,-431,-337,-159,-46,-30,-67,-82,-64,-24,-2,-31,-83,-112,-103,-73,-26,-11,-59,-120,-117,-88,-61,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 175 degrees, measured left/right ears + {0,-3,-4,4,-3,5,-7,16,-23,19,-26,29,-37,54,10,2094,5398,131,-4603,-926,1186,-947,3482,11948,6225,-962,2781,2348,-2957,-3704,-3188,-5175,-4991,-2281,-2001,-2617,-343,1502,664,1162,2480,1847,499,262,319,-309,-526,-559,-857,-1127,-1226,-1316,-1106,-597,-247,24,100,186,430,796,927,590,250,-36,-242,-505,-662,-558,-596,-772,-749,-391,-102,-25,-42,8,75,89,190,305,190,-35,-175,-350,-430,-290,-162,-280,-361,-261,-188,-159,-32,64,-6,-64,-36,-4,32,85,96,6,-128,-217,-265,-263,-241,-276,-364,-385,-256,-91,-15,-23,-50,-55,-43,-4,2,-46,-109,-152,-138,-102,-52,-27,-60,-101,0,0,0,0,0,0,0,0,0,0,0,0}, + {-5,2,-2,9,-10,19,-28,25,-40,44,-57,73,-38,2329,5661,40,-4201,-1159,574,-643,3807,11970,7200,191,2772,2360,-2718,-4296,-4006,-5257,-5407,-3396,-2263,-2564,-638,1577,1100,1504,2279,1820,965,495,41,-753,-784,-388,-636,-1254,-1471,-1557,-1319,-799,-491,-247,91,525,622,559,800,846,553,193,27,-182,-422,-384,-435,-704,-861,-651,-440,-353,-277,-167,-72,35,256,364,201,25,-56,-207,-329,-217,-88,-153,-278,-316,-318,-280,-97,22,6,-59,-59,-17,48,140,162,78,-71,-195,-264,-265,-258,-318,-411,-426,-312,-144,-49,-31,-61,-77,-52,-9,22,-6,-70,-121,-126,-89,-46,-31,-76,-127,-117,-88,0,0,0,0,0,0,0,0,0,0,0,0} + }, + { // 180 degrees, measured left/right ears + {-3,-4,3,-4,6,-9,16,-25,19,-31,34,-46,60,-8,2200,5530,192,-4501,-1159,994,-791,3572,12125,6811,-604,2758,2477,-2946,-4064,-3530,-5220,-5273,-2800,-2070,-2631,-454,1570,847,1284,2371,1898,744,291,266,-401,-869,-519,-607,-1259,-1358,-1433,-1302,-662,-168,-84,-173,223,718,668,709,834,593,149,-154,-298,-432,-521,-623,-815,-876,-560,-307,-258,-149,9,40,62,235,376,223,-47,-141,-249,-333,-247,-136,-208,-341,-301,-266,-265,-124,53,48,-53,-68,-32,61,155,167,37,-124,-209,-254,-266,-276,-308,-389,-407,-289,-120,-33,-35,-51,-66,-41,3,26,-14,-87,-134,-143,-108,-50,-25,-76,-124,-110,0,0,0,0,0,0,0,0,0,0,0,0}, + {-3,-4,3,-4,6,-9,16,-25,19,-31,34,-46,60,-8,2200,5530,192,-4501,-1159,994,-791,3572,12125,6811,-604,2758,2477,-2946,-4064,-3530,-5220,-5273,-2800,-2070,-2631,-454,1570,847,1284,2371,1898,744,291,266,-401,-869,-519,-607,-1259,-1358,-1433,-1302,-662,-168,-84,-173,223,718,668,709,834,593,149,-154,-298,-432,-521,-623,-815,-876,-560,-307,-258,-149,9,40,62,235,376,223,-47,-141,-249,-333,-247,-136,-208,-341,-301,-266,-265,-124,53,48,-53,-68,-32,61,155,167,37,-124,-209,-254,-266,-276,-308,-389,-407,-289,-120,-33,-35,-51,-66,-41,3,26,-14,-87,-134,-143,-108,-50,-25,-76,-124,-110,0,0,0,0,0,0,0,0,0,0,0,0} + } +}; +inline constexpr std::int16_t normal48000[directions][2][taps] = { + { // 0 degrees, measured left/right ears + {10,-12,26,-27,31,-24,3,29,-82,133,-169,189,51,4864,7267,-4810,-3900,2957,-5107,64,9185,3622,3640,12917,10387,-6104,-6581,4354,-3565,-14484,-7288,562,-4544,-6604,661,2727,-56,1062,4056,3725,1523,2025,2394,112,-1047,545,1001,-983,-1665,-1087,-1199,-1990,-2674,-2550,-2190,-1752,-822,-13,115,259,766,1327,1390,975,725,606,333,-121,-258,-259,-621,-820,-680,-749,-923,-762,-554,-586,-548,-218,32,99,211,413,557,389,110,-32,-11,-57,-264,-301,-269,-363,-379,-245,-158,-178,-143,-9,-37,-224,-198,6,78,29,22,30,-69,-147,-118,-151,-196,-179,-202,-243,-192,-45,61,62,-8,-45,-33,-96,-197,-195,-156,-183,-186,-119,-63,-44,-21,-26,-56,-57,-39,-51,-66,-14}, + {10,-12,26,-27,31,-24,3,29,-82,133,-169,189,51,4864,7267,-4810,-3900,2957,-5107,64,9185,3622,3640,12917,10387,-6104,-6581,4354,-3565,-14484,-7288,562,-4544,-6604,661,2727,-56,1062,4056,3725,1523,2025,2394,112,-1047,545,1001,-983,-1665,-1087,-1199,-1990,-2674,-2550,-2190,-1752,-822,-13,115,259,766,1327,1390,975,725,606,333,-121,-258,-259,-621,-820,-680,-749,-923,-762,-554,-586,-548,-218,32,99,211,413,557,389,110,-32,-11,-57,-264,-301,-269,-363,-379,-245,-158,-178,-143,-9,-37,-224,-198,6,78,29,22,30,-69,-147,-118,-151,-196,-179,-202,-243,-192,-45,61,62,-8,-45,-33,-96,-197,-195,-156,-183,-186,-119,-63,-44,-21,-26,-56,-57,-39,-51,-66,-14} + }, + { // 5 degrees, measured left/right ears + {-5,8,-6,17,-22,26,-18,-6,30,-70,106,-134,152,63,4065,6620,-3503,-3645,2621,-4135,-759,7762,3922,3206,10919,10224,-3628,-6078,2961,-2317,-12198,-7492,-176,-3559,-5979,-257,2274,238,679,3094,3319,1531,1609,2274,715,-734,312,1198,-324,-1544,-1223,-1104,-2022,-2710,-2241,-1707,-1527,-901,13,376,371,420,765,1066,826,484,365,248,-71,-235,-273,-558,-766,-652,-634,-830,-742,-474,-417,-407,-169,98,181,229,326,382,273,58,-114,-112,-135,-277,-253,-181,-254,-305,-194,-113,-178,-164,-49,-68,-200,-180,-10,44,-24,-25,-21,-103,-152,-121,-117,-143,-149,-171,-198,-146,-44,37,72,25,-23,-41,-106,-191,-201,-169,-194,-200,-142,-94,-82,-71,-48,-52,-54,-45,-33,-7}, + {-13,31,-30,32,-18,-18,58,-120,169,-204,218,-60,4710,8706,-4682,-5472,3401,-5272,-505,10310,3955,3388,13960,11842,-6951,-8297,5056,-2862,-15865,-8401,974,-4435,-7555,483,3275,-191,756,4486,4429,1704,2182,2824,134,-1418,300,953,-1037,-1701,-1059,-1156,-1965,-2652,-2748,-2677,-2152,-1099,-343,-192,430,1276,1622,1599,1189,921,785,485,4,-242,-268,-613,-841,-699,-774,-1001,-843,-642,-674,-650,-331,-46,6,166,411,582,490,230,68,53,-3,-237,-272,-197,-375,-507,-343,-196,-230,-190,-29,-32,-227,-201,65,138,54,50,65,-29,-115,-83,-151,-237,-210,-242,-291,-247,-103,31,52,-6,-51,-46,-78,-174,-173,-127,-184,-182,-115,-66,-32,-3,22,-28,-54,-36,-54,-78,-64,-12} + }, + { // 10 degrees, measured left/right ears + {-2,-1,7,-10,19,-18,17,-9,-5,25,-56,84,-104,124,78,3528,5901,-2639,-3265,2184,-3327,-1052,6567,4041,3018,9425,9680,-2020,-5501,1884,-1483,-10298,-7378,-626,-2877,-5402,-759,1922,352,303,2442,3029,1376,1400,2307,1030,-510,188,1056,-91,-1191,-1133,-1225,-2030,-2449,-1883,-1493,-1403,-818,0,443,513,393,387,543,518,353,243,70,-183,-206,-224,-551,-758,-608,-575,-722,-605,-321,-220,-231,-58,128,180,198,199,230,147,-16,-139,-180,-197,-294,-241,-111,-171,-253,-206,-118,-119,-151,-87,-84,-186,-166,-28,39,-19,-62,-50,-101,-156,-130,-125,-149,-144,-136,-153,-143,-56,47,86,32,-37,-65,-105,-164,-172,-172,-219,-219,-170,-119,-99,-78,-56,-68,-58,-31,-5}, + {31,-29,24,1,-35,84,-157,206,-220,212,-112,4390,10153,-4104,-7332,3537,-5281,-1053,11499,4174,3339,15209,13028,-7722,-9877,5352,-2586,-16725,-8978,921,-4466,-7995,355,3429,-272,596,4552,4967,2072,2404,3205,350,-1855,-469,1207,-483,-1888,-1208,-1104,-2034,-2763,-2886,-3006,-2665,-1673,-648,31,790,1445,1790,1909,1485,1083,830,501,65,-143,-199,-652,-913,-705,-768,-1062,-911,-661,-764,-792,-403,-77,-10,149,383,598,569,333,117,48,6,-192,-224,-185,-367,-487,-384,-288,-330,-287,-81,-46,-198,-155,98,207,134,112,102,-22,-125,-98,-133,-224,-236,-271,-344,-312,-159,-19,29,-30,-75,-49,-70,-138,-130,-101,-162,-184,-119,-69,-45,16,43,-9,-50,-38,-67,-87,-55,-83,-28} + }, + { // 15 degrees, measured left/right ears + {-3,-1,-1,6,-6,12,-12,15,-8,-9,26,-51,63,-79,98,59,2888,5380,-1711,-3137,1893,-2516,-1466,5551,4065,2687,8031,9246,-552,-5053,1152,-534,-8601,-7165,-997,-2286,-4923,-1285,1536,244,-49,1970,2662,1335,1433,2309,1214,-329,127,884,-36,-876,-896,-1199,-1836,-2097,-1811,-1496,-1233,-693,-21,327,382,282,235,284,226,154,73,-37,-172,-238,-232,-433,-683,-601,-484,-529,-392,-173,-119,-138,-52,85,119,94,106,146,88,-68,-194,-187,-199,-280,-231,-135,-152,-215,-157,-88,-135,-148,-101,-96,-172,-167,-20,38,-6,-33,-65,-125,-177,-161,-152,-169,-126,-109,-128,-108,-49,27,47,-1,-52,-77,-89,-124,-159,-177,-225,-231,-166,-130,-112,-93,-66,-58,-66,-16}, + {-5,8,13,-67,122,-184,200,-189,151,-88,3586,11452,-2153,-9666,2895,-4345,-2327,12175,5145,3024,16021,14722,-7552,-11835,4924,-1759,-17406,-9911,1028,-4246,-8615,175,3801,-496,284,4484,5379,2398,2531,3867,409,-2748,-708,1916,-205,-1957,-1030,-1235,-2376,-2841,-2842,-3547,-3639,-2060,-303,475,862,1353,1932,2283,1792,1195,855,528,69,-158,-160,-616,-920,-748,-820,-1112,-903,-624,-830,-886,-459,-83,-10,121,384,648,632,334,104,87,71,-169,-227,-155,-360,-513,-403,-344,-429,-347,-79,-19,-186,-173,125,289,225,177,114,-11,-107,-75,-133,-265,-255,-292,-384,-367,-205,-30,28,-36,-109,-77,-51,-123,-120,-51,-122,-168,-121,-76,-42,4,47,-3,-52,-51,-61,-83,-60,-56,-65,-12} + }, + { // 20 degrees, measured left/right ears + {2,-5,-2,1,4,-7,10,-8,10,-1,-12,30,-46,51,-56,74,34,2241,4908,-811,-3008,1597,-1784,-1734,4561,3937,2413,6708,8757,810,-4488,589,297,-6939,-6860,-1353,-1799,-4534,-1753,1037,75,-224,1495,2373,1518,1414,2135,1364,-107,53,759,102,-657,-691,-967,-1614,-1953,-1770,-1386,-1057,-676,-227,-10,118,273,268,109,-47,-60,-11,-10,-128,-236,-236,-325,-470,-454,-415,-412,-276,-145,-113,-139,-92,33,80,70,63,75,15,-103,-195,-190,-161,-235,-249,-163,-140,-183,-161,-104,-127,-157,-99,-53,-117,-148,-39,45,-5,-64,-69,-125,-192,-179,-159,-145,-117,-98,-99,-102,-64,-22,-3,-20,-58,-54,-60,-116,-147,-157,-179,-191,-178,-129,-121,-103,-73,-82,-20}, + {-22,54,-92,131,-181,165,-107,30,23,2471,12013,1231,-11533,689,-2623,-3358,11528,6350,3350,16219,16058,-5788,-13227,3043,-773,-16816,-11576,-37,-2932,-8651,-1144,4292,8,-191,3873,5622,3177,2461,3681,416,-2703,-668,1987,359,-1695,-1198,-1210,-2417,-3079,-3217,-4252,-4503,-2080,541,669,430,1414,2287,2535,1881,1172,922,644,129,-199,-238,-654,-913,-732,-865,-1192,-945,-606,-773,-902,-485,-40,-41,76,411,683,634,341,121,35,71,-76,-174,-147,-392,-596,-513,-410,-407,-323,-86,-12,-175,-180,107,329,297,220,146,8,-90,-80,-143,-269,-288,-324,-442,-448,-247,-34,60,-8,-106,-92,-89,-126,-117,-58,-103,-156,-97,-62,-55,-8,25,-23,-77,-89,-71,-61,-14,-9,-50,2,9} + }, + { // 25 degrees, measured left/right ears + {-5,2,-1,-2,-1,4,-3,8,-3,5,5,-16,31,-39,38,-32,55,14,1611,4386,115,-2821,1180,-988,-1882,3468,3792,2184,5413,8182,2100,-3732,71,975,-5263,-6449,-1775,-1471,-4083,-2197,412,14,-287,1106,2191,1557,1324,2008,1460,105,52,764,327,-514,-720,-859,-1288,-1716,-1609,-1283,-1173,-931,-526,-211,7,131,142,27,-105,-115,13,111,-55,-201,-124,-164,-334,-367,-374,-449,-360,-158,-95,-156,-105,40,64,5,-6,34,6,-95,-164,-156,-151,-220,-233,-168,-162,-205,-170,-117,-129,-130,-63,-6,-67,-119,-58,-7,-44,-77,-68,-108,-166,-171,-155,-139,-117,-103,-123,-133,-88,-30,-15,-40,-65,-49,-45,-89,-115,-110,-123,-160,-163,-154,-146,-127,-96,-19}, + {62,-108,130,-139,78,16,-110,178,1228,11306,5876,-11619,-3399,-949,-3647,9852,7365,3485,16440,17356,-3323,-13148,510,-545,-15205,-12621,-2586,-2537,-7123,-2318,3544,782,124,3292,5077,3883,2785,2464,227,-1197,-588,1243,1076,-1026,-1443,-1400,-1992,-3135,-4458,-5137,-4254,-1651,440,532,535,1517,2407,2675,1977,1171,892,718,281,-219,-335,-615,-934,-836,-881,-1194,-1031,-653,-701,-795,-447,-9,-25,25,379,701,715,363,58,-29,38,0,-128,-160,-390,-661,-589,-423,-373,-292,-102,-7,-124,-179,60,325,349,275,156,15,-79,-96,-149,-264,-291,-355,-497,-498,-286,-58,72,47,-67,-96,-98,-119,-131,-87,-105,-148,-102,-64,-45,-19,1,-38,-110,-139,-96,-38,31,62,26,12,-18,-9} + }, + { // 30 degrees, measured left/right ears + {0,-3,2,-1,-1,-2,2,-1,3,-1,-1,8,-17,27,-32,22,-9,32,2,1047,3774,988,-2515,682,-221,-1913,2368,3568,2008,4233,7425,3295,-2754,-422,1466,-3636,-5942,-2284,-1217,-3537,-2699,-178,131,-275,654,1876,1655,1303,1804,1541,412,224,739,301,-534,-707,-643,-916,-1413,-1637,-1550,-1366,-1081,-717,-429,-221,-52,37,91,82,43,109,187,75,-55,-52,-140,-356,-437,-405,-464,-441,-242,-95,-99,-105,-39,-8,-27,-9,60,48,-57,-159,-179,-150,-198,-230,-183,-176,-219,-211,-147,-111,-99,-40,9,-41,-103,-82,-46,-68,-91,-79,-95,-139,-151,-156,-159,-139,-127,-142,-148,-96,-51,-39,-50,-61,-45,-36,-48,-71,-76,-106,-142,-170,-167,-154,-143,-31}, + {-76,79,-64,-29,120,-225,299,217,9162,10387,-8661,-8305,-988,-2858,7589,8103,3601,15703,18959,86,-12312,-1846,-342,-13453,-13289,-5148,-3287,-6063,-3043,3049,1279,84,3458,5275,3586,1701,2315,1229,-1001,-636,1382,1275,-698,-1250,-1159,-1899,-3686,-5490,-5416,-3354,-1468,-454,313,1027,1766,2220,2491,2108,1411,967,621,233,-208,-299,-521,-927,-985,-923,-1178,-1154,-721,-607,-609,-426,-105,24,130,425,691,706,346,67,-20,-44,-88,-162,-175,-366,-615,-567,-397,-356,-293,-107,-4,-100,-179,41,325,356,288,190,25,-127,-140,-135,-251,-297,-350,-505,-530,-333,-82,78,87,-12,-86,-112,-131,-134,-69,-86,-169,-148,-96,-50,-26,-3,-36,-120,-165,-141,-43,61,121,84,38,1,-44,-13} + }, + { // 35 degrees, measured left/right ears + {-4,1,-1,0,0,-1,-1,2,1,1,1,-4,13,-18,20,-17,3,16,1,14,601,3036,1741,-2001,103,425,-1708,1286,3193,1951,3199,6445,4317,-1501,-813,1617,-2102,-5234,-2791,-1054,-2975,-3035,-609,124,-384,315,1626,1728,1304,1645,1705,758,190,468,304,-321,-497,-491,-887,-1462,-1728,-1636,-1447,-1302,-1000,-605,-337,-115,100,318,373,254,228,269,193,-4,-129,-226,-430,-512,-465,-484,-444,-299,-146,-106,-147,-73,17,37,29,50,79,-23,-155,-183,-154,-174,-216,-201,-193,-236,-229,-142,-104,-99,-43,27,-5,-102,-100,-55,-73,-99,-91,-96,-126,-145,-134,-137,-158,-157,-167,-143,-101,-80,-55,-39,-43,-31,-7,-21,-52,-78,-81,-123,-147,-155,-176,-43}, + {-4,41,-125,197,-272,329,-262,6094,13116,-2947,-11656,-3511,-1844,5870,7927,3761,14888,19810,3236,-9903,-3235,-994,-11286,-12723,-7986,-5157,-4940,-3800,1415,2126,799,3212,5573,3407,248,2401,2684,-823,-1047,1181,1488,-267,-900,-841,-2147,-4537,-5973,-4815,-2660,-1703,-1097,75,1263,1982,2028,2176,2152,1705,1173,548,56,-255,-222,-464,-891,-978,-1046,-1217,-1212,-795,-499,-489,-430,-213,84,327,529,695,643,333,104,-19,-152,-255,-237,-145,-323,-570,-514,-362,-296,-242,-112,-30,-99,-129,21,265,366,312,205,17,-164,-187,-174,-259,-287,-318,-442,-532,-410,-125,94,156,32,-89,-118,-137,-128,-73,-81,-163,-175,-145,-91,-29,5,-38,-122,-166,-144,-42,50,121,112,62,17,-28,8,10} + }, + { // 40 degrees, measured left/right ears + {1,-1,0,0,-1,1,-1,-2,1,2,-1,3,-3,10,-14,12,-6,-9,26,-16,35,270,2248,2265,-1293,-468,867,-1253,281,2655,1987,2350,5306,5050,-36,-1076,1409,-690,-4286,-3207,-996,-2315,-3243,-1235,53,-268,59,1331,1835,1417,1494,1617,884,226,362,463,-57,-596,-822,-1024,-1336,-1662,-1785,-1671,-1462,-1084,-615,-275,-8,289,523,575,469,313,264,183,-60,-258,-373,-485,-551,-532,-497,-456,-354,-218,-129,-92,-21,62,69,35,52,69,3,-116,-181,-156,-172,-240,-243,-210,-223,-216,-155,-101,-87,-60,-2,-17,-81,-100,-79,-72,-101,-99,-78,-105,-121,-133,-156,-165,-171,-153,-157,-137,-91,-55,-21,-27,-17,-4,-8,-48,-67,-84,-108,-135,-164,-40}, + {88,-179,221,-214,190,-182,2915,13258,4096,-12008,-7498,-1986,4755,7781,3182,13796,21295,5772,-8161,-3310,-684,-10053,-11652,-8740,-8112,-5445,-3467,-175,1256,1268,4482,5479,2024,332,3230,2877,-400,-630,474,1028,216,-275,-694,-2854,-5186,-5613,-4068,-2649,-1956,-1007,84,989,1808,1984,1974,2062,1855,1405,564,-70,-255,-214,-505,-876,-893,-1084,-1336,-1305,-767,-433,-504,-411,-137,180,363,611,775,649,337,50,-95,-259,-321,-226,-180,-340,-520,-464,-302,-266,-233,-60,18,-41,-106,-44,188,323,347,268,13,-213,-265,-224,-270,-298,-264,-371,-515,-439,-170,97,199,87,-50,-123,-151,-121,-82,-89,-178,-210,-177,-131,-42,6,-16,-98,-172,-134,-25,46,96,111,59,19,-29,-8,74,25} + }, + { // 45 degrees, measured left/right ears + {3,1,0,0,-1,-1,2,-1,-1,2,2,-3,7,-2,6,-4,5,10,-15,31,-12,36,89,1488,2436,-424,-883,1013,-612,-512,1960,2025,1773,4132,5341,1463,-1053,985,466,-3066,-3286,-1183,-1957,-3261,-1619,-25,-168,-40,1138,1837,1344,1207,1567,1166,452,267,216,-253,-792,-975,-1033,-1300,-1716,-1881,-1682,-1366,-956,-465,-124,139,448,659,687,523,331,218,48,-193,-383,-442,-506,-596,-568,-525,-475,-349,-192,-69,-45,3,70,71,66,58,52,12,-75,-154,-193,-220,-254,-242,-196,-191,-202,-157,-107,-105,-94,-49,-30,-70,-94,-58,-42,-74,-84,-72,-78,-122,-153,-152,-161,-159,-176,-165,-131,-97,-43,-14,0,-6,-6,-18,-54,-84,-85,-103,-129,-32}, + {-95,79,-11,-98,185,498,10468,10829,-8467,-11824,-3441,3404,7745,2753,10969,23026,9597,-6948,-3791,276,-8199,-10869,-8323,-10004,-7099,-3774,-1518,552,717,4371,5516,1838,878,3380,3454,478,-387,56,537,529,-193,-971,-3278,-5328,-4925,-3762,-2907,-2059,-850,464,911,1215,1696,1949,1981,1767,1531,746,-8,-248,-328,-475,-843,-954,-1032,-1407,-1463,-855,-384,-395,-389,-73,273,412,621,763,703,358,-36,-173,-297,-328,-228,-206,-324,-490,-458,-292,-278,-235,-22,106,49,-63,-78,57,245,365,306,45,-223,-331,-303,-309,-302,-232,-315,-473,-465,-238,66,223,148,2,-108,-163,-133,-81,-80,-180,-252,-249,-196,-76,7,-2,-70,-141,-133,-33,54,99,90,48,-7,-47,-32,39,99,25} + }, + { // 50 degrees, measured left/right ears + {1,1,0,2,0,1,-1,-1,-1,-1,-1,2,-2,2,-1,0,1,-6,15,-15,20,-2,22,17,835,2256,464,-1019,851,78,-979,1138,1993,1459,3042,5129,2781,-609,518,1373,-1695,-3385,-1673,-1495,-2877,-1970,-215,66,-32,738,1542,1390,1275,1620,1279,192,-337,-79,-244,-893,-1193,-1157,-1224,-1557,-1730,-1486,-1111,-709,-301,2,265,500,644,656,474,236,61,-96,-290,-467,-489,-516,-618,-597,-495,-402,-290,-142,-34,-47,-31,68,112,66,26,41,15,-90,-185,-212,-212,-238,-242,-195,-181,-202,-179,-137,-132,-126,-72,-25,-46,-76,-40,-16,-58,-80,-60,-80,-141,-160,-153,-167,-183,-170,-153,-129,-90,-48,-6,-14,-31,-41,-48,-69,-86,-73,-76,-20}, + {-101,200,-281,322,-357,5498,14511,-210,-14789,-7027,2071,7177,3301,6669,22874,15506,-4816,-5151,1151,-5480,-10566,-7493,-9804,-9546,-4566,-2447,-657,239,2997,4525,2132,1721,3639,4244,1470,1,448,99,390,-10,-1590,-3885,-5088,-4149,-3699,-3430,-2108,-507,617,950,1042,1335,1677,1810,1712,1564,951,171,-195,-352,-455,-773,-990,-1101,-1457,-1580,-1067,-373,-250,-312,-33,317,516,588,707,720,372,-13,-147,-265,-398,-336,-177,-196,-429,-519,-370,-269,-202,-43,137,135,8,-43,-16,151,325,338,129,-209,-366,-354,-348,-325,-236,-242,-403,-493,-318,7,210,213,63,-85,-154,-142,-60,-44,-142,-250,-304,-282,-172,-43,27,-9,-87,-129,-72,65,125,124,70,-27,-102,-92,28,109,74,10} + }, + { // 55 degrees, measured left/right ears + {1,1,2,1,1,1,1,-1,-1,0,0,0,0,0,1,0,-2,4,-4,14,-10,10,12,5,10,362,1794,1197,-781,475,636,-1055,302,1802,1365,2177,4481,3762,431,272,1518,-600,-2914,-1978,-1239,-2359,-2093,-428,88,-165,485,1532,1655,1259,1015,636,-70,-479,-304,-489,-1060,-1206,-1022,-964,-1217,-1381,-1182,-819,-449,-187,17,248,438,525,477,320,127,-86,-232,-334,-470,-520,-531,-552,-501,-401,-302,-232,-143,-54,-47,-19,50,72,57,12,-2,-26,-104,-159,-191,-199,-230,-260,-215,-186,-202,-194,-154,-125,-110,-70,-35,-42,-48,-26,-7,-43,-68,-69,-102,-128,-152,-164,-174,-175,-150,-138,-122,-98,-78,-60,-49,-53,-44,-41,-45,-54,-60,-14}, + {76,-38,-30,82,1032,12140,10469,-11886,-13480,-141,6418,4609,2614,18678,22324,155,-7178,975,-1792,-9394,-7839,-8389,-10821,-6067,-3301,-1869,58,714,2659,2812,1876,2897,5097,3803,539,413,675,562,-258,-2107,-3923,-5101,-4213,-3582,-3718,-2378,-434,717,1041,1072,1166,1375,1651,1617,1394,1150,487,-113,-312,-429,-662,-939,-1183,-1586,-1716,-1197,-513,-250,-190,11,316,590,597,576,670,556,125,-188,-221,-384,-454,-230,-131,-317,-522,-440,-273,-236,-94,146,212,87,-41,-64,96,292,336,210,-117,-386,-425,-387,-335,-246,-203,-328,-479,-406,-116,167,252,116,-44,-129,-154,-77,-17,-69,-196,-303,-343,-298,-152,-16,26,-27,-109,-98,36,148,162,120,4,-117,-152,-78,67,120,53,5} + }, + { // 60 degrees, measured left/right ears + {-1,0,0,1,1,1,1,-1,-1,-2,-1,-1,0,-2,0,-2,0,-5,4,2,4,-5,-2,27,-6,6,105,1192,1595,-202,68,881,-787,-375,1434,1371,1627,3734,4370,1459,-8,1432,598,-2094,-2280,-1147,-1710,-2134,-868,82,203,594,1205,1193,553,314,355,-190,-781,-683,-537,-852,-989,-714,-552,-765,-1011,-877,-552,-349,-220,-66,122,257,305,277,147,-31,-185,-272,-353,-466,-474,-413,-404,-394,-312,-235,-214,-161,-79,-41,-36,-23,22,29,-23,-41,-47,-84,-128,-187,-215,-236,-265,-227,-184,-182,-168,-134,-110,-104,-79,-37,-35,-46,-25,-17,-38,-67,-76,-75,-114,-149,-160,-174,-163,-146,-152,-151,-143,-117,-74,-49,-24,-21,-16,-28,-60,-16}, + {167,-255,294,-313,5052,15890,485,-18426,-6923,5731,6162,1220,10251,25710,10208,-8132,-1753,1947,-6130,-8601,-7067,-10683,-8578,-3570,-2838,-827,-594,265,2514,1900,2130,4352,5291,2763,878,1138,970,187,-2152,-4031,-4735,-4680,-3951,-3949,-2963,-727,799,1106,1030,1147,1243,1473,1528,1336,1213,788,100,-244,-279,-557,-970,-1141,-1487,-1827,-1534,-814,-247,-116,36,278,468,605,559,620,685,385,-47,-247,-326,-456,-375,-156,-236,-446,-460,-334,-258,-188,77,257,170,18,-71,-1,213,371,309,28,-323,-489,-450,-349,-252,-179,-236,-415,-487,-305,50,253,190,27,-100,-155,-119,-5,12,-110,-249,-349,-371,-263,-103,-8,-6,-74,-110,-14,145,189,153,76,-59,-148,-134,-19,85,71,18,2} + }, + { // 65 degrees, measured left/right ears + {3,3,3,5,4,4,5,4,4,4,3,6,6,6,4,8,4,7,7,7,16,3,8,15,33,-6,11,27,640,1590,547,-130,751,-293,-701,905,1493,1623,2751,3907,2590,641,1245,1239,-1073,-2168,-1342,-1327,-1785,-783,302,227,-29,195,531,292,-144,-264,-485,-710,-568,-423,-512,-473,-240,-162,-384,-659,-669,-470,-346,-350,-255,-63,48,79,54,-3,-91,-217,-290,-287,-297,-307,-290,-281,-275,-233,-185,-194,-180,-105,-63,-79,-74,-28,-8,-20,-39,-52,-69,-113,-173,-212,-226,-217,-187,-146,-126,-129,-118,-103,-83,-67,-54,-33,-35,-29,-9,-16,-31,-44,-58,-88,-135,-156,-168,-180,-174,-166,-155,-138,-97,-52,-18,0,4,-13,-38,-11}, + {121,-254,332,53,10348,14594,-10737,-18249,1077,8161,2911,2521,20125,22169,-2493,-7256,2949,-443,-7774,-7279,-8520,-10683,-5695,-2757,-1799,-1337,-2181,1186,2492,1090,2701,5309,4862,1807,1500,2127,1041,-1402,-3943,-4275,-4513,-4627,-4353,-3751,-1658,347,1288,1173,920,1097,1404,1551,1310,1234,1100,434,-174,-202,-264,-844,-1291,-1337,-1559,-1777,-1354,-546,-60,26,158,375,503,505,635,818,611,138,-147,-177,-389,-533,-275,-139,-330,-518,-424,-261,-239,-81,200,260,96,-39,-42,87,287,372,229,-145,-451,-484,-420,-298,-180,-149,-281,-490,-465,-177,152,253,120,-42,-155,-158,-30,48,-7,-158,-321,-375,-330,-192,-61,-18,-49,-124,-80,91,187,166,126,50,-74,-155,-76,47,53,17,-14,-7} + }, + { // 70 degrees, measured left/right ears + {0,0,0,0,1,1,3,1,2,2,0,-1,1,0,-1,2,3,-2,5,0,-2,16,-6,9,12,12,1,-8,19,249,1237,1156,13,376,129,-547,667,1367,1095,1895,3599,3571,1552,1005,1406,-85,-1843,-1463,-604,-911,-1004,-601,-583,-650,-371,-35,-294,-760,-627,-294,-302,-365,-164,24,65,132,93,-181,-476,-581,-532,-514,-566,-467,-299,-225,-149,-108,-103,-143,-203,-177,-128,-140,-199,-211,-180,-192,-208,-205,-221,-211,-184,-161,-136,-130,-82,-41,-54,-66,-79,-80,-108,-175,-198,-178,-162,-143,-134,-128,-125,-127,-102,-109,-113,-83,-58,-25,-19,-20,-17,-33,-37,-65,-121,-156,-193,-200,-197,-191,-169,-159,-116,-83,-65,-36,-15,-16,-43,-14}, + {-31,-52,84,1523,14875,9206,-19012,-13584,7227,7454,129,8146,25695,12509,-9306,-2683,4799,-2709,-7982,-7130,-9719,-9143,-3719,-2138,-1747,-3240,-2301,2466,2068,818,3468,5639,3711,1556,2330,2174,414,-2585,-4298,-4025,-4434,-4683,-4561,-3105,-687,826,1331,1005,811,1108,1538,1516,1235,1251,867,119,-177,-146,-466,-1122,-1362,-1403,-1677,-1657,-1064,-326,-69,-22,203,446,509,474,743,912,496,-27,-126,-184,-486,-477,-170,-178,-472,-563,-398,-270,-205,52,289,202,20,-41,14,150,302,317,85,-292,-485,-441,-346,-234,-156,-184,-377,-548,-418,-39,225,187,22,-113,-176,-130,13,54,-55,-217,-360,-388,-292,-136,-28,-24,-102,-147,-57,119,171,142,116,0,-107,-122,-2,74,32,-32,-99,-29} + }, + { // 75 degrees, measured left/right ears + {0,0,-1,-1,0,0,0,1,1,2,1,0,0,0,0,0,0,0,-2,3,-1,-3,18,-1,-5,19,13,2,-14,20,56,778,1450,471,71,645,53,-176,720,1316,1686,2943,3959,2583,989,1208,892,-598,-1052,-595,-1092,-1917,-1629,-1020,-1001,-1085,-861,-719,-763,-465,24,153,107,223,430,507,389,151,-152,-407,-594,-710,-732,-754,-704,-552,-406,-280,-201,-134,-73,-41,-15,-5,-29,-92,-132,-125,-150,-212,-243,-265,-284,-264,-212,-170,-156,-132,-91,-71,-81,-87,-87,-90,-97,-120,-127,-120,-134,-133,-120,-127,-138,-147,-142,-114,-74,-36,-23,-24,-26,-27,-38,-72,-103,-128,-165,-189,-202,-196,-173,-159,-123,-116,-110,-83,-54,-27,-40,-13}, + {-201,224,-279,3695,17485,2419,-23237,-7758,10789,5404,-675,14663,25947,2602,-10927,1931,5245,-4303,-8080,-7204,-10060,-7604,-2189,-1790,-3153,-4858,-1149,3239,1246,1188,4444,5193,2577,1695,2817,1593,-697,-2907,-3498,-3533,-4695,-4906,-4044,-2328,-442,867,1222,724,637,1210,1648,1393,1223,1320,693,-134,-161,-27,-606,-1296,-1351,-1427,-1721,-1533,-802,-195,-145,-160,178,548,495,501,834,900,425,-67,-81,-255,-535,-329,-71,-264,-603,-578,-351,-275,-167,177,309,136,-29,-27,68,172,326,267,-52,-391,-477,-350,-234,-166,-157,-256,-478,-545,-308,79,236,93,-57,-162,-183,-83,40,43,-88,-265,-379,-367,-231,-75,14,-7,-152,-196,-33,153,176,125,78,-34,-117,-61,86,82,-12,-84,-138,-37} + }, + { // 80 degrees, measured left/right ears + {0,-1,-1,-1,-1,-1,0,-1,0,1,0,0,-1,0,2,0,0,0,-1,0,1,0,2,12,0,-3,28,16,-10,-17,1,12,454,1414,1271,329,200,29,-55,678,1224,1455,2408,3761,3340,1725,1671,1855,163,-1528,-1636,-1621,-2215,-2272,-1778,-1567,-1505,-1181,-712,-412,-109,391,667,575,547,697,719,450,64,-230,-467,-713,-897,-964,-945,-865,-693,-502,-352,-165,-12,66,111,92,78,46,-30,-70,-112,-169,-262,-328,-299,-304,-296,-252,-226,-191,-164,-117,-87,-95,-68,-25,-7,-35,-88,-104,-107,-124,-138,-148,-157,-168,-159,-124,-100,-77,-51,-32,-31,-53,-63,-69,-90,-106,-134,-164,-184,-185,-162,-158,-159,-144,-129,-124,-108,-74,-41,-7}, + {-313,427,-549,5703,18346,-3205,-24555,-3065,12396,3551,-8,19449,23330,-4674,-10113,5669,5356,-5669,-7994,-6878,-10150,-6513,-926,-1963,-5185,-5720,491,3486,119,1830,5551,4517,1627,1927,2836,523,-1568,-2476,-2520,-3274,-4723,-4558,-3678,-1984,-107,723,681,472,684,1202,1496,1318,1368,1281,446,-223,-35,29,-681,-1245,-1338,-1507,-1692,-1392,-641,-183,-241,-238,135,521,481,541,899,885,331,-56,-55,-311,-505,-222,-23,-346,-683,-563,-320,-251,-117,215,273,69,-60,-16,71,195,339,211,-131,-455,-447,-276,-174,-106,-151,-314,-550,-544,-211,150,203,22,-131,-222,-199,-54,70,14,-137,-297,-380,-312,-169,-33,20,-49,-192,-194,0,170,150,94,45,-69,-114,-35,108,67,-39,-98,-173,-49} + }, + { // 85 degrees, measured left/right ears + {1,0,-1,-1,-1,0,0,0,0,1,2,2,1,1,1,0,1,-1,-2,0,0,5,1,-3,15,9,5,23,10,-19,-32,29,79,567,1634,1254,-154,205,817,298,352,955,1282,1888,3569,4640,3268,1615,1081,-152,-1947,-2260,-1942,-2614,-3006,-2342,-1668,-1406,-1105,-508,35,375,728,1008,953,751,738,681,361,-76,-443,-633,-825,-1061,-1113,-1034,-934,-754,-493,-222,-26,93,171,191,159,107,82,29,-92,-178,-229,-286,-320,-323,-316,-322,-310,-260,-209,-175,-123,-55,-21,-7,25,31,-16,-62,-95,-119,-131,-149,-162,-170,-163,-139,-119,-108,-101,-79,-42,-40,-64,-74,-87,-99,-110,-121,-139,-165,-156,-145,-162,-167,-162,-154,-132,-86,-34,-4}, + {-364,528,-672,6734,18447,-6239,-24773,-392,13048,2580,861,21690,20597,-8987,-9077,8636,5805,-6892,-7729,-6086,-10294,-5993,78,-2484,-7212,-5841,1924,3018,-523,2575,5797,4224,1441,1803,2407,-447,-1936,-1862,-1868,-3153,-4455,-3795,-3330,-1992,-19,705,314,8,651,1260,1240,1180,1470,1246,267,-257,147,130,-702,-1157,-1223,-1515,-1750,-1284,-483,-219,-342,-268,97,440,454,574,917,855,296,-54,-56,-300,-457,-166,-3,-385,-692,-516,-276,-227,-91,242,216,-20,-83,-20,83,213,325,173,-169,-442,-414,-259,-128,-42,-115,-335,-594,-529,-158,184,188,-34,-184,-263,-210,-40,71,1,-156,-302,-340,-272,-148,-7,19,-69,-191,-162,15,160,161,93,16,-109,-138,-29,107,69,-31,-111,-193,-53} + }, + { // 90 degrees, measured left/right ears + {0,-1,-1,-1,-1,-1,-1,0,0,-1,1,0,-1,1,0,-1,0,-2,-3,-2,-1,4,-1,-2,5,17,10,-1,15,-6,-22,15,332,735,433,440,1109,809,485,894,762,404,455,868,2178,4418,5250,3093,558,-100,-394,-1689,-2680,-2748,-2962,-3011,-2300,-1543,-1133,-763,-160,425,717,971,1181,1105,797,565,497,175,-344,-652,-792,-902,-1078,-1178,-1062,-883,-614,-318,-125,46,157,209,215,161,117,37,-41,-105,-200,-238,-286,-344,-342,-342,-345,-351,-294,-180,-107,-55,-21,3,32,44,22,-37,-79,-90,-104,-130,-164,-192,-175,-147,-157,-161,-139,-101,-67,-52,-52,-73,-98,-94,-100,-112,-120,-132,-132,-145,-158,-176,-195,-171,-115,-62,-32,-6}, + {-371,536,-699,6457,18519,-6301,-25112,64,13460,2553,1173,21732,19204,-10847,-8960,10799,7037,-7628,-7732,-5030,-10254,-6135,806,-3061,-8824,-5745,2482,2689,-666,2814,5790,3917,1586,2017,1740,-1311,-1931,-1345,-1620,-3007,-3993,-3239,-2915,-1758,-170,479,217,-236,369,1108,1132,1031,1349,1187,286,-222,147,241,-547,-1069,-1151,-1420,-1723,-1326,-424,-158,-374,-342,15,388,399,546,889,803,287,-37,-42,-283,-440,-149,35,-355,-674,-468,-228,-218,-103,242,177,-114,-140,-10,88,192,316,166,-184,-446,-374,-201,-77,-17,-123,-332,-596,-529,-148,182,171,-75,-216,-291,-241,-53,74,20,-144,-305,-356,-286,-129,26,37,-69,-201,-174,26,184,167,72,-31,-148,-161,-43,96,58,-45,-118,-168,-44} + }, + { // 95 degrees, measured left/right ears + {-1,-1,-1,-1,-1,-1,-1,-1,0,-1,-1,-1,1,0,0,1,0,-3,-2,-2,-1,2,-4,2,6,11,9,13,-5,-6,2,226,777,551,-221,-25,843,1293,1065,805,1258,1692,327,-745,1235,3469,4120,3726,1991,26,-622,-561,-1590,-3032,-3204,-2725,-2435,-2095,-1360,-618,-324,17,576,953,1121,1131,977,649,378,205,-148,-545,-801,-825,-851,-1066,-1111,-915,-645,-434,-272,-68,81,167,195,143,85,49,24,-24,-121,-212,-278,-308,-318,-369,-396,-367,-290,-187,-118,-68,-32,-4,18,13,-1,-33,-52,-36,-60,-127,-168,-185,-197,-202,-187,-162,-152,-134,-101,-85,-75,-61,-70,-95,-120,-128,-114,-106,-118,-142,-159,-165,-163,-150,-103,-51,-32,-7}, + {-337,431,-559,4939,18393,-3304,-25514,-1853,13811,3343,747,20000,19405,-10383,-10129,11753,9342,-7410,-8325,-4031,-9694,-6855,1073,-3232,-9830,-6066,2108,2864,-362,2377,5593,3970,1658,2083,1717,-1842,-2228,-874,-1423,-2864,-3670,-2849,-2524,-1573,-87,326,-87,-362,376,859,805,933,1275,1071,287,-133,135,275,-413,-922,-1013,-1352,-1659,-1313,-460,-129,-327,-390,-85,335,361,496,808,728,288,-18,-22,-247,-437,-165,79,-267,-609,-451,-202,-177,-132,190,159,-128,-203,-78,75,166,300,177,-164,-409,-337,-162,-52,6,-114,-334,-577,-509,-160,144,153,-77,-246,-330,-247,-47,93,35,-169,-335,-368,-278,-111,52,57,-76,-203,-153,42,179,145,41,-45,-147,-180,-82,49,34,-31,-92,-145,-38} + }, + { // 100 degrees, measured left/right ears + {1,0,-1,-1,0,0,0,0,0,0,0,0,1,2,1,3,2,1,1,-1,3,-1,0,5,10,5,13,13,9,-13,158,805,783,-177,-274,397,581,542,1028,1764,2145,2200,1001,-941,-294,2182,2902,2306,2005,1434,57,-798,-815,-1640,-2806,-2856,-2272,-1943,-1596,-890,-402,-227,156,728,1017,958,861,750,480,114,-157,-409,-627,-697,-746,-819,-886,-844,-671,-516,-367,-202,-53,54,62,49,82,95,80,21,-76,-172,-231,-245,-295,-375,-382,-296,-220,-200,-156,-83,-36,-30,-42,-36,-18,-15,-23,-31,-47,-85,-146,-201,-217,-202,-174,-151,-152,-165,-148,-100,-69,-65,-75,-85,-108,-124,-117,-115,-122,-122,-105,-107,-110,-97,-82,-56,-35,-7}, + {-206,177,-189,2599,17206,2516,-24823,-6513,13735,5166,-247,16671,20694,-7413,-12302,10747,12628,-5589,-9500,-3547,-8445,-7893,676,-2727,-10233,-6978,1034,3182,325,1646,5133,4154,1934,2063,1740,-1684,-2492,-889,-1207,-2453,-3518,-2867,-2084,-1406,-143,365,-85,-556,157,838,706,658,1053,1098,368,-179,47,331,-275,-827,-873,-1205,-1574,-1314,-461,-101,-313,-374,-121,250,287,428,737,691,276,-40,-2,-163,-409,-224,110,-148,-543,-435,-199,-148,-154,145,174,-125,-216,-131,12,117,279,232,-85,-358,-326,-154,-29,41,-87,-310,-561,-524,-179,124,160,-85,-263,-310,-238,-43,90,22,-179,-339,-343,-251,-132,23,72,-23,-143,-143,2,130,137,73,-33,-157,-208,-118,41,47,-17,-74,-120,-30} + }, + { // 105 degrees, measured left/right ears + {1,0,2,2,0,1,2,-1,1,0,0,0,0,0,2,2,1,1,1,1,0,0,0,14,-2,8,17,8,10,95,786,1022,-55,-440,293,546,304,322,916,2349,3340,2189,543,2,-183,171,980,1226,1119,1207,1106,267,-722,-1045,-1302,-2028,-2351,-1777,-1266,-1158,-881,-464,-13,339,544,707,718,634,448,154,-143,-356,-425,-475,-566,-628,-633,-625,-619,-568,-426,-296,-248,-183,-85,11,52,80,91,16,-65,-117,-153,-213,-278,-270,-249,-245,-217,-176,-133,-111,-110,-92,-82,-67,-23,-15,-50,-67,-58,-75,-135,-172,-174,-170,-159,-165,-182,-182,-156,-110,-82,-86,-94,-86,-87,-113,-138,-135,-111,-76,-47,-47,-48,-62,-61,-56,-61,-14}, + {28,-207,345,334,13797,9833,-20690,-13571,11733,8332,-1055,11494,21891,-1529,-14322,6987,15909,-1354,-10645,-4222,-6427,-8825,-704,-1557,-9833,-8431,-621,3171,1210,971,4364,4450,2255,2050,2035,-1234,-2833,-938,-974,-2127,-3172,-3068,-2037,-1276,-188,330,-8,-477,-83,600,751,682,776,920,536,-80,-179,228,-97,-734,-828,-1062,-1377,-1287,-571,-53,-216,-382,-188,190,246,311,621,697,317,-85,-38,-73,-332,-289,73,-12,-470,-467,-226,-135,-149,78,197,-88,-247,-165,-35,48,238,279,8,-289,-341,-162,-30,50,-54,-286,-504,-547,-261,74,165,-34,-247,-290,-234,-124,25,49,-105,-279,-369,-307,-172,-7,111,37,-126,-185,-63,122,159,68,-53,-165,-197,-121,23,57,-5,-67,-93,-21} + }, + { // 110 degrees, measured left/right ears + {0,0,1,1,0,2,0,0,0,0,0,-1,1,0,0,2,3,0,3,2,2,-6,9,8,-2,11,11,20,50,749,1276,124,-649,183,642,258,91,719,2106,2972,2341,1508,1011,353,-21,-514,-927,-243,501,643,877,963,444,-363,-776,-895,-1211,-1493,-1445,-1187,-1037,-793,-327,-49,89,273,446,456,249,66,-10,-130,-269,-318,-317,-368,-464,-479,-460,-464,-485,-505,-407,-295,-204,-74,-19,-7,4,-8,-35,-103,-134,-108,-118,-159,-191,-187,-167,-153,-131,-155,-178,-146,-103,-59,-73,-88,-80,-112,-118,-96,-82,-94,-116,-132,-166,-203,-199,-168,-144,-133,-118,-99,-100,-97,-113,-132,-123,-99,-69,-55,-23,-10,-2,-20,-47,-67,-103,-28}, + {246,-465,610,-674,8136,15246,-11239,-20243,5546,12026,186,4827,20716,6947,-13957,510,17119,5294,-10066,-6575,-4308,-8653,-3246,-525,-8088,-9908,-2996,2594,2093,565,3286,4685,2778,1957,2328,-91,-3108,-1646,-450,-1563,-2949,-3262,-2119,-1321,-381,300,85,-376,-190,461,683,689,772,821,530,47,-250,10,-53,-646,-809,-910,-1173,-1225,-698,-74,-63,-304,-303,65,274,236,464,670,433,-51,-138,-11,-212,-320,-33,70,-347,-528,-291,-122,-124,0,191,-10,-242,-202,-34,50,157,276,106,-183,-322,-197,-49,22,-29,-220,-426,-546,-361,-20,175,56,-176,-298,-311,-182,21,123,-13,-250,-400,-363,-182,0,82,17,-117,-168,-68,92,130,37,-39,-99,-152,-135,-5,76,31,-35,-76,-18} + }, + { // 115 degrees, measured left/right ears + {1,1,1,2,2,1,3,1,0,1,0,2,1,0,0,4,0,3,1,7,0,-1,9,2,11,4,31,20,683,1530,396,-861,-11,731,289,-29,617,2276,3275,2249,1012,882,966,587,-367,-1160,-1287,-1133,-590,206,572,772,1104,830,-19,-292,-149,-639,-1351,-1452,-1041,-766,-782,-582,-265,-94,5,65,45,2,76,116,1,-125,-148,-154,-253,-343,-367,-424,-507,-533,-479,-354,-274,-227,-160,-114,-88,-91,-81,-35,11,25,-16,-95,-139,-110,-95,-136,-171,-172,-170,-164,-144,-119,-126,-160,-175,-152,-108,-82,-64,-45,-60,-117,-177,-203,-182,-159,-146,-127,-129,-124,-123,-130,-136,-122,-81,-52,-35,-35,-16,8,25,-6,-46,-89,-134,-34}, + {216,-276,223,-183,2390,14944,1893,-21081,-5204,12856,4874,-751,14598,15460,-8411,-6883,14049,12486,-5740,-9651,-3794,-6644,-5972,-1087,-5184,-10100,-6102,971,2851,632,1875,4541,3569,2007,2234,1328,-2303,-2844,-684,-634,-2310,-3519,-2481,-1315,-686,17,155,-163,-298,288,752,700,661,857,722,105,-321,-155,-63,-603,-892,-798,-927,-1134,-867,-175,64,-178,-312,-108,238,240,309,596,541,81,-200,-26,-82,-310,-180,47,-218,-556,-388,-148,-114,-89,131,100,-169,-210,-55,76,110,210,179,-56,-272,-250,-107,-20,-23,-165,-333,-513,-452,-128,141,112,-169,-308,-280,-170,11,104,12,-196,-341,-330,-237,-112,-10,8,-52,-128,-117,-6,83,64,17,-42,-113,-139,-37,90,80,1,-67,-20} + }, + { // 120 degrees, measured left/right ears + {0,2,0,3,2,1,1,-1,0,0,1,1,2,-2,2,1,3,0,6,3,0,8,-5,18,-5,39,12,596,1749,746,-1028,-306,797,379,-192,566,2656,3673,2275,959,859,539,126,-140,-845,-1396,-1261,-1096,-1046,-569,249,871,1063,1104,1142,775,115,-277,-664,-1119,-1165,-975,-927,-926,-740,-518,-422,-377,-226,45,181,218,222,141,50,-20,-104,-267,-380,-392,-404,-426,-465,-456,-389,-326,-280,-278,-260,-127,23,72,65,52,29,-10,-52,-72,-74,-94,-137,-171,-182,-186,-188,-196,-231,-241,-204,-141,-93,-85,-52,-35,-72,-119,-155,-166,-158,-145,-135,-123,-129,-153,-169,-146,-117,-82,-51,-47,-33,-12,14,5,-3,-33,-67,-102,-145,-37}, + {-56,183,-349,475,-427,8731,12098,-12126,-15790,6787,10753,-852,4444,18195,3131,-10739,5921,16653,2632,-10445,-6240,-3873,-6806,-3641,-3070,-8000,-8506,-2302,2780,1525,533,3466,4383,2633,1814,2057,-322,-3111,-1877,-430,-1258,-3033,-3075,-1674,-900,-287,-51,-41,-154,47,660,843,667,720,907,440,-276,-418,-142,-388,-950,-912,-781,-933,-961,-449,78,-19,-230,-185,124,257,181,434,615,306,-135,-107,13,-237,-324,-99,-115,-486,-524,-242,-126,-147,9,165,-18,-166,-85,71,113,161,204,49,-184,-298,-185,-77,-44,-114,-268,-422,-483,-273,-25,52,-68,-198,-198,-178,-95,28,56,-56,-237,-358,-336,-216,-72,11,-41,-149,-186,-68,86,98,41,-9,-62,-103,-55,72,108,25,-44,-16} + }, + { // 125 degrees, measured left/right ears + {2,1,2,1,1,1,-1,0,-1,0,-2,-2,-1,1,-2,1,-3,3,4,-7,10,-10,17,-8,30,16,515,1931,1146,-1163,-657,824,480,-305,507,3057,4225,2358,815,926,545,-143,-618,-1418,-1608,-1064,-996,-1088,-881,-591,43,664,921,1271,1604,1327,556,-91,-292,-439,-923,-1217,-1105,-1048,-1103,-1044,-891,-665,-302,19,188,270,341,378,256,25,-117,-175,-261,-315,-347,-396,-441,-469,-453,-442,-468,-391,-189,-47,4,24,52,82,46,5,17,25,-24,-92,-121,-164,-200,-194,-238,-292,-309,-253,-165,-150,-122,-72,-55,-76,-123,-135,-128,-123,-103,-104,-125,-147,-165,-153,-157,-141,-95,-63,-44,-49,-26,0,-3,-30,-46,-76,-96,-113,-141,-35}, + {-154,223,-234,135,-100,1838,12616,2913,-17273,-5688,11519,5402,-2662,10638,14618,-5111,-4205,13882,11975,-5528,-10105,-3387,-4598,-6266,-3600,-5100,-8282,-5957,533,2655,226,1556,4413,3707,1940,1722,1412,-1531,-2762,-1241,-808,-1967,-3027,-2261,-1335,-711,-214,-167,-63,0,429,866,803,660,863,784,57,-497,-363,-200,-703,-1056,-901,-817,-887,-713,-166,76,-75,-148,20,260,169,164,500,567,139,-156,-19,-118,-387,-320,-122,-319,-613,-441,-175,-138,-119,102,143,-38,-70,46,123,126,195,124,-84,-271,-283,-147,-73,-74,-202,-345,-480,-473,-220,39,75,-87,-197,-213,-152,-3,114,29,-205,-367,-354,-238,-154,-97,-91,-147,-177,-102,41,113,72,15,-13,-48,-45,22,100,68,-29,-16} + }, + { // 130 degrees, measured left/right ears + {1,2,2,1,1,-2,1,-2,1,0,-1,-2,1,-2,3,0,-2,8,-6,10,-8,18,-6,25,22,449,2106,1584,-1258,-1073,799,601,-396,494,3563,4792,2387,730,1069,517,-395,-798,-1737,-2265,-1614,-1035,-942,-897,-496,138,210,213,936,1543,1335,1009,855,452,15,-281,-533,-889,-1267,-1334,-1316,-1402,-1226,-706,-291,-107,81,351,471,329,235,182,42,-98,-194,-250,-348,-419,-405,-427,-526,-551,-389,-215,-167,-149,-91,4,44,8,33,98,113,68,-22,-100,-141,-159,-161,-202,-285,-316,-290,-234,-175,-148,-121,-96,-96,-123,-156,-145,-94,-61,-51,-80,-133,-162,-166,-136,-114,-90,-74,-71,-51,-35,-28,-35,-50,-79,-92,-111,-106,-100,-122,-31}, + {47,-121,204,-305,372,-421,5307,11817,-5420,-15226,2465,11204,-15,-1076,14447,8793,-6891,3508,15951,4874,-9954,-7121,-1844,-5731,-6293,-3978,-6044,-7512,-3258,1923,1458,-119,2862,4690,2848,1399,1686,670,-1996,-2141,-1088,-1343,-2364,-2543,-1658,-1245,-769,-248,-80,-39,190,720,940,753,724,899,524,-232,-504,-214,-335,-912,-1025,-875,-842,-845,-509,-16,60,-51,-42,192,286,107,216,526,475,44,-98,-36,-298,-482,-302,-191,-477,-622,-354,-150,-158,-25,209,142,-10,15,134,150,146,167,31,-172,-308,-222,-82,-64,-170,-356,-458,-460,-309,-61,50,-50,-165,-159,-77,-10,26,20,-101,-245,-332,-316,-232,-189,-149,-104,-122,-130,-36,100,128,51,32,21,-13,-17,67,99,-14,-17} + }, + { // 135 degrees, measured left/right ears + {3,1,-1,0,-2,0,-2,0,-2,-1,-3,2,-1,-1,0,-3,9,-9,10,-13,16,-2,13,35,398,2256,2024,-1311,-1512,728,698,-500,561,4186,5359,2342,605,1243,577,-662,-1052,-1967,-2731,-2023,-1256,-1267,-1167,-450,421,516,331,716,1064,972,826,759,701,647,357,-87,-370,-643,-1107,-1523,-1610,-1417,-1063,-740,-463,-153,52,194,325,356,325,260,101,-57,-152,-259,-354,-413,-434,-419,-393,-359,-282,-220,-229,-195,-138,-111,-64,21,122,142,78,9,-50,-117,-150,-122,-138,-219,-281,-278,-226,-199,-200,-170,-139,-150,-166,-172,-158,-118,-63,-31,-59,-116,-153,-142,-118,-99,-68,-46,-62,-83,-81,-62,-61,-96,-115,-133,-128,-117,-103,-91,-107,-27}, + {62,-69,38,31,-146,238,80,7898,8373,-9999,-10456,7288,7999,-3821,2355,15565,4164,-4967,9137,13938,-1795,-10527,-3548,-1990,-7308,-6128,-3945,-6525,-6195,-1019,1966,373,368,3837,4416,2004,1143,1575,33,-1995,-1614,-1169,-1776,-2337,-2052,-1436,-1280,-826,-243,-72,3,400,890,933,725,786,796,291,-297,-365,-183,-532,-977,-918,-826,-874,-774,-354,4,22,-14,69,284,279,150,309,468,268,-61,-46,-94,-435,-517,-294,-304,-597,-565,-258,-133,-117,100,262,122,25,100,177,127,122,113,-50,-206,-232,-162,-166,-217,-260,-314,-379,-398,-283,-111,-20,-46,-66,-54,-54,-26,7,-25,-154,-299,-350,-305,-221,-158,-113,-99,-124,-81,41,126,108,61,52,32,-17,-14,44,30,0} + }, + { // 140 degrees, measured left/right ears + {1,-1,0,-3,0,-2,0,-1,0,-3,0,0,-1,2,-4,9,-9,12,-13,12,0,9,43,371,2434,2444,-1363,-1953,642,809,-622,665,4931,5930,2230,502,1424,567,-907,-1233,-2223,-3197,-2371,-1397,-1433,-1420,-728,369,731,573,1039,1361,807,289,416,549,422,363,426,271,-284,-766,-1015,-1339,-1476,-1156,-844,-703,-585,-371,-18,143,217,341,310,173,64,-9,-165,-335,-348,-261,-254,-339,-319,-204,-191,-248,-267,-237,-192,-154,-72,43,101,70,19,-42,-119,-124,-80,-90,-173,-228,-193,-157,-173,-191,-186,-174,-192,-211,-194,-176,-130,-70,-44,-84,-140,-140,-121,-84,-36,-5,-22,-68,-100,-96,-82,-95,-125,-147,-138,-148,-133,-107,-86,-81,-107,-28}, + {-61,92,-112,99,-80,14,9,1029,8963,4714,-11392,-5578,8991,3661,-5231,5998,14960,1540,-1730,11938,9697,-6073,-8397,-1126,-3652,-8465,-5239,-4011,-6713,-4614,300,1434,-209,1279,4382,3601,1457,1179,1279,-413,-1800,-1286,-1276,-1819,-2119,-1862,-1434,-1277,-764,-345,-193,98,602,951,821,720,852,724,185,-260,-270,-255,-669,-959,-795,-714,-790,-733,-337,-23,-37,7,173,352,272,186,350,346,33,-174,-42,-132,-483,-524,-324,-399,-606,-440,-151,-105,-102,140,263,130,86,133,125,61,106,109,-63,-239,-273,-186,-153,-187,-270,-368,-445,-428,-251,-50,10,-50,-59,-21,-16,-38,-67,-124,-228,-303,-300,-237,-175,-157,-123,-95,-81,-21,64,119,94,59,40,-10,-49,-18,29,8} + }, + { // 145 degrees, measured left/right ears + {-1,-2,-5,-1,-4,0,-2,-1,-3,-2,0,-1,1,-5,9,-14,14,-14,8,2,-3,49,365,2647,2841,-1469,-2405,556,919,-748,851,5818,6434,1957,467,1715,458,-1290,-1394,-2389,-3648,-2753,-1495,-1557,-1679,-833,432,656,503,1282,1671,1008,420,284,154,52,96,161,230,112,-280,-775,-1054,-962,-774,-756,-841,-772,-521,-285,-124,11,110,155,114,46,-29,-160,-186,-95,-104,-221,-278,-211,-128,-140,-219,-260,-243,-216,-202,-164,-81,-13,-5,-34,-69,-107,-116,-80,-85,-141,-170,-134,-99,-124,-156,-150,-146,-190,-228,-215,-194,-157,-111,-107,-137,-167,-166,-128,-52,24,40,-1,-78,-126,-125,-106,-105,-134,-150,-162,-163,-157,-115,-91,-85,-97,-126,-32}, + {12,-48,69,-96,106,-118,96,-106,1923,8954,1885,-10785,-1634,8153,-224,-4495,8753,13545,693,1390,12044,5229,-7416,-5450,-602,-5809,-8404,-4204,-4516,-6299,-3154,594,911,-180,2169,4458,2690,1098,1243,1099,-718,-1680,-1038,-1194,-1615,-1948,-1754,-1495,-1372,-718,-454,-320,136,688,958,765,725,905,758,184,-240,-233,-329,-753,-843,-638,-637,-722,-637,-311,-135,-68,81,236,323,184,160,312,268,-71,-274,-140,-218,-448,-421,-297,-424,-542,-313,-91,-106,-82,151,232,127,108,129,81,19,59,27,-89,-144,-134,-138,-224,-301,-360,-396,-410,-352,-194,-50,0,-26,-29,-38,-72,-103,-125,-153,-203,-228,-228,-208,-185,-151,-87,-50,-40,0,71,91,56,25,4,-25,-44,-20,0} + }, + { // 150 degrees, measured left/right ears + {0,-4,0,-2,-2,-3,-1,-5,-1,-1,-1,4,-7,11,-16,13,-16,11,5,-9,51,374,2901,3210,-1613,-2843,459,1029,-858,1097,6827,6890,1555,446,2085,380,-1770,-1635,-2512,-4061,-3102,-1562,-1686,-1896,-903,490,708,523,1336,1793,1109,443,439,357,-126,-325,-151,-25,-191,-388,-448,-649,-710,-457,-382,-486,-558,-507,-337,-290,-247,-126,-64,-127,-245,-201,-70,3,1,-40,-90,-181,-163,-63,-71,-138,-182,-174,-197,-258,-208,-93,-78,-152,-152,-111,-147,-158,-92,-63,-114,-142,-102,-78,-115,-108,-63,-88,-140,-164,-184,-197,-178,-156,-160,-203,-224,-185,-116,-38,28,53,-4,-94,-149,-139,-100,-87,-106,-145,-165,-169,-148,-119,-95,-102,-111,-112,-110,-24}, + {11,1,-29,52,-86,100,-124,118,-125,2503,8424,166,-9136,656,5843,-2494,-2704,10083,12136,1191,3424,10316,2085,-6635,-3256,-1594,-7259,-7394,-3777,-4998,-5414,-2219,358,556,329,2815,4077,1981,907,1296,864,-891,-1423,-973,-1073,-1226,-1718,-1716,-1654,-1495,-750,-544,-425,93,687,937,786,752,922,806,233,-220,-231,-329,-705,-743,-592,-585,-636,-543,-231,-131,-81,57,139,163,72,120,226,131,-117,-219,-142,-284,-463,-329,-201,-364,-434,-229,-92,-139,-87,136,176,105,114,75,-40,-43,105,126,9,-112,-178,-219,-282,-313,-357,-395,-382,-289,-141,-62,-57,-62,-51,-72,-115,-128,-107,-111,-153,-190,-211,-192,-161,-110,-47,-25,-22,-6,36,42,14,7,-6,-50,-68,-15} + }, + { // 155 degrees, measured left/right ears + {-4,-1,-3,-1,0,-1,-4,1,1,0,3,-6,12,-18,16,-16,10,8,-7,48,405,3190,3528,-1806,-3245,382,1105,-958,1446,7893,7254,1071,484,2476,266,-2254,-1951,-2634,-4409,-3494,-1606,-1746,-2128,-941,631,721,490,1506,1970,1098,377,430,416,-37,-279,-303,-381,-514,-628,-690,-720,-572,-223,6,-54,-154,-159,-172,-264,-293,-224,-301,-506,-521,-267,-119,-154,-66,41,-15,-116,-106,18,46,-60,-119,-116,-148,-198,-168,-103,-122,-173,-195,-239,-303,-258,-84,-16,-116,-160,-118,-80,-74,-66,-23,-15,-56,-92,-133,-184,-195,-164,-165,-212,-243,-218,-149,-60,10,15,-65,-157,-175,-125,-64,-50,-79,-122,-158,-159,-133,-110,-100,-108,-131,-134,-107,-61,-9}, + {-12,20,-8,-20,43,-78,101,-129,135,-112,2745,7718,-461,-7209,1208,3323,-3043,-975,10116,11261,2431,4076,7958,680,-4974,-2363,-3108,-7481,-6251,-4005,-5069,-4443,-1814,26,441,927,3085,3475,1591,1016,1207,448,-822,-1043,-965,-1000,-929,-1340,-1605,-1899,-1625,-849,-682,-461,111,648,825,777,870,994,766,222,-84,-100,-354,-691,-631,-527,-534,-534,-428,-186,-99,-77,-78,-59,-17,-67,-1,120,111,-51,-93,-43,-277,-473,-323,-144,-216,-274,-193,-165,-179,-83,107,88,-6,25,69,74,78,111,61,-40,-114,-162,-223,-282,-314,-320,-296,-313,-294,-226,-145,-83,-68,-47,-68,-110,-113,-91,-90,-120,-153,-168,-158,-120,-72,-36,-17,-20,-4,6,-5,-19,-19,-16,-39,-13} + }, + { // 160 degrees, measured left/right ears + {-2,-3,0,-3,-2,-5,0,1,3,3,-5,13,-19,18,-20,15,3,-3,50,468,3537,3753,-2076,-3569,316,1146,-1038,1905,9036,7493,515,619,2870,74,-2724,-2289,-2854,-4688,-3808,-1723,-1814,-2332,-918,836,734,489,1625,2090,1206,381,357,370,-144,-349,-190,-364,-782,-873,-894,-1138,-864,-106,309,248,98,175,251,47,-158,-263,-408,-504,-519,-525,-475,-306,-110,-48,-167,-226,-27,163,115,-7,-36,-31,-84,-148,-132,-38,-34,-160,-248,-318,-390,-336,-174,-88,-146,-190,-120,-62,-80,-45,34,56,10,-70,-133,-172,-142,-97,-116,-175,-243,-242,-178,-101,-48,-71,-153,-233,-226,-131,-35,-9,-34,-88,-136,-139,-112,-84,-95,-125,-151,-153,-124,-65,5,8}, + {15,-18,21,-10,-15,34,-72,96,-128,143,-104,2712,7022,-221,-5604,509,1450,-2462,63,9306,11060,3844,3617,5782,641,-3368,-2602,-4226,-6782,-5635,-4476,-4709,-3583,-1838,-303,772,1247,2722,3058,1686,1094,863,283,-630,-915,-829,-829,-860,-1137,-1359,-1912,-1867,-1106,-707,-353,112,475,657,795,949,1036,784,259,-12,-71,-303,-584,-539,-415,-435,-469,-399,-252,-193,-156,-166,-223,-222,-185,-89,73,164,60,2,-5,-188,-362,-304,-167,-183,-176,-131,-190,-276,-230,-18,72,67,91,69,38,46,62,24,-39,-102,-143,-192,-231,-239,-258,-286,-355,-369,-299,-200,-100,-38,-19,-64,-117,-114,-89,-70,-65,-92,-138,-146,-115,-62,-15,2,-14,-50,-49,-46,-46,-21,-23,-8} + }, + { // 165 degrees, measured left/right ears + {-4,2,-2,-2,-4,1,-1,1,2,-5,12,-23,17,-24,17,-5,4,45,572,3916,3878,-2394,-3799,279,1123,-1080,2457,10124,7638,-17,813,3241,-184,-3180,-2582,-3126,-5015,-4054,-1804,-1889,-2538,-948,1088,832,468,1772,2202,1197,428,410,303,-285,-458,-256,-377,-757,-1076,-1258,-1200,-827,-360,22,267,396,467,446,290,119,54,-28,-355,-696,-693,-545,-428,-340,-326,-336,-292,-118,55,106,80,47,83,25,-93,-31,74,15,-159,-246,-292,-402,-392,-238,-183,-271,-262,-132,-71,-61,13,83,59,-8,-71,-115,-127,-86,-19,-18,-114,-210,-241,-220,-170,-140,-137,-196,-292,-293,-183,-46,13,-7,-46,-94,-104,-77,-66,-83,-119,-149,-164,-144,-82,-11,22,6}, + {-7,16,-19,20,-11,-13,24,-60,86,-116,132,-92,2482,6427,548,-4551,-733,455,-1456,336,8144,11358,5087,2536,4132,1381,-2285,-3321,-4577,-5867,-5510,-4775,-4135,-2967,-2029,-549,1149,1431,2131,2590,1960,1337,570,153,-384,-870,-787,-574,-707,-1196,-1421,-1662,-1728,-1380,-880,-211,176,240,485,813,993,1024,738,340,92,-64,-245,-405,-380,-313,-341,-512,-574,-396,-288,-277,-323,-289,-208,-228,-147,79,243,169,78,22,-178,-284,-179,-99,-194,-291,-265,-219,-245,-217,-46,63,94,68,-7,-57,-41,43,84,47,-42,-112,-162,-201,-231,-267,-309,-379,-402,-349,-224,-99,-45,-31,-64,-103,-102,-63,-23,-29,-82,-127,-135,-106,-43,0,0,-46,-90,-93,-78,-56,-37,-8} + }, + { // 170 degrees, measured left/right ears + {1,-1,-1,-6,3,-3,2,0,-1,11,-24,20,-29,25,-17,13,34,741,4340,3836,-2779,-3891,282,1021,-1073,3160,11114,7627,-437,1094,3508,-502,-3620,-2882,-3377,-5331,-4342,-1902,-1926,-2655,-946,1247,927,548,1912,2335,1221,364,397,302,-322,-537,-293,-500,-1171,-1213,-1002,-1187,-1013,-513,-86,150,250,465,521,407,532,646,288,-276,-525,-518,-569,-640,-571,-457,-502,-553,-318,-29,51,42,42,63,73,74,130,180,86,-86,-205,-316,-428,-406,-236,-186,-316,-356,-226,-106,-69,20,96,34,-51,-74,-60,-44,-16,29,30,-45,-133,-213,-263,-257,-211,-188,-255,-343,-331,-199,-58,-6,-17,-38,-60,-64,-40,-26,-55,-114,-141,-147,-136,-104,-39,-1,-36,-14}, + {6,-8,14,-12,18,-9,-12,22,-49,70,-93,108,-72,2117,5950,1523,-3985,-1986,131,-511,79,6937,11862,6053,1288,3038,2327,-1718,-3951,-4398,-5091,-5562,-4913,-3519,-2531,-2307,-650,1407,1415,1649,2254,2028,1438,769,144,-500,-663,-693,-565,-567,-1188,-1523,-1603,-1476,-1193,-951,-422,107,306,449,707,851,872,780,479,197,48,-133,-293,-309,-302,-390,-607,-739,-578,-379,-351,-401,-335,-174,-95,-19,142,259,210,109,41,-120,-292,-254,-131,-135,-241,-329,-291,-250,-185,-32,37,17,-63,-87,-34,8,79,121,111,33,-87,-173,-233,-266,-268,-292,-362,-426,-396,-248,-100,-31,-38,-72,-81,-64,-27,-2,-20,-67,-105,-111,-92,-57,-16,-16,-67,-121,-119,-90,-71,-15} + }, + { // 175 degrees, measured left/right ears + {-1,-1,-6,4,-3,3,-3,3,8,-23,23,-32,32,-31,29,15,986,4761,3601,-3140,-3815,294,852,-993,3973,11854,7459,-588,1456,3604,-850,-3964,-3217,-3681,-5514,-4604,-2139,-1995,-2666,-860,1359,1003,651,1985,2452,1338,308,311,276,-320,-528,-535,-780,-1064,-1197,-1278,-1286,-919,-479,-184,45,101,179,394,721,947,736,387,110,-126,-310,-569,-654,-553,-594,-758,-782,-495,-172,-38,-32,-34,38,79,98,204,305,206,-7,-143,-293,-425,-377,-209,-181,-324,-350,-247,-187,-161,-52,60,22,-54,-54,-19,7,48,94,89,-2,-127,-209,-260,-268,-246,-251,-318,-390,-356,-212,-69,-14,-22,-50,-55,-49,-18,9,-21,-71,-132,-150,-135,-95,-52,-27,-51,-106,-30}, + {-7,4,-5,11,-9,11,-4,-14,19,-42,55,-70,80,-43,1711,5549,2413,-3689,-2919,156,169,-360,5852,12229,6695,241,2367,3069,-1443,-4246,-3992,-4494,-5636,-4894,-2927,-2294,-2529,-658,1511,1217,1243,2161,2114,1380,697,397,-176,-835,-743,-385,-598,-1185,-1447,-1540,-1474,-1034,-633,-406,-165,181,564,617,555,770,870,656,309,79,-44,-303,-431,-374,-465,-725,-861,-679,-463,-372,-304,-217,-113,-39,101,309,351,181,23,-49,-180,-319,-272,-118,-102,-213,-304,-315,-319,-265,-90,20,13,-47,-68,-32,11,94,160,148,46,-92,-201,-264,-266,-256,-295,-383,-434,-385,-241,-101,-39,-33,-65,-76,-55,-16,19,9,-43,-102,-128,-118,-74,-42,-31,-79,-126,-119,-101,-22} + }, + { // 180 degrees, measured left/right ears + {-2,-6,5,-5,6,-6,6,2,-20,20,-36,42,-50,51,-13,1314,5166,3131,-3449,-3526,253,600,-765,4872,12260,7150,-396,1876,3489,-1191,-4210,-3566,-4059,-5625,-4774,-2483,-2126,-2633,-730,1471,1071,901,2067,2314,1397,470,306,194,-481,-869,-544,-530,-1144,-1372,-1380,-1443,-1040,-437,-101,-109,-159,251,710,684,675,828,722,347,-25,-217,-341,-457,-533,-633,-813,-888,-627,-343,-271,-209,-63,40,34,94,271,376,220,-34,-132,-217,-324,-297,-176,-142,-268,-346,-286,-268,-263,-132,38,66,-30,-71,-54,5,103,171,150,10,-131,-208,-251,-265,-273,-291,-353,-415,-373,-231,-87,-29,-37,-50,-66,-47,-7,23,11,-54,-110,-144,-135,-100,-42,-27,-73,-119,-125,-28}, + {-2,-6,5,-5,6,-6,6,2,-20,20,-36,42,-50,51,-13,1314,5166,3131,-3449,-3526,253,600,-765,4872,12260,7150,-396,1876,3489,-1191,-4210,-3566,-4059,-5625,-4774,-2483,-2126,-2633,-730,1471,1071,901,2067,2314,1397,470,306,194,-481,-869,-544,-530,-1144,-1372,-1380,-1443,-1040,-437,-101,-109,-159,251,710,684,675,828,722,347,-25,-217,-341,-457,-533,-633,-813,-888,-627,-343,-271,-209,-63,40,34,94,271,376,220,-34,-132,-217,-324,-297,-176,-142,-268,-346,-286,-268,-263,-132,38,66,-30,-71,-54,5,103,171,150,10,-131,-208,-251,-265,-273,-291,-353,-415,-373,-231,-87,-29,-37,-50,-66,-47,-7,23,11,-54,-110,-144,-135,-100,-42,-27,-73,-119,-125,-28} + } +}; +} // namespace armix::sonku::hrir diff --git a/engine/builtin_fx/sonku/SonKuMusicalReverb.h b/engine/builtin_fx/sonku/SonKuMusicalReverb.h new file mode 100644 index 000000000..ab76c230e --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuMusicalReverb.h @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// Compact eight-line stereo FDN for musical late ambience. The 8x8 Hadamard +// feedback matrix is orthogonal (unit-energy): stability depends solely on +// prepared per-line RT60 gains and damping. No heap/locks/FFT/trig/I/O in process. +// A small, diffuse late field complements the already-approved square early +// reflections; no source-following stereo pan is imposed on the reverb tail. +// These listening-test presets are OFF in the shipping JUCE editor. +namespace armix::sonku { +enum class SonKuReverbPreset : std::uint8_t { StudioGlue=0, AiryChamber=1, LargeRoom=2 }; + +class SonKuMusicalReverb final { +public: + struct Ears {float left=0.f,right=0.f;}; + static constexpr int lineCount=8; + static constexpr int ringFrames=4096; + bool prepare(double rate) noexcept { + ready_=false; + if(!std::isfinite(rate) || (std::abs(rate-44100.)>.1 && + std::abs(rate-48000.)>.1))return false; + sampleRate_=static_cast(rate); + slew_=static_cast(1.-std::exp(-1./(rate*.012))); + amountTarget_=0.f; + preset_=SonKuReverbPreset::StudioGlue; + configure(); + // All room-aware coefficients prepared once OFF the PCM callback. + prepared_[0]=makeCoefficients(.78f,5900.f); + prepared_[1]=makeCoefficients(1.28f,7000.f); + prepared_[2]=makeCoefficients(2.05f,6000.f); + targetGain_=gain_;targetDamp_=dampCoeff_; + realtimeMode_=false; + reset(); + ready_=true; + return true; + } + void reset() noexcept { + for(auto& line:memory_)line.fill(0.f); + lowpass_.fill(0.f); + write_=0;amount_=0.f;validFrames_=0; + // The target amount is a CONTROL-side setting and survives resetting + // host transport/processor so the same program can restart cleanly. + } + bool setAmount(float amount) noexcept { + if(!std::isfinite(amount) || amount<0.f || amount>1.f)return false; + if(amount_==0.f && amountTarget_==0.f && amount>0.f)reset(); + amountTarget_=amount; + return true; + } + bool setPreset(SonKuReverbPreset value) noexcept { + if(value!=SonKuReverbPreset::StudioGlue && + value!=SonKuReverbPreset::AiryChamber)return false; + // Preset updates calculate RT60 coefficients. Never use this setter + // on an active realtime callback; native host doesn't expose it yet. + if(active())return false; + preset_=value; + configure(); + return true; + } + // Realtime-safe preset/wet update: only POD/table copies, no exponentials, + // heap, locks or clearing 128 KiB of delay memory in the audio callback. + // A validity horizon ensures no stale tail from a previous OFF period. + bool setRealtimeProgram(SonKuReverbPreset preset,float amount) noexcept { + if((preset!=SonKuReverbPreset::StudioGlue && + preset!=SonKuReverbPreset::AiryChamber && + preset!=SonKuReverbPreset::LargeRoom)|| + !std::isfinite(amount)||amount<0.f||amount>1.f)return false; + if(!active() && amount>0.f){validFrames_=0;lowpass_.fill(0.f);} + const auto& coefficients=prepared_[static_cast(preset)]; + targetGain_=coefficients.gains; + targetDamp_=coefficients.damping; + if(!realtimeMode_){gain_=targetGain_;dampCoeff_=targetDamp_;} + realtimeMode_=true; + preset_=preset; + amountTarget_=amount; + return true; + } + SonKuReverbPreset preset() const noexcept {return preset_;} + bool active() const noexcept {return ready_&&(amount_>0.f||amountTarget_>0.f);} + float targetAmount() const noexcept {return amountTarget_;} + Ears process(float left,float right) noexcept { + if(!active())return {}; + const float a=std::isfinite(left)?left:0.f; + const float b=std::isfinite(right)?right:0.f; + const float mid=.5f*(a+b); + const float side=.5f*(a-b); + std::array y{},mix{}; + if(realtimeMode_)dampCoeff_+=slew_*(targetDamp_-dampCoeff_); + for(int i=0;i inMid{1,1,-1,1,1,-1,-1,1}; + constexpr std::array inSide{1,-1,1,-1,1,-1,1,-1}; + constexpr std::array outL{1,-1,1,1,-1,1,-1,1}; + constexpr std::array outR{-1,1,1,-1,1,1,-1,1}; + float wetLeft=0.f,wetRight=0.f; + for(int i=0;i gains{}; + float damping=0.f; + }; + Coefficients makeCoefficients(float rt60,float cutoff) const noexcept { + Coefficients prepared{}; + constexpr float pi=3.14159265358979323846f; + prepared.damping=1.f-std::exp(-2.f*pi*cutoff/sampleRate_); + for(int i=0;i(delay_[i])/(sampleRate_*rt60)); + return prepared; + } + void configure() noexcept { + // Incommensurate lengths at 48k, scaled once at prepare/control side. + // First late energy arrives ~44 ms: behind earliest image reflections. + constexpr std::array lengths{ + 2111,2339,2579,2803,3079,3319,3593,3929}; + const float rt60=preset_==SonKuReverbPreset::StudioGlue?.78f:1.28f; + const float cutoff=preset_==SonKuReverbPreset::StudioGlue?5900.f:7000.f; + constexpr float pi=3.14159265358979323846f; + dampCoeff_=1.f-std::exp(-2.f*pi*cutoff/sampleRate_); + for(int i=0;i(std::lround( + lengths[i]*sampleRate_/48000.f)),1,ringFrames-2); + gain_[i]=std::exp(-6.9077553f* + static_cast(delay_[i])/(sampleRate_*rt60)); + } + } + static_assert((ringFrames&(ringFrames-1))==0); + std::array,lineCount> memory_{}; + std::array lowpass_{}; + std::array gain_{},targetGain_{}; + std::array prepared_{}; + std::array delay_{}; + float sampleRate_=48000.f,dampCoeff_=0.f,targetDamp_=0.f,slew_=0.f; + float amount_=0.f,amountTarget_=0.f; + int write_=0,validFrames_=0; + bool realtimeMode_=false; + SonKuReverbPreset preset_=SonKuReverbPreset::StudioGlue; + bool ready_=false; +}; +} // namespace armix::sonku diff --git a/engine/builtin_fx/sonku/SonKuSpatialCore.h b/engine/builtin_fx/sonku/SonKuSpatialCore.h new file mode 100644 index 000000000..924fbb639 --- /dev/null +++ b/engine/builtin_fx/sonku/SonKuSpatialCore.h @@ -0,0 +1,353 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "SonKuMeasuredHrir.h" +#include "SonKuEarlyReflections.h" +#include "SonKuMusicalReverb.h" +#include +#include +#include +#include +#include + +// Headphone binaural DSP: measured MIT KEMAR FIR, not a stereo auto-panner. +// All storage is fixed. prepare/setSettings are CONTROL-side before live render; +// process is the same native FX callback as other inserts (no own device/worker). +namespace armix::sonku { +struct Settings { + float startAzimuthDegrees = 0.f; // FRONT; +90 RIGHT; 180 REAR; -90 LEFT + float revolutionSeconds = 12.f; + float stereoSpreadDegrees = 60.f; + float spatialMix = 1.f; // 1=HRTF; 0=original L/R + float outputTrim = 0.75f; // legacy linear gain, now user-facing GAIN (-24..+12 dB) + bool moving = true; + bool clockwise = true; + // Version-2 persisted, native-ACKed acoustic scene. Zero is legacy + // HRTF-only. All other scenes are optional and OFF unless selected. + int spacePreset = 0; // 0=OFF, 1=Square 7.2, 2=Chamber 14.4, 3=Large 28.8 + float sourceDistanceMeters = 1.6f; + // Stored while OFF so the first selected scene is immediately audible + // and turning ROOM off/on remembers the previous wet preference. + // spacePreset=0 still guarantees identical legacy HRTF-only PCM. + float roomAmount = .55f; + float ambience = .30f; +}; +inline bool valid(const Settings& s) noexcept { + return std::isfinite(s.startAzimuthDegrees) && + std::abs(s.startAzimuthDegrees)<=360.f && + std::isfinite(s.revolutionSeconds) && s.revolutionSeconds>=0.5f && + s.revolutionSeconds<=120.f && + std::isfinite(s.stereoSpreadDegrees) && s.stereoSpreadDegrees>=0.f && + s.stereoSpreadDegrees<=180.f && + std::isfinite(s.spatialMix) && s.spatialMix>=0.f && s.spatialMix<=1.f && + std::isfinite(s.outputTrim) && s.outputTrim>=0.f && s.outputTrim<=4.f && + s.spacePreset>=0 && s.spacePreset<=3 && + std::isfinite(s.sourceDistanceMeters) && s.sourceDistanceMeters>=1.6f && + s.sourceDistanceMeters<=10.f && + std::isfinite(s.roomAmount) && s.roomAmount>=0.f && s.roomAmount<=1.f && + std::isfinite(s.ambience) && s.ambience>=0.f && s.ambience<=1.f && + (s.spacePreset==0 || SonKuEarlyReflections::validGeometry({ + s.spacePreset==1?7.2f:s.spacePreset==2?14.4f:28.8f, + s.spacePreset==1?7.2f:s.spacePreset==2?14.4f:28.8f, + s.sourceDistanceMeters})); +} +inline double wrapDegrees(double degrees) noexcept { + degrees=std::fmod(degrees,360.0); + return degrees<0.?degrees+360.:degrees; +} +class SonKuSpatialCore final { +public: + static constexpr int taps=hrir::taps; + static constexpr int updateInterval=16; + bool prepare(double rate) noexcept { + ready_=false; + if(!std::isfinite(rate) || (std::abs(rate-44100.)>.1 && + std::abs(rate-48000.)>.1))return false; + sampleRate_=rate; + bank_=(std::abs(rate-44100.)<.1)?hrir::normal44100:hrir::normal48000; + // Prepared control-side: continuous coefficient and gain smoothing + // without trigonometric/exponential work in the audio callback. + filterSlew_=static_cast(1.-std::exp(-1./(rate*0.006))); + levelSlew_=static_cast(1.-std::exp(-1./(rate*0.008))); + // Music-monitor distance/loudness controls are prepared off the + // realtime callback. Headphone low shelf ~180 Hz; no added latency. + distanceSlew_=static_cast(1.-std::exp(-1./(rate*0.030))); + bassSlew_=static_cast(1.-std::exp(-2.*3.14159265358979323846*180./rate)); + limiterRelease_=static_cast(1./(rate*0.080)); + if(!room_.prepare(rate)||!reverb_.prepare(rate))return false; + reset(); + ready_=true; + // Re-publish a saved active scene after device restart, but do NOT + // select the new realtime FDN program for the legacy/offline default: + // original Studio Glue / Airy Chamber listening renders remain exact. + return settings_.spacePreset==0 || applyAcousticSettings(settings_); + } + void reset() noexcept { + for(auto& channel:history_)channel.fill(0.f); + for(auto& source:kernels_)for(auto& ear:source)ear.fill(0.f); + for(auto& source:targets_)for(auto& ear:source)ear.fill(0.f); + smoothedMix_=settings_.spatialMix; + smoothedTrim_=settings_.outputTrim; + smoothedDistanceGain_=1.f; + smoothedRoomLevel_=1.f; + smoothedBassShelf_=0.f; + smoothedErPresence_=1.f; + smoothedTailPresence_=1.f; + earBass_.fill(0.f); + limiterGain_=1.f; + write_=0; + remaining_=0; + degrees_=wrapDegrees(settings_.startAzimuthDegrees); + haveKernel_=false; + room_.reset(); + reverb_.reset(); + } + bool setSettings(const Settings& s) noexcept { + if(!valid(s))return false; + // Keep phase continuous for live speed/spread adjustments; changing start + // position while static is an intentional absolute reposition. + if(!s.moving || !settings_.moving || + s.startAzimuthDegrees!=settings_.startAzimuthDegrees) + degrees_=wrapDegrees(s.startAzimuthDegrees); + const bool changed=s.spacePreset!=settings_.spacePreset || + s.sourceDistanceMeters!=settings_.sourceDistanceMeters || + s.roomAmount!=settings_.roomAmount || + s.ambience!=settings_.ambience; + if(changed && !applyAcousticSettings(s))return false; + settings_=s; + // Once native ROOM has been enabled, retain the smoothed transition + // when it is turned OFF. Standalone experimental V2/V3 OFF fixtures + // continue to use their exact original 1/r distance law. + if(s.spacePreset!=0)nativeSpaceEverUsed_=true; + remaining_=0; + return true; + } + Settings settings() const noexcept {return settings_;} + // A/B-only control pending room's headphone/device qualification. + // Legacy live insert remains room-free until product evidence is accepted. + bool setEarlyReflectionsAmount(float amount) noexcept { + return room_.setAmount(amount); + } + // Explicit A/B-only shape selection; never persisted or host-exposed. + bool setEarlyReflectionsShape(SonKuRoomShape shape) noexcept { + return room_.setShape(shape); + } + // Offline M3 distance/large-room acoustic trial. Not a GUI/native ABI. + bool setAcousticRoomGeometry(const SonKuRoomGeometry& geometry) noexcept { + return room_.setGeometry(geometry); + } + // Experimental wet-only late room, OFF unless explicitly enabled by + // controlled offline A/B. The native parameter contract is unchanged. + bool setMusicalReverbAmount(float amount) noexcept { + return reverb_.setAmount(amount); + } + bool setMusicalReverbPreset(SonKuReverbPreset preset) noexcept { + return reverb_.setPreset(preset); + } + bool ready() const noexcept {return ready_;} + double azimuthDegrees() const noexcept {return degrees_;} + // In-place stereo; caller owns valid, non-overlapping L/R PCM pointers. + // No vector, heap, blocking calls, I/O or filter bank allocation. + void process(float* left,float* right,int samples) noexcept { + if(!ready_ || !left || !right || samples<=0)return; + const double step=(settings_.moving ? + (settings_.clockwise?1.:-1.)*360./(sampleRate_*settings_.revolutionSeconds) : 0.); + const float distanceGain=room_.relativeDistanceGain(); + const bool nativeSpace=nativeSpaceEverUsed_; + const bool roomEnabled=settings_.spacePreset!=0; + // Deliberate music-monitor compensation: real distance perception + // still comes from direct/reflected ratio and high-frequency cues, + // while the direct field is not attenuated by the full physical 1/r. + // 1.6m=1; 8m~0.55 instead of 0.20. No pow/exp on the PCM callback. + const float targetDistance=roomEnabled? + 1.f/(1.f+0.13f*(settings_.sourceDistanceMeters-1.6f)):1.f; + for(int i=0;i unity + // uses the protected branch below even with ROOM OFF. + if(distanceGain==1.f) { + left[i]=dryLevel*x0+legacyBinauralLevel*(ears[0]+reflection.left+late.left); + right[i]=dryLevel*x1+legacyBinauralLevel*(ears[1]+reflection.right+late.right); + } else { + left[i]=dryLevel*x0+legacyBinauralLevel* + (distanceGain*ears[0]+reflection.left+late.left); + right[i]=dryLevel*x1+legacyBinauralLevel* + (distanceGain*ears[1]+reflection.right+late.right); + } + } else { + // Slew gain changes per sample; a typed 1.6→8 m edit must + // never step the direct pressure at the buffer boundary. + smoothedDistanceGain_+=distanceSlew_* + (targetDistance-smoothedDistanceGain_); + smoothedRoomLevel_+=distanceSlew_* + ((roomEnabled?1.12f:1.f)-smoothedRoomLevel_); + smoothedBassShelf_+=distanceSlew_* + ((roomEnabled?0.82f:0.f)-smoothedBassShelf_); + // The original experimental return levels were intentionally + // near-silent: ER base 0.28 * wall 0.70 * 1/r and diffuse FDN + // output 0.23 * amount, followed by another 0.5 * trim. + // Scene-only presence curves keep direct/reflected/tail + // INDEPENDENT: distance still reduces direct while wall + // echoes and the later diffuse field identify the room. + // Gain laws are bounded affine maps, zero wet stays EXACT + // zero, no exp/pow/alloc on the audio callback. + const float targetErPresence=roomEnabled? + 1.45f+2.0f*settings_.roomAmount:1.f; + const float targetTailPresence=roomEnabled? + 2.2f+4.0f*settings_.ambience:1.f; + smoothedErPresence_+=distanceSlew_* + (targetErPresence-smoothedErPresence_); + smoothedTailPresence_+=distanceSlew_* + (targetTailPresence-smoothedTailPresence_); + float spatialL=smoothedDistanceGain_*ears[0]+ + smoothedErPresence_*reflection.left+ + smoothedTailPresence_*late.left; + float spatialR=smoothedDistanceGain_*ears[1]+ + smoothedErPresence_*reflection.right+ + smoothedTailPresence_*late.right; + // Low-frequency KEMAR response is ~-7..-11 dB below 200Hz. + // A gentle bounded *binaural* shelf restores warmth without + // mixing dry mono under the HRIR or altering left/right ITD. + earBass_[0]+=bassSlew_*(spatialL-earBass_[0]); + earBass_[1]+=bassSlew_*(spatialR-earBass_[1]); + spatialL+=smoothedBassShelf_*earBass_[0]; + spatialR+=smoothedBassShelf_*earBass_[1]; + // GAIN is final full-output gain, not the old wet-only trim. + // When ROOM OFF is reselected after a native scene, the + // additional wet presence smoothly decays with its own engine. + float outL=smoothedTrim_* + (dryLevel*x0+sceneBinauralLevel*smoothedRoomLevel_*spatialL); + float outR=smoothedTrim_* + (dryLevel*x1+sceneBinauralLevel*smoothedRoomLevel_*spatialR); + // Zero-lookahead *linked* sample-peak safety guard. Quiet + // signals are linear; peaks are gently returned below unity + // without routing through a second engine or allocating. + const float peak=std::max(std::abs(outL),std::abs(outR)); + const float immediate=peak>0.98f?0.98f/peak:1.f; + limiterGain_=std::min(immediate, + std::min(1.f,limiterGain_+limiterRelease_)); + left[i]=outL*limiterGain_; + right[i]=outR*limiterGain_; + } + if(++write_==taps)write_=0; + if(step!=0.) { + degrees_+=step; + if(degrees_>=360.)degrees_-=360.; + if(degrees_<0.)degrees_+=360.; + } + --remaining_; + } + } +private: + bool applyAcousticSettings(const Settings& s) noexcept { + const float width=s.spacePreset==1?7.2f: + s.spacePreset==2?14.4f:28.8f; + const SonKuRoomGeometry geometry{ + width,width,s.spacePreset? s.sourceDistanceMeters:1.6f}; + const auto preset=s.spacePreset==3?SonKuReverbPreset::LargeRoom: + s.spacePreset==2?SonKuReverbPreset::AiryChamber: + SonKuReverbPreset::StudioGlue; + return room_.setRealtimeRoom(geometry,s.roomAmount,s.spacePreset!=0) && + reverb_.setRealtimeProgram(preset, + s.spacePreset!=0?s.ambience:0.f); + } + // Positive azimuth is right. MIT KEMAR supplied azimuth 0..180 with + // symmetric opposite-ear swapping for left hemisphere, not yaw-panning. + void interpolate(std::size_t source,double azimuth) noexcept { + const double norm=wrapDegrees(azimuth); + const bool swapped=norm>180.; + const double positive=swapped?360.-norm:norm; + const double index=positive/static_cast(hrir::spacingDegrees); + const int lo=std::clamp(static_cast(index),0,hrir::directions-1); + const int hi=std::min(lo+1,hrir::directions-1); + const float u=static_cast(index-static_cast(lo)); + constexpr float scale=1.f/32768.f; + for(int ear=0;ear<2;++ear) { + const int measuredEar=swapped?1-ear:ear; + for(int k=0;k(bank_[lo][measuredEar][k])*(1.f-u) + + static_cast(bank_[hi][measuredEar][k])*u); + // Recompute target every 16 samples, interpolate per sample. + targets_[source][ear][k]=next; + } + } + } + void updateKernels() noexcept { + interpolate(0,degrees_-static_cast(settings_.stereoSpreadDegrees)*0.5); + interpolate(1,degrees_+static_cast(settings_.stereoSpreadDegrees)*0.5); + // First prepared sample is a valid full-level measured HRIR; only + // subsequent direction edits slew, avoiding initial audio dropout. + if(!haveKernel_)kernels_=targets_; + haveKernel_=true; + } + using Bank=const std::int16_t (*)[2][taps]; + Bank bank_=nullptr; + std::array,2> history_{}; + std::array,2>,2> kernels_{}; + std::array,2>,2> targets_{}; + Settings settings_{}; + SonKuEarlyReflections room_{}; + SonKuMusicalReverb reverb_{}; + float smoothedMix_=1.f,smoothedTrim_=0.75f; + float smoothedDistanceGain_=1.f,smoothedRoomLevel_=1.f; + float smoothedBassShelf_=0.f,limiterGain_=1.f; + float smoothedErPresence_=1.f,smoothedTailPresence_=1.f; + std::array earBass_{}; + float filterSlew_=0.f,levelSlew_=0.f; + float distanceSlew_=0.f,bassSlew_=0.f,limiterRelease_=0.f; + double sampleRate_=0.; + double degrees_=0.; + int write_=0; + int remaining_=0; + bool ready_=false; + bool haveKernel_=false; + bool nativeSpaceEverUsed_=false; +}; +} // namespace armix::sonku diff --git a/engine/core/DynamicAcceptedSession.h b/engine/core/DynamicAcceptedSession.h index dd4486f23..ca11e76da 100644 --- a/engine/core/DynamicAcceptedSession.h +++ b/engine/core/DynamicAcceptedSession.h @@ -306,6 +306,14 @@ class DynamicAcceptedSession final { return false; return accepted_.rememberLiveMix(id,linear,pan); } + // Pre-insert, pre-fader digital input gain; a real ChannelId PCM target. + bool setLiveInputGain(std::uint64_t epoch,std::uint64_t graphRevision, + ChannelId id,float linear) noexcept { + const auto* row=accepted_.find(id); + if(!row || row->role!=ChannelRole::input || + !publisher_.setChannelInputGain(epoch,graphRevision,id,linear))return false; + return accepted_.rememberLiveInputGain(id,linear); + } // The accepted physical patch is canonical too: subsequent Group/FX // graph recompiles must preserve the most recently ACKed live SOURCE. bool setLivePhysicalSource(std::uint64_t epoch,std::uint64_t graphRevision, @@ -350,6 +358,20 @@ class DynamicAcceptedSession final { source,destination,preFader,linear); } + // The exact existing parallel EdgeId is toggled without deleting its + // connection, changing the source's primary OUT, or recompiling the graph. + bool setLiveSendEnabled(std::uint64_t epoch,std::uint64_t graphRevision, + ChannelId source,std::uint64_t edgeId,bool enabled) noexcept { + const auto* row=accepted_.find(source); + if(!row || !edgeId)return false; + for(const auto& edge:row->sends) + if(edge.edgeId==edgeId && !edge.primaryOutput){ + if(!publisher_.setWireEnabled(epoch,graphRevision,source,edgeId,enabled)) + return false; + return accepted_.rememberLiveSendEnabled(source,edgeId,enabled); + } + return false; + } bool setLiveWireGain(std::uint64_t epoch,std::uint64_t revision, ChannelId source,std::uint64_t edgeId,float gain) noexcept { const auto* row=accepted_.find(source); diff --git a/engine/core/DynamicChannelRoster.h b/engine/core/DynamicChannelRoster.h index bf76ad572..fb11276ff 100644 --- a/engine/core/DynamicChannelRoster.h +++ b/engine/core/DynamicChannelRoster.h @@ -30,6 +30,7 @@ struct ChannelSendRef final { float pan=0.f; // send-only balance: PRE mono uses equal-power coefficients bool primaryOutput=false; // OUT selector edge, not a parallel SEND std::uint64_t edgeId=0; // stable native identity; CONTROL-only assignment + bool enabled=true; // independent SEND ON/OFF retains gain/tap/EdgeId }; struct ChannelStripDefinition final { ChannelId id{}; @@ -42,6 +43,9 @@ struct ChannelStripDefinition final { // The existing audio control thread owns independent VST instance creation. std::vector insertCatalogIds; std::vector sends; + // Digital INPUT gain is independent of the channel fader and physical preamp. + // Append to retain positional aggregate compatibility with older fixtures. + float inputGainLinear=1.f; }; struct ChannelRosterBudget final { @@ -62,7 +66,8 @@ struct ChannelEdit final { removeInsertReference, moveInsertReference, // Control-document metadata (rack/slot bypass) changes revision // without changing a fader, audio descriptor or live PCM topology. - touchDocumentRevision + touchDocumentRevision, + setInputGain, setSendEnabled, setSendTap } kind=Kind::add; ChannelId id{}; // existing channel (except add) ChannelId target{}; // send destination @@ -76,6 +81,7 @@ struct ChannelEdit final { bool primaryOutput=false; // exclusive OUT edge, independent of parallel SEND bool connectMainOnCreate=false; // WIRE-first native creation; legacy imports unchanged float sendPan=0.f; // independent send PAN, never channel fader PAN + std::uint64_t sendEdgeId=0; // exact existing parallel EdgeId std::string text; }; struct ChannelEditResult final { @@ -88,11 +94,12 @@ struct ChannelEditResult final { }; struct WireChange final { - enum class Kind : std::uint8_t {connect,remove,retarget,routeOnly}; + enum class Kind : std::uint8_t {connect,remove,retarget,routeOnly,setTap}; Kind kind=Kind::connect; ChannelId from{},to{}; std::uint64_t edgeId=0; float gain=1.f; + bool preFader=false; // SET_TAP only: true = post-FX / pre-channel-fader }; class DynamicChannelRoster final { @@ -119,6 +126,21 @@ class DynamicChannelRoster final { row.faderLinear=gain;row.pan=pan; return true; } + // No graph revision change for realtime input trim; native PCM must ACK first. + bool rememberLiveInputGain(ChannelId id,float gain) noexcept { + if(!id.value || !std::isfinite(gain) || gain<0.f || gain>16.f)return false; + const auto it=index_.find(id.value); + if(it==index_.end() || channels_[it->second].role!=ChannelRole::input)return false; + channels_[it->second].inputGainLinear=gain; + return true; + } + bool rememberLiveSendEnabled(ChannelId id,std::uint64_t edgeId,bool enabled) noexcept { + const auto it=index_.find(id.value); + if(!id.value||!edgeId||it==index_.end())return false; + for(auto& edge:channels_[it->second].sends) + if(edge.edgeId==edgeId&&!edge.primaryOutput){edge.enabled=enabled;return true;} + return false; + } bool rememberLiveMuteSolo(ChannelId id,bool mute,bool solo) noexcept { const auto it=index_.find(id.value); if(!id.value||it==index_.end())return false; @@ -225,6 +247,12 @@ class DynamicChannelRoster final { if(!validFormat(op.format))result.fault=ChannelEditFault::invalidValue; else it->format=op.format; break; + case ChannelEdit::Kind::setInputGain: + if(it->role!=ChannelRole::input || !std::isfinite(op.value) || + op.value<0.f || op.value>16.f) + result.fault=ChannelEditFault::invalidValue; + else it->inputGainLinear=op.value; + break; case ChannelEdit::Kind::setFader: if(!std::isfinite(op.value)||op.value<0.f||op.value>4.f) result.fault=ChannelEditFault::invalidValue; @@ -241,6 +269,19 @@ class DynamicChannelRoster final { case ChannelEdit::Kind::setSolo: it->solo=op.enabled; break; + case ChannelEdit::Kind::setSendEnabled: + case ChannelEdit::Kind::setSendTap: { + const auto edge=std::find_if(it->sends.begin(),it->sends.end(), + [&](const auto& send){return send.edgeId==op.sendEdgeId;}); + if(!op.sendEdgeId || edge==it->sends.end()) + result.fault=ChannelEditFault::missingEdge; + else if(edge->primaryOutput) + result.fault=ChannelEditFault::invalidAction; + else if(op.kind==ChannelEdit::Kind::setSendEnabled) + edge->enabled=op.enabled; + else edge->preFader=op.preFader; // post-FX PRE, not PRE_FX + break; + } case ChannelEdit::Kind::touchDocumentRevision: // Exact stable ChannelId is validated above. Bump the // document revision without fabricating a DSP parameter @@ -397,13 +438,23 @@ class DynamicChannelRoster final { } auto& sends=source->sends; if(op.kind==WireChange::Kind::remove || - op.kind==WireChange::Kind::retarget) { + op.kind==WireChange::Kind::retarget || + op.kind==WireChange::Kind::setTap) { const auto edge=std::find_if(sends.begin(),sends.end(), [&](const auto& s){return s.edgeId==op.edgeId;}); if(!op.edgeId || edge==sends.end()) { result.fault=ChannelEditFault::missingEdge;break; } if(op.kind==WireChange::Kind::remove){sends.erase(edge);continue;} + if(op.kind==WireChange::Kind::setTap) { + // One exact parallel EdgeId. Never alter PRIMARY_OUT, + // other sends, their levels, destination or PAN. + if(edge->primaryOutput || edge->preFader==op.preFader) { + result.fault=ChannelEditFault::invalidValue;break; + } + edge->preFader=op.preFader; + continue; + } if(!op.to.value || op.to==op.from || edge->destination==op.to){ result.fault=ChannelEditFault::invalidValue;break; } @@ -750,7 +801,10 @@ class DynamicChannelRoster final { if(!ch.id.value || ch.id.value==std::numeric_limits::max() || !ids.insert(ch.id.value).second || !std::isfinite(ch.faderLinear) || ch.faderLinear<0.f || - ch.faderLinear>4.f || !std::isfinite(ch.pan) || + ch.faderLinear>4.f || !std::isfinite(ch.inputGainLinear) || + ch.inputGainLinear<0.f || ch.inputGainLinear>16.f || + (ch.role!=ChannelRole::input && ch.inputGainLinear!=1.f) || + !std::isfinite(ch.pan) || ch.pan< -1.f || ch.pan>1.f)return false; maxId=std::max(maxId,ch.id.value); mains+=ch.role==ChannelRole::main; @@ -764,6 +818,7 @@ class DynamicChannelRoster final { !std::isfinite(send.gain)||send.gain<0.f||send.gain>4.f || !std::isfinite(send.pan)||send.pan< -1.f||send.pan>1.f) return false; + if(send.primaryOutput&&!send.enabled)return false; primary+=send.primaryOutput; maxEdge=std::max(maxEdge,send.edgeId); } diff --git a/engine/core/DynamicConsoleRoutingView.h b/engine/core/DynamicConsoleRoutingView.h index 29cf7b460..4563cde6e 100644 --- a/engine/core/DynamicConsoleRoutingView.h +++ b/engine/core/DynamicConsoleRoutingView.h @@ -20,12 +20,13 @@ struct ConsoleSendView final { float gain=1.f,pan=0.f; bool preFader=false; std::uint64_t edgeId=0; + bool enabled=true; }; struct ConsoleEdgeView final { std::uint64_t edgeId=0; ChannelId from{},to{}; float gainLinear=1.f; - bool preFader=false,primaryOutput=false; + bool preFader=false,primaryOutput=false,enabled=true; }; struct ConsoleChannelView final { ChannelId id{}; @@ -90,7 +91,7 @@ class DynamicConsoleRoutingView final { if(it==index.end() || !link.edgeId || !acceptedEdgeIds.insert(link.edgeId).second)return false; next.edges.push_back({link.edgeId,sender.id,link.destination, - link.gain,link.preFader,link.primaryOutput}); + link.gain,link.preFader,link.primaryOutput,link.enabled}); auto& destination=next.channels[it->second]; if(link.primaryOutput) { if(sender.primaryOutput.value || link.preFader || @@ -100,7 +101,7 @@ class DynamicConsoleRoutingView final { destination.primarySources.push_back(sender.id); } else { sender.parallelSends.push_back( - {link.destination,link.gain,link.pan,link.preFader,link.edgeId}); + {link.destination,link.gain,link.pan,link.preFader,link.edgeId,link.enabled}); // One source shown once in the Bus fan-in even if it has // multiple legal taps to that destination. if(std::find(destination.parallelSendSources.begin(), diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index 4970c1046..8092f1b6a 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -6,6 +6,7 @@ #include "NativeBeatFrameContext.h" #include "RealtimeRoutePublisher.h" #include "RealtimeRenderPermit.h" +#include "../lms/NativeSpeakerOutputReservation.h" #include #include #include @@ -25,6 +26,45 @@ class DynamicNativeSessionPublisher final { public: // Control-owned native FX lifetime travels IN the same accepted PCM // snapshot. JUCE types stay outside this portable DSP publisher. + // Optional one-pass observer of the already-accepted MAIN PCM after + // ChannelId routing and rack FX. No new renderer, separate mixing pass, + // hardware pin ownership, or data lifetime beyond this callback. + // Observers MUST be no-throw, allocation-free and MUST NOT mutate MAIN. + // This is pre-master-output gain; the physical post-gain path remains the + // authority for future speaker activation and must be gated separately. + struct MainPcmObserver final { + void* context=nullptr; + void (*observe)(void*,const float*,const float*,int) noexcept=nullptr; + }; + // M5: CONTROL-only, immutable readback of a VERIFIED but DISCONNECTED + // speaker design. Never exposed to the realtime callback. In particular, + // `validatedDraft` must NOT be presented as physically APPLIED/LIVE. + enum class SpeakerDraftFault : std::uint8_t { + none,staleDeviceOrGraph,staleDraft,invalidSource, + invalidReservation,invalidDsp,preparationFailed + }; + struct SpeakerDraftAck final { + SpeakerDraftFault fault=SpeakerDraftFault::none; + armix::lms::SpeakerReservationFault reservationFault= + armix::lms::SpeakerReservationFault::none; + armix::lms::SpeakerPlanFault planFault=armix::lms::SpeakerPlanFault::none; + std::uint64_t deviceEpoch=0,graphRevision=0,designRevision=0; + std::size_t preparedScratchBytes=0; + bool validatedDraft=false,hardwareApplied=false; + [[nodiscard]] bool ok() const noexcept { + return fault==SpeakerDraftFault::none && validatedDraft && + !hardwareApplied; + } + }; + struct SpeakerDraftReadback final { + std::uint64_t deviceEpoch=0,graphRevision=0,designRevision=0; + ChannelId mainSource{}; + std::string deviceIdentity; + armix::lms::SpeakerSystemRequest design; + std::vector reservedOutputOrdinals; + std::size_t preparedScratchBytes=0; + bool validatedDraft=true,hardwareApplied=false; + }; struct FxPlan final { std::shared_ptr owner; // CONTROL-only copy/destruction void* context=nullptr; // unchanged owner.get(), RT raw pointer @@ -45,6 +85,11 @@ class DynamicNativeSessionPublisher final { int physicalInputs=0; bool monitor=false; }; + // On CONTROL only: one speaker design belongs to the same accepted + // ChannelId/epoch. The prepared DSP is intentionally NOT placed in the + // hardware callback's published snapshot until physical protection exists. + std::unique_ptr speakerDraft_; + std::unique_ptr speakerPrepared_; using Publisher=armix::rt::RealtimeRoutePublisher; public: enum class Fault : std::uint8_t { @@ -127,6 +172,10 @@ class DynamicNativeSessionPublisher final { expectedRevision,activeDeviceEpoch); switch(status) { case Publisher::Result::applied: { + // Every accepted structural PCM revision revokes old speaker + // pin identity and DSP; a UI draft cannot survive by accident. + speakerDraft_.reset(); + speakerPrepared_.reset(); const auto source=musicTempo_.selectedSource(); if(source.value) { const auto* published=publisher_.controlPrepared( @@ -155,6 +204,98 @@ class DynamicNativeSessionPublisher final { return report; } + // M5: same-publisher CONTROL transaction. Required caller-side proof: + // inventory was constructed from the ACTUAL active JUCE device's + // enabled output mask, never from browser-stored ordinal labels. + // No side effects on existing ChannelId PCM or hardware pin ownership. + // ALL speaker output DSP remains permanently DISCONNECTED at M5. + SpeakerDraftAck acceptSpeakerDraft( + const armix::lms::SpeakerSystemRequest& request, + const armix::lms::NativePcmOutputInventory& inventory, + ChannelId mainSource,std::uint64_t expectedDesignRevision) { + SpeakerDraftAck ack; + ack.deviceEpoch=request.deviceEpoch; + ack.graphRevision=request.graphRevision; + ack.designRevision=speakerDraft_?speakerDraft_->designRevision:0; + const auto* accepted=publisher_.controlPrepared( + request.deviceEpoch,request.graphRevision); + if(!accepted || !request.deviceEpoch || !request.graphRevision || + !inventory.acceptedChannelIdPcm || + !inventory.deviceEpoch || !inventory.acceptedGraphRevision || + inventory.deviceEpoch!=request.deviceEpoch || + inventory.acceptedGraphRevision!=request.graphRevision) { + ack.fault=SpeakerDraftFault::staleDeviceOrGraph;return ack; + } + if(expectedDesignRevision!=ack.designRevision || + expectedDesignRevision==std::numeric_limits::max()){ + ack.fault=SpeakerDraftFault::staleDraft;return ack; + } + if(!mainSource.value || accepted->routing.main!=mainSource || + inventory.mainChannelId!=mainSource.value){ + ack.fault=SpeakerDraftFault::invalidSource;return ack; + } + if(request.maxFrames!=accepted->graph.capacity()) { + ack.fault=SpeakerDraftFault::invalidDsp; + ack.planFault=armix::lms::SpeakerPlanFault::invalidFormat; + return ack; + } + try { + const auto reserved=armix::lms::NativeSpeakerOutputReservation:: + preflight(request,inventory,mainSource.value); + if(!reserved.ok() || reserved.mayWritePhysicalAudio){ + ack.fault=SpeakerDraftFault::invalidReservation; + ack.reservationFault=reserved.fault;return ack; + } + std::unique_ptr dsp; + const auto candidate=armix::lms::PreparedSpeakerSystem:: + prepare(request,dsp); + if(!candidate.ok() || !dsp){ + ack.fault=SpeakerDraftFault::invalidDsp; + ack.planFault=candidate.fault;return ack; + } + // Everything above is speculative. Build a complete readback + // BEFORE publishing either pointer: an exception leaves the last + // accepted draft and PCM untouched (transactional rollback). + auto snapshot=std::make_unique(); + snapshot->deviceEpoch=request.deviceEpoch; + snapshot->graphRevision=request.graphRevision; + snapshot->designRevision=expectedDesignRevision+1; + snapshot->mainSource=mainSource; + snapshot->deviceIdentity=inventory.deviceIdentity; + snapshot->design=request; + snapshot->reservedOutputOrdinals=reserved.reservedCallbackOrdinals; + snapshot->preparedScratchBytes=candidate.scratchBytes; + speakerPrepared_=std::move(dsp); + speakerDraft_=std::move(snapshot); + ack.designRevision=speakerDraft_->designRevision; + ack.preparedScratchBytes=candidate.scratchBytes; + ack.validatedDraft=true; + // No hardware output ACL exists in this transaction. + ack.hardwareApplied=false; + return ack; + } catch(...) { + ack.fault=SpeakerDraftFault::preparationFailed; + return ack; + } + } + + // Copy the returned values on CONTROL before modifying the accepted PCM. + // Any graph/device change makes old draft readback unavailable. + [[nodiscard]] const SpeakerDraftReadback* speakerDraftReadback( + std::uint64_t epoch,std::uint64_t graphRevision) const noexcept { + if(!speakerDraft_ || speakerDraft_->deviceEpoch!=epoch || + speakerDraft_->graphRevision!=graphRevision || + !publisher_.controlPrepared(epoch,graphRevision))return nullptr; + return speakerDraft_.get(); + } + + // Closing a session, disconnecting device, or clearing a physical patch + // must invalidate readback before another control request arrives. + void revokeSpeakerDraft() noexcept { + speakerDraft_.reset(); + speakerPrepared_.reset(); + } + // Sole AUDIO CALLBACK path when connected by DYN1 live migration: // no alloc, mutex, wait, refcount, graph sorting or VST creation. // Caller-supplied FX owns its native ChannelId-keyed VST instance lease. @@ -168,7 +309,9 @@ class DynamicNativeSessionPublisher final { std::span channelPeaksR={}, std::span playerPcm={}, float* const* hardwareOutputs=nullptr, - int hardwareOutputCount=0) noexcept { + int hardwareOutputCount=0, + MainPcmObserver observer={}) noexcept { + static_assert(std::is_nothrow_invocable_v, "Realtime VST dispatch must be noexcept"); const auto clearOutputs=[&]() noexcept { @@ -241,6 +384,8 @@ class DynamicNativeSessionPublisher final { physical,physicalCount,mainL,mainR,frames, dispatch,monitorL,monitorR,channelPeaksL,channelPeaksR,playerPcm, hardwareOutputs,hardwareOutputCount); + if(ok && observer.observe) + observer.observe(observer.context,mainL,mainR,frames); if(!ok) { // A rejected physical callback (including aliased independent // amplifier buffers) emits silence, not a stale LIVE snapshot. @@ -284,10 +429,12 @@ class DynamicNativeSessionPublisher final { // Caller validates actual driver pins and MAIN/MONITOR collision first. bool setExternalOutput(std::uint64_t epoch,std::uint64_t revision, ChannelId id,int left,int right,int outputCount) noexcept { - return publisher_.updateActiveControl(epoch,revision, + const bool updated=publisher_.updateActiveControl(epoch,revision, [&](Prepared& active) noexcept { return active.graph.setExternalOutput(id,left,right,outputCount); }); + if(updated)revokeSpeakerDraft(); // physical pin inventory changed + return updated; } std::pair externalOutput(std::uint64_t epoch, std::uint64_t revision,ChannelId id) const noexcept { @@ -318,6 +465,13 @@ class DynamicNativeSessionPublisher final { return active.graph.setChannelMix(id,gain,pan); }); } + bool setChannelInputGain(std::uint64_t epoch,std::uint64_t revision, + ChannelId id,float gain) noexcept { + return publisher_.updateActiveControl(epoch,revision, + [&](Prepared& active) noexcept { + return active.graph.setChannelInputGain(id,gain); + }); + } bool setChannelMuteSolo(std::uint64_t epoch,std::uint64_t revision, ChannelId id,bool mute,bool solo) noexcept { return publisher_.updateActiveControl(epoch,revision, @@ -353,6 +507,40 @@ class DynamicNativeSessionPublisher final { return true; }); } + bool setParallelSendEnabled(std::uint64_t epoch,std::uint64_t revision, + ChannelId source,ChannelId destination, + bool preFader,bool enabled) noexcept { + return publisher_.updateActiveControl(epoch,revision, + [&](Prepared& active) noexcept { + const bool admitted=std::any_of(active.routing.edges.begin(), + active.routing.edges.end(),[&](const auto& edge){ + return edge.from==source&&edge.to==destination&& + edge.preFader==preFader&&!edge.primaryOutput; + }); + if(!admitted)return false; + if(active.graph.channelScheduled(source)&& + !active.graph.setParallelSendEnabled(source,destination,preFader,enabled)) + return false; + for(auto& edge:active.routing.edges) + if(edge.from==source&&edge.to==destination&& + edge.preFader==preFader&&!edge.primaryOutput)edge.enabled=enabled; + for(auto& row:active.routing.channels)if(row.id==source) + for(auto& edge:row.parallelSends) + if(edge.destination==destination&&edge.preFader==preFader) + edge.enabled=enabled; + return true; + }); + } + bool setWireEnabled(std::uint64_t epoch,std::uint64_t revision, + ChannelId source,std::uint64_t edgeId,bool enabled) noexcept { + const auto* routing=acceptedRouting(epoch,revision); + if(!routing||!edgeId)return false; + for(const auto& edge:routing->edges) + if(edge.edgeId==edgeId&&edge.from==source&&!edge.primaryOutput) + return setParallelSendEnabled(epoch,revision,source,edge.to, + edge.preFader,enabled); + return false; + } bool setWireGain(std::uint64_t epoch,std::uint64_t revision, ChannelId source,std::uint64_t edgeId,float gain) noexcept { const auto* routing=acceptedRouting(epoch,revision); @@ -368,7 +556,7 @@ class DynamicNativeSessionPublisher final { const auto* p=publisher_.controlPrepared(epoch,revision); return p?p->graph.latencySamples():0; } - void unpublish() noexcept {publisher_.unpublish();} + void unpublish() noexcept {revokeSpeakerDraft();publisher_.unpublish();} void pollRetirement() noexcept {publisher_.pollRetirement();} std::uint64_t acceptedRevision() const noexcept { return publisher_.lastRevision(); // CONTROL only diff --git a/engine/core/DynamicPreparedMixerBlock.h b/engine/core/DynamicPreparedMixerBlock.h index e44575411..454b7926b 100644 --- a/engine/core/DynamicPreparedMixerBlock.h +++ b/engine/core/DynamicPreparedMixerBlock.h @@ -64,7 +64,7 @@ class DynamicPreparedMixerBlock final { struct Edge final { std::size_t destination=0; float panL=0.f,panR=0.f,initialGain=1.f; - bool pre=false,primary=false; + bool pre=false,primary=false,enabled=true; }; struct Lane final { ChannelId id{}; @@ -98,7 +98,8 @@ class DynamicPreparedMixerBlock final { } struct ChannelTarget final { std::atomic state{Word::encode(1.f,1.f,false,false)}; - armix::dsp::RealtimeSlew64 appliedL{},appliedR{},gate{}; // AUDIO only + armix::dsp::RealtimeSlew64 appliedL{},appliedR{},gate{},inputApplied{}; // AUDIO only + std::atomic inputGain{1.f}; // CONTROL writes, AUDIO reads }; // CONTROL only packs already verified callback-ordinal physical pin pairs. // 0xFFFF means missing right input for mono, never an active physical pin. @@ -121,6 +122,7 @@ class DynamicPreparedMixerBlock final { static_assert(std::atomic::is_always_lock_free, "Realtime SEND must never enter a hidden blocking atomic path"); std::atomic gain{1.f}; + std::atomic enabled{true}; armix::dsp::RealtimeSlew64 applied{}; }; // O1: immutable lane roster + one lock-free control target per lane. @@ -172,6 +174,16 @@ class DynamicPreparedMixerBlock final { std::memory_order_release); return true; } + // CONTROL only: input DIGITAL trim, before FX, separate from FADER/PAN. + // 64-sample dezipper is owned by the existing native callback. + bool setChannelInputGain(ChannelId id,float gain) noexcept { + if(!id.value || !std::isfinite(gain) || gain<0.f || gain>16.f)return false; + const auto found=controlIndex_.find(id.value); + if(found==controlIndex_.end() || lanes_[found->second].role!=ChannelRole::input) + return false; + channelTargets_[found->second].inputGain.store(gain,std::memory_order_release); + return true; + } // Canonical physical-pin validation shared by structural preflight and // accepted realtime SOURCE changes. Never normalize an invalid draft // into an apparently successful ACK by replacing it with old pins. @@ -245,6 +257,22 @@ class DynamicPreparedMixerBlock final { } return false; } + bool setParallelSendEnabled(ChannelId source,ChannelId destination, + bool preFader,bool enabled) noexcept { + if(!source.value||!destination.value)return false; + const auto found=controlIndex_.find(source.value); + if(found==controlIndex_.end())return false; + const auto& lane=lanes_[found->second]; + for(std::size_t e=lane.first;e4.f || + !std::isfinite(row.inputGainLinear) || row.inputGainLinear<0.f || + row.inputGainLinear>16.f || + (row.role!=ChannelRole::input && row.inputGainLinear!=1.f) || !std::isfinite(row.pan) || row.pan< -1.f || row.pan>1.f || (row.format!=ProcessingFormat::mono && row.format!=ProcessingFormat::stereo) || @@ -483,8 +514,11 @@ class DynamicPreparedMixerBlock final { (send.pan>0.f?1.f-send.pan:1.f); const float gr=monoPre?std::sqrt(.5f*(1.f+send.pan)): (send.pan<0.f?1.f+send.pan:1.f); + if(send.primaryOutput&&!send.enabled){ + error={DynamicGraphFault::invalidSendDestination,rows[i].id};return false; + } outgoing[i].push_back({to,gl,gr,send.gain,send.preFader, - send.primaryOutput}); + send.primaryOutput,send.enabled}); parents[to].push_back(i); ++indegree[to]; } @@ -595,6 +629,8 @@ class DynamicPreparedMixerBlock final { target.appliedL.reset(next.lanes_[i].gainL); target.appliedR.reset(next.lanes_[i].gainR); target.gate.reset(next.initialAudible_[i]?1.f:0.f); + target.inputGain.store(rows[i].inputGainLinear,std::memory_order_relaxed); + target.inputApplied.reset(rows[i].inputGainLinear); } next.externalTargets_=std::make_unique[]>(rows.size()); next.externalAppliedTargets_=std::make_unique[]>(rows.size()); @@ -608,7 +644,8 @@ class DynamicPreparedMixerBlock final { for(std::size_t e=0;e +#include +#include +#include +#include +#include +#include + +namespace armix::lms { +struct NativePcmOutputInventory final { + // Obtained from the accepted ChannelId PCM graph + current device snapshot, + // NEVER from GUI labels or ordinal assumptions. + std::uint64_t deviceEpoch=0,acceptedGraphRevision=0,mainChannelId=0; + std::string deviceIdentity; + double sampleRate=0.; + int callbackOutputs=0; + int mainL=-1,mainR=-1,monitorL=-1,monitorR=-1; + bool acceptedChannelIdPcm=false,allOutputsDisarmed=false; + std::vector otherOccupiedOutputOrdinals; // e.g. EXTERNAL or BUS direct + std::vector enabledOutputPorts; +}; +enum class SpeakerReservationFault : std::uint8_t { + none,notAcceptedPcm,staleDevice,staleGraph,invalidSource, + deviceLayoutMismatch,occupiedOutput,unknownPort,unprotectedOutput +}; +struct SpeakerReservationResult final { + SpeakerReservationFault fault=SpeakerReservationFault::none; + std::vector reservedCallbackOrdinals; // CONTROL: explicit exclusive pins + std::uint64_t acceptedDeviceEpoch=0,acceptedGraphRevision=0; + bool mayWritePhysicalAudio=false; // M3 always FALSE: no calibrated limiter. + [[nodiscard]] bool ok() const noexcept{return fault==SpeakerReservationFault::none;} +}; +class NativeSpeakerOutputReservation final { +public: + // NO allocation in the realtime callback; only invoke from CONTROL with + // current device readback and accepted native ChannelId graph. + // Even an "unmuted" browser design cannot arm real loudspeakers using a + // Boolean acknowledgement or a digital hard clip masquerading as a limiter. + static SpeakerReservationResult preflight( + const SpeakerSystemRequest& request, + const NativePcmOutputInventory& accepted, + std::uint64_t requestedSourceChannelId) { + SpeakerReservationResult report{}; + auto reject=[&](SpeakerReservationFault reason) { + report.fault=reason; + report.reservedCallbackOrdinals.clear(); + return report; + }; + if(!accepted.acceptedChannelIdPcm||!accepted.allOutputsDisarmed|| + accepted.deviceIdentity.empty()||accepted.deviceEpoch==0|| + accepted.acceptedGraphRevision==0) + return reject(SpeakerReservationFault::notAcceptedPcm); + if(request.deviceEpoch!=accepted.deviceEpoch) + return reject(SpeakerReservationFault::staleDevice); + if(request.graphRevision!=accepted.acceptedGraphRevision) + return reject(SpeakerReservationFault::staleGraph); + if(!requestedSourceChannelId||requestedSourceChannelId!=accepted.mainChannelId) + return reject(SpeakerReservationFault::invalidSource); + if(request.activeOutputChannels!=accepted.callbackOutputs|| + accepted.callbackOutputs<2||accepted.callbackOutputs>256|| + !std::isfinite(accepted.sampleRate)|| + accepted.sampleRate!=request.sampleRate|| + accepted.mainL<0||accepted.mainR<0|| + accepted.mainL==accepted.mainR|| + accepted.mainL>=accepted.callbackOutputs|| + accepted.mainR>=accepted.callbackOutputs) + return reject(SpeakerReservationFault::deviceLayoutMismatch); + auto owned=accepted.otherOccupiedOutputOrdinals; + owned.push_back(accepted.mainL);owned.push_back(accepted.mainR); + if(accepted.monitorL>=0||accepted.monitorR>=0) { + if(accepted.monitorL<0||accepted.monitorR<0|| + accepted.monitorL==accepted.monitorR|| + accepted.monitorL>=accepted.callbackOutputs|| + accepted.monitorR>=accepted.callbackOutputs) + return reject(SpeakerReservationFault::deviceLayoutMismatch); + owned.push_back(accepted.monitorL);owned.push_back(accepted.monitorR); + } + std::unordered_set used; + for(const auto pin:owned) + if(pin<0||pin>=accepted.callbackOutputs||!used.insert(pin).second) + return reject(SpeakerReservationFault::deviceLayoutMismatch); + for(const auto& selected:request.outputs) { + const auto verified=std::find_if(accepted.enabledOutputPorts.begin(), + accepted.enabledOutputPorts.end(),[&](const VerifiedOutputPort& p){ + return p.identity==selected.portIdentity; + }); + const auto draft=std::find_if(request.verifiedPorts.begin(), + request.verifiedPorts.end(),[&](const VerifiedOutputPort& p){ + return p.identity==selected.portIdentity; + }); + if(verified==accepted.enabledOutputPorts.end()|| + draft==request.verifiedPorts.end()|| + verified->callbackOrdinal!=draft->callbackOrdinal) + return reject(SpeakerReservationFault::unknownPort); + const int ordinal=verified->callbackOrdinal; + if(ordinal<0||ordinal>=accepted.callbackOutputs) + return reject(SpeakerReservationFault::unknownPort); + if(!used.insert(ordinal).second) + return reject(SpeakerReservationFault::occupiedOutput); + report.reservedCallbackOrdinals.push_back(ordinal); + // The M2 "limiter" is currently a HARD DIGITAL CEILING, not a + // calibrated voltage/RMS/peak speaker safety DSP. No live output + // authorization is legal merely because a user enabled it. + if(!selected.mute) + return reject(SpeakerReservationFault::unprotectedOutput); + } + report.acceptedDeviceEpoch=accepted.deviceEpoch; + report.acceptedGraphRevision=accepted.acceptedGraphRevision; + // Result describes only a safely disconnected mapping draft. + // A later true native limiter + verified profile must introduce a + // distinct typed hardware publication transaction. + return report; + } +}; +} // namespace armix::lms diff --git a/engine/lms/PreparedSpeakerSystem.h b/engine/lms/PreparedSpeakerSystem.h new file mode 100644 index 000000000..8762e8002 --- /dev/null +++ b/engine/lms/PreparedSpeakerSystem.h @@ -0,0 +1,326 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// LMS M2 native PCM kernel. Not a second callback, mixer, or device manager. +// CONTROL: validate/compile/allocate. AUDIO: bounded process only. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace armix::lms { +struct VerifiedOutputPort final { + std::string identity; // exact verified device-native pin, not DEMO/GUI ordinal + int callbackOrdinal=-1; +}; +struct ParametricBand final { + double frequencyHz=1000.,q=0.70710678118,gainDb=0.; + bool enabled=true; // same bypass semantics as LMS Output EQ editor +}; +struct OutputPatch final { + std::string outputId,portIdentity; + int sourceSide=0,section=0; // section [0,ways); side 0=L/mono, 1=R + double delayMs=0.,gainDb=0.; + std::vector peq; // max 8 fully prepared peaking bands + bool mute=true,limiterEnabled=false,polarityInverted=false; + double ceilingDbfs=-6.; + // A host-owned, explicit operator acknowledgement, NOT proof of physical protection. + bool confirmedSpeakerProfile=false; +}; +struct SpeakerSystemRequest final { + std::uint64_t deviceEpoch=0,graphRevision=0; + double sampleRate=0.; + int maxFrames=0,activeOutputChannels=0,ways=2; // 1..16, budget constrained + bool stereo=true; + std::vector crossoverHz; // ascending, ways-1 + std::vector verifiedPorts; + std::vector outputs; + std::size_t scratchBudgetBytes=16U*1024U*1024U; +}; +enum class SpeakerPlanFault : std::uint8_t { + none,invalidEpoch,invalidFormat,invalidCrossover,invalidPort, + duplicatePort,invalidRoute,invalidOutputDsp,unconfirmedSpeaker, + scratchBudget,preparationFailed +}; +struct SpeakerPrepareResult final { + SpeakerPlanFault fault=SpeakerPlanFault::none; + std::size_t scratchBytes=0; + [[nodiscard]] bool ok() const noexcept {return fault==SpeakerPlanFault::none;} +}; + +// 2 x 2nd-order Butterworth = LR4, 24 dB/oct, in-phase complementary pair. +struct Biquad final { + double b0=1.,b1=0.,b2=0.,a1=0.,a2=0.,z1=0.,z2=0.; + [[nodiscard]] float process(float in) noexcept { + const double x=static_cast(in),y=b0*x+z1; + z1=b1*x-a1*y+z2;z2=b2*x-a2*y; + if(std::abs(z1)<1.e-28)z1=0.; + if(std::abs(z2)<1.e-28)z2=0.; + return static_cast(y); + } + static Biquad make(double sr,double hz,bool high) noexcept { + constexpr double q=0.7071067811865475244; + constexpr double pi=3.14159265358979323846; + const double w=2.*pi*hz/sr,c=std::cos(w),a=std::sin(w)/(2.*q); + const double scale=1./(1.+a); + Biquad b; + b.b0=((high?(1.+c):(1.-c))*.5)*scale; + b.b1=(high?-(1.+c):(1.-c))*scale; + b.b2=b.b0;b.a1=-2.*c*scale;b.a2=(1.-a)*scale; + return b; + } + static Biquad peak(double sr,double hz,double q,double gainDb) noexcept { + constexpr double pi=3.14159265358979323846; + const double w=2.*pi*hz/sr,c=std::cos(w),alpha=std::sin(w)/(2.*q); + const double A=std::pow(10.,gainDb/40.),scale=1./(1.+alpha/A); + Biquad b; + b.b0=(1.+alpha*A)*scale; + b.b1=-2.*c*scale; + b.b2=(1.-alpha*A)*scale; + b.a1=b.b1; + b.a2=(1.-alpha/A)*scale; + return b; + } +}; + +class PreparedSpeakerSystem final { + struct Section final { + int side=0,way=0; + std::array hp{},lp{}; + bool hasHigh=false,hasLow=false; + }; + struct Destination final { + int source=0,physical=0; + float gain=1.f,ceiling=1.f,polarity=1.f; + bool mute=true,limit=false; + double delaySamples=0.; + std::vector eq; + std::vector ring; + std::size_t write=0; + [[nodiscard]] float delay(float sample) noexcept { + if(delaySamples<=0.)return sample; + ring[write]=sample; + double read=static_cast(write)-delaySamples; + if(read<0.)read+=static_cast(ring.size()); + const auto index=static_cast(read); + const auto other=(index+1)%ring.size(); + const float frac=static_cast(read-static_cast(index)); + const float result=ring[index]+(ring[other]-ring[index])*frac; + if(++write==ring.size())write=0; + return result; + } + }; + std::uint64_t epoch_=0,revision_=0; + int capacity_=0,physicalCount_=0,ways_=0; + bool stereo_=false; + std::vector
sections_; + std::vector destinations_; + std::vector scratch_; + std::size_t usedBytes_=0; +public: + PreparedSpeakerSystem()=default; + PreparedSpeakerSystem(const PreparedSpeakerSystem&)=delete; + PreparedSpeakerSystem& operator=(const PreparedSpeakerSystem&)=delete; + PreparedSpeakerSystem(PreparedSpeakerSystem&&)=default; + PreparedSpeakerSystem& operator=(PreparedSpeakerSystem&&)=default; + [[nodiscard]] std::size_t scratchBytes() const noexcept{return usedBytes_;} + [[nodiscard]] std::size_t sectionCount() const noexcept{return sections_.size();} + [[nodiscard]] std::size_t destinationCount() const noexcept{return destinations_.size();} + [[nodiscard]] std::uint64_t epoch() const noexcept{return epoch_;} + [[nodiscard]] std::uint64_t revision() const noexcept{return revision_;} + + // A rejected candidate NEVER changes the prior accepted snapshot. + static SpeakerPrepareResult prepare(const SpeakerSystemRequest& req, + std::unique_ptr& accepted) { + SpeakerPrepareResult result; + try { + if(!req.deviceEpoch||!req.graphRevision){ + result.fault=SpeakerPlanFault::invalidEpoch;return result; + } + if(!(req.sampleRate>=8000.&&req.sampleRate<=384000.)|| + !std::isfinite(req.sampleRate)||req.maxFrames<1||req.maxFrames>8192|| + req.ways<1||req.ways>16||req.activeOutputChannels<1|| + req.activeOutputChannels>256){ + result.fault=SpeakerPlanFault::invalidFormat;return result; + } + if(req.crossoverHz.size()!=static_cast(req.ways-1)){ + result.fault=SpeakerPlanFault::invalidCrossover;return result; + } + double prev=15.; + for(const auto hz:req.crossoverHz){ + if(!std::isfinite(hz)||hz<20.||hz<=prev*1.01|| + hz>=req.sampleRate*.45){ + result.fault=SpeakerPlanFault::invalidCrossover;return result; + } + prev=hz; + } + std::unordered_set names; + std::unordered_set ordinals; + if(req.verifiedPorts.empty()||req.verifiedPorts.size()>256){ + result.fault=SpeakerPlanFault::invalidPort;return result; + } + for(const auto& p:req.verifiedPorts) { + if(p.identity.empty()||p.identity.starts_with("DEMO-")|| + p.callbackOrdinal<0||p.callbackOrdinal>=req.activeOutputChannels|| + !names.insert(p.identity).second|| + !ordinals.insert(p.callbackOrdinal).second){ + result.fault=SpeakerPlanFault::invalidPort;return result; + } + } + if(req.outputs.size()>req.verifiedPorts.size()){ + result.fault=SpeakerPlanFault::invalidPort;return result; + } + std::unordered_set logical; + std::unordered_set physical; + std::size_t totalRing=0,totalEq=0; + for(const auto& p:req.outputs){ + if(p.outputId.empty()||p.portIdentity.empty()|| + !logical.insert(p.outputId).second|| + !physical.insert(p.portIdentity).second){ + result.fault=SpeakerPlanFault::duplicatePort;return result; + } + if((p.sourceSide!=0&&p.sourceSide!=1)|| + (!req.stereo&&p.sourceSide!=0)|| + p.section<0||p.section>=req.ways){ + result.fault=SpeakerPlanFault::invalidRoute;return result; + } + if(!std::any_of(req.verifiedPorts.begin(),req.verifiedPorts.end(), + [&](const auto& x){return x.identity==p.portIdentity;})){ + result.fault=SpeakerPlanFault::invalidPort;return result; + } + if(!std::isfinite(p.gainDb)||p.gainDb< -60.||p.gainDb>6.|| + !std::isfinite(p.delayMs)||p.delayMs<0.||p.delayMs>500.|| + !std::isfinite(p.ceilingDbfs)||p.ceilingDbfs< -60.||p.ceilingDbfs>0.){ + result.fault=SpeakerPlanFault::invalidOutputDsp;return result; + } + if(p.peq.size()>8){ + result.fault=SpeakerPlanFault::invalidOutputDsp;return result; + } + for(const auto& band:p.peq) + if(!std::isfinite(band.frequencyHz)||band.frequencyHz<20.|| + band.frequencyHz>=req.sampleRate*.45|| + !std::isfinite(band.q)||band.q<.1||band.q>18.|| + !std::isfinite(band.gainDb)||band.gainDb< -18.|| + band.gainDb>18.){ + result.fault=SpeakerPlanFault::invalidOutputDsp;return result; + } + totalEq+=p.peq.size(); + if(!p.mute&&(!p.confirmedSpeakerProfile||!p.limiterEnabled)){ + result.fault=SpeakerPlanFault::unconfirmedSpeaker;return result; + } + const double samples=std::ceil(p.delayMs*req.sampleRate/1000.); + if(samples>=static_cast( + std::numeric_limits::max()/sizeof(float)-4)){ + result.fault=SpeakerPlanFault::scratchBudget;return result; + } + totalRing+=static_cast(samples)+3; + } + const auto sections=static_cast(req.ways)*(req.stereo?2U:1U); + const auto maxFloats=req.scratchBudgetBytes/sizeof(float); + if(sections>maxFloats/static_cast(req.maxFrames)|| + totalRing>maxFloats-sections*static_cast(req.maxFrames)|| + totalEq*sizeof(Biquad)>req.scratchBudgetBytes- + (totalRing+sections*static_cast(req.maxFrames))*sizeof(float)){ + result.fault=SpeakerPlanFault::scratchBudget;return result; + } + auto next=std::make_unique(); + next->epoch_=req.deviceEpoch;next->revision_=req.graphRevision; + next->capacity_=req.maxFrames;next->physicalCount_=req.activeOutputChannels; + next->ways_=req.ways;next->stereo_=req.stereo; + next->scratch_.resize(sections*static_cast(req.maxFrames)); + next->sections_.reserve(sections); + for(int side=0;side<(req.stereo?2:1);++side) + for(int way=0;way0){ + s.hasHigh=true; + s.hp[0]=s.hp[1]=Biquad::make(req.sampleRate,req.crossoverHz[way-1],true); + } + if(waysections_.push_back(s); + } + next->destinations_.reserve(req.outputs.size()); + for(const auto& p:req.outputs){ + Destination d; + const auto pin=std::find_if(req.verifiedPorts.begin(),req.verifiedPorts.end(), + [&](const auto& x){return x.identity==p.portIdentity;}); + d.physical=pin->callbackOrdinal; + d.source=p.sourceSide*req.ways+p.section; + d.gain=static_cast(std::pow(10.,p.gainDb/20.)); + d.mute=p.mute;d.limit=p.limiterEnabled; + d.polarity=p.polarityInverted?-1.f:1.f; + d.ceiling=static_cast(std::pow(10.,p.ceilingDbfs/20.)); + d.delaySamples=p.delayMs*req.sampleRate/1000.; + d.eq.reserve(p.peq.size()); + for(const auto& band:p.peq) + if(band.enabled) + d.eq.push_back(Biquad::peak(req.sampleRate,band.frequencyHz, + band.q,band.gainDb)); + if(d.delaySamples>0.) + d.ring.resize(static_cast(std::ceil(d.delaySamples))+3); + next->destinations_.push_back(std::move(d)); + } + next->usedBytes_=next->scratch_.size()*sizeof(float); + for(const auto& d:next->destinations_) + next->usedBytes_+=d.ring.size()*sizeof(float)+d.eq.size()*sizeof(Biquad); + result.scratchBytes=next->usedBytes_; + accepted=std::move(next); + return result; + }catch(...){ + result.fault=SpeakerPlanFault::preparationFailed;return result; + } + } + // AUDIO only. All source planes are copied into prepared section buffers + // BEFORE output writes, so input aliasing physical MAIN is supported. + // On stale epoch/revision, bad frame count, or absent pin: zero writes. + [[nodiscard]] bool process(std::uint64_t currentDeviceEpoch, + std::uint64_t acceptedGraphRevision,const float* mainL, + const float* mainR,float* const* output,int physicalCount, + int frames,bool nativeOutputAuthorized) noexcept { + if(!nativeOutputAuthorized||currentDeviceEpoch!=epoch_|| + acceptedGraphRevision!=revision_||physicalCount!=physicalCount_|| + frames<1||frames>capacity_||!mainL||(stereo_&&!mainR)||!output) + return false; + for(const auto& d:destinations_) + if(d.physical<0||d.physical>=physicalCount||!output[d.physical]) + return false; + if(destinations_.empty())return true; // no active physical pins + for(std::size_t idx=0;idx(capacity_); + for(int i=0;i(d.source)*capacity_; + if(d.mute){std::fill_n(out,frames,0.f);continue;} + for(int i=0;i16.) + return reject("INPUT_GAIN_READBACK_UNAVAILABLE"); + const double nativeDb=nativeGain>0.?20.*std::log10(nativeGain):-144.; + if(std::abs(nativeDb-acceptedDb)>0.12) + return reject("STALE_INPUT_GAIN_READBACK"); + const auto payload=publicIntent.getProperty("payload",{}); + if(!payload.isObject()|| + !nativeV8Number(payload.getProperty("valueDb",{}),requestedDb)|| + requestedDb< -24.||requestedDb>24.) + return reject("INVALID_INPUT_GAIN_VALUE"); + const double linear=std::pow(10.,requestedDb/20.); + if(!std::isfinite(linear)||linear>16.)return reject("INPUT_GAIN_UNREPRESENTABLE"); + auto args=std::make_unique(); + args->setProperty("gain",linear); + auto translated=std::make_unique(); + translated->setProperty("requestId",request); + translated->setProperty("deviceEpoch",epoch); + translated->setProperty("baseGraphRevision",revision); + translated->setProperty("baseRosterRevision",roster); + translated->setProperty("targetChannelId",ids); + translated->setProperty("operation","NATIVE_SET_INPUT_GAIN"); + translated->setProperty("payload",juce::var(args.release())); + return {juce::var(translated.release()),{}}; + } if(op=="SET_PROCESSING_FORMAT") { if(!approvedHasOperation(caps.getProperty("supportedOps",{}), "SET_PROCESSING_FORMAT") || @@ -108,6 +153,45 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( converted->setProperty("payload",juce::var(checked.release())); return {juce::var(converted.release()),{}}; } + if(op=="SET_SEND_ENABLED") { + if(!approvedHasOperation(caps.getProperty("supportedOps",{}),"SET_SEND_ENABLED")|| + !approvedHasOperation(installedBus.getProperty("supportedOps",{}), + "NATIVE_SET_SEND_ENABLED")) + return reject("NATIVE_SEND_ENABLE_NOT_ADMITTED"); + const auto payload=publicIntent.getProperty("payload",{}); + const auto edgeId=payload.getProperty("edgeId",{}); + const auto enabled=payload.getProperty("enabled",{}); + if(!nativeV8Decimal(edgeId)||!enabled.isBool()) + return reject("INVALID_SEND_ENABLE_PAYLOAD"); + juce::var pub,native; + const auto p=graph.getProperty("edges",{}),n=installedBus.getProperty("edges",{}); + if(!p.isArray()||!n.isArray())return reject("WIRE_EDGE_INVENTORY_UNAVAILABLE"); + for(const auto& e:*p.getArray()) + if(e.getProperty("edgeId",{})==edgeId&&e.getProperty("from",{})==ids)pub=e; + for(const auto& e:*n.getArray()) + if(e.getProperty("edgeId",{})==edgeId&&e.getProperty("from",{})==ids)native=e; + if(!pub.isObject()||!native.isObject()|| + pub.getProperty("primaryOutput",{})!=juce::var(false)|| + native.getProperty("primaryOutput",{})!=juce::var(false)|| + pub.getProperty("to",{})!=native.getProperty("to",{})|| + pub.getProperty("tap",{})!=native.getProperty("tap",{})|| + !pub.getProperty("sendEnabled",{}).isBool()|| + !native.getProperty("enabled",{}).isBool()|| + pub.getProperty("sendEnabled",{})!=native.getProperty("enabled",{})|| + pub.getProperty("sendEnabled",{})==enabled) + return reject("SEND_ENABLE_STALE_OR_UNCHANGED"); + auto args=std::make_unique(); + args->setProperty("edgeId",edgeId);args->setProperty("enabled",enabled); + auto converted=std::make_unique(); + converted->setProperty("requestId",request); + converted->setProperty("deviceEpoch",epoch); + converted->setProperty("baseGraphRevision",revision); + converted->setProperty("baseRosterRevision",roster); + converted->setProperty("targetChannelId",ids); + converted->setProperty("operation","NATIVE_SET_SEND_ENABLED"); + converted->setProperty("payload",juce::var(args.release())); + return {juce::var(converted.release()),{}}; + } if(op=="SET_WIRE_GAIN") { if(!approvedHasOperation(caps.getProperty("supportedOps",{}),"SET_WIRE_GAIN")|| !approvedHasOperation(installedBus.getProperty("supportedOps",{}),"NATIVE_SET_WIRE_GAIN")) @@ -181,12 +265,12 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( const auto from=edit.getProperty("from",{}); if(from.toString()!=ids.toString()|| (kind!="CONNECT" && kind!="REMOVE" && - kind!="RETARGET" && kind!="ROUTE_ONLY")) + kind!="RETARGET" && kind!="ROUTE_ONLY" && kind!="SET_TAP")) return reject("WIRE_SOURCE_OR_OPERATION_INVALID"); auto item=std::make_unique(); item->setProperty("op",kind); item->setProperty("from",ids); - if(kind=="REMOVE" || kind=="RETARGET") { + if(kind=="REMOVE" || kind=="RETARGET" || kind=="SET_TAP") { const auto edgeId=edit.getProperty("edgeId",{}); if(!nativeV8Decimal(edgeId))return reject("WIRE_EDGE_ID_INVALID"); bool pubFound=false,nativeFound=false; @@ -199,6 +283,27 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( e.getProperty("from","").toString()==ids.toString()) nativeFound=true; if(!pubFound||!nativeFound)return reject("WIRE_STALE_EDGE"); + if(kind=="SET_TAP") { + juce::var pub,native; + for(const auto& e:*pubEdges.getArray()) + if(e.getProperty("edgeId",{})==edgeId && + e.getProperty("from",{})==ids)pub=e; + for(const auto& e:*nativeEdges.getArray()) + if(e.getProperty("edgeId",{})==edgeId && + e.getProperty("from",{})==ids)native=e; + const auto expectedTap=edit.getProperty("tap","").toString(); + const auto currentTap=pub.getProperty("tap","").toString(); + const auto nativeTap=native.getProperty("tap","").toString(); + if(!pub.isObject()||!native.isObject()|| + pub.getProperty("primaryOutput",{})!=juce::var(false)|| + native.getProperty("primaryOutput",{})!=juce::var(false)|| + pub.getProperty("to",{})!=native.getProperty("to",{})|| + currentTap!=nativeTap || + (expectedTap!="PRE_FADER"&&expectedTap!="POST_FADER")|| + currentTap==expectedTap) + return reject("WIRE_TAP_NOT_ADMITTED"); + item->setProperty("tap",expectedTap); + } item->setProperty("edgeId",edgeId); } if(kind=="CONNECT" || kind=="RETARGET" || kind=="ROUTE_ONLY") { @@ -505,6 +610,24 @@ inline bool executeApprovedNativeControl(Engine& engine, return result.accepted&&result.error&&result.error[0]==0; }else return false; } + if(operation=="NATIVE_SET_INPUT_GAIN") { + double gain=0.; + if(!nativeV8Number(payload.getProperty("gain",{}),gain)|| + gain<0.f||gain>16.f)return false; + if constexpr(requires(Engine& e){e.setNativeInputGain(epoch,revision,channel,0.f);}) + return engine.setNativeInputGain(epoch,revision,channel,static_cast(gain)); + return false; + } + if(operation=="NATIVE_SET_SEND_ENABLED") { + std::uint64_t edge=0; + const auto enabled=payload.getProperty("enabled",{}); + if(!approvedNativeId(payload.getProperty("edgeId",{}),edge)|| + !enabled.isBool())return false; + if constexpr(requires(Engine& e){e.setNativeWireEnabled(epoch,revision,roster,channel,edge,true);}) + return engine.setNativeWireEnabled(epoch,revision,roster,channel,edge, + static_cast(enabled)); + return false; + } if(operation=="NATIVE_SET_WIRE_GAIN") { std::uint64_t edge=0;double gain=0.; if(!approvedNativeId(payload.getProperty("edgeId",{}),edge)|| @@ -531,16 +654,22 @@ inline bool executeApprovedNativeControl(Engine& engine, else if(op=="REMOVE")change.kind=armix::mixer::WireChange::Kind::remove; else if(op=="RETARGET")change.kind=armix::mixer::WireChange::Kind::retarget; else if(op=="ROUTE_ONLY")change.kind=armix::mixer::WireChange::Kind::routeOnly; + else if(op=="SET_TAP")change.kind=armix::mixer::WireChange::Kind::setTap; else return false; if(op=="CONNECT"||op=="RETARGET"||op=="ROUTE_ONLY") { if(!approvedNativeId(edit.getProperty("to",{}),to)||to==from) return false; change.to=armix::mixer::ChannelId{to}; } - if(op=="REMOVE"||op=="RETARGET") { + if(op=="REMOVE"||op=="RETARGET"||op=="SET_TAP") { if(!approvedNativeId(edit.getProperty("edgeId",{}),edgeId)) return false; change.edgeId=edgeId; + if(op=="SET_TAP") { + const auto tap=edit.getProperty("tap","").toString(); + if(tap!="PRE_FADER"&&tap!="POST_FADER")return false; + change.preFader=tap=="PRE_FADER"; + } } if(op=="CONNECT"||op=="ROUTE_ONLY") { double gain=0.; diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index 2b3207ea9..2ce7c450b 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -295,6 +295,7 @@ inline bool projectInstalledNativeChannelIdGraph( available.add(juce::String("SET_FADER")); available.add(juce::String("SET_PAN")); } + if(has("NATIVE_SET_INPUT_GAIN"))available.add(juce::String("SET_INPUT_GAIN")); if(has("NATIVE_SET_CHANNEL_MUTE_SOLO")) { available.add(juce::String("SET_MUTE")); available.add(juce::String("SET_SOLO")); @@ -306,6 +307,8 @@ inline bool projectInstalledNativeChannelIdGraph( available.add(juce::String("APPLY_WIRE_TRANSACTION")); if(has("NATIVE_SET_WIRE_GAIN")) available.add(juce::String("SET_WIRE_GAIN")); + if(has("NATIVE_SET_SEND_ENABLED")) + available.add(juce::String("SET_SEND_ENABLED")); if(has("NATIVE_SET_PROCESSING_FORMAT")) available.add(juce::String("SET_PROCESSING_FORMAT")); if(has("NATIVE_REMOVE_INSERT"))available.add(juce::String("REMOVE_INSERT")); diff --git a/integration/ApprovedNativeV8Projection.h b/integration/ApprovedNativeV8Projection.h index c444c726c..700e428c9 100644 --- a/integration/ApprovedNativeV8Projection.h +++ b/integration/ApprovedNativeV8Projection.h @@ -79,6 +79,18 @@ inline bool projectNativeGraph(juce::var& snapshot,const juce::var& bus, auto controls=std::make_unique(); const double db=linear>0.?20.*std::log10(linear):-60.; controls->setProperty("faderDb",juce::jlimit(-60.,12.,db)); + // Source-owned native digital trim is not the hardware preamp. + // Missing field on legacy snapshots remains unadmitted, never 0 dB guessed. + const auto trim=row.getProperty("inputGain",{}); + double inputLinear=0.; + if(trim.isVoid()) { + // Historical/retained snapshots may predate digital gain. + } else { + if(!nativeV8Number(trim,inputLinear)||inputLinear<0.||inputLinear>16.|| + (role!="INPUT"&&inputLinear!=1.))return false; + if(role=="INPUT")controls->setProperty("inputGainDb", + inputLinear>0.?20.*std::log10(inputLinear):-144.); + } controls->setProperty("pan",p); controls->setProperty("mute",mute);controls->setProperty("solo",solo); ch->setProperty("controls",juce::var(controls.release())); @@ -140,6 +152,7 @@ inline bool projectNativeGraph(juce::var& snapshot,const juce::var& bus, to=edge.getProperty("to",{}),gain=edge.getProperty("gainLinear",{}); const auto tap=edge.getProperty("tap","").toString(); const auto primary=edge.getProperty("primaryOutput",{}); + const auto nativeEnabled=edge.getProperty("enabled",{}); double linear=0.; if(!nativeV8Decimal(id)||!nativeV8Decimal(from)||!nativeV8Decimal(to)|| from.toString()==to.toString()|| @@ -148,18 +161,23 @@ inline bool projectNativeGraph(juce::var& snapshot,const juce::var& bus, !ids.count(to.toString().toStdString())|| from.toString()==mainId||(tap!="PRE_FADER"&&tap!="POST_FADER")|| !nativeV8Number(gain,linear)||linear<0.||linear>4.|| - !primary.isBool())return false; + !primary.isBool()||(!nativeEnabled.isVoid()&&!nativeEnabled.isBool())|| + (static_cast(primary)&&nativeEnabled==juce::var(false)))return false; auto w=std::make_unique(); w->setProperty("edgeId",id);w->setProperty("from",from);w->setProperty("to",to); w->setProperty("tap",tap);w->setProperty("gainLinear",linear); w->setProperty("primaryOutput",primary); - w->setProperty("enabled",true);w->setProperty("signalKind","AUDIO"); + // Connected patch identity survives SEND OFF; audio gate is separate. + w->setProperty("enabled",true); + w->setProperty("sendEnabled",nativeEnabled.isVoid()?true:static_cast(nativeEnabled)); + w->setProperty("signalKind","AUDIO"); wires.add(juce::var(w.release())); if(!static_cast(primary))for(auto& channel:channels) { if(channel.getProperty("id","").toString()!=from.toString())continue; auto send=std::make_unique(); send->setProperty("id",id);send->setProperty("targetId",to); send->setProperty("tap",tap);send->setProperty("gainLinear",linear); + send->setProperty("sendEnabled",nativeEnabled.isVoid()?true:static_cast(nativeEnabled)); const auto list=channel.getProperty("sends",{}); if(auto* a=list.getArray())a->add(juce::var(send.release())); break; diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index c395e277f..fc3f502dd 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -216,6 +216,9 @@ def accepted_pages_html() -> str: "window.__ARMIX_NATIVE_SCOPE__=Object.freeze({\n" " get tracks(){return tracks;},get master(){return master;},\n" " get wireEdges(){return wireEdges;}, // native read-only UI edge identity\n" + " get sofEnabled(){return sofEnabled;},get sofTarget(){return sofTarget;},\n" + " get sofTargetId(){return sofTargetId;},toggleSof,\n" + " get selectedWireEdgeId(){return selectedWireEdgeId;},\n" " get wireGainDragging(){return !!sendKnobDrag;},paintWireKnob,\n" " syncNativeWireGains(rows){\n" " for(const row of rows){\n" @@ -226,8 +229,31 @@ def accepted_pages_html() -> str: " if(input&&input!==sendKnobDrag?.input&&!row.pending){\n" " input.value=String(row.levelDb);paintWireKnob(input,row.levelDb);\n" " }\n" + " // Inspector LCD follows independent accepted native PCM readback,\n" + " // not a speculative range input. No strip or inspector rerender.\n" + " const ws=document.getElementById('wireWsGain');\n" + " if(ws?.dataset.wsGain===String(edge.id)&&!row.pending){\n" + " if(document.activeElement!==ws)ws.value=String(row.levelDb);\n" + " const value=document.getElementById('wireWsGainText');\n" + " if(value)value.textContent=row.levelDb+' dB';\n" + " }\n" " }\n" " },\n" + " rollbackNativeWireInspector(rows){\n" + " const gain=document.getElementById('wireWsGain');\n" + " const text=document.getElementById('wireWsGainText');\n" + " // Rejection/expiry has no new PCM snapshot. Restore the last admitted\n" + " // readback in-place rather than leaving a forever-PENDING inspector.\n" + " if(!gain||!text?.textContent?.startsWith('PENDING · '))return false;\n" + " const id=Number(gain.dataset.wsGain);\n" + " const edge=wireEdges.find(e=>e.id===id&&e.kind!=='primary'&&e.enabled);\n" + " const row=Array.isArray(rows)?rows.find(r=>r.id===id&&Number.isFinite(r.levelDb)):null;\n" + " if(!edge||!row){gain.disabled=true;text.textContent='SEND UNAVAILABLE';return true;}\n" + " edge.levelDb=row.levelDb;\n" + " gain.value=String(row.levelDb); // same focused input, no DOM replacement\n" + " text.textContent='UNCHANGED · '+row.levelDb+' dB';\n" + " return true;\n" + " },\n" " syncVerifiedM4Wires(rows,ids){\n" " if(!Array.isArray(rows)||rows.length!==10||!Array.isArray(ids)||ids.length!==10)\n" " return false;\n" @@ -283,6 +309,21 @@ def accepted_pages_html() -> str: ) +# Native-only WIRE Inspector: keep the public /preview/ HTML strictly unchanged. +# These fail-closed exact-source edits are reversed by public_from_native(). +# A PRIMARY_OUT is unity, a PARALLEL_SEND can target MAIN, and native edits +# are never accepted by the browser mock before installed PCM readback. +NATIVE_EVENT_HOOKS += ( + (" const tapEditable=!native||(src.nativeTapAvailable===true&&\n edge?.kind==='send'&&['PRE_FADER','POST_FADER'].includes(edge.nativeTap));\n", + " const gainEditable=edge&&(!native?edge.kind!=='primary':\n window.__ARMIX_NATIVE_M2__?.canWireGain?.(edge.id,edge.sourceId)===true);\n const tapEditable=edge&&(!native?edge.kind!=='primary':\n window.__ARMIX_NATIVE_M2__?.canWireTap?.(edge.id,edge.sourceId)===true);\n"), + (" const controls=edge?\n '
'+\n ''+\n ''+edge.levelDb+' dB'+\n ''+\n ''+\n '
':\n '
Managed by existing '+escapeHtml(info.kind.toUpperCase())+' routing. No duplicate WIRE edge.
';\n", + " const controls=edge?\n '
'+\n ''+\n ''+(edge.kind==='primary'?'PRIMARY · UNITY':\n edge.levelDb+' dB')+''+\n ''+\n ''+\n '
':\n '
Managed by existing '+escapeHtml(info.kind.toUpperCase())+' routing. No duplicate WIRE edge.
';\n"), + ("document.getElementById('wireWsInspector').addEventListener('input',e=>{\n const gain=e.target.closest?.('[data-ws-gain]');\n if(!gain)return;\n const edge=wireEdges.find(x=>x.id===Number(gain.dataset.wsGain)&&x.enabled);\n if(!edge||edge.destId===master.id)return;\n const amount=Math.max(-60,Math.min(6,Math.round(Number(gain.value)||0)));\n if(!wireGraphCommit([{type:'GAIN',sourceId:edge.sourceId,edgeId:edge.id,\n levelDb:amount}],{record:false}))return;\n document.getElementById('wireWsGainText').textContent=amount+' dB';\n});\ndocument.getElementById('wireWsInspector').addEventListener('change',e=>{\n const gain=e.target.closest?.('[data-ws-gain]'),tap=e.target.closest?.('[data-ws-tap]');\n if(tap){\n const edge=wireEdges.find(x=>x.id===Number(tap.dataset.wsTap)&&x.enabled);\n if(!edge||!wireGraphCommit([{type:'MODE',sourceId:edge.sourceId,edgeId:edge.id,\n mode:tap.value==='split'?'split':'send'}],{record:false}))return;\n const owner=wireSourceTrack(edge.sourceId);if(owner)owner.wireTapMode=tap.value==='split'?'split':'send';\n }\n if(gain||tap){\n wireWsRecord(wireWsEditBefore);wireWsEditBefore=null;render();renderWireWorkspace();\n say('WIRE inspector accepted · reference graph only');\n }\n});\n\n", + "document.getElementById('wireWsInspector').addEventListener('input',e=>{\n const gain=e.target.closest?.('[data-ws-gain]');\n if(!gain)return;\n const edge=wireEdges.find(x=>x.id===Number(gain.dataset.wsGain)&&x.enabled);\n if(!edge||edge.kind==='primary')return;\n const amount=Math.max(-60,Math.min(6,Math.round(Number(gain.value)||0)));\n if(window.__JUCE__?.backend){\n if(window.__ARMIX_NATIVE_M2__?.canWireGain?.(edge.id,edge.sourceId)!==true)return;\n // Coalesce rapid gestures in the existing native control queue. This LCD\n // shows a pending operation, NEVER a speculative accepted PCM level.\n window.__ARMIX_NATIVE_M2__?.consumeWire?.([{type:'GAIN',\n sourceId:edge.sourceId,edgeId:edge.id,levelDb:amount}]);\n const readout=document.getElementById('wireWsGainText');\n if(readout)readout.textContent='PENDING · '+amount+' dB';\n return;\n }\n if(!wireGraphCommit([{type:'GAIN',sourceId:edge.sourceId,edgeId:edge.id,\n levelDb:amount}],{record:false}))return;\n document.getElementById('wireWsGainText').textContent=amount+' dB';\n});\ndocument.getElementById('wireWsInspector').addEventListener('change',e=>{\n const gain=e.target.closest?.('[data-ws-gain]'),tap=e.target.closest?.('[data-ws-tap]');\n if(window.__JUCE__?.backend){\n if(gain){\n const edge=wireEdges.find(x=>x.id===Number(gain.dataset.wsGain)&&x.enabled);\n if(edge?.kind!=='primary'&&window.__ARMIX_NATIVE_M2__?.canWireGain?.(edge.id,edge.sourceId)===true){\n // Keyboard-only range change may not have emitted 'input'.\n window.__ARMIX_NATIVE_M2__?.consumeWire?.([{type:'GAIN',sourceId:edge.sourceId,\n edgeId:edge.id,levelDb:Math.max(-60,Math.min(6,Math.round(Number(gain.value)||0)))}]);\n }\n }\n if(tap){\n const edge=wireEdges.find(x=>x.id===Number(tap.dataset.wsTap)&&x.enabled);\n const requested=tap.value==='split'?'split':'send';\n // Restore the accepted selector position immediately. An independent\n // structural readback will move it after the engine actually publishes.\n tap.value=edge?.nativeTap==='PRE_FADER'?'split':'send';\n if(edge&&window.__ARMIX_NATIVE_M2__?.canWireTap?.(edge.id,edge.sourceId)===true){\n window.__ARMIX_NATIVE_M2__?.consumeWire?.([{type:'MODE',sourceId:edge.sourceId,\n edgeId:edge.id,mode:requested}]);\n say('WIRE tap requested · awaiting accepted native PCM readback');\n }else say('WIRE tap unavailable · native graph or EdgeId changed');\n }\n wireWsEditBefore=null;return; // native owns state; no demo undo or full repaint\n }\n if(tap){\n const edge=wireEdges.find(x=>x.id===Number(tap.dataset.wsTap)&&x.enabled);\n if(!edge||!wireGraphCommit([{type:'MODE',sourceId:edge.sourceId,edgeId:edge.id,\n mode:tap.value==='split'?'split':'send'}],{record:false}))return;\n const owner=wireSourceTrack(edge.sourceId);if(owner)owner.wireTapMode=tap.value==='split'?'split':'send';\n }\n if(gain||tap){\n wireWsRecord(wireWsEditBefore);wireWsEditBefore=null;render();renderWireWorkspace();\n say('WIRE inspector accepted · reference graph only');\n }\n});\n\n"), +) + + + def native_html(approved: str | None = None) -> str: original = accepted_pages_html() if approved is None else approved newline = "\r\n" if "\r\n" in original else "\n" diff --git a/scripts/build_guitar_fx_layered_assets.mjs b/scripts/build_guitar_fx_layered_assets.mjs new file mode 100644 index 000000000..e0ae28c63 --- /dev/null +++ b/scripts/build_guitar_fx_layered_assets.mjs @@ -0,0 +1,186 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Production-only layered Guitar FX RGBA PNGs. Native JUCE owns all +// controls, hit targets, state and PCM ACK; this is decorative bitmap art. +// Deterministic, dependency-free, and small (zlib-compressed). +import { deflateSync } from "node:zlib"; +import { mkdir, writeFile } from "node:fs/promises"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +const output = resolve(dirname(fileURLToPath(import.meta.url)), + "../design-references/guitar-fx/assets"); +export const SKINS = Object.freeze([ + ["gfx-amp-head.png",720,300,"amp"],["gfx-cabinet.png",720,300,"cab"], + ["gfx-pedal-gate-body.png",300,420,"gate"], + ["gfx-pedal-drive-body.png",300,420,"drive"], + ["gfx-knob.png",120,120,"knob"], + ["gfx-switch-off.png",200,74,"switchOff"], + ["gfx-switch-on.png",200,74,"switchOn"], + ["gfx-button-off.png",280,80,"buttonOff"], + ["gfx-button-on.png",280,80,"buttonOn"], + ["gfx-panel.png",800,330,"panel"], + ["gfx-stomp-off.png",110,110,"stompOff"], + ["gfx-stomp-on.png",110,110,"stompOn"] +]); +const clamp = x => Math.max(0,Math.min(255,Math.round(x))); +const sdBox=(x,y,l,t,r,b,rad)=>{ + const cx=Math.max(l+rad,Math.min(r-rad,x)); + const cy=Math.max(t+rad,Math.min(b-rad,y)); + return Math.hypot(x-cx,y-cy)-rad; +}; +const hash=(x,y,s=7)=>{ + let n=Math.imul(x+27,374761393)^Math.imul(y+43,668265263)^Math.imul(s,2246822519); + n=Math.imul(n^(n>>>13),1274126177);return ((n^(n>>>16))>>>0)/4294967295; +}; +const mix=(a,b,t)=>a.map((v,i)=>clamp(v*(1-t)+b[i]*t)); +const gold=[190,128,58],silver=[166,158,149],dark=[28,30,34]; +const pixel=(spec,x,y)=>{ + // Shared texture seed for state pairs prevents frame pixel shimmering. + const [name,w,h,kind]=spec, X=x/w,Y=y/h; + const seed=kind.startsWith("switch")?11: + kind.startsWith("button")?13: + kind.startsWith("stomp")?17:kind.length; + const n=hash(x,y,seed),grain=(n-.5)*11; + const gray=v=>[clamp(v+grain),clamp(v+grain*0.9),clamp(v+grain*0.8),255]; + const metal=(v,g=0)=>[clamp(v+g+grain),clamp(v+g*.67+grain),clamp(v+g*.24+grain),255]; + const alpha=(v,a)=>[v[0],v[1],v[2],clamp(a)]; + const dist=(px,py)=>Math.hypot(x-px,y-py); + if(kind==="knob"){ + const d=Math.hypot(X-.5,Y-.5),a=Math.atan2(Y-.5,X-.5); + if(d>.478)return [0,0,0,0]; + if(d>.421)return metal(29+Math.abs(Math.sin(a*44))*19,12); + if(d>.379)return metal(78+Math.cos(a*5)*10,73); + if(d>.344)return metal(33+Math.sin(a*31)*10,14); + const shine=Math.max(0,1-Math.hypot(X-.30,Y-.27)*1.4); + const v=110+66*shine+Math.sin(a*32)*3+Math.cos(d*350)*3; + if(Y<.39&&Y>.205&&Math.abs(X-.5)<.024)return [247,214,149,255]; + return metal(v,6); + } + if(kind==="stompOn"||kind==="stompOff"){ + // Shared aperture and body, only LED ring brightness changes. + const d=Math.hypot(X-.5,Y-.5); + if(d>.47)return [0,0,0,0]; + if(d>.42)return metal(22+grain*2,24); + if(d>.32)return metal(65+12*Math.sin(d*140),kind==="stompOn"?96:55); + if(d>.26)return metal(42,48); + return metal(120+35*Math.max(0,1-d/.26),13); + } + if(kind==="switchOn"||kind==="switchOff"){ + // Same exact body geometry/alpha, independent of state. No flicker. + const edge=sdBox(x,y,6,7,w-7,h-8,28); + if(edge>0)return [0,0,0,0]; + if(edge> -3)return metal(31,20); + const rim=sdBox(x,y,10,11,w-11,h-12,24); + if(rim>-4)return metal(62,95); + const well=sdBox(x,y,16,17,w-17,h-18,19); + if(well>-2)return metal(27,20); + const on=kind==="switchOn", thumbX=on?w-44:44; + const d=dist(thumbX,h*.5); + if(d<23){ + if(d>20)return metal(67,95); + return metal(133+35*Math.max(0,1-d/23)+24*(.5-Y),20); + } + if(on)return [clamp(52+grain),clamp(37+grain),clamp(23+grain),255]; + return gray(24+3*Y); + } + if(kind==="buttonOn"||kind==="buttonOff"){ + // Both states share the same opaque silhouette and fixed canvas. + const e=sdBox(x,y,4,7,w-5,h-8,21); + if(e>0)return [0,0,0,0]; + if(e>-3)return metal(46,18); + const rim=sdBox(x,y,9,12,w-10,h-13,17); + if(rim>-3)return metal(63,94); + if(kind==="buttonOn")return [clamp(66+grain+22*(1-Y)),clamp(45+grain+11*(1-Y)),clamp(28+grain),255]; + return gray(31+11*(1-Y)); + } + if(kind==="panel"){ + const e=sdBox(x,y,3,4,w-4,h-5,23); + if(e>0)return [0,0,0,0]; + if(e>-4)return metal(30,20); + const rim=sdBox(x,y,11,12,w-12,h-13,18); + if(rim>-3)return metal(53,86); + const inner=sdBox(x,y,21,23,w-22,h-24,12); + if(inner>-2)return gray(15+12*(1-Y)); + return gray(25+9*(1-Y)+7*(.5-Math.abs(X-.5))); + } + if(kind==="amp"||kind==="cab"){ + const edge=sdBox(x,y,5,9,w-6,h-9,33); + if(edge>0)return [0,0,0,0]; + if(edge>-5)return gray(25+21*(1-Y)); + const rim=sdBox(x,y,15,18,w-16,h-19,26); + if(rim>-4)return metal(54+18*(1-Y),91); + const inn=sdBox(x,y,24,27,w-25,h-28,18); + if(inn>-3)return gray(13); + if(kind==="cab"){ + const weave=((x+y*3)%7<2||(x-y*3+10000)%7<2)?7:0; + const speakers=[w*.28,w*.72]; + let shadow=0; + for(const px of speakers)shadow=Math.max(shadow,16*Math.max(0,1-dist(px,h*.54)/(h*.40))); + if(Y>.79)return metal(64+grain*2,60); + return gray(22+weave+8*(1-Y)-shadow); + } + // Physical head has NO baked controls: overlay independent PNG knobs. + if(Y<.53){ + const weave=(x+y*2)%8<2?4:0; + return gray(23+weave+8*(1-Y)); + } + if(Y<.55)return metal(52,110); + if(Y>.9)return metal(48,55); + return metal(98+18*Math.sin(y*.08)+20*(1-Y),24); + } + if(kind==="gate"||kind==="drive"){ + const e=sdBox(x,y,10,7,w-11,h-7,29); + if(e>0)return [0,0,0,0]; + if(e>-5)return gray(19+16*(1-Y)); + const rim=sdBox(x,y,19,16,w-20,h-16,20); + if(rim>-4)return metal(64,79); + const inner=sdBox(x,y,27,25,w-28,h-25,14); + if(inner>-2)return gray(17); + const wells=kind==="gate"?[[.31,.28],[.69,.28],[.50,.38]]:[[.50,.38]]; + for(const [sx,sy] of wells){ + const d=Math.hypot((X-sx)*w,(Y-sy)*h); + if(d<38){ + if(d>34)return metal(56,78); + if(d>29)return metal(21,30); + return gray(12); + } + } + // Empty footswitch mounting well, no baked stomp switch or LED. + const foot=Math.hypot((X-.5)*w,(Y-.82)*h); + if(foot<45){ + if(foot>39)return metal(82,70); + if(foot>33)return metal(33,12); + return gray(15); + } + if(Y>.65){ + const strip=sdBox(x,y,27,h*.63,w-28,h*.93,12); + if(strip>-5&&strip<0)return metal(57,70); + return metal(96+15*Math.sin(y*.1),22); + } + // Painted pedal chassis and empty sockets only. + return gray(34+10*(1-Y)); + } + return [0,0,0,0]; +}; +const crcTable=Array.from({length:256},(_,i)=>{ + let c=i;for(let k=0;k<8;k++)c=(c&1)?0xedb88320^(c>>>1):c>>>1;return c>>>0; +}); +const crc=b=>{let c=0xffffffff;for(const k of b)c=crcTable[(c^k)&255]^(c>>>8);return (c^0xffffffff)>>>0;}; +const u32=n=>Buffer.from([(n>>>24)&255,(n>>>16)&255,(n>>>8)&255,n&255]); +const chunk=(name,data)=>{const n=Buffer.from(name,"ascii"),b=Buffer.concat([n,data]);return Buffer.concat([u32(data.length),b,u32(crc(b))]);}; +export function render(spec){ + const [,w,h]=spec,row=w*4,scan=Buffer.alloc((row+1)*h); + for(let y=0;ys[0]).join(", ")); diff --git a/scripts/build_pages.py b/scripts/build_pages.py index 61b4c03d1..4c7d6fd73 100644 --- a/scripts/build_pages.py +++ b/scripts/build_pages.py @@ -7,6 +7,7 @@ from approved_fx_rack_interaction import apply_fx_rack_interaction from compose_native_peq import apply_native_peq from compose_operator_ux import apply_operator_ux +from compose_lms import apply_lms ROOT=Path(__file__).resolve().parents[1] p=argparse.ArgumentParser() p.add_argument('--out',default='dist-pages') @@ -92,6 +93,7 @@ canonical_html=apply_fx_rack_interaction(canonical_html,buttons_dest/'assets') canonical_html=apply_native_peq(canonical_html) canonical_html=apply_operator_ux(canonical_html,buttons_dest/'assets') +canonical_html=apply_lms(canonical_html,buttons_dest/'assets') # The shipped UI is composed from inline JS as well as owner assets. Check all # inline code BEFORE packaging or deployment: a single unterminated string # otherwise leaves an empty mixer despite green source/PNG contract tests. diff --git a/scripts/collect_hardware_fat_windows.ps1 b/scripts/collect_hardware_fat_windows.ps1 index 2dbd9b552..606671038 100644 --- a/scripts/collect_hardware_fat_windows.ps1 +++ b/scripts/collect_hardware_fat_windows.ps1 @@ -39,7 +39,12 @@ function Get-FatSha256([string] $Path) { $manifestPath=Join-Path $root 'BUILD_PROVENANCE.json' if (-not (Test-Path -LiteralPath $manifestPath -PathType Leaf)) { throw 'Missing BUILD_PROVENANCE.json: extract the complete verified Windows FAT ZIP first' } $m=Get-Content -LiteralPath $manifestPath -Raw -Encoding UTF8 | ConvertFrom-Json -if ([string]$m.fatStatus -ne 'SOFTWARE_VERIFIED_PREVIEW_CANDIDATE') { throw 'Unexpected hardware qualification claim' } +# A portable FIELD preview is intentionally NOT full-CTest qualified. +# Accept it as a manual field-test input only, with the same exact EXE and +# collector SHA checks below; never convert it into a release certification. +if ([string]$m.fatStatus -notin @('SOFTWARE_VERIFIED_PREVIEW_CANDIDATE','FIELD_PREVIEW_FULL_CTEST_NOT_RUN')) { + throw 'Unexpected or unapproved software qualification status' +} if ([string]$m.sourceCommit -notmatch '^[a-f0-9]{40}$') { throw 'Invalid exact source SHA' } if ([string]$m.fatCollectorSha256 -notmatch '^[a-f0-9]{64}$') { throw 'Missing FAT collector provenance' } $selfHash=(Get-FatSha256 -Path $PSCommandPath) diff --git a/scripts/compose_lms.py b/scripts/compose_lms.py new file mode 100644 index 000000000..498edc6ab --- /dev/null +++ b/scripts/compose_lms.py @@ -0,0 +1,53 @@ +"""Integrate LMS in the SINGLE approved /preview/ assembler, never a second page. + +LMS is an offline logical DESIGN workspace only. Native PCM is neither +created nor touched; production hardware must implement ACK/readback separately. +""" +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +LMS_STYLE = ROOT / "site" / "preview-v2" / "assets" / "lms-workspace.css" +LMS_SCRIPTS = ("lms-system-model.js", "lms-workspace.js") + + +def _once(source: str, target: str, replacement: str, label: str) -> str: + if source.count(target) != 1: + raise ValueError("LMS approved /preview/ anchor drift: " + label) + return source.replace(target, replacement, 1) + + +def apply_lms(html: str, assets: Path) -> str: + """Compose one scoped workspace beside the mixer, not over its PCM state.""" + button = ('') + html = _once( + html, button, + button + '\n ', + "primary toolbar button") + html = _once( + html, '
', + ' \n' + '
', + "single in-app workspace") + scripts = "".join('\n' + for name in LMS_SCRIPTS) + for name in LMS_SCRIPTS: + if not (ROOT / "site" / "preview-v2" / "assets" / name).is_file(): + raise FileNotFoundError("LMS asset missing: " + name) + html = _once(html, '', scripts + '', "script order") + + chrome = assets / "mixer-chrome-material.css" + current = chrome.read_text(encoding="utf-8") + scoped = LMS_STYLE.read_text(encoding="utf-8") + if ".lms-workspace{" in current or "\n.console-pane{" in scoped: + raise ValueError("LMS CSS ownership collision") + if not scoped.startswith("/* ArSonMix LMS:"): + raise ValueError("Unexpected LMS CSS source") + chrome.write_text(current.rstrip() + "\n" + scoped.rstrip() + "\n", + encoding="utf-8") + return html diff --git a/scripts/compose_native_peq.py b/scripts/compose_native_peq.py index 81e2873df..c7eaaf6b3 100644 --- a/scripts/compose_native_peq.py +++ b/scripts/compose_native_peq.py @@ -7,6 +7,7 @@ COMP_SCRIPT='' HARMONY_SCRIPT='' THROW_SCRIPT='' +SONKU_SCRIPT='' PRESET_SCRIPT='' PICKER_HEAD="function renderFastPicker(){" @@ -95,6 +96,26 @@ refreshStrip(t);setFastPicker(false); say('Vocal Throw · browser preview ONLY · no audio DSP');return true; } +function insertChosenNativeSonKu(){ + 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('8D-SonKu · choose an empty FX insert');return false; + } + if(window.__JUCE__?.backend?.emitEvent){ + if(!window.ArSonMixNativeSonKu?.insert){ + say('8D-SonKu native FX host unavailable');return false; + } + return window.ArSonMixNativeSonKu.insert(activeFxTarget); + } + if(t.fx[slot]!=='None'){ + say('FX slot already occupied');return false; + } + t.fx[slot]='8D-SonKu';t.slotBypass[slot]=false; + t.fxInsertIds[slot]={id:'visual-sonku-'+t.id+'-'+slot,name:'8D-SonKu'}; + refreshStrip(t);setFastPicker(false); + say('8D-SonKu · browser visual preview ONLY · no audio');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))? @@ -105,26 +126,26 @@ '':''; const throwBuiltin=!q||['vocal throw','throw','delay','echo','phrase','concert','built-in fx'].some(n=>n.includes(q))? '':''; - // The quick picker previously hard-coded ONLY four buttons and then put - // every new native processor under "VST3 PLUGINS". This made Guitar FX - // invisible in the actual first-screen BUILT-IN FX group, despite a valid - // registry, bridge catalog, and green source-level tests. Keep four existing - // specialized editor buttons and discover all additional JUCE built-ins from - // the authoritative installed native catalog instead of adding another stub. + const sonkuBuiltin=!q||['8d-sonku','sonku','8d','binaural','spatial','orbit','built-in fx'].some(n=>n.includes(q))? + '':''; + // One catalog-driven builtin shelf. Keep the dedicated SonKu editor button + // exactly once: it is excluded from generic native catalog items, as are + // EQ/Comp/Harmony/Throw which already have specialized editor actions. const specializedIds=new Set([ 'armix.builtin.channel-eq.v1', 'armix.builtin.channel-compressor.v1', 'armix.builtin.arson-harmony.v1', - 'armix.builtin.vocal-throw.v1' + 'armix.builtin.vocal-throw.v1', + 'armix.builtin.8d-sonku.v1' ]); const nativeExtra=list.filter(p=>p.format==='Native' && - p.id.startsWith('armix.builtin.')&&!specializedIds.has(p.id)).map(p=> + p.id.startsWith('armix.builtin.')&&!specializedIds.has(p.id)).map(p=> '' ).join(''); - const builtin=(eqBuiltin||compBuiltin||harmonyBuiltin||throwBuiltin||nativeExtra? + const builtin=(eqBuiltin||compBuiltin||harmonyBuiltin||throwBuiltin||sonkuBuiltin||nativeExtra? '
BUILT-IN FX
':'')+ - nativeExtra+eqBuiltin+compBuiltin+harmonyBuiltin+throwBuiltin; - // Native processors are not VST3 files: do not duplicate them under VST3. + nativeExtra+eqBuiltin+compBuiltin+harmonyBuiltin+throwBuiltin+sonkuBuiltin; + // Native processors must not appear twice or under the VST3 PLUGINS heading. const vstItems=list.filter(p=>p.format!=='Native'); plugEl('fastResults').innerHTML=builtin+'
VST3 PLUGINS
'+(vstItems.length?vstItems.map(p=>""" PICKER_END=""").join(''):'
No matching effects
';""" @@ -134,9 +155,10 @@ 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;} + if(e.target.closest('[data-fast-native-sonku]')){insertChosenNativeSonKu();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-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);}" +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 if(b.hasAttribute('data-fast-native-sonku'))insertChosenNativeSonKu();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); @@ -152,6 +174,9 @@ if(t.fx[index]==='ArSon Vocal Throw'){ window.ArSonMixNativeVocalThrow?.open(t,index);return; } + if(t.fx[index]==='8D-SonKu'){ + window.ArSonMixNativeSonKu?.open(t,index);return; + } openFastPicker(t,index,btn);return; }""" def apply_native_peq(html: str)->str: @@ -162,11 +187,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 HARMONY_SCRIPT in html or THROW_SCRIPT in html or PRESET_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 PRESET_SCRIPT in html or SONKU_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('',PRESET_SCRIPT+'\n'+SCRIPT+'\n'+COMP_SCRIPT+'\n'+HARMONY_SCRIPT+'\n'+THROW_SCRIPT+'\n',1) + html=html.replace('',PRESET_SCRIPT+'\n'+SCRIPT+'\n'+COMP_SCRIPT+'\n'+HARMONY_SCRIPT+'\n'+THROW_SCRIPT+'\n'+SONKU_SCRIPT+'\n',1) return html diff --git a/scripts/m3e_fat_evidence_gate.mjs b/scripts/m3e_fat_evidence_gate.mjs index 14bf14f54..d47b9c11e 100644 --- a/scripts/m3e_fat_evidence_gate.mjs +++ b/scripts/m3e_fat_evidence_gate.mjs @@ -13,6 +13,13 @@ export const M3E_MODES=Object.freeze([ ]); export const M3E_SCHEMA='arsonmix.hardware-fat-field-journal.v1'; const HEX40=/^[a-f0-9]{40}$/,HEX64=/^[a-f0-9]{64}$/; +// These are two distinct, honestly-labelled SOFTWARE package types. +// A field preview intentionally skips full CTest and is NEVER a public FAT +// release. Both require identical PE, exact-SHA source, GUI and tool checks. +export const M3E_PACKAGE_QUALIFICATIONS=Object.freeze([ + 'SOFTWARE_VERIFIED_PREVIEW_CANDIDATE', + 'FIELD_PREVIEW_FULL_CTEST_NOT_RUN' +]); const hash=x=>createHash('sha256').update(x).digest('hex'); const nonempty=v=>typeof v==='string'&&v.trim().length>0; const uniqueInts=v=>Array.isArray(v)&&v.every(n=>Number.isSafeInteger(n)&&n>=0&&n<=255) @@ -57,7 +64,7 @@ export function inspectM3ePackage(root){ !HEX64.test(manifest.approvedGuiPagesSha256||'')|| !HEX64.test(manifest.approvedGuiNativeHtmlSha256||'')|| !HEX64.test(manifest.approvedGuiManifestSha256||'')|| - manifest.fatStatus!=='SOFTWARE_VERIFIED_PREVIEW_CANDIDATE') + !M3E_PACKAGE_QUALIFICATIONS.includes(manifest.fatStatus)) throw Error('Source/GUI/qualification manifest is not approved and fail-closed'); const exe=readExact(p,manifest.executable,manifest.exeSha256); checkPe64Gui(exe); @@ -68,7 +75,8 @@ export function inspectM3ePackage(root){ // inspection. This tool does not claim compressed ZIP verification. return {sourceSha:manifest.sourceCommit,exeSha256:manifest.exeSha256, build:'EXE_AND_FAT_BYTES_VERIFIED',zip:'EXTERNAL_WINDOWS_VERIFIER_REQUIRED', - gui:'APPROVED_PREVIEW_PROVENANCE_MANIFEST',manifest}; + gui:'APPROVED_PREVIEW_PROVENANCE_MANIFEST', + softwareQualification:manifest.fatStatus,manifest}; } function verifySession(run,mode,rate,root,blockers){ const tag=rate+' '+mode; @@ -170,6 +178,7 @@ export function assessM3eFat(root){ const journalPath=join(resolve(root),'FAT_RUNS.json'); if(!existsSync(journalPath)) return {sourceSha:packageResult.sourceSha,build:packageResult.build, + softwareQualification:packageResult.softwareQualification, zip:packageResult.zip,nativePcm:'PENDING_NATIVE_CALLBACK_PROOF', physical:'PENDING',releaseReady:false,hardwareCertified:false, blockers:['No physical FAT_RUNS.json: no 44.1/48-kHz field evidence']}; @@ -180,6 +189,7 @@ export function assessM3eFat(root){ throw Error('Journal source/executable SHA differs from packaged native EXE'); const physical=inspectM3eJournal(journal,{root:resolve(root)}); return {sourceSha:packageResult.sourceSha,build:packageResult.build, + softwareQualification:packageResult.softwareQualification, zip:packageResult.zip,nativePcm:'PENDING_NATIVE_CALLBACK_PROOF', physical:physical.physical,releaseReady:false,hardwareCertified:false, selectedSessions:physical.selectedSessions,blockers:physical.blockers, @@ -187,6 +197,7 @@ export function assessM3eFat(root){ renderHardwareXrun:physical.actualRenderXrunEvidence}; }catch(error){ return {sourceSha:packageResult.sourceSha,build:packageResult.build, + softwareQualification:packageResult.softwareQualification, zip:packageResult.zip,nativePcm:'PENDING_NATIVE_CALLBACK_PROOF', physical:'PENDING',releaseReady:false,hardwareCertified:false, blockers:['FAT journal integrity: '+error.message]}; diff --git a/scripts/validate_guitar_fx_artist_source.mjs b/scripts/validate_guitar_fx_artist_source.mjs new file mode 100644 index 000000000..531e3718d --- /dev/null +++ b/scripts/validate_guitar_fx_artist_source.mjs @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Validate the artist's independent PNG layers BEFORE embedding into JUCE. +// Never let mismatched ON/OFF frames or missing transparent channels ship. +import {readFileSync,existsSync} from "node:fs"; +import {resolve} from "node:path"; +import {inflateSync} from "node:zlib"; +const folder=resolve(process.argv[2]||"design-references/guitar-fx/artist-source"); +const sizes={ + "gfx-amp-head.png":[720,300],"gfx-cabinet.png":[720,300], + "gfx-pedal-gate-body.png":[300,420],"gfx-pedal-drive-body.png":[300,420], + "gfx-knob.png":[120,120],"gfx-switch-off.png":[200,74], + "gfx-switch-on.png":[200,74],"gfx-button-off.png":[280,80], + "gfx-button-on.png":[280,80],"gfx-panel.png":[800,330], + "gfx-stomp-off.png":[110,110],"gfx-stomp-on.png":[110,110] +}; +function decode(name) { + const p=resolve(folder,name); + if(!existsSync(p))throw Error("Missing independent guitar skin: "+name); + const b=readFileSync(p); + if(!b.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))) + throw Error(name+" is not a PNG"); + let x=8,dat=[],w=0,h=0; + while(x+12<=b.length){ + const n=b.readUInt32BE(x),type=b.toString("ascii",x+4,x+8),v=b.subarray(x+8,x+8+n); + if(type==="IHDR"){ + w=v.readUInt32BE(0);h=v.readUInt32BE(4); + if(v[8]!==8||v[9]!==6||v[12]!==0)throw Error(name+" must use 8-bit noninterlaced RGBA"); + } + if(type==="IDAT")dat.push(v); + x+=n+12;if(type==="IEND")break; + } + const [ex,ey]=sizes[name]; + if(w!==ex||h!==ey)throw Error(name+" must be "+ex+"x"+ey+"; got "+w+"x"+h); + const raw=inflateSync(Buffer.concat(dat)),stride=w*4; + const rows=Buffer.alloc(stride*h),rowLen=stride+1; + if(raw.length!==h*rowLen)throw Error(name+" malformed PNG scanlines"); + for(let y=0;y=4?rows[start+i-4]:0; + const up=y?rows[start-stride+i]:0; + const ul=y&&i>=4?rows[start-stride+i-4]:0; + const p=a+up-ul,pa=Math.abs(p-a),pb=Math.abs(p-up),pc=Math.abs(p-ul); + const predict=pa<=pb&&pa<=pc?a:pb<=pc?up:ul; + const add=[0,a,up,Math.floor((a+up)/2),predict][filter]; + if(add===undefined)throw Error(name+" invalid PNG row filter "+filter); + rows[start+i]=(raw[y*rowLen+1+i]+add)&255; + } + } + return {w,h,bytes:rows}; +} +const images=new Map(Object.keys(sizes).map(n=>[n,decode(n)])); +for(const kind of ["switch","button","stomp"]){ + const a=images.get("gfx-"+kind+"-off.png"),b=images.get("gfx-"+kind+"-on.png"); + let visible=0,changed=0; + const borderX=Math.max(3,Math.floor(a.w*.055)); + const borderY=Math.max(3,Math.floor(a.h*.09)); + for(let y=0;y=a.w-borderX||y=a.h-borderY; + for(let c=0;c<3;c++){ + if(isOuter&&a.bytes[i+c]!==b.bytes[i+c]) + throw Error(kind+" ON/OFF outer frame differs at "+x+","+y); + if(a.bytes[i+c]!==b.bytes[i+c])changed++; + } + } + if(visible===0||changed===0)throw Error(kind+" has blank/identical states"); +} +console.log("Guitar FX artist source validated: 12 RGBA PNGs, stable frames and exact ON/OFF alpha"); diff --git a/site/preview-buttons/assets/mixer-control-keys.css b/site/preview-buttons/assets/mixer-control-keys.css index d6c40449d..82c7ce2b8 100644 --- a/site/preview-buttons/assets/mixer-control-keys.css +++ b/site/preview-buttons/assets/mixer-control-keys.css @@ -124,3 +124,28 @@ @media(prefers-reduced-motion:reduce){ .app .console-body .strip .mx-hw-row>button.mx-hw-key{transition:none!important} } + +/* SAME approved Harmonice v9 sprite in contextual SOF FX cell. + No new generated button artwork, CSS approximation or alternate state. */ +.app .console-body .strip .mx-sof-tap-key{ + position:relative;display:block;flex:0 0 55px;width:55px;height:29px; + margin:0;padding:0;border:0;background:transparent;overflow:visible; + isolation:isolate;cursor:pointer;color:transparent;font-size:0;line-height:0; +} +.app .console-body .strip .mx-sof-tap-key::before{ + content:"";position:absolute;inset:0;display:block;pointer-events:none; + background-image:url("harmonice-thin-flat-v9-approved-off-shadow-57x30.png"); + background-repeat:no-repeat;background-size:400% 300%; + background-position:var(--mx-native-x,33.333333%) 0%; +} +.app .console-body .strip .mx-sof-tap-key[data-tap-visual="pre"]{--mx-native-x:0%} +.app .console-body .strip .mx-sof-tap-key[data-tap-visual="idle"]{--mx-native-x:33.333333%} +.app .console-body .strip .mx-sof-tap-key[data-tap-visual="post"]{--mx-native-x:66.666667%} +.app .console-body .strip .mx-sof-tap-key[data-tap-visual="mixed"]{--mx-native-x:100%} +.app .console-body .strip .mx-sof-tap-key:disabled{opacity:.72;cursor:default} +.app .console-body .strip .mx-sof-tap-key:focus-visible{outline:2px solid #9eddec;outline-offset:2px} + +/* Same approved v9 physical OFF shadow as the source strip. */ +.app .console-body .strip .mx-sof-tap-key[data-tap-visual="pre"]::before{ + filter:drop-shadow(0 .8px 1.15px rgba(0,0,0,.42)) drop-shadow(0 1.7px 2.1px rgba(0,0,0,.32)); +} diff --git a/site/preview-v2/assets/lms-system-model.js b/site/preview-v2/assets/lms-system-model.js new file mode 100644 index 000000000..29a40b0b3 --- /dev/null +++ b/site/preview-v2/assets/lms-system-model.js @@ -0,0 +1,305 @@ +/* ArSonMix LMS logical DESIGN model. No PCM, no device writes, no fake ACK. + * Portable CommonJS/browser API. Hardware mapping belongs to native control. + */ +(function (root, factory) { + const api = factory(); + if (typeof module === "object" && module.exports) module.exports = api; + else root.ArSonMixLmsModel = api; +})(typeof globalThis !== "undefined" ? globalThis : this, function () { + "use strict"; + const MIN_HZ = 20, MAX_HZ = 20000, SPEED_M_S = 343; + const SIDES = Object.freeze(["L", "R"]); + const MAX_WAYS = 16; + const MAX_DEMO_PORTS = 32; + const requireNumber = (v, lo, hi, label) => { + if (typeof v !== "number" || !Number.isFinite(v) || v < lo || v > hi) + throw new RangeError(label); + return v; + }; + const requireInteger = (v, lo, hi, label) => { + requireNumber(v, lo, hi, label); + if (!Number.isInteger(v)) throw new RangeError(label); + return v; + }; + const suffixes = n => { + if (n === 1) return ["FULL"]; + if (n === 2) return ["LOW", "HIGH"]; + if (n === 3) return ["LOW", "MID", "HIGH"]; + if (n === 4) return ["SUB", "LOW", "MID", "HIGH"]; + return Array.from({length:n}, (_,i) => "WAY " + String(i+1).padStart(2,"0")); + }; + function sectionsFor(ways, stereo) { + requireInteger(ways, 1, MAX_WAYS, "ways"); + const names = suffixes(ways); + return (stereo ? SIDES : ["M"]).flatMap(side => + names.map((band,i) => Object.freeze({ + id: side + ":" + (i+1), + name: band + (side === "M" ? "" : " " + side), + band, side, index:i + })) + ); + } + function defaultCutoffs(ways) { + if (ways === 1) return []; + if (ways === 2) return [1600]; + if (ways === 3) return [120,2400]; + if (ways === 4) return [80,250,2400]; + return Array.from({length:ways-1}, (_,i) => + Math.round(40 * Math.pow(12000/40,(i+1)/ways))); + } + function validateCutoffs(cutoffs, ways) { + if (!Array.isArray(cutoffs) || cutoffs.length !== ways-1) + throw new RangeError("crossover boundary count"); + let previous = MIN_HZ; + for (const value of cutoffs) { + requireNumber(value, MIN_HZ, MAX_HZ, "crossover frequency"); + if (value <= previous*1.01 || value >= MAX_HZ) + throw new RangeError("crossover bands must remain strictly ordered"); + previous = value; + } + return true; + } + function demoPorts(n) { + requireInteger(n, 1, MAX_DEMO_PORTS, "demo port count"); + return Array.from({length:n}, (_,i) => "DEMO-" + String(i+1).padStart(2,"0")); + } + const defaultDsp = () => ({ + gainDb:0, delayMs:0, polarity:"normal", peq:[], + muted:true, limiterEnabled:false, limiterThresholdDb:null + }); + const defaultPosition = i => ({x:(i%2===0?-4.5:4.5), y:3+2*Math.floor(i/2)}); + function createSystem({ways=3,stereo=true,ports=[]}={}) { + if (typeof stereo!=="boolean") throw new TypeError("stereo"); + requireInteger(ways,1,MAX_WAYS,"ways"); + if (!Array.isArray(ports) || ports.length>64 || ports.some(p=>typeof p!=="string" || !p.trim())) + throw new TypeError("ports"); + if (new Set(ports).size !== ports.length) throw new Error("duplicate port identity"); + return { + schema:"arsonmix.lms.draft.v1", revision:0, name:"Main PA", + ways, stereo, cutoffsHz:defaultCutoffs(ways), + sections:sectionsFor(ways,stereo), ports:ports.slice(), + // Empty crosspoints are intentional: NEVER auto-connect to an unknown speaker. + routes:{}, dsp:Object.fromEntries(ports.map(p=>[p,defaultDsp()])), + positions:Object.fromEntries(ports.map((p,i)=>[p,defaultPosition(i)])), + listener:{x:0,y:15}, applied:false + }; + } + function validateSystem(s) { + if (!s || s.schema!=="arsonmix.lms.draft.v1" || s.applied!==false) + throw new Error("not an offline LMS draft"); + requireInteger(s.ways,1,MAX_WAYS,"ways"); + validateCutoffs(s.cutoffsHz,s.ways); + if (!Array.isArray(s.ports) || new Set(s.ports).size!==s.ports.length) + throw new Error("invalid port list"); + const expected = sectionsFor(s.ways,s.stereo).map(x=>x.id); + if (JSON.stringify(expected)!==JSON.stringify(s.sections.map(x=>x.id))) + throw new Error("section identities inconsistent"); + for (const [port,section] of Object.entries(s.routes)) { + if (!s.ports.includes(port)||!expected.includes(section)) + throw new Error("orphan output mapping"); + } + return true; + } + function withWays(s,ways) { + validateSystem(s); + requireInteger(ways,1,MAX_WAYS,"ways"); + if (ways===s.ways) return s; + // Section ordinal meaning changes: clearing ALL crosspoints is intentional. + // Old acoustic protection settings must never silently migrate to a new driver. + return {...s, revision:s.revision+1, ways, + cutoffsHz:defaultCutoffs(ways), sections:sectionsFor(ways,s.stereo), + routes:{}, dsp:Object.fromEntries(s.ports.map(p=>[p,defaultDsp()])) + }; + } + function withStereo(s,stereo) { + validateSystem(s); + if (typeof stereo!=="boolean") throw new TypeError("stereo"); + if (s.stereo===stereo) return s; + return {...s, revision:s.revision+1, stereo, + sections:sectionsFor(s.ways,stereo), routes:{}, + dsp:Object.fromEntries(s.ports.map(p=>[p,defaultDsp()]))}; + } + function withCutoff(s,index,hz) { + validateSystem(s); + requireInteger(index,0,s.ways-2,"cutoff index"); + const next=s.cutoffsHz.slice(); + next[index]=requireNumber(hz,MIN_HZ,MAX_HZ,"crossover frequency"); + validateCutoffs(next,s.ways); + return {...s, revision:s.revision+1, cutoffsHz:next}; + } + function withPorts(s,ports) { + validateSystem(s); + if (!Array.isArray(ports) || ports.some(p=>typeof p!=="string" || !p.trim()) + || new Set(ports).size!==ports.length || ports.length>64) + throw new TypeError("ports must have distinct stable identities"); + if (JSON.stringify(ports)===JSON.stringify(s.ports)) return s; + // Device identity changed: any previous patch is now unsafe, even if + // a previous ordinal happens to have the same visible number. + return {...s, revision:s.revision+1, ports:ports.slice(), routes:{}, + dsp:Object.fromEntries(ports.map(p=>[p,defaultDsp()])), + positions:Object.fromEntries(ports.map((p,i)=>[p,s.positions[p]||defaultPosition(i)])) + }; + } + function withRoute(s,port,section) { + validateSystem(s); + if (!s.ports.includes(port)) throw new RangeError("unknown output port"); + if (section!==null && !s.sections.some(x=>x.id===section)) + throw new RangeError("unknown crossover section"); + const routes={...s.routes}; + if (section===null || routes[port]===section) delete routes[port]; + else routes[port]=section; // one feed per physical output; fanout is allowed + return {...s, revision:s.revision+1, routes}; + } + function withDsp(s,port,patch) { + validateSystem(s); + if (!s.ports.includes(port) || !patch || typeof patch!=="object") + throw new RangeError("unknown output DSP target"); + const allowed=new Set(["gainDb","delayMs","polarity","muted", + "limiterEnabled","limiterThresholdDb"]); + for (const key of Object.keys(patch)) if (!allowed.has(key)) + throw new Error("unknown DSP property: "+key); + const p={...s.dsp[port],...patch}; + requireNumber(p.gainDb,-60,6,"gainDb"); + requireNumber(p.delayMs,0,500,"delayMs"); + if (!["normal","invert"].includes(p.polarity)) throw new RangeError("polarity"); + if (typeof p.muted!=="boolean" || typeof p.limiterEnabled!=="boolean") + throw new TypeError("DSP switches"); + if (p.limiterThresholdDb!==null) + requireNumber(p.limiterThresholdDb,-60,0,"limiterThresholdDb"); + // No hardware safety claims: this offline draft NEVER authorizes output. + return {...s, revision:s.revision+1, dsp:{...s.dsp,[port]:p}}; + } + // Output DSP band editor. The browser never runs audio; parameters stay + // in a typed disconnected draft pending native rate/port verification. + function validateBand(b) { + if (!b || typeof b !== "object" || typeof b.enabled !== "boolean") + throw new TypeError("PEQ band identity"); + requireNumber(b.frequencyHz,20,20000,"PEQ frequency"); + requireNumber(b.q,0.1,18,"PEQ Q"); + requireNumber(b.gainDb,-18,18,"PEQ gain"); + return true; + } + function withPeqBand(s,port,index,patch) { + validateSystem(s); + if (!s.ports.includes(port)) throw new RangeError("unknown output DSP target"); + if (!Number.isInteger(index)||index<0||index>=8)throw new RangeError("PEQ band index"); + const before=s.dsp[port].peq; + if (!Array.isArray(before)||index>before.length)throw new RangeError("PEQ gap"); + const allowed=["frequencyHz","q","gainDb","enabled"]; + if (!patch || Object.keys(patch).some(key=>!allowed.includes(key))) + throw new Error("unknown PEQ property"); + const next=before.map(p=>({...p})); + next[index]={frequencyHz:1000,q:0.70710678118,gainDb:0,enabled:true, + ...next[index],...patch}; + validateBand(next[index]); + return {...s,revision:s.revision+1,dsp:{ + ...s.dsp,[port]:{...s.dsp[port],peq:next} + }}; + } + function withoutPeqBand(s,port,index) { + validateSystem(s); + if(!s.ports.includes(port))throw new RangeError("unknown output DSP target"); + const before=s.dsp[port].peq; + requireInteger(index,0,before.length-1,"PEQ band index"); + return {...s,revision:s.revision+1,dsp:{ + ...s.dsp,[port]:{...s.dsp[port],peq:before.filter((_,i)=>i!==index)} + }}; + } + // C++ PreparedSpeakerSystem::Biquad::make is the authority. Mirror its + // 2 x Butterworth LR4 magnitude here, not made-up rectangular "curves". + // Preview always labels its ASSUMED 48kHz sample rate; not a measurement. + function biquadMagnitude(hz,cutoff,high,sampleRate) { + requireNumber(hz,20,sampleRate*.5-.01,"preview Hz"); + const omega=2*Math.PI*cutoff/sampleRate,c=Math.cos(omega); + const alpha=Math.sin(omega)/(2*Math.SQRT1_2); + const scale=1/(1+alpha); + const b0=((high?1+c:1-c)*.5)*scale; + const b1=(high?-(1+c):1-c)*scale,b2=b0; + const a1=-2*c*scale,a2=(1-alpha)*scale; + const theta=2*Math.PI*hz/sampleRate; + const cos=Math.cos(theta),sin=Math.sin(theta); + const real=b0+b1*cos+b2*Math.cos(2*theta); + const imag=-b1*sin-b2*Math.sin(2*theta); + const denR=1+a1*cos+a2*Math.cos(2*theta); + const denI=-a1*sin-a2*Math.sin(2*theta); + return Math.sqrt((real*real+imag*imag)/ + Math.max(1e-28,denR*denR+denI*denI)); + } + function crossoverMagnitude(cutoffs,way,hz,sampleRate=48000) { + if(!Array.isArray(cutoffs)||!Number.isInteger(way)|| + way<0||way>cutoffs.length||sampleRate<44100||sampleRate>192000|| + !Number.isFinite(hz)||hz<20||hz>=sampleRate*.5) + throw new RangeError("crossover plot request"); + let magnitude=1; + if(way>0){ + const one=biquadMagnitude(hz,cutoffs[way-1],true,sampleRate); + magnitude*=one*one; + } + if(way192000|| + !Number.isFinite(hz)||hz<20||hz>=sampleRate*.5) + throw new RangeError("PEQ plot request"); + let mag=1; + for(const b of bands) { + validateBand(b); + if(!b.enabled)continue; + if(b.frequencyHz>=sampleRate*.45)continue; // visual marker; native rejects + const w=2*Math.PI*b.frequencyHz/sampleRate,c=Math.cos(w); + const alpha=Math.sin(w)/(2*b.q),A=Math.pow(10,b.gainDb/40); + const scale=1/(1+alpha/A),th=2*Math.PI*hz/sampleRate; + const b0=(1+alpha*A)*scale,b1=-2*c*scale,b2=(1-alpha*A)*scale; + const a1=b1,a2=(1-alpha/A)*scale; + const cos=Math.cos(th),sin=Math.sin(th); + const nr=b0+b1*cos+b2*Math.cos(2*th),ni=-b1*sin-b2*Math.sin(2*th); + const dr=1+a1*cos+a2*Math.cos(2*th),di=-a1*sin-a2*Math.sin(2*th); + mag*=Math.sqrt((nr*nr+ni*ni)/Math.max(1e-28,dr*dr+di*di)); + } + return 20*Math.log10(Math.max(1e-10,mag)); + } + function withSuggestedDelays(s) { + validateSystem(s); + const estimates=alignment(s); + if(estimates.some(x=>x.additionalMs>500))throw new RangeError("alignment delay budget"); + const dsp={...s.dsp}; + for(const x of estimates) + dsp[x.port]={...dsp[x.port],delayMs:Math.round(x.additionalMs*100)/100}; + return {...s,revision:s.revision+1,dsp}; + } + function withPosition(s,port,x,y) { + validateSystem(s); + if (!s.ports.includes(port)) throw new RangeError("unknown speaker"); + requireNumber(x,-1000,1000,"speaker x"); + requireNumber(y,-1000,1000,"speaker y"); + return {...s, revision:s.revision+1, + positions:{...s.positions,[port]:{x,y}}}; + } + function withListener(s,x,y) { + validateSystem(s); + requireNumber(x,-1000,1000,"listener x"); + requireNumber(y,-1000,1000,"listener y"); + return {...s, revision:s.revision+1,listener:{x,y}}; + } + function alignment(s,{speed=SPEED_M_S}={}) { + validateSystem(s); + requireNumber(speed,300,360,"sound speed"); + const distances=s.ports.map(p=>{ + const v=s.positions[p], dx=v.x-s.listener.x,dy=v.y-s.listener.y; + return {port:p,distanceM:Math.hypot(dx,dy)}; + }); + const farthest=Math.max(0,...distances.map(d=>d.distanceM)); + return distances.map(d=>({...d,additionalMs:(farthest-d.distanceM)/speed*1000})); + } + return Object.freeze({ + MAX_WAYS,MAX_DEMO_PORTS,sectionsFor,defaultCutoffs,validateCutoffs, + demoPorts,createSystem,validateSystem,withWays,withStereo,withCutoff, + withPorts,withRoute,withDsp,withPeqBand,withoutPeqBand, + crossoverMagnitude,peqMagnitude,withSuggestedDelays, + withPosition,withListener,alignment + }); +}); diff --git a/site/preview-v2/assets/lms-workspace.css b/site/preview-v2/assets/lms-workspace.css new file mode 100644 index 000000000..b5fe56a58 --- /dev/null +++ b/site/preview-v2/assets/lms-workspace.css @@ -0,0 +1,127 @@ +/* ArSonMix LMS: one scoped workspace in the approved /preview/ console. + Compiled into existing mixer-chrome-material CSS owner, no extra runtime sheet. + Independent of source mixer/fader/WIRE styling and all native PCM controls. */ +.app.lms-active .console-pane{display:none!important} +.app.lms-active .command-bar>:not(#lmsOpen){display:none!important} +.command-bar #lmsOpen[aria-pressed="true"]{border-color:#58bbce;background:#183944;color:#c8eff5} +.lms-workspace[hidden]{display:none!important} +.lms-workspace{ + --lms-bg:#0c151c;--lms-surface:#13202a;--lms-border:#30434e; + --lms-ink:#d8e6eb;--lms-secondary:#92aeb9;--lms-accent:#5bc5d1; + flex:1;min-height:0;min-width:0;display:flex;overflow:hidden; + background:var(--lms-bg);color:var(--lms-ink); + font:400 12px/1.4 "Segoe UI",Arial,sans-serif;letter-spacing:0 +} +.lms-workspace *{box-sizing:border-box} +.lms-workspace button,.lms-workspace input,.lms-workspace select{ + font:inherit;color:inherit +} +.lms-workspace button{cursor:pointer} +.lms-workspace button:focus-visible,.lms-workspace input:focus-visible, +.lms-workspace select:focus-visible{outline:2px solid var(--lms-accent);outline-offset:2px} +.lms-sidebar{width:164px;flex:none;border-right:1px solid var(--lms-border); + background:linear-gradient(180deg,#172630,#101b24);padding:14px 8px;overflow-y:auto} +.lms-sidebar .lms-name{font-size:12px;font-weight:620;letter-spacing:.03em; + color:#e8f4f6;margin:3px 10px 16px} +.lms-nav{display:flex;flex-direction:column;gap:3px} +.lms-nav button{display:flex;align-items:center;gap:10px;width:100%;text-align:left; + border:1px solid transparent;background:transparent;padding:10px 11px; + border-radius:5px;color:#a9c0c9} +.lms-nav button.active{background:#22424c;color:#e8fcff;border-color:#477985} +.lms-nav button:hover:not(.active){background:#1d303b} +.lms-nav .lms-index{opacity:.65;font:500 10px/1.2 monospace} +.lms-sidebar-foot{border-top:1px solid #30434e;color:#93abb5;margin-top:22px; + padding:14px 10px;font-size:10px;line-height:1.5} +.lms-stage{flex:1;min-width:0;min-height:0;display:flex;flex-direction:column;overflow:hidden} +.lms-heading{display:flex;justify-content:space-between;align-items:center;gap:10px; + padding:11px 18px;border-bottom:1px solid var(--lms-border);min-height:53px;flex:none} +.lms-heading h2{font-size:16px;font-weight:580;margin:0} +.lms-heading small{font-size:10px;color:var(--lms-secondary)} +.lms-offline{font-size:10px;border:1px solid #6e6141;padding:4px 8px;color:#e5c996; + border-radius:4px;white-space:nowrap;background:#332e22} +.lms-content{overflow:auto;flex:1;min-height:0;padding:16px 18px 24px} +.lms-grid{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(240px,.8fr);gap:14px} +.lms-panel{border:1px solid var(--lms-border);background:var(--lms-surface); + border-radius:6px;padding:14px;min-width:0;overflow:hidden} +.lms-panel h3{font-size:12px;font-weight:590;margin:0 0 13px;color:#e3eff3} +.lms-panel h3 span{float:right;font-weight:400;font-size:10px;color:var(--lms-secondary)} +.lms-label{display:block;font-size:10px;color:var(--lms-secondary);margin-bottom:6px} +.lms-muted{color:var(--lms-secondary)} +.lms-caption{font-size:10px;color:#94afb8;line-height:1.45} +.lms-line{border-top:1px solid #334651;margin:12px 0} +.lms-control-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap} +.lms-btn,.lms-select,.lms-number{border:1px solid #3c5664;background:#192b35; + border-radius:4px;padding:7px 10px;min-height:30px} +.lms-btn:hover{background:#26414c;border-color:#5da0b2} +.lms-btn.active{background:#174753;border-color:#5ac3d1;color:#c7f6ff} +.lms-btn:disabled{cursor:not-allowed;opacity:.45} +.lms-select{max-width:100%;min-width:100px} +.lms-number{width:92px;text-align:right;font-variant-numeric:tabular-nums} +.lms-number:disabled{opacity:.5} +.lms-summary{display:flex;gap:10px;flex-wrap:wrap} +.lms-stat{padding:10px 14px;border:1px solid #364e59;background:#142733; + min-width:95px;border-radius:4px} +.lms-stat b{font-size:19px;font-weight:500;display:block} +.lms-stat span{font-size:10px;color:var(--lms-secondary)} +.lms-steps{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin:12px 0} +.lms-step{padding:9px 11px;border:1px solid #375463;background:#1a2b37;border-radius:4px} +.lms-step strong{display:block;font-weight:500;font-size:11px} +.lms-step small{font-size:9px;color:#a4b9c1} +.lms-arrow{color:#6c939f;font-size:16px} +.lms-speaker-map{height:226px;position:relative; + border:1px solid #36505e;border-radius:5px; + background:repeating-linear-gradient(0deg,transparent,transparent 34px,#29404b40 35px), + repeating-linear-gradient(90deg,transparent,transparent 34px,#29404b40 35px),#0e1d26} +.lms-speaker-map .stage{position:absolute;top:8px;left:30%;right:30%; + padding:7px;text-align:center;background:#334651;border-radius:4px;font-size:10px} +.lms-map-spk{position:absolute;border:1px solid #689cac;border-radius:5px; + background:#1e414d;padding:6px 10px;color:#dcf8fd;font-size:10px} +.lms-listener{position:absolute;bottom:21px;left:50%;transform:translateX(-50%); + border:1px solid #6a92a1;border-radius:20px;padding:7px;background:#213442} +.lms-frequency{width:100%;max-height:250px;display:block;border:1px solid #334855;border-radius:4px} +.lms-band-row{display:flex;gap:8px;align-items:center;border-bottom:1px solid #2d414e; + padding:9px 2px;font-size:11px} +.lms-band-row:last-child{border-bottom:0} +.lms-band-mark{width:9px;height:9px;border-radius:2px;display:inline-block;flex:none} +.lms-band-row .lms-band-name{flex:1} +.lms-split-row{display:flex;align-items:center;gap:12px;padding:8px 0;border-bottom:1px solid #2d414e} +.lms-split-row:last-child{border:0} +.lms-split-row label{flex:1} +.lms-table-scroll{max-width:100%;overflow:auto;border:1px solid #354c57;border-radius:4px} +.lms-matrix{border-collapse:separate;border-spacing:0;width:max-content;min-width:100%;font-size:11px} +.lms-matrix th,.lms-matrix td{padding:7px 8px;border-right:1px solid #2b404d; + border-bottom:1px solid #293e48;text-align:center;white-space:nowrap} +.lms-matrix th:first-child,.lms-matrix td:first-child{position:sticky;left:0; + background:#1a2c37;text-align:left;z-index:2;min-width:95px} +.lms-matrix th{background:#1c2d38;font-weight:500;font-size:10px;color:#b3ccd4;position:sticky;top:0;z-index:1} +.lms-cross{min-width:26px;min-height:26px;border:1px solid #405765;border-radius:4px; + background:#10212b;color:#90abb4;padding:0} +.lms-cross.active{background:#177989;color:#fff;border-color:#5ed1de} +.lms-cross:hover{border-color:#85dbe5} +.lms-output-list{display:flex;flex-direction:column;gap:5px} +.lms-output{display:flex;align-items:center;gap:10px;border:1px solid #334956; + background:#152731;padding:9px 10px;border-radius:4px;text-align:left;width:100%} +.lms-output.active{border-color:#5cbdca;background:#1a3945} +.lms-output strong{font-size:11px;font-weight:570;flex:1} +.lms-output small{font-size:10px;color:#99b4be} +.lms-form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px} +.lms-field label{display:block;color:#9bb6bf;font-size:10px;margin-bottom:6px} +.lms-field input,.lms-field select{width:100%;max-width:100%} +.lms-tip{border-left:2px solid #82b7c0;color:#a8c6cd;padding:5px 10px; + font-size:10px;margin:12px 0} +.lms-warn{border-left:2px solid #c3a06d;color:#e4c9a1;padding:5px 10px;font-size:10px} +.lms-room{width:100%;max-height:450px;display:block;background:#101e27;border-radius:5px; + border:1px solid #3c5360;touch-action:none} +.lms-room .spk{cursor:grab} +.lms-room .ref{cursor:move} +.lms-room text{pointer-events:none;font:10px "Segoe UI",sans-serif} +.lms-mini-table{width:100%;border-collapse:collapse;font-size:11px} +.lms-mini-table th{text-align:left;font-size:10px;font-weight:500;color:#99b5be} +.lms-mini-table td,.lms-mini-table th{padding:8px;border-bottom:1px solid #324752} +.lms-mini-table tr.current{background:#23404b} +@media(max-width:960px){.lms-grid{grid-template-columns:1fr}.lms-sidebar{width:138px}.lms-content{padding:12px}} +@media(max-width:640px){.lms-sidebar{width:55px;padding:10px 4px}.lms-sidebar .lms-name{font-size:0} + .lms-nav button{justify-content:center;padding:10px 0;font-size:0} + .lms-nav .lms-index{font-size:12px}.lms-sidebar-foot{display:none} + .lms-heading{padding:10px}.lms-heading h2{font-size:13px}.lms-content{padding:8px} + .lms-form-grid{grid-template-columns:1fr}} diff --git a/site/preview-v2/assets/lms-workspace.js b/site/preview-v2/assets/lms-workspace.js new file mode 100644 index 000000000..6156e701e --- /dev/null +++ b/site/preview-v2/assets/lms-workspace.js @@ -0,0 +1,395 @@ +/* ArSonMix LMS workspace: GUI-only offline draft. + * Native publication is deliberately NOT wired; all output ports are DEMO + * identities and every output DSP begins muted with limiter uncalibrated. + */ +(function () { +"use strict"; +const M=window.ArSonMixLmsModel, root=document.getElementById("lmsWorkspace"); +const app=document.querySelector(".app"), launch=document.getElementById("lmsOpen"); +if (!M||!root||!app||!launch||root.dataset.ready) return; +root.dataset.ready="1"; +let state=M.createSystem({ways:3,stereo:true,ports:M.demoPorts(6)}); +let page="system",selectedPort=state.ports[0],pending=null,message=""; +let dspTab="eq",selectedBand=0; +let dragging=null; +const pageNames={system:"System",crossover:"Crossover",matrix:"Matrix", + processing:"Processing",alignment:"Alignment"}; +const pages=Object.keys(pageNames); +const safe=x=>String(x).replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[c])); +const number=x=>Number(x).toFixed(1); +const unit=x=>Number(x).toFixed(2); +const color=i=>["#59bfd0","#8cb7dd","#d9b77e","#88c6ae","#b5a8dc","#cb9fab"][i%6]; +function selectOptions(items,value) { + return items.map(o=>'').join(""); +} +function btn(label,act,active=false) { + return ''; +} +function stats() { + return '
'+state.ways+'Ways / source
'+ + '
'+state.sections.length+'Section signals
'+ + '
'+Object.keys(state.routes).length+'Draft patches
'+ + '
'+state.ports.length+'Demo output ports
'; +} +function overviewMap() { + return '
'+ + '
STAGE / MAIN PA
'+ + 'LEFT '+state.ways+'-WAY'+ + 'RIGHT '+state.ways+'-WAY'+ + 'LISTENER
'; +} +function systemPage() { + return '
'+ + '

Speaker system Signal flow

'+ + '
MAIN / BUSLogical source›'+ + ''+state.ways+'-Way XOVER'+state.sections.length+' sections›'+ + 'MATRIXExplicit patch›'+ + 'OUTPUT DSPPer hardware pin
'+ + '
'+stats()+ + '

Choose the number of ways in Crossover first, then route sections to outputs in Matrix. All changes remain offline drafts.

'+ + '
'+btn("Edit Crossover","go:crossover")+ + btn("Open Matrix","go:matrix")+'
'+ + '

Speaker placement Top view

'+ + overviewMap()+'
'+ + btn("Visual alignment","go:alignment")+'No measured acoustic data
'; +} +function freqX(hz) {return 24+(Math.log10(hz)-Math.log10(20))/(Math.log10(20000)-Math.log10(20))*650;} +function frequencyPage() { + // Numeric response is the exact same two cascaded Butterworth magnitude + // model as the native PreparedSpeakerSystem LR4 kernel, at assumed 48 kHz. + const freqPoints=Array.from({length:116},(_,i)=>20*Math.pow(1000,i/115)); + const dbToY=db=>Math.max(30,Math.min(196,30+(3-db)*3.75)); + const guides=[0,-6,-12,-24,-36].map(db=> + ''+ + ''+db+'').join(""); + let curves="",rows=""; + for(let i=0;i{ + const mag=M.crossoverMagnitude(state.cutoffsHz,i,hz,48000); + const db=20*Math.log10(Math.max(1e-7,mag)); + return (j?"L":"M")+freqX(hz).toFixed(2)+" "+dbToY(db).toFixed(2); + }).join(" "); + const shade=color(i); + curves+=''; + const edges=[20].concat(state.cutoffsHz,[20000]); + rows+='
'+ + ''+safe(state.sections[i].band)+''+ + safe(Math.round(edges[i])+'–'+Math.round(edges[i+1])+' Hz')+'
'; + } + const crossoverMarks=state.cutoffsHz.map(hz=> + '').join(""); + const ticks=[20,100,1000,10000,20000].map(hz=> + ''+ + (hz===20000?"20k":hz===10000?"10k":hz===1000?"1k":hz)+'').join(""); + const splits=state.cutoffsHz.map((v,i)=> + '
'+ + 'Hz
').join(""); + return '
'+ + '

Crossover frequency response LR4 · 24 dB/oct · calculated at 48 kHz

'+ + ''+ + ''+guides+ + [50,100,500,1000,5000,10000].map(hz=>'').join("")+ + crossoverMarks+curves+ticks+''+ + '

Calculated electrical LR4 magnitude. No microphone measurement, speaker response, acoustic summation or phase correction. Output remains disconnected.

'+ + '
'+ + ''+ + ''+ + ''+ + '
'+ + '

A structural change clears every matrix patch and output protection draft. Never reconnect an HF speaker automatically.

'+ + '
'+ + '

Section boundaries Linked '+(state.stereo?"L/R":"mono")+' design

'+ + rows+'
'+splits+ + '

Start with section count, then patch sections to destinations in Matrix. Split frequencies must be checked against speaker specifications and actual device sample rate.

'+ + '
'+btn("Route sections → Matrix","go:matrix")+'
'+ + '
'; +} +function matrixPage() { + const headers=state.ports.map(p=>''+safe(p.replace("DEMO-","D"))+'').join(""); + const rows=state.sections.map(s=>''+safe(s.name)+''+ + state.ports.map(p=>'').join("")+'').join(""); + return '

Section → Output Matrix Exclusive destination · source fan-out allowed

'+ + '
'+ + 'Hardware pin identity will come from ASIO discovery; these IDs are placeholders.
'+ + '
'+ + headers+''+rows+'
CROSSOVER
'+ + '

Click a crosspoint to assign/unassign that section. A destination can have only one section; several destinations may share a source. A different hardware device must be explicitly mapped later.

'+ + '
'; +} +function outputList() { + return '
'+state.ports.map(p=> + '').join("")+'
'; +} +function dspPage() { + const p=state.dsp[selectedPort]||{},section=state.sections.find(s=>s.id===state.routes[selectedPort]); + const bands=p.peq||[]; + const selector='
'+ + ["eq","level","protection"].map(id=> + '').join("")+'
'; + let editor=""; + if(dspTab==="eq"){ + const pointX=i=>24+650*i/95,yDb=db=>30+(18-Math.max(-18,Math.min(18,db)))*4.5; + const pth=Array.from({length:96},(_,i)=>{ + const hz=20*Math.pow(1000,i/95); + const db=M.peqMagnitude(bands,hz); + return (i?'L':'M')+pointX(i).toFixed(2)+' '+yDb(db).toFixed(2); + }).join(' '); + const eqRows=bands.map((b,i)=> + '').join(""); + const current=bands[selectedBand]; + editor='

Parametric EQ 8-band capacity · design only

'+ + ''+ + ''+ + [-18,-9,0,9,18].map(db=>''+ + (db>0?'+':'')+db+'').join('')+ + ''+ + [20,100,1000,10000,20000].map(hz=>''+ + (hz===20000?'20k':hz===10000?'10k':hz===1000?'1k':hz)+'').join('')+ + '

Calculated peaking EQ response at 48 kHz. No acoustic measurement or output PCM.

'+ + '
'+eqRows+'
'+ + '
'+ + ''+ + (current?btn("Remove selected","removePeq"):'')+'
'+ + (current?'
'+ + '
'+ + '
'+ + '
'+ + '
': + '

No EQ bands. Add a band to start shaping this output.

'); + }else if(dspTab==="level"){ + editor='

Gain / polarity / delay Selected destination only

'+ + '
'+ + '
'+ + '
'+ + '
'+ + '
'+ + '
'+ + '
'+ + '

Need distance-based timing? Use Alignment and copy its calculated offsets to output delay drafts.

'+ + btn("Open visual alignment","go:alignment"); + }else{ + editor='

Speaker protection NOT CALIBRATED

'+ + '
'+ + '
'+ + '
'+ + '
'+ + '

Digital dBFS is not loudspeaker power or excursion. Native soft-knee/peak/RMS protection, amplifier sensitivity and speaker profiles require field calibration before hardware can ever be armed. No DSP writes or output-enable API exists here.

'; + } + return '
'+ + '

Section destinations Hardware port unavailable

'+ + outputList()+'
'+ + '

'+safe(selectedPort||"No output")+ + ' '+safe(section?.name||"Not patched")+'

'+ + selector+'
'+editor+'
'; +} +function alignPage() { + const all=M.alignment(state); + const result=all.find(r=>r.port===selectedPort); + const xSvg=x=>320+x*12,ySvg=y=>70+y*10; + const lines=all.map(r=>{ + const s=state.positions[r.port],x=xSvg(s.x),y=ySvg(s.y); + const refX=xSvg(state.listener.x),refY=ySvg(state.listener.y); + const midX=(x+refX)/2,midY=(y+refY)/2; + return ''+ + ''+unit(r.distanceM)+' m'+ + ''+ + ''+safe(r.port.replace("DEMO-","D"))+''; + }).join(""); + const sx=state.positions[selectedPort]?.x??0,sy=state.positions[selectedPort]?.y??0; + const table=all.map(r=>''+ + ''+safe(r.port)+''+unit(r.distanceM)+' m'+unit(r.additionalMs)+' ms'+ + ''+unit(state.dsp[r.port]?.delayMs??0)+' ms').join(""); + return '
'+ + '

Distance alignment Top view · metres

'+ + ''+ + ''+ + 'STAGE'+ + [100,160,220,280,340].map(y=>'').join('')+ + lines+''+ + 'REFERENCE'+ + '

Drag speakers or the reference marker. This calculates direct-path distances and arrival-time offsets, NOT phase or measured acoustic alignment.

'+ + '
'+ + ''+ + ''+table+'
OutputDistanceSuggestedDraft
'+ + '

Geometry inspector Not applied to audio

'+ + ''+ + ''+ + '
'+ + '
'+ + '
'+ + '
'+ + '
'+ + '
'+unit(result?.additionalMs||0)+' ms'+ + 'Suggested offset for '+safe(selectedPort)+'
'+ + '

Farthest speaker receives zero relative delay. Nearer speakers receive an additional delay (343 m/s assumption).

'+ + '
'+btn("Copy offsets into delay drafts","planDelay")+ + '

No geometry-only estimate compensates crossover phase, horn depth, temperature, device latency or measured impulse response. Draft changes never arm hardware or modify the JUCE callback.

'+ + '
'; +} +function reviewBox() { + if (!pending) return ""; + return '
'+ + 'Review structural change

'+safe(pending.description)+ + '

'+btn("Confirm, clear routes","confirm")+ + btn("Cancel","cancel")+'
'; +} +function render() { + const open=!root.hidden; + if (!open) return; + root.innerHTML=''+ + '

'+pageNames[page]+ + '

'+safe(state.name)+' · '+(state.stereo?"Stereo":"Mono")+ + ' · '+state.ways+' Way · revision '+state.revision+'
'+ + '
DESIGN ONLY · OUTPUT DISCONNECTED
'+ + '
'+reviewBox()+ + (message?'':'')+ + ({system:systemPage,crossover:frequencyPage,matrix:matrixPage, + processing:dspPage,alignment:alignPage}[page]())+'
'; +} +function update(next) {state=next;message="";pending=null;if(!state.ports.includes(selectedPort)){selectedPort=state.ports[0]||null;selectedBand=0;}render();} +function openLms(open) { + root.hidden=!open;app.classList.toggle("lms-active",open); + launch.setAttribute("aria-pressed",String(open)); + launch.textContent=open?"Back to Mixer":"Speakers"; + if (open) render(); +} +launch.addEventListener("click",()=>openLms(root.hidden)); +root.addEventListener("click",event=>{ + const t=event.target.closest("button");if(!t)return; + const id=t.dataset.page; + if(id){page=id;pending=null;message="";render();return;} + const act=t.dataset.action; + if(act?.startsWith("go:")){page=act.slice(3);pending=null;render();return;} + if(act==="cancel"){pending=null;render();return;} + if(act==="planDelay"){ + pending={description:"Copy calculated geometric delays to all output DSP DRAFTS. No audio, device, native PCM ACK, or hardware output will be changed.", + run:()=>M.withSuggestedDelays(state)}; + render();return; + } + if(act==="addPeq"){ + try{selectedBand=state.dsp[selectedPort].peq.length; + update(M.withPeqBand(state,selectedPort,selectedBand,{}));} + catch(e){message=e.message;render();} + return; + } + if(act==="removePeq"){ + try{const next=M.withoutPeqBand(state,selectedPort,selectedBand); + selectedBand=Math.max(0,selectedBand-1);update(next);} + catch(e){message=e.message;render();} + return; + } + if(t.dataset.dspTab){dspTab=t.dataset.dspTab;render();return;} + if(t.dataset.selectBand!==undefined){selectedBand=Number(t.dataset.selectBand);render();return;} + + if(act==="confirm"&&pending){const p=pending;update(p.run());return;} + if(t.dataset.routePort){ + try{update(M.withRoute(state,t.dataset.routePort,t.dataset.routeSection));} + catch(e){message=e.message;render();} + return; + } + if(t.dataset.selectPort){selectedPort=t.dataset.selectPort;selectedBand=0;render();} +}); +root.addEventListener("change",event=>{ + const t=event.target; + try { + if(t.dataset.ways!==undefined){ + const ways=Number(t.value); + if(ways!==state.ways) pending={description:"Changing the number of ways clears ALL crosspoints and resets output DSP drafts. The current mixer/audio remains untouched.",run:()=>M.withWays(state,ways)}; + render();return; + } + if(t.dataset.stereo!==undefined){ + const stereo=t.value==="1"; + if(stereo!==state.stereo)pending={description:"Changing mono/stereo layout clears ALL patches and resets output DSP drafts.",run:()=>M.withStereo(state,stereo)}; + render();return; + } + if(t.dataset.ports!==undefined){ + const n=Number(t.value); + if(n!==state.ports.length)pending={description:"Changing the demo port roster clears ALL patches. Real ASIO pins are never guessed.",run:()=>M.withPorts(state,M.demoPorts(n))}; + render();return; + } + if(t.dataset.cutoff!==undefined){update(M.withCutoff(state,Number(t.dataset.cutoff),Number(t.value)));return;} + if(t.dataset.selectPort!==undefined||t.dataset.alignPort!==undefined){selectedPort=t.value;selectedBand=0;render();return;} + if(t.dataset.peqField!==undefined){ + const field=t.dataset.peqField; + const value=field==="enabled"?t.value==="1":Number(t.value); + update(M.withPeqBand(state,selectedPort,selectedBand,{[field]:value})); + return; + } + if(t.dataset.dsp!==undefined){ + const field=t.dataset.dsp; + const v=["muted","limiterEnabled"].includes(field)?t.value==="1": + field==="limiterThresholdDb"?(t.value===""?null:Number(t.value)): + ["delayMs","gainDb"].includes(field)?Number(t.value):t.value; + update(M.withDsp(state,selectedPort,{[field]:v}));return; + } + if(t.dataset.position!==undefined){ + const pos=state.positions[selectedPort]; + update(M.withPosition(state,selectedPort, + t.dataset.position==="x"?Number(t.value):pos.x, + t.dataset.position==="y"?Number(t.value):pos.y));return; + } + if(t.dataset.listener!==undefined){ + update(M.withListener(state, + t.dataset.listener==="x"?Number(t.value):state.listener.x, + t.dataset.listener==="y"?Number(t.value):state.listener.y));return; + } + }catch(e){message=e.message;render();} +}); +function point(svg,e) { + const r=svg.getBoundingClientRect(); + return {x:(e.clientX-r.left)*640/r.width,y:(e.clientY-r.top)*380/r.height}; +} +root.addEventListener("pointerdown",e=>{ + const t=e.target.closest("[data-speaker],[data-listener-point]"); + if(!t||e.button!==0)return; + const svg=t.closest("svg");if(!svg)return; + dragging={svg,id:e.pointerId,port:t.dataset.speaker||null}; + svg.setPointerCapture(e.pointerId); + e.preventDefault(); +}); +root.addEventListener("pointerup",e=>{ + if(!dragging||dragging.id!==e.pointerId)return; + const drag=dragging;dragging=null; + const q=point(drag.svg,e),x=Math.round(((q.x-320)/12)*10)/10, + y=Math.round(((q.y-70)/10)*10)/10; + try{ + if(drag.port){selectedPort=drag.port;update(M.withPosition(state,drag.port,x,y));} + else update(M.withListener(state,x,y)); + }catch(err){message=err.message;render();} +}); +root.addEventListener("pointercancel",()=>{dragging=null;}); +window.addEventListener("keydown",e=>{ + if(e.key==="Escape"&&!root.hidden&& + !e.target.closest("input,select,textarea"))openLms(false); +}); +launch.setAttribute("aria-pressed","false"); +})(); diff --git a/site/preview-v2/assets/mixer-control-keys.css b/site/preview-v2/assets/mixer-control-keys.css index 8dd084432..72e39d90d 100644 --- a/site/preview-v2/assets/mixer-control-keys.css +++ b/site/preview-v2/assets/mixer-control-keys.css @@ -212,7 +212,7 @@ } .app .console-body .strip .mx-hw-row>button.mx-hw-key[data-hw-kind="mute"]{--mx-hw-led:255,78,90} .app .console-body .strip .mx-hw-row>button.mx-hw-key[data-hw-kind="solo"]{--mx-hw-led:255,207,68} -.app .console-body .strip .mx-hw-row>button.mx-hw-key[data-hw-kind="cue"]{--mx-hw-led:101,210,236} +.app .console-body .strip .mx-hw-row>button.mx-hw-key[data-hw-kind="pfl"]{--mx-hw-led:101,210,236} /* Occluded light escape: partial bottom + weak short sides, no neon perimeter. */ .app .console-body .strip .mx-hw-row>button.mx-hw-key::before{ content:""; diff --git a/site/preview-v2/assets/mixer-control-keys.js b/site/preview-v2/assets/mixer-control-keys.js index 4db54dfeb..50a1e5651 100644 --- a/site/preview-v2/assets/mixer-control-keys.js +++ b/site/preview-v2/assets/mixer-control-keys.js @@ -5,7 +5,7 @@ 'use strict'; const SELECTOR='.console-body .mx-hw-row>button.mx-hw-key'; const COLORS=Object.freeze({ - mute:'255,78,90',solo:'255,207,68',cue:'101,210,236' + mute:'255,78,90',solo:'255,207,68',pfl:'101,210,236' }); const records=new WeakMap(); const escapeXml=value=>String(value).replace(/[&<>"']/g,ch=>({ @@ -78,7 +78,7 @@ if(records.has(button)){if(button.dataset.hwKind!=='mute')render(button);return;} const semantic=button.dataset.hwKind; if(!Object.hasOwn(COLORS,semantic))return; - const legend=({mute:'MUTE',solo:'SOLO',cue:'PFL'})[semantic]; + const legend=({mute:'MUTE',solo:'SOLO',pfl:'PFL'})[semantic]; if(!button.hasAttribute('aria-label'))button.setAttribute('aria-label',legend); // MUTE uses lightweight DOM + CSS; no SVG, image asset, or resize redraw. if(semantic==='mute'){ diff --git a/site/preview-v2/assets/mixer-fx-rack.css b/site/preview-v2/assets/mixer-fx-rack.css index 2328ef9dd..fcfe5033d 100644 --- a/site/preview-v2/assets/mixer-fx-rack.css +++ b/site/preview-v2/assets/mixer-fx-rack.css @@ -1157,3 +1157,220 @@ .mx-peq .mx-fxp-save-as::before{content:"+";font-size:14px} .mx-peq .mx-fxp-manage{min-width:23px;padding:0} } + +/* 8D-SonKu editor: inherits the existing approved FX Rack CSS owner. */ +.mx-sonku[hidden]{display:none!important} +.mx-sonku{position:fixed;z-index:1300;left:50%;transform:translateX(-50%); + max-height:88vh;overflow:auto; + color:#dcecf3;border-radius:12px; + font:400 12px/1.45 inherit} +.mx-sonku button,.mx-sonku input{font:inherit} +.mx-sonku button{cursor:pointer;color:inherit} +.mx-sonku .sk-head{display:flex;align-items:center;gap:12px; + } +.mx-sonku .sk-brand{color:#f3f9ff} +.mx-sonku .sk-brand span{color:#56c3d7} +.mx-sonku .sk-headnote{} +.mx-sonku .sk-channel{margin-left:auto;font-size:11px;color:#b1cad8;white-space:nowrap} +.mx-sonku .sk-close{border:1px solid #526878;background:#233849;border-radius:6px;width:25px;height:25px;font-size:20px;line-height:1} +.mx-sonku .sk-content{display:grid;} +.mx-sonku .sk-stage{min-width:0} +.mx-sonku .sk-stage svg{display:block;width:100%;height:auto;} +.mx-sonku .sk-stage text{font-family:inherit;font-size:10px;fill:#90adbb;letter-spacing:1px} +.mx-sonku .sk-stage .sk-source-label{} +.mx-sonku .sk-stage .sk-right .sk-source-label{} +.mx-sonku .sk-source-bg{stroke:#61d6e8;} +.mx-sonku .sk-source-core{fill:#61d6e8} +.mx-sonku .sk-right .sk-source-bg{stroke:#e2a8d9} +.mx-sonku .sk-right .sk-source-core{fill:#e2a8d9} +.mx-sonku .sk-src{} +.mx-sonku .sk-src:focus .sk-source-bg{stroke-width:4} +.mx-sonku .sk-src:active{} +.mx-sonku .sk-stage-caption{text-align:center;margin-top:5px} +.mx-sonku .sk-controls{min-width:0;display:flex;flex-direction:column;} +.mx-sonku .sk-control-title{} +.mx-sonku .sk-buttons{display:flex;} +.mx-sonku .sk-buttons button{line-height:1.2;flex:1;border-radius:6px; + } +.mx-sonku .sk-buttons button[aria-pressed="true"]{} +.mx-sonku .sk-controls label{display:grid;grid-template-columns:1fr auto;gap:5px;font-size:10px;letter-spacing:.6px;color:#a6c2cf} +.mx-sonku .sk-controls label output{font-variant-numeric:tabular-nums;color:#e1f6fa} +.mx-sonku .sk-controls label input{grid-column:1/-1;width:100%;margin:3px 0 0;accent-color:#5fc8db;height:14px} +.mx-sonku .sk-guide{margin-top:auto} +.mx-sonku .sk-status{display:flex;justify-content:space-between;gap:10px; + font-size:10px;} +.mx-sonku #skHint{text-align:right} +@media(max-width:550px){.mx-sonku{} + .mx-sonku .sk-content{} + .mx-sonku .sk-headnote{display:none} + .mx-sonku .sk-stage svg{} + .mx-sonku .sk-controls{} +} + +/* 8D-SonKu top-view graphic. ONE approved FX Rack CSS owner; no new CSS file. */ +.mx-sonku .sk-listener-art{ + + +} +.mx-sonku .sk-stage .sk-direction{} +.mx-sonku .sk-stage .sk-front{} +.mx-sonku .sk-stage .sk-src{touch-action:none} + +/* SonKu top-view polish: lightweight vector stage + passive approved PNG. + Keep sprite and CSS in the existing 18-owner GUI, never rotate audio DSP. */ +.mx-sonku .sk-stage svg{background:#0c1926} +.mx-sonku .sk-listener-art{image-rendering:auto; + } +.mx-sonku .sk-source-bg{stroke-width:1.8;fill:#153d51;fill-opacity:.98; + filter:drop-shadow(0 1px 5px rgba(81,207,235,.42))} +.mx-sonku .sk-right .sk-source-bg{fill:#482c42;filter:drop-shadow(0 1px 5px rgba(227,158,208,.36))} +.mx-sonku .sk-source-core{display:none} +.mx-sonku .sk-stage .sk-source-label{fill:#e1faff;font-size:11px;font-weight:600;letter-spacing:0;pointer-events:none} +.mx-sonku .sk-stage .sk-right .sk-source-label{fill:#ffe4f6} +.mx-sonku .sk-stage .sk-front{font-weight:600} + +/* 8D-SonKu P1 studio hardware skin; component scoped, 18 CSS owners intact. + The far dashed rail is behind listener PNG; near elliptical rail is in front. + Source monitor separation is render-only; never changes native HRIR angles. */ +.mx-sonku{width:min(758px,calc(100vw - 28px));top:8%;background:#0f1d29; + border:1px solid #435b68;border-top-color:#708997;border-bottom-color:#253a45; + box-shadow:0 23px 54px rgba(0,0,0,.74),inset 0 1px rgba(233,251,255,.11); + font-family:Inter,"Segoe UI",Arial,sans-serif;font-size:11px;letter-spacing:.04px} +.mx-sonku .sk-head{background:linear-gradient(180deg,#2c4150,#152833); + border-bottom:1px solid #071721;box-shadow:inset 0 1px rgba(231,248,255,.15); + min-height:40px;padding:8px 14px} +.mx-sonku .sk-brand{font-weight:650;letter-spacing:.1px;font-size:15px; + text-shadow:0 1px 1px #000} +.mx-sonku .sk-headnote{letter-spacing:1.3px;color:#93b6c6;font-size:9px} +.mx-sonku .sk-content{grid-template-columns:minmax(0,1.48fr) minmax(220px,1fr); + gap:0;padding:0;align-items:stretch} +.mx-sonku .sk-stage{padding:11px 10px 6px 12px; + background:linear-gradient(155deg,#162936,#0c1b28); + border-right:1px solid #395565} +.mx-sonku .sk-stage svg{border:1px solid #3f5f70;border-top-color:#233f4f; + border-radius:7px;box-shadow:inset 0 2px 8px #010c15;aspect-ratio:400/330} +.mx-sonku .sk-stage text{paint-order:stroke fill} +.mx-sonku .sk-orbit-rear{stroke-linecap:round} +.mx-sonku .sk-orbit-front{stroke-linecap:round;filter:drop-shadow(0 0 3px rgba(104,202,224,.27))} +.mx-sonku .sk-listener-art{pointer-events:none;opacity:.97; + filter:drop-shadow(0 5px 9px rgba(37,183,230,.17))} +.mx-sonku .sk-stage .sk-direction{font-size:9px;letter-spacing:1.25px;fill:#98bcc9; + font-weight:550} +.mx-sonku .sk-stage .sk-front{fill:#81e6ee;font-size:10px} +.mx-sonku .sk-src{cursor:grab;touch-action:none;outline:none; + filter:drop-shadow(0 2px 4px rgba(0,0,0,.62))} +.mx-sonku .sk-src:active{cursor:grabbing} +.mx-sonku .sk-speaker-shell{fill:#203745;stroke:#7cbdcc;stroke-width:1.4} +.mx-sonku .sk-speaker-inner{fill:#0c202c;stroke:#325665;stroke-width:.8} +.mx-sonku .sk-speaker-tweeter{fill:#8bcbd7;stroke:#365c6b;stroke-width:1} +.mx-sonku .sk-speaker-woofer{fill:#355f70;stroke:#91cfda;stroke-width:1.15} +.mx-sonku .sk-speaker-cone{fill:#162e3a;stroke:#78acba;stroke-width:.9} +.mx-sonku .sk-right .sk-speaker-shell{stroke:#e3accf;fill:#4a3545} +.mx-sonku .sk-right .sk-speaker-inner{fill:#251e2b;stroke:#7a526d} +.mx-sonku .sk-right .sk-speaker-tweeter{fill:#edc5df;stroke:#885d7b} +.mx-sonku .sk-right .sk-speaker-woofer{fill:#8b5d7c;stroke:#e8b6d5} +.mx-sonku .sk-right .sk-speaker-cone{fill:#3c293e;stroke:#d3a5c4} +.mx-sonku .sk-stage .sk-speaker-label{fill:#e9fbff;font-size:12px; + font-weight:650;letter-spacing:.5px;pointer-events:none; + stroke:rgba(3,20,30,.8);stroke-width:2.1px} +.mx-sonku .sk-right .sk-speaker-label{fill:#ffe7f8} +.mx-sonku .sk-src:focus-visible .sk-speaker-shell{stroke-width:2.8} +.mx-sonku .sk-tether{pointer-events:none} +.mx-sonku .sk-stage-caption{font-size:8px;letter-spacing:.9px;margin:5px 0 1px;color:#86aebc} +.mx-sonku .sk-controls{padding:13px 14px 9px;gap:9px; + background:linear-gradient(135deg,#233542 0,#182b38 22%,#142430 85%,#10212d 100%); + box-shadow:inset 1px 0 rgba(255,255,255,.07)} +.mx-sonku .sk-control-title{display:flex;align-items:center;justify-content:space-between; + font-size:10px;letter-spacing:1.4px;font-weight:600;color:#bedbe5;padding:2px 0} +.mx-sonku .sk-engine-led{display:inline-flex;align-items:center;gap:5px; + font-size:8px;letter-spacing:.65px;color:#83acb7;font-weight:500} +.mx-sonku .sk-engine-led::before{content:"";width:5px;height:5px;border-radius:50%; + background:#72d6ce;box-shadow:0 0 6px #65ceb8} +.mx-sonku .sk-buttons{gap:7px} +.mx-sonku .sk-buttons button{min-height:31px;padding:6px 4px;font-weight:600; + letter-spacing:.75px;font-size:9px;color:#b6d1dd; + border:1px solid #425e6f;border-top-color:#6d8b98;border-bottom-color:#223c4b; + background:linear-gradient(#304a59,#1d3342); + box-shadow:inset 0 1px rgba(255,255,255,.11),0 2px 3px rgba(0,0,0,.35)} +.mx-sonku .sk-buttons button[aria-pressed="true"]{ + background:linear-gradient(#2c6a7b,#19485b);border-color:#73baca; + color:#e5fbff;box-shadow:inset 0 1px rgba(255,255,255,.2),0 0 6px rgba(75,193,219,.17)} +.mx-sonku .sk-rotary-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr)); + row-gap:9px;column-gap:9px;align-items:center;justify-items:center; + flex:1;min-height:240px} +.mx-sonku .sk-rotary{display:flex!important;flex-direction:column;align-items:center; + justify-content:center;gap:4px;min-width:0;width:100%; + padding:5px 1px!important;border:0;letter-spacing:.7px} +.mx-sonku .sk-param-name{font-size:9px;color:#b9d3df; + letter-spacing:.8px;font-weight:600;white-space:nowrap;text-align:center} +.mx-sonku .sk-dial{--sk-sweep:135deg;--sk-needle:0deg; + display:block;position:relative;width:62px;height:62px;flex:none; + cursor:ns-resize;touch-action:none;user-select:none;outline:none} +.mx-sonku .sk-dial-track{position:absolute;inset:0;border-radius:50%; + background:conic-gradient(from 225deg,#65cadd 0deg,#65cadd var(--sk-sweep), + #344d5d var(--sk-sweep),#344d5d 270deg,transparent 270deg 360deg); + mask:radial-gradient(circle,transparent 0 53%,black 55% 62%,transparent 64%); + filter:drop-shadow(0 0 2px rgba(95,199,221,.27))} +.mx-sonku .sk-dial-cap{position:absolute;inset:9px;border-radius:50%; + border:1px solid #758a94;border-bottom-color:#142530;border-right-color:#263f4b; + background:radial-gradient(circle at 38% 28%,#5e7481 0%,#3c5462 24%,#233d4b 55%,#142b39 84%); + box-shadow:0 3px 6px #081521,inset 0 1px 2px rgba(240,251,255,.4), + inset 0 -3px 7px rgba(0,0,0,.35);pointer-events:none} +.mx-sonku .sk-dial-needle{position:absolute;inset:0;transform:rotate(var(--sk-needle)); + transition:transform 60ms linear;pointer-events:none} +.mx-sonku .sk-dial-needle::before{content:"";display:block;position:absolute; + width:3px;height:10px;left:calc(50% - 1.5px);top:3px;border-radius:2px; + background:#d6faff;box-shadow:0 0 3px rgba(155,241,255,.56)} +.mx-sonku .sk-controls .sk-rotary .sk-dial input{ + position:absolute;inset:0;width:100%;height:100%;margin:0!important;grid-column:auto; + opacity:0;cursor:ns-resize;pointer-events:none;accent-color:transparent} +.mx-sonku .sk-rotary:focus-within .sk-dial-cap{outline:1px solid #87d5e6;outline-offset:2px} +.mx-sonku .sk-rotary output{font-size:11px;font-weight:600;letter-spacing:.2px; + font-variant-numeric:tabular-nums;color:#dcf3f7} +.mx-sonku .sk-guide{font-size:9px;line-height:1.42;color:#91b2c2; + border-top:1px solid rgba(113,157,173,.24);padding-top:9px;letter-spacing:.1px} +.mx-sonku .sk-status{background:linear-gradient(#142836,#0c1a27); + border-top:1px solid #415d6d;padding:7px 13px;letter-spacing:.55px; + color:#99bac8} +@media(max-width:550px){ + .mx-sonku{top:8px;max-height:calc(100vh - 16px)} + .mx-sonku .sk-content{grid-template-columns:1fr} + .mx-sonku .sk-stage{border-right:0;border-bottom:1px solid #344d5d} + .mx-sonku .sk-stage svg{max-height:37vh} + .mx-sonku .sk-controls{gap:8px} + .mx-sonku .sk-rotary-grid{grid-template-columns:repeat(4,minmax(0,1fr)); + row-gap:0;min-height:auto;gap:1px} + .mx-sonku .sk-dial{width:48px;height:48px} + .mx-sonku .sk-dial-cap{inset:8px} + .mx-sonku .sk-param-name{font-size:8px} + .mx-sonku .sk-rotary{padding:3px 0!important} + .mx-sonku .sk-guide{font-size:9px} +} + +/* SonKu M4 native SPACE controls — same existing FX-rack CSS owner. + Small instrument-row treatment, not another card or a 19th CSS bundle. */ +.mx-sonku .sk-space-panel{display:grid;gap:7px;padding:9px 8px 8px; + border-top:1px solid #446171;border-bottom:1px solid #203a4a; + background:rgba(5,20,30,.27);border-radius:6px} +.mx-sonku .sk-space-head{display:flex;align-items:center;justify-content:space-between; + font-size:9px;letter-spacing:.85px;color:#afcfdd;font-weight:550} +.mx-sonku .sk-space-head output{color:#8ed3e0;font-size:9px;letter-spacing:.2px; + font-variant-numeric:tabular-nums} +.mx-sonku .sk-space-options{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:4px} +.mx-sonku .sk-space-options button{min-width:0;min-height:26px;padding:4px 2px; + border:1px solid #45616c;border-radius:4px;background:#1d3543; + font-size:8px;letter-spacing:.2px;font-weight:500;color:#bad2dc} +.mx-sonku .sk-space-options button[aria-pressed="true"]{color:#e8fbff; + border-color:#6fc6d7;background:#24556a;box-shadow:inset 0 1px #ffffff19} +.mx-sonku .sk-space-options button:focus-visible{outline:2px solid #9bdae8;outline-offset:1px} +.mx-sonku .sk-controls .sk-space-slider{display:grid!important; + grid-template-columns:1fr auto;gap:3px!important;align-items:center; + font-size:9px;letter-spacing:.4px;color:#a6c5d1;margin:0} +.mx-sonku .sk-controls .sk-space-slider output{font-size:9px; + color:#daf2f7;font-variant-numeric:tabular-nums} +.mx-sonku .sk-controls .sk-space-slider input{grid-column:1/-1; + width:100%;height:13px;margin:0!important;accent-color:#67c4d7} +.mx-sonku .sk-space-slider input:disabled{opacity:.32;cursor:not-allowed} +.mx-sonku .sk-space-hint{font-size:8px;line-height:1.35;color:#87aebb} +@media(max-width:550px){.mx-sonku .sk-space-panel{gap:6px;padding:8px} + .mx-sonku .sk-space-options button{min-height:29px;font-size:9px}} diff --git a/site/preview-v2/assets/mixer-native-sonku.js b/site/preview-v2/assets/mixer-native-sonku.js new file mode 100644 index 000000000..e6e57fd7c --- /dev/null +++ b/site/preview-v2/assets/mixer-native-sonku.js @@ -0,0 +1,537 @@ +/* 8D-SonKu. Presentation only: native JUCE remains the ONLY PCM authority. + No WebAudio, source simulation, optimistic DSP success or second /preview/. */ +(() => { +"use strict"; +const ID="armix.builtin.8d-sonku.v1"; +const defaults=()=>({startAzimuthDegrees:0,revolutionSeconds:12, + stereoSpreadDegrees:60,spatialMix:1,outputTrim:.75,moving:true,clockwise:true, + spacePreset:0,sourceDistanceMeters:1.6,roomAmount:.55,ambience:.30}); +const normalizeSettings=s=>({...defaults(),...s}); +// Legacy v1/v2 states already persist a LINEAR outputTrim number (0..1). +// Keep the native JSON key and its meaning intact; the visible GAIN dial +// now expresses the SAME linear multiplier in dB and can exceed unity. +// No schema/serialized-bytes migration is necessary. +const toDb=g=>g>0?Math.max(-24,20*Math.log10(g)):-24; +const fromDb=db=>Number(Math.pow(10,Number(db)/20).toFixed(6)); +const dbLabel=db=>(db>0?"+":"")+db.toFixed(1)+" dB"; +const roomMaxDistance=[10,3.1,6.7,10]; +const valid=s=>s && Number.isFinite(s.startAzimuthDegrees) && + Math.abs(s.startAzimuthDegrees)<=360 && + Number.isFinite(s.revolutionSeconds)&&s.revolutionSeconds>=.5&&s.revolutionSeconds<=120 && + Number.isFinite(s.stereoSpreadDegrees)&&s.stereoSpreadDegrees>=0&&s.stereoSpreadDegrees<=180 && + Number.isFinite(s.spatialMix)&&s.spatialMix>=0&&s.spatialMix<=1 && + Number.isFinite(s.outputTrim)&&s.outputTrim>=0&&s.outputTrim<=4 && + typeof s.moving==="boolean"&&typeof s.clockwise==="boolean" && + Number.isInteger(s.spacePreset) && s.spacePreset>=0 && s.spacePreset<=3 && + Number.isFinite(s.sourceDistanceMeters) && s.sourceDistanceMeters>=1.6 && + s.sourceDistanceMeters<=roomMaxDistance[s.spacePreset]+.0001 && + Number.isFinite(s.roomAmount) && s.roomAmount>=0 && s.roomAmount<=1 && + Number.isFinite(s.ambience) && s.ambience>=0 && s.ambience<=1; +const backend=()=>window.__JUCE__?.backend; +const native=()=>typeof backend()?.emitEvent==="function"; +const snapshot=()=>window.__ARMIX_NATIVE_M2__?.fxEditorState?.()|| + window.__ARMIX_NATIVE_M2__?.state?.()?.current; +const angle=(v)=>((v%360)+360)%360; +// Top-down listener faces the TOP: FRONT=0°, RIGHT=+90°, REAR=180°, +// LEFT=-90°. Presentation-only SVG projection; native HRIR ITD/ILD +// and audio rotation coordinates NEVER change. +const STAGE=Object.freeze({x:200,y:174,rx:148,ry:83}); +const stagePoint=(azimuthDegrees)=>{ + const rad=angle(azimuthDegrees)*Math.PI/180; + return {x:STAGE.x+STAGE.rx*Math.sin(rad), + y:STAGE.y-STAGE.ry*Math.cos(rad)}; +}; +const stageAzimuth=(screenX,screenY)=> + Math.atan2((screenX-STAGE.x)/STAGE.rx, + (STAGE.y-screenY)/STAGE.ry)*180/Math.PI; +// At SPREAD=0 the two actual HRIR directions coincide. Separate the +// drawings (not their acoustic coordinates) tangentially, with tiny tethers +// identifying the shared acoustic point. L and R remain independently draggable. +const displayPair=(azimuths)=>{ + const anchors=azimuths.map(stagePoint); + const distance=Math.hypot(anchors[0].x-anchors[1].x,anchors[0].y-anchors[1].y); + const mid=(azimuths[0]+azimuths[1])*0.5*Math.PI/180; + const tangent={x:STAGE.rx*Math.cos(mid),y:STAGE.ry*Math.sin(mid)}; + const n=Math.hypot(tangent.x,tangent.y)||1; + const offset=Math.max(0,(46-distance)*0.5); + return anchors.map((anchor,i)=>({ + anchor,visible:{x:anchor.x+(i===0?-1:1)*offset*tangent.x/n, + y:anchor.y+(i===0?-1:1)*offset*tangent.y/n} + })); +}; +const root=document.createElement("section"); +root.id="mxNativeSonKu";root.className="mx-sonku";root.hidden=true; +root.setAttribute("role","dialog");root.setAttribute("aria-modal","false"); +root.setAttribute("aria-label","8D-SonKu binaural spatial audio"); +root.innerHTML=[ + '
8D·SonKu', + 'BINAURAL SPATIAL MOTION', + '', + '
', + '
', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + // Far orbit belongs BEHIND the listener; true perspective elliptical rail. + '', + '', + 'FRONT', + 'REAR', + 'LEFTRIGHT', + // Original vector back-view listener: anatomy and shoulders face UP. + // Do not rotate the old face PNG upside-down or alter native HRTF angles. + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + // Near orbit overlays lower bust, forming ONE plausible 3D spatial ring. + '', + '', + // Near-field speaker icons are painted above the bust, with perspective. + '', + '', + // No circle markers: each emitter is a small raised studio monitor. + // Offsets at coincident directions are display-only; native azimuth stays equal. + '', + '', + '', + '', + '', + '', + '', + 'L', + '', + '', + '', + '', + '', + '', + '', + 'R', + '
HEADPHONES · HRIR 0° ELEVATION · 44.1 / 48 kHz
', + '
', + '
VISUAL PREVIEWNo browser audio
' +].join(""); +const $=id=>root.querySelector("#"+id); +const mount=()=>{if(!root.isConnected)document.body.append(root)}; +if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",mount,{once:true});else mount(); +let current=null,accepted=defaults(),draft=defaults(),pending=null,latest=null, + readId="",readSentAt=0,seq=1,clock=null,frame=null,observed=0,observedAt=0, + drag=null,dialDrag=null,rangeEdits=new Set(),gestureStart=new Map(), + visualPhase=0,visualAt=0,liveTimer=null,lastLiveAt=0; +const context=()=>{ + if(!current||!native())return null; + const s=snapshot(),id=window.__ARMIX_NATIVE_M2__?.nativeIdFor?.(current.track); + const ch=s?.graph?.channels?.find(x=>x.id===id); + const fx=ch?.inserts?.[current.slot]; + if(!(s?.admitted||s?.logical)||!id||fx?.catalogId!==ID||!fx?.id || + (current.instanceId&¤t.instanceId!==fx.id))return null; + return {channelId:id,slot:current.slot,instanceId:fx.id, + deviceEpoch:s.logical?"0":s.device.epoch, + ...(s.logical?{workspaceToken:s.workspaceToken}:{}),graphRevision:s.graph.revision}; +}; +function render(){ + const s=draft; + $("skMotion").textContent=s.moving?"ORBIT":"STATIC"; + $("skMotion").setAttribute("aria-pressed",String(s.moving)); + $("skDirection").textContent=s.clockwise?"CLOCKWISE":"COUNTER-CW"; + $("skDirection").setAttribute("aria-pressed",String(s.clockwise)); + const vals=[["skSpeed",s.revolutionSeconds,"skSpeedValue",s.revolutionSeconds.toFixed(1)+" s"], + ["skSpread",s.stereoSpreadDegrees,"skSpreadValue",Math.round(s.stereoSpreadDegrees)+"°"], + ["skMix",s.spatialMix*100,"skMixValue",Math.round(s.spatialMix*100)+"%"], + ["skTrim",toDb(s.outputTrim),"skTrimValue",dbLabel(toDb(s.outputTrim))]]; + for(const [input,value,out,label] of vals){ + const el=$(input);el.value=String(value);$(out).textContent=label; + const min=Number(el.min),max=Number(el.max); + const p=Math.max(0,Math.min(1,(value-min)/(max-min))); + const dial=el.closest(".sk-dial"); + dial.style.setProperty("--sk-sweep",(p*270).toFixed(2)+"deg"); + dial.style.setProperty("--sk-needle",(-135+p*270).toFixed(2)+"deg"); + } + // ROOM is one typed native scene, never a browser audio simulator. + root.querySelectorAll("[data-sk-room]").forEach(el=>{ + el.setAttribute("aria-pressed", + String(Number(el.dataset.skRoom)===s.spacePreset)); + }); + const sizeLabels=["DIRECT ONLY","7.2 × 7.2 m","14.4 × 14.4 m","28.8 × 28.8 m"]; + $("skSpaceText").textContent=sizeLabels[s.spacePreset]; + const distance=$("skDistance"),max=roomMaxDistance[s.spacePreset]; + distance.max=String(max); + distance.disabled=s.spacePreset===0; + // Native readback may arrive while the pointer is held. Never send the + // slider thumb back to the last ACK while the operator is editing. + if(!rangeEdits.has("skDistance")) + distance.value=String(Math.min(max,s.sourceDistanceMeters)); + $("skDistanceValue").textContent=s.sourceDistanceMeters.toFixed(1)+" m"; + if(!rangeEdits.has("skAmbience")) + $("skAmbience").value=String(Math.round(s.ambience*100)); + const reflections=$("skReflections"); + if(!rangeEdits.has("skReflections")) + reflections.value=String(Math.round(s.roomAmount*100)); + reflections.disabled=s.spacePreset===0; + $("skReflectionsValue").textContent=Math.round(s.roomAmount*100)+"%"; + $("skAmbience").disabled=s.spacePreset===0; + $("skAmbienceValue").textContent=Math.round(s.ambience*100)+"%"; + // Only source placement is animated; knobs and input ranges are NOT + // redrawn at 60 Hz. The native audio callback remains the time authority. + drawSpeakers(); + $("skMode").textContent=native()?(context()?"NATIVE HRTF":"NATIVE UNAVAILABLE"):"VISUAL ONLY · NO AUDIO"; +} +function drawSpeakers(){ + const s=draft; + const phase=s.moving?visualPhase:s.startAzimuthDegrees; + const angles=[phase-s.stereoSpreadDegrees/2,phase+s.stereoSpreadDegrees/2]; + const pair=displayPair(angles); + for(let source=0;source<2;++source) { + const deg=angle(angles[source]); + const {anchor,visible}=pair[source]; + const g=root.querySelector('.sk-src[data-index="'+source+'"]'); + const front=Math.cos(deg*Math.PI/180)>=0; + const layer=front?$("skFrontSources"):$("skRearSources"); + if(g.parentNode!==layer)layer.appendChild(g); + // Orthographic stage with light depth scaling: rear behind head, front + // above bust. No CSS animation of acoustic coordinates or SVG duplicate. + const depth=Math.cos(deg*Math.PI/180); + const scale=(.91+.13*depth).toFixed(3); + g.setAttribute("transform","translate("+visible.x.toFixed(2)+","+visible.y.toFixed(2)+") scale("+scale+")"); + g.style.opacity=front?"1":".84"; + g.dataset.acousticX=anchor.x.toFixed(2); + g.dataset.acousticY=anchor.y.toFixed(2); + g.dataset.visualX=visible.x.toFixed(2); + g.dataset.visualY=visible.y.toFixed(2); + const deltaX=anchor.x-visible.x,deltaY=anchor.y-visible.y; + const leader=g.querySelector(".sk-tether"); + leader.setAttribute("d","M0 0 L"+deltaX.toFixed(2)+" "+deltaY.toFixed(2)); + leader.style.opacity=Math.hypot(deltaX,deltaY)>4?".65":"0"; + g.setAttribute("aria-valuenow",String(Math.round(deg>180?deg-360:deg))); + const direction=deg<45||deg>=315?"FRONT":deg<135?"RIGHT":deg<225?"REAR":"LEFT"; + g.setAttribute("aria-valuetext",direction+" "+Math.round(deg)+"°"); + } +} +// rAF is a VISUAL interpolator, not an audio clock or optimistic DSP ACK. +// A bounded phase-locked correction follows the real native callback without +// teleporting at each ~250ms readback. Only SVG geometry is painted per frame. +function animate(time){ + if(root.hidden||!current){frame=null;return;} + if(visualAt && draft.moving && !drag){ + const dt=Math.max(0,Math.min(.08,(time-visualAt)*.001)); + const speed=(draft.clockwise?1:-1)*360/draft.revolutionSeconds; + visualPhase=angle(visualPhase+speed*dt); + if(observedAt&&!pending){ + const expected=angle(observed+(time-observedAt)*.001*speed); + const error=((expected-visualPhase+540)%360)-180; + // No hard reset to a delayed readback; max 1.5deg/frame correction. + const correction=error*(1-Math.exp(-dt/.32)); + visualPhase=angle(visualPhase+Math.max(-1.5,Math.min(1.5,correction))); + } + drawSpeakers(); + } + visualAt=time; + frame=requestAnimationFrame(animate); +} +function hint(s){$("skHint").textContent=s;} +function requestSnapshot(force=false){ + const c=context();if(!c)return; + const now=performance.now(); + // Avoid replacing an unanswered request at each 250ms render tick. + if(!force && readId && now-readSentAt<1500)return; + readId="sk-read-"+String(Date.now())+"-"+(++seq); + readSentAt=now; + backend().emitEvent("arMixAction",{action:"nativeSonKuSnapshot",requestId:readId,...c}); +} +// One reusable CONTROL gesture publisher for every SonKu slider, knob, +// keyboard nudge and SVG speaker. The JUCE PCM callback still owns audio. +// Limit UI→native emissions to <= 25Hz. At most ONE change in flight, with +// latest-wins coalescing; ACK + accepted snapshot remain mandatory before +// issuing the next. Never fill the DSP SPSC queue with raw pointer events. +const LIVE_INTERVAL_MS=40; +const sameSettings=(a,b)=>a&&b&&Object.keys(defaults()).every(k=>a[k]===b[k]); +function send(next,continuous=false){ + if(!valid(next))return false; + draft={...next};render(); + if(!native()){accepted={...next};hint("BROWSER VISUAL ONLY · NO DSP");return true;} + const c=context();if(!c){hint("NATIVE INSERT NOT ACCEPTED");return false;} + if(pending){ + latest=sameSettings(next,pending.settings)?null:{...next}; + if(!continuous)hint("DSP FOLLOWING · FINAL VALUE PENDING"); + return true; + } + if(sameSettings(next,accepted))return true; + const id="sonku-"+String(Date.now()*1000+(++seq%1000)); + pending={requestId:id,settings:{...next},context:c,ack:false}; + backend().emitEvent("arMixAction",{action:"nativeSonKuSet",requestId:id,...c,settings:next}); + hint(continuous?"DSP LIVE · AWAITING AUDIO ACK":"DSP QUEUED · AWAITING AUDIO ACK"); + return true; +} +function cancelLiveTimer(){ + if(liveTimer!==null){clearTimeout(liveTimer);liveTimer=null;} +} +function liveInput(next){ + if(!valid(next))return false; + draft={...next};render(); + const now=performance.now(),wait=LIVE_INTERVAL_MS-(now-lastLiveAt); + if(wait<=0){ + cancelLiveTimer();lastLiveAt=now;return send(next,true); + } + if(liveTimer===null)liveTimer=setTimeout(()=>{ + liveTimer=null;lastLiveAt=performance.now(); + if(current&&!root.hidden)send({...draft},true); + },Math.max(0,wait)); + return true; +} +function commitInput(next){ + cancelLiveTimer();lastLiveAt=performance.now(); + return send(next,false); +} +function flushLatest(){ + if(latest){const next=latest;latest=null; + if(!sameSettings(next,accepted))send(next,true); + } +} +function finishFailure(reason){ + cancelLiveTimer();pending=null;latest=null; + // Native failure is real. Never display false "applied" audio; read back + // authoritative DSP state, do not retry a stale device/graph on a timer. + draft={...accepted};hint(reason);render();requestSnapshot(true); +} +backend()?.addEventListener?.("arMixBuiltinSonKuQueue",r=>{ + if(!pending||r?.requestId!==pending.requestId)return; + if(r.status==="REJECTED")finishFailure("DSP REJECTED · "+(r.errorCode||"STALE")); +}); +backend()?.addEventListener?.("arMixBuiltinSonKuAck",r=>{ + if(!pending||r?.requestId!==pending.requestId)return; + if(r.status!=="APPLIED")return finishFailure("DSP NOT APPLIED · "+(r.errorCode||"STALE")); + pending.ack=true;hint("DSP APPLIED · VERIFYING READBACK");requestSnapshot(true); +}); +backend()?.addEventListener?.("arMixBuiltinSonKuSnapshot",r=>{ + if(r?.requestId!==readId||!current)return; + const c=context();if(!c||r.status!=="ACCEPTED"|| + r.channelId!==c.channelId||r.instanceId!==c.instanceId)return; + const incoming=normalizeSettings(r.settings); + if(!valid(incoming))return; + readId="";readSentAt=0; + if(pending) { + if(!pending.ack || r.appliedRequestId!==pending.requestId){ + if(pending.ack)requestSnapshot(); + return; + } + accepted={...incoming};pending=null;hint("DSP APPLIED · ACCEPTED");flushLatest(); + }else if(!drag&&!dialDrag&&rangeEdits.size===0){ + accepted={...incoming};draft={...incoming}; + }else if(!pending){ + // Preserve live thumb ownership, yet advance the accepted mirror so a + // later failure/reopen never restores a stale value. + accepted={...incoming}; + } + if(Number.isFinite(r.observedAzimuthDegrees)){ + // First authoritative phase anchors the loop once. Subsequent readbacks + // only adjust the PLL; never set the visible phase discontinuously. + if(!observedAt)visualPhase=angle(r.observedAzimuthDegrees); + observed=r.observedAzimuthDegrees;observedAt=performance.now(); + } + render(); +}); +$("skClose").addEventListener("click",()=>{root.hidden=true;current=null; + cancelLiveTimer();pending=null;latest=null;readId="";readSentAt=0;dialDrag=null; + drag=null;rangeEdits.clear();gestureStart.clear();lastLiveAt=0; + if(clock!==null){clearInterval(clock);clock=null;} + if(frame!==null){cancelAnimationFrame(frame);frame=null;}}); +$("skMotion").addEventListener("click",()=>send({...draft,moving:!draft.moving})); +$("skDirection").addEventListener("click",()=>send({...draft,clockwise:!draft.clockwise})); +root.querySelectorAll("[data-sk-room]").forEach(btn=>btn.addEventListener("click",()=>{ + const preset=Number(btn.dataset.skRoom),max=roomMaxDistance[preset]; + send({...draft,spacePreset:preset, + sourceDistanceMeters:preset===0?draft.sourceDistanceMeters: + Math.min(draft.sourceDistanceMeters,max)}); +})); +for(const [id,key,convert] of [ + ["skDistance","sourceDistanceMeters",v=>v], + ["skReflections","roomAmount",v=>v/100], + ["skAmbience","ambience",v=>v/100]]) { + const slider=$(id); + // ALL acoustic sliders stream PCM changes on input, not only on release. + // Thumb ownership survives stale ACK snapshots; no speculative "APPLIED". + slider.addEventListener("pointerdown",()=>{ + rangeEdits.add(id);gestureStart.set(id,draft[key]); + }); + slider.addEventListener("input",()=>{ + if(slider.disabled)return; + const value=Number(slider.value); + if(!Number.isFinite(value))return; + rangeEdits.add(id); + liveInput({...draft,[key]:convert(value)}); + }); + slider.addEventListener("change",()=>{ + gestureStart.delete(id);rangeEdits.delete(id); + if(slider.disabled)return; + const value=Number(slider.value); + if(Number.isFinite(value))commitInput({...draft,[key]:convert(value)}); + }); + slider.addEventListener("pointercancel",()=>{ + const original=gestureStart.has(id)?gestureStart.get(id):accepted[key]; + gestureStart.delete(id);rangeEdits.delete(id); + commitInput({...draft,[key]:original}); + }); +} +for(const [id,key,convert] of [ + ["skSpeed","revolutionSeconds",v=>v], + ["skSpread","stereoSpreadDegrees",v=>v], + ["skMix","spatialMix",v=>v/100], + ["skTrim","outputTrim",v=>fromDb(v)]]) { + const input=$(id); + input.addEventListener("input",()=>{const v=Number(input.value); + if(Number.isFinite(v))liveInput({...draft,[key]:convert(v)}); + }); + input.addEventListener("change",()=>{ + const value=Number(input.value); + if(Number.isFinite(value))commitInput({...draft,[key]:convert(value)}); + }); +} +// Tactile dials use the SAME bounded live gesture publisher as acoustic +// sliders. Keyboard, mouse and touch all have one native PCM authority. +for(const [id,initial] of [["skSpeed",12],["skSpread",60],["skMix",100],["skTrim",0]]){ + const input=$(id),dial=input.closest(".sk-dial"); + const min=Number(input.min),max=Number(input.max),step=Number(input.step)||1; + dial.addEventListener("pointerdown",e=>{ + if(e.button!==0)return; + e.preventDefault();input.focus({preventScroll:true}); + dialDrag={id,pointer:e.pointerId,startY:e.clientY,origin:Number(input.value),moved:false}; + dial.setPointerCapture(e.pointerId); + }); + dial.addEventListener("pointermove",e=>{ + if(!dialDrag||dialDrag.id!==id||dialDrag.pointer!==e.pointerId)return; + const delta=dialDrag.startY-e.clientY; + if(Math.abs(delta)>2)dialDrag.moved=true; + if(!dialDrag.moved)return; + const raw=dialDrag.origin+delta*(max-min)/135; + const bounded=Math.min(max,Math.max(min,raw)); + const next=Math.min(max,Math.max(min,min+Math.round((bounded-min)/step)*step)); + if(Number(input.value)!==next){input.value=String(next);input.dispatchEvent(new Event("input",{bubbles:true}));} + }); + const finish=e=>{ + if(!dialDrag||dialDrag.id!==id||dialDrag.pointer!==e.pointerId)return; + const moved=dialDrag.moved; + dialDrag=null; + if(dial.hasPointerCapture(e.pointerId))dial.releasePointerCapture(e.pointerId); + if(moved)input.dispatchEvent(new Event("change",{bubbles:true})); + }; + dial.addEventListener("pointerup",finish); + dial.addEventListener("pointercancel",e=>{ + if(dialDrag?.id!==id || dialDrag.pointer!==e.pointerId)return; + input.value=String(dialDrag.origin);dialDrag=null; + input.dispatchEvent(new Event("input",{bubbles:true})); + input.dispatchEvent(new Event("change",{bubbles:true})); + }); + dial.addEventListener("dblclick",e=>{ + e.preventDefault();input.value=String(initial); + input.dispatchEvent(new Event("input",{bubbles:true})); + input.dispatchEvent(new Event("change",{bubbles:true})); + }); +} +const map=$("skMap"); +function toAzimuth(e) { + const rect=map.getBoundingClientRect(); + const x=(e.clientX-rect.left)*400/rect.width; + const y=(e.clientY-rect.top)*330/rect.height; + return stageAzimuth(x,y); +} +map.addEventListener("pointerdown",e=>{ + const g=e.target.closest(".sk-src");if(!g)return; + drag={source:Number(g.dataset.index),pointer:e.pointerId, + starting:{...draft}}; + map.setPointerCapture?.(e.pointerId);e.preventDefault(); +}); +map.addEventListener("pointermove",e=>{ + if(!drag||drag.pointer!==e.pointerId)return; + const value=toAzimuth(e)-(drag.source?1:-1)*draft.stereoSpreadDegrees/2; + liveInput({...draft,startAzimuthDegrees:Math.max(-360,Math.min(360,value)), + moving:false}); +}); +map.addEventListener("pointerup",e=>{ + if(!drag||drag.pointer!==e.pointerId)return; + drag=null;map.releasePointerCapture?.(e.pointerId); + commitInput({...draft}); +}); +map.addEventListener("pointercancel",e=>{ + if(!drag||drag.pointer!==e.pointerId)return; + const prior=drag.starting;drag=null; + commitInput(prior); +}); +map.addEventListener("keydown",e=>{ + const g=e.target.closest(".sk-src");if(!g)return; + if(!["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(e.key))return; + e.preventDefault(); + // Screen-space arrow nudges preserve anatomical orientation on every quadrant. + const source=Number(g.dataset.index),offset=(source?1:-1)*draft.stereoSpreadDegrees/2; + const point=stagePoint(draft.startAzimuthDegrees+offset); + const deltaX=e.key==="ArrowLeft"?-7:e.key==="ArrowRight"?7:0; + const deltaY=e.key==="ArrowUp"?-7:e.key==="ArrowDown"?7:0; + const next=stageAzimuth(point.x+deltaX,point.y+deltaY)-offset; + send({...draft,startAzimuthDegrees:Math.max(-360,Math.min(360,next)),moving:false}); +}); +const api={ + id:ID, + insert(target){return Boolean(window.__ARMIX_NATIVE_M2__?.insertPlugin?.(ID,target));}, + open(track,slot){ + cancelLiveTimer();pending=null;latest=null;readId="";readSentAt=0;dialDrag=null; + observedAt=0;visualAt=0;visualPhase=0;lastLiveAt=0; + drag=null;rangeEdits.clear();gestureStart.clear(); + accepted=defaults();draft=defaults(); + current={track,slot,instanceId:null}; + const s=snapshot(),id=window.__ARMIX_NATIVE_M2__?.nativeIdFor?.(track); + const fx=s?.graph?.channels?.find(x=>x.id===id)?.inserts?.[slot]; + if(native()&&(s?.admitted||s?.logical)&&fx?.catalogId===ID)current.instanceId=fx.id; + $("skChannel").textContent=String(track.name)+" · FX "+(slot+1); + root.hidden=false; + hint(native()?"READING ACCEPTED DSP":"BROWSER VISUAL ONLY · NO AUDIO"); + if(native())requestSnapshot(); + if(clock!==null)clearInterval(clock); + clock=setInterval(()=>{if(root.hidden)return; + if(native()&&!pending&&context())requestSnapshot();},250); + render(); + if(frame!==null)cancelAnimationFrame(frame); + frame=requestAnimationFrame(animate); + }, + close(){$("skClose").click();} +}; +window.ArSonMixNativeSonKu=Object.freeze(api); +})(); diff --git a/site/preview-v2/assets/mixer-section-controls.css b/site/preview-v2/assets/mixer-section-controls.css index 9131ee6e4..193d4ed4a 100644 --- a/site/preview-v2/assets/mixer-section-controls.css +++ b/site/preview-v2/assets/mixer-section-controls.css @@ -78,3 +78,101 @@ @media(max-width:900px){.command-bar{padding:0 5px;gap:4px}.command-bar .toolbar-label{display:none}.command-bar .tool{padding:4px 6px}.command-bar .toolbar-select{max-width:86px}.command-bar .sep{margin:0 1px}} + + +/* Contextual console views. One existing FX cell, no extra strip height. + All expensive effects/graph state stays mounted on the native side. */ +.command-bar .strip-view-switch{ + display:inline-flex;align-items:center;flex:none;border:1px solid #53656c; + border-radius:3px;overflow:hidden;background:#172833;height:28px; +} +.command-bar .strip-view-switch .tool{ + min-height:26px;height:26px;padding:3px 9px;border:0;border-radius:0; + font-size:10px;letter-spacing:.015em;background:transparent;color:#b9ced6; +} +.command-bar .strip-view-switch .tool+.tool{border-left:1px solid #4a5b65} +.command-bar .strip-view-switch .tool[aria-pressed="true"]{ + color:#eff9fa;background:#365765;box-shadow:inset 0 -2px #7ec5d4; +} +.command-bar .strip-view-switch .tool:disabled{opacity:.65;cursor:default} +.command-bar .mix-context{ + display:inline-flex;align-items:center;min-width:0;margin-left:9px; + padding:2px 7px;border:1px solid #435c69;border-radius:2px; + color:#9acbd9;background:#182c37;font-size:10px;font-weight:500; + letter-spacing:.03em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; +} +.command-bar:has(#sofToggle[aria-pressed="true"]) #sofToggle{ + color:#e7f6f5;background:#2b5760;border-color:#6a9aa6; +} +.console-body .strip .fx-section.is-gain-view, +.console-body .strip .fx-section.is-sof-view{ + display:flex;flex-direction:column;min-height:0;overflow:hidden; + background:linear-gradient(180deg,#21343d,#172832); +} +.console-body .strip .gain-view-body{ + min-height:0;flex:1;display:flex;flex-direction:column; + justify-content:center;align-items:center;gap:2px;padding:2px 2px 4px; +} +.console-body .strip .gain-dial{ + position:relative;display:block;flex:0 0 39px;width:39px;height:39px; + border-radius:50%;cursor:ns-resize; +} +.console-body .strip .gain-dial-face{ + display:block;position:absolute;inset:2px;border:2px solid #5c747f; + border-radius:50%;background:radial-gradient(circle at 38% 31%,#617480,#273842 65%,#15242b); + box-shadow:inset 0 1px #9aafb844,0 2px 3px #0007; +} +.console-body .strip .gain-dial-face::after{ + content:"";position:absolute;left:50%;top:4px;width:2px;height:10px; + border-radius:2px;background:#d2ecf3;box-shadow:0 0 1px #fff8; + transform-origin:1px 12px;transform:translateX(-50%) rotate(var(--gain-rotation,0deg)); +} +.console-body .strip .gain-dial input{ + position:absolute;inset:0;width:100%;height:100%;margin:0;opacity:0; + cursor:ns-resize;writing-mode:vertical-lr;direction:rtl; +} +.console-body .strip .gain-dial:focus-within{outline:2px solid #7ebccf;outline-offset:1px} +.console-body .strip .gain-readout{ + display:block;text-align:center;font-size:10px;line-height:15px; + min-width:65px;max-width:100%;padding:0 4px;border-radius:2px; + background:#102530;border:1px solid #3c606e;color:#b9e8f3; + font-variant-numeric:tabular-nums;font-weight:500;white-space:nowrap; +} +.console-body .strip .sof-view-body{ + flex:1;display:flex;align-items:center;justify-content:space-between; + min-height:0;gap:4px;padding:4px 4px 5px; +} +.console-body .strip .sof-info{display:flex;flex-direction:column;min-width:0;gap:3px} +.console-body .strip .sof-badge{ + color:#c1e5ed;font-size:9px;font-weight:500;white-space:nowrap; + overflow:hidden;text-overflow:ellipsis; +} +.console-body .strip .sof-info small{ + font-size:9px;color:#91b3c0;max-width:100%;white-space:nowrap; + overflow:hidden;text-overflow:ellipsis; +} +.console-body .strip .sof-actions{display:flex;align-items:center;gap:2px;flex:0 0 auto} +.console-body .strip .mx-sof-on-key{ + flex:0 0 27px;width:27px;height:23px;padding:0 1px; + border:1px solid #58727c;border-radius:2px;background:#27353d; + font-size:9px;font-weight:500;color:#a9bbc4;cursor:pointer; +} +.console-body .strip .mx-sof-on-key[aria-pressed="true"]{ + border-color:#598d8f;background:#2e6461;color:#e6f6ed; +} +.console-body .strip .mx-sof-on-key:disabled{opacity:.48;cursor:default} +.console-body .strip .mx-sof-on-key:focus-visible{outline:2px solid #91d5e5;outline-offset:1px} +.console-body.sends-mode .strip.audio .fader-head{ + background:#173844;border-bottom:1px solid #507481; +} +.console-body.sends-mode .strip.audio .fader-readout{color:#b3e6ef} +.console-body.sends-mode .strip.audio .fader:disabled{opacity:.42;cursor:not-allowed} +@media(max-width:900px){ + .command-bar .strip-view-switch .tool{padding:3px 5px;font-size:9px} + .command-bar .mix-context{padding:2px 4px} +} +@media(max-height:610px){ + .console-body .strip .gain-dial{flex-basis:28px;width:28px;height:28px} + .console-body .strip .gain-dial-face::after{height:7px;transform-origin:1px 9px} + .console-body .strip .sof-info small{display:none} +} diff --git a/site/preview-v2/assets/sonku-listener-top.png b/site/preview-v2/assets/sonku-listener-top.png new file mode 100644 index 000000000..658d7a889 Binary files /dev/null and b/site/preview-v2/assets/sonku-listener-top.png differ diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index 9a8a18a81..019006a77 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -42,8 +42,15 @@ + STRIP +
+ + +
+ + MAIN MIX @@ -201,7 +208,7 @@ }));}catch(error){/* Manager still works without browser storage. */} } const tracksEl=document.getElementById('tracks'),masterEl=document.getElementById('master'),info=document.getElementById('info'); -let nextId=1,nextGroup=1,tracks=[],master,preview=false,meterFrame=0,lastTick=0,clipboard=null,scenes=[],sofEnabled=false,sofTarget="Bus A",wireSourceId=1,wireEdges=[],nextWireId=1,selectedWireEdgeId=null,wireMode='send',wireAnchorId=null,wireHoverId=null,wireGesture=null,wireSuppressClick=false,pendingBusRoute=null,wireView='focus',wireSourcePinned=false,wireIntent=false; +let nextId=1,nextGroup=1,tracks=[],master,preview=false,meterFrame=0,lastTick=0,clipboard=null,scenes=[],stripView="fx",sofEnabled=false,sofTarget="Bus A",sofTargetId=null,wireSourceId=1,wireEdges=[],nextWireId=1,selectedWireEdgeId=null,wireMode='send',wireAnchorId=null,wireHoverId=null,wireGesture=null,wireSuppressClick=false,pendingBusRoute=null,wireView='focus',wireSourcePinned=false,wireIntent=false; const clone=x=>JSON.parse(JSON.stringify(x)); const selection=()=>tracks.concat(master).filter(t=>t.selected); const make=(name,kind,color)=>{ @@ -321,7 +328,54 @@ say(t.name+' · FX reorder undone · GUI reference'); return true; } + +/* UI context only; FX/DSP slots remain in the session when the rack is hidden. */ +function sectionGain(t){ + const value=Math.max(-24,Math.min(24,Number(t.trim)||0)); + const nativeUnavailable=!!window.__JUCE__?.backend&&!t.nativeGainAvailable; + return '
'+ + 'GINPUT GAIN
'+ + '
'+ + ''+(nativeUnavailable?'NATIVE PENDING':formatDb(value)+' dB')+'
'; +} +/* SOF is a contextual UI view of an explicit existing EdgeId, not a new graph. */ +function sectionSof(t){ + // SOF is a view of ONE selected target WIRE, not a parallel audio graph. + const dest=selectedSofDestination(); + const edge=dest?wireFor(t.id,dest.id):null; + const send=edge&&edge.kind==='send'?edge:null; + const native=!!window.__JUCE__?.backend; + const tap=send?.nativeTap==='PRE_FADER'?'preFader': + send?.nativeTap==='POST_FADER'?'postFader': + send?.mode==='split'?'preFx':'postFader'; + const visual=!send?'idle':tap==='preFader'||tap==='preFx'?'pre':'post'; + const badge=!edge?'NO SEND':edge.kind!=='send'?'PRIMARY OUT': + tap==='preFader'?'PRE-FADER':tap==='preFx'?'PRE-FX':'POST-FADER'; + const status=!dest?'Select a BUS/FX':!edge?'Patch with WIRE': + !send?'PRIMARY ROUTE · no send level': + send.sendEnabled===false?'OFF · saved '+wireDbText(send.levelDb): + 'LEVEL '+wireDbText(send.levelDb); + const editable=!!send&&(!native||t.nativeTapAvailable===true); + const onEditable=!!send&&(!native||t.nativeSendAvailable===true); + const enabled=!!send&&send.sendEnabled!==false; + return '
'+ + '
↗SEND TO '+escapeHtml(sofTarget||'—')+'
'+ + '
'+badge+''+ + ''+escapeHtml(status)+'
'+ + '
'+ + '
'; +} function sectionFx(t){ + if(sofEnabled&&t.kind==='audio')return sectionSof(t); + if(stripView==='gain'&&t.kind==='audio')return sectionGain(t); ensureFxInsertIds(t); const used=t.fx.map((name,i)=>({name,i})).filter(x=>x.name!=='None'); const first=t.fx.findIndex(x=>x==='None'); @@ -601,7 +655,12 @@ let label='',status=''; if(isSource){label='SOURCE';status='⇢ '+wireOutgoingCount(t.id)+' OUT';} else if(t.kind==='master'){label='MAIN';status=source&&wireFor(source.id,master.id)?'DIRECT ON':'DIRECT OFF';} - else if(edge){label='IN ← CH'+String(source.id).padStart(2,'0');status=edge.mode==='split'?'PRE FX':'POST FADER';} + else if(edge){ + label='IN ← CH'+String(source.id).padStart(2,'0'); + status=edge.nativeTap==='PRE_FADER'?'PRE FADER': + edge.nativeTap==='POST_FADER'?'POST FADER': + edge.mode==='split'?'PRE FX':'POST FADER'; + } else if(legacy){label='LEGACY';status='SEND ACTIVE';} else if(t.kind==='bus')label='BUS'; else if(t.kind==='fx')label='FX RETURN'; @@ -697,7 +756,7 @@ return '
'+(isSend?'SEND ':'')+formatDb(value)+' dB
' +'
' +'
'+(t.format==='mono'?'':'
')+'
'+vuScale+'
' - +'
' + +'
' +'
'+gainScale+'
'; } function strip(t){ @@ -766,8 +825,16 @@ if(tracksEl.style?.setProperty)tracksEl.style.setProperty('--bank-columns',String(capacity)); // Release observers for detached bank DOM; never accumulate orphan lanes. meterObserver?.disconnect();meterGeometry=new WeakMap(); + updateSofTargets(); // Resolve selected EdgeId destination before painting strips. tracksEl.innerHTML=bankTracks.map(strip).join(''); - updateSofTargets(); + const gainBtn=document.getElementById('gainView'),fxBtn=document.getElementById('fxView'); + for(const [button,value] of [[gainBtn,'gain'],[fxBtn,'fx']]){ + button.disabled=sofEnabled; + button.setAttribute('aria-pressed',String(stripView===value&&!sofEnabled)); + button.classList.toggle('active',stripView===value&&!sofEnabled); + } + const context=document.getElementById('mixContext'); + if(context)context.textContent=sofEnabled?'SEND MIX → '+sofTarget:'MAIN MIX'; masterEl.innerHTML=strip(master); document.getElementById('viewport').scrollLeft=0; document.getElementById('bankPrev').disabled=count<=1; @@ -805,33 +872,45 @@ btn.classList.toggle('active',compact);btn.setAttribute('aria-pressed',String(compact)); return density; } +function selectedSofDestination(){ + // A stable local display ID, never an audio-graph identity or a bus name. + // Native ChannelId stays a precise decimal string in the bridge. + return tracks.find(t=>t.id===sofTargetId&&(t.kind==='bus'||t.kind==='fx'))||null; +} function updateSofTargets(){ - const el=document.getElementById('sofTarget'),choices=tracks.filter(t=>t.kind==='bus'||t.kind==='fx').map(t=>t.name); - const target=choices.includes(sofTarget)?sofTarget:choices[0]||''; - sofTarget=target; - const html=choices.map(name=>'').join(''); - if(el.innerHTML!==html)el.innerHTML=html;el.value=sofTarget; + const el=document.getElementById('sofTarget'); + const choices=tracks.filter(t=>t.kind==='bus'||t.kind==='fx'); + let target=selectedSofDestination(); + if(!target){ + const named=choices.filter(t=>t.name===sofTarget); + target=named.length===1?named[0]:choices[0]||null; + } + sofTargetId=target?.id??null;sofTarget=target?.name||''; + const html=choices.map(t=>'').join(''); + if(el.innerHTML!==html)el.innerHTML=html; + el.value=target?String(target.id):''; } function getSofIndex(t){return t.sendSlots.findIndex((slot,i)=>(i===t.activeSend?t.send:slot.send)===sofTarget);} -function getSofLevel(t){const dest=tracks.find(x=>x.name===sofTarget); - const edge=dest&&wireFor(t.id,dest.id);return edge?edge.levelDb:-60;} +function getSofEdge(t){ + const dest=selectedSofDestination(); + const edge=dest&&wireFor(t.id,dest.id); + return edge&&edge.kind==='send'?edge:null; +} +function getSofLevel(t){const edge=getSofEdge(t);return edge?edge.levelDb:-60;} function setSofLevel(t,newLevel){ - const dest=tracks.find(x=>x.name===sofTarget&&x.id!==t.id); + const dest=selectedSofDestination(); if(!dest||t.kind==='master')return false; const level=Math.round(Math.max(-60,Math.min(6,newLevel))*10)/10; - const edge=wireFor(t.id,dest.id); - if(!edge&&level<=-60)return true; - const ops=level<=-60?[{type:'REMOVE',sourceId:t.id,edgeId:edge.id}]: - edge?[{type:'GAIN',sourceId:t.id,edgeId:edge.id,levelDb:level}]: - [{type:'CONNECT',sourceId:t.id,destId:dest.id}, - {type:'GAIN',sourceId:t.id,edgeId:nextWireId,levelDb:level}]; - return wireGraphCommit(ops,{record:false}); + const edge=getSofEdge(t); + // Never auto-patch or remove a WIRE at minimum send level. + if(!edge)return false; + return wireGraphCommit([{type:'GAIN',sourceId:t.id,edgeId:edge.id,levelDb:level}],{record:false}); } function toggleSof(force){ sofEnabled=typeof force==='boolean'?force:!sofEnabled; - if(sofEnabled&&!sofTarget){sofEnabled=false;say('Create a Bus or FX Return to use Sends on Faders');return;} - // PFL is visible in both workspaces; changing fader context must not - // silently clear the channel's browser-only cue selection. + updateSofTargets(); + if(sofEnabled&&!selectedSofDestination()){sofEnabled=false;say('Create a Bus or FX Return to use Sends on Faders');return;} + // PFL visual selection remains stable when switching between MAIN and SOF. const btn=document.getElementById('sofToggle');btn.classList.toggle('active',sofEnabled); btn.setAttribute('aria-pressed',String(sofEnabled));document.querySelector('.console-body').classList.toggle('sends-mode',sofEnabled); render();say(sofEnabled?'SENDS ON FADERS: adjusting '+sofTarget+' send levels · main faders protected':'MAIN MIX: faders control primary channel level'); @@ -1336,14 +1415,23 @@ const src=tracks.find(t=>t.id===p.src),dst=tracks.concat(master).find(t=>t.id===p.dst); if(!src||!dst){panel.hidden=true;return;} const edge=info.edge,key=p.src+':'+p.dst; + const native=!!window.__JUCE__?.backend; + const tapValue=edge?.nativeTap==='PRE_FADER'?'split': + edge?.nativeTap==='POST_FADER'?'send':edge?.mode; + const tapEditable=!native||(src.nativeTapAvailable===true&& + edge?.kind==='send'&&['PRE_FADER','POST_FADER'].includes(edge.nativeTap)); const controls=edge? - '
'+ + '
'+ ''+ ''+edge.levelDb+' dB'+ ''+ - ''+ + ''+ '
': '
Managed by existing '+escapeHtml(info.kind.toUpperCase())+' routing. No duplicate WIRE edge.
'; panel.innerHTML=''+escapeHtml(wireWsLabel(p.src))+' → '+escapeHtml(wireWsLabel(p.dst))+''+ @@ -1948,7 +2036,16 @@ if(label)label.textContent=panLabel(value); if(event.type==='change')say(t.name+' pan '+panLabel(value)); } - else if(field==='trim'){t.trim=Number(el.value);if(el.style?.setProperty)el.style.setProperty('--range-pct',rangePct(t.trim,-24,24)+'%');const readout=el.closest('.trim-section')?.querySelector('.trim-value');if(readout)readout.textContent=formatDb(t.trim);if(event.type==='change')say(t.name+' digital trim '+formatDb(t.trim)+' dB');} + else if(field==='trim'){ + if(window.__JUCE__?.backend){say('Native digital gain not admitted');return;} + t.trim=Math.max(-24,Math.min(24,Math.round(Number(el.value)*10)/10)); + if(el.style?.setProperty)el.style.setProperty('--range-pct',rangePct(t.trim,-24,24)+'%'); + const section=el.closest('.gain-view-body,.trim-section'); + const readout=section?.querySelector('.gain-readout,.trim-value'); + if(readout)readout.textContent=formatDb(t.trim)+' dB'; + section?.querySelector('.gain-dial')?.style.setProperty('--gain-rotation',(t.trim*5.625).toFixed(2)+'deg'); + if(event.type==='change')say(t.name+' digital trim '+formatDb(t.trim)+' dB · reference only'); + } else if(field==='sendLevel'){t.sendLevel=Number(el.value);if(el.style?.setProperty)el.style.setProperty('--range-pct',rangePct(t.sendLevel,-60,6)+'%');el.nextElementSibling.textContent=formatDb(t.sendLevel);} else if(field==='sendPan'){t.sendPan=Number(el.value);el.nextElementSibling.textContent=t.sendPan===0?'C':t.sendPan<0?'L'+Math.abs(t.sendPan):'R'+t.sendPan;} else if(field==='activeSend'){const slot=Number(el.value.slice(1))-1;if(slot<0||slot>=16)return;openSendSlot(t,slot);refreshStrip(t);say(t.name+' · selected Send '+(slot+1));return;} @@ -2214,6 +2311,26 @@ if(a==='openPlugin'){openFastPicker(t,Number(btn.dataset.slot),btn);return;} if(a==='removeFx'){if(deferNativeFxIntent('Remove FX insert'))return;const i=Number(btn.dataset.slot);t.fx[i]='None';t.slotBypass[i]=false;if(t.fxInsertIds)t.fxInsertIds[i]=null;fxReorderUndo=null;refreshStrip(t);say(t.name+' · cleared FX insert '+(i+1));return;} if(a==='slotPower'){if(deferNativeFxIntent('FX insert bypass'))return;const slot=Number(btn.dataset.slot);if(t.fx[slot]==='None'){say(t.name+': choose an effect before toggling bypass');return;}t.slotBypass[slot]=!t.slotBypass[slot];refreshStrip(t);say(t.name+': FX '+(slot+1)+(t.slotBypass[slot]?' bypassed':' enabled'));return;} + if(a==='sofOn'){ + if(!sofEnabled||t.kind!=='audio')return; + if(window.__JUCE__?.backend)return; // native bridge owns accepted send gate + const edge=getSofEdge(t); + if(!edge)return; + edge.sendEnabled=edge.sendEnabled===false; + refreshStrip(t);say(t.name+' → '+sofTarget+' send '+(edge.sendEnabled?'ON':'OFF')+' · GUI reference only'); + return; + } + if(a==='sofTap'){ + if(!sofEnabled||t.kind!=='audio')return; + if(window.__JUCE__?.backend){say('Native WIRE tap change requires PCM ACK');return;} + const edge=getSofEdge(t); + if(!edge){say('Connect a parallel WIRE to '+sofTarget+' before changing its tap');return;} + const next=edge.mode==='split'?'send':'split'; + if(!wireGraphCommit([{type:'MODE',sourceId:t.id,edgeId:edge.id,mode:next}]))return; + refreshStrip(t); + say(t.name+' → '+sofTarget+' · '+(next==='split'?'PRE-FX':'POST-FADER')+' · reference graph'); + return; + } if(a==='eq')t.eq=!t.eq; else if(a==='fxOn'){if(deferNativeFxIntent('FX chain bypass'))return;t.fxOn=!t.fxOn;} else if(a==='pre'){t.pre=!t.pre;syncActiveSend(t);} @@ -2230,6 +2347,7 @@ return; } else if(['mute','solo','mon','phase'].includes(a)){ + t[a]=!t[a]; if(t.group&&(a==='mute'||a==='solo')){ tracks.filter(other=>other.group===t.group&&other.id!==t.id).forEach(other=>{other[a]=t[a];refreshStrip(other);}); @@ -2242,7 +2360,28 @@ if(e.target.closest?.('.wire-gain,.wire-pot')){ const el=e.target.closest('.wire-pot')?.querySelector('.wire-gain')||e.target.closest('.wire-gain');el.value='0';handleField({target:el,type:'change'});return; } - if(e.target.classList.contains('fader')){t.level=0;refreshStrip(t);say(t.name+' fader reset to 0.0 dB');} + const dial=e.target.closest?.('.gain-dial'); + if(dial){ + const gain=dial.querySelector('[data-field="trim"]'); + if(!gain||gain.disabled)return; + // Same field path as a knob gesture: native ACK, no UI-only gain mutation. + gain.value='0';gain.dispatchEvent(new Event('input',{bubbles:true})); + gain.dispatchEvent(new Event('change',{bubbles:true})); + if(!window.__JUCE__?.backend)say(t.name+' digital input gain → unity (0.0 dB)'); + return; + } + if(e.target.classList.contains('fader')){ + const send=sofEnabled&&t.kind==='audio'; + if(send&&!getSofEdge(t)){say('NO SEND · patch one WIRE first');return;} + // Never mutate t.level directly: in SOF the physical fader belongs to + // the selected EdgeId, not MAIN. Native bridge owns the accepted write. + const fader=e.target; + if(fader.disabled)return; + fader.value='0';fader.dispatchEvent(new Event('input',{bubbles:true})); + fader.dispatchEvent(new Event('change',{bubbles:true})); + if(!window.__JUCE__?.backend)say(t.name+(send?' SEND':' MAIN')+' fader → 0.0 dB'); + return; + } if(e.target.classList.contains('center-pan')){t.pan=0;refreshStrip(t);say(t.name+' pan centered');} if(e.target.closest('.footer-label,.strip-identity-top'))openChannelIdentity(t,e.target); }); @@ -2720,8 +2859,28 @@ document.getElementById('routeParallel').addEventListener('click',()=>commitRouteChoice('parallel')); document.getElementById('routeChoiceClose').addEventListener('click',closeRouteChoice); document.getElementById('wireMaster').addEventListener('click',toggleDirectMain); +for(const [id,value] of [['gainView','gain'],['fxView','fx']]){ + document.getElementById(id).addEventListener('click',()=>{ + if(sofEnabled)return; + if(value==='gain'&&window.__JUCE__?.backend&& + !tracks.some(t=>t.kind==='audio'&&t.nativeGainAvailable===true)){ + say('INPUT GAIN unavailable · no channel has an acknowledged native gain stage'); + return; + } + // View selection is presentation-only; the DSP insert chain stays resident. + stripView=value;render(); + say(value==='gain'?'Digital INPUT GAIN · each knob follows accepted channel readback': + 'FX RACK · existing inserts preserved'); + }); +} document.getElementById('sofToggle').addEventListener('click',()=>toggleSof()); -document.getElementById('sofTarget').addEventListener('change',()=>{sofTarget=document.getElementById('sofTarget').value;render();say('Sends target: '+sofTarget);}); +document.getElementById('sofTarget').addEventListener('change',()=>{ + const id=Number(document.getElementById('sofTarget').value); + const target=tracks.find(t=>t.id===id&&(t.kind==='bus'||t.kind==='fx')); + if(!target){updateSofTargets();say('Invalid SEND target · selection unchanged');return;} + sofTargetId=target.id;sofTarget=target.name; + render();say('SEND MIX → '+sofTarget+' · MAIN faders protected'); +}); document.getElementById('addTrack').addEventListener('click',()=>{ const n=tracks.filter(t=>t.kind==='audio').length+1,t=make('Track '+n,'audio',COLORS[(n-1)%COLORS.length]);const firstBus=tracks.findIndex(x=>x.kind==='bus');tracks.splice(firstBus<0?tracks.length:firstBus,0,t); if(!wireGraphCommit([{type:'CONNECT',sourceId:t.id,destId:master.id}],{record:false})){tracks=tracks.filter(x=>x.id!==t.id);return;}revealTrack(t);say('Added '+t.name+' → MAIN · reference only'); @@ -2783,7 +2942,7 @@ if(x.send===old)x.send=name; x.sendSlots.forEach(slot=>{if(slot.send===old)slot.send=name;}); }); - if(sofTarget===old)sofTarget=name; + if(sofTargetId===t.id)sofTarget=name; closeChannelIdentity();render();say('Channel identity updated · '+name+' · routing references preserved'); } document.getElementById('identityClose').addEventListener('click',closeChannelIdentity); diff --git a/src/ArSonWindowChrome.h b/src/ArSonWindowChrome.h index e9c397ee1..ead5516d7 100644 --- a/src/ArSonWindowChrome.h +++ b/src/ArSonWindowChrome.h @@ -6,7 +6,7 @@ namespace armix::ui { // Only the main JUCE mixer window uses this caption. No WebView2 command // round trips for minimise, maximise, close, drag or OS window resizing. -class MixerCaptionButton final : public juce::Button +class MixerCaptionButton final : public juce::Button, private juce::Timer { public: explicit MixerCaptionButton (int kind) : Button ("ArSonMiX window control"), kind_ (kind) @@ -36,16 +36,19 @@ class MixerCaptionButton final : public juce::Button void paintButton (juce::Graphics& g, bool over, bool down) override { - // Native window caption: semantic, low-glare hover followed by a - // clearly lit pressed face. No animations, timers, CSS or WebView2. - // Keep the existing 34 px click target and original SVG geometry. - if (over || down) + // The caption action would normally run on mouse-up in the SAME + // message-loop turn, immediately minimising/closing before JUCE can + // paint its bright down state. Keep the accepted pressed colour + // visible for one bounded 160 ms feedback interval before dispatch. + // Inactive/hover appearance and original SVG geometry are unchanged. + const bool pressed = down || pendingClick_; + if (over || pressed) { const auto palette = paletteFor (kind_); const auto face = getLocalBounds().toFloat().reduced (2.0f, 3.0f); - g.setColour (down ? palette.pressedFace : palette.hoverFace); + g.setColour (pressed ? palette.pressedFace : palette.hoverFace); g.fillRoundedRectangle (face, 3.0f); - g.setColour (down ? palette.pressedEdge : palette.hoverEdge); + g.setColour (pressed ? palette.pressedEdge : palette.hoverEdge); g.drawRoundedRectangle (face.reduced (0.5f), 3.0f, 1.0f); } if (hasKeyboardFocus (true)) @@ -57,8 +60,8 @@ class MixerCaptionButton final : public juce::Button const bool restoring = kind_ == juce::DocumentWindow::maximiseButton && parent != nullptr && parent->isFullScreen(); auto* image = restoring - ? (down && pressedRestoreIcon_ != nullptr ? pressedRestoreIcon_.get() : restoreIcon_.get()) - : (down && pressedIcon_ != nullptr ? pressedIcon_.get() : icon_.get()); + ? (pressed && pressedRestoreIcon_ != nullptr ? pressedRestoreIcon_.get() : restoreIcon_.get()) + : (pressed && pressedIcon_ != nullptr ? pressedIcon_.get() : icon_.get()); if (image != nullptr) { const auto b = getLocalBounds().toFloat(); @@ -67,6 +70,32 @@ class MixerCaptionButton final : public juce::Button } } + void internalClickCallback (const juce::ModifierKeys& modifiers) override + { + // JUCE's Button::mouseUp invokes the document window listener + // immediately, before the down-state repaint is serviced. Keep the + // exact native button command but give the operator a perceptible + // lit-press frame first. Repeated clicks cannot queue duplicate + // minimise/maximise/quit commands. + if (!isEnabled() || pendingClick_) + return; + pendingModifiers_ = modifiers; + pendingClick_ = true; + repaint(); + startTimer (160); // one-shot JUCE message-thread feedback; no audio involvement + } + + void timerCallback() override + { + stopTimer(); + pendingClick_ = false; + repaint(); + // Dispatch through JUCE's original DocumentWindow listener *only* + // after the pressed face has had time to paint. The command may + // destroy this button (Close), so do nothing after this call. + juce::Button::internalClickCallback (pendingModifiers_); + } + private: struct CaptionPalette { @@ -100,6 +129,8 @@ class MixerCaptionButton final : public juce::Button return {}; } int kind_; + bool pendingClick_ = false; + juce::ModifierKeys pendingModifiers_; std::unique_ptr icon_, restoreIcon_, pressedIcon_, pressedRestoreIcon_; }; diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 50670cdf7..65baae3d3 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -2296,6 +2296,15 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::diagnostics::Route::normal)return false; return dryRoutingLab_.setNativeWireGain(epoch,rev,roster,source,edge,gain); } + bool setNativeWireEnabled(std::uint64_t epoch,std::uint64_t rev, + std::uint64_t roster,armix::mixer::ChannelId source, + std::uint64_t edge,bool enabled) noexcept { + if(independent_.active()||!attached_||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.setNativeWireEnabled(epoch,rev,roster,source,edge,enabled); + } bool setNativeInputMix(std::uint64_t epoch,std::uint64_t rev, armix::mixer::ChannelId id,float gain,float pan) noexcept { if(independent_.active()||!directFence_.permitted()|| @@ -2304,6 +2313,14 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::diagnostics::Route::normal)return false; return dryRoutingLab_.setNativeInputMix(epoch,rev,id,gain,pan); } + bool setNativeInputGain(std::uint64_t epoch,std::uint64_t rev, + armix::mixer::ChannelId id,float gain) noexcept { + if(independent_.active()||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.setNativeInputGain(epoch,rev,id,gain); + } bool setNativeInputMuteSolo(std::uint64_t epoch,std::uint64_t rev, armix::mixer::ChannelId id,bool mute,bool solo) noexcept { if(independent_.active()||!directFence_.permitted()|| diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 8390fa7b2..cc6587749 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2143,6 +2143,24 @@ class LiveDryRoutingLab final { nativeControlDirty_=true; return true; } + // Real ChannelId pre-insert digital input trim. Safe 64-sample DSP ramp; + // no new graph, callback, plugin instance or WIRE edit. + bool setNativeInputGain(std::uint64_t epochValue,std::uint64_t revision, + armix::mixer::ChannelId id,float gain) noexcept { + if(!channelIdPhysicalPcmActive()|| + nativeAccepted_.deviceEpoch!=epochValue||epochValue!=epoch()|| + revision!=nativeAccepted_.pcmRevision|| + !std::isfinite(gain)||gain<0.f||gain>16.f)return false; + const auto* channel=nativeAccepted_.graph.roster.find(id); + if(!channel||channel->role!=armix::mixer::ChannelRole::input)return false; + if(!nativePublisher_.setChannelInputGain(epochValue,revision,id,gain))return false; + if(!nativeAccepted_.graph.roster.rememberLiveInputGain(id,gain)) { + topologyFault_.store(true,std::memory_order_release); + return false; + } + nativeControlDirty_=true; + return true; + } bool setNativeInputMuteSolo(std::uint64_t epochValue,std::uint64_t revision, armix::mixer::ChannelId id, bool mute,bool solo) noexcept { @@ -2225,6 +2243,29 @@ class LiveDryRoutingLab final { } return false; } + // SEND ON/OFF changes only the selected existing EdgeId audio gate. + // A 64-sample PCM ramp preserves the saved level/tap/PAN and WIRE. + bool setNativeWireEnabled(std::uint64_t ep,std::uint64_t graphRev, + std::uint64_t rosterRev,armix::mixer::ChannelId source, + std::uint64_t edgeId,bool enabled) noexcept { + if(!channelIdPhysicalPcmActive()||!ready()||ep!=epoch()|| + graphRev!=nativeAccepted_.pcmRevision|| + rosterRev!=nativeAccepted_.graph.roster.revision())return false; + const auto* row=nativeAccepted_.graph.roster.find(source); + if(!row||!edgeId)return false; + for(const auto& edge:row->sends) + if(edge.edgeId==edgeId&&!edge.primaryOutput){ + if(!nativePublisher_.setWireEnabled(ep,graphRev,source,edgeId,enabled)) + return false; + if(!nativeAccepted_.graph.roster.rememberLiveSendEnabled(source,edgeId,enabled)){ + topologyFault_.store(true,std::memory_order_release); + return false; + } + nativeControlDirty_=true; + return true; + } + return false; + } int nativePcmLatencySamples() const noexcept { return channelIdPhysicalPcmActive()? nativePublisher_.latencySamples(epoch(),nativeAccepted_.pcmRevision):0; @@ -2575,8 +2616,10 @@ class LiveDryRoutingLab final { "NATIVE_SET_PRIMARY_OUT", "NATIVE_APPLY_WIRE_TRANSACTION", "NATIVE_SET_WIRE_GAIN", + "NATIVE_SET_SEND_ENABLED", "NATIVE_SET_PROCESSING_FORMAT", "NATIVE_SET_CHANNEL_MIX", + "NATIVE_SET_INPUT_GAIN", "NATIVE_SET_CHANNEL_MUTE_SOLO", "NATIVE_SET_BUS_MUTE_SOLO", "NATIVE_LOAD_INSERT","NATIVE_REMOVE_INSERT","NATIVE_MOVE_INSERT", @@ -2609,6 +2652,7 @@ class LiveDryRoutingLab final { ?"STEREO":"MONO"); if(const auto* accepted=nativeAccepted_.graph.roster.find(ch.id)) { row->setProperty("fader",static_cast(accepted->faderLinear)); + row->setProperty("inputGain",static_cast(accepted->inputGainLinear)); row->setProperty("pan",static_cast(accepted->pan)); row->setProperty("mute",accepted->mute); row->setProperty("solo",accepted->solo); @@ -2673,6 +2717,7 @@ class LiveDryRoutingLab final { std::to_string(send.destination.value))); edge->setProperty("preFader",send.preFader); edge->setProperty("gain",static_cast(send.gain)); + edge->setProperty("enabled",send.enabled); edge->setProperty("pan",static_cast(send.pan)); sends.add(juce::var(edge.release())); } @@ -2693,6 +2738,7 @@ class LiveDryRoutingLab final { static_cast(accepted.gainLinear)); edge->setProperty("tap",accepted.preFader?"PRE_FADER":"POST_FADER"); edge->setProperty("primaryOutput",accepted.primaryOutput); + edge->setProperty("enabled",accepted.enabled); edges.add(juce::var(edge.release())); } state->setProperty("edges",juce::var(edges)); diff --git a/src/Main.cpp b/src/Main.cpp index 7f1e637eb..8cf803a63 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -338,9 +338,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // synchronous native controls with JUCE's existing resize constrainer. setLookAndFeel (&mixerCaption_); setUsingNativeTitleBar (false); - // DocumentWindow creates its caption buttons before ConsoleWindow - // installs its own LookAndFeel. Recreate them explicitly from the - // approved native SVG factory; never leave stock JUCE buttons here. + // Recreate JUCE caption buttons after our own SVG LookAndFeel exists. setTitleBarButtonsRequired (allButtons, false); setTitleBarHeight (31); #else @@ -390,14 +388,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr { juce::DocumentWindow::activeWindowStatusChanged(); #if defined(_WIN32) - // JUCE disables DocumentWindow caption buttons when isActiveWindow() - // is false. WebView2 has its own child HWND/focus lifetime; this can - // temporarily report the mixer as inactive even while its native - // caption is visible and the user is clicking its controls. - // Windows caption commands must remain interactable on an inactive - // window: the first pointer click can activate it and perform the - // requested minimise/maximise/close action. - // No timers, synthetic clicks, forced foreground or WebView roundtrip. + // WebView2 child-HWND focus must not disable the actual native + // minimize/maximize/close buttons while the mixer is visible. for (auto* control : { getMinimiseButton(), getMaximiseButton(), getCloseButton() }) if (control != nullptr) control->setEnabled (true); @@ -531,6 +523,13 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } pendingNativeHarmony_; juce::String lastNativeHarmonyRequest_,lastNativeHarmonyInstance_; juce::String lastNativeHarmonyEpoch_,lastNativeHarmonyRevision_; + struct PendingNativeSonKu { + armix::mixer::LiveChannelFxGraph::InstanceLease owner; + juce::String request,channelId,deviceEpoch,revision,instanceId; + juce::uint32 started=0; + } pendingNativeSonKu_; + juce::String lastNativeSonKuRequest_,lastNativeSonKuInstance_; + juce::String lastNativeSonKuEpoch_,lastNativeSonKuRevision_; struct PendingNativeThrow { armix::mixer::LiveChannelFxGraph::InstanceLease owner; juce::String request,channelId,deviceEpoch,revision,instanceId; @@ -2983,6 +2982,88 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr "arMixBuiltinCompAck",juce::var(ack.release())); } + // SonKu Native FX: one editor target = exact ChannelId/slot/instance/epoch. + // Snapshot reads accepted CONTROL settings only; the single atomically + // published angle is observation, never another audio motion clock. + void emitNativeSonKuSnapshot(const juce::String& request, + const juce::String& channelId,const juce::String& epoch, + const juce::String& revision,const juce::String& instanceId, + armix::builtin_fx::SonKuSpatialProcessor* 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",2); + reply->setProperty("status",processor?"ACCEPTED":"REJECTED"); + if(processor) { + const auto s=processor->acceptedSettings(); + auto values=std::make_unique(); + values->setProperty("startAzimuthDegrees",s.startAzimuthDegrees); + values->setProperty("revolutionSeconds",s.revolutionSeconds); + values->setProperty("stereoSpreadDegrees",s.stereoSpreadDegrees); + values->setProperty("spatialMix",s.spatialMix); + values->setProperty("outputTrim",s.outputTrim); + values->setProperty("moving",s.moving); + values->setProperty("clockwise",s.clockwise); + values->setProperty("spacePreset",s.spacePreset); + values->setProperty("sourceDistanceMeters",s.sourceDistanceMeters); + values->setProperty("roomAmount",s.roomAmount); + values->setProperty("ambience",s.ambience); + reply->setProperty("settings",juce::var(values.release())); + reply->setProperty("observedAzimuthDegrees", + processor->observedAzimuthDegrees()); + if(epoch=="0" && instanceId==lastLogicalFxInstance_ && + revision==lastLogicalFxRevision_) + reply->setProperty("appliedRequestId",lastLogicalFxRequest_); + else if(instanceId==lastNativeSonKuInstance_ && + epoch==lastNativeSonKuEpoch_ && + revision==lastNativeSonKuRevision_) + reply->setProperty("appliedRequestId",lastNativeSonKuRequest_); + } else reply->setProperty("error","SONKU_INSTANCE_OR_REVISION_UNAVAILABLE"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinSonKuSnapshot",juce::var(reply.release())); + } + + void servicePendingNativeSonKu() { + if(!pendingNativeSonKu_.owner)return; + auto* processor=dynamic_cast( + pendingNativeSonKu_.owner->processor.get()); + if(!processor){pendingNativeSonKu_={};return;} + armix::builtin_fx::SonKuSpatialProcessor::Completion result{}; + const bool complete=processor->pollCompletion(result); + if(!complete && juce::Time::getMillisecondCounter()- + pendingNativeSonKu_.started<3000u)return; + const auto request=pendingNativeSonKu_.request; + bool applied=complete&&result.applied&&result.requestId!=0 && + request=="sonku-"+juce::String(std::to_string(result.requestId)); + const auto snap=approvedNativeSnapshot(); + const auto device=snap.getProperty("device",{}); + const auto graph=snap.getProperty("graph",{}); + applied=applied&&pendingNativeSonKu_.deviceEpoch== + device.getProperty("epoch","").toString()&& + pendingNativeSonKu_.revision== + graph.getProperty("revision","").toString(); + if(applied) { + lastNativeSonKuRequest_=request; + lastNativeSonKuInstance_=pendingNativeSonKu_.instanceId; + lastNativeSonKuEpoch_=pendingNativeSonKu_.deviceEpoch; + lastNativeSonKuRevision_=pendingNativeSonKu_.revision; + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("channelId",pendingNativeSonKu_.channelId); + ack->setProperty("deviceEpoch",pendingNativeSonKu_.deviceEpoch); + ack->setProperty("graphRevision",pendingNativeSonKu_.revision); + ack->setProperty("instanceId",pendingNativeSonKu_.instanceId); + ack->setProperty("status",applied?"APPLIED":"REJECTED"); + ack->setProperty("errorCode",applied?"NONE":"SONKU_EDIT_NOT_APPLIED_OR_STALE"); + pendingNativeSonKu_={}; + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinSonKuAck",juce::var(ack.release())); + } + // One channel/slot/epoch/revision-bound Harmony state. No browser DSP. void emitNativeHarmonySnapshot(const juce::String& request, const juce::String& channelId,const juce::String& epoch, @@ -4025,6 +4106,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action == "routingNativeFxInsertBypass" || action == "routingFxRackBypass" || action == "nativeEqSetBand" || action == "nativeCompSet" || + action == "nativeSonKuSet" || action == "nativeThrowSet" || action == "nativeThrowTrigger" || action == "nativeThrowTempoSource")) { @@ -4510,6 +4592,97 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return; } + // 8D-SonKu typed settings; ordinary native FX lease and PCM mailbox. + if(action=="nativeSonKuSnapshot"||action=="nativeSonKuSet") { + const auto fxRequest=armix::builtin_fx::NativeFxControlRequest::parse( + args,LiveDryRoutingLab::maxFxPerLane); + const auto& rawChannel=fxRequest.rawChannel; + const auto& rawEpoch=fxRequest.rawEpoch; + const auto& rawRevision=fxRequest.rawRevision; + const auto& rawInstance=fxRequest.rawInstance; + const auto& request=fxRequest.request; + const int slot=fxRequest.slot; + const auto ch=fxRequest.channel,ep=fxRequest.epoch,rev=fxRequest.revision; + const bool valid=fxRequest.valid,unbound=fxRequest.unbound; + armix::session::StoredInsert offlineInsert; + auto offline=unbound?openLogicalBuiltinFx(args,offlineInsert, + armix::builtin_fx::SonKuSpatialProcessor::catalogIdentity):nullptr; + auto owner=valid&&!unbound?engine_.leaseNativeVst3Editor(ep,rev, + armix::mixer::ChannelId{ch},static_cast(slot), + rawInstance.toString()): + armix::mixer::LiveChannelFxGraph::InstanceLease{}; + auto* p=dynamic_cast( + unbound?offline.get():owner?owner->processor.get():nullptr); + if(action=="nativeSonKuSnapshot") { + emitNativeSonKuSnapshot(request,rawChannel.toString(), + rawEpoch.toString(),rawRevision.toString(),rawInstance.toString(),p); + return; + } + const auto values=args.getProperty("settings",{}); + armix::sonku::Settings settings{}; + auto number=[&values](const char* key,float& dest) { + const auto v=values.getProperty(key,{}); + if(!v.isDouble()&&!v.isInt())return false; + const double n=static_cast(v); + if(!std::isfinite(n) || n>1.0e6 || n< -1.0e6)return false; + dest=static_cast(n); + return std::isfinite(dest); + }; + const auto moving=values.getProperty("moving",{}); + const auto clockwise=values.getProperty("clockwise",{}); + const bool parameters=values.isObject() && + number("startAzimuthDegrees",settings.startAzimuthDegrees) && + number("revolutionSeconds",settings.revolutionSeconds) && + number("stereoSpreadDegrees",settings.stereoSpreadDegrees) && + number("spatialMix",settings.spatialMix) && + number("outputTrim",settings.outputTrim) && + moving.isBool()&&clockwise.isBool(); + if(parameters){settings.moving=static_cast(moving); + settings.clockwise=static_cast(clockwise);} + // Optional v2 fields preserve legacy v1 clients and old sessions. + // Typed native intent remains bounded and validated before SPSC. + const auto preset=values.getProperty("spacePreset",{}); + bool acousticParameters=true; + if(!preset.isVoid()){ + if(!preset.isInt())acousticParameters=false; + else settings.spacePreset=static_cast(preset); + } + const auto optionalNumber=[&](const char* key,float& target) { + if(values.getProperty(key,{}).isVoid())return true; + return number(key,target); + }; + acousticParameters=acousticParameters && + optionalNumber("sourceDistanceMeters",settings.sourceDistanceMeters) && + optionalNumber("roomAmount",settings.roomAmount) && + optionalNumber("ambience",settings.ambience); + const auto numeric=fxRequest.sequence("sonku-"); + bool queued=false; + if(p&&numeric&¶meters&&acousticParameters&&armix::sonku::valid(settings) && + !pendingNativeSonKu_.owner&&!nativeShowBusy_&&!studioBackupBusy_&& + !engine_.independentClockActive()) { + queued=p->queueSettings(settings,numeric); + if(queued&&!unbound) { + pendingNativeSonKu_.owner=owner; + pendingNativeSonKu_.request=request; + pendingNativeSonKu_.channelId=rawChannel.toString(); + pendingNativeSonKu_.deviceEpoch=rawEpoch.toString(); + pendingNativeSonKu_.revision=rawRevision.toString(); + pendingNativeSonKu_.instanceId=rawInstance.toString(); + pendingNativeSonKu_.started=juce::Time::getMillisecondCounter(); + } + } + if(unbound)return completeLogicalFxEdit(args,std::move(offlineInsert), + p,queued,"arMixBuiltinSonKuAck"); + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("status",queued?"QUEUED":"REJECTED"); + ack->setProperty("errorCode",queued?"NONE": + pendingNativeSonKu_.owner?"SONKU_CONTROL_BUSY":"INVALID_OR_STALE_SONKU"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinSonKuQueue",juce::var(ack.release())); + return; + } + // ArSon Vocal Throw: all UI commands reference one exact installed // ChannelId + device epoch + graph revision + insert instance. if(action=="nativeThrowSnapshot"||action=="nativeThrowSet"|| @@ -6720,6 +6893,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr serviceNativeMusicTempo(); servicePendingNativeEq(); servicePendingNativeComp(); + servicePendingNativeSonKu(); servicePendingNativeHarmony(); servicePendingNativeThrow(); saveClosedLogicalVendorEditor(); diff --git a/src/NativeBuiltInFx.h b/src/NativeBuiltInFx.h index 5666ee3a2..fef1f68aa 100644 --- a/src/NativeBuiltInFx.h +++ b/src/NativeBuiltInFx.h @@ -6,6 +6,7 @@ #include "../engine/builtin_fx/ChannelHarmonyProcessor.h" #include "../engine/builtin_fx/VocalThrowProcessor.h" #include "../engine/builtin_fx/GuitarRigEditor.h" +#include "../engine/builtin_fx/SonKuSpatialProcessor.h" #include "../engine/core/PreparedMixerBlock.h" #include #include @@ -77,6 +78,11 @@ inline constexpr std::array nativeBuiltInFx{ "NATIVE_THROW_UNSUPPORTED_AUDIO_FORMAT","NATIVE_THROW_PREPARE_REJECTED", "NATIVE_THROW_PREPARE_EXCEPTION","Saved native Vocal Throw state rejected; graph unchanged", prepareNativeBuiltInFx}, + NativeBuiltInFx{SonKuSpatialProcessor::catalogIdentity,"8D-SonKu","Spatial",true,44100.,48000., + "NATIVE_SONKU_HOST_UNAVAILABLE","NATIVE_SONKU_DEVICE_CHANGED", + "NATIVE_SONKU_UNSUPPORTED_AUDIO_FORMAT","NATIVE_SONKU_PREPARE_REJECTED", + "NATIVE_SONKU_PREPARE_EXCEPTION","Saved 8D-SonKu state rejected; graph unchanged", + prepareNativeBuiltInFx}, NativeBuiltInFx{GuitarRigProcessor::catalogIdentity,"Guitar FX Rig","Guitar",true,32000.,192000., "NATIVE_GFX_HOST_UNAVAILABLE","NATIVE_GFX_DEVICE_CHANGED", "NATIVE_GFX_UNSUPPORTED_AUDIO_FORMAT","NATIVE_GFX_PREPARE_REJECTED", diff --git a/src/NativeLogicalMixerWorkspace.h b/src/NativeLogicalMixerWorkspace.h index a3d187f8e..53058bb54 100644 --- a/src/NativeLogicalMixerWorkspace.h +++ b/src/NativeLogicalMixerWorkspace.h @@ -163,6 +163,16 @@ class NativeLogicalMixerWorkspace final { armix::mixer::ProcessingFormat::mono: armix::mixer::ProcessingFormat::stereo; result=editor_.edit(expected,std::span{&edit,1}); + } else if(operation=="SET_INPUT_GAIN") { + if(!(number.isDouble() || number.isInt() || number.isInt64())) + return bad("INVALID_INPUT_GAIN"); + const auto n=static_cast(number); + const auto* owner=editor_.roster().find(id); + if(!owner || owner->role!=Role::input || !std::isfinite(n) || + n< -24. || n>24.)return bad("INVALID_INPUT_GAIN"); + edit.kind=ChannelEdit::Kind::setInputGain; + edit.value=static_cast(std::pow(10.,n/20.)); + result=editor_.edit(expected,std::span{&edit,1}); } else if(operation=="SET_FADER" || operation=="SET_PAN") { if(!(number.isDouble() || number.isInt() || number.isInt64())) return bad("INVALID_CONTROL_VALUE"); @@ -178,6 +188,29 @@ class NativeLogicalMixerWorkspace final { edit.value=static_cast(n); } result=editor_.edit(expected,std::span{&edit,1}); + } else if(operation=="SET_SEND_TAP") { + const auto raw=payload.getProperty("edgeId",{}); + std::uint64_t edgeId=0; + if(!armix::session::parseDecimal(raw,edgeId)||!edgeId) + return bad("INVALID_SEND_TAP_EDGE"); + const auto tap=payload.getProperty("tap","").toString(); + if(tap!="PRE_FADER" && tap!="POST_FADER") + return bad("INVALID_SEND_TAP_STAGE"); + edit.kind=ChannelEdit::Kind::setSendTap; + edit.sendEdgeId=edgeId; + edit.preFader=tap=="PRE_FADER"; + result=editor_.edit(expected,std::span{&edit,1}); + } else if(operation=="SET_SEND_ENABLED") { + // Document-only operation: never impersonate installed ASIO PCM. + const auto raw=payload.getProperty("edgeId",{}); + const auto enabled=payload.getProperty("enabled",{}); + std::uint64_t edgeId=0; + if(!armix::session::parseDecimal(raw,edgeId)||!edgeId|| + !enabled.isBool())return bad("INVALID_SEND_ENABLED"); + edit.kind=ChannelEdit::Kind::setSendEnabled; + edit.sendEdgeId=edgeId; + edit.enabled=static_cast(enabled); + result=editor_.edit(expected,std::span{&edit,1}); } else if(operation=="SET_MUTE" || operation=="SET_SOLO") { if(!number.isBool())return bad("INVALID_BOOLEAN_CONTROL"); edit.kind=operation=="SET_MUTE"? @@ -339,8 +372,9 @@ class NativeLogicalMixerWorkspace final { set(cap,"callbackOwnsChannelIds",false); juce::Array operations; for(const char* op:{"CREATE_CHANNEL","DELETE_CHANNEL","CREATE_GROUP", - "REMOVE_BUS","RENAME_CHANNEL","SET_FADER","SET_PAN","SET_MUTE", + "REMOVE_BUS","RENAME_CHANNEL","SET_FADER","SET_INPUT_GAIN","SET_PAN","SET_MUTE", "SET_SOLO","SET_PROCESSING_FORMAT","WIRE_TRANSACTION", + "SET_SEND_ENABLED","SET_SEND_TAP", "ADD_FX_REFERENCE","REMOVE_FX_REFERENCE", "SET_FX_SLOT_BYPASS","SET_FX_RACK_BYPASS"})operations.add(juce::String(op)); set(cap,"supportedOps",juce::var(operations)); @@ -358,6 +392,8 @@ class NativeLogicalMixerWorkspace final { set(channel,"role",role); set(channel,"processingFormat",row.format==armix::mixer::ProcessingFormat::stereo? "STEREO":"MONO"); + if(row.role==Role::input)set(controls,"inputGainDb",row.inputGainLinear>0.f? + 20.*std::log10(static_cast(row.inputGainLinear)):-144.); set(controls,"faderDb",row.faderLinear>0.f? std::max(-60.,20.*std::log10(static_cast(row.faderLinear))):-60.); set(controls,"pan",static_cast(row.pan)); @@ -394,9 +430,13 @@ class NativeLogicalMixerWorkspace final { set(edge,"from",str(row.id.value)); set(edge,"to",str(send.destination.value)); set(edge,"signalKind","AUDIO");set(edge,"enabled",true); + // The wire remains present; SEND ON is an independent audio gate. + set(edge,"sendEnabled",send.enabled); set(edge,"gainLinear",static_cast(send.gain)); set(edge,"primaryOutput",send.primaryOutput); set(edge,"tap",send.preFader?"SPLIT_PRE":"POST_FADER"); + // Never confuse the modern post-FX PRE_FADER tap with PRE_FX. + set(edge,"tapStage",send.preFader?"PRE_FADER":"POST_FADER"); edges.add(edge); sends.add(edge); if(send.primaryOutput)set(channel,"primaryOutId",str(send.destination.value)); diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index 4dbdfbb8b..dd3492675 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -530,6 +530,7 @@ class Codec final { set(ch,"format",static_cast(row.format)); set(ch,"name",juce::String::fromUTF8(row.name.c_str())); set(ch,"gain",row.faderLinear); + set(ch,"inputGain",row.inputGainLinear); set(ch,"pan",row.pan);set(ch,"mute",row.mute);set(ch,"solo",row.solo); juce::Array catalogs,sends; for(const auto& c:row.insertCatalogIds) @@ -540,6 +541,7 @@ class Codec final { set(e,"to",decimal(s.destination.value)); set(e,"gain",s.gain);set(e,"pan",s.pan); set(e,"pre",s.preFader);set(e,"primary",s.primaryOutput); + set(e,"enabled",s.enabled); sends.add(e); } set(ch,"catalogs",juce::var(catalogs)); @@ -679,6 +681,13 @@ class Codec final { if(!textField(get(ch,"name"),name,96)|| !real(get(ch,"gain"),n,0.,4.))return false; row.name=name.toStdString();row.faderLinear=static_cast(n); + // Optional since v1 .smix predates independent input gain. + // Absent means unity; malformed/present values fail closed. + const auto inputGain=get(ch,"inputGain"); + if(!inputGain.isVoid()) { + if(!real(inputGain,n,0.,16.))return false; + row.inputGainLinear=static_cast(n); + } if(!real(get(ch,"pan"),n,-1.,1.))return false; row.pan=static_cast(n); if(!strictBool(get(ch,"mute"),row.mute)|| @@ -703,6 +712,8 @@ class Codec final { edge.pan=static_cast(n); if(!strictBool(get(send,"pre"),edge.preFader)|| !strictBool(get(send,"primary"),edge.primaryOutput))return false; + const auto enabled=get(send,"enabled"); + if(!enabled.isVoid()&&!strictBool(enabled,edge.enabled))return false; row.sends.push_back(edge); } entries.push_back(std::move(row)); diff --git a/tests/approved_css_original_bundle_fixture.py b/tests/approved_css_original_bundle_fixture.py index 783bf09d2..de2a35f09 100644 --- a/tests/approved_css_original_bundle_fixture.py +++ b/tests/approved_css_original_bundle_fixture.py @@ -15,6 +15,7 @@ sys.path.insert(0, str(ROOT / "scripts")) from compile_approved_css import LINK from compose_operator_ux import apply_operator_ux +from compose_lms import apply_lms from approved_fx_rack_interaction import apply_fx_rack_interaction ORIGINAL_LINK = re.compile( r'' @@ -44,5 +45,6 @@ def restore_original_css_bundle(bundle: Path) -> None: shutil.copyfile(ROOT / "site" / owner / "assets" / name, assets / name) # The shipped DOM already contains the same composition. Reapply it # only to reconstruct the CSS owner bytes, using its original HTML input. - apply_operator_ux(apply_fx_rack_interaction(source_html, assets), assets) + composed=apply_operator_ux(apply_fx_rack_interaction(source_html, assets), assets) + apply_lms(composed, assets) # same new owner bytes before CSS optimization index.write_text(original_html, encoding="utf-8") diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 9f5eb90d7..8e09afd3d 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -27,6 +27,188 @@ function acceptedFixture(){ tap:"POST",gainLinear:1,enabled:true,signalKind:"AUDIO"}]; return s; } +test("WIRE inspector controls PRIMARY BUS and PARALLEL MAIN by actual EdgeId, with native readback only",()=>{ + const vm=require("node:vm"),{execFileSync}=require("node:child_process"); + const publicHtml=read("site/preview-v2/index.html"); + assert.doesNotMatch(publicHtml,/__ARMIX_NATIVE_M2__/, + "public approved /preview/ must never own native control authority"); + const html=execFileSync("python3",["-c", + "from scripts.build_approved_native_gui import native_html; from pathlib import Path; print(native_html(Path('site/preview-v2/index.html').read_text(encoding='utf-8')))" + ],{ + encoding:"utf8",maxBuffer:10*1024*1024, + // Windows runner's default Python stdout is often CP1252. The approved + // GUI includes Unicode symbols (e.g. ◉), so explicitly encode THIS child + // stream as UTF-8 rather than relying on host code page or a global CI knob. + env:{...process.env,PYTHONIOENCODING:"utf-8"} + }); + assert.ok(html.includes("◉"),"native assembled Unicode survives Python stdout on Windows"); + const bridge=read("web/approved-native-bridge.js"); + const builder=read("scripts/build_approved_native_gui.py"); + assert.match(bridge,/function admittedParallelWire\(uiSourceId,uiEdgeId,operation\)/); + assert.match(bridge,/e\.edgeId===edgeId&&e\.from===source&&e\.primaryOutput===false/); + assert.match(builder,/getElementById\('wireWsGainText'\)/); + assert.match(builder,/!row\.pending/); + const renderStart=html.indexOf("function renderWireWsInspector(){"); + const renderEnd=html.indexOf("function renderWireWorkspace(){",renderStart); + assert.ok(renderStart>0&&renderEnd>renderStart); + const primary={id:41,sourceId:1,destId:2,kind:"primary",mode:"routeOnly", + nativeTap:"POST_FADER",levelDb:0,enabled:true}; + const parallel={id:42,sourceId:1,destId:3,kind:"send",mode:"send", + nativeTap:"POST_FADER",levelDb:-6,enabled:true}; + const panel={hidden:false,innerHTML:""},readout={textContent:"-6 dB"}; + const inspectorGain={value:"-12",dataset:{wsGain:"42"},disabled:false}; + const observed=[]; + const gain=input=>input?.dataset?.wsGain!==undefined?input:null; + const tap=input=>input?.dataset?.wsTap!==undefined?input:null; + const handlers={}; + const scope={ + document:{getElementById(id){ + if(id==="wireWsInspector")return { ...panel, addEventListener(type,fn){handlers[type]=fn}, + get hidden(){return panel.hidden},set hidden(v){panel.hidden=v}, + get innerHTML(){return panel.innerHTML},set innerHTML(v){panel.innerHTML=v}}; + if(id==="wireWsGainText")return readout; + if(id==="wireWsGain")return inspectorGain; + return null; + }}, + window:{__JUCE__:{backend:{}},__ARMIX_NATIVE_M2__:{ + canWireGain(edge,source){return edge===42&&source===1}, + canWireTap(edge,source){return edge===42&&source===1}, + consumeWire(changes){observed.push(changes)} + }}, + wireWsOpen:true,wireWsInspect:{src:1,dst:2},wireWsRemoveConfirm:null, + wireWsEditBefore:null, + wireEdges:[primary,parallel], + tracks:[{id:1,kind:"audio",name:"Vocal"},{id:2,kind:"bus",name:"Bus A"}], + master:{id:3,kind:"master",name:"MAIN"}, + wireWsRoutes:()=>[], + wireWsRouteKind:(src,dst)=>({kind:"wire",edge:src===1&&dst===2?primary:parallel}), + wireWsLabel:id=>"CH "+id,escapeHtml:s=>String(s), + wireSourceTrack:id=>({id}),wireGraphCommit(){throw Error("native must not mutate demo graph")}, + wireWsSnapshot(){throw Error("native must not take demo undo snapshot")}, + wireWsRecord(){throw Error("native must not create demo undo history")}, + render(){throw Error("native must not rebuild mixer DOM")}, + renderWireWorkspace(){throw Error("native must not rebuild inspector")}, + say:s=>observed.push(s) + }; + vm.runInNewContext(html.slice(renderStart,renderEnd),scope); + vm.runInNewContext("renderWireWsInspector()",scope); + assert.match(panel.innerHTML,/PRIMARY · UNITY/); + assert.match(panel.innerHTML,/data-ws-gain="41"[^>]+disabled/); + scope.wireWsInspect={src:1,dst:3}; + vm.runInNewContext("renderWireWsInspector()",scope); + assert.match(panel.innerHTML,/data-ws-gain="42"/); + assert.doesNotMatch(panel.innerHTML,/data-ws-gain="42"[^>]+disabled/); + assert.match(panel.innerHTML,/POST FADER/); + const eventStart=html.indexOf("document.getElementById('wireWsInspector').addEventListener('focusin',"); + const eventEnd=html.indexOf("document.getElementById('wireLegend').addEventListener('change',",eventStart); + assert.ok(eventStart>0&&eventEnd>eventStart); + vm.runInNewContext(html.slice(eventStart,eventEnd),scope); + const event=(element,selector)=>({target:{closest:name=>name===selector?element:null}}); + handlers.input(event({dataset:{wsGain:"41"},value:"-10"},"[data-ws-gain]")); + assert.equal(observed.length,0,"PRIMARY BUS has no independent SEND gain"); + handlers.input(event({dataset:{wsGain:"42"},value:"-12"},"[data-ws-gain]")); + assert.deepEqual(JSON.parse(JSON.stringify(observed[0])),[{ + type:"GAIN",sourceId:1,edgeId:42,levelDb:-12 + }],"PARALLEL MAIN has the exact writable EdgeId"); + assert.equal(readout.textContent,"PENDING · -12 dB", + "input gesture is pending; never labels it accepted"); + const picker={dataset:{wsTap:"42"},value:"split"}; + handlers.change(event(picker,"[data-ws-tap]")); + assert.equal(picker.value,"send","native tap selector waits for independent PCM readback"); + assert.deepEqual(JSON.parse(JSON.stringify(observed[1])),[{ + type:"MODE",sourceId:1,edgeId:42,mode:"split" + }]); + assert.match(observed[2],/awaiting accepted native PCM readback/); + assert.equal(primary.levelDb,0); + assert.equal(parallel.levelDb,-6,"reference WIRE graph never becomes native routing owner"); + // Execute the native compiled rollback method rather than a mock. It must + // repair the same focused DOM control from the latest accepted PCM readback. + // Rejection has no new snapshot: the original level remains -6, not -12. + const rollbackStart=html.indexOf(" rollbackNativeWireInspector(rows){"); + const rollbackEnd=html.indexOf(" syncVerifiedM4Wires(rows,ids){",rollbackStart); + assert.ok(rollbackStart>0&&rollbackEnd>rollbackStart,"native rollback method installed exactly once"); + const method=html.slice(rollbackStart,rollbackEnd).trim().replace(/,\s*$/,""); + const rollback=vm.runInNewContext("({"+method+"})",scope); + assert.equal(rollback.rollbackNativeWireInspector([{id:42,levelDb:-6}]),true); + assert.equal(inspectorGain.value,"-6","failed native intent restores accepted gain without replacing the focused input"); + assert.equal(readout.textContent,"UNCHANGED · -6 dB","LCD cannot remain PENDING after a rejected gain"); + assert.equal(parallel.levelDb,-6,"no browser graph edit or optimistic audio state"); + assert.equal(rollback.rollbackNativeWireInspector([{id:42,levelDb:-6}]),false, + "idempotent failure reconciliation must not repaint a settled LCD"); + // A stale EdgeId cannot silently roll back or write a different route. + inspectorGain.dataset.wsGain="41";readout.textContent="PENDING · -8 dB"; + assert.equal(rollback.rollbackNativeWireInspector([{id:42,levelDb:-6}]),true); + assert.equal(inspectorGain.disabled,true); + assert.equal(readout.textContent,"SEND UNAVAILABLE"); + assert.match(bridge,/rollbackNativeWireInspector\?\.\(nativeWireGainReadback\(state.current\)\)/, + "native control failure must invoke the same compiled inspector rollback"); +}); + +test("native PRE_FADER WIRE inspector uses one exact SET_TAP PCM intent and accepted readback",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const preview=read("site/preview-v2/index.html"); + assert.match(bridge,/function requestNativeTap\(source,edgeId,tap\)/); + assert.match(bridge,/ops\[0\]\.type==="MODE"/); + assert.match(bridge,/op:"SET_TAP",from:source,edgeId,tap/); + assert.match(bridge,/const tap=\["PRE_FADER","POST_FADER"\]\.includes\(edge\.tapStage\)/); + assert.match(preview,/edge\.nativeTap==='PRE_FADER'\?'PRE FADER'/); + assert.match(preview,/edge\?\.nativeTap==='PRE_FADER'\?'split'/); + assert.match(preview,/native\?'PRE FADER':'Pre FX'/); + const s=acceptedFixture(),source=s.graph.channels[0].id; + const bus={id:"9007199254740999",role:"GROUP",name:"BUS B",processingFormat:"STEREO", + controls:{faderDb:0,pan:0,mute:false,solo:false},inserts:[],sends:[]}; + s.graph.channels.splice(1,0,bus); + s.graph.destinations.push({id:bus.id,role:"GROUP"}); + delete s.graph.channels[0].primaryOutId; + s.graph.edges[0]={edgeId:"9223372036854775808",from:source,to:bus.id, + tap:"POST_FADER",gainLinear:.5,enabled:true,sendEnabled:true, + primaryOutput:false,signalKind:"AUDIO"}; + const sent=[],c=protocol.createController({emit:(event,payload)=>sent.push({event,payload})}); + assert.equal(c.onSnapshot(clone(s)),true); + const change={op:"SET_TAP",from:source,edgeId:s.graph.edges[0].edgeId,tap:"PRE_FADER"}; + const t=c.intent("APPLY_WIRE_TRANSACTION",source,{changes:[change]}); + assert.equal(t.ok,true); + assert.deepEqual(sent.at(-1).payload.payload.changes,[change]); + assert.equal(c.state().current.graph.edges[0].tap,"POST_FADER"); + assert.equal(c.onAck({requestId:t.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:s.device.epoch,graphRevision:"6",rosterRevision:"8"}),true); + assert.equal(c.state().current.graph.edges[0].tap,"POST_FADER", + "ACK alone cannot repaint a PRE_FADER send"); + const next=clone(s);next.graph.revision="6";next.graph.rosterRevision="8"; + next.graph.edges[0].tap="PRE_FADER"; + assert.equal(c.onSnapshot(next),true); + assert.equal(c.state().pending,null); + assert.equal(c.state().current.graph.edges[0].tap,"PRE_FADER"); + assert.equal(c.state().current.graph.edges[0].edgeId,change.edgeId); + assert.equal(c.state().current.graph.edges[0].gainLinear,.5); + assert.equal(c.state().current.graph.edges[0].sendEnabled,true); +}); + +test("native input Gain is a separate ChannelId scalar proven only by ACK plus inputGain readback",()=>{ + const s=acceptedFixture(),id=s.graph.channels[0].id; + s.graph.capabilities.supportedOps.push("SET_INPUT_GAIN"); + s.graph.channels[0].controls.inputGainDb=0; + const sent=[],ctl=protocol.createController({emit:(name,value)=>sent.push({name,value})}); + assert.equal(ctl.onSnapshot(s),true); + const edit=ctl.intent("SET_INPUT_GAIN",id,{valueDb:6}); + assert.equal(edit.ok,true); + assert.equal(sent.length,1); + assert.equal(ctl.state().pending?.operation,"SET_INPUT_GAIN"); + assert.equal(ctl.onAck({requestId:edit.requestId,status:"ACCEPTED", + deviceEpoch:s.device.epoch,graphRevision:s.graph.revision, + rosterRevision:s.graph.rosterRevision,errorCode:"NONE"}),true); + // An unchanged FADER is not proof that an INPUT GAIN changed. + assert.equal(protocol.readbackProvesIntent(ctl.state().current, + {operation:"SET_INPUT_GAIN",targetChannelId:id,payload:{valueDb:6}}),false); + const actual=clone(s);actual.graph.channels[0].controls.inputGainDb=6; + assert.equal(ctl.onSnapshot(actual),true); + assert.equal(ctl.state().pending,null); + assert.equal(ctl.state().current.graph.channels[0].controls.faderDb,-6); + assert.equal(ctl.state().current.graph.channels[0].controls.inputGainDb,6); + const malformed=clone(actual);malformed.graph.channels[0].controls.inputGainDb="NaN"; + assert.equal(protocol.normalizeSnapshot(malformed),null); +}); + test("M5 native FX snapshot rejects malformed/duplicate lease tokens without losing accepted state",()=>{ const good=acceptedFixture(),input=good.graph.channels[0].id; good.graph.channels[0].inserts=[{ @@ -1208,6 +1390,25 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a listeners.get("arMixConsoleSnapshot")(gained); assert.equal(scope.edges[0].levelDb,-12); assert.equal(paints,paintBeforeGain); + // WIRE inspector MODE is a legacy visual gesture. It MUST become one + // exact native SET_TAP EdgeId transaction; rejection leaves the PCM tap intact. + const tapUi=scope.edges[0].id; + assert.equal(window.__ARMIX_NATIVE_M2__.consumeWire([{ + type:"MODE",sourceId:sourceUi,edgeId:tapUi,mode:"split" + }]),true); + const tapRequest=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + assert.equal(tapRequest.operation,"APPLY_WIRE_TRANSACTION"); + assert.deepEqual(JSON.parse(JSON.stringify(tapRequest.payload.changes)),[{ + op:"SET_TAP",from:routed.graph.channels[0].id, + edgeId:"9223372036854775810",tap:"PRE_FADER" + }]); + assert.equal(scope.edges[0].nativeTap,"POST_FADER"); + listeners.get("arMixConsoleAck")({requestId:tapRequest.requestId,status:"REJECTED", + errorCode:"NATIVE_WIRE_TRANSACTION_REJECTED",deviceEpoch:gained.device.epoch, + graphRevision:"8",rosterRevision:"8"}); + assert.equal(window.__ARMIX_NATIVE_M2__.state().pending,null); + assert.equal(scope.edges[0].nativeTap,"POST_FADER", + "rejected native tap must restore the last accepted PCM stage"); // OUT uses the same actual INPUT destination as WIRE, not a name-only // GROUP lookup. An exclusive route promotes the existing native edge. const hooks=window.__ARMIX_NATIVE_M2__,sourceTrack=scope.tracks[0]; @@ -1991,3 +2192,24 @@ test("Guitar FX picker binding is real, visible and matches native installed reg assert.ok(bridge.includes('controller.intent("LOAD_INSERT",nativeId,')); assert.ok(bridge.includes('pendingFxInsert={authority:"CHANNEL_ID"')); }); + +test("SOF double-click and target selection never commandeer MAIN fader",()=>{ + const html=read("site/preview-v2/index.html"); + const bridge=read("web/approved-native-bridge.js"); + const bundle=read("scripts/build_approved_native_gui.py"); + assert.match(html,/function selectedSofDestination\(\)/); + assert.match(html,/sofTargetId=target\?\.id\?\?null/); + assert.match(html,/const send=sofEnabled&&t\.kind==='audio'/); + assert.match(html,/fader\.dispatchEvent\(new Event\('change'/); + assert.match(bundle,/get sofTargetId\(\)\{return sofTargetId;\}/); + assert.match(bridge,/x\.id===scope\.sofTargetId/); + const start=bridge.indexOf("consumeDoubleClick(event,t)"); + const end=bridge.indexOf("applyIdentity:",start); + assert.ok(start>0&&end>start,"native delegate must own double-click"); + const handler=bridge.slice(start,end); + assert.ok(handler.indexOf("scope?.sofEnabled") < + handler.indexOf('sendM4Control'), + "SOF must intercept fader reset BEFORE M4/Main fader ownership"); + assert.match(handler,/requestWireGain\(\{sourceId:t\.id,edgeId:id,levelDb:0\}\)/); + assert.match(handler,/intent\("SET_INPUT_GAIN",t,\{valueDb:0\}\)/); +}); diff --git a/tests/approved_native_sof_chromium_smoke.py b/tests/approved_native_sof_chromium_smoke.py new file mode 100644 index 000000000..254de70a3 --- /dev/null +++ b/tests/approved_native_sof_chromium_smoke.py @@ -0,0 +1,203 @@ +#!/usr/bin/env python3 +"""Actual compiled native Sends-on-Faders GUI: EdgeId intents -> ACK -> readback. + +Uses the SAME native-only assembled /preview/ as the Windows WebView2 host. +Playwright emulates the JUCE transport, never PCM or a second audio engine. +PCM PRE/POST, gain slew and enable gates are independently verified in CTest. +No private mixer mutators, reference reducer, or fake browser audio are used. +""" +from __future__ import annotations + +import copy +import importlib.util +from pathlib import Path +import tempfile + +from playwright.sync_api import sync_playwright +from approved_native_wire_gain_smoke import MAIN, RECEIVER, SEND, SOURCE, ack, emit, snapshot + +ROOT = Path(__file__).resolve().parents[1] + + +def admitted_session(): + state = snapshot() + graph = state["graph"] + graph["capabilities"]["supportedOps"] = [ + "SET_FADER", "SET_WIRE_GAIN", "SET_SEND_ENABLED", "APPLY_WIRE_TRANSACTION" + ] + graph["channels"][0]["controls"]["faderDb"] = -7.5 + graph["channels"][1]["role"] = "GROUP" + graph["channels"][1]["name"] = "STAGE BUS" + graph["edges"][1]["sendEnabled"] = True + graph["destinations"] = [ + {k: channel[k] for k in ("id", "role", "name")} + for channel in graph["channels"] + ] + state["mixerSession"]["channels"] = copy.deepcopy(graph["channels"]) + state["productionCallbackLive"] = True + return state + + +def intent_list(page, operation): + return page.evaluate( + "operation=>window.__nativeIntents.filter(x=>x.operation===operation)", + operation, + ) + + +def wait_for_intents(page, operation, count): + page.wait_for_function( + """([operation,count])=> + window.__nativeIntents.filter(x=>x.operation===operation).length>=count""", + arg=[operation, count], timeout=6000, + ) + values = intent_list(page, operation) + assert len(values) == count, (operation, values) + return values[-1] + + +def exercise(browser, out, width, height): + page = browser.new_page(viewport={"width":width, "height":height}) + errors = [] + page.on("pageerror", lambda error: errors.append(str(error))) + page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[]; + window.__JUCE__={backend:{ + emitEvent(name,payload){ + if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload); + }, + addEventListener(name,callback){window.__nativeListeners.set(name,callback);} + }};""") + page.goto((out/"index.html").as_uri()) + page.wait_for_function("()=>window.__ARMIX_NATIVE_M2__?.enabled", timeout=15000) + state = admitted_session() + emit(page, "arMixConsoleSnapshot", state) + source = page.locator('#tracks .strip[data-id="1"]') + source.wait_for(state="attached",timeout=15000) + target = page.locator("#sofTarget") + toggle = page.locator("#sofToggle") + assert toggle.is_visible() and toggle.is_enabled(), ( + "A current native PCM graph with all three SEND capabilities must admit SOF") + options = target.locator("option").all_text_contents() + assert any("STAGE BUS" in label for label in options), options + target.select_option(label=next(label for label in options if "STAGE BUS" in label)) + toggle.click() + assert page.locator("#mixContext").inner_text() == "SEND MIX → STAGE BUS" + on = source.locator('[data-action="sofOn"]') + tap = source.locator('[data-action="sofTap"]') + assert on.is_enabled() and tap.is_enabled() + assert on.get_attribute("aria-pressed") == "true" + assert "POST-FADER" in source.locator(".sof-badge").inner_text() + assert not source.locator(".fader").is_disabled(), "Admitted send must own SOF fader" + + # SEND OFF is a scalar against the EXACT existing EdgeId, not topology. + on.click() + off = wait_for_intents(page, "SET_SEND_ENABLED", 1) + assert off["targetChannelId"] == SOURCE and off["payload"] == { + "edgeId":SEND,"enabled":False + }, off + assert on.get_attribute("aria-pressed") == "true", ( + "An unacknowledged intent must not visibly turn off the accepted send") + ack(page, state, off) + assert on.get_attribute("aria-pressed") == "true", "ACK alone is not PCM readback" + state["graph"]["edges"][1]["sendEnabled"] = False + emit(page, "arMixConsoleSnapshot", state) + page.wait_for_function("""()=>document.querySelector( + '#tracks .strip[data-id="1"] [data-action="sofOn"]')?.getAttribute('aria-pressed')==='false'""") + assert source.locator(".sof-badge").inner_text() == "POST-FADER" + assert "OFF" in source.locator(".sof-info small").inner_text() + assert len(state["graph"]["edges"]) == 3 + assert state["graph"]["edges"][1]["gainLinear"] == .5 + + on = source.locator('[data-action="sofOn"]') + on.click() + enabled = wait_for_intents(page, "SET_SEND_ENABLED", 2) + assert enabled["payload"] == {"edgeId":SEND,"enabled":True} + ack(page, state, enabled) + state["graph"]["edges"][1]["sendEnabled"] = True + emit(page, "arMixConsoleSnapshot", state) + page.wait_for_function("""()=>document.querySelector( + '#tracks .strip[data-id="1"] [data-action="sofOn"]')?.getAttribute('aria-pressed')==='true'""") + + # A PRE-FADER tap changes the installed graph revision; no DOM optimism. + source.locator('[data-action="sofTap"]').click() + structural = wait_for_intents(page, "APPLY_WIRE_TRANSACTION", 1) + changes = structural["payload"]["changes"] + assert len(changes)==1 and changes[0] == { + "op":"SET_TAP","from":SOURCE,"edgeId":SEND,"tap":"PRE_FADER" + }, structural + assert "POST-FADER" in source.locator(".sof-badge").inner_text() + state["graph"].update(revision="3",rosterRevision="3") + state["mixerSession"].update(routeRevision="3",rosterRevision="3") + state["graph"]["edges"][1]["tap"] = "PRE_FADER" + ack(page, state, structural) + assert "POST-FADER" in source.locator(".sof-badge").inner_text(), ( + "A control ACK alone cannot announce a newly installed PRE tap") + emit(page, "arMixConsoleSnapshot", state) + page.wait_for_function("""()=>document.querySelector( + '#tracks .strip[data-id="1"] .sof-badge')?.textContent==='PRE-FADER'""") + assert source.locator('[data-action="sofTap"]').get_attribute("data-tap-visual")=="pre" + + # The physical SOF fader controls SEND GAIN only. The accepted main fader + # remains -7.5 dB and no SET_FADER intent may be generated by a send move. + fader = source.locator(".fader") + assert fader.is_enabled() + fader.evaluate("""el=>{ + el.value='-12'; + el.dispatchEvent(new Event('input',{bubbles:true})); + el.dispatchEvent(new Event('change',{bubbles:true})); + }""") + level = wait_for_intents(page,"SET_WIRE_GAIN",1) + assert level["targetChannelId"]==SOURCE + assert level["payload"]["edgeId"]==SEND + assert abs(level["payload"]["gainLinear"]-10**(-12/20))<1e-8 + assert intent_list(page,"SET_FADER")==[] + assert state["graph"]["channels"][0]["controls"]["faderDb"]==-7.5 + ack(page,state,level) + state["graph"]["edges"][1]["gainLinear"] = level["payload"]["gainLinear"] + emit(page,"arMixConsoleSnapshot",state) + fader.evaluate("el=>el.blur()") + emit(page,"arMixConsoleSnapshot",state) + assert state["graph"]["channels"][0]["controls"]["faderDb"]==-7.5 + assert intent_list(page,"SET_FADER")==[] + page.screenshot(path=f"arsonmix-native-sof-{width}.png") + + # The absence of an admitted EdgeId must never trigger an automatic + # patch, a ghost send, nor an unintended MAIN fader write. + state["graph"].update(revision="4",rosterRevision="4") + state["mixerSession"].update(routeRevision="4",rosterRevision="4") + state["graph"]["edges"].pop(1) + emit(page,"arMixConsoleSnapshot",state) + assert "NO SEND" in source.locator(".sof-badge").inner_text() + assert source.locator('[data-action="sofOn"]').is_disabled() + assert source.locator('[data-action="sofTap"]').is_disabled() + before=len(page.evaluate("()=>window.__nativeIntents")) + assert source.locator(".fader").is_disabled() + assert len(page.evaluate("()=>window.__nativeIntents"))==before + + toggle.click() + assert page.locator("#mixContext").inner_text()=="MAIN MIX" + assert abs(float(source.locator(".fader").input_value())-(-7.5))<.01 + assert not errors, errors + page.close() + + +def main(): + spec=importlib.util.spec_from_file_location( + "native_bundle",ROOT/"scripts/build_approved_native_gui.py") + bundle=importlib.util.module_from_spec(spec) + spec.loader.exec_module(bundle) + with tempfile.TemporaryDirectory(prefix="armix-native-sof-") as directory: + out=Path(directory) + bundle.stage(out) + with sync_playwright() as pw: + browser=pw.chromium.launch(headless=True) + try: + for width,height in ((1366,900),(1024,768)): + exercise(browser,out,width,height) + finally: + browser.close() + print("PASS native SOF actual Chromium: exact EdgeId ON/OFF, PRE tap, gain, ACK/readback, no ghost patch or MAIN fader write; two viewports") + + +if __name__=="__main__": + main() diff --git a/tests/approved_native_sonku_smoke.py b/tests/approved_native_sonku_smoke.py new file mode 100644 index 000000000..182b1d80d --- /dev/null +++ b/tests/approved_native_sonku_smoke.py @@ -0,0 +1,487 @@ +#!/usr/bin/env python3 +"""8D-SonKu real compiled WebView2 GUI: native insert -> ACK -> readback -> editor. +Transport is emulated, never PCM. Native DSP is independently tested by CTest. +The test does not invoke private mixer state APIs to fake accepted inserts. +""" +import copy +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 + +ROOT=Path(__file__).resolve().parents[1] +CATALOG="armix.builtin.8d-sonku.v1" +INSTANCE="sonku-accepted-instance" +SETTINGS={ + "startAzimuthDegrees":0.0, + "revolutionSeconds":12.0, + "stereoSpreadDegrees":60.0, + "spatialMix":1.0, + "outputTrim":0.75, + "moving":True, + "clockwise":True, + "spacePreset":0, + "sourceDistanceMeters":1.6, + "roomAmount":0.55, + "ambience":0.30, +} + +def last_action(page,name): + actions=page.evaluate( + "name=>window.__actions.filter(a=>a.action===name)",name) + assert actions, "Expected actual native action "+name + return actions[-1] + +def accepted_snapshot(page,state,settings,applied=None): + read=last_action(page,"nativeSonKuSnapshot") + payload={ + "requestId":read["requestId"],"status":"ACCEPTED","schemaVersion":2, + "channelId":SOURCE,"slot":0,"instanceId":INSTANCE, + "deviceEpoch":state["device"]["epoch"], + "graphRevision":state["graph"]["revision"], + "observedAzimuthDegrees":settings["startAzimuthDegrees"], + "settings":copy.deepcopy(settings), + } + if applied:payload["appliedRequestId"]=applied + emit(page,"arMixBuiltinSonKuSnapshot",payload) + +def exercise(browser,out,width,height): + page=browser.new_page(viewport={"width":width,"height":height}) + failures=[] + page.on("pageerror",lambda exc:failures.append(str(exc))) + 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 prior=window.__nativeListeners.get(name); + window.__nativeListeners.set(name,prior? + packet=>{prior(packet);callback(packet)}:callback); + } + }};""") + page.goto((out/"index.html").as_uri()) + page.wait_for_function( + "()=>window.__ARMIX_NATIVE_M2__?.enabled && window.ArSonMixNativeSonKu", + timeout=15000) + state=snapshot() + state["graph"]["capabilities"]["supportedOps"]+=["LOAD_INSERT","REMOVE_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() + # Real assembled WebView picker: Guitar FX is a catalog Native processor + # BEFORE the VST3 divider; SonKu retains its one specialized editor button. + # This catches the #657 / SonKu M4 cross-branch regression at the operator + # click surface, not merely by matching assembler source strings. + guitar=page.locator('#fastResults [data-fast-id="armix.builtin.guitar-rig.v1"]') + guitar.wait_for(state="visible",timeout=6000) + assert guitar.count()==1,"Native Guitar FX missing or duplicated in BUILT-IN FX" + assert page.evaluate("""()=>{ + const node=document.querySelector('#fastResults [data-fast-id="armix.builtin.guitar-rig.v1"]'); + const group=Array.from(document.querySelectorAll('#fastResults .fast-fx-category')); + return group.length===2 && group[0].textContent==='BUILT-IN FX' && + group[1].textContent==='VST3 PLUGINS' && + (group[0].compareDocumentPosition(node)&Node.DOCUMENT_POSITION_FOLLOWING)!==0 && + (node.compareDocumentPosition(group[1])&Node.DOCUMENT_POSITION_FOLLOWING)!==0; + }"""),"Guitar FX shown under VST3 instead of first native BUILT-IN shelf" + assert page.locator('#fastResults [data-fast-id="armix.builtin.8d-sonku.v1"]').count()==0, ( + "SonKu specialized editor must not be duplicated as catalog generic") + picker=page.locator("#fastResults [data-fast-native-sonku]") + picker.wait_for(state="visible") + assert picker.count()==1,"8D-SonKu picker duplicated or missing" + assert page.locator("#mxNativeSonKu").is_hidden(),"Editor opened before native ACK" + picker.click() + requests=page.evaluate( + "()=>window.__nativeIntents.filter(x=>x.operation==='LOAD_INSERT')") + assert len(requests)==1,requests + req=requests[0] + assert req["payload"]["catalogId"]==CATALOG,req + assert page.locator("#mxNativeSonKu").is_hidden(),"Editor opened on intent only" + state["graph"].update(revision="3",rosterRevision="3") + state["graph"]["channels"][0]["inserts"].append({ + "id":INSTANCE,"catalogId":CATALOG,"name":"8D-SonKu","bypassed":False}) + state["mixerSession"].update(routeRevision="3",rosterRevision="3", + channels=copy.deepcopy(state["graph"]["channels"])) + ack(page,state,req) + # Acceptance alone does not paint active DSP; readback authorizes editor. + assert page.locator("#mxNativeSonKu").is_hidden() + emit(page,"arMixConsoleSnapshot",state) + editor=page.locator("#mxNativeSonKu") + editor.wait_for(state="visible",timeout=5000) + assert editor.locator("#skMap .sk-src").count()==2 + assert editor.locator("#skMap .sk-speaker-shell").count()==2 + assert editor.locator("#skMap #skRearArc").count()==1 + assert editor.locator("#skMap #skFrontArc").count()==1 + # Painter's ordering is 3D: far rail -> back-facing listener -> near rail. + assert page.evaluate("""() => { + const map=document.querySelector('#skMap'); + const rear=map.querySelector('#skRearArc'); + const art=map.querySelector('#skListenerArt'); + const front=map.querySelector('#skFrontArc'); + return Boolean((rear.compareDocumentPosition(art) & Node.DOCUMENT_POSITION_FOLLOWING) && + (art.compareDocumentPosition(front) & Node.DOCUMENT_POSITION_FOLLOWING)); + }"""), "Front/back ring painter layering incorrect" + # Painter's algorithm applies to the *speakers*, not only the floor rail. + assert page.evaluate("""() => { + const map=document.querySelector('#skMap'); + const far=map.querySelector('#skRearSources'); + const art=map.querySelector('#skListenerArt'); + const near=map.querySelector('#skFrontSources'); + return Boolean((far.compareDocumentPosition(art)&Node.DOCUMENT_POSITION_FOLLOWING) && + (art.compareDocumentPosition(near)&Node.DOCUMENT_POSITION_FOLLOWING)); + }"""),"Rear speakers are incorrectly rendered in FRONT of the head" + # Every rotation input remains an accessible native range, wrapped in + # a tactile rotary shell: no browser PCM, no fake processed state. + assert editor.locator(".sk-rotary-grid .sk-dial").count()==4 + for knob in ("skSpeed","skSpread","skMix","skTrim"): + assert editor.locator("#"+knob).get_attribute("type")=="range" + assert editor.locator("#"+knob).evaluate("(n)=>n.closest('.sk-dial')!==null") + art=editor.locator("#skListenerArt") + assert art.count()==1 and "facing top" in art.get_attribute("aria-label") + # An original back-of-head vector replaces the physically incorrect + # upside-down face PNG. Same SVG is bundled directly into /preview/. + assert art.locator("path").count()>=6 + assert editor.locator("#skMap #skCrown").count()==1 + assert editor.locator("#skMap #skBackSuit").count()==1 + # SVG is not HTML text: Chromium 158 no longer exposes usable + # HTMLElement.innerText for these nodes. Read SVG textContent and verify + # the actual anchors, so front/rear cannot silently flip in the GUI. + direction=editor.locator("#skMap .sk-direction") + labels=direction.evaluate_all( + "(nodes)=>nodes.map(n=>({text:n.textContent.trim(),x:Number(n.getAttribute('x')),y:Number(n.getAttribute('y'))}))") + assert [x["text"] for x in labels]==["FRONT","REAR","LEFT","RIGHT"],labels + assert labels[0]["y"]<60 and labels[1]["y"]>290,labels + assert labels[2]["x"]<50 and labels[3]["x"]>300,labels + assert editor.locator("#skListenerArt").get_attribute("pointer-events")=="none" + assert editor.locator("#skMotion").inner_text()=="ORBIT" + assert editor.locator("#skDirection").inner_text()=="CLOCKWISE" + assert editor.locator("#skMode").inner_text()=="NATIVE HRTF" + # 250ms visualization timer must not overwrite an unacknowledged + # snapshot request (real JUCE message thread can be temporarily busy). + count=page.evaluate( + "()=>window.__actions.filter(a=>a.action==='nativeSonKuSnapshot').length") + page.wait_for_timeout(700) + after=page.evaluate( + "()=>window.__actions.filter(a=>a.action==='nativeSonKuSnapshot').length") + assert after==count, "Unanswered SonKu readback was overwritten" + accepted_snapshot(page,state,SETTINGS) + # A true visual animation must advance BETWEEN native readbacks. + # The old 250ms setInterval was ~4fps despite valid DSP PCM. + vx0=editor.locator('.sk-src[data-index="0"]').get_attribute("data-visual-x") + page.wait_for_timeout(150) + vx1=editor.locator('.sk-src[data-index="0"]').get_attribute("data-visual-x") + assert abs(float(vx1)-float(vx0))>1.0,("Orbit is frozen between readbacks",vx0,vx1) + # Close/reopen must use the installed FX rack click, never a private open(). + editor.locator("#skClose").click() + assert editor.is_hidden() + row=strip.locator('.fxslot-row[data-insert-id="'+INSTANCE+'"]') + row.wait_for(state="visible") + row.locator('[data-action="openPlugin"]').click() + editor.wait_for(state="visible") + accepted_snapshot(page,state,SETTINGS) + editor.locator("#skMotion").click() + command=last_action(page,"nativeSonKuSet") + assert command["settings"]["moving"] is False,command + assert command["instanceId"]==INSTANCE and command["channelId"]==SOURCE + emit(page,"arMixBuiltinSonKuQueue",{ + "requestId":command["requestId"],"status":"QUEUED"}) + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":command["requestId"],"status":"APPLIED"}) + accepted_snapshot(page,state,{**SETTINGS,"moving":False}, + applied=command["requestId"]) + assert editor.locator("#skMotion").inner_text()=="STATIC" + assert "ACCEPTED" in editor.locator("#skHint").inner_text() + # Verify native HRTF azimuth is unchanged while screen orientation + # now matches the real user: FRONT=TOP, anatomical RIGHT=SCREEN RIGHT. + def pose(degrees): + page.wait_for_timeout(270) + settings={**SETTINGS,"moving":False,"stereoSpreadDegrees":0.0, + "startAzimuthDegrees":float(degrees)} + accepted_snapshot(page,state,settings) + # Acoustic anchor is distinct from the readable icon's display offset. + # The offset NEVER alters native azimuth when both sources coincide. + nodes=editor.locator('#skMap .sk-src') + data=nodes.evaluate_all("""els=>els.map(n=>({ + ax:Number(n.dataset.acousticX),ay:Number(n.dataset.acousticY), + vx:Number(n.dataset.visualX),vy:Number(n.dataset.visualY), + value:Number(n.getAttribute('aria-valuenow'))}))""") + assert len(data)==2 and data[0]["value"]==data[1]["value"]==degrees,data + assert abs(data[0]["ax"]-data[1]["ax"])<.01,data + assert abs(data[0]["ay"]-data[1]["ay"])<.01,data + separation=((data[0]["vx"]-data[1]["vx"])**2+ + (data[0]["vy"]-data[1]["vy"])**2)**.5 + assert separation>=44,("Two studio speakers overlap at zero spread",data) + # Source icon is now INSIDE the front or rear SVG paint layer. + layer=nodes.first.evaluate("(n)=>n.parentElement.id") + if degrees in (0,180): + expected="skFrontSources" if degrees==0 else "skRearSources" + assert layer==expected,(degrees,layer,expected) + return data[0]["ax"],data[0]["ay"] + x,y=pose(0);assert abs(x-200)<1 and y<100,("FRONT",x,y) + x,y=pose(90);assert x>335 and abs(y-174)<1,("RIGHT",x,y) + x,y=pose(180);assert abs(x-200)<1 and y>245,("REAR",x,y) + x,y=pose(-90);assert x<60 and abs(y-174)<1,("LEFT",x,y) + # All drag paths now STREAM native edits DURING the gesture. A burst + # must emit only one in-flight command; the most recent sample follows + # verified ACK+snapshot, not hundreds of SPSC entries or false UI ACKs. + def command_count(): + return page.evaluate( + "()=>window.__actions.filter(a=>a.action==='nativeSonKuSet').length") + def applied_settings(action,settings): + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":action["requestId"],"status":"APPLIED"}) + accepted_snapshot(page,state,settings,applied=action["requestId"]) + svg=editor.locator("#skMap").bounding_box() + assert svg + def screen(x,y): + return (svg["x"]+x*svg["width"]/400, + svg["y"]+y*svg["height"]/330) + + # SVG speaker movement must affect the JUCE PCM route BEFORE mouseup. + # FRONT is now visual TOP and acoustic 0°, not bottom. + source=editor.locator('.sk-src[data-index="0"]') + sx,sy=screen(float(source.get_attribute("data-visual-x")), + float(source.get_attribute("data-visual-y"))) + ex,ey=screen(200,91) + before=command_count() + page.mouse.move(sx,sy) + page.mouse.down() + page.mouse.move(ex,ey,steps=10) + assert command_count()==before+1,"Speaker drag not live / SPSC flooded" + first=last_action(page,"nativeSonKuSet") + assert first["settings"]["moving"] is False + page.mouse.up() + assert command_count()==before+1,"Unverified sends flooded during drag" + applied_settings(first,{**SETTINGS,"moving":False, + "stereoSpreadDegrees":0.0, + "startAzimuthDegrees":first["settings"]["startAzimuthDegrees"]}) + dragAction=last_action(page,"nativeSonKuSet") + assert dragAction["settings"]["moving"] is False + assert abs(dragAction["settings"]["startAzimuthDegrees"])<5,dragAction + if dragAction["requestId"]!=first["requestId"]: + assert command_count()==before+2,"Latest-wins did not coalesce" + applied_settings(dragAction,{**SETTINGS,"moving":False, + "stereoSpreadDegrees":0.0,"startAzimuthDegrees": + dragAction["settings"]["startAzimuthDegrees"]}) + + # Same global gesture scheduler handles FOUR rotary knobs (pointer, key). + # The original bug sent NOTHING until pointer release. + knob=editor.locator("#skSpeed").locator("..") + box=knob.bounding_box();assert box + x=box["x"]+box["width"]*.5;y=box["y"]+box["height"]*.5 + before=command_count() + page.mouse.move(x,y);page.mouse.down() + page.mouse.move(x,y-17,steps=6) + assert command_count()==before+1,"Rotary does not stream native edit" + knobFirst=last_action(page,"nativeSonKuSet") + page.mouse.up() + assert command_count()==before+1,"Rotary overran single in-flight" + firstSettings={**SETTINGS,"moving":False, + "stereoSpreadDegrees":0.0,"startAzimuthDegrees":0.0, + "revolutionSeconds":knobFirst["settings"]["revolutionSeconds"]} + applied_settings(knobFirst,firstSettings) + dialAction=last_action(page,"nativeSonKuSet") + assert dialAction["settings"]["revolutionSeconds"]>12,dialAction + if dialAction["requestId"]!=knobFirst["requestId"]: + assert command_count()==before+2 + applied_settings(dialAction,{**firstSettings, + "revolutionSeconds":dialAction["settings"]["revolutionSeconds"]}) + # M4: native SPACE must be an actual typed ACK/readback edit. + # No browser-only audio, no visual success before PCM applied. + assert editor.locator(".sk-space-options button").count()==4 + assert editor.locator("#skDistance").is_disabled() + assert editor.locator("#skAmbience").is_disabled() + assert editor.locator("#skReflections").is_disabled() + assert editor.locator("#skTrimValue").inner_text().endswith("dB") + assert editor.locator("#skTrim").get_attribute("max")=="12" + editor.locator('[data-sk-room="2"]').click() + scene=last_action(page,"nativeSonKuSet") + assert scene["settings"]["spacePreset"]==2,scene + assert scene["settings"]["sourceDistanceMeters"]==1.6,scene + assert scene["settings"]["roomAmount"]==0.55,scene + assert scene["settings"]["ambience"]==0.30,scene + assert "ACCEPTED" not in editor.locator("#skHint").inner_text() + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":scene["requestId"],"status":"APPLIED"}) + sceneState={**SETTINGS,"moving":False,"startAzimuthDegrees":0.0, + "stereoSpreadDegrees":0.0, + "revolutionSeconds":dialAction["settings"]["revolutionSeconds"], + "spacePreset":2} + accepted_snapshot(page,state,sceneState,applied=scene["requestId"]) + assert editor.locator('[data-sk-room="2"]').get_attribute("aria-pressed")=="true" + assert editor.locator("#skDistance").is_enabled() + assert editor.locator("#skAmbience").is_enabled() + assert editor.locator("#skReflections").is_enabled() + # The 0..100% controls must reach independent native wet parameters, + # never only browser-side visual labels. Include a >unity GAIN request + # to prove the formerly capped 0..100% trim has genuinely become dB gain. + def apply_slider(selector,value,field): + editor.locator(selector).evaluate("""(n,v)=>{ + n.value=String(v); + n.dispatchEvent(new Event('input',{bubbles:true})); + n.dispatchEvent(new Event('change',{bubbles:true})); + }""",value) + sent=last_action(page,"nativeSonKuSet") + assert field in sent["settings"],sent + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":sent["requestId"],"status":"APPLIED"}) + return sent + gain=apply_slider("#skTrim",6.0,"outputTrim") + assert 1.993.0,("Distance pointer gesture not effective",held) + assert command_count()==before+1,"Distance changed only after release or flooded DSP" + distanceFirst=last_action(page,"nativeSonKuSet") + assert distanceFirst["settings"]["sourceDistanceMeters"]>=1.6 + # Simulate a delayed periodic snapshot DURING the gesture: no thumb snap. + page.wait_for_timeout(310) + accepted_snapshot(page,state,sceneState) + assert abs(float(slider.input_value())-held)<.15,( + "Native snapshot incorrectly reverted held range thumb", + held,slider.input_value()) + assert editor.locator("#skDistanceValue").inner_text()==f"{held:.1f} m" + page.mouse.up() + assert command_count()==before+1 + firstState={**sceneState, + "sourceDistanceMeters":distanceFirst["settings"]["sourceDistanceMeters"]} + applied_settings(distanceFirst,firstState) + userDistance=last_action(page,"nativeSonKuSet") + assert userDistance["settings"]["sourceDistanceMeters"]>3.,userDistance + if userDistance["requestId"]!=distanceFirst["requestId"]: + assert command_count()==before+2,"Latest range edit not coalesced after ACK" + sceneState={**sceneState, + "sourceDistanceMeters":userDistance["settings"]["sourceDistanceMeters"]} + applied_settings(userDistance,sceneState) + else: + sceneState=firstState + # Verify a burst of 30 values on REVERB sends bounded realtime packets + # before a final change. This catches accidental unbounded streaming. + before=command_count() + editor.locator("#skAmbience").evaluate("""n=>{ + for(let i=0;i<30;i++){ + n.value=String(i%2?i*3:30+i); + n.dispatchEvent(new Event('input',{bubbles:true})); + } + }""") + page.wait_for_timeout(60) + assert command_count()==before+1,"Reverb did not stream / issued uncontrolled edits" + one=last_action(page,"nativeSonKuSet") + assert one["settings"]["ambience"]!=sceneState["ambience"] + # Make a FINAL distinct value while earlier PCM ACK is still pending. + editor.locator("#skAmbience").evaluate("""n=>{ + n.value="71";n.dispatchEvent(new Event('input',{bubbles:true})); + n.dispatchEvent(new Event('change',{bubbles:true})); + }""") + assert command_count()==before+1,"Reverb flooded the native SPSC" + applied_settings(one,{**sceneState,"ambience":one["settings"]["ambience"]}) + finalReverb=last_action(page,"nativeSonKuSet") + assert finalReverb["requestId"]!=one["requestId"],"Latest 71% edit lost" + assert finalReverb["settings"]["ambience"]==.71 + sceneState={**sceneState,"ambience":.71} + applied_settings(finalReverb,sceneState) + # Programmatic range edit emits native DOM input+change for keyboard / + # automation, using the exact same transaction and ACK fences. + editor.locator("#skDistance").evaluate("""n=>{ + n.value='5.0';n.dispatchEvent(new Event('input',{bubbles:true})); + n.dispatchEvent(new Event('change',{bubbles:true}));}""") + distance=last_action(page,"nativeSonKuSet") + assert distance["settings"]["spacePreset"]==2,distance + assert abs(distance["settings"]["sourceDistanceMeters"]-5.0)<.01,distance + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":distance["requestId"],"status":"APPLIED"}) + sceneState={**sceneState,"sourceDistanceMeters":5.0} + accepted_snapshot(page,state,sceneState,applied=distance["requestId"]) + editor.locator('[data-sk-room="1"]').click() + clamped=last_action(page,"nativeSonKuSet") + assert clamped["settings"]["spacePreset"]==1,clamped + assert clamped["settings"]["sourceDistanceMeters"]<=3.1,clamped + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":clamped["requestId"],"status":"APPLIED"}) + sceneState={**sceneState,"spacePreset":1, + "sourceDistanceMeters":clamped["settings"]["sourceDistanceMeters"]} + accepted_snapshot(page,state,sceneState,applied=clamped["requestId"]) + editor.locator('[data-sk-room="0"]').click() + off=last_action(page,"nativeSonKuSet") + assert off["settings"]["spacePreset"]==0,off + emit(page,"arMixBuiltinSonKuAck",{ + "requestId":off["requestId"],"status":"APPLIED"}) + accepted_snapshot(page,state,{**sceneState,"spacePreset":0}, + applied=off["requestId"]) + assert editor.locator("#skDistance").is_disabled() + assert editor.locator("#skAmbience").is_disabled() + assert editor.locator("#skReflections").is_disabled() + # Every remaining SonKu rotary (4/4 total) is tested with INPUT ALONE, + # not a synthetic input+change pair that could hide release-only audio. + sceneState={**sceneState,"spacePreset":0} + for control,value,key in [ + ("skSpeed",18.0,"revolutionSeconds"), + ("skSpread",45,"stereoSpreadDegrees"), + ("skMix",65,"spatialMix"), + ("skTrim",3.0,"outputTrim"), + ]: + before=command_count() + editor.locator("#"+control).evaluate("""(n,v)=>{ + n.value=String(v); + n.dispatchEvent(new Event('input',{bubbles:true})); + }""",value) + page.wait_for_timeout(58) + assert command_count()==before+1,(control,"no native edit on input") + cmd=last_action(page,"nativeSonKuSet") + assert cmd["settings"][key]!=sceneState[key],(control,cmd) + sceneState={**sceneState,key:cmd["settings"][key]} + applied_settings(cmd,sceneState) + # Committing an already-applied value must not create a duplicate + # SPSC native edit. + editor.locator("#"+control).evaluate( + "n=>n.dispatchEvent(new Event('change',{bubbles:true}))") + assert command_count()==before+1,(control,"duplicate final edit") + bounds=editor.bounding_box() + assert bounds and bounds["width"]>260 and bounds["width"]window.__ARMIX_NATIVE_M2__?.enabled") + state=snapshot() + # Use an exactly representable accepted -6 dB gain to prove the + # native coalescer's equality/no-op path emits no redundant intent. + state["graph"]["edges"][1]["gainLinear"]=10**(-6/20) + emit(page,"arMixConsoleSnapshot",state) + page.locator("#wireMatrixToggle").click() + route=page.locator('[data-ws-inspect="1:2"]') + route.wait_for(state="visible") + route.click() + slider=page.locator("#wireWsGain") + slider.wait_for(state="visible") + assert slider.is_enabled(),"Selected parallel SEND must allow native gain" + assert "PRIMARY" not in page.locator("#wireWsGainText").inner_text() + assert abs(float(slider.input_value())-(-6.0))<.11 + page.evaluate("()=>window.__heldInspectorGain=document.getElementById('wireWsGain')") + slider.focus() + slider.evaluate("""el=>{ + el.value='-12'; + el.dispatchEvent(new Event('input',{bubbles:true})); + }""") + assert page.locator("#wireWsGainText").inner_text()=="PENDING · -12 dB" + page.wait_for_function( + "()=>window.__nativeIntents.filter(x=>x.operation==='SET_WIRE_GAIN').length===1") + request=page.evaluate( + "()=>window.__nativeIntents.find(x=>x.operation==='SET_WIRE_GAIN')") + assert request["targetChannelId"]==SOURCE,request + assert request["payload"]["edgeId"]==SEND,request + assert abs(request["payload"]["gainLinear"]-10**(-12/20))<1e-8,request + emit(page,"arMixConsoleAck",{ + "requestId":request["requestId"],"status":"REJECTED", + "errorCode":"TEST_REJECTION","deviceEpoch":state["device"]["epoch"], + "graphRevision":state["graph"]["revision"], + "rosterRevision":state["graph"]["rosterRevision"]}) + # NO independent later snapshot is intentionally emitted. + # A rejected request cannot wait for one to repaint its LCD. + assert page.locator("#wireWsGainText").inner_text()=="UNCHANGED · -6 dB" + assert abs(float(slider.input_value())-(-6))<.11 + assert page.evaluate( + "()=>document.getElementById('wireWsGain')===window.__heldInspectorGain") + assert slider.evaluate("el=>document.activeElement===el"), ( + "Rejection must not drop keyboard focus on the original range input") + assert len(page.evaluate( + "()=>window.__nativeIntents.filter(x=>x.operation==='SET_WIRE_GAIN')"))==1 + assert abs(float(page.evaluate("""()=>{ + // EdgeId is allocated by the native graph projector; never assume 2. + const id=Number(document.getElementById('wireWsGain').dataset.wsGain); + return window.__ARMIX_NATIVE_SCOPE__.wireEdges.find(e=>e.id===id)?.levelDb; + }"""))-(-6))<.11 + # Requesting the exact same accepted -6 dB is a no-op: native must + # suppress redundant PCM writes AND settle the pending LCD by itself. + # No ACK, new snapshot or hidden user recovery action is available. + slider.evaluate("""el=>{ + el.value='-6'; + el.dispatchEvent(new Event('input',{bubbles:true})); + }""") + assert page.locator("#wireWsGainText").inner_text()=="PENDING · -6 dB" + page.wait_for_function("""()=>{ + return document.getElementById('wireWsGainText')?.textContent==='-6 dB'; + }""",timeout=5000) + assert len(page.evaluate( + "()=>window.__nativeIntents.filter(x=>x.operation==='SET_WIRE_GAIN')"))==1, ( + "Exact accepted gain no-op must not resend a native PCM command") + assert slider.evaluate("el=>document.activeElement===el") + assert not errors,errors + def verify_external_output(page, out): """Actual /preview/ native WebView: select -> native ACK -> callback readback. @@ -250,6 +330,9 @@ def main(): impact = browser.new_page(viewport={"width": 1366, "height": 768}) verify_socket_impact(impact, out) impact.close() + inspector_page = browser.new_page(viewport={"width":1366,"height":900}) + verify_inspector_rejected_gain(inspector_page,out) + inspector_page.close() output_page = browser.new_page(viewport={"width":1366,"height":900}) verify_external_output(output_page,out) output_page.close() @@ -287,7 +370,12 @@ def main(): page.wait_for_function("()=>window.__nativeIntents.length===2") assert page.evaluate("()=>window.__heldWireInput===document.querySelector('#tracks .strip[data-id=\"2\"] .wire-gain')"), "ACK detached held gain control" latest = page.evaluate("()=>window.__nativeIntents.at(-1)") - assert abs(latest["payload"]["gainLinear"] - .001) < 1e-8 + # Native SOF/WIRE policy defines the bottom -60 dB + # detent as -infinity/silence (linear zero), not 0.001. + # The exact SEND EdgeId is retained; this is a scalar + # mute-level gain, NEVER a graph REMOVE/disconnect. + assert latest["payload"]["gainLinear"] == 0, latest + assert latest["payload"]["edgeId"] == SEND, latest state["graph"]["edges"][1]["gainLinear"] = latest["payload"]["gainLinear"] ack(page, state, latest) emit(page, "arMixConsoleSnapshot", state) diff --git a/tests/device_independent_mixer_session_test.cpp b/tests/device_independent_mixer_session_test.cpp index 780c76216..af1ccdfc8 100644 --- a/tests/device_independent_mixer_session_test.cpp +++ b/tests/device_independent_mixer_session_test.cpp @@ -80,6 +80,41 @@ int main() { valid(track->sends.back().destination==stableMain && !track->sends.back().primaryOutput); + // SEND ON/OFF is a state of the exact parallel EdgeId, NOT removal. + // Primary OUT and a different edge may not be touched accidentally. + const auto sendEdge=track->sends.back().edgeId; + ChannelEdit off;off.kind=ChannelEdit::Kind::setSendEnabled; + off.id=backing;off.sendEdgeId=sendEdge;off.enabled=false; + auto toggled=logical.edit(logical.revision(), + std::span{&off,1}); + valid(toggled.accepted()); + track=logical.roster().find(backing); + valid(track->sends.size()==2 && !track->sends.back().enabled && + track->sends.back().gain==.25f && + track->sends.back().edgeId==sendEdge && + track->sends.front().primaryOutput && track->sends.front().enabled); + const auto revisionAfterOff=logical.revision(); + valid(!logical.edit(revisionAfterOff-1, + std::span{&off,1}).accepted()); + ChannelEdit wrong=off;wrong.sendEdgeId=serialEdge; + valid(!logical.edit(logical.revision(), + std::span{&wrong,1}).accepted()); + wrong.sendEdgeId=99999999; + valid(!logical.edit(logical.revision(), + std::span{&wrong,1}).accepted()); + valid(!logical.roster().find(backing)->sends.back().enabled); + // Restore retains disabled SEND identity and parameters without hardware. + DeviceIndependentMixerSession switched; + valid(switched.restore(logical.roster())); + const auto* swapped=switched.roster().find(backing); + valid(swapped && !swapped->sends.back().enabled && + swapped->sends.back().gain==.25f && swapped->sends.back().edgeId==sendEdge); + ChannelEdit on=off;on.enabled=true; + valid(logical.edit(logical.revision(), + std::span{&on,1}).accepted()); + valid(logical.roster().find(backing)->sends.back().enabled && + logical.roster().find(backing)->sends.back().edgeId==sendEdge); + // 4) SOURCE ONLY removes primary MAIN but leaves the strip and // its explicit parallel SEND. Removing the last send keeps the channel. ChannelEdit sourceOnly; @@ -124,6 +159,9 @@ int main() { ChannelEdit gain;gain.kind=ChannelEdit::Kind::setFader; gain.id=backing;gain.value=.5f; settings.push_back(gain); + ChannelEdit trim;trim.kind=ChannelEdit::Kind::setInputGain; + trim.id=backing;trim.value=2.f; + settings.push_back(trim); ChannelEdit pan;pan.kind=ChannelEdit::Kind::setPan; pan.id=backing;pan.value=-.2f; settings.push_back(pan); @@ -157,7 +195,8 @@ int main() { const auto* row=restored.roster().find(backing); valid(row && row->format==ProcessingFormat::mono && std::abs(row->faderLinear-.5f)<1.e-6f && - std::abs(row->pan+.2f)<1.e-6f && row->mute && row->solo && + std::abs(row->pan+.2f)<1.e-6f && row->inputGainLinear==2.f && + row->mute && row->solo && row->insertCatalogIds.size()==1 && row->insertCatalogIds.front()=="armix.builtin.channel-compressor.v1"); diff --git a/tests/dynamic_accepted_session_test.cpp b/tests/dynamic_accepted_session_test.cpp index de60b7740..ccba0566d 100644 --- a/tests/dynamic_accepted_session_test.cpp +++ b/tests/dynamic_accepted_session_test.cpp @@ -29,6 +29,171 @@ static ChannelEdit send(ChannelId from,ChannelId to,float gain,bool pre=false) { e.id=from;e.target=to;e.value=gain;e.preFader=pre;return e; } +// Real PCM SEND ON/OFF: mute one parallel edge without deleting the cable, +// changing its gain/tap, or affecting the source channel's MAIN contribution. +static void verifyPerEdgeSendEnablePcm() { + constexpr std::uint64_t epoch=9422; + DynamicAcceptedSession session; + DynamicGraphRequest req;req.physicalInputs=1;req.maxFrames=64; + const std::array channels{ + add(0,ChannelRole::input,"VOICE"), + add(1,ChannelRole::fxReturn,"WET",ProcessingFormat::stereo), + add(2,ChannelRole::main,"MAIN",ProcessingFormat::stereo) + }; + auto a=session.edit(0,0,channels,req,epoch,epoch,true); + assert(a.ok()); + const auto voice=a.edit.createdIds[0]; + const auto wet=a.edit.createdIds[1]; + const auto main=a.edit.createdIds[2]; + const std::array links{ + output(voice,main),output(wet,main),send(voice,wet,.5f,true) + }; + req.sources={{voice,0,-1,false}}; + a=session.edit(1,1,links,req,epoch,epoch,true); + assert(a.ok()); + const auto* row=session.acceptedRoster().find(voice); + assert(row && row->sends.size()==2); + const auto edge=std::find_if(row->sends.begin(),row->sends.end(), + [&](const auto& e){return e.destination==wet && !e.primaryOutput;}); + assert(edge!=row->sends.end() && edge->enabled); + const auto edgeId=edge->edgeId; + std::array input{},l{},r{};input.fill(.5f); + const float* pins[]{input.data()}; + const auto fx=+[](ChannelId,float*,float*,int) noexcept {}; + const auto render=[&](int frames=64){ + return session.render(epoch,pins,1,l.data(),r.data(),frames,false,fx); + }; + assert(render()); + const float withSend=l[63]; + assert(withSend>.35f); + ChannelEdit off;off.kind=ChannelEdit::Kind::setSendEnabled; + off.id=voice;off.sendEdgeId=edgeId;off.enabled=false; + const std::array disable{off}; + a=session.edit(2,2,disable,req,epoch,epoch,true); + assert(a.ok() && a.graphRevision==3); + row=session.acceptedRoster().find(voice); + const auto offEdge=std::find_if(row->sends.begin(),row->sends.end(), + [&](const auto& e){return e.edgeId==edgeId;}); + assert(offEdge!=row->sends.end() && !offEdge->enabled && + offEdge->gain==.5f && offEdge->preFader); + // Disabled SEND stores its prior gain; no accidental auto-enable. + assert(session.acceptedRoster().find(voice)->sends.back().gain==.5f); + assert(render()); + const float withoutSend=l[63]; + assert(withoutSend>.1f && withoutSend enable{on}; + a=session.edit(3,3,enable,req,epoch,epoch,true); + assert(a.ok() && a.graphRevision==4); + row=session.acceptedRoster().find(voice); + const auto onEdge=std::find_if(row->sends.begin(),row->sends.end(), + [&](const auto& e){return e.edgeId==edgeId;}); + assert(onEdge!=row->sends.end() && onEdge->enabled && + onEdge->gain==.5f && onEdge->preFader); + assert(render() && near(l[63],withSend,1e-4f)); + // Toggle the same EdgeId LIVE without a graph revision or WIRE removal. + assert(!session.setLiveSendEnabled(epoch-1,4,voice,edgeId,false)); + assert(!session.setLiveSendEnabled(epoch,3,voice,edgeId,false)); + assert(session.setLiveSendEnabled(epoch,4,voice,edgeId,false)); + assert(session.acceptedGraphRevision()==4); + assert(!session.acceptedRoster().find(voice)->sends.back().enabled); + const auto* accepted=session.acceptedRouting(epoch,4); + assert(accepted); + const auto routingEdge=std::find_if(accepted->edges.begin(),accepted->edges.end(), + [&](const auto& e){return e.edgeId==edgeId;}); + assert(routingEdge!=accepted->edges.end() && !routingEdge->enabled); + // Disabled SEND stores its prior gain; no accidental auto-enable. + assert(session.acceptedRoster().find(voice)->sends.back().gain==.5f); + assert(render(4)); + const float liveOff=l[3]; + assert(liveOff>withoutSend && liveOffsends.back().enabled); + assert(render(4) && l[3]>withoutSend && l[3].01f && truePre post{retap}; + a=session.edit(4,4,post,req,epoch,epoch,true); + assert(a.ok() && a.graphRevision==5); + row=session.acceptedRoster().find(voice); + const auto moved=std::find_if(row->sends.begin(),row->sends.end(), + [&](const auto& e){return e.edgeId==edgeId;}); + assert(moved!=row->sends.end() && !moved->preFader && + moved->enabled && moved->gain==.5f); + assert(render() && near(l[63],0.f,1e-5f)); + // Reject primary tap edits and keep the accepted revision/audio intact. + const auto primary=std::find_if(row->sends.begin(),row->sends.end(), + [&](const auto& e){return e.primaryOutput;}); + assert(primary!=row->sends.end()); + retap.sendEdgeId=primary->edgeId;retap.preFader=true; + const std::array illegal{retap}; + a=session.edit(5,5,illegal,req,epoch,epoch,true); + assert(!a.ok() && session.acceptedGraphRevision()==5); + assert(render() && near(l[63],0.f,1e-5f)); + session.unpublish();session.pollRetirement(); +} + +// Digital input trim must precede nonlinear FX, with callback-continuous +// sample smoothing and a stable ChannelId during live parameter changes. +static void verifyDigitalInputGainBeforeFxPcm() { + constexpr std::uint64_t epoch=9442; + DynamicAcceptedSession session; + DynamicGraphRequest req;req.physicalInputs=1;req.maxFrames=64; + const std::array setup{ + add(0,ChannelRole::input,"MIC"), + add(1,ChannelRole::main,"MAIN",ProcessingFormat::stereo) + }; + auto a=session.edit(0,0,setup,req,epoch,epoch,true); + assert(a.ok()); + const auto mic=a.edit.createdIds[0]; + const auto main=a.edit.createdIds[1]; + const std::array link{output(mic,main)}; + req.sources={{mic,0,-1,false}}; + a=session.edit(1,1,link,req,epoch,epoch,true); + assert(a.ok()); + std::array input{},l{},r{};input.fill(.25f); + const float* pins[]{input.data()}; + const auto square=[&](ChannelId ch,float* left,float* right,int n) noexcept { + if(ch!=mic)return; + for(int i=0;iinputGainLinear==2.f); + assert(render(4)); + assert(l[3]>original && l[3] change{rename}; + a=session.edit(2,2,change,req,epoch,epoch,true); + assert(a.ok() && session.acceptedRoster().find(mic)->inputGainLinear==2.f); + assert(render(64)); + assert(near(l[63],original*4.f,1e-4f)); + session.unpublish();session.pollRetirement(); +} + static void verifyRealtimeSlewAndNativeChannelIdContinuousControls() { using armix::dsp::RealtimeSlew64; // Sub-64 variable callbacks must not finish a 64-sample gesture in 4 @@ -919,6 +1084,8 @@ int main() { verifyConsoleWirePrimaryOutputPcm(); verifyRealtimeSlewAndNativeChannelIdContinuousControls(); + verifyPerEdgeSendEnablePcm(); + verifyDigitalInputGainBeforeFxPcm(); constexpr std::uint64_t epoch=77; constexpr float center=.7071067811865475f; DynamicAcceptedSession session; diff --git a/tests/guitar_fx_assets_contract.test.mjs b/tests/guitar_fx_assets_contract.test.mjs index 1839e1808..03de8f93a 100644 --- a/tests/guitar_fx_assets_contract.test.mjs +++ b/tests/guitar_fx_assets_contract.test.mjs @@ -74,11 +74,11 @@ test("native JUCE editor uses the generated binary resource identifiers",()=>{ assert(cmake.includes("ARMIX_GUITAR_SKIN_PNGS"),"GFX images are embedded"); assert(cmake.includes("juce_add_binary_data(ARMixAssets"),"one existing app resource target"); for(const name of [ - "amp-head-class-a.png", - "cabinet-dual-12.png", - "pedal-gate.png", - "pedal-overdrive.png", - "knob-brushed-metal.png" + "gfx-amp-head.png","gfx-cabinet.png", + "gfx-pedal-gate-body.png","gfx-pedal-drive-body.png", + "gfx-knob.png","gfx-switch-off.png","gfx-switch-on.png", + "gfx-button-off.png","gfx-button-on.png","gfx-panel.png", + "gfx-stomp-off.png","gfx-stomp-on.png" ]){ const id=name.replace(/\.png$/,"").replace(/[^A-Za-z0-9_]/g,"")+"_png"; assert(editor.includes("BinaryData::"+id),name+" correct generated JUCE identifier"); @@ -116,9 +116,11 @@ test("bypassed Guitar FX editor may enqueue tone without a live wet meter",()=>{ test("native hardware PNG decoding is cached across editor close/reopen",()=>{ const editor=readFileSync(resolve(root,"engine/builtin_fx/GuitarRigEditor.h"),"utf8"); - assert(editor.includes("static const std::array skins"), - "native editor must not decode all five PNG resources for every window"); - for(const key of ["amp_","cab_","gate_","pedal_","knob_"]) + assert(editor.includes("static const std::array skins"), + "native editor must cache all 12 layered PNG resources per app"); + for(const key of ["amp_","cab_","gate_","pedal_","knob_","switchOff_", + "switchOn_","buttonOff_","buttonOn_","panel_", + "stompOff_","stompOn_"]) assert(editor.includes(key+"=skins["),key+" shares cached image resource"); }); @@ -152,3 +154,70 @@ test("Guitar FX 2x polyphase processing preserves an authoritative fixed PDC",() assert(portable.includes("assert(aliasedThirdDb < -35.0)"), "folded 21kHz alias must remain a hard regression gate"); }); + +test("production guitar hardware is layered and old prototype art is not embedded",()=>{ + const cmake=readFileSync(resolve(root,"CMakeLists.txt"),"utf8"); + const editor=readFileSync(resolve(root,"engine/builtin_fx/GuitarRigEditor.h"),"utf8"); + assert(cmake.includes("build_guitar_fx_layered_assets.mjs")); + assert(cmake.includes("assets/gfx-*.png"), + "production binary must exclude deprecated old baked-footpedal PNGs"); + assert(editor.includes("juce::Rectangle knobBounds("), + "independent physical knob hit targets must follow artwork anchors"); + assert(editor.includes("stomp_.onClick=")&&editor.includes("power_[focus_].triggerClick()"), + "stomp must affect the same PCM program as the chain power toggle"); + assert(editor.includes("setLookAndFeel(&switchLook_)") && + editor.includes("setLookAndFeel(&buttonLook_)"), + "native controls must use the same layered material language"); + for(const path of ["pedalgate_png","pedaloverdrive_png","ampheadclassa_png"]) + assert(!editor.includes("BinaryData::"+path), + "obsolete baked bitmap must not be loaded: "+path); +}); +test("generated ON and OFF PNGs have byte-identical silhouettes and frame pixels",async()=>{ + const {SKINS,render}=await import("../scripts/build_guitar_fx_layered_assets.mjs"); + const decode=spec=>{ + const b=render(spec),w=b.readUInt32BE(16),h=b.readUInt32BE(20); + assert.equal(b[25],6,"RGBA PNG (not opaque image with fake black alpha)"); + let i=8,idat=[]; + while(iSKINS.find(s=>s[0]===name); + assert.equal(SKINS.length,12,"only active GFX modules and UI chrome"); + for(const [a,b] of [["gfx-switch-off.png","gfx-switch-on.png"], + ["gfx-button-off.png","gfx-button-on.png"], + ["gfx-stomp-off.png","gfx-stomp-on.png"]]){ + const A=decode(find(a)),B=decode(find(b)); + assert.equal(A.w,B.w);assert.equal(A.h,B.h); + let stateChanges=0; + for(let y=0;y.43: + x<8||x>=A.w-8||y<10||y>=A.h-10; + if(outside) + for(let c=0;c<4;c++)assert.equal(A.raw[offset+c],B.raw[offset+c], + "outer frame cannot flicker across ON/OFF"); + if(!outside&&A.raw[offset]!==B.raw[offset])stateChanges++; + } + assert(stateChanges>100,"state must visibly change while frame stays fixed"); + } + // These are true independent body PNGs, with empty wells. The only + // draggable controls are JUCE child widgets, not burned-in knob pixels. + for(const name of ["gfx-pedal-gate-body.png","gfx-pedal-drive-body.png"]){ + const body=decode(find(name)); + const x=Math.floor(body.w*.5),y=Math.floor(body.h*.82); + const k=y*(body.w*4+1)+1+x*4; + assert(body.raw[k]<75,"stomp well must not contain a baked shiny switch"); + } +}); diff --git a/tests/lms_native_draft_ack_readback_test.cpp b/tests/lms_native_draft_ack_readback_test.cpp new file mode 100644 index 000000000..b1b83a251 --- /dev/null +++ b/tests/lms_native_draft_ack_readback_test.cpp @@ -0,0 +1,134 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// One accepted native ChannelId PCM graph owns the speaker design admission. +// This test never opens, borrows, or writes an ASIO hardware output buffer. +#include "../engine/core/DynamicNativeSessionPublisher.h" +#if defined(NDEBUG) +#undef NDEBUG // Release/CTest must execute every safety assertion. +#endif +#include +#include +#include +#include +#include +using namespace armix::mixer; +using namespace armix::lms; + +static ChannelEdit create(int at,ChannelRole role,const char* name){ + ChannelEdit e; + e.kind=ChannelEdit::Kind::add;e.position=static_cast(at); + e.role=role;e.format=ProcessingFormat::stereo;e.text=name;return e; +} +static SpeakerSystemRequest design(std::uint64_t epoch,std::uint64_t graph){ + SpeakerSystemRequest s; + s.deviceEpoch=epoch;s.graphRevision=graph; + s.sampleRate=48000.;s.maxFrames=256; + s.activeOutputChannels=8;s.ways=2;s.stereo=true; + s.crossoverHz={1400.}; + for(int i=0;i<8;++i)s.verifiedPorts.push_back( + {"ASIO-DEVICE-IDENTITY:PIN-"+std::to_string(i),i}); + OutputPatch a,b; + a.outputId="HF-L";a.portIdentity=s.verifiedPorts[4].identity; + a.sourceSide=0;a.section=1;a.mute=true; + b.outputId="HF-R";b.portIdentity=s.verifiedPorts[6].identity; + b.sourceSide=1;b.section=1;b.mute=true; + s.outputs={a,b}; + return s; +} +static NativePcmOutputInventory actual(const SpeakerSystemRequest& s, + ChannelId main){ + NativePcmOutputInventory p; + p.deviceEpoch=s.deviceEpoch; + p.acceptedGraphRevision=s.graphRevision; + p.mainChannelId=main.value; + p.deviceIdentity="ASIO-DEVICE-IDENTITY"; + p.sampleRate=s.sampleRate; + p.callbackOutputs=s.activeOutputChannels; + p.mainL=0;p.mainR=1;p.monitorL=2;p.monitorR=3; + p.allOutputsDisarmed=true;p.acceptedChannelIdPcm=true; + p.enabledOutputPorts=s.verifiedPorts; + return p; +} +int main() { + constexpr std::uint64_t epoch=9876; + DynamicChannelRoster roster; + const std::array add{ + create(0,ChannelRole::input,"VOICE"), + create(1,ChannelRole::main,"MAIN") + }; + const auto made=roster.edit(0,add); + assert(made.ok()&&made.createdIds.size()==2); + const auto voice=made.createdIds[0],main=made.createdIds[1]; + ChannelEdit wire; + wire.kind=ChannelEdit::Kind::setPrimaryOutput;wire.id=voice;wire.target=main; + assert(roster.edit(roster.revision(),std::span(&wire,1)).ok()); + DynamicGraphRequest request; + request.physicalInputs=2;request.maxFrames=256; + request.sources={{voice,0,1,true}}; + DynamicNativeSessionPublisher native; + assert(native.commit(roster,request,0,epoch,epoch,true).ok()); + auto s=design(epoch,1); + auto p=actual(s,main); + auto accepted=native.acceptSpeakerDraft(s,p,main,0); + assert(accepted.ok()&&accepted.designRevision==1); + assert(!accepted.hardwareApplied&&accepted.preparedScratchBytes>0); + auto* read=native.speakerDraftReadback(epoch,1); + assert(read&&read->validatedDraft&&!read->hardwareApplied); + assert(read->designRevision==1&&read->graphRevision==1); + assert(read->deviceEpoch==epoch&&read->mainSource==main); + assert(read->reservedOutputOrdinals.size()==2); + assert(read->reservedOutputOrdinals[0]==4&&read->reservedOutputOrdinals[1]==6); + assert(read->design.crossoverHz==s.crossoverHz); + assert(read->design.outputs[0].portIdentity==s.outputs[0].portIdentity); + // Replay of stale browser revision cannot stomp the first acceptance. + const auto stale=native.acceptSpeakerDraft(s,p,main,0); + assert(stale.fault==DynamicNativeSessionPublisher::SpeakerDraftFault::staleDraft); + assert(stale.designRevision==1&&!stale.validatedDraft); + assert(native.speakerDraftReadback(epoch,1)->designRevision==1); + // Native source authority belongs to MAIN, never an arbitrary sender. + const auto notMain=native.acceptSpeakerDraft(s,p,voice,1); + assert(notMain.fault==DynamicNativeSessionPublisher::SpeakerDraftFault::invalidSource); + assert(native.speakerDraftReadback(epoch,1)->designRevision==1); + // Unsafe user unmute + checkbox limiter is not an approved protection. + s.outputs[0].mute=false; + s.outputs[0].limiterEnabled=true; + s.outputs[0].confirmedSpeakerProfile=true; + const auto unsafe=native.acceptSpeakerDraft(s,p,main,1); + assert(unsafe.fault==DynamicNativeSessionPublisher::SpeakerDraftFault::invalidReservation); + assert(unsafe.reservationFault==SpeakerReservationFault::unprotectedOutput); + assert(!unsafe.hardwareApplied); + assert(native.speakerDraftReadback(epoch,1)->designRevision==1); + s.outputs[0].mute=true; + // A physically occupied MAIN or MONITOR socket is not a speaker target. + s.outputs[0].portIdentity=s.verifiedPorts[0].identity; + const auto collision=native.acceptSpeakerDraft(s,p,main,1); + assert(collision.reservationFault==SpeakerReservationFault::occupiedOutput); + s.outputs[0].portIdentity=s.verifiedPorts[4].identity; + // Rejected DSP parameters cannot corrupt the accepted draft. + s.crossoverHz={30000.}; + const auto badFilter=native.acceptSpeakerDraft(s,p,main,1); + assert(badFilter.fault==DynamicNativeSessionPublisher::SpeakerDraftFault::invalidDsp); + assert(badFilter.planFault==SpeakerPlanFault::invalidCrossover); + s.crossoverHz={1800.}; + s.maxFrames=128; + const auto badQuantum=native.acceptSpeakerDraft(s,p,main,1); + assert(badQuantum.fault==DynamicNativeSessionPublisher::SpeakerDraftFault::invalidDsp); + s.maxFrames=256; + // Operator design revision advances ONLY after full validation and prep. + const auto updated=native.acceptSpeakerDraft(s,p,main,1); + assert(updated.ok()&&updated.designRevision==2); + assert(native.speakerDraftReadback(epoch,1)->design.crossoverHz[0]==1800.); + assert(!native.speakerDraftReadback(epoch+1,1)); + assert(!native.speakerDraftReadback(epoch,2)); + // Accepted structural PCM revision invalidates ALL previously prepared + // speaker state; even if driver output ordinals happen to be identical. + const auto nextGraph=native.commit(roster,request,1,epoch,epoch,true); + assert(nextGraph.ok()&&nextGraph.revision==2); + assert(!native.speakerDraftReadback(epoch,1)); + assert(!native.speakerDraftReadback(epoch,2)); + s.graphRevision=2;p.acceptedGraphRevision=2; + const auto fresh=native.acceptSpeakerDraft(s,p,main,0); + assert(fresh.ok()&&fresh.designRevision==1); + native.unpublish(); + assert(!native.speakerDraftReadback(epoch,2)); + std::puts("PASS LMS M5: same-native-PCM draft ACK/readback, revision rollback, pin safety, structural revoke, hardware disabled"); +} diff --git a/tests/lms_native_output_reservation_test.cpp b/tests/lms_native_output_reservation_test.cpp new file mode 100644 index 000000000..8b8437f87 --- /dev/null +++ b/tests/lms_native_output_reservation_test.cpp @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/lms/NativeSpeakerOutputReservation.h" +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include +#include +using namespace armix::lms; +static SpeakerSystemRequest speaker() { + SpeakerSystemRequest s; + s.deviceEpoch=13;s.graphRevision=28;s.sampleRate=48000.; + s.maxFrames=256;s.activeOutputChannels=8;s.ways=2;s.stereo=true; + s.crossoverHz={1200.}; + s.verifiedPorts={{"ASIO#EXACT/1",0},{"ASIO#EXACT/2",1}, + {"ASIO#EXACT/3",2},{"ASIO#EXACT/4",3}, + {"ASIO#EXACT/5",4},{"ASIO#EXACT/6",5}, + {"ASIO#EXACT/7",6},{"ASIO#EXACT/8",7}}; + OutputPatch p;p.outputId="LOW-L";p.portIdentity="ASIO#EXACT/5"; + p.sourceSide=0;p.section=0;p.mute=true; + s.outputs.push_back(p); + p.outputId="LOW-R";p.portIdentity="ASIO#EXACT/7";p.sourceSide=1; + s.outputs.push_back(p); + return s; +} +static NativePcmOutputInventory current() { + NativePcmOutputInventory i; + i.deviceEpoch=13;i.acceptedGraphRevision=28;i.mainChannelId=101; + i.deviceIdentity="DRIVER#EXACT";i.sampleRate=48000.; + i.callbackOutputs=8;i.mainL=0;i.mainR=1; + i.monitorL=2;i.monitorR=3;i.acceptedChannelIdPcm=true; + i.allOutputsDisarmed=true; + i.enabledOutputPorts=speaker().verifiedPorts; + return i; +} +static void gate() { + auto s=speaker();auto i=current(); + const auto ok=NativeSpeakerOutputReservation::preflight(s,i,101); + assert(ok.ok() && !ok.mayWritePhysicalAudio); + assert((ok.reservedCallbackOrdinals==std::vector{4,6})); + auto rejected=[&](SpeakerReservationFault fault) { + const auto r=NativeSpeakerOutputReservation::preflight(s,i,101); + assert(!r.ok()&&r.fault==fault&&!r.mayWritePhysicalAudio); + assert(r.reservedCallbackOrdinals.empty()); + }; + i.allOutputsDisarmed=false;rejected(SpeakerReservationFault::notAcceptedPcm); + i.allOutputsDisarmed=true; + i.acceptedChannelIdPcm=false;rejected(SpeakerReservationFault::notAcceptedPcm); + i.acceptedChannelIdPcm=true; + s.deviceEpoch=12;rejected(SpeakerReservationFault::staleDevice); + s.deviceEpoch=13; + s.graphRevision=27;rejected(SpeakerReservationFault::staleGraph); + s.graphRevision=28; + i.mainChannelId=999;rejected(SpeakerReservationFault::invalidSource); + i.mainChannelId=101; + s.sampleRate=96000.;rejected(SpeakerReservationFault::deviceLayoutMismatch); + s.sampleRate=48000.; + i.enabledOutputPorts[4].callbackOrdinal=5; + rejected(SpeakerReservationFault::unknownPort); + i.enabledOutputPorts[4].callbackOrdinal=4; + i.otherOccupiedOutputOrdinals={4}; + rejected(SpeakerReservationFault::occupiedOutput); + i.otherOccupiedOutputOrdinals.clear(); + s.outputs[0].portIdentity="ASIO#EXACT/3"; // MONITOR 2 + rejected(SpeakerReservationFault::occupiedOutput); + s.outputs[0].portIdentity="ASIO#EXACT/1"; // MAIN 0 + rejected(SpeakerReservationFault::occupiedOutput); + s.outputs[0].portIdentity="ASIO#EXACT/5"; + s.outputs[1].portIdentity="ASIO#EXACT/5"; // same pin twice + rejected(SpeakerReservationFault::occupiedOutput); + s.outputs[1].portIdentity="ASIO#EXACT/7"; + s.outputs[1].mute=false; + s.outputs[1].confirmedSpeakerProfile=true;s.outputs[1].limiterEnabled=true; + rejected(SpeakerReservationFault::unprotectedOutput); // hard clip is NOT speaker protection + s.outputs[1].mute=true; + const auto final=NativeSpeakerOutputReservation::preflight(s,i,101); + assert(final.ok()&&!final.mayWritePhysicalAudio); +} +int main() { + gate(); + std::puts("PASS LMS M3: exact native ChannelId/epoch/ASIO pin reservation, no hardware output authority"); +} diff --git a/tests/lms_native_postfx_main_witness_test.cpp b/tests/lms_native_postfx_main_witness_test.cpp new file mode 100644 index 000000000..441109539 --- /dev/null +++ b/tests/lms_native_postfx_main_witness_test.cpp @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// M4: End-to-end portable ChannelId post-FX MAIN -> real LMS DSP PCM witness. +// The 12 buffers below are isolated DIAGNOSTIC buffers, NOT ASIO output pins; +// the accepted native publisher performs the ONE graph render / VST dispatch. +#include "../engine/core/DynamicNativeSessionPublisher.h" +#include "../engine/lms/PreparedSpeakerSystem.h" +#include "../engine/lms/NativeSpeakerOutputReservation.h" +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace armix::mixer; +using namespace armix::lms; + +static std::atomic allocations{0}; +void* operator new(std::size_t n) { + allocations.fetch_add(1,std::memory_order_relaxed); + if(void* p=std::malloc(n?n:1)) return p; + throw std::bad_alloc(); +} +void* operator new[](std::size_t n) { + allocations.fetch_add(1,std::memory_order_relaxed); + if(void* p=std::malloc(n?n:1)) return p; + throw std::bad_alloc(); +} +// Keep the replacement deallocator opaque to GCC's unrelated vector-copy +// inliner; it falsely diagnoses custom malloc/new pairs as mismatched while +// the allocation counter still covers ALL global new/new[] calls. +#if defined(_MSC_VER) +__declspec(noinline) +#elif defined(__GNUC__) +__attribute__((noinline)) +#endif +static void releaseTracked(void* p) noexcept {std::free(p);} +void operator delete(void* p) noexcept {releaseTracked(p);} +void operator delete(void* p,std::size_t) noexcept {releaseTracked(p);} +void operator delete[](void* p) noexcept {releaseTracked(p);} +void operator delete[](void* p,std::size_t) noexcept {releaseTracked(p);} + +static ChannelEdit add(int index,ChannelRole role,const char* name) { + ChannelEdit e; + e.kind=ChannelEdit::Kind::add;e.position=static_cast(index); + e.role=role;e.format=ProcessingFormat::stereo;e.text=name;return e; +} +static ChannelEdit output(ChannelId from,ChannelId to) { + ChannelEdit e;e.kind=ChannelEdit::Kind::setPrimaryOutput; + e.id=from;e.target=to;return e; +} + +struct Witness { + static constexpr int maxFrames=256,activePins=12; + PreparedSpeakerSystem* speaker=nullptr; + std::uint64_t epoch=750,revision=1; + std::array,activePins> diagnostic{}; + std::array diagnosticPointers{}; + int observations=0; + bool processed=false; + Witness() { + for(int i=0;i(ctx); + ++self.observations; + self.processed=self.speaker->process(self.epoch,self.revision,left,right, + self.diagnosticPointers.data(),activePins,frames,true); + } +}; + +int main() { + constexpr auto epoch=750ULL; + DynamicNativeSessionPublisher native; + DynamicChannelRoster roster; + const std::array creates{ + add(0,ChannelRole::input,"VOICE"), + add(1,ChannelRole::main,"MAIN") + }; + const auto created=roster.edit(0,creates); + assert(created.ok() && created.createdIds.size()==2); + const auto voice=created.createdIds[0],main=created.createdIds[1]; + const ChannelEdit mainWire=output(voice,main); + assert(roster.edit(roster.revision(),std::span(&mainWire,1)).ok()); + DynamicGraphRequest request; + request.physicalInputs=2;request.maxFrames=Witness::maxFrames; + request.sources={{voice,0,1,true}}; + const auto accepted=native.commit(roster,request,0,epoch,epoch,true); + assert(accepted.ok() && accepted.revision==1); + assert(native.acceptedRouting(epoch,1)->find(voice)->primaryOutput==main); + + SpeakerSystemRequest settings; + settings.deviceEpoch=epoch;settings.graphRevision=1; + settings.sampleRate=48000.;settings.maxFrames=Witness::maxFrames; + settings.activeOutputChannels=Witness::activePins; + settings.stereo=true;settings.ways=4; + settings.crossoverHz={100.,1000.,6000.}; + for(int i=0;i dsp; + assert(PreparedSpeakerSystem::prepare(settings,dsp).ok()); + Witness witness;witness.speaker=dsp.get(); + DynamicNativeSessionPublisher::MainPcmObserver observer{ + &witness,&Witness::capture + }; + std::array inL{},inR{},mainL{},mainR{}; + std::array inputs{inL.data(),inR.data()}; + inL.fill(.2f);inR.fill(.05f); + // Physical pins supplied by an ASIO callback must NEVER be modified in + // M4 diagnostic witnessing (including MAIN, MONITOR and other BUS). + std::array,Witness::activePins> driver{}; + for(auto& pin:driver)pin.fill(.8125f); + int voiceFxCalls=0,mainFxCalls=0; + auto fx=[&](ChannelId id,float* l,float* r,int n) noexcept { + if(id==voice) { + ++voiceFxCalls; + for(int i=0;i 8 isolated crossover outputs, zero callback heap, no physical write"); +} diff --git a/tests/lms_prepared_speaker_pcm_test.cpp b/tests/lms_prepared_speaker_pcm_test.cpp new file mode 100644 index 000000000..cb9aefaac --- /dev/null +++ b/tests/lms_prepared_speaker_pcm_test.cpp @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/lms/PreparedSpeakerSystem.h" +#include +#ifdef NDEBUG +#undef NDEBUG // Always execute PCM assertions, even in release CTest. +#endif +#include +#include +#include +#include +#include +#include +using namespace armix::lms; +constexpr double pi=3.14159265358979323846; +SpeakerSystemRequest base(int ways=2,bool stereo=true) { + SpeakerSystemRequest r; + r.deviceEpoch=71;r.graphRevision=14; + r.sampleRate=48000.;r.maxFrames=256;r.activeOutputChannels=8; + r.ways=ways;r.stereo=stereo; + if(ways==2)r.crossoverHz={1000.}; + if(ways==3)r.crossoverHz={150.,2000.}; + if(ways==4)r.crossoverHz={80.,300.,2500.}; + r.verifiedPorts={{"ASIO#37/OUT-1",0},{"ASIO#37/OUT-3",2}, + {"ASIO#37/OUT-4",3},{"ASIO#37/OUT-6",5}, + {"ASIO#37/OUT-8",7}}; + return r; +} +OutputPatch patch(std::string id,std::string pin,int side,int way,double delay=0.) { + OutputPatch p; + p.outputId=std::move(id);p.portIdentity=std::move(pin); + p.sourceSide=side;p.section=way;p.delayMs=delay; + p.mute=false;p.limiterEnabled=true;p.ceilingDbfs=0.; + p.confirmedSpeakerProfile=true;return p; +} +std::unique_ptr prepared(const SpeakerSystemRequest& r) { + std::unique_ptr out; + const auto result=PreparedSpeakerSystem::prepare(r,out); + if(!result.ok()) { + std::cerr<<"prepare fault="<(result.fault)<<"\n"; + throw std::runtime_error("prepare failed"); + } + assert(out&&out->epoch()==r.deviceEpoch&&out->revision()==r.graphRevision); + assert(out->sectionCount()==static_cast(r.ways*(r.stereo?2:1))); + assert(out->destinationCount()==r.outputs.size()); + assert(out->scratchBytes()==result.scratchBytes); + return out; +} +struct Outputs { + std::vector> data; + std::vector raw; + explicit Outputs(int n):data(n,std::vector(256,0.f)){ + for(auto& d:data)raw.push_back(d.data()); + } +}; +void validate() { + auto r=base(); + auto kept=prepared(r); + auto reject=[&](SpeakerPlanFault fault){ + auto report=PreparedSpeakerSystem::prepare(r,kept); + assert(report.fault==fault); + assert(kept&&kept->revision()==14); + }; + r.deviceEpoch=0;reject(SpeakerPlanFault::invalidEpoch);r.deviceEpoch=71; + r.crossoverHz={30000.};reject(SpeakerPlanFault::invalidCrossover);r.crossoverHz={1000.}; + r.verifiedPorts[0].identity="DEMO-01";reject(SpeakerPlanFault::invalidPort); + r.verifiedPorts[0].identity="ASIO#37/OUT-1"; + r.outputs={patch("low","invalid",0,0)};reject(SpeakerPlanFault::invalidPort); + r.outputs={patch("low","ASIO#37/OUT-1",0,5)};reject(SpeakerPlanFault::invalidRoute); + r.outputs={patch("low","ASIO#37/OUT-1",0,0),patch("low2","ASIO#37/OUT-1",0,0)}; + reject(SpeakerPlanFault::duplicatePort); + r.outputs={patch("low","ASIO#37/OUT-1",0,0)}; + r.outputs[0].limiterEnabled=false;reject(SpeakerPlanFault::unconfirmedSpeaker); + r.outputs[0].mute=true;r.outputs[0].confirmedSpeakerProfile=false; + assert(prepared(r)->sectionCount()==4); + r.outputs[0].delayMs=600.;reject(SpeakerPlanFault::invalidOutputDsp); + r.outputs[0].delayMs=500.;r.scratchBudgetBytes=512; + reject(SpeakerPlanFault::scratchBudget); + r=base();r.verifiedPorts[1].callbackOrdinal=0; + reject(SpeakerPlanFault::invalidPort); +} +void frequency(double hz,double low,double high) { + auto r=base(); + r.outputs={patch("low L","ASIO#37/OUT-1",0,0), + patch("high L","ASIO#37/OUT-3",0,1), + patch("low R","ASIO#37/OUT-4",1,0), + patch("high R","ASIO#37/OUT-6",1,1)}; + auto system=prepared(r); + std::array left{},right{}; + Outputs output(8); + double sumLo=0.,sumHi=0.,sumInput=0.,sumCombined=0.; + for(int block=0;block<400;++block){ + for(int i=0;i<256;++i){ + const double t=static_cast(block*256+i)/r.sampleRate; + left[i]=static_cast(.25*std::sin(2*pi*hz*t)); + right[i]=left[i]*.5f; + } + assert(system->process(71,14,left.data(),right.data(),output.raw.data(),8,256,true)); + if(block<15)continue; + for(int i=0;i<256;++i){ + const double lo=output.data[0][i],hi=output.data[2][i]; + sumLo+=lo*lo;sumHi+=hi*hi;sumInput+=left[i]*left[i]; + sumCombined+=(lo+hi)*(lo+hi); + assert(std::abs(output.data[3][i]-lo*.5)<.00001); + assert(std::abs(output.data[5][i]-hi*.5)<.00001); + } + } + const auto measuredLow=std::sqrt(sumLo/sumInput); + const auto measuredHigh=std::sqrt(sumHi/sumInput); + const auto summed=std::sqrt(sumCombined/sumInput); + std::cout<<"LR4 "< source{};source.fill(.25f); + assert(!system->process(72,14,source.data(),nullptr,out.raw.data(),8,256,true)); + assert(!system->process(71,15,source.data(),nullptr,out.raw.data(),8,256,true)); + assert(!system->process(71,14,source.data(),nullptr,out.raw.data(),8,257,true)); + assert(!system->process(71,14,source.data(),nullptr,out.raw.data(),8,256,false)); + for(const auto sample:out.data[0])assert(sample==0.f); + std::fill(out.data[0].begin(),out.data[0].end(),.25f); + assert(system->process(71,14,out.raw[0],nullptr,out.raw.data(),8,256,true)); + assert(std::abs(out.data[2][100])<.2f); + for(const auto& lane:out.data)for(const auto sample:lane)assert(std::isfinite(sample)); +} +void delay_fanout_and_mute() { + auto r=base(1,false); + r.outputs={patch("dry","ASIO#37/OUT-1",0,0), + patch("delayed","ASIO#37/OUT-3",0,0,1.5/48.)}; + auto system=prepared(r); + Outputs out(8); + std::array impulse{};impulse[0]=.5f; + assert(system->process(71,14,impulse.data(),nullptr,out.raw.data(),8,256,true)); + assert(std::abs(out.data[0][0]-.5f)<1e-6f); + assert(std::abs(out.data[2][0])<1e-6f); + assert(std::abs(out.data[2][1]-.25f)<1e-6f); + assert(std::abs(out.data[2][2]-.25f)<1e-6f); + r.outputs[0].mute=true;r.outputs[0].limiterEnabled=false; + auto muted=prepared(r); + std::fill(out.data[0].begin(),out.data[0].end(),9.f); + assert(muted->process(71,14,impulse.data(),nullptr,out.raw.data(),8,256,true)); + for(const auto sample:out.data[0])assert(sample==0.f); +} +void digital_ceiling() { + auto r=base(1,false); + r.outputs={patch("full","ASIO#37/OUT-1",0,0)}; + r.outputs[0].gainDb=6.;r.outputs[0].ceilingDbfs=-12.; + auto system=prepared(r); + Outputs out(8); + std::array in{};in.fill(1.f); + assert(system->process(71,14,in.data(),nullptr,out.raw.data(),8,256,true)); + const float ceiling=static_cast(std::pow(10.,-12./20.)); + for(const float sample:out.data[0])assert(sample<=ceiling+1.e-6f); +} +void per_output_peq() { + auto r=base(1,false); + r.outputs={patch("peq","ASIO#37/OUT-1",0,0)}; + r.outputs[0].peq.push_back({1000.,1.,6.}); + auto system=prepared(r); + Outputs out(8); + std::array in{}; + double inPower=0.,outPower=0.; + for(int block=0;block<200;++block){ + for(int i=0;i<256;++i){ + const double time=(block*256+i)/48000.; + in[i]=static_cast(.1*std::sin(2*pi*1000.*time)); + } + assert(system->process(71,14,in.data(),nullptr,out.raw.data(),8,256,true)); + if(block<10)continue; + for(int i=0;i<256;++i){ + inPower+=in[i]*in[i]; + outPower+=out.data[0][i]*out.data[0][i]; + } + } + const auto gain=std::sqrt(outPower/inPower); + assert(gain>1.93&&gain<2.07); // 6 dB peaking EQ, true PCM + r.outputs[0].peq[0].q=0.; + std::unique_ptr rejected=std::move(system); + const auto bad=PreparedSpeakerSystem::prepare(r,rejected); + assert(bad.fault==SpeakerPlanFault::invalidOutputDsp); + assert(rejected&&rejected->destinationCount()==1); // rollback +} + +void polarity_and_eq_band_bypass() { + auto req=base(1,false); + req.outputs={patch("polarity","ASIO#37/OUT-1",0,0), + patch("eq-bypass","ASIO#37/OUT-3",0,0)}; + req.outputs[0].polarityInverted=true; + req.outputs[1].peq.push_back({1000.,1.,6.,false}); + auto system=prepared(req); + Outputs out(8); + std::array input{}; + input.fill(.2f); + assert(system->process(71,14,input.data(),nullptr,out.raw.data(),8,256,true)); + for(int i=0;i<256;++i) { + assert(std::abs(out.data[0][i]+.2f)<.00001f); + assert(std::abs(out.data[2][i]-.2f)<.00001f); + } + assert(out.data[0][255]<0.f&&out.data[2][255]>0.f); + // A bypassed 6 dB EQ must not retain DSP state or affect any channel. + // Verify enabled band peak is about +6 dB after the biquad settles. + req.outputs[0].peq.clear(); + req.outputs[1].peq[0].enabled=true; + system=prepared(req); + double energyIn=0.,energyOut=0.; + for(int block=0;block<100;++block) { + for(int i=0;i<256;++i) { + const double time=static_cast(block*256+i)/req.sampleRate; + input[i]=static_cast(.05*std::sin(2*pi*1000.*time)); + } + assert(system->process(71,14,input.data(),nullptr,out.raw.data(),8,256,true)); + if(block>10)for(int i=0;i<256;++i) { + energyIn+=input[i]*input[i]; + energyOut+=out.data[2][i]*out.data[2][i]; + } + } + const auto measured=std::sqrt(energyOut/energyIn); + assert(measured>1.93&&measured<2.07); +} +int main(){ + validate(); + frequency(100.,1.,0.); + frequency(1000.,.5,.5); + frequency(10000.,0.,1.); + hardware_guard_and_alias();delay_fanout_and_mute();digital_ceiling();per_output_peq();polarity_and_eq_band_bypass(); + for(int ways=1;ways<=4;++ways) + assert(prepared(base(ways))->sectionCount()==static_cast(2*ways)); + std::cout<<"PASS LMS prepared PCM: LR4, routing, epoch, DSP and delay\n"; +} diff --git a/tests/lms_synthetic_realtime_budget_test.cpp b/tests/lms_synthetic_realtime_budget_test.cpp new file mode 100644 index 000000000..d44111a69 --- /dev/null +++ b/tests/lms_synthetic_realtime_budget_test.cpp @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Synthetic audio-thread allocation/performance fixture; never ASIO FAT proof. +#include "../engine/lms/PreparedSpeakerSystem.h" +#include +#include +#ifdef NDEBUG +#undef NDEBUG // Always execute PCM assertions, even in release CTest. +#endif +#include +#include +#include +#include +#include +#include +#include +static std::atomic allocations{0}; +void* operator new(std::size_t n){ + ++allocations; + if(void* p=std::malloc(n))return p; + throw std::bad_alloc(); +} +void* operator new[](std::size_t n){ + ++allocations; + if(void* p=std::malloc(n))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);} +int main(){ + using namespace armix::lms; + SpeakerSystemRequest r; + r.deviceEpoch=1;r.graphRevision=1;r.sampleRate=48000.; + r.maxFrames=256;r.activeOutputChannels=16;r.ways=4;r.stereo=true; + r.crossoverHz={80.,300.,2500.}; + for(int i=0;i<8;++i){ + const auto pin="DRIVER#A/"+std::to_string(i); + r.verifiedPorts.push_back({pin,i}); + OutputPatch o; + o.outputId="speaker-"+std::to_string(i);o.portIdentity=pin; + o.sourceSide=i/4;o.section=i%4;o.delayMs=i*2.; + o.mute=false;o.limiterEnabled=true; + o.confirmedSpeakerProfile=true;o.ceilingDbfs=-3.; + o.peq={{120.,1.1,2.},{800.,.75,-3.},{3500.,1.2,1.5}}; + r.outputs.push_back(o); + } + std::unique_ptr graph; + assert(PreparedSpeakerSystem::prepare(r,graph).ok()); + std::array sourceL{},sourceR{}; + std::vector> output(16,std::vector(256)); + std::array pointers{}; + for(int i=0;i<16;++i)pointers[i]=output[i].data(); + for(int i=0;i<256;++i){ + sourceL[i]=std::sin(static_cast(i)*.05f)*.3f; + sourceR[i]=std::cos(static_cast(i)*.07f)*.3f; + } + assert(graph->process(1,1,sourceL.data(),sourceR.data(),pointers.data(),16,256,true)); + const auto before=allocations.load(); + const auto started=std::chrono::steady_clock::now(); + for(int block=0;block<1500;++block) + assert(graph->process(1,1,sourceL.data(),sourceR.data(),pointers.data(),16,256,true)); + const auto micros=std::chrono::duration_cast( + std::chrono::steady_clock::now()-started).count(); + assert(allocations.load()==before); + for(int c=0;c<8;++c)for(float sample:output[c]) + assert(std::isfinite(sample)&&std::abs(sample)<1.001f); + std::cout<<"PASS LMS: 8 output, stereo 4-way, 1500 x 256 PCM frames, " + <<"no realtime heap, synthetic duration "<{ + const s=M.createSystem({ways:3,ports:M.demoPorts(6)}); + assert.deepEqual(s.sections.map(x=>x.name),[ + "LOW L","MID L","HIGH L","LOW R","MID R","HIGH R"]); + assert.deepEqual(s.routes,{}); + assert.equal(s.applied,false); + for(const p of s.ports){ + assert.equal(s.dsp[p].muted,true); + assert.equal(s.dsp[p].limiterEnabled,false); + assert.equal(s.dsp[p].limiterThresholdDb,null); + } + assert.equal(M.validateSystem(s),true); +}); + +test("crossover ways are flexible and structural change clears ALL patch/output safety drafts",()=>{ + const s=M.createSystem({ways:2,ports:M.demoPorts(4)}); + const mapped=M.withRoute(s,s.ports[0],"L:1"); + const edited=M.withDsp(mapped,s.ports[0],{gainDb:-6,muted:false}); + const next=M.withWays(edited,3); + assert.equal(next.sections.length,6); + assert.equal(next.ports.length,4); + assert.deepEqual(next.routes,{}); + assert.equal(next.dsp[s.ports[0]].gainDb,0); + assert.equal(next.dsp[s.ports[0]].muted,true); + assert.equal(next.applied,false); + assert.equal(edited.ways,2); // immutable transaction, old accepted draft intact + assert.equal(edited.routes[s.ports[0]],"L:1"); + const sixteen=M.withWays(next,16); + assert.equal(sixteen.sections.length,32); + assert.equal(sixteen.cutoffsHz.length,15); + assert.equal(M.validateSystem(sixteen),true); +}); + +test("routing one output is exclusive; one source may fan out to multiple destinations",()=>{ + let s=M.createSystem({ways:3,ports:M.demoPorts(6)}); + s=M.withRoute(s,"DEMO-01","L:1"); + s=M.withRoute(s,"DEMO-02","L:1"); + assert.equal(s.routes["DEMO-02"],"L:1"); + s=M.withRoute(s,"DEMO-01","L:2"); + assert.equal(s.routes["DEMO-01"],"L:2"); + assert.equal(Object.keys(s.routes).length,2); + s=M.withRoute(s,"DEMO-01","L:2"); // clicking active crosspoint disconnects + assert.equal(s.routes["DEMO-01"],undefined); + assert.throws(()=>M.withRoute(s,"DEMO-01","L:55"),/unknown crossover/); + assert.throws(()=>M.withRoute(s,"ASIO 1","L:1"),/unknown output/); +}); + +test("port discovery changes never silently reuse ordinal pin assignments",()=>{ + let s=M.createSystem({ways:2,ports:["device-A#1","device-A#2"]}); + s=M.withRoute(s,"device-A#1","L:1"); + s=M.withPorts(s,["device-B#1","device-B#2"]); + assert.deepEqual(s.routes,{}); + assert.equal(s.dsp["device-B#1"].muted,true); + assert.equal(s.ports[0],"device-B#1"); + assert.equal(s.applied,false); + assert.throws(()=>M.createSystem({ports:["same","same"]}),/duplicate/); +}); + +test("boundaries must be ordered and physically plausible; invalid edit rolls back",()=>{ + const s=M.createSystem({ways:3}); + assert.deepEqual(s.cutoffsHz,[120,2400]); + const edited=M.withCutoff(s,1,3000); + assert.deepEqual(edited.cutoffsHz,[120,3000]); + assert.deepEqual(s.cutoffsHz,[120,2400]); + assert.throws(()=>M.withCutoff(s,0,3000),/strictly ordered/); + assert.throws(()=>M.withCutoff(s,0,Infinity),/crossover frequency/); + assert.throws(()=>M.withCutoff(s,0,0),/crossover frequency/); +}); + +test("visual distance alignment returns additional geometric delay for nearer speaker",()=>{ + let s=M.createSystem({ways:1,ports:["far","near"]}); + s=M.withListener(s,0,0); + s=M.withPosition(s,"far",0,20); + s=M.withPosition(s,"near",0,10); + const values=M.alignment(s); + assert.equal(values[0].additionalMs,0); + assert.ok(Math.abs(values[1].additionalMs-10000/343)<1e-8); + assert.equal(values[1].distanceM,10); + assert.equal(s.dsp.near.delayMs,0); // cannot silently write acoustic estimate + assert.throws(()=>M.withPosition(s,"near",NaN,0),/speaker x/); +}); + +test("output DSP is bounded, muted by default and never grants hardware authority",()=>{ + const s=M.createSystem({ports:["out1"]}); + const next=M.withDsp(s,"out1",{gainDb:-3,limiterThresholdDb:-12}); + assert.equal(next.dsp.out1.limiterEnabled,false); + assert.equal(next.applied,false); + assert.throws(()=>M.withDsp(s,"out1",{gainDb:30}),/gainDb/); + assert.throws(()=>M.withDsp(s,"out1",{limiterThresholdDb:3}),/limiterThresholdDb/); + assert.throws(()=>M.withDsp(s,"out1",{unsafeHardwareEnable:true}),/unknown DSP/); +}); + + +test("native-calculated LR4 amplitude response is complementary at split",()=>{ + const low=M.crossoverMagnitude([1000],0,1000); + const high=M.crossoverMagnitude([1000],1,1000); + assert.ok(Math.abs(low-.5)<.002,(low).toString()); + assert.ok(Math.abs(high-.5)<.002,(high).toString()); + assert.ok(M.crossoverMagnitude([1000],0,100)>.99); + assert.ok(M.crossoverMagnitude([1000],1,100)<.01); + assert.throws(()=>M.crossoverMagnitude([1000],0,25000),/plot request/); +}); + +test("EQ band state and graph match native RBJ peak filter math",()=>{ + const original=M.createSystem({ways:2,ports:["port"]}); + const edited=M.withPeqBand(original,"port",0, + {frequencyHz:1000,q:1,gainDb:6,enabled:true}); + assert.equal(original.dsp.port.peq.length,0); + assert.equal(edited.dsp.port.peq[0].gainDb,6); + const atPeak=M.peqMagnitude(edited.dsp.port.peq,1000); + assert.ok(Math.abs(atPeak-6)<.01,atPeak.toString()); + assert.equal(M.peqMagnitude([{...edited.dsp.port.peq[0],enabled:false}],1000),0); + assert.throws(()=>M.withPeqBand(edited,"port",1,{q:0}),/PEQ Q/); + assert.throws(()=>M.withPeqBand(edited,"port",2,{}),/PEQ gap/); + assert.throws(()=>M.withPeqBand(edited,"port",1,{notAllowed:1}),/unknown PEQ/); + const removed=M.withoutPeqBand(edited,"port",0); + assert.deepEqual(removed.dsp.port.peq,[]); + assert.equal(removed.applied,false); +}); + +test("visual alignment explicitly copies geometric offsets to disconnected drafts",()=>{ + let s=M.createSystem({ways:2,ports:["far","near"]}); + s=M.withListener(s,0,0); + s=M.withPosition(s,"far",0,30); + s=M.withPosition(s,"near",0,10); + const prior=s; + const planned=M.withSuggestedDelays(s); + assert.equal(prior.dsp.near.delayMs,0); + assert.equal(planned.dsp.far.delayMs,0); + assert.ok(Math.abs(planned.dsp.near.delayMs-58.31)<.015); + assert.equal(planned.applied,false); + assert.deepEqual(planned.routes,{}); + assert.equal(planned.dsp.near.muted,true); + const waysChanged=M.withWays(planned,3); + assert.equal(waysChanged.dsp.near.delayMs,0); +}); + +test("real five-workspace interactions show curves, PEQ and review rather than applying",()=>{ + const fs=require("node:fs"); + const ui=fs.readFileSync(require.resolve("../site/preview-v2/assets/lms-workspace.js"),"utf8"); + const callbacks={root:{},launcher:{}}; + const root={dataset:{},hidden:true,innerHTML:"", + addEventListener(type,fn){callbacks.root[type]=fn}}; + const launcher={addEventListener(type,fn){callbacks.launcher[type]=fn}, + setAttribute(k,v){this[k]=v},textContent:""}; + const app={classList:{toggle(){}}}; + const document={getElementById(id){return id==="lmsWorkspace"?root: + id==="lmsOpen"?launcher:null}, + querySelector(q){return q===".app"?app:null}}; + const window={ArSonMixLmsModel:M,addEventListener(){}}; + new Function("window","document",ui)(window,document); + const click=dataset=>callbacks.root.click({target:{closest:()=>({dataset})}}); + callbacks.launcher.click(); + assert.ok(root.innerHTML.includes("Speaker system")); + click({page:"crossover"}); + assert.ok(root.innerHTML.includes("LR4 · 24 dB/oct")); + assert.ok(root.innerHTML.includes("Calculated electrical LR4")); + click({page:"processing"}); + assert.ok(root.innerHTML.includes("Parametric EQ")); + click({action:"addPeq"}); + assert.ok(root.innerHTML.includes("EQ 1")); + callbacks.root.change({target:{dataset:{peqField:"gainDb"},value:"6"}}); + assert.ok(root.innerHTML.includes("6.0 dB")); + click({dspTab:"protection"}); + assert.ok(root.innerHTML.includes("NOT CALIBRATED")); + click({page:"alignment"}); + assert.ok(root.innerHTML.includes("Suggested")); + click({action:"planDelay"}); + assert.ok(root.innerHTML.includes("Review structural change")); + click({action:"cancel"}); + assert.ok(!root.innerHTML.includes("Review structural change")); + click({action:"planDelay"}); + click({action:"confirm"}); + assert.ok(root.innerHTML.includes("revision ")); + assert.ok(root.innerHTML.includes("Not applied to audio")); + assert.equal(launcher["aria-pressed"],"true"); +}); diff --git a/tests/m3e_fat_evidence_gate.test.mjs b/tests/m3e_fat_evidence_gate.test.mjs index fecf478ad..abb7680bf 100644 --- a/tests/m3e_fat_evidence_gate.test.mjs +++ b/tests/m3e_fat_evidence_gate.test.mjs @@ -72,6 +72,42 @@ test('no captured hardware record is PENDING, even if package hashes/PE match',( assert.equal(r.hardwareCertified,false);assert.equal(r.releaseReady,false); }finally{clean(d);} }); +test('exact field preview package is integrity-verified but NEVER a public FAT approval',()=>{ + const d=makeTemp();try{ + const p=makePackage(d); + p.m.fatStatus='FIELD_PREVIEW_FULL_CTEST_NOT_RUN';p.save(); + const verified=inspectM3ePackage(d); + assert.equal(verified.build,'EXE_AND_FAT_BYTES_VERIFIED'); + assert.equal(verified.softwareQualification,'FIELD_PREVIEW_FULL_CTEST_NOT_RUN'); + const assessment=assessM3eFat(d); + assert.equal(assessment.build,'EXE_AND_FAT_BYTES_VERIFIED'); + assert.equal(assessment.softwareQualification,'FIELD_PREVIEW_FULL_CTEST_NOT_RUN'); + assert.equal(assessment.nativePcm,'PENDING_NATIVE_CALLBACK_PROOF'); + assert.equal(assessment.physical,'PENDING'); + assert.equal(assessment.releaseReady,false); + assert.equal(assessment.hardwareCertified,false); + assert.match(assessment.blockers.join(' '),/No physical FAT_RUNS.json/); + // Both package modes must independently attest the same EXE and tools. + writeFileSync(join(d,'collect_hardware_fat_windows.ps1'),'tampered'); + assert.equal(assessM3eFat(d).build,'BLOCKED'); + assert.match(assessM3eFat(d).blockers.join(' '),/SHA256 mismatch/); + }finally{clean(d);} +}); + +test('unknown, blank or forged software qualification claims remain fail-closed',()=>{ + const d=makeTemp();try{ + const p=makePackage(d); + for(const value of ['','FULL_CTEST_PASS','HARDWARE_CERTIFIED', + 'FIELD_PREVIEW_FULL_CTEST_NOT_RUN_EXTRA',null]){ + p.m.fatStatus=value;p.save(); + assert.equal(assessM3eFat(d).build,'BLOCKED',String(value)); + } + p.m.fatStatus='SOFTWARE_VERIFIED_PREVIEW_CANDIDATE';p.save(); + assert.equal(inspectM3ePackage(d).softwareQualification, + 'SOFTWARE_VERIFIED_PREVIEW_CANDIDATE'); + }finally{clean(d);} +}); + test('native PE target, original package SHA and approved GUI are required',()=>{ const d=makeTemp();try{ const p=makePackage(d); @@ -200,6 +236,27 @@ test('BOM does not weaken malformed-journal rejection or source SHA pinning',()= }finally{clean(d);} }); +test('Windows offline FAT collector accepts attested FIELD preview, rejects invented qualification',()=>{ + if(process.platform!=='win32')return; + const d=makeTemp();try{ + const p=makePackage(d); + const collector=readFileSync('scripts/collect_hardware_fat_windows.ps1'); + const collectorPath=join(d,'collect_hardware_fat_windows.ps1'); + writeFileSync(collectorPath,collector); + p.m.fatCollectorSha256=sha(collector); + const verify=()=>execFileSync('powershell.exe',[ + '-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass', + '-File',collectorPath,'-Action','Verify' + ],{cwd:d,timeout:30000,encoding:'utf8'}); + p.m.fatStatus='FIELD_PREVIEW_FULL_CTEST_NOT_RUN';p.save(); + assert.doesNotThrow(verify); + p.m.fatStatus='HARDWARE_CERTIFIED';p.save(); + assert.throws(verify,/Unexpected or unapproved software qualification status/); + p.m.fatStatus='SOFTWARE_VERIFIED_PREVIEW_CANDIDATE';p.save(); + assert.doesNotThrow(verify); + }finally{clean(d);} +}); + test('PowerShell Summary validates 44.1/48 kHz real start/end duration rather than a forged 30-minute field',()=>{ if(process.platform!=='win32')return; const d=makeTemp();try{ diff --git a/tests/mixer_routing_plan_test.cpp b/tests/mixer_routing_plan_test.cpp index 248df8046..888108e35 100644 --- a/tests/mixer_routing_plan_test.cpp +++ b/tests/mixer_routing_plan_test.cpp @@ -10,6 +10,7 @@ #endif #include #include +#include #include using namespace armix::mixer; @@ -1015,7 +1016,165 @@ static void verifyDynamicInPlacePhysicalIOBuffers() { assert(host.acceptedRevision()==1); } +// The native graph must apply DIGITAL INPUT GAIN before the real FX callback, +// not after FX, and never alias the channel fader or rebuild WIRE topology. +static void verifyNativeInputGainBeforeFx() { + using Kind=ChannelEdit::Kind; + DynamicChannelRoster roster; + std::array create{}; + create[0].kind=Kind::add;create[0].position=0; + create[0].role=ChannelRole::input;create[0].text="Mic"; + create[1].kind=Kind::add;create[1].position=1; + create[1].role=ChannelRole::main;create[1].format=ProcessingFormat::stereo; + create[1].text="MAIN"; + // Preserve the golden microphone equal-power PAN without adding an + // unrelated second mono-pan attenuation on the MAIN sink. + const auto added=roster.edit(0,create); + assert(added.ok()); + const auto mic=added.createdIds[0],main=added.createdIds[1]; + ChannelEdit out{};out.kind=Kind::setPrimaryOutput;out.id=mic;out.target=main; + assert(roster.edit(roster.revision(),std::span(&out,1)).ok()); + DynamicGraphRequest req;req.physicalInputs=1;req.maxFrames=64; + req.sources={{mic,0,-1,false}}; + DynamicNativeSessionPublisher host; + const auto committed=host.commit(roster,req,0,777,777,true); + assert(committed.ok()&&committed.revision==1); + std::array input{},left{},right{};input.fill(.25f); + const float* physical[]={input.data()}; + // A genuine nonlinear processor distinguishes input-before-FX from + // gain-after-FX. FX runs once regardless of the extra gain stage. + int calls=0; + const auto fx=[&](ChannelId id,float* l,float* r,int frames) noexcept { + if(id!=mic)return; + ++calls; + for(int i=0;i.4f?1.f:0.f;l[i]=v;r[i]=v; + } + }; + const auto render=[&](){return host.render(777,physical,1, + left.data(),right.data(),64,false,fx);}; + assert(render()&&close(left[63],0.f)); + assert(host.setChannelInputGain(777,1,mic,2.f)); + assert(!host.setChannelInputGain(778,1,mic,1.f)); + assert(!host.setChannelInputGain(777,0,mic,1.f)); + assert(!host.setChannelInputGain(777,1,main,2.f)); + assert(!host.setChannelInputGain(777,1,mic,-1.f)); + assert(!host.setChannelInputGain(777,1,mic, + std::numeric_limits::quiet_NaN())); + assert(render()); + constexpr float center=.7071067811865475f; + assert(close(left[63],center,1.e-4f)); + assert(host.acceptedRevision()==1 && calls==2); + assert(host.setChannelInputGain(777,1,mic,1.f)); + assert(render()&&close(left[63],0.f)); + // The accepted roster retains the same ChannelId, fader and WIRE after + // a control-thread digital gain edit; restore/recompile seeds it. + ChannelEdit gain{};gain.kind=Kind::setInputGain;gain.id=mic;gain.value=2.f; + assert(roster.edit(roster.revision(),std::span(&gain,1)).ok()); + assert(close(roster.find(mic)->inputGainLinear,2.f)); + assert(close(roster.find(mic)->faderLinear,1.f)); + assert(roster.find(mic)->sends.size()==1 && + roster.find(mic)->sends[0].destination==main); + assert(host.commit(roster,req,1,777,777,true).ok()); + assert(render()&&close(left[0],center,1.e-4f)); + ChannelEdit bad=gain;bad.id=main; + assert(!roster.edit(roster.revision(),std::span(&bad,1)).ok()); +} + +// A real post-insert PRE tap is independent of the source fader, whereas +// POST follows it. ON/OFF changes no WIRE topology, stored level or EdgeId. +static void verifyNativePrePostAndSendEnablePcm() { + using Kind=ChannelEdit::Kind; + DynamicChannelRoster roster; + std::array add{}; + for(int i=0;i<3;++i){ + add[i].kind=Kind::add;add[i].position=static_cast(i); + add[i].role=i==0?ChannelRole::input:i==1?ChannelRole::fxReturn:ChannelRole::main; + // Deliberate mono microphone into stereo FX RETURN and stereo MAIN. + // Without explicit formats, ChannelEdit defaults ALL THREE to mono: + // wet and MAIN each apply an additional equal-power -3 dB pan. The + // golden .25*2*mono*.5 assumes only the input's mono-pan stage. + add[i].format=i==0?ProcessingFormat::mono:ProcessingFormat::stereo; + add[i].text=i==0?"Mic":i==1?"Wet":"MAIN"; + } + const auto created=roster.edit(0,add); + assert(created.ok()); + const auto mic=created.createdIds[0],wet=created.createdIds[1],main=created.createdIds[2]; + ChannelEdit primary{};primary.kind=Kind::setPrimaryOutput; + primary.id=wet;primary.target=main; + ChannelEdit send{};send.kind=Kind::addSendReference;send.id=mic; + send.target=wet;send.value=.5f;send.preFader=false; + std::array patch{primary,send}; + assert(roster.edit(roster.revision(),patch).ok()); + const auto* row=roster.find(mic);assert(row&&row->sends.size()==1); + const auto edgeId=row->sends[0].edgeId; + DynamicGraphRequest req;req.physicalInputs=1;req.maxFrames=64; + req.sources={{mic,0,-1,false}}; + DynamicNativeSessionPublisher host; + assert(host.commit(roster,req,0,874,874,true).ok()); + std::array input{},left{},right{};input.fill(.25f); + const float* physical[]={input.data()}; + int fxCalls=0; + const auto fx=[&](ChannelId id,float* l,float* r,int n) noexcept { + if(id!=mic)return; + ++fxCalls; + for(int k=0;k(postRendered),left[0],left[63],right[63],expectedPost, + static_cast(roster.find(mic)->format), + static_cast(roster.find(wet)->format), + static_cast(roster.find(main)->format)); + assert(postRendered&&close(left[63],expectedPost,1.e-4f)); + assert(host.setChannelMix(874,1,mic,0.f,0.f)); + assert(roster.rememberLiveMix(mic,0.f,0.f)); + assert(render()&&close(left[63],0.f)); + WireChange tap{};tap.kind=WireChange::Kind::setTap; + tap.from=mic;tap.edgeId=edgeId;tap.preFader=true; + assert(roster.wireTransaction(roster.revision(),std::span(&tap,1)).ok()); + assert(roster.find(mic)->sends[0].edgeId==edgeId); + assert(roster.find(mic)->sends[0].gain==.5f); + assert(host.commit(roster,req,1,874,874,true).ok()); + const bool preRendered=render(); + const float expectedPre=.25f*2.f*mono*.5f; + if(!preRendered || !close(left[63],expectedPre,1.e-4f)) + std::fprintf(stderr,"PRE_POST_DIAG pre_render=%d L0=%.9g L63=%.9g R63=%.9g expected=%.9g gain=%.9g edge_pre=%d edge_gain=%.9g\n", + static_cast(preRendered),left[0],left[63],right[63],expectedPre, + roster.find(mic)->faderLinear,static_cast(roster.find(mic)->sends[0].preFader), + roster.find(mic)->sends[0].gain); + assert(preRendered&&close(left[63],expectedPre,1.e-4f)); + assert(fxCalls==3); // one nonlinear FX pass per callback, no parallel duplicate + assert(host.setWireEnabled(874,2,mic,edgeId,false)); + assert(roster.rememberLiveSendEnabled(mic,edgeId,false)); + assert(render()&&close(left[63],0.f)); + assert(roster.find(mic)->sends[0].edgeId==edgeId && + roster.find(mic)->sends[0].gain==.5f && + roster.find(mic)->sends[0].preFader && !roster.find(mic)->sends[0].enabled); + assert(!host.setWireEnabled(874,2,wet,edgeId,true)); + assert(!host.setWireEnabled(875,2,mic,edgeId,true)); + assert(!host.setWireEnabled(874,1,mic,edgeId,true)); + assert(host.setWireEnabled(874,2,mic,edgeId,true)); + assert(roster.rememberLiveSendEnabled(mic,edgeId,true)); + assert(render()&&close(left[63],.25f*2.f*mono*.5f,1.e-4f)); + tap.preFader=false; + assert(roster.wireTransaction(roster.revision(),std::span(&tap,1)).ok()); + assert(host.commit(roster,req,2,874,874,true).ok()); + assert(render()&&close(left[63],0.f)); + tap.from=wet; + assert(!roster.wireTransaction(roster.revision(),std::span(&tap,1)).ok()); +} + int main() { + verifyNativePrePostAndSendEnablePcm(); + verifyNativeInputGainBeforeFx(); verifyDynamicInPlacePhysicalIOBuffers(); verifyDynamicChannelIdLiveControls(); verifyDynamicNativeSessionPublication(); diff --git a/tests/native_artifact_packaging_contract_test.mjs b/tests/native_artifact_packaging_contract_test.mjs index dbfa34f34..dcb8e1916 100644 --- a/tests/native_artifact_packaging_contract_test.mjs +++ b/tests/native_artifact_packaging_contract_test.mjs @@ -153,6 +153,28 @@ test('FAT bundle retains the reviewed first-sound guide and SHA protection',()=> assert.ok(quick.includes(text),text); }); +test('FIELD preview provenance is accepted by BOTH verifiers without counterfeit full FAT',()=>{ + const gate=read('scripts/m3e_fat_evidence_gate.mjs'); + const collector=read('scripts/collect_hardware_fat_windows.ps1'); + const expected='FIELD_PREVIEW_FULL_CTEST_NOT_RUN'; + const legacy='SOFTWARE_VERIFIED_PREVIEW_CANDIDATE'; + for(const contents of [gate,collector]){ + assert.ok(contents.includes(expected),'field marker missing from artifact verifier/collector'); + assert.ok(contents.includes(legacy),'legacy full-software marker removed'); + } + assert.match(gate,/M3E_PACKAGE_QUALIFICATIONS\.includes\(manifest\.fatStatus\)/); + assert.match(gate,/hardwareCertified:false/); + assert.match(gate,/releaseReady:false/); + assert.match(collector,/-notin @\('SOFTWARE_VERIFIED_PREVIEW_CANDIDATE','FIELD_PREVIEW_FULL_CTEST_NOT_RUN'\)/); + assert.match(collector,/FAT collector was modified after packaging/); + const mark=workflow.indexOf('Mark unqualified field preview BEFORE independent distribution verification'); + const set=workflow.indexOf("fatStatus = 'FIELD_PREVIEW_FULL_CTEST_NOT_RUN'"); + const verifyStep=workflow.indexOf('Independently verify release ZIP and embedded GUI/engine before upload'); + const upload=workflow.indexOf('Upload portable Windows field preview'); + assert.ok(mark>=0 && set>mark && verifyStep>set && upload>verifyStep); + assert.match(verify,/node scripts\/m3e_fat_evidence_gate\.mjs \$OutputDir/); +}); + test('M3-E same-SHA native ZIP carries SHA-pinned FAT tools and no fake hardware claims',()=>{ const p=read('scripts/package_native_windows.ps1'); const v=read('scripts/verify_native_windows_artifact.ps1'); diff --git a/tests/native_caption_wire_geometry_contract.test.cjs b/tests/native_caption_wire_geometry_contract.test.cjs index c0c985b41..8042978db 100644 --- a/tests/native_caption_wire_geometry_contract.test.cjs +++ b/tests/native_caption_wire_geometry_contract.test.cjs @@ -26,7 +26,7 @@ assert.match(activation,/for \(auto\* control : \{ getMinimiseButton\(\), getMax assert.match(activation,/control->setEnabled \(true\)/); assert.doesNotMatch(activation,/startTimer|setAlwaysOnTop|toFront|SetForegroundWindow|engine_/); assert.match(chrome,/void paintButton \(juce::Graphics& g, bool over, bool down\) override/); -assert.match(chrome,/if \(over \|\| down\)/); +assert.match(chrome,/if \(over \|\| pressed\)/); assert.match(main, /setUsingNativeTitleBar \(false\)/); assert.match(main, /setTitleBarHeight \(31\)/); @@ -41,8 +41,8 @@ const palette = chrome.slice(chrome.indexOf('static CaptionPalette paletteFor'), chrome.indexOf('static std::unique_ptr load')); assert.ok(palette.length > 300, 'native caption must own one state palette'); assert.match(chrome, /const auto palette = paletteFor \(kind_\)/); -assert.match(chrome, /down \? palette\.pressedFace : palette\.hoverFace/); -assert.match(chrome, /down \? palette\.pressedEdge : palette\.hoverEdge/); +assert.match(chrome, /pressed \? palette\.pressedFace : palette\.hoverFace/); +assert.match(chrome, /pressed \? palette\.pressedEdge : palette\.hoverEdge/); assert.match(palette, /closeButton[\s\S]*?0xff5c3039[\s\S]*?0xffab5864[\s\S]*?0xffef3e50[\s\S]*?0xffff8993/); assert.match(palette, /minimiseButton[\s\S]*?0xff244e3a[\s\S]*?0xff4ead7a[\s\S]*?0xff1fb76b[\s\S]*?0xff8be2b4/); assert.match(palette, /0xff584929[\s\S]*?0xffbc9544[\s\S]*?0xffe5ae2b[\s\S]*?0xffffdf81/); @@ -50,14 +50,37 @@ assert.doesNotMatch(palette, /0xff50d4e7|0xff67b9ff|0xff168fa7|0xff287abd/); assert.match(chrome, /drawRoundedRectangle/); assert.match(chrome, /parent->isFullScreen\(\)/); +/* JUCE 8 Button::mouseUp runs its listener before the message-loop's paint: + * Close/minimize vanish and maximize changes geometry before the bright click + * face is drawn. Test a real bounded, one-shot paint->dispatch handoff, not + * just the existence of red/green/amber palette hex values. */ +assert.match(chrome,/class MixerCaptionButton final : public juce::Button, private juce::Timer/); +assert.match(chrome,/const bool pressed = down \|\| pendingClick_/); +assert.match(chrome,/g\.setColour \(pressed \? palette\.pressedFace : palette\.hoverFace\)/); +assert.match(chrome,/g\.setColour \(pressed \? palette\.pressedEdge : palette\.hoverEdge\)/); +assert.match(chrome,/pressed && pressedRestoreIcon_ != nullptr/); +assert.match(chrome,/pressed && pressedIcon_ != nullptr/); +const defer=chrome.slice(chrome.indexOf('void internalClickCallback ('), + chrome.indexOf('private:\n struct CaptionPalette')); +assert.match(defer,/if \(!isEnabled\(\) \|\| pendingClick_\)\s*return/); +assert.match(defer,/pendingModifiers_ = modifiers/); +assert.match(defer,/pendingClick_ = true;\s*repaint\(\);\s*startTimer \(160\)/); +assert.match(defer,/void timerCallback\(\) override/); +assert.match(defer,/stopTimer\(\);\s*pendingClick_ = false;\s*repaint\(\);/); +assert.match(defer,/juce::Button::internalClickCallback \(pendingModifiers_\)/); +assert.equal((defer.match(/juce::Button::internalClickCallback/g)||[]).length,1, + 'a caption click must dispatch once, through the original JUCE listener'); +assert.doesNotMatch(defer,/engine_|WebView|setAlwaysOnTop|toFront|sleep|Thread::sleep|std::thread/); + + /* Dark-ink pressed glyphs are prebuilt once, not reparsed/recoloured when paintButton receives a hover or pointer-down transition. Maintain WCAG non-text graphic contrast against the luminous green/amber pressed faces. */ assert.match(chrome, /pressedIcon_ = load \(iconPath, kind == juce::DocumentWindow::minimiseButton/); assert.match(chrome, /pressedRestoreIcon_ = load \(restorePath/); assert.match(chrome, /const bool restoring = kind_ == juce::DocumentWindow::maximiseButton/); -assert.match(chrome, /down && pressedRestoreIcon_ != nullptr/); -assert.match(chrome, /down && pressedIcon_ != nullptr/); +assert.match(chrome, /pressed && pressedRestoreIcon_ != nullptr/); +assert.match(chrome, /pressed && pressedIcon_ != nullptr/); assert.match(chrome, /static std::unique_ptr load \(const char\* path, const char\* ink/); const paint = chrome.slice(chrome.indexOf('void paintButton '), chrome.indexOf('private:\n struct CaptionPalette')); assert.doesNotMatch(paint, /Drawable::createFromSVG|XmlDocument::parse|std::make_unique|new juce::/); diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index b5d1142ac..a756dd34c 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -1277,7 +1277,41 @@ static void verifyExternalOutputPortableIntent() { assert(!Codec::decode(Codec::encode(doc),loaded)); } +static void verifyChannelInputGainSessionRoundtrip() { + auto session=makeSession(); + auto rows=session.roster.channels(); + rows[0].inputGainLinear=2.f; + assert(session.roster.restoreExact(session.acceptedRevision,rows)); + const auto json=Codec::encode(session); + MixerSessionDocument restored; + assert(Codec::decode(json,restored)); + assert(std::abs(restored.roster.find({1})->inputGainLinear-2.f)<1.e-6f); + assert(std::abs(restored.roster.find({1})->faderLinear-1.f)<1.e-6f); + assert(restored.roster.find({1})->sends[0].edgeId==100); + assert(Codec::encode(restored)==json); + // Pre-GAIN v1 sessions have no inputGain property; absence means unity + // without inventing a new schema or erasing WIRE/VST references. + auto old=juce::JSON::parse(json); + auto channels=old.getProperty("channels",{}); + for(auto& item:*channels.getArray()) + item.getDynamicObject()->removeProperty("inputGain"); + assert(Codec::decode(juce::JSON::toString(old,false),restored)); + assert(restored.roster.find({1})->inputGainLinear==1.f); + // Present but malformed/off-role input gain cannot be normalized. + auto invalid=juce::JSON::parse(json); + auto values=invalid.getProperty("channels",{}); + values.getArray()->getReference(0).getDynamicObject() + ->setProperty("inputGain",juce::String("NaN")); + assert(!Codec::decode(juce::JSON::toString(invalid,false),restored)); + invalid=juce::JSON::parse(json); + values=invalid.getProperty("channels",{}); + values.getArray()->getReference(values.getArray()->size()-1) + .getDynamicObject()->setProperty("inputGain",2.0); + assert(!Codec::decode(juce::JSON::toString(invalid,false),restored)); +} + int main(){ + verifyChannelInputGainSessionRoundtrip(); verifyDurableNativeFxPowerIdentity(); verifyHotkeyDocumentIdentityAndMigration(); verifyLogicalControlTransactions(); diff --git a/tests/native_peq_assembly_test.py b/tests/native_peq_assembly_test.py index 07e34a495..63df007dc 100644 --- a/tests/native_peq_assembly_test.py +++ b/tests/native_peq_assembly_test.py @@ -27,21 +27,24 @@ def test_one_authoritative_mixer(self): 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) + self.assertEqual(self.assembled.count('data-fast-native-sonku="1"'),1) + self.assertEqual(self.assembled.count('src="assets/mixer-native-sonku.js?v=sonku-1"'),1) + self.assertEqual(self.assembled.count("function insertChosenNativeSonKu(){"),1) - def test_additional_native_registry_fx_are_first_class_builtins(self): - # Source-level guard for the owner's actual Windows FAT screenshot: - # hardcoded EQ/Comp/Harmony/Throw were visible in BUILT-IN FX while - # catalog-driven Guitar FX was incorrectly below VST3 PLUGINS. + def test_catalog_driven_guitar_and_one_specialized_sonku_button(self): + # Main #657: use native catalog for newly compiled FX, not a fifth + # browser-only Guitar button. Preserve the M4 SonKu specialized editor. self.assertIn("const nativeExtra=list.filter(p=>p.format==='Native'",self.assembled) self.assertIn("p.id.startsWith('armix.builtin.')",self.assembled) - self.assertIn("nativeExtra+eqBuiltin+compBuiltin+harmonyBuiltin+throwBuiltin",self.assembled) + self.assertIn("'armix.builtin.8d-sonku.v1'",self.assembled) + self.assertIn("nativeExtra+eqBuiltin+compBuiltin+harmonyBuiltin+throwBuiltin+sonkuBuiltin",self.assembled) self.assertIn("const vstItems=list.filter(p=>p.format!=='Native');",self.assembled) self.assertIn("(vstItems.length?vstItems.map(p=>",self.assembled) - # New effects use standard catalog id insertion; no visual-only - # Guitar button and no fifth bespoke native FX branch are invented. self.assertIn('data-fast-id="'+ "'+escapeHtml(p.id)+'"+'"',self.assembled) + self.assertEqual(self.assembled.count('data-fast-native-sonku="1"'),1) self.assertNotIn('data-fast-native-guitar',self.assembled) + self.assertIn("if(b.hasAttribute('data-fast-native-sonku'))",self.assembled) def test_native_rack_uses_regular_insert_slot(self): self.assertIn("host.insert(activeFxTarget)",self.assembled) @@ -61,6 +64,23 @@ def test_single_style_owner(self): self.assertNotIn('href="assets/mixer-native-peq.css',self.assembled) css=(ROOT/"site/preview-v2/assets/mixer-fx-rack.css").read_text("utf-8") self.assertIn(".mx-peq[hidden]{display:none}",css) + self.assertIn(".mx-sonku[hidden]{display:none!important}",css) + self.assertIn(".mx-sonku .sk-listener-art",css) + png=(ROOT/"site/preview-v2/assets/sonku-listener-top.png").read_bytes() + self.assertEqual(png[:8],bytes([137,80,78,71,13,10,26,10])) + self.assertLess(len(png),45000) + self.assertNotIn("mixer-native-sonku.css",self.assembled) + sonku=(ROOT/"site/preview-v2/assets/mixer-native-sonku.js").read_text("utf-8") + # SonKu FRONT-up scene now uses a shaded inline vector back view + # rather than displaying the old face PNG upside-down. The legacy + # PNG is still packaged for historical/checkpoint builds. + self.assertIn('id="skListenerArt"',sonku) + self.assertIn('id="skCrown"',sonku) + self.assertIn('id="skBackSuit"',sonku) + self.assertIn("FRONT",sonku) + self.assertIn('arMixBuiltinSonKuAck',sonku) + self.assertIn('nativeSonKuSet',sonku) + self.assertNotIn("new AudioContext",sonku) self.assertIn("grid-template-columns:minmax(0,1fr) 143px",css) script=(ROOT/"site/preview-v2/assets/mixer-native-peq.js").read_text("utf-8") self.assertIn('const LOG=Math.log(1000)',script) @@ -81,6 +101,31 @@ def test_single_style_owner(self): self.assertIn("armix-floating-close",throw) self.assertNotIn("new AudioContext",throw) + def test_sonku_native_space_v2_owned_by_single_pcm_graph(self): + main=(ROOT/"src/Main.cpp").read_text("utf-8") + processor=(ROOT/"engine/builtin_fx/SonKuSpatialProcessor.h").read_text("utf-8") + core=(ROOT/"engine/builtin_fx/sonku/SonKuSpatialCore.h").read_text("utf-8") + js=(ROOT/"site/preview-v2/assets/mixer-native-sonku.js").read_text("utf-8") + snapshot=main.split("void emitNativeSonKuSnapshot(",1)[1].split( + "void servicePendingNativeSonKu()",1)[0] + for field in ("spacePreset","sourceDistanceMeters","roomAmount","ambience"): + self.assertIn('values->setProperty("'+field+'"',snapshot) + if field=="spacePreset": + self.assertIn('values.getProperty("spacePreset"',main) + else: + self.assertIn('optionalNumber("'+field+'"',main) + self.assertIn(field,js) + self.assertIn(field,core) + self.assertIn('reply->setProperty("schemaVersion",2)',snapshot) + self.assertIn("queueSettings(settings,numeric)",main) + self.assertIn("complete_.push(",processor) + self.assertIn("out.writeInt(2)",processor) + self.assertIn("version==1&&size!=30",processor) + self.assertIn("version==2&&size!=46",processor) + self.assertNotIn("new AudioContext",js) + self.assertIn("[data-sk-room]",js) + self.assertIn('arMixBuiltinSonKuAck',js) + 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 diff --git a/tests/pages_controls_v6_smoke.py b/tests/pages_controls_v6_smoke.py index e9b824cb6..3b052cf98 100644 --- a/tests/pages_controls_v6_smoke.py +++ b/tests/pages_controls_v6_smoke.py @@ -40,11 +40,20 @@ def assert_ownership(): # Still verifies every V26 owner fingerprint and V25 migrated material. from css_v26_restore import restore_owner,manifest as v26_manifest from css_v25_restore import manifest as v25_manifest - original_v25_key=restore_owner(css,v26_manifest()["sources"]["mixer-control-keys.css"]) + # The owner-approved historical V26 fixture used the internal + # data-hw-kind="cue" spelling. The current one-GUI preview now displays + # the semantic "pfl" hardware kind while retaining data-action="cue". + # Normalize ONLY this exact selector to reconstruct immutable V25/V26 + # evidence; never rewrite its original CSS fixture or weaken the check. + old_selector='data-hw-kind="cue"' + live_selector='data-hw-kind="pfl"' + assert css.count(live_selector)==1 and old_selector not in css + historical_css=css.replace(live_selector,old_selector) + original_v25_key=restore_owner(historical_css,v26_manifest()["sources"]["mixer-control-keys.css"]) v30=v25_manifest()["movedCss"] assert original_v25_key.startswith(v30) modern_v6=original_v25_key[len(v30):] - assert css.endswith(modern_v6),"V6 modern MUTE/SOLO/PFL CSS changed" + assert historical_css.endswith(modern_v6),"V6 original hardware CSS drifted beyond the PFL selector" assert css.count("!important")-modern_v6.count("!important")==83 assert modern_v6.count("!important")<=14, "V6 key owner priority budget regressed" @@ -79,7 +88,7 @@ async def assert_mixer(page, width): background:s.backgroundImage,focus:e.getAttribute('aria-label') }; })""") - assert [d["kind"] for d in details]==["mute","solo","cue"],details + assert [d["kind"] for d in details]==["mute","solo","pfl"],details assert [d["action"] for d in details]==["mute","solo","cue"],details assert [d["label"] for d in details]==["MUTE","SOLO","PFL"],details assert [d["led"] for d in details]==["255,78,90","255,207,68","101,210,236"],details diff --git a/tests/pages_inter_utility_v7_smoke.py b/tests/pages_inter_utility_v7_smoke.py index 14762750b..b65479f24 100644 --- a/tests/pages_inter_utility_v7_smoke.py +++ b/tests/pages_inter_utility_v7_smoke.py @@ -117,14 +117,27 @@ async def visual(page,width): if width==1680: await page.screenshot(path='pages-v7-embedded-inter-utility-1680.png') # MUTE is an independent CSS/HTML caption; SOLO/PFL retain SVG masks. - for k in ('mute','solo','cue'): + # The accepted hardware key identity is 'pfl'; its action is 'cue'. + # Never confuse data-hw-kind with the internal click-handler action. + for k in ('mute','solo','pfl'): key=row.locator(f'.mx-hw-row button[data-hw-kind="{k}"]') + # FX/FORMAT toggles asynchronously re-render this strip; wait for the + # post-render DOM instead of sampling a transient detached key. + await key.wait_for(state="attached",timeout=6000) assert await key.count()==1 if k=='mute': assert await key.locator('.mx-mute-face .mx-mute-legend').inner_text()=='MUTE' assert await key.locator('svg,img').count()==0 else: - assert await key.locator('svg.mx-hw-face mask text').count()==1 + # The SVG is inserted by the one authoritative resize-aware hardware + # renderer after the button enters the DOM. Assert the real mask and + # embossed legend, not merely the presence of an inert button. + legend=key.locator('svg.mx-hw-face mask text') + await legend.wait_for(state="attached",timeout=6000) + assert await legend.count()==1 + # SVG is SVGTextElement, not HTMLElement: Playwright's + # inner_text() fails in Chromium despite the valid painted legend. + assert (await legend.text_content())==('PFL' if k=='pfl' else 'SOLO') async def main(): source_contract() diff --git a/tests/pages_lms_five_workspaces_smoke.py b/tests/pages_lms_five_workspaces_smoke.py new file mode 100644 index 000000000..ad16054a4 --- /dev/null +++ b/tests/pages_lms_five_workspaces_smoke.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +"""Real Chromium UX FAT for the ONE canonical ArSonMix /preview/ LMS workspace. +No fake ASIO, audio, protection, or hardware ACK claims. +""" +from pathlib import Path +import subprocess,sys,tempfile +from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console + +ROOT=Path(__file__).resolve().parents[1] + +def main(): + with tempfile.TemporaryDirectory(prefix="arsonmix-lms-ui-") as name: + target=Path(name)/"dist" + subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), + "--out",str(target),"--sha","lms-ui-exact-source", + "--branch","lms"],cwd=ROOT,check=True,capture_output=True,text=True) + public=published_console(target) + with sync_playwright() as pw: + browser=pw.chromium.launch(headless=True) + for width in (1366,1680): + page=browser.new_page(viewport={"width":width,"height":900}) + errors=[] + page.on("pageerror",lambda e:errors.append(str(e))) + page.goto(public.as_uri()) + speaker=page.locator("#lmsOpen") + assert speaker.count()==1,"one LMS entrypoint inside approved mixer" + speaker.click() + body=page.locator("#lmsWorkspace") + assert body.is_visible() and page.locator(".app.lms-active").count()==1 + assert body.locator(".lms-nav button").count()==5 + assert "DESIGN ONLY" in body.inner_text() + assert "OUTPUT DISCONNECTED" in body.inner_text() + assert page.locator(".console-pane").is_hidden() + assert not body.evaluate("(el)=>!!el.querySelector('audio,video,iframe')"), \ + "LMS cannot instantiate any competing audio graph or renderer" + + body.locator('button[data-page="crossover"]').click() + assert body.locator(".lms-frequency path").count()==3 + before=body.locator(".lms-frequency path").first.get_attribute("d") + body.locator("#lms-x0").fill("180") + body.locator("#lms-x0").press("Tab") + after=body.locator(".lms-frequency path").first.get_attribute("d") + assert before!=after,"Crossover must plot recalculated LR4, not static rectangles" + assert "48 kHz" in body.inner_text() + if width==1680: + page.screenshot(path="pages-lms-crossover-1680.png",full_page=False) + body.locator("#lms-way").select_option("4") + assert "Review structural change" in body.inner_text() + body.locator('[data-action="confirm"]').click() + assert body.locator(".lms-frequency path").count()==4 + + body.locator('button[data-page="matrix"]').click() + matrix=body.locator(".lms-matrix") + assert matrix.locator("tbody tr").count()==8 + first=matrix.locator('[data-route-port="DEMO-01"][data-route-section="L:1"]') + first.click() + assert matrix.locator('[data-route-port="DEMO-01"][data-route-section="L:1"]').get_attribute("aria-pressed")=="true" + another=matrix.locator('[data-route-port="DEMO-01"][data-route-section="L:2"]') + another.click() + assert matrix.locator('[data-route-port="DEMO-01"][data-route-section="L:2"]').get_attribute("aria-pressed")=="true" + assert matrix.locator('[data-route-port="DEMO-01"][data-route-section="L:1"]').get_attribute("aria-pressed")=="false", \ + "one physical destination cannot silently sum two crossover sections" + body.locator('button[data-page="processing"]').click() + assert "Parametric EQ" in body.inner_text() + body.locator('[data-action="addPeq"]').click() + assert body.locator('[data-select-band="0"]').count()==1 + before=body.locator(".lms-frequency path").first.get_attribute("d") + body.locator('[data-peq-field="gainDb"]').fill("6") + body.locator('[data-peq-field="gainDb"]').press("Tab") + after=body.locator(".lms-frequency path").first.get_attribute("d") + assert before!=after,"EQ must plot real biquad response" + if width==1680: + page.screenshot(path="pages-lms-eq-1680.png",full_page=False) + body.locator('[data-dsp-tab="protection"]').click() + assert "NOT CALIBRATED" in body.inner_text() + + body.locator('button[data-page="alignment"]').click() + assert body.locator("#lms-room-svg").count()==1 + assert "Suggested" in body.inner_text() + body.locator("#lms-align-port").select_option("DEMO-06") + assert "ms" in body.inner_text() + body.locator('[data-action="planDelay"]').click() + assert "Review structural change" in body.inner_text() + body.locator('[data-action="cancel"]').click() + body.locator('[data-action="planDelay"]').click() + body.locator('[data-action="confirm"]').click() + if width==1680: + page.screenshot(path="pages-lms-alignment-1680.png",full_page=False) + body.locator('button[data-page="processing"]').click() + body.locator('[data-dsp-tab="level"]').click() + delay=float(body.locator("#lms-delay").input_value()) + assert delay>0,"Nearer speaker requires positive extra delay draft" + assert "DESIGN ONLY" in body.inner_text() + assert not errors,(width,errors) + speaker.click() + assert body.is_hidden() and page.locator(".app.lms-active").count()==0 + assert page.locator(".console-pane").is_visible() + page.close() + browser.close() + print("PASS LMS canonical /preview/: 5 pages, calculated LR4/PEQ curves, exclusive patch," + " draft geometry, fail-closed no native ACK; 2 viewport Chromium UX") + +if __name__=="__main__": + main() diff --git a/tests/preview_v2_v7_visual_smoke.py b/tests/preview_v2_v7_visual_smoke.py index 9f9f4d10e..68fa4b51f 100644 --- a/tests/preview_v2_v7_visual_smoke.py +++ b/tests/preview_v2_v7_visual_smoke.py @@ -42,7 +42,16 @@ def audit_geometry(page, title): if(a!==b)problems.push('top/bottom channel color mismatch '+tag); } const controls=[...t.querySelectorAll('.switch-section.mx-hw-row > button.mx-hw-key')]; - if(controls.length!==3)problems.push('MUTE/SOLO/PFL count !=3 '+tag); + // MASTER has only MUTE/SOLO; there is no independent MAIN PFL + // tap. All regular channels retain the three approved keys. + const master=t===m, expected=master?['mute','solo']:['mute','solo','pfl']; + const kinds=controls.map(c=>c.dataset.hwKind); + const actions=controls.map(c=>c.dataset.action); + const expectedActions=master?['mute','solo']:['mute','solo','cue']; + if(kinds.join(',')!==expected.join(',')|| + actions.join(',')!==expectedActions.join(',')) + problems.push('unexpected physical MUTE/SOLO/PFL identity '+tag+ + ' kinds='+kinds.join(',')+' actions='+actions.join(',')); else { if(Math.max(...controls.map(c=>r(c).width))-Math.min(...controls.map(c=>r(c).width))>1.8) problems.push('inconsistent V6 button widths '+tag); diff --git a/tests/single_preview_publication_contract_test.py b/tests/single_preview_publication_contract_test.py index c9e51060c..1510a1a82 100644 --- a/tests/single_preview_publication_contract_test.py +++ b/tests/single_preview_publication_contract_test.py @@ -1,12 +1,13 @@ """Fail closed: GitHub Pages must expose ONE approved ArSonMix GUI at /preview/.""" from pathlib import Path -import json, re, sys, hashlib, shutil, tempfile +import json, re, sys, hashlib, shutil, tempfile, subprocess sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts')) from compile_approved_css import LINK, optimize_css, compile_runtime_bundle, link_runtime_bundle, RUNTIME_CSS from approved_fx_rack_power import apply_authoritative_fx_power from approved_fx_rack_interaction import apply_fx_rack_interaction from compose_native_peq import apply_native_peq from compose_operator_ux import apply_operator_ux +from compose_lms import apply_lms ROOT=Path(__file__).resolve().parents[1] DST=Path(sys.argv[1]).resolve() if len(sys.argv)>1 else ROOT/'dist-pages' gui=DST/'preview' @@ -55,6 +56,7 @@ def require(ok,why): # then run the existing operator composer. Historic V28 assets stay locked. apply_fx_rack_interaction((ROOT/"site/preview-v2/index.html").read_text(encoding="utf-8"),owned) expected=apply_operator_ux(expected,owned) + expected=apply_lms(expected,owned) composed_css={name:(owned/name).read_text(encoding="utf-8") for name in owners} # Stage C: the source HTML remains byte-exact, but the 18 deployed CSS files # contain only proven cascade winners. Verify every *generated* byte and query @@ -104,6 +106,18 @@ def css_rewrite(match): require(len(shipped)==1 and shipped[0].group(2)==RUNTIME_CSS, 'Only the single compiled runtime CSS is allowed to load') require(html==expected,'rendered /preview/ DOM differs from source + approved buttons + one runtime CSS + nonvisual profiler') +# LMS is a sibling workspace in the SAME renderer; never a second /preview/ page. +require(html.count('id="lmsOpen"')==1 and html.count('id="lmsWorkspace"')==1, + 'LMS button or workspace absent/duplicated') +for asset in ('lms-workspace.js','lms-system-model.js','lms-workspace.css'): + require((gui/'assets'/asset).read_bytes()== + (ROOT/'site/preview-v2/assets'/asset).read_bytes(), + 'LMS composed asset drift: '+asset) +require('ArSonMixLmsModel' in (gui/'assets/lms-workspace.js').read_text(encoding='utf-8'), + 'LMS logical model not used by workspace') +subprocess.run(['node','--test',str(ROOT/'tests/lms_system_model.test.cjs')], + cwd=ROOT,check=True) + for name in ('mixer-wire-dots.css','knob-ICON.svg'): require((gui/'assets'/name).read_bytes()==(ROOT/'site/preview-v2/assets'/name).read_bytes(),'WIRE source drift: '+name) require((gui/'assets/mixer-keys-thin-flat-v9-approved-off-shadow-57x30.png').read_bytes()==(ROOT/'site/preview-buttons/assets/mixer-keys-thin-flat-v9-approved-off-shadow-57x30.png').read_bytes(),'approved PNG sprite mismatch') diff --git a/tests/sof_contextual_console_smoke.py b/tests/sof_contextual_console_smoke.py new file mode 100644 index 000000000..0b248ec65 --- /dev/null +++ b/tests/sof_contextual_console_smoke.py @@ -0,0 +1,169 @@ +"""Contextual Gain/FX Rack and Sends-on-Faders public GUI smoke. + +Runs against the single *assembled* /preview/ renderer. All control checks +below are browser-reference only, not claims of native ASIO/PCM admission. +No direct engine/graph mutation in this fixture. +""" +from __future__ import annotations + +import subprocess +import sys +import tempfile +from pathlib import Path + +from playwright.sync_api import sync_playwright + +ROOT = Path(__file__).resolve().parents[1] + + +def run() -> None: + with tempfile.TemporaryDirectory(prefix="arsonmix-sof-context-") as tmp: + dist = Path(tmp) / "pages" + subprocess.run( + [ + sys.executable, + str(ROOT / "scripts/build_pages.py"), + "--out", str(dist), + "--sha", "sof-context-test", + "--branch", "gui-test", + ], + cwd=ROOT, check=True, capture_output=True, text=True, + ) + html = dist / "preview" / "index.html" + source = html.read_text(encoding="utf-8") + assert 'id="gainView"' in source and 'id="fxView"' in source + assert 'id="mixContext"' in source + assert "Never auto-patch or remove a WIRE at minimum send level." in source + assert "const send=sofEnabled&&t.kind==='audio';" in source, ( + "Fader reset must inspect active SEND context instead of overwriting MAIN") + assert "nativeGainAvailable===true" in source, ( + "Native input gain should be available only with installed capability") + with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + try: + for width, height in ((1366, 768), (1680, 900), (1920, 1080)): + page = browser.new_page(viewport={"width": width, "height": height}) + errors = [] + page.on("pageerror", lambda err: errors.append(str(err))) + page.goto(html.as_uri()) + first = page.locator('#tracks .strip[data-id="1"]') + first.wait_for(timeout=15000) + gain = page.locator("#gainView") + fx = page.locator("#fxView") + assert gain.get_attribute("aria-pressed") == "false" + assert fx.get_attribute("aria-pressed") == "true" + assert page.locator("#mixContext").inner_text() == "MAIN MIX" + + # The same cell swaps only its presentation, not FX state. + gain.click() + assert gain.get_attribute("aria-pressed") == "true" + assert first.locator(".is-gain-view").count() == 1 + knob = first.locator('[data-field="trim"]') + assert knob.count() == 1 + knob.evaluate("""el => { + el.value = '6.5'; + el.dispatchEvent(new Event('input', {bubbles:true})); + }""") + assert "+6.5 dB" in first.locator(".gain-readout").inner_text() + assert "6.5" in knob.get_attribute("value") or knob.input_value() == "6.5" + # Double-click must use the same gain parameter path and restore unity. + first.locator(".gain-dial").dblclick() + # The public formatter reserves '+' for strictly + # positive values; gain unity is displayed as 0.0 dB. + assert first.locator(".gain-readout").inner_text().strip() == "0.0 dB" + assert knob.input_value() == "0" + knob.evaluate("""el => { + el.value = '6.5'; + el.dispatchEvent(new Event('input', {bubbles:true})); + }""") + + fx.click() + assert first.locator(".is-gain-view").count() == 0 + assert first.locator(".fxslot-list").count() == 1 + + # Enter SENDS: the approved strip and pinned master survive. + page.locator("#sofToggle").click() + assert page.locator("#mixContext").inner_text().startswith("SEND MIX") + assert gain.is_disabled() and fx.is_disabled() + assert first.locator(".is-sof-view").count() == 1 + assert first.locator(".mx-sof-tap-key").count() == 1 + assert first.locator('button[data-hw-kind="tap"]').count() == 0 + assert first.locator('button[data-hw-kind="mute"]').count() == 1 + assert first.locator('button[data-hw-kind="solo"]').count() == 1 + assert first.locator(".fader").is_disabled(), ( + "A missing WIRE must not turn a fader gesture into auto-patch") + assert page.locator("#master .strip").count() == 1 + assert page.locator("#wireLayer").count() == 1 + + # SENDS mode exposes approved raster, not a fake CSS key. + tap = first.locator(".mx-sof-tap-key") + sprite = tap.evaluate( + "el => getComputedStyle(el, '::before').backgroundImage") + assert "harmonice-thin-flat-v9-approved-off-shadow-57x30.png" in sprite, sprite + assert tap.is_disabled() + + # SOF target is a stable strip ID, never a BUS display name. + target_select = page.locator("#sofTarget") + initial_id = target_select.input_value() + assert initial_id.isdigit(), (width, initial_id) + expected_name = target_select.locator("option:checked").inner_text() + assert page.locator("#mixContext").inner_text() == "SEND MIX → " + expected_name + assert first.locator(".mx-sof-on-key").get_attribute("aria-pressed") == "false", ( + "An absent SEND is not secretly ON") + + # Returning to MAIN must keep FX/GAIN selection and actual fader mix. + page.locator("#sofToggle").click() + assert page.locator("#mixContext").inner_text() == "MAIN MIX" + gain.click() + assert "+6.5 dB" in first.locator(".gain-readout").inner_text() + + # Rename the selected BUS in the native-style identity card. + # SOF selection must follow its ID, not jump back to Bus A. + # VIEW & SELECTION was deliberately moved under the + # compact More menu. Exercise its visible operator path; + # do not force a hidden