cmake_minimum_required(VERSION 3.22)

if (CMAKE_HOST_APPLE AND "${CMAKE_OSX_DEPLOYMENT_TARGET}" STREQUAL "")
    set(CMAKE_OSX_DEPLOYMENT_TARGET "12.0" CACHE STRING "Minimum supported macOS version" FORCE)
endif()

project(Ratio9 VERSION 1.3.0 LANGUAGES C CXX)

# Human-readable release identity is separate from stable app/settings names.
# Ratio9 Alpha 1.3.0 is the activation-free Standalone, VST3 and AU release:
# its channel word "Alpha" gives the label "Ratio9 Alpha 1.3.0". Bundle, class,
# plug-in and parameter identities are unchanged from 1.2.x.
set(RATIO9_RELEASE_CHANNEL "Alpha")
# Used only when the channel is empty. The app and its plug-ins share one
# build tag: a plug-in accepts only the app with its build id for local AI.
set(RATIO9_RELEASE_FORMAT_WORD "" CACHE STRING
    "Format word after the version when no channel is set; empty for a multi-format candidate")
set(RATIO9_BUILD_ID_TAG "alpha-1" CACHE STRING
    "Build identity tag shared by an app and the plug-ins that name it")
if (NOT "${RATIO9_RELEASE_FORMAT_WORD}" STREQUAL ""
    AND NOT "${RATIO9_RELEASE_FORMAT_WORD}" MATCHES "^[A-Za-z0-9]([A-Za-z0-9 .-]*[A-Za-z0-9])?$")
    message(FATAL_ERROR "RATIO9_RELEASE_FORMAT_WORD must be empty or plain letters, digits, spaces, dots and hyphens")
endif()
if (NOT "${RATIO9_BUILD_ID_TAG}" MATCHES "^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$")
    message(FATAL_ERROR "RATIO9_BUILD_ID_TAG must be lower-case letters, digits, dots and hyphens")
endif()
if (NOT "${RATIO9_RELEASE_CHANNEL}" STREQUAL "")
    set(RATIO9_RELEASE_NAME "Ratio9 ${RATIO9_RELEASE_CHANNEL} ${PROJECT_VERSION}")
elseif ("${RATIO9_RELEASE_FORMAT_WORD}" STREQUAL "")
    set(RATIO9_RELEASE_NAME "Ratio9 ${PROJECT_VERSION}")
else()
    set(RATIO9_RELEASE_NAME "Ratio9 ${PROJECT_VERSION} ${RATIO9_RELEASE_FORMAT_WORD}")
endif()
# Internal candidate identity, distinct from the public label above.
set(RATIO9_BUILD_ID "ratio9-${PROJECT_VERSION}-${RATIO9_BUILD_ID_TAG}")

# Development candidates can bind every Ratio9-managed content/settings path
# to a disposable root. Public builds must leave this empty.
set(RATIO9_ISOLATED_RUNTIME_ROOT "" CACHE PATH "Disposable content/settings root for validation candidates")
# The public source omits the private isolated validation app,
# Source/IsolatedStandaloneApp.cpp (derived from JUCE; no shipping build uses
# it). Asking for that mode, through an isolated runtime root or native
# capture, stops here. Normal builds never reach this error.
if ((NOT "${RATIO9_ISOLATED_RUNTIME_ROOT}" STREQUAL "" OR ENVFM_ENABLE_NATIVE_CAPTURE)
    AND NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/Source/IsolatedStandaloneApp.cpp")
    message(FATAL_ERROR
        "RATIO9_ISOLATED_RUNTIME_ROOT and ENVFM_ENABLE_NATIVE_CAPTURE select the private isolated "
        "validation build, which needs Source/IsolatedStandaloneApp.cpp. That JUCE-derived harness is "
        "not part of the public Ratio9 source. Leave RATIO9_ISOLATED_RUNTIME_ROOT empty and "
        "ENVFM_ENABLE_NATIVE_CAPTURE OFF to build Ratio9.")
endif()
if (NOT "${RATIO9_ISOLATED_RUNTIME_ROOT}" STREQUAL "")
    if (NOT IS_ABSOLUTE "${RATIO9_ISOLATED_RUNTIME_ROOT}")
        message(FATAL_ERROR "The isolated runtime root must be absolute")
    endif()
    add_compile_definitions(RATIO9_ISOLATED_RUNTIME_ROOT="${RATIO9_ISOLATED_RUNTIME_ROOT}")
endif()

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

include(FetchContent)

option(ENVFM_ENABLE_RT_DIAGNOSTICS
       "Enable Ratio9's fixed-size real-time diagnostic telemetry" OFF)
option(ENVFM_ENABLE_NATIVE_CAPTURE
       "Compile the isolated Standalone playback recorder (explicit launch opt-in required)" OFF)
if (ENVFM_ENABLE_NATIVE_CAPTURE)
    if ("${RATIO9_ISOLATED_RUNTIME_ROOT}" STREQUAL "" OR NOT APPLE)
        message(FATAL_ERROR "Native capture requires an isolated macOS validation root")
    endif()
    if (NOT ENVFM_ENABLE_RT_DIAGNOSTICS)
        message(FATAL_ERROR "Native capture requires existing callback diagnostics")
    endif()
    add_compile_definitions(ENVFM_ENABLE_NATIVE_CAPTURE=1)
endif()

# DOWNLOAD_EXTRACT_TIMESTAMP exists from CMake 3.24. CMake 3.22 and 3.23 would
# read it as part of URL_HASH and stop; they already keep the archive's
# timestamps, which is what TRUE asks for.
set(RATIO9_JUCE_FETCH_OPTIONS "")
if (CMAKE_VERSION VERSION_GREATER_EQUAL 3.24)
    list(APPEND RATIO9_JUCE_FETCH_OPTIONS DOWNLOAD_EXTRACT_TIMESTAMP TRUE)
endif()
FetchContent_Declare(
    JUCE
    URL https://github.com/juce-framework/JUCE/archive/refs/tags/8.0.14.tar.gz
    URL_HASH SHA256=ceb18e4ac9ab5ea71f3f20240d5852707767a1789ab43d06656a296da9e62f3e
    ${RATIO9_JUCE_FETCH_OPTIONS}
)
FetchContent_MakeAvailable(JUCE)

# Avoid embedding developer checkout locations through __FILE__ or debug info.
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
    add_compile_options(
        "-ffile-prefix-map=${CMAKE_CURRENT_SOURCE_DIR}=Ratio9"
        "-ffile-prefix-map=${CMAKE_CURRENT_BINARY_DIR}=Ratio9Build"
        "-ffile-prefix-map=${juce_SOURCE_DIR}=JUCE")
endif()

option(RATIO9_ENABLE_LIVE_CONTROL "Include local AI controls in Ratio9 (Standalone, VST3 and AU)" ON)
set(ENVFM_LIVE_CONTROL_SOURCES
    Source/LiveControlTransport.cpp Source/LiveControlTransport.h
    Source/LiveControlService.cpp Source/LiveControlService.h
    Source/LiveControlAudition.cpp Source/LiveControlAudition.h
    Source/LiveControlCoordinator.cpp Source/LiveControlCoordinator.h
    Source/LiveControlUiState.h
    Source/AiOnboarding.cpp Source/AiOnboarding.h)

set(ENVFM_SOURCES
    Source/Ratio9Module.cpp
    Source/Ratio9Module.h
    Source/BankReview.cpp
    Source/BankReview.h
    Source/BankReviewFileIO.h
    Source/Ahdsr.cpp
    Source/Ahdsr.h
    Source/DiagnosticStemCapture.cpp
    Source/DiagnosticStemCapture.h
    Source/FilterDSP.cpp
    Source/FilterDSP.h
    Source/CoreFilterDSP.cpp
    Source/CoreFilterDSP.h
    Source/MeasuredCoreFilters.cpp
    Source/MeasuredCoreFilters.h
    Source/MeasuredLadderFilters.cpp
    Source/MeasuredLadderFilters.h
    Source/MeasuredMotionFilters.cpp
    Source/MeasuredMotionFilters.h
    Source/MeasuredCharacterFilters.cpp
    Source/MeasuredCharacterFilters.h
    Source/MeasuredCharacterNonlinear.cpp
    Source/MeasuredCharacterNonlinear.h
    Source/MeasuredCharacterGenerators.cpp
    Source/MeasuredCharacterGenerators.h
    Source/MeasuredCharacterComb2.cpp
    Source/MeasuredCharacterComb2.h
    Source/MeasuredCharacterFormant.cpp
    Source/MeasuredCharacterFormant.h
    Source/MeasuredCharacterDelayBanks.cpp
    Source/MeasuredCharacterDelayBanks.h
    Source/FmInspector.cpp
    Source/FmInspector.h
    Source/FmPreviewEngine.cpp
    Source/FmPreviewEngine.h
    Source/FormantMatrixDSP.cpp
    Source/FormantMatrixDSP.h
    Source/FilterCatalog.cpp
    Source/FilterCatalog.h
    Source/FilterPanel.cpp
    Source/FilterPanel.h
    Source/FxEffectCatalog.cpp
    Source/FxEffectCatalog.h
    Source/FxDeviceCatalog.cpp
    Source/FxDeviceCatalog.h
    Source/FxDeviceState.cpp
    Source/FxDeviceState.h
    Source/FxGraphLayout.cpp
    Source/FxGraphLayout.h
    Source/FxCreativeFamilyState.cpp
    Source/FxCreativeFamilyState.h
    Source/FxCharacterFilterState.cpp
    Source/FxCharacterFilterState.h
    Source/FxImpactDynamicsState.cpp
    Source/FxImpactDynamicsState.h
    Source/FxToneMapDSP.cpp
    Source/FxToneMapDSP.h
    Source/FxToneMapState.cpp
    Source/FxToneMapState.h
    Source/FxFormantMatrixState.cpp
    Source/FxFormantMatrixState.h
    Source/FxImpulseResponse.cpp
    Source/FxImpulseResponse.h
    Source/FxEqualizerDSP.cpp
    Source/FxEqualizerDSP.h
    Source/FxModulationResponse.cpp
    Source/FxModulationResponse.h
    Source/FxBodyResonatorDSP.cpp
    Source/FxBodyResonatorDSP.h
    Source/FxDistortionDSP.cpp
    Source/FxDistortionDSP.h
    Source/FxModulatableControl.cpp
    Source/FxModulatableControl.h
    Source/FxMultiEffectDSP.cpp
    Source/FxMultiEffectDSP.h
    Source/FxTriKillDSP.cpp
    Source/FxTriKillDSP.h
    Source/FxResonatorShape.cpp
    Source/FxResonatorShape.h
    Source/FxSculptDriveState.cpp
    Source/FxSculptDriveState.h
    Source/FxRackComponents.cpp
    Source/FxRackComponents.h
    Source/FxMultibandEditor.cpp
    Source/FxMultibandEditor.h
    Source/FxPage.cpp
    Source/FxPage.h
    Source/FxSpectrumAnalyzer.cpp
    Source/FxSpectrumAnalyzer.h
    Source/LiveInspection.cpp
    Source/LiveInspection.h
    Source/GlobalPage.cpp
    Source/GlobalPage.h
    Source/LfoSourceCard.cpp
    Source/LfoSourceCard.h
    Source/Mseg.cpp
    Source/Mseg.h
    Source/MsegEditing.cpp
    Source/MsegEditing.h
    Source/MsegTools.cpp
    Source/MsegTools.h
    Source/ModulationModes.cpp
    Source/ModulationModes.h
    Source/ModulationMatrix.cpp
    Source/ModulationMatrix.h
    Source/OutputStageDSP.cpp
    Source/OutputStageDSP.h
    Source/MatrixPage.cpp
    Source/MatrixPage.h
    Source/OscWarp.cpp
    Source/OscWarp.h
    Source/OscModulationStrip.cpp
    Source/OscModulationStrip.h
    Source/Parameters.cpp
    Source/Parameters.h
    Source/Ratio9Branding.cpp
    Source/Ratio9Branding.h
    Source/WaveformEditing.cpp
    Source/WaveformEditing.h
    Source/Wavetable.cpp
    Source/WavetableBank.cpp
    Source/WavetableBank.h
    Source/WavetableBankManifest.generated.h
    Source/Wavetable.h
    Source/WavetableSelectionLoader.cpp
    Source/WavetableSelectionLoader.h
    Source/UserWavetableLibrary.cpp
    Source/UserWavetableLibrary.h
    Source/UserWavetableBrowser.cpp
    Source/UserWavetableBrowser.h
    Source/WavetableEditor.cpp
    Source/WavetableEditor.h
    Source/Sampler.cpp
    Source/Sampler.h
    Source/SamplerPanel.cpp
    Source/SamplerPanel.h
    Source/SynthVoice.cpp
    Source/SynthVoice.h
    Source/VoiceRenderWorker.cpp
    Source/VoiceRenderWorker.h
    Source/PluginProcessor.cpp
    Source/PluginProcessor.h
    Source/PresetLibraryIndex.cpp
    Source/PresetLibraryIndex.h
    Source/PresetFileValidation.cpp
    Source/PresetFileValidation.h
    Source/FactoryPresetCatalog.cpp
    Source/FactoryPresetCatalog.h
    Source/PluginEditor.cpp
    Source/PluginEditor.h
)

# Labs is part of every Ratio9 format when RATIO9_ENABLE_LABS is on.
set(ENVFM_AUTHORING_LAB_SOURCES
    Source/BankReviewPanel.cpp
    Source/BankReviewPanel.h
    Source/AuthoringLab.cpp
    Source/AuthoringLab.h
    Source/AuthoringLabEngine.cpp
    Source/AuthoringLabEngine.h
    Source/LiveInspectorComponent.cpp
    Source/LiveInspectorComponent.h
)

# Mugi is an offline developer tool. Keep it out of the real-time plug-in
# target while sharing the production Ratio9 processor, preset, and DSP code.
set(MUGI_SOURCES
    Source/Mugi.h
    Source/MugiIntent.cpp
    Source/MugiPreset.cpp
    Source/MugiAudio.cpp
    Source/MugiRunner.cpp
)

# Standalone always builds; VST3 and AU are an explicit configuration choice.
option(RATIO9_BUILD_HOSTED_PLUGINS "Build VST3 and Audio Unit plug-ins" OFF)
set(RATIO9_HOSTED_FORMATS "VST3;AU" CACHE STRING
    "Hosted formats built when RATIO9_BUILD_HOSTED_PLUGINS is ON: VST3, AU, AAX, LV2 and CLAP as the platform allows, each once")
option(RATIO9_BETA_RELEASE "Use the separate Ratio9 Beta product name and identifiers" OFF)
set(RATIO9_PRODUCT_NAME "Ratio9")
set(RATIO9_BUNDLE_ID "com.ratio9.synth")
set(RATIO9_PLUGIN_CODE Rnio)
if (RATIO9_BETA_RELEASE)
    set(RATIO9_PRODUCT_NAME "Ratio9 Beta")
    set(RATIO9_BUNDLE_ID "com.ratio9.synth.beta")
    # AU and VST3 identities also include this code. A different bundle name
    # alone would collide with the regular Ratio9 plug-in in host caches.
    set(RATIO9_PLUGIN_CODE RnBt)
endif()
# Ratio9 Alpha 1.3.0 has no activation: every format plays immediately and
# needs no licence file, device identity, account or network. The offline
# activation of earlier releases is unchanged in those releases and is not
# part of this source.

if (NOT "${RATIO9_ISOLATED_RUNTIME_ROOT}" STREQUAL "")
    # Validation candidates never shadow the release plug-in in host caches.
    set(RATIO9_PRODUCT_NAME "Ratio9 Validation")
    set(RATIO9_BUNDLE_ID "com.ratio9.synth.validation")
    set(RATIO9_PLUGIN_CODE RnVa)
endif()
# Plug-in bundles carry their own CFBundleIdentifiers; manufacturer/plug-in
# codes (and so AU/VST3 class identities) stay stable.
set(RATIO9_VST3_BUNDLE_ID "${RATIO9_BUNDLE_ID}.vst3")
set(RATIO9_AU_BUNDLE_ID "${RATIO9_BUNDLE_ID}.component")
# R9-PORT o125: identities of the added formats. They derive from the stable
# bundle identifier and product name, so Beta and Validation builds never
# collide with the release. AAX keeps JUCE's default identifier (the bundle
# identifier above) and the unchanged manufacturer and plug-in codes.
set(RATIO9_AAX_BUNDLE_ID "${RATIO9_BUNDLE_ID}.aaxplugin")
set(RATIO9_CLAP_BUNDLE_ID "${RATIO9_BUNDLE_ID}.clap")
set(RATIO9_CLAP_ID "${RATIO9_BUNDLE_ID}")
string(TOLOWER "${RATIO9_PRODUCT_NAME}" RATIO9_LV2_SLUG)
string(REPLACE " " "-" RATIO9_LV2_SLUG "${RATIO9_LV2_SLUG}")
set(RATIO9_LV2_URI "https://ratio9synth.com/lv2/${RATIO9_LV2_SLUG}")
# Plug-ins offer AI only through the shared helper of this installed app.
set(RATIO9_HOSTED_HELPER_APP "/Applications/Ratio9.app" CACHE PATH
    "Ratio9 app whose shared AI helper plug-ins name (isolated validation only may change it)")
if ("${RATIO9_ISOLATED_RUNTIME_ROOT}" STREQUAL ""
    AND NOT "${RATIO9_HOSTED_HELPER_APP}" STREQUAL "/Applications/Ratio9.app")
    message(FATAL_ERROR "Consumer builds must use the installed /Applications/Ratio9.app helper")
endif()
add_compile_definitions(
    RATIO9_STANDALONE_BUNDLE_ID="${RATIO9_BUNDLE_ID}"
    RATIO9_VST3_BUNDLE_ID="${RATIO9_VST3_BUNDLE_ID}"
    RATIO9_AU_BUNDLE_ID="${RATIO9_AU_BUNDLE_ID}"
    RATIO9_HOSTED_HELPER_APP="${RATIO9_HOSTED_HELPER_APP}")
set(RATIO9_PLUGIN_FORMATS Standalone)
if (RATIO9_BUILD_HOSTED_PLUGINS)
    if (ENVFM_ENABLE_NATIVE_CAPTURE)
        message(FATAL_ERROR "Native capture is Standalone only")
    endif()
    # Only the selected hosted formats get a target, a features record and a
    # catalog entry. An empty, unknown or repeated entry stops the configuration.
    set(RATIO9_SELECTED_HOSTED_FORMATS "")
    foreach (hosted_format IN LISTS RATIO9_HOSTED_FORMATS)
        if (NOT hosted_format MATCHES "^(VST3|AU|AAX|LV2|CLAP)$")
            message(FATAL_ERROR "RATIO9_HOSTED_FORMATS accepts only VST3, AU, AAX, LV2 and CLAP, not \"${hosted_format}\"")
        endif()
        # R9-PORT o125: a format this platform lacks stops the configuration.
        if (hosted_format STREQUAL "AU" AND NOT APPLE)
            message(FATAL_ERROR "AU exists on macOS only. Remove it from RATIO9_HOSTED_FORMATS on this platform.")
        endif()
        if (hosted_format STREQUAL "AAX" AND NOT APPLE AND NOT WIN32)
            message(FATAL_ERROR "AAX exists on macOS and Windows only. Remove it from RATIO9_HOSTED_FORMATS on this platform.")
        endif()
        if (hosted_format IN_LIST RATIO9_SELECTED_HOSTED_FORMATS)
            message(FATAL_ERROR "RATIO9_HOSTED_FORMATS names ${hosted_format} more than once")
        endif()
        list(APPEND RATIO9_SELECTED_HOSTED_FORMATS ${hosted_format})
    endforeach()
    if ("${RATIO9_SELECTED_HOSTED_FORMATS}" STREQUAL "")
        message(FATAL_ERROR "RATIO9_BUILD_HOSTED_PLUGINS is ON but RATIO9_HOSTED_FORMATS selects no format")
    endif()
    list(APPEND RATIO9_PLUGIN_FORMATS ${RATIO9_SELECTED_HOSTED_FORMATS})
endif()

# R9-PORT o125: JUCE builds every selected format except CLAP, which the pinned
# free-audio wrapper adds further down from the same EnvFM shared code. Format
# arguments are passed only when their format is selected, so a configuration
# without the added formats reaches juce_add_plugin exactly as before.
set(RATIO9_JUCE_FORMATS ${RATIO9_PLUGIN_FORMATS})
list(REMOVE_ITEM RATIO9_JUCE_FORMATS CLAP)
set(RATIO9_FORMAT_ARGUMENTS "")
if ("LV2" IN_LIST RATIO9_PLUGIN_FORMATS)
    list(APPEND RATIO9_FORMAT_ARGUMENTS LV2URI "${RATIO9_LV2_URI}")
endif()
juce_add_plugin(EnvFM
    COMPANY_NAME "Ratio9"
    COMPANY_COPYRIGHT "Copyright © 2026 the rights holder."
    BUNDLE_ID "${RATIO9_BUNDLE_ID}"
    PLIST_TO_MERGE "<plist><dict><key>LSMinimumSystemVersion</key><string>${CMAKE_OSX_DEPLOYMENT_TARGET}</string><key>CFBundleDisplayName</key><string>${RATIO9_RELEASE_NAME}</string></dict></plist>"
    IS_SYNTH TRUE
    NEEDS_MIDI_INPUT TRUE
    NEEDS_MIDI_OUTPUT FALSE
    IS_MIDI_EFFECT FALSE
    EDITOR_WANTS_KEYBOARD_FOCUS FALSE
    COPY_PLUGIN_AFTER_BUILD FALSE
    PLUGIN_MANUFACTURER_CODE Rati
    PLUGIN_CODE ${RATIO9_PLUGIN_CODE}
    AU_MAIN_TYPE kAudioUnitType_MusicDevice
    FORMATS ${RATIO9_JUCE_FORMATS}
    ${RATIO9_FORMAT_ARGUMENTS}
    PRODUCT_NAME "${RATIO9_PRODUCT_NAME}"
)

juce_generate_juce_header(EnvFM)
# R9-PORT o125: JUCE leaves out a format it cannot build on this platform
# without saying so. Stop instead of producing a configuration that lacks it.
foreach (juce_format IN LISTS RATIO9_JUCE_FORMATS)
    if (NOT TARGET EnvFM_${juce_format})
        message(FATAL_ERROR "This JUCE created no EnvFM_${juce_format} target on this platform. Remove ${juce_format} from RATIO9_HOSTED_FORMATS or supply what it needs.")
    endif()
endforeach()
if (APPLE AND RATIO9_BUILD_HOSTED_PLUGINS)
    # JUCE writes one CFBundleIdentifier for every format. Give each plug-in
    # bundle its own identifier before any signature is applied.
    foreach (format_and_id IN ITEMS "VST3|${RATIO9_VST3_BUNDLE_ID}" "AU|${RATIO9_AU_BUNDLE_ID}")
        string(REPLACE "|" ";" format_and_id "${format_and_id}")
        list(GET format_and_id 0 hosted_format)
        list(GET format_and_id 1 hosted_bundle_id)
        if (NOT hosted_format IN_LIST RATIO9_SELECTED_HOSTED_FORMATS)
            continue()
        endif()
        add_custom_command(TARGET EnvFM_${hosted_format} POST_BUILD
            COMMAND /usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier ${hosted_bundle_id}"
                    "$<TARGET_BUNDLE_DIR:EnvFM_${hosted_format}>/Contents/Info.plist"
            VERBATIM COMMENT "Setting the ${hosted_format} bundle identifier")
    endforeach()
endif()
if (NOT "${RATIO9_ISOLATED_RUNTIME_ROOT}" STREQUAL "")
    target_compile_definitions(EnvFM_Standalone PRIVATE JUCE_USE_CUSTOM_PLUGIN_STANDALONE_APP=1)
    target_sources(EnvFM_Standalone PRIVATE Source/IsolatedStandaloneApp.cpp)
    if (ENVFM_ENABLE_NATIVE_CAPTURE)
        target_sources(EnvFM_Standalone PRIVATE Source/DiagnosticTypingDriver.mm)
        # Keep every existing JUCE/DSP translation unit on its original compiler
        # path. Only this host fixture needs explicit Objective-C++ parsing.
        set_source_files_properties(Source/DiagnosticTypingDriver.mm PROPERTIES
            LANGUAGE CXX COMPILE_FLAGS "-x objective-c++")
    endif()
endif()
target_sources(EnvFM PRIVATE ${ENVFM_SOURCES})
if (RATIO9_ENABLE_LIVE_CONTROL)
    target_sources(EnvFM PRIVATE ${ENVFM_LIVE_CONTROL_SOURCES})
    target_compile_definitions(EnvFM PRIVATE ENVFM_ENABLE_LIVE_CONTROL=1)
endif()
option(RATIO9_ENABLE_LABS "Include Labs in every Ratio9 format" ON)
if (RATIO9_ENABLE_LABS)
    target_sources(EnvFM PRIVATE ${ENVFM_AUTHORING_LAB_SOURCES})
    target_compile_definitions(EnvFM PRIVATE ENVFM_ENABLE_AUTHORING_LAB=1)
endif()
target_include_directories(EnvFM PRIVATE Source)
# R9-PORT o125: non-Apple builds only. Stand-ins for Apple headers that the
# unchanged sources include outside their platform guards. The directory is
# written by the port audit and exists only when it found such includes.
if (NOT APPLE AND IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/Tools/port/compat/include")
    target_include_directories(EnvFM PRIVATE Tools/port/compat/include)
endif()
target_compile_features(EnvFM PRIVATE cxx_std_20)
target_compile_definitions(EnvFM
    PUBLIC
        ENVFM_BUILD_VERSION="${PROJECT_VERSION}"
        ENVFM_RELEASE_CHANNEL="${RATIO9_RELEASE_CHANNEL}"
        ENVFM_RELEASE_NAME="${RATIO9_RELEASE_NAME}"
        ENVFM_BUILD_ID="${RATIO9_BUILD_ID}"
        JUCE_WEB_BROWSER=0
        JUCE_USE_CURL=0
        JUCE_VST3_CAN_REPLACE_VST2=0
        RATIO9_BETA_RELEASE=$<BOOL:${RATIO9_BETA_RELEASE}>
    PRIVATE
        ENVFM_ENABLE_DIAGNOSTIC_STEMS=1
)
if (ENVFM_ENABLE_RT_DIAGNOSTICS)
    target_compile_definitions(EnvFM PRIVATE ENVFM_ENABLE_RT_DIAGNOSTICS=1)
endif()
target_link_libraries(EnvFM
    PRIVATE
        juce::juce_audio_utils
        juce::juce_dsp
        juce::juce_cryptography
    PUBLIC
        juce::juce_recommended_config_flags
        juce::juce_recommended_warning_flags
)

# R9-PORT o125: CLAP comes from the free-audio wrapper around the same EnvFM
# shared code as every JUCE format. The wrapper is a pinned local checkout with
# its submodules (Tools/port/ratio9_port.py deps). Configuring downloads nothing.
if ("CLAP" IN_LIST RATIO9_PLUGIN_FORMATS)
    set(RATIO9_CLAP_JUCE_EXTENSIONS_DIR "" CACHE PATH
        "Pinned free-audio/clap-juce-extensions checkout, submodules included")
    if (NOT EXISTS "${RATIO9_CLAP_JUCE_EXTENSIONS_DIR}/cmake/ClapTargetHelpers.cmake"
        OR NOT EXISTS "${RATIO9_CLAP_JUCE_EXTENSIONS_DIR}/clap-libs/clap/include/clap/clap.h"
        OR NOT EXISTS "${RATIO9_CLAP_JUCE_EXTENSIONS_DIR}/clap-libs/clap-helpers/CMakeLists.txt")
        message(FATAL_ERROR "CLAP needs RATIO9_CLAP_JUCE_EXTENSIONS_DIR to name the pinned clap-juce-extensions checkout with its submodules (Tools/port/ratio9_port.py deps).")
    endif()
    if (CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
        add_compile_options("-ffile-prefix-map=${RATIO9_CLAP_JUCE_EXTENSIONS_DIR}=clap-juce-extensions")
    endif()
    add_subdirectory("${RATIO9_CLAP_JUCE_EXTENSIONS_DIR}"
                     "${CMAKE_CURRENT_BINARY_DIR}/clap-juce-extensions" EXCLUDE_FROM_ALL)
    # A stereo instrument and nothing more. Note ports and dialects are reported
    # by the wrapper from the processor's own MIDI and MPE answers.
    clap_juce_extensions_plugin(TARGET EnvFM
        CLAP_ID "${RATIO9_CLAP_ID}"
        CLAP_FEATURES instrument synthesizer stereo)
    if (NOT TARGET EnvFM_CLAP)
        message(FATAL_ERROR "The CLAP wrapper created no EnvFM_CLAP target.")
    endif()
    # R9-PORT o125 delta 02: this rename is seen by the CLAP wrapper sources alone, so
    # every CLAP instance is constructed by the dedicated Ratio9 factory in
    # Source/PluginProcessor.cpp and never by the entry point the other formats use.
    target_compile_definitions(EnvFM_CLAP PRIVATE createPluginFilter=createRatio9ClapPluginFilter)
endif()
if (APPLE)
    # AAX and CLAP bundles get their own CFBundleIdentifier, as VST3 and AU do,
    # before any signature is applied. Plug-in identities are not affected.
    foreach (format_and_id IN ITEMS "AAX|${RATIO9_AAX_BUNDLE_ID}" "CLAP|${RATIO9_CLAP_BUNDLE_ID}")
        string(REPLACE "|" ";" format_and_id "${format_and_id}")
        list(GET format_and_id 0 added_format)
        list(GET format_and_id 1 added_bundle_id)
        if (NOT added_format IN_LIST RATIO9_PLUGIN_FORMATS)
            continue()
        endif()
        add_custom_command(TARGET EnvFM_${added_format} POST_BUILD
            COMMAND /usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier ${added_bundle_id}"
                    "$<TARGET_BUNDLE_DIR:EnvFM_${added_format}>/Contents/Info.plist"
            VERBATIM COMMENT "Setting the ${added_format} bundle identifier")
    endforeach()
endif()
# Production products use the external content library. The legacy bank is an
# explicit test fixture only; it is never embedded in Standalone or Bridge.
set(RATIO9_WAVETABLE_BANK_ROOT "" CACHE PATH "Optional verified legacy bank for regression fixtures only")
find_package(Python3 REQUIRED COMPONENTS Interpreter)

if (APPLE AND RATIO9_ENABLE_LIVE_CONTROL)
    add_executable(Ratio9AIHelper Tools/consumer_ai/launcher.c)
    set_target_properties(Ratio9AIHelper PROPERTIES OUTPUT_NAME "ratio9-ai-helper")
    target_compile_options(Ratio9AIHelper PRIVATE -Wall -Wextra -Werror)
    add_dependencies(EnvFM_Standalone Ratio9AIHelper)
    # A launcher-only change must relink/re-copy/re-sign the enclosing app too.
    set_property(TARGET EnvFM_Standalone APPEND PROPERTY LINK_DEPENDS "$<TARGET_FILE:Ratio9AIHelper>;${CMAKE_CURRENT_SOURCE_DIR}/CMakeLists.txt")
    add_custom_command(TARGET EnvFM_Standalone POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
                "$<TARGET_FILE:Ratio9AIHelper>"
                "$<TARGET_BUNDLE_DIR:EnvFM_Standalone>/Contents/MacOS/ratio9-ai-helper"
        VERBATIM COMMENT "Embedding the fixed local AI helper launcher")
endif()

# R9-PORT o125: where each format keeps bundled resources and what an ad-hoc
# signature covers. macOS bundles keep the paths used so far. Other layouts use
# the nearest equivalent inside the product, or beside a single-file product.
set(RATIO9_TARGET_ARCHITECTURE "${CMAKE_OSX_ARCHITECTURES}")
if (NOT APPLE)
    set(RATIO9_TARGET_ARCHITECTURE "${CMAKE_SYSTEM_PROCESSOR}")
    if (MSVC)
        set(RATIO9_TARGET_ARCHITECTURE "${CMAKE_CXX_COMPILER_ARCHITECTURE_ID}")
    endif()
endif()
foreach (format IN LISTS RATIO9_PLUGIN_FORMATS)
    if (APPLE AND NOT format STREQUAL "LV2")
        set(RATIO9_RESOURCES_DIR_${format} "$<TARGET_BUNDLE_DIR:EnvFM_${format}>/Contents/Resources")
        set(RATIO9_SIGN_PATH_${format} "$<TARGET_BUNDLE_DIR:EnvFM_${format}>")
    elseif (format STREQUAL "LV2")
        set(RATIO9_RESOURCES_DIR_${format} "$<TARGET_FILE_DIR:EnvFM_${format}>/Resources")
        set(RATIO9_SIGN_PATH_${format} "$<TARGET_FILE:EnvFM_${format}>")
    elseif (format STREQUAL "VST3" OR format STREQUAL "AAX")
        set(RATIO9_RESOURCES_DIR_${format} "$<TARGET_FILE_DIR:EnvFM_${format}>/../Resources")
    else()
        set(RATIO9_RESOURCES_DIR_${format} "$<TARGET_FILE_DIR:EnvFM_${format}>/${RATIO9_PRODUCT_NAME}-resources")
    endif()
endforeach()
# Package inspection can verify the configured product features without relying
# on its display name. This contains no developer paths or live credentials.
# Every bundle records its own format and identifier; build_id is shared.
set(RATIO9_FEATURE_AI false)
set(RATIO9_FEATURE_LABS false)
set(RATIO9_FEATURE_ISOLATED false)
if (RATIO9_ENABLE_LIVE_CONTROL)
    set(RATIO9_FEATURE_AI true)
endif()
if (RATIO9_ENABLE_LABS)
    set(RATIO9_FEATURE_LABS true)
endif()
if (NOT "${RATIO9_ISOLATED_RUNTIME_ROOT}" STREQUAL "")
    set(RATIO9_FEATURE_ISOLATED true)
endif()
set(RATIO9_FORMATS_JSON "")
foreach (format IN LISTS RATIO9_PLUGIN_FORMATS)
    if (NOT "${RATIO9_FORMATS_JSON}" STREQUAL "")
        string(APPEND RATIO9_FORMATS_JSON ", ")
    endif()
    string(APPEND RATIO9_FORMATS_JSON "\"${format}\"")
endforeach()
foreach (format IN LISTS RATIO9_PLUGIN_FORMATS)
    if (format STREQUAL "VST3")
        set(format_bundle_id "${RATIO9_VST3_BUNDLE_ID}")
    elseif (format STREQUAL "AU")
        set(format_bundle_id "${RATIO9_AU_BUNDLE_ID}")
    elseif (format STREQUAL "AAX")
        set(format_bundle_id "${RATIO9_AAX_BUNDLE_ID}")
    elseif (format STREQUAL "CLAP")
        set(format_bundle_id "${RATIO9_CLAP_BUNDLE_ID}")
    elseif (format STREQUAL "LV2")
        # R9-PORT o125: an LV2 bundle is identified by its URI.
        set(format_bundle_id "${RATIO9_LV2_URI}")
    else()
        set(format_bundle_id "${RATIO9_BUNDLE_ID}")
    endif()
    file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/build-features/${format}/ratio9-build-features.json" CONTENT
"{\n  \"schema\": 1,\n  \"product\": \"${RATIO9_PRODUCT_NAME}\",\n  \"version\": \"${PROJECT_VERSION}\",\n  \"release_channel\": \"${RATIO9_RELEASE_CHANNEL}\",\n  \"release_name\": \"${RATIO9_RELEASE_NAME}\",\n  \"build_id\": \"${RATIO9_BUILD_ID}\",\n  \"format\": \"${format}\",\n  \"bundle_id\": \"${format_bundle_id}\",\n  \"formats\": [${RATIO9_FORMATS_JSON}],\n  \"labs\": ${RATIO9_FEATURE_LABS},\n  \"live_ai\": ${RATIO9_FEATURE_AI},\n  \"isolated_validation\": ${RATIO9_FEATURE_ISOLATED},\n  \"architecture\": \"${RATIO9_TARGET_ARCHITECTURE}\",\n  \"minimum_macos\": \"${CMAKE_OSX_DEPLOYMENT_TARGET}\"\n}\n")
    add_custom_command(TARGET EnvFM_${format} POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E make_directory
                "${RATIO9_RESOURCES_DIR_${format}}"
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
                "${CMAKE_CURRENT_BINARY_DIR}/build-features/${format}/ratio9-build-features.json"
                "${RATIO9_RESOURCES_DIR_${format}}/ratio9-build-features.json"
        VERBATIM COMMENT "Recording the complete Ratio9 ${format} configuration")
endforeach()

# Private-build convenience only: a hosted-module catalog generated from the
# built plug-ins. The release assembler regenerates it from the post-sign
# bundles and seals it inside the app; nothing here installs or trusts it.
if (RATIO9_BUILD_HOSTED_PLUGINS)
    set(RATIO9_CATALOG_BUNDLE_ARGUMENTS "")
    set(RATIO9_CATALOG_TARGETS "")
    foreach (hosted_format IN LISTS RATIO9_SELECTED_HOSTED_FORMATS)
        # R9-PORT o125: the catalog tool covers the macOS VST3 and AU bundles only.
        if (NOT APPLE OR NOT hosted_format MATCHES "^(VST3|AU)$")
            continue()
        endif()
        string(TOLOWER "${hosted_format}" hosted_option)
        list(APPEND RATIO9_CATALOG_BUNDLE_ARGUMENTS
             "--${hosted_option}" "$<TARGET_BUNDLE_DIR:EnvFM_${hosted_format}>")
        list(APPEND RATIO9_CATALOG_TARGETS "EnvFM_${hosted_format}")
    endforeach()
    add_custom_target(Ratio9HostedModuleCatalog
        COMMAND "${Python3_EXECUTABLE}" -I "${CMAKE_CURRENT_SOURCE_DIR}/Tools/release/hosted_module_catalog.py"
                --build-id "${RATIO9_BUILD_ID}"
                ${RATIO9_CATALOG_BUNDLE_ARGUMENTS}
                --output "${CMAKE_CURRENT_BINARY_DIR}/hosted-modules.json"
        DEPENDS ${RATIO9_CATALOG_TARGETS}
        VERBATIM COMMENT "Writing the private hosted-module catalog")
endif()

function(ratio9_copy_test_bank target destination)
    if (NOT EXISTS "${RATIO9_WAVETABLE_BANK_ROOT}/manifest.json")
        message(FATAL_ERROR "Tests require RATIO9_WAVETABLE_BANK_ROOT for retained legacy fixture coverage")
    endif()
    add_custom_command(TARGET ${target} POST_BUILD
        COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/Tools/WavetableBankAssets.py"
                package --root "${RATIO9_WAVETABLE_BANK_ROOT}"
                --source-dir "${CMAKE_CURRENT_SOURCE_DIR}/Source"
                --destination "${destination}"
        VERBATIM COMMENT "Packaging exact legacy regression fixtures for ${target}")
endfunction()

# Keep the legal terms inside every built bundle. Release archives also place
# copies beside the bundle so recipients can read them before installation.
set(RATIO9_THIRD_PARTY_LICENSE_FILES
    Apache-2.0.txt FLAC-BSD.txt HarfBuzz-Old-MIT.txt HarfBuzz-fasthash-MIT.txt
    IJG-JPEG-LICENSE.txt Ogg-Vorbis-BSD.txt Unicode-License-v3.txt
    VST3-SDK-MIT.txt libpng-LICENSE.txt zlib-LICENSE.txt
    CLAP.txt CLAP-helpers.txt CLAP-wrapper.txt
    LV2-lilv.txt LV2-lv2.txt LV2-serd.txt LV2-sord.txt LV2-sratom.txt)
foreach (format IN LISTS RATIO9_PLUGIN_FORMATS)
    set(format_target "EnvFM_${format}")
    add_custom_command (TARGET ${format_target} POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E make_directory
                "${RATIO9_RESOURCES_DIR_${format}}"
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
                "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE"
                "${RATIO9_RESOURCES_DIR_${format}}/Ratio9-LICENSE.txt"
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
                "${CMAKE_CURRENT_SOURCE_DIR}/COPYRIGHT.md"
                "${RATIO9_RESOURCES_DIR_${format}}/Ratio9-COPYRIGHT.md"
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
                "${CMAKE_CURRENT_SOURCE_DIR}/THIRD_PARTY_NOTICES.md"
                "${RATIO9_RESOURCES_DIR_${format}}/THIRD-PARTY-NOTICES.md"
        VERBATIM
        COMMENT "Embedding Ratio9 legal notices in ${format_target}"
    )
    foreach (license_file IN LISTS RATIO9_THIRD_PARTY_LICENSE_FILES)
        add_custom_command (TARGET ${format_target} POST_BUILD
            COMMAND ${CMAKE_COMMAND} -E make_directory
                    "${RATIO9_RESOURCES_DIR_${format}}/legal/notices"
            COMMAND ${CMAKE_COMMAND} -E copy_if_different
                    "${CMAKE_CURRENT_SOURCE_DIR}/legal/notices/${license_file}"
                    "${RATIO9_RESOURCES_DIR_${format}}/legal/notices/${license_file}"
            VERBATIM)
    endforeach()
endforeach()

option(ENVFM_ADHOC_SIGN "Ad-hoc sign completed macOS bundles for local use" ON)
option(RATIO9_HARDENED_RUNTIME "Enable Hardened Runtime on local macOS candidate signatures" ON)

# Ad-hoc sign every completed macOS bundle for local beta testing. Disable this
# when a release pipeline will apply Developer ID and Installer signatures.
if (APPLE AND ENVFM_ADHOC_SIGN)
    set(RATIO9_SIGN_RUNTIME_OPTIONS)
    if (RATIO9_HARDENED_RUNTIME)
        list(APPEND RATIO9_SIGN_RUNTIME_OPTIONS --options runtime)
    endif()
    foreach (format IN LISTS RATIO9_PLUGIN_FORMATS)
        set(format_target "EnvFM_${format}")
        if (format STREQUAL "Standalone" AND RATIO9_ENABLE_LIVE_CONTROL)
            add_custom_command (TARGET ${format_target} POST_BUILD
                COMMAND /usr/bin/codesign --force --sign - --timestamp=none ${RATIO9_SIGN_RUNTIME_OPTIONS}
                        "$<TARGET_BUNDLE_DIR:${format_target}>/Contents/MacOS/ratio9-ai-helper"
                VERBATIM COMMENT "Ad-hoc signing the fixed AI helper launcher")
        endif()
        add_custom_command (TARGET ${format_target} POST_BUILD
            COMMAND /usr/bin/codesign --force --sign - --timestamp=none ${RATIO9_SIGN_RUNTIME_OPTIONS}
                    "${RATIO9_SIGN_PATH_${format}}"
            VERBATIM
            COMMENT "Ad-hoc signing completed ${format_target} bundle"
        )
    endforeach()
endif()

# Optional developer benchmark hook. The source path is supplied explicitly so
# production builds remain unchanged while a retained probe can be rebuilt
# against the exact current Ratio9 engine sources.
set(ENVFM_UNISON_PROBE_SOURCE "" CACHE FILEPATH
    "Optional source file for the Ratio9 polyphonic-unison deadline probe")
if (NOT "${ENVFM_UNISON_PROBE_SOURCE}" STREQUAL "")
    juce_add_console_app(Ratio9UnisonProbe
        PRODUCT_NAME "ratio9_unison_probe")
    set_target_properties(Ratio9UnisonProbe PROPERTIES
        OUTPUT_NAME "ratio9_unison_probe")
    juce_generate_juce_header(Ratio9UnisonProbe)
    target_sources(Ratio9UnisonProbe PRIVATE
        ${ENVFM_SOURCES}
        ${ENVFM_UNISON_PROBE_SOURCE})
    if (APPLE)
        # The retained probe constructs a macOS os_workgroup for a faithful
        # host-audio scheduling test. Compile only that optional source as
        # Objective-C++ so its opaque handle has the same ABI as JUCE's native
        # AudioWorkgroup implementation.
        set_source_files_properties(${ENVFM_UNISON_PROBE_SOURCE}
            PROPERTIES COMPILE_OPTIONS "-x;objective-c++")
    endif()
    target_include_directories(Ratio9UnisonProbe PRIVATE Source)
    target_compile_features(Ratio9UnisonProbe PRIVATE cxx_std_20)
    target_compile_definitions(Ratio9UnisonProbe
        PUBLIC
            ENVFM_BUILD_VERSION="${PROJECT_VERSION}"
        ENVFM_RELEASE_CHANNEL="${RATIO9_RELEASE_CHANNEL}"
        ENVFM_RELEASE_NAME="${RATIO9_RELEASE_NAME}"
        ENVFM_BUILD_ID="${RATIO9_BUILD_ID}"
            JUCE_WEB_BROWSER=0
            JUCE_USE_CURL=0
            JUCE_VST3_CAN_REPLACE_VST2=0
            ENVFM_ENABLE_TEST_HOOKS=1)
    if (ENVFM_ENABLE_RT_DIAGNOSTICS)
        target_compile_definitions(Ratio9UnisonProbe PRIVATE
            ENVFM_ENABLE_RT_DIAGNOSTICS=1)
    endif()
    target_link_libraries(Ratio9UnisonProbe
        PRIVATE
            juce::juce_audio_formats
            juce::juce_audio_utils
            juce::juce_dsp
            juce::juce_cryptography
        PUBLIC
            juce::juce_recommended_config_flags
            juce::juce_recommended_warning_flags)
endif()

option(ENVFM_BUILD_MUGI "Build the offline Mugi preset designer" ON)

if (ENVFM_BUILD_MUGI)
    juce_add_console_app(MugiGenerate PRODUCT_NAME "mugi_generate")
    set_target_properties(MugiGenerate PROPERTIES OUTPUT_NAME "mugi_generate")
    juce_generate_juce_header(MugiGenerate)
    target_sources(MugiGenerate PRIVATE
        ${ENVFM_SOURCES}
        ${MUGI_SOURCES}
        Tools/MugiGenerate.cpp)
    target_include_directories(MugiGenerate PRIVATE Source)
    target_compile_features(MugiGenerate PRIVATE cxx_std_20)
    target_compile_definitions(MugiGenerate
        PUBLIC
            ENVFM_BUILD_VERSION="${PROJECT_VERSION}"
        ENVFM_RELEASE_CHANNEL="${RATIO9_RELEASE_CHANNEL}"
        ENVFM_RELEASE_NAME="${RATIO9_RELEASE_NAME}"
        ENVFM_BUILD_ID="${RATIO9_BUILD_ID}"
            JUCE_WEB_BROWSER=0
            JUCE_USE_CURL=0
            JUCE_VST3_CAN_REPLACE_VST2=0
    )
    target_link_libraries(MugiGenerate
        PRIVATE
            juce::juce_audio_formats
            juce::juce_audio_utils
            juce::juce_dsp
            juce::juce_cryptography
        PUBLIC
            juce::juce_recommended_config_flags
            juce::juce_recommended_warning_flags
    )
endif()

option(ENVFM_BUILD_MUGI_BRIDGE
       "Build the external Mugi JSON Lines developer bridge" ON)

if (ENVFM_BUILD_MUGI_BRIDGE)
    juce_add_console_app(Ratio9MugiBridge PRODUCT_NAME "ratio9_mugi_bridge")
    set_target_properties(Ratio9MugiBridge PROPERTIES
        OUTPUT_NAME "ratio9_mugi_bridge")
    juce_generate_juce_header(Ratio9MugiBridge)
    target_sources(Ratio9MugiBridge PRIVATE
        ${ENVFM_SOURCES}
        Source/AuthoringLabEngine.cpp
        Source/AuthoringLabEngine.h
        Tools/MugiBridgeProtocol.cpp
        Tools/MugiBridgeProtocol.h
        Tools/MugiBridgeCatalog.cpp
        Tools/MugiBridgeCatalog.h
        Tools/MugiBridgePatch.cpp
        Tools/MugiBridgePatch.h
        Tools/MugiBridgeDiagnostic.cpp
        Tools/MugiBridgeDiagnostic.h
        Tools/MugiBridgeLab.cpp
        Tools/MugiBridgeLab.h
        Tools/MugiBridgeBankReview.cpp
        Tools/MugiBridgeBankReview.h
        Tools/MugiBridgeRender.cpp
        Tools/MugiBridgeRender.h
        Tools/MugiBridgeSession.cpp
        Tools/MugiBridgeSession.h
        Tools/MugiBridge.cpp)
    target_include_directories(Ratio9MugiBridge PRIVATE Source Tools)
    target_compile_features(Ratio9MugiBridge PRIVATE cxx_std_20)
    target_compile_definitions(Ratio9MugiBridge
        PUBLIC
            ENVFM_BUILD_VERSION="${PROJECT_VERSION}"
        ENVFM_RELEASE_CHANNEL="${RATIO9_RELEASE_CHANNEL}"
        ENVFM_RELEASE_NAME="${RATIO9_RELEASE_NAME}"
        ENVFM_BUILD_ID="${RATIO9_BUILD_ID}"
            JUCE_WEB_BROWSER=0
            JUCE_USE_CURL=0
            JUCE_VST3_CAN_REPLACE_VST2=0
        PRIVATE
            ENVFM_ENABLE_DIAGNOSTIC_STEMS=1
            ENVFM_ENABLE_MUGI_SESSION=1
            ENVFM_ENABLE_RT_DIAGNOSTICS=1
    )
    target_link_libraries(Ratio9MugiBridge
        PRIVATE
            juce::juce_audio_formats
            juce::juce_audio_utils
            juce::juce_cryptography
            juce::juce_dsp
        PUBLIC
            juce::juce_recommended_config_flags
            juce::juce_recommended_warning_flags
    )
endif()

# The 1.2.x unit-test runner still exercises the activation module that Alpha
# 1.3.0 removed; it stays off until that suite is ported.
option(ENVFM_BUILD_TESTS "Build the EnvFM DSP and state tests" OFF)
option(ENVFM_TESTS_ENABLE_ASAN
       "Build EnvFMTests with AddressSanitizer instrumentation" OFF)
option(ENVFM_TESTS_ENABLE_UBSAN
       "Build EnvFMTests with UndefinedBehaviorSanitizer instrumentation" OFF)
option(ENVFM_ENABLE_UNISON_LAYOUT_COUNTERS
       "Enable test-only global-unison layout cache counters" OFF)
option(ENVFM_ENABLE_VOICE_MICROPROFILE
       "Enable test-only per-voice microprofiling instrumentation" OFF)
option(ENVFM_ENABLE_VOICE_MICROPROFILE_ACTIVITY
       "Enable test-only per-voice microprofile call, byte, and lifecycle counters" OFF)

if (ENVFM_ENABLE_VOICE_MICROPROFILE_ACTIVITY
    AND NOT ENVFM_ENABLE_VOICE_MICROPROFILE)
    message(FATAL_ERROR
        "ENVFM_ENABLE_VOICE_MICROPROFILE_ACTIVITY requires ENVFM_ENABLE_VOICE_MICROPROFILE")
endif()

if (ENVFM_TESTS_ENABLE_ASAN AND ENVFM_TESTS_ENABLE_UBSAN)
    message(FATAL_ERROR
        "Configure ASan and UBSan in separate build directories so each test run has one sanitizer")
endif()

if (ENVFM_BUILD_TESTS)
    message(FATAL_ERROR "EnvFMTests still covers the activation module removed in Ratio9 Alpha 1.3.0; port Tests/ before enabling it")
    enable_testing()
    juce_add_console_app(EnvFMTests PRODUCT_NAME "Ratio9 Tests")
    juce_generate_juce_header(EnvFMTests)
    target_sources(EnvFMTests PRIVATE
        ${ENVFM_SOURCES}
        ${ENVFM_AUTHORING_LAB_SOURCES}
        ${MUGI_SOURCES}
        Tools/MugiBridgeProtocol.cpp
        Tools/MugiBridgeProtocol.h
        Tools/MugiBridgeCatalog.cpp
        Tools/MugiBridgeCatalog.h
        Tools/MugiBridgePatch.cpp
        Tools/MugiBridgePatch.h
        Tools/MugiBridgeDiagnostic.cpp
        Tools/MugiBridgeDiagnostic.h
        Tools/MugiBridgeLab.cpp
        Tools/MugiBridgeLab.h
        Tools/MugiBridgeBankReview.cpp
        Tools/MugiBridgeBankReview.h
        Tools/MugiBridgeRender.cpp
        Tools/MugiBridgeRender.h
        Tools/MugiBridgeSession.cpp
        Tools/MugiBridgeSession.h
        Tests/EnvFMTests.cpp)
    if (RATIO9_ENABLE_LIVE_CONTROL)
        target_sources(EnvFMTests PRIVATE ${ENVFM_LIVE_CONTROL_SOURCES})
        target_compile_definitions(EnvFMTests PRIVATE ENVFM_ENABLE_LIVE_CONTROL=1)
    endif()
    if (APPLE)
        # Test-runner-only headless guard; inert unless RATIO9_TEST_HEADLESS=1.
        target_sources(EnvFMTests PRIVATE Tests/HeadlessTestGuard.mm)
        set_source_files_properties(Tests/HeadlessTestGuard.mm PROPERTIES
            LANGUAGE CXX COMPILE_FLAGS "-x objective-c++ -fno-objc-arc")
    endif()
    target_include_directories(EnvFMTests PRIVATE Source Tools)
    target_compile_features(EnvFMTests PRIVATE cxx_std_20)
    target_compile_definitions(EnvFMTests
        PUBLIC
            ENVFM_BUILD_VERSION="${PROJECT_VERSION}"
        ENVFM_RELEASE_CHANNEL="${RATIO9_RELEASE_CHANNEL}"
        ENVFM_RELEASE_NAME="${RATIO9_RELEASE_NAME}"
        ENVFM_BUILD_ID="${RATIO9_BUILD_ID}"
            JUCE_WEB_BROWSER=0
            JUCE_USE_CURL=0
            JUCE_PLUGINHOST_VST3=1
            ENVFM_ENABLE_TEST_HOOKS=1
            ENVFM_ENABLE_AUTHORING_LAB=1
            ENVFM_ENABLE_DIAGNOSTIC_STEMS=1
            ENVFM_ENABLE_MUGI_SESSION=1
            JUCE_MODAL_LOOPS_PERMITTED=1
    )
    if (ENVFM_ENABLE_RT_DIAGNOSTICS)
        target_compile_definitions(EnvFMTests PRIVATE
            ENVFM_ENABLE_RT_DIAGNOSTICS=1)
    endif()
    # Frozen, hash-pinned activation contract fixtures (test runner only).
    target_compile_definitions(EnvFMTests PRIVATE
        RATIO9_ACTIVATION_FIXTURE_DIRECTORY="${CMAKE_CURRENT_SOURCE_DIR}/Tests/fixtures/activation")
    if (ENVFM_ENABLE_UNISON_LAYOUT_COUNTERS)
        target_compile_definitions(EnvFMTests PRIVATE
            ENVFM_ENABLE_UNISON_LAYOUT_COUNTERS=1)
    endif()
    if (ENVFM_ENABLE_VOICE_MICROPROFILE)
        target_compile_definitions(EnvFMTests PRIVATE
            ENVFM_ENABLE_VOICE_MICROPROFILE=1)
    endif()
    if (ENVFM_ENABLE_VOICE_MICROPROFILE_ACTIVITY)
        target_compile_definitions(EnvFMTests PRIVATE
            ENVFM_ENABLE_VOICE_MICROPROFILE_ACTIVITY=1)
    endif()
    target_link_libraries(EnvFMTests
        PRIVATE
            juce::juce_audio_formats
            juce::juce_audio_utils
            juce::juce_cryptography
            juce::juce_dsp
        PUBLIC
            juce::juce_recommended_config_flags
            juce::juce_recommended_warning_flags
    )

    if (ENVFM_TESTS_ENABLE_ASAN OR ENVFM_TESTS_ENABLE_UBSAN)
        if (NOT CMAKE_CXX_COMPILER_ID MATCHES "AppleClang|Clang|GNU")
            message(FATAL_ERROR
                "Ratio9's EnvFMTests sanitizer options require a Clang- or GCC-compatible compiler")
        endif()

        if (ENVFM_TESTS_ENABLE_ASAN)
            target_compile_options(EnvFMTests PRIVATE
                -fsanitize=address
                -fno-omit-frame-pointer)
            target_link_options(EnvFMTests PRIVATE -fsanitize=address)
        endif()

        if (ENVFM_TESTS_ENABLE_UBSAN)
            target_compile_options(EnvFMTests PRIVATE
                -fsanitize=undefined
                -fno-sanitize-recover=all
                -fno-omit-frame-pointer)
            target_link_options(EnvFMTests PRIVATE
                -fsanitize=undefined
                -fno-sanitize-recover=all)
        endif()
    endif()

    add_test(NAME EnvFMTests COMMAND EnvFMTests)
endif()

# Only the test runner receives the frozen historical bank fixture.
if(TARGET EnvFMTests)
    ratio9_copy_test_bank(EnvFMTests "$<TARGET_FILE_DIR:EnvFMTests>/Resources")
endif()
