diff --git a/.deslop.toml b/.deslop.toml new file mode 100644 index 0000000..89a5574 --- /dev/null +++ b/.deslop.toml @@ -0,0 +1,40 @@ +# Deslop configuration for flutter_vst3. +# +# `report_hide` keeps these files in analysis (so "hand-written code duplicates +# a hidden file" is still detectable) but drops clusters whose every occurrence +# is hidden from the actionable report. We use it for the real-time audio and +# FFI-marshalling hot paths: their structural similarity is intrinsic to DSP / +# native-interop code, and extracting "shared" helpers would add per-sample or +# per-block indirection (closures, virtual dispatch, cross-package coupling) on +# the audio thread — a performance cost we refuse to pay. Built-in generated/ +# build excludes still apply; project config only extends them. + +# Measured 5.6% with Deslop 0.38.0 (301/5413 LOC). This ceiling only goes down. +[threshold] +max_duplication_percent = 6.0 + +[defaults] +report_hide = [ + # Freeverb DSP run per-sample in the audio callback. CombFilter.process and + # AllpassFilter.process share a read-buffer / advance-index / return shape but + # are distinct algorithms (comb has dampening + feedback state; allpass is + # -input + bufout). Merging them onto a shared base would cost a virtual call + # per sample inside the inner processStereo loop. + "vsts/flutter_reverb/lib/src/reverb_processor.dart", + + # FFI buffer marshalling: malloc + copy-in + native call + copy-out per audio + # block. The two near-identical copies (process / processStereoF32) live in + # separate packages (dart_vst_graph, dart_vst_host); unifying them would + # couple the packages and add an indirection layer on the buffer path. + "dart_vst_graph/lib/src/bindings.dart", + "dart_vst_host/lib/src/host.dart", + + # Per-audio-block IPC marshalling in the native-compiled processor entry + # points: the cmdProcess case decodes an interleaved Float32 buffer, calls + # processStereo, and re-encodes the response on every block. The reverb and + # echo copies are structurally alike but belong to separate self-contained + # plugin packages; sharing this loop would couple the packages and add + # indirection on the per-block decode/encode path. + "vsts/flutter_reverb/lib/flutter_reverb_processor_exe.dart", + "vsts/echo/lib/echo_processor_exe.dart", +] diff --git a/.devcontainer/README.md b/.devcontainer/README.md index 4dc7183..fc12f11 100644 --- a/.devcontainer/README.md +++ b/.devcontainer/README.md @@ -39,7 +39,7 @@ The container automatically sets: After the container starts, run: ```bash -make check-env +make _check-env ``` This should show all dependencies as available. diff --git a/.github/actions/restore-build/action.yml b/.github/actions/restore-build/action.yml new file mode 100644 index 0000000..5c04b46 --- /dev/null +++ b/.github/actions/restore-build/action.yml @@ -0,0 +1,10 @@ +name: Restore the build +description: Restores what the Build job cached for this OS, and fails if it is missing. +runs: + using: composite + steps: + - uses: actions/cache/restore@v4 + with: + path: ${{ env.BUILD_CACHE_PATHS }} + key: build-${{ runner.os }}-${{ github.sha }}-${{ github.run_id }} + fail-on-cache-miss: true diff --git a/.github/actions/vst3-toolchain/action.yml b/.github/actions/vst3-toolchain/action.yml new file mode 100644 index 0000000..8b5d43f --- /dev/null +++ b/.github/actions/vst3-toolchain/action.yml @@ -0,0 +1,31 @@ +name: VST3 toolchain +description: Installs Ninja and the Linux libraries, and fetches the Steinberg VST3 SDK. +inputs: + runtime-only: + description: Install only what prebuilt binaries need to run. Skips Ninja and the SDK. + default: 'false' +runs: + using: composite + steps: + - name: Install Linux packages + if: runner.os == 'Linux' + shell: bash + run: | + sudo apt-get update + sudo apt-get install -y ninja-build clang cmake pkg-config xvfb \ + libgtk-3-dev libgtkmm-3.0-dev libxtst-dev libx11-dev libgl1-mesa-dri liblzma-dev + - name: Install Ninja on macOS + if: runner.os == 'macOS' && inputs.runtime-only != 'true' + shell: bash + run: brew install ninja + - name: Install Ninja on Windows + if: runner.os == 'Windows' && inputs.runtime-only != 'true' + shell: bash + run: choco install ninja --no-progress -y + - name: Fetch the VST3 SDK + if: inputs.runtime-only != 'true' + shell: bash + run: | + git clone --depth 1 --recursive --shallow-submodules --branch "$VST3_SDK_TAG" \ + https://github.com/steinbergmedia/vst3sdk "$RUNNER_TEMP/vst3sdk" + echo "VST3_SDK_DIR=$RUNNER_TEMP/vst3sdk" >> "$GITHUB_ENV" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..535dc5c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,346 @@ +name: CI + +# Three phases, each once: +# 1. Build: analyze, build every binary the tests run, cache the build. +# 2. Test: run tests in parallel with coverage, on the cached build. +# 3. Coverage: check the collected reports against coverage-thresholds.json. + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + VST3_SDK_TAG: v3.8.1_build_84 + VST3_E2E_BUILD_DIR: build/e2e + VST3_IPC_TEST_BUILD_DIR: ${{ github.workspace }}/build/e2e/ipc + VST3_TEST_PLUGIN: ${{ github.workspace }}/build/e2e/adelay/VST3/Release/adelay.vst3 + BUILD_CACHE_PATHS: | + build/e2e + libdart_vst_* + dart_vst_host/libdart_vst_host.* + dart_vst_host/native/build/libdart_vst_host.* + dart_vst_graph/libdart_vst_graph.* + +jobs: + # Phase 1: build and analyze + + analyze: + name: 'Build: analyze and duplication' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: Nimblesite/Deslop@v0.38.0 + with: + nohtml: true + upload-artifact: false + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + - run: make lint + + build: + name: 'Build: binaries (${{ matrix.os }})' + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + - uses: ./.github/actions/vst3-toolchain + - name: Set up MSVC + if: runner.os == 'Windows' + uses: ilammy/msvc-dev-cmd@v1 + - name: Resolve dependencies + shell: bash + run: for package in flutter_vst3 vsts/echo vsts/flutter_reverb; do (cd "$package" && flutter pub get); done + - name: IPC tests on Windows + if: runner.os == 'Windows' + shell: pwsh + run: ./flutter_vst3/test/native/run.ps1 -Phase build + - name: IPC tests on Linux and macOS + if: runner.os != 'Windows' + run: bash flutter_vst3/test/native/run.sh build + - name: Echo, Reverb, the test hosts and the validator + shell: bash + run: | + bash flutter_vst3/test/native/run_plugin_e2e.sh build + bash flutter_vst3/test/native/run_editor_e2e.sh build + - name: Editor logic test + if: runner.os == 'Linux' + run: bash flutter_vst3/test/native/run_view_logic.sh build + - name: Host and graph libraries, and their ADelay fixture + if: runner.os != 'Windows' + run: | + make native + cmake -S "$VST3_SDK_DIR" -B build/e2e/adelay -DCMAKE_BUILD_TYPE=Release \ + -DSMTG_ENABLE_VSTGUI_SUPPORT=OFF -DSMTG_CREATE_PLUGIN_LINK=OFF -DSMTG_ENABLE_VST3_HOSTING_EXAMPLES=OFF + cmake --build build/e2e/adelay --target adelay --parallel + - name: Drop object files from the cache + shell: bash + run: find build/e2e \( -name '*.o' -o -name '*.obj' \) -delete + - uses: actions/cache/save@v4 + with: + path: ${{ env.BUILD_CACHE_PATHS }} + key: build-${{ runner.os }}-${{ github.sha }}-${{ github.run_id }} + + # Phase 2: test on the cached build + + package-tests: + name: 'Test: ${{ matrix.package }} (${{ matrix.os }})' + needs: [analyze, build] + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + include: + - { package: flutter_vst3, artifact: flutter_vst3, os: ubuntu-latest } + - { package: vsts/echo, artifact: echo, os: ubuntu-latest } + - { package: vsts/flutter_reverb, artifact: flutter_reverb, os: ubuntu-latest } + - { package: dart_vst_host, artifact: dart_vst_host, os: ubuntu-latest } + - { package: dart_vst_host, artifact: dart_vst_host, os: macos-latest } + - { package: dart_vst_graph, artifact: dart_vst_graph, os: ubuntu-latest } + - { package: dart_vst_graph, artifact: dart_vst_graph, os: macos-latest } + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + - uses: ./.github/actions/restore-build + - name: Resolve dependencies + working-directory: ${{ matrix.package }} + run: flutter pub get + - name: Run with coverage + run: bash flutter_vst3/test/native/run_package_coverage.sh ${{ matrix.package }} + - name: Upload coverage + if: runner.os == 'Linux' + uses: actions/upload-artifact@v4 + with: + name: coverage-${{ matrix.artifact }} + path: ${{ matrix.package }}/coverage/lcov.info + retention-days: 1 + if-no-files-found: error + + ipc: + name: 'Test: IPC round trip (${{ matrix.os }})' + needs: [analyze, build] + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/restore-build + - name: Run on Windows + if: runner.os == 'Windows' + shell: pwsh + run: ./flutter_vst3/test/native/run.ps1 -Phase test + - name: Run on Linux and macOS + if: runner.os != 'Windows' + run: bash flutter_vst3/test/native/run.sh test + + view-logic: + name: 'Test: editor logic' + needs: [analyze, build] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/restore-build + - run: bash flutter_vst3/test/native/run_view_logic.sh test + + makefile: + name: 'Test: make test failure propagation' + needs: [analyze, build] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - run: bash dart_vst_host/test/native/harness_test.sh + + plugin-e2e: + name: 'Test: Echo and validator (${{ matrix.os }})' + needs: [analyze, build] + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/vst3-toolchain + with: + runtime-only: 'true' + - uses: ./.github/actions/restore-build + - shell: bash + run: bash flutter_vst3/test/native/run_plugin_e2e.sh test + + editor-e2e: + name: 'Test: Flutter editor in a test host (${{ matrix.os }})' + needs: [analyze, build] + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/vst3-toolchain + with: + runtime-only: 'true' + - uses: ./.github/actions/restore-build + - shell: bash + run: bash flutter_vst3/test/native/run_editor_e2e.sh test + + # The next three test the build itself, so they build in their own trees. + + incremental-build: + name: 'Test: incremental worker rebuild' + needs: [analyze, build] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + - uses: ./.github/actions/vst3-toolchain + - run: bash flutter_vst3/test/native/run_incremental_build.sh + - run: python3 flutter_vst3/test/native/generator_strings_test.py + + windows-public-build: + name: 'Test: Windows public build and deploy' + needs: [analyze, build] + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + - uses: ./.github/actions/vst3-toolchain + - uses: ilammy/msvc-dev-cmd@v1 + - name: Public commands and installed workers + shell: pwsh + run: | + foreach ($target in @('reverb', 'echo', 'deploy')) { + & ./build.bat $target + if ($LASTEXITCODE -ne 0) { throw "build.bat $target failed ($LASTEXITCODE)" } + } + foreach ($plugin in @('echo', 'flutter_reverb')) { + $bundle = "$env:LOCALAPPDATA/Programs/Common/VST3/$plugin.vst3" + if (-not (Test-Path $bundle -PathType Container)) { throw "Missing $bundle" } + $workers = @(Get-ChildItem $bundle -Recurse -Filter "${plugin}_processor.exe") + if ($workers.Count -ne 1) { throw "Expected one installed $plugin worker, got $($workers.Count)" } + } + + editor-mutations: + name: 'Test: editor mutation proof (${{ matrix.os }})' + needs: [analyze, build] + runs-on: ${{ matrix.os }} + timeout-minutes: 120 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + - uses: ./.github/actions/vst3-toolchain + - name: Set up MSVC + if: runner.os == 'Windows' + uses: ilammy/msvc-dev-cmd@v1 + - name: Kill editor mutants + shell: bash + run: bash flutter_vst3/test/native/run_editor_mutations.sh + + repository-rules: + name: 'Test: repository and documentation rules' + needs: [analyze, build] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: subosito/flutter-action@v2 + with: + channel: stable + cache: true + - uses: ./.github/actions/vst3-toolchain + - uses: ./.github/actions/restore-build + - run: make dart-deps + - run: python3 flutter_vst3/test/native/repo_rules_test.py + - run: python3 flutter_vst3/test/native/build_rules_versions_test.py + - run: python3 flutter_vst3/test/native/coverage_check_test.py + - run: python3 flutter_vst3/test/native/build_rules_make_test.py + - run: python3 flutter_vst3/test/native/build_rules_flutter_test.py + - run: python3 flutter_vst3/test/native/docs_commands_test.py + + # Phase 3: check coverage. Runs no tests. + + coverage: + name: 'Coverage: check thresholds' + needs: package-tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: coverage-flutter_vst3 + path: flutter_vst3/coverage + - uses: actions/download-artifact@v4 + with: + name: coverage-echo + path: vsts/echo/coverage + - uses: actions/download-artifact@v4 + with: + name: coverage-flutter_reverb + path: vsts/flutter_reverb/coverage + - uses: actions/download-artifact@v4 + with: + name: coverage-dart_vst_host + path: dart_vst_host/coverage + - uses: actions/download-artifact@v4 + with: + name: coverage-dart_vst_graph + path: dart_vst_graph/coverage + - run: make coverage-check + + ci: + name: CI + if: always() + needs: + - analyze + - build + - package-tests + - ipc + - view-logic + - makefile + - plugin-e2e + - editor-e2e + - incremental-build + - windows-public-build + - editor-mutations + - repository-rules + - coverage + runs-on: ubuntu-latest + steps: + - name: Fail if any required job failed, was cancelled or was skipped + if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped') + run: exit 1 + - name: All required jobs succeeded + run: echo "All required jobs succeeded." diff --git a/.gitignore b/.gitignore index ed6eb77..01c80d3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # Ignore build products build/ +coverage/ .dart_tool/ .idea/ *.iml @@ -9,6 +10,8 @@ node_modules/ *.dll *.so *.dylib +*.lib +*.exp *.zip .DS_Store @@ -17,3 +20,12 @@ vst3sdk/ *.wav vst_plugins/ + + +.deslop-cache/ +.deslop/ + +# Compiled DSP workers and generated Flutter machine configuration +vsts/*/*_processor +vsts/*/*_processor.exe +vsts/*/macos/Flutter/ephemeral/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..c8ff1b6 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,50 @@ +# AGENTS.md + +Steinberg VST® 3 toolkit for Dart and Flutter: build plugins and hosts with no hand-written C++. *VST® is a trademark of Steinberg Media Technologies GmbH.* + +## Workflow +- ❌ subagents, linked worktrees, git hooks. Primary checkout only; git = commit/push. +- **Offload legwork (repetitive, simple work) to pi agents** — exact ids only, in this precedence: `kimi-coding/k3.1-pro-highspeed` → `zai/glm-5.3` → `zai/glm-5.3-flash` → `deepseek/deepseek-flash`. `pi auth check --model ` first; out of credit → tell user, fall to the next. You own their output: review and fix it. +- **Tokens:** check file size before reading, grep first, smallest diff. +- **Entry points = make targets.** `make help` + [`Makefile`](Makefile) first. Each package has its own Makefile; shared rules live in `mk/` and `vsts/plugin.mk`. Targets starting with `_` are private. Windows: `build.bat `. + +## Duplication +- 🐛 **Duplication and superfluous code are bugs** — copies, parallel versions, dead code, stale comments. Fix on sight; move code, ❌ copy it. +- 🛑 Run [deslop](https://deslop.live/docs/for-ai/) before writing (is it already there?) and after (`make deslop`). Install: `brew install nimblesite/tap/deslop`. +- `make deslop` and the CI `duplication` job fail above `max_duplication_percent` in [`.deslop.toml`](.deslop.toml). That ceiling only goes ⬇️. ❌ raise it, or add `exclude`/`report_hide` entries to hide a finding; fix the code. + +## Correctness +- **Fail hard, in the open.** ❌ placeholders, fallbacks, fake values, warnings instead of failures. Not implemented → throw. +- 🛑 **A plugin never takes down the DAW.** ❌ `abort()` in plugin code. Native failures go through the VST3 API: `setActive` returns an error, `process` returns `kNotInitialized` with silence. +- 🛑 **The audio thread never starts a process.** A dead worker restarts at the next activation. +- **Test before fix.** If only one, write the test. A red test is correct: ❌ weaken, skip, delete or drop assertions. + +## Tests +- ✅ E2E tests driving real use cases: many input permutations, many interactions per test, many assertions per interaction. Unit tests only when isolation is needed. +- Tests fail hard: ❌ allowances, printed warnings. +- `make test` runs everything and needs the native libraries, which it builds. Per package: `(cd vsts/echo && flutter test)`. +- Validate built plugins: `./validate_echo.sh`, `./validate_flutter_reverb.sh`. + +## CI +Three phases, each once — ❌ mixing them: +1. **Build** — lint, duplication, build every binary the tests run, cache the build. +2. **Test** — run in parallel with coverage on the cached build, via a script's `test` step. ❌ recompiling, except jobs that test the build itself. +3. **Coverage** — check the reports against [`coverage-thresholds.json`](coverage-thresholds.json). ❌ running tests. Floors only go ⬆️. + +- `make ci` runs the same order. `.github/workflows/ci.yml` has one root `CI` job (`if: always()`, `needs:` every job); a new job goes in its `needs:`. +- ❌ weaken gates or merge red — fix the code. + +## Code +- Files < 400 LOC, tests too. Functions < 20 LOC. +- FP: pure functions, named constants. Classes and mutable state only where Flutter, the VST3 SDK or per-sample DSP state need them. +- **Dart:** ❌ `late`; ❌ `if` — use pattern matching or ternaries; `///` docs on all public functions. +- **Shipped DSP is native machine code:** a `dart compile exe` worker. ❌ `dart run`, JIT, or anything needing an installed Dart SDK. +- Spec IDs: hierarchical slugs (`[GROUP-TOPIC-DETAIL]`), ❌ numbers; cite them in code and tests. + +## Architecture +- **`flutter_vst3/`** — the plugin framework. `native/cmake/VST3Bridge.cmake` provides `add_dart_vst3_plugin`, which generates all C++ from `native/templates/` and a Dart parameter file. New plugin: [`flutter_vst3/create_plugin_guide.md`](flutter_vst3/create_plugin_guide.md). +- **`vsts/`** — self-contained plugins, each building its own `.vst3`: `flutter_reverb`, `echo`. `make deploy` builds both and copies them to the folder VST3 hosts scan; `make deploy-echo` and `make deploy-reverb` do one. Echo's editor is the interactive test UI: `cd vsts/echo && flutter run`. +- **`dart_vst_host/`, `dart_vst_graph/`** — Dart FFI over C++ in each package's `native/`. C APIs: `native/include/dart_vst_host.h`, `native/include/dvh_graph.h`. The graph connects plugin, mixer, splitter and gain nodes. +- **Plugin process model** — read [`docs/FLUTTER_UI_SPEC.md`](docs/FLUTTER_UI_SPEC.md) before touching it. The VST3 module and Flutter editor run in the host; DSP runs in one worker process per instance, over shared memory. +- **Setup:** `make setup` fetches the SDK; `VST3_SDK_DIR` overrides the default `vst3sdk/`. Needs CMake 3.20+, C++17, Dart, Flutter. +- **Linux:** editors embed through X11 only: `GDK_BACKEND=x11 flutter run`. ❌ Wayland. diff --git a/CLAUDE.md b/CLAUDE.md index d4f42e4..eef4bd2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,219 +1 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## Code Rules -- NO PLACEHOLDERS. NO FALLBACKS. FAIL HARD!!! If the code is not implemented, THROW AN ERROR!!! Fail LOUDLY by throwing an exception. -- NO DUPLICATION. Move files, code elements instead of copying them. Search for elements before adding them. -- FP style. No interfaces, classes, or mutable state. Pure functions with no side effects. -- Tests must FAIL HARD. Don't add allowances and print warnings. Just FAIL! -- Keep functions under 20 lines long. -- Do not use Git commands unless explicitly requested -- Keep files under 400 LOC, even tests - -## Dart Rules -- NEVER use the late keyword -- Document all public functions with Dart /// doc, especially the important ones -- Don't use if statements. Use pattern matching or ternaries instead. -- Only native machine code. No AOT or Dart runtime! - - -## Project Overview - -This a Steinberg VST® 3 toolkit for Dart and Flutter. Use this toolkit to implement VST® plugins and VST® hosts. This toolkit enables anyone to create VST® 3 plugins with pure Dart and Flutter. - -*VST® is a trademark of Steinberg Media Technologies GmbH.* - -The main project is flutter_vst3. Use this to create your own VST® 3 plugins with Flutter and Dart. There is also VST3 host and audio graph system written in Dart with native C++ components. The project enables loading VST3 plugins into a customizable audio graph that can be controlled from Dart and Flutter applications. - -Download Steinberg SDK here: -https://www.steinberg.net/vst3sdk -curl -L -o vst3sdk.zip https://www.steinberg.net/vst3sdk - -### Core Components - -1. **dart_vst_host** - High-level Dart bindings for VST® 3 plugin hosting with RAII resource management -2. **dart_vst_graph** - Audio graph system allowing connection of VST® plugins, mixers, splitters, and gain nodes -3. **flutter_vst3** - Complete framework for building VST® 3 plugins with Flutter UI and Dart audio processing (auto-generates ALL C++ from Dart parameter definitions) -4. **flutter_ui** - Desktop Flutter application providing a GUI for the VST host -5. **native/** - C++ implementation of VST3 host and audio graph using Steinberg VST3 SDK -6. **vsts/** - Individual VST plugin packages, each builds its own .vst3 plugin (flutter_reverb, echo) - -### Architecture - -The system uses FFI to bridge Dart and C++. The native library (`libdart_vst_host.dylib/so/dll`) contains both VST host functionality and the audio graph implementation. Dart packages provide high-level APIs that manage native resource lifetimes using RAII patterns. - -The audio graph supports: -- VST3 plugin nodes -- Mixer nodes (multiple stereo inputs → single stereo output) -- Splitter nodes (single stereo input → multiple stereo outputs) -- Gain nodes with dB control -- Arbitrary connections between compatible nodes - -## Build Requirements - -### Prerequisites -- **VST3_SDK_DIR environment variable** must point to Steinberg VST3 SDK root (or use bundled `vst3sdk/` directory) -- CMake 3.20+ -- C++17 compiler -- Dart SDK 3.0+ -- Flutter (for UI component) - -### Build Commands - -**Setup (First time):** -```bash -./setup.sh # Downloads Steinberg VST® 3 SDK and builds native library automatically -``` - -**Primary build targets using Makefile:** -```bash -# Build Flutter Dart Reverb VST3 plugin (default target) -make - -# Build specific plugins -make reverb-vst # Build Flutter Reverb VST3 -make echo-vst # Build Echo VST3 - -# Install to system VST folder -make install - -# Build native library (required for all Dart components) -make native - -# Clean and rebuild -make clean reverb-vst -``` - -**Manual Native Library Build:** -```bash -cd native/ -mkdir build && cd build -cmake .. -make -# Copies libdart_vst_host.dylib to project root for Dart tests -cp libdart_vst_host.dylib ../../ -``` - -**VST3 Plugins (auto-generated from Dart parameter definitions):** -```bash -# Build flutter_reverb plugin -cd vsts/flutter_reverb/ -mkdir build && cd build -cmake .. -make -# Output: flutter_reverb.vst3 bundle - -# Build echo plugin -cd vsts/echo/ -mkdir build && cd build -cmake .. -make -# Output: echo.vst3 bundle -``` - -**Dart Packages:** -```bash -# Install dependencies for all packages -make dart-deps - -# Or manually: -cd dart_vst_host/ && dart pub get -cd dart_vst_graph/ && dart pub get -cd dart_vst3_bridge/ && dart pub get -``` - -**Flutter UI:** -```bash -make flutter-deps -cd flutter_ui/ -flutter run -``` - -## Testing - -**Run all tests:** -```bash -make test -``` - -**Run individual package tests:** -```bash -make test-host # dart_vst_host tests -make test-graph # dart_vst_graph tests - -# Manual test runs: -cd dart_vst_host/ && dart test -cd dart_vst_graph/ && dart test -cd vsts/flutter_reverb/ && dart test -cd vsts/echo/ && dart test -``` - -**Important:** Tests require the native library to be built and present in the working directory. The test framework will fail with a clear error message if `libdart_vst_host.dylib` is missing. - -## VST® 3 Plugin Development (Zero C++ Required) - -The flutter_vst3 framework now auto-generates ALL C++ boilerplate from Dart parameter definitions: - -1. **Define parameters in Dart** with doc comments: -```dart -class ReverbParameters { - /// Controls the size of the reverb space (0% = small room, 100% = large hall) - double roomSize = 0.5; - - /// Controls high frequency absorption (0% = bright, 100% = dark) - double damping = 0.5; -} -``` - -2. **CMake auto-generates C++ files**: -```cmake -add_dart_vst3_plugin(flutter_reverb reverb_parameters.dart - BUNDLE_IDENTIFIER "com.yourcompany.vst3.flutterreverb" - COMPANY_NAME "Your Company" - PLUGIN_NAME "Flutter Reverb" -) -``` - -3. **Generated files** (completely hidden): - - `generated/flutter_reverb_controller.cpp` - - `generated/flutter_reverb_processor.cpp` - - `generated/flutter_reverb_factory.cpp` - - `include/flutter_reverb_ids.h` - -## Key Files - -- `native/include/dart_vst_host.h` - C API for VST hosting -- `native/include/dvh_graph.h` - C API for audio graph -- `dart_vst_host/lib/src/host.dart` - High-level VST host wrapper -- `dart_vst_graph/lib/src/bindings.dart` - FFI bindings and VstGraph class -- `dart_vst3_bridge/native/cmake/VST3Bridge.cmake` - Shared CMake functions for plugin builds -- `vsts/*/CMakeLists.txt` - Individual plugin build configurations -- `flutter_ui/lib/main.dart` - Flutter application entry point -- `Makefile` - Primary build system with all targets -- `setup.sh` - Environment setup script - -## Development Workflow - -1. Run `./setup.sh` for first-time setup (downloads SDK, builds native library) -2. Use `make` to build Flutter Dart Reverb VST3 plugin -3. Use `make test` to run all tests and verify FFI bindings -4. Use Flutter UI (`make run-flutter`) for interactive testing -5. Build individual VST plugins in their respective `vsts/` directories -6. Each plugin package is self-contained and builds its own .vst3 bundle -7. Tests will fail loudly if native dependencies are missing - -## Platform-Specific Notes - -- **macOS:** Outputs `.dylib` and `.vst3` bundle -- **Linux:** Outputs `.so` library -- **Windows:** Outputs `.dll` library -- All platforms require VST3 SDK and appropriate build tools -- Use `make install` to install VST3 plugins to system folders automatically - -## Plugin Validation - -```bash -# Validate built plugins -./validate_echo.sh # Runs VST3 validator on echo plugin -``` \ No newline at end of file +@AGENTS.md \ No newline at end of file diff --git a/GEMINI.md b/GEMINI.md new file mode 120000 index 0000000..47dc3e3 --- /dev/null +++ b/GEMINI.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/Makefile b/Makefile index 413894e..996032c 100644 --- a/Makefile +++ b/Makefile @@ -1,266 +1,78 @@ -# flutter_vst3 Toolkit Makefile -# Builds VST® 3 plugins with Flutter UI and pure Dart audio processing - -.PHONY: all build test clean clean-native clean-plugin help dart-deps flutter-deps reverb-vst install reverb reverb-build-only echo echo-vst echo-build-only echo-deps - -# Default target - build the Flutter Reverb VST® 3 plugin -all: reverb - -# Build all components (host, graph, and reverb VST) -build: native plugin dart-deps flutter-deps reverb-vst - -# Build the Flutter Reverb VST® 3 plugin -reverb: reverb-deps - @echo "Building Flutter Reverb VST® 3 plugin..." - @mkdir -p vsts/flutter_reverb/build - @cd vsts/flutter_reverb/build && cmake -DCMAKE_BUILD_TYPE=Release .. && make -j$(shell nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 1) - @echo "✅ VST® 3 plugin built: vsts/flutter_reverb/build/VST3/Release/flutter_reverb.vst3" - -# Alias for reverb -reverb-vst: reverb - -# Build reverb VST® 3 without installing (explicit build-only target) -reverb-build-only: reverb - -# Build the Echo VST® 3 plugin -echo: echo-deps - @echo "Building Echo VST® 3 plugin..." - @mkdir -p vsts/echo/build - @cd vsts/echo/build && cmake -DCMAKE_BUILD_TYPE=Release .. && make -j$(shell nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo 1) - @echo "✅ VST® 3 plugin built: vsts/echo/build/VST3/Release/echo.vst3" - -# Alias for echo -echo-vst: echo - -# Build echo VST® 3 without installing (explicit build-only target) -echo-build-only: echo - -# Run all tests -test: build - @echo "Running flutter_vst3 tests..." - cd flutter_vst3 && dart test || true - @echo "Running flutter_reverb tests..." - cd vsts/flutter_reverb && dart test || true - @echo "Running echo tests..." - cd vsts/echo && dart test || true - @echo "Running dart_vst_host tests..." - cd dart_vst_host && dart test - @echo "Running dart_vst_graph tests..." - cd dart_vst_graph && dart test - -# Build native libraries (required for all Dart components) -native: clean-native - @echo "Building native libraries..." - @if [ -z "$(VST3_SDK_DIR)" ]; then \ - if [ -d "vst3sdk" ]; then \ - export VST3_SDK_DIR="$(shell pwd)/vst3sdk"; \ - echo "Using VST3 SDK from $(shell pwd)/vst3sdk"; \ - elif [ -d "/workspace/vst3sdk" ]; then \ - export VST3_SDK_DIR="/workspace/vst3sdk"; \ - echo "Using VST3 SDK from /workspace/vst3sdk"; \ - else \ - echo "Error: VST3_SDK_DIR environment variable not set"; \ - echo "Please set it to the root of Steinberg VST3 SDK or run setup.sh first"; \ - exit 1; \ - fi; \ - fi - @echo "Building dart_vst_host library..." - @if [ -d "/workspace" ]; then \ - mkdir -p /workspace/dart_vst_host/native/build; \ - cd /workspace/dart_vst_host/native/build && VST3_SDK_DIR=$${VST3_SDK_DIR:-/workspace/vst3sdk} cmake .. && make; \ - cp /workspace/dart_vst_host/native/build/libdart_vst_host.* /workspace/ 2>/dev/null || true; \ - cp /workspace/dart_vst_host/native/build/libdart_vst_host.* /workspace/dart_vst_host/ 2>/dev/null || true; \ - else \ - mkdir -p dart_vst_host/native/build; \ - cd dart_vst_host/native/build && VST3_SDK_DIR=$${VST3_SDK_DIR:-$(shell pwd)/vst3sdk} cmake .. && make; \ - cp dart_vst_host/native/build/libdart_vst_host.* . 2>/dev/null || true; \ - cp dart_vst_host/native/build/libdart_vst_host.* dart_vst_host/ 2>/dev/null || true; \ - fi - @echo "Building dart_vst_graph library..." - @if [ -d "/workspace" ]; then \ - mkdir -p /workspace/dart_vst_graph/native/build; \ - cd /workspace/dart_vst_graph/native/build && VST3_SDK_DIR=$${VST3_SDK_DIR:-/workspace/vst3sdk} cmake .. && make; \ - cp /workspace/dart_vst_graph/native/build/libdart_vst_graph.* /workspace/ 2>/dev/null || true; \ - cp /workspace/dart_vst_graph/native/build/libdart_vst_graph.* /workspace/dart_vst_graph/ 2>/dev/null || true; \ - else \ - mkdir -p dart_vst_graph/native/build; \ - cd dart_vst_graph/native/build && VST3_SDK_DIR=$${VST3_SDK_DIR:-$(shell pwd)/vst3sdk} cmake .. && make; \ - cp dart_vst_graph/native/build/libdart_vst_graph.* . 2>/dev/null || true; \ - cp dart_vst_graph/native/build/libdart_vst_graph.* dart_vst_graph/ 2>/dev/null || true; \ - fi - @echo "Native libraries built and copied to required locations" - -# Build all VST® 3 plugins -plugin: native clean-plugin - @echo "Building all VST® 3 plugins..." - @for plugin in vsts/*/; do \ - if [ -f "$$plugin/CMakeLists.txt" ]; then \ - echo "Building $$plugin"; \ - cd "$$plugin" && mkdir -p build && cd build && cmake .. && make && cd ../../../; \ - fi; \ - done - -# Install Dart dependencies for all packages +# agent-pmo:372ce7f +# Flutter VST3 toolkit: run from the repository root. Each package has its own +# Makefile; targets starting with _ are private to the build. +.DEFAULT_GOAL := reverb +include mk/common.mk +PACKAGES ?= dart_vst_host dart_vst_graph flutter_vst3 vsts/flutter_reverb vsts/echo +.PHONY: help deploy deploy-echo deploy-reverb echo reverb build native dart-deps lint fmt deslop test coverage-check ci setup clean _plugin _test-native _test-host _test-graph _check-env + +## deploy: Build Echo and Reverb, then copy both to the folder VST3 hosts scan. +## deploy-echo: Build Echo, then copy it to that folder. +## deploy-reverb: Build Reverb, then copy it to that folder. +## echo: Build echo.vst3. +## reverb: Build flutter_reverb.vst3. +deploy deploy-echo deploy-reverb echo reverb: + $(MAKE) -C vsts $@ + +## build: Build the native libraries and both plugins. +build: native dart-deps _plugin +_plugin: + $(MAKE) -C vsts build + +## native: Build the host and graph libraries. +native: + $(MAKE) -C dart_vst_graph _native + +## dart-deps: Resolve dependencies in every package. dart-deps: - @echo "Installing flutter_vst3 dependencies..." - @if [ -d "/workspace" ]; then \ - dart pub get --directory=/workspace/flutter_vst3; \ - dart pub get --directory=/workspace/dart_vst_host; \ - dart pub get --directory=/workspace/dart_vst_graph; \ - else \ - dart pub get --directory=flutter_vst3; \ - dart pub get --directory=dart_vst_host; \ - dart pub get --directory=dart_vst_graph; \ - fi - -# Install reverb plugin dependencies -reverb-deps: - @echo "Installing Flutter Reverb dependencies..." - @if [ -d "/workspace" ]; then \ - dart pub get --directory=/workspace/flutter_vst3; \ - dart pub get --directory=/workspace/vsts/flutter_reverb; \ - else \ - dart pub get --directory=flutter_vst3; \ - dart pub get --directory=vsts/flutter_reverb; \ - fi - -# Install echo plugin dependencies -echo-deps: - @echo "Installing Echo plugin dependencies..." - @if [ -d "/workspace" ]; then \ - dart pub get --directory=/workspace/flutter_vst3; \ - dart pub get --directory=/workspace/vsts/echo; \ - else \ - dart pub get --directory=flutter_vst3; \ - dart pub get --directory=vsts/echo; \ - fi - -# Install Flutter dependencies -flutter-deps: - @echo "Installing Flutter dependencies..." - @if [ -d "/workspace" ]; then \ - flutter pub get --directory=/workspace/flutter_ui; \ - else \ - flutter pub get --directory=flutter_ui; \ - fi - -# Install VST® 3 plugin to system location (macOS/Linux) -install: reverb-vst - @echo "Installing flutter_reverb.vst3..." - @if [ "$$(uname)" = "Darwin" ]; then \ - mkdir -p ~/Library/Audio/Plug-Ins/VST3/; \ - cp -r vsts/flutter_reverb/build/VST3/Release/flutter_reverb.vst3 ~/Library/Audio/Plug-Ins/VST3/; \ - echo "✅ Installed to ~/Library/Audio/Plug-Ins/VST3/"; \ - elif [ "$$(uname)" = "Linux" ]; then \ - mkdir -p ~/.vst3/; \ - cp -r vsts/flutter_reverb/build/VST3/Release/flutter_reverb.vst3 ~/.vst3/; \ - echo "✅ Installed to ~/.vst3/"; \ - else \ - echo "⚠️ Manual installation required on this platform"; \ - fi - -# Clean all build artifacts -clean: clean-native clean-plugin - @echo "Removing native libraries from all locations..." - rm -f libdart_vst_host.* - rm -f *.dylib *.so *.dll - rm -f dart_vst_host/libdart_vst_host.* - rm -f dart_vst_graph/libdart_vst_graph.* - -# Clean native library builds -clean-native: - @echo "Cleaning native builds..." - @if [ -d "/workspace" ]; then \ - rm -rf /workspace/dart_vst_host/native/build; \ - rm -rf /workspace/dart_vst_graph/native/build; \ - else \ - rm -rf dart_vst_host/native/build; \ - rm -rf dart_vst_graph/native/build; \ - fi - -# Clean plugin builds -clean-plugin: - @echo "Cleaning all VST plugin builds..." - @for plugin in vsts/*/; do \ - if [ -d "$$plugin/build" ]; then \ - echo "Cleaning $$plugin"; \ - rm -rf "$$plugin/build"; \ - fi; \ - done - -# Run Flutter app -run-flutter: flutter-deps - cd flutter_ui && flutter run - -# Run dart_vst_host tests only -test-host: native dart-deps - cd dart_vst_host && dart test - -# Run dart_vst_graph tests only -test-graph: native dart-deps - cd dart_vst_graph && dart test - -# Check environment -check-env: - @echo "Checking environment..." - @test -n "$(VST3_SDK_DIR)" && echo "✅ VST3_SDK_DIR = $(VST3_SDK_DIR)" || echo "❌ VST3_SDK_DIR not set" - @command -v cmake >/dev/null 2>&1 && echo "✅ CMake available" || echo "❌ CMake not found" - @command -v dart >/dev/null 2>&1 && echo "✅ Dart available" || echo "❌ Dart not found" - @command -v flutter >/dev/null 2>&1 && echo "✅ Flutter available" || echo "❌ Flutter not found" - -# Help + for package in $(PACKAGES); do $(MAKE) -C "$$package" _deps || exit 1; done + +## lint: Analyze every package. +lint: dart-deps + for package in $(PACKAGES); do $(MAKE) -C "$$package" _lint || exit 1; done + +## fmt: Format every package. +fmt: + dart format dart_vst_host/lib dart_vst_host/test dart_vst_graph/lib dart_vst_graph/test flutter_vst3/lib flutter_vst3/test vsts/echo/lib vsts/echo/test vsts/flutter_reverb/lib vsts/flutter_reverb/test + +## deslop: Fail if duplication is above the ceiling in .deslop.toml. +deslop: + deslop . --nohtml --nojson --no-color --log-level error + +## test: Run every test with coverage. +test: native dart-deps _test-native + for package in $(PACKAGES); do $(MAKE) -C "$$package" _test || exit 1; done +_test-native: + bash flutter_vst3/test/native/run.sh +_test-host: native + $(MAKE) -C dart_vst_host _deps _test +_test-graph: native + $(MAKE) -C dart_vst_graph _deps _test + +## coverage-check: Check coverage reports against coverage-thresholds.json. Runs no tests. +coverage-check: + python3 flutter_vst3/test/native/coverage_check.py + +## ci: Run the same phases as CI: build, test, coverage. +ci: deslop lint build test coverage-check + +## setup: Fetch the VST3 SDK and build the native libraries. +setup: + ./setup.sh + +## clean: Delete all build output. +clean: + $(MAKE) -C dart_vst_host _clean + $(MAKE) -C dart_vst_graph _clean + $(MAKE) -C vsts _clean + +_check-env: + test -d "$(VST3_SDK_DIR)" + command -v cmake + command -v dart + command -v flutter + +## help: List the public targets. help: - @echo "Dart VST3 Toolkit Build System" - @echo "===============================" - @echo "" - @echo "🎯 PRIMARY TARGET:" - @echo " all (default) - Build Flutter Dart Reverb VST3 plugin" - @echo "" - @echo "🎛️ PLUGIN TARGETS:" - @echo " reverb-vst - Build Flutter Dart Reverb VST3 plugin" - @echo " reverb-build-only - Build Flutter Dart Reverb VST3 plugin (no install)" - @echo " reverb-deps - Install reverb plugin dependencies only" - @echo " echo-vst - Build Echo VST3 plugin" - @echo " echo-build-only - Build Echo VST3 plugin (no install)" - @echo " echo-deps - Install echo plugin dependencies only" - @echo " install - Build and install VST3 plugin to system" - @echo "" - @echo "🏗️ BUILD TARGETS:" - @echo " build - Build all components (host, graph, reverb)" - @echo " native - Build native library with VST3 bridge" - @echo " plugin - Build generic VST3 plugin (old)" - @echo "" - @echo "📦 DEPENDENCY TARGETS:" - @echo " dart-deps - Install all Dart package dependencies" - @echo " flutter-deps - Install Flutter UI dependencies" - @echo "" - @echo "🧪 TESTING TARGETS:" - @echo " test - Run all tests (bridge, reverb, host, graph)" - @echo " test-host - Run dart_vst_host tests only" - @echo " test-graph - Run dart_vst_graph tests only" - @echo "" - @echo "🧹 CLEANUP TARGETS:" - @echo " clean - Clean all build artifacts" - @echo " clean-native - Clean native library build only" - @echo " clean-plugin - Clean plugin build only" - @echo "" - @echo "🔧 UTILITY TARGETS:" - @echo " run-flutter - Run Flutter UI application" - @echo " check-env - Check build environment setup" - @echo " help - Show this help message" - @echo "" - @echo "📋 EXAMPLES:" - @echo " make # Build FlutterDartReverb.vst3" - @echo " make clean reverb-vst # Clean build and rebuild reverb VST" - @echo " make install # Build and install to DAW plugins folder" - @echo "" - @echo "🔧 PREREQUISITES:" - @echo " • Set VST3_SDK_DIR environment variable (or use bundled SDK)" - @echo " • Install CMake 3.20+, Dart SDK 3.0+, and Flutter" - @echo "" - @echo "📁 PACKAGES:" - @echo " • dart_vst3_bridge/ - FFI bridge for any Dart VST3 plugin" - @echo " • vsts/flutter_reverb/ - Pure Dart reverb VST3 implementation" - @echo " • vsts/echo/ - Pure Dart echo VST3 implementation" - @echo " • dart_vst_host/ - VST3 hosting for Dart applications" - @echo " • dart_vst_graph/ - Audio graph system with VST routing" \ No newline at end of file + @sed -n 's/^## //p' $(MAKEFILE_LIST) + @echo 'Set VST3_SDK_DIR to the Steinberg SDK root. Flutter is required for plugin packages.' diff --git a/PR_5_REVIEW.md b/PR_5_REVIEW.md new file mode 100644 index 0000000..c09ea49 --- /dev/null +++ b/PR_5_REVIEW.md @@ -0,0 +1,342 @@ +# Review: PR #5, shared-memory DSP and embedded Flutter GUI + +| | | +|---|---| +| PR | [#5](https://github.com/MelbourneDeveloper/flutter_vst3/pull/5), `alnitak:fromSoloud` at `d152d9e` | +| Merged to | `feature/soloud-shared-memory-gui` as `63b646d` (not `main`) | +| Diff reviewed | `main` (`39d5e42`) to `63b646d`: 26 commits, 119 files | +| Line numbers | All `file:line` references are at `63b646d` | +| Verdict | Every blocker is closed, and CI passes on all three OSes. Not tried in a real DAW: see [limits](#what-this-does-not-prove) | + +Status values: `Fixed` (a test proves it, and was seen to fail when the fix was undone; the [fix log](#fix-log) names it), +`Won't fix` (reason given). + +## Summary + +The separate-process DSP design is sound. It isolates Dart from the host's audio thread and keeps the Flutter engine out +of the DSP process. The implementation isn't ready: one late block desynchronizes audio for the rest of the session, two +instances of one plugin share one DSP, the sample rate never reaches the DSP, saved state never reaches the DSP, and every +Windows editor with parameters can deadlock on open. The PR's test claims don't hold up: its one new test file covers +argument checks and a bad magic number, and `make test` can't fail for three of its packages. + +## Blockers + +### IPC and audio path + +Paths are under `flutter_vst3/native/templates/` unless given in full. `native` is `plugin_processor_native.cpp.template` +and `aot` is `plugin_processor_aot.cpp.template`. + +| ID | Where | Trigger | Failure | Required fix | Proof required | Status | +|---|---|---|---|---|---|---| +| B1 | `native:269-299` | One block takes over 50 ms, such as a Dart GC pause or a scheduler stall | The late `sem_done` stays posted, so the next block takes it at once and copies the previous output. The host then overwrites input while the worker is reading it. It never recovers | The host owns shared memory only between "done" and "ready". After a timeout it leaves shared memory alone, outputs silence, and resyncs when the late "done" arrives | Round trip with a real worker: stall one block, then assert later blocks return their own output | Fixed | +| B2 | `aot:83,106-109` | Host runs at anything but 44.1 kHz, or changes rate or block size | `setupProcessing` stores the rate, but `initialize` returns early when already set up (`native:119`), and block size is hardcoded to `512`. A second activation at a new rate leaves the DSP on the old one, so delay times are wrong | Pass `setup.sampleRate` and `setup.maxSamplesPerBlock`, and reconfigure the live worker on activation | Activate at 44.1k, reactivate at 96k, assert the worker sees 96k | Fixed | +| B3 | `native:404-411`, `aot:82-84` | Worker missing, or handshake fails | `native_initialize` swallows the exception, the caller sets `nativeProcessorInitialized = true`, and the plugin is silent with no error. The `catch`/`abort` in `aot` is unreachable. Shared memory, semaphores and the child leak | Roll back all resources on failure and return failure from `setActive` | Missing exe and exe that exits at once: both fail fast, leaving no child, shm or semaphores | Fixed | +| B4 | `native:262,293-299` | Block larger than 4096 samples, such as offline render | Only the first 4096 samples are processed. Samples past that in `output` are never written, so the host plays stale memory | Process in chunks of up to 4096 samples | 10000-sample block matches the same audio in small blocks | Fixed | +| B5 | `native:401,406` | Two instances of one plugin in a session | `g_processor` is per module. Both instances share one DSP and one parameter set, and audio passes through a single delay line. Disposing either kills both | One host object per plugin instance | Two instances keep separate DSP state, and disposing one leaves the other working | Fixed | +| B6 | `aot:181-197` | Save and reload a project | `getState`/`setState` use C++ member doubles that `process()` never updates, and nothing forwards them to Dart. Saved projects restore defaults | Track values in `process()`, and replay state to the worker before audio starts | Automate, get state, load into a new instance, assert the DSP received the values | Fixed | +| B7 | `native:261,269-291`, `native:303-315` | Every block | Audio thread holds a mutex, sleeps in a poll loop, and can block for 50 ms against a block budget of a few ms. A full parameter ring drops automation | No mutex or fixed 50 ms wait. Base the budget on block length with a real timed wait, and keep the latest value when the ring is full | Timing test: stalled worker costs at most one budget. Overflow test: the last value arrives | Fixed | +| B8 | `native:223-235` | Worker dies mid-session | Every later block stalls 50 ms and outputs silence, and the host's audio thread runs far behind. On Linux, `PR_SET_PDEATHSIG` also fires when the *spawning thread* exits, so the worker can die while the DAW lives. Other platforms orphan the worker if the host dies | Detect a dead child and skip the wait. Have the worker watch the host process directly | Kill the worker: later blocks return silence immediately. Kill the host: the worker exits | Fixed | +| B9 | `native:328` | Windows: two instances, editor open on A, delete B | `UnmapViewOfFile` frees memory the UI reader still reads, so the host crashes. POSIX is safe through the `MAP_FIXED` remap | Keep the Windows view mapped with `magic = 0`, and reuse it | Reader stays valid and reads `isValid == false` after dispose on both OSes | Fixed | +| B10 | `native:317`, `aot:94-96` | Stop transport, or `setActive(false)` | `reset()` is an empty body, so old tails play on restart | Add a reset command that reaches the DSP | Reset clears an echo tail in a round trip | Fixed | + +### Embedded GUI + +Paths are under `flutter_vst3/native/src/`. + +| ID | Where | Trigger | Failure | Required fix | Proof required | Status | +|---|---|---|---|---|---|---| +| B11 | `embedded_flutter_view.cpp:146,227,262` | Windows: open an editor on a plugin with parameters | `mount` holds a non-recursive `std::mutex`, calls `updateParam`, which locks it again. That's undefined behaviour and in practice a deadlock or abort | Split into locked and unlocked functions | Windows compile plus a test on the extracted logic | Fixed | +| B12 | `embedded_flutter_view.cpp:156,168` | Any plugin other than Echo on Windows and Linux | Entrypoint is hardcoded to `"echoMain"`. Reverb's editor can't start | Take the entrypoint from `plugin_metadata.json` and pass it as a compile definition | Generator test: the entrypoint reaches CMake metadata | Fixed | +| B13 | `embedded_flutter_view.cpp:247-268,891-913` | Two editors open, close one | `sActiveController` is cleared unconditionally and `updateParam` has no instance check. Editor B drives A's parameters and closing A blanks B | Check ownership on shutdown and update | Test of the extracted ownership logic | Fixed | +| B14 | `embedded_flutter_view.cpp:1216,1228,1231` | Flutter engine fails to start | `attached` ignores the failure and returns `kResultTrue`, leaving a blank editor. The PR claims a graceful fallback | Return failure, or mount the native sliders that already exist | Force init failure: native UI appears or `attached` fails | Fixed | + +## High + +| ID | Where | Problem | Fix | Status | +|---|---|---|---|---| +| H1 | `flutter_vst3/lib/src/vst3_shared_memory_processor.dart:339-349` | `readIdx++` is an unbounded Dart int but `writeIdx` is `Uint32`. At the 2^32 wrap, `readIdx != writeIdx` never ends and the worker hangs | Mask to 32 bits, with a wrap test | Fixed | +| H2 | same file `:165-172` | `mmap` is compared with `nullptr`, not `MAP_FAILED`. `sem_open` results aren't checked, so a failure segfaults later | Check both and throw | Fixed | +| H3 | same file, plus `vst3_shared_memory.h` | Layout constants are hand-copied in Dart, `version` is never validated, and C++ has no `static_assert` | `static_assert` in C++, a test parsing the header against Dart constants, and a version check | Fixed | +| H4 | `native:123,195,217-218` | Names use only 16 bits of `this`. On Windows, a collision opens the existing mapping and `memset`s another instance's audio. Mode `0666` lets any local user read or inject audio | Full pointer in the name, exclusive creation, mode `0600` | Fixed | +| H5 | `native:166` | `CreateProcessA` flags are `0`, so a console window pops up with each instance on Windows | `CREATE_NO_WINDOW` | Fixed | +| H6 | `native:234` | `exit(1)` after `fork` runs host static destructors in the child | `_exit` | Fixed | +| H7 | `flutter_vst3/native/src/vst3_shared_memory.cpp:7-15` | Process-global "active shm": last writer wins, so editor A shows instance B's waveform. Closing either instance nulls it for both | Route the address from processor to controller over `IConnectionPoint` | Fixed | +| H8 | `flutter_vst3/lib/src/shared_memory_reader.dart:46-54,124-139` | `try/catch` around a raw pointer deref can't catch a segfault. `numSamples` isn't clamped | Rely on B9 for validity, remove the catch, clamp | Fixed | +| H9 | `flutter_vst3/lib/src/flutter_vst3_bridge.dart:44-56` | `registerProcessor` now always throws, but `vsts/echo/lib/src/echo_bridge.dart:14` calls it and `flutter_vst3/README.md:60` documents it. The export of `flutter_vst3_callbacks.dart` was removed without a changelog entry | Remove the stale API, caller and docs, or restore it | Fixed | +| H10 | `embedded_flutter_view.cpp:307-310,764-767`, `:510-513,1059-1062`, `embedded_flutter_view.mm:240-243`, `native_cocoa_view.mm:22-25` | Each drag tick sends begin, perform and end, so a single gesture becomes hundreds of automation undo steps | One begin and end per gesture, with channel methods for Dart | Fixed | +| H11 | `plugin_controller.cpp.template:44-50` | `setParamNormalized` echoes the UI's own edits back, so sliders jitter during a drag | Skip the echo while the parameter is being edited | Fixed | +| H12 | `embedded_flutter_view.cpp:128` | `SetDllDirectoryW` changes host-wide DLL search and is never restored | Restore it, or use `LoadLibraryExW` with full paths | Fixed | +| H13 | `embedded_flutter_view.cpp:710-712,949-950` | `setenv("GDK_BACKEND")` and `gdk_set_allowed_backends` change the whole host process | Skip when GTK is already initialized, and document the X11 requirement | Fixed | +| H14 | `embedded_flutter_view.cpp:397-423` | A fixed window class name registers under the host `hInstance` with this DLL's `wndProc`. A second plugin gets the first plugin's window procedure, which is a crash once that module unloads | Use a per-module class name and the module's own `HINSTANCE` | Fixed | +| H15 | `embedded_flutter_view.mm:85-89,230-233` | `dispatch_async` captures raw `this`, and `weakCtrl` is a raw pointer, so it's use-after-free if the view closes first | Liveness token checked in the block | Fixed | +| H16 | `embedded_flutter_view.mm:49-51`, `native_cocoa_view.h:10-14` | Flutter framework class lookups are process-wide. Objective-C classes in embedded view code can collide between plugins | Per-plugin class prefix everywhere | Fixed for our classes. Won't fix for Flutter's (see fix log) | +| H17 | `flutter_vst3/native/cmake/VST3Bridge.cmake:44-45` | The Steinberg validator is turned off | Turn it on and run it in CI | Fixed | +| H18 | `VST3Bridge.cmake:385-387,420-422,450-452` | Release builds silently fall back to the Debug Flutter bundle | `FATAL_ERROR` | Fixed | +| H19 | `VST3Bridge.cmake:314-316` | Windows and Linux silently drop the embedded GUI when `ephemeral` is absent at configure time. No `$ORIGIN` RPATH was found for `libflutter_linux_gtk.so` | Fail or say so with `message(STATUS)`, and set the RPATH | Fixed | +| H20 | `vsts/flutter_reverb/lib/src/reverb_processor.dart:139-142` | `processStereo` returns silently when uninitialized or on a length mismatch, leaving output unwritten. Breaks the repo's fail-hard rule | Throw, as Echo does | Fixed | +| H21 | `vsts/echo/lib/src/echo_processor.dart:93-96` | Bypass doesn't feed the delay line or advance the write index, so unbypassing replays a frozen tail | Keep the delay line running during bypass | Fixed | +| H22 | `vsts/echo/lib/src/echo_processor.dart:7,98` | Delay is 10-500 ms but docs and metadata say 0-1000 ms. The fixed 132300-sample buffer also clamps delay at high rates | Match the docs and size the buffer from the sample rate | Fixed | +| H23 | `vsts/echo/lib/src/echo_processor.dart:125-128` | `_softSaturate` jumps from 1.0 to 0.5 at the threshold, which adds a click in the feedback path | Continuous curve, with a test | Fixed | +| H24 | `vsts/echo/lib/ui/echo_ui.dart:56` | Shows `value*100` with the units, so "50.0ms" appears for a real delay of about 255 ms | Format from each parameter's real range | Fixed | + +## Medium and low + +| ID | Where | Problem | Status | +|---|---|---|---| +| M1 | `flutter_vst3/lib/src/parameter_binding.dart:48-55,81,178` | `print` debugging and `catch (_) {}` hide failures | Fixed | +| M2 | `parameter_binding.dart:189-224` | Dead `VST3AudioProcessor` class describing the rejected same-isolate design | Fixed | +| M3 | `vsts/echo/lib/src/echo_processor.dart:114-122` | `waveformBuffer` is unreachable because the UI runs in another process, and it costs CPU each block | Fixed | +| M4 | `vsts/echo/lib/ui/echo_ui.dart:2` | Comment claims the UI shares a process with the DSP | Fixed | +| M5 | `vsts/echo/lib/ui/echo_ui.dart:198,206,219` | Forces a channel call on every parameter change, and every 33 ms when there is no reader | Fixed | +| M6 | `vsts/echo/lib/ui/echo_ui.dart:307` | Divides by zero with a single sample | Fixed | +| M7 | `vsts/echo/lib/ui/echo_ui.dart:91,95`, `pubspec.yaml` | Uses `withValues` and `activeThumbColor` while pubspecs allow Flutter `>=3.0.0` | Fixed | +| M8 | `flutter_vst3/native/src/flutter_embedder.cpp`, `flutter_embedder_stubs.cpp`, `include/flutter_embedder.h` | Unbuilt code. The first defines `class FlutterEmbedder` twice and can't compile, and the stubs return fake handles such as `0x1234` | Fixed | +| M9 | `flutter_vst3/native/src/plugin_view.cpp:86` | Unbuilt, and runs `system()` with a hardcoded `/Users/christianfindlay/...` path | Fixed | +| M10 | `vsts/echo/echo_processor` | 5.6 MB committed Mach-O binary | Fixed | +| M11 | `vsts/echo/macos/Flutter/ephemeral/*`, `.vscode/settings.json` | Machine-specific paths committed | Fixed | +| M12 | `vsts/echo/README.md` | Flutter template boilerplate | Fixed | +| M13 | `FLUTTER_UI_SPEC.md` | Calls same-isolate UI "non-negotiable", which the implementation contradicts | Fixed | +| M14 | `dart_vst_graph/lib/src/bindings.dart` | `try/catch` fallback library loading breaks the repo's no-fallback rule | Fixed | +| M15 | `embedded_flutter_view.cpp:708` and others | `fprintf` debugging left in | Fixed | +| M16 | `embedded_flutter_view.cpp:1268` | `setFrame` is ignored, and no `IRunLoop` is used on Linux, so GLib timers depend on the host pumping GLib (`:723`) | Fixed | +| M17 | `flutter_vst3/pubspec.yaml` | Flutter SDK dependency breaks the Makefile's `dart pub get` | Fixed | +| M18 | `aot:131-135` | Only the last automation point of each block is used. Not sample-accurate, which should be documented | Fixed | +| M19 | `native:1-22`, `vst3_shared_memory.h:1-25` | Comments claim "zero-copy" and "lock-free", which the code isn't | Fixed | + +## PR claims against the code + +| Claim | What the code does | Evidence | +|---|---|---| +| "Zero-copy" | Two `memcpy` calls each way per block | `native:264-265,294-295` | +| "No CPU spinning or polling", microsecond wakeups | `sem_trywait` plus `sleep_for(100us)`, up to 500 times | `native:284-290` | +| "Lock-free" | `std::mutex` on the audio thread, plain non-atomic indices | `native:261,305` | +| "Safety timeout, never freezes" | 50 ms per block when dead, nominally. Windows sleep granularity can stretch it to seconds (reasoned, not measured) | `native:273-279` | +| "Zero allocations verified" | Four `asTypedList` views per block, plus `dynamic` dispatch | `vst3_shared_memory_processor.dart:330-334` | +| "Graceful fallback" | Blank editor on asynchronous mount failure on Windows and Linux | B14 | +| "Multi-instance tested" | Only different plugins could work. Same-plugin instances share one global | B5 | +| `test/vst3_test.dart` all passing | The file doesn't exist. Only `vst3_shared_memory_test.dart` does | Repo tree | +| Logic Pro listed as a host | Logic hosts AU, not VST3 | | +| Real host testing | Tested in flutter_soloud, a Flutter/GTK host. No evidence of a real DAW | PR description | + +## Missing tests + +Ranked by the damage a regression would do. + +1. IPC round trip between real C++ host code and a real compiled Dart worker, on POSIX and Win32 +2. Timeout, then recovery with correct output (B1) +3. Dead worker: bounded cost and no per-block stall (B8) +4. Sample rate and block size change reaching the DSP (B2) +5. Blocks over 4096 samples (B4) +6. Two instances of one plugin: DSP isolation and independent disposal (B5) +7. Parameter ring overflow and 2^32 index wrap (B7, H1) +8. C++ and Dart layout parity (H3) +9. Reader validity after dispose, including Windows (B9) +10. `mmap` and `sem_open` failure (H2) +11. Saved state reaching the DSP (B6) +12. One begin/end pair per drag (H10) and no UI echo loop (H11) +13. Multi-editor open and close ownership on Windows and Linux (B13) +14. Non-Echo plugin entrypoint (B12) and mount failure fallback (B14) +15. Module unload with a live engine: needs a runtime check +16. Steinberg validator in CI (H17) +17. Smoke test in a real DAW such as Reaper: manual, not automated +18. Widget tests with a mocked `MethodChannel` +19. Child, shm and semaphore leak checks on shutdown and failure (B3) +20. Echo: impulse timing at a known delay, bypass tail (H21), saturation continuity (H23) + +## The test harness hides failures + +| ID | Where | Problem | Status | +|---|---|---|---| +| T1 | `Makefile:57,59,61` | `dart test \|\| true` for `flutter_vst3`, reverb and echo, so they can never fail | Fixed | +| T2 | `Makefile:92-93,104-105` | `cp` runs from the wrong directory after `cd`, hidden by `\|\| true`, so libraries aren't copied | Fixed | +| T3 | `build.ps1:150` | `Run-Tests` covers only host and graph, and doesn't check `$LASTEXITCODE` | Fixed | +| T4 | `vsts/echo/test/widget_test.dart` | Imports Flutter, so it fails under `dart test`, hidden by T1 | Fixed | +| T5 | `dart_vst_host/test/host_test.dart:151,174,257,291` | Hardcoded `/workspace/...` paths | Fixed | +| T6 | `dart_vst_host/test/host_test.dart:286-346` | The "load plugin" test catches everything and prints, so it can't fail | Fixed | +| T7 | `dart_vst_host/test/host_test.dart:90` | The "audio generation" test never touches the host | Fixed | +| T8 | `vsts/flutter_reverb/test/reverb_test.dart` | A plain `main` with asserts and no `test()`. `flutter test` reports "No tests ran" and exits non-zero | Fixed | +| T9 | `vsts/echo/test/echo_test.dart` | Assertions are too weak: `any != 0`, "obvious echo" checks only the first dry sample, and the click threshold is 0.95 | Fixed | +| T10 | `flutter_vst3/test/vst3_shared_memory_test.dart:61` | `0x0200` is `O_CREAT` only on macOS. On Linux it's `O_TRUNC`, so the test can write to fd `-1` and segfault. POSIX lookups also fail on Windows | Fixed | +| T11 | Repo | No CI on this branch | Fixed | + +## Credit + +These parts are good and should stay: the `Float32List` migration, correct header offsets (checked by hand), `ui.dart` keeping the headless worker free of Flutter, the Windows setup and build scripts, Release build defaults, Cocoa class prefixes, the POSIX `MAP_FIXED` remap that keeps UI memory valid, and the choice to run DSP out of process. + +## Decision for the maintainer + +The instructions said "Only native machine code. No AOT or Dart runtime!" and asks for FP style with no classes. This design ships +a `dart compile exe` binary, which is AOT plus the Dart runtime, and the VST3 SDK requires classes. The fixes follow the +existing design because no other in-process option exists today. `AGENTS.md` now words those rules to match. + +`aot:86-90,169-174` deliberately call `abort()` in the host when something fails. The repo says "FAIL HARD", but this takes +down the user's whole DAW session and unsaved work. The fixes fail through the VST3 API instead: `setActive` returns an +error, `process` returns `kNotInitialized` with silence. The failure is still visible to the host. Revert this if crashing is really what you want. + +## How this review was done + +The first pass was static, cross-checked with `pi` agents whose claims were verified by hand. Some of their claims were +rejected: POSIX `SIGSEGV` after dispose (the mapping stays valid), and off-main-thread `removed()` (`IPlugView` is +UI-thread only). Items that were only reasoned about, and not reproduced, are marked as such. + +## Fix log + +### Tests that prove each finding + +| Findings | Test | Where | +|---|---|---| +| B1, B7, B8, DSP exception | `B1 recovers after a late block`, `B7 stall is bounded`, `B7 parameters survive a stall`, `B8 dead worker is bounded`, `B8 worker exits when the host dies`, `DSP exception is detected` | `flutter_vst3/test/native/ipc_host_recovery_test.cpp`, `ipc_host_test.cpp` | +| B2, B3, B4, B5, B9, B10 | The cases of the same names, against a real compiled Dart worker, and again against the built Echo | `ipc_host_test.cpp`, `plugin_host_test.cpp` | +| B6 | `B6 saved state reaches the DSP`, `B6 truncated state is rejected` | `plugin_host_test.cpp` | +| B11, B12, B14 | `B12/B14 positive`, `B14 broken bundle fallback`. Opening a Windows editor with parameters is what deadlocked in B11. B12 also has `B12: the Flutter entrypoint reaches the CMake metadata` | `editor_host_test.cpp`, `generate_plugin_test.dart` | +| B13 | `B13 owner closed first`, `B13 secondary closed first`, `B13 same view chooses Flutter again` | `editor_host_test.cpp` | +| H1, H2, H3 | `parameter ring crosses uint32 wrap and writes read index`, `POSIX failure sentinels are checked without dereferencing`, `every native protocol define matches Dart` | `vst3_worker_loop_test.dart`, `vst3_shm_layout_test.dart` | +| H7 | `H7 activation sender and forwarding`, `H7 foreign pid accepted without crash`, `H7 deactivation payload` | `editor_host_test.cpp` wire mode | +| H8 | `reader invalidation and bounded sample counts` | `shared_memory_reader_test.dart` | +| H10, H11 | `one begin/set/end gesture per knob drag and bypass`, `pointer completed and interrupted gestures`, and the edit suppression checks in `view_logic_test.cpp` | `ui_regression_test.dart`, `editor_host_test.cpp` | +| H17 | The validator on Echo and Reverb: 47 of 47 on all three OSes | `run_plugin_e2e.sh`, `run_editor_e2e.sh` | +| H20 | Reverb's fail-hard cases | `reverb_test.dart` | +| H21, H22, H23, H24 | `bypass records incoming audio and advances tail`, `impulse timing`, `H23: saturation has continuous value and slope at the threshold`, `physical parameter formatting` | `dsp_regression_test.dart`, `ui_regression_test.dart` | +| M5, M6 | `waveform fetch is attachment-driven, not timer or parameters`, `single sample waveform is finite` | `ui_regression_test.dart` | +| M16 | The Linux test host provides `IRunLoop` and pumps only that, as a host does, and the editor still starts and draws | `editor_host_platform_x11.cpp` | +| T1, T3, T4, T8, T9, T10, T11 | `dart_vst_host/test/native/harness_test.sh` injects a failure into each of 5 packages and checks `make test` exits with it. The rewritten package tests, and `.github/workflows/ci.yml` | | +| H4, H5, H6 | `exclusive resources, sentinels and permissions`, `full owner names with identical low 16 bits`, `detached worker has no visible or new console window`, `failed exec never runs host atexit handlers` | `ipc_platform_test.cpp` | +| H12, H13 | `H12 DLL directory invariant`, `H13 GDK_BACKEND invariant before and after GTK initialization` | `editor_host_regressions.h`, `environment` mode | +| H14 | `H14 separate module unload and survivor slider`: two copies of the plugin, one unloaded, then a real drag on the survivor | `editor_host_test.cpp`, `modules` mode | +| H15 | `H15 dead/live/expired token exact work counts`, `H15 immediate close` | `editor_liveness_test.cpp`, `immediate` mode | +| H18, H19 | `test_H18_release_never_uses_debug_bundle`, `test_H19_missing_ephemeral_is_fatal`, `test_H19_runpath_is_origin_relative` | `build_rules_flutter_test.py` | +| M1 | `avoid_print` and `empty_catches` as analyzer errors | `flutter_vst3/analysis_options.yaml` | +| M7 | Version floors parsed from both pubspecs | `build_rules_versions_test.py` | +| M14 | `M14 missing graph library throws with attempted library name` | `dart_vst_graph/test/missing_library_test.dart` | +| M17, T2 | `test_M17_clean_dart_deps_resolves_all_packages`, under a `dart` that refuses Flutter packages as a standalone one does. `test_T2_native_copies_fresh_libraries` | `build_rules_make_test.py` | +| T6, T7 | A real SDK plugin is loaded and rendered, and all 512 samples of both outputs are asserted exactly | `dart_vst_host/test/host_audio_regression_test.dart` | +| H9, H16, M2, M3, M4, M8 to M13, M15, M18, M19, T5 | Each is an absence, so a named rule checks it: removed code, tracked binaries by magic bytes, stale claims, absolute paths, and the prefix on every Objective-C class we define | `repo_rules_test.py` | +| AB4 | Extracts the README's test commands, runs each, and requires every package's tests to pass | `docs_commands_test.py` | + +### Found while fixing + +The first review missed these. Each has a test unless it says otherwise. + +| ID | Problem | Fix | +|---|---|---| +| H25 | All plugins shared hardcoded UIDs, so a host saw Echo and Reverb as one plugin | New plugins derive UIDs from the bundle id, and Reverb now has its own. Echo keeps its original UIDs, pinned in `plugin_metadata.json`, so saved Echo projects still find it. **Reverb's UID did change, so projects saved with the old Reverb won't find it**. Tests: `H25: a pinned UID is used exactly`, `H25: a bad pinned UID is rejected`, `H25: Echo keeps its original UIDs, and Reverb has its own`, and `Echo keeps its UID` on the built bundle | +| B15 | Windows release builds never passed the AOT path, so the Flutter editor could never start there | Pass `data\app.so`. Found by the first Windows run of the editor test | +| F1 | A corrupt `App` on macOS crashed the host | Preflight with `dlopen`, and fall back to native sliders | +| F2 | On Windows, the worker didn't exit after a DSP exception | Explicit exit with status 70 | +| F3 | On Windows, the Ninja generator built a broken bundle | `FATAL_ERROR` without a Visual Studio generator. No test, as it's a build-time check | +| F4 | `dart_vst_host` let its `PlugProvider` go out of scope, which terminated the plugin it had loaded | The state owns the provider | +| F5 | Flutter's Linux platform handler calls `exit(0)` on a plug delete event, which would exit the DAW. A close race also gave `BadWindow` | The plug swallows the delete event. The editor test exited early before this, which its completion marker catches | +| F6 | The worker inherited the host's file descriptors | `worker does not inherit descriptors` | +| F8 | A worker crash during playback was silent for the user: audio just stopped. The host now clears the block's magic word, and the Flutter editor shows "DSP stopped" until a new worker starts | `the editor says when the DSP stops, and when it is back`, `a block with a cleared magic word means the worker died`, `B8 dead worker is bounded` | +| F7 | The plugin's RUNPATH held an absolute path from the build machine. Found by the H19 test | Only `$ORIGIN` now | + +### Second adversarial review + +Four `pi` reviewers attacked the fixed code, read-only, each required to reproduce or point to exact lines. Reports were checked by hand before anything was changed. + +| ID | Problem | Before | Test now | Status | +|---|---|---|---|---| +| AI1 | Windows leaked a process handle per dead worker | 20 crashes: 71 to 91 handles | `crash cycles leak nothing` | Fixed | +| AI2 | A partly late block kept audio while flagged silent | `sample 0 is not silent` | `partly late block is wholly silent` | Fixed | +| AI3 | The B1 test passed with recovery removed | Mutant survived | `B1 recovers after a late block` now requires recovery | Fixed | +| AI4 | Echo and Reverb reported no tail, so hosts could cut them off | Tail 0 | `tail is reported`. Reports infinite, because feedback has no fixed length | Fixed | +| AI5 | NaN and out-of-range saved state reached the processor; the controller read a short state as zeros. Found while checking AI | `invalid value must be rejected` | `processor rejects invalid state`, `controller rejects invalid state` | Fixed | +| AG1 | Closing an editor mid-drag left the host's gesture open | Open gesture on the host | `interrupted gesture and fresh begin after reattach`, pointer test | Fixed | +| AG2 | Channel values skipped range and type checks | `getParameter(0)` returned 2.0 | `exact bidirectional contract and atomic rejection` | Fixed | +| AG3 | The editor test passed with parameter sync removed | Mutants survived | `host to UI display sync and reopen`, `pointer completed and interrupted gestures` | Fixed | +| AG4 | `attached` accepted unsupported platform types | Returned success | Asserted on every editor opened | Fixed | +| AG5 | The host could get a perform outside any gesture, after an interrupted drag on Windows. Found by AG3's test on CI | `FAIL drag boundaries`, with performs after the end | Pointer test, and a stray perform in `interrupted gesture`. The controller now drops these | Fixed | +| AG6 | A host value over 1 displayed wrongly in native sliders and was rejected by the Flutter UI. Found by me | `out-of-range value must display as its clamped value` | Part of the display test | Fixed | +| AG7 | On Linux, dragging, closing the editor, releasing, then reopening left the knob dead, because the embedder still thought the button was down. Found by a reordered pointer test | `FAIL drag missing events` | The `releasedWhileClosed` drag in the pointer test. The Linux view now ends the pointer before hiding | Fixed | +| AG8 | On Windows, holding the button through a close and reopen left the host's gesture open. Found by the contract check on CI | `contract: gesture left open`, then a drag with no end | The `releasedAfterReopen` drag. The begin now waits for the first value. Two Windows pointer workarounds tried on the way were removed, as mutants showed no test needed them | Fixed | +| AD1 | Reverb tests passed with its wet output or decay removed | 6 mutants survived | `wet_contract_test.dart`, with landmarks worked out by hand | Fixed | +| AD2 | Echo tests passed with feedback removed | 2 mutants survived | `feedback_contract_test.dart` | Fixed | +| AD3 | Binding tests passed with the wrong id or value sent | 4 mutants survived | `parameter_binding_contract_test.dart` | Fixed | +| AD4 | Quoted or hyphenated names generated C++ that doesn't compile | `SUCCESS`, then g++ errors | `generator_strings_test.py` compiles the output | Fixed | +| AD5 | Docs called maximum feedback "infinite", but it's capped at 0.85 | | Docs corrected, ratio asserted | Fixed | +| AB1 | `build.bat` always ran a Flutter build, which Reverb can't do | Default Windows build failed | CI job `Windows public build and install` | Fixed | +| AB2 | Incremental builds shipped a stale worker, and accepted invalid Dart | Same hash after an edit | `run_incremental_build.sh` | Fixed | +| AB3 | `build.bat test` ran the POSIX IPC script on Windows | | CI runs `build.bat test-native` | Fixed | +| AB4 | The README's test commands used the wrong runner | `dart:ui is not available` | `docs_commands_test.py` | Fixed | + +The mutation sweep went from 12 of 14 surviving to 0 of 43. These are hand-picked mutants, so this isn't a project-wide rate. + +### What ran where + +CI run `41385874459` at `b8857d1`: all 23 jobs green. + +| Suite | Linux | macOS | Windows | +|---|---|---|---| +| IPC round trip, 18 cases | Pass | Pass | Pass | +| Built Echo in a host, 11 cases | Pass | Pass | Pass | +| Validator on Echo and Reverb, native and Flutter | 47 of 47 | 47 of 47 | 47 of 47 | +| Editor lifecycle, fallback, H7 wire | Pass | Pass | Pass | +| Interrupted gesture, on the real controller | Pass | Pass | Pass | +| Rendering, host-to-UI display, pointer drag | Pass | **Not run** | Pass | +| Two modules, one unloaded | Pass, with pointer and pixels | Pass, without them | Pass, with pointer and pixels | +| Platform IPC rules (H4, H6 on POSIX, H5 on Windows) | Pass | Pass | Pass | +| Editor mutation job | 3 killed | 1 killed | 3 killed | +| Public `build.bat` commands | n/a | n/a | Pass | +| Incremental build, generator output, repo rules, build rules, README commands, `flutter_vst3`, Echo and Reverb packages | Pass | Not run | Not run | +| Host and graph libraries | Pass | Pass | Not run | + +### Evidence that the tests can fail + +- `plugin_host_test` on the original PR (`63b646d`): 7 of 7 failed, including B2 with the echo at sample 2832 not 4800, and B4 with sample 4096 not rendered. Leftover `/dev/shm/vst3_shm_*` files proved the B3 leak. +- A leak planted in the IPC run makes `run.sh` exit 1. `red_B13.log` and `red_B14.log` show those cases exit 1 with the fix disabled. +- **Sweep on final code** (`d9344c4`): all 43 mutants killed by a test assertion, with none surviving. 35 are Dart and 8 are editor. After that commit, only Windows pointer code, the macOS test host and the test runner changed, none of which those mutants touch. +- **CI's `Editor mutation proof` job** undoes fixes on each OS and requires the expected failure. It kills `linux_release`, `h13` and `h15` on Linux, `h12`, `h14` and `h15` on Windows, and `h15` on macOS. +- **Each finding added for lack of a test** was seen failing when its fix was undone, in a scratch copy. H5's mutant ran on Windows. Logs are in the agents' reports. +- **Survivors were acted on.** Mutants removing `releasePointer` and `ignoreHeldButton` on Windows survived, so that code was deleted. M17's first mutant survived because this toolchain's `dart` comes with Flutter, so the test now models a standalone one. +- **Not every test failed before its fix.** Tests over code that already worked, including those added for this section, were proven by mutation. AG1's host-level tests were written after its fix: the unit test failed first, and a mutation proves the rest. + +### What this does not prove + +- **No real DAW has run this.** Everything is the SDK's hosting classes, the validator, and a test host. Try Reaper by hand before release. +- **macOS isn't checked through its real UI.** CI has no screen capture or input permission, so rendering, display sync and pointer drags print `NOT RUN`. Its Flutter editor starts, and the gesture logic passes, but nobody has seen it draw in these tests. macOS also has no asynchronous startup watchdog, only the synchronous checks. +- **Pixel checks cover a limited region.** It catches a value changing and returning, not that a label reads correctly. 0.9 and 1.0 look the same to it on the Flutter knob. +- **Some tests check text, not behaviour.** The rules in `repo_rules_test.py` fail if something removed comes back, which is what those findings needed. H16's rule checks that our class names carry the prefix, not how the Objective-C runtime resolves them. M11's tracked-ephemeral branch wasn't separately mutated, though its absolute-path branch was. +- **H15's protection on macOS is partly by proxy.** The liveness check is tested as a unit, and a real close-while-queued runs without crashing. A use-after-free doesn't crash reliably, so that run alone wouldn't prove it. +- **H5 relies on one Windows session's behaviour.** The test detaches from its console so that a wrong flag would open a window. It failed under mutation on a local Windows machine. CI's runs have only shown it pass. +- **H7's address inside the controller can't be observed from a host.** The test checks the message and its forwarding. +- **H10 on native sliders** is tested through real pointer drags on Linux and Windows, but not on Cocoa. +- **"DSP stopped" isn't tested end to end.** The IPC test proves the host clears the magic word, and the widget test proves the editor reacts to it, on the same memory layout. No test kills a real worker under an open editor. +- **Module unload with a live engine** is only exercised by the test process exiting. +- **Audio-thread timing** was measured on CI and WSL, not under real load. An offline render waits up to 30 seconds for a worker that hangs. + +### Assumptions behind the choices + +Made without asking, on the owner's instruction to use judgment. Each can be reversed. + +| Choice | Assumption | If it's wrong | +|---|---|---| +| Echo keeps its original UIDs, pinned in metadata | Echo is the plugin people have saved projects with | Delete `processorUid` and `controllerUid` from `vsts/echo/plugin_metadata.json` | +| Reverb gets a new UID, not Echo's | The two can't share a UID in one host, and Reverb had no working editor on `main`, so few projects use it | Pin a different pair in Reverb's metadata. They can't both have the old pair | +| A failure reports an error through the VST3 API, not `abort()` | "Fail hard" means visibly, not by taking down the user's DAW and unsaved work | Put `abort()` back in `setActive` | +| A dead worker restarts at the next activation, not by itself | Starting a process from the audio thread isn't acceptable, and a restart thread isn't worth its cost | Add a restart thread in `Vst3IpcHost` | +| "DSP stopped" shows in the Flutter editor only | Most users see that editor. **The native slider fallback, which Reverb always uses, shows no message** | Add it to each native UI | +| The editor checks for a new worker about once a second | A one-second delay in clearing the message doesn't matter | Change `_restartCheckTicks` | +| A saved state with a bad value is rejected whole | Clamping would silently change a user's project | Clamp in `vst3ReadPluginState` | +| No PR to `main` opened | The owner said not to open PRs, and hasn't changed that. **Nothing can merge until one exists** | Open one from this branch | +| Light agentpmo means agent files, Makefile targets and the Deslop gate | "Light" rules out the rest of the standard: coverage thresholds, Dependabot, CodeQL, a release workflow, the shipwright check and repo settings. None was applied, and `make test` doesn't enforce coverage | Run the `agent-pmo` skill for the full conversion | +| `AGENTS.md` is canonical, and `CLAUDE.md` and `GEMINI.md` point at it | The owner moved the instructions there | Swap them | +| CI runs on pushes to `feature/**` as well as on PRs | The owner wanted proof on this branch before any PR exists | Remove the trigger before merging, as the standard is PR-only | + +### Decisions + +- H16: `Won't fix` for the Flutter framework's own classes, since those lookups are process-wide by Objective-C's design and aren't ours to prefix. Our own classes are prefixed. +- Interrupted gestures end on close, instead of asking the host to cope. Late messages from Dart are ignored. +- A gesture reaches the host at its first value, not at pointer down. A tap on a knob therefore makes no undo step. +- Saved state with a bad value is rejected whole. Clamping would silently change a user's project. + +### Branch cleanup + +Useful code was consolidated in `a140df6`, then these were deleted. They can be restored from these SHAs. + +| Branch | SHA | +|---|---| +| `flutter_ui` | `039802a1163a606acac31abd818b0533813c1dcf` | +| `flutter_ui2` | `040e8db65537f049599eb7322d6ec76c57f6f28d` | +| `rebrand` | `908c90f925ee7b7bcfab527e449d7ae87182c486` | +| `ci/root-gate` | `fcab2e84ecb77f9af13ba7fc34e6ae2825dc4487` | +| `fromSoloud` (local) | `d152d9e` | diff --git a/README.md b/README.md index cee084e..860a6a9 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,7 @@ sequenceDiagram **Primary Purpose: Build VST® 3 plugins with Flutter UIs that compile to .vst3 bundles** - **`flutter_vst3`** - Complete framework that auto-generates all C++ VST® 3 boilerplate from Dart -- **`vsts/flutter_reverb`** - Example VST® 3 reverb plugin with Flutter UI +- **`vsts/flutter_reverb`** - Example VST® 3 reverb plugin with native sliders (no standalone Flutter app) - **`vsts/echo`** - Example VST® 3 echo/delay plugin with Flutter UI - **Native Executable Compilation** - Dart compiles to native machine code (no runtime required) @@ -146,40 +146,74 @@ sequenceDiagram ### Cross-Platform Support - ✅ **macOS** - Universal binaries (Intel + Apple Silicon) - ✅ **Windows** - Native Windows VST® 3 support -- ✅ **Linux** - Full Linux VST® 3 support +- ✅ **Linux** - Full Linux VST® 3 support (X11 desktop backend for GUI; run with `GDK_BACKEND=x11`) ## Quick Start ### Prerequisites ```bash -# Download Steinberg VST® 3 SDK -./setup.sh # Automatically downloads SDK and builds native libraries +# macOS / Linux: Download Steinberg VST® 3 SDK & build native libraries +./setup.sh -# Or manually set VST3_SDK_DIR -export VST3_SDK_DIR=/path/to/vst3sdk +# Windows (Command Prompt or PowerShell): +.\setup.bat # or .\setup.ps1 ``` +> [!TIP] +> If running `.ps1` scripts in PowerShell gives an execution policy error, simply run `.\setup.bat` and `.\build.bat`, or allow local scripts once via `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`. + ### Building Your First VST® Plugin 1. **Build the example plugins:** + +**macOS / Linux:** ```bash # Build Flutter Reverb VST® 3 (default) make # Build specific plugins: -make reverb-vst # Build flutter_reverb.vst3 -make echo-vst # Build echo.vst3 +make reverb # Build flutter_reverb.vst3 +make echo # Build echo.vst3 -# Install to system VST folder -make install +# Build, then copy to the folder VST3 hosts scan +make deploy # Echo and Reverb +make deploy-echo # Echo only (or: make -C vsts/echo deploy) +make deploy-reverb # Reverb only (or: make -C vsts/flutter_reverb deploy) ``` +**Windows (PowerShell or Command Prompt):** +```cmd +:: Build Flutter Reverb VST® 3 (default) +./build.bat + +:: Build specific plugins: +./build.bat reverb +./build.bat echo + +:: Build native libraries only (dart_vst_host & dart_vst_graph) +./build.bat native + +:: Build, then copy plugins to the user VST3 folder (%LOCALAPPDATA%\Programs\Common\VST3\) +.\build.bat deploy +.\build.bat deploy-echo +.\build.bat deploy-reverb + +:: Clean build artifacts +.\build.bat clean +``` + +> [!NOTE] +> `.\build.bat deploy` copies plugins to the standard user directory `C:\Users\\AppData\Local\Programs\Common\VST3\`. It does not require Administrator privileges. + 2. **Test in your DAW:** - macOS: `~/Library/Audio/Plug-Ins/VST3/` -- Windows: `C:\Program Files\Common Files\VST3\` +- Windows: `C:\Users\\AppData\Local\Programs\Common\VST3\` - Linux: `~/.vst3/` +> [!IMPORTANT] +> **Linux GUI Requirement**: The standard VST3 windowing backend on Linux uses **X11**. Any application or host running VST3 plugins with a graphical interface on Linux must be launched with the `GDK_BACKEND=x11` environment variable (e.g. `GDK_BACKEND=x11 flutter run`), otherwise the GUI will not be displayed on Wayland desktop sessions. + ### Creating Your Own VST® Plugin 1. **Define parameters with Flutter UI bindings:** @@ -213,54 +247,46 @@ class MyProcessor { ```dart // lib/my_ui_main.dart import 'package:flutter/material.dart'; -import 'package:flutter_vst3/flutter_vst3.dart'; +import 'package:flutter_vst3/ui.dart'; void main() { - runApp(MyPluginUI()); + runApp(const MaterialApp(home: MyPluginUI())); } class MyPluginUI extends StatefulWidget { + const MyPluginUI({super.key}); + @override - _MyPluginUIState createState() => _MyPluginUIState(); + State createState() => _MyPluginUIState(); } class _MyPluginUIState extends State { - final parameters = MyParameters(); - + static const gainParam = 0; + final VST3ParameterBinding _binding = VST3ParameterBinding.getInstance(); + + void _rebuild() => setState(() {}); + @override void initState() { super.initState(); - // Register for DAW parameter changes - VST3Bridge.registerParameterChangeCallback(_onParameterChanged); - } - - void _onParameterChanged(int paramId, double value) { - setState(() { - parameters.setParameter(paramId, value); - }); + _binding.addListener(_rebuild); + _binding.loadInitialParameters(); } - - void _updateParameter(int paramId, double value) { - setState(() { - parameters.setParameter(paramId, value); - }); - // Send to VST host/DAW - VST3Bridge.sendParameterToHost(paramId, value); + + @override + void dispose() { + _binding.removeListener(_rebuild); + super.dispose(); } - + @override Widget build(BuildContext context) { - return MaterialApp( - home: Scaffold( - body: Column( - children: [ - Text('My VST Plugin'), - Slider( - value: parameters.gain, - onChanged: (v) => _updateParameter(0, v), - ), - ], - ), + return Scaffold( + body: Slider( + value: _binding.getParameter(gainParam), + onChangeStart: (_) => _binding.beginEdit(gainParam), + onChanged: (value) => _binding.setParameter(gainParam, value), + onChangeEnd: (_) => _binding.endEdit(gainParam), ), ); } @@ -302,11 +328,11 @@ void main() async { flutter_vst3_toolkit/ ├── flutter_vst3/ # Framework for building VST® 3 plugins with Flutter │ ├── lib/ -│ │ ├── flutter_vst3.dart +│ │ ├── flutter_vst3.dart # DSP worker API +│ │ ├── ui.dart # Flutter editor API │ │ └── src/ -│ │ ├── flutter_vst3_bridge.dart # DAW ↔ Flutter binding -│ │ ├── flutter_vst3_callbacks.dart # FFI callbacks -│ │ └── flutter_vst3_parameters.dart # Parameter management +│ │ ├── vst3_worker_loop.dart # DSP worker over shared memory +│ │ └── parameter_binding.dart # Editor ↔ DAW parameters │ ├── native/ # C++ templates and CMake helpers │ └── scripts/ # Plugin generation scripts ├── vsts/ @@ -323,8 +349,8 @@ flutter_vst3_toolkit/ ### VST® Plugin Development 1. Design UI in Flutter with hot reload 2. Implement audio processing in pure Dart -3. Test with `flutter run` -4. Build VST® 3: `make echo-vst` +3. Test with `flutter test`; plugins with a Flutter entrypoint can also use `flutter run` +4. Build and deploy VST® 3: `make deploy-echo` 5. Load in DAW and test ### Parameter Binding System @@ -349,16 +375,20 @@ The framework provides automatic 3-way parameter binding: ```bash # Run all tests -make test +make test # macOS / Linux +build.bat test # Windows (or .\build.ps1 test) # Test individual packages -cd flutter_vst3 && dart test -cd vsts/echo && dart test -cd dart_vst_host && dart test -cd dart_vst_graph && dart test +(cd flutter_vst3 && flutter test) +(cd vsts/echo && flutter test) +(cd dart_vst_host && dart test) +(cd dart_vst_graph && dart test) # Interactive testing with example plugins -cd vsts/flutter_reverb && flutter run +# (On Linux, set GDK_BACKEND=x11 so native VST3 GUIs can be displayed) +# Reverb has no standalone app: build with make deploy-reverb and load in a VST3 host. +# On Linux: +(cd vsts/echo && GDK_BACKEND=x11 flutter run) ``` ## Contributing diff --git a/build.bat b/build.bat new file mode 100644 index 0000000..83c9b24 --- /dev/null +++ b/build.bat @@ -0,0 +1,5 @@ +@echo off +setlocal +cd /d "%~dp0" +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0build.ps1" %* +exit /b %ERRORLEVEL% diff --git a/build.ps1 b/build.ps1 new file mode 100644 index 0000000..ad60646 --- /dev/null +++ b/build.ps1 @@ -0,0 +1,117 @@ +# Windows build entry point. Every native command is checked immediately. +param([Parameter(Position = 0)][string]$Target = 'reverb') +$ErrorActionPreference = 'Stop' +$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path +Set-Location $ScriptDir +if (-not $env:VST3_SDK_DIR) { $env:VST3_SDK_DIR = "$ScriptDir/vst3sdk" } + +function Invoke-Checked { + param([string]$Command, [string[]]$Arguments) + & $Command @Arguments + if ($LASTEXITCODE -ne 0) { throw "$Command $Arguments failed ($LASTEXITCODE)" } +} + +function Package-Command { + param([string]$Package, [string]$Tool, [string[]]$Arguments) + Push-Location (Join-Path $ScriptDir $Package) + try { Invoke-Checked $Tool $Arguments } finally { Pop-Location } +} + +function Dart-Deps { + foreach ($p in @('dart_vst_host', 'dart_vst_graph')) { + Package-Command $p 'dart' @('pub', 'get') + } + foreach ($p in @('flutter_vst3', 'vsts/echo', 'vsts/flutter_reverb')) { + Package-Command $p 'flutter' @('pub', 'get') + } +} + +function Plugin-Deps { + param([string]$Name) + Package-Command 'flutter_vst3' 'flutter' @('pub', 'get') + Package-Command "vsts/$Name" 'flutter' @('pub', 'get') +} + +function Build-NativeLib { + param([string]$Name) + $source = "$ScriptDir/$Name/native" + $build = "$source/build" + Invoke-Checked 'cmake' @('-S', $source, '-B', $build, '-DCMAKE_BUILD_TYPE=Release') + Invoke-Checked 'cmake' @('--build', $build, '--config', 'Release') + $dlls = @(Get-ChildItem $build -Recurse -Filter "$Name.dll") + if ($dlls.Count -ne 1) { throw "Expected exactly one $Name.dll, found $($dlls.Count)" } + foreach ($dest in @($ScriptDir, "$ScriptDir/$Name")) { + Copy-Item $dlls[0].FullName $dest -Force + } +} + +function Build-Native { + Build-NativeLib 'dart_vst_host' + Build-NativeLib 'dart_vst_graph' +} + +function Build-Plugin { + param([string]$Name) + Plugin-Deps $Name + $metadata = Get-Content "vsts/$Name/plugin_metadata.json" -Raw | ConvertFrom-Json + if ($metadata.flutterEntrypoint) { + Package-Command "vsts/$Name" 'flutter' @('build', 'windows', '--release') + } + Invoke-Checked 'cmake' @('-S', "vsts/$Name", '-B', "vsts/$Name/build", '-DCMAKE_BUILD_TYPE=Release') + Invoke-Checked 'cmake' @('--build', "vsts/$Name/build", '--config', 'Release') +} + +function Run-Tests { + Build-Native + Dart-Deps + Invoke-Checked 'powershell' @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', 'flutter_vst3/test/native/run.ps1') + foreach ($p in @('dart_vst_host', 'dart_vst_graph')) { + Package-Command $p 'dart' @('test') + } + foreach ($p in @('flutter_vst3', 'vsts/echo', 'vsts/flutter_reverb')) { + Package-Command $p 'flutter' @('test') + } +} + +function Remove-Build { + param([string]$Path) + if (Test-Path $Path) { Remove-Item $Path -Recurse -Force } +} +function Clean-Native { + foreach ($p in @('dart_vst_host', 'dart_vst_graph')) { Remove-Build "$p/native/build" } +} +function Clean-Plugin { + foreach ($p in @('echo', 'flutter_reverb')) { Remove-Build "vsts/$p/build" } +} +function Deploy-Plugins { + param([string[]]$Plugins) + $dest = "$env:LOCALAPPDATA/Programs/Common/VST3" + New-Item -ItemType Directory -Force $dest | Out-Null + foreach ($p in $Plugins) { + Build-Plugin $p + Remove-Build "$dest/$p.vst3" + Copy-Item "vsts/$p/build/VST3/Release/$p.vst3" $dest -Recurse -Force + } +} + +switch ($Target.ToLower()) { + { $_ -in 'all', 'reverb' } { Build-Plugin 'flutter_reverb' } + 'echo' { Build-Plugin 'echo' } + 'native' { Build-Native } + 'build' { Build-Native; Build-Plugin 'echo'; Build-Plugin 'flutter_reverb' } + 'dart-deps' { Dart-Deps } + 'reverb-deps' { Plugin-Deps 'flutter_reverb' } + 'echo-deps' { Plugin-Deps 'echo' } + 'test' { Run-Tests } + 'test-native' { Invoke-Checked 'powershell' @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', 'flutter_vst3/test/native/run.ps1') } + 'test-host' { Build-Native; Package-Command 'dart_vst_host' 'dart' @('test') } + 'test-graph' { Build-Native; Package-Command 'dart_vst_graph' 'dart' @('test') } + 'clean' { Clean-Native; Clean-Plugin } + 'clean-native' { Clean-Native } + 'clean-plugin' { Clean-Plugin } + 'deploy' { Deploy-Plugins @('echo', 'flutter_reverb') } + 'deploy-echo' { Deploy-Plugins @('echo') } + 'deploy-reverb' { Deploy-Plugins @('flutter_reverb') } + 'help' { Write-Host 'Targets: native, build, reverb, echo, test, test-native, test-host, test-graph, dart-deps, deploy, deploy-echo, deploy-reverb, clean' } + default { throw "Unknown target: $Target" } +} diff --git a/coverage-thresholds.json b/coverage-thresholds.json new file mode 100644 index 0000000..d190930 --- /dev/null +++ b/coverage-thresholds.json @@ -0,0 +1,10 @@ +{ + "_doc": "Line coverage floors per package, measured from each package's tests; only ever go up.", + "packages": { + "dart_vst_host": 60.3, + "dart_vst_graph": 37.7, + "flutter_vst3": 51.0, + "vsts/flutter_reverb": 85.9, + "vsts/echo": 63.2 + } +} diff --git a/dart_vst_graph/Makefile b/dart_vst_graph/Makefile new file mode 100644 index 0000000..08c0592 --- /dev/null +++ b/dart_vst_graph/Makefile @@ -0,0 +1,8 @@ +NATIVE_LIB ?= dart_vst_graph +include ../mk/native.mk +.PHONY: _host-native + +# The graph library links against the host library. +_native: _host-native +_host-native: + $(MAKE) -C ../dart_vst_host _native diff --git a/dart_vst_graph/lib/src/bindings.dart b/dart_vst_graph/lib/src/bindings.dart index fbdc10b..aee7000 100644 --- a/dart_vst_graph/lib/src/bindings.dart +++ b/dart_vst_graph/lib/src/bindings.dart @@ -73,15 +73,16 @@ class GraphBindings { lib.lookupFunction<_ProcessC, int Function(Pointer, Pointer, Pointer, Pointer, Pointer, int)>('dvh_graph_process_stereo'); } -/// Helper to load the native library. See dart_vst_host.loadDvh() -/// for details on path selection. This wrapper is duplicated here to -/// avoid depending on dart_vst_host from dart_vst_graph. +/// Opens only the graph library for this platform, or the explicit path. +/// Loader failures propagate with the attempted path; no substitute is loaded. DynamicLibrary _openLib({String? path}) { - if (path != null) return DynamicLibrary.open(path); - if (Platform.isMacOS) return DynamicLibrary.open('libdart_vst_host.dylib'); - if (Platform.isLinux) return DynamicLibrary.open('libdart_vst_host.so'); - if (Platform.isWindows) return DynamicLibrary.open('dart_vst_host.dll'); - throw UnsupportedError('Unsupported platform'); + final libraryPath = path ?? switch (Platform.operatingSystem) { + 'macos' => 'libdart_vst_graph.dylib', + 'linux' => 'libdart_vst_graph.so', + 'windows' => 'dart_vst_graph.dll', + _ => throw UnsupportedError('Unsupported platform'), + }; + return DynamicLibrary.open(libraryPath); } /// High level API wrapping GraphBindings. Manages lifetime and diff --git a/dart_vst_graph/native/CMakeLists.txt b/dart_vst_graph/native/CMakeLists.txt index aedbb00..11543c9 100644 --- a/dart_vst_graph/native/CMakeLists.txt +++ b/dart_vst_graph/native/CMakeLists.txt @@ -1,6 +1,11 @@ cmake_minimum_required(VERSION 3.20) project(dart_vst_graph LANGUAGES CXX) +# Default to Release for single-config generators (Linux/macOS Makefiles & Ninja) +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) +endif() + # Build the VST audio graph library for connecting and routing VST plugins. # When consuming from Dart you will need to load # libdart_vst_graph.{so,dylib,dll} from your application. @@ -10,9 +15,9 @@ set(CMAKE_POSITION_INDEPENDENT_CODE ON) # Use the properly downloaded VST3 SDK if(NOT DEFINED ENV{VST3_SDK_DIR}) - set(VST3_SDK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../vst3sdk) + set(VST3_SDK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../vst3sdk) else() - set(VST3_SDK_DIR $ENV{VST3_SDK_DIR}) + file(TO_CMAKE_PATH "$ENV{VST3_SDK_DIR}" VST3_SDK_DIR) endif() if(NOT EXISTS ${VST3_SDK_DIR}/CMakeLists.txt) @@ -89,14 +94,44 @@ elseif(WIN32) ) endif() -target_compile_definitions(dart_vst_graph PRIVATE +target_compile_definitions(dart_vst_graph PRIVATE DART_VST_HOST_EXPORTS - RELEASE=1 + $<$:_DEBUG> + $<$:DEVELOPMENT=1> + $<$>:NDEBUG> + $<$>:RELEASE=1> ) +if(MSVC) + target_compile_options(dart_vst_graph PRIVATE + $<$>:/O2> + $<$>:/Oi> + $<$>:/Ot> + $<$>:/GF> + $<$>:/Gy> + $<$>:/fp:fast> + ) +else() + target_compile_options(dart_vst_graph PRIVATE + $<$>:-O3> + $<$>:-fno-math-errno> + $<$>:-fno-trapping-math> + $<$>:-ffp-contract=fast> + ) +endif() + # Link dart_vst_host library -set(DART_VST_HOST_LIB "${CMAKE_CURRENT_SOURCE_DIR}/../../dart_vst_host/native/build/libdart_vst_host.dylib") -if(EXISTS ${DART_VST_HOST_LIB}) +find_library(DART_VST_HOST_LIB + NAMES dart_vst_host libdart_vst_host + PATHS + "${CMAKE_CURRENT_SOURCE_DIR}/../../dart_vst_host/native/build/Release" + "${CMAKE_CURRENT_SOURCE_DIR}/../../dart_vst_host/native/build/Debug" + "${CMAKE_CURRENT_SOURCE_DIR}/../../dart_vst_host/native/build" + "${CMAKE_CURRENT_SOURCE_DIR}/../../dart_vst_host" + "${CMAKE_CURRENT_SOURCE_DIR}/../.." + NO_DEFAULT_PATH +) +if(DART_VST_HOST_LIB) target_link_libraries(dart_vst_graph ${DART_VST_HOST_LIB}) endif() diff --git a/dart_vst_graph/pubspec.lock b/dart_vst_graph/pubspec.lock index e36953b..9ebaa88 100644 --- a/dart_vst_graph/pubspec.lock +++ b/dart_vst_graph/pubspec.lock @@ -66,7 +66,7 @@ packages: source: hosted version: "3.1.2" coverage: - dependency: transitive + dependency: "direct dev" description: name: coverage sha256: "5da775aa218eaf2151c721b16c01c7676fbfdd99cebba2bf64e8b807a28ff94d" diff --git a/dart_vst_graph/pubspec.yaml b/dart_vst_graph/pubspec.yaml index 38a6676..fe8a033 100644 --- a/dart_vst_graph/pubspec.yaml +++ b/dart_vst_graph/pubspec.yaml @@ -6,4 +6,5 @@ environment: dependencies: ffi: ^2.1.0 dev_dependencies: + coverage: ^1.15.0 test: ^1.24.0 \ No newline at end of file diff --git a/dart_vst_graph/test/graph_test.dart b/dart_vst_graph/test/graph_test.dart index c318aa0..59cc908 100644 --- a/dart_vst_graph/test/graph_test.dart +++ b/dart_vst_graph/test/graph_test.dart @@ -2,32 +2,61 @@ import 'dart:io'; import 'package:test/test.dart'; import 'package:dart_vst_graph/dart_vst_graph.dart'; -void main() { - // Determine if the native library is present in the working - // directory. On CI or developer machines the library should be - // built into libdart_vst_host.{so,dylib,dll} alongside the tests. - final libFile = Platform.isWindows - ? File('dart_vst_host.dll') - : Platform.isMacOS - ? File('libdart_vst_host.dylib') - : File('libdart_vst_host.so'); - - if (!libFile.existsSync()) { - throw Exception('Native library ${libFile.path} not found! Build the native library first.'); - } - - late VstGraph graph; - setUp(() { - final absolutePath = Directory.current.path + Platform.pathSeparator + libFile.path; - graph = VstGraph(sampleRate: 48000, maxBlock: 512, dylibPath: absolutePath); - }); - tearDown(() { - graph.dispose(); - }); +String _libraryName(String package) => switch (Platform.operatingSystem) { + 'windows' => '$package.dll', + 'macos' => 'lib$package.dylib', + 'linux' => 'lib$package.so', + _ => throw UnsupportedError('Unsupported platform'), + }; +void main() { test('gain node parameters', () { + final graph = VstGraph( + sampleRate: 48000, + maxBlock: 512, + dylibPath: File(_libraryName('dart_vst_graph')).absolute.path); + addTearDown(graph.dispose); final id = graph.addGain(0.0); - // The GainNode has exactly one parameter at index 0 expect(graph.setParam(id, 0, 0.5), isTrue); }); -} \ No newline at end of file + + test('missing explicit library fails with its path', () { + final path = File('missing-graph-library').absolute.path; + expect( + () => VstGraph(sampleRate: 48000, maxBlock: 512, dylibPath: path), + throwsA(isA() + .having((e) => '$e', 'message', contains(path)))); + }); + + test('default loader never substitutes the host library', () { + final temp = Directory.systemTemp.createTempSync('graph-loader-'); + addTearDown(() => temp.deleteSync(recursive: true)); + _copyHost(temp); + final probe = File('${temp.path}/probe.dart') + ..writeAsStringSync( + "import '${File('lib/src/bindings.dart').absolute.uri}';\n" + 'void main() { VstGraph(sampleRate: 48000, maxBlock: 512); }\n'); + final result = _probe(probe, temp); + expect(result.exitCode, isNot(0)); + expect('${result.stderr}', contains(_libraryName('dart_vst_graph'))); + }); +} + +void _copyHost(Directory temp) { + final host = File('../dart_vst_host/${_libraryName('dart_vst_host')}'); + host.copySync('${temp.path}/${_libraryName('dart_vst_host')}'); +} + +ProcessResult _probe(File script, Directory temp) => Process.runSync( + Platform.resolvedExecutable, + [ + '--packages=${File('.dart_tool/package_config.json').absolute.path}', + script.path + ], + workingDirectory: temp.path, + environment: { + 'LD_LIBRARY_PATH': temp.path, + 'DYLD_LIBRARY_PATH': temp.path, + 'PATH': '${temp.path}${Platform.isWindows ? ';' : ':'}' + '${Platform.environment['PATH']}', + }); diff --git a/dart_vst_graph/test/missing_library_test.dart b/dart_vst_graph/test/missing_library_test.dart new file mode 100644 index 0000000..1ea9ae0 --- /dev/null +++ b/dart_vst_graph/test/missing_library_test.dart @@ -0,0 +1,16 @@ +import 'dart:io'; +import 'package:dart_vst_graph/dart_vst_graph.dart'; +import 'package:test/test.dart'; + +/// Verifies loader errors name the requested graph library. +void main() { + test('M14 missing graph library throws with attempted library name', () { + final directory = Directory.systemTemp.createTempSync('graph_missing_'); + addTearDown(() => directory.deleteSync(recursive: true)); + final path = '${directory.path}/missing_libdart_vst_graph.so'; + expect(File(path).existsSync(), isFalse); + expect(() => VstGraph(sampleRate: 48000, maxBlock: 512, dylibPath: path), + throwsA(isA().having( + (error) => error.toString(), 'loader error', contains(path)))); + }); +} diff --git a/dart_vst_host/Makefile b/dart_vst_host/Makefile new file mode 100644 index 0000000..6e584af --- /dev/null +++ b/dart_vst_host/Makefile @@ -0,0 +1,2 @@ +NATIVE_LIB ?= dart_vst_host +include ../mk/native.mk diff --git a/dart_vst_host/native/CMakeLists.txt b/dart_vst_host/native/CMakeLists.txt index 060af60..f7d5bfc 100644 --- a/dart_vst_host/native/CMakeLists.txt +++ b/dart_vst_host/native/CMakeLists.txt @@ -1,6 +1,11 @@ cmake_minimum_required(VERSION 3.20) project(dart_vst_host LANGUAGES CXX) +# Default to Release for single-config generators (Linux/macOS Makefiles & Ninja) +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) +endif() + # Build the VST host library for loading and controlling VST3 plugins. # When consuming from Dart you will need to load # libdart_vst_host.{so,dylib,dll} from your application. @@ -10,9 +15,9 @@ set(CMAKE_POSITION_INDEPENDENT_CODE ON) # Use the properly downloaded VST3 SDK if(NOT DEFINED ENV{VST3_SDK_DIR}) - set(VST3_SDK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../vst3sdk) + set(VST3_SDK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../vst3sdk) else() - set(VST3_SDK_DIR $ENV{VST3_SDK_DIR}) + file(TO_CMAKE_PATH "$ENV{VST3_SDK_DIR}" VST3_SDK_DIR) endif() if(NOT EXISTS ${VST3_SDK_DIR}/CMakeLists.txt) @@ -88,11 +93,32 @@ elseif(WIN32) ) endif() -target_compile_definitions(dart_vst_host PRIVATE +target_compile_definitions(dart_vst_host PRIVATE DART_VST_HOST_EXPORTS - RELEASE=1 + $<$:_DEBUG> + $<$:DEVELOPMENT=1> + $<$>:NDEBUG> + $<$>:RELEASE=1> ) +if(MSVC) + target_compile_options(dart_vst_host PRIVATE + $<$>:/O2> + $<$>:/Oi> + $<$>:/Ot> + $<$>:/GF> + $<$>:/Gy> + $<$>:/fp:fast> + ) +else() + target_compile_options(dart_vst_host PRIVATE + $<$>:-O3> + $<$>:-fno-math-errno> + $<$>:-fno-trapping-math> + $<$>:-ffp-contract=fast> + ) +endif() + if(APPLE) find_library(COCOA_FRAMEWORK Cocoa) find_library(CARBON_FRAMEWORK Carbon) diff --git a/dart_vst_host/native/src/dart_vst_host.cpp b/dart_vst_host/native/src/dart_vst_host.cpp index 234477d..b6e6824 100644 --- a/dart_vst_host/native/src/dart_vst_host.cpp +++ b/dart_vst_host/native/src/dart_vst_host.cpp @@ -52,11 +52,12 @@ struct DVH_HostState { struct DVH_PluginState { std::shared_ptr module; VST3::Hosting::ClassInfo classInfo; + // Owns initialization, the component/controller connection and terminate. + // Declared after module, so the module outlives it. + IPtr provider; IPtr component; IPtr processor; IPtr controller; - IPtr compCP; - IPtr ctrlCP; ParameterChanges inputParamChanges; ParameterChanges outputParamChanges; @@ -125,12 +126,16 @@ DVH_Plugin dvh_load_plugin(DVH_Host host, const char* module_path_utf8, const ch } if (!found) return nullptr; - auto plugProvider = std::make_shared(mod->getFactory(), chosen, true); + // PlugProvider reads the context while initializing, and the most recently + // created host may not be this one. + Vst::PluginContextFactory::instance().setPluginContext(&hs->hostApp); + auto plugProvider = owned(new Vst::PlugProvider(mod->getFactory(), chosen, true)); if (!plugProvider->initialize()) return nullptr; auto* ps = new DVH_PluginState(); ps->module = mod; ps->classInfo = chosen; + ps->provider = plugProvider; ps->component = plugProvider->getComponentPtr(); ps->controller = plugProvider->getControllerPtr(); @@ -144,25 +149,10 @@ DVH_Plugin dvh_load_plugin(DVH_Host host, const char* module_path_utf8, const ch return nullptr; } - ps->component->initialize(&((DVH_HostState*)host)->hostApp); - if (ps->controller) - ps->controller->initialize(&((DVH_HostState*)host)->hostApp); - - // Connect component and controller via IConnectionPoint if both - // expose it. This is necessary for parameter automation to flow. - ps->component->queryInterface(IConnectionPoint::iid, (void**)&ps->compCP); - if (ps->controller) - ps->controller->queryInterface(IConnectionPoint::iid, (void**)&ps->ctrlCP); - if (ps->compCP && ps->ctrlCP) { - ps->compCP->connect(ps->ctrlCP); - ps->ctrlCP->connect(ps->compCP); - } - return (DVH_Plugin)ps; } -// Unload a previously loaded plug‑in. Terminates the component and -// controller and frees the DVH_PluginState. Does nothing if p is +// Unload a previously loaded plug‑in. Deactivates it and frees the DVH_PluginState. Does nothing if p is // nullptr. void dvh_unload_plugin(DVH_Plugin p) { if (!p) return; @@ -171,12 +161,7 @@ void dvh_unload_plugin(DVH_Plugin p) { ps->processor->setProcessing(false); ps->component->setActive(false); } - if (ps->compCP && ps->ctrlCP) { - ps->compCP->disconnect(ps->ctrlCP); - ps->ctrlCP->disconnect(ps->compCP); - } - if (ps->controller) ps->controller->terminate(); - if (ps->component) ps->component->terminate(); + // The provider disconnects and terminates when it is destroyed. delete ps; } diff --git a/dart_vst_host/pubspec.lock b/dart_vst_host/pubspec.lock index 58652a9..ee9e403 100644 --- a/dart_vst_host/pubspec.lock +++ b/dart_vst_host/pubspec.lock @@ -66,7 +66,7 @@ packages: source: hosted version: "3.1.2" coverage: - dependency: transitive + dependency: "direct dev" description: name: coverage sha256: "5da775aa218eaf2151c721b16c01c7676fbfdd99cebba2bf64e8b807a28ff94d" diff --git a/dart_vst_host/pubspec.yaml b/dart_vst_host/pubspec.yaml index 232a687..be90924 100644 --- a/dart_vst_host/pubspec.yaml +++ b/dart_vst_host/pubspec.yaml @@ -7,4 +7,5 @@ dependencies: ffi: ^2.1.0 meta: ^1.12.0 dev_dependencies: + coverage: ^1.15.0 test: ^1.24.0 \ No newline at end of file diff --git a/dart_vst_host/test/host_audio_regression_test.dart b/dart_vst_host/test/host_audio_regression_test.dart new file mode 100644 index 0000000..63ac193 --- /dev/null +++ b/dart_vst_host/test/host_audio_regression_test.dart @@ -0,0 +1,20 @@ +import 'package:dart_vst_host/dart_vst_host.dart'; +import 'package:test/test.dart'; + +import 'host_test_harness.dart'; + +/// Verifies real native plugin loading and exact stereo processing. +void main() { + test('T6 T7 real ADelay returns exact one-sample delayed stereo impulse', () { + final plugin = loadFixture('audio'); + expect(plugin.setParamNormalized(100, 0), isTrue); + _assertImpulse(resumePlugin(plugin)); + }, timeout: const Timeout(Duration(minutes: 10))); +} + +void _assertImpulse(VstPlugin plugin) { + final (left, right) = renderStereoImpulse(plugin); + final expected = List.filled(512, 0)..[1] = 0.5; + expect(left, orderedEquals(expected)); + expect(right, orderedEquals(expected)); +} diff --git a/dart_vst_host/test/host_test.dart b/dart_vst_host/test/host_test.dart index 2041811..68f2503 100644 --- a/dart_vst_host/test/host_test.dart +++ b/dart_vst_host/test/host_test.dart @@ -1,352 +1,27 @@ import 'dart:io'; -import 'dart:math'; -import 'dart:typed_data'; -import 'package:test/test.dart'; import 'package:dart_vst_host/dart_vst_host.dart'; +import 'package:test/test.dart'; -/// Create a simple WAV file from Float32 audio data -Uint8List _createWavFile(Float32List audioData, int sampleRate) { - final numSamples = audioData.length; - final byteRate = sampleRate * 2; // 16-bit mono - final dataSize = numSamples * 2; // 16-bit samples - final fileSize = 36 + dataSize; - - final bytes = ByteData(44 + dataSize); - int offset = 0; - - // RIFF header - bytes.setUint8(offset++, 0x52); // 'R' - bytes.setUint8(offset++, 0x49); // 'I' - bytes.setUint8(offset++, 0x46); // 'F' - bytes.setUint8(offset++, 0x46); // 'F' - bytes.setUint32(offset, fileSize, Endian.little); - offset += 4; - bytes.setUint8(offset++, 0x57); // 'W' - bytes.setUint8(offset++, 0x41); // 'A' - bytes.setUint8(offset++, 0x56); // 'V' - bytes.setUint8(offset++, 0x45); // 'E' - - // fmt chunk - bytes.setUint8(offset++, 0x66); // 'f' - bytes.setUint8(offset++, 0x6D); // 'm' - bytes.setUint8(offset++, 0x74); // 't' - bytes.setUint8(offset++, 0x20); // ' ' - bytes.setUint32(offset, 16, Endian.little); - offset += 4; // chunk size - bytes.setUint16(offset, 1, Endian.little); - offset += 2; // PCM format - bytes.setUint16(offset, 1, Endian.little); - offset += 2; // mono - bytes.setUint32(offset, sampleRate, Endian.little); - offset += 4; - bytes.setUint32(offset, byteRate, Endian.little); - offset += 4; - bytes.setUint16(offset, 2, Endian.little); - offset += 2; // block align - bytes.setUint16(offset, 16, Endian.little); - offset += 2; // bits per sample - - // data chunk - bytes.setUint8(offset++, 0x64); // 'd' - bytes.setUint8(offset++, 0x61); // 'a' - bytes.setUint8(offset++, 0x74); // 't' - bytes.setUint8(offset++, 0x61); // 'a' - bytes.setUint32(offset, dataSize, Endian.little); - offset += 4; - - // Convert float32 to 16-bit PCM - for (int i = 0; i < numSamples; i++) { - final sample = (audioData[i] * 32767).round().clamp(-32768, 32767); - bytes.setInt16(offset, sample, Endian.little); - offset += 2; - } - - return bytes.buffer.asUint8List(); -} +import 'host_test_harness.dart'; void main() { - // Only run tests when the native library is present - final libFile = Platform.isWindows - ? File('dart_vst_host.dll') - : Platform.isMacOS - ? File('libdart_vst_host.dylib') - : File('libdart_vst_host.so'); - if (!libFile.existsSync()) { - throw Exception( - 'Native library ${libFile.path} not found! Build the native library first.'); - } - - test('load missing plug‑in throws', () { - final host = VstHost.create( - sampleRate: 48000, maxBlock: 512, dylibPath: libFile.absolute.path); - try { - expect(() => host.load('/nonexistent/plugin.vst3'), - throwsA(isA())); - } finally { - host.dispose(); - } - }); - - test('audio generation and save to file', () { - final host = VstHost.create( - sampleRate: 48000, maxBlock: 512, dylibPath: libFile.absolute.path); - try { - // Create test audio buffers - final blockSize = 256; - final inL = Float32List(blockSize); - final inR = Float32List(blockSize); - final outL = Float32List(blockSize); - final outR = Float32List(blockSize); - - // Generate a 440Hz sine wave for testing - for (int i = 0; i < blockSize; i++) { - final sample = 0.5 * sin(2 * pi * 440 * i / 48000); - inL[i] = sample; - inR[i] = sample; - } - - print( - 'Generated sine wave input: first 10 samples = ${inL.take(10).toList()}'); - print( - 'Input RMS: ${sqrt(inL.map((x) => x * x).reduce((a, b) => a + b) / blockSize)}'); - - // Verify the sine wave generation is correct - expect(inL[0], closeTo(0.0, 0.001)); // First sample should be near 0 - expect(inL.any((sample) => sample > 0.1), - isTrue); // Should have positive values - expect(inL.any((sample) => sample < -0.1), - isTrue); // Should have negative values - - // Test that we can create and use the host - expect(host, isNotNull); - print('Host created successfully'); - - // Copy input to output (passthrough test) - for (int i = 0; i < blockSize; i++) { - outL[i] = inL[i]; - outR[i] = inR[i]; - } - - // Verify audio passthrough - final outputRMS = - sqrt(outL.map((x) => x * x).reduce((a, b) => a + b) / blockSize); - print('Output RMS: $outputRMS'); - print('Output first 10 samples = ${outL.take(10).toList()}'); - - expect(outputRMS, - closeTo(0.354, 0.01)); // RMS of 0.5 amplitude sine wave ≈ 0.354 - - // Save audio to a WAV file so we can actually hear it! - final duration = 2.0; // 2 seconds - final sampleRate = 48000; - final totalSamples = (duration * sampleRate).round(); - final audioData = Float32List(totalSamples); - - // Generate 2 seconds of 440Hz sine wave - for (int i = 0; i < totalSamples; i++) { - audioData[i] = 0.5 * sin(2 * pi * 440 * i / sampleRate); - } - - // Create a simple WAV file - final outputFile = File('/workspace/test_audio_440hz.wav'); - final wavData = _createWavFile(audioData, sampleRate); - outputFile.writeAsBytesSync(wavData); - - print('Audio saved to: ${outputFile.path}'); - print('File size: ${outputFile.lengthSync()} bytes'); - print('Duration: ${duration}s at ${sampleRate}Hz'); - print('Download this file to your Mac and play it!'); - print( - 'Audio processing test completed - verified audio generation and saved to file'); - } finally { - host.dispose(); - } - }); - - test('VST3 FX processing - MUST load real plugins or FAIL HARD', () { - final host = VstHost.create( - sampleRate: 48000, maxBlock: 512, dylibPath: libFile.absolute.path); - - VstPlugin? reverbPlugin; - - try { - // HARD REQUIREMENT: Load FlutterDartReverb plugin - FAIL if not found - final reverbPath = '/workspace/vst_plugins/FlutterDartReverb.vst3'; - - if (!File(reverbPath).existsSync() && - !Directory(reverbPath).existsSync()) { - throw Exception( - '🔥 HARD FAIL: FlutterDartReverb VST3 plugin NOT FOUND at $reverbPath'); - } - - reverbPlugin = host.load(reverbPath); - print('✅ REVERB PLUGIN LOADED: $reverbPath'); - - // Generate 100ms on/off pattern audio - final duration = 4.0; - final sampleRate = 48000; - final totalSamples = (duration * sampleRate).round(); - final onDuration = 0.1; // 100ms on - final offDuration = 0.1; // 100ms off - final cycleDuration = onDuration + offDuration; - final onSamples = (onDuration * sampleRate).round(); - final cycleSamples = (cycleDuration * sampleRate).round(); - - final audioData = Float32List(totalSamples); - - // Generate 100ms on/off pattern with 440Hz sine wave - for (int i = 0; i < totalSamples; i++) { - final cyclePos = i % cycleSamples; - final isOn = cyclePos < onSamples; - - if (isOn) { - audioData[i] = 0.5 * sin(2 * pi * 440 * i / sampleRate); - } else { - audioData[i] = 0.0; - } - } - - print( - 'Generated 100ms on/off pattern - ${(duration / cycleDuration).round()} cycles'); - - // PROCESS THROUGH REVERB PLUGIN - final reverbResumed = - reverbPlugin.resume(sampleRate: 48000, maxBlock: 512); - if (!reverbResumed) { - throw Exception('🔥 HARD FAIL: Reverb plugin failed to resume!'); - } - - print('Reverb plugin parameters: ${reverbPlugin.paramCount()}'); - - // Process audio through reverb - final blockSize = 512; - final finalAudio = Float32List(totalSamples); - - for (int start = 0; start < totalSamples; start += blockSize) { - final end = (start + blockSize).clamp(0, totalSamples); - final currentBlockSize = end - start; - - final inL = Float32List(currentBlockSize); - final inR = Float32List(currentBlockSize); - final outL = Float32List(currentBlockSize); - final outR = Float32List(currentBlockSize); - - // Copy input audio - for (int i = 0; i < currentBlockSize; i++) { - inL[i] = audioData[start + i]; - inR[i] = audioData[start + i]; - } - - // Process through reverb plugin - final processed = reverbPlugin.processStereoF32(inL, inR, outL, outR); - if (!processed) { - throw Exception( - '🔥 HARD FAIL: Reverb plugin processing failed at sample $start!'); - } - - // Copy output data (use left channel) - for (int i = 0; i < currentBlockSize; i++) { - finalAudio[start + i] = outL[i]; - } - } - - reverbPlugin.suspend(); - print('✅ REVERB PROCESSING COMPLETED'); - - // Save the processed audio - final outputFile = File('/workspace/test_vst3_fx_audio.wav'); - final wavData = _createWavFile(finalAudio, sampleRate); - outputFile.writeAsBytesSync(wavData); - - final finalRMS = sqrt( - finalAudio.map((x) => x * x).reduce((a, b) => a + b) / totalSamples); - - print('🎵 REAL VST3 FX PROCESSING COMPLETED!'); - print('Output file: ${outputFile.path}'); - print('File size: ${outputFile.lengthSync()} bytes'); - print('Final RMS: $finalRMS'); - - // HARD VERIFICATION - output must be different from input - final inputRMS = sqrt( - audioData.map((x) => x * x).reduce((a, b) => a + b) / totalSamples); - if ((finalRMS - inputRMS).abs() < 0.01) { - throw Exception( - '🔥 HARD FAIL: VST3 effects had no audible impact! Input RMS: $inputRMS, Output RMS: $finalRMS'); - } - - expect(outputFile.existsSync(), isTrue); - expect(finalRMS, greaterThan(0.1)); - print('✅ TEST PASSED: FlutterDartReverb plugin processed audio successfully!'); - } finally { - reverbPlugin?.unload(); - host.dispose(); - } + test('load missing plugin throws', () { + final host = createHost(); + expect(() => host.load(File('missing-plugin.vst3').absolute.path), + throwsA(isA())); }); - test('try loading built plugin', () { - final host = VstHost.create( - sampleRate: 48000, maxBlock: 512, dylibPath: libFile.absolute.path); - try { - // Try to load our built plugin - final pluginPath = '/workspace/plugin/build/libdvh_plugin.so'; - final pluginFile = File(pluginPath); - - if (pluginFile.existsSync()) { - print('Found plugin at: $pluginPath'); - try { - final plugin = host.load(pluginPath); - print('Successfully loaded plugin!'); - - // Test basic plugin functionality - print('Parameter count: ${plugin.paramCount()}'); - - // Test audio processing if plugin loads - final blockSize = 256; - final inL = Float32List(blockSize); - final inR = Float32List(blockSize); - final outL = Float32List(blockSize); - final outR = Float32List(blockSize); + test('loads a real plugin and processes stereo audio', () { + _process(resumePlugin(loadFixture('host'))); + }, timeout: const Timeout(Duration(minutes: 10))); - // Generate test audio - for (int i = 0; i < blockSize; i++) { - final sample = 0.3 * sin(2 * pi * 440 * i / 48000); - inL[i] = sample; - inR[i] = sample; - } - - // Resume plugin for processing - final resumed = plugin.resume(sampleRate: 48000, maxBlock: blockSize); - print('Plugin resume result: $resumed'); - - if (resumed) { - // Process audio through plugin - final processed = plugin.processStereoF32(inL, inR, outL, outR); - print('Audio processing result: $processed'); - - if (processed) { - final outputRMS = sqrt( - outL.map((x) => x * x).reduce((a, b) => a + b) / blockSize); - print('Plugin output RMS: $outputRMS'); - print( - 'Plugin output first 10 samples = ${outL.take(10).toList()}'); - - expect(processed, isTrue); - print('SUCCESS: Plugin processed audio!'); - } - - plugin.suspend(); - } + test('real SDK plugin exposes controller parameters', () { + expect(loadFixture('host').paramCount(), greaterThan(0)); + }, timeout: const Timeout(Duration(minutes: 10))); +} - plugin.unload(); - } catch (e) { - print('Plugin loading failed: $e'); - // This is expected if the plugin format is wrong - } - } else { - print('Plugin not found at: $pluginPath'); - } - } finally { - host.dispose(); - } - }); +void _process(VstPlugin plugin) { + final (left, right) = renderStereoImpulse(plugin); + expect(left.every((sample) => sample.isFinite), isTrue); + expect(right.every((sample) => sample.isFinite), isTrue); } diff --git a/dart_vst_host/test/host_test_harness.dart b/dart_vst_host/test/host_test_harness.dart new file mode 100644 index 0000000..08b5840 --- /dev/null +++ b/dart_vst_host/test/host_test_harness.dart @@ -0,0 +1,50 @@ +// Copyright (c) 2025 +// Shared harness for tests hosting real plugins through the native library. + +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:dart_vst_host/dart_vst_host.dart'; +import 'package:test/test.dart'; + +import 'plugin_fixture.dart'; + +/// A host over the real native library at 48 kHz, disposed at test end. +VstHost createHost() { + final host = VstHost.create( + sampleRate: 48000, maxBlock: 512, dylibPath: _libraryPath()); + addTearDown(host.dispose); + return host; +} + +/// The [name] fixture plugin loaded into a host, unloaded at test end. +VstPlugin loadFixture(String name) { + final plugin = createHost().load(pluginFixture(name)); + addTearDown(plugin.unload); + return plugin; +} + +/// Resumes [plugin] at 48 kHz, expecting success, and suspends it at test end. +VstPlugin resumePlugin(VstPlugin plugin) { + expect(plugin.resume(sampleRate: 48000, maxBlock: 512), isTrue); + addTearDown(plugin.suspend); + return plugin; +} + +/// Renders one 512-sample block holding a single 0.5 impulse at sample 0 +/// through [plugin], expecting success, and returns both output channels +/// pre-filled with NaN so an unwritten sample fails the caller's assertion. +(Float32List, Float32List) renderStereoImpulse(VstPlugin plugin) { + final input = Float32List(512)..[0] = 0.5; + final left = Float32List(512)..fillRange(0, 512, double.nan); + final right = Float32List(512)..fillRange(0, 512, double.nan); + expect(plugin.processStereoF32(input, input, left, right), isTrue); + return (left, right); +} + +String _libraryPath() => File(switch (Platform.operatingSystem) { + 'windows' => 'dart_vst_host.dll', + 'macos' => 'libdart_vst_host.dylib', + 'linux' => 'libdart_vst_host.so', + _ => throw UnsupportedError('Unsupported platform'), + }).absolute.path; diff --git a/dart_vst_host/test/native/harness_test.sh b/dart_vst_host/test/native/harness_test.sh new file mode 100644 index 0000000..9a087e4 --- /dev/null +++ b/dart_vst_host/test/native/harness_test.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Failure injection for the root Makefile; no native/plugin build is needed. +set -euo pipefail +cd "$(dirname "$0")/../../.." +root=$PWD +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT +printf '#!/bin/sh\ncase "$PWD" in */"$FAIL_PACKAGE") exit 37;; esac\nexit 0\n' > "$tmp/dart" +cp "$tmp/dart" "$tmp/flutter" +chmod +x "$tmp/dart" "$tmp/flutter" +for package in dart_vst_host dart_vst_graph flutter_vst3 vsts/flutter_reverb vsts/echo; do + if PATH="$tmp:$PATH" FAIL_PACKAGE="$package" make -C "$root" -o native -o dart-deps -o _test-native test > "$tmp/output" 2>&1; then + printf 'FAIL: make test hid failure in %s\n' "$package" >&2 + exit 1 + fi + grep -q 'Error 37' "$tmp/output" + printf 'PASS: make test propagated %s exit 37\n' "$package" +done diff --git a/dart_vst_host/test/plugin_fixture.dart b/dart_vst_host/test/plugin_fixture.dart new file mode 100644 index 0000000..d7ff2f3 --- /dev/null +++ b/dart_vst_host/test/plugin_fixture.dart @@ -0,0 +1,38 @@ +import 'dart:io'; + +/// Finds an explicit plugin or builds the SDK's real ADelay plugin for hosting. +/// +/// Test files run in parallel, so each passes its own [name] for a build folder. +String pluginFixture(String name) => + Platform.environment['VST3_TEST_PLUGIN'] ?? _buildSdkPlugin(name); + +String _buildSdkPlugin(String name) { + final sdk = Platform.environment['VST3_SDK_DIR'] ?? + (throw StateError( + 'Set VST3_SDK_DIR to build ADelay, or VST3_TEST_PLUGIN')); + final build = Directory('build/test-sdk/$name').absolute.path; + _run([ + '-S', + sdk, + '-B', + build, + '-DCMAKE_BUILD_TYPE=Release', + '-DSMTG_ENABLE_VSTGUI_SUPPORT=OFF', + '-DSMTG_CREATE_PLUGIN_LINK=OFF', + '-DSMTG_ENABLE_VST3_HOSTING_EXAMPLES=OFF' + ]); + _run(['--build', build, '--target', 'adelay', '--parallel', '2']); + final plugin = Directory('$build/VST3/Release/adelay.vst3'); + return plugin.existsSync() + ? plugin.path + : (throw StateError('ADelay build did not produce ${plugin.path}')); +} + +void _run(List arguments) { + final result = Process.runSync('cmake', arguments); + result.exitCode == 0 + ? null + : throw StateError( + 'cmake ${arguments.join(' ')} failed (${result.exitCode})\n' + '${result.stdout}\n${result.stderr}'); +} diff --git a/docs/FLUTTER_UI_SPEC.md b/docs/FLUTTER_UI_SPEC.md new file mode 100644 index 0000000..4659e97 --- /dev/null +++ b/docs/FLUTTER_UI_SPEC.md @@ -0,0 +1,399 @@ +# Plugin UI and DSP design + +The VST3 module runs in the audio host process. Its editor embeds a Flutter engine in the host-provided native window (Cocoa on macOS, Win32 on Windows, GTK/X11 on Linux). The Flutter editor is not the audio processor. + +DSP runs in a separate compiled Dart worker process for each plugin instance. The native processor exchanges audio blocks and parameter commands with that worker through shared memory and platform synchronization primitives. Audio is copied between the host buffers and shared memory; this is not zero-copy. + +The controller connects Flutter parameter gestures to VST3 host automation. The editor reads the instance's shared-memory telemetry for visualization. Saved parameter state belongs to the VST3 processor and must be replayed to the worker when restoring a session. Closing an editor must not stop DSP; disposing a processor must release its worker and IPC resources. + +Linux embedded editors require X11. Launch Flutter hosts with `GDK_BACKEND=x11 flutter run`; Wayland embedding is not supported. + +Each requirement below has a spec ID, the code that implements it, and the test that proves it. `Test: none` means nothing proves it yet. Cite IDs in code and tests. + +## Process model + +### [PROCESS-ONE-WORKER-PER-INSTANCE] +Each `Vst3IpcHost` owns exactly one worker process, one shared block and two named semaphores; there is no shared pool of workers or blocks. Disposing one host MUST NOT disturb another host's worker or DSP state. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:85-98 · Test: flutter_vst3/test/native/ipc_host_test.cpp + +### [PROCESS-WORKER-LAUNCH] +The constructor MUST NOT spawn anything; the worker starts on the first `configure()`. The executable is the sibling of the loaded module named `_processor` (`.exe` appended on Windows), started with exactly four values: shm name, ready semaphore, done semaphore, host pid; the Dart entry point MUST reject any other argument count with `ArgumentError`. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:45-52,98 · Test: none + +### [PROCESS-LIVE-RECONFIGURE] +`configure()` on a healthy running host MUST reuse the running worker: it reclaims the block, writes `sampleRate` and `maxBlockSize`, sends `VST3_CMD_CONFIGURE` and waits for the reply. The worker pid MUST be unchanged by that path. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:69-75 · Test: flutter_vst3/test/native/ipc_host_test.cpp + +### [PROCESS-RESTART-ON-CONFIGURE] +A `configure()` after the worker died MUST dispose the remains and spawn a new worker; every previously known parameter value is marked dirty and pushed with the new worker's first block. The host MUST NOT restart a worker from `process()`. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:76-81,104 · Test: flutter_vst3/test/native/ipc_host_recovery_test.cpp + +### [PROCESS-WORKER-EXITS-WITH-HOST] +The worker MUST spawn a watcher isolate that exits the process once the host pid is gone: POSIX polls `getppid()` every 250 ms, Windows waits on the host process handle. This MUST hold even when the host is killed without cleanup. +Code: flutter_vst3/lib/src/vst3_shared_memory_processor.dart:265-283 · Test: flutter_vst3/test/native/ipc_host_test.cpp + +## Handshake + +### [IPC-HANDSHAKE-START-SEQUENCE] +Startup MUST follow this order: unique names, map and zero the whole 69,632-byte block, write version/sampleRate/maxBlockSize/`VST3_CMD_IDLE`, write the magic word last, create both semaphores at zero, spawn, wait for the handshake, then unlink the names. The host MUST NOT set `running_` before the handshake reply arrives. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:85-101 · Test: flutter_vst3/test/native/ipc_host_test.cpp + +### [IPC-HANDSHAKE-WORKER-ACK] +The worker MUST reject a block whose magic or version is wrong before touching DSP, then call `initialize(sampleRate, maxBlockSize)` from the block, then post the done semaphore. Startup completes for the host only when that post arrives. +Code: flutter_vst3/lib/src/vst3_worker_loop.dart:73-83 · Test: flutter_vst3/test/vst3_worker_loop_test.dart + +### [IPC-HANDSHAKE-FAILURE] +Handshake and control waits MUST time out after 5000 ms, and a dead child MUST abort the wait immediately with "Dart worker exited". A throwing `configure()` MUST release everything, leaving `isRunning()` false, `workerProcessId()` 0 and `process()` silent. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:20,107-117 · Test: flutter_vst3/test/native/ipc_host_test.cpp + +## Block layout + +### [IPC-BLOCK-MAGIC] +A live block MUST hold `0x56535433` ("VST3") at offset 0 and protocol version `2` at offset 4; both are checked on both sides, and a wrong magic or version MUST NOT be treated as a usable block. +Code: flutter_vst3/native/include/vst3_shared_memory.h:23-26 · Test: flutter_vst3/test/vst3_shared_memory_test.dart + +### [IPC-BLOCK-OFFSETS] +The block is exactly 69,632 bytes with page-aligned audio, little-endian, `#pragma pack(1)`, no atomic fields (non-atomic fields per owner process). +Code: flutter_vst3/native/include/vst3_shared_memory.h:42-58 + +| Offset | Size | Field | +| --- | --- | --- | +| 0 | 4 | `magic` (u32) | +| 4 | 4 | `version` (u32) | +| 8 | 8 | `sampleRate` (f64) | +| 16 | 4 | `maxBlockSize` (u32) | +| 20 | 4 | `command` (u32) | +| 24 | 4 | `numSamples` (i32) | +| 28 | 4 | `hostParamWriteIndex` (u32) | +| 32 | 4 | `hostParamReadIndex` (u32) | +| 36 | 1024 | `hostParams[64]` (16-byte events: id i32 @+0, padding i32 @+4, value f64 @+8) | +| 1060 | 4 | `uiParamWriteIndex` (u32) | +| 1064 | 4 | `uiParamReadIndex` (u32) | +| 1068 | 1024 | `uiParams[64]` | +| 2092 | 2004 | reserved padding to 4096 | +| 4096 | 16384 | `inputL[4096]` (f32) | +| 20480 | 16384 | `inputR[4096]` | +| 36864 | 16384 | `outputL[4096]` | +| 53248 | 16384 | `outputR[4096]` | + +Test: flutter_vst3/test/vst3_shm_layout_test.dart + +### [IPC-BLOCK-LAYOUT-MIRROR] +`flutter_vst3/lib/src/vst3_shm_layout.dart` MUST mirror the header's defines, and any change to a define MUST be made on both sides in the same commit. A test parses the header and fails on any value mismatch. +Code: flutter_vst3/lib/src/vst3_shm_layout.dart:8-68 · Test: flutter_vst3/test/vst3_shm_layout_test.dart + +### [IPC-BLOCK-DEAD-MAGIC] +A block whose worker died or whose host was disposed MUST read magic 0 while its address stays mapped, so an in-process reader sees an invalid block instead of faulting. Readers MUST treat any non-magic value as "DSP not running". +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:194-200 · Test: flutter_vst3/test/native/ipc_host_recovery_test.cpp + +## Commands and audio + +### [IPC-COMMAND-DISPATCH] +The worker MUST read `command` at offset 20 on every handover, apply the matching action, and post done for every command except TERMINATE; an unknown or `IDLE` value MUST be a no-op that still posts done. +Code: flutter_vst3/lib/src/vst3_worker_loop.dart:114-131 · Test: flutter_vst3/test/vst3_worker_loop_test.dart + +| Value | Command | Worker action | +| --- | --- | --- | +| 0 | `VST3_CMD_IDLE` | none | +| 1 | `VST3_CMD_PROCESS` | drain host ring, process `numSamples` | +| 2 | `VST3_CMD_TERMINATE` | leave the loop without posting done | +| 3 | `VST3_CMD_CONFIGURE` | re-read `sampleRate`/`maxBlockSize`, re-initialize | +| 4 | `VST3_CMD_RESET` | clear DSP state | + +### [IPC-AUDIO-CHUNKING] +`process()` MUST split any length above `VST3_SHM_MAX_SAMPLES` (4096) into successive chunks of at most 4096 samples, each a separate handover, and MUST keep the overall result false if any chunk failed. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:243-250 · Test: flutter_vst3/test/native/ipc_host_test.cpp + +### [IPC-AUDIO-COPY] +Per chunk the host MUST flush parameters, copy `numSamples` floats from both input channels into the block, write `numSamples` and `VST3_CMD_PROCESS`, hand over, then copy both output buffers back. Only stereo is supported: fewer than two input or output channels MUST produce silence. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:219-234 · Test: flutter_vst3/test/native/ipc_host_test.cpp + +### [IPC-AUDIO-SILENCE-ON-FAILURE] +When any chunk is late or the worker is dead, the whole output buffer MUST be zeroed and `process()` MUST return false, so the caller's silence flags match every sample. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:215-218,249-250 · Test: flutter_vst3/test/native/ipc_host_recovery_test.cpp + +## Synchronization + +### [IPC-SYNC-HANDOFF] +Ownership passes only through the two semaphores: the host owns the block until it posts ready, the worker owns it until it posts done. While the previous block is unreclaimed the host MUST only try-wait and MUST leave the block byte-for-byte untouched. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:204-212 · Test: flutter_vst3/test/native/ipc_host_recovery_test.cpp + +### [IPC-SYNC-PARAM-PUSH] +`setParameter()` MUST only record the value and mark it dirty; the queue MUST be written just before a handover, with 64-event capacity, and an event that does not fit MUST stay dirty for a later block. A later value for the same id MUST replace the earlier one. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:167-188 · Test: flutter_vst3/test/native/ipc_host_recovery_test.cpp + +### [IPC-SYNC-PARAM-PULL] +The worker MUST drain the host ring at the start of each PROCESS block, apply events in order, and write the read index back; indices are 32-bit counters that wrap and MUST be masked, never clamped. +Code: flutter_vst3/lib/src/vst3_worker_loop.dart:188-204 · Test: flutter_vst3/test/vst3_worker_loop_test.dart + +## Timeouts and worker death + +### [IPC-TIMEOUT-BLOCK-BUDGET] +The wait for a processed block MUST be `max(1 ms, numSamples / sampleRate)`, except in offline mode where it is 30 s; control commands and the handshake use 5000 ms and termination allows a 500 ms grace before the child is killed. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:20-23,226 · Test: flutter_vst3/test/native/ipc_host_recovery_test.cpp + +### [IPC-TIMEOUT-LATE-BLOCK] +On a missed deadline the host MUST mark the worker busy and return silence without any further wait, so subsequent blocks cost a try-wait only until the late done arrives. A late result MUST be discarded, never used for a later block. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:204-212,227-232 · Test: flutter_vst3/test/native/ipc_host_recovery_test.cpp + +### [IPC-DEATH-DETECTION] +A child that is no longer alive MUST be forgotten with `isRunning()` false, `workerProcessId()` 0 and block magic 0. An exception escaping the DSP MUST print to stderr and exit the worker with code 70 so the host sees the death the same way. +Code: flutter_vst3/lib/src/vst3_worker_loop.dart:61,73-90 · Test: flutter_vst3/test/native/ipc_host_recovery_test.cpp + +## Cleanup and leaks + +### [IPC-CLEANUP-DISPOSE] +`dispose()` MUST post `VST3_CMD_TERMINATE` when the block and ready semaphore exist, wait up to 500 ms, then kill the child, close both semaphores, retire the mapping and clear running state. It MUST be safe to call repeatedly, including from the destructor before any configure. +Code: flutter_vst3/native/src/vst3_ipc_host.cpp:137-165 · Test: flutter_vst3/test/native/ipc_host_test.cpp + +### [IPC-CLEANUP-RETIRED-BLOCK] +A retired block MUST stay mapped with magic 0 and be reused by the next `mapCreate()`; the retired pool is process-global, mutex-guarded and never destroyed. Total retained mapping is therefore bounded by the peak instance count, not by the number of configure/dispose cycles. +Code: flutter_vst3/native/src/vst3_ipc_retired.h:34-46 · Test: flutter_vst3/test/native/ipc_host_test.cpp + +### [IPC-CLEANUP-SYSTEM-NAMES] +IPC names MUST be unique per instance and generation (`pid_owner_counter`, within macOS's 31-character limit), created exclusively at mode 0600, and unlinked once the worker has opened them so nothing outlives a host crash. The worker MUST close all inherited descriptors from 3 up before exec so no host handle leaks into it. +Code: flutter_vst3/native/src/vst3_ipc_platform_posix.cpp:36-44,90-92 · Test: flutter_vst3/test/native/ipc_platform_test.cpp + +## Platform embedding + +### [EDITOR-PLATFORM-TYPE] +`isPlatformTypeSupported` MUST return `kResultTrue` only for `kPlatformTypeNSView` on macOS, `kPlatformTypeHWND` on Windows and `kPlatformTypeX11EmbedWindowID` on Linux. `attached` MUST return `kInvalidArgument` for a null parent or any other type, before creating a window, an engine or a pending mount. +Code: flutter_vst3/native/src/embedded_flutter_view.cpp:106; flutter_vst3/native/src/embedded_flutter_view.mm:99 · Test: flutter_vst3/test/native/editor_host_test.cpp + +### [EDITOR-LINUX-X11-EMBED] +On Linux the editor MUST embed through `gtk_plug_new` on the host-supplied X11 window id, add the `FlView` to that plug, and map and raise the plug's XID. The plug MUST be realized and shown with a size request of 600x650 at mount. +Code: flutter_vst3/native/src/embedded_flutter_view_linux_flutter.inc:141 · Test: flutter_vst3/test/native/editor_host_test.cpp + +### [EDITOR-LINUX-X11-REQUIRED] +The Linux Flutter host MUST refuse to initialize unless `gtk_init_check` succeeds and the default display is a `GdkX11Display`; it forces allowed backends to `x11` only when no display exists and `GDK_BACKEND` is unset. When it refuses, `attached` MUST fall through to the GTK fallback host, which applies the same X11 check and returns `kResultFalse` if it also fails. +Code: flutter_vst3/native/src/embedded_flutter_view_linux_flutter.inc:49; flutter_vst3/native/src/embedded_flutter_view_linux_native.inc:25 · Test: flutter_vst3/test/native/editor_host_test.cpp + +### [EDITOR-COCOA-SUBVIEW] +On macOS the view MUST construct a `FlutterViewController` over the bundle's precompiled Dart bundle and add its view as a subview of the host `NSView`, sized to the parent bounds or 600x650 when those are degenerate. The subview MUST resize with the parent via `NSViewWidthSizable | NSViewHeightSizable`. +Code: flutter_vst3/native/src/embedded_flutter_view.mm:244 · Test: none + +### [EDITOR-WIN32-HWND] +On Windows the view MUST create the desktop view controller at 600x650, clear `WS_POPUP` in favour of `WS_CHILD`, and `SetParent` the Flutter HWND into the host HWND. It MUST size that HWND to the parent client rect, falling back to 600x650, and force a redraw. +Code: flutter_vst3/native/src/embedded_flutter_view_win_flutter.inc:169 · Test: flutter_vst3/test/native/editor_host_test.cpp + +### [EDITOR-SIZE] +`getSize` MUST report 600x650 while a Flutter engine is mounted, and 540xmax(280, 74 + parameters*56 + 36) for the native fallback. After `onSize` it MUST report the last accepted rect and propagate that size to the plug, Flutter HWND or Flutter view. After a runtime Flutter failure the view MUST reset its cached size, mount the fallback and resize itself through `IPlugFrame::resizeView` to the fallback rect. +Code: flutter_vst3/native/src/embedded_flutter_view.cpp:166 · Test: flutter_vst3/test/native/editor_host_test.cpp + +## Flutter app detection and native fallback + +### [EDITOR-FLUTTER-DETECT-DESKTOP] +On Windows and Linux the Flutter app MUST be considered present only when the module directory has `data/flutter_assets` as a directory, `data/icudtl.dat` as a file, and an app library (`lib/libapp.so` or `libapp.so` on Linux, `data/app.so` or `flutter_assets/kernel_blob.bin` on Windows). Windows additionally MUST load `flutter_windows.dll` from the module directory before mounting. +Code: flutter_vst3/native/src/embedded_flutter_view_linux_flutter.inc:35; flutter_vst3/native/src/embedded_flutter_view_win_flutter.inc:63 · Test: flutter_vst3/test/native/editor_host_test.cpp + +### [EDITOR-FLUTTER-DETECT-COCOA] +On macOS the Flutter app MUST be considered present only when `Contents/Frameworks` holds `App.framework/App`, `App.framework/Resources/flutter_assets` and `FlutterMacOS.framework/Resources/icudtl.dat`, and the build MUST define `VST3_FLUTTER_ENTRYPOINT`. Otherwise the view MUST mount the Cocoa fallback without attempting to load any framework. +Code: flutter_vst3/native/src/embedded_flutter_view.mm:36 · Test: none + +### [EDITOR-ENTRYPOINT] +macOS and Windows MUST start the Dart function named by `flutterEntrypoint`. The Linux embedder has no public API to name one and always runs `main`, so a plugin's `main` MUST call its `flutterEntrypoint`. +Code: flutter_vst3/native/src/embedded_flutter_view.mm; flutter_vst3/native/src/embedded_flutter_view_win_flutter.inc:145 · Test: flutter_vst3/test/native/repo_rules_test.py + +### [EDITOR-CORRUPT-APP-COCOA] +macOS MUST `dlopen` the App framework executable and reject it before constructing a view, because a corrupt app library crashes the host. A mount exception or an engine that will not run MUST remove the subview, shut the engine down, nil the channel and fall back to the Cocoa sliders. +Code: flutter_vst3/native/src/embedded_flutter_view.mm:66 · Test: flutter_vst3/test/native/editor_host_test.cpp + +### [EDITOR-FALLBACK-NATIVE-ROWS] +The fallback MUST build one row per controller parameter with a name label, a value label rendered from `getParamStringByValue`, and a 0..1 slider (Cocoa `NSSlider`, GTK `GtkScale`, Win32 trackbar). Each row's control MUST begin an edit on gesture start, set and perform on change, and end the edit on release. +Code: flutter_vst3/native/src/native_cocoa_view.mm:101; flutter_vst3/native/src/embedded_flutter_view_linux_native.inc:118 · Test: flutter_vst3/test/native/editor_host_test.cpp + +### [EDITOR-START-WATCHDOG] +A mount MUST arm a 10000 ms watchdog; if the controller still owns the editor and the Dart side has made no channel call, or engine creation failed, the Flutter host MUST tear itself down and the view MUST mount the native fallback. +Code: flutter_vst3/native/include/view_logic.h:12; flutter_vst3/native/src/embedded_flutter_view_linux_flutter.inc:175 · Test: flutter_vst3/test/native/view_logic_test.cpp; flutter_vst3/test/native/editor_host_test.cpp + +## Editor lifecycle + +### [EDITOR-SINGLE-FLUTTER-OWNER] +At most one Flutter editor per module process MAY exist: a second view MUST be refused a Flutter host and MUST mount the 540-wide native fallback. It MUST NOT take over the existing plug, engine or channel, and closing the non-owner MUST NOT disturb the owner's editor. +Code: flutter_vst3/native/src/embedded_flutter_view_linux_flutter.inc:48; flutter_vst3/native/src/embedded_flutter_view_win_flutter.inc:75; flutter_vst3/native/src/embedded_flutter_view.mm:107 · Test: flutter_vst3/test/native/editor_host_test.cpp + +### [EDITOR-DEFERRED-MOUNT] +Engine creation MUST be deferred out of `attached`: a 50 ms GLib timeout on Linux, a 10 ms Win32 timer on Windows, and `dispatch_async` on the macOS main queue. The deferred mount MUST re-check that the editor still owns the controller and, on macOS, that the parent view is unchanged, and MUST be cancellable by closing the editor first. +Code: flutter_vst3/native/src/embedded_flutter_view_linux_flutter.inc:63; flutter_vst3/native/src/embedded_flutter_view_win_flutter.inc:100; flutter_vst3/native/src/embedded_flutter_view.mm:112 · Test: flutter_vst3/test/native/editor_host_test.cpp + +### [EDITOR-LIVENESS-TOKEN] +On macOS every queued UI action — parameter updates, fallback label refresh and method calls — MUST run only when the editor's liveness token is still set. Closing the editor MUST clear the token so work already queued is dropped instead of touching a torn-down view. +Code: flutter_vst3/native/include/view_logic.h:8; flutter_vst3/native/src/embedded_flutter_view.mm:159 · Test: flutter_vst3/test/native/editor_liveness_test.cpp; flutter_vst3/test/native/editor_host_test.cpp + +### [EDITOR-CLOSE-ENDS-EDITS] +`removed` MUST end any gesture still open on the controller before tearing the UI down. A release that arrives after the editor closed MUST NOT be able to reopen or extend that gesture. +Code: flutter_vst3/native/src/embedded_flutter_view.cpp:160; flutter_vst3/native/src/embedded_flutter_view.mm:121 · Test: flutter_vst3/test/native/editor_host_test.cpp + +### [EDITOR-CLOSE-KEEPS-ENGINE] +Closing a mounted Flutter editor MUST only notify `onHostDetached`, hide the view and detach it from the host window — reparenting to the root window on Linux and to a hidden holder window on Windows — and MUST NOT destroy the engine or the channel. Only a startup failure MAY destroy the engine and plug. +Code: flutter_vst3/native/src/embedded_flutter_view_linux_flutter.inc:297; flutter_vst3/native/src/embedded_flutter_view_win_flutter.inc:206 · Test: flutter_vst3/test/native/editor_host_test.cpp + +### [EDITOR-REOPEN-RESYNC] +Reopening MUST re-embed the surviving plug/view into the new parent window and resize it, then invoke `onHostAttached` and push every parameter's current normalized value to Dart before any user input. A view reattached after being closed MUST choose Flutter again when it is eligible, not keep the stale native size. +Code: flutter_vst3/native/src/embedded_flutter_view_linux_flutter.inc:234; flutter_vst3/native/src/embedded_flutter_view_win_flutter.inc:177 · Test: flutter_vst3/test/native/editor_host_test.cpp + +## Telemetry + +### [TELEMETRY-SHM-INFO] +`getSharedMemoryInfo` MUST reply with `address` taken from that instance's controller, plus `totalSize` and `maxSamples` as the shared-memory constants, and MUST reply 0 for the address when the controller has no block. The reply MUST be per instance, never a process-global block. +Code: flutter_vst3/native/src/embedded_flutter_view.mm:309; flutter_vst3/native/src/embedded_flutter_view_linux_flutter.inc:121 · Test: vsts/echo/test/ui_regression_test.dart + +### [TELEMETRY-READER-MAGIC] +A reader MUST be created only when the address is non-zero and the first 32-bit word of the block equals `vst3ShmMagic`; otherwise the result MUST be null. `isValid` MUST re-read the magic on every check. +Code: flutter_vst3/lib/src/shared_memory_reader.dart:32 · Test: flutter_vst3/test/shared_memory_reader_test.dart + +### [TELEMETRY-DSP-STOPPED-FLAG] +Each reader fetch MUST set `dspStopped` to true only when the address is non-zero and the reader came back null, and MUST notify listeners only when the flag changes. A zero address MUST read as deactivated, not stopped, and a failed fetch MUST leave the flag unchanged. +Code: flutter_vst3/lib/src/parameter_binding.dart:238 · Test: flutter_vst3/test/dsp_stopped_test.dart + +### [TELEMETRY-DSP-STOPPED-MESSAGE] +Echo's editor MUST show the text "DSP stopped. Audio is silent until the plugin is re-enabled." exactly while `dspStopped` is true, and MUST remove it when a fetch succeeds again. +Code: vsts/echo/lib/ui/echo_ui.dart:125 · Test: vsts/echo/test/ui_regression_test.dart + +### [TELEMETRY-RESTART-POLL] +The waveform visualiser MUST poll every 33 ms and MUST do nothing while the host is detached. An invalid reader MUST be dropped and refetched immediately; a missing reader MUST trigger a refetch at most once per 30 ticks, whether or not `dspStopped` is set, because the plugin may be activated after the editor opens. +Code: vsts/echo/lib/ui/echo_ui.dart:181; vsts/echo/lib/ui/echo_ui.dart:219 · Test: vsts/echo/test/ui_regression_test.dart + +### [TELEMETRY-DETACH] +`onHostDetached` MUST set `isHostAttached` false, drop the cached reader and clear pending begins before notifying listeners. `onHostAttached` MUST set it true, drop the reader and reload the initial parameter map. +Code: flutter_vst3/lib/src/parameter_binding.dart:58 · Test: vsts/echo/test/ui_regression_test.dart + +### [TELEMETRY-BOUNDS] +`numSamples` MUST be clamped to 0..`vst3ShmMaxSamples`, and every typed-list accessor MUST return an empty list when the block is invalid. `getLatestOutputSamples` MUST return a mono average of output L and R, capped by `maxCount` and the shared-memory maximum, as a copy rather than a view. +Code: flutter_vst3/lib/src/shared_memory_reader.dart:50; flutter_vst3/lib/src/shared_memory_reader.dart:91 · Test: flutter_vst3/test/shared_memory_reader_test.dart + +## Parameter gestures and values + +### [PARAM-GESTURE-DEFERRED] +`beginEdit` MUST only add the id to a local pending set; it MUST NOT send anything over the `flutter_vst3/parameters` channel. +Code: flutter_vst3/lib/src/parameter_binding.dart:176 · Test: flutter_vst3/test/parameter_binding_contract_test.dart + +### [PARAM-GESTURE-VALUE-OPENS] +The first `setParameter` for a pending id MUST send `beginEdit` with `{'id': id}` before sending `setParameter` with `{'id': id, 'value': clamped}`, so a tap that never changes a value leaves no host gesture. +Code: flutter_vst3/lib/src/parameter_binding.dart:196 · Test: flutter_vst3/test/parameter_binding_contract_test.dart + +### [PARAM-GESTURE-END] +`endEdit` MUST send `endEdit` with `{'id': id}` only when the id is no longer pending, and MUST send nothing when the gesture never reached the host. +Code: flutter_vst3/lib/src/parameter_binding.dart:179 · Test: flutter_vst3/test/parameter_binding_contract_test.dart + +### [PARAM-VALUE-CLAMP] +`setParameter` MUST clamp the value to 0.0..1.0, MUST store the clamped value in the local cache before sending, and MUST notify listeners afterwards. +Code: flutter_vst3/lib/src/parameter_binding.dart:193 · Test: flutter_vst3/test/parameter_binding_contract_test.dart + +### [PARAM-INBOUND-VALIDATION] +An inbound `onParameterChanged` message MUST carry an int id in `0..parameterCount-1` and a finite value in 0.0..1.0; any other id, value or argument shape MUST raise `ArgumentError` and MUST leave the cache unchanged. +Code: flutter_vst3/lib/src/parameter_binding.dart:119 · Test: flutter_vst3/test/parameter_binding_contract_test.dart + +### [PARAM-INITIAL-LOAD] +`loadInitialParameters` MUST accept only a map whose keys are ints or decimal-digit strings and whose values pass the same range check, and MUST apply all of that map or none of it. `MissingPluginException` MUST be ignored, leaving the cache untouched. +Code: flutter_vst3/lib/src/parameter_binding.dart:79 · Test: flutter_vst3/test/parameter_binding_contract_test.dart + +### [PARAM-PERFORM-GESTURE] +A UI value MUST be applied to the controller as `setParamNormalized` followed by `performEdit`. `beginEdit` MUST reach the host only on the first begin for an id, and `performEdit` MUST return `kResultFalse` when no gesture is open for that id. +Code: flutter_vst3/native/templates/plugin_controller.cpp.template:91 · Test: flutter_vst3/test/native/view_logic_test.cpp + +### [PARAM-ECHO-SUPPRESSED] +`setParamNormalized` MUST forward a host value to the active view only when that id is not mid-gesture, and `isEditing` MUST report the inverse, so a UI never receives its own drag echoed back. +Code: flutter_vst3/native/templates/plugin_controller.cpp.template:54 · Test: flutter_vst3/test/native/view_logic_test.cpp + +### [PARAM-AUTOMATION-PER-BLOCK] +The processor MUST apply host automation once per block, using only the last point of each parameter queue, MUST ignore ids at or above the parameter count, and MUST pass accepted values to the worker through `Vst3IpcHost::setParameter`. +Code: flutter_vst3/native/templates/plugin_processor_aot.cpp.template:159 · Test: flutter_vst3/test/native/plugin_host_test.cpp + +## Saved state + +### [STATE-LAYOUT] +Saved state MUST be the parameter count times 8 bytes of IEEE-754 doubles in ascending parameter id, with no header, magic, version or count field. + +| Offset | Size | Contents | +| --- | --- | --- | +| 0 | 8 | normalized value, parameter 0 | +| 8 | 8 | normalized value, parameter 1 | +| 8×n | 8 | normalized value, parameter n | + +Code: flutter_vst3/native/include/vst3_plugin_state.h:14 · Test: flutter_vst3/test/native/plugin_host_test.cpp + +### [STATE-READ-REJECT] +Reading MUST return false when the stream supplies fewer than 8 bytes for any value, or a value that is not finite or is outside 0.0..1.0. A failed read MUST leave the caller's vector unchanged so a state is applied whole or not at all. +Code: flutter_vst3/native/include/vst3_plugin_state.h:22 · Test: flutter_vst3/test/native/plugin_host_test.cpp + +### [STATE-PROCESSOR-IO] +`setState` MUST return `kResultFalse` and change no parameter when the read fails, and MUST mark the state dirty on success. `getState` MUST return `kResultFalse` when the stream takes fewer than 8 bytes for a value. +Code: flutter_vst3/native/templates/plugin_processor_aot.cpp.template:204 · Test: flutter_vst3/test/native/plugin_host_test.cpp + +### [STATE-CONTROLLER-SET-STATE] +Controller `setComponentState` and `setState` MUST use the same reader and apply values through `setParamNormalized`; a rejected state MUST leave every parameter as it was. Controller `getState` MUST write the current normalized values in id order. +Code: flutter_vst3/native/templates/plugin_controller.cpp.template:107 · Test: flutter_vst3/test/native/plugin_host_test.cpp + +### [STATE-REPLAY-DEFERRED] +`setState` MUST NOT talk to the worker; it MUST only mark the state dirty, and the next `process` call MUST push every parameter value to the worker before that block's automation. A restarted worker MUST receive the known values again. +Code: flutter_vst3/native/templates/plugin_processor_aot.cpp.template:176 · Test: flutter_vst3/test/native/plugin_host_test.cpp + +## Lifecycle + +### [LIFECYCLE-SET-ACTIVE-START] +`setActive(true)` MUST configure the worker with the sample rate, block size and offline flag from `setupProcessing`, mark the state dirty, and send the worker's memory address to the controller. A worker that fails to start MUST make `setActive` return `kResultFalse` rather than throw. +Code: flutter_vst3/native/templates/plugin_processor_aot.cpp.template:123 · Test: flutter_vst3/test/native/plugin_host_test.cpp + +### [LIFECYCLE-SET-ACTIVE-STOP] +`setActive(false)` MUST send address 0 to the controller and reset the worker's DSP state; it MUST NOT stop or dispose the worker. +Code: flutter_vst3/native/templates/plugin_processor_aot.cpp.template:130 · Test: flutter_vst3/test/native/plugin_host_test.cpp + +### [LIFECYCLE-PROCESS-NOT-ACTIVE] +`process` MUST silence every output bus and return `kNotInitialized` when there is no IPC host or the last `setActive` did not succeed. +Code: flutter_vst3/native/templates/plugin_processor_aot.cpp.template:183 · Test: flutter_vst3/test/native/plugin_host_test.cpp + +## Build generation + +### [BUILD-GENERATED-SOURCES] +The build MUST generate `_controller.cpp`, `_processor.cpp` and `_factory.cpp` from the three templates, plus `_ids.h` and `metadata.cmake`, into the build directory's `generated` folder. Any unresolved `{{...}}` placeholder MUST abort generation. +Code: flutter_vst3/scripts/generate_plugin.dart:88 · Test: flutter_vst3/test/generate_plugin_test.dart + +### [BUILD-WORKER-EXE] +The build MUST compile `lib/_processor_exe.dart` with `dart compile exe` at configure time and MUST fail configuration when that source is missing or the compile returns non-zero. +Code: flutter_vst3/native/cmake/VST3Bridge.cmake:129 · Test: none + +### [BUILD-PARAMETER-IDS] +Metadata parameter ids MUST be exactly 0..n-1 in order, and every parameter name MUST reduce to a unique C identifier used for its enum entry and display title. +Code: flutter_vst3/scripts/generate_plugin.dart:216 · Test: flutter_vst3/test/generate_plugin_test.dart + +### [BUILD-METADATA-REJECT] +Generation MUST exit non-zero on any invalid metadata, including the cases in the table below. Accepted text MUST have backslashes, quotes and newlines escaped when copied into C++ string literals and CMake values. + +| Rejected input | Reason recorded | +| --- | --- | +| missing `pluginName`/`vendor`/`version`/`category`/`bundleIdentifier`/`companyWeb`/`companyEmail` | required field | +| parameter `defaultValue` not a finite number in 0..1 | invalid parameter default | +| parameter name reducing to an already used identifier | duplicate parameter identifier | +| name or value not convertible to `[A-Za-z][A-Za-z0-9]*` | unusable identifier | +| text containing control characters | expected text without control characters | +| `processorUid`/`controllerUid` set singly, equal, or not 32 hex digits | must be set together / must differ / 32 hex digits | + +Code: flutter_vst3/scripts/generate_plugin.dart:282 · Test: flutter_vst3/test/native/generator_strings_test.py + +## Gaps + +Where the code falls short of this design or lacks a test. Nothing here is fixed yet. + +- The intro says disposing a processor releases its IPC resources, but the mapping is retired, not released: each peak instance retains 69,632 bytes plus its platform handle for the life of the host process. +- The layout declares a UI-to-host parameter ring (`uiParamWriteIndex`/`uiParamReadIndex`/`uiParams` at 1060/1064/1068) that no code reads or writes today; the editor's only shared-memory use is the block address message plus magic-based validity checks. +- `vst3_shm_layout.dart` has no constants for the UI-ring offsets; `vst3_shm_layout_test.dart` compares those three defines against hardcoded literals instead, so they are not actually mirrored. +- After a worker dies nothing restarts it automatically: the template keeps `active_` true and `process()` keeps returning `kResultOk` with silence flags, so the plugin stays silent until the host deactivates and reactivates. +- `vst3_ipc_host.h` claims `process` "never waits longer than the block's own duration", but the budget floor is 1 ms and macOS polls the done semaphore in 50 µs sleeps. +- The `command` field comment in `vst3_shared_memory.h` lists only PROCESS and TERMINATE, while IDLE, CONFIGURE and RESET are also written. +- `shared_memory_reader.dart` validates only the magic word, not the protocol version, so a block from another protocol version would read as valid. +- No test pins the 5000 ms handshake/control timeout or the 500 ms terminate grace; no test asserts the worker's exit code 70 for a DSP exception, only that the host notices the death. +- macOS never invokes `onHostAttached` or `onHostDetached` (only Linux `embedded_flutter_view_linux_flutter.inc:234,305` and Windows `embedded_flutter_view_win_flutter.inc:177,216` do), so on macOS the Dart `isHostAttached` stays at its initial `true`, the cached reader is never dropped on close and no test covers telemetry after a macOS close/reopen. +- `getSize` can report the Flutter 600x650 before `attached` for a view that will then mount the 540-wide native fallback, because `hasFlutter_` is set in the constructor (`embedded_flutter_view.cpp:70`, `embedded_flutter_view.mm:83`) without the ownership check used at attach time. No test calls `getSize` before `attached`. +- On Linux, a non-X11 display makes both the Flutter host and the GTK fallback initialise nothing, so `attached` returns `kResultFalse` and no editor appears at all; the spec prose only says Wayland embedding is unsupported, and this path is untested. +- The startup watchdog treats "no method-channel call within 10 s" as a dead UI, so a working Flutter editor that never calls `flutter_vst3/parameters` would be replaced by native sliders. No test covers that case. +- `withLiveEditor` is used only by macOS; the Windows and Linux views gate queued work on controller identity alone, and `editor_liveness_test.cpp` tests the helper rather than any view. +- `dspStopped` is not cleared by `onHostDetached` (`parameter_binding.dart:58`), so the "DSP stopped" message would persist through a detach; no test covers detach while stopped. +- The "DSP stopped" text exists only in the Echo example UI; `flutter_vst3` itself ships no widget or message for it, so the requirement is example-level, not library-level. +- The generator emits `{{GET_PARAMETER_INFO}}`, `{{PARAMETER_STATE_SAVE}}`, `{{PARAMETER_STATE_LOAD}}`, `{{NORMALIZE_PARAMETER}}` and `{{DENORMALIZE_PARAMETER}}` snippets that no template consumes, so per-parameter min/max and Dart-side text conversion never reach C++; parameter text uses the SDK `EditController` defaults (generate_plugin.dart:128-173 versus native/templates). +- Host automation values are stored and forwarded to the worker without the finite/0..1 check that saved state gets, so an out-of-range automation value reaches the DSP (plugin_processor_aot.cpp.template:159). +- The state reader never checks for trailing bytes, so a stream holding more than the parameter count is accepted (vst3_plugin_state.h:14); no test covers this. +- No test asserts that closing an editor leaves the worker running; `immediateClose` only checks that a closing editor does not change a parameter value (editor_host_regressions.h:51). +- `performEdit`/`endEdit` return codes and the echo suppression on `setParamNormalized` are only covered at the `EditState` level (view_logic_test.cpp), never through the controller. +- The platform channel handlers report success to Flutter for `beginEdit`/`endEdit` even when the controller rejects the gesture (`kResultFalse`), so the failure is invisible to Dart (embedded_flutter_view.mm:321). +- `VST3ParameterBinding.getInstance` fixes `parameterCount` at 64 on first use, so a plugin with more parameters would reject its own ids; no test covers a count above the default. diff --git a/flutter_vst3/CHANGELOG.md b/flutter_vst3/CHANGELOG.md index ffa488e..de71bae 100644 --- a/flutter_vst3/CHANGELOG.md +++ b/flutter_vst3/CHANGELOG.md @@ -1,3 +1,7 @@ +## Unreleased + +- Removed obsolete same-process VST3Bridge registration and FFI callbacks; use the shared-memory worker. + ## 0.1.2 * Corrections diff --git a/flutter_vst3/CONTRIBUTING.md b/flutter_vst3/CONTRIBUTING.md index c626641..be4ce15 100644 --- a/flutter_vst3/CONTRIBUTING.md +++ b/flutter_vst3/CONTRIBUTING.md @@ -26,7 +26,7 @@ We encourage contributors to leverage modern AI development tools like [Claude C ## Code Style -Follow the existing code patterns in the project. Refer to the [CLAUDE.md](../CLAUDE.md) file for coding guidelines. +Follow the existing code patterns in the project. Refer to the [AGENTS.md](../AGENTS.md) file for coding guidelines. ## Questions? diff --git a/flutter_vst3/Makefile b/flutter_vst3/Makefile new file mode 100644 index 0000000..c9fba0f --- /dev/null +++ b/flutter_vst3/Makefile @@ -0,0 +1,2 @@ +PACKAGE_TOOL ?= flutter +include ../mk/package.mk diff --git a/flutter_vst3/README.md b/flutter_vst3/README.md index 07514f9..7c7a92f 100644 --- a/flutter_vst3/README.md +++ b/flutter_vst3/README.md @@ -33,40 +33,44 @@ The guide covers everything you need to build your first VST® 3 plugin: ## API Reference -### VST3Processor +### DSP worker -Base class for all Dart VST® 3 processors: +DSP runs in a compiled Dart worker process, one per plugin instance. Implement +`Vst3WorkerProcessor` for your DSP and pass it to +`runVst3SharedMemoryProcessor` from a headless `_processor_exe.dart` +entry point; the build compiles that file with `dart compile exe` and the VST3 +module exchanges audio and parameters with it over shared memory: ```dart -abstract class VST3Processor { - void initialize(double sampleRate, int maxBlockSize); - void processStereo(List inputL, List inputR, - List outputL, List outputR); - void setParameter(int paramId, double normalizedValue); - double getParameter(int paramId); - int getParameterCount(); - void reset(); - void dispose(); -} -``` +import 'dart:typed_data'; +import 'package:flutter_vst3/flutter_vst3.dart'; -### VST3Bridge +final class MyProcessor implements Vst3WorkerProcessor { + @override + void initialize(double sampleRate, int maxBlockSize) {} -Main bridge for Flutter UI ↔ VST® host communication: + @override + void setParameter(int paramId, double value) {} -```dart -class VST3Bridge { - // Register your processor - static void registerProcessor(VST3Processor processor); - - // Initialize processor (called from C++ layer) - static void initializeProcessor(double sampleRate, int maxBlockSize); - - // Process audio (called from C++ layer) - static void processStereoCallback(/* FFI parameters */); + @override + void processStereo(Float32List inputL, Float32List inputR, + Float32List outputL, Float32List outputR) {} + + @override + void reset() {} + + @override + void dispose() {} +} + +void main(List args) { + runVst3SharedMemoryProcessor(args: args, processor: MyProcessor()); } ``` +See [create_plugin_guide.md](create_plugin_guide.md) and the example plugins in +[`vsts/`](https://github.com/MelbourneDeveloper/flutter_vst3/tree/main/vsts). + ## Examples See the complete example plugins in the main repository: @@ -80,6 +84,11 @@ See the complete example plugins in the main repository: - CMake 3.20+ - Steinberg VST® 3 SDK - C++17 compiler +- Linux: X11 backend required for VST3 plugin GUI (launch with `GDK_BACKEND=x11 flutter run`) + +## Linux editor entrypoint + +On Linux the plugin's `main` is the Flutter UI entrypoint because the public Flutter Linux API cannot select a named entrypoint. `main` and `flutterEntrypoint` must start the same UI. Plugins without `flutterEntrypoint` use native sliders. ## Legal Notice @@ -91,4 +100,4 @@ See: https://steinbergmedia.github.io/vst3_dev_portal/pages/VST+3+Licensing/Inde ## License -This project is licensed under the BSD 3-Clause License - see the [LICENSE](LICENSE) file for details. \ No newline at end of file +This project is licensed under the BSD 3-Clause License - see the [LICENSE](LICENSE) file for details. diff --git a/flutter_vst3/analysis_options.yaml b/flutter_vst3/analysis_options.yaml new file mode 100644 index 0000000..4ec3609 --- /dev/null +++ b/flutter_vst3/analysis_options.yaml @@ -0,0 +1,13 @@ +linter: + rules: + avoid_print: true + empty_catches: true + +analyzer: + errors: + avoid_print: error + empty_catches: error + exclude: + - build/** + # This command-line generator intentionally writes its output to stdout. + - scripts/generate_plugin.dart diff --git a/flutter_vst3/create_plugin_guide.md b/flutter_vst3/create_plugin_guide.md index 20c1bf0..45d5fe5 100644 --- a/flutter_vst3/create_plugin_guide.md +++ b/flutter_vst3/create_plugin_guide.md @@ -239,8 +239,11 @@ dart test ## Installation ```bash -# Install to system VST3 folder -make install +# Add a Makefile to your plugin folder with these two lines +# PLUGIN ?= my_plugin +# include ../plugin.mk +# Then build and copy it to the folder VST3 hosts scan +make -C vsts/my_plugin deploy ``` Your plugin is now ready to use in any VST® 3 host! \ No newline at end of file diff --git a/flutter_vst3/example/README.md b/flutter_vst3/example/README.md index 650bcf0..7266adf 100644 --- a/flutter_vst3/example/README.md +++ b/flutter_vst3/example/README.md @@ -12,23 +12,32 @@ Follow the [Complete Step-by-Step Plugin Creation Guide](../create_plugin_guide. ## Basic Plugin Structure ```dart +import 'dart:typed_data'; import 'package:flutter_vst3/flutter_vst3.dart'; -class MyProcessor extends VST3Processor { +final class MyProcessor implements Vst3WorkerProcessor { @override - void initialize(double sampleRate, int maxBlockSize) { - // Initialize your audio processing - } + void initialize(double sampleRate, int maxBlockSize) {} + + @override + void setParameter(int paramId, double value) {} @override - void processStereo(List inputL, List inputR, - List outputL, List outputR) { - // Your audio processing logic here - for (int i = 0; i < inputL.length; i++) { - outputL[i] = inputL[i]; // Pass through for now - outputR[i] = inputR[i]; - } + void processStereo(Float32List inputL, Float32List inputR, + Float32List outputL, Float32List outputR) { + outputL.setAll(0, inputL); + outputR.setAll(0, inputR); } + + @override + void reset() {} + + @override + void dispose() {} +} + +void main(List args) { + runVst3SharedMemoryProcessor(args: args, processor: MyProcessor()); } ``` diff --git a/flutter_vst3/lib/flutter_vst3.dart b/flutter_vst3/lib/flutter_vst3.dart index a4ada0b..d781592 100644 --- a/flutter_vst3/lib/flutter_vst3.dart +++ b/flutter_vst3/lib/flutter_vst3.dart @@ -1,12 +1,12 @@ /// flutter_vst3 - Framework for VST® 3 Plugin Development -/// +/// /// This package provides the complete framework for building VST® 3 plugins /// with Flutter UI and pure Dart audio processing. It bridges Dart/Flutter /// code with the Steinberg VST® 3 SDK C++ infrastructure. -/// +/// /// VST® is a trademark of Steinberg Media Technologies GmbH. library flutter_vst3; -export 'src/flutter_vst3_bridge.dart'; -export 'src/flutter_vst3_callbacks.dart'; -export 'src/flutter_vst3_parameters.dart'; \ No newline at end of file +export 'src/vst3_shared_memory_processor.dart' show runVst3SharedMemoryProcessor; +export 'src/vst3_shm_layout.dart'; +export 'src/vst3_worker_loop.dart' show Vst3WorkerProcessor; diff --git a/flutter_vst3/lib/src/flutter_vst3_bridge.dart b/flutter_vst3/lib/src/flutter_vst3_bridge.dart deleted file mode 100644 index 498baa8..0000000 --- a/flutter_vst3/lib/src/flutter_vst3_bridge.dart +++ /dev/null @@ -1,118 +0,0 @@ -import 'dart:ffi' as ffi; - -/// Abstract interface that all Dart VST3 processors must implement -abstract class VST3Processor { - /// Initialize the processor with sample rate and block size - void initialize(double sampleRate, int maxBlockSize); - - /// Process stereo audio - void processStereo(List inputL, List inputR, - List outputL, List outputR); - - /// Set parameter value (normalized 0.0-1.0) - void setParameter(int paramId, double normalizedValue); - - /// Get parameter value (normalized 0.0-1.0) - double getParameter(int paramId); - - /// Get total number of parameters - int getParameterCount(); - - /// Reset processor state - void reset(); - - /// Dispose resources - void dispose(); -} - -/// Callback function signatures for FFI -typedef DartInitializeProcessorNative = ffi.Void Function(ffi.Double, ffi.Int32); -typedef DartProcessAudioNative = ffi.Void Function(ffi.Pointer, ffi.Pointer, ffi.Pointer, ffi.Pointer, ffi.Int32); -typedef DartSetParameterNative = ffi.Void Function(ffi.Int32, ffi.Double); -typedef DartGetParameterNative = ffi.Double Function(ffi.Int32); -typedef DartGetParameterCountNative = ffi.Int32 Function(); -typedef DartResetNative = ffi.Void Function(); -typedef DartDisposeNative = ffi.Void Function(); - -/// Main FFI bridge between Dart VST3 plugins and C++ VST3 infrastructure -class VST3Bridge { - static VST3Processor? _processor; - - /// Register a Dart VST3 processor with the bridge - /// This must be called before the VST3 plugin can process audio - static void registerProcessor(VST3Processor processor) { - _processor = processor; - print('Dart VST3 processor registered locally (callbacks not yet implemented in FFI layer)'); - } - - /// Initialize the processor - /// Called from C++ when VST3 plugin is initialized - static void initializeProcessor(double sampleRate, int maxBlockSize) { - if (_processor == null) { - throw StateError('CRITICAL VST3 BRIDGE FAILURE: Cannot initialize - no processor registered! Call VST3Bridge.registerProcessor() before using the plugin!'); - } - _processor!.initialize(sampleRate, maxBlockSize); - } - - /// Process stereo audio block - /// Called from C++ VST3 processor during audio processing - static void processAudio(ffi.Pointer inputL, - ffi.Pointer inputR, - ffi.Pointer outputL, - ffi.Pointer outputR, - int numSamples) { - if (_processor == null) { - throw StateError('CRITICAL VST3 BRIDGE FAILURE: No processor registered! Audio processing CANNOT continue without a Dart processor! Call VST3Bridge.registerProcessor() first!'); - } - - // Convert C pointers to Dart lists - final inL = inputL.asTypedList(numSamples); - final inR = inputR.asTypedList(numSamples); - final outL = outputL.asTypedList(numSamples); - final outR = outputR.asTypedList(numSamples); - - // Convert float arrays to double arrays for Dart processing - final dartInL = List.generate(numSamples, (i) => inL[i].toDouble()); - final dartInR = List.generate(numSamples, (i) => inR[i].toDouble()); - final dartOutL = List.filled(numSamples, 0.0); - final dartOutR = List.filled(numSamples, 0.0); - - // Process through Dart processor - _processor!.processStereo(dartInL, dartInR, dartOutL, dartOutR); - - // Convert back to C float arrays - for (int i = 0; i < numSamples; i++) { - outL[i] = dartOutL[i]; - outR[i] = dartOutR[i]; - } - } - - /// Set parameter value - /// Called from C++ when VST3 parameter changes - static void setParameter(int paramId, double normalizedValue) { - _processor?.setParameter(paramId, normalizedValue); - } - - /// Get parameter value - /// Called from C++ when VST3 needs current parameter value - static double getParameter(int paramId) { - return _processor?.getParameter(paramId) ?? 0.0; - } - - /// Get parameter count - static int getParameterCount() { - return _processor?.getParameterCount() ?? 0; - } - - /// Reset processor state - /// Called from C++ when VST3 is activated/deactivated - static void reset() { - _processor?.reset(); - } - - /// Dispose resources - static void dispose() { - _processor?.dispose(); - _processor = null; - } -} \ No newline at end of file diff --git a/flutter_vst3/lib/src/flutter_vst3_callbacks.dart b/flutter_vst3/lib/src/flutter_vst3_callbacks.dart deleted file mode 100644 index fdcd699..0000000 --- a/flutter_vst3/lib/src/flutter_vst3_callbacks.dart +++ /dev/null @@ -1,119 +0,0 @@ -import 'dart:ffi' as ffi; -import 'dart:io'; -import 'package:ffi/ffi.dart'; -import 'flutter_vst3_bridge.dart'; - -/// C function type definitions for FFI callbacks -typedef InitializeProcessorC = ffi.Void Function(ffi.Double sampleRate, ffi.Int32 maxBlockSize); -typedef InitializeProcessorDart = void Function(double sampleRate, int maxBlockSize); - -typedef ProcessAudioC = ffi.Void Function(ffi.Pointer inputL, - ffi.Pointer inputR, - ffi.Pointer outputL, - ffi.Pointer outputR, - ffi.Int32 numSamples); -typedef ProcessAudioDart = void Function(ffi.Pointer inputL, - ffi.Pointer inputR, - ffi.Pointer outputL, - ffi.Pointer outputR, - int numSamples); - -typedef SetParameterC = ffi.Void Function(ffi.Int32 paramId, ffi.Double normalizedValue); -typedef SetParameterDart = void Function(int paramId, double normalizedValue); - -typedef GetParameterC = ffi.Double Function(ffi.Int32 paramId); -typedef GetParameterDart = double Function(int paramId); - -typedef GetParameterCountC = ffi.Int32 Function(); -typedef GetParameterCountDart = int Function(); - -typedef ResetC = ffi.Void Function(); -typedef ResetDart = void Function(); - -typedef DisposeC = ffi.Void Function(); -typedef DisposeDart = void Function(); - -// C++ function bindings -typedef CreateInstanceC = ffi.Pointer Function(ffi.Pointer); -typedef CreateInstanceDart = ffi.Pointer Function(ffi.Pointer); - -typedef RegisterCallbacksC = ffi.Int32 Function(ffi.Pointer, ffi.Pointer); -typedef RegisterCallbacksDart = int Function(ffi.Pointer, ffi.Pointer); - -// Struct matching the C++ DartVST3Callbacks structure -final class DartVST3Callbacks extends ffi.Struct { - external ffi.Pointer> initializeProcessor; - external ffi.Pointer> processAudio; - external ffi.Pointer> setParameter; - external ffi.Pointer> getParameter; - external ffi.Pointer> getParameterCount; - external ffi.Pointer> reset; - external ffi.Pointer> dispose; -} - -/// Register Dart callbacks with C++ layer -/// This MUST be called before the VST3 plugin can use the Dart processor -void registerVST3Callbacks({required String pluginId}) { - try { - // Load the native library - late ffi.DynamicLibrary lib; - if (Platform.isMacOS) { - lib = ffi.DynamicLibrary.open('libdart_vst_host.dylib'); - } else if (Platform.isLinux) { - lib = ffi.DynamicLibrary.open('libdart_vst_host.so'); - } else if (Platform.isWindows) { - lib = ffi.DynamicLibrary.open('dart_vst_host.dll'); - } else { - throw UnsupportedError('Unsupported platform for VST3 callbacks'); - } - - // Get C++ function pointers - final createInstance = lib.lookupFunction( - 'dart_vst3_create_instance'); - final registerCallbacks = lib.lookupFunction( - 'dart_vst3_register_callbacks'); - - // Create plugin instance - final pluginIdPtr = pluginId.toNativeUtf8(); - final instance = createInstance(pluginIdPtr); - - if (instance == ffi.nullptr) { - throw StateError('CRITICAL VST3 BRIDGE FAILURE: Failed to create plugin instance for $pluginId'); - } - - // Create callback structure and populate with Dart function pointers - final callbacks = calloc(); - callbacks.ref.initializeProcessor = ffi.Pointer.fromFunction( - VST3Bridge.initializeProcessor); - callbacks.ref.processAudio = ffi.Pointer.fromFunction( - VST3Bridge.processAudio); - callbacks.ref.setParameter = ffi.Pointer.fromFunction( - VST3Bridge.setParameter); - callbacks.ref.getParameter = ffi.Pointer.fromFunction( - VST3Bridge.getParameter, 0.0); - callbacks.ref.getParameterCount = ffi.Pointer.fromFunction( - VST3Bridge.getParameterCount, 0); - callbacks.ref.reset = ffi.Pointer.fromFunction( - VST3Bridge.reset); - callbacks.ref.dispose = ffi.Pointer.fromFunction( - VST3Bridge.dispose); - - // Register callbacks with C++ bridge - final result = registerCallbacks(instance, callbacks); - - if (result == 0) { - calloc.free(callbacks); - throw StateError('CRITICAL VST3 BRIDGE FAILURE: Failed to register callbacks for $pluginId'); - } - - // Cleanup - calloc.free(callbacks); - print('VST3 callbacks successfully registered for $pluginId'); - - } catch (e, stackTrace) { - print('FATAL VST3 BRIDGE ERROR: Failed to register callbacks for $pluginId'); - print('Error: $e'); - print('Stack trace: $stackTrace'); - throw StateError('VST3 bridge initialization failed: $e'); - } -} \ No newline at end of file diff --git a/flutter_vst3/lib/src/flutter_vst3_parameters.dart b/flutter_vst3/lib/src/flutter_vst3_parameters.dart deleted file mode 100644 index e55831e..0000000 --- a/flutter_vst3/lib/src/flutter_vst3_parameters.dart +++ /dev/null @@ -1,45 +0,0 @@ -/// VST3 Parameter utilities and types -/// -/// This file provides common parameter handling utilities that Dart VST3 -/// plugins can use for consistent parameter management. - -/// Common parameter information structure -class VST3ParameterInfo { - final int id; - final String name; - final String shortName; - final String units; - final double minValue; - final double maxValue; - final double defaultNormalized; - final bool canAutomate; - - const VST3ParameterInfo({ - required this.id, - required this.name, - required this.shortName, - required this.units, - this.minValue = 0.0, - this.maxValue = 1.0, - required this.defaultNormalized, - this.canAutomate = true, - }); -} - -/// Base class for parameter management in VST3 plugins -abstract class VST3ParameterHandler { - /// Get parameter information by index - VST3ParameterInfo getParameterInfo(int index); - - /// Get total number of parameters - int get parameterCount; - - /// Convert normalized value (0.0-1.0) to display string - String parameterToString(int paramId, double normalizedValue); - - /// Convert display string to normalized value (0.0-1.0) - double stringToParameter(int paramId, String text); - - /// Get default normalized value for parameter - double getDefaultValue(int paramId); -} \ No newline at end of file diff --git a/flutter_vst3/lib/src/parameter_binding.dart b/flutter_vst3/lib/src/parameter_binding.dart new file mode 100644 index 0000000..fd2e14a --- /dev/null +++ b/flutter_vst3/lib/src/parameter_binding.dart @@ -0,0 +1,235 @@ +/// Parameter binding between Flutter UI and VST3 controller +library; + +import 'package:flutter/services.dart'; +import 'shared_memory_reader.dart'; + +/// Manages bidirectional parameter and audio streaming synchronization between +/// the Flutter UI and the VST3 EditController across macOS, Windows, and Linux. +class VST3ParameterBinding { + static const MethodChannel _channel = + MethodChannel('flutter_vst3/parameters'); + static VST3ParameterBinding? _instance; + final List _listeners = []; + + final Map _parameters = {}; + final Map _parameterNames = {}; + final Map _parameterUnits = {}; + final Set _pendingBegins = {}; + final int parameterCount; + + /// Returns the singleton binding instance. + static VST3ParameterBinding getInstance({int paramCount = 64}) { + _instance ??= VST3ParameterBinding._(paramCount); + return _instance!; + } + + VST3ParameterBinding._(this.parameterCount) { + _initChannel(); + for (var i = 0; i < parameterCount; i++) { + _parameters[i] = 0.0; + } + } + + bool _isHostAttached = true; + bool _dspStopped = false; + + /// Whether the DSP worker died: the host still names a memory block, but the + /// block no longer reads as valid. Audio is silent until the next activation. + bool get dspStopped => _dspStopped; + + void _setDspStopped(bool stopped) { + final changed = stopped != _dspStopped; + _dspStopped = stopped; + changed ? notifyListeners() : null; + } + + /// Whether the plugin GUI is currently attached to an active OS window. + bool get isHostAttached => _isHostAttached; + + void _initChannel() { + _channel.setMethodCallHandler((call) async { + switch (call.method) { + case 'onParameterChanged': + _handleParamChanged(call.arguments); + case 'onHostDetached': + _isHostAttached = false; + _audioReader = null; + _pendingBegins.clear(); + notifyListeners(); + case 'onHostAttached': + _isHostAttached = true; + _audioReader = null; + await loadInitialParameters(); + notifyListeners(); + default: + break; + } + }); + loadInitialParameters(); + } + + /// Loads current parameter values from the VST3 EditController. + /// + /// Running without a host, as `flutter run` does, is not an error: there's + /// no channel, and the cache stays as it is. A bad reply from a host throws. + Future loadInitialParameters() async { + try { + _applyInitial( + await _channel.invokeMethod('getInitialParameters'), + ); + } on MissingPluginException { + return; + } + } + + void _applyInitial(Object? reply) { + final map = switch (reply) { + Map value => value, + _ => throw ArgumentError('Expected initial parameter map'), + }; + final validated = {}; + for (final entry in map.entries) { + validated[_initialId(entry.key)] = _validatedValue(entry.value); + } + _parameters.addAll(validated); + notifyListeners(); + } + + void _handleParamChanged(dynamic arguments) { + final args = switch (arguments) { + Map value => value, + _ => throw ArgumentError('Expected parameter message map'), + }; + final id = _validatedId(args['id']); + final value = _validatedValue(args['value']); + _parameters[id] = value; + notifyListeners(); + } + + int _initialId(Object? key) => switch (key) { + String text when RegExp(r'^(0|[1-9][0-9]*)$').hasMatch(text) => + _validatedId(int.tryParse(text)), + _ => _validatedId(key), + }; + + int _validatedId(Object? id) => switch (id) { + int value when value >= 0 && value < parameterCount => value, + _ => throw ArgumentError.value(id, 'id', 'Invalid parameter ID'), + }; + + double _validatedValue(Object? value) => switch (value) { + num number when number.isFinite && number >= 0 && number <= 1 => + number.toDouble(), + _ => throw ArgumentError.value(value, 'value', 'Expected normalized value'), + }; + + /// Adds a listener for parameter updates. + void addListener(void Function() listener) { + _listeners.add(listener); + } + + /// Removes a listener. + void removeListener(void Function() listener) { + _listeners.remove(listener); + } + + /// Notifies all registered listeners of parameter changes. + void notifyListeners() { + for (final listener in _listeners) { + listener(); + } + } + + /// Returns current parameter value (0.0 to 1.0). + double getParameter(int id) { + return _parameters[id] ?? 0.0; + } + + /// Begins one host automation gesture. + /// + /// The host hears of it at the first value, so that a tap, or a stray pointer + /// event, leaves no empty gesture on the host. + Future beginEdit(int id) async => _pendingBegins.add(id); + + /// Ends one host automation gesture. + Future endEdit(int id) async => _pendingBegins.remove(id) + ? null + : await _send('endEdit', {'id': id}); + + /// Without a host there's no channel to send to, which isn't an error. + Future _send(String method, Map arguments) async { + try { + await _channel.invokeMethod(method, arguments); + } on MissingPluginException { + return; + } + } + + /// Sets parameter value from UI and notifies the VST3 EditController. + /// + /// The beginEdit and the value both leave for the host before the first + /// await, so a value or endEdit issued in the meantime cannot overtake them. + Future setParameter(int id, double value) async { + final clamped = value.clamp(0.0, 1.0); + _parameters[id] = clamped; + final sends = [ + ..._pendingBegins.remove(id) + ? [_send('beginEdit', {'id': id})] + : >[], + _send('setParameter', {'id': id, 'value': clamped}), + ]; + await Future.wait(sends); + notifyListeners(); + } + + /// Stores the display name for [id]. + void setParameterName(int id, String name) { + _parameterNames[id] = name; + } + + /// Returns the display name for [id]. + String getParameterName(int id) { + return _parameterNames[id] ?? 'Parameter $id'; + } + + /// Stores the display units for [id]. + void setParameterUnits(int id, String units) { + _parameterUnits[id] = units; + } + + /// Returns the display units for [id]. + String getParameterUnits(int id) { + return _parameterUnits[id] ?? ''; + } + + /// Returns a snapshot of all cached normalized parameters. + Map getAllParameters() { + return Map.from(_parameters); + } + + Vst3AudioBufferReader? _audioReader; + + /// Obtains direct zero-copy read access to the audio buffers in shared memory. + Future getAudioBufferReader( + {bool forceRefresh = false}) async { + if (_audioReader != null && !forceRefresh) return _audioReader; + try { + final info = await _channel + .invokeMapMethod('getSharedMemoryInfo'); + if (info != null) { + final addr = (info['address'] as num?)?.toInt() ?? 0; + _audioReader = Vst3AudioBufferReader.fromAddress(addr); + _setDspStopped(addr != 0 && _audioReader == null); + } + } on MissingPluginException { + // Standalone Flutter has no host channel. + } + return _audioReader; + } + + /// Invalidates and clears the cached shared memory audio buffer reader. + void invalidateAudioReader() { + _audioReader = null; + } +} diff --git a/flutter_vst3/lib/src/rotary_knob.dart b/flutter_vst3/lib/src/rotary_knob.dart new file mode 100644 index 0000000..a13fa3f --- /dev/null +++ b/flutter_vst3/lib/src/rotary_knob.dart @@ -0,0 +1,142 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +/// Vertical drag distance, in logical pixels, that sweeps the full range. +const double knobDragRangePixels = 120.0; + +/// Returns the normalized knob value after a vertical drag of [deltaY] pixels. +/// +/// Dragging up (negative [deltaY]) increases the value. The result is clamped +/// to the normalized VST3 parameter range of 0..1. +double knobValueAfterDrag(double value, double deltaY) => + (value - deltaY / knobDragRangePixels).clamp(0.0, 1.0).toDouble(); + +/// Rotary control for a normalized (0..1) parameter. +/// +/// [onChangeStart] and [onChangeEnd] bracket a drag so that callers can map it +/// to a single VST3 beginEdit/performEdit/endEdit automation gesture. +class RotaryKnob extends StatefulWidget { + /// Creates a knob showing [value] with [display] as the centre readout. + const RotaryKnob({ + super.key, + required this.label, + required this.value, + required this.display, + required this.onChanged, + required this.onChangeStart, + required this.onChangeEnd, + this.color = const Color(0xFF00E5FF), + this.size = 100.0, + }); + + /// Caption shown above the knob. + final String label; + + /// Current normalized value. + final double value; + + /// Formatted value shown in the centre of the knob. + final String display; + + /// Called with the new normalized value for every drag update. + final ValueChanged onChanged; + + /// Called once when a drag gesture starts. + final VoidCallback onChangeStart; + + /// Called once when a drag gesture ends or is cancelled. + final VoidCallback onChangeEnd; + + /// Colour of the value arc and readout. + final Color color; + + /// Width and height of the knob. + final double size; + + @override + State createState() => _RotaryKnobState(); +} + +/// Accumulates drag deltas from the gesture start, so updates arriving before +/// a rebuild still move the value by their full distance. +class _RotaryKnobState extends State { + double? _dragValue; + + void _startDrag() { + _dragValue = widget.value; + widget.onChangeStart(); + } + + void _updateDrag(DragUpdateDetails details) { + final value = + knobValueAfterDrag(_dragValue ?? widget.value, details.delta.dy); + _dragValue = value; + widget.onChanged(value); + } + + void _endDrag() { + _dragValue = null; + widget.onChangeEnd(); + } + + @override + Widget build(BuildContext context) => Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(widget.label, style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 8), + GestureDetector( + onPanStart: (_) => _startDrag(), + onPanUpdate: _updateDrag, + onPanEnd: (_) => _endDrag(), + onPanCancel: _endDrag, + child: CustomPaint( + size: Size.square(widget.size), + painter: _KnobPainter(value: widget.value, color: widget.color), + child: SizedBox.square( + dimension: widget.size, + child: Center( + child: Text(widget.display, + style: TextStyle(color: widget.color))), + ), + ), + ), + ], + ); +} + +class _KnobPainter extends CustomPainter { + const _KnobPainter({required this.value, required this.color}); + + static const double _startAngle = 0.75 * math.pi; + static const double _sweepAngle = 1.5 * math.pi; + + final double value; + final Color color; + + @override + void paint(Canvas canvas, Size size) { + final center = size.center(Offset.zero); + final radius = size.width / 2 - 8; + final rect = Rect.fromCircle(center: center, radius: radius); + final stroke = Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 4 + ..strokeCap = StrokeCap.round; + canvas.drawArc(rect, _startAngle, _sweepAngle, false, + stroke..color = color.withValues(alpha: 0.15)); + canvas.drawArc(rect, _startAngle, _sweepAngle * value, false, + stroke..color = color); + final angle = _startAngle + _sweepAngle * value; + canvas.drawCircle( + center + Offset(math.cos(angle), math.sin(angle)) * radius, + 6, + Paint()..color = color, + ); + } + + @override + bool shouldRepaint(_KnobPainter old) => + old.value != value || old.color != color; +} diff --git a/flutter_vst3/lib/src/shared_memory_reader.dart b/flutter_vst3/lib/src/shared_memory_reader.dart new file mode 100644 index 0000000..52e388f --- /dev/null +++ b/flutter_vst3/lib/src/shared_memory_reader.dart @@ -0,0 +1,93 @@ +// Copyright (c) 2025 +// Direct read access to VST3 zero-copy shared memory audio buffers. + +import 'dart:ffi'; +import 'dart:typed_data'; + +import 'vst3_shm_layout.dart'; + +/// Reader providing direct zero-copy read access to VST3 audio buffers. +final class Vst3AudioBufferReader { + final Pointer _base; + final Pointer _outputL; + final Pointer _outputR; + final Pointer _inputL; + final Pointer _inputR; + final Pointer _numSamplesPtr; + final Pointer _sampleRatePtr; + + Vst3AudioBufferReader._(this._base) + : _outputL = + Pointer.fromAddress(_base.address + vst3OffsetOutputL), + _outputR = + Pointer.fromAddress(_base.address + vst3OffsetOutputR), + _inputL = Pointer.fromAddress(_base.address + vst3OffsetInputL), + _inputR = Pointer.fromAddress(_base.address + vst3OffsetInputR), + _numSamplesPtr = + Pointer.fromAddress(_base.address + vst3OffsetNumSamples), + _sampleRatePtr = + Pointer.fromAddress(_base.address + vst3OffsetSampleRate); + + /// Attaches directly to a shared memory block using an in-process raw address. + static Vst3AudioBufferReader? fromAddress(int address) { + if (address == 0) return null; + final ptr = Pointer.fromAddress(address); + final magic = Pointer.fromAddress(ptr.address).value; + return (magic == vst3ShmMagic) ? Vst3AudioBufferReader._(ptr) : null; + } + + /// Checks whether the underlying shared memory block is still valid and active. + bool get isValid { + if (_base == nullptr || _base.address == 0) return false; + final magic = Pointer.fromAddress(_base.address).value; + return magic == vst3ShmMagic; + } + + /// Raw base memory pointer of the mapped shared memory block. + Pointer get baseAddress => _base; + + /// Current number of valid samples processed in the active audio block. + int get numSamples { + if (!isValid) return 0; + return _numSamplesPtr.value.clamp(0, vst3ShmMaxSamples); + } + + /// Host audio sample rate in Hz. + double get sampleRate { + return isValid + ? _sampleRatePtr.value + : throw StateError('Shared memory reader is no longer valid'); + } + + /// Returns a zero-copy typed list view over the left output channel buffer. + Float32List getOutputL([int? count]) => _channelView(_outputL, count); + + /// Returns a zero-copy typed list view over the right output channel buffer. + Float32List getOutputR([int? count]) => _channelView(_outputR, count); + + /// Returns a zero-copy typed list view over the left input channel buffer. + Float32List getInputL([int? count]) => _channelView(_inputL, count); + + /// Returns a zero-copy typed list view over the right input channel buffer. + Float32List getInputR([int? count]) => _channelView(_inputR, count); + + /// Channel view for [channel], clamped by [count] and the block maximum, + /// empty while the block is invalid ([TELEMETRY-BOUNDS]). + Float32List _channelView(Pointer channel, int? count) => isValid + ? channel.asTypedList((count ?? numSamples).clamp(0, vst3ShmMaxSamples)) + : Float32List(0); + + /// Returns a mixed stereo waveform snapshot up to [maxCount] samples. + Float32List getLatestOutputSamples({int maxCount = 256}) { + if (!isValid) return Float32List(0); + final active = numSamples; + final n = active.clamp(0, maxCount.clamp(0, vst3ShmMaxSamples)); + final out = Float32List(n); + final lList = _outputL.asTypedList(n); + final rList = _outputR.asTypedList(n); + for (var i = 0; i < n; i++) { + out[i] = (lList[i] + rList[i]) * 0.5; + } + return out; + } +} diff --git a/flutter_vst3/lib/src/vst3_shared_memory_processor.dart b/flutter_vst3/lib/src/vst3_shared_memory_processor.dart new file mode 100644 index 0000000..100a8be --- /dev/null +++ b/flutter_vst3/lib/src/vst3_shared_memory_processor.dart @@ -0,0 +1,321 @@ +import 'dart:ffi'; +import 'dart:io'; +import 'package:ffi/ffi.dart'; + +import 'vst3_shm_layout.dart'; +import 'vst3_worker_loop.dart'; + +// C and Dart function signatures for POSIX shared memory and semaphores +typedef _ShmOpenC = Int32 Function(Pointer, Int32, Uint16); +typedef _ShmOpenDart = int Function(Pointer, int, int); +typedef _MmapC = Pointer Function(Pointer, IntPtr, Int32, Int32, Int32, Int64); +typedef _MmapDart = Pointer Function(Pointer, int, int, int, int, int); +typedef _MunmapC = Int32 Function(Pointer, IntPtr); +typedef _MunmapDart = int Function(Pointer, int); +typedef _CloseC = Int32 Function(Int32); +typedef _CloseDart = int Function(int); +typedef _SemOpenC = Pointer Function(Pointer, Int32); +typedef _SemOpenDart = Pointer Function(Pointer, int); +typedef _SemWaitC = Int32 Function(Pointer); +typedef _SemWaitDart = int Function(Pointer); +typedef _SemPostC = Int32 Function(Pointer); +typedef _SemPostDart = int Function(Pointer); +typedef _SemCloseC = Int32 Function(Pointer); +typedef _SemCloseDart = int Function(Pointer); +typedef _ErrnoLocationC = Pointer Function(); +typedef _ErrnoLocationDart = Pointer Function(); + +/// POSIX FFI bindings for inter-process shared memory and semaphores. +final class _PosixNative { + final _ShmOpenDart shmOpen; + final _MmapDart mmap; + final _MunmapDart munmap; + final _CloseDart close; + final _SemOpenDart semOpen; + final _SemWaitDart semWait; + final _SemPostDart semPost; + final _SemCloseDart semClose; + final _ErrnoLocationDart errnoLocation; + + _PosixNative(DynamicLibrary lib) + : shmOpen = lib.lookupFunction<_ShmOpenC, _ShmOpenDart>('shm_open'), + mmap = lib.lookupFunction<_MmapC, _MmapDart>('mmap'), + munmap = lib.lookupFunction<_MunmapC, _MunmapDart>('munmap'), + close = lib.lookupFunction<_CloseC, _CloseDart>('close'), + semOpen = lib.lookupFunction<_SemOpenC, _SemOpenDart>('sem_open'), + semWait = lib.lookupFunction<_SemWaitC, _SemWaitDart>('sem_wait'), + semPost = lib.lookupFunction<_SemPostC, _SemPostDart>('sem_post'), + semClose = lib.lookupFunction<_SemCloseC, _SemCloseDart>('sem_close'), + errnoLocation = lib.lookupFunction<_ErrnoLocationC, _ErrnoLocationDart>( + Platform.isMacOS ? '__error' : '__errno_location'); +} + +/// errno when a signal interrupts sem_wait before it takes the semaphore. +const int vst3SemWaitEintr = 4; + +/// Runs [semWait] until it takes the semaphore. Returning after EINTR would +/// re-run the previous command and post an extra done [IPC-SYNC-HANDOFF]. Any +/// other failure throws. +void retryOnSemEintr(int Function() semWait, int Function() errno) { + var result = semWait(); + while (result != 0) { + final int code = errno(); + switch (code) { + case vst3SemWaitEintr: + result = semWait(); + default: + throw StateError('sem_wait failed with errno $code'); + } + } +} + +/// Library providing the POSIX IPC symbols. Before glibc 2.34 they live outside +/// libc, where a Dart executable may not have loaded them yet. +DynamicLibrary _posixLibrary() { + final process = DynamicLibrary.process(); + return process.providesSymbol('shm_open') && process.providesSymbol('sem_open') + ? process + : DynamicLibrary.open('librt.so.1'); +} + +final class _PosixIpc implements Vst3Ipc { + final Pointer _ptr; + final int _fd; + final Pointer _semReady; + final Pointer _semDone; + final _PosixNative _native; + + _PosixIpc(this._ptr, this._fd, this._semReady, this._semDone, this._native); + + @override + Pointer get pointer => _ptr; + + @override + void waitReady() => retryOnSemEintr( + () => _native.semWait(_semReady), + () => _native.errnoLocation().value, + ); + + @override + void signalDone() => _native.semPost(_semDone); + + @override + void dispose() { + _native.semClose(_semReady); + _native.semClose(_semDone); + _native.munmap(_ptr, vst3ShmTotalSize); + _native.close(_fd); + } +} + +final class _Win32Ipc implements Vst3Ipc { + final Pointer _hMap; + final Pointer _ptr; + final Pointer _hSemReady; + final Pointer _hSemDone; + + final int Function(Pointer, int) _waitForSingleObject; + final int Function(Pointer, int, Pointer) _releaseSemaphore; + final int Function(Pointer) _unmapViewOfFile; + final int Function(Pointer) _closeHandle; + + _Win32Ipc({ + required Pointer hMap, + required Pointer ptr, + required Pointer hSemReady, + required Pointer hSemDone, + required int Function(Pointer, int) waitForSingleObject, + required int Function(Pointer, int, Pointer) releaseSemaphore, + required int Function(Pointer) unmapViewOfFile, + required int Function(Pointer) closeHandle, + }) : _hMap = hMap, + _ptr = ptr, + _hSemReady = hSemReady, + _hSemDone = hSemDone, + _waitForSingleObject = waitForSingleObject, + _releaseSemaphore = releaseSemaphore, + _unmapViewOfFile = unmapViewOfFile, + _closeHandle = closeHandle; + + @override + Pointer get pointer => _ptr; + + @override + void waitReady() { + _waitForSingleObject(_hSemReady, 0xFFFFFFFF); // INFINITE + } + + @override + void signalDone() { + _releaseSemaphore(_hSemDone, 1, nullptr); + } + + @override + void dispose() { + _unmapViewOfFile(_ptr); + _closeHandle(_hMap); + _closeHandle(_hSemReady); + _closeHandle(_hSemDone); + } +} + +/// Throws if [ptr] is mmap's failure value, which is -1 and not null. +void throwIfMapFailed(Pointer ptr, String name) => ptr.address == -1 + ? throw StateError('Failed to mmap shared memory: $name') + : null; + +/// Throws if [sem] is a sem_open failure value, which is null on Linux and -1 +/// on some other POSIX systems. +void throwIfSemFailed(Pointer sem, String name) => + sem.address == 0 || sem.address == -1 + ? throw StateError('Failed to open semaphore: $name') + : null; + +_PosixIpc _openPosixIpc(String shmName, String semReadyName, String semDoneName) { + final posix = _PosixNative(_posixLibrary()); + final shmNameNative = shmName.toNativeUtf8(); + final semRNameNative = semReadyName.toNativeUtf8(); + final semDNameNative = semDoneName.toNativeUtf8(); + + try { + final fd = posix.shmOpen(shmNameNative, 2, 0); // O_RDWR = 2 + if (fd < 0) throw StateError('Failed to open shared memory: $shmName'); + + final ptr = posix.mmap(nullptr, vst3ShmTotalSize, 3, 1, fd, 0); + throwIfMapFailed(ptr, shmName); + + final semReady = posix.semOpen(semRNameNative, 0); + throwIfSemFailed(semReady, semReadyName); + final semDone = posix.semOpen(semDNameNative, 0); + throwIfSemFailed(semDone, semDoneName); + + return _PosixIpc(ptr, fd, semReady, semDone, posix); + } finally { + calloc.free(shmNameNative); + calloc.free(semRNameNative); + calloc.free(semDNameNative); + } +} + +_Win32Ipc _openWin32Ipc(String shmName, String semReadyName, String semDoneName) { + final k32 = DynamicLibrary.open('kernel32.dll'); + final openFileMapping = k32.lookupFunction< + Pointer Function(Uint32, Int32, Pointer), + Pointer Function(int, int, Pointer)>('OpenFileMappingA'); + final mapViewOfFile = k32.lookupFunction< + Pointer Function(Pointer, Uint32, Uint32, Uint32, IntPtr), + Pointer Function(Pointer, int, int, int, int)>('MapViewOfFile'); + final unmapViewOfFile = k32.lookupFunction< + Int32 Function(Pointer), + int Function(Pointer)>('UnmapViewOfFile'); + final closeHandle = k32.lookupFunction< + Int32 Function(Pointer), + int Function(Pointer)>('CloseHandle'); + final openSemaphore = k32.lookupFunction< + Pointer Function(Uint32, Int32, Pointer), + Pointer Function(int, int, Pointer)>('OpenSemaphoreA'); + final waitForSingleObject = k32.lookupFunction< + Uint32 Function(Pointer, Uint32), + int Function(Pointer, int)>('WaitForSingleObject'); + final releaseSemaphore = k32.lookupFunction< + Int32 Function(Pointer, Int32, Pointer), + int Function(Pointer, int, Pointer)>('ReleaseSemaphore'); + + final shmUtf8 = shmName.toNativeUtf8(); + final semRUtf8 = semReadyName.toNativeUtf8(); + final semDUtf8 = semDoneName.toNativeUtf8(); + + try { + final hMap = openFileMapping(0x000F001F, 0, shmUtf8); // FILE_MAP_ALL_ACCESS + if (hMap == nullptr) { + throw StateError('Failed to open Win32 shared memory: $shmName'); + } + final ptr = mapViewOfFile(hMap, 0x000F001F, 0, 0, vst3ShmTotalSize); + if (ptr == nullptr) { + closeHandle(hMap); + throw StateError('Failed to map Win32 shared memory: $shmName'); + } + final hReady = openSemaphore(0x001F0003, 0, semRUtf8); // SEMAPHORE_ALL_ACCESS + if (hReady == nullptr) { + unmapViewOfFile(ptr); + closeHandle(hMap); + throw StateError('Failed to open Win32 semaphore: $semReadyName'); + } + final hDone = openSemaphore(0x001F0003, 0, semDUtf8); + if (hDone == nullptr) { + closeHandle(hReady); + unmapViewOfFile(ptr); + closeHandle(hMap); + throw StateError('Failed to open Win32 semaphore: $semDoneName'); + } + + return _Win32Ipc( + hMap: hMap, + ptr: ptr, + hSemReady: hReady, + hSemDone: hDone, + waitForSingleObject: waitForSingleObject, + releaseSemaphore: releaseSemaphore, + unmapViewOfFile: unmapViewOfFile, + closeHandle: closeHandle, + ); + } finally { + calloc.free(shmUtf8); + calloc.free(semRUtf8); + calloc.free(semDUtf8); + } +} + +/// Runs [processor] as the DSP worker for one plugin instance. +/// +/// [args] are the shared memory name, the two semaphore names and the process +/// id of the host. Blocks until the host terminates the worker, then exits. +void runVst3SharedMemoryProcessor({ + required List args, + required Vst3WorkerProcessor processor, +}) { + switch (args.length) { + case 4: + final Vst3Ipc ipc = Platform.isWindows + ? _openWin32Ipc(args[0], args[1], args[2]) + : _openPosixIpc(args[0], args[1], args[2]); + runWorker(ipc, processor, _exitWhenHostDies, int.parse(args[3])); + default: + throw ArgumentError( + 'Usage: processor ', + ); + } +} + +/// Exits this process when the host process is gone, so that a crashed host +/// can't leave a worker behind on any platform. +void _exitWhenHostDies(int hostPid) { + switch (Platform.isWindows) { + case true: + _waitForWindowsProcess(hostPid); + case false: + _waitForPosixParent(hostPid); + } + exit(0); +} + +void _waitForPosixParent(int hostPid) { + final getppid = DynamicLibrary.process() + .lookupFunction('getppid'); + while (getppid() == hostPid) { + sleep(const Duration(milliseconds: 250)); + } +} + +void _waitForWindowsProcess(int hostPid) { + final k32 = DynamicLibrary.open('kernel32.dll'); + final openProcess = k32.lookupFunction< + Pointer Function(Uint32, Int32, Uint32), + Pointer Function(int, int, int)>('OpenProcess'); + final wait = k32.lookupFunction, Uint32), + int Function(Pointer, int)>('WaitForSingleObject'); + const synchronize = 0x00100000; + const infinite = 0xFFFFFFFF; + final handle = openProcess(synchronize, 0, hostPid); + handle == nullptr ? null : wait(handle, infinite); +} diff --git a/flutter_vst3/lib/src/vst3_shm_layout.dart b/flutter_vst3/lib/src/vst3_shm_layout.dart new file mode 100644 index 0000000..498c451 --- /dev/null +++ b/flutter_vst3/lib/src/vst3_shm_layout.dart @@ -0,0 +1,73 @@ +/// Shared memory layout mirrored from native/include/vst3_shared_memory.h. +/// +/// test/vst3_shm_layout_test.dart fails if these values differ from the header. +library; + +/// Magic word identifying a live block ('VST3'). +const int vst3ShmMagic = 0x56535433; + +/// Protocol version. The worker refuses a block with any other version. +const int vst3ShmVersion = 2; + +/// Maximum samples in one block. +const int vst3ShmMaxSamples = 4096; + +/// Capacity of the parameter ring. +const int vst3ShmParamQueueSize = 64; + +/// Size in bytes of one parameter event. +const int vst3ShmParamEventSize = 16; + +/// Host command: process the audio block. +const int vst3CmdProcess = 1; + +/// Host command: exit the event loop. +const int vst3CmdTerminate = 2; + +/// Host command: reinitialize the DSP from the sample rate and block size. +const int vst3CmdConfigure = 3; + +/// Host command: clear DSP state. +const int vst3CmdReset = 4; + +/// Byte offset of the magic word. +const int vst3OffsetMagic = 0; + +/// Byte offset of the protocol version. +const int vst3OffsetVersion = 4; + +/// Byte offset of the sample rate. +const int vst3OffsetSampleRate = 8; + +/// Byte offset of the maximum block size. +const int vst3OffsetMaxBlockSize = 16; + +/// Byte offset of the command. +const int vst3OffsetCommand = 20; + +/// Byte offset of the sample count. +const int vst3OffsetNumSamples = 24; + +/// Byte offset of the parameter ring write index. +const int vst3OffsetHostParamWrite = 28; + +/// Byte offset of the parameter ring read index. +const int vst3OffsetHostParamRead = 32; + +/// Byte offset of the parameter ring. +const int vst3OffsetHostParams = 36; + +/// Byte offset of the left input. +const int vst3OffsetInputL = 4096; + +/// Byte offset of the right input. +const int vst3OffsetInputR = 20480; + +/// Byte offset of the left output. +const int vst3OffsetOutputL = 36864; + +/// Byte offset of the right output. +const int vst3OffsetOutputR = 53248; + +/// Total size of the block in bytes. +const int vst3ShmTotalSize = 69632; diff --git a/flutter_vst3/lib/src/vst3_worker_loop.dart b/flutter_vst3/lib/src/vst3_worker_loop.dart new file mode 100644 index 0000000..83c1d44 --- /dev/null +++ b/flutter_vst3/lib/src/vst3_worker_loop.dart @@ -0,0 +1,212 @@ +import 'dart:ffi'; +import 'dart:io'; +import 'dart:isolate'; +import 'dart:typed_data'; + +import 'vst3_shm_layout.dart'; + +/// DSP implementation driven by the worker event loop. +abstract interface class Vst3WorkerProcessor { + /// Prepares the DSP. Called at startup and again when the host changes the + /// sample rate or block size. + void initialize(double sampleRate, int maxBlockSize); + + /// Applies a normalized parameter value. + void setParameter(int paramId, double value); + + /// Renders one block. All lists have the same length. + void processStereo( + Float32List inputL, + Float32List inputR, + Float32List outputL, + Float32List outputR, + ); + + /// Clears DSP state such as delay tails. + void reset(); + + /// Releases resources before the process exits. + void dispose(); +} + +/// Operating system handles for one block and its two semaphores. +abstract interface class Vst3Ipc { + /// Address of the shared block. + Pointer get pointer; + + /// Blocks until the host hands over the shared block. + void waitReady(); + + /// Hands the shared block back to the host. + void signalDone(); + + /// Closes all handles. + void dispose(); +} + +/// Reads the u32 field at [offset] of the shared block at [ptr]. +int shmU32(Pointer ptr, int offset) => + Pointer.fromAddress(ptr.address + offset).value; + +/// Reads the i32 field at [offset] of the shared block at [ptr]. +int shmI32(Pointer ptr, int offset) => + Pointer.fromAddress(ptr.address + offset).value; + +/// Reads the f64 field at [offset] of the shared block at [ptr]. +double shmF64(Pointer ptr, int offset) => + Pointer.fromAddress(ptr.address + offset).value; + +/// Throws unless [ptr] holds a live block with the expected protocol version. +void validateShmHeader(Pointer ptr) { + final magic = shmU32(ptr, vst3OffsetMagic); + final version = shmU32(ptr, vst3OffsetVersion); + magic == vst3ShmMagic + ? null + : throw StateError('Invalid VST3 shared memory magic: $magic'); + version == vst3ShmVersion + ? null + : throw StateError('Unsupported VST3 shared memory version: $version'); +} + +/// Exit code of a worker stopped by an exception from the DSP. +const vst3WorkerFailureExitCode = 70; + +/// Starts watching [hostPid] and runs the worker until the host terminates it. +/// +/// [waitForHostExit] runs in a separate isolate so that it can exit the process +/// while this isolate is blocked waiting for the host. +void runWorker( + Vst3Ipc ipc, + Vst3WorkerProcessor processor, + void Function(int) waitForHostExit, + int hostPid, +) { + try { + validateShmHeader(ipc.pointer); + Isolate.spawn(waitForHostExit, hostPid); + _configure(ipc.pointer, processor); + ipc.signalDone(); // Tells the host that startup is complete. + _processingLoop(ipc, processor); + processor.dispose(); + ipc.dispose(); + } catch (error, stack) { + // Exit explicitly. With the watcher isolate running, the host never saw the + // process end after an uncaught exception on Windows. + // print is used because it is synchronous and exit would drop stderr. + // ignore: avoid_print + print('flutter_vst3 worker failed: $error\n$stack'); + exit(vst3WorkerFailureExitCode); + } + exit(0); +} + +void _configure(Pointer ptr, Vst3WorkerProcessor processor) { + processor.initialize( + shmF64(ptr, vst3OffsetSampleRate), + shmU32(ptr, vst3OffsetMaxBlockSize), + ); +} + +/// Handles commands until the host asks the worker to terminate. An exception +/// from the DSP reaches [runWorker], which ends the process. +void _processingLoop(Vst3Ipc ipc, Vst3WorkerProcessor processor) { + final ptr = ipc.pointer; + final views = Vst3BlockViews(ptr); + var running = true; + while (running) { + ipc.waitReady(); + running = handleCommand(ptr, views, processor); + running ? ipc.signalDone() : null; + } +} + +/// Runs the command in the block at [ptr]. Returns false on terminate. +bool handleCommand( + Pointer ptr, + Vst3BlockViews views, + Vst3WorkerProcessor processor, +) { + final cmd = shmU32(ptr, vst3OffsetCommand); + switch (cmd) { + case vst3CmdProcess: + drainHostParameters(ptr, processor); + views.resize(blockLength(ptr)); + processor.processStereo(views.inL, views.inR, views.outL, views.outR); + case vst3CmdConfigure: + _configure(ptr, processor); + case vst3CmdReset: + processor.reset(); + } + return cmd != vst3CmdTerminate; +} + +/// Returns the block length at [ptr], and throws if it's out of range. +int blockLength(Pointer ptr) { + final numSamples = shmI32(ptr, vst3OffsetNumSamples); + return numSamples >= 0 && numSamples <= vst3ShmMaxSamples + ? numSamples + : throw StateError('Invalid block length: $numSamples'); +} + +/// Views of the audio buffers, recreated only when the block length changes. +final class Vst3BlockViews { + /// Creates empty views for the block at [_ptr]. + Vst3BlockViews(this._ptr); + + final Pointer _ptr; + int _length = -1; + Float32List _inL = Float32List(0); + Float32List _inR = Float32List(0); + Float32List _outL = Float32List(0); + Float32List _outR = Float32List(0); + + /// Left input. + Float32List get inL => _inL; + + /// Right input. + Float32List get inR => _inR; + + /// Left output. + Float32List get outL => _outL; + + /// Right output. + Float32List get outR => _outR; + + /// Points the views at [length] samples. + void resize(int length) { + switch (length == _length) { + case true: + return; + case false: + _length = length; + _inL = _view(vst3OffsetInputL); + _inR = _view(vst3OffsetInputR); + _outL = _view(vst3OffsetOutputL); + _outR = _view(vst3OffsetOutputR); + } + } + + Float32List _view(int offset) => + Pointer.fromAddress(_ptr.address + offset).asTypedList(_length); +} + +/// Applies queued parameter events from the ring at [ptr] to [processor]. +/// +/// The ring indices are 32-bit counters that wrap, so the read index is masked +/// after every increment. +void drainHostParameters(Pointer ptr, Vst3WorkerProcessor processor) { + final writeIdx = shmU32(ptr, vst3OffsetHostParamWrite); + final readPtr = + Pointer.fromAddress(ptr.address + vst3OffsetHostParamRead); + var readIdx = readPtr.value; + while (readIdx != writeIdx) { + final event = vst3OffsetHostParams + + (readIdx % vst3ShmParamQueueSize) * vst3ShmParamEventSize; + processor.setParameter( + shmI32(ptr, event), + shmF64(ptr, event + 8), + ); + readIdx = (readIdx + 1) & 0xFFFFFFFF; + } + readPtr.value = readIdx; +} diff --git a/flutter_vst3/lib/ui.dart b/flutter_vst3/lib/ui.dart new file mode 100644 index 0000000..dbdde7d --- /dev/null +++ b/flutter_vst3/lib/ui.dart @@ -0,0 +1,8 @@ +/// Flutter UI bindings for flutter_vst3 plugins. +/// Provides MethodChannel parameter binding for embedded Flutter GUIs. +library flutter_vst3_ui; + +export 'flutter_vst3.dart'; +export 'src/parameter_binding.dart'; +export 'src/rotary_knob.dart'; +export 'src/shared_memory_reader.dart'; diff --git a/flutter_vst3/native/cmake/VST3Bridge.cmake b/flutter_vst3/native/cmake/VST3Bridge.cmake index 94f2c14..ce7f77a 100644 --- a/flutter_vst3/native/cmake/VST3Bridge.cmake +++ b/flutter_vst3/native/cmake/VST3Bridge.cmake @@ -3,6 +3,35 @@ # This file provides common functions and setup for building VST® 3 plugins that use # the flutter_vst3 framework for Flutter UI and Dart audio processing integration. +# Default to Release for single-config generators (Linux/macOS Makefiles & Ninja) +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) +endif() + +# Which Flutter bundle to embed: Release unless this is a Debug build. A Release +# plugin must never pick up a Debug bundle by accident. +option(FLUTTER_VST3_NATIVE_UI_ONLY "Build without the Flutter editor, using native sliders" OFF) +if(CMAKE_BUILD_TYPE STREQUAL "Debug") + set(FLUTTER_VST3_BUNDLE_MODE "Debug") +else() + set(FLUTTER_VST3_BUNDLE_MODE "Release") +endif() +string(TOLOWER "${FLUTTER_VST3_BUNDLE_MODE}" FLUTTER_VST3_BUNDLE_MODE_LOWER) + +include(${CMAKE_CURRENT_LIST_DIR}/VST3BridgeBundle.cmake) + +# Other generators link the plugin outside the bundle that receives its worker. +if(WIN32 AND NOT CMAKE_GENERATOR MATCHES "Visual Studio") + message(FATAL_ERROR "VST3 plugins must use a Visual Studio generator on Windows, not ${CMAKE_GENERATOR}") +endif() + +# Stops the configure if a plugin wants a Flutter editor and path doesn't exist. +function(flutter_vst3_require_flutter_path path hint) + if(FLUTTER_VST3_WANTS_FLUTTER AND NOT EXISTS "${path}") + message(FATAL_ERROR "Flutter editor file not found: ${path}\n${hint}\nSet FLUTTER_VST3_NATIVE_UI_ONLY=ON to build with native sliders.") + endif() +endfunction() + # Function to create a VST3 plugin using the bridge function(add_dart_vst3_plugin target_name dart_file) # Parse additional arguments @@ -28,14 +57,15 @@ function(add_dart_vst3_plugin target_name dart_file) if(NOT DEFINED ENV{VST3_SDK_DIR}) set(VST3_SDK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../vst3sdk) else() - set(VST3_SDK_DIR $ENV{VST3_SDK_DIR}) + file(TO_CMAKE_PATH "$ENV{VST3_SDK_DIR}" VST3_SDK_DIR) endif() if(NOT EXISTS ${VST3_SDK_DIR}/CMakeLists.txt) message(FATAL_ERROR "VST3 SDK not found at ${VST3_SDK_DIR}. Download it first.") endif() - # Disable validator and module info to avoid build failures + # Tests run the validator explicitly against the finished bundle. It can't + # run as a post-build step because the worker is copied in after linking. set(SMTG_RUN_VST_VALIDATOR OFF CACHE BOOL "" FORCE) set(SMTG_CREATE_MODULE_INFO OFF CACHE BOOL "" FORCE) @@ -43,7 +73,9 @@ function(add_dart_vst3_plugin target_name dart_file) set(SMTG_ADD_VST3_PLUGINS_SAMPLES OFF CACHE BOOL "" FORCE) set(SMTG_ADD_VST3_HOSTING_SAMPLES OFF CACHE BOOL "" FORCE) set(SMTG_ADD_VSTGUI OFF CACHE BOOL "" FORCE) + set(SMTG_ENABLE_VSTGUI_SUPPORT OFF CACHE BOOL "" FORCE) set(SMTG_CREATE_VST3_LINK OFF CACHE BOOL "" FORCE) + set(SMTG_CREATE_PLUGIN_LINK OFF CACHE BOOL "" FORCE) # Only build the minimal SDK components needed set(SMTG_BUILD_UNIVERSAL_BINARY OFF CACHE BOOL "" FORCE) @@ -72,17 +104,28 @@ function(add_dart_vst3_plugin target_name dart_file) # Auto-generate C++ files from JSON metadata # Find Dart compiler for code generation and native executable compilation - find_program(DART_EXECUTABLE dart) + find_program(DART_EXECUTABLE NAMES dart.bat dart.exe dart) if(NOT DART_EXECUTABLE) message(FATAL_ERROR "Dart compiler is required for code generation and native executable compilation") endif() + # Configure-time compilation must be repeated for every imported source, + # metadata edit, and template edit, including newly added Dart files. + file(GLOB_RECURSE DART_BUILD_INPUTS CONFIGURE_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/lib/*.dart" + "${BRIDGE_DIR}/../lib/*.dart" + "${BRIDGE_DIR}/templates/*") + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS + ${DART_BUILD_INPUTS} + "${CMAKE_CURRENT_SOURCE_DIR}/plugin_metadata.json" + "${BRIDGE_DIR}/../scripts/generate_plugin.dart") + set(GENERATE_SCRIPT "${BRIDGE_DIR}/../scripts/generate_plugin.dart") if(NOT EXISTS ${GENERATE_SCRIPT}) message(FATAL_ERROR "Code generator not found: ${GENERATE_SCRIPT}") endif() - # COMPILE DART TO NATIVE EXECUTABLE - NOT AOT! + # Compile the headless DSP worker. It must not import Flutter. set(DART_EXE_SOURCE "${CMAKE_CURRENT_SOURCE_DIR}/lib/${target_name}_processor_exe.dart") if(EXISTS ${DART_EXE_SOURCE}) @@ -98,7 +141,6 @@ function(add_dart_vst3_plugin target_name dart_file) COMMAND ${DART_EXECUTABLE} compile exe ${DART_EXE_SOURCE} -o ${DART_EXE_OUTPUT} - --verbose RESULT_VARIABLE DART_COMPILE_RESULT OUTPUT_VARIABLE DART_COMPILE_OUTPUT ERROR_VARIABLE DART_COMPILE_ERROR @@ -114,7 +156,7 @@ function(add_dart_vst3_plugin target_name dart_file) # Store executable path for later use in bundle creation set(DART_PROCESSOR_EXE "${DART_EXE_OUTPUT}") else() - message(WARNING "No Dart executable source at ${DART_EXE_SOURCE}") + message(FATAL_ERROR "No Dart worker source at ${DART_EXE_SOURCE}") endif() # Run code generation using Dart script @@ -165,20 +207,25 @@ function(add_dart_vst3_plugin target_name dart_file) endif() endforeach() - # Check if native C++ processor exists (transpiled from Dart) - set(NATIVE_PROCESSOR_FILE "${CMAKE_CURRENT_BINARY_DIR}/generated/${target_name}_processor_native.cpp") - - # Bridge components (view and native processor if available) - set(bridge_sources_no_factory - ${BRIDGE_DIR}/src/plugin_view.cpp - ) - - if(EXISTS ${NATIVE_PROCESSOR_FILE}) - message(STATUS "Using native C++ processor: ${NATIVE_PROCESSOR_FILE}") - list(APPEND bridge_sources_no_factory ${NATIVE_PROCESSOR_FILE}) + # Bridge components - Platform-specific view + set(bridge_sources_no_factory) + list(APPEND bridge_sources_no_factory ${BRIDGE_DIR}/src/vst3_ipc_host.cpp) + if(SMTG_WIN) + list(APPEND bridge_sources_no_factory ${BRIDGE_DIR}/src/vst3_ipc_platform_win.cpp) + else() + list(APPEND bridge_sources_no_factory ${BRIDGE_DIR}/src/vst3_ipc_platform_posix.cpp) + endif() + if(SMTG_MAC) + list(APPEND bridge_sources_no_factory + ${BRIDGE_DIR}/src/embedded_flutter_view.mm + ${BRIDGE_DIR}/src/native_cocoa_view.mm) + set_source_files_properties( + ${BRIDGE_DIR}/src/embedded_flutter_view.mm + ${BRIDGE_DIR}/src/native_cocoa_view.mm + PROPERTIES COMPILE_FLAGS "-fobjc-arc" + ) else() - message(STATUS "Using FFI Dart bridge: ${BRIDGE_DIR}/src/dart_vst3_bridge.cpp") - list(APPEND bridge_sources_no_factory ${BRIDGE_DIR}/src/dart_vst3_bridge.cpp) + list(APPEND bridge_sources_no_factory ${BRIDGE_DIR}/src/embedded_flutter_view.cpp) endif() # Add platform-specific main entry point @@ -206,12 +253,23 @@ function(add_dart_vst3_plugin target_name dart_file) cxx_std_17 ) + if(MSVC) + target_compile_options(${target_name} PRIVATE + $<$>:/O2 /Oi /Ot /GF /Gy /fp:fast> + ) + else() + target_compile_options(${target_name} PRIVATE + $<$>:-O3 -fno-math-errno -fno-trapping-math -ffp-contract=fast> + ) + endif() + # Add include directories - INCLUDE generated FOLDER FOR HEADERS target_include_directories(${target_name} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/generated ${CMAKE_CURRENT_SOURCE_DIR}/include ${BRIDGE_DIR}/include + ${BRIDGE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/../../native/include ${PLUGIN_INCLUDE_DIRS} ) @@ -220,6 +278,7 @@ function(add_dart_vst3_plugin target_name dart_file) if(EXISTS ${METADATA_CMAKE_FILE}) target_compile_definitions(${target_name} PRIVATE PLUGIN_NAME="${JSON_PLUGIN_NAME}" + PLUGIN_TARGET_NAME=${target_name} PLUGIN_VENDOR="${JSON_VENDOR}" PLUGIN_VERSION="${JSON_VERSION}" PLUGIN_CATEGORY="${JSON_CATEGORY}" @@ -228,121 +287,82 @@ function(add_dart_vst3_plugin target_name dart_file) ) endif() + set(FLUTTER_VST3_WANTS_FLUTTER FALSE) + if(JSON_FLUTTER_ENTRYPOINT AND NOT FLUTTER_VST3_NATIVE_UI_ONLY) + set(FLUTTER_VST3_WANTS_FLUTTER TRUE) + target_compile_definitions(${target_name} PRIVATE + VST3_FLUTTER_ENTRYPOINT="${JSON_FLUTTER_ENTRYPOINT}" + ) + endif() + message(STATUS "${target_name} Flutter editor: ${FLUTTER_VST3_WANTS_FLUTTER}") + # Link against SDK and additional libraries target_link_libraries(${target_name} PRIVATE sdk ${PLUGIN_LINK_LIBRARIES} ) - - # Set bundle properties on macOS - if(SMTG_MAC) - # Create Info.plist.in in build directory to avoid polluting source - set(INFO_PLIST_PATH "${CMAKE_CURRENT_BINARY_DIR}/Info.plist.in") - if(NOT EXISTS ${INFO_PLIST_PATH}) - file(WRITE ${INFO_PLIST_PATH} " - - - - CFBundleExecutable - ${PLUGIN_PLUGIN_NAME} - CFBundleIconFile - - CFBundleIdentifier - ${PLUGIN_BUNDLE_IDENTIFIER} - CFBundleName - ${PLUGIN_PLUGIN_NAME} - CFBundlePackageType - BNDL - CFBundleVersion - 1.0.0 - CFBundleSignature - ???? - -") + + if(SMTG_WIN) + target_link_libraries(${target_name} PRIVATE comctl32) + set(FLUTTER_EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/windows/flutter/ephemeral") + flutter_vst3_require_flutter_path("${FLUTTER_EPHEMERAL_DIR}/flutter_windows.h" "Run: flutter build windows --release") + if(FLUTTER_VST3_WANTS_FLUTTER) + message(STATUS "Configuring Flutter Windows UI embedding for ${target_name}...") + target_include_directories(${target_name} PRIVATE + "${FLUTTER_EPHEMERAL_DIR}" + "${FLUTTER_EPHEMERAL_DIR}/cpp_client_wrapper" + "${FLUTTER_EPHEMERAL_DIR}/cpp_client_wrapper/include" + ) + target_sources(${target_name} PRIVATE + "${FLUTTER_EPHEMERAL_DIR}/cpp_client_wrapper/core_implementations.cc" + "${FLUTTER_EPHEMERAL_DIR}/cpp_client_wrapper/standard_codec.cc" + ) + target_link_libraries(${target_name} PRIVATE + "${FLUTTER_EPHEMERAL_DIR}/flutter_windows.dll.lib" + delayimp + ) + target_link_options(${target_name} PRIVATE + "/DELAYLOAD:flutter_windows.dll" + ) + target_compile_definitions(${target_name} PRIVATE + FLUTTER_VST3_HAS_FLUTTER=1 + ) endif() + endif() + + # Link macOS frameworks for embedded views + if(SMTG_MAC) + find_library(FOUNDATION_FRAMEWORK Foundation) + find_library(APPKIT_FRAMEWORK AppKit) + target_link_libraries(${target_name} PRIVATE ${FOUNDATION_FRAMEWORK} ${APPKIT_FRAMEWORK}) - smtg_target_set_bundle(${target_name} - BUNDLE_IDENTIFIER "${PLUGIN_BUNDLE_IDENTIFIER}" - COMPANY_NAME "${PLUGIN_COMPANY_NAME}" - INFOPLIST_IN ${INFO_PLIST_PATH} - ) - - # Set bundle bit for plugins without native library - get_target_property(PLUGIN_PACKAGE_PATH ${target_name} SMTG_PLUGIN_PACKAGE_PATH) - if(NOT EXISTS ${DART_VST_HOST_LIB}) - # Copy Dart executable to VST3 bundle - if(EXISTS ${DART_PROCESSOR_EXE}) - add_custom_command(TARGET ${target_name} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy - ${DART_PROCESSOR_EXE} - "${PLUGIN_PACKAGE_PATH}/Contents/MacOS/${target_name}_processor" - COMMAND SetFile -a B "${PLUGIN_PACKAGE_PATH}" - COMMAND xattr -cr "${PLUGIN_PACKAGE_PATH}" - COMMAND codesign --force --deep --sign - "${PLUGIN_PACKAGE_PATH}" - COMMENT "Bundling Dart executable, setting bundle bit, cleaning attrs, and signing VST3 plugin" - ) - else() - add_custom_command(TARGET ${target_name} POST_BUILD - COMMAND SetFile -a B "${PLUGIN_PACKAGE_PATH}" - COMMAND xattr -cr "${PLUGIN_PACKAGE_PATH}" - COMMAND codesign --force --deep --sign - "${PLUGIN_PACKAGE_PATH}" - COMMENT "Setting bundle bit, cleaning attrs, and signing VST3 plugin" - ) - endif() + find_library(FLUTTER_FRAMEWORK FlutterMacOS PATHS "/usr/local/flutter" PATH_SUFFIXES "bin/cache/artifacts/engine/darwin-x64") + if(FLUTTER_FRAMEWORK) + target_link_libraries(${target_name} PRIVATE ${FLUTTER_FRAMEWORK}) endif() - endif() - - # The native library is optional for standalone VST3 plugins - # Only link if it exists (for plugins that need host functionality) - if(EXISTS "/workspace/native/build") - set(DART_VST_HOST_LIB "/workspace/native/build/libdart_vst_host.dylib") - else() - set(DART_VST_HOST_LIB "${CMAKE_CURRENT_SOURCE_DIR}/../../native/build/libdart_vst_host.dylib") - endif() - - if(EXISTS ${DART_VST_HOST_LIB}) - target_link_libraries(${target_name} - PRIVATE - ${DART_VST_HOST_LIB} - ) - - # Bundle the dylib into the VST3 package on macOS - if(SMTG_MAC) - get_target_property(PLUGIN_PACKAGE_PATH ${target_name} SMTG_PLUGIN_PACKAGE_PATH) - - # Create basic command list - set(BUNDLE_COMMANDS - COMMAND ${CMAKE_COMMAND} -E make_directory - "${PLUGIN_PACKAGE_PATH}/Contents/Frameworks" - COMMAND ${CMAKE_COMMAND} -E copy_if_different - "${DART_VST_HOST_LIB}" - "${PLUGIN_PACKAGE_PATH}/Contents/Frameworks/" - COMMAND install_name_tool -change @rpath/libdart_vst_host.dylib - @loader_path/../Frameworks/libdart_vst_host.dylib - "${PLUGIN_PACKAGE_PATH}/Contents/MacOS/${target_name}" + elseif(SMTG_LINUX) + find_package(PkgConfig REQUIRED) + pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0 gtk+-x11-3.0) + target_link_libraries(${target_name} PRIVATE PkgConfig::GTK ${CMAKE_DL_LIBS}) + set(FLUTTER_LINUX_EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/linux/flutter/ephemeral") + flutter_vst3_require_flutter_path("${FLUTTER_LINUX_EPHEMERAL_DIR}/flutter_linux/flutter_linux.h" "Run: flutter build linux --release") + if(FLUTTER_VST3_WANTS_FLUTTER) + message(STATUS "Configuring Flutter Linux UI embedding for ${target_name}...") + # The engine library is bundled next to the plugin binary. + set_target_properties(${target_name} PROPERTIES BUILD_WITH_INSTALL_RPATH TRUE BUILD_RPATH "$ORIGIN" INSTALL_RPATH "$ORIGIN") + target_include_directories(${target_name} PRIVATE + "${FLUTTER_LINUX_EPHEMERAL_DIR}" ) - - # Add Dart executable copy if it exists - if(EXISTS ${DART_PROCESSOR_EXE}) - list(APPEND BUNDLE_COMMANDS - COMMAND ${CMAKE_COMMAND} -E copy - ${DART_PROCESSOR_EXE} - "${PLUGIN_PACKAGE_PATH}/Contents/MacOS/${target_name}_processor" - ) - endif() - - # Add signing commands - list(APPEND BUNDLE_COMMANDS - COMMAND SetFile -a B "${PLUGIN_PACKAGE_PATH}" - COMMAND xattr -cr "${PLUGIN_PACKAGE_PATH}" - COMMAND codesign --force --deep --sign - "${PLUGIN_PACKAGE_PATH}" + target_link_libraries(${target_name} PRIVATE + "${FLUTTER_LINUX_EPHEMERAL_DIR}/libflutter_linux_gtk.so" ) - - add_custom_command(TARGET ${target_name} POST_BUILD - ${BUNDLE_COMMANDS} - COMMENT "Bundling libdart_vst_host.dylib and Dart executable, fixing rpath, setting bundle bit, cleaning attrs, and signing" + target_compile_definitions(${target_name} PRIVATE + FLUTTER_VST3_HAS_FLUTTER=1 ) endif() endif() + + # Set bundle properties on macOS + flutter_vst3_bundle_resources(${target_name}) endfunction() \ No newline at end of file diff --git a/flutter_vst3/native/cmake/VST3BridgeBundle.cmake b/flutter_vst3/native/cmake/VST3BridgeBundle.cmake new file mode 100644 index 0000000..819dac6 --- /dev/null +++ b/flutter_vst3/native/cmake/VST3BridgeBundle.cmake @@ -0,0 +1,147 @@ +# Copies the Dart worker and the Flutter runtime into the plugin bundle. +# A macro, because it reads the variables set by add_dart_vst3_plugin. +macro(flutter_vst3_bundle_resources target_name) + if(SMTG_MAC) + # Create Info.plist.in in build directory to avoid polluting source + set(INFO_PLIST_PATH "${CMAKE_CURRENT_BINARY_DIR}/Info.plist.in") + if(NOT EXISTS ${INFO_PLIST_PATH}) + file(WRITE ${INFO_PLIST_PATH} " + + + + CFBundleExecutable + ${PLUGIN_PLUGIN_NAME} + CFBundleIconFile + + CFBundleIdentifier + ${PLUGIN_BUNDLE_IDENTIFIER} + CFBundleName + ${PLUGIN_PLUGIN_NAME} + CFBundlePackageType + BNDL + CFBundleVersion + 1.0.0 + CFBundleSignature + ???? + + ") + endif() + + smtg_target_set_bundle(${target_name} + BUNDLE_IDENTIFIER "${PLUGIN_BUNDLE_IDENTIFIER}" + COMPANY_NAME "${PLUGIN_COMPANY_NAME}" + INFOPLIST_IN ${INFO_PLIST_PATH} + ) + + # Set bundle bit for plugins without native library + get_target_property(PLUGIN_PACKAGE_PATH ${target_name} SMTG_PLUGIN_PACKAGE_PATH) + set(BUNDLE_COMMANDS) + + # Copy Dart processor executable if exists + if(EXISTS ${DART_PROCESSOR_EXE}) + list(APPEND BUNDLE_COMMANDS + COMMAND ${CMAKE_COMMAND} -E copy + ${DART_PROCESSOR_EXE} + "${PLUGIN_PACKAGE_PATH}/Contents/MacOS/${target_name}_processor" + ) + endif() + + # Copy and link host dylib if exists + if(EXISTS ${DART_VST_HOST_LIB}) + target_link_libraries(${target_name} PRIVATE ${DART_VST_HOST_LIB}) + list(APPEND BUNDLE_COMMANDS + COMMAND ${CMAKE_COMMAND} -E make_directory "${PLUGIN_PACKAGE_PATH}/Contents/Frameworks" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${DART_VST_HOST_LIB}" + "${PLUGIN_PACKAGE_PATH}/Contents/Frameworks/" + COMMAND install_name_tool -change @rpath/libdart_vst_host.dylib + @loader_path/../Frameworks/libdart_vst_host.dylib + "${PLUGIN_PACKAGE_PATH}/Contents/MacOS/${target_name}" + ) + endif() + + # Copy Flutter frameworks if present + set(FLUTTER_MAC_FW_DIR "${CMAKE_CURRENT_SOURCE_DIR}/build/macos/Build/Products/${FLUTTER_VST3_BUNDLE_MODE}/${target_name}.app/Contents/Frameworks") + flutter_vst3_require_flutter_path("${FLUTTER_MAC_FW_DIR}/FlutterMacOS.framework" "Run: flutter build macos --${FLUTTER_VST3_BUNDLE_MODE_LOWER}") + if(FLUTTER_VST3_WANTS_FLUTTER) + list(APPEND BUNDLE_COMMANDS + COMMAND ${CMAKE_COMMAND} -E make_directory "${PLUGIN_PACKAGE_PATH}/Contents/Frameworks" + COMMAND cp -a "${FLUTTER_MAC_FW_DIR}/FlutterMacOS.framework" "${PLUGIN_PACKAGE_PATH}/Contents/Frameworks/" + COMMAND cp -a "${FLUTTER_MAC_FW_DIR}/App.framework" "${PLUGIN_PACKAGE_PATH}/Contents/Frameworks/" + COMMAND codesign --force --sign - "${PLUGIN_PACKAGE_PATH}/Contents/Frameworks/FlutterMacOS.framework" + COMMAND codesign --force --sign - "${PLUGIN_PACKAGE_PATH}/Contents/Frameworks/App.framework" + ) + endif() + + # Set bundle bit, strip quarantine, and sign outer bundle + list(APPEND BUNDLE_COMMANDS + COMMAND SetFile -a B "${PLUGIN_PACKAGE_PATH}" + COMMAND xattr -cr "${PLUGIN_PACKAGE_PATH}" + COMMAND codesign --force --sign - "${PLUGIN_PACKAGE_PATH}" + ) + + add_custom_command(TARGET ${target_name} POST_BUILD + ${BUNDLE_COMMANDS} + COMMENT "Finalizing and codesigning VST3 bundle" + ) + elseif(SMTG_WIN) + get_target_property(PLUGIN_PACKAGE_PATH ${target_name} SMTG_PLUGIN_PACKAGE_PATH) + set(BUNDLE_COMMANDS) + if(EXISTS ${DART_PROCESSOR_EXE}) + list(APPEND BUNDLE_COMMANDS + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${DART_PROCESSOR_EXE}" + "${PLUGIN_PACKAGE_PATH}/Contents/x86_64-win/${target_name}_processor.exe" + ) + endif() + set(FLUTTER_WIN_DIR "${CMAKE_CURRENT_SOURCE_DIR}/build/windows/x64/runner/${FLUTTER_VST3_BUNDLE_MODE}") + flutter_vst3_require_flutter_path("${FLUTTER_WIN_DIR}/flutter_windows.dll" "Run: flutter build windows --${FLUTTER_VST3_BUNDLE_MODE_LOWER}") + if(FLUTTER_VST3_WANTS_FLUTTER) + list(APPEND BUNDLE_COMMANDS + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${FLUTTER_WIN_DIR}/flutter_windows.dll" + "${PLUGIN_PACKAGE_PATH}/Contents/x86_64-win/flutter_windows.dll" + COMMAND ${CMAKE_COMMAND} -E copy_directory + "${FLUTTER_WIN_DIR}/data" + "${PLUGIN_PACKAGE_PATH}/Contents/x86_64-win/data" + ) + endif() + if(BUNDLE_COMMANDS) + add_custom_command(TARGET ${target_name} POST_BUILD + ${BUNDLE_COMMANDS} + COMMENT "Bundling Dart processor and Flutter Windows assets into VST3 package" + ) + endif() + elseif(SMTG_LINUX) + get_target_property(PLUGIN_PACKAGE_PATH ${target_name} SMTG_PLUGIN_PACKAGE_PATH) + set(BUNDLE_COMMANDS) + if(EXISTS ${DART_PROCESSOR_EXE}) + list(APPEND BUNDLE_COMMANDS + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${DART_PROCESSOR_EXE}" + "${PLUGIN_PACKAGE_PATH}/Contents/x86_64-linux/${target_name}_processor" + ) + endif() + set(FLUTTER_LINUX_DIR "${CMAKE_CURRENT_SOURCE_DIR}/build/linux/x64/${FLUTTER_VST3_BUNDLE_MODE_LOWER}/bundle") + flutter_vst3_require_flutter_path("${FLUTTER_LINUX_DIR}/lib/libflutter_linux_gtk.so" "Run: flutter build linux --${FLUTTER_VST3_BUNDLE_MODE_LOWER}") + if(FLUTTER_VST3_WANTS_FLUTTER) + list(APPEND BUNDLE_COMMANDS + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${FLUTTER_LINUX_DIR}/lib/libflutter_linux_gtk.so" + "${PLUGIN_PACKAGE_PATH}/Contents/x86_64-linux/libflutter_linux_gtk.so" + COMMAND ${CMAKE_COMMAND} -E copy_directory + "${FLUTTER_LINUX_DIR}/data" + "${PLUGIN_PACKAGE_PATH}/Contents/x86_64-linux/data" + COMMAND ${CMAKE_COMMAND} -E copy_directory + "${FLUTTER_LINUX_DIR}/lib" + "${PLUGIN_PACKAGE_PATH}/Contents/x86_64-linux/lib" + ) + endif() + if(BUNDLE_COMMANDS) + add_custom_command(TARGET ${target_name} POST_BUILD + ${BUNDLE_COMMANDS} + COMMENT "Bundling Dart processor and Flutter Linux assets into VST3 package" + ) + endif() + endif() +endmacro() diff --git a/flutter_vst3/native/include/dart_vst3_bridge.h b/flutter_vst3/native/include/dart_vst3_bridge.h deleted file mode 100644 index eb85828..0000000 --- a/flutter_vst3/native/include/dart_vst3_bridge.h +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2025 -// -// Generic C bridge for calling Dart VST3 processors from C++ -// This provides a universal interface between VST3 C++ code and -// pure Dart implementations via FFI callbacks. - -#pragma once -#include - -#ifdef _WIN32 -# ifdef DART_VST_HOST_EXPORTS -# define DART_VST3_API __declspec(dllexport) -# else -# define DART_VST3_API __declspec(dllimport) -# endif -#else -# define DART_VST3_API __attribute__((visibility("default"))) -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// Function pointer types for Dart callbacks -typedef void (*DartInitializeProcessorFn)(double sample_rate, int32_t max_block_size); -typedef void (*DartProcessAudioFn)(const float* input_l, const float* input_r, - float* output_l, float* output_r, - int32_t num_samples); -typedef void (*DartSetParameterFn)(int32_t param_id, double normalized_value); -typedef double (*DartGetParameterFn)(int32_t param_id); -typedef int32_t (*DartGetParameterCountFn)(void); -typedef void (*DartResetFn)(void); -typedef void (*DartDisposeFn)(void); - -// Structure holding all Dart callback functions -typedef struct { - DartInitializeProcessorFn initialize_processor; - DartProcessAudioFn process_audio; - DartSetParameterFn set_parameter; - DartGetParameterFn get_parameter; - DartGetParameterCountFn get_parameter_count; - DartResetFn reset; - DartDisposeFn dispose; -} DartVST3Callbacks; - -// Per-plugin instance management -typedef struct DartVST3Instance DartVST3Instance; - -// Create a new plugin instance -DART_VST3_API DartVST3Instance* dart_vst3_create_instance(const char* plugin_id); - -// Destroy a plugin instance -DART_VST3_API int32_t dart_vst3_destroy_instance(DartVST3Instance* instance); - -// Register Dart callback functions for a specific plugin instance -DART_VST3_API int32_t dart_vst3_register_callbacks(DartVST3Instance* instance, - const DartVST3Callbacks* callbacks); - -// Initialize the Dart processor -DART_VST3_API int32_t dart_vst3_initialize(DartVST3Instance* instance, - double sample_rate, int32_t max_block_size); - -// Process stereo audio through Dart processor -DART_VST3_API int32_t dart_vst3_process_stereo(DartVST3Instance* instance, - const float* input_l, const float* input_r, - float* output_l, float* output_r, - int32_t num_samples); - -// Set/get parameter values -DART_VST3_API int32_t dart_vst3_set_parameter(DartVST3Instance* instance, - int32_t param_id, double normalized_value); -DART_VST3_API double dart_vst3_get_parameter(DartVST3Instance* instance, int32_t param_id); -DART_VST3_API int32_t dart_vst3_get_parameter_count(DartVST3Instance* instance); - -// Reset processor state -DART_VST3_API int32_t dart_vst3_reset(DartVST3Instance* instance); - -// Dispose resources -DART_VST3_API int32_t dart_vst3_dispose(DartVST3Instance* instance); - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/flutter_vst3/native/include/embedded_flutter_view.h b/flutter_vst3/native/include/embedded_flutter_view.h new file mode 100644 index 0000000..c44c791 --- /dev/null +++ b/flutter_vst3/native/include/embedded_flutter_view.h @@ -0,0 +1,83 @@ +// Copyright (c) 2025 +// Header for embedded Flutter/Native view factory function +// +// Architecture & Synchronization Overview: +// In the Steinberg VST3 architecture, the `EditController` handles parameter +// management and UI creation (`createView`). When using Steinberg's proprietary +// VSTGUI framework, parameter changes from the host automatically propagate +// to controls. However, when embedding an OS-native view (such as macOS AppKit +// NSView, Windows HWND, or Linux X11/Wayland), Steinberg's `EditController` +// does not have a built-in mechanism to notify the native view. +// +// `IEmbeddedFlutterView` solves this: +// 1. Controller -> View: The controller implements `setParamNormalized` and +// forwards incoming host/automation updates to `activeView_->updateParameter(id, value)`. +// 2. View -> Controller: User interactions in the native GUI call +// `EditController::beginEdit`, `setParamNormalized`, `performEdit`, and `endEdit`, +// which notify both the DAW automation queue and the real-time audio DSP thread. +// 3. Safe Lifecycles: An optional `IEmbeddedFlutterView** outViewPtr` holder ensures +// neither the controller nor the view holds dangling pointers if either is closed first. + +#pragma once + +#include "pluginterfaces/gui/iplugview.h" +#include "pluginterfaces/vst/vsttypes.h" +#include "view_logic.h" +#include "public.sdk/source/vst/vsteditcontroller.h" + +namespace Steinberg { + class IPlugView; + +namespace Vst { + class EditController; + + inline uintptr_t controllerShmAddress(EditController* controller) { + const auto* source = dynamic_cast(controller); + return source ? source->sharedMemoryAddress() : 0; + } + + inline void endControllerEdits(EditController* controller) { + auto* source = dynamic_cast(controller); + if (source) source->endOpenEdits(); + } + + /// Applies an edit from a UI. A UI whose gesture was ended by closing the + /// editor can still send edits, and those must not reach the controller. + inline void applyUiEdit(EditController* controller, ParamID id, ParamValue value) { + auto* source = dynamic_cast(controller); + if (source && !source->isEditing(id)) return; + controller->setParamNormalized(id, value); + controller->performEdit(id, value); + } + + /// Interface implemented by native UI views (Cocoa/Win32/X11) to receive + /// parameter updates directly from the VST3 EditController. + class IEmbeddedFlutterView { + public: + virtual ~IEmbeddedFlutterView() = default; + + /// Called by EditController::setParamNormalized when a parameter is updated + /// by the DAW host, preset loading, or parameter automation. + /// + /// Implementations should dispatch the update to the main UI thread. + virtual void updateParameter(ParamID id, ParamValue value) = 0; + + /// Notifies the view that the parent EditController is being destroyed. + /// The view must clear any references to the controller to prevent use-after-free. + virtual void onControllerClosed() = 0; + }; + + /// Factory function that creates the platform-specific embedded plugin view. + /// + /// @param controller Pointer to the plugin's EditController. + /// @param pluginName Display name of the plugin shown in the UI header. + /// @param outViewPtr Optional pointer to the controller's active view holder. + /// When provided, the view registers itself and automatically + /// nullifies `*outViewPtr` when the view window is closed. + /// @return A pointer to the newly created IPlugView instance. + IPlugView* createEmbeddedFlutterView( + EditController* controller, + const char* pluginName, + IEmbeddedFlutterView** outViewPtr = nullptr); +} +} \ No newline at end of file diff --git a/flutter_vst3/native/include/native_cocoa_view.h b/flutter_vst3/native/include/native_cocoa_view.h new file mode 100644 index 0000000..ed0b17e --- /dev/null +++ b/flutter_vst3/native/include/native_cocoa_view.h @@ -0,0 +1,35 @@ +// Copyright (c) 2025 +// Native Cocoa/AppKit view fallback for macOS VST3 plugins + +#pragma once + +#import +#include "public.sdk/source/vst/vsteditcontroller.h" +#include + +#define CONCAT_INNER(a, b) a##_##b +#define CONCAT(a, b) CONCAT_INNER(a, b) +#ifndef PLUGIN_TARGET_NAME +#error PLUGIN_TARGET_NAME is required for module-specific Objective-C class names +#endif +#ifdef PLUGIN_TARGET_NAME +#define Vst3FlippedView CONCAT(Vst3FlippedView, PLUGIN_TARGET_NAME) +#define Vst3PluginEditorDelegate CONCAT(Vst3PluginEditorDelegate, PLUGIN_TARGET_NAME) +#endif + +/// Delegate handling Cocoa sliders and parameter labels. +@interface Vst3PluginEditorDelegate : NSObject +@property (nonatomic, assign) Steinberg::Vst::EditController* controller; +@property (nonatomic, strong) NSMutableArray* sliders; +@property (nonatomic, strong) NSMutableArray* valueLabels; + +- (void)onSliderChanged:(NSSlider*)sender; +- (void)updateParamId:(Steinberg::Vst::ParamID)paramId withValue:(Steinberg::Vst::ParamValue)value; +@end + +/// Builds the native Cocoa fallback UI with header, sliders, and footer. +NSView* createCocoaFallbackView( + NSView* parent, + Steinberg::Vst::EditController* controller, + const std::string& pluginName, + Vst3PluginEditorDelegate** outDelegate); diff --git a/flutter_vst3/native/include/plugin_ids.h b/flutter_vst3/native/include/plugin_ids.h deleted file mode 100644 index b30344e..0000000 --- a/flutter_vst3/native/include/plugin_ids.h +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2025 -// -// Definition of unique identifiers for the Dart VST host plug‑in. The -// processor and controller GUIDs must be globally unique to avoid -// clashes with other plug‑ins. Adjust these values when creating a -// new plug‑in product. - -#pragma once -#include "pluginterfaces/base/fplatform.h" -#include "pluginterfaces/base/funknown.h" -#include "pluginterfaces/vst/vsttypes.h" - -// com.yourorg.DartVstHost -static const Steinberg::FUID kProcessorUID (0xA1B2C3D4, 0x00000001, 0x00000002, 0x00000003); -static const Steinberg::FUID kControllerUID(0xA1B2C3D4, 0x00000004, 0x00000005, 0x00000006); - -// Parameter identifiers for the host plug‑in. Currently only one -// parameter controlling the output gain of the main mixer. When you -// add more exposed parameters to the graph they should be listed here. -enum Params : Steinberg::Vst::ParamID { - kParamOutputGain = 0, -}; \ No newline at end of file diff --git a/flutter_vst3/native/include/view_logic.h b/flutter_vst3/native/include/view_logic.h new file mode 100644 index 0000000..c319697 --- /dev/null +++ b/flutter_vst3/native/include/view_logic.h @@ -0,0 +1,43 @@ +#pragma once +#include +#include +#include + +namespace flutter_vst3 { +/// Executes queued UI work only while its editor's liveness token is live. +template inline void withLiveEditor(const std::atomic& alive, Work work) { + if (alive.load()) work(); +} +inline constexpr unsigned kFlutterStartTimeoutMs = 10000; +inline bool flutterStartFailed(bool uiAlive, bool engineFailed, bool hasOwner) { + return hasOwner && (engineFailed || !uiAlive); +} +/// Pure ownership decisions shared by platform editors. +inline bool ownsEditor(const void* owner, const void* candidate) { + return owner != nullptr && owner == candidate; +} +inline uintptr_t localShmAddress(int64_t address, int64_t sender, int64_t current) { + return sender == current ? static_cast(address) : 0; +} +/// Tracks balanced gestures and suppresses host-to-view feedback while editing. +class EditState { +public: + std::set takeOpen() { + std::set result; + result.swap(editing_); + return result; + } + bool begin(uint32_t id) { return editing_.insert(id).second; } + bool end(uint32_t id) { return editing_.erase(id) != 0; } + bool shouldEcho(uint32_t id) const { return editing_.count(id) == 0; } +private: + std::set editing_; +}; +/// Controller-owned address; never a process-global active instance. +struct ShmAddressSource { + virtual ~ShmAddressSource() = default; + virtual uintptr_t sharedMemoryAddress() const = 0; + virtual void endOpenEdits() = 0; + virtual bool isEditing(uint32_t id) const = 0; +}; +} diff --git a/flutter_vst3/native/include/vst3_ipc_host.h b/flutter_vst3/native/include/vst3_ipc_host.h new file mode 100644 index 0000000..a4179ed --- /dev/null +++ b/flutter_vst3/native/include/vst3_ipc_host.h @@ -0,0 +1,90 @@ +// Copyright (c) 2025 +// Plugin side of the shared memory bridge to a Dart worker process. +// +// Each plugin instance owns one Vst3IpcHost and so has its own worker, memory +// block and semaphores. Threads: +// - configure, reset and dispose run on the host's non-realtime thread, never +// concurrently with process (VST3 setActive and terminate rules). +// - setParameter and process run on the audio thread. They never allocate or +// lock, and process never waits longer than the block's own duration. + +#pragma once + +#include +#include +#include + +#include "vst3_shared_memory.h" + +/// Returns the path of workerName next to the module containing this code. +std::string vst3WorkerPathNextToModule(const std::string& workerName); + +class Vst3IpcHost { +public: + /// Creates an idle host. Nothing is spawned until configure. + Vst3IpcHost(std::string workerPath, int parameterCount); + ~Vst3IpcHost(); + Vst3IpcHost(const Vst3IpcHost&) = delete; + Vst3IpcHost& operator=(const Vst3IpcHost&) = delete; + + /// Starts the worker, or reconfigures a running one. Replays known + /// parameter values to a new worker. Throws, leaving nothing behind, if the + /// worker can't start. + void configure(double sampleRate, int maxBlockSize, bool offline); + + /// Clears DSP state in the worker. Does nothing if no worker is running. + void reset(); + + /// Stops the worker and releases its resources. Safe to call repeatedly. + void dispose(); + + /// Records a parameter value for the next block. Later values win, so + /// nothing is lost while the worker is late. Unknown ids are ignored. + void setParameter(int paramId, double value) noexcept; + + /// Renders any number of samples. Returns false, with all of the output + /// silent, if the worker was late or dead for any part of it. + bool process(const float* inL, const float* inR, float* outL, float* outR, int numSamples) noexcept; + + /// True once configure has succeeded and the worker hasn't been seen dead. + bool isRunning() const noexcept { return running_ && !dead_; } + + /// Memory block for in-process readers, or null when idle. An address taken + /// from here stays mapped after dispose with a + /// zero magic word, so a reader can never fault on it. + Vst3SharedMemory* memory() const noexcept { return memory_; } + + /// Worker process id, or 0 when there is none. + int64_t workerProcessId() const noexcept; + +private: + bool processChunk(const float* inL, const float* inR, float* outL, float* outR, int numSamples) noexcept; + bool reclaimFromLateWorker() noexcept; + void flushParameters() noexcept; + void noteWorkerLate() noexcept; + void forgetDeadWorker() noexcept; + void reclaimForControl(); + void start(double sampleRate, int maxBlockSize); + void sendControl(uint32_t command); + void waitForWorker(int timeoutMs); + void stopWorker() noexcept; + void releaseResources() noexcept; + + std::string workerPath_; + std::string shmName_; + std::string semReadyName_; + std::string semDoneName_; + Vst3SharedMemory* memory_ = nullptr; + void* mappingHandle_ = nullptr; + void* semReady_ = nullptr; + void* semDone_ = nullptr; + intptr_t child_ = 0; + bool running_ = false; + bool dead_ = false; + bool workerBusy_ = false; + double secondsPerSample_ = 0.0; + bool offline_ = false; + std::vector paramValues_; + std::vector paramKnown_; + std::vector paramDirty_; +}; diff --git a/flutter_vst3/native/include/vst3_plugin_state.h b/flutter_vst3/native/include/vst3_plugin_state.h new file mode 100644 index 0000000..c035723 --- /dev/null +++ b/flutter_vst3/native/include/vst3_plugin_state.h @@ -0,0 +1,33 @@ +// Copyright (c) 2025 +// The saved state of a generated plugin: one normalized double per parameter. +// The processor and the controller both read it, and must agree on what's valid. + +#pragma once + +#include +#include + +#include "pluginterfaces/base/ibstream.h" + +/// Reads count values from state. Returns false if the stream is short or any +/// value isn't a normalized number, so a caller applies all of a state or none. +inline bool vst3ReadPluginState(Steinberg::IBStream* state, int count, std::vector& values) { + if (!state) return false; + std::vector read(static_cast(count)); + for (double& value : read) { + Steinberg::int32 bytesRead = 0; + if (state->read(&value, sizeof(value), &bytesRead) != Steinberg::kResultTrue || bytesRead != sizeof(value)) { + return false; + } + if (!std::isfinite(value) || value < 0.0 || value > 1.0) return false; + } + values.swap(read); + return true; +} + +/// Appends one value to state. Returns false if the stream took less than all of it. +inline bool vst3WritePluginStateValue(Steinberg::IBStream* state, double value) { + Steinberg::int32 bytesWritten = 0; + return state->write(&value, sizeof(value), &bytesWritten) == Steinberg::kResultTrue && + bytesWritten == sizeof(value); +} diff --git a/flutter_vst3/native/include/vst3_shared_memory.h b/flutter_vst3/native/include/vst3_shared_memory.h new file mode 100644 index 0000000..e48ec83 --- /dev/null +++ b/flutter_vst3/native/include/vst3_shared_memory.h @@ -0,0 +1,118 @@ +// Copyright (c) 2025 +// VST3 shared memory layout +// +// One fixed block of memory is shared between the plugin (inside the host) and +// its Dart worker process. Audio is copied in and out of it once per block. +// +// Ownership of the block passes between the processes with two named +// semaphores, so no field needs to be atomic: +// - The plugin owns the block until it posts sem_ready. +// - The worker owns the block from sem_ready until it posts sem_done. +// If the worker runs late, the plugin leaves the block alone until the late +// sem_done arrives. +// +// flutter_vst3/lib/src/vst3_shm_layout.dart mirrors these constants, and +// flutter_vst3/test/vst3_shm_layout_test.dart fails if the two differ. + +#pragma once + +#include +#include + +/// Magic identifier ('VST3') validating memory layout compatibility. +#define VST3_SHM_MAGIC 0x56535433 + +/// Protocol version number. +#define VST3_SHM_VERSION 2 + +/// Maximum number of audio samples supported per processing block (e.g. 4096 samples). +#define VST3_SHM_MAX_SAMPLES 4096 + +/// Capacity of the circular parameter ring buffers. +#define VST3_SHM_PARAM_QUEUE_SIZE 64 + +// Commands sent from C++ host wrapper to Dart processor via Vst3SharedMemory::command +#define VST3_CMD_IDLE 0 // Standby / no-op +#define VST3_CMD_PROCESS 1 // Process the current audio buffer in numSamples +#define VST3_CMD_TERMINATE 2 // Shut down the Dart processor event loop +#define VST3_CMD_CONFIGURE 3 // Reinitialize the DSP from sampleRate and maxBlockSize +#define VST3_CMD_RESET 4 // Clear DSP state such as delay tails + +// Fixed memory byte offsets ensuring exact binary alignment across C++ and Dart FFI +#define VST3_SHM_OFFSET_MAGIC 0 +#define VST3_SHM_OFFSET_VERSION 4 +#define VST3_SHM_OFFSET_SAMPLE_RATE 8 +#define VST3_SHM_OFFSET_MAX_BLOCK_SIZE 16 +#define VST3_SHM_OFFSET_COMMAND 20 +#define VST3_SHM_OFFSET_NUM_SAMPLES 24 +#define VST3_SHM_OFFSET_HOST_PARAM_WRITE 28 +#define VST3_SHM_OFFSET_HOST_PARAM_READ 32 +#define VST3_SHM_OFFSET_HOST_PARAMS 36 +#define VST3_SHM_OFFSET_UI_PARAM_WRITE 1060 +#define VST3_SHM_OFFSET_UI_PARAM_READ 1064 +#define VST3_SHM_OFFSET_UI_PARAMS 1068 +#define VST3_SHM_OFFSET_INPUT_L 4096 +#define VST3_SHM_OFFSET_INPUT_R 20480 +#define VST3_SHM_OFFSET_OUTPUT_L 36864 +#define VST3_SHM_OFFSET_OUTPUT_R 53248 +#define VST3_SHM_TOTAL_SIZE 69632 + +#pragma pack(push, 1) + +/// Represents a single parameter change event within a ring buffer. +struct Vst3ParamEvent { + int32_t paramId; // Target parameter identifier + int32_t padding; // Alignment padding + double value; // Normalized parameter value (0.0 to 1.0) +}; + +/// Main shared memory layout mapped between C++ and Dart processes. +/// Exactly 69,632 bytes (17 x 4096-byte pages) with audio buffers page-aligned at 4096. +struct Vst3SharedMemory { + // Header & control flags + uint32_t magic; // Set to VST3_SHM_MAGIC (0x56535433) + uint32_t version; // Protocol version (VST3_SHM_VERSION) + double sampleRate; // Host sample rate in Hz (e.g. 44100.0, 48000.0) + uint32_t maxBlockSize; // Host maximum buffer block size + uint32_t command; // Active command: VST3_CMD_PROCESS or VST3_CMD_TERMINATE + int32_t numSamples; // Number of valid samples in the current processing block + + // Parameter queue: DAW host automation -> Dart DSP processor + uint32_t hostParamWriteIndex; + uint32_t hostParamReadIndex; + Vst3ParamEvent hostParams[VST3_SHM_PARAM_QUEUE_SIZE]; + + // Parameter queue: Dart UI -> DAW host controller + uint32_t uiParamWriteIndex; + uint32_t uiParamReadIndex; + Vst3ParamEvent uiParams[VST3_SHM_PARAM_QUEUE_SIZE]; + + uint8_t reserved[2004]; // Padding to align audio buffers to 4096 bytes + + // Preallocated Audio Buffers (page-aligned at offset 4096 for optimal SIMD throughput) + float inputL[VST3_SHM_MAX_SAMPLES]; // Left channel input from DAW + float inputR[VST3_SHM_MAX_SAMPLES]; // Right channel input from DAW + float outputL[VST3_SHM_MAX_SAMPLES]; // Left channel output back to DAW + float outputR[VST3_SHM_MAX_SAMPLES]; // Right channel output back to DAW +}; +#pragma pack(pop) + +#ifdef __cplusplus +static_assert(offsetof(Vst3SharedMemory, version) == VST3_SHM_OFFSET_VERSION, "layout"); +static_assert(offsetof(Vst3SharedMemory, sampleRate) == VST3_SHM_OFFSET_SAMPLE_RATE, "layout"); +static_assert(offsetof(Vst3SharedMemory, maxBlockSize) == VST3_SHM_OFFSET_MAX_BLOCK_SIZE, "layout"); +static_assert(offsetof(Vst3SharedMemory, command) == VST3_SHM_OFFSET_COMMAND, "layout"); +static_assert(offsetof(Vst3SharedMemory, numSamples) == VST3_SHM_OFFSET_NUM_SAMPLES, "layout"); +static_assert(offsetof(Vst3SharedMemory, hostParamWriteIndex) == VST3_SHM_OFFSET_HOST_PARAM_WRITE, "layout"); +static_assert(offsetof(Vst3SharedMemory, hostParamReadIndex) == VST3_SHM_OFFSET_HOST_PARAM_READ, "layout"); +static_assert(offsetof(Vst3SharedMemory, hostParams) == VST3_SHM_OFFSET_HOST_PARAMS, "layout"); +static_assert(offsetof(Vst3SharedMemory, uiParamWriteIndex) == VST3_SHM_OFFSET_UI_PARAM_WRITE, "layout"); +static_assert(offsetof(Vst3SharedMemory, uiParamReadIndex) == VST3_SHM_OFFSET_UI_PARAM_READ, "layout"); +static_assert(offsetof(Vst3SharedMemory, uiParams) == VST3_SHM_OFFSET_UI_PARAMS, "layout"); +static_assert(offsetof(Vst3SharedMemory, inputL) == VST3_SHM_OFFSET_INPUT_L, "layout"); +static_assert(offsetof(Vst3SharedMemory, inputR) == VST3_SHM_OFFSET_INPUT_R, "layout"); +static_assert(offsetof(Vst3SharedMemory, outputL) == VST3_SHM_OFFSET_OUTPUT_L, "layout"); +static_assert(offsetof(Vst3SharedMemory, outputR) == VST3_SHM_OFFSET_OUTPUT_R, "layout"); +static_assert(sizeof(Vst3ParamEvent) == 16, "layout"); +static_assert(sizeof(Vst3SharedMemory) == VST3_SHM_TOTAL_SIZE, "layout"); +#endif diff --git a/flutter_vst3/native/src/dart_vst3_bridge.cpp b/flutter_vst3/native/src/dart_vst3_bridge.cpp deleted file mode 100644 index e6968bb..0000000 --- a/flutter_vst3/native/src/dart_vst3_bridge.cpp +++ /dev/null @@ -1,171 +0,0 @@ -// Copyright (c) 2025 -// -// Implementation of the generic C bridge for calling Dart VST3 processors -// from C++. This manages callback functions per plugin instance and provides -// a universal C API that any VST3 processor can use. - -#include "dart_vst3_bridge.h" -#include -#include -#include -#include -#include -#include -#include - -// Per-instance data structure -struct DartVST3Instance { - std::string plugin_id; - DartVST3Callbacks callbacks; - bool callbacks_registered; - std::mutex mutex; - - DartVST3Instance(const std::string& id) - : plugin_id(id), callbacks{0}, callbacks_registered(false) {} -}; - -// Global instance registry -static std::unordered_map> g_instances; -static std::mutex g_instances_mutex; - -extern "C" { - -DartVST3Instance* dart_vst3_create_instance(const char* plugin_id) { - std::lock_guard lock(g_instances_mutex); - - if (!plugin_id) return nullptr; - - auto instance = std::make_unique(plugin_id); - auto* raw_ptr = instance.get(); - g_instances[raw_ptr] = std::move(instance); - - return raw_ptr; -} - -int32_t dart_vst3_destroy_instance(DartVST3Instance* instance) { - std::lock_guard lock(g_instances_mutex); - - if (!instance) return 0; - - auto it = g_instances.find(instance); - if (it != g_instances.end()) { - g_instances.erase(it); - return 1; - } - - return 0; -} - -int32_t dart_vst3_register_callbacks(DartVST3Instance* instance, - const DartVST3Callbacks* callbacks) { - if (!instance || !callbacks) return 0; - - std::lock_guard lock(instance->mutex); - - // Copy all callback function pointers - instance->callbacks = *callbacks; - instance->callbacks_registered = true; - - return 1; -} - -int32_t dart_vst3_initialize(DartVST3Instance* instance, - double sample_rate, int32_t max_block_size) { - if (!instance) return 0; - - std::lock_guard lock(instance->mutex); - - if (!instance->callbacks_registered || !instance->callbacks.initialize_processor) { - return 0; - } - - instance->callbacks.initialize_processor(sample_rate, max_block_size); - return 1; -} - -int32_t dart_vst3_process_stereo(DartVST3Instance* instance, - const float* input_l, const float* input_r, - float* output_l, float* output_r, - int32_t num_samples) { - if (!instance) return 0; - - std::lock_guard lock(instance->mutex); - - if (!instance->callbacks_registered || !instance->callbacks.process_audio) { - // NO FALLBACKS! FAIL HARD! CRASH THE ENTIRE PLUGIN! - fprintf(stderr, "CRITICAL VST3 BRIDGE FAILURE: No Dart callbacks registered! Plugin ID: %s\n", instance->plugin_id.c_str()); - fprintf(stderr, "CALLBACKS_REGISTERED: %d\n", instance->callbacks_registered); - fprintf(stderr, "PROCESS_AUDIO CALLBACK: %p\n", (void*)instance->callbacks.process_audio); - fflush(stderr); - abort(); // KILL THE PLUGIN HARD! - } - - instance->callbacks.process_audio(input_l, input_r, output_l, output_r, num_samples); - return 1; -} - -int32_t dart_vst3_set_parameter(DartVST3Instance* instance, - int32_t param_id, double normalized_value) { - if (!instance) return 0; - - std::lock_guard lock(instance->mutex); - - if (!instance->callbacks_registered || !instance->callbacks.set_parameter) { - return 0; - } - - instance->callbacks.set_parameter(param_id, normalized_value); - return 1; -} - -double dart_vst3_get_parameter(DartVST3Instance* instance, int32_t param_id) { - if (!instance) return 0.0; - - std::lock_guard lock(instance->mutex); - - if (!instance->callbacks_registered || !instance->callbacks.get_parameter) { - return 0.0; - } - - return instance->callbacks.get_parameter(param_id); -} - -int32_t dart_vst3_get_parameter_count(DartVST3Instance* instance) { - if (!instance) return 0; - - std::lock_guard lock(instance->mutex); - - if (!instance->callbacks_registered || !instance->callbacks.get_parameter_count) { - return 0; - } - - return instance->callbacks.get_parameter_count(); -} - -int32_t dart_vst3_reset(DartVST3Instance* instance) { - if (!instance) return 0; - - std::lock_guard lock(instance->mutex); - - if (!instance->callbacks_registered || !instance->callbacks.reset) { - return 0; - } - - instance->callbacks.reset(); - return 1; -} - -int32_t dart_vst3_dispose(DartVST3Instance* instance) { - if (!instance) return 0; - - std::lock_guard lock(instance->mutex); - - if (!instance->callbacks_registered || !instance->callbacks.dispose) { - return 0; - } - - instance->callbacks.dispose(); - return 1; -} - -} // extern "C" \ No newline at end of file diff --git a/flutter_vst3/native/src/embedded_flutter_view.cpp b/flutter_vst3/native/src/embedded_flutter_view.cpp new file mode 100644 index 0000000..977a205 --- /dev/null +++ b/flutter_vst3/native/src/embedded_flutter_view.cpp @@ -0,0 +1,295 @@ +#include "embedded_flutter_view.h" +#include "base/source/fobject.h" +#include "public.sdk/source/vst/vsteditcontroller.h" +#include "pluginterfaces/base/ustring.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "vst3_shared_memory.h" +#if defined(__linux__) +#include +#include +#include +#include +#if defined(FLUTTER_VST3_HAS_FLUTTER) +#include +#endif +#endif + +#if defined(_WIN32) +#ifndef NOMINMAX +#define NOMINMAX +#endif +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include +#pragma comment(lib, "comctl32.lib") + +#if defined(FLUTTER_VST3_HAS_FLUTTER) +#include +#include +#include +#include +#include "binary_messenger_impl.h" +#include "vst3_shared_memory.h" +#include +#include +#include +#endif +#endif + +namespace Steinberg::Vst { + +#ifndef __APPLE__ + +#if defined(_WIN32) +#include "embedded_flutter_view_win_module.inc" +#include "embedded_flutter_view_win_flutter.inc" +#include "embedded_flutter_view_win_native.inc" +#elif defined(__linux__) +#include "embedded_flutter_view_linux_flutter.inc" +#include "embedded_flutter_view_linux_native.inc" +#include "embedded_flutter_view_linux_run_loop.inc" +#endif + +/// Cross-platform IPlugView implementation for Windows (HWND) and Linux (X11). +class EmbeddedFlutterView : public IPlugView, public FObject, public IEmbeddedFlutterView { +public: + EmbeddedFlutterView(EditController* c, const char* name, IEmbeddedFlutterView** holder = nullptr) + : controller_(c), pluginName_(name ? name : "VST3 Plugin"), viewHolder_(holder) { +#if defined(_WIN32) && defined(FLUTTER_VST3_HAS_FLUTTER) + hasFlutter_ = WinFlutterHost::checkHasFlutter(); +#elif defined(__linux__) + hasFlutter_ = LinuxFlutterHost::checkHasFlutter(); +#endif + if (viewHolder_) *viewHolder_ = this; + } + + ~EmbeddedFlutterView() override { + cleanup(); + if (viewHolder_ && *viewHolder_ == this) *viewHolder_ = nullptr; + } + + void updateParameter(ParamID paramId, ParamValue value) override { +#if defined(_WIN32) +#if defined(FLUTTER_VST3_HAS_FLUTTER) + if (hasFlutter_) { + winFlutterHost_.updateParam(paramId, value); + return; + } +#endif + winHost_.updateParam(paramId, value); +#elif defined(__linux__) + if (hasFlutter_) { + linuxFlutterHost_.updateParam(paramId, value); + return; + } + linuxNativeHost_.updateParam(paramId, value); +#endif + } + + void onControllerClosed() override { + cleanup(); + controller_ = nullptr; + viewHolder_ = nullptr; + } + + tresult PLUGIN_API isPlatformTypeSupported(FIDString type) override { +#if defined(_WIN32) + return (type && strcmp(type, kPlatformTypeHWND) == 0) ? kResultTrue : kResultFalse; +#else + return (type && strcmp(type, kPlatformTypeX11EmbedWindowID) == 0) ? kResultTrue : kResultFalse; +#endif + } + + tresult PLUGIN_API attached(void* parent, FIDString type) override { + if (!parent || isPlatformTypeSupported(type) != kResultTrue) return kInvalidArgument; + parentView_ = parent; + if (viewHolder_) *viewHolder_ = this; + size_.reset(); +#if defined(_WIN32) && defined(FLUTTER_VST3_HAS_FLUTTER) + hasFlutter_ = WinFlutterHost::checkHasFlutter(); +#elif defined(__linux__) + hasFlutter_ = LinuxFlutterHost::checkHasFlutter(); +#endif +#if defined(_WIN32) +#if defined(FLUTTER_VST3_HAS_FLUTTER) + winFlutterHost_.onFailure = [this] { mountNativeWindows(); }; + if (hasFlutter_) { + bool ok = winFlutterHost_.init((HWND)parent, controller_, 600, 650); + if (!ok) { + hasFlutter_ = false; + } + } +#endif + if (!hasFlutter_) { + int count = controller_ ? controller_->getParameterCount() : 0; + int h = (std::max)(280, 74 + count * 56 + 36); + if (!winHost_.init((HWND)parent, controller_, pluginName_, 540, h)) return kResultFalse; + } +#elif defined(__linux__) + glibPump_.setFrame(frame_); +#if defined(FLUTTER_VST3_HAS_FLUTTER) + linuxFlutterHost_.onFailure = [this] { mountNativeLinux(); }; +#endif + if (hasFlutter_) { + bool ok = linuxFlutterHost_.init(parent, controller_, 600, 650); + if (!ok) { + hasFlutter_ = false; + } + } + if (!hasFlutter_) { + int count = controller_ ? controller_->getParameterCount() : 0; + int h = (std::max)(280, 74 + count * 56 + 36); + if (!linuxNativeHost_.init(parent, controller_, pluginName_, 540, h)) return kResultFalse; + } +#endif + return kResultTrue; + } + + tresult PLUGIN_API removed() override { + endControllerEdits(controller_); + cleanup(); + if (viewHolder_ && *viewHolder_ == this) *viewHolder_ = nullptr; + return kResultTrue; + } + + tresult PLUGIN_API getSize(ViewRect* size) override { + if (!size) return kInvalidArgument; + if (size_) { *size = *size_; return kResultTrue; } + int count = controller_ ? controller_->getParameterCount() : 0; + size->left = 0; + size->top = 0; + size->right = hasFlutter_ ? 600 : 540; + size->bottom = hasFlutter_ ? 650 : (std::max)(280, 74 + count * 56 + 36); + return kResultTrue; + } + + tresult PLUGIN_API onSize(ViewRect* r) override { + if (!r || r->getWidth() <= 0 || r->getHeight() <= 0) return kInvalidArgument; + size_ = *r; +#if defined(_WIN32) + if (r) { +#if defined(FLUTTER_VST3_HAS_FLUTTER) + if (hasFlutter_ && winFlutterHost_.flutterHwnd) { + SetWindowPos(winFlutterHost_.flutterHwnd, nullptr, 0, 0, r->getWidth(), r->getHeight(), SWP_NOMOVE | SWP_NOZORDER); + return kResultTrue; + } +#endif + if (winHost_.hwnd) { + SetWindowPos(winHost_.hwnd, nullptr, 0, 0, r->getWidth(), r->getHeight(), SWP_NOMOVE | SWP_NOZORDER); + } + } +#elif defined(__linux__) + if (!r) return kInvalidArgument; + auto* plug = hasFlutter_ ? linuxFlutterHost_.plug : linuxNativeHost_.plug; + if (plug) gtk_widget_set_size_request(plug, r->getWidth(), r->getHeight()); +#endif + return kResultTrue; + } + + tresult PLUGIN_API setFrame(IPlugFrame* frame) override { + frame_ = frame; +#if defined(__linux__) + glibPump_.setFrame(frame); +#endif + return kResultTrue; + } + tresult PLUGIN_API canResize() override { return kResultTrue; } + tresult PLUGIN_API checkSizeConstraint(ViewRect*) override { return kResultTrue; } + tresult PLUGIN_API onWheel(float) override { return kResultFalse; } + tresult PLUGIN_API onKeyDown(char16, int16, int16) override { return kResultFalse; } + tresult PLUGIN_API onKeyUp(char16, int16, int16) override { return kResultFalse; } + tresult PLUGIN_API onFocus(TBool) override { return kResultTrue; } + + REFCOUNT_METHODS(FObject) + + tresult PLUGIN_API queryInterface(const TUID iid, void** obj) override { + QUERY_INTERFACE(iid, obj, IPlugView::iid, IPlugView) + return FObject::queryInterface(iid, obj); + } + +private: +#if defined(_WIN32) && defined(FLUTTER_VST3_HAS_FLUTTER) + void mountNativeWindows() { + hasFlutter_ = false; + size_.reset(); + const int count = controller_ ? controller_->getParameterCount() : 0; + const int height = (std::max)(280, 74 + count * 56 + 36); + if (!winHost_.init((HWND)parentView_, controller_, pluginName_, 540, height)) { + fprintf(stderr, "flutter_vst3: native Windows editor failed after Flutter startup failure.\n"); + return; + } + ViewRect rect(0, 0, 540, height); + if (frame_) frame_->resizeView(this, &rect); + } +#endif +#if defined(__linux__) + void mountNativeLinux() { + hasFlutter_ = false; + size_.reset(); + const int count = controller_ ? controller_->getParameterCount() : 0; + const int height = (std::max)(280, 74 + count * 56 + 36); + if (!linuxNativeHost_.init(parentView_, controller_, pluginName_, 540, height)) return; + ViewRect rect(0, 0, 540, height); + if (frame_) frame_->resizeView(this, &rect); + } +#endif + void cleanup() { +#if defined(_WIN32) +#if defined(FLUTTER_VST3_HAS_FLUTTER) + if (hasFlutter_) { + winFlutterHost_.shutdown(); + } +#endif + winHost_.shutdown(); +#elif defined(__linux__) + glibPump_.stop(); + if (hasFlutter_) { + linuxFlutterHost_.shutdown(); + } + linuxNativeHost_.shutdown(); +#endif + parentView_ = nullptr; + hasFlutter_ = false; + size_.reset(); + } + + std::optional size_; + IPlugFrame* frame_{nullptr}; + EditController* controller_{nullptr}; + std::string pluginName_; + void* parentView_{nullptr}; + IEmbeddedFlutterView** viewHolder_{nullptr}; + bool hasFlutter_{false}; +#if defined(_WIN32) +#if defined(FLUTTER_VST3_HAS_FLUTTER) + WinFlutterHost winFlutterHost_; +#endif + WinNativeEditorHost winHost_; +#elif defined(__linux__) + LinuxGlibPump glibPump_; + LinuxFlutterHost linuxFlutterHost_; + LinuxNativeEditorHost linuxNativeHost_; +#endif +}; + +IPlugView* createEmbeddedFlutterView( + EditController* controller, + const char* pluginName, + IEmbeddedFlutterView** outViewPtr) { + return new EmbeddedFlutterView(controller, pluginName, outViewPtr); +} + +#endif // !__APPLE__ + +} // namespace Steinberg::Vst \ No newline at end of file diff --git a/flutter_vst3/native/src/embedded_flutter_view.mm b/flutter_vst3/native/src/embedded_flutter_view.mm new file mode 100644 index 0000000..ddc2872 --- /dev/null +++ b/flutter_vst3/native/src/embedded_flutter_view.mm @@ -0,0 +1,376 @@ +// Copyright (c) 2025 +// Native embedded view for flutter_vst3 plugins on macOS +// Hosts an in-process Flutter Engine with dynamic fallback to Cocoa UI. + +#import +#import +#import +#include "embedded_flutter_view.h" +#include "view_logic.h" +#include "native_cocoa_view.h" +#include "vst3_shared_memory.h" +#include "base/source/fobject.h" +#include "public.sdk/source/vst/vsteditcontroller.h" +#include +#include +#include +#include + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + +namespace Steinberg::Vst { + +/// Locates the VST3 bundle directory for the current dylib. +static NSString* findPluginBundlePath() { + Dl_info info; + if (!dladdr((const void*)&createEmbeddedFlutterView, &info) || !info.dli_fname) return nil; + auto dylibPath = [NSString stringWithUTF8String:info.dli_fname]; + auto macosDir = [dylibPath stringByDeletingLastPathComponent]; + auto contentsDir = [macosDir stringByDeletingLastPathComponent]; + auto bundleDir = [contentsDir stringByDeletingLastPathComponent]; + return [[bundleDir pathExtension] isEqualToString:@"vst3"] ? bundleDir : contentsDir; +} + +/// Checks if the bundle contains an embedded Flutter App.framework. +static BOOL pluginHasFlutter(NSString* bundlePath) { +#ifndef VST3_FLUTTER_ENTRYPOINT + return NO; +#else + if (!bundlePath) return NO; + auto fm = [NSFileManager defaultManager]; + auto fwDir = [bundlePath stringByAppendingPathComponent:@"Contents/Frameworks"]; + return [fm fileExistsAtPath:[fwDir stringByAppendingPathComponent:@"App.framework/App"]] + && [fm fileExistsAtPath:[fwDir stringByAppendingPathComponent:@"App.framework/Resources/flutter_assets"]] + && [fm fileExistsAtPath:[fwDir stringByAppendingPathComponent:@"FlutterMacOS.framework/Resources/icudtl.dat"]]; +#endif +} + +/// Dynamically loads Flutter and App frameworks from the bundle. +static BOOL loadFlutterFrameworks(NSString* bundlePath, NSBundle** outFlutter, NSBundle** outApp) { + if (!bundlePath) return NO; + auto fm = [NSFileManager defaultManager]; + auto fwDir = [bundlePath stringByAppendingPathComponent:@"Contents/Frameworks"]; + auto flPath = [fwDir stringByAppendingPathComponent:@"FlutterMacOS.framework"]; + auto appPath = [fwDir stringByAppendingPathComponent:@"App.framework"]; + if (![fm fileExistsAtPath:flPath] || ![fm fileExistsAtPath:appPath]) return NO; + *outFlutter = [NSBundle bundleWithPath:flPath]; + *outApp = [NSBundle bundleWithPath:appPath]; + if (!NSClassFromString(@"FlutterViewController")) { + if (![*outFlutter load]) return NO; + } + return YES; +} + +/// The engine crashes the host when the app library is corrupt, so try it first. +static BOOL appLibraryLoads(NSBundle* appBundle) { + void* handle = dlopen(appBundle.executablePath.fileSystemRepresentation, RTLD_LAZY | RTLD_LOCAL); + if (!handle) { + NSLog(@"[flutter_vst3] Flutter app library failed to load: %s", dlerror()); + return NO; + } + dlclose(handle); + return YES; +} + +/// Native macOS IPlugView embedding Flutter or falling back to Cocoa sliders. +class EmbeddedFlutterView : public Steinberg::IPlugView, + public Steinberg::FObject, + public IEmbeddedFlutterView { +public: + EmbeddedFlutterView(EditController* c, const char* name, IEmbeddedFlutterView** holder = nullptr) + : controller_(c), pluginName_(name ? name : "VST3 Plugin"), viewHolder_(holder) { + hasFlutter_ = pluginHasFlutter(findPluginBundlePath()); + if (viewHolder_) *viewHolder_ = this; + } + + ~EmbeddedFlutterView() override { + cleanup(); + if (viewHolder_ && *viewHolder_ == this) *viewHolder_ = nullptr; + } + + void onControllerClosed() override { + cleanup(); + controller_ = nullptr; + if (cocoaDelegate_) cocoaDelegate_.controller = nullptr; + viewHolder_ = nullptr; + } + + tresult PLUGIN_API isPlatformTypeSupported(FIDString type) override { + return (type && strcmp(type, kPlatformTypeNSView) == 0) ? kResultTrue : kResultFalse; + } + + tresult PLUGIN_API attached(void* parent, FIDString type) override { + if (!parent || !type || strcmp(type, kPlatformTypeNSView) != 0) return kInvalidArgument; + parentView_ = parent; + size_.reset(); + hasFlutter_ = !sOwner && pluginHasFlutter(findPluginBundlePath()); + if (hasFlutter_) sOwner = this; + NSView* parentNsView = (__bridge NSView*)parent; + alive_ = std::make_shared>(true); + auto alive = alive_; + dispatch_async(dispatch_get_main_queue(), ^{ + flutter_vst3::withLiveEditor(*alive, [&] { + if (parentView_ == parent) mountView(parentNsView); + }); + }); + return kResultTrue; + } + + tresult PLUGIN_API removed() override { + endControllerEdits(controller_); + cleanup(); + if (viewHolder_ && *viewHolder_ == this) *viewHolder_ = nullptr; + return kResultTrue; + } + + tresult PLUGIN_API getSize(ViewRect* size) override { + if (!size) return kInvalidArgument; + if (size_) { *size = *size_; return kResultTrue; } + size->left = 0; + size->top = 0; + size->right = hasFlutter_ ? 600 : 540; + int count = controller_ ? controller_->getParameterCount() : 0; + size->bottom = hasFlutter_ ? 650 : std::max(280, 74 + count * 56 + 36); + return kResultTrue; + } + + tresult PLUGIN_API onSize(ViewRect* rect) override { + if (!rect || rect->getWidth() <= 0 || rect->getHeight() <= 0) return kInvalidArgument; + size_ = *rect; + NSView* view = flutterViewController_ + ? [flutterViewController_ performSelector:sel_registerName("view")] : cocoaContainerView_; + [view setFrameSize:NSMakeSize(rect->getWidth(), rect->getHeight())]; + return kResultTrue; + } + tresult PLUGIN_API setFrame(IPlugFrame* frame) override { frame_ = frame; return kResultTrue; } + tresult PLUGIN_API canResize() override { return kResultTrue; } + tresult PLUGIN_API checkSizeConstraint(ViewRect*) override { return kResultTrue; } + tresult PLUGIN_API onWheel(float) override { return kResultFalse; } + tresult PLUGIN_API onKeyDown(char16, int16, int16) override { return kResultFalse; } + tresult PLUGIN_API onKeyUp(char16, int16, int16) override { return kResultFalse; } + tresult PLUGIN_API onFocus(TBool) override { return kResultTrue; } + + void updateParameter(ParamID paramId, ParamValue value) override { + auto alive = alive_; + id flChannel = flutterChannel_; + if (flChannel) { + dispatch_async(dispatch_get_main_queue(), ^{ + flutter_vst3::withLiveEditor(*alive, [&] { + NSDictionary* args = @{@"id": @(paramId), @"value": @(value)}; + [flChannel performSelector:sel_registerName("invokeMethod:arguments:") + withObject:@"onParameterChanged" withObject:args]; + }); + }); + } else if (cocoaDelegate_) { + auto del = cocoaDelegate_; + dispatch_async(dispatch_get_main_queue(), ^{ + flutter_vst3::withLiveEditor(*alive, [&] { + [del updateParamId:paramId withValue:value]; + }); + }); + } + } + + REFCOUNT_METHODS(Steinberg::FObject) + + tresult PLUGIN_API queryInterface(const TUID iid, void** obj) override { + QUERY_INTERFACE(iid, obj, Steinberg::IPlugView::iid, Steinberg::IPlugView) + return Steinberg::FObject::queryInterface(iid, obj); + } + +private: + void cleanup() { + alive_->store(false); + if (cocoaDelegate_) cocoaDelegate_.controller = nullptr; + teardownFlutterView(); + if (cocoaContainerView_) { + [cocoaContainerView_ removeFromSuperview]; + cocoaContainerView_ = nil; + cocoaDelegate_ = nil; + } + if (sOwner == this) sOwner = nullptr; + hasFlutter_ = NO; + size_.reset(); + parentView_ = nullptr; + } + + void mountView(NSView* parent) { + BOOL mounted = NO; + if (hasFlutter_) { + @try { + mounted = tryMountFlutter(parent); + } @catch (NSException* e) { + NSLog(@"[flutter_vst3] Flutter UI mount exception: %@. Falling back to Cocoa.", e); + mounted = NO; + } + } + if (!mounted) { + hasFlutter_ = NO; + size_.reset(); + if (sOwner == this) sOwner = nullptr; + Vst3PluginEditorDelegate* del = nil; + cocoaContainerView_ = createCocoaFallbackView(parent, controller_, pluginName_, &del); + cocoaDelegate_ = del; + [parent addSubview:cocoaContainerView_]; + } + } + + /// Removes the Flutter channel, subview and engine; a no-op when the + /// Flutter editor never mounted. + void teardownFlutterView() { + if (flutterChannel_) { + [flutterChannel_ performSelector:sel_registerName("setMethodCallHandler:") withObject:nil]; + flutterChannel_ = nil; + } + NSView* v = flutterViewController_ ? [flutterViewController_ performSelector:sel_registerName("view")] : nil; + [v removeFromSuperview]; + flutterViewController_ = nil; + if (flutterEngine_) { + ((void (*)(id, SEL))objc_msgSend)(flutterEngine_, sel_registerName("shutDownEngine")); + flutterEngine_ = nil; + } + } + + BOOL tryMountFlutter(NSView* parent) { + NSBundle *flBundle = nil, *appBundle = nil; + if (!loadFlutterFrameworks(findPluginBundlePath(), &flBundle, &appBundle)) return NO; + if (!appLibraryLoads(appBundle)) return NO; + Class projCls = NSClassFromString(@"FlutterDartProject"); + Class vcCls = NSClassFromString(@"FlutterViewController"); + Class engineCls = NSClassFromString(@"FlutterEngine"); + if (!projCls || !vcCls || !engineCls) return NO; + + id proj = [[projCls alloc] performSelector:sel_registerName("initWithPrecompiledDartBundle:") withObject:appBundle]; + if (!createFlutterStack(engineCls, vcCls, proj)) { + NSLog(@"[flutter_vst3] FlutterEngine failed to launch (e.g. Dart SDK hash mismatch). Falling back to Cocoa."); + teardownFlutterView(); + return NO; + } + + setupMethodChannel(); + return embedFlutterView(parent); + } + + /// Builds the engine and its view controller, then runs the plugin's + /// declared entrypoint; the controller's implicit engine would run Dart's + /// default main. [EDITOR-ENTRYPOINT] + BOOL createFlutterStack(Class engineCls, Class vcCls, id proj) { + SEL engineInit = sel_registerName("initWithName:project:allowHeadlessExecution:"); + flutterEngine_ = ((id (*)(id, SEL, id, id, BOOL))objc_msgSend)([engineCls alloc], engineInit, @"flutter_vst3", proj, NO); + return wrapEngineInViewController(vcCls) && runEngineWithEntrypoint(); + } + + BOOL runEngineWithEntrypoint() { +#ifndef VST3_FLUTTER_ENTRYPOINT + return NO; +#else + return ((BOOL (*)(id, SEL, id))objc_msgSend)( + flutterEngine_, sel_registerName("runWithEntrypoint:"), @VST3_FLUTTER_ENTRYPOINT); +#endif + } + + BOOL wrapEngineInViewController(Class vcCls) { + SEL init = sel_registerName("initWithEngine:nibName:bundle:"); + flutterViewController_ = ((id (*)(id, SEL, id, id, id))objc_msgSend)([vcCls alloc], init, flutterEngine_, nil, nil); + return flutterViewController_ != nil; + } + + BOOL embedFlutterView(NSView* parent) { + NSView* fv = [flutterViewController_ performSelector:sel_registerName("view")]; + NSRect b = parent.bounds; + if (b.size.width <= 0 || b.size.height <= 0) b = NSMakeRect(0, 0, 600, 650); + [fv setFrame:b]; + [fv setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; + [parent addSubview:fv]; + return YES; + } + + void setupMethodChannel() { + id messenger = [flutterEngine_ performSelector:sel_registerName("binaryMessenger")]; + Class chanCls = NSClassFromString(@"FlutterMethodChannel"); + flutterChannel_ = [chanCls performSelector:sel_registerName("methodChannelWithName:binaryMessenger:") + withObject:@"flutter_vst3/parameters" + withObject:messenger]; + auto alive = alive_; + id flHandler = ^(id call, void (^result)(id)) { + if (!alive->load()) { result(nil); return; } + handleMethodCall(call, result, controller_); + }; + [flutterChannel_ performSelector:sel_registerName("setMethodCallHandler:") withObject:flHandler]; + } + + static void handleSetParameter(NSDictionary* args, EditController* ctrl, void (^result)(id)) { + int pid = [args[@"id"] intValue]; + double val = [args[@"value"] doubleValue]; + applyUiEdit(ctrl, static_cast(pid), val); + result(@(YES)); + } + + static void handleGetInitialParameters(EditController* ctrl, void (^result)(id)) { + NSMutableDictionary* dict = [NSMutableDictionary dictionary]; + if (ctrl) { + int count = ctrl->getParameterCount(); + for (int i = 0; i < count; ++i) { + ParameterInfo info; + if (ctrl->getParameterInfo(i, info) == kResultTrue) { + dict[@(info.id)] = @(ctrl->getParamNormalized(info.id)); + } + } + } + result(dict); + } + + static void handleGetSharedMemoryInfo(EditController* ctrl, void (^result)(id)) { + uintptr_t addr = controllerShmAddress(ctrl); + result(@{ + @"address": @(addr), + @"totalSize": @(VST3_SHM_TOTAL_SIZE), + @"maxSamples": @(VST3_SHM_MAX_SAMPLES) + }); + } + + static void handleMethodCall(id call, void (^result)(id), EditController* ctrl) { + NSString* method = [call performSelector:sel_registerName("method")]; + id arguments = [call performSelector:sel_registerName("arguments")]; + if (([method isEqualToString:@"beginEdit"] || [method isEqualToString:@"endEdit"]) && ctrl) { + const auto pid = [arguments[@"id"] unsignedIntValue]; + [method isEqualToString:@"beginEdit"] ? ctrl->beginEdit(pid) : ctrl->endEdit(pid); + result(@(YES)); + } else if ([method isEqualToString:@"setParameter"] && ctrl) { + handleSetParameter((NSDictionary*)arguments, ctrl, result); + } else if ([method isEqualToString:@"getInitialParameters"] && ctrl) { + handleGetInitialParameters(ctrl, result); + } else if ([method isEqualToString:@"getSharedMemoryInfo"]) { + handleGetSharedMemoryInfo(ctrl, result); + } else { + result(nil); + } + } + + std::shared_ptr> alive_{std::make_shared>(true)}; + std::optional size_; + EditController* controller_{nullptr}; + std::string pluginName_; + void* parentView_{nullptr}; + IPlugFrame* frame_{nullptr}; + IEmbeddedFlutterView** viewHolder_{nullptr}; + static inline EmbeddedFlutterView* sOwner{nullptr}; + BOOL hasFlutter_{NO}; + id flutterViewController_{nil}; + id flutterEngine_{nil}; + id flutterChannel_{nil}; + NSView* cocoaContainerView_{nil}; + Vst3PluginEditorDelegate* cocoaDelegate_{nil}; +}; + +Steinberg::IPlugView* createEmbeddedFlutterView( + EditController* controller, + const char* pluginName, + IEmbeddedFlutterView** outViewPtr) { + return new EmbeddedFlutterView(controller, pluginName, outViewPtr); +} + +} // namespace Steinberg::Vst + +#pragma clang diagnostic pop \ No newline at end of file diff --git a/flutter_vst3/native/src/embedded_flutter_view_linux_flutter.inc b/flutter_vst3/native/src/embedded_flutter_view_linux_flutter.inc new file mode 100644 index 0000000..06fa67a --- /dev/null +++ b/flutter_vst3/native/src/embedded_flutter_view_linux_flutter.inc @@ -0,0 +1,333 @@ + +#if defined(__linux__) && defined(FLUTTER_VST3_HAS_FLUTTER) + + +struct LinuxFlutterHost { + std::function onFailure; + guint watchdog{0}; + static inline bool sUiAlive{false}; + static inline bool sEngineFailed{false}; + GtkWidget* plug{nullptr}; + guint idleSourceId{0}; + void* parentWindow{nullptr}; + int width{600}; + int height{650}; + bool mounted{false}; + EditController* controller{nullptr}; + + static inline GtkWidget* sSharedPlug{nullptr}; + static inline FlView* sSharedView{nullptr}; + static inline FlMethodChannel* sSharedChannel{nullptr}; + static inline Steinberg::Vst::EditController* sActiveController{nullptr}; + + static std::string getModuleDirectory() { + Dl_info info; + if (dladdr(reinterpret_cast(&createEmbeddedFlutterView), &info) && info.dli_fname) { + std::string path(info.dli_fname); + size_t lastSlash = path.find_last_of('/'); + if (lastSlash != std::string::npos) { + return path.substr(0, lastSlash); + } + } + return ""; + } + + static bool checkHasFlutter() { + std::string modDir = getModuleDirectory(); + if (sEngineFailed || modDir.empty()) return false; + std::string assetsDir = modDir + "/data/flutter_assets"; + struct stat st; + return stat(assetsDir.c_str(), &st) == 0 && S_ISDIR(st.st_mode) + && stat((modDir + "/data/icudtl.dat").c_str(), &st) == 0 + && (stat((modDir + "/lib/libapp.so").c_str(), &st) == 0 + || stat((modDir + "/libapp.so").c_str(), &st) == 0 + || stat((assetsDir + "/kernel_blob.bin").c_str(), &st) == 0); + } + + bool init(void* parentX11, Steinberg::Vst::EditController* ctrl, int w, int h) { + if (sActiveController && sActiveController != ctrl) return false; + if (!gdk_display_get_default() && !getenv("GDK_BACKEND")) + gdk_set_allowed_backends("x11"); + if (!gtk_init_check(nullptr, nullptr) || !GDK_IS_X11_DISPLAY(gdk_display_get_default())) return false; + parentWindow = parentX11; + width = w; + height = h; + mounted = false; + controller = ctrl; + sActiveController = ctrl; + + // Post-mount via GLib timeout so it executes on the platform thread + // AFTER the host Dart FFI call (openEditorWindow) has returned to the event loop. + // This avoids Dart VM asserting "CreateIsolate expects there to be no current isolate" + // when the second Flutter engine spins up its isolate. + idleSourceId = g_timeout_add(50, +[](gpointer data) -> gboolean { + auto* self = static_cast(data); + self->idleSourceId = 0; + self->mount(); + return G_SOURCE_REMOVE; + }, this); + return true; + } + + static void onMethodCall(FlMethodChannel* ch, FlMethodCall* methodCall, gpointer userData) { + sUiAlive = true; + const gchar* name = fl_method_call_get_name(methodCall); + FlValue* args = fl_method_call_get_args(methodCall); + auto* ctrl = sActiveController; + + if (g_strcmp0(name, "getInitialParameters") == 0) { + g_autoptr(FlValue) map = fl_value_new_map(); + if (ctrl) { + int count = ctrl->getParameterCount(); + for (int i = 0; i < count; ++i) { + Steinberg::Vst::ParameterInfo info{}; + if (ctrl->getParameterInfo(i, info) == Steinberg::kResultTrue) { + g_autofree gchar* key = g_strdup_printf("%u", info.id); + fl_value_set_string_take( + map, key, + fl_value_new_float(ctrl->getParamNormalized(info.id))); + } + } + } + g_autoptr(FlMethodResponse) resp = FL_METHOD_RESPONSE(fl_method_success_response_new(map)); + fl_method_call_respond(methodCall, resp, nullptr); + } else if (g_strcmp0(name, "beginEdit") == 0 || g_strcmp0(name, "endEdit") == 0) { + FlValue* id = args && fl_value_get_type(args) == FL_VALUE_TYPE_MAP + ? fl_value_lookup_string(args, "id") : nullptr; + if (!ctrl || !id || fl_value_get_type(id) != FL_VALUE_TYPE_INT) { + fl_method_call_respond_error(methodCall, "INVALID_ARGUMENTS", "Expected parameter id", nullptr, nullptr); + return; + } + const auto pid = static_cast(fl_value_get_int(id)); + g_strcmp0(name, "beginEdit") == 0 ? ctrl->beginEdit(pid) : ctrl->endEdit(pid); + fl_method_call_respond_success(methodCall, nullptr, nullptr); + } else if (g_strcmp0(name, "setParameter") == 0) { + if (ctrl && args && fl_value_get_type(args) == FL_VALUE_TYPE_MAP) { + FlValue* idVal = fl_value_lookup_string(args, "id"); + FlValue* valVal = fl_value_lookup_string(args, "value"); + if (idVal && valVal) { + int64_t pid = (fl_value_get_type(idVal) == FL_VALUE_TYPE_INT) + ? fl_value_get_int(idVal) + : static_cast(fl_value_get_float(idVal)); + double val = (fl_value_get_type(valVal) == FL_VALUE_TYPE_FLOAT) + ? fl_value_get_float(valVal) + : static_cast(fl_value_get_int(valVal)); + applyUiEdit(ctrl, static_cast(pid), val); + } + } + g_autoptr(FlValue) ret = fl_value_new_bool(TRUE); + g_autoptr(FlMethodResponse) resp = FL_METHOD_RESPONSE(fl_method_success_response_new(ret)); + fl_method_call_respond(methodCall, resp, nullptr); + } else if (g_strcmp0(name, "getSharedMemoryInfo") == 0) { + g_autoptr(FlValue) map = fl_value_new_map(); + uintptr_t addr = controllerShmAddress(ctrl); + fl_value_set_string_take(map, "address", fl_value_new_int(static_cast(addr))); + fl_value_set_string_take(map, "totalSize", fl_value_new_int(static_cast(VST3_SHM_TOTAL_SIZE))); + fl_value_set_string_take(map, "maxSamples", fl_value_new_int(static_cast(VST3_SHM_MAX_SAMPLES))); + g_autoptr(FlMethodResponse) resp = FL_METHOD_RESPONSE(fl_method_success_response_new(map)); + fl_method_call_respond(methodCall, resp, nullptr); + } else { + g_autoptr(FlMethodResponse) resp = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); + fl_method_call_respond(methodCall, resp, nullptr); + } + } + + void mount() { + if (!flutter_vst3::ownsEditor(sActiveController, controller) || mounted || !parentWindow) return; + mounted = true; + + Display* xdpy = gdk_x11_get_default_xdisplay(); + + if (!sSharedPlug) { + sSharedPlug = gtk_plug_new((Window)(uintptr_t)parentWindow); + if (!sSharedPlug) { + fprintf(stderr, "flutter_vst3: gtk_plug_new failed. VST3 GUI embedding on Linux requires an X11 backend (GDK_BACKEND=x11).\n"); + fail(); + return; + } + g_object_ref_sink(sSharedPlug); + g_signal_connect(sSharedPlug, "delete-event", G_CALLBACK(+[](GtkWidget*, GdkEvent*, gpointer) -> gboolean { + return TRUE; + }), nullptr); + gtk_widget_set_size_request(sSharedPlug, width, height); + gtk_widget_realize(sSharedPlug); + gtk_widget_show(sSharedPlug); + + gdk_gl_context_clear_current(); + + std::string modDir = getModuleDirectory(); + std::string assetsPath = modDir + "/data/flutter_assets"; + std::string icuPath = modDir + "/data/icudtl.dat"; + + FlDartProject* proj = fl_dart_project_new(); + fl_dart_project_set_assets_path(proj, const_cast(assetsPath.c_str())); + fl_dart_project_set_icu_data_path(proj, const_cast(icuPath.c_str())); + + std::string aotPath = modDir + "/lib/libapp.so"; + struct stat aotSt; + if (stat(aotPath.c_str(), &aotSt) != 0) { + aotPath = modDir + "/libapp.so"; + } + if (stat(aotPath.c_str(), &aotSt) == 0) { + fl_dart_project_set_aot_library_path(proj, aotPath.c_str()); + } + + watchdog = g_timeout_add(flutter_vst3::kFlutterStartTimeoutMs, +[](gpointer data) -> gboolean { + auto* self = static_cast(data); + self->watchdog = 0; + if (flutter_vst3::flutterStartFailed(sUiAlive, sEngineFailed, sActiveController != nullptr)) self->fail(); + return G_SOURCE_REMOVE; + }, this); + sSharedView = fl_view_new(proj); + g_object_unref(proj); + if (!sSharedView) { fail(); return; } + g_object_ref_sink(sSharedView); + + FlEngine* engine = fl_view_get_engine(sSharedView); + FlBinaryMessenger* messenger = fl_engine_get_binary_messenger(engine); + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + sSharedChannel = fl_method_channel_new(messenger, "flutter_vst3/parameters", FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler(sSharedChannel, onMethodCall, nullptr, nullptr); + + gtk_container_add(GTK_CONTAINER(sSharedPlug), GTK_WIDGET(sSharedView)); + } else { + // Re-embed existing persistent plug into the new parentWindow if different + GdkWindow* plugWin = gtk_widget_get_window(sSharedPlug); + if (plugWin && xdpy) { + Window plugXid = gdk_x11_window_get_xid(plugWin); + if (plugXid) { + Window currentParent = 0; + Window rootRet = 0; + Window* childrenRet = nullptr; + unsigned int nchildrenRet = 0; + if (XQueryTree(xdpy, plugXid, &rootRet, ¤tParent, &childrenRet, &nchildrenRet)) { + if (childrenRet) XFree(childrenRet); + } + if (currentParent != (Window)(uintptr_t)parentWindow) { + auto* parent = gdk_x11_window_foreign_new_for_display( + gdk_display_get_default(), (Window)(uintptr_t)parentWindow); + if (!parent) { fail(); return; } + gdk_window_reparent(plugWin, parent, 0, 0); + g_object_unref(parent); + } + XResizeWindow(xdpy, plugXid, width, height); + } + } + } + + plug = sSharedPlug; + gtk_widget_set_size_request(plug, width, height); + gtk_widget_show_all(plug); + + GdkWindow* plugWin = gtk_widget_get_window(plug); + if (plugWin) { + gdk_window_show(plugWin); + Window plugXid = gdk_x11_window_get_xid(plugWin); + if (xdpy && plugXid) { + XMapRaised(xdpy, plugXid); + XFlush(xdpy); + } + } + + // On reopen, synchronize parameters and notify Flutter UI that host is attached + if (sSharedChannel) { + fl_method_channel_invoke_method(sSharedChannel, "onHostAttached", nullptr, nullptr, nullptr, nullptr); + if (sActiveController) { + int count = sActiveController->getParameterCount(); + for (int i = 0; i < count; ++i) { + Steinberg::Vst::ParameterInfo info{}; + if (sActiveController->getParameterInfo(i, info) == Steinberg::kResultTrue) { + updateParam(info.id, sActiveController->getParamNormalized(info.id)); + } + } + } + } + } + + void updateParam(Steinberg::Vst::ParamID pid, Steinberg::Vst::ParamValue val) { + if (!flutter_vst3::ownsEditor(sActiveController, controller) || !sSharedChannel) return; + g_autoptr(FlValue) args = fl_value_new_map(); + fl_value_set_string_take(args, "id", fl_value_new_int(static_cast(pid))); + fl_value_set_string_take(args, "value", fl_value_new_float(static_cast(val))); + fl_method_channel_invoke_method(sSharedChannel, "onParameterChanged", args, nullptr, nullptr, nullptr); + } + + void fail() { + if (watchdog) { g_source_remove(watchdog); watchdog = 0; } + sEngineFailed = true; + g_clear_object(&sSharedChannel); + if (sSharedPlug) gtk_widget_destroy(sSharedPlug); + g_clear_object(&sSharedView); + g_clear_object(&sSharedPlug); + plug = nullptr; + sActiveController = nullptr; + mounted = false; + if (onFailure) onFailure(); + } + + static GtkWidget* findEventBox(GtkWidget* widget) { + if (GTK_IS_EVENT_BOX(widget)) return widget; + if (!GTK_IS_CONTAINER(widget)) return nullptr; + GtkWidget* found = nullptr; + GList* children = gtk_container_get_children(GTK_CONTAINER(widget)); + for (GList* child = children; child && !found; child = child->next) { + found = findEventBox(GTK_WIDGET(child->data)); + } + g_list_free(children); + return found; + } + + /// Ends Flutter's drag before its window hides. Its embedder would otherwise + /// wait for a release that goes elsewhere, and ignore the next press. + static void releasePointer() { + GtkWidget* box = findEventBox(sSharedPlug); + GdkWindow* window = box ? gtk_widget_get_window(box) : nullptr; + if (!window) return; + GdkEvent* event = gdk_event_new(GDK_BUTTON_RELEASE); + event->button.window = GDK_WINDOW(g_object_ref(window)); + event->button.send_event = TRUE; + event->button.time = GDK_CURRENT_TIME; + event->button.button = 1; + event->button.state = GDK_BUTTON1_MASK; + gdk_event_set_device(event, gdk_seat_get_pointer(gdk_display_get_default_seat(gdk_window_get_display(window)))); + gtk_widget_event(box, event); + gdk_event_free(event); + } + + void shutdown() { + if (watchdog) { g_source_remove(watchdog); watchdog = 0; } + if (idleSourceId != 0) { + g_source_remove(idleSourceId); + idleSourceId = 0; + } + if (!flutter_vst3::ownsEditor(sActiveController, controller)) return; + if (sSharedChannel) { + fl_method_channel_invoke_method(sSharedChannel, "onHostDetached", nullptr, nullptr, nullptr, nullptr); + } + if (sSharedPlug) { + releasePointer(); + gtk_widget_hide(sSharedPlug); + auto* window = gtk_widget_get_window(sSharedPlug); + auto* display = gdk_x11_get_default_xdisplay(); + if (window && display) { + gdk_window_reparent(window, gdk_get_default_root_window(), 0, 0); + XSync(display, False); + while (gtk_events_pending()) gtk_main_iteration_do(FALSE); + } + } + gdk_gl_context_clear_current(); + plug = nullptr; + sActiveController = nullptr; + mounted = false; + parentWindow = nullptr; + } +}; +#else +struct LinuxFlutterHost { + GtkWidget* plug{nullptr}; + static bool checkHasFlutter() { return false; } + bool init(void*, Steinberg::Vst::EditController*, int, int) { return false; } + void updateParam(Steinberg::Vst::ParamID, Steinberg::Vst::ParamValue) {} + void shutdown() {} +}; +#endif diff --git a/flutter_vst3/native/src/embedded_flutter_view_linux_native.inc b/flutter_vst3/native/src/embedded_flutter_view_linux_native.inc new file mode 100644 index 0000000..798d5b9 --- /dev/null +++ b/flutter_vst3/native/src/embedded_flutter_view_linux_native.inc @@ -0,0 +1,254 @@ + +struct LinuxNativeParamRow { + Steinberg::Vst::ParamID id{0}; + GtkWidget* valLabel{nullptr}; + GtkWidget* scale{nullptr}; + GtkAdjustment* adj{nullptr}; +}; + +class LinuxNativeEditorHost { +public: + GtkWidget* plug{nullptr}; + GtkWidget* mainBox{nullptr}; + GtkCssProvider* cssProvider{nullptr}; + Steinberg::Vst::EditController* controller{nullptr}; + std::string pluginName; + std::vector rows; + bool inScroll{false}; + guint idleSourceId{0}; + void* parentWindow{nullptr}; + int width{540}; + int height{400}; + + bool init(void* parentX11, Steinberg::Vst::EditController* ctrl, const std::string& name, int w, int h) { + if (!gdk_display_get_default() && !getenv("GDK_BACKEND")) + gdk_set_allowed_backends("x11"); + if (!gtk_init_check(nullptr, nullptr) || !GDK_IS_X11_DISPLAY(gdk_display_get_default())) return false; + parentWindow = parentX11; + controller = ctrl; + pluginName = name; + width = w; + height = h; + + mount(); + return plug != nullptr; + } + + void mount() { + if (!parentWindow) return; + plug = gtk_plug_new((Window)(uintptr_t)parentWindow); + if (!plug) { + fprintf(stderr, "flutter_vst3: gtk_plug_new failed. VST3 GUI embedding on Linux requires an X11 backend (GDK_BACKEND=x11).\n"); + return; + } + + gtk_widget_set_size_request(plug, width, height); + gtk_style_context_add_class(gtk_widget_get_style_context(plug), "vst3-native-editor"); + + if (!cssProvider) { + cssProvider = gtk_css_provider_new(); + const char* css = + ".vst3-native-editor, .vst3-native-editor box { background-color: #17171c; color: #e6e6eb; }" + ".vst3-native-editor label.plugin-title { font-size: 16pt; font-weight: bold; color: #ffffff; }" + ".vst3-native-editor label.plugin-sub { font-size: 10pt; color: #888899; }" + ".vst3-native-editor label.param-name { font-size: 11pt; font-weight: 600; color: #e6e6eb; }" + ".vst3-native-editor label.param-val { font-size: 11pt; font-weight: bold; color: #40c0ff; font-family: monospace; }" + ".vst3-native-editor label.footer { font-size: 9pt; color: #666677; }" + ".vst3-native-editor scale contents trough { min-height: 4px; background-color: #2d2d37; border-radius: 2px; }" + ".vst3-native-editor scale contents trough highlight { background-color: #40c0ff; border-radius: 2px; }" + ".vst3-native-editor scale contents trough slider { min-width: 16px; min-height: 16px; margin: -6px; border-radius: 8px; background-color: #ffffff; }"; + gtk_css_provider_load_from_data(cssProvider, css, -1, nullptr); + gtk_style_context_add_provider_for_screen( + gdk_screen_get_default(), + GTK_STYLE_PROVIDER(cssProvider), + GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); + } + + mainBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); + gtk_style_context_add_class(gtk_widget_get_style_context(mainBox), "vst3-native-editor"); + gtk_widget_set_margin_start(mainBox, 24); + gtk_widget_set_margin_end(mainBox, 24); + gtk_widget_set_margin_top(mainBox, 16); + gtk_widget_set_margin_bottom(mainBox, 16); + + // Title + GtkWidget* titleLbl = gtk_label_new(pluginName.empty() ? "VST3 Plugin" : pluginName.c_str()); + gtk_widget_set_halign(titleLbl, GTK_ALIGN_START); + gtk_style_context_add_class(gtk_widget_get_style_context(titleLbl), "plugin-title"); + gtk_box_pack_start(GTK_BOX(mainBox), titleLbl, FALSE, FALSE, 0); + + // Subtitle + GtkWidget* subLbl = gtk_label_new("flutter_vst3 \u2022 Pure Dart DSP & UI"); + gtk_widget_set_halign(subLbl, GTK_ALIGN_START); + gtk_style_context_add_class(gtk_widget_get_style_context(subLbl), "plugin-sub"); + gtk_box_pack_start(GTK_BOX(mainBox), subLbl, FALSE, FALSE, 0); + + // Separator + GtkWidget* sep = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL); + gtk_box_pack_start(GTK_BOX(mainBox), sep, FALSE, FALSE, 6); + + // Parameter rows + rows.clear(); + if (controller) { + int count = controller->getParameterCount(); + for (int i = 0; i < count; ++i) { + Steinberg::Vst::ParameterInfo info{}; + if (controller->getParameterInfo(i, info) != Steinberg::kResultTrue) continue; + + LinuxNativeParamRow row; + row.id = info.id; + + char asciiTitle[128] = {0}; + Steinberg::UString128(info.title).toAscii(asciiTitle, sizeof(asciiTitle)); + + GtkWidget* rowBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 4); + + GtkWidget* headerBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + GtkWidget* nameLbl = gtk_label_new(asciiTitle[0] != '\0' ? asciiTitle : "Param"); + gtk_widget_set_halign(nameLbl, GTK_ALIGN_START); + gtk_style_context_add_class(gtk_widget_get_style_context(nameLbl), "param-name"); + gtk_box_pack_start(GTK_BOX(headerBox), nameLbl, TRUE, TRUE, 0); + + row.valLabel = gtk_label_new(""); + gtk_widget_set_halign(row.valLabel, GTK_ALIGN_END); + gtk_style_context_add_class(gtk_widget_get_style_context(row.valLabel), "param-val"); + gtk_box_pack_start(GTK_BOX(headerBox), row.valLabel, FALSE, FALSE, 0); + + gtk_box_pack_start(GTK_BOX(rowBox), headerBox, FALSE, FALSE, 0); + + double currentVal = controller->getParamNormalized(info.id); + row.adj = gtk_adjustment_new(currentVal, 0.0, 1.0, 0.001, 0.01, 0.0); + row.scale = gtk_scale_new(GTK_ORIENTATION_HORIZONTAL, row.adj); + gtk_scale_set_draw_value(GTK_SCALE(row.scale), FALSE); + gtk_box_pack_start(GTK_BOX(rowBox), row.scale, FALSE, FALSE, 0); + + struct CallbackData { + LinuxNativeEditorHost* self; + Steinberg::Vst::ParamID paramId; + size_t rowIndex; + bool editing{false}; + }; + auto* cbData = new CallbackData{this, info.id, rows.size()}; + g_object_set_data_full(G_OBJECT(row.scale), "gesture-data", cbData, + +[](gpointer user_data) { + auto* data = static_cast(user_data); + if (data->editing && data->self->controller) + data->self->controller->endEdit(data->paramId); + delete data; + }); + const auto begin = +[](GtkWidget*, GdkEvent*, gpointer user_data) -> gboolean { + auto* data = static_cast(user_data); + if (!data->editing && data->self->controller) { + data->editing = true; + data->self->controller->beginEdit(data->paramId); + } + return FALSE; + }; + const auto end = +[](GtkWidget*, GdkEvent*, gpointer user_data) -> gboolean { + auto* data = static_cast(user_data); + if (data->editing && data->self->controller) { + data->self->controller->endEdit(data->paramId); + data->editing = false; + } + return FALSE; + }; + g_signal_connect(row.scale, "button-press-event", G_CALLBACK(begin), cbData); + g_signal_connect(row.scale, "key-press-event", G_CALLBACK(begin), cbData); + g_signal_connect_after(row.scale, "button-release-event", G_CALLBACK(end), cbData); + g_signal_connect_after(row.scale, "key-release-event", G_CALLBACK(end), cbData); + g_signal_connect_data(row.adj, "value-changed", + G_CALLBACK(+[](GtkAdjustment* adj, gpointer user_data) { + auto* data = static_cast(user_data); + if (data->self->inScroll || !data->self->controller) return; + data->self->inScroll = true; + double val = gtk_adjustment_get_value(adj); + if (!data->editing) data->self->controller->beginEdit(data->paramId); + data->self->controller->setParamNormalized(data->paramId, val); + data->self->controller->performEdit(data->paramId, val); + if (!data->editing) data->self->controller->endEdit(data->paramId); + data->self->updateValueLabel(data->self->rows[data->rowIndex], val); + data->self->inScroll = false; + }), + cbData, + nullptr, + G_CONNECT_AFTER); + + updateValueLabel(row, currentVal); + gtk_box_pack_start(GTK_BOX(mainBox), rowBox, FALSE, FALSE, 4); + rows.push_back(row); + } + + // Footer + GtkWidget* footer = gtk_label_new("Shared Memory DSP"); + gtk_widget_set_halign(footer, GTK_ALIGN_CENTER); + gtk_style_context_add_class(gtk_widget_get_style_context(footer), "footer"); + gtk_box_pack_start(GTK_BOX(mainBox), footer, FALSE, FALSE, 8); + } + + gtk_container_add(GTK_CONTAINER(plug), mainBox); + gtk_widget_show_all(plug); + + GdkWindow* plugWin = gtk_widget_get_window(plug); + if (plugWin) { + gdk_window_show(plugWin); + Window plugXid = gdk_x11_window_get_xid(plugWin); + Display* xdpy = gdk_x11_get_default_xdisplay(); + if (xdpy && plugXid) { + XMapRaised(xdpy, plugXid); + XFlush(xdpy); + } + } + } + + void updateValueLabel(LinuxNativeParamRow& row, double val) { + if (!row.valLabel) return; + char buf[128]; + if (controller) { + Steinberg::Vst::String128 str128; + if (controller->getParamStringByValue(row.id, val, str128) == Steinberg::kResultTrue) { + Steinberg::UString128(str128).toAscii(buf, sizeof(buf)); + gtk_label_set_text(GTK_LABEL(row.valLabel), buf); + return; + } + } + snprintf(buf, sizeof(buf), "%.2f", val); + gtk_label_set_text(GTK_LABEL(row.valLabel), buf); + } + + void updateParam(Steinberg::Vst::ParamID paramId, Steinberg::Vst::ParamValue val) { + if (inScroll) return; + for (auto& r : rows) { + if (r.id == paramId) { + inScroll = true; + if (r.adj) { + gtk_adjustment_set_value(r.adj, val); + } + updateValueLabel(r, val); + inScroll = false; + break; + } + } + } + + void shutdown() { + if (idleSourceId != 0) { + g_source_remove(idleSourceId); + idleSourceId = 0; + } + if (cssProvider) { + gtk_style_context_remove_provider_for_screen( + gdk_screen_get_default(), + GTK_STYLE_PROVIDER(cssProvider)); + g_object_unref(cssProvider); + cssProvider = nullptr; + } + if (plug) { + gtk_widget_destroy(plug); + gdk_display_sync(gdk_display_get_default()); + plug = nullptr; + mainBox = nullptr; + } + rows.clear(); + parentWindow = nullptr; + } +}; diff --git a/flutter_vst3/native/src/embedded_flutter_view_linux_run_loop.inc b/flutter_vst3/native/src/embedded_flutter_view_linux_run_loop.inc new file mode 100644 index 0000000..01ee7c6 --- /dev/null +++ b/flutter_vst3/native/src/embedded_flutter_view_linux_run_loop.inc @@ -0,0 +1,31 @@ +/// Bridges GLib sources to the host UI run loop, without a background GTK thread. +class LinuxGlibPump : public Linux::ITimerHandler, public FObject { +public: + ~LinuxGlibPump() override { stop(); } + void setFrame(IPlugFrame* frame) { + stop(); + if (!frame || frame->queryInterface(Linux::IRunLoop::iid, + reinterpret_cast(&loop_)) != kResultTrue) return; + if (loop_->registerTimer(this, 10) != kResultTrue) { + loop_->release(); + loop_ = nullptr; + } + } + void stop() { + if (!loop_) return; + loop_->unregisterTimer(this); + loop_->release(); + loop_ = nullptr; + } + void PLUGIN_API onTimer() override { + for (int i = 0; i < 32 && g_main_context_pending(nullptr); ++i) + g_main_context_iteration(nullptr, FALSE); + } + REFCOUNT_METHODS(FObject) + tresult PLUGIN_API queryInterface(const TUID iid, void** obj) override { + QUERY_INTERFACE(iid, obj, Linux::ITimerHandler::iid, Linux::ITimerHandler) + return FObject::queryInterface(iid, obj); + } +private: + Linux::IRunLoop* loop_{nullptr}; +}; diff --git a/flutter_vst3/native/src/embedded_flutter_view_win_flutter.inc b/flutter_vst3/native/src/embedded_flutter_view_win_flutter.inc new file mode 100644 index 0000000..f990237 --- /dev/null +++ b/flutter_vst3/native/src/embedded_flutter_view_win_flutter.inc @@ -0,0 +1,348 @@ + +#if defined(FLUTTER_VST3_HAS_FLUTTER) +class WinFlutterHost { +public: + std::function onFailure; + UINT_PTR watchdog{0}; + static inline bool sUiAlive{false}; + static inline bool sEngineFailed{false}; + static inline WinFlutterHost* sOwner{nullptr}; + HWND flutterHwnd{nullptr}; + HWND parentHwnd{nullptr}; + EditController* controller{nullptr}; + int width{600}; + int height{650}; + + UINT_PTR pendingTimerId{0}; + std::atomic mounted{false}; + + static inline HWND sSharedFlutterHwnd{nullptr}; + static inline FlutterDesktopViewControllerRef sSharedVc{nullptr}; + static inline FlutterDesktopEngineRef sSharedEngine{nullptr}; + static inline std::unique_ptr sSharedMessenger; + static inline std::unique_ptr> sSharedChannel; + static inline HMODULE sFlDll{nullptr}; + static inline EditController* sActiveController{nullptr}; + + static HWND getHolderHwnd() { + static HWND holder = nullptr; + if (!holder) { + HINSTANCE hInst = editorModule(); + static const auto name = editorClassName(L"FlutterVst3HolderWindow"); + WNDCLASSEXW wc{}; + wc.cbSize = sizeof(WNDCLASSEXW); + wc.lpfnWndProc = DefWindowProcW; + wc.hInstance = hInst; + wc.lpszClassName = name.c_str(); + RegisterClassExW(&wc); + + holder = CreateWindowExW( + 0, name.c_str(), L"FlutterHolder", + WS_POPUP, 0, 0, 0, 0, nullptr, nullptr, hInst, nullptr + ); + } + return holder; + } + + static std::wstring getModuleDirectory() { + HMODULE hModule = nullptr; + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(&createEmbeddedFlutterView), + &hModule); + wchar_t path[MAX_PATH]; + GetModuleFileNameW(hModule, path, MAX_PATH); + std::wstring p(path); + size_t lastSlash = p.find_last_of(L"\\/"); + if (lastSlash != std::wstring::npos) { + return p.substr(0, lastSlash); + } + return L""; + } + + static bool checkHasFlutter() { + std::wstring moduleDir = getModuleDirectory(); + if (sEngineFailed || moduleDir.empty()) return false; + std::wstring assetsPath = moduleDir + L"\\data\\flutter_assets"; + DWORD attr = GetFileAttributesW(assetsPath.c_str()); + return attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY) + && GetFileAttributesW((moduleDir + L"\\data\\icudtl.dat").c_str()) != INVALID_FILE_ATTRIBUTES + && (GetFileAttributesW((moduleDir + L"\\data\\app.so").c_str()) != INVALID_FILE_ATTRIBUTES + || GetFileAttributesW((assetsPath + L"\\kernel_blob.bin").c_str()) != INVALID_FILE_ATTRIBUTES); + } + + bool init(HWND parent, EditController* ctrl, int w, int h) { + if (sActiveController && sActiveController != ctrl) return false; + controller = ctrl; + parentHwnd = parent; + width = w; + height = h; + mounted = false; + + std::wstring moduleDir = getModuleDirectory(); + if (moduleDir.empty()) return false; + + std::wstring dllPath = moduleDir + L"\\flutter_windows.dll"; + std::wstring assetsPath = moduleDir + L"\\data\\flutter_assets"; + DWORD attr = GetFileAttributesW(assetsPath.c_str()); + if (attr == INVALID_FILE_ATTRIBUTES || !(attr & FILE_ATTRIBUTE_DIRECTORY)) { + return false; + } + + if (!sFlDll) { + sFlDll = LoadLibraryExW(dllPath.c_str(), nullptr, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + if (!sFlDll) return false; + } + + // Post-mount via thread timer so it executes on the main platform thread + // AFTER the Dart FFI call (openEditorWindow) has returned to the event loop. + UINT_PTR tid = SetTimer(nullptr, 0, 10, &WinFlutterHost::timerProc); + if (tid == 0) return false; + pendingTimerId = tid; + registerTimer(tid, this); + sActiveController = ctrl; + sOwner = this; + return true; + } + + void mount() { + if (!flutter_vst3::ownsEditor(sActiveController, controller) || mounted.load() || !parentHwnd) return; + mounted = true; + + if (!sSharedVc) { + std::wstring moduleDir = getModuleDirectory(); + std::wstring assetsPath = moduleDir + L"\\data\\flutter_assets"; + std::wstring icuPath = moduleDir + L"\\data\\icudtl.dat"; + + FlutterDesktopEngineProperties props{}; + props.assets_path = assetsPath.c_str(); + props.icu_data_path = icuPath.c_str(); + // Release engines load the app from here. Debug bundles have no app.so. + const std::wstring aotPath = moduleDir + L"\\data\\app.so"; + props.aot_library_path = GetFileAttributesW(aotPath.c_str()) != INVALID_FILE_ATTRIBUTES ? aotPath.c_str() : nullptr; +#ifndef VST3_FLUTTER_ENTRYPOINT +#error VST3_FLUTTER_ENTRYPOINT must name the plugin Dart entrypoint +#endif + props.dart_entrypoint = VST3_FLUTTER_ENTRYPOINT; + props.ui_thread_policy = RunOnPlatformThread; + props.impeller_switch = DisabledImpeller; + + sSharedEngine = FlutterDesktopEngineCreate(&props); + if (!sSharedEngine) { fail(); return; } + watchdog = SetTimer(nullptr, 0, flutter_vst3::kFlutterStartTimeoutMs, + +[](HWND, UINT, UINT_PTR id, DWORD) { + KillTimer(nullptr, id); + if (!sOwner) return; + sOwner->watchdog = 0; + if (flutter_vst3::flutterStartFailed(sUiAlive, sEngineFailed, sActiveController != nullptr)) sOwner->fail(); + }); + if (!watchdog) { fail(); return; } + + setupMethodChannel(); + if (!sSharedChannel) { fail(); return; } + + if (!FlutterDesktopEngineRun(sSharedEngine, VST3_FLUTTER_ENTRYPOINT)) { fail(); return; } + + sSharedVc = FlutterDesktopViewControllerCreate(width, height, sSharedEngine); + if (!sSharedVc) { sSharedEngine = nullptr; fail(); return; } + + FlutterDesktopViewRef view = FlutterDesktopViewControllerGetView(sSharedVc); + if (!view) { fail(); return; } + + sSharedFlutterHwnd = FlutterDesktopViewGetHWND(view); + if (!sSharedFlutterHwnd) { fail(); return; } + + LONG_PTR curStyle = GetWindowLongPtrW(sSharedFlutterHwnd, GWL_STYLE); + curStyle = (curStyle & ~WS_POPUP) | WS_CHILD; + SetWindowLongPtrW(sSharedFlutterHwnd, GWL_STYLE, curStyle); + } + + RECT rc{}; + GetClientRect(parentHwnd, &rc); + int w = rc.right - rc.left; + int h = rc.bottom - rc.top; + if (w <= 0) w = width > 0 ? width : 600; + if (h <= 0) h = height > 0 ? height : 650; + + flutterHwnd = sSharedFlutterHwnd; + SetParent(sSharedFlutterHwnd, parentHwnd); + SetWindowPos(sSharedFlutterHwnd, nullptr, 0, 0, w, h, SWP_NOZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW); + ShowWindow(sSharedFlutterHwnd, SW_SHOW); + UpdateWindow(sSharedFlutterHwnd); + FlutterDesktopViewControllerForceRedraw(sSharedVc); + + // Notify Flutter UI and synchronize parameters (mirroring Linux) + if (sSharedChannel) { + sSharedChannel->InvokeMethod("onHostAttached", nullptr); + if (sActiveController) { + int count = sActiveController->getParameterCount(); + for (int i = 0; i < count; ++i) { + Steinberg::Vst::ParameterInfo info{}; + if (sActiveController->getParameterInfo(i, info) == Steinberg::kResultTrue) { + updateParam(info.id, sActiveController->getParamNormalized(info.id)); + } + } + } + } + } + + void fail() { + if (watchdog) { KillTimer(nullptr, watchdog); watchdog = 0; } + sEngineFailed = true; + sSharedChannel.reset(); + sSharedMessenger.reset(); + if (sSharedVc) FlutterDesktopViewControllerDestroy(sSharedVc); + else if (sSharedEngine) FlutterDesktopEngineDestroy(sSharedEngine); + sSharedVc = nullptr; + sSharedEngine = nullptr; + sSharedFlutterHwnd = flutterHwnd = nullptr; + sActiveController = nullptr; + sOwner = nullptr; + mounted = false; + if (onFailure) onFailure(); + } + + void shutdown() { + if (watchdog) { KillTimer(nullptr, watchdog); watchdog = 0; } + if (pendingTimerId != 0) { + KillTimer(nullptr, pendingTimerId); + unregisterTimer(pendingTimerId); + pendingTimerId = 0; + } + + if (!flutter_vst3::ownsEditor(sActiveController, controller)) return; + if (sSharedChannel) { + sSharedChannel->InvokeMethod("onHostDetached", nullptr); + } + + if (sSharedFlutterHwnd) { + ShowWindow(sSharedFlutterHwnd, SW_HIDE); + SetParent(sSharedFlutterHwnd, getHolderHwnd()); + } + + if (sActiveController == controller) { + sActiveController = nullptr; + } + + sOwner = nullptr; + flutterHwnd = nullptr; + parentHwnd = nullptr; + mounted = false; + } + + void updateParam(Steinberg::Vst::ParamID pid, Steinberg::Vst::ParamValue val) { + if (!flutter_vst3::ownsEditor(sActiveController, controller) || !sSharedChannel) return; + flutter::EncodableMap args; + args[flutter::EncodableValue("id")] = flutter::EncodableValue(static_cast(pid)); + args[flutter::EncodableValue("value")] = flutter::EncodableValue(static_cast(val)); + sSharedChannel->InvokeMethod("onParameterChanged", std::make_unique(args)); + } + +private: + void setupMethodChannel() { + FlutterDesktopMessengerRef messenger = FlutterDesktopEngineGetMessenger(sSharedEngine); + if (!messenger) return; + + sSharedMessenger = std::make_unique(messenger); + sSharedChannel = std::make_unique>( + sSharedMessenger.get(), "flutter_vst3/parameters", + &flutter::StandardMethodCodec::GetInstance()); + + sSharedChannel->SetMethodCallHandler( + [](const flutter::MethodCall& call, + std::unique_ptr> result) { + sUiAlive = true; + auto* ctrl = sActiveController; + if ((call.method_name() == "beginEdit" || call.method_name() == "endEdit") && ctrl) { + const auto* args = std::get_if(call.arguments()); + if (!args || args->count(flutter::EncodableValue("id")) == 0) { + result->Error("INVALID_ARGUMENTS", "Expected parameter id"); + return; + } + const auto& id = args->at(flutter::EncodableValue("id")); + const auto pid = std::holds_alternative(id) + ? std::get(id) : static_cast(std::get(id)); + call.method_name() == "beginEdit" ? ctrl->beginEdit(pid) : ctrl->endEdit(pid); + result->Success(flutter::EncodableValue(true)); + } else if (call.method_name() == "setParameter" && ctrl) { + const auto* args = std::get_if(call.arguments()); + if (!args) { + result->Error("INVALID_ARGUMENTS", "Expected map arguments"); + return; + } + auto idIt = args->find(flutter::EncodableValue("id")); + auto valIt = args->find(flutter::EncodableValue("value")); + if (idIt != args->end() && valIt != args->end()) { + int pid = 0; + if (std::holds_alternative(idIt->second)) { + pid = std::get(idIt->second); + } else if (std::holds_alternative(idIt->second)) { + pid = static_cast(std::get(idIt->second)); + } + double val = 0.0; + if (std::holds_alternative(valIt->second)) { + val = std::get(valIt->second); + } else if (std::holds_alternative(valIt->second)) { + val = static_cast(std::get(valIt->second)); + } else if (std::holds_alternative(valIt->second)) { + val = static_cast(std::get(valIt->second)); + } + applyUiEdit(ctrl, static_cast(pid), val); + result->Success(flutter::EncodableValue(true)); + } else { + result->Error("MISSING_PARAM", "id or value missing"); + } + } else if (call.method_name() == "getInitialParameters") { + flutter::EncodableMap map; + if (ctrl) { + int count = ctrl->getParameterCount(); + for (int i = 0; i < count; ++i) { + Steinberg::Vst::ParameterInfo info{}; + if (ctrl->getParameterInfo(i, info) == Steinberg::kResultTrue) { + map[flutter::EncodableValue(static_cast(info.id))] = + flutter::EncodableValue(ctrl->getParamNormalized(info.id)); + } + } + } + result->Success(flutter::EncodableValue(map)); + } else if (call.method_name() == "getSharedMemoryInfo") { + flutter::EncodableMap map; + uintptr_t addr = controllerShmAddress(ctrl); + map[flutter::EncodableValue("address")] = flutter::EncodableValue(static_cast(addr)); + map[flutter::EncodableValue("totalSize")] = flutter::EncodableValue(static_cast(VST3_SHM_TOTAL_SIZE)); + map[flutter::EncodableValue("maxSamples")] = flutter::EncodableValue(static_cast(VST3_SHM_MAX_SAMPLES)); + result->Success(flutter::EncodableValue(map)); + } else { + result->NotImplemented(); + } + }); + } + + static inline std::unordered_map sPendingTimers; + + static void registerTimer(UINT_PTR id, WinFlutterHost* host) { + sPendingTimers[id] = host; + } + + static void unregisterTimer(UINT_PTR id) { + sPendingTimers.erase(id); + } + + static void CALLBACK timerProc(HWND hwnd, UINT msg, UINT_PTR id, DWORD time) { + KillTimer(nullptr, id); + WinFlutterHost* host = nullptr; + { + auto it = sPendingTimers.find(id); + if (it != sPendingTimers.end()) { + host = it->second; + sPendingTimers.erase(it); + } + } + if (host) { + host->pendingTimerId = 0; + host->mount(); + } + } +}; +#endif // FLUTTER_VST3_HAS_FLUTTER diff --git a/flutter_vst3/native/src/embedded_flutter_view_win_module.inc b/flutter_vst3/native/src/embedded_flutter_view_win_module.inc new file mode 100644 index 0000000..a54176f --- /dev/null +++ b/flutter_vst3/native/src/embedded_flutter_view_win_module.inc @@ -0,0 +1,10 @@ +inline HINSTANCE editorModule() { + HMODULE module = nullptr; + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | + GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(&createEmbeddedFlutterView), &module); + return module; +} +inline std::wstring editorClassName(const wchar_t* role) { + return std::wstring(role) + L"_" + std::to_wstring(reinterpret_cast(editorModule())); +} diff --git a/flutter_vst3/native/src/embedded_flutter_view_win_native.inc b/flutter_vst3/native/src/embedded_flutter_view_win_native.inc new file mode 100644 index 0000000..7ca0ca4 --- /dev/null +++ b/flutter_vst3/native/src/embedded_flutter_view_win_native.inc @@ -0,0 +1,305 @@ + +struct ParamRowControls { + Steinberg::Vst::ParamID id{0}; + HWND nameHwnd{nullptr}; + HWND valHwnd{nullptr}; + HWND trackbarHwnd{nullptr}; + bool editing{false}; +}; + +class WinNativeEditorHost { +public: + HWND hwnd{nullptr}; + EditController* controller{nullptr}; + std::string pluginName; + std::vector rows; + HFONT fontTitle{nullptr}; + HFONT fontSubtitle{nullptr}; + HFONT fontLabel{nullptr}; + HFONT fontValue{nullptr}; + HFONT fontFooter{nullptr}; + HBRUSH bgBrush{nullptr}; + HPEN sepPen{nullptr}; + bool inScroll{false}; + + static const wchar_t* className() { + static const auto name = editorClassName(L"FlutterVst3NativeWin32View"); + return name.c_str(); + } + + static void registerClass(HINSTANCE hInst) { + static bool registered = false; + if (registered) return; + + INITCOMMONCONTROLSEX icex{}; + icex.dwSize = sizeof(icex); + icex.dwICC = ICC_BAR_CLASSES; + InitCommonControlsEx(&icex); + + WNDCLASSEXW wc{}; + wc.cbSize = sizeof(WNDCLASSEXW); + wc.style = CS_HREDRAW | CS_VREDRAW; + wc.lpfnWndProc = &WinNativeEditorHost::wndProc; + wc.hInstance = hInst; + wc.hCursor = LoadCursor(nullptr, IDC_ARROW); + wc.hbrBackground = CreateSolidBrush(RGB(23, 23, 28)); + wc.lpszClassName = className(); + RegisterClassExW(&wc); + registered = true; + } + + bool init(HWND parent, EditController* ctrl, const std::string& name, int w, int h) { + controller = ctrl; + pluginName = name; + HINSTANCE hInst = editorModule(); + if (!hInst) return false; + registerClass(hInst); + + hwnd = CreateWindowExW( + 0, className(), L"", + WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN, + 0, 0, w, h, parent, nullptr, hInst, this + ); + return hwnd != nullptr; + } + + void shutdown() { + for (auto& row : rows) + row.editing = false; + if (hwnd) { + SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0); + DestroyWindow(hwnd); + hwnd = nullptr; + } + rows.clear(); + if (bgBrush) { DeleteObject(bgBrush); bgBrush = nullptr; } + if (sepPen) { DeleteObject(sepPen); sepPen = nullptr; } + if (fontTitle) { DeleteObject(fontTitle); fontTitle = nullptr; } + if (fontSubtitle) { DeleteObject(fontSubtitle); fontSubtitle = nullptr; } + if (fontLabel) { DeleteObject(fontLabel); fontLabel = nullptr; } + if (fontValue) { DeleteObject(fontValue); fontValue = nullptr; } + if (fontFooter) { DeleteObject(fontFooter); fontFooter = nullptr; } + } + + void updateParam(Steinberg::Vst::ParamID pid, Steinberg::Vst::ParamValue val) { + if (!hwnd || inScroll) return; + for (auto& row : rows) { + if (row.id == pid) { + int pos = static_cast(std::round(val * 1000.0)); + SendMessageW(row.trackbarHwnd, TBM_SETPOS, TRUE, pos); + updateValueLabel(row, val); + break; + } + } + } + + void updateValueLabel(const ParamRowControls& row, double val) { + if (!row.valHwnd || !controller) return; + Steinberg::Vst::String128 str{}; + std::wstring text; + if (controller->getParamStringByValue(row.id, val, str) == Steinberg::kResultTrue) { + char ascii[128] = {0}; + Steinberg::UString128(str).toAscii(ascii, sizeof(ascii)); + if (ascii[0] != '\0') { + int needed = MultiByteToWideChar(CP_UTF8, 0, ascii, -1, nullptr, 0); + if (needed > 1) { + text.resize(needed - 1); + MultiByteToWideChar(CP_UTF8, 0, ascii, -1, text.data(), needed); + } + } + } + if (text.empty()) { + wchar_t buf[32]; + swprintf_s(buf, L"%.1f%%", val * 100.0); + text = buf; + } + SetWindowTextW(row.valHwnd, text.c_str()); + } + +private: + static LRESULT CALLBACK wndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { + if (msg == WM_NCCREATE) { + auto* cs = reinterpret_cast(lParam); + SetWindowLongPtrW(hWnd, GWLP_USERDATA, reinterpret_cast(cs->lpCreateParams)); + return DefWindowProcW(hWnd, msg, wParam, lParam); + } + + auto* self = reinterpret_cast(GetWindowLongPtrW(hWnd, GWLP_USERDATA)); + if (!self) return DefWindowProcW(hWnd, msg, wParam, lParam); + + switch (msg) { + case WM_CREATE: { + self->onCreate(hWnd); + return 0; + } + case WM_HSCROLL: { + HWND trackbar = (HWND)lParam; + if (!trackbar || !self->controller) return 0; + for (auto& row : self->rows) { + if (row.trackbarHwnd == trackbar) { + self->inScroll = true; + int pos = (int)SendMessageW(trackbar, TBM_GETPOS, 0, 0); + double normVal = pos / 1000.0; + const auto action = LOWORD(wParam); + if (!row.editing) { + self->controller->beginEdit(row.id); + row.editing = true; + } + if (action != TB_ENDTRACK) { + self->controller->setParamNormalized(row.id, normVal); + self->controller->performEdit(row.id, normVal); + } + if (action == TB_ENDTRACK) { + self->controller->endEdit(row.id); + row.editing = false; + } + self->updateValueLabel(row, normVal); + self->inScroll = false; + break; + } + } + return 0; + } + case WM_CTLCOLORSTATIC: { + HDC hdc = (HDC)wParam; + HWND ctrlHwnd = (HWND)lParam; + SetBkMode(hdc, TRANSPARENT); + bool isVal = false; + for (const auto& r : self->rows) { + if (r.valHwnd == ctrlHwnd) { isVal = true; break; } + } + if (isVal) { + SetTextColor(hdc, RGB(64, 192, 255)); + } else { + SetTextColor(hdc, RGB(230, 230, 235)); + } + return (LRESULT)self->bgBrush; + } + case WM_PAINT: { + PAINTSTRUCT ps; + HDC hdc = BeginPaint(hWnd, &ps); + RECT rc; + GetClientRect(hWnd, &rc); + FillRect(hdc, &rc, self->bgBrush); + + SelectObject(hdc, self->sepPen); + MoveToEx(hdc, 24, 64, nullptr); + LineTo(hdc, rc.right - 24, 64); + + EndPaint(hWnd, &ps); + return 0; + } + case WM_SIZE: { + int newW = LOWORD(lParam); + for (auto& row : self->rows) { + if (row.valHwnd) { + SetWindowPos(row.valHwnd, nullptr, newW - 134, 0, 110, 18, SWP_NOSIZE | SWP_NOZORDER); + } + if (row.trackbarHwnd) { + SetWindowPos(row.trackbarHwnd, nullptr, 24, 0, newW - 48, 24, SWP_NOMOVE | SWP_NOZORDER); + } + } + InvalidateRect(hWnd, nullptr, FALSE); + return 0; + } + } + return DefWindowProcW(hWnd, msg, wParam, lParam); + } + + void onCreate(HWND hWnd) { + bgBrush = CreateSolidBrush(RGB(23, 23, 28)); + sepPen = CreatePen(PS_SOLID, 1, RGB(45, 45, 55)); + + fontTitle = CreateFontW(20, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, DEFAULT_CHARSET, + OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, + DEFAULT_PITCH | FF_DONTCARE, L"Segoe UI"); + fontSubtitle = CreateFontW(13, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, + OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, + DEFAULT_PITCH | FF_DONTCARE, L"Segoe UI"); + fontLabel = CreateFontW(15, 0, 0, 0, FW_SEMIBOLD, FALSE, FALSE, FALSE, DEFAULT_CHARSET, + OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, + DEFAULT_PITCH | FF_DONTCARE, L"Segoe UI"); + fontValue = CreateFontW(14, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE, DEFAULT_CHARSET, + OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, + DEFAULT_PITCH | FF_DONTCARE, L"Consolas"); + fontFooter = CreateFontW(12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET, + OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, + DEFAULT_PITCH | FF_DONTCARE, L"Segoe UI"); + + HINSTANCE hInst = (HINSTANCE)GetWindowLongPtrW(hWnd, GWLP_HINSTANCE); + RECT rc; + GetClientRect(hWnd, &rc); + int w = rc.right - rc.left; + if (w <= 0) w = 540; + + std::wstring widePluginName = L"VST3 Plugin"; + if (!pluginName.empty()) { + int needed = MultiByteToWideChar(CP_UTF8, 0, pluginName.c_str(), -1, nullptr, 0); + if (needed > 1) { + widePluginName.resize(needed - 1); + MultiByteToWideChar(CP_UTF8, 0, pluginName.c_str(), -1, widePluginName.data(), needed); + } + } + HWND hTitle = CreateWindowExW(0, L"STATIC", widePluginName.c_str(), + WS_CHILD | WS_VISIBLE | SS_LEFT, + 24, 14, 350, 24, hWnd, nullptr, hInst, nullptr); + SendMessageW(hTitle, WM_SETFONT, (WPARAM)fontTitle, TRUE); + + HWND hSub = CreateWindowExW(0, L"STATIC", L"flutter_vst3 \u2022 Pure Dart DSP & UI", + WS_CHILD | WS_VISIBLE | SS_LEFT, + 24, 40, 350, 18, hWnd, nullptr, hInst, nullptr); + SendMessageW(hSub, WM_SETFONT, (WPARAM)fontSubtitle, TRUE); + + if (controller) { + int count = controller->getParameterCount(); + int y = 78; + for (int i = 0; i < count; ++i) { + Steinberg::Vst::ParameterInfo info{}; + if (controller->getParameterInfo(i, info) != Steinberg::kResultTrue) continue; + + ParamRowControls row; + row.id = info.id; + + char asciiTitle[128] = {0}; + Steinberg::UString128(info.title).toAscii(asciiTitle, sizeof(asciiTitle)); + std::wstring nameW = L"Param"; + if (asciiTitle[0] != '\0') { + int needed = MultiByteToWideChar(CP_UTF8, 0, asciiTitle, -1, nullptr, 0); + if (needed > 1) { + nameW.resize(needed - 1); + MultiByteToWideChar(CP_UTF8, 0, asciiTitle, -1, nameW.data(), needed); + } + } + row.nameHwnd = CreateWindowExW(0, L"STATIC", nameW.c_str(), + WS_CHILD | WS_VISIBLE | SS_LEFT, + 24, y, w - 160, 18, hWnd, nullptr, hInst, nullptr); + SendMessageW(row.nameHwnd, WM_SETFONT, (WPARAM)fontLabel, TRUE); + + row.valHwnd = CreateWindowExW(0, L"STATIC", L"", + WS_CHILD | WS_VISIBLE | SS_RIGHT, + w - 134, y, 110, 18, hWnd, nullptr, hInst, nullptr); + SendMessageW(row.valHwnd, WM_SETFONT, (WPARAM)fontValue, TRUE); + + double currentVal = controller->getParamNormalized(info.id); + int initPos = static_cast(std::round(currentVal * 1000.0)); + row.trackbarHwnd = CreateWindowExW(0, TRACKBAR_CLASSW, L"", + WS_CHILD | WS_VISIBLE | TBS_HORZ | TBS_NOTICKS, + 24, y + 22, w - 48, 24, hWnd, + (HMENU)(UINT_PTR)(10000 + i), hInst, nullptr); + SendMessageW(row.trackbarHwnd, TBM_SETRANGEMIN, FALSE, 0); + SendMessageW(row.trackbarHwnd, TBM_SETRANGEMAX, FALSE, 1000); + SendMessageW(row.trackbarHwnd, TBM_SETPOS, TRUE, initPos); + + updateValueLabel(row, currentVal); + rows.push_back(row); + + y += 56; + } + + HWND hFooter = CreateWindowExW(0, L"STATIC", L"Shared Memory DSP", + WS_CHILD | WS_VISIBLE | SS_CENTER, + 24, y + 10, w - 48, 16, hWnd, nullptr, hInst, nullptr); + SendMessageW(hFooter, WM_SETFONT, (WPARAM)fontFooter, TRUE); + } + } +}; diff --git a/flutter_vst3/native/src/factory.cpp b/flutter_vst3/native/src/factory.cpp deleted file mode 100644 index b3c8753..0000000 --- a/flutter_vst3/native/src/factory.cpp +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2025 -// -// Factory implementation for the Dart VST host plug‑in. Registers -// processor and controller classes with Steinberg’s module factory. - -#include "plugin_ids.h" -#include "public.sdk/source/main/pluginfactory.h" -#include "pluginterfaces/vst/ivstaudioprocessor.h" -#include "pluginterfaces/vst/ivsteditcontroller.h" - -#define FULL_VERSION_STR "1.0.0" - -using namespace Steinberg; - -extern FUnknown* createDvhProcessor(void*); -extern FUnknown* createDvhController(void*); - -bool InitModule() { return true; } -bool DeinitModule() { return true; } - -BEGIN_FACTORY_DEF("YourOrg","https://your.org","support@your.org") - -DEF_CLASS2(INLINE_UID_FROM_FUID(kProcessorUID), - PClassInfo::kManyInstances, kVstAudioEffectClass, "DartVstHost", - Vst::kDistributable | Vst::kSimpleModeSupported, - "Instrument|Fx", FULL_VERSION_STR, kVstVersionString, createDvhProcessor) - -DEF_CLASS2(INLINE_UID_FROM_FUID(kControllerUID), - PClassInfo::kManyInstances, kVstComponentControllerClass, "DartVstHostController", - 0, "", FULL_VERSION_STR, kVstVersionString, createDvhController) - -END_FACTORY \ No newline at end of file diff --git a/flutter_vst3/native/src/native_cocoa_view.mm b/flutter_vst3/native/src/native_cocoa_view.mm new file mode 100644 index 0000000..e07e8cd --- /dev/null +++ b/flutter_vst3/native/src/native_cocoa_view.mm @@ -0,0 +1,187 @@ +// Copyright (c) 2025 +// Native Cocoa/AppKit view fallback for macOS VST3 plugins + +#import "native_cocoa_view.h" +#include "pluginterfaces/base/ustring.h" +#include + +@interface Vst3FlippedView : NSView +@end + +@implementation Vst3FlippedView +- (BOOL)isFlipped { + return YES; +} +@end + +#define Vst3GestureSlider CONCAT(Vst3GestureSlider, PLUGIN_TARGET_NAME) +@interface Vst3GestureSlider : NSSlider +@property(nonatomic, assign) BOOL editing; +@end +@implementation Vst3GestureSlider +- (void)mouseDown:(NSEvent*)event { + Vst3PluginEditorDelegate* delegate = (Vst3PluginEditorDelegate*)self.target; + auto* controller = delegate.controller; + if (!controller) return; + self.editing = YES; + controller->beginEdit(static_cast(self.tag)); + [super mouseDown:event]; + if (delegate.controller == controller) + controller->endEdit(static_cast(self.tag)); + self.editing = NO; +} +@end + +@implementation Vst3PluginEditorDelegate +- (void)onSliderChanged:(NSSlider*)sender { + if (!_controller) return; + auto pid = static_cast(sender.tag); + double val = [sender doubleValue]; + const BOOL dragging = [(Vst3GestureSlider*)sender editing]; + if (!dragging) _controller->beginEdit(pid); + _controller->setParamNormalized(pid, val); + _controller->performEdit(pid, val); + if (!dragging) _controller->endEdit(pid); + [self refreshLabelForParam:pid value:val slider:sender]; +} + +- (void)refreshLabelForParam:(Steinberg::Vst::ParamID)pid value:(double)val slider:(NSSlider*)slider { + Steinberg::Vst::String128 str; + _controller->getParamStringByValue(pid, val, str); + char ascii[128] = {0}; + Steinberg::UString128(str).toAscii(ascii, sizeof(ascii)); + NSString* text = (ascii[0] != '\0') + ? [NSString stringWithUTF8String:ascii] + : [NSString stringWithFormat:@"%.1f%%", val * 100.0]; + NSInteger idx = [_sliders indexOfObject:slider]; + if (idx != NSNotFound && idx < static_cast(_valueLabels.count)) { + [_valueLabels[idx] setStringValue:text]; + } +} + +- (void)updateParamId:(Steinberg::Vst::ParamID)pid withValue:(Steinberg::Vst::ParamValue)value { + for (NSUInteger i = 0; i < _sliders.count; ++i) { + if (static_cast(_sliders[i].tag) == pid) { + if (std::abs([_sliders[i] doubleValue] - value) > 1e-5) { + [_sliders[i] setDoubleValue:value]; + if (_controller && i < _valueLabels.count) { + [self refreshLabelForParam:pid value:value slider:_sliders[i]]; + } + } + break; + } + } +} +@end + +static void buildHeader(NSView* parent, const std::string& name) { + CGFloat w = parent.bounds.size.width; + NSView* header = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, w, 64)]; + header.autoresizingMask = NSViewWidthSizable | NSViewMaxYMargin; + + NSTextField* title = [NSTextField labelWithString:[NSString stringWithUTF8String:name.c_str()]]; + title.frame = NSMakeRect(24, 12, 300, 24); + title.font = [NSFont systemFontOfSize:17 weight:NSFontWeightBold]; + title.textColor = [NSColor whiteColor]; + [header addSubview:title]; + + NSTextField* sub = [NSTextField labelWithString:@"flutter_vst3 • Pure Dart DSP & UI"]; + sub.frame = NSMakeRect(24, 38, 300, 16); + sub.font = [NSFont systemFontOfSize:11 weight:NSFontWeightMedium]; + sub.textColor = [NSColor colorWithCalibratedWhite:0.6 alpha:1.0]; + [header addSubview:sub]; + + NSBox* sep = [[NSBox alloc] initWithFrame:NSMakeRect(0, 63, w, 1)]; + sep.boxType = NSBoxSeparator; + sep.autoresizingMask = NSViewWidthSizable; + [header addSubview:sep]; + [parent addSubview:header]; +} + +static void buildSingleRow( + NSView* parent, + Steinberg::Vst::EditController* controller, + const Steinberg::Vst::ParameterInfo& info, + CGFloat width, + CGFloat y, + Vst3PluginEditorDelegate* delegate) { + char asciiTitle[128] = {0}; + Steinberg::UString128(info.title).toAscii(asciiTitle, sizeof(asciiTitle)); + NSString* name = (asciiTitle[0] != '\0') + ? [NSString stringWithUTF8String:asciiTitle] + : [NSString stringWithFormat:@"Param %d", info.id]; + + NSTextField* nameLabel = [NSTextField labelWithString:name]; + nameLabel.frame = NSMakeRect(24, y, width - 160, 18); + nameLabel.font = [NSFont systemFontOfSize:13 weight:NSFontWeightSemibold]; + nameLabel.textColor = [NSColor colorWithCalibratedWhite:0.92 alpha:1.0]; + [parent addSubview:nameLabel]; + + double val = controller->getParamNormalized(info.id); + NSTextField* valLabel = [NSTextField labelWithString:[NSString stringWithFormat:@"%.1f%%", val * 100.0]]; + valLabel.frame = NSMakeRect(width - 134, y, 110, 18); + valLabel.font = [NSFont monospacedDigitSystemFontOfSize:12 weight:NSFontWeightMedium]; + valLabel.textColor = [NSColor colorWithCalibratedRed:0.25 green:0.75 blue:1.0 alpha:1.0]; + valLabel.alignment = NSTextAlignmentRight; + valLabel.autoresizingMask = NSViewMinXMargin; + [parent addSubview:valLabel]; + [delegate.valueLabels addObject:valLabel]; + + NSSlider* slider = [Vst3GestureSlider sliderWithValue:val minValue:0.0 maxValue:1.0 target:delegate action:@selector(onSliderChanged:)]; + slider.frame = NSMakeRect(24, y + 22, width - 48, 20); + slider.continuous = YES; + slider.tag = info.id; + slider.autoresizingMask = NSViewWidthSizable; + [parent addSubview:slider]; + [delegate.sliders addObject:slider]; +} + +static void buildParameterRows( + NSView* parent, + Steinberg::Vst::EditController* controller, + Vst3PluginEditorDelegate* delegate) { + if (!controller) return; + int count = controller->getParameterCount(); + CGFloat width = parent.bounds.size.width; + CGFloat y = 74.0; + for (int i = 0; i < count; ++i) { + Steinberg::Vst::ParameterInfo info; + if (controller->getParameterInfo(i, info) != Steinberg::kResultTrue) continue; + buildSingleRow(parent, controller, info, width, y, delegate); + y += 56.0; + } +} + +static void buildFooter(NSView* parent) { + CGFloat w = parent.bounds.size.width; + CGFloat h = parent.bounds.size.height; + NSTextField* footer = [NSTextField labelWithString:@"Shared Memory DSP"]; + footer.frame = NSMakeRect(24, h - 24, w - 48, 16); + footer.alignment = NSTextAlignmentCenter; + footer.font = [NSFont systemFontOfSize:10 weight:NSFontWeightRegular]; + footer.textColor = [NSColor colorWithCalibratedWhite:0.4 alpha:1.0]; + footer.autoresizingMask = NSViewWidthSizable | NSViewMinYMargin; + [parent addSubview:footer]; +} + +NSView* createCocoaFallbackView( + NSView* parent, + Steinberg::Vst::EditController* controller, + const std::string& pluginName, + Vst3PluginEditorDelegate** outDelegate) { + auto container = [[Vst3FlippedView alloc] initWithFrame:parent.bounds]; + container.wantsLayer = YES; + container.layer.backgroundColor = [NSColor colorWithCalibratedRed:0.09 green:0.09 blue:0.11 alpha:1.0].CGColor; + container.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; + + auto delegate = [[Vst3PluginEditorDelegate alloc] init]; + delegate.controller = controller; + delegate.sliders = [NSMutableArray array]; + delegate.valueLabels = [NSMutableArray array]; + if (outDelegate) *outDelegate = delegate; + + buildHeader(container, pluginName); + buildParameterRows(container, controller, delegate); + buildFooter(container); + return container; +} diff --git a/flutter_vst3/native/src/plugin_controller.cpp b/flutter_vst3/native/src/plugin_controller.cpp deleted file mode 100644 index 5b2e1b3..0000000 --- a/flutter_vst3/native/src/plugin_controller.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2025 -// -// Controller class for the Dart VST host plug‑in. Exposes parameters -// to the host and manages the state of the user interface. Only one -// parameter controlling the output gain is currently provided. - -#include "plugin_ids.h" -#include "public.sdk/source/vst/vsteditcontroller.h" -#include "public.sdk/source/vst/vstparameters.h" -#include "pluginterfaces/base/ustring.h" - -using namespace Steinberg; -using namespace Steinberg::Vst; - -class DvhController : public EditController { -public: - tresult PLUGIN_API initialize(FUnknown* ctx) override { - tresult r = EditController::initialize(ctx); - if (r != kResultTrue) return r; - - // Create a normalized parameter for output gain. Normalized - // 0.0 -> -60dB, 1.0 -> 0dB. The unit string is in decibels. - RangeParameter* outGain = new RangeParameter(USTRING("Output Gain"), kParamOutputGain, USTRING("dB"), 0, 1, 0.5); - parameters.addParameter(outGain); - return kResultTrue; - } - -}; - -// Factory function for the controller -FUnknown* createDvhController(void*) { - return (IEditController*)new DvhController(); -} \ No newline at end of file diff --git a/flutter_vst3/native/src/plugin_processor.cpp b/flutter_vst3/native/src/plugin_processor.cpp deleted file mode 100644 index f95d290..0000000 --- a/flutter_vst3/native/src/plugin_processor.cpp +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright (c) 2025 -// -// Implementation of the audio processor for the Dart VST host plug‑in. -// This component wraps the Graph API and exposes it as a VST3 -// processor. It forwards incoming audio and MIDI to the graph and -// outputs the processed result. Automation of the exposed gain -// parameter is mapped to the graph’s gain node. - -#include "plugin_ids.h" -#include "pluginterfaces/base/ibstream.h" -#include "pluginterfaces/base/ipluginbase.h" -#include "pluginterfaces/vst/ivstaudioprocessor.h" -#include "pluginterfaces/vst/ivstevents.h" -#include "pluginterfaces/vst/ivstparameterchanges.h" -#include "public.sdk/source/vst/vstaudioeffect.h" - -#include "dvh_graph.h" - -#define FULL_VERSION_STR "1.0.0" - -using namespace Steinberg; -using namespace Steinberg::Vst; - -// The processor derives from AudioEffect and holds an instance of the -// graph. It wires up buses and responds to parameter and event -// messages from the host. -class DvhProcessor : public AudioEffect { -public: - DvhProcessor() { setControllerClass(kControllerUID); } - ~DvhProcessor() override { - if (graph_) dvh_graph_destroy(graph_); - } - - tresult PLUGIN_API initialize(FUnknown* ctx) override { - tresult r = AudioEffect::initialize(ctx); - if (r != kResultTrue) return r; - - // Add stereo audio inputs and outputs. Use auxiliary type for - // inputs to allow both main input and sidechain. Only the main - // output is required. - addAudioInput(STR16("Main In"), SpeakerArr::kStereo, kAux); - addAudioInput(STR16("Sidechain"), SpeakerArr::kStereo, kAux); - addAudioOutput(STR16("Main Out"), SpeakerArr::kStereo, kMain); - - // MIDI input for note events - addEventInput(STR16("MIDI In"), 16); - - // Create the graph with a default sample rate and block size. These - // will be updated in setupProcessing(). - graph_ = dvh_graph_create(48000.0, 1024); - // Construct a minimal internal graph: input -> mixer -> gain -> output - int32_t inNode = -1, outNode = -1, mix = -1, gain = -1; - dvh_graph_add_split(graph_, &inNode); - dvh_graph_add_mixer(graph_, 3, &mix); - dvh_graph_add_gain(graph_, 0.0f, &gain); - dvh_graph_add_split(graph_, &outNode); - - dvh_graph_connect(graph_, inNode, 0, mix, 0); - dvh_graph_connect(graph_, mix, 0, gain, 0); - dvh_graph_connect(graph_, gain, 0, outNode, 0); - dvh_graph_set_io_nodes(graph_, inNode, outNode); - // Remember the index of the gain node (2) for automation later - gainNode_ = gain; - return r; - } - - tresult PLUGIN_API setBusArrangements(SpeakerArrangement* inputs, int32 numIns, - SpeakerArrangement* outputs, int32 numOuts) override { - // We only support one stereo output - if (numOuts != 1 || outputs[0] != SpeakerArr::kStereo) return kResultFalse; - return kResultTrue; - } - - tresult PLUGIN_API setupProcessing(ProcessSetup& s) override { - setup_ = s; - // Recreate the graph with the actual sample rate and maximum block - // size when changed. The current implementation does not rebuild - // nodes on the fly but this could be extended. - return kResultTrue; - } - - tresult PLUGIN_API setActive(TBool state) override { - return AudioEffect::setActive(state); - } - - tresult PLUGIN_API process(ProcessData& data) override { - if (!graph_) return kResultFalse; - - // Apply parameter changes from automation. Only one parameter for - // gain is implemented. Iterate through all incoming changes and - // update the graph accordingly. - if (data.inputParameterChanges) { - int32 listCount = data.inputParameterChanges->getParameterCount(); - for (int32 i = 0; i < listCount; ++i) { - IParamValueQueue* q = data.inputParameterChanges->getParameterData(i); - if (!q) continue; - int32 index; - ParamValue v; - int32 sampleOffset; - // Use the last point in the queue as the effective value - if (q->getPoint(q->getPointCount() - 1, sampleOffset, v) == kResultTrue) { - if (q->getParameterId() == kParamOutputGain) { - dvh_graph_set_param(graph_, gainNode_, 0, (float)v); - } - } - } - } - - // Dispatch MIDI events - if (data.inputEvents) { - int32 n = data.inputEvents->getEventCount(); - for (int32 i = 0; i < n; ++i) { - Event e; - if (data.inputEvents->getEvent(i, e) != kResultTrue) continue; - if (e.type == Event::kNoteOnEvent) dvh_graph_note_on(graph_, -1, e.noteOn.channel, e.noteOn.pitch, e.noteOn.velocity); - if (e.type == Event::kNoteOffEvent) dvh_graph_note_off(graph_, -1, e.noteOff.channel, e.noteOff.pitch, e.noteOff.velocity); - } - } - - // Determine pointers to input and output channel buffers. - const float* inL = nullptr; - const float* inR = nullptr; - if (data.numInputs > 0) { - auto in0 = &data.inputs[0]; - if (in0->numChannels >= 2) { - inL = in0->channelBuffers32[0]; - inR = in0->channelBuffers32[1]; - } - } - float* outL = nullptr; - float* outR = nullptr; - if (data.numOutputs > 0) { - auto out0 = &data.outputs[0]; - if (out0->numChannels >= 2) { - outL = out0->channelBuffers32[0]; - outR = out0->channelBuffers32[1]; - } - } - if (!outL || !outR) return kResultFalse; - // Provide zero input if no buffers are connected (e.g. instrument) - if (!inL || !inR) { - static float zeros[4096] = {0}; - inL = inR = zeros; - } - - if (dvh_graph_process_stereo(graph_, inL, inR, outL, outR, data.numSamples) != 1) - return kResultFalse; - - return kResultTrue; - } - -private: - DVH_Graph graph_{nullptr}; - ProcessSetup setup_{}; - int32_t gainNode_ = -1; -}; - -// Factory function for the processor -FUnknown* createDvhProcessor(void*) { - return (IAudioProcessor*)new DvhProcessor(); -} \ No newline at end of file diff --git a/flutter_vst3/native/src/plugin_view.cpp b/flutter_vst3/native/src/plugin_view.cpp deleted file mode 100644 index 5cd0215..0000000 --- a/flutter_vst3/native/src/plugin_view.cpp +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) 2025 -// -// Minimal view implementation that launches an external Flutter UI -// application. This plug‑in uses an external window to avoid -// embedding Flutter directly into the VST host for now. When the -// view is attached, the external process is started; when removed it -// simply retains its state. Resize support is limited. - -#include "public.sdk/source/vst/utility/uid.h" -#include "public.sdk/source/vst/vsteditcontroller.h" -#include "pluginterfaces/vst/ivsteditcontroller.h" -#include -#include -#include -#include -#include - -#if defined(_WIN32) -#include -#endif - -namespace Steinberg::Vst { - -class DummyView : public IPlugView, public FObject { -public: - DummyView() {} - ~DummyView() override {} - - tresult PLUGIN_API isPlatformTypeSupported(FIDString type) override { -#if defined(_WIN32) - if (strcmp(type, kPlatformTypeHWND) == 0) return kResultTrue; -#elif defined(__APPLE__) - if (strcmp(type, kPlatformTypeNSView) == 0) return kResultTrue; -#else - if (strcmp(type, kPlatformTypeX11EmbedWindowID) == 0) return kResultTrue; -#endif - return kInvalidArgument; - } - - tresult PLUGIN_API attached(void* parent, FIDString) override { - parent_ = parent; - launchFlutter(); - return kResultTrue; - } - tresult PLUGIN_API removed() override { - parent_ = nullptr; - return kResultTrue; - } - tresult PLUGIN_API onSize(ViewRect*) override { return kResultTrue; } - tresult PLUGIN_API getSize(ViewRect* r) override { - if (!r) return kInvalidArgument; - r->left = 0; - r->top = 0; - r->right = 600; - r->bottom = 420; - return kResultTrue; - } - tresult PLUGIN_API setFrame(IPlugFrame*) override { return kResultTrue; } - tresult PLUGIN_API canResize() override { return kResultTrue; } - tresult PLUGIN_API checkSizeConstraint(ViewRect*) override { return kResultTrue; } - - REFCOUNT_METHODS(FObject) - tresult PLUGIN_API queryInterface(const TUID iid, void** obj) override { - QUERY_INTERFACE(iid, obj, IPlugView::iid, IPlugView) - return FObject::queryInterface(iid, obj); - } - -private: - void* parent_{nullptr}; - std::atomic launched_{false}; - - void launchFlutter() { - if (launched_.exchange(true)) return; -#if defined(_WIN32) - std::wstring exe = L"flutter_ui\\build\\windows\\runner\\Release\\flutter_ui.exe"; - STARTUPINFO si{}; - PROCESS_INFORMATION pi{}; - CreateProcessW(exe.c_str(), NULL, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi); - CloseHandle(pi.hProcess); - CloseHandle(pi.hThread); -#elif defined(__APPLE__) - system("open flutter_ui/build/macos/Build/Products/Release/flutter_ui.app"); -#else - if (!fork()) { - execl("flutter_ui/build/linux/x64/release/bundle/flutter_ui", "flutter_ui", (char*)NULL); - _exit(0); - } -#endif - } -}; - -} // namespace Steinberg::Vst \ No newline at end of file diff --git a/flutter_vst3/native/src/vst3_ipc_host.cpp b/flutter_vst3/native/src/vst3_ipc_host.cpp new file mode 100644 index 0000000..27c9c66 --- /dev/null +++ b/flutter_vst3/native/src/vst3_ipc_host.cpp @@ -0,0 +1,254 @@ +// Copyright (c) 2025 +// See vst3_ipc_host.h. Ownership of the memory block passes by semaphore: the +// host may only touch it while the worker isn't busy. + +#include "vst3_ipc_host.h" + +#include +#include +#include +#include +#include +#include + +#include "vst3_ipc_platform.h" + +using namespace vst3_ipc; + +namespace { + +constexpr int kHandshakeTimeoutMs = 5000; +constexpr int kTerminateGraceMs = 500; +constexpr double kMinBudgetSeconds = 0.001; +constexpr double kOfflineBudgetSeconds = 30.0; + +/// Names are unique per instance and generation, and within macOS's 31 +/// character limit for POSIX names. +std::string uniqueName(const char* prefix, const void* owner) { + static std::mutex counterMutex; + static unsigned counter = 0; + std::lock_guard lock(counterMutex); + char name[64]; + std::snprintf(name, sizeof(name), "%s%lx_%llx_%x", prefix, currentProcessId(), + static_cast(reinterpret_cast(owner)) & 0xFFFFFFFFFFFFULL, + ++counter & 0xFFFFu); + return name; +} + +void writeSilence(float* outL, float* outR, int numSamples) noexcept { + std::memset(outL, 0, static_cast(numSamples) * sizeof(float)); + std::memset(outR, 0, static_cast(numSamples) * sizeof(float)); +} + +} // namespace + +std::string vst3WorkerPathNextToModule(const std::string& workerName) { + const std::string path = modulePath(); + const size_t slash = path.find_last_of("\\/"); + const std::string dir = slash == std::string::npos ? std::string(".") : path.substr(0, slash); +#ifdef _WIN32 + return dir + "\\" + workerName + ".exe"; +#else + return dir + "/" + workerName; +#endif +} + +Vst3IpcHost::Vst3IpcHost(std::string workerPath, int parameterCount) + : workerPath_(std::move(workerPath)), + paramValues_(static_cast(parameterCount), 0.0), + paramKnown_(static_cast(parameterCount), 0), + paramDirty_(static_cast(parameterCount), 0) {} + +Vst3IpcHost::~Vst3IpcHost() { dispose(); } + +int64_t Vst3IpcHost::workerProcessId() const noexcept { return child_ ? childPid(child_) : 0; } + +void Vst3IpcHost::configure(double sampleRate, int maxBlockSize, bool offline) { + offline_ = offline; + secondsPerSample_ = 1.0 / sampleRate; + if (running_ && !dead_) { + reclaimForControl(); + memory_->sampleRate = sampleRate; + memory_->maxBlockSize = static_cast(maxBlockSize); + sendControl(VST3_CMD_CONFIGURE); + return; + } + dispose(); + try { + start(sampleRate, maxBlockSize); + } catch (...) { + dispose(); + throw; + } +} + +void Vst3IpcHost::start(double sampleRate, int maxBlockSize) { + shmName_ = uniqueName(shmPrefix(), this); + semReadyName_ = uniqueName(semReadyPrefix(), this); + semDoneName_ = uniqueName(semDonePrefix(), this); + memory_ = mapCreate(shmName_, mappingHandle_); + std::memset(memory_, 0, VST3_SHM_TOTAL_SIZE); + memory_->version = VST3_SHM_VERSION; + memory_->sampleRate = sampleRate; + memory_->maxBlockSize = static_cast(maxBlockSize); + memory_->command = VST3_CMD_IDLE; + memory_->magic = VST3_SHM_MAGIC; + semReady_ = semCreate(semReadyName_); + semDone_ = semCreate(semDoneName_); + child_ = spawnWorker(workerPath_, shmName_, semReadyName_, semDoneName_); + waitForWorker(kHandshakeTimeoutMs); + unlinkNames(shmName_, semReadyName_, semDoneName_); + running_ = true; + dead_ = false; + workerBusy_ = false; + std::copy(paramKnown_.begin(), paramKnown_.end(), paramDirty_.begin()); +} + +void Vst3IpcHost::waitForWorker(int timeoutMs) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); + while (std::chrono::steady_clock::now() < deadline) { + if (semTimedWait(semDone_, 0.01)) return; + if (!childAlive(child_)) { + forgetDeadWorker(); + throw std::runtime_error("Dart worker exited: " + workerPath_); + } + } + // The worker may still post done after this throw; marking it busy keeps + // that late post from answering a later handshake. + workerBusy_ = true; + throw std::runtime_error("Dart worker timed out: " + workerPath_); +} + +void Vst3IpcHost::reclaimForControl() { + if (!workerBusy_) return; + waitForWorker(kHandshakeTimeoutMs); + workerBusy_ = false; +} + +void Vst3IpcHost::sendControl(uint32_t command) { + reclaimForControl(); + memory_->command = command; + semPost(semReady_); + waitForWorker(kHandshakeTimeoutMs); +} + +void Vst3IpcHost::reset() { + if (!running_ || dead_) return; + sendControl(VST3_CMD_RESET); +} + +void Vst3IpcHost::stopWorker() noexcept { + if (!child_) return; + if (memory_ && semReady_) { + memory_->command = VST3_CMD_TERMINATE; + semPost(semReady_); + } + childStop(child_, kTerminateGraceMs); + child_ = 0; +} + +void Vst3IpcHost::releaseResources() noexcept { + if (!memory_) return; + unlinkNames(shmName_, semReadyName_, semDoneName_); + if (semReady_) semRelease(semReady_); + if (semDone_) semRelease(semDone_); + semReady_ = nullptr; + semDone_ = nullptr; + mapRetire(memory_, mappingHandle_, shmName_); + memory_ = nullptr; + mappingHandle_ = nullptr; +} + +void Vst3IpcHost::dispose() { + stopWorker(); + releaseResources(); + running_ = false; + dead_ = false; + workerBusy_ = false; +} + +void Vst3IpcHost::setParameter(int paramId, double value) noexcept { + if (paramId < 0 || static_cast(paramId) >= paramValues_.size()) return; + const auto id = static_cast(paramId); + paramValues_[id] = value; + paramKnown_[id] = 1; + paramDirty_[id] = 1; +} + +/// Anything that doesn't fit stays dirty for the next block. +void Vst3IpcHost::flushParameters() noexcept { + uint32_t write = memory_->hostParamWriteIndex; + const uint32_t read = memory_->hostParamReadIndex; + for (size_t id = 0; id < paramDirty_.size() && write - read < VST3_SHM_PARAM_QUEUE_SIZE; ++id) { + if (!paramDirty_[id]) continue; + Vst3ParamEvent& event = memory_->hostParams[write % VST3_SHM_PARAM_QUEUE_SIZE]; + event.paramId = static_cast(id); + event.value = paramValues_[id]; + paramDirty_[id] = 0; + ++write; + } + memory_->hostParamWriteIndex = write; +} + +void Vst3IpcHost::noteWorkerLate() noexcept { + if (!childAlive(child_)) forgetDeadWorker(); +} + +void Vst3IpcHost::forgetDeadWorker() noexcept { + if (child_) childReleaseDead(child_); + child_ = 0; + dead_ = true; + // The editor reads this block, and this is how it learns the DSP has stopped. + if (memory_) memory_->magic = 0; +} + +/// Returns true if the block belongs to the host again. A late worker's output +/// is for a block the host already answered with silence, so it's discarded. +bool Vst3IpcHost::reclaimFromLateWorker() noexcept { + if (!workerBusy_) return true; + if (semTryWait(semDone_)) { + workerBusy_ = false; + return true; + } + noteWorkerLate(); + return false; +} + +bool Vst3IpcHost::processChunk(const float* inL, const float* inR, float* outL, float* outR, int numSamples) noexcept { + if (dead_ || !reclaimFromLateWorker()) { + writeSilence(outL, outR, numSamples); + return false; + } + flushParameters(); + const size_t bytes = static_cast(numSamples) * sizeof(float); + std::memcpy(memory_->inputL, inL, bytes); + std::memcpy(memory_->inputR, inR, bytes); + memory_->numSamples = numSamples; + memory_->command = VST3_CMD_PROCESS; + semPost(semReady_); + const double budget = offline_ ? kOfflineBudgetSeconds : std::max(kMinBudgetSeconds, numSamples * secondsPerSample_); + if (!semTimedWait(semDone_, budget)) { + workerBusy_ = true; + noteWorkerLate(); + writeSilence(outL, outR, numSamples); + return false; + } + std::memcpy(outL, memory_->outputL, bytes); + std::memcpy(outR, memory_->outputR, bytes); + return true; +} + +bool Vst3IpcHost::process(const float* inL, const float* inR, float* outL, float* outR, int numSamples) noexcept { + if (!running_) { + writeSilence(outL, outR, numSamples); + return false; + } + bool complete = true; + for (int done = 0; done < numSamples;) { + const int chunk = std::min(numSamples - done, static_cast(VST3_SHM_MAX_SAMPLES)); + complete = processChunk(inL + done, inR + done, outL + done, outR + done, chunk) && complete; + done += chunk; + } + if (!complete) writeSilence(outL, outR, numSamples); + return complete; +} diff --git a/flutter_vst3/native/src/vst3_ipc_platform.h b/flutter_vst3/native/src/vst3_ipc_platform.h new file mode 100644 index 0000000..0ad4a8a --- /dev/null +++ b/flutter_vst3/native/src/vst3_ipc_platform.h @@ -0,0 +1,56 @@ +// Copyright (c) 2025 +// Operating system primitives used by Vst3IpcHost. Implemented separately for +// Win32 and POSIX in vst3_ipc_platform_win.cpp and vst3_ipc_platform_posix.cpp. + +#pragma once + +#include +#include + +#include "vst3_shared_memory.h" + +namespace vst3_ipc { + +long currentProcessId() noexcept; +const char* shmPrefix() noexcept; +const char* semReadyPrefix() noexcept; +const char* semDonePrefix() noexcept; + +/// Creates a new semaphore at zero. Throws if the name is already in use. +void* semCreate(const std::string& name); +void semPost(void* sem) noexcept; +bool semTryWait(void* sem) noexcept; +bool semTimedWait(void* sem, double seconds) noexcept; +void semRelease(void* sem) noexcept; + +/// Removes names from the system, so nothing outlives a host crash. The worker +/// must already have opened them. +void unlinkNames(const std::string& shm, const std::string& ready, const std::string& done) noexcept; + +/// Creates a block of VST3_SHM_TOTAL_SIZE bytes, reusing a retired address if +/// there is one. On Windows a reused block keeps its old name, so name is an +/// in-out parameter. +Vst3SharedMemory* mapCreate(std::string& name, void*& handle); + +/// Clears the magic word and keeps the address valid for in-process readers. +void mapRetire(Vst3SharedMemory* memory, void* handle, const std::string& name) noexcept; + +/// Starts the worker with the block and semaphore names and this process's id. +intptr_t spawnWorker(const std::string& path, const std::string& shm, const std::string& ready, + const std::string& done); + +/// Reports whether the child still runs. On POSIX this reaps a dead child. +bool childAlive(intptr_t child) noexcept; + +/// Waits up to graceMs for the child to exit, then kills it, and releases it. +void childStop(intptr_t child, int graceMs) noexcept; + +/// Releases what's still held for a child that childAlive reported dead. +void childReleaseDead(intptr_t child) noexcept; + +int64_t childPid(intptr_t child) noexcept; + +/// Absolute path of the module containing this code. +std::string modulePath(); + +} // namespace vst3_ipc diff --git a/flutter_vst3/native/src/vst3_ipc_platform_posix.cpp b/flutter_vst3/native/src/vst3_ipc_platform_posix.cpp new file mode 100644 index 0000000..ddde64f --- /dev/null +++ b/flutter_vst3/native/src/vst3_ipc_platform_posix.cpp @@ -0,0 +1,170 @@ +// Copyright (c) 2025 +// POSIX implementation of vst3_ipc_platform.h. + +#ifndef _WIN32 + +#include "vst3_ipc_platform.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#if defined(__linux__) +#include +#endif + +#include "vst3_ipc_retired.h" + +namespace vst3_ipc { +namespace { + +void moduleAnchor() {} + +/// Closes everything the host left open, such as audio devices and sockets. +/// Runs between fork and exec, so only async-signal-safe calls are allowed. +void closeInheritedDescriptors() noexcept { +#if defined(__linux__) && defined(SYS_close_range) + syscall(SYS_close_range, 3U, ~0U, 0U); +#else + const int limit = getdtablesize(); + for (int fd = 3; fd < limit; ++fd) close(fd); +#endif +} + +} // namespace + +long currentProcessId() noexcept { return static_cast(getpid()); } +const char* shmPrefix() noexcept { return "/v3s"; } +const char* semReadyPrefix() noexcept { return "/v3r"; } +const char* semDonePrefix() noexcept { return "/v3d"; } + +void* semCreate(const std::string& name) { + sem_t* sem = sem_open(name.c_str(), O_CREAT | O_EXCL, 0600, 0); + if (sem == SEM_FAILED) throw std::runtime_error("sem_open failed: " + name); + return sem; +} + +void semPost(void* sem) noexcept { sem_post(static_cast(sem)); } +bool semTryWait(void* sem) noexcept { return sem_trywait(static_cast(sem)) == 0; } + +#if defined(__APPLE__) +// macOS has no sem_timedwait, so this is the one place that has to poll. +bool semTimedWait(void* sem, double seconds) noexcept { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration(seconds); + do { + if (semTryWait(sem)) return true; + std::this_thread::sleep_for(std::chrono::microseconds(50)); + } while (std::chrono::steady_clock::now() < deadline); + return false; +} +#else +bool semTimedWait(void* sem, double seconds) noexcept { + timespec deadline{}; + clock_gettime(CLOCK_REALTIME, &deadline); + const auto wholeSeconds = static_cast(seconds); + deadline.tv_sec += wholeSeconds; + deadline.tv_nsec += static_cast((seconds - static_cast(wholeSeconds)) * 1e9); + deadline.tv_sec += deadline.tv_nsec / 1000000000L; + deadline.tv_nsec %= 1000000000L; + int result = 0; + do { + result = sem_timedwait(static_cast(sem), &deadline); + } while (result != 0 && errno == EINTR); + return result == 0; +} +#endif + +void semRelease(void* sem) noexcept { sem_close(static_cast(sem)); } + +void unlinkNames(const std::string& shm, const std::string& ready, const std::string& done) noexcept { + shm_unlink(shm.c_str()); + sem_unlink(ready.c_str()); + sem_unlink(done.c_str()); +} + +Vst3SharedMemory* mapCreate(std::string& name, void*& handle) { + const int fd = shm_open(name.c_str(), O_CREAT | O_EXCL | O_RDWR, 0600); + if (fd < 0) throw std::runtime_error("shm_open failed: " + name); + if (ftruncate(fd, VST3_SHM_TOTAL_SIZE) != 0) { + close(fd); + shm_unlink(name.c_str()); + throw std::runtime_error("ftruncate failed: " + name); + } + RetiredMapping retired; + const bool reuse = takeRetired(retired); + void* address = mmap(reuse ? retired.memory : nullptr, VST3_SHM_TOTAL_SIZE, PROT_READ | PROT_WRITE, + MAP_SHARED | (reuse ? MAP_FIXED : 0), fd, 0); + close(fd); + if (address == MAP_FAILED) { + shm_unlink(name.c_str()); + throw std::runtime_error("mmap failed: " + name); + } + handle = nullptr; + return static_cast(address); +} + +void mapRetire(Vst3SharedMemory* memory, void*, const std::string&) noexcept { + memory->magic = 0; + mmap(memory, VST3_SHM_TOTAL_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); + RetiredMapping retired; + retired.memory = memory; + addRetired(std::move(retired)); +} + +intptr_t spawnWorker(const std::string& path, const std::string& shm, const std::string& ready, + const std::string& done) { + const std::string hostPid = std::to_string(currentProcessId()); + const pid_t child = fork(); + if (child < 0) throw std::runtime_error("fork failed for Dart worker: " + path); + if (child == 0) { + closeInheritedDescriptors(); + execl(path.c_str(), path.c_str(), shm.c_str(), ready.c_str(), done.c_str(), hostPid.c_str(), + static_cast(nullptr)); + _exit(127); + } + return static_cast(child); +} + +bool childAlive(intptr_t child) noexcept { + int status = 0; + return child != 0 && waitpid(static_cast(child), &status, WNOHANG) == 0; +} + +void childStop(intptr_t child, int graceMs) noexcept { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(graceMs); + while (std::chrono::steady_clock::now() < deadline) { + if (!childAlive(child)) return; + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } + kill(static_cast(child), SIGKILL); + int status = 0; + waitpid(static_cast(child), &status, 0); +} + +// childAlive already reaped it. +void childReleaseDead(intptr_t) noexcept {} + +int64_t childPid(intptr_t child) noexcept { return static_cast(child); } + +std::string modulePath() { + Dl_info info{}; + if (dladdr(reinterpret_cast(&moduleAnchor), &info) == 0 || !info.dli_fname) { + throw std::runtime_error("Failed to locate the VST3 module"); + } + return info.dli_fname; +} + +} // namespace vst3_ipc + +#endif diff --git a/flutter_vst3/native/src/vst3_ipc_platform_win.cpp b/flutter_vst3/native/src/vst3_ipc_platform_win.cpp new file mode 100644 index 0000000..f0fba49 --- /dev/null +++ b/flutter_vst3/native/src/vst3_ipc_platform_win.cpp @@ -0,0 +1,155 @@ +// Copyright (c) 2025 +// Win32 implementation of vst3_ipc_platform.h. + +#ifdef _WIN32 + +#include "vst3_ipc_platform.h" + +#include + +#include +#include + +#include "vst3_ipc_retired.h" + +namespace vst3_ipc { +namespace { + +void moduleAnchor() {} + +constexpr DWORD kLongestWindowsPath = 32768; + +std::wstring widened(const std::string& utf8) { + const int size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), + static_cast(utf8.size()), nullptr, 0); + if (size == 0 && !utf8.empty()) throw std::runtime_error("Path is not valid UTF-8: " + utf8); + std::wstring wide(static_cast(size), L'\0'); + MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.data(), static_cast(utf8.size()), + wide.data(), size); + return wide; +} + +std::string narrowed(const wchar_t* wide, int length) { + const int size = WideCharToMultiByte(CP_UTF8, 0, wide, length, nullptr, 0, nullptr, nullptr); + std::string utf8(static_cast(size), '\0'); + WideCharToMultiByte(CP_UTF8, 0, wide, length, utf8.data(), size, nullptr, nullptr); + return utf8; +} + +Vst3SharedMemory* mapNew(const std::string& name, void*& handle) { + HANDLE mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, + VST3_SHM_TOTAL_SIZE, name.c_str()); + if (!mapping) throw std::runtime_error("CreateFileMapping failed: " + name); + if (GetLastError() == ERROR_ALREADY_EXISTS) { + CloseHandle(mapping); + throw std::runtime_error("Shared memory already exists: " + name); + } + void* view = MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, VST3_SHM_TOTAL_SIZE); + if (!view) { + CloseHandle(mapping); + throw std::runtime_error("MapViewOfFile failed: " + name); + } + handle = mapping; + return static_cast(view); +} + +} // namespace + +long currentProcessId() noexcept { return static_cast(GetCurrentProcessId()); } +const char* shmPrefix() noexcept { return "Local\\v3s"; } +const char* semReadyPrefix() noexcept { return "Local\\v3r"; } +const char* semDonePrefix() noexcept { return "Local\\v3d"; } + +void* semCreate(const std::string& name) { + HANDLE handle = CreateSemaphoreA(nullptr, 0, 1000, name.c_str()); + if (!handle) throw std::runtime_error("CreateSemaphore failed: " + name); + if (GetLastError() == ERROR_ALREADY_EXISTS) { + CloseHandle(handle); + throw std::runtime_error("Semaphore already exists: " + name); + } + return handle; +} + +void semPost(void* sem) noexcept { ReleaseSemaphore(sem, 1, nullptr); } +bool semTryWait(void* sem) noexcept { return WaitForSingleObject(sem, 0) == WAIT_OBJECT_0; } + +bool semTimedWait(void* sem, double seconds) noexcept { + const DWORD ms = static_cast(seconds * 1000.0 + 0.999); + return WaitForSingleObject(sem, ms) == WAIT_OBJECT_0; +} + +void semRelease(void* sem) noexcept { CloseHandle(sem); } + +// Win32 kernel objects disappear with their last handle, so no unlink step. +void unlinkNames(const std::string&, const std::string&, const std::string&) noexcept {} + +Vst3SharedMemory* mapCreate(std::string& name, void*& handle) { + RetiredMapping retired; + if (!takeRetired(retired)) return mapNew(name, handle); + name = retired.name; + handle = retired.handle; + return retired.memory; +} + +// UnmapViewOfFile would let an in-process reader fault, so the view stays. +void mapRetire(Vst3SharedMemory* memory, void* handle, const std::string& name) noexcept { + memory->magic = 0; + RetiredMapping retired; + retired.memory = memory; + retired.handle = handle; + retired.name = name; + addRetired(std::move(retired)); +} + +intptr_t spawnWorker(const std::string& path, const std::string& shm, const std::string& ready, + const std::string& done) { + const std::string cmd = "\"" + path + "\" \"" + shm + "\" \"" + ready + "\" \"" + done + "\" " + + std::to_string(currentProcessId()); + const std::wstring wide = widened(cmd); + std::vector buffer(wide.begin(), wide.end()); + buffer.push_back(L'\0'); + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + PROCESS_INFORMATION info{}; + if (!CreateProcessW(nullptr, buffer.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, nullptr, + nullptr, &startup, &info)) { + throw std::runtime_error("Failed to start Dart worker: " + path); + } + CloseHandle(info.hThread); + return reinterpret_cast(info.hProcess); +} + +bool childAlive(intptr_t child) noexcept { + return child != 0 && WaitForSingleObject(reinterpret_cast(child), 0) == WAIT_TIMEOUT; +} + +void childStop(intptr_t child, int graceMs) noexcept { + HANDLE handle = reinterpret_cast(child); + if (WaitForSingleObject(handle, static_cast(graceMs)) != WAIT_OBJECT_0) TerminateProcess(handle, 1); + WaitForSingleObject(handle, INFINITE); + CloseHandle(handle); +} + +void childReleaseDead(intptr_t child) noexcept { CloseHandle(reinterpret_cast(child)); } + +int64_t childPid(intptr_t child) noexcept { + return static_cast(GetProcessId(reinterpret_cast(child))); +} + +std::string modulePath() { + HMODULE module = nullptr; + std::vector path(kLongestWindowsPath); + const DWORD length = + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(&moduleAnchor), &module) + ? GetModuleFileNameW(module, path.data(), kLongestWindowsPath) + : 0; + if (length == 0 || length == kLongestWindowsPath) { + throw std::runtime_error("Failed to locate the VST3 module"); + } + return narrowed(path.data(), static_cast(length)); +} + +} // namespace vst3_ipc + +#endif diff --git a/flutter_vst3/native/src/vst3_ipc_retired.h b/flutter_vst3/native/src/vst3_ipc_retired.h new file mode 100644 index 0000000..2b89d60 --- /dev/null +++ b/flutter_vst3/native/src/vst3_ipc_retired.h @@ -0,0 +1,48 @@ +// Copyright (c) 2025 +// Pool of retired memory blocks shared by the platform implementations. +// +// A retired block stays mapped so in-process readers can't fault on it. New +// instances reuse retired blocks, which bounds the cost to the peak instance +// count. The pool is deliberately never destroyed. + +#pragma once + +#include +#include +#include + +#include "vst3_shared_memory.h" + +namespace vst3_ipc { + +struct RetiredMapping { + Vst3SharedMemory* memory = nullptr; + void* handle = nullptr; + std::string name; +}; + +inline std::mutex& retiredMutex() { + static auto* mutex = new std::mutex(); + return *mutex; +} + +inline std::vector& retiredMappings() { + static auto* mappings = new std::vector(); + return *mappings; +} + +inline bool takeRetired(RetiredMapping& out) { + std::lock_guard lock(retiredMutex()); + auto& pool = retiredMappings(); + if (pool.empty()) return false; + out = pool.back(); + pool.pop_back(); + return true; +} + +inline void addRetired(RetiredMapping mapping) noexcept { + std::lock_guard lock(retiredMutex()); + retiredMappings().push_back(std::move(mapping)); +} + +} // namespace vst3_ipc diff --git a/flutter_vst3/native/templates/plugin_controller.cpp.template b/flutter_vst3/native/templates/plugin_controller.cpp.template index de11b88..6f6e366 100644 --- a/flutter_vst3/native/templates/plugin_controller.cpp.template +++ b/flutter_vst3/native/templates/plugin_controller.cpp.template @@ -12,10 +12,33 @@ using namespace Steinberg; using namespace Steinberg::Vst; -// Controller for the {{PLUGIN_NAME}} plugin -class {{PLUGIN_CLASS_NAME}}Controller : public EditController { + +#include "embedded_flutter_view.h" +#include "view_logic.h" +#include "vst3_plugin_state.h" +#include "pluginterfaces/vst/ivstmessage.h" +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif + +/// EditController implementation for the {{PLUGIN_NAME}} VST3 plugin. +/// Manages parameter definitions, state persistence, value formatting, +/// and bidirectional synchronization with the active GUI view. +class {{PLUGIN_CLASS_NAME}}Controller : public EditController, public flutter_vst3::ShmAddressSource { public: {{PLUGIN_CLASS_NAME}}Controller() = default; + + /// Cleans up references to the active GUI view when the controller is destroyed. + ~{{PLUGIN_CLASS_NAME}}Controller() override { + if (activeView_) { + activeView_->onControllerClosed(); + activeView_ = nullptr; + } + } tresult PLUGIN_API initialize(FUnknown* context) override { tresult result = EditController::initialize(context); @@ -27,18 +50,66 @@ public: return kResultTrue; } - tresult PLUGIN_API setComponentState(IBStream* state) override { - if (!state) return kResultFalse; + /// Sets parameter value from DAW host and notifies the active native GUI view. + tresult PLUGIN_API setParamNormalized(ParamID id, ParamValue value) override { + tresult result = EditController::setParamNormalized(id, value); + if (activeView_ && editing_.shouldEcho(id)) { + activeView_->updateParameter(id, EditController::getParamNormalized(id)); + } + return result; + } - // Read parameter values from processor state - for (int32 i = 0; i < {{PARAMETER_COUNT}}; ++i) { - double value = 0.0; - int32 bytesRead = 0; - if (state->read(&value, sizeof(value), &bytesRead) == kResultTrue) { - setParamNormalized(i, value); - } + + uintptr_t sharedMemoryAddress() const override { return shmAddress_; } + + tresult PLUGIN_API notify(IMessage* message) override { + if (message && message->getMessageID() && + std::strcmp(message->getMessageID(), "Vst3Shm") == 0) { + int64 address = 0, pid = 0; + auto* attributes = message->getAttributes(); + const bool valid = attributes && + attributes->getInt("address", address) == kResultTrue && + attributes->getInt("pid", pid) == kResultTrue; +#ifdef _WIN32 + const auto current = GetCurrentProcessId(); +#else + const auto current = getpid(); +#endif + shmAddress_ = valid ? flutter_vst3::localShmAddress(address, pid, current) : 0; + return valid ? kResultTrue : kInvalidArgument; } + return EditController::notify(message); + } + + tresult PLUGIN_API beginEdit(ParamID id) override { + return editing_.begin(id) ? EditController::beginEdit(id) : kResultTrue; + } + + bool isEditing(uint32_t id) const override { return !editing_.shouldEcho(id); } + /// The host requires every perform to sit between a begin and an end. + tresult PLUGIN_API performEdit(ParamID id, ParamValue value) override { + return editing_.shouldEcho(id) ? kResultFalse : EditController::performEdit(id, value); + } + + void endOpenEdits() override { + for (auto id : editing_.takeOpen()) EditController::endEdit(id); + } + + tresult PLUGIN_API endEdit(ParamID id) override { + return editing_.end(id) ? EditController::endEdit(id) : kResultFalse; + } + + int32 PLUGIN_API getParameterCount() override { + return {{PARAMETER_COUNT}}; + } + + tresult PLUGIN_API setComponentState(IBStream* state) override { + std::vector values; + if (!vst3ReadPluginState(state, {{PARAMETER_COUNT}}, values)) return kResultFalse; + for (int32 i = 0; i < {{PARAMETER_COUNT}}; ++i) { + setParamNormalized(i, values[static_cast(i)]); + } return kResultTrue; } @@ -49,39 +120,39 @@ public: tresult PLUGIN_API getState(IBStream* state) override { if (!state) return kResultFalse; - // Write current parameter values for (int32 i = 0; i < {{PARAMETER_COUNT}}; ++i) { - double value = getParamNormalized(i); - int32 bytesWritten = 0; - state->write(&value, sizeof(value), &bytesWritten); + if (!vst3WritePluginStateValue(state, getParamNormalized(i))) return kResultFalse; } - return kResultTrue; } // Convert normalized parameter values to display strings tresult PLUGIN_API getParamStringByValue(ParamID id, ParamValue valueNormalized, String128 string) override { {{PARAMETER_TO_STRING}} - return EditController::getParamStringByValue(id, valueNormalized, string); } // Convert display strings to normalized parameter values tresult PLUGIN_API getParamValueByString(ParamID id, TChar* string, ParamValue& valueNormalized) override { {{STRING_TO_PARAMETER}} - return EditController::getParamValueByString(id, string, valueNormalized); } - // Create view (UI) for the plugin - integrates with Flutter UI + /// Instantiates the native plugin GUI window and binds the activeView_ pointer. IPlugView* PLUGIN_API createView(FIDString name) override { - if (strcmp(name, ViewType::kEditor) == 0) { - // TODO: Return Flutter-based UI view - // For now, return nullptr to use generic host UI - return nullptr; + if (name && strcmp(name, ViewType::kEditor) == 0) { + return createEmbeddedFlutterView(this, "{{PLUGIN_NAME}}", &activeView_); } return nullptr; } + +private: + /// Tracks the active native GUI view to push parameter updates. + /// Cleared automatically by the view when the window is closed. + IEmbeddedFlutterView* activeView_{nullptr}; + uintptr_t shmAddress_{0}; + flutter_vst3::EditState editing_; }; + // Factory functions in proper namespace namespace Steinberg { namespace Vst { diff --git a/flutter_vst3/native/templates/plugin_ids.h.template b/flutter_vst3/native/templates/plugin_ids.h.template deleted file mode 100644 index 065e074..0000000 --- a/flutter_vst3/native/templates/plugin_ids.h.template +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2025 -// Auto-generated plugin IDs and parameters for {{PLUGIN_NAME}} -// This file is generated automatically by dart_vst3_bridge at build time. -// DO NOT EDIT - any changes will be overwritten. - -#pragma once - -#include "pluginterfaces/base/funknown.h" -#include "pluginterfaces/vst/vsttypes.h" - -using namespace Steinberg; - -// Plugin UIDs (generated from plugin name and company) -static const FUID k{{PLUGIN_CLASS_NAME}}ProcessorUID({{PROCESSOR_UID}}); -static const FUID k{{PLUGIN_CLASS_NAME}}ControllerUID({{CONTROLLER_UID}}); - -// Parameter IDs -enum { -{{PARAMETER_ENUMS}} - {{PARAM_COUNT_NAME}} = {{PARAM_COUNT}} -}; \ No newline at end of file diff --git a/flutter_vst3/native/templates/plugin_processor.cpp.template b/flutter_vst3/native/templates/plugin_processor.cpp.template deleted file mode 100644 index 84eb60e..0000000 --- a/flutter_vst3/native/templates/plugin_processor.cpp.template +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright (c) 2025 -// Auto-generated VST3 processor for {{PLUGIN_NAME}} -// This file is generated automatically by dart_vst3_bridge at build time. -// DO NOT EDIT - any changes will be overwritten. - -#include "{{PLUGIN_ID}}_ids.h" -#include "pluginterfaces/vst/ivstparameterchanges.h" -#include "pluginterfaces/vst/ivstprocesscontext.h" -#include "pluginterfaces/base/ibstream.h" -#include "public.sdk/source/vst/vstaudioeffect.h" -#include "base/source/fstreamer.h" -#include "dart_vst3_bridge.h" -#include -#include - -using namespace Steinberg; -using namespace Steinberg::Vst; - -// Processor for the {{PLUGIN_NAME}} plugin -class {{PLUGIN_CLASS_NAME}}Processor : public AudioEffect { -public: - {{PLUGIN_CLASS_NAME}}Processor(); - virtual ~{{PLUGIN_CLASS_NAME}}Processor() = default; - - tresult PLUGIN_API initialize(FUnknown* context) override; - tresult PLUGIN_API terminate() override; - tresult PLUGIN_API setActive(TBool state) override; - tresult PLUGIN_API process(ProcessData& data) override; - tresult PLUGIN_API setupProcessing(ProcessSetup& setup) override; - tresult PLUGIN_API setBusArrangements(SpeakerArrangement* inputs, int32 numIns, - SpeakerArrangement* outputs, int32 numOuts) override; - tresult PLUGIN_API setState(IBStream* state) override; - tresult PLUGIN_API getState(IBStream* state) override; - tresult PLUGIN_API getControllerClassId(TUID classId) override; - -private: -{{PARAMETER_VARIABLES}} - double sampleRate = 44100.0; - - // Dart VST3 bridge instance - DartVST3Instance* dartInstance = nullptr; -}; - -{{PLUGIN_CLASS_NAME}}Processor::{{PLUGIN_CLASS_NAME}}Processor() { - setControllerClass(k{{PLUGIN_CLASS_NAME}}ControllerUID); - - // CRITICAL ARCHITECTURE PROBLEM: This VST3 plugin requires Dart runtime! - // The current architecture assumes the VST3 is loaded by a Dart application, - // but DAWs like Ableton don't have Dart runtime. - // - // TODO: Either embed Dart VM in this plugin OR redesign the bridge architecture - // For now, create instance but expect it to fail during audio processing - dartInstance = dart_vst3_create_instance("{{PLUGIN_ID}}"); - - if (dartInstance == nullptr) { - // Log the issue but don't crash during construction - fprintf(stderr, "WARNING: Failed to create Dart VST3 instance for '{{PLUGIN_ID}}'\n"); - fprintf(stderr, "This plugin requires Dart runtime support which is missing!\n"); - fflush(stderr); - } -{{PARAMETER_DEFAULTS}} -} - -tresult {{PLUGIN_CLASS_NAME}}Processor::initialize(FUnknown* context) { - tresult result = AudioEffect::initialize(context); - if (result != kResultTrue) return result; - - // Configure audio buses - stereo in/out by default - addAudioInput(STR16("Stereo In"), SpeakerArr::kStereo); - addAudioOutput(STR16("Stereo Out"), SpeakerArr::kStereo); - - return kResultTrue; -} - -tresult {{PLUGIN_CLASS_NAME}}Processor::terminate() { - if (dartInstance) { - dart_vst3_dispose(dartInstance); - dart_vst3_destroy_instance(dartInstance); - dartInstance = nullptr; - } - return AudioEffect::terminate(); -} - -tresult {{PLUGIN_CLASS_NAME}}Processor::setActive(TBool state) { - if (state) { - // Plugin activated - initialize Dart processor - if (dartInstance) { - dart_vst3_initialize(dartInstance, sampleRate, 512); - } - } else { - // Plugin deactivated - reset Dart processor - if (dartInstance) { - dart_vst3_reset(dartInstance); - } - } - return AudioEffect::setActive(state); -} - -tresult {{PLUGIN_CLASS_NAME}}Processor::setupProcessing(ProcessSetup& setup) { - sampleRate = setup.sampleRate; - return AudioEffect::setupProcessing(setup); -} - -tresult {{PLUGIN_CLASS_NAME}}Processor::setBusArrangements(SpeakerArrangement* inputs, int32 numIns, - SpeakerArrangement* outputs, int32 numOuts) { - // Only accept stereo input/output - if (numIns == 1 && numOuts == 1 && inputs[0] == SpeakerArr::kStereo && outputs[0] == SpeakerArr::kStereo) { - return AudioEffect::setBusArrangements(inputs, numIns, outputs, numOuts); - } - return kResultFalse; -} - -tresult {{PLUGIN_CLASS_NAME}}Processor::process(ProcessData& data) { - // Process parameter changes - if (data.inputParameterChanges) { - int32 numParamsChanged = data.inputParameterChanges->getParameterCount(); - for (int32 i = 0; i < numParamsChanged; i++) { - IParamValueQueue* paramQueue = data.inputParameterChanges->getParameterData(i); - if (paramQueue) { - ParamValue value; - int32 sampleOffset; - int32 numPoints = paramQueue->getPointCount(); - - if (paramQueue->getPoint(numPoints - 1, sampleOffset, value) == kResultTrue) { - // Forward parameter changes to Dart processor - if (dartInstance) { - dart_vst3_set_parameter(dartInstance, paramQueue->getParameterId(), value); - } - } - } - } - } - - // Process audio - if (data.numInputs == 0 || data.numOutputs == 0) { - return kResultOk; - } - - AudioBusBuffers* input = &data.inputs[0]; - AudioBusBuffers* output = &data.outputs[0]; - - int32 numChannels = input->numChannels; - int32 sampleFrames = data.numSamples; - - if (numChannels > 0 && sampleFrames > 0) { - if (dartInstance && numChannels >= 2) { - // Process stereo audio through Dart - Sample32* inputL = input->channelBuffers32[0]; - Sample32* inputR = input->channelBuffers32[1]; - Sample32* outputL = output->channelBuffers32[0]; - Sample32* outputR = output->channelBuffers32[1]; - - dart_vst3_process_stereo(dartInstance, inputL, inputR, outputL, outputR, sampleFrames); - } else { - // NO FALLBACKS! FAIL HARD! - throw std::runtime_error("VST3 PROCESSOR CRITICAL FAILURE: Dart instance is null or audio is not stereo! Plugin cannot function without proper Dart processor!"); - } - } - - return kResultOk; -} - -tresult {{PLUGIN_CLASS_NAME}}Processor::setState(IBStream* state) { - if (!state) return kResultFalse; - - // Read parameter values -{{PARAMETER_STATE_READ}} - - return kResultOk; -} - -tresult {{PLUGIN_CLASS_NAME}}Processor::getState(IBStream* state) { - if (!state) return kResultFalse; - - // Write parameter values -{{PARAMETER_STATE_WRITE}} - - return kResultOk; -} - -tresult {{PLUGIN_CLASS_NAME}}Processor::getControllerClassId(TUID classId) { - memcpy(classId, k{{PLUGIN_CLASS_NAME}}ControllerUID, sizeof(TUID)); - return kResultTrue; -} - -// Factory functions in proper namespace -namespace Steinberg { -namespace Vst { -namespace {{PLUGIN_CLASS_NAME}} { - FUnknown* createProcessorInstance(void*) { - return (IAudioProcessor*)new {{PLUGIN_CLASS_NAME}}Processor(); - } -} -} -} \ No newline at end of file diff --git a/flutter_vst3/native/templates/plugin_processor_aot.cpp.template b/flutter_vst3/native/templates/plugin_processor_aot.cpp.template index 6f0d1ac..70588c9 100644 --- a/flutter_vst3/native/templates/plugin_processor_aot.cpp.template +++ b/flutter_vst3/native/templates/plugin_processor_aot.cpp.template @@ -1,34 +1,60 @@ // Copyright (c) 2025 -// Auto-generated VST3 processor for {{PLUGIN_NAME}} using AOT-compiled Dart code -// This file is generated automatically by dart_vst3_bridge at build time. +// Auto-generated VST3 processor for {{PLUGIN_NAME}}. +// This file is generated automatically by flutter_vst3 at build time. // DO NOT EDIT - any changes will be overwritten. +// +// Audio runs in a compiled Dart worker process, one per plugin instance, through +// Vst3IpcHost. A failure to start the worker is reported to the host by +// setActive returning an error. The host's session is never brought down. #include "{{PLUGIN_ID}}_ids.h" +#include "pluginterfaces/base/ibstream.h" #include "pluginterfaces/vst/ivstparameterchanges.h" #include "pluginterfaces/vst/ivstprocesscontext.h" -#include "pluginterfaces/base/ibstream.h" #include "public.sdk/source/vst/vstaudioeffect.h" -#include "base/source/fstreamer.h" -// Using native AOT-compiled Dart processor - NO FFI BRIDGE! -extern "C" { - void {{PLUGIN_ID}}_native_initialize(double sample_rate, int max_block_size); - void {{PLUGIN_ID}}_native_process_stereo(float* inputL, float* inputR, float* outputL, float* outputR, int samples); - void {{PLUGIN_ID}}_native_set_parameter(int param_id, double value); - double {{PLUGIN_ID}}_native_get_parameter(int param_id); - void {{PLUGIN_ID}}_native_reset(); - void {{PLUGIN_ID}}_native_dispose(); -} +#include "vst3_ipc_host.h" +#include "vst3_plugin_state.h" + +#include +#include #include -#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif using namespace Steinberg; using namespace Steinberg::Vst; +namespace { +constexpr int32 kParameterCount = {{PARAMETER_COUNT}}; +const std::vector kParameterDefaults{ {{PARAMETER_DEFAULT_VALUES}} }; + +int64 currentProcessIdForMessage() { +#ifdef _WIN32 + return static_cast(GetCurrentProcessId()); +#else + return static_cast(getpid()); +#endif +} + +void silenceBus(AudioBusBuffers& bus, int32 numSamples) { + for (int32 channel = 0; channel < bus.numChannels; ++channel) { + std::memset(bus.channelBuffers32[channel], 0, static_cast(numSamples) * sizeof(Sample32)); + } + bus.silenceFlags = bus.numChannels >= 64 ? ~uint64(0) : (uint64(1) << bus.numChannels) - 1; +} +} // namespace + // Processor for the {{PLUGIN_NAME}} plugin class {{PLUGIN_CLASS_NAME}}Processor : public AudioEffect { public: {{PLUGIN_CLASS_NAME}}Processor(); - virtual ~{{PLUGIN_CLASS_NAME}}Processor() = default; + ~{{PLUGIN_CLASS_NAME}}Processor() override = default; tresult PLUGIN_API initialize(FUnknown* context) override; tresult PLUGIN_API terminate() override; @@ -40,168 +66,165 @@ public: tresult PLUGIN_API setState(IBStream* state) override; tresult PLUGIN_API getState(IBStream* state) override; tresult PLUGIN_API getControllerClassId(TUID classId) override; + uint32 PLUGIN_API getTailSamples() override { return kInfiniteTail; } private: -{{PARAMETER_VARIABLES}} - double sampleRate = 44100.0; - - // Native AOT processor - NO MORE DART RUNTIME DEPENDENCY! - bool nativeProcessorInitialized = false; + void applyParameterChanges(ProcessData& data); + void forwardStateIfChanged(); + void sendMemoryAddress(void* address); + + std::vector> parameterValues_; + std::atomic stateChanged_{true}; + double sampleRate_ = 44100.0; + int32 maxBlockSize_ = 4096; + bool offline_ = false; + bool active_ = false; + std::unique_ptr host_; }; -{{PLUGIN_CLASS_NAME}}Processor::{{PLUGIN_CLASS_NAME}}Processor() { +{{PLUGIN_CLASS_NAME}}Processor::{{PLUGIN_CLASS_NAME}}Processor() : parameterValues_(kParameterCount) { setControllerClass(k{{PLUGIN_CLASS_NAME}}ControllerUID); - - // ARCHITECTURE FIXED: Using AOT-compiled native Dart code - NO RUNTIME DEPENDENCY! - nativeProcessorInitialized = false; -{{PARAMETER_DEFAULTS}} + for (int32 i = 0; i < kParameterCount; ++i) { + parameterValues_[static_cast(i)].store(kParameterDefaults[static_cast(i)]); + } } tresult {{PLUGIN_CLASS_NAME}}Processor::initialize(FUnknown* context) { tresult result = AudioEffect::initialize(context); if (result != kResultTrue) return result; - // Configure audio buses - stereo in/out by default addAudioInput(STR16("Stereo In"), SpeakerArr::kStereo); addAudioOutput(STR16("Stereo Out"), SpeakerArr::kStereo); - + try { + host_ = std::make_unique(vst3WorkerPathNextToModule("{{PLUGIN_ID}}_processor"), kParameterCount); + } catch (const std::exception& error) { + std::fprintf(stderr, "{{PLUGIN_ID}}: %s\n", error.what()); + return kResultFalse; + } return kResultTrue; } tresult {{PLUGIN_CLASS_NAME}}Processor::terminate() { - if (nativeProcessorInitialized) { - {{PLUGIN_ID}}_native_dispose(); - nativeProcessorInitialized = false; - } + sendMemoryAddress(nullptr); + host_.reset(); return AudioEffect::terminate(); } +void {{PLUGIN_CLASS_NAME}}Processor::sendMemoryAddress(void* address) { + IMessage* message = allocateMessage(); + if (!message) return; + message->setMessageID("Vst3Shm"); + message->getAttributes()->setInt("address", static_cast(reinterpret_cast(address))); + message->getAttributes()->setInt("pid", currentProcessIdForMessage()); + sendMessage(message); + message->release(); +} + tresult {{PLUGIN_CLASS_NAME}}Processor::setActive(TBool state) { - if (state) { - // Plugin activated - TRY to initialize native AOT processor and FAIL HARD if it doesn't work - try { - {{PLUGIN_ID}}_native_initialize(sampleRate, 512); - nativeProcessorInitialized = true; - } catch (const std::exception& e) { - // FAIL HARD! CRASH THE WHOLE DAW! - fprintf(stderr, "{{PLUGIN_ID}} CRITICAL FAILURE: AOT processor initialization failed: %s\n", e.what()); - fprintf(stderr, "THIS PLUGIN REQUIRES WORKING AOT COMPILATION!\n"); - fflush(stderr); - abort(); // CRASH THE DAW - NO SILENT FAILURES! - } - } else { - // Plugin deactivated - reset native processor - if (nativeProcessorInitialized) { - try { - {{PLUGIN_ID}}_native_reset(); - } catch (...) { - // Even cleanup failures should crash - abort(); - } + if (!host_) return kNotInitialized; + try { + if (state) { + host_->configure(sampleRate_, maxBlockSize_, offline_); + stateChanged_.store(true); + sendMemoryAddress(host_->memory()); + } else { + sendMemoryAddress(nullptr); + host_->reset(); } + } catch (const std::exception& error) { + std::fprintf(stderr, "{{PLUGIN_ID}}: %s\n", error.what()); + active_ = false; + return kResultFalse; } + active_ = state != 0; return AudioEffect::setActive(state); } tresult {{PLUGIN_CLASS_NAME}}Processor::setupProcessing(ProcessSetup& setup) { - sampleRate = setup.sampleRate; + sampleRate_ = setup.sampleRate; + maxBlockSize_ = setup.maxSamplesPerBlock; + offline_ = setup.processMode == kOffline; return AudioEffect::setupProcessing(setup); } tresult {{PLUGIN_CLASS_NAME}}Processor::setBusArrangements(SpeakerArrangement* inputs, int32 numIns, SpeakerArrangement* outputs, int32 numOuts) { - // Only accept stereo input/output if (numIns == 1 && numOuts == 1 && inputs[0] == SpeakerArr::kStereo && outputs[0] == SpeakerArr::kStereo) { return AudioEffect::setBusArrangements(inputs, numIns, outputs, numOuts); } return kResultFalse; } -tresult {{PLUGIN_CLASS_NAME}}Processor::process(ProcessData& data) { - // Process parameter changes - if (data.inputParameterChanges) { - int32 numParamsChanged = data.inputParameterChanges->getParameterCount(); - for (int32 i = 0; i < numParamsChanged; i++) { - IParamValueQueue* paramQueue = data.inputParameterChanges->getParameterData(i); - if (paramQueue) { - ParamValue value; - int32 sampleOffset; - int32 numPoints = paramQueue->getPointCount(); - - if (paramQueue->getPoint(numPoints - 1, sampleOffset, value) == kResultTrue) { - // Forward parameter changes to native AOT processor - if (nativeProcessorInitialized) { - {{PLUGIN_ID}}_native_set_parameter(paramQueue->getParameterId(), value); - } - } - } - } +/// Parameters apply per block, so only the last point in each queue is used. +void {{PLUGIN_CLASS_NAME}}Processor::applyParameterChanges(ProcessData& data) { + if (!data.inputParameterChanges) return; + const int32 count = data.inputParameterChanges->getParameterCount(); + for (int32 i = 0; i < count; ++i) { + IParamValueQueue* queue = data.inputParameterChanges->getParameterData(i); + if (!queue || queue->getPointCount() == 0) continue; + ParamValue value = 0.0; + int32 sampleOffset = 0; + if (queue->getPoint(queue->getPointCount() - 1, sampleOffset, value) != kResultTrue) continue; + const ParamID id = queue->getParameterId(); + if (id >= static_cast(kParameterCount)) continue; + parameterValues_[id].store(value); + host_->setParameter(static_cast(id), value); } +} - // Process audio - if (data.numInputs == 0 || data.numOutputs == 0) { - return kResultOk; +/// setState runs on another thread, and only this thread may talk to the worker. +void {{PLUGIN_CLASS_NAME}}Processor::forwardStateIfChanged() { + if (!stateChanged_.exchange(false)) return; + for (int32 i = 0; i < kParameterCount; ++i) { + host_->setParameter(i, parameterValues_[static_cast(i)].load()); } +} - AudioBusBuffers* input = &data.inputs[0]; - AudioBusBuffers* output = &data.outputs[0]; - - int32 numChannels = input->numChannels; - int32 sampleFrames = data.numSamples; - - if (numChannels > 0 && sampleFrames > 0) { - if (nativeProcessorInitialized && numChannels >= 2) { - // Process stereo audio through AOT-compiled native Dart code - ZERO FFI OVERHEAD! - Sample32* inputL = input->channelBuffers32[0]; - Sample32* inputR = input->channelBuffers32[1]; - Sample32* outputL = output->channelBuffers32[0]; - Sample32* outputR = output->channelBuffers32[1]; - - try { - {{PLUGIN_ID}}_native_process_stereo(inputL, inputR, outputL, outputR, sampleFrames); - } catch (const std::exception& e) { - // FAIL HARD! CRASH THE WHOLE DAW! - fprintf(stderr, "{{PLUGIN_ID}} CRITICAL FAILURE: Audio processing failed: %s\n", e.what()); - fflush(stderr); - abort(); // CRASH THE DAW - NO SILENT FAILURES! - } - } else { - // NO FALLBACKS! FAIL HARD! CRASH THE DAW! - fprintf(stderr, "VST3 PROCESSOR CRITICAL FAILURE: Native AOT processor not initialized or audio is not stereo!\n"); - fprintf(stderr, "nativeProcessorInitialized: %s, numChannels: %d\n", - nativeProcessorInitialized ? "true" : "false", numChannels); - fflush(stderr); - abort(); // CRASH THE WHOLE DAW! - } +tresult {{PLUGIN_CLASS_NAME}}Processor::process(ProcessData& data) { + if (!host_ || !active_) { + for (int32 bus = 0; bus < data.numOutputs; ++bus) silenceBus(data.outputs[bus], data.numSamples); + return kNotInitialized; } + forwardStateIfChanged(); + applyParameterChanges(data); + if (data.numSamples <= 0 || data.numOutputs == 0) return kResultOk; + AudioBusBuffers& output = data.outputs[0]; + if (data.numInputs == 0 || data.inputs[0].numChannels < 2 || output.numChannels < 2) { + silenceBus(output, data.numSamples); + return kResultOk; + } + AudioBusBuffers& input = data.inputs[0]; + const bool complete = host_->process(input.channelBuffers32[0], input.channelBuffers32[1], + output.channelBuffers32[0], output.channelBuffers32[1], data.numSamples); + output.silenceFlags = complete ? 0 : 3; return kResultOk; } tresult {{PLUGIN_CLASS_NAME}}Processor::setState(IBStream* state) { - if (!state) return kResultFalse; - - // Read parameter values -{{PARAMETER_STATE_READ}} - + std::vector values; + if (!vst3ReadPluginState(state, kParameterCount, values)) return kResultFalse; + for (int32 i = 0; i < kParameterCount; ++i) { + parameterValues_[static_cast(i)].store(values[static_cast(i)]); + } + stateChanged_.store(true); return kResultOk; } tresult {{PLUGIN_CLASS_NAME}}Processor::getState(IBStream* state) { if (!state) return kResultFalse; - - // Write parameter values -{{PARAMETER_STATE_WRITE}} - + for (auto& parameter : parameterValues_) { + if (!vst3WritePluginStateValue(state, parameter.load())) return kResultFalse; + } return kResultOk; } tresult {{PLUGIN_CLASS_NAME}}Processor::getControllerClassId(TUID classId) { - memcpy(classId, k{{PLUGIN_CLASS_NAME}}ControllerUID, sizeof(TUID)); + k{{PLUGIN_CLASS_NAME}}ControllerUID.toTUID(classId); return kResultTrue; } -// Factory functions in proper namespace +// Factory functions in proper namespace namespace Steinberg { namespace Vst { namespace {{PLUGIN_CLASS_NAME}} { @@ -210,4 +233,4 @@ namespace {{PLUGIN_CLASS_NAME}} { } } } -} \ No newline at end of file +} diff --git a/flutter_vst3/native/templates/plugin_processor_native.cpp.template b/flutter_vst3/native/templates/plugin_processor_native.cpp.template deleted file mode 100644 index 7a454ab..0000000 --- a/flutter_vst3/native/templates/plugin_processor_native.cpp.template +++ /dev/null @@ -1,291 +0,0 @@ -// WORKING NATIVE PROCESSOR - NO AOT BULLSHIT! -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 - #include -#else - #include - #include -#endif - -constexpr uint8_t CMD_INIT = 0x01; -constexpr uint8_t CMD_PROCESS = 0x02; -constexpr uint8_t CMD_SET_PARAM = 0x03; -constexpr uint8_t CMD_TERMINATE = 0xFF; - -// Forward declaration to get address for dladdr -static void dummy_function() {} - -class {{PLUGIN_CLASS_NAME}}NativeProcessor { -private: - FILE* to_dart = nullptr; - FILE* from_dart = nullptr; - bool initialized = false; - std::mutex io_mutex; - std::string dart_exe_path; - -#ifdef _WIN32 - HANDLE hProcess = NULL; -#else - pid_t child_pid = -1; -#endif - - std::string getExecutablePath() { - // Use dladdr to get the path of the current shared object (VST3 binary) - Dl_info dl_info; - if (dladdr((void*)&dummy_function, &dl_info) != 0) { - char* path_copy = strdup(dl_info.dli_fname); - char* dir = dirname(path_copy); - std::string dart_path = std::string(dir) + "/{{PLUGIN_ID}}_processor"; - - // fprintf(stderr, "{{PLUGIN_NAME_UPPER}}: VST3 binary at: %s\n", dl_info.dli_fname); - // fprintf(stderr, "{{PLUGIN_NAME_UPPER}}: Looking for Dart executable at: %s\n", dart_path.c_str()); - - free(path_copy); - return dart_path; - } - throw std::runtime_error("FAILED TO GET VST3 BINARY PATH!"); - } - -public: - void initialize(double sampleRate, int maxBlockSize) { - if (initialized) return; - - // Get path to Dart executable relative to VST3 binary - dart_exe_path = getExecutablePath(); - - // SPAWN THE DART EXECUTABLE -#ifdef _WIN32 - // Windows implementation - SECURITY_ATTRIBUTES sa; - sa.nLength = sizeof(SECURITY_ATTRIBUTES); - sa.bInheritHandle = TRUE; - sa.lpSecurityDescriptor = NULL; - - HANDLE stdin_r, stdin_w, stdout_r, stdout_w; - CreatePipe(&stdin_r, &stdin_w, &sa, 0); - CreatePipe(&stdout_r, &stdout_w, &sa, 0); - SetHandleInformation(stdin_w, HANDLE_FLAG_INHERIT, 0); - SetHandleInformation(stdout_r, HANDLE_FLAG_INHERIT, 0); - - STARTUPINFO si = {0}; - si.cb = sizeof(STARTUPINFO); - si.hStdInput = stdin_r; - si.hStdOutput = stdout_w; - si.hStdError = stdout_w; - si.dwFlags = STARTF_USESTDHANDLES; - - PROCESS_INFORMATION pi; - if (!CreateProcess("{{PLUGIN_ID}}_processor.exe", NULL, NULL, NULL, - TRUE, 0, NULL, NULL, &si, &pi)) { - throw std::runtime_error("FAILED TO START {{PLUGIN_ID}}_processor.exe!"); - } - - hProcess = pi.hProcess; - CloseHandle(pi.hThread); - CloseHandle(stdin_r); - CloseHandle(stdout_w); - - to_dart = _fdopen(_open_osfhandle((intptr_t)stdin_w, 0), "wb"); - from_dart = _fdopen(_open_osfhandle((intptr_t)stdout_r, 0), "rb"); -#else - // Unix implementation with bidirectional pipe - int to_child[2], from_child[2]; - if (pipe(to_child) == -1 || pipe(from_child) == -1) { - throw std::runtime_error("FAILED TO CREATE PIPES!"); - } - - child_pid = fork(); - if (child_pid == -1) { - throw std::runtime_error("FAILED TO FORK!"); - } - - if (child_pid == 0) { - // Child process - dup2(to_child[0], STDIN_FILENO); - dup2(from_child[1], STDOUT_FILENO); - close(to_child[0]); - close(to_child[1]); - close(from_child[0]); - close(from_child[1]); - - // fprintf(stderr, "{{PLUGIN_NAME_UPPER}}: Child process executing: %s\n", dart_exe_path.c_str()); - // fflush(stderr); - execl(dart_exe_path.c_str(), "{{PLUGIN_ID}}_processor", nullptr); - // fprintf(stderr, "{{PLUGIN_NAME_UPPER}}: exec failed!\n"); - // fflush(stderr); - exit(1); // exec failed - } - - // Parent process - close(to_child[0]); - close(from_child[1]); - to_dart = fdopen(to_child[1], "wb"); - from_dart = fdopen(from_child[0], "rb"); -#endif - - // Send init command - uint8_t init_msg[9]; - init_msg[0] = CMD_INIT; - memcpy(&init_msg[1], &sampleRate, sizeof(double)); - - fwrite(init_msg, 1, 9, to_dart); - fflush(to_dart); - - // Wait for ACK - uint8_t ack; - if (fread(&ack, 1, 1, from_dart) != 1 || ack != CMD_INIT) { - throw std::runtime_error("DART PROCESS FAILED TO INITIALIZE!"); - } - - initialized = true; - } - - void processStereo(float* inputL, float* inputR, - float* outputL, float* outputR, int numSamples) { - if (!initialized) { - throw std::runtime_error("NOT INITIALIZED!"); - } - - std::lock_guard lock(io_mutex); - - // Create message - size_t msg_size = 5 + numSamples * 8; - std::vector message(msg_size); - - message[0] = CMD_PROCESS; - memcpy(&message[1], &numSamples, sizeof(int32_t)); - - // Interleave audio - float* data = (float*)&message[5]; - for (int i = 0; i < numSamples; i++) { - data[i * 2] = inputL[i]; - data[i * 2 + 1] = inputR[i]; - } - - // Send to Dart - if (fwrite(message.data(), 1, msg_size, to_dart) != msg_size) { - throw std::runtime_error("FAILED TO SEND AUDIO TO DART!"); - } - fflush(to_dart); - - // Read response - uint8_t response_cmd; - if (fread(&response_cmd, 1, 1, from_dart) != 1 || response_cmd != CMD_PROCESS) { - throw std::runtime_error("INVALID RESPONSE FROM DART!"); - } - - // Read processed audio - std::vector processed(numSamples * 2); - if (fread(processed.data(), sizeof(float), numSamples * 2, from_dart) != numSamples * 2) { - throw std::runtime_error("FAILED TO READ PROCESSED AUDIO!"); - } - - // De-interleave - for (int i = 0; i < numSamples; i++) { - outputL[i] = processed[i * 2]; - outputR[i] = processed[i * 2 + 1]; - } - } - - void setParameter(int paramId, double value) { - if (!initialized) return; - - uint8_t msg[13]; - msg[0] = CMD_SET_PARAM; - memcpy(&msg[1], ¶mId, sizeof(int32_t)); - memcpy(&msg[5], &value, sizeof(double)); - - fwrite(msg, 1, 13, to_dart); - fflush(to_dart); - - uint8_t ack; - fread(&ack, 1, 1, from_dart); - } - - void reset() { - // Implemented if needed - } - - void dispose() { - if (!initialized) return; - - uint8_t term = CMD_TERMINATE; - fwrite(&term, 1, 1, to_dart); - fflush(to_dart); - - fclose(to_dart); - fclose(from_dart); - -#ifdef _WIN32 - WaitForSingleObject(hProcess, 5000); - CloseHandle(hProcess); -#else - int status; - waitpid(child_pid, &status, 0); -#endif - - initialized = false; - } - - ~{{PLUGIN_CLASS_NAME}}NativeProcessor() { - dispose(); - } -}; - -// Global instance -static {{PLUGIN_CLASS_NAME}}NativeProcessor* g_processor = nullptr; - -// C interface -extern "C" { - void {{PLUGIN_ID}}_native_initialize(double sample_rate, int max_block_size) { - try { - if (!g_processor) g_processor = new {{PLUGIN_CLASS_NAME}}NativeProcessor(); - g_processor->initialize(sample_rate, max_block_size); - } catch (const std::exception& e) { - fprintf(stderr, "{{PLUGIN_NAME_UPPER}} NATIVE FAILURE: %s\n", e.what()); - abort(); // FAIL HARD! - } - } - - void {{PLUGIN_ID}}_native_process_stereo(float* inputL, float* inputR, - float* outputL, float* outputR, int samples) { - try { - if (!g_processor) throw std::runtime_error("NOT INITIALIZED!"); - g_processor->processStereo(inputL, inputR, outputL, outputR, samples); - } catch (const std::exception& e) { - fprintf(stderr, "{{PLUGIN_NAME_UPPER}} NATIVE FAILURE: %s\n", e.what()); - abort(); // FAIL HARD! - } - } - - void {{PLUGIN_ID}}_native_set_parameter(int param_id, double value) { - if (g_processor) g_processor->setParameter(param_id, value); - } - - double {{PLUGIN_ID}}_native_get_parameter(int param_id) { - return 0.0; // Implement if needed - } - - void {{PLUGIN_ID}}_native_reset() { - if (g_processor) g_processor->reset(); - } - - void {{PLUGIN_ID}}_native_dispose() { - if (g_processor) { - g_processor->dispose(); - delete g_processor; - g_processor = nullptr; - } - } -} \ No newline at end of file diff --git a/flutter_vst3/pubspec.lock b/flutter_vst3/pubspec.lock index 7b96e61..7db7986 100644 --- a/flutter_vst3/pubspec.lock +++ b/flutter_vst3/pubspec.lock @@ -41,6 +41,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" cli_config: dependency: transitive description: @@ -49,6 +57,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.2.0" + clock: + dependency: transitive + description: + name: clock + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e + url: "https://pub.dev" + source: hosted + version: "1.1.3" collection: dependency: transitive description: @@ -81,6 +97,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.6" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" ffi: dependency: "direct main" description: @@ -97,6 +121,16 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" frontend_server_client: dependency: transitive description: @@ -137,14 +171,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.5" - js: + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: dependency: transitive description: - name: js - sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" url: "https://pub.dev" source: hosted - version: "0.7.2" + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" lints: dependency: "direct dev" description: @@ -165,18 +215,26 @@ packages: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.20" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" meta: dependency: transitive description: name: meta - sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" url: "https://pub.dev" source: hosted - version: "1.17.0" + version: "1.19.0" mime: dependency: transitive description: @@ -257,6 +315,11 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" source_map_stack_trace: dependency: transitive description: @@ -317,26 +380,26 @@ packages: dependency: "direct dev" description: name: test - sha256: "75906bf273541b676716d1ca7627a17e4c4070a3a16272b7a3dc7da3b9f3f6b7" + sha256: ca578dc12bb8b2f40b67b7d3bd2fac4f31c01a6ff7130a14e2597b919934507f url: "https://pub.dev" source: hosted - version: "1.26.3" + version: "1.31.1" test_api: dependency: transitive description: name: test_api - sha256: ab2726c1a94d3176a45960b6234466ec367179b87dd74f1611adb1f3b5fb9d55 + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" url: "https://pub.dev" source: hosted - version: "0.7.7" + version: "0.7.12" test_core: dependency: transitive description: name: test_core - sha256: "0cc24b5ff94b38d2ae73e1eb43cc302b77964fbf67abad1e296025b78deb53d0" + sha256: d2e98ec12998368dc59ddd47ab709f2cd55acd6b66dc7db764455a44082f4bc5 url: "https://pub.dev" source: hosted - version: "0.6.12" + version: "0.6.18" typed_data: dependency: transitive description: @@ -345,6 +408,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d" + url: "https://pub.dev" + source: hosted + version: "2.4.3" vm_service: dependency: transitive description: @@ -402,4 +473,5 @@ packages: source: hosted version: "3.1.3" sdks: - dart: ">=3.7.0 <4.0.0" + dart: ">=3.11.0-0 <4.0.0" + flutter: ">=3.27.0" diff --git a/flutter_vst3/pubspec.yaml b/flutter_vst3/pubspec.yaml index 413415e..57dc4e9 100644 --- a/flutter_vst3/pubspec.yaml +++ b/flutter_vst3/pubspec.yaml @@ -15,11 +15,16 @@ platforms: linux: environment: - sdk: '>=3.0.0 <4.0.0' + sdk: '>=3.6.0 <4.0.0' + flutter: '>=3.27.0' dependencies: + flutter: + sdk: flutter ffi: ^2.1.0 dev_dependencies: + flutter_test: + sdk: flutter test: ^1.24.0 lints: ^4.0.0 \ No newline at end of file diff --git a/flutter_vst3/scripts/generate_plugin.dart b/flutter_vst3/scripts/generate_plugin.dart index ff57d70..9dc6b39 100644 --- a/flutter_vst3/scripts/generate_plugin.dart +++ b/flutter_vst3/scripts/generate_plugin.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'dart:io'; +/// Generates native plugin sources from the command-line metadata directory. void main(List args) { if (args.length < 3 || args.length > 4) { print('USAGE: generate_plugin.dart [build_dir]'); @@ -23,6 +24,7 @@ void main(List args) { } } +/// Writes native sources and CMake metadata, rejecting unsupported metadata. void generatePluginFiles(String pluginDir, String pluginName, String targetName, String? buildDir) { // Read metadata JSON final metadataFile = File('$pluginDir/plugin_metadata.json'); @@ -42,6 +44,12 @@ void generatePluginFiles(String pluginDir, String pluginName, String targetName, final parameters = (metadata['parameters'] as List? ?? []) .cast>(); + _validateParameterIds(parameters); + _validateNames(parameters); + _validateTarget(targetName); + _validateTarget(pluginName); + _validateMetadata(metadata, parameters); + _validateUids(metadata); // Generate files final genDir = buildDir != null @@ -61,16 +69,16 @@ void generatePluginFiles(String pluginDir, String pluginName, String targetName, // Base replacements final replacements = { - '{{PLUGIN_NAME}}': metadata['pluginName'], + '{{PLUGIN_NAME}}': _cpp(metadata['pluginName']), '{{PLUGIN_NAME_UPPER}}': pluginName.toUpperCase(), '{{PLUGIN_NAME_CAMEL}}': pluginClass, '{{PLUGIN_CLASS_NAME}}': pluginClass, '{{PLUGIN_ID}}': pluginName, - '{{COMPANY_NAME}}': metadata['vendor'], - '{{PLUGIN_URL}}': metadata['companyWeb'], - '{{PLUGIN_EMAIL}}': metadata['companyEmail'], - '{{PLUGIN_CATEGORY}}': metadata['category'], - '{{PLUGIN_VERSION}}': metadata['version'], + '{{COMPANY_NAME}}': _cpp(metadata['vendor']), + '{{PLUGIN_URL}}': _cpp(metadata['companyWeb']), + '{{PLUGIN_EMAIL}}': _cpp(metadata['companyEmail']), + '{{PLUGIN_CATEGORY}}': _cpp(metadata['category']), + '{{PLUGIN_VERSION}}': _cpp(metadata['version']), }; // Add generated C++ code @@ -81,7 +89,6 @@ void generatePluginFiles(String pluginDir, String pluginName, String targetName, ('plugin_controller.cpp.template', '${targetName}_controller.cpp'), ('plugin_processor_aot.cpp.template', '${targetName}_processor.cpp'), ('plugin_factory.cpp.template', '${targetName}_factory.cpp'), - ('plugin_processor_native.cpp.template', '${targetName}_processor_native.cpp') ]; for (final template in templates) { @@ -89,8 +96,7 @@ void generatePluginFiles(String pluginDir, String pluginName, String targetName, final outputFile = File('${genDir.path}/${template.$2}'); if (!templateFile.existsSync()) { - print('WARNING: Template missing: ${templateFile.path}'); - continue; + throw Exception('Template missing: ${templateFile.path}'); } var content = templateFile.readAsStringSync(); @@ -119,68 +125,55 @@ void generatePluginFiles(String pluginDir, String pluginName, String targetName, print('Generated ${parameters.length} parameter(s)'); } +/// Title-cases the parameter's name: underscores become spaces and every +/// word starts uppercase. +String _parameterTitle(Map p) => + (p['name'] as String).replaceAll('_', ' ').split(' ').map((word) => word.isEmpty ? '' : word[0].toUpperCase() + word.substring(1)).join(' '); + Map _generateCppSnippets(List> parameters, Map metadata, String pluginName) { if (parameters.isEmpty) { return { '{{PARAMETER_COUNT}}': '0', - '{{PARAMETER_VARIABLES}}': ' // No parameters', - '{{PARAMETER_DEFAULTS}}': ' // No parameters to initialize', + '{{PARAMETER_DEFAULT_VALUES}}': '', '{{PARAMETER_CONTROLLER_INIT}}': ' // No parameters to add', '{{PARAMETER_STATE_SAVE}}': ' // No parameters to save', '{{PARAMETER_STATE_LOAD}}': ' // No parameters to load', '{{GET_PARAMETER_INFO}}': ' return kResultFalse;', '{{NORMALIZE_PARAMETER}}': ' return normalizedValue;', '{{DENORMALIZE_PARAMETER}}': ' return plainValue;', - '{{STRING_TO_PARAMETER}}': ' return false;', - '{{PARAMETER_TO_STRING}}': ' return false;', + '{{STRING_TO_PARAMETER}}': ' return EditController::getParamValueByString(id, string, valueNormalized);', + '{{PARAMETER_TO_STRING}}': ' return EditController::getParamStringByValue(id, valueNormalized, string);', }; } - // Generate parameter variables - final paramVars = parameters.map((p) => ' double ${p['name']} = ${p['defaultValue']};').join('\n'); - - // Generate parameter initialization - final paramDefaults = parameters.map((p) => ' ${p['name']} = ${p['defaultValue']};').join('\n'); - // Generate controller parameter registration final controllerInit = parameters.map((p) { - final title = (p['name'] as String).replaceAll('_', ' ').split(' ').map((word) => word.isEmpty ? '' : word[0].toUpperCase() + word.substring(1)).join(' '); - return ' parameters.addParameter(STR16("$title"), STR16("${p['units']}"), 0, ${p['defaultValue']}, ParameterInfo::kCanAutomate, ${p['id']});'; + return ' parameters.addParameter(STR16("${_cpp(_parameterTitle(p))}"), STR16("${_cpp(p['units'])}"), 0, ${p['defaultValue']}, ParameterInfo::kCanAutomate, ${p['id']});'; }).join('\n'); - + // Generate parameter info getter final paramInfoCases = parameters.map((p) { - final title = (p['name'] as String).replaceAll('_', ' ').split(' ').map((word) => word.isEmpty ? '' : word[0].toUpperCase() + word.substring(1)).join(' '); + final title = _parameterTitle(p); return ''' case ${p['id']}: info.id = ${p['id']}; - info.title = STR16("$title"); - info.shortTitle = STR16("$title"); - info.units = STR16("${p['units']}"); + info.title = STR16("${_cpp(title)}"); + info.shortTitle = STR16("${_cpp(title)}"); + info.units = STR16("${_cpp(p['units'])}"); info.stepCount = 0; info.defaultNormalizedValue = ${p['defaultValue']}; info.flags = ParameterInfo::kCanAutomate; return kResultTrue;'''; }).join('\n'); - // Generate state read/write - final stateRead = parameters.map((p) => ''' // Read ${p['name']} - if (state->read(&${p['name']}, sizeof(${p['name']}), &bytesRead) != kResultTrue) return kResultFalse;''').join('\n'); - - final stateWrite = parameters.map((p) => ''' // Write ${p['name']} - if (state->write(&${p['name']}, sizeof(${p['name']}), &bytesWritten) != kResultTrue) return kResultFalse;''').join('\n'); - return { '{{PARAMETER_COUNT}}': parameters.length.toString(), - '{{PARAMETER_VARIABLES}}': paramVars, - '{{PARAMETER_DEFAULTS}}': paramDefaults, + '{{PARAMETER_DEFAULT_VALUES}}': parameters.map((p) => '${p['defaultValue']}').join(', '), '{{PARAMETER_CONTROLLER_INIT}}': controllerInit, '{{GET_PARAMETER_INFO}}': paramInfoCases + '\n return kResultFalse;', '{{NORMALIZE_PARAMETER}}': ' return normalizedValue; // Identity for now', '{{DENORMALIZE_PARAMETER}}': ' return plainValue; // Identity for now', - '{{STRING_TO_PARAMETER}}': ' return false; // Not implemented', - '{{PARAMETER_TO_STRING}}': ' return false; // Not implemented', - '{{PARAMETER_STATE_READ}}': parameters.isEmpty ? ' // No parameters to read' : ' int32 bytesRead = 0;\n$stateRead', - '{{PARAMETER_STATE_WRITE}}': parameters.isEmpty ? ' // No parameters to write' : ' int32 bytesWritten = 0;\n$stateWrite', + '{{STRING_TO_PARAMETER}}': ' return EditController::getParamValueByString(id, string, valueNormalized);', + '{{PARAMETER_TO_STRING}}': ' return EditController::getParamStringByValue(id, valueNormalized, string);', }; } @@ -190,15 +183,16 @@ void _generateIdsHeader(Directory genDir, String targetName, String pluginClass, using namespace Steinberg; -// Parameter IDs for ${metadata['pluginName']} +// Parameter IDs for ${_comment(metadata['pluginName'])} enum ${pluginClass}Parameters { ${parameters.map((p) => ' k${_toPascalCase(p['name'] as String)}Param = ${p['id']},').join('\n')} kNumParameters = ${parameters.length} }; -// Plugin UIDs as proper FUID objects (generate proper GUIDs in production) -static const FUID k${pluginClass}ProcessorUID(0xF9D0C991, 0x074C8404, 0x4D825FC5, 0x21E8F92B); -static const FUID k${pluginClass}ControllerUID(0xA0115732, 0x16F06596, 0x4B9846B6, 0x007933D0); +// Pinned in plugin_metadata.json, or derived from the bundle identifier, so they +// are stable and unique per plugin. +static const FUID k${pluginClass}ProcessorUID(${_classUid(metadata, 'processor')}); +static const FUID k${pluginClass}ControllerUID(${_classUid(metadata, 'controller')}); '''; File('${genDir.path}/${targetName}_ids.h').writeAsStringSync(content); @@ -206,6 +200,7 @@ static const FUID k${pluginClass}ControllerUID(0xA0115732, 0x16F06596, 0x4B9846B } void _generateCMakeMetadata(Directory genDir, Map metadata, List> parameters) { + metadata = metadata.map((key, value) => MapEntry(key, value is String ? _cmake(value) : value)); final content = '''set(JSON_PLUGIN_NAME "${metadata['pluginName']}") set(JSON_VENDOR "${metadata['vendor']}") set(JSON_VERSION "${metadata['version']}") @@ -214,11 +209,100 @@ set(JSON_BUNDLE_ID "${metadata['bundleIdentifier']}") set(JSON_WEB "${metadata['companyWeb']}") set(JSON_EMAIL "${metadata['companyEmail']}") set(PARAM_COUNT "${parameters.length}") +set(JSON_FLUTTER_ENTRYPOINT "${metadata['flutterEntrypoint'] ?? ''}") '''; File('${genDir.path}/metadata.cmake').writeAsStringSync(content); } -String _toPascalCase(String input) { - return input.split('_').map((word) => word.isEmpty ? '' : word[0].toUpperCase() + word.substring(1)).join(''); -} \ No newline at end of file +/// Throws unless parameter ids are exactly 0..n-1. The processor, controller and +/// saved state formats all index parameters by id. +void _validateParameterIds(List> parameters) { + for (var i = 0; i < parameters.length; i++) { + if (parameters[i]['id'] != i) { + throw Exception('Parameter ids must be 0..n-1 in order. Index $i has id ${parameters[i]['id']}'); + } + } +} + +/// Returns four comma-separated 32-bit hex words derived from [key] with +/// FNV-1a, for use as a VST3 FUID. The same key always gives the same result. +String pluginUid(String key) { + return List.generate(4, (word) { + var hash = 0x811C9DC5 ^ word; + for (final unit in key.codeUnits) { + hash = ((hash ^ unit) * 0x01000193) & 0xFFFFFFFF; + } + return '0x${hash.toRadixString(16).padLeft(8, '0').toUpperCase()}'; + }).join(', '); +} + +/// A plugin that shipped with a UID pins it in its metadata, because hosts find +/// a plugin in saved projects by UID. Any other plugin gets one from its bundle id. +String _classUid(Map metadata, String kind) => switch (metadata['${kind}Uid']) { + null => pluginUid('${metadata['bundleIdentifier']}:$kind'), + final String uid => [ + for (var word = 0; word < 4; word++) + '0x${uid.substring(word * 8, word * 8 + 8).toUpperCase()}', + ].join(', '), + final other => throw FormatException('Metadata error: ${kind}Uid must be 32 hex digits: $other'), + }; + +void _validateUids(Map metadata) { + final processor = metadata['processorUid']; + final controller = metadata['controllerUid']; + (processor == null) == (controller == null) + ? null : throw const FormatException('Metadata error: processorUid and controllerUid must be set together'); + processor != null && processor == controller + ? throw const FormatException('Metadata error: processorUid and controllerUid must differ') : null; + for (final kind in ['processor', 'controller']) { + final uid = metadata['${kind}Uid']; + uid == null || (uid is String && RegExp(r'^[0-9A-Fa-f]{32}$').hasMatch(uid)) + ? null : throw FormatException('Metadata error: ${kind}Uid must be 32 hex digits: $uid'); + } +} + +String _toPascalCase(String input) => _identifier(input); + +String _identifier(String input) { + final words = input.split(RegExp(r'[^a-zA-Z0-9]+')).where((w) => w.isNotEmpty); + final result = words.map((w) => w[0].toUpperCase() + w.substring(1)).join(); + return RegExp(r'^[A-Za-z][A-Za-z0-9]*$').hasMatch(result) + ? result : throw FormatException('Metadata error: unusable identifier: $input'); +} + +void _validateNames(List> parameters) { + final seen = {'NumParameters'}; + for (final parameter in parameters) { + final name = _identifier(parameter['name'] as String); + seen.add(name) ? null : throw FormatException('Metadata error: duplicate parameter identifier $name'); + } +} + +void _validateTarget(String value) => + RegExp(r'^[A-Za-z_][A-Za-z0-9_]*$').hasMatch(value) + ? null : throw FormatException('Metadata error: invalid target: $value'); + +void _validateMetadata(Map metadata, List> parameters) { + for (final key in ['pluginName', 'vendor', 'version', 'category', 'bundleIdentifier', 'companyWeb', 'companyEmail']) { + _validateText(metadata[key]); + } + for (final p in parameters) { + p['id'] is int ? null : throw const FormatException('Metadata error: parameter id must be an integer'); + _validateText(p['name']); + _validateText(p['units']); + final value = p['defaultValue']; + value is num && value.isFinite && value >= 0 && value <= 1 + ? null : throw FormatException('Metadata error: invalid parameter default: $value'); + } +} + +void _validateText(dynamic value) => value is String && !value.contains(RegExp(r'[\x00-\x1f\x7f]')) + ? null : throw const FormatException('Metadata error: expected text without control characters'); + +String _cpp(dynamic value) => value.toString().replaceAll(r'\', r'\\') + .replaceAll('"', r'\"').replaceAll('\n', r'\n').replaceAll('\r', r'\r'); + +String _comment(dynamic value) => _cpp(value).endsWith(r'\') ? '${_cpp(value)} ' : _cpp(value); + +String _cmake(dynamic value) => _cpp(value).replaceAll(r'$', r'\$').replaceAll(';', r'\;'); \ No newline at end of file diff --git a/flutter_vst3/test/dsp_stopped_test.dart b/flutter_vst3/test/dsp_stopped_test.dart new file mode 100644 index 0000000..360c74b --- /dev/null +++ b/flutter_vst3/test/dsp_stopped_test.dart @@ -0,0 +1,73 @@ +import 'dart:ffi'; + +import 'package:ffi/ffi.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_vst3/src/parameter_binding.dart'; +import 'package:flutter_vst3/src/vst3_shm_layout.dart'; + +const _channel = MethodChannel('flutter_vst3/parameters'); +final _messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('a block with a cleared magic word means the worker died', () async { + final first = calloc(vst3ShmTotalSize); + final second = calloc(vst3ShmTotalSize); + addTearDown(() { + calloc.free(first); + calloc.free(second); + }); + first.cast().value = vst3ShmMagic; + second.cast().value = vst3ShmMagic; + var address = first.address; + _messenger.setMockMethodCallHandler(_channel, (call) async { + return switch (call.method) { + 'getSharedMemoryInfo' => {'address': address}, + 'getInitialParameters' => {}, + _ => null, + }; + }); + final binding = VST3ParameterBinding.getInstance(); + await binding.loadInitialParameters(); + var notified = 0; + void listener() => notified++; + binding.addListener(listener); + addTearDown(() => binding.removeListener(listener)); + Future refresh() => binding.getAudioBufferReader(forceRefresh: true); + + await refresh(); + expect(binding.dspStopped, isFalse); + expect(notified, 0); + + first.cast().value = 0; + await refresh(); + expect(binding.dspStopped, isTrue); + expect(notified, 1); + + await refresh(); + expect(binding.dspStopped, isTrue); + expect(notified, 1, reason: 'no change means no notification'); + + address = second.address; + await refresh(); + expect(binding.dspStopped, isFalse); + expect(notified, 2); + + address = 0; + await refresh(); + expect(binding.dspStopped, isFalse, reason: 'deactivated is not stopped'); + expect(notified, 2); + + address = first.address; + await refresh(); + expect(binding.dspStopped, isTrue); + expect(notified, 3); + + _messenger.setMockMethodCallHandler(_channel, null); + await refresh(); + expect(binding.dspStopped, isTrue, reason: 'no reply changes nothing'); + expect(notified, 3); + }); +} diff --git a/flutter_vst3/test/generate_plugin_test.dart b/flutter_vst3/test/generate_plugin_test.dart new file mode 100644 index 0000000..8a4cd2e --- /dev/null +++ b/flutter_vst3/test/generate_plugin_test.dart @@ -0,0 +1,134 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +Map _metadata({ + String bundle = 'com.test.alpha', + String? entrypoint, + List ids = const [0, 1], +}) => + { + 'pluginName': 'Alpha', + 'vendor': 'Test', + 'version': '1.0.0', + 'category': 'Fx', + 'bundleIdentifier': bundle, + 'companyWeb': 'https://example.com', + 'companyEmail': 'a@example.com', + if (entrypoint != null) 'flutterEntrypoint': entrypoint, + 'parameters': [ + for (final id in ids) + { + 'id': id, + 'name': 'param$id', + 'defaultValue': 0.25, + 'units': '%', + }, + ], + }; + +ProcessResult _generate(Directory dir, Map metadata) { + File('${dir.path}/plugin_metadata.json') + .writeAsStringSync(jsonEncode(metadata)); + return Process.runSync( + 'dart', + ['scripts/generate_plugin.dart', dir.path, 'alpha', 'alpha', dir.path], + ); +} + +String _generated(Directory dir, String name) => + File('${dir.path}/generated/$name').readAsStringSync(); + +void main() { + var dir = Directory.current; + + setUp(() => dir = Directory.systemTemp.createTempSync('vst3_generate')); + tearDown(() => dir.deleteSync(recursive: true)); + + test('generates a processor with no unresolved placeholders', () { + final result = _generate(dir, _metadata()); + expect(result.exitCode, 0, reason: '${result.stdout}'); + final processor = _generated(dir, 'alpha_processor.cpp'); + expect(processor, isNot(contains('{{'))); + expect(processor, contains('kParameterDefaults{ 0.25, 0.25 }')); + expect(processor, contains('vst3WorkerPathNextToModule("alpha_processor")')); + }); + + test('H25: UIDs differ by plugin, and are stable', () { + expect(_generate(dir, _metadata()).exitCode, 0); + final first = _generated(dir, 'alpha_ids.h'); + expect(_generate(dir, _metadata()).exitCode, 0); + expect(_generated(dir, 'alpha_ids.h'), first); + expect(_generate(dir, _metadata(bundle: 'com.test.beta')).exitCode, 0); + final other = _generated(dir, 'alpha_ids.h'); + final uids = RegExp(r'UID\((.*)\);'); + final firstUids = uids.allMatches(first).map((m) => m.group(1)).toList(); + final otherUids = uids.allMatches(other).map((m) => m.group(1)).toList(); + expect(firstUids, hasLength(2)); + expect(firstUids[0], isNot(firstUids[1])); + expect(otherUids[0], isNot(firstUids[0])); + expect(otherUids[1], isNot(firstUids[1])); + }); + + test('H25: a pinned UID is used exactly', () { + final metadata = _metadata() + ..['processorUid'] = 'F9D0C991074C84044D825FC521E8F92B' + ..['controllerUid'] = 'A011573216F065964B9846B6007933D0'; + expect(_generate(dir, metadata).exitCode, 0); + final ids = _generated(dir, 'alpha_ids.h'); + expect(ids, contains('kAlphaProcessorUID(0xF9D0C991, 0x074C8404, 0x4D825FC5, 0x21E8F92B);')); + expect(ids, contains('kAlphaControllerUID(0xA0115732, 0x16F06596, 0x4B9846B6, 0x007933D0);')); + }); + + test('H25: a bad pinned UID is rejected', () { + const good = 'F9D0C991074C84044D825FC521E8F92B'; + const other = 'A011573216F065964B9846B6007933D0'; + final cases = <(Map, String)>[ + ({'processorUid': good}, 'processorUid and controllerUid must be set together'), + ({'controllerUid': good}, 'processorUid and controllerUid must be set together'), + ({'processorUid': good, 'controllerUid': good}, 'processorUid and controllerUid must differ'), + ({'processorUid': 'F9D0', 'controllerUid': other}, 'processorUid must be 32 hex digits'), + ({'processorUid': good, 'controllerUid': 'not hex at all, but thirty two!!'}, 'controllerUid must be 32 hex digits'), + ({'processorUid': 7, 'controllerUid': other}, 'processorUid must be 32 hex digits'), + ]; + for (final (uids, message) in cases) { + final result = _generate(dir, _metadata()..addAll(uids)); + expect(result.exitCode, isNot(0), reason: '$uids'); + expect('${result.stdout}', contains(message)); + } + }); + + test('H25: Echo keeps its original UIDs, and Reverb has its own', () { + Map real(String name) => + jsonDecode(File('../vsts/$name/plugin_metadata.json').readAsStringSync()) + as Map; + expect(_generate(dir, real('echo')).exitCode, 0); + final echo = _generated(dir, 'alpha_ids.h'); + expect(echo, contains('ProcessorUID(0xF9D0C991, 0x074C8404, 0x4D825FC5, 0x21E8F92B);')); + expect(echo, contains('ControllerUID(0xA0115732, 0x16F06596, 0x4B9846B6, 0x007933D0);')); + expect(_generate(dir, real('flutter_reverb')).exitCode, 0); + final reverb = _generated(dir, 'alpha_ids.h'); + expect(reverb, isNot(contains('0xF9D0C991, 0x074C8404, 0x4D825FC5, 0x21E8F92B'))); + expect(reverb, isNot(contains('0xA0115732, 0x16F06596, 0x4B9846B6, 0x007933D0'))); + }); + + test('B12: the Flutter entrypoint reaches the CMake metadata', () { + expect(_generate(dir, _metadata(entrypoint: 'alphaMain')).exitCode, 0); + expect( + _generated(dir, 'metadata.cmake'), + contains('set(JSON_FLUTTER_ENTRYPOINT "alphaMain")'), + ); + expect(_generate(dir, _metadata()).exitCode, 0); + expect( + _generated(dir, 'metadata.cmake'), + contains('set(JSON_FLUTTER_ENTRYPOINT "")'), + ); + }); + + test('rejects parameter ids that are not 0..n-1', () { + final result = _generate(dir, _metadata(ids: [0, 2])); + expect(result.exitCode, isNot(0)); + expect('${result.stdout}', contains('Parameter ids must be 0..n-1')); + }); +} diff --git a/flutter_vst3/test/native/CMakeLists.txt b/flutter_vst3/test/native/CMakeLists.txt new file mode 100644 index 0000000..649cad1 --- /dev/null +++ b/flutter_vst3/test/native/CMakeLists.txt @@ -0,0 +1,67 @@ +# Builds plugin_host_test, which loads a real .vst3 bundle through the SDK's +# hosting classes. VST3_SDK_DIR must point at the Steinberg VST3 SDK. +cmake_minimum_required(VERSION 3.20) +project(flutter_vst3_plugin_host_test LANGUAGES C CXX) +if(APPLE) + enable_language(OBJC OBJCXX) +endif() + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE) +endif() + +if(NOT DEFINED ENV{VST3_SDK_DIR}) + message(FATAL_ERROR "Set VST3_SDK_DIR to the Steinberg VST3 SDK") +endif() +file(TO_CMAKE_PATH "$ENV{VST3_SDK_DIR}" VST3_SDK_DIR) + +set(SMTG_ADD_VSTGUI OFF CACHE BOOL "" FORCE) +set(SMTG_ENABLE_VSTGUI_SUPPORT OFF CACHE BOOL "" FORCE) +set(SMTG_ADD_VST3_PLUGINS_SAMPLES OFF CACHE BOOL "" FORCE) +set(SMTG_ADD_VST3_HOSTING_SAMPLES OFF CACHE BOOL "" FORCE) +set(SMTG_RUN_VST_VALIDATOR OFF CACHE BOOL "" FORCE) +set(SMTG_CREATE_MODULE_INFO OFF CACHE BOOL "" FORCE) +add_subdirectory(${VST3_SDK_DIR} ${CMAKE_CURRENT_BINARY_DIR}/vst3sdk EXCLUDE_FROM_ALL) + +add_executable(plugin_host_test plugin_host_test.cpp) +target_link_libraries(plugin_host_test PRIVATE sdk_hosting sdk_common pluginterfaces base) +target_include_directories(plugin_host_test PRIVATE ${VST3_SDK_DIR}) + +# The SDK leaves these out of sdk_hosting, for hosts to add themselves. +set(hosting_dir ${VST3_SDK_DIR}/public.sdk/source/vst/hosting) +target_sources(plugin_host_test PRIVATE + ${VST3_SDK_DIR}/public.sdk/source/common/memorystream.cpp + ${hosting_dir}/module.cpp +) +if(WIN32) + target_sources(plugin_host_test PRIVATE ${hosting_dir}/module_win32.cpp) +elseif(APPLE) + target_sources(plugin_host_test PRIVATE ${hosting_dir}/module_mac.mm) + set_source_files_properties(${hosting_dir}/module_mac.mm PROPERTIES COMPILE_FLAGS -fobjc-arc) + target_link_libraries(plugin_host_test PRIVATE "-framework Foundation" "-framework CoreFoundation") +else() + target_sources(plugin_host_test PRIVATE ${hosting_dir}/module_linux.cpp) + target_link_libraries(plugin_host_test PRIVATE ${CMAKE_DL_LIBS} stdc++fs) +endif() + +add_executable(editor_liveness_test editor_liveness_test.cpp) +add_executable(editor_host_test editor_host_test.cpp ${hosting_dir}/module.cpp + ${VST3_SDK_DIR}/public.sdk/source/common/memorystream.cpp) +target_include_directories(editor_host_test PRIVATE ${VST3_SDK_DIR}) +target_link_libraries(editor_host_test PRIVATE sdk sdk_hosting sdk_common pluginterfaces base) +if(WIN32) + target_sources(editor_host_test PRIVATE editor_host_platform_win.cpp ${hosting_dir}/module_win32.cpp) +elseif(APPLE) + target_sources(editor_host_test PRIVATE editor_host_platform_mac.mm ${hosting_dir}/module_mac.mm) + set_source_files_properties(editor_host_platform_mac.mm PROPERTIES COMPILE_FLAGS -fobjc-arc) + target_link_libraries(editor_host_test PRIVATE "-framework Cocoa" "-framework Foundation" "-framework CoreFoundation") +else() + find_package(X11 REQUIRED) + find_package(PkgConfig REQUIRED) + pkg_check_modules(GTK3 REQUIRED IMPORTED_TARGET gtk+-3.0) + target_link_libraries(editor_host_test PRIVATE PkgConfig::GTK3) + target_sources(editor_host_test PRIVATE editor_host_platform_x11.cpp ${hosting_dir}/module_linux.cpp) + target_link_libraries(editor_host_test PRIVATE X11::X11 Xtst ${CMAKE_DL_LIBS} stdc++fs) +endif() diff --git a/flutter_vst3/test/native/build_rules_flutter_test.py b/flutter_vst3/test/native/build_rules_flutter_test.py new file mode 100644 index 0000000..ba4062c --- /dev/null +++ b/flutter_vst3/test/native/build_rules_flutter_test.py @@ -0,0 +1,68 @@ +"""Real Linux Echo configure and ELF runpath regressions.""" +import pathlib +import re +import shutil +import subprocess +import unittest +from build_rules_make_test import scratch, invoke + + +def command(root, args): + return subprocess.run(args, cwd=root, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True) + + +def configure(root, name): + return command(root, ['cmake', '-S', 'vsts/echo', '-B', str(root / name), + '-DCMAKE_BUILD_TYPE=Release', '-DFLUTTER_VST3_NATIVE_UI_ONLY=OFF']) + + +class FlutterBuildRules(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.root = scratch() + invoke(cls.root, 'dart-deps') + result = command(cls.root / 'vsts/echo', ['flutter', 'build', 'linux', '--release']) + if result.returncode != 0: + raise AssertionError(result.stdout) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.root) + + def test_H18_release_never_uses_debug_bundle(self): + base = self.root / 'vsts/echo/build/linux/x64' + shutil.copytree(base / 'release/bundle', base / 'debug/bundle') + (base / 'release').rename(base / 'hidden-release') + self.addCleanup((base / 'hidden-release').rename, base / 'release') + result = configure(self.root, 'missing-release') + self.assertNotEqual(0, result.returncode, result.stdout) + expected = str(base / 'release/bundle/lib/libflutter_linux_gtk.so') + self.assertIn('Flutter editor file not found: ' + expected, ' '.join(result.stdout.split())) + self.assertIn('Run: flutter build linux --release', result.stdout) + self.assertIn('Set FLUTTER_VST3_NATIVE_UI_ONLY=ON to build with native sliders.', result.stdout) + + def test_H19_missing_ephemeral_is_fatal(self): + path = self.root / 'vsts/echo/linux/flutter/ephemeral' + path.rename(path.with_name('hidden-ephemeral')) + self.addCleanup(path.with_name('hidden-ephemeral').rename, path) + result = configure(self.root, 'missing-ephemeral') + self.assertNotEqual(0, result.returncode, result.stdout) + self.assertIn('Flutter editor file not found: ' + str(path / 'flutter_linux/flutter_linux.h'), + ' '.join(result.stdout.split())) + + def test_H19_runpath_is_origin_relative(self): + result = configure(self.root, 'with-flutter') + self.assertEqual(0, result.returncode, result.stdout) + result = command(self.root, ['cmake', '--build', 'with-flutter', '--parallel', '4']) + self.assertEqual(0, result.returncode, result.stdout) + plugins = list((self.root / 'with-flutter/VST3').rglob('echo.so')) + self.assertEqual(1, len(plugins)) + result = command(self.root, ['readelf', '-d', str(plugins[0])]) + self.assertEqual(0, result.returncode, result.stdout) + paths = re.findall(r'\(RUNPATH\).*?\[(.*?)\]', result.stdout) + self.assertEqual(['$ORIGIN'], paths) + + +if __name__ == '__main__': + unittest.main() diff --git a/flutter_vst3/test/native/build_rules_make_test.py b/flutter_vst3/test/native/build_rules_make_test.py new file mode 100644 index 0000000..499ae29 --- /dev/null +++ b/flutter_vst3/test/native/build_rules_make_test.py @@ -0,0 +1,117 @@ +"""Exercise public dependency and native-library targets in a clean scratch tree.""" +import os +import pathlib +import shutil +import subprocess +import sys +import tempfile +import time +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[3] +PACKAGES = ('dart_vst_host', 'dart_vst_graph', 'flutter_vst3', 'vsts/echo', 'vsts/flutter_reverb') + + +def scratch(): + destination = pathlib.Path(tempfile.mkdtemp(prefix='review_c_make_')) + shutil.copytree(ROOT, destination, dirs_exist_ok=True, + ignore=shutil.ignore_patterns('.git', '.dart_tool', 'build', 'ephemeral', + '.symlinks', '*.so', '*.dylib', '*.dll')) + return destination + + +STANDALONE_DART = """#!/usr/bin/env bash +# A dart with no Flutter refuses a package that depends on the Flutter SDK. The +# dart that comes with Flutter doesn't, which would hide the wrong command here. +if [ "$1 $2" = "pub get" ] && grep -q 'sdk: flutter' pubspec.yaml; then + echo "Because $PWD requires the Flutter SDK, version solving failed." >&2 + exit 65 +fi +exec "%s" "$@" +""" + + +def standalone_dart_path(): + directory = pathlib.Path(tempfile.mkdtemp(prefix='review_c_dart_')) + shim = directory / 'dart' + shim.write_text(STANDALONE_DART % shutil.which('dart')) + shim.chmod(0o755) + return directory + + +def invoke(root, target, path_prefix=None): + env = dict(os.environ) + if path_prefix: + env['PATH'] = str(path_prefix) + os.pathsep + env['PATH'] + result = subprocess.run(['make', target], cwd=root, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True, env=env) + if result.returncode != 0: + raise AssertionError(result.stdout) + return result.stdout + + +class PublicMakeTargets(unittest.TestCase): + def test_M17_clean_dart_deps_resolves_all_packages(self): + root = scratch() + self.addCleanup(shutil.rmtree, root) + for package in PACKAGES: + self.assertFalse((root / package / '.dart_tool/package_config.json').exists()) + shim = standalone_dart_path() + self.addCleanup(shutil.rmtree, shim) + invoke(root, 'dart-deps', shim) + for package in PACKAGES: + self.assertTrue((root / package / '.dart_tool/package_config.json').is_file(), package) + + def test_T2_native_copies_fresh_libraries(self): + root = scratch() + self.addCleanup(shutil.rmtree, root) + start = time.time_ns() + invoke(root, 'native') + for package in ('dart_vst_host', 'dart_vst_graph'): + path = root / package / ('lib' + package + '.so') + self.assertTrue(path.is_file(), str(path)) + self.assertGreater(path.stat().st_mtime_ns, start, str(path)) + self.assertEqual((root / path.name).read_bytes(), path.read_bytes()) + + +class DeployTargets(unittest.TestCase): + def deploy(self, root, home, plugin): + env = dict(os.environ, HOME=str(home)) + return subprocess.run(['make', '-C', 'vsts/' + plugin, '-o', 'build', 'deploy'], cwd=root, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env) + + def test_deploy_copies_one_plugin_and_fails_without_touching_a_missing_build(self): + root = scratch() + home = pathlib.Path(tempfile.mkdtemp(prefix='review_c_home_')) + self.addCleanup(shutil.rmtree, root) + self.addCleanup(shutil.rmtree, home) + folder = home / ('Library/Audio/Plug-Ins/VST3' if sys.platform == 'darwin' else '.vst3') + folder.mkdir(parents=True) + (folder / 'echo.vst3').symlink_to(home / 'gone') + (folder / 'other.vst3').mkdir() + bundles = {name: root / 'vsts' / name / 'build/VST3/Release' / (name + '.vst3') + for name in ('echo', 'flutter_reverb')} + for name, bundle in bundles.items(): + bundle.mkdir(parents=True) + (bundle / 'marker').write_text(name) + + echo = self.deploy(root, home, 'echo') + self.assertEqual(0, echo.returncode, echo.stdout) + self.assertFalse((folder / 'echo.vst3').is_symlink()) + self.assertEqual('echo', (folder / 'echo.vst3/marker').read_text()) + self.assertFalse((folder / 'flutter_reverb.vst3').exists()) + self.assertTrue((folder / 'other.vst3').is_dir()) + + reverb = self.deploy(root, home, 'flutter_reverb') + self.assertEqual(0, reverb.returncode, reverb.stdout) + self.assertEqual('flutter_reverb', (folder / 'flutter_reverb.vst3/marker').read_text()) + self.assertEqual('echo', (folder / 'echo.vst3/marker').read_text()) + + shutil.rmtree(bundles['echo']) + missing = self.deploy(root, home, 'echo') + self.assertNotEqual(0, missing.returncode, missing.stdout) + self.assertEqual('echo', (folder / 'echo.vst3/marker').read_text()) + + +if __name__ == '__main__': + unittest.main() diff --git a/flutter_vst3/test/native/build_rules_versions_test.py b/flutter_vst3/test/native/build_rules_versions_test.py new file mode 100644 index 0000000..6637db2 --- /dev/null +++ b/flutter_vst3/test/native/build_rules_versions_test.py @@ -0,0 +1,26 @@ +"""Verify declared SDK floors cover the APIs used by the Flutter UI.""" +import pathlib +import re +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[3] + + +def floor(source, key): + match = re.search(r'^ ' + key + r':\s*[\'\"]?[>=^]*(\d+)\.(\d+)\.(\d+)', source, re.M) + if match is None: + raise AssertionError('Missing version floor for ' + key) + return tuple(map(int, match.groups())) + + +class VersionFloors(unittest.TestCase): + def test_M7_sdk_floors_cover_new_color_and_slider_APIs(self): + for package in ('flutter_vst3', 'vsts/echo'): + source = (ROOT / package / 'pubspec.yaml').read_text() + with self.subTest(package=package): + self.assertGreaterEqual(floor(source, 'sdk'), (3, 6, 0)) + self.assertGreaterEqual(floor(source, 'flutter'), (3, 27, 0)) + + +if __name__ == '__main__': + unittest.main() diff --git a/flutter_vst3/test/native/coverage_check.py b/flutter_vst3/test/native/coverage_check.py new file mode 100755 index 0000000..8ca2eb1 --- /dev/null +++ b/flutter_vst3/test/native/coverage_check.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python3 +"""Check per-package line coverage against the floors in coverage-thresholds.json. + +Only files under a package's lib/ count. Files the test run never loaded are +counted at 0% using their non-blank, non-comment source lines. Duplicate lcov +records for the same file or line are merged. +""" +import json +import pathlib +import sys +from dataclasses import dataclass + +REPO_ROOT = pathlib.Path(__file__).resolve().parents[3] +THRESHOLDS_FILE = 'coverage-thresholds.json' +LCOV_FILE = 'coverage/lcov.info' +COMMENT_STARTS = ('//', '/*', '*') + + +@dataclass +class Stats: + package: str + lines: int + hit: int + percent: float + floor: float + unloaded: list + + @property + def below(self): + return self.percent < self.floor + + +def load_thresholds(repo): + path = repo / THRESHOLDS_FILE + if not path.is_file(): + raise SystemExit(f'error: missing thresholds file {path}') + return json.loads(path.read_text(encoding='utf-8'))['packages'] + + +def lcov_packages(root): + """Package names (relative to root) that have a coverage/lcov.info file.""" + return {path.parent.parent.relative_to(root).as_posix(): path + for path in root.rglob(LCOV_FILE)} + + +def lib_relative(source, package_dir): + """Return a lib-relative path, or None when the source is outside lib/.""" + lib = (package_dir / 'lib').resolve() + raw = pathlib.Path(source.strip().replace('\\', '/')) + for candidate in (raw, package_dir / raw): + resolved = candidate.resolve() + if resolved == lib or lib in resolved.parents: + return resolved.relative_to(lib).as_posix() + return None + + +def parse_records(path, package_dir): + """Map lib-relative file name to {line: hit}, merging duplicate records.""" + records = {} + current = None + for line in path.read_text(encoding='utf-8', errors='replace').splitlines(): + if line.startswith('SF:'): + current = lib_relative(line[3:], package_dir) + elif line.startswith('DA:') and current is not None: + number, count = (int(field) for field in line[3:].split(',')[:2]) + lines = records.setdefault(current, {}) + lines[number] = lines.get(number, False) or count > 0 + return records + + +def code_lines(path): + """Count non-blank, non-comment source lines.""" + return sum(1 for line in path.read_text(encoding='utf-8', errors='replace').splitlines() + if line.strip() and not line.strip().startswith(COMMENT_STARTS)) + + +def package_stats(root, package, floor): + package_dir = root / package + lcov = package_dir / LCOV_FILE + if not lcov.is_file(): + raise CheckError(f'{package}: missing {lcov}') + records = parse_records(lcov, package_dir) + recorded = sum(len(lines) for lines in records.values()) + if recorded == 0: + raise CheckError(f'{package}: empty lcov {lcov}') + hit = sum(sum(lines.values()) for lines in records.values()) + sources = {path.relative_to(package_dir / 'lib').as_posix(): path + for path in (package_dir / 'lib').rglob('*.dart') if path.is_file()} + unloaded = [(name, code_lines(path)) for name, path in sorted(sources.items()) + if name not in records] + lines = recorded + sum(count for _, count in unloaded) + percent = 100.0 * hit / lines if lines else 0.0 + return Stats(package, lines, hit, percent, floor, unloaded) + + +class CheckError(Exception): + """A structural coverage problem that must fail the check.""" + + +def validate(root, thresholds): + """Return the packages to check, raising CheckError on bad trees.""" + packages = lcov_packages(root) + unknown = [name for name in thresholds if not (root / name / 'lib').is_dir()] + if unknown: + raise CheckError(f'unknown package(s) in {THRESHOLDS_FILE}: {", ".join(sorted(unknown))}') + unlisted = sorted(set(packages) - set(thresholds)) + if unlisted: + raise CheckError(f'package(s) with no thresholds entry: {", ".join(unlisted)}') + return sorted(thresholds) + + +def print_stats(stats): + print(stats.package) + for name, count in stats.unloaded: + print(f' MISSING lib/{name}: {count} lines, 0.0%') + print(' lines hit percent floor status') + status = 'BELOW' if stats.below else 'ok' + print(f' {stats.lines:5d} {stats.hit:3d} {stats.percent:6.1f}%' + f' {stats.floor:5.1f} {status}') + + +def report(results): + for stats in results: + print_stats(stats) + failures = [stats for stats in results if stats.below] + for stats in failures: + print(f'error: {stats.package} {stats.percent:.1f}% is below floor {stats.floor:.1f}%', + file=sys.stderr) + return 1 if failures else 0 + + +def main(argv): + root = pathlib.Path(argv[1]).resolve() if len(argv) > 1 else REPO_ROOT + thresholds = load_thresholds(root) + try: + packages = validate(root, thresholds) + results = [package_stats(root, package, float(thresholds[package])) + for package in packages] + except CheckError as error: + print(f'error: {error}', file=sys.stderr) + return 1 + return report(results) + + +if __name__ == '__main__': + sys.exit(main(sys.argv)) diff --git a/flutter_vst3/test/native/coverage_check_test.py b/flutter_vst3/test/native/coverage_check_test.py new file mode 100644 index 0000000..94270c5 --- /dev/null +++ b/flutter_vst3/test/native/coverage_check_test.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""End-to-end tests for coverage_check.py against disposable package trees.""" +import json +import pathlib +import shutil +import subprocess +import sys +import tempfile +import unittest + +SCRIPT = pathlib.Path(__file__).resolve().parent / 'coverage_check.py' +COVERAGE = 'coverage/lcov.info' +THRESHOLDS = 'coverage-thresholds.json' + + +def write(path, text): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding='utf-8') + + +def make_tree(test, packages, floors): + """Build a temporary repository with a byte-for-byte copy of the checker.""" + root = pathlib.Path(tempfile.mkdtemp(prefix='coverage_check_')) + test.addCleanup(shutil.rmtree, root) + checker = root / 'flutter_vst3/test/native/coverage_check.py' + checker.parent.mkdir(parents=True) + shutil.copy2(SCRIPT, checker) + write(root / THRESHOLDS, json.dumps({'_doc': 'test floors', 'packages': floors})) + for name, spec in packages.items(): + (root / name / 'lib').mkdir(parents=True, exist_ok=True) + for relative, source in spec.get('sources', {}).items(): + write(root / name / 'lib' / relative, source) + if spec.get('lcov') is not None: + write(root / name / COVERAGE, spec['lcov']) + for relative, source in spec.get('extra', {}).items(): + write(root / name / relative, source) + return root + + +def invoke(root, *arguments): + command = [sys.executable, str(SCRIPT), str(root)] + return subprocess.run(command + list(arguments), capture_output=True, text=True) + + +def invoke_default(root): + script = root / 'flutter_vst3/test/native/coverage_check.py' + return subprocess.run([sys.executable, str(script)], capture_output=True, text=True) + + +def output(result): + return result.stdout + result.stderr + + +def lcov(*records): + return ''.join(f'SF:{source}\n{lines}end_of_record\n' for source, lines in records) + + +ONE_LINE = {'sources': {'a.dart': 'int a = 1;\n'}, 'lcov': lcov(('lib/a.dart', 'DA:1,1\n'))} +TWO_LINES = 'int a = 1;\nint b = 2;\n' + + +class CoverageCheckTests(unittest.TestCase): + def check(self, code, package, floors): + """Runs the checker on one package named pkg and asserts its exit code.""" + result = invoke(make_tree(self, {'pkg': package}, floors)) + self.assertEqual(code, result.returncode, output(result)) + return result + + def test_duplicate_records_merge_and_a_line_hit_anywhere_wins(self): + result = self.check(0, { + 'sources': {'a.dart': TWO_LINES}, + 'lcov': lcov(('lib/a.dart', 'DA:1,0\nDA:2,1\nDA:1,1\n'), + ('lib/a.dart', 'DA:1,1\nDA:2,0\n')), + }, {'pkg': 100.0}) + self.assertIn('2 2 100.0% 100.0 ok', result.stdout) + self.assertNotIn('BELOW', result.stdout) + + def test_unloaded_file_counts_zero_and_is_listed(self): + result = self.check(0, { + 'sources': {'a.dart': TWO_LINES, 'b.dart': TWO_LINES}, + 'lcov': lcov(('lib/a.dart', 'DA:1,1\nDA:2,1\n')), + }, {'pkg': 50.0}) + self.assertIn('MISSING lib/b.dart: 2 lines, 0.0%', result.stdout) + self.assertNotIn('MISSING lib/a.dart', result.stdout) + self.assertIn('4 2 50.0% 50.0 ok', result.stdout) + + def test_comment_only_and_blank_unloaded_files_add_no_lines(self): + result = self.check(0, { + 'sources': {**ONE_LINE['sources'], + 'comments.dart': '// only\n\n/* block\n * more\n */\n', + 'blank.dart': '\n\n \n', + 'mixed.dart': '// lead\nint x = 1; // tail\n/* block\n */\nint y = 2;\n'}, + 'lcov': ONE_LINE['lcov'], + }, {'pkg': 33.3}) + self.assertIn('MISSING lib/comments.dart: 0 lines, 0.0%', result.stdout) + self.assertIn('MISSING lib/blank.dart: 0 lines, 0.0%', result.stdout) + self.assertIn('MISSING lib/mixed.dart: 2 lines, 0.0%', result.stdout) + self.assertIn('3 1 33.3% 33.3 ok', result.stdout) + + def test_below_floor_fails_and_exactly_at_floor_passes(self): + package = {'sources': {'a.dart': TWO_LINES}, + 'lcov': lcov(('lib/a.dart', 'DA:1,1\nDA:2,0\n'))} + below = self.check(1, package, {'pkg': 50.1}) + self.assertIn('BELOW', below.stdout) + self.assertIn('below floor 50.1%', below.stderr) + self.assertIn('2 1 50.0% 50.0 ok', self.check(0, package, {'pkg': 50.0}).stdout) + + def test_missing_lcov_fails(self): + root = make_tree(self, {'pkg': {'sources': ONE_LINE['sources']}}, {'pkg': 0.0}) + result = invoke(root) + self.assertEqual(1, result.returncode, output(result)) + self.assertIn(f'missing {root.resolve() / "pkg" / COVERAGE}', result.stderr) + + def test_empty_lcov_fails(self): + for contents in ('', '\n \n', lcov(('lib/a.dart', ''))): + with self.subTest(contents=contents): + result = self.check(1, {'sources': ONE_LINE['sources'], 'lcov': contents}, {'pkg': 0.0}) + self.assertIn('empty lcov', result.stderr) + + def test_unknown_package_in_thresholds_fails(self): + result = self.check(1, ONE_LINE, {'pkg': 100.0, 'ghost': 10.0}) + self.assertIn('unknown package(s)', result.stderr) + self.assertIn('ghost', result.stderr) + + def test_package_without_thresholds_entry_fails(self): + result = self.check(1, ONE_LINE, {}) + self.assertIn('no thresholds entry', result.stderr) + self.assertIn('pkg', result.stderr) + + def test_files_outside_lib_are_ignored(self): + result = self.check(0, { + 'sources': ONE_LINE['sources'], + 'extra': {'test/a_test.dart': TWO_LINES}, + 'lcov': lcov(('lib/a.dart', 'DA:1,1\n'), + ('test/a_test.dart', 'DA:1,1\nDA:2,1\n'), + ('other/lib/ignored.dart', 'DA:1,1\nDA:2,1\n')), + }, {'pkg': 100.0}) + self.assertIn('1 1 100.0% 100.0 ok', result.stdout) + self.assertNotIn('MISSING lib/a.dart', result.stdout) + + def test_absolute_and_relative_paths_merge_one_file(self): + root = make_tree(self, {'pkg': {'sources': {'a.dart': TWO_LINES}}}, {'pkg': 100.0}) + write(root / 'pkg' / COVERAGE, + lcov(('lib/a.dart', 'DA:1,1\n'), (str(root / 'pkg/lib/a.dart'), 'DA:2,1\n'))) + result = invoke(root) + self.assertEqual(0, result.returncode, output(result)) + self.assertIn('2 2 100.0% 100.0 ok', result.stdout) + + def test_default_root_is_the_script_repository(self): + root = make_tree(self, {'pkg': ONE_LINE}, {'pkg': 100.0}) + result = invoke_default(root) + self.assertEqual(0, result.returncode, output(result)) + self.assertEqual(result.stdout, invoke(root).stdout) + + def test_missing_thresholds_file_fails(self): + root = make_tree(self, {}, {}) + (root / THRESHOLDS).unlink() + result = invoke(root) + self.assertEqual(1, result.returncode, output(result)) + self.assertIn('missing thresholds file', result.stderr) + + +if __name__ == '__main__': + unittest.main() diff --git a/flutter_vst3/test/native/docs_commands_test.py b/flutter_vst3/test/native/docs_commands_test.py new file mode 100644 index 0000000..91a85f0 --- /dev/null +++ b/flutter_vst3/test/native/docs_commands_test.py @@ -0,0 +1,29 @@ +"""Execute every documented individual package test command.""" +import os +import pathlib +import re +import subprocess +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[3] + + +class DocumentationCommands(unittest.TestCase): + def test_AB4_documented_tests_execute(self): + blocks = re.findall(r'```[^\n]*\n(.*?)```', (ROOT / 'README.md').read_text(), re.S) + commands = re.findall(r'^\(cd [^\n]+ && (?:dart|flutter) test\)\s*$', + '\n'.join(blocks), re.M) + self.assertGreaterEqual(len(commands), 4) + packages = {re.search(r'cd (\S+)', command)[1] for command in commands} + self.assertTrue({'flutter_vst3', 'vsts/echo', 'dart_vst_host', 'dart_vst_graph'} <= packages) + for command in commands: + with self.subTest(command=command): + env = {k: v for k, v in os.environ.items() if k not in ('CI', 'GITHUB_ACTIONS')} + result = subprocess.run(['bash', '-lc', command], cwd=ROOT, env=env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + self.assertEqual(0, result.returncode, result.stdout) + self.assertIn('All tests passed!', result.stdout) + + +if __name__ == '__main__': + unittest.main() diff --git a/flutter_vst3/test/native/editor_host_platform.h b/flutter_vst3/test/native/editor_host_platform.h new file mode 100644 index 0000000..7d7b1c1 --- /dev/null +++ b/flutter_vst3/test/native/editor_host_platform.h @@ -0,0 +1,44 @@ +// What editor_host_test needs from the OS: parent windows and an event loop. +#pragma once +#include +#include "base/source/fobject.h" +#include "pluginterfaces/gui/iplugview.h" + +inline void check(bool ok, const char* text) { + if (!ok) throw std::runtime_error(text); +} + +/// A host frame that accepts every resize. Linux adds a run loop to this. +class BasicFrame : public Steinberg::IPlugFrame, public Steinberg::FObject { +public: + REFCOUNT_METHODS(Steinberg::FObject) + Steinberg::tresult PLUGIN_API queryInterface(const Steinberg::TUID iid, void** obj) override { + QUERY_INTERFACE(iid, obj, Steinberg::IPlugFrame::iid, Steinberg::IPlugFrame) + return Steinberg::FObject::queryInterface(iid, obj); + } + Steinberg::tresult PLUGIN_API resizeView(Steinberg::IPlugView* view, Steinberg::ViewRect* rect) override { + return view->onSize(rect); + } +}; + +void platformInit(); +void platformShutdown(); +Steinberg::IPlugFrame* platformFrame(); +const char* platformViewType(); +long long platformProcessId(); +void* platformCreateWindow(); +void platformDestroyWindow(void* window); +/// Runs the host's event loop for this long. +void platformPump(int ms); +bool platformHasVisibleChild(void* window); +/// Whether this OS can read back the window's pixels in a test. +bool platformCanCapture(); +/// Whether the window shows more than one colour. +bool platformRendered(void* window); +unsigned long long platformCaptureHash(void* window); +void platformPress(void* window, int x, int y); +void platformMove(void* window, int x, int y); +void platformRelease(void* window, int x, int y); +inline void platformDrag(void* window, int x0, int y0, int x1, int y1) { + platformPress(window, x0, y0); platformMove(window, x1, y1); platformRelease(window, x1, y1); +} diff --git a/flutter_vst3/test/native/editor_host_platform_mac.mm b/flutter_vst3/test/native/editor_host_platform_mac.mm new file mode 100644 index 0000000..ed5e138 --- /dev/null +++ b/flutter_vst3/test/native/editor_host_platform_mac.mm @@ -0,0 +1,60 @@ +// Cocoa parents and a main run loop. +#include "editor_host_platform.h" +#import +#include +using namespace Steinberg; + +namespace { +BasicFrame frame; +NSView* asView(void* window) { return (__bridge NSView*)window; } +} + +void platformInit() { + [NSApplication sharedApplication]; + [NSApp setActivationPolicy:NSApplicationActivationPolicyAccessory]; + [NSApp finishLaunching]; +} +void platformShutdown() {} +IPlugFrame* platformFrame() { return &frame; } +const char* platformViewType() { return kPlatformTypeNSView; } +long long platformProcessId() { return getpid(); } +void* platformCreateWindow() { + NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 600, 650) + styleMask:NSWindowStyleMaskBorderless + backing:NSBackingStoreBuffered + defer:NO]; + window.releasedWhenClosed = NO; + [window orderFrontRegardless]; + return (__bridge_retained void*)window.contentView; +} +void platformDestroyWindow(void* window) { + NSView* view = (__bridge_transfer NSView*)window; + [view.window orderOut:nil]; +} +void platformPump(int ms) { + NSDate* end = [NSDate dateWithTimeIntervalSinceNow:ms / 1000.0]; + while ([end timeIntervalSinceNow] > 0) { + @autoreleasepool { + NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny + untilDate:[NSDate dateWithTimeIntervalSinceNow:0.001] + inMode:NSDefaultRunLoopMode + dequeue:YES]; + if (event) [NSApp sendEvent:event]; + } + } +} +bool platformHasVisibleChild(void* window) { + for (NSView* child in asView(window).subviews) { + if (!child.isHidden) return true; + } + return false; +} +// Reading a Metal layer back needs a screen recording permission that CI lacks. +void platformPress(void*, int, int) { throw std::runtime_error("macOS pointer unsupported"); } +void platformMove(void*, int, int) { throw std::runtime_error("macOS pointer unsupported"); } +void platformRelease(void*, int, int) { throw std::runtime_error("macOS pointer unsupported"); } +unsigned long long platformCaptureHash(void*) { throw std::runtime_error("macOS capture unsupported"); } +bool platformCanCapture() { return false; } +bool platformRendered(void*) { + throw std::runtime_error("Rendering cannot be captured on macOS"); +} diff --git a/flutter_vst3/test/native/editor_host_platform_win.cpp b/flutter_vst3/test/native/editor_host_platform_win.cpp new file mode 100644 index 0000000..73deb7f --- /dev/null +++ b/flutter_vst3/test/native/editor_host_platform_win.cpp @@ -0,0 +1,111 @@ +// Win32 parents and a message loop. +#include "editor_host_platform.h" +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#include +using namespace Steinberg; +using Clock = std::chrono::steady_clock; + +namespace { +BasicFrame frame; +const wchar_t* const kClassName = L"EditorHostTestParent"; +HWND asWindow(void* window) { return static_cast(window); } +BOOL CALLBACK findVisible(HWND child, LPARAM found) { + *reinterpret_cast(found) |= IsWindowVisible(child) != FALSE; + return TRUE; +} +} + +void platformInit() { + WNDCLASSEXW wc{}; + wc.cbSize = sizeof(wc); + wc.lpfnWndProc = DefWindowProcW; + wc.hInstance = GetModuleHandleW(nullptr); + wc.hbrBackground = static_cast(GetStockObject(BLACK_BRUSH)); + wc.lpszClassName = kClassName; + check(RegisterClassExW(&wc) != 0, "RegisterClassExW"); +} +void platformShutdown() {} +IPlugFrame* platformFrame() { return &frame; } +const char* platformViewType() { return kPlatformTypeHWND; } +long long platformProcessId() { return GetCurrentProcessId(); } +void* platformCreateWindow() { + HWND window = CreateWindowExW(WS_EX_TOPMOST, kClassName, L"parent", WS_POPUP | WS_VISIBLE, 0, 0, 600, 650, + nullptr, nullptr, GetModuleHandleW(nullptr), nullptr); + check(window != nullptr, "CreateWindowExW"); + return window; +} +void platformDestroyWindow(void* window) { DestroyWindow(asWindow(window)); } +void platformPump(int ms) { + const auto end = Clock::now() + std::chrono::milliseconds(ms); + while (Clock::now() < end) { + MSG msg; + while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + Sleep(1); + } +} +bool platformHasVisibleChild(void* window) { + bool found = false; + EnumChildWindows(asWindow(window), findVisible, reinterpret_cast(&found)); + return found; +} +unsigned long long platformCaptureHash(void* window) { + RECT r; check(GetWindowRect(asWindow(window), &r), "capture rect"); + HDC screen = GetDC(nullptr), memory = CreateCompatibleDC(screen); + HBITMAP bitmap = CreateCompatibleBitmap(screen, 540, 180); + auto old = SelectObject(memory, bitmap); + check(BitBlt(memory, 0, 0, 540, 180, screen, r.left, r.top + 60, SRCCOPY), "capture BitBlt"); + unsigned long long hash = 14695981039346656037ULL; + for (int y = 0; y < 180; ++y) for (int x = 0; x < 540; ++x) { + auto pixel = GetPixel(memory, x, y); check(pixel != CLR_INVALID, "capture GetPixel"); + for (int b = 0; b < 4; ++b) { hash ^= (pixel >> (b * 8)) & 255; hash *= 1099511628211ULL; } + } + SelectObject(memory, old); DeleteObject(bitmap); DeleteDC(memory); ReleaseDC(nullptr, screen); + return hash; +} +void platformMove(void* window, int x, int y) { + RECT r; check(GetWindowRect(asWindow(window), &r), "pointer rect"); + INPUT input{}; input.type = INPUT_MOUSE; + input.mi.dx = (r.left + x) * 65535 / (GetSystemMetrics(SM_CXSCREEN) - 1); + input.mi.dy = (r.top + y) * 65535 / (GetSystemMetrics(SM_CYSCREEN) - 1); + input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE; + check(SendInput(1, &input, sizeof(input)) == 1, "SendInput move"); platformPump(150); +} +void platformButton(void* window, int x, int y, DWORD flags) { + platformMove(window, x, y); INPUT input{}; input.type = INPUT_MOUSE; input.mi.dwFlags = flags; + check(SendInput(1, &input, sizeof(input)) == 1, "SendInput button"); platformPump(150); +} +void platformPress(void* w, int x, int y) { platformButton(w, x, y, MOUSEEVENTF_LEFTDOWN); } +void platformRelease(void*, int, int) { + INPUT input{}; input.type = INPUT_MOUSE; input.mi.dwFlags = MOUSEEVENTF_LEFTUP; + check(SendInput(1, &input, sizeof(input)) == 1, "SendInput release"); platformPump(150); +} +bool platformCanCapture() { return true; } +// Reads the screen, since a swap chain's pixels don't reach the window's own DC. +bool platformRendered(void* window) { + RECT rect; + check(GetWindowRect(asWindow(window), &rect) != 0, "Rendering: GetWindowRect"); + const int width = rect.right - rect.left, height = rect.bottom - rect.top; + HDC screen = GetDC(nullptr); + check(screen != nullptr, "Rendering: GetDC"); + HDC memory = CreateCompatibleDC(screen); + HBITMAP bitmap = CreateCompatibleBitmap(screen, width, height); + SelectObject(memory, bitmap); + check(BitBlt(memory, 0, 0, width, height, screen, rect.left, rect.top, SRCCOPY) != 0, "Rendering: BitBlt"); + const COLORREF first = GetPixel(memory, 0, 0); + bool varied = false; + for (int y = 0; y < height; y += 2) for (int x = 0; x < width; x += 2) + varied |= GetPixel(memory, x, y) != first; + std::printf("captured %dx%d, first pixel %06lx, varied %d\n", width, height, + static_cast(first), varied ? 1 : 0); + DeleteObject(bitmap); + DeleteDC(memory); + ReleaseDC(nullptr, screen); + return varied; +} diff --git a/flutter_vst3/test/native/editor_host_platform_x11.cpp b/flutter_vst3/test/native/editor_host_platform_x11.cpp new file mode 100644 index 0000000..5ca3c62 --- /dev/null +++ b/flutter_vst3/test/native/editor_host_platform_x11.cpp @@ -0,0 +1,134 @@ +// Xlib parents and an IRunLoop, pumped the way a Linux host does it. +#include "editor_host_platform.h" +#include +#include +#include +#include +#include +#include +#include +#include +using namespace Steinberg; +using Clock = std::chrono::steady_clock; + +namespace { +class Frame : public BasicFrame, public Linux::IRunLoop { +public: + struct Timer { Linux::ITimerHandler* handler; uint64 interval; Clock::time_point next; }; + struct Event { Linux::IEventHandler* handler; int fd; }; + std::vector timers; + std::vector events; + REFCOUNT_METHODS(BasicFrame) + tresult PLUGIN_API queryInterface(const TUID iid, void** obj) override { + QUERY_INTERFACE(iid, obj, Linux::IRunLoop::iid, Linux::IRunLoop) + return BasicFrame::queryInterface(iid, obj); + } + tresult PLUGIN_API registerTimer(Linux::ITimerHandler* h, uint64 ms) override { + timers.push_back({h, ms, Clock::now() + std::chrono::milliseconds(ms)}); + return kResultTrue; + } + tresult PLUGIN_API unregisterTimer(Linux::ITimerHandler* h) override { + timers.erase(std::remove_if(timers.begin(), timers.end(), [h](auto t) { return t.handler == h; }), timers.end()); + return kResultTrue; + } + tresult PLUGIN_API registerEventHandler(Linux::IEventHandler* h, int fd) override { + events.push_back({h, fd}); + return kResultTrue; + } + tresult PLUGIN_API unregisterEventHandler(Linux::IEventHandler* h) override { + events.erase(std::remove_if(events.begin(), events.end(), [h](auto e) { return e.handler == h; }), events.end()); + return kResultTrue; + } + void tick() { + const auto now = Clock::now(); + std::vector due; + for (auto& t : timers) if (now >= t.next) { + t.next = now + std::chrono::milliseconds(t.interval); + due.push_back(t.handler); + } + for (auto* h : due) h->onTimer(); + for (auto e : events) { + pollfd p{e.fd, POLLIN, 0}; + if (poll(&p, 1, 0) > 0) e.handler->onFDIsSet(e.fd); + } + } +}; +Display* display; +Frame frame; +Window asWindow(void* window) { return reinterpret_cast(window); } +} + +void platformInit() { + display = XOpenDisplay(nullptr); + check(display != nullptr, "XOpenDisplay"); +} +void platformShutdown() { XCloseDisplay(display); } +IPlugFrame* platformFrame() { return &frame; } +const char* platformViewType() { return kPlatformTypeX11EmbedWindowID; } +long long platformProcessId() { return getpid(); } +void* platformCreateWindow() { + const Window window = XCreateSimpleWindow(display, DefaultRootWindow(display), 0, 0, 600, 650, 0, 0, 0); + XMapWindow(display, window); + XSync(display, False); + return reinterpret_cast(window); +} +void platformDestroyWindow(void* window) { + XDestroyWindow(display, asWindow(window)); + XSync(display, False); +} +void platformPump(int ms) { + const auto end = Clock::now() + std::chrono::milliseconds(ms); + while (Clock::now() < end) { + frame.tick(); + usleep(1000); + } +} +bool platformHasVisibleChild(void* window) { + Window root, parent, *children = nullptr; + unsigned count = 0; + bool mapped = false; + check(XQueryTree(display, asWindow(window), &root, &parent, &children, &count), "XQueryTree"); + for (unsigned i = 0; i < count; ++i) { + XWindowAttributes a; + XGetWindowAttributes(display, children[i], &a); + mapped |= a.map_state == IsViewable; + } + if (children) XFree(children); + return mapped; +} +unsigned long long platformCaptureHash(void* window) { + XImage* image = XGetImage(display, asWindow(window), 0, 60, 540, 180, AllPlanes, ZPixmap); + check(image != nullptr, "parameter XGetImage"); + unsigned long long hash = 14695981039346656037ULL; + for (int y = 0; y < 180; ++y) for (int x = 0; x < 540; ++x) { + auto pixel = XGetPixel(image, x, y); + for (int b = 0; b < 4; ++b) { hash ^= (pixel >> (b * 8)) & 255; hash *= 1099511628211ULL; } + } + XDestroyImage(image); return hash; +} +void platformMove(void* window, int x, int y) { + Window child; int sx, sy; + check(XTranslateCoordinates(display, asWindow(window), DefaultRootWindow(display), x, y, &sx, &sy, &child), "pointer coordinates"); + check(XTestFakeMotionEvent(display, -1, sx, sy, CurrentTime), "XTest motion"); + XFlush(display); platformPump(150); +} +void platformPress(void* window, int x, int y) { + platformMove(window, x, y); + check(XTestFakeButtonEvent(display, 1, True, CurrentTime), "XTest press"); + XFlush(display); platformPump(150); +} +void platformRelease(void*, int, int) { + check(XTestFakeButtonEvent(display, 1, False, CurrentTime), "XTest release"); + XFlush(display); platformPump(150); +} +bool platformCanCapture() { return true; } +bool platformRendered(void* window) { + XImage* image = XGetImage(display, asWindow(window), 0, 0, 600, 650, AllPlanes, ZPixmap); + check(image != nullptr, "Rendering: XGetImage failed under Xvfb"); + const auto first = XGetPixel(image, 0, 0); + bool varied = false; + for (int y = 0; y < 650; ++y) for (int x = 0; x < 600; ++x) + varied |= XGetPixel(image, x, y) != first; + XDestroyImage(image); + return varied; +} diff --git a/flutter_vst3/test/native/editor_host_recording.h b/flutter_vst3/test/native/editor_host_recording.h new file mode 100644 index 0000000..c2325ce --- /dev/null +++ b/flutter_vst3/test/native/editor_host_recording.h @@ -0,0 +1,58 @@ +#pragma once +#include +#include +#include "editor_host_platform.h" +#include "pluginterfaces/vst/ivsteditcontroller.h" +using namespace Steinberg; +using namespace Steinberg::Vst; +struct RecordedEdit { char kind; ParamID id; ParamValue value; }; +class RecordingHandler : public IComponentHandler, public FObject { +public: + std::vector events; + REFCOUNT_METHODS(FObject) + tresult PLUGIN_API queryInterface(const TUID iid, void** obj) override { + QUERY_INTERFACE(iid, obj, IComponentHandler::iid, IComponentHandler) + return FObject::queryInterface(iid, obj); + } + tresult PLUGIN_API beginEdit(ParamID id) override { + events.push_back({'b', id, 0}); return kResultTrue; + } + tresult PLUGIN_API performEdit(ParamID id, ParamValue value) override { + events.push_back({'p', id, value}); return kResultTrue; + } + tresult PLUGIN_API endEdit(ParamID id) override { + events.push_back({'e', id, 0}); return kResultTrue; + } + tresult PLUGIN_API restartComponent(int32) override { return kResultTrue; } + void balanced(double finalValue) { + check(events.size() >= 3, "drag missing events"); + for (auto event : events) std::fprintf(stderr, "gesture %c(%u,%.17g)\n", event.kind, event.id, event.value); + check(events.front().kind == 'b' && events.back().kind == 'e', "drag boundaries"); + for (size_t i = 0; i < events.size(); ++i) { + check(events[i].id == 0, "drag wrong id"); + if (i > 0 && i + 1 < events.size()) { + check(events[i].kind == 'p', "drag duplicate begin/end"); + check(events[i].value >= 0 && events[i].value <= 1, "drag range"); + } + } + check(events[events.size()-2].value > 0.1, "drag did not increase"); + check(events[events.size()-2].value == finalValue, "drag controller value mismatch"); + } + /// What a host requires whatever the order: performs only inside a gesture, + /// no nesting, and nothing left open. + void contractHolds() { + bool open = false; + for (auto event : events) { + check(event.id == 0, "contract: wrong id"); + check(event.kind == 'b' ? !open : open, "contract: event outside its gesture"); + open = event.kind == 'b' || (event.kind == 'p' && open); + } + check(!open, "contract: gesture left open"); + } + void exactTriple(double value) { + check(events.size() == 3, "gesture must contain exactly three events"); + check(events[0].kind == 'b' && events[0].id == 0, "begin(0)"); + check(events[1].kind == 'p' && events[1].id == 0 && events[1].value == value, "perform(0,v)"); + check(events[2].kind == 'e' && events[2].id == 0, "end(0)"); + } +}; diff --git a/flutter_vst3/test/native/editor_host_regressions.h b/flutter_vst3/test/native/editor_host_regressions.h new file mode 100644 index 0000000..b443deb --- /dev/null +++ b/flutter_vst3/test/native/editor_host_regressions.h @@ -0,0 +1,60 @@ +#pragma once +#include +#if defined(_WIN32) +#include +std::wstring dllDirectory() { + wchar_t value[32768]{}; + auto size = GetDllDirectoryW(32768, value); + check(size < 32768, "H12 directory read"); + return std::wstring(value, size); +} +void environmentInvariant() { + const auto original = dllDirectory(); + wchar_t directory[32768]{}; + check(GetWindowsDirectoryW(directory, 32768) > 0, "H12 Windows directory"); + for (const auto& expected : {original, std::wstring(directory)}) { + check(SetDllDirectoryW(expected.c_str()) != 0, "H12 set directory"); + { Editor a; platformPump(1500); check(dllDirectory() == expected, "H12 DLL directory changed on attach"); } + check(dllDirectory() == expected, "H12 DLL directory changed on close"); + } + check(SetDllDirectoryW(original.c_str()) != 0, "H12 restore directory"); + puts("PASS H12 DLL directory invariant"); +} +#elif defined(__linux__) +#include +void initializedBackendInvariant() { + auto* display = gdk_display_get_default(); + check(display != nullptr, "H13 GTK was not initialized"); + const std::string backend = G_OBJECT_TYPE_NAME(display); + check(backend == "GdkX11Display", "H13 expected initialized X11 backend"); + { Editor a; platformPump(500); } + check(gdk_display_get_default() == display, "H13 initialized display replaced"); + check(std::string(G_OBJECT_TYPE_NAME(display)) == backend, "H13 initialized backend changed"); +} +void environmentInvariant() { + const char* prior = getenv("GDK_BACKEND"); + const bool present = prior != nullptr; + const std::string original = present ? prior : ""; + for (const char* value : {static_cast(nullptr), "x11"}) { + check((value ? setenv("GDK_BACKEND", value, 1) : unsetenv("GDK_BACKEND")) == 0, "H13 setup"); + { Editor a; platformPump(1500); } + const char* actual = getenv("GDK_BACKEND"); + check(value ? actual && std::string(actual) == value : actual == nullptr, "H13 GDK_BACKEND changed"); + } + initializedBackendInvariant(); + check((present ? setenv("GDK_BACKEND", original.c_str(), 1) : unsetenv("GDK_BACKEND")) == 0, "H13 restore"); + puts("PASS H13 GDK_BACKEND invariant before and after GTK initialization"); +} +#else +void environmentInvariant() { puts("PASS environment invariant not applicable on Cocoa"); } +#endif +void immediateClose() { + for (bool update : {false, true}) { + Editor a; + if (update) check(a.controller->setParamNormalized(0, 0.37) == kResultTrue, "H15 set value"); + a.view->removed(); a.view->setFrame(nullptr); a.view = nullptr; + platformPump(500); + if (update) check(a.controller->getParamNormalized(0) == 0.37, "H15 queued value changed"); + } + puts("PASS H15 immediate close"); +} diff --git a/flutter_vst3/test/native/editor_host_test.cpp b/flutter_vst3/test/native/editor_host_test.cpp new file mode 100644 index 0000000..16dc446 --- /dev/null +++ b/flutter_vst3/test/native/editor_host_test.cpp @@ -0,0 +1,327 @@ +#include +#include +#include +#include +#include "editor_host_platform.h" +#include "editor_host_recording.h" +#include "public.sdk/source/vst/vsteditcontroller.h" +#include "public.sdk/source/common/memorystream.h" +#include "pluginterfaces/vst/ivsteditcontroller.h" +#include "pluginterfaces/vst/ivstcomponent.h" +#include "pluginterfaces/vst/ivstaudioprocessor.h" +#include "pluginterfaces/vst/ivstmessage.h" +#include "public.sdk/source/vst/hosting/hostclasses.h" +#include "public.sdk/source/vst/hosting/module.h" +using namespace Steinberg; +using namespace Steinberg::Vst; +HostApplication host; +std::shared_ptr module; +VST3::UID controllerUid; +VST3::UID processorUid; +class Wire : public IConnectionPoint, public FObject { +public: + IConnectionPoint* target{nullptr}; + int64 address{-1}, pid{-1}; + REFCOUNT_METHODS(FObject) + tresult PLUGIN_API queryInterface(const TUID iid, void** obj) override { + QUERY_INTERFACE(iid, obj, IConnectionPoint::iid, IConnectionPoint) + return FObject::queryInterface(iid, obj); + } + tresult PLUGIN_API connect(IConnectionPoint*) override { return kResultTrue; } + tresult PLUGIN_API disconnect(IConnectionPoint*) override { return kResultTrue; } + tresult PLUGIN_API notify(IMessage* message) override { + check(std::string(message->getMessageID()) == "Vst3Shm", "H7 unexpected message"); + check(message->getAttributes()->getInt("address", address) == kResultTrue, "H7 address wire type"); + check(message->getAttributes()->getInt("pid", pid) == kResultTrue, "H7 pid wire type"); + check(target->notify(message) == kResultTrue, "H7 controller rejected message"); + return kResultTrue; + } +}; +void foreignPid(IConnectionPoint* receiver) { + HostMessage foreign; foreign.setMessageID("Vst3Shm"); + foreign.getAttributes()->setInt("address", 123); foreign.getAttributes()->setInt("pid", platformProcessId() + 1); + check(receiver->notify(&foreign) == kResultTrue, "H7 foreign pid notify"); + puts("PASS H7 foreign pid accepted without crash"); +} +void wireActivation(IComponent* component, Wire& wire) { + FUnknownPtr processor(component); + check(processor != nullptr, "H7 processor interface"); + ProcessSetup setup{kOffline, kSample32, 512, 48000}; + check(processor->setupProcessing(setup) == kResultTrue, "H7 setup"); + check(component->setActive(true) == kResultTrue, "H7 activation"); + check(wire.address != 0 && wire.pid == platformProcessId(), "H7 activation wire payload"); + puts("PASS H7 activation sender and forwarding (internal controller address not observable)"); + check(component->setActive(false) == kResultTrue, "H7 deactivate"); +} +void sharedMemoryWire() { + auto factory = module->getFactory(); + auto component = factory.createInstance(processorUid); + auto controller = factory.createInstance(controllerUid); + check(component->initialize(&host) == kResultTrue, "H7 component initialize"); + check(controller->initialize(&host) == kResultTrue, "H7 controller initialize"); + FUnknownPtr sender(component), receiver(controller); + check(sender && receiver, "H7 interfaces"); + Wire wire; wire.target = receiver; check(sender->connect(&wire) == kResultTrue, "H7 connect"); + wireActivation(component, wire); + const bool cleared = wire.address == 0; + foreignPid(receiver); + sender->disconnect(&wire); controller->terminate(); component->terminate(); + check(cleared, "H7 deactivation payload: processor never sent address 0"); + puts("PASS H7 deactivation payload"); +} +struct Editor { + IPtr controller; + IPtr view; + void* window; + bool terminated{false}; + Editor() { + controller = module->getFactory().createInstance(controllerUid); + check(controller && controller->initialize(&host) == kResultOk, "controller initialize"); + view = owned(controller->createView("editor")); + check(view != nullptr, "createView"); + window = platformCreateWindow(); + check(view->setFrame(platformFrame()) == kResultTrue, "setFrame"); + check(view->attached(window, "unsupported-editor-platform") != kResultTrue, "unsupported platform must not attach"); + platformPump(500); + check(!platformHasVisibleChild(window), "unsupported platform created a child or pending startup"); + check(view->attached(window, platformViewType()) == kResultTrue, "attached"); + } + ~Editor() { + if (view) { view->removed(); view->setFrame(nullptr); view = nullptr; } + if (!terminated) controller->terminate(); + platformDestroyWindow(window); + } + int width() { + ViewRect r; check(view->getSize(&r) == kResultTrue, "getSize"); return r.getWidth(); + } + bool child() { return platformHasVisibleChild(window); } +}; +#include "editor_host_regressions.h" +void rendering(Editor& editor) { + if (!platformCanCapture()) { + puts("NOT RUN Rendering: this OS cannot read the window back in a test"); + return; + } + check(platformRendered(editor.window), "Rendering: the editor window is one uniform colour"); + puts("PASS Rendering"); +} +void concurrent(bool ownerFirst) { + auto a = std::make_unique(); platformPump(500); + auto b = std::make_unique(); platformPump(500); + check(a->width() == 600 && b->width() == 540, "B13 owner stolen or second editor not native"); + check(a->child() && b->child(), "B13 missing mapped child"); + if (ownerFirst) { + a.reset(); platformPump(500); + check(b->width() == 540 && b->child(), "B13 native editor disturbed by owner close"); + check(b->controller->setParamNormalized(0, 0.4) == kResultTrue, "B13 native parameter update"); + b.reset(); auto c = std::make_unique(); platformPump(500); + check(c->width() == 600 && c->child(), "B13 reopen failed"); + } else { + b.reset(); platformPump(500); + check(a->width() == 600 && a->child(), "B13 owner disturbed by secondary close"); + } + puts(ownerFirst ? "PASS B13 owner closed first" : "PASS B13 secondary closed first"); +} +void reopenSameView() { + auto owner = std::make_unique(); platformPump(500); + Editor secondary; platformPump(500); + ViewRect nativeRect(0, 0, 540, 400); + secondary.view->onSize(&nativeRect); + secondary.view->removed(); owner.reset(); + check(secondary.view->attached(secondary.window, platformViewType()) == kResultTrue, "same view reattach"); + platformPump(500); + check(secondary.width() == 600 && secondary.child(), "same view kept stale native host/size"); + puts("PASS B13 same view chooses Flutter again"); +} +void interruptedGesture() { + Editor a; platformPump(1500); + RecordingHandler handler; + a.controller->setComponentHandler(&handler); + auto* controller = dynamic_cast(a.controller.get()); + check(controller != nullptr, "EditController cast"); + controller->beginEdit(0); controller->performEdit(0, 0.37); + a.view->removed(); handler.exactTriple(0.37); + controller->endEdit(0); handler.exactTriple(0.37); + controller->performEdit(0, 0.5); handler.exactTriple(0.37); + check(a.view->attached(a.window, platformViewType()) == kResultTrue, "gesture reattach"); + platformPump(1500); handler.events.clear(); + controller->beginEdit(0); controller->performEdit(0, 0.61); + a.view->removed(); handler.exactTriple(0.61); + a.controller->setComponentHandler(nullptr); + puts("PASS interrupted gesture and fresh begin after reattach"); +} +unsigned long long settledImage(void* window) { + platformPump(300); + auto previous = platformCaptureHash(window); + for (int i = 0; i < 40; ++i) { + platformPump(100); + auto current = platformCaptureHash(window); + if (current == previous) return current; + previous = current; + } + check(false, "parameter image never settled"); return 0; +} +/// Waits for a repaint, since a value reaches the pixels some frames later. +unsigned long long changedImage(void* window, unsigned long long from, const char* failure) { + for (int i = 0; i < 100; ++i) { + platformPump(100); + if (platformCaptureHash(window) != from) return settledImage(window); + } + check(false, failure); return 0; +} +void awaitImage(void* window, unsigned long long expected, const char* failure) { + for (int i = 0; i < 100; ++i) { + platformPump(100); + if (platformCaptureHash(window) == expected) return; + } + check(false, failure); +} +void displayCycle(Editor& a) { + a.controller->setParamNormalized(0, 0.5); platformPump(3000); + auto start = settledImage(a.window); + a.controller->setParamNormalized(0, 0.1); + auto low = changedImage(a.window, start, "parameter 0 display unchanged between 0.5 and 0.1"); + a.controller->setParamNormalized(0, 0.9); + auto high = changedImage(a.window, low, "parameter 0 display unchanged between 0.1 and 0.9"); + MemoryStream state; + check(a.controller->getState(&state) == kResultTrue, "capture 0.9 state"); + a.controller->setParamNormalized(0, 0.1); + awaitImage(a.window, low, "parameter 0 display did not return to 0.1"); + state.seek(0, IBStream::kIBSeekSet, nullptr); + check(a.controller->setComponentState(&state) == kResultTrue, "restore 0.9 state"); + check(a.controller->getParamNormalized(0) == 0.9, "state parameter 0 value"); + awaitImage(a.window, high, "restored state display differs from 0.9"); + a.controller->setParamNormalized(0, 0.1); + awaitImage(a.window, low, "parameter 0 display did not return to 0.1 after restore"); + a.controller->setParamNormalized(0, 1.0); + auto top = changedImage(a.window, low, "parameter 0 display unchanged between 0.1 and 1.0"); + a.controller->setParamNormalized(0, 0.1); + awaitImage(a.window, low, "parameter 0 display did not return to 0.1 from 1.0"); + a.controller->setParamNormalized(0, 1.5); + check(a.controller->getParamNormalized(0) == 1.0, "out-of-range value not clamped"); + awaitImage(a.window, top, "out-of-range value must display as its clamped value"); +} +void reattach(Editor& a) { + check(a.view->attached(a.window, platformViewType()) == kResultTrue, "reattach"); + platformPump(1500); +} +void displaySync() { + if (!platformCanCapture()) { puts("NOT RUN display sync: platform cannot capture"); return; } + Editor a; platformPump(2000); + for (int cycle = 0; cycle < 2; ++cycle) { + displayCycle(a); a.view->removed(); reattach(a); + } + puts("PASS host to UI display sync and reopen"); +} +enum class Drag { completed, releasedWhileClosed, releasedAfterReopen }; +void pointerCycle(Editor& a, RecordingHandler& handler, Drag drag) { + const bool flutter = a.width() == 600; +#if defined(_WIN32) + constexpr int nativeY = 112; +#elif defined(__APPLE__) + constexpr int nativeY = 106; +#else + constexpr int nativeY = 145; +#endif + const int x = flutter ? 137 : 82, y = flutter ? 254 : nativeY; + a.controller->setParamNormalized(0, 0.1); platformPump(500); handler.events.clear(); + platformPress(a.window, x, y); + platformMove(a.window, flutter ? x : 200, flutter ? y - 25 : y); + platformMove(a.window, flutter ? x : 350, flutter ? y - 50 : y); + if (drag == Drag::completed) { + platformRelease(a.window, x, y); + handler.balanced(a.controller->getParamNormalized(0)); + return; + } + a.view->removed(); + handler.balanced(a.controller->getParamNormalized(0)); + if (drag == Drag::releasedWhileClosed) { + platformRelease(a.window, x, y); platformPump(500); + handler.balanced(a.controller->getParamNormalized(0)); + reattach(a); + handler.balanced(a.controller->getParamNormalized(0)); + return; + } + // Holding the button through a close and reopen is unusual, and the release + // can register as a click. It must not break the host's contract. + reattach(a); platformRelease(a.window, x, y); platformPump(1500); + handler.contractHolds(); +} +void pointerGesture() { + if (!platformCanCapture()) { puts("NOT RUN pointer: macOS injection unavailable"); return; } + Editor a; platformPump(15000); RecordingHandler handler; + a.controller->setComponentHandler(&handler); + for (Drag drag : {Drag::completed, Drag::releasedWhileClosed, Drag::completed, + Drag::releasedAfterReopen, Drag::completed}) pointerCycle(a, handler, drag); + a.controller->setComponentHandler(nullptr); puts("PASS pointer completed and interrupted gestures"); +} +void run(const std::string& mode) { + if (mode != "garbage") displaySync(); + if (mode != "garbage") pointerGesture(); + if (mode != "garbage") interruptedGesture(); + if (mode == "good") { + { Editor a; platformPump(15000); check(a.width() == 600 && a.child(), "B12/B14 Dart did not start"); + puts("PASS B12/B14 positive"); } + concurrent(true); concurrent(false); reopenSameView(); + { Editor a; platformPump(500); a.controller->terminate(); a.terminated = true; } + puts("PASS controller terminate before view close"); + { Editor a; platformPump(3000); rendering(a); } + } else { + Editor a; + if (mode == "missing") check(a.width() == 540, "B14 missing AOT did not fall back immediately"); + else { check(mode == "garbage", "unknown mode"); platformPump(13000); } + platformPump(500); + check(a.width() == 540 && a.child(), "B14 failed to mount native fallback"); + Editor b; platformPump(500); + check(b.width() == 540 && b.child(), "B14 second editor did not remain native"); + puts("PASS B14 broken bundle fallback"); + } +} +void loadBundle(const char* path) { + std::string error; module = VST3::Hosting::Module::create(path, error); + check(module != nullptr, error.c_str()); + auto factory = module->getFactory(); factory.setHostContext(&host); + bool found = false; + for (const auto& info : factory.classInfos()) { + if (info.category() == kVstComponentControllerClass) { controllerUid = info.ID(); found = true; } + if (info.category() == kVstAudioEffectClass) processorUid = info.ID(); + } + check(found, "controller class missing"); +} +void separateModules(const char* survivorPath) { + auto firstModule = module; + auto first = std::make_unique(); platformPump(500); + loadBundle(survivorPath); + auto second = std::make_unique(); platformPump(500); + check(first->width() == 540 && second->width() == 540, "H14 native editors required"); + first.reset(); firstModule.reset(); platformPump(500); + Editor survivor; platformPump(500); + check(survivor.width() == 540 && survivor.child(), "H14 survivor editor did not open"); + check(survivor.controller->setParamNormalized(0, 0.37) == kResultTrue, "H14 survivor update"); + check(survivor.controller->getParamNormalized(0) == 0.37, "H14 survivor value"); + if (!platformCanCapture()) { + puts("PASS H14 separate module unload and survivor opens"); + puts("NOT RUN H14 survivor pixels and pointer: macOS has no capture or input on CI"); + return; + } + RecordingHandler handler; survivor.controller->setComponentHandler(&handler); + const auto before = settledImage(survivor.window); + pointerCycle(survivor, handler, Drag::completed); + changedImage(survivor.window, before, "H14 survivor pixels unchanged"); + survivor.controller->setComponentHandler(nullptr); + puts("PASS H14 separate module unload and survivor slider"); +} +int main(int argc, char** argv) { + setvbuf(stdout, nullptr, _IONBF, 0); + try { + check(argc == 3 || argc == 4, "usage: editor_host_test bundle mode [second bundle]"); + platformInit(); + loadBundle(argv[1]); + if (std::string(argv[2]) == "modules") { check(argc == 4, "H14 second path required"); separateModules(argv[3]); } + else if (std::string(argv[2]) == "environment") environmentInvariant(); + else if (std::string(argv[2]) == "immediate") immediateClose(); + else if (std::string(argv[2]) == "wire") sharedMemoryWire(); + else run(argv[2]); + module.reset(); platformShutdown(); puts("PASS ALL EDITOR CASES"); return 0; + } catch (const std::exception& e) { fprintf(stderr, "FAIL %s\n", e.what()); return 1; } +} diff --git a/flutter_vst3/test/native/editor_liveness_test.cpp b/flutter_vst3/test/native/editor_liveness_test.cpp new file mode 100644 index 0000000..6e87617 --- /dev/null +++ b/flutter_vst3/test/native/editor_liveness_test.cpp @@ -0,0 +1,16 @@ +#include "../../native/include/view_logic.h" +#include +#include +int main() { + std::atomic alive{false}; + int calls = 0; + flutter_vst3::withLiveEditor(alive, [&] { ++calls; }); + if (calls != 0) { puts("FAIL H15 dead token ran work"); return 1; } + alive.store(true); + flutter_vst3::withLiveEditor(alive, [&] { calls += 7; }); + if (calls != 7) { puts("FAIL H15 live token skipped work"); return 1; } + alive.store(false); + flutter_vst3::withLiveEditor(alive, [&] { ++calls; }); + if (calls != 7) { puts("FAIL H15 expired token ran work"); return 1; } + puts("PASS H15 dead/live/expired token exact work counts"); +} diff --git a/flutter_vst3/test/native/generator_strings_test.py b/flutter_vst3/test/native/generator_strings_test.py new file mode 100644 index 0000000..c7ab682 --- /dev/null +++ b/flutter_vst3/test/native/generator_strings_test.py @@ -0,0 +1,46 @@ +"""Exercise generator string escaping, identifiers and factory syntax.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile + +root = Path(__file__).resolve().parents[3] +sdk = Path(os.environ['VST3_SDK_DIR']) +assert (sdk / 'pluginterfaces/base/funknown.h').is_file() +metadata = json.loads((root / 'vsts/echo/plugin_metadata.json').read_text()) +with tempfile.TemporaryDirectory(prefix='generator-strings-') as tmp: + path = Path(tmp) + metadata['pluginName'] = 'Space "Echo" \\ 音' + metadata['parameters'][0]['name'] = 'wet-dry' + (path / 'plugin_metadata.json').write_text(json.dumps(metadata)) + command = ['dart', str(root / 'flutter_vst3/scripts/generate_plugin.dart'), str(path), 'echo', 'echo', str(path)] + subprocess.run(command, check=True) + factory = (path / 'generated/echo_factory.cpp').read_text() + assert '"Space \\"Echo\\" \\\\ 音"' in factory, factory + assert 'kWetDryParam = 0,' in (path / 'generated/echo_ids.h').read_text() + assert 'set(JSON_PLUGIN_NAME "Space \\"Echo\\" \\\\ 音")' in (path / 'generated/metadata.cmake').read_text() + for source in ['echo_factory.cpp', 'echo_controller.cpp', 'echo_processor.cpp']: + subprocess.run(['g++', '-std=c++17', '-DNDEBUG', '-fsyntax-only', '-I' + str(sdk), '-I' + str(root / 'flutter_vst3/native/include'), str(path / 'generated' / source)], check=True) + for names, error in [(['wet-dry', 'wet_dry'], 'Metadata error: duplicate parameter identifier WetDry'), ([''], 'Metadata error: unusable identifier: '), (['音'], 'Metadata error: unusable identifier: 音')]: + for param, name in zip(metadata['parameters'], names): + param['name'] = name + (path / 'plugin_metadata.json').write_text(json.dumps(metadata)) + result = subprocess.run(command, text=True, capture_output=True) + assert result.returncode == 1, result.stdout + assert result.stdout.splitlines()[-1] == 'CRITICAL ERROR: FormatException: ' + error, result.stdout + metadata = json.loads((root / 'vsts/echo/plugin_metadata.json').read_text()) + (path / 'plugin_metadata.json').write_text(json.dumps(metadata)) + subprocess.run(command, check=True) + generated = {name: (path / 'generated' / name).read_text().replace('\r\n', '\n') + for name in ['echo_ids.h', 'metadata.cmake', 'echo_factory.cpp']} + for line in ['kDelayTimeParam = 0,', 'kFeedbackParam = 1,', 'kMixParam = 2,', 'kBypassParam = 3,', 'kNumParameters = 4', + 'kEchoProcessorUID(0xF9D0C991, 0x074C8404, 0x4D825FC5, 0x21E8F92B);', + 'kEchoControllerUID(0xA0115732, 0x16F06596, 0x4B9846B6, 0x007933D0);']: + assert line in generated['echo_ids.h'], line + for line in ['set(JSON_PLUGIN_NAME "Echo")', 'set(JSON_BUNDLE_ID "com.cf.echo")', 'set(PARAM_COUNT "4")', + 'set(JSON_FLUTTER_ENTRYPOINT "echoMain")']: + assert line in generated['metadata.cmake'], line + for line in ['"Echo",', '"Echo Controller",', '"Fx|Delay",', '"1.0.0",']: + assert line in generated['echo_factory.cpp'], line + print('PASS exact escaping, identifiers, rejection, SDK syntax and unchanged Echo identifiers, UIDs and factory') diff --git a/flutter_vst3/test/native/ipc_host_recovery_test.cpp b/flutter_vst3/test/native/ipc_host_recovery_test.cpp new file mode 100644 index 0000000..890bdd4 --- /dev/null +++ b/flutter_vst3/test/native/ipc_host_recovery_test.cpp @@ -0,0 +1,217 @@ +// How Vst3IpcHost behaves when its worker is late, dead or failing. + +#include "ipc_test_support.h" + +#include + +namespace { + +/// B1: a late block must not desynchronize any later block. +void testRecoversAfterLateBlock() { + Vst3IpcHost host(gWorker, kParamCount); + host.configure(48000.0, 256, false); + host.setParameter(kParamStallMs, 200); + Block late(256, 0.25f); + check(!late.render(host), "stalled block should be reported late"); + for (float sample : late.outL) checkNear(sample, 0.0, "late block is silent"); + + const auto start = std::chrono::steady_clock::now(); + bool recovered = false; + while (!recovered && msSince(start) < 2000) { + Block next(256, 0.1f); + recovered = next.render(host); + for (float sample : next.outL) checkNear(sample, recovered ? 0.2 : 0.0, "block around the stall"); + if (!recovered) std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + check(recovered, "the host never recovered from a late block"); + int rendered = 0; + for (int i = 0; i < 50; ++i) { + const float value = 0.01f * static_cast(i + 1); + Block block(256, value); + if (!block.render(host)) continue; // A slow machine may miss a realtime deadline. + ++rendered; + checkNear(block.outL[0], value * 2.0, "block returned its own output, not a stale one"); + } + check(rendered > 0, "no block rendered after recovery"); +} + +/// B7: a stalled worker costs one block's budget, and later blocks don't wait. +void testStallIsBounded() { + Vst3IpcHost host(gWorker, kParamCount); + host.configure(48000.0, 480, false); + host.setParameter(kParamStallMs, 500); + Block block(480); + const auto start = std::chrono::steady_clock::now(); + check(!block.render(host), "stalled block should be reported late"); + const double firstMs = msSince(start); + check(firstMs < 40.0, "first late block took " + std::to_string(firstMs) + " ms against a 10 ms budget"); + const auto second = std::chrono::steady_clock::now(); + for (int i = 0; i < 100; ++i) block.render(host); + const double laterMs = msSince(second); + check(laterMs < 50.0, "100 blocks during a stall took " + std::to_string(laterMs) + " ms"); +} + +/// B8: a dead worker produces silence without any per-block wait. +void testDeadWorkerIsBounded() { + Vst3IpcHost host(gWorker, kParamCount); + host.configure(48000.0, 4096, false); + const int64_t pid = host.workerProcessId(); + Vst3SharedMemory* oldBlock = host.memory(); + check(oldBlock->magic == VST3_SHM_MAGIC, "a running worker's block is valid"); + host.setParameter(kParamExit, 1.0); + Block block(4096); + check(!block.render(host), "block from a dying worker should be reported late"); + check(waitUntilGone(pid, 2000), "worker should have exited"); + block.render(host); + check(!host.isRunning(), "host should notice the dead worker"); + check(oldBlock->magic == 0, "a dead worker's block must read as invalid, so the editor can say so"); + host.setParameter(kParamExit, 0.0); + const auto start = std::chrono::steady_clock::now(); + for (int i = 0; i < 1000; ++i) { + check(!block.render(host), "dead worker block must be reported"); + } + const double elapsed = msSince(start); + check(elapsed < 200.0, "1000 blocks with a dead worker took " + std::to_string(elapsed) + " ms"); + for (float sample : block.outL) checkNear(sample, 0.0, "dead worker output is silent"); + host.configure(48000.0, 4096, true); + check(host.isRunning(), "configure should start a new worker"); + check(host.memory()->magic == VST3_SHM_MAGIC, "a new worker's block is valid"); + check(block.render(host), "new worker should render"); + checkNear(block.outL[0], 0.5, "new worker output"); +} + +/// An exception in the DSP is fatal to the worker and visible to the host. +void testDspExceptionIsDetected() { + Vst3IpcHost host(gWorker, kParamCount); + host.configure(48000.0, 4096, false); + host.setParameter(kParamThrow, 1.0); + Block block(4096); + const auto start = std::chrono::steady_clock::now(); + while (host.isRunning() && msSince(start) < 3000) { + block.render(host); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + check(!host.isRunning(), "host should notice a worker killed by a DSP exception"); +} + +/// B7: values set while the worker is late are kept, and the latest one wins. +void testParametersSurviveStall() { + Vst3IpcHost host(gWorker, kParamCount); + host.configure(48000.0, 256, false); + host.setParameter(kParamStallMs, 100); + Block block(256); + block.render(host); + for (int i = 0; i < 1000; ++i) { + host.setParameter(kParamValue, i / 1000.0); + block.render(host); + } + host.configure(48000.0, 256, true); + checkNear(probe(host, kProbeLastValue), 0.999, "latest value arrives after the stall"); +} + +/// A false return means the whole output is silent: that's what the plugin tells +/// the host through its silence flags, so no part may hold audio. +void testPartlyLateBlockIsWhollySilent() { + Vst3IpcHost host(gWorker, kParamCount); + host.configure(48000.0, 8192, false); + host.setParameter(kParamStallNextMs, 500); + Block block(8192, 0.25f); + check(!block.render(host), "a block with a late chunk should be reported late"); + for (size_t i = 0; i < block.outL.size(); ++i) { + check(block.outL[i] == 0.f && block.outR[i] == 0.f, "sample " + std::to_string(i) + " is not silent"); + } +} + +/// [IPC-TIMEOUT-LATE-BLOCK] [IPC-SYNC-HANDOFF]: a control command that +/// outlives its 5 s wait must leave the worker marked busy, so its late done +/// is discarded instead of answering a later activation, whose blocks would +/// then race the worker for the buffers. +void testControlTimeoutKeepsHandshakeInSync() { + constexpr int kParamInitStallMs = 6; + Vst3IpcHost host(gWorker, kParamInitStallMs + 1); + host.configure(48000.0, 64, true); + host.setParameter(kParamInitStallMs, 7000); // CONFIGURE takes 7 s against a 5 s wait. + Block arm(64); + check(arm.render(host), "arming block was late"); + bool threw = false; + try { + host.configure(48000.0, 64, true); + } catch (const std::runtime_error&) { + threw = true; + } + check(threw, "a control command over 5 s must time out"); + host.configure(48000.0, 64, true); + for (int i = 0; i < 20; ++i) { + const float value = 0.01f * static_cast(i + 1); + Block block(64, value); + check(block.render(host), "block after a control timeout was late"); + checkNear(block.outL[0], value * 2.0, "block returned its own output, not a stale one"); + } +} + +/// [PROCESS-WORKER-LAUNCH]: a plugin installed under a user folder whose name +/// the ANSI code page can't express still starts its worker. +void testWorkerStartsFromNonAnsiPath() { + namespace fs = std::filesystem; + const fs::path dir = fs::temp_directory_path() / fs::u8path("flutter_vst3 \xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E"); + fs::remove_all(dir); + fs::create_directories(dir); + const fs::path worker = dir / fs::u8path(gWorker).filename(); + fs::copy_file(fs::u8path(gWorker), worker); + { + Vst3IpcHost host(worker.u8string(), kParamCount); + host.configure(48000.0, 64, true); + Block block(64, 0.25f); + check(block.render(host), "block from a non-ANSI worker path was late"); + checkNear(block.outL[0], 0.5, "worker at a non-ANSI path processes audio"); + } + fs::remove_all(dir); +} + +/// Worker crashes must not cost the host anything: each restart works, and no +/// process handles build up. +void testCrashCyclesLeakNothing() { + Vst3IpcHost host(gWorker, kParamCount); + const auto crashOnce = [&] { + host.configure(48000.0, 64, false); + host.setParameter(kParamExit, 0); + Block good(64, 0.25f); + const auto waited = std::chrono::steady_clock::now(); + bool rendered = false; + while (!rendered && msSince(waited) < 2000) rendered = good.render(host); + check(rendered, "restarted worker never rendered"); + checkNear(good.outL[0], 0.5, "restarted worker output"); + host.setParameter(kParamExit, 1); + const auto start = std::chrono::steady_clock::now(); + Block block(64); + while (host.isRunning() && msSince(start) < 5000) block.render(host); + check(!host.isRunning(), "the host never noticed the crash"); + check(host.workerProcessId() == 0, "a dead worker has no process id"); + }; + crashOnce(); +#ifdef _WIN32 + DWORD before = 0, after = 0; + check(GetProcessHandleCount(GetCurrentProcess(), &before) != 0, "GetProcessHandleCount"); +#endif + for (int i = 0; i < 20; ++i) crashOnce(); +#ifdef _WIN32 + check(GetProcessHandleCount(GetCurrentProcess(), &after) != 0, "GetProcessHandleCount"); + check(after < before + 10, "process handles grew from " + std::to_string(before) + " to " + std::to_string(after)); +#endif +} + +} // namespace + +IpcTests recoveryTests() { + return { + {"B1 recovers after a late block", testRecoversAfterLateBlock}, + {"B7 stall is bounded", testStallIsBounded}, + {"B7 parameters survive a stall", testParametersSurviveStall}, + {"B8 dead worker is bounded", testDeadWorkerIsBounded}, + {"DSP exception is detected", testDspExceptionIsDetected}, + {"partly late block is wholly silent", testPartlyLateBlockIsWhollySilent}, + {"control timeout keeps handshake in sync", testControlTimeoutKeepsHandshakeInSync}, + {"worker starts from a non-ANSI path", testWorkerStartsFromNonAnsiPath}, + {"crash cycles leak nothing", testCrashCyclesLeakNothing}, + }; +} diff --git a/flutter_vst3/test/native/ipc_host_test.cpp b/flutter_vst3/test/native/ipc_host_test.cpp new file mode 100644 index 0000000..d26b998 --- /dev/null +++ b/flutter_vst3/test/native/ipc_host_test.cpp @@ -0,0 +1,223 @@ +// Round-trip tests of Vst3IpcHost against a real compiled Dart worker. +// +// Usage: ipc_host_test [--host-then-die ] +// Every failure exits non-zero. + +#include +#include +#include + +#include "ipc_test_support.h" + +namespace { + +void testRoundTrip() { + Vst3IpcHost host(gWorker, kParamCount); + host.configure(48000.0, 512, true); + Block block(512, 0.25f); + check(block.render(host), "block was late"); + for (float sample : block.outL) checkNear(sample, 0.5, "output is the worker's output"); + checkNear(probe(host, kProbeSampleRate), 48000.0, "worker saw the sample rate"); + checkNear(probe(host, kProbeMaxBlock), 512.0, "worker saw the block size"); +} + +/// B2: the live worker must see changes to rate and block size. +void testReconfigure() { + Vst3IpcHost host(gWorker, kParamCount); + host.configure(44100.0, 512, true); + const int64_t pid = host.workerProcessId(); + host.setParameter(kParamValue, 0.75); + Block block(16); + check(block.render(host), "block was late"); + host.configure(96000.0, 2048, true); + check(host.workerProcessId() == pid, "reconfigure should keep the worker"); + checkNear(probe(host, kProbeSampleRate), 96000.0, "sample rate after reconfigure"); + checkNear(probe(host, kProbeMaxBlock), 2048.0, "block size after reconfigure"); + checkNear(probe(host, kProbeLastValue), 0.75, "parameters survive reconfigure"); +} + +/// Parameters set before the worker exists must reach it. +void testParametersReplayToNewWorker() { + Vst3IpcHost host(gWorker, kParamCount); + host.setParameter(kParamValue, 0.625); + host.configure(48000.0, 64, true); + checkNear(probe(host, kProbeLastValue), 0.625, "value set before start"); + host.dispose(); + host.configure(48000.0, 64, true); + checkNear(probe(host, kProbeLastValue), 0.625, "value replayed to a restarted worker"); +} + +/// B3: failed startup throws quickly and leaves nothing behind. +void testStartupFailure(const std::string& badPath, const char* label) { + Vst3IpcHost host(badPath, kParamCount); + const auto start = std::chrono::steady_clock::now(); + bool threw = false; + try { + host.configure(48000.0, 512, false); + } catch (const std::runtime_error&) { + threw = true; + } + check(threw, std::string(label) + ": configure should throw"); + check(msSince(start) < 1000.0, std::string(label) + ": failure should be fast"); + check(!host.isRunning(), std::string(label) + ": host should not be running"); + check(host.workerProcessId() == 0, std::string(label) + ": child should be gone"); + Block block(16); + check(!block.render(host), std::string(label) + ": rendering should report failure"); + checkNear(block.outL[0], 0.0, std::string(label) + ": output should be silent"); +} + +/// B4: blocks over the shared buffer size are processed completely. +void testOversizedBlock() { + Vst3IpcHost host(gWorker, kParamCount); + host.configure(48000.0, 10000, true); + Block block(10000); + for (int i = 0; i < 10000; ++i) block.inL[static_cast(i)] = static_cast(i) / 10000.0f; + check(block.render(host), "oversized block was late"); + for (int i = 0; i < 10000; ++i) { + checkNear(block.outL[static_cast(i)], 2.0 * i / 10000.0, "sample " + std::to_string(i)); + } + checkNear(probe(host, kProbeBlocks), 4.0, "10000 samples take 3 chunks, plus this probe"); +} + +/// B5: instances have separate DSP state and independent lifetimes. +void testInstancesAreIsolated() { + Vst3IpcHost a(gWorker, kParamCount); + Vst3IpcHost b(gWorker, kParamCount); + a.configure(44100.0, 128, true); + b.configure(96000.0, 256, true); + check(a.workerProcessId() != b.workerProcessId(), "each instance has its own worker"); + a.setParameter(kParamValue, 0.1); + b.setParameter(kParamValue, 0.9); + Block block(16); + check(block.render(a), "render a"); + check(block.render(b), "render b"); + checkNear(probe(a, kProbeSampleRate), 44100.0, "a keeps its sample rate"); + checkNear(probe(b, kProbeSampleRate), 96000.0, "b keeps its sample rate"); + checkNear(probe(a, kProbeLastValue), 0.1, "a keeps its parameter"); + checkNear(probe(b, kProbeLastValue), 0.9, "b keeps its parameter"); + a.dispose(); + check(block.render(b), "b must survive disposing a"); + checkNear(block.outL[0], 0.5, "b output after disposing a"); +} + +/// B10: reset reaches the DSP. +void testReset() { + Vst3IpcHost host(gWorker, kParamCount); + host.reset(); // Must be harmless with no worker. + host.configure(48000.0, 64, true); + host.reset(); + host.reset(); + checkNear(probe(host, kProbeResets), 2.0, "both resets reached the DSP"); +} + +/// B9: the reader's memory stays readable after dispose, and shows as dead. +void testMemoryStaysReadableAfterDispose() { + std::vector blocks; + for (int i = 0; i < 3; ++i) { + Vst3IpcHost host(gWorker, kParamCount); + host.configure(48000.0, 64, true); + Vst3SharedMemory* memory = host.memory(); + check(memory->magic == VST3_SHM_MAGIC, "live block has the magic word"); + blocks.push_back(memory); + host.dispose(); + check(memory->magic == 0, "disposed block has no magic word"); + } + check(blocks[0] == blocks[1] && blocks[1] == blocks[2], "retired blocks are reused, so the cost is bounded"); +} + +void testDisposeStopsWorker() { + Vst3IpcHost host(gWorker, kParamCount); + host.configure(48000.0, 64, true); + const int64_t pid = host.workerProcessId(); + host.dispose(); + host.dispose(); + check(host.workerProcessId() == 0, "no worker after dispose"); + check(waitUntilGone(pid, 2000), "worker process exited"); +} + +/// Inherited host descriptors must not leak into the worker. +void testWorkerDoesNotInheritDescriptors() { +#ifndef _WIN32 + int fds[2]; + check(pipe(fds) == 0, "pipe"); + Vst3IpcHost host(gWorker, kParamCount); + host.configure(48000.0, 64, true); + close(fds[1]); + char byte = 0; + alarm(5); + const ssize_t got = read(fds[0], &byte, 1); + alarm(0); + close(fds[0]); + check(got == 0, "worker kept the host's descriptor open"); +#endif +} + +/// B8: run as a child by testWorkerExitsWhenHostDies, this dies without cleanup. +int hostThenDie(const std::string& pidFile) { + Vst3IpcHost* host = new Vst3IpcHost(gWorker, kParamCount); + host->configure(48000.0, 64, true); + std::ofstream(pidFile) << host->workerProcessId(); +#ifdef _WIN32 + TerminateProcess(GetCurrentProcess(), 9); +#else + kill(getpid(), SIGKILL); +#endif + return 0; +} + +void testWorkerExitsWhenHostDies(const std::string& self) { + const std::string pidFile = self + ".pid"; + std::remove(pidFile.c_str()); +#ifdef _WIN32 + const std::string cmd = "\"\"" + self + "\" \"" + gWorker + "\" --host-then-die \"" + pidFile + "\"\""; +#else + const std::string cmd = "\"" + self + "\" \"" + gWorker + "\" --host-then-die \"" + pidFile + "\""; +#endif + const int childStatus = std::system(cmd.c_str()); + check(childStatus != 0, "child host should have died by signal"); + int64_t pid = 0; + std::ifstream(pidFile) >> pid; + std::remove(pidFile.c_str()); + check(pid > 0, "child host should report its worker"); + check(waitUntilGone(pid, 5000), "worker must exit when its host dies"); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc < 2) { + std::fprintf(stderr, "usage: %s \n", argv[0]); + return 2; + } + gWorker = argv[1]; + if (argc == 4 && std::string(argv[2]) == "--host-then-die") return hostThenDie(argv[3]); + const std::string self = argv[0]; + + IpcTests tests = { + {"round trip", testRoundTrip}, + {"B2 reconfigure reaches the worker", testReconfigure}, + {"B3 missing worker fails fast", [] { testStartupFailure(gWorker + ".missing", "missing"); }}, + {"B4 oversized block", testOversizedBlock}, + {"B5 instances are isolated", testInstancesAreIsolated}, + {"B8 worker exits when the host dies", [&] { testWorkerExitsWhenHostDies(self); }}, + {"B9 memory stays readable after dispose", testMemoryStaysReadableAfterDispose}, + {"B10 reset reaches the DSP", testReset}, + {"parameters replay to a new worker", testParametersReplayToNewWorker}, + {"dispose stops the worker", testDisposeStopsWorker}, + {"worker does not inherit descriptors", testWorkerDoesNotInheritDescriptors}, + }; + for (auto& test : recoveryTests()) tests.push_back(std::move(test)); + int failures = 0; + for (const auto& test : tests) { + try { + test.second(); + std::printf("PASS %s\n", test.first.c_str()); + } catch (const std::exception& error) { + ++failures; + std::printf("FAIL %s: %s\n", test.first.c_str(), error.what()); + } + std::fflush(stdout); + } + std::printf("%d of %zu failed\n", failures, tests.size()); + return failures == 0 ? 0 : 1; +} diff --git a/flutter_vst3/test/native/ipc_platform_test.cpp b/flutter_vst3/test/native/ipc_platform_test.cpp new file mode 100644 index 0000000..2b3d6b6 --- /dev/null +++ b/flutter_vst3/test/native/ipc_platform_test.cpp @@ -0,0 +1,132 @@ +// Direct platform regression tests; include host implementation to test private naming. +#include "vst3_ipc_host.cpp" +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#include +#include +#include +#include +#endif +using namespace vst3_ipc; +void check(bool value, const char* message) { + if (!value) throw std::runtime_error(message); +} +void namesTest() { + const auto a = reinterpret_cast(uintptr_t{0x12345678}); + const auto b = reinterpret_cast(uintptr_t{0x12355678}); + const auto first = uniqueName(shmPrefix(), a); + const auto second = uniqueName(shmPrefix(), b); + check(first != second, "host names collide"); + check(first.find("_12345678_") != std::string::npos, "first owner truncated"); + check(second.find("_12355678_") != std::string::npos, "second owner truncated"); + std::cout << "PASS full owner names with identical low 16 bits\n"; +} +void mapCollision(std::string name, Vst3SharedMemory* memory) { + memory->magic = 0x1234abcd; + void* duplicateHandle = nullptr; + bool threw = false; + try { mapCreate(name, duplicateHandle); } + catch (const std::runtime_error&) { threw = true; } + check(memory->magic == 0x1234abcd, "mapping sentinel changed"); + check(threw, "duplicate mapping did not throw"); +} +void semaphoreCollision(const std::string& name, void* sem) { + semPost(sem); + bool threw = false; + try { semCreate(name); } + catch (const std::runtime_error&) { threw = true; } + check(semTryWait(sem), "semaphore sentinel lost"); + check(!semTryWait(sem), "semaphore count not exactly one"); + check(threw, "duplicate semaphore did not throw"); +} +#ifndef _WIN32 +void permissions(const std::string& name, const std::string& sem) { + (void)sem; // macOS does not expose a named semaphore's filesystem mode. + struct stat info{}; + const int fd = shm_open(name.c_str(), O_RDWR, 0); + check(fd >= 0, "shm_open inspection failed"); + check(fstat(fd, &info) == 0, "fstat failed"); + close(fd); + check((info.st_mode & 0777) == 0600, "mapping mode != 0600"); +#ifdef __linux__ + const auto path = "/dev/shm/sem." + sem.substr(1); + check(stat(path.c_str(), &info) == 0, "semaphore stat failed"); + check((info.st_mode & 0777) == 0600, "semaphore mode != 0600"); +#endif +} +#endif +void resourcesTest() { + auto name = uniqueName(shmPrefix(), nullptr); + const auto semName = uniqueName(semReadyPrefix(), nullptr); + void* handle = nullptr; + auto* memory = mapCreate(name, handle); + auto* sem = semCreate(semName); +#ifndef _WIN32 + permissions(name, semName); +#endif + mapCollision(name, memory); + semaphoreCollision(semName, sem); + semRelease(sem); + unlinkNames(name, semName, semName); + mapRetire(memory, handle, name); + std::cout << "PASS exclusive resources, sentinels and permissions\n"; +} +#ifndef _WIN32 +std::string exitFile; +void recordExit() { + const int fd = open(exitFile.c_str(), O_WRONLY | O_APPEND); + const auto pid = std::to_string(getpid()) + "\n"; + if (fd < 0 || write(fd, pid.data(), pid.size()) != static_cast(pid.size())) _exit(99); + close(fd); +} +void failedExecChild() { + check(atexit(recordExit) == 0, "atexit failed"); + const auto child = spawnWorker("/definitely/missing/vst3-worker", "", "", ""); + int status = 0; + check(waitpid(static_cast(child), &status, 0) == child, "worker wait failed"); + check(WIFEXITED(status) && WEXITSTATUS(status) == 127, "exec failure status != 127"); + _exit(0); +} +void failedExecTest() { + char path[] = "/tmp/ipc_platform_exit_XXXXXX"; + const int fd = mkstemp(path); + check(fd >= 0, "mkstemp failed"); + close(fd); + exitFile = path; + const auto child = fork(); + check(child >= 0, "test fork failed"); + if (child == 0) failedExecChild(); + int status = 0; + check(waitpid(child, &status, 0) == child && status == 0, "child mode failed"); + struct stat info{}; + check(stat(path, &info) == 0, "exit file stat failed"); + unlink(path); + check(info.st_size == 0, "failed exec ran host atexit handler"); + std::cout << "PASS failed exec never runs host atexit handlers\n"; +} +#else +#include "ipc_platform_windows.h" +#endif +int main(int argc, char** argv) { + try { +#ifdef _WIN32 + if (argc > 1) return windowsChild(argv[1]); + windowsTest(argv[0]); +#else + (void)argc; (void)argv; + umask(0); + failedExecTest(); +#endif + namesTest(); + resourcesTest(); + return 0; + } catch (const std::exception& error) { + std::cerr << "FAIL " << error.what() << '\n'; + return 1; + } +} diff --git a/flutter_vst3/test/native/ipc_platform_windows.h b/flutter_vst3/test/native/ipc_platform_windows.h new file mode 100644 index 0000000..2242bc9 --- /dev/null +++ b/flutter_vst3/test/native/ipc_platform_windows.h @@ -0,0 +1,54 @@ +#pragma once +#include +#include +#include +std::set consoles; +DWORD workerPid = 0; +bool visibleWorker = false; +BOOL CALLBACK inspectWindow(HWND window, LPARAM) { + char name[128]{}; + GetClassNameA(window, name, sizeof(name)); + if (std::string(name) == "ConsoleWindowClass") consoles.insert(window); + DWORD pid = 0; + GetWindowThreadProcessId(window, &pid); + if (pid == workerPid && IsWindowVisible(window)) visibleWorker = true; + return TRUE; +} +void detachedTest(const char* executable) { + FreeConsole(); + check(GetConsoleWindow() == nullptr, "test still has console"); + check(EnumWindows(inspectWindow, 0) != 0, "initial EnumWindows failed"); + const auto before = consoles; + consoles.clear(); + const auto worker = spawnWorker(executable, "worker", "", ""); + workerPid = static_cast(childPid(worker)); + std::this_thread::sleep_for(std::chrono::milliseconds(1500)); + check(childAlive(worker), "console worker died prematurely"); + check(EnumWindows(inspectWindow, 0) != 0, "worker EnumWindows failed"); + childStop(worker, 0); + check(!visibleWorker, "worker owns a visible window"); + for (auto window : consoles) check(before.count(window) == 1, "new ConsoleWindowClass window"); +} +int windowsChild(const char* mode) { + if (std::string(mode) == "worker") { Sleep(10000); return 0; } + check(std::string(mode) == "detached", "unknown child mode"); + char executable[MAX_PATH]{}; + check(GetModuleFileNameA(nullptr, executable, MAX_PATH) != 0, "executable lookup failed"); + detachedTest(executable); + return 0; +} +void windowsTest(const char* executable) { + std::string command = std::string("\"") + executable + "\" detached"; + STARTUPINFOA startup{}; + startup.cb = sizeof(startup); + PROCESS_INFORMATION process{}; + check(CreateProcessA(nullptr, command.data(), nullptr, nullptr, FALSE, CREATE_NO_WINDOW, + nullptr, nullptr, &startup, &process) != 0, "child mode spawn failed"); + check(WaitForSingleObject(process.hProcess, 15000) == WAIT_OBJECT_0, "child mode timed out"); + DWORD result = 99; + check(GetExitCodeProcess(process.hProcess, &result) != 0, "child mode status failed"); + CloseHandle(process.hThread); + CloseHandle(process.hProcess); + check(result == 0, "detached console test failed"); + std::cout << "PASS detached worker has no visible or new console window\n"; +} diff --git a/flutter_vst3/test/native/ipc_test_support.h b/flutter_vst3/test/native/ipc_test_support.h new file mode 100644 index 0000000..7c4da5e --- /dev/null +++ b/flutter_vst3/test/native/ipc_test_support.h @@ -0,0 +1,91 @@ +// Helpers shared by the Vst3IpcHost tests, which run against a real compiled +// Dart worker (probe_worker.dart). +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "vst3_ipc_host.h" + +#ifdef _WIN32 +#include +#else +#include +#include +#include +#endif + +constexpr int kParamStallMs = 0; +constexpr int kParamExit = 1; +constexpr int kParamThrow = 2; +constexpr int kParamProbe = 3; +constexpr int kParamValue = 4; +constexpr int kParamStallNextMs = 5; +constexpr int kParamCount = 6; +constexpr int kProbeSampleRate = 1; +constexpr int kProbeMaxBlock = 2; +constexpr int kProbeBlocks = 3; +constexpr int kProbeResets = 4; +constexpr int kProbeLastValue = 5; + +inline std::string gWorker; + +inline void check(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +inline void checkNear(double actual, double expected, const std::string& message) { + check(std::fabs(actual - expected) < 1e-3, + message + ": expected " + std::to_string(expected) + ", got " + std::to_string(actual)); +} + +struct Block { + std::vector inL, inR, outL, outR; + explicit Block(int size, float value = 0.25f) : inL(size, value), inR(size, value), outL(size, 9.f), outR(size, 9.f) {} + bool render(Vst3IpcHost& host) { + return host.process(inL.data(), inR.data(), outL.data(), outR.data(), static_cast(inL.size())); + } +}; + +inline double probe(Vst3IpcHost& host, int which) { + host.setParameter(kParamProbe, which); + Block block(16); + check(block.render(host), "probe block was late"); + return block.outR[0]; +} + +inline double msSince(std::chrono::steady_clock::time_point start) { + return std::chrono::duration(std::chrono::steady_clock::now() - start).count(); +} + +inline bool workerGone(int64_t pid) { +#ifdef _WIN32 + HANDLE handle = OpenProcess(SYNCHRONIZE, FALSE, static_cast(pid)); + if (!handle) return true; + const bool gone = WaitForSingleObject(handle, 0) == WAIT_OBJECT_0; + CloseHandle(handle); + return gone; +#else + return kill(static_cast(pid), 0) != 0; +#endif +} + +inline bool waitUntilGone(int64_t pid, int timeoutMs) { + const auto start = std::chrono::steady_clock::now(); + while (msSince(start) < timeoutMs) { + if (workerGone(pid)) return true; + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + return false; +} + +using IpcTests = std::vector>>; + +/// Tests of how the host behaves when its worker is late, dead or failing. +IpcTests recoveryTests(); diff --git a/flutter_vst3/test/native/plugin_host_test.cpp b/flutter_vst3/test/native/plugin_host_test.cpp new file mode 100644 index 0000000..d20b134 --- /dev/null +++ b/flutter_vst3/test/native/plugin_host_test.cpp @@ -0,0 +1,398 @@ +// End-to-end tests of a real built Echo .vst3 bundle, loaded through the VST3 SDK +// hosting classes the way a DAW loads it, with its real Dart worker. +// +// Usage: plugin_host_test +// Every failure exits non-zero. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "base/source/fobject.h" +#include "pluginterfaces/vst/ivstaudioprocessor.h" +#include "pluginterfaces/vst/ivstcomponent.h" +#include "pluginterfaces/vst/ivsteditcontroller.h" +#include "public.sdk/source/common/memorystream.h" +#include "public.sdk/source/vst/hosting/hostclasses.h" +#include "public.sdk/source/vst/hosting/module.h" +#include "public.sdk/source/vst/hosting/parameterchanges.h" + +using namespace Steinberg; +using namespace Steinberg::Vst; + +namespace { + +constexpr ParamID kDelay = 0; +constexpr ParamID kFeedback = 1; +constexpr ParamID kMix = 2; +constexpr int32 kBlock = 512; + +HostApplication gHost; +std::shared_ptr gModule; +VST3::UID gProcessorUid; +std::string gWorkerPath; + +void check(bool condition, const std::string& message) { + if (!condition) throw std::runtime_error(message); +} + +using Params = std::vector>; + +class Instance { +public: + Instance() { + auto factory = gModule->getFactory(); + factory.setHostContext(&gHost); + component_ = factory.createInstance(gProcessorUid); + check(component_ != nullptr, "failed to create the processor"); + check(component_->initialize(&gHost) == kResultOk, "initialize failed"); + processor_ = FUnknownPtr(component_); + check(processor_ != nullptr, "component is not an IAudioProcessor"); + component_->activateBus(kAudio, kInput, 0, true); + component_->activateBus(kAudio, kOutput, 0, true); + } + + ~Instance() { + if (active_) deactivate(); + component_->terminate(); + } + + tresult activate(double sampleRate) { + ProcessSetup setup{kOffline, kSample32, kBlock, sampleRate}; + check(processor_->setupProcessing(setup) == kResultOk, "setupProcessing failed"); + const tresult result = component_->setActive(true); + if (result != kResultOk) return result; + processor_->setProcessing(true); + active_ = true; + return result; + } + + void deactivate() { + processor_->setProcessing(false); + check(component_->setActive(false) == kResultOk, "setActive(false) failed"); + active_ = false; + } + + /// Renders one block and returns the left output. + std::vector render(const std::vector& input, const Params& params = {}, tresult* status = nullptr) { + std::vector inL(input), inR(input), outL(input.size(), 7.f), outR(input.size(), 7.f); + float* inPtrs[2] = {inL.data(), inR.data()}; + float* outPtrs[2] = {outL.data(), outR.data()}; + AudioBusBuffers inBus{}; + inBus.numChannels = 2; + inBus.channelBuffers32 = inPtrs; + AudioBusBuffers outBus{}; + outBus.numChannels = 2; + outBus.channelBuffers32 = outPtrs; + ParameterChanges changes(static_cast(params.size()) + 1); + for (const auto& param : params) { + int32 index = 0; + auto* queue = changes.addParameterData(param.first, index); + queue->addPoint(0, param.second, index); + } + ProcessData data; + data.processMode = kOffline; + data.symbolicSampleSize = kSample32; + data.numSamples = static_cast(input.size()); + data.numInputs = 1; + data.numOutputs = 1; + data.inputs = &inBus; + data.outputs = &outBus; + data.inputParameterChanges = &changes; + const tresult result = processor_->process(data); + if (status) *status = result; + else check(result == kResultOk, "process failed"); + return outL; + } + + IComponent* component() { return component_.get(); } + IAudioProcessor* processor() { return processor_.get(); } + +private: + IPtr component_; + IPtr processor_; + bool active_ = false; +}; + +std::vector silence(int32 size = kBlock) { return std::vector(static_cast(size), 0.f); } + +std::vector impulse() { + auto block = silence(); + block[0] = 1.f; + return block; +} + +/// Sends an impulse and returns the sample position of the first echo. +int measureEchoPosition(Instance& instance, int maxSamples) { + auto out = instance.render(impulse()); + for (int position = 0; position < maxSamples; position += kBlock) { + for (int i = 0; i < kBlock; ++i) { + if (std::fabs(out[static_cast(i)]) > 0.1f) return position + i; + } + out = instance.render(silence()); + } + return -1; +} + +void checkEchoAt(Instance& instance, int expected, const std::string& label) { + const int position = measureEchoPosition(instance, expected + 4 * kBlock); + check(std::abs(position - expected) <= 2, + label + ": expected the echo at " + std::to_string(expected) + ", got " + std::to_string(position)); +} + +/// Applies wet-only settings with a delay of delayValue, on a silent block. +void applyEchoSettings(Instance& instance, double delayValue) { + instance.render(silence(), {{kDelay, delayValue}, {kFeedback, 0.0}, {kMix, 1.0}}); +} + +/// B2: delay time in samples must track the host's sample rate. +void testSampleRateReachesDsp() { + Instance instance; + check(instance.activate(48000.0) == kResultOk, "activate failed"); + applyEchoSettings(instance, 0.1); + checkEchoAt(instance, 4800, "100 ms at 48 kHz"); + instance.deactivate(); + check(instance.activate(96000.0) == kResultOk, "reactivate failed"); + applyEchoSettings(instance, 0.1); + checkEchoAt(instance, 9600, "100 ms at 96 kHz"); +} + +/// B3: a missing worker is a failed activation, not silence or a crash. +void testMissingWorkerFailsActivation() { + const std::string moved = gWorkerPath + ".moved"; + check(std::rename(gWorkerPath.c_str(), moved.c_str()) == 0, "failed to move the worker aside"); + tresult activation = kResultOk; + tresult processing = kResultOk; + std::vector out; + { + Instance instance; + activation = instance.activate(48000.0); + out = instance.render(impulse(), {}, &processing); + } + check(std::rename(moved.c_str(), gWorkerPath.c_str()) == 0, "failed to restore the worker"); + check(activation != kResultOk, "activation must fail without a worker"); + check(processing == kNotInitialized, "process must report that it isn't initialized"); + for (float sample : out) check(sample == 0.f, "output must be silent without a worker"); +} + +/// B5: two instances of one plugin share nothing. +void testInstancesAreIsolated() { + Instance a; + Instance b; + check(a.activate(48000.0) == kResultOk, "activate a"); + check(b.activate(48000.0) == kResultOk, "activate b"); + applyEchoSettings(a, 0.05); + applyEchoSettings(b, 0.05); + a.render(impulse()); + for (int i = 0; i < 20; ++i) { + for (float sample : b.render(silence())) { + check(sample == 0.f, "an impulse into a must not be heard in b"); + } + } + b.render(impulse()); + a.deactivate(); + a.activate(48000.0); + a.deactivate(); + int heard = 0; + for (int i = 0; i < 20; ++i) { + for (float sample : b.render(silence())) heard += std::fabs(sample) > 0.1f ? 1 : 0; + } + check(heard > 0, "b must keep working while a is stopped"); +} + +/// B6: saved state must reach the DSP of a new instance. +void testSavedStateReachesDsp() { + MemoryStream stream; + { + Instance original; + check(original.activate(48000.0) == kResultOk, "activate original"); + applyEchoSettings(original, 0.25); + check(original.component()->getState(&stream) == kResultOk, "getState failed"); + } + stream.seek(0, IBStream::kIBSeekSet, nullptr); + Instance restored; + check(restored.component()->setState(&stream) == kResultOk, "setState failed"); + check(restored.activate(48000.0) == kResultOk, "activate restored"); + restored.render(silence()); + checkEchoAt(restored, 12000, "restored 250 ms delay"); +} + +/// A short state stream must be rejected. +void testTruncatedStateIsRejected() { + MemoryStream stream; + double only = 0.5; + stream.write(&only, sizeof(only), nullptr); + stream.seek(0, IBStream::kIBSeekSet, nullptr); + Instance instance; + check(instance.component()->setState(&stream) != kResultOk, "truncated state must be rejected"); +} + +/// Effects with feedback ring on after the input ends, so the host must keep rendering. +void testTailIsReported() { + Instance instance; + check(instance.processor()->getTailSamples() == kInfiniteTail, "the echo's tail must not be reported as absent"); +} + +std::vector savedValues(IComponent* component) { + MemoryStream stream; + check(component->getState(&stream) == kResultOk, "getState failed"); + int64 size = 0; + stream.seek(0, IBStream::kIBSeekEnd, &size); + stream.seek(0, IBStream::kIBSeekSet, nullptr); + std::vector values(static_cast(size) / sizeof(double)); + int32 bytes = 0; + stream.read(values.data(), static_cast(size), &bytes); + check(bytes == size && !values.empty(), "state holds whole values"); + return values; +} + +void loadInto(MemoryStream& stream, const std::vector& values) { + stream.write(const_cast(values.data()), static_cast(values.size() * sizeof(double)), nullptr); + stream.seek(0, IBStream::kIBSeekSet, nullptr); +} + +const std::vector& badValues() { + static const std::vector values = {std::numeric_limits::quiet_NaN(), + std::numeric_limits::infinity(), -0.5, 1.5}; + return values; +} + +/// Corrupt state must not reach the DSP, and must leave the instance as it was. +void testProcessorRejectsInvalidState() { + Instance instance; + const auto before = savedValues(instance.component()); + for (double bad : badValues()) { + auto values = before; + values.back() = bad; + MemoryStream stream; + loadInto(stream, values); + check(instance.component()->setState(&stream) != kResultOk, "invalid value must be rejected"); + check(savedValues(instance.component()) == before, "a rejected state must change nothing"); + } +} + +/// The controller reads the same state, and must treat it the same way. +void testControllerRejectsInvalidState() { + Instance instance; + TUID cid; + check(instance.component()->getControllerClassId(cid) == kResultTrue, "getControllerClassId"); + auto factory = gModule->getFactory(); + auto controller = factory.createInstance(VST3::UID::fromTUID(cid)); + check(controller != nullptr, "create controller"); + check(controller->initialize(&gHost) == kResultOk, "initialize controller"); + const auto saved = savedValues(instance.component()); + for (size_t i = 0; i < saved.size(); ++i) check(controller->setParamNormalized(static_cast(i), 0.75) == kResultOk, "set"); + const auto unchanged = [&](const std::string& label) { + for (size_t i = 0; i < saved.size(); ++i) { + check(controller->getParamNormalized(static_cast(i)) == 0.75, label + " changed a parameter"); + } + }; + for (double bad : badValues()) { + auto values = saved; + values.back() = bad; + MemoryStream stream; + loadInto(stream, values); + check(controller->setComponentState(&stream) != kResultOk, "invalid value must be rejected"); + unchanged("an invalid state"); + } + MemoryStream truncated; + loadInto(truncated, {0.25}); + check(controller->setComponentState(&truncated) != kResultOk, "truncated state must be rejected"); + unchanged("a truncated state"); + MemoryStream good; + loadInto(good, std::vector(saved.size(), 0.25)); + check(controller->setComponentState(&good) == kResultOk, "valid state accepted"); + for (size_t i = 0; i < saved.size(); ++i) check(controller->getParamNormalized(static_cast(i)) == 0.25, "valid state applied"); + controller->terminate(); +} + +/// Hosts find a plugin in saved projects by UID, so Echo's must never change. +void testEchoKeepsItsUid() { + TUID expected; + FUID(0xF9D0C991, 0x074C8404, 0x4D825FC5, 0x21E8F92B).toTUID(expected); + check(gProcessorUid == VST3::UID::fromTUID(expected), "Echo's processor UID changed"); +} + +/// B10: stopping must clear the tail. +void testDeactivateClearsTail() { + Instance instance; + check(instance.activate(48000.0) == kResultOk, "activate"); + applyEchoSettings(instance, 0.05); + instance.render(impulse()); + instance.deactivate(); + check(instance.activate(48000.0) == kResultOk, "reactivate"); + for (int i = 0; i < 20; ++i) { + for (float sample : instance.render(silence())) { + check(sample == 0.f, "a tail from before deactivation must not play"); + } + } +} + +/// B4: a block larger than the shared buffer must be fully rendered. +void testOversizedBlock() { + Instance instance; + check(instance.activate(48000.0) == kResultOk, "activate"); + instance.render(silence(), {{kFeedback, 0.0}, {kMix, 0.0}}); + std::vector input(10000, 0.5f); + const auto out = instance.render(input); + for (size_t i = 0; i < out.size(); ++i) { + check(std::fabs(out[i] - 0.5f) < 1e-3f, "sample " + std::to_string(i) + " was not rendered"); + } +} + +VST3::UID findProcessor() { + for (const auto& info : gModule->getFactory().classInfos()) { + if (info.category() == kVstAudioEffectClass) return info.ID(); + } + throw std::runtime_error("the module has no audio effect class"); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc != 3) { + std::fprintf(stderr, "usage: %s \n", argv[0]); + return 2; + } + std::string error; + gModule = VST3::Hosting::Module::create(argv[1], error); + if (!gModule) { + std::fprintf(stderr, "failed to load %s: %s\n", argv[1], error.c_str()); + return 2; + } + gProcessorUid = findProcessor(); + gWorkerPath = argv[2]; + + const std::vector>> tests = { + {"B2 sample rate reaches the DSP", testSampleRateReachesDsp}, + {"B3 missing worker fails activation", testMissingWorkerFailsActivation}, + {"B4 oversized block", testOversizedBlock}, + {"B5 instances are isolated", testInstancesAreIsolated}, + {"B6 saved state reaches the DSP", testSavedStateReachesDsp}, + {"B6 truncated state is rejected", testTruncatedStateIsRejected}, + {"B10 deactivate clears the tail", testDeactivateClearsTail}, + {"tail is reported", testTailIsReported}, + {"Echo keeps its UID", testEchoKeepsItsUid}, + {"processor rejects invalid state", testProcessorRejectsInvalidState}, + {"controller rejects invalid state", testControllerRejectsInvalidState}, + }; + int failures = 0; + for (const auto& test : tests) { + try { + test.second(); + std::printf("PASS %s\n", test.first.c_str()); + } catch (const std::exception& failure) { + ++failures; + std::printf("FAIL %s: %s\n", test.first.c_str(), failure.what()); + } + std::fflush(stdout); + } + std::printf("%d of %zu failed\n", failures, tests.size()); + return failures == 0 ? 0 : 1; +} diff --git a/flutter_vst3/test/native/probe_worker.dart b/flutter_vst3/test/native/probe_worker.dart new file mode 100644 index 0000000..3ba4dc7 --- /dev/null +++ b/flutter_vst3/test/native/probe_worker.dart @@ -0,0 +1,105 @@ +// Worker used by ipc_host_test.cpp. It's a real compiled Dart worker with DSP +// whose behaviour the native test controls and inspects through parameters. + +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_vst3/flutter_vst3.dart'; + +const int _paramStallMs = 0; +const int _paramExit = 1; +const int _paramThrow = 2; +const int _paramProbe = 3; +const int _paramValue = 4; +const int _paramStallNextMs = 5; +const int _paramInitStallMs = 6; + +const int _probeSampleRate = 1; +const int _probeMaxBlock = 2; +const int _probeBlocks = 3; +const int _probeResets = 4; +const int _probeLastValue = 5; +const int _probeInitializes = 6; + +/// Output left is the input plus a running total of samples, so that any stale +/// or repeated block is visible. Output right reports the selected probe. +final class _ProbeProcessor implements Vst3WorkerProcessor { + double _sampleRate = 0; + int _maxBlock = 0; + int _blocks = 0; + int _resets = 0; + int _initializes = 0; + double _lastValue = -1; + int _stallMs = 0; + int _stallNextMs = 0; + int _initStallMs = 0; + int _probe = 0; + + @override + void initialize(double sampleRate, int maxBlockSize) { + _sampleRate = sampleRate; + _maxBlock = maxBlockSize; + _initializes++; + final int stall = _initStallMs; + _initStallMs = 0; + stall > 0 ? sleep(Duration(milliseconds: stall)) : null; + } + + @override + void setParameter(int paramId, double value) { + switch (paramId) { + case _paramStallMs: + _stallMs = value.toInt(); + case _paramExit: + value > 0 ? exit(3) : null; + case _paramThrow: + value > 0 ? throw StateError('Probe DSP failure') : null; + case _paramProbe: + _probe = value.toInt(); + case _paramValue: + _lastValue = value; + case _paramStallNextMs: + _stallNextMs = value.toInt(); + case _paramInitStallMs: + _initStallMs = value.toInt(); + } + } + + double get _probeValue => switch (_probe) { + _probeSampleRate => _sampleRate, + _probeMaxBlock => _maxBlock.toDouble(), + _probeBlocks => _blocks.toDouble(), + _probeResets => _resets.toDouble(), + _probeLastValue => _lastValue, + _probeInitializes => _initializes.toDouble(), + _ => 0, + }; + + @override + void processStereo( + Float32List inputL, + Float32List inputR, + Float32List outputL, + Float32List outputR, + ) { + _blocks++; + _stallMs > 0 ? sleep(Duration(milliseconds: _stallMs)) : null; + _stallMs = _stallNextMs; + _stallNextMs = 0; + final probe = _probeValue; + for (var i = 0; i < inputL.length; i++) { + outputL[i] = inputL[i] * 2; + outputR[i] = probe; + } + } + + @override + void reset() => _resets++; + + @override + void dispose() {} +} + +void main(List args) { + runVst3SharedMemoryProcessor(args: args, processor: _ProbeProcessor()); +} diff --git a/flutter_vst3/test/native/repo_rules_test.py b/flutter_vst3/test/native/repo_rules_test.py new file mode 100644 index 0000000..1d6fe2b --- /dev/null +++ b/flutter_vst3/test/native/repo_rules_test.py @@ -0,0 +1,160 @@ +"""Regression checks for deliberately removed APIs and artifacts.""" +import pathlib +import re +import subprocess +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[3] + + +def text(path): + return (ROOT / path).read_text(encoding='utf-8') + + +class RemovedDesignTests(unittest.TestCase): + def test_H9_registration_removed_and_migration_recorded(self): + for folder in ('flutter_vst3/lib', 'vsts/echo/lib'): + for path in (ROOT / folder).rglob('*.dart'): + self.assertNotIn('registerProcessor', path.read_text(), str(path)) + self.assertNotIn('registerProcessor', text('flutter_vst3/README.md')) + self.assertIn('Removed obsolete same-process VST3Bridge registration and FFI callbacks', + text('flutter_vst3/CHANGELOG.md')) + + def test_M2_dead_processor_removed(self): + self.assertNotIn('VST3AudioProcessor', text('flutter_vst3/lib/src/parameter_binding.dart')) + + def test_dead_parallel_api_removed(self): + for path in ('flutter_vst3/lib/src/flutter_vst3_bridge.dart', + 'flutter_vst3/lib/src/flutter_vst3_callbacks.dart', + 'flutter_vst3/lib/src/flutter_vst3_parameters.dart', + 'vsts/echo/lib/src/echo_bridge.dart', + 'vsts/echo/lib/src/echo_plugin.dart', + 'vsts/echo/lib/src/echo_vst3_processor.dart'): + self.assertFalse((ROOT / path).exists(), path) + for path in ('README.md', 'flutter_vst3/README.md', 'flutter_vst3/example/README.md'): + self.assertNotRegex(text(path), r'\bVST3Processor\b|VST3Bridge\.', path) + + def test_M3_waveform_work_removed(self): + self.assertNotIn('waveformBuffer', text('vsts/echo/lib/src/echo_processor.dart')) + + def test_M4_shared_process_claim_removed(self): + self.assertNotRegex(text('vsts/echo/lib/ui/echo_ui.dart'), + r'(?i)(same|shared)\s+process') + + def test_M8_embedder_files_removed(self): + self.assertEqual([], list((ROOT / 'flutter_vst3/native').rglob('flutter_embedder*.cpp'))) + self.assertEqual([], list((ROOT / 'flutter_vst3/native').rglob('flutter_embedder.h'))) + + def test_M9_plugin_view_removed(self): + self.assertEqual([], list((ROOT / 'flutter_vst3/native').rglob('plugin_view.cpp'))) + + def test_M10_no_tracked_native_binaries(self): + names = subprocess.check_output(['git', 'ls-files', '-z'], cwd=ROOT).split(b'\0') + magic = {b'\x7fELF', b'\xfe\xed\xfa\xce', b'\xce\xfa\xed\xfe', + b'\xfe\xed\xfa\xcf', b'\xcf\xfa\xed\xfe', b'\xca\xfe\xba\xbe', + b'\xbe\xba\xfe\xca', b'\xca\xfe\xba\xbf', b'\xbf\xba\xfe\xca'} + for name in filter(None, names): + path = ROOT / name.decode() + with path.open('rb') as source: + self.assertNotIn(source.read(4), magic, str(path)) + + def test_H16_own_objc_classes_are_prefixed(self): + files = list((ROOT / 'flutter_vst3/native').rglob('*')) + source = '\n'.join(p.read_text() for p in files if p.suffix in ('.h', '.mm')) + classes = re.findall(r'@interface\s+(\w+)', source) + self.assertGreaterEqual(len(classes), 3) + for name in classes: + self.assertRegex(source, r'#define\s+' + name + + r'\s+CONCAT\(' + name + r',\s*PLUGIN_TARGET_NAME\)') + + def test_M11_no_ephemeral_or_user_config_paths(self): + names = subprocess.check_output(['git', 'ls-files', '-z'], cwd=ROOT).decode().split('\0') + for name in filter(None, names): + self.assertNotRegex(name, r'Flutter/ephemeral/') + if pathlib.Path(name).suffix in ('.json', '.yaml', '.yml', '.cmake'): + self.assertNotRegex(text(name), r'/Users/|/home/[^$\s/]+/|[A-Za-z]:[\\\\/]Users[\\\\/]') + + def test_M13_no_same_isolate_requirement(self): + self.assertNotRegex(text('docs/FLUTTER_UI_SPEC.md'), r'(?i)non.negotiable') + + def test_M12_echo_readme_not_template(self): + self.assertNotIn('A new Flutter project.', text('vsts/echo/README.md')) + self.assertNotIn('This project is a starting point', text('vsts/echo/README.md')) + + def test_M15_only_allowlisted_error_prints(self): + allowed = { + 'std::fprintf(stderr, "{{PLUGIN_ID}}: %s\\n", error.what());', + 'fprintf(stderr, "flutter_vst3: native Windows editor failed after Flutter startup failure.\\n");', + 'fprintf(stderr, "flutter_vst3: gtk_plug_new failed. VST3 GUI embedding on Linux requires an X11 backend (GDK_BACKEND=x11).\\n");', + 'NSLog(@"[flutter_vst3] Flutter app library failed to load: %s", dlerror());', + 'NSLog(@"[flutter_vst3] Flutter UI mount exception: %@. Falling back to Cocoa.", e);', + 'NSLog(@"[flutter_vst3] FlutterEngine failed to launch (e.g. Dart SDK hash mismatch). Falling back to Cocoa.");', + } + for folder in ('src', 'templates'): + for path in (ROOT / 'flutter_vst3/native' / folder).rglob('*'): + if path.is_file(): + for line in path.read_text().splitlines(): + if re.search(r'(? echoMain();', (ROOT / 'vsts/echo/lib/main.dart').read_text()) + + def test_M18_block_automation_documented(self): + self.assertIn('Parameters apply per block, so only the last point in each queue is used.', + text('flutter_vst3/native/templates/plugin_processor_aot.cpp.template')) + + def test_M19_no_untrue_performance_claims(self): + for path in (ROOT / 'flutter_vst3/native').rglob('*'): + if path.is_file(): + self.assertNotRegex(path.read_text(), r'(?i)zero-copy|lock-free', str(path)) + + def test_T5_no_workspace_paths(self): + for folder in ('dart_vst_host/test', 'dart_vst_graph/test', 'flutter_vst3/test'): + for path in (ROOT / folder).rglob('*.dart'): + self.assertNotIn('/workspace', path.read_text(), str(path)) + + +class AgentSetup(unittest.TestCase): + def test_standard_make_targets_exist(self): + for target in ('deslop', 'coverage-check', 'lint', 'fmt', 'ci', 'setup', 'test', 'build', 'clean', + 'deploy', 'deploy-echo', 'deploy-reverb', 'echo', 'reverb'): + result = subprocess.run(['make', '-n', target], cwd=ROOT, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, text=True) + self.assertEqual(0, result.returncode, target + ': ' + result.stdout) + self.assertTrue(result.stdout.strip(), target + ' does nothing') + + def test_deslop_gates_the_pipeline(self): + ci = (ROOT / '.github/workflows/ci.yml').read_text() + analyze = ci[ci.index('\n analyze:'):ci.index('\n build:')] + config = (ROOT / '.deslop.toml').read_text() + ceiling = float(re.search(r'^max_duplication_percent = ([\d.]+)$', config, re.M).group(1)) + self.assertLessEqual(ceiling, 6.0) + self.assertIn('uses: Nimblesite/Deslop@', analyze) + for bypass in ('fail-over', 'continue-on-error', 'only-changed', 'config:'): + self.assertNotIn(bypass, analyze) + self.assertRegex(ci, r'name: CI\n\s+if: always\(\)\n\s+needs:\n\s+- analyze\n') + self.assertRegex((ROOT / 'Makefile').read_text(), r'(?m)^ci: deslop ') + hidden = re.search(r'report_hide = \[(.*?)\n\]', config, re.S).group(1) + self.assertEqual(len(re.findall(r'^\s+"', hidden, re.M)), 5) + self.assertNotRegex(config, r'(?m)^\s*exclude\s*=') + + def test_agent_files_point_at_one_canonical_file(self): + self.assertEqual('@AGENTS.md', (ROOT / 'CLAUDE.md').read_text().strip()) + self.assertEqual('AGENTS.md', (ROOT / 'GEMINI.md').readlink().as_posix()) + self.assertIn('make deslop', (ROOT / 'AGENTS.md').read_text()) + + +if __name__ == '__main__': + unittest.main() diff --git a/flutter_vst3/test/native/run.ps1 b/flutter_vst3/test/native/run.ps1 new file mode 100644 index 0000000..e198cf7 --- /dev/null +++ b/flutter_vst3/test/native/run.ps1 @@ -0,0 +1,51 @@ +# Builds and runs the native IPC round-trip tests on Windows. +# Run from a Visual Studio developer prompt, so that cl.exe is on PATH. +# -Phase build or test does one half; with neither it does both. +param([ValidateSet('all', 'build', 'test')][string]$Phase = 'all') +$ErrorActionPreference = 'Stop' + +function Invoke-Checked { + param([string]$Exe, [string[]]$Arguments) + & $Exe @Arguments + if ($LASTEXITCODE -ne 0) { throw "$Exe failed with exit code $LASTEXITCODE" } +} + +$root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path +$build = if ($env:VST3_IPC_TEST_BUILD_DIR) { $env:VST3_IPC_TEST_BUILD_DIR } else { Join-Path $env:TEMP 'vst3_ipc_test' } +New-Item -ItemType Directory -Force -Path $build | Out-Null + +if ($Phase -ne 'test') { +Push-Location $root +try { + Invoke-Checked 'dart' @('compile', 'exe', 'test/native/probe_worker.dart', '-o', "$build\probe_worker.exe") +} finally { + Pop-Location +} + +Push-Location $build +try { + Invoke-Checked 'cl.exe' @('/nologo', '/std:c++17', '/EHsc', '/W4', '/WX', '/O1', '/D_CRT_SECURE_NO_WARNINGS', + "/I$root\native\include", "/I$root\native\src", + "$root\native\src\vst3_ipc_host.cpp", + "$root\native\src\vst3_ipc_platform_win.cpp", + "$root\test\native\ipc_host_test.cpp", + "$root\test\native\ipc_host_recovery_test.cpp", + '/Fe:ipc_host_test.exe') + Invoke-Checked 'cl.exe' @('/nologo', '/std:c++17', '/EHsc', '/W4', '/WX', '/O1', '/D_CRT_SECURE_NO_WARNINGS', + "/I$root\native\include", "/I$root\native\src", + "$root\native\src\vst3_ipc_platform_win.cpp", + "$root\test\native\ipc_platform_test.cpp", 'user32.lib', '/Fe:ipc_platform_test.exe') +} finally { + Pop-Location +} +} + +if ($Phase -eq 'build') { exit 0 } + +Push-Location $build +try { + Invoke-Checked "$build\ipc_platform_test.exe" @() + Invoke-Checked "$build\ipc_host_test.exe" @("$build\probe_worker.exe") +} finally { + Pop-Location +} diff --git a/flutter_vst3/test/native/run.sh b/flutter_vst3/test/native/run.sh new file mode 100644 index 0000000..cd8a1b5 --- /dev/null +++ b/flutter_vst3/test/native/run.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Builds and runs the native IPC round-trip tests on Linux and macOS. +# Usage: run.sh [build|test]. With no argument it does both. +set -euo pipefail + +phase="${1:-all}" + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +build="${VST3_IPC_TEST_BUILD_DIR:-$(mktemp -d)}" +mkdir -p "$build" + +if [ "$phase" != test ]; then +(cd "$root" && dart compile exe test/native/probe_worker.dart -o "$build/probe_worker") + +libs=(-pthread) +if [ "$(uname)" = "Linux" ]; then libs+=(-lrt -ldl); fi + +c++ -std=c++17 -O1 -g -Wall -Wextra -Werror \ + -I"$root/native/include" -I"$root/native/src" \ + "$root/native/src/vst3_ipc_host.cpp" \ + "$root/native/src/vst3_ipc_platform_posix.cpp" \ + "$root/test/native/ipc_host_test.cpp" \ + "$root/test/native/ipc_host_recovery_test.cpp" \ + "${libs[@]}" -o "$build/ipc_host_test" + +c++ -std=c++17 -O1 -g -Wall -Wextra -Werror \ + -I"$root/native/include" -I"$root/native/src" \ + "$root/native/src/vst3_ipc_platform_posix.cpp" \ + "$root/test/native/ipc_platform_test.cpp" \ + "${libs[@]}" -o "$build/ipc_platform_test" +fi + +if [ "$phase" = build ]; then exit 0; fi + +"$build/ipc_platform_test" +"$build/ipc_host_test" "$build/probe_worker" + +# Names are unlinked after the handshake, so a clean run or a failed start leaves none. +if [ "$(uname)" = "Linux" ]; then + leaked="$(find /dev/shm -maxdepth 1 \( -name 'v3s*' -o -name 'sem.v3r*' -o -name 'sem.v3d*' \))" + if [ -n "$leaked" ]; then + printf 'FAIL leaked shared memory or semaphores:\n%s\n' "$leaked" >&2 + exit 1 + fi + echo "PASS no shared memory or semaphores leaked" +fi diff --git a/flutter_vst3/test/native/run_editor_e2e.sh b/flutter_vst3/test/native/run_editor_e2e.sh new file mode 100644 index 0000000..174fc22 --- /dev/null +++ b/flutter_vst3/test/native/run_editor_e2e.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +# Builds the Flutter-enabled Echo, then opens real editors on it in a test host, +# with a good bundle and with bundles whose Flutter app is missing or corrupt. +# Usage: run_editor_e2e.sh [build|test]. With no argument it does both. +set -euo pipefail + +phase="${1:-all}" +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" +build="${VST3_E2E_BUILD_DIR:-$(mktemp -d)}" +mkdir -p "$build" +build="$(cd "$build" && pwd)" + +case "$(uname)" in + Linux) + platform=linux; app=x86_64-linux/lib/libapp.so; run=(xvfb-run -a) + export CMAKE_GENERATOR="${CMAKE_GENERATOR:-Ninja}" ;; + Darwin) + platform=macos; app=Frameworks/App.framework/Versions/A/App; run=() + export CMAKE_GENERATOR="${CMAKE_GENERATOR:-Ninja}" ;; + *) + # CMake's default here is Visual Studio, which the SDK's bundle layout needs. + platform=windows; app=x86_64-win/data/app.so; run=() ;; +esac + +if [[ "$phase" != test ]]; then + : "${VST3_SDK_DIR:?Set VST3_SDK_DIR}" + export VST3_SDK_DIR + (cd "$root/vsts/echo" && flutter build "$platform" --release) + cmake -S "$root/vsts/echo" -B "$build/echo-flutter" -DCMAKE_BUILD_TYPE=Release -DSMTG_CREATE_PLUGIN_LINK=OFF -DFLUTTER_VST3_NATIVE_UI_ONLY=OFF + cmake --build "$build/echo-flutter" --config Release --target echo + cmake -S "$root/flutter_vst3/test/native" -B "$build/host" -DCMAKE_BUILD_TYPE=Release + cmake --build "$build/host" --config Release --target editor_host_test editor_liveness_test + if [[ -z "${VST3_E2E_MODES:-}" ]]; then + cmake -S "$VST3_SDK_DIR" -B "$build/sdk" -DCMAKE_BUILD_TYPE=Release \ + -DSMTG_ADD_VSTGUI=OFF -DSMTG_ENABLE_VSTGUI_SUPPORT=OFF -DSMTG_ADD_VST3_PLUGINS_SAMPLES=OFF -DSMTG_RUN_VST_VALIDATOR=OFF + cmake --build "$build/sdk" --config Release --target validator + fi +fi + +if [[ "$phase" == build ]]; then exit 0; fi + +liveness="$(find "$build/host" -type f \( -name editor_liveness_test -o -name editor_liveness_test.exe \) -print -quit)" +"$liveness" +host_test="$(find "$build/host" -type f \( -name editor_host_test -o -name editor_host_test.exe \) -print -quit)" +bundle="$(find "$build/echo-flutter" -type d -name echo.vst3 -print -quit)" +test -n "$bundle" +test -e "$bundle/Contents/$app" + +mkdir -p "$build/missing" "$build/garbage" +rm -rf "$build/missing/echo.vst3" "$build/garbage/echo.vst3" +cp -a "$bundle" "$build/missing/" +cp -a "$bundle" "$build/garbage/" +rm "$build/missing/echo.vst3/Contents/$app" +printf 'not a library\n' > "$build/garbage/echo.vst3/Contents/$app" + +# Every mode runs even after a failure. The marker catches a process that exits +# with status 0 before finishing. +result=0 +modes="${VST3_E2E_MODES:-good missing garbage wire environment immediate modules}" +for mode in $modes; do + path="$bundle" + if [[ "$mode" == missing || "$mode" == garbage ]]; then path="$build/$mode/echo.vst3"; fi + extra=() + if [[ "$mode" == modules ]]; then + mkdir -p "$build/second" + rm -rf "$build/second/echo.vst3" + cp -a "$build/missing/echo.vst3" "$build/second/" + path="$build/missing/echo.vst3" + extra=("$build/second/echo.vst3") + fi + echo "=== $mode" + if ! "${run[@]+"${run[@]}"}" "$host_test" "$path" "$mode" ${extra[@]+"${extra[@]}"} 2>&1 | tee "$build/$mode.log"; then + result=1 + if [[ "$mode" == modules ]]; then echo 'FAIL H14 module survivor process failed'; fi + fi + grep -q '^PASS ALL EDITOR CASES' "$build/$mode.log" || result=1 +done + +if [[ -n "${VST3_E2E_MODES:-}" ]]; then exit "$result"; fi + +validator="$(find "$build/sdk" -type f \( -name validator -o -name validator.exe \) -print -quit)" +"${run[@]+"${run[@]}"}" "$validator" "$bundle" || result=1 +exit "$result" diff --git a/flutter_vst3/test/native/run_editor_mutations.sh b/flutter_vst3/test/native/run_editor_mutations.sh new file mode 100644 index 0000000..6b4ac83 --- /dev/null +++ b/flutter_vst3/test/native/run_editor_mutations.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# Every mutation lives in a separate source tree and build tree. +set -euo pipefail +root="$(cd "$(dirname "$0")/../../.." && pwd)" +: "${VST3_SDK_DIR:?Set VST3_SDK_DIR}" +case "$(uname)" in + Linux) mutants=(linux_release h13 h15) ;; + Darwin) mutants=(h15) ;; + *) mutants=(h12 h14 h15) ;; +esac +work="$(mktemp -d /tmp/testb_mutations.XXXXXX)" +echo "Mutation evidence: $work" +survivors=0 +for mutant in "${mutants[@]}"; do + tree="$work/$mutant/source" + mkdir -p "$tree" + (cd "$root" && tar --exclude=.git --exclude=node_modules --exclude=build --exclude=.dart_tool -cf - .) | (cd "$tree" && tar -xf -) + python3 - "$tree" "$mutant" <<'PY' +import pathlib, sys +root, mutant = pathlib.Path(sys.argv[1]), sys.argv[2] +base = root / 'flutter_vst3/native/src' +def replace(path, old, new): + text = path.read_text() + assert text.count(old) == 1, (path, old, text.count(old)) + path.write_text(text.replace(old, new), newline='\n') +if mutant == 'linux_release': + replace(base/'embedded_flutter_view_linux_flutter.inc', ' releasePointer();', ' /* mutant: no release */') +elif mutant == 'h12': + replace(base/'embedded_flutter_view_win_flutter.inc', 'sFlDll = LoadLibraryExW(', 'SetDllDirectoryW(L"C:\\\\Windows");\n sFlDll = LoadLibraryExW(') +elif mutant == 'h13': + replace(base/'embedded_flutter_view_linux_flutter.inc', 'gdk_set_allowed_backends("x11");', 'gdk_set_allowed_backends("x11");\n setenv("GDK_BACKEND", "x11", 1);') +elif mutant == 'h14': + replace(base/'embedded_flutter_view_win_native.inc', 'static const auto name = editorClassName(L"FlutterVst3NativeWin32View");', 'static const std::wstring name = L"FlutterVst3NativeWin32View";') + replace(base/'embedded_flutter_view_win_native.inc', 'HINSTANCE hInst = editorModule();', 'HINSTANCE hInst = GetModuleHandleW(nullptr);') +elif mutant == 'h15': + replace(root/'flutter_vst3/native/include/view_logic.h', 'if (alive.load()) work();', 'if (true) work();') +else: + raise AssertionError(mutant) +print('APPLIED', mutant) +PY + (cd "$tree/vsts/echo" && flutter pub get) > "$work/$mutant-pub.log" 2>&1 + if [[ "$mutant" == h15 ]]; then + cmake -S "$tree/flutter_vst3/test/native" -B "$work/$mutant/host" -DCMAKE_BUILD_TYPE=Release > "$work/$mutant-build.log" 2>&1 + cmake --build "$work/$mutant/host" --config Release --target editor_liveness_test >> "$work/$mutant-build.log" 2>&1 + executable="$(find "$work/$mutant/host" -type f \( -name editor_liveness_test -o -name editor_liveness_test.exe \) -print -quit)" + test -n "$executable" + command=("$executable") + else + case "$mutant" in + h12|h13) modes=environment ;; + h14) modes=modules ;; + *) modes=good ;; + esac + command=(env "VST3_E2E_BUILD_DIR=$work/$mutant/build" "VST3_E2E_MODES=$modes" bash "$tree/flutter_vst3/test/native/run_editor_e2e.sh") + fi + if "${command[@]}" > "$work/$mutant.log" 2>&1; then + echo "FAIL mutant survived: $mutant"; survivors=$((survivors + 1)); continue + fi + case "$mutant" in + linux_release) expected='FAIL .*drag missing events' ;; + h12) expected='FAIL H12 DLL directory changed' ;; + h13) expected='FAIL H13 GDK_BACKEND changed' ;; + h14) expected='FAIL H14|FAIL .*drag|FAIL .*controller|FAIL .*attached' ;; + h15) expected='FAIL H15 dead token ran work' ;; + esac + if ! grep -E "$expected" "$work/$mutant.log"; then + echo "FAIL mutant failed for another reason: $mutant"; tail -15 "$work/$mutant.log" + survivors=$((survivors + 1)); continue + fi + echo "KILLED $mutant" +done +test "$survivors" -eq 0 diff --git a/flutter_vst3/test/native/run_incremental_build.sh b/flutter_vst3/test/native/run_incremental_build.sh new file mode 100644 index 0000000..13afcfc --- /dev/null +++ b/flutter_vst3/test/native/run_incremental_build.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# All mutations and build outputs are confined to this disposable copy. +set -euo pipefail +root="$(cd "$(dirname "$0")/../../.." && pwd)" +work="$(mktemp -d /tmp/vst3-incremental-XXXXXX)" +trap 'rm -rf "$work"' EXIT +tar -C "$root" --exclude=.git --exclude=build --exclude=.dart_tool -cf - flutter_vst3 vsts/echo | tar -C "$work" -xf - +(cd "$work/flutter_vst3" && flutter pub get) +(cd "$work/vsts/echo" && flutter pub get) +cmake -S "$work/vsts/echo" -B "$work/build" -G Ninja -DFLUTTER_VST3_NATIVE_UI_ONLY=ON +cmake --build "$work/build" --target echo +worker="$work/build/VST3/Release/echo.vst3/Contents/x86_64-linux/echo_processor" +before="$(sha256sum "$worker" | cut -d' ' -f1)" +source="$work/vsts/echo/lib/src/echo_processor.dart" +cp "$source" "$work/original.dart" +python3 - "$source" <<'PY' +from pathlib import Path +import sys +p = Path(sys.argv[1]); text = p.read_text() +assert '0.85' in text +p.write_text(text.replace('0.85', '0.75')) +PY +cmake --build "$work/build" --target echo +test "$before" != "$(sha256sum "$worker" | cut -d' ' -f1)" +echo 'PASS audible constant changed bundled worker hash' +printf '\nTHIS_IS_INVALID_DART\n' >> "$source" +if cmake --build "$work/build" --target echo; then + echo 'FAIL invalid Dart accepted' >&2; exit 1 +fi +echo 'PASS invalid Dart rejected' +cp "$work/original.dart" "$source" +cmake --build "$work/build" --target echo +python3 - "$work/vsts/echo/plugin_metadata.json" <<'PY' +import json, sys +from pathlib import Path +p = Path(sys.argv[1]); data = json.loads(p.read_text()) +data['parameters'][0]['defaultValue'] = 0.123456 +p.write_text(json.dumps(data)) +PY +cmake --build "$work/build" --target echo +grep -F '0.123456' "$work/build/generated/echo_controller.cpp" +grep -F '0.123456' "$work/build/generated/echo_processor.cpp" +echo 'PASS restored Dart and regenerated metadata default' diff --git a/flutter_vst3/test/native/run_package_coverage.sh b/flutter_vst3/test/native/run_package_coverage.sh new file mode 100755 index 0000000..b7253fe --- /dev/null +++ b/flutter_vst3/test/native/run_package_coverage.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +# Runs one package's tests with line coverage and always writes its lcov report. +# Usage: run_package_coverage.sh +set -euo pipefail + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" +package="${1:?usage: run_package_coverage.sh }" +: "${VST3_SDK_DIR:=$root/vst3sdk}" +export VST3_SDK_DIR +cd "$root/$package" +mkdir -p coverage +rm -f coverage/lcov.info + +status=0 +format_status=0 +if grep -qE '^[[:space:]]+sdk:[[:space:]]*flutter' pubspec.yaml; then + flutter test --coverage || status=$? +else + dart test --coverage=coverage || status=$? + dart run coverage:format_coverage --lcov --in=coverage --out=coverage/lcov.info \ + --report-on=lib --packages=.dart_tool/package_config.json || format_status=$? +fi +[ -f coverage/lcov.info ] || : > coverage/lcov.info +[ "$status" -eq 0 ] || exit "$status" +exit "$format_status" diff --git a/flutter_vst3/test/native/run_plugin_e2e.sh b/flutter_vst3/test/native/run_plugin_e2e.sh new file mode 100644 index 0000000..0e9b339 --- /dev/null +++ b/flutter_vst3/test/native/run_plugin_e2e.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Builds the real Echo plugin, runs Steinberg's validator on it, and runs +# plugin_host_test against it. Usage: run_plugin_e2e.sh [build|test]; with no +# argument it does both. Building needs VST3_SDK_DIR, plus cl.exe on PATH on Windows. +set -euo pipefail + +phase="${1:-all}" + +root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)" +build="${VST3_E2E_BUILD_DIR:-$(mktemp -d)}" +mkdir -p "$build" +build="$(cd "$build" && pwd)" +# On Windows CMake's default generator is Visual Studio, which the SDK's bundle layout needs. +case "$(uname)" in + MINGW*|MSYS*|CYGWIN*) ;; + *) export CMAKE_GENERATOR="${CMAKE_GENERATOR:-Ninja}" ;; +esac + +if [ "$phase" != test ]; then +: "${VST3_SDK_DIR:?Set VST3_SDK_DIR to the Steinberg VST3 SDK}" +export VST3_SDK_DIR +# Native sliders only: this checks audio and the VST3 contract, not the editor. +cmake -S "$root/vsts/echo" -B "$build/echo-native" -DCMAKE_BUILD_TYPE=Release \ + -DSMTG_CREATE_PLUGIN_LINK=OFF -DFLUTTER_VST3_NATIVE_UI_ONLY=ON +cmake --build "$build/echo-native" --config Release --target echo +cmake -S "$root/flutter_vst3/test/native" -B "$build/host" -DCMAKE_BUILD_TYPE=Release +cmake --build "$build/host" --config Release --target plugin_host_test +cmake -S "$VST3_SDK_DIR" -B "$build/sdk" -DCMAKE_BUILD_TYPE=Release \ + -DSMTG_ADD_VSTGUI=OFF -DSMTG_ENABLE_VSTGUI_SUPPORT=OFF -DSMTG_ADD_VST3_PLUGINS_SAMPLES=OFF -DSMTG_RUN_VST_VALIDATOR=OFF +cmake --build "$build/sdk" --config Release --target validator +# Reverb has no flutterEntrypoint, so it must build and validate with native sliders. +cmake -S "$root/vsts/flutter_reverb" -B "$build/reverb" -DCMAKE_BUILD_TYPE=Release -DSMTG_CREATE_PLUGIN_LINK=OFF -DFLUTTER_VST3_NATIVE_UI_ONLY=ON +cmake --build "$build/reverb" --config Release --target flutter_reverb +fi + +if [ "$phase" = build ]; then exit 0; fi + +bundle="$(find "$build/echo-native" -type d -name 'echo.vst3' | head -n 1)" +worker="$(find "$bundle/Contents" -type f \( -name echo_processor -o -name echo_processor.exe \) | head -n 1)" +test -x "$worker" + +host_test="$(find "$build/host" -type f \( -name plugin_host_test -o -name plugin_host_test.exe \) | head -n 1)" +"$host_test" "$bundle" "$worker" + +validator="$(find "$build/sdk" -type f \( -name validator -o -name validator.exe \) | head -n 1)" +"$validator" "$bundle" + +"$validator" "$(find "$build/reverb" -type d -name 'flutter_reverb.vst3' | head -n 1)" + diff --git a/flutter_vst3/test/native/run_view_logic.sh b/flutter_vst3/test/native/run_view_logic.sh new file mode 100644 index 0000000..354e816 --- /dev/null +++ b/flutter_vst3/test/native/run_view_logic.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Usage: run_view_logic.sh [build|test]. With no argument it does both. +set -euo pipefail +phase="${1:-all}" +root="$(cd "$(dirname "$0")/../.." && pwd)" +build="${VST3_E2E_BUILD_DIR:-$(mktemp -d)}" +mkdir -p "$build" +binary="$build/view_logic_test" +if [ "$phase" != test ]; then + g++ -std=c++17 -Wall -Wextra -Werror -I "$root/native/include" "$root/test/native/view_logic_test.cpp" -o "$binary" +fi +if [ "$phase" != build ]; then "$binary"; fi diff --git a/flutter_vst3/test/native/view_logic_test.cpp b/flutter_vst3/test/native/view_logic_test.cpp new file mode 100644 index 0000000..27c3092 --- /dev/null +++ b/flutter_vst3/test/native/view_logic_test.cpp @@ -0,0 +1,64 @@ +#include "view_logic.h" +#include +#include +#include + +void require(bool value) { + if (!value) { std::cerr << "view logic assertion failed\n"; std::exit(1); } +} +void testOwnershipAndShm() { + const int a = 1, b = 2; + require(flutter_vst3::ownsEditor(&a, &a)); + require(!flutter_vst3::ownsEditor(&a, &b)); + require(!flutter_vst3::ownsEditor(nullptr, nullptr)); + require(flutter_vst3::localShmAddress(1234, 5, 5) == 1234); + require(flutter_vst3::localShmAddress(1234, 5, 6) == 0); + require(flutter_vst3::localShmAddress(0, 5, 5) == 0); +} +void testEditSuppression() { + flutter_vst3::EditState edits; + require(edits.shouldEcho(7)); + require(edits.begin(7)); + require(!edits.begin(7)); + require(!edits.shouldEcho(7)); + require(edits.shouldEcho(8)); + require(edits.end(7)); + require(!edits.end(7)); + require(edits.shouldEcho(7)); +} +void testGestureSequence() { + flutter_vst3::EditState edits; + std::vector events; + if (edits.begin(1)) events.push_back('b'); + for (int tick = 0; tick < 10; ++tick) { + require(!edits.shouldEcho(1)); + events.push_back('p'); + } + if (edits.end(1)) events.push_back('e'); + require(events.size() == 12); + require(events.front() == 'b' && events.back() == 'e'); + for (size_t i = 1; i + 1 < events.size(); ++i) require(events[i] == 'p'); +} +void testStartupDecision() { + require(flutter_vst3::kFlutterStartTimeoutMs == 10000); + for (bool alive : {false, true}) for (bool failed : {false, true}) { + require(!flutter_vst3::flutterStartFailed(alive, failed, false)); + require(flutter_vst3::flutterStartFailed(alive, failed, true) == (failed || !alive)); + } +} +int main() { + flutter_vst3::EditState interrupted; + require(interrupted.begin(7)); + require(interrupted.begin(2)); + require(interrupted.takeOpen() == std::set({2, 7})); + require(interrupted.takeOpen().empty()); + require(interrupted.shouldEcho(7)); + require(!interrupted.end(7)); + require(interrupted.begin(7)); + require(interrupted.end(7)); + testStartupDecision(); + testOwnershipAndShm(); + testEditSuppression(); + testGestureSequence(); + std::cout << "ownership, gesture state, edit suppression, shm routing and startup watchdog passed\n"; +} diff --git a/flutter_vst3/test/parameter_binding_contract_test.dart b/flutter_vst3/test/parameter_binding_contract_test.dart new file mode 100644 index 0000000..8de1f3c --- /dev/null +++ b/flutter_vst3/test/parameter_binding_contract_test.dart @@ -0,0 +1,161 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_vst3/src/parameter_binding.dart'; + +const _channel = MethodChannel('flutter_vst3/parameters'); +const _codec = StandardMethodCodec(); +final _messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; +Object? _initial = {'0': 0.25, '2': 0.5}; +final _calls = []; +final _values = []; + +Future _incoming(Object? args) async { + Object? result; + await _messenger.handlePlatformMessage(_channel.name, + _codec.encodeMethodCall(MethodCall('onParameterChanged', args)), + (data) => result = data == null ? null : _codec.decodeEnvelope(data)); + return result; +} + +Future _outgoing(VST3ParameterBinding binding) async { + _calls.clear(); + await binding.beginEdit(2); + await binding.setParameter(2, 0.7); + await binding.setParameter(2, -1); + await binding.setParameter(2, 2); + await binding.endEdit(2); + expect(_calls.map((c) => c.method).toList(), + ['beginEdit', 'setParameter', 'setParameter', 'setParameter', 'endEdit']); + expect(_calls.map((c) => c.arguments).toList(), [ + {'id': 2}, {'id': 2, 'value': 0.7}, {'id': 2, 'value': 0.0}, + {'id': 2, 'value': 1.0}, {'id': 2} + ]); + expect(binding.getParameter(2), 1); + expect(_values, [0.7, 0, 1]); +} + +Future _rejectMessages(VST3ParameterBinding binding) async { + for (final bad in [ + {'id': 2, 'value': 2.0}, {'id': 2, 'value': -1.0}, + {'id': 2, 'value': double.nan}, {'id': '2', 'value': 0.2}, + {'id': 4, 'value': 0.2}, {'id': -1, 'value': 0.2}, + {'id': 2.5, 'value': 0.2}, {'id': 2, 'value': 'bad'}, [], null + ]) { + await expectLater(_incoming(bad), throwsA(isA())); + expect(binding.getParameter(2), 0.3); + expect(_values, [0.7, 0, 1, 0.3]); + } +} + +Future _rejectInitial(VST3ParameterBinding binding) async { + final badValues = [2.0, -1.0, double.nan, 'bad']; + final badMaps = [ + for (final bad in badValues) {0: 0.9, 2: bad}, + {0: 0.9, '2.0': 0.2}, {0: 0.9, 'bad': 0.2}, + {0: 0.9, 4: 0.2}, {0: 0.9, 2.5: 0.2}, null, [] + ]; + for (final bad in badMaps) { + _initial = bad; + await expectLater(binding.loadInitialParameters(), throwsArgumentError); + expect(binding.getParameter(0), 0.25); + expect(binding.getParameter(2), 0.3); + expect(_values, [0.7, 0, 1, 0.3]); + } +} + +Future _setup() async { + _messenger.setMockMethodCallHandler(_channel, (call) async { + _calls.add(call); + return call.method == 'getInitialParameters' ? _initial : null; + }); + final binding = VST3ParameterBinding.getInstance(paramCount: 4); + await binding.loadInitialParameters(); + void listener() => _values.add(binding.getParameter(2)); + binding.addListener(listener); + addTearDown(() => binding.removeListener(listener)); + expect(binding.getParameter(0), 0.25); + expect(binding.getParameter(2), 0.5); + return binding; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + test('exact bidirectional contract and atomic rejection', () async { + final binding = await _setup(); + await _outgoing(binding); + await _incoming({'id': 2, 'value': 0.3}); + expect(binding.getParameter(2), 0.3); + expect(_values, [0.7, 0, 1, 0.3]); + await _rejectMessages(binding); + await _rejectInitial(binding); + }); + test('a gesture reaches the host only once a value changes', () async { + _initial = const {'0': 0.25, '2': 0.5}; + final binding = await _setup(); + _calls.clear(); + await binding.beginEdit(1); + await binding.endEdit(1); + expect(_calls, isEmpty); + await binding.beginEdit(1); + expect(_calls, isEmpty); + await binding.setParameter(1, 0.4); + await binding.setParameter(1, 0.5); + await binding.endEdit(1); + expect(_calls.map((c) => c.method).toList(), + ['beginEdit', 'setParameter', 'setParameter', 'endEdit']); + expect(_calls.map((c) => c.arguments).toList(), [ + {'id': 1}, {'id': 1, 'value': 0.4}, {'id': 1, 'value': 0.5}, {'id': 1} + ]); + }); + test('no message overtakes the value that opens a gesture ' + '[PARAM-GESTURE-VALUE-OPENS] [PARAM-GESTURE-END]', () async { + _initial = const {'0': 0.25, '2': 0.5}; + final binding = await _setup(); + _calls.clear(); + await binding.beginEdit(1); + final first = binding.setParameter(1, 0.4); + final second = binding.setParameter(1, 0.5); + await first; + await second; + expect(_calls.map((c) => c.method).toList(), + ['beginEdit', 'setParameter', 'setParameter']); + expect(_calls[1].arguments, {'id': 1, 'value': 0.4}); + expect(_calls[2].arguments, {'id': 1, 'value': 0.5}); + _calls.clear(); + await binding.beginEdit(1); + final dragValue = binding.setParameter(1, 0.2); + final release = binding.endEdit(1); + await dragValue; + await release; + expect(_calls.map((c) => c.method).toList(), + ['beginEdit', 'setParameter', 'endEdit']); + }); + test('closing the editor forgets a gesture that has not started', () async { + _initial = const {'0': 0.25, '2': 0.5}; + final binding = await _setup(); + _calls.clear(); + await binding.beginEdit(1); + await _messenger.handlePlatformMessage(_channel.name, + _codec.encodeMethodCall(const MethodCall('onHostDetached')), (_) {}); + await binding.setParameter(1, 0.6); + expect(_calls.map((c) => c.method).toList(), ['setParameter']); + await _messenger.handlePlatformMessage(_channel.name, + _codec.encodeMethodCall(const MethodCall('onHostAttached')), (_) {}); + }); + test('running without a host keeps the cache and throws nothing', () async { + _initial = const {'0': 0.25, '2': 0.5}; + final binding = await _setup(); + await binding.setParameter(2, 0.6); + final notified = _values.length; + _messenger.setMockMethodCallHandler(_channel, null); + await binding.loadInitialParameters(); + expect(binding.getParameter(0), 0.25); + expect(binding.getParameter(2), 0.6); + expect(_values.length, notified); + await binding.beginEdit(2); + await binding.setParameter(2, 0.8); + await binding.endEdit(2); + expect(binding.getParameter(2), 0.8); + expect(_values.sublist(notified), [0.8]); + }); +} diff --git a/flutter_vst3/test/rotary_knob_test.dart b/flutter_vst3/test/rotary_knob_test.dart new file mode 100644 index 0000000..4415626 --- /dev/null +++ b/flutter_vst3/test/rotary_knob_test.dart @@ -0,0 +1,74 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_vst3/src/rotary_knob.dart'; + +void main() { + group('knobValueAfterDrag', () { + test('dragging up by the full range sweeps 0 to 1', () { + expect(knobValueAfterDrag(0.0, -knobDragRangePixels), 1.0); + }); + test('dragging down decreases the value', () { + expect(knobValueAfterDrag(0.5, 12.0), closeTo(0.4, 1e-12)); + }); + test('clamps to the normalized range', () { + expect(knobValueAfterDrag(0.9, -1000.0), 1.0); + expect(knobValueAfterDrag(0.1, 1000.0), 0.0); + }); + }); + + testWidgets('every drag delta lands even without a rebuild between ' + 'updates [PARAM-GESTURE-VALUE-OPENS]', (tester) async { + final values = []; + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Center( + child: RotaryKnob( + label: 'Mix', + value: 0.5, + display: '50', + onChanged: values.add, + onChangeStart: () {}, + onChangeEnd: () {}, + ), + ), + ), + )); + final gesture = + await tester.startGesture(tester.getCenter(find.text('50'))); + await gesture.moveBy(const Offset(0, -12)); + await gesture.moveBy(const Offset(0, -12)); + await gesture.moveBy(const Offset(0, -12)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + expect(values.length, 3); + expect(values[0], closeTo(0.6, 1e-12)); + expect(values[1], closeTo(0.7, 1e-12)); + expect(values[2], closeTo(0.8, 1e-12)); + }); + testWidgets('a drag fires one start, updates, then one end', (tester) async { + final events = []; + final values = []; + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: Center( + child: RotaryKnob( + label: 'Mix', + value: 0.5, + display: '50', + onChanged: values.add, + onChangeStart: () => events.add('start'), + onChangeEnd: () => events.add('end'), + ), + ), + ), + )); + expect(find.text('Mix'), findsOneWidget); + expect(find.text('50'), findsOneWidget); + await tester.drag(find.text('50'), const Offset(0, -60)); + await tester.pump(); + expect(events, ['start', 'end']); + expect(values, isNotEmpty); + expect(values.every((v) => v > 0.5), isTrue); + }); +} diff --git a/flutter_vst3/test/shared_memory_reader_test.dart b/flutter_vst3/test/shared_memory_reader_test.dart new file mode 100644 index 0000000..2edd6a4 --- /dev/null +++ b/flutter_vst3/test/shared_memory_reader_test.dart @@ -0,0 +1,32 @@ +import 'dart:ffi'; +import 'package:ffi/ffi.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_vst3/src/shared_memory_reader.dart'; +import 'package:flutter_vst3/src/vst3_shm_layout.dart'; + +void main() { + test('reader invalidation and bounded sample counts', () { + final memory = calloc(vst3ShmTotalSize); + addTearDown(() => calloc.free(memory)); + memory.cast().value = vst3ShmMagic; + final reader = Vst3AudioBufferReader.fromAddress(memory.address)!; + expect(reader.isValid, isTrue); + final count = + Pointer.fromAddress(memory.address + vst3OffsetNumSamples); + count.value = 0x7fffffff; + expect(reader.numSamples, vst3ShmMaxSamples); + expect(reader.getOutputL().length, vst3ShmMaxSamples); + expect(reader.getOutputR().length, vst3ShmMaxSamples); + expect(reader.getInputL().length, vst3ShmMaxSamples); + expect(reader.getInputR().length, vst3ShmMaxSamples); + expect(reader.getLatestOutputSamples(maxCount: 100000).length, + vst3ShmMaxSamples); + count.value = -1; + expect(reader.numSamples, 0); + expect(reader.getLatestOutputSamples(), isEmpty); + memory.cast().value = 0; + expect(reader.isValid, isFalse); + expect(reader.getOutputL(), isEmpty); + expect(Vst3AudioBufferReader.fromAddress(0), isNull); + }); +} diff --git a/flutter_vst3/test/shared_memory_routing_test.dart b/flutter_vst3/test/shared_memory_routing_test.dart new file mode 100644 index 0000000..b046f1b --- /dev/null +++ b/flutter_vst3/test/shared_memory_routing_test.dart @@ -0,0 +1,22 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_vst3/src/shared_memory_reader.dart'; +import 'package:flutter_vst3/src/vst3_shm_layout.dart'; + +import 'shm_test_harness.dart'; + +void main() { + test('reader routes four distinct channels and averages exactly', () { + final memory = shmBlock(); + writeI32(memory, vst3OffsetNumSamples, 3); + fillChannels(memory, samples: 3, scale: 10, base: 0.5); + final reader = Vst3AudioBufferReader.fromAddress(memory.address)!; + expect(reader.getInputL(), [0.5, 1.5, 2.5]); + expect(reader.getInputR(), [10.5, 11.5, 12.5]); + expect(reader.getOutputL(), [20.5, 21.5, 22.5]); + expect(reader.getOutputR(), [30.5, 31.5, 32.5]); + expect(reader.getLatestOutputSamples(), [25.5, 26.5, 27.5]); + expect(reader.getLatestOutputSamples(maxCount: 2), [25.5, 26.5]); + reader.getInputL()[1] = -7; + expect(readF32(memory, vst3OffsetInputL, 1), -7); + }); +} diff --git a/flutter_vst3/test/shm_test_harness.dart b/flutter_vst3/test/shm_test_harness.dart new file mode 100644 index 0000000..5f788a1 --- /dev/null +++ b/flutter_vst3/test/shm_test_harness.dart @@ -0,0 +1,67 @@ +// Copyright (c) 2025 +// Shared setup for tests that poke VST3 shared-memory blocks directly. + +import 'dart:ffi'; + +import 'package:ffi/ffi.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_vst3/src/vst3_shm_layout.dart'; +import 'package:flutter_vst3/src/vst3_worker_loop.dart'; + +/// Channel buffer offsets in L-in, R-in, L-out, R-out order +/// ([IPC-BLOCK-OFFSETS]). +const List channelOffsets = [ + vst3OffsetInputL, + vst3OffsetInputR, + vst3OffsetOutputL, + vst3OffsetOutputR, +]; + +/// Allocates a live [vst3ShmTotalSize] block ([IPC-BLOCK-MAGIC]) that frees +/// itself at test end. +Pointer shmBlock() { + final memory = calloc(vst3ShmTotalSize); + addTearDown(() => calloc.free(memory)); + writeU32(memory, vst3OffsetMagic, vst3ShmMagic); + return memory; +} + +/// Marks [memory] live ([IPC-BLOCK-MAGIC]) and expects the header check to +/// keep rejecting the block while the protocol version is missing, then +/// completes the header. +void writeLiveMagicExpectingVersionReject(Pointer memory) { + writeU32(memory, vst3OffsetMagic, vst3ShmMagic); + expect(() => validateShmHeader(memory.cast()), throwsStateError); + writeU32(memory, vst3OffsetVersion, vst3ShmVersion); +} + +/// Writes [value] into the u32 field at [offset]. +void writeU32(Pointer memory, int offset, int value) => + Pointer.fromAddress(memory.address + offset).value = value; + +/// Writes [value] into the i32 field at [offset]. +void writeI32(Pointer memory, int offset, int value) => + Pointer.fromAddress(memory.address + offset).value = value; + +/// Writes [value] into the f64 field at [offset]. +void writeF64(Pointer memory, int offset, double value) => + Pointer.fromAddress(memory.address + offset).value = value; + +/// Reads sample [index] of the f32 channel at [offset]. +double readF32(Pointer memory, int offset, int index) => + Pointer.fromAddress(memory.address + offset)[index]; + +/// Fills all four channel buffers with `channel * [scale] + sample + [base]`. +void fillChannels( + Pointer memory, { + required int samples, + required int scale, + required double base, +}) { + for (var channel = 0; channel < channelOffsets.length; channel++) { + for (var sample = 0; sample < samples; sample++) { + Pointer.fromAddress(memory.address + channelOffsets[channel])[ + sample] = channel * scale + sample + base; + } + } +} diff --git a/flutter_vst3/test/support/shared_memory_fixture.dart b/flutter_vst3/test/support/shared_memory_fixture.dart new file mode 100644 index 0000000..b74ba8e --- /dev/null +++ b/flutter_vst3/test/support/shared_memory_fixture.dart @@ -0,0 +1,9 @@ +import 'dart:ffi'; +import 'package:ffi/ffi.dart'; +import 'package:flutter_vst3/src/vst3_shm_layout.dart'; + +/// Allocates a zeroed protocol block for reader and widget tests. +Pointer allocateSharedMemoryFixture() => calloc(vst3ShmTotalSize); + +/// Releases a block after its readers have been disposed. +void freeSharedMemoryFixture(Pointer memory) => calloc.free(memory); diff --git a/flutter_vst3/test/vst3_shared_memory_test.dart b/flutter_vst3/test/vst3_shared_memory_test.dart new file mode 100644 index 0000000..55cd6e4 --- /dev/null +++ b/flutter_vst3/test/vst3_shared_memory_test.dart @@ -0,0 +1,30 @@ +import 'dart:ffi'; +import 'package:ffi/ffi.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_vst3/src/vst3_shm_layout.dart'; +import 'package:flutter_vst3/src/vst3_worker_loop.dart'; + +import 'shm_test_harness.dart'; + +void main() { + test('header magic, version and block bounds are checked', () { + final memory = calloc(vst3ShmTotalSize); + final ptr = memory.cast(); + try { + expect(() => validateShmHeader(ptr), throwsStateError); + writeLiveMagicExpectingVersionReject(memory); + validateShmHeader(ptr); + final length = Pointer.fromAddress(ptr.address + vst3OffsetNumSamples); + for (final invalid in [-1, vst3ShmMaxSamples + 1]) { + length.value = invalid; + expect(() => blockLength(ptr), throwsStateError); + } + for (final valid in [0, vst3ShmMaxSamples]) { + length.value = valid; + expect(blockLength(ptr), valid); + } + } finally { + calloc.free(memory); + } + }); +} diff --git a/flutter_vst3/test/vst3_shm_layout_test.dart b/flutter_vst3/test/vst3_shm_layout_test.dart new file mode 100644 index 0000000..cbcaf69 --- /dev/null +++ b/flutter_vst3/test/vst3_shm_layout_test.dart @@ -0,0 +1,47 @@ +import 'dart:io'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_vst3/src/vst3_shm_layout.dart'; + +void main() { + test('every native protocol define matches Dart', () { + final header = + File('native/include/vst3_shared_memory.h').readAsStringSync(); + final expected = { + 'VST3_SHM_MAGIC': vst3ShmMagic, + 'VST3_SHM_VERSION': vst3ShmVersion, + 'VST3_SHM_MAX_SAMPLES': vst3ShmMaxSamples, + 'VST3_SHM_PARAM_QUEUE_SIZE': vst3ShmParamQueueSize, + 'VST3_CMD_IDLE': 0, + 'VST3_CMD_PROCESS': vst3CmdProcess, + 'VST3_CMD_TERMINATE': vst3CmdTerminate, + 'VST3_CMD_CONFIGURE': vst3CmdConfigure, + 'VST3_CMD_RESET': vst3CmdReset, + 'VST3_SHM_OFFSET_MAGIC': vst3OffsetMagic, + 'VST3_SHM_OFFSET_VERSION': vst3OffsetVersion, + 'VST3_SHM_OFFSET_SAMPLE_RATE': vst3OffsetSampleRate, + 'VST3_SHM_OFFSET_MAX_BLOCK_SIZE': vst3OffsetMaxBlockSize, + 'VST3_SHM_OFFSET_COMMAND': vst3OffsetCommand, + 'VST3_SHM_OFFSET_NUM_SAMPLES': vst3OffsetNumSamples, + 'VST3_SHM_OFFSET_HOST_PARAM_WRITE': vst3OffsetHostParamWrite, + 'VST3_SHM_OFFSET_HOST_PARAM_READ': vst3OffsetHostParamRead, + 'VST3_SHM_OFFSET_HOST_PARAMS': vst3OffsetHostParams, + 'VST3_SHM_OFFSET_UI_PARAM_WRITE': 1060, + 'VST3_SHM_OFFSET_UI_PARAM_READ': 1064, + 'VST3_SHM_OFFSET_UI_PARAMS': 1068, + 'VST3_SHM_OFFSET_INPUT_L': vst3OffsetInputL, + 'VST3_SHM_OFFSET_INPUT_R': vst3OffsetInputR, + 'VST3_SHM_OFFSET_OUTPUT_L': vst3OffsetOutputL, + 'VST3_SHM_OFFSET_OUTPUT_R': vst3OffsetOutputR, + 'VST3_SHM_TOTAL_SIZE': vst3ShmTotalSize, + }; + final matches = RegExp(r'^#define (VST3_\w+) (0x[0-9a-fA-F]+|[0-9]+)\b', + multiLine: true) + .allMatches(header); + expect(matches.length, 26); + expect(expected.length, 26); + for (final match in matches) { + expect(expected, contains(match[1])); + expect(int.parse(match[2]!), expected[match[1]], reason: match[1]); + } + }); +} diff --git a/flutter_vst3/test/vst3_worker_loop_test.dart b/flutter_vst3/test/vst3_worker_loop_test.dart new file mode 100644 index 0000000..2077679 --- /dev/null +++ b/flutter_vst3/test/vst3_worker_loop_test.dart @@ -0,0 +1,153 @@ +import 'dart:ffi'; +import 'dart:isolate'; +import 'dart:typed_data'; +import 'package:ffi/ffi.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_vst3/src/vst3_worker_loop.dart'; +import 'package:flutter_vst3/src/vst3_shm_layout.dart'; +import 'package:flutter_vst3/src/vst3_shared_memory_processor.dart'; + +import 'shm_test_harness.dart'; + +class _Processor implements Vst3WorkerProcessor { + final events = <(int, double)>[]; + final calls = []; + @override + void initialize(double rate, int size) => calls.add('$rate/$size'); + @override + void setParameter(int id, double value) => events.add((id, value)); + @override + void reset() => calls.add('reset'); + @override + void dispose() => calls.add('dispose'); + @override + void processStereo( + Float32List a, Float32List b, Float32List c, Float32List d) { + calls.add('process/${a.length}'); + } +} + +void main() { + test('an interrupted ready wait restarts, any other failure throws ' + '[IPC-SYNC-HANDOFF]', () { + for (final interruptions in [0, 1, 2, 50]) { + var waits = 0; + retryOnSemEintr( + () => ++waits <= interruptions ? -1 : 0, () => vst3SemWaitEintr); + expect(waits, interruptions + 1); + } + for (final errno in [22, 5, 1]) { + var waits = 0; + expect( + () => retryOnSemEintr(() { + waits++; + return -1; + }, () => errno), + throwsA(isA() + .having((e) => e.message, 'message', contains('errno $errno')))); + expect(waits, 1); + } + }); + + test('parameter ring crosses uint32 wrap and writes read index', () async { + final port = ReceivePort(); + final isolate = await Isolate.spawn(_wrapProbe, port.sendPort); + addTearDown(() { + isolate.kill(priority: Isolate.immediate); + port.close(); + }); + final result = await port.first.timeout(const Duration(seconds: 3)) as ( + List<(int, double)>, + int, + int + ); + expect(result.$1, [(10, 0.0), (11, 0.25), (12, 0.5)]); + expect(result.$2, 1); + expect(result.$3, 3); + }, timeout: const Timeout(Duration(seconds: 5))); + + test('header requires both magic and protocol version', () { + final memory = calloc(vst3ShmTotalSize); + addTearDown(() => calloc.free(memory)); + expect(() => validateShmHeader(memory.cast()), throwsStateError); + writeLiveMagicExpectingVersionReject(memory); + expect(() => validateShmHeader(memory.cast()), returnsNormally); + }); + + test('commands and view reuse', () { + final memory = shmBlock(); + final processor = _Processor(); + final views = Vst3BlockViews(memory.cast()); + writeF64(memory, vst3OffsetSampleRate, 96000); + writeU32(memory, vst3OffsetMaxBlockSize, 256); + writeI32(memory, vst3OffsetNumSamples, 8); + for (final command in [ + 0, + vst3CmdConfigure, + vst3CmdReset, + vst3CmdProcess, + vst3CmdTerminate + ]) { + writeU32(memory, vst3OffsetCommand, command); + expect(handleCommand(memory.cast(), views, processor), + command != vst3CmdTerminate); + } + expect(processor.calls, ['96000.0/256', 'reset', 'process/8']); + final originals = [views.inL, views.inR, views.outL, views.outR]; + _assertRouting(memory, originals); + views.resize(8); + final current = [views.inL, views.inR, views.outL, views.outR]; + for (var i = 0; i < 4; i++) { + expect(identical(originals[i], current[i]), isTrue); + } + views.resize(4); + expect(identical(originals[0], views.inL), isFalse); + expect(views.inL.length, 4); + }); + + test('POSIX failure sentinels are checked without dereferencing', () { + expect(() => throwIfMapFailed(Pointer.fromAddress(-1), 'test'), + throwsStateError); + expect(() => throwIfMapFailed(nullptr, 'test'), returnsNormally); + expect(() => throwIfMapFailed(Pointer.fromAddress(1234), 'test'), + returnsNormally); + for (final address in [-1, 0]) { + expect(() => throwIfSemFailed(Pointer.fromAddress(address), 'test'), + throwsStateError); + } + expect(() => throwIfSemFailed(Pointer.fromAddress(1234), 'test'), + returnsNormally); + }); +} + +void _assertRouting(Pointer memory, List views) { + fillChannels(memory, samples: 8, scale: 100, base: 0.25); + for (var channel = 0; channel < channelOffsets.length; channel++) { + expect(views[channel], + [for (var sample = 0; sample < 8; sample++) channel * 100 + sample + 0.25]); + views[channel][7] = channel * 1000 + 0.5; + expect(readF32(memory, channelOffsets[channel], 7), channel * 1000 + 0.5); + } +} + +void _wrapProbe(SendPort port) { + final memory = calloc(vst3ShmTotalSize); + + final processor = _Processor(); + writeU32(memory, vst3OffsetHostParamRead, 0xfffffffe); + writeU32(memory, vst3OffsetHostParamWrite, 1); + for (var i = 0; i < 3; i++) { + final slot = ((0xfffffffe + i) & 0xffffffff) % vst3ShmParamQueueSize; + final event = vst3OffsetHostParams + slot * vst3ShmParamEventSize; + writeI32(memory, event, 10 + i); + writeF64(memory, event + 8, i / 4); + } + drainHostParameters(memory.cast(), processor); + final firstEvents = List.of(processor.events); + final index = + Pointer.fromAddress(memory.address + vst3OffsetHostParamRead) + .value; + drainHostParameters(memory.cast(), processor); + port.send((firstEvents, index, processor.events.length)); + calloc.free(memory); +} diff --git a/mk/common.mk b/mk/common.mk new file mode 100644 index 0000000..f7fe896 --- /dev/null +++ b/mk/common.mk @@ -0,0 +1,6 @@ +# Settings every Makefile shares. macOS ships Make 3.81, which ignores .SHELLFLAGS, +# so a recipe line that runs several commands has to stop on failure itself. +REPO_ROOT := $(abspath $(dir $(lastword $(MAKEFILE_LIST)))..) +VST3_SDK_DIR ?= $(REPO_ROOT)/vst3sdk +export VST3_SDK_DIR +.SHELLFLAGS = -ec diff --git a/mk/native.mk b/mk/native.mk new file mode 100644 index 0000000..1234e45 --- /dev/null +++ b/mk/native.mk @@ -0,0 +1,14 @@ +# Private targets for a package with a native library. Set NATIVE_LIB first. +PACKAGE_TOOL ?= dart +include $(dir $(lastword $(MAKEFILE_LIST)))package.mk +.PHONY: _native _clean + +_native: + test -d "$(VST3_SDK_DIR)" + cmake -S native -B native/build -DCMAKE_BUILD_TYPE=Release + cmake --build native/build --parallel + cp native/build/lib$(NATIVE_LIB).* "$(REPO_ROOT)/" + cp native/build/lib$(NATIVE_LIB).* . +_clean: + rm -rf native/build + rm -f "$(REPO_ROOT)"/lib$(NATIVE_LIB).* lib$(NATIVE_LIB).* diff --git a/mk/package.mk b/mk/package.mk new file mode 100644 index 0000000..a7a4fbb --- /dev/null +++ b/mk/package.mk @@ -0,0 +1,11 @@ +# Private targets every Dart package has. Set PACKAGE_TOOL to dart or flutter first. +include $(dir $(lastword $(MAKEFILE_LIST)))common.mk +PACKAGE ?= $(patsubst $(REPO_ROOT)/%,%,$(CURDIR)) +.PHONY: _deps _lint _test + +_deps: + $(PACKAGE_TOOL) pub get +_lint: + $(PACKAGE_TOOL) analyze +_test: + bash "$(REPO_ROOT)/flutter_vst3/test/native/run_package_coverage.sh" "$(PACKAGE)" diff --git a/setup.bat b/setup.bat new file mode 100644 index 0000000..37e976b --- /dev/null +++ b/setup.bat @@ -0,0 +1,5 @@ +@echo off +setlocal +cd /d "%~dp0" +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0setup.ps1" %* +exit /b %ERRORLEVEL% diff --git a/setup.ps1 b/setup.ps1 new file mode 100644 index 0000000..892a2eb --- /dev/null +++ b/setup.ps1 @@ -0,0 +1,95 @@ +# Stop on first error +$ErrorActionPreference = 'Stop' + +Write-Host "Setting up development environment on Windows..." + +# Resolve script root directory +$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path +Set-Location $ScriptDir + +# Check dependencies on Windows +Write-Host "Checking dependencies for Windows..." + +# 1. Check CMake +if (-not (Get-Command cmake -ErrorAction SilentlyContinue)) { + Write-Host "CMake is not installed or not in PATH." -ForegroundColor Yellow + if (Get-Command winget -ErrorAction SilentlyContinue) { + Write-Host "Installing CMake via winget..." + winget install --id Kitware.CMake -e --silent --accept-source-agreements --accept-package-agreements + if ($LASTEXITCODE -ne 0) { throw 'CMake installation failed' } + Write-Host "Please restart your terminal after installation and run this script again." + exit 1 + } else { + Write-Error "Please install CMake (https://cmake.org/download/) and add it to your PATH." + } +} else { + Write-Host "cmake already installed" +} + +# 2. Check C++ Compiler / Build Tools (MSVC / Visual Studio Build Tools) +$hasCompiler = $false +if (Get-Command cl -ErrorAction SilentlyContinue) { + $hasCompiler = $true +} else { + $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" + if (Test-Path $vswhere) { + $vsInstall = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath + if ($LASTEXITCODE -ne 0) { throw 'vswhere failed' } + if ($vsInstall) { + $hasCompiler = $true + } + } +} + +if (-not $hasCompiler) { + Write-Host "Visual Studio C++ Build Tools not detected." -ForegroundColor Yellow + Write-Host "Please install 'Desktop development with C++' via Visual Studio Installer or run:" + Write-Host " winget install Microsoft.VisualStudio.2022.BuildTools --override `"--add Microsoft.VisualStudio.Workload.VCTools --includeRecommended`"" + Write-Error "C++ compiler tools are required to build native libraries." +} else { + Write-Host "C++ build tools available" +} + +# 3. Check / Download and extract VST3 SDK +$vst3SdkDir = "$ScriptDir\vst3sdk" +if (-not (Test-Path $vst3SdkDir)) { + Write-Host "Downloading VST3 SDK..." + $zipFile = "$ScriptDir\vst3sdk.zip" + + # Download using curl if available, otherwise Invoke-WebRequest + if (Get-Command curl.exe -ErrorAction SilentlyContinue) { + & curl.exe -fL -o $zipFile https://www.steinberg.net/vst3sdk + if ($LASTEXITCODE -ne 0) { throw 'SDK download failed' } + } else { + Invoke-WebRequest -Uri "https://www.steinberg.net/vst3sdk" -OutFile $zipFile + } + + Write-Host "Extracting VST3 SDK..." + # tar is built-in on Windows 10/11 and much faster than Expand-Archive + if (Get-Command tar.exe -ErrorAction SilentlyContinue) { + & tar.exe -xf $zipFile + if ($LASTEXITCODE -ne 0) { throw 'SDK extraction failed' } + } else { + Expand-Archive -Path $zipFile -DestinationPath $ScriptDir -Force + } + + if (Test-Path "$ScriptDir\VST_SDK\vst3sdk") { + Move-Item -Path "$ScriptDir\VST_SDK\vst3sdk" -Destination $ScriptDir -Force + Remove-Item -Path "$ScriptDir\VST_SDK" -Recurse -Force + } + if (Test-Path $zipFile) { + Remove-Item -Path $zipFile -Force + } + Write-Host "VST3 SDK downloaded and extracted." +} else { + Write-Host "VST3 SDK already exists, skipping download." +} + +# 4. Set VST3_SDK_DIR environment variable (forward slashes for CMake compatibility) +$cmakeVst3Sdk = ($vst3SdkDir).Replace('\', '/') +$env:VST3_SDK_DIR = $cmakeVst3Sdk + +# 5. Reuse the checked native build and artifact validation. +& "$ScriptDir/build.ps1" native + +Write-Host "Setup complete! Native libraries built and ready for development." -ForegroundColor Green diff --git a/setup.sh b/setup.sh index ef4c51b..6d94146 100755 --- a/setup.sh +++ b/setup.sh @@ -1,72 +1,31 @@ -#!/bin/bash - -set -e - +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" echo 'Setting up development environment...' -# Check and install dependencies on macOS -if [ "$(uname)" = "Darwin" ]; then - echo 'Checking dependencies for macOS...' - - # Check if Homebrew is installed - if ! command -v brew &> /dev/null; then - echo 'Installing Homebrew...' - /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" - fi - - # Check and install cmake - if ! command -v cmake &> /dev/null; then - echo 'Installing cmake...' +if [ "$(uname)" = Darwin ]; then + if ! command -v cmake >/dev/null; then + command -v brew >/dev/null brew install cmake - else - echo 'cmake already installed' fi - - # Check and install make (part of Xcode command line tools) - if ! command -v make &> /dev/null; then - echo 'Installing Xcode command line tools...' + if ! command -v make >/dev/null; then xcode-select --install - echo 'Please complete the Xcode command line tools installation and run this script again.' + echo 'Complete the Xcode command line tools installation, then rerun setup.' >&2 exit 1 - else - echo 'make already installed' fi fi -# Download and extract VST3 SDK if not present if [ ! -d vst3sdk ]; then - echo 'Downloading VST3 SDK...' - curl -L -o vst3sdk.zip https://www.steinberg.net/vst3sdk + curl -fL -o vst3sdk.zip https://www.steinberg.net/vst3sdk unzip -q vst3sdk.zip if [ -d VST_SDK/vst3sdk ]; then mv VST_SDK/vst3sdk . rm -rf VST_SDK fi - rm -f vst3sdk.zip - echo 'VST3 SDK downloaded and extracted.' -else - echo 'VST3 SDK already exists, skipping download.' + test -d vst3sdk + find vst3sdk -name '*.sh' -exec chmod +x {} + + rm vst3sdk.zip fi - -# Set VST3_SDK_DIR environment variable -export VST3_SDK_DIR="$(pwd)/vst3sdk" - -# Build native library -echo 'Building native library...' -mkdir -p native/build -cd native/build -cmake .. -make - -# Copy library to project root -if [ "$(uname)" = "Darwin" ]; then - cp libdart_vst_host.dylib ../../ -elif [ "$(uname)" = "Linux" ]; then - cp libdart_vst_host.so ../../ -else - cp libdart_vst_host.dll ../../ -fi - -cd ../.. - -echo 'Setup complete! Native library built and ready for development.' \ No newline at end of file +export VST3_SDK_DIR="$PWD/vst3sdk" +make native +echo 'Setup complete! Native libraries built and ready for development.' diff --git a/vsts/Makefile b/vsts/Makefile new file mode 100644 index 0000000..d0cb342 --- /dev/null +++ b/vsts/Makefile @@ -0,0 +1,17 @@ +# Every plugin. Each has its own Makefile in its folder. +.DEFAULT_GOAL := build +.PHONY: build deploy echo reverb deploy-echo deploy-reverb _clean + +build: echo reverb +deploy: deploy-echo deploy-reverb +echo: + $(MAKE) -C echo build +reverb: + $(MAKE) -C flutter_reverb build +deploy-echo: + $(MAKE) -C echo deploy +deploy-reverb: + $(MAKE) -C flutter_reverb deploy +_clean: + $(MAKE) -C echo _clean + $(MAKE) -C flutter_reverb _clean diff --git a/vsts/echo/.metadata b/vsts/echo/.metadata new file mode 100644 index 0000000..3fd27bc --- /dev/null +++ b/vsts/echo/.metadata @@ -0,0 +1,33 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "6a19cca56475dbfba1478ee68d7bd0c2ef891da1" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + - platform: linux + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + - platform: windows + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/vsts/echo/CMakeLists.txt b/vsts/echo/CMakeLists.txt index ff2d19e..5399092 100644 --- a/vsts/echo/CMakeLists.txt +++ b/vsts/echo/CMakeLists.txt @@ -1,28 +1,34 @@ cmake_minimum_required(VERSION 3.20) project(echo_plugin VERSION 1.0.0 - LANGUAGES CXX) + LANGUAGES C CXX) +if(APPLE) + enable_language(OBJC OBJCXX) +endif() # Build the Echo VST® 3 plugin using flutter_vst3 # This plugin uses pure Dart audio processing with Flutter UI via FFI bridge set(CMAKE_CXX_STANDARD 17) -# Set build type and debug flags -if(NOT CMAKE_BUILD_TYPE) - set(CMAKE_BUILD_TYPE Release) +# Set build type and debug/release flags across single- and multi-config generators +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) endif() -if(CMAKE_BUILD_TYPE STREQUAL "Debug") - add_compile_definitions(_DEBUG) -else() - add_compile_definitions(NDEBUG RELEASE) -endif() +add_compile_definitions( + $<$:_DEBUG> + $<$>:NDEBUG> + $<$>:RELEASE=1> +) # Include the flutter_vst3 CMake helper include(../../flutter_vst3/native/cmake/VST3Bridge.cmake) # Create the VST® 3 plugin using auto-generated code from Dart definitions -# The bridge will auto-generate all C++ files from lib/echo_parameters.dart -# Metadata is read from plugin_metadata.json by the generator -add_dart_vst3_plugin(echo echo_parameters.dart) \ No newline at end of file +# The bridge will auto-generate all C++ files from lib/src/echo_parameters.dart +add_dart_vst3_plugin(echo lib/src/echo_parameters.dart + BUNDLE_IDENTIFIER "com.yourcompany.vst3.echo" + COMPANY_NAME "Your Company" + PLUGIN_NAME "Echo" +) \ No newline at end of file diff --git a/vsts/echo/Makefile b/vsts/echo/Makefile new file mode 100644 index 0000000..5cbaf55 --- /dev/null +++ b/vsts/echo/Makefile @@ -0,0 +1,10 @@ +PLUGIN ?= echo +FLUTTER_BUILD_MODE ?= release +include ../plugin.mk +.PHONY: _flutter-ui + +# Echo's editor is a Flutter app, which goes inside the bundle. +build: _flutter-ui +_flutter-ui: _deps + case "$$(uname)" in Darwin) platform=macos;; Linux) platform=linux;; MINGW*|MSYS*|CYGWIN*) platform=windows;; *) echo 'Unsupported platform' >&2; exit 1;; esac; \ + flutter build $$platform --$(FLUTTER_BUILD_MODE) diff --git a/vsts/echo/README.md b/vsts/echo/README.md new file mode 100644 index 0000000..1ca662a --- /dev/null +++ b/vsts/echo/README.md @@ -0,0 +1,25 @@ +# Echo + +A stereo VST3 delay effect with an embedded Flutter editor. DSP runs in a +separate worker process connected to the host through shared memory. + +Parameters from `plugin_metadata.json` (values are normalized 0–1): + +| Parameter | Meaning | Default | +|---|---|---| +| Delay Time | 0–1000 ms | 0.5 (500 ms) | +| Feedback | 0–100% | 0.3 (30%) | +| Mix | Dry to wet, 0–100% | 0.5 (50%) | +| Bypass | Enables bypass | 0 (off) | + +From the repository root, with Flutter, CMake, a C++ toolchain and +`VST3_SDK_DIR` pointing at the Steinberg SDK: + +```sh +make echo +cd vsts/echo +flutter test +``` + +The bundle is produced at `vsts/echo/build/VST3/Release/echo.vst3`. +On Windows use `build.bat echo`. Linux editors require an X11 host environment. diff --git a/vsts/echo/analysis_options.yaml b/vsts/echo/analysis_options.yaml new file mode 100644 index 0000000..1493108 --- /dev/null +++ b/vsts/echo/analysis_options.yaml @@ -0,0 +1,34 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +analyzer: + exclude: + - build/** + - macos/** + - windows/** + - linux/** +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/vsts/echo/lib/echo_parameters.dart b/vsts/echo/lib/echo_parameters.dart deleted file mode 100644 index 0eafd0b..0000000 --- a/vsts/echo/lib/echo_parameters.dart +++ /dev/null @@ -1,76 +0,0 @@ -/// Echo parameters for the VST3 plugin -class EchoParameters { - static const int kDelayTimeParam = 0; - static const int kFeedbackParam = 1; - static const int kMixParam = 2; - static const int kBypassParam = 3; - - /// Controls the delay time in milliseconds (0ms to 1000ms) - double delayTime = 0.5; - - /// Controls the feedback amount (0% = single echo, 100% = infinite) - double feedback = 0.3; - - /// Controls the wet/dry mix (0% = dry only, 100% = wet only) - double mix = 0.5; - - /// Bypasses the echo effect when enabled - double bypass = 0.0; - - /// Get parameter value by ID - double getParameter(int paramId) { - return switch (paramId) { - kDelayTimeParam => delayTime, - kFeedbackParam => feedback, - kMixParam => mix, - kBypassParam => bypass, - _ => throw ArgumentError('Unknown parameter ID: $paramId'), - }; - } - - /// Set parameter value by ID - void setParameter(int paramId, double value) { - final clampedValue = value.clamp(0.0, 1.0); - switch (paramId) { - case kDelayTimeParam: - delayTime = clampedValue; - break; - case kFeedbackParam: - feedback = clampedValue; - break; - case kMixParam: - mix = clampedValue; - break; - case kBypassParam: - bypass = clampedValue; - break; - default: - throw ArgumentError('Unknown parameter ID: $paramId'); - } - } - - /// Get parameter name by ID - String getParameterName(int paramId) { - return switch (paramId) { - kDelayTimeParam => 'Delay Time', - kFeedbackParam => 'Feedback', - kMixParam => 'Mix', - kBypassParam => 'Bypass', - _ => throw ArgumentError('Unknown parameter ID: $paramId'), - }; - } - - /// Get parameter units by ID - String getParameterUnits(int paramId) { - return switch (paramId) { - kDelayTimeParam => 'ms', - kFeedbackParam => '%', - kMixParam => '%', - kBypassParam => '', - _ => throw ArgumentError('Unknown parameter ID: $paramId'), - }; - } - - /// Get number of parameters - static const int numParameters = 4; -} \ No newline at end of file diff --git a/vsts/echo/lib/echo_processor_exe.dart b/vsts/echo/lib/echo_processor_exe.dart index 5963736..9cedd97 100644 --- a/vsts/echo/lib/echo_processor_exe.dart +++ b/vsts/echo/lib/echo_processor_exe.dart @@ -1,81 +1,44 @@ -import 'dart:io'; import 'dart:typed_data'; -import 'src/echo_processor.dart'; +import 'package:flutter_vst3/flutter_vst3.dart'; import 'src/echo_parameters.dart'; +import 'src/echo_processor.dart'; + +/// Adapts the Echo DSP engine and parameter state to match the interface +/// expected by [runVst3SharedMemoryProcessor]. +final class _EchoProcessorWrapper implements Vst3WorkerProcessor { + final EchoProcessor _processor = EchoProcessor(); + final EchoParameters _parameters = EchoParameters(); + + @override + void initialize(double sampleRate, int maxBlockSize) => + _processor.initialize(sampleRate, maxBlockSize); + + @override + void setParameter(int paramId, double value) => + _parameters.setParameter(paramId, value); + + @override + void processStereo( + Float32List inputL, + Float32List inputR, + Float32List outputL, + Float32List outputR, + ) => + _processor.processStereo(inputL, inputR, outputL, outputR, _parameters); + + @override + void reset() => _processor.reset(); + + @override + void dispose() => _processor.dispose(); +} -const CMD_INIT = 0x01; -const CMD_PROCESS = 0x02; -const CMD_SET_PARAM = 0x03; -const CMD_TERMINATE = 0xFF; -void main() async { - final processor = EchoProcessor(); - final parameters = EchoParameters(); - - // CRITICAL: Set binary mode (only if stdin is a terminal) - try { - stdin.lineMode = false; - } catch (e) { - // Ignore error if stdin is not a terminal (e.g., when piped) - } - - // Main event loop - await for (final bytes in stdin) { - if (bytes.isEmpty) continue; - - final buffer = ByteData.view(Uint8List.fromList(bytes).buffer); - final command = buffer.getUint8(0); - - switch (command) { - case CMD_INIT: - final sampleRate = buffer.getFloat64(1, Endian.little); - processor.initialize(sampleRate, 512); - stdout.add([CMD_INIT]); // ACK - await stdout.flush(); - break; - - case CMD_PROCESS: - final numSamples = buffer.getInt32(1, Endian.little); - // Read interleaved stereo - final audioData = Float32List(numSamples * 2); - for (int i = 0; i < numSamples * 2; i++) { - audioData[i] = buffer.getFloat32(5 + i * 4, Endian.little); - } - - // Split to L/R - final inputL = List.generate(numSamples, - (i) => audioData[i * 2].toDouble()); - final inputR = List.generate(numSamples, - (i) => audioData[i * 2 + 1].toDouble()); - - final outputL = List.filled(numSamples, 0.0); - final outputR = List.filled(numSamples, 0.0); - - // PROCESS WITH YOUR DART CODE! - processor.processStereo(inputL, inputR, outputL, outputR, parameters); - - // Send back interleaved - final response = ByteData(1 + numSamples * 8); - response.setUint8(0, CMD_PROCESS); - for (int i = 0; i < numSamples; i++) { - response.setFloat32(1 + i * 8, outputL[i], Endian.little); - response.setFloat32(1 + i * 8 + 4, outputR[i], Endian.little); - } - - stdout.add(response.buffer.asUint8List()); - await stdout.flush(); - break; - - case CMD_SET_PARAM: - final paramId = buffer.getInt32(1, Endian.little); - final value = buffer.getFloat64(5, Endian.little); - parameters.setParameter(paramId, value); - stdout.add([CMD_SET_PARAM]); // ACK - await stdout.flush(); - break; - - case CMD_TERMINATE: - exit(0); - } - } -} \ No newline at end of file +/// Entry point for Echo processor executable. +/// Uses preallocated zero-copy shared memory and POSIX semaphores. +void main(List args) { + runVst3SharedMemoryProcessor( + args: args, + processor: _EchoProcessorWrapper(), + ); +} diff --git a/vsts/echo/lib/main.dart b/vsts/echo/lib/main.dart new file mode 100644 index 0000000..f21048a --- /dev/null +++ b/vsts/echo/lib/main.dart @@ -0,0 +1,32 @@ +import 'package:flutter/material.dart'; +import 'ui/echo_ui.dart'; + +/// Entry point for the Echo plugin Flutter GUI. +@pragma('vm:entry-point') +void echoMain() { + debugPrint('=== [Echo VST3] echoMain launched ==='); + runApp(const EchoApp()); +} + +void main() => echoMain(); + + +/// Root widget for the Echo plugin UI. +class EchoApp extends StatelessWidget { + const EchoApp({super.key}); + + @override + Widget build(BuildContext context) { + return MaterialApp( + debugShowCheckedModeBanner: false, + title: 'Echo VST3', + theme: ThemeData.dark(useMaterial3: true).copyWith( + colorScheme: ColorScheme.fromSeed( + seedColor: const Color(0xFF00E5FF), + brightness: Brightness.dark, + ), + ), + home: const EchoUI(), + ); + } +} diff --git a/vsts/echo/lib/src/echo_bridge.dart b/vsts/echo/lib/src/echo_bridge.dart deleted file mode 100644 index 7ed043d..0000000 --- a/vsts/echo/lib/src/echo_bridge.dart +++ /dev/null @@ -1,21 +0,0 @@ -import 'package:flutter_vst3/flutter_vst3.dart'; -import 'echo_vst3_processor.dart'; - -/// FFI bindings for the echo VST3 bridge - FAILS HARD if callbacks not registered -class EchoBridge { - static EchoVST3Processor? _processor; - - /// Initialize the bridge and register callbacks - static void initialize() { - // Create the processor - _processor = EchoVST3Processor(); - - // Register with the global VST3 bridge - VST3Bridge.registerProcessor(_processor!); - - print('Echo bridge initialized with callbacks registered'); - } - - /// Get the registered processor (for testing) - static EchoVST3Processor? getProcessor() => _processor; -} \ No newline at end of file diff --git a/vsts/echo/lib/src/echo_parameters.dart b/vsts/echo/lib/src/echo_parameters.dart index 0eafd0b..514a225 100644 --- a/vsts/echo/lib/src/echo_parameters.dart +++ b/vsts/echo/lib/src/echo_parameters.dart @@ -8,7 +8,8 @@ class EchoParameters { /// Controls the delay time in milliseconds (0ms to 1000ms) double delayTime = 0.5; - /// Controls the feedback amount (0% = single echo, 100% = infinite) + /// Controls decaying feedback (0% = single echo, 100% = stable 0.85 loop gain, + /// 15% decay per repeat). double feedback = 0.3; /// Controls the wet/dry mix (0% = dry only, 100% = wet only) diff --git a/vsts/echo/lib/src/echo_plugin.dart b/vsts/echo/lib/src/echo_plugin.dart deleted file mode 100644 index a76e67b..0000000 --- a/vsts/echo/lib/src/echo_plugin.dart +++ /dev/null @@ -1,161 +0,0 @@ -import 'echo_processor.dart'; -import 'echo_parameters.dart'; - -/// Simple Echo Plugin with natural delay effect and FAIL HARD validation -class DartEchoPlugin { - - EchoProcessor? _processor; - final EchoParameters _parameters = EchoParameters(); - bool _isActive = false; - - /// Initialize the plugin - bool initialize() { - _processor = EchoProcessor(); - return true; - } - - /// Set up audio processing parameters - void setupProcessing(double sampleRate, int maxBlockSize) { - _processor?.initialize(sampleRate, maxBlockSize); - } - - /// Activate/deactivate the plugin - void setActive(bool active) { - if (active && !_isActive) { - _processor?.reset(); - } - _isActive = active; - } - - /// Get plugin information from metadata JSON - Map get pluginInfo { - return { - 'name': 'Echo', - 'vendor': 'CF', - 'version': '1.0.0', - 'category': 'Fx|Delay', - 'type': 'effect', - 'inputs': 2, - 'outputs': 2, - 'parameters': 4, - 'canProcessReplacing': true, - 'hasEditor': false, - }; - } - - /// Set parameter value by index - void setParameter(int index, double value) { - switch (index) { - case 0: - _parameters.delayTime = value; - break; - case 1: - _parameters.feedback = value; - break; - case 2: - _parameters.mix = value; - break; - case 3: - _parameters.bypass = value; - break; - } - } - - /// Get parameter value by index - double getParameter(int index) { - return switch (index) { - 0 => _parameters.delayTime, - 1 => _parameters.feedback, - 2 => _parameters.mix, - 3 => _parameters.bypass, - _ => 0.0, - }; - } - - /// Get parameter info by index - Map getParameterInfo(int index) { - return switch (index) { - 0 => { - 'name': 'delayTime', - 'displayName': 'Delay Time', - 'description': 'Controls the delay time in milliseconds (0ms to 500ms)', - 'defaultValue': 0.5, - 'units': 'ms', - }, - 1 => { - 'name': 'feedback', - 'displayName': 'Feedback', - 'description': 'Controls the feedback amount (0% = single echo, 85% = max stable)', - 'defaultValue': 0.3, - 'units': '%', - }, - 2 => { - 'name': 'mix', - 'displayName': 'Mix', - 'description': 'Controls the wet/dry mix (0% = dry only, 100% = wet only)', - 'defaultValue': 0.5, - 'units': '%', - }, - 3 => { - 'name': 'bypass', - 'displayName': 'Bypass', - 'description': 'Bypasses the echo effect when enabled', - 'defaultValue': 0.0, - 'units': '', - }, - _ => {}, - }; - } - - /// Process audio block - void processAudio(List> inputs, List> outputs) { - if (!_isActive || inputs.isEmpty || outputs.isEmpty) { - return; - } - - // Ensure we have stereo inputs and outputs - final inputL = inputs.isNotEmpty ? inputs[0] : []; - final inputR = inputs.length > 1 ? inputs[1] : inputL; - - if (outputs.isEmpty) return; - final outputL = outputs[0]; - final outputR = outputs.length > 1 ? outputs[1] : outputL; - - if (inputL.isEmpty || outputL.isEmpty) return; - - // Process the audio through the echo effect with parameters - if (_processor == null) { - throw StateError('CRITICAL PLUGIN FAILURE: EchoProcessor not initialized!'); - } - - // Use current parameter values (not hardcoded defaults) - - _processor!.processStereo(inputL, inputR, outputL, outputR, _parameters); - } - - /// Dispose resources - void dispose() { - _isActive = false; - _processor?.dispose(); - } -} - -/// Factory for creating echo plugin instances -class DartEchoFactory { - /// Create a new plugin instance - static DartEchoPlugin createInstance() { - return DartEchoPlugin(); - } - - /// Get plugin class information from metadata JSON - static Map getClassInfo() { - return { - 'name': 'Echo', - 'vendor': 'CF', - 'version': '1.0.0', - 'category': 'Fx|Delay', - 'classId': 'DartEcho', - 'controllerId': 'DartEchoController', - }; - } -} \ No newline at end of file diff --git a/vsts/echo/lib/src/echo_processor.dart b/vsts/echo/lib/src/echo_processor.dart index 0faf077..f7b0dc3 100644 --- a/vsts/echo/lib/src/echo_processor.dart +++ b/vsts/echo/lib/src/echo_processor.dart @@ -1,103 +1,116 @@ +import 'dart:math' as math; +import 'dart:typed_data'; import 'echo_parameters.dart'; /// Simple echo/delay effect processor that FAILS HARD without parameters class EchoProcessor { - static const int _delayBufferSize = 132300; // ~3 seconds at 44.1kHz + int _delayBufferSize = 0; - final List _delayBufferL = List.filled(_delayBufferSize, 0.0); - final List _delayBufferR = List.filled(_delayBufferSize, 0.0); + Float32List _delayBufferL = Float32List(0); + Float32List _delayBufferR = Float32List(0); int _writeIndex = 0; double _sampleRate = 44100.0; bool _initialized = false; + double _currentDelaySamples = -1.0; + double _smoothCoeff = 0.0; /// Initialize the echo processor void initialize(double sampleRate, int maxBlockSize) { _sampleRate = sampleRate; + sampleRate.isFinite && sampleRate > 0 && maxBlockSize > 0 + ? null : throw ArgumentError("Invalid audio configuration"); + _smoothCoeff = 1.0 - math.exp(-1.0 / (sampleRate * 0.03)); + _delayBufferSize = sampleRate.ceil() + 2; + _delayBufferL = Float32List(_delayBufferSize); + _delayBufferR = Float32List(_delayBufferSize); + reset(); _initialized = true; } - /// Process stereo audio block with parameters-driven echo that FAILS HARD - void processStereo(List inputL, List inputR, - List outputL, List outputR, - EchoParameters parameters) { + void _validateBuffers( + Float32List inL, + Float32List inR, + Float32List outL, + Float32List outR, + ) { if (!_initialized) { - throw StateError('ECHO PROCESSOR FAILURE: Not initialized! Cannot process audio without initialization!'); - } - - if (inputL.length != inputR.length || outputL.length != inputL.length || outputR.length != inputL.length) { - throw ArgumentError('ECHO PROCESSOR FAILURE: Buffer length mismatch! All buffers must have the same length!'); - } - - // Convert normalized parameters to actual values - final delayTime = parameters.delayTime; // 0.0 to 1.0 -> 0ms to 1000ms - final feedback = parameters.feedback; // 0.0 to 1.0 -> 0% to 100% - final mix = parameters.mix; // 0.0 to 1.0 -> 0% to 100% - final bypass = parameters.bypass; // 0.0 = active, 1.0 = bypassed - - // If bypassed, pass through clean signal - if (bypass > 0.5) { - for (int i = 0; i < inputL.length; i++) { - outputL[i] = inputL[i]; - outputR[i] = inputR[i]; - } - return; + throw StateError( + 'ECHO PROCESSOR FAILURE: Not initialized! Cannot process audio without initialization!', + ); } - - // Calculate delay in samples (scale from 0-1 to 10ms-500ms for musical range) - final delayMs = 10.0 + (delayTime * 490.0); // 10ms to 500ms range - final delayInSamples = (delayMs * _sampleRate / 1000.0).round().clamp(1, _delayBufferSize - 1); - - // Scale feedback for musical control - final feedbackAmount = feedback * 0.85; // Max 85% for stable feedback - - // Scale wet/dry mix for natural blend - final wetLevel = mix; - final dryLevel = (1.0 - mix); - - for (int i = 0; i < inputL.length; i++) { - // Calculate read index for delay - final readIndex = (_writeIndex - delayInSamples + _delayBufferSize) % _delayBufferSize; - - // Get delayed samples - final delayedL = _delayBufferL[readIndex]; - final delayedR = _delayBufferR[readIndex]; - - // Apply feedback with saturation - final saturatedFeedbackL = _softSaturate(delayedL * feedbackAmount); - final saturatedFeedbackR = _softSaturate(delayedR * feedbackAmount); - - // Write input + feedback to delay buffer - _delayBufferL[_writeIndex] = inputL[i] + saturatedFeedbackL; - _delayBufferR[_writeIndex] = inputR[i] + saturatedFeedbackR; - - // Clean wet signal with slight stereo width - final wetL = (delayedL * wetLevel) + (delayedR * wetLevel * 0.1); - final wetR = (delayedR * wetLevel) + (delayedL * wetLevel * 0.1); - - // Mix dry and wet signals - final finalL = (inputL[i] * dryLevel) + wetL; - final finalR = (inputR[i] * dryLevel) + wetR; - - outputL[i] = finalL; - outputR[i] = finalR; - - // Advance write index - _writeIndex = (_writeIndex + 1) % _delayBufferSize; + if (inL.length != inR.length || + outL.length != inL.length || + outR.length != inL.length) { + throw ArgumentError( + 'ECHO PROCESSOR FAILURE: Buffer length mismatch! All buffers must have the same length!', + ); } } - - /// Soft saturation for controlled feedback limiting - double _softSaturate(double x) { - return x > 1.0 ? 1.0 - (1.0 / (x + 1.0)) : - x < -1.0 ? -1.0 + (1.0 / (-x + 1.0)) : x; + + void _processSample( + double inL, + double inR, + double targetDelay, + double feedbackAmt, + double wet, + double dry, + Float32List outL, + Float32List outR, + int i, + ) { + _currentDelaySamples += (targetDelay - _currentDelaySamples) * _smoothCoeff; + var pos = _writeIndex - _currentDelaySamples; + if (pos < 0) pos += _delayBufferSize; + final i0 = pos.toInt(); + final frac = pos - i0; + final i1 = i0 + 1 >= _delayBufferSize ? 0 : i0 + 1; + + // Under one sample of delay there is nothing older to read but the input. + final dL = _currentDelaySamples < 1.0 ? inL : _delayBufferL[i0] + frac * (_delayBufferL[i1] - _delayBufferL[i0]); + final dR = _currentDelaySamples < 1.0 ? inR : _delayBufferR[i0] + frac * (_delayBufferR[i1] - _delayBufferR[i0]); + _delayBufferL[_writeIndex] = inL + softSaturate(dL * feedbackAmt); + _delayBufferR[_writeIndex] = inR + softSaturate(dR * feedbackAmt); + outL[i] = (inL * dry) + (dL * wet) + (dR * wet * 0.1); + outR[i] = (inR * dry) + (dR * wet) + (dL * wet * 0.1); + _writeIndex = (_writeIndex + 1) % _delayBufferSize; } + /// Process stereo audio block with parameters-driven echo that FAILS HARD + void processStereo( + Float32List inputL, + Float32List inputR, + Float32List outputL, + Float32List outputR, + EchoParameters parameters, + ) { + _validateBuffers(inputL, inputR, outputL, outputR); + final targetDelay = parameters.delayTime.clamp(0.0, 1.0) * _sampleRate; + _currentDelaySamples = _currentDelaySamples < 0 ? targetDelay : _currentDelaySamples; + final fb = parameters.feedback * 0.85; + final wet = parameters.bypass > 0.5 ? 0.0 : parameters.mix; + final dry = 1.0 - wet; + + for (var i = 0; i < inputL.length; i++) { + _processSample(inputL[i], inputR[i], targetDelay, fb, wet, dry, outputL, outputR, i); + } + + } + + /// Unity gain up to a magnitude of 1, then a limit approaching 2. Value and + /// slope are both continuous at the threshold. + static double softSaturate(double x) => x > 1.0 + ? 2.0 - 1.0 / x + : x < -1.0 + ? -2.0 - 1.0 / x + : x; + /// Reset delay buffers void reset() { _delayBufferL.fillRange(0, _delayBufferSize, 0.0); _delayBufferR.fillRange(0, _delayBufferSize, 0.0); _writeIndex = 0; + _currentDelaySamples = -1.0; } /// Dispose resources diff --git a/vsts/echo/lib/src/echo_vst3_processor.dart b/vsts/echo/lib/src/echo_vst3_processor.dart deleted file mode 100644 index 9ba5f7c..0000000 --- a/vsts/echo/lib/src/echo_vst3_processor.dart +++ /dev/null @@ -1,48 +0,0 @@ -import 'package:flutter_vst3/flutter_vst3.dart'; -import 'echo_processor.dart'; -import 'echo_parameters.dart'; - -/// VST3 processor adapter for the Echo plugin -/// This connects the pure Dart echo processor to the VST3 bridge -class EchoVST3Processor extends VST3Processor { - EchoProcessor? _echoProcessor; - final EchoParameters _parameters = EchoParameters(); - - @override - void initialize(double sampleRate, int maxBlockSize) { - _echoProcessor = EchoProcessor(); - _echoProcessor!.initialize(sampleRate, maxBlockSize); - } - - @override - void processStereo(List inputL, List inputR, - List outputL, List outputR) { - _echoProcessor?.processStereo(inputL, inputR, outputL, outputR, _parameters); - } - - @override - void setParameter(int paramId, double normalizedValue) { - _parameters.setParameter(paramId, normalizedValue); - } - - @override - double getParameter(int paramId) { - return _parameters.getParameter(paramId); - } - - @override - int getParameterCount() { - return EchoParameters.numParameters; - } - - @override - void reset() { - _echoProcessor?.reset(); - } - - @override - void dispose() { - _echoProcessor?.dispose(); - _echoProcessor = null; - } -} \ No newline at end of file diff --git a/vsts/echo/lib/ui/echo_ui.dart b/vsts/echo/lib/ui/echo_ui.dart new file mode 100644 index 0000000..d33fcfa --- /dev/null +++ b/vsts/echo/lib/ui/echo_ui.dart @@ -0,0 +1,353 @@ +/// Flutter UI for Echo VST3 plugin +library; + +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter_vst3/ui.dart'; +import '../src/echo_parameters.dart'; + +/// Main UI screen for the Echo VST3 plugin. +class EchoUI extends StatefulWidget { + const EchoUI({super.key}); + + @override + State createState() => _EchoUIState(); +} + +class _EchoUIState extends State { + final VST3ParameterBinding _binding = VST3ParameterBinding.getInstance(); + + @override + void initState() { + super.initState(); + _binding.addListener(_onParametersChanged); + _binding.loadInitialParameters(); + } + + @override + void dispose() { + _binding.removeListener(_onParametersChanged); + super.dispose(); + } + + void _onParametersChanged() { + setState(() {}); + } + + Widget _buildParameterSlider(int paramId, String label) { + final value = _binding.getParameter(paramId); + return RotaryKnob( + label: label, + value: value, + display: formatEchoParameter(paramId, value), + onChangeStart: () => _binding.beginEdit(paramId), + onChanged: (value) => _binding.setParameter(paramId, value), + onChangeEnd: () => _binding.endEdit(paramId), + ); + } + + Widget _buildBypassToggle() { + final isBypassed = _binding.getParameter(EchoParameters.kBypassParam) > 0.5; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Bypass', + style: Theme.of(context).textTheme.titleMedium, + ), + Switch( + value: isBypassed, + onChanged: (value) async { + await _binding.beginEdit(EchoParameters.kBypassParam); + await _binding.setParameter( + EchoParameters.kBypassParam, + value ? 1.0 : 0.0, + ); + await _binding.endEdit(EchoParameters.kBypassParam); + }, + activeThumbColor: Theme.of(context).colorScheme.primary, + ), + ], + ), + ); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Theme.of(context).colorScheme.surface, + appBar: AppBar( + backgroundColor: Theme.of(context).colorScheme.inversePrimary, + title: const Text('Echo VST3'), + centerTitle: true, + ), + body: Column( + children: [ + Expanded( + child: SingleChildScrollView( + physics: const NeverScrollableScrollPhysics(), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 600), + child: Card( + margin: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(height: 24), + Text( + 'Echo Effect', + style: Theme.of(context).textTheme.headlineMedium, + ), + const SizedBox(height: 32), + Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + _buildParameterSlider( + EchoParameters.kDelayTimeParam, + 'Delay Time', + ), + _buildParameterSlider( + EchoParameters.kFeedbackParam, + 'Feedback', + ), + _buildParameterSlider( + EchoParameters.kMixParam, + 'Mix', + ), + ], + ), + const Divider(height: 32), + _buildBypassToggle(), + ..._binding.dspStopped + ? [ + Padding( + padding: const EdgeInsets.only(top: 12), + child: Text( + 'DSP stopped. Audio is silent until the plugin is re-enabled.', + style: TextStyle( + color: Theme.of(context).colorScheme.error, + ), + ), + ), + ] + : const [], + const SizedBox(height: 24), + ], + ), + ), + ), + ), + ), + ), + const EchoWaveformVisualizer(height: 150.0), + ], + ), + ); + } +} + +/// Custom oscilloscope visualizer widget displaying real-time audio waveform. +class EchoWaveformVisualizer extends StatefulWidget { + final double height; + final Color waveColor; + + const EchoWaveformVisualizer({ + super.key, + this.height = 150.0, + this.waveColor = const Color(0xFF00E5FF), + }); + + @override + State createState() => _EchoWaveformVisualizerState(); +} + +class _EchoWaveformVisualizerState extends State { + Timer? _timer; + Vst3AudioBufferReader? _reader; + List _samples = const []; + bool _fetchingReader = false; + bool _attached = true; + int _ticksWithoutReader = 0; + static const int _restartCheckTicks = 30; + + @override + void initState() { + super.initState(); + _initReader(); + _timer = Timer.periodic( + const Duration(milliseconds: 33), (_) => _pollWaveform()); + VST3ParameterBinding.getInstance().addListener(_onBindingUpdated); + } + + void _onBindingUpdated() { + if (!VST3ParameterBinding.getInstance().isHostAttached) { + _attached = false; + _reader = null; + if (mounted && _samples.isNotEmpty) { + setState(() { + _samples = const []; + }); + } + return; + } + final attached = VST3ParameterBinding.getInstance().isHostAttached; + attached && !_attached ? _initReader() : null; + _attached = attached; + } + + void _initReader() async { + if (!VST3ParameterBinding.getInstance().isHostAttached) return; + if (_fetchingReader) return; + _fetchingReader = true; + try { + final reader = await VST3ParameterBinding.getInstance() + .getAudioBufferReader(forceRefresh: true); + if (mounted) { + _reader = (reader != null && reader.isValid) ? reader : null; + } + } finally { + _fetchingReader = false; + } + } + + /// A missing reader is retried on a bounded tick: the worker may have + /// restarted into a new block, or the plugin may have been activated. + void _retryMissingReader() { + _ticksWithoutReader = _ticksWithoutReader + 1; + final due = _ticksWithoutReader >= _restartCheckTicks; + due ? _ticksWithoutReader = 0 : null; + due ? _initReader() : null; + } + + void _pollWaveform() { + if (!VST3ParameterBinding.getInstance().isHostAttached) return; + final reader = _reader; + if (reader == null) { + _retryMissingReader(); + return; + } + if (!reader.isValid || !mounted) { + _reader = null; + _initReader(); + return; + } + final samples = reader.getLatestOutputSamples(maxCount: 256); + if (mounted) { + setState(() => _samples = samples); + } + } + + @override + void dispose() { + VST3ParameterBinding.getInstance().removeListener(_onBindingUpdated); + _timer?.cancel(); + _timer = null; + _reader = null; + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Container( + width: double.infinity, + height: widget.height, + color: Colors.black, + child: CustomPaint( + size: Size(double.infinity, widget.height), + painter: _EchoWaveformPainter( + samples: _samples, + color: widget.waveColor, + ), + ), + ); + } +} + +class _EchoWaveformPainter extends CustomPainter { + final List samples; + final Color color; + + _EchoWaveformPainter({required this.samples, required this.color}); + + @override + void paint(Canvas canvas, Size size) { + _drawGrid(canvas, size); + _drawWave(canvas, size); + } + + void _drawGrid(Canvas canvas, Size size) { + final gridPaint = Paint() + ..color = const Color(0x22FFFFFF) + ..strokeWidth = 1.0; + canvas.drawLine( + Offset(0, size.height / 2), + Offset(size.width, size.height / 2), + gridPaint, + ); + } + + void _drawWave(Canvas canvas, Size size) { + switch (samples.isEmpty) { + case true: + final idlePaint = Paint() + ..color = color.withValues(alpha: 0.5) + ..strokeWidth = 1.5; + canvas.drawLine( + Offset(0, size.height / 2), + Offset(size.width, size.height / 2), + idlePaint, + ); + return; + case false: + final path = buildEchoWaveformPath(samples, size); + _renderPath(canvas, path); + } + } + + void _renderPath(Canvas canvas, Path path) { + final glow = Paint() + ..color = color.withValues(alpha: 0.3) + ..strokeWidth = 5.0 + ..style = PaintingStyle.stroke + ..maskFilter = const MaskFilter.blur(BlurStyle.normal, 3.0); + final line = Paint() + ..color = color + ..strokeWidth = 2.0 + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round; + canvas.drawPath(path, glow); + canvas.drawPath(path, line); + } + + @override + bool shouldRepaint(covariant _EchoWaveformPainter oldDelegate) => true; +} + +/// Builds a finite waveform path, including empty and single-sample blocks. +Path buildEchoWaveformPath(List samples, Size size) { + final path = Path(); + final slice = samples.length < 2 ? 0.0 : size.width / (samples.length - 1); + final centerY = size.height / 2; + + for (var i = 0; i < samples.length; i++) { + final x = i * slice; + final y = centerY - (samples[i].clamp(-1.0, 1.0) * (size.height * 0.44)); + switch (i == 0) { + case true: + path.moveTo(x, y); + case false: + path.lineTo(x, y); + } + } + return path; +} + +/// Formats normalized Echo parameters in their physical units. +String formatEchoParameter(int id, double value) => + id == EchoParameters.kDelayTimeParam + ? '${(value * 1000).toStringAsFixed(1)}ms' + : '${(value * 100).toStringAsFixed(1)}%'; diff --git a/vsts/echo/linux/.gitignore b/vsts/echo/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/vsts/echo/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/vsts/echo/linux/CMakeLists.txt b/vsts/echo/linux/CMakeLists.txt new file mode 100644 index 0000000..37a81d9 --- /dev/null +++ b/vsts/echo/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "echo") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.echo") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/vsts/echo/linux/flutter/CMakeLists.txt b/vsts/echo/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/vsts/echo/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/vsts/echo/linux/flutter/generated_plugin_registrant.cc b/vsts/echo/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..e71a16d --- /dev/null +++ b/vsts/echo/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/vsts/echo/linux/flutter/generated_plugin_registrant.h b/vsts/echo/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/vsts/echo/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/vsts/echo/linux/flutter/generated_plugins.cmake b/vsts/echo/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..2e1de87 --- /dev/null +++ b/vsts/echo/linux/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/vsts/echo/linux/runner/CMakeLists.txt b/vsts/echo/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/vsts/echo/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/vsts/echo/linux/runner/main.cc b/vsts/echo/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/vsts/echo/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/vsts/echo/linux/runner/my_application.cc b/vsts/echo/linux/runner/my_application.cc new file mode 100644 index 0000000..7c07364 --- /dev/null +++ b/vsts/echo/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "echo"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "echo"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/vsts/echo/linux/runner/my_application.h b/vsts/echo/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/vsts/echo/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/vsts/echo/macos/.gitignore b/vsts/echo/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/vsts/echo/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/vsts/echo/macos/Flutter/Flutter-Debug.xcconfig b/vsts/echo/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/vsts/echo/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/vsts/echo/macos/Flutter/Flutter-Release.xcconfig b/vsts/echo/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/vsts/echo/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/vsts/echo/macos/Flutter/ephemeral/Flutter-Generated.xcconfig b/vsts/echo/macos/Flutter/ephemeral/Flutter-Generated.xcconfig deleted file mode 100644 index 1fa71a0..0000000 --- a/vsts/echo/macos/Flutter/ephemeral/Flutter-Generated.xcconfig +++ /dev/null @@ -1,11 +0,0 @@ -// This is a generated file; do not edit or check into version control. -FLUTTER_ROOT=/opt/homebrew/Caskroom/flutter/3.27.2/flutter -FLUTTER_APPLICATION_PATH=/Users/christianfindlay/Documents/Code/vst_project_package/vsts/echo -COCOAPODS_PARALLEL_CODE_SIGN=true -FLUTTER_BUILD_DIR=build -FLUTTER_BUILD_NAME=1.0.0 -FLUTTER_BUILD_NUMBER=1.0.0 -DART_OBFUSCATION=false -TRACK_WIDGET_CREATION=true -TREE_SHAKE_ICONS=false -PACKAGE_CONFIG=.dart_tool/package_config.json diff --git a/vsts/echo/macos/Flutter/ephemeral/flutter_export_environment.sh b/vsts/echo/macos/Flutter/ephemeral/flutter_export_environment.sh deleted file mode 100755 index 393d7e2..0000000 --- a/vsts/echo/macos/Flutter/ephemeral/flutter_export_environment.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh -# This is a generated file; do not edit or check into version control. -export "FLUTTER_ROOT=/opt/homebrew/Caskroom/flutter/3.27.2/flutter" -export "FLUTTER_APPLICATION_PATH=/Users/christianfindlay/Documents/Code/vst_project_package/vsts/echo" -export "COCOAPODS_PARALLEL_CODE_SIGN=true" -export "FLUTTER_BUILD_DIR=build" -export "FLUTTER_BUILD_NAME=1.0.0" -export "FLUTTER_BUILD_NUMBER=1.0.0" -export "DART_OBFUSCATION=false" -export "TRACK_WIDGET_CREATION=true" -export "TREE_SHAKE_ICONS=false" -export "PACKAGE_CONFIG=.dart_tool/package_config.json" diff --git a/vsts/echo/macos/Runner.xcodeproj/project.pbxproj b/vsts/echo/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..2202af9 --- /dev/null +++ b/vsts/echo/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* echo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "echo.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* echo.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* echo.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.echo.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/echo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/echo"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.echo.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/echo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/echo"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.echo.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/echo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/echo"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 12.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/vsts/echo/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/vsts/echo/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/vsts/echo/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/vsts/echo/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/vsts/echo/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..fb57887 --- /dev/null +++ b/vsts/echo/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vsts/echo/macos/Runner.xcworkspace/contents.xcworkspacedata b/vsts/echo/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/vsts/echo/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/vsts/echo/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/vsts/echo/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/vsts/echo/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/vsts/echo/macos/Runner/AppDelegate.swift b/vsts/echo/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/vsts/echo/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/vsts/echo/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/vsts/echo/macos/Runner/Base.lproj/MainMenu.xib b/vsts/echo/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/vsts/echo/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vsts/echo/macos/Runner/Configs/AppInfo.xcconfig b/vsts/echo/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..19882a3 --- /dev/null +++ b/vsts/echo/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = echo + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.echo + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2025 com.example. All rights reserved. diff --git a/vsts/echo/macos/Runner/Configs/Debug.xcconfig b/vsts/echo/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/vsts/echo/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/vsts/echo/macos/Runner/Configs/Release.xcconfig b/vsts/echo/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/vsts/echo/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/vsts/echo/macos/Runner/Configs/Warnings.xcconfig b/vsts/echo/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/vsts/echo/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/vsts/echo/macos/Runner/DebugProfile.entitlements b/vsts/echo/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/vsts/echo/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/vsts/echo/macos/Runner/Info.plist b/vsts/echo/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/vsts/echo/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/vsts/echo/macos/Runner/MainFlutterWindow.swift b/vsts/echo/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/vsts/echo/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/vsts/echo/macos/Runner/Release.entitlements b/vsts/echo/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/vsts/echo/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/vsts/echo/macos/RunnerTests/RunnerTests.swift b/vsts/echo/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/vsts/echo/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/vsts/echo/plugin_metadata.json b/vsts/echo/plugin_metadata.json index 8a9bfb4..34412d9 100644 --- a/vsts/echo/plugin_metadata.json +++ b/vsts/echo/plugin_metadata.json @@ -1,9 +1,12 @@ { "pluginName": "Echo", + "flutterEntrypoint": "echoMain", "vendor": "CF", "version": "1.0.0", "category": "Fx|Delay", "bundleIdentifier": "com.cf.echo", + "processorUid": "F9D0C991074C84044D825FC521E8F92B", + "controllerUid": "A011573216F065964B9846B6007933D0", "companyWeb": "https://cf.com", "companyEmail": "info@cf.com", "parameters": [ @@ -19,7 +22,7 @@ "id": 1, "name": "feedback", "displayName": "Feedback", - "description": "Controls the feedback amount (0% = single echo, 100% = infinite)", + "description": "Controls decaying feedback (0% = single echo, 100% = stable 0.85 loop gain, 15% decay per repeat)", "defaultValue": 0.3, "units": "%" }, diff --git a/vsts/echo/pubspec.lock b/vsts/echo/pubspec.lock index 2501147..007b834 100644 --- a/vsts/echo/pubspec.lock +++ b/vsts/echo/pubspec.lock @@ -5,18 +5,18 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: da0d9209ca76bde579f2da330aeb9df62b6319c834fa7baae052021b0462401f + sha256: "1b0e6a07425a3e460666e88bf1c949ccc7bb0116ad562ce94a1eca60fe820725" url: "https://pub.dev" source: hosted - version: "85.0.0" + version: "103.0.0" analyzer: dependency: transitive description: name: analyzer - sha256: "974859dc0ff5f37bc4313244b3218c791810d03ab3470a579580279ba971a48d" + sha256: "61c04d0c1bfed555c681ea079519933f071a5a026578ff73c4ff0df2d3462e5e" url: "https://pub.dev" source: hosted - version: "7.7.1" + version: "13.3.0" args: dependency: transitive description: @@ -29,10 +29,10 @@ packages: dependency: transitive description: name: async - sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 url: "https://pub.dev" source: hosted - version: "2.13.0" + version: "2.13.1" boolean_selector: dependency: transitive description: @@ -45,10 +45,10 @@ packages: dependency: transitive description: name: characters - sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b url: "https://pub.dev" source: hosted - version: "1.4.0" + version: "1.4.1" cli_config: dependency: transitive description: @@ -57,14 +57,22 @@ packages: url: "https://pub.dev" source: hosted version: "0.2.0" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: "89b8801ba49f8b593fbf2d3e59efd0f566c46cd4ba6837ae2610c72b52a0f899" + url: "https://pub.dev" + source: hosted + version: "0.6.0" clock: dependency: transitive description: name: clock - sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e url: "https://pub.dev" source: hosted - version: "1.1.2" + version: "1.1.3" collection: dependency: transitive description: @@ -85,18 +93,18 @@ packages: dependency: transitive description: name: coverage - sha256: "5da775aa218eaf2151c721b16c01c7676fbfdd99cebba2bf64e8b807a28ff94d" + sha256: ff89e37c19355194e279d26dafe8e4bece46c9ea63a30be4dc68214f5bc290d3 url: "https://pub.dev" source: hosted - version: "1.15.0" + version: "1.16.0" crypto: dependency: transitive description: name: crypto - sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855" + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf url: "https://pub.dev" source: hosted - version: "3.0.6" + version: "3.0.7" fake_async: dependency: transitive description: @@ -109,10 +117,10 @@ packages: dependency: transitive description: name: ffi - sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418" + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" url: "https://pub.dev" source: hosted - version: "2.1.4" + version: "2.2.0" file: dependency: transitive description: @@ -145,23 +153,23 @@ packages: path: "../../flutter_vst3" relative: true source: path - version: "0.1.0" + version: "0.1.2" frontend_server_client: dependency: transitive description: name: frontend_server_client - sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + sha256: "404dbf9bce29beafbe9dcb19219447b6f7d49900cd42b8d3b7af102b24508e25" url: "https://pub.dev" source: hosted - version: "4.0.0" + version: "4.1.0" glob: dependency: transitive description: name: glob - sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de + sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb" url: "https://pub.dev" source: hosted - version: "2.1.3" + version: "2.2.0" http_multi_server: dependency: transitive description: @@ -182,42 +190,34 @@ packages: dependency: transitive description: name: io - sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b - url: "https://pub.dev" - source: hosted - version: "1.0.5" - js: - dependency: transitive - description: - name: js - sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" + sha256: "2635216ca6a737e60de577ffa1a48a0bec76ca8a62917cfc1bb88c14c570646f" url: "https://pub.dev" source: hosted - version: "0.7.2" + version: "1.1.0" leak_tracker: dependency: transitive description: name: leak_tracker - sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0" + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" url: "https://pub.dev" source: hosted - version: "10.0.9" + version: "11.0.2" leak_tracker_flutter_testing: dependency: transitive description: name: leak_tracker_flutter_testing - sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" url: "https://pub.dev" source: hosted - version: "3.0.9" + version: "3.0.10" leak_tracker_testing: dependency: transitive description: name: leak_tracker_testing - sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" url: "https://pub.dev" source: hosted - version: "3.0.1" + version: "3.0.2" lints: dependency: transitive description: @@ -238,34 +238,34 @@ packages: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.20" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" url: "https://pub.dev" source: hosted - version: "0.11.1" + version: "0.13.0" meta: dependency: transitive description: name: meta - sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + sha256: c82594181e3312f3d0695fc95aaaf7758d75b8d4ae2bbecf223b9fd5109a059d url: "https://pub.dev" source: hosted - version: "1.16.0" + version: "1.18.3" mime: dependency: transitive description: name: mime - sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" + sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6 url: "https://pub.dev" source: hosted - version: "2.0.0" + version: "2.1.0" node_preamble: dependency: transitive description: @@ -294,26 +294,26 @@ packages: dependency: transitive description: name: pool - sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" + sha256: "4177f68c237ea2128d1bee66ac17b2ce05ba3dbaafcbdd54c5d40a39d0b6b11c" url: "https://pub.dev" source: hosted - version: "1.5.1" + version: "1.5.3" pub_semver: dependency: transitive description: name: pub_semver - sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" url: "https://pub.dev" source: hosted - version: "2.2.0" + version: "2.2.1" shelf: dependency: transitive description: name: shelf - sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + sha256: e75e9cf311d7fd712048038cc17c25199c38536c20330d53e7db058b543d5a48 url: "https://pub.dev" source: hosted - version: "1.4.2" + version: "1.4.3" shelf_packages_handler: dependency: transitive description: @@ -326,10 +326,10 @@ packages: dependency: transitive description: name: shelf_static - sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3 + sha256: "480504af9e5323899c5be26a4f6c2fc4437d50954d39842f0290f4ae733d57b4" url: "https://pub.dev" source: hosted - version: "1.1.3" + version: "1.2.0" shelf_web_socket: dependency: transitive description: @@ -355,26 +355,26 @@ packages: dependency: transitive description: name: source_maps - sha256: "190222579a448b03896e0ca6eca5998fa810fda630c1d65e2f78b3f638f54812" + sha256: "14c2945847669b44089bb1222f66873d7ff7103c58911917f2a63c5a62327898" url: "https://pub.dev" source: hosted - version: "0.10.13" + version: "0.10.14" source_span: dependency: transitive description: name: source_span - sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c" + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" url: "https://pub.dev" source: hosted - version: "1.10.1" + version: "1.10.2" stack_trace: dependency: transitive description: name: stack_trace - sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" url: "https://pub.dev" source: hosted - version: "1.12.1" + version: "1.12.2" stream_channel: dependency: transitive description: @@ -403,26 +403,26 @@ packages: dependency: "direct dev" description: name: test - sha256: "301b213cd241ca982e9ba50266bd3f5bd1ea33f1455554c5abb85d1be0e2d87e" + sha256: ca578dc12bb8b2f40b67b7d3bd2fac4f31c01a6ff7130a14e2597b919934507f url: "https://pub.dev" source: hosted - version: "1.25.15" + version: "1.31.1" test_api: dependency: transitive description: name: test_api - sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" url: "https://pub.dev" source: hosted - version: "0.7.4" + version: "0.7.12" test_core: dependency: transitive description: name: test_core - sha256: "84d17c3486c8dfdbe5e12a50c8ae176d15e2a771b96909a9442b40173649ccaa" + sha256: d2e98ec12998368dc59ddd47ab709f2cd55acd6b66dc7db764455a44082f4bc5 url: "https://pub.dev" source: hosted - version: "0.6.8" + version: "0.6.18" typed_data: dependency: transitive description: @@ -435,26 +435,26 @@ packages: dependency: transitive description: name: vector_math - sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + sha256: "1d774bbdf6b72a0b12122fc1560c9c2d2a67db5a4a4cc2bd8a5c990ab20e3188" url: "https://pub.dev" source: hosted - version: "2.1.4" + version: "2.4.0" vm_service: dependency: transitive description: name: vm_service - sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02 + sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78" url: "https://pub.dev" source: hosted - version: "15.0.0" + version: "15.4.0" watcher: dependency: transitive description: name: watcher - sha256: "0b7fd4a0bbc4b92641dbf20adfd7e3fd1398fe17102d94b674234563e110088a" + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" url: "https://pub.dev" source: hosted - version: "1.1.2" + version: "1.2.1" web: dependency: transitive description: @@ -491,10 +491,10 @@ packages: dependency: transitive description: name: yaml - sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea url: "https://pub.dev" source: hosted - version: "3.1.3" + version: "3.1.4" sdks: - dart: ">=3.7.0 <4.0.0" - flutter: ">=3.18.0-18.0.pre.54" + dart: ">=3.11.0 <4.0.0" + flutter: ">=3.27.0" diff --git a/vsts/echo/pubspec.yaml b/vsts/echo/pubspec.yaml index 283f7a9..5269400 100644 --- a/vsts/echo/pubspec.yaml +++ b/vsts/echo/pubspec.yaml @@ -4,8 +4,8 @@ version: 1.0.0 publish_to: 'none' environment: - sdk: '>=3.0.0 <4.0.0' - flutter: ">=3.0.0" + sdk: '>=3.6.0 <4.0.0' + flutter: '>=3.27.0' dependencies: flutter: diff --git a/vsts/echo/test/dsp_regression_test.dart b/vsts/echo/test/dsp_regression_test.dart new file mode 100644 index 0000000..f398b98 --- /dev/null +++ b/vsts/echo/test/dsp_regression_test.dart @@ -0,0 +1,98 @@ +import 'dart:math' as math; +import 'dart:typed_data'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:echo/src/echo_processor.dart'; + +import 'echo_test_harness.dart'; + +void main() { + for (final rate in [44100, 96000, 192000]) { + for (final delay in [0.0, 0.25, 1.0]) { + test('impulse timing $rate $delay', () { + final (dsp, params) = + echoDsp(rate.toDouble(), 512, delayTime: delay, feedback: 0); + final position = (rate * delay).round(); + final input = Float32List(position + 2)..[0] = 1; + final output = Float32List(input.length); + dsp.processStereo(input, Float32List(input.length), output, + Float32List(input.length), params); + expect(output[position], 1); + expect(output.where((x) => x != 0).length, 1); + }); + } + } + test('bypass records incoming audio and advances tail', () { + final (dsp, params) = echoDsp(1000, 512, delayTime: 0.01, feedback: 0); + params.bypass = 1; + final first = Float32List(5)..[0] = 1; + dsp.processStereo(first, Float32List(5), Float32List(5), Float32List(5), params); + params.bypass = 0; + final output = Float32List(10); + dsp.processStereo(Float32List(10), Float32List(10), output, + Float32List(10), params); + expect(output[5], 1); + expect(output.where((x) => x != 0).length, 1); + }); + + test('H23: saturation has continuous value and slope at the threshold', () { + const h = 1e-6; + for (final edge in [1.0, -1.0]) { + final below = EchoProcessor.softSaturate(edge * (1 - h)); + final above = EchoProcessor.softSaturate(edge * (1 + h)); + expect(above - below, closeTo(edge * 2 * h, 1e-9)); + } + expect(EchoProcessor.softSaturate(0.5), 0.5, reason: 'unity below the threshold'); + expect(EchoProcessor.softSaturate(1e9), lessThan(2.0)); + expect(EchoProcessor.softSaturate(-1e9), greaterThan(-2.0)); + }); + + test('H23: maximum feedback stays bounded over 10 seconds of loud input', () { + const rate = 48000.0; + const block = 480; + final (processor, parameters) = + echoDsp(rate, block, delayTime: 0.01, feedback: 1.0); + final input = Float32List(block)..fillRange(0, block, 1.0); + final outL = Float32List(block); + final outR = Float32List(block); + for (var n = 0; n < 1000; n++) { + processor.processStereo(input, input, outL, outR, parameters); + expect(outL.every((s) => s.isFinite && s.abs() < 10.0), isTrue); + } + }); + + test('moving the delay is smoothed, with no jump in the output', () { + const rate = 48000.0; + const block = 64; + final (processor, parameters) = + echoDsp(rate, block, delayTime: 0.1, feedback: 0.0); + final inputL = Float32List(block); + final outL = Float32List(block); + final outR = Float32List(block); + var phase = 0; + double? previous; + var largestStep = 0.0; + for (var n = 0; n < 3000; n++) { + parameters.delayTime = n < 1500 ? 0.1 : 0.2; + for (var i = 0; i < block; i++) { + inputL[i] = math.sin(2 * math.pi * 100 * phase++ / rate); + } + processor.processStereo(inputL, inputL, outL, outR, parameters); + for (var i = 0; n > 1000 && i < block; i++) { + final step = previous == null ? 0.0 : (outL[i] - previous).abs(); + largestStep = step > largestStep ? step : largestStep; + previous = outL[i]; + } + } + expect(largestStep, lessThan(0.08), reason: 'an unsmoothed jump is near 1'); + }); + + test('zero delay passes input through with no stale samples', () { + final (processor, parameters) = + echoDsp(48000, 64, delayTime: 0.0, feedback: 0.0); + final input = Float32List(64)..fillRange(0, 64, 0.5); + final outL = Float32List(64); + final outR = Float32List(64); + processor.processStereo(input, input, outL, outR, parameters); + expect(outL[10], closeTo(0.55, 1e-6), reason: 'L plus 10% of R crossfeed'); + }); +} diff --git a/vsts/echo/test/echo_test.dart b/vsts/echo/test/echo_test.dart index 247e2b2..63bf99b 100644 --- a/vsts/echo/test/echo_test.dart +++ b/vsts/echo/test/echo_test.dart @@ -1,128 +1,100 @@ +import 'dart:typed_data'; import 'package:test/test.dart'; -import '../lib/src/echo_processor.dart'; -import '../lib/src/echo_parameters.dart'; -import '../lib/src/echo_plugin.dart'; +import 'package:echo/src/echo_processor.dart'; +import 'package:echo/src/echo_parameters.dart'; + +import 'echo_test_harness.dart'; + +/// Processes [input] on both channels into a fresh output buffer. +Float32List _render( + EchoProcessor processor, EchoParameters parameters, Float32List input) { + final output = Float32List(input.length); + processor.processStereo(input, input, output, output, parameters); + return output; +} void main() { group('EchoProcessor', () { test('initializes correctly', () { final processor = EchoProcessor(); processor.initialize(44100.0, 512); - + expect(processor, isNotNull); }); - + test('processes stereo audio without crashing', () { - final processor = EchoProcessor(); - processor.initialize(44100.0, 512); - final parameters = EchoParameters(); - parameters.mix = 0.8; // High mix for obvious effect - parameters.feedback = 0.7; // High feedback - parameters.delayTime = 0.3; // Medium delay - - final inputL = List.filled(128, 0.5); - final inputR = List.filled(128, 0.3); - final outputL = List.filled(128, 0.0); - final outputR = List.filled(128, 0.0); - + final (processor, parameters) = echoDsp(44100.0, 512, + delayTime: 0.3, // Medium delay + feedback: 0.7, // High feedback + mix: 0.8); // High mix for obvious effect + + final inputL = Float32List(128)..fillRange(0, 128, 0.5); + final inputR = Float32List(128)..fillRange(0, 128, 0.3); + final outputL = Float32List(128); + final outputR = Float32List(128); + processor.processStereo(inputL, inputR, outputL, outputR, parameters); - + // Should produce some output (not all zeros due to dry signal) - expect(outputL.any((sample) => sample != 0.0), isTrue); - expect(outputR.any((sample) => sample != 0.0), isTrue); + expect(outputL, everyElement(closeTo(0.1, 1e-8))); + expect(outputR, everyElement(closeTo(0.06, 1e-8))); }); - - test('produces obvious echo effect', () { - final processor = EchoProcessor(); - processor.initialize(44100.0, 512); - final parameters = EchoParameters(); - parameters.mix = 0.9; // EXTREME mix for testing - parameters.feedback = 0.8; // High feedback - parameters.delayTime = 0.2; // Fast delay - + + test('preserves the exact dry block before the delay arrives', () { + final (processor, parameters) = echoDsp(44100.0, 512, + delayTime: 0.2, // Fast delay + feedback: 0.8, // High feedback + mix: 0.9); // EXTREME mix for testing + // Process silence first to clear buffers - final silence = List.filled(128, 0.0); - final output = List.filled(128, 0.0); + final silence = Float32List(128); + final output = Float32List(128); processor.processStereo(silence, silence, output, output, parameters); - + // Now process a short impulse - final impulse = List.filled(128, 0.0); + final impulse = Float32List(128); impulse[0] = 1.0; // Single sample impulse - final impulseOutput = List.filled(128, 0.0); - - processor.processStereo(impulse, impulse, impulseOutput, impulseOutput, parameters); - + final impulseOutput = Float32List(128); + + processor.processStereo( + impulse, impulse, impulseOutput, impulseOutput, parameters); + // Should have dry signal at start - expect(impulseOutput[0], greaterThan(0.0)); + expect(impulseOutput[0], closeTo(0.1, 1e-8)); + expect(impulseOutput.skip(1), everyElement(0.0)); }); - + test('can be reset', () { final processor = EchoProcessor(); processor.initialize(44100.0, 512); - + processor.reset(); - + // After reset, should still work final parameters = EchoParameters(); parameters.mix = 0.5; // Moderate settings - final input = List.filled(128, 0.1); - final output = List.filled(128, 0.0); + final input = Float32List(128)..fillRange(0, 128, 0.1); + final output = Float32List(128); processor.processStereo(input, input, output, output, parameters); - - expect(output.any((sample) => sample != 0.0), isTrue); - }); - }); - group('DartEchoPlugin', () { - test('initializes correctly', () { - final plugin = DartEchoPlugin(); - expect(plugin.initialize(), isTrue); + expect(output, everyElement(closeTo(0.05, 1e-8))); }); - - test('has correct plugin info', () { - final plugin = DartEchoPlugin(); - final info = plugin.pluginInfo; - - expect(info['name'], equals('Echo')); - expect(info['vendor'], equals('CF')); - expect(info['inputs'], equals(2)); - expect(info['outputs'], equals(2)); - expect(info['parameters'], equals(4)); // Now has 4 parameters - }); - - test('can process audio without crashing', () { - final plugin = DartEchoPlugin(); - plugin.initialize(); - plugin.setupProcessing(44100.0, 512); - plugin.setActive(true); - - final inputs = [ - List.filled(128, 0.5), - List.filled(128, 0.3) - ]; - final outputs = [ - List.filled(128, 0.0), - List.filled(128, 0.0) - ]; - - plugin.processAudio(inputs, outputs); - - // Should produce some output - expect(outputs[0].any((sample) => sample != 0.0), isTrue); - expect(outputs[1].any((sample) => sample != 0.0), isTrue); - }); - }); - - group('DartEchoFactory', () { - test('creates plugin instances', () { - final plugin = DartEchoFactory.createInstance(); - expect(plugin, isA()); - }); - - test('provides class info', () { - final info = DartEchoFactory.getClassInfo(); - expect(info['name'], equals('Echo')); - expect(info['classId'], equals('DartEcho')); + + test('delay automation cannot emit audio before either delay arrives', () { + final (processor, parameters) = echoDsp(44100.0, 512, + delayTime: 0.1, feedback: 0.5); + + final input = Float32List.fromList( + List.generate(512, (i) => (i % 32 == 0) ? 0.8 : 0.0), + ); + final output = _render(processor, parameters, input); + + // Change delayTime sharply + parameters.delayTime = 0.6; + final output2 = _render(processor, parameters, input); + + expect(output, everyElement(0.0)); + expect(output2, everyElement(0.0)); }); }); -} \ No newline at end of file +} diff --git a/vsts/echo/test/echo_test_harness.dart b/vsts/echo/test/echo_test_harness.dart new file mode 100644 index 0000000..a0d5a0c --- /dev/null +++ b/vsts/echo/test/echo_test_harness.dart @@ -0,0 +1,22 @@ +// Copyright (c) 2025 +// Shared DSP setup for the echo plugin tests. + +import 'package:echo/src/echo_parameters.dart'; +import 'package:echo/src/echo_processor.dart'; + +/// An echo running at [rate] Hz with [block]-sample blocks, the given delay +/// and feedback, and [mix] wet level. +(EchoProcessor, EchoParameters) echoDsp( + double rate, + int block, { + required double delayTime, + required double feedback, + double mix = 1, +}) { + final processor = EchoProcessor()..initialize(rate, block); + final parameters = EchoParameters() + ..delayTime = delayTime + ..feedback = feedback + ..mix = mix; + return (processor, parameters); +} diff --git a/vsts/echo/test/feedback_contract_test.dart b/vsts/echo/test/feedback_contract_test.dart new file mode 100644 index 0000000..5a79f89 --- /dev/null +++ b/vsts/echo/test/feedback_contract_test.dart @@ -0,0 +1,31 @@ +import 'dart:typed_data'; +import 'package:flutter_test/flutter_test.dart'; + +import 'echo_test_harness.dart'; + +(Float32List, Float32List) _render(double feedback) { + final (dsp, parameters) = echoDsp(1000, 128, delayTime: 0.01, feedback: feedback); + final input = Float32List(101)..[0] = 0.1; + final left = Float32List(101), right = Float32List(101); + dsp.processStereo(input, Float32List(101), left, right, parameters); + return (left, right); +} + +void _assertRepeats(double feedback) { + final (left, right) = _render(feedback); + var amplitude = Float32List.fromList([0.1])[0]; + for (var repeat = 1; repeat <= 10; repeat++) { + expect(left[repeat * 10], closeTo(amplitude, 1e-8)); + expect(right[repeat * 10], closeTo(amplitude * 0.1, 1e-8)); + amplitude *= feedback * 0.85; + } + expect(left[20] / left[10], closeTo(feedback * 0.85, 1e-7)); + expect(left.where((x) => x != 0).length, feedback == 0 ? 1 : 10); +} + +void main() { + for (final feedback in [0.0, 1.0]) { + test('quiet repeats at feedback $feedback retain capped decay', + () => _assertRepeats(feedback)); + } +} diff --git a/vsts/echo/test/parameter_contract_test.dart b/vsts/echo/test/parameter_contract_test.dart new file mode 100644 index 0000000..32bf013 --- /dev/null +++ b/vsts/echo/test/parameter_contract_test.dart @@ -0,0 +1,23 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:echo/src/echo_parameters.dart'; + +void _assertParameters() { + final parameters = EchoParameters(); + for (final (id, value) in [(0, 0.1), (1, 0.2), (2, 0.7), (3, 1.0)]) { + parameters.setParameter(id, value); + expect(parameters.getParameter(id), value); + } + expect(parameters.delayTime, 0.1); + expect(parameters.feedback, 0.2); + expect(parameters.mix, 0.7); + expect(parameters.bypass, 1); + parameters.setParameter(1, -2); + expect(parameters.feedback, 0); + parameters.setParameter(1, 2); + expect(parameters.feedback, 1); + expect(parameters.mix, 0.7); +} + +void main() { + test('each parameter routes and clamps independently', _assertParameters); +} diff --git a/vsts/echo/test/ui_regression_test.dart b/vsts/echo/test/ui_regression_test.dart new file mode 100644 index 0000000..91733fd --- /dev/null +++ b/vsts/echo/test/ui_regression_test.dart @@ -0,0 +1,219 @@ +import 'dart:ffi' hide Size; +import '../../../flutter_vst3/test/support/shared_memory_fixture.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_vst3/ui.dart'; +import 'package:echo/ui/echo_ui.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('flutter_vst3/parameters'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final calls = []; + var address = 0; + var fail = false; + setUp(() { + calls.clear(); + fail = false; + address = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + if (fail) throw PlatformException(code: 'host-failed'); + return switch (call.method) { + 'getInitialParameters' => {'0': 0.5, '1': 0.5, '2': 0.5}, + 'getSharedMemoryInfo' => {'address': address}, + _ => null, + }; + }); + }); + + Future host(String method) async { + await messenger.handlePlatformMessage( + channel.name, + const StandardMethodCodec().encodeMethodCall(MethodCall(method)), + (_) {}); + } + + test('physical parameter formatting', () { + expect(formatEchoParameter(0, 0), '0.0ms'); + expect(formatEchoParameter(0, 0.5), '500.0ms'); + expect(formatEchoParameter(0, 1), '1000.0ms'); + expect(formatEchoParameter(1, 0.25), '25.0%'); + expect(formatEchoParameter(2, 1), '100.0%'); + }); + + test('single sample waveform is finite', () { + final path = buildEchoWaveformPath([0.5], const Size(200, 100)); + final bounds = path.getBounds(); + expect(bounds.left.isFinite, isTrue); + expect(bounds.top.isFinite, isTrue); + expect(bounds.left, 0); + expect(bounds.top, 28); + }); + + testWidgets('one begin/set/end gesture per knob drag and bypass', + (tester) async { + await tester.pumpWidget(const MaterialApp(home: EchoUI())); + await tester.pump(); + calls.clear(); + final knob = find.descendant( + of: find.byType(RotaryKnob).first, matching: find.byType(CustomPaint)); + final gesture = await tester.startGesture(tester.getCenter(knob)); + await gesture.moveBy(const Offset(0, -25)); + await tester.pump(); + await gesture.moveBy(const Offset(0, -25)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + final edits = calls + .where( + (c) => ['beginEdit', 'setParameter', 'endEdit'].contains(c.method)) + .toList(); + expect(edits.first.method, 'beginEdit'); + expect(edits.last.method, 'endEdit'); + expect(edits.where((c) => c.method == 'beginEdit').length, 1); + expect(edits.where((c) => c.method == 'endEdit').length, 1); + expect(edits.sublist(1, edits.length - 1), isNotEmpty); + expect( + edits + .sublist(1, edits.length - 1) + .every((c) => c.method == 'setParameter'), + isTrue); + expect(edits.every((c) => (c.arguments as Map)['id'] == 0), isTrue); + calls.clear(); + await tester.ensureVisible(find.byType(Switch)); + await tester.tap(find.byType(Switch)); + await tester.pump(); + expect( + calls.map((c) => c.method), ['beginEdit', 'setParameter', 'endEdit']); + expect(calls.map((c) => (c.arguments as Map)['id']), [3, 3, 3]); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('a valid reader fetches only on attachment, a missing one on the bounded tick', + (tester) async { + final memory = allocateSharedMemoryFixture(); + addTearDown(() => freeSharedMemoryFixture(memory)); + memory.cast().value = vst3ShmMagic; + address = memory.address; + await host('onHostDetached'); + await host('onHostAttached'); + await tester.pumpWidget(const MaterialApp(home: EchoWaveformVisualizer())); + await tester.pump(); + int fetches() => + calls.where((c) => c.method == 'getSharedMemoryInfo').length; + expect(fetches(), 1); + VST3ParameterBinding.getInstance().notifyListeners(); + await tester.pump(const Duration(seconds: 2)); + expect(fetches(), 1); + memory.cast().value = 0; + address = 0; + await tester.pump(const Duration(milliseconds: 40)); + await tester.pump(); + expect(fetches(), 2); + await tester.pump(const Duration(seconds: 2)); + expect(fetches(), 4, + reason: 'a missing reader retries about once a second, bounded'); + await host('onHostDetached'); + await host('onHostAttached'); + await tester.pump(); + expect(fetches(), 5); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('an editor opened while inactive picks the wave up at ' + 'activation [TELEMETRY-RESTART-POLL] [TELEMETRY-SHM-INFO]', (tester) async { + final memory = allocateSharedMemoryFixture(); + addTearDown(() => freeSharedMemoryFixture(memory)); + address = 0; + await host('onHostDetached'); + await host('onHostAttached'); + await tester.pumpWidget(const MaterialApp(home: EchoWaveformVisualizer())); + await tester.pump(); + int fetches() => + calls.where((c) => c.method == 'getSharedMemoryInfo').length; + CustomPaint scope() => find + .descendant( + of: find.byType(EchoWaveformVisualizer), + matching: find.byType(CustomPaint)) + .evaluate() + .single + .widget as CustomPaint; + expect(fetches(), 1); + final flatPainter = scope().painter; + + memory.cast().value = vst3ShmMagic; + Pointer.fromAddress(memory.address + vst3OffsetNumSamples).value = 4; + Pointer.fromAddress(memory.address + vst3OffsetOutputL) + ..[0] = 0.5 + ..[1] = -0.5 + ..[2] = 0.5 + ..[3] = -0.5; + address = memory.address; + await tester.pump(const Duration(milliseconds: 1100)); + await tester.pump(); + expect(fetches(), 2, + reason: 'the missing reader is retried on the bounded tick'); + expect(identical(scope().painter, flatPainter), isFalse, + reason: 'the scope repaints with the block\'s samples'); + await tester.pumpWidget(const SizedBox()); + }); + testWidgets('the editor says when the DSP stops, and when it is back', + (tester) async { + const message = 'DSP stopped. Audio is silent until the plugin is re-enabled.'; + final memory = allocateSharedMemoryFixture(); + final restarted = allocateSharedMemoryFixture(); + addTearDown(() { + freeSharedMemoryFixture(memory); + freeSharedMemoryFixture(restarted); + }); + memory.cast().value = vst3ShmMagic; + restarted.cast().value = vst3ShmMagic; + address = memory.address; + await host('onHostDetached'); + await host('onHostAttached'); + await tester.pumpWidget(const MaterialApp(home: EchoUI())); + await tester.pump(); + expect(find.text(message), findsNothing); + int fetches() => + calls.where((c) => c.method == 'getSharedMemoryInfo').length; + + memory.cast().value = 0; + await tester.pump(const Duration(milliseconds: 40)); + await tester.pump(); + await tester.pump(); + expect(find.text(message), findsOneWidget); + + final before = fetches(); + await tester.pump(const Duration(seconds: 2)); + await tester.pump(); + expect(fetches() - before, inInclusiveRange(1, 3), + reason: 'looks for a new worker about once a second, not every frame'); + expect(find.text(message), findsOneWidget); + + address = restarted.address; + await tester.pump(const Duration(milliseconds: 1100)); + await tester.pump(); + await tester.pump(); + expect(find.text(message), findsNothing); + await tester.pumpWidget(const SizedBox()); + }); + + test('host channel failures propagate to callers', () async { + final binding = VST3ParameterBinding.getInstance(); + await binding.loadInitialParameters(); + fail = true; + await expectLater( + binding.loadInitialParameters(), throwsA(isA())); + await expectLater(binding.getAudioBufferReader(forceRefresh: true), + throwsA(isA())); + await expectLater( + binding.setParameter(0, 0.5), throwsA(isA())); + await binding.beginEdit(0); + await expectLater( + binding.setParameter(0, 0.6), throwsA(isA())); + await expectLater(binding.endEdit(0), throwsA(isA())); + }); +} diff --git a/vsts/echo/test/widget_test.dart b/vsts/echo/test/widget_test.dart new file mode 100644 index 0000000..382588a --- /dev/null +++ b/vsts/echo/test/widget_test.dart @@ -0,0 +1,13 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:echo/main.dart'; +import 'package:echo/ui/echo_ui.dart'; + +void main() { + testWidgets('EchoApp renders EchoUI and EchoWaveformVisualizer', + (WidgetTester tester) async { + await tester.pumpWidget(const EchoApp()); + expect(find.byType(EchoUI), findsOneWidget); + expect(find.byType(EchoWaveformVisualizer), findsOneWidget); + expect(find.text('Echo Effect'), findsOneWidget); + }); +} diff --git a/vsts/echo/windows/.gitignore b/vsts/echo/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/vsts/echo/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/vsts/echo/windows/CMakeLists.txt b/vsts/echo/windows/CMakeLists.txt new file mode 100644 index 0000000..ed39f9d --- /dev/null +++ b/vsts/echo/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(echo LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "echo") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/vsts/echo/windows/flutter/CMakeLists.txt b/vsts/echo/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/vsts/echo/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/vsts/echo/windows/flutter/generated_plugin_registrant.cc b/vsts/echo/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..8b6d468 --- /dev/null +++ b/vsts/echo/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/vsts/echo/windows/flutter/generated_plugin_registrant.h b/vsts/echo/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/vsts/echo/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/vsts/echo/windows/flutter/generated_plugins.cmake b/vsts/echo/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..b93c4c3 --- /dev/null +++ b/vsts/echo/windows/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/vsts/echo/windows/runner/CMakeLists.txt b/vsts/echo/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/vsts/echo/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/vsts/echo/windows/runner/Runner.rc b/vsts/echo/windows/runner/Runner.rc new file mode 100644 index 0000000..1cc5fea --- /dev/null +++ b/vsts/echo/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "echo" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "echo" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "echo.exe" "\0" + VALUE "ProductName", "echo" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/vsts/echo/windows/runner/flutter_window.cpp b/vsts/echo/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/vsts/echo/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/vsts/echo/windows/runner/flutter_window.h b/vsts/echo/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/vsts/echo/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/vsts/echo/windows/runner/main.cpp b/vsts/echo/windows/runner/main.cpp new file mode 100644 index 0000000..18599d1 --- /dev/null +++ b/vsts/echo/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"echo", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/vsts/echo/windows/runner/resource.h b/vsts/echo/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/vsts/echo/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/vsts/echo/windows/runner/resources/app_icon.ico b/vsts/echo/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/vsts/echo/windows/runner/resources/app_icon.ico differ diff --git a/vsts/echo/windows/runner/runner.exe.manifest b/vsts/echo/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/vsts/echo/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/vsts/echo/windows/runner/utils.cpp b/vsts/echo/windows/runner/utils.cpp new file mode 100644 index 0000000..3cb7146 --- /dev/null +++ b/vsts/echo/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(target_length) > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/vsts/echo/windows/runner/utils.h b/vsts/echo/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/vsts/echo/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/vsts/echo/windows/runner/win32_window.cpp b/vsts/echo/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/vsts/echo/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/vsts/echo/windows/runner/win32_window.h b/vsts/echo/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/vsts/echo/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ diff --git a/vsts/flutter_reverb/CMakeLists.txt b/vsts/flutter_reverb/CMakeLists.txt index 564669f..547cc47 100644 --- a/vsts/flutter_reverb/CMakeLists.txt +++ b/vsts/flutter_reverb/CMakeLists.txt @@ -1,23 +1,26 @@ cmake_minimum_required(VERSION 3.20) project(flutter_reverb_plugin VERSION 1.0.0 - LANGUAGES CXX) + LANGUAGES C CXX) +if(APPLE) + enable_language(OBJC OBJCXX) +endif() # Build the Flutter Reverb VST® 3 plugin using flutter_vst3 # This plugin uses pure Dart audio processing with Flutter UI via FFI bridge set(CMAKE_CXX_STANDARD 17) -# Set build type and debug flags -if(NOT CMAKE_BUILD_TYPE) - set(CMAKE_BUILD_TYPE Release) +# Set build type and debug/release flags across single- and multi-config generators +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE) endif() -if(CMAKE_BUILD_TYPE STREQUAL "Debug") - add_compile_definitions(_DEBUG) -else() - add_compile_definitions(NDEBUG RELEASE) -endif() +add_compile_definitions( + $<$:_DEBUG> + $<$>:NDEBUG> + $<$>:RELEASE=1> +) # Include the flutter_vst3 CMake helper include(../../flutter_vst3/native/cmake/VST3Bridge.cmake) diff --git a/vsts/flutter_reverb/Makefile b/vsts/flutter_reverb/Makefile new file mode 100644 index 0000000..da53ce9 --- /dev/null +++ b/vsts/flutter_reverb/Makefile @@ -0,0 +1,2 @@ +PLUGIN ?= flutter_reverb +include ../plugin.mk diff --git a/vsts/flutter_reverb/lib/flutter_reverb_processor_exe.dart b/vsts/flutter_reverb/lib/flutter_reverb_processor_exe.dart index 2a3c494..3413b15 100644 --- a/vsts/flutter_reverb/lib/flutter_reverb_processor_exe.dart +++ b/vsts/flutter_reverb/lib/flutter_reverb_processor_exe.dart @@ -1,79 +1,13 @@ -import 'dart:io'; -import 'dart:typed_data'; +import 'package:flutter_vst3/flutter_vst3.dart'; import 'src/reverb_processor.dart'; -const CMD_INIT = 0x01; -const CMD_PROCESS = 0x02; -const CMD_SET_PARAM = 0x03; -const CMD_TERMINATE = 0xFF; - -void main() async { - final processor = ReverbProcessor(); - - // CRITICAL: Set binary mode (only if stdin is a terminal) - try { - stdin.lineMode = false; - } catch (e) { - // Ignore error if stdin is not a terminal (e.g., when piped) - } - - // Main event loop - await for (final bytes in stdin) { - if (bytes.isEmpty) continue; - - final buffer = ByteData.view(Uint8List.fromList(bytes).buffer); - final command = buffer.getUint8(0); - - switch (command) { - case CMD_INIT: - final sampleRate = buffer.getFloat64(1, Endian.little); - processor.initialize(sampleRate, 512); - stdout.add([CMD_INIT]); // ACK - await stdout.flush(); - break; - - case CMD_PROCESS: - final numSamples = buffer.getInt32(1, Endian.little); - // Read interleaved stereo - final audioData = Float32List(numSamples * 2); - for (int i = 0; i < numSamples * 2; i++) { - audioData[i] = buffer.getFloat32(5 + i * 4, Endian.little); - } - - // Split to L/R - final inputL = List.generate(numSamples, - (i) => audioData[i * 2].toDouble()); - final inputR = List.generate(numSamples, - (i) => audioData[i * 2 + 1].toDouble()); - - final outputL = List.filled(numSamples, 0.0); - final outputR = List.filled(numSamples, 0.0); - - // PROCESS WITH REVERB DART CODE! - processor.processStereo(inputL, inputR, outputL, outputR); - - // Send back interleaved - final response = ByteData(1 + numSamples * 8); - response.setUint8(0, CMD_PROCESS); - for (int i = 0; i < numSamples; i++) { - response.setFloat32(1 + i * 8, outputL[i], Endian.little); - response.setFloat32(1 + i * 8 + 4, outputR[i], Endian.little); - } - - stdout.add(response.buffer.asUint8List()); - await stdout.flush(); - break; - - case CMD_SET_PARAM: - final paramId = buffer.getInt32(1, Endian.little); - final value = buffer.getFloat64(5, Endian.little); - processor.setParameter(paramId, value); - stdout.add([CMD_SET_PARAM]); // ACK - await stdout.flush(); - break; - - case CMD_TERMINATE: - exit(0); - } - } +/// Entry point for the Flutter Reverb processor standalone executable. +/// +/// Uses preallocated zero-copy shared memory and POSIX semaphores to receive +/// audio buffers and parameter changes directly from the C++ VST3 plugin wrapper. +void main(List args) { + runVst3SharedMemoryProcessor( + args: args, + processor: ReverbProcessor(), + ); } \ No newline at end of file diff --git a/vsts/flutter_reverb/lib/src/reverb_processor.dart b/vsts/flutter_reverb/lib/src/reverb_processor.dart index 0a9d2e2..7e4a5d3 100644 --- a/vsts/flutter_reverb/lib/src/reverb_processor.dart +++ b/vsts/flutter_reverb/lib/src/reverb_processor.dart @@ -1,14 +1,16 @@ +import 'package:flutter_vst3/flutter_vst3.dart'; +import 'dart:typed_data'; import '../flutter_reverb_parameters.dart'; /// Comb filter implementation for reverb class CombFilter { - final List _buffer; + final Float32List _buffer; int _bufferIndex = 0; double _feedback = 0.5; double _dampening = 0.5; double _filterStore = 0.0; - CombFilter(int bufferSize) : _buffer = List.filled(bufferSize, 0.0); + CombFilter(int bufferSize) : _buffer = Float32List(bufferSize); double process(double input) { final output = _buffer[_bufferIndex]; @@ -31,11 +33,11 @@ class CombFilter { /// Allpass filter implementation for reverb class AllpassFilter { - final List _buffer; + final Float32List _buffer; int _bufferIndex = 0; final double _feedback = 0.5; - AllpassFilter(int bufferSize) : _buffer = List.filled(bufferSize, 0.0); + AllpassFilter(int bufferSize) : _buffer = Float32List(bufferSize); double process(double input) { final bufout = _buffer[_bufferIndex]; @@ -53,7 +55,7 @@ class AllpassFilter { } /// Pure Dart reverb processor using Freeverb algorithm -class ReverbProcessor { +class ReverbProcessor implements Vst3WorkerProcessor { static const int _kNumCombs = 8; static const int _kNumAllpass = 4; @@ -79,41 +81,39 @@ class ReverbProcessor { void _initializeFilters() { final scale = _sampleRate / 44100.0; - + _clearFilterLists(); + _initCombFilters(scale); + _initAllpassFilters(scale); + _updateCombFilterParameters(); + } + + void _clearFilterLists() { _combFiltersL.clear(); _combFiltersR.clear(); _allpassFiltersL.clear(); _allpassFiltersR.clear(); - - // Initialize comb filters - for (int i = 0; i < _kNumCombs; i++) { - final bufferSizeL = (_combTuning[i] * scale).round(); - final bufferSizeR = ((_combTuning[i] + 23) * scale).round(); - - _combFiltersL.add(CombFilter(bufferSizeL)); - _combFiltersR.add(CombFilter(bufferSizeR)); + } + + void _initCombFilters(double scale) { + for (var i = 0; i < _kNumCombs; i++) { + _combFiltersL.add(CombFilter((_combTuning[i] * scale).round())); + _combFiltersR.add(CombFilter(((_combTuning[i] + 23) * scale).round())); } - - // Initialize allpass filters - for (int i = 0; i < _kNumAllpass; i++) { - final bufferSizeL = (_allpassTuning[i] * scale).round(); - final bufferSizeR = ((_allpassTuning[i] + 23) * scale).round(); - - _allpassFiltersL.add(AllpassFilter(bufferSizeL)); - _allpassFiltersR.add(AllpassFilter(bufferSizeR)); + } + + void _initAllpassFilters(double scale) { + for (var i = 0; i < _kNumAllpass; i++) { + _allpassFiltersL.add(AllpassFilter((_allpassTuning[i] * scale).round())); + _allpassFiltersR.add(AllpassFilter(((_allpassTuning[i] + 23) * scale).round())); } - - _updateCombFilterParameters(); } void _updateCombFilterParameters() { final feedback = _parameters.roomSize * 0.28 + 0.7; - for (final filter in _combFiltersL) { filter.setFeedback(feedback); filter.setDampening(_parameters.damping); } - for (final filter in _combFiltersR) { filter.setFeedback(feedback); filter.setDampening(_parameters.damping); @@ -123,7 +123,6 @@ class ReverbProcessor { /// Set parameter value void setParameter(int paramId, double value) { _parameters.setParameter(paramId, value); - if (_initialized && (paramId == ReverbParameters.kRoomSizeParam || paramId == ReverbParameters.kDampingParam)) { _updateCombFilterParameters(); @@ -136,11 +135,11 @@ class ReverbProcessor { } /// Process stereo audio block - void processStereo(List inputL, List inputR, - List outputL, List outputR) { + void processStereo(Float32List inputL, Float32List inputR, + Float32List outputL, Float32List outputR) { if (!_initialized || inputL.length != inputR.length || outputL.length != inputL.length || outputR.length != inputL.length) { - return; + throw StateError("Reverb is uninitialized or buffer lengths differ"); } for (int i = 0; i < inputL.length; i++) { @@ -150,7 +149,6 @@ class ReverbProcessor { // Process through comb filters double combOutL = 0.0; double combOutR = 0.0; - for (int j = 0; j < _kNumCombs; j++) { combOutL += _combFiltersL[j].process(monoIn); combOutR += _combFiltersR[j].process(monoIn); diff --git a/vsts/flutter_reverb/pubspec.lock b/vsts/flutter_reverb/pubspec.lock index fc59341..0a78e04 100644 --- a/vsts/flutter_reverb/pubspec.lock +++ b/vsts/flutter_reverb/pubspec.lock @@ -5,18 +5,18 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: da0d9209ca76bde579f2da330aeb9df62b6319c834fa7baae052021b0462401f + sha256: "1b0e6a07425a3e460666e88bf1c949ccc7bb0116ad562ce94a1eca60fe820725" url: "https://pub.dev" source: hosted - version: "85.0.0" + version: "103.0.0" analyzer: dependency: transitive description: name: analyzer - sha256: "974859dc0ff5f37bc4313244b3218c791810d03ab3470a579580279ba971a48d" + sha256: "61c04d0c1bfed555c681ea079519933f071a5a026578ff73c4ff0df2d3462e5e" url: "https://pub.dev" source: hosted - version: "7.7.1" + version: "13.3.0" args: dependency: transitive description: @@ -45,10 +45,10 @@ packages: dependency: transitive description: name: characters - sha256: f71061c654a3380576a52b451dd5532377954cf9dbd272a78fc8479606670803 + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b url: "https://pub.dev" source: hosted - version: "1.4.0" + version: "1.4.1" cli_config: dependency: transitive description: @@ -145,7 +145,7 @@ packages: path: "../../flutter_vst3" relative: true source: path - version: "0.1.0" + version: "0.1.2" frontend_server_client: dependency: transitive description: @@ -186,38 +186,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.5" - js: - dependency: transitive - description: - name: js - sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" - url: "https://pub.dev" - source: hosted - version: "0.7.2" leak_tracker: dependency: transitive description: name: leak_tracker - sha256: "6bb818ecbdffe216e81182c2f0714a2e62b593f4a4f13098713ff1685dfb6ab0" + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" url: "https://pub.dev" source: hosted - version: "10.0.9" + version: "11.0.2" leak_tracker_flutter_testing: dependency: transitive description: name: leak_tracker_flutter_testing - sha256: f8b613e7e6a13ec79cfdc0e97638fddb3ab848452eff057653abd3edba760573 + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" url: "https://pub.dev" source: hosted - version: "3.0.9" + version: "3.0.10" leak_tracker_testing: dependency: transitive description: name: leak_tracker_testing - sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" url: "https://pub.dev" source: hosted - version: "3.0.1" + version: "3.0.2" lints: dependency: transitive description: @@ -238,26 +230,26 @@ packages: dependency: transitive description: name: matcher - sha256: dc58c723c3c24bf8d3e2d3ad3f2f9d7bd9cf43ec6feaa64181775e60190153f2 + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" url: "https://pub.dev" source: hosted - version: "0.12.17" + version: "0.12.20" material_color_utilities: dependency: transitive description: name: material_color_utilities - sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" url: "https://pub.dev" source: hosted - version: "0.11.1" + version: "0.13.0" meta: dependency: transitive description: name: meta - sha256: e3641ec5d63ebf0d9b41bd43201a66e3fc79a65db5f61fc181f04cd27aab950c + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" url: "https://pub.dev" source: hosted - version: "1.16.0" + version: "1.19.0" mime: dependency: transitive description: @@ -403,26 +395,26 @@ packages: dependency: "direct dev" description: name: test - sha256: "301b213cd241ca982e9ba50266bd3f5bd1ea33f1455554c5abb85d1be0e2d87e" + sha256: ca578dc12bb8b2f40b67b7d3bd2fac4f31c01a6ff7130a14e2597b919934507f url: "https://pub.dev" source: hosted - version: "1.25.15" + version: "1.31.1" test_api: dependency: transitive description: name: test_api - sha256: fb31f383e2ee25fbbfe06b40fe21e1e458d14080e3c67e7ba0acfde4df4e0bbd + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" url: "https://pub.dev" source: hosted - version: "0.7.4" + version: "0.7.12" test_core: dependency: transitive description: name: test_core - sha256: "84d17c3486c8dfdbe5e12a50c8ae176d15e2a771b96909a9442b40173649ccaa" + sha256: d2e98ec12998368dc59ddd47ab709f2cd55acd6b66dc7db764455a44082f4bc5 url: "https://pub.dev" source: hosted - version: "0.6.8" + version: "0.6.18" typed_data: dependency: transitive description: @@ -435,10 +427,10 @@ packages: dependency: transitive description: name: vector_math - sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d" url: "https://pub.dev" source: hosted - version: "2.1.4" + version: "2.4.3" vm_service: dependency: transitive description: @@ -496,5 +488,5 @@ packages: source: hosted version: "3.1.3" sdks: - dart: ">=3.7.0 <4.0.0" - flutter: ">=3.18.0-18.0.pre.54" + dart: ">=3.11.0 <4.0.0" + flutter: ">=3.27.0" diff --git a/vsts/flutter_reverb/pubspec.yaml b/vsts/flutter_reverb/pubspec.yaml index 4d1d647..743da67 100644 --- a/vsts/flutter_reverb/pubspec.yaml +++ b/vsts/flutter_reverb/pubspec.yaml @@ -4,8 +4,8 @@ version: 1.0.0 publish_to: 'none' environment: - sdk: '>=3.0.0 <4.0.0' - flutter: ">=3.0.0" + sdk: '>=3.6.0 <4.0.0' + flutter: '>=3.27.0' dependencies: flutter: diff --git a/vsts/flutter_reverb/test/reverb_test.dart b/vsts/flutter_reverb/test/reverb_test.dart index e5d6a0b..cf6a018 100644 --- a/vsts/flutter_reverb/test/reverb_test.dart +++ b/vsts/flutter_reverb/test/reverb_test.dart @@ -1,95 +1,104 @@ +import 'package:flutter_test/flutter_test.dart'; import 'dart:math' as math; -import '../lib/flutter_reverb_parameters.dart'; -import '../lib/src/reverb_processor.dart'; +import 'dart:typed_data'; +import 'package:flutter_reverb/flutter_reverb_parameters.dart'; +import 'package:flutter_reverb/src/reverb_processor.dart'; /// Test suite for Flutter Reverb VST3 plugin components void main() { - print('=== Flutter Reverb Test Suite ===\n'); - - _testReverbParameters(); - _testReverbProcessor(); - - print('🎉 All tests passed! Flutter Reverb components are working correctly.'); + test('invalid buffers throw and reset clears tail', () { + final dsp = ReverbProcessor(); + final zero = Float32List(4096); + final output = Float32List(4096); + expect(() => dsp.processStereo(zero, zero, output, output), throwsStateError); + dsp.initialize(44100, 4096); + expect(() => dsp.processStereo(zero, Float32List(1), output, output), throwsStateError); + final impulse = Float32List(4096)..[0] = 1; + dsp.processStereo(impulse, impulse, output, Float32List(4096)); + expect(output.any((x) => x != 0), isTrue); + dsp.reset(); + dsp.processStereo(zero, zero, output, Float32List(4096)); + expect(output, everyElement(0)); + }); + test('parameters' , _testReverbParameters); + test('processor', _testReverbProcessor); } void _testReverbParameters() { - print('Testing ReverbParameters...'); final params = ReverbParameters(); // Test default values - assert(params.roomSize == 0.5, 'Default room size should be 0.5'); - assert(params.damping == 0.5, 'Default damping should be 0.5'); - assert(params.wetLevel == 0.3, 'Default wet level should be 0.3'); - assert(params.dryLevel == 0.7, 'Default dry level should be 0.7'); + expect(params.roomSize == 0.5, isTrue, reason: 'Default room size should be 0.5'); + expect(params.damping == 0.5, isTrue, reason: 'Default damping should be 0.5'); + expect(params.wetLevel == 0.3, isTrue, reason: 'Default wet level should be 0.3'); + expect(params.dryLevel == 0.7, isTrue, reason: 'Default dry level should be 0.7'); // Test parameter setting and getting params.setParameter(ReverbParameters.kRoomSizeParam, 0.8); - assert(params.getParameter(ReverbParameters.kRoomSizeParam) == 0.8, 'Room size should be 0.8'); + expect(params.getParameter(ReverbParameters.kRoomSizeParam) == 0.8, isTrue, reason: 'Room size should be 0.8'); // Test clamping params.setParameter(ReverbParameters.kWetLevelParam, 1.5); - assert(params.getParameter(ReverbParameters.kWetLevelParam) == 1.0, 'Wet level should be clamped to 1.0'); + expect(params.getParameter(ReverbParameters.kWetLevelParam) == 1.0, isTrue, reason: 'Wet level should be clamped to 1.0'); params.setParameter(ReverbParameters.kDryLevelParam, -0.5); - assert(params.getParameter(ReverbParameters.kDryLevelParam) == 0.0, 'Dry level should be clamped to 0.0'); + expect(params.getParameter(ReverbParameters.kDryLevelParam) == 0.0, isTrue, reason: 'Dry level should be clamped to 0.0'); // Test parameter names - assert(params.getParameterName(ReverbParameters.kRoomSizeParam) == 'Room Size', 'Room size name should match'); - assert(params.getParameterName(ReverbParameters.kDampingParam) == 'Damping', 'Damping name should match'); + expect(params.getParameterName(ReverbParameters.kRoomSizeParam) == 'Room Size', isTrue, reason: 'Room size name should match'); + expect(params.getParameterName(ReverbParameters.kDampingParam) == 'Damping', isTrue, reason: 'Damping name should match'); // Test parameter units - assert(params.getParameterUnits(ReverbParameters.kWetLevelParam) == '%', 'Wet level units should be %'); + expect(params.getParameterUnits(ReverbParameters.kWetLevelParam) == '%', isTrue, reason: 'Wet level units should be %'); // Test parameter constants - assert(ReverbParameters.kRoomSizeParam == 0, 'Room size param ID should be 0'); - assert(ReverbParameters.kDampingParam == 1, 'Damping param ID should be 1'); - assert(ReverbParameters.kWetLevelParam == 2, 'Wet level param ID should be 2'); - assert(ReverbParameters.kDryLevelParam == 3, 'Dry level param ID should be 3'); - assert(ReverbParameters.numParameters == 4, 'Should have 4 parameters'); + expect(ReverbParameters.kRoomSizeParam == 0, isTrue, reason: 'Room size param ID should be 0'); + expect(ReverbParameters.kDampingParam == 1, isTrue, reason: 'Damping param ID should be 1'); + expect(ReverbParameters.kWetLevelParam == 2, isTrue, reason: 'Wet level param ID should be 2'); + expect(ReverbParameters.kDryLevelParam == 3, isTrue, reason: 'Dry level param ID should be 3'); + expect(ReverbParameters.numParameters == 4, isTrue, reason: 'Should have 4 parameters'); - print('✓ ReverbParameters tests passed\n'); } void _testReverbProcessor() { - print('Testing ReverbProcessor...'); final processor = ReverbProcessor(); processor.initialize(44100.0, 512); // Test parameter setting processor.setParameter(ReverbParameters.kRoomSizeParam, 0.7); - assert(processor.getParameter(ReverbParameters.kRoomSizeParam) == 0.7, 'Processor should store parameter values'); + expect(processor.getParameter(ReverbParameters.kRoomSizeParam) == 0.7, isTrue, reason: 'Processor should store parameter values'); // Test different parameter values processor.setParameter(ReverbParameters.kDampingParam, 0.9); processor.setParameter(ReverbParameters.kWetLevelParam, 0.4); processor.setParameter(ReverbParameters.kDryLevelParam, 0.6); - assert(processor.getParameter(ReverbParameters.kDampingParam) == 0.9, 'Damping should be set'); - assert(processor.getParameter(ReverbParameters.kWetLevelParam) == 0.4, 'Wet level should be set'); - assert(processor.getParameter(ReverbParameters.kDryLevelParam) == 0.6, 'Dry level should be set'); + expect(processor.getParameter(ReverbParameters.kDampingParam) == 0.9, isTrue, reason: 'Damping should be set'); + expect(processor.getParameter(ReverbParameters.kWetLevelParam) == 0.4, isTrue, reason: 'Wet level should be set'); + expect(processor.getParameter(ReverbParameters.kDryLevelParam) == 0.6, isTrue, reason: 'Dry level should be set'); // Test audio processing const numSamples = 100; - final inputL = List.generate(numSamples, (i) => math.sin(i * 0.1) * 0.5); - final inputR = List.generate(numSamples, (i) => math.cos(i * 0.1) * 0.5); - final outputL = List.filled(numSamples, 0.0); - final outputR = List.filled(numSamples, 0.0); + final inputL = Float32List.fromList(List.generate(numSamples, (i) => math.sin(i * 0.1) * 0.5)); + final inputR = Float32List.fromList(List.generate(numSamples, (i) => math.cos(i * 0.1) * 0.5)); + final outputL = Float32List(numSamples); + final outputR = Float32List(numSamples); processor.processStereo(inputL, inputR, outputL, outputR); // Verify output is not just zeros (reverb should produce some output) final hasNonZeroL = outputL.any((sample) => sample.abs() > 0.001); final hasNonZeroR = outputR.any((sample) => sample.abs() > 0.001); - assert(hasNonZeroL, 'Processor should produce non-zero left output'); - assert(hasNonZeroR, 'Processor should produce non-zero right output'); + expect(hasNonZeroL, isTrue, reason: 'Processor should produce non-zero left output'); + expect(hasNonZeroR, isTrue, reason: 'Processor should produce non-zero right output'); // Test silence processing (should still work) - final silentL = List.filled(numSamples, 0.0); - final silentR = List.filled(numSamples, 0.0); - final outputSilentL = List.filled(numSamples, 0.0); - final outputSilentR = List.filled(numSamples, 0.0); + final silentL = Float32List(numSamples); + final silentR = Float32List(numSamples); + final outputSilentL = Float32List(numSamples); + final outputSilentR = Float32List(numSamples); processor.processStereo(silentL, silentR, outputSilentL, outputSilentR); // With silence, output should be very quiet but might not be exactly zero due to reverb tail @@ -100,5 +109,4 @@ void _testReverbProcessor() { // Test disposal processor.dispose(); - print('✓ ReverbProcessor tests passed\n'); } \ No newline at end of file diff --git a/vsts/flutter_reverb/test/wet_contract_test.dart b/vsts/flutter_reverb/test/wet_contract_test.dart new file mode 100644 index 0000000..9fc8532 --- /dev/null +++ b/vsts/flutter_reverb/test/wet_contract_test.dart @@ -0,0 +1,95 @@ +import 'dart:typed_data'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_reverb/src/reverb_processor.dart'; + +(Float32List, Float32List) _render(double rate, double room, double damping) { + final dsp = ReverbProcessor()..initialize(rate, 512); + for (final entry in {0: room, 1: damping, 2: 1.0, 3: 0.0}.entries) { + dsp.setParameter(entry.key, entry.value); + } + final input = Float32List(100000)..[0] = 1; + final left = Float32List(input.length), right = Float32List(input.length); + dsp.processStereo(input, input, left, right); + return (left, right); +} + +double _energy(Float32List samples, int start) => + samples.skip(start).fold(0.0, (sum, x) => sum + x * x); + +double _differenceEnergy(Float32List samples) { + var sum = 0.0; + for (var i = 30000; i < samples.length; i++) { + final difference = samples[i] - samples[i - 1]; + sum += difference * difference; + } + return sum; +} + +void _landmarks(double rate) { + final (left, right) = _render(rate, 0, 0); + final scale = rate / 44100; + for (final (samples, spread) in [(left, 0), (right, 23)]) { + final onset = ((1116 + spread) * scale).round(); + expect(samples.take(onset).toList(), List.filled(onset, 0.0)); + // Four allpasses each invert the direct impulse: (-1)^4 = 1. + expect(samples[onset], 1.0); + expect(samples[((1188 + spread) * scale).round()], 1.0); + // The shortest allpass's first delayed impulse has opposite sign. + expect(samples[onset + ((225 + spread) * scale).round()], -1.0); + } +} + +void _roomDecay() { + final small = _render(44100, 0, 0.5); + final large = _render(44100, 1, 0.5); + for (final (a, b) in [(small.$1, large.$1), (small.$2, large.$2)]) { + expect(_energy(b, 50000), greaterThan(_energy(a, 50000) * 100)); + expect(_energy(a, 50000), greaterThan(0)); + } +} + +void _dampingDecay() { + final bright = _render(44100, 0.8, 0); + final dark = _render(44100, 0.8, 0.8); + for (final (a, b) in [(bright.$1, dark.$1), (bright.$2, dark.$2)]) { + expect(_differenceEnergy(b), lessThan(_differenceEnergy(a) * 0.1)); + expect(_differenceEnergy(b), greaterThan(0)); + } +} + +void _allpassReference() { + final filter = AllpassFilter(2); + // H(z) = -1 + z^-2 / (1 - 0.5 z^-2). + final actual = [for (final x in [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) filter.process(x)]; + expect(actual, [-1, 0, 1, 0, 0.5, 0, 0.25]); + filter.reset(); + expect(filter.process(0), 0); +} + +void _combReference() { + for (final room in [0.0, 1.0]) { + for (final damping in [0.0, 0.75]) { + final feedback = 0.7 + room * 0.28; + final comb = CombFilter(4) + ..setFeedback(feedback) + ..setDampening(damping); + final actual = [for (var i = 0; i < 11; i++) comb.process(i == 0 ? 1 : 0)]; + final first = feedback * (1 - damping); + final expected = [0, 0, 0, 0, 1, 0, 0, 0, + first, first * damping, first * damping * damping]; + for (var i = 0; i < expected.length; i++) { + expect(actual[i], closeTo(expected[i], 1e-7)); + } + } + } +} + +void main() { + for (final rate in [44100.0, 96000.0]) { + test('wet only stereo landmarks at $rate', () => _landmarks(rate)); + } + test('large room retains more late energy on both channels', _roomDecay); + test('damping absorbs high frequency late tail on both channels', _dampingDecay); + test('allpass independent two sample delay reference', _allpassReference); + test('comb feedback and damping independent reference', _combReference); +} diff --git a/vsts/plugin.mk b/vsts/plugin.mk new file mode 100644 index 0000000..fa11e5d --- /dev/null +++ b/vsts/plugin.mk @@ -0,0 +1,26 @@ +# Targets every plugin has. Set PLUGIN first. +PACKAGE_TOOL ?= flutter +BUNDLE ?= build/VST3/Release/$(PLUGIN).vst3 +include ../../mk/package.mk +.DEFAULT_GOAL := build +.PHONY: build deploy _framework-deps _clean + +## build: Build this plugin's .vst3 bundle. +build: _deps + cmake -S . -B build -DCMAKE_BUILD_TYPE=Release + cmake --build build --parallel + +## deploy: Build this plugin, then copy it to the folder VST3 hosts scan. +deploy: build + test -d "$(BUNDLE)" + case "$$(uname)" in Darwin) dest="$$HOME/Library/Audio/Plug-Ins/VST3";; Linux) dest="$$HOME/.vst3";; MINGW*|MSYS*|CYGWIN*) dest="$$LOCALAPPDATA/Programs/Common/VST3";; *) echo 'Unsupported platform' >&2; exit 1;; esac; \ + mkdir -p "$$dest" && \ + rm -rf "$$dest/$(PLUGIN).vst3" && \ + cp -R "$(BUNDLE)" "$$dest/" && \ + echo "Deployed $(PLUGIN) to $$dest" + +_deps: _framework-deps +_framework-deps: + $(MAKE) -C ../../flutter_vst3 _deps +_clean: + rm -rf build