diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 11eeefe..0eb7352 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,5 +1,5 @@ name: Public source build -on: [push, pull_request] +on: [push, pull_request, workflow_dispatch] permissions: contents: read jobs: @@ -13,3 +13,92 @@ jobs: run: cmake --build build --parallel 3 - name: Test run: ctest --test-dir build --output-on-failure + windows: + runs-on: windows-2022 + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - name: Configure without private data + shell: cmd + run: | + call "%ProgramFiles%\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat" + cmake -S . -B build-windows -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=clang-cl -DCMAKE_CXX_COMPILER=clang-cl -DCMAKE_LINKER=lld-link -DCMAKE_AR=llvm-lib -DWAVE_EMBED_PRIVATE_ASSETS=OFF -DWAVE_BUILD_TESTS=ON + - name: Build + shell: cmd + run: | + call "%ProgramFiles%\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\Build\vcvars64.bat" + cmake --build build-windows --parallel 3 + - name: Check embedded Windows manifests + run: >- + python scripts/check-windows-manifests.py + --exe "build-windows/WaveEmulation_artefacts/Release/Standalone/Wave Emulation.exe" + --vst3 "build-windows/WaveEmulation_artefacts/Release/VST3/Wave Emulation.vst3" + - name: Test + env: + WAVE_TEST_ARTIFACT_DIR: ${{ github.workspace }}/build-windows/test-results + WAVE_TEST_NATIVE_WINDOW: "1" + run: ctest --test-dir build-windows -C Release --output-on-failure + - name: Check Windows artifacts + shell: pwsh + run: | + $output = "build-windows/WaveEmulation_artefacts/Release" + if (-not (Test-Path "$output/Standalone/Wave Emulation.exe")) { throw "Standalone app is missing" } + if (-not (Test-Path "$output/VST3/Wave Emulation.vst3")) { throw "VST3 bundle is missing" } + - name: Launch and close standalone on Windows + shell: pwsh + run: | + $exe = (Resolve-Path "build-windows/WaveEmulation_artefacts/Release/Standalone/Wave Emulation.exe").Path + $app = Start-Process -FilePath $exe -PassThru + try { + $deadline = (Get-Date).AddSeconds(30) + do { + Start-Sleep -Milliseconds 500 + $app.Refresh() + if ($app.HasExited) { throw "Standalone exited before opening a window ($($app.ExitCode))" } + } while ($app.MainWindowHandle -eq 0 -and (Get-Date) -lt $deadline) + if ($app.MainWindowHandle -eq 0) { throw "Standalone did not open a window" } + Start-Sleep -Seconds 5 + $app.Refresh() + if ($app.HasExited -or -not $app.Responding) { throw "Standalone crashed or stopped responding" } + if (-not $app.CloseMainWindow()) { throw "Standalone refused to close" } + if (-not $app.WaitForExit(30000)) { throw "Standalone shutdown timed out" } + if ($app.ExitCode -ne 0) { throw "Standalone exited with code $($app.ExitCode)" } + } finally { + if (-not $app.HasExited) { Stop-Process -Id $app.Id -Force } + } + - name: Validate VST3 with pluginval + shell: pwsh + run: | + Invoke-WebRequest "https://github.com/Tracktion/pluginval/releases/download/v1.0.4/pluginval_Windows.zip" -OutFile "$env:RUNNER_TEMP/pluginval.zip" + Expand-Archive "$env:RUNNER_TEMP/pluginval.zip" "$env:RUNNER_TEMP/pluginval" + $validator = (Get-ChildItem "$env:RUNNER_TEMP/pluginval" -Recurse -Filter pluginval.exe | Select-Object -First 1).FullName + if (-not $validator) { throw "pluginval executable is missing" } + $plugin = (Resolve-Path "build-windows/WaveEmulation_artefacts/Release/VST3/Wave Emulation.vst3").Path + & $validator --strictness-level 5 --validate $plugin 2>&1 | Tee-Object -FilePath "build-windows/test-results/pluginval.log" + if ($LASTEXITCODE -ne 0) { throw "VST3 validation failed ($LASTEXITCODE)" } + - name: Upload Windows test evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: wave-emulation-windows-test-results + path: | + build-windows/test-results/ + build-windows/Testing/Temporary/ + if-no-files-found: warn + - name: Include license and source information + shell: pwsh + run: | + $package = "build-windows/package" + New-Item -ItemType Directory -Force "$package/Standalone", "$package/VST3" | Out-Null + Copy-Item "build-windows/WaveEmulation_artefacts/Release/Standalone/Wave Emulation.exe" "$package/Standalone/" + Copy-Item "build-windows/WaveEmulation_artefacts/Release/VST3/Wave Emulation.vst3" "$package/VST3/" -Recurse + Copy-Item LICENSE, THIRD_PARTY_NOTICES.md, README.md $package + Copy-Item "data/BlankWave.img" "$package/Blank Wave.img" + Copy-Item LICENSES "$package/LICENSES" -Recurse + "Source: https://github.com/${{ github.repository }}/tree/${{ github.sha }}`nBuild: Windows x64 Release, private assets disabled" | Set-Content "$package/BUILD.txt" + - name: Upload Windows app and VST3 + uses: actions/upload-artifact@v4 + with: + name: wave-emulation-windows-x64 + path: build-windows/package/ + if-no-files-found: error diff --git a/.gitignore b/.gitignore index 4b34084..eba2184 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ *.pkg *.rom *.img +!/data/BlankWave.img *.zip *.log *.jucer diff --git a/BUILDING-0.1.11.md b/BUILDING-0.1.11.md new file mode 100644 index 0000000..931b6cd --- /dev/null +++ b/BUILDING-0.1.11.md @@ -0,0 +1,13 @@ +# Building Wave Emulation 0.1.11 + +This source archive contains the release source and the JUCE and Musashi sources used for the build, including local dependency patches. It contains no Git history or private instrument data. + +On macOS, from this directory: + +```sh +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DWAVE_EMBED_PRIVATE_ASSETS=OFF -DFETCHCONTENT_SOURCE_DIR_JUCE="$PWD/vendor/juce" -DFETCHCONTENT_SOURCE_DIR_MUSASHI="$PWD/vendor/musashi" +cmake --build build --parallel 4 +ctest --test-dir build --output-on-failure +``` + +Release bundles target macOS 13.0 and contain arm64 and x86_64 binaries. Public tests run without instrument firmware. Signing, PACE wrapping, and notarization require your own release credentials. See README.md and THIRD_PARTY_NOTICES.md for build and license details. diff --git a/BUILDING-0.1.12.md b/BUILDING-0.1.12.md new file mode 100644 index 0000000..aeee152 --- /dev/null +++ b/BUILDING-0.1.12.md @@ -0,0 +1,21 @@ +# Building Wave Emulation 0.1.12 + +This archive includes the source and the JUCE/Musashi dependencies used for this release, including local patches. It contains no Git history or private instrument data. + +On macOS, from this directory: + +```sh +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DWAVE_EMBED_PRIVATE_ASSETS=OFF -DWAVE_SIGN_RELEASE_ARTIFACTS=OFF -DFETCHCONTENT_SOURCE_DIR_JUCE="$PWD/vendor/juce" -DFETCHCONTENT_SOURCE_DIR_MUSASHI="$PWD/vendor/musashi" +cmake --build build --parallel 4 +ctest --test-dir build --output-on-failure +``` + +On Windows with Visual Studio 2022 and CMake: + +```powershell +cmake -S . -B build -G "Visual Studio 17 2022" -A x64 -DWAVE_EMBED_PRIVATE_ASSETS=OFF -DFETCHCONTENT_SOURCE_DIR_JUCE="$PWD/vendor/juce" -DFETCHCONTENT_SOURCE_DIR_MUSASHI="$PWD/vendor/musashi" +cmake --build build --config Release --parallel 4 +ctest --test-dir build -C Release --output-on-failure +``` + +macOS bundles are universal arm64/x86_64 and target macOS 13.0. Windows bundles target x64 and use the static release CRT. Signing, PACE wrapping and notarization require the maintainer's separate account configuration; no credentials are included. See README.md for cross-compilation and firmware setup. diff --git a/CMakeLists.txt b/CMakeLists.txt index b3dbb7f..3c023da 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,7 @@ if(CMAKE_HOST_APPLE AND NOT CMAKE_OSX_DEPLOYMENT_TARGET) "Minimum supported macOS version" FORCE) endif() -project(WaveEmulationSample VERSION 0.1.6 LANGUAGES C CXX) +project(WaveEmulationSample VERSION 0.1.13 LANGUAGES C CXX) include(FetchContent) @@ -14,6 +14,13 @@ set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) +# Keep Windows downloads self-contained, including the standalone executable. +# Apply the same CRT choice to JUCE, Musashi, plugins and tests. +if(MSVC AND NOT DEFINED CMAKE_MSVC_RUNTIME_LIBRARY) + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>" + CACHE STRING "MSVC runtime library") +endif() + option(WAVE_BUILD_TESTS "Build deterministic DSP and firmware tests" ON) # Build universal macOS bundles. Distribution signing is an explicit opt-in. @@ -33,6 +40,8 @@ FetchContent_Declare( GIT_TAG 8.0.15 GIT_SHALLOW TRUE) FetchContent_MakeAvailable(JUCE) +include(cmake/PrepareJuce.cmake) +wave_prepare_juce("${juce_SOURCE_DIR}") FetchContent_Declare( Musashi @@ -83,7 +92,9 @@ target_compile_definitions(WaveM68k PRIVATE M68K_INSTRUCTION_HOOK=1) set(WAVE_ASSET_SOURCES + data/BlankWave.img media/WaldorfWaveUI_NOLOGO.svg + media/WaldorfWaveUI_Compact.svg media/Slider.svg media/Knob1.svg media/Knob_red1.svg @@ -138,10 +149,13 @@ set(WAVE_CORE_SOURCES Source/Dsp/DspMath.h Source/Dsp/Cem3387.cpp Source/Dsp/Cem3387.h + Source/Dsp/Cem3387Transfer.h Source/Dsp/ReferenceComparator.cpp Source/Dsp/ReferenceComparator.h Source/Dsp/PpgWaveRom.cpp Source/Dsp/PpgWaveRom.h + Source/Dsp/WaveFactoryRom.cpp + Source/Dsp/WaveFactoryRom.h Source/Dsp/WaldorfAsic.cpp Source/Dsp/WaldorfAsic.h Source/Dsp/WaldorfEngine.cpp @@ -179,6 +193,8 @@ set(WAVE_CORE_SOURCES Source/WaveParameters.h) add_library(WaveCore STATIC ${WAVE_CORE_SOURCES}) +# Both libraries contain thread-local state and are linked into shared plugins. +set_target_properties(WaveCore WaveM68k PROPERTIES POSITION_INDEPENDENT_CODE ON) target_include_directories(WaveCore PUBLIC Source) target_link_libraries(WaveCore PUBLIC @@ -209,18 +225,38 @@ target_include_directories(DecodePpgWavetables PRIVATE Source) add_executable(CreateWaveDisk EXCLUDE_FROM_ALL Tools/CreateWaveDisk.cpp) target_link_libraries(CreateWaveDisk PRIVATE WaveCore juce::juce_recommended_config_flags) +add_executable(ProbeWaveFilter EXCLUDE_FROM_ALL Tools/ProbeWaveFilter.cpp) +target_link_libraries(ProbeWaveFilter PRIVATE WaveCore juce::juce_recommended_config_flags) + +add_executable(DecodeWaveFactoryWavetables EXCLUDE_FROM_ALL Tools/DecodeWaveFactoryWavetables.cpp) +target_link_libraries(DecodeWaveFactoryWavetables PRIVATE WaveCore juce::juce_recommended_config_flags) + if(MSVC) target_compile_options(WaveCore PRIVATE /W4 /permissive-) else() target_compile_options(WaveCore PRIVATE -Wall -Wextra -Wpedantic -Wconversion -Wshadow) endif() +if(APPLE) + set(WAVE_PLUGIN_FORMATS AU VST3 AAX Standalone) +else() + set(WAVE_PLUGIN_FORMATS VST3 Standalone) +endif() + +# JUCE's manifest helper is executed directly after linking and cannot run on +# the build host during Windows cross-compilation. VST3 hosts can scan the +# bundle without this optional JSON manifest. +set(WAVE_VST3_AUTO_MANIFEST TRUE) +if(CMAKE_CROSSCOMPILING) + set(WAVE_VST3_AUTO_MANIFEST FALSE) +endif() + juce_add_plugin(WaveEmulation COMPANY_NAME "DJW" BUNDLE_ID "com.DJW.WaveEmulation" PLUGIN_MANUFACTURER_CODE Djwh PLUGIN_CODE WvSm - FORMATS AU VST3 AAX Standalone + FORMATS ${WAVE_PLUGIN_FORMATS} PRODUCT_NAME "Wave Emulation" DESCRIPTION "Firmware-aware Waldorf Wave hardware modelling research sample" AAX_CATEGORY AAX_ePlugInCategory_SWGenerators @@ -229,6 +265,7 @@ juce_add_plugin(WaveEmulation NEEDS_MIDI_OUTPUT FALSE IS_MIDI_EFFECT FALSE EDITOR_WANTS_KEYBOARD_FOCUS TRUE + VST3_AUTO_MANIFEST ${WAVE_VST3_AUTO_MANIFEST} COPY_PLUGIN_AFTER_BUILD FALSE) target_sources(WaveEmulation PRIVATE diff --git a/Installer/build_installer.sh b/Installer/build_installer.sh index 3307350..ecbca4a 100755 --- a/Installer/build_installer.sh +++ b/Installer/build_installer.sh @@ -7,8 +7,8 @@ # are stored in this script. # # Common overrides: -# VERSION=0.1.6 (must match the built bundles) -# RELEASE_LABEL=0.1.6-resizable (shown in file names and the installer) +# VERSION=0.1.13 (must match the built bundles) +# RELEASE_LABEL=0.1.13-resizable (shown in file names and the installer) # BUILD_JOBS=8 # SKIP_PLUGIN_BUILD=1 # SKIP_WRAP=1 @@ -38,7 +38,7 @@ PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)" if [ -f "$PROJECT_ROOT/Installer/.env.local" ]; then source "$PROJECT_ROOT/Installer/.env.local" fi -BUILD_DIR="$PROJECT_ROOT/build" +BUILD_DIR="${BUILD_DIR:-$PROJECT_ROOT/build}" INSTALLER_DIR="$PROJECT_ROOT/Installer" WORK_DIR="$INSTALLER_DIR/.release-work" STAGING_DIR="$WORK_DIR/staging" @@ -46,9 +46,9 @@ PACKAGES_DIR="$WORK_DIR/packages" RESOURCES_DIR="$WORK_DIR/resources" DMG_STAGING_DIR="$WORK_DIR/dmg" -VERSION="${VERSION:-0.1.6}" -# Label for a derived release; the bundle version itself stays numeric. -RELEASE_LABEL="${RELEASE_LABEL:-$VERSION}" +VERSION="${VERSION:-0.1.13}" +# Label for this derived release; the bundle version itself stays numeric. +RELEASE_LABEL="${RELEASE_LABEL:-$VERSION-resizable}" TEAM_ID="${TEAM_ID:-}" BUILD_CONFIG="${BUILD_CONFIG:-Release}" CMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE:-$BUILD_CONFIG}" @@ -85,6 +85,13 @@ NOTARIZE_APPLE_ID="${NOTARIZE_APPLE_ID:-${APPLE_ID:-}}" NOTARIZE_PASSWORD="${NOTARIZE_PASSWORD:-${APP_SPECIFIC_PASSWORD:-}}" NOTARIZE_TEAM_ID="${NOTARIZE_TEAM_ID:-$TEAM_ID}" NOTARIZE_DMG="${NOTARIZE_DMG:-1}" +# An AAX bundle that is not PACE-wrapped will not load in Pro Tools and cannot +# pass notarization unsigned, so it is left out of the installer by default. +if is_truthy "${SKIP_WRAP:-}"; then + INCLUDE_AAX="${INCLUDE_AAX:-0}" +else + INCLUDE_AAX="${INCLUDE_AAX:-1}" +fi FINAL_PKG_NAME="${FINAL_PKG_NAME:-DJW $PRODUCT_NAME Installer $RELEASE_LABEL.pkg}" FINAL_DMG_NAME="${FINAL_DMG_NAME:-DJW $PRODUCT_NAME $RELEASE_LABEL.dmg}" @@ -99,14 +106,16 @@ find_signing_identities() { : "${TEAM_ID:?Set TEAM_ID for release signing, or use SKIP_SIGN=1}" if [ -z "${CODESIGN_IDENTITY:-}" ]; then + # Use the SHA-1 fingerprint, not the name: names with non-ASCII letters + # (e.g. Polish diacritics) get mangled and are then "not found". CODESIGN_IDENTITY="$(security find-identity -v -p codesigning | grep "Developer ID Application" | grep "$TEAM_ID" | head -1 | - sed -E 's/.*"([^"]+)".*/\1/' || true)" + awk '{print $2}' || true)" fi if [ -z "${INSTALLER_IDENTITY:-}" ]; then INSTALLER_IDENTITY="$(security find-identity -v | grep "Developer ID Installer" | grep "$TEAM_ID" | head -1 | - sed -E 's/.*"([^"]+)".*/\1/' || true)" + awk '{print $2}' || true)" fi if [ -z "$CODESIGN_IDENTITY" ] || [ -z "$INSTALLER_IDENTITY" ]; then @@ -277,8 +286,26 @@ stage_plugins() { "$STAGING_DIR/au/Library/Audio/Plug-Ins/Components/$AU_NAME" /usr/bin/ditto --noextattr --norsrc "$VST3_SOURCE" \ "$STAGING_DIR/vst3/Library/Audio/Plug-Ins/VST3/$VST3_NAME" - /usr/bin/ditto --noextattr --norsrc "$AAX_SOURCE" \ - "$STAGING_DIR/aax/Library/Application Support/Avid/Audio/Plug-Ins/$AAX_NAME" + if is_truthy "$INCLUDE_AAX"; then + /usr/bin/ditto --noextattr --norsrc "$AAX_SOURCE" \ + "$STAGING_DIR/aax/Library/Application Support/Avid/Audio/Plug-Ins/$AAX_NAME" + fi + + local notices="$STAGING_DIR/standalone/Library/Application Support/DJW/Wave Emulation" + mkdir -p "$notices" + /usr/bin/ditto --noextattr --norsrc "$PROJECT_ROOT/data/BlankWave.img" \ + "$notices/Blank Wave.img" + for file in LICENSE THIRD_PARTY_NOTICES.md; do + /usr/bin/ditto --noextattr --norsrc "$PROJECT_ROOT/$file" "$notices/$file" + done + /usr/bin/ditto --noextattr --norsrc "$PROJECT_ROOT/LICENSES" "$notices/LICENSES" + cat >"$notices/BUILD.txt" <" + aax_ref="WaveEmulation_AAX.pkg" + formats="AU, VST3 and AAX" + fi MODIFIED_BY="${MODIFIED_BY:-Bronisław Hońca}" - MODIFIED_DATE="${MODIFIED_DATE:-2026-09-27}" + MODIFIED_DATE="${MODIFIED_DATE:-2026-10-11}" MODIFIED_URL="${MODIFIED_URL:-https://bronislawhonca.pl}" cat >"$RESOURCES_DIR/welcome.html" <

$PRODUCT_NAME $RELEASE_LABEL

-

This installer provides the Wave Emulation standalone app in /Applications, plus AU, VST3 and AAX instrument formats.

+

This installer provides the Wave Emulation standalone app in /Applications, plus $formats instrument formats.

Authors

Original software: Wave Emulation © 2026 Dave Whiting (github.com/mo0kid/wave).

This is a modified version, changed by $MODIFIED_BY (${MODIFIED_URL#https://}) on $MODIFIED_DATE: -resizable editor window that fits the screen, zoom steps and shortcuts (Cmd +, Cmd −, Cmd 0), -compact layouts without the on-screen keyboard, remembered window size and layout. -The sound engine is unchanged.

+the editor opens at a size that fits your screen instead of the full 2338-pixel panel, +remembers its zoom and keyboard visibility between sessions, and adds Fit to Screen +(System menu or Cmd/Ctrl + Shift + 0). The sound engine is unchanged.

License

Free software under the GNU General Public License, version 3 or later, with no warranty. The complete source code of this version is included on this disk image (Wave Emulation $RELEASE_LABEL Source.zip). JUCE is used under the AGPLv3; see the third-party notices on the disk image.

-

No Waldorf system firmware, sound sets or floppy images are included – -supply your own Wave OS 1.700 files. Waldorf and Wave are trademarks of their respective owner; +

No Waldorf system firmware or factory sound sets are included (only an empty +Blank Wave.img) – supply your own Wave OS 1.700 files. Waldorf and Wave are trademarks of their respective owner; this project is not affiliated with or endorsed by Waldorf Music.

WELCOME @@ -379,16 +413,16 @@ WELCOME - + $aax_outline - + $aax_choice WaveEmulation_Standalone.pkg WaveEmulation_AU.pkg WaveEmulation_VST3.pkg - WaveEmulation_AAX.pkg + $aax_ref DISTRIBUTION @@ -461,6 +495,11 @@ build_dmg() { mkdir -p "$DMG_STAGING_DIR" /usr/bin/ditto --noextattr --norsrc "$FINAL_PKG" \ "$DMG_STAGING_DIR/$FINAL_PKG_NAME" + /usr/bin/ditto --noextattr --norsrc "$PROJECT_ROOT/data/BlankWave.img" \ + "$DMG_STAGING_DIR/Blank Wave.img" + /usr/bin/ditto --noextattr --norsrc \ + "$STAGING_DIR/standalone/Library/Application Support/DJW/Wave Emulation" \ + "$DMG_STAGING_DIR/License and Source Information" if [ -n "$MANUAL_PDF" ]; then /usr/bin/ditto --noextattr --norsrc "$MANUAL_PDF" \ "$DMG_STAGING_DIR/$(basename "$MANUAL_PDF")" @@ -473,9 +512,6 @@ build_dmg() { "$(basename "$PROJECT_ROOT")" \ -x "*/build/*" "*/build-*/*" "*/.release-work/*" "*/Firmware/*" \ "*.dmg" "*.pkg" "*.set" "*/.env.local" "*/.git/*" "*.DS_Store") - for doc in LICENSE THIRD_PARTY_NOTICES.md; do - /usr/bin/ditto --noextattr --norsrc "$PROJECT_ROOT/$doc" "$DMG_STAGING_DIR/$doc" - done rm -f "$FINAL_DMG" hdiutil create -volname "DJW $PRODUCT_NAME" -srcfolder "$DMG_STAGING_DIR" \ -ov -format UDZO "$FINAL_DMG" @@ -514,8 +550,10 @@ build_plugins validate_bundle "$APP_SOURCE" validate_bundle "$AU_SOURCE" validate_bundle "$VST3_SOURCE" -validate_bundle "$AAX_SOURCE" -wrap_aax +if is_truthy "$INCLUDE_AAX"; then + validate_bundle "$AAX_SOURCE" + wrap_aax +fi stage_plugins sign_staged_plugins build_packages diff --git a/PUBLIC_RELEASE.md b/PUBLIC_RELEASE.md index 1d103f1..62ba0d0 100644 --- a/PUBLIC_RELEASE.md +++ b/PUBLIC_RELEASE.md @@ -27,16 +27,21 @@ git commit -m "Initial public source release" The exporter includes current working-tree edits and approved source directories. It excludes the old logo artwork, factory-table payload header, firmware, -Wave sound libraries, ROM archives, disk images, installers, build directories, +Wave sound libraries, ROM archives, other disk images, installers, build directories, and all existing Git history. It refuses to overwrite a destination. Review new source files before exporting; a file allowlist is not a substitute for reviewing newly added data or secrets. Public builds default to `WAVE_EMBED_PRIVATE_ASSETS=OFF` and `WAVE_SIGN_RELEASE_ARTIFACTS=OFF`, even if private assets are present locally. -The approved decoded PPG sample bank in `data/` is included. -The upper Wave factory tables use the procedural fallback unless explicitly enabled -in a private development build. Users may import their own wavetable data. +The approved decoded PPG sample bank and maintainer-supplied blank INIT disk +in `data/` are included. The blank disk is embedded for new-instance startup +and included separately in release packages. +Loading the authenticated Wave OS 1.700 firmware supplied by the user generates +all 64 original factory tables by executing the firmware's own routines. Before +Wave firmware is loaded, the public build uses its PPG/procedural fallback. +Firmware and derived factory-table payloads are not included in the snapshot. +See [wavetable authenticity](docs/wavetable-authenticity.md) for verification details. Publish only the new snapshot repository after reviewing its files. No remote is configured by the exporter. Existing private installers and DMGs may embed diff --git a/README.md b/README.md index bc79057..6fe1758 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,47 @@ A JUCE C++ research instrument that recreates the documented Waldorf Wave signal path: 250 kHz 8-bit/time-multiplexed wavetable voices, the ES2 ASIC's signed mixer overflow, the ASIC's 12 dB digital high-pass, CEM3387 three-pole reconstruction and separately saturating nonlinear resonant four-pole low-pass sections, 12-bit control-voltage stepping, VCA/panning, and the 480 x 64 monochrome graphic LCD. +## This modified version (0.1.13-resizable) + +This fork of Wave Emulation 0.1.13 by Dave Whiting was modified by +Bronisław Hońca ([bronislawhonca.pl](https://bronislawhonca.pl)) on 2026-10-11. +On top of the original zoom and compact-skin features, the editor now opens at +a size that fits the screen instead of the full 2338-pixel panel, remembers its +zoom and keyboard visibility between sessions, and offers **System → Fit to +Screen** (Cmd/Ctrl + Shift + 0). `build-mac.sh` makes a quick local build, and +the installer adds an author and modification notice, shows the GPL and puts +the complete source code on the DMG. The sound engine is unchanged. Distributed +under the same GPL-3.0-or-later license. + +Build the DMG on a Mac: + +```sh +SKIP_WRAP=1 SKIP_SIGN=1 SKIP_NOTARIZE=1 ./Installer/build_installer.sh +``` + +## Downloads + +| Platform | Download | Included formats | +| --- | --- | --- | +| Windows x64 — 0.1.13 | [Windows ZIP](https://github.com/mo0kid/wave/releases/download/v0.1.13/Wave-Emulation-0.1.13-Windows-x64.zip) | Standalone EXE and VST3 | +| macOS 13.0 or later, Apple Silicon and Intel — 0.1.13 | [macOS installer DMG](https://github.com/mo0kid/wave/releases/download/v0.1.13/DJW.Wave.Emulation.0.1.13.dmg) | Standalone app, AU, VST3 and AAX | + +See the [0.1.13 release page](https://github.com/mo0kid/wave/releases/tag/v0.1.13) +for release notes. The DMG contains the installer and Blank Wave.img. +The [corresponding source ZIP](https://github.com/mo0kid/wave/releases/download/v0.1.13/Wave-Emulation-0.1.13-Source.zip) +is a separate download and includes the modified dependencies used for the build. +The public source is also available [in the repository](https://github.com/mo0kid/wave/tree/v0.1.13). + +Supply your own Wave OS 1.700 firmware and sound disks. The release contains +no firmware, ROM archives or Wave factory sound SETs. + Enjoying Wave Emulation? [Leave a tip on Ko-fi](https://ko-fi.com/djw_audio) to support its development. Support development with a tip on Ko-fi -The public build includes the decoded PPG V6 wavetable sample bank, with -procedural fallback for the remaining tables. It contains no executable firmware, +Loading authenticated Wave OS 1.700 firmware generates all 64 original factory +wavetables using the firmware’s own routines. Before firmware is loaded, the public +build uses the decoded PPG V6 sample bank and procedural fallback tables. It contains no executable firmware, ROM archives, Wave factory sound sets, or upper Wave factory wavetable payload. See [data provenance and format](data/README.md). You can load your own Wave OS 1.700 firmware (`w2sys.bin` and `wdv.sys`) and wavetable images locally. @@ -18,6 +53,33 @@ its [legacy Wave page](https://waldorfmusic.com/legacy-wave/). The editor embeds `media/WaldorfWaveUI_NOLOGO.svg` as its 2338 x 1042 source artwork. JUCE controls are transparent hit regions aligned to the artwork coordinates, and the live framebuffer is rendered only inside the LCD rectangle at `(939, 237, 448, 70)`. Additional panel switch, rotary, and fader regions are derived at runtime from the circles and rounded rectangles already in that SVG. The eight Performance faders use relative mouse dragging, retain their physical positions across Performance changes, and apply the destination/parameter assignments stored in each native factory Performance record only after a fader is moved. A playable 61-note keyboard spans C2 through C7 in the lower black keyboard bed, with pressed-key feedback and drag glissando. +Use **Cmd/Ctrl + =** and **Cmd/Ctrl + -** to zoom the editor in and out, **Cmd/Ctrl + 0** for actual size, and **Cmd/Ctrl + K** to show or hide the lower keyboard and controller area. The same actions are in the System menu. Hiding the lower area shortens the window while keeping the upper panel at the same scale. + +Hover over any knob or fader to see its tooltip. Knob names follow the selected LFO and envelope page; hold Shift while dragging a knob for finer adjustment. Fader tips identify the numbered control and whether it uses a Performance assignment or the current LCD parameter. + +Choose **System → Panel Skin → Compact Skin** for the bundled 1693 × 768 layout, with the controls rearranged around the LCD and no keyboard, wheels, or transport controls. The selection is remembered for future instances. Choose **Original** to return to the full panel. + +To use your own artwork in the original layout, choose **System → Panel Skin → Load Alternative SVG Skin…**. The selected file is remembered for future instances; keep it at the same path. Missing or invalid files fall back to the original skin. + +Create a larger-label skin by copying [the original panel SVG](media/WaldorfWaveUI_NOLOGO.svg) and editing its labels, colours, or decoration. Keep `width="2338"`, `height="1042"`, and `viewBox="0 0 2338 1042"`, and leave all control, LCD, LED, and keyboard positions unchanged. Only panel artwork is replaced; the moving controls, keyboard, LEDs, LCD, and interaction geometry retain their original layout. Export text as paths for consistent rendering across machines. Reload the SVG from the menu after editing it. + +## Installing the Windows release + +1. Download and extract the Windows ZIP. Run + `Standalone/Wave Emulation.exe` to use the portable standalone application. +2. To install the VST3, quit your DAW and copy the entire + `VST3/Wave Emulation.vst3` folder into + `C:\Program Files\Common Files\VST3`. Copying into Program Files may require + administrator permission. Reopen your DAW and rescan plug-ins, then add + **Wave Emulation** as a virtual instrument. +3. Load your firmware folder and sound disk in the standalone or plug-in using + the [firmware and sound-disk instructions](#before-you-start-system-and-sound-floppies). + +The Windows binaries are unsigned and do not require a separate Visual C++ +redistributable installation. The ZIP includes installation instructions and +licenses. Windows builds include VST3 and standalone formats; AU and AAX are +available in the macOS release. + ## Installing the macOS release Builds target macOS Ventura 13.0 or later on Apple Silicon and Intel Macs. @@ -25,13 +87,72 @@ Plugin use also requires a host compatible with your macOS version. CPU and RAM minimums have not yet been established by testing. Earlier release binaries may have a higher macOS minimum; they must be rebuilt to support Ventura. -Run the installer inside the release DMG. Starting with version 0.1.2, it installs +Download the macOS DMG linked above and run the installer inside it. +Starting with version 0.1.2, it installs **Wave Emulation.app** in `/Applications` as well as the AU, VST3, and AAX plugins. Quit any older standalone instance, then launch `/Applications/Wave Emulation.app`. Older development copies named **Wave Emulation Sample.app** are separate files and are not updated by this installer. Versions 0.1.0 and 0.1.1 installed only the plugins, so they did not update a standalone app you already had open. +## What's new in 0.1.13 + +New instances automatically mount the bundled blank INIT disk and load its SET, +with Instrument 1 active and editable. The release also adds the compact panel +skin, improves panel input and firmware-derived voice behavior, and refines +the CEM3387 filter model. See [the release notes](docs/release-0.1.13.md). + +## What's new in 0.1.12 + +Version 0.1.12 fixes original factory/user wavetable loading, saved +wavetable selections, LCD browsing and Store state, Instrument voice allocation, +and Button 1/2 touch/toggle and MIDI routing. It adds WTB-to-disk-image conversion +and automatic flushing of emulated disk writes. The full internal oscillator +sampling rate is retained. See [the release notes](docs/release-0.1.12.md). + +## What's new in 0.1.11 + +[Version 0.1.11](https://github.com/mo0kid/wave/releases/tag/v0.1.11) restores complete Performance and Sound banks when reopening, including native Store names containing NUL bytes. It fixes Total Recall after cancelling optional machine-specific adjustments, mode lamps after Store, repeated + browsing after Store, and pending writes when remounting the same disk image. + +The macOS installer is signed, notarized, and contains universal Apple Silicon and Intel builds of the standalone app, AU, VST3, and PACE-wrapped AAX. The [macOS source archive](https://github.com/mo0kid/wave/releases/download/v0.1.11/Wave-Emulation-0.1.11-Source.zip) includes the modified dependencies used for the build. [Checksums](https://github.com/mo0kid/wave/releases/download/v0.1.11/SHA256SUMS.txt) cover the installer, source archive, and release notes. + +## What's new in 0.1.10 + +[Version 0.1.10](https://github.com/mo0kid/wave/releases/tag/v0.1.10) is a Windows +maintenance release. It restores embedded Common Controls v6 manifests in the +standalone EXE and VST3 DLL, addressing the **Ordinal 345 not found** startup +error reported on Windows 10 in [issue #2](https://github.com/mo0kid/wave/issues/2). +The build workflow now checks both manifests before running tests. + +At publication of 0.1.10, Windows 10 runtime confirmation and native MSVC CPU-test +issues remained under investigation. See the current release validation report +for the checks completed for 0.1.12. + +## Version history + +### Version 0.1.8 + +Version 0.1.8 is available for Windows x64 as a standalone EXE and VST3, as well +as the macOS formats above. The Windows build improves window startup, +shutdown and UI refresh when display refresh notifications are unavailable. + +[Version 0.1.8](https://github.com/mo0kid/wave/releases/tag/v0.1.8) preserves saved Sound parameters, including oscillator octave, +when switching Performances and layers. It also prevents a display refresh +from replacing a Performance name during Store, clears inactive destination +layers when overwriting a Performance, and handles brief Store Cancel clicks. +Store also keeps mode buttons and their LEDs in sync with the firmware page. +Instrument Edit faders follow the firmware's current page so a tuning change +cannot write to Transpose or another page's parameter. The TuneTable slider's +choices now follow the displayed positions, and HMT changes preserve the pitch +of held and newly played notes. Window zoom and keyboard visibility shortcuts +are available in the System menu. + +### Earlier releases + +[Version 0.1.7](https://github.com/mo0kid/wave/releases/tag/v0.1.7) fixes repeated or missed front-panel actions in Disk, Store, and +Instrument Edit, including name cursors and Load-menu stepping. It also keeps +Performance program names and layered sounds consistent when switching modes. + [Version 0.1.6](https://github.com/mo0kid/wave/releases/tag/v0.1.6) targets macOS Ventura 13.0 and later in universal Apple Silicon/Intel builds of the standalone app, AU, VST3 and AAX plugins. The installer checks the minimum OS, @@ -52,7 +173,7 @@ instances' firmware-emulator execution state independent, and connects voice-car workers to the host's macOS audio workgroup when provided. Version 0.1.3 remains withdrawn; users of that version should update to 0.1.5. -### CPU load in Logic Pro +## CPU load in Logic Pro Wave can split voice processing across three threads at higher polyphony. Light loads and very short audio segments run serially to avoid worker overhead; @@ -64,35 +185,10 @@ Multithreading > Playback & Live Tracks**. This lets Logic distribute eligible live tracks across processing threads; it does not automatically divide one plugin's processing. See [Apple's multithreading guide](https://support.apple.com/en-ae/101975). -## Modified version - -This is a modified version of Wave Emulation 0.1.6 by Dave Whiting, changed by -Bronisław Hońca ([bronislawhonca.pl](https://bronislawhonca.pl)) on 2026-09-27. Changes: resizable, screen-fitting editor -window with zoom steps and shortcuts, compact layouts without the on-screen -keyboard, remembered window size and layout, a local macOS build script -(`build-mac.sh`), and an installer/DMG that includes this source code, the -license and author information. The sound engine and firmware handling are -unchanged. Distributed under the same GPL-3.0-or-later license. - -## Window size and compact layouts - -The editor opens at a size that fits the current screen and remembers the last -zoom and layout (stored in `~/Library/Application Support/Wave Emulation/`). -Open the floppy-icon **System** menu at the top left and choose **View**: - -- **Full Panel with Keyboard** – the original layout. -- **Hide On-Screen Keyboard** – keeps the transport, Shift and Glide controls but - removes the keybed, wheels, octave buttons and System Volume. -- **Upper Panel Only** – just the synthesis panel and display. -- **Fit to Screen**, **Zoom In/Out** and fixed zoom steps from 35 % to 100 %. - -Shortcuts while the editor has focus: Cmd + / Cmd − to zoom, Cmd 0 to fit the -screen. The window can also be resized by dragging its lower-right corner. - ## Before you start: system and sound floppies **You must obtain your own Waldorf Wave system floppy files to run the original -operating system in this emulation.** The installer/DMG does not contain the +operating system in this emulation.** The release packages do not contain the Wave system ROM, voice firmware, factory sound disks, or floppy images. The included PPG wavetables are sound data, not the Wave operating system. @@ -114,8 +210,50 @@ included PPG wavetables are sound data, not the Wave operating system. image. These extensions must contain a supported raw floppy image, not a ZIP. Use the Wave panel's Disk controls to load its contents. 4. If you have a Wave `.set` file instead, choose **Create Disk Image from Wave - Setup...** to create and mount a 720 KB DD image. A new blank disk contains + Setup...** to create and mount a 720 KB DD image, then confirm the SET import + with the Wave panel's **OK** button. Creating a blank disk instead provides no system firmware or factory sounds. +5. For a native Wave `.wtb` file, choose **Create Disk Image from WTB...**, + select the file and save the new `.img`. The image is mounted automatically; + load the WTB using the Wave panel's Disk controls. WTB bytes, including any + attached Wave data, are preserved unchanged. + +Additional sound banks and wavetables are available from the **Sounds** +download on [Waldorf's legacy Wave page](https://waldorfmusic.com/legacy-wave/). +The archive includes contributions credited to Dirk Gehl and Peter Eulert, +Till Kopper, and other sound designers. Download and extract it from Waldorf, +then use the SET or WTB conversion instructions above to create disk images. +These third-party banks are not bundled with this project; their contents +remain subject to the original authors' terms and are not covered by this +repository's licence. + +Fresh instances mount a private, writable copy of the bundled **Blank Wave.img** +and automatically load its SET. Both banks contain INIT Sounds and **MULTI INIT** +Performances, with Instrument 1 active and selected, so the panel has an editable +Sound immediately after system firmware is loaded. No Disk/Import confirmation +is needed. The blank image is also included separately in the macOS DMG and +Windows ZIP. Choosing **Create Blank Disk Image...** still creates an empty disk. +Each plug-in instance has its own sound-bank state. Saving a DAW project embeds +that instance's mounted disk image and bank, so reopening restores them even if +the original image has moved. The standalone restores its last saved session. +For an older session containing stale bank entries, **System > Reload Performance +Bank from Mounted Image** replaces the bank with the mounted image's SET; +save the project afterwards to retain the corrected bank. + +A SET with a few malformed records can still load its valid bank. Those damaged +slots are treated as empty in the working sound/performance banks, with the +source image preserved. Selecting an empty Performance clears its Instruments +and completes the native LCD recall instead of retaining the preceding patch. + +Wave Disk-page writes (including Save, Delete and Format) automatically overwrite +the currently mounted image. Sector writes are batched and saved in the +background, with a complete temporary file replacing the image only after a +successful write. Read-only images remain write-protected. If saving fails, the +System menu's disk status reports it; pending changes stay in memory and are +retried. **Save Mounted Disk Image** also commits pending changes immediately. +Recalled DAW disks remain private copies of the project's embedded snapshot; +use **Save Mounted Disk Image As...** to save that copy to an external image, +which then becomes the mounted file for subsequent writes. The app can open without firmware and provide its behavioural synthesis fallback, but that does not run the original Wave operating system. Mounting a @@ -133,22 +271,22 @@ This sample is honest about a hard distinction: - The master 68000 runs continuously on a 16 MHz emulated clock with a 1 kHz timer source. The model exposes the documented UART, timer/mode, RTC/latch, front-panel switch/LED, ADC-selection/readback, shared-memory, and LCD windows used by the authenticated boot path. - The WDV voice image's 32-byte loader header is decoded and its genuine 68000 body publishes at shared mailbox `$105086`, waits for the main CPU at `$10508A`, and reaches its service state after that externally visible acknowledgement. Production code no longer inserts a synthetic acknowledgement. - Both CPU runtimes use the same shared program/work SRAM object. The genuine master `w2sys.bin` executes its cold-start hardware writes and its OS 1.700 post-copy loader handoff, writing the observed acknowledgement value `1` to `$10508A`; the WDV CPU then publishes service at `$10508E`. -- The decoded WDV service transport uses a per-board 16-voice update mask at `$105092`, per-voice TAS semaphores at `$1050A2`, and 256-byte voice records beginning at `$100000`. The WDV runtime maps its observed waveform RAM at `$600000`, CV banks at `$880000/$8A0000`, and two oscillator-chip register pages at `$980000/$980100`. All writes are timestamped on the WDV clock for correlation with captures. +- The decoded WDV service transport uses a per-board 16-voice update mask at `$105092`, per-voice TAS semaphores at `$1050A2`, and 256-byte voice records beginning at `$100000`. The WDV runtime maps its two wave RAMs at `$040000`/`$050000` (with a write-both alias at `$060000`), CV banks at `$880000/$8A0000`, and two oscillator-chip register pages at `$980000/$980100`. All writes are timestamped on the WDV clock for correlation with captures. - The current bridge supplies `INIT.SND` and `INIT.PFM` through a narrowly scoped virtual system-disk service, and the genuine OS 1.700 loader opens, reads, and closes both files. Until original factory files are available, their contents are byte-exact copies of the genuine safe sound and performance records embedded in OS 1.700; they are conservative defaults, not claimed factory banks. The same records are preloaded as a defensive fallback. The CPU board's DP8473 floppy controller is modelled for mounted raw MS-DOS disk images; the separate boot-time `WDV.SYS` copy remains bypassed because the authenticated WDV body is installed directly into shared SRAM before the genuine master instructions resume at the verified post-copy handoff. This is not presented as a complete main-OS boot. - The CPU-board LCD is represented as two byte-wide 5563 SRAMs forming a 16-bit word, four 4 KiB pages, two parallel 74LS166 shifters, and the firmware page latch at `$BE0001`. The genuine OS renderer proves a 64-byte hardware scanline: 60 visible bytes for 480 pixels followed by four blanking bytes. Writes in the `$FEA00000-$FEA03FFF` video window automatically replace the model diagnostics with correctly decoded firmware scanout. - The oscillator ASIC is an undocumented black box. Its internal algorithms cannot be recovered or claimed from the available documentation. The DSP is explicitly an external behavioural proxy, using Waldorf's documented 250 kHz rate and ES2 eight-bit numerical mix-overflow boundary; its exact accumulator ordering and truncation remain to be validated against real-hardware measurements. Firmware register traces reveal only the external contract. -- The included procedural wavetable bank is a neutral fallback. The loader accepts a user-supplied exact 64 or 128 x 64 x 128 signed-eight-bit dump, a 32 x 64 x 128 first-table dump, or a raw PPG Wave 2.2/2.3 EPROM image. Raw PPG images are decoded from their 768-byte sparse table directory and 256 stored 64-sample half waves. The V6 firmware's recursive midpoint averaging, complemented half-cycle, calculated tables 28/29, and byte-exact triangle/pulse/square/saw tail are reproduced, yielding all 30 original lower tables. Native Wave SET images also install all 64 user Wavetables and their 1000-Wave pool. The lower 30 PPG tables are included as decoded samples. Remaining tables retain procedural fallback data until a user imports a bank. +- Loading the authenticated Wave OS 1.700 firmware installs all 64 original factory wavetables by executing its own 68000 table routines, including slot 60 and the original triangle/square/saw standards. Saved PPG paths cannot replace this bank during startup or project recall. Native Wave SET images supply their own 64 user tables and 1000-Wave pool. Without Wave firmware, the included lower 30 PPG tables and procedural upper tables remain a fallback. Explicit imports of signed-eight-bit 64/128-table banks, first-32-table banks and PPG EPROM images remain available for research. See [wavetable verification](docs/wavetable-authenticity.md) for provenance, hashes and limits. - The filter path implements all four sound-record modes: analogue 24 dB low-pass, digital 12 dB high-pass, linked serial band-pass with width, and Dual mode with independently modulated HP/LP cutoffs. The WDV frequency table establishes semitone-spaced cutoff values beginning at 20 Hz. The fixed CEM3387 three-pole 1 dB Chebyshev reconstruction section and nonlinear resonant four-pole low-pass are separate from the pre-analogue ASIC high-pass. Envelope selection, velocity, key tracking, both modulation routes, resonance modulation, and maximum-resonance self-oscillation are active. Unknown ASIC arithmetic and unmeasured component tolerances remain explicit calibration hypotheses. -- The mixed-signal path explicitly models eight-bit multiplexed conversion, signed ES2 mixer wrap, sample-and-hold behaviour, three-pole reconstruction and AC coupling, the distinct VCF input saturation around 70% mixer output, AD7545-style 12-bit CV quantisation, nonlinear four-pole CEM3387 filtering, VCA bleed/noise, panning, output coupling, slew, and rails. Values without measurements remain documented calibration hypotheses. +- The mixed-signal path explicitly models eight-bit multiplexed conversion, signed ES2 mixer wrap, sample-and-hold behaviour, three-pole reconstruction and AC coupling, estimated VCF input/output headroom, AD7545-style 12-bit CV quantisation, nonlinear four-pole CEM3387 filtering, VCA bleed/noise, panning, output coupling, slew, and rails. The [CEM3387 model notes](docs/cem3387-filter.md) document the datasheet-guided distortion estimate and assumed signal-voltage scale; hardware measurements are still needed to calibrate them. - MIDI bytes are delivered to the master UART at their host-sample offsets while the behavioural audio engine receives the same event timeline. This preserves a useful audible instrument during protocol research without falsely claiming that every high-level WDV voice-record field has already been named. - `ReferenceComparator` and `reference-captures/README.md` provide the real-hardware validation path: alignment, fitted gain, normalized correlation, RMS error, and peak error. Set `WAVE_REFERENCE_CAPTURE` when running tests to compare a capture. - The live LCD scanout is 480 x 64 at one bit per pixel. Before genuine firmware produces video writes, the same framebuffer shows the sound and firmware diagnostic pages. -That makes this a useful, buildable hardware-model foundation rather than a false claim of bit-perfect emulation. A real-Wave capture set, factory wavetable data supplied by its owner, and oscillator-chip bus/audio measurements are still required before the words “sample accurate” or “circuit accurate” would be defensible. +That makes this a useful, buildable hardware-model foundation rather than a false claim of bit-perfect emulation. A real-Wave capture set and oscillator-chip bus/audio measurements are still required before the words “sample accurate” or “circuit accurate” would be defensible. ## Build -Requirements: CMake 3.25+, Ninja or Xcode, and a C++20 compiler. JUCE 8.0.15 is fetched automatically. +Requirements: CMake 3.25+, Ninja, Xcode or Visual Studio 2022, and a C++20 compiler. JUCE 8.0.15 is fetched automatically. ```sh cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release @@ -158,12 +296,29 @@ ctest --test-dir build --output-on-failure For private development only, place your own images in `Firmware/wave_sys1_700`, an optional factory set at `wave.set`, and an optional -private upper-table header at `Firmware/private/FactoryUpperWavetables.h`. +legacy upper-table fallback at `Firmware/private/FactoryUpperWavetables.h`. +The authenticated firmware supplies the complete original bank at startup. Configure a separate build with `-DWAVE_EMBED_PRIVATE_ASSETS=ON` to embed them. Do not distribute artifacts from that build. The installer explicitly disables private embedding. Firmware-backed integration/editor tests are enabled only when all three private ROM inputs are present and embedding is enabled. +The private build also provides `WavePerformanceBenchmark`. Its arguments are +block size, voice count, DSP resonance (0–1), sample rate, rendered seconds, +and full-processor program index (defaults: 512, 48, 0.18, 48000, 2, 12): + +```sh +build/Tests/WavePerformanceBenchmark 512 48 0.18 48000 2 12 +``` + +Compare repeated Release runs on the same machine. The benchmark reports +elapsed rendering time separately from process CPU time summed across all +threads, whether firmware is loaded, and how many voices actually rendered. +CPU time per second of rendered audio measures processor work; elapsed time +also includes scheduling and worker waits. The resonance +argument controls the standalone DSP fixture; the full-processor fixture uses +its selected Performance. + For the authenticated continuous-firmware core tests: ```sh @@ -185,7 +340,9 @@ PPG_WAVETABLE_ROM=/path/to/ppg-eprom.bin \ ctest --test-dir build --output-on-failure ``` -The Standalone, Audio Unit, VST3, and AAX artifacts are written below +### macOS bundles and installer DMG + +On macOS, the Standalone, Audio Unit, VST3, and AAX artifacts are written below `build/WaveEmulation_artefacts`. macOS Release bundles are universal `arm64`/`x86_64` binaries and are unsigned by default. To sign a local release, explicitly set `WAVE_SIGN_RELEASE_ARTIFACTS=ON` and `WAVE_CODESIGN_IDENTITY` when configuring CMake. Distribution to normal Pro Tools systems additionally @@ -208,9 +365,117 @@ environment overrides documented at its top. For a local packaging check that does not contact PACE or Apple, use `SKIP_WRAP=1 SKIP_SIGN=1 SKIP_NOTARIZE=1 SKIP_DMG=1`. +### Windows x64 build + +Install Visual Studio 2022 with Desktop development with C++ and CMake 3.25 or +newer. From a PowerShell terminal, build the standalone app and VST3 plugin: + +```powershell +cmake -S . -B build-windows -G "Visual Studio 17 2022" -A x64 -DWAVE_EMBED_PRIVATE_ASSETS=OFF +cmake --build build-windows --config Release --parallel 3 +ctest --test-dir build-windows -C Release --output-on-failure +``` + +The `.exe` and `.vst3` bundle are under +`build-windows/WaveEmulation_artefacts/Release`. Copy the VST3 bundle to +`C:\Program Files\Common Files\VST3` to use it in a VST3 host. The standalone +app can run directly from its build folder. Windows builds do not include AU or +AAX. The default Windows build links the C++ runtime statically, so these +downloads do not require a separate Visual C++ redistributable installer. + +### Testing Windows without a Windows computer + +For local testing on macOS, `cmake/WindowsLLVMToolchain.cmake` builds Windows +x64 binaries with `clang-cl`, `lld-link`, and Microsoft's headers/libraries +downloaded with [xwin](https://github.com/Jake-Shadle/xwin). Accept Microsoft's +license before downloading the SDK. JUCE 8 does not support MinGW compilation; +use the MSVC target provided by this toolchain. The build applies a small JUCE +VBlank-thread fallback so unsupported DXGI refresh calls in Wine still trigger +repaints and cannot deadlock window creation or teardown. + +With CrossOver installed and a Windows 10 64-bit bottle named +`Wave Windows Testing`, configure a Release build: + +```sh +cmake -S . -B build-windows-local/msvc -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_TOOLCHAIN_FILE="$PWD/cmake/WindowsLLVMToolchain.cmake" \ + -DWAVE_WINDOWS_SDK_ROOT="$PWD/build-windows-local/sdk" \ + -DWAVE_CLANG_CL=/opt/homebrew/opt/llvm/bin/clang-cl \ + -DWAVE_LLD_LINK="$PWD/build-windows-local/toolchain/bin/lld-link" \ + -DCMAKE_CROSSCOMPILING_EMULATOR="/usr/bin/python3;$PWD/scripts/run-windows-crossover.py" \ + -DWAVE_EMBED_PRIVATE_ASSETS=OFF +cmake --build build-windows-local/msvc --parallel 4 +WAVE_TEST_NATIVE_WINDOW=1 WAVE_TEST_ARTIFACT_DIR="$PWD/build-windows-local/evidence" \ + ctest --test-dir build-windows-local/msvc --output-on-failure +``` + +Supply the paths to your installed tools and xwin SDK. The SDK must include +the x64 release CRT. Cross builds omit the optional VST3 `moduleinfo.json`; +hosts can scan the plugin DLL directly. The runner uses CrossOver's configured +bottle directory, or `CX_BOTTLE_PATH`, and accepts an alternate bottle name +through `WAVE_CROSSOVER_BOTTLE`. It also runs the standalone executable: + +```sh +WAVE_CROSSOVER_GUI=1 python3 scripts/run-windows-crossover.py \ + 'build-windows-local/msvc/WaveEmulation_artefacts/Release/Standalone/Wave Emulation.exe' +``` + +Install Windows REAPER in the same bottle and copy the complete VST3 bundle to +that bottle's `C:\Program Files\Common Files\VST3` directory for DAW testing. +Load your locally obtained firmware through Wave's System menu. CrossOver +testing covers Windows binaries on Wine; native Windows audio/MIDI drivers +still require a Windows computer or VM. + +`WAVE_TEST_NATIVE_WINDOW=1` also opens, recreates and closes a real editor window +in the public editor test. `WAVE_CROSSOVER_GUI=1` uses Windows ShellExecute for +interactive launches; omit it for test executables and build generators. + +The **Public source build** GitHub Actions workflow uses a Windows x64 runner +to build the standalone app and VST3. It runs on pushes and pull requests and +can also be started from the workflow's **Run workflow** button. Its Windows +job checks: + +- DSP/core tests, concurrent 68000 instances, and host state save/recall. +- Editor creation, rendering, zoom, keyboard visibility and reopening, using + public assets without embedded firmware. +- The actual standalone executable opens a responsive window and closes cleanly. +- The built VST3 passes pluginval 1.0.4 at strictness level 5. + +After a successful job, download **wave-emulation-windows-x64** from the run's +Artifacts section. The ZIP contains `Standalone/Wave Emulation.exe`, the +`VST3/Wave Emulation.vst3` bundle, licenses, and the source revision in `BUILD.txt`. +**wave-emulation-windows-test-results** contains editor PNGs, CTest logs and +the pluginval log, including available diagnostics from failed jobs. + +For example, download a particular run's build from your Mac using GitHub CLI: + +```sh +gh run download RUN_ID --repo mo0kid/wave --name wave-emulation-windows-x64 +``` + +CI verifies Windows execution and plugin API behaviour without an audio device. +It does not establish audio-driver latency, MIDI hardware compatibility, DAW +compatibility or firmware-backed operation. Before calling the Windows build +a tested release, use a Windows VM or a Windows tester to check a VST3 DAW, +audio/MIDI devices, loading locally obtained firmware, and preset save/recall. +Review the uploaded editor PNGs for rendering problems as well. + +## MIDI and wavetable loading + +Instrument Page 2's **Alloc** setting controls audible allocation independently +for each Instrument. Dynamic mode reuses only that Instrument's sounding voices +when the shared pool is full. Poly 1–16 sets its allowance for reclaiming voices +from other Instruments; it does not cap normal polyphony. The six mono modes +provide last/lowest/highest-key priority with retrigger or single-trigger +envelopes, held-key return, sustain and fingered glide. The setting is retained +in the native Performance record and DAW state. + The Standalone automatically enables present and newly connected MIDI inputs. The on-screen keyboard plays MIDI notes 36–96, and the computer keyboard mapping `A W S E D F T G Y H U J K` plays C4 through C5. Host MIDI supports note velocity, sustain pedal, pitch bend, mod wheel, channel pressure, all-notes-off, and all-sound-off. -If a legal PPG EPROM or expanded wavetable image is placed beside the selected firmware files with a `.bin` or `.rom` extension, it is detected automatically. Names containing `ppg` or `wavetable` are tried first. The image path is retained in plug-in state without modifying the supplied SVG interface. +The lower-panel **Button 1** and **Button 2** feed their dedicated Sound modulation sources. Their touch/toggle modes and incoming MIDI controller assignments come from the current Performance's Controls page. Physical button presses remain independent when the two MIDI assignments coincide; received MIDI then addresses both assigned sources. Instruments follow their keyboard/MIDI source and MIDI channel settings. + +If the firmware does not supply the authenticated OS 1.700 factory bank, a legal PPG EPROM or expanded wavetable image placed beside the selected firmware files with a `.bin` or `.rom` extension is detected automatically. Names containing `ppg` or `wavetable` are tried first. The image path is retained in plug-in state without modifying the supplied SVG interface. For the original seven-file PPG Wave 2.3 V6 EPROM archive, run `scripts/import-ppg-wave-23-v6-rom.sh`. It combines the physical `w23_64`/`w23_66` wavetable pair and the adjacent V6 program-ROM bytes exposed by the original out-of-range wavetable-13 references, then places the resulting private image beside the Waldorf firmware for automatic loading. diff --git a/Source/Dsp/Cem3387.cpp b/Source/Dsp/Cem3387.cpp index 1cb7d41..2ceec32 100644 --- a/Source/Dsp/Cem3387.cpp +++ b/Source/Dsp/Cem3387.cpp @@ -1,6 +1,8 @@ #include "Cem3387.h" +#include "Cem3387Transfer.h" #include +#include #include #include @@ -26,17 +28,22 @@ Cem3387::coefficientTableForSampleRate(double targetSampleRate) const auto unit = static_cast(index) / static_cast(table->size() - 1); const auto cv = minimumCv + unit * (maximumCv - minimumCv); - // Measurements from a Wave voice card at full resonance place the - // oscillation at approximately 28 Hz, 957 Hz and 7.78 kHz for Sound - // cutoff values 0, 62 and 100. The nominal OS table alone produces - // 20 Hz, 710 Hz and 5.88 kHz in this four-pole topology. This stable - // 1.35 analogue scale factor belongs at the CEM control-law boundary, - // while the firmware-facing semitone table remains unchanged. - constexpr auto waveCemFrequencyScale = 1.35f; + // Wave voice-card oscillation measurements: 28 Hz, 957 Hz and + // 7779 Hz at Sound cutoff 0, 62 and 100. Interpolate in log frequency + // at the analogue control-law boundary. A constant scale previously + // concealed digital feedback delay at high cutoff. Above the last + // measured point, retain its scale; that range still needs captures. + const auto step = cv * 127.0f; + const auto scaleAt62 = 957.0f / (20.0f * std::exp2(62.0f / 12.0f)); + const auto scaleAt100 = 7779.0f / (20.0f * std::exp2(100.0f / 12.0f)); + const auto logScale = step <= 62.0f + ? std::log2(1.4f) + juce::jlimit(0.0f, 1.0f, step / 62.0f) + * (std::log2(scaleAt62) - std::log2(1.4f)) + : std::log2(scaleAt62) + juce::jlimit(0.0f, 1.0f, (step - 62.0f) / 38.0f) + * (std::log2(scaleAt100) - std::log2(scaleAt62)); const auto cutoff = juce::jlimit( 12.0f, static_cast(targetSampleRate * 0.225), - waveCemFrequencyScale * 20.0f - * std::exp2(cv * cutoffRangeOctaves)); + 20.0f * std::exp2(cv * cutoffRangeOctaves + logScale)); const auto g = std::tan(juce::MathConstants::pi * cutoff / static_cast(targetSampleRate)); (*table)[index] = g / (1.0f + g); @@ -83,6 +90,7 @@ void Cem3387::setControls(float cutoffHz, float resonance, float driveDb, float if (limitedAge != lastAgeInput) { age = lastAgeInput = limitedAge; + transconductorScale = cem3387::linearityScale / (1.0f + age * 0.08f); constexpr auto settlingTimeSeconds = 0.00028f; const auto hostSampleRate = static_cast(sampleRate * 0.5); const auto timeConstant = settlingTimeSeconds * (1.0f + age * 0.15f); @@ -191,8 +199,10 @@ Cem3387::StereoSample Cem3387::process(float input, float vcaLevel) noexcept const auto vcaCurvature = vcaCv * vcaCv * (3.0f - 2.0f * vcaCv); const auto componentNoise = noise * (0.0000025f + age * 0.000008f); const auto vcaBleed = 0.000018f * (1.0f + age * 2.0f); - const auto rawOutput = std::tanh(filtered * (1.0f + age * 0.08f)) - * (vcaCurvature + vcaBleed) + componentNoise; + // Headroom is already limited at the VCF output, inside its feedback loop. + // A second unity-drive tanh here previously added substantial distortion + // even with the filter fully open and the VCA below its current limit. + const auto rawOutput = filtered * (vcaCurvature + vcaBleed) + componentNoise; const auto output = rawOutput - couplingInput + couplingCoefficient * couplingOutput; couplingInput = rawOutput; @@ -203,14 +213,10 @@ Cem3387::StereoSample Cem3387::process(float input, float vcaLevel) noexcept float Cem3387::saturateVcfInput(float input) noexcept { - // Waldorf specifies the original input circuit as beginning to saturate - // at about 70% of maximum oscillator mixer output (a level setting near - // 75). A normalised tanh with modest drive is essentially unity for small - // signals, is about 8% compressed at that boundary, and remains smooth - // beyond it. Do not normalise its full-scale result back to one: that - // would add makeup gain which is absent from the passive input network. - constexpr auto inputDriveAtKnee = 0.75f; - return std::tanh(input * inputDriveAtKnee) / inputDriveAtKnee; + // Interpret the datasheet's ~6.5 V signal-handling figure as Vpp and + // assume a nominal full-scale input of 5 Vpp. This voltage mapping and + // shoulder shape remain estimates; digital signed wrap stays separate. + return cem3387::limitHeadroom(input, cem3387::inputHeadroom).value; } void Cem3387::updateControlVoltages(float vcaLevel) noexcept @@ -273,13 +279,9 @@ void Cem3387::updateControlVoltages(float vcaLevel) noexcept / (1.0f - std::exp(-lossCurve)); const auto measuredPassbandGain = std::pow( 10.0f, -maximumPassbandLossDb * lossPosition / 20.0f); - const auto selfOscillationPosition = juce::jmax( - 0.0f, (resonanceCv - 0.5f) * 2.0f); - const auto drivenLoopMakeup - = 1.0f + 0.64f * std::pow(selfOscillationPosition, 0.6f); resonanceInputGain = (1.0f + feedbackGain * resonanceAmount) - * measuredPassbandGain * drivenLoopMakeup; + * measuredPassbandGain; } if (panCv != coefficientPanCv) { @@ -294,20 +296,81 @@ void Cem3387::updateControlVoltages(float vcaLevel) noexcept float Cem3387::runFilter(float input) noexcept { - const auto saturatedInput = saturateVcfInput(input); - auto stageInput = std::tanh((saturatedInput * resonanceInputGain - - integrators[3] * resonanceAmount * 4.15f) - * inputDrive); + // Datasheet pp. 5-6: with Ca = 4 Cb the two second-order + // sections have H(s) = 1 / (1 + s/wc)^4. Four trapezoidal + // one-poles give that equivalent small-signal response. Close the + // resonance loop around their *current outputs*, not their stored + // integrator states: the latter adds artificial feedback phase delay. + const auto drivenInput = saturateVcfInput(input * inputDrive) * resonanceInputGain; + const auto feedback = resonanceAmount * 4.15f; + std::array outputs{}; + auto vcfOutput = 0.0f; + const auto evaluate = [&](float stageInput) { + auto derivative = 1.0f; + for (size_t stage = 0; stage < outputs.size(); ++stage) + { + outputs[stage] = integrators[stage] + + coefficient * (stageInput - integrators[stage]); + derivative *= coefficient; + if (stage + 1 < outputs.size()) + { + const auto transfer = cem3387::linearisedTransconductor( + outputs[stage], transconductorScale); + stageInput = transfer.value; + derivative *= transfer.derivative; + } + } + const auto transfer = cem3387::limitHeadroom( + outputs[3], cem3387::outputHeadroom); + vcfOutput = transfer.value; + return derivative * transfer.derivative; + }; - for (auto& state : integrators) + // The scalar feedback equation is monotone, with derivative >= 1. + // A safeguarded Newton solve handles saturation without updating any + // state until the whole loop has been evaluated. Drive acts on the + // incoming signal only; multiplying feedback by it changes the chip's Q. + auto stageInput = cem3387::linearisedTransconductor( + drivenInput - feedback * cem3387::limitHeadroom( + integrators[3], cem3387::outputHeadroom).value, + transconductorScale).value; + if (feedback == 0.0f) { - const auto delta = (stageInput - state) * coefficient; - const auto output = state + delta; - state = output + delta; - stageInput = std::tanh(output); + // With no feedback the first evaluation is already the solution. + // Keep the same stage arithmetic and saturation as the general solver. + (void) evaluate(stageInput); + for (size_t stage = 0; stage < outputs.size(); ++stage) + integrators[stage] = 2.0f * outputs[stage] - integrators[stage]; + return vcfOutput; } - - return integrators[3]; + auto lower = -transconductorScale; + auto upper = transconductorScale; + for (int iteration = 0; iteration < 8; ++iteration) + { + const auto derivative = evaluate(stageInput); + const auto feedbackInput = cem3387::linearisedTransconductor( + drivenInput - feedback * vcfOutput, transconductorScale); + const auto residual = stageInput - feedbackInput.value; + // Four float stages and the feedback subtraction have several ULPs + // of rounding noise. Chasing it adds Newton iterations without + // improving the signal, especially in the nearly linear regime. + constexpr auto relativeTolerance = 4.0f * std::numeric_limits::epsilon(); + if (std::abs(residual) < relativeTolerance * std::abs(stageInput) + 1.0e-12f + || iteration == 7) + break; + if (residual < 0.0f) + lower = stageInput; + else + upper = stageInput; + const auto next = stageInput - residual + / (1.0f + feedback * feedbackInput.derivative * derivative); + if (next == stageInput) + break; + stageInput = next > lower && next < upper ? next : 0.5f * (lower + upper); + } + for (size_t stage = 0; stage < outputs.size(); ++stage) + integrators[stage] = 2.0f * outputs[stage] - integrators[stage]; + return vcfOutput; } float Cem3387::quantiseCv(float normalised) noexcept diff --git a/Source/Dsp/Cem3387.h b/Source/Dsp/Cem3387.h index dd12728..d25dd33 100644 --- a/Source/Dsp/Cem3387.h +++ b/Source/Dsp/Cem3387.h @@ -24,8 +24,8 @@ class Cem3387 void setCutoffCalibrationCode(uint16_t code) noexcept; [[nodiscard]] StereoSample process(float input, float vcaLevel) noexcept; - // The Wave/Microwave voice input begins compressing at roughly 70% of - // maximum mixer output. This is separate from the ES2 digital mix wrap. + // Estimated input headroom, assuming full scale = 5 Vpp at the chip. + // This behavioral voltage mapping is separate from ES2 digital mix wrap. [[nodiscard]] static float saturateVcfInput(float input) noexcept; // Exposed for mixed-signal regression tests. These are the voltages after @@ -62,6 +62,7 @@ class Cem3387 float resonanceAmount = 0.0f; float resonanceInputGain = 1.0f; float inputDrive = 1.0f; + float transconductorScale = 26.0f; float panPosition = 0.0f; float targetCutoffCv = 0.0f; float targetResonanceCv = 0.0f; diff --git a/Source/Dsp/Cem3387Transfer.h b/Source/Dsp/Cem3387Transfer.h new file mode 100644 index 0000000..f10cabd --- /dev/null +++ b/Source/Dsp/Cem3387Transfer.h @@ -0,0 +1,67 @@ +#pragma once + +#include + +namespace wave::dsp::cem3387 +{ +// Educated behavioral calibration, not measured Wave pin voltages. Full-scale +// peak 1 is assumed to be 2.5 V (5 Vpp, the datasheet's typical 0.1% THD point). +// The weak OTA curve approximates linearised transconductors; its scale is not +// an internal voltage rail. Only input/output headroom has a pin-voltage mapping. +inline constexpr auto nominalPeakVolts = 2.5f; +inline constexpr auto linearityScale = 26.0f; +inline constexpr auto inputHeadroom = 3.25f / nominalPeakVolts; +inline constexpr auto outputHeadroom = 3.5f / nominalPeakVolts; + +struct Transfer +{ + float value; + float derivative; +}; + +[[nodiscard]] inline Transfer linearisedTransconductor( + float input, float scale = linearityScale) noexcept +{ + const auto argument = input / scale; + // Linearised stages spend almost all their time in this small interval. + // Through x^9 the tanh series is accurate to float precision here; use + // the library curve for larger overloads rather than extending the series. + auto unit = 0.0f; + if (std::abs(argument) <= 0.25f) + { + const auto squared = argument * argument; + unit = argument * (1.0f + squared * (-1.0f / 3.0f + + squared * (2.0f / 15.0f + squared * (-17.0f / 315.0f + + squared * (62.0f / 2835.0f))))); + } + else + unit = std::tanh(argument); + return { scale * unit, 1.0f - unit * unit }; +} + +// Smooth, symmetric headroom shoulder. The 16th-power shape keeps the nominal +// signal nearly linear while approaching the rail without a hard clip. +[[nodiscard]] inline Transfer limitHeadroom(float input, float rail) noexcept +{ + const auto unit = input / rail; + if (std::abs(unit) >= 16.0f) + return { std::copysign(rail, input), 0.0f }; + const auto squared = unit * unit; + const auto fourth = squared * squared; + const auto eighth = fourth * fourth; + const auto shoulder = eighth * eighth; + if (shoulder <= 0.01f) + { + // Binomial series avoids four square roots below the rail shoulder. + // Value and slope agree with the full curve to float precision. + const auto gain = 1.0f + shoulder * (-1.0f / 16.0f + + shoulder * (17.0f / 512.0f - shoulder * (187.0f / 8192.0f))); + const auto slope = 1.0f + shoulder * (-17.0f / 16.0f + + shoulder * (561.0f / 512.0f - shoulder * (9163.0f / 8192.0f))); + return { input * gain, slope }; + } + const auto term = 1.0f + shoulder; + const auto divisor = std::sqrt(std::sqrt(std::sqrt(std::sqrt(term)))); + return { input / divisor, 1.0f / (term * divisor) }; +} +} // namespace wave::dsp::cem3387 diff --git a/Source/Dsp/WaldorfAsic.cpp b/Source/Dsp/WaldorfAsic.cpp index 4cc8d5c..00b4f26 100644 --- a/Source/Dsp/WaldorfAsic.cpp +++ b/Source/Dsp/WaldorfAsic.cpp @@ -1,15 +1,25 @@ #include "WaldorfAsic.h" +#include "Cem3387Transfer.h" #if WAVE_HAS_PRIVATE_UPPER_TABLES #include "FactoryUpperWavetables.h" #endif #include "PpgWaveRom.h" +#include "WaveFactoryRom.h" #include #include #include #include +#include +#include #include +#if defined(__ARM_NEON) +#include +#elif defined(__SSE2__) || defined(_M_X64) +#include +#endif + namespace wave::dsp { namespace @@ -190,25 +200,58 @@ WavetableBank::WavetableBank() return generated; }(); samples = sharedFallback; +#if WAVE_HAS_PRIVATE_UPPER_TABLES + source = "PPG V6 lower tables + legacy Wave upper fallback"; +#endif } -void WavetableBank::detachSamples() +WavetableBank::WavetableBank(std::shared_ptr snapshot) noexcept + : samples(std::move(snapshot)), source() { - if (samples.use_count() > 1) - samples = std::make_shared(*samples); +} + +WavetableBank WavetableBank::renderSnapshot() const noexcept +{ + return WavetableBank(std::atomic_load_explicit(&samples, std::memory_order_acquire)); +} + +std::shared_ptr WavetableBank::copySamples() const +{ + return std::make_shared( + *std::atomic_load_explicit(&samples, std::memory_order_acquire)); +} + +bool WavetableBank::loadWaveFactoryRom(const void* data, size_t size) +{ + std::vector decoded; + std::vector decodedRomWaves; + if (!WaveFactoryRom::decode(data, size, decoded) + || !WaveFactoryRom::decodeRomWaves(data, size, decodedRomWaves)) + return false; + romWaves = std::make_shared>(std::move(decodedRomWaves)); + auto imported = copySamples(); + std::copy(decoded.begin(), decoded.end(), imported->begin()); + std::atomic_store_explicit(&samples, std::move(imported), std::memory_order_release); + originalWaveFactoryTables = true; + externalRomLoaded = true; + importedTables = factoryTableCount; + source = "Original Waldorf Wave OS 1.700 factory tables 1–64"; + return true; } bool WavetableBank::loadSigned8BitRom(const void* data, size_t size) noexcept { constexpr auto factorySamples = static_cast(factoryTableCount) * wavesPerTable * samplesPerWave; - if (data == nullptr || (size != samples->size() && size != factorySamples)) + if (data == nullptr || (size != totalSamples && size != factorySamples)) return false; - detachSamples(); - std::memcpy(samples->data(), data, size); + auto imported = copySamples(); + std::memcpy(imported->data(), data, size); + std::atomic_store_explicit(&samples, std::move(imported), std::memory_order_release); + originalWaveFactoryTables = false; externalRomLoaded = true; - importedTables = size == samples->size() ? numTables : factoryTableCount; - source = size == samples->size() + importedTables = size == totalSamples ? numTables : factoryTableCount; + source = size == totalSamples ? "User-supplied 128-table signed 8-bit image" : "User-supplied 64-table signed 8-bit image"; return true; @@ -219,8 +262,10 @@ bool WavetableBank::loadFirst32Signed8BitRom(const void* data, size_t size) noex constexpr auto first32Samples = static_cast(32) * wavesPerTable * samplesPerWave; if (data == nullptr || size != first32Samples) return false; - detachSamples(); - std::memcpy(samples->data(), data, first32Samples); + auto imported = copySamples(); + std::memcpy(imported->data(), data, first32Samples); + std::atomic_store_explicit(&samples, std::move(imported), std::memory_order_release); + originalWaveFactoryTables = false; externalRomLoaded = true; importedTables = 32; source = "User-supplied first-32-table signed 8-bit image"; @@ -238,8 +283,10 @@ bool WavetableBank::loadPpgWaveRom(const void* data, size_t size) noexcept if (!result.success) return false; - detachSamples(); - std::copy(decoded.begin(), decoded.end(), samples->begin()); + auto imported = copySamples(); + std::copy(decoded.begin(), decoded.end(), imported->begin()); + std::atomic_store_explicit(&samples, std::move(imported), std::memory_order_release); + originalWaveFactoryTables = false; externalRomLoaded = true; importedTables = result.decodedTables; source = "User-supplied PPG Wave 2.3 V6 EPROM (30 lower tables reconstructed)"; @@ -256,7 +303,7 @@ bool WavetableBank::loadRomImage(const void* data, size_t size) noexcept constexpr auto factorySamples = static_cast(factoryTableCount) * wavesPerTable * samplesPerWave; constexpr auto first32Samples = static_cast(32) * wavesPerTable * samplesPerWave; - if (size == samples->size() || size == factorySamples) + if (size == totalSamples || size == factorySamples) return loadSigned8BitRom(data, size); if (size == first32Samples) return loadFirst32Signed8BitRom(data, size); @@ -269,80 +316,110 @@ bool WavetableBank::loadWaveSetUserTables(const void* data, size_t size) noexcep return false; const auto* bytes = static_cast(data); + std::array validTables{}; + auto damagedCount = 0; for (int table = 0; table < userTableCount; ++table) { const auto record = waveSetUserTableOffset + static_cast(table) * waveSetUserTableRecordBytes; - if (bytes[record + 9] != 0x55u) - return false; + auto valid = bytes[record + 9] == 0x55u; + for (int wave = 0; wave < wavesPerTable && valid; ++wave) + { + const auto offset = record + 10 + static_cast(wave) * 2; + const auto reference = static_cast( + (static_cast(bytes[offset]) << 8u) | bytes[offset + 1]); + valid = reference == 0xffffu || reference < 300u + waveSetUserWaveCount + || (reference >= 0x1000u + && reference < 0x1000u + waveSetUserWaveCount); + } + validTables[static_cast(table)] = valid; + if (!valid) + ++damagedCount; } - detachSamples(); + // Reject unrelated data without changing the bank. A damaged individual + // record is replaced by INIT, rather than abandoning a half-imported SET. + if (damagedCount == userTableCount) + return false; + auto imported = copySamples(); for (int userTable = 0; userTable < userTableCount; ++userTable) { const auto destinationTable = factoryTableCount + userTable; const auto record = waveSetUserTableOffset + static_cast(userTable) * waveSetUserTableRecordBytes; std::array populated{}; + const auto valid = validTables[static_cast(userTable)]; for (int wave = 0; wave < wavesPerTable; ++wave) { const auto referenceOffset = record + 10 + static_cast(wave) * 2; - const auto reference = static_cast( - (static_cast(bytes[referenceOffset]) << 8u) - | bytes[referenceOffset + 1]); + // Native INIT WTBL has ROM Wave 0 at position 0 and Wave 1 + // at position 60. All other positions are interpolated/defaults. + const auto reference = valid + ? static_cast((static_cast(bytes[referenceOffset]) << 8u) + | bytes[referenceOffset + 1]) + : static_cast(wave == 0 ? 0 : wave == 60 ? 1 : 0xffffu); if (reference == 0xffffu) continue; - if (reference < 0x1000u) + if (reference < 300u) { - // Factory Wave references are a flat 0..4095 Wave number, - // not an encoded table/position byte pair. + // R000..R299 index the original ROM's individual Wave pool, + // rather than interpolated positions in the factory tables. const auto sourceTable = static_cast(reference) / wavesPerTable; const auto sourceWave = static_cast(reference) % wavesPerTable; - if (sourceTable >= factoryTableCount) - return false; for (int sampleIndex = 0; sampleIndex < samplesPerWave; ++sampleIndex) - (*samples)[index(destinationTable, wave, sampleIndex)] - = (*samples)[index(sourceTable, sourceWave, sampleIndex)]; + (*imported)[index(destinationTable, wave, sampleIndex)] + = romWaves != nullptr + ? (*romWaves)[static_cast(reference) * samplesPerWave + + static_cast(sampleIndex)] + : (*imported)[index(sourceTable, sourceWave, sampleIndex)]; } - else if (reference < 0x2000u) + else { - const auto userWave = static_cast(reference & 0x0fffu); - if (userWave >= waveSetUserWaveCount) - return false; + // Native U000..U999 are numbered 300..1299. Retain support + // for 0x1000-based references in historical SET snapshots. + const auto userWave = reference >= 0x1000u + ? static_cast(reference & 0x0fffu) + : static_cast(reference - 300u); const auto* halfWave = bytes + waveSetUserWaveOffset + userWave * waveSetHalfWaveSamples; for (int sampleIndex = 0; sampleIndex < 64; ++sampleIndex) { const auto value = halfWave[static_cast(sampleIndex)]; - (*samples)[index(destinationTable, wave, sampleIndex)] + (*imported)[index(destinationTable, wave, sampleIndex)] = static_cast(static_cast(value) - 128); - (*samples)[index(destinationTable, wave, 127 - sampleIndex)] + (*imported)[index(destinationTable, wave, 127 - sampleIndex)] = static_cast(static_cast( static_cast(~value)) - 128); } } - else - { - return false; - } populated[static_cast(wave)] = true; } - // Empty tail positions have the Wave's standard pulse, square and + // Empty tail positions have the Wave's standard triangle, square and // saw waves. Explicit user choices still take precedence. for (int wave = 61; wave < wavesPerTable; ++wave) { if (populated[static_cast(wave)]) continue; for (int sampleIndex = 0; sampleIndex < samplesPerWave; ++sampleIndex) - (*samples)[index(destinationTable, wave, sampleIndex)] - = (*samples)[index(0, wave, sampleIndex)]; + (*imported)[index(destinationTable, wave, sampleIndex)] + = (*imported)[index(0, wave, sampleIndex)]; populated[static_cast(wave)] = true; } + // Sparse records must not inherit the previous disk's leading waves. + if (!populated[0]) + { + for (int sampleIndex = 0; sampleIndex < samplesPerWave; ++sampleIndex) + (*imported)[index(destinationTable, 0, sampleIndex)] + = romWaves != nullptr ? (*romWaves)[static_cast(sampleIndex)] + : (*imported)[index(0, 0, sampleIndex)]; + populated[0] = true; + } + // Wave OS repeatedly creates the midpoint of each remaining gap. // This retains its quantised averaging character instead of using a // floating-point crossfade across the complete gap. @@ -364,20 +441,23 @@ bool WavetableBank::loadWaveSetUserTables(const void* data, size_t size) noexcep if (right - left > 1) { const auto midpoint = left + (right - left) / 2; - for (int sampleIndex = 0; sampleIndex < samplesPerWave; ++sampleIndex) + for (int sampleIndex = 0; sampleIndex < 64; ++sampleIndex) { const auto leftUnsigned = static_cast( - static_cast((*samples)[index(destinationTable, left, + static_cast((*imported)[index(destinationTable, left, sampleIndex)]) + 128); const auto rightUnsigned = static_cast( - static_cast((*samples)[index(destinationTable, right, + static_cast((*imported)[index(destinationTable, right, sampleIndex)]) + 128); - (*samples)[index(destinationTable, midpoint, sampleIndex)] + const auto value = static_cast( + (leftUnsigned + rightUnsigned) >> 1u); + (*imported)[index(destinationTable, midpoint, sampleIndex)] + = static_cast(static_cast(value) - 128); + (*imported)[index(destinationTable, midpoint, 127 - sampleIndex)] = static_cast(static_cast( - (leftUnsigned + rightUnsigned) >> 1u) - - 128); + static_cast(~value)) - 128); } populated[static_cast(midpoint)] = true; complete = false; @@ -389,6 +469,8 @@ bool WavetableBank::loadWaveSetUserTables(const void* data, size_t size) noexcep } } + std::atomic_store_explicit(&samples, std::move(imported), std::memory_order_release); + damagedUserTables = damagedCount; waveSetUserTablesLoaded = true; if (!source.contains("Wave SET user tables")) source += " + Wave SET user tables"; @@ -432,15 +514,141 @@ int8_t WavetableBank::rawSample(int table, int position, int sampleIndex) const juce::jlimit(0, samplesPerWave - 1, sampleIndex))]; } +int8_t WavetableBank::rawRomWaveSample(int wave, int sampleIndex) const noexcept +{ + wave = juce::jlimit(0, 299, wave); + sampleIndex = juce::jlimit(0, samplesPerWave - 1, sampleIndex); + if (romWaves != nullptr) + return (*romWaves)[static_cast(wave) * samplesPerWave + + static_cast(sampleIndex)]; + return rawSample(wave / wavesPerTable, wave % wavesPerTable, sampleIndex); +} + size_t WavetableBank::index(int table, int position, int sampleIndex) noexcept { return (static_cast(table) * wavesPerTable + static_cast(position)) * samplesPerWave + static_cast(sampleIndex); } +void AsicResampler::prepare(double hostSampleRate, double internalSampleRate) +{ + // Coefficients are shared by all voices and only built during prepare. + static std::mutex cacheMutex; + static std::map, std::weak_ptr> cache; + const auto rate = juce::jmax(1.0, hostSampleRate); + const auto internalRate = juce::jmax(1.0, internalSampleRate); + const auto key = std::make_pair(rate, internalRate); + const std::lock_guard lock(cacheMutex); + kernel = cache[key].lock(); + if (kernel == nullptr) + { + auto next = std::make_shared(); + const auto bandwidth = juce::jmin(rate, internalRate); + const auto ratio = internalRate / bandwidth; + // Blackman-windowed sinc: flat through 0.40 * bandwidth, with a + // transition centred at 0.45 and rejection by host Nyquist. Bound + // storage for pathological non-audio rates; normal audio rates use + // the full 96-tap-per-output-period design. + next->taps = 4 * static_cast(std::ceil(juce::jmin(8192.0, 24.0 * ratio))); + next->coefficients.resize(static_cast((phaseCount + 1) * next->taps)); + const auto cutoff = 0.45 / ratio; + const auto radius = static_cast(next->taps) * 0.5; + for (int phaseIndex = 0; phaseIndex <= phaseCount; ++phaseIndex) + { + const auto fraction = static_cast(phaseIndex) / phaseCount; + auto sum = 0.0; + auto* coefficients = next->coefficients.data() + phaseIndex * next->taps; + for (int tap = 0; tap < next->taps; ++tap) + { + const auto distance = static_cast(tap) + fraction - radius; + const auto angle = twoPi * cutoff * distance; + const auto sinc = std::abs(angle) < 1.0e-12 ? 1.0 : std::sin(angle) / angle; + const auto window = 0.42 + 0.5 * std::cos(juce::MathConstants::pi + * distance / radius) + + 0.08 * std::cos(twoPi * distance / radius); + coefficients[tap] = static_cast(2.0 * cutoff * sinc * window); + sum += coefficients[tap]; + } + for (int tap = 0; tap < next->taps; ++tap) + coefficients[tap] = static_cast(coefficients[tap] / sum); + } + kernel = next; + cache[key] = kernel; + } + // Mirroring the ring keeps the dot products contiguous without per-tap + // modulus operations. No allocations or coefficient generation in render. + history.resize(static_cast(2 * kernel->taps)); + reset(); +} + +void AsicResampler::reset() noexcept +{ + std::fill(history.begin(), history.end(), 0.0f); + head = 0; +} + +void AsicResampler::push(float sample) noexcept +{ + if (--head < 0) + head = kernel->taps - 1; + history[static_cast(head)] = sample; + history[static_cast(head + kernel->taps)] = sample; +} + +float AsicResampler::read(double fractionalTick) const noexcept +{ + const auto phase = juce::jlimit(0.0, 1.0, fractionalTick) * phaseCount; + const auto index = juce::jmin(phaseCount - 1, static_cast(phase)); + const auto blend = static_cast(phase - index); + const auto* first = kernel->coefficients.data() + index * kernel->taps; + const auto* second = first + kernel->taps; + const auto* samples = history.data() + head; + // Explicit four-lane accumulation avoids compiler-generated lane extraction + // inside the tap loop. Unaligned loads are required by the rotating history. + // Preserve the four independent sums and their final reduction order. + std::array a {}; + std::array b {}; +#if defined(__ARM_NEON) + auto va = vdupq_n_f32(0.0f); + auto vb = vdupq_n_f32(0.0f); + for (int tap = 0; tap < kernel->taps; tap += 4) + { + const auto input = vld1q_f32(samples + tap); + va = vaddq_f32(va, vmulq_f32(input, vld1q_f32(first + tap))); + vb = vaddq_f32(vb, vmulq_f32(input, vld1q_f32(second + tap))); + } + vst1q_f32(a.data(), va); + vst1q_f32(b.data(), vb); +#elif defined(__SSE2__) || defined(_M_X64) + auto va = _mm_setzero_ps(); + auto vb = _mm_setzero_ps(); + for (int tap = 0; tap < kernel->taps; tap += 4) + { + const auto input = _mm_loadu_ps(samples + tap); + va = _mm_add_ps(va, _mm_mul_ps(input, _mm_loadu_ps(first + tap))); + vb = _mm_add_ps(vb, _mm_mul_ps(input, _mm_loadu_ps(second + tap))); + } + _mm_storeu_ps(a.data(), va); + _mm_storeu_ps(b.data(), vb); +#else + for (int tap = 0; tap < kernel->taps; tap += 4) + { + for (int lane = 0; lane < 4; ++lane) + { + a[static_cast(lane)] += samples[tap + lane] * first[tap + lane]; + b[static_cast(lane)] += samples[tap + lane] * second[tap + lane]; + } + } +#endif + const auto firstSum = (a[0] + a[1]) + (a[2] + a[3]); + const auto secondSum = (b[0] + b[1]) + (b[2] + b[3]); + return firstSum + blend * (secondSum - firstSum); +} + void OscillatorChipProxy::prepare(double hostSampleRate) { sampleRate = juce::jmax(1.0, hostSampleRate); + resampler.prepare(sampleRate); reset(); } @@ -449,6 +657,7 @@ void OscillatorChipProxy::reset(double startPhase) noexcept phase = startPhase - std::floor(startPhase); clockPhase = 1.0; heldSample = 0.0f; + resampler.reset(); } void OscillatorChipProxy::setFrequency(float frequencyHz) noexcept @@ -465,8 +674,9 @@ float OscillatorChipProxy::process(const WavetableBank& bank, int table, float p { clockPhase -= 1.0; heldSample = tick(bank, table, position, smoothPosition); + resampler.push(heldSample); } - return heldSample; + return resampler.read(clockPhase); } float OscillatorChipProxy::tick(const WavetableBank& bank, int table, float position, @@ -592,6 +802,15 @@ void ReconstructionStage::setAge(float amount) noexcept void ReconstructionStage::updateCoefficients() noexcept { coefficientAge = age; + // The DAC input is rounded to one of 255 signed levels. Cache the exact + // weak transconductor transfer at those levels instead of calling tanh + // at 250 kHz. The chip's reconstruction filter is a low-distortion stage, + // so a unity-drive waveshaper is inappropriate at normal DAC levels. + for (int code = -127; code <= 127; ++code) + saturatedLevels[static_cast(code + 127)] + = cem3387::linearisedTransconductor( + static_cast(code) / 127.0f, + cem3387::linearityScale / (1.0f + age * 0.08f)).value; const auto cutoff = 15400.0f; firstPoleCoefficient = 1.0f - std::exp(-juce::MathConstants::twoPi * cutoff * 0.5f @@ -611,15 +830,16 @@ float ReconstructionStage::process(float input) noexcept // The PD508 output is an eight-bit multiplexed level feeding a held and // reconstructed analogue path. These are observable boundary behaviours; // no undocumented oscillator-chip internals are assumed here. - const auto quantised = std::round(juce::jlimit(-1.0f, 1.0f, input) * 127.0f) / 127.0f; + const auto code = static_cast(std::round( + juce::jlimit(-1.0f, 1.0f, input) * 127.0f)); // OscillatorChipProxy has already performed the digital sample-and-hold: // its output only changes when the emulated oscillator clock advances. // Following that held value with an 18 ms one-pole here would model a // second, non-existent hold as an audio low-pass at about 9 Hz, removing // virtually the entire wavetable signal. The PD508 level therefore // drives the analogue reconstruction filter directly. - heldLevel = quantised; - const auto slewInput = std::tanh(heldLevel * (1.0f + age * 0.16f)); + heldLevel = static_cast(code) / 127.0f; + const auto slewInput = saturatedLevels[static_cast(code + 127)]; // CEM3387 datasheet application: the fixed three-pole reconstruction // section is a one-pole followed by a second-order 1 dB Chebyshev stage. // Its first pole is half the final pole frequency and the second-order diff --git a/Source/Dsp/WaldorfAsic.h b/Source/Dsp/WaldorfAsic.h index e5296c1..91250af 100644 --- a/Source/Dsp/WaldorfAsic.h +++ b/Source/Dsp/WaldorfAsic.h @@ -5,6 +5,7 @@ #include #include #include +#include namespace wave::dsp { @@ -18,15 +19,21 @@ class WavetableBank static constexpr int samplesPerWave = 128; WavetableBank(); + // Capture samples once per render block; oscillator sampling needs no locks. + // Import metadata belongs to the source bank, not this sample-only view. + [[nodiscard]] WavetableBank renderSnapshot() const noexcept; bool loadSigned8BitRom(const void* data, size_t size) noexcept; bool loadFirst32Signed8BitRom(const void* data, size_t size) noexcept; bool loadPpgWaveRom(const void* data, size_t size) noexcept; bool loadRomImage(const void* data, size_t size) noexcept; + bool loadWaveFactoryRom(const void* data, size_t size); + [[nodiscard]] bool hasOriginalWaveFactoryTables() const noexcept { return originalWaveFactoryTables; } bool loadWaveSetUserTables(const void* data, size_t size) noexcept; [[nodiscard]] bool isExternalRomLoaded() const noexcept { return externalRomLoaded; } [[nodiscard]] int importedTableCount() const noexcept { return importedTables; } [[nodiscard]] bool hasWaveSetUserTables() const noexcept { return waveSetUserTablesLoaded; } + [[nodiscard]] int damagedUserTableCount() const noexcept { return damagedUserTables; } [[nodiscard]] const juce::String& sourceDescription() const noexcept { return source; } [[nodiscard]] float sample(int table, float position, double phase, @@ -34,19 +41,47 @@ class WavetableBank [[nodiscard]] int8_t sampleCode(int table, float position, double phase, bool smoothPosition = true) const noexcept; [[nodiscard]] int8_t rawSample(int table, int position, int sampleIndex) const noexcept; + [[nodiscard]] int8_t rawRomWaveSample(int wave, int sampleIndex) const noexcept; private: static constexpr size_t totalSamples = static_cast(numTables) * wavesPerTable * samplesPerWave; using SampleStorage = std::array; std::shared_ptr samples; + std::shared_ptr> romWaves; bool externalRomLoaded = false; + bool originalWaveFactoryTables = false; bool waveSetUserTablesLoaded = false; + int damagedUserTables = 0; int importedTables = 0; juce::String source { "PPG V6 lower tables + procedural upper tables" }; [[nodiscard]] static size_t index(int table, int position, int sampleIndex) noexcept; - void detachSamples(); + explicit WavetableBank(std::shared_ptr snapshot) noexcept; + [[nodiscard]] std::shared_ptr copySamples() const; +}; + +// Bandlimited conversion from the fixed ASIC clock to the host clock. Feed +// every internal tick, then read at the fractional host sampling instant. +// The causal FIR adds about 1.1 ms at 44.1 kHz; it is not an analogue model. +class AsicResampler +{ +public: + void prepare(double hostSampleRate, double internalSampleRate = 250000.0); + void reset() noexcept; + void push(float sample) noexcept; + [[nodiscard]] float read(double fractionalTick) const noexcept; + +private: + static constexpr int phaseCount = 64; + struct Kernel + { + int taps = 0; + std::vector coefficients; + }; + std::shared_ptr kernel; + std::vector history; + int head = 0; }; // External behavioural proxy for the undocumented oscillator chip. This does @@ -57,6 +92,10 @@ class OscillatorChipProxy void prepare(double hostSampleRate); void reset(double startPhase = 0.0) noexcept; void setFrequency(float frequencyHz) noexcept; + [[nodiscard]] float frequencyHz() const noexcept + { + return static_cast(phaseIncrementPerTick * modelClockRate()); + } [[nodiscard]] float process(const WavetableBank& bank, int table, float position, bool smoothPosition = true) noexcept; @@ -76,6 +115,7 @@ class OscillatorChipProxy double clockPhase = 1.0; double phaseIncrementPerTick = 440.0 / modelClockRate(); float heldSample = 0.0f; + AsicResampler resampler; }; // The ES2 ASIC combines its two signed eight-bit oscillator values after @@ -133,6 +173,7 @@ class ReconstructionStage float tolerance = 0.0f; float age = 0.0f; float coefficientAge = -1.0f; + std::array saturatedLevels{}; float firstPoleCoefficient = 0.0f; float secondOrderA1 = 1.0f; float secondOrderA2 = 0.0f; diff --git a/Source/Dsp/WaldorfEngine.cpp b/Source/Dsp/WaldorfEngine.cpp index 45df3fa..50fffdf 100644 --- a/Source/Dsp/WaldorfEngine.cpp +++ b/Source/Dsp/WaldorfEngine.cpp @@ -1,25 +1,35 @@ #include "WaldorfEngine.h" -#include "DspMath.h" #include #include +#include #include #include +#include namespace wave::dsp { namespace { // WDV OS 1.700 stores modulation amounts in a 128-word table at 0x25e8. -// Apart from the saturated -64 endpoint, its exact relationship is -// sign(amount) * amount^2 / 4096. The pitch routine applies that curve twice, -// then both oscillator callers at $0e34/$0eea arithmetic-shift its result -// right by three before adding it to the pitch accumulator. +// Apart from the saturated -64 endpoint and three typos, its relationship is +// sign(amount) * amount^2 / 4096 (8 * n^2 of 32768). The typos are index 6 +// (amount -58: -29912 instead of -26912), index 126 (+62: 31000 instead of +// 30752) and index 127 (+63: 32767 instead of 31752). The pitch routine +// applies the result squared, then both oscillator callers at $0e14/$0eca +// arithmetic-shift it right by three before adding it to the pitch +// accumulator. float wdvAmountDepth(float amount) noexcept { const auto limited = juce::jlimit(-64.0f, 63.0f, amount); - return std::copysign(limited * limited / 4096.0f, limited); + static constexpr std::array, 3> tableTypos {{ + { -58.0f, -3000.0f }, { 62.0f, 248.0f }, { 63.0f, 1015.0f } + }}; + auto depth = std::copysign(limited * limited / 4096.0f, limited); + for (const auto& [index, error] : tableTypos) + depth += error / 32768.0f * juce::jmax(0.0f, 1.0f - std::abs(limited - index)); + return depth; } float wdvPitchDepthSemitones(float amount) noexcept @@ -208,6 +218,8 @@ void WaldorfEngine::prepare(double sampleRate, int maximumBlockSize) parallelCardRenders = 0; lastPlayedNotesByLayer.fill(-1); layerGlideTrajectories.fill({}); + heldNotesByLayer.fill({}); + allocationModesByLayer.fill(0); startVoiceCardWorkers(sampleRate, maximumRenderBlockSize); } @@ -228,12 +240,28 @@ void WaldorfEngine::reset() modWheelAmount = 0.0f; channelPressureAmount = 0.0f; midiControllerAmounts.fill(0.0f); + buttonAmountsByLayer.fill({}); + buttonSourcesByLayer.fill(0); + appliedKeyboardButtonStates.fill(-1); midiControllerAmounts[16] = 64.0f / 127.0f; lastPlayedNotesByLayer.fill(-1); layerGlideTrajectories.fill({}); + heldNotesByLayer.fill({}); + allocationModesByLayer.fill(0); sustainPedal = false; } +void WaldorfEngine::setKeyboardButtons(bool button1, bool button2) noexcept +{ + keyboardButtonStates = { button1 ? 1 : 0, button2 ? 1 : 0 }; +} + +void WaldorfEngine::setKeyboardButtonControllers(int button1, int button2) noexcept +{ + keyboardButtonControllers = { juce::jlimit(1, 120, button1), + juce::jlimit(1, 120, button2) }; +} + float WaldorfEngine::tunedNoteForLayer(const PerformanceLayer& layer, int translatedNote, uint64_t seed, int layerIndex) const noexcept @@ -309,6 +337,24 @@ float WaldorfEngine::tunedNoteForLayer(const PerformanceLayer& layer, void WaldorfEngine::synchroniseActiveVoiceTuning( const PerformanceSnapshot& performance) noexcept { + for (size_t layerIndex = 0; layerIndex < layerGlideTrajectories.size(); ++layerIndex) + { + auto& trajectory = layerGlideTrajectories[layerIndex]; + if (!trajectory.initialised || lastPlayedNotesByLayer[layerIndex] < 0) + continue; + const auto desiredTarget = tunedNoteForLayer( + performance.layers[layerIndex], lastPlayedNotesByLayer[layerIndex], + trajectory.triggerId, static_cast(layerIndex)); + const auto tuningDelta = desiredTarget - trajectory.targetNote; + if (std::abs(tuningDelta) > 1.0e-6f) + { + // Portamento is owned by the layer. Retuning only its active + // voices leaves the next note gliding from the old temperament. + trajectory.currentNote += tuningDelta; + trajectory.targetNote = desiredTarget; + } + } + for (auto& voice : voices) { if (!voice.active || voice.layerIndex < 0 || voice.layerIndex >= 8) @@ -369,6 +415,27 @@ void WaldorfEngine::render(juce::AudioBuffer& output, const juce::MidiBuf { output.clear(); synchroniseActiveVoiceTuning(performance); + for (size_t layer = 0; layer < performance.layers.size(); ++layer) + { + const auto source = performance.layers[layer].source; + if (source == 1 || source == 3) + for (size_t button = 0; button < keyboardButtonStates.size(); ++button) + if (appliedKeyboardButtonStates[button] != keyboardButtonStates[button] + || buttonSourcesByLayer[layer] != source) + buttonAmountsByLayer[layer][button] = static_cast(keyboardButtonStates[button]); + buttonSourcesByLayer[layer] = source; + } + appliedKeyboardButtonStates = keyboardButtonStates; + for (size_t layer = 0; layer < performance.layers.size(); ++layer) + { + const auto mode = performance.layers[layer].allocationMode; + if (mode == allocationModesByLayer[layer]) + continue; + allocationModesByLayer[layer] = mode; + if (mode >= 17 && performance.layers[layer].enabled) + if (const auto* selected = heldNotesByLayer[layer].selected(mode)) + startLayerNote(*selected, layer, performance, false); + } auto cursor = 0; const auto sampleCount = output.getNumSamples(); @@ -407,11 +474,11 @@ void WaldorfEngine::Voice::prepare(double newSampleRate, int index) noiseState = 0x9e3779b9u ^ (static_cast(index) * 0x45d9f3bu); oscillator1.prepare(sampleRate); oscillator2.prepare(sampleRate); - // Only the digital ASIC/DAC/reconstruction boundary runs at the original - // 250 kHz domain. The substantially more expensive CEM voice circuit - // remains at its own existing 2x-host integration rate. + // Keep the oscillator and reconstruction path at the original 250 kHz. + // Lowering this rate aliases wavetable harmonics before resampling. highpassFilter.prepare(OscillatorChipProxy::modelClockRate()); reconstruction.prepare(OscillatorChipProxy::modelClockRate(), tolerance); + asicResampler.prepare(sampleRate); circuit.prepare(sampleRate, tolerance); // Reinstate the installed card trim before the first note. The firmware's // $15A680 service table remains authoritative once the CPU is running. @@ -427,12 +494,39 @@ void WaldorfEngine::Voice::prepare(double newSampleRate, int index) reset(); } +int WaldorfEngine::startPhaseCode(int programmed, int storedAmount, int source, + bool secondOscillator) noexcept +{ + if (programmed <= 0) + return 0; + + const auto word = [](int value) { return static_cast(static_cast(value)); }; + // WDV 0x246C: source word times the amount table at 0x25E8 (saturated at + // -32767), keeping the high word and doubling it in a 16-bit add. + auto modulation = 0; + if (storedAmount != 64 && source != 0) + { + const auto table = juce::jlimit( + -32767, 32767, + juce::roundToInt(wdvAmountDepth(static_cast(storedAmount - 64)) * 32768.0f)); + modulation = word(((source * table) >> 16) * 2); + } + const auto code = word(word(programmed << 8) + modulation) >> 8; + if (code == 0) + return 1; + // 0xFB8 compares signed (ble) in Wave 1, 0x109C unsigned (bcs) in Wave 2. + if (!secondOscillator) + return std::min(code, 127) & 0xff; + return code > 0 && code < 127 ? code : 127; +} + void WaldorfEngine::Voice::reset() { oscillator1.reset(); oscillator2.reset(); highpassFilter.reset(); reconstruction.reset(); + asicResampler.reset(); circuit.reset(); envelope.reset(); filterEnvelope.reset(); @@ -453,7 +547,6 @@ void WaldorfEngine::Voice::reset() active = false; currentWavePosition = 0.0f; currentLfoValues.fill(0.0f); - waveStartOffsets.fill(0.0f); currentPitchModulations.fill(0.0f); currentGlideNote = 0.0f; targetGlideNote = 0.0f; @@ -487,7 +580,7 @@ void WaldorfEngine::Voice::reset() vcaDrainSamplesRemaining = 0; controlFilterMode = 0; asicClockPhase = 1.0; - waveStartOffsetsPending = false; + startPhaseModPending = false; filterEnvelopePending = false; filterEnvelopeTriggered = false; } @@ -500,7 +593,8 @@ void WaldorfEngine::Voice::start(int midiNote, int midiChannel, float noteVeloci bool shouldQuantiseGlide, float inheritedGlideStepPerSample, int inheritedGlideSamplesRemaining, float modWheel, - float channelPressure, float pitchBend) + float channelPressure, float pitchBend, + bool retriggerEnvelopes) { const auto isStealingActiveVoice = active; const auto& parameters = layer.sound; @@ -573,8 +667,11 @@ void WaldorfEngine::Voice::start(int midiNote, int midiChannel, float noteVeloci + oscillator * 0x632be59bd9b4e019ull; return static_cast(hash & 0xffffu) / 65536.0; }; - oscillator1.reset(startPhase(0)); - oscillator2.reset(startPhase(1)); + if (!isStealingActiveVoice || retriggerEnvelopes) + { + oscillator1.reset(startPhase(0)); + oscillator2.reset(startPhase(1)); + } // A reassigned hardware voice does not discharge its analogue filter, // reconstruction network, sample-and-hold capacitors or VCA in one CPU @@ -584,10 +681,16 @@ void WaldorfEngine::Voice::start(int midiNote, int midiChannel, float noteVeloci { highpassFilter.reset(); reconstruction.reset(); + asicResampler.reset(); circuit.reset(); baseCutoffInitialised = false; } + // Single-trigger legato and returning to a held key preserve the digital + // envelopes, LFOs, oscillator phase and pending filter-envelope delay. + if (isStealingActiveVoice && !retriggerEnvelopes) + return; + envelopeParameters.attack = parameters.attackSeconds; envelopeParameters.decay = parameters.decaySeconds; envelopeParameters.sustain = parameters.sustainLevel; @@ -617,8 +720,7 @@ void WaldorfEngine::Voice::start(int midiNote, int midiChannel, float noteVeloci for (size_t lfo = 0; lfo < lfos.size(); ++lfo) lfos[lfo].noteOn(parameters.lfos[lfo].sync, parameters.lfos[lfo].phaseDegrees); - waveStartOffsets.fill(0.0f); - waveStartOffsetsPending = true; + startPhaseModPending = true; } void WaldorfEngine::Voice::release(bool allowSustain) @@ -635,15 +737,19 @@ void WaldorfEngine::Voice::release(bool allowSustain) } } -void WaldorfEngine::Voice::updatePitch(const parameters::Snapshot& parameters, float pitchBend) +float WaldorfEngine::Voice::baseFrequencyHz() const noexcept { - if (note < 0) - return; const auto pitchNote = glideQuantised ? std::round(currentGlideNote) : currentGlideNote; - const auto baseFrequency - = 440.0f * std::exp2((pitchNote - 69.0f) / 12.0f); + return 440.0f * std::exp2((pitchNote - 69.0f) / 12.0f); +} + +void WaldorfEngine::Voice::updatePitch(const parameters::Snapshot& parameters, float pitchBend) +{ + if (note < 0) + return; + const auto baseFrequency = baseFrequencyHz(); const auto bend1 = pitchBend * parameters.oscillatorBendRanges[0] / 2.0f; const auto bend2Range = parameters.oscillatorLinkEnabled ? parameters.oscillatorBendRanges[0] @@ -818,24 +924,37 @@ Cem3387::StereoSample WaldorfEngine::Voice::process( { // Start modifiers are sampled at note-on; all other WDV targets are // refreshed by the voice-board control interrupt rather than by the - // host audio clock. - if (waveStartOffsetsPending) + // host audio clock. WDV 0xF92/0x1074 add the route to Startphase (sound + // byte 27/43, one full cycle at full scale) in 16-bit arithmetic, see + // startPhaseCode; a Startphase of 0 is a free start and ignores it. + if (startPhaseModPending) { - waveStartOffsets[0] - = 64.0f - * wdvAmountDepth( - parameters.modulationRoutes[parameters::wave1StartMod].amount) - * routeValue(parameters::wave1StartMod, parameters, env, - waveEnvelopeValue, currentLfoValues, modWheel, - channelPressure, pitchBend); - waveStartOffsets[1] - = 64.0f - * wdvAmountDepth( - parameters.modulationRoutes[parameters::wave2StartMod].amount) - * routeValue(parameters::wave2StartMod, parameters, env, - waveEnvelopeValue, currentLfoValues, modWheel, - channelPressure, pitchBend); - waveStartOffsetsPending = false; + constexpr std::array startRoutes { + parameters::wave1StartMod, parameters::wave2StartMod + }; + std::array oscillators { &oscillator1, &oscillator2 }; + for (size_t i = 0; i < startRoutes.size(); ++i) + { + const auto& route = parameters.modulationRoutes[startRoutes[i]]; + // ponytail: float sources map to words at 32768 full scale; the + // master's MIDI controller words are CC << 8 (max 0x7F00), so a + // controller-driven start can land one step off. Per-source word + // scales would fix every route, not just this one. + const auto source = juce::jlimit( + -32768, 32767, + juce::roundToInt(32768.0f + * routeValue(startRoutes[i], parameters, env, + waveEnvelopeValue, currentLfoValues, + modWheel, channelPressure, pitchBend))); + const auto code = startPhaseCode(juce::roundToInt(parameters.wavePhases[i]), + juce::roundToInt(route.amount) + 64, + source, i == 1); + // ponytail: the ASIC takes the code as 8 bits, but Startphase + // is documented 0..127 = one cycle; bit 7 is assumed ignored. + if (code != 0) + oscillators[i]->reset(static_cast(code & 127) / 128.0); + } + startPhaseModPending = false; } const auto bend1 = pitchBend * parameters.oscillatorBendRanges[0] / 2.0f; @@ -876,7 +995,10 @@ Cem3387::StereoSample WaldorfEngine::Voice::process( waveEnvelopeValue, currentLfoValues, modWheel, channelPressure, pitchBend); currentPitchModulations = { pitch1 - bend1, pitch2 - bend2 }; - const auto baseFrequency = math::midiFrequency(note); + // The control interrupt must use the same live tuned/gliding pitch as + // Voice::updatePitch. Using the original MIDI key here alternated HMT + // (or a User tuning) with equal temperament about once per millisecond. + const auto baseFrequency = baseFrequencyHz(); const auto performanceRatio = std::exp2(performanceDetuneCents / 1200.0f); auto detune = parameters.oscillatorDetuneCents; if (detune[0] == 0.0f && detune[1] == 0.0f && parameters.detuneCents != 0.0f) @@ -888,8 +1010,8 @@ Cem3387::StereoSample WaldorfEngine::Voice::process( baseFrequency * performanceRatio * std::exp2((pitch2 + detune[1] / 100.0f) / 12.0f)); - const auto wave1Mod = waveStartOffsets[0] - + 64.0f * wdvAmountDepth( + const auto wave1Mod + = 64.0f * wdvAmountDepth( parameters.modulationRoutes[parameters::wave1Mod1].amount) * routeValue(parameters::wave1Mod1, parameters, env, waveEnvelopeValue, currentLfoValues, modWheel, @@ -909,8 +1031,8 @@ Cem3387::StereoSample WaldorfEngine::Voice::process( + 64.0f * wdvAmountDepth(parameters.waveKeytrackAmounts[0]) * keyPosition + wave1Mod); currentWavePosition = controlWavePositions[0]; - const auto wave2Mod = waveStartOffsets[1] - + 64.0f * wdvAmountDepth( + const auto wave2Mod + = 64.0f * wdvAmountDepth( parameters.modulationRoutes[parameters::wave2Mod1].amount) * routeValue(parameters::wave2Mod1, parameters, env, waveEnvelopeValue, currentLfoValues, modWheel, @@ -1051,7 +1173,6 @@ Cem3387::StereoSample WaldorfEngine::Voice::process( } reconstruction.setAge(parameters.circuitAgeAmount); - auto reconstructed = 0.0f; const auto levelCode1 = static_cast(juce::jlimit( 0, 127, juce::roundToInt(controlWaveLevels[0] * 112.0f))); const auto levelCode2 = static_cast(juce::jlimit( @@ -1076,8 +1197,9 @@ Cem3387::StereoSample WaldorfEngine::Voice::process( = controlFilterMode == 0 ? dacInput : highpassFilter.process(dacInput, controlHighpassCutoff); - reconstructed = reconstruction.process(digitalInput); + asicResampler.push(reconstruction.process(digitalInput)); } + const auto reconstructed = asicResampler.read(asicClockPhase); circuit.setControls(controlAnalogueCutoff, controlResonance, parameters.driveDb, controlPan, parameters.circuitAgeAmount); @@ -1225,6 +1347,169 @@ float WaldorfEngine::Voice::noise() noexcept / static_cast(std::numeric_limits::max()); } +void WaldorfEngine::HeldNotes::add(HeldNote note) noexcept +{ + if (count == notes.size()) + { + std::move(notes.begin() + 1, notes.end(), notes.begin()); + --count; + } + notes[count++] = note; +} + +void WaldorfEngine::HeldNotes::remove(uint64_t trigger) noexcept +{ + size_t destination = 0; + for (size_t source = 0; source < count; ++source) + if (notes[source].trigger != trigger) + notes[destination++] = notes[source]; + count = destination; +} + +const WaldorfEngine::HeldNote* WaldorfEngine::HeldNotes::selected(int mode) const noexcept +{ + if (count == 0) + return nullptr; + const auto priority = (mode - 17) % 3; + const auto* result = ¬es[count - 1]; + if (priority == 0) + return result; + for (size_t index = 0; index < count; ++index) + if ((priority == 1 && notes[index].note < result->note) + || (priority == 2 && notes[index].note > result->note)) + result = ¬es[index]; + return result; +} + +void WaldorfEngine::startLayerNote(const HeldNote& held, size_t layerIndex, + const PerformanceSnapshot& performance, + bool noteOnEvent) +{ + const auto& layer = performance.layers[layerIndex]; + const auto midiNote = held.note; + const auto triggerId = held.trigger; + auto* allocated = chooseVoice(static_cast(layerIndex), performance); + if (allocated == nullptr) + return; + const auto monophonic = layer.allocationMode >= 17; + const auto hadHeldVoice = allocated->active && allocated->keyDown; + if (monophonic) + { + // Reuse one physical voice, including its release tail. Mode changes + // must also retire any previous polyphonic voices of this Instrument. + for (auto& candidate : voices) + if (&candidate != allocated && candidate.active + && candidate.layerIndex == static_cast(layerIndex)) + candidate.reset(); + if (hadHeldVoice && allocated->triggerId == triggerId) + return; // A non-priority key must not retrigger low/high modes. + } + const auto retrigger = !monophonic || !hadHeldVoice + || (noteOnEvent && layer.allocationMode < 20); + const auto translatedNote = juce::jlimit( + 0, 127, midiNote + layer.transposeSemitones); + const auto tunedTargetNote = tunedNoteForLayer( + layer, translatedNote, triggerId, static_cast(layerIndex)); + const auto previousNote + = lastPlayedNotesByLayer[layerIndex]; + const auto hasHeldLayerVoice = std::any_of( + voices.begin(), voices.end(), [layerIndex](const auto& candidate) { + return candidate.active && candidate.keyDown + && candidate.layerIndex == static_cast(layerIndex); + }); + const auto glideMode = juce::jlimit(1, 6, layer.sound.glideTypeMode); + const auto midiControlled = glideMode == 3 || glideMode == 4; + const auto fingered = glideMode == 5 || glideMode == 6; + const auto midiPortamentoEnabled + = midiControllerAmounts[65] >= 0.5f; + const auto shouldGlide + = layer.sound.glideEnabled && previousNote >= 0 + && (!fingered || hasHeldLayerVoice) + && (!midiControlled || midiPortamentoEnabled); + const auto rate = midiControlled + ? midiControllerAmounts[5] * 127.0f + : layer.sound.glideRateValue; + + auto glideFromNote = tunedTargetNote; + if (shouldGlide) + { + glideFromNote = layerGlideTrajectories[layerIndex].initialised + ? layerGlideTrajectories[layerIndex].targetNote + : tunedNoteForLayer( + layer, previousNote, triggerId - 1u, + static_cast(layerIndex)); + } + float inheritedGlideStepPerSample = 0.0f; + int inheritedGlideSamplesRemaining = 0; + auto& glideTrajectory = layerGlideTrajectories[layerIndex]; + if (shouldGlide && glideTrajectory.initialised + && glideTrajectory.samplesRemaining > 0) + { + // Portamento belongs to the instrument layer, not to the + // particular hardware voice that happened to start it. A new + // key therefore begins at the live glide accumulator even if + // the preceding voice has already completed its VCA release. + glideFromNote = glideTrajectory.currentNote; + + // Repeating the same destination must not restart either the + // curve or its timer. When the destination changes, Voice::start + // computes a fresh leg from this live position instead. + if (std::abs(glideTrajectory.targetNote + - tunedTargetNote) <= 1.0e-5f) + { + inheritedGlideStepPerSample = glideTrajectory.stepPerSample; + inheritedGlideSamplesRemaining = glideTrajectory.samplesRemaining; + } + } + + auto& voice = *allocated; + voice.start(midiNote, held.channel, + performanceVelocity(held.velocity, layer.velocityTable), + ++noteOrder, triggerId, static_cast(layerIndex), layer, + tunedTargetNote, glideFromNote, + rate, layer.sound.glideTimeModeValue != 0, + glideMode == 2 || glideMode == 4 || glideMode == 6, + inheritedGlideStepPerSample, inheritedGlideSamplesRemaining, + modWheelAmount, channelPressureAmount, pitchBendSemitones, retrigger); + + const auto destinationChanged + = shouldGlide && glideTrajectory.initialised + && glideTrajectory.samplesRemaining > 0 + && std::abs(glideTrajectory.targetNote + - tunedTargetNote) > 1.0e-5f; + if (destinationChanged) + { + // Released voices can remain audible for a substantial VCA + // tail. Leaving those voices on the abandoned trajectory makes + // the instrument audibly keep rising after a lower key has + // redirected the layer glide. The hardware layer clock changes + // direction as one unit, so attach every release tail to the + // newly calculated leg while leaving held polyphonic notes alone. + for (auto& candidate : voices) + { + if (&candidate == &voice || !candidate.active + || candidate.keyDown + || candidate.layerIndex != static_cast(layerIndex)) + continue; + + candidate.currentGlideNote = voice.currentGlideNote; + candidate.targetGlideNote = voice.targetGlideNote; + candidate.glideStepPerSample = voice.glideStepPerSample; + candidate.glideSamplesRemaining = voice.glideSamplesRemaining; + candidate.glideQuantised = voice.glideQuantised; + candidate.updatePitch(layer.sound, pitchBendSemitones); + } + } + glideTrajectory.currentNote = voice.currentGlideNote; + glideTrajectory.targetNote = voice.targetGlideNote; + glideTrajectory.stepPerSample = voice.glideStepPerSample; + glideTrajectory.samplesRemaining = voice.glideSamplesRemaining; + glideTrajectory.triggerId = triggerId; + glideTrajectory.initialised = true; + lastPlayedNotesByLayer[layerIndex] = translatedNote; + voice.updatePitch(layer.sound, pitchBendSemitones); +} + void WaldorfEngine::handleMidi(const juce::MidiMessage& message, const PerformanceSnapshot& performance, bool localKeyboard) @@ -1248,107 +1533,14 @@ void WaldorfEngine::handleMidi(const juce::MidiMessage& message, && message.getChannel() != layer.midiChannel)) continue; - const auto translatedNote = juce::jlimit( - 0, 127, midiNote + layer.transposeSemitones); - const auto tunedTargetNote = tunedNoteForLayer( - layer, translatedNote, triggerId, static_cast(layerIndex)); - const auto previousNote - = lastPlayedNotesByLayer[layerIndex]; - const auto hasHeldLayerVoice = std::any_of( - voices.begin(), voices.end(), [layerIndex](const auto& candidate) { - return candidate.active && candidate.keyDown - && candidate.layerIndex == static_cast(layerIndex); - }); - const auto glideMode = juce::jlimit(1, 6, layer.sound.glideTypeMode); - const auto midiControlled = glideMode == 3 || glideMode == 4; - const auto fingered = glideMode == 5 || glideMode == 6; - const auto midiPortamentoEnabled - = midiControllerAmounts[65] >= 0.5f; - const auto shouldGlide - = layer.sound.glideEnabled && previousNote >= 0 - && (!fingered || hasHeldLayerVoice) - && (!midiControlled || midiPortamentoEnabled); - const auto rate = midiControlled - ? midiControllerAmounts[5] * 127.0f - : layer.sound.glideRateValue; - - auto glideFromNote = tunedTargetNote; - if (shouldGlide) - { - glideFromNote = layerGlideTrajectories[layerIndex].initialised - ? layerGlideTrajectories[layerIndex].targetNote - : tunedNoteForLayer( - layer, previousNote, triggerId - 1u, - static_cast(layerIndex)); - } - float inheritedGlideStepPerSample = 0.0f; - int inheritedGlideSamplesRemaining = 0; - auto& glideTrajectory = layerGlideTrajectories[layerIndex]; - if (shouldGlide && glideTrajectory.initialised - && glideTrajectory.samplesRemaining > 0) - { - // Portamento belongs to the instrument layer, not to the - // particular hardware voice that happened to start it. A new - // key therefore begins at the live glide accumulator even if - // the preceding voice has already completed its VCA release. - glideFromNote = glideTrajectory.currentNote; - - // Repeating the same destination must not restart either the - // curve or its timer. When the destination changes, Voice::start - // computes a fresh leg from this live position instead. - if (std::abs(glideTrajectory.targetNote - - tunedTargetNote) <= 1.0e-5f) - { - inheritedGlideStepPerSample = glideTrajectory.stepPerSample; - inheritedGlideSamplesRemaining = glideTrajectory.samplesRemaining; - } - } - - auto& voice = chooseVoice(); - voice.start(midiNote, localKeyboard ? 0 : message.getChannel(), - performanceVelocity(message.getFloatVelocity(), layer.velocityTable), - ++noteOrder, triggerId, static_cast(layerIndex), layer, - tunedTargetNote, glideFromNote, - rate, layer.sound.glideTimeModeValue != 0, - glideMode == 2 || glideMode == 4 || glideMode == 6, - inheritedGlideStepPerSample, inheritedGlideSamplesRemaining, - modWheelAmount, channelPressureAmount, pitchBendSemitones); - - const auto destinationChanged - = shouldGlide && glideTrajectory.initialised - && glideTrajectory.samplesRemaining > 0 - && std::abs(glideTrajectory.targetNote - - tunedTargetNote) > 1.0e-5f; - if (destinationChanged) - { - // Released voices can remain audible for a substantial VCA - // tail. Leaving those voices on the abandoned trajectory makes - // the instrument audibly keep rising after a lower key has - // redirected the layer glide. The hardware layer clock changes - // direction as one unit, so attach every release tail to the - // newly calculated leg while leaving held polyphonic notes alone. - for (auto& candidate : voices) - { - if (&candidate == &voice || !candidate.active - || candidate.keyDown - || candidate.layerIndex != static_cast(layerIndex)) - continue; - - candidate.currentGlideNote = voice.currentGlideNote; - candidate.targetGlideNote = voice.targetGlideNote; - candidate.glideStepPerSample = voice.glideStepPerSample; - candidate.glideSamplesRemaining = voice.glideSamplesRemaining; - candidate.glideQuantised = voice.glideQuantised; - candidate.updatePitch(layer.sound, pitchBendSemitones); - } - } - glideTrajectory.currentNote = voice.currentGlideNote; - glideTrajectory.targetNote = voice.targetGlideNote; - glideTrajectory.stepPerSample = voice.glideStepPerSample; - glideTrajectory.samplesRemaining = voice.glideSamplesRemaining; - glideTrajectory.initialised = true; - lastPlayedNotesByLayer[layerIndex] = translatedNote; - voice.updatePitch(layer.sound, pitchBendSemitones); + auto& held = heldNotesByLayer[layerIndex]; + held.add({ midiNote, localKeyboard ? 0 : message.getChannel(), + message.getFloatVelocity(), triggerId }); + const auto* selected = layer.allocationMode >= 17 + ? held.selected(layer.allocationMode) + : &held.notes[held.count - 1]; + if (selected != nullptr) + startLayerNote(*selected, layerIndex, performance, true); } return; } @@ -1357,22 +1549,33 @@ void WaldorfEngine::handleMidi(const juce::MidiMessage& message, { const auto channel = localKeyboard ? 0 : message.getChannel(); auto oldestTrigger = std::numeric_limits::max(); - for (const auto& voice : voices) - if (voice.active && voice.keyDown - && voice.triggerNote == message.getNoteNumber() - && voice.triggerChannel == channel) - oldestTrigger = std::min(oldestTrigger, voice.triggerId); - - // A MIDI stream may retrigger a pitch before the earlier Note Off is - // delivered. Release only the oldest matching keystroke and all of - // its Performance layers. Releasing every voice with this pitch also - // kills the freshly allocated note and can collapse a three-note - // chord to one audible note. + for (const auto& held : heldNotesByLayer) + for (size_t index = 0; index < held.count; ++index) + if (held.notes[index].note == message.getNoteNumber() + && held.notes[index].channel == channel) + oldestTrigger = std::min(oldestTrigger, held.notes[index].trigger); if (oldestTrigger != std::numeric_limits::max()) - for (auto& voice : voices) - if (voice.active && voice.keyDown - && voice.triggerId == oldestTrigger) - voice.release(sustainPedal); + for (size_t layerIndex = 0; layerIndex < performance.layers.size(); ++layerIndex) + { + auto& held = heldNotesByLayer[layerIndex]; + held.remove(oldestTrigger); + const auto& layer = performance.layers[layerIndex]; + if (layer.allocationMode >= 17) + { + if (const auto* selected = held.selected(layer.allocationMode)) + startLayerNote(*selected, layerIndex, performance, false); + else + for (auto& voice : voices) + if (voice.active && voice.keyDown + && voice.layerIndex == static_cast(layerIndex)) + voice.release(sustainPedal); + } + else + for (auto& voice : voices) + if (voice.active && voice.keyDown && voice.triggerId == oldestTrigger + && voice.layerIndex == static_cast(layerIndex)) + voice.release(sustainPedal); + } return; } @@ -1394,12 +1597,14 @@ void WaldorfEngine::handleMidi(const juce::MidiMessage& message, voice.reset(); lastPlayedNotesByLayer.fill(-1); layerGlideTrajectories.fill({}); + heldNotesByLayer.fill({}); sustainPedal = false; return; } if (message.isAllNotesOff()) { + heldNotesByLayer.fill({}); for (auto& voice : voices) voice.release(sustainPedal); return; @@ -1409,6 +1614,20 @@ void WaldorfEngine::handleMidi(const juce::MidiMessage& message, { const auto controller = message.getControllerNumber(); const auto value = message.getControllerValue(); + for (size_t layer = 0; layer < performance.layers.size(); ++layer) + { + const auto& instrument = performance.layers[layer]; + // Physical keyboard controls already have dedicated identities; + // only received MIDI translates CC assignments into button sources. + if (localKeyboard || !instrument.enabled + || (instrument.source != 2 && instrument.source != 3) + || (instrument.midiChannel != 0 + && instrument.midiChannel != message.getChannel())) + continue; + for (size_t button = 0; button < keyboardButtonControllers.size(); ++button) + if (controller == keyboardButtonControllers[button]) + buttonAmountsByLayer[layer][button] = static_cast(value) / 127.0f; + } midiControllerAmounts[static_cast(juce::jlimit(0, 127, controller))] = static_cast(value) / 127.0f; if (controller == 1) @@ -1453,6 +1672,7 @@ void WaldorfEngine::renderRangeChunk(juce::AudioBuffer& output, if (rangeSamples <= 0) return; + renderingWavetableBank = wavetableBank.renderSnapshot(); renderingVoiceCount = 0; const auto hasSoloedInstrument = std::any_of( performance.layers.begin(), performance.layers.end(), [](const auto& layer) { @@ -1469,13 +1689,14 @@ void WaldorfEngine::renderRangeChunk(juce::AudioBuffer& output, continue; } const auto& layer = performance.layers[static_cast(voice.layerIndex)]; - const auto audible = !layer.muted && layer.audioOutput == 0 + const auto audible = layer.enabled && !layer.muted + && layer.audioOutput == PerformanceLayer::mainAudioOut && (!hasSoloedInstrument || layer.soloed); voice.currentFreeWheel = juce::jlimit(-1.0f, 1.0f, midiControllerAmounts[16] * 2.0f - 1.0f); - voice.currentButton1 = midiControllerAmounts[80]; - voice.currentButton2 = midiControllerAmounts[81]; + voice.currentButton1 = buttonAmountsByLayer[static_cast(voice.layerIndex)][0]; + voice.currentButton2 = buttonAmountsByLayer[static_cast(voice.layerIndex)][1]; voice.currentVolumeController = midiControllerAmounts[7]; voice.currentPanController = juce::jlimit(-1.0f, 1.0f, @@ -1637,7 +1858,7 @@ void WaldorfEngine::renderVoiceCard(int board, int sampleCount) noexcept Cem3387::StereoSample voiceSample; if (voice.active) voiceSample = voice.process( - wavetableBank, *rendering.parameters, rendering.modWheel, + renderingWavetableBank, *rendering.parameters, rendering.modWheel, rendering.pressure, rendering.pitchBend); else voice.advanceIdleLfos(*rendering.parameters); @@ -1712,7 +1933,8 @@ WaldorfEngine::voiceStates() const noexcept voice.circuit.currentCutoffCv(), voice.circuit.cutoffCalibrationCode(), voice.glideQuantised ? std::round(voice.currentGlideNote) : voice.currentGlideNote, - voice.active, voice.keyDown + voice.active, voice.keyDown, + voice.oscillator1.frequencyHz() }; } return states; @@ -1801,12 +2023,13 @@ WaldorfEngine::VoiceProbe WaldorfEngine::probeVoice( voice.start(midiNote, 1, velocity, order, order, layerIndex, layer, tunedNote, tunedNote, 0.0f, false, false, 0.0f, 0, 0.0f, 0.0f, 0.0f); - const auto performanceGain = layer.audioOutput == 0 ? layer.gain : 0.0f; + const auto performanceGain = layer.audioOutput == PerformanceLayer::mainAudioOut ? layer.gain : 0.0f; result.minimumCutoffHz = std::numeric_limits::max(); double energy = 0.0; + const auto bank = wavetableBank.renderSnapshot(); for (int sample = 0; sample < samples; ++sample) { - const auto output = voice.process(wavetableBank, layer.sound, + const auto output = voice.process(bank, layer.sound, 0.0f, 0.0f, 0.0f); result.minimumCutoffHz = juce::jmin(result.minimumCutoffHz, voice.controlAnalogueCutoff); @@ -1830,6 +2053,11 @@ bool WaldorfEngine::loadWavetableRom(const juce::MemoryBlock& data) noexcept return wavetableBank.loadRomImage(data.getData(), data.getSize()); } +bool WaldorfEngine::loadWaveFactoryRom(const juce::MemoryBlock& data) +{ + return wavetableBank.loadWaveFactoryRom(data.getData(), data.getSize()); +} + bool WaldorfEngine::loadWaveSetUserTables(const juce::MemoryBlock& data) noexcept { // A native Wave SET places its four 256-byte STT-format tables directly @@ -1846,13 +2074,21 @@ bool WaldorfEngine::loadWaveSetUserTables(const juce::MemoryBlock& data) noexcep for (size_t table = 0; table < tableCount; ++table) { const auto* source = bytes + tuningBankOffset + table * tableSize; + auto valid = true; + for (size_t key = 0; key < 128u; ++key) + valid = valid && source[key * 2u] <= 127u + && source[key * 2u + 1u] >= 14u + && source[key * 2u + 1u] <= 114u; + // A displaced Sound/Performance record can still look like + // seven-bit tuning data. Do not mask/clamp it into a scale that + // silently changes every Global Instrument's keyboard pitch. + // The value-initialised table supplies equal temperament instead. + if (!valid) + continue; for (size_t key = 0; key < 128u; ++key) { - const auto destinationNote = static_cast(source[key * 2u] & 0x7fu); - const auto detuneCents - = juce::jlimit(14, 114, - static_cast(source[key * 2u + 1u] & 0x7fu)) - - 64; + const auto destinationNote = static_cast(source[key * 2u]); + const auto detuneCents = static_cast(source[key * 2u + 1u]) - 64; (*decoded)[table][key] = static_cast((destinationNote - static_cast(key)) * 100 + detuneCents); @@ -1883,26 +2119,51 @@ void WaldorfEngine::applyFirmwareHardwareWrite(int board, uint32_t address, ++appliedFirmwareWrites; } -WaldorfEngine::Voice& WaldorfEngine::chooseVoice() -{ - if (const auto inactive = std::find_if(voices.begin(), voices.end(), - [](const auto& voice) { return !voice.active; }); - inactive != voices.end()) - return *inactive; - - // Dynamic allocation protects notes whose keys are still held. Released - // and sustain-held tails are the hardware-like first candidates for reuse. - if (const auto released = std::min_element( - voices.begin(), voices.end(), [](const auto& a, const auto& b) { - if (a.keyDown != b.keyDown) - return !a.keyDown; - return a.startOrder < b.startOrder; - }); - released != voices.end() && !released->keyDown) - return *released; - - return *std::min_element(voices.begin(), voices.end(), [](const auto& a, const auto& b) { +WaldorfEngine::Voice* WaldorfEngine::chooseVoice( + int layerIndex, const PerformanceSnapshot& performance) +{ + const auto mode = performance.layers[static_cast(layerIndex)].allocationMode; + Voice* own = nullptr; + int ownCount = 0; + const auto older = [](const Voice& a, const Voice& b) { + if (a.keyDown != b.keyDown) + return !a.keyDown; return a.startOrder < b.startOrder; - }); + }; + for (auto& voice : voices) + if (voice.active && voice.layerIndex == layerIndex) + { + ++ownCount; + if (own == nullptr || (mode >= 17 ? voice.startOrder > own->startOrder + : older(voice, *own))) + own = &voice; + } + if (mode >= 17 && own != nullptr) + return own; + for (auto& voice : voices) + if (!voice.active) + return &voice; + + // Dynamic Instruments can only reuse their own sounding voices. Poly N + // permits reclaiming up to N voices from other Instruments when full; + // it does not limit ordinary polyphony while free voices are available. + if (mode == 0 || (mode < 17 && ownCount >= mode)) + return own; + Voice* other = nullptr; + for (auto& voice : voices) + { + if (voice.layerIndex == layerIndex) + continue; + const auto otherMode = performance.layers[static_cast(voice.layerIndex)] + .allocationMode; + if (otherMode >= 17) + continue; // Mono voices are protected, even from another mono part. + const auto previousMode = other == nullptr ? 0 + : performance.layers[static_cast(other->layerIndex)].allocationMode; + if (other == nullptr || (otherMode == 0 && previousMode != 0) + || ((otherMode == 0) == (previousMode == 0) && older(voice, *other))) + other = &voice; + } + return other != nullptr ? other : own; } } // namespace wave::dsp diff --git a/Source/Dsp/WaldorfEngine.h b/Source/Dsp/WaldorfEngine.h index 571fcbc..fdb419e 100644 --- a/Source/Dsp/WaldorfEngine.h +++ b/Source/Dsp/WaldorfEngine.h @@ -49,7 +49,10 @@ class WaldorfEngine float detuneCents = 0.0f; float gain = 1.0f; float auxGain = 0.0f; - int audioOutput = 0; + // Firmware "Audio Out" (Instrument part byte +0xC): 0 Aux only, + // 1 main, 2 sub 1, 3 sub 2. Only main reaches the plugin output. + static constexpr int mainAudioOut = 1; + int audioOutput = mainAudioOut; int keyLow = 0; int keyHigh = 127; int velocityLow = 1; @@ -59,6 +62,9 @@ class WaldorfEngine // temperaments: global, linear+, HMT, linear-, random 1..4, // user 1..4 and the MIDI Tuning Standard table. int tuningTable = 0; + // Native Instrument byte 15: dynamic, poly 1..16, last/low/high + // retrigger, then last/low/high single-trigger. + int allocationMode = 0; float performanceModWheel = -1.0f; float performanceChannelPressure = -1.0f; float performancePitchBend = -100.0f; @@ -76,6 +82,15 @@ class WaldorfEngine float circuitAgeAmount = 0.18f; }; + // Phase-load code the WDV writes to the ASIC at key-on (OS 1.700 0xF92 for + // Wave 1, 0x1074 for Wave 2). `programmed` is Startphase (sound byte 27/43, + // 0 = free start), `storedAmount` the route amount byte (0..127, 64 = off) + // and `source` the 16-bit modulation word. Returns 0 for a free start + // (nothing is written), otherwise the byte the firmware sends: the sum is + // formed in 16-bit words, so Wave 1 wraps to 8 bits where Wave 2 saturates. + [[nodiscard]] static int startPhaseCode(int programmed, int storedAmount, int source, + bool secondOscillator) noexcept; + struct VoiceProbe { float minimumCutoffHz = 0.0f; @@ -100,6 +115,7 @@ class WaldorfEngine float glidePitch = 0.0f; bool active = false; bool keyDown = false; + float oscillator1FrequencyHz = 0.0f; }; WaldorfEngine(); @@ -109,6 +125,9 @@ class WaldorfEngine // Called by the host between render callbacks, while all card jobs are idle. void setAudioWorkgroup(const juce::AudioWorkgroup& workgroup) { audioWorkgroup = workgroup; } void reset(); + // Physical buttons remain distinct even when their MIDI assignments coincide. + void setKeyboardButtons(bool button1, bool button2) noexcept; + void setKeyboardButtonControllers(int button1, int button2) noexcept; void render(juce::AudioBuffer& output, const juce::MidiBuffer& midi, const parameters::Snapshot& parameters); void render(juce::AudioBuffer& output, const juce::MidiBuffer& midi, @@ -122,6 +141,7 @@ class WaldorfEngine [[nodiscard]] const WavetableBank& getWavetableBank() const noexcept { return wavetableBank; } bool loadWavetableRom(const juce::MemoryBlock& data) noexcept; + bool loadWaveFactoryRom(const juce::MemoryBlock& data); bool loadWaveSetUserTables(const juce::MemoryBlock& data) noexcept; void applyFirmwareHardwareWrite(int board, uint32_t address, uint8_t value) noexcept; void applyFirmwareHardwareWrite(uint32_t address, uint8_t value) noexcept @@ -173,9 +193,11 @@ class WaldorfEngine bool glideDistanceMode, bool glideQuantised, float inheritedGlideStepPerSample, int inheritedGlideSamplesRemaining, float modWheel, - float channelPressure, float pitchBend); + float channelPressure, float pitchBend, + bool retriggerEnvelopes = true); void release(bool allowSustain = true); void updatePitch(const parameters::Snapshot& parameters, float pitchBend); + [[nodiscard]] float baseFrequencyHz() const noexcept; [[nodiscard]] Cem3387::StereoSample process(const WavetableBank& bank, const parameters::Snapshot& parameters, float modWheel, float channelPressure, @@ -219,6 +241,7 @@ class WaldorfEngine OscillatorChipProxy oscillator2; AsicHighpassFilter highpassFilter; ReconstructionStage reconstruction; + AsicResampler asicResampler; Cem3387 circuit; WdvEnvelope envelope; WdvEnvelope filterEnvelope; @@ -246,7 +269,6 @@ class WaldorfEngine bool active = false; float currentWavePosition = 0.0f; std::array currentLfoValues{}; - std::array waveStartOffsets{}; std::array currentPitchModulations{}; float currentGlideNote = 0.0f; float targetGlideNote = 0.0f; @@ -286,7 +308,7 @@ class WaldorfEngine int filterEnvelopeDelaySamples = 0; int vcaDrainSamplesRemaining = 0; int controlFilterMode = 0; - bool waveStartOffsetsPending = false; + bool startPhaseModPending = false; bool filterEnvelopePending = false; bool filterEnvelopeTriggered = false; }; @@ -297,6 +319,7 @@ class WaldorfEngine float targetNote = 0.0f; float stepPerSample = 0.0f; int samplesRemaining = 0; + uint64_t triggerId = 0; bool initialised = false; }; @@ -331,9 +354,28 @@ class WaldorfEngine void renderVoiceCard(int board, int sampleCount) noexcept; void startVoiceCardWorkers(double sampleRate, int maximumBlockSize); void stopVoiceCardWorkers() noexcept; - Voice& chooseVoice(); + Voice* chooseVoice(int layer, const PerformanceSnapshot& performance); + struct HeldNote + { + int note = -1; + int channel = 0; + float velocity = 0.0f; + uint64_t trigger = 0; + }; + struct HeldNotes + { + std::array notes{}; + size_t count = 0; + void add(HeldNote note) noexcept; + void remove(uint64_t trigger) noexcept; + [[nodiscard]] const HeldNote* selected(int allocationMode) const noexcept; + }; + void startLayerNote(const HeldNote& note, size_t layerIndex, + const PerformanceSnapshot& performance, + bool noteOnEvent); WavetableBank wavetableBank; + WavetableBank renderingWavetableBank; std::shared_ptr userTuningBank; std::array voices; std::array renderingVoices{}; @@ -356,8 +398,15 @@ class WaldorfEngine float modWheelAmount = 0.0f; float channelPressureAmount = 0.0f; std::array midiControllerAmounts{}; + std::array keyboardButtonControllers { 64, 1 }; + std::array keyboardButtonStates {}; + std::array appliedKeyboardButtonStates { -1, -1 }; + std::array, 8> buttonAmountsByLayer {}; + std::array buttonSourcesByLayer {}; std::array lastPlayedNotesByLayer {}; std::array layerGlideTrajectories {}; + std::array heldNotesByLayer{}; + std::array allocationModesByLayer{}; bool sustainPedal = false; }; } // namespace wave::dsp diff --git a/Source/Dsp/WaveFactoryRom.cpp b/Source/Dsp/WaveFactoryRom.cpp new file mode 100644 index 0000000..c16e058 --- /dev/null +++ b/Source/Dsp/WaveFactoryRom.cpp @@ -0,0 +1,130 @@ +#include "WaveFactoryRom.h" +#include "Firmware/M68000.h" + +#include +#include +#include + +namespace wave::dsp +{ +namespace +{ +class FactoryBus final : public firmware::M68000Bus +{ +public: + std::vector ram = std::vector(0x200000); + bool completed = false; + bool unmapped = false; + + uint8_t read8(uint32_t address) noexcept override + { + if (address < ram.size()) + return ram[address]; + unmapped = true; + return 0xff; + } + void write8(uint32_t address, uint8_t value) noexcept override + { + if (address < ram.size()) + ram[address] = value; + else + unmapped = true; + } + bool usesInstructionInterception() const noexcept override { return true; } + bool interceptInstruction(firmware::M68000& cpu, uint32_t pc) noexcept override + { + // All 64 half-waves have been filled when the master reaches its + // WDV transfer call. Stop before the hardware handshake. + if (pc == 0x00bd6e) + { + completed = true; + cpu.endTimeslice(); + return true; + } + return false; + } +}; +} // namespace + +bool WaveFactoryRom::decode(const void* image, size_t size, std::vector& output) +{ + // Absolute routine/data addresses are specific to this official image. + if (image == nullptr || size != 302768 + || juce::SHA256(image, size).toHexString() + != "4282457d9bf7d70da2e2aa4d6a1e69467c178d0d8d8be0a27f524ab8d62e3286") + return false; + + static std::mutex mutex; + static std::vector cached; + const std::lock_guard lock(mutex); + if (!cached.empty()) + { + output = cached; + return true; + } + + const auto* bytes = static_cast(image); + std::vector halfWaves; + halfWaves.reserve(tableCount * wavesPerTable * 64); + FactoryBus bus; + for (int table = 0; table < tableCount; ++table) + { + std::fill(bus.ram.begin(), bus.ram.end(), 0); + std::copy_n(bytes, size, bus.ram.begin() + 0x1000); + bus.completed = false; + bus.unmapped = false; + firmware::M68000 cpu; + cpu.start(bus, 0x0ffffe, 0x011bb8); + cpu.setDataRegister(bus, 0, static_cast(table)); + cpu.setDataRegister(bus, 1, 0); + for (int cycles = 0; !bus.completed && !bus.unmapped && cycles < 2000000; + cycles += 10000) + cpu.execute(bus, 10000); + if (!bus.completed || bus.unmapped) + return false; + halfWaves.insert(halfWaves.end(), bus.ram.begin() + 0x104000, + bus.ram.begin() + 0x105000); + } + // Guard the complete result, including the Wave-specific calculated + // tables, slot 60, and the original triangle/square/saw terminal waves. + if (juce::SHA256(halfWaves.data(), halfWaves.size()).toHexString() + != "e2d3bdd4d22053058458962df7dc9a7ad08e895190f7b08e7f6b1ef63d1976c3") + return false; + + std::vector decoded(tableCount * wavesPerTable * samplesPerWave); + for (size_t wave = 0; wave < tableCount * wavesPerTable; ++wave) + for (size_t sample = 0; sample < 64; ++sample) + { + const auto value = halfWaves[wave * 64 + sample]; + decoded[wave * 128 + sample] = static_cast(static_cast(value) - 128); + decoded[wave * 128 + 127 - sample] + = static_cast(static_cast(static_cast(~value)) - 128); + } + cached = std::move(decoded); + output = cached; + return true; +} + +bool WaveFactoryRom::decodeRomWaves(const void* image, size_t size, std::vector& output) +{ + if (image == nullptr || size != 302768 + || juce::SHA256(image, size).toHexString() + != "4282457d9bf7d70da2e2aa4d6a1e69467c178d0d8d8be0a27f524ab8d62e3286") + return false; + // OS 1.700's Wave lookup at $0120EE resolves R000..R299 to + // $042850 + Wave * 64. The system image begins at CPU address $001000. + constexpr size_t halfWaveOffset = 0x42850u - 0x1000u; + const auto* bytes = static_cast(image); + std::vector decoded(static_cast(romWaveCount) * samplesPerWave); + for (size_t wave = 0; wave < romWaveCount; ++wave) + for (size_t sample = 0; sample < 64; ++sample) + { + const auto value = bytes[halfWaveOffset + wave * 64 + sample]; + decoded[wave * 128 + sample] = static_cast(static_cast(value) - 128); + decoded[wave * 128 + 127 - sample] + = static_cast(static_cast(static_cast(~value)) - 128); + } + output = std::move(decoded); + return true; +} +} // namespace wave::dsp diff --git a/Source/Dsp/WaveFactoryRom.h b/Source/Dsp/WaveFactoryRom.h new file mode 100644 index 0000000..f1aa7a0 --- /dev/null +++ b/Source/Dsp/WaveFactoryRom.h @@ -0,0 +1,20 @@ +#pragma once + +#include +#include + +namespace wave::dsp +{ +// Execute the original OS 1.700 factory-table routines. No reconstructed +// PPG generator or separately captured upper bank is involved. +class WaveFactoryRom +{ +public: + static constexpr int tableCount = 64; + static constexpr int wavesPerTable = 64; + static constexpr int samplesPerWave = 128; + static constexpr int romWaveCount = 300; + static bool decode(const void* image, size_t size, std::vector& output); + static bool decodeRomWaves(const void* image, size_t size, std::vector& output); +}; +} // namespace wave::dsp diff --git a/Source/Firmware/DosFloppyImage.cpp b/Source/Firmware/DosFloppyImage.cpp index b5aaf38..da9fee4 100644 --- a/Source/Firmware/DosFloppyImage.cpp +++ b/Source/Firmware/DosFloppyImage.cpp @@ -169,23 +169,53 @@ juce::Result DosFloppyImage::createEmpty(const juce::File& destination) juce::Result DosFloppyImage::createWithWaveSetup(const juce::File& destination, const juce::File& source) { + return createWithWaveFile(destination, source, false); +} + +juce::Result DosFloppyImage::createWithWaveWavetable(const juce::File& destination, + const juce::File& source) +{ + return createWithWaveFile(destination, source, true); +} + +juce::Result DosFloppyImage::createWithWaveFile(const juce::File& destination, + const juce::File& source, + bool wavetable) +{ + auto output = destination; + if (output.getFileExtension().isEmpty()) + output = output.withFileExtension(".img"); + if (output == source) + return juce::Result::fail("Save the disk image to a different file from its source."); const auto rootSectors = rootEntries * 32u / bytesPerSector; const auto rootStartSector = 1u + 2u * fatSectors; const auto dataStartSector = rootStartSector + rootSectors; const auto clusterBytes = bytesPerSector * sectorsPerCluster; const auto availableClusters = (totalSectors - dataStartSector) / sectorsPerCluster; if (!source.existsAsFile()) - return juce::Result::fail("The selected Wave Setup file does not exist."); + return juce::Result::fail("The selected Wave file does not exist."); juce::MemoryBlock setup; if (!source.loadFileAsData(setup) || setup.getSize() == 0) - return juce::Result::fail("The Wave Setup file could not be read."); + return juce::Result::fail("The Wave file could not be read."); + if (wavetable) + { + constexpr size_t recordBytes = 138; + constexpr size_t halfWaveBytes = 64; + const auto* bytes = static_cast(setup.getData()); + if (!source.hasFileExtension(".wtb") || setup.getSize() < recordBytes + || (setup.getSize() - recordBytes) % halfWaveBytes != 0 + || setup.getSize() > recordBytes + 1000u * halfWaveBytes + || bytes[9] != 0x55u) + return juce::Result::fail( + "Select a native Waldorf Wave .WTB file (a wavetable record with optional Wave data)."); + } const auto requiredClusters = (setup.getSize() + clusterBytes - 1u) / clusterBytes; if (requiredClusters > availableClusters) return juce::Result::fail( - "The selected Wave Setup does not fit on a 720 KB DD floppy."); + "The selected Wave file does not fit on a 720 KB DD floppy."); auto disk = makeFormattedDisk(); - std::copy_n(reinterpret_cast("WAVE SET "), 11, + std::copy_n(reinterpret_cast(wavetable ? "WAVE WTB " : "WAVE SET "), 11, disk.begin() + 43); auto* firstFat = disk.data() + bytesPerSector; @@ -212,9 +242,6 @@ juce::Result DosFloppyImage::createWithWaveSetup(const juce::File& destination, std::copy_n(static_cast(setup.getData()), setup.getSize(), disk.begin() + static_cast(dataOffset)); - auto output = destination; - if (output.getFileExtension().isEmpty()) - output = output.withFileExtension(".img"); if (!output.replaceWithData(disk.data(), disk.size())) return juce::Result::fail("The floppy image could not be written."); return juce::Result::ok(); diff --git a/Source/Firmware/DosFloppyImage.h b/Source/Firmware/DosFloppyImage.h index c9aa842..d931ab0 100644 --- a/Source/Firmware/DosFloppyImage.h +++ b/Source/Firmware/DosFloppyImage.h @@ -22,9 +22,16 @@ class DosFloppyImage final // manual, containing one Wave Setup file in an ordinary 8.3 directory. static juce::Result createWithWaveSetup(const juce::File& destinationImage, const juce::File& waveSetupFile); + // Packages a native Wave .WTB unchanged for loading via the Disk pages. + static juce::Result createWithWaveWavetable(const juce::File& destinationImage, + const juce::File& wavetableFile); // Reads the first ordinary .SET file from a FAT12 floppy image. This is // used by the audio engine as the same bank source the firmware sees. static juce::Result readWaveSetup(const juce::File& imageFile, SetupFile& setupFile); +private: + static juce::Result createWithWaveFile(const juce::File& destinationImage, + const juce::File& sourceFile, + bool wavetable); }; } // namespace wave::firmware diff --git a/Source/Firmware/Dp8473.cpp b/Source/Firmware/Dp8473.cpp index bc5e7cf..92ad32e 100644 --- a/Source/Firmware/Dp8473.cpp +++ b/Source/Firmware/Dp8473.cpp @@ -1,6 +1,7 @@ #include "Dp8473.h" #include +#include namespace wave::firmware { @@ -25,48 +26,103 @@ uint32_t little32(const std::vector& bytes, size_t offset) noexcept } } +Dp8473::~Dp8473() +{ + { + const std::scoped_lock lock(mutex); + stopping = true; + } + saveRequested.notify_one(); + if (saveThread.joinable()) + saveThread.join(); + (void) flush(); +} + +void Dp8473::saveLoop() +{ + std::unique_lock lock(mutex); + while (!stopping) + { + saveRequested.wait(lock, [this] { return stopping || dirty; }); + if (stopping) + break; + + // Batch a floppy's sector transfers, with a bounded delay even while + // the firmware continues writing. Never perform file I/O on audio. + if (saveRequested.wait_for(lock, std::chrono::milliseconds(100), + [this] { return stopping; })) + break; + lock.unlock(); + const auto saved = flush(); + lock.lock(); + if (saved.failed()) + saveRequested.wait_for(lock, std::chrono::seconds(1), + [this] { return stopping; }); + } +} + juce::Result Dp8473::mount(const juce::File& file) { if (!file.existsAsFile()) return juce::Result::fail("The selected disk image does not exist."); - juce::MemoryBlock bytes; - if (!file.loadFileAsData(bytes)) - return juce::Result::fail("The selected disk image could not be read."); - - std::vector loaded(bytes.getSize()); - if (!loaded.empty()) - std::copy_n(static_cast(bytes.getData()), loaded.size(), - loaded.begin()); - Geometry detected; - if (!geometryForImage(loaded, detected)) - return juce::Result::fail( - "This is not a supported raw MS-DOS floppy image (720 KB, 800 KB, " - "1.44 MB, or a valid FAT BPB geometry)."); - - const auto previousFlush = flush(); - if (previousFlush.failed()) - return previousFlush; + const std::scoped_lock saveLock(saveMutex); + for (;;) + { + // The selected path may be the image already in the drive. Commit its + // pending sector writes before reading it, so a remount cannot install + // the older on-disk bytes after successfully flushing the newer image. + const auto previousFlush = flushWithSaveLock(); + if (previousFlush.failed()) + return previousFlush; + + juce::MemoryBlock bytes; + if (!file.loadFileAsData(bytes)) + return juce::Result::fail("The selected disk image could not be read."); + + std::vector loaded(bytes.getSize()); + if (!loaded.empty()) + std::copy_n(static_cast(bytes.getData()), loaded.size(), + loaded.begin()); + Geometry detected; + if (!geometryForImage(loaded, detected)) + return juce::Result::fail( + "This is not a supported raw MS-DOS floppy image (720 KB, 800 KB, " + "1.44 MB, or a valid FAT BPB geometry)."); - const std::scoped_lock lock(mutex); - imagePath = file; - image = std::move(loaded); - geometry = detected; - writable = file.hasWriteAccess(); - dirty = false; - bytesRead = 0; - ++revision; - // The Wave polls the drive-status input before it will issue any FDC - // command. Leaving the change line asserted here deadlocks the firmware: - // it keeps displaying "Please insert Disk!" and never seeks/recalibrates, - // which are the only controller commands that otherwise clear the latch. - // A host mount represents the completed insertion, so present ready media. - diskChanged = false; - resetController(); - return juce::Result::ok(); + const std::scoped_lock lock(mutex); + // A completed audio-thread transfer during the read must also reach the + // old image before it is replaced (including a remount of the same path). + if (dirty) + continue; + if (!saveThread.joinable()) + saveThread = std::thread([this] { saveLoop(); }); + imagePath = file; + image = std::move(loaded); + geometry = detected; + writable = file.hasWriteAccess(); + dirty = false; + lastSaveError.clear(); + bytesRead = 0; + ++revision; + // The Wave polls the drive-status input before it will issue any FDC + // command. Leaving the change line asserted here deadlocks the firmware: + // it keeps displaying "Please insert Disk!" and never seeks/recalibrates, + // which are the only controller commands that otherwise clear the latch. + // A host mount represents the completed insertion, so present ready media. + diskChanged = false; + resetController(); + return juce::Result::ok(); + } } juce::Result Dp8473::flush() +{ + const std::scoped_lock saveLock(saveMutex); + return flushWithSaveLock(); +} + +juce::Result Dp8473::flushWithSaveLock() { juce::File destination; std::vector snapshot; @@ -82,31 +138,56 @@ juce::Result Dp8473::flush() snapshotRevision = revision; } - if (!destination.replaceWithData(snapshot.data(), snapshot.size())) - return juce::Result::fail("The mounted disk image could not be saved."); + // Only replace the original after a complete, successful write. JUCE's + // File::replaceWithData does not check its temporary-file write result. + const juce::TemporaryFile temporary(destination, juce::TemporaryFile::useHiddenFile); + auto saved = false; + { + juce::FileOutputStream stream(temporary.getFile()); + if (stream.openedOk() && stream.write(snapshot.data(), snapshot.size())) + { + stream.flush(); + saved = stream.getStatus().wasOk(); + } + } + if (saved) + saved = temporary.overwriteTargetFileWithTemporary(); const std::scoped_lock lock(mutex); - if (imagePath == destination && revision == snapshotRevision) + if (!saved) + { + lastSaveError = "The mounted disk image could not be saved."; + return juce::Result::fail(lastSaveError); + } + lastSaveError.clear(); + if (revision == snapshotRevision) dirty = false; return juce::Result::ok(); } juce::Result Dp8473::eject() { - const auto saved = flush(); - if (saved.failed()) - return saved; - const std::scoped_lock lock(mutex); - imagePath = juce::File{}; - image.clear(); - geometry = {}; - writable = false; - dirty = false; - bytesRead = 0; - diskChanged = true; - ++revision; - resetController(); - return juce::Result::ok(); + const std::scoped_lock saveLock(saveMutex); + for (;;) + { + const auto saved = flushWithSaveLock(); + if (saved.failed()) + return saved; + const std::scoped_lock lock(mutex); + if (dirty) + continue; + imagePath = juce::File{}; + image.clear(); + geometry = {}; + writable = false; + dirty = false; + lastSaveError.clear(); + bytesRead = 0; + diskChanged = true; + ++revision; + resetController(); + return juce::Result::ok(); + } } juce::MemoryBlock Dp8473::mountedImageSnapshot() const @@ -580,6 +661,7 @@ void Dp8473::setDirty() noexcept { dirty = true; ++revision; + saveRequested.notify_one(); } bool Dp8473::drqAsserted() const noexcept @@ -638,6 +720,8 @@ juce::String Dp8473::mountedDescription() const description += " (read-only)"; if (dirty) description += " *"; + if (lastSaveError.isNotEmpty()) + description += " (save failed; retrying)"; return description; } } // namespace wave::firmware diff --git a/Source/Firmware/Dp8473.h b/Source/Firmware/Dp8473.h index 28acfd2..d989ed2 100644 --- a/Source/Firmware/Dp8473.h +++ b/Source/Firmware/Dp8473.h @@ -3,8 +3,10 @@ #include #include +#include #include #include +#include #include namespace wave::firmware @@ -16,6 +18,9 @@ namespace wave::firmware class Dp8473 final { public: + Dp8473() = default; + ~Dp8473(); + juce::Result mount(const juce::File& imageFile); juce::Result flush(); juce::Result eject(); @@ -70,8 +75,17 @@ class Dp8473 final [[nodiscard]] uint8_t readDataRegister(bool dma, bool terminalCount) noexcept; void writeDataRegister(uint8_t value, bool dma) noexcept; void setDirty() noexcept; + juce::Result flushWithSaveLock(); + void saveLoop(); mutable std::mutex mutex; + // Serialize host file writes and media changes independently of the + // controller lock: audio only touches the in-memory image. + std::mutex saveMutex; + std::condition_variable saveRequested; + std::thread saveThread; + bool stopping = false; + juce::String lastSaveError; juce::File imagePath; std::vector image; Geometry geometry; diff --git a/Source/Firmware/FirmwareBundle.cpp b/Source/Firmware/FirmwareBundle.cpp index d9ad0ec..f02443a 100644 --- a/Source/Firmware/FirmwareBundle.cpp +++ b/Source/Firmware/FirmwareBundle.cpp @@ -17,9 +17,11 @@ Bundle::Report Bundle::load(const juce::File& directoryOrImage) { clear(); - const auto root = directoryOrImage.isDirectory() - ? directoryOrImage - : directoryOrImage.getParentDirectory(); + // A missing path must not fall back to its parent: the recursive image + // search below would then walk e.g. the whole filesystem for "/nonexistent". + const auto root = directoryOrImage.existsAsFile() + ? directoryOrImage.getParentDirectory() + : directoryOrImage; const auto masterFile = findImage(root, "w2sys.bin"); const auto voiceFile = findImage(root, "wdv.sys"); diff --git a/Source/Firmware/MasterFirmwareRuntime.cpp b/Source/Firmware/MasterFirmwareRuntime.cpp index 7be21fe..851fb72 100644 --- a/Source/Firmware/MasterFirmwareRuntime.cpp +++ b/Source/Firmware/MasterFirmwareRuntime.cpp @@ -25,6 +25,27 @@ constexpr uint32_t osFileClose = 0x02d234; constexpr uint32_t osFileRead = 0x02d23a; constexpr uint16_t initSoundHandle = 0x7001; constexpr uint16_t initPerformanceHandle = 0x7002; + +class ScopedDisplayTextBuffer +{ +public: + explicit ScopedDisplayTextBuffer(SharedFirmwareMemory& memory) noexcept + : text(memory.mainRam.data() + 0x56000u) + { + std::copy_n(text, saved.size(), saved.begin()); + } + + ~ScopedDisplayTextBuffer() + { + std::copy(saved.begin(), saved.end(), text); + } + +private: + // OS 1.700 shares this formatting workspace with Store's name editor. + // The panel dispatch table begins immediately after it at $56070. + uint8_t* text; + std::array saved{}; +}; } // namespace void MasterFirmwareRuntime::Acia6850::reset() noexcept @@ -81,14 +102,20 @@ void MasterFirmwareRuntime::Acia6850::pushReceive(uint8_t value) noexcept bool MasterFirmwareRuntime::loadAndStart(const juce::MemoryBlock& masterImage) { loaded = false; + pendingPanelEventCount = 0; if (sharedMemory == &ownedSharedMemory) sharedMemory->clear(); else sharedMemory->mainRam.fill(0); for (auto& byte : lcdVideoRam) byte.store(0, std::memory_order_relaxed); - for (auto& word : panelSwitchWords) - word.store(0xffffu, std::memory_order_relaxed); + // The first six banks are active-low switches. The last two are + // quadrature encoder inputs, whose idle phase must match the firmware's + // zero-initialised previous-phase words at $5520C. Starting those banks + // high makes the scanner generate a -1 step for every encoder at boot. + for (size_t bank = 0; bank < panelSwitchWords.size(); ++bank) + panelSwitchWords[bank].store(bank < 6 ? 0xffffu : 0x0000u, + std::memory_order_relaxed); for (auto& cycle : panelReleaseCycles) cycle.store(0, std::memory_order_relaxed); for (auto& pending : panelReleasePending) @@ -124,6 +151,11 @@ bool MasterFirmwareRuntime::loadAndStart(const juce::MemoryBlock& masterImage) displayRefreshActive = false; displayRefreshComplete = false; pendingPerformanceRefresh = -1; + pendingPerformanceDisplayFrozen.store(false, std::memory_order_release); + lcdPresentationRevision.fetch_add(1, std::memory_order_release); + pendingPerformanceMidiAddress = 0; + internalPerformanceDispatch = false; + pendingPerformanceSelectionHandled = false; voiceLoaderReached = false; voiceBoardHandoffComplete = false; activeVoiceBoardCount = 0; @@ -216,33 +248,70 @@ bool MasterFirmwareRuntime::installEditRecords( return true; } +bool MasterFirmwareRuntime::installSoundBank( + std::span sounds) noexcept +{ + constexpr size_t editableBank = 0x8000u; + constexpr size_t storedBank = 0x18000u; + constexpr size_t bankBytes = 256u * 256u; + if (!loaded || sounds.size() != bankBytes + || storedBank + bankBytes > sharedMemory->program.size()) + return false; + + // The OS can resolve a Sound through either bank according to its edit + // registry. Populate both from the loaded SET so the native browser and + // subsequent selection see the same 256 distinct programs as the engine. + std::copy(sounds.begin(), sounds.end(), + sharedMemory->program.begin() + editableBank); + std::copy(sounds.begin(), sounds.end(), + sharedMemory->program.begin() + storedBank); + return true; +} + +bool MasterFirmwareRuntime::installPerformanceBank( + std::span performances) noexcept +{ + constexpr uint32_t bankOffset = 0x28000u; + constexpr size_t bankBytes = 256u * 512u; + if (!loaded || sharedMemory == nullptr || performances.size() != bankBytes) + return false; + + // The native bank at $128000 crosses into work SRAM at $140000. + for (size_t index = 0; index < bankBytes; ++index) + write8(sharedProgramBase + bankOffset + static_cast(index), + performances[index]); + return true; +} + bool MasterFirmwareRuntime::requestPerformanceSelection(int programIndex) noexcept { if (!loaded || programIndex < 0 || programIndex >= 256) return false; - // OS 1.700's MIDI program-change handler combines the 7-bit program - // number with bit 0 of this genuine system-work byte (see $008B3C-$008B52) - // before calling the firmware's performance-selection routine. Feeding - // the request through that handler is important: merely replacing the - // edit records leaves the OS's selected-performance state and its LCD - // callbacks pointing at the previous program. - constexpr uint32_t performanceBankOffset = 0x8820u; - auto& bank = sharedMemory->work[performanceBankOffset]; - bank = static_cast((bank & 0xfeu) | ((programIndex / 128) & 0x01)); - - // A request may deliberately reselect the same program number after its - // backing bank has changed (for example, cold-start A001 after a disk - // Total Recall). Do not let runCycles mistake the old matching number for - // completion before OS 1.700 has consumed the MIDI event and installed - // the new bank's display callbacks/data. - constexpr uint32_t selectedPerformanceAddress = 0x54b40u; - sharedMemory->mainRam[selectedPerformanceAddress] = 0xffu; - sharedMemory->mainRam[selectedPerformanceAddress + 1u] = 0xffu; - + if (!pendingPerformanceDisplayFrozen.load(std::memory_order_acquire)) + { + const auto frame = lcdVideoSnapshot(); + for (size_t index = 0; index < frame.size(); ++index) + pendingPerformanceDisplay[index].store(frame[index], std::memory_order_relaxed); + pendingPerformanceDisplayPage.store(lcdDisplayPage(), std::memory_order_relaxed); + pendingPerformanceDisplayFrozen.store(true, std::memory_order_release); + lcdPresentationRevision.fetch_add(1, std::memory_order_release); + } + // Feed panel/host recall through the normal OS parser, tagging its data + // byte so external MIDI routing/maps cannot redirect this internal request. + // Keep the live selected ID valid until the OS installs the new one. + auto& bank = sharedMemory->work[0x8820u]; + bank = static_cast((bank & 0xfeu) | ((programIndex / 128) & 1)); + pendingPerformanceRefresh = programIndex; + pendingPerformanceSelectionHandled = false; pushMidiByte(0, 0xc0u); + constexpr uint32_t writePointerAddress = 0x4dda4u; + const auto& ram = sharedMemory->mainRam; + pendingPerformanceMidiAddress = (static_cast(ram[writePointerAddress]) << 24u) + | (static_cast(ram[writePointerAddress + 1u]) << 16u) + | (static_cast(ram[writePointerAddress + 2u]) << 8u) + | ram[writePointerAddress + 3u]; pushMidiByte(0, static_cast(programIndex & 0x7f)); - pendingPerformanceRefresh = programIndex; return true; } @@ -267,6 +336,10 @@ bool MasterFirmwareRuntime::redrawCurrentScreenWithFirmware() // Its temporary stack occupies the Wave's reserved upper stack area and is // restored afterwards, leaving the continuously running OS CPU untouched. // All display writes and all drawing decisions still come from w2sys.bin. + // The main CPU may be suspended between selecting a Store destination + // and copying its edited name. Drawing fader labels uses the same text + // buffer, so preserve it as well as the stack during this extra redraw. + const ScopedDisplayTextBuffer preserveText(*sharedMemory); std::array savedStack{}; std::copy(ram.begin() + temporaryStackBottom, ram.end(), savedStack.begin()); ram[temporaryStackPointer] = static_cast(returnSentinel >> 24u); @@ -282,9 +355,36 @@ bool MasterFirmwareRuntime::redrawCurrentScreenWithFirmware() displayCpu.execute(*this, 50000); displayRefreshActive = false; std::copy(savedStack.begin(), savedStack.end(), ram.begin() + temporaryStackBottom); + if (displayRefreshComplete) + prepareNumericPanelInput(); return displayRefreshComplete; } +void MasterFirmwareRuntime::prepareNumericPanelInput() noexcept +{ + if (!loaded || sharedMemory == nullptr) + return; + auto& ram = sharedMemory->mainRam; + const auto readLong = [&ram](uint32_t address) { + return bigEndian32(ram.data() + address); + }; + if (ram[0x56f4au] != 0 && readLong(0x56bb0u) == 0x0189c4u + && readLong(0x57030u) == 0x01ce84u + && readLong(0x56728u) == 0x01ce84u + && readLong(0x56738u) == 0x01ce84u) + { + // Performance has restored the OS's inert Manager and response + // callbacks, but a preceding disk workspace can leave its active flag + // behind. $1CBDC then sends completed numbers to the inert callback. + // Retire that orphaned ownership and any entry made into it. Genuine + // numeric entry and requesters install other callbacks and stay intact. + ram[0x56f4au] = 0; + ram[0x58f73u] = 0; + ram[0x58f74u] = 0; + ram[0x58f76u] = 0; + } +} + bool MasterFirmwareRuntime::navigatePageWithFirmware(bool forwards) noexcept { if (!loaded || sharedMemory == nullptr) @@ -295,8 +395,36 @@ bool MasterFirmwareRuntime::navigatePageWithFirmware(bool forwards) noexcept // scheduler, which makes a host mouse click liable either to be missed or // to repeat several times inside one audio block. Run the callbacks that // the current screen installed, in their exact firmware order, once. - constexpr uint32_t backwardsCallbacks = 0x56698u; - constexpr uint32_t forwardsCallbacks = 0x566a8u; + const auto completed = runPanelCallbacksWithFirmware(forwards ? 0x566a8u : 0x56698u); + sharedMemory->mainRam[0x59890u] = 0u; + releasePanelEventLatch(21); + releasePanelEventLatch(23); + return completed; +} + +bool MasterFirmwareRuntime::stepDiskMenuWithFirmware(bool forwards) noexcept +{ + if (!loaded || sharedMemory == nullptr) + return false; + const auto code = forwards ? 72u : 69u; + const auto action = sharedMemory->mainRam[0x2850eu + code]; + const auto callbacks = 0x56618u + static_cast(action) * 16u; + const auto& ram = sharedMemory->mainRam; + const auto callback = (static_cast(ram[callbacks]) << 24u) + | (static_cast(ram[callbacks + 1u]) << 16u) + | (static_cast(ram[callbacks + 2u]) << 8u) + | ram[callbacks + 3u]; + // OS menu selectors do not arm the +/- repeat latch. Calling their + // installed selector once avoids mistaking successful input for a retry. + if (callback != (forwards ? 0x2dcaau : 0x2dce6u)) + return false; + discardPendingPanelButtonEvents(static_cast(code)); + releasePanelEventLatch(static_cast(code)); + return runPanelCallbacksWithFirmware(callbacks); +} + +bool MasterFirmwareRuntime::runPanelCallbacksWithFirmware(uint32_t callbackTable) noexcept +{ constexpr uint32_t displayService = 0x0010b6u; constexpr uint32_t temporaryStackBottom = 0x0f0000u; constexpr uint32_t trampolineAddress = temporaryStackBottom + 0x10u; @@ -309,7 +437,6 @@ bool MasterFirmwareRuntime::navigatePageWithFirmware(bool forwards) noexcept | (static_cast(ram[address + 2u]) << 8u) | static_cast(ram[address + 3u]); }; - const auto callbackTable = forwards ? forwardsCallbacks : backwardsCallbacks; const std::array entries { readLong(callbackTable), displayService, readLong(callbackTable + 4u), displayService }; for (const auto entry : entries) @@ -346,12 +473,6 @@ bool MasterFirmwareRuntime::navigatePageWithFirmware(bool forwards) noexcept displayRefreshActive = false; std::copy(savedStack.begin(), savedStack.end(), ram.begin() + temporaryStackBottom); - // Both page keys are electrically released after the one-shot callback. - // This also recovers an emulator session left in the firmware's Help-key - // chord state by an earlier interrupted click. - ram[0x59890u] = 0u; - releasePanelEventLatch(21); - releasePanelEventLatch(23); return displayRefreshComplete; } @@ -441,6 +562,7 @@ bool MasterFirmwareRuntime::redrawPerformanceFaderWithFirmware(int faderIndex) // $18D6C is the handler that OS 1.700 installs for each of the eight // Performance faders. Invoke that genuine routine with D0 equal to the // fader index; it chooses and rasterises the displayed value itself. + const ScopedDisplayTextBuffer preserveText(*sharedMemory); std::array savedStack{}; std::copy(ram.begin() + temporaryStackBottom, ram.end(), savedStack.begin()); ram[temporaryStackPointer] = static_cast(returnSentinel >> 24u); @@ -504,7 +626,32 @@ bool MasterFirmwareRuntime::runOs1700InitialisationFileLoad() bool MasterFirmwareRuntime::interceptInstruction(M68000& activeCpu, uint32_t programCounter) noexcept { + // Both switch and ADC scanners hold their producer cursor in A5 while + // running. Appending while the CPU is paused inside a scanner lets its + // final stale cursor overwrite the host event. Deliver only at the native + // consumer entry, after the producer has committed its cursor. + if (programCounter == 0x00468eu && pendingPanelEventCount != 0) + { + size_t delivered = 0; + while (delivered < pendingPanelEventCount + && appendPanelEventToFirmwareRing(pendingPanelEvents[delivered])) + ++delivered; + for (size_t i = delivered; i < pendingPanelEventCount; ++i) + pendingPanelEvents[i - delivered] = pendingPanelEvents[i]; + pendingPanelEventCount -= delivered; + } constexpr uint32_t displayRefreshReturnSentinel = 0x0f0000u; + // The MIDI parser copies the packet to $514D0 before dispatch, but A2 + // retains its input-ring cursor just past the consumed data byte. Only + // the specifically tagged internal event bypasses external MIDI settings. + if (programCounter == 0x008ac4u) + internalPerformanceDispatch = pendingPerformanceRefresh >= 0 + && activeCpu.addressRegister(2) == pendingPerformanceMidiAddress + 1u; + if (programCounter == 0x008b58u && internalPerformanceDispatch) + { + internalPerformanceDispatch = false; + } + if (displayRefreshActive && programCounter == displayRefreshReturnSentinel) { displayRefreshComplete = true; @@ -648,10 +795,14 @@ int MasterFirmwareRuntime::runCycles(int cycles) << 8) | static_cast(sharedMemory->mainRam[ selectedPerformanceAddress + 1u]); - if (selected == pendingPerformanceRefresh) + if (pendingPerformanceSelectionHandled && selected == pendingPerformanceRefresh) { - redrawCurrentScreenWithFirmware(); - pendingPerformanceRefresh = -1; + if (redrawCurrentScreenWithFirmware()) + { + pendingPerformanceRefresh = -1; + pendingPerformanceDisplayFrozen.store(false, std::memory_order_release); + lcdPresentationRevision.fetch_add(1, std::memory_order_release); + } } } @@ -769,7 +920,10 @@ uint8_t MasterFirmwareRuntime::localByte(uint32_t address) const noexcept uint8_t MasterFirmwareRuntime::sharedProgramByte(uint32_t offset) const noexcept { - return offset < sharedMemory->program.size() ? sharedMemory->program[offset] : 0xffu; + if (offset < sharedMemory->program.size()) + return sharedMemory->program[offset]; + offset -= static_cast(sharedMemory->program.size()); + return offset < sharedMemory->work.size() ? sharedMemory->work[offset] : 0xffu; } bool MasterFirmwareRuntime::writePerformanceInstrumentByte( @@ -786,15 +940,13 @@ bool MasterFirmwareRuntime::writePerformanceInstrumentByte( const auto address = *performance + instrumentTable + static_cast(instrument) * instrumentRecordSize + offset; - if (address >= sharedMemory->program.size()) - return false; - sharedMemory->program[address] = value; + write8(sharedProgramBase + address, value); return true; } std::optional MasterFirmwareRuntime::currentPerformanceId() const noexcept { - if (!loaded || sharedMemory == nullptr) + if (!loaded || sharedMemory == nullptr || pendingPerformanceRefresh >= 0) return std::nullopt; constexpr uint32_t address = 0x54b40u; @@ -807,12 +959,11 @@ std::optional MasterFirmwareRuntime::currentPerformanceId() const noexcept std::optional MasterFirmwareRuntime::currentPerformanceInstrument() const noexcept { const auto performanceOffset = currentPerformanceRecordOffset(); - if (!performanceOffset.has_value() || sharedMemory == nullptr - || *performanceOffset + 24u >= sharedMemory->program.size()) + if (!performanceOffset.has_value() || sharedMemory == nullptr) return std::nullopt; return static_cast( - sharedMemory->program[*performanceOffset + 24u] & 0x0fu); + sharedProgramByte(*performanceOffset + 24u) & 0x0fu); } std::optional @@ -838,15 +989,44 @@ MasterFirmwareRuntime::currentPerformanceRecordOffset() const noexcept == readProgramWord(specialPerformanceIdOffset) ? specialPerformanceOffset : performanceBankOffset - + static_cast(*performanceId) * 0x200u; - if (performanceOffset + 0x200u > program.size() - || program[performanceOffset + 48u] != 0x55u) + + (static_cast(*performanceId) & 0xffu) * 0x200u; + if (sharedProgramByte(performanceOffset + 48u) != 0x55u) performanceOffset = fallbackPerformanceOffset; - if (performanceOffset + 0x200u > program.size()) - return std::nullopt; return performanceOffset; } +std::optional MasterFirmwareRuntime::currentInstrumentEditTarget() const noexcept +{ + if (!loaded || sharedMemory == nullptr) + return std::nullopt; + // OS 1.700's Instrument Edit fader handler ($14122) reads this page + // target. Performance byte 24 can change when an Instrument is disabled + // or its Performance is promoted to the edit buffer. + // Group Edit reuses that byte as a parameter selector ($14142), so it + // retains the Performance's selected Instrument for single-layer feedback. + if (sharedMemory->mainRam[0x56ed8u] != 0u) + return currentPerformanceInstrument(); + const auto target = static_cast(sharedMemory->mainRam[0x56eeau]); + return target < 8 ? std::optional(target) : std::nullopt; +} + +std::optional MasterFirmwareRuntime::currentInstrumentEditPage() const noexcept +{ + if (!loaded || sharedMemory == nullptr) + return std::nullopt; + const auto& ram = sharedMemory->mainRam; + const auto callback = (static_cast(ram[0x56bb0u]) << 24u) + | (static_cast(ram[0x56bb1u]) << 16u) + | (static_cast(ram[0x56bb2u]) << 8u) + | ram[0x56bb3u]; + // OS 1.700's Instrument renderer $13F78 uses this persistent page index. + // Re-entering Instrument Edit preserves it; the mode key does not reset + // it. Group/External Edit have different fader destinations. + if (callback != 0x13f78u || ram[0x56ee8u] != 0x49u || ram[0x56ed8u] != 0u) + return std::nullopt; + return static_cast(ram[0x56ee9u] & 3u); +} + std::optional MasterFirmwareRuntime::currentSoundRecordOffset() const noexcept { const auto instrument = currentPerformanceInstrument(); @@ -862,7 +1042,6 @@ MasterFirmwareRuntime::performanceInstrumentSoundRecordOffset( if (!loaded || sharedMemory == nullptr) return std::nullopt; - const auto& ram = sharedMemory->mainRam; const auto& program = sharedMemory->program; const auto readProgramWord = [&program](uint32_t offset) { if (offset + 1u >= program.size()) @@ -874,11 +1053,6 @@ MasterFirmwareRuntime::performanceInstrumentSoundRecordOffset( // These are the same record-resolution tables used by OS 1.700 at // $A8A2/$A8D4/$AE38/$AB7C. The firmware edits the selected Instrument's // live Sound record, which is not necessarily the $5300 startup record. - constexpr uint32_t currentPerformanceAddress = 0x54b40u; - constexpr uint32_t specialPerformanceIdOffset = 0x5184u; - constexpr uint32_t specialPerformanceOffset = 0x5600u; - constexpr uint32_t fallbackPerformanceOffset = 0x5400u; - constexpr uint32_t performanceBankOffset = 0x28000u; constexpr uint32_t soundCacheIdsOffset = 0x5186u; constexpr uint32_t soundRegistryOffset = 0x5200u; constexpr uint32_t soundCacheOffset = 0x5800u; @@ -887,17 +1061,10 @@ MasterFirmwareRuntime::performanceInstrumentSoundRecordOffset( constexpr uint32_t fallbackSoundOffset = 0x5300u; constexpr uint32_t soundRecordSize = 0x100u; - const auto performanceId = static_cast( - (static_cast(ram[currentPerformanceAddress]) << 8u) - | ram[currentPerformanceAddress + 1u]); - auto performanceOffset - = performanceId == readProgramWord(specialPerformanceIdOffset) - ? specialPerformanceOffset - : performanceBankOffset - + static_cast(performanceId) * 0x200u; - if (performanceOffset + 0x200u > program.size() - || program[performanceOffset + 48u] != 0x55u) - performanceOffset = fallbackPerformanceOffset; + const auto performance = currentPerformanceRecordOffset(); + if (!performance.has_value()) + return std::nullopt; + const auto performanceOffset = *performance; if (requestedInstrument < 0 || requestedInstrument >= 8) return std::nullopt; @@ -906,11 +1073,9 @@ MasterFirmwareRuntime::performanceInstrumentSoundRecordOffset( = instrument < 8u ? performanceOffset + 64u + instrument * 32u : performanceOffset + 64u + 256u + (instrument & 7u) * 24u; - if (instrumentOffset + 2u > program.size()) - return std::nullopt; const auto soundId = static_cast( - (static_cast(program[instrumentOffset + 1u]) << 7u - | static_cast(program[instrumentOffset])) + (static_cast(sharedProgramByte(instrumentOffset + 1u)) << 7u + | static_cast(sharedProgramByte(instrumentOffset))) & 0xffu); for (int slot = 7; slot >= 0; --slot) @@ -978,11 +1143,11 @@ bool MasterFirmwareRuntime::installCurrentPerformanceRecord( std::span performance) noexcept { const auto record = currentPerformanceRecordOffset(); - if (!record.has_value() || sharedMemory == nullptr - || *record + performance.size() > sharedMemory->program.size()) + if (!record.has_value() || sharedMemory == nullptr) return false; - std::copy(performance.begin(), performance.end(), - sharedMemory->program.begin() + *record); + for (size_t index = 0; index < performance.size(); ++index) + write8(sharedProgramBase + *record + static_cast(index), + performance[index]); return true; } @@ -1025,27 +1190,40 @@ uint8_t MasterFirmwareRuntime::lcdVideoByte(uint32_t offset) const noexcept MasterFirmwareRuntime::LcdVideoSnapshot MasterFirmwareRuntime::lcdVideoSnapshot() const noexcept { LcdVideoSnapshot snapshot{}; - for (size_t index = 0; index < lcdVideoRam.size(); ++index) - snapshot[index] = lcdVideoRam[index].load(std::memory_order_relaxed); + const auto frozen = pendingPerformanceDisplayFrozen.load(std::memory_order_acquire); + const auto& source = frozen ? pendingPerformanceDisplay : lcdVideoRam; + for (size_t index = 0; index < source.size(); ++index) + snapshot[index] = source[index].load(std::memory_order_relaxed); return snapshot; } uint8_t MasterFirmwareRuntime::lcdDisplayPage() const noexcept { - return lcdPage.load(std::memory_order_relaxed); + return pendingPerformanceDisplayFrozen.load(std::memory_order_acquire) + ? pendingPerformanceDisplayPage.load(std::memory_order_relaxed) + : lcdPage.load(std::memory_order_relaxed); } uint8_t MasterFirmwareRuntime::read8(uint32_t address) noexcept { + if (pendingPerformanceRefresh >= 0 && !pendingPerformanceSelectionHandled + && (address == 0x54b40u || address == 0x54b41u)) + // Preserve the OS's no-selection recall phase without storing an + // invalid ID in SRAM. The LCD publishes the completed frame only. + return 0xffu; + + if (internalPerformanceDispatch + && (address == sharedWorkBase + 0x8824u // MIDI program reception mode. + || address == sharedWorkBase + 0x880du // External receive channel. + || address == sharedWorkBase + 0x8806u)) // External program map. + return 0u; + if (address < sharedMemory->mainRam.size()) return sharedMemory->mainRam[address]; if (address >= sharedProgramBase && address < sharedProgramBase + sharedMemory->program.size()) return sharedMemory->program[address - sharedProgramBase]; if (address >= sharedWorkBase && address < sharedWorkBase + sharedMemory->work.size()) return sharedMemory->work[address - sharedWorkBase]; - if (address >= sharedExtensionBase - && address < sharedExtensionBase + sharedMemory->extension.size()) - return sharedMemory->extension[address - sharedExtensionBase]; if (address >= lcdVideoBase && address < lcdVideoBase + lcdVideoRam.size()) return lcdVideoRam[address - lcdVideoBase].load(std::memory_order_relaxed); @@ -1117,6 +1295,8 @@ void MasterFirmwareRuntime::write8(uint32_t address, uint8_t value) noexcept if (address < sharedMemory->mainRam.size()) { sharedMemory->mainRam[address] = value; + if (address == 0x54b41u && internalPerformanceDispatch) + pendingPerformanceSelectionHandled = true; return; } if (address >= sharedProgramBase && address < sharedProgramBase + sharedMemory->program.size()) @@ -1129,12 +1309,6 @@ void MasterFirmwareRuntime::write8(uint32_t address, uint8_t value) noexcept sharedMemory->work[address - sharedWorkBase] = value; return; } - if (address >= sharedExtensionBase - && address < sharedExtensionBase + sharedMemory->extension.size()) - { - sharedMemory->extension[address - sharedExtensionBase] = value; - return; - } if (address >= lcdVideoBase && address < lcdVideoBase + lcdVideoRam.size()) { lcdVideoRam[address - lcdVideoBase].store(value, std::memory_order_relaxed); @@ -1386,9 +1560,16 @@ void MasterFirmwareRuntime::setPerformanceFaderValue(int faderIndex, void MasterFirmwareRuntime::pushPanelEvent(uint8_t status, uint8_t data1, uint8_t data2) noexcept +{ + if (loaded && pendingPanelEventCount < pendingPanelEvents.size()) + pendingPanelEvents[pendingPanelEventCount++] = { status, data1, data2 }; +} + +bool MasterFirmwareRuntime::appendPanelEventToFirmwareRing( + const std::array& event) noexcept { if (sharedMemory == nullptr) - return; + return false; // The panel scanner writes fixed three-byte records into this genuine OS // ring. $468E consumes them as status, control number and value/delta. @@ -1413,7 +1594,7 @@ void MasterFirmwareRuntime::pushPanelEvent(uint8_t status, uint8_t data1, const auto consumer = readPointer(readPointerAddress); if (producer < ringBegin || producer >= ringEnd || consumer < ringBegin || consumer >= ringEnd) - return; + return false; const auto advance = [](uint32_t pointer) { ++pointer; @@ -1424,14 +1605,15 @@ void MasterFirmwareRuntime::pushPanelEvent(uint8_t status, uint8_t data1, { end = advance(end); if (end == consumer) - return; + return false; } - for (const auto value : { status, data1, data2 }) + for (const auto value : event) { ram[producer] = value; producer = advance(producer); } writePointer(writePointerAddress, producer); + return true; } int MasterFirmwareRuntime::discardPendingPanelButtonEvents(int buttonId) noexcept @@ -1439,6 +1621,18 @@ int MasterFirmwareRuntime::discardPendingPanelButtonEvents(int buttonId) noexcep if (sharedMemory == nullptr || buttonId < 0 || buttonId >= 128) return 0; + int queuedRemoved = 0; + size_t retainedCount = 0; + for (size_t i = 0; i < pendingPanelEventCount; ++i) + { + const auto& event = pendingPanelEvents[i]; + if (event[0] == 0x80u && event[1] == static_cast(buttonId)) + ++queuedRemoved; + else + pendingPanelEvents[retainedCount++] = event; + } + pendingPanelEventCount = retainedCount; + constexpr uint32_t readPointerAddress = 0x551f0u; constexpr uint32_t writePointerAddress = 0x551f4u; constexpr uint32_t ringBegin = 0x55840u; @@ -1465,11 +1659,11 @@ int MasterFirmwareRuntime::discardPendingPanelButtonEvents(int buttonId) noexcep const auto producer = readPointer(writePointerAddress); if (consumer < ringBegin || consumer >= ringEnd || producer < ringBegin || producer >= ringEnd) - return 0; + return queuedRemoved; std::array retained{}; auto retainedBytes = size_t{}; - auto removed = 0; + auto removed = queuedRemoved; auto cursor = consumer; while (cursor != producer) { @@ -1477,11 +1671,11 @@ int MasterFirmwareRuntime::discardPendingPanelButtonEvents(int buttonId) noexcep for (auto& byte : event) { if (cursor == producer) - return 0; // The controller ring must contain complete records. + return queuedRemoved; // The controller ring must contain complete records. byte = ram[cursor]; cursor = advance(cursor); } - if ((event[0] & 0x80u) != 0u + if (event[0] == 0x80u && event[1] == static_cast(buttonId)) { ++removed; @@ -1504,6 +1698,9 @@ int MasterFirmwareRuntime::discardPendingPanelButtonEvents(int buttonId) noexcep bool MasterFirmwareRuntime::panelEventPending(uint8_t status, uint8_t data1, uint8_t data2) const noexcept { + for (size_t i = 0; i < pendingPanelEventCount; ++i) + if (pendingPanelEvents[i] == std::array { status, data1, data2 }) + return true; if (sharedMemory == nullptr) return false; constexpr uint32_t readPointerAddress = 0x551f0u; @@ -1550,6 +1747,18 @@ bool MasterFirmwareRuntime::releasePanelEventLatch(int buttonId) noexcept if (sharedMemory == nullptr || buttonId < 0 || buttonId >= 87) return false; + // OK/CANCEL share a chord latch and execute on release ($28416-$28474). + // A missed scanner release can leave the panic state at $FF indefinitely. + // Once both physical contacts are up, clear only that stale held state + // before a new explicit response transaction. + if ((buttonId == 70 || buttonId == 71) + && !panelButtonRequestedDown(70) && !panelButtonRequestedDown(71) + && !panelButtonPressed(70) && !panelButtonPressed(71)) + { + sharedMemory->mainRam[0x58feau] = 0; + return true; + } + // OS 1.700's event dispatcher maps panel serials through $2850E and keeps // the active auto-repeat action at $58FE4. Mirror its release branch at // $28362 after a host-generated click, so the next discrete click cannot diff --git a/Source/Firmware/MasterFirmwareRuntime.h b/Source/Firmware/MasterFirmwareRuntime.h index 3f4fc1e..5ccdee2 100644 --- a/Source/Firmware/MasterFirmwareRuntime.h +++ b/Source/Firmware/MasterFirmwareRuntime.h @@ -35,7 +35,11 @@ class MasterFirmwareRuntime final : private M68000Bus } bool installEditRecords(std::span sound, std::span performance) noexcept; + bool installPerformanceBank(std::span performances) noexcept; + bool installSoundBank(std::span sounds) noexcept; bool requestPerformanceSelection(int programIndex) noexcept; + // Audio-thread preparation before the native keypad scanner runs. + void prepareNumericPanelInput() noexcept; bool refreshCurrentScreenFromFirmware() { return loaded && redrawCurrentScreenWithFirmware(); @@ -72,6 +76,7 @@ class MasterFirmwareRuntime final : private M68000Bus uint8_t data2) const noexcept; bool releasePanelEventLatch(int buttonId) noexcept; bool navigatePageWithFirmware(bool forwards) noexcept; + bool stepDiskMenuWithFirmware(bool forwards) noexcept; bool stepStoreDestinationWithFirmware(bool forwards) noexcept; [[nodiscard]] bool panelActionBitActive(int buttonId) const noexcept; bool releasePanelActionBit(int buttonId) noexcept; @@ -117,9 +122,18 @@ class MasterFirmwareRuntime final : private M68000Bus [[nodiscard]] uint8_t ioByte(uint32_t address) const noexcept; [[nodiscard]] uint8_t localByte(uint32_t address) const noexcept; [[nodiscard]] uint8_t sharedProgramByte(uint32_t offset) const noexcept; + // A queued recall has no committed ID yet; its live LCD frame stays valid. + // Audio-thread recall scheduling: keep each parser transaction intact + // until its completed display has been published. + [[nodiscard]] bool performanceSelectionPending() const noexcept + { + return pendingPerformanceRefresh >= 0; + } [[nodiscard]] std::optional currentPerformanceId() const noexcept; [[nodiscard]] std::optional currentPerformanceRecordOffset() const noexcept; [[nodiscard]] std::optional currentPerformanceInstrument() const noexcept; + [[nodiscard]] std::optional currentInstrumentEditTarget() const noexcept; + [[nodiscard]] std::optional currentInstrumentEditPage() const noexcept; [[nodiscard]] std::optional currentSoundRecordOffset() const noexcept; [[nodiscard]] std::optional performanceInstrumentSoundRecordOffset( int instrument) const noexcept; @@ -140,6 +154,12 @@ class MasterFirmwareRuntime final : private M68000Bus [[nodiscard]] bool panelButtonRequestedDown(int buttonId) const noexcept; [[nodiscard]] uint8_t lcdVideoByte(uint32_t offset) const noexcept; [[nodiscard]] uint8_t lcdDisplayPage() const noexcept; + // Changes when the visible source switches between a held recall frame + // and live VRAM, even if that switch performs no additional VRAM write. + [[nodiscard]] uint64_t lcdDisplayRevision() const noexcept + { + return lcdPresentationRevision.load(std::memory_order_acquire); + } [[nodiscard]] uint64_t lcdVideoWriteCount() const noexcept { return lcdWrites.load(std::memory_order_relaxed); @@ -161,13 +181,14 @@ class MasterFirmwareRuntime final : private M68000Bus static constexpr uint32_t sharedProgramSize = SharedFirmwareMemory::programSize; static constexpr uint32_t sharedWorkBase = 0x140000; static constexpr uint32_t sharedWorkSize = SharedFirmwareMemory::workSize; - static constexpr uint32_t sharedExtensionBase = 0x180000; static constexpr uint32_t lcdVideoBase = 0xa00000; static constexpr uint32_t lcdVideoWindowSize = 0x4000; using LcdVideoSnapshot = std::array; [[nodiscard]] LcdVideoSnapshot lcdVideoSnapshot() const noexcept; private: + bool runPanelCallbacksWithFirmware(uint32_t callbackTable) noexcept; + bool appendPanelEventToFirmwareRing(const std::array& event) noexcept; struct VirtualInitialisationFile { bool open = false; @@ -200,8 +221,9 @@ class MasterFirmwareRuntime final : private M68000Bus void write8(uint32_t address, uint8_t value) noexcept override; [[nodiscard]] bool usesInstructionInterception() const noexcept override { - return initialisationLoaderActive || startupContinuationActive - || displayRefreshActive; + return pendingPanelEventCount != 0 || initialisationLoaderActive || startupContinuationActive + || displayRefreshActive || pendingPerformanceRefresh >= 0 + || internalPerformanceDispatch; } bool interceptInstruction(M68000& activeCpu, uint32_t programCounter) noexcept override; bool redrawCurrentScreenWithFirmware(); @@ -214,7 +236,10 @@ class MasterFirmwareRuntime final : private M68000Bus SharedFirmwareMemory ownedSharedMemory; SharedFirmwareMemory* sharedMemory = &ownedSharedMemory; std::array, lcdVideoWindowSize> lcdVideoRam{}; + std::atomic lcdPresentationRevision{ 0 }; std::array, 8> panelSwitchWords{}; + std::array, 256> pendingPanelEvents {}; + size_t pendingPanelEventCount = 0; std::array, 128> panelReleaseCycles{}; std::array, 128> panelReleasePending{}; std::array, 128> panelButtonRequested{}; @@ -245,6 +270,12 @@ class MasterFirmwareRuntime final : private M68000Bus bool displayRefreshActive = false; bool displayRefreshComplete = false; int pendingPerformanceRefresh = -1; + std::array, lcdVideoWindowSize> pendingPerformanceDisplay{}; + std::atomic pendingPerformanceDisplayPage { 0 }; + std::atomic pendingPerformanceDisplayFrozen { false }; + uint32_t pendingPerformanceMidiAddress = 0; + bool internalPerformanceDispatch = false; + bool pendingPerformanceSelectionHandled = false; bool voiceLoaderReached = false; bool customInitialisationRecords = false; bool voiceBoardHandoffComplete = false; diff --git a/Source/Firmware/SharedFirmwareMemory.h b/Source/Firmware/SharedFirmwareMemory.h index 561c2b1..a887461 100644 --- a/Source/Firmware/SharedFirmwareMemory.h +++ b/Source/Firmware/SharedFirmwareMemory.h @@ -10,7 +10,9 @@ struct SharedFirmwareMemory static constexpr uint32_t mainRamSize = 0x100000; static constexpr uint32_t programSize = 0x40000; static constexpr uint32_t workSize = 0x40000; - static constexpr uint32_t extensionSize = 0x80000; + // The shared SRAM is 512 KB (0x100000-0x17FFFF = program + work); nothing + // is decoded above it, so accesses there count as unmapped. + static constexpr uint32_t extensionSize = 0; void clear() noexcept { diff --git a/Source/Firmware/VoiceFirmwareRuntime.cpp b/Source/Firmware/VoiceFirmwareRuntime.cpp index b50b57e..a450dfd 100644 --- a/Source/Firmware/VoiceFirmwareRuntime.cpp +++ b/Source/Firmware/VoiceFirmwareRuntime.cpp @@ -25,7 +25,8 @@ bool VoiceFirmwareRuntime::loadAndReset(const juce::MemoryBlock& voiceImage) if (sharedMemory == &ownedSharedMemory) sharedMemory->clear(); asicRegisters.fill(0); - waveformRam.fill(0); + for (auto& ram : waveformRam) + ram.fill(0); for (auto& bank : cvRegisters) bank.fill(0); controlLatch = 0; @@ -156,17 +157,18 @@ uint8_t VoiceFirmwareRuntime::read8(uint32_t address) noexcept { if (address < localRam.size()) return localRam[address]; - if (address < sharedMemory->mainRam.size()) - return sharedMemory->mainRam[address]; + // The board has only its private 64 KB below the shared SRAM; master DRAM + // is on the other bus. if (address >= sharedProgramBase && address < sharedProgramBase + sharedMemory->program.size()) return sharedMemory->program[address - sharedProgramBase]; if (address >= sharedWorkBase && address < sharedWorkBase + sharedMemory->work.size()) return sharedMemory->work[address - sharedWorkBase]; - if (address >= sharedExtensionBase - && address < sharedExtensionBase + sharedMemory->extension.size()) - return sharedMemory->extension[address - sharedExtensionBase]; - if (address >= waveformRamBase && address < waveformRamBase + waveformRam.size()) - return waveformRam[address - waveformRamBase]; + if (address >= waveRamABase && address < waveRamABase + waveRamSize) + return waveformRam[0][address - waveRamABase]; + if (address >= waveRamBBase && address < waveRamBBase + waveRamSize) + return waveformRam[1][address - waveRamBBase]; + if (address >= waveRamBothBase && address < waveRamBothBase + waveRamSize) + return waveformRam[0][address - waveRamBothBase]; if (address == boardControlAddress) return boardStatus; if (address >= asicBase && address < asicBase + asicRegisters.size()) @@ -188,11 +190,6 @@ void VoiceFirmwareRuntime::write8(uint32_t address, uint8_t value) noexcept localRam[address] = value; return; } - if (address < sharedMemory->mainRam.size()) - { - sharedMemory->mainRam[address] = value; - return; - } if (address >= sharedProgramBase && address < sharedProgramBase + sharedMemory->program.size()) { sharedMemory->program[address - sharedProgramBase] = value; @@ -203,20 +200,22 @@ void VoiceFirmwareRuntime::write8(uint32_t address, uint8_t value) noexcept sharedMemory->work[address - sharedWorkBase] = value; return; } - if (address >= sharedExtensionBase - && address < sharedExtensionBase + sharedMemory->extension.size()) + // Wave-RAM stores are not queued: a bank load is up to 32K bytes, which + // would crowd the 64K ASIC/CV write queue, and the engine ignores them. + if (address >= waveRamABase && address < waveRamABase + waveRamSize) { - sharedMemory->extension[address - sharedExtensionBase] = value; + waveformRam[0][address - waveRamABase] = value; return; } - if (address >= waveformRamBase && address < waveformRamBase + waveformRam.size()) + if (address >= waveRamBBase && address < waveRamBBase + waveRamSize) { - waveformRam[address - waveformRamBase] = value; - if (hardwareWrites.size() < 65536) - hardwareWrites.push_back( - { emulatedCycles - + static_cast(juce::jmax(0, cpu.currentExecutionCycleOffset())), - address, value }); + waveformRam[1][address - waveRamBBase] = value; + return; + } + if (address >= waveRamBothBase && address < waveRamBothBase + waveRamSize) + { + waveformRam[0][address - waveRamBothBase] = value; + waveformRam[1][address - waveRamBothBase] = value; return; } if (address == boardControlAddress) @@ -227,30 +226,29 @@ void VoiceFirmwareRuntime::write8(uint32_t address, uint8_t value) noexcept if (address >= asicBase && address < asicBase + asicRegisters.size()) { asicRegisters[address - asicBase] = value; - if (hardwareWrites.size() < 65536) - hardwareWrites.push_back( - { emulatedCycles - + static_cast(juce::jmax(0, cpu.currentExecutionCycleOffset())), - address, value }); + queueHardwareWrite(address, value); } if (address >= cvBankABase && address < cvBankABase + cvWindowSize) { cvRegisters[0][address - cvBankABase] = value; - if (hardwareWrites.size() < 65536) - hardwareWrites.push_back( - { emulatedCycles - + static_cast(juce::jmax(0, cpu.currentExecutionCycleOffset())), - address, value }); + queueHardwareWrite(address, value); } if (address >= cvBankBBase && address < cvBankBBase + cvWindowSize) { cvRegisters[1][address - cvBankBBase] = value; - if (hardwareWrites.size() < 65536) - hardwareWrites.push_back( - { emulatedCycles - + static_cast(juce::jmax(0, cpu.currentExecutionCycleOffset())), - address, value }); + queueHardwareWrite(address, value); } + if (address >= routingLatchBase && address < routingLatchBase + routingLatchWindowSize) + queueHardwareWrite(address, value); +} + +void VoiceFirmwareRuntime::queueHardwareWrite(uint32_t address, uint8_t value) noexcept +{ + if (hardwareWrites.size() < 65536) + hardwareWrites.push_back( + { emulatedCycles + + static_cast(juce::jmax(0, cpu.currentExecutionCycleOffset())), + address, value }); } uint32_t VoiceFirmwareRuntime::bigEndian32(const uint8_t* bytes) noexcept diff --git a/Source/Firmware/VoiceFirmwareRuntime.h b/Source/Firmware/VoiceFirmwareRuntime.h index f1b0734..7ca5570 100644 --- a/Source/Firmware/VoiceFirmwareRuntime.h +++ b/Source/Firmware/VoiceFirmwareRuntime.h @@ -44,6 +44,12 @@ class VoiceFirmwareRuntime final : private M68000Bus [[nodiscard]] uint16_t asicWord(uint32_t offset) const noexcept; [[nodiscard]] uint16_t cvWord(int bank, uint32_t offset) const noexcept; [[nodiscard]] uint8_t sharedByte(uint32_t offset) const noexcept; + [[nodiscard]] uint8_t waveRamByte(int ram, uint32_t offset) const noexcept + { + return (ram == 0 || ram == 1) && offset < waveRamSize + ? waveformRam[static_cast(ram)][offset] + : 0xffu; + } [[nodiscard]] uint64_t emulatedCycleCount() const noexcept { return emulatedCycles; } [[nodiscard]] uint64_t controlTickCount() const noexcept { return controlTicks; } [[nodiscard]] int getBoardIndex() const noexcept { return boardIndex; } @@ -53,13 +59,21 @@ class VoiceFirmwareRuntime final : private M68000Bus static constexpr uint32_t sharedProgramBase = 0x100000; static constexpr uint32_t sharedProgramSize = SharedFirmwareMemory::programSize; static constexpr uint32_t sharedWorkBase = 0x140000; - static constexpr uint32_t sharedExtensionBase = 0x180000; - static constexpr uint32_t waveformRamBase = 0x600000; - static constexpr uint32_t waveformRamSize = 0x20000; + // Two 64 KB wave RAMs (A, B) with a write-both alias. WDV.SYS stores 8-bit + // samples on odd bytes at 0x060001 + (bank << 13); the alias is read back + // as RAM A (alias read behaviour is not established by the firmware). + static constexpr uint32_t waveRamABase = 0x040000; + static constexpr uint32_t waveRamBBase = 0x050000; + static constexpr uint32_t waveRamBothBase = 0x060000; + static constexpr uint32_t waveRamSize = 0x10000; static constexpr uint32_t cvBankABase = 0x880000; static constexpr uint32_t cvBankBBase = 0x8a0000; static constexpr uint32_t cvWindowSize = 0x10000; static constexpr uint32_t boardControlAddress = 0x800001; + // Write-only output routing latch: WDV 0xCBA writes 8 bytes (4 words) + // here per voice. Queued with the ASIC/CV writes; the engine ignores it. + static constexpr uint32_t routingLatchBase = 0x8c0000; + static constexpr uint32_t routingLatchWindowSize = 0x10000; // Firmware-visible black-box register window. The name describes the // physical target only; register storage does not model chip internals. static constexpr uint32_t asicBase = 0x980000; @@ -69,6 +83,7 @@ class VoiceFirmwareRuntime final : private M68000Bus private: [[nodiscard]] uint8_t read8(uint32_t address) noexcept override; void write8(uint32_t address, uint8_t value) noexcept override; + void queueHardwareWrite(uint32_t address, uint8_t value) noexcept; [[nodiscard]] static uint32_t bigEndian32(const uint8_t* bytes) noexcept; M68000 cpu; @@ -76,7 +91,7 @@ class VoiceFirmwareRuntime final : private M68000Bus SharedFirmwareMemory ownedSharedMemory; SharedFirmwareMemory* sharedMemory = &ownedSharedMemory; std::array asicRegisters{}; - std::array waveformRam{}; + std::array, 2> waveformRam{}; std::array, 2> cvRegisters{}; uint8_t controlLatch = 0; int boardIndex = 0; diff --git a/Source/PanelWiring.h b/Source/PanelWiring.h index e378bb5..3f4e643 100644 --- a/Source/PanelWiring.h +++ b/Source/PanelWiring.h @@ -16,6 +16,7 @@ struct Switch float y; int diagnosticCode; int matrixIndex = -1; + const char* name = ""; }; // OS 1.700 applies this private dispatch permutation after the panel scanner @@ -41,15 +42,15 @@ constexpr int diagnosticCodeForMatrixIndex(int matrixIndex) noexcept return matrixIndex >= 0 && matrixIndex < 128 ? matrixIndex : -1; } -constexpr Switch button(float x, float y, int diagnosticCode) noexcept +constexpr Switch button(float x, float y, int diagnosticCode, const char* name = "") noexcept { return { x, y, diagnosticCode, - matrixIndexForDiagnosticCode(diagnosticCode) }; + matrixIndexForDiagnosticCode(diagnosticCode), name }; } -constexpr Switch specialButton(float x, float y, int matrixIndex) noexcept +constexpr Switch specialButton(float x, float y, int matrixIndex, const char* name = "") noexcept { - return { x, y, -1, matrixIndex }; + return { x, y, -1, matrixIndex, name }; } constexpr int physicalMatrixIndex(const Switch& item) noexcept @@ -60,81 +61,81 @@ constexpr int physicalMatrixIndex(const Switch& item) noexcept } inline constexpr std::array visibleSwitches { - button(98.0f, 160.0f, 0), // Oscillator 1 Octave - button(39.0f, 358.0f, 16), // Oscillator Link - button(98.0f, 358.0f, 1), // Oscillator 2 Octave - button(392.0f, 358.0f, 15), // Wave Link - button(39.0f, 555.0f, 2), // LFO Select - button(98.0f, 555.0f, 5), // LFO Shape - button(154.0f, 551.0f, 7), // LFO Trigger - button(392.0f, 555.0f, 14), // Wave-envelope Select - button(786.0f, 555.0f, 20), // Knob Mode - - button(292.173f, 120.174f, 8), // Oscillator 1 Edit - button(706.173f, 120.174f, 17), // Wave 1 Edit - button(785.173f, 220.174f, 86), // Oscillator Mixer Edit - button(292.173f, 318.174f, 9), // Oscillator 2 Edit - button(706.173f, 318.174f, 18), // Wave 2 Edit - button(292.173f, 514.174f, 10), // LFO Edit - button(706.173f, 514.174f, 19), // Wave/free-envelope Edit - - Switch { 903.0f, 139.0f, 24 }, // Mute - Switch { 959.0f, 139.0f, 78 }, // Solo - Switch { 1276.5f, 139.0f, 31 }, // Group Edit - Switch { 903.0f, 199.0f, 22 }, // Instrument 1 - Switch { 959.0f, 199.0f, 25 }, // Instrument 2 - Switch { 1014.0f, 199.0f, 26 }, // Instrument 3 - Switch { 1070.0f, 199.0f, 27 }, // Instrument 4 - Switch { 1125.0f, 199.0f, 79 }, // Instrument 5 - Switch { 1181.0f, 199.0f, 28 }, // Instrument 6 - Switch { 1236.0f, 199.0f, 29 }, // Instrument 7 - Switch { 1292.0f, 199.0f, 30 }, // Instrument 8 - Switch { 903.0f, 553.0f, 21 }, // Page left - Switch { 942.0f, 553.0f, 23 }, // Page right - specialButton(1078.0f, 553.0f, 71), // Cancel / ESC - specialButton(1117.0f, 553.0f, 70), // OK / Return - Switch { 1253.0f, 553.0f, 69 }, // Minus - Switch { 1292.0f, 553.0f, 72 }, // Plus - - Switch { 1402.5f, 139.0f, 38 }, // Quick Edit - Switch { 1402.5f, 198.0f, 33 }, // Global Edit - Switch { 1402.5f, 257.0f, 35 }, // Sequencer - Switch { 1402.5f, 316.0f, 34 }, // Option - Switch { 1402.5f, 376.0f, 32 }, // Wave Edit - Switch { 1402.5f, 435.0f, 37 }, // External Edit - Switch { 1402.5f, 494.0f, 36 }, // Instrument Edit - Switch { 1402.5f, 553.0f, 39 }, // Performance - - Switch { 1484.0f, 237.0f, 43 }, // Filter Type - Switch { 1543.0f, 237.0f, 75 }, // Filter Select - Switch { 1859.173f, 195.174f, 60 }, // Filter Edit - Switch { 2152.173f, 195.174f, 67 }, // Amplifier Edit - Switch { 1800.173f, 354.174f, 59 }, // Filter-envelope Edit - Switch { 2152.173f, 354.174f, 66 }, // Amplifier-envelope Edit - Switch { 1956.173f, 509.174f, 61 }, // Panning Edit - - Switch { 1484.0f, 435.0f, 42 }, // Copy - Switch { 1484.0f, 494.0f, 41 }, // Compare / Undo - Switch { 1484.0f, 553.0f, 40 }, // Recall / Init - Switch { 1543.0f, 553.0f, 44 }, // Bank - Switch { 1602.0f, 553.0f, 45 }, // 1__ - Switch { 1680.0f, 553.0f, 47 }, // Hold - Switch { 1602.0f, 435.0f, 48 }, // 7 - Switch { 1641.0f, 435.0f, 51 }, // 8 - Switch { 1680.0f, 435.0f, 54 }, // 9 - Switch { 1602.0f, 475.0f, 53 }, // 4 - Switch { 1641.0f, 475.0f, 50 }, // 5 - Switch { 1680.0f, 475.0f, 49 }, // 6 - Switch { 1602.0f, 513.0f, 46 }, // 1 - Switch { 1641.0f, 513.0f, 56 }, // 2 - Switch { 1680.0f, 513.0f, 55 }, // 3 - Switch { 1641.0f, 553.0f, 52 }, // 0 - Switch { 1788.0f, 492.0f, 58 }, // Disk - Switch { 1789.5f, 553.0f, 57 }, // Store - Switch { 2103.0f, 473.0f, 62 }, // Aux - Switch { 2162.0f, 473.0f, 64 }, // Control Mixer / Comparator - Switch { 2103.0f, 551.0f, 65 }, // Control Delay / S&H - Switch { 2162.0f, 551.0f, 63 }, // Control Shaper / Ramp + button(98.0f, 160.0f, 0, "Oscillator 1 Octave"), + button(39.0f, 358.0f, 16, "Oscillator Link"), + button(98.0f, 358.0f, 1, "Oscillator 2 Octave"), + button(392.0f, 358.0f, 15, "Wave Link"), + button(39.0f, 555.0f, 2, "LFO Select"), + button(98.0f, 555.0f, 5, "LFO Shape"), + button(154.0f, 551.0f, 7, "LFO Trigger"), + button(392.0f, 555.0f, 14, "Wave Envelope Select"), + button(786.0f, 555.0f, 20, "Knob Mode"), + + button(292.173f, 120.174f, 8, "Oscillator 1 Edit"), + button(706.173f, 120.174f, 17, "Wave 1 Edit"), + button(785.173f, 220.174f, 86, "Oscillator Mixer Edit"), + button(292.173f, 318.174f, 9, "Oscillator 2 Edit"), + button(706.173f, 318.174f, 18, "Wave 2 Edit"), + button(292.173f, 514.174f, 10, "LFO Edit"), + button(706.173f, 514.174f, 19, "Wave / Free Envelope Edit"), + + Switch { 903.0f, 139.0f, 24, -1, "Mute" }, + Switch { 959.0f, 139.0f, 78, -1, "Solo" }, + Switch { 1276.5f, 139.0f, 31, -1, "Group Edit" }, + Switch { 903.0f, 199.0f, 22, -1, "Instrument 1" }, + Switch { 959.0f, 199.0f, 25, -1, "Instrument 2" }, + Switch { 1014.0f, 199.0f, 26, -1, "Instrument 3" }, + Switch { 1070.0f, 199.0f, 27, -1, "Instrument 4" }, + Switch { 1125.0f, 199.0f, 79, -1, "Instrument 5" }, + Switch { 1181.0f, 199.0f, 28, -1, "Instrument 6" }, + Switch { 1236.0f, 199.0f, 29, -1, "Instrument 7" }, + Switch { 1292.0f, 199.0f, 30, -1, "Instrument 8" }, + Switch { 903.0f, 553.0f, 21, -1, "Page Left" }, + Switch { 942.0f, 553.0f, 23, -1, "Page Right" }, + specialButton(1078.0f, 553.0f, 71, "Cancel"), + specialButton(1117.0f, 553.0f, 70, "OK"), + Switch { 1253.0f, 553.0f, 69, -1, "Minus" }, + Switch { 1292.0f, 553.0f, 72, -1, "Plus" }, + + Switch { 1402.5f, 139.0f, 38, -1, "Quick Edit" }, + Switch { 1402.5f, 198.0f, 33, -1, "Global Edit" }, + Switch { 1402.5f, 257.0f, 35, -1, "Sequencer" }, + Switch { 1402.5f, 316.0f, 34, -1, "Option" }, + Switch { 1402.5f, 376.0f, 32, -1, "Wave Edit" }, + Switch { 1402.5f, 435.0f, 37, -1, "External Edit" }, + Switch { 1402.5f, 494.0f, 36, -1, "Instrument Edit" }, + Switch { 1402.5f, 553.0f, 39, -1, "Performance" }, + + Switch { 1484.0f, 237.0f, 43, -1, "Filter Type" }, + Switch { 1543.0f, 237.0f, 75, -1, "Filter Select" }, + Switch { 1859.173f, 195.174f, 60, -1, "Filter Edit" }, + Switch { 2152.173f, 195.174f, 67, -1, "Amplifier Edit" }, + Switch { 1800.173f, 354.174f, 59, -1, "Filter Envelope Edit" }, + Switch { 2152.173f, 354.174f, 66, -1, "Amplifier Envelope Edit" }, + Switch { 1956.173f, 509.174f, 61, -1, "Panning Edit" }, + + Switch { 1484.0f, 435.0f, 42, -1, "Copy" }, + Switch { 1484.0f, 494.0f, 41, -1, "Compare / Undo" }, + Switch { 1484.0f, 553.0f, 40, -1, "Recall / Init" }, + Switch { 1543.0f, 553.0f, 44, -1, "Bank" }, + Switch { 1602.0f, 553.0f, 45, -1, "1__" }, + Switch { 1680.0f, 553.0f, 47, -1, "Hold" }, + Switch { 1602.0f, 435.0f, 48, -1, "7" }, + Switch { 1641.0f, 435.0f, 51, -1, "8" }, + Switch { 1680.0f, 435.0f, 54, -1, "9" }, + Switch { 1602.0f, 475.0f, 53, -1, "4" }, + Switch { 1641.0f, 475.0f, 50, -1, "5" }, + Switch { 1680.0f, 475.0f, 49, -1, "6" }, + Switch { 1602.0f, 513.0f, 46, -1, "1" }, + Switch { 1641.0f, 513.0f, 56, -1, "2" }, + Switch { 1680.0f, 513.0f, 55, -1, "3" }, + Switch { 1641.0f, 553.0f, 52, -1, "0" }, + Switch { 1788.0f, 492.0f, 58, -1, "Disk" }, + Switch { 1789.5f, 553.0f, 57, -1, "Store" }, + Switch { 2103.0f, 473.0f, 62, -1, "Aux" }, + Switch { 2162.0f, 473.0f, 64, -1, "Control Mixer / Comparator" }, + Switch { 2103.0f, 551.0f, 65, -1, "Control Delay / S&H" }, + Switch { 2162.0f, 551.0f, 63, -1, "Control Shaper / Ramp" }, }; inline const Switch* switchAt(float x, float y, float tolerance = 1.5f) noexcept @@ -150,12 +151,12 @@ inline const Switch* switchAt(float x, float y, float tolerance = 1.5f) noexcept // offset-local coordinate system. Their serials are the genuine BUTTON TEST // values from OS 1.700. inline constexpr std::array keyboardPanelSwitches { - button(110.0f, 766.5f, 3), // Button 1 - button(170.0f, 766.5f, 4), // Button 2 - button(228.0f, 751.0f, 6), // Glide On/Off - button(366.173f, 753.174f, 11),// Glide Edit - button(288.0f, 849.0f, 12), // Octave Up - button(288.0f, 927.0f, 73), // Octave Down + button(110.0f, 766.5f, 3, "Button 1"), + button(170.0f, 766.5f, 4, "Button 2"), + button(228.0f, 751.0f, 6, "Glide On/Off"), + button(366.173f, 753.174f, 11, "Glide Edit"), + button(288.0f, 849.0f, 12, "Octave Up"), + button(288.0f, 927.0f, 73, "Octave Down"), }; inline const Switch* keyboardPanelSwitchAt(float x, float y, @@ -172,20 +173,21 @@ struct KeyboardControllerButton float x; float y; uint8_t asciiCode; + const char* name; }; // These controls live on the Wave keyboard assembly rather than the upper // front-panel scanner. The values are the ASCII command bytes decoded by the // genuine OS 1.700 keyboard dispatcher. inline constexpr std::array keyboardControllerButtons { - KeyboardControllerButton { 982.0f, 678.0f, 0x27u }, // Rewind - KeyboardControllerButton { 1021.0f, 678.0f, 0x0du }, // Fast forward - KeyboardControllerButton { 1079.5f, 678.0f, 0x4cu }, // Stop - KeyboardControllerButton { 1145.5f, 678.0f, 0x4du }, // Play - KeyboardControllerButton { 1196.0f, 678.0f, 0x50u }, // Locator In - KeyboardControllerButton { 1261.0f, 678.0f, 0x54u }, // Record - KeyboardControllerButton { 1300.0f, 678.0f, 0x51u }, // Locator Out - KeyboardControllerButton { 1372.0f, 678.0f, 0x52u } // Shift + KeyboardControllerButton { 982.0f, 678.0f, 0x27u, "Rewind" }, + KeyboardControllerButton { 1021.0f, 678.0f, 0x0du, "Fast Forward" }, + KeyboardControllerButton { 1079.5f, 678.0f, 0x4cu, "Stop" }, + KeyboardControllerButton { 1145.5f, 678.0f, 0x4du, "Play" }, + KeyboardControllerButton { 1196.0f, 678.0f, 0x50u, "Locator In" }, + KeyboardControllerButton { 1261.0f, 678.0f, 0x54u, "Record" }, + KeyboardControllerButton { 1300.0f, 678.0f, 0x51u, "Locator Out" }, + KeyboardControllerButton { 1372.0f, 678.0f, 0x52u, "Shift" } }; inline const KeyboardControllerButton* keyboardControllerButtonAt( @@ -197,6 +199,27 @@ inline const KeyboardControllerButton* keyboardControllerButtonAt( return nullptr; } +// Display names share the same physical IDs as the original and compact +// layouts, so alternate artwork cannot change a button's tooltip identity. +inline const char* buttonName(int matrixIndex) noexcept +{ + for (const auto& item : visibleSwitches) + if (physicalMatrixIndex(item) == matrixIndex) + return item.name; + for (const auto& item : keyboardPanelSwitches) + if (physicalMatrixIndex(item) == matrixIndex) + return item.name; + return ""; +} + +inline const char* keyboardControllerButtonName(int asciiCode) noexcept +{ + for (const auto& item : keyboardControllerButtons) + if (item.asciiCode == asciiCode) + return item.name; + return ""; +} + struct Pot { const char* parameterId; diff --git a/Source/PluginEditor.cpp b/Source/PluginEditor.cpp index a63bf77..1dad0bc 100644 --- a/Source/PluginEditor.cpp +++ b/Source/PluginEditor.cpp @@ -1,9 +1,11 @@ -// Modified 2026-09-27 by Bronisław Hońca: resizable/zoomable editor window and -// compact layouts without the on-screen keyboard. Licensed under GPL-3.0-or-later. +// Modified 2026-10-11 by Bronisław Hońca (bronislawhonca.pl): the editor opens +// at a size that fits the screen, remembers zoom and keyboard visibility, and +// offers Fit to Screen. Licensed under GPL-3.0-or-later. #include "PluginEditor.h" #include "PanelWiring.h" +#include "UI/CompactPanelLayout.h" #include @@ -16,22 +18,11 @@ namespace { constexpr auto designWidth = 2338.0f; constexpr auto designHeight = 1042.0f; +constexpr auto panelOnlyHeight = 619.0f; constexpr auto panelHorizontalOffset = 66.0f; -constexpr auto minimumEditorScale = 0.3f; +constexpr auto minimumEditorScale = 0.4f; constexpr auto maximumEditorScale = 2.0f; constexpr auto defaultEditorScale = 1.0f; -// Visible design heights for the optional compact layouts. The panel artwork -// keeps its original design coordinates; compact layouts only crop the bottom. -constexpr auto noKeyboardDesignHeight = 812.0f; -constexpr auto panelOnlyDesignHeight = 622.0f; -constexpr auto layoutFullMenuItem = 0x4801; -constexpr auto layoutNoKeyboardMenuItem = 0x4802; -constexpr auto layoutPanelOnlyMenuItem = 0x4803; -constexpr auto fitToScreenMenuItem = 0x4804; -constexpr auto zoomInMenuItem = 0x4805; -constexpr auto zoomOutMenuItem = 0x4806; -constexpr auto zoomMenuItemBase = 0x4810; -constexpr std::array zoomPercentages { 35, 40, 50, 60, 70, 80, 90, 100 }; constexpr auto keyboardLeft = 446.0f; constexpr auto keyboardTop = 764.0f; constexpr auto keyboardWidth = 1671.0f; @@ -59,6 +50,25 @@ constexpr auto ejectDiskMenuItem = 0x4703; constexpr auto createDiskFromSetMenuItem = 0x4704; constexpr auto createBlankDiskMenuItem = 0x4705; constexpr auto saveDiskAsMenuItem = 0x4706; +constexpr auto zoomInMenuItem = 0x4708; +constexpr auto zoomOutMenuItem = 0x4709; +constexpr auto resetZoomMenuItem = 0x470a; +constexpr auto toggleKeyboardMenuItem = 0x470b; +constexpr auto loadPanelSkinMenuItem = 0x470c; +constexpr auto defaultPanelSkinMenuItem = 0x470d; +constexpr auto reloadDiskBankMenuItem = 0x470e; +constexpr auto createDiskFromWavetableMenuItem = 0x470f; +constexpr auto compactPanelSkinMenuItem = 0x4710; +constexpr auto fitToScreenMenuItem = 0x4711; + +const wave::ui::compact::Knob* compactKnobAt(juce::Point originalPanelCentre) +{ + for (const auto& knob : wave::ui::compact::knobs) + if (std::abs(knob.originalX - originalPanelCentre.x - panelHorizontalOffset) < 0.1f + && std::abs(knob.originalY - originalPanelCentre.y) < 0.1f) + return &knob; + return nullptr; +} bool hitCircle(juce::Point point, float x, float y) noexcept { @@ -260,9 +270,12 @@ class WaveEmulationAudioProcessorEditor::ParameterKnob final encoderPixelsPerStep = juce::jmax(1.0f, pixels); } - void setPhysicalPotCallback(std::function callback) + void setPhysicalPotCallbacks( + std::function callback, + std::function(const juce::String&)> positionCallback) { physicalPotCallback = std::move(callback); + physicalPotPositionCallback = std::move(positionCallback); } void synchronisePhysicalPosition(float normalised) noexcept @@ -285,6 +298,11 @@ class WaveEmulationAudioProcessorEditor::ParameterKnob final if (!endlessRelative) { + // Firmware boot/recall can reset the ADC before the next editor + // timer tick. Begin this gesture from the current physical value. + if (physicalPotPositionCallback != nullptr) + if (const auto physical = physicalPotPositionCallback(boundParameterId)) + synchronisePhysicalPosition(*physical); boundedDragging = true; lastDragOffsetY = 0; attachedParameter->beginChangeGesture(); @@ -420,6 +438,7 @@ class WaveEmulationAudioProcessorEditor::ParameterKnob final std::unique_ptr attachment; std::function encoderTurnCallback; std::function physicalPotCallback; + std::function(const juce::String&)> physicalPotPositionCallback; juce::RangedAudioParameter* attachedParameter = nullptr; juce::String boundParameterId; int lastDragOffsetY = 0; @@ -475,7 +494,7 @@ class WaveEmulationAudioProcessorEditor::SystemMenuButton final : public juce::B public: SystemMenuButton() : juce::Button("Disk image menu") { - setTooltip("System / Disk images"); + setTooltip("System"); setMouseClickGrabsKeyboardFocus(false); } @@ -529,17 +548,13 @@ WaveEmulationAudioProcessorEditor::WaveEmulationAudioProcessorEditor( systemMenuButton->onClick = [this] { showSystemMenu(); }; addAndMakeVisible(*systemMenuButton); setResizable(true, true); - { - juce::PropertiesFile::Options options; - options.applicationName = "Wave Emulation UI"; - options.filenameSuffix = ".settings"; - options.folderName = "Wave Emulation"; - options.osxLibrarySubFolder = "Application Support"; - options.millisecondsBeforeSaving = 1000; - uiSettings = std::make_unique(options); - } - panelLayout = static_cast(juce::jlimit( - 0, 2, uiSettings->getIntValue("panelLayout", static_cast(PanelLayout::full)))); + setResizeLimits( + juce::roundToInt(panelDesignWidth() * minimumEditorScale), + juce::roundToInt(designHeight * minimumEditorScale), + juce::roundToInt(panelDesignWidth() * maximumEditorScale), + juce::roundToInt(designHeight * maximumEditorScale)); + if (auto* constrainer = getConstrainer()) + constrainer->setFixedAspectRatio(static_cast(panelDesignWidth() / designHeight)); const auto svg = juce::String::fromUTF8(WaveAssets::WaldorfWaveUI_NOLOGO_svg, WaveAssets::WaldorfWaveUI_NOLOGO_svgSize); @@ -598,6 +613,7 @@ WaveEmulationAudioProcessorEditor::WaveEmulationAudioProcessorEditor( auto button = std::make_unique(editButtonArtwork.get()); auto* buttonPointer = button.get(); const auto hardwareId = editButtonHardwareIds[index]; + button->setTooltip(wave::panel::buttonName(hardwareId)); button->setTriggeredOnMouseDown(true); button->onStateChange = [this, buttonPointer, hardwareId] { const auto down = buttonPointer->getState() == juce::Button::buttonDown; @@ -719,25 +735,14 @@ WaveEmulationAudioProcessorEditor::WaveEmulationAudioProcessorEditor( lcd->setPanelEmbedded(true); addAndMakeVisible(*lcd); - { - // Editor tests address controls in design pixels, so they request the - // original full-size layout and ignore any saved user preference. - const auto designSizeRequested - = juce::SystemStats::getEnvironmentVariable("WAVE_EDITOR_DESIGN_SIZE", {}).isNotEmpty(); - if (designSizeRequested) - panelLayout = PanelLayout::full; - const auto savedScale = designSizeRequested - ? 1.0f - : static_cast(uiSettings->getDoubleValue("editorScale", 0.0)); - // First launch: pick a size that fits the screen instead of the 2338 px - // design size, which is wider than most laptop displays. - const auto requestedLayout = panelLayout; - panelLayout = PanelLayout::full; - applyLayout(requestedLayout, savedScale > 0.0f ? savedScale - : juce::jmin(defaultEditorScale, - fitToScreenScale())); - layoutInitialised = true; - } + setSize(juce::roundToInt(panelDesignWidth() * defaultEditorScale), + juce::roundToInt(designHeight * defaultEditorScale)); + if (ownerProcessor.getRememberedCompactPanelSkin()) + applyPanelLayout(true, defaultEditorScale); + else if (const auto rememberedSkin = ownerProcessor.getRememberedPanelSkin(); + rememberedSkin != juce::File{}) + loadPanelSkin(rememberedSkin, false); + restoreWindowPreferences(); startTimerHz(60); juce::MessageManager::callAsync([safe = juce::Component::SafePointer(this)] { if (safe != nullptr) @@ -748,6 +753,8 @@ WaveEmulationAudioProcessorEditor::WaveEmulationAudioProcessorEditor( WaveEmulationAudioProcessorEditor::~WaveEmulationAudioProcessorEditor() { stopTimer(); + if (windowSettings != nullptr) + windowSettings->saveIfNeeded(); // Pitch Bend is the sole spring-loaded controller. Mod and the freely // assignable bipolar Free wheel retain their physical positions. if (activePerformanceWheel == 0) @@ -761,74 +768,9 @@ WaveEmulationAudioProcessorEditor::~WaveEmulationAudioProcessorEditor() if (activePanelFader >= 0) ownerProcessor.endPanelFaderGesture(activePanelFader, activePanelFaderPerformanceMode); - if (uiSettings != nullptr) - uiSettings->saveIfNeeded(); setLookAndFeel(nullptr); } -float WaveEmulationAudioProcessorEditor::visibleDesignHeight() const noexcept -{ - switch (panelLayout) - { - case PanelLayout::noKeyboard: return noKeyboardDesignHeight; - case PanelLayout::panelOnly: return panelOnlyDesignHeight; - case PanelLayout::full: break; - } - return designHeight; -} - -float WaveEmulationAudioProcessorEditor::currentScale() const noexcept -{ - return static_cast(getWidth()) / designWidth; -} - -float WaveEmulationAudioProcessorEditor::fitToScreenScale() const -{ - auto area = juce::Rectangle { 1440, 900 }; - const auto& displays = juce::Desktop::getInstance().getDisplays(); - const auto* display = isShowing() ? displays.getDisplayForRect(getScreenBounds()) - : displays.getPrimaryDisplay(); - if (display != nullptr) - area = display->userBounds.toNearestInt(); - // Leave room for the window title bar, the standalone Options strip and a - // small margin around the window. - const auto scale = juce::jmin((static_cast(area.getWidth()) - 40.0f) / designWidth, - (static_cast(area.getHeight()) - 110.0f) - / visibleDesignHeight()); - return juce::jlimit(minimumEditorScale, maximumEditorScale, scale); -} - -void WaveEmulationAudioProcessorEditor::applyLayout(PanelLayout layout, float scale) -{ - const auto layoutChanged = layout != panelLayout; - panelLayout = layout; - scale = juce::jlimit(minimumEditorScale, maximumEditorScale, scale); - const auto visibleHeight = visibleDesignHeight(); - // Clear the old aspect ratio first so the new limits are not fought by it. - if (auto* sizeConstrainer = getConstrainer()) - sizeConstrainer->setFixedAspectRatio(0.0); - setResizeLimits(juce::roundToInt(designWidth * minimumEditorScale), - juce::roundToInt(visibleHeight * minimumEditorScale), - juce::roundToInt(designWidth * maximumEditorScale), - juce::roundToInt(visibleHeight * maximumEditorScale)); - if (auto* sizeConstrainer = getConstrainer()) - sizeConstrainer->setFixedAspectRatio(static_cast(designWidth / visibleHeight)); - - const auto newWidth = juce::roundToInt(designWidth * scale); - const auto newHeight = juce::roundToInt(visibleHeight * scale); - if (newWidth == getWidth() && newHeight == getHeight()) - { - if (layoutChanged) - resized(); - } - else - setSize(newWidth, newHeight); - - if (layoutInitialised && uiSettings != nullptr) - uiSettings->setValue("panelLayout", static_cast(panelLayout)); - repaint(); -} - juce::StringArray WaveEmulationAudioProcessorEditor::getMenuBarNames() { return { "System" }; @@ -841,30 +783,12 @@ juce::PopupMenu WaveEmulationAudioProcessorEditor::getMenuForIndex( if (topLevelMenuIndex != 0) return menu; - juce::PopupMenu view; - view.addItem(layoutFullMenuItem, "Full Panel with Keyboard", true, - panelLayout == PanelLayout::full); - view.addItem(layoutNoKeyboardMenuItem, "Hide On-Screen Keyboard", true, - panelLayout == PanelLayout::noKeyboard); - view.addItem(layoutPanelOnlyMenuItem, "Upper Panel Only", true, - panelLayout == PanelLayout::panelOnly); - view.addSeparator(); - view.addItem(fitToScreenMenuItem, "Fit to Screen (Cmd 0)"); - view.addItem(zoomInMenuItem, "Zoom In (Cmd +)"); - view.addItem(zoomOutMenuItem, "Zoom Out (Cmd -)"); - view.addSeparator(); - const auto scalePercent = currentScale() * 100.0f; - for (size_t index = 0; index < zoomPercentages.size(); ++index) - view.addItem(zoomMenuItemBase + static_cast(index), - juce::String(zoomPercentages[index]) + "%", true, - std::abs(scalePercent - static_cast(zoomPercentages[index])) < 1.0f); - menu.addSubMenu("View", view); - menu.addSeparator(); menu.addItem(loadFirmwareMenuItem, "Load System Firmware Folder..."); menu.addSeparator(); const auto mounted = ownerProcessor.hasMountedDiskImage(); menu.addItem(createBlankDiskMenuItem, "New Blank 720 KB DD Disk Image..."); menu.addItem(createDiskFromSetMenuItem, "Create Disk Image from Wave Setup..."); + menu.addItem(createDiskFromWavetableMenuItem, "Create Disk Image from WTB..."); menu.addSeparator(); menu.addItem(mountDiskMenuItem, mounted ? "Mount Another Disk Image..." : "Mount Disk Image..."); @@ -873,8 +797,26 @@ juce::PopupMenu WaveEmulationAudioProcessorEditor::getMenuForIndex( .mountedDiskImageIsWritable()); menu.addItem(saveDiskAsMenuItem, "Save Mounted Disk Image As...", mounted); menu.addItem(ejectDiskMenuItem, "Eject Disk", mounted); + menu.addItem(reloadDiskBankMenuItem, "Reload Performance Bank from Mounted Image", mounted); menu.addSeparator(); menu.addItem(-1, ownerProcessor.getMountedDiskDescription(), false, false); + menu.addSeparator(); + menu.addItem(zoomInMenuItem, "Zoom In (Cmd/Ctrl + =)"); + menu.addItem(zoomOutMenuItem, "Zoom Out (Cmd/Ctrl + -)"); + menu.addItem(resetZoomMenuItem, "Actual Size (Cmd/Ctrl + 0)"); + menu.addItem(fitToScreenMenuItem, "Fit to Screen (Cmd/Ctrl + Shift + 0)"); + menu.addItem(toggleKeyboardMenuItem, + keyboardVisible ? "Hide Lower Keyboard Area (Cmd/Ctrl + K)" + : "Show Lower Keyboard Area (Cmd/Ctrl + K)", !compactSkin); + menu.addSeparator(); + juce::PopupMenu skins; + skins.addItem(defaultPanelSkinMenuItem, "Original", true, + !compactSkin && panelSkinFile == juce::File{}); + skins.addItem(compactPanelSkinMenuItem, "Compact Skin", true, compactSkin); + skins.addItem(loadPanelSkinMenuItem, "Load Alternative SVG Skin..."); + if (panelSkinFile != juce::File{}) + skins.addItem(-2, "Current: " + panelSkinFile.getFileName(), false); + menu.addSubMenu("Panel Skin", skins); return menu; } @@ -893,28 +835,48 @@ void WaveEmulationAudioProcessorEditor::showSystemMenu() void WaveEmulationAudioProcessorEditor::menuItemSelected(int menuItemId, int) { - if (menuItemId == layoutFullMenuItem || menuItemId == layoutNoKeyboardMenuItem - || menuItemId == layoutPanelOnlyMenuItem) + if (menuItemId == reloadDiskBankMenuItem) { - applyLayout(static_cast(menuItemId - layoutFullMenuItem), currentScale()); + const auto result = ownerProcessor.reloadBankFromMountedImage(); + if (result.failed()) + showDiskError("Reload Performance Bank", result); return; } - if (menuItemId == fitToScreenMenuItem) + if (menuItemId == loadPanelSkinMenuItem) { - applyLayout(panelLayout, fitToScreenScale()); + showPanelSkinChooser(); + return; + } + if (menuItemId == compactPanelSkinMenuItem) + { + useCompactPanelSkin(); + return; + } + if (menuItemId == defaultPanelSkinMenuItem) + { + useDefaultPanelSkin(); return; } if (menuItemId == zoomInMenuItem || menuItemId == zoomOutMenuItem) { - stepZoom(menuItemId == zoomInMenuItem ? 1 : -1); + const auto currentScale = static_cast(getWidth()) / panelDesignWidth(); + const auto direction = menuItemId == zoomInMenuItem ? 1.0f : -1.0f; + setWindowScale(std::round(currentScale * 10.0f + direction) / 10.0f); + return; + } + if (menuItemId == resetZoomMenuItem) + { + setWindowScale(defaultEditorScale); + return; + } + if (menuItemId == fitToScreenMenuItem) + { + setWindowScale(fitToScreenScale()); return; } - if (menuItemId >= zoomMenuItemBase - && menuItemId < zoomMenuItemBase + static_cast(zoomPercentages.size())) + if (menuItemId == toggleKeyboardMenuItem) { - applyLayout(panelLayout, - static_cast(zoomPercentages[static_cast( - menuItemId - zoomMenuItemBase)]) / 100.0f); + setKeyboardVisible(!keyboardVisible); return; } if (menuItemId == loadFirmwareMenuItem) @@ -937,6 +899,11 @@ void WaveEmulationAudioProcessorEditor::menuItemSelected(int menuItemId, int) showDiskImageChooser(); return; } + if (menuItemId == createDiskFromWavetableMenuItem) + { + showCreateDiskFromWavetableChooser(); + return; + } if (menuItemId == saveDiskMenuItem) { const auto result = ownerProcessor.flushMountedDiskImage(); @@ -959,6 +926,85 @@ void WaveEmulationAudioProcessorEditor::menuItemSelected(int menuItemId, int) } } +float WaveEmulationAudioProcessorEditor::activeDesignHeight() const noexcept +{ + return compactSkin ? panelDesignHeight() : keyboardVisible ? designHeight : panelOnlyHeight; +} + +float WaveEmulationAudioProcessorEditor::fitToScreenScale() const +{ + auto area = juce::Rectangle { 1440, 900 }; + const auto& displays = juce::Desktop::getInstance().getDisplays(); + const auto* display = isShowing() ? displays.getDisplayForRect(getScreenBounds()) + : displays.getPrimaryDisplay(); + if (display != nullptr) + area = display->userBounds.toNearestInt(); + // Leave room for the title bar, the standalone Options strip and a margin. + const auto scale = juce::jmin((static_cast(area.getWidth()) - 40.0f) / panelDesignWidth(), + (static_cast(area.getHeight()) - 110.0f) + / activeDesignHeight()); + return juce::jlimit(minimumEditorScale, maximumEditorScale, + std::floor(scale * 100.0f) / 100.0f); +} + +void WaveEmulationAudioProcessorEditor::restoreWindowPreferences() +{ + // Editor tests address controls in design pixels and keep the original size. + if (juce::SystemStats::getEnvironmentVariable("WAVE_EDITOR_DESIGN_SIZE", {}).isNotEmpty()) + return; + juce::PropertiesFile::Options options; + options.applicationName = "Wave Emulation UI"; + options.filenameSuffix = ".settings"; + options.folderName = "Wave Emulation"; + options.osxLibrarySubFolder = "Application Support"; + options.millisecondsBeforeSaving = 1000; + windowSettings = std::make_unique(options); + + if (!compactSkin && !windowSettings->getBoolValue("keyboardVisible", true)) + keyboardVisible = false; + const auto savedScale = static_cast(windowSettings->getDoubleValue( + compactSkin ? "compactScale" : "editorScale", 0.0)); + // First launch: fit the screen rather than opening wider than the display. + setWindowScale(savedScale > 0.0f ? savedScale + : juce::jmin(defaultEditorScale, fitToScreenScale())); + windowPreferencesRestored = true; +} + +void WaveEmulationAudioProcessorEditor::saveWindowPreferences() +{ + if (!windowPreferencesRestored || windowSettings == nullptr || getWidth() <= 0) + return; + windowSettings->setValue(compactSkin ? "compactScale" : "editorScale", + static_cast(getWidth()) / panelDesignWidth()); + if (!compactSkin) + windowSettings->setValue("keyboardVisible", keyboardVisible); +} + +void WaveEmulationAudioProcessorEditor::setWindowScale(float scale) +{ + scale = juce::jlimit(minimumEditorScale, maximumEditorScale, scale); + const auto activeHeight = activeDesignHeight(); + if (auto* constrainer = getConstrainer()) + constrainer->setFixedAspectRatio(static_cast(panelDesignWidth() / activeHeight)); + setResizeLimits(juce::roundToInt(panelDesignWidth() * minimumEditorScale), + juce::roundToInt(activeHeight * minimumEditorScale), + juce::roundToInt(panelDesignWidth() * maximumEditorScale), + juce::roundToInt(activeHeight * maximumEditorScale)); + setSize(juce::roundToInt(panelDesignWidth() * scale), + juce::roundToInt(activeHeight * scale)); +} + +void WaveEmulationAudioProcessorEditor::setKeyboardVisible(bool visible) +{ + if (compactSkin || keyboardVisible == visible) + return; + releaseActivePointerInteractions(false); + const auto currentScale = static_cast(getWidth()) / panelDesignWidth(); + keyboardVisible = visible; + setWindowScale(currentScale); + menuItemsChanged(); +} + void WaveEmulationAudioProcessorEditor::showFirmwareFolderChooser() { firmwareFolderChooser = std::make_unique( @@ -1049,18 +1095,39 @@ void WaveEmulationAudioProcessorEditor::showDiskDestinationChooser( const auto destination = chooser.getResult(); if (destination == juce::File{}) return; - const auto result = safe->ownerProcessor.createDiskImageFromWaveSetup( - waveSetup, destination); + const auto wavetable = waveSetup.hasFileExtension(".wtb"); + const auto result = wavetable + ? safe->ownerProcessor.createDiskImageFromWavetable(waveSetup, destination) + : safe->ownerProcessor.createDiskImageFromWaveSetup(waveSetup, destination); if (result.failed()) safe->showDiskError("Could not create Wave disk image", result); else juce::AlertWindow::showMessageBoxAsync( juce::MessageBoxIconType::InfoIcon, "Wave disk ready", - "The canonical 720 KB DD disk image was created and mounted."); + wavetable + ? "A 720 KB DD disk image was created and mounted. Use the Wave's Disk controls to load its WTB file." + : "The canonical 720 KB DD disk image was created and mounted."); safe->menuItemsChanged(); }); } +void WaveEmulationAudioProcessorEditor::showCreateDiskFromWavetableChooser() +{ + waveSetChooser = std::make_unique( + "Choose a Waldorf Wave Wavetable", juce::File::getSpecialLocation( + juce::File::userDocumentsDirectory), + "*.wtb", true); + waveSetChooser->launchAsync( + juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, + [safe = juce::Component::SafePointer(this)](const juce::FileChooser& chooser) { + if (safe == nullptr) + return; + const auto selected = chooser.getResult(); + if (selected.existsAsFile()) + safe->showDiskDestinationChooser(selected); + }); +} + void WaveEmulationAudioProcessorEditor::showSaveDiskAsChooser() { const auto mounted = ownerProcessor.getMountedDiskImageFile(); @@ -1116,56 +1183,33 @@ void WaveEmulationAudioProcessorEditor::showDiskError(const juce::String& title, title, result.getErrorMessage()); } -void WaveEmulationAudioProcessorEditor::stepZoom(int direction) -{ - const auto scale = currentScale(); - auto target = scale; - if (direction > 0) - { - target = maximumEditorScale; - for (const auto percent : zoomPercentages) - if (static_cast(percent) / 100.0f > scale + 0.005f) - { - target = static_cast(percent) / 100.0f; - break; - } - } - else - { - target = minimumEditorScale; - for (auto it = zoomPercentages.rbegin(); it != zoomPercentages.rend(); ++it) - if (static_cast(*it) / 100.0f < scale - 0.005f) - { - target = static_cast(*it) / 100.0f; - break; - } - } - applyLayout(panelLayout, target); -} - bool WaveEmulationAudioProcessorEditor::keyPressed(const juce::KeyPress& key) { + const auto code = juce::CharacterFunctions::toLowerCase(key.getKeyCode()); if (key.getModifiers().isCommandDown()) { - const auto keyCode = key.getKeyCode(); - if (keyCode == '=' || keyCode == '+') + if (code == '+' || code == '=' || code == juce::KeyPress::numberPadAdd) { - stepZoom(1); + menuItemSelected(zoomInMenuItem, 0); return true; } - if (keyCode == '-') + if (code == '-' || code == juce::KeyPress::numberPadSubtract) { - stepZoom(-1); + menuItemSelected(zoomOutMenuItem, 0); return true; } - if (keyCode == '0') + if (code == '0' || code == ')' || code == juce::KeyPress::numberPad0) { - applyLayout(panelLayout, fitToScreenScale()); + menuItemSelected(key.getModifiers().isShiftDown() ? fitToScreenMenuItem + : resetZoomMenuItem, 0); + return true; + } + if (code == 'k') + { + menuItemSelected(toggleKeyboardMenuItem, 0); return true; } - return false; } - const auto code = juce::CharacterFunctions::toLowerCase(key.getKeyCode()); const auto found = std::find(performanceKeys.begin(), performanceKeys.end(), code); if (found == performanceKeys.end()) return false; @@ -1189,11 +1233,15 @@ bool WaveEmulationAudioProcessorEditor::keyStateChanged(bool) bool WaveEmulationAudioProcessorEditor::updateComputerKeyboardNotes() { auto handled = false; + const auto commandDown + = juce::ModifierKeys::getCurrentModifiersRealtime().isCommandDown(); for (size_t index = 0; index < performanceKeys.size(); ++index) { - const auto down = juce::KeyPress::isKeyCurrentlyDown(performanceKeys[index]) - || juce::KeyPress::isKeyCurrentlyDown( - juce::CharacterFunctions::toUpperCase(performanceKeys[index])); + const auto down + = !commandDown + && (juce::KeyPress::isKeyCurrentlyDown(performanceKeys[index]) + || juce::KeyPress::isKeyCurrentlyDown( + juce::CharacterFunctions::toUpperCase(performanceKeys[index]))); if (down == keyboardNotes[index]) continue; @@ -1252,18 +1300,21 @@ void WaveEmulationAudioProcessorEditor::focusLost(FocusChangeType) void WaveEmulationAudioProcessorEditor::paint(juce::Graphics& graphics) { graphics.fillAll(juce::Colours::black); + const auto scaleX = static_cast(getWidth()) / panelDesignWidth(); + const auto fullPanelBounds = juce::Rectangle { + 0.0f, 0.0f, static_cast(getWidth()), panelDesignHeight() * scaleX + }; if (panelImage.isValid()) { graphics.setImageResamplingQuality(juce::Graphics::highResamplingQuality); - graphics.drawImage(panelImage, getLocalBounds().toFloat(), + graphics.drawImage(panelImage, fullPanelBounds, juce::RectanglePlacement::stretchToFit); } else if (panelArtwork != nullptr) - panelArtwork->drawWithin(graphics, fullArtworkBounds(1.0f), + panelArtwork->drawWithin(graphics, fullPanelBounds, juce::RectanglePlacement::stretchToFit, 1.0f); - const auto scaleX = static_cast(getWidth()) / designWidth; - const auto scaleY = static_cast(getHeight()) / visibleDesignHeight(); + const auto scaleY = scaleX; const auto minScale = juce::jmin(scaleX, scaleY); const auto scaledKeyboardBounds = [scaleX, scaleY](juce::Rectangle bounds) { return juce::Rectangle { @@ -1272,128 +1323,121 @@ void WaveEmulationAudioProcessorEditor::paint(juce::Graphics& graphics) }; }; - if (panelLayout == PanelLayout::noKeyboard) - { - // Cover the top edge of the (hidden) keybed with the chassis colour so - // the compact layout ends in a clean strip below the transport row. - graphics.setColour(keybedCoverColour); - graphics.fillRect(juce::Rectangle { - (keyboardLeft - 4.0f) * scaleX, (keyboardTop - 2.0f) * scaleY, - (keyboardWidth + 8.0f) * scaleX, - (noKeyboardDesignHeight - keyboardTop + 2.0f) * scaleY }); - } - if (panelLayout == PanelLayout::full) - { - // Draw the keyboard at runtime so it remains visible even when the panel - // SVG is re-exported with only the empty black keyboard bed. The keybed - // deliberately occupies the complete 1671 x 278 black rectangle. - const auto whiteKeys = scaledKeyboardBounds( - { keyboardLeft, keyboardTop, keyboardWidth, keyboardWhiteKeyHeight }); - - juce::ColourGradient whiteKeyGradient( - juce::Colour(0xfff8f8f5), whiteKeys.getX(), whiteKeys.getY(), - juce::Colour(0xffd3d3cf), whiteKeys.getX(), whiteKeys.getBottom(), false); - whiteKeyGradient.addColour(0.78, juce::Colour(0xffe9e9e5)); - graphics.setGradientFill(whiteKeyGradient); - graphics.fillRect(whiteKeys); - - graphics.setColour(juce::Colour(0xff27282c)); - for (auto whiteKey = 1; whiteKey < 36; ++whiteKey) - { - const auto x = (keyboardLeft - + static_cast(whiteKey) * keyboardWhiteKeyWidth) * scaleX; - graphics.drawLine(x, whiteKeys.getY(), x, whiteKeys.getBottom(), - juce::jmax(1.5f, 2.0f * minScale)); - } - - const auto feedbackIsVisible = recentMidiNote >= 0 - && juce::Time::getMillisecondCounterHiRes() - < recentMidiNoteHighlightUntil; - const auto drawMidiKeyFeedback = [&](int midiNote, bool blackKeys) { - if (midiNote < keyboardLowestMidiNote || midiNote > keyboardHighestMidiNote - || isBlackMidiNote(midiNote) != blackKeys) - return; - const auto bounds = scaledKeyboardBounds(midiKeyBounds(midiNote)); - graphics.setColour(juce::Colour(0xffda2e2e).withAlpha(0.25f)); - if (blackKeys) - graphics.fillRoundedRectangle(bounds, 2.0f * minScale); - else - graphics.fillRect(bounds); - }; - const auto drawFeedbackForKeyType = [&](bool blackKeys) { + if (!compactSkin) + { + // Draw the keyboard at runtime so it remains visible even when the panel + // SVG is re-exported with only the empty black keyboard bed. The keybed + // deliberately occupies the complete 1671 x 278 black rectangle. + const auto whiteKeys = scaledKeyboardBounds( + { keyboardLeft, keyboardTop, keyboardWidth, keyboardWhiteKeyHeight }); + + juce::ColourGradient whiteKeyGradient( + juce::Colour(0xfff8f8f5), whiteKeys.getX(), whiteKeys.getY(), + juce::Colour(0xffd3d3cf), whiteKeys.getX(), whiteKeys.getBottom(), false); + whiteKeyGradient.addColour(0.78, juce::Colour(0xffe9e9e5)); + graphics.setGradientFill(whiteKeyGradient); + graphics.fillRect(whiteKeys); + + graphics.setColour(juce::Colour(0xff27282c)); + for (auto whiteKey = 1; whiteKey < 36; ++whiteKey) + { + const auto x = (keyboardLeft + + static_cast(whiteKey) * keyboardWhiteKeyWidth) * scaleX; + graphics.drawLine(x, whiteKeys.getY(), x, whiteKeys.getBottom(), + juce::jmax(1.5f, 2.0f * minScale)); + } + + const auto feedbackIsVisible = recentMidiNote >= 0 + && juce::Time::getMillisecondCounterHiRes() + < recentMidiNoteHighlightUntil; + const auto drawMidiKeyFeedback = [&](int midiNote, bool blackKeys) { + if (midiNote < keyboardLowestMidiNote || midiNote > keyboardHighestMidiNote + || isBlackMidiNote(midiNote) != blackKeys) + return; + const auto bounds = scaledKeyboardBounds(midiKeyBounds(midiNote)); + graphics.setColour(juce::Colour(0xffda2e2e).withAlpha(0.25f)); + if (blackKeys) + graphics.fillRoundedRectangle(bounds, 2.0f * minScale); + else + graphics.fillRect(bounds); + }; + const auto drawFeedbackForKeyType = [&](bool blackKeys) { + for (auto midiNote = keyboardLowestMidiNote; + midiNote <= keyboardHighestMidiNote; ++midiNote) + if (ownerProcessor.isMidiNoteActive(midiNote)) + drawMidiKeyFeedback(midiNote, blackKeys); + for (size_t index = 0; index < keyboardNotes.size(); ++index) + if (keyboardNotes[index]) + drawMidiKeyFeedback(60 + static_cast(index), blackKeys); + if (feedbackIsVisible) + drawMidiKeyFeedback(recentMidiNote, blackKeys); + if (activeMidiNote >= 0) + drawMidiKeyFeedback(activeMidiNote, blackKeys); + }; + + // White-key feedback is painted before the raised black keys so adjacent + // black keys retain their physical overlap and remain easy to read. + drawFeedbackForKeyType(false); + + juce::ColourGradient blackKeyGradient( + juce::Colour(0xff383a42), 0.0f, keyboardTop * scaleY, + juce::Colour(0xff050506), 0.0f, + (keyboardTop + keyboardBlackKeyHeight) * scaleY, false); + blackKeyGradient.addColour(0.18, juce::Colour(0xff202127)); + blackKeyGradient.addColour(0.82, juce::Colour(0xff111216)); for (auto midiNote = keyboardLowestMidiNote; midiNote <= keyboardHighestMidiNote; ++midiNote) - if (ownerProcessor.isMidiNoteActive(midiNote)) - drawMidiKeyFeedback(midiNote, blackKeys); - for (size_t index = 0; index < keyboardNotes.size(); ++index) - if (keyboardNotes[index]) - drawMidiKeyFeedback(60 + static_cast(index), blackKeys); - if (feedbackIsVisible) - drawMidiKeyFeedback(recentMidiNote, blackKeys); - if (activeMidiNote >= 0) - drawMidiKeyFeedback(activeMidiNote, blackKeys); - }; - - // White-key feedback is painted before the raised black keys so adjacent - // black keys retain their physical overlap and remain easy to read. - drawFeedbackForKeyType(false); + { + if (!isBlackMidiNote(midiNote)) + continue; + const auto bounds = scaledKeyboardBounds(midiKeyBounds(midiNote)); + graphics.setGradientFill(blackKeyGradient); + graphics.fillRoundedRectangle(bounds, 2.0f * minScale); + graphics.setColour(juce::Colour(0xff050506)); + graphics.drawRoundedRectangle(bounds, 2.0f * minScale, + juce::jmax(1.0f, 2.0f * minScale)); + } + drawFeedbackForKeyType(true); - juce::ColourGradient blackKeyGradient( - juce::Colour(0xff383a42), 0.0f, keyboardTop * scaleY, - juce::Colour(0xff050506), 0.0f, - (keyboardTop + keyboardBlackKeyHeight) * scaleY, false); - blackKeyGradient.addColour(0.18, juce::Colour(0xff202127)); - blackKeyGradient.addColour(0.82, juce::Colour(0xff111216)); - for (auto midiNote = keyboardLowestMidiNote; - midiNote <= keyboardHighestMidiNote; ++midiNote) - { - if (!isBlackMidiNote(midiNote)) - continue; - const auto bounds = scaledKeyboardBounds(midiKeyBounds(midiNote)); - graphics.setGradientFill(blackKeyGradient); - graphics.fillRoundedRectangle(bounds, 2.0f * minScale); - graphics.setColour(juce::Colour(0xff050506)); - graphics.drawRoundedRectangle(bounds, 2.0f * minScale, - juce::jmax(1.0f, 2.0f * minScale)); - } - drawFeedbackForKeyType(true); - } - - // The SVG supplies the three exact black wheel recesses. Draw only the - // black wheel bodies inside those bounds, preserving the Figma layout and - // adjacent position markings unchanged. - for (size_t wheel = 0; wheel < performanceWheelSlots.size(); ++wheel) - { - const auto slot = scaledKeyboardBounds(performanceWheelSlots[wheel]); - const auto centreY = juce::jmap( - performanceWheelValues[wheel], slot.getBottom() - 13.0f * scaleY, - slot.getY() + 13.0f * scaleY); - const auto body = juce::Rectangle { - slot.getWidth() - 2.0f * scaleX, 34.0f * scaleY - }.withCentre({ slot.getCentreX(), centreY }); - juce::Graphics::ScopedSaveState clipped(graphics); - graphics.reduceClipRegion(slot.toNearestInt()); - juce::ColourGradient wheelGradient( - juce::Colour(0xff050506), body.getX(), body.getY(), - juce::Colour(0xff202126), body.getRight(), body.getY(), false); - wheelGradient.addColour(0.5, juce::Colour(0xff0b0c0f)); - graphics.setGradientFill(wheelGradient); - graphics.fillRoundedRectangle(body, 3.0f * minScale); - graphics.setColour(juce::Colour(0xff363840)); - for (auto rib = 1; rib < 6; ++rib) + // The SVG supplies the three exact black wheel recesses. Draw only the + // black wheel bodies inside those bounds, preserving the Figma layout and + // adjacent position markings unchanged. + for (size_t wheel = 0; wheel < performanceWheelSlots.size(); ++wheel) { - const auto y = body.getY() - + static_cast(rib) * body.getHeight() / 6.0f; - graphics.drawLine(body.getX() + 2.0f * scaleX, y, - body.getRight() - 2.0f * scaleX, y, - juce::jmax(0.6f, 0.8f * minScale)); + const auto slot = scaledKeyboardBounds(performanceWheelSlots[wheel]); + const auto centreY = juce::jmap( + performanceWheelValues[wheel], slot.getBottom() - 13.0f * scaleY, + slot.getY() + 13.0f * scaleY); + const auto body = juce::Rectangle { + slot.getWidth() - 2.0f * scaleX, 34.0f * scaleY + }.withCentre({ slot.getCentreX(), centreY }); + juce::Graphics::ScopedSaveState clipped(graphics); + graphics.reduceClipRegion(slot.toNearestInt()); + juce::ColourGradient wheelGradient( + juce::Colour(0xff050506), body.getX(), body.getY(), + juce::Colour(0xff202126), body.getRight(), body.getY(), false); + wheelGradient.addColour(0.5, juce::Colour(0xff0b0c0f)); + graphics.setGradientFill(wheelGradient); + graphics.fillRoundedRectangle(body, 3.0f * minScale); + graphics.setColour(juce::Colour(0xff363840)); + for (auto rib = 1; rib < 6; ++rib) + { + const auto y = body.getY() + + static_cast(rib) * body.getHeight() / 6.0f; + graphics.drawLine(body.getX() + 2.0f * scaleX, y, + body.getRight() - 2.0f * scaleX, y, + juce::jmax(0.6f, 0.8f * minScale)); + } + graphics.setColour(juce::Colours::black); + graphics.drawRoundedRectangle(body, 3.0f * minScale, + juce::jmax(1.0f, minScale)); } - graphics.setColour(juce::Colours::black); - graphics.drawRoundedRectangle(body, 3.0f * minScale, - juce::jmax(1.0f, minScale)); + } - if (roundButtonArtwork != nullptr) + // Compact switches are already complete SVG paths, including the numeric + // keypad glyphs. Painting the generic round asset would cover those labels. + if (!compactSkin && roundButtonArtwork != nullptr) { for (const auto& region : panelRegions) { @@ -1401,7 +1445,8 @@ void WaveEmulationAudioProcessorEditor::paint(juce::Graphics& graphics) continue; roundButtonArtwork->drawWithin( graphics, - juce::Rectangle { 30.0f * scaleX, 30.0f * scaleY } + juce::Rectangle { 30.0f * region.artworkScale * scaleX, + 30.0f * region.artworkScale * scaleY } .withCentre({ region.centre.x * scaleX, region.centre.y * scaleY }), juce::RectanglePlacement::stretchToFit, 1.0f); } @@ -1414,7 +1459,8 @@ void WaveEmulationAudioProcessorEditor::paint(juce::Graphics& graphics) continue; verticalButtonArtwork->drawWithin( graphics, - juce::Rectangle { 30.0f * scaleX, 61.0f * scaleY } + juce::Rectangle { 30.0f * region.artworkScale * scaleX, + 61.0f * region.artworkScale * scaleY } .withCentre({ region.centre.x * scaleX, region.centre.y * scaleY }), juce::RectanglePlacement::stretchToFit, 1.0f); } @@ -1428,14 +1474,15 @@ void WaveEmulationAudioProcessorEditor::paint(juce::Graphics& graphics) if (!region.fader) continue; const auto value = panelAnalogValues[static_cast(region.hardwareId)]; - const auto handleX = region.centre.x - handleWidth * 0.5f; + const auto handleX = region.centre.x - handleWidth * region.artworkScale * 0.5f; const auto handleCentreY = juce::jmap(value, region.faderTrackBottom, region.faderTrackTop); - const auto handleY = handleCentreY - handleHeight * 0.5f; + const auto handleY = handleCentreY - handleHeight * region.artworkScale * 0.5f; sliderArtwork->drawWithin( graphics, { handleX * scaleX, handleY * scaleY, - handleWidth * scaleX, handleHeight * scaleY }, + handleWidth * region.artworkScale * scaleX, + handleHeight * region.artworkScale * scaleY }, juce::RectanglePlacement::stretchToFit, 1.0f); } } @@ -1446,6 +1493,8 @@ void WaveEmulationAudioProcessorEditor::paint(juce::Graphics& graphics) constexpr auto rotationExtent = juce::MathConstants::pi * 0.75f; for (size_t index = 0; index < knobs.size(); ++index) { + if (!knobs[index]->isVisible()) + continue; const auto bounds = knobs[index]->getBounds().toFloat(); const auto centre = bounds.getCentre(); auto* artwork = knobArtwork.get(); @@ -1462,6 +1511,15 @@ void WaveEmulationAudioProcessorEditor::paint(juce::Graphics& graphics) } if (artwork == nullptr) continue; + if (compactSkin) + if (const auto* placement = compactKnobAt(knobDesignCentres[index])) + { + artworkSize = placement->artworkSize; + if ((placement->originalX == 516.0f + && (placement->originalY == 160.0f || placement->originalY == 357.0f)) + || (placement->originalX == 1670.0f && placement->originalY == 237.0f)) + artwork = redKnobArtwork.get(); + } const auto artworkBounds = juce::Rectangle { artworkSize * scaleX, artworkSize * scaleY }.withCentre(centre); @@ -1483,7 +1541,7 @@ void WaveEmulationAudioProcessorEditor::paint(juce::Graphics& graphics) artwork = ledOnRedArtwork.get(); else if (colour == juce::Colours::yellow && ledOnYellowArtwork != nullptr) artwork = ledOnYellowArtwork.get(); - const auto bounds = juce::Rectangle { 6.0f * scaleX, 6.0f * scaleY } + const auto bounds = juce::Rectangle { led.size * scaleX, led.size * scaleY } .withCentre({ led.centre.x * scaleX, led.centre.y * scaleY }); if (artwork != nullptr) @@ -1495,11 +1553,10 @@ void WaveEmulationAudioProcessorEditor::paint(juce::Graphics& graphics) void WaveEmulationAudioProcessorEditor::mouseDown(const juce::MouseEvent& event) { const auto designPoint = juce::Point { - event.position.x * designWidth / static_cast(getWidth()), - event.position.y * visibleDesignHeight() / static_cast(getHeight()) + event.position.x * panelDesignWidth() / static_cast(getWidth()), + event.position.y * panelDesignWidth() / static_cast(getWidth()) }; - if (const auto midiNote = panelLayout == PanelLayout::full ? midiNoteAt(designPoint) : -1; - midiNote >= 0) + if (const auto midiNote = compactSkin ? -1 : midiNoteAt(designPoint); midiNote >= 0) { midiKeyboardDragging = true; recentMidiNote = -1; @@ -1509,7 +1566,7 @@ void WaveEmulationAudioProcessorEditor::mouseDown(const juce::MouseEvent& event) return; } - for (size_t wheel = 0; wheel < performanceWheelSlots.size(); ++wheel) + for (size_t wheel = 0; !compactSkin && wheel < performanceWheelSlots.size(); ++wheel) { if (!performanceWheelSlots[wheel].contains(designPoint)) continue; @@ -1517,32 +1574,36 @@ void WaveEmulationAudioProcessorEditor::mouseDown(const juce::MouseEvent& event) analogDragStartY = event.position.y; analogDragStartValue = performanceWheelValues[wheel]; analogDragRangePixels = performanceWheelSlots[wheel].getHeight() - * static_cast(getHeight()) / visibleDesignHeight(); + * static_cast(getWidth()) / panelDesignWidth(); return; } - const auto panelPoint = designPoint.translated(-panelHorizontalOffset, 0.0f); - if (hitCircle(panelPoint, 39.0f, 555.0f)) + if (!compactSkin) { - pressPanelButton(wave::panel::matrixIndexForDiagnosticCode(2)); - updateLfoKnobBindings(); - repaint(); - return; - } - if (hitCircle(panelPoint, 392.0f, 555.0f)) - { - pressPanelButton(wave::panel::matrixIndexForDiagnosticCode(14)); - updateWaveEnvelopeKnobBindings(); - repaint(); - return; - } - if (handlePerformanceControl(panelPoint)) - return; + const auto panelPoint = designPoint.translated(-panelHorizontalOffset, 0.0f); + if (hitCircle(panelPoint, 39.0f, 555.0f)) + { + pressPanelButton(wave::panel::matrixIndexForDiagnosticCode(2)); + updateLfoKnobBindings(); + repaint(); + return; + } + if (hitCircle(panelPoint, 392.0f, 555.0f)) + { + pressPanelButton(wave::panel::matrixIndexForDiagnosticCode(14)); + updateWaveEnvelopeKnobBindings(); + repaint(); + return; + } + if (handlePerformanceControl(panelPoint)) + return; - // The seven blue edit-mode selectors above Performance leave Performance - // mode. Their normal firmware button handling remains unchanged below. - if (hitRectangle(panelPoint, 1372.0f, 124.0f, 61.0f, 385.0f)) - performanceMode = false; + // The seven blue edit-mode selectors above Performance leave Performance + // mode. Their normal firmware button handling remains unchanged below. + if (hitRectangle(panelPoint, 1372.0f, 124.0f, 61.0f, 385.0f)) + performanceMode = false; + + } for (auto region = panelRegions.rbegin(); region != panelRegions.rend(); ++region) { @@ -1560,8 +1621,8 @@ void WaveEmulationAudioProcessorEditor::mouseDown(const juce::MouseEvent& event) 1.0f, (region->faderTrackBottom - region->faderTrackTop) - * static_cast(getHeight()) - / visibleDesignHeight()) + * static_cast(getWidth()) + / panelDesignWidth()) : 160.0f; if (region->fader) { @@ -1584,6 +1645,10 @@ void WaveEmulationAudioProcessorEditor::mouseDown(const juce::MouseEvent& event) return; } pressPanelButton(region->hardwareId); + if (region->hardwareId == 2) + updateLfoKnobBindings(); + else if (region->hardwareId == 14) + updateWaveEnvelopeKnobBindings(); return; } } @@ -1753,10 +1818,10 @@ void WaveEmulationAudioProcessorEditor::mouseDrag(const juce::MouseEvent& event) if (midiKeyboardDragging) { const auto designPoint = juce::Point { - event.position.x * designWidth / static_cast(getWidth()), - event.position.y * visibleDesignHeight() / static_cast(getHeight()) + event.position.x * panelDesignWidth() / static_cast(getWidth()), + event.position.y * panelDesignWidth() / static_cast(getWidth()) }; - const auto midiNote = panelLayout == PanelLayout::full ? midiNoteAt(designPoint) : -1; + const auto midiNote = midiNoteAt(designPoint); if (midiNote != activeMidiNote) { if (activeMidiNote >= 0) @@ -2142,11 +2207,9 @@ void WaveEmulationAudioProcessorEditor::timerCallback() void WaveEmulationAudioProcessorEditor::resized() { rebuildPanelImage(); - if (layoutInitialised && uiSettings != nullptr && getWidth() > 0 - && juce::SystemStats::getEnvironmentVariable("WAVE_EDITOR_DESIGN_SIZE", {}).isEmpty()) - uiSettings->setValue("editorScale", static_cast(currentScale())); - const auto scaleX = static_cast(getWidth()) / designWidth; - const auto scaleY = static_cast(getHeight()) / visibleDesignHeight(); + saveWindowPreferences(); + const auto scaleX = static_cast(getWidth()) / panelDesignWidth(); + const auto scaleY = scaleX; const auto scaled = [scaleX, scaleY](juce::Rectangle rectangle) { return juce::Rectangle(rectangle.getX() * scaleX, rectangle.getY() * scaleY, rectangle.getWidth() * scaleX, @@ -2159,13 +2222,16 @@ void WaveEmulationAudioProcessorEditor::resized() // The supplied artwork leaves this narrow chassis rail free of panel // controls. Keeping the host-side menu here makes it available in AU, // VST3, and standalone builds without moving or covering the Wave UI. - systemMenuButton->setBounds(scaled({ 16.0f, 4.0f, 36.0f, 28.0f })); + // Compact's left rail is 48 px wide, versus 66 px on the original. + systemMenuButton->setBounds(scaled({ compactSkin ? 6.0f : 16.0f, + 4.0f, 36.0f, 28.0f })); systemMenuButton->toFront(false); } if (lcd != nullptr) - lcd->setBounds(scaled({ 873.0f + panelHorizontalOffset, 237.0f, - 448.0f, 70.0f })); + lcd->setBounds(scaled(compactSkin + ? juce::Rectangle { 776.8f, 179.92f, 367.36f, 57.4f } + : juce::Rectangle { 873.0f + panelHorizontalOffset, 237.0f, 448.0f, 70.0f })); if (knobDesignCentres.size() == knobs.size() && knobArtworkTypes.size() == knobs.size()) @@ -2174,10 +2240,15 @@ void WaveEmulationAudioProcessorEditor::resized() { const auto hitSize = knobArtworkTypes[index] == KnobArtworkType::largeRed ? 104.0f : 60.0f; + const auto* placement = compactKnobAt(knobDesignCentres[index]); + knobs[index]->setVisible(!compactSkin || placement != nullptr); + const auto centre = compactSkin && placement != nullptr + ? juce::Point { placement->x, placement->y } + : knobDesignCentres[index].translated(panelHorizontalOffset, 0.0f); + const auto size = compactSkin && placement != nullptr + && placement->artworkSize > 90.0f ? 120.0f : hitSize; knobs[index]->setBounds(scaled( - juce::Rectangle(hitSize, hitSize) - .withCentre(knobDesignCentres[index].translated( - panelHorizontalOffset, 0.0f)))); + juce::Rectangle(size, size).withCentre(centre))); } } @@ -2185,9 +2256,16 @@ void WaveEmulationAudioProcessorEditor::resized() { for (size_t index = 0; index < editButtons.size(); ++index) { - editButtons[index]->setBounds(scaled( - juce::Rectangle(65.0f, 65.0f) - .withCentre(editButtonDesignCentres[index]))); + const auto region = std::find_if(panelRegions.begin(), panelRegions.end(), + [this, index](const auto& item) { + return item.editButton && item.hardwareId == editButtonHardwareIds[index]; + }); + editButtons[index]->setVisible(region != panelRegions.end()); + if (region != panelRegions.end()) + editButtons[index]->setBounds(scaled( + juce::Rectangle(65.0f * region->artworkScale, + 65.0f * region->artworkScale) + .withCentre(region->centre))); // Parameter knobs are constructed later and would otherwise sit // above the small overlapping edge of a diagonal Edit switch. // Only the exact pill path accepts a click, so its transparent @@ -2210,29 +2288,14 @@ void WaveEmulationAudioProcessorEditor::rebuildPanelImage() // at the current editor size avoids retracing thousands of vector paths on // every LED, fader, or LCD refresh. constexpr auto artworkScale = 2; + const auto fullArtworkHeight + = juce::roundToInt(panelDesignHeight() * static_cast(getWidth()) / panelDesignWidth()); panelImage = juce::Image(juce::Image::RGB, getWidth() * artworkScale, - getHeight() * artworkScale, true); + fullArtworkHeight * artworkScale, true); juce::Graphics imageGraphics(panelImage); imageGraphics.fillAll(juce::Colours::black); - panelArtwork->drawWithin(imageGraphics, fullArtworkBounds(static_cast(artworkScale)), + panelArtwork->drawWithin(imageGraphics, panelImage.getBounds().toFloat(), juce::RectanglePlacement::stretchToFit, 1.0f); - - // Sample the chassis colour just above the keybed for the compact layout. - const auto pixelsPerDesignUnit = static_cast(panelImage.getWidth()) / designWidth; - const auto sampleX = juce::roundToInt(1300.0f * pixelsPerDesignUnit); - const auto sampleY = juce::roundToInt(752.0f * pixelsPerDesignUnit); - keybedCoverColour = juce::isPositiveAndBelow(sampleY, panelImage.getHeight()) - ? panelImage.getPixelAt(sampleX, sampleY) - : juce::Colour(0xff2b2b3f); -} - -juce::Rectangle WaveEmulationAudioProcessorEditor::fullArtworkBounds( - float pixelScale) const noexcept -{ - // The complete artwork at the current zoom. In compact layouts its lower - // part simply falls outside the component and is clipped away. - const auto width = static_cast(getWidth()) * pixelScale; - return { 0.0f, 0.0f, width, width * designHeight / designWidth }; } WaveEmulationAudioProcessorEditor::ParameterKnob& @@ -2247,9 +2310,12 @@ WaveEmulationAudioProcessorEditor::addKnob(const juce::String& parameterId, auto& result = *knob; if (!endlessRelative) { - result.setPhysicalPotCallback( + result.setPhysicalPotCallbacks( [this](const juce::String& boundParameterId, float normalised) { ownerProcessor.setPanelPotValue(boundParameterId, normalised); + }, + [this](const juce::String& boundParameterId) { + return ownerProcessor.getPanelPotValue(boundParameterId); }); if (const auto physical = ownerProcessor.getPanelPotValue(parameterId)) result.synchronisePhysicalPosition(*physical); @@ -2331,3 +2397,219 @@ void WaveEmulationAudioProcessorEditor::updateWaveEnvelopeKnobBindings() wave::parameters::waveEnvelopeLevel[point], "Wave Envelope Level " + number); } } + +juce::String WaveEmulationAudioProcessorEditor::getTooltip() +{ + return tooltipAt(getMouseXYRelative().toFloat()); +} + +juce::String WaveEmulationAudioProcessorEditor::tooltipAt(juce::Point point) const +{ + if (getWidth() <= 0) + return {}; + const auto designPoint = point * (panelDesignWidth() / static_cast(getWidth())); + for (auto region = panelRegions.rbegin(); region != panelRegions.rend(); ++region) + if (region->path.contains(designPoint.x, designPoint.y)) + { + if (region->fader && region->faderIndex >= 0) + return "Fader " + juce::String(region->faderIndex + 1); + if (region->keyboardCode >= 0) + return wave::panel::keyboardControllerButtonName(region->keyboardCode); + if (!region->analog && region->hardwareId >= 0) + return wave::panel::buttonName(region->hardwareId); + } + for (const auto& knob : knobs) + if (knob->isVisible() && knob->getBounds().toFloat().contains(point)) + return knob->getTooltip(); + return {}; +} + +float WaveEmulationAudioProcessorEditor::panelDesignWidth() const noexcept +{ + return compactSkin ? wave::ui::compact::width : designWidth; +} + +float WaveEmulationAudioProcessorEditor::panelDesignHeight() const noexcept +{ + return compactSkin ? wave::ui::compact::height : designHeight; +} + +void WaveEmulationAudioProcessorEditor::applyPanelLayout(bool compact, float scale) +{ + const auto original = juce::XmlDocument::parse(juce::String::fromUTF8( + WaveAssets::WaldorfWaveUI_NOLOGO_svg, WaveAssets::WaldorfWaveUI_NOLOGO_svgSize)); + const auto artworkXml = compact + ? juce::XmlDocument::parse(juce::String::fromUTF8( + WaveAssets::WaldorfWaveUI_Compact_svg, WaveAssets::WaldorfWaveUI_Compact_svgSize)) + : nullptr; + if (original == nullptr || (compact && artworkXml == nullptr)) + return; + auto artwork = juce::Drawable::createFromSVG(compact ? *artworkXml : *original); + if (artwork == nullptr) + return; + releaseActivePointerInteractions(false); + // Restore the wiring contract before translating its controls to the + // compact artwork. Never derive electrical IDs from SVG element order. + initialisePanelRegions(*original); + if (compact) + initialiseCompactPanelRegions(*artworkXml); + compactSkin = compact; + panelSkinFile = juce::File{}; + panelArtwork = std::move(artwork); + synchroniseFaderValues(); + setWindowScale(scale); + resized(); // Also refresh child controls when selecting the current skin. + menuItemsChanged(); + repaint(); +} + +void WaveEmulationAudioProcessorEditor::useCompactPanelSkin() +{ + const auto result = ownerProcessor.rememberPanelSkin({}, true); + if (result.failed()) + { + showDiskError("Panel Skin", result); + return; + } + applyPanelLayout(true, static_cast(getWidth()) / panelDesignWidth()); +} + +void WaveEmulationAudioProcessorEditor::initialiseCompactPanelRegions(const juce::XmlElement& svg) +{ + struct ArtworkPath + { + juce::String fill; + juce::Path path; + }; + std::vector paths; + for (const auto* element : svg.getChildIterator()) + if (element->hasTagName("path")) + paths.push_back({ element->getStringAttribute("fill"), + juce::Drawable::parseSVGPath(element->getStringAttribute("d")) }); + const auto pathAt = [&paths](juce::Point centre, bool led) -> const juce::Path* { + for (const auto& item : paths) + if ((led ? item.fill == "#6C0455" + : item.fill == "#676767" || item.fill == "#DA2E2E" + || item.fill == "#607EA7") + && item.path.getBounds().getCentre().getDistanceFrom(centre) < 0.1f) + return &item.path; + return nullptr; + }; + std::vector compactRegions; + for (const auto& button : wave::ui::compact::buttons) + { + const auto original = std::find_if(panelRegions.begin(), panelRegions.end(), + [&button](const auto& region) { + return !region.analog && region.hardwareId == button.serial; + }); + const juce::Point centre { button.x, button.y }; + if (original == panelRegions.end()) + continue; + if (const auto* path = pathAt(centre, false)) + { + auto region = *original; + region.artworkScale = path->getBounds().getWidth() + / original->path.getBounds().getWidth(); + region.path = *path; + region.centre = centre; + compactRegions.push_back(std::move(region)); + } + } + // The LCD bank is scaled to 82% in this SVG. Read the recess paths and + // retain the physical left-to-right ADC routing from PanelWiring.h. + std::vector faders; + for (const auto& item : paths) + if (item.fill == "#3C3953" && item.path.getBounds().getHeight() > 100.0f) + faders.push_back(item.path); + std::sort(faders.begin(), faders.end(), [](const auto& left, const auto& right) { + return left.getBounds().getCentreX() < right.getBounds().getCentreX(); + }); + for (size_t index = 0; index < faders.size() + && index < wave::panel::performanceFaderAdcChannels.size(); ++index) + { + PanelRegion region; + region.path = faders[index]; + region.centre = region.path.getBounds().getCentre(); + region.analog = region.fader = true; + region.faderIndex = static_cast(index); + region.hardwareId = wave::panel::performanceFaderAdcChannels[index]; + region.artworkScale = 0.82f; + region.faderTrackTop = 265.6f; + region.faderTrackBottom = 366.46f; + compactRegions.push_back(std::move(region)); + } + panelRegions = std::move(compactRegions); + panelLeds.clear(); + for (const auto& led : wave::ui::compact::leds) + { + const juce::Point centre { led.x, led.y }; + if (const auto* path = pathAt(centre, true)) + panelLeds.push_back({ centre, led.redSerial, led.greenSerial, + path->getBounds().getWidth() }); + } +} + +juce::Result WaveEmulationAudioProcessorEditor::loadPanelSkin(const juce::File& file, + bool remember) +{ + const auto xml = juce::XmlDocument::parse(file); + if (xml == nullptr || !xml->hasTagName("svg")) + return juce::Result::fail("Choose a valid SVG panel skin."); + auto viewBox = juce::StringArray::fromTokens(xml->getStringAttribute("viewBox"), " ,\t\r\n", ""); + viewBox.removeEmptyStrings(); + if (viewBox.size() != 4 || viewBox[0].getDoubleValue() != 0.0 + || viewBox[1].getDoubleValue() != 0.0 + || !juce::approximatelyEqual(viewBox[2].getDoubleValue(), static_cast(designWidth)) + || !juce::approximatelyEqual(viewBox[3].getDoubleValue(), static_cast(designHeight)) + || !juce::approximatelyEqual(xml->getDoubleAttribute("width"), static_cast(designWidth)) + || !juce::approximatelyEqual(xml->getDoubleAttribute("height"), static_cast(designHeight))) + return juce::Result::fail("Panel skins must use width=2338, height=1042 and viewBox=\"0 0 2338 1042\". Keep controls in their original positions."); + auto artwork = juce::Drawable::createFromSVG(*xml); + if (artwork == nullptr) + return juce::Result::fail("The SVG panel skin could not be rendered."); + if (remember) + { + const auto result = ownerProcessor.rememberPanelSkin(file); + if (result.failed()) + return result; + } + const auto scale = static_cast(getWidth()) / panelDesignWidth(); + applyPanelLayout(false, scale); + panelArtwork = std::move(artwork); + panelSkinFile = file; + // External skin geometry comes from the original panel, so changing + // label paths/groups cannot change firmware wiring or fader destinations. + rebuildPanelImage(); + repaint(); + return juce::Result::ok(); +} + +void WaveEmulationAudioProcessorEditor::useDefaultPanelSkin() +{ + const auto xml = juce::XmlDocument::parse(juce::String::fromUTF8( + WaveAssets::WaldorfWaveUI_NOLOGO_svg, WaveAssets::WaldorfWaveUI_NOLOGO_svgSize)); + if (xml == nullptr) + return; + const auto result = ownerProcessor.rememberPanelSkin({}); + if (result.failed()) + { + showDiskError("Panel Skin", result); + return; + } + applyPanelLayout(false, static_cast(getWidth()) / panelDesignWidth()); +} + +void WaveEmulationAudioProcessorEditor::showPanelSkinChooser() +{ + panelSkinChooser = std::make_unique( + "Load Alternative Panel Skin", panelSkinFile, "*.svg"); + panelSkinChooser->launchAsync(juce::FileBrowserComponent::openMode + | juce::FileBrowserComponent::canSelectFiles, + [safe = juce::Component::SafePointer(this)](const juce::FileChooser& chooser) { + if (safe == nullptr || chooser.getResult() == juce::File{}) + return; + const auto result = safe->loadPanelSkin(chooser.getResult()); + if (result.failed()) + safe->showDiskError("Panel Skin", result); + }); +} diff --git a/Source/PluginEditor.h b/Source/PluginEditor.h index e11184d..8f90200 100644 --- a/Source/PluginEditor.h +++ b/Source/PluginEditor.h @@ -10,12 +10,19 @@ class WaveEmulationAudioProcessorEditor final : public juce::AudioProcessorEditor, private juce::Timer, - private juce::MenuBarModel + private juce::MenuBarModel, + public juce::TooltipClient { public: explicit WaveEmulationAudioProcessorEditor(WaveEmulationAudioProcessor&); ~WaveEmulationAudioProcessorEditor() override; + juce::String getTooltip() override; + [[nodiscard]] juce::String tooltipAt(juce::Point editorPoint) const; + juce::Result loadPanelSkin(const juce::File& file, bool remember = true); + void useDefaultPanelSkin(); + void useCompactPanelSkin(); + void paint(juce::Graphics&) override; void resized() override; void mouseDown(const juce::MouseEvent&) override; @@ -26,13 +33,6 @@ class WaveEmulationAudioProcessorEditor final : public juce::AudioProcessorEdito bool keyStateChanged(bool isKeyDown) override; void focusLost(FocusChangeType) override; - enum class PanelLayout - { - full = 0, - noKeyboard = 1, - panelOnly = 2 - }; - private: class WaveLookAndFeel; class ParameterKnob; @@ -60,6 +60,7 @@ class WaveEmulationAudioProcessorEditor final : public juce::AudioProcessorEdito int faderIndex = -1; float faderTrackTop = 0.0f; float faderTrackBottom = 0.0f; + float artworkScale = 1.0f; }; struct PanelLed @@ -67,6 +68,7 @@ class WaveEmulationAudioProcessorEditor final : public juce::AudioProcessorEdito juce::Point centre; int redSerialCode = -1; int greenSerialCode = -1; + float size = 6.0f; }; ParameterKnob& addKnob(const juce::String& parameterId, const juce::String& displayName, @@ -76,6 +78,10 @@ class WaveEmulationAudioProcessorEditor final : public juce::AudioProcessorEdito void updateLfoKnobBindings(); void updateWaveEnvelopeKnobBindings(); void initialisePanelRegions(const juce::XmlElement& svg); + void initialiseCompactPanelRegions(const juce::XmlElement& svg); + void applyPanelLayout(bool compact, float scale); + [[nodiscard]] float panelDesignWidth() const noexcept; + [[nodiscard]] float panelDesignHeight() const noexcept; void synchroniseFaderValues() noexcept; void rebuildPanelImage(); bool handlePerformanceControl(juce::Point designPoint); @@ -88,35 +94,36 @@ class WaveEmulationAudioProcessorEditor final : public juce::AudioProcessorEdito void releaseComputerKeyboardNotes(); void releaseComputerKeyboardShift(); void timerCallback() override; - [[nodiscard]] float visibleDesignHeight() const noexcept; - [[nodiscard]] float currentScale() const noexcept; - [[nodiscard]] float fitToScreenScale() const; - [[nodiscard]] juce::Rectangle fullArtworkBounds(float pixelScale) const noexcept; - void applyLayout(PanelLayout layout, float scale); - void stepZoom(int direction); juce::StringArray getMenuBarNames() override; juce::PopupMenu getMenuForIndex(int topLevelMenuIndex, const juce::String& menuName) override; void menuItemSelected(int menuItemId, int topLevelMenuIndex) override; void showSystemMenu(); void showFirmwareFolderChooser(); + void showPanelSkinChooser(); void showDiskImageChooser(); void showCreateBlankDiskChooser(); void showCreateDiskFromSetChooser(); + void showCreateDiskFromWavetableChooser(); void showDiskDestinationChooser(const juce::File& waveSetup); void showSaveDiskAsChooser(); void showDiskError(const juce::String& title, const juce::Result& result); + void setWindowScale(float scale); + void setKeyboardVisible(bool visible); + [[nodiscard]] float activeDesignHeight() const noexcept; + [[nodiscard]] float fitToScreenScale() const; + void restoreWindowPreferences(); + void saveWindowPreferences(); WaveEmulationAudioProcessor& ownerProcessor; - std::unique_ptr uiSettings; - PanelLayout panelLayout = PanelLayout::full; - bool layoutInitialised = false; - juce::Colour keybedCoverColour { 0xff2b2b3f }; std::unique_ptr lookAndFeel; std::vector> knobs; std::unique_ptr lcd; std::unique_ptr panelArtwork; juce::Image panelImage; + juce::File panelSkinFile; + juce::TooltipWindow tooltipWindow { this, 650 }; + std::unique_ptr panelSkinChooser; std::unique_ptr sliderArtwork; std::unique_ptr knobArtwork; std::unique_ptr redKnobArtwork; @@ -160,6 +167,10 @@ class WaveEmulationAudioProcessorEditor final : public juce::AudioProcessorEdito std::array performanceWheelValues { 0.5f, 0.0f, 0.5f }; std::array keyboardNotes{}; bool computerShiftDown = false; + bool keyboardVisible = true; + std::unique_ptr windowSettings; + bool windowPreferencesRestored = false; + bool compactSkin = false; bool performanceMode = true; int selectedLfo = 0; int waveEnvelopePage = 0; diff --git a/Source/PluginProcessor.cpp b/Source/PluginProcessor.cpp index 7f87afd..06b8e3d 100644 --- a/Source/PluginProcessor.cpp +++ b/Source/PluginProcessor.cpp @@ -492,6 +492,7 @@ bool applyFirmwareModifierRouting( if (!initialSource && hostSourceChanged) { storedSource = juce::jlimit(0, 39, hostSource); + effectiveSources[routeIndex] = storedSource; firmware.writeCurrentSoundRecordByte( static_cast(layout.sourceOffset), static_cast(storedSource)); @@ -527,6 +528,7 @@ bool applyFirmwareModifierRouting( if (layout.controlOffset >= 0 && !initialControl && hostControlChanged) { storedControl = juce::jlimit(0, 39, hostControl); + effectiveControls[routeIndex] = storedControl; firmware.writeCurrentSoundRecordByte( static_cast(layout.controlOffset), static_cast(storedControl)); @@ -579,6 +581,13 @@ bool applyFirmwareModifierRouting( ? (juce::roundToInt(hostAmount) + 8) * 8 : juce::roundToInt(hostAmount) + 64; effectiveStoredAmount = juce::jlimit(0, 127, effectiveStoredAmount); + // A host write can coincide with an ADC edit. Since that write + // wins in the native record, it must also win in the published + // Sound; otherwise Instrument switching restores the older ADC + // amount even though the live record contains the host value. + effectiveAmounts[routeIndex] = layout.volumeAmount + ? static_cast(effectiveStoredAmount / 8 - 8) + : static_cast(effectiveStoredAmount - 64); firmware.writeCurrentSoundRecordByte( static_cast(layout.amountOffset), static_cast(effectiveStoredAmount)); @@ -592,7 +601,8 @@ bool applyFirmwareModifierRouting( } } // namespace -WaveEmulationAudioProcessor::WaveEmulationAudioProcessor(const juce::File& preferenceFile) +WaveEmulationAudioProcessor::WaveEmulationAudioProcessor(const juce::File& preferenceFile, + InitialBank initialBank) : AudioProcessor(BusesProperties().withOutput("Output", juce::AudioChannelSet::stereo(), true)), parameters(*this, nullptr, "WaveState", wave::parameters::createLayout()), firmwarePreferenceFile(preferenceFile == juce::File{} @@ -618,6 +628,8 @@ WaveEmulationAudioProcessor::WaveEmulationAudioProcessor(const juce::File& prefe std::memory_order_relaxed); for (auto& value : pendingFirmwareGlideValues) value.store(-1000, std::memory_order_relaxed); + for (auto& value : pendingGlideFaderEdits) + value.store(-1, std::memory_order_relaxed); lastFirmwarePanelPotRecordBytes.fill(-1); lastHostPanelPotValues.fill(std::numeric_limits::quiet_NaN()); lastFirmwareGlideRecordBytes.fill(-1); @@ -644,10 +656,55 @@ WaveEmulationAudioProcessor::WaveEmulationAudioProcessor(const juce::File& prefe runtime.attachSharedMemory(sharedFirmwareMemory); runtime.setBoardIndex(board); } - loadEmbeddedFactorySet(); + if (initialBank == InitialBank::embeddedFactory) + loadEmbeddedFactorySet(); loadEmbeddedPrivateRoms(); - applyFactoryProgram(0, false); + if (initialBank == InitialBank::embeddedFactory) + applyFactoryProgram(0, false); loadRememberedFirmware(); + if (initialBank == InitialBank::embeddedFactory) + // The factory boot already installs Performance 0. A second recall + // from loading remembered firmware can discard early panel events. + pendingFirmwareProgram.store(-1, std::memory_order_release); + if (initialBank != InitialBank::embeddedFactory) + { + resetToColdStart(); + // Each instance gets writable media independent of the bundled image. + // Host/session recall subsequently replaces this with its own image. + restoredHostStateDirectory = juce::File::getSpecialLocation(juce::File::tempDirectory) + .getChildFile(hostStateDirectoryName).getChildFile(hostStateInstanceId); + if (restoredHostStateDirectory.createDirectory().wasOk()) + { + const auto image = restoredHostStateDirectory.getChildFile("Blank Wave.img"); + if (initialBank == InitialBank::initialised) + (void) loadDefaultBank(image); + else + (void) createBlankDiskImage(image); + } + } +} + +juce::Result WaveEmulationAudioProcessor::loadDefaultBank(const juce::File& image) +{ + if (!image.replaceWithData(WaveAssets::BlankWave_img, + static_cast(WaveAssets::BlankWave_imgSize))) + return juce::Result::fail("The default blank disk image could not be created."); + const auto mounted = mountDiskImage(image); + if (mounted.failed()) + return mounted; + const auto set = currentPerformanceSet(); + if (set == nullptr || !set->isLoaded()) + return juce::Result::fail("The default disk image contains no valid Wave SET."); + + // Startup loads the SET directly into native SRAM; it does not leave a + // Disk/Import confirmation or depend on a later user-triggered disk read. + pendingDiskSetActivation.store(false, std::memory_order_release); + pendingDiskSetBytes.store(0, std::memory_order_release); + diskSetImportConfirmationPending.store(false, std::memory_order_release); + masterFirmware.installSoundBank(set->soundBank()); + masterFirmware.installPerformanceBank(set->performanceBank()); + setCurrentProgram(0); + return juce::Result::ok(); } WaveEmulationAudioProcessor::~WaveEmulationAudioProcessor() @@ -694,10 +751,12 @@ juce::Result WaveEmulationAudioProcessor::mountDiskImage(const juce::File& image { returnToPerformanceAfterDiskImport.store(false, std::memory_order_release); - returnToPerformanceAfterStoreExit.store(false, + storeSaveCompletionPending.store(false, std::memory_order_release); + storeExitModePending.store(false, std::memory_order_release); pendingDiskSetBytes.store(0, std::memory_order_release); pendingDiskSetActivation.store(false, std::memory_order_release); + pendingManagerExitProgram.store(-1, std::memory_order_release); diskSetImportConfirmationPending.store(false, std::memory_order_release); const auto result = masterFirmware.mountDiskImage(image); @@ -753,6 +812,19 @@ juce::Result WaveEmulationAudioProcessor::createBlankDiskImage( return mountDiskImage(output); } +juce::Result WaveEmulationAudioProcessor::createDiskImageFromWavetable( + const juce::File& wavetable, const juce::File& destination) +{ + auto output = destination; + if (output.getFileExtension().isEmpty()) + output = output.withFileExtension(".img"); + const auto created = wave::firmware::DosFloppyImage::createWithWaveWavetable( + output, wavetable); + if (created.failed()) + return created; + return mountDiskImage(output); +} + juce::Result WaveEmulationAudioProcessor::flushMountedDiskImage() { return masterFirmware.flushDiskImage(); @@ -802,11 +874,13 @@ juce::Result WaveEmulationAudioProcessor::ejectDiskImage() { pendingDiskSetBytes.store(0, std::memory_order_release); pendingDiskSetActivation.store(false, std::memory_order_release); + pendingManagerExitProgram.store(-1, std::memory_order_release); diskSetImportConfirmationPending.store(false, std::memory_order_release); returnToPerformanceAfterDiskImport.store(false, std::memory_order_release); - returnToPerformanceAfterStoreExit.store(false, + storeSaveCompletionPending.store(false, std::memory_order_release); + storeExitModePending.store(false, std::memory_order_release); removeRestoredHostStateDisk(); parameters.state.removeProperty("mountedDiskImage", nullptr); @@ -814,6 +888,30 @@ juce::Result WaveEmulationAudioProcessor::ejectDiskImage() return result; } +juce::Result WaveEmulationAudioProcessor::reloadBankFromMountedImage() +{ + const juce::ScopedLock callbackLock(getCallbackLock()); + wave::firmware::DosFloppyImage::SetupFile setup; + const auto read = wave::firmware::DosFloppyImage::readWaveSetup( + masterFirmware.mountedDiskImageFile(), setup); + if (read.failed()) + return read; + wave::presets::WaveFactorySet set; + if (!set.load(setup.data).validLayout) + return juce::Result::fail("The mounted image contains no valid Wave bank."); + juce::MemoryBlock saved; + getStateInformation(saved); + const auto xml = getXmlFromBinary(saved.getData(), static_cast(saved.getSize())); + auto state = juce::ValueTree::fromXml(*xml); + state.setProperty("machineActiveSetData", juce::var(setup.data), nullptr); + state.setProperty("machineHasActiveSet", true, nullptr); + for (const auto* key : { "machinePerformanceSnapshot", "machineFirmwareEditBuffers" }) + state.removeProperty(key, nullptr); + copyXmlToBinary(*state.createXml(), saved); + setStateInformation(saved.getData(), static_cast(saved.getSize())); + return juce::Result::ok(); +} + void WaveEmulationAudioProcessor::resetToColdStart() { suspendProcessing(true); @@ -825,9 +923,13 @@ void WaveEmulationAudioProcessor::resetToColdStart() instrumentEditPage.store(0, std::memory_order_release); for (auto& value : pendingInstrumentFaderEdits) value.store(-1, std::memory_order_release); + for (auto& value : pendingGlideFaderEdits) + value.store(-1, std::memory_order_release); instrumentPageReady.store(false, std::memory_order_release); startInstrumentPageSelectionDelay.store(false, std::memory_order_release); pendingFirmwareSoftButton.store(-1, std::memory_order_release); + pendingPanelCancel.store(false, std::memory_order_release); + pendingManagerExitProgram.store(-1, std::memory_order_release); pendingFirmwarePageButton.store(-1, std::memory_order_release); pendingFirmwareModeButton.store(-1, std::memory_order_release); pendingFirmwareGlideSwitchClicks.store(0, std::memory_order_release); @@ -845,11 +947,13 @@ void WaveEmulationAudioProcessor::resetToColdStart() pendingPanelPerformance.store(-1, std::memory_order_release); pendingDiskSetBytes.store(0, std::memory_order_release); pendingDiskSetActivation.store(false, std::memory_order_release); + pendingManagerExitProgram.store(-1, std::memory_order_release); diskSetImportConfirmationPending.store(false, std::memory_order_release); returnToPerformanceAfterDiskImport.store(false, std::memory_order_release); - returnToPerformanceAfterStoreExit.store(false, + storeSaveCompletionPending.store(false, std::memory_order_release); + storeExitModePending.store(false, std::memory_order_release); keyboardOctaveShift.store(0, std::memory_order_release); pendingKeyboardOctaveRestore.store(2, std::memory_order_release); @@ -921,6 +1025,11 @@ void WaveEmulationAudioProcessor::setCurrentProgram(int index) } const auto bounded = juce::jlimit(0, wave::presets::WaveFactorySet::programCount - 1, index); + const auto managerExitPending + = pendingManagerExitProgram.load(std::memory_order_acquire) >= 0; + const auto leaveCompletedStore = managerExitPending + || (storeMenuActive.load(std::memory_order_acquire) + && completedStoreMode.load(std::memory_order_acquire) >= 0); armPanelPotProgramRecallGuard(); instrumentButtonMode.store(static_cast(InstrumentButtonMode::normal), std::memory_order_release); @@ -928,7 +1037,12 @@ void WaveEmulationAudioProcessor::setCurrentProgram(int index) pendingInstrumentPageSelection.store(-1, std::memory_order_release); instrumentPageReady.store(false, std::memory_order_release); startInstrumentPageSelectionDelay.store(false, std::memory_order_release); - pendingFirmwareSoftButton.store(-1, std::memory_order_release); + if (!managerExitPending) + { + pendingFirmwareSoftButton.store(-1, std::memory_order_release); + pendingPanelCancel.store(false, std::memory_order_release); + pendingManagerExitProgram.store(-1, std::memory_order_release); + } pendingFirmwarePageButton.store(-1, std::memory_order_release); pendingFirmwareModeButton.store(-1, std::memory_order_release); panelModeDisplayTransitionActive.store(false, std::memory_order_release); @@ -940,14 +1054,24 @@ void WaveEmulationAudioProcessor::setCurrentProgram(int index) // -/+ contacts are not misrouted to the page we just left. diskMenuActive.store(false, std::memory_order_release); storeMenuActive.store(false, std::memory_order_release); - returnToPerformanceAfterStoreExit.store(false, + storeSaveCompletionPending.store(false, std::memory_order_release); + storeExitModePending.store(false, std::memory_order_release); panelSelectedMode.store(39, std::memory_order_release); panelSelectedEdit.store(-1, std::memory_order_release); cancelPanelStepButtonEvents.store(true, std::memory_order_release); currentProgram = bounded; parameters.state.setProperty("factoryProgram", bounded, nullptr); - applyFactoryProgram(bounded, true); + applyFactoryProgram(bounded, !leaveCompletedStore); + if (leaveCompletedStore) + { + // A completed Store still owns the native chooser. Exit it before + // recalling the requested program, retaining one Cancel transaction + // while rapid browsing clicks update its destination. + pendingManagerExitProgram.store(bounded, std::memory_order_release); + if (!managerExitPending) + pendingPanelCancel.store(true, std::memory_order_release); + } updateHostDisplay(ChangeDetails{}.withProgramChanged(true) .withNonParameterStateChanged(true)); } @@ -993,7 +1117,10 @@ bool WaveEmulationAudioProcessor::selectPerformanceInstrument(int instrument) return false; const auto current = std::atomic_load_explicit( &factoryPerformance, std::memory_order_acquire); - if (current == nullptr || !current->layers[static_cast(instrument)].enabled) + if (current == nullptr + || (!current->layers[static_cast(instrument)].enabled + && (panelSelectedMode.load(std::memory_order_acquire) != 36 + || masterFirmware.currentInstrumentEditTarget() != instrument))) return false; static constexpr std::array instrumentCodes { 22, 25, 26, 27, 79, 28, 29, 30 }; @@ -1008,8 +1135,11 @@ bool WaveEmulationAudioProcessor::selectPerformanceInstrument(int instrument) if (physicalSelectionInFlight || !masterFirmware.isLoaded()) return; cancelActiveInstrumentSelection.store(true, std::memory_order_release); + const auto firmwareTarget = panelSelectedMode.load(std::memory_order_acquire) == 36 + ? masterFirmware.currentInstrumentEditTarget() + : masterFirmware.currentPerformanceInstrument(); pendingFirmwareInstrument.store( - masterFirmware.currentPerformanceInstrument() == instrument + firmwareTarget == instrument ? -1 : instrument, std::memory_order_release); }; @@ -1404,23 +1534,14 @@ void WaveEmulationAudioProcessor::processBlock(juce::AudioBuffer& buffer, transposedLocalKeyboardMidi.addEvent(message, metadata.samplePosition); } localKeyboardMidi.swapWith(transposedLocalKeyboardMidi); - // Button 1/2 modes are owned by the keyboard firmware. Their genuine LED - // outputs are the authoritative latched/touch state presented to the two - // modulation sources; the editor never guesses a mode from mouse state. - constexpr std::array keyboardButtonLedSerials { 16, 35 }; - for (size_t button = 0; button < keyboardButtonLedSerials.size(); ++button) - { - const auto state = masterFirmware.panelLed( - keyboardButtonLedSerials[button]) - ? 1 : 0; - if (state == lastKeyboardAssignableButtonStates[button]) - continue; - lastKeyboardAssignableButtonStates[button] = state; - localKeyboardMidi.addEvent( - juce::MidiMessage::controllerEvent( - 1, 80 + static_cast(button), state != 0 ? 127 : 0), - 0); - } + // OS 1.700 owns touch/toggle mode and the lamps reflect its actual state. + // Do not disguise these dedicated sources as CC80/81: MIDI assignments + // are Performance bytes 4/5 and may coincide with each other or a wheel. + engine.setKeyboardButtons(masterFirmware.panelLed(16), masterFirmware.panelLed(35)); + if (const auto performance = masterFirmware.currentPerformanceRecordOffset()) + engine.setKeyboardButtonControllers( + masterFirmware.sharedProgramByte(*performance + 4u) & 0x7fu, + masterFirmware.sharedProgramByte(*performance + 5u) & 0x7fu); const auto selectionVersionBefore = performanceInstrumentSelectionVersion.load(std::memory_order_acquire); auto editedSound = wave::parameters::readSnapshot(parameters); @@ -1577,52 +1698,16 @@ void WaveEmulationAudioProcessor::processBlock(juce::AudioBuffer& buffer, for (size_t offset = 0; offset < liveRecord.size(); ++offset) liveRecord[offset] = masterFirmware.currentSoundRecordByte( static_cast(offset)); - // During the initial SET import, OS 1.700 copies a nonzero Wavetable - // selector into its live edit buffer one count lower than the original - // Instrument-local record. Once that record is installed directly in - // the cache (or edited from the panel), it uses the normal selector. - // Reconcile that one import edge exactly once per Instrument. Treating - // every later live byte as import-encoded would increment the selector - // on every softbutton press; never reconciling it steps A045/A051 to an - // adjacent table as soon as their selected Instrument changes. - auto persistentRecord = liveRecord; - const auto selectedIndex = static_cast(*firmwareInstrument); - if (!activeInstrumentSoundRecordReconciled[selectedIndex] - && activeInstrumentSoundPerformance == *firmwarePerformance - && activeInstrumentSoundRecordValid[selectedIndex]) - { - const auto seededSelector - = activeInstrumentSoundRecords[selectedIndex][25]; - if (liveRecord[25] < 0x7fu - && static_cast(liveRecord[25] + 1u) - == seededSelector) - { - persistentRecord[25] = seededSelector; - activeInstrumentSoundRecordReconciled[selectedIndex] = true; - activeInstrumentSoundRecordUsesImportEncoding[selectedIndex] - = true; - } - else if (liveRecord[25] != seededSelector) - { - // A value other than the seed or its import encoding is a - // genuine edit, so this record is already in the live/cache - // representation from now on. - activeInstrumentSoundRecordReconciled[selectedIndex] = true; - activeInstrumentSoundRecordUsesImportEncoding[selectedIndex] - = false; - } - // Equality can be observed briefly before the OS completes its - // import conversion. Keep waiting instead of prematurely marking - // this Instrument reconciled. - } - else if (activeInstrumentSoundRecordUsesImportEncoding[selectedIndex] - && persistentRecord[25] < 0x7fu) - { - ++persistentRecord[25]; - } publishHostMachineSnapshot(*firmwarePerformance, *firmwareInstrument, - persistentRecord); - firmwareSelectedSound = decodeFactorySound(persistentRecord); + liveRecord); + firmwareSelectedSound = decodeFactorySound(liveRecord); + // Store updates the firmware's Sound bank, while the originally loaded + // SET can still contain an older octave. Recall must follow the actual + // selected Sound bytes, just like the other native synthesis fields. + for (size_t oscillator = 0; oscillator < panelOscillatorOctaves.size(); ++oscillator) + panelOscillatorOctaves[oscillator].store( + firmwareSelectedSound->oscillatorOctaves[oscillator], + std::memory_order_release); // Modifier selectors also support host automation. The reconciliation // above has already resolved firmware edits versus a genuine host // change for this block, so retain only that resolved route set rather @@ -1688,8 +1773,6 @@ void WaveEmulationAudioProcessor::processBlock(juce::AudioBuffer& buffer, renderedSound.panModulationMode = nativeSound.panModulationMode; renderedSound.driveDb = editedSound.driveDb; renderedSound.quickEditAmounts = editedSound.quickEditAmounts; - renderedSound.oscillatorOctaves[0] = getFirmwareOscillatorOctave(0); - renderedSound.oscillatorOctaves[1] = getFirmwareOscillatorOctave(1); wave::parameters::applyQuickEdit(renderedSound); performance.layers[static_cast(editable)].sound = renderedSound; } @@ -1816,8 +1899,7 @@ void WaveEmulationAudioProcessor::advanceFirmware(int samples) filterCalibrationServiceExitPending.store(false, std::memory_order_release); } - const auto selected = (static_cast(masterFirmware.localByte(0x54b40u)) << 8) - | static_cast(masterFirmware.localByte(0x54b41u)); + auto selected = masterFirmware.currentPerformanceId().value_or(-1); auto refreshSelectedPerformancePage = false; const auto expected = pendingPanelPerformance.load(std::memory_order_acquire); if (expected >= 0) @@ -1828,7 +1910,10 @@ void WaveEmulationAudioProcessor::advanceFirmware(int samples) refreshSelectedPerformancePage = true; } } - else if (selected >= 0 + else if (!pendingDiskSetActivation.load(std::memory_order_acquire) + && pendingManagerExitProgram.load(std::memory_order_acquire) < 0 + && pendingFirmwareProgram.load(std::memory_order_acquire) < 0 + && selected >= 0 && selected < wave::presets::WaveFactorySet::programCount && selected != currentProgram.load(std::memory_order_acquire)) { @@ -1838,23 +1923,55 @@ void WaveEmulationAudioProcessor::advanceFirmware(int samples) } // Mounting media only inserts the disk. Total Recall is complete once - // OS 1.700 has transferred at least the SET payload through the real - // FDC register path. Force one engine decode at that boundary because + // OS 1.700 has transferred the SET through the real FDC register path + // and closed its confirmation requester. Directory reads contribute + // to the byte count, so that count alone can fire during the load. + // Force one engine decode at that boundary because // A001 may have the same numeric index as the preceding empty INIT // state and therefore cannot be detected by an index-change test. if (pendingDiskSetActivation.load(std::memory_order_acquire) && masterFirmware.mountedDiskBytesRead() >= pendingDiskSetBytes.load(std::memory_order_acquire) - && selected >= 0 - && selected < wave::presets::WaveFactorySet::programCount) + && !firmwareRequesterActive.load(std::memory_order_acquire) + && !masterFirmware.panelButtonPressed(70)) { pendingDiskSetActivation.store(false, std::memory_order_release); + if (diskSetImportConfirmationPending.exchange( + false, std::memory_order_acq_rel) + && diskMenuActive.exchange(false, std::memory_order_acq_rel)) + { + // Disk/Load needs more than one OK: the first opens the file + // selector, and the next starts Total Recall. Only the SET + // transfer proves the operation has finished. + panelSelectedMode.store(39, std::memory_order_release); + panelSelectedEdit.store(-1, std::memory_order_release); + panelModeDisplayTransitionActive.store(true, + std::memory_order_release); + panelModeDisplayAwaitingDispatch.store(true, + std::memory_order_release); + // Total Recall returns to the Disk manager. Exit that native + // workspace before selecting the new bank: a Performance + // contact alone is rejected while the manager owns input. + selected = 0; + pendingManagerExitProgram.store(selected, std::memory_order_release); + pendingPanelCancel.store(true, std::memory_order_release); + } + if (const auto set = currentPerformanceSet(); set != nullptr) + { + masterFirmware.installSoundBank(set->soundBank()); + masterFirmware.installPerformanceBank(set->performanceBank()); + } pendingEngineProgram.store(selected, std::memory_order_release); triggerAsyncUpdate(); refreshSelectedPerformancePage = true; } - if (refreshSelectedPerformancePage) + if (refreshSelectedPerformancePage + && !storeMenuActive.load(std::memory_order_acquire) + && pendingManagerExitProgram.load(std::memory_order_acquire) < 0) { + // Total Recall still needs the Disk Manager's Cancel callbacks + // until its exit transaction finishes. The subsequent program + // recall supplies the Performance redraw after that release. installFactoryEditRecords(selected); masterFirmware.refreshCurrentScreenFromFirmware(); } @@ -1914,10 +2031,14 @@ void WaveEmulationAudioProcessor::handleAsyncUpdate() // Recall from disk) also retires the preceding Disk/Option context. // The LCD remains firmware-owned; this only synchronises subsequent // serial-button routing and the mutually-exclusive mode lamps. - diskMenuActive.store(false, std::memory_order_release); - storeMenuActive.store(false, std::memory_order_release); - panelSelectedMode.store(39, std::memory_order_release); - panelSelectedEdit.store(-1, std::memory_order_release); + // Store selects its destination while its dialog still owns input. + // Keep that context until Cancel completes the native exit. + if (!storeMenuActive.load(std::memory_order_acquire)) + { + diskMenuActive.store(false, std::memory_order_release); + panelSelectedMode.store(39, std::memory_order_release); + panelSelectedEdit.store(-1, std::memory_order_release); + } currentProgram.store(selected, std::memory_order_release); parameters.state.setProperty("factoryProgram", selected, nullptr); // OS 1.700 has already performed the selection and owns the LCD. Decode @@ -2010,8 +2131,55 @@ void WaveEmulationAudioProcessor::synchroniseInstrumentSoundSeed() noexcept activeInstrumentSoundPerformance = seed->performance; activeInstrumentSoundRecords = seed->records; activeInstrumentSoundRecordValid = seed->valid; - activeInstrumentSoundRecordReconciled.fill(false); - activeInstrumentSoundRecordUsesImportEncoding.fill(false); + // The imported SET is only an initial seed. Native Store updates the bank + // in SRAM, so a new Performance must create its private Instrument edits + // from those saved records, not resurrect the SET's older parameter bytes. + const auto performanceOffset = 0x28000u + + static_cast(seed->performance) * 512u; + if (masterFirmware.isLoaded() + && masterFirmware.sharedProgramByte(performanceOffset + 48u) == 0x55u) + { + for (size_t instrument = 0; instrument < activeInstrumentSoundRecords.size(); ++instrument) + { + const auto assignment = performanceOffset + 64u + + static_cast(instrument) * 32u; + const auto soundId = (masterFirmware.sharedProgramByte(assignment) + | (masterFirmware.sharedProgramByte(assignment + 1u) << 7u)) & 0xffu; + const auto soundOffset = 0x18000u + static_cast(soundId) * 256u; + auto& record = activeInstrumentSoundRecords[instrument]; + std::array stored {}; + for (size_t byte = 0; byte < stored.size(); ++byte) + stored[byte] = masterFirmware.sharedProgramByte( + soundOffset + static_cast(byte)); + // An unpopulated startup slot still needs the imported seed. + if (std::any_of(stored.begin(), stored.end(), [](uint8_t byte) { return byte != 0; })) + record = stored; + } + // Unselected layers also sound immediately after recall. Refresh their + // DSP snapshots at the same boundary as their private edit buffers. + const auto current = std::atomic_load_explicit(&factoryPerformance, std::memory_order_acquire); + if (current != nullptr) + { + auto recalled = std::make_shared(*current); + for (size_t instrument = 0; instrument < recalled->layers.size(); ++instrument) + { + if (!activeInstrumentSoundRecordValid[instrument]) + continue; + auto& sound = recalled->layers[instrument].sound; + auto saved = decodeFactorySound(activeInstrumentSoundRecords[instrument]); + saved.panAmount = sound.panAmount; + saved.panModulationMode = sound.panModulationMode; + saved.driveDb = sound.driveDb; + saved.quickEditAmounts = sound.quickEditAmounts; + saved.outputDb = sound.outputDb; + saved.circuitAgeAmount = sound.circuitAgeAmount; + sound = saved; + } + std::atomic_store_explicit(&factoryPerformance, + std::static_pointer_cast(recalled), + std::memory_order_release); + } + } appliedInstrumentSoundSeed = seed; } @@ -2092,9 +2260,6 @@ void WaveEmulationAudioProcessor::applyPendingHostMachineRestore() noexcept activeInstrumentSoundPerformance = pending->performance; activeInstrumentSoundRecords = pending->soundRecords; activeInstrumentSoundRecordValid = pending->soundRecordValid; - activeInstrumentSoundRecordReconciled.fill(false); - activeInstrumentSoundRecordUsesImportEncoding.fill(false); - activeInstrumentSoundRecordReconciled[static_cast(selected)] = true; masterFirmware.refreshCurrentScreenFromFirmware(); suspendFirmwareSoundFeedback(); modulationRoutingResetPending.store(true, std::memory_order_release); @@ -2125,23 +2290,10 @@ void WaveEmulationAudioProcessor::stageFirmwareInstrumentSound( { const auto currentIndex = static_cast(*currentInstrument); auto& currentRecord = activeInstrumentSoundRecords[currentIndex]; - const auto previousPersistentSelector = currentRecord[25]; for (size_t offset = 0; offset < wave::presets::WaveFactorySet::soundSize; ++offset) currentRecord[offset] = masterFirmware.currentSoundRecordByte( static_cast(offset)); - if (activeInstrumentSoundRecordUsesImportEncoding[currentIndex] - && currentRecord[25] < 0x7fu) - ++currentRecord[25]; - else if (!activeInstrumentSoundRecordReconciled[currentIndex] - && currentRecord[25] < 0x7fu - && static_cast(currentRecord[25] + 1u) - == previousPersistentSelector) - { - currentRecord[25] = previousPersistentSelector; - activeInstrumentSoundRecordUsesImportEncoding[currentIndex] = true; - } - activeInstrumentSoundRecordReconciled[currentIndex] = true; } // Two Instruments may intentionally assign the same stored Sound number @@ -2152,10 +2304,6 @@ void WaveEmulationAudioProcessor::stageFirmwareInstrumentSound( masterFirmware.installPerformanceInstrumentSoundRecord( targetInstrument, activeInstrumentSoundRecords[static_cast(targetInstrument)]); - activeInstrumentSoundRecordReconciled[static_cast(targetInstrument)] - = true; - activeInstrumentSoundRecordUsesImportEncoding[static_cast(targetInstrument)] - = false; suspendFirmwareSoundFeedback(); modulationRoutingResetPending.store(true, std::memory_order_release); } @@ -2163,7 +2311,52 @@ void WaveEmulationAudioProcessor::stageFirmwareInstrumentSound( void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& midi, int sampleCount) { + if (pendingNumericPanelInput.exchange(false, std::memory_order_acq_rel)) + masterFirmware.prepareNumericPanelInput(); + // The lower keyboard switches send serial press=1/release=0 events. + // Keep each edge until the genuine callback has applied its state: OS + // background work can consume a packet without dispatching it. + if (activeKeyboardButtonEvent >= 0) + { + const auto button = static_cast(activeKeyboardButtonEvent >> 1); + const auto serial = static_cast(3u + button); + const auto down = static_cast(activeKeyboardButtonEvent & 1); + const auto pending = masterFirmware.panelEventPending(0x80u, serial, down); + if (!pending && masterFirmware.localByte(0x58f78u + button) + == activeKeyboardButtonExpectedState) + { + if (down == 0u) + masterFirmware.releasePanelEventLatch(serial); + activeKeyboardButtonEvent = -1; + } + else if (!pending && --keyboardButtonRetryBlocks <= 0) + { + masterFirmware.pushPanelEvent(0x80u, serial, down); + keyboardButtonRetryBlocks = 8; + } + } + if (activeKeyboardButtonEvent < 0) + { + const auto event = keyboardButtonEventFifo.read(1); + if (event.blockSize1 != 0) + { + const auto packed = keyboardButtonEvents[static_cast(event.startIndex1)]; + const auto button = static_cast(packed >> 1u); + const auto down = static_cast(packed & 1u); + const auto state = masterFirmware.localByte(0x58f78u + button) != 0u; + const auto record = masterFirmware.currentPerformanceRecordOffset(); + const auto toggle = record.has_value() + && masterFirmware.sharedProgramByte(*record + 6u + button) != 0u; + activeKeyboardButtonExpectedState = toggle ? (down != 0u ? !state : state) + : down != 0u; + activeKeyboardButtonEvent = packed; + keyboardButtonRetryBlocks = 8; + masterFirmware.pushPanelEvent(0x80u, static_cast(3u + button), down); + } + } synchroniseInstrumentSoundSeed(); + if (const auto page = masterFirmware.currentInstrumentEditPage()) + instrumentEditPage.store(*page, std::memory_order_release); instrumentFaderRecordBaselineValid = false; if (panelSelectedMode.load(std::memory_order_acquire) == 36 && panelSelectedEdit.load(std::memory_order_acquire) < 0 @@ -2179,7 +2372,7 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi const auto instrument = (packedEdit >> 8) & 0x07; const auto firmwarePerformance = masterFirmware.currentPerformanceId(); const auto firmwareInstrument - = masterFirmware.currentPerformanceInstrument(); + = masterFirmware.currentInstrumentEditTarget(); const auto record = masterFirmware.currentPerformanceRecordOffset(); if (firmwarePerformance.has_value() && firmwareInstrument.has_value() && record.has_value() @@ -2204,8 +2397,13 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi } const auto cancelStepEvents = cancelPanelStepButtonEvents.exchange( false, std::memory_order_acq_rel); + const auto completedPerformanceStore + = storeMenuActive.load(std::memory_order_acquire) + && completedStoreMode.load(std::memory_order_acquire) == 39 + && !firmwareRequesterActive.load(std::memory_order_acquire); const auto performanceOwnsStepping - = panelSelectedMode.load(std::memory_order_acquire) == 39 + = (panelSelectedMode.load(std::memory_order_acquire) == 39 + || completedPerformanceStore) && panelSelectedEdit.load(std::memory_order_acquire) < 0; if (cancelStepEvents || performanceOwnsStepping) { @@ -2266,8 +2464,8 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi std::memory_order_release); // Requesters replace the otherwise inert CANCEL and OK action callbacks // in the OS-owned front-panel action table. This is the firmware's modal - // state, independent of LCD text or editor state. While either callback - // is installed, the physical panel accepts only those two contacts. + // state, independent of LCD text or editor state. The requester owns + // the panel; name editors also retain their cursor controls. const auto installedCancelAction = readFirmwareLong(cancelActionCallback); const auto installedOkAction = readFirmwareLong(okActionCallback); @@ -2278,6 +2476,31 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi firmwareRequesterActive.store( installedCancelAction != installedOkAction, std::memory_order_release); + if (storeSaveCompletionPending.load(std::memory_order_acquire) + && installedCancelAction == installedOkAction + && !masterFirmware.panelButtonPressed(70)) + { + // The naming requester has closed after OK. Store retains its native + // chooser for another save and redraws the preceding operating page. + // Restore that page's lamp as well: the record type being saved does + // not select a new operating mode in the native OS. + storeSaveCompletionPending.store(false, std::memory_order_release); + completedStoreMode.store(storeReturnMode.load(std::memory_order_acquire), + std::memory_order_release); + } + // Total Recall asks about optional machine-specific calibration only after + // the Sound/Performance banks have transferred. CANCEL here means "No"; + // it does not cancel the SET load or require reading its optional tail. + firmwareDiskCalibrationRequesterActive.store( + installedCancelAction == 0x0001f494u + && installedOkAction == 0x0001f488u, + std::memory_order_release); + // OS 1.700 installs these Page callbacks for DOS name entry (including + // Format's Diskname). Detect the actual editor, independent of panel mode. + firmwareDiskNameEditorActive.store( + readFirmwareLong(0x56698u) == 0x00013c1cu + && readFirmwareLong(0x566a8u) == 0x00013c34u, + std::memory_order_release); if (cancelInstrumentPanelEvents.exchange(false, std::memory_order_acq_rel)) { constexpr std::array instrumentCodes { 22, 25, 26, 27, @@ -2311,6 +2534,11 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi activeSoftButtonRetryCount = 0; activeSoftButtonInitialLcd.fill(0); } + if (pendingPanelCancel.exchange(false, std::memory_order_acq_rel)) + { + masterFirmware.releasePanelEventLatch(71); + pendingFirmwareSoftButton.store(71, std::memory_order_release); + } if (cancelInstrumentPageSelection.exchange(false, std::memory_order_acq_rel)) { pendingInstrumentPageSelection.store(-1, std::memory_order_release); @@ -2335,15 +2563,26 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi const auto shiftDown = keyboardControllerShiftDown.load(std::memory_order_acquire); if (shiftDown != firmwareKeyboardShiftDown) { - // The keyboard assembly reports its labelled ASCII command and the - // panel-event edge consumed by the Store page. Feed both genuine - // serial paths; the engine does not alter the firmware modifier or LCD. - masterFirmware.pushPanelEvent(0x80u, 83u, shiftDown ? 1u : 0u); firmwareKeyboardShiftDown = shiftDown; + firmwareKeyboardShiftRetryBlocks = 0; + } + if (shiftDown != (masterFirmware.localByte(0x59869u) != 0u) + && !masterFirmware.panelEventPending(0x80u, 83u, shiftDown ? 1u : 0u) + && --firmwareKeyboardShiftRetryBlocks <= 0) + { + // Serial 83 maps to native action 83, the keyboard Shift modifier. + // The Store page can consume this edge during redraw. + // Retry until its genuine handler acknowledges the physical state. + masterFirmware.pushPanelEvent(0x80u, 83u, shiftDown ? 1u : 0u); + firmwareKeyboardShiftRetryBlocks = 8; } - if (const auto requestedProgram = pendingFirmwareProgram.exchange( - -1, std::memory_order_acq_rel); + // A newer click can arrive while the previous program-change handler + // still owns its tagged MIDI cursor and edit records. Keep the latest + // destination queued until that recall finishes, rather than replacing + // its tag and stranding the held LCD frame. + if (const auto requestedProgram = masterFirmware.performanceSelectionPending() + ? -1 : pendingFirmwareProgram.exchange(-1, std::memory_order_acq_rel); requestedProgram >= 0) { pendingFirmwareGlideSwitchClicks.store(0, std::memory_order_release); @@ -2414,7 +2653,9 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi 0x80u, static_cast(activeInstrumentPanelDiagnosticCode), 1u) - && masterFirmware.currentPerformanceInstrument() + && (panelSelectedMode.load(std::memory_order_acquire) == 36 + ? masterFirmware.currentInstrumentEditTarget() + : masterFirmware.currentPerformanceInstrument()) == activeInstrumentPanelTarget) { masterFirmware.releasePanelActionBit( @@ -2615,9 +2856,9 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi -1, std::memory_order_acq_rel); requestedPageButton >= 0) { - // OS 1.700 installs a pair of native callbacks for each direction on - // the current screen. Invoke that pair once instead of entering the - // unusually fast Page-key auto-repeat scheduler. + // OS 1.700 installs a pair of native callbacks for each direction, + // including name-cursor movement in Store. Invoke the pair once so + // a brief host click cannot be lost in the key-repeat scheduler. masterFirmware.navigatePageWithFirmware(requestedPageButton == 23); } if (activeSoftButtonDiagnosticCode >= 0) @@ -2631,13 +2872,16 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi activeSoftButtonHoldBlocks = 0; } else if (!activeSoftButtonAccepted - && masterFirmware.panelActionBitActive( - activeSoftButtonDiagnosticCode)) + && (masterFirmware.panelActionBitActive(activeSoftButtonDiagnosticCode) + || (activeSoftButtonDiagnosticCode == 71 + && (masterFirmware.localByte(0x58feau) & 2u) != 0u))) { // The display-action bit is set only after OS 1.700 has accepted // this softkey and entered the current Wave Edit menu handler. activeSoftButtonAccepted = true; - activeSoftButtonHoldBlocks = 32; + // CANCEL is dispatched on release. Its press is acknowledged in + // the OK/CANCEL chord latch, not the display-softkey action bits. + activeSoftButtonHoldBlocks = activeSoftButtonDiagnosticCode == 71 ? 0 : 32; } else if (!activeSoftButtonAccepted && masterFirmware.panelEventPending( @@ -2679,11 +2923,15 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi if (changed && readFirmwareLong(cancelActionCallback) != readFirmwareLong(okActionCallback)) + { // A requester may reuse the handlers installed by the // preceding requester. The LCD transition produced by a newly // accepted softkey is therefore the second genuine open edge. firmwareRequesterActive.store(true, std::memory_order_release); + if (storeMenuActive.load(std::memory_order_acquire)) + completedStoreMode.store(-1, std::memory_order_release); + } masterFirmware.pushPanelEvent( 0x80u, static_cast(activeSoftButtonDiagnosticCode), 0u); activeSoftButtonReleaseSent = true; @@ -2703,6 +2951,29 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi // surviving display bit here cannot duplicate or cancel it. masterFirmware.releasePanelActionBit( activeSoftButtonDiagnosticCode); + if (activeSoftButtonDiagnosticCode == 71 + && storeExitModePending.exchange(false, std::memory_order_acq_rel)) + { + panelModeDisplayTransitionActive.store(true, std::memory_order_release); + panelModeDisplayAwaitingDispatch.store(true, std::memory_order_release); + const auto mode = storeExitMode.load(std::memory_order_acquire); + pendingFirmwareModeButton.store(mode, std::memory_order_release); + if (mode == 36) + startInstrumentPageSelectionDelay.store(true, std::memory_order_release); + } + if (activeSoftButtonDiagnosticCode == 71) + { + if (const auto program = pendingManagerExitProgram.exchange( + -1, std::memory_order_acq_rel); program >= 0) + { + // A newer browsing click can arrive as Cancel retires. + // Preserve that newer request rather than replacing it. + auto empty = -1; + pendingFirmwareProgram.compare_exchange_strong( + empty, program, std::memory_order_release, + std::memory_order_relaxed); + } + } activeSoftButtonDiagnosticCode = -1; activeSoftButtonPressSent = false; activeSoftButtonAccepted = false; @@ -2739,13 +3010,17 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi scheduledInstrumentPageSelection = requestedSelection; if (scheduledInstrumentPageSelection >= 0 && panelSelectedMode.load(std::memory_order_acquire) == 36 + && !storeExitModePending.load(std::memory_order_acquire) && activeSoftButtonDiagnosticCode < 0 && pendingFirmwareSoftButton.load(std::memory_order_acquire) < 0) { if (scheduledInstrumentPageDelayBlocks > 0) --scheduledInstrumentPageDelayBlocks; - else + else if (masterFirmware.currentInstrumentEditPage().has_value()) { + // A Store exit can take longer than the nominal mode-button hold. + // Its chooser owns these same eight softkeys until OS 1.700 has + // actually installed Instrument Edit's callbacks. pendingFirmwareInstrument.store(scheduledInstrumentPageSelection, std::memory_order_release); scheduledInstrumentPageSelection = -1; @@ -2775,11 +3050,12 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi // the scan lets the OS finish processing the preceding fader position and // replace the newly committed Performance byte with its stale value. sendPendingInstrumentFadersToFirmware(); + sendPendingGlideFadersToFirmware(); // Instrument Edit pages beyond Page 1 are interpreted by the real OS. // Feed the resulting native Instrument record back into the audio engine; // the panel never supplies DSP values directly and the LCD remains solely // firmware-driven. - synchroniseCurrentPerformanceInstrumentFromFirmware(); + synchronisePerformanceInstrumentsFromFirmware(); // A mode button's serial press/release transaction remains alive after // its LCD page has finished rasterising. Publish as soon as the firmware @@ -2847,9 +3123,13 @@ void WaveEmulationAudioProcessor::runFirmwareTimeline(const juce::MidiBuffer& mi false, std::memory_order_release); } } - if (panelSelectedMode.load(std::memory_order_acquire) == 36) + if (panelSelectedMode.load(std::memory_order_acquire) == 36 + && instrumentPageReady.load(std::memory_order_acquire)) { - const auto firmwareInstrument = masterFirmware.currentPerformanceInstrument(); + // The page target still belongs to the preceding visit until the + // queued Instrument selection is acknowledged. Reading it during + // mode entry changes the engine's layer (and Sound) behind the LCD. + const auto firmwareInstrument = masterFirmware.currentInstrumentEditTarget(); if (firmwareInstrument.has_value() && *firmwareInstrument != getSelectedPerformanceInstrument()) selectPerformanceInstrument(*firmwareInstrument); @@ -2897,9 +3177,18 @@ void WaveEmulationAudioProcessor::sendPendingInstrumentFadersToFirmware() { if (!masterFirmware.isLoaded()) return; + const auto firmwarePage = masterFirmware.currentInstrumentEditPage(); + if (firmwarePage.has_value()) + instrumentEditPage.store(*firmwarePage, std::memory_order_release); + if (!firmwarePage.has_value() + && panelSelectedMode.load(std::memory_order_acquire) == 36 + && panelSelectedEdit.load(std::memory_order_acquire) < 0 + && (panelModeDisplayTransitionActive.load(std::memory_order_acquire) + || !instrumentPageReady.load(std::memory_order_acquire))) + return; // Retain the edge until the native page has finished opening. if (panelSelectedMode.load(std::memory_order_acquire) != 36 || panelSelectedEdit.load(std::memory_order_acquire) >= 0 - || instrumentEditPage.load(std::memory_order_acquire) > 1) + || !firmwarePage.has_value() || *firmwarePage > 1) { for (auto& edit : pendingInstrumentFaderEdits) edit.store(-1, std::memory_order_release); @@ -2907,7 +3196,7 @@ void WaveEmulationAudioProcessor::sendPendingInstrumentFadersToFirmware() } static constexpr std::array pageOneRecordOffsets { - 4u, 5u, 7u, 8u, 9u, 10u, 2u, 3u + 4u, 5u, 7u, 12u, 9u, 10u, 2u, 3u // firmware table 0x14BCA }; static constexpr std::array pageTwoRecordOffsets { 4u, 5u, 7u, 21u, 22u, 15u, 16u, 11u @@ -2918,7 +3207,7 @@ void WaveEmulationAudioProcessor::sendPendingInstrumentFadersToFirmware() &factoryPerformance, std::memory_order_acquire); std::shared_ptr changed; const auto firmwarePerformance = masterFirmware.currentPerformanceId(); - const auto firmwareInstrument = masterFirmware.currentPerformanceInstrument(); + const auto firmwareInstrument = masterFirmware.currentInstrumentEditTarget(); for (size_t fader = 0; fader < pendingInstrumentFaderEdits.size(); ++fader) { @@ -2930,6 +3219,7 @@ void WaveEmulationAudioProcessor::sendPendingInstrumentFadersToFirmware() const auto instrument = (packed >> 8) & 0x07; const auto page = (packed >> 19) & 0x03; const auto physical = packed & 0x7f; + const auto adc = (packed >> 21) & 0xff; if (program != currentProgram.load(std::memory_order_acquire)) { pendingInstrumentFaderEdits[fader].store(-1, @@ -2945,9 +3235,13 @@ void WaveEmulationAudioProcessor::sendPendingInstrumentFadersToFirmware() // selected during the transition. continue; } - if (page != instrumentEditPage.load(std::memory_order_acquire) - || page > 1) + if (page != *firmwarePage) + { + // An edge queued for a page that has since closed cannot be + // applied to a field occupying the same fader on the new page. + pendingInstrumentFaderEdits[fader].store(-1, std::memory_order_release); continue; + } auto stored = physical; if (page == 0) @@ -2967,8 +3261,20 @@ void WaveEmulationAudioProcessor::sendPendingInstrumentFadersToFirmware() switch (fader) { case 3: stored = (physical * 11 + 63) / 127; break; - // Thirteen native choices: global through MIDI Tune. - case 4: stored = (physical * 12 + 63) / 127; break; + case 4: + { + // Match the firmware's displayed TuneTable transition at + // each raw ADC value, including odd values that share the + // same seven-bit position as their even neighbour. + static constexpr std::array thresholds { + 21, 41, 61, 81, 101, 121, + 139, 159, 179, 199, 219, 239 + }; + stored = static_cast(std::upper_bound( + thresholds.begin(), thresholds.end(), adc) + - thresholds.begin()); + break; + } case 5: stored = (physical * 22 + 63) / 127; break; case 6: stored = (physical * 4 + 63) / 127; break; case 7: stored = (physical * 3 + 63) / 127; break; @@ -3049,7 +3355,7 @@ void WaveEmulationAudioProcessor::sendPendingInstrumentFadersToFirmware() const auto currentFirmwarePerformance = masterFirmware.currentPerformanceId(); const auto currentFirmwareInstrument - = masterFirmware.currentPerformanceInstrument(); + = masterFirmware.currentInstrumentEditTarget(); if (currentFirmwarePerformance.has_value() && currentFirmwareInstrument.has_value() && *currentFirmwarePerformance == instrumentFaderBaselinePerformance @@ -3072,94 +3378,171 @@ void WaveEmulationAudioProcessor::sendPendingInstrumentFadersToFirmware() std::memory_order_release); } -void WaveEmulationAudioProcessor::synchroniseCurrentPerformanceInstrumentFromFirmware() +void WaveEmulationAudioProcessor::synchronisePerformanceInstrumentsFromFirmware() noexcept { if (!masterFirmware.isLoaded()) return; + // A cold start has no active bank. The OS's safe INIT records may enable + // Instruments, but must not repopulate the intentionally empty DSP bank. + const auto set = currentPerformanceSet(); + if (set == nullptr || !set->isLoaded()) + return; + const auto current = std::atomic_load_explicit( &factoryPerformance, std::memory_order_acquire); const auto firmwarePerformance = masterFirmware.currentPerformanceId(); - const auto firmwareInstrument = masterFirmware.currentPerformanceInstrument(); + const auto firmwareInstrument = panelSelectedMode.load(std::memory_order_acquire) == 36 + ? masterFirmware.currentInstrumentEditTarget() + : masterFirmware.currentPerformanceInstrument(); const auto performanceRecord = masterFirmware.currentPerformanceRecordOffset(); if (current == nullptr || !firmwarePerformance.has_value() || !firmwareInstrument.has_value() || !performanceRecord.has_value() || *firmwarePerformance != currentProgram.load(std::memory_order_acquire) - || *firmwareInstrument != current->editableLayer || *firmwareInstrument < 0 || *firmwareInstrument >= 8) return; - constexpr uint32_t instrumentTable = 64u; - constexpr uint32_t instrumentRecordSize = 32u; - const auto base = *performanceRecord + instrumentTable - + static_cast(*firmwareInstrument) - * instrumentRecordSize; - const auto byte = [this, base](uint32_t offset) { - return static_cast(masterFirmware.sharedProgramByte(base + offset) - & 0x7fu); - }; + // Store can replace every Instrument in the destination Performance. + // Synchronise all eight records so inactive source slots also clear the + // destination's playback layers and panel indicators. + std::shared_ptr changed; + for (int instrument = 0; instrument < 8; ++instrument) + { + constexpr uint32_t instrumentTable = 64u; + constexpr uint32_t instrumentRecordSize = 32u; + const auto base = *performanceRecord + instrumentTable + + static_cast(instrument) + * instrumentRecordSize; + const auto byte = [this, base](uint32_t offset) { + return static_cast(masterFirmware.sharedProgramByte(base + offset) + & 0x7fu); + }; - const auto source = juce::jlimit(0, 3, byte(3)); - const auto enabled = source != 0 && byte(13) == 0; - const auto midiChannel = juce::jlimit(0, 16, byte(2)); - const auto gain = static_cast(byte(4)) / 127.0f; - const auto pan = juce::jlimit( - -1.0f, 1.0f, static_cast(byte(5) - 64) / 64.0f); - const auto panMode = juce::jlimit(0, 2, byte(6)); - const auto auxGain = static_cast(byte(7)) / 127.0f; - const auto audioOutput = juce::jlimit(0, 3, byte(8)); - const auto transpose = byte(9) - 64; - const auto detune = static_cast(byte(10) - 64); - const auto keyLow = byte(17); - const auto keyHigh = byte(18); - const auto velocityLow = juce::jmax(1, byte(19)); - const auto velocityHigh = juce::jmax(1, byte(20)); - const auto velocityTable = juce::jlimit(0, 11, byte(21)); - const auto tuningTable = juce::jlimit(0, 12, byte(22)); - - const auto& existing - = current->layers[static_cast(*firmwareInstrument)]; - if (existing.enabled == enabled && existing.source == source - && existing.midiChannel == midiChannel - && std::abs(existing.gain - gain) <= 1.0e-6f - && std::abs(existing.sound.panAmount - pan) <= 1.0e-6f - && existing.sound.panModulationMode == panMode - && std::abs(existing.auxGain - auxGain) <= 1.0e-6f - && existing.audioOutput == audioOutput - && existing.transposeSemitones == transpose - && std::abs(existing.detuneCents - detune) <= 1.0e-6f - && existing.keyLow == keyLow && existing.keyHigh == keyHigh - && existing.velocityLow == velocityLow - && existing.velocityHigh == velocityHigh - && existing.velocityTable == velocityTable - && existing.tuningTable == tuningTable) - return; + const auto source = juce::jlimit(0, 3, byte(3)); + const auto enabled = source != 0 && byte(13) == 0; + const auto midiChannel = juce::jlimit(0, 16, byte(2)); + const auto gain = static_cast(byte(4)) / 127.0f; + const auto pan = juce::jlimit( + -1.0f, 1.0f, static_cast(byte(5) - 64) / 64.0f); + const auto panMode = juce::jlimit(0, 2, byte(6)); + const auto auxGain = static_cast(byte(7)) / 127.0f; + const auto audioOutput = juce::jlimit(0, 3, byte(12)); + const auto transpose = byte(9) - 64; + const auto detune = static_cast(byte(10) - 64); + const auto keyLow = byte(17); + const auto keyHigh = byte(18); + const auto velocityLow = juce::jmax(1, byte(19)); + const auto velocityHigh = juce::jmax(1, byte(20)); + const auto velocityTable = juce::jlimit(0, 11, byte(21)); + const auto tuningTable = juce::jlimit(0, 12, byte(22)); + const auto allocationMode = juce::jlimit(0, 22, byte(15)); + + const auto& existing + = current->layers[static_cast(instrument)]; + if (existing.enabled == enabled && existing.source == source + && existing.midiChannel == midiChannel + && std::abs(existing.gain - gain) <= 1.0e-6f + && std::abs(existing.sound.panAmount - pan) <= 1.0e-6f + && existing.sound.panModulationMode == panMode + && std::abs(existing.auxGain - auxGain) <= 1.0e-6f + && existing.audioOutput == audioOutput + && existing.transposeSemitones == transpose + && std::abs(existing.detuneCents - detune) <= 1.0e-6f + && existing.keyLow == keyLow && existing.keyHigh == keyHigh + && existing.velocityLow == velocityLow + && existing.velocityHigh == velocityHigh + && existing.velocityTable == velocityTable + && existing.tuningTable == tuningTable + && existing.allocationMode == allocationMode) + continue; - auto changed - = std::make_shared(*current); - auto& layer = changed->layers[static_cast(*firmwareInstrument)]; - layer.enabled = enabled; - layer.source = source; - layer.midiChannel = midiChannel; - layer.gain = gain; - layer.sound.panAmount = pan; - layer.sound.panModulationMode = panMode; - layer.auxGain = auxGain; - layer.audioOutput = audioOutput; - layer.transposeSemitones = transpose; - layer.detuneCents = detune; - layer.keyLow = keyLow; - layer.keyHigh = keyHigh; - layer.velocityLow = velocityLow; - layer.velocityHigh = velocityHigh; - layer.velocityTable = velocityTable; - layer.tuningTable = tuningTable; - std::atomic_store_explicit( - &factoryPerformance, - std::static_pointer_cast( - changed), - std::memory_order_release); + if (changed == nullptr) + changed = std::make_shared(*current); + auto& layer = changed->layers[static_cast(instrument)]; + if (enabled && !existing.enabled) + { + if (const auto record = masterFirmware.performanceInstrumentSoundRecordOffset(instrument)) + { + std::array sound {}; + for (size_t offset = 0; offset < sound.size(); ++offset) + sound[offset] = masterFirmware.sharedProgramByte( + *record + static_cast(offset)); + layer.sound = decodeFactorySound(sound); + } + } + layer.enabled = enabled; + layer.source = source; + layer.midiChannel = midiChannel; + layer.gain = gain; + layer.sound.panAmount = pan; + layer.sound.panModulationMode = panMode; + layer.auxGain = auxGain; + layer.audioOutput = audioOutput; + layer.transposeSemitones = transpose; + layer.detuneCents = detune; + layer.keyLow = keyLow; + layer.keyHigh = keyHigh; + layer.velocityLow = velocityLow; + layer.velocityHigh = velocityHigh; + layer.velocityTable = velocityTable; + layer.tuningTable = tuningTable; + layer.allocationMode = allocationMode; + } + if (changed != nullptr) + std::atomic_store_explicit( + &factoryPerformance, + std::static_pointer_cast( + changed), + std::memory_order_release); +} + +void WaveEmulationAudioProcessor::sendPendingGlideFadersToFirmware() +{ + if (panelSelectedEdit.load(std::memory_order_acquire) != 11) + { + for (auto& edit : pendingGlideFaderEdits) + edit.store(-1, std::memory_order_release); + return; + } + if (panelModeDisplayTransitionActive.load(std::memory_order_acquire) + || !masterFirmware.panelLed(75)) + return; + const auto program = masterFirmware.currentPerformanceId(); + const auto instrument = masterFirmware.currentPerformanceInstrument(); + auto changed = false; + for (const auto fader : { 0, 1, 4, 5 }) + { + const auto packed = pendingGlideFaderEdits[static_cast(fader)].load( + std::memory_order_acquire); + if (packed < 0) + continue; + if (((packed >> 11) & 0xff) != currentProgram.load(std::memory_order_acquire)) + { + pendingGlideFaderEdits[static_cast(fader)].store(-1, + std::memory_order_release); + continue; + } + if (!program.has_value() || !instrument.has_value() + || *program != ((packed >> 11) & 0xff) + || *instrument != ((packed >> 8) & 7)) + continue; + pendingGlideFaderEdits[static_cast(fader)].store(-1, + std::memory_order_release); + const auto physical = packed & 0x7f; + const auto offset = fader == 0 ? 233u : fader == 1 ? 235u + : fader == 4 ? 236u : 237u; + const auto value = fader == 0 ? 1 + physical * 6 / 128 + : fader == 1 ? physical * 2 / 128 + : fader == 4 ? physical * 39 / 128 : physical; + // As with Instrument Edit, model the absent ASIC's contextual + // analogue-to-record transfer on the audio thread. The OS owns the + // page, Sound destination, display, and subsequent voice commands. + changed |= masterFirmware.writeCurrentSoundRecordByte( + offset, static_cast(value)); + } + if (changed) + masterFirmware.refreshCurrentScreenFromFirmware(); } void WaveEmulationAudioProcessor::sendPendingPanelEncodersToFirmware() @@ -3308,6 +3691,11 @@ void WaveEmulationAudioProcessor::sendPendingPanelStepButtonsToFirmware() if (queuedPanelStepButtonEvents == 0) return; + if (masterFirmware.stepDiskMenuWithFirmware(queuedPanelStepButtonEvents > 0)) + { + queuedPanelStepButtonEvents += queuedPanelStepButtonEvents < 0 ? 1 : -1; + return; + } activePanelStepButtonDiagnosticCode = queuedPanelStepButtonEvents < 0 ? 69 : 72; activePanelStepButtonWaitBlocks = 0; @@ -3508,22 +3896,44 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe { const auto diagnosticCode = wave::panel::diagnosticCodeForMatrixIndex(buttonId); + if (diagnosticCode == 3 || diagnosticCode == 4) + { + auto& down = panelButtonDown[static_cast(buttonId)]; + if (down.load(std::memory_order_acquire) == pressed) + return true; + const auto event = keyboardButtonEventFifo.write(1); + if (event.blockSize1 == 0) + return false; + keyboardButtonEvents[static_cast(event.startIndex1)] + = static_cast(((diagnosticCode - 3) << 1) | (pressed ? 1 : 0)); + down.store(pressed, std::memory_order_release); + return true; + } if (pressed && (diagnosticCode == 12 || diagnosticCode == 73)) { pendingKeyboardOctaveRestore.store(2, std::memory_order_release); keyboardOctaveRestoreWaitBlocks.store(0, std::memory_order_release); } + const auto storeCancel = diagnosticCode == 71 + && (storeMenuActive.load(std::memory_order_acquire) + || storeExitModePending.load(std::memory_order_acquire)); const auto requesterActive = firmwareRequesterActive.load(std::memory_order_acquire); const auto storeDestinationStep = requesterActive && storeMenuActive.load(std::memory_order_acquire) && (diagnosticCode == 69 || diagnosticCode == 72); + const auto nameCursorStep + = requesterActive + && (storeMenuActive.load(std::memory_order_acquire) + || firmwareDiskNameEditorActive.load(std::memory_order_acquire)) + && (diagnosticCode == 21 || diagnosticCode == 23); if (pressed && requesterActive && diagnosticCode != 70 - && diagnosticCode != 71 && !storeDestinationStep) + && diagnosticCode != 71 && !storeDestinationStep + && !nameCursorStep) { // A genuine OS requester owns the front panel until CANCEL or OK. The - // Store requester additionally accepts the physical -/+ contacts to - // choose its destination location. Reject every other contact before + // Store requester additionally accepts -/+ for its destination, and + // Store/DOS name editors accept Page arrows. Reject other contacts before // any local mode/edit/LED state is changed; the UI receives this // result as engine feedback and never infers modal state from pixels. if (buttonId >= 0 && buttonId < static_cast(panelButtonDown.size())) @@ -3532,6 +3942,44 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe masterFirmware.setPanelButton(buttonId, false); return false; } + // An open requester owns the page (handled above). Once a Store save has + // closed its requester, the OS accepts another operating-mode button as + // an exit from Store. Keep our mode and Store lamp on that same path; + // previously the OS changed pages but our exclusive-mode guard left the + // Store lamp lit and could expose the old requester over the new page. + constexpr std::array exclusivePageCodes { 38, 33, 35, 34, 32, + 37, 36, 39, 58, 57 }; + const auto currentMode = panelSelectedMode.load(std::memory_order_acquire); + const auto requestedOperatingPage + = std::find(exclusivePageCodes.begin(), exclusivePageCodes.end(), + diagnosticCode) != exclusivePageCodes.end(); + const auto completedStoreCanExitByMode + = currentMode == 57 && !requesterActive + && !storeExitModePending.load(std::memory_order_acquire) + && diagnosticCode != 57 && diagnosticCode != 35 + && requestedOperatingPage; + const auto exclusiveModeOwnsSelection + = (currentMode == 34 || currentMode == 32 + || currentMode == 58 || currentMode == 57) + && diagnosticCode != currentMode && requestedOperatingPage + && !completedStoreCanExitByMode; + if (pressed && exclusiveModeOwnsSelection) + { + if (buttonId >= 0 && buttonId < static_cast(panelButtonDown.size())) + panelButtonDown[static_cast(buttonId)].store( + false, std::memory_order_release); + masterFirmware.setPanelButton(buttonId, false); + return false; + } + if (pressed && completedStoreCanExitByMode) + { + // The saved record's page is visible, but Store still owns the native + // Instrument chooser. Retire it before delivering the new mode and + // its Instrument softkey, which would otherwise open another save. + storeExitMode.store(diagnosticCode, std::memory_order_release); + storeExitModePending.store(true, std::memory_order_release); + pendingPanelCancel.store(true, std::memory_order_release); + } if (storeDestinationStep) { // Store owns this destination field. Queue the genuine serial action @@ -3549,6 +3997,12 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe } if (pressed && (diagnosticCode == 70 || diagnosticCode == 71)) { + if (diagnosticCode == 70 && requesterActive + && storeMenuActive.load(std::memory_order_acquire)) + storeSaveCompletionPending.store(true, std::memory_order_release); + else if (diagnosticCode == 71) + storeSaveCompletionPending.store(false, std::memory_order_release); + // Once a display softkey has opened a requester, its transaction is // complete. CANCEL/OK must retire it so the next Zoning softkey can // create a fresh edge after the requester closes. @@ -3561,18 +4015,24 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe // selection after the OS has returned to Performance. const auto diskWorkspaceActive = diskMenuActive.load(std::memory_order_acquire); - const auto leavingDisk + const auto skippingDiskCalibration = diagnosticCode == 71 + && diskSetImportConfirmationPending.load(std::memory_order_acquire) + && firmwareDiskCalibrationRequesterActive.load(std::memory_order_acquire); + if (skippingDiskCalibration) + pendingDiskSetBytes.store(0, std::memory_order_release); + const auto leavingDisk + = diagnosticCode == 71 && !skippingDiskCalibration && diskMenuActive.exchange(false, std::memory_order_acq_rel); const auto leavingStore - = storeMenuActive.load(std::memory_order_acquire); + = diagnosticCode == 71 + && storeMenuActive.load(std::memory_order_acquire); const auto selectedMode = panelSelectedMode.load(std::memory_order_acquire); const auto diskImportAwaitingConfirmation = diskSetImportConfirmationPending.load(std::memory_order_acquire); const auto diskImportWorkspace - = diskWorkspaceActive || selectedMode == 34 - || selectedMode == 32 || selectedMode == 58; + = !diskWorkspaceActive && (selectedMode == 34 || selectedMode == 32); const auto completingDiskImport = diagnosticCode == 70 && diskImportAwaitingConfirmation && diskImportWorkspace; @@ -3587,15 +4047,19 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe returnToPerformanceAfterDiskImport.store( true, std::memory_order_release); } - else if (diagnosticCode == 71) + else if (diagnosticCode == 71 && !skippingDiskCalibration) { - if (diskImportAwaitingConfirmation && diskImportWorkspace) + if (diskImportAwaitingConfirmation + && (diskImportWorkspace || diskWorkspaceActive)) + { diskSetImportConfirmationPending.store( false, std::memory_order_release); + pendingDiskSetActivation.store(false, std::memory_order_release); + } returnToPerformanceAfterDiskImport.store( false, std::memory_order_release); } - if ((diagnosticCode == 71 + if ((diagnosticCode == 71 && !skippingDiskCalibration && (leavingDisk || selectedMode == 34 || selectedMode == 32)) @@ -3606,34 +4070,32 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe } if (leavingStore) { - // Store's requester leaves its Manager/name-selection callback - // installed until the next operating-page serial action. Merely - // changing the engine's LED state makes '?' render every numeric - // candidate with the current Performance name. Defer the real - // Performance contact until OK/Cancel has physically released. - returnToPerformanceAfterStoreExit.store( + // Store's Manager callbacks need a native Cancel release before + // returning to Performance. The audio-thread transaction supplies + // both edges even when the whole click falls between callbacks. + storeExitMode.store(39, std::memory_order_release); + storeExitModePending.store( true, std::memory_order_release); + pendingPanelCancel.store(true, std::memory_order_release); } - // The Store requester is itself the Store page's final operation. - // Either response leaves that page, so its page lamp must be retired - // with the same firmware-facing OK/CANCEL edge. - storeMenuActive.store(false, std::memory_order_release); + if (leavingStore) + storeMenuActive.store(false, std::memory_order_release); } const auto schedulePerformanceAfterDiskOkRelease = !pressed && diagnosticCode == 70 && returnToPerformanceAfterDiskImport.exchange( false, std::memory_order_acq_rel); - const auto schedulePerformanceAfterStoreRelease - = !pressed && (diagnosticCode == 70 || diagnosticCode == 71) - && returnToPerformanceAfterStoreExit.exchange( - false, std::memory_order_acq_rel); if (pressed && diagnosticCode != 69 && diagnosticCode != 72) panelWavetableDataDialActive.store(false, std::memory_order_release); - auto firmwareButtonEventHandled = false; + auto firmwareButtonEventHandled = storeCancel; if (buttonId >= 0 && buttonId < static_cast(panelButtonDown.size())) panelButtonDown[static_cast(buttonId)].store( pressed, std::memory_order_release); + if (pressed && diagnosticCode >= 45 && diagnosticCode <= 56) + // Repair abandoned Manager ownership on the audio thread, before the + // native scanner consumes this contact. Never modify OS RAM here. + pendingNumericPanelInput.store(true, std::memory_order_release); if (diagnosticCode == 6) { // The audio-thread transaction owns both edges. Queue on mouse-down; @@ -3651,16 +4113,7 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe if (pressed) { - constexpr std::array operatingModeCodes { 38, 33, 35, 34, 32, - 37, 36, 39, 58, 57 }; - const auto selectedOperatingMode - = panelSelectedMode.load(std::memory_order_acquire); - const auto exclusiveModeOwnsSelection - = (selectedOperatingMode == 34 || selectedOperatingMode == 32 - || selectedOperatingMode == 58 || selectedOperatingMode == 57) - && diagnosticCode != selectedOperatingMode - && std::find(operatingModeCodes.begin(), operatingModeCodes.end(), - diagnosticCode) != operatingModeCodes.end(); + constexpr auto operatingModeCodes = exclusivePageCodes; if (!exclusiveModeOwnsSelection && diagnosticCode == 58) // Disk { storeMenuActive.store(false, std::memory_order_release); @@ -3672,6 +4125,10 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe { diskMenuActive.store(false, std::memory_order_release); storeMenuActive.store(true, std::memory_order_release); + if (currentMode != 57) + storeReturnMode.store(currentMode, std::memory_order_release); + completedStoreMode.store(-1, std::memory_order_release); + storeSaveCompletionPending.store(false, std::memory_order_release); panelSelectedMode.store(57, std::memory_order_release); panelSelectedEdit.store(-1, std::memory_order_release); } @@ -3769,9 +4226,11 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe const auto instrument = std::find(instrumentCodes.begin(), instrumentCodes.end(), diagnosticCode); - if (performanceMode && hasPerformanceSet && diagnosticCode == 24) + const auto instrumentControlsActive + = performanceMode || selectedPanelMode == 36; + if (instrumentControlsActive && hasPerformanceSet && diagnosticCode == 24) togglePerformanceMuteMode(); - else if (performanceMode && hasPerformanceSet && diagnosticCode == 78) + else if (instrumentControlsActive && hasPerformanceSet && diagnosticCode == 78) togglePerformanceSoloMode(); else if (selectedPanelMode == 36 && hasPerformanceSet && instrument != instrumentCodes.end()) @@ -3809,6 +4268,18 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe selectedInstrument, std::memory_order_release); } } + else + { + // An OFF Instrument must still reach the OS: its Source + // fader is how the Wave activates it. The engine will + // mirror the native record after Source is changed. + cancelInstrumentPageSelection.store( + true, std::memory_order_release); + cancelActiveInstrumentSelection.store( + true, std::memory_order_release); + pendingFirmwareInstrument.store( + selectedInstrument, std::memory_order_release); + } } } else if (!performanceMode && selectedPanelMode != 36 @@ -3865,7 +4336,6 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe panelSelectedEdit.store(-1, std::memory_order_release); if (diagnosticCode == 36) { - instrumentEditPage.store(0, std::memory_order_release); instrumentPageReady.store(false, std::memory_order_release); startInstrumentPageSelectionDelay.store( true, std::memory_order_release); @@ -3920,8 +4390,9 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe std::memory_order_release); panelModeDisplayAwaitingDispatch.store(true, std::memory_order_release); - pendingFirmwareModeButton.store(diagnosticCode, - std::memory_order_release); + if (!storeExitModePending.load(std::memory_order_acquire)) + pendingFirmwareModeButton.store(diagnosticCode, + std::memory_order_release); } if (diagnosticCode == 21 || diagnosticCode == 23) { @@ -3930,14 +4401,6 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe firmwareButtonEventHandled = true; pendingFirmwarePageButton.store(diagnosticCode, std::memory_order_release); - if (panelSelectedMode.load(std::memory_order_acquire) == 36) - { - const auto page = instrumentEditPage.load( - std::memory_order_acquire); - instrumentEditPage.store( - (page + (diagnosticCode == 23 ? 1 : 3)) % 4, - std::memory_order_release); - } } } if (firmwareButtonEventHandled) @@ -3945,7 +4408,9 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe else if ((diagnosticCode == 69 || diagnosticCode == 72) && pressed) { const auto performancePage - = panelSelectedMode.load(std::memory_order_acquire) == 39 + = (panelSelectedMode.load(std::memory_order_acquire) == 39 + || (storeMenuActive.load(std::memory_order_acquire) + && completedStoreMode.load(std::memory_order_acquire) == 39)) && panelSelectedEdit.load(std::memory_order_acquire) < 0; if (performancePage) { @@ -3988,8 +4453,7 @@ bool WaveEmulationAudioProcessor::setPanelButton(int buttonId, bool pressed) noe } else if (diagnosticCode != 69 && diagnosticCode != 72) masterFirmware.setPanelButton(buttonId, pressed); - if (schedulePerformanceAfterDiskOkRelease - || schedulePerformanceAfterStoreRelease) + if (schedulePerformanceAfterDiskOkRelease) { // The unavailable panel/disk glue returns the operating page after // Total Recall. Queue the genuine Performance serial contact only @@ -4056,13 +4520,9 @@ int WaveEmulationAudioProcessor::getFirmwareOscillatorOctave(int oscillator) con { if (oscillator < 0 || oscillator >= 2) return 0; - // The engine owns the selected layer's five-position octave state. The - // current firmware runtime does not yet model the CPU board's periodic LED - // scan, so its output latch can retain an octave LED from the previously - // selected Instrument. Treating that stale lamp as parameter feedback - // changes the new layer's pitch merely by selecting it. The panel LEDs - // below are therefore driven from this engine state, while an actual - // Octave-button edge updates the same state in setPanelButton(). + // This mirror is refreshed from the selected firmware Sound record, whose + // octave bytes are also used by the DSP. The panel's serial LED latch can + // retain a previous Instrument's lamp and is not parameter feedback. return panelOscillatorOctaves[static_cast(oscillator)].load( std::memory_order_acquire); } @@ -4105,6 +4565,18 @@ void WaveEmulationAudioProcessor::setPanelFader(int faderIndex, int controlId, masterFirmware.setPanelAnalog(controlId, value); if (!performanceMode) { + if (panelSelectedEdit.load(std::memory_order_acquire) == 11 + && (faderIndex == 0 || faderIndex == 1 + || faderIndex == 4 || faderIndex == 5)) + { + const auto instrument = getSelectedPerformanceInstrument(); + const auto program = currentProgram.load(std::memory_order_acquire); + if (instrument >= 0 && instrument < 8 && program >= 0 && program < 256) + pendingGlideFaderEdits[static_cast(faderIndex)].store( + (program << 11) | (instrument << 8) | juce::roundToInt(value * 127.0f), + std::memory_order_release); + return; + } if (panelSelectedMode.load(std::memory_order_acquire) == 36 && panelSelectedEdit.load(std::memory_order_acquire) < 0 && instrumentEditPage.load(std::memory_order_acquire) <= 1 @@ -4116,8 +4588,9 @@ void WaveEmulationAudioProcessor::setPanelFader(int faderIndex, int controlId, if (instrument >= 0 && instrument < 8 && program >= 0 && program < 256) { const auto physical = juce::roundToInt(value * 127.0f); + const auto adc = juce::roundToInt(value * 255.0f); pendingInstrumentFaderEdits[static_cast(faderIndex)].store( - (page << 19) | (program << 11) | (instrument << 8) + (adc << 21) | (page << 19) | (program << 11) | (instrument << 8) | physical, std::memory_order_release); } @@ -4349,10 +4822,14 @@ bool WaveEmulationAudioProcessor::getPanelLed(int ledId) const noexcept // bank first can illuminate both the old and newly requested modes. constexpr std::array modeCodes { 38, 33, 35, 34, 32, 37, 36, 39 }; constexpr std::array modeLeds { 64, 69, 21, 74, 26, 10, 22, 51 }; + auto lampMode = panelSelectedMode.load(std::memory_order_acquire); + if (storeMenuActive.load(std::memory_order_acquire)) + if (const auto completed = completedStoreMode.load(std::memory_order_acquire); + completed >= 0) + lampMode = completed; for (size_t index = 0; index < modeCodes.size(); ++index) if (ledId == modeLeds[index]) - return panelSelectedMode.load(std::memory_order_acquire) - == modeCodes[index]; + return lampMode == modeCodes[index]; // An Edit overlay has exactly one selected section. The 6522 output banks // are written independently and the raw firmware latch can briefly retain @@ -4422,13 +4899,14 @@ bool WaveEmulationAudioProcessor::getPanelLed(int ledId) const noexcept return (currentProgram.load(std::memory_order_acquire) / 128 == 1) == (ledId == 85); - // Disk and Store are full operating-mode lamps, not contact lamps. Their - // physical switches are momentary, but each indicator remains asserted - // exclusively until its firmware workspace is exited. + // Disk stays lit while its workspace is active. Store gives way to the + // preceding operating-mode lamp after a successful save, while the + // native chooser remains available for another record. if (ledId == 52) return diskMenuActive.load(std::memory_order_acquire); if (ledId == 87) - return storeMenuActive.load(std::memory_order_acquire); + return storeMenuActive.load(std::memory_order_acquire) + && completedStoreMode.load(std::memory_order_acquire) < 0; struct MomentaryLed { @@ -4524,6 +5002,13 @@ void WaveEmulationAudioProcessor::getStateInformation(juce::MemoryBlock& destina // lock. The firmware, disk and calibration state must remain one snapshot. const juce::ScopedLock callbackLock(getCallbackLock()); auto state = parameters.copyState(); + state.removeProperty("ecoMode", nullptr); + // These are regenerated from the current machine. copyState() may still + // contain snapshots from an earlier project or a previously loaded disk. + for (const auto* key : { "machineActiveSetData", "machineDiskImageData", + "machineDiskImageName", "mountedDiskImage", + "machinePerformanceSnapshot", "machineFirmwareEditBuffers" }) + state.removeProperty(key, nullptr); state.setProperty("machineStateSchema", machineStateSchemaVersion, nullptr); state.setProperty("factoryProgram", currentProgram.load(std::memory_order_acquire), nullptr); @@ -4549,12 +5034,31 @@ void WaveEmulationAudioProcessor::getStateInformation(juce::MemoryBlock& destina activeSet != nullptr && activeSet->isLoaded(), nullptr); if (activeSet != nullptr && activeSet->isLoaded() && !activeSet->sourceImage().isEmpty()) + { + auto setImage = activeSet->sourceImage(); + if (masterFirmware.isLoaded() + && !pendingDiskSetActivation.load(std::memory_order_acquire)) + { + // Store changes native SRAM, not the imported SET. Persist both + // complete banks alongside the separate current edit buffers. + std::vector sounds(activeSet->soundBank().size()); + std::vector performances(activeSet->performanceBank().size()); + for (size_t byte = 0; byte < sounds.size(); ++byte) + sounds[byte] = masterFirmware.sharedProgramByte( + 0x18000u + static_cast(byte)); + for (size_t byte = 0; byte < performances.size(); ++byte) + performances[byte] = masterFirmware.sharedProgramByte( + 0x28000u + static_cast(byte)); + setImage = activeSet->imageWithStoredBanks(sounds, performances); + } state.setProperty("machineActiveSetData", - juce::var(activeSet->sourceImage()), nullptr); + juce::var(setImage), nullptr); + } auto persistentPerformance = std::atomic_load_explicit( &factoryPerformance, std::memory_order_acquire); - if (persistentPerformance != nullptr) + if (persistentPerformance != nullptr + && !pendingDiskSetActivation.load(std::memory_order_acquire)) { auto exactPerformance = *persistentPerformance; const auto editable = exactPerformance.editableLayer; @@ -4618,7 +5122,8 @@ void WaveEmulationAudioProcessor::getStateInformation(juce::MemoryBlock& destina editBuffers = std::static_pointer_cast(fallback); } } - if (editBuffers != nullptr) + if (editBuffers != nullptr && activeSet != nullptr && activeSet->isLoaded() + && !pendingDiskSetActivation.load(std::memory_order_acquire)) { juce::MemoryBlock binary; juce::MemoryOutputStream stream(binary, false); @@ -4687,7 +5192,17 @@ void WaveEmulationAudioProcessor::setStateInformation(const void* data, int size { if (xml->hasTagName(parameters.state.getType())) { - const auto restoredState = juce::ValueTree::fromXml(*xml); + auto restoredState = juce::ValueTree::fromXml(*xml); + // Retired reduced-rate Eco settings must not degrade recalled audio. + restoredState.removeProperty("ecoMode", nullptr); + // Edit buffers belong to the incoming project, not the instance's + // previously selected disk or Performance with the same number. + std::atomic_store_explicit(&latestFirmwareSelectedSound, + std::shared_ptr{}, std::memory_order_release); + std::atomic_store_explicit(&latestHostMachineSnapshot, + std::shared_ptr{}, std::memory_order_release); + std::atomic_store_explicit(&pendingHostMachineRestore, + std::shared_ptr{}, std::memory_order_release); const auto exactMachineState = static_cast(restoredState.getProperty( "machineStateSchema", 0)) == machineStateSchemaVersion; @@ -4701,18 +5216,20 @@ void WaveEmulationAudioProcessor::setStateInformation(const void* data, int size const auto activeSetData = restoredState.getProperty("machineActiveSetData"); if (exactMachineState) { - if (const auto* bytes = activeSetData.getBinaryData(); bytes != nullptr) + const auto hasActiveSet = static_cast(restoredState.getProperty( + "machineHasActiveSet", true)); + if (const auto* bytes = activeSetData.getBinaryData(); + hasActiveSet && bytes != nullptr) { auto set = std::make_shared(); - if (set->load(*bytes).validLayout) + if (set->loadStateSnapshot(*bytes).validLayout) restoredExactSet = std::static_pointer_cast< const wave::presets::WaveFactorySet>(set); } if (restoredExactSet != nullptr) setActivePerformanceSet(restoredExactSet); - else if (!static_cast(restoredState.getProperty( - "machineHasActiveSet", true))) - setActivePerformanceSet(nullptr); + else if (!hasActiveSet) + resetToColdStart(); } parameters.replaceState(restoredState.createCopy()); @@ -4733,7 +5250,14 @@ void WaveEmulationAudioProcessor::setStateInformation(const void* data, int size if (!report.hasBothImages() && !loadRememberedFirmware()) loadEmbeddedPrivateRoms(); } + // Embedded-firmware sessions can restore without rebooting. + // Reinstall the native bank even if this instance previously + // imported a PPG image, then resolve this SET's user references. + if (engine.loadWaveFactoryRom(firmware.getMasterImage()) + && restoredSet != nullptr) + engine.loadWaveSetUserTables(restoredSet->sourceImage()); removeRestoredHostStateDisk(); + (void) masterFirmware.ejectDiskImage(); auto restoredEmbeddedDisk = false; const auto diskData = restoredState.getProperty("machineDiskImageData"); if (exactMachineState) @@ -4776,12 +5300,18 @@ void WaveEmulationAudioProcessor::setStateInformation(const void* data, int size if (restoredExactSet != nullptr) setActivePerformanceSet(restoredExactSet); pendingDiskSetActivation.store(false, std::memory_order_release); + pendingManagerExitProgram.store(-1, std::memory_order_release); pendingDiskSetBytes.store(0, std::memory_order_release); diskSetImportConfirmationPending.store( false, std::memory_order_release); const auto set = currentPerformanceSet(); if (set != nullptr && set->isLoaded()) { + // Embedded firmware may already be running, so restoring a + // SET does not necessarily reboot through startLoadedFirmware. + // Install the full banks before selecting the saved program. + masterFirmware.installSoundBank(set->soundBank()); + masterFirmware.installPerformanceBank(set->performanceBank()); // Reconstruct all eight factory Performance elements, then restore // current-version edits over that template. Older standalone state // predates complete Performance layering and may contain a stale pan @@ -4999,6 +5529,9 @@ wave::firmware::Bundle::Report WaveEmulationAudioProcessor::loadFirmware( return report; firmware = std::move(candidate); report = startLoadedFirmware(report, true); + if (currentPerformanceSet() != nullptr) + pendingFirmwareProgram.store(currentProgram.load(std::memory_order_acquire), + std::memory_order_release); if (rememberForNewInstances) { const auto created = firmwarePreferenceFile.getParentDirectory().createDirectory(); @@ -5014,6 +5547,9 @@ wave::firmware::Bundle::Report WaveEmulationAudioProcessor::startLoadedFirmware( { if (report.hasBothImages()) { + // The Wave's own factory routines supersede the PPG fallback and + // previously remembered PPG imports on every firmware/state reload. + engine.loadWaveFactoryRom(firmware.getMasterImage()); sharedFirmwareMemory.clear(); if (rememberDirectory && firmware.getDirectory().isDirectory()) parameters.state.setProperty("firmwareDirectory", @@ -5075,9 +5611,16 @@ wave::firmware::Bundle::Report WaveEmulationAudioProcessor::startLoadedFirmware( } } } - if (firmware.getDirectory().isDirectory()) + if (!engine.getWavetableBank().hasOriginalWaveFactoryTables() + && firmware.getDirectory().isDirectory()) discoverWavetableRom(firmware.getDirectory()); seedFilterCalibrationTable(); + if (const auto set = currentPerformanceSet(); set != nullptr) + { + engine.loadWaveSetUserTables(set->sourceImage()); + masterFirmware.installSoundBank(set->soundBank()); + masterFirmware.installPerformanceBank(set->performanceBank()); + } } return report; } @@ -5090,9 +5633,10 @@ void WaveEmulationAudioProcessor::loadEmbeddedPrivateRoms() const juce::MemoryBlock voice(WaveAssets::wdv_sys, static_cast(WaveAssets::wdv_sysSize)); startLoadedFirmware(firmware.loadImages(master, voice), false); - engine.loadWavetableRom(juce::MemoryBlock( - WaveAssets::ppgwave2_3v6wavetables_rom, - static_cast(WaveAssets::ppgwave2_3v6wavetables_romSize))); + if (!engine.getWavetableBank().hasOriginalWaveFactoryTables()) + engine.loadWavetableRom(juce::MemoryBlock( + WaveAssets::ppgwave2_3v6wavetables_rom, + static_cast(WaveAssets::ppgwave2_3v6wavetables_romSize))); if (const auto set = currentPerformanceSet()) engine.loadWaveSetUserTables(set->sourceImage()); #endif @@ -5153,7 +5697,12 @@ bool WaveEmulationAudioProcessor::installFactoryEditRecords(int programIndex) no { } if (instrument >= 8) - return false; + { + // Empty/quarantined slots still need a native recall. Leaving the + // previous edit records installed keeps both its LCD and Sound live. + const std::array emptySound{}; + return masterFirmware.installEditRecords(emptySound, performance); + } const auto offset = static_cast(64 + instrument * 32); const auto sound = set->sound(performance[offset + 1], performance[offset]); @@ -5186,7 +5735,25 @@ void WaveEmulationAudioProcessor::applyFactoryProgram(int index, bool notifyFirm } } if (instrument == 8) + { + auto emptyPerformance + = std::make_shared(); + emptyPerformance->editableLayer = -1; + auto emptySeed = std::make_shared(); + emptySeed->performance = index; + std::atomic_store_explicit( + &factoryPerformance, + std::static_pointer_cast( + emptyPerformance), std::memory_order_release); + std::atomic_store_explicit( + &instrumentSoundSeed, + std::static_pointer_cast(emptySeed), + std::memory_order_release); + modulationRoutingResetPending.store(true, std::memory_order_release); + if (notifyFirmware && masterFirmware.isLoaded()) + pendingFirmwareProgram.store(index, std::memory_order_release); return; + } instrumentOffset = static_cast(64 + instrument * 32); const auto soundBank = static_cast(performance[instrumentOffset + 1]); @@ -5412,7 +5979,7 @@ void WaveEmulationAudioProcessor::applyFactoryProgram(int index, bool notifyFirm destination.auxGain = static_cast(sevenBit(performance[layerOffset + 7])) / 127.0f; destination.audioOutput - = juce::jlimit(0, 3, sevenBit(performance[layerOffset + 8])); + = juce::jlimit(0, 3, sevenBit(performance[layerOffset + 12])); destination.keyLow = sevenBit(performance[layerOffset + 17]); destination.keyHigh = sevenBit(performance[layerOffset + 18]); destination.velocityLow = juce::jmax(1, sevenBit(performance[layerOffset + 19])); @@ -5421,6 +5988,8 @@ void WaveEmulationAudioProcessor::applyFactoryProgram(int index, bool notifyFirm 0, 11, sevenBit(performance[layerOffset + 21])); destination.tuningTable = juce::jlimit( 0, 12, sevenBit(performance[layerOffset + 22])); + destination.allocationMode = juce::jlimit( + 0, 22, sevenBit(performance[layerOffset + 15])); const auto nativeSound = set->sound( sevenBit(performance[layerOffset + 1]), sevenBit(performance[layerOffset])); @@ -5537,3 +6106,34 @@ juce::AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new WaveEmulationAudioProcessor(); } + +// UI artwork is a per-user preference, independent of firmware and host audio state. +juce::File WaveEmulationAudioProcessor::getRememberedPanelSkin() const +{ + const auto preference = firmwarePreferenceFile.getSiblingFile( + firmwarePreferenceFile.getFileNameWithoutExtension() + "-panel-skin.txt"); + const auto path = preference.loadFileAsString().trim(); + return juce::File::isAbsolutePath(path) ? juce::File(path) : juce::File{}; +} + +bool WaveEmulationAudioProcessor::getRememberedCompactPanelSkin() const +{ + return firmwarePreferenceFile.getSiblingFile( + firmwarePreferenceFile.getFileNameWithoutExtension() + "-panel-skin.txt") + .loadFileAsString().trim() == "compact"; +} + +juce::Result WaveEmulationAudioProcessor::rememberPanelSkin(const juce::File& file, + bool compact) +{ + const auto preference = firmwarePreferenceFile.getSiblingFile( + firmwarePreferenceFile.getFileNameWithoutExtension() + "-panel-skin.txt"); + const auto created = preference.getParentDirectory().createDirectory(); + if (created.failed()) + return created; + if (!preference.replaceWithText(compact ? juce::String("compact") + : file == juce::File{} ? juce::String{} + : file.getFullPathName())) + return juce::Result::fail("Could not save the panel skin preference."); + return juce::Result::ok(); +} diff --git a/Source/PluginProcessor.h b/Source/PluginProcessor.h index 839838b..cb5c9ca 100644 --- a/Source/PluginProcessor.h +++ b/Source/PluginProcessor.h @@ -29,7 +29,9 @@ class WaveEmulationAudioProcessor final : public juce::AudioProcessor, solo }; - explicit WaveEmulationAudioProcessor(const juce::File& firmwarePreferenceFile = {}); + enum class InitialBank { empty, initialised, embeddedFactory }; + explicit WaveEmulationAudioProcessor(const juce::File& firmwarePreferenceFile = {}, + InitialBank initialBank = InitialBank::initialised); ~WaveEmulationAudioProcessor() override; void prepareToPlay(double sampleRate, int samplesPerBlock) override; @@ -91,10 +93,13 @@ class WaveEmulationAudioProcessor final : public juce::AudioProcessor, juce::Result createBlankDiskImage(const juce::File& destination); juce::Result createDiskImageFromWaveSetup(const juce::File& setup, const juce::File& destination); + juce::Result createDiskImageFromWavetable(const juce::File& wavetable, + const juce::File& destination); juce::Result flushMountedDiskImage(); juce::Result saveMountedDiskImageAs(const juce::File& destination); juce::Result ejectDiskImage(); void resetToColdStart(); + juce::Result reloadBankFromMountedImage(); [[nodiscard]] bool hasMountedDiskImage() const noexcept { return masterFirmware.hasMountedDiskImage(); @@ -199,6 +204,9 @@ class WaveEmulationAudioProcessor final : public juce::AudioProcessor, { return keyboardOctaveShift.load(std::memory_order_acquire); } + [[nodiscard]] juce::File getRememberedPanelSkin() const; + [[nodiscard]] bool getRememberedCompactPanelSkin() const; + juce::Result rememberPanelSkin(const juce::File& file, bool compact = false); bool setPanelButton(int buttonId, bool pressed) noexcept; void setKeyboardControllerButton(uint8_t asciiCode, bool pressed) noexcept; [[nodiscard]] int getFirmwareOscillatorOctave(int oscillator) const noexcept; @@ -294,8 +302,6 @@ class WaveEmulationAudioProcessor final : public juce::AudioProcessor, std::array, 8> activeInstrumentSoundRecords {}; std::array activeInstrumentSoundRecordValid {}; - std::array activeInstrumentSoundRecordReconciled {}; - std::array activeInstrumentSoundRecordUsesImportEncoding {}; int activeInstrumentSoundPerformance = -1; uint64_t lastPublishedFirmwareSoundHash = 0; uint64_t lastPublishedHostMachineHash = 0; @@ -317,11 +323,14 @@ class WaveEmulationAudioProcessor final : public juce::AudioProcessor, std::atomic instrumentZoningPageActive { false }; std::atomic instrumentEditPage { 0 }; std::atomic firmwareRequesterActive { false }; + std::atomic firmwareDiskNameEditorActive { false }; std::atomic instrumentPageReady { false }; std::atomic startInstrumentPageSelectionDelay { false }; int scheduledInstrumentPageSelection = -1; int scheduledInstrumentPageDelayBlocks = 0; std::atomic pendingFirmwareSoftButton { -1 }; + std::atomic pendingNumericPanelInput { false }; + std::atomic pendingPanelCancel { false }; std::atomic cancelFirmwareSoftButtonEvents { false }; int activeSoftButtonDiagnosticCode = -1; bool activeSoftButtonPressSent = false; @@ -357,8 +366,14 @@ class WaveEmulationAudioProcessor final : public juce::AudioProcessor, // byte transfer can finish before OK is pressed, so it cannot double as // the front-panel requester's ownership flag. std::atomic diskSetImportConfirmationPending { false }; + std::atomic firmwareDiskCalibrationRequesterActive { false }; + std::atomic pendingManagerExitProgram { -1 }; std::atomic returnToPerformanceAfterDiskImport { false }; - std::atomic returnToPerformanceAfterStoreExit { false }; + std::atomic storeExitModePending { false }; + std::atomic storeExitMode { 39 }; + std::atomic storeReturnMode { 39 }; + std::atomic completedStoreMode { -1 }; + std::atomic storeSaveCompletionPending { false }; const juce::String hostStateInstanceId { juce::Uuid().toString() }; juce::File restoredHostStateDirectory; std::array @@ -387,7 +402,11 @@ class WaveEmulationAudioProcessor final : public juce::AudioProcessor, std::atomic controllerInputSequence { 0 }; std::atomic modWheelInputSequence { 0 }; std::array, 8> performanceFaderInputSequences {}; - std::array lastKeyboardAssignableButtonStates { -1, -1 }; + juce::AbstractFifo keyboardButtonEventFifo { 64 }; + std::array keyboardButtonEvents {}; + int activeKeyboardButtonEvent = -1; + int activeKeyboardButtonExpectedState = 0; + int keyboardButtonRetryBlocks = 0; std::array localKeyboardTransposedNotes {}; std::atomic instrumentButtonMode { static_cast(InstrumentButtonMode::normal) @@ -456,6 +475,7 @@ class WaveEmulationAudioProcessor final : public juce::AudioProcessor, // position here; advanceFirmware() commits and redraws it on the sole // firmware-owning audio thread. std::atomic pendingPanelGlideRate { -1 }; + std::array, 8> pendingGlideFaderEdits; std::atomic pendingFirmwareGlideSwitchClicks { 0 }; int queuedFirmwareGlideSwitchClicks = 0; bool firmwareGlideSwitchTransactionActive = false; @@ -481,13 +501,15 @@ class WaveEmulationAudioProcessor final : public juce::AudioProcessor, double currentSampleRate = 44100.0; std::atomic currentProgram { 0 }; bool firmwareKeyboardShiftDown = false; + int firmwareKeyboardShiftRetryBlocks = 0; void advanceFirmware(int samples); void handleAsyncUpdate() override; void runFirmwareTimeline(const juce::MidiBuffer& midi, int sampleCount); void sendPendingPerformanceFadersToFirmware(); void sendPendingInstrumentFadersToFirmware(); - void synchroniseCurrentPerformanceInstrumentFromFirmware() noexcept; + void sendPendingGlideFadersToFirmware(); + void synchronisePerformanceInstrumentsFromFirmware() noexcept; void sendPendingPanelEncodersToFirmware(); void sendPendingPanelGlideSwitchesToFirmware(); void sendPendingPanelStepButtonsToFirmware(); @@ -520,6 +542,7 @@ class WaveEmulationAudioProcessor final : public juce::AudioProcessor, const wave::firmware::Bundle::Report& report, bool rememberDirectory); void loadEmbeddedPrivateRoms(); void loadEmbeddedFactorySet(); + juce::Result loadDefaultBank(const juce::File& image); bool installFactoryEditRecords(int programIndex) noexcept; void applyFactoryProgram(int index, bool notifyFirmware); diff --git a/Source/Presets/WaveFactorySet.cpp b/Source/Presets/WaveFactorySet.cpp index 4e5eb2c..069e4dd 100644 --- a/Source/Presets/WaveFactorySet.cpp +++ b/Source/Presets/WaveFactorySet.cpp @@ -9,10 +9,12 @@ namespace wave::presets { namespace { -bool printableName(const uint8_t* bytes) noexcept +bool nativeName(const uint8_t* bytes) noexcept { + // Store can write NULs inside the otherwise space-padded 16-byte name. + // These also occur in SET files saved by the firmware, not just host state. return std::all_of(bytes, bytes + 16, [](uint8_t value) { - return value >= 0x20u && value <= 0x7eu; + return value == 0u || (value >= 0x20u && value <= 0x7eu); }); } @@ -47,20 +49,84 @@ WaveFactorySet::Report WaveFactorySet::load(const void* bytes, size_t size) const auto* soundRecord = sounds.data() + static_cast(index) * soundSize; const auto* performanceRecord = performances.data() + static_cast(index) * performanceSize; - if (soundRecord[239] == 0x55u && printableName(soundRecord + 240)) + if (soundRecord[239] == 0x55u && nativeName(soundRecord + 240)) ++report.validSounds; - if (performanceRecord[48] == 0x55u && printableName(performanceRecord + 32)) + else if (std::all_of(soundRecord, soundRecord + soundSize, + [](uint8_t value) { return value == 0; })) + ++report.emptySounds; + else + ++report.invalidSounds; + if (performanceRecord[48] == 0x55u && nativeName(performanceRecord + 32)) ++report.validPerformances; + else if (std::all_of(performanceRecord, performanceRecord + performanceSize, + [](uint8_t value) { return value == 0; })) + ++report.emptyPerformances; + else + ++report.invalidPerformances; } report.sha256 = juce::SHA256(bytes, size).toHexString(); - report.validLayout = report.validSounds >= 250 && report.validPerformances == programCount; + report.validLayout = report.validSounds > 0 && report.validPerformances > 0 + && report.validSounds + report.emptySounds >= 250 + && report.validPerformances + report.emptyPerformances >= 250; + if (report.validLayout) + { + // A few damaged records must not strand Total Recall using the old + // host bank after the OS has loaded a new one. Quarantine only those + // slots in the working banks; retain the source disk bytes verbatim. + for (int index = 0; index < programCount; ++index) + { + auto* soundRecord = sounds.data() + static_cast(index) * soundSize; + auto* performanceRecord = performances.data() + + static_cast(index) * performanceSize; + if (soundRecord[239] != 0x55u || !nativeName(soundRecord + 240)) + std::fill_n(soundRecord, soundSize, uint8_t{}); + if (performanceRecord[48] != 0x55u || !nativeName(performanceRecord + 32)) + std::fill_n(performanceRecord, performanceSize, uint8_t{}); + } + } report.detail = report.validLayout ? "Native Waldorf Wave SET: two 128-program sound banks and two 128-program performance banks" : "SET bank markers or names do not match the Waldorf Wave layout"; + if (report.validLayout && report.invalidSounds + report.invalidPerformances > 0) + report.detail += "; working bank omits " + juce::String(report.invalidSounds) + + " malformed Sounds and " + juce::String(report.invalidPerformances) + + " malformed Performances"; return report; } +WaveFactorySet::Report WaveFactorySet::loadStateSnapshot(const juce::MemoryBlock& data) +{ + load(data); + if (data.getSize() >= minimumSize) + { + // Host snapshots represent exact SRAM, including records a disk + // import would quarantine. Do not change those saved machine bytes. + const auto* bytes = static_cast(data.getData()); + std::copy_n(bytes + soundBankOffset, sounds.size(), sounds.begin()); + std::copy_n(bytes + performanceBankOffset, performances.size(), performances.begin()); + report.validLayout = true; + report.detail = "Saved native Wave sound and performance SRAM banks"; + } + return report; +} + +juce::MemoryBlock WaveFactorySet::imageWithStoredBanks( + std::span storedSounds, + std::span storedPerformances) const +{ + auto image = loadedImage; + if (image.getSize() >= minimumSize && storedSounds.size() == sounds.size() + && storedPerformances.size() == performances.size()) + { + auto* bytes = static_cast(image.getData()); + std::copy(storedSounds.begin(), storedSounds.end(), bytes + soundBankOffset); + std::copy(storedPerformances.begin(), storedPerformances.end(), + bytes + performanceBankOffset); + } + return image; +} + std::span WaveFactorySet::sound( int bank, int program) const noexcept { @@ -81,7 +147,7 @@ std::string WaveFactorySet::nameAt(std::span record, size_t offse if (offset + 16 > record.size()) return {}; std::string result(reinterpret_cast(record.data() + offset), 16); - while (!result.empty() && result.back() == ' ') + while (!result.empty() && (result.back() == ' ' || result.back() == '\0')) result.pop_back(); return result; } diff --git a/Source/Presets/WaveFactorySet.h b/Source/Presets/WaveFactorySet.h index 76c0c85..8902b5d 100644 --- a/Source/Presets/WaveFactorySet.h +++ b/Source/Presets/WaveFactorySet.h @@ -23,16 +23,25 @@ class WaveFactorySet bool validLayout = false; int validSounds = 0; int validPerformances = 0; + int emptySounds = 0; + int emptyPerformances = 0; + int invalidSounds = 0; + int invalidPerformances = 0; juce::String sha256; juce::String detail; }; Report load(const void* bytes, size_t size); Report load(const juce::MemoryBlock& data) { return load(data.getData(), data.getSize()); } + // Host snapshots contain native SRAM, including uninitialised/empty slots. + // Preserve those bytes without applying disk-import record validation. + Report loadStateSnapshot(const juce::MemoryBlock& data); [[nodiscard]] bool isLoaded() const noexcept { return report.validLayout; } [[nodiscard]] const Report& getReport() const noexcept { return report; } [[nodiscard]] std::span sound(int bank, int program) const noexcept; + [[nodiscard]] std::span performanceBank() const noexcept { return performances; } + [[nodiscard]] std::span soundBank() const noexcept { return sounds; } [[nodiscard]] std::span performance( int bank, int program) const noexcept; [[nodiscard]] std::string soundName(int bank, int program) const; @@ -44,6 +53,9 @@ class WaveFactorySet { return loadedImage; } + [[nodiscard]] juce::MemoryBlock imageWithStoredBanks( + std::span storedSounds, + std::span storedPerformances) const; private: static constexpr size_t soundBankOffset = 0x12e7c; diff --git a/Source/UI/CompactPanelLayout.h b/Source/UI/CompactPanelLayout.h new file mode 100644 index 0000000..15cc22c --- /dev/null +++ b/Source/UI/CompactPanelLayout.h @@ -0,0 +1,240 @@ +#pragma once + +#include + +namespace wave::ui::compact +{ +// Geometry from media/WaldorfWaveUI_Compact.svg. The firmware's physical +// switch and LED serials are unchanged; only their screen positions differ. +inline constexpr float width = 1693.0f; +inline constexpr float height = 768.0f; +struct Knob { float originalX, originalY, x, y, artworkSize; }; +inline constexpr std::array knobs { + Knob { 222.000f, 81.000f, 207.000f, 122.500f, 34.000f }, + Knob { 301.000f, 81.000f, 144.000f, 278.500f, 34.000f }, + Knob { 222.000f, 160.000f, 207.000f, 190.500f, 34.000f }, + Knob { 301.000f, 160.000f, 207.000f, 278.500f, 34.000f }, + Knob { 516.000f, 81.000f, 280.994f, 121.000f, 34.000f }, + Knob { 574.000f, 81.000f, 357.000f, 122.500f, 34.000f }, + Knob { 712.000f, 81.000f, 321.000f, 278.500f, 34.000f }, + Knob { 516.000f, 160.000f, 281.000f, 192.000f, 33.000f }, + Knob { 574.000f, 160.000f, 357.000f, 190.500f, 34.000f }, + Knob { 632.000f, 160.000f, 432.000f, 190.500f, 34.000f }, + Knob { 712.000f, 160.000f, 396.000f, 278.500f, 34.000f }, + Knob { 222.000f, 278.000f, 207.000f, 388.500f, 34.000f }, + Knob { 301.000f, 278.000f, 144.000f, 544.500f, 34.000f }, + Knob { 222.000f, 357.000f, 207.000f, 456.500f, 34.000f }, + Knob { 301.000f, 357.000f, 207.000f, 544.500f, 34.000f }, + Knob { 516.000f, 278.000f, 280.994f, 387.000f, 34.000f }, + Knob { 574.000f, 278.000f, 357.000f, 388.500f, 34.000f }, + Knob { 712.000f, 278.000f, 321.000f, 544.500f, 34.000f }, + Knob { 516.000f, 357.000f, 281.000f, 458.000f, 33.000f }, + Knob { 574.000f, 357.000f, 357.000f, 456.500f, 34.000f }, + Knob { 632.000f, 357.000f, 432.000f, 456.500f, 34.000f }, + Knob { 712.000f, 357.000f, 396.000f, 544.500f, 34.000f }, + Knob { 457.000f, 220.000f, 677.000f, 202.000f, 106.000f }, + Knob { 851.000f, 120.000f, 546.000f, 105.000f, 33.000f }, + Knob { 851.000f, 318.000f, 547.000f, 247.000f, 33.000f }, + Knob { 851.000f, 416.000f, 547.000f, 324.000f, 33.000f }, + Knob { 288.000f, 753.000f, 568.000f, 556.000f, 33.000f }, + Knob { 366.000f, 927.000f, 677.000f, 115.000f, 33.000f }, + Knob { 301.000f, 474.000f, 321.000f, 675.500f, 34.000f }, + Knob { 301.000f, 553.000f, 396.000f, 675.500f, 34.000f }, + Knob { 516.000f, 475.000f, 885.002f, 564.000f, 34.000f }, + Knob { 516.000f, 554.000f, 885.002f, 669.000f, 34.000f }, + Knob { 574.000f, 475.000f, 962.002f, 564.000f, 34.000f }, + Knob { 574.000f, 554.000f, 962.002f, 669.000f, 34.000f }, + Knob { 632.000f, 475.000f, 1039.000f, 564.000f, 34.000f }, + Knob { 632.000f, 554.000f, 1039.000f, 669.000f, 34.000f }, + Knob { 693.000f, 475.000f, 1116.000f, 564.000f, 34.000f }, + Knob { 693.000f, 554.000f, 1116.000f, 669.000f, 34.000f }, + Knob { 1670.000f, 159.000f, 1389.000f, 192.000f, 34.000f }, + Knob { 1729.000f, 159.000f, 1389.000f, 122.500f, 34.000f }, + Knob { 1670.000f, 237.000f, 1328.000f, 192.000f, 34.000f }, + Knob { 1729.000f, 237.000f, 1450.000f, 192.500f, 34.000f }, + Knob { 1787.000f, 237.000f, 1511.000f, 192.500f, 34.000f }, + Knob { 1865.000f, 81.000f, 1572.000f, 122.500f, 34.000f }, + Knob { 1865.000f, 159.000f, 1450.000f, 122.500f, 34.000f }, + Knob { 1865.000f, 237.000f, 1511.000f, 122.500f, 34.000f }, + Knob { 1552.000f, 354.000f, 1267.000f, 304.000f, 34.000f }, + Knob { 1611.000f, 354.000f, 1328.000f, 304.000f, 34.000f }, + Knob { 1670.000f, 354.000f, 1389.000f, 304.000f, 34.000f }, + Knob { 1729.000f, 354.000f, 1450.000f, 304.000f, 34.000f }, + Knob { 1787.000f, 354.000f, 1511.000f, 304.000f, 34.000f }, + Knob { 2022.000f, 159.000f, 1328.000f, 412.500f, 34.000f }, + Knob { 2022.000f, 237.000f, 1267.000f, 412.500f, 34.000f }, + Knob { 2081.000f, 237.000f, 1389.000f, 412.500f, 34.000f }, + Knob { 2159.000f, 159.000f, 1450.000f, 412.500f, 34.000f }, + Knob { 2159.000f, 237.000f, 1511.000f, 412.500f, 34.000f }, + Knob { 1963.000f, 354.000f, 1328.000f, 528.000f, 34.000f }, + Knob { 2022.000f, 354.000f, 1389.000f, 528.000f, 34.000f }, + Knob { 2081.000f, 354.000f, 1450.000f, 528.000f, 34.000f }, + Knob { 2139.000f, 354.000f, 1511.000f, 528.000f, 34.000f }, + Knob { 1963.000f, 473.000f, 1272.000f, 642.500f, 34.000f }, + Knob { 1963.000f, 551.000f, 1333.000f, 642.500f, 34.000f }, +}; +struct Button { int serial; float x, y; }; +inline constexpr std::array buttons { + Button { 0, 142.836f, 186.283f }, // Oscillator 1 Octave + Button { 1, 142.836f, 455.283f }, // Oscillator 2 Octave + Button { 2, 107.500f, 683.283f }, // LFO Select + Button { 5, 177.500f, 683.283f }, // LFO Shape + Button { 7, 244.500f, 683.283f }, // LFO Trigger + Button { 14, 812.521f, 665.521f }, // Wave-envelope Select + Button { 20, 521.000f, 442.984f }, // Knob Mode + Button { 8, 263.165f, 279.165f }, // Oscillator 1 Edit + Button { 17, 452.165f, 279.165f }, // Wave 1 Edit + Button { 86, 545.165f, 183.165f }, // Oscillator Mixer Edit + Button { 9, 263.165f, 545.165f }, // Oscillator 2 Edit + Button { 18, 452.165f, 545.165f }, // Wave 2 Edit + Button { 10, 452.165f, 676.165f }, // LFO Edit + Button { 19, 1176.165f, 632.165f }, // Wave/free-envelope Edit + Button { 24, 801.400f, 115.560f }, // Mute + Button { 78, 847.320f, 115.560f }, // Solo + Button { 31, 1107.670f, 115.560f }, // Group Edit + Button { 21, 801.400f, 425.040f }, // Page left + Button { 23, 833.380f, 425.040f }, // Page right + Button { 71, 944.900f, 425.040f }, // Cancel / ESC + Button { 70, 976.880f, 425.040f }, // OK / Return + Button { 69, 1088.400f, 425.040f }, // Minus + Button { 72, 1120.380f, 425.040f }, // Plus + Button { 43, 1262.400f, 151.630f }, // Filter Type + Button { 75, 1262.400f, 201.630f }, // Filter Select + Button { 60, 1571.165f, 192.165f }, // Filter Edit + Button { 67, 1571.165f, 412.165f }, // Amplifier Edit + Button { 59, 1571.165f, 304.165f }, // Filter-envelope Edit + Button { 66, 1571.165f, 523.165f }, // Amplifier-envelope Edit + Button { 61, 1393.165f, 642.165f }, // Panning Edit + Button { 42, 636.500f, 486.500f }, // Copy + Button { 41, 676.500f, 486.500f }, // Compare / Undo + Button { 40, 714.500f, 486.500f }, // Recall / Init + Button { 44, 638.500f, 583.500f }, // Bank + Button { 58, 714.500f, 583.500f }, // Disk + Button { 57, 677.000f, 639.500f }, // Store + Button { 62, 1462.500f, 641.500f }, // Aux + Button { 64, 1505.500f, 641.500f }, // Control Mixer / Comparator + Button { 65, 1549.500f, 641.500f }, // Control Delay / S&H + Button { 63, 1593.500f, 641.500f }, // Control Shaper / Ramp + Button { 3, 520.593f, 710.575f }, // Button 1 + Button { 4, 574.593f, 710.575f }, // Button 2 + Button { 6, 520.500f, 559.500f }, // Glide On/Off + Button { 11, 546.165f, 626.165f }, // Glide Edit + Button { 73, 639.500f, 707.500f }, // Octave Down + Button { 12, 714.500f, 707.500f }, // Octave Up + Button { 22, 801.400f, 161.760f }, // Instrument 1 + Button { 25, 847.320f, 161.760f }, // Instrument 2 + Button { 26, 892.420f, 161.760f }, // Instrument 3 + Button { 27, 938.340f, 161.760f }, // Instrument 4 + Button { 79, 983.440f, 161.760f }, // Instrument 5 + Button { 28, 1029.360f, 161.760f }, // Instrument 6 + Button { 29, 1074.460f, 161.760f }, // Instrument 7 + Button { 30, 1120.380f, 161.760f }, // Instrument 8 + Button { 38, 1196.990f, 115.560f }, // Quick Edit + Button { 33, 1196.990f, 160.300f }, // Global Edit + Button { 35, 1196.990f, 203.300f }, // Sequencer + Button { 34, 1196.990f, 245.300f }, // Option + Button { 32, 1196.990f, 288.300f }, // Wave Edit + Button { 37, 1196.990f, 332.300f }, // External Edit + Button { 36, 1196.990f, 375.300f }, // Instrument Edit + Button { 39, 1196.990f, 418.300f }, // Performance + Button { 48, 638.500f, 325.500f }, // 7 + Button { 51, 676.500f, 325.500f }, // 8 + Button { 54, 714.500f, 325.500f }, // 9 + Button { 53, 638.500f, 363.500f }, // 4 + Button { 50, 676.500f, 363.500f }, // 5 + Button { 49, 714.500f, 363.500f }, // 6 + Button { 46, 638.500f, 401.500f }, // 1 + Button { 56, 676.500f, 401.500f }, // 2 + Button { 55, 714.500f, 401.500f }, // 3 + Button { 45, 638.500f, 439.500f }, // 1__ + Button { 52, 676.500f, 439.500f }, // 0 + Button { 47, 714.500f, 439.500f }, // Hold +}; +struct Led { int redSerial, greenSerial; float x, y; }; +inline constexpr std::array leds { + Led { 9, -1, 141.836f, 108.283f }, + Led { 73, -1, 141.836f, 120.283f }, + Led { 1, -1, 141.836f, 145.283f }, + Led { 65, -1, 141.836f, 158.283f }, + Led { 12, -1, 141.836f, 377.283f }, + Led { 28, -1, 141.836f, 389.283f }, + Led { 44, -1, 141.836f, 414.283f }, + Led { 60, -1, 141.836f, 427.283f }, + Led { -1, 25, 141.836f, 133.283f }, + Led { -1, 76, 141.836f, 402.283f }, + Led { 15, -1, 286.080f, 258.160f }, + Led { 80, -1, 475.080f, 258.160f }, + Led { 95, -1, 568.080f, 162.160f }, + Led { 47, -1, 286.080f, 524.160f }, + Led { 32, -1, 475.080f, 524.160f }, + Led { 18, -1, 475.080f, 655.160f }, + Led { 48, -1, 1199.080f, 611.160f }, + Led { 68, -1, 1594.080f, 171.160f }, + Led { 77, -1, 1594.080f, 391.160f }, + Led { 29, -1, 1594.080f, 283.160f }, + Led { 61, -1, 1594.080f, 502.160f }, + Led { 20, -1, 1416.080f, 621.160f }, + Led { 75, -1, 569.080f, 605.160f }, + Led { 83, -1, 636.820f, 463.500f }, + Led { 62, -1, 676.820f, 463.500f }, + Led { 46, -1, 714.820f, 463.500f }, + Led { 84, -1, 626.500f, 560.500f }, + Led { 85, -1, 650.500f, 560.500f }, + Led { 52, -1, 714.500f, 559.500f }, + Led { 87, -1, 676.500f, 615.500f }, + Led { 30, -1, 1462.820f, 618.500f }, + Led { 14, -1, 1505.820f, 618.500f }, + Led { 4, -1, 1549.820f, 618.500f }, + Led { 78, -1, 1593.820f, 618.500f }, + Led { 11, -1, 520.820f, 536.500f }, + Led { 27, -1, 639.500f, 683.500f }, + Led { 58, -1, 714.500f, 683.500f }, + Led { 16, -1, 520.593f, 682.950f }, + Led { 35, -1, 574.593f, 682.950f }, + Led { 6, -1, 543.000f, 429.283f }, + Led { 70, -1, 543.000f, 441.283f }, + Led { 71, -1, 543.000f, 455.283f }, + Led { 7, -1, 543.000f, 468.283f }, + Led { 24, -1, 106.500f, 643.000f }, + Led { 8, -1, 106.500f, 655.000f }, + Led { 49, -1, 156.000f, 630.283f }, + Led { 2, -1, 189.500f, 630.283f }, + Led { 66, -1, 156.000f, 643.283f }, + Led { 72, -1, 189.500f, 643.000f }, + Led { 19, -1, 156.000f, 655.283f }, + Led { 67, -1, 189.500f, 655.283f }, + Led { 17, -1, 246.500f, 643.000f }, + Led { 56, -1, 246.500f, 656.000f }, + Led { 34, -1, 791.313f, 567.911f }, + Led { 40, -1, 791.313f, 599.327f }, + Led { 23, -1, 791.313f, 613.827f }, + Led { 39, -1, 791.313f, 628.327f }, + Led { 45, -1, 1247.700f, 89.906f }, + Led { 37, -1, 1247.700f, 102.126f }, + Led { 5, -1, 1247.700f, 113.406f }, + Led { 0, -1, 1247.700f, 125.626f }, + Led { 53, -1, 1297.220f, 113.406f }, + Led { 41, -1, 1297.220f, 125.626f }, + Led { 43, -1, 801.400f, 92.600f }, + Led { 59, -1, 847.320f, 92.600f }, + Led { 54, -1, 1109.720f, 93.420f }, + Led { 3, -1, 944.900f, 401.260f }, + Led { 82, -1, 976.880f, 401.260f }, + Led { 97, 96, 801.400f, 138.800f }, + Led { 99, 98, 847.320f, 138.800f }, + Led { 101, 100, 892.420f, 138.800f }, + Led { 103, 102, 938.340f, 138.800f }, + Led { 105, 104, 983.440f, 138.800f }, + Led { 107, 106, 1029.360f, 138.800f }, + Led { 109, 108, 1074.460f, 138.800f }, + Led { 111, 110, 1120.380f, 138.800f }, + Led { 64, -1, 1163.780f, 115.560f }, + Led { 69, -1, 1163.780f, 160.300f }, + Led { 21, -1, 1163.780f, 203.300f }, + Led { 74, -1, 1163.780f, 245.300f }, + Led { 26, -1, 1163.780f, 288.300f }, + Led { 10, -1, 1163.780f, 332.300f }, + Led { 22, -1, 1163.780f, 375.300f }, + Led { 51, -1, 1163.780f, 418.300f }, +}; +} // namespace wave::ui::compact diff --git a/Source/UI/WaveLcdComponent.cpp b/Source/UI/WaveLcdComponent.cpp index b078c9a..4df668e 100644 --- a/Source/UI/WaveLcdComponent.cpp +++ b/Source/UI/WaveLcdComponent.cpp @@ -9,7 +9,7 @@ WaveLcdComponent::WaveLcdComponent(WaveEmulationAudioProcessor& processor) { setOpaque(false); setInterceptsMouseClicks(false, false); - setTooltip("480 x 64 Waldorf Wave firmware LCD"); + setTooltip("LCD"); static_cast(copyFirmwareDisplay()); startTimerHz(60); } @@ -92,26 +92,28 @@ bool WaveLcdComponent::copyFirmwareDisplay() if (completingModeTransition) modeTransitionWasActive = false; - // Instrument Edit can ask OS 1.700 to rasterise the same completed page - // several more times while its initial Instrument action unwinds. The - // first complete frame is already genuine firmware output, so retain it - // while those residual passes temporarily clear and restore rows. Resume - // live monitoring after VRAM and the display-page register have both been - // quiet for 300 ms. + // Suppress residual passes of the same completed mode page. A new + // Performance/frame publication ends that guard immediately. Continuous + // MIDI/controller redraws must also have a finite hold time. if (postCommitGuardActive && !completingModeTransition) { const auto writes = runtime.lcdVideoWriteCount(); const auto page = runtime.lcdDisplayPage(); const auto now = juce::Time::getMillisecondCounterHiRes(); - if (writes != postCommitWriteCount || page != postCommitPage) + const auto sameRecall = owner.getCurrentProgram() == postCommitProgram + && runtime.lcdDisplayRevision() == postCommitRevision; + if (sameRecall && now - postCommitStartedMs < 500.0) { - postCommitWriteCount = writes; - postCommitPage = page; - postCommitLastChangeMs = now; - return false; + if (writes != postCommitWriteCount || page != postCommitPage) + { + postCommitWriteCount = writes; + postCommitPage = page; + postCommitLastChangeMs = now; + return false; + } + if (now - postCommitLastChangeMs < 300.0) + return false; } - if (now - postCommitLastChangeMs < 300.0) - return false; postCommitGuardActive = false; } @@ -129,16 +131,18 @@ bool WaveLcdComponent::copyFirmwareDisplay() else { const auto pageBefore = runtime.lcdDisplayPage(); + auto revisionBefore = runtime.lcdDisplayRevision(); // Most timer ticks see an unchanged display. Avoid copying all four // VRAM pages until the firmware has written or selected a new frame. if (hasDisplayedFrame && writesBefore == displayedWriteCount - && pageBefore == displayedPage) + && pageBefore == displayedPage && revisionBefore == displayedRevision) return false; auto video = runtime.lcdVideoSnapshot(); auto pageAfter = runtime.lcdDisplayPage(); auto writesAfter = runtime.lcdVideoWriteCount(); + auto revisionAfter = runtime.lcdDisplayRevision(); // Prefer a snapshot taken between firmware writes. The Wavetable/Data // encoder can legitimately make the OS draw on every audio block, @@ -146,8 +150,10 @@ bool WaveLcdComponent::copyFirmwareDisplay() // monitor for the entire gesture. Retry once to reduce tearing, then // publish the newest scan just as the physical LCD would while its RAM // is being changed continuously. - if (writesBefore != writesAfter || pageBefore != pageAfter) + if (writesBefore != writesAfter || pageBefore != pageAfter + || revisionBefore != revisionAfter) { + revisionBefore = revisionAfter; video = runtime.lcdVideoSnapshot(); pageAfter = runtime.lcdDisplayPage(); writesAfter = runtime.lcdVideoWriteCount(); @@ -155,6 +161,9 @@ bool WaveLcdComponent::copyFirmwareDisplay() framebuffer.loadHardwareVideoRam(video.data(), video.size(), pageAfter); displayedWriteCount = writesAfter; + // If publication raced this snapshot, leave its old revision cached + // so the next UI tick retries even after the final VRAM write. + displayedRevision = revisionBefore; displayedPage = pageAfter; hasDisplayedFrame = true; if (completingModeTransition) @@ -162,8 +171,10 @@ bool WaveLcdComponent::copyFirmwareDisplay() postCommitGuardActive = true; postCommitWriteCount = writesAfter; postCommitPage = pageAfter; - postCommitLastChangeMs - = juce::Time::getMillisecondCounterHiRes(); + postCommitLastChangeMs = juce::Time::getMillisecondCounterHiRes(); + postCommitStartedMs = postCommitLastChangeMs; + postCommitProgram = owner.getCurrentProgram(); + postCommitRevision = runtime.lcdDisplayRevision(); } } rebuildPixelImage(); diff --git a/Source/UI/WaveLcdComponent.h b/Source/UI/WaveLcdComponent.h index 754649c..457c8de 100644 --- a/Source/UI/WaveLcdComponent.h +++ b/Source/UI/WaveLcdComponent.h @@ -34,10 +34,14 @@ class WaveLcdComponent final : public juce::Component, juce::Image pixelImage { juce::Image::ARGB, LcdFramebuffer::width, LcdFramebuffer::height, true }; uint64_t displayedWriteCount = 0; + uint64_t displayedRevision = 0; uint8_t displayedPage = 0; uint64_t postCommitWriteCount = 0; uint8_t postCommitPage = 0; double postCommitLastChangeMs = 0.0; + double postCommitStartedMs = 0.0; + uint64_t postCommitRevision = 0; + int postCommitProgram = -1; bool hasDisplayedFrame = false; bool modeTransitionWasActive = false; bool postCommitGuardActive = false; diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index bb172d0..417b338 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -33,6 +33,10 @@ SOFTWARE. ## JUCE 8.0.15 and bundled dependencies JUCE is fetched from https://github.com/juce-framework/JUCE at tag `8.0.15`. +The build applies `cmake/PrepareJuce.cmake` to the fetched checkout. This changes +the Windows VBlank thread to observe thread shutdown and send paced repaint +notifications when `IDXGIOutput::WaitForVBlank` fails. This prevents frozen +repaints and window-recreation deadlocks under Wine. The rest of the pinned JUCE source is unchanged. Its framework modules are dual-licensed under AGPLv3 and the commercial JUCE license. This project's GPL-3.0-or-later license does not replace JUCE's terms. The upstream notice and dependency license index are reproduced in @@ -43,9 +47,11 @@ Distributors must retain applicable dependency notices with their artifacts. ## External instrument data -Waldorf/PPG executable firmware, ROM archives, Wave factory banks, disk images, and recordings are not +Waldorf/PPG executable firmware, ROM archives, Wave factory banks, other disk images, and recordings are not part of the public source distribution or its license. The PPG-derived decoded waveform sample bank is included separately; see `data/README.md` for provenance. +The maintainer-supplied blank INIT disk is also included; its native INIT records +retain their original provenance and are not relicensed by the project GPL grant. The project GPL license does not assert ownership of that third-party data. Import tools operate on user-supplied files or separately downloaded firmware. Public availability of diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 9848bab..2fc6e2e 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -7,6 +7,11 @@ target_link_libraries(WaveCoreTests juce::juce_recommended_warning_flags) add_test(NAME WaveCoreTests COMMAND WaveCoreTests) +if(MSVC) + # The DSP and firmware test fixtures need more than Windows' 1 MB default. + target_link_options(WaveCoreTests PRIVATE /STACK:8388608) +endif() +set_tests_properties(WaveCoreTests PROPERTIES TIMEOUT 120) find_package(Threads REQUIRED) add_executable(M68000ThreadTests M68000ThreadTests.cpp ../Source/Firmware/M68000.cpp) @@ -21,6 +26,13 @@ target_link_libraries(WaveHostStateTests PRIVATE WaveEmulation juce::juce_audio_ add_test(NAME WaveHostStateTests COMMAND WaveHostStateTests) set_tests_properties(WaveHostStateTests PROPERTIES TIMEOUT 120) +add_executable(WavePublicEditorTests WavePublicEditorTests.cpp) +target_include_directories(WavePublicEditorTests PRIVATE ../Source) +target_link_libraries(WavePublicEditorTests PRIVATE WaveEmulation juce::juce_audio_utils) +add_test(NAME WavePublicEditorTests COMMAND WavePublicEditorTests) +set_tests_properties(WavePublicEditorTests PROPERTIES TIMEOUT 60 + ENVIRONMENT "WAVE_EDITOR_DESIGN_SIZE=1") + if(WAVE_HAS_PRIVATE_ROMS) add_executable(WaveIntegrationTests WaveIntegrationTests.cpp) target_include_directories(WaveIntegrationTests PRIVATE ${CMAKE_SOURCE_DIR}/Source) @@ -31,6 +43,21 @@ if(WAVE_HAS_PRIVATE_ROMS) juce::juce_recommended_config_flags juce::juce_recommended_warning_flags) add_test(NAME WaveIntegrationTests COMMAND WaveIntegrationTests) + add_test(NAME WaveFactoryWavetableTests COMMAND WaveIntegrationTests --factory-wavetables) + add_test(NAME WaveLcdBrowsingTests COMMAND WaveIntegrationTests --lcd-browsing) + add_test(NAME WaveWtbDiskImageTests COMMAND WaveIntegrationTests --wtb-image) + add_test(NAME WaveDamagedUserWavetableTests COMMAND WaveIntegrationTests --damaged-user-wavetables) + set_tests_properties(WaveDamagedUserWavetableTests PROPERTIES TIMEOUT 120) + add_test(NAME WaveVoiceAllocationTests COMMAND WaveIntegrationTests --voice-allocation) + add_test(NAME WaveDiskTotalRecallTests COMMAND WaveIntegrationTests --disk-total-recall) + add_test(NAME WaveDiskWriteThroughTests COMMAND WaveIntegrationTests --disk-write-through) + add_test(NAME WaveDamagedDiskLcdTests COMMAND WaveIntegrationTests --damaged-disk-lcd) + set_tests_properties(WaveDamagedDiskLcdTests PROPERTIES TIMEOUT 120) + add_test(NAME WavePerformanceSelectionTests COMMAND WaveIntegrationTests --performance-selection) + add_test(NAME WaveStoreModeLampTests COMMAND WaveIntegrationTests --store-mode-exit) + add_test(NAME WaveKeyboardButtonTests COMMAND WaveIntegrationTests --keyboard-buttons) + add_test(NAME WaveStoredWavetableTests COMMAND WaveIntegrationTests --wavetable-recall) + add_test(NAME WaveReopenBankTests COMMAND WaveIntegrationTests --reopen-banks) add_executable(WaveEditorTests WaveEditorTests.cpp) target_include_directories(WaveEditorTests PRIVATE ${CMAKE_SOURCE_DIR}/Source) @@ -41,6 +68,8 @@ if(WAVE_HAS_PRIVATE_ROMS) juce::juce_recommended_config_flags juce::juce_recommended_warning_flags) add_test(NAME WaveEditorTests COMMAND WaveEditorTests) + add_test(NAME WaveKeyboardButtonEditorTests COMMAND WaveEditorTests --keyboard-buttons) + add_test(NAME WaveNumericKeypadEditorTests COMMAND WaveEditorTests --keypad) add_executable(WavePerformanceBenchmark WavePerformanceBenchmark.cpp) target_include_directories(WavePerformanceBenchmark PRIVATE ${CMAKE_SOURCE_DIR}/Source) @@ -54,10 +83,16 @@ endif() if(WAVE_HAS_PRIVATE_ROMS) set_tests_properties(WaveCoreTests PROPERTIES ENVIRONMENT "WAVE_FIRMWARE_DIR=${CMAKE_SOURCE_DIR}/Firmware/wave_sys1_700;PPG_WAVETABLE_ROM=${CMAKE_SOURCE_DIR}/Firmware/wave_sys1_700/ppg-wave-2.3-v6-wavetables.rom;WAVE_FACTORY_SET=${CMAKE_SOURCE_DIR}/wave.set") - set_tests_properties(WaveIntegrationTests PROPERTIES + set_tests_properties(WaveIntegrationTests WaveFactoryWavetableTests WaveLcdBrowsingTests WaveWtbDiskImageTests WaveDamagedUserWavetableTests WaveVoiceAllocationTests WaveDiskTotalRecallTests WaveDiskWriteThroughTests WaveDamagedDiskLcdTests WavePerformanceSelectionTests WaveStoreModeLampTests WaveStoredWavetableTests WaveKeyboardButtonTests WaveReopenBankTests PROPERTIES WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" ENVIRONMENT "WAVE_FACTORY_SET=${CMAKE_SOURCE_DIR}/wave.set") - set_tests_properties(WaveEditorTests PROPERTIES + set_tests_properties(WaveEditorTests WaveKeyboardButtonEditorTests WaveNumericKeypadEditorTests PROPERTIES WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}" ENVIRONMENT "WAVE_FACTORY_SET=${CMAKE_SOURCE_DIR}/wave.set;WAVE_EDITOR_DESIGN_SIZE=1") endif() + +# Developer tool: drives the real WDV.SYS from a script and prints the ASIC/CV +# write stream for the oracle diff (needs no ROMs at build time). +add_executable(WaveVoiceTrace EXCLUDE_FROM_ALL WaveVoiceTrace.cpp) +target_include_directories(WaveVoiceTrace PRIVATE ../Source) +target_link_libraries(WaveVoiceTrace PRIVATE WaveCore) diff --git a/Tests/WaveCoreTests.cpp b/Tests/WaveCoreTests.cpp index ecb1baf..eceaaf2 100644 --- a/Tests/WaveCoreTests.cpp +++ b/Tests/WaveCoreTests.cpp @@ -1,4 +1,5 @@ #include "Dsp/Cem3387.h" +#include "Dsp/Cem3387Transfer.h" #include "Dsp/PpgWaveRom.h" #include "Dsp/ReferenceComparator.h" #include "Dsp/WaldorfAsic.h" @@ -24,7 +25,10 @@ #include #include +#include #include +#include +#include #include #include #include @@ -107,6 +111,61 @@ void testDosFloppyImageCreation() && std::equal(setup.begin(), setup.end(), static_cast(extracted.data.getData())), "Wave disk reader did not recover the created Setup byte-for-byte"); + for (const auto halfWaves : { 0u, 61u, 64u }) + { + const auto wtbFile = temporaryDirectory.getChildFile("User Table.WTB"); + std::vector wtb(138u + halfWaves * 64u, 0); + std::copy_n(reinterpret_cast("USER WT "), 9, wtb.begin()); + wtb[9] = 0x55; + std::fill(wtb.begin() + 10, wtb.begin() + 138, 0xff); + for (size_t sample = 138; sample < wtb.size(); ++sample) + wtb[sample] = static_cast((sample * 37u + 3u) & 0xffu); + require(wtbFile.replaceWithData(wtb.data(), wtb.size()) + && wave::firmware::DosFloppyImage::createWithWaveWavetable( + imageFile, wtbFile).wasOk(), + "Native WTB could not be packaged in a disk image"); + image.reset(); + require(imageFile.loadFileAsData(image) && image.getSize() == 720u * 1024u, + "WTB disk has incorrect DD geometry"); + bytes = static_cast(image.getData()); + require(std::equal(bytes + 3584, bytes + 3595, + reinterpret_cast("USERTABLWTB")) + && std::equal(wtb.begin(), wtb.end(), bytes + 7168) + && wave::firmware::DosFloppyImage::readWaveSetup(imageFile, extracted).failed(), + "WTB packaging changed the file or misidentified it as a SET"); + const auto size = static_cast(bytes[3612]) + | static_cast(bytes[3613]) << 8u + | static_cast(bytes[3614]) << 16u + | static_cast(bytes[3615]) << 24u; + require(size == wtb.size(), "WTB directory size differs from the original"); + require(std::equal(bytes + 512, bytes + 2048, bytes + 2048), "WTB FAT copies differ"); + const auto clusters = (wtb.size() + 1023u) / 1024u; + for (size_t cluster = 2; cluster < 2 + clusters; ++cluster) + { + const auto offset = 512 + cluster * 3 / 2; + const auto entry = cluster % 2 == 0 + ? static_cast(bytes[offset] | (bytes[offset + 1] & 15u) << 8u) + : static_cast((bytes[offset] >> 4u) | bytes[offset + 1] << 4u); + require(entry == (cluster + 1 == 2 + clusters ? 0xfffu : cluster + 1), + "WTB FAT cluster chain is truncated or unterminated"); + } + const auto imageBefore = image; + require(wave::firmware::DosFloppyImage::createWithWaveWavetable(wtbFile, wtbFile).failed(), + "WTB conversion overwrote its source file"); + wtb[9] = 0; + image.reset(); + require(wtbFile.replaceWithData(wtb.data(), wtb.size()) + && wave::firmware::DosFloppyImage::createWithWaveWavetable( + imageFile, wtbFile).failed() + && imageFile.loadFileAsData(image) && image == imageBefore, + "Rejected WTB conversion changed the destination image"); + wtb[9] = 0x55; + wtb.push_back(1); + require(wtbFile.replaceWithData(wtb.data(), wtb.size()) + && wave::firmware::DosFloppyImage::createWithWaveWavetable( + imageFile, wtbFile).failed(), + "Truncated WTB Wave data passed validation"); + } require(temporaryDirectory.deleteRecursively(), "Could not remove the temporary DD-image test directory"); } @@ -156,7 +215,7 @@ void testDp8473MountedDiskImage() (void) controller.read(0xa8002b); for (int byte = 0; byte < 7; ++byte) (void) controller.read(0xa8000b); - require(controller.isDirty() && controller.flush().wasOk(), + require(controller.flush().wasOk(), "DP8473 did not persist a written sector"); juce::MemoryBlock persisted; @@ -166,12 +225,170 @@ void testDp8473MountedDiskImage() require(std::all_of(persistedBytes + 1024, persistedBytes + 1536, [](uint8_t value) { return value == 0xa5; }), "DP8473 sector writes were not saved at the correct CHS offset"); + // Reopening the same path must flush pending writes before reading it. + send({ 0x45, 0x00, 0x00, 0x00, 0x04, 0x02, 0x04, 0x2a, 0xff }); + for (int byte = 0; byte < 512; ++byte) + controller.write(0xa8001b, 0x3c); + (void) controller.read(0xa8002b); + for (int byte = 0; byte < 7; ++byte) + (void) controller.read(0xa8000b); + require(controller.mount(temporary).wasOk(), + "DP8473 could not reopen its dirty mounted image"); + controller.write(0xa80005, 0x1c); + send({ 0x46, 0x00, 0x00, 0x00, 0x04, 0x02, 0x04, 0x2a, 0xff }); + for (int byte = 0; byte < 512; ++byte) + require(controller.read(0xa8001b) == 0x3c, + "Reopening the mounted image discarded pending sector changes"); + (void) controller.read(0xa8002b); + for (int byte = 0; byte < 7; ++byte) + (void) controller.read(0xa8000b); require(controller.eject().wasOk(), "DP8473 could not eject its mounted image"); require((controller.read(0xa8000f) & 0x80u) != 0, "DP8473 did not report an empty drive after ejecting its image"); require(temporary.deleteFile(), "Could not remove the temporary DP8473 image"); } +void testDp8473AutomaticDiskWrites() +{ + juce::TemporaryFile directory; + const auto media = directory.getFile().getChildFile("media"); + const auto offlineMedia = directory.getFile().getChildFile("offline"); + require(media.createDirectory().wasOk(), "Could not create disk-write test directory"); + const auto first = media.getChildFile("First.img"); + const auto second = media.getChildFile("Second.img"); + require(wave::firmware::DosFloppyImage::createEmpty(first).wasOk() + && wave::firmware::DosFloppyImage::createEmpty(second).wasOk(), + "Could not create disk-write fixtures"); + juce::MemoryBlock expectedFirst, expectedSecond; + require(first.loadFileAsData(expectedFirst) && second.loadFileAsData(expectedSecond), + "Could not read disk-write fixtures"); + const auto fillSector = [](juce::MemoryBlock& bytes, int sector, uint8_t value) { + std::fill_n(static_cast(bytes.getData()) + (sector - 1) * 512, + 512, value); + }; + const auto matches = [](const juce::File& file, const juce::MemoryBlock& expected) { + juce::MemoryBlock bytes; + return file.loadFileAsData(bytes) && bytes == expected; + }; + const auto waitFor = [](const auto& predicate) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(4); + while (!predicate()) + { + if (std::chrono::steady_clock::now() >= deadline) + return false; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + return true; + }; + + { + wave::firmware::Dp8473 controller; + require(controller.mount(first).wasOk(), "Could not mount disk-write fixture"); + controller.write(0xa80005, 0x1c); + const auto send = [&controller](std::initializer_list bytes) { + for (const auto byte : bytes) + controller.write(0xa8000b, byte); + }; + const auto finish = [&controller] { + (void) controller.read(0xa8002b); + for (int byte = 0; byte < 7; ++byte) + (void) controller.read(0xa8000b); + }; + const auto writeSector = [&](uint8_t sector, uint8_t value) { + send({ 0x45, 0x00, 0x00, 0x00, sector, 0x02, sector, 0x2a, 0xff }); + for (int byte = 0; byte < 512; ++byte) + controller.write(0xa8001b, value); + finish(); + }; + + writeSector(3, 0xa5); + fillSector(expectedFirst, 3, 0xa5); + require(waitFor([&] { return !controller.isDirty(); }) + && matches(first, expectedFirst), + "Sector writes did not reach the mounted file without a manual save"); + + send({ 0x4d, 0x00, 0x02, 0x02, 0x2a, 0xe5 }); + for (const auto byte : { 0, 0, 4, 2, 0, 0, 5, 2 }) + controller.write(0xa8001b, static_cast(byte)); + finish(); + fillSector(expectedFirst, 4, 0xe5); + fillSector(expectedFirst, 5, 0xe5); + require(waitFor([&] { return !controller.isDirty(); }) + && matches(first, expectedFirst), + "Formatted sectors did not automatically replace the disk image"); + + // Manual flushes and the automatic writer may overlap newer DMA writes. + // The last revision must win and all unrelated bytes must survive. + std::atomic flushesSucceeded{ true }; + std::thread flusher([&] { + for (int flush = 0; flush < 32; ++flush) + { + if (controller.flush().failed()) + flushesSucceeded.store(false); + std::this_thread::sleep_for(std::chrono::milliseconds(8)); + } + }); + for (uint8_t value = 0; value < 32; ++value) + { + writeSector(6, value); + std::this_thread::sleep_for(std::chrono::milliseconds(8)); + } + flusher.join(); + fillSector(expectedFirst, 6, 31); + require(flushesSucceeded.load() + && waitFor([&] { return !controller.isDirty(); }) + && matches(first, expectedFirst), + "Concurrent saves replaced newer sectors with an older image"); + + // A disconnected destination must retain pending bytes and retry when + // it returns, without replacing the old file with incomplete data. + require(media.moveFileTo(offlineMedia), "Could not disconnect test media"); + writeSector(7, 0x7c); + require(waitFor([&] { return controller.mountedDescription().contains("save failed"); }) + && controller.isDirty() + && matches(offlineMedia.getChildFile(first.getFileName()), expectedFirst), + "A failed automatic save lost data or was not reported"); + fillSector(expectedFirst, 7, 0x7c); + require(offlineMedia.moveFileTo(media), "Could not reconnect test media"); + require(waitFor([&] { return !controller.isDirty(); }) + && matches(first, expectedFirst) + && !controller.mountedDescription().contains("save failed"), + "Automatic disk saving did not recover after reconnecting media"); + + writeSector(8, 0x8d); + fillSector(expectedFirst, 8, 0x8d); + require(controller.mount(second).wasOk() && matches(first, expectedFirst), + "Changing disks lost pending writes to the previous image"); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + require(matches(second, expectedSecond), + "The old disk's automatic save overwrote the replacement image"); + controller.write(0xa80005, 0x1c); + writeSector(9, 0x9e); + fillSector(expectedSecond, 9, 0x9e); + // Destruction must save even if the batching interval has not elapsed. + } + require(matches(second, expectedSecond), + "Controller destruction lost the final pending disk write"); + + require(second.setReadOnly(true), "Could not write-protect test media"); + auto writeProtected = false; + { + wave::firmware::Dp8473 controller; + const auto mounted = controller.mount(second); + controller.write(0xa80005, 0x1c); + for (const auto byte : { 0x45, 0, 0, 0, 9, 2, 9, 0x2a, 0xff }) + controller.write(0xa8000b, static_cast(byte)); + const auto st0 = controller.read(0xa8000b); + const auto st1 = controller.read(0xa8000b); + writeProtected = mounted.wasOk() && !controller.isWritable() + && !controller.drqAsserted() && !controller.isDirty() + && (st0 & 0x40u) != 0 && (st1 & 0x02u) != 0; + } + require(second.setReadOnly(false), "Could not unlock test media"); + require(writeProtected && matches(second, expectedSecond), + "Automatic saving bypassed native floppy write protection"); +} + void testCutoffControlLaw() { require(std::abs(wave::parameters::cutoffFrequencyForStep(0.0f) - 20.0f) < 1.0e-5f @@ -306,11 +523,195 @@ void testAsicClockMixOverflowAndVcfSaturation() const auto knee = wave::dsp::Cem3387::saturateVcfInput(0.7f); const auto full = wave::dsp::Cem3387::saturateVcfInput(1.0f); require(std::abs(small - 0.1f) < 0.001f - && knee > 0.60f && knee < 0.67f - && full > knee && full < 0.90f + && std::abs(knee - 0.7f) < 0.001f + && full > knee && full > 0.995f && full <= 1.0f + && wave::dsp::Cem3387::saturateVcfInput(8.0f) < 1.301f && std::abs(wave::dsp::Cem3387::saturateVcfInput(-0.7f) + knee) < 1.0e-6f, - "VCF input saturation is not a mild symmetric compression near 70% level"); + "VCF input headroom compresses nominal levels or fails to limit overload"); +} + +void testAsicResampling(double clockRate = 250000.0) +{ + for (const auto hostRate : { 32000.0, 44100.0, 48000.0, 88200.0, + 96000.0, 192000.0, 250000.0, 384000.0 }) + { + wave::dsp::AsicResampler resampler; + resampler.prepare(hostRate, clockRate); + auto clockPhase = 0.0; + auto tick = int64_t { 0 }; + const auto render = [&](double frequency, int samples) { + auto energy = 0.0; + for (int sample = 0; sample < samples; ++sample) + { + clockPhase += clockRate / hostRate; + while (clockPhase >= 1.0) + { + clockPhase -= 1.0; + ++tick; + resampler.push(static_cast(std::cos( + juce::MathConstants::twoPi * frequency + * static_cast(tick) / clockRate))); + } + const auto value = resampler.read(clockPhase); + energy += static_cast(value) * value; + } + return std::sqrt(energy / samples); + }; + const auto measure = [&](double frequency) { + resampler.reset(); + clockPhase = 0.0; + tick = 0; + static_cast(render(frequency, 4096)); + return render(frequency, 8192); + }; + require(std::abs(measure(0.0) - 1.0) < 2.0e-6, + "ASIC resampler changes DC gain"); + const auto passband = measure(0.40 * std::min(hostRate, clockRate)); + require(std::abs(passband - std::sqrt(0.5)) < 0.002, + "ASIC resampler attenuates the audible passband"); + if (hostRate < clockRate) + for (const auto fraction : { 0.501, 0.55, 0.73, 1.13, 1.91 }) + { + const auto frequency = fraction * hostRate; + if (frequency < clockRate * 0.5) + require(measure(frequency) < 0.0002, + "ASIC resampler folds ultrasonic harmonics into the host band"); + } + + // Check the actual fractional sampling time, including hosts faster + // than the ASIC (some output frames contain no new internal tick). + resampler.reset(); + clockPhase = 0.0; + tick = 0; + constexpr auto frequency = 1000.0; + const auto delayTicks = 2.0 * std::ceil(24.0 * clockRate / std::min(hostRate, clockRate)); + static_cast(render(frequency, 4096)); + for (int sample = 0; sample < 1024; ++sample) + { + static_cast(render(frequency, 1)); + const auto expected = std::cos(juce::MathConstants::twoPi * frequency + * (static_cast(tick) + clockPhase + - delayTicks) / clockRate); + require(std::abs(resampler.read(clockPhase) - expected) < 0.0001, + "ASIC resampling has incorrect fractional timing"); + } + resampler.reset(); + require(resampler.read(0.37) == 0.0f, + "ASIC resampler retains history after reset"); + } +} + +void testResamplerSimdAgainstScalar(double clockRate = 250000.0) +{ + constexpr auto phases = 64; + for (const auto rate : { 22050.0, 44100.0, 48000.0, 96000.0, 192000.0, 250000.0 }) + { + wave::dsp::AsicResampler resampler; + resampler.prepare(rate, clockRate); + const auto ratio = clockRate / std::min(rate, clockRate); + const auto taps = 4 * static_cast(std::ceil(24.0 * ratio)); + const auto radius = static_cast(taps) * 0.5; + const auto cutoff = 0.45 / ratio; + std::vector coefficients(static_cast((phases + 1) * taps)); + for (int phase = 0; phase <= phases; ++phase) + { + double sum = 0.0; + for (int tap = 0; tap < taps; ++tap) + { + const auto distance = tap + static_cast(phase) / phases - radius; + const auto angle = juce::MathConstants::twoPi * cutoff * distance; + const auto sinc = std::abs(angle) < 1.0e-12 ? 1.0 : std::sin(angle) / angle; + const auto window = 0.42 + 0.5 * std::cos( + juce::MathConstants::pi * distance / radius) + + 0.08 * std::cos(juce::MathConstants::twoPi * distance / radius); + auto& value = coefficients[static_cast(phase * taps + tap)]; + value = static_cast(2.0 * cutoff * sinc * window); + sum += value; + } + for (int tap = 0; tap < taps; ++tap) + { + auto& value = coefficients[static_cast(phase * taps + tap)]; + value = static_cast(value / sum); + } + } + std::vector history(static_cast(taps)); + int head = 0; + uint32_t random = 12345; + for (int tick = 0; tick < taps * 2 + 9; ++tick) + { + random = random * 1664525u + 1013904223u; + const auto input = static_cast(static_cast(random)) / 2147483648.0f; + resampler.push(input); + head = (head + taps - 1) % taps; + history[static_cast(head)] = input; + for (const auto fraction : { 0.0, 0.013, 0.37, 0.999, 1.0 }) + { + const auto position = fraction * phases; + const auto phase = std::min(phases - 1, static_cast(position)); + const auto blend = static_cast(position - phase); + std::array a {}, b {}; + for (int tap = 0; tap < taps; ++tap) + { + const auto sample = history[static_cast((head + tap) % taps)]; + const auto lane = static_cast(tap % 4); + a[lane] += sample * coefficients[static_cast(phase * taps + tap)]; + b[lane] += sample * coefficients[static_cast((phase + 1) * taps + tap)]; + } + const auto first = (a[0] + a[1]) + (a[2] + a[3]); + const auto second = (b[0] + b[1]) + (b[2] + b[3]); + const auto expected = first + blend * (second - first); + require(std::abs(resampler.read(fraction) - expected) < 2.0e-6f, + "SIMD resampler differs from the scalar convolution"); + } + } + } +} + +void testHighRegisterOscillatorResampling() +{ + // A synthetic bright wave has a 10 kHz fundamental and a 30 kHz third + // harmonic. Point sampling at 48 kHz folds the third down to 18 kHz. + using Bank = wave::dsp::WavetableBank; + std::vector rom(static_cast(Bank::factoryTableCount) + * Bank::wavesPerTable * Bank::samplesPerWave); + for (size_t sample = 0; sample < rom.size(); ++sample) + { + const auto phase = juce::MathConstants::twoPi + * static_cast(sample % Bank::samplesPerWave) + / Bank::samplesPerWave; + rom[sample] = static_cast(std::lround(48.0 * (std::cos(phase) + + std::cos(3.0 * phase)))); + } + Bank bank; + require(bank.loadSigned8BitRom(rom.data(), rom.size()), + "Synthetic high-register wavetable did not load"); + wave::dsp::OscillatorChipProxy oscillator; + oscillator.prepare(48000.0); + oscillator.setFrequency(10000.0f); + for (int sample = 0; sample < 4096; ++sample) + static_cast(oscillator.process(bank, 0, 0.0f)); + std::array real {}; + std::array imaginary {}; + constexpr std::array frequencies { 10000.0, 18000.0 }; + constexpr int sampleCount = 4800; + for (int sample = 0; sample < sampleCount; ++sample) + { + const auto output = oscillator.process(bank, 0, 0.0f); + for (size_t bin = 0; bin < frequencies.size(); ++bin) + { + const auto angle = juce::MathConstants::twoPi * frequencies[bin] + * sample / 48000.0; + real[bin] += output * std::cos(angle); + imaginary[bin] += output * std::sin(angle); + } + } + const auto fundamental = 2.0 * std::hypot(real[0], imaginary[0]) / sampleCount; + const auto alias = 2.0 * std::hypot(real[1], imaginary[1]) / sampleCount; + require(fundamental > 0.35 && fundamental < 0.40, + "High-register oscillator loses its in-band fundamental"); + require(alias < 0.0001, + "High-register oscillator aliases its ultrasonic third harmonic"); } void testWaveEnvelopeTraversal() @@ -391,6 +792,279 @@ void testDspMathTables() "MIDI pitch lookup table exceeded its error bound"); } +void testPerformanceAudioOutRouting() +{ + // Firmware Audio Out values: 0 Aux only, 1 main, 2 sub 1, 3 sub 2. + const auto mainLevel = [](int audioOutput) { + wave::dsp::WaldorfEngine engine; + engine.prepare(48000.0, 512); + wave::dsp::WaldorfEngine::PerformanceSnapshot performance; + auto& layer = performance.layers[0]; + layer.enabled = true; + layer.source = 2; + layer.audioOutput = audioOutput; + layer.sound.attackSeconds = 0.001f; + juce::AudioBuffer audio(2, 512); + juce::MidiBuffer noteOn; + noteOn.addEvent(juce::MidiMessage::noteOn(1, 60, 0.9f), 0); + for (int block = 0; block < 4; ++block) + { + audio.clear(); + engine.render(audio, block == 0 ? noteOn : juce::MidiBuffer(), performance); + } + return audio.getMagnitude(0, 512); + }; + require(mainLevel(1) > 1.0e-3f, "Audio Out 'main' (1) is silent"); + require(mainLevel(0) < 1.0e-4f && mainLevel(2) < 1.0e-4f && mainLevel(3) < 1.0e-4f, + "Aux-only and sub outputs reached the main mix"); +} + +void testStartPhaseCode() +{ + using Engine = wave::dsp::WaldorfEngine; + // Free start: Startphase 0 writes no phase load and ignores the route. + require(Engine::startPhaseCode(0, 127, 32767, false) == 0 + && Engine::startPhaseCode(0, 0, -32768, true) == 0, + "A free start was modulated"); + // Fixed phase: amount byte 64 (route off) or a zero source leaves it alone. + for (const auto phase : { 1, 64, 127 }) + for (const auto second : { false, true }) + require(Engine::startPhaseCode(phase, 64, 32767, second) == phase + && Engine::startPhaseCode(phase, 120, 0, second) == phase, + "An unmodulated fixed Startphase changed"); + // Half-scale source, amount +7 steps (stored 120): 64 + 49, both waves. + require(Engine::startPhaseCode(64, 120, 16384, false) == 113 + && Engine::startPhaseCode(64, 120, 16384, true) == 113 + && Engine::startPhaseCode(64, 120, -16384, false) == 15, + "Positive/negative Startphase modulation differs from WDV 0xF92"); + + // Reference values executed on WDV 0xF92 (Wave 1) and 0x1074 (Wave 2) of OS + // 1.700 in the Musashi oracle. Outside 1..127 the two waves differ: Wave 1 + // adds in 16-bit words and keeps 8 bits (signed compare), Wave 2 saturates + // at 127 (unsigned compare), so a negative result gives 127 there. + struct Row { int phase; int amount; int source; int wave1; int wave2; }; + static constexpr Row rows[] = { + { 1, 0, -32768, 128, 127 }, + { 1, 0, -16384, 64, 64 }, + { 1, 0, 16384, 193, 127 }, + { 1, 0, 32767, 129, 127 }, + { 1, 40, -32768, 19, 19 }, + { 1, 40, -16384, 10, 10 }, + { 1, 40, 16384, 248, 127 }, + { 1, 40, 32767, 239, 127 }, + { 1, 88, -32768, 239, 127 }, + { 1, 88, -16384, 248, 127 }, + { 1, 88, 16384, 10, 10 }, + { 1, 88, 32767, 18, 18 }, + { 1, 127, -32768, 129, 127 }, + { 1, 127, -16384, 193, 127 }, + { 1, 127, 16384, 64, 64 }, + { 1, 127, 32767, 128, 127 }, + { 64, 0, -32768, 191, 127 }, + { 64, 0, -16384, 127, 127 }, + { 64, 0, 16384, 1, 1 }, + { 64, 0, 32767, 192, 127 }, + { 64, 40, -32768, 82, 82 }, + { 64, 40, -16384, 73, 73 }, + { 64, 40, 16384, 55, 55 }, + { 64, 40, 32767, 46, 46 }, + { 64, 88, -32768, 46, 46 }, + { 64, 88, -16384, 55, 55 }, + { 64, 88, 16384, 73, 73 }, + { 64, 88, 32767, 81, 81 }, + { 64, 127, -32768, 192, 127 }, + { 64, 127, -16384, 1, 1 }, + { 64, 127, 16384, 127, 127 }, + { 64, 127, 32767, 191, 127 }, + { 127, 0, -32768, 254, 127 }, + { 127, 0, -16384, 190, 127 }, + { 127, 0, 16384, 63, 63 }, + { 127, 0, 32767, 255, 127 }, + { 127, 40, -32768, 145, 127 }, + { 127, 40, -16384, 136, 127 }, + { 127, 40, 16384, 118, 118 }, + { 127, 40, 32767, 109, 109 }, + { 127, 88, -32768, 109, 109 }, + { 127, 88, -16384, 118, 118 }, + { 127, 88, 16384, 136, 127 }, + { 127, 88, 32767, 144, 127 }, + { 127, 127, -32768, 255, 127 }, + { 127, 127, -16384, 63, 63 }, + { 127, 127, 16384, 190, 127 }, + { 127, 127, 32767, 254, 127 }, + }; + for (const auto& row : rows) + require(Engine::startPhaseCode(row.phase, row.amount, row.source, false) == row.wave1 + && Engine::startPhaseCode(row.phase, row.amount, row.source, true) == row.wave2, + "Startphase code differs from the WDV firmware"); +} + +void testStartPhaseCodeMatchesFirmwareWhenAvailable() +{ + // Runs the real WDV key-on path for every Startphase/route combination and + // compares the phase load it writes to the ASIC (reg 2 = n & 3, reg 4 = + // n >> 2, then a select write with bit 4 clear) with startPhaseCode(). + const auto* path = std::getenv("WAVE_FIRMWARE_DIR"); + if (path == nullptr) + return; + wave::firmware::Bundle bundle; + require(bundle.load(juce::File(path)).authenticity + == wave::firmware::Bundle::Authenticity::verifiedOs1700, + "WAVE_FIRMWARE_DIR does not contain the known OS 1.700 pair"); + + auto memoryStorage = std::make_unique(); + auto& memory = *memoryStorage; + memory.clear(); + wave::firmware::VoiceFirmwareRuntime runtime; + runtime.attachSharedMemory(memory); + require(runtime.setBoardIndex(0) && runtime.loadAndReset(bundle.getVoiceImage()), + "WDV image was rejected"); + + const auto poke = [&](uint32_t address, uint32_t value) { + (address >= 0x140000 ? memory.work[address - 0x140000] + : memory.program[address - 0x100000]) + = static_cast(value); + }; + const auto scan = [&] { + constexpr uint32_t alive = 0x10508e; // set after every full voice scan + poke(alive, 0); + for (int slice = 0; runtime.sharedByte(alive - 0x100000) == 0; ++slice) + { + require(slice < 5'000'000, "WDV voice scan did not finish"); + runtime.runCycles(200); + } + }; + + // Same seed as the oracle gate: master-go preset, boot to the main loop, + // 0x40-centred tuning bytes, one voice record per voice. + constexpr uint32_t p2 = 0x130000, p3 = 0x131000, p4 = 0x132000, p5 = 0x133000; + poke(0x10508a, 1); + poke(0x105006, 0x5a); + poke(0x1050e7, 48); + for (int steps = 0; runtime.programCounter() != 0x516; ++steps) + { + require(steps < 50'000'000, "WDV did not reach its main loop"); + runtime.runCycles(1); + } + poke(0x148812, 0x5a); + poke(0x148803, 1); + poke(0x148802, 0x80); + poke(0x148826, 0x40); + for (const auto offset : { 1u, 2u, 13u, 14u }) + poke(p2 + offset, 0x40); + poke(p4 + 12, 2); + poke(p4 + 16, 1); + poke(p4 + 9, 0x40); + poke(p4 + 10, 0x80); + poke(p2 + 0xef, 0x55); + poke(p3 + 0x30, 0x55); + poke(p2 + 40, 1); + constexpr uint32_t voice = 3; + for (uint32_t v = 0; v < 16; ++v) + { + const auto record = 0x100000 + v * 0x100; + const auto pointer = [&](uint32_t offset, uint32_t value) { + for (uint32_t i = 0; i < 4; ++i) + poke(record + offset + i, value >> (24 - 8 * i)); + }; + pointer(0x2c, p5); + pointer(0x30, p4); + pointer(0x34, p3); + pointer(0x38, p2); + poke(record + 0x3d, 0x20 * (v % 3)); + poke(record + 0x3c, v & 1); + poke(record + 0x0a, 48 + v); + poke(0x15a680 + 2 * v, 1); + poke(0x15a681 + 2 * v, 3 * v); + } + scan(); + + // Route source 0x16 is the modulation-wheel word at record + 0xAC. + struct Case { int phase; int amount; int source; }; + for (const auto& c : { Case { 0, 127, 32767 }, Case { 64, 64, 32767 }, Case { 64, 120, 16384 }, + Case { 64, 120, -16384 }, Case { 2, 0, 32767 }, Case { 2, 0, -32768 }, + Case { 100, 127, 24000 }, Case { 127, 8, -8192 }, Case { 1, 127, -32768 }, + Case { 127, 127, 32767 }, Case { 64, 40, 32767 }, Case { 33, 100, -20000 } }) + { + const auto record = 0x100000 + voice * 0x100; + const auto word = static_cast(c.source); + poke(record + 0xac, word >> 8); + poke(record + 0xad, word & 0xff); + for (const auto base : { 0x1bu, 0x2bu }) + { + poke(p2 + base, static_cast(c.phase)); + poke(p2 + base + 1, 0x16); + poke(p2 + base + 2, static_cast(c.amount)); + poke(p5 + base + 2, 0xff); + } + runtime.clearHardwareWrites(); + poke(record + 6, 1); + scan(); + scan(); + + // Pair the ASIC bytes into words, and catch the phase-load selects. + std::array loaded { -1, -1 }; + int reg2 = 0, reg4 = 0; + const auto& writes = runtime.pendingHardwareWrites(); + for (size_t i = 0; i + 1 < writes.size(); ++i) + { + if (writes[i].address < 0x980000 || writes[i].address >= 0x980200 + || (writes[i].address & 1) != 0 || writes[i + 1].address != writes[i].address + 1) + continue; + const auto value = (writes[i].value << 8) | writes[i + 1].value; + const auto reg = writes[i].address & 0xfe; + if (reg == 2) reg2 = value; + else if (reg == 4) reg4 = value; + else if (reg == 0xe && (value & 0x1e) == (0x2 * (voice & 7)) && writes[i].address < 0x980100) + loaded[value & 1] = (reg4 << 2) | (reg2 & 3); + } + for (const auto second : { false, true }) + { + const auto expected = wave::dsp::WaldorfEngine::startPhaseCode( + c.phase, c.amount, c.source, second); + require(loaded[second ? 1 : 0] == (expected == 0 ? -1 : expected), + "startPhaseCode differs from the Startphase the WDV firmware loads"); + } + } +} + +void testStartModulationAtNoteOn() +{ + // The route is evaluated once at note-on and offsets Startphase, not the + // wave position. Source 38 x control 38 is a constant +1. + const auto render = [](float startphase, float amount) { + wave::dsp::WaldorfEngine engine; + engine.prepare(48000.0, 512); + wave::dsp::WaldorfEngine::PerformanceSnapshot performance; + auto& layer = performance.layers[0]; + layer.enabled = true; + layer.source = 2; + layer.sound.attackSeconds = 0.001f; + for (const auto oscillator : { 0, 1 }) + layer.sound.wavePhases[static_cast(oscillator)] = startphase; + for (const auto route : { wave::parameters::wave1StartMod, wave::parameters::wave2StartMod }) + { + auto& assignment = layer.sound.modulationRoutes[static_cast(route)]; + assignment.source = 38; + assignment.control = 38; + assignment.amount = amount; + } + juce::AudioBuffer audio(2, 512); + juce::MidiBuffer noteOn; + noteOn.addEvent(juce::MidiMessage::noteOn(1, 60, 0.9f), 0); + engine.render(audio, noteOn, performance); + return std::vector(audio.getReadPointer(0), audio.getReadPointer(0) + 512); + }; + require(render(0.0f, 0.0f) == render(0.0f, 40.0f) && render(0.0f, 0.0f) == render(0.0f, -40.0f), + "A free start was modulated"); + require(render(64.0f, 0.0f) != render(32.0f, 0.0f), + "Startphase does not change the note-on waveform"); + require(render(64.0f, 40.0f) != render(64.0f, 0.0f) + && render(64.0f, -40.0f) != render(64.0f, 0.0f) + && render(64.0f, 40.0f) != render(64.0f, -40.0f), + "Start modulation did not move a fixed Startphase in both directions"); +} + void testPerformanceTuningTables() { wave::dsp::WaldorfEngine engine; @@ -451,6 +1125,176 @@ void testPerformanceTuningTables() engine.render(audio, {}, performance); require(std::abs(heldPitch(60) - 67.25f) < 1.0e-5f, "Wave SET User table 1 could not be selected directly"); + + // A SET with displaced Performance bytes in its tuning pool must not + // remap every Global Instrument to arbitrary notes. Reset each damaged + // table completely while preserving an adjacent valid custom tuning. + const auto pristineTuning = setImage; + bytes[0x42e7cu + 69u * 2u + 1u] = 0; + bytes[0x42e7cu + 256u + 60u * 2u] = 62; + bytes[0x42e7cu + 256u + 60u * 2u + 1u] = 114; + bytes[0x42e7cu + 512u + 69u * 2u] = 0x80; + bytes[0x42e7cu + 768u + 69u * 2u + 1u] = 115; + const auto damagedTuning = setImage; + juce::ignoreUnused(engine.loadWaveSetUserTables(setImage)); + const auto checkPitch = [&](int table, int key, float expected) { + layer.tuningTable = table; + juce::MidiBuffer events; + events.addEvent(juce::MidiMessage::allSoundOff(1), 0); + events.addEvent(juce::MidiMessage::noteOn(1, key, 0.9f), 1); + engine.render(audio, events, performance); + require(std::abs(heldPitch(key) - expected) < 1.0e-5f, + "Malformed SET tuning data changed the played note"); + }; + for (const auto key : { 48, 60, 69, 72 }) + checkPitch(0, key, static_cast(key)); + checkPitch(8, 60, 60.0f); + checkPitch(9, 60, 62.5f); + checkPitch(10, 60, 60.0f); + checkPitch(11, 60, 60.0f); + require(setImage == damagedTuning, "Tuning quarantine changed source SET bytes"); + juce::ignoreUnused(engine.loadWaveSetUserTables(pristineTuning)); + checkPitch(0, 60, 67.25f); + + // HMT retunes a held chord as notes arrive. The oscillator must keep that + // pitch after the next voice-board control update, including when changing + // back to HMT while the chord is already sounding. + wave::dsp::WaldorfEngine hmtEngine; + hmtEngine.prepare(48000.0, 32); + wave::dsp::WaldorfEngine::PerformanceSnapshot hmtPerformance; + auto& hmtLayer = hmtPerformance.layers[0]; + hmtLayer.enabled = true; + hmtLayer.source = 2; + hmtLayer.tuningTable = 2; + hmtLayer.sound.attackSeconds = 0.001f; + hmtLayer.sound.detuneCents = 0.0f; + + const auto playHmtNote = [&](int midiNote) { + juce::MidiBuffer event; + event.addEvent(juce::MidiMessage::noteOn(1, midiNote, 0.9f), 0); + audio.clear(); + hmtEngine.render(audio, event, hmtPerformance); + }; + const auto oscillatorPitch = [&](int triggerNote) { + for (const auto& state : hmtEngine.voiceStates()) + if (state.active && state.keyDown && state.triggerNote == triggerNote) + return state.oscillator1FrequencyHz; + throw std::runtime_error("Expected HMT test voice is not active"); + }; + const auto frequencyForNote = [](float midiNote) { + return 440.0f * std::exp2((midiNote - 69.0f) / 12.0f); + }; + const auto requireOscillatorPitch = [&](int triggerNote, float tunedNote, + const char* message) { + const auto expected = frequencyForNote(tunedNote); + require(std::abs(oscillatorPitch(triggerNote) - expected) < expected * 1.0e-4f, + message); + }; + + playHmtNote(60); + playHmtNote(64); + audio.clear(); + hmtEngine.render(audio, {}, hmtPerformance); + requireOscillatorPitch(64, 63.86314f, + "New HMT chord note reverted to equal temperament"); + + hmtLayer.tuningTable = 1; + audio.clear(); + hmtEngine.render(audio, {}, hmtPerformance); + requireOscillatorPitch(64, 64.0f, + "Changing from HMT did not retune a held note"); + + hmtLayer.tuningTable = 2; + audio.clear(); + hmtEngine.render(audio, {}, hmtPerformance); + requireOscillatorPitch(64, 63.86314f, + "Switching to HMT retuned only until the next control update"); + + // A held note started in Linear- can be dozens of semitones below its HMT + // pitch. Retuning the voice must also retune its layer glide history, or + // every later note with Glide enabled starts down at the old pitch. + wave::dsp::WaldorfEngine glideEngine; + glideEngine.prepare(48000.0, 32); + auto glidePerformance = hmtPerformance; + auto& glideLayer = glidePerformance.layers[0]; + glideLayer.tuningTable = 3; + glideLayer.sound.glideEnabled = true; + glideLayer.sound.glideRateValue = 50.0f; + juce::MidiBuffer highNote; + highNote.addEvent(juce::MidiMessage::noteOn(1, 84, 0.9f), 0); + glideEngine.render(audio, highNote, glidePerformance); + glideLayer.tuningTable = 2; + glideEngine.render(audio, {}, glidePerformance); + juce::MidiBuffer nextNote; + nextNote.addEvent(juce::MidiMessage::noteOn(1, 86, 0.9f), 0); + glideEngine.render(audio, nextNote, glidePerformance); + auto nextPitch = -1.0f; + for (const auto& state : glideEngine.voiceStates()) + if (state.active && state.keyDown && state.triggerNote == 86) + nextPitch = state.glidePitch; + require(nextPitch > 83.0f && nextPitch < 86.1f, + "Changing to HMT left later Glide notes at the previous low tuning"); + + // With Glide disabled, changing tuning under a held key must not leave + // subsequent notes at the pitch of the old table. + wave::dsp::WaldorfEngine directEngine; + directEngine.prepare(48000.0, 32); + auto directPerformance = hmtPerformance; + auto& directLayer = directPerformance.layers[0]; + directLayer.sound.glideEnabled = false; + directLayer.sound.oscillatorOctaves[0] = -1; + for (const auto table : { 3, 2, 1, 2, 3, 1 }) + { + directLayer.tuningTable = table; + juce::MidiBuffer heldNote; + heldNote.addEvent(juce::MidiMessage::noteOn(1, 72, 0.9f), 0); + directEngine.render(audio, heldNote, directPerformance); + const auto nextTable = table == 3 ? 2 : 3; + directLayer.tuningTable = nextTable; + directEngine.render(audio, {}, directPerformance); + juce::MidiBuffer releaseAndPlay; + releaseAndPlay.addEvent(juce::MidiMessage::noteOff(1, 72), 0); + releaseAndPlay.addEvent(juce::MidiMessage::noteOn(1, 60, 0.9f), 1); + directEngine.render(audio, releaseAndPlay, directPerformance); + auto freshFrequency = 0.0f; + for (const auto& state : directEngine.voiceStates()) + if (state.active && state.keyDown && state.triggerNote == 60) + freshFrequency = state.oscillator1FrequencyHz; + const auto expectedFrequency + = 0.5f * frequencyForNote(nextTable == 3 ? 68.0f : 60.0f); + require(std::abs(freshFrequency - expectedFrequency) + < expectedFrequency * 1.0e-4f, + "Changing a tuning table under a held key left a new note subsonic without Glide"); + juce::MidiBuffer release; + release.addEvent(juce::MidiMessage::noteOff(1, 60), 0); + directEngine.render(audio, release, directPerformance); + } + + wave::dsp::WaldorfEngine chordEngine; + chordEngine.prepare(48000.0, 32); + auto chordPerformance = directPerformance; + auto& chordLayer = chordPerformance.layers[0]; + chordLayer.tuningTable = 1; + chordLayer.sound.oscillatorSemitones[0] = 3.0f; + juce::MidiBuffer firstKey; + firstKey.addEvent(juce::MidiMessage::noteOn(1, 72, 0.9f), 0); + chordEngine.render(audio, firstKey, chordPerformance); + chordLayer.tuningTable = 2; + chordEngine.render(audio, {}, chordPerformance); + juce::MidiBuffer secondKey; + secondKey.addEvent(juce::MidiMessage::noteOn(1, 60, 0.9f), 0); + chordEngine.render(audio, secondKey, chordPerformance); + chordEngine.render(audio, {}, chordPerformance); + for (const auto& state : chordEngine.voiceStates()) + { + if (!state.active || !state.keyDown) + continue; + const auto expected + = frequencyForNote(static_cast(state.triggerNote) - 9.0f); + require(std::abs(state.oscillator1FrequencyHz - expected) + < expected * 1.0e-4f, + "Second key pressed while holding HMT chord has incorrect pitch"); + } } void testFreeRunningEngineLfo() @@ -474,6 +1318,154 @@ void testFreeRunningEngineLfo() "Unsynchronised Wave LFO phase froze while no voice was sounding"); } +void testSparsePerformanceBanks() +{ + constexpr size_t soundOffset = 0x12e7c; + constexpr size_t performanceOffset = 0x22e7c; + juce::MemoryBlock image(performanceOffset + 256 * 512, true); + auto* bytes = static_cast(image.getData()); + bytes[soundOffset + 239] = 0x55; + bytes[performanceOffset + 48] = 0x55; + std::copy_n("ONLY PATCH", 10, bytes + performanceOffset + 32); + wave::presets::WaveFactorySet set; + const auto report = set.load(image); + require(report.validLayout && report.validPerformances == 1 + && report.emptyPerformances == 255, + "A one-patch SET with empty slots was rejected"); + require(set.performanceName(0, 1).empty() && set.performance(1, 127)[48] == 0, + "An empty Performance was replaced during SET import"); + const auto pristine = image; + auto* damaged = bytes + performanceOffset + 151u * 512u; + std::fill_n(damaged, 512, uint8_t{ 0xff }); + damaged[48] = 0x55; + auto damagedReport = set.load(image); + require(damagedReport.validLayout && damagedReport.invalidPerformances == 1 + && set.performanceName(0, 0) == "ONLY PATCH" + && std::all_of(set.performance(1, 23).begin(), set.performance(1, 23).end(), + [](uint8_t value) { return value == 0; }) + && set.sourceImage() == image, + "One damaged Performance rejected the bank or changed the source disk bytes"); + require(set.loadStateSnapshot(image).validLayout && set.performance(1, 23)[0] == 0xff, + "Disk-import quarantine changed an exact host SRAM snapshot"); + image = pristine; + bytes = static_cast(image.getData()); + for (size_t slot = 1; slot <= 7; ++slot) + bytes[performanceOffset + slot * 512u + 32u] = 0xff; + require(!set.load(image).validLayout, + "A bank with more than six malformed Performances passed SET validation"); + image.reset(); + image.setSize(performanceOffset + 256 * 512, true); + require(!set.load(image).validLayout, "A zero-filled file passed disk SET validation"); + require(set.loadStateSnapshot(image).validLayout, + "An empty native host bank failed snapshot recall"); + require(set.performanceName(0, 0).empty(), "Empty snapshot recalled a prior patch"); +} + +void testDamagedUserWavetableImport() +{ + constexpr size_t tableOffset = 0x4387c; + constexpr size_t waveOffset = 0x45afc; + std::vector setup(waveOffset + 1000u * 64u, 128); + const auto reference = [&](int table, int wave, uint16_t value) { + const auto offset = tableOffset + static_cast(table) * 138u + + 10u + static_cast(wave) * 2u; + setup[offset] = static_cast(value >> 8u); + setup[offset + 1] = static_cast(value); + }; + for (int table = 0; table < 64; ++table) + { + const auto record = tableOffset + static_cast(table) * 138u; + setup[record + 9] = 0x55; + std::fill_n(setup.begin() + static_cast(record + 10), 128, 0xff); + reference(table, 0, 0); + reference(table, 60, 1); + } + wave::dsp::WavetableBank init; + require(init.loadWaveSetUserTables(setup.data(), setup.size()), "INIT fixture failed to import"); + const auto hash = [](const wave::dsp::WavetableBank& bank, int first, int last) { + std::vector codes; + for (int table = first; table < last; ++table) + for (int wave = 0; wave < 64; ++wave) + for (int sample = 0; sample < 128; ++sample) + codes.push_back(bank.rawSample(table, wave, sample)); + return juce::SHA256(codes.data(), codes.size()).toHexString(); + }; + auto imported = init; + const auto audioSnapshot = imported.renderSnapshot(); + const auto previousHash = hash(init, 0, 128); + const auto factoryHash = hash(init, 0, 64); + reference(0, 0, 300); + reference(63, 0, 1299); // Last valid user Wave, after damaged table 93. + setup[waveOffset] = 230; + setup[waveOffset + 999u * 64u] = 20; + reference(28, 0, 0x4c54); // DG_PE's misplaced Performance record. + setup[tableOffset + 30u * 138u + 9u] = 0; + reference(31, 0, 1300); // One past the last stored user Wave. + reference(32, 0, 0xffff); // Sparse table with no leading anchor. + reference(32, 15, 2); + const auto source = setup; + require(imported.loadWaveSetUserTables(setup.data(), setup.size()) + && imported.hasWaveSetUserTables() && imported.damagedUserTableCount() == 3, + "Damaged records aborted the complete user-table import"); + require(imported.rawSample(64, 0, 0) == 102 && imported.rawSample(127, 0, 0) == -108, + "Valid tables on either side of a damaged record were not imported"); + for (const auto table : { 92, 94, 95 }) + for (int wave = 0; wave < 64; ++wave) + for (int sample = 0; sample < 128; ++sample) + require(imported.rawSample(table, wave, sample) == init.rawSample(64, wave, sample), + "A damaged user table retained old samples instead of INIT"); + require(imported.rawSample(96, 0, 0) == imported.rawSample(0, 0, 0) + && hash(imported, 0, 64) == factoryHash && hash(init, 0, 128) == previousHash + && hash(audioSnapshot, 0, 128) == previousHash + && setup == source, + "User import changed factory waves, a shared bank, or its source bytes"); + const auto importedHash = hash(imported, 0, 128); + require(!imported.loadWaveSetUserTables(setup.data(), waveOffset) + && hash(imported, 0, 128) == importedHash, + "Truncated SET changed the active wavetable bank"); + for (int table = 0; table < 64; ++table) + setup[tableOffset + static_cast(table) * 138u + 9u] = 0; + require(!imported.loadWaveSetUserTables(setup.data(), setup.size()) + && hash(imported, 0, 128) == importedHash, + "Unrelated data replaced the active wavetable bank"); + require(imported.loadWaveSetUserTables(source.data(), source.size()), "Repeated SET import failed"); + + // Publishing from the loader must not change a bank being sampled by + // the audio thread, including when factory ROMs are replaced explicitly. + std::vector firstBank(128u * 64u * 128u, 24); + std::vector secondBank(firstBank.size(), -53); + require(imported.loadSigned8BitRom(firstBank.data(), firstBank.size()), "Concurrent fixture failed"); + std::atomic finished{ false }; + std::atomic coherent{ true }; + std::atomic snapshots{ 0 }; + std::thread renderer([&] { + while (!finished.load(std::memory_order_acquire)) + { + const auto snapshot = imported.renderSnapshot(); + const auto expected = snapshot.rawSample(0, 0, 0); + if (expected != 24 && expected != -53) + coherent.store(false, std::memory_order_relaxed); + for (int table = 0; table < 128; ++table) + for (int wave = 0; wave < 64; ++wave) + if (snapshot.rawSample(table, wave, (wave * 13) % 128) != expected) + coherent.store(false, std::memory_order_relaxed); + snapshots.fetch_add(1, std::memory_order_relaxed); + } + }); + while (snapshots.load(std::memory_order_acquire) == 0) + std::this_thread::yield(); + bool loaded = true; + for (int load = 0; load < 32; ++load) + { + const auto& bank = load % 2 == 0 ? secondBank : firstBank; + loaded = imported.loadSigned8BitRom(bank.data(), bank.size()) && loaded; + } + finished.store(true, std::memory_order_release); + renderer.join(); + require(loaded && coherent.load() && snapshots.load() > 0, + "Concurrent wavetable publication changed samples within an audio snapshot"); +} + void testFactorySetWhenAvailable() { const auto* path = std::getenv("WAVE_FACTORY_SET"); @@ -518,19 +1510,25 @@ void testFactorySetWhenAvailable() && wavetableBank.hasWaveSetUserTables(), "Factory SET user Wavetables were not decoded"); - // Sound A001 (used by Performance A030, Sitar) stores selector 95. That - // is user-table slot 32, named TSITAR3 in this SET, and maps to engine - // table index 95. Its first 13 entries reference flat factory Wave - // numbers $0507..$0513: table 20, positions 7..19. + // TSITAR3's first 13 references are native U987..U999 (1287..1299), + // followed by legacy Wave Edit workspace references $100D..$103F. constexpr auto sitarTable = 95; + constexpr size_t userWaveBankOffset = 0x45afc; + const auto* setBytes = static_cast(data.getData()); for (int wave = 0; wave < 13; ++wave) - for (int sample = 0; sample < wave::dsp::WavetableBank::samplesPerWave; ++sample) + for (int sample = 0; sample < 64; ++sample) + { + const auto stored = setBytes[userWaveBankOffset + + static_cast(987 + wave) * 64u + + static_cast(sample)]; require(wavetableBank.rawSample(sitarTable, wave, sample) - == wavetableBank.rawSample(20, 7 + wave, sample), - "TSITAR3 factory-Wave reference was decoded incorrectly"); + == static_cast(static_cast(stored) - 128) + && wavetableBank.rawSample(sitarTable, wave, 127 - sample) + == static_cast(static_cast( + static_cast(~stored)) - 128), + "TSITAR3 native user-Wave reference was decoded incorrectly"); + } - constexpr size_t userWaveBankOffset = 0x45afc; - const auto* setBytes = static_cast(data.getData()); for (int sample = 0; sample < 64; ++sample) { const auto stored = setBytes[userWaveBankOffset + 13u * 64u @@ -654,6 +1652,156 @@ void testFactoryUpperWavetableBank() #endif } +void testOriginalWaveFactoryTablesWhenAvailable() +{ + const auto* directory = std::getenv("WAVE_FIRMWARE_DIR"); + if (directory == nullptr) + return; + juce::MemoryBlock image; + require(juce::File(directory).getChildFile("w2sys.bin").loadFileAsData(image), + "Wave factory-table source firmware could not be read"); + wave::dsp::WavetableBank bank; + const auto untouchedUserWave = bank.rawSample(64, 12, 34); + require(bank.loadWaveFactoryRom(image.getData(), image.getSize()), + "Original Wave factory routines failed to produce the verified bank"); + require(bank.hasOriginalWaveFactoryTables() && bank.importedTableCount() == 64, + "Original factory bank was not marked as complete"); + std::vector halfWaves; + for (int table = 0; table < 64; ++table) + for (int wave = 0; wave < 64; ++wave) + for (int sample = 0; sample < 64; ++sample) + { + const auto value = static_cast( + static_cast(bank.rawSample(table, wave, sample)) + 128); + halfWaves.push_back(value); + require(bank.rawSample(table, wave, 127 - sample) + == static_cast(static_cast( + static_cast(~value)) - 128), + "Wave factory waveform lost its complemented half-cycle"); + } + require(juce::SHA256(halfWaves.data(), halfWaves.size()).toHexString() + == "e2d3bdd4d22053058458962df7dc9a7ad08e895190f7b08e7f6b1ef63d1976c3", + "Factory bank differs from the original OS 1.700 routine output"); + require(bank.rawSample(0, 60, 0) == 2 + && bank.rawSample(0, 61, 0) == 2 + && bank.rawSample(0, 62, 0) == 64 + && bank.rawSample(0, 63, 0) == 64 + && bank.rawSample(0, 63, 63) == 1, + "Wave endpoint or triangle/square/saw slots use PPG replacements"); + require(bank.rawSample(64, 12, 34) == untouchedUserWave, + "Factory installation overwrote a user wavetable"); + // The individual ROM Wave palette is separate from the 64 factory + // tables: user records address R000..R299, then U000..U999. + const auto* romBytes = static_cast(image.getData()); + for (int wave = 0; wave < 300; ++wave) + for (int sample = 0; sample < 64; ++sample) + { + const auto value = romBytes[0x41850u + static_cast(wave) * 64u + + static_cast(sample)]; + require(bank.rawRomWaveSample(wave, sample) + == static_cast(static_cast(value) - 128) + && bank.rawRomWaveSample(wave, 127 - sample) + == static_cast(static_cast( + static_cast(~value)) - 128), + "Original ROM Wave palette differs from firmware data"); + } + + constexpr size_t tableOffset = 0x4387c; + constexpr size_t waveOffset = 0x45afc; + std::vector setup(waveOffset + 1000u * 64u, 128); + for (int table = 0; table < 64; ++table) + { + const auto record = tableOffset + static_cast(table) * 138u; + setup[record + 9] = 0x55; + std::fill_n(setup.begin() + static_cast(record + 10), 128, 0xff); + setup[record + 10] = 0; + setup[record + 11] = 0; + setup[record + 130] = 0; + setup[record + 131] = 1; + } + class UserTableBus final : public wave::firmware::M68000Bus + { + public: + std::vector ram = std::vector(0x200000); + bool completed = false; + bool unmapped = false; + uint8_t read8(uint32_t address) noexcept override + { + if (address < ram.size()) return ram[address]; + unmapped = true; + return 0xff; + } + void write8(uint32_t address, uint8_t value) noexcept override + { + if (address < ram.size()) ram[address] = value; + else unmapped = true; + } + bool usesInstructionInterception() const noexcept override { return true; } + bool interceptInstruction(wave::firmware::M68000& cpu, uint32_t pc) noexcept override + { + if (pc != 0x00bd6e) return false; + completed = true; + cpu.endTimeslice(); + return true; + } + } bus; + for (int fixture = 0; fixture < 2; ++fixture) + { + if (fixture == 1) + { + const auto reference = [&](int wave, uint16_t value) { + setup[tableOffset + 10u + static_cast(wave) * 2u] + = static_cast(value >> 8u); + setup[tableOffset + 11u + static_cast(wave) * 2u] + = static_cast(value); + }; + reference(0, 299); + reference(30, 300); + reference(60, 1299); + for (size_t sample = 0; sample < 64; ++sample) + { + setup[waveOffset + sample] = static_cast(sample * 3u); + setup[waveOffset + 999u * 64u + sample] = static_cast(255u - sample * 2u); + } + } + require(bank.loadWaveSetUserTables(setup.data(), setup.size()), + "Native user Wave fixture failed to import"); + std::fill(bus.ram.begin(), bus.ram.end(), 0); + bus.completed = false; + bus.unmapped = false; + std::copy_n(romBytes, image.getSize(), bus.ram.begin() + 0x1000); + std::copy_n(setup.begin() + tableOffset, 138, bus.ram.begin() + 0x148a00); + std::copy_n(setup.begin() + waveOffset, 1000u * 64u, bus.ram.begin() + 0x14ac80); + wave::firmware::M68000 cpu; + cpu.start(bus, 0x0ffffe, 0x011bb8); + cpu.setDataRegister(bus, 0, 64); + cpu.setDataRegister(bus, 1, 0); + for (int cycles = 0; !bus.completed && !bus.unmapped && cycles < 2000000; + cycles += 10000) + cpu.execute(bus, 10000); + require(bus.completed && !bus.unmapped, + "Original firmware failed to generate a native user table"); + for (int wave = 0; wave < 64; ++wave) + for (int sample = 0; sample < 64; ++sample) + { + const auto value = bus.ram[0x104000u + static_cast(wave) * 64u + + static_cast(sample)]; + require(bank.rawSample(64, wave, sample) + == static_cast(static_cast(value) - 128) + && bank.rawSample(64, wave, 127 - sample) + == static_cast(static_cast( + static_cast(~value)) - 128), + "Native user table differs from original firmware output"); + } + } + + auto corrupted = image; + static_cast(corrupted.getData())[100] ^= 1; + require(!bank.loadWaveFactoryRom(corrupted.getData(), corrupted.getSize()) + && bank.hasOriginalWaveFactoryTables() && bank.rawSample(0, 63, 63) == 1, + "Unverified firmware was accepted or changed the existing bank"); +} + void testExpandedFirst32Loading() { constexpr auto byteCount = static_cast(32) @@ -717,7 +1865,11 @@ void testCemStability() auto peak = 0.0f; for (int i = 0; i < 96000; ++i) { - const auto output = filter.process(i == 0 ? 1.0f : 0.0f, 1.0f); + const auto input = i < 48000 + ? std::sin(juce::MathConstants::twoPi * 3200.0f + * static_cast(i) / 48000.0f) + : 0.0f; + const auto output = filter.process(input, 1.0f); require(std::isfinite(output.left) && std::isfinite(output.right), "CEM3387 model became non-finite"); peak = juce::jmax(peak, std::abs(output.left), std::abs(output.right)); @@ -877,6 +2029,54 @@ void testAllVoiceFiltersAreCalibrated() "Fixed reconstruction filters retain an undocumented voice spread"); } +void testReconstructionCachedTransfer() +{ + // Independent, uncached signal path: exercise every DAC code, rounding + // boundary, clipping, reset, and live age changes against the exact curve. + for (const auto rate : { 44100.0, 48000.0, 96000.0, 250000.0 }) + { + wave::dsp::ReconstructionStage reconstruction; + reconstruction.prepare(rate, 0.0f); + const auto firstPole = 1.0f - std::exp( + -juce::MathConstants::twoPi * 15400.0f * 0.5f + / static_cast(rate)); + const auto g = std::tan(juce::MathConstants::pi * 15400.0f + / static_cast(rate)); + const auto a1 = 1.0f / (1.0f + g * (g + 0.5f)); + const auto a2 = g * a1; + const auto a3 = g * a2; + const auto highpass = std::exp(-juce::MathConstants::twoPi * 7.0f + / static_cast(rate)); + float state = 0.0f, secondState = 0.0f, thirdState = 0.0f, dcState = 0.0f; + for (const auto age : { 0.0f, 0.18f, 1.0f, 0.4f, 0.0f }) + { + reconstruction.setAge(age); + for (int code = -140; code <= 140; ++code) + for (const auto offset : { -0.501f, -0.5f, 0.0f, 0.5f, 0.501f }) + { + const auto input = (static_cast(code) + offset) / 127.0f; + const auto quantised = std::round( + juce::jlimit(-1.0f, 1.0f, input) * 127.0f) / 127.0f; + const auto linearity = 26.0f / (1.0f + age * 0.08f); + const auto saturated = linearity * std::tanh(quantised / linearity); + state += firstPole * (saturated - state); + const auto v3 = state - thirdState; + const auto v1 = a1 * secondState + a2 * v3; + const auto v2 = thirdState + a2 * secondState + a3 * v3; + secondState = 2.0f * v1 - secondState; + thirdState = 2.0f * v2 - thirdState; + const auto dc = v2 + highpass * (dcState - v2); + const auto expected = v2 - dc; + dcState = dc; + require(std::abs(reconstruction.process(input) - expected) < 0.000002f, + "Cached reconstruction differs from the uncached transfer"); + } + reconstruction.reset(); + state = secondState = thirdState = dcState = 0.0f; + } + } +} + void testCemControlVoltageSettling() { wave::dsp::Cem3387 circuit; @@ -1041,6 +2241,170 @@ void testCemSelfOscillation() "CEM self-oscillation tracking no longer matches the measured Wave cutoffs"); } +void testCemResonanceAcrossSampleRates() +{ + // A continuous analogue feedback loop must not start oscillating earlier + // as its cutoff approaches the digital sample rate. Drive is an input + // level control, so it must not change the unexcited loop's threshold. + for (const auto cutoff : { 1000.0f, 6000.0f }) + { + auto referenceFrequency = 0; + for (const auto rate : { 44100.0, 48000.0, 96000.0 }) + for (const auto drive : { 0.0f, 18.0f }) + { + const auto measure = [=](float resonance) { + wave::dsp::Cem3387 filter; + filter.prepare(rate, 0.0f); + filter.setControls(cutoff, resonance, drive, 0.0f, 0.0f); + double energy = 0.0; + auto crossings = 0; + auto previous = 0.0f; + for (int sample = 0; sample < static_cast(rate * 2.0); ++sample) + { + const auto output = filter.process(sample == 0 ? 0.1f : 0.0f, + 1.0f).left; + if (sample >= static_cast(rate)) + { + energy += static_cast(output) * output; + if (previous <= 0.0f && output > 0.0f) + ++crossings; + } + previous = output; + } + return std::pair { std::sqrt(energy / rate), crossings }; + }; + const auto belowThreshold = measure(0.85f); + require(belowThreshold.first < 1.0e-5, + "CEM resonance oscillates below threshold at high cutoff or drive"); + require(measure(0.95f).first < 1.0e-5, + "CEM resonance starts oscillating before the analogue threshold"); + const auto oscillating = measure(1.0f); + require(oscillating.first > 0.01, + "CEM maximum resonance fails to oscillate across sample rates"); + if (referenceFrequency == 0) + referenceFrequency = oscillating.second; + require(std::abs(static_cast(oscillating.second) + / static_cast(referenceFrequency) - 1.0f) < 0.02f, + "CEM oscillation frequency shifts with sample rate or drive"); + } + } +} + +void testCemSmallSignalResonanceResponse() +{ + // Datasheet's classical four-pole application: at w = wc, the + // open-loop response is -1/4. Negative feedback k therefore gives + // |H(wc)| / |H(0)| = (1+k)/(4-k), independent of input makeup gain. + constexpr auto resonance = 0.7f; + constexpr auto feedback = 4.15f * resonance; + constexpr auto expectedRatio = (1.0f + feedback) / (4.0f - feedback); + for (const auto rate : { 44100.0, 48000.0, 96000.0 }) + { + const auto measure = [=](double frequency) { + wave::dsp::Cem3387 filter; + filter.prepare(rate, 0.0f); + filter.setControls(wave::parameters::cutoffFrequencyForStep(62.0f), + resonance, 0.0f, 0.0f, 0.0f); + double energy = 0.0; + for (int sample = 0; sample < static_cast(rate); ++sample) + { + const auto input = 0.001f * static_cast(std::sin( + juce::MathConstants::twoPi * frequency * sample / rate)); + const auto output = filter.process(input, 1.0f).left; + if (sample >= static_cast(rate * 0.5)) + energy += static_cast(output) * output; + } + return std::sqrt(energy / (rate * 0.5)); + }; + const auto ratio = measure(957.0) / measure(100.0); + require(std::abs(ratio / expectedRatio - 1.0) < 0.03, + "CEM resonance peak does not match the analogue four-pole response"); + } +} + +void testCemEstimatedLinearityAndHeadroom() +{ + // Validate fast evaluation independently against the exact mathematical + // curves, including the polynomial boundaries and severe overloads. + for (int step = -1600; step <= 1600; ++step) + { + const auto input = static_cast(step) * 0.01f; + const auto transfer = wave::dsp::cem3387::linearisedTransconductor(input); + const auto exactUnit = std::tanh(static_cast(input) / 26.0); + require(std::abs(transfer.value - 26.0 * exactUnit) < 0.000003 + && std::abs(transfer.derivative - (1.0 - exactUnit * exactUnit)) < 0.0000002, + "Fast CEM transconductor differs from the reference curve"); + const auto headroom = wave::dsp::cem3387::limitHeadroom(input, 1.4f); + const auto term = 1.0 + std::pow(static_cast(input) / 1.4f, 16.0); + const auto exactGain = std::pow(term, -1.0 / 16.0); + require(std::abs(headroom.value - input * exactGain) < 0.0000004 + && std::abs(headroom.derivative - exactGain / term) < 0.0000004, + "Fast CEM headroom differs from the reference curve"); + } + // This constrains our datasheet-guided estimate, not measured Wave THD. + // Nominal peak 1 is assumed to represent the specified 5 Vpp input. + const auto thd = [](double rate, float peak, float drive) { + wave::dsp::Cem3387 filter; + filter.prepare(rate, 0.0f); + filter.setControls(wave::parameters::cutoffFrequencyForStep(100.0f), + 0.0f, drive, 0.0f, 0.0f); + std::array sine {}, cosine {}; + for (int sample = 0; sample < static_cast(rate * 2.0); ++sample) + { + const auto phase = juce::MathConstants::twoPi * 100.0 * sample / rate; + const auto output = filter.process(peak * static_cast(std::sin(phase)), + 1.0f).left; + if (sample >= static_cast(rate)) + for (size_t harmonic = 0; harmonic < sine.size(); ++harmonic) + { + const auto angle = phase * static_cast(harmonic + 1); + sine[harmonic] += output * std::sin(angle); + cosine[harmonic] += output * std::cos(angle); + } + } + double harmonicEnergy = 0.0; + for (size_t harmonic = 1; harmonic < sine.size(); ++harmonic) + harmonicEnergy += sine[harmonic] * sine[harmonic] + + cosine[harmonic] * cosine[harmonic]; + return std::sqrt(harmonicEnergy / (sine[0] * sine[0] + cosine[0] * cosine[0])); + }; + require(thd(48000.0, 0.1f, 0.0f) < 0.00005, + "CEM nominal low-level input is excessively distorted"); + auto referenceThd = 0.0; + for (const auto rate : { 44100.0, 48000.0, 96000.0 }) + { + const auto nominalThd = thd(rate, 1.0f, 0.0f); + require(nominalThd > 0.0006 && nominalThd < 0.0016, + "CEM nominal distortion no longer follows the datasheet-guided estimate"); + if (referenceThd == 0.0) + referenceThd = nominalThd; + require(std::abs(nominalThd / referenceThd - 1.0) < 0.02, + "CEM nominal distortion changes substantially with sample rate"); + + wave::dsp::Cem3387 filter; + filter.prepare(rate, 0.0f); + filter.setControls(wave::parameters::cutoffFrequencyForStep(62.0f), + 1.0f, 0.0f, 0.0f, 0.0f); + double energy = 0.0; + auto peak = 0.0f; + for (int sample = 0; sample < static_cast(rate * 4.0); ++sample) + { + // No impulse: the model must start from its internal device noise. + const auto output = filter.process(0.0f, 1.0f).left; + if (sample >= static_cast(rate * 3.0)) + { + energy += static_cast(output) * output; + peak = juce::jmax(peak, std::abs(output)); + } + } + const auto rms = std::sqrt(energy / rate); + require(rms > 0.6 && rms < 0.75 && peak < 1.01f, + "CEM noise-seeded self-oscillation fails to reach bounded estimated headroom"); + } + require(thd(48000.0, 1.0f, 18.0f) > 0.03, + "CEM input drive no longer produces overload distortion"); +} + void testIndependentFilterEnvelope() { wave::dsp::WaldorfEngine engine; @@ -1263,6 +2627,36 @@ void testAudibleKeyboardRange() } } +void testEmptyPerformanceSilencesHeldNotes() +{ + wave::dsp::WaldorfEngine engine; + engine.prepare(48000.0, 512); + wave::dsp::WaldorfEngine::PerformanceSnapshot performance; + performance.layers[0].enabled = true; + performance.layers[0].source = 3; + performance.circuitAgeAmount = 0.0f; + performance.layers[0].sound.attackSeconds = 0.001f; + performance.layers[0].sound.filterEnvelopeSemitones = 0.0f; + performance.layers[0].sound.cutoffHz = 16000.0f; + juce::AudioBuffer audio(2, 512); + juce::MidiBuffer noteOn; + noteOn.addEvent(juce::MidiMessage::noteOn(1, 60, 1.0f), 0); + engine.render(audio, noteOn, performance); + require(audio.getMagnitude(0, 0, 512) > 1.0e-6f, + "Empty Performance fixture did not start an audible held note"); + performance.layers[0].enabled = false; + // Drain the analogue output stage's stored charge after removing its input. + for (int block = 0; block < 64; ++block) + { + audio.clear(); + engine.render(audio, {}, performance); + } + // The output-stage model retains its tiny analogue noise floor. + require(audio.getMagnitude(0, 0, 512) < 2.0e-6f + && audio.getMagnitude(1, 0, 512) < 2.0e-6f, + "Selecting an empty Performance retained the preceding held voice audio"); +} + void testPerformanceMidi() { wave::dsp::WaldorfEngine engine; @@ -1320,6 +2714,171 @@ void testPerformanceMidi() "MIDI all-sound-off did not stop voices immediately"); } +void testInstrumentVoiceAllocation() +{ + wave::dsp::WaldorfEngine engine; + engine.prepare(48000.0, 512); + wave::dsp::WaldorfEngine::PerformanceSnapshot performance; + auto& layer = performance.layers[0]; + layer.enabled = true; + layer.source = 3; + layer.sound.attackSeconds = 0.3f; + layer.sound.filterAttackSeconds = 0.3f; + layer.sound.releaseSeconds = 0.2f; + juce::AudioBuffer audio(2, 1); + const auto send = [&](const juce::MidiMessage& message, bool local = false) { + juce::MidiBuffer midi; + midi.addEvent(message, 0); + if (local) + engine.render(audio, {}, midi, performance); + else + engine.render(audio, midi, performance); + }; + const auto warm = [&] { + juce::AudioBuffer block(2, 512); + for (int count = 0; count < 16; ++count) + engine.render(block, {}, performance); + }; + const auto heldNote = [&] { + auto note = -1; + auto count = 0; + for (const auto& voice : engine.voiceStates()) + if (voice.active && voice.keyDown && voice.layer == 0) + { + note = voice.triggerNote; + ++count; + } + require(count == 1, "Monophonic Instrument allocated more than one held voice"); + return note; + }; + for (int mode = 17; mode <= 22; ++mode) + { + engine.reset(); + layer.allocationMode = mode; + const auto priority = (mode - 17) % 3; + send(juce::MidiMessage::noteOn(1, 60, 0.8f)); + warm(); + const auto envelopeBefore = engine.firstActiveAmplifierEnvelopeValue(); + const auto filterBefore = engine.firstActiveFilterEnvelopeValue(); + require(envelopeBefore > 0.05f && filterBefore > 0.05f, + "Mono envelope fixture did not advance its attack"); + send(juce::MidiMessage::noteOn(1, 67, 0.9f)); + require(heldNote() == (priority == 1 ? 60 : 67), + "Mono last/low/high note priority is incorrect"); + if (mode >= 20 || priority == 1) + require(engine.firstActiveAmplifierEnvelopeValue() >= envelopeBefore - 0.01f + && engine.firstActiveFilterEnvelopeValue() >= filterBefore - 0.01f, + "Single-trigger or non-priority key restarted an envelope"); + else + require(engine.firstActiveAmplifierEnvelopeValue() < envelopeBefore * 0.25f + && engine.firstActiveFilterEnvelopeValue() < filterBefore * 0.25f, + "Mono retrigger mode did not restart the envelopes"); + send(juce::MidiMessage::noteOn(1, 55, 0.7f)); + require(heldNote() == (priority == 2 ? 67 : 55), + "Mono low/high priority failed with three overlapping keys"); + send(juce::MidiMessage::noteOff(1, 55)); + require(heldNote() == (priority == 1 ? 60 : 67), + "Mono release did not return to the correct held key"); + send(juce::MidiMessage::noteOff(1, 67)); + require(heldNote() == 60, "Mono allocation forgot the first held key"); + send(juce::MidiMessage::controllerEvent(1, 64, 127)); + send(juce::MidiMessage::noteOff(1, 60)); + require(engine.heldVoiceCount() == 0 && engine.activeVoiceCount() == 1, + "Mono sustain released its voice too early or retained a held key"); + send(juce::MidiMessage::controllerEvent(1, 64, 0)); + send(juce::MidiMessage::allSoundOff(1)); + require(engine.activeVoiceCount() == 0, "Mono panic left a sounding voice"); + // Local keyboard and repeated-pitch MIDI Note Offs use the same + // priority stack without consuming another physical voice. + send(juce::MidiMessage::noteOn(1, 60, 0.8f), true); + send(juce::MidiMessage::noteOn(1, 60, 0.9f), true); + send(juce::MidiMessage::noteOff(1, 60), true); + require(heldNote() == 60, "Repeated mono pitch lost its remaining keystroke"); + send(juce::MidiMessage::noteOff(1, 60), true); + require(engine.heldVoiceCount() == 0, "Repeated mono pitch became stuck"); + } + + engine.reset(); + layer.allocationMode = 1; + send(juce::MidiMessage::noteOn(1, 60, 0.8f)); + send(juce::MidiMessage::noteOn(1, 64, 0.8f)); + send(juce::MidiMessage::noteOn(1, 67, 0.8f)); + require(engine.heldVoiceCount() == 3, "Poly 1 incorrectly limited ordinary polyphony"); + layer.allocationMode = 21; + engine.render(audio, {}, performance); + require(heldNote() == 60 && engine.activeVoiceCount() == 1, + "A live change from polyphonic to mono did not take effect"); + + engine.reset(); + layer.allocationMode = 20; + performance.layers[1] = layer; + performance.layers[1].allocationMode = 0; + send(juce::MidiMessage::noteOn(1, 60, 0.8f)); + send(juce::MidiMessage::noteOn(1, 67, 0.8f)); + send(juce::MidiMessage::noteOn(1, 55, 0.8f)); + require(heldNote() == 55 && engine.heldVoiceCount() == 4, + "Mono allocation leaked into another Performance Instrument"); + send(juce::MidiMessage::noteOff(1, 55)); + require(heldNote() == 67 && engine.heldVoiceCount() == 3, + "Layered mono fallback released the wrong polyphonic keystroke"); + + engine.reset(); + performance.layers[1].enabled = false; + layer.sound.glideEnabled = true; + layer.sound.glideTypeMode = 5; // Fingered portamento. + layer.sound.glideRateValue = 100.0f; + send(juce::MidiMessage::noteOn(1, 60, 0.8f)); + send(juce::MidiMessage::noteOn(1, 72, 0.8f)); + for (const auto& voice : engine.voiceStates()) + if (voice.active && voice.keyDown) + require(voice.glidePitch >= 60.0f && voice.glidePitch < 61.0f, + "Single-trigger mono legato bypassed fingered portamento"); +} + +void testInstrumentVoiceSharing() +{ + wave::dsp::WaldorfEngine engine; + engine.prepare(48000.0, 32); + wave::dsp::WaldorfEngine::PerformanceSnapshot performance; + for (int index = 0; index < 3; ++index) + { + auto& layer = performance.layers[static_cast(index)]; + layer.enabled = true; + layer.source = 2; + layer.midiChannel = index + 1; + } + juce::AudioBuffer audio(2, 1); + const auto on = [&](int channel, int note) { + juce::MidiBuffer midi; + midi.addEvent(juce::MidiMessage::noteOn(channel, note, 0.8f), 0); + engine.render(audio, midi, performance); + }; + const auto count = [&](int layer) { + auto total = 0; + for (const auto& voice : engine.voiceStates()) + total += voice.active && voice.layer == layer ? 1 : 0; + return total; + }; + for (int note = 0; note < 48; ++note) + on(1, note); + on(2, 60); + require(count(0) == 48 && count(1) == 0, + "Dynamic allocation stole another Instrument's sounding voice"); + performance.layers[1].allocationMode = 2; + on(2, 61); + on(2, 62); + on(2, 63); + require(count(0) == 46 && count(1) == 2, + "Poly N did not respect its cross-Instrument voice-sharing allowance"); + performance.layers[2].allocationMode = 17; + on(3, 70); + on(3, 72); + require(count(2) == 1, "Mono allocation did not reclaim and reuse one voice"); + for (int note = 60; note < 110; ++note) + on(1, note); + require(count(2) == 1, "Another Instrument stole a protected mono voice"); +} + void testWaveGlideModes() { wave::dsp::WaldorfEngine engine; @@ -1878,6 +3437,15 @@ void testReferenceComparison() << " peak=" << metrics.peakError << '\n'; } +void testFirmwareBundleRejectsMissingPath() +{ + // Used to search the parent ("/") recursively and effectively never return. + wave::firmware::Bundle bundle; + const auto report = bundle.load(juce::File("/nonexistent-wave-firmware-dir")); + require(report.authenticity != wave::firmware::Bundle::Authenticity::verifiedOs1700, + "Missing firmware path was accepted"); +} + void testOfficialFirmwareWhenAvailable() { const auto* path = std::getenv("WAVE_FIRMWARE_DIR"); @@ -2006,6 +3574,12 @@ void testOfficialFirmwareWhenAvailable() masterRuntime.runCycles(50000); voiceRuntime.runCycles(100000); } + // OS 1.700 samples two quadrature banks separately from its six + // active-low switch banks. An all-high reset formerly produced sixteen + // unsolicited negative encoder steps, changing a recalled Sound at boot. + for (uint32_t address = 0x5520cu; address < 0x55220u; ++address) + require(masterRuntime.localByte(address) == 0, + "Idle panel encoders generated a phase transition at startup"); require(masterRuntime.timerTickCount() > 0, "Main-board 6522 timer did not advance after OS hardware setup"); require(masterRuntime.installedSyntheticInitialisationRecords(), @@ -2042,8 +3616,48 @@ void testOfficialFirmwareWhenAvailable() < wave::firmware::VoiceFirmwareRuntime::asicBase + 0x200u; }), "Firmware-driven note did not reach either oscillator-chip register page"); + require(std::any_of(midiWrites.begin(), midiWrites.end(), [](const auto& write) { + return write.address == wave::firmware::VoiceFirmwareRuntime::routingLatchBase; + }), + "Firmware-driven note did not refresh the output routing latch"); require(masterRuntime.unmappedReadCount() == 0 && voiceRuntime.unmappedReadCount() == 0, "Firmware-driven MIDI note reached an unmodelled system-bus address"); + + // Disk machine settings may disable Performance reception or remap MIDI + // programs. Internal panel recall must work, then release its bypass so + // the following external MIDI packet still obeys those settings. + sharedMemory.work[0x8824u] = 1u; + sharedMemory.work[0x880du] = 7u; + sharedMemory.work[0x8806u] = 1u; + const auto displayRevision = masterRuntime.lcdDisplayRevision(); + const auto displayWrites = masterRuntime.lcdVideoWriteCount(); + require(masterRuntime.requestPerformanceSelection(128), + "Internal Performance recall was rejected"); + require(masterRuntime.lcdDisplayRevision() != displayRevision + && masterRuntime.lcdVideoWriteCount() == displayWrites, + "Holding a recall frame did not notify the LCD without a VRAM write"); + const auto heldDisplayRevision = masterRuntime.lcdDisplayRevision(); + for (int slice = 0; slice < 40; ++slice) + { + masterRuntime.runCycles(50000); + voiceRuntime.runCycles(100000); + } + require(masterRuntime.currentPerformanceId() == 128, + "External MIDI settings redirected internal panel recall"); + require(masterRuntime.lcdDisplayRevision() != heldDisplayRevision, + "Completed Performance recall did not publish a new LCD revision"); + masterRuntime.pushMidiByte(0, 0xc0u); + masterRuntime.pushMidiByte(0, 2u); + for (int slice = 0; slice < 40; ++slice) + { + masterRuntime.runCycles(50000); + voiceRuntime.runCycles(100000); + } + require(masterRuntime.currentPerformanceId() == 128 + && sharedMemory.work[0x8824u] == 1u + && sharedMemory.work[0x880du] == 7u + && sharedMemory.work[0x8806u] == 1u, + "Internal recall left external MIDI reception bypassed or changed its settings"); } void testDecodedVoiceBoardProtocol() @@ -2065,6 +3679,82 @@ void testDecodedVoiceBoardProtocol() "WDV shared bus mutex was not released"); } +void testVoiceBoardWaveRamDecode() +{ + // Hand-built WDV image (no firmware needed): SP 0x8FFE, reset 0x400, then + // byte stores through RAM A, RAM B and the write-both alias, and a spin. + static constexpr uint8_t code[] = { + 0x13, 0xfc, 0x00, 0xa5, 0x00, 0x06, 0x00, 0x01, // move.b #$a5,$060001 + 0x13, 0xfc, 0x00, 0x5a, 0x00, 0x05, 0x00, 0x03, // move.b #$5a,$050003 + 0x13, 0xfc, 0x00, 0x11, 0x00, 0x04, 0x00, 0x05, // move.b #$11,$040005 + 0x60, 0xfe // bra.s * + }; + juce::MemoryBlock image(0x20 + 0x400 + sizeof(code), true); + auto* bytes = static_cast(image.getData()); + bytes[0x20 + 2] = 0x8f; + bytes[0x20 + 3] = 0xfe; + bytes[0x20 + 6] = 0x04; + std::copy(std::begin(code), std::end(code), bytes + 0x20 + 0x400); + + wave::firmware::SharedFirmwareMemory memory; + memory.clear(); + wave::firmware::VoiceFirmwareRuntime runtime; + runtime.attachSharedMemory(memory); + require(runtime.loadAndReset(image), "Synthetic WDV image was rejected"); + runtime.runCycles(2000); + require(runtime.waveRamByte(0, 1) == 0xa5 && runtime.waveRamByte(1, 1) == 0xa5, + "Write at $060001 did not reach both wave RAMs"); + require(runtime.waveRamByte(1, 3) == 0x5a && runtime.waveRamByte(0, 3) == 0, + "Write at $050003 did not reach wave RAM B only"); + require(runtime.waveRamByte(0, 5) == 0x11 && runtime.waveRamByte(1, 5) == 0, + "Write at $040005 did not reach wave RAM A only"); + require(memory.mainRam[0x60001] == 0 && memory.mainRam[0x50003] == 0 + && memory.mainRam[0x40005] == 0, + "Voice-board wave RAM stores leaked into master DRAM"); +} + +void testVoiceBoardRoutingLatchAndBoardLimit() +{ + // The one-cold slot strap (WDV 0x466 scan, w2sys 0xB80E mask) names boards + // 0-2 only, so the three cards the engine renders are the whole machine. + static_assert(wave::firmware::VoiceFirmwareRuntime::maximumBoardCount + == wave::dsp::WaldorfEngine::voiceBoardCount); + wave::firmware::VoiceFirmwareRuntime strapProbe; + require(strapProbe.setBoardIndex(0) && strapProbe.setBoardIndex(2), + "Board slots 0-2 were rejected"); + require(!strapProbe.setBoardIndex(3) && !strapProbe.setBoardIndex(-1), + "A fourth voice board slot was accepted although the strap names only three"); + + // Hand-built WDV image: one long store to the write-only routing latch, + // as WDV 0xCBA does (MOVE.L d0,$8C0000), then a spin. + static constexpr uint8_t code[] = { + 0x23, 0xfc, 0xdb, 0x6d, 0x8b, 0x6d, 0x00, 0x8c, 0x00, 0x00, // move.l #$db6d8b6d,$8c0000 + 0x60, 0xfe // bra.s * + }; + juce::MemoryBlock image(0x20 + 0x400 + sizeof(code), true); + auto* bytes = static_cast(image.getData()); + bytes[0x20 + 2] = 0x8f; + bytes[0x20 + 3] = 0xfe; + bytes[0x20 + 6] = 0x04; + std::copy(std::begin(code), std::end(code), bytes + 0x20 + 0x400); + + wave::firmware::SharedFirmwareMemory memory; + memory.clear(); + wave::firmware::VoiceFirmwareRuntime runtime; + runtime.attachSharedMemory(memory); + require(runtime.loadAndReset(image), "Synthetic WDV image was rejected"); + runtime.runCycles(2000); + const auto& writes = runtime.pendingHardwareWrites(); + constexpr std::array expected { 0xdb, 0x6d, 0x8b, 0x6d }; + require(writes.size() == expected.size(), + "Routing latch long store was not logged as four byte writes"); + for (size_t i = 0; i < expected.size(); ++i) + require(writes[i].address == wave::firmware::VoiceFirmwareRuntime::routingLatchBase + i + && writes[i].value == expected[i], + "Routing latch byte write has the wrong address or value"); + require(runtime.unmappedReadCount() == 0, "Routing latch store caused an unmapped read"); +} + class Test68000Bus final : public wave::firmware::M68000Bus { public: @@ -2415,28 +4105,42 @@ int main() { testWavetableQuantisation(); testAsicClockMixOverflowAndVcfSaturation(); + testAsicResampling(); + testResamplerSimdAgainstScalar(); + testHighRegisterOscillatorResampling(); testCutoffControlLaw(); testQuickEditFastAccessControls(); testWaveEnvelopeTraversal(); testWaveLfo(); testDspMathTables(); testPerformanceTuningTables(); + testPerformanceAudioOutRouting(); + testStartPhaseCode(); + testStartPhaseCodeMatchesFirmwareWhenAvailable(); + testStartModulationAtNoteOn(); testFreeRunningEngineLfo(); testFactorySetWhenAvailable(); + testDamagedUserWavetableImport(); + testSparsePerformanceBanks(); testPpgRomDecoding(); testBundledPpgWavetables(); testFactoryUpperWavetableBank(); + testOriginalWaveFactoryTablesWhenAvailable(); testExpandedFirst32Loading(); testUserPpgRomWhenAvailable(); testCemStability(); testCemFilterResponse(); testMeasuredWaveResonancePassbandLoss(); testAllVoiceFiltersAreCalibrated(); + testReconstructionCachedTransfer(); testCemControlVoltageSettling(); testLiveCutoffUsesContinuousBaseControlVoltage(); testAsicHighpassResponse(); testSerialBandpassTopology(); testCemSelfOscillation(); + testCemResonanceAcrossSampleRates(); + testCemSmallSignalResonanceResponse(); + testCemEstimatedLinearityAndHeadroom(); testMeasuredFastAmplifierAttackScaling(); testAmplifierEnvelopeStages(); testShortVcaReleaseDrainsAnalogueControl(); @@ -2445,6 +4149,9 @@ int main() testSampleAccurateMidiStart(); testAudibleKeyboardRange(); testPerformanceMidi(); + testEmptyPerformanceSilencesHeldNotes(); + testInstrumentVoiceAllocation(); + testInstrumentVoiceSharing(); testWaveGlideModes(); testReleasedVoicesAreStolenBeforeHeldChord(); testVoiceStealPreservesAnalogueHandover(); @@ -2458,9 +4165,13 @@ int main() test6522TimerOneInterruptPath(); testDosFloppyImageCreation(); testDp8473MountedDiskImage(); + testDp8473AutomaticDiskWrites(); testLcdFramebuffer(); testCompletePanelWiringContract(); testDecodedVoiceBoardProtocol(); + testVoiceBoardWaveRamDecode(); + testVoiceBoardRoutingLatchAndBoardLimit(); + testFirmwareBundleRejectsMissingPath(); testOfficialFirmwareWhenAvailable(); std::cout << "WaveCoreTests: all checks passed\n"; return 0; diff --git a/Tests/WaveEditorTests.cpp b/Tests/WaveEditorTests.cpp index 0d9b29a..fe29eac 100644 --- a/Tests/WaveEditorTests.cpp +++ b/Tests/WaveEditorTests.cpp @@ -2,6 +2,7 @@ #include "PanelWiring.h" #include +#include #include #include #include @@ -10,6 +11,16 @@ namespace { +std::unique_ptr makeFactoryProcessor(const juce::File& preference = {}) +{ + // Layout tests must not inherit the developer's remembered panel skin or + // firmware folder. Explicit test preferences still exercise persistence. + juce::TemporaryFile isolatedPreference(".txt"); + return std::make_unique( + preference == juce::File{} ? isolatedPreference.getFile() : preference, + WaveEmulationAudioProcessor::InitialBank::embeddedFactory); +} + void require(bool condition, const char* message) { if (!condition) @@ -99,9 +110,53 @@ void dragEditorControl(WaveEmulationAudioProcessorEditor& editor, editor.mouseUp(up); } +void testWindowShortcutsPreservePanelLayout() +{ + auto processor = makeFactoryProcessor(); + WaveEmulationAudioProcessorEditor editor(*processor); + editor.setVisible(true); + auto* lcd = static_cast(nullptr); + for (int index = 0; index < editor.getNumChildComponents(); ++index) + { + auto* child = editor.getChildComponent(index); + if (dynamic_cast(child) != nullptr) + lcd = child; + } + require(lcd != nullptr, "Could not find the firmware LCD in the editor"); + const auto fullLcdBounds = lcd->getBounds(); + const auto pressCommand = [&](int keyCode) { + return editor.keyPressed(juce::KeyPress( + keyCode, juce::ModifierKeys { juce::ModifierKeys::commandModifier }, 0)); + }; + + require(editor.getWidth() == 2338 && editor.getHeight() == 1042, + "Editor did not open at its default scale"); + require(pressCommand('k') && editor.getWidth() == 2338 + && editor.getHeight() == 619 && lcd->getBounds() == fullLcdBounds, + "Hide Keyboard distorted or moved the upper panel"); + require(std::abs(editor.getConstrainer()->getFixedAspectRatio() + - 2338.0 / 619.0) < 0.001, + "Hidden keyboard kept the full-height resize aspect ratio"); + require(pressCommand('+') && editor.getWidth() == 2572 + && editor.getHeight() == 681, + "Zoom In did not resize the cropped panel"); + require(pressCommand('-') && editor.getWidth() == 2338 + && editor.getHeight() == 619, + "Zoom Out did not restore the cropped panel size"); + require(pressCommand('k') && editor.getWidth() == 2338 + && editor.getHeight() == 1042 + && lcd->getBounds() == fullLcdBounds, + "Show Keyboard did not restore the full editor"); + require(pressCommand('-') && editor.getWidth() == 2104, + "Zoom Out did not shrink the full editor"); + require(pressCommand('0') && editor.getWidth() == 2338 + && editor.getHeight() == 1042, + "Actual Size did not restore the default editor size"); +} + void testLowerPerformanceWheelsFollowHardwareRules() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); WaveEmulationAudioProcessorEditor editor(*processor); editor.setVisible(true); @@ -131,7 +186,7 @@ void testLowerPerformanceWheelsFollowHardwareRules() void testRepeatedInstrumentEditLayerClicks() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(41); // A042: three active Instruments. juce::AudioBuffer audio(2, 512); @@ -211,7 +266,7 @@ void testRepeatedInstrumentEditLayerClicks() void testLayerProcessingPromptAcceptsCancel() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); processBlocks(*processor, audio, 640); @@ -282,7 +337,7 @@ void testLayerProcessingPromptAcceptsCancel() void testFirmwareWavetableStepReachesAudioParameter() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); processBlocks(*processor, audio, 64); @@ -317,7 +372,7 @@ void testFirmwareWavetableStepReachesAudioParameter() void testInstrumentEditPageOneFadersUpdatePerformance() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); processBlocks(*processor, audio, 640); @@ -355,7 +410,7 @@ void testInstrumentEditPageOneFadersUpdatePerformance() }; constexpr auto channels = wave::panel::performanceFaderAdcChannels; constexpr std::array offsets { - 4u, 5u, 7u, 8u, 9u, 10u, 2u, 3u + 4u, 5u, 7u, 12u, 9u, 10u, 2u, 3u }; constexpr std::array positions { 0.50f, 0.25f, 0.25f, 0.75f, @@ -365,7 +420,7 @@ void testInstrumentEditPageOneFadersUpdatePerformance() 64, 32, 32, 2, 32, 95, 12, 1 }; - processor->setPanelFader(3, channels[3], 0.0f, false); // Main output. + processor->setPanelFader(3, channels[3], 1.0f / 3.0f, false); // Main output. processor->setPanelFader(7, channels[7], 1.0f, false); // Keys + MIDI. processor->setPanelFader(0, channels[0], 0.0f, false); processBlocks(*processor, audio, 32); @@ -375,6 +430,10 @@ void testInstrumentEditPageOneFadersUpdatePerformance() for (size_t fader = 0; fader < channels.size(); ++fader) { + std::array before {}; + for (size_t offset = 0; offset < before.size(); ++offset) + before[offset] = processor->getMasterFirmwareRuntime().sharedProgramByte( + instrumentBase() + static_cast(offset)); processor->setPanelFader(static_cast(fader), channels[fader], positions[fader], false); processBlocks(*processor, audio, 32); @@ -387,10 +446,15 @@ void testInstrumentEditPageOneFadersUpdatePerformance() + std::to_string(fader) + ", expected " + std::to_string(expected[fader]) + ", observed " + std::to_string(stored)); + for (size_t offset = 0; offset < before.size(); ++offset) + if (offset != offsets[fader]) + require(processor->getMasterFirmwareRuntime().sharedProgramByte( + instrumentBase() + static_cast(offset)) == before[offset], + "Page 1 fader changed another Instrument field"); } // Volume must reach the live layer, not just its LCD/record value. - processor->setPanelFader(3, channels[3], 0.0f, false); // Main output. + processor->setPanelFader(3, channels[3], 1.0f / 3.0f, false); // Main output. processor->setPanelFader(7, channels[7], 1.0f, false); // Keys + MIDI. processBlocks(*processor, audio, 32); const auto audible = processor->probeCurrentLayerVoice( @@ -404,7 +468,7 @@ void testInstrumentEditPageOneFadersUpdatePerformance() void testInstrumentPageOneFaderDoesNotLeakIntoOtherPages() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); processBlocks(*processor, audio, 640); @@ -448,7 +512,8 @@ void testInstrumentPageOneFaderDoesNotLeakIntoOtherPages() wave::panel::performanceFaderAdcChannels[audioOutFader], 0.92f, false); processBlocks(*processor, audio, 1200); - constexpr auto audioOutRecordOffset = size_t { 8 }; + // Audio Out is Instrument part byte +0xC (firmware table 0x14BCA). + constexpr auto audioOutRecordOffset = size_t { 12 }; require((processor->getMasterFirmwareRuntime().sharedProgramByte( base + static_cast(audioOutRecordOffset)) & 0x7fu) @@ -468,7 +533,7 @@ void testInstrumentPageOneFaderDoesNotLeakIntoOtherPages() void testInstrumentEditPageTwoVolumeReachesAudioEngine() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); processBlocks(*processor, audio, 640); @@ -484,6 +549,16 @@ void testInstrumentEditPageTwoVolumeReachesAudioEngine() require(processor->getInstrumentEditPage() == 1, "Instrument Edit did not reach Page 2 for its audio test"); + // Firmware remembers Page 2 across mode changes. The host must not reset + // its fader destinations to Page 1 when Instrument Edit is reopened. + clickPanelControl(editor, *processor, audio, 1402.5f, 553.0f); + clickPanelControl(editor, *processor, audio, 1402.5f, 494.0f); + processBlocks(*processor, audio, 320); + require(processor->getMasterFirmwareRuntime().localByte(0x56ee9u) == 1u, + "Firmware did not restore Instrument Edit Page 2"); + require(processor->getInstrumentEditPage() == 1, + "Reopening Instrument Edit routed Page 2 faders to Page 1"); + const auto instrument = processor->getSelectedPerformanceInstrument(); const auto performanceOffset = processor->getMasterFirmwareRuntime() .currentPerformanceRecordOffset(); @@ -497,6 +572,137 @@ void testInstrumentEditPageTwoVolumeReachesAudioEngine() return *currentOffset + 64u + static_cast(instrument) * 32u; }; + // Compare every reachable ADC value with the actual firmware-rendered + // TuneTable word. The native display has 13 uneven bins, including a + // transition between two ADC values that share one seven-bit position. + const auto tuningScreen = [&] { + const auto& runtime = processor->getMasterFirmwareRuntime(); + const auto video = runtime.lcdVideoSnapshot(); + wave::ui::LcdFramebuffer framebuffer; + framebuffer.loadHardwareVideoRam(video.data(), video.size(), + runtime.lcdDisplayPage()); + std::array word {}; + for (int y = 54; y < 64; ++y) + for (int x = 240; x < 300; ++x) + word[static_cast((y - 54) * 60 + x - 240)] + = static_cast(framebuffer.pixel(x, y)); + return word; + }; + const auto setTuningFader = [&](int physical) { + processor->setPanelFader( + 4, wave::panel::performanceFaderAdcChannels[4], + static_cast(physical) / 127.0f, false); + processBlocks(*processor, audio, 64); + return tuningScreen(); + }; + std::array, 13> tuningWords {}; + for (int selector = 0; selector < 13; ++selector) + { + const auto first = (selector * 128 + 12) / 13; + const auto last = ((selector + 1) * 128 - 1) / 13; + tuningWords[static_cast(selector)] + = setTuningFader((first + last) / 2); + if (selector > 0) + require(tuningWords[static_cast(selector)] + != tuningWords[static_cast(selector - 1)], + "Two TuneTable selectors rendered the same LCD word"); + } + juce::MidiBuffer heldNote; + heldNote.addEvent(juce::MidiMessage::noteOn(1, 60, 0.9f), 0); + audio.clear(); + processor->processBlock(audio, heldNote); + processBlocks(*processor, audio, 32); + require(processor->getActiveVoiceCount() > 0, + "TuneTable sweep did not hold a sounding note"); + std::array recordBefore {}; + for (size_t offset = 0; offset < recordBefore.size(); ++offset) + recordBefore[offset] = processor->getMasterFirmwareRuntime() + .sharedProgramByte(instrumentBase() + + static_cast(offset)); + const auto soundRecordOffset = processor->getMasterFirmwareRuntime() + .performanceInstrumentSoundRecordOffset(instrument); + require(soundRecordOffset.has_value(), + "TuneTable sweep could not locate the active Sound record"); + std::array soundBefore {}; + for (size_t offset = 0; offset < soundBefore.size(); ++offset) + soundBefore[offset] = processor->getMasterFirmwareRuntime() + .sharedProgramByte(*soundRecordOffset + + static_cast(offset)); + const auto snapshotBefore = processor->getCurrentPerformanceSnapshot(); + for (int adc = 0; adc < 256; ++adc) + { + processor->setPanelFader( + 4, wave::panel::performanceFaderAdcChannels[4], + static_cast(adc) / 255.0f, false); + processBlocks(*processor, audio, 64); + const auto screen = tuningScreen(); + const auto stored = static_cast( + processor->getMasterFirmwareRuntime() + .sharedProgramByte(instrumentBase() + 22u) + & 0x7fu); + const auto audible = processor->getCurrentPerformanceSnapshot() + .layers[static_cast(instrument)] + .tuningTable; + auto displayed = -1; + for (int candidate = 0; candidate < 13; ++candidate) + if (screen == tuningWords[static_cast(candidate)]) + displayed = candidate; + if (displayed < 0 || stored != displayed || audible != displayed) + throw std::runtime_error( + "TuneTable LCD and audio disagree at ADC " + + std::to_string(adc) + ": LCD " + + std::to_string(displayed) + ", record " + + std::to_string(stored) + ", engine " + + std::to_string(audible)); + for (size_t offset = 0; offset < recordBefore.size(); ++offset) + if (offset != 22u + && processor->getMasterFirmwareRuntime().sharedProgramByte( + instrumentBase() + static_cast(offset)) + != recordBefore[offset]) + throw std::runtime_error( + "Held-note TuneTable edit changed Instrument record byte " + + std::to_string(offset) + " at ADC " + + std::to_string(adc)); + for (size_t offset = 0; offset < soundBefore.size(); ++offset) + if (processor->getMasterFirmwareRuntime().sharedProgramByte( + *soundRecordOffset + static_cast(offset)) + != soundBefore[offset]) + throw std::runtime_error( + "Held-note TuneTable edit changed Sound record byte " + + std::to_string(offset) + " at ADC " + + std::to_string(adc)); + const auto current = processor->getCurrentPerformanceSnapshot(); + const auto& currentLayer = current.layers[static_cast(instrument)]; + const auto& previousLayer + = snapshotBefore.layers[static_cast(instrument)]; + if (currentLayer.transposeSemitones != previousLayer.transposeSemitones + || currentLayer.sound.oscillatorOctaves + != previousLayer.sound.oscillatorOctaves) + throw std::runtime_error( + "Held-note TuneTable edit changed transpose or oscillator octave at ADC " + + std::to_string(adc)); + } + // ADC 55 is in the displayed HMT band, but the old seven-bit mapping + // selected Linear- in the engine. A second external MIDI key exposes the + // error as a large downward pitch jump while the first key stays held. + processor->setPanelFader( + 4, wave::panel::performanceFaderAdcChannels[4], 55.0f / 255.0f, false); + processBlocks(*processor, audio, 64); + require(processor->getCurrentPerformanceSnapshot() + .layers[static_cast(instrument)].tuningTable == 2, + "Displayed HMT band selected another audible tuning"); + juce::MidiBuffer secondHeldNote; + secondHeldNote.addEvent(juce::MidiMessage::noteOn(1, 72, 0.9f), 0); + processor->processBlock(audio, secondHeldNote); + processBlocks(*processor, audio, 4); + auto secondNotePitch = -1.0f; + for (const auto& voice : processor->getVoiceStates()) + if (voice.active && voice.keyDown && voice.triggerNote == 72) + secondNotePitch = voice.glidePitch; + require(std::abs(secondNotePitch - 72.0f) < 1.0e-4f, + "New external MIDI note fell to Linear- pitch while HMT was displayed"); + processor->allSoundOffFromUi(); + processBlocks(*processor, audio, 8); constexpr auto volumeFader = 0; constexpr auto volumeOffset = 4u; constexpr std::array pageTwoOffsets { @@ -512,6 +718,14 @@ void testInstrumentEditPageTwoVolumeReachesAudioEngine() for (size_t fader = 0; fader < pageTwoOffsets.size(); ++fader) { + // Exercise the retained page on every return, not only initial entry. + clickPanelControl(editor, *processor, audio, 1402.5f, 553.0f); + clickPanelControl(editor, *processor, audio, 1402.5f, 494.0f); + processBlocks(*processor, audio, 64); + std::array before {}; + for (size_t offset = 0; offset < before.size(); ++offset) + before[offset] = processor->getMasterFirmwareRuntime().sharedProgramByte( + instrumentBase() + static_cast(offset)); processor->setPanelFader( static_cast(fader), wave::panel::performanceFaderAdcChannels[fader], @@ -526,7 +740,16 @@ void testInstrumentEditPageTwoVolumeReachesAudioEngine() "Instrument Edit Page 2 fader did not commit its native field: fader " + std::to_string(fader) + ", expected " + std::to_string(pageTwoExpected[fader]) + ", observed " - + std::to_string(stored)); + + std::to_string(stored) + ", host page " + + std::to_string(processor->getInstrumentEditPage()) + + ", firmware page " + + std::to_string(processor->getMasterFirmwareRuntime() + .currentInstrumentEditPage().value_or(-1))); + for (size_t offset = 0; offset < before.size(); ++offset) + if (offset != pageTwoOffsets[fader]) + require(processor->getMasterFirmwareRuntime().sharedProgramByte( + instrumentBase() + static_cast(offset)) == before[offset], + "Page 2 fader changed another Instrument field after mode return"); } const auto decodedPageTwo = processor->getCurrentPerformanceSnapshot(); @@ -569,7 +792,7 @@ void testInstrumentEditPageTwoVolumeReachesAudioEngine() void testWaveEditSoftKeysRelease() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); processBlocks(*processor, audio, 96); @@ -652,7 +875,7 @@ void testWaveEditSoftKeysRelease() void testLowerGlideOnOffUsesFirmwareSerial() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); processBlocks(*processor, audio, 96); @@ -673,7 +896,7 @@ void testLowerGlideOnOffUsesFirmwareSerial() void testEveryLowerControllerButtonReachesItsSerialInput() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); processBlocks(*processor, audio, 96); @@ -684,15 +907,22 @@ void testEveryLowerControllerButtonReachesItsSerialInput() // These positions are the centres in the complete Figma SVG. The editor // helper accepts upper-panel-local X, hence the common artwork offset. constexpr auto offset = 66.0f; - clickPanelControl(editor, *processor, audio, 110.0f - offset, 766.5f, 16); - processBlocks(*processor, audio, 48); - require(processor->getPanelLed(16), - "The visible lower Button 1 did not reach firmware serial 3"); - - clickPanelControl(editor, *processor, audio, 170.0f - offset, 766.5f, 16); - processBlocks(*processor, audio, 48); - require(processor->getPanelLed(35), - "The visible lower Button 2 did not reach firmware serial 4"); + const auto& firmware = processor->getMasterFirmwareRuntime(); + const auto performance = firmware.currentPerformanceRecordOffset(); + require(performance.has_value(), "Lower button fixture has no live Performance"); + for (const auto [x, led, modeOffset] : std::array, 2> { + std::tuple { 110.0f, 16, 6u }, { 170.0f, 35, 7u } }) + { + const auto toggle = firmware.sharedProgramByte(*performance + modeOffset) != 0u; + clickPanelControl(editor, *processor, audio, x - offset, 766.5f, 16, [&] { + processBlocks(*processor, audio, 48); + require(processor->getPanelLed(led), + "A visible lower Button press did not reach its firmware controller"); + }); + processBlocks(*processor, audio, 48); + require(processor->getPanelLed(led) == toggle, + "A visible lower Button release ignored the Performance mode"); + } const auto beforeGlidePage = processor->getMasterFirmwareRuntime().lcdVideoSnapshot(); @@ -723,11 +953,26 @@ void testEveryLowerControllerButtonReachesItsSerialInput() && !processor->getPanelLed(58) && !processor->getPanelLed(27), "The visible lower Octave Down did not reach firmware serial 73"); + + editor.useCompactPanelSkin(); + require(editor.tooltipAt({ 639.5f, 707.5f }) == "Octave Down" + && editor.tooltipAt({ 714.5f, 707.5f }) == "Octave Up", + "Compact octave tooltips do not match the revised SVG"); + clickPanelControl(editor, *processor, audio, 639.5f - offset, 707.5f, 16); + processBlocks(*processor, audio, 48); + require(processor->getKeyboardOctaveShift() == -1 + && processor->getPanelLed(27) && !processor->getPanelLed(58), + "Compact left Octave Down did not lower the keyboard octave"); + clickPanelControl(editor, *processor, audio, 714.5f - offset, 707.5f, 16); + processBlocks(*processor, audio, 48); + require(processor->getKeyboardOctaveShift() == 0 + && !processor->getPanelLed(27) && !processor->getPanelLed(58), + "Compact right Octave Up did not restore the keyboard octave"); } void testWaveEnvelopeSelectorRemainsStable() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); processBlocks(*processor, audio, 96); @@ -763,7 +1008,7 @@ void testWaveEnvelopeSelectorRemainsStable() void testPerformanceStepButtonsDoNotRepeatAfterRelease() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(40); juce::AudioBuffer audio(2, 512); @@ -815,7 +1060,7 @@ void testPerformanceStepButtonsDoNotRepeatAfterRelease() void testColdStartPerformanceStepDoesNotRepeat() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); WaveEmulationAudioProcessorEditor editor(*processor); @@ -848,7 +1093,7 @@ void testColdStartPerformanceStepDoesNotRepeat() void testRestoredEditModeCannotMisrouteFirstPerformanceStep() { - auto saved = std::make_unique(); + auto saved = makeFactoryProcessor(); saved->prepareToPlay(48000.0, 512); saved->setCurrentProgram(40); juce::AudioBuffer audio(2, 512); @@ -865,7 +1110,7 @@ void testRestoredEditModeCannotMisrouteFirstPerformanceStep() saved->getStateInformation(state); saved.reset(); - auto restored = std::make_unique(); + auto restored = makeFactoryProcessor(); restored->setStateInformation(state.getData(), static_cast(state.getSize())); restored->prepareToPlay(48000.0, 512); @@ -884,7 +1129,7 @@ void testRestoredEditModeCannotMisrouteFirstPerformanceStep() void testPerformanceStepCancelsAnOutgoingEditStep() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(40); juce::AudioBuffer audio(2, 512); @@ -944,7 +1189,7 @@ void testPerformanceStepCancelsAnOutgoingEditStep() void testModeButtonsChangePageOnFirstClick() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); processBlocks(*processor, audio, 160); @@ -997,7 +1242,7 @@ void testModeButtonsChangePageOnFirstClick() void testPageButtonsChangePageOnFirstClick() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); processBlocks(*processor, audio, 160); @@ -1053,7 +1298,7 @@ void testPageButtonsChangePageOnFirstClick() void testModifierEditButtonsOpenFirmwarePages() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(0); juce::AudioBuffer audio(2, 512); @@ -1079,8 +1324,9 @@ void testModifierEditButtonsOpenFirmwarePages() processBlocks(*processor, audio, 240); require(processor->getPanelLed(ledCodes[index]), "A Modifier Edit button did not latch its LED"); - require(processor->getMasterFirmwareRuntime().lcdVideoSnapshot() != before, - "A Modifier Edit button did not open its firmware LCD page"); + if (processor->getMasterFirmwareRuntime().lcdVideoSnapshot() == before) + throw std::runtime_error("Modifier Edit button " + std::to_string(index + 1) + + " did not open its firmware LCD page"); const auto callback = (static_cast(processor->getMasterFirmwareRuntime().localByte( 0x56bb0u)) @@ -1105,13 +1351,103 @@ void testModifierEditButtonsOpenFirmwarePages() } } +void testNumericKeypadUi() +{ + for (int skin = 0; skin < 3; ++skin) + { + juce::TemporaryFile preference(".txt"); + auto processor = std::make_unique(preference.getFile()); + processor->prepareToPlay(48000.0, 512); + juce::AudioBuffer audio(2, 512); + processBlocks(*processor, audio, 160); + WaveEmulationAudioProcessorEditor editor(*processor); + editor.setVisible(true); + const auto compact = skin == 1; + if (compact) + editor.useCompactPanelSkin(); + else if (skin == 2) + require(editor.loadPanelSkin(juce::File::getCurrentWorkingDirectory() + .getChildFile("media/WaldorfWaveUI_NOLOGO.svg")).wasOk(), + "Could not load the alternative keypad test skin"); + const auto clickDigit = [&](float originalX, float originalY, float compactX, float compactY) { + clickPanelControl(editor, *processor, audio, + compact ? compactX - 66.0f : originalX, + compact ? compactY : originalY, 0); + processBlocks(*processor, audio, 64); + }; + const auto before = processor->getMasterFirmwareRuntime().lcdVideoSnapshot(); + clickDigit(1641.0f, 553.0f, 676.5f, 439.5f); // 0. + require(processor->getMasterFirmwareRuntime().lcdVideoSnapshot() != before, + "First keypad digit did not open number entry on the LCD"); + clickDigit(1641.0f, 513.0f, 676.5f, 401.5f); // 2: A002. + require(processor->getMasterFirmwareRuntime().currentPerformanceId() == 1, + "Keypad did not select A002"); + // Exercise every digit through its painted hit area. + for (const auto& digit : std::array, 6> {{ + {1680.0f,513.0f,714.5f,401.5f}, // 3. + {1602.0f,475.0f,638.5f,363.5f}, // 4: A034. + {1641.0f,475.0f,676.5f,363.5f}, // 5. + {1680.0f,475.0f,714.5f,363.5f}, // 6: A056. + {1602.0f,435.0f,638.5f,325.5f}, // 7. + {1641.0f,435.0f,676.5f,325.5f} // 8: A078. + }}) + clickDigit(digit[0], digit[1], digit[2], digit[3]); + require(processor->getMasterFirmwareRuntime().currentPerformanceId() == 77, + "Keypad digit sequence did not select A078"); + clickDigit(1641.0f, 553.0f, 676.5f, 439.5f); // 0. + clickDigit(1641.0f, 513.0f, 676.5f, 401.5f); // 2: restore A002. + clickDigit(1602.0f, 553.0f, 638.5f, 439.5f); // 1__: hundreds prefix. + clickDigit(1641.0f, 513.0f, 676.5f, 401.5f); // 2. + clickDigit(1680.0f, 435.0f, 714.5f, 325.5f); // 9: A129 is invalid. + require(processor->getMasterFirmwareRuntime().currentPerformanceId() == 1, + "Invalid keypad number changed Performance"); + clickDigit(1602.0f, 553.0f, 638.5f, 439.5f); // 1__. + clickDigit(1641.0f, 513.0f, 676.5f, 401.5f); // 2. + clickDigit(1641.0f, 435.0f, 676.5f, 325.5f); // 8: A128. + require(processor->getMasterFirmwareRuntime().currentPerformanceId() == 127, + "Keypad hundreds prefix did not select A128"); + clickDigit(1543.0f, 553.0f, 638.5f, 583.5f); // Bank B. + clickDigit(1641.0f, 553.0f, 676.5f, 439.5f); // 0. + clickDigit(1641.0f, 513.0f, 676.5f, 401.5f); // 2: B002. + require(processor->getMasterFirmwareRuntime().currentPerformanceId() == 129, + "Keypad did not select a Performance in Bank B"); + } +} + } // namespace -int main() +int main(int argc, char** argv) { juce::ScopedJuceInitialiser_GUI initialiseGui; try { + if (argc == 2 && std::string_view(argv[1]) == "--keypad") + { + testNumericKeypadUi(); + std::cout << "Numeric keypad UI checks passed\n"; + return 0; + } + if (argc == 2 && std::string_view(argv[1]) == "--keyboard-buttons") + { + testEveryLowerControllerButtonReachesItsSerialInput(); + std::cout << "Lower keyboard button UI checks passed\n"; + return 0; + } + if (argc == 2 && std::string_view(argv[1]) == "--instrument-faders") + { + testInstrumentEditPageOneFadersUpdatePerformance(); + testInstrumentPageOneFaderDoesNotLeakIntoOtherPages(); + testInstrumentEditPageTwoVolumeReachesAudioEngine(); + std::cout << "Instrument fader checks passed\n"; + return 0; + } + if (argc == 2 && std::string_view(argv[1]) == "--modifier-edit") + { + testModifierEditButtonsOpenFirmwarePages(); + std::cout << "Modifier Edit checks passed\n"; + return 0; + } + testWindowShortcutsPreservePanelLayout(); testLowerPerformanceWheelsFollowHardwareRules(); testLayerProcessingPromptAcceptsCancel(); testInstrumentEditPageOneFadersUpdatePerformance(); diff --git a/Tests/WaveHostStateTests.cpp b/Tests/WaveHostStateTests.cpp index 7f85de8..c7cc7d6 100644 --- a/Tests/WaveHostStateTests.cpp +++ b/Tests/WaveHostStateTests.cpp @@ -1,11 +1,37 @@ #include "PluginProcessor.h" #include "PanelWiring.h" +#include "Firmware/DosFloppyImage.h" +#include #include #include #include #include +namespace +{ +// macOS CI's libc++ does not yet provide jthread/stop_token. Keep the same +// exception-safe shutdown with an atomic stop flag and an ordinary thread. +class RenderThread +{ +public: + template + explicit RenderThread(Function render) + : worker([this, render] { render(stop); }) {} + ~RenderThread() + { + stop.store(true); + worker.join(); + } + RenderThread(const RenderThread&) = delete; + RenderThread& operator=(const RenderThread&) = delete; + +private: + std::atomic stop { false }; + std::thread worker; +}; +} + int main(int argc, char** argv) { juce::ScopedJuceInitialiser_GUI initialiseJuce; @@ -41,6 +67,26 @@ int main(int argc, char** argv) return processor->getMasterFirmwareRuntime().lcdVideoSnapshot(); }; processor->setStateInformation(state.getData(), static_cast(state.getSize())); + if (std::getenv("WAVE_TEST_STARTUP_RECALL") != nullptr) + { + renderAndCheck(); + const auto capture = [&] { + std::array sound {}; + for (size_t i = 0; i < sound.size(); ++i) + sound[i] = processor->getMasterFirmwareRuntime() + .currentSoundRecordByte(static_cast(i)); + return sound; + }; + const auto initial = capture(); + processor->stepFactoryPerformance(1); + renderAndCheck(); + processor->stepFactoryPerformance(-1); + renderAndCheck(); + if (initial != capture()) + throw std::runtime_error("Startup Sound differs from its Performance recall"); + std::cout << "Startup and returned Performance have identical native Sound records\n"; + return 0; + } const auto referenceScreen = renderAndCheck(); if (std::getenv("WAVE_TEST_PATCH_STEPS") != nullptr) { @@ -113,11 +159,11 @@ int main(int argc, char** argv) return 0; } std::atomic renderedBlocks { 0 }; - std::jthread concurrentRender([&](std::stop_token stop) + RenderThread concurrentRender([&](const std::atomic& stop) { juce::AudioBuffer audio(2, 512); juce::MidiBuffer midi; - while (!stop.stop_requested()) + while (!stop.load()) { { const juce::ScopedLock lock(processor->getCallbackLock()); @@ -161,13 +207,92 @@ int main(int argc, char** argv) const auto* directory = std::getenv("WAVE_FIRMWARE_DIR"); for (auto* processor : { first.get(), second.get() }) { + if (!processor->hasMountedDiskImage() + || processor->getMountedDiskImageFile().getFileName() != "Blank Wave.img" + || processor->getNumPrograms() != 256 + || processor->getProgramName(0) != "MULTI INIT" + || processor->getProgramName(255) != "MULTI INIT" + || processor->getSelectedPerformanceInstrument() != 0 + || !processor->isPerformanceInstrumentActive(0)) + throw std::runtime_error("Fresh instance did not load the default INIT bank and Instrument"); + for (int instrument = 1; instrument < 8; ++instrument) + if (processor->isPerformanceInstrumentActive(instrument)) + throw std::runtime_error("Default INIT bank enabled an unintended Instrument"); + wave::firmware::DosFloppyImage::SetupFile startupSetup; + if (!processor->mountedDiskImageIsWritable() + || wave::firmware::DosFloppyImage::readWaveSetup( + processor->getMountedDiskImageFile(), startupSetup).failed()) + throw std::runtime_error("Default mounted disk did not contain a writable SET"); if (directory != nullptr && !processor->loadFirmware(juce::File(directory)).hasBothImages()) throw std::runtime_error("Unable to load the supplied test firmware"); processor->prepareToPlay(48000.0, 128); } + if (first->getMountedDiskImageFile() == second->getMountedDiskImageFile()) + throw std::runtime_error("Fresh instances share the same writable startup disk"); if (directory != nullptr) { + juce::AudioBuffer startupAudio(2, 128); + const auto renderStartup = [&] { + for (int block = 0; block < 1000; ++block) + { + juce::MidiBuffer midi; + first->processBlock(startupAudio, midi); + } + }; + renderStartup(); + const auto& runtime = first->getMasterFirmwareRuntime(); + if (runtime.currentPerformanceId() != 0 + || runtime.currentPerformanceInstrument() != 0 + || first->getPanelSelectedMode() != 39 + || first->isPanelModeDisplayTransitionActive()) + throw std::runtime_error("Default SET did not finish on its editable Performance page"); + const auto cutoffBefore = runtime.currentSoundRecordByte(79); + first->setPanelPotValue(wave::parameters::cutoff, 0.9f); + renderStartup(); + first->setPanelPotValue(wave::parameters::cutoff, 0.1f); + renderStartup(); + if (runtime.currentSoundRecordByte(79) == cutoffBefore) + throw std::runtime_error("Startup knob movement did not edit the INIT Sound"); + juce::MidiBuffer startupNote; + startupNote.addEvent(juce::MidiMessage::noteOn(1, 60, 0.8f), 0); + first->processBlock(startupAudio, startupNote); + if (first->getActiveVoiceCount() == 0) + throw std::runtime_error("Default INIT Instrument could not play a note"); + juce::MidiBuffer releaseStartupNote; + releaseStartupNote.addEvent(juce::MidiMessage::allSoundOff(1), 0); + first->processBlock(startupAudio, releaseStartupNote); + + // A nonzero wavetable makes phantom startup encoder steps audible. + // Preserve an Instrument-local edit through a fresh instance. + auto& editableRuntime = const_cast(runtime); + if (!editableRuntime.writeCurrentSoundRecordByte(25, 42)) + throw std::runtime_error("Cannot install startup wavetable regression edit"); + renderStartup(); + juce::MemoryBlock startupState; + first->getStateInformation(startupState); + juce::TemporaryFile startupPreference(".txt"); + auto startupReopened = std::make_unique(startupPreference.getFile()); + startupReopened->prepareToPlay(96000.0, 512); + startupReopened->setStateInformation(startupState.getData(), static_cast(startupState.getSize())); + juce::AudioBuffer recalledAudio(2, 512); + const auto renderRecalled = [&] { + for (int block = 0; block < 1000; ++block) + { + juce::MidiBuffer midi; + startupReopened->processBlock(recalledAudio, midi); + } + }; + renderRecalled(); + auto& recalledRuntime = const_cast( + startupReopened->getMasterFirmwareRuntime()); + if (recalledRuntime.currentSoundRecordByte(25) != 42) + throw std::runtime_error("Fresh project recall changed the saved wavetable selector"); + startupReopened->turnPanelEncoder(8, -1); + renderRecalled(); + if (recalledRuntime.currentSoundRecordByte(25) != 41) + throw std::runtime_error("A genuine wavetable decrement was undone after startup"); + const auto remembered = preference.getFile().loadFileAsString(); juce::TemporaryFile emptyFolder(".dir"); emptyFolder.getFile().createDirectory(); @@ -202,11 +327,121 @@ int main(int argc, char** argv) || unrelatedPreference.getFile().loadFileAsString() != missingDefault) throw std::runtime_error("Project recall replaced the default firmware preference"); } - auto render = [](std::stop_token stop, WaveEmulationAudioProcessor* processor) + // Restore a one-patch image over an existing populated project bank. + // Zero slots must replace the old records rather than reject the bank. + { + constexpr size_t soundOffset = 0x12e7c, performanceOffset = 0x22e7c; + juce::MemoryBlock image(performanceOffset + 256 * 512, true); + auto* bytes = static_cast(image.getData()); + bytes[soundOffset + 239] = 0x55; + bytes[performanceOffset + 48] = 0x55; + std::copy_n("ONLY PATCH", 10, bytes + performanceOffset + 32); + juce::TemporaryFile setupFile(".set"), diskFile(".img"); + if (!setupFile.getFile().replaceWithData(image.getData(), image.getSize()) + || wave::firmware::DosFloppyImage::createWithWaveSetup( + diskFile.getFile(), setupFile.getFile()).failed() + || first->mountDiskImage(diskFile.getFile()).failed() + || !first->getProgramName(1).isEmpty()) + throw std::runtime_error("Mounting a one-patch disk retained the previous bank"); + juce::MemoryBlock state; + first->getStateInformation(state); + auto xml = juce::AudioProcessor::getXmlFromBinary(state.getData(), static_cast(state.getSize())); + auto tree = juce::ValueTree::fromXml(*xml); + tree.setProperty("machineHasActiveSet", true, nullptr); + tree.setProperty("machineActiveSetData", juce::var(image), nullptr); + tree.setProperty("factoryProgram", 0, nullptr); + for (const auto* key : { "machinePerformanceSnapshot", "machineFirmwareEditBuffers" }) + tree.removeProperty(key, nullptr); + juce::AudioProcessor::copyXmlToBinary(*tree.createXml(), state); + if (!diskFile.getFile().deleteFile()) + throw std::runtime_error("Could not remove one-patch source disk"); + second->setStateInformation(state.getData(), static_cast(state.getSize())); + if (second->getNumPrograms() != 256 || second->getProgramName(0) != "ONLY PATCH" + || !second->getProgramName(1).isEmpty() || !second->getProgramName(255).isEmpty() + || !second->hasMountedDiskImage() + || second->getMountedDiskImageFile().getFileName() != diskFile.getFile().getFileName()) + throw std::runtime_error("One-patch project inherited old Performance slots"); + // An explicit empty-bank flag wins over an old saved bank payload. + tree.setProperty("machineHasActiveSet", false, nullptr); + for (const auto* key : { "machineDiskImageData", "machineDiskImageName", "mountedDiskImage" }) + tree.removeProperty(key, nullptr); + juce::AudioProcessor::copyXmlToBinary(*tree.createXml(), state); + first->setStateInformation(state.getData(), static_cast(state.getSize())); + first->getStateInformation(state); + xml = juce::AudioProcessor::getXmlFromBinary(state.getData(), static_cast(state.getSize())); + tree = juce::ValueTree::fromXml(*xml); + if (first->getNumPrograms() != 1 || tree.hasProperty("machineActiveSetData") + || tree.hasProperty("machineDiskImageData")) + throw std::runtime_error("Empty project resurrected a previous bank or disk"); + } + if (const auto* imagePath = std::getenv("WAVE_TEST_DISK_IMAGE")) + { + wave::firmware::DosFloppyImage::SetupFile setup; + if (wave::firmware::DosFloppyImage::readWaveSetup(juce::File(imagePath), setup).failed()) + throw std::runtime_error("Cannot read supplied project-recall disk fixture"); + wave::presets::WaveFactorySet expected; + if (!expected.load(setup.data).validLayout) + throw std::runtime_error("Supplied disk fixture has no valid bank"); + juce::TemporaryFile disk(".img"), isolatedPreference(".txt"); + if (!juce::File(imagePath).copyFileTo(disk.getFile())) + throw std::runtime_error("Cannot copy project-recall disk fixture"); + auto reader = std::make_unique(isolatedPreference.getFile()); + reader->prepareToPlay(48000.0, 512); + if (reader->mountDiskImage(disk.getFile()).failed()) + throw std::runtime_error("Cannot mount project-recall fixture copy"); + juce::MemoryBlock state; + reader->getStateInformation(state); + auto reopened = std::make_unique(isolatedPreference.getFile()); + reopened->prepareToPlay(48000.0, 512); + reopened->setStateInformation(state.getData(), static_cast(state.getSize())); + juce::AudioBuffer audio(2, 512); + for (int block = 0; block < 32; ++block) + { + juce::MidiBuffer midi; + reopened->processBlock(audio, midi); + } + for (int program = 0; program < 256; ++program) + if (reopened->getProgramName(program) + != juce::String(expected.performanceName(program / 128, program % 128))) + throw std::runtime_error("Disk fixture reopened with a different Performance name"); + const auto& runtime = reopened->getMasterFirmwareRuntime(); + if (runtime.isLoaded()) + for (size_t byte = 0; byte < expected.performanceBank().size(); ++byte) + if (runtime.sharedProgramByte(0x28000u + static_cast(byte)) + != expected.performanceBank()[byte]) + throw std::runtime_error("Disk fixture's recalled Performance bank inherited old bytes"); + reopened->getStateInformation(state); + auto rereopened = std::make_unique(isolatedPreference.getFile()); + rereopened->setStateInformation(state.getData(), static_cast(state.getSize())); + for (int program = 0; program < 256; ++program) + if (rereopened->getProgramName(program) + != juce::String(expected.performanceName(program / 128, program % 128))) + throw std::runtime_error("Saving the recalled disk fixture changed an INIT slot"); + // Older state can contain a mixed bank even though its disk image + // is correct. Reload replaces all slots, not just the selected one. + auto cachedXml = juce::AudioProcessor::getXmlFromBinary( + state.getData(), static_cast(state.getSize())); + auto contaminated = juce::ValueTree::fromXml(*cachedXml); + auto wrongBank = setup.data; + auto* wrong = static_cast(wrongBank.getData()); + std::fill_n(wrong + 0x22e7c + 5 * 512 + 32, 16, static_cast(' ')); + std::copy_n("OLD DISK PATCH", 14, wrong + 0x22e7c + 5 * 512 + 32); + contaminated.setProperty("machineActiveSetData", juce::var(wrongBank), nullptr); + juce::AudioProcessor::copyXmlToBinary(*contaminated.createXml(), state); + rereopened->setStateInformation(state.getData(), static_cast(state.getSize())); + if (rereopened->reloadBankFromMountedImage().failed()) + throw std::runtime_error("Could not reload correct bank from remembered image"); + for (int program = 0; program < 256; ++program) + if (rereopened->getProgramName(program) + != juce::String(expected.performanceName(program / 128, program % 128))) + throw std::runtime_error("Reloading the image retained an older disk patch"); + std::cout << "Supplied disk bank retained all 256 Performance slots across project recall\n"; + } + auto render = [](const std::atomic& stop, WaveEmulationAudioProcessor* processor) { juce::AudioBuffer audio(2, 128); juce::MidiBuffer midi; - while (!stop.stop_requested()) + while (!stop.load()) { const juce::ScopedLock lock(processor->getCallbackLock()); audio.clear(); @@ -214,8 +449,8 @@ int main(int argc, char** argv) processor->processBlock(audio, midi); } }; - std::jthread firstRender(render, first.get()); - std::jthread secondRender(render, second.get()); + RenderThread firstRender([&](const std::atomic& stop) { render(stop, first.get()); }); + RenderThread secondRender([&](const std::atomic& stop) { render(stop, second.get()); }); for (int recall = 0; recall < 8; ++recall) { juce::MemoryBlock state; @@ -225,6 +460,20 @@ int main(int argc, char** argv) throw std::runtime_error("Host preset contained no state"); auto restored = std::make_unique(preference.getFile()); restored->setStateInformation(state.getData(), static_cast(state.getSize())); + if (recall == 0) + { + auto legacy = juce::AudioProcessor::getXmlFromBinary(state.getData(), + static_cast(state.getSize())); + legacy->setAttribute("ecoMode", true); + juce::MemoryBlock legacyState; + juce::AudioProcessor::copyXmlToBinary(*legacy, legacyState); + restored->setStateInformation(legacyState.getData(), static_cast(legacyState.getSize())); + restored->getStateInformation(legacyState); + const auto cleaned = juce::AudioProcessor::getXmlFromBinary( + legacyState.getData(), static_cast(legacyState.getSize())); + if (cleaned->hasAttribute("ecoMode")) + throw std::runtime_error("Recalled state retained the retired Eco setting"); + } if (directory != nullptr && !restored->getFirmwareReport().hasBothImages()) throw std::runtime_error("Host preset lost the firmware reference"); if (restored->getCurrentProgram() != first->getCurrentProgram()) diff --git a/Tests/WaveIntegrationTests.cpp b/Tests/WaveIntegrationTests.cpp index 6cef7b6..c91773f 100644 --- a/Tests/WaveIntegrationTests.cpp +++ b/Tests/WaveIntegrationTests.cpp @@ -1,6 +1,8 @@ #include "PluginProcessor.h" #include "PanelWiring.h" #include "Firmware/DosFloppyImage.h" +#include "UI/WaveLcdComponent.h" +#include #include #include @@ -8,11 +10,22 @@ #include #include #include +#include #include +#include #include +#if JUCE_MAC +#include +#endif namespace { +std::unique_ptr makeFactoryProcessor(const juce::File& preference = {}) +{ + return std::make_unique( + preference, WaveEmulationAudioProcessor::InitialBank::embeddedFactory); +} + void require(bool condition, const char* message) { if (!condition) @@ -27,9 +40,120 @@ void requireFinite(const juce::AudioBuffer& audio) "Plug-in processing produced non-finite audio"); } +void testOriginalFactoryWavetablesAndRecall() +{ + const auto checkBank = [](const WaveEmulationAudioProcessor& processor) { + const auto& bank = processor.getWavetableBank(); + require(bank.hasOriginalWaveFactoryTables() && bank.importedTableCount() == 64, + "Startup or project recall replaced original Wave tables with a fallback"); + std::vector halfWaves; + for (int table = 0; table < 64; ++table) + for (int wave = 0; wave < 64; ++wave) + for (int sample = 0; sample < 64; ++sample) + halfWaves.push_back(static_cast( + static_cast(bank.rawSample(table, wave, sample)) + 128)); + require(juce::SHA256(halfWaves.data(), halfWaves.size()).toHexString() + == "e2d3bdd4d22053058458962df7dc9a7ad08e895190f7b08e7f6b1ef63d1976c3", + "Active factory bank differs from original Wave OS 1.700 output"); + }; + juce::TemporaryFile preference(".txt"); + auto fresh = std::make_unique(preference.getFile()); + checkBank(*fresh); + auto processor = makeFactoryProcessor(preference.getFile()); + checkBank(*processor); + const auto ppg = juce::File::getCurrentWorkingDirectory().getChildFile( + "Firmware/wave_sys1_700/ppg-wave-2.3-v6-wavetables.rom"); + require(processor->loadWavetableRom(ppg), "Stale PPG import fixture failed to load"); + require(!processor->getWavetableBank().hasOriginalWaveFactoryTables(), + "An imported PPG bank was incorrectly labelled as original Wave data"); + juce::MemoryBlock state; + processor->getStateInformation(state); + processor->setStateInformation(state.getData(), static_cast(state.getSize())); + checkBank(*processor); + auto restored = std::make_unique(preference.getFile()); + restored->setStateInformation(state.getData(), static_cast(state.getSize())); + checkBank(*restored); +} + +void testInstrumentAllocationPageDrivesAudioAndRecall() +{ + juce::TemporaryFile preference(".txt"); + auto processor = makeFactoryProcessor(preference.getFile()); + processor->prepareToPlay(48000.0, 512); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int blocks) { + for (int block = 0; block < blocks; ++block) + { + juce::MidiBuffer midi; + processor->processBlock(audio, midi); + } + }; + const auto click = [&](int code) { + const auto matrix = wave::panel::matrixIndexForDiagnosticCode(code); + processor->setPanelButton(matrix, true); + process(8); + processor->setPanelButton(matrix, false); + process(96); + }; + process(96); + click(36); // Instrument Edit. + click(25); // Instrument 2, as in the reported screen. + click(23); // Page 2. + auto& firmware = const_cast( + processor->getMasterFirmwareRuntime()); + require(firmware.currentInstrumentEditTarget() == 1 + && firmware.currentInstrumentEditPage() == 1, + "Allocation fixture did not open Instrument 2 page 2"); + // Isolate the edited Instrument from the other active factory layers. + for (int layer = 0; layer < 8; ++layer) + require(firmware.writePerformanceInstrumentByte(layer, 3u, + layer == 1 ? 3 : 0), + "Could not isolate the allocation-test Instrument"); + process(8); + const auto checkNotes = [&](WaveEmulationAudioProcessor& target, int mode) { + juce::MidiBuffer midi; + midi.addEvent(juce::MidiMessage::allSoundOff(1), 0); + midi.addEvent(juce::MidiMessage::noteOn(1, 60, 0.8f), 1); + midi.addEvent(juce::MidiMessage::noteOn(1, 67, 0.8f), 2); + midi.addEvent(juce::MidiMessage::noteOn(1, 55, 0.8f), 3); + target.processBlock(audio, midi); + auto held = 0; + auto note = -1; + for (const auto& voice : target.getVoiceStates()) + if (voice.active && voice.keyDown && voice.layer == 1) + { + ++held; + note = voice.triggerNote; + } + require(held == (mode >= 17 ? 1 : 3), + "Alloc changed on the firmware page but not in audible voice allocation"); + if (mode >= 17) + require(note == ((mode - 17) % 3 == 2 ? 67 : 55), + "Firmware-selected mono priority did not reach the audio engine"); + }; + for (const auto mode : { 1, 17, 18, 19, 20, 21, 22 }) + { + processor->setPanelFader(5, wave::panel::performanceFaderAdcChannels[5], + static_cast(mode) / 22.0f, false); + process(64); + const auto record = firmware.currentPerformanceRecordOffset(); + require(record.has_value() + && (firmware.sharedProgramByte(*record + 64u + 32u + 15u) & 0x7fu) + == static_cast(mode), + "The Alloc fader did not commit its native Instrument field"); + checkNotes(*processor, mode); + } + juce::MemoryBlock state; + processor->getStateInformation(state); + auto restored = makeFactoryProcessor(preference.getFile()); + restored->setStateInformation(state.getData(), static_cast(state.getSize())); + restored->prepareToPlay(48000.0, 512); + checkNotes(*restored, 22); +} + void testAutomaticBootAudioAndState() { - auto processorStorage = std::make_unique(); + auto processorStorage = makeFactoryProcessor(); auto& processor = *processorStorage; const auto& report = processor.getFirmwareReport(); require(report.hasBothImages(), @@ -79,13 +203,27 @@ void testAutomaticBootAudioAndState() && localLong(0x4de18u) >= wave::firmware::MasterFirmwareRuntime::imageBase && localLong(0x4de18u) < 0x00050000u, "Automatic startup skipped the genuine OS MIDI callback registration"); - require(processor.getWavetableBank().isExternalRomLoaded() - && processor.getWavetableBank().importedTableCount() == 30, - "Reconstructed PPG Wave 2.3 V6 bank did not load automatically"); + require(processor.getWavetableBank().hasOriginalWaveFactoryTables() + && processor.getWavetableBank().importedTableCount() == 64, + "Original Wave factory bank did not load automatically"); require(processor.getFactorySetReport().validLayout && processor.getFactorySetReport().validSounds == 256 && processor.getFactorySetReport().validPerformances == 256, "Embedded Wave factory SET did not load its two native banks"); + constexpr uint32_t storedSoundBank = 0x18000u; + constexpr uint32_t soundSize = 0x100u; + const auto nativeSoundName = [&](uint32_t soundIndex) { + std::string name; + for (uint32_t i = 0; i < 16; ++i) + name.push_back(static_cast( + processor.getMasterFirmwareRuntime().sharedProgramByte( + storedSoundBank + soundIndex * soundSize + 240u + i))); + return name; + }; + require(nativeSoundName(0) == "sitar " + && nativeSoundName(1) == "DROOPOLYFLANGE " + && nativeSoundName(128) == "WoodOrgan WMF", + "Firmware Sound browser bank does not contain distinct SET names"); require(processor.getNumPrograms() == 256 && processor.getProgramName(0) == "drooSyn 1 oo DN" && processor.getProgramName(128) == "WoodOrgan WMF", @@ -98,6 +236,8 @@ void testAutomaticBootAudioAndState() processor.getStateInformation(restoredState); processor.setStateInformation(restoredState.getData(), static_cast(restoredState.getSize())); + require(processor.getWavetableBank().hasOriginalWaveFactoryTables(), + "Project state recall replaced the Wave factory bank"); require(std::abs(processor.getPanelFaderValue(0) - 0.75f) < 1.0e-5f, "Restored state discarded the Control-X performance fader position"); require((processor.getPerformanceFadersTouchedMask() & 0x01u) != 0u, @@ -464,7 +604,7 @@ void testAutomaticBootAudioAndState() juce::MemoryBlock savedState; processor.getStateInformation(savedState); - auto restoredStorage = std::make_unique(); + auto restoredStorage = makeFactoryProcessor(); auto& restored = *restoredStorage; restored.setStateInformation(savedState.getData(), static_cast(savedState.getSize())); @@ -482,7 +622,7 @@ void testAutomaticBootAudioAndState() void testFactoryA092ChoirVibratoUsesCallerScale() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(91); // A092: Choir 2. require(processor->getProgramName(91).startsWith("Choir 2"), @@ -530,7 +670,7 @@ void testFactoryA092ChoirVibratoUsesCallerScale() void testFactoryB057UsesMeasuredVcaAttackOne() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(184); // B057: Sarahvoice. require(processor->getProgramName(184).startsWithIgnoreCase("Sarahvoice"), @@ -579,7 +719,7 @@ void testFactoryB057UsesMeasuredVcaAttackOne() void testA030UsesItsSetUserWavetable() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->setCurrentProgram(29); // A030, Sitar. const auto* wavetable @@ -604,7 +744,7 @@ void testA030UsesItsSetUserWavetable() void testA044UsesNineteenTwentySpeechTable() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->setCurrentProgram(43); // A044, NINETEENTWENTY. const auto* wavetable @@ -627,7 +767,7 @@ void testA044UsesNineteenTwentySpeechTable() void testFactoryPerformanceLayering() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(41); // A042 -> three distinct full-range Sounds. @@ -658,7 +798,7 @@ void testFactoryPerformanceLayering() void testRapidPerformanceLcdRefreshIsAtomic() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto settle = [&] (int blocks) { @@ -672,6 +812,21 @@ void testRapidPerformanceLcdRefreshIsAtomic() processor->setCurrentProgram(11); // A012 settle(64); + auto& runtime = const_cast( + processor->getMasterFirmwareRuntime()); // Test the transaction before its next CPU slice. + const auto frameBeforeRecall = runtime.lcdVideoSnapshot(); + const auto pageBeforeRecall = runtime.lcdDisplayPage(); + require(runtime.requestPerformanceSelection(11) + && runtime.localByte(0x54b40u) == 0u + && runtime.localByte(0x54b41u) == 11u + && !runtime.currentPerformanceId().has_value(), + "Reselection put an invalid @128 sentinel into the live firmware selection"); + require(runtime.lcdVideoSnapshot() == frameBeforeRecall + && runtime.lcdDisplayPage() == pageBeforeRecall, + "Pending Performance recall published an incomplete LCD frame"); + settle(64); + require(runtime.currentPerformanceId() == 11, + "Same-number recall did not commit its valid Performance ID"); const auto referenceSelected = (static_cast(processor->getMasterFirmwareRuntime().localByte(0x54b40u)) << 8) | processor->getMasterFirmwareRuntime().localByte(0x54b41u); @@ -702,7 +857,7 @@ void testRapidPerformanceLcdRefreshIsAtomic() void testFirmwarePerformanceStepButtonsRefreshLcd() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) @@ -741,7 +896,7 @@ void testFirmwarePerformanceStepButtonsRefreshLcd() void testStoreButtonReachesFirmwareMenu() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) @@ -785,7 +940,7 @@ void testStoreButtonReachesFirmwareMenu() void testStoreRequesterStepButtonsChooseDestination() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) @@ -850,16 +1005,390 @@ void testStoreRequesterStepButtonsChooseDestination() "Store Minus did not restore the preceding firmware destination"); require(processor->getPanelLed(87), "Store LED did not remain lit throughout its requester"); - click(71); // Cancel / ESC exits Store. + const auto& runtime = processor->getMasterFirmwareRuntime(); + const auto cursorBefore = runtime.localByte(0x57005u); + click(23); // The naming dialog accepts Page Right. + require(runtime.localByte(0x57005u) == cursorBefore + 1, + "Performance name Page Right did not advance the firmware cursor"); + click(21); // And Page Left, while retaining the Store requester. + require(runtime.localByte(0x57005u) == cursorBefore, + "Performance name Page Left did not restore the firmware cursor"); + require(processor->isFirmwareRequesterActive(), + "Page cursor keys closed the Store requester"); + click(71); // Cancel / ESC leaves Store. + click(33); + click(57); + click(25); + require(processor->isFirmwareRequesterActive(), + "A second Store requester did not open"); + const auto reopenedCursor = runtime.localByte(0x57005u); + click(23); + require(processor->isFirmwareRequesterActive(), + "Page Right closed the second Store requester"); + require(runtime.localByte(0x57005u) == reopenedCursor + 1, + "Page Right did not move the cursor in the reopened Store requester"); + click(71); // Leave the second requester without writing again. require(processor->getPanelSelectedMode() == 39 && processor->getPanelLed(51) && !processor->getPanelLed(87), "Store LED remained lit after leaving the Store page"); } +void testPerformanceStoreNameAcrossBanks(int commitSamples, int commitOffset) +{ + auto processor = makeFactoryProcessor(); + processor->prepareToPlay(48000.0, 512); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int count) { + for (int block = 0; block < count; ++block) { + audio.clear(); + juce::MidiBuffer none; + processor->processBlock(audio, none); + } + }; + const auto click = [&](int code) { + const auto button = wave::panel::matrixIndexForDiagnosticCode(code); + require(processor->setPanelButton(button, true), "Performance Store rejected an input"); + process(8); + processor->setPanelButton(button, false); + process(64); + }; + process(64); + processor->setCurrentProgram(255); + process(128); + const auto& runtime = processor->getMasterFirmwareRuntime(); + const auto nameAt = [&](uint32_t offset, bool local) { + std::string result; + for (uint32_t index = 0; index < 16; ++index) + result += static_cast(local ? runtime.localByte(offset + index) + : runtime.sharedProgramByte(offset + index)); + return result; + }; + click(57); // Store directly from Performance, retaining its drawing callback. + click(25); // Perf. + require(processor->isFirmwareRequesterActive(), "Performance Store name dialog did not open"); + const std::string expected = "SAW2 Pad "; + for (size_t character = 0; character < expected.size(); ++character) { + for (int attempt = 0; attempt < 4; ++attempt) { + const auto value = runtime.localByte(0x56000u + static_cast(character)); + if (value == static_cast(expected[character])) + break; + processor->turnPanelEncoder(8, static_cast(expected[character]) - value); + process(48); + } + require(runtime.localByte(0x56000u + static_cast(character)) + == static_cast(expected[character]), "Performance name entry did not accept a character"); + if (character + 1 < expected.size()) + click(23); + } + const auto minus = wave::panel::matrixIndexForDiagnosticCode(69); + for (int index = 0; index < 255; ++index) + processor->setPanelButton(minus, true); + process(300); + processor->setPanelButton(minus, false); + process(64); + require(nameAt(0x56000u, true) == expected, "Changing Store destination replaced the entered name"); + audio.setSize(2, commitSamples); + process(commitOffset); + click(70); + process(2048 / commitSamples); + require(nameAt(0x28000u + 32u, false) == expected, + "Storing B128 to A001 replaced the Performance name"); + require(runtime.currentPerformanceId() == 0, + "Performance Store did not select its A001 destination"); + require(runtime.currentPerformanceRecordOffset().has_value(), "Stored Performance record is unavailable"); + require(nameAt(*runtime.currentPerformanceRecordOffset() + 32u, false) == expected, + "The current Performance name differs from the stored name"); +} + +void testStoreModeButtonExitAfterSave(bool sound = false, int operatingMode = 39) +{ + juce::ScopedJuceInitialiser_GUI initialiseJuce; + auto processor = makeFactoryProcessor(); + processor->prepareToPlay(48000.0, 512); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int count) { + for (int block = 0; block < count; ++block) { + audio.clear(); + juce::MidiBuffer none; + processor->processBlock(audio, none); +#if JUCE_MAC + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0001, true); +#endif + } + }; + const auto click = [&](int code) { + const auto button = wave::panel::matrixIndexForDiagnosticCode(code); + require(processor->setPanelButton(button, true), + "Store mode exit rejected a required panel button"); + process(8); + processor->setPanelButton(button, false); + process(96); + }; + process(96); + if (operatingMode != 39) + click(operatingMode); + const auto screenCallback = [&] { + uint32_t callback = 0; + for (uint32_t byte = 0; byte < 4; ++byte) + callback = (callback << 8u) + | processor->getMasterFirmwareRuntime().localByte(0x56bb0u + byte); + return callback; + }; + const auto operatingScreenCallback = screenCallback(); + click(57); // Store. + if (sound) + { + click(79); // Sound chooser. + click(22); // First Instrument. + } + else + click(25); // Performance. + require(processor->isFirmwareRequesterActive(), + "Performance Store requester did not open"); + const auto requesterScreen + = processor->getMasterFirmwareRuntime().lcdVideoSnapshot(); + const auto instrumentButton + = wave::panel::matrixIndexForDiagnosticCode(36); + require(!processor->setPanelButton(instrumentButton, true), + "Instrument Edit displaced the open Store requester"); + processor->setPanelButton(instrumentButton, false); + process(96); + require(processor->isFirmwareRequesterActive() + && processor->getPanelLed(87), + "Blocked Instrument Edit altered the Store requester or its lamp"); + + click(70); // Save and close the requester. + process(512); + require(!processor->isFirmwareRequesterActive() + && processor->getPanelSelectedMode() == 57 + && processor->getPanelLed(operatingMode == 36 ? 22 + : operatingMode == 33 ? 69 : 51) + && (operatingMode == 36 || !processor->getPanelLed(22)) + && (operatingMode == 39 || !processor->getPanelLed(51)) + && !processor->getPanelLed(87), + "Saving did not restore the preceding operating-mode lamp"); + require(screenCallback() == operatingScreenCallback, + "Saving restored the mode lamp without its operating LCD page"); + if (!sound && operatingMode == 39) + { + const auto selected = processor->getCurrentProgram(); + const auto plus = wave::panel::matrixIndexForDiagnosticCode(72); + for (int clickIndex = 0; clickIndex < 3; ++clickIndex) + { + require(processor->setPanelButton(plus, true), + "Plus immediately after Store was rejected"); + processor->setPanelButton(plus, false); // Brief click between callbacks. + process(clickIndex + 1); + } + process(512); + require(processor->getCurrentProgram() == (selected + 3) % 256 + && processor->getMasterFirmwareRuntime().currentPerformanceId() + == processor->getCurrentProgram(), + "Plus after Store lost or repeated a browsing click"); + const auto afterClick = processor->getCurrentProgram(); + process(1000); + require(processor->getCurrentProgram() == afterClick + && processor->getMasterFirmwareRuntime().currentPerformanceId() == afterClick, + "Released Plus kept browsing after Store"); + } + click(36); // The firmware accepts a mode change after the save. + process(512); + require(processor->getPanelSelectedMode() == 36 + && processor->getPanelLed(22) + && !processor->getPanelLed(87) + && !processor->isFirmwareRequesterActive() + && processor->getMasterFirmwareRuntime().lcdVideoSnapshot() + != requesterScreen, + "Instrument Edit after saving retained Store's light or requester"); +} + +void testPerformanceOverwriteClearsInactiveSlots(int blockSize) +{ + juce::ScopedJuceInitialiser_GUI initialiseJuce; + auto processor = makeFactoryProcessor(); + processor->prepareToPlay(48000.0, 512); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int count) { + for (int block = 0; block < count; ++block) { + audio.clear(); + juce::MidiBuffer none; + processor->processBlock(audio, none); +#if JUCE_MAC + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0001, true); +#endif + } + }; + const auto click = [&](int code) { + processor->setPanelButton(code, true); + process(8); + processor->setPanelButton(code, false); + process(96); + }; + auto& runtime = const_cast(processor->getMasterFirmwareRuntime()); + process(96); + std::vector bank(256u * 512u); + for (size_t byte = 0; byte < bank.size(); ++byte) + bank[byte] = runtime.sharedProgramByte(0x28000u + static_cast(byte)); + for (const auto program : { 2u, 3u }) { + std::copy_n(bank.begin(), 512, bank.begin() + program * 512u); + bank[program * 512u + 24u] = 0; + for (size_t layer = 0; layer < 8; ++layer) { + const auto slot = program * 512u + 64u + layer * 32u; + bank[slot + 3u] = layer < (program == 2u ? 3u : 1u) ? 3u : 0u; + bank[slot + 13u] = 0; + } + } + require(runtime.installPerformanceBank(bank), "Could not install overwrite fixture"); + processor->setCurrentProgram(3); + process(128); + click(57); + click(25); + require(processor->isFirmwareRequesterActive(), "Performance Store requester did not open"); + click(69); + require(runtime.localByte(0x4b1b3u) == 2, "Store destination did not reach A003"); + audio.setSize(2, blockSize); + click(70); + process(512); + for (uint32_t layer = 0; layer < 8; ++layer) { + const auto actual = runtime.sharedProgramByte(0x28400u + 64u + layer * 32u + 3u); + if (actual != (layer == 0 ? 3u : 0u)) + std::cerr << "Overwrite block " << blockSize << " layer " << layer << " source " << int(actual) << '\n'; + require(actual == (layer == 0 ? 3u : 0u), "Performance Store retained destination layer settings"); + } + for (int layer = 0; layer < 8; ++layer) + require(processor->isPerformanceInstrumentActive(layer) == (layer == 0), + "Performance Store left destination layers active in the engine"); + processor->setPanelButton(71, true); + processor->setPanelButton(71, false); // Mouse click between audio callbacks. + process(512); + require(!processor->isFirmwareRequesterActive(), "Cancel did not close Performance Store requester"); + require(processor->getPanelSelectedMode() == 39 + && processor->getPanelLed(51) + && !processor->getPanelLed(87), + "Store save did not restore the Performance mode lamp"); + audio.setSize(2, 512); + for (int repeat = 0; repeat < 2; ++repeat) { + click(57); + click(25); + require(processor->isFirmwareRequesterActive(), "Repeated Performance Store did not open"); + processor->setPanelButton(71, true); + processor->setPanelButton(71, false); + process(128); + require(!processor->isFirmwareRequesterActive(), "A brief Cancel left repeated Performance Store open"); + } + processor->setCurrentProgram(0); + process(128); + processor->setCurrentProgram(2); + process(128); + for (int layer = 0; layer < 8; ++layer) + require(processor->isPerformanceInstrumentActive(layer) == (layer == 0), + "Recalling the overwritten Performance reactivated empty slots"); +} + +void testRepeatedSoundStoreCursor() +{ + auto processor = makeFactoryProcessor(); + processor->prepareToPlay(48000.0, 512); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int count) { + for (int block = 0; block < count; ++block) { + audio.clear(); + juce::MidiBuffer none; + processor->processBlock(audio, none); + } + }; + const auto click = [&](int code) { + const auto button = wave::panel::matrixIndexForDiagnosticCode(code); + require(processor->setPanelButton(button, true), "Sound Store rejected a button"); + process(8); + processor->setPanelButton(button, false); + process(48); + }; + process(64); + click(33); + click(57); + click(79); // Sound opens the Instrument chooser. + for (int pass = 0; pass < 3; ++pass) { + click(pass % 2 == 0 ? 22 : 25); + require(processor->isFirmwareRequesterActive() && processor->getPanelLed(87) + && !processor->getPanelLed(22), + "Sound Store requester did not restore its Store lamp"); + const auto& runtime = processor->getMasterFirmwareRuntime(); + const auto cursor = runtime.localByte(0x57005u); + click(23); + require(runtime.localByte(0x57005u) == cursor + 1, + "Sound name Page Right did not advance the actual firmware cursor"); + click(21); + require(runtime.localByte(0x57005u) == cursor, + "Sound name Page Left did not restore the actual firmware cursor"); + const auto character = runtime.localByte(0x56000u + cursor); + for (int step = 0; step < 8 && runtime.localByte(0x56000u + cursor) == character; ++step) + { + processor->turnPanelEncoder(8, 1); + process(48); + } + require(runtime.localByte(0x56000u + cursor) != character, + "Data dial did not edit the selected Sound name character"); + click(70); + process(512); + require(!processor->isFirmwareRequesterActive(), + "One OK press did not close the Sound naming requester"); + require(processor->getPanelSelectedMode() == 57 && processor->getPanelLed(69) + && !processor->getPanelLed(22) + && !processor->getPanelLed(87), + "Sound Store OK did not restore the preceding Global Edit lamp"); + } + click(71); + require(processor->getPanelSelectedMode() == 39 && !processor->getPanelLed(87), + "Cancel did not leave the Sound Store chooser"); +} + +void testPerformanceBrowserHasDistinctStoredRecords() +{ + auto processor = makeFactoryProcessor(); + processor->prepareToPlay(48000.0, 512); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int count) { + for (int block = 0; block < count; ++block) + { + audio.clear(); + juce::MidiBuffer none; + processor->processBlock(audio, none); + } + }; + process(64); + const auto& firmware = processor->getMasterFirmwareRuntime(); + const auto verifyNames = [&]() { + for (int program = 0; program < 256; ++program) + { + const auto offset = 0x28000u + static_cast(program) * 512u; + require(firmware.sharedProgramByte(offset + 48u) == 0x55u, + "Firmware browser Performance bank contains an uninitialised record"); + juce::String name; + for (uint32_t character = 0; character < 16; ++character) + name += juce::String::charToString(static_cast( + firmware.sharedProgramByte(offset + 32u + character))); + require(name.trim() == processor->getProgramName(program).trim(), + "Firmware browser Performance name differs from its stored program"); + } + }; + verifyNames(); + for (int pass = 0; pass < 3; ++pass) + for (const int code : {36, 39}) + { + const auto matrix = wave::panel::matrixIndexForDiagnosticCode(code); + require(processor->setPanelButton(matrix, true), "Mode switch rejected"); + process(8); + processor->setPanelButton(matrix, false); + process(96); + verifyNames(); + } +} + void testStoreCancelRestoresNumericPerformancePreview() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks) { @@ -903,7 +1432,7 @@ void testStoreCancelRestoresNumericPerformancePreview() void testKeyboardControllerShiftReachesFirmware() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); juce::MidiBuffer noMidi; @@ -934,7 +1463,7 @@ void testKeyboardControllerShiftReachesFirmware() void testKeyboardOctaveButtonsDriveLocalKeyboardRange() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks, juce::MidiBuffer* supplied = nullptr) { @@ -965,7 +1494,7 @@ void testKeyboardOctaveButtonsDriveLocalKeyboardRange() juce::MemoryBlock savedState; processor->getStateInformation(savedState); - auto restored = std::make_unique(); + auto restored = makeFactoryProcessor(); restored->setStateInformation(savedState.getData(), static_cast(savedState.getSize())); restored->prepareToPlay(48000.0, 512); @@ -981,6 +1510,9 @@ void testKeyboardOctaveButtonsDriveLocalKeyboardRange() && restored->getPanelLed(58), "Host state did not restore the firmware keyboard octave position"); + // Running the restored processor above pauses this fixture's audio clock. + // Rebase its real-time MIDI collector before queuing an on-screen note. + process(1); processor->noteOnFromUi(60, 0.9f); process(4); require(processor->getFirstActiveMidiNote() == 72, @@ -1023,34 +1555,187 @@ void testKeyboardOctaveButtonsDriveLocalKeyboardRange() void testLowerKeyboardAssignableButtonsDriveFirmware() { - auto processor = std::make_unique(); - processor->prepareToPlay(48000.0, 512); - juce::AudioBuffer audio(2, 512); - const auto process = [&](int count) { - for (int block = 0; block < count; ++block) + juce::ScopedJuceInitialiser_GUI initialiseJuce; + for (const auto toggle : { false, true }) + { + auto processor = makeFactoryProcessor(); + processor->prepareToPlay(48000.0, 512); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int count) { + for (int block = 0; block < count; ++block) + { + juce::MidiBuffer none; + processor->processBlock(audio, none); +#if JUCE_MAC + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0001, true); +#endif + } + }; + process(96); + auto& runtime = const_cast( + processor->getMasterFirmwareRuntime()); + const auto offset = runtime.currentPerformanceRecordOffset(); + require(offset.has_value(), "Button fixture has no live Performance"); + std::array performance {}; + for (size_t byte = 0; byte < performance.size(); ++byte) + performance[byte] = runtime.sharedProgramByte(*offset + static_cast(byte)); + const auto instrument = runtime.currentPerformanceInstrument().value_or(-1); + require(instrument >= 0 && instrument < 8, "Button fixture has no selected Instrument"); + for (int layer = 0; layer < 8; ++layer) + performance[static_cast(64 + layer * 32 + 3)] = layer == instrument ? 3 : 0; + performance[4] = 70; + performance[5] = 71; + performance[6] = performance[7] = toggle ? 1 : 0; + require(runtime.installCurrentPerformanceRecord(performance), + "Could not install keyboard button modes"); + // Isolate Button 1/2 as audible pitch sources on the selected Sound. + for (const auto [byte, value] : std::array, 5> { + std::pair { 5, 29 }, { 6, 38 }, { 7, 100 }, + { 8, 38 }, { 9, 64 } }) + require(runtime.writeCurrentSoundRecordByte(byte, value), + "Could not install the keyboard button pitch route"); + process(32); + juce::MidiBuffer note; + note.addEvent(juce::MidiMessage::noteOn(1, 60, 0.9f), 0); + processor->processBlock(audio, note); + for (const auto [button, led, source] : std::array, 2> { + std::tuple { 3, 16, 29 }, { 4, 35, 30 } }) { - audio.clear(); - juce::MidiBuffer none; - processor->processBlock(audio, none); + require(runtime.writeCurrentSoundRecordByte(5, source), "Could not select Button source"); + process(16); + const auto idlePitch = processor->getFirstActivePitchModulation(); + require(!processor->getPanelLed(led), "Keyboard button started active"); + processor->setPanelButton(button, true); + process(48); + require(processor->getPanelLed(led), "Keyboard button press did not light its lamp"); + const auto activePitch = processor->getFirstActivePitchModulation(); + require(activePitch > idlePitch + 0.05f, + "Physical keyboard button did not drive its dedicated modulation source"); + processor->setPanelButton(button, false); + process(48); + require(processor->getPanelLed(led) == toggle, + "Keyboard button ignored Performance touch/toggle mode"); + require(std::abs(processor->getFirstActivePitchModulation() + - (toggle ? activePitch : idlePitch)) < 0.01f, + "Button release left the wrong modulation state"); + if (toggle) + { + // Hosts reset the audio engine without resetting the panel firmware. + processor->releaseResources(); + processor->prepareToPlay(48000.0, 512); + juce::MidiBuffer retrigger; + retrigger.addEvent(juce::MidiMessage::noteOn(1, 60, 0.9f), 0); + processor->processBlock(audio, retrigger); + process(8); + require(processor->getFirstActivePitchModulation() > idlePitch + 0.05f, + "Audio restart lost the latched keyboard button"); + processor->setPanelButton(button, true); + process(48); + processor->setPanelButton(button, false); + process(48); + require(!processor->getPanelLed(led), "Second toggle press did not turn the button off"); + processor->setPanelButton(button, true); + processor->setPanelButton(button, false); + process(48); + require(processor->getPanelLed(led), "A click between audio callbacks was lost"); + // Two complete clicks queued together must toggle twice. + for (int click = 0; click < 2; ++click) + { + processor->setPanelButton(button, true); + processor->setPanelButton(button, false); + } + process(96); + require(processor->getPanelLed(led), "Rapid clicks collapsed into one toggle"); + processor->setPanelButton(button, true); + processor->setPanelButton(button, false); + process(48); + } } - }; - process(96); - for (const auto [button, led] : std::array, 2> { - std::pair { 3, 16 }, std::pair { 4, 35 } }) - { - const auto before = processor->getPanelLed(led); - processor->setPanelButton(button, true); + // The selected live Performance assigns Button 2 to CC71, rather + // than the previous bridge's fixed CC81 or the startup SET's CC1. + const auto idlePitch = processor->getFirstActivePitchModulation(); + juce::MidiBuffer controller; + controller.addEvent(juce::MidiMessage::controllerEvent(1, 71, 127), 0); + processor->processBlock(audio, controller); process(48); - processor->setPanelButton(button, false); - process(48); - require(processor->getPanelLed(led) != before, - "A lower assignable button did not reach its firmware mode/LED output"); + require(processor->getFirstActivePitchModulation() > idlePitch + 0.05f, + "The processor ignored the live Performance's Button MIDI assignment"); } } +void testAssignableButtonMidiRouting() +{ + wave::dsp::WaldorfEngine engine; + engine.prepare(48000.0, 512); + wave::dsp::WaldorfEngine::PerformanceSnapshot performance; + auto& layer = performance.layers[0]; + layer.enabled = true; + layer.source = 3; + layer.midiChannel = 2; + layer.sound.modulationRoutes[wave::parameters::osc1PitchMod1] = { 29, 38, 24.0f }; + layer.sound.modulationRoutes[wave::parameters::osc2PitchMod1] = { 30, 38, 24.0f }; + layer.sound.modulationRoutes[wave::parameters::osc1PitchMod2].amount = 0.0f; + layer.sound.modulationRoutes[wave::parameters::osc2PitchMod2].amount = 0.0f; + layer.sound.oscillatorOctaves = { 0, 0 }; + layer.sound.oscillatorSemitones = { 0, 0 }; + engine.setKeyboardButtonControllers(70, 71); + juce::AudioBuffer audio(2, 512); + const auto send = [&](juce::MidiMessage message) { + juce::MidiBuffer midi; + midi.addEvent(message, 0); + engine.render(audio, midi, performance); + for (int block = 0; block < 4; ++block) + engine.render(audio, {}, performance); + }; + send(juce::MidiMessage::noteOn(2, 60, 0.9f)); + const auto check = [&](bool one, bool two) { + require((std::abs(engine.firstActivePitchModulation(0)) > 0.1f) == one + && (std::abs(engine.firstActivePitchModulation(1)) > 0.1f) == two, + "Assigned keyboard button MIDI routing produced the wrong modifier state"); + }; + check(false, false); + send(juce::MidiMessage::controllerEvent(2, 80, 127)); + send(juce::MidiMessage::controllerEvent(1, 70, 127)); + check(false, false); // Neither the obsolete fixed CC nor another channel. + send(juce::MidiMessage::controllerEvent(2, 70, 127)); + check(true, false); + send(juce::MidiMessage::controllerEvent(2, 70, 0)); + send(juce::MidiMessage::controllerEvent(2, 71, 127)); + check(false, true); + send(juce::MidiMessage::controllerEvent(2, 71, 0)); + engine.setKeyboardButtonControllers(70, 70); + juce::MidiBuffer physicalControl; + physicalControl.addEvent(juce::MidiMessage::controllerEvent(1, 70, 127), 0); + engine.render(audio, {}, physicalControl, performance); + for (int block = 0; block < 4; ++block) + engine.render(audio, {}, performance); + check(false, false); // A physical wheel does not acquire a Button identity via CC aliasing. + engine.setKeyboardButtons(true, false); + for (int block = 0; block < 4; ++block) + engine.render(audio, {}, performance); + check(true, false); // Physical identity survives a shared MIDI assignment. + require(!engine.isSustainPedalDown(), "A physical Button press became a sustain pedal event"); + send(juce::MidiMessage::controllerEvent(2, 70, 127)); + check(true, true); // Recorded MIDI intentionally reaches both assigned sources. + send(juce::MidiMessage::controllerEvent(2, 70, 0)); + check(false, false); + layer.source = 1; + send(juce::MidiMessage::controllerEvent(2, 70, 127)); + check(true, false); // Switching to the keyboard source adopts its held button state. + engine.setKeyboardButtons(false, true); + for (int block = 0; block < 4; ++block) + engine.render(audio, {}, performance); + check(false, true); + layer.source = 2; + engine.setKeyboardButtons(true, false); + for (int block = 0; block < 4; ++block) + engine.render(audio, {}, performance); + check(false, true); // MIDI-only Instruments ignore physical keyboard controls. +} + void testGlideEditUsesFirmwareLamp() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int count) { @@ -1076,7 +1761,7 @@ void testPluginMidiFollowsKeyboardOctaveButtons() { juce::AudioProcessor::setTypeOfNextNewPlugin( juce::AudioProcessor::wrapperType_VST3); - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); juce::AudioProcessor::setTypeOfNextNewPlugin( juce::AudioProcessor::wrapperType_Undefined); processor->prepareToPlay(48000.0, 128); @@ -1125,7 +1810,7 @@ void testPluginMidiFollowsKeyboardOctaveButtons() void testShiftDisplaySevenOpensFirmwareServiceMenu() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); juce::MidiBuffer noMidi; @@ -1144,7 +1829,9 @@ void testShiftDisplaySevenOpensFirmwareServiceMenu() const auto storeScreen = processor->getMasterFirmwareRuntime().lcdVideoSnapshot(); processor->setKeyboardControllerButton(0x52u, true); - processBlocks(8); + for (int block = 0; block < 64 + && processor->getMasterFirmwareRuntime().localByte(0x59869u) == 0; ++block) + processBlocks(1); require(processor->getMasterFirmwareRuntime().localByte(0x59869u) != 0, "Firmware Shift virtual input did not assert the Store modifier"); processor->setPanelButton(29, true); // Seventh button above the display. @@ -1152,7 +1839,9 @@ void testShiftDisplaySevenOpensFirmwareServiceMenu() processor->setPanelButton(29, false); processBlocks(32); processor->setKeyboardControllerButton(0x52u, false); - processBlocks(8); + for (int block = 0; block < 64 + && processor->getMasterFirmwareRuntime().localByte(0x59869u) != 0; ++block) + processBlocks(1); const auto readPointer = [&processor](uint32_t address) { const auto& runtime = processor->getMasterFirmwareRuntime(); return (static_cast(runtime.localByte(address)) << 24u) @@ -1170,7 +1859,7 @@ void testShiftDisplaySevenOpensFirmwareServiceMenu() void testFirmwareVcfCalibrationTableFeedsAllVoices() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); const auto& runtime = processor->getMasterFirmwareRuntime(); std::array initialCodes{}; @@ -1223,7 +1912,7 @@ void testFirmwareVcfCalibrationTableFeedsAllVoices() void testFactoryA001VoiceCardsTrackTheSameFilter() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->selectFactoryPerformance(0, 1); const auto sound = wave::parameters::readSnapshot(processor->parameters); @@ -1266,7 +1955,7 @@ void testFactoryA001VoiceCardsTrackTheSameFilter() void testFactoryA001HeldCutoffUsesFirmwareEnvelopeScale() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(96000.0, 256); processor->selectFactoryPerformance(0, 1); const auto sound = wave::parameters::readSnapshot(processor->parameters); @@ -1287,7 +1976,7 @@ void testFactoryA001HeldCutoffUsesFirmwareEnvelopeScale() void testFactoryA001OverlappingChordNoteOffKeepsRetriggeredVoices() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->selectFactoryPerformance(0, 1); @@ -1328,7 +2017,7 @@ void testFactoryA001OverlappingChordNoteOffKeepsRetriggeredVoices() void testFactoryA001CapturedChordSequenceKeepsEveryVcaOpen() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->setMidiInputActsAsLocalKeyboard(true); processor->prepareToPlay(96000.0, 256); processor->selectFactoryPerformance(0, 1); @@ -1392,8 +2081,12 @@ void testFactoryA001CapturedChordSequenceKeepsEveryVcaOpen() "Captured A001 sequence collapsed five held voice VCAs"); } -void testDiskSetSerialSelectionUpdatesDsp() +void testDiskSetSerialSelectionUpdatesDsp(bool checkColdStart = true, + bool nativeDiskLoad = false, + bool fromColdStart = false, + bool loadMachineSpecific = true) { + juce::ScopedJuceInitialiser_GUI initialiseJuce; constexpr size_t soundBankOffset = 0x12e7cu; constexpr size_t performanceBankOffset = 0x22e7cu; constexpr size_t soundSize = 256u; @@ -1405,8 +2098,18 @@ void testDiskSetSerialSelectionUpdatesDsp() ? juce::File(configuredSet) : juce::File::getCurrentWorkingDirectory().getChildFile("wave.set"); juce::MemoryBlock setup; - require(factorySetFile.loadFileAsData(setup), - "Could not load the source SET for disk/DSP regression"); + const auto suppliedDisk = juce::SystemStats::getEnvironmentVariable("WAVE_TEST_DISK_IMAGE", {}); + if (suppliedDisk.isNotEmpty()) + { + wave::firmware::DosFloppyImage::SetupFile diskSetup; + require(wave::firmware::DosFloppyImage::readWaveSetup( + juce::File(suppliedDisk), diskSetup).wasOk(), + "Could not read supplied disk for disk/DSP regression"); + setup = diskSetup.data; + } + else + require(factorySetFile.loadFileAsData(setup), + "Could not load the source SET for disk/DSP regression"); auto* bytes = static_cast(setup.getData()); const auto performanceOffset = performanceBankOffset + performanceSize; // A002. const auto* performance = bytes + performanceOffset; @@ -1447,8 +2150,14 @@ void testDiskSetSerialSelectionUpdatesDsp() && firstImageFile.copyFileTo(imageFile), "Could not create disk/DSP regression image"); - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); + if (fromColdStart) + processor->resetToColdStart(); +#if JUCE_MAC + else if (nativeDiskLoad) + processor->setCurrentProgram(7); // Recall must retire a different prior program. +#endif require(processor->mountDiskImage(firstImageFile).wasOk(), "Initial Wave disk could not be mounted before media swap"); juce::AudioBuffer audio(2, 512); @@ -1491,10 +2200,47 @@ void testDiskSetSerialSelectionUpdatesDsp() processor->processBlock(audio, noMidi); } }; - clickAndSettle(34); // Option / Import workspace. - require(processor->getPanelSelectedMode() == 34, - "Mounted SET did not enter the Option/Import workspace"); - clickAndSettle(70); // Confirm the SET load. + clickAndSettle(58); // Disk / Load menu. + if (!nativeDiskLoad) + clickAndSettle(70); // Open its next step; the SET has not transferred. + require(processor->getPanelSelectedMode() == 58, + "First Disk OK prematurely closed the Total Recall workspace"); + if (nativeDiskLoad) + { + clickAndSettle(22); // Load choices. + for (int choice = 0; choice < 12; ++choice) + clickAndSettle(72); + clickAndSettle(70); // Select Total Recall. + clickAndSettle(70); // Confirm the file. + clickAndSettle(70); // Confirm the load. + for (int block = 0; block < 4000; ++block) + { + audio.clear(); + juce::MidiBuffer noMidi; + processor->processBlock(audio, noMidi); + } + clickAndSettle(loadMachineSpecific ? 70 : 71); // Machine-specific data choice. + for (int block = 0; block < 4000; ++block) + { + audio.clear(); + juce::MidiBuffer noMidi; + processor->processBlock(audio, noMidi); + } + uint32_t callback = 0; + for (uint32_t i = 0; i < 4; ++i) + callback = (callback << 8u) | processor->getMasterFirmwareRuntime().localByte(0x56bb0u + i); + require(callback == 0x0189c4u, "Total Recall did not install the Performance screen"); + } + else + { + clickAndSettle(71); // Leave Disk before testing Option/Import separately. + require(processor->mountDiskImage(imageFile).wasOk(), + "Could not remount SET after cancelling Disk selection"); + clickAndSettle(34); // Option / Import workspace. + require(processor->getPanelSelectedMode() == 34, + "Mounted SET did not enter the Option/Import workspace"); + clickAndSettle(70); // Confirm the SET load. + } for (int block = 0; block < 256 && processor->isPanelModeDisplayTransitionActive(); ++block) @@ -1506,9 +2252,49 @@ void testDiskSetSerialSelectionUpdatesDsp() require(processor->getPanelSelectedMode() == 39 && !processor->isPanelModeDisplayTransitionActive(), "Successful SET import left Performance mode or its LCD transaction frozen"); + require(processor->getMasterFirmwareRuntime().currentPerformanceId() == 0, + "SET import did not select A001"); +#if JUCE_MAC + // The firmware posts its DSP recall to the message thread, just as in a host. + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, false); + require(processor->getCurrentProgram() == 0, "DSP recall did not reach the message thread"); +#endif + clickAndSettle(52); // 0. + clickAndSettle(56); // 2: A002, using the keypad after importing the bank. + require(processor->getMasterFirmwareRuntime().currentPerformanceId() == 1, + "Keypad did not select A002 after SET import"); + require(processor->getMasterFirmwareRuntime().localByte(0x56f4au) == 0, + "SET import left the Manager owning keypad input"); +#if JUCE_MAC + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, false); + // Only the native load transfers and activates the mounted SET. The + // synthetic Option fixture leaves it as a candidate until host recall. + if (nativeDiskLoad) + require(processor->getCurrentProgram() == 1, + "Keypad selection after SET import did not reach the DSP"); +#endif + clickAndSettle(52); // 0. + clickAndSettle(46); // 1: restore A001 for the increment checks below. + require(processor->getMasterFirmwareRuntime().currentPerformanceId() == 0, + "Keypad did not return to A001 after SET import"); +#if JUCE_MAC + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, false); +#endif + constexpr uint32_t storedSoundBank = 0x18000u; + constexpr uint32_t bankBSound1Name = storedSoundBank + 128u * 256u + 240u; + require(processor->getMasterFirmwareRuntime().sharedProgramByte( + bankBSound1Name) == bytes[soundBankOffset + 128u * soundSize + 240u] + && processor->getMasterFirmwareRuntime().sharedProgramByte( + bankBSound1Name + 256u) == bytes[soundBankOffset + 129u * soundSize + 240u], + "Imported SET did not populate distinct firmware Sound names"); const auto lcdWritesBeforeStep = processor->getMasterFirmwareRuntime().lcdVideoWriteCount(); + constexpr std::array receiveSettings { 0x8806u, 0x880du, 0x8824u }; + std::array originalReceiveSettings {}; + for (size_t index = 0; index < receiveSettings.size(); ++index) + originalReceiveSettings[index] = processor->getMasterFirmwareRuntime() + .sharedWorkByte(receiveSettings[index]); processor->setPanelButton( wave::panel::matrixIndexForDiagnosticCode(72), true); // Plus serial code. for (int block = 0; block < 8; ++block) @@ -1555,6 +2341,33 @@ void testDiskSetSerialSelectionUpdatesDsp() > writesBefore, "Repeated Plus froze after importing a replacement disk SET"); } + // Exercise both bank boundaries with the same panel contacts as the UI. + for (const auto start : { 0, 127, 128, 255 }) + { + processor->setCurrentProgram(start); + for (int block = 0; block < 64; ++block) + { + juce::MidiBuffer noMidi; + processor->processBlock(audio, noMidi); + } + clickAndSettle(72); + require(processor->getMasterFirmwareRuntime().currentPerformanceId() + == (start + 1) % 256, + "Plus after disk load produced an invalid Performance bank/number"); + clickAndSettle(69); + require(processor->getMasterFirmwareRuntime().currentPerformanceId() == start, + "Minus after disk load produced an invalid Performance bank/number"); + } + processor->setCurrentProgram(4); + for (int block = 0; block < 64; ++block) + { + juce::MidiBuffer noMidi; + processor->processBlock(audio, noMidi); + } + for (size_t index = 0; index < receiveSettings.size(); ++index) + require(processor->getMasterFirmwareRuntime().sharedWorkByte(receiveSettings[index]) + == originalReceiveSettings[index], + "Panel browsing changed the disk's external MIDI receive settings"); for (int voice = 0; voice < wave::dsp::WaldorfEngine::voiceCount; ++voice) require(processor->getMasterFirmwareRuntime().filterCalibrationCode(voice) == wave::dsp::WaldorfEngine::installedFilterCalibrationCodes[ @@ -1565,7 +2378,7 @@ void testDiskSetSerialSelectionUpdatesDsp() processor->getStateInformation(persistentState); require(imageFile.deleteFile(), "Could not remove the source disk before the self-contained recall test"); - auto restored = std::make_unique(); + auto restored = makeFactoryProcessor(); restored->setStateInformation(persistentState.getData(), static_cast(persistentState.getSize())); require(restored->hasMountedDiskImage() @@ -1589,6 +2402,12 @@ void testDiskSetSerialSelectionUpdatesDsp() require(!restoredHostStateDirectory.exists(), "Destroying a plugin instance retained its private restored disk directory"); + if (!checkColdStart) + { + require(directory.deleteRecursively(), + "Could not remove disk/DSP regression directory"); + return; + } processor->resetToColdStart(); require(!processor->hasMountedDiskImage() && processor->getNumPrograms() == 1 @@ -1604,13 +2423,21 @@ void testDiskSetSerialSelectionUpdatesDsp() processor->processBlock(audio, coldStartMidi); require(processor->getActiveVoiceCount() == 0, "Cold start allocated a voice without a loaded sound set"); + for (int block = 0; block < 32; ++block) + { + juce::MidiBuffer noMidi; + processor->processBlock(audio, noMidi); + } + for (int layer = 0; layer < 8; ++layer) + require(!processor->isPerformanceInstrumentActive(layer), + "Firmware INIT records repopulated the cold-start bank"); require(directory.deleteRecursively(), "Could not remove disk/DSP regression directory"); } void testSamePerformanceReselectionLeavesModalScreen() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) @@ -1667,7 +2494,7 @@ void testSamePerformanceReselectionLeavesModalScreen() void testPerformanceInstrumentSelection() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) { @@ -1789,7 +2616,9 @@ void testPerformanceInstrumentSelection() require(restoredFilterMod != nullptr && std::abs(restoredFilterMod->load() - confirmedOriginalFilterMod) < 0.002f, - "A modulation knob edit was lost when switching away and back"); + ("A modulation knob edit was lost when switching away and back: " + + std::to_string(restoredFilterMod->load()) + " vs " + + std::to_string(confirmedOriginalFilterMod)).c_str()); require(processor->getMasterFirmwareRuntime().panelAnalogByte(62) == physicalResonance, "Returning to an Instrument moved a physical potentiometer"); @@ -1839,7 +2668,7 @@ void testPerformanceInstrumentSelection() void testSelectedInstrumentSoundRecordOverridesOldPanelSnapshot() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(41); // A042: several active Instruments. juce::AudioBuffer audio(2, 512); @@ -1903,7 +2732,7 @@ void testSelectedInstrumentSoundRecordOverridesOldPanelSnapshot() void testOutgoingInstrumentIsSavedFromFirmwareNotPanelMirror() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(41); // A042: several active Instruments. juce::AudioBuffer audio(2, 512); @@ -1956,7 +2785,7 @@ void testOutgoingInstrumentIsSavedFromFirmwareNotPanelMirror() void requireInstrumentSelectionDoesNotChangeSound(int program, const char* performanceName) { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(program); juce::AudioBuffer audio(2, 512); @@ -2015,10 +2844,17 @@ void requireInstrumentSelectionDoesNotChangeSound(int program, for (const auto instrument : active) { const auto index = static_cast(instrument); - require(std::memcmp( - &selectedSnapshot.layers[index], - &baselineSnapshot.layers[index], - sizeof(wave::dsp::WaldorfEngine::PerformanceLayer)) == 0, + const auto& originalLayer = baselineSnapshot.layers[index]; + const auto& selectedLayer = selectedSnapshot.layers[index]; + // Compare values, not struct padding: Snapshot contains bools + // whose adjacent padding can differ after an equivalent decode. + require(selectedLayer.sound.panAmount == originalLayer.sound.panAmount + && selectedLayer.sound.panModulationMode == originalLayer.sound.panModulationMode + && selectedLayer.sound.wavetableIndex == originalLayer.sound.wavetableIndex + && selectedLayer.sound.oscillatorOctaves == originalLayer.sound.oscillatorOctaves + && selectedLayer.gain == originalLayer.gain + && selectedLayer.transposeSemitones == originalLayer.transposeSemitones + && selectedLayer.detuneCents == originalLayer.detuneCents, "Instrument selection mutated a stored Performance layer"); const auto after = processor->probeCurrentLayerVoice( 7, instrument, 60, 0.8f, 24000, 42); @@ -2044,7 +2880,7 @@ void testFactoryStereoInstrumentSelectionDoesNotChangeSound() void testA001DuplicateSoundAssignmentsHavePrivateInstrumentEdits() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(0); // A001: I1 and I2 both assign Sound a002. juce::AudioBuffer audio(2, 512); @@ -2093,7 +2929,7 @@ void testA001DuplicateSoundAssignmentsHavePrivateInstrumentEdits() juce::MemoryBlock hostState; processor->getStateInformation(hostState); - auto restored = std::make_unique(); + auto restored = makeFactoryProcessor(); restored->setStateInformation(hostState.getData(), static_cast(hostState.getSize())); restored->prepareToPlay(48000.0, 512); @@ -2129,7 +2965,7 @@ void testA001DuplicateSoundAssignmentsHavePrivateInstrumentEdits() void testInstrumentButtonsDoNotRewriteLayerOctaves() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(41); // A042: three active Instruments. juce::AudioBuffer audio(2, 512); @@ -2195,7 +3031,7 @@ void testInstrumentButtonsDoNotRewriteLayerOctaves() void testInstrumentEditLayerSelection() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(41); // A042: three active Instruments. juce::AudioBuffer audio(2, 512); @@ -2252,16 +3088,128 @@ void testInstrumentEditLayerSelection() } } -void testPerformanceMuteAndSolo() +void testInstrumentSourceKeepsOtherLayers() { - auto processor = std::make_unique(); - processor->setCurrentProgram(41); // A042: three active Instruments. - std::array active { -1, -1, -1 }; - auto activeCount = 0; - for (int instrument = 0; instrument < 8 && activeCount < 3; ++instrument) - if (processor->isPerformanceInstrumentActive(instrument)) - active[static_cast(activeCount++)] = instrument; - require(activeCount == 3, "A042 did not expose three Mute/Solo targets"); + const auto configuredSet = juce::SystemStats::getEnvironmentVariable( + "WAVE_FACTORY_SET", {}); + const auto sourceSet = configuredSet.isNotEmpty() + ? juce::File(configuredSet) + : juce::File::getCurrentWorkingDirectory().getChildFile("wave.set"); + juce::MemoryBlock setup; + require(sourceSet.loadFileAsData(setup), "Source test could not read SET"); + auto* bytes = static_cast(setup.getData()); + constexpr size_t performanceOffset = 0x22e7cu + 41u * 512u; + constexpr size_t layerTable = performanceOffset + 64u; + std::array firstLayer {}; + std::copy_n(bytes + layerTable, firstLayer.size(), firstLayer.begin()); + for (int layer = 0; layer < 3; ++layer) + { + auto* destination = bytes + layerTable + static_cast(layer) * 32u; + std::copy(firstLayer.begin(), firstLayer.end(), destination); + destination[3] = 3; // Keys and MIDI; all three share the same Sound. + destination[13] = 0; + } + const auto directory = juce::File::getSpecialLocation(juce::File::tempDirectory) + .getNonexistentChildFile("wave-source-test", {}, true); + require(directory.createDirectory().wasOk(), "Source test directory failed"); + const auto setFile = directory.getChildFile("SOURCE.SET"); + const auto imageFile = directory.getChildFile("SOURCE.IMG"); + require(setFile.replaceWithData(setup.getData(), setup.getSize()) + && wave::firmware::DosFloppyImage::createWithWaveSetup( + imageFile, setFile).wasOk(), + "Source test disk creation failed"); + auto processor = makeFactoryProcessor(); + processor->prepareToPlay(48000.0, 512); + require(processor->mountDiskImage(imageFile).wasOk(), + "Source test disk mount failed"); + processor->setCurrentProgram(41); // A042 has three active Instruments. + juce::AudioBuffer audio(2, 512); + const auto processBlocks = [&](int count) { + for (int block = 0; block < count; ++block) + { + audio.clear(); + juce::MidiBuffer midi; + processor->processBlock(audio, midi); + } + }; + processBlocks(96); + for (int layer = 0; layer < 3; ++layer) + require(processor->isPerformanceInstrumentActive(layer), + "Source test did not initialise three active layers"); + const auto& firmware = processor->getMasterFirmwareRuntime(); + const auto record = firmware.currentPerformanceRecordOffset(); + require(record.has_value(), "Source test has no Performance record"); + std::array originalSources {}; + for (int layer = 0; layer < 8; ++layer) + originalSources[static_cast(layer)] + = firmware.sharedProgramByte(*record + 64u + + static_cast(layer) * 32u + 3u) & 0x7f; + const auto click = [&](int code) { + const auto button = wave::panel::matrixIndexForDiagnosticCode(code); + processor->setPanelButton(button, true); + processBlocks(8); + processor->setPanelButton(button, false); + processBlocks(96); + }; + click(36); // Instrument Edit. + click(26); // Instrument 3. + require(firmware.currentPerformanceInstrument() == 2, + "Source test did not select Instrument 3"); + for (int layer = 0; layer < 8; ++layer) + { + const auto selectedRecord = firmware.currentPerformanceRecordOffset(); + require(selectedRecord.has_value(), "Selection lost Performance record"); + const auto source = firmware.sharedProgramByte( + *selectedRecord + 64u + + static_cast(layer) * 32u + 3u) & 0x7f; + require(source == originalSources[static_cast(layer)], + "Selecting Instrument 3 changed another Instrument Source"); + } + constexpr auto sourceChannel = wave::panel::performanceFaderAdcChannels[7]; + for (const auto position : { 0.0f, 1.0f, 0.0f, 1.0f }) + { + processor->setPanelFader(7, sourceChannel, position, false); + processBlocks(96); + const auto liveRecord = firmware.currentPerformanceRecordOffset(); + require(liveRecord.has_value(), "Source edit lost its Performance record"); + require(firmware.currentInstrumentEditTarget() == 2 + && processor->getSelectedPerformanceInstrument() == 2, + "Source change moved the Instrument Edit target"); + require((firmware.sharedProgramByte(*liveRecord + 64u + 2u * 32u + 3u) & 0x7f) + == (position == 0.0f ? 0 : 3) + && processor->isPerformanceInstrumentActive(2) == (position > 0.0f), + "Source change did not update Instrument 3 in firmware and engine"); + for (int layer = 0; layer < 8; ++layer) + { + if (layer == 2) + continue; + const auto source = firmware.sharedProgramByte( + *liveRecord + 64u + + static_cast(layer) * 32u + 3u) & 0x7f; + if (source != originalSources[static_cast(layer)]) + throw std::runtime_error("Changing Instrument 3 Source changed native Source for Instrument " + + std::to_string(layer + 1) + ": " + + std::to_string(originalSources[static_cast(layer)]) + + " -> " + std::to_string(source) + + " at fader " + std::to_string(position)); + require(processor->isPerformanceInstrumentActive(layer) + == (source != 0), + "Instrument Source engine state disagreed with native record"); + } + } + require(directory.deleteRecursively(), "Source test cleanup failed"); +} + +void testPerformanceMuteAndSolo() +{ + auto processor = makeFactoryProcessor(); + processor->setCurrentProgram(41); // A042: three active Instruments. + std::array active { -1, -1, -1 }; + auto activeCount = 0; + for (int instrument = 0; instrument < 8 && activeCount < 3; ++instrument) + if (processor->isPerformanceInstrumentActive(instrument)) + active[static_cast(activeCount++)] = instrument; + require(activeCount == 3, "A042 did not expose three Mute/Solo targets"); processor->togglePerformanceMuteMode(); require(processor->getInstrumentButtonMode() @@ -2322,7 +3270,7 @@ void testPerformanceMuteAndSolo() void testA013ComparatorAutoPan() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(12); // A013 -> 2.3 Sweep oo WMF. @@ -2349,7 +3297,7 @@ void testA013ComparatorAutoPan() void testFactoryVcaReleaseTail() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(0); // A001, release byte 47 in both layers. juce::AudioBuffer audio(2, 512); @@ -2390,7 +3338,7 @@ void testFactoryVcaReleaseTail() void testLegacyStartupStateReloadsExactFactoryPerformance() { - auto savedProcessor = std::make_unique(); + auto savedProcessor = makeFactoryProcessor(); savedProcessor->setCurrentProgram(0); // A001: one left and one right layer. auto* pan = savedProcessor->parameters.getParameter(wave::parameters::pan); require(pan != nullptr, "Factory pan parameter is unavailable"); @@ -2404,7 +3352,7 @@ void testLegacyStartupStateReloadsExactFactoryPerformance() if (const auto xml = legacyState.createXml()) juce::AudioProcessor::copyXmlToBinary(*xml, legacyBinary); - auto restored = std::make_unique(); + auto restored = makeFactoryProcessor(); restored->setStateInformation(legacyBinary.getData(), static_cast(legacyBinary.getSize())); const auto* restoredPan = restored->parameters.getRawParameterValue( @@ -2434,7 +3382,7 @@ void testLegacyStartupStateReloadsExactFactoryPerformance() void testFactoryMultimodeFilterLoading() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(4); // A005 -> WaveStrings, Dual filter. @@ -2475,7 +3423,7 @@ void testFactoryMultimodeFilterLoading() void testPanelEditButtonFirmwareRouting() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) @@ -2669,12 +3617,12 @@ void testArtworkControlsMatchCompleteWiringMap() == wave::panel::keyboardPanelLeds.size(), "The SVG and lower keyboard-panel LED table have different marker counts"); - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); const auto& runtime = processor->getMasterFirmwareRuntime(); for (const auto& control : wave::panel::visibleSwitches) { const auto target = wave::panel::physicalMatrixIndex(control); - processor->setPanelButton(target, true); + const auto accepted = processor->setPanelButton(target, true); const auto oneShot = control.diagnosticCode == 69 || control.diagnosticCode == 72 || control.diagnosticCode == 21 @@ -2700,13 +3648,16 @@ void testArtworkControlsMatchCompleteWiringMap() const auto serial = wave::panel::physicalMatrixIndex(observed); const auto requested = runtime.panelButtonRequestedDown(serial); require(serial == target - ? (oneShot || dualPurposeDisplayButton + ? (!accepted ? !requested + : oneShot || dualPurposeDisplayButton || discreteModeButton || discreteEditButton || control.diagnosticCode == 31 || control.diagnosticCode == 11 || requested) : !requested, - "A UI button asserted more than its one mapped matrix input"); + (std::string("A UI button's matrix state did not match its accepted routing: target ") + + std::to_string(target) + ", observed " + + std::to_string(serial)).c_str()); } processor->setPanelButton(target, false); require(!runtime.panelButtonRequestedDown(target), @@ -2733,7 +3684,7 @@ void testArtworkControlsMatchCompleteWiringMap() void testKnobModeSelectUsesFirmwarePanelPath() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) @@ -2835,7 +3786,7 @@ void testKnobModeSelectUsesFirmwarePanelPath() void testEditPageFadersDriveFirmwareValues() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) @@ -2941,7 +3892,7 @@ void testEditPageRefreshesAfterFirmwarePerformanceChange() { const auto makeProcessor = [] { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); return processor; }; @@ -3006,7 +3957,7 @@ void testEditPageRefreshesAfterFirmwarePerformanceChange() void testOscillatorOctaveButtonsDriveFirmwareSoundRecord() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) { @@ -3038,6 +3989,11 @@ void testOscillatorOctaveButtonsDriveFirmwareSoundRecord() processBlocks(48); const auto after = processor->getFirmwareOscillatorOctave( static_cast(oscillator)); + const auto savedOctave = static_cast( + processor->getMasterFirmwareRuntime().currentSoundRecordByte( + oscillator == 0 ? 0u : 12u)) / 16 - 2; + require(savedOctave == after, + "Oscillator octave changed audibly but was not written into the Sound for Store"); require(after != before, "An oscillator Octave switch did not change the genuine firmware sound record"); @@ -3058,11 +4014,312 @@ void testOscillatorOctaveButtonsDriveFirmwareSoundRecord() "An oscillator Octave bank illuminated more than one position"); } } + + const auto click = [&](int code) { + const auto button = wave::panel::matrixIndexForDiagnosticCode(code); + require(processor->setPanelButton(button, true), "Stored octave test rejected a panel input"); + processBlocks(8); + processor->setPanelButton(button, false); + processBlocks(64); + }; + click(0); + const auto expectedOctave = processor->getFirmwareOscillatorOctave(0); + click(57); // Store. + click(79); // Sound. + click(22); // Instrument 1. + require(processor->isFirmwareRequesterActive(), "Sound Store did not open for octave recall"); + click(70); + click(71); + // A host program change first loads the original SET's parameter mirror. + // Returning must recover the octave just stored in the native Sound bank. + for (int pass = 0; pass < 2; ++pass) + { + processor->setCurrentProgram(1); + processBlocks(128); + processor->setCurrentProgram(0); + processBlocks(128); + const auto recalledOctave = static_cast( + processor->getMasterFirmwareRuntime().currentSoundRecordByte(0)) / 16 - 2; + require(recalledOctave == expectedOctave, + "Changing Performance modified the octave in the stored Sound"); + require(processor->getFirmwareOscillatorOctave(0) == expectedOctave, + "Changing Performance and returning lost the stored oscillator octave"); + } +} + +void testSavedStateRestoresBanks(const juce::File& file) +{ + juce::ScopedJuceInitialiser_GUI initialiseJuce; + juce::MemoryBlock state; + require(file.loadFileAsData(state), "Could not read saved machine state"); + const auto xml = juce::AudioProcessor::getXmlFromBinary(state.getData(), static_cast(state.getSize())); + require(xml != nullptr, "Could not decode saved machine state"); + const auto tree = juce::ValueTree::fromXml(*xml); + const auto data = tree.getProperty("machineActiveSetData"); + const auto* bytes = data.getBinaryData(); + wave::presets::WaveFactorySet expected; + require(bytes != nullptr && expected.load(*bytes).validLayout, + "Saved native bank was rejected by the SET loader"); + juce::TemporaryFile preference(".txt"); + auto processor = makeFactoryProcessor(preference.getFile()); + processor->prepareToPlay(48000.0, 512); + processor->setStateInformation(state.getData(), static_cast(state.getSize())); + const auto& runtime = processor->getMasterFirmwareRuntime(); + const auto performances = expected.performanceBank(); + const auto sounds = expected.soundBank(); + for (size_t byte = 0; byte < performances.size(); ++byte) + require(runtime.sharedProgramByte(0x28000u + static_cast(byte)) == performances[byte], + "Saved state restored a different Performance bank"); + for (size_t byte = 0; byte < sounds.size(); ++byte) + require(runtime.sharedProgramByte(0x18000u + static_cast(byte)) == sounds[byte], + "Saved state restored a different Sound bank"); +} + +void testReopenRestoresAllStoredBanks() +{ + juce::ScopedJuceInitialiser_GUI initialiseJuce; + juce::TemporaryFile preference(".txt"); + auto processor = makeFactoryProcessor(preference.getFile()); + processor->prepareToPlay(48000.0, 512); + auto& runtime = const_cast( + processor->getMasterFirmwareRuntime()); + std::vector performances(256u * 512u); + std::vector sounds(256u * 256u); + for (size_t byte = 0; byte < performances.size(); ++byte) + performances[byte] = runtime.sharedProgramByte(0x28000u + static_cast(byte)); + for (size_t byte = 0; byte < sounds.size(); ++byte) + sounds[byte] = runtime.sharedProgramByte(0x18000u + static_cast(byte)); + // Model bank changes made by Store after the original SET was imported. + // Change every name so restoring only the selected record cannot pass. + for (size_t program = 0; program < 256u; ++program) + { + performances[program * 512u + 32u] = 'R'; + performances[program * 512u + 33u] = '0' + static_cast(program % 10u); + sounds[program * 256u + 240u] = 'S'; + sounds[program * 256u + 2u] = static_cast(program % 128u); + } + // Native Store can leave NUL terminators in a name. This is valid machine + // state and also occurs in SET files saved by the firmware. + performances[512u + 42u] = 0; + performances[512u + 43u] = 0; + require(runtime.installPerformanceBank(performances), "Could not prepare saved Performance bank"); + require(runtime.installSoundBank(sounds), "Could not prepare saved Sound bank"); + juce::MemoryBlock state; + processor->getStateInformation(state); + // Embedded firmware has no remembered directory. Exercise that restore + // path even on machines where a local firmware preference exists. + auto xml = juce::AudioProcessor::getXmlFromBinary(state.getData(), static_cast(state.getSize())); + require(xml != nullptr, "Could not decode bank state"); + auto tree = juce::ValueTree::fromXml(*xml); + tree.removeProperty("firmwareDirectory", nullptr); + juce::AudioProcessor::copyXmlToBinary(*tree.createXml(), state); + processor.reset(); + auto reopened = makeFactoryProcessor(preference.getFile()); + reopened->prepareToPlay(48000.0, 512); + reopened->setStateInformation(state.getData(), static_cast(state.getSize())); + const auto& restored = reopened->getMasterFirmwareRuntime(); + for (size_t byte = 0; byte < performances.size(); ++byte) + require(restored.sharedProgramByte(0x28000u + static_cast(byte)) == performances[byte], + "Reopening lost an unselected stored Performance"); + for (size_t byte = 0; byte < sounds.size(); ++byte) + require(restored.sharedProgramByte(0x18000u + static_cast(byte)) == sounds[byte], + "Reopening lost a stored Sound"); + juce::AudioBuffer audio(2, 512); + for (const auto program : { 1, 63, 128, 255 }) + { + reopened->setCurrentProgram(program); + for (int block = 0; block < 128; ++block) + { + audio.clear(); + juce::MidiBuffer midi; + reopened->processBlock(audio, midi); +#if JUCE_MAC + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0001, true); +#endif + } + require(restored.currentPerformanceId() == program, + "Reopened bank could not browse an unselected Performance"); + const auto offset = restored.currentPerformanceRecordOffset(); + require(offset.has_value() && restored.sharedProgramByte(*offset + 32u) == 'R', + "Browsing after reopening recalled a previous bank name"); + } +} + +void testWavetableSelectorSurvivesSoundStore(int selector = 17) +{ + juce::ScopedJuceInitialiser_GUI initialiseJuce; + auto processor = makeFactoryProcessor(); + processor->setCurrentProgram(29); // Sitar. + processor->prepareToPlay(48000.0, 512); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int count) { + for (int block = 0; block < count; ++block) { + audio.clear(); + juce::MidiBuffer none; + processor->processBlock(audio, none); +#if JUCE_MAC + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0001, true); +#endif + } + }; + const auto click = [&](int code) { + const auto button = wave::panel::matrixIndexForDiagnosticCode(code); + require(processor->setPanelButton(button, true), "Wavetable Store rejected a button"); + process(8); + processor->setPanelButton(button, false); + process(96); + }; + auto& runtime = const_cast( + processor->getMasterFirmwareRuntime()); + const auto renderedSelector = [](WaveEmulationAudioProcessor& target) { + juce::MemoryBlock state; + target.getStateInformation(state); + const auto xml = juce::AudioProcessor::getXmlFromBinary(state.getData(), + static_cast(state.getSize())); + require(xml != nullptr, "Wavetable Store state is missing"); + const auto tree = juce::ValueTree::fromXml(*xml); + const auto snapshot = tree.getProperty("machinePerformanceSnapshot"); + const auto* bytes = snapshot.getBinaryData(); + wave::dsp::WaldorfEngine::PerformanceSnapshot performance; + require(bytes != nullptr && bytes->getSize() == sizeof(performance), + "Wavetable Store DSP snapshot is missing"); + std::memcpy(&performance, bytes->getData(), sizeof(performance)); + return performance.layers[static_cast(performance.editableLayer)].sound.wavetableIndex; + }; + process(128); + if (selector >= 0) + { + processor->turnPanelEncoder(8, selector - static_cast(runtime.currentSoundRecordByte(25))); + process(128); + require(runtime.currentSoundRecordByte(25) == selector, + ("The native Data dial selected " + std::to_string(runtime.currentSoundRecordByte(25)) + + " instead of wavetable " + std::to_string(selector)).c_str()); + } + const auto editedSelector = renderedSelector(*processor); + require(editedSelector == (selector < 0 ? 95 : selector), + "The native wavetable selector did not reach audio playback"); + const auto performanceRecord = runtime.currentPerformanceRecordOffset(); + require(performanceRecord.has_value(), "The Sitar Performance record is missing"); + const auto soundId = static_cast( + runtime.sharedProgramByte(*performanceRecord + 64u) + | (runtime.sharedProgramByte(*performanceRecord + 65u) << 7u)); + click(57); + click(79); + click(22); + require(processor->isFirmwareRequesterActive(), "Wavetable Sound Store did not open"); + click(70); + click(71); + require(runtime.sharedProgramByte(0x18000u + soundId * 256u + 25u) == editedSelector, + "Sound Store saved a different wavetable from audio playback"); + processor->setCurrentProgram(0); + process(128); + processor->setCurrentProgram(29); + process(128); + require(runtime.currentSoundRecordByte(25) == editedSelector + && renderedSelector(*processor) == editedSelector, + "Sound Store/recall changed the audible wavetable selector"); + if (selector == -1 || selector == 17 || selector == 127) + { + juce::MemoryBlock state; + processor->getStateInformation(state); + auto reopened = makeFactoryProcessor(); + reopened->prepareToPlay(48000.0, 512); + reopened->setStateInformation(state.getData(), static_cast(state.getSize())); + for (int block = 0; block < 128; ++block) + { + audio.clear(); + juce::MidiBuffer none; + reopened->processBlock(audio, none); +#if JUCE_MAC + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.0001, true); +#endif + } + require(reopened->getMasterFirmwareRuntime().currentSoundRecordByte(25) == editedSelector + && renderedSelector(*reopened) == editedSelector, + "Project restore changed the stored wavetable selector"); + } +} + +void testStoredSoundParametersSurvivePerformanceRecall() +{ + auto processor = makeFactoryProcessor(); + processor->prepareToPlay(48000.0, 512); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int count) { + for (int block = 0; block < count; ++block) { + audio.clear(); + juce::MidiBuffer none; + processor->processBlock(audio, none); + } + }; + const auto click = [&](int code) { + const auto button = wave::panel::matrixIndexForDiagnosticCode(code); + processor->setPanelButton(button, true); + process(8); + processor->setPanelButton(button, false); + process(64); + }; + process(96); + click(22); + auto& runtime = const_cast( + processor->getMasterFirmwareRuntime()); + // Distinct edits to detune, wavetable, wave position, cutoff and wave envelope. + constexpr std::array, 5> edits {{ + { 2u, 73u }, { 25u, 17u }, { 26u, 31u }, { 79u, 19u }, { 135u, 57u } + }}; + for (const auto [offset, value] : edits) + require(runtime.writeCurrentSoundRecordByte(offset, value), "Could not edit Sound fixture"); + process(8); + click(57); + click(79); + click(22); + require(processor->isFirmwareRequesterActive(), "Sound Store requester is missing"); + click(70); + click(71); + for (const auto [offset, value] : edits) + require(runtime.sharedProgramByte(0x18100u + offset) == value, + "Sound Store did not persist the edited parameter"); + // Model two saved Performances referring to the same Sound, independently + // of Store's user-interface flow. Preserve the rest of the native bank. + std::vector bank(256u * 512u); + for (size_t byte = 0; byte < bank.size(); ++byte) + bank[byte] = runtime.sharedProgramByte(0x28000u + static_cast(byte)); + std::copy_n(bank.begin(), 512, bank.begin() + 512); + require(runtime.installPerformanceBank(bank), "Could not create shared-Sound Performance fixture"); + processor->setCurrentProgram(1); + process(128); + for (const auto [offset, value] : edits) + require(runtime.currentSoundRecordByte(offset) == value, + "A second Performance recalled outdated saved Sound parameters"); + require(processor->getCurrentPerformanceSnapshot().layers[0].sound.oscillatorDetuneCents[0] == 9.0f, + "A second Performance played the imported detune instead of the saved value"); + processor->setCurrentProgram(0); + process(128); + // A001 has two Instruments assigned to a002. Both must start from the + // newly stored Sound on recall, retaining independent edits thereafter. + const auto recalled = processor->getCurrentPerformanceSnapshot(); + for (const auto instrument : { 0u, 1u }) { + const auto& sound = recalled.layers[instrument].sound; + require(sound.oscillatorDetuneCents[0] == 9.0f + && sound.wavePosition == 31.0f + && sound.waveEnvelopeTimes[0] == 57.0f, + "An unselected layer's DSP retained the original SET parameters after recall"); + } + for (const auto code : { 22, 25, 22, 25 }) { + click(code); + for (const auto [offset, value] : edits) { + if (runtime.currentSoundRecordByte(offset) != value) + std::cerr << "Recalled parameter " << offset << " expected " << int(value) + << " got " << int(runtime.currentSoundRecordByte(offset)) << '\n'; + require(runtime.currentSoundRecordByte(offset) == value, + "Instrument selection restored an outdated Sound parameter after Performance recall"); + } + } } void testEditSectionKnobsDriveFirmwareValues() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) @@ -3133,7 +4390,7 @@ void testEditSectionKnobsDriveFirmwareValues() void testEndlessPanelDialDrivesFirmwareValue() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) @@ -3171,7 +4428,7 @@ void testEndlessPanelDialDrivesFirmwareValue() void testGlideEditPageDrivesNativeSoundAndDsp() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks) { @@ -3183,6 +4440,8 @@ void testGlideEditPageDrivesNativeSoundAndDsp() } }; const auto click = [&](int diagnosticCode) { + const auto glideBefore = processor->getMasterFirmwareRuntime() + .currentSoundRecordByte(238u) & 0x01u; const auto button = wave::panel::matrixIndexForDiagnosticCode(diagnosticCode); processor->setPanelButton(button, true); process(8); @@ -3192,6 +4451,15 @@ void testGlideEditPageDrivesNativeSoundAndDsp() ++block) process(1); process(8); + // LCD completion can precede retirement of the mode-button serial + // transaction. Glide waits for that transaction, so await its native + // acknowledgement rather than assuming a fixed host-block latency. + for (int block = 0; + diagnosticCode == 6 && block < 128 + && (processor->getMasterFirmwareRuntime() + .currentSoundRecordByte(238u) & 0x01u) == glideBefore; + ++block) + process(1); }; process(96); @@ -3199,6 +4467,10 @@ void testGlideEditPageDrivesNativeSoundAndDsp() click(11); // Glide Edit. auto& firmware = const_cast( processor->getMasterFirmwareRuntime()); + const std::array glideFaderOffsets { 233u, 235u, 236u, 237u }; + std::array beforeFaders {}; + for (size_t index = 0; index < beforeFaders.size(); ++index) + beforeFaders[index] = firmware.currentSoundRecordByte(glideFaderOffsets[index]); processor->setPanelFader(0, wave::panel::performanceFaderAdcChannels[0], 0.9f, false); processor->setPanelFader(1, wave::panel::performanceFaderAdcChannels[1], @@ -3207,6 +4479,9 @@ void testGlideEditPageDrivesNativeSoundAndDsp() 0.9f, false); processor->setPanelFader(5, wave::panel::performanceFaderAdcChannels[5], 0.9f, false); + for (size_t index = 0; index < beforeFaders.size(); ++index) + require(firmware.currentSoundRecordByte(glideFaderOffsets[index]) == beforeFaders[index], + "Glide faders mutated the Sound outside the audio-thread timeline"); process(64); require((firmware.currentSoundRecordByte(233) & 0x7fu) == 6 && (firmware.currentSoundRecordByte(235) & 0x7fu) == 1 @@ -3260,7 +4535,7 @@ void testGlideEditPageDrivesNativeSoundAndDsp() void testPhysicalGlideControlsWorkOutsideEditPage() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks) { @@ -3320,7 +4595,7 @@ void testPhysicalGlideControlsWorkOutsideEditPage() void testBriefGlideSwitchClicksSurviveFirmwareScan() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks) { @@ -3378,7 +4653,7 @@ void testBriefGlideSwitchClicksSurviveFirmwareScan() void testPlusTapAfterDataDialAdvancesOneStep() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) @@ -3450,7 +4725,18 @@ void testPlusTapAfterDataDialAdvancesOneStep() void testWaveLinkUsesFirmwareLatch() { - auto processor = std::make_unique(); + // Exercise a remembered firmware path as well as embedded factory boot; + // a redundant startup recall must not swallow the first Link click. + juce::TemporaryFile preference(".txt"); + const auto firmwareDirectory = juce::File(__FILE__).getParentDirectory() + .getParentDirectory() + .getChildFile("Firmware/wave_sys1_700"); + require(firmwareDirectory.getChildFile("w2sys.bin").existsAsFile() + && firmwareDirectory.getChildFile("wdv.sys").existsAsFile(), + "Remembered firmware regression fixture is missing"); + require(preference.getFile().replaceWithText(firmwareDirectory.getFullPathName()), + "Could not prepare remembered firmware preference"); + auto processor = makeFactoryProcessor(preference.getFile()); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks) { @@ -3485,7 +4771,7 @@ void testWaveLinkUsesFirmwareLatch() void testProgramStateDoesNotMasqueradeAsPanelMovement() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) { @@ -3513,7 +4799,7 @@ void testProgramStateDoesNotMasqueradeAsPanelMovement() void testHostStatePreservesRelativePanelPotPositions() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](WaveEmulationAudioProcessor& target, int blocks) { @@ -3542,7 +4828,7 @@ void testHostStatePreservesRelativePanelPotPositions() juce::MemoryBlock state; processor->getStateInformation(state); - auto restored = std::make_unique(); + auto restored = makeFactoryProcessor(); restored->setStateInformation(state.getData(), static_cast(state.getSize())); restored->prepareToPlay(48000.0, 512); process(*restored, 64); @@ -3590,7 +4876,7 @@ void testHostStatePreservesRelativePanelPotPositions() void testProgramRecallRejectsPreviousHostPanelEcho() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks) { @@ -3643,7 +4929,7 @@ void testProgramRecallRejectsPreviousHostPanelEcho() void testRecallInitModalAcceptsDisplaySoftKeys() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto processBlocks = [&](int count) @@ -3682,7 +4968,7 @@ void testRecallInitModalAcceptsDisplaySoftKeys() void testFirmwareModifierSelectorDrivesDsp() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks, juce::MidiBuffer* first = nullptr) @@ -3805,7 +5091,7 @@ void testFirmwareModifierSelectorDrivesDsp() void testEditedPerformanceFaderRoutingDrivesDsp() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(255); // MULTI INIT: only Instrument 1 is active. @@ -3947,7 +5233,7 @@ void testEditedPerformanceFaderRoutingDrivesDsp() void testB019FilterEnvelopeAudibility() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(146); // B019: Chung Bass FB. juce::AudioBuffer audio(2, 512); @@ -3976,7 +5262,7 @@ void testB019FilterEnvelopeAudibility() void testB004StereoLayerBalance() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(131); // B004: Vox Bells, left/right/centre layers. @@ -4007,7 +5293,7 @@ void testB004StereoLayerBalance() void testA004LocalKeyboardRouting() { - auto externalMidiProcessor = std::make_unique(); + auto externalMidiProcessor = makeFactoryProcessor(); externalMidiProcessor->prepareToPlay(48000.0, 512); externalMidiProcessor->setCurrentProgram(3); // A004: channels 1/2, hard left/right. juce::AudioBuffer externalAudio(2, 512); @@ -4017,7 +5303,7 @@ void testA004LocalKeyboardRouting() require(externalMidiProcessor->getActiveVoiceCount() == 1, "A004 external MIDI channel 1 did not retain its genuine single-Instrument routing"); - auto localKeyboardProcessor = std::make_unique(); + auto localKeyboardProcessor = makeFactoryProcessor(); localKeyboardProcessor->setMidiInputActsAsLocalKeyboard(true); localKeyboardProcessor->prepareToPlay(48000.0, 512); localKeyboardProcessor->setCurrentProgram(3); @@ -4046,7 +5332,7 @@ void testA004LocalKeyboardRouting() void testBriefPanelClicksSurviveFirmwareScan() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks) { @@ -4074,7 +5360,7 @@ void testBriefPanelClicksSurviveFirmwareScan() void testEditSectionLedsAreMutuallyExclusive() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks) { @@ -4121,7 +5407,7 @@ void testEditSectionLedsAreMutuallyExclusive() void testGroupEditUsesFirmwareSerialPageAndLed() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 128); juce::AudioBuffer audio(2, 128); const auto process = [&](int blocks) { @@ -4175,9 +5461,99 @@ void testGroupEditUsesFirmwareSerialPageAndLed() "Group Edit LED remained latched after leaving its page"); } +void testInstrumentModeRoundTripsKeepSelectionAndSolo() +{ + auto processor = makeFactoryProcessor(); + processor->prepareToPlay(48000.0, 512); + processor->setCurrentProgram(41); + juce::AudioBuffer audio(2, 512); + int expectedDuringTransition = -1; + const auto process = [&](int count) { + for (int block = 0; block < count; ++block) + { + audio.clear(); + juce::MidiBuffer none; + processor->processBlock(audio, none); + if (expectedDuringTransition >= 0) + require(processor->getSelectedPerformanceInstrument() == expectedDuringTransition, + "A mode transition temporarily selected a different Instrument"); + } + }; + const auto click = [&](int code) { + if (code == 36 || code == 39) + expectedDuringTransition = processor->getSelectedPerformanceInstrument(); + const auto matrix = wave::panel::matrixIndexForDiagnosticCode(code); + require(processor->setPanelButton(matrix, true), "Mode-cycle button rejected"); + process(8); + processor->setPanelButton(matrix, false); + process(96); + expectedDuringTransition = -1; + }; + process(128); + click(25); // Select Instrument 2. + require(processor->getSelectedPerformanceInstrument() == 1, + "Mode-cycle setup did not select Instrument 2"); + const auto& firmware = processor->getMasterFirmwareRuntime(); + std::array originalSound {}; + for (size_t byte = 0; byte < originalSound.size(); ++byte) + originalSound[byte] = firmware.currentSoundRecordByte(static_cast(byte)); + const auto baselineVoice = processor->probeCurrentLayerVoice(7, 1, 60, 0.8f, 24000, 42); + for (int round = 0; round < 3; ++round) + { + click(78); // Enter Solo in Performance. + require(processor->getPanelLed(59), "Solo LED did not light in Performance"); + click(25); // Solo Instrument 2. + click(36); + click(26); // Select Instrument 3 for editing while Solo remains active. + require(processor->getSelectedPerformanceInstrument() == 2 + && firmware.currentInstrumentEditTarget() == 2, + "Solo prevented Instrument Edit from selecting another layer"); + click(25); // Return to the original Sound before comparing its record. + click(78); // Leave Solo from Instrument Edit. + require(!processor->getPanelLed(59) + && processor->getInstrumentButtonMode() + == WaveEmulationAudioProcessor::InstrumentButtonMode::normal, + "Solo did not switch off after entering Instrument Edit"); + require(processor->getSelectedPerformanceInstrument() == 1 + && firmware.currentInstrumentEditTarget() == 1 + && processor->isPerformanceInstrumentActive(1), + "Mode cycling lost the selected active Instrument"); + click(39); + require(processor->getSelectedPerformanceInstrument() == 1 + && firmware.currentPerformanceInstrument() == 1, + "Returning to Performance lost the selected Instrument"); + for (size_t byte = 0; byte < originalSound.size(); ++byte) + require(firmware.currentSoundRecordByte(static_cast(byte)) + == originalSound[byte], + "Mode cycling changed the selected Sound record"); + const auto voice = processor->probeCurrentLayerVoice(7, 1, 60, 0.8f, 24000, 42); + require(std::abs(voice.rmsOutput - baselineVoice.rmsOutput) + <= std::max(1.0e-8, baselineVoice.rmsOutput * 1.0e-4) + && std::abs(voice.meanCutoffHz - baselineVoice.meanCutoffHz) + <= std::max(1.0e-5, baselineVoice.meanCutoffHz * 1.0e-5), + "Mode cycling changed the selected layer's rendered Sound"); + } + click(36); + bool sawOrange = false; + bool sawOff = false; + const auto deadline = juce::Time::getMillisecondCounterHiRes() + 900.0; + while (juce::Time::getMillisecondCounterHiRes() < deadline + && !(sawOrange && sawOff)) + { + process(1); + const auto green = processor->getPanelLed(98); + const auto red = processor->getPanelLed(99); + sawOrange = sawOrange || (green && red); + sawOff = sawOff || (!green && !red); + juce::Thread::sleep(1); + } + require(sawOrange && sawOff, + "Selected Instrument LED stopped flashing after mode cycling"); +} + void testSelectedInstrumentSoftkeyFlashesOrangeOff() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); processor->setCurrentProgram(41); // A042: multiple active Instruments. @@ -4202,7 +5578,7 @@ void testSelectedInstrumentSoftkeyFlashesOrangeOff() void testModeLcdRedrawIsOneDisplayTransaction() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 128); juce::AudioBuffer audio(2, 128); const auto processOne = [&] { @@ -4256,7 +5632,7 @@ void testModeLcdRedrawIsOneDisplayTransaction() void testSequencerKeyDoesNotTrapPerformanceMode() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks) { @@ -4289,9 +5665,645 @@ void testSequencerKeyDoesNotTrapPerformanceMode() "The reserved Sequencer key trapped subsequent Performance controls"); } +void testDiskLoadStepDoesNotRepeat() +{ + auto processor = makeFactoryProcessor(); + processor->prepareToPlay(48000.0, 512); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int blocks) { + for (int block = 0; block < blocks; ++block) { + audio.clear(); + juce::MidiBuffer none; + processor->processBlock(audio, none); + } + }; + const auto click = [&](int code) { + const auto button = wave::panel::matrixIndexForDiagnosticCode(code); + require(processor->setPanelButton(button, true), "Disk Load rejected a panel contact"); + process(8); + processor->setPanelButton(button, false); + process(8); + }; + process(64); + click(58); // Disk. + click(22); // Open the Load choices. + process(64); + const auto& runtime = processor->getMasterFirmwareRuntime(); + const auto initial = runtime.lcdVideoSnapshot(); + click(72); + process(64); + const auto advanced = runtime.lcdVideoSnapshot(); + require(advanced != initial, "Load + did not move the selection"); + process(500); + require(runtime.lcdVideoSnapshot() == advanced, + "Load selection kept scrolling after releasing +"); + click(69); + process(64); + require(runtime.lcdVideoSnapshot() == initial, + "Load +/- did not move by exactly one menu entry"); + process(500); + require(runtime.lcdVideoSnapshot() == initial, + "Load selection kept scrolling after releasing -"); +} + +void checkDgUserWavetables(const WaveEmulationAudioProcessor& processor) +{ + const auto bank = processor.getWavetableBank().renderSnapshot(); + std::vector factory; + for (int table = 0; table < 64; ++table) + for (int wave = 0; wave < 64; ++wave) + for (int sample = 0; sample < 128; ++sample) + factory.push_back(bank.rawSample(table, wave, sample)); + require(juce::SHA256(factory.data(), factory.size()).toHexString() + == "f77d1bc6f90e3a1605915f7b9b0004d26955692d5f99bd176ec5564cc91387cc", + "DG_PE import changed original hardware factory waves"); + require(processor.getWavetableBank().damagedUserTableCount() == 1, + "DG_PE's damaged user table was not identified"); + for (int table = 64; table < 128; ++table) + for (int wave = 0; wave < 64; ++wave) + for (int sample = 0; sample < 128; ++sample) + require(bank.rawSample(table, wave, sample) == bank.rawSample(64, wave, sample), + "DG_PE retained a previous disk's user wavetable"); + for (int sample = 0; sample < 128; ++sample) + require(bank.rawSample(64, 0, sample) == processor.getWavetableBank().rawRomWaveSample(0, sample) + && bank.rawSample(64, 60, sample) == processor.getWavetableBank().rawRomWaveSample(1, sample), + "DG_PE INIT user bank has the wrong ROM Wave anchors"); +} + +void checkImportedDiskPlaybackTuning(WaveEmulationAudioProcessor& processor, int programs) +{ + processor.prepareToPlay(48000.0, 512); + processor.setMidiInputActsAsLocalKeyboard(true); + juce::AudioBuffer audio(2, 512); + const auto settle = [&] { + for (int block = 0; block < 64; ++block) + { + juce::MidiBuffer midi; + processor.processBlock(audio, midi); +#if JUCE_MAC + if (block % 16 == 0) + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, false); +#endif + } + }; + int checked = 0; + for (int program = 0; program < programs; ++program) + { + processor.setCurrentProgram(program); + settle(); + for (const auto key : { 48, 60, 69, 72 }) + { + juce::MidiBuffer midi; + midi.addEvent(juce::MidiMessage::allSoundOff(1), 0); + midi.addEvent(juce::MidiMessage::noteOn(1, key, 0.8f), 1); + processor.processBlock(audio, midi); + const auto performance = processor.getCurrentPerformanceSnapshot(); + for (const auto& voice : processor.getVoiceStates()) + { + if (!voice.active || !voice.keyDown || voice.layer < 0) + continue; + const auto& layer = performance.layers[static_cast(voice.layer)]; + if (layer.tuningTable != 0) + continue; + const auto expected = static_cast(juce::jlimit( + 0, 127, voice.triggerNote + layer.transposeSemitones)); + if (std::abs(voice.glidePitch - expected) >= 1.0e-4f) + std::cerr << "Bad disk tuning: program=" << program + << " key=" << key << " pitch=" << voice.glidePitch + << " expected=" << expected << '\n'; + require(std::abs(voice.glidePitch - expected) < 1.0e-4f, + "A damaged disk tuning table remapped a played note"); + ++checked; + } + } + } + require(checked > 0, "Disk tuning check did not play any Global Instruments"); +} + +void testVisibleLcdAfterPerformanceStep(const juce::File& stateFile = {}) +{ + auto processor = makeFactoryProcessor(); + if (stateFile != juce::File{}) + { + juce::MemoryBlock state; + require(stateFile.loadFileAsData(state), "Could not read LCD browsing state"); + processor->setStateInformation(state.getData(), static_cast(state.getSize())); + } + processor->prepareToPlay(96000.0, 512); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int blocks) { + for (int block = 0; block < blocks; ++block) + { + juce::MidiBuffer midi; + processor->processBlock(audio, midi); + } + }; + const auto pollLcd = [] { + juce::Thread::sleep(20); + juce::Timer::callPendingTimersSynchronously(); + }; + processor->setCurrentProgram(43); + process(96); + wave::ui::WaveLcdComponent lcd(*processor); + lcd.setPanelEmbedded(true); + lcd.setSize(480, 64); + for (const auto mode : { 36, 39 }) + { + const auto button = wave::panel::matrixIndexForDiagnosticCode(mode); + processor->setPanelButton(button, true); + pollLcd(); // Observe the start of the genuine mode transition. + process(8); + processor->setPanelButton(button, false); + process(96); + require(!processor->isPanelModeDisplayTransitionActive(), + "LCD browsing fixture did not finish its mode transition"); + pollLcd(); // Commit the mode frame and arm its residual-redraw guard. + } + const auto& runtime = processor->getMasterFirmwareRuntime(); + const auto plus = wave::panel::matrixIndexForDiagnosticCode(72); + for (int program = 44; program <= 48; ++program) + { + processor->setPanelButton(plus, true); + process(1); + processor->setPanelButton(plus, false); + process(96); + require(runtime.currentPerformanceId() == program, + "LCD browsing fixture did not complete native recall"); + pollLcd(); + const auto image = lcd.createComponentSnapshot(lcd.getLocalBounds()); + const auto video = runtime.lcdVideoSnapshot(); + wave::ui::LcdFramebuffer expected; + expected.loadHardwareVideoRam(video.data(), video.size(), runtime.lcdDisplayPage()); + for (int y = 0; y < 64; ++y) + for (int x = 0; x < 480; ++x) + { + const auto pixel = image.getPixelAt(x, y); + const auto dark = pixel.getRed() < 40 && pixel.getGreen() < 100; + require(dark == expected.pixel(x, y), + "LCD redraw guard hid a completed +/- Performance recall"); + } + } + // A continuing controller gesture must not extend the residual redraw + // hold forever, even when the Performance number stays unchanged. + for (const auto mode : { 36, 39 }) + { + const auto button = wave::panel::matrixIndexForDiagnosticCode(mode); + processor->setPanelButton(button, true); + pollLcd(); + process(8); + processor->setPanelButton(button, false); + process(96); + pollLcd(); + } + const auto beforeGesture = runtime.lcdVideoSnapshot(); + int redrawFrames = 0; + for (int frame = 0; frame < 32; ++frame) + { + const auto writes = runtime.lcdVideoWriteCount(); + processor->setPanelFader(0, wave::panel::performanceFaderAdcChannels[0], + frame % 2 == 0 ? 0.2f : 0.8f); + process(32); + if (runtime.lcdVideoWriteCount() > writes) + ++redrawFrames; + pollLcd(); + } + require(redrawFrames >= 8, "Continuous LCD fixture did not sustain firmware redraws"); + const auto video = runtime.lcdVideoSnapshot(); + require(video != beforeGesture, "Continuous LCD fixture did not change visible firmware data"); + const auto image = lcd.createComponentSnapshot(lcd.getLocalBounds()); + wave::ui::LcdFramebuffer expected; + expected.loadHardwareVideoRam(video.data(), video.size(), runtime.lcdDisplayPage()); + for (int y = 0; y < 64; ++y) + for (int x = 0; x < 480; ++x) + { + const auto pixel = image.getPixelAt(x, y); + const auto dark = pixel.getRed() < 40 && pixel.getGreen() < 100; + require(dark == expected.pixel(x, y), + "Continuous firmware redraws kept the visible LCD frozen"); + } + +} + +void testSavedDiskBrowsing(const juce::File& stateFile) +{ + juce::MemoryBlock state; + require(stateFile.loadFileAsData(state), "Could not read saved browsing state"); + juce::TemporaryFile preference(".txt"); + auto processor = makeFactoryProcessor(preference.getFile()); + processor->setStateInformation(state.getData(), static_cast(state.getSize())); + processor->prepareToPlay(96000.0, 512); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int blocks) { + for (int block = 0; block < blocks; ++block) + { + juce::MidiBuffer midi; + processor->processBlock(audio, midi); +#if JUCE_MAC + if (block % 16 == 0) + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, false); +#endif + } + }; + const auto& runtime = processor->getMasterFirmwareRuntime(); + const auto plus = wave::panel::matrixIndexForDiagnosticCode(72); + const auto minus = wave::panel::matrixIndexForDiagnosticCode(69); + processor->setCurrentProgram(0); + process(96); + for (int program = 1; program < 128; ++program) + { + const auto before = runtime.lcdVideoSnapshot(); + processor->setPanelButton(plus, true); + process(1); + processor->setPanelButton(plus, false); + process(32); + if (runtime.currentPerformanceId() != program || runtime.lcdVideoSnapshot() == before) + std::cerr << "Saved disk browse froze at A" << program + 1 + << " native=" << runtime.currentPerformanceId().value_or(-1) + << " pc=" << std::hex << runtime.programCounter() << std::dec << '\n'; + require(runtime.currentPerformanceId() == program && runtime.lcdVideoSnapshot() != before, + "Saved disk +/- browsing froze the LCD"); + } + for (int program = 126; program >= 0; --program) + { + const auto before = runtime.lcdVideoSnapshot(); + processor->setPanelButton(minus, true); + process(1); + processor->setPanelButton(minus, false); + process(32); + require(runtime.currentPerformanceId() == program && runtime.lcdVideoSnapshot() != before, + "Saved disk reverse browsing froze the LCD"); + } +} + +void testWtbImageConversion(const juce::File& wtb) +{ + juce::TemporaryFile preference(".txt"); + juce::TemporaryFile image(".img"); + auto processor = makeFactoryProcessor(preference.getFile()); + const auto program = processor->getProgramName(0); + juce::MemoryBlock original; + require(wtb.loadFileAsData(original) + && processor->createDiskImageFromWavetable(wtb, image.getFile()).wasOk() + && processor->getMountedDiskImageFile() == image.getFile(), + "WTB conversion did not create and mount a disk image"); + juce::MemoryBlock disk; + require(image.getFile().loadFileAsData(disk) && disk.getSize() == 720u * 1024u, + "WTB conversion did not produce a DD floppy"); + const auto* bytes = static_cast(disk.getData()); + require(bytes[3592] == 'W' && bytes[3593] == 'T' && bytes[3594] == 'B' + && original == juce::MemoryBlock(bytes + 7168, original.getSize()) + && processor->getProgramName(0) == program, + "WTB image lost its native extension, data, or the current Performance bank"); + juce::MemoryBlock after; + require(wtb.loadFileAsData(after) && after == original, "WTB conversion changed the source file"); +} + +void testImportedDiskLcd(const juce::File& source, bool nativeDiskLoad, + bool loadMachineSpecific = false, bool checkDg = false) +{ + juce::TemporaryFile copy(".img"); + require(source.copyFileTo(copy.getFile()), "Could not copy LCD regression disk"); + auto processor = makeFactoryProcessor(); + processor->prepareToPlay(48000.0, 512); + wave::ui::WaveLcdComponent lcd(*processor); + lcd.setPanelEmbedded(true); + lcd.setSize(480, 64); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int blocks) { + for (int block = 0; block < blocks; ++block) + { + audio.clear(); + juce::MidiBuffer midi; + processor->processBlock(audio, midi); +#if JUCE_MAC + if (block % 16 == 0) + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, false); +#endif + } +#if JUCE_MAC + CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, false); +#endif + }; + const auto& runtime = processor->getMasterFirmwareRuntime(); + const auto verifyDisplay = [&] { + for (int tick = 0; tick < 25; ++tick) + { + process(2); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + juce::Timer::callPendingTimersSynchronously(); + } + const auto image = lcd.createComponentSnapshot(lcd.getLocalBounds()); + const auto video = runtime.lcdVideoSnapshot(); + wave::ui::LcdFramebuffer expected; + expected.loadHardwareVideoRam(video.data(), video.size(), runtime.lcdDisplayPage()); + for (int y = 0; y < 64; ++y) + for (int x = 0; x < 480; ++x) + { + const auto pixel = image.getPixelAt(x, y); + const auto dark = pixel.getRed() < 40 && pixel.getGreen() < 100; + require(dark == expected.pixel(x, y), + "Imported disk left the visible LCD displaying an obsolete frame"); + } + }; + const auto diagnostic = [&](const char* where) { + if (std::getenv("WAVE_TEST_VERBOSE") == nullptr) + return; + uint32_t callback = 0; + for (uint32_t i = 0; i < 4; ++i) + callback = (callback << 8u) | runtime.localByte(0x56bb0u + i); + uint64_t hash = 1469598103934665603ull; + for (const auto byte : runtime.lcdVideoSnapshot()) + hash = (hash ^ byte) * 1099511628211ull; + std::cerr << where << " program=" << processor->getCurrentProgram() + << " name=" << processor->getProgramName(processor->getCurrentProgram()) + << " native=" << runtime.currentPerformanceId().value_or(-1) + << " raw=" << ((runtime.localByte(0x54b40u) << 8u) | runtime.localByte(0x54b41u)) + << " mode=" << processor->getPanelSelectedMode() + << " requester=" << processor->isFirmwareRequesterActive() + << " transition=" << processor->isPanelModeDisplayTransitionActive() + << " pc=" << std::hex << runtime.programCounter() + << " callback=" << callback << " lcd=" << hash << std::dec + << " writes=" << runtime.lcdVideoWriteCount() + << " diskread=" << runtime.mountedDiskBytesRead() + << " response=" << std::hex; + for (const auto address : { 0x56728u, 0x56738u }) + { + uint32_t response = 0; + for (uint32_t i = 0; i < 4; ++i) + response = (response << 8u) | runtime.localByte(address + i); + std::cerr << response << ','; + } + std::cerr << std::dec << '\n'; + }; + const auto click = [&](int code) { + const auto button = wave::panel::matrixIndexForDiagnosticCode(code); + const auto accepted = processor->setPanelButton(button, true); + process(8); + processor->setPanelButton(button, false); + process(96); + require(accepted, "Imported disk rejected a mode or disk contact"); + diagnostic("click"); + }; + process(64); + diagnostic("boot"); + require(processor->mountDiskImage(copy.getFile()).wasOk(), "Could not mount LCD regression disk"); + wave::firmware::DosFloppyImage::SetupFile setup; + wave::presets::WaveFactorySet diskSet; + require(wave::firmware::DosFloppyImage::readWaveSetup(copy.getFile(), setup).wasOk() + && diskSet.load(setup.data).validLayout + && processor->getProgramName(0) == juce::String(diskSet.performanceName(0, 0)), + "Imported SET was rejected while the firmware loaded a different bank"); + process(64); + diagnostic("mounted"); + if (checkDg) + checkDgUserWavetables(*processor); + if (nativeDiskLoad) + { + click(58); + click(22); + for (int choice = 0; choice < 12; ++choice) + click(72); + click(70); + click(70); + click(70); + process(4000); + diagnostic("loaded"); + click(loadMachineSpecific ? 70 : 71); + process(4000); + diagnostic("calibration skipped"); + require(runtime.mountedDiskBytesRead() >= 350000u, + "Native Total Recall did not transfer the SET"); + require(processor->getPanelSelectedMode() == 39 + && !processor->isPanelModeDisplayTransitionActive(), + "Total Recall did not retire the Disk workspace and LCD transition"); + verifyDisplay(); + if (checkDg) + checkDgUserWavetables(*processor); + } + else + { + click(34); + click(70); + } + for (const auto program : { 0, 1, 2, 43, 44, 45, 44, 151, 127, 128, 255, 0 }) + { + const auto before = runtime.lcdVideoSnapshot(); + processor->setCurrentProgram(program); + process(96); + diagnostic("selected"); + require(runtime.currentPerformanceId() == program, + "Imported disk Performance recall did not complete"); + const auto record = runtime.currentPerformanceRecordOffset(); + require(record.has_value(), "Imported disk has no selected native record"); + const auto expectedPerformance = diskSet.performance(program / 128, program % 128); + for (uint32_t character = 0; character < 16; ++character) + require(runtime.sharedProgramByte(*record + 32u + character) + == expectedPerformance[32u + character], + "Imported disk retained the previous bank's native Performance name"); + if (program != 0) + require(runtime.lcdVideoSnapshot() != before, + "Imported disk froze the LCD during Performance recall"); + verifyDisplay(); + if (expectedPerformance[48] == 0) + for (int instrument = 0; instrument < 8; ++instrument) + require(!processor->isPerformanceInstrumentActive(instrument), + "An empty imported slot retained a preceding Instrument"); + } + for (const auto mode : { 36, 33, 39, 37, 39 }) + { + const auto before = runtime.lcdVideoSnapshot(); + click(mode); + require(runtime.lcdVideoSnapshot() != before, + "Imported disk froze the LCD during a mode change"); + verifyDisplay(); + } + if (checkDg) + { + processor->prepareToPlay(96000.0, 512); + processor->setCurrentProgram(0); + process(96); + const auto plus = wave::panel::matrixIndexForDiagnosticCode(72); + const auto minus = wave::panel::matrixIndexForDiagnosticCode(69); + for (int program = 1; program <= 52; ++program) + { + const auto before = runtime.lcdVideoSnapshot(); + require(processor->setPanelButton(plus, true), "DG_PE browsing rejected +"); + process(1); + processor->setPanelButton(plus, false); + process(32); + diagnostic("browsed"); + require(processor->getCurrentProgram() == program + && runtime.currentPerformanceId() == program + && runtime.lcdVideoSnapshot() != before, + "DG_PE +/- browsing froze the LCD"); + } + for (const auto blocks : { 0, 1, 2, 4, 8, 16 }) + { + processor->setCurrentProgram(40); + process(96); + for (int step = 0; step < 4; ++step) + { + processor->setPanelButton(plus, true); + process(blocks); + processor->setPanelButton(plus, false); + process(blocks); + } + process(96); + diagnostic("rapid browse"); + require(processor->getCurrentProgram() == 44 + && runtime.currentPerformanceId() == 44, + "Rapid DG_PE +/- browsing stranded firmware recall"); + const auto before = runtime.lcdVideoSnapshot(); + processor->setPanelButton(minus, true); + process(1); + processor->setPanelButton(minus, false); + process(96); + require(runtime.currentPerformanceId() == 43 + && runtime.lcdVideoSnapshot() != before, + "DG_PE LCD did not recover after rapid browsing"); + } + checkImportedDiskPlaybackTuning(*processor, 256); + processor->setCurrentProgram(0); + process(96); + juce::MemoryBlock state; + processor->getStateInformation(state); + juce::TemporaryFile preference(".txt"); + auto restored = makeFactoryProcessor(preference.getFile()); + restored->setStateInformation(state.getData(), static_cast(state.getSize())); + checkDgUserWavetables(*restored); + checkImportedDiskPlaybackTuning(*restored, 3); + require(restored->reloadBankFromMountedImage().wasOk(), "DG_PE reload after DAW recall failed"); + checkDgUserWavetables(*restored); + } +} + +void testPartiallyDamagedDiskLcd() +{ + const auto* path = std::getenv("WAVE_FACTORY_SET"); + require(path != nullptr, "Damaged-bank LCD test needs the factory SET fixture"); + juce::MemoryBlock setup; + require(juce::File(juce::String::fromUTF8(path)).loadFileAsData(setup), + "Could not load the damaged-bank SET fixture"); + constexpr size_t damagedOffset = 0x22e7cu + 151u * 512u; + require(setup.getSize() >= damagedOffset + 512u, "Damaged-bank fixture is too short"); + auto* record = static_cast(setup.getData()) + damagedOffset; + std::fill_n(record, 512, uint8_t{ 0xff }); + record[48] = 0x55; + juce::TemporaryFile setFile(".set"), disk(".img"); + require(setFile.getFile().replaceWithData(setup.getData(), setup.getSize()) + && wave::firmware::DosFloppyImage::createWithWaveSetup( + disk.getFile(), setFile.getFile()).wasOk(), + "Could not create the damaged-bank disk fixture"); + testImportedDiskLcd(disk.getFile(), true); + testImportedDiskLcd(disk.getFile(), true, true); +} + +void testDamagedUserWavetableDisk() +{ + const auto* path = std::getenv("WAVE_FACTORY_SET"); + juce::MemoryBlock setup; + require(path != nullptr && juce::File(juce::String::fromUTF8(path)).loadFileAsData(setup), + "Could not read the user-wavetable disk fixture"); + auto* bytes = static_cast(setup.getData()); + for (size_t table = 0; table < 64; ++table) + { + auto* record = bytes + 0x4387c + table * 138; + std::copy_n(reinterpret_cast("INIT WTBL"), 9, record); + record[9] = 0x55; + std::fill_n(record + 10, 128, uint8_t{ 0xff }); + record[10] = record[11] = record[130] = 0; + record[131] = 1; + } + // Reproduce DG_PE's displaced Performance overwriting user table 93. + auto* damaged = bytes + 0x4387c + 28u * 138u; + std::copy_n(bytes + 0x22e7c, 138, damaged); + damaged[9] = 0x55; + damaged[10] = 0x4c; + damaged[11] = 0x54; + std::copy_n(bytes + 0x22e7c, 512, bytes + 0x42e7c); + std::copy_n(bytes + 0x22e7c, 512, bytes + 0x4307c); + juce::TemporaryFile setFile(".SET"); + juce::TemporaryFile image(".img"); + require(setFile.getFile().replaceWithData(setup.getData(), setup.getSize()) + && wave::firmware::DosFloppyImage::createWithWaveSetup( + image.getFile(), setFile.getFile()).wasOk(), + "Could not create the damaged user-wavetable disk"); + testImportedDiskLcd(image.getFile(), true, false, true); +} + +void testDiskFormatNameCursor() +{ + auto processor = makeFactoryProcessor(); + processor->prepareToPlay(48000.0, 512); + const juce::TemporaryFile temporaryDisk(".img"); + const auto disk = temporaryDisk.getFile(); + require(wave::firmware::DosFloppyImage::createEmpty(disk).wasOk(), "Test disk creation failed"); + juce::MemoryBlock beforeFormat; + require(disk.loadFileAsData(beforeFormat), "Could not read format test image"); + // A format must erase this unused final sector without a host Save action. + std::fill_n(static_cast(beforeFormat.getData()) + + beforeFormat.getSize() - 512u, + 512, static_cast(0x6b)); + require(disk.replaceWithData(beforeFormat.getData(), beforeFormat.getSize()), + "Could not prepare format test image"); + require(processor->mountDiskImage(disk).wasOk(), "Test disk mount failed"); + juce::AudioBuffer audio(2, 512); + const auto process = [&](int blocks) { + for (int block = 0; block < blocks; ++block) { + audio.clear(); + juce::MidiBuffer none; + processor->processBlock(audio, none); + } + }; + const auto click = [&](int code) { + const auto button = wave::panel::matrixIndexForDiagnosticCode(code); + require(processor->setPanelButton(button, true), "Disk naming rejected a panel contact"); + process(8); + processor->setPanelButton(button, false); + process(64); + }; + process(64); + click(58); // Disk. + click(79); // Format. + click(70); // Choose the format operation. + click(70); // Confirm the test medium to reach its name editor. + process(3000); // Let the emulated floppy finish formatting the temporary medium. + const auto& runtime = processor->getMasterFirmwareRuntime(); + require(processor->isFirmwareRequesterActive(), "Format name requester did not open"); + const auto formatted = runtime.mountedDiskImageSnapshot(); + require(formatted != beforeFormat, "Native disk format did not change the image"); + const auto saveDeadline = std::chrono::steady_clock::now() + std::chrono::seconds(4); + while (runtime.mountedDiskImageIsDirty() + && std::chrono::steady_clock::now() < saveDeadline) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + juce::MemoryBlock savedFormat; + require(!runtime.mountedDiskImageIsDirty() + && disk.loadFileAsData(savedFormat) && savedFormat == formatted, + "Native Disk-page format did not automatically overwrite the mounted image"); + const auto cursor = runtime.localByte(0x5705fu); + const auto character = runtime.localByte(0x56f30u + cursor); + for (int step = 0; step < 8 && runtime.localByte(0x56f30u + cursor) == character; ++step) + { + processor->turnPanelEncoder(8, 1); + process(48); + } + require(runtime.localByte(0x56f30u + cursor) != character, + "Data dial did not edit the selected disk-name character"); + // The DOS editor skips padding on Right; enter a character first so + // this checks movement by one actual name position. + click(23); + require(runtime.localByte(0x5705fu) == cursor + 1, + "Disk name Page Right did not advance the firmware cursor"); + click(21); + require(runtime.localByte(0x5705fu) == cursor, + "Disk name Page Left did not restore the firmware cursor"); + click(71); // Cancel naming the temporary medium. + processor.reset(); +} + void testDiskCancelReturnsPerformanceModeLed() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks) { @@ -4331,7 +6343,7 @@ void testDiskCancelReturnsPerformanceModeLed() void testExclusiveModesRejectOtherModeLeds() { - auto processor = std::make_unique(); + auto processor = makeFactoryProcessor(); processor->prepareToPlay(48000.0, 512); juce::AudioBuffer audio(2, 512); const auto process = [&](int blocks) { @@ -4359,8 +6371,8 @@ void testExclusiveModesRejectOtherModeLeds() constexpr std::array modeLeds { 64, 69, 21, 74, 26, 10, 22, 51, 52, 87 }; - constexpr std::array exclusiveModes { 34, 32, 58, 57 }; - constexpr std::array exclusiveLeds { 74, 26, 52, 87 }; + constexpr std::array exclusiveModes { 34, 32, 58 }; + constexpr std::array exclusiveLeds { 74, 26, 52 }; for (size_t exclusive = 0; exclusive < exclusiveModes.size(); ++exclusive) { require(click(exclusiveModes[exclusive]), @@ -4384,16 +6396,262 @@ void testExclusiveModesRejectOtherModeLeds() require(processor->getPanelSelectedMode() == 39 && processor->getPanelLed(51) && !processor->getPanelLed(exclusiveLeds[exclusive]), - "Exclusive mode Cancel did not restore Performance mode"); + (std::string("Exclusive mode Cancel did not restore Performance mode: from ") + + std::to_string(exclusiveModes[exclusive]) + " to " + + std::to_string(processor->getPanelSelectedMode()) + ", old LED " + + std::to_string(processor->getPanelLed(exclusiveLeds[exclusive]))).c_str()); } } } // namespace -int main() +int main(int argc, char** argv) { try { + if (argc > 1 && std::string_view(argv[1]) == "--glide") + { + testGlideEditPageDrivesNativeSoundAndDsp(); + std::cout << "Glide page controls passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--wiring") + { + testArtworkControlsMatchCompleteWiringMap(); + std::cout << "Artwork control wiring passed\n"; + return 0; + } + if (argc >= 3 && std::string_view(argv[1]) == "--check-wtb-image") + { + testWtbImageConversion(juce::File(juce::String::fromUTF8(argv[2]))); + std::cout << "WTB disk image conversion and mount passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--wtb-image") + { + juce::TemporaryFile wtb(".WTB"); + std::vector bytes(138u + 61u * 64u, 128); + std::fill_n(bytes.begin() + 10, 128, 0xff); + bytes[9] = 0x55; + require(wtb.getFile().replaceWithData(bytes.data(), bytes.size()), "Could not create WTB fixture"); + testWtbImageConversion(wtb.getFile()); + std::cout << "WTB disk image conversion and mount passed\n"; + return 0; + } + if (argc >= 3 && std::string_view(argv[1]) == "--check-dg-wavetables") + { + juce::ScopedJuceInitialiser_GUI initialiseGui; + testImportedDiskLcd(juce::File(juce::String::fromUTF8(argv[2])), true, false, true); + std::cout << "DG_PE factory/user wavetables, native Total Recall and DAW recall passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--damaged-user-wavetables") + { + juce::ScopedJuceInitialiser_GUI initialiseGui; + testDamagedUserWavetableDisk(); + std::cout << "Damaged user wavetable disk, native Total Recall and DAW recall passed\n"; + return 0; + } + if (argc >= 3 && std::string_view(argv[1]) == "--check-disk-lcd") + { + juce::ScopedJuceInitialiser_GUI initialiseGui; + testImportedDiskLcd(juce::File(juce::String::fromUTF8(argv[2])), argc > 3, + argc > 3 && std::string_view(argv[3]) == "native-machine"); + std::cout << "Imported disk LCD regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--damaged-disk-lcd") + { + juce::ScopedJuceInitialiser_GUI initialiseGui; + testPartiallyDamagedDiskLcd(); + std::cout << "Damaged SET Total Recall and visible LCD passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--disk-write-through") + { + testDiskFormatNameCursor(); + std::cout << "Automatic disk write regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--voice-allocation") + { + testInstrumentAllocationPageDrivesAudioAndRecall(); + std::cout << "Instrument allocation page, audio and recall passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--lcd-browsing") + { + testVisibleLcdAfterPerformanceStep(argc > 2 + ? juce::File(juce::String::fromUTF8(argv[2])) : juce::File{}); + std::cout << "Visible LCD Performance browsing passed\n"; + return 0; + } + if (argc > 2 && std::string_view(argv[1]) == "--check-browsing-state") + { + testSavedDiskBrowsing(juce::File(juce::String::fromUTF8(argv[2]))); + std::cout << "Saved disk sequential browsing passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--factory-wavetables") + { + testOriginalFactoryWavetablesAndRecall(); + testA030UsesItsSetUserWavetable(); + std::cout << "Original factory wavetable startup and recall passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--links") + { + testWaveLinkUsesFirmwareLatch(); + std::cout << "Link button regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--performance-overwrite") + { + testPerformanceOverwriteClearsInactiveSlots(16); + testPerformanceOverwriteClearsInactiveSlots(512); + std::cout << "Performance overwrite regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--reopen-banks") + { + testReopenRestoresAllStoredBanks(); + std::cout << "Reopened stored banks regression passed\n"; + return 0; + } + if (argc == 3 && std::string_view(argv[1]) == "--check-reopen-state") + { + testSavedStateRestoresBanks(juce::File(argv[2])); + std::cout << "Saved machine bank restore passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--store-mode-exit") + { + testStoreModeButtonExitAfterSave(); + testStoreModeButtonExitAfterSave(false, 36); + testStoreModeButtonExitAfterSave(false, 33); + testStoreModeButtonExitAfterSave(true); + testStoreModeButtonExitAfterSave(true, 36); + testStoreModeButtonExitAfterSave(true, 33); + testRepeatedSoundStoreCursor(); + std::cout << "Store mode exit regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--instrument-selection") + { + testPerformanceInstrumentSelection(); + std::cout << "Instrument selection regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--stored-octave") + { + testStoredSoundParametersSurvivePerformanceRecall(); + testSelectedInstrumentSoundRecordOverridesOldPanelSnapshot(); + testOutgoingInstrumentIsSavedFromFirmwareNotPanelMirror(); + testFactoryStereoInstrumentSelectionDoesNotChangeSound(); + testProgramRecallRejectsPreviousHostPanelEcho(); + testOscillatorOctaveButtonsDriveFirmwareSoundRecord(); + testInstrumentButtonsDoNotRewriteLayerOctaves(); + testA001DuplicateSoundAssignmentsHavePrivateInstrumentEdits(); + std::cout << "Stored Sound parameter regressions passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--wavetable-recall") + { + for (const auto selector : { -1, 0, 17, 18, 63, 64, 95, 127 }) + testWavetableSelectorSurvivesSoundStore(selector); + std::cout << "Stored wavetable selector regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--keyboard-controls") + { + testKeyboardControllerShiftReachesFirmware(); + testKeyboardOctaveButtonsDriveLocalKeyboardRange(); + testPluginMidiFollowsKeyboardOctaveButtons(); + testShiftDisplaySevenOpensFirmwareServiceMenu(); + std::cout << "Keyboard octave and Shift checks passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--keyboard-buttons") + { + testAssignableButtonMidiRouting(); + testLowerKeyboardAssignableButtonsDriveFirmware(); + std::cout << "Keyboard buttons regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--performance-store-name") + { + for (const auto samples : { 16, 512 }) + testPerformanceStoreNameAcrossBanks(samples, 0); + std::cout << "Performance Store name regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--disk-step") + { + testDiskLoadStepDoesNotRepeat(); + std::cout << "Disk Load step regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--disk-name") + { + testDiskFormatNameCursor(); + std::cout << "Disk naming regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--program-names") + { + testPerformanceBrowserHasDistinctStoredRecords(); + std::cout << "Performance browser names regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--mode-selection") + { + testInstrumentModeRoundTripsKeepSelectionAndSolo(); + testInstrumentEditLayerSelection(); + testPerformanceMuteAndSolo(); + testSelectedInstrumentSoftkeyFlashesOrangeOff(); + std::cout << "Mode selection regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--exclusive-modes") + { + testExclusiveModesRejectOtherModeLeds(); + std::cout << "Exclusive mode regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--disk-total-recall") + { + if (juce::SystemStats::getEnvironmentVariable("WAVE_TEST_DISK_IMAGE", {}).isEmpty()) + testDiskSetSerialSelectionUpdatesDsp(false); + testDiskSetSerialSelectionUpdatesDsp(false, true); + testDiskSetSerialSelectionUpdatesDsp(false, true, true); + testDiskSetSerialSelectionUpdatesDsp(false, true, false, false); + testDiskSetSerialSelectionUpdatesDsp(false, true, true, false); + std::cout << "Disk Total Recall regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--performance-selection") + { + testRapidPerformanceLcdRefreshIsAtomic(); + testFirmwarePerformanceStepButtonsRefreshLcd(); + testSamePerformanceReselectionLeavesModalScreen(); + std::cout << "Performance selection regressions passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--instrument-source") + { + testInstrumentSourceKeepsOtherLayers(); + testInstrumentEditLayerSelection(); + std::cout << "Instrument Source regression passed\n"; + return 0; + } + if (argc > 1 && std::string_view(argv[1]) == "--store-name") + { + testRepeatedSoundStoreCursor(); + testStoreRequesterStepButtonsChooseDestination(); + testStoreCancelRestoresNumericPerformancePreview(); + std::cout << "Store Page-key routing regression passed\n"; + return 0; + } testAutomaticBootAudioAndState(); testFactoryA092ChoirVibratoUsesCallerScale(); testFactoryB057UsesMeasuredVcaAttackOne(); @@ -4402,13 +6660,26 @@ int main() testLegacyStartupStateReloadsExactFactoryPerformance(); testFactoryVcaReleaseTail(); testFactoryPerformanceLayering(); + testPerformanceBrowserHasDistinctStoredRecords(); testRapidPerformanceLcdRefreshIsAtomic(); testFirmwarePerformanceStepButtonsRefreshLcd(); testStoreButtonReachesFirmwareMenu(); testStoreRequesterStepButtonsChooseDestination(); + testPerformanceStoreNameAcrossBanks(16, 0); + testPerformanceStoreNameAcrossBanks(512, 0); + testPerformanceOverwriteClearsInactiveSlots(16); + testPerformanceOverwriteClearsInactiveSlots(512); + testStoreModeButtonExitAfterSave(); + testStoreModeButtonExitAfterSave(false, 36); + testStoreModeButtonExitAfterSave(false, 33); + testStoreModeButtonExitAfterSave(true); + testStoreModeButtonExitAfterSave(true, 36); + testStoreModeButtonExitAfterSave(true, 33); + testRepeatedSoundStoreCursor(); testStoreCancelRestoresNumericPerformancePreview(); testKeyboardControllerShiftReachesFirmware(); testLowerKeyboardAssignableButtonsDriveFirmware(); + testAssignableButtonMidiRouting(); testGlideEditUsesFirmwareLamp(); testKeyboardOctaveButtonsDriveLocalKeyboardRange(); testPluginMidiFollowsKeyboardOctaveButtons(); @@ -4424,9 +6695,13 @@ int main() testSelectedInstrumentSoundRecordOverridesOldPanelSnapshot(); testOutgoingInstrumentIsSavedFromFirmwareNotPanelMirror(); testFactoryStereoInstrumentSelectionDoesNotChangeSound(); + testStoredSoundParametersSurvivePerformanceRecall(); + for (const auto selector : { -1, 0, 17, 18, 63, 64, 95, 127 }) + testWavetableSelectorSurvivesSoundStore(selector); testA001DuplicateSoundAssignmentsHavePrivateInstrumentEdits(); testInstrumentButtonsDoNotRewriteLayerOctaves(); testInstrumentEditLayerSelection(); + testInstrumentSourceKeepsOtherLayers(); testPerformanceMuteAndSolo(); testA013ComparatorAutoPan(); testFactoryMultimodeFilterLoading(); @@ -4456,8 +6731,11 @@ int main() testEditSectionLedsAreMutuallyExclusive(); testGroupEditUsesFirmwareSerialPageAndLed(); testSelectedInstrumentSoftkeyFlashesOrangeOff(); + testInstrumentModeRoundTripsKeepSelectionAndSolo(); testModeLcdRedrawIsOneDisplayTransaction(); testSequencerKeyDoesNotTrapPerformanceMode(); + testDiskLoadStepDoesNotRepeat(); + testDiskFormatNameCursor(); testDiskCancelReturnsPerformanceModeLed(); testExclusiveModesRejectOtherModeLeds(); std::cout << "WaveIntegrationTests: all checks passed\n"; diff --git a/Tests/WavePerformanceBenchmark.cpp b/Tests/WavePerformanceBenchmark.cpp index 777f6c2..d977667 100644 --- a/Tests/WavePerformanceBenchmark.cpp +++ b/Tests/WavePerformanceBenchmark.cpp @@ -4,16 +4,49 @@ #include #include +#if JUCE_WINDOWS +#include +#else +#include +#endif + namespace { using Clock = std::chrono::steady_clock; +double processCpuSeconds() +{ +#if JUCE_WINDOWS + FILETIME created {}, exited {}, kernel {}, user {}; + if (!GetProcessTimes(GetCurrentProcess(), &created, &exited, &kernel, &user)) + return 0.0; + const auto seconds = [](const FILETIME& value) { + return static_cast((static_cast(value.dwHighDateTime) << 32u) + | value.dwLowDateTime) * 1.0e-7; + }; + return seconds(kernel) + seconds(user); +#else + rusage usage {}; + getrusage(RUSAGE_SELF, &usage); + return static_cast(usage.ru_utime.tv_sec + usage.ru_stime.tv_sec) + + static_cast(usage.ru_utime.tv_usec + usage.ru_stime.tv_usec) * 1.0e-6; +#endif +} + +struct Timing +{ + double wallSeconds = 0.0; + double cpuSeconds = 0.0; +}; + template -double measure(Render&& render) +Timing measure(Render&& render) { + const auto cpuStart = processCpuSeconds(); const auto start = Clock::now(); render(); - return std::chrono::duration(Clock::now() - start).count(); + const auto wallSeconds = std::chrono::duration(Clock::now() - start).count(); + return { wallSeconds, processCpuSeconds() - cpuStart }; } juce::MidiBuffer notes(int count) @@ -27,7 +60,9 @@ juce::MidiBuffer notes(int count) int main(int argc, char** argv) { - constexpr auto sampleRate = 48000.0; + const auto sampleRate = argc > 4 + ? juce::jlimit(8000.0, 384000.0, juce::String(argv[4]).getDoubleValue()) + : 48000.0; const auto blockSize = argc > 1 ? juce::jlimit(16, 4096, juce::String(argv[1]).getIntValue()) @@ -36,7 +71,10 @@ int main(int argc, char** argv) ? juce::jlimit(1, wave::dsp::WaldorfEngine::voiceCount, juce::String(argv[2]).getIntValue()) : wave::dsp::WaldorfEngine::voiceCount; - const auto blocks = juce::roundToInt(std::ceil(2.0 * sampleRate / blockSize)); + const auto duration = argc > 5 + ? juce::jlimit(0.25, 60.0, juce::String(argv[5]).getDoubleValue()) + : 2.0; + const auto blocks = juce::roundToInt(std::ceil(duration * sampleRate / blockSize)); const auto renderedSeconds = static_cast(blockSize * blocks) / sampleRate; wave::dsp::WaldorfEngine engine; @@ -49,6 +87,9 @@ int main(int argc, char** argv) sound.releaseSeconds = 2.0f; sound.cutoffHz = 12000.0f; sound.filterEnvelopeSemitones = 0.0f; + if (argc > 3) + sound.resonanceAmount = juce::jlimit(0.0f, 1.0f, + juce::String(argv[3]).getFloatValue()); juce::AudioBuffer audio(2, blockSize); auto engineMidi = notes(voiceCount); const auto engineSeconds = measure([&] { @@ -68,10 +109,12 @@ int main(int argc, char** argv) }); const auto bootStart = Clock::now(); - auto processor = std::make_unique(); + auto processor = std::make_unique( + juce::File{}, WaveEmulationAudioProcessor::InitialBank::embeddedFactory); const auto bootSeconds = std::chrono::duration(Clock::now() - bootStart).count(); processor->prepareToPlay(sampleRate, blockSize); - processor->setCurrentProgram(12); // A013: one full-range instrument. + const auto program = argc > 6 ? juce::String(argv[6]).getIntValue() : 12; + processor->setCurrentProgram(program); // Default A013: one full-range instrument. auto processorMidi = notes(voiceCount); const auto processorSeconds = measure([&] { for (int block = 0; block < blocks; ++block) @@ -83,14 +126,24 @@ int main(int argc, char** argv) }); std::cout << "Block size: " << blockSize << " samples, voices: " << voiceCount << '\n' - << "Parallel DSP: " << engineSeconds << " s, " - << renderedSeconds / engineSeconds << "x realtime\n" - << "Serial DSP: " << serialSeconds << " s, " - << renderedSeconds / serialSeconds << "x realtime\n" - << "Voice-card threading speedup: " << serialSeconds / engineSeconds << "x\n" + << "DSP resonance: " << sound.resonanceAmount << '\n' + << "Sample rate: " << sampleRate << " Hz, duration: " << renderedSeconds << " s\n" + << "Active DSP voices: " << engine.activeVoiceCount() << '\n' + << "Parallel DSP: " << engineSeconds.wallSeconds << " s, " + << renderedSeconds / engineSeconds.wallSeconds << "x realtime\n" + << "Serial DSP: " << serialSeconds.wallSeconds << " s, " + << renderedSeconds / serialSeconds.wallSeconds << "x realtime\n" + << "Voice-card threading speedup: " << serialSeconds.wallSeconds / engineSeconds.wallSeconds << "x\n" << "Processor boot: " << bootSeconds << " s\n" - << "Full processor: " << processorSeconds << " s, " - << renderedSeconds / processorSeconds << "x realtime\n"; + << "Full processor: " << processorSeconds.wallSeconds << " s, " + << renderedSeconds / processorSeconds.wallSeconds << "x realtime\n" + << "Parallel DSP CPU: " << engineSeconds.cpuSeconds << " s\n" + << "Serial DSP CPU: " << serialSeconds.cpuSeconds << " s\n" + << "Full processor CPU: " << processorSeconds.cpuSeconds << " s, " + << 100.0 * processorSeconds.cpuSeconds / renderedSeconds + << "% of one core's audio-time budget (all process threads combined)\n"; + std::cout << "Firmware loaded: " << processor->getMasterFirmwareRuntime().isLoaded() + << ", active processor voices: " << processor->getActiveVoiceCount() << '\n'; std::cout << "Master delay cycles fast-forwarded: " << processor->getMasterFirmwareRuntime().fastForwardedCycleCount() << '\n'; return 0; diff --git a/Tests/WavePublicEditorTests.cpp b/Tests/WavePublicEditorTests.cpp new file mode 100644 index 0000000..b01aa0b --- /dev/null +++ b/Tests/WavePublicEditorTests.cpp @@ -0,0 +1,496 @@ +#include "PluginEditor.h" +#include "PanelWiring.h" +#include "UI/WaveLcdComponent.h" + +#include +#include +#include + +namespace +{ +void require(bool condition, const char* message) +{ + if (!condition) + throw std::runtime_error(message); +} + +class RepaintProbe final : public juce::Component +{ +public: + void paint(juce::Graphics& graphics) override + { + ++paintCount; + graphics.fillAll(juce::Colours::red); + } + int paintCount = 0; +}; + +void snapshot(juce::Component& editor, const juce::String& name) +{ + auto image = editor.createComponentSnapshot(editor.getLocalBounds()); + require(image.isValid(), "Editor snapshot is invalid"); + // Catch missing artwork or a blank renderer without depending on platform + // font rasterisation or exact pixel equality. + const auto first = image.getPixelAt(0, 0); + int different = 0; + for (int y = 0; y < image.getHeight(); y += 16) + for (int x = 0; x < image.getWidth(); x += 16) + if (image.getPixelAt(x, y) != first) + ++different; + require(different > 100, "Editor snapshot is blank"); + if (const auto* directory = std::getenv("WAVE_TEST_ARTIFACT_DIR")) + { + juce::File folder(directory); + require(folder.createDirectory().wasOk(), "Cannot create snapshot folder"); + auto stream = folder.getChildFile(name + ".png").createOutputStream(); + require(stream != nullptr && juce::PNGImageFormat{}.writeImageToStream(image, *stream), + "Cannot write editor snapshot"); + } +} +} + +int main() +{ + juce::ScopedJuceInitialiser_GUI initialiseJuce; + try + { + juce::TemporaryFile preference(".txt"); + auto processor = std::make_unique(preference.getFile()); + processor->prepareToPlay(48000.0, 128); + std::unique_ptr editor(processor->createEditor()); + require(editor != nullptr, "Plugin did not create an editor"); + editor->setVisible(true); + require(editor->getWidth() == 2338 && editor->getHeight() == 1042, + "Unexpected initial editor size"); + snapshot(*editor, "editor-full"); + auto* panelEditor = dynamic_cast(editor.get()); + require(panelEditor != nullptr, "Unexpected editor type"); + require(panelEditor->tooltipAt({ 222.0f, 81.0f }) == "Wave 1 Detune", + "Knob tooltip does not identify its control"); + for (const auto x : { 969.0f, 1025.0f, 1080.0f, 1136.0f, + 1191.0f, 1248.0f, 1302.0f, 1358.0f }) + require(panelEditor->tooltipAt({ x, 400.0f }).startsWith("Fader "), + "Missing fader tooltip"); + require(panelEditor->tooltipAt({ 10.0f, 600.0f }).isEmpty(), + "Empty panel space should not have a control tooltip"); + + // A synthetic skin verifies visible replacement and fixed hit geometry. + juce::TemporaryFile skin(".svg"); + require(skin.getFile().replaceWithText( + ""), + "Cannot write synthetic skin"); + require(panelEditor->loadPanelSkin(skin.getFile()).wasOk(), "Valid skin rejected"); + const auto skinImage = editor->createComponentSnapshot(editor->getLocalBounds()); + require(skinImage.getPixelAt(80, 20) == juce::Colours::lime, + "Alternative skin did not replace panel artwork"); + require(panelEditor->tooltipAt({ 222.0f, 81.0f }) == "Wave 1 Detune", + "Skin replaced control geometry"); + { + std::unique_ptr reopened(processor->createEditor()); + require(reopened->createComponentSnapshot(reopened->getLocalBounds()) + .getPixelAt(80, 20) == juce::Colours::lime, + "Reopened editor did not remember the skin"); + } + juce::TemporaryFile invalidSkin(".svg"); + invalidSkin.getFile().replaceWithText( + ""); + require(panelEditor->loadPanelSkin(invalidSkin.getFile()).failed(), + "Skin with incompatible coordinates accepted"); + require(editor->createComponentSnapshot(editor->getLocalBounds()) + .getPixelAt(80, 20) == juce::Colours::lime, + "Rejected skin replaced working artwork"); + panelEditor->useDefaultPanelSkin(); + require(processor->getRememberedPanelSkin() == juce::File{}, + "Original skin did not clear the saved preference"); + // Built-in compact artwork relocates live controls, and its preference + // survives a fresh processor without depending on an SVG file path. + panelEditor->useCompactPanelSkin(); + require(editor->getWidth() == 1693 && editor->getHeight() == 768, + "Compact skin did not resize to the supplied artwork"); + require(processor->getRememberedCompactPanelSkin(), + "Compact skin preference was not saved"); + for (const auto& control : std::array, juce::String>, 8> {{ + { {207.0f, 122.5f}, "Wave 1 Detune" }, + { {207.0f, 388.5f}, "Wave 2 Detune" }, + { {677.0f, 202.0f}, "Wavetable/Data" }, + { {677.0f, 115.0f}, "System Volume" }, + { {568.0f, 556.0f}, "Glide Rate" }, + { {1328.0f, 192.0f}, "Cutoff" }, + { {1333.0f, 642.5f}, "Panning Mod 2 Amount" }, + { {885.0f, 564.0f}, "Wave Envelope Time 1" } + }}) + require(panelEditor->tooltipAt(control.first) == control.second, + "Compact knob is missing or bound to the wrong control"); + for (const auto x : { 801.4f, 847.32f, 892.42f, 938.34f, + 983.44f, 1030.18f, 1074.46f, 1120.38f }) + require(panelEditor->tooltipAt({x, 316.03f}).startsWith("Fader "), + "Compact fader hit region is missing"); + // Each visible fader must operate its corresponding performance + // parameter, including the final fader's distinct physical ADC channel. + int compactFader = 0; + for (const auto x : { 801.4f, 847.32f, 892.42f, 938.34f, + 983.44f, 1030.18f, 1074.46f, 1120.38f }) + { + const auto initialValue = processor->getPanelFaderValue(compactFader); + const juce::Point start {x, 316.03f}; + const auto end = start.translated(0.0f, initialValue < 0.5f ? -50.0f : 50.0f); + const auto input = juce::Desktop::getInstance().getMainMouseSource(); + const auto timestamp = juce::Time::getCurrentTime(); + const juce::MouseEvent faderDown { + input, start, juce::ModifierKeys {juce::ModifierKeys::leftButtonModifier}, + 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, panelEditor, panelEditor, + timestamp, start, timestamp, 1, false + }; + const juce::MouseEvent faderDrag { + input, end, juce::ModifierKeys {juce::ModifierKeys::leftButtonModifier}, + 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, panelEditor, panelEditor, + timestamp, start, timestamp, 1, true + }; + panelEditor->mouseDown(faderDown); + panelEditor->mouseDrag(faderDrag); + panelEditor->mouseUp(faderDrag); + require(std::abs(processor->getPanelFaderValue(compactFader) - initialValue) > 0.4f, + "Compact fader did not operate its corresponding parameter"); + ++compactFader; + } + auto* compactLcd = static_cast(nullptr); + for (int index = 0; index < editor->getNumChildComponents(); ++index) + if (auto* child = editor->getChildComponent(index); + dynamic_cast(child) != nullptr) + compactLcd = child; + require(compactLcd != nullptr + && compactLcd->getBounds() == juce::Rectangle(777, 180, 367, 57), + "Compact LCD does not align with the SVG"); + const auto compactCommand = [&](int key) { + return editor->keyPressed(juce::KeyPress( + key, juce::ModifierKeys { juce::ModifierKeys::commandModifier }, 0)); + }; + require(compactCommand('k') && editor->getWidth() == 1693 && editor->getHeight() == 768, + "Keyboard shortcut changed the compact layout"); + snapshot(*editor, "editor-compact"); + require(compactCommand('=') && editor->getWidth() == 1862 && editor->getHeight() == 845, + "Compact zoom did not retain the artwork aspect ratio"); + require(panelEditor->tooltipAt({207.0f * 1.1f, 122.5f * 1.1f}).contains("Wave 1 Detune"), + "Compact zoom moved knob interaction away from the artwork"); + require(compactCommand('0'), "Cannot reset compact zoom"); + { + auto reopenedProcessor = std::make_unique(preference.getFile()); + std::unique_ptr reopened(reopenedProcessor->createEditor()); + require(reopened->getWidth() == 1693 && reopened->getHeight() == 768, + "Fresh processor did not remember Compact Skin"); + } + require(panelEditor->loadPanelSkin(skin.getFile()).wasOk() + && editor->getWidth() == 2338 && editor->getHeight() == 1042 + && !processor->getRememberedCompactPanelSkin(), + "Loading an original-layout skin did not leave compact mode"); + panelEditor->useCompactPanelSkin(); + panelEditor->useDefaultPanelSkin(); + require(editor->getWidth() == 2338 && editor->getHeight() == 1042 + && !processor->getRememberedCompactPanelSkin(), + "Original skin did not restore layout and preference"); + std::cout << "Compact skin layout, zoom, persistence and switching passed" << std::endl; + preference.getFile().getSiblingFile( + preference.getFile().getFileNameWithoutExtension() + "-panel-skin.txt").deleteFile(); + // A physical pot must move its visible artwork, even before firmware + // or a factory SET is supplied. Exercise the actual child input handler. + const juce::Point knobCentre { 222.0f, 81.0f }; + auto* knob = editor->getComponentAt(knobCentre.roundToInt()); + require(knob != nullptr && knob != editor.get(), "Missing detune knob input component"); + const auto knobBounds = knob->getBounds(); + const auto beforeDrag = editor->createComponentSnapshot(knobBounds); + const auto localStart = knob->getLocalPoint(editor.get(), knobCentre); + const auto source = juce::Desktop::getInstance().getMainMouseSource(); + const auto time = juce::Time::getCurrentTime(); + const juce::MouseEvent down { + source, localStart, juce::ModifierKeys { juce::ModifierKeys::leftButtonModifier }, + 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, knob, knob, + time, localStart, time, 1, false + }; + const juce::MouseEvent drag { + source, localStart.translated(0.0f, 60.0f), + juce::ModifierKeys { juce::ModifierKeys::leftButtonModifier }, + 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, knob, knob, + time, localStart, time, 1, true + }; + knob->mouseDown(down); + knob->mouseDrag(drag); + knob->mouseUp(drag); + const auto afterDrag = editor->createComponentSnapshot(knobBounds); + int changedPixels = 0; + for (int y = 0; y < beforeDrag.getHeight(); ++y) + for (int x = 0; x < beforeDrag.getWidth(); ++x) + changedPixels += beforeDrag.getPixelAt(x, y) != afterDrag.getPixelAt(x, y) ? 1 : 0; + require(changedPixels > 10, "Dragging a synth knob did not rotate its artwork"); + std::cout << "Synth knob drag changed " << changedPixels << " pixels" << std::endl; + + const auto command = [&](int key) { + return editor->keyPressed(juce::KeyPress( + key, juce::ModifierKeys { juce::ModifierKeys::commandModifier }, 0)); + }; + require(command('k') && editor->getWidth() == 2338 && editor->getHeight() == 619, + "Hide Keyboard failed"); + snapshot(*editor, "editor-panel"); + require(command('=') && editor->getWidth() == 2572 && editor->getHeight() == 681, + "Zoom In failed"); + require(command('-') && editor->getWidth() == 2338 && editor->getHeight() == 619, + "Zoom Out failed"); + require(command('k') && command('0') + && editor->getWidth() == 2338 && editor->getHeight() == 1042, + "Restore full editor failed"); + // Exercise editor destruction/recreation as hosts do when reopening UI. + editor.reset(); + editor.reset(processor->createEditor()); + require(editor != nullptr, "Plugin did not reopen its editor"); + editor->setVisible(true); + const auto loadAndCheckFirmware = [&] { + if (const auto* directory = std::getenv("WAVE_FIRMWARE_DIR")) + { + require(processor->loadFirmware(juce::File(directory)).hasBothImages(), + "Cannot load LCD test firmware"); + juce::AudioBuffer audio(2, 128); + juce::MidiBuffer midi; + for (int block = 0; block < 1000; ++block) + { + audio.clear(); + processor->processBlock(audio, midi); + } + require(processor->getNumPrograms() == 256 + && processor->getSelectedPerformanceInstrument() == 0 + && processor->isPerformanceInstrumentActive(0), + "First firmware load did not retain the default INIT Instrument"); + // Exercise the real Cutoff mouse handler before importing any + // user SET: rotating the artwork must also edit the live Sound. + const auto cutoffBefore + = processor->getMasterFirmwareRuntime().currentSoundRecordByte(79); + const juce::Point cutoffCentre { 1670.0f, 237.0f }; + auto* cutoffKnob = editor->getComponentAt(cutoffCentre.roundToInt()); + require(cutoffKnob != nullptr && cutoffKnob != editor.get(), + "Default Cutoff knob has no input component"); + const auto cutoffStart = cutoffKnob->getLocalPoint(editor.get(), cutoffCentre); + const auto cutoffTime = juce::Time::getCurrentTime(); + const juce::MouseEvent cutoffDown { + source, cutoffStart, + juce::ModifierKeys { juce::ModifierKeys::leftButtonModifier }, + 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, cutoffKnob, cutoffKnob, + cutoffTime, cutoffStart, cutoffTime, 1, false + }; + const juce::MouseEvent cutoffDrag { + source, cutoffStart.translated(0.0f, 80.0f), + juce::ModifierKeys { juce::ModifierKeys::leftButtonModifier }, + 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, cutoffKnob, cutoffKnob, + cutoffTime, cutoffStart, cutoffTime, 1, true + }; + cutoffKnob->mouseDown(cutoffDown); + cutoffKnob->mouseDrag(cutoffDrag); + cutoffKnob->mouseUp(cutoffDrag); + for (int block = 0; block < 1000; ++block) + { + audio.clear(); + processor->processBlock(audio, midi); + } + require(processor->getMasterFirmwareRuntime().currentSoundRecordByte(79) + != cutoffBefore, + "Default SET knob rotated without editing the INIT Sound"); + std::cout << "Default INIT Instrument responds to editor knob dragging" << std::endl; + // Public builds must accept panel input after user-supplied firmware + // boots, without relying on an embedded factory sound bank. + auto* panel = dynamic_cast(editor.get()); + require(panel != nullptr, "Unexpected editor type"); + for (const auto compact : { false, true }) + { + if (compact) + panel->useCompactPanelSkin(); + for (const auto y : { 494.0f, 553.0f }) + { + const auto before = processor->getMasterFirmwareRuntime().lcdVideoSnapshot(); + const juce::Point position = compact + ? juce::Point {1196.99f, y < 500.0f ? 375.3f : 418.3f} + : juce::Point {1402.5f + 66.0f, y}; + require(panel->getComponentAt(position.roundToInt()) == panel, + "Panel control is intercepted by a child component"); + const auto time = juce::Time::getCurrentTime(); + const auto source = juce::Desktop::getInstance().getMainMouseSource(); + const juce::MouseEvent down { + source, position, juce::ModifierKeys { juce::ModifierKeys::leftButtonModifier }, + 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, panel, panel, + time, position, time, 1, false + }; + panel->mouseDown(down); + panel->mouseUp(down); + for (int block = 0; block < 1000; ++block) + { + audio.clear(); + processor->processBlock(audio, midi); + } + require(processor->getMasterFirmwareRuntime().lcdVideoSnapshot() != before, + "Public firmware mode button did not change the LCD"); + } + } + snapshot(*editor, "editor-compact-firmware"); + panel->useDefaultPanelSkin(); + std::cout << "Original and compact firmware mode buttons passed" << std::endl; + std::cout << "Performance count before SET import: " + << processor->getNumPrograms() << std::endl; + if (const auto* setup = std::getenv("WAVE_FACTORY_SET")) + { + const auto* imagePath = std::getenv("WAVE_TEST_DISK_IMAGE"); + require(imagePath != nullptr, "SET test needs a local disk image destination"); + require(processor->createDiskImageFromWaveSetup( + juce::File(setup), juce::File(imagePath)).wasOk(), + "Could not create/mount the local SET test disk"); + const auto render = [&](int count) { + for (int block = 0; block < count; ++block) + { + audio.clear(); + processor->processBlock(audio, midi); + } + }; + render(64); + const auto ok = wave::panel::matrixIndexForDiagnosticCode(70); + processor->setPanelButton(ok, true); + render(8); + processor->setPanelButton(ok, false); + render(1000); + require(processor->getNumPrograms() == 256 + && processor->getPanelSelectedMode() == 39, + "SET import did not enable the Performance bank"); + processor->setCurrentProgram(0); + render(1000); + for (const auto code : { 72, 69 }) + { + const auto matrix = wave::panel::matrixIndexForDiagnosticCode(code); + processor->setPanelButton(matrix, true); + render(8); + processor->setPanelButton(matrix, false); + render(1000); + const auto expected = code == 72 ? 1 : 0; + require(processor->getCurrentProgram() == expected + && processor->getMasterFirmwareRuntime().currentPerformanceId() + == expected, + "Performance +/- did not select the adjacent firmware program"); + } + std::cout << "Imported SET: Performance +/- selected A002 then A001" << std::endl; + } + const auto& runtime = processor->getMasterFirmwareRuntime(); + const auto video = runtime.lcdVideoSnapshot(); + wave::ui::LcdFramebuffer framebuffer; + framebuffer.loadHardwareVideoRam(video.data(), video.size(), runtime.lcdDisplayPage()); + int firmwarePixels = 0; + for (int y = 0; y < wave::ui::LcdFramebuffer::height; ++y) + for (int x = 0; x < wave::ui::LcdFramebuffer::width; ++x) + firmwarePixels += framebuffer.pixel(x, y) ? 1 : 0; + std::cout << "Firmware LCD: " << firmwarePixels << " pixels, " + << runtime.lcdVideoWriteCount() << " writes" << std::endl; + require(firmwarePixels > 0, "Firmware LCD framebuffer is blank"); + wave::ui::WaveLcdComponent lcd(*processor); + lcd.setPanelEmbedded(true); + lcd.setSize(480, 64); + for (const auto software : { false, true }) + { + const auto image = software + ? lcd.createComponentSnapshot(lcd.getLocalBounds(), true, 1.0f, + juce::SoftwareImageType{}) + : lcd.createComponentSnapshot(lcd.getLocalBounds()); + int paintedPixels = 0; + for (int y = 0; y < image.getHeight(); ++y) + for (int x = 0; x < image.getWidth(); ++x) + { + const auto pixel = image.getPixelAt(x, y); + paintedPixels += pixel.getRed() < 40 && pixel.getGreen() < 100 ? 1 : 0; + } + std::cout << (software ? "Software" : "Native") << " LCD image: " + << paintedPixels << " pixels" << std::endl; + if (const auto* output = std::getenv("WAVE_TEST_ARTIFACT_DIR")) + { + auto stream = juce::File(output).getChildFile( + software ? "lcd-software.png" : "lcd-native.png").createOutputStream(); + require(stream != nullptr && juce::PNGImageFormat{}.writeImageToStream(image, *stream), + "Cannot save LCD test image"); + } + require(paintedPixels == firmwarePixels, "LCD renderer lost firmware pixels"); + } + } + }; + const auto liveFirmwareLoad = std::getenv("WAVE_TEST_LIVE_FIRMWARE_LOAD") != nullptr; + if (!liveFirmwareLoad) + loadAndCheckFirmware(); + if (std::getenv("WAVE_TEST_NATIVE_WINDOW") != nullptr) + { + std::cout << "Creating native window" << std::endl; + juce::DocumentWindow window("Wave Windows display test", + juce::Colours::darkgrey, + juce::DocumentWindow::allButtons); + std::cout << "Setting native title bar" << std::endl; + window.setUsingNativeTitleBar(true); + std::cout << "Attaching editor" << std::endl; + window.setContentNonOwned(editor.get(), true); + std::cout << "Positioning window" << std::endl; + window.setTopLeftPosition(40, 40); + std::cout << "Showing window" << std::endl; + window.setVisible(true); + require(window.getPeer() != nullptr && window.isShowing(), + "Native editor window is not showing"); + std::cout << "Detected " << juce::Desktop::getInstance().getDisplays().displays.size() + << " display(s); native window bounds " + << window.getScreenBounds().toString() << std::endl; + RepaintProbe repaintProbe; + repaintProbe.setBounds(5, 40, 8, 8); + editor->addAndMakeVisible(repaintProbe); + int paintsBeforeRequest = -1; + juce::Timer::callAfterDelay(4000, [&] { + paintsBeforeRequest = repaintProbe.paintCount; + repaintProbe.repaint(); + }); + juce::String firmwareLoadError; + if (liveFirmwareLoad) + juce::Timer::callAfterDelay(1000, [&] { + try { loadAndCheckFirmware(); } + catch (const std::exception& error) + { + firmwareLoadError = error.what(); + juce::MessageManager::getInstance()->stopDispatchLoop(); + } + }); + juce::Timer::callAfterDelay(10000, [] { + juce::MessageManager::getInstance()->stopDispatchLoop(); + }); + juce::MessageManager::getInstance()->runDispatchLoop(); + require(firmwareLoadError.isEmpty(), firmwareLoadError.toRawUTF8()); + std::cout << "Native paints before/after repaint request: " + << paintsBeforeRequest << "/" << repaintProbe.paintCount << std::endl; + require(paintsBeforeRequest >= 0 && repaintProbe.paintCount > paintsBeforeRequest, + "Native window stopped repainting after its initial frame"); + if (std::getenv("WAVE_FIRMWARE_DIR") != nullptr) + for (int index = 0; index < editor->getNumChildComponents(); ++index) + if (auto* lcd = dynamic_cast(editor->getChildComponent(index))) + { + const auto image = lcd->createComponentSnapshot(lcd->getLocalBounds(), true, 1.0f, + juce::SoftwareImageType{}); + int darkPixels = 0; + for (int y = 0; y < image.getHeight(); ++y) + for (int x = 0; x < image.getWidth(); ++x) + { + const auto pixel = image.getPixelAt(x, y); + darkPixels += pixel.getRed() < 40 && pixel.getGreen() < 100 ? 1 : 0; + } + std::cout << "Live editor LCD: " << darkPixels << " pixels" << std::endl; + if (const auto* output = std::getenv("WAVE_TEST_ARTIFACT_DIR")) + { + auto stream = juce::File(output).getChildFile("lcd-live-editor.png").createOutputStream(); + require(stream != nullptr && juce::PNGImageFormat{}.writeImageToStream(image, *stream), + "Cannot save live LCD test image"); + } + require(darkPixels > 0, "Live editor LCD is blank after firmware loading"); + } + window.clearContentComponent(); + } + processor->releaseResources(); + std::cout << "Public editor rendering, shortcuts and reopening passed\n"; + } + catch (const std::exception& error) + { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/Tests/WaveVoiceTrace.cpp b/Tests/WaveVoiceTrace.cpp new file mode 100644 index 0000000..45ddc01 --- /dev/null +++ b/Tests/WaveVoiceTrace.cpp @@ -0,0 +1,145 @@ +// Runs the real WDV.SYS in VoiceFirmwareRuntime from a command script and prints +// the logged ASIC/CV/routing-latch write stream ("W "). +// The oracle gate gate_e_wdv_note_trace.py (Waldorf Wave firmware repo) runs the +// same script on the Musashi oracle and diffs the two streams. +// +// Script commands: poke (shared RAM 0x100000..0x1fffff), +// until_pc (single-step), scan (wait for one full voice scan), +// run , mark . An optional third argument selects the board +// (0-2, default 0; the board's alive flag is 0x10508e + board). +#include "Firmware/VoiceFirmwareRuntime.h" + +#include +#include +#include +#include +#include + +using namespace wave::firmware; + +namespace +{ +constexpr uint32_t loopAliveFlag = 0x10508e; // st.b after every 0x79c call, + board id +constexpr int scanSliceCycles = 200; +constexpr long stepLimit = 50'000'000; + +uint8_t* sharedAt(SharedFirmwareMemory& memory, uint32_t address) +{ + if (address >= 0x180000 && address < 0x180000 + memory.extension.size()) + return &memory.extension[address - 0x180000]; + if (address >= 0x140000 && address < 0x140000 + memory.work.size()) + return &memory.work[address - 0x140000]; + if (address >= 0x100000 && address < 0x100000 + memory.program.size()) + return &memory.program[address - 0x100000]; + return nullptr; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3 && argc != 4) + { + std::fprintf(stderr, "usage: WaveVoiceTrace wdv.sys script [board]\n"); + return 2; + } + const auto board = argc == 4 ? std::atoi(argv[3]) : 0; + juce::MemoryBlock image; + if (!juce::File(argv[1]).loadFileAsData(image)) + { + std::fprintf(stderr, "cannot read %s\n", argv[1]); + return 2; + } + + SharedFirmwareMemory memory; + memory.clear(); + VoiceFirmwareRuntime runtime; + runtime.attachSharedMemory(memory); + if (!runtime.setBoardIndex(board)) + { + std::fprintf(stderr, "board %d is not a valid strap slot\n", board); + return 2; + } + if (!runtime.loadAndReset(image)) + { + std::fprintf(stderr, "WDV image rejected\n"); + return 2; + } + + const auto flush = [&] { + for (const auto& write : runtime.pendingHardwareWrites()) + std::printf("W %llu %06x %02x\n", static_cast(write.cycle), + write.address, write.value); + runtime.clearHardwareWrites(); + }; + + std::ifstream script(argv[2]); + if (!script.is_open()) + { + std::fprintf(stderr, "cannot read script %s\n", argv[2]); + return 2; + } + std::string line; + while (std::getline(script, line)) + { + std::istringstream in(line); + std::string command; + in >> command; + if (command == "poke") + { + uint32_t address = 0, value = 0; + in >> std::hex >> address >> value; + auto* byte = sharedAt(memory, address); + if (byte == nullptr) + { + std::fprintf(stderr, "poke outside shared RAM: %06x\n", address); + return 2; + } + *byte = static_cast(value); + } + else if (command == "until_pc") + { + uint32_t pc = 0; + in >> std::hex >> pc; + long steps = 0; + while (runtime.programCounter() != pc) + { + runtime.runCycles(1); + if (++steps > stepLimit) + { + std::fprintf(stderr, "PC %06x not reached\n", pc); + return 3; + } + } + } + else if (command == "scan") + { + const auto alive = loopAliveFlag + static_cast(board); + *sharedAt(memory, alive) = 0; + long slices = 0; + while (runtime.sharedByte(alive - 0x100000) == 0) + { + runtime.runCycles(scanSliceCycles); + if (++slices > stepLimit) + { + std::fprintf(stderr, "scan did not finish\n"); + return 3; + } + } + } + else if (command == "run") + { + int cycles = 0; + in >> cycles; + runtime.runCycles(cycles); + } + else if (command == "mark") + { + std::string name; + in >> name; + flush(); + std::printf("M %s\n", name.c_str()); + } + } + flush(); + return 0; +} diff --git a/Tools/DecodeWaveFactoryWavetables.cpp b/Tools/DecodeWaveFactoryWavetables.cpp new file mode 100644 index 0000000..0d7aaae --- /dev/null +++ b/Tools/DecodeWaveFactoryWavetables.cpp @@ -0,0 +1,24 @@ +#include "Dsp/WaveFactoryRom.h" +#include +#include + +int main(int argc, char** argv) +{ + if (argc != 3) + { + std::cerr << "Usage: DecodeWaveFactoryWavetables /path/to/w2sys.bin /path/to/private-output.bin\n"; + return 1; + } + juce::MemoryBlock image; + std::vector decoded; + if (!juce::File(argv[1]).loadFileAsData(image) + || !wave::dsp::WaveFactoryRom::decode(image.getData(), image.getSize(), decoded)) + { + std::cerr << "A verified Wave OS 1.700 master image is required.\n"; + return 2; + } + if (!juce::File(argv[2]).replaceWithData(decoded.data(), decoded.size())) + return 3; + std::cout << "64 original Wave tables, 64 waves each, 128 signed 8-bit samples per wave\n" + << "SHA256: " << juce::SHA256(decoded.data(), decoded.size()).toHexString() << '\n'; +} diff --git a/Tools/ProbeWaveFilter.cpp b/Tools/ProbeWaveFilter.cpp new file mode 100644 index 0000000..ab50deb --- /dev/null +++ b/Tools/ProbeWaveFilter.cpp @@ -0,0 +1,58 @@ +#include "Dsp/Cem3387.h" + +#include +#include +#include +#include + +// Offline, ROM-free trace for comparison with SPICE or hardware captures. +// Amplitudes are DSP units. Peak 1 is estimated as 5 Vpp input, not measured. +int main(int argc, char** argv) +{ + if (argc != 8) + { + std::cerr << "Usage: ProbeWaveFilter sampleRate seconds cutoffCode resonanceCode inputHz inputPeak driveDb\n" + "Cutoff/resonance codes: 0..127. Zero inputPeak tests noise-seeded oscillation.\n"; + return 1; + } + try + { + const auto number = [&](int index) { + size_t end = 0; + const auto value = std::stod(argv[index], &end); + if (argv[index][end] != '\0' || !std::isfinite(value)) + throw std::runtime_error("Arguments must be finite numbers"); + return value; + }; + const auto rate = number(1), seconds = number(2); + const auto cutoff = number(3), resonance = number(4); + const auto hz = number(5), peak = number(6), drive = number(7); + if (rate < 8000 || rate > 384000 || seconds <= 0 || seconds > 60 + || cutoff < 0 || cutoff > 127 || resonance < 0 || resonance > 127 + || hz < 0 || hz >= rate * 0.5 || peak < 0 || peak > 8 + || drive < 0 || drive > 18) + throw std::runtime_error("Argument outside supported range"); + wave::dsp::Cem3387 filter; + filter.prepare(rate, 0.0f); + filter.setControls(static_cast(20.0 * std::exp2(cutoff / 12.0)), + static_cast(resonance / 127.0), + static_cast(drive), 0.0f, 0.0f); + std::cout << "time_s,input,left,right\n" << std::setprecision(10); + const auto count = static_cast(std::round(rate * seconds)); + for (int64_t i = 0; i < count; ++i) + { + const auto time = static_cast(i) / rate; + const auto input = static_cast(peak * std::sin(6.283185307179586 * hz * time)); + const auto output = filter.process(input, 1.0f); + if (!std::isfinite(output.left) || !std::isfinite(output.right)) + throw std::runtime_error("Filter produced a non-finite sample"); + std::cout << time << ',' << input << ',' << output.left << ',' << output.right << '\n'; + } + } + catch (const std::exception& error) + { + std::cerr << error.what() << '\n'; + return 1; + } + return 0; +} diff --git a/Wave-0.1.11-release-notes.md b/Wave-0.1.11-release-notes.md new file mode 100644 index 0000000..70e9f8c --- /dev/null +++ b/Wave-0.1.11-release-notes.md @@ -0,0 +1,12 @@ +Wave Emulation 0.1.11 fixes disk loading, Store controls, and bank restoration when reopening. + +- Restores the complete stored Performance and Sound banks, including Store changes, when reopening the standalone app or recalling host state. +- Accepts native Store names containing NUL bytes so a saved bank is not rejected in favour of an older bank. +- Returns Total Recall to Performance correctly when cancelling the optional machine-specific voice and filter adjustment data. +- Shows the Performance lamp after saving a Performance and the Instrument Edit lamp after saving a Sound. +- Prevents the + button from repeating after Store, including rapid Performance browsing clicks. +- Flushes pending disk writes before remounting the same image. + +Store updates the Wave's internal banks. Use Wave Disk → Save to write those banks to the mounted disk, then System → Save Mounted Disk Image to flush the image to disk. + +The macOS installer targets macOS 13.0 and later and contains universal Apple Silicon and Intel builds. Firmware, ROM dumps, factory SETs, and disk images are not included; supply your own instrument data. diff --git a/cmake/PrepareJuce.cmake b/cmake/PrepareJuce.cmake new file mode 100644 index 0000000..f2161a4 --- /dev/null +++ b/cmake/PrepareJuce.cmake @@ -0,0 +1,59 @@ +# JUCE 8.0.15 only notifies repaint listeners (and checks its exit flag) when +# DXGI WaitForVBlank succeeds. Wine returns an unsupported error, freezing +# repainting and window teardown. Fall back to a paced notification on failure. +function(wave_prepare_juce source_dir) + set(path "${source_dir}/modules/juce_gui_basics/native/juce_VBlank_windows.cpp") + file(READ "${path}" contents) + string(REPLACE "\r\n" "\n" contents "${contents}") + string(REPLACE " for (;;)\n" " while (! threadShouldExit())\n" contents "${contents}") + set(original [=[ if (output->WaitForVBlank() == S_OK) + { + const auto now = Time::getMillisecondCounterHiRes(); + + if (now - lastVBlankEvent.exchange (now) < 1.0) + sleep (1); + + const auto stateToRead = state.fetch_or (flagPaintPending); + + if ((stateToRead & flagExit) != 0) + return; + + if ((stateToRead & flagPaintPending) != 0) + continue; + + triggerAsyncUpdate(); + } + else + { + sleep (1); + }]=]) + set(fixed [=[ // DXGI can lack VBlank support under Wine or a remote display. + // Repaints still need a clock; pace the fallback instead of spinning. + if (output->WaitForVBlank() != S_OK) + sleep (16); + + const auto now = Time::getMillisecondCounterHiRes(); + + if (now - lastVBlankEvent.exchange (now) < 1.0) + sleep (1); + + const auto stateToRead = state.fetch_or (flagPaintPending); + + if ((stateToRead & flagExit) != 0) + return; + + if ((stateToRead & flagPaintPending) != 0) + continue; + + triggerAsyncUpdate();]=]) + string(FIND "${contents}" "${fixed}" already_fixed) + if(NOT already_fixed EQUAL -1) + return() + endif() + string(FIND "${contents}" "${original}" match) + if(match EQUAL -1) + message(FATAL_ERROR "Pinned JUCE VBlank source changed; review the Wine repaint/shutdown fix") + endif() + string(REPLACE "${original}" "${fixed}" contents "${contents}") + file(WRITE "${path}" "${contents}") +endfunction() diff --git a/cmake/PrepareMusashi.cmake b/cmake/PrepareMusashi.cmake index 98c2a02..182efd0 100644 --- a/cmake/PrepareMusashi.cmake +++ b/cmake/PrepareMusashi.cmake @@ -14,13 +14,28 @@ function(wave_prepare_musashi source destination) default_pc_changed_callback_data default_set_fc_callback_data) foreach(filename m68kcpu.c m68kcpu.h) file(READ "${source}/${filename}" contents) + if(filename STREQUAL "m68kcpu.c") + # Upstream repeats this tentative definition in an indented block. + # Thread-local definitions cannot be repeated with GCC 16; retain + # the first definition and make the later declarations extern. + foreach(trap_type sigjmp_buf jmp_buf) + string(REPLACE "\t${trap_type} m68ki_aerr_trap;" + "\textern ${trap_type} m68ki_aerr_trap;" + contents "${contents}") + endforeach() + endif() foreach(symbol IN LISTS execution_state) - set(pattern "(^|\n)([ \t]*)(extern |static )?((unsigned int|int|sint|uint|m68ki_cpu_core|sigjmp_buf|jmp_buf)[ \t]+${symbol}[ \t]*[;=])") + # Capture the whole prefix, which always participates in the match. + # CMake < 4.1 rejects a backreference to an unmatched optional group. + set(pattern "(^|\n)([ \t]*(extern |static )?)((unsigned int|int|sint|uint|m68ki_cpu_core|sigjmp_buf|jmp_buf)[ \t]+${symbol}[ \t]*[;=])") if(filename STREQUAL "m68kcpu.c" AND NOT contents MATCHES "${pattern}") message(FATAL_ERROR "Musashi execution-state declaration changed: ${symbol}") endif() - string(REGEX REPLACE "${pattern}" "\\1\\2\\3WAVE_M68K_THREAD_LOCAL \\4" - contents "${contents}") + # Some symbols occur only in the implementation, not the header. + if(contents MATCHES "${pattern}") + string(REGEX REPLACE "${pattern}" "\\1\\2WAVE_M68K_THREAD_LOCAL \\4" + contents "${contents}") + endif() endforeach() set(existing "") if(EXISTS "${destination}/${filename}") diff --git a/cmake/WindowsLLVMToolchain.cmake b/cmake/WindowsLLVMToolchain.cmake new file mode 100644 index 0000000..51ea8c5 --- /dev/null +++ b/cmake/WindowsLLVMToolchain.cmake @@ -0,0 +1,44 @@ +# Windows x64 cross-compilation from macOS with Clang and xwin's MSVC SDK. +# Pass WAVE_WINDOWS_SDK_ROOT, WAVE_CLANG_CL and WAVE_LLD_LINK when configuring. +set(CMAKE_SYSTEM_NAME Windows) +set(CMAKE_SYSTEM_PROCESSOR AMD64) +set(CMAKE_TRY_COMPILE_CONFIGURATION Release) +if(NOT WAVE_WINDOWS_SDK_ROOT OR NOT WAVE_CLANG_CL OR NOT WAVE_LLD_LINK) + message(FATAL_ERROR "Set WAVE_WINDOWS_SDK_ROOT, WAVE_CLANG_CL and WAVE_LLD_LINK") +endif() +list(APPEND CMAKE_TRY_COMPILE_PLATFORM_VARIABLES + WAVE_WINDOWS_SDK_ROOT WAVE_CLANG_CL WAVE_LLD_LINK) +set(CMAKE_C_COMPILER "${WAVE_CLANG_CL}") +set(CMAKE_CXX_COMPILER "${WAVE_CLANG_CL}") +set(CMAKE_C_COMPILER_TARGET x86_64-pc-windows-msvc) +set(CMAKE_CXX_COMPILER_TARGET x86_64-pc-windows-msvc) +get_filename_component(WAVE_CLANG_BIN "${WAVE_CLANG_CL}" DIRECTORY) +set(CMAKE_RC_COMPILER "${WAVE_CLANG_BIN}/llvm-rc") +set(CMAKE_MT "${WAVE_CLANG_BIN}/llvm-mt") +set(CMAKE_LINKER "${WAVE_LLD_LINK}") +set(CMAKE_AR "${WAVE_CLANG_BIN}/llvm-lib") +set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +set(WAVE_WINDOWS_INCLUDES "") +set(WAVE_WINDOWS_RC_INCLUDES "") +foreach(directory crt/include sdk/include/ucrt sdk/include/shared sdk/include/um sdk/include/winrt) + string(APPEND WAVE_WINDOWS_INCLUDES " /imsvc\"${WAVE_WINDOWS_SDK_ROOT}/${directory}\"") + string(APPEND WAVE_WINDOWS_RC_INCLUDES " -I\"${WAVE_WINDOWS_SDK_ROOT}/${directory}\"") +endforeach() +set(CMAKE_C_FLAGS_INIT "${WAVE_WINDOWS_INCLUDES}") +set(CMAKE_CXX_FLAGS_INIT "${WAVE_WINDOWS_INCLUDES}") +set(CMAKE_RC_FLAGS_INIT "${WAVE_WINDOWS_RC_INCLUDES}") +set(WAVE_WINDOWS_LIBRARIES "") +foreach(directory crt/lib/x86_64 sdk/lib/um/x86_64 sdk/lib/ucrt/x86_64) + string(APPEND WAVE_WINDOWS_LIBRARIES " /libpath:\"${WAVE_WINDOWS_SDK_ROOT}/${directory}\"") +endforeach() +# CMake's MSVC linker wrapper asks lld to embed manifests (EXE resource 1, +# DLL resource 2). Preserve JUCE's Common Controls v6 dependency: disabling +# manifests makes Windows load comctl32 v5, which lacks TaskDialogIndirect. +set(CMAKE_EXE_LINKER_FLAGS_INIT "${WAVE_WINDOWS_LIBRARIES}") +set(CMAKE_SHARED_LINKER_FLAGS_INIT "${WAVE_WINDOWS_LIBRARIES}") +set(CMAKE_MODULE_LINKER_FLAGS_INIT "${WAVE_WINDOWS_LIBRARIES}") +set(CMAKE_FIND_ROOT_PATH "${WAVE_WINDOWS_SDK_ROOT}") +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) diff --git a/data/BlankWave.img b/data/BlankWave.img new file mode 100644 index 0000000..9b66355 Binary files /dev/null and b/data/BlankWave.img differ diff --git a/data/README.md b/data/README.md index a974141..0c4259b 100644 --- a/data/README.md +++ b/data/README.md @@ -25,3 +25,18 @@ cmake --build build --target DecodePpgWavetables This third-party PPG-derived data is included at the maintainer's direction. The GPL-3.0-or-later grant for project-authored code and artwork does not relicense third-party sample data or assert ownership of it. + +## Blank startup disk + +`BlankWave.img` is the maintainer-supplied `wave-init-all2.img`, a 720 KB FAT12 +floppy containing a SET with 256 identical INIT SOUND records and 256 MULTI INIT +Performances. Each Performance enables Instrument 1 and assigns INIT SOUND. +The INIT records match the safe defaults in Wave OS 1.700. The image contains +no executable firmware or factory sound presets. + +SHA-256: `a29a5926cd89275f231bb12d00ef70bfafbd77395b89bdb5ad9660b34b3a80d1`. + +New instances mount their own writable copy and load the default SET. Saved +projects restore their own bank and disk instead. Release packages also include +the image as `Blank Wave.img`. This native instrument data is included at the +maintainer's direction; the project GPL grant does not relicense it. diff --git a/docs/cem3387-filter.md b/docs/cem3387-filter.md new file mode 100644 index 0000000..2c8621c --- /dev/null +++ b/docs/cem3387-filter.md @@ -0,0 +1,166 @@ +# CEM3387 filter model + +The Curtis CEM3387 contains a three-pole reconstruction filter followed by a +separate four-pole resonant low-pass. The reconstruction section is modeled in +`MixedSignalPath`; resonance acts only around the four-pole section in `Cem3387`. + +The [Curtis datasheet](https://www.alldatasheet.com/datasheet-pdf/pdf/1157738/CES/CEM3387.html) +(pages 5–6) gives the second-order section transfer function and specifies +`Ca = 4 Cb` for the classical musical low-pass response. Two such sections give +`H(s) = 1 / (1 + s/wc)^4`. Four equal trapezoidal one-poles implement that +equivalent small-signal response. The nonlinear feedback equation is solved +within each circuit step, before committing the integrator states. Feedback +comes from the current fourth-stage output. Using the previous integrator state +introduces digital phase delay, changes resonance with sample rate, and causes +premature self-oscillation at high cutoff. + +Drive scales the incoming signal, leaving feedback gain unchanged. The +normalized resonance control represents the Wave's increasing panel control; +it is not a literal voltage at pin 13. The datasheet specifies decreasing chip +CV for increasing resonance (typically 4.5 V for no feedback and 1 V for +sustained oscillation). The panel-to-chip voltage mapping and nonlinear gain +law still need hardware measurements. The current feedback range is 0–4.15, +slightly exceeding the ideal four-pole oscillation threshold of 4. + +The existing Wave calibration references are approximately 28 Hz, 957 Hz, and +7779 Hz at Sound cutoff values 0, 62, and 100. The model interpolates their +frequency scale in log frequency, independently of host sample rate. Beyond +the measured range it holds the nearest scale; that extrapolation remains an +assumption. The measured passband-loss approximation remains in the input path; +the additional high-resonance makeup factor used by the delayed loop has been +removed. + +`WaveCoreTests` checks the classical small-signal resonant response, existing +Wave passband loss and oscillation references, output stability, and resonance +behavior at 44.1, 48, and 96 kHz with 0 and 18 dB drive. Below-threshold +excitation must decay, maximum resonance must sustain oscillation, and its +frequency must remain consistent across sample rates and drive settings. + +This is a behavioral model with a datasheet-guided nonlinear estimate, not a +transistor-level CEM3387 simulation. No physical Wave was available to validate +distortion, oscillation amplitude or the signal-voltage mapping. Thermal noise, +VCA/control settling and the resonance gain law remain approximations. + +## Educated nonlinear estimate (2026-10-04) + +The [original Curtis datasheet](https://www.synfo.nl/datasheets/CEM3387.pdf), +page 3, specifies typical filter THD of 0.1% at 5.0 V peak-to-peak input with ++12 V/-5 V supplies at 20 C, and a typical maximum VCF output of +/-3.5 V. Page 5 +gives a signal-handling expression of `(7/12)*Vcc - 0.5 V`, or 6.5 V for a +12 V supply. The latter does not clearly identify peak or peak-to-peak units. + +The working assumptions are: + +- DSP input peak 1 represents 2.5 V peak, or 5 Vpp, before the VCF. This is an + assumed scale, not a measured property of the Wave voice card. +- Interpret the 6.5 V input-handling figure as peak-to-peak: estimated input + headroom is +/-3.25 V, or +/-1.3 DSP units. Output headroom is +/-3.5 V, or + +/-1.4 DSP units. A smooth 16th-power shoulder approaches each limit. +- Weak symmetric transconductor curves replace the old strongly compressing + unity-scale tanh stages. Their scale of 26 DSP units is a behavioral curve + parameter, not a physical transistor voltage or internal supply rail. + The same weak curve replaces excessive reconstruction-stage compression. +- VCF output limiting operates inside the instantaneous feedback loop. It + controls autonomous oscillation amplitude without a second saturator after + the filter. Drive multiplies input before the input headroom limit. +- Cutoff calibration, passband loss, feedback range 0–4.15, CV quantization, + 250 kHz oscillator sampling and eight-bit DAC/mixer behavior are retained. + Digital wrap/quantization distortion is separate from analog chip THD. + +The nominal VCF distortion target is approximately 0.1%, with gently rising +distortion at lower levels and a stronger shoulder under overload. Symmetric +curves favor odd harmonics; actual even harmonics, resonance-dependent +distortion and surrounding VCA/voice-card loading remain unmeasured. Aging +slightly strengthens the weak curves without an arbitrary post-filter gain. +The less compressed signal can be louder than the previous approximation, +especially with resonance or drive; self-oscillation is substantially louder. + +Small-argument polynomial evaluation agrees with the exact transfer curves +to float precision, with the full curves used outside those intervals. +Reconstruction transfers remain cached per DAC code. Regression tests check +transfer accuracy, nominal/overdriven THD, bounded noise-seeded oscillation, +small-signal response, and frequency tracking across sample rates. + +On this development Mac, three paired 48-voice benchmarks (48 kHz, 512-sample +blocks, resonance 0.7, three seconds of audio) gave median serial DSP CPU time +of 3.214 s before and 2.937 s after, approximately 9% lower. This measures +the isolated engine rather than firmware or GUI cost; other patches, drive +levels, polyphony and hardware can produce different results. + +## Offline SPICE and DSP comparison + +The neighboring `bb830` project now has an offline ngspice reference in +`spice/cem3387-vcf-linear.cir`. Its existing sample-based simulator is not a +SPICE solver, and its CEM3320 component is not a CEM3387 substitute. The deck +implements only the datasheet's equivalent small-signal four-pole response, +using buffered RC poles and instantaneous feedback. It excludes nonlinear +chip behavior, reconstruction, VCAs, panning and the panel-to-chip CV law. +Its AC result was checked against `H/(1 + K*H)` with +`H = (1 + j*f/fc)^-4`: maximum gain error over 10 Hz–100 kHz was less than +0.000001 dB at fc = 957 Hz and K = 3. This validates the reference circuit, +not the nonlinear hardware model. + +`spice/cem3387-vcf-estimate.cir` adds the assumed weak curves and headroom, +using physical volts with the assumed 2.5 V-per-DSP-unit scale. Its buffered +RC poles are an equivalent behavioral circuit, not the chip's OTA topology. +It excludes reconstruction, VCA/pan, output coupling, noise and CV settling. +Running the same nonlinear assumptions in ngspice checks discretization and +solver behavior; it provides no independent evidence of hardware accuracy. + +At cutoff 7779 Hz, zero resonance and 100 Hz/5 Vpp input, ngspice gives +0.08848% H2–H10 THD with a 2 us timestep. Halving the timestep to 1 us changes +this to 0.08848%. The DSP result is 0.08858% at 48 kHz. The small difference +includes digital sampling and the DSP's output coupling. At fc = 957 Hz, +K = 4.15 and zero input after a small startup pulse, SPICE sustains oscillation +at 957.00 Hz with 2.4099 V RMS (2 us timestep). At 1 us it gives 957.01 Hz +and 2.4099 V RMS. The DSP's centered-channel RMS of 0.6815 corresponds to +about 2.4095 V RMS before pan under the assumed voltage mapping. + +Build the ROM-free trace tool with +`cmake --build build --target ProbeWaveFilter`. For example: + +```sh +build/ProbeWaveFilter 48000 2 100 0 100 0.1 0 > filter.csv +``` + +Arguments are sample rate, duration in seconds, cutoff code, resonance code, +input sine frequency, input peak and drive dB. The output CSV contains time, +input and stereo output samples. Zero input peak tests oscillation seeded +solely by the model's internal noise. The trace includes the current Cem3387 +filter, input headroom, VCA and output coupling, but excludes the separate +reconstruction stage and the rest of the synth. Input amplitude is in DSP +units; peak 1 is estimated as 5 Vpp input. That physical scale is unverified. + +### Characterization of the estimate + +At zero drive, zero age/tolerance, centered pan and open VCA, zero-input +maximum resonance sustains oscillation at all three tested sample rates: + +| Cutoff code | 44.1 kHz | 48 kHz | 96 kHz | +| --- | ---: | ---: | ---: | +| 0 | 28.00 Hz | 28.00 Hz | 28.00 Hz | +| 62 | 956.78 Hz | 956.80 Hz | 956.78 Hz | +| 100 | 7773.76 Hz | 7773.81 Hz | 7773.81 Hz | + +Measurement uses positive-going crossings in the final second after 3 seconds +of silence (14 seconds for cutoff 0). At cutoff 62, centered left-channel +RMS is 0.6815 at 44.1/48 kHz and 0.6816 at 96 kHz. These amplitudes follow +the estimated output rail; the real Wave's onset and amplitude need comparison. + +A 100 Hz sine at cutoff 100, zero resonance and 48 kHz produces these H2–H10 +THD values, measured by harmonic projections over the final full second of a +2-second run: + +| Input peak (DSP units) | Previous model THD | Estimated model THD | +| ---: | ---: | ---: | +| 0.10 | 0.454% | 0.00049% | +| 0.70 | 12.32% | 0.02424% | +| 1.00 | 17.79% | 0.08858% | + +At nominal peak 1, THD is 0.08858% at both 44.1 and 96 kHz as well. These +figures characterize the behavioral DSP, not measured Wave hardware. The +datasheet's single specification point does not uniquely identify a nonlinear +curve, test spectrum, full-scale mapping or self-oscillation amplitude. Future +measurements should constrain H2–H10 versus level/cutoff/resonance, autonomous +oscillation onset/amplitude, and physical pin voltages before claiming a +hardware-calibrated nonlinear response. diff --git a/docs/release-0.1.12.md b/docs/release-0.1.12.md new file mode 100644 index 0000000..8fb4db2 --- /dev/null +++ b/docs/release-0.1.12.md @@ -0,0 +1,21 @@ +# Wave Emulation 0.1.12 + +This release improves disk loading, saved Sounds, Performance browsing, voice allocation, and the lower keyboard controls. + +- Generates all 64 original factory wavetables from the user's authenticated Wave OS 1.700 firmware. Factory tables remain intact when loading user banks or restoring projects. +- Corrects native ROM and user-wave references and interpolation in imported wavetables. Invalid individual tables and tuning records fall back safely without changing the source image. +- Preserves the audible wavetable selection through Sound Store, Performance recall, and DAW reopening, including the reported Sitar table mismatch. +- Fixes LCD freezes during disk/Total Recall operations and rapid Performance browsing. The LCD and mode lamps remain synchronized after Store. Cancel distinguishes normal mode exits from Total Recall calibration prompts. +- Implements native Instrument voice-allocation settings, including fixed polyphony and mono note-priority/retrigger modes, and corrects Instrument Edit and Glide Edit fader routing. +- Connects Button 1 and Button 2 to their dedicated modulation sources, with Performance touch/toggle modes and MIDI assignments. Handles quick clicks, dropped firmware events, and audio restarts. Makes keyboard Shift delivery reliable for native service controls. +- Adds System → Create Disk Image from WTB for native Wave wavetable files. +- Flushes emulated disk writes to the mounted image automatically. Fresh installations start with a blank disk; standalone sessions and DAW projects restore their disk and bank state. Cold starts keep the cleared playback bank empty after firmware initialization. +- Retains the full internal oscillator sampling rate while optimizing voice rendering; the reduced-rate Eco mode is removed. + +macOS builds target macOS 13.0 and later and contain universal Apple Silicon and Intel standalone, AU, VST3, and AAX builds. Windows builds contain the x64 standalone EXE and VST3, with the runtime linked statically. + +Firmware, ROM dumps, factory Sound SETs, and disk images are not included. Supply your own instrument data; the README links to the original sources. + +Store saves into the Wave's internal bank. Use the Wave's Disk Save controls to write the bank to the mounted image; the image is then flushed to disk automatically. Project-restored disk snapshots are isolated from the original file and can be exported with Save Mounted Disk Image As. + +The project owner confirmed DAW testing and approved publication of this version. Windows execution and plugin validation under CrossOver do not replace checks of native Windows audio/MIDI drivers. diff --git a/docs/release-0.1.13.md b/docs/release-0.1.13.md new file mode 100644 index 0000000..a4e0c90 --- /dev/null +++ b/docs/release-0.1.13.md @@ -0,0 +1,15 @@ +# Wave Emulation 0.1.13 + +- New instances mount a private, writable copy of the bundled Blank Wave.img and automatically load its INIT SET. Instrument 1 is active and selected, so the knobs have a Sound to edit after system firmware loads. Saved sessions restore their own bank and disk. +- Includes Blank Wave.img in the macOS installer, at the DMG root and in the Windows ZIP. Each bank contains INIT Sounds and MULTI INIT Performances; no factory sound library or executable firmware is bundled. +- Fixes the first knob gesture after firmware startup by reading the current physical pot position at the start of a drag. +- Adds the compact panel skin, with repositioned controls, remembered selection and the same live firmware LCD. +- Corrects front-panel switch wiring and numeric keypad delivery, including rapid presses and firmware acknowledgement. +- Incorporates firmware-derived oscillator, modulation, voice-control and Instrument audio-output routing corrections. +- Refines the CEM3387 transfer model and nonlinear filter behavior. The filter model remains an approximation; its measurements and validation are documented in docs/cem3387-filter.md. + +The macOS download is one DMG, targeting macOS 13.0 or later. Its installer contains universal Apple Silicon and Intel standalone, AU, VST3 and PACE-wrapped AAX formats. The Windows x64 ZIP contains the standalone EXE and VST3. Both binary packages include dependency notices. The corresponding source ZIP is available as a separate release download. + +Supply your own supported Wave OS 1.700 firmware. The bundled blank disk provides an initialized working bank; other sound libraries and wavetables can be loaded through the existing Disk controls. + +Store writes to the Wave's internal bank. Use the Disk Save controls to write the bank to the mounted image, which is flushed automatically. Project-restored disks remain private copies and can be exported with Save Mounted Disk Image As. diff --git a/docs/wavetable-authenticity.md b/docs/wavetable-authenticity.md new file mode 100644 index 0000000..0a7ae61 --- /dev/null +++ b/docs/wavetable-authenticity.md @@ -0,0 +1,84 @@ +# Original Wave factory wavetables + +When the authenticated Waldorf Wave OS 1.700 firmware is loaded, the audio +engine installs all 64 factory tables from the original master firmware's +own 68000 routines. This applies to both embedded private firmware and +locally supplied firmware in the public build. No additional factory-bank +download is needed. + +The input is the maintainer's local `w2sys.bin` from Waldorf's original +system archive, 302,768 bytes, SHA256 +`4282457d9bf7d70da2e2aa4d6a1e69467c178d0d8d8be0a27f524ab8d62e3286`. +Only this exact image is accepted by the extractor; absolute addresses +must not be reused with another operating-system revision. + +`WaveFactoryRom` executes routine `$011BB8` for selectors 0–63 in an +isolated 68000 address space. It stops at the WDV transfer call `$00BD6E` +after the firmware has filled the 4,096-byte half-wave workspace at +`$104000`. Each table includes all 64 positions, including position 60 +and the original triangle, square and saw standards at 61–63. The complete +262,144-byte unsigned half-wave result has SHA256 +`e2d3bdd4d22053058458962df7dc9a7ad08e895190f7b08e7f6b1ef63d1976c3`. +The engine expands each half-wave using its complemented reverse half-cycle +and subtracts 128 to obtain signed eight-bit samples. + +This fixes differences in the old PPG-based lower bank: table 14's +out-of-range references, calculated tables 29/30, position 60, and the +standard terminal waves. It also replaces the separately generated private +upper fallback, including differences in some calculated tables and their +terminal waves. All factory data now comes from one operating-system image. + +Automatic PPG discovery and old saved PPG paths cannot replace the original +factory bank after this firmware loads. An explicit wavetable-file import +remains available for research and is labelled as imported data rather than +an original Wave bank. Loading a SET/disk image still supplies its own 64 +user tables; those are editable content, not another fixed factory bank. + +Native user-table references resolve individual Waves: 0–299 select the +ROM palette at CPU address `$042850`, and 300–1299 select U000–U999 from +the SET's stored half-wave pool. They do not index positions in the 64 +factory tables. The loader retains the complete 300-Wave ROM palette +alongside the factory bank. Interpolation averages unsigned half-waves +before complemented expansion, matching the original routine's rounding. +The core tests execute that routine for INIT and for a user table spanning +R299, U000 and U999, then compare every resulting sample. + +Historical SET snapshots containing `$1000`-based Wave Edit workspace +references retain the previous compatibility mapping to their stored user +Wave pool. That mapping has not been verified against a hardware capture; +it is separate from the verified native ROM/user reference ranges above. + +SET imports build all user tables before publishing a new sample bank. A +malformed table marker or out-of-range Wave reference resets that individual +table to INIT in the audio engine; valid tables continue loading. Sparse +records cannot inherit leading samples from a previous disk. Factory tables +and source image bytes remain unchanged. Audio voices share one immutable +sample snapshot per render block, including across parallel voice cards. + +User tuning tables are also validated before use. Records with invalid note +or fine-tuning bytes fall back to equal temperament, including when selected +through Global tuning. This prevents damaged SET tuning data from changing +keyboard pitch across otherwise valid sounds. + +The public build without Wave firmware retains the documented PPG/procedural +fallback. The old private upper header is also only a pre-firmware fallback. +Neither is labelled as a verified original factory bank. + +## Reproduce + +```sh +cmake --build build --target DecodeWaveFactoryWavetables +./build/DecodeWaveFactoryWavetables /path/to/w2sys.bin /private/tmp/wave-factory.bin +ctest --test-dir build -R 'WaveCoreTests|WaveFactoryWavetableTests' --output-on-failure +``` + +The core tests check every half-wave byte, complemented expansion, rejection +of modified firmware, and preservation of user slots. The integration test +checks the active bank after fresh startup, factory-set startup, and project +recall with a stale PPG import path. + +This establishes equality with the factory-table data generated by the +original OS 1.700 software. It does not establish equality with every other +Wave OS revision, modified user tables, or analogue audio output. ASIC +addressing and analogue-path accuracy still require hardware measurements. +Firmware and derived bank exports remain private research inputs. diff --git a/media/WaldorfWaveUI_Compact.svg b/media/WaldorfWaveUI_Compact.svg new file mode 100644 index 0000000..e90c9f0 --- /dev/null +++ b/media/WaldorfWaveUI_Compact.svg @@ -0,0 +1,895 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/scripts/check-windows-manifests.py b/scripts/check-windows-manifests.py new file mode 100644 index 0000000..8d09401 --- /dev/null +++ b/scripts/check-windows-manifests.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Check the embedded Common Controls v6 manifests in Windows release binaries.""" +import argparse +from pathlib import Path +import struct +import sys +import xml.etree.ElementTree as ET + + +def check_manifest(path, resource_id): + data = path.read_bytes() + + def unpack(format, offset): + return struct.unpack_from(format, data, offset) + + if data[:2] != b"MZ": + raise ValueError("not a PE executable") + pe = unpack(" resource_size: + raise ValueError("invalid resource directory") + named, ids = unpack(" resource_size: + raise ValueError("invalid resource entries") + return [unpack(" resource_size: + raise ValueError("invalid manifest resource") + rva, size = unpack(" address -> value -> read/write -> decoded device/voice +MIDI / keybed / panel / disk / RS-232 + | + v + Main 68000 (w2sys.bin, 1 MB DRAM, runs from RAM) + | + shared SRAM 0x100000-0x17FFFF (one RAM, seen at the same addresses by master and boards) + | + +--------+--------+--------+ + | | | + WDV 1 WDV 2 WDV 3 (up to 3 by the 3-bit slot strap) + 68000 16 voices each + | + CV DACs + S/H, two 8-voice ASICs (0x980000 / 0x980100), wave RAM A/B, routing latch ``` -Correlating those traces with controlled note, pitch, wavetable, envelope, and modulation changes can reveal: - -- which address ranges select ASIC A versus ASIC B; -- how voices 1-8 and 9-16 are selected; -- the format and width of pitch and wavetable-position values; -- whether updates are immediate, double-buffered, latched, or interrupt-driven; -- the control-rate cadence and ordering of oscillator and CV updates; and -- how the firmware synchronizes shared data with the main CPU. - -That is much stronger evidence than reconstructing the ASIC solely from audible output. It still does not disclose the ASIC's internal oscillator arithmetic, interpolation, aliasing, or truncation rules; those require hardware measurements, logic traces, patent/design evidence if available, and hypothesis testing against real output. - -## 4. Relevance to sample-accurate emulation - -“Sample-accurate” should be used narrowly. At a minimum, the same input event and initial state must produce deterministic hardware-side events at the same emulated times, and those events must affect the rendered host sample at the correct fractional-sample position. - -A credible Wave model therefore needs: - -1. **Firmware-accurate control behaviour.** The original voice allocation, modulation rules, quantization, tables, update order, and edge cases should come from executed firmware where practical. -2. **Clock-domain scheduling.** Main-CPU execution, WDV execution, interrupts, shared-bus handshakes, ASIC clocks, and control updates need one monotonic emulated timeline. Host audio block boundaries must not change the result. -3. **Timestamped side effects.** ASIC, waveform-RAM, DAC, multiplexer, and gate writes must be timestamped rather than collapsed into one value per host block. -4. **Digital voice modelling.** The ASIC must remain a black box. A behavioural proxy for wavetable addressing, phase accumulation, interpolation/truncation, mixing, and output quantization can only be inferred and validated from its external bus and real-hardware measurements; this cannot establish the undocumented internal implementation. -5. **Mixed-signal modelling.** The time-multiplexed conversion, sample-and-hold behaviour, 12-bit control-voltage stepping, reconstruction stages, CEM3387 filter/VCA/panning response, and output path need explicit models. - -Executing both firmware images without those hardware models would reproduce the control computer but not the instrument's sound. Conversely, a good DSP approximation without the firmware can sound Wave-like while still getting voice allocation, timing, modulation, and obscure behaviours wrong. The goal is to join the two at the same observable hardware boundary. - -Cycle-exact CPU emulation may not be necessary everywhere, but it is the safest initial reference. After traces show which timings are audible or state-significant, noncritical regions can be optimized while preserving the same timestamped I/O sequence. - -## 5. Recommended reverse-engineering workflow - -### Step 1: preserve provenance and build a manifest - -- Acquire `System.zip` only from Waldorf's official Legacy Wave link. -- Record retrieval date, source URL, byte size, and SHA-256 for the outer and nested archives. -- Extract every Waldorf version into a local research area excluded from version control. -- Record the per-file sizes and hashes shown above. -- Make the emulator accept user-supplied files and identify exact known revisions. Never silently accept a different image as 1.700. - -The existing `FirmwareBundle` already authenticates the 1.700 pair. Extend its manifest to recognize the official 1.668, 1.671, and 1.680 main images while recording that their WDV image is shared. - -### Step 2: confirm CPU architecture and object formats - -- Trace the CPU part number, clock, reset, interrupt, bus, RAM, and chip-select nets in the service schematics for both the main and WDV boards. -- Configure analysis as big-endian Motorola 68000 initially. Do not select 68020 merely because a host utility uses that label for the a.out header. -- Parse the `wdv.sys` header explicitly. Confirm magic, text/data/BSS fields, relocation assumptions, entry semantics, and the loader's copy/zero/launch sequence in `w2sys.bin`. -- Determine whether the WDV vector table begins at file offset `0x20`, whether it is copied to board address `0x000000`, and whether reset begins at `0x000400`. -- Determine the main image base by following its opening jump stubs, absolute references, reset mapping, and the main-board memory decode. - -The load address should be proven from both code and hardware decode. A disassembly that happens to look plausible at one base is not enough. - -### Step 3: construct the memory maps - -For each CPU, create a table containing: - -- ROM or downloaded code; -- local SRAM/DRAM and BSS; -- shared/global RAM windows; -- system-bus address windows; -- ASIC A and B interfaces; -- waveform RAM; -- DAC, timer, interrupt, reset, status, and watchdog registers; and -- any programmable-logic-controlled aliases or mirrors. - -Start from schematic chip-select equations and then validate each range against absolute-address references in the disassembly. Name addresses by evidence level: `confirmed`, `probable`, or `unknown_io_x`. - -### Step 4: recover the main OS's WDV loader - -The main OS contains excellent string anchors around reading, validating, starting, and checking `WDV.SYS`. Work outward from those references to recover: - -1. disk read and object validation; -2. header parsing; -3. WDV reset assertion and release; -4. transfer destination and length; -5. BSS clearing or relocation processing; -6. start address/vector handling; -7. board-presence and ready polling; and -8. timeout, retry, and error paths. - -Implementing this loader behaviour first provides a concrete success criterion: an emulated WDV should reach the same ready state that the main OS expects. - -### Step 5: recover main-to-WDV communication - -The service schematics and diagnostics indicate an S-bus/shared-state relationship, but the exact protocol must be derived. Identify: - -- per-board address selection and board numbering; -- reset, fault, setup, status, and interrupt lines; -- shared-memory or mailbox layout; -- ownership and bus-arbitration rules; -- command and acknowledgement fields; -- sequence counters, ready flags, and timeout rules; -- voice-to-board mapping; and -- wavetable bulk-transfer paths. - -Use cross-references from the main OS's voice-board error strings and from WDV interrupt handlers. Then run both CPUs under one deterministic scheduler with all shared-memory reads, writes, interrupts, and status transitions logged. - -### Step 6: identify ASIC and CV side effects - -On WDV, enumerate every access outside ordinary code/RAM. Group accesses by address, instruction site, interrupt context, and repetition rate. For each candidate register or port: - -- vary one high-level parameter at a time; -- compare the resulting write sequence; -- test voice 1 versus 8, 9, and 16 to expose chip and voice selection; -- test minimum, midpoint, maximum, negative, and wrapped values; -- measure write cadence and phase relative to WDV interrupts; and -- determine whether values are raw, table-transformed, split across bytes/words, or latched by a later write. - -Do not name a register from a single correlation. Require at least two independent experiments or a matching schematic/code clue. - -### Step 7: locate envelope, LFO, pitch, and control-rate tables - -Search both binaries because responsibilities may be divided between CPUs. Useful methods include: - -- locating monotonic or symmetric word/longword arrays; -- testing candidate tables as big-endian signed and unsigned values; -- finding multiply/divide or indexed-load code near pitch, envelope, glide, and LFO parameter paths; -- comparing 1.668/1.671/1.680/1.700 main images to isolate changed routines and tables; -- tracing from SysEx/patch fields through normalized parameters to shared-memory writes; and -- observing table indices and outputs dynamically. - -Extracted tables should carry their source image hash, file offset, interpreted type, and evidence. Avoid committing copyrighted bulk data unless redistribution rights are clear; generating derived tests or asking the user to supply firmware at runtime is safer. - -Initial OS 1.700 result: the WDV executable body contains a 128-entry big-endian signed-word modulation table at offset `0x25e8`. Its entries follow `sign(n) * 8 * n^2` for signed amount `n = -64...+63`, with the negative endpoint saturated to `-32767`. General modulation destinations apply this table once. The oscillator-pitch routines at `0x254e` and `0x25a6` apply the table twice, producing a signed fourth-power depth curve. Both oscillator callers then apply `asr.l #3` at `0x0e34` and `0x0eea` before adding the result to their pitch accumulators. Pitch accumulation uses 256 internal units per semitone. Including that caller scaling makes the factory value `+12` approximately ±0.020 semitone at a full-scale LFO, rather than the ±2.25 semitones produced by a linear interpretation. - -### Step 8: build a deterministic dual-CPU execution harness - -The first harness should prioritize observability over real-time speed: - -- one main 68000 instance; -- one WDV 68000 instance initially, expandable to three; -- a single emulated-time scheduler based on device clock cycles; -- instrumented memory and I/O handlers; -- interrupt and reset tracing; -- reproducible disk/boot inputs; and -- trace checkpoints for boot, note-on, note-off, pitch bend, wavetable movement, and modulation. - -The service schematic's 32 MHz oscillator divided to a 16 MHz WDV CPU clock supplies a starting timing anchor. Other device rates must be derived from the schematics and measured behaviour rather than inferred from host sample rate. - -### Step 9: turn traces into the ASIC contract - -Define an internal interface at the observable WDV hardware boundary, for example: - -```text -write(time, device, address, value) -read(time, device, address) -> value -interrupt(time, source, level) -``` - -Keep the firmware-facing register model separate from the oscillator algorithm. This allows multiple ASIC hypotheses to be tested against the same authoritative firmware trace and lets a future gate-level or measured model replace an approximation without changing CPU emulation. - -### Step 10: validate against real hardware - -Use several independent oracles: - -- service diagnostics and expected boot/status messages; -- logic-analyser captures of WDV bus, ASIC selects, clocks, DAC updates, and shared-bus activity where safe; -- audio captures for controlled patches at multiple notes, velocities, wavetable positions, filter settings, and modulation rates; -- repeated captures to separate deterministic behaviour from analogue tolerance/noise; and -- cross-version tests, especially 1.680 versus 1.700 voice allocation under identical MIDI sequences. - -Validation should compare event traces before comparing audio. If the ASIC/DAC write stream is wrong, tuning the analogue model to hide it will produce a fragile imitation. - -## 6. Legal and practical caveats +Key facts: -### Publicly downloadable is not necessarily redistributable +- **The OS runs from RAM.** It is loaded at 0x1000 by a loader that is not in this image (an Atari-ST-style floppy boot sector). Evidence: the DOS layer stores its "current drive" in the first opcode word of `fs_init`, and the line-draw code patches opcodes in itself. +- **Boot (0x100C):** reset the three serial chips, copy a 1 KB exception-vector template to address 0, boot self-tests (cookies 0xBABEFACE / 0xFEEDFEED skip them on a warm start), heap init, load the voice boards, start the UI. Holding both panel boot switches (0xFE980020 bits 7/6) jumps into diagnostics. +- **Interrupts:** VIA timer = level 2 (system tick, key/encoder scan, LED PWM), MIDI ACIAs = level 4, console ACIA = level 5, floppy controller = level 6. Exceptions drop into the built-in System Monitor. +- **The OS also contains** a 27-command System Monitor, a diagnostics menu, a complete DOS/FAT12 file system with a group-file "database" layer, a TIFF screenshot writer, an FFT-based sample-to-wavetable analyser, FM and formant wavetable synthesis, and Microwave bulk-dump import. -Waldorf publicly hosts the archive, which is strong evidence that owners and researchers can legitimately obtain the historical system files from the manufacturer. It is not a clear software license granting third parties permission to mirror, bundle, modify, or commercially redistribute the binaries. +### Main-CPU devices (24-bit bus: firmware address 0xFEB80001 is 0xB80001) -Recommended project policy: +| address | device | +|---|---| +| 0x000000-0x0FFFFF | DRAM, 1 MB (OS image at 0x1000, heap 0x5AA80-0xFDFEA) | +| 0x100000-0x17FFFF | shared SRAM, 512 KB, battery-backed | +| 0xFEA00000-0xFEA03FFF | LCD video RAM: 1 bpp, 64 bytes/row, 4 pages of 0x1000 (480 x 64 visible) | +| 0xFEA80000 | floppy controller (uPD765/82077-type), data moved by CPU polling | +| 0xFEAA0000 | real-time clock (RP5C01-type) | +| 0xFEB80001/3, 0xFEBA0001/3 | 6850 ACIAs: MIDI A and B | +| 0xFEBC0001/3 | 6850 ACIA: RS-232 console / monitor | +| 0xFEBE0001-0x1D | 6522 VIA: tick timer, WDV reset line, board-present strap, LCD display page, FDC DRQ | +| 0xFE90..0xFE9E | keybed, buttons, encoders, LED matrix, analogue mux and ADC | -- do not commit `System.zip`, `w2sys.bin`, `wdv.sys`, factory wavetables, or derived bulk firmware data; -- direct users to Waldorf's official Legacy Wave page or provide an opt-in fetch script; -- authenticate user-supplied files by hash; -- store only hashes, sizes, format metadata, addresses, annotations, and independently written emulation code in the repository; -- keep clean-room boundaries available if the project may become commercial; and -- obtain legal advice before distributing firmware-derived tables or translated code. +### Voice board (WDV) -### Version provenance matters +| address (board bus) | device | +|---|---| +| 0x0000-0xFFFF | private RAM (program copy at 0, per-voice workspaces from 0x9000) | +| 0x100000-0x17FFFF | the same shared SRAM as the master | +| 0x040000 / 0x050000 / 0x060000 | wave RAM A / B / write-both alias; the firmware writes 8-bit samples to odd bytes at 0x60001 + (bank << 13) | +| 0x800001 | board control/status byte (bit 1 bus claim, bit 3 wave-RAM write, slot strap in bits 0-2 on read) | +| 0x880000 | CV DAC data latch (12-bit values) | +| 0x8A0000 + 16*voice + channel | sample-and-hold strobe | +| 0x8C0000 | output routing latch (write-only; 64-bit image of one cold bit per voice, from part byte +0xC "Audio Out", plus four "Analog in" bits for voices 0-3; the emulator logs the writes) | +| 0x980000 / 0x980100 | ASIC A (voices 0-7) / ASIC B (voices 8-15) | -Do not call every pair of correctly named files “Waldorf OS 1.700.” Verify both images together. A mixed pair may boot but invalidate research results. Later community OS images have different sizes, features, and key/personalization behaviour and need separate approval, manifests, and test expectations. +## 3. The master-to-voice-board protocol -### Hardware revisions matter +There is **no command parser on the board.** The master drives it through shared RAM and the board polls: -The main OS detects old- and new-style voice hardware. A single software model may therefore need multiple WDV/analogue-board configurations, timing variations, or compatibility behaviours. Machine-specific calibration and filter-adjustment data should not be mistaken for firmware or shared blindly between instruments. +1. **Download:** the master opens `WDV.SYS`, reads the 32-byte header (accepted type words 0x107/0x108/0x10B/0x111 at +2), and copies the body to 0x100000. It then pulses the board reset via VIA port B bit 0. +2. **Board start (0x400):** the board copies 0x2000 words from 0x100000 to its own address 0, reads its slot id from the one-cold strap in `0x800001` bits 0-2, marks itself present at `0x105086 + id`, then waits for the master's go flag at `0x10508A + id`. +3. **Voice update:** the master takes the bus mutex (`0x1050E2`, test-and-set), writes a 0x100-byte voice record at `0x100000 + (16*board + voice) * 0x100`, sets that voice's bit in the per-board update mask at `0x105092`, and releases. Each voice has a semaphore at `0x1050A2 + voice`. +4. **Board scan (0x79C):** per voice, the board runs ramp, LFOs, mixer, envelopes, pitch, filter, VCA and pan stages, then writes the CV DACs, the sample-and-hold strobes and the ASIC registers. +5. **Wavetable load:** the master renders 64 waves of 64 bytes into a staging area at 0x104000, writes the bank to `0x105081` and a command to `0x105080`; each board writes the samples to wave RAM and acknowledges. The only command byte on the board is this one. +6. **Fault report:** a board fault writes a record at 0x105100 (type at +1, board id word at +2) and blinks a code on `0x800001`. The master's CA2 interrupt path reads it, prints "VOICE BOARD n" and enters the monitor. -### Firmware does not guarantee bit-perfect sound +### Modulation depth (the part the old note called "table applied once or twice") -The ASIC design and analogue voice chain remain only partly documented. Component variation means that even two physical Waves will not necessarily null against each other. The defensible goal is deterministic, traceable digital/control behaviour plus a measured analogue model with documented tolerances—not an unsupported “bit-perfect” claim. +- The WDV holds a 128-entry signed-word modulation table. It follows `clamp(sign(n) * 8 * n^2, +-32767)` with `n = index - 64`; **125 of 128 entries match**, and the three real deviations are index 6 (-29912), index 126 (31000) and index 127 (32767). Index 0 (-32767) is the clamp. +- One routine applies the table once (linear depth); the pitch routines apply it **twice**, giving a fourth-order depth curve. The two oscillator callers then `asr.l #3` before adding to the pitch accumulator, at 0xE14 and 0xECA. Pitch accumulates at 256 units per semitone, so full depth is 4095 units, about 16 semitones. +- The pitch-to-increment table has 257 words with a constant of about 19.584, not 19.58. -## 7. Recommended next-step checklist +## 4. Data formats established -### Acquisition and evidence +The map documents these in `spec/firmware-map.md` §4: the sound record (256 B), multi/performance record (512 B), voice record (0x100 B), global parameter block (0x180 B at 0x148800), tuning tables (4 x 128 x {coarse, fine}), velocity curves (128 B, 8 breakpoints), wavetable records (0x8A B: a 9-character name, a 0x55 marker, 64 wave numbers) and the 300 factory waves of 64 bytes, the Wave's own SysEx format (`F0 3E 03 ... F7`), the Microwave bulk-import format, the MIDI Tuning Standard and Sample Dump handlers, the FAT12 disk layout, and the file types `.SND .PFM .SBK .PBK .ARR .TTB .VTB .GLB .WTB .GSX .SET .WVS` plus the TIFF screenshot. -- [ ] Run `scripts/fetch-official-firmware.sh` and verify the 1.700 hashes against this document. -- [ ] Extend the acquisition script to optionally extract the old-systems archive without committing any binaries. -- [ ] Add a machine-readable manifest for 1.668, 1.671, 1.680, and 1.700. -- [ ] Record archive provenance and retrieval date in a research log. -- [ ] Add firmware and analysis-project directories to ignore rules if they are not already excluded. +## 5. Corrections to the 23 August note and to the existing emulator constants -### Static analysis +Checked against the bytes: -- [ ] Create separate big-endian 68000 analysis projects for `w2sys.bin` and `wdv.sys`. -- [ ] Parse and document the 32-byte WDV object header. -- [ ] Confirm WDV vector-table offset, initial stack, entry point, and copy address from the main loader. -- [ ] Confirm the main image base and startup vectors from schematic address decode. -- [ ] Import known strings, schematic net names, and service-diagnostic labels as symbols. -- [ ] Diff all four official main images and classify changed functions/data. +- **Not a Microwave-style VIA/FDC layout at FEB8/FEBA/FEBC:** those are three 6850 serial chips (two MIDI, one RS-232 console). The VIA is at FEBE, the floppy controller at FEA8, the RTC at FEAA. +- **Waveform RAM** is at board 0x040000 / 0x050000 with a write-both alias at 0x060000, written via `0x60001 + (bank << 13)`. The emulator's `VoiceFirmwareRuntime.h` constant `waveformRamBase = 0x600000` does not match the code. +- **Shared SRAM** is one RAM seen at 0x100000 by master and boards, not a window onto board address 0. The offsets 0x5092 / 0x50A2 / 0x50E2 used in the emulator are offsets from 0x100000 and are confirmed. +- **The modulation-table `asr.l #3` sites** are 0xE14 and 0xECA, not 0x0E34 and 0x0EEA. The table has three real deviations, not four (index 0 is the clamp). +- **The master/loader details** are confirmed: `w2sys` base 0x1000, `wdv.sys` header words, SP 0x8FFE, reset 0x400, board reset on VIA port B bit 0, board presence on VIA port A bits 0-2, board id from the strap on `0x800001`. +- The old note's recommended acquisition and "do not commit firmware" policy stands. -### Hardware and protocol recovery +## 6. Firmware bugs the oracle reproduced -- [ ] Produce reviewed main-CPU and WDV memory maps with evidence levels. -- [ ] Recover the WDV reset/download/start handshake. -- [ ] Recover the shared-memory/mailbox structures and interrupt protocol. -- [ ] Identify ASIC A/B, waveform-RAM, DAC, timer, and status address ranges. -- [ ] Trace one complete note-on/note-off path from MIDI event to WDV hardware writes. -- [ ] Locate pitch, envelope, LFO, glide, and control-rate transforms on whichever CPU owns them. +Behaviours that the real ROM exhibits under the 68000 core and that the gates now pin: the SysEx program-change-map dump converts only 8 or 9 of 128 words; the Sample Dump receiver answers a bad checksum with ACK; the MIDI Tuning dump encoder is one semitone flat and reads its names from the wrong address; the single-note-change receiver is off by one and negative cents give an invalid data byte; a multi request always answers multi 247; `strncpy_pad_d` pads using the destination address as the count; several FAT12 directory-scan bugs (slot-15 re-scan, a sub-directory find-next that restarts at the first cluster, signed drive-letter checks); the heap `shrink` is a no-op on the first 20 blocks; `printf` mishandles `%d` of -32768; the velocity-curve loader overruns its slot; the voice-board boot pre-init uses the wrong stride for boards other than 0; and the global-parameter SysEx receiver copies 0x160 of 0x180 bytes. The full table (about 40 suspected bugs, with evidence level) is in `spec/firmware-map.md` §6. -### Emulator integration +## 7. What is still open -- [ ] Integrate an instruction-correct 68000 core behind testable memory/I/O callbacks. -- [ ] Run one main CPU and one WDV CPU under a deterministic common scheduler. -- [ ] Timestamp every hardware side effect independently of host audio block size. -- [ ] Reproduce Wave boot, WDV ready, diagnostics, and failure cases before enabling audio. -- [ ] Expand from one WDV board to two and three only after the one-board protocol is stable. -- [ ] Keep the firmware CPU/ASIC bridge explicit; the UI must not report genuine firmware execution while only the procedural model is active. +- **The reported OS 1.700 voice-allocation bug** (missing notes, fixed in 1.8x) is **not localised.** The voice-board image is identical to 1.680, so the cause is on the master. Candidate areas are the note-on allocation code (0x26C4-0x3162) and the key scheduler (0x35B8). This needs a diff of the 1.680 and 1.700 `w2sys.bin` plus oracle runs with the same polyphonic MIDI sequence. +- **ASIC semantics:** the *write patterns* are decoded (`spec/firmware-map.md` §4): reg 6 carries the 6-bit wave position every scan, reg 4 three bits each of Wave 1/Wave 2/Noise volume, reg 0xE commits with bit 0 = oscillator, bits 1-3 = voice, bit 4 = parameters/phase load and bits 5-7 = wave RAM bank (one of 8 resident wavetables), and the once-per-key-on write through regs 2/0/4 is the 7-bit **start phase** ("Startphase", 0 = free start, nothing written), not a wave number. What the chips do with them, the CV channel meanings (cutoff, resonance and pan are guesses) and the physical meaning of the routing bits (main / sub 1 / sub 2 by UI label only) need hardware. +- **Hardware details:** VIA port bits beyond those listed, the panel boot-switch bits, LED strobe rows (7 vs 8), the physical meaning of the analogue channels. +- **Maximum board count: resolved, 3.** The presence mask and the WDV slot strap are 3 bits wide; the "up to 4" and 64-entry tables are sizing slack (`spec/firmware-map.md` §7.2). `gate_e` runs boards 0, 1 and 2. +- **Emulator assumptions that disagreed with the map (found 2026-10-02; 1 and 2 fixed, hardware-unvalidated; 3 is open):** + 1. *Audio Out byte (fixed: the plugin now reads and edits +0xC; `PerformanceLayer::audioOutput` holds the firmware value and only 1 = main is audible).* The firmware's instrument page 1 table (0x14BCA = `04 05 07 0C 09 0A 02 03`) puts "Audio Out" at part byte **+0xC**, and WDV 0xBC6 routes from that byte; the plugin reads and edits **+8** (`PluginProcessor.cpp` `pageOneRecordOffsets`, `byte(8)`), a byte nothing consumes and which is 0 in every factory set. +0xC is 1 in every factory set (enum labels at 0x29D24: Aux only / main / sub 1 / sub 2), so the plugin's `audioOutput == 0` test is right only by accident. Sets with +0xC = 0 (three parts in `pg.set`/`ultimate.set`) now leave the main mix, as the "Aux only" label implies. + 2. *Start modulation (fixed: the route now offsets the oscillator's start phase at note-on, 128 steps = one cycle at full scale, ignored when Startphase is 0; `WaldorfEngine::startPhaseCode` reproduces the firmware's integer arithmetic).* The firmware adds the route in sound bytes 28/29 (44/45) to **Startphase** (byte 27/43, written once at key-on, 0 = free start) in 16-bit words and the two waves do not clamp alike: Wave 1 (WDV 0xF92) compares signed, so the 8-bit result wraps (64 + 127 gives 191, a negative sum gives 128-255); Wave 2 (0x1074) compares unsigned, so any result outside 1-126 becomes 127. Whether the ASIC uses bit 7 of the code is unknown, the engine ignores it; `WaldorfEngine` applies `wave1StartMod`/`wave2StartMod` as a wave-position offset sampled at note-on instead. The engine's Startphase itself (`wavePhases`, 0 = free start) matches the write pattern. + 3. *Level resolution.* reg 4 carries only 3 bits per level (value 0-0x70 >> 4); the engine mixes 7-bit level codes (0-112) from the ES2 description. Whether the chip has another level path is open. + Single wavetable per voice (one bank slot for both oscillators), 64 waves of 64 stored samples per table, 8 resident tables per board and 128 table ids (64 factory + 64 user) all match `WavetableBank` and `WaldorfEngine`; the mirrored second half of each wave is an inference that no write shows. +- **Static only:** the UI pages, the Wave Editor, the LFO, env3/env4 and glide stages on the board, and anything timing-dependent. -### Measurement and validation +## 8. What this means for sample-accurate emulation -- [ ] Design a minimal set of hardware-safe logic captures for clock, reset, bus, ASIC select, and DAC timing. -- [ ] Record calibrated single-voice audio fixtures from a real Wave. -- [ ] Compare event traces before spectral/audio comparisons. -- [ ] Test 1.680 and 1.700 with the same polyphonic MIDI sequence to isolate the known allocation difference. -- [ ] Publish an accuracy matrix stating what is confirmed, inferred, approximated, or not yet implemented. +"Sample-accurate" still requires the same things the earlier note listed: one deterministic emulated timeline, timestamped side effects independent of host block size, a digital voice model for the ASIC, and a measured mixed-signal model for the converters, filters and output stage. The mapping removes the guesswork from the *control* side: the order and content of every write the firmware makes to the ASICs, DACs and strobes is now documented and gated. The remaining work is on the other side of that boundary, where only measurements of a real Wave can settle the open points in §7. -## 8. Suggested milestone definition +Practical next steps: -The next meaningful milestone should be called **firmware-driven control emulation**, not complete Wave emulation. It is achieved when: +- [ ] Check the emulator's constants and behaviours against `spec/firmware-map.md` §3-§5 (starting with the waveform-RAM address). +- [ ] Diff OS 1.668, 1.671, 1.680 and 1.700 `w2sys.bin` and localise the voice-allocation change. +- [x] Capture ASIC/CV write traces for one note from the oracle and compare them with the emulator's (2026-10-02, `oracle/gate_e_wdv_note_trace.py` + `Tests/WaveVoiceTrace.cpp`). The same script (boot, seeded voice records, an idle scan, key-on of voices 3 and 9, three more scans) runs on the Musashi oracle and on `VoiceFirmwareRuntime`; all 11,146 logged writes (CV latch, CV strobes, ASIC, incl. tick-IRQ acknowledges) match in order, value and cycle stamp. Both sides use the same 68000 core, so this checks the emulator's bus decode, shared RAM and IRQ plumbing, not the ROM. Findings: `WaldorfAsic.cpp` never sees these writes (it is a behavioural proxy driven by the engine); `WaldorfEngine::applyFirmwareHardwareWrite` only shadows the bytes and nothing reads the shadow yet; at that time the emulator did not log the routing latch (0x8C0000, 128 byte-writes per scan) or the board-control latch (0x800001). Since then the routing latch is logged and diffed too, and the gate runs on all three boards (35,004 checks, 0 failures). +- [ ] Plan the hardware captures (bus, ASIC select, DAC timing, calibrated audio) needed to pin the ASIC and analogue model. -1. authentic `w2sys.bin` and `wdv.sys` execute on emulated 68000 CPUs; -2. the main OS downloads and starts WDV using the recovered hardware protocol; -3. a controlled MIDI note produces a deterministic, timestamped series of WDV ASIC/DAC writes; -4. the trace is stable across host buffer sizes and runs; and -5. at least one part of that trace is confirmed against a real Wave or an independently documented schematic/diagnostic behaviour. +## 9. Legal and practical caveats -Only after that milestone should the project claim that original firmware is actively driving the sound model. Sample-accurate Wave emulation then becomes a measurable hardware-modelling problem rather than a speculative reimplementation of the instrument's control software. +- Waldorf publicly hosts the archive, which supports legitimate research use. It is not a licence to redistribute. **Do not commit `System.zip`, `w2sys.bin`, `wdv.sys`, the factory wavetables or derived bulk firmware data** to this or any repository. Keep hashes, sizes, addresses, annotations and independently written code only. +- Verify both images together; a mismatched pair can boot yet invalidate results. Later community OS images need separate provenance. +- Hardware revisions matter (the OS detects old and new voice hardware); machine-specific calibration data in the shared SRAM is not firmware and should not be shared between instruments. +- Firmware does not guarantee bit-perfect sound. The defensible goal is deterministic, traceable digital/control behaviour plus a measured analogue model with documented tolerances. ## References