diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a05f5aee..134af71b 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -4,10 +4,12 @@ on: push: env: - CACHE_VERSION: 19 + CACHE_VERSION: 31 + CARDINAL_UNDER_WINE: 1 DEBIAN_FRONTEND: noninteractive HOMEBREW_NO_AUTO_UPDATE: 1 LIBGL_ALWAYS_SOFTWARE: 'true' + WITH_LTO: 'false' jobs: linux-arm64: @@ -22,17 +24,6 @@ jobs: with: path: | ~/PawPawBuilds - */*.a - bin/*.*/*.so - bin/*.vst3/Contents/*/*.so - bin/Cardinal - build/Cardinal - build/CardinalFX - build/CardinalSynth - build/plugins - build/rack - carla/build - dpf/build src/Rack/dep/bin src/Rack/dep/include src/Rack/dep/lib @@ -42,7 +33,7 @@ jobs: src/Rack/dep/libsamplerate-0.1.9 src/Rack/dep/speexdsp-SpeexDSP-1.2rc3 src/Rack/dep/zstd-1.4.5 - key: linux-arm64-v${{ env.CACHE_VERSION }} + key: linux-arm64-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Fix GitHub's mess run: | sudo rm -f /etc/apt/sources.list.d/microsoft-prod.list @@ -57,16 +48,24 @@ jobs: echo "deb [arch=arm64] http://ports.ubuntu.com/ubuntu-ports focal-backports main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/ports-arm64.list sudo apt-get update -qq sudo apt-get install -yqq g++-aarch64-linux-gnu libdbus-1-dev:arm64 libgl1-mesa-dev:arm64 libglib2.0-dev:arm64 libx11-dev:arm64 libxcursor-dev:arm64 libxext-dev:arm64 libxrandr-dev:arm64 qemu-user-static + - name: Set up ccache + uses: hendrikmuhs/ccache-action@v1.2 + with: + key: ccache-linux-arm64-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Build extra dependencies env: PKG_CONFIG_PATH: /usr/lib/aarch64-linux-gnu/pkgconfig run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" ./deps/PawPaw/bootstrap-cardinal.sh linux-aarch64 && ./deps/PawPaw/.cleanup.sh linux-aarch64 - name: Build linux arm64 cross-compiled run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" pushd deps/PawPaw; source local.env linux-aarch64; popd make features - make CIBUILD=true NOOPT=true WITH_LTO=true -j $(nproc) + make CIBUILD=true NOOPT=true WITH_LTO=${{ env.WITH_LTO }} -j $(nproc) make unzipfx - name: Set sha8 (non-release) if: startsWith(github.ref, 'refs/tags/') != true @@ -81,7 +80,7 @@ jobs: run: echo "::set-output name=sha8::$(echo ${{ steps.slug1.outputs.sha8 || steps.slug2.outputs.sha8 }})" - name: Pack binaries run: | - tar -c -h --hard-dereference -z -f ${{ github.event.repository.name }}-linux-arm64-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }}.tar.gz -C bin $(ls bin | grep -e lv2 -e vst) ../Cardinal + tar -c -h --hard-dereference -z -f ${{ github.event.repository.name }}-linux-arm64-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }}.tar.gz -C bin $(ls bin | grep -e lv2 -e vst) ../CardinalJACK ../CardinalNative - uses: actions/upload-artifact@v2 with: name: ${{ github.event.repository.name }}-linux-arm64-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }} @@ -109,17 +108,6 @@ jobs: with: path: | ~/PawPawBuilds - */*.a - bin/*.*/*.so - bin/*.vst3/Contents/*/*.so - bin/Cardinal - build/Cardinal - build/CardinalFX - build/CardinalSynth - build/plugins - build/rack - carla/build - dpf/build src/Rack/dep/bin src/Rack/dep/include src/Rack/dep/lib @@ -129,7 +117,7 @@ jobs: src/Rack/dep/libsamplerate-0.1.9 src/Rack/dep/speexdsp-SpeexDSP-1.2rc3 src/Rack/dep/zstd-1.4.5 - key: linux-armhf-v${{ env.CACHE_VERSION }} + key: linux-armhf-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Fix GitHub's mess run: | sudo rm -f /etc/apt/sources.list.d/microsoft-prod.list @@ -144,16 +132,24 @@ jobs: echo "deb [arch=armhf] http://ports.ubuntu.com/ubuntu-ports focal-backports main restricted universe multiverse" | sudo tee -a /etc/apt/sources.list.d/ports-armhf.list sudo apt-get update -qq sudo apt-get install -yqq g++-arm-linux-gnueabihf libdbus-1-dev:armhf libgl1-mesa-dev:armhf libglib2.0-dev:armhf libx11-dev:armhf libxcursor-dev:armhf libxext-dev:armhf libxrandr-dev:armhf qemu-user-static + - name: Set up ccache + uses: hendrikmuhs/ccache-action@v1.2 + with: + key: ccache-linux-armhf-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Build extra dependencies env: PKG_CONFIG_PATH: /usr/lib/arm-linux-gnueabihf/pkgconfig run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" ./deps/PawPaw/bootstrap-cardinal.sh linux-armhf && ./deps/PawPaw/.cleanup.sh linux-armhf - name: Build linux armhf cross-compiled run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" pushd deps/PawPaw; source local.env linux-armhf; popd make features - make CIBUILD=true NOOPT=true WITH_LTO=true -j $(nproc) + make CIBUILD=true NOOPT=true WITH_LTO=${{ env.WITH_LTO }} -j $(nproc) make unzipfx - name: Set sha8 (non-release) if: startsWith(github.ref, 'refs/tags/') != true @@ -168,7 +164,7 @@ jobs: run: echo "::set-output name=sha8::$(echo ${{ steps.slug1.outputs.sha8 || steps.slug2.outputs.sha8 }})" - name: Pack binaries run: | - tar -c -h --hard-dereference -z -f ${{ github.event.repository.name }}-linux-armhf-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }}.tar.gz -C bin $(ls bin | grep -e lv2 -e vst) ../Cardinal + tar -c -h --hard-dereference -z -f ${{ github.event.repository.name }}-linux-armhf-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }}.tar.gz -C bin $(ls bin | grep -e lv2 -e vst) ../CardinalJACK ../CardinalNative - uses: actions/upload-artifact@v2 with: name: ${{ github.event.repository.name }}-linux-armhf-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }} @@ -196,17 +192,6 @@ jobs: with: path: | ~/PawPawBuilds - */*.a - bin/*.*/*.so - bin/*.vst3/Contents/*/*.so - bin/Cardinal - build/Cardinal - build/CardinalFX - build/CardinalSynth - build/plugins - build/rack - carla/build - dpf/build src/Rack/dep/bin src/Rack/dep/include src/Rack/dep/lib @@ -216,7 +201,7 @@ jobs: src/Rack/dep/libsamplerate-0.1.9 src/Rack/dep/speexdsp-SpeexDSP-1.2rc3 src/Rack/dep/zstd-1.4.5 - key: linux-i686-v${{ env.CACHE_VERSION }} + key: linux-i686-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Fix GitHub's mess run: | sudo rm -f /etc/apt/sources.list.d/microsoft-prod.list @@ -227,16 +212,24 @@ jobs: sudo dpkg --add-architecture i386 sudo apt-get update -qq sudo apt-get install -yqq g++-multilib libdbus-1-dev:i386 libgl1-mesa-dev:i386 libglib2.0-dev:i386 libx11-dev:i386 libxcursor-dev:i386 libxext-dev:i386 libxrandr-dev:i386 + - name: Set up ccache + uses: hendrikmuhs/ccache-action@v1.2 + with: + key: ccache-linux-i686-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Build extra dependencies env: PKG_CONFIG_PATH: /usr/lib/i386-linux-gnu/pkgconfig run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" ./deps/PawPaw/bootstrap-cardinal.sh linux-i686 && ./deps/PawPaw/.cleanup.sh linux-i686 - name: Build linux i686 run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" pushd deps/PawPaw; source local.env linux-i686; popd make features - make CIBUILD=true NOOPT=true WITH_LTO=true -j $(nproc) + make CIBUILD=true NOOPT=true WITH_LTO=${{ env.WITH_LTO }} -j $(nproc) make unzipfx - name: Set sha8 (non-release) if: startsWith(github.ref, 'refs/tags/') != true @@ -251,7 +244,7 @@ jobs: run: echo "::set-output name=sha8::$(echo ${{ steps.slug1.outputs.sha8 || steps.slug2.outputs.sha8 }})" - name: Pack binaries run: | - tar -c -h --hard-dereference -z -f ${{ github.event.repository.name }}-linux-i686-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }}.tar.gz -C bin $(ls bin | grep -e lv2 -e vst) ../Cardinal + tar -c -h --hard-dereference -z -f ${{ github.event.repository.name }}-linux-i686-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }}.tar.gz -C bin $(ls bin | grep -e lv2 -e vst) ../CardinalJACK ../CardinalNative - uses: actions/upload-artifact@v2 with: name: ${{ github.event.repository.name }}-linux-i686-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }} @@ -279,17 +272,6 @@ jobs: with: path: | ~/PawPawBuilds - */*.a - bin/*.*/*.so - bin/*.vst3/Contents/*/*.so - bin/Cardinal - build/Cardinal - build/CardinalFX - build/CardinalSynth - build/plugins - build/rack - carla/build - dpf/build src/Rack/dep/bin src/Rack/dep/include src/Rack/dep/lib @@ -299,19 +281,27 @@ jobs: src/Rack/dep/libsamplerate-0.1.9 src/Rack/dep/speexdsp-SpeexDSP-1.2rc3 src/Rack/dep/zstd-1.4.5 - key: linux-x86_64-v${{ env.CACHE_VERSION }} + key: linux-x86_64-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Set up dependencies run: | sudo apt-get update -qq sudo apt-get install -yqq libdbus-1-dev libgl1-mesa-dev libglib2.0-dev libx11-dev libxcursor-dev libxext-dev libxrandr-dev + - name: Set up ccache + uses: hendrikmuhs/ccache-action@v1.2 + with: + key: ccache-linux-x86_64-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Build extra dependencies run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" ./deps/PawPaw/bootstrap-cardinal.sh linux && ./deps/PawPaw/.cleanup.sh linux - name: Build linux x86_64 run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" pushd deps/PawPaw; source local.env linux; popd make features - make CIBUILD=true NOOPT=true WITH_LTO=true -j $(nproc) + make CIBUILD=true NOOPT=true WITH_LTO=${{ env.WITH_LTO }} -j $(nproc) make unzipfx - name: Set sha8 (non-release) if: startsWith(github.ref, 'refs/tags/') != true @@ -326,7 +316,7 @@ jobs: run: echo "::set-output name=sha8::$(echo ${{ steps.slug1.outputs.sha8 || steps.slug2.outputs.sha8 }})" - name: Pack binaries run: | - tar -c -h --hard-dereference -z -f ${{ github.event.repository.name }}-linux-x86_64-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }}.tar.gz -C bin $(ls bin | grep -e lv2 -e vst) ../Cardinal + tar -c -h --hard-dereference -z -f ${{ github.event.repository.name }}-linux-x86_64-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }}.tar.gz -C bin $(ls bin | grep -e lv2 -e vst) ../CardinalJACK ../CardinalNative - uses: actions/upload-artifact@v2 with: name: ${{ github.event.repository.name }}-linux-x86_64-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }} @@ -402,7 +392,7 @@ jobs: make SYSDEPS=true -j $(nproc) macos-intel: - runs-on: macos-10.15 + runs-on: macos-11 steps: - uses: actions/checkout@v2 with: @@ -413,18 +403,6 @@ jobs: with: path: | ~/PawPawBuilds - */*.a - bin/*.*/*.dylib - bin/*.*/Contents/MacOS/* - bin/Cardinal - build/Cardinal - build/CardinalFX - build/CardinalSynth - build/plugins - build/rack - carla/build - dpf/build - jucewrapper/build src/Rack/dep/bin src/Rack/dep/include src/Rack/dep/lib @@ -434,24 +412,37 @@ jobs: src/Rack/dep/libsamplerate-0.1.9 src/Rack/dep/speexdsp-SpeexDSP-1.2rc3 src/Rack/dep/zstd-1.4.5 - key: macos-intel-v${{ env.CACHE_VERSION }} + key: macos-intel-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} + - name: Set up ccache + uses: hendrikmuhs/ccache-action@v1.2 + with: + key: ccache-macos-intel-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Build extra dependencies run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/local/opt/ccache/libexec:${PATH}" ./deps/PawPaw/bootstrap-cardinal.sh macos && ./deps/PawPaw/.cleanup.sh macos - name: Build macOS intel (base) run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/local/opt/ccache/libexec:${PATH}" pushd deps/PawPaw; source local.env macos; popd make features - make CIBUILD=true NOOPT=true WITH_LTO=true -j $(sysctl -n hw.logicalcpu) + make CIBUILD=true NOOPT=true WITH_LTO=${{ env.WITH_LTO }} -j $(sysctl -n hw.logicalcpu) - name: Build macOS intel (AU using juce) + env: + MACOSX_DEPLOYMENT_TARGET: '10.8' run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi pushd deps/PawPaw; source local.env macos; popd - git clone --depth=1 -b master https://github.com/juce-framework/JUCE.git jucewrapper/JUCE + git clone --depth=1 -b 6.1.6 https://github.com/juce-framework/JUCE.git jucewrapper/JUCE sed -i -e 's/kAudioUnitProperty_SupportsMPE/kAudioUnitProperty_ignore_SupportsMPE/' jucewrapper/JUCE/modules/juce_audio_processors/format_types/juce_AudioUnitPluginFormat.h mkdir -p jucewrapper/build - pushd jucewrapper/build; cmake -DCMAKE_OSX_ARCHITECTURES=x86_64 -DCMAKE_OSX_DEPLOYMENT_TARGET=10.8 -DCMAKE_BUILD_TYPE=Release .. && make -j $(sysctl -n hw.logicalcpu); popd + pushd jucewrapper/build; cmake -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_OSX_ARCHITECTURES=x86_64 -DCMAKE_OSX_DEPLOYMENT_TARGET=10.8 -DCMAKE_OSX_SYSROOT="macosx" -DCMAKE_BUILD_TYPE=Release .. && make VERBOSE=1 -j $(sysctl -n hw.logicalcpu); popd mv jucewrapper/build/*_artefacts/Release/AU/*.component bin/ - name: Build macOS intel (packaging) + env: + MACOS_ARCHS: 'x86_64' run: | pushd deps/PawPaw; source local.env macos; popd ./utils/create-macos-installer.sh @@ -485,7 +476,7 @@ jobs: ${{ github.event.repository.name }}-*.pkg macos-universal: - runs-on: macos-10.15 + runs-on: macos-11 steps: - uses: actions/checkout@v2 with: @@ -496,18 +487,6 @@ jobs: with: path: | ~/PawPawBuilds - */*.a - bin/*.*/*.dylib - bin/*.*/Contents/MacOS/* - bin/Cardinal - build/Cardinal - build/CardinalFX - build/CardinalSynth - build/plugins - build/rack - carla/build - dpf/build - jucewrapper/build src/Rack/dep/bin src/Rack/dep/include src/Rack/dep/lib @@ -517,27 +496,36 @@ jobs: src/Rack/dep/libsamplerate-0.1.9 src/Rack/dep/speexdsp-SpeexDSP-1.2rc3 src/Rack/dep/zstd-1.4.5 - key: macos-universal-v${{ env.CACHE_VERSION }} - - name: Fix up Xcode - run: | - sudo rm -Rf /Library/Developer/CommandLineTools/SDKs/* - sudo xcode-select -s "/Applications/Xcode_12.3.app" + key: macos-universal-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} + - name: Set up ccache + uses: hendrikmuhs/ccache-action@v1.2 + with: + key: ccache-macos-universal-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Build extra dependencies run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/local/opt/ccache/libexec:${PATH}" ./deps/PawPaw/bootstrap-cardinal.sh macos-universal && ./deps/PawPaw/.cleanup.sh macos-universal - name: Build macOS universal (base) run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/local/opt/ccache/libexec:${PATH}" pushd deps/PawPaw; source local.env macos-universal; popd make features - make CIBUILD=true NOOPT=true WITH_LTO=true -j $(sysctl -n hw.logicalcpu) + make CIBUILD=true NOOPT=true WITH_LTO=${{ env.WITH_LTO }} -j $(sysctl -n hw.logicalcpu) - name: Build macOS universal (AU using juce) + env: + MACOSX_DEPLOYMENT_TARGET: '10.12' run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi pushd deps/PawPaw; source local.env macos-universal; popd - git clone --depth=1 -b master https://github.com/juce-framework/JUCE.git jucewrapper/JUCE + git clone --depth=1 -b 6.1.6 https://github.com/juce-framework/JUCE.git jucewrapper/JUCE mkdir -p jucewrapper/build - pushd jucewrapper/build; cmake -DCMAKE_OSX_ARCHITECTURES='arm64;x86_64' -DCMAKE_OSX_DEPLOYMENT_TARGET=10.12 -DCMAKE_BUILD_TYPE=Release .. && make -j $(sysctl -n hw.logicalcpu); popd + pushd jucewrapper/build; cmake -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_OSX_ARCHITECTURES='arm64;x86_64' -DCMAKE_OSX_DEPLOYMENT_TARGET=10.12 -DCMAKE_OSX_SYSROOT="macosx" -DCMAKE_BUILD_TYPE=Release .. && make VERBOSE=1 -j $(sysctl -n hw.logicalcpu); popd mv jucewrapper/build/*_artefacts/Release/AU/*.component bin/ - name: Build macOS universal (packaging) + env: + MACOS_ARCHS: 'arm64,x86_64' run: | pushd deps/PawPaw; source local.env macos-universal; popd ./utils/create-macos-installer.sh @@ -582,7 +570,7 @@ jobs: with: path: | ~/mod-workdir - key: modduo-static-v${{ env.CACHE_VERSION }} + key: modduo-static-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Set up dependencies run: | sudo apt-get update -qq @@ -596,7 +584,7 @@ jobs: $(pwd)/deps/mod-plugin-builder/bootstrap.sh modduo-static minimal && $(pwd)/deps/mod-plugin-builder/.clean-install.sh modduo-static - name: Build for modduo run: | - make modduo HEADLESS=true WITH_LTO=true MODDUO=true -j $(nproc) + make modduo HEADLESS=true WITH_LTO=${{ env.WITH_LTO }} MODDUO=true -j $(nproc) - name: Set sha8 id: slug run: echo "::set-output name=sha8::$(echo ${{ github.sha }} | cut -c1-8)" @@ -621,7 +609,7 @@ jobs: with: path: | ~/mod-workdir - key: modduox-v${{ env.CACHE_VERSION }} + key: modduox-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Set up dependencies run: | sudo apt-get update -qq @@ -635,7 +623,7 @@ jobs: $(pwd)/deps/mod-plugin-builder/bootstrap.sh modduox-static minimal && $(pwd)/deps/mod-plugin-builder/.clean-install.sh modduox-static - name: Build for modduox run: | - make modduox HEADLESS=true WITH_LTO=true -j $(nproc) + make modduox HEADLESS=true WITH_LTO=${{ env.WITH_LTO }} -j $(nproc) - name: Set sha8 id: slug run: echo "::set-output name=sha8::$(echo ${{ github.sha }} | cut -c1-8)" @@ -660,7 +648,7 @@ jobs: with: path: | ~/mod-workdir - key: moddwarf-v${{ env.CACHE_VERSION }} + key: moddwarf-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Set up dependencies run: | sudo apt-get update -qq @@ -674,7 +662,7 @@ jobs: $(pwd)/deps/mod-plugin-builder/bootstrap.sh moddwarf minimal && $(pwd)/deps/mod-plugin-builder/.clean-install.sh moddwarf - name: Build for moddwarf run: | - make moddwarf HEADLESS=true WITH_LTO=true -j $(nproc) + make moddwarf HEADLESS=true WITH_LTO=${{ env.WITH_LTO }} -j $(nproc) - name: Set sha8 id: slug run: echo "::set-output name=sha8::$(echo ${{ github.sha }} | cut -c1-8)" @@ -687,6 +675,138 @@ jobs: path: | *.tar.gz + wasm: + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v2 + with: + submodules: recursive + - name: Set up cache + id: cache + uses: actions/cache@v2 + with: + path: | + ~/PawPawBuilds + src/Rack/dep/bin + src/Rack/dep/include + src/Rack/dep/lib + src/Rack/dep/share + src/Rack/dep/jansson-2.12 + src/Rack/dep/libarchive-3.4.3 + src/Rack/dep/libsamplerate-0.1.9 + src/Rack/dep/speexdsp-SpeexDSP-1.2rc3 + src/Rack/dep/zstd-1.4.5 + key: wasm-v${{ env.CACHE_VERSION }} + - name: Set up dependencies + run: | + [ -e ~/PawPawBuilds/emsdk ] || git clone https://github.com/emscripten-core/emsdk.git ~/PawPawBuilds/emsdk + cd ~/PawPawBuilds/emsdk && ./emsdk install latest && ./emsdk activate latest + - name: Build extra dependencies + run: | + source ~/PawPawBuilds/emsdk/emsdk_env.sh + ./deps/PawPaw/bootstrap-cardinal.sh wasm && ./deps/PawPaw/.cleanup.sh wasm + - name: Build wasm cross-compiled + run: | + source ~/PawPawBuilds/emsdk/emsdk_env.sh + pushd deps/PawPaw; source local.env wasm; popd + make features + make CIBUILD=true NOOPT=true USE_GLES2=true -j $(nproc) + - name: Set sha8 (non-release) + if: startsWith(github.ref, 'refs/tags/') != true + id: slug1 + run: echo "::set-output name=sha8::$(echo ${{ github.sha }} | cut -c1-8)" + - name: Set sha8 (release) + if: startsWith(github.ref, 'refs/tags/') + id: slug2 + run: echo "::set-output name=sha8::$(echo ${{ github.ref_name }})" + - name: Set sha8 + id: slug + run: echo "::set-output name=sha8::$(echo ${{ steps.slug1.outputs.sha8 || steps.slug2.outputs.sha8 }})" + - name: Pack binaries + run: | + cd bin; zip -r -9 ../${{ github.event.repository.name }}-wasm-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }}.zip $(ls *.html *.data *.js *.wasm) + - uses: actions/upload-artifact@v2 + with: + name: ${{ github.event.repository.name }}-wasm-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }} + path: | + *.zip + - uses: softprops/action-gh-release@v1 + if: startsWith(github.ref, 'refs/tags/') + with: + tag_name: ${{ github.ref_name }} + name: ${{ github.ref_name }} + draft: false + prerelease: false + files: | + *.zip + + wasm-mini: + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v2 + with: + submodules: recursive + - name: Set up cache + id: cache + uses: actions/cache@v2 + with: + path: | + ~/emsdk + src/Rack/dep/bin + src/Rack/dep/include + src/Rack/dep/lib + src/Rack/dep/share + src/Rack/dep/jansson-2.12 + src/Rack/dep/libarchive-3.4.3 + src/Rack/dep/libsamplerate-0.1.9 + src/Rack/dep/speexdsp-SpeexDSP-1.2rc3 + src/Rack/dep/zstd-1.4.5 + key: wasm-mini-v${{ env.CACHE_VERSION }} + - name: Set up dependencies + run: | + [ -e ~/emsdk ] || git clone https://github.com/emscripten-core/emsdk.git ~/emsdk + cd ~/emsdk && ./emsdk install latest && ./emsdk activate latest + - name: Build wasm-mini cross-compiled + env: + AR: emar + CC: emcc + CXX: em++ + NM: emnm + RANLIB: emranlib + STRIP: emstrip + run: | + source ~/emsdk/emsdk_env.sh + make features + make CIBUILD=true NOPLUGINS=true STATIC_BUILD=true USE_GLES2=true -j $(nproc) + - name: Set sha8 (non-release) + if: startsWith(github.ref, 'refs/tags/') != true + id: slug1 + run: echo "::set-output name=sha8::$(echo ${{ github.sha }} | cut -c1-8)" + - name: Set sha8 (release) + if: startsWith(github.ref, 'refs/tags/') + id: slug2 + run: echo "::set-output name=sha8::$(echo ${{ github.ref_name }})" + - name: Set sha8 + id: slug + run: echo "::set-output name=sha8::$(echo ${{ steps.slug1.outputs.sha8 || steps.slug2.outputs.sha8 }})" + - name: Pack binaries + run: | + cd bin; zip -r -9 ../${{ github.event.repository.name }}-wasm-mini-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }}.zip $(ls *.html *.data *.js *.wasm) + - uses: actions/upload-artifact@v2 + with: + name: ${{ github.event.repository.name }}-wasm-mini-${{ github.event.pull_request.number || steps.slug.outputs.sha8 }} + path: | + *.zip + - uses: softprops/action-gh-release@v1 + if: startsWith(github.ref, 'refs/tags/') + with: + tag_name: ${{ github.ref_name }} + name: ${{ github.ref_name }} + draft: false + prerelease: false + files: | + *.zip + win32: runs-on: ubuntu-20.04 steps: @@ -699,17 +819,6 @@ jobs: with: path: | ~/PawPawBuilds - */*.a - bin/*.*/*.dll - bin/*.vst3/Contents/*/*.vst3 - bin/Cardinal.exe - build/Cardinal - build/CardinalFX - build/CardinalSynth - build/plugins - build/rack - carla/build - dpf/build src/Rack/dep/bin src/Rack/dep/include src/Rack/dep/lib @@ -719,29 +828,40 @@ jobs: src/Rack/dep/libsamplerate-0.1.9 src/Rack/dep/speexdsp-SpeexDSP-1.2rc3 src/Rack/dep/zstd-1.4.5 - key: win32-v${{ env.CACHE_VERSION }} + key: win32-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Fix GitHub's mess run: | sudo rm -f /etc/apt/sources.list.d/microsoft-prod.list sudo apt-get update -qq - sudo apt-get install -yqq --allow-downgrades libpcre2-8-0/focal libpcre2-16-0/focal libpcre2-32-0/focal libpcre2-posix2/focal + sudo apt-get install -yqq --allow-downgrades libgd3/focal libpcre2-8-0/focal libpcre2-16-0/focal libpcre2-32-0/focal libpcre2-posix2/focal + sudo apt-get purge -yqq libmono* moby* mono* php* libgdiplus libpcre2-posix3 libzip4 - name: Set up dependencies run: | sudo dpkg --add-architecture i386 sudo apt-get update -qq sudo apt-get install -yqq binutils-mingw-w64-i686 g++-mingw-w64-i686 mingw-w64 wine-stable:i386 qttools5-dev qttools5-dev-tools xvfb + - name: Set up ccache + uses: hendrikmuhs/ccache-action@v1.2 + with: + key: ccache-win32-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Build extra dependencies run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" ./deps/PawPaw/bootstrap-cardinal.sh win32 && ./deps/PawPaw/.cleanup.sh win32 - name: Build win32 cross-compiled (base) run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" pushd deps/PawPaw; source local.env win32; popd make features - make CIBUILD=true NOOPT=true WITH_LTO=true -j $(nproc) + make CIBUILD=true NOOPT=true WITH_LTO=${{ env.WITH_LTO }} -j $(nproc) - name: Build win64 cross-compiled (carla) run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" pushd deps/PawPaw; source local.env win32; popd - make -C carla CARLA_BACKEND_NAMESPACE=Cardinal EXTERNAL_PLUGINS=true HAVE_FLUIDSYNTH=false HAVE_ZYN_DEPS=false HAVE_ZYN_UI_DEPS=false HAVE_PYQT=true HAVE_QT5=true HAVE_QT5PKG=true STATIC_PLUGIN_TARGET=true USING_JUCE=false USING_JUCE_GUI_EXTRA=false -j $(nproc) + make -C carla CARLA_BACKEND_NAMESPACE=Cardinal EXTERNAL_PLUGINS=true HAVE_FLUIDSYNTH=false HAVE_ZYN_DEPS=false HAVE_ZYN_UI_DEPS=false HAVE_PYQT=true HAVE_QT5=true HAVE_QT5PKG=true STATIC_PLUGIN_TARGET=true USING_CUSTOM_DPF=true CUSTOM_DPF_PATH=$(pwd)/dpf -j $(nproc) make -C carla EMBED_TARGET=true TESTING=true dist make -C carla EMBED_TARGET=true TESTING=true dist - name: Build win64 cross-compiled (packaging) @@ -791,17 +911,6 @@ jobs: with: path: | ~/PawPawBuilds - */*.a - bin/*.*/*.dll - bin/*.vst3/Contents/*/*.vst3 - bin/Cardinal.exe - build/Cardinal - build/CardinalFX - build/CardinalSynth - build/plugins - build/rack - carla/build - dpf/build src/Rack/dep/bin src/Rack/dep/include src/Rack/dep/lib @@ -811,29 +920,40 @@ jobs: src/Rack/dep/libsamplerate-0.1.9 src/Rack/dep/speexdsp-SpeexDSP-1.2rc3 src/Rack/dep/zstd-1.4.5 - key: win64-v${{ env.CACHE_VERSION }} + key: win64-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Fix GitHub's mess run: | sudo rm -f /etc/apt/sources.list.d/microsoft-prod.list sudo apt-get update -qq - sudo apt-get install -yqq --allow-downgrades libpcre2-8-0/focal libpcre2-16-0/focal libpcre2-32-0/focal libpcre2-posix2/focal + sudo apt-get install -yqq --allow-downgrades libgd3/focal libpcre2-8-0/focal libpcre2-16-0/focal libpcre2-32-0/focal libpcre2-posix2/focal + sudo apt-get purge -yqq libmono* moby* mono* php* libgdiplus libpcre2-posix3 libzip4 - name: Set up dependencies run: | sudo dpkg --add-architecture i386 sudo apt-get update -qq sudo apt-get install -yqq binutils-mingw-w64-x86-64 g++-mingw-w64-x86-64 mingw-w64 wine-stable qttools5-dev qttools5-dev-tools xvfb + - name: Set up ccache + uses: hendrikmuhs/ccache-action@v1.2 + with: + key: ccache-win64-v${{ env.CACHE_VERSION }}-${{ env.WITH_LTO }} - name: Build extra dependencies run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" ./deps/PawPaw/bootstrap-cardinal.sh win64 && ./deps/PawPaw/.cleanup.sh win64 - name: Build win64 cross-compiled (base) run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" pushd deps/PawPaw; source local.env win64; popd make features - make CIBUILD=true NOOPT=true WITH_LTO=true -j $(nproc) + make CIBUILD=true NOOPT=true WITH_LTO=${{ env.WITH_LTO }} -j $(nproc) - name: Build win64 cross-compiled (carla) run: | + if [ "${{ env.WITH_LTO }}" != "true" ]; then export PAWPAW_SKIP_LTO=1; fi + export PATH="/usr/lib/ccache:${PATH}" pushd deps/PawPaw; source local.env win64; popd - make -C carla CARLA_BACKEND_NAMESPACE=Cardinal EXTERNAL_PLUGINS=true HAVE_FLUIDSYNTH=false HAVE_ZYN_DEPS=false HAVE_ZYN_UI_DEPS=false HAVE_PYQT=true HAVE_QT5=true HAVE_QT5PKG=true STATIC_PLUGIN_TARGET=true USING_JUCE=false USING_JUCE_GUI_EXTRA=false all win32r -j $(nproc) + make -C carla CARLA_BACKEND_NAMESPACE=Cardinal EXTERNAL_PLUGINS=true HAVE_FLUIDSYNTH=false HAVE_ZYN_DEPS=false HAVE_ZYN_UI_DEPS=false HAVE_PYQT=true HAVE_QT5=true HAVE_QT5PKG=true STATIC_PLUGIN_TARGET=true USING_CUSTOM_DPF=true CUSTOM_DPF_PATH=$(pwd)/dpf all win32r -j $(nproc) make -C carla EMBED_TARGET=true TESTING=true dist make -C carla EMBED_TARGET=true TESTING=true dist - name: Build win64 cross-compiled (packaging) @@ -921,24 +1041,54 @@ jobs: - uses: actions/checkout@v2 with: submodules: recursive + - name: Set up cache + id: cache + uses: actions/cache@v2 + with: + path: | + src/Rack/dep/bin + src/Rack/dep/include + src/Rack/dep/lib + src/Rack/dep/share + src/Rack/dep/jansson-2.12 + src/Rack/dep/libarchive-3.4.3 + src/Rack/dep/libsamplerate-0.1.9 + src/Rack/dep/speexdsp-SpeexDSP-1.2rc3 + src/Rack/dep/zstd-1.4.5 + key: pluginval-v${{ env.CACHE_VERSION }} - name: Set up dependencies run: | # custom repos - wget https://launchpad.net/~kxstudio-debian/+archive/kxstudio/+files/kxstudio-repos_10.0.3_all.deb - sudo dpkg -i kxstudio-repos_10.0.3_all.deb + wget https://launchpad.net/~kxstudio-debian/+archive/kxstudio/+files/kxstudio-repos_11.1.0_all.deb + sudo dpkg -i kxstudio-repos_11.1.0_all.deb sudo apt-get update -qq # build-deps - sudo apt-get install -yqq liblo-dev + sudo apt-get install -yqq libdbus-1-dev libgl1-mesa-dev liblo-dev libx11-dev libxcursor-dev libxext-dev libxrandr-dev # runtime testing - sudo apt-get install -yqq carla-git lilv-utils lv2-dev lv2lint valgrind + sudo apt-get install -yqq carla-git lilv-utils lv2-dev lv2lint kxstudio-lv2-extensions mod-lv2-extensions valgrind xvfb + - name: Set up ccache + uses: hendrikmuhs/ccache-action@v1.2 + with: + key: ccache-pluginval-v${{ env.CACHE_VERSION }} - name: Build Cardinal env: CFLAGS: -g - CXXFLAGS: -g -DDPF_ABORT_ON_ERROR + CXXFLAGS: -g -DDPF_ABORT_ON_ERROR -DDPF_RUNTIME_TESTING LDFLAGS: -static-libgcc -static-libstdc++ run: | - make HEADLESS=true features - make HEADLESS=true NOOPT=true NOPLUGINS=true STATIC_BUILD=true SKIP_STRIPPING=true -j $(nproc) + export PATH="/usr/lib/ccache:${PATH}" + make features + make NOOPT=true SKIP_STRIPPING=true -j $(nproc) + - name: Run Cardinal self-tests + run: | + # --exit-on-first-error=yes + xvfb-run valgrind \ + --gen-suppressions=all \ + --error-exitcode=255 \ + --leak-check=no \ + --track-origins=yes \ + --suppressions=./dpf/utils/valgrind-dpf.supp \ + ./bin/Cardinal selftest - name: Validate LV2 ttl syntax run: | lv2_validate \ @@ -954,13 +1104,13 @@ jobs: cp -r bin/CardinalFX.lv2 bin/CardinalSynth.lv2 \ /usr/lib/lv2/{atom,buf-size,core,data-access,kx-control-input-port-change-request,kx-programs,instance-access,midi,mod,parameters,port-groups,port-props,options,patch,presets,resize-port,state,time,ui,units,urid,worker}.lv2 \ ${LV2_PATH} - lv2lint -s lv2_generate_ttl -l ld-linux-x86-64.so.2 -M nopack $(lv2ls) + xvfb-run lv2lint -s lv2_generate_ttl -l ld-linux-x86-64.so.2 -M nopack $(lv2ls) - name: Test LV2 plugin run: | export LV2_PATH=/tmp/lv2-path for p in $(lv2ls); do \ env CARLA_BRIDGE_DUMMY=1 CARLA_BRIDGE_TESTING=native \ - valgrind \ + xvfb-run valgrind \ --error-exitcode=255 \ --leak-check=no \ --track-origins=yes \ @@ -971,7 +1121,7 @@ jobs: run: | for p in $(ls bin/*.vst/*.so); do \ env CARLA_BRIDGE_DUMMY=1 CARLA_BRIDGE_TESTING=native \ - valgrind \ + xvfb-run valgrind \ --error-exitcode=255 \ --leak-check=no \ --track-origins=yes \ @@ -982,7 +1132,7 @@ jobs: run: | for p in $(ls bin/ | grep vst3); do \ env CARLA_BRIDGE_DUMMY=1 CARLA_BRIDGE_TESTING=native \ - valgrind \ + xvfb-run valgrind \ --error-exitcode=255 \ --leak-check=no \ --track-origins=yes \ diff --git a/.gitignore b/.gitignore index 9e158373..4b7839a5 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ *.exe *.dll *.dylib +*.pkg *.so *.zip @@ -12,8 +13,14 @@ .kdev_include_paths .kdev4/ -bin/ -build/ -documentation.pdf -utils/inno/resources.iss -utils/inno/version.iss +.cache +compile_commands.json + +/bin/ +/build/ +/documentation.pdf +/jucewrapper/build/ +/jucewrapper/JUCE/ +/src/CardinalNative/resources/ +/utils/inno/resources.iss +/utils/inno/version.iss diff --git a/.gitmodules b/.gitmodules index 01450977..6dc1aa03 100644 --- a/.gitmodules +++ b/.gitmodules @@ -193,6 +193,22 @@ [submodule "plugins/PinkTrombone"] path = plugins/PinkTrombone url = https://github.com/VegaDeftwing/PinkTromboneVCV.git +[submodule "plugins/Meander"] + path = plugins/Meander + url = https://github.com/knchaffin/Meander.git + branch = master-V2 +[submodule "plugins/WhatTheRack"] + path = plugins/WhatTheRack + url = https://github.com/korfuri/WhatTheRack.git +[submodule "plugins/AS"] + path = plugins/AS + url = https://github.com/AScustomWorks/AS.git +[submodule "plugins/forsitan-modulare"] + path = plugins/forsitan-modulare + url = https://github.com/gosub/forsitan-modulare.git +[submodule "plugins/myth-modules"] + path = plugins/myth-modules + url = https://github.com/Ahineya/vcv-myth-plugin.git [submodule "plugins/StarlingVia"] path = plugins/StarlingVia url = https://github.com/starlingcode/Via-for-Rack.git diff --git a/Makefile b/Makefile index be7735c7..b2b722f5 100644 --- a/Makefile +++ b/Makefile @@ -5,14 +5,14 @@ # # also set in: +# jucewrapper/CMakeList.txt `project` # src/CardinalCommon.cpp `CARDINAL_VERSION` # src/CardinalPlugin.cpp `getVersion` -VERSION = 22.04 +VERSION = 22.09 # -------------------------------------------------------------- # Import base definitions -USE_NANOVG_FBO = true include dpf/Makefile.base.mk # -------------------------------------------------------------- @@ -43,7 +43,9 @@ endif # -------------------------------------------------------------- # Carla config -CARLA_EXTRA_ARGS = CARLA_BACKEND_NAMESPACE=Cardinal \ +CARLA_EXTRA_ARGS = \ + CARLA_BACKEND_NAMESPACE=Cardinal \ + DGL_NAMESPACE=CardinalDGL \ HAVE_FFMPEG=false \ HAVE_FLUIDSYNTH=false \ HAVE_PROJECTM=false \ @@ -54,20 +56,19 @@ ifneq ($(DEBUG),true) CARLA_EXTRA_ARGS += EXTERNAL_PLUGINS=true endif -CARLA_EXTRA_ARGS += USING_JUCE=false -CARLA_EXTRA_ARGS += USING_JUCE_GUI_EXTRA=false - # -------------------------------------------------------------- # DGL config DGL_EXTRA_ARGS = \ + DISTRHO_NAMESPACE=CardinalDISTRHO \ + DGL_NAMESPACE=CardinalDGL \ NVG_DISABLE_SKIPPING_WHITESPACE=true \ NVG_FONT_TEXTURE_FLAGS=NVG_IMAGE_NEAREST \ USE_NANOVG_FBO=true \ WINDOWS_ICON_ID=401 # -------------------------------------------------------------- -# Check for system-wide dependencies +# Check for required system-wide dependencies ifeq ($(SYSDEPS),true) @@ -97,8 +98,7 @@ endif # -------------------------------------------------------------- # Check for X11+OpenGL dependencies (unless headless build) -ifneq ($(HAIKU_OR_MACOS_OR_WINDOWS),true) -ifneq ($(WASM),true) +ifneq ($(HAIKU_OR_MACOS_OR_WASM_OR_WINDOWS),true) ifneq ($(HEADLESS),true) ifneq ($(HAVE_OPENGL),true) @@ -107,6 +107,9 @@ endif ifneq ($(HAVE_X11),true) $(error X11 dependency not installed/available) endif +ifneq ($(HAVE_XCURSOR),true) +$(warning Xcursor dependency not installed/available) +endif ifneq ($(HAVE_XEXT),true) $(warning Xext dependency not installed/available) endif @@ -118,11 +121,20 @@ else CARLA_EXTRA_ARGS += HAVE_OPENGL=false CARLA_EXTRA_ARGS += HAVE_X11=false +CARLA_EXTRA_ARGS += HAVE_XCURSOR=false CARLA_EXTRA_ARGS += HAVE_XEXT=false CARLA_EXTRA_ARGS += HAVE_XRANDR=false endif endif + +# -------------------------------------------------------------- +# Check for optional system-wide dependencies + +ifeq ($(shell $(PKG_CONFIG) --exists fftw3f && echo true),true) +HAVE_FFTW3F = true +else +$(warning fftw3f dependency not installed/available) endif # -------------------------------------------------------------- @@ -186,14 +198,16 @@ endif # -------------------------------------------------------------- # Individual targets -cardinal: carla deps dgl plugins +cardinal: carla deps dgl plugins resources $(MAKE) all -C src $(CARLA_EXTRA_ARGS) carla: ifneq ($(STATIC_BUILD),true) $(MAKE) static-plugin -C carla $(CARLA_EXTRA_ARGS) \ CAN_GENERATE_LV2_TTL=false \ - STATIC_PLUGIN_TARGET=true + CUSTOM_DPF_PATH=$(CURDIR)/dpf \ + STATIC_PLUGIN_TARGET=true \ + USING_CUSTOM_DPF=true endif deps: @@ -202,6 +216,9 @@ ifeq ($(SYSDEPS),true) else $(MAKE) all -C deps endif +ifeq ($(HAVE_FFTW3F),true) + $(MAKE) all -C deps/aubio +endif dgl: ifneq ($(HEADLESS),true) @@ -211,7 +228,7 @@ endif plugins: deps $(MAKE) all -C plugins -resources: cardinal +resources: $(MAKE) resources -C plugins ifneq ($(CROSS_COMPILING),true) @@ -227,16 +244,24 @@ endif # -------------------------------------------------------------- # Packaging standalone for CI -unzipfx: deps/unzipfx/unzipfx2cat$(APP_EXT) Cardinal.zip - cat deps/unzipfx/unzipfx2cat$(APP_EXT) Cardinal.zip > Cardinal - chmod +x Cardinal - -Cardinal.zip: bin/Cardinal bin/CardinalFX.lv2/resources - mkdir -p build/unzipfx - ln -sf ../../bin/Cardinal build/unzipfx/Cardinal - ln -s ../../bin/CardinalFX.lv2/resources build/unzipfx/resources - cd build/unzipfx && \ - zip -r -9 ../../Cardinal.zip Cardinal resources +unzipfx: deps/unzipfx/unzipfx2cat$(APP_EXT) CardinalJACK.zip CardinalNative.zip + cat deps/unzipfx/unzipfx2cat$(APP_EXT) CardinalJACK.zip > CardinalJACK + cat deps/unzipfx/unzipfx2cat$(APP_EXT) CardinalNative.zip > CardinalNative + chmod +x CardinalJACK CardinalNative + +CardinalJACK.zip: bin/Cardinal bin/CardinalFX.lv2/resources + mkdir -p build/unzipfx-jack + ln -sf ../../bin/Cardinal build/unzipfx-jack/Cardinal + ln -s ../../bin/CardinalFX.lv2/resources build/unzipfx-jack/resources + cd build/unzipfx-jack && \ + zip -r -9 ../../$@ Cardinal resources + +CardinalNative.zip: bin/CardinalNative bin/CardinalFX.lv2/resources + mkdir -p build/unzipfx-native + ln -sf ../../bin/CardinalNative build/unzipfx-native/Cardinal + ln -s ../../bin/CardinalFX.lv2/resources build/unzipfx-native/resources + cd build/unzipfx-native && \ + zip -r -9 ../../$@ Cardinal resources deps/unzipfx/unzipfx2cat: make -C deps/unzipfx -f Makefile.linux @@ -250,6 +275,7 @@ deps/unzipfx/unzipfx2cat.exe: clean: $(MAKE) distclean -C carla $(CARLA_EXTRA_ARGS) CAN_GENERATE_LV2_TTL=false STATIC_PLUGIN_TARGET=true $(MAKE) clean -C deps + $(MAKE) clean -C deps/aubio $(MAKE) clean -C dpf/dgl $(MAKE) clean -C dpf/utils/lv2-ttl-generator $(MAKE) clean -C plugins @@ -312,7 +338,6 @@ TAR_ARGS = \ --exclude=build \ --exclude=jucewrapper \ --exclude=lv2export \ - --exclude=patches \ --exclude=carla/data \ --exclude=carla/source/frontend \ --exclude=carla/source/interposer \ diff --git a/README.md b/README.md index 1fcdf3e4..d7cb1d7b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ - +# DISTRHO Cardinal *Cardinal, the Rack!* @@ -19,16 +19,12 @@ All "Core" modules from Rack have been replaced by Cardinal equivalents, simplif Cardinal does not load external modules and does not connect to the official Rack library/store. All VCV branding has been removed (to the best of our knowledge) in order to avoid any trademark issues. -The VST3 version is in progress, already part of the build but still experimental. - ## Current status -With the exception of a few bugs, Cardinal can be considered stable. -Though currently the following should be noted: +Cardinal should be considered stable, if you spot any bugs please report them. +Currently the following should be noted: -- Keyboard input does not always work in some hosts [#24](https://github.com/DISTRHO/Cardinal/issues/24) -- VST3 support incomplete/experimental [#41](https://github.com/DISTRHO/Cardinal/issues/41) - Windows 32bit builds do not work well [#80](https://github.com/DISTRHO/Cardinal/issues/80) ### Stable release @@ -86,10 +82,6 @@ Plugin type is set as regular "effect". Because people will ask for it. It is, well... Rack. But a couple of modules background's have their colors flipped, because damn we want proper dark mode! -### Init / Default patch - -![screenshot](docs/Screenshot_Init-Patch.png "Screenshot") - ### Module browser ![screenshot](docs/Screenshot_Module-Browser.png "Screenshot") @@ -102,6 +94,10 @@ But a couple of modules background's have their colors flipped, because damn we ![screenshot](docs/Screenshot_Carla+Ildaeil.png "Screenshot") +### Custom Fundamental modules design + +![screenshot](docs/Screenshot_Fundamental.png "Screenshot") + ## Included modules @@ -115,6 +111,7 @@ At the moment the following 3rd-party modules are provided: - Animated Circuits - Arable Instruments - Aria Salvatrice +- AS - Audible Instruments - Autinn - Axioma @@ -130,6 +127,7 @@ At the moment the following 3rd-party modules are provided: - ExpertSleepers Encoders - Extratone - Fehler Fabrik +- forsitan modulare - Fundamental - Glue the Giant - GoodSheperd @@ -145,12 +143,14 @@ At the moment the following 3rd-party modules are provided: - Little Utils - Lomas Modules - Lyrae Modules +- Meander - MindMeld - ML Modules - Mockba Modular - Mog - mscHack - MSM +- Myth - Nonlinear Circuits - Orbits - Parable Instruments @@ -165,10 +165,11 @@ At the moment the following 3rd-party modules are provided: - unless_modules - Valley - Voxglitch +- WhatTheRack - ZetaCarinae - ZZC -Additionally Cardinal provides its own modules for DAW/Host automation, time position and internal plugin hosting. +Additionally Cardinal provides its own modules for DAW/Host automation, time position, audio to CV pitch conversion and internal plugin hosting. ### Adding modules diff --git a/carla b/carla index 04558b63..963f194b 160000 --- a/carla +++ b/carla @@ -1 +1 @@ -Subproject commit 04558b63101de55556733edfa4a369b51f36e9b3 +Subproject commit 963f194b0ed93829188ffda23320b1dc848f07d8 diff --git a/deps/Makefile b/deps/Makefile index 56ba9a88..28e4f39b 100644 --- a/deps/Makefile +++ b/deps/Makefile @@ -7,7 +7,10 @@ # -------------------------------------------------------------- # Import base definitions +DISTRHO_NAMESPACE = CardinalDISTRHO +DGL_NAMESPACE = CardinalDGL USE_NANOVG_FBO = true +WASM_EXCEPTIONS = true include ../dpf/Makefile.base.mk # -------------------------------------------------------------- @@ -29,7 +32,7 @@ endif # custom build flags BASE_FLAGS += -I../include -BASE_FLAGS += -I../include/neon-compat +BASE_FLAGS += -I../include/simd-compat ifeq ($(HEADLESS),true) ifeq ($(WITH_LTO),true) @@ -41,11 +44,11 @@ ifneq ($(SYSDEPS),true) BASE_FLAGS += -DZSTDLIB_VISIBILITY= endif -ifeq ($(WASM),true) -BASE_FLAGS += -msse -msse2 -msse3 -msimd128 -else ifneq ($(HAIKU),true) +ifneq ($(HAIKU),true) +ifneq ($(WASM),true) BASE_FLAGS += -pthread endif +endif ifeq ($(WINDOWS),true) BASE_FLAGS += -D_USE_MATH_DEFINES @@ -63,15 +66,12 @@ BUILD_CXX_FLAGS += -U_GLIBCXX_ASSERTIONS -Wp,-U_GLIBCXX_ASSERTIONS # -------------------------------------------------------------- # override VCV arch.mk stuff so we can build more architectures -ifeq ($(CPU_AARCH64),true) -ARCH_NAME = aarch64 -MACHINE = x86_64-the-rack +ifeq ($(CPU_ARM32),true) +ARCH_NAME = arm +MACHINE = i686-the-rack else ifeq ($(CPU_ARM64),true) ARCH_NAME = arm64 MACHINE = x86_64-the-rack -else ifeq ($(CPU_ARM),true) -ARCH_NAME = arm -MACHINE = i686-the-rack else ifeq ($(WASM),true) MACHINE = i686-wasm else @@ -86,31 +86,65 @@ else MACHINE_SUFFIX = -linux endif +# -------------------------------------------------------------- +# Set up env to pass to cmake and configure + +ENV = env +ENV += AR=$(AR) +ENV += CC=$(CC) +ENV += CXX=$(CXX) +ENV += CFLAGS='$(BUILD_C_FLAGS)' +ENV += CXXFLAGS='$(BUILD_CXX_FLAGS)' +ENV += LDFLAGS='$(LINK_FLAGS)' + # -------------------------------------------------------------- # Fix up cmake SPACE = SPACE += -CMAKE = cmake - +CMAKE = cmake CMAKE += -DCMAKE_INSTALL_LIBDIR=lib CMAKE += -DCMAKE_INSTALL_PREFIX='$(DEP_PATH)' CMAKE += -DBUILD_SHARED_LIBS=OFF +# make sure debug/release matches +ifeq ($(DEBUG),true) +CMAKE += -DCMAKE_BUILD_TYPE=Debug +else +CMAKE += -DCMAKE_BUILD_TYPE=Release +endif + # make sure macOS target matches ours +ifeq ($(MACOS),true) ifneq (,$(findstring -arch$(SPACE),$(CXXFLAGS))) CMAKE += -DCMAKE_OSX_ARCHITECTURES='$(subst $(SPACE),;,$(subst -arch=,,$(filter -arch=%,$(subst -arch$(SPACE),-arch=,$(CXXFLAGS)))))' +else ifeq ($(CIBUILD),true) +$(error CI build requires -arch flag on macOS) endif ifneq (,$(findstring -mmacosx-version-min=,$(CXXFLAGS))) -CMAKE += -DCMAKE_OSX_DEPLOYMENT_TARGET=$(subst -mmacosx-version-min=,,$(filter -mmacosx-version-min=%,$(CXXFLAGS))) +export MACOSX_DEPLOYMENT_TARGET = $(subst -mmacosx-version-min=,,$(filter -mmacosx-version-min=%,$(CXXFLAGS))) +CMAKE += -DCMAKE_OSX_DEPLOYMENT_TARGET=$(MACOSX_DEPLOYMENT_TARGET) +else ifeq ($(CIBUILD),true) +$(error CI build requires -mmacosx-version-min flag on macOS) +endif +CMAKE += -DCMAKE_OSX_SYSROOT="macosx" endif -# make sure debug/release matches -ifeq ($(DEBUG),true) -CMAKE += -DCMAKE_BUILD_TYPE=Debug -else -CMAKE += -DCMAKE_BUILD_TYPE=Release +# fix emar and emranlib usage +ifeq ($(WASM),true) +CMAKE_AR = $(shell which $(AR)) +CMAKE_RANLIB = $(shell which $(RANLIB)) +CMAKE += -DCMAKE_AR=$(CMAKE_AR) +CMAKE += -DCMAKE_C_COMPILER_AR=$(CMAKE_AR) +CMAKE += -DCMAKE_CXX_COMPILER_AR=$(CMAKE_AR) +CMAKE += -DCMAKE_RANLIB=$(CMAKE_RANLIB) +CMAKE += -DCMAKE_C_COMPILER_RANLIB=$(CMAKE_RANLIB) +CMAKE += -DCMAKE_CXX_COMPILER_RANLIB=$(CMAKE_RANLIB) +ifeq ($(shell uname -s),Darwin) +CMAKE += -DCMAKE_CROSSCOMPILING=ON +CMAKE += -DCMAKE_SYSTEM_NAME=Generic +endif endif # fix cross-compilation for windows @@ -140,29 +174,37 @@ CONFIGURE += ac_cv_host=$(TARGET_MACHINE) DEP_MAKE = $(MAKE) DEP_MAKE += ARCH_NAME=$(ARCH_NAME) +DEP_MAKE += AR=$(AR) DEP_MAKE += CC=$(CC) DEP_MAKE += CXX=$(CXX) DEP_MAKE += CFLAGS="$(BUILD_C_FLAGS)" DEP_MAKE += CXXFLAGS="$(BUILD_CXX_FLAGS)" DEP_MAKE += LDFLAGS="$(LINK_FLAGS)" -DEP_MAKE += CMAKE="$(CMAKE)" -DEP_MAKE += CONFIGURE="$(CONFIGURE)" DEP_MAKE += DEP_FLAGS="$(BASE_FLAGS)" DEP_MAKE += DEP_MAC_SDK_FLAGS= DEP_MAKE += MACHINE=$(MACHINE)$(MACHINE_SUFFIX) +DEP_MAKE += VERBOSE=1 -ifeq ($(MACOS),true) -DEP_MAKE += SHA256SUM="shasum5.28 -a 256" +ifeq ($(shell uname -s),Darwin) +ifeq ($(CIBUILD),true) +DEP_MAKE += SHA256SUM="shasum5.30 -a 256" +else +DEP_MAKE += SHA256SUM="shasum5.30 -a 256" endif +endif + +DEP_MAKE2 = $(DEP_MAKE) +DEP_MAKE2 += CMAKE="$(ENV) $(CMAKE)" +DEP_MAKE2 += CONFIGURE="$(ENV) $(CONFIGURE)" # -------------------------------------------------------------- # Rack internal dependencies target $(DEP_PATH)/lib/%.a: - $(DEP_MAKE) -C $(DEP_PATH) lib/$*.a + $(DEP_MAKE2) -C $(DEP_PATH) lib/$*.a $(DEP_PATH)/jansson-2.12: - $(DEP_MAKE) -C $(DEP_PATH) jansson-2.12 + $(DEP_MAKE2) -C $(DEP_PATH) jansson-2.12 # libarchive: skip shared lib and ensure libzstd is enabled $(DEP_PATH)/lib/libarchive.a: $(DEP_PATH)/lib/libzstd.a $(DEP_PATH)/libarchive-3.4.3/.stamp-patched @@ -170,7 +212,7 @@ $(DEP_PATH)/lib/libarchive.a: $(DEP_PATH)/lib/libzstd.a $(DEP_PATH)/libarchive-3 $(DEP_PATH)/lib/libarchive_static.a: $(DEP_PATH)/lib/libzstd.a $(DEP_PATH)/libarchive-3.4.3/.stamp-patched $(DEP_PATH)/libarchive-3.4.3/.stamp-patched: - $(DEP_MAKE) -C $(DEP_PATH) libarchive-3.4.3 + $(DEP_MAKE2) -C $(DEP_PATH) libarchive-3.4.3 sed -i -e "618,625d" $(DEP_PATH)/libarchive-3.4.3/CMakeLists.txt awk 'NR==616{print " SET(HAVE_LIBZSTD 1)"}1' $(DEP_PATH)/libarchive-3.4.3/CMakeLists.txt > $(DEP_PATH)/libarchive-3.4.3/CMakeLists.txt2 mv $(DEP_PATH)/libarchive-3.4.3/CMakeLists.txt2 $(DEP_PATH)/libarchive-3.4.3/CMakeLists.txt @@ -182,7 +224,7 @@ $(DEP_PATH)/libarchive-3.4.3/.stamp-patched: $(DEP_PATH)/lib/libsamplerate.a: $(DEP_PATH)/libsamplerate-0.1.9/.stamp-patched $(DEP_PATH)/libsamplerate-0.1.9/.stamp-patched: - $(DEP_MAKE) -C $(DEP_PATH) libsamplerate-0.1.9 + $(DEP_MAKE2) -C $(DEP_PATH) libsamplerate-0.1.9 sed -i -e "s/src doc examples tests/src/" $(DEP_PATH)/libsamplerate-0.1.9/Makefile.in touch $@ @@ -190,19 +232,23 @@ $(DEP_PATH)/libsamplerate-0.1.9/.stamp-patched: $(DEP_PATH)/lib/libspeexdsp.a: $(DEP_PATH)/speexdsp-SpeexDSP-1.2rc3/.stamp-patched $(DEP_PATH)/speexdsp-SpeexDSP-1.2rc3/.stamp-patched: - $(DEP_MAKE) -C $(DEP_PATH) speexdsp-SpeexDSP-1.2rc3 \ + $(DEP_MAKE2) -C $(DEP_PATH) speexdsp-SpeexDSP-1.2rc3 \ WGET="wget -c http://downloads.xiph.org/releases/speex/speexdsp-1.2rc3.tar.gz && mv speexdsp-1.2rc3.tar.gz speexdsp-SpeexDSP-1.2rc3.tgz #" \ SHA256SUM="true" \ UNTAR="mkdir -p speexdsp-SpeexDSP-1.2rc3 && tar -x --strip-components=1 --directory=$(DEP_PATH)/speexdsp-SpeexDSP-1.2rc3 -f" sed -i -e "s/#pragma GCC visibility push/#error we dont want this/" $(DEP_PATH)/speexdsp-SpeexDSP-1.2rc3/configure touch $@ -# zstd cmake is borked, see https://github.com/facebook/zstd/issues/1401 -# zstd also fails to build on old systems, patch that too +# custom zstd build for only building static libs $(DEP_PATH)/lib/libzstd.a: $(DEP_PATH)/zstd-1.4.5/.stamp-patched + cd $(DEP_PATH)/zstd-1.4.5/build/cmake && $(CMAKE) -DZSTD_BUILD_STATIC=ON -DZSTD_BUILD_PROGRAMS=OFF -DZSTD_BUILD_SHARED=OFF -DZSTD_MULTITHREAD_SUPPORT=OFF . + $(DEP_MAKE2) -C $(DEP_PATH)/zstd-1.4.5/build/cmake + $(DEP_MAKE2) -C $(DEP_PATH)/zstd-1.4.5/build/cmake install +# zstd cmake is borked, see https://github.com/facebook/zstd/issues/1401 +# zstd also fails to build on old systems, patch that too $(DEP_PATH)/zstd-1.4.5/.stamp-patched: - $(DEP_MAKE) -C $(DEP_PATH) zstd-1.4.5 + $(DEP_MAKE2) -C $(DEP_PATH) zstd-1.4.5 sed -i -e "56,66d" $(DEP_PATH)/zstd-1.4.5/build/cmake/CMakeModules/AddZstdCompilationFlags.cmake sed -i -e "146,175d" $(DEP_PATH)/zstd-1.4.5/programs/util.c sed -i -e "142,144d" $(DEP_PATH)/zstd-1.4.5/programs/util.c diff --git a/deps/PawPaw b/deps/PawPaw index 01d07086..4f7f9eb6 160000 --- a/deps/PawPaw +++ b/deps/PawPaw @@ -1 +1 @@ -Subproject commit 01d07086586818e427b2898d2d446d30b68f3139 +Subproject commit 4f7f9eb6ff1677606a85fe701bbb535f8fe7086c diff --git a/deps/aubio/COPYING b/deps/aubio/COPYING new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/deps/aubio/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/deps/aubio/Makefile b/deps/aubio/Makefile new file mode 100644 index 00000000..7c150a4f --- /dev/null +++ b/deps/aubio/Makefile @@ -0,0 +1,66 @@ +#!/usr/bin/make -f +# Makefile for static aubio # +# ------------------------- # +# Created by falkTX +# + +# -------------------------------------------------------------- +# Import base definitions + +USE_NANOVG_FBO = true +include ../../dpf/Makefile.base.mk + +# -------------------------------------------------------------- + +BUILD_C_FLAGS += -DHAVE_CONFIG_H +BUILD_C_FLAGS += -I. +BUILD_C_FLAGS += -Isrc +BUILD_C_FLAGS += $(shell pkg-config --cflags fftw3f) + +ifeq ($(CIBUILD),true) +BUILD_C_FLAGS += -DSKIP_FFTW_MUTEX +endif + +OBJS = \ + src/cvec.c.o \ + src/fvec.c.o \ + src/lvec.c.o \ + src/mathutils.c.o \ + src/pitch/pitch.c.o \ + src/pitch/pitchfcomb.c.o \ + src/pitch/pitchmcomb.c.o \ + src/pitch/pitchschmitt.c.o \ + src/pitch/pitchspecacf.c.o \ + src/pitch/pitchyin.c.o \ + src/pitch/pitchyinfast.c.o \ + src/pitch/pitchyinfft.c.o \ + src/spectral/fft.c.o \ + src/spectral/phasevoc.c.o \ + src/temporal/a_weighting.c.o \ + src/temporal/biquad.c.o \ + src/temporal/c_weighting.c.o \ + src/temporal/filter.c.o \ + src/temporal/resampler.c.o \ + src/utils/log.c.o \ + +# -------------------------------------------------------------- + +all: libaubio.a + +clean: + rm -f *.a src/*.d src/*.o src/*/*.d src/*/*.o + +libaubio.a: $(OBJS) + rm -f $@ + $(AR) crs $@ $^ + +# -------------------------------------------------------------- + +%.c.o: %.c + $(CC) $< $(BUILD_C_FLAGS) -c -o $@ + +# -------------------------------------------------------------- + +-include $(OBJS:%.o=%.d) + +# -------------------------------------------------------------- diff --git a/deps/aubio/config.h b/deps/aubio/config.h new file mode 100644 index 00000000..7985662f --- /dev/null +++ b/deps/aubio/config.h @@ -0,0 +1,20 @@ +#ifndef AUBIO_CONFIG_H +#define AUBIO_CONFIG_H + +#define HAVE_STDLIB_H 1 +#define HAVE_STDIO_H 1 +#define HAVE_MATH_H 1 +#define HAVE_STRING_H 1 +#define HAVE_LIMITS_H 1 +#define HAVE_STDARG_H 1 +#define HAVE_GETOPT_H 1 +#define HAVE_UNISTD_H 1 + +#define HAVE_C99_VARARGS_MACROS 1 +#define HAVE_MEMCPY_HACKS 1 + +#define HAVE_FFTW3 +#define HAVE_FFTW3F +#define HAVE_COMPLEX_H + +#endif /* AUBIO_CONFIG_H */ diff --git a/deps/aubio/src/aubio.h b/deps/aubio/src/aubio.h new file mode 100644 index 00000000..4d26ea86 --- /dev/null +++ b/deps/aubio/src/aubio.h @@ -0,0 +1,208 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** \mainpage + + \section introduction Introduction + + aubio is a library to extract annotations from audio signals: it provides a + set of functions that take an input audio signal, and output pitch estimates, + attack times (onset), beat location estimates, and other annotation tasks. + + \section basics Basics + + All object structures in aubio share the same function prefixes and suffixes: + + - \p new_aubio_foo creates the object \p foo + - \p aubio_foo_do executes the object \p foo + - \p del_aubio_foo destroys the object \p foo + + All memory allocation and deallocation take place in the \p new_ and \p del_ + functions. Optionally, more than one \p _do methods are available. + Additional parameters can be adjusted and observed using: + + - \p aubio_foo_get_param, getter function, gets the value of a parameter + - \p aubio_foo_set_param, setter function, changes the value of a parameter + + Unless specified in its documentation, no memory operations take place in the + getter functions. However, memory resizing can take place in setter + functions. + + \subsection vectors Vectors + + Two basic structures are being used in aubio: ::fvec_t and ::cvec_t. The + ::fvec_t structures are used to store vectors of floating pointer number. + ::cvec_t are used to store complex number, as two vectors of norm and phase + elements. + + Additionally, the ::lvec_t structure can be used to store floating point + numbers in double precision. They are mostly used to store filter + coefficients, to avoid instability. + + \subsection objects Available objects + + Here is a list of some of the most common objects for aubio: + + \code + + // fast Fourier transform (FFT) + aubio_fft_t *fft = new_aubio_fft (winsize); + // phase vocoder + aubio_pvoc_t *pv = new_aubio_pvoc (winsize, stepsize); + // onset detection + aubio_onset_t *onset = new_aubio_onset (method, winsize, stepsize, samplerate); + // pitch detection + aubio_pitch_t *pitch = new_aubio_pitch (method, winsize, stepsize, samplerate); + // beat tracking + aubio_tempo_t *tempo = new_aubio_tempo (method, winsize, stepsize, samplerate); + + \endcode + + See the list of typedefs for a complete list. + + \subsection example Example + + Here is a simple example that creates an A-Weighting filter and applies it to a + vector. + + \code + + // set window size, and sampling rate + uint_t winsize = 1024, sr = 44100; + // create a vector + fvec_t *this_buffer = new_fvec (winsize); + // create the a-weighting filter + aubio_filter_t *this_filter = new_aubio_filter_a_weighting (sr); + + while (running) { + // here some code to put some data in this_buffer + // ... + + // apply the filter, in place + aubio_filter_do (this_filter, this_buffer); + + // here some code to get some data from this_buffer + // ... + } + + // and free the structures + del_aubio_filter (this_filter); + del_fvec (this_buffer); + + \endcode + + Several examples of C programs are available in the \p examples/ and \p tests/src + directories of the source tree. + + Some examples: + - @ref spectral/test-fft.c + - @ref spectral/test-phasevoc.c + - @ref onset/test-onset.c + - @ref pitch/test-pitch.c + - @ref tempo/test-tempo.c + - @ref test-fvec.c + - @ref test-cvec.c + + \subsection unstable_api Unstable API + + Several more functions are available and used within aubio, but not + documented here, either because they are not considered useful to the user, + or because they may need to be changed in the future. However, they can still + be used by defining AUBIO_UNSTABLE to 1 before including the aubio header: + + \code + #define AUBIO_UNSTABLE 1 + #include + \endcode + + Future versions of aubio could break API compatibility with these functions + without warning. If you choose to use functions in AUBIO_UNSTABLE, you are on + your own. + + \section download Download + + Latest versions, further documentation, examples, wiki, and mailing lists can + be found at https://aubio.org . + + */ + +#ifndef AUBIO_H +#define AUBIO_H + +/** @file aubio.h Global aubio include file. + + You will want to include this file as: + + @code + #include + @endcode + + To access headers with unstable prototypes, use: + + @code + #define AUBIO_UNSTABLE 1 + #include + @endcode + + */ + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* in this order */ +#include "types.h" +#include "fvec.h" +// #include "cvec.h" +// #include "lvec.h" +// // #include "fmat.h" +// #include "musicutils.h" +// // #include "vecutils.h" +// #include "temporal/resampler.h" +// #include "temporal/filter.h" +// #include "temporal/biquad.h" +// #include "temporal/a_weighting.h" +// #include "temporal/c_weighting.h" +// #include "spectral/fft.h" +// // #include "spectral/dct.h" +// #include "spectral/phasevoc.h" +// // #include "spectral/filterbank.h" +// // #include "spectral/filterbank_mel.h" +// // #include "spectral/mfcc.h" +// // #include "spectral/specdesc.h" +// // #include "spectral/awhitening.h" +// // #include "spectral/tss.h" +#include "pitch/pitch.h" +// // #include "onset/onset.h" +// // #include "tempo/tempo.h" +// // #include "notes/notes.h" +// // #include "io/source.h" +// // #include "io/sink.h" +// // #include "synth/sampler.h" +// // #include "synth/wavetable.h" +// // #include "utils/parameter.h" +// #include "utils/log.h" + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/deps/aubio/src/aubio_priv.h b/deps/aubio/src/aubio_priv.h new file mode 100644 index 00000000..8cd3225c --- /dev/null +++ b/deps/aubio/src/aubio_priv.h @@ -0,0 +1,359 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** @file + * Private include file + * + * This file is for inclusion from _within_ the library only. + */ + +#ifndef AUBIO_PRIV_H +#define AUBIO_PRIV_H + +/********************* + * + * External includes + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#ifdef HAVE_STDLIB_H +#include +#endif + +#ifdef HAVE_STDIO_H +#include +#endif + +/* must be included before fftw3.h */ +#ifdef HAVE_COMPLEX_H +#include +#endif + +#if defined(HAVE_FFTW3) || defined(HAVE_FFTW3F) +#include +#endif + +#ifdef HAVE_MATH_H +#include +#endif + +#ifdef HAVE_STRING_H +#include +#endif + +#ifdef HAVE_LIMITS_H +#include // for CHAR_BIT, in C99 standard +#endif + +#ifdef HAVE_STDARG_H +#include +#endif + +#ifdef HAVE_ACCELERATE +#define HAVE_ATLAS 1 +#include +#elif defined(HAVE_ATLAS_CBLAS_H) +#define HAVE_ATLAS 1 +#include +#else +#undef HAVE_ATLAS +#endif + +#ifdef HAVE_ACCELERATE +#include +#ifndef HAVE_AUBIO_DOUBLE +#define aubio_vDSP_mmov vDSP_mmov +#define aubio_vDSP_vmul vDSP_vmul +#define aubio_vDSP_vfill vDSP_vfill +#define aubio_vDSP_meanv vDSP_meanv +#define aubio_vDSP_sve vDSP_sve +#define aubio_vDSP_maxv vDSP_maxv +#define aubio_vDSP_maxvi vDSP_maxvi +#define aubio_vDSP_minv vDSP_minv +#define aubio_vDSP_minvi vDSP_minvi +#define aubio_vDSP_dotpr vDSP_dotpr +#define aubio_vDSP_vclr vDSP_vclr +#else /* HAVE_AUBIO_DOUBLE */ +#define aubio_vDSP_mmov vDSP_mmovD +#define aubio_vDSP_vmul vDSP_vmulD +#define aubio_vDSP_vfill vDSP_vfillD +#define aubio_vDSP_meanv vDSP_meanvD +#define aubio_vDSP_sve vDSP_sveD +#define aubio_vDSP_maxv vDSP_maxvD +#define aubio_vDSP_maxvi vDSP_maxviD +#define aubio_vDSP_minv vDSP_minvD +#define aubio_vDSP_minvi vDSP_minviD +#define aubio_vDSP_dotpr vDSP_dotprD +#define aubio_vDSP_vclr vDSP_vclrD +#endif /* HAVE_AUBIO_DOUBLE */ +#endif /* HAVE_ACCELERATE */ + +#ifdef HAVE_ATLAS +#ifndef HAVE_AUBIO_DOUBLE +#define aubio_catlas_set catlas_sset +#define aubio_cblas_copy cblas_scopy +#define aubio_cblas_swap cblas_sswap +#define aubio_cblas_dot cblas_sdot +#else /* HAVE_AUBIO_DOUBLE */ +#define aubio_catlas_set catlas_dset +#define aubio_cblas_copy cblas_dcopy +#define aubio_cblas_swap cblas_dswap +#define aubio_cblas_dot cblas_ddot +#endif /* HAVE_AUBIO_DOUBLE */ +#endif /* HAVE_ATLAS */ + +#if defined HAVE_INTEL_IPP +#include +#include +#include +#ifndef HAVE_AUBIO_DOUBLE +#define aubio_ippsSet ippsSet_32f +#define aubio_ippsZero ippsZero_32f +#define aubio_ippsCopy ippsCopy_32f +#define aubio_ippsMul ippsMul_32f +#define aubio_ippsMulC ippsMulC_32f +#define aubio_ippsAddC ippsAddC_32f +#define aubio_ippsLn ippsLn_32f_A21 +#define aubio_ippsMean(a,b,c) ippsMean_32f(a, b, c, ippAlgHintFast) +#define aubio_ippsSum(a,b,c) ippsSum_32f(a, b, c, ippAlgHintFast) +#define aubio_ippsMax ippsMax_32f +#define aubio_ippsMin ippsMin_32f +#else /* HAVE_AUBIO_DOUBLE */ +#define aubio_ippsSet ippsSet_64f +#define aubio_ippsZero ippsZero_64f +#define aubio_ippsCopy ippsCopy_64f +#define aubio_ippsMul ippsMul_64f +#define aubio_ippsMulC ippsMulC_64f +#define aubio_ippsAddC ippsAddC_64f +#define aubio_ippsLn ippsLn_64f_A26 +#define aubio_ippsMean ippsMean_64f +#define aubio_ippsSum ippsSum_64f +#define aubio_ippsMax ippsMax_64f +#define aubio_ippsMin ippsMin_64f +#endif /* HAVE_AUBIO_DOUBLE */ +#endif + +#if !defined(HAVE_MEMCPY_HACKS) && !defined(HAVE_ACCELERATE) && !defined(HAVE_ATLAS) && !defined(HAVE_INTEL_IPP) +#define HAVE_NOOPT 1 +#else +#undef HAVE_NOOPT +#endif + +#include "types.h" + +#define AUBIO_UNSTABLE 1 + +#include "mathutils.h" + +/**** + * + * SYSTEM INTERFACE + * + */ + +/* Memory management */ +#define AUBIO_MALLOC(_n) malloc(_n) +#define AUBIO_REALLOC(_p,_n) realloc(_p,_n) +#define AUBIO_NEW(_t) (_t*)calloc(sizeof(_t), 1) +#define AUBIO_ARRAY(_t,_n) (_t*)calloc((_n)*sizeof(_t), 1) +#define AUBIO_MEMCPY(_dst,_src,_n) memcpy(_dst,_src,_n) +#define AUBIO_MEMSET(_dst,_src,_t) memset(_dst,_src,_t) +#define AUBIO_FREE(_p) free(_p) + + +/* file interface */ +#define AUBIO_FOPEN(_f,_m) fopen(_f,_m) +#define AUBIO_FCLOSE(_f) fclose(_f) +#define AUBIO_FREAD(_p,_s,_n,_f) fread(_p,_s,_n,_f) +#define AUBIO_FSEEK(_f,_n,_set) fseek(_f,_n,_set) + +/* strings */ +#define AUBIO_STRLEN(_s) strlen(_s) +#define AUBIO_STRCMP(_s,_t) strcmp(_s,_t) +#define AUBIO_STRNCMP(_s,_t,_n) strncmp(_s,_t,_n) +#define AUBIO_STRCPY(_dst,_src) strcpy(_dst,_src) +#define AUBIO_STRCHR(_s,_c) strchr(_s,_c) +#ifdef strdup +#define AUBIO_STRDUP(s) strdup(s) +#else +#define AUBIO_STRDUP(s) AUBIO_STRCPY(AUBIO_MALLOC(AUBIO_STRLEN(s) + 1), s) +#endif + + +/* Error reporting */ +typedef enum { + AUBIO_OK = 0, + AUBIO_FAIL = 1 +} aubio_status; + +/* Logging */ + +#include "utils/log.h" + +/** internal logging function, defined in utils/log.c */ +uint_t aubio_log(sint_t level, const char_t *fmt, ...); + +#ifdef HAVE_C99_VARARGS_MACROS +#define AUBIO_ERR(...) aubio_log(AUBIO_LOG_ERR, "AUBIO ERROR: " __VA_ARGS__) +#define AUBIO_INF(...) aubio_log(AUBIO_LOG_INF, "AUBIO INFO: " __VA_ARGS__) +#define AUBIO_MSG(...) aubio_log(AUBIO_LOG_MSG, __VA_ARGS__) +#define AUBIO_DBG(...) aubio_log(AUBIO_LOG_DBG, __VA_ARGS__) +#define AUBIO_WRN(...) aubio_log(AUBIO_LOG_WRN, "AUBIO WARNING: " __VA_ARGS__) +#else +#define AUBIO_ERR(format, args...) aubio_log(AUBIO_LOG_ERR, "AUBIO ERROR: " format , ##args) +#define AUBIO_INF(format, args...) aubio_log(AUBIO_LOG_INF, "AUBIO INFO: " format , ##args) +#define AUBIO_MSG(format, args...) aubio_log(AUBIO_LOG_MSG, format , ##args) +#define AUBIO_DBG(format, args...) aubio_log(AUBIO_LOG_DBG, format , ##args) +#define AUBIO_WRN(format, args...) aubio_log(AUBIO_LOG_WRN, "AUBIO WARNING: " format, ##args) +#endif + +#define AUBIO_ERROR AUBIO_ERR + +#define AUBIO_QUIT(_s) exit(_s) +#define AUBIO_SPRINTF sprintf + +#define AUBIO_MAX_SAMPLERATE (192000*8) +#define AUBIO_MAX_CHANNELS 1024 + +/* pi and 2*pi */ +#ifndef M_PI +#define PI (3.14159265358979323846) +#else +#define PI (M_PI) +#endif +#define TWO_PI (PI*2.) + +#ifndef PATH_MAX +#define PATH_MAX 1024 +#endif + +/* aliases to math.h functions */ +#if !HAVE_AUBIO_DOUBLE +#define EXP expf +#define COS cosf +#define SIN sinf +#define ABS fabsf +#define POW powf +#define SQRT sqrtf +#define LOG10 log10f +#define LOG logf +#define FLOOR floorf +#define CEIL ceilf +#define ATAN atanf +#define ATAN2 atan2f +#else +#error using double +#define EXP exp +#define COS cos +#define SIN sin +#define ABS fabs +#define POW pow +#define SQRT sqrt +#define LOG10 log10 +#define LOG log +#define FLOOR floor +#define CEIL ceil +#define ATAN atan +#define ATAN2 atan2 +#endif +#define ROUND(x) FLOOR(x+.5) + +/* aliases to complex.h functions */ +#if HAVE_AUBIO_DOUBLE || !defined(HAVE_COMPLEX_H) || defined(WIN32) +/* mingw32 does not know about c*f functions */ +#define EXPC cexp +/** complex = CEXPC(complex) */ +#define CEXPC cexp +/** sample = ARGC(complex) */ +#define ARGC carg +/** sample = ABSC(complex) norm */ +#define ABSC cabs +/** sample = REAL(complex) */ +#define REAL creal +/** sample = IMAG(complex) */ +#define IMAG cimag +#else +/** sample = EXPC(complex) */ +#define EXPC cexpf +/** complex = CEXPC(complex) */ +#define CEXPC cexp +/** sample = ARGC(complex) */ +#define ARGC cargf +/** sample = ABSC(complex) norm */ +#define ABSC cabsf +/** sample = REAL(complex) */ +#define REAL crealf +/** sample = IMAG(complex) */ +#define IMAG cimagf +#endif + +/* avoid unresolved symbol with msvc 9 */ +#if defined(_MSC_VER) && (_MSC_VER < 1900) +#define isnan _isnan +#endif + +/* handy shortcuts */ +#define DB2LIN(g) (POW(10.0,(g)*0.05f)) +#define LIN2DB(v) (20.0*LOG10(v)) +#define SQR(_a) ((_a)*(_a)) + +#ifndef MAX +#define MAX(a,b) (((a)>(b))?(a):(b)) +#endif /* MAX */ +#ifndef MIN +#define MIN(a,b) (((a)<(b))?(a):(b)) +#endif /* MIN */ + +#define ELEM_SWAP(a,b) { register smpl_t t=(a);(a)=(b);(b)=t; } + +#define VERY_SMALL_NUMBER 2.e-42 //1.e-37 + +/** if ABS(f) < VERY_SMALL_NUMBER, returns 1, else 0 */ +#define IS_DENORMAL(f) ABS(f) < VERY_SMALL_NUMBER + +/** if ABS(f) < VERY_SMALL_NUMBER, returns 0., else f */ +#define KILL_DENORMAL(f) IS_DENORMAL(f) ? 0. : f + +/** if f > VERY_SMALL_NUMBER, returns f, else returns VERY_SMALL_NUMBER */ +#define CEIL_DENORMAL(f) f < VERY_SMALL_NUMBER ? VERY_SMALL_NUMBER : f + +#define SAFE_LOG10(f) LOG10(CEIL_DENORMAL(f)) +#define SAFE_LOG(f) LOG(CEIL_DENORMAL(f)) + +/** silence unused parameter warning by adding an attribute */ +#if defined(__GNUC__) +#define UNUSED __attribute__((unused)) +#else +#define UNUSED +#endif + +/* are we using gcc -std=c99 ? */ +#if defined(__STRICT_ANSI__) +#define strnlen(a,b) MIN(strlen(a),b) +#if !HAVE_AUBIO_DOUBLE +#define floorf floor +#endif +#endif /* __STRICT_ANSI__ */ + +#endif /* AUBIO_PRIV_H */ diff --git a/deps/aubio/src/cvec.c b/deps/aubio/src/cvec.c new file mode 100644 index 00000000..00c43bee --- /dev/null +++ b/deps/aubio/src/cvec.c @@ -0,0 +1,169 @@ +/* + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "cvec.h" + +cvec_t * new_cvec(uint_t length) { + cvec_t * s; + if ((sint_t)length <= 0) { + return NULL; + } + s = AUBIO_NEW(cvec_t); + s->length = length/2 + 1; + s->norm = AUBIO_ARRAY(smpl_t,s->length); + s->phas = AUBIO_ARRAY(smpl_t,s->length); + return s; +} + +void del_cvec(cvec_t *s) { + AUBIO_FREE(s->norm); + AUBIO_FREE(s->phas); + AUBIO_FREE(s); +} + +void cvec_norm_set_sample (cvec_t *s, smpl_t data, uint_t position) { + s->norm[position] = data; +} + +void cvec_phas_set_sample (cvec_t *s, smpl_t data, uint_t position) { + s->phas[position] = data; +} + +smpl_t cvec_norm_get_sample (cvec_t *s, uint_t position) { + return s->norm[position]; +} + +smpl_t cvec_phas_get_sample (cvec_t *s, uint_t position) { + return s->phas[position]; +} + +smpl_t * cvec_norm_get_data (const cvec_t *s) { + return s->norm; +} + +smpl_t * cvec_phas_get_data (const cvec_t *s) { + return s->phas; +} + +/* helper functions */ + +void cvec_print(const cvec_t *s) { + uint_t j; + AUBIO_MSG("norm: "); + for (j=0; j< s->length; j++) { + AUBIO_MSG(AUBIO_SMPL_FMT " ", s->norm[j]); + } + AUBIO_MSG("\n"); + AUBIO_MSG("phas: "); + for (j=0; j< s->length; j++) { + AUBIO_MSG(AUBIO_SMPL_FMT " ", s->phas[j]); + } + AUBIO_MSG("\n"); +} + +void cvec_copy(const cvec_t *s, cvec_t *t) { + if (s->length != t->length) { + AUBIO_ERR("trying to copy %d elements to %d elements \n", + s->length, t->length); + return; + } +#if defined(HAVE_INTEL_IPP) + aubio_ippsCopy(s->phas, t->phas, (int)s->length); + aubio_ippsCopy(s->norm, t->norm, (int)s->length); +#elif defined(HAVE_MEMCPY_HACKS) + memcpy(t->norm, s->norm, t->length * sizeof(smpl_t)); + memcpy(t->phas, s->phas, t->length * sizeof(smpl_t)); +#else + uint_t j; + for (j=0; j< t->length; j++) { + t->norm[j] = s->norm[j]; + t->phas[j] = s->phas[j]; + } +#endif +} + +void cvec_norm_set_all(cvec_t *s, smpl_t val) { +#if defined(HAVE_INTEL_IPP) + aubio_ippsSet(val, s->norm, (int)s->length); +#else + uint_t j; + for (j=0; j< s->length; j++) { + s->norm[j] = val; + } +#endif +} + +void cvec_norm_zeros(cvec_t *s) { +#if defined(HAVE_INTEL_IPP) + aubio_ippsZero(s->norm, (int)s->length); +#elif defined(HAVE_MEMCPY_HACKS) + memset(s->norm, 0, s->length * sizeof(smpl_t)); +#else + cvec_norm_set_all (s, 0.); +#endif +} + +void cvec_norm_ones(cvec_t *s) { + cvec_norm_set_all (s, 1.); +} + +void cvec_phas_set_all (cvec_t *s, smpl_t val) { +#if defined(HAVE_INTEL_IPP) + aubio_ippsSet(val, s->phas, (int)s->length); +#else + uint_t j; + for (j=0; j< s->length; j++) { + s->phas[j] = val; + } +#endif +} + +void cvec_phas_zeros(cvec_t *s) { +#if defined(HAVE_INTEL_IPP) + aubio_ippsZero(s->phas, (int)s->length); +#elif defined(HAVE_MEMCPY_HACKS) + memset(s->phas, 0, s->length * sizeof(smpl_t)); +#else + cvec_phas_set_all (s, 0.); +#endif +} + +void cvec_phas_ones(cvec_t *s) { + cvec_phas_set_all (s, 1.); +} + +void cvec_zeros(cvec_t *s) { + cvec_norm_zeros(s); + cvec_phas_zeros(s); +} + +void cvec_logmag(cvec_t *s, smpl_t lambda) { +#if defined(HAVE_INTEL_IPP) + aubio_ippsMulC(s->norm, lambda, s->norm, (int)s->length); + aubio_ippsAddC(s->norm, 1.0, s->norm, (int)s->length); + aubio_ippsLn(s->norm, s->norm, (int)s->length); +#else + uint_t j; + for (j=0; j< s->length; j++) { + s->norm[j] = LOG(lambda * s->norm[j] + 1); + } +#endif +} diff --git a/deps/aubio/src/cvec.h b/deps/aubio/src/cvec.h new file mode 100644 index 00000000..7c826b68 --- /dev/null +++ b/deps/aubio/src/cvec.h @@ -0,0 +1,247 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#ifndef AUBIO_CVEC_H +#define AUBIO_CVEC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file + + Vector of complex-valued data, stored in polar coordinates + + This file specifies the ::cvec_t buffer type, which is used throughout aubio + to store complex data. Complex values are stored in terms of ::cvec_t.phas + and norm, within 2 vectors of ::smpl_t of size (size/2+1) each. + + \example test-cvec.c + +*/ + +/** Vector of real-valued phase and spectrum data + + \code + + uint_t buffer_size = 1024; + + // create a complex vector of 512 values + cvec_t * input = new_cvec (buffer_size); + + // set some values of the vector + input->norm[23] = 2.; + input->phas[23] = M_PI; + // .. + + // compute the mean of the vector + mean = cvec_mean(input); + + // destroy the vector + del_cvec (input); + + \endcode + + */ +typedef struct { + uint_t length; /**< length of buffer = (requested length)/2 + 1 */ + smpl_t *norm; /**< norm array of size ::cvec_t.length */ + smpl_t *phas; /**< phase array of size ::cvec_t.length */ +} cvec_t; + +/** cvec_t buffer creation function + + This function creates a cvec_t structure holding two arrays of size + [length/2+1], corresponding to the norm and phase values of the + spectral frame. The length stored in the structure is the actual size of both + arrays, not the length of the complex and symmetrical vector, specified as + creation argument. + + \param length the length of the buffer to create + +*/ +cvec_t * new_cvec(uint_t length); + +/** cvec_t buffer deletion function + + \param s buffer to delete as returned by new_cvec() + +*/ +void del_cvec(cvec_t *s); + +/** write norm value in a complex buffer + + This is equivalent to: + \code + s->norm[position] = val; + \endcode + + \param s vector to write to + \param val norm value to write in s->norm[position] + \param position sample position to write to + +*/ +void cvec_norm_set_sample (cvec_t *s, smpl_t val, uint_t position); + +/** write phase value in a complex buffer + + This is equivalent to: + \code + s->phas[position] = val; + \endcode + + \param s vector to write to + \param val phase value to write in s->phas[position] + \param position sample position to write to + +*/ +void cvec_phas_set_sample (cvec_t *s, smpl_t val, uint_t position); + +/** read norm value from a complex buffer + + This is equivalent to: + \code + smpl_t foo = s->norm[position]; + \endcode + + \param s vector to read from + \param position sample position to read from + +*/ +smpl_t cvec_norm_get_sample (cvec_t *s, uint_t position); + +/** read phase value from a complex buffer + + This is equivalent to: + \code + smpl_t foo = s->phas[position]; + \endcode + + \param s vector to read from + \param position sample position to read from + \returns the value of the sample at position + +*/ +smpl_t cvec_phas_get_sample (cvec_t *s, uint_t position); + +/** read norm data from a complex buffer + + \code + smpl_t *data = s->norm; + \endcode + + \param s vector to read from + +*/ +smpl_t * cvec_norm_get_data (const cvec_t *s); + +/** read phase data from a complex buffer + + This is equivalent to: + \code + smpl_t *data = s->phas; + \endcode + + \param s vector to read from + +*/ +smpl_t * cvec_phas_get_data (const cvec_t *s); + +/** print out cvec data + + \param s vector to print out + +*/ +void cvec_print(const cvec_t *s); + +/** make a copy of a vector + + \param s source vector + \param t vector to copy to + +*/ +void cvec_copy(const cvec_t *s, cvec_t *t); + +/** set all norm elements to a given value + + \param s vector to modify + \param val value to set elements to + +*/ +void cvec_norm_set_all (cvec_t *s, smpl_t val); + +/** set all norm elements to zero + + \param s vector to modify + +*/ +void cvec_norm_zeros(cvec_t *s); + +/** set all norm elements to one + + \param s vector to modify + +*/ +void cvec_norm_ones(cvec_t *s); + +/** set all phase elements to a given value + + \param s vector to modify + \param val value to set elements to + +*/ +void cvec_phas_set_all (cvec_t *s, smpl_t val); + +/** set all phase elements to zero + + \param s vector to modify + +*/ +void cvec_phas_zeros(cvec_t *s); + +/** set all phase elements to one + + \param s vector to modify + +*/ +void cvec_phas_ones(cvec_t *s); + +/** set all norm and phas elements to zero + + \param s vector to modify + +*/ +void cvec_zeros(cvec_t *s); + +/** take logarithmic magnitude + + \param s input cvec to compress + \param lambda value to use for normalisation + + \f$ S_k = log( \lambda * S_k + 1 ) \f$ + +*/ +void cvec_logmag(cvec_t *s, smpl_t lambda); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_CVEC_H */ diff --git a/deps/aubio/src/fvec.c b/deps/aubio/src/fvec.c new file mode 100644 index 00000000..3bb0b173 --- /dev/null +++ b/deps/aubio/src/fvec.c @@ -0,0 +1,149 @@ +/* + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "fvec.h" + +fvec_t * new_fvec(uint_t length) { + fvec_t * s; + if ((sint_t)length <= 0) { + return NULL; + } + s = AUBIO_NEW(fvec_t); + s->length = length; + s->data = AUBIO_ARRAY(smpl_t, s->length); + return s; +} + +void del_fvec(fvec_t *s) { + AUBIO_FREE(s->data); + AUBIO_FREE(s); +} + +void fvec_set_sample(fvec_t *s, smpl_t data, uint_t position) { + s->data[position] = data; +} + +smpl_t fvec_get_sample(const fvec_t *s, uint_t position) { + return s->data[position]; +} + +smpl_t * fvec_get_data(const fvec_t *s) { + return s->data; +} + +/* helper functions */ + +void fvec_print(const fvec_t *s) { + uint_t j; + for (j=0; j< s->length; j++) { + AUBIO_MSG(AUBIO_SMPL_FMT " ", s->data[j]); + } + AUBIO_MSG("\n"); +} + +void fvec_set_all (fvec_t *s, smpl_t val) { +#if defined(HAVE_INTEL_IPP) + aubio_ippsSet(val, s->data, (int)s->length); +#elif defined(HAVE_ATLAS) + aubio_catlas_set(s->length, val, s->data, 1); +#elif defined(HAVE_ACCELERATE) + aubio_vDSP_vfill(&val, s->data, 1, s->length); +#else + uint_t j; + for ( j = 0; j< s->length; j++ ) + { + s->data[j] = val; + } +#endif +} + +void fvec_zeros(fvec_t *s) { +#if defined(HAVE_INTEL_IPP) + aubio_ippsZero(s->data, (int)s->length); +#elif defined(HAVE_ACCELERATE) + aubio_vDSP_vclr(s->data, 1, s->length); +#elif defined(HAVE_MEMCPY_HACKS) + memset(s->data, 0, s->length * sizeof(smpl_t)); +#else + fvec_set_all(s, 0.); +#endif +} + +void fvec_ones(fvec_t *s) { + fvec_set_all (s, 1.); +} + +void fvec_rev(fvec_t *s) { + uint_t j; + for (j=0; j< FLOOR((smpl_t)s->length/2); j++) { + ELEM_SWAP(s->data[j], s->data[s->length-1-j]); + } +} + +void fvec_weight(fvec_t *s, const fvec_t *weight) { + uint_t length = MIN(s->length, weight->length); +#if defined(HAVE_INTEL_IPP) + aubio_ippsMul(s->data, weight->data, s->data, (int)length); +#elif defined(HAVE_ACCELERATE) + aubio_vDSP_vmul( s->data, 1, weight->data, 1, s->data, 1, length ); +#else + uint_t j; + for (j = 0; j < length; j++) { + s->data[j] *= weight->data[j]; + } +#endif /* HAVE_ACCELERATE */ +} + +void fvec_weighted_copy(const fvec_t *in, const fvec_t *weight, fvec_t *out) { + uint_t length = MIN(in->length, MIN(out->length, weight->length)); +#if defined(HAVE_INTEL_IPP) + aubio_ippsMul(in->data, weight->data, out->data, (int)length); +#elif defined(HAVE_ACCELERATE) + aubio_vDSP_vmul(in->data, 1, weight->data, 1, out->data, 1, length); +#else + uint_t j; + for (j = 0; j < length; j++) { + out->data[j] = in->data[j] * weight->data[j]; + } +#endif +} + +void fvec_copy(const fvec_t *s, fvec_t *t) { + if (s->length != t->length) { + AUBIO_ERR("trying to copy %d elements to %d elements \n", + s->length, t->length); + return; + } +#if defined(HAVE_INTEL_IPP) + aubio_ippsCopy(s->data, t->data, (int)s->length); +#elif defined(HAVE_BLAS) + aubio_cblas_copy(s->length, s->data, 1, t->data, 1); +#elif defined(HAVE_ACCELERATE) + aubio_vDSP_mmov(s->data, t->data, 1, s->length, 1, 1); +#elif defined(HAVE_MEMCPY_HACKS) + memcpy(t->data, s->data, t->length * sizeof(smpl_t)); +#else + uint_t j; + for (j = 0; j < t->length; j++) { + t->data[j] = s->data[j]; + } +#endif +} diff --git a/deps/aubio/src/fvec.h b/deps/aubio/src/fvec.h new file mode 100644 index 00000000..bd8c5a60 --- /dev/null +++ b/deps/aubio/src/fvec.h @@ -0,0 +1,178 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#ifndef AUBIO_FVEC_H +#define AUBIO_FVEC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file + + Vector of real-valued data + + This file specifies the ::fvec_t buffer type, which is used throughout aubio + to store vector of real-valued ::smpl_t. + + \example test-fvec.c + +*/ + +/** Buffer for real data + + Vector of real-valued data + + ::fvec_t is is the structure used to store vector of real-valued data, ::smpl_t . + + \code + + uint_t buffer_size = 1024; + + // create a vector of 512 values + fvec_t * input = new_fvec (buffer_size); + + // set some values of the vector + input->data[23] = 2.; + // .. + + // compute the mean of the vector + mean = fvec_mean(a_vector); + + // destroy the vector + del_fvec(a_vector); + + \endcode + + See `examples/` and `tests/src` directories for more examples. + + */ +typedef struct { + uint_t length; /**< length of buffer */ + smpl_t *data; /**< data vector of length ::fvec_t.length */ +} fvec_t; + +/** fvec_t buffer creation function + + \param length the length of the buffer to create + +*/ +fvec_t * new_fvec(uint_t length); + +/** fvec_t buffer deletion function + + \param s buffer to delete as returned by new_fvec() + +*/ +void del_fvec(fvec_t *s); + +/** read sample value in a buffer + + \param s vector to read from + \param position sample position to read from + +*/ +smpl_t fvec_get_sample(const fvec_t *s, uint_t position); + +/** write sample value in a buffer + + \param s vector to write to + \param data value to write in s->data[position] + \param position sample position to write to + +*/ +void fvec_set_sample(fvec_t *s, smpl_t data, uint_t position); + +/** read data from a buffer + + \param s vector to read from + +*/ +smpl_t * fvec_get_data(const fvec_t *s); + +/** print out fvec data + + \param s vector to print out + +*/ +void fvec_print(const fvec_t *s); + +/** set all elements to a given value + + \param s vector to modify + \param val value to set elements to + +*/ +void fvec_set_all (fvec_t *s, smpl_t val); + +/** set all elements to zero + + \param s vector to modify + +*/ +void fvec_zeros(fvec_t *s); + +/** set all elements to ones + + \param s vector to modify + +*/ +void fvec_ones(fvec_t *s); + +/** revert order of vector elements + + \param s vector to revert + +*/ +void fvec_rev(fvec_t *s); + +/** apply weight to vector + + If the weight vector is longer than s, only the first elements are used. If + the weight vector is shorter than s, the last elements of s are not weighted. + + \param s vector to weight + \param weight weighting coefficients + +*/ +void fvec_weight(fvec_t *s, const fvec_t *weight); + +/** make a copy of a vector + + \param s source vector + \param t vector to copy to + +*/ +void fvec_copy(const fvec_t *s, fvec_t *t); + +/** make a copy of a vector, applying weights to each element + + \param in input vector + \param weight weights vector + \param out output vector + +*/ +void fvec_weighted_copy(const fvec_t *in, const fvec_t *weight, fvec_t *out); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_FVEC_H */ diff --git a/deps/aubio/src/lvec.c b/deps/aubio/src/lvec.c new file mode 100644 index 00000000..dd63bf42 --- /dev/null +++ b/deps/aubio/src/lvec.c @@ -0,0 +1,80 @@ +/* + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "lvec.h" + +lvec_t * new_lvec(uint_t length) { + lvec_t * s; + if ((sint_t)length <= 0) { + return NULL; + } + s = AUBIO_NEW(lvec_t); + s->length = length; + s->data = AUBIO_ARRAY(lsmp_t, s->length); + return s; +} + +void del_lvec(lvec_t *s) { + AUBIO_FREE(s->data); + AUBIO_FREE(s); +} + +void lvec_set_sample(lvec_t *s, lsmp_t data, uint_t position) { + s->data[position] = data; +} + +lsmp_t lvec_get_sample(lvec_t *s, uint_t position) { + return s->data[position]; +} + +lsmp_t * lvec_get_data(const lvec_t *s) { + return s->data; +} + +/* helper functions */ + +void lvec_print(const lvec_t *s) { + uint_t j; + for (j=0; j< s->length; j++) { + AUBIO_MSG(AUBIO_LSMP_FMT " ", s->data[j]); + } + AUBIO_MSG("\n"); +} + +void lvec_set_all (lvec_t *s, smpl_t val) { + uint_t j; + for (j=0; j< s->length; j++) { + s->data[j] = val; + } +} + +void lvec_zeros(lvec_t *s) { +#if HAVE_MEMCPY_HACKS + memset(s->data, 0, s->length * sizeof(lsmp_t)); +#else + lvec_set_all (s, 0.); +#endif +} + +void lvec_ones(lvec_t *s) { + lvec_set_all (s, 1.); +} + diff --git a/deps/aubio/src/lvec.h b/deps/aubio/src/lvec.h new file mode 100644 index 00000000..402ba0ff --- /dev/null +++ b/deps/aubio/src/lvec.h @@ -0,0 +1,118 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#ifndef AUBIO_LVEC_H +#define AUBIO_LVEC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file + + Vector of real-valued data in double precision + + This file specifies the ::lvec_t buffer type, which is used in some places in + aubio to store a vector of ::lsmp_t. + + Note: the lvec_t data type is required in some algorithms such as IIR filters + (see temporal/filter.h). + + \example test-lvec.c + +*/ + +/** Buffer for real data in double precision */ +typedef struct { + uint_t length; /**< length of buffer */ + lsmp_t *data; /**< data array of size [length] */ +} lvec_t; + +/** lvec_t buffer creation function + + \param length the length of the buffer to create + +*/ +lvec_t * new_lvec(uint_t length); +/** lvec_t buffer deletion function + + \param s buffer to delete as returned by new_lvec() + +*/ +void del_lvec(lvec_t *s); + +/** read sample value in a buffer + + \param s vector to read from + \param position sample position to read from + +*/ +lsmp_t lvec_get_sample(lvec_t *s, uint_t position); + +/** write sample value in a buffer + + \param s vector to write to + \param data value to write in s->data[position] + \param position sample position to write to + +*/ +void lvec_set_sample(lvec_t *s, lsmp_t data, uint_t position); + +/** read data from a buffer + + \param s vector to read from + +*/ +lsmp_t * lvec_get_data(const lvec_t *s); + +/** print out lvec data + + \param s vector to print out + +*/ +void lvec_print(const lvec_t *s); + +/** set all elements to a given value + + \param s vector to modify + \param val value to set elements to + +*/ +void lvec_set_all(lvec_t *s, smpl_t val); + +/** set all elements to zero + + \param s vector to modify + +*/ +void lvec_zeros(lvec_t *s); + +/** set all elements to ones + + \param s vector to modify + +*/ +void lvec_ones(lvec_t *s); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_LVEC_H */ diff --git a/deps/aubio/src/mathutils.c b/deps/aubio/src/mathutils.c new file mode 100644 index 00000000..35755fe4 --- /dev/null +++ b/deps/aubio/src/mathutils.c @@ -0,0 +1,681 @@ +/* + Copyright (C) 2003-2014 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/* see in mathutils.h for doc */ + +#include "aubio_priv.h" +#include "fvec.h" +#include "mathutils.h" +#include "musicutils.h" + +/** Window types */ +typedef enum +{ + aubio_win_ones, + aubio_win_rectangle, + aubio_win_hamming, + aubio_win_hanning, + aubio_win_hanningz, + aubio_win_blackman, + aubio_win_blackman_harris, + aubio_win_gaussian, + aubio_win_welch, + aubio_win_parzen, + aubio_win_default = aubio_win_hanningz, +} aubio_window_type; + +fvec_t * +new_aubio_window (char_t * window_type, uint_t length) +{ + fvec_t * win = new_fvec (length); + uint_t err; + if (win == NULL) { + return NULL; + } + err = fvec_set_window (win, window_type); + if (err != 0) { + del_fvec(win); + return NULL; + } + return win; +} + +uint_t fvec_set_window (fvec_t *win, char_t *window_type) { + smpl_t * w = win->data; + uint_t i, size = win->length; + aubio_window_type wintype; + if (window_type == NULL) { + AUBIO_ERR ("window type can not be null.\n"); + return 1; + } else if (strcmp (window_type, "ones") == 0) + wintype = aubio_win_ones; + else if (strcmp (window_type, "rectangle") == 0) + wintype = aubio_win_rectangle; + else if (strcmp (window_type, "hamming") == 0) + wintype = aubio_win_hamming; + else if (strcmp (window_type, "hanning") == 0) + wintype = aubio_win_hanning; + else if (strcmp (window_type, "hanningz") == 0) + wintype = aubio_win_hanningz; + else if (strcmp (window_type, "blackman") == 0) + wintype = aubio_win_blackman; + else if (strcmp (window_type, "blackman_harris") == 0) + wintype = aubio_win_blackman_harris; + else if (strcmp (window_type, "gaussian") == 0) + wintype = aubio_win_gaussian; + else if (strcmp (window_type, "welch") == 0) + wintype = aubio_win_welch; + else if (strcmp (window_type, "parzen") == 0) + wintype = aubio_win_parzen; + else if (strcmp (window_type, "default") == 0) + wintype = aubio_win_default; + else { + AUBIO_ERR ("unknown window type `%s`.\n", window_type); + return 1; + } + switch(wintype) { + case aubio_win_ones: + fvec_ones(win); + break; + case aubio_win_rectangle: + fvec_set_all(win, .5); + break; + case aubio_win_hamming: + for (i=0;idata, (int)s->length, &tmp); + return tmp; +#elif defined(HAVE_ACCELERATE) + aubio_vDSP_meanv(s->data, 1, &tmp, s->length); + return tmp; +#else + uint_t j; + for (j = 0; j < s->length; j++) { + tmp += s->data[j]; + } + return tmp / (smpl_t)(s->length); +#endif +} + +smpl_t +fvec_sum (fvec_t * s) +{ + smpl_t tmp = 0.0; +#if defined(HAVE_INTEL_IPP) + aubio_ippsSum(s->data, (int)s->length, &tmp); +#elif defined(HAVE_ACCELERATE) + aubio_vDSP_sve(s->data, 1, &tmp, s->length); +#else + uint_t j; + for (j = 0; j < s->length; j++) { + tmp += s->data[j]; + } +#endif + return tmp; +} + +smpl_t +fvec_max (fvec_t * s) +{ +#if defined(HAVE_INTEL_IPP) + smpl_t tmp = 0.; + aubio_ippsMax( s->data, (int)s->length, &tmp); +#elif defined(HAVE_ACCELERATE) + smpl_t tmp = 0.; + aubio_vDSP_maxv( s->data, 1, &tmp, s->length ); +#else + uint_t j; + smpl_t tmp = s->data[0]; + for (j = 1; j < s->length; j++) { + tmp = (tmp > s->data[j]) ? tmp : s->data[j]; + } +#endif + return tmp; +} + +smpl_t +fvec_min (fvec_t * s) +{ +#if defined(HAVE_INTEL_IPP) + smpl_t tmp = 0.; + aubio_ippsMin(s->data, (int)s->length, &tmp); +#elif defined(HAVE_ACCELERATE) + smpl_t tmp = 0.; + aubio_vDSP_minv(s->data, 1, &tmp, s->length); +#else + uint_t j; + smpl_t tmp = s->data[0]; + for (j = 1; j < s->length; j++) { + tmp = (tmp < s->data[j]) ? tmp : s->data[j]; + } +#endif + return tmp; +} + +uint_t +fvec_min_elem (fvec_t * s) +{ +#ifndef HAVE_ACCELERATE + uint_t j, pos = 0.; + smpl_t tmp = s->data[0]; + for (j = 0; j < s->length; j++) { + pos = (tmp < s->data[j]) ? pos : j; + tmp = (tmp < s->data[j]) ? tmp : s->data[j]; + } +#else + smpl_t tmp = 0.; + vDSP_Length pos = 0; + aubio_vDSP_minvi(s->data, 1, &tmp, &pos, s->length); +#endif + return (uint_t)pos; +} + +uint_t +fvec_max_elem (fvec_t * s) +{ +#ifndef HAVE_ACCELERATE + uint_t j, pos = 0; + smpl_t tmp = 0.0; + for (j = 0; j < s->length; j++) { + pos = (tmp > s->data[j]) ? pos : j; + tmp = (tmp > s->data[j]) ? tmp : s->data[j]; + } +#else + smpl_t tmp = 0.; + vDSP_Length pos = 0; + aubio_vDSP_maxvi(s->data, 1, &tmp, &pos, s->length); +#endif + return (uint_t)pos; +} + +void +fvec_shift (fvec_t * s) +{ + uint_t half = s->length / 2, start = half, j; + // if length is odd, middle element is moved to the end + if (2 * half < s->length) start ++; +#ifndef HAVE_BLAS + for (j = 0; j < half; j++) { + ELEM_SWAP (s->data[j], s->data[j + start]); + } +#else + aubio_cblas_swap(half, s->data, 1, s->data + start, 1); +#endif + if (start != half) { + for (j = 0; j < half; j++) { + ELEM_SWAP (s->data[j + start - 1], s->data[j + start]); + } + } +} + +void +fvec_ishift (fvec_t * s) +{ + uint_t half = s->length / 2, start = half, j; + // if length is odd, middle element is moved to the beginning + if (2 * half < s->length) start ++; +#ifndef HAVE_BLAS + for (j = 0; j < half; j++) { + ELEM_SWAP (s->data[j], s->data[j + start]); + } +#else + aubio_cblas_swap(half, s->data, 1, s->data + start, 1); +#endif + if (start != half) { + for (j = 0; j < half; j++) { + ELEM_SWAP (s->data[half], s->data[j]); + } + } +} + +void fvec_push(fvec_t *in, smpl_t new_elem) { + uint_t i; + for (i = 0; i < in->length - 1; i++) { + in->data[i] = in->data[i + 1]; + } + in->data[in->length - 1] = new_elem; +} + +void fvec_clamp(fvec_t *in, smpl_t absmax) { + uint_t i; + for (i = 0; i < in->length; i++) { + if (in->data[i] > 0 && in->data[i] > ABS(absmax)) { + in->data[i] = absmax; + } else if (in->data[i] < 0 && in->data[i] < -ABS(absmax)) { + in->data[i] = -absmax; + } + } +} + +smpl_t +aubio_level_lin (const fvec_t * f) +{ + smpl_t energy = 0.; +#ifndef HAVE_BLAS + uint_t j; + for (j = 0; j < f->length; j++) { + energy += SQR (f->data[j]); + } +#else + energy = aubio_cblas_dot(f->length, f->data, 1, f->data, 1); +#endif + return energy / f->length; +} + +smpl_t +fvec_local_hfc (fvec_t * v) +{ + smpl_t hfc = 0.; + uint_t j; + for (j = 0; j < v->length; j++) { + hfc += (j + 1) * v->data[j]; + } + return hfc; +} + +void +fvec_min_removal (fvec_t * v) +{ + smpl_t v_min = fvec_min (v); + fvec_add (v, - v_min ); +} + +smpl_t +fvec_alpha_norm (fvec_t * o, smpl_t alpha) +{ + uint_t j; + smpl_t tmp = 0.; + for (j = 0; j < o->length; j++) { + tmp += POW (ABS (o->data[j]), alpha); + } + return POW (tmp / o->length, 1. / alpha); +} + +void +fvec_alpha_normalise (fvec_t * o, smpl_t alpha) +{ + uint_t j; + smpl_t norm = fvec_alpha_norm (o, alpha); + for (j = 0; j < o->length; j++) { + o->data[j] /= norm; + } +} + +void +fvec_add (fvec_t * o, smpl_t val) +{ + uint_t j; + for (j = 0; j < o->length; j++) { + o->data[j] += val; + } +} + +void +fvec_mul (fvec_t *o, smpl_t val) +{ + uint_t j; + for (j = 0; j < o->length; j++) { + o->data[j] *= val; + } +} + +void fvec_adapt_thres(fvec_t * vec, fvec_t * tmp, + uint_t post, uint_t pre) { + uint_t length = vec->length, j; + for (j=0;jdata[j] -= fvec_moving_thres(vec, tmp, post, pre, j); + } +} + +smpl_t +fvec_moving_thres (fvec_t * vec, fvec_t * tmpvec, + uint_t post, uint_t pre, uint_t pos) +{ + uint_t k; + smpl_t *medar = (smpl_t *) tmpvec->data; + uint_t win_length = post + pre + 1; + uint_t length = vec->length; + /* post part of the buffer does not exist */ + if (pos < post + 1) { + for (k = 0; k < post + 1 - pos; k++) + medar[k] = 0.; /* 0-padding at the beginning */ + for (k = post + 1 - pos; k < win_length; k++) + medar[k] = vec->data[k + pos - post]; + /* the buffer is fully defined */ + } else if (pos + pre < length) { + for (k = 0; k < win_length; k++) + medar[k] = vec->data[k + pos - post]; + /* pre part of the buffer does not exist */ + } else { + for (k = 0; k < length - pos + post; k++) + medar[k] = vec->data[k + pos - post]; + for (k = length - pos + post; k < win_length; k++) + medar[k] = 0.; /* 0-padding at the end */ + } + return fvec_median (tmpvec); +} + +smpl_t fvec_median (fvec_t * input) { + uint_t n = input->length; + smpl_t * arr = (smpl_t *) input->data; + uint_t low, high ; + uint_t median; + uint_t middle, ll, hh; + + low = 0 ; high = n-1 ; median = (low + high) / 2; + for (;;) { + if (high <= low) /* One element only */ + return arr[median] ; + + if (high == low + 1) { /* Two elements only */ + if (arr[low] > arr[high]) + ELEM_SWAP(arr[low], arr[high]) ; + return arr[median] ; + } + + /* Find median of low, middle and high items; swap into position low */ + middle = (low + high) / 2; + if (arr[middle] > arr[high]) ELEM_SWAP(arr[middle], arr[high]); + if (arr[low] > arr[high]) ELEM_SWAP(arr[low], arr[high]); + if (arr[middle] > arr[low]) ELEM_SWAP(arr[middle], arr[low]) ; + + /* Swap low item (now in position middle) into position (low+1) */ + ELEM_SWAP(arr[middle], arr[low+1]) ; + + /* Nibble from each end towards middle, swapping items when stuck */ + ll = low + 1; + hh = high; + for (;;) { + do ll++; while (arr[low] > arr[ll]) ; + do hh--; while (arr[hh] > arr[low]) ; + + if (hh < ll) + break; + + ELEM_SWAP(arr[ll], arr[hh]) ; + } + + /* Swap middle item (in position low) back into correct position */ + ELEM_SWAP(arr[low], arr[hh]) ; + + /* Re-set active partition */ + if (hh <= median) + low = ll; + if (hh >= median) + high = hh - 1; + } +} + +smpl_t fvec_quadratic_peak_pos (const fvec_t * x, uint_t pos) { + smpl_t s0, s1, s2; uint_t x0, x2; + smpl_t half = .5, two = 2.; + if (pos == 0 || pos == x->length - 1) return pos; + x0 = (pos < 1) ? pos : pos - 1; + x2 = (pos + 1 < x->length) ? pos + 1 : pos; + if (x0 == pos) return (x->data[pos] <= x->data[x2]) ? pos : x2; + if (x2 == pos) return (x->data[pos] <= x->data[x0]) ? pos : x0; + s0 = x->data[x0]; + s1 = x->data[pos]; + s2 = x->data[x2]; + return pos + half * (s0 - s2 ) / (s0 - two * s1 + s2); +} + +smpl_t fvec_quadratic_peak_mag (fvec_t *x, smpl_t pos) { + smpl_t x0, x1, x2; + uint_t index = (uint_t)(pos - .5) + 1; + if (pos >= x->length || pos < 0.) return 0.; + if ((smpl_t)index == pos) return x->data[index]; + x0 = x->data[index - 1]; + x1 = x->data[index]; + x2 = x->data[index + 1]; + return x1 - .25 * (x0 - x2) * (pos - index); +} + +uint_t fvec_peakpick(const fvec_t * onset, uint_t pos) { + uint_t tmp=0; + tmp = (onset->data[pos] > onset->data[pos-1] + && onset->data[pos] > onset->data[pos+1] + && onset->data[pos] > 0.); + return tmp; +} + +smpl_t +aubio_quadfrac (smpl_t s0, smpl_t s1, smpl_t s2, smpl_t pf) +{ + smpl_t tmp = + s0 + (pf / 2.) * (pf * (s0 - 2. * s1 + s2) - 3. * s0 + 4. * s1 - s2); + return tmp; +} + +smpl_t +aubio_freqtomidi (smpl_t freq) +{ + smpl_t midi; + if (freq < 2. || freq > 100000.) return 0.; // avoid nans and infs + /* log(freq/A-2)/log(2) */ + midi = freq / 6.875; + midi = LOG (midi) / 0.6931471805599453; + midi *= 12; + midi -= 3; + return midi; +} + +smpl_t +aubio_miditofreq (smpl_t midi) +{ + smpl_t freq; + if (midi > 140.) return 0.; // avoid infs + freq = (midi + 3.) / 12.; + freq = EXP (freq * 0.6931471805599453); + freq *= 6.875; + return freq; +} + +smpl_t +aubio_bintofreq (smpl_t bin, smpl_t samplerate, smpl_t fftsize) +{ + smpl_t freq = samplerate / fftsize; + return freq * MAX(bin, 0); +} + +smpl_t +aubio_bintomidi (smpl_t bin, smpl_t samplerate, smpl_t fftsize) +{ + smpl_t midi = aubio_bintofreq (bin, samplerate, fftsize); + return aubio_freqtomidi (midi); +} + +smpl_t +aubio_freqtobin (smpl_t freq, smpl_t samplerate, smpl_t fftsize) +{ + smpl_t bin = fftsize / samplerate; + return MAX(freq, 0) * bin; +} + +smpl_t +aubio_miditobin (smpl_t midi, smpl_t samplerate, smpl_t fftsize) +{ + smpl_t freq = aubio_miditofreq (midi); + return aubio_freqtobin (freq, samplerate, fftsize); +} + +uint_t +aubio_is_power_of_two (uint_t a) +{ + if ((a & (a - 1)) == 0) { + return 1; + } else { + return 0; + } +} + +uint_t +aubio_next_power_of_two (uint_t a) +{ + uint_t i = 1; + while (i < a) i <<= 1; + return i; +} + +uint_t +aubio_power_of_two_order (uint_t a) +{ + int order = 0; + int temp = aubio_next_power_of_two(a); + while (temp >>= 1) { + ++order; + } + return order; +} + +smpl_t +aubio_db_spl (const fvec_t * o) +{ + return 10. * LOG10 (aubio_level_lin (o)); +} + +uint_t +aubio_silence_detection (const fvec_t * o, smpl_t threshold) +{ + return (aubio_db_spl (o) < threshold); +} + +smpl_t +aubio_level_detection (const fvec_t * o, smpl_t threshold) +{ + smpl_t db_spl = aubio_db_spl (o); + if (db_spl < threshold) { + return 1.; + } else { + return db_spl; + } +} + +smpl_t +aubio_zero_crossing_rate (fvec_t * input) +{ + uint_t j; + uint_t zcr = 0; + for (j = 1; j < input->length; j++) { + // previous was strictly negative + if (input->data[j - 1] < 0.) { + // current is positive or null + if (input->data[j] >= 0.) { + zcr += 1; + } + // previous was positive or null + } else { + // current is strictly negative + if (input->data[j] < 0.) { + zcr += 1; + } + } + } + return zcr / (smpl_t) input->length; +} + +void +aubio_autocorr (const fvec_t * input, fvec_t * output) +{ + uint_t i, j, length = input->length; + smpl_t *data, *acf; + smpl_t tmp = 0; + data = input->data; + acf = output->data; + for (i = 0; i < length; i++) { + tmp = 0.; + for (j = i; j < length; j++) { + tmp += data[j - i] * data[j]; + } + acf[i] = tmp / (smpl_t) (length - i); + } +} + +void +aubio_cleanup (void) +{ +#ifdef HAVE_FFTW3F + fftwf_cleanup (); +#else +#ifdef HAVE_FFTW3 + fftw_cleanup (); +#endif +#endif +} diff --git a/deps/aubio/src/mathutils.h b/deps/aubio/src/mathutils.h new file mode 100644 index 00000000..4336d7ec --- /dev/null +++ b/deps/aubio/src/mathutils.h @@ -0,0 +1,338 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** \file + + Various math functions + + \example test-mathutils.c + \example test-mathutils-window.c + + */ + +#ifndef AUBIO_MATHUTILS_H +#define AUBIO_MATHUTILS_H + +#include "fvec.h" +#include "musicutils.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** compute the mean of a vector + + \param s vector to compute mean from + \return the mean of `v` + +*/ +smpl_t fvec_mean (fvec_t * s); + +/** find the max of a vector + + \param s vector to get the max from + + \return the value of the minimum of v + +*/ +smpl_t fvec_max (fvec_t * s); + +/** find the min of a vector + + \param s vector to get the min from + + \return the value of the maximum of v + +*/ +smpl_t fvec_min (fvec_t * s); + +/** find the index of the min of a vector + + \param s vector to get the index from + + \return the index of the minimum element of v + +*/ +uint_t fvec_min_elem (fvec_t * s); + +/** find the index of the max of a vector + + \param s vector to get the index from + + \return the index of the maximum element of v + +*/ +uint_t fvec_max_elem (fvec_t * s); + +/** swap the left and right halves of a vector + + This function swaps the left part of the signal with the right part of the +signal. Therefore + + \f$ a[0], a[1], ..., a[\frac{N}{2}], a[\frac{N}{2}+1], ..., a[N-1], a[N] \f$ + + becomes + + \f$ a[\frac{N}{2}+1], ..., a[N-1], a[N], a[0], a[1], ..., a[\frac{N}{2}] \f$ + + This operation, known as 'fftshift' in the Matlab Signal Processing Toolbox, +can be used before computing the FFT to simplify the phase relationship of the +resulting spectrum. See Amalia de Götzen's paper referred to above. + +*/ +void fvec_shift (fvec_t * v); + +/** swap the left and right halves of a vector + + This function swaps the left part of the signal with the right part of the +signal. Therefore + + \f$ a[0], a[1], ..., a[\frac{N}{2}], a[\frac{N}{2}+1], ..., a[N-1], a[N] \f$ + + becomes + + \f$ a[\frac{N}{2}+1], ..., a[N-1], a[N], a[0], a[1], ..., a[\frac{N}{2}] \f$ + + This operation, known as 'ifftshift' in the Matlab Signal Processing Toolbox, +can be used after computing the inverse FFT to simplify the phase relationship +of the resulting spectrum. See Amalia de Götzen's paper referred to above. + +*/ +void fvec_ishift (fvec_t * v); + +/** push a new element to the end of a vector, erasing the first element and + * sliding all others + + \param in vector to push to + \param new_elem new_element to add at the end of the vector + + In numpy words, this is equivalent to: in = np.concatenate([in, [new_elem]])[1:] + +*/ +void fvec_push(fvec_t *in, smpl_t new_elem); + +/** compute the sum of all elements of a vector + + \param v vector to compute the sum of + + \return the sum of v + +*/ +smpl_t fvec_sum (fvec_t * v); + +/** compute the High Frequency Content of a vector + + The High Frequency Content is defined as \f$ \sum_0^{N-1} (k+1) v[k] \f$. + + \param v vector to get the energy from + + \return the HFC of v + +*/ +smpl_t fvec_local_hfc (fvec_t * v); + +/** computes the p-norm of a vector + + Computes the p-norm of a vector for \f$ p = \alpha \f$ + + \f$ L^p = ||x||_p = (|x_1|^p + |x_2|^p + ... + |x_n|^p ) ^ \frac{1}{p} \f$ + + If p = 1, the result is the Manhattan distance. + + If p = 2, the result is the Euclidean distance. + + As p tends towards large values, \f$ L^p \f$ tends towards the maximum of the +input vector. + + References: + + - \f$L^p\f$ space on + Wikipedia + + \param v vector to compute norm from + \param p order of the computed norm + + \return the p-norm of v + +*/ +smpl_t fvec_alpha_norm (fvec_t * v, smpl_t p); + +/** alpha normalisation + + This function divides all elements of a vector by the p-norm as computed by +fvec_alpha_norm(). + + \param v vector to compute norm from + \param p order of the computed norm + +*/ +void fvec_alpha_normalise (fvec_t * v, smpl_t p); + +/** add a constant to each elements of a vector + + \param v vector to add constant to + \param c constant to add to v + +*/ +void fvec_add (fvec_t * v, smpl_t c); + +/** multiply each elements of a vector by a scalar + + \param v vector to add constant to + \param s constant to scale v with + +*/ +void fvec_mul (fvec_t * v, smpl_t s); + +/** remove the minimum value of the vector to each elements + + \param v vector to remove minimum from + +*/ +void fvec_min_removal (fvec_t * v); + +/** compute moving median threshold of a vector + + This function computes the moving median threshold value of at the given +position of a vector, taking the median among post elements before and up to +pre elements after pos. + + \param v input vector + \param tmp temporary vector of length post+1+pre + \param post length of causal part to take before pos + \param pre length of anti-causal part to take after pos + \param pos index to compute threshold for + + \return moving median threshold value + +*/ +smpl_t fvec_moving_thres (fvec_t * v, fvec_t * tmp, uint_t post, uint_t pre, + uint_t pos); + +/** apply adaptive threshold to a vector + + For each points at position p of an input vector, this function remove the +moving median threshold computed at p. + + \param v input vector + \param tmp temporary vector of length post+1+pre + \param post length of causal part to take before pos + \param pre length of anti-causal part to take after pos + +*/ +void fvec_adapt_thres (fvec_t * v, fvec_t * tmp, uint_t post, uint_t pre); + +/** returns the median of a vector + + The QuickSelect routine is based on the algorithm described in "Numerical +recipes in C", Second Edition, Cambridge University Press, 1992, Section 8.5, +ISBN 0-521-43108-5 + + This implementation of the QuickSelect routine is based on Nicolas +Devillard's implementation, available at http://ndevilla.free.fr/median/median/ +and in the Public Domain. + + \param v vector to get median from + + \return the median of v + +*/ +smpl_t fvec_median (fvec_t * v); + +/** finds exact peak index by quadratic interpolation + + See [Quadratic Interpolation of Spectral + Peaks](https://ccrma.stanford.edu/~jos/sasp/Quadratic_Peak_Interpolation.html), + by Julius O. Smith III + + \f$ p_{frac} = \frac{1}{2} \frac {x[p-1] - x[p+1]} {x[p-1] - 2 x[p] + x[p+1]} \in [ -.5, .5] \f$ + + \param x vector to get the interpolated peak position from + \param p index of the peak in vector `x` + \return \f$ p + p_{frac} \f$ exact peak position of interpolated maximum or minimum + +*/ +smpl_t fvec_quadratic_peak_pos (const fvec_t * x, uint_t p); + +/** finds magnitude of peak by quadratic interpolation + + See [Quadratic Interpolation of Spectral + Peaks](https://ccrma.stanford.edu/~jos/sasp/Quadratic_Peak_Interpolation.html), + by Julius O. Smith III + + \param x vector to get the magnitude of the interpolated peak position from + \param p index of the peak in vector `x` + \return magnitude of interpolated peak + +*/ +smpl_t fvec_quadratic_peak_mag (fvec_t * x, smpl_t p); + +/** Quadratic interpolation using Lagrange polynomial. + + Inspired from ``Comparison of interpolation algorithms in real-time sound +processing'', Vladimir Arnost, + + \param s0,s1,s2 are 3 consecutive samples of a curve + \param pf is the floating point index [0;2] + + \return \f$ s0 + (pf/2.)*((pf-3.)*s0-2.*(pf-2.)*s1+(pf-1.)*s2); \f$ + +*/ +smpl_t aubio_quadfrac (smpl_t s0, smpl_t s1, smpl_t s2, smpl_t pf); + +/** return 1 if v[p] is a peak and positive, 0 otherwise + + This function returns 1 if a peak is found at index p in the vector v. The +peak is defined as follows: + + - v[p] is positive + - v[p-1] < v[p] + - v[p] > v[p+1] + + \param v input vector + \param p position of supposed for peak + + \return 1 if a peak is found, 0 otherwise + +*/ +uint_t fvec_peakpick (const fvec_t * v, uint_t p); + +/** return 1 if a is a power of 2, 0 otherwise */ +uint_t aubio_is_power_of_two(uint_t a); + +/** return the next power of power of 2 greater than a */ +uint_t aubio_next_power_of_two(uint_t a); + +/** return the log2 factor of the given power of 2 value a */ +uint_t aubio_power_of_two_order(uint_t a); + +/** compute normalised autocorrelation function + + \param input vector to compute autocorrelation from + \param output vector to store autocorrelation function to + +*/ +void aubio_autocorr (const fvec_t * input, fvec_t * output); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_MATHUTILS_H */ diff --git a/deps/aubio/src/musicutils.h b/deps/aubio/src/musicutils.h new file mode 100644 index 00000000..af222e5b --- /dev/null +++ b/deps/aubio/src/musicutils.h @@ -0,0 +1,270 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** @file + * various functions useful in audio signal processing + */ + +#ifndef AUBIO_MUSICUTILS_H +#define AUBIO_MUSICUTILS_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** create window + + \param window_type type of the window to create + \param size length of the window to create (see fvec_set_window()) + +*/ +fvec_t *new_aubio_window (char_t * window_type, uint_t size); + +/** set elements of a vector to window coefficients + + \param window exsting ::fvec_t to use + \param window_type type of the window to create + + List of available window types: "rectangle", "hamming", "hanning", + "hanningz", "blackman", "blackman_harris", "gaussian", "welch", "parzen", + "default". + + "default" is equivalent to "hanningz". + + References: + + - Window +function on Wikipedia + - Amalia de Götzen, Nicolas Bernardini, and Daniel Arfib. Traditional (?) +implementations of a phase vocoder: the tricks of the trade. In Proceedings of +the International Conference on Digital Audio Effects (DAFx-00), pages 37–44, +Uni- versity of Verona, Italy, 2000. + ( + pdf) + + */ +uint_t fvec_set_window (fvec_t * window, char_t * window_type); + +/** compute the principal argument + + This function maps the input phase to its corresponding value wrapped in the +range \f$ [-\pi, \pi] \f$. + + \param phase unwrapped phase to map to the unit circle + + \return equivalent phase wrapped to the unit circle + +*/ +smpl_t aubio_unwrap2pi (smpl_t phase); + +/** convert frequency bin to midi value */ +smpl_t aubio_bintomidi (smpl_t bin, smpl_t samplerate, smpl_t fftsize); + +/** convert midi value to frequency bin */ +smpl_t aubio_miditobin (smpl_t midi, smpl_t samplerate, smpl_t fftsize); + +/** convert frequency bin to frequency (Hz) */ +smpl_t aubio_bintofreq (smpl_t bin, smpl_t samplerate, smpl_t fftsize); + +/** convert frequency (Hz) to frequency bin */ +smpl_t aubio_freqtobin (smpl_t freq, smpl_t samplerate, smpl_t fftsize); + +/** convert frequency (Hz) to mel + + \param freq input frequency, in Hz + + \return output mel + + Converts a scalar from the frequency domain to the mel scale using Slaney + Auditory Toolbox's implementation: + + If \f$ f < 1000 \f$, \f$ m = 3 f / 200 \f$. + + If \f$ f >= 1000 \f$, \f$ m = 1000 + 27 \frac{{ln}(f) - ln(1000))} + {{ln}(6400) - ln(1000)} + \f$ + + See also + -------- + + aubio_meltohz(), aubio_hztomel_htk(). + +*/ +smpl_t aubio_hztomel (smpl_t freq); + +/** convert mel to frequency (Hz) + + \param mel input mel + + \return output frequency, in Hz + + Converts a scalar from the mel scale to the frequency domain using Slaney + Auditory Toolbox's implementation: + + If \f$ f < 1000 \f$, \f$ f = 200 m/3 \f$. + + If \f$ f \geq 1000 \f$, \f$ f = 1000 + \left(\frac{6400}{1000}\right) + ^{\frac{m - 1000}{27}} \f$ + + See also + -------- + + aubio_hztomel(), aubio_meltohz_htk(). + + References + ---------- + + Malcolm Slaney, *Auditory Toolbox Version 2, Technical Report #1998-010* + https://engineering.purdue.edu/~malcolm/interval/1998-010/ + +*/ +smpl_t aubio_meltohz (smpl_t mel); + +/** convert frequency (Hz) to mel + + \param freq input frequency, in Hz + + \return output mel + + Converts a scalar from the frequency domain to the mel scale, using the + equation defined by O'Shaughnessy, as implemented in the HTK speech + recognition toolkit: + + \f$ m = 1127 + ln(1 + \frac{f}{700}) \f$ + + See also + -------- + + aubio_meltohz_htk(), aubio_hztomel(). + + References + ---------- + + Douglas O'Shaughnessy (1987). *Speech communication: human and machine*. + Addison-Wesley. p. 150. ISBN 978-0-201-16520-3. + + HTK Speech Recognition Toolkit: http://htk.eng.cam.ac.uk/ + + */ +smpl_t aubio_hztomel_htk (smpl_t freq); + +/** convert mel to frequency (Hz) + + \param mel input mel + + \return output frequency, in Hz + + Converts a scalar from the mel scale to the frequency domain, using the + equation defined by O'Shaughnessy, as implemented in the HTK speech + recognition toolkit: + + \f$ f = 700 * {e}^\left(\frac{f}{1127} - 1\right) \f$ + + See also + -------- + + aubio_hztomel_htk(), aubio_meltohz(). + +*/ +smpl_t aubio_meltohz_htk (smpl_t mel); + +/** convert frequency (Hz) to midi value (0-128) */ +smpl_t aubio_freqtomidi (smpl_t freq); + +/** convert midi value (0-128) to frequency (Hz) */ +smpl_t aubio_miditofreq (smpl_t midi); + +/** clean up cached memory at the end of program + + This function should be used at the end of programs to purge all cached + memory. So far it is only useful to clean FFTW's cache. + +*/ +void aubio_cleanup (void); + +/** zero-crossing rate (ZCR) + + The zero-crossing rate is the number of times a signal changes sign, + divided by the length of this signal. + + \param v vector to compute ZCR from + + \return zero-crossing rate of v + +*/ +smpl_t aubio_zero_crossing_rate (fvec_t * v); + +/** compute sound level on a linear scale + + This gives the average of the square amplitudes. + + \param v vector to compute level from + + \return level of v + +*/ +smpl_t aubio_level_lin (const fvec_t * v); + +/** compute sound pressure level (SPL) in dB + + This quantity is often wrongly called 'loudness'. + + This gives ten times the log10 of the average of the square amplitudes. + + \param v vector to compute dB SPL from + + \return level of v in dB SPL + +*/ +smpl_t aubio_db_spl (const fvec_t * v); + +/** check if buffer level in dB SPL is under a given threshold + + \param v vector to get level from + \param threshold threshold in dB SPL + + \return 1 if level is under the given threshold, 0 otherwise + +*/ +uint_t aubio_silence_detection (const fvec_t * v, smpl_t threshold); + +/** get buffer level if level >= threshold, 1. otherwise + + \param v vector to get level from + \param threshold threshold in dB SPL + + \return level in dB SPL if level >= threshold, 1. otherwise + +*/ +smpl_t aubio_level_detection (const fvec_t * v, smpl_t threshold); + +/** clamp the values of a vector within the range [-abs(max), abs(max)] + + \param in vector to clamp + \param absmax maximum value over which input vector elements should be clamped + +*/ +void fvec_clamp(fvec_t *in, smpl_t absmax); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_MUSICUTILS_H */ diff --git a/deps/aubio/src/pitch/pitch.c b/deps/aubio/src/pitch/pitch.c new file mode 100644 index 00000000..40cd7fc8 --- /dev/null +++ b/deps/aubio/src/pitch/pitch.c @@ -0,0 +1,530 @@ +/* + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "fvec.h" +#include "cvec.h" +#include "lvec.h" +#include "mathutils.h" +#include "musicutils.h" +#include "spectral/phasevoc.h" +#include "temporal/filter.h" +#include "temporal/c_weighting.h" +#include "pitch/pitchmcomb.h" +#include "pitch/pitchyin.h" +#include "pitch/pitchfcomb.h" +#include "pitch/pitchschmitt.h" +#include "pitch/pitchyinfft.h" +#include "pitch/pitchyinfast.h" +#include "pitch/pitchspecacf.h" +#include "pitch/pitch.h" + +#define DEFAULT_PITCH_SILENCE -50. + +/** pitch detection algorithms */ +typedef enum +{ + aubio_pitcht_yin, /**< `yin`, YIN algorithm */ + aubio_pitcht_mcomb, /**< `mcomb`, Multi-comb filter */ + aubio_pitcht_schmitt, /**< `schmitt`, Schmitt trigger */ + aubio_pitcht_fcomb, /**< `fcomb`, Fast comb filter */ + aubio_pitcht_yinfft, /**< `yinfft`, Spectral YIN */ + aubio_pitcht_yinfast, /**< `yinfast`, YIN fast */ + aubio_pitcht_specacf, /**< `specacf`, Spectral autocorrelation */ + aubio_pitcht_default + = aubio_pitcht_yinfft, /**< `default` */ +} aubio_pitch_type; + +/** pitch detection output modes */ +typedef enum +{ + aubio_pitchm_freq, /**< Frequency (Hz) */ + aubio_pitchm_midi, /**< MIDI note (0.,127) */ + aubio_pitchm_cent, /**< Cent */ + aubio_pitchm_bin, /**< Frequency bin (0,bufsize) */ + aubio_pitchm_default = aubio_pitchm_freq, /**< the one used when "default" is asked */ +} aubio_pitch_mode; + +/** callback to get pitch candidate, defined below */ +typedef void (*aubio_pitch_detect_t) (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf); + +/** callback to convert pitch from one unit to another, defined below */ +typedef smpl_t(*aubio_pitch_convert_t) (smpl_t value, uint_t samplerate, uint_t bufsize); + +/** callback to fetch the confidence of the algorithm */ +typedef smpl_t (*aubio_pitch_get_conf_t) (void * p); + +/** generic pitch detection structure */ +struct _aubio_pitch_t +{ + aubio_pitch_type type; /**< pitch detection mode */ + aubio_pitch_mode mode; /**< pitch detection output mode */ + uint_t samplerate; /**< samplerate */ + uint_t bufsize; /**< buffer size */ + void *p_object; /**< pointer to pitch object */ + aubio_filter_t *filter; /**< filter */ + fvec_t *filtered; /**< filtered input */ + aubio_pvoc_t *pv; /**< phase vocoder for mcomb */ + cvec_t *fftgrain; /**< spectral frame for mcomb */ + fvec_t *buf; /**< temporary buffer for yin */ + aubio_pitch_detect_t detect_cb; /**< callback to get the pitch candidates */ + aubio_pitch_convert_t conv_cb; /**< callback to convert it to the desired unit */ + aubio_pitch_get_conf_t conf_cb; /**< pointer to the current confidence callback */ + smpl_t silence; /**< silence threshold */ +}; + +/* callback functions for pitch detection */ +static void aubio_pitch_do_mcomb (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf); +static void aubio_pitch_do_yin (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf); +static void aubio_pitch_do_schmitt (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf); +static void aubio_pitch_do_fcomb (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf); +static void aubio_pitch_do_yinfft (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf); +static void aubio_pitch_do_yinfast (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf); +static void aubio_pitch_do_specacf (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf); + +/* internal functions for frequency conversion */ +static smpl_t freqconvbin (smpl_t f, uint_t samplerate, uint_t bufsize); +static smpl_t freqconvmidi (smpl_t f, uint_t samplerate, uint_t bufsize); +static smpl_t freqconvpass (smpl_t f, uint_t samplerate, uint_t bufsize); + +/* adapter to stack ibuf new samples at the end of buf, and trim `buf` to `bufsize` */ +void aubio_pitch_slideblock (aubio_pitch_t * p, const fvec_t * ibuf); + + +aubio_pitch_t * +new_aubio_pitch (const char_t * pitch_mode, + uint_t bufsize, uint_t hopsize, uint_t samplerate) +{ + aubio_pitch_t *p = AUBIO_NEW (aubio_pitch_t); + aubio_pitch_type pitch_type; + if (pitch_mode == NULL) { + AUBIO_ERR ("pitch: can not use ‘NULL‘ for pitch detection method\n"); + goto beach; + } + if (strcmp (pitch_mode, "mcomb") == 0) + pitch_type = aubio_pitcht_mcomb; + else if (strcmp (pitch_mode, "yinfast") == 0) + pitch_type = aubio_pitcht_yinfast; + else if (strcmp (pitch_mode, "yinfft") == 0) + pitch_type = aubio_pitcht_yinfft; + else if (strcmp (pitch_mode, "yin") == 0) + pitch_type = aubio_pitcht_yin; + else if (strcmp (pitch_mode, "schmitt") == 0) + pitch_type = aubio_pitcht_schmitt; + else if (strcmp (pitch_mode, "fcomb") == 0) + pitch_type = aubio_pitcht_fcomb; + else if (strcmp (pitch_mode, "specacf") == 0) + pitch_type = aubio_pitcht_specacf; + else if (strcmp (pitch_mode, "default") == 0) + pitch_type = aubio_pitcht_default; + else { + AUBIO_ERR ("pitch: unknown pitch detection method ‘%s’\n", pitch_mode); + goto beach; + } + + // check parameters are valid + if ((sint_t)hopsize < 1) { + AUBIO_ERR("pitch: got hopsize %d, but can not be < 1\n", hopsize); + goto beach; + } else if ((sint_t)bufsize < 1) { + AUBIO_ERR("pitch: got buffer_size %d, but can not be < 1\n", bufsize); + goto beach; + } else if (bufsize < hopsize) { + AUBIO_ERR("pitch: hop size (%d) is larger than win size (%d)\n", hopsize, bufsize); + goto beach; + } else if ((sint_t)samplerate < 1) { + AUBIO_ERR("pitch: samplerate (%d) can not be < 1\n", samplerate); + goto beach; + } + + p->samplerate = samplerate; + p->type = pitch_type; + aubio_pitch_set_unit (p, "default"); + p->bufsize = bufsize; + p->silence = DEFAULT_PITCH_SILENCE; + p->conf_cb = NULL; + switch (p->type) { + case aubio_pitcht_yin: + p->buf = new_fvec (bufsize); + p->p_object = new_aubio_pitchyin (bufsize); + if (!p->p_object) goto beach; + p->detect_cb = aubio_pitch_do_yin; + p->conf_cb = (aubio_pitch_get_conf_t)aubio_pitchyin_get_confidence; + aubio_pitchyin_set_tolerance (p->p_object, 0.15); + break; + case aubio_pitcht_mcomb: + p->filtered = new_fvec (hopsize); + p->pv = new_aubio_pvoc (bufsize, hopsize); + if (!p->pv) goto beach; + p->fftgrain = new_cvec (bufsize); + p->p_object = new_aubio_pitchmcomb (bufsize, hopsize); + p->filter = new_aubio_filter_c_weighting (samplerate); + p->detect_cb = aubio_pitch_do_mcomb; + break; + case aubio_pitcht_fcomb: + p->buf = new_fvec (bufsize); + p->p_object = new_aubio_pitchfcomb (bufsize, hopsize); + if (!p->p_object) goto beach; + p->detect_cb = aubio_pitch_do_fcomb; + break; + case aubio_pitcht_schmitt: + p->buf = new_fvec (bufsize); + p->p_object = new_aubio_pitchschmitt (bufsize); + p->detect_cb = aubio_pitch_do_schmitt; + break; + case aubio_pitcht_yinfft: + p->buf = new_fvec (bufsize); + p->p_object = new_aubio_pitchyinfft (samplerate, bufsize); + if (!p->p_object) goto beach; + p->detect_cb = aubio_pitch_do_yinfft; + p->conf_cb = (aubio_pitch_get_conf_t)aubio_pitchyinfft_get_confidence; + aubio_pitchyinfft_set_tolerance (p->p_object, 0.85); + break; + case aubio_pitcht_yinfast: + p->buf = new_fvec (bufsize); + p->p_object = new_aubio_pitchyinfast (bufsize); + if (!p->p_object) goto beach; + p->detect_cb = aubio_pitch_do_yinfast; + p->conf_cb = (aubio_pitch_get_conf_t)aubio_pitchyinfast_get_confidence; + aubio_pitchyinfast_set_tolerance (p->p_object, 0.15); + break; + case aubio_pitcht_specacf: + p->buf = new_fvec (bufsize); + p->p_object = new_aubio_pitchspecacf (bufsize); + if (!p->p_object) goto beach; + p->detect_cb = aubio_pitch_do_specacf; + p->conf_cb = (aubio_pitch_get_conf_t)aubio_pitchspecacf_get_tolerance; + aubio_pitchspecacf_set_tolerance (p->p_object, 0.85); + break; + default: + break; + } + return p; + +beach: + if (p->filtered) del_fvec(p->filtered); + if (p->buf) del_fvec(p->buf); + AUBIO_FREE(p); + return NULL; +} + +void +del_aubio_pitch (aubio_pitch_t * p) +{ + switch (p->type) { + case aubio_pitcht_yin: + del_fvec (p->buf); + del_aubio_pitchyin (p->p_object); + break; + case aubio_pitcht_mcomb: + del_fvec (p->filtered); + del_aubio_pvoc (p->pv); + del_cvec (p->fftgrain); + del_aubio_filter (p->filter); + del_aubio_pitchmcomb (p->p_object); + break; + case aubio_pitcht_schmitt: + del_fvec (p->buf); + del_aubio_pitchschmitt (p->p_object); + break; + case aubio_pitcht_fcomb: + del_fvec (p->buf); + del_aubio_pitchfcomb (p->p_object); + break; + case aubio_pitcht_yinfft: + del_fvec (p->buf); + del_aubio_pitchyinfft (p->p_object); + break; + case aubio_pitcht_yinfast: + del_fvec (p->buf); + del_aubio_pitchyinfast (p->p_object); + break; + case aubio_pitcht_specacf: + del_fvec (p->buf); + del_aubio_pitchspecacf (p->p_object); + break; + default: + break; + } + AUBIO_FREE (p); +} + +void +aubio_pitch_slideblock (aubio_pitch_t * p, const fvec_t * ibuf) +{ + uint_t overlap_size = p->buf->length - ibuf->length; +#if 1 //!HAVE_MEMCPY_HACKS + uint_t j; + for (j = 0; j < overlap_size; j++) { + p->buf->data[j] = p->buf->data[j + ibuf->length]; + } + for (j = 0; j < ibuf->length; j++) { + p->buf->data[j + overlap_size] = ibuf->data[j]; + } +#else + smpl_t *data = p->buf->data; + smpl_t *newdata = ibuf->data; + memmove(data, data + ibuf->length, overlap_size); + memcpy(data + overlap_size, newdata, ibuf->length); +#endif +} + +uint_t +aubio_pitch_set_unit (aubio_pitch_t * p, const char_t * pitch_unit) +{ + uint_t err = AUBIO_OK; + aubio_pitch_mode pitch_mode; + if (strcmp (pitch_unit, "freq") == 0) + pitch_mode = aubio_pitchm_freq; + else if (strcmp (pitch_unit, "hertz") == 0) + pitch_mode = aubio_pitchm_freq; + else if (strcmp (pitch_unit, "Hertz") == 0) + pitch_mode = aubio_pitchm_freq; + else if (strcmp (pitch_unit, "Hz") == 0) + pitch_mode = aubio_pitchm_freq; + else if (strcmp (pitch_unit, "f0") == 0) + pitch_mode = aubio_pitchm_freq; + else if (strcmp (pitch_unit, "midi") == 0) + pitch_mode = aubio_pitchm_midi; + else if (strcmp (pitch_unit, "cent") == 0) + pitch_mode = aubio_pitchm_cent; + else if (strcmp (pitch_unit, "bin") == 0) + pitch_mode = aubio_pitchm_bin; + else if (strcmp (pitch_unit, "default") == 0) + pitch_mode = aubio_pitchm_default; + else { + AUBIO_WRN("pitch: unknown pitch detection unit ‘%s’, using default\n", + pitch_unit); + pitch_mode = aubio_pitchm_default; + err = AUBIO_FAIL; + } + p->mode = pitch_mode; + switch (p->mode) { + case aubio_pitchm_freq: + p->conv_cb = freqconvpass; + break; + case aubio_pitchm_midi: + p->conv_cb = freqconvmidi; + break; + case aubio_pitchm_cent: + /* bug: not implemented */ + p->conv_cb = freqconvmidi; + break; + case aubio_pitchm_bin: + p->conv_cb = freqconvbin; + break; + default: + break; + } + return err; +} + +uint_t +aubio_pitch_set_tolerance (aubio_pitch_t * p, smpl_t tol) +{ + switch (p->type) { + case aubio_pitcht_yin: + aubio_pitchyin_set_tolerance (p->p_object, tol); + break; + case aubio_pitcht_yinfft: + aubio_pitchyinfft_set_tolerance (p->p_object, tol); + break; + case aubio_pitcht_yinfast: + aubio_pitchyinfast_set_tolerance (p->p_object, tol); + break; + default: + break; + } + return AUBIO_OK; +} + +smpl_t +aubio_pitch_get_tolerance (aubio_pitch_t * p) +{ + smpl_t tolerance = 1.; + switch (p->type) { + case aubio_pitcht_yin: + tolerance = aubio_pitchyin_get_tolerance (p->p_object); + break; + case aubio_pitcht_yinfft: + tolerance = aubio_pitchyinfft_get_tolerance (p->p_object); + break; + case aubio_pitcht_yinfast: + tolerance = aubio_pitchyinfast_get_tolerance (p->p_object); + break; + default: + break; + } + return tolerance; +} + +uint_t +aubio_pitch_set_silence (aubio_pitch_t * p, smpl_t silence) +{ + if (silence <= 0 && silence >= -200) { + p->silence = silence; + return AUBIO_OK; + } else { + AUBIO_WRN("pitch: could not set silence to %.2f\n", silence); + return AUBIO_FAIL; + } +} + +smpl_t +aubio_pitch_get_silence (aubio_pitch_t * p) +{ + return p->silence; +} + + +/* do method, calling the detection callback, then the conversion callback */ +void +aubio_pitch_do (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf) +{ + p->detect_cb (p, ibuf, obuf); + if (aubio_silence_detection(ibuf, p->silence) == 1) { + obuf->data[0] = 0.; + } + obuf->data[0] = p->conv_cb (obuf->data[0], p->samplerate, p->bufsize); +} + +/* do method for each algorithm */ +void +aubio_pitch_do_mcomb (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf) +{ + aubio_filter_do_outplace (p->filter, ibuf, p->filtered); + aubio_pvoc_do (p->pv, ibuf, p->fftgrain); + aubio_pitchmcomb_do (p->p_object, p->fftgrain, obuf); + obuf->data[0] = aubio_bintofreq (obuf->data[0], p->samplerate, p->bufsize); +} + +void +aubio_pitch_do_yin (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf) +{ + smpl_t pitch = 0.; + aubio_pitch_slideblock (p, ibuf); + aubio_pitchyin_do (p->p_object, p->buf, obuf); + pitch = obuf->data[0]; + if (pitch > 0) { + pitch = p->samplerate / (pitch + 0.); + } else { + pitch = 0.; + } + obuf->data[0] = pitch; +} + + +void +aubio_pitch_do_yinfft (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf) +{ + smpl_t pitch = 0.; + aubio_pitch_slideblock (p, ibuf); + aubio_pitchyinfft_do (p->p_object, p->buf, obuf); + pitch = obuf->data[0]; + if (pitch > 0) { + pitch = p->samplerate / (pitch + 0.); + } else { + pitch = 0.; + } + obuf->data[0] = pitch; +} + +void +aubio_pitch_do_yinfast (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * obuf) +{ + smpl_t pitch = 0.; + aubio_pitch_slideblock (p, ibuf); + aubio_pitchyinfast_do (p->p_object, p->buf, obuf); + pitch = obuf->data[0]; + if (pitch > 0) { + pitch = p->samplerate / (pitch + 0.); + } else { + pitch = 0.; + } + obuf->data[0] = pitch; +} + +void +aubio_pitch_do_specacf (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * out) +{ + smpl_t pitch = 0., period; + aubio_pitch_slideblock (p, ibuf); + aubio_pitchspecacf_do (p->p_object, p->buf, out); + //out->data[0] = aubio_bintofreq (out->data[0], p->samplerate, p->bufsize); + period = out->data[0]; + if (period > 0) { + pitch = p->samplerate / period; + } else { + pitch = 0.; + } + out->data[0] = pitch; +} + +void +aubio_pitch_do_fcomb (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * out) +{ + aubio_pitch_slideblock (p, ibuf); + aubio_pitchfcomb_do (p->p_object, p->buf, out); + out->data[0] = aubio_bintofreq (out->data[0], p->samplerate, p->bufsize); +} + +void +aubio_pitch_do_schmitt (aubio_pitch_t * p, const fvec_t * ibuf, fvec_t * out) +{ + smpl_t period, pitch = 0.; + aubio_pitch_slideblock (p, ibuf); + aubio_pitchschmitt_do (p->p_object, p->buf, out); + period = out->data[0]; + if (period > 0) { + pitch = p->samplerate / period; + } else { + pitch = 0.; + } + out->data[0] = pitch; +} + +/* conversion callbacks */ +smpl_t +freqconvbin(smpl_t f, uint_t samplerate, uint_t bufsize) +{ + return aubio_freqtobin(f, samplerate, bufsize); +} + +smpl_t +freqconvmidi (smpl_t f, uint_t samplerate UNUSED, uint_t bufsize UNUSED) +{ + return aubio_freqtomidi (f); +} + +smpl_t +freqconvpass (smpl_t f, uint_t samplerate UNUSED, uint_t bufsize UNUSED) +{ + return f; +} + +/* confidence callbacks */ +smpl_t +aubio_pitch_get_confidence (aubio_pitch_t * p) +{ + if (p->conf_cb) { + return p->conf_cb(p->p_object); + } + return 0.; +} diff --git a/deps/aubio/src/pitch/pitch.h b/deps/aubio/src/pitch/pitch.h new file mode 100644 index 00000000..b807a6a1 --- /dev/null +++ b/deps/aubio/src/pitch/pitch.h @@ -0,0 +1,197 @@ +/* + Copyright (C) 2003-2013 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#ifndef AUBIO_PITCH_H +#define AUBIO_PITCH_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file + + Pitch detection object + + This file creates the objects required for the computation of the selected + pitch detection algorithm and output the results, in midi note or Hz. + + \section pitch Pitch detection methods + + A list of the pitch detection methods currently available follows. + + \b \p default : use the default method + + Currently, the default method is set to \p yinfft . + + \b \p schmitt : Schmitt trigger + + This pitch extraction method implements a Schmitt trigger to estimate the + period of a signal. + + This file was derived from the tuneit project, written by Mario Lang to + detect the fundamental frequency of a sound. + + See http://delysid.org/tuneit.html + + \b \p fcomb : a fast harmonic comb filter + + This pitch extraction method implements a fast harmonic comb filter to + determine the fundamental frequency of a harmonic sound. + + This file was derived from the tuneit project, written by Mario Lang to + detect the fundamental frequency of a sound. + + See http://delysid.org/tuneit.html + + \b \p mcomb : multiple-comb filter + + This fundamental frequency estimation algorithm implements spectral + flattening, multi-comb filtering and peak histogramming. + + This method was designed by Juan P. Bello and described in: + + Juan-Pablo Bello. ``Towards the Automated Analysis of Simple Polyphonic + Music''. PhD thesis, Centre for Digital Music, Queen Mary University of + London, London, UK, 2003. + + \b \p yin : YIN algorithm + + This algorithm was developed by A. de Cheveigne and H. Kawahara and + published in: + + De Cheveigné, A., Kawahara, H. (2002) "YIN, a fundamental frequency + estimator for speech and music", J. Acoust. Soc. Am. 111, 1917-1930. + + see http://recherche.ircam.fr/equipes/pcm/pub/people/cheveign.html + + \b \p yinfast : Yinfast algorithm + + This algorithm is equivalent to the YIN algorithm, but computed in the + spectral domain for efficiency. See also `python/demos/demo_yin_compare.py`. + + \b \p yinfft : Yinfft algorithm + + This algorithm was derived from the YIN algorithm. In this implementation, a + Fourier transform is used to compute a tapered square difference function, + which allows spectral weighting. Because the difference function is tapered, + the selection of the period is simplified. + + Paul Brossier, [Automatic annotation of musical audio for interactive + systems](http://aubio.org/phd/), Chapter 3, Pitch Analysis, PhD thesis, + Centre for Digital music, Queen Mary University of London, London, UK, 2006. + + \example pitch/test-pitch.c + \example examples/aubiopitch.c + +*/ + +/** pitch detection object */ +typedef struct _aubio_pitch_t aubio_pitch_t; + +/** execute pitch detection on an input signal frame + + \param o pitch detection object as returned by new_aubio_pitch() + \param in input signal of size [hop_size] + \param out output pitch candidates of size [1] + +*/ +void aubio_pitch_do (aubio_pitch_t * o, const fvec_t * in, fvec_t * out); + +/** change yin or yinfft tolerance threshold + + \param o pitch detection object as returned by new_aubio_pitch() + \param tol tolerance default is 0.15 for yin and 0.85 for yinfft + +*/ +uint_t aubio_pitch_set_tolerance (aubio_pitch_t * o, smpl_t tol); + +/** get yin or yinfft tolerance threshold + + \param o pitch detection object as returned by new_aubio_pitch() + \return tolerance (default is 0.15 for yin and 0.85 for yinfft) + +*/ +smpl_t aubio_pitch_get_tolerance (aubio_pitch_t * o); + +/** deletion of the pitch detection object + + \param o pitch detection object as returned by new_aubio_pitch() + +*/ +void del_aubio_pitch (aubio_pitch_t * o); + +/** creation of the pitch detection object + + \param method set pitch detection algorithm + \param buf_size size of the input buffer to analyse + \param hop_size step size between two consecutive analysis instant + \param samplerate sampling rate of the signal + + \return newly created ::aubio_pitch_t + +*/ +aubio_pitch_t *new_aubio_pitch (const char_t * method, + uint_t buf_size, uint_t hop_size, uint_t samplerate); + +/** set the output unit of the pitch detection object + + \param o pitch detection object as returned by new_aubio_pitch() + \param mode set pitch units for output + + mode can be one of "Hz", "midi", "cent", or "bin". Defaults to "Hz". + + \return 0 if successfull, non-zero otherwise + +*/ +uint_t aubio_pitch_set_unit (aubio_pitch_t * o, const char_t * mode); + +/** set the silence threshold of the pitch detection object + + \param o pitch detection object as returned by new_aubio_pitch() + \param silence level threshold under which pitch should be ignored, in dB + + \return 0 if successfull, non-zero otherwise + +*/ +uint_t aubio_pitch_set_silence (aubio_pitch_t * o, smpl_t silence); + +/** set the silence threshold of the pitch detection object + + \param o pitch detection object as returned by ::new_aubio_pitch() + + \return level threshold under which pitch should be ignored, in dB + +*/ +smpl_t aubio_pitch_get_silence (aubio_pitch_t * o); + +/** get the current confidence + + \param o pitch detection object as returned by new_aubio_pitch() + + \return the current confidence of the pitch algorithm + +*/ +smpl_t aubio_pitch_get_confidence (aubio_pitch_t * o); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_PITCH_H */ diff --git a/deps/aubio/src/pitch/pitchfcomb.c b/deps/aubio/src/pitch/pitchfcomb.c new file mode 100644 index 00000000..5cc49b9b --- /dev/null +++ b/deps/aubio/src/pitch/pitchfcomb.c @@ -0,0 +1,144 @@ +/* + Copyright (C) 2004, 2005 Mario Lang + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "fvec.h" +#include "cvec.h" +#include "mathutils.h" +#include "musicutils.h" +#include "spectral/fft.h" +#include "pitch/pitchfcomb.h" + +#define MAX_PEAKS 8 + +typedef struct +{ + smpl_t bin; + smpl_t db; +} aubio_fpeak_t; + +struct _aubio_pitchfcomb_t +{ + uint_t fftSize; + uint_t stepSize; + uint_t rate; + fvec_t *winput; + fvec_t *win; + cvec_t *fftOut; + fvec_t *fftLastPhase; + aubio_fft_t *fft; +}; + +aubio_pitchfcomb_t * +new_aubio_pitchfcomb (uint_t bufsize, uint_t hopsize) +{ + aubio_pitchfcomb_t *p = AUBIO_NEW (aubio_pitchfcomb_t); + p->fftSize = bufsize; + p->stepSize = hopsize; + p->fft = new_aubio_fft (bufsize); + if (!p->fft) goto beach; + p->winput = new_fvec (bufsize); + p->fftOut = new_cvec (bufsize); + p->fftLastPhase = new_fvec (bufsize); + p->win = new_aubio_window ("hanning", bufsize); + return p; + +beach: + AUBIO_FREE(p); + return NULL; +} + +/* input must be stepsize long */ +void +aubio_pitchfcomb_do (aubio_pitchfcomb_t * p, const fvec_t * input, fvec_t * output) +{ + uint_t k, l, maxharm = 0; + smpl_t phaseDifference = TWO_PI * (smpl_t) p->stepSize / (smpl_t) p->fftSize; + aubio_fpeak_t peaks[MAX_PEAKS]; + + for (k = 0; k < MAX_PEAKS; k++) { + peaks[k].db = -200.; + peaks[k].bin = 0.; + } + + for (k = 0; k < input->length; k++) { + p->winput->data[k] = p->win->data[k] * input->data[k]; + } + aubio_fft_do (p->fft, p->winput, p->fftOut); + + for (k = 0; k <= p->fftSize / 2; k++) { + smpl_t + magnitude = + 20. * LOG10 (2. * p->fftOut->norm[k] / (smpl_t) p->fftSize), + phase = p->fftOut->phas[k], tmp, bin; + + /* compute phase difference */ + tmp = phase - p->fftLastPhase->data[k]; + p->fftLastPhase->data[k] = phase; + + /* subtract expected phase difference */ + tmp -= (smpl_t) k *phaseDifference; + + /* map delta phase into +/- Pi interval */ + tmp = aubio_unwrap2pi (tmp); + + /* get deviation from bin frequency from the +/- Pi interval */ + tmp = p->fftSize / (smpl_t) p->stepSize * tmp / (TWO_PI); + + /* compute the k-th partials' true bin */ + bin = (smpl_t) k + tmp; + + if (bin > 0.0 && magnitude > peaks[0].db) { // && magnitude < 0) { + memmove (peaks + 1, peaks, sizeof (aubio_fpeak_t) * (MAX_PEAKS - 1)); + peaks[0].bin = bin; + peaks[0].db = magnitude; + } + } + + k = 0; + for (l = 1; l < MAX_PEAKS && peaks[l].bin > 0.0; l++) { + sint_t harmonic; + for (harmonic = 5; harmonic > 1; harmonic--) { + if (peaks[0].bin / peaks[l].bin < harmonic + .02 && + peaks[0].bin / peaks[l].bin > harmonic - .02) { + if (harmonic > (sint_t) maxharm && peaks[0].db < peaks[l].db / 2) { + maxharm = harmonic; + k = l; + } + } + } + } + output->data[0] = peaks[k].bin; + /* quick hack to clean output a bit */ + if (peaks[k].bin > 5000.) + output->data[0] = 0.; +} + +void +del_aubio_pitchfcomb (aubio_pitchfcomb_t * p) +{ + del_cvec (p->fftOut); + del_fvec (p->fftLastPhase); + del_fvec (p->win); + del_fvec (p->winput); + del_aubio_fft (p->fft); + AUBIO_FREE (p); +} diff --git a/deps/aubio/src/pitch/pitchfcomb.h b/deps/aubio/src/pitch/pitchfcomb.h new file mode 100644 index 00000000..50167088 --- /dev/null +++ b/deps/aubio/src/pitch/pitchfcomb.h @@ -0,0 +1,76 @@ +/* + Copyright (C) 2003-2013 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** \file + + Pitch detection using a fast harmonic comb filter + + This pitch extraction method implements a fast harmonic comb filter to + determine the fundamental frequency of a harmonic sound. + + This file was derived from the tuneit project, written by Mario Lang to + detect the fundamental frequency of a sound. + + See http://delysid.org/tuneit.html + + \example pitch/test-pitchfcomb.c + +*/ + +#ifndef AUBIO_PITCHFCOMB_H +#define AUBIO_PITCHFCOMB_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** pitch detection object */ +typedef struct _aubio_pitchfcomb_t aubio_pitchfcomb_t; + +/** execute pitch detection on an input buffer + + \param p pitch detection object as returned by new_aubio_pitchfcomb + \param input input signal window (length as specified at creation time) + \param output pitch candidates in bins + +*/ +void aubio_pitchfcomb_do (aubio_pitchfcomb_t * p, const fvec_t * input, + fvec_t * output); + +/** creation of the pitch detection object + + \param buf_size size of the input buffer to analyse + \param hop_size step size between two consecutive analysis instant + +*/ +aubio_pitchfcomb_t *new_aubio_pitchfcomb (uint_t buf_size, uint_t hop_size); + +/** deletion of the pitch detection object + + \param p pitch detection object as returned by new_aubio_pitchfcomb + +*/ +void del_aubio_pitchfcomb (aubio_pitchfcomb_t * p); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_PITCHFCOMB_H */ diff --git a/deps/aubio/src/pitch/pitchmcomb.c b/deps/aubio/src/pitch/pitchmcomb.c new file mode 100644 index 00000000..9ce160ed --- /dev/null +++ b/deps/aubio/src/pitch/pitchmcomb.c @@ -0,0 +1,435 @@ +/* + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "fvec.h" +#include "cvec.h" +#include "mathutils.h" +#include "pitch/pitchmcomb.h" + +#define CAND_SWAP(a,b) { register aubio_spectralcandidate_t *t=(a);(a)=(b);(b)=t; } + +typedef struct _aubio_spectralpeak_t aubio_spectralpeak_t; +typedef struct _aubio_spectralcandidate_t aubio_spectralcandidate_t; +uint_t aubio_pitchmcomb_get_root_peak (aubio_spectralpeak_t * peaks, + uint_t length); +uint_t aubio_pitchmcomb_quadpick (aubio_spectralpeak_t * spectral_peaks, + const fvec_t * X); +void aubio_pitchmcomb_spectral_pp (aubio_pitchmcomb_t * p, const fvec_t * oldmag); +void aubio_pitchmcomb_combdet (aubio_pitchmcomb_t * p, const fvec_t * newmag); +/* not used but useful : sort by amplitudes (or anything else) + * sort_pitchpeak(peaks, length); + */ +#if 0 +/** spectral_peak comparison function (must return signed int) */ +static sint_t aubio_pitchmcomb_sort_peak_comp (const void *x, const void *y); +/** sort spectral_peak against their mag */ +void aubio_pitchmcomb_sort_peak (aubio_spectralpeak_t * peaks, uint_t nbins); +/** select the best candidates */ +uint_t aubio_pitch_cands (aubio_pitchmcomb_t * p, const cvec_t * fftgrain, + smpl_t * cands); +#endif + +/** sort spectral_candidate against their comb ene */ +void aubio_pitchmcomb_sort_cand_ene (aubio_spectralcandidate_t ** candidates, + uint_t nbins); +#if 0 +/** sort spectral_candidate against their frequency */ +void aubio_pitchmcomb_sort_cand_freq (aubio_spectralcandidate_t ** candidates, + uint_t nbins); +#endif + +struct _aubio_pitchmcomb_t +{ + smpl_t threshold; /**< offset threshold [0.033 or 0.01] */ + smpl_t alpha; /**< normalisation exponent [9] */ + smpl_t cutoff; /**< low-pass filter cutoff [0.34, 1] */ + smpl_t tol; /**< tolerance [0.05] */ + // smpl_t tau; /**< frequency precision [44100/4096] */ + uint_t win_post; /**< median filter window length */ + uint_t win_pre; /**< median filter window */ + uint_t ncand; /**< maximum number of candidates (combs) */ + uint_t npartials; /**< maximum number of partials per combs */ + uint_t count; /**< picked picks */ + uint_t goodcandidate; /**< best candidate */ + uint_t spec_partition; /**< spectrum partition to consider */ + aubio_spectralpeak_t *peaks; /**< up to length win/spec_partition */ + aubio_spectralcandidate_t **candidates; /** up to five candidates */ + /* some scratch pads */ + /** \bug (unnecessary copied from fftgrain?) */ + fvec_t *newmag; /**< vec to store mag */ + fvec_t *scratch; /**< vec to store modified mag */ + fvec_t *scratch2; /**< vec to compute moving median */ + fvec_t *theta; /**< vec to store phase */ + smpl_t phasediff; + smpl_t phasefreq; + /** threshfn: name or handle of fn for computing adaptive threshold [median] */ + /** aubio_thresholdfn_t thresholdfn; */ + /** picker: name or handle of fn for picking event times [quadpick] */ + /** aubio_pickerfn_t pickerfn; */ +}; + +/** spectral peak object */ +struct _aubio_spectralpeak_t +{ + uint_t bin; /**< bin [0-(length-1)] */ + smpl_t ebin; /**< estimated bin */ + smpl_t mag; /**< peak magnitude */ +}; + +/** spectral candidates array object */ +struct _aubio_spectralcandidate_t +{ + smpl_t ebin; /**< interpolated bin */ + smpl_t *ecomb; /**< comb */ + smpl_t ene; /**< candidate energy */ + smpl_t len; /**< length */ +}; + + +void +aubio_pitchmcomb_do (aubio_pitchmcomb_t * p, const cvec_t * fftgrain, fvec_t * output) +{ + uint_t j; + smpl_t instfreq; + fvec_t *newmag = (fvec_t *) p->newmag; + //smpl_t hfc; //fe=instfreq(theta1,theta,ops); //theta1=theta; + /* copy incoming grain to newmag */ + for (j = 0; j < newmag->length; j++) + newmag->data[j] = fftgrain->norm[j]; + /* detect only if local energy > 10. */ + //if (aubio_level_lin (newmag) * newmag->length > 10.) { + //hfc = fvec_local_hfc(newmag); //not used + aubio_pitchmcomb_spectral_pp (p, newmag); + aubio_pitchmcomb_combdet (p, newmag); + //aubio_pitchmcomb_sort_cand_freq(p->candidates,p->ncand); + //return p->candidates[p->goodcandidate]->ebin; + j = (uint_t) FLOOR (p->candidates[p->goodcandidate]->ebin + .5); + instfreq = aubio_unwrap2pi (fftgrain->phas[j] + - p->theta->data[j] - j * p->phasediff); + instfreq *= p->phasefreq; + /* store phase for next run */ + for (j = 0; j < p->theta->length; j++) { + p->theta->data[j] = fftgrain->phas[j]; + } + //return p->candidates[p->goodcandidate]->ebin; + output->data[0] = + FLOOR (p->candidates[p->goodcandidate]->ebin + .5) + instfreq; + /*} else { + return -1.; + } */ +} + +#if 0 +uint_t +aubio_pitch_cands (aubio_pitchmcomb_t * p, const cvec_t * fftgrain, smpl_t * cands) +{ + uint_t j; + uint_t k; + fvec_t *newmag = (fvec_t *) p->newmag; + aubio_spectralcandidate_t **scands = + (aubio_spectralcandidate_t **) (p->candidates); + //smpl_t hfc; //fe=instfreq(theta1,theta,ops); //theta1=theta; + /* copy incoming grain to newmag */ + for (j = 0; j < newmag->length; j++) + newmag->data[j] = fftgrain->norm[j]; + /* detect only if local energy > 10. */ + if (aubio_level_lin (newmag) * newmag->length > 10.) { + /* hfc = fvec_local_hfc(newmag); do not use */ + aubio_pitchmcomb_spectral_pp (p, newmag); + aubio_pitchmcomb_combdet (p, newmag); + aubio_pitchmcomb_sort_cand_freq (scands, p->ncand); + /* store ncand comb energies in cands[1:ncand] */ + for (k = 0; k < p->ncand; k++) + cands[k] = p->candidates[k]->ene; + /* store ncand[end] freq in cands[end] */ + cands[p->ncand] = p->candidates[p->ncand - 1]->ebin; + return 1; + } else { + for (k = 0; k < p->ncand; k++) + cands[k] = 0; + return 0; + } +} +#endif + +void +aubio_pitchmcomb_spectral_pp (aubio_pitchmcomb_t * p, const fvec_t * newmag) +{ + fvec_t *mag = (fvec_t *) p->scratch; + fvec_t *tmp = (fvec_t *) p->scratch2; + uint_t j; + uint_t length = mag->length; + /* copy newmag to mag (scracth) */ + for (j = 0; j < length; j++) { + mag->data[j] = newmag->data[j]; + } + fvec_min_removal (mag); /* min removal */ + fvec_alpha_normalise (mag, p->alpha); /* alpha normalisation */ + /* skipped *//* low pass filtering */ + /** \bug fvec_moving_thres may write out of bounds */ + fvec_adapt_thres (mag, tmp, p->win_post, p->win_pre); /* adaptative threshold */ + fvec_add (mag, -p->threshold); /* fixed threshold */ + { + aubio_spectralpeak_t *peaks = (aubio_spectralpeak_t *) p->peaks; + uint_t count; + /* return bin and ebin */ + count = aubio_pitchmcomb_quadpick (peaks, mag); + for (j = 0; j < count; j++) + peaks[j].mag = newmag->data[peaks[j].bin]; + /* reset non peaks */ + for (j = count; j < length; j++) + peaks[j].mag = 0.; + p->peaks = peaks; + p->count = count; + } +} + +void +aubio_pitchmcomb_combdet (aubio_pitchmcomb_t * p, const fvec_t * newmag) +{ + aubio_spectralpeak_t *peaks = (aubio_spectralpeak_t *) p->peaks; + aubio_spectralcandidate_t **candidate = + (aubio_spectralcandidate_t **) p->candidates; + + /* parms */ + uint_t N = p->npartials; /* maximum number of partials to be considered 10 */ + uint_t M = p->ncand; /* maximum number of combs to be considered 5 */ + uint_t length = newmag->length; + uint_t count = p->count; + uint_t k; + uint_t l; + uint_t d; + uint_t curlen = 0; + + smpl_t delta2; + smpl_t xx; + uint_t position = 0; + + uint_t root_peak = 0; + uint_t tmpl = 0; + smpl_t tmpene = 0.; + + /* get the biggest peak in the spectrum */ + root_peak = aubio_pitchmcomb_get_root_peak (peaks, count); + /* not enough partials in highest notes, could be forced */ + //if (peaks[root_peak].ebin >= aubio_miditofreq(85.)/p->tau) N=2; + //if (peaks[root_peak].ebin >= aubio_miditofreq(90.)/p->tau) N=1; + /* now calculate the energy of each of the 5 combs */ + for (l = 0; l < M; l++) { + smpl_t scaler = (1. / (l + 1.)); + candidate[l]->ene = 0.; /* reset ene and len sums */ + candidate[l]->len = 0.; + candidate[l]->ebin = scaler * peaks[root_peak].ebin; + /* if less than N peaks available, curlen < N */ + if (candidate[l]->ebin != 0.) + curlen = (uint_t) FLOOR (length / (candidate[l]->ebin)); + curlen = (N < curlen) ? N : curlen; + /* fill candidate[l]->ecomb[k] with (k+1)*candidate[l]->ebin */ + for (k = 0; k < curlen; k++) + candidate[l]->ecomb[k] = (candidate[l]->ebin) * (k + 1.); + for (k = curlen; k < length; k++) + candidate[l]->ecomb[k] = 0.; + /* for each in candidate[l]->ecomb[k] */ + for (k = 0; k < curlen; k++) { + xx = 100000.; + /** get the candidate->ecomb the closer to peaks.ebin + * (to cope with the inharmonicity)*/ + for (d = 0; d < count; d++) { + delta2 = ABS (candidate[l]->ecomb[k] - peaks[d].ebin); + if (delta2 <= xx) { + position = d; + xx = delta2; + } + } + /* for a Q factor of 17, maintaining "constant Q filtering", + * and sum energy and length over non null combs */ + if (17. * xx < candidate[l]->ecomb[k]) { + candidate[l]->ecomb[k] = peaks[position].ebin; + candidate[l]->ene += /* ecomb rounded to nearest int */ + POW (newmag->data[(uint_t) FLOOR (candidate[l]->ecomb[k] + .5)], + 0.25); + candidate[l]->len += 1. / curlen; + } else + candidate[l]->ecomb[k] = 0.; + } + /* punishment */ + /*if (candidate[l]->len<0.6) + candidate[l]->ene=0.; */ + /* remember best candidate energy (in polyphonic, could check for + * tmpene*1.1 < candidate->ene to reduce jumps towards low frequencies) */ + if (tmpene < candidate[l]->ene) { + tmpl = l; + tmpene = candidate[l]->ene; + } + } + //p->candidates=candidate; + //p->peaks=peaks; + p->goodcandidate = tmpl; +} + +/** T=quadpick(X): return indices of elements of X which are peaks and positive + * exact peak positions are retrieved by quadratic interpolation + * + * \bug peak-picking too picky, sometimes counts too many peaks ? + */ +uint_t +aubio_pitchmcomb_quadpick (aubio_spectralpeak_t * spectral_peaks, const fvec_t * X) +{ + uint_t j, ispeak, count = 0; + for (j = 1; j < X->length - 1; j++) { + ispeak = fvec_peakpick (X, j); + if (ispeak) { + count += ispeak; + spectral_peaks[count - 1].bin = j; + spectral_peaks[count - 1].ebin = fvec_quadratic_peak_pos (X, j); + } + } + return count; +} + +/* get predominant partial */ +uint_t +aubio_pitchmcomb_get_root_peak (aubio_spectralpeak_t * peaks, uint_t length) +{ + uint_t i, pos = 0; + smpl_t tmp = 0.; + for (i = 0; i < length; i++) + if (tmp <= peaks[i].mag) { + pos = i; + tmp = peaks[i].mag; + } + return pos; +} + +#if 0 +void +aubio_pitchmcomb_sort_peak (aubio_spectralpeak_t * peaks, uint_t nbins) +{ + qsort (peaks, nbins, sizeof (aubio_spectralpeak_t), + aubio_pitchmcomb_sort_peak_comp); +} + +static sint_t +aubio_pitchmcomb_sort_peak_comp (const void *x, const void *y) +{ + return (((aubio_spectralpeak_t *) y)->mag - + ((aubio_spectralpeak_t *) x)->mag); +} + + +void +aubio_pitchmcomb_sort_cand_ene (aubio_spectralcandidate_t ** candidates, + uint_t nbins) +{ + uint_t cur = 0; + uint_t run = 0; + for (cur = 0; cur < nbins; cur++) { + for (run = cur + 1; run < nbins; run++) { + if (candidates[run]->ene > candidates[cur]->ene) + CAND_SWAP (candidates[run], candidates[cur]); + } + } +} + +void +aubio_pitchmcomb_sort_cand_freq (aubio_spectralcandidate_t ** candidates, + uint_t nbins) +{ + uint_t cur = 0; + uint_t run = 0; + for (cur = 0; cur < nbins; cur++) { + for (run = cur + 1; run < nbins; run++) { + if (candidates[run]->ebin < candidates[cur]->ebin) + CAND_SWAP (candidates[run], candidates[cur]); + } + } +} +#endif + +aubio_pitchmcomb_t * +new_aubio_pitchmcomb (uint_t bufsize, uint_t hopsize) +{ + aubio_pitchmcomb_t *p = AUBIO_NEW (aubio_pitchmcomb_t); + /* bug: should check if size / 8 > post+pre+1 */ + uint_t i, j; + uint_t spec_size; + p->spec_partition = 2; + p->ncand = 5; + p->npartials = 5; + p->cutoff = 1.; + p->threshold = 0.01; + p->win_post = 8; + p->win_pre = 7; + // p->tau = samplerate/bufsize; + p->alpha = 9.; + p->goodcandidate = 0; + p->phasefreq = bufsize / hopsize / TWO_PI; + p->phasediff = TWO_PI * hopsize / bufsize; + spec_size = bufsize / p->spec_partition + 1; + //p->pickerfn = quadpick; + //p->biquad = new_biquad(0.1600,0.3200,0.1600, -0.5949, 0.2348); + /* allocate temp memory */ + p->newmag = new_fvec (spec_size); + /* array for median */ + p->scratch = new_fvec (spec_size); + /* array for phase */ + p->theta = new_fvec (spec_size); + /* array for adaptative threshold */ + p->scratch2 = new_fvec (p->win_post + p->win_pre + 1); + /* array of spectral peaks */ + p->peaks = AUBIO_ARRAY (aubio_spectralpeak_t, spec_size); + for (i = 0; i < spec_size; i++) { + p->peaks[i].bin = 0.; + p->peaks[i].ebin = 0.; + p->peaks[i].mag = 0.; + } + /* array of pointers to spectral candidates */ + p->candidates = AUBIO_ARRAY (aubio_spectralcandidate_t *, p->ncand); + for (i = 0; i < p->ncand; i++) { + p->candidates[i] = AUBIO_NEW (aubio_spectralcandidate_t); + p->candidates[i]->ecomb = AUBIO_ARRAY (smpl_t, spec_size); + for (j = 0; j < spec_size; j++) { + p->candidates[i]->ecomb[j] = 0.; + } + p->candidates[i]->ene = 0.; + p->candidates[i]->ebin = 0.; + p->candidates[i]->len = 0.; + } + return p; +} + + +void +del_aubio_pitchmcomb (aubio_pitchmcomb_t * p) +{ + uint_t i; + del_fvec (p->newmag); + del_fvec (p->scratch); + del_fvec (p->theta); + del_fvec (p->scratch2); + AUBIO_FREE (p->peaks); + for (i = 0; i < p->ncand; i++) { + AUBIO_FREE (p->candidates[i]->ecomb); + AUBIO_FREE (p->candidates[i]); + } + AUBIO_FREE (p->candidates); + AUBIO_FREE (p); +} diff --git a/deps/aubio/src/pitch/pitchmcomb.h b/deps/aubio/src/pitch/pitchmcomb.h new file mode 100644 index 00000000..88f117f2 --- /dev/null +++ b/deps/aubio/src/pitch/pitchmcomb.h @@ -0,0 +1,77 @@ +/* + Copyright (C) 2003-2013 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** \file + + Pitch detection using multiple-comb filter + + This fundamental frequency estimation algorithm implements spectral + flattening, multi-comb filtering and peak histogramming. + + This method was designed by Juan P. Bello and described in: + + Juan-Pablo Bello. ``Towards the Automated Analysis of Simple Polyphonic + Music''. PhD thesis, Centre for Digital Music, Queen Mary University of + London, London, UK, 2003. + + \example pitch/test-pitchmcomb.c + +*/ + +#ifndef AUBIO_PITCHMCOMB_H +#define AUBIO_PITCHMCOMB_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** pitch detection object */ +typedef struct _aubio_pitchmcomb_t aubio_pitchmcomb_t; + +/** execute pitch detection on an input spectral frame + + \param p pitch detection object as returned by new_aubio_pitchmcomb + \param in_fftgrain input signal spectrum as computed by aubio_pvoc_do + \param out_cands pitch candidate frequenciess, in bins + +*/ +void aubio_pitchmcomb_do (aubio_pitchmcomb_t * p, const cvec_t * in_fftgrain, + fvec_t * out_cands); + +/** creation of the pitch detection object + + \param buf_size size of the input buffer to analyse + \param hop_size step size between two consecutive analysis instant + +*/ +aubio_pitchmcomb_t *new_aubio_pitchmcomb (uint_t buf_size, uint_t hop_size); + +/** deletion of the pitch detection object + + \param p pitch detection object as returned by new_aubio_pitchfcomb + +*/ +void del_aubio_pitchmcomb (aubio_pitchmcomb_t * p); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_PITCHMCOMB_H */ diff --git a/deps/aubio/src/pitch/pitchschmitt.c b/deps/aubio/src/pitch/pitchschmitt.c new file mode 100644 index 00000000..06a34e8e --- /dev/null +++ b/deps/aubio/src/pitch/pitchschmitt.c @@ -0,0 +1,119 @@ +/* + Copyright (C) 2004, 2005 Mario Lang + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "fvec.h" +#include "pitch/pitchschmitt.h" + +smpl_t aubio_schmittS16LE (aubio_pitchschmitt_t * p, uint_t nframes, + signed short int *indata); + +struct _aubio_pitchschmitt_t +{ + uint_t blockSize; + uint_t rate; + signed short int *schmittBuffer; + signed short int *schmittPointer; + signed short int *buf; +}; + +aubio_pitchschmitt_t * +new_aubio_pitchschmitt (uint_t size) +{ + aubio_pitchschmitt_t *p = AUBIO_NEW (aubio_pitchschmitt_t); + p->blockSize = size; + p->schmittBuffer = AUBIO_ARRAY (signed short int, p->blockSize); + p->buf = AUBIO_ARRAY (signed short int, p->blockSize); + p->schmittPointer = p->schmittBuffer; + return p; +} + +void +aubio_pitchschmitt_do (aubio_pitchschmitt_t * p, const fvec_t * input, + fvec_t * output) +{ + uint_t j; + for (j = 0; j < input->length; j++) { + p->buf[j] = input->data[j] * 32768.; + } + output->data[0] = aubio_schmittS16LE (p, input->length, p->buf); +} + +smpl_t +aubio_schmittS16LE (aubio_pitchschmitt_t * p, uint_t nframes, + signed short int *indata) +{ + uint_t i, j; + uint_t blockSize = p->blockSize; + signed short int *schmittBuffer = p->schmittBuffer; + signed short int *schmittPointer = p->schmittPointer; + + smpl_t period = 0., trigfact = 0.6; + + for (i = 0; i < nframes; i++) { + *schmittPointer++ = indata[i]; + if (schmittPointer - schmittBuffer >= (sint_t) blockSize) { + sint_t endpoint, startpoint, t1, t2, A1, A2, tc, schmittTriggered; + + schmittPointer = schmittBuffer; + + for (j = 0, A1 = 0, A2 = 0; j < blockSize; j++) { + if (schmittBuffer[j] > 0 && A1 < schmittBuffer[j]) + A1 = schmittBuffer[j]; + if (schmittBuffer[j] < 0 && A2 < -schmittBuffer[j]) + A2 = -schmittBuffer[j]; + } + t1 = (sint_t) (A1 * trigfact + 0.5); + t2 = -(sint_t) (A2 * trigfact + 0.5); + startpoint = 0; + for (j = 1; j < blockSize && schmittBuffer[j] <= t1; j++); + for ( ; j < blockSize - 1 && !(schmittBuffer[j] >= t2 && + schmittBuffer[j + 1] < t2); j++); + startpoint = j; + schmittTriggered = 0; + endpoint = startpoint + 1; + for (j = startpoint, tc = 0; j < blockSize; j++) { + if (!schmittTriggered) { + schmittTriggered = (schmittBuffer[j] >= t1); + } else if (schmittBuffer[j] >= t2 && schmittBuffer[j + 1] < t2) { + endpoint = j; + tc++; + schmittTriggered = 0; + } + } + if ((endpoint > startpoint) && (tc > 0)) { + period = (smpl_t) (endpoint - startpoint) / tc; + } + } + } + + p->schmittBuffer = schmittBuffer; + p->schmittPointer = schmittPointer; + return period; +} + +void +del_aubio_pitchschmitt (aubio_pitchschmitt_t * p) +{ + AUBIO_FREE (p->schmittBuffer); + AUBIO_FREE (p->buf); + AUBIO_FREE (p); +} diff --git a/deps/aubio/src/pitch/pitchschmitt.h b/deps/aubio/src/pitch/pitchschmitt.h new file mode 100644 index 00000000..db952c34 --- /dev/null +++ b/deps/aubio/src/pitch/pitchschmitt.h @@ -0,0 +1,75 @@ +/* + Copyright (C) 2003-2013 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** \file + + Pitch detection using a Schmitt trigger + + This pitch extraction method implements a Schmitt trigger to estimate the + period of a signal. + + This file was derived from the tuneit project, written by Mario Lang to + detect the fundamental frequency of a sound. + + See http://delysid.org/tuneit.html + + \example pitch/test-pitchschmitt.c + +*/ + +#ifndef AUBIO_PITCHSCHMITT_H +#define AUBIO_PITCHSCHMITT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** pitch detection object */ +typedef struct _aubio_pitchschmitt_t aubio_pitchschmitt_t; + +/** execute pitch detection on an input buffer + + \param p pitch detection object as returned by new_aubio_pitchschmitt + \param samples_in input signal vector (length as specified at creation time) + \param cands_out pitch period estimates, in samples + +*/ +void aubio_pitchschmitt_do (aubio_pitchschmitt_t * p, const fvec_t * samples_in, + fvec_t * cands_out); + +/** creation of the pitch detection object + + \param buf_size size of the input buffer to analyse + +*/ +aubio_pitchschmitt_t *new_aubio_pitchschmitt (uint_t buf_size); + +/** deletion of the pitch detection object + + \param p pitch detection object as returned by new_aubio_pitchschmitt + +*/ +void del_aubio_pitchschmitt (aubio_pitchschmitt_t * p); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_PITCHSCHMITT_H */ diff --git a/deps/aubio/src/pitch/pitchspecacf.c b/deps/aubio/src/pitch/pitchspecacf.c new file mode 100644 index 00000000..170cfa32 --- /dev/null +++ b/deps/aubio/src/pitch/pitchspecacf.c @@ -0,0 +1,116 @@ +/* + Copyright (C) 2013 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "fvec.h" +#include "cvec.h" +#include "mathutils.h" +#include "spectral/fft.h" +#include "pitch/pitchspecacf.h" + +/** pitch specacf structure */ +struct _aubio_pitchspecacf_t +{ + fvec_t *win; /**< temporal weighting window */ + fvec_t *winput; /**< windowed spectrum */ + aubio_fft_t *fft; /**< fft object to compute*/ + fvec_t *fftout; /**< Fourier transform output */ + fvec_t *sqrmag; /**< square magnitudes */ + fvec_t *acf; /**< auto correlation function */ + smpl_t tol; /**< tolerance */ + smpl_t confidence; /**< confidence */ +}; + +aubio_pitchspecacf_t * +new_aubio_pitchspecacf (uint_t bufsize) +{ + aubio_pitchspecacf_t *p = AUBIO_NEW (aubio_pitchspecacf_t); + p->fft = new_aubio_fft (bufsize); + if (!p->fft) goto beach; + p->win = new_aubio_window ("hanningz", bufsize); + p->winput = new_fvec (bufsize); + p->fftout = new_fvec (bufsize); + p->sqrmag = new_fvec (bufsize); + p->acf = new_fvec (bufsize / 2 + 1); + p->tol = 1.; + p->confidence = 0.; + return p; + +beach: + AUBIO_FREE(p); + return NULL; +} + +void +aubio_pitchspecacf_do (aubio_pitchspecacf_t * p, const fvec_t * input, fvec_t * output) +{ + uint_t l, tau; + fvec_t *fftout = p->fftout; + // window the input + for (l = 0; l < input->length; l++) { + p->winput->data[l] = p->win->data[l] * input->data[l]; + } + // get the real / imag parts of its fft + aubio_fft_do_complex (p->fft, p->winput, fftout); + for (l = 0; l < input->length / 2 + 1; l++) { + p->sqrmag->data[l] = SQR(fftout->data[l]); + } + // get the real / imag parts of the fft of the squared magnitude + aubio_fft_do_complex (p->fft, p->sqrmag, fftout); + // copy real part to acf + for (l = 0; l < fftout->length / 2 + 1; l++) { + p->acf->data[l] = fftout->data[l]; + } + // get the minimum + tau = fvec_min_elem (p->acf); + // get the interpolated minimum + output->data[0] = fvec_quadratic_peak_pos (p->acf, tau) * 2.; +} + +void +del_aubio_pitchspecacf (aubio_pitchspecacf_t * p) +{ + del_fvec (p->win); + del_fvec (p->winput); + del_aubio_fft (p->fft); + del_fvec (p->sqrmag); + del_fvec (p->fftout); + del_fvec (p->acf); + AUBIO_FREE (p); +} + +smpl_t +aubio_pitchspecacf_get_confidence (const aubio_pitchspecacf_t * o) { + // no confidence for now + return o->confidence; +} + +uint_t +aubio_pitchspecacf_set_tolerance (aubio_pitchspecacf_t * p, smpl_t tol) +{ + p->tol = tol; + return 0; +} + +smpl_t +aubio_pitchspecacf_get_tolerance (const aubio_pitchspecacf_t * p) +{ + return p->tol; +} diff --git a/deps/aubio/src/pitch/pitchspecacf.h b/deps/aubio/src/pitch/pitchspecacf.h new file mode 100644 index 00000000..e3c9c4c1 --- /dev/null +++ b/deps/aubio/src/pitch/pitchspecacf.h @@ -0,0 +1,103 @@ +/* + Copyright (C) 2013 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** \file + + Pitch detection using spectral auto correlation + + This algorithm implements pitch detection by computing the autocorrelation + function as the cosine transform of the square spectral magnitudes. + + Anssi Klapuri. Qualitative and quantitative aspects in the design of + periodicity esti- mation algorithms. In Proceedings of the European Signal + Processing Conference (EUSIPCO), 2000. + + Paul Brossier, [Automatic annotation of musical audio for interactive + systems](http://aubio.org/phd/), Chapter 3, Pitch Analysis, Autocorrelation, + pp. 75-77, PhD thesis, Centre for Digital music, Queen Mary University of + London, London, UK, 2006. + + \example pitch/test-pitchspecacf.c + +*/ + +#ifndef AUBIO_PITCHSPECACF_H +#define AUBIO_PITCHSPECACF_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** pitch detection object */ +typedef struct _aubio_pitchspecacf_t aubio_pitchspecacf_t; + +/** execute pitch detection on an input buffer + + \param o pitch detection object as returned by new_aubio_pitchspecacf + \param samples_in input signal vector (length as specified at creation time) + \param cands_out pitch period candidates, in samples + +*/ +void aubio_pitchspecacf_do (aubio_pitchspecacf_t * o, const fvec_t * samples_in, fvec_t * cands_out); +/** creation of the pitch detection object + + \param buf_size size of the input buffer to analyse + +*/ +aubio_pitchspecacf_t *new_aubio_pitchspecacf (uint_t buf_size); +/** deletion of the pitch detection object + + \param o pitch detection object as returned by new_aubio_pitchspecacf() + +*/ +void del_aubio_pitchspecacf (aubio_pitchspecacf_t * o); + +/** get tolerance parameter for `specacf` pitch detection object + + \param o pitch detection object + + \return tolerance parameter for minima selection [default 1.] + +*/ +smpl_t aubio_pitchspecacf_get_tolerance (const aubio_pitchspecacf_t * o); + +/** set tolerance parameter for `specacf` pitch detection object + + \param o pitch detection object + \param tol tolerance parameter for minima selection [default 1.] + + \return `1` on error, `0` on success + +*/ +uint_t aubio_pitchspecacf_set_tolerance (aubio_pitchspecacf_t * o, smpl_t tol); + +/** get currenct confidence for `specacf` pitch detection object + + \param o pitch detection object + \return confidence parameter + +*/ +smpl_t aubio_pitchspecacf_get_confidence (const aubio_pitchspecacf_t * o); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_PITCHSPECACF_H */ diff --git a/deps/aubio/src/pitch/pitchyin.c b/deps/aubio/src/pitch/pitchyin.c new file mode 100644 index 00000000..85b4566b --- /dev/null +++ b/deps/aubio/src/pitch/pitchyin.c @@ -0,0 +1,189 @@ +/* + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/* This algorithm was developed by A. de Cheveigné and H. Kawahara and + * published in: + * + * de Cheveigné, A., Kawahara, H. (2002) "YIN, a fundamental frequency + * estimator for speech and music", J. Acoust. Soc. Am. 111, 1917-1930. + * + * see http://recherche.ircam.fr/equipes/pcm/pub/people/cheveign.html + */ + +#include "aubio_priv.h" +#include "fvec.h" +#include "mathutils.h" +#include "pitch/pitchyin.h" + +struct _aubio_pitchyin_t +{ + fvec_t *yin; + smpl_t tol; + uint_t peak_pos; +}; + +#if 0 +/** compute difference function + + \param input input signal + \param yinbuf output buffer to store difference function (half shorter than input) + +*/ +void aubio_pitchyin_diff (fvec_t * input, fvec_t * yinbuf); + +/** in place computation of the YIN cumulative normalised function + + \param yinbuf input signal (a square difference function), also used to store function + +*/ +void aubio_pitchyin_getcum (fvec_t * yinbuf); + +/** detect pitch in a YIN function + + \param yinbuf input buffer as computed by aubio_pitchyin_getcum + +*/ +uint_t aubio_pitchyin_getpitch (const fvec_t * yinbuf); +#endif + +aubio_pitchyin_t * +new_aubio_pitchyin (uint_t bufsize) +{ + aubio_pitchyin_t *o = AUBIO_NEW (aubio_pitchyin_t); + o->yin = new_fvec (bufsize / 2); + o->tol = 0.15; + o->peak_pos = 0; + return o; +} + +void +del_aubio_pitchyin (aubio_pitchyin_t * o) +{ + del_fvec (o->yin); + AUBIO_FREE (o); +} + +#if 0 +/* outputs the difference function */ +void +aubio_pitchyin_diff (fvec_t * input, fvec_t * yin) +{ + uint_t j, tau; + smpl_t tmp; + for (tau = 0; tau < yin->length; tau++) { + yin->data[tau] = 0.; + } + for (tau = 1; tau < yin->length; tau++) { + for (j = 0; j < yin->length; j++) { + tmp = input->data[j] - input->data[j + tau]; + yin->data[tau] += SQR (tmp); + } + } +} + +/* cumulative mean normalized difference function */ +void +aubio_pitchyin_getcum (fvec_t * yin) +{ + uint_t tau; + smpl_t tmp = 0.; + yin->data[0] = 1.; + //AUBIO_DBG("%f\t",yin->data[0]); + for (tau = 1; tau < yin->length; tau++) { + tmp += yin->data[tau]; + yin->data[tau] *= tau / tmp; + //AUBIO_DBG("%f\t",yin->data[tau]); + } + //AUBIO_DBG("\n"); +} + +uint_t +aubio_pitchyin_getpitch (const fvec_t * yin) +{ + uint_t tau = 1; + do { + if (yin->data[tau] < 0.1) { + while (yin->data[tau + 1] < yin->data[tau]) { + tau++; + } + return tau; + } + tau++; + } while (tau < yin->length); + //AUBIO_DBG("No pitch found"); + return 0; +} +#endif + +/* all the above in one */ +void +aubio_pitchyin_do (aubio_pitchyin_t * o, const fvec_t * input, fvec_t * out) +{ + const smpl_t tol = o->tol; + fvec_t* yin = o->yin; + const smpl_t *input_data = input->data; + const uint_t length = yin->length; + smpl_t *yin_data = yin->data; + uint_t j, tau; + sint_t period; + smpl_t tmp, tmp2 = 0.; + + yin_data[0] = 1.; + for (tau = 1; tau < length; tau++) { + yin_data[tau] = 0.; + for (j = 0; j < length; j++) { + tmp = input_data[j] - input_data[j + tau]; + yin_data[tau] += SQR (tmp); + } + tmp2 += yin_data[tau]; + if (tmp2 != 0) { + yin->data[tau] *= tau / tmp2; + } else { + yin->data[tau] = 1.; + } + period = tau - 3; + if (tau > 4 && (yin_data[period] < tol) && + (yin_data[period] < yin_data[period + 1])) { + o->peak_pos = (uint_t)period; + out->data[0] = fvec_quadratic_peak_pos (yin, o->peak_pos); + return; + } + } + o->peak_pos = (uint_t)fvec_min_elem (yin); + out->data[0] = fvec_quadratic_peak_pos (yin, o->peak_pos); +} + +smpl_t +aubio_pitchyin_get_confidence (aubio_pitchyin_t * o) { + return 1. - o->yin->data[o->peak_pos]; +} + +uint_t +aubio_pitchyin_set_tolerance (aubio_pitchyin_t * o, smpl_t tol) +{ + o->tol = tol; + return 0; +} + +smpl_t +aubio_pitchyin_get_tolerance (aubio_pitchyin_t * o) +{ + return o->tol; +} diff --git a/deps/aubio/src/pitch/pitchyin.h b/deps/aubio/src/pitch/pitchyin.h new file mode 100644 index 00000000..fa32b8da --- /dev/null +++ b/deps/aubio/src/pitch/pitchyin.h @@ -0,0 +1,100 @@ +/* + Copyright (C) 2003-2013 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** \file + + Pitch detection using the YIN algorithm + + This algorithm was developed by A. de Cheveigne and H. Kawahara and + published in: + + De Cheveigné, A., Kawahara, H. (2002) "YIN, a fundamental frequency + estimator for speech and music", J. Acoust. Soc. Am. 111, 1917-1930. + + see http://recherche.ircam.fr/equipes/pcm/pub/people/cheveign.html + http://recherche.ircam.fr/equipes/pcm/cheveign/ps/2002_JASA_YIN_proof.pdf + + \example pitch/test-pitchyin.c + +*/ + +#ifndef AUBIO_PITCHYIN_H +#define AUBIO_PITCHYIN_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** pitch detection object */ +typedef struct _aubio_pitchyin_t aubio_pitchyin_t; + +/** creation of the pitch detection object + + \param buf_size size of the input buffer to analyse + +*/ +aubio_pitchyin_t *new_aubio_pitchyin (uint_t buf_size); + +/** deletion of the pitch detection object + + \param o pitch detection object as returned by new_aubio_pitchyin() + +*/ +void del_aubio_pitchyin (aubio_pitchyin_t * o); + +/** execute pitch detection an input buffer + + \param o pitch detection object as returned by new_aubio_pitchyin() + \param samples_in input signal vector (length as specified at creation time) + \param cands_out pitch period candidates, in samples + +*/ +void aubio_pitchyin_do (aubio_pitchyin_t * o, const fvec_t * samples_in, fvec_t * cands_out); + + +/** set tolerance parameter for YIN algorithm + + \param o YIN pitch detection object + \param tol tolerance parameter for minima selection [default 0.15] + +*/ +uint_t aubio_pitchyin_set_tolerance (aubio_pitchyin_t * o, smpl_t tol); + +/** get tolerance parameter for YIN algorithm + + \param o YIN pitch detection object + \return tolerance parameter for minima selection [default 0.15] + +*/ +smpl_t aubio_pitchyin_get_tolerance (aubio_pitchyin_t * o); + +/** get current confidence of YIN algorithm + + \param o YIN pitch detection object + \return confidence parameter + +*/ +smpl_t aubio_pitchyin_get_confidence (aubio_pitchyin_t * o); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_PITCHYIN_H */ diff --git a/deps/aubio/src/pitch/pitchyinfast.c b/deps/aubio/src/pitch/pitchyinfast.c new file mode 100644 index 00000000..b2dcadcd --- /dev/null +++ b/deps/aubio/src/pitch/pitchyinfast.c @@ -0,0 +1,201 @@ +/* + Copyright (C) 2003-2017 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/* This algorithm was developed by A. de Cheveigné and H. Kawahara and + * published in: + * + * de Cheveigné, A., Kawahara, H. (2002) "YIN, a fundamental frequency + * estimator for speech and music", J. Acoust. Soc. Am. 111, 1917-1930. + * + * see http://recherche.ircam.fr/equipes/pcm/pub/people/cheveign.html + */ + +#include "aubio_priv.h" +#include "fvec.h" +#include "mathutils.h" +#include "cvec.h" +#include "spectral/fft.h" +#include "pitch/pitchyinfast.h" + +struct _aubio_pitchyinfast_t +{ + fvec_t *yin; + smpl_t tol; + uint_t peak_pos; + fvec_t *tmpdata; + fvec_t *sqdiff; + fvec_t *kernel; + fvec_t *samples_fft; + fvec_t *kernel_fft; + aubio_fft_t *fft; +}; + +aubio_pitchyinfast_t * +new_aubio_pitchyinfast (uint_t bufsize) +{ + aubio_pitchyinfast_t *o = AUBIO_NEW (aubio_pitchyinfast_t); + o->yin = new_fvec (bufsize / 2); + o->tmpdata = new_fvec (bufsize); + o->sqdiff = new_fvec (bufsize / 2); + o->kernel = new_fvec (bufsize); + o->samples_fft = new_fvec (bufsize); + o->kernel_fft = new_fvec (bufsize); + o->fft = new_aubio_fft (bufsize); + if (!o->yin || !o->tmpdata || !o->tmpdata || !o->sqdiff + || !o->kernel || !o->samples_fft || !o->kernel || !o->fft) + { + del_aubio_pitchyinfast(o); + return NULL; + } + o->tol = 0.15; + o->peak_pos = 0; + return o; +} + +void +del_aubio_pitchyinfast (aubio_pitchyinfast_t * o) +{ + if (o->yin) + del_fvec (o->yin); + if (o->tmpdata) + del_fvec (o->tmpdata); + if (o->sqdiff) + del_fvec (o->sqdiff); + if (o->kernel) + del_fvec (o->kernel); + if (o->samples_fft) + del_fvec (o->samples_fft); + if (o->kernel_fft) + del_fvec (o->kernel_fft); + if (o->fft) + del_aubio_fft (o->fft); + AUBIO_FREE (o); +} + +/* all the above in one */ +void +aubio_pitchyinfast_do (aubio_pitchyinfast_t * o, const fvec_t * input, fvec_t * out) +{ + const smpl_t tol = o->tol; + fvec_t* yin = o->yin; + const uint_t length = yin->length; + uint_t B = o->tmpdata->length; + uint_t W = o->yin->length; // B / 2 + fvec_t tmp_slice, kernel_ptr; + uint_t tau; + sint_t period; + smpl_t tmp2 = 0.; + + // compute r_t(0) + r_t+tau(0) + { + fvec_t *squares = o->tmpdata; + fvec_weighted_copy(input, input, squares); +#if 0 + for (tau = 0; tau < W; tau++) { + tmp_slice.data = squares->data + tau; + tmp_slice.length = W; + o->sqdiff->data[tau] = fvec_sum(&tmp_slice); + } +#else + tmp_slice.data = squares->data; + tmp_slice.length = W; + o->sqdiff->data[0] = fvec_sum(&tmp_slice); + for (tau = 1; tau < W; tau++) { + o->sqdiff->data[tau] = o->sqdiff->data[tau-1]; + o->sqdiff->data[tau] -= squares->data[tau-1]; + o->sqdiff->data[tau] += squares->data[W+tau-1]; + } +#endif + fvec_add(o->sqdiff, o->sqdiff->data[0]); + } + // compute r_t(tau) = -2.*ifft(fft(samples)*fft(samples[W-1::-1])) + { + fvec_t *compmul = o->tmpdata; + fvec_t *rt_of_tau = o->samples_fft; + aubio_fft_do_complex(o->fft, input, o->samples_fft); + // build kernel, take a copy of first half of samples + tmp_slice.data = input->data; + tmp_slice.length = W; + kernel_ptr.data = o->kernel->data + 1; + kernel_ptr.length = W; + fvec_copy(&tmp_slice, &kernel_ptr); + // reverse them + fvec_rev(&kernel_ptr); + // compute fft(kernel) + aubio_fft_do_complex(o->fft, o->kernel, o->kernel_fft); + // compute complex product + compmul->data[0] = o->kernel_fft->data[0] * o->samples_fft->data[0]; + for (tau = 1; tau < W; tau++) { + compmul->data[tau] = o->kernel_fft->data[tau] * o->samples_fft->data[tau]; + compmul->data[tau] -= o->kernel_fft->data[B-tau] * o->samples_fft->data[B-tau]; + } + compmul->data[W] = o->kernel_fft->data[W] * o->samples_fft->data[W]; + for (tau = 1; tau < W; tau++) { + compmul->data[B-tau] = o->kernel_fft->data[B-tau] * o->samples_fft->data[tau]; + compmul->data[B-tau] += o->kernel_fft->data[tau] * o->samples_fft->data[B-tau]; + } + // compute inverse fft + aubio_fft_rdo_complex(o->fft, compmul, rt_of_tau); + // compute square difference r_t(tau) = sqdiff - 2 * r_t_tau[W-1:-1] + for (tau = 0; tau < W; tau++) { + yin->data[tau] = o->sqdiff->data[tau] - 2. * rt_of_tau->data[tau+W]; + } + } + + // now build yin and look for first minimum + fvec_zeros(out); + yin->data[0] = 1.; + for (tau = 1; tau < length; tau++) { + tmp2 += yin->data[tau]; + if (tmp2 != 0) { + yin->data[tau] *= tau / tmp2; + } else { + yin->data[tau] = 1.; + } + period = tau - 3; + if (tau > 4 && (yin->data[period] < tol) && + (yin->data[period] < yin->data[period + 1])) { + o->peak_pos = (uint_t)period; + out->data[0] = fvec_quadratic_peak_pos (yin, o->peak_pos); + return; + } + } + // use global minimum + o->peak_pos = (uint_t)fvec_min_elem (yin); + out->data[0] = fvec_quadratic_peak_pos (yin, o->peak_pos); +} + +smpl_t +aubio_pitchyinfast_get_confidence (aubio_pitchyinfast_t * o) { + return 1. - o->yin->data[o->peak_pos]; +} + +uint_t +aubio_pitchyinfast_set_tolerance (aubio_pitchyinfast_t * o, smpl_t tol) +{ + o->tol = tol; + return 0; +} + +smpl_t +aubio_pitchyinfast_get_tolerance (aubio_pitchyinfast_t * o) +{ + return o->tol; +} diff --git a/deps/aubio/src/pitch/pitchyinfast.h b/deps/aubio/src/pitch/pitchyinfast.h new file mode 100644 index 00000000..abb81393 --- /dev/null +++ b/deps/aubio/src/pitch/pitchyinfast.h @@ -0,0 +1,102 @@ +/* + Copyright (C) 2003-2017 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** \file + + Pitch detection using YIN algorithm (fast implementation) + + This algorithm was developed by A. de Cheveigne and H. Kawahara and + published in: + + De Cheveigné, A., Kawahara, H. (2002) "YIN, a fundamental frequency + estimator for speech and music", J. Acoust. Soc. Am. 111, 1917-1930. + + This implementation compute the autocorrelation function using time domain + convolution computed in the spectral domain. + + see http://recherche.ircam.fr/equipes/pcm/pub/people/cheveign.html + http://recherche.ircam.fr/equipes/pcm/cheveign/ps/2002_JASA_YIN_proof.pdf + +*/ + +#ifndef AUBIO_PITCHYINFAST_H +#define AUBIO_PITCHYINFAST_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** pitch detection object */ +typedef struct _aubio_pitchyinfast_t aubio_pitchyinfast_t; + +/** creation of the pitch detection object + + \param buf_size size of the input buffer to analyse + +*/ +aubio_pitchyinfast_t *new_aubio_pitchyinfast (uint_t buf_size); + +/** deletion of the pitch detection object + + \param o pitch detection object as returned by new_aubio_pitchyin() + +*/ +void del_aubio_pitchyinfast (aubio_pitchyinfast_t * o); + +/** execute pitch detection an input buffer + + \param o pitch detection object as returned by new_aubio_pitchyin() + \param samples_in input signal vector (length as specified at creation time) + \param cands_out pitch period candidates, in samples + +*/ +void aubio_pitchyinfast_do (aubio_pitchyinfast_t * o, const fvec_t * samples_in, fvec_t * cands_out); + + +/** set tolerance parameter for YIN algorithm + + \param o YIN pitch detection object + \param tol tolerance parameter for minima selection [default 0.15] + +*/ +uint_t aubio_pitchyinfast_set_tolerance (aubio_pitchyinfast_t * o, smpl_t tol); + +/** get tolerance parameter for YIN algorithm + + \param o YIN pitch detection object + \return tolerance parameter for minima selection [default 0.15] + +*/ +smpl_t aubio_pitchyinfast_get_tolerance (aubio_pitchyinfast_t * o); + +/** get current confidence of YIN algorithm + + \param o YIN pitch detection object + \return confidence parameter + +*/ +smpl_t aubio_pitchyinfast_get_confidence (aubio_pitchyinfast_t * o); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_PITCHYINFAST_H */ + diff --git a/deps/aubio/src/pitch/pitchyinfft.c b/deps/aubio/src/pitch/pitchyinfft.c new file mode 100644 index 00000000..b613f60e --- /dev/null +++ b/deps/aubio/src/pitch/pitchyinfft.c @@ -0,0 +1,208 @@ +/* + Copyright (C) 2003-2013 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "fvec.h" +#include "cvec.h" +#include "mathutils.h" +#include "spectral/fft.h" +#include "pitch/pitchyinfft.h" + +/** pitch yinfft structure */ +struct _aubio_pitchyinfft_t +{ + fvec_t *win; /**< temporal weighting window */ + fvec_t *winput; /**< windowed spectrum */ + fvec_t *sqrmag; /**< square difference function */ + fvec_t *weight; /**< spectral weighting window (psychoacoustic model) */ + fvec_t *fftout; /**< Fourier transform output */ + aubio_fft_t *fft; /**< fft object to compute square difference function */ + fvec_t *yinfft; /**< Yin function */ + smpl_t tol; /**< Yin tolerance */ + uint_t peak_pos; /**< currently selected peak pos*/ + uint_t short_period; /** shortest period under which to check for octave error */ +}; + +static const smpl_t freqs[] = { + 0., 20., 25., 31.5, 40., 50., 63., 80., 100., 125., + 160., 200., 250., 315., 400., 500., 630., 800., 1000., 1250., + 1600., 2000., 2500., 3150., 4000., 5000., 6300., 8000., 9000., 10000., + 12500., 15000., 20000., 25100., -1. +}; + +static const smpl_t weight[] = { + -75.8, -70.1, -60.8, -52.1, -44.2, -37.5, -31.3, -25.6, -20.9, -16.5, + -12.6, -9.60, -7.00, -4.70, -3.00, -1.80, -0.80, -0.20, -0.00, 0.50, + 1.60, 3.20, 5.40, 7.80, 8.10, 5.30, -2.40, -11.1, -12.8, -12.2, + -7.40, -17.8, -17.8, -17.8 +}; + +aubio_pitchyinfft_t * +new_aubio_pitchyinfft (uint_t samplerate, uint_t bufsize) +{ + uint_t i = 0, j = 1; + smpl_t freq = 0, a0 = 0, a1 = 0, f0 = 0, f1 = 0; + aubio_pitchyinfft_t *p = AUBIO_NEW (aubio_pitchyinfft_t); + p->winput = new_fvec (bufsize); + p->fft = new_aubio_fft (bufsize); + if (!p->fft) goto beach; + p->fftout = new_fvec (bufsize); + p->sqrmag = new_fvec (bufsize); + p->yinfft = new_fvec (bufsize / 2 + 1); + p->tol = 0.85; + p->peak_pos = 0; + p->win = new_aubio_window ("hanningz", bufsize); + p->weight = new_fvec (bufsize / 2 + 1); + for (i = 0; i < p->weight->length; i++) { + freq = (smpl_t) i / (smpl_t) bufsize *(smpl_t) samplerate; + while (freq > freqs[j] && freqs[j] > 0) { + //AUBIO_DBG("freq %3.5f > %3.5f \tsamplerate %d (Hz) \t" + // "(weight length %d, bufsize %d) %d %d\n", freq, freqs[j], + // samplerate, p->weight->length, bufsize, i, j); + j += 1; + } + a0 = weight[j - 1]; + f0 = freqs[j - 1]; + a1 = weight[j]; + f1 = freqs[j]; + if (f0 == f1) { // just in case + p->weight->data[i] = a0; + } else if (f0 == 0) { // y = ax+b + p->weight->data[i] = (a1 - a0) / f1 * freq + a0; + } else { + p->weight->data[i] = (a1 - a0) / (f1 - f0) * freq + + (a0 - (a1 - a0) / (f1 / f0 - 1.)); + } + while (freq > freqs[j]) { + j += 1; + } + //AUBIO_DBG("%f\n",p->weight->data[i]); + p->weight->data[i] = DB2LIN (p->weight->data[i]); + //p->weight->data[i] = SQRT(DB2LIN(p->weight->data[i])); + } + // check for octave errors above 1300 Hz + p->short_period = (uint_t)ROUND(samplerate / 1300.); + return p; + +beach: + if (p->winput) del_fvec(p->winput); + AUBIO_FREE(p); + return NULL; +} + +void +aubio_pitchyinfft_do (aubio_pitchyinfft_t * p, const fvec_t * input, fvec_t * output) +{ + uint_t tau, l; + uint_t length = p->fftout->length; + uint_t halfperiod; + fvec_t *fftout = p->fftout; + fvec_t *yin = p->yinfft; + smpl_t tmp = 0., sum = 0.; + // window the input + fvec_weighted_copy(input, p->win, p->winput); + // get the real / imag parts of its fft + aubio_fft_do_complex (p->fft, p->winput, fftout); + // get the squared magnitude spectrum, applying some weight + p->sqrmag->data[0] = SQR(fftout->data[0]); + p->sqrmag->data[0] *= p->weight->data[0]; + for (l = 1; l < length / 2; l++) { + p->sqrmag->data[l] = SQR(fftout->data[l]) + SQR(fftout->data[length - l]); + p->sqrmag->data[l] *= p->weight->data[l]; + p->sqrmag->data[length - l] = p->sqrmag->data[l]; + } + p->sqrmag->data[length / 2] = SQR(fftout->data[length / 2]); + p->sqrmag->data[length / 2] *= p->weight->data[length / 2]; + // get sum of weighted squared mags + for (l = 0; l < length / 2 + 1; l++) { + sum += p->sqrmag->data[l]; + } + sum *= 2.; + // get the real / imag parts of the fft of the squared magnitude + aubio_fft_do_complex (p->fft, p->sqrmag, fftout); + yin->data[0] = 1.; + for (tau = 1; tau < yin->length; tau++) { + // compute the square differences + yin->data[tau] = sum - fftout->data[tau]; + // and the cumulative mean normalized difference function + tmp += yin->data[tau]; + if (tmp != 0) { + yin->data[tau] *= tau / tmp; + } else { + yin->data[tau] = 1.; + } + } + // find best candidates + tau = fvec_min_elem (yin); + if (yin->data[tau] < p->tol) { + // no interpolation, directly return the period as an integer + //output->data[0] = tau; + //return; + + // 3 point quadratic interpolation + //return fvec_quadratic_peak_pos (yin,tau,1); + /* additional check for (unlikely) octave doubling in higher frequencies */ + if (tau > p->short_period) { + output->data[0] = fvec_quadratic_peak_pos (yin, tau); + } else { + /* should compare the minimum value of each interpolated peaks */ + halfperiod = FLOOR (tau / 2 + .5); + if (yin->data[halfperiod] < p->tol) + p->peak_pos = halfperiod; + else + p->peak_pos = tau; + output->data[0] = fvec_quadratic_peak_pos (yin, p->peak_pos); + } + } else { + p->peak_pos = 0; + output->data[0] = 0.; + } +} + +void +del_aubio_pitchyinfft (aubio_pitchyinfft_t * p) +{ + del_fvec (p->win); + del_aubio_fft (p->fft); + del_fvec (p->yinfft); + del_fvec (p->sqrmag); + del_fvec (p->fftout); + del_fvec (p->winput); + del_fvec (p->weight); + AUBIO_FREE (p); +} + +smpl_t +aubio_pitchyinfft_get_confidence (aubio_pitchyinfft_t * o) { + return 1. - o->yinfft->data[o->peak_pos]; +} + +uint_t +aubio_pitchyinfft_set_tolerance (aubio_pitchyinfft_t * p, smpl_t tol) +{ + p->tol = tol; + return 0; +} + +smpl_t +aubio_pitchyinfft_get_tolerance (aubio_pitchyinfft_t * p) +{ + return p->tol; +} diff --git a/deps/aubio/src/pitch/pitchyinfft.h b/deps/aubio/src/pitch/pitchyinfft.h new file mode 100644 index 00000000..ccd4e518 --- /dev/null +++ b/deps/aubio/src/pitch/pitchyinfft.h @@ -0,0 +1,99 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** \file + + Pitch detection using a spectral implementation of the YIN algorithm + + This algorithm was derived from the YIN algorithm. In this implementation, a + Fourier transform is used to compute a tapered square difference function, + which allows spectral weighting. Because the difference function is tapered, + the selection of the period is simplified. + + Paul Brossier, [Automatic annotation of musical audio for interactive + systems](http://aubio.org/phd/), Chapter 3, Pitch Analysis, PhD thesis, + Centre for Digital music, Queen Mary University of London, London, UK, 2006. + + \example pitch/test-pitchyinfft.c + +*/ + +#ifndef AUBIO_PITCHYINFFT_H +#define AUBIO_PITCHYINFFT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** pitch detection object */ +typedef struct _aubio_pitchyinfft_t aubio_pitchyinfft_t; + +/** execute pitch detection on an input buffer + + \param o pitch detection object as returned by new_aubio_pitchyinfft + \param samples_in input signal vector (length as specified at creation time) + \param cands_out pitch period candidates, in samples + +*/ +void aubio_pitchyinfft_do (aubio_pitchyinfft_t * o, const fvec_t * samples_in, fvec_t * cands_out); +/** creation of the pitch detection object + + \param samplerate samplerate of the input signal + \param buf_size size of the input buffer to analyse + +*/ +aubio_pitchyinfft_t *new_aubio_pitchyinfft (uint_t samplerate, uint_t buf_size); +/** deletion of the pitch detection object + + \param o pitch detection object as returned by new_aubio_pitchyinfft() + +*/ +void del_aubio_pitchyinfft (aubio_pitchyinfft_t * o); + +/** get tolerance parameter for YIN algorithm + + \param o YIN pitch detection object + + \return tolerance parameter for minima selection [default 0.15] + +*/ +smpl_t aubio_pitchyinfft_get_tolerance (aubio_pitchyinfft_t * o); + +/** set tolerance parameter for YIN algorithm + + \param o YIN pitch detection object + \param tol tolerance parameter for minima selection [default 0.15] + +*/ +uint_t aubio_pitchyinfft_set_tolerance (aubio_pitchyinfft_t * o, smpl_t tol); + +/** get current confidence of YIN algorithm + + \param o YIN pitch detection object + \return confidence parameter + +*/ +smpl_t aubio_pitchyinfft_get_confidence (aubio_pitchyinfft_t * o); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_PITCHYINFFT_H */ diff --git a/deps/aubio/src/spectral/fft.c b/deps/aubio/src/spectral/fft.c new file mode 100644 index 00000000..9384ca24 --- /dev/null +++ b/deps/aubio/src/spectral/fft.c @@ -0,0 +1,237 @@ +/* + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "fvec.h" +#include "cvec.h" +#include "mathutils.h" +#include "spectral/fft.h" + +/* note that is not included here but only in aubio_priv.h, so that + * c++ projects can still use their own complex definition. */ +#include +#include + +/** fft data type with complex.h and fftw3f */ +#define FFTW_TYPE fftwf_complex + +/** fft data type */ +typedef FFTW_TYPE fft_data_t; + +#define fftw_malloc fftwf_malloc +#define fftw_free fftwf_free +#define fftw_execute fftwf_execute +#define fftw_plan_dft_r2c_1d fftwf_plan_dft_r2c_1d +#define fftw_plan_dft_c2r_1d fftwf_plan_dft_c2r_1d +#define fftw_plan_r2r_1d fftwf_plan_r2r_1d +#define fftw_plan fftwf_plan +#define fftw_destroy_plan fftwf_destroy_plan + +#if HAVE_AUBIO_DOUBLE +#error "Using aubio in double precision with fftw3 in single precision" +#endif /* HAVE_AUBIO_DOUBLE */ + +#define real_t float + +#ifndef SKIP_FFTW_MUTEX +// a global mutex for FFTW thread safety +pthread_mutex_t aubio_fftw_mutex = PTHREAD_MUTEX_INITIALIZER; +#endif + +struct _aubio_fft_t { + uint_t winsize; + uint_t fft_size; + + real_t *in, *out; + fftw_plan pfw, pbw; + fft_data_t * specdata; /* complex spectral data */ + + fvec_t * compspec; +}; + +aubio_fft_t * new_aubio_fft (uint_t winsize) { + aubio_fft_t * s = AUBIO_NEW(aubio_fft_t); + if ((sint_t)winsize < 2) { + AUBIO_ERR("fft: got winsize %d, but can not be < 2\n", winsize); + goto beach; + } + + uint_t i; + s->winsize = winsize; + /* allocate memory */ + s->in = AUBIO_ARRAY(real_t,winsize); + s->out = AUBIO_ARRAY(real_t,winsize); + s->compspec = new_fvec(winsize); + /* create plans */ +#ifndef SKIP_FFTW_MUTEX + pthread_mutex_lock(&aubio_fftw_mutex); +#endif + s->fft_size = winsize/2 + 1; + s->specdata = (fft_data_t*)fftw_malloc(sizeof(fft_data_t)*s->fft_size); + s->pfw = fftw_plan_dft_r2c_1d(winsize, s->in, s->specdata, FFTW_ESTIMATE); + s->pbw = fftw_plan_dft_c2r_1d(winsize, s->specdata, s->out, FFTW_ESTIMATE); +#ifndef SKIP_FFTW_MUTEX + pthread_mutex_unlock(&aubio_fftw_mutex); +#endif + for (i = 0; i < s->winsize; i++) { + s->in[i] = 0.; + s->out[i] = 0.; + } + for (i = 0; i < s->fft_size; i++) { + s->specdata[i] = 0.; + } + + return s; + +beach: + AUBIO_FREE(s); + return NULL; +} + +void del_aubio_fft(aubio_fft_t * s) { + /* destroy data */ +#ifndef SKIP_FFTW_MUTEX + pthread_mutex_lock(&aubio_fftw_mutex); +#endif + fftw_destroy_plan(s->pfw); + fftw_destroy_plan(s->pbw); + fftw_free(s->specdata); +#ifndef SKIP_FFTW_MUTEX + pthread_mutex_unlock(&aubio_fftw_mutex); +#endif + + del_fvec(s->compspec); + AUBIO_FREE(s->in); + AUBIO_FREE(s->out); + AUBIO_FREE(s); +} + +void aubio_fft_do(aubio_fft_t * s, const fvec_t * input, cvec_t * spectrum) { + aubio_fft_do_complex(s, input, s->compspec); + aubio_fft_get_spectrum(s->compspec, spectrum); +} + +void aubio_fft_rdo(aubio_fft_t * s, const cvec_t * spectrum, fvec_t * output) { + aubio_fft_get_realimag(spectrum, s->compspec); + aubio_fft_rdo_complex(s, s->compspec, output); +} + +void aubio_fft_do_complex(aubio_fft_t * s, const fvec_t * input, fvec_t * compspec) { + uint_t i; +#ifndef HAVE_MEMCPY_HACKS + for (i=0; i < s->winsize; i++) { + s->in[i] = input->data[i]; + } +#else + memcpy(s->in, input->data, s->winsize * sizeof(smpl_t)); +#endif /* HAVE_MEMCPY_HACKS */ + + fftw_execute(s->pfw); + compspec->data[0] = REAL(s->specdata[0]); + for (i = 1; i < s->fft_size -1 ; i++) { + compspec->data[i] = REAL(s->specdata[i]); + compspec->data[compspec->length - i] = IMAG(s->specdata[i]); + } + compspec->data[s->fft_size-1] = REAL(s->specdata[s->fft_size-1]); +} + +void aubio_fft_rdo_complex(aubio_fft_t * s, const fvec_t * compspec, fvec_t * output) { + uint_t i; + const smpl_t renorm = 1./(smpl_t)s->winsize; + s->specdata[0] = compspec->data[0]; + for (i=1; i < s->fft_size - 1; i++) { + s->specdata[i] = compspec->data[i] + + I * compspec->data[compspec->length - i]; + } + s->specdata[s->fft_size - 1] = compspec->data[s->fft_size - 1]; + fftw_execute(s->pbw); + for (i = 0; i < output->length; i++) { + output->data[i] = s->out[i]*renorm; + } +} + +void aubio_fft_get_spectrum(const fvec_t * compspec, cvec_t * spectrum) { + aubio_fft_get_phas(compspec, spectrum); + aubio_fft_get_norm(compspec, spectrum); +} + +void aubio_fft_get_realimag(const cvec_t * spectrum, fvec_t * compspec) { + aubio_fft_get_imag(spectrum, compspec); + aubio_fft_get_real(spectrum, compspec); +} + +void aubio_fft_get_phas(const fvec_t * compspec, cvec_t * spectrum) { + uint_t i; + if (compspec->data[0] < 0) { + spectrum->phas[0] = PI; + } else { + spectrum->phas[0] = 0.; + } + for (i=1; i < spectrum->length - 1; i++) { + spectrum->phas[i] = ATAN2(compspec->data[compspec->length-i], + compspec->data[i]); + } + // for even length only, make sure last element is 0 or PI + if (2 * (compspec->length / 2) == compspec->length) { + if (compspec->data[compspec->length/2] < 0) { + spectrum->phas[spectrum->length - 1] = PI; + } else { + spectrum->phas[spectrum->length - 1] = 0.; + } + } else { + i = spectrum->length - 1; + spectrum->phas[i] = ATAN2(compspec->data[compspec->length-i], + compspec->data[i]); + } +} + +void aubio_fft_get_norm(const fvec_t * compspec, cvec_t * spectrum) { + uint_t i = 0; + spectrum->norm[0] = ABS(compspec->data[0]); + for (i=1; i < spectrum->length - 1; i++) { + spectrum->norm[i] = SQRT(SQR(compspec->data[i]) + + SQR(compspec->data[compspec->length - i]) ); + } + // for even length, make sure last element is > 0 + if (2 * (compspec->length / 2) == compspec->length) { + spectrum->norm[spectrum->length-1] = + ABS(compspec->data[compspec->length/2]); + } else { + i = spectrum->length - 1; + spectrum->norm[i] = SQRT(SQR(compspec->data[i]) + + SQR(compspec->data[compspec->length - i]) ); + } +} + +void aubio_fft_get_imag(const cvec_t * spectrum, fvec_t * compspec) { + uint_t i; + for (i = 1; i < ( compspec->length + 1 ) / 2 /*- 1 + 1*/; i++) { + compspec->data[compspec->length - i] = + spectrum->norm[i]*SIN(spectrum->phas[i]); + } +} + +void aubio_fft_get_real(const cvec_t * spectrum, fvec_t * compspec) { + uint_t i; + for (i = 0; i < compspec->length / 2 + 1; i++) { + compspec->data[i] = + spectrum->norm[i]*COS(spectrum->phas[i]); + } +} diff --git a/deps/aubio/src/spectral/fft.h b/deps/aubio/src/spectral/fft.h new file mode 100644 index 00000000..21072c8b --- /dev/null +++ b/deps/aubio/src/spectral/fft.h @@ -0,0 +1,144 @@ +/* + Copyright (C) 2003-2013 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** \file + + Fast Fourier Transform + + Depending on how aubio was compiled, FFT are computed using one of: + - [Ooura](http://www.kurims.kyoto-u.ac.jp/~ooura/fft.html) + - [FFTW3](http://www.fftw.org) + - [vDSP](https://developer.apple.com/library/mac/#documentation/Accelerate/Reference/vDSPRef/Reference/reference.html) + + \example spectral/test-fft.c + +*/ + +#ifndef AUBIO_FFT_H +#define AUBIO_FFT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** FFT object + + This object computes forward and backward FFTs. + +*/ +typedef struct _aubio_fft_t aubio_fft_t; + +/** create new FFT computation object + + \param size length of the FFT + +*/ +aubio_fft_t * new_aubio_fft (uint_t size); +/** delete FFT object + + \param s fft object as returned by new_aubio_fft + +*/ +void del_aubio_fft(aubio_fft_t * s); + +/** compute forward FFT + + \param s fft object as returned by new_aubio_fft + \param input input signal + \param spectrum output spectrum + +*/ +void aubio_fft_do (aubio_fft_t *s, const fvec_t * input, cvec_t * spectrum); +/** compute backward (inverse) FFT + + \param s fft object as returned by new_aubio_fft + \param spectrum input spectrum + \param output output signal + +*/ +void aubio_fft_rdo (aubio_fft_t *s, const cvec_t * spectrum, fvec_t * output); + +/** compute forward FFT + + \param s fft object as returned by new_aubio_fft + \param input real input signal + \param compspec complex output fft real/imag + +*/ +void aubio_fft_do_complex (aubio_fft_t *s, const fvec_t * input, fvec_t * compspec); +/** compute backward (inverse) FFT from real/imag + + \param s fft object as returned by new_aubio_fft + \param compspec real/imag input fft array + \param output real output array + +*/ +void aubio_fft_rdo_complex (aubio_fft_t *s, const fvec_t * compspec, fvec_t * output); + +/** convert real/imag spectrum to norm/phas spectrum + + \param compspec real/imag input fft array + \param spectrum cvec norm/phas output array + +*/ +void aubio_fft_get_spectrum(const fvec_t * compspec, cvec_t * spectrum); +/** convert real/imag spectrum to norm/phas spectrum + + \param compspec real/imag input fft array + \param spectrum cvec norm/phas output array + +*/ +void aubio_fft_get_realimag(const cvec_t * spectrum, fvec_t * compspec); + +/** compute phas spectrum from real/imag parts + + \param compspec real/imag input fft array + \param spectrum cvec norm/phas output array + +*/ +void aubio_fft_get_phas(const fvec_t * compspec, cvec_t * spectrum); +/** compute imaginary part from the norm/phas cvec + + \param spectrum norm/phas input array + \param compspec real/imag output fft array + +*/ +void aubio_fft_get_imag(const cvec_t * spectrum, fvec_t * compspec); + +/** compute norm component from real/imag parts + + \param compspec real/imag input fft array + \param spectrum cvec norm/phas output array + +*/ +void aubio_fft_get_norm(const fvec_t * compspec, cvec_t * spectrum); +/** compute real part from norm/phas components + + \param spectrum norm/phas input array + \param compspec real/imag output fft array + +*/ +void aubio_fft_get_real(const cvec_t * spectrum, fvec_t * compspec); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_FFT_H */ diff --git a/deps/aubio/src/spectral/phasevoc.c b/deps/aubio/src/spectral/phasevoc.c new file mode 100644 index 00000000..05ebdb06 --- /dev/null +++ b/deps/aubio/src/spectral/phasevoc.c @@ -0,0 +1,224 @@ +/* + Copyright (C) 2003-2014 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "fvec.h" +#include "cvec.h" +#include "mathutils.h" +#include "spectral/fft.h" +#include "spectral/phasevoc.h" + +/** phasevocoder internal object */ +struct _aubio_pvoc_t { + uint_t win_s; /** grain length */ + uint_t hop_s; /** overlap step */ + aubio_fft_t * fft; /** fft object */ + fvec_t * data; /** current input grain, [win_s] frames */ + fvec_t * dataold; /** memory of past grain, [win_s-hop_s] frames */ + fvec_t * synth; /** current output grain, [win_s] frames */ + fvec_t * synthold; /** memory of past grain, [win_s-hop_s] frames */ + fvec_t * w; /** grain window [win_s] */ + uint_t start; /** where to start additive synthesis */ + uint_t end; /** where to end it */ + smpl_t scale; /** scaling factor for synthesis */ + uint_t end_datasize; /** size of memory to end */ + uint_t hop_datasize; /** size of memory to hop_s */ +}; + + +/** returns data and dataold slided by hop_s */ +static void aubio_pvoc_swapbuffers(aubio_pvoc_t *pv, const fvec_t *new); + +/** do additive synthesis from 'old' and 'cur' */ +static void aubio_pvoc_addsynth(aubio_pvoc_t *pv, fvec_t * synthnew); + +void aubio_pvoc_do(aubio_pvoc_t *pv, const fvec_t * datanew, cvec_t *fftgrain) { + /* slide */ + aubio_pvoc_swapbuffers(pv, datanew); + /* windowing */ + fvec_weight(pv->data, pv->w); + /* shift */ + fvec_shift(pv->data); + /* calculate fft */ + aubio_fft_do (pv->fft,pv->data,fftgrain); +} + +void aubio_pvoc_rdo(aubio_pvoc_t *pv,cvec_t * fftgrain, fvec_t * synthnew) { + /* calculate rfft */ + aubio_fft_rdo(pv->fft,fftgrain,pv->synth); + /* unshift */ + fvec_ishift(pv->synth); + /* windowing */ + // if overlap = 50%, do not apply window (identity) + if (pv->hop_s * 2 < pv->win_s) { + fvec_weight(pv->synth, pv->w); + } + /* additive synthesis */ + aubio_pvoc_addsynth(pv, synthnew); +} + +aubio_pvoc_t * new_aubio_pvoc (uint_t win_s, uint_t hop_s) { + aubio_pvoc_t * pv = AUBIO_NEW(aubio_pvoc_t); + + /* if (win_s < 2*hop_s) { + AUBIO_WRN("Hop size bigger than half the window size!\n"); + } */ + + if ((sint_t)hop_s < 1) { + AUBIO_ERR("pvoc: got hop_size %d, but can not be < 1\n", hop_s); + goto beach; + } else if ((sint_t)win_s < 2) { + AUBIO_ERR("pvoc: got buffer_size %d, but can not be < 2\n", win_s); + goto beach; + } else if (win_s < hop_s) { + AUBIO_ERR("pvoc: hop size (%d) is larger than win size (%d)\n", hop_s, win_s); + goto beach; + } + + pv->fft = new_aubio_fft (win_s); + if (pv->fft == NULL) { + goto beach; + } + + /* remember old */ + pv->data = new_fvec (win_s); + pv->synth = new_fvec (win_s); + + /* new input output */ + if (win_s > hop_s) { + pv->dataold = new_fvec (win_s-hop_s); + pv->synthold = new_fvec (win_s-hop_s); + } else { + pv->dataold = new_fvec (1); + pv->synthold = new_fvec (1); + } + pv->w = new_aubio_window ("hanningz", win_s); + + pv->hop_s = hop_s; + pv->win_s = win_s; + + /* more than 50% overlap, overlap anyway */ + if (win_s < 2 * hop_s) pv->start = 0; + /* less than 50% overlap, reset latest grain trail */ + else pv->start = win_s - hop_s - hop_s; + + if (win_s > hop_s) pv->end = win_s - hop_s; + else pv->end = 0; + + pv->end_datasize = pv->end * sizeof(smpl_t); + pv->hop_datasize = pv->hop_s * sizeof(smpl_t); + + // for reconstruction with 75% overlap + if (win_s == hop_s * 4) { + pv->scale = 2./3.; + } else if (win_s == hop_s * 8) { + pv->scale = 1./3.; + } else if (win_s == hop_s * 2) { + pv->scale = 1.; + } else { + pv->scale = .5; + } + + return pv; + +beach: + AUBIO_FREE (pv); + return NULL; +} + +uint_t aubio_pvoc_set_window(aubio_pvoc_t *pv, const char_t *window) { + return fvec_set_window(pv->w, (char_t*)window); +} + +void del_aubio_pvoc(aubio_pvoc_t *pv) { + del_fvec(pv->data); + del_fvec(pv->synth); + del_fvec(pv->dataold); + del_fvec(pv->synthold); + del_fvec(pv->w); + del_aubio_fft(pv->fft); + AUBIO_FREE(pv); +} + +static void aubio_pvoc_swapbuffers(aubio_pvoc_t *pv, const fvec_t *new) +{ + /* some convenience pointers */ + smpl_t * data = pv->data->data; + smpl_t * dataold = pv->dataold->data; + smpl_t * datanew = new->data; +#ifndef HAVE_MEMCPY_HACKS + uint_t i; + for (i = 0; i < pv->end; i++) + data[i] = dataold[i]; + for (i = 0; i < pv->hop_s; i++) + data[pv->end + i] = datanew[i]; + for (i = 0; i < pv->end; i++) + dataold[i] = data[i + pv->hop_s]; +#else + memcpy(data, dataold, pv->end_datasize); + data += pv->end; + memcpy(data, datanew, pv->hop_datasize); + data -= pv->end; + data += pv->hop_s; + memcpy(dataold, data, pv->end_datasize); +#endif +} + +static void aubio_pvoc_addsynth(aubio_pvoc_t *pv, fvec_t *synth_new) +{ + uint_t i; + /* some convenience pointers */ + smpl_t * synth = pv->synth->data; + smpl_t * synthold = pv->synthold->data; + smpl_t * synthnew = synth_new->data; + + /* put new result in synthnew */ + for (i = 0; i < pv->hop_s; i++) + synthnew[i] = synth[i] * pv->scale; + + /* no overlap, nothing else to do */ + if (pv->end == 0) return; + + /* add new synth to old one */ + for (i = 0; i < pv->hop_s; i++) + synthnew[i] += synthold[i]; + + /* shift synthold */ + for (i = 0; i < pv->start; i++) + synthold[i] = synthold[i + pv->hop_s]; + + /* erase last frame in synthold */ + for (i = pv->start; i < pv->end; i++) + synthold[i] = 0.; + + /* additive synth */ + for (i = 0; i < pv->end; i++) + synthold[i] += synth[i + pv->hop_s] * pv->scale; +} + +uint_t aubio_pvoc_get_win(aubio_pvoc_t* pv) +{ + return pv->win_s; +} + +uint_t aubio_pvoc_get_hop(aubio_pvoc_t* pv) +{ + return pv->hop_s; +} diff --git a/deps/aubio/src/spectral/phasevoc.h b/deps/aubio/src/spectral/phasevoc.h new file mode 100644 index 00000000..e3caf2de --- /dev/null +++ b/deps/aubio/src/spectral/phasevoc.h @@ -0,0 +1,113 @@ +/* + Copyright (C) 2003-2013 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +/** \file + + Phase vocoder object + + This object implements a phase vocoder. The spectral frames are computed + using a HanningZ window and a swapped version of the signal to simplify the + phase relationships across frames. The window sizes and overlap are specified + at creation time. + + \example spectral/test-phasevoc.c + +*/ + +#ifndef AUBIO_PHASEVOC_H +#define AUBIO_PHASEVOC_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** phasevocoder object */ +typedef struct _aubio_pvoc_t aubio_pvoc_t; + +/** create phase vocoder object + + \param win_s size of analysis buffer (and length the FFT transform) + \param hop_s step size between two consecutive analysis + +*/ +aubio_pvoc_t * new_aubio_pvoc (uint_t win_s, uint_t hop_s); +/** delete phase vocoder object + + \param pv phase vocoder object as returned by new_aubio_pvoc + +*/ +void del_aubio_pvoc(aubio_pvoc_t *pv); + +/** compute spectral frame + + This function accepts an input vector of size [hop_s]. The + analysis buffer is rotated and filled with the new data. After windowing of + this signal window, the Fourier transform is computed and returned in + fftgrain as two vectors, magnitude and phase. + + \param pv phase vocoder object as returned by new_aubio_pvoc + \param in new input signal (hop_s long) + \param fftgrain output spectral frame + +*/ +void aubio_pvoc_do(aubio_pvoc_t *pv, const fvec_t *in, cvec_t * fftgrain); +/** compute signal from spectral frame + + This function takes an input spectral frame fftgrain of size + [buf_s] and computes its inverse Fourier transform. Overlap-add + synthesis is then computed using the previously synthetised frames, and the + output stored in out. + + \param pv phase vocoder object as returned by new_aubio_pvoc + \param fftgrain input spectral frame + \param out output signal (hop_s long) + +*/ +void aubio_pvoc_rdo(aubio_pvoc_t *pv, cvec_t * fftgrain, fvec_t *out); + +/** get window size + + \param pv phase vocoder to get the window size from + +*/ +uint_t aubio_pvoc_get_win(aubio_pvoc_t* pv); + +/** get hop size + + \param pv phase vocoder to get the hop size from + +*/ +uint_t aubio_pvoc_get_hop(aubio_pvoc_t* pv); + +/** set window type + + \param pv phase vocoder to set the window type + \param window_type a string representing a window + + \return 0 if successful, non-zero otherwise + + */ +uint_t aubio_pvoc_set_window(aubio_pvoc_t *pv, const char_t *window_type); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_PHASEVOC_H */ diff --git a/deps/aubio/src/temporal/a_weighting.c b/deps/aubio/src/temporal/a_weighting.c new file mode 100644 index 00000000..f19f566f --- /dev/null +++ b/deps/aubio/src/temporal/a_weighting.c @@ -0,0 +1,262 @@ +/* + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "types.h" +#include "fvec.h" +#include "lvec.h" +#include "temporal/filter.h" +#include "temporal/a_weighting.h" + +uint_t +aubio_filter_set_a_weighting (aubio_filter_t * f, uint_t samplerate) +{ + uint_t order; lsmp_t *a, *b; lvec_t *as, *bs; + + if ((sint_t)samplerate <= 0) { + AUBIO_ERROR("aubio_filter: failed setting A-weighting with samplerate %d\n", samplerate); + return AUBIO_FAIL; + } + if (f == NULL) { + AUBIO_ERROR("aubio_filter: failed setting A-weighting with filter NULL\n"); + return AUBIO_FAIL; + } + + order = aubio_filter_get_order (f); + if (order != 7) { + AUBIO_ERROR ("aubio_filter: order of A-weighting filter must be 7, not %d\n", order); + return 1; + } + + aubio_filter_set_samplerate (f, samplerate); + bs = aubio_filter_get_feedforward (f); + as = aubio_filter_get_feedback (f); + b = bs->data, a = as->data; + + /* select coefficients according to sampling frequency */ + switch (samplerate) { + + case 8000: + b[0] = 6.306209468238731519207362907764036208391189575195312500e-01; + b[1] = -1.261241893647746525886077506584115326404571533203125000e+00; + b[2] = -6.306209468238730408984338282607495784759521484375000000e-01; + b[3] = 2.522483787295493051772155013168230652809143066406250000e+00; + b[4] = -6.306209468238730408984338282607495784759521484375000000e-01; + b[5] = -1.261241893647746525886077506584115326404571533203125000e+00; + b[6] = 6.306209468238731519207362907764036208391189575195312500e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -2.128467193009123015201566886389628052711486816406250000e+00; + a[2] = 2.948668980101234460278192273108288645744323730468750000e-01; + a[3] = 1.824183830735050637628091863007284700870513916015625000e+00; + a[4] = -8.056628943119792385374466903158463537693023681640625000e-01; + a[5] = -3.947497982842933517133587884018197655677795410156250000e-01; + a[6] = 2.098548546080332977137317129745497368276119232177734375e-01; + break; + + case 11025: + b[0] = 6.014684165832374640459079273568931967020034790039062500e-01; + b[1] = -1.202936833166475150136420779745094478130340576171875000e+00; + b[2] = -6.014684165832373530236054648412391543388366699218750000e-01; + b[3] = 2.405873666332950300272841559490188956260681152343750000e+00; + b[4] = -6.014684165832373530236054648412391543388366699218750000e-01; + b[5] = -1.202936833166475150136420779745094478130340576171875000e+00; + b[6] = 6.014684165832374640459079273568931967020034790039062500e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -2.463578747722854345170162559952586889266967773437500000e+00; + a[2] = 1.096799662705210121060872552334330976009368896484375000e+00; + a[3] = 1.381222210556041218865175324026495218276977539062500000e+00; + a[4] = -1.013875696476876031582037285261321812868118286132812500e+00; + a[5] = -1.839132734476921215982514468123554252088069915771484375e-01; + a[6] = 1.833526393172056623281918064094497822225093841552734375e-01; + break; + + case 16000: + b[0] = 5.314898298235570806014038680586963891983032226562500000e-01; + b[1] = -1.062979659647114161202807736117392778396606445312500000e+00; + b[2] = -5.314898298235570806014038680586963891983032226562500000e-01; + b[3] = 2.125959319294228322405615472234785556793212890625000000e+00; + b[4] = -5.314898298235570806014038680586963891983032226562500000e-01; + b[5] = -1.062979659647114161202807736117392778396606445312500000e+00; + b[6] = 5.314898298235570806014038680586963891983032226562500000e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -2.867832572992162987191022693878039717674255371093750000e+00; + a[2] = 2.221144410202312347024644623161293566226959228515625000e+00; + a[3] = 4.552683347886614662058946123579517006874084472656250000e-01; + a[4] = -9.833868636162828025248927588108927011489868164062500000e-01; + a[5] = 5.592994142413361402521587706360151059925556182861328125e-02; + a[6] = 1.188781038285612462468421313133148942142724990844726562e-01; + break; + + case 22050: + b[0] = 4.492998504299193784916610638902056962251663208007812500e-01; + b[1] = -8.985997008598388680056245902960654348134994506835937500e-01; + b[2] = -4.492998504299192674693586013745516538619995117187500000e-01; + b[3] = 1.797199401719677958055854105623438954353332519531250000e+00; + b[4] = -4.492998504299192674693586013745516538619995117187500000e-01; + b[5] = -8.985997008598388680056245902960654348134994506835937500e-01; + b[6] = 4.492998504299193784916610638902056962251663208007812500e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -3.229078805225074955131958631682209670543670654296875000e+00; + a[2] = 3.354494881236033787530459449044428765773773193359375000e+00; + a[3] = -7.317843680657351024265722116979304701089859008789062500e-01; + a[4] = -6.271627581807257545420952737913466989994049072265625000e-01; + a[5] = 1.772142005020879151899748649157118052244186401367187500e-01; + a[6] = 5.631716697383508385410522123493137769401073455810546875e-02; + break; + + case 24000: + b[0] = 4.256263892891054001488271296693710610270500183105468750e-01; + b[1] = -8.512527785782106892753517968230880796909332275390625000e-01; + b[2] = -4.256263892891054556599783609271980822086334228515625000e-01; + b[3] = 1.702505557156421378550703593646176159381866455078125000e+00; + b[4] = -4.256263892891054556599783609271980822086334228515625000e-01; + b[5] = -8.512527785782106892753517968230880796909332275390625000e-01; + b[6] = 4.256263892891054001488271296693710610270500183105468750e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -3.325996004241962733516402295208536088466644287109375000e+00; + a[2] = 3.677161079286316969216841243905946612358093261718750000e+00; + a[3] = -1.106476076828482035807610373012721538543701171875000000e+00; + a[4] = -4.726706734908718843257702246773988008499145507812500000e-01; + a[5] = 1.861941760230954034938122276798821985721588134765625000e-01; + a[6] = 4.178771337829546850262119050967157818377017974853515625e-02; + break; + + case 32000: + b[0] = 3.434583386824304196416335344110848382115364074707031250e-01; + b[1] = -6.869166773648609503055695313378237187862396240234375000e-01; + b[2] = -3.434583386824303641304823031532578170299530029296875000e-01; + b[3] = 1.373833354729721900611139062675647437572479248046875000e+00; + b[4] = -3.434583386824303641304823031532578170299530029296875000e-01; + b[5] = -6.869166773648609503055695313378237187862396240234375000e-01; + b[6] = 3.434583386824304196416335344110848382115364074707031250e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -3.656446043233668063976438133977353572845458984375000000e+00; + a[2] = 4.831468450652579349480220116674900054931640625000000000e+00; + a[3] = -2.557597496581567764195597192156128585338592529296875000e+00; + a[4] = 2.533680394205302666144064005493419244885444641113281250e-01; + a[5] = 1.224430322452567110325105659285327419638633728027343750e-01; + a[6] = 6.764072168342137418572956875095769646577537059783935547e-03; + break; + + case 44100: + b[0] = 2.557411252042575133813784304948057979345321655273437500e-01; + b[1] = -5.114822504085150267627568609896115958690643310546875000e-01; + b[2] = -2.557411252042575133813784304948057979345321655273437500e-01; + b[3] = 1.022964500817030053525513721979223191738128662109375000e+00; + b[4] = -2.557411252042575133813784304948057979345321655273437500e-01; + b[5] = -5.114822504085150267627568609896115958690643310546875000e-01; + b[6] = 2.557411252042575133813784304948057979345321655273437500e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -4.019576181115832369528106937650591135025024414062500000e+00; + a[2] = 6.189406442920693862674852425698190927505493164062500000e+00; + a[3] = -4.453198903544116404873420833609998226165771484375000000e+00; + a[4] = 1.420842949621876627475103305187076330184936523437500000e+00; + a[5] = -1.418254738303044160119270600262098014354705810546875000e-01; + a[6] = 4.351177233495117681327801761881346465088427066802978516e-03; + break; + + case 48000: + b[0] = 2.343017922995132285013397677175817079842090606689453125e-01; + b[1] = -4.686035845990265125138307666929904371500015258789062500e-01; + b[2] = -2.343017922995132007457641520886681973934173583984375000e-01; + b[3] = 9.372071691980530250276615333859808743000030517578125000e-01; + b[4] = -2.343017922995132007457641520886681973934173583984375000e-01; + b[5] = -4.686035845990265125138307666929904371500015258789062500e-01; + b[6] = 2.343017922995132285013397677175817079842090606689453125e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -4.113043408775872045168853219365701079368591308593750000e+00; + a[2] = 6.553121752655050258340452273841947317123413085937500000e+00; + a[3] = -4.990849294163385074796224216697737574577331542968750000e+00; + a[4] = 1.785737302937575599059982778271660208702087402343750000e+00; + a[5] = -2.461905953194876706113802811159985139966011047363281250e-01; + a[6] = 1.122425003323123879339640041052916785702109336853027344e-02; + break; + + case 88200: + b[0] = 1.118876366882113199130444058937428053468465805053710938e-01; + b[1] = -2.237752733764226120705131961585721001029014587402343750e-01; + b[2] = -1.118876366882113337908322137081995606422424316406250000e-01; + b[3] = 4.475505467528452241410263923171442002058029174804687500e-01; + b[4] = -1.118876366882113337908322137081995606422424316406250000e-01; + b[5] = -2.237752733764226120705131961585721001029014587402343750e-01; + b[6] = 1.118876366882113199130444058937428053468465805053710938e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -4.726938565651158441482948546763509511947631835937500000e+00; + a[2] = 9.076897983832765248735086061060428619384765625000000000e+00; + a[3] = -9.014855113464800950850985827855765819549560546875000000e+00; + a[4] = 4.852772261031594425162438710685819387435913085937500000e+00; + a[5] = -1.333877820398965186043938047077972441911697387695312500e+00; + a[6] = 1.460012549591642450064199465487035922706127166748046875e-01; + break; + + case 96000: + b[0] = 9.951898975972744976203898659150581806898117065429687500e-02; + b[1] = -1.990379795194548995240779731830116361379623413085937500e-01; + b[2] = -9.951898975972744976203898659150581806898117065429687500e-02; + b[3] = 3.980759590389097990481559463660232722759246826171875000e-01; + b[4] = -9.951898975972744976203898659150581806898117065429687500e-02; + b[5] = -1.990379795194548995240779731830116361379623413085937500e-01; + b[6] = 9.951898975972744976203898659150581806898117065429687500e-02; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -4.802203044225376693532325589330866932868957519531250000e+00; + a[2] = 9.401807218627226347962277941405773162841796875000000000e+00; + a[3] = -9.566143943569164420637207513209432363510131835937500000e+00; + a[4] = 5.309775930392619081032989925006404519081115722656250000e+00; + a[5] = -1.517333360452622237346531619550660252571105957031250000e+00; + a[6] = 1.740971994228911745583587844521389342844486236572265625e-01; + break; + + case 192000: + b[0] = 3.433213424548713782469278044118254911154508590698242188e-02; + b[1] = -6.866426849097426177159775306790834292769432067871093750e-02; + b[2] = -3.433213424548714476358668434841092675924301147460937500e-02; + b[3] = 1.373285369819485235431955061358166858553886413574218750e-01; + b[4] = -3.433213424548714476358668434841092675924301147460937500e-02; + b[5] = -6.866426849097426177159775306790834292769432067871093750e-02; + b[6] = 3.433213424548713782469278044118254911154508590698242188e-02; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -5.305923689674640009172890131594613194465637207031250000e+00; + a[2] = 1.165952437466175695135461864992976188659667968750000000e+01; + a[3] = -1.357560092700591525272102444432675838470458984375000000e+01; + a[4] = 8.828906932824192921316353022120893001556396484375000000e+00; + a[5] = -3.039490120988216581565666274400427937507629394531250000e+00; + a[6] = 4.325834301870381537469256727490574121475219726562500000e-01; + break; + + default: + AUBIO_ERROR ("sampling rate of A-weighting filter is %d, should be one of\ + 8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000, 192000.\n", samplerate); + return 1; + + } + + return 0; +} + +aubio_filter_t * +new_aubio_filter_a_weighting (uint_t samplerate) +{ + aubio_filter_t *f = new_aubio_filter (7); + if (aubio_filter_set_a_weighting(f,samplerate) != AUBIO_OK) { + del_aubio_filter(f); + return NULL; + } + return f; +} diff --git a/deps/aubio/src/temporal/a_weighting.h b/deps/aubio/src/temporal/a_weighting.h new file mode 100644 index 00000000..49dd4d5c --- /dev/null +++ b/deps/aubio/src/temporal/a_weighting.h @@ -0,0 +1,88 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#ifndef AUBIO_FILTER_A_DESIGN_H +#define AUBIO_FILTER_A_DESIGN_H + +/** \file + + A-weighting filter coefficients + + This file creates an A-weighting digital filter, which reduces low and high + frequencies and enhance the middle ones to reflect the ability of the human + hearing. + + The implementation is based on the following standard: + + - IEC/CD 1672: Electroacoustics-Sound Level Meters, IEC, Geneva, Nov. 1996, + for A- and C-weighting filters. + + See also: + + - A-Weighting on + Wikipedia + - Weighting filter on + Wikipedia + - Christophe + Couvreur's 'octave' toolbox + + The coefficients in this file have been computed using Christophe Couvreur's + scripts in octave 3.0 (debian package 1:3.0.5-6+b2 with octave-signal + 1.0.9-1+b1 on i386), with
 [b, a] = adsign(1/Fs) 
for various + sampling frequencies (8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, + 88200, 96000, and 192000 Hz). + + The sampling frequency should normally be higher than 20kHz, but most common + file sampling rates have been included for completeness. + + \example temporal/test-a_weighting.c + +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/** create new A-design filter + + \param samplerate sampling frequency of the signal to filter. Should be one of + 8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000, and + 192000 Hz + + \return a new filter object + +*/ +aubio_filter_t *new_aubio_filter_a_weighting (uint_t samplerate); + +/** set feedback and feedforward coefficients of a A-weighting filter + + \param f filter object to get coefficients from + \param samplerate sampling frequency of the signal to filter. Should be one of + 8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000, and + 192000 Hz + +*/ +uint_t aubio_filter_set_a_weighting (aubio_filter_t * f, uint_t samplerate); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_FILTER_A_DESIGN_H */ diff --git a/deps/aubio/src/temporal/biquad.c b/deps/aubio/src/temporal/biquad.c new file mode 100644 index 00000000..426b64fb --- /dev/null +++ b/deps/aubio/src/temporal/biquad.c @@ -0,0 +1,54 @@ +/* + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "fvec.h" +#include "lvec.h" +#include "temporal/filter.h" +#include "temporal/biquad.h" + +uint_t +aubio_filter_set_biquad (aubio_filter_t * f, lsmp_t b0, lsmp_t b1, lsmp_t b2, + lsmp_t a1, lsmp_t a2) +{ + uint_t order = aubio_filter_get_order (f); + lvec_t *bs = aubio_filter_get_feedforward (f); + lvec_t *as = aubio_filter_get_feedback (f); + + if (order != 3) { + AUBIO_ERROR ("order of biquad filter must be 3, not %d\n", order); + return AUBIO_FAIL; + } + bs->data[0] = b0; + bs->data[1] = b1; + bs->data[2] = b2; + as->data[0] = 1.; + as->data[1] = a1; + as->data[2] = a2; + return AUBIO_OK; +} + +aubio_filter_t * +new_aubio_filter_biquad (lsmp_t b0, lsmp_t b1, lsmp_t b2, lsmp_t a1, lsmp_t a2) +{ + aubio_filter_t *f = new_aubio_filter (3); + aubio_filter_set_biquad (f, b0, b1, b2, a1, a2); + return f; +} diff --git a/deps/aubio/src/temporal/biquad.h b/deps/aubio/src/temporal/biquad.h new file mode 100644 index 00000000..1d19d942 --- /dev/null +++ b/deps/aubio/src/temporal/biquad.h @@ -0,0 +1,75 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#ifndef AUBIO_FILTER_BIQUAD_H +#define AUBIO_FILTER_BIQUAD_H + +/** \file + + Second order Infinite Impulse Response filter + + This file implements a normalised biquad filter (second order IIR): + + \f$ y[n] = b_0 x[n] + b_1 x[n-1] + b_2 x[n-2] - a_1 y[n-1] - a_2 y[n-2] \f$ + + The filtfilt version runs the filter twice, forward and backward, to + compensate the phase shifting of the forward operation. + + See also Digital + biquad filter on wikipedia. + + \example temporal/test-biquad.c + +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/** set coefficients of a biquad filter + + \param f filter object as returned by new_aubio_filter() + \param b0 forward filter coefficient + \param b1 forward filter coefficient + \param b2 forward filter coefficient + \param a1 feedback filter coefficient + \param a2 feedback filter coefficient + +*/ +uint_t aubio_filter_set_biquad (aubio_filter_t * f, lsmp_t b0, lsmp_t b1, + lsmp_t b2, lsmp_t a1, lsmp_t a2); + +/** create biquad filter with `b0`, `b1`, `b2`, `a1`, `a2` coeffs + + \param b0 forward filter coefficient + \param b1 forward filter coefficient + \param b2 forward filter coefficient + \param a1 feedback filter coefficient + \param a2 feedback filter coefficient + +*/ +aubio_filter_t *new_aubio_filter_biquad (lsmp_t b0, lsmp_t b1, lsmp_t b2, + lsmp_t a1, lsmp_t a2); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_FILTER_BIQUAD_H */ diff --git a/deps/aubio/src/temporal/c_weighting.c b/deps/aubio/src/temporal/c_weighting.c new file mode 100644 index 00000000..91ada717 --- /dev/null +++ b/deps/aubio/src/temporal/c_weighting.c @@ -0,0 +1,217 @@ +/* + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "types.h" +#include "fvec.h" +#include "lvec.h" +#include "temporal/filter.h" +#include "temporal/c_weighting.h" + +uint_t +aubio_filter_set_c_weighting (aubio_filter_t * f, uint_t samplerate) +{ + uint_t order; lsmp_t *a, *b; lvec_t *as, *bs; + + if ((sint_t)samplerate <= 0) { + AUBIO_ERROR("aubio_filter: failed setting C-weighting with samplerate %d\n", samplerate); + return AUBIO_FAIL; + } + if (f == NULL) { + AUBIO_ERROR("aubio_filter: failed setting C-weighting with filter NULL\n"); + return AUBIO_FAIL; + } + + order = aubio_filter_get_order (f); + if ( order != 5 ) { + AUBIO_ERROR ("aubio_filter: order of C-weighting filter must be 5, not %d\n", order); + return 1; + } + + aubio_filter_set_samplerate (f, samplerate); + bs = aubio_filter_get_feedforward (f); + as = aubio_filter_get_feedback (f); + b = bs->data, a = as->data; + + /* select coefficients according to sampling frequency */ + switch (samplerate) { + + case 8000: + b[0] = 6.782173932405135552414776611840352416038513183593750000e-01; + b[1] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[2] = -1.356434786481027110482955322368070483207702636718750000e+00; + b[3] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[4] = 6.782173932405135552414776611840352416038513183593750000e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -6.589092811505605773447769024642184376716613769531250000e-01; + a[2] = -1.179445664897062595599663836765103042125701904296875000e+00; + a[3] = 4.243329729632123736848825501510873436927795410156250000e-01; + a[4] = 4.147270002091348328754349950031610205769538879394531250e-01; + break; + + case 11025: + b[0] = 6.002357155402652244546857218665536493062973022460937500e-01; + b[1] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[2] = -1.200471431080530448909371443733107298612594604492187500e+00; + b[3] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[4] = 6.002357155402652244546857218665536493062973022460937500e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -8.705602141280316397242700077185872942209243774414062500e-01; + a[2] = -9.037199507150940336330791069485712796449661254882812500e-01; + a[3] = 4.758433040929530011275971901341108605265617370605468750e-01; + a[4] = 2.987653956523212417373258631414500996470451354980468750e-01; + break; + + case 16000: + b[0] = 4.971057193673903418229542694461997598409652709960937500e-01; + b[1] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[2] = -9.942114387347806836459085388923995196819305419921875000e-01; + b[3] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[4] = 4.971057193673903418229542694461997598409652709960937500e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -1.162322939286873690889478893950581550598144531250000000e+00; + a[2] = -4.771961355734982701548574368644040077924728393554687500e-01; + a[3] = 4.736145114694704227886745684372726827859878540039062500e-01; + a[4] = 1.660337524309875301131711466950946487486362457275390625e-01; + break; + + case 22050: + b[0] = 4.033381299002754549754001800465630367398262023925781250e-01; + b[1] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[2] = -8.066762598005509099508003600931260734796524047851562500e-01; + b[3] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[4] = 4.033381299002754549754001800465630367398262023925781250e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -1.449545371157945350404361306573264300823211669921875000e+00; + a[2] = -1.030104190885922088583015465701464563608169555664062500e-02; + a[3] = 3.881857047554073680828423675848171114921569824218750000e-01; + a[4] = 7.171589940116777917022972133054281584918498992919921875e-02; + break; + + case 24000: + b[0] = 3.786678621924967069745093795063439756631851196289062500e-01; + b[1] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[2] = -7.573357243849934139490187590126879513263702392578125000e-01; + b[3] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[4] = 3.786678621924967069745093795063439756631851196289062500e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -1.529945307555420797029910318087786436080932617187500000e+00; + a[2] = 1.283553182116208835061854642844991758465766906738281250e-01; + a[3] = 3.494608072385725350272878131363540887832641601562500000e-01; + a[4] = 5.217291949300089520802359288609295617789030075073242188e-02; + break; + + case 32000: + b[0] = 2.977986488230693340462096330156782642006874084472656250e-01; + b[1] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[2] = -5.955972976461386680924192660313565284013748168945312500e-01; + b[3] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[4] = 2.977986488230693340462096330156782642006874084472656250e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -1.812455387128179218336754274787381291389465332031250000e+00; + a[2] = 6.425013281155662614452239722595550119876861572265625000e-01; + a[3] = 1.619857574578579817448087396769551560282707214355468750e-01; + a[4] = 7.987649713547682189807019881300220731645822525024414062e-03; + break; + + case 44100: + b[0] = 2.170085619492190254220531642204150557518005371093750000e-01; + b[1] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[2] = -4.340171238984380508441063284408301115036010742187500000e-01; + b[3] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[4] = 2.170085619492190254220531642204150557518005371093750000e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -2.134674963687040794013682898366823792457580566406250000e+00; + a[2] = 1.279333533236062692139967111870646476745605468750000000e+00; + a[3] = -1.495598460893957093453821016737492755055427551269531250e-01; + a[4] = 4.908700174624683852664386307651511742733418941497802734e-03; + break; + + case 48000: + b[0] = 1.978871200263932761398422144338837824761867523193359375e-01; + b[1] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[2] = -3.957742400527865522796844288677675649523735046386718750e-01; + b[3] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[4] = 1.978871200263932761398422144338837824761867523193359375e-01; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -2.219172914052801814932536217384040355682373046875000000e+00; + a[2] = 1.455135878947171557129536267893854528665542602539062500e+00; + a[3] = -2.484960738877830532800317087094299495220184326171875000e-01; + a[4] = 1.253882314727246607977129144728678511455655097961425781e-02; + break; + + case 88200: + b[0] = 9.221909851156021020734954163344809785485267639160156250e-02; + b[1] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[2] = -1.844381970231204204146990832668961957097053527832031250e-01; + b[3] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[4] = 9.221909851156021020734954163344809785485267639160156250e-02; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -2.785795902923448696952846148633398115634918212890625000e+00; + a[2] = 2.727736758747444145711824603495188057422637939453125000e+00; + a[3] = -1.097007502819661528548067508381791412830352783203125000e+00; + a[4] = 1.550674356752141103132913713125162757933139801025390625e-01; + break; + + case 96000: + b[0] = 8.182864044979756834585771230194950476288795471191406250e-02; + b[1] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[2] = -1.636572808995951366917154246038990095257759094238281250e-01; + b[3] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[4] = 8.182864044979756834585771230194950476288795471191406250e-02; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -2.856378516857566829401093855267390608787536621093750000e+00; + a[2] = 2.897640237559524045707348705036565661430358886718750000e+00; + a[3] = -1.225265958339703198376469117647502571344375610351562500e+00; + a[4] = 1.840048283551226071530493300087982788681983947753906250e-01; + break; + + case 192000: + b[0] = 2.784755468532278815940728122768632601946592330932617188e-02; + b[1] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[2] = -5.569510937064557631881456245537265203893184661865234375e-02; + b[3] = 0.000000000000000000000000000000000000000000000000000000e+00; + b[4] = 2.784755468532278815940728122768632601946592330932617188e-02; + a[0] = 1.000000000000000000000000000000000000000000000000000000e+00; + a[1] = -3.333298856144166322224009491037577390670776367187500000e+00; + a[2] = 4.111467536240339448738723149290308356285095214843750000e+00; + a[3] = -2.222889041651291641699117462849244475364685058593750000e+00; + a[4] = 4.447204118126878991112960193277103826403617858886718750e-01; + break; + + default: + AUBIO_ERROR ( "sampling rate of C-weighting filter is %d, should be one of\ + 8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000, 192000.\n", + samplerate ); + return 1; + + } + + return 0; +} + +aubio_filter_t * new_aubio_filter_c_weighting (uint_t samplerate) { + aubio_filter_t * f = new_aubio_filter(5); + if (aubio_filter_set_c_weighting(f,samplerate) != AUBIO_OK) { + del_aubio_filter(f); + return NULL; + } + return f; +} diff --git a/deps/aubio/src/temporal/c_weighting.h b/deps/aubio/src/temporal/c_weighting.h new file mode 100644 index 00000000..d87f61fa --- /dev/null +++ b/deps/aubio/src/temporal/c_weighting.h @@ -0,0 +1,88 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#ifndef AUBIO_FILTER_C_DESIGN_H +#define AUBIO_FILTER_C_DESIGN_H + +/** \file + + C-weighting filter coefficients + + This file creates a C-weighting digital filter, which reduces low and high + frequencies and enhance the middle ones to reflect the ability of the human + hearing. + + The implementation is based on the following standard: + + - IEC/CD 1672: Electroacoustics-Sound Level Meters, IEC, Geneva, Nov. 1996, + for A- and C-weighting filters. + + See also: + + - A-Weighting on + Wikipedia + - Weighting filter on + Wikipedia + - Christophe + Couvreur's 'octave' toolbox + + The coefficients in this file have been computed using Christophe Couvreur's + scripts in octave 3.0 (debian package 1:3.0.5-6+b2 with octave-signal + 1.0.9-1+b1 on i386), with
 [b, a] = cdsign(1/Fs) 
for various + sampling frequencies (8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, + 88200, 96000, and 192000 Hz). + + The sampling frequency should normally be higher than 20kHz, but most common + file sampling rates have been included for completeness. + + \example temporal/test-c_weighting.c + +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/** create new C-design filter + + \param samplerate sampling frequency of the signal to filter. Should be one of + 8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000, and + 192000 Hz + + \return a new filter object + +*/ +aubio_filter_t *new_aubio_filter_c_weighting (uint_t samplerate); + +/** set feedback and feedforward coefficients of a C-weighting filter + + \param f filter object to get coefficients from + \param samplerate sampling frequency of the signal to filter. Should be one of + 8000, 11025, 16000, 22050, 24000, 32000, 44100, 48000, 88200, 96000, and + 192000 Hz + +*/ +uint_t aubio_filter_set_c_weighting (aubio_filter_t * f, uint_t samplerate); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_FILTER_C_DESIGN_H */ diff --git a/deps/aubio/src/temporal/filter.c b/deps/aubio/src/temporal/filter.c new file mode 100644 index 00000000..776d2e6f --- /dev/null +++ b/deps/aubio/src/temporal/filter.c @@ -0,0 +1,163 @@ +/* + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + + +/* Requires lsmp_t to be long or double. float will NOT give reliable + * results */ + +#include "aubio_priv.h" +#include "fvec.h" +#include "lvec.h" +#include "mathutils.h" +#include "temporal/filter.h" + +struct _aubio_filter_t +{ + uint_t order; + uint_t samplerate; + lvec_t *a; + lvec_t *b; + lvec_t *y; + lvec_t *x; +}; + +void +aubio_filter_do_outplace (aubio_filter_t * f, const fvec_t * in, fvec_t * out) +{ + fvec_copy (in, out); + aubio_filter_do (f, out); +} + +void +aubio_filter_do (aubio_filter_t * f, fvec_t * in) +{ + uint_t j, l, order = f->order; + lsmp_t *x = f->x->data; + lsmp_t *y = f->y->data; + lsmp_t *a = f->a->data; + lsmp_t *b = f->b->data; + + for (j = 0; j < in->length; j++) { + /* new input */ + x[0] = KILL_DENORMAL (in->data[j]); + y[0] = b[0] * x[0]; + for (l = 1; l < order; l++) { + y[0] += b[l] * x[l]; + y[0] -= a[l] * y[l]; + } + /* new output */ + in->data[j] = y[0]; + /* store for next sample */ + for (l = order - 1; l > 0; l--) { + x[l] = x[l - 1]; + y[l] = y[l - 1]; + } + } +} + +/* The rough way: reset memory of filter between each run to avoid end effects. */ +void +aubio_filter_do_filtfilt (aubio_filter_t * f, fvec_t * in, fvec_t * tmp) +{ + uint_t j; + uint_t length = in->length; + /* apply filtering */ + aubio_filter_do (f, in); + aubio_filter_do_reset (f); + /* mirror */ + for (j = 0; j < length; j++) + tmp->data[length - j - 1] = in->data[j]; + /* apply filtering on mirrored */ + aubio_filter_do (f, tmp); + aubio_filter_do_reset (f); + /* invert back */ + for (j = 0; j < length; j++) + in->data[j] = tmp->data[length - j - 1]; +} + +lvec_t * +aubio_filter_get_feedback (const aubio_filter_t * f) +{ + return f->a; +} + +lvec_t * +aubio_filter_get_feedforward (const aubio_filter_t * f) +{ + return f->b; +} + +uint_t +aubio_filter_get_order (const aubio_filter_t * f) +{ + return f->order; +} + +uint_t +aubio_filter_get_samplerate (const aubio_filter_t * f) +{ + return f->samplerate; +} + +uint_t +aubio_filter_set_samplerate (aubio_filter_t * f, uint_t samplerate) +{ + f->samplerate = samplerate; + return AUBIO_OK; +} + +void +aubio_filter_do_reset (aubio_filter_t * f) +{ + lvec_zeros (f->x); + lvec_zeros (f->y); +} + +aubio_filter_t * +new_aubio_filter (uint_t order) +{ + aubio_filter_t *f = AUBIO_NEW (aubio_filter_t); + if ((sint_t)order < 1) { + AUBIO_FREE(f); + return NULL; + } + f->x = new_lvec (order); + f->y = new_lvec (order); + f->a = new_lvec (order); + f->b = new_lvec (order); + /* by default, samplerate is not set */ + f->samplerate = 0; + f->order = order; + /* set default to identity */ + f->a->data[0] = 1.; + f->b->data[0] = 1.; + return f; +} + +void +del_aubio_filter (aubio_filter_t * f) +{ + del_lvec (f->a); + del_lvec (f->b); + del_lvec (f->x); + del_lvec (f->y); + AUBIO_FREE (f); + return; +} diff --git a/deps/aubio/src/temporal/filter.h b/deps/aubio/src/temporal/filter.h new file mode 100644 index 00000000..b8b678e8 --- /dev/null +++ b/deps/aubio/src/temporal/filter.h @@ -0,0 +1,176 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#ifndef AUBIO_FILTER_H +#define AUBIO_FILTER_H + +/** \file + + Digital filter + + This object stores a digital filter of order \f$n\f$. + It contains the following data: + - \f$ n*1 b_i \f$ feedforward coefficients + - \f$ n*1 a_i \f$ feedback coefficients + - \f$ n*c x_i \f$ input signal + - \f$ n*c y_i \f$ output signal + + For convenience, the samplerate of the input signal is also stored in the + object. + + Feedforward and feedback parameters can be modified using + aubio_filter_get_feedback() and aubio_filter_get_feedforward(). + + The function aubio_filter_do_outplace() computes the following output signal + \f$ y[n] \f$ from the input signal \f$ x[n] \f$: + + \f{eqnarray*}{ + y[n] = b_0 x[n] & + & b_1 x[n-1] + b_2 x[n-2] + ... + b_P x[n-P] \\ + & - & a_1 y[n-1] - a_2 y[n-2] - ... - a_P y[n-P] \\ + \f} + + The function aubio_filter_do() executes the same computation but modifies + directly the input signal (in-place). + + The function aubio_filter_do_filtfilt() version runs the filter twice, first + forward then backward, to compensate with the phase shifting of the forward + operation. + + Some convenience functions are provided: + - new_aubio_filter_a_weighting() and aubio_filter_set_a_weighting(), + - new_aubio_filter_c_weighting() and aubio_filter_set_c_weighting(). + - new_aubio_filter_biquad() and aubio_filter_set_biquad(). + + \example temporal/test-filter.c + +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/** Digital filter + +*/ +typedef struct _aubio_filter_t aubio_filter_t; + +/** filter input vector (in-place) + + \param f filter object as returned by new_aubio_filter() + \param in input vector to filter + +*/ +void aubio_filter_do (aubio_filter_t * f, fvec_t * in); + +/** filter input vector (out-of-place) + + \param f filter object as returned by new_aubio_filter() + \param in input vector to filter + \param out output vector to store filtered input + +*/ +void aubio_filter_do_outplace (aubio_filter_t * f, const fvec_t * in, fvec_t * out); + +/** filter input vector forward and backward + + \param f ::aubio_filter_t object as returned by new_aubio_filter() + \param in ::fvec_t input vector to filter + \param tmp memory space to use for computation + +*/ +void aubio_filter_do_filtfilt (aubio_filter_t * f, fvec_t * in, fvec_t * tmp); + +/** returns a pointer to feedback coefficients \f$ a_i \f$ + + \param f filter object to get parameters from + + \return a pointer to the \f$ a_0 ... a_i ... a_P \f$ coefficients + +*/ +lvec_t *aubio_filter_get_feedback (const aubio_filter_t * f); + +/** returns a pointer to feedforward coefficients \f$ b_i \f$ + + \param f filter object to get coefficients from + + \return a pointer to the \f$ b_0 ... b_i ... b_P \f$ coefficients + +*/ +lvec_t *aubio_filter_get_feedforward (const aubio_filter_t * f); + +/** get order of the filter + + \param f filter to get order from + + \return the order of the filter + +*/ +uint_t aubio_filter_get_order (const aubio_filter_t * f); + +/** get sampling rate of the filter + + \param f filter to get sampling rate from + + \return the sampling rate of the filter, in Hz + +*/ +uint_t aubio_filter_get_samplerate (const aubio_filter_t * f); + +/** get sampling rate of the filter + + \param f filter to get sampling rate from + \param samplerate sample rate to set the filter to + + \return the sampling rate of the filter, in Hz + +*/ +uint_t aubio_filter_set_samplerate (aubio_filter_t * f, uint_t samplerate); + +/** reset filter memory + + \param f filter object as returned by new_aubio_filter() + +*/ +void aubio_filter_do_reset (aubio_filter_t * f); + +/** create new filter object + + This function creates a new ::aubio_filter_t object, given the order of the + filter. + + \param order order of the filter (number of coefficients) + + \return the newly created filter object + +*/ +aubio_filter_t *new_aubio_filter (uint_t order); + +/** delete a filter object + + \param f filter object to delete + +*/ +void del_aubio_filter (aubio_filter_t * f); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_FILTER_H */ diff --git a/deps/aubio/src/temporal/resampler.c b/deps/aubio/src/temporal/resampler.c new file mode 100644 index 00000000..adfb08fd --- /dev/null +++ b/deps/aubio/src/temporal/resampler.c @@ -0,0 +1,100 @@ +/* + Copyright (C) 2003-2009 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "fvec.h" +#include "temporal/resampler.h" + +#ifdef HAVE_SAMPLERATE + +#if HAVE_AUBIO_DOUBLE +#error "Should not use libsamplerate with aubio in double precision" +#endif + +#include /* from libsamplerate */ + +struct _aubio_resampler_t +{ + SRC_DATA *proc; + SRC_STATE *stat; + smpl_t ratio; + uint_t type; +}; + +aubio_resampler_t * +new_aubio_resampler (smpl_t ratio, uint_t type) +{ + aubio_resampler_t *s = AUBIO_NEW (aubio_resampler_t); + int error = 0; + s->stat = src_new (type, 1, &error); /* only one channel */ + if (error) { + AUBIO_ERR ("Failed creating resampler: %s\n", src_strerror (error)); + del_aubio_resampler(s); + return NULL; + } + s->proc = AUBIO_NEW (SRC_DATA); + s->ratio = ratio; + return s; +} + +void +del_aubio_resampler (aubio_resampler_t * s) +{ + if (s->stat) src_delete (s->stat); + AUBIO_FREE (s->proc); + AUBIO_FREE (s); +} + +void +aubio_resampler_do (aubio_resampler_t * s, const fvec_t * input, fvec_t * output) +{ + s->proc->input_frames = input->length; + s->proc->output_frames = output->length; + s->proc->src_ratio = (double) s->ratio; + /* make SRC_PROC data point to input outputs */ + s->proc->data_in = (float *) input->data; + s->proc->data_out = (float *) output->data; + /* do resampling */ + src_process (s->stat, s->proc); +} + +#else +struct _aubio_resampler_t +{ + void *dummy; +}; + +aubio_resampler_t * +new_aubio_resampler (smpl_t ratio UNUSED, uint_t type UNUSED) +{ + AUBIO_ERR ("aubio was not compiled with libsamplerate\n"); + return NULL; +} + +void +del_aubio_resampler (aubio_resampler_t * s UNUSED) +{ +} + +void +aubio_resampler_do (aubio_resampler_t * s UNUSED, const fvec_t * input UNUSED, fvec_t * output UNUSED) +{ +} +#endif /* HAVE_SAMPLERATE */ diff --git a/deps/aubio/src/temporal/resampler.h b/deps/aubio/src/temporal/resampler.h new file mode 100644 index 00000000..7528e8ac --- /dev/null +++ b/deps/aubio/src/temporal/resampler.h @@ -0,0 +1,65 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#ifndef AUBIO_RESAMPLER_H +#define AUBIO_RESAMPLER_H + +/** \file + + Resampling object + + This object resamples an input vector into an output vector using + libsamplerate. See http://www.mega-nerd.com/SRC/ + +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/** resampler object */ +typedef struct _aubio_resampler_t aubio_resampler_t; + +/** create resampler object + + \param ratio output_sample_rate / input_sample_rate + \param type libsamplerate resampling type, see http://www.mega-nerd.com/SRC/api_misc.html#Converters + +*/ +aubio_resampler_t *new_aubio_resampler (smpl_t ratio, uint_t type); + +/** delete resampler object */ +void del_aubio_resampler (aubio_resampler_t * s); + +/** resample input in output + + \param s resampler object + \param input input buffer of size N + \param output output buffer of size N*ratio + +*/ +void aubio_resampler_do (aubio_resampler_t * s, const fvec_t * input, + fvec_t * output); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_RESAMPLER_H */ diff --git a/deps/aubio/src/types.h b/deps/aubio/src/types.h new file mode 100644 index 00000000..57df2e0d --- /dev/null +++ b/deps/aubio/src/types.h @@ -0,0 +1,70 @@ +/* + Copyright (C) 2003-2015 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#ifndef AUBIO_TYPES_H +#define AUBIO_TYPES_H + +/** \file + + Definition of data types used in aubio + +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef HAVE_AUBIO_DOUBLE +/** defined to 1 if aubio is compiled in double precision */ +#define HAVE_AUBIO_DOUBLE 0 +#endif + +/** short sample format (32 or 64 bits) */ +#if !HAVE_AUBIO_DOUBLE +typedef float smpl_t; +/** print format for sample in single precision */ +#define AUBIO_SMPL_FMT "%f" +#else +typedef double smpl_t; +/** print format for double in single precision */ +#define AUBIO_SMPL_FMT "%lf" +#endif +/** long sample format (64 bits or more) */ +#if !HAVE_AUBIO_DOUBLE +typedef double lsmp_t; +/** print format for sample in double precision */ +#define AUBIO_LSMP_FMT "%lf" +#else +typedef long double lsmp_t; +/** print format for double in double precision */ +#define AUBIO_LSMP_FMT "%Lf" +#endif +/** unsigned integer */ +typedef unsigned int uint_t; +/** signed integer */ +typedef int sint_t; +/** character */ +typedef char char_t; + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_TYPES_H */ diff --git a/deps/aubio/src/utils/log.c b/deps/aubio/src/utils/log.c new file mode 100644 index 00000000..967c2d6c --- /dev/null +++ b/deps/aubio/src/utils/log.c @@ -0,0 +1,92 @@ +/* + Copyright (C) 2016 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#include "aubio_priv.h" +#include "log.h" + +/** array of pointers to logging functions, one per level */ +static aubio_log_function_t aubio_log_function[AUBIO_LOG_LAST_LEVEL]; +/** array of pointers to closure passed to logging functions, one per level */ +static void* aubio_log_user_data[AUBIO_LOG_LAST_LEVEL]; +/** buffer for logging messages */ +static char aubio_log_buffer[512]; + +/** private function used by default by logging functions */ +void +aubio_default_log(sint_t level, const char_t *message, void * data UNUSED) +{ + FILE *out; + out = stdout; + if (level == AUBIO_LOG_ERR || level == AUBIO_LOG_DBG || level == AUBIO_LOG_WRN) { + out = stderr; + } + fprintf(out, "%s", message); + //fflush(out); +} + +uint_t +aubio_log(sint_t level, const char_t *fmt, ...) +{ + aubio_log_function_t fun = NULL; + + va_list args; + va_start(args, fmt); + vsnprintf(aubio_log_buffer, sizeof(aubio_log_buffer), fmt, args); + va_end(args); + + if ((level >= 0) && (level < AUBIO_LOG_LAST_LEVEL)) { + fun = aubio_log_function[level]; + if (fun != NULL) { + (*fun)(level, aubio_log_buffer, aubio_log_user_data[level]); + } else { + aubio_default_log(level, aubio_log_buffer, NULL); + } + } + return AUBIO_FAIL; +} + +void +aubio_log_reset(void) +{ + uint_t i = 0; + for (i = 0; i < AUBIO_LOG_LAST_LEVEL; i++) { + aubio_log_set_level_function(i, aubio_default_log, NULL); + } +} + +aubio_log_function_t +aubio_log_set_level_function(sint_t level, aubio_log_function_t fun, void * data) +{ + aubio_log_function_t old = NULL; + if ((level >= 0) && (level < AUBIO_LOG_LAST_LEVEL)) { + old = aubio_log_function[level]; + aubio_log_function[level] = fun; + aubio_log_user_data[level] = data; + } + return old; +} + +void +aubio_log_set_function(aubio_log_function_t fun, void * data) { + uint_t i = 0; + for (i = 0; i < AUBIO_LOG_LAST_LEVEL; i++) { + aubio_log_set_level_function(i, fun, data); + } +} diff --git a/deps/aubio/src/utils/log.h b/deps/aubio/src/utils/log.h new file mode 100644 index 00000000..091e91d4 --- /dev/null +++ b/deps/aubio/src/utils/log.h @@ -0,0 +1,99 @@ +/* + Copyright (C) 2016 Paul Brossier + + This file is part of aubio. + + aubio is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + aubio is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with aubio. If not, see . + +*/ + +#ifndef AUBIO_LOG_H +#define AUBIO_LOG_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** \file + + Logging features + + This file specifies ::aubio_log_set_function and + ::aubio_log_set_level_function, which let you define one or several custom + logging functions to redirect warnings and errors from aubio to your + application. The custom function should have the prototype defined in + ::aubio_log_function_t. + + After a call to ::aubio_log_set_level_function, ::aubio_log_reset can be used + to reset each logging functions to the default ones. + + \example utils/test-log.c + +*/ + +/** list of logging levels */ +enum aubio_log_level { + AUBIO_LOG_ERR, /**< critical errors */ + AUBIO_LOG_INF, /**< infos */ + AUBIO_LOG_MSG, /**< general messages */ + AUBIO_LOG_DBG, /**< debug messages */ + AUBIO_LOG_WRN, /**< warnings */ + AUBIO_LOG_LAST_LEVEL, /**< number of valid levels */ +}; + +/** Logging function prototype, to be passed to ::aubio_log_set_function + + \param level log level + \param message text to log + \param data optional closure used by the callback + + See @ref utils/test-log.c for an example of logging function. + + */ +typedef void (*aubio_log_function_t)(sint_t level, const char_t *message, void + *data); + +/** Set logging function for all levels + + \param fun the function to be used to log, of type ::aubio_log_function_t + \param data optional closure to be passed to the function (can be NULL if + nothing to pass) + + */ +void aubio_log_set_function(aubio_log_function_t fun, void* data); + +/** Set logging function for a given level + + \param level the level for which to set the logging function + \param fun the function to be used to log, of type ::aubio_log_function_t + \param data optional closure to be passed to the function (can be NULL if + nothing to pass) + +*/ +aubio_log_function_t aubio_log_set_level_function(sint_t level, + aubio_log_function_t fun, void* data); + +/** Reset all logging functions to the default one + + After calling this function, the default logging function will be used to + print error, warning, normal, and debug messages to `stdout` or `stderr`. + + */ +void aubio_log_reset(void); + +#ifdef __cplusplus +} +#endif + +#endif /* AUBIO_LOG_H */ diff --git a/docs/CARDINAL-MODULES.md b/docs/CARDINAL-MODULES.md index a01dbd40..04a0b5c9 100644 --- a/docs/CARDINAL-MODULES.md +++ b/docs/CARDINAL-MODULES.md @@ -20,6 +20,25 @@ Even though this player plugin can loop files, it is not an audio looper. Audio can loop back to the beginning if enabled, but it does not resample or pitch-shift to fit the host BPM. The audio files are played back as-is, with resampling only done when needed to match the host sample rate. +### Audio To CV Pitch + +![screenshot](Module_AudioToCVPitch.png) + +The Audio To CV Pitch module is a tool that turns your audio signal into CV pitch and CV gate signals. +This allows audio from instruments (such as guitars) to play and control synth sounds and effects. + +It detects the pitch in your incoming audio signal and outputs a 1V/Oct CV pitch signal on the "Pitch Out" CV port. +The "Gate" CV port sends out 10V while a pitch is detected, and resets to 0V when the pitch can no longer be detected. + +There is an Octave right-click option that allows you to shift the detected pitch up or down by a maximum of 4 octaves. +When set to 0, it will output the same pitch as is detected on the input. + +Then the "Hold Output Pitch" right-click option sets whether the plugin resets its outputs to 0, or holds the last detected pitch. + +The Sensitivity parameter can be increased to detect quieter signals, or decreased to reduce artifacts. +The Confidence Threshold can be increased to make sure the correct pitch is being output, or decrease it to get a faster response time. +And finally, the Tolerance parameter influences how quickly you can change pitch, turn it down for a more accurate pitch output, or turn it up to make it easier to jump from one pitch to the next. + ### Carla ![screenshot](Module_Carla.png) @@ -28,8 +47,9 @@ The audio files are played back as-is, with resampling only done when needed to This is a Cardinal/Rack module of Carla with 2 audio and 8 CV IO. Double-click on the panel to show the Carla's own window. -Note it is required for Carla to be installed on your system in order to show its GUI. -This is currently not supported under Windows. +Note that it is required for Carla to be installed on your system in order to show its GUI. +Cardinal Windows installers ship with their own Carla version, for convenience. +On Linux and macOS you will need Carla to be installed in their typical locations. MIDI input and output are possible with the use of expander modules. @@ -44,7 +64,7 @@ You can change this with right-click menu options, in case you want no offset to [Ildaeil](https://github.com/DISTRHO/Ildaeil) is a mini-plugin host based on [Carla](https://kx.studio/Applications:Carla). This is a Cardinal/Rack module of Ildaeil with 2 audio IO. -Currently Ildaeil supports (Carla) internal and LV2 plugins. +Currently Ildaeil supports (Carla) internal, LV2 and JSFX plugins. More plugin support will be added in future releases. There is no way to automate hosted plugin parameters yet. @@ -113,7 +133,30 @@ It has pretty much the same options and functionality as the Rack MIDI-Map. For automating CV sources from the host side, this module directly converts the 24 Cardinal host-exposed parameters into CV signals inside Cardinal. The parameters have an internal slew limiter in order to smooth out the changes over time. -The fall time of the smoothing filter is based on the current host block size and sample rate. +The fall time of the smoothing filter is based on the current host block size and sample rate. +You can disable this smoothing filter using right-click menu options. + +Clicking on an input jack from this module will send a "touch"/"edit" event to the plugin host / DAW, +required for allowing to create parameter automation lines in some hosts. + +### Host Parameters Map + +![screenshot](Module_HostParametersMap.png) + +For automating modules loaded inside Cardinal from within host side, using the 24 Cardinal host-exposed parameters. + +This is similar to Host MIDI CC Map, but instead of having MIDI CC from the host as source of events, it uses host-exposed parameters. + +Simply click on the last item on the list of mappings (which will say "click here to map" or "unmapped" depending if you have already any mappings or not), +and then move a Cardinal-side module knob or controllable widget. + +Anytime you click to either do a new mapping or edit an existing one, a few options appear for setting host parameter, smooth on/off and invert on/off. +It is not possible to reassign an existing mapping to a different knob. +Right-clicking an item on the mapping list will remove it. + +Changing module knobs from Cardinal side will not send a parameter change event to the host. +This module works more in a "one to many" control scheme, where 1 single host parameter can control many cardinal modules, but never the other way around. +If you need to send a "parameter change" signal from Cardinal, use the "Host Parameters" module. ### Host Time @@ -144,6 +187,15 @@ If you find other content we can use, under clear license terms, maybe it could Sometimes we just need to have fun. :) +### Sassy Scope + +![screenshot](Module_SassyScope.png) + +The virtual oscilloscope from the [Sassy Spreadsheet](https://github.com/jarikomppa/sassy) project. +Features time and frequency analysis, input-based trigger sync and allows to pause the analysis for careful inspection. + +Line colors follow the color of the cable connected to its respective input. + ### Expanders MIDI ![screenshot](Module_ExpandersMIDI.png) diff --git a/docs/DEBUGGING.md b/docs/DEBUGGING.md index 9cd50718..27abd547 100644 --- a/docs/DEBUGGING.md +++ b/docs/DEBUGGING.md @@ -12,7 +12,7 @@ By default carla-discovery will do 1 audio processing/run block for testing, whi ``` valgrind --leak-check=full --track-origins=yes --suppressions=./dpf/utils/valgrind-dpf.supp \ -/usr/lib/carla/carla-discovery-native vst2 ./bin/CardinalFX.vst/CardinalFX.so +/usr/lib/carla/carla-discovery-native vst2 ./bin/Cardinal.vst/CardinalFX.so ``` ## Plugin usage @@ -26,5 +26,5 @@ It is recommended to remove all modules from the Rack except for the strictly ne ``` env CARLA_BRIDGE_DUMMY=30 \ valgrind --leak-check=full --track-origins=yes --suppressions=./dpf/utils/valgrind-dpf.supp \ -/usr/lib/carla/carla-bridge-native vst2 ./bin/CardinalFX.vst/CardinalFX.so "" +/usr/lib/carla/carla-bridge-native vst2 ./bin/Cardinal.vst/CardinalFX.so "" ``` diff --git a/docs/DIFFERENCES.md b/docs/DIFFERENCES.md index 3b404efe..cbf1bb33 100644 --- a/docs/DIFFERENCES.md +++ b/docs/DIFFERENCES.md @@ -24,7 +24,8 @@ Bellow follows a list of features comparing the official plugin to Cardinal. | Plugin in AU format | No | Yes | | | Plugin in LV2 format | No | Yes | | | Plugin in VST2 format | Yes | Yes | | -| Plugin in VST3 format | No | WIP | | +| Plugin in VST3 format | No | Yes | | +| Plugin in CLAP format | No | WIP | | | Plugin inside itself | No, will crash | Yes | Technical limitations prevent Rack Pro from loading inside itself | | Multi-threaded engine | Yes | No, uses host audio thread | Intentional in Cardinal, for removing jitter | | Supports ARM systems | No | Yes | This means Apple M1 too, yes | @@ -48,6 +49,7 @@ Additionally, Cardinal contains the following built-in modules not present in th * mscHack (never updated to v2) * rackwindows * Audio File + * Audio to CV Pitch converter * Carla Plugin Host * Ildaeil Host * glBars (OpenGL bars visualization, as seen in XMMS and XBMC/Kodi) diff --git a/docs/LICENSE-PERMISSIONS.md b/docs/LICENSE-PERMISSIONS.md index 3ae45197..7cea36b0 100644 --- a/docs/LICENSE-PERMISSIONS.md +++ b/docs/LICENSE-PERMISSIONS.md @@ -55,6 +55,28 @@ Below follows a direct copy and paste of each individual request. > All the best, > Manu +### Light Panels + +*On Monday, July 25, 2022, 4:31 PM CET, Alexander Chalikiopoulos wrote:* + +> I have another panel-question for you. Filipe has been working on a (silly) feature for Cardinal that brings "real light mode" to all the panels. This is something we have been doing for "dark mode" already. This was not applicable to Befaco panels of course, since they are already dark. However now it will be possible to also flip a switch and turn all panels to "light". +> +> What we are wondering is if you are OK with us changing the panels in this way. We do not modify the source files, but this is done in real time in the rendering itself. If you have any remarks or suggestions we'll be happy to take those into consideration as well of course. +> +> A picture says more than just some words -> https://i.imgur.com/fKBhHCn.png +> +> cheers, +> Alexander + +*On Monday, August 15, 2022, 11:21 AM CET, Manu Retamuro wrote:* + +> I do not see too much trouble on this mod, for the light version! +> +> Thanks a bunch for this!! +> +> All the best, +> Manu + ## ESeries (Paul Schreiber @ SynthTech) *On Wednesday, January 19, 2022, 04:53:44 AM CST, Filipe Coelho wrote:* diff --git a/docs/LICENSES.md b/docs/LICENSES.md index 199fb697..70e6d9c0 100644 --- a/docs/LICENSES.md +++ b/docs/LICENSES.md @@ -21,6 +21,7 @@ Bellow follows a list of all code licenses used in Cardinal and linked submodule | Animated Circuits | GPL-3.0-or-later | | | Arable Instruments | GPL-3.0-or-later | | | Aria Salvatrice | GPL-3.0-or-later | | +| AS | MIT | | | Audible Instruments | GPL-3.0-or-later | | | Autinn | GPL-3.0-or-later | | | Axioma | GPL-3.0-or-later | | @@ -36,6 +37,7 @@ Bellow follows a list of all code licenses used in Cardinal and linked submodule | ExpertSleepers Encoders | MIT | | | Extratone | GPL-3.0-or-later | | | Fehler Fabrik | GPL-3.0-or-later | | +| forsitan modulare | GPL-3.0-or-later | | | Fundamental | GPL-3.0-or-later | | | Glue the Giant | GPL-3.0-or-later | | | GoodSheperd | GPL-3.0-or-later | | @@ -51,12 +53,14 @@ Bellow follows a list of all code licenses used in Cardinal and linked submodule | Little Utils | EUPL-1.2 | | | Lomas Modules | GPL-3.0-or-later | | | Lyrae Modules | GPL-3.0-or-later | | +| Meander | GPL-3.0-or-later | | | MindMeld | GPL-3.0-or-later | | | ML Modules | BSD-3-Clause | | | Mockba Modular | MIT | | | Mog | CC0-1.0 | | | mscHack | BSD-3-Clause | | | MSM | MIT | Repo's [LICENSE-dist.md](https://github.com/netboy3/MSM-vcvrack-plugin/issues/10) includes wrong information | +| Myth | GPL-3.0-or-later | | | Nonlinear Circuits | CC0-1.0 | | | Orbits | GPL-3.0-or-later | | | Parable Instruments | GPL-3.0-or-later | | @@ -71,6 +75,7 @@ Bellow follows a list of all code licenses used in Cardinal and linked submodule | unless_modules | GPL-3.0-or-later | | | Valley | GPL-3.0-or-later | | | Voxglitch | GPL-3.0-or-later | | +| WhatTheRack | WTFPL | | | ZetaCarinae | GPL-3.0-or-later | | | ZZC | GPL-3.0-or-later | | @@ -108,6 +113,9 @@ Below is a list of artwork licenses from plugins | AriaModules/lcd/Fixed_v01/* | Custom | See [LICENSE.txt](../plugins/AriaModules/res/lcd/Fixed_v01/LICENSE.txt) | | AriaModules/lcd/piano/* | WTFPL | | | AriaModules/signature/* | Custom | Removal required if modifying other files without author's permission | +| AS/* | CC-BY-NC-ND-4.0 | The AS Logo/Monogram is Copyright (c) 2017 Alfredo Santamaria and cannot be used in derivative works; Cardinal has [explicit permission](https://github.com/AScustomWorks/AS/issues/60#issuecomment-1133488586) for its use. | +| AS/saxmono.ttf | Custom | You may download this font, circulate it und use it freely. You may not alter, rename, change copyrights or modify this font in any way. | +| AS/Segment7Standard.ttf | OFL-1.1-RFN | | | AudibleInstruments/* | Custom | Copyright © Emilie Gillet, [used and distributed with permission](LICENSE-PERMISSIONS.md#audible-instruments-émilie-gillet--mutable-instruments) | | Autinn/* | GPL-3.0-or-later | No artwork specific license provided | | Axioma/* | GPL-3.0-or-later | No artwork specific license provided | @@ -139,6 +147,7 @@ Below is a list of artwork licenses from plugins | ExpertSleepers-Encoders/* | MIT | [Same license as source code](https://github.com/expertsleepersltd/vcvrack-encoders/issues/3) | | Extratone/* | GPL-3.0-or-later | [Same license as source code](https://github.com/EaterOfSheep/Extratone/issues/7) | | FehlerFabrik/* | GPL-3.0-or-later | No artwork specific license provided, see [FehlerFabrik#17](https://github.com/RCameron93/FehlerFabrik/issues/17) | +| forsitan-modulare/* | GPL-3.0-or-later | No artwork specific license provided | | Fundamental/* | GPL-3.0-or-later | Same license as source code | | GlueTheGiant/* | GPL-3.0-or-later | Same license as source code | | GlueTheGiant/fonts/DSEG7-* | OFL-1.1-RFN | | @@ -162,6 +171,10 @@ Below is a list of artwork licenses from plugins | LomasModules/* | GPL-3.0-or-later | [Same license as source code](https://github.com/LomasModules/LomasModules/issues/26) | | LomasModules/Fonts/FiraMono-Bold.ttf | OFL-1.1-RFN | | | LyraeModules/* | CC-BY-NC-SA-4.0 | | +| Meander/* | GPL-3.0-or-later | No artwork specific license provided | +| Meander/Bravura.otf | OFL-1.1-RFN | | +| Meander/DejaVuSansMono.ttf | Bitstream-Vera | | +| Meander/Ubuntu Condensed 400.ttf | UFL-1.0 | Ubuntu Font License, based on OFL-1.1 | | MindMeld/* | CC-BY-NC-ND-4.0 | | | MindMeld/fonts/RobotoCondensed-*.ttf | Apache-2.0 | | | ML_modules/* | BSD-3-Clause | No artwork specific license provided | @@ -176,6 +189,7 @@ Below is a list of artwork licenses from plugins | MSM/Fonts/DejaVuSansMono.ttf | Bitstream-Vera | | | MSM/Fonts/Segment7Standard.ttf | OFL-1.1-RFN | | | MSM/Fonts/Sudo.ttf | OFL-1.1-no-RFN | | +| Myth/* | GPL-3.0-or-later | No artwork specific license provided | | nonlinearcircuits/* | CC0-1.0 | No artwork specific license provided | | nonlinearcircuits/Audiowide-Regular.ttf | OFL-1.1-RFN | | | Orbits/* | CC-BY-NC-ND-4.0 | | @@ -199,9 +213,11 @@ Below is a list of artwork licenses from plugins | ValleyAudio/ShareTechMono-*.ttf | OFL-1.1-RFN | | | voxglitch/* | GPL-3.0-or-later | No artwork specific license provided | | voxglitch/ShareTechMono-Regular.ttf | OFL-1.1-RFN | | +| WhatTheRack/* | WTFPL | | +| WhatTheRack/BoomButton/* | CC-BY-3.0 | | | ZetaCarinaeModules/* | GPL-3.0-or-later | [Same license as source code](https://github.com/mhampton/ZetaCarinaeModules/issues/8) | | ZZC/* | CC-BY-NC-SA-4.0 | | -| ZZC/panels/* | CC-BY-NC-SA-4.0 | NOTE: The ZZC Logo is Copyright (c) 2019 Sergey Ukolov and cannot be used in derivative works; Cardinal's use does not officially constitute derivative work. | +| ZZC/panels/* | CC-BY-NC-SA-4.0 | The ZZC Logo is Copyright (c) 2019 Sergey Ukolov and cannot be used in derivative works; Cardinal's use does not officially constitute derivative work. | | ZZC/fonts/DSEG/* | OFL-1.1-RFN | | | ZZC/fonts/Nunito/* | OFL-1.1-RFN | | diff --git a/docs/Module_AudioToCVPitch.png b/docs/Module_AudioToCVPitch.png new file mode 100644 index 00000000..359c7528 Binary files /dev/null and b/docs/Module_AudioToCVPitch.png differ diff --git a/docs/Module_HostMIDI.png b/docs/Module_HostMIDI.png index a4e25787..14a64c24 100644 Binary files a/docs/Module_HostMIDI.png and b/docs/Module_HostMIDI.png differ diff --git a/docs/Module_HostParametersMap.png b/docs/Module_HostParametersMap.png new file mode 100644 index 00000000..548f7b8f Binary files /dev/null and b/docs/Module_HostParametersMap.png differ diff --git a/docs/Module_SassyScope.png b/docs/Module_SassyScope.png new file mode 100644 index 00000000..b629c35b Binary files /dev/null and b/docs/Module_SassyScope.png differ diff --git a/docs/Screenshot_Fundamental.png b/docs/Screenshot_Fundamental.png new file mode 100644 index 00000000..17916e7f Binary files /dev/null and b/docs/Screenshot_Fundamental.png differ diff --git a/docs/Screenshot_Init-Patch.png b/docs/Screenshot_Init-Patch.png deleted file mode 100644 index c2f1a076..00000000 Binary files a/docs/Screenshot_Init-Patch.png and /dev/null differ diff --git a/dpf b/dpf index 68de732e..5ddaeefc 160000 --- a/dpf +++ b/dpf @@ -1 +1 @@ -Subproject commit 68de732eecbd1d8febf94e15558c5adaa45dfa9b +Subproject commit 5ddaeefc47bd215c630b372304461a62f3464924 diff --git a/include/common.hpp b/include/common.hpp index 6dd74703..4de06be9 100644 --- a/include/common.hpp +++ b/include/common.hpp @@ -30,6 +30,22 @@ #include_next "common.hpp" +// Workaround for wrong file permissions from zstd extraction and system usage +#ifdef __EMSCRIPTEN__ +#define fopen fopen_wasm +#define system system_wasm + +extern "C" { +FILE* fopen_wasm(const char* filename, const char* mode); +inline int system_wasm(const char*) { return 0; } +} + +namespace std { + using ::fopen_wasm; + using ::system_wasm; +} +#endif + // Make binary resources work the same no matter the OS #undef BINARY #undef BINARY_START @@ -68,7 +84,7 @@ // opens a file browser, startDir and title can be null // action is always triggered on close (path can be null), must be freed if not null -void async_dialog_filebrowser(bool saving, const char* startDir, const char* title, +void async_dialog_filebrowser(bool saving, const char* defaultName, const char* startDir, const char* title, std::function action); // opens a message dialog with only an "ok" button diff --git a/include/engine/Port.hpp b/include/engine/Port.hpp index b5188703..12eb1364 100644 --- a/include/engine/Port.hpp +++ b/include/engine/Port.hpp @@ -32,6 +32,13 @@ #include +/** NOTE alignas is required in some systems in order to allow SSE usage. */ +#ifndef ARCH_MAC +#define SIMD_ALIGN alignas(32) +#else +#define SIMD_ALIGN +#endif + namespace rack { namespace engine { @@ -48,7 +55,7 @@ struct Port { /** Voltage of the port. */ /** NOTE alignas is required in order to allow SSE usage. Consecutive data (like in a vector) would otherwise pack Ports in a way that breaks SSE. */ - union alignas(32) { + union SIMD_ALIGN { /** Unstable API. Use getVoltage() and setVoltage() instead. */ float voltages[PORT_MAX_CHANNELS] = {}; /** DEPRECATED. Unstable API. Use getVoltage() and setVoltage() instead. */ diff --git a/include/helpers.hpp b/include/helpers.hpp index 2a30f1ac..7126f3f5 100644 --- a/include/helpers.hpp +++ b/include/helpers.hpp @@ -68,7 +68,7 @@ struct CardinalPluginModel : CardinalPluginModelHelper tm = dynamic_cast(m); } app::ModuleWidget* const tmw = new TModuleWidget(tm); - DISTRHO_SAFE_ASSERT_RETURN(tmw->module == m, nullptr); + DISTRHO_CUSTOM_SAFE_ASSERT_RETURN(m != nullptr ? m->model->name.c_str() : "null", tmw->module == m, nullptr); tmw->setModel(this); return tmw; } diff --git a/include/haiku-compat/execinfo.h b/include/linux-compat/execinfo.h similarity index 92% rename from include/haiku-compat/execinfo.h rename to include/linux-compat/execinfo.h index 78e164a6..c569c92e 100644 --- a/include/haiku-compat/execinfo.h +++ b/include/linux-compat/execinfo.h @@ -19,7 +19,7 @@ #define pthread_setname_np(...) -static int pthread_getcpuclockid(pthread_t, clockid_t* const clock_id) +int pthread_getcpuclockid(pthread_t, clockid_t* const clock_id) { *clock_id = CLOCK_REALTIME; return 0; diff --git a/include/haiku-compat/ghc/filesystem.hpp b/include/linux-compat/ghc/filesystem.hpp similarity index 96% rename from include/haiku-compat/ghc/filesystem.hpp rename to include/linux-compat/ghc/filesystem.hpp index 83e50ce2..d7033a47 100644 --- a/include/haiku-compat/ghc/filesystem.hpp +++ b/include/linux-compat/ghc/filesystem.hpp @@ -17,6 +17,9 @@ #pragma once +#ifndef __EMSCRIPTEN__ #define GHC_OS_DETECTED #define GHC_OS_LINUX +#endif + #include_next diff --git a/include/osdialog-stub/osdialog.h b/include/osdialog-stub/osdialog.h new file mode 100644 index 00000000..10a75bcf --- /dev/null +++ b/include/osdialog-stub/osdialog.h @@ -0,0 +1,51 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +/** + * This file is an edited version of osdialog.h + * Originally licensed under CC0 1.0 Universal. + */ + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +/** Linked list of patterns. */ +typedef struct osdialog_filter_patterns { + char* pattern; + struct osdialog_filter_patterns* next; +} osdialog_filter_patterns; + +/** Linked list of file filters. */ +typedef struct osdialog_filters { + char* name; + osdialog_filter_patterns* patterns; + struct osdialog_filters* next; +} osdialog_filters; + +/** Parses a filter string. */ +static inline osdialog_filters* osdialog_filters_parse(const char* str) { return NULL; } +static inline void osdialog_filters_free(osdialog_filters* filters) {} + +#ifdef __cplusplus +} +#endif diff --git a/include/settings.hpp b/include/settings.hpp new file mode 100644 index 00000000..49baef74 --- /dev/null +++ b/include/settings.hpp @@ -0,0 +1,29 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +#pragma once + +#include_next "settings.hpp" + +namespace rack { +namespace settings { + +extern bool darkMode; +extern int rateLimit; + +} // namespace settings +} // namespace rack diff --git a/include/simd-compat/mmintrin.h b/include/simd-compat/mmintrin.h new file mode 100644 index 00000000..ce019805 --- /dev/null +++ b/include/simd-compat/mmintrin.h @@ -0,0 +1,26 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +#pragma once + +#if defined(__i386__) || defined(__x86_64__) +# include_next +#elif defined(__EMSCRIPTEN__) +# include +#else +# include "../sse2neon/sse2neon.h" +#endif diff --git a/include/neon-compat/pmmintrin.h b/include/simd-compat/pmmintrin.h similarity index 60% rename from include/neon-compat/pmmintrin.h rename to include/simd-compat/pmmintrin.h index de10d32c..45fa3fb1 100644 --- a/include/neon-compat/pmmintrin.h +++ b/include/simd-compat/pmmintrin.h @@ -1,6 +1,6 @@ /* * DISTRHO Cardinal Plugin - * Copyright (C) 2021 Filipe Coelho + * Copyright (C) 2021-2022 Filipe Coelho * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -17,34 +17,25 @@ #pragma once -#if defined(__i386__) || defined(__x86_64__) || defined(__EMSCRIPTEN__) +#if defined(__i386__) || defined(__x86_64__) # include_next -#else -# include "../sse2neon/sse2neon.h" -static inline -void __builtin_ia32_pause() -{ - __asm__ __volatile__("isb\n"); -} +#elif defined(__EMSCRIPTEN__) +# include_next static inline -__m64 _mm_and_si64(__m64 a, __m64 b) +__m64 _mm_set1_pi16(short w) { - return vreinterpret_s64_s32(vand_s32(vreinterpret_s32_m64(a), vreinterpret_s32_m64(b))); + return __extension__ (__m64){ static_cast(w), static_cast(w) }; } -static inline -__m64 _mm_andnot_si64(__m64 a, __m64 b) -{ - // *NOTE* argument swap - return vreinterpret_s64_s32(vbic_s32(vreinterpret_s32_m64(b), vreinterpret_s32_m64(a))); -} +#else +# include "../sse2neon/sse2neon.h" static inline -__m64 _mm_or_si64(__m64 a, __m64 b) +void __builtin_ia32_pause() { - return vreinterpret_s64_s32(vorr_s32(vreinterpret_s32_m64(a), vreinterpret_s32_m64(b))); + __asm__ __volatile__("isb\n"); } static inline diff --git a/include/simd/Vector.hpp b/include/simd/Vector.hpp index b1640cd1..7dd77ada 100644 --- a/include/simd/Vector.hpp +++ b/include/simd/Vector.hpp @@ -30,6 +30,13 @@ #include #include +/** NOTE alignas is required in some systems in order to allow SSE usage. */ +#ifndef ARCH_MAC +#define SIMD_ALIGN alignas(32) +#else +#define SIMD_ALIGN +#endif + namespace rack { @@ -62,8 +69,7 @@ struct Vector { using type = float; constexpr static int size = 4; - /** NOTE alignas is required in order to allow SSE usage. */ - union alignas(32) { + union SIMD_ALIGN { __m128 v; /** Accessing this array of scalars is slow and defeats the purpose of vectorizing. */ @@ -137,8 +143,7 @@ struct Vector { using type = int32_t; constexpr static int size = 4; - /** NOTE alignas is required in order to allow SSE usage. */ - union alignas(32) { + union SIMD_ALIGN { __m128i v; int32_t s[4]; }; diff --git a/jucewrapper/CMakeLists.txt b/jucewrapper/CMakeLists.txt index 8bab15f2..099ff1d0 100644 --- a/jucewrapper/CMakeLists.txt +++ b/jucewrapper/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.15) -project(Cardinal VERSION 22.03) +project(Cardinal VERSION 22.09) add_subdirectory(JUCE) @@ -14,37 +14,43 @@ add_library(dgl STATIC IMPORTED) set_property(TARGET dgl PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../dpf/build/libdgl-opengl.a") add_library(carla_host_plugin STATIC IMPORTED) -set_property(TARGET carla_host_plugin PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/plugin/Release/carla-host-plugin.cpp.o") +set_property(TARGET carla_host_plugin PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/plugin/${CMAKE_BUILD_TYPE}/carla-host-plugin.cpp.o") add_library(carla_engine_plugin STATIC IMPORTED) -set_property(TARGET carla_engine_plugin PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/Release/carla_engine_plugin.a") +set_property(TARGET carla_engine_plugin PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/${CMAKE_BUILD_TYPE}/carla_engine_plugin.a") add_library(carla_plugin STATIC IMPORTED) -set_property(TARGET carla_plugin PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/Release/carla_plugin.a") +set_property(TARGET carla_plugin PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/${CMAKE_BUILD_TYPE}/carla_plugin.a") add_library(native_plugins STATIC IMPORTED) -set_property(TARGET native_plugins PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/Release/native-plugins.a") +set_property(TARGET native_plugins PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/${CMAKE_BUILD_TYPE}/native-plugins.a") add_library(audio_decoder STATIC IMPORTED) -set_property(TARGET audio_decoder PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/Release/audio_decoder.a") +set_property(TARGET audio_decoder PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/${CMAKE_BUILD_TYPE}/audio_decoder.a") add_library(jackbridge STATIC IMPORTED) -set_property(TARGET jackbridge PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/Release/jackbridge.min.a") +set_property(TARGET jackbridge PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/${CMAKE_BUILD_TYPE}/jackbridge.min.a") add_library(lilv STATIC IMPORTED) -set_property(TARGET lilv PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/Release/lilv.a") +set_property(TARGET lilv PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/${CMAKE_BUILD_TYPE}/lilv.a") add_library(rtmempool STATIC IMPORTED) -set_property(TARGET rtmempool PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/Release/rtmempool.a") +set_property(TARGET rtmempool PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/${CMAKE_BUILD_TYPE}/rtmempool.a") add_library(sfzero STATIC IMPORTED) -set_property(TARGET sfzero PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/Release/sfzero.a") +set_property(TARGET sfzero PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/${CMAKE_BUILD_TYPE}/sfzero.a") add_library(water STATIC IMPORTED) -set_property(TARGET water PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/Release/water.a") +set_property(TARGET water PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/${CMAKE_BUILD_TYPE}/water.a") + +add_library(ysfx STATIC IMPORTED) +set_property(TARGET ysfx PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/${CMAKE_BUILD_TYPE}/ysfx.a") add_library(zita_resampler STATIC IMPORTED) -set_property(TARGET zita_resampler PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/Release/zita-resampler.a") +set_property(TARGET zita_resampler PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../carla/build/modules/${CMAKE_BUILD_TYPE}/zita-resampler.a") + +add_library(sCardinal STATIC IMPORTED) +set_property(TARGET sCardinal PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../bin/Cardinal.a") add_library(sCardinalFX STATIC IMPORTED) set_property(TARGET sCardinalFX PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../bin/CardinalFX.a") @@ -58,6 +64,9 @@ set_property(TARGET sPlugins PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/. add_library(sRack STATIC IMPORTED) set_property(TARGET sRack PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../src/rack.a") +add_library(libaubio STATIC IMPORTED) +set_property(TARGET libaubio PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../deps/aubio/libaubio.a") + add_library(libarchive STATIC IMPORTED) if (WIN32) set_property(TARGET libarchive PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/../src/Rack/dep/lib/libarchive_static.a") @@ -83,6 +92,7 @@ set_property(TARGET libzstd PROPERTY IMPORTED_LOCATION "${PROJECT_SOURCE_DIR}/.. # dependencies find_package(PkgConfig REQUIRED) +pkg_check_modules(FFTW3F REQUIRED fftw3f) pkg_check_modules(LIBLO REQUIRED liblo) pkg_check_modules(SNDFILE REQUIRED sndfile) @@ -103,6 +113,100 @@ set(STATIC_LIBS_END "-Wl,--no-whole-archive") set(PLUGIN_FORMATS Standalone VST3) endif (APPLE) +# Main variant + +#[[ +juce_add_plugin(Cardinal + AU_MAIN_TYPE kAudioUnitType_MusicEffect + COMPANY_COPYRIGHT "GPL-3.0-or-later" + COMPANY_NAME "DISTRHO" + COMPANY_WEBSITE "https://github.com/DISTRHO/Cardinal" + DESCRIPTION "Virtual modular synthesizer plugin" + EDITOR_WANTS_KEYBOARD_FOCUS FALSE + FORMATS ${PLUGIN_FORMATS} + IS_MIDI_EFFECT FALSE + IS_SYNTH FALSE + NEEDS_MIDI_INPUT TRUE + NEEDS_MIDI_OUTPUT TRUE + PLUGIN_CODE DcnM + PLUGIN_MANUFACTURER_CODE Dstr + PRODUCT_NAME "Cardinal") + +target_sources(Cardinal + PRIVATE + CardinalWrapper.cpp) + +target_include_directories(Cardinal + PRIVATE + ../dpf/distrho + ../src/Cardinal) + +target_compile_definitions(Cardinal + PUBLIC + DISTRHO_NAMESPACE=CardinalDISTRHO + DGL_NAMESPACE=CardinalDGL + JucePlugin_PreferredChannelConfigurations=8,8 + JUCE_CHECK_MEMORY_LEAKS=0 + JUCE_DISABLE_NATIVE_FILECHOOSERS=1 + JUCE_DISPLAY_SPLASH_SCREEN=0 + JUCE_MODAL_LOOPS_PERMITTED=0 + JUCE_USE_CURL=0 + JUCE_USE_FLAC=0 + JUCE_USE_OGGVORBIS=0 + JUCE_USE_XINERAMA=0 + JUCE_VST3_CAN_REPLACE_VST2=0 + JUCE_ALSA=1 + JUCE_DIRECTSOUND=0 + JUCE_JACK=1 + JUCE_WASAPI=0 + JUCE_WEB_BROWSER=0) + +target_link_libraries(Cardinal + PRIVATE + juce::juce_audio_utils + ${STATIC_LIBS_START} + sPlugins + sCardinal + sRack + carla_host_plugin + carla_engine_plugin + carla_plugin + native_plugins + audio_decoder + jackbridge + lilv + rtmempool + sfzero + water + ysfx + zita_resampler + dgl + libaubio + libarchive + libjansson + libquickjs + libsamplerate + libspeexdsp + libzstd + ${STATIC_LIBS_END} + ${GL_LIBRARIES} + ${DBUS_LIBRARIES} + -L${LIBLO_LIBRARY_DIRS} + ${FFTW3F_LIBRARIES} + ${LIBLO_LIBRARIES} + ${SNDFILE_LIBRARIES} + ${X11_LIBRARIES} + ${XCURSOR_LIBRARIES} + ${XEXT_LIBRARIES} + ${XRANDR_LIBRARIES} + ${EXTRA_LIBS} + -lmagic + PUBLIC + juce::juce_recommended_config_flags + juce::juce_recommended_lto_flags + juce::juce_recommended_warning_flags) +#]] + # FX variant juce_add_plugin(CardinalFX @@ -111,7 +215,7 @@ juce_add_plugin(CardinalFX COMPANY_NAME "DISTRHO" COMPANY_WEBSITE "https://github.com/DISTRHO/Cardinal" DESCRIPTION "Virtual modular synthesizer plugin" - EDITOR_WANTS_KEYBOARD_FOCUS TRUE + EDITOR_WANTS_KEYBOARD_FOCUS FALSE FORMATS ${PLUGIN_FORMATS} IS_MIDI_EFFECT FALSE IS_SYNTH FALSE @@ -132,6 +236,8 @@ target_include_directories(CardinalFX target_compile_definitions(CardinalFX PUBLIC + DISTRHO_NAMESPACE=CardinalDISTRHO + DGL_NAMESPACE=CardinalDGL JucePlugin_PreferredChannelConfigurations=2,2 JUCE_CHECK_MEMORY_LEAKS=0 JUCE_DISABLE_NATIVE_FILECHOOSERS=1 @@ -152,8 +258,8 @@ target_link_libraries(CardinalFX PRIVATE juce::juce_audio_utils ${STATIC_LIBS_START} - sCardinalFX sPlugins + sCardinalFX sRack carla_host_plugin carla_engine_plugin @@ -165,8 +271,10 @@ target_link_libraries(CardinalFX rtmempool sfzero water + ysfx zita_resampler dgl + libaubio libarchive libjansson libquickjs @@ -177,6 +285,7 @@ target_link_libraries(CardinalFX ${GL_LIBRARIES} ${DBUS_LIBRARIES} -L${LIBLO_LIBRARY_DIRS} + ${FFTW3F_LIBRARIES} ${LIBLO_LIBRARIES} ${SNDFILE_LIBRARIES} ${X11_LIBRARIES} @@ -198,7 +307,7 @@ juce_add_plugin(CardinalSynth COMPANY_NAME "DISTRHO" COMPANY_WEBSITE "https://github.com/DISTRHO/Cardinal" DESCRIPTION "Virtual modular synthesizer plugin" - EDITOR_WANTS_KEYBOARD_FOCUS TRUE + EDITOR_WANTS_KEYBOARD_FOCUS FALSE FORMATS ${PLUGIN_FORMATS} IS_MIDI_EFFECT FALSE IS_SYNTH TRUE @@ -219,6 +328,8 @@ target_include_directories(CardinalSynth target_compile_definitions(CardinalSynth PUBLIC + DISTRHO_NAMESPACE=CardinalDISTRHO + DGL_NAMESPACE=CardinalDGL JucePlugin_PreferredChannelConfigurations=0,2 JUCE_CHECK_MEMORY_LEAKS=0 JUCE_DISABLE_NATIVE_FILECHOOSERS=1 @@ -239,8 +350,8 @@ target_link_libraries(CardinalSynth PRIVATE juce::juce_audio_utils ${STATIC_LIBS_START} - sCardinalSynth sPlugins + sCardinalSynth sRack carla_host_plugin carla_engine_plugin @@ -252,8 +363,10 @@ target_link_libraries(CardinalSynth rtmempool sfzero water + ysfx zita_resampler dgl + libaubio libarchive libjansson libquickjs @@ -264,6 +377,7 @@ target_link_libraries(CardinalSynth ${GL_LIBRARIES} ${DBUS_LIBRARIES} -L${LIBLO_LIBRARY_DIRS} + ${FFTW3F_LIBRARIES} ${LIBLO_LIBRARIES} ${SNDFILE_LIBRARIES} ${X11_LIBRARIES} diff --git a/jucewrapper/CardinalWrapper.cpp b/jucewrapper/CardinalWrapper.cpp index c4da989a..a4fd7e1f 100644 --- a/jucewrapper/CardinalWrapper.cpp +++ b/jucewrapper/CardinalWrapper.cpp @@ -17,6 +17,11 @@ #include +#include +#if MAC_OS_X_VERSION_MAX_ALLOWED > 101200 + #error unwanted macOS version, too new +#endif + #define createPlugin createStaticPlugin #include "src/DistrhoPluginInternal.hpp" #include "src/DistrhoUIInternal.hpp" @@ -363,6 +368,12 @@ class CardinalWrapperProcessor : public juce::AudioProcessor else timePosition.frame = 0; + // use 4/4 as fallback time signature if not provided by the host + if (posInfo.timeSigNumerator == 0) + posInfo.timeSigNumerator = 4; + if (posInfo.timeSigDenominator == 0) + posInfo.timeSigDenominator = 4; + timePosition.bbt.beatsPerMinute = posInfo.bpm; const double ppqPos = std::abs(posInfo.ppqPosition); @@ -396,14 +407,16 @@ class CardinalWrapperProcessor : public juce::AudioProcessor plugin.setTimePosition(timePosition); - DISTRHO_SAFE_ASSERT_RETURN(buffer.getNumChannels() == 2,); + DISTRHO_SAFE_ASSERT_RETURN(buffer.getNumChannels() >= 2,); + + const float* audioBufferIn[18] = {}; + float* audioBufferOut[18] = {}; - const float* audioBufferIn[2]; - float* audioBufferOut[2]; - audioBufferIn[0] = buffer.getReadPointer(0); - audioBufferIn[1] = buffer.getReadPointer(1); - audioBufferOut[0] = buffer.getWritePointer(0); - audioBufferOut[1] = buffer.getWritePointer(1); + for (int i=buffer.getNumChannels(); --i >= 0;) + { + audioBufferIn[i] = buffer.getReadPointer(i); + audioBufferOut[i] = buffer.getWritePointer(i); + } plugin.run(audioBufferIn, audioBufferOut, static_cast(numSamples), midiEvents, midiEventCount); } diff --git a/lv2export/Makefile b/lv2export/Makefile index 0549e88d..53ef3a1c 100644 --- a/lv2export/Makefile +++ b/lv2export/Makefile @@ -14,6 +14,7 @@ SYSDEPS ?= false # -------------------------------------------------------------- # Import base definitions +DISTRHO_NAMESPACE = CardinalLV2 include ../dpf/Makefile.base.mk # -------------------------------------------------------------- @@ -21,9 +22,6 @@ include ../dpf/Makefile.base.mk BUILD_DIR = ../build/lv2export -BASE_FLAGS += -DHEADLESS -BASE_FLAGS += -DPRIVATE= - ifeq ($(MACOS),true) BASE_FLAGS += -DARCH_MAC else ifeq ($(WINDOWS),true) @@ -32,29 +30,31 @@ else BASE_FLAGS += -DARCH_LIN endif -BASE_FLAGS += -fno-finite-math-only -# BASE_FLAGS += -I../dpf/dgl -BASE_FLAGS += -I../dpf/dgl/src/nanovg -BASE_FLAGS += -I../dpf/distrho -BASE_FLAGS += -I../include -BASE_FLAGS += -I../include/neon-compat -BASE_FLAGS += -I../src/Rack/include -ifeq ($(SYSDEPS),true) -BASE_FLAGS += -DCARDINAL_SYSDEPS -BASE_FLAGS += $(shell pkg-config --cflags jansson libarchive samplerate speexdsp) -else -BASE_FLAGS += -DZSTDLIB_VISIBILITY= -BASE_FLAGS += -I../src/Rack/dep/include +ifeq ($(DEBUG),true) +BASE_FLAGS += -UDEBUG endif -BASE_FLAGS += -I../src/Rack/dep/filesystem/include -BASE_FLAGS += -I../src/Rack/dep/fuzzysearchdatabase/src -BASE_FLAGS += -I../src/Rack/dep/glfw/include -BASE_FLAGS += -I../src/Rack/dep/nanosvg/src -# BASE_FLAGS += -IRack/dep/osdialog -BASE_FLAGS += -I../src/Rack/dep/oui-blendish -BASE_FLAGS += -I../src/Rack/dep/pffft + +BASE_FLAGS += -DHEADLESS +BASE_FLAGS += -fno-finite-math-only BASE_FLAGS += -pthread +# might be needed later +# BASE_FLAGS += -I../include/neon-compat +# ifeq ($(SYSDEPS),true) +# BASE_FLAGS += -DCARDINAL_SYSDEPS +# BASE_FLAGS += $(shell pkg-config --cflags jansson libarchive samplerate speexdsp) +# else +# BASE_FLAGS += -DZSTDLIB_VISIBILITY= +# BASE_FLAGS += -I../src/Rack/dep/include +# endif +# BASE_FLAGS += -I../src/Rack/dep/filesystem/include +# BASE_FLAGS += -I../src/Rack/dep/fuzzysearchdatabase/src +# BASE_FLAGS += -I../src/Rack/dep/glfw/include +# BASE_FLAGS += -I../src/Rack/dep/nanosvg/src +# # BASE_FLAGS += -IRack/dep/osdialog +# BASE_FLAGS += -I../src/Rack/dep/oui-blendish +# BASE_FLAGS += -I../src/Rack/dep/pffft + ifeq ($(WINDOWS),true) BASE_FLAGS += -D_USE_MATH_DEFINES BASE_FLAGS += -DWIN32_LEAN_AND_MEAN @@ -65,87 +65,37 @@ endif # -------------------------------------------------------------- # lots of warnings from VCV side -BASE_FLAGS += -Wno-unused-but-set-variable BASE_FLAGS += -Wno-unused-parameter -BASE_FLAGS += -Wno-unused-result BASE_FLAGS += -Wno-unused-variable -ifeq ($(MACOS),true) -BASE_FLAGS += -Wno-unknown-warning-option -endif - # -------------------------------------------------------------- -# extra linker flags +# also from plugins -LINK_FLAGS += -pthread - -ifneq ($(HAIKU_OR_MACOS_OR_WINDOWS),true) -LINK_FLAGS += -ldl -endif +BASE_FLAGS += -Wno-deprecated-declarations +BASE_FLAGS += -Wno-implicit-fallthrough ifeq ($(MACOS),true) -LINK_FLAGS += -framework IOKit -else ifeq ($(WINDOWS),true) -# needed by VCVRack -EXTRA_LIBS += -ldbghelp -lshlwapi -# needed by JW-Modules -EXTRA_LIBS += -lws2_32 -lwinmm -endif - -ifeq ($(SYSDEPS),true) -EXTRA_LIBS += $(shell pkg-config --libs jansson libarchive samplerate speexdsp) +BASE_FLAGS += -Wno-unknown-warning-option endif # -------------------------------------------------------------- -# Build files - -# BUILD_FILES += test.cpp -# BUILD_FILES = dep.cpp -BUILD_FILES += dep2.cpp -BUILD_FILES += ../src/override/context.cpp -BUILD_FILES += ../src/override/RemoteNanoVG.cpp -BUILD_FILES += ../src/Rack/src/logger.cpp -BUILD_FILES += ../src/Rack/src/random.cpp -BUILD_FILES += ../src/Rack/src/string.cpp -BUILD_FILES += ../src/Rack/src/system.cpp -BUILD_FILES += ../src/Rack/src/tinyexpr.c -BUILD_FILES += ../src/Rack/src/Quantity.cpp -BUILD_FILES += ../src/Rack/src/engine/Module.cpp -BUILD_FILES += ../src/Rack/src/engine/ParamQuantity.cpp -BUILD_FILES += ../src/Rack/src/engine/PortInfo.cpp -BUILD_FILES += ../src/Rack/dep/pffft/pffft.c -BUILD_FILES += ../src/Rack/dep/pffft/fftpack.c - -BUILD_OBJS = $(BUILD_FILES:%=$(BUILD_DIR)/%.o) - -# ChowDSP Chorus -BUILD_OBJS += $(BUILD_DIR)/lv2plugin/chowdsp-chorus.o -BUILD_OBJS += $(BUILD_DIR)/plugin/ChowDSP/ChowChorus/ChowChorus.cpp.o -BUILD_OBJS += $(BUILD_DIR)/plugin/ChowDSP/ChowChorus/BBDDelayLine.cpp.o -BUILD_OBJS += $(BUILD_DIR)/plugin/ChowDSP/shared/SineWave.cpp.o -BUILD_OBJS += $(BUILD_DIR)/plugin/ChowDSP/plugin.cpp.o - -# EXTRA_LIBS = ../plugins/plugins.a - -ifneq ($(SYSDEPS),true) -EXTRA_LIBS += ../src/Rack/dep/lib/libjansson.a -EXTRA_LIBS += ../src/Rack/dep/lib/libsamplerate.a -EXTRA_LIBS += ../src/Rack/dep/lib/libspeexdsp.a -ifeq ($(WINDOWS),true) -EXTRA_LIBS += ../src/Rack/dep/lib/libarchive_static.a -else -EXTRA_LIBS += ../src/Rack/dep/lib/libarchive.a -endif -EXTRA_LIBS += ../src/Rack/dep/lib/libzstd.a -endif +# stuff to include + +BUILD_CXX_FLAGS += -I. +BUILD_CXX_FLAGS += -Iincludes +BUILD_CXX_FLAGS += -I../dpf/distrho +BUILD_CXX_FLAGS += -I../plugins # -------------------------------------------------------------- # Build targets -TARGETS = ../bin/CardinalModules.lv2/manifest.ttl -TARGETS += ../bin/CardinalModules.lv2/plugins$(LIB_EXT) +PLUGINS = $(subst plugins/,,$(subst .cpp,,$(wildcard plugins/*.cpp))) + +BINARIES = $(PLUGINS:%=../bin/cardinal-%.lv2/plugin$(LIB_EXT)) +RESOURCES = $(PLUGINS:%=../bin/cardinal-%.lv2/manifest.ttl) +RESOURCES += $(PLUGINS:%=../bin/cardinal-%.lv2/plugin.ttl) -all: $(TARGETS) +all: $(BINARIES) $(RESOURCES) clean: rm -f $(TARGETS) $(BUILD_OBJS) @@ -153,44 +103,36 @@ clean: # -------------------------------------------------------------- # Build commands -../bin/CardinalModules.lv2/manifest.ttl: manifest.ttl.in +../bin/cardinal-%.lv2/manifest.ttl: manifest.ttl.in -@mkdir -p $(shell dirname $@) - sed -e "s/@LIB_EXT@/$(LIB_EXT)/" $< > $@ - # FIXME wildcard install - install -m 644 lv2ttl/* ../bin/CardinalModules.lv2/ + sed -e "s/@LIB_EXT@/$(LIB_EXT)/" -e "s/@SLUG@/$*/" $< > $@ -../bin/CardinalModules.lv2/plugins$(LIB_EXT): $(BUILD_OBJS) +../bin/cardinal-%.lv2/plugin.ttl: ../bin/cardinal-%.lv2/plugin$(LIB_EXT) + ../dpf/utils/lv2_ttl_generator$(APP_EXT) $^ | tail -n +2 > $@ + +../bin/cardinal-%.lv2/plugin$(LIB_EXT): $(BUILD_DIR)/%.cpp.o -@mkdir -p $(shell dirname $@) - $(CXX) $^ $(BUILD_CXX_FLAGS) $(LINK_FLAGS) $(EXTRA_LIBS) $(SHARED) -o $@ + $(SILENT)$(CXX) $< $(LINK_FLAGS) $(SHARED) -o $@ + +# -------------------------------------------------------------- -$(BUILD_DIR)/%.c.o: %.c +$(BUILD_DIR)/aubileinstruments-%.cpp.o: plugins/aubileinstruments-%.cpp -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" @echo "Compiling $<" - $(SILENT)$(CC) $< $(BUILD_C_FLAGS) -c -o $@ - -$(BUILD_DIR)/%.cpp.o: %.cpp + $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -DSLUG='"aubileinstruments-$*"' \ + -DTEST \ + -I../plugins/AudibleInstruments/eurorack \ + -Wno-class-memaccess \ + -Wno-unused-local-typedefs \ + -c -o $@ + +$(BUILD_DIR)/%.cpp.o: plugins/%.cpp -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" @echo "Compiling $<" - $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -c -o $@ - -# -------------------------------------------------------------- - -$(BUILD_DIR)/lv2plugin/chowdsp-chorus.o: lv2plugin.cpp - -@mkdir -p "$(shell dirname $@)" - @echo "Compiling $< (ChowDSP Chorus)" - $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -UPRIVATE -c -o $@ \ - -DPLUGIN_INSTANCE=pluginInstance__ChowDSP \ - -DPLUGIN_MODEL=modelChowChorus \ - -DPLUGIN_URI='"urn:cardinal:chow:chorus"' - -$(BUILD_DIR)/plugin/ChowDSP/%.o: ../plugins/ChowDSP/src/% - -@mkdir -p "$(shell dirname $@)" - @echo "Compiling $< (ChowDSP Chorus)" - $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -UPRIVATE -c -o $@ \ - -DpluginInstance=pluginInstance__ChowDSP + $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -DSLUG='"$*"' -c -o $@ # -------------------------------------------------------------- --include $(BUILD_OBJS:%.o=%.d) +-include $(PLUGINS:%=$(BUILD_DIR)/%.cpp.d) # -------------------------------------------------------------- diff --git a/lv2export/dep2.cpp b/lv2export/dep2.cpp deleted file mode 100644 index ecf7cfbf..00000000 --- a/lv2export/dep2.cpp +++ /dev/null @@ -1,272 +0,0 @@ -/* - * DISTRHO Cardinal Plugin - * Copyright (C) 2021 Filipe Coelho - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation; either version 3 of - * the License, or any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * For a full copy of the GNU General Public License see the LICENSE file. - */ - -#define PRIVATE -#include - -#undef PRIVATE -#include - -using namespace rack; - -namespace rack { -namespace settings { -bool cpuMeter = false; -} -Exception::Exception(const char* format, ...) -{ - va_list args; - va_start(args, format); - msg = string::fV(format, args); - va_end(args); -} -namespace asset { -std::string plugin(plugin::Plugin* plugin, std::string filename) { return {}; } -std::string system(std::string filename) { return {}; } -} -namespace engine { -float Engine::getParamValue(Module* module, int paramId) { return 0.0f; } -float Engine::getParamSmoothValue(Module* module, int paramId) { return 0.0f; } -void Engine::setParamValue(Module* module, int paramId, float value) {} -void Engine::setParamSmoothValue(Module* module, int paramId, float value) {} -} -} - -namespace rack { -namespace app { - -Knob::Knob() {} -Knob::~Knob() {} -void Knob::initParamQuantity() {} -void Knob::onHover(const HoverEvent& e) {} -void Knob::onButton(const ButtonEvent& e) {} -void Knob::onDragStart(const DragStartEvent& e) {} -void Knob::onDragEnd(const DragEndEvent& e) {} -void Knob::onDragMove(const DragMoveEvent& e) {} -void Knob::onDragLeave(const DragLeaveEvent& e) {} -void Knob::onHoverScroll(const HoverScrollEvent& e) {} -void Knob::onLeave(const LeaveEvent& e) {} - -void LightWidget::draw(const DrawArgs& args) {} -void LightWidget::drawLayer(const DrawArgs& args, int layer) {} -void LightWidget::drawBackground(const DrawArgs& args) {} -void LightWidget::drawLight(const DrawArgs& args) {} -void LightWidget::drawHalo(const DrawArgs& args) {} - -ModuleLightWidget::~ModuleLightWidget() {} -engine::Light* ModuleLightWidget::getLight(int colorId) { return nullptr; } -engine::LightInfo* ModuleLightWidget::getLightInfo() { return nullptr; } -void ModuleLightWidget::createTooltip() {} -void ModuleLightWidget::destroyTooltip() {} -void ModuleLightWidget::step() {} -void ModuleLightWidget::onHover(const HoverEvent& e) {} -void ModuleLightWidget::onEnter(const EnterEvent& e) {} -void ModuleLightWidget::onLeave(const LeaveEvent& e) {} - -ModuleWidget::ModuleWidget() {} -ModuleWidget::~ModuleWidget() {} -plugin::Model* ModuleWidget::getModel() { return nullptr; } -void ModuleWidget::setModel(plugin::Model* model) {} -engine::Module* ModuleWidget::getModule() { return nullptr; } -void ModuleWidget::setModule(engine::Module* module) {} -widget::Widget* ModuleWidget::getPanel() { return nullptr; } -void ModuleWidget::setPanel(widget::Widget* panel) {} -void ModuleWidget::setPanel(std::shared_ptr svg) {} -void ModuleWidget::addParam(ParamWidget* param) {} -void ModuleWidget::addInput(PortWidget* input) {} -void ModuleWidget::addOutput(PortWidget* output) {} -ParamWidget* ModuleWidget::getParam(int paramId) { return nullptr; } -PortWidget* ModuleWidget::getInput(int portId) { return nullptr; } -PortWidget* ModuleWidget::getOutput(int portId) { return nullptr; } -std::vector ModuleWidget::getParams() { return {}; } -std::vector ModuleWidget::getPorts() { return {}; } -std::vector ModuleWidget::getInputs() { return {}; } -std::vector ModuleWidget::getOutputs() { return {}; } -void ModuleWidget::draw(const DrawArgs& args) {} -void ModuleWidget::drawLayer(const DrawArgs& args, int layer) {} -void ModuleWidget::onHover(const HoverEvent& e) {} -void ModuleWidget::onHoverKey(const HoverKeyEvent& e) {} -void ModuleWidget::onButton(const ButtonEvent& e) {} -void ModuleWidget::onDragStart(const DragStartEvent& e) {} -void ModuleWidget::onDragEnd(const DragEndEvent& e) {} -void ModuleWidget::onDragMove(const DragMoveEvent& e) {} -void ModuleWidget::onDragHover(const DragHoverEvent& e) {} -json_t* ModuleWidget::toJson() { return nullptr; } -void ModuleWidget::fromJson(json_t* rootJ) {} -bool ModuleWidget::pasteJsonAction(json_t* rootJ) { return false; } -void ModuleWidget::copyClipboard() {} -bool ModuleWidget::pasteClipboardAction() { return false; } -void ModuleWidget::load(std::string filename) {} -void ModuleWidget::loadAction(std::string filename) {} -void ModuleWidget::loadTemplate() {} -void ModuleWidget::loadDialog() {} -void ModuleWidget::save(std::string filename) {} -void ModuleWidget::saveTemplate() {} -void ModuleWidget::saveTemplateDialog() {} -bool ModuleWidget::hasTemplate() { return false; } -void ModuleWidget::clearTemplate() {} -void ModuleWidget::clearTemplateDialog() {} -void ModuleWidget::saveDialog() {} -void ModuleWidget::disconnect() {} -void ModuleWidget::resetAction() {} -void ModuleWidget::randomizeAction() {} -void ModuleWidget::appendDisconnectActions(history::ComplexAction* complexAction) {} -void ModuleWidget::disconnectAction() {} -void ModuleWidget::cloneAction(bool cloneCables) {} -void ModuleWidget::bypassAction(bool bypassed) {} -void ModuleWidget::removeAction() {} -void ModuleWidget::createContextMenu() {} -math::Vec& ModuleWidget::dragOffset() { static math::Vec r; return r; } -bool& ModuleWidget::dragEnabled() { static bool r; return r; } -math::Vec& ModuleWidget::oldPos() { static math::Vec r; return r; } -engine::Module* ModuleWidget::releaseModule() { return nullptr; } - -int MultiLightWidget::getNumColors() { return 0; } -void MultiLightWidget::addBaseColor(NVGcolor baseColor) {} -void MultiLightWidget::setBrightnesses(const std::vector& brightnesses) {} - -ParamWidget::ParamWidget() {} -ParamWidget::~ParamWidget() {} -engine::ParamQuantity* ParamWidget::getParamQuantity() { return nullptr; } -void ParamWidget::createTooltip() {} -void ParamWidget::destroyTooltip() {} -void ParamWidget::step() {} -void ParamWidget::draw(const DrawArgs& args) {} -void ParamWidget::onButton(const ButtonEvent& e) {} -void ParamWidget::onDoubleClick(const DoubleClickEvent& e) {} -void ParamWidget::onEnter(const EnterEvent& e) {} -void ParamWidget::onLeave(const LeaveEvent& e) {} -void ParamWidget::createContextMenu() {} -void ParamWidget::resetAction() {} - -PortWidget::PortWidget() {} -PortWidget::~PortWidget() {} -engine::Port* PortWidget::getPort() { return nullptr; } -engine::PortInfo* PortWidget::getPortInfo() { return nullptr; } -void PortWidget::createTooltip() {} -void PortWidget::destroyTooltip() {} -void PortWidget::createContextMenu() {} -void PortWidget::deleteTopCableAction() {} -void PortWidget::step() {} -void PortWidget::draw(const DrawArgs& args) {} -void PortWidget::onButton(const ButtonEvent& e) {} -void PortWidget::onEnter(const EnterEvent& e) {} -void PortWidget::onLeave(const LeaveEvent& e) {} -void PortWidget::onDragStart(const DragStartEvent& e) {} -void PortWidget::onDragEnd(const DragEndEvent& e) {} -void PortWidget::onDragDrop(const DragDropEvent& e) {} -void PortWidget::onDragEnter(const DragEnterEvent& e) {} -void PortWidget::onDragLeave(const DragLeaveEvent& e) {} - -SliderKnob::SliderKnob() {} -void SliderKnob::onHover(const HoverEvent& e) {} -void SliderKnob::onButton(const ButtonEvent& e) {} - -SvgKnob::SvgKnob() {} -void SvgKnob::setSvg(std::shared_ptr svg) {} -void SvgKnob::onChange(const ChangeEvent& e) {} - -SvgPort::SvgPort() {} -void SvgPort::setSvg(std::shared_ptr svg) {} - -SvgScrew::SvgScrew() {} -void SvgScrew::setSvg(std::shared_ptr svg) {} - -SvgSlider::SvgSlider() {} -void SvgSlider::setBackgroundSvg(std::shared_ptr svg) {} -void SvgSlider::setHandleSvg(std::shared_ptr svg) {} -void SvgSlider::setHandlePos(math::Vec minHandlePos, math::Vec maxHandlePos) {} -void SvgSlider::setHandlePosCentered(math::Vec minHandlePosCentered, math::Vec maxHandlePosCentered) {} -void SvgSlider::onChange(const ChangeEvent& e) {} - -} - -namespace engine { - -std::string LightInfo::getName() { return name; } -std::string LightInfo::getDescription() { return description; } - -} - -namespace widget { - -FramebufferWidget::FramebufferWidget() {} -FramebufferWidget::~FramebufferWidget() {} -void FramebufferWidget::setDirty(bool dirty) {} -int FramebufferWidget::getImageHandle() { return 0; } -NVGLUframebuffer* FramebufferWidget::getFramebuffer() { return nullptr; } -math::Vec FramebufferWidget::getFramebufferSize() { return {}; } -void FramebufferWidget::deleteFramebuffer() {} -void FramebufferWidget::step() {} -void FramebufferWidget::draw(const DrawArgs& args) {} -void FramebufferWidget::render(math::Vec scale, math::Vec offsetF, math::Rect clipBox) {} -void FramebufferWidget::drawFramebuffer() {} -void FramebufferWidget::onDirty(const DirtyEvent& e) {} -void FramebufferWidget::onContextCreate(const ContextCreateEvent& e) {} -void FramebufferWidget::onContextDestroy(const ContextDestroyEvent& e) {} - -SvgWidget::SvgWidget() {} -void SvgWidget::wrap() {} -void SvgWidget::setSvg(std::shared_ptr svg) {} -void SvgWidget::draw(const DrawArgs& args) {} - -Widget::~Widget() {} -math::Rect Widget::getBox() { return {}; } -void Widget::setBox(math::Rect box) {} -math::Vec Widget::getPosition() { return {}; } -void Widget::setPosition(math::Vec pos) {} -math::Vec Widget::getSize() { return {}; } -void Widget::setSize(math::Vec size) {} -widget::Widget* Widget::getParent() { return nullptr; } -bool Widget::isVisible() { return false; } -void Widget::setVisible(bool visible) {} -void Widget::requestDelete() {} -math::Rect Widget::getChildrenBoundingBox() { return {}; } -math::Rect Widget::getVisibleChildrenBoundingBox() { return {}; } -bool Widget::isDescendantOf(Widget* ancestor) { return false; } -math::Vec Widget::getRelativeOffset(math::Vec v, Widget* ancestor) { return {}; } -float Widget::getRelativeZoom(Widget* ancestor) { return 0.0f; } -math::Rect Widget::getViewport(math::Rect r) { return {}; } -bool Widget::hasChild(Widget* child) { return false; } -void Widget::addChild(Widget* child) {} -void Widget::addChildBottom(Widget* child) {} -void Widget::addChildBelow(Widget* child, Widget* sibling) {} -void Widget::addChildAbove(Widget* child, Widget* sibling) {} -void Widget::removeChild(Widget* child) {} -void Widget::clearChildren() {} -void Widget::step() {} -void Widget::draw(const DrawArgs& args) {} -void Widget::drawLayer(const DrawArgs& args, int layer) {} -void Widget::drawChild(Widget* child, const DrawArgs& args, int layer) {} - -} - -namespace window { - -Svg::~Svg() {} -void Svg::loadFile(const std::string& filename) {} -void Svg::loadString(const std::string& str) {} -math::Vec Svg::getSize() { return {}; } -int Svg::getNumShapes() { return 0; } -int Svg::getNumPaths() { return 0; } -int Svg::getNumPoints() { return 0; } -void Svg::draw(NVGcontext* vg) {} -std::shared_ptr Svg::load(const std::string& filename) { return {}; } - -} - -} diff --git a/lv2export/export.cpp b/lv2export/export.cpp new file mode 100644 index 00000000..c058ea9c --- /dev/null +++ b/lv2export/export.cpp @@ -0,0 +1,169 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +#ifndef PLUGIN_BRAND +# error PLUGIN_BRAND undefined +#endif + +#ifndef PLUGIN_LABEL +# error PLUGIN_LABEL undefined +#endif + +#ifndef PLUGIN_MODEL +# error PLUGIN_MODEL undefined +#endif + +#ifndef PLUGIN_CV_INPUTS +# error PLUGIN_CV_INPUTS undefined +#endif + +#ifndef PLUGIN_CV_OUTPUTS +# error PLUGIN_CV_OUTPUTS undefined +#endif + +#include + +// ----------------------------------------------------------------------- + +DISTRHO_PLUGIN_EXPORT +void lv2_generate_ttl() +{ + Context context; + context._engine.sampleRate = 48000.f; + contextSet(&context); + + engine::Module* module = PLUGIN_MODEL->createModule(); + + d_stdout("@prefix doap: ."); + d_stdout("@prefix foaf: ."); + d_stdout("@prefix lv2: ."); + d_stdout("@prefix mod: ."); + d_stdout(""); + + d_stdout(""); + d_stdout(" a \"" PLUGIN_LV2_CATEGORY "\", doap:Project ;"); + d_stdout(" doap:name \"" SLUG "\" ;"); + d_stdout(" mod:brand \"" PLUGIN_BRAND "\" ;"); + d_stdout(" mod:label \"" PLUGIN_LABEL "\" ;"); + d_stdout(""); + + int index = 0; + + for (int i=0, numAudio=0, numCV=0; igetNumInputs(); ++i) + { + d_stdout(" lv2:port ["); + if (kCvInputs[i]) + { + d_stdout(" a lv2:InputPort, lv2:CVPort, mod:CVPort ;"); + d_stdout(" lv2:symbol \"lv2_cv_in_%d\" ;", ++numCV); + if (kCvOutputs[i] == Bi) + { + d_stdout(" lv2:minimum -5.0 ;"); + d_stdout(" lv2:maximum 5.0 ;"); + } + else + { + d_stdout(" lv2:minimum 0.0 ;"); + d_stdout(" lv2:maximum 10.0 ;"); + } + } + else + { + d_stdout(" a lv2:InputPort, lv2:AudioPort ;"); + d_stdout(" lv2:symbol \"lv2_audio_in_%d\" ;", ++numAudio); + } + d_stdout(" lv2:name \"%s\" ;", module->getInputInfo(i)->getFullName().c_str()); + d_stdout(" lv2:index %d ;", index++); + d_stdout(" ] ;"); + d_stdout(""); + } + + for (int i=0, numAudio=0, numCV=0; igetNumOutputs(); ++i) + { + d_stdout(" lv2:port ["); + if (kCvOutputs[i]) + { + d_stdout(" a lv2:OutputPort, lv2:CVPort, mod:CVPort ;"); + d_stdout(" lv2:symbol \"lv2_cv_out_%d\" ;", ++numCV); + if (kCvOutputs[i] == Bi) + { + d_stdout(" lv2:minimum -5.0 ;"); + d_stdout(" lv2:maximum 5.0 ;"); + } + else + { + d_stdout(" lv2:minimum 0.0 ;"); + d_stdout(" lv2:maximum 10.0 ;"); + } + } + else + { + d_stdout(" a lv2:OutputPort, lv2:AudioPort ;"); + d_stdout(" lv2:symbol \"lv2_audio_out_%d\" ;", ++numAudio); + } + d_stdout(" lv2:name \"%s\" ;", module->getOutputInfo(i)->getFullName().c_str()); + d_stdout(" lv2:index %d ;", index++); + d_stdout(" ] ;"); + d_stdout(""); + } + + for (int i=0; igetNumParams(); ++i) + { + ParamQuantity* const q = module->getParamQuantity(i); + d_stdout(" lv2:port ["); + d_stdout(" a lv2:InputPort, lv2:ControlPort ;"); + d_stdout(" lv2:index %d ;", index++); + d_stdout(" lv2:symbol \"lv2_param_%d\" ;", i + 1); + d_stdout(" lv2:name \"%s\" ;", q->name.c_str()); + d_stdout(" lv2:default %f ;", q->defaultValue); + d_stdout(" lv2:minimum %f ;", q->minValue); + d_stdout(" lv2:maximum %f ;", q->maxValue); + d_stdout(" ] ;"); + d_stdout(""); + // q->getDescription().c_str() + // q->unit.c_str() + } + + for (int i=0; igetNumLights(); ++i) + { + LightInfo* const li = module->getLightInfo(i); + d_stdout(" lv2:port ["); + d_stdout(" a lv2:OutputPort, lv2:ControlPort ;"); + d_stdout(" lv2:index %d ;", index++); + d_stdout(" lv2:symbol \"lv2_light_%d\" ;", i + 1); + if (!li->name.empty()) + { + d_stdout(" lv2:name \"%s\" ;", li->name.c_str()); + if (!li->description.empty()) + d_stdout(" lv2:comment \"%s\" ;", li->description.c_str()); + } + else + { + d_stdout(" lv2:name \"Light %d\" ;", i + 1); + } + d_stdout(" ] ;"); + d_stdout(""); + // q->getDescription().c_str() + // q->unit.c_str() + } + + d_stdout(" ."); + + delete module; +} + +// ----------------------------------------------------------------------- diff --git a/lv2export/includes/asset.hpp b/lv2export/includes/asset.hpp new file mode 100644 index 00000000..e69de29b diff --git a/lv2export/includes/rack.hpp b/lv2export/includes/rack.hpp new file mode 100644 index 00000000..e1707ab3 --- /dev/null +++ b/lv2export/includes/rack.hpp @@ -0,0 +1,2239 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +/** + * This file contains a substantial amount of code from VCVRack, adjusted for inline use + * Copyright (C) 2016-2021 VCV. + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or (at your option) any later version. + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#define assert(x) + +#define ENUMS(name, count) name, name ## _LAST = name + (count) - 1 + +#define VEC_ARGS(v) (v).x, (v).y +#define RECT_ARGS(r) (r).pos.x, (r).pos.y, (r).size.x, (r).size.y + +#define GLFW_MOUSE_BUTTON_LEFT 0 +#define GLFW_MOUSE_BUTTON_RIGHT 0 + +enum NVGalign { + NVG_ALIGN_LEFT, + NVG_ALIGN_RIGHT +}; +struct NVGcolor { float a; }; +struct NVGpaint {}; +struct NVGcontext {}; +struct NSVGimage {}; + +inline NVGcolor nvgRGB(int r, int g, int b) { return {}; } +inline NVGcolor nvgRGBA(int r, int g, int b, int a) { return {}; } +inline NVGcolor nvgRGBf(float r, float g, float b) { return {}; } +inline NVGcolor nvgRGBAf(float r, float g, float b, float a) { return {}; } +inline NVGcolor nvgTransRGBA(NVGcolor, int) { return {}; } +inline NVGcolor nvgTransRGBAf(NVGcolor, float) { return {}; } +inline void nvgBeginPath(NVGcontext* vg) {} +inline void nvgFillColor(NVGcontext* vg, NVGcolor) {} +inline void nvgFillPaint(NVGcontext* vg, NVGpaint) {} +inline void nvgFill(NVGcontext* vg) {} +inline void nvgStrokeColor(NVGcontext* vg, NVGcolor) {} +inline void nvgStrokeWidth(NVGcontext* vg, float) {} +inline void nvgStroke(NVGcontext* vg) {} +inline void nvgRect(NVGcontext* vg, float a, float b, float c, float d) {} +inline void nvgImageSize(NVGcontext*, int, void*, void*) {} +inline NVGpaint nvgImagePattern(NVGcontext*, float, float, float, float, float, int handle, float) { return {}; } +inline void nvgRoundedRect(NVGcontext* vg, float, float, float, float, float) {} +inline void nvgFontSize(NVGcontext*, int) {} +inline void nvgFontFaceId(NVGcontext*, int) {} +inline void nvgTextLetterSpacing(NVGcontext*, float) {} +inline void nvgText(NVGcontext*, float, float, const char*, const char*) {} +inline void nvgTextAlign(NVGcontext*, NVGalign) {} +inline void nvgSave(NVGcontext*) {} +inline void nvgRestore(NVGcontext*) {} +inline void nvgScale(NVGcontext*, float, float) {} + +struct json_t {}; +inline json_t* json_boolean(bool) { return NULL; } +inline json_t* json_integer(int) { return NULL; } +inline json_t* json_object(void) { return NULL; } +inline json_t* json_object_get(json_t*, const char*) { return NULL; } +inline bool json_is_true(json_t*) { return false; } +inline bool json_boolean_value(json_t*) { return false; } +inline int json_integer_value(json_t*) { return 0; } +inline float json_number_value(json_t*) { return 0.f; } +inline void json_object_set_new(json_t*, const char*, json_t*) {} +inline json_t* json_array(void) { return NULL; } +inline json_t* json_array_get(json_t*, int) { return NULL; } +inline void json_array_insert_new(json_t*, int, json_t*) {} + +namespace rack { + +struct Quantity { + virtual ~Quantity() {} + virtual void setValue(float value) {} + virtual float getValue() { return 0.f; } + virtual float getMinValue() { return 0.f; } + virtual float getMaxValue() { return 1.f; } + virtual float getDefaultValue() { return 0.f; } +// virtual float getDisplayValue(); +// virtual void setDisplayValue(float displayValue); +// virtual int getDisplayPrecision(); +// virtual std::string getDisplayValueString(); +// virtual void setDisplayValueString(std::string s); + virtual std::string getLabel() { return ""; } + virtual std::string getUnit() { return ""; } +// virtual std::string getString(); +// virtual void reset(); +// virtual void randomize(); +// bool isMin(); +// bool isMax(); +// void setMin(); +// void setMax(); +// void toggle(); +// void moveValue(float deltaValue); +// float getRange(); +// bool isBounded(); +// float toScaled(float value); +// float fromScaled(float scaledValue); +// void setScaledValue(float scaledValue); +// float getScaledValue(); +// void moveScaledValue(float deltaScaledValue); +}; + +namespace ui { +struct Menu; +} + +namespace window { +struct Svg; +} + +namespace math { + +template +inline bool isEven(T x) { return x % 2 == 0; } + +template +inline bool isOdd(T x) { return x % 2 != 0; } + +inline int clamp(int x, int a, int b) { return std::max(std::min(x, b), a); } +inline int clampSafe(int x, int a, int b) { return (a <= b) ? clamp(x, a, b) : clamp(x, b, a); } + +inline float clamp(float x, float a = 0.f, float b = 1.f) { return std::fmax(std::fmin(x, b), a); } +inline float clampSafe(float x, float a = 0.f, float b = 1.f) { return (a <= b) ? clamp(x, a, b) : clamp(x, b, a); } + +inline int eucMod(int a, int b) { + int mod = a % b; + if (mod < 0) { + mod += b; + } + return mod; +} + +inline int eucDiv(int a, int b) { + int div = a / b; + int mod = a % b; + if (mod < 0) { + div -= 1; + } + return div; +} + +inline void eucDivMod(int a, int b, int* div, int* mod) { + *div = a / b; + *mod = a % b; + if (*mod < 0) { + *div -= 1; + *mod += b; + } +} + +inline int log2(int n) { + int i = 0; + while (n >>= 1) { + i++; + } + return i; +} + +template +bool isPow2(T n) { return n > 0 && (n & (n - 1)) == 0; } + +template +T sgn(T x) { return x > 0 ? 1 : (x < 0 ? -1 : 0); } + +#if defined __clang__ +__attribute__((optnone)) +#else +__attribute__((optimize("signed-zeros"))) +#endif +inline float normalizeZero(float x) { return x + 0.f; } + +inline float eucMod(float a, float b) { + float mod = std::fmod(a, b); + if (mod < 0.f) { + mod += b; + } + return mod; +} + +inline bool isNear(float a, float b, float epsilon = 1e-6f) { return std::fabs(a - b) <= epsilon; } + +inline float chop(float x, float epsilon = 1e-6f) { return std::fabs(x) <= epsilon ? 0.f : x; } + +inline float rescale(float x, float xMin, float xMax, float yMin, float yMax) { + return yMin + (x - xMin) / (xMax - xMin) * (yMax - yMin); +} + +inline float crossfade(float a, float b, float p) { return a + (b - a) * p; } + +inline float interpolateLinear(const float* p, float x) { + const int xi = x; + const float xf = x - xi; + return crossfade(p[xi], p[xi + 1], xf); +} + +inline void complexMult(float ar, float ai, float br, float bi, float* cr, float* ci) { + *cr = ar * br - ai * bi; + *ci = ar * bi + ai * br; +} + +struct Rect; + +struct Vec { + float x = 0.f; + float y = 0.f; + Vec() {} + Vec(float xy) : x(xy), y(xy) {} + Vec(float x, float y) : x(x), y(y) {} + float& operator[](int i) { return (i == 0) ? x : y; } + const float& operator[](int i) const { return (i == 0) ? x : y; } + Vec neg() const { return Vec(-x, -y); } + Vec plus(Vec b) const { return Vec(x + b.x, y + b.y); } + Vec minus(Vec b) const { return Vec(x - b.x, y - b.y); } + Vec mult(float s) const { return Vec(x * s, y * s); } + Vec mult(Vec b) const { return Vec(x * b.x, y * b.y); } + Vec div(float s) const { return Vec(x / s, y / s); } + Vec div(Vec b) const { return Vec(x / b.x, y / b.y); } + float dot(Vec b) const { return x * b.x + y * b.y; } + float arg() const { return std::atan2(y, x); } + float norm() const { return std::hypot(x, y); } + Vec normalize() const { return div(norm()); } + float square() const { return x * x + y * y; } + float area() const { return x * y; } + Vec rotate(float angle) { + float sin = std::sin(angle); + float cos = std::cos(angle); + return Vec(x * cos - y * sin, x * sin + y * cos); + } + Vec flip() const { return Vec(y, x); } + Vec min(Vec b) const { return Vec(std::fmin(x, b.x), std::fmin(y, b.y)); } + Vec max(Vec b) const { return Vec(std::fmax(x, b.x), std::fmax(y, b.y)); } + Vec abs() const { return Vec(std::fabs(x), std::fabs(y)); } + Vec round() const { return Vec(std::round(x), std::round(y)); } + Vec floor() const { return Vec(std::floor(x), std::floor(y)); } + Vec ceil() const { return Vec(std::ceil(x), std::ceil(y)); } + bool equals(Vec b) const { return x == b.x && y == b.y; } + bool isZero() const { return x == 0.f && y == 0.f; } + bool isFinite() const { return std::isfinite(x) && std::isfinite(y); } + Vec clamp(Rect bound) const; + Vec clampSafe(Rect bound) const; + Vec crossfade(Vec b, float p) { return this->plus(b.minus(*this).mult(p)); } + bool isEqual(Vec b) const { return equals(b); } +}; + +struct Rect { + Vec pos; + Vec size; + Rect() {} + Rect(Vec pos, Vec size) : pos(pos), size(size) {} + Rect(float posX, float posY, float sizeX, float sizeY) : pos(Vec(posX, posY)), size(Vec(sizeX, sizeY)) {} + static Rect fromMinMax(Vec a, Vec b) { return Rect(a, b.minus(a)); } + static Rect fromCorners(Vec a, Vec b) { return fromMinMax(a.min(b), a.max(b)); } + static Rect inf() { return Rect(Vec(-INFINITY, -INFINITY), Vec(INFINITY, INFINITY)); } + bool contains(Vec v) const { + return (pos.x <= v.x) && (size.x == INFINITY || v.x < pos.x + size.x) + && (pos.y <= v.y) && (size.y == INFINITY || v.y < pos.y + size.y); + } + bool contains(Rect r) const { + return (pos.x <= r.pos.x) && (r.pos.x - size.x <= pos.x - r.size.x) + && (pos.y <= r.pos.y) && (r.pos.y - size.y <= pos.y - r.size.y); + } + bool intersects(Rect r) const { + return (r.size.x == INFINITY || pos.x < r.pos.x + r.size.x) && (size.x == INFINITY || r.pos.x < pos.x + size.x) + && (r.size.y == INFINITY || pos.y < r.pos.y + r.size.y) && (size.y == INFINITY || r.pos.y < pos.y + size.y); + } + bool equals(Rect r) const { return pos.equals(r.pos) && size.equals(r.size); } + float getLeft() const { return pos.x; } + float getRight() const { return (size.x == INFINITY) ? INFINITY : (pos.x + size.x); } + float getTop() const { return pos.y; } + float getBottom() const { return (size.y == INFINITY) ? INFINITY : (pos.y + size.y); } + float getWidth() const { return size.x; } + float getHeight() const { return size.y; } + Vec getCenter() const { return pos.plus(size.mult(0.5f)); } + Vec getTopLeft() const { return pos; } + Vec getTopRight() const { return Vec(getRight(), getTop()); } + Vec getBottomLeft() const { return Vec(getLeft(), getBottom()); } + Vec getBottomRight() const { return Vec(getRight(), getBottom()); } + Rect clamp(Rect bound) const { + Rect r; + r.pos.x = math::clampSafe(pos.x, bound.pos.x, bound.pos.x + bound.size.x); + r.pos.y = math::clampSafe(pos.y, bound.pos.y, bound.pos.y + bound.size.y); + r.size.x = math::clamp(pos.x + size.x, bound.pos.x, bound.pos.x + bound.size.x) - r.pos.x; + r.size.y = math::clamp(pos.y + size.y, bound.pos.y, bound.pos.y + bound.size.y) - r.pos.y; + return r; + } + Rect nudge(Rect bound) const { + Rect r; + r.size = size; + r.pos.x = math::clampSafe(pos.x, bound.pos.x, bound.pos.x + bound.size.x - size.x); + r.pos.y = math::clampSafe(pos.y, bound.pos.y, bound.pos.y + bound.size.y - size.y); + return r; + } + Rect expand(Rect b) const { + Rect r; + r.pos.x = std::fmin(pos.x, b.pos.x); + r.pos.y = std::fmin(pos.y, b.pos.y); + r.size.x = std::fmax(pos.x + size.x, b.pos.x + b.size.x) - r.pos.x; + r.size.y = std::fmax(pos.y + size.y, b.pos.y + b.size.y) - r.pos.y; + return r; + } + Rect intersect(Rect b) const { + Rect r; + r.pos.x = std::fmax(pos.x, b.pos.x); + r.pos.y = std::fmax(pos.y, b.pos.y); + r.size.x = std::fmin(pos.x + size.x, b.pos.x + b.size.x) - r.pos.x; + r.size.y = std::fmin(pos.y + size.y, b.pos.y + b.size.y) - r.pos.y; + return r; + } + Rect zeroPos() const { + return Rect(Vec(), size); + } + Rect grow(Vec delta) const { + Rect r; + r.pos = pos.minus(delta); + r.size = size.plus(delta.mult(2.f)); + return r; + } + Rect shrink(Vec delta) const { + Rect r; + r.pos = pos.plus(delta); + r.size = size.minus(delta.mult(2.f)); + return r; + } + Vec interpolate(Vec p) { + return pos.plus(size.mult(p)); + } + bool isContaining(Vec v) const { return contains(v); } + bool isIntersecting(Rect r) const { return intersects(r); } + bool isEqual(Rect r) const { return equals(r); } +}; + +inline Vec Vec::clamp(Rect bound) const { + return Vec(math::clamp(x, bound.pos.x, bound.pos.x + bound.size.x), + math::clamp(y, bound.pos.y, bound.pos.y + bound.size.y)); +} + +inline Vec Vec::clampSafe(Rect bound) const { + return Vec(math::clampSafe(x, bound.pos.x, bound.pos.x + bound.size.x), + math::clampSafe(y, bound.pos.y, bound.pos.y + bound.size.y)); +} +inline Vec operator+(const Vec& a) { return a; } +inline Vec operator-(const Vec& a) { return a.neg(); } +inline Vec operator+(const Vec& a, const Vec& b) { return a.plus(b); } +inline Vec operator-(const Vec& a, const Vec& b) { return a.minus(b); } +inline Vec operator*(const Vec& a, const Vec& b) { return a.mult(b); } +inline Vec operator*(const Vec& a, const float& b) { return a.mult(b); } +inline Vec operator*(const float& a, const Vec& b) { return b.mult(a); } +inline Vec operator/(const Vec& a, const Vec& b) { return a.div(b); } +inline Vec operator/(const Vec& a, const float& b) { return a.div(b); } +inline Vec operator+=(Vec& a, const Vec& b) { return a = a.plus(b); } +inline Vec operator-=(Vec& a, const Vec& b) { return a = a.minus(b); } +inline Vec operator*=(Vec& a, const Vec& b) { return a = a.mult(b); } +inline Vec operator*=(Vec& a, const float& b) { return a = a.mult(b); } +inline Vec operator/=(Vec& a, const Vec& b) { return a = a.div(b); } +inline Vec operator/=(Vec& a, const float& b) { return a = a.div(b); } +inline bool operator==(const Vec& a, const Vec& b) { return a.equals(b); } +inline bool operator!=(const Vec& a, const Vec& b) { return !a.equals(b); } + +inline bool operator==(const Rect& a, const Rect& b) { return a.equals(b); } +inline bool operator!=(const Rect& a, const Rect& b) { return !a.equals(b); } + +} // namespace math + +namespace engine { + +static constexpr const int PORT_MAX_CHANNELS = 16; + +struct Module; + +struct Engine { + float getSampleRate() { return sampleRate; } + // custom + float sampleRate = 0.f; +}; + +struct Light { + float value = 0.f; + inline void setBrightness(float brightness) { + value = brightness; + } + inline float getBrightness() { + return value; + } + inline void setBrightnessSmooth(float brightness, float deltaTime, float lambda = 30.f) { + if (brightness < value) { + // Fade out light + value += (brightness - value) * lambda * deltaTime; + } + else { + // Immediately illuminate light + value = brightness; + } + } + inline void setSmoothBrightness(float brightness, float deltaTime) { + setBrightnessSmooth(brightness, deltaTime); + } + inline void setBrightnessSmooth(float brightness, int frames = 1) { + setBrightnessSmooth(brightness, frames / 44100.f); + } +}; + +struct LightInfo { + Module* module = NULL; + int lightId = -1; + std::string name; + std::string description; + virtual ~LightInfo() {} + virtual std::string getName() { return name; } + virtual std::string getDescription() { return description; } +}; + +struct Param { + float value = 0.f; + inline float getValue() { return value; } + inline void setValue(float value) { this->value = value; } +}; + +struct Port { + union { + float voltages[PORT_MAX_CHANNELS] = {}; + float value; + }; + union { + uint8_t channels = 0; + uint8_t active; + }; + Light plugLights[3]; + enum Type { + INPUT, + OUTPUT, + }; + inline void setVoltage(float voltage, int channel = 0) { voltages[channel] = voltage; } + inline float getVoltage(int channel = 0) { return voltages[channel]; } + inline float getPolyVoltage(int channel) { return isMonophonic() ? getVoltage(0) : getVoltage(channel); } + inline float getNormalVoltage(float normalVoltage, int channel = 0) { + return isConnected() ? getVoltage(channel) : normalVoltage; + } + inline float getNormalPolyVoltage(float normalVoltage, int channel) { + return isConnected() ? getPolyVoltage(channel) : normalVoltage; + } + inline float* getVoltages(int firstChannel = 0) { return &voltages[firstChannel]; } + inline void readVoltages(float* v) { + for (int c = 0; c < channels; c++) { + v[c] = voltages[c]; + } + } + inline void writeVoltages(const float* v) { + for (int c = 0; c < channels; c++) { + voltages[c] = v[c]; + } + } + inline void clearVoltages() { + for (int c = 0; c < channels; c++) { + voltages[c] = 0.f; + } + } + inline float getVoltageSum() { + float sum = 0.f; + for (int c = 0; c < channels; c++) { + sum += voltages[c]; + } + return sum; + } + inline float getVoltageRMS() { + if (channels == 0) { + return 0.f; + } + else if (channels == 1) { + return std::fabs(voltages[0]); + } + else { + float sum = 0.f; + for (int c = 0; c < channels; c++) { + sum += std::pow(voltages[c], 2); + } + return std::sqrt(sum); + } + } +// template +// T getVoltageSimd(int firstChannel) { +// return T::load(&voltages[firstChannel]); +// } +// +// template +// T getPolyVoltageSimd(int firstChannel) { +// return isMonophonic() ? getVoltage(0) : getVoltageSimd(firstChannel); +// } +// +// template +// T getNormalVoltageSimd(T normalVoltage, int firstChannel) { +// return isConnected() ? getVoltageSimd(firstChannel) : normalVoltage; +// } +// +// template +// T getNormalPolyVoltageSimd(T normalVoltage, int firstChannel) { +// return isConnected() ? getPolyVoltageSimd(firstChannel) : normalVoltage; +// } +// +// template +// void setVoltageSimd(T voltage, int firstChannel) { +// voltage.store(&voltages[firstChannel]); +// } + inline void setChannels(int channels) { + if (this->channels == 0) { + return; + } + for (int c = channels; c < this->channels; c++) { + voltages[c] = 0.f; + } + if (channels == 0) { + channels = 1; + } + this->channels = channels; + } + inline int getChannels() { return channels; } + inline bool isConnected() { return channels > 0; } + inline bool isMonophonic() { return channels == 1; } + inline bool isPolyphonic() { return channels > 1; } + inline float normalize(float normalVoltage) { return getNormalVoltage(normalVoltage); } +}; + +struct Output : Port {}; + +struct Input : Port {}; + +struct PortInfo { + Module* module = NULL; + Port::Type type = Port::INPUT; + int portId = -1; + std::string name; + std::string description; + virtual ~PortInfo() {} + virtual std::string getName() { + if (name == "") + return std::string("#") + std::to_string(portId + 1); + return name; + } + std::string getFullName() { + std::string name = getName(); + name += " "; + name += (type == Port::INPUT) ? "input" : "output"; + return name; + } + virtual std::string getDescription() { return description; } +}; + +struct ParamQuantity : Quantity { + Module* module = NULL; + int paramId = -1; + float minValue = 0.f; + float maxValue = 1.f; + float defaultValue = 0.f; + std::string name; + std::string unit; + float displayBase = 0.f; + float displayMultiplier = 1.f; + float displayOffset = 0.f; + int displayPrecision = 5; + std::string description; + bool resetEnabled = true; + bool randomizeEnabled = true; + bool smoothEnabled = false; + bool snapEnabled = false; +// Param* getParam(); +// /** If smoothEnabled is true, requests to the engine to smoothly move to a target value each sample. */ +// void setSmoothValue(float value); +// float getSmoothValue(); +// void setValue(float value) override; +// float getValue() override; + inline float getMinValue() override { return minValue; } + inline float getMaxValue() override { return maxValue; } + inline float getDefaultValue() override { return defaultValue; } +// float getDisplayValue() override; +// void setDisplayValue(float displayValue) override; +// std::string getDisplayValueString() override; +// void setDisplayValueString(std::string s) override; +// int getDisplayPrecision() override; +// std::string getLabel() override; +// std::string getUnit() override; +// void reset() override; +// void randomize() override; + virtual std::string getDescription() { return description; } +// virtual json_t* toJson(); +// virtual void fromJson(json_t* rootJ); +}; + +struct SwitchQuantity : ParamQuantity { +// std::vector labels; +// std::string getDisplayValueString() override; +// void setDisplayValueString(std::string s) override; +}; + +struct Module { + std::vector params; + std::vector
{ +public: + explicit FFTRealWithSize() : FFTReal
(size) {} +}; +} + +struct SassyScopeModule : Module { + enum ParamIds { + NUM_PARAMS + }; + enum InputIds { + INPUT1, + INPUT2, + INPUT3, + INPUT4, + NUM_INPUTS + }; + enum OutputIds { + NUM_OUTPUTS + }; + enum LightIds { + NUM_LIGHTS + }; + + ScopeData scope; + + ffft::FFTRealWithSize fftObj16; + ffft::FFTRealWithSize fftObj32; + ffft::FFTRealWithSize fftObj64; + ffft::FFTRealWithSize fftObj128; + ffft::FFTRealWithSize fftObj256; + ffft::FFTRealWithSize fftObj512; + ffft::FFTRealWithSize fftObj1024; + ffft::FFTRealWithSize fftObj2048; + ffft::FFTRealWithSize fftObj4096; + ffft::FFTRealWithSize fftObj8192; + ffft::FFTRealWithSize fftObj16384; + ffft::FFTRealWithSize fftObj32768; + ffft::FFTRealWithSize fftObj65536; + + SassyScopeModule() + { + config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); + + scope.fft.average = 1; + scope.fft.obj16 = &fftObj16; + scope.fft.obj32 = &fftObj32; + scope.fft.obj64 = &fftObj64; + scope.fft.obj128 = &fftObj128; + scope.fft.obj256 = &fftObj256; + scope.fft.obj512 = &fftObj512; + scope.fft.obj1024 = &fftObj1024; + scope.fft.obj2048 = &fftObj2048; + scope.fft.obj4096 = &fftObj4096; + scope.fft.obj8192 = &fftObj8192; + scope.fft.obj16384 = &fftObj16384; + scope.fft.obj32768 = &fftObj32768; + scope.fft.obj65536 = &fftObj65536; + } + + void process(const ProcessArgs&) override + { + scope.probe(inputs[INPUT1].getVoltage(), + inputs[INPUT2].getVoltage(), + inputs[INPUT3].getVoltage(), + inputs[INPUT4].getVoltage()); + } + + void onSampleRateChange(const SampleRateChangeEvent& e) override + { + scope.realloc(e.sampleRate); + } + + json_t* dataToJson() override + { + json_t* const rootJ = json_object(); + DISTRHO_SAFE_ASSERT_RETURN(rootJ != nullptr, nullptr); + + json_object_set_new(rootJ, "mTimeScale", json_real(scope.mTimeScale)); + json_object_set_new(rootJ, "mTimeScaleSlider", json_integer(scope.mTimeScaleSlider)); + json_object_set_new(rootJ, "mSyncMode", json_integer(scope.mSyncMode)); + json_object_set_new(rootJ, "mSyncChannel", json_integer(scope.mSyncChannel)); + json_object_set_new(rootJ, "mMode", json_integer(scope.mMode)); + json_object_set_new(rootJ, "mDisplay", json_integer(scope.mDisplay)); + json_object_set_new(rootJ, "mFFTZoom", json_integer(scope.mFFTZoom)); + json_object_set_new(rootJ, "mPot", json_integer(scope.mPot)); + json_object_set_new(rootJ, "fft.average", json_integer(scope.fft.average)); + + json_object_set_new(rootJ, "mCh0.mEnabled", json_boolean(scope.mCh[0].mEnabled)); + json_object_set_new(rootJ, "mCh0.mScale", json_real(scope.mCh[0].mScale)); + json_object_set_new(rootJ, "mCh0.mScaleSlider", json_integer(scope.mCh[0].mScaleSlider)); + json_object_set_new(rootJ, "mCh0.mOffset", json_integer(scope.mCh[0].mOffset)); + + json_object_set_new(rootJ, "mCh1.mEnabled", json_boolean(scope.mCh[1].mEnabled)); + json_object_set_new(rootJ, "mCh1.mScale", json_real(scope.mCh[1].mScale)); + json_object_set_new(rootJ, "mCh1.mScaleSlider", json_integer(scope.mCh[1].mScaleSlider)); + json_object_set_new(rootJ, "mCh1.mOffset", json_integer(scope.mCh[1].mOffset)); + + json_object_set_new(rootJ, "mCh2.mEnabled", json_boolean(scope.mCh[2].mEnabled)); + json_object_set_new(rootJ, "mCh2.mScale", json_real(scope.mCh[2].mScale)); + json_object_set_new(rootJ, "mCh2.mScaleSlider", json_integer(scope.mCh[2].mScaleSlider)); + json_object_set_new(rootJ, "mCh2.mOffset", json_integer(scope.mCh[2].mOffset)); + + json_object_set_new(rootJ, "mCh3.mEnabled", json_boolean(scope.mCh[3].mEnabled)); + json_object_set_new(rootJ, "mCh3.mScale", json_real(scope.mCh[3].mScale)); + json_object_set_new(rootJ, "mCh3.mScaleSlider", json_integer(scope.mCh[3].mScaleSlider)); + json_object_set_new(rootJ, "mCh3.mOffset", json_integer(scope.mCh[3].mOffset)); + + return rootJ; + } + + void dataFromJson(json_t* const rootJ) override + { + if (json_t* const mTimeScaleJ = json_object_get(rootJ, "mTimeScale")) + scope.mTimeScale = json_real_value(mTimeScaleJ); + + if (json_t* const mTimeScaleSliderJ = json_object_get(rootJ, "mTimeScaleSlider")) + scope.mTimeScaleSlider = json_integer_value(mTimeScaleSliderJ); + + if (json_t* const mSyncModeJ = json_object_get(rootJ, "mSyncMode")) + scope.mSyncMode = json_integer_value(mSyncModeJ); + + if (json_t* const mSyncChannelJ = json_object_get(rootJ, "mSyncChannel")) + scope.mSyncChannel = json_integer_value(mSyncChannelJ); + + if (json_t* const mModeJ = json_object_get(rootJ, "mMode")) + scope.mMode = json_integer_value(mModeJ); + + if (json_t* const mDisplayJ = json_object_get(rootJ, "mDisplay")) + scope.mDisplay = json_integer_value(mDisplayJ); + + if (json_t* const mFFTZoomJ = json_object_get(rootJ, "mFFTZoom")) + scope.mFFTZoom = json_integer_value(mFFTZoomJ); + + if (json_t* const mPotJ = json_object_get(rootJ, "mPot")) + scope.mPot = json_integer_value(mPotJ); + + if (json_t* const fftAverageJ = json_object_get(rootJ, "fft.average")) + scope.fft.average = json_integer_value(fftAverageJ); + + { + if (json_t* const mCh0mEnabledJ = json_object_get(rootJ, "mCh0.mEnabled")) + scope.mCh[0].mEnabled = json_boolean_value(mCh0mEnabledJ); + + if (json_t* const mCh0mScaleJ = json_object_get(rootJ, "mCh0.mScale")) + scope.mCh[0].mScale = json_real_value(mCh0mScaleJ); + + if (json_t* const mCh0mScaleSliderJ = json_object_get(rootJ, "mCh0.mScaleSlider")) + scope.mCh[0].mScaleSlider = json_integer_value(mCh0mScaleSliderJ); + + if (json_t* const mCh0mOffsetJ = json_object_get(rootJ, "mCh0.mOffset")) + scope.mCh[0].mOffset = json_integer_value(mCh0mOffsetJ); + } + + { + if (json_t* const mCh1mEnabledJ = json_object_get(rootJ, "mCh1.mEnabled")) + scope.mCh[1].mEnabled = json_boolean_value(mCh1mEnabledJ); + + if (json_t* const mCh1mScaleJ = json_object_get(rootJ, "mCh1.mScale")) + scope.mCh[1].mScale = json_real_value(mCh1mScaleJ); + + if (json_t* const mCh1mScaleSliderJ = json_object_get(rootJ, "mCh1.mScaleSlider")) + scope.mCh[1].mScaleSlider = json_integer_value(mCh1mScaleSliderJ); + + if (json_t* const mCh1mOffsetJ = json_object_get(rootJ, "mCh1.mOffset")) + scope.mCh[1].mOffset = json_integer_value(mCh1mOffsetJ); + } + + { + if (json_t* const mCh2mEnabledJ = json_object_get(rootJ, "mCh2.mEnabled")) + scope.mCh[2].mEnabled = json_boolean_value(mCh2mEnabledJ); + + if (json_t* const mCh2mScaleJ = json_object_get(rootJ, "mCh2.mScale")) + scope.mCh[2].mScale = json_real_value(mCh2mScaleJ); + + if (json_t* const mCh2mScaleSliderJ = json_object_get(rootJ, "mCh2.mScaleSlider")) + scope.mCh[2].mScaleSlider = json_integer_value(mCh2mScaleSliderJ); + + if (json_t* const mCh2mOffsetJ = json_object_get(rootJ, "mCh2.mOffset")) + scope.mCh[2].mOffset = json_integer_value(mCh2mOffsetJ); + } + + { + if (json_t* const mCh3mEnabledJ = json_object_get(rootJ, "mCh3.mEnabled")) + scope.mCh[3].mEnabled = json_boolean_value(mCh3mEnabledJ); + + if (json_t* const mCh3mScaleJ = json_object_get(rootJ, "mCh3.mScale")) + scope.mCh[3].mScale = json_real_value(mCh3mScaleJ); + + if (json_t* const mCh3mScaleSliderJ = json_object_get(rootJ, "mCh3.mScaleSlider")) + scope.mCh[3].mScaleSlider = json_integer_value(mCh3mScaleSliderJ); + + if (json_t* const mCh3mOffsetJ = json_object_get(rootJ, "mCh3.mOffset")) + scope.mCh[3].mOffset = json_integer_value(mCh3mOffsetJ); + } + } +}; + +// used for module browser +static ScopeData* getFakeScopeInstance() +{ + static ScopeData scope; + static ffft::FFTReal fftObj16(16*2); + static ffft::FFTReal fftObj32(32*2); + static ffft::FFTReal fftObj64(64*2); + static ffft::FFTReal fftObj128(128*2); + static ffft::FFTReal fftObj256(256*2); + static ffft::FFTReal fftObj512(512*2); + static ffft::FFTReal fftObj1024(1024*2); + static ffft::FFTReal fftObj2048(2048*2); + static ffft::FFTReal fftObj4096(4096*2); + static ffft::FFTReal fftObj8192(8192*2); + static ffft::FFTReal fftObj16384(16384*2); + static ffft::FFTReal fftObj32768(32768*2); + static ffft::FFTReal fftObj65536(65536*2); + + static bool needsInit = true; + + if (needsInit) + { + needsInit = false; + scope.fft.average = 1; + scope.fft.obj16 = &fftObj16; + scope.fft.obj32 = &fftObj32; + scope.fft.obj64 = &fftObj64; + scope.fft.obj128 = &fftObj128; + scope.fft.obj256 = &fftObj256; + scope.fft.obj512 = &fftObj512; + scope.fft.obj1024 = &fftObj1024; + scope.fft.obj2048 = &fftObj2048; + scope.fft.obj4096 = &fftObj4096; + scope.fft.obj8192 = &fftObj8192; + scope.fft.obj16384 = &fftObj16384; + scope.fft.obj32768 = &fftObj32768; + scope.fft.obj65536 = &fftObj65536; + scope.realloc(48000); + } + + return &scope; +} + +struct SassyScopeWidget : ImGuiWidget { + SassyScopeModule* module = nullptr; + int lastClickedSliderBox = -1; + Rect sliderBoxes[8]; + + SassyScopeWidget() + { + for (int i=0; i<8; ++i) + { + sliderBoxes[i].pos = Vec(8 + (i % 4) * 27, 32 + (i / 4) * 153); + sliderBoxes[i].size = Vec(19, 150); + } + } + + void drawImGui() override + { + const float scaleFactor = getScaleFactor(); + + ImGui::SetNextWindowPos(ImVec2(0, 0)); + ImGui::SetNextWindowSize(ImVec2(box.size.x * scaleFactor, box.size.y * scaleFactor)); + + do_show_scope_window(module != nullptr ? &module->scope : getFakeScopeInstance(), scaleFactor); + } + + void onButton(const ButtonEvent& e) override + { + // if mouse press is over draggable areas, do nothing so event can go to Rack + if (e.action == GLFW_PRESS) + { + // bottom left + if (e.pos.x < 116 && e.pos.y >= 335) + return; + // bottom right + if (e.pos.x >= 456 && e.pos.y >= 348) + return; + // fft label + if (e.pos.x >= 491 && e.pos.y >= 54 && e.pos.y <= 74) + return; + // nudge label + if (e.pos.x >= 463 && e.pos.y >= 236 && e.pos.y <= 255) + return; + // center scope + if (e.pos.x >= 110 && e.pos.x <= 452 && e.pos.y >= 0 && e.pos.y <= 350) + return; + + // consume for double-click if event belongs to a slider + lastClickedSliderBox = -1; + for (int i=0; i<8; ++i) + { + if (sliderBoxes[i].contains(e.pos)) + { + lastClickedSliderBox = i; + e.consume(this); + break; + } + } + } + + ImGuiWidget::onButton(e); + } + + void onDoubleClick(const DoubleClickEvent& e) override + { + // handle double-click for slider param reset + if (lastClickedSliderBox != -1) + { + const int i = lastClickedSliderBox; + lastClickedSliderBox = -1; + + // fake a mouse release + ButtonEvent e2 = {}; + e2.button = GLFW_MOUSE_BUTTON_LEFT; + e2.action = GLFW_RELEASE; + ImGuiWidget::onButton(e2); + + // do the reset + if (i < 4) + { + module->scope.mCh[i].mScaleSlider = 0; + module->scope.mCh[i].mScale = 1.0f / 5.0f; + } + else + { + module->scope.mCh[i-4].mOffset = 0; + } + + e.consume(this); + return; + } + + ImGuiWidget::onDoubleClick(e); + } +}; + +struct SassyScopeModuleWidget : ModuleWidget { + SassyScopeModule* scopeModule = nullptr; + SassyScopeWidget* scopeWidget = nullptr; + + SassyScopeModuleWidget(SassyScopeModule* const module) { + setModule(module); + box.size = Vec(RACK_GRID_WIDTH * 37, RACK_GRID_HEIGHT); + + scopeModule = module; + scopeWidget = new SassyScopeWidget(); + scopeWidget->box.pos = Vec(0, 0); + scopeWidget->box.size = Vec(box.size.x, box.size.y); + scopeWidget->module = module; + addChild(scopeWidget); + + for (int i=0; i(Vec(5 + 26.5f * i, RACK_GRID_HEIGHT - 40), module, i)); + } + + void draw(const DrawArgs& args) override + { + nvgBeginPath(args.vg); + nvgRect(args.vg, 0.0, 0.0, box.size.x, box.size.y); + nvgFillColor(args.vg, nvgRGB(0x20, 0x20, 0x20)); + nvgFill(args.vg); + ModuleWidget::draw(args); + } + + void step() override + { + ModuleWidget::step(); + + if (scopeModule == nullptr) + return; + + // Update colors + for (int i=0; iscene->rack->getTopCable(getInput(i))) + { + NVGcolor c = cableWidget->color; + scopeModule->scope.colors[i] = (clamp(int(c.a * 0xff), 0, 0xff) << 24) + | (clamp(int(c.b * 0xff), 0, 0xff) << 16) + | (clamp(int(c.g * 0xff), 0, 0xff) << 8) + | clamp(int(c.r * 0xff), 0, 0xff); + } + } + } + + void appendContextMenu(Menu* const menu) override + { + menu->addChild(new MenuSeparator); + + struct AveragingItem : MenuItem { + ScopeData* scope; + Menu* createChildMenu() override { + Menu* menu = new Menu; + menu->addChild(createCheckMenuItem("1x", "", + [=]() {return scope->fft.average == 1;}, + [=]() {scope->fft.average = 1;} + )); + menu->addChild(createCheckMenuItem("4x", "", + [=]() {return scope->fft.average == 4;}, + [=]() {scope->fft.average = 4;} + )); + menu->addChild(createCheckMenuItem("16x", "", + [=]() {return scope->fft.average == 16;}, + [=]() {scope->fft.average = 16;} + )); + menu->addChild(createCheckMenuItem("64x", "", + [=]() {return scope->fft.average == 64;}, + [=]() {scope->fft.average = 64;} + )); + menu->addChild(createCheckMenuItem("256x", "", + [=]() {return scope->fft.average == 256;}, + [=]() {scope->fft.average = 256;} + )); + return menu; + } + }; + AveragingItem* const averagingItem = new AveragingItem; + averagingItem->text = "Averaging (FFT mode)"; + averagingItem->rightText = string::f("%d", scopeModule->scope.fft.average) + " " + RIGHT_ARROW; + averagingItem->scope = &scopeModule->scope; + menu->addChild(averagingItem); + } +}; + +// -------------------------------------------------------------------------------------------------------------------- + +Model* modelSassyScope = createModel("SassyScope"); + +// -------------------------------------------------------------------------------------------------------------------- + diff --git a/plugins/Cardinal/src/TextEditor.cpp b/plugins/Cardinal/src/TextEditor.cpp index cbcda030..ba03cc17 100644 --- a/plugins/Cardinal/src/TextEditor.cpp +++ b/plugins/Cardinal/src/TextEditor.cpp @@ -19,7 +19,6 @@ #ifndef HEADLESS # include "ImGuiTextEditor.hpp" -# include "extra/FileBrowserDialog.hpp" #endif #include @@ -79,6 +78,9 @@ struct TextEditorModule : Module { return rootJ; } + void process(const ProcessArgs&) override + {} + void dataFromJson(json_t* const rootJ) override { file.clear(); @@ -233,7 +235,7 @@ struct TextEditorLoadFileItem : MenuItem { TextEditorModule* const module = this->module;; WeakPtr widget = this->widget; - async_dialog_filebrowser(false, nullptr, text.c_str(), [module, widget](char* path) + async_dialog_filebrowser(false, nullptr, nullptr, text.c_str(), [module, widget](char* path) { if (path) { @@ -322,7 +324,7 @@ struct ModuleResizeHandle : OpaqueWidget { nvgMoveTo(args.vg, x + 0.5, margin + 0.5); nvgLineTo(args.vg, x + 0.5, box.size.y - margin + 0.5); nvgStrokeWidth(args.vg, 1.0); - nvgStrokeColor(args.vg, nvgRGBAf(0.5, 0.5, 0.5, 0.5)); + nvgStrokeColor(args.vg, nvgRGBAf(0.5f, 0.5f, 0.5f, 0.5f)); nvgStroke(args.vg); } } @@ -347,8 +349,8 @@ struct TextEditorModuleWidget : ModuleWidget { textEditorModule = module; textEditorWidget = new ImGuiTextEditor(); - textEditorWidget->box.pos = Vec(RACK_GRID_WIDTH, 0); - textEditorWidget->box.size = Vec(box.size.x - 2 * RACK_GRID_WIDTH, box.size.y); + textEditorWidget->box.pos = Vec(RACK_GRID_WIDTH + 1, 1); + textEditorWidget->box.size = Vec(box.size.x - 2 * RACK_GRID_WIDTH - 2, box.size.y - 2); addChild(textEditorWidget); if (module != nullptr) @@ -382,7 +384,8 @@ struct TextEditorModuleWidget : ModuleWidget { { nvgBeginPath(args.vg); nvgRect(args.vg, 0.0, 0.0, box.size.x, box.size.y); - nvgFillColor(args.vg, nvgRGB(0x20, 0x20, 0x20)); + nvgFillColor(args.vg, settings::darkMode ? nvgRGB(0x20, 0x20, 0x20) + : nvgRGB(0xe6, 0xe6, 0xe6)); nvgFill(args.vg); ModuleWidget::draw(args); } diff --git a/plugins/Cardinal/src/Widgets.hpp b/plugins/Cardinal/src/Widgets.hpp index 730262a0..7faff609 100644 --- a/plugins/Cardinal/src/Widgets.hpp +++ b/plugins/Cardinal/src/Widgets.hpp @@ -61,9 +61,8 @@ struct CardinalLedDisplayChoice : LedDisplayChoice { } }; +template struct NanoKnob : Knob { - static const int ringSize = 4; - std::string displayLabel = "Level"; std::string displayString = "0 dB"; float normalizedValue = 0.5f; @@ -81,14 +80,14 @@ struct NanoKnob : Knob { const float w = box.size.x; const float h = box.size.y; - const int knobSize = std::min(w, h - BND_WIDGET_HEIGHT * 2) - ringSize; + const int knobSize = std::min(w, h - BND_WIDGET_HEIGHT * heightPadding) - ringSize; const int knobStartX = w / 2 - knobSize / 2; const int knobStartY = ringSize; const int knobCenterX = knobStartX + knobSize / 2; const int knobCenterY = knobStartY + knobSize / 2; - const NVGcolor testing = nvgRGBf(0.76f, 0.11f, 0.22f); + const NVGcolor cardinalColor = nvgRGBf(0.76f, 0.11f, 0.22f); nvgLineCap(args.vg, NVG_ROUND); @@ -102,7 +101,7 @@ struct NanoKnob : Knob { nvgDegToRad(135.0f) + nvgDegToRad(270.0f * normalizedValue), NVG_CW); nvgStrokeWidth(args.vg, ringSize); - nvgStrokeColor(args.vg, testing); + nvgStrokeColor(args.vg, cardinalColor); nvgStroke(args.vg); // simulate color bleeding @@ -115,7 +114,7 @@ struct NanoKnob : Knob { nvgDegToRad(135.0f) + nvgDegToRad(270.0f * normalizedValue), NVG_CW); nvgStrokeWidth(args.vg, 5); - nvgStrokeColor(args.vg, nvgRGBAf(testing.r, testing.g, testing.b, 0.1f)); + nvgStrokeColor(args.vg, nvgRGBAf(cardinalColor.r, cardinalColor.g, cardinalColor.b, 0.1f)); nvgStroke(args.vg); // line indicator @@ -136,7 +135,7 @@ struct NanoKnob : Knob { float radius = knobSize * 0.5f; float oradius = radius + std::min(radius * 4.f, 15.f); - NVGcolor icol = color::mult(nvgRGBAf(testing.r, testing.g, testing.b, 0.2f), halo); + NVGcolor icol = color::mult(nvgRGBAf(cardinalColor.r, cardinalColor.g, cardinalColor.b, 0.2f), halo); NVGcolor ocol = nvgRGBA(0, 0, 0, 0); NVGpaint paint = nvgRadialGradient(args.vg, knobCenterX, knobCenterY, radius, oradius, icol, ocol); @@ -146,10 +145,13 @@ struct NanoKnob : Knob { nvgFill(args.vg); } - // bottom label (value) - bndIconLabelValue(args.vg, 0, knobSize + ringSize, w, BND_WIDGET_HEIGHT, -1, - testing, BND_CENTER, - BND_LABEL_FONT_SIZE, displayString.c_str(), nullptr); + if (! displayString.empty()) + { + // bottom label (value) + bndIconLabelValue(args.vg, -w, knobSize + ringSize, w*3, BND_WIDGET_HEIGHT, -1, + cardinalColor, BND_CENTER, + BND_LABEL_FONT_SIZE, displayString.c_str(), nullptr); + } Knob::drawLayer(args, layer); } @@ -162,7 +164,7 @@ struct NanoKnob : Knob { const float w = box.size.x; const float h = box.size.y; - const int knobSize = std::min(w, h - BND_WIDGET_HEIGHT * 2) - ringSize; + const int knobSize = std::min(w, h - BND_WIDGET_HEIGHT * heightPadding) - ringSize; const int knobStartX = w / 2 - knobSize / 2; const int knobStartY = ringSize; @@ -224,10 +226,14 @@ struct NanoKnob : Knob { nvgStrokeColor(args.vg, nvgRGBf(0.5f, 0.5f, 0.5f)); nvgStroke(args.vg); - // bottom label (name) - bndIconLabelValue(args.vg, 0, knobStartY + knobSize + BND_WIDGET_HEIGHT * 0.75f, w, BND_WIDGET_HEIGHT, -1, - SCHEME_WHITE, BND_CENTER, - BND_LABEL_FONT_SIZE, displayLabel.c_str(), nullptr); + if (! displayLabel.empty()) + { + // bottom label (name) + bndIconLabelValue(args.vg, -w, knobStartY + knobSize + BND_WIDGET_HEIGHT * 0.75f, + w*3, BND_WIDGET_HEIGHT, -1, + SCHEME_WHITE, BND_CENTER, + BND_LABEL_FONT_SIZE, displayLabel.c_str(), nullptr); + } Knob::draw(args); } @@ -371,8 +377,9 @@ struct OpenGlWidgetWithBrowserPreview : OpenGlWidget { fb = nvgluCreateFramebuffer(args.vg, box.size.x * oversample, box.size.y * oversample, 0); DISTRHO_SAFE_ASSERT_RETURN(fb != nullptr,); - // draw our special framebuffer nvgluBindFramebuffer(fb); + + // draw our special framebuffer drawFramebufferForBrowserPreview(); // reset to regular framebuffer @@ -382,8 +389,8 @@ struct OpenGlWidgetWithBrowserPreview : OpenGlWidget { nvgBeginPath(args.vg); nvgRect(args.vg, 0.0f, 0.0f, box.size.x, box.size.y); NVGpaint paint = nvgImagePattern(args.vg, - 0.0f, 0.0f, box.size.x, box.size.y, - 0.0f, fb->image, 1.0f); + 0.0f, 0.0f, box.size.x, box.size.y, + 0.0f, fb->image, 1.0f); nvgFillPaint(args.vg, paint); nvgFill(args.vg); } diff --git a/plugins/Cardinal/src/glBars.cpp b/plugins/Cardinal/src/glBars.cpp index 979f9f5d..190a77d0 100644 --- a/plugins/Cardinal/src/glBars.cpp +++ b/plugins/Cardinal/src/glBars.cpp @@ -17,6 +17,7 @@ #ifndef HEADLESS # include "glBars.hpp" +# include "ModuleWidgets.hpp" # include "Widgets.hpp" #else # include "plugin.hpp" @@ -129,16 +130,13 @@ struct glBarsRendererWidget : OpenGlWidgetWithBrowserPreview { } }; -struct glBarsWidget : ModuleWidget { +struct glBarsWidget : ModuleWidgetWith25HP { glBarsWidget(glBarsModule* const module) { setModule(module); setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/glBars.svg"))); - addChild(createWidget(Vec(RACK_GRID_WIDTH, 0))); - addChild(createWidget(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); - addChild(createWidget(Vec(RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); - addChild(createWidget(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); + createAndAddScrews(); addInput(createInput(Vec(135.0f, 20.0f), module, glBarsModule::IN1_INPUT)); @@ -151,13 +149,8 @@ struct glBarsWidget : ModuleWidget { void draw(const DrawArgs& args) override { - nvgBeginPath(args.vg); - nvgRect(args.vg, 0, 0, box.size.x, box.size.y); - nvgFillPaint(args.vg, nvgLinearGradient(args.vg, 0, 0, 0, box.size.y, - nvgRGB(0x18, 0x19, 0x19), nvgRGB(0x21, 0x22, 0x22))); - nvgFill(args.vg); - - ModuleWidget::draw(args); + drawBackground(args.vg); + ModuleWidgetWith25HP::draw(args); } }; #else diff --git a/plugins/Cardinal/src/plugin.hpp b/plugins/Cardinal/src/plugin.hpp index b7f67671..96a5a9bb 100644 --- a/plugins/Cardinal/src/plugin.hpp +++ b/plugins/Cardinal/src/plugin.hpp @@ -29,6 +29,7 @@ using namespace rack; extern Plugin* pluginInstance; extern Model* modelAudioFile; +extern Model* modelAudioToCVPitch; extern Model* modelCarla; extern Model* modelCardinalBlank; extern Model* modelExpanderInputMIDI; @@ -42,9 +43,11 @@ extern Model* modelHostMIDICC; extern Model* modelHostMIDIGate; extern Model* modelHostMIDIMap; extern Model* modelHostParameters; +extern Model* modelHostParametersMap; extern Model* modelHostTime; extern Model* modelIldaeil; extern Model* modelMPV; +extern Model* modelSassyScope; extern Model* modelTextEditor; extern std::vector hostTerminalModels; @@ -58,7 +61,7 @@ float d_findMaxNormalizedFloat(const float floats[], const std::size_t count) DISTRHO_SAFE_ASSERT_RETURN(floats != nullptr, 0.0f); DISTRHO_SAFE_ASSERT_RETURN(count > 0, 0.0f); - static const float kEmptyFloats[8192] = {}; + static constexpr const float kEmptyFloats[8192] = {}; if (count <= 8192 && std::memcmp(floats, kEmptyFloats, count) == 0) return 0.0f; @@ -67,6 +70,9 @@ float d_findMaxNormalizedFloat(const float floats[], const std::size_t count) for (std::size_t i=1; i maxf2) diff --git a/plugins/Cardinal/src/plugincontext.hpp b/plugins/Cardinal/src/plugincontext.hpp index 1d25256a..f48b2a83 100644 --- a/plugins/Cardinal/src/plugincontext.hpp +++ b/plugins/Cardinal/src/plugincontext.hpp @@ -21,7 +21,7 @@ #include "DistrhoUtils.hpp" #ifndef HEADLESS -# include "dgl/Base.hpp" +# include "../dgl/Base.hpp" #else # include "extra/LeakDetector.hpp" #endif @@ -36,6 +36,7 @@ static constexpr const uint32_t kModuleParameters = 24; enum CardinalVariant { kCardinalVariantMain, kCardinalVariantFX, + kCardinalVariantNative, kCardinalVariantSynth, }; diff --git a/plugins/Cardinal/src/sassy/fftreal/Array.h b/plugins/Cardinal/src/sassy/fftreal/Array.h new file mode 100644 index 00000000..f31b8979 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/Array.h @@ -0,0 +1,98 @@ +/***************************************************************************** + + Array.h + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if ! defined (ffft_Array_HEADER_INCLUDED) +#define ffft_Array_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +namespace ffft +{ + + + +template +class Array +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef T DataType; + + Array (); + + inline const DataType & + operator [] (long pos) const; + inline DataType & + operator [] (long pos); + + static inline long + size (); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + DataType _data_arr [LEN]; + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + Array (const Array &other); + Array & operator = (const Array &other); + bool operator == (const Array &other); + bool operator != (const Array &other); + +}; // class Array + + + +} // namespace ffft + + + +#include "Array.hpp" + + + +#endif // ffft_Array_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/Array.hpp b/plugins/Cardinal/src/sassy/fftreal/Array.hpp new file mode 100644 index 00000000..0c9c2852 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/Array.hpp @@ -0,0 +1,99 @@ +/***************************************************************************** + + Array.hpp + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if defined (ffft_Array_CURRENT_CODEHEADER) + #error Recursive inclusion of Array code header. +#endif +#define ffft_Array_CURRENT_CODEHEADER + +#if ! defined (ffft_Array_CODEHEADER_INCLUDED) +#define ffft_Array_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include + + + +namespace ffft +{ + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +Array ::Array () +{ + // Nothing +} + + + +template +const typename Array ::DataType & Array ::operator [] (long pos) const +{ + assert (pos >= 0); + assert (pos < LEN); + + return (_data_arr [pos]); +} + + + +template +typename Array ::DataType & Array ::operator [] (long pos) +{ + assert (pos >= 0); + assert (pos < LEN); + + return (_data_arr [pos]); +} + + + +template +long Array ::size () +{ + return (LEN); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +} // namespace ffft + + + +#endif // ffft_Array_CODEHEADER_INCLUDED + +#undef ffft_Array_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/DynArray.h b/plugins/Cardinal/src/sassy/fftreal/DynArray.h new file mode 100644 index 00000000..756e4433 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/DynArray.h @@ -0,0 +1,101 @@ +/***************************************************************************** + + DynArray.h + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if ! defined (ffft_DynArray_HEADER_INCLUDED) +#define ffft_DynArray_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +namespace ffft +{ + + + +template +class DynArray +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef T DataType; + + DynArray (); + explicit DynArray (long size); + ~DynArray (); + + inline long size () const; + inline void resize (long size); + + inline const DataType & + operator [] (long pos) const; + inline DataType & + operator [] (long pos); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + DataType * _data_ptr; + long _len; + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + DynArray (const DynArray &other); + DynArray & operator = (const DynArray &other); + bool operator == (const DynArray &other); + bool operator != (const DynArray &other); + +}; // class DynArray + + + +} // namespace ffft + + + +#include "DynArray.hpp" + + + +#endif // ffft_DynArray_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/DynArray.hpp b/plugins/Cardinal/src/sassy/fftreal/DynArray.hpp new file mode 100644 index 00000000..38f1471c --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/DynArray.hpp @@ -0,0 +1,144 @@ +/***************************************************************************** + + DynArray.hpp + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if defined (ffft_DynArray_CURRENT_CODEHEADER) + #error Recursive inclusion of DynArray code header. +#endif +#define ffft_DynArray_CURRENT_CODEHEADER + +#if ! defined (ffft_DynArray_CODEHEADER_INCLUDED) +#define ffft_DynArray_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include + + + +namespace ffft +{ + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +DynArray ::DynArray () +: _data_ptr (0) +, _len (0) +{ + // Nothing +} + + + +template +DynArray ::DynArray (long size) +: _data_ptr (0) +, _len (0) +{ + assert (size >= 0); + if (size > 0) + { + _data_ptr = new DataType [size]; + _len = size; + } +} + + + +template +DynArray ::~DynArray () +{ + delete [] _data_ptr; + _data_ptr = 0; + _len = 0; +} + + + +template +long DynArray ::size () const +{ + return (_len); +} + + + +template +void DynArray ::resize (long size) +{ + assert (size >= 0); + if (size > 0) + { + DataType * old_data_ptr = _data_ptr; + DataType * tmp_data_ptr = new DataType [size]; + + _data_ptr = tmp_data_ptr; + _len = size; + + delete [] old_data_ptr; + } +} + + + +template +const typename DynArray ::DataType & DynArray ::operator [] (long pos) const +{ + assert (pos >= 0); + assert (pos < _len); + + return (_data_ptr [pos]); +} + + + +template +typename DynArray ::DataType & DynArray ::operator [] (long pos) +{ + assert (pos >= 0); + assert (pos < _len); + + return (_data_ptr [pos]); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +} // namespace ffft + + + +#endif // ffft_DynArray_CODEHEADER_INCLUDED + +#undef ffft_DynArray_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTReal.h b/plugins/Cardinal/src/sassy/fftreal/FFTReal.h new file mode 100644 index 00000000..f9a2553d --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTReal.h @@ -0,0 +1,143 @@ +/***************************************************************************** + + FFTReal.h + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if ! defined (ffft_FFTReal_HEADER_INCLUDED) +#define ffft_FFTReal_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" +#include "DynArray.h" +#include "OscSinCos.h" + + + +namespace ffft +{ + + + +template +class FFTReal +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + enum { MAX_BIT_DEPTH = 30 }; // So length can be represented as long int + + typedef DT DataType; + + explicit FFTReal (long length); + virtual ~FFTReal () {} + + long get_length () const; + void do_fft (DataType f [], const DataType x []) const; + void do_ifft (const DataType f [], DataType x []) const; + void rescale (DataType x []) const; + DataType * use_buffer () const; + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + // Over this bit depth, we use direct calculation for sin/cos + enum { TRIGO_BD_LIMIT = 12 }; + + typedef OscSinCos OscType; + + void init_br_lut (); + void init_trigo_lut (); + void init_trigo_osc (); + + ffft_FORCEINLINE const long * + get_br_ptr () const; + ffft_FORCEINLINE const DataType * + get_trigo_ptr (int level) const; + ffft_FORCEINLINE long + get_trigo_level_index (int level) const; + + inline void compute_fft_general (DataType f [], const DataType x []) const; + inline void compute_direct_pass_1_2 (DataType df [], const DataType x []) const; + inline void compute_direct_pass_3 (DataType df [], const DataType sf []) const; + inline void compute_direct_pass_n (DataType df [], const DataType sf [], int pass) const; + inline void compute_direct_pass_n_lut (DataType df [], const DataType sf [], int pass) const; + inline void compute_direct_pass_n_osc (DataType df [], const DataType sf [], int pass) const; + + inline void compute_ifft_general (const DataType f [], DataType x []) const; + inline void compute_inverse_pass_n (DataType df [], const DataType sf [], int pass) const; + inline void compute_inverse_pass_n_osc (DataType df [], const DataType sf [], int pass) const; + inline void compute_inverse_pass_n_lut (DataType df [], const DataType sf [], int pass) const; + inline void compute_inverse_pass_3 (DataType df [], const DataType sf []) const; + inline void compute_inverse_pass_1_2 (DataType x [], const DataType sf []) const; + + const long _length; + const int _nbr_bits; + DynArray + _br_lut; + DynArray + _trigo_lut; + mutable DynArray + _buffer; + mutable DynArray + _trigo_osc; + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTReal (); + FFTReal (const FFTReal &other); + FFTReal & operator = (const FFTReal &other); + bool operator == (const FFTReal &other); + bool operator != (const FFTReal &other); + +}; // class FFTReal + + + +} // namespace ffft + + + +#include "FFTReal.hpp" + + + +#endif // ffft_FFTReal_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTReal.hpp b/plugins/Cardinal/src/sassy/fftreal/FFTReal.hpp new file mode 100644 index 00000000..590a3ff0 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTReal.hpp @@ -0,0 +1,917 @@ +/***************************************************************************** + + FFTReal.hpp + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if defined (ffft_FFTReal_CURRENT_CODEHEADER) + #error Recursive inclusion of FFTReal code header. +#endif +#define ffft_FFTReal_CURRENT_CODEHEADER + +#if ! defined (ffft_FFTReal_CODEHEADER_INCLUDED) +#define ffft_FFTReal_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include +#include + + + +namespace ffft +{ + + + +static inline bool FFTReal_is_pow2 (long x) +{ + assert (x > 0); + + return ((x & -x) == x); +} + + + +static inline int FFTReal_get_next_pow2 (long x) +{ + --x; + + int p = 0; + while ((x & ~0xFFFFL) != 0) + { + p += 16; + x >>= 16; + } + while ((x & ~0xFL) != 0) + { + p += 4; + x >>= 4; + } + while (x > 0) + { + ++p; + x >>= 1; + } + + return (p); +} + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/* +============================================================================== +Name: ctor +Input parameters: + - length: length of the array on which we want to do a FFT. Range: power of + 2 only, > 0. +Throws: std::bad_alloc +============================================================================== +*/ + +template +FFTReal
::FFTReal (long length) +: _length (length) +, _nbr_bits (FFTReal_get_next_pow2 (length)) +, _br_lut () +, _trigo_lut () +, _buffer (length) +, _trigo_osc () +{ + assert (FFTReal_is_pow2 (length)); + assert (_nbr_bits <= MAX_BIT_DEPTH); + + init_br_lut (); + init_trigo_lut (); + init_trigo_osc (); +} + + + +/* +============================================================================== +Name: get_length +Description: + Returns the number of points processed by this FFT object. +Returns: The number of points, power of 2, > 0. +Throws: Nothing +============================================================================== +*/ + +template +long FFTReal
::get_length () const +{ + return (_length); +} + + + +/* +============================================================================== +Name: do_fft +Description: + Compute the FFT of the array. +Input parameters: + - x: pointer on the source array (time). +Output parameters: + - f: pointer on the destination array (frequencies). + f [0...length(x)/2] = real values, + f [length(x)/2+1...length(x)-1] = negative imaginary values of + coefficents 1...length(x)/2-1. +Throws: Nothing +============================================================================== +*/ + +template +void FFTReal
::do_fft (DataType f [], const DataType x []) const +{ + assert (f != 0); + assert (f != use_buffer ()); + assert (x != 0); + assert (x != use_buffer ()); + assert (x != f); + + // General case + if (_nbr_bits > 2) + { + compute_fft_general (f, x); + } + + // 4-point FFT + else if (_nbr_bits == 2) + { + f [1] = x [0] - x [2]; + f [3] = x [1] - x [3]; + + const DataType b_0 = x [0] + x [2]; + const DataType b_2 = x [1] + x [3]; + + f [0] = b_0 + b_2; + f [2] = b_0 - b_2; + } + + // 2-point FFT + else if (_nbr_bits == 1) + { + f [0] = x [0] + x [1]; + f [1] = x [0] - x [1]; + } + + // 1-point FFT + else + { + f [0] = x [0]; + } +} + + + +/* +============================================================================== +Name: do_ifft +Description: + Compute the inverse FFT of the array. Note that data must be post-scaled: + IFFT (FFT (x)) = x * length (x). +Input parameters: + - f: pointer on the source array (frequencies). + f [0...length(x)/2] = real values + f [length(x)/2+1...length(x)-1] = negative imaginary values of + coefficents 1...length(x)/2-1. +Output parameters: + - x: pointer on the destination array (time). +Throws: Nothing +============================================================================== +*/ + +template +void FFTReal
::do_ifft (const DataType f [], DataType x []) const +{ + assert (f != 0); + assert (f != use_buffer ()); + assert (x != 0); + assert (x != use_buffer ()); + assert (x != f); + + // General case + if (_nbr_bits > 2) + { + compute_ifft_general (f, x); + } + + // 4-point IFFT + else if (_nbr_bits == 2) + { + const DataType b_0 = f [0] + f [2]; + const DataType b_2 = f [0] - f [2]; + + x [0] = b_0 + f [1] * 2; + x [2] = b_0 - f [1] * 2; + x [1] = b_2 + f [3] * 2; + x [3] = b_2 - f [3] * 2; + } + + // 2-point IFFT + else if (_nbr_bits == 1) + { + x [0] = f [0] + f [1]; + x [1] = f [0] - f [1]; + } + + // 1-point IFFT + else + { + x [0] = f [0]; + } +} + + + +/* +============================================================================== +Name: rescale +Description: + Scale an array by divide each element by its length. This function should + be called after FFT + IFFT. +Input parameters: + - x: pointer on array to rescale (time or frequency). +Throws: Nothing +============================================================================== +*/ + +template +void FFTReal
::rescale (DataType x []) const +{ + const DataType mul = DataType (1.0 / _length); + + if (_length < 4) + { + long i = _length - 1; + do + { + x [i] *= mul; + --i; + } + while (i >= 0); + } + + else + { + assert ((_length & 3) == 0); + + // Could be optimized with SIMD instruction sets (needs alignment check) + long i = _length - 4; + do + { + x [i + 0] *= mul; + x [i + 1] *= mul; + x [i + 2] *= mul; + x [i + 3] *= mul; + i -= 4; + } + while (i >= 0); + } +} + + + +/* +============================================================================== +Name: use_buffer +Description: + Access the internal buffer, whose length is the FFT one. + Buffer content will be erased at each do_fft() / do_ifft() call! + This buffer cannot be used as: + - source for FFT or IFFT done with this object + - destination for FFT or IFFT done with this object +Returns: + Buffer start address +Throws: Nothing +============================================================================== +*/ + +template +typename FFTReal
::DataType * FFTReal
::use_buffer () const +{ + return (&_buffer [0]); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +void FFTReal
::init_br_lut () +{ + const long length = 1L << _nbr_bits; + _br_lut.resize (length); + + _br_lut [0] = 0; + long br_index = 0; + for (long cnt = 1; cnt < length; ++cnt) + { + // ++br_index (bit reversed) + long bit = length >> 1; + while (((br_index ^= bit) & bit) == 0) + { + bit >>= 1; + } + + _br_lut [cnt] = br_index; + } +} + + + +template +void FFTReal
::init_trigo_lut () +{ + using namespace std; + + if (_nbr_bits > 3) + { + const long total_len = (1L << (_nbr_bits - 1)) - 4; + _trigo_lut.resize (total_len); + + for (int level = 3; level < _nbr_bits; ++level) + { + const long level_len = 1L << (level - 1); + DataType * const level_ptr = + &_trigo_lut [get_trigo_level_index (level)]; + const double mul = PI / (level_len << 1); + + for (long i = 0; i < level_len; ++ i) + { + level_ptr [i] = static_cast (cos (i * mul)); + } + } + } +} + + + +template +void FFTReal
::init_trigo_osc () +{ + const int nbr_osc = _nbr_bits - TRIGO_BD_LIMIT; + if (nbr_osc > 0) + { + _trigo_osc.resize (nbr_osc); + + for (int osc_cnt = 0; osc_cnt < nbr_osc; ++osc_cnt) + { + OscType & osc = _trigo_osc [osc_cnt]; + + const long len = 1L << (TRIGO_BD_LIMIT + osc_cnt); + const double mul = (0.5 * PI) / len; + osc.set_step (mul); + } + } +} + + + +template +const long * FFTReal
::get_br_ptr () const +{ + return (&_br_lut [0]); +} + + + +template +const typename FFTReal
::DataType * FFTReal
::get_trigo_ptr (int level) const +{ + assert (level >= 3); + + return (&_trigo_lut [get_trigo_level_index (level)]); +} + + + +template +long FFTReal
::get_trigo_level_index (int level) const +{ + assert (level >= 3); + + return ((1L << (level - 1)) - 4); +} + + + +// Transform in several passes +template +void FFTReal
::compute_fft_general (DataType f [], const DataType x []) const +{ + assert (f != 0); + assert (f != use_buffer ()); + assert (x != 0); + assert (x != use_buffer ()); + assert (x != f); + + DataType * sf; + DataType * df; + + if ((_nbr_bits & 1) != 0) + { + df = use_buffer (); + sf = f; + } + else + { + df = f; + sf = use_buffer (); + } + + compute_direct_pass_1_2 (df, x); + compute_direct_pass_3 (sf, df); + + for (int pass = 3; pass < _nbr_bits; ++ pass) + { + compute_direct_pass_n (df, sf, pass); + + DataType * const temp_ptr = df; + df = sf; + sf = temp_ptr; + } +} + + + +template +void FFTReal
::compute_direct_pass_1_2 (DataType df [], const DataType x []) const +{ + assert (df != 0); + assert (x != 0); + assert (df != x); + + const long * const bit_rev_lut_ptr = get_br_ptr (); + long coef_index = 0; + do + { + const long rev_index_0 = bit_rev_lut_ptr [coef_index]; + const long rev_index_1 = bit_rev_lut_ptr [coef_index + 1]; + const long rev_index_2 = bit_rev_lut_ptr [coef_index + 2]; + const long rev_index_3 = bit_rev_lut_ptr [coef_index + 3]; + + DataType * const df2 = df + coef_index; + df2 [1] = x [rev_index_0] - x [rev_index_1]; + df2 [3] = x [rev_index_2] - x [rev_index_3]; + + const DataType sf_0 = x [rev_index_0] + x [rev_index_1]; + const DataType sf_2 = x [rev_index_2] + x [rev_index_3]; + + df2 [0] = sf_0 + sf_2; + df2 [2] = sf_0 - sf_2; + + coef_index += 4; + } + while (coef_index < _length); +} + + + +template +void FFTReal
::compute_direct_pass_3 (DataType df [], const DataType sf []) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + + const DataType sqrt2_2 = DataType (SQRT2 * 0.5); + long coef_index = 0; + do + { + DataType v; + + df [coef_index] = sf [coef_index] + sf [coef_index + 4]; + df [coef_index + 4] = sf [coef_index] - sf [coef_index + 4]; + df [coef_index + 2] = sf [coef_index + 2]; + df [coef_index + 6] = sf [coef_index + 6]; + + v = (sf [coef_index + 5] - sf [coef_index + 7]) * sqrt2_2; + df [coef_index + 1] = sf [coef_index + 1] + v; + df [coef_index + 3] = sf [coef_index + 1] - v; + + v = (sf [coef_index + 5] + sf [coef_index + 7]) * sqrt2_2; + df [coef_index + 5] = v + sf [coef_index + 3]; + df [coef_index + 7] = v - sf [coef_index + 3]; + + coef_index += 8; + } + while (coef_index < _length); +} + + + +template +void FFTReal
::compute_direct_pass_n (DataType df [], const DataType sf [], int pass) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + assert (pass >= 3); + assert (pass < _nbr_bits); + + if (pass <= TRIGO_BD_LIMIT) + { + compute_direct_pass_n_lut (df, sf, pass); + } + else + { + compute_direct_pass_n_osc (df, sf, pass); + } +} + + + +template +void FFTReal
::compute_direct_pass_n_lut (DataType df [], const DataType sf [], int pass) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + assert (pass >= 3); + assert (pass < _nbr_bits); + + const long nbr_coef = 1 << pass; + const long h_nbr_coef = nbr_coef >> 1; + const long d_nbr_coef = nbr_coef << 1; + long coef_index = 0; + const DataType * const cos_ptr = get_trigo_ptr (pass); + do + { + const DataType * const sf1r = sf + coef_index; + const DataType * const sf2r = sf1r + nbr_coef; + DataType * const dfr = df + coef_index; + DataType * const dfi = dfr + nbr_coef; + + // Extreme coefficients are always real + dfr [0] = sf1r [0] + sf2r [0]; + dfi [0] = sf1r [0] - sf2r [0]; // dfr [nbr_coef] = + dfr [h_nbr_coef] = sf1r [h_nbr_coef]; + dfi [h_nbr_coef] = sf2r [h_nbr_coef]; + + // Others are conjugate complex numbers + const DataType * const sf1i = sf1r + h_nbr_coef; + const DataType * const sf2i = sf1i + nbr_coef; + for (long i = 1; i < h_nbr_coef; ++ i) + { + const DataType c = cos_ptr [i]; // cos (i*PI/nbr_coef); + const DataType s = cos_ptr [h_nbr_coef - i]; // sin (i*PI/nbr_coef); + DataType v; + + v = sf2r [i] * c - sf2i [i] * s; + dfr [i] = sf1r [i] + v; + dfi [-i] = sf1r [i] - v; // dfr [nbr_coef - i] = + + v = sf2r [i] * s + sf2i [i] * c; + dfi [i] = v + sf1i [i]; + dfi [nbr_coef - i] = v - sf1i [i]; + } + + coef_index += d_nbr_coef; + } + while (coef_index < _length); +} + + + +template +void FFTReal
::compute_direct_pass_n_osc (DataType df [], const DataType sf [], int pass) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + assert (pass > TRIGO_BD_LIMIT); + assert (pass < _nbr_bits); + + const long nbr_coef = 1 << pass; + const long h_nbr_coef = nbr_coef >> 1; + const long d_nbr_coef = nbr_coef << 1; + long coef_index = 0; + OscType & osc = _trigo_osc [pass - (TRIGO_BD_LIMIT + 1)]; + do + { + const DataType * const sf1r = sf + coef_index; + const DataType * const sf2r = sf1r + nbr_coef; + DataType * const dfr = df + coef_index; + DataType * const dfi = dfr + nbr_coef; + + osc.clear_buffers (); + + // Extreme coefficients are always real + dfr [0] = sf1r [0] + sf2r [0]; + dfi [0] = sf1r [0] - sf2r [0]; // dfr [nbr_coef] = + dfr [h_nbr_coef] = sf1r [h_nbr_coef]; + dfi [h_nbr_coef] = sf2r [h_nbr_coef]; + + // Others are conjugate complex numbers + const DataType * const sf1i = sf1r + h_nbr_coef; + const DataType * const sf2i = sf1i + nbr_coef; + for (long i = 1; i < h_nbr_coef; ++ i) + { + osc.step (); + const DataType c = osc.get_cos (); + const DataType s = osc.get_sin (); + DataType v; + + v = sf2r [i] * c - sf2i [i] * s; + dfr [i] = sf1r [i] + v; + dfi [-i] = sf1r [i] - v; // dfr [nbr_coef - i] = + + v = sf2r [i] * s + sf2i [i] * c; + dfi [i] = v + sf1i [i]; + dfi [nbr_coef - i] = v - sf1i [i]; + } + + coef_index += d_nbr_coef; + } + while (coef_index < _length); +} + + + +// Transform in several pass +template +void FFTReal
::compute_ifft_general (const DataType f [], DataType x []) const +{ + assert (f != 0); + assert (f != use_buffer ()); + assert (x != 0); + assert (x != use_buffer ()); + assert (x != f); + + DataType * sf = const_cast (f); + DataType * df; + DataType * df_temp; + + if (_nbr_bits & 1) + { + df = use_buffer (); + df_temp = x; + } + else + { + df = x; + df_temp = use_buffer (); + } + + for (int pass = _nbr_bits - 1; pass >= 3; -- pass) + { + compute_inverse_pass_n (df, sf, pass); + + if (pass < _nbr_bits - 1) + { + DataType * const temp_ptr = df; + df = sf; + sf = temp_ptr; + } + else + { + sf = df; + df = df_temp; + } + } + + compute_inverse_pass_3 (df, sf); + compute_inverse_pass_1_2 (x, df); +} + + + +template +void FFTReal
::compute_inverse_pass_n (DataType df [], const DataType sf [], int pass) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + assert (pass >= 3); + assert (pass < _nbr_bits); + + if (pass <= TRIGO_BD_LIMIT) + { + compute_inverse_pass_n_lut (df, sf, pass); + } + else + { + compute_inverse_pass_n_osc (df, sf, pass); + } +} + + + +template +void FFTReal
::compute_inverse_pass_n_lut (DataType df [], const DataType sf [], int pass) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + assert (pass >= 3); + assert (pass < _nbr_bits); + + const long nbr_coef = 1 << pass; + const long h_nbr_coef = nbr_coef >> 1; + const long d_nbr_coef = nbr_coef << 1; + long coef_index = 0; + const DataType * const cos_ptr = get_trigo_ptr (pass); + do + { + const DataType * const sfr = sf + coef_index; + const DataType * const sfi = sfr + nbr_coef; + DataType * const df1r = df + coef_index; + DataType * const df2r = df1r + nbr_coef; + + // Extreme coefficients are always real + df1r [0] = sfr [0] + sfi [0]; // + sfr [nbr_coef] + df2r [0] = sfr [0] - sfi [0]; // - sfr [nbr_coef] + df1r [h_nbr_coef] = sfr [h_nbr_coef] * 2; + df2r [h_nbr_coef] = sfi [h_nbr_coef] * 2; + + // Others are conjugate complex numbers + DataType * const df1i = df1r + h_nbr_coef; + DataType * const df2i = df1i + nbr_coef; + for (long i = 1; i < h_nbr_coef; ++ i) + { + df1r [i] = sfr [i] + sfi [-i]; // + sfr [nbr_coef - i] + df1i [i] = sfi [i] - sfi [nbr_coef - i]; + + const DataType c = cos_ptr [i]; // cos (i*PI/nbr_coef); + const DataType s = cos_ptr [h_nbr_coef - i]; // sin (i*PI/nbr_coef); + const DataType vr = sfr [i] - sfi [-i]; // - sfr [nbr_coef - i] + const DataType vi = sfi [i] + sfi [nbr_coef - i]; + + df2r [i] = vr * c + vi * s; + df2i [i] = vi * c - vr * s; + } + + coef_index += d_nbr_coef; + } + while (coef_index < _length); +} + + + +template +void FFTReal
::compute_inverse_pass_n_osc (DataType df [], const DataType sf [], int pass) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + assert (pass > TRIGO_BD_LIMIT); + assert (pass < _nbr_bits); + + const long nbr_coef = 1 << pass; + const long h_nbr_coef = nbr_coef >> 1; + const long d_nbr_coef = nbr_coef << 1; + long coef_index = 0; + OscType & osc = _trigo_osc [pass - (TRIGO_BD_LIMIT + 1)]; + do + { + const DataType * const sfr = sf + coef_index; + const DataType * const sfi = sfr + nbr_coef; + DataType * const df1r = df + coef_index; + DataType * const df2r = df1r + nbr_coef; + + osc.clear_buffers (); + + // Extreme coefficients are always real + df1r [0] = sfr [0] + sfi [0]; // + sfr [nbr_coef] + df2r [0] = sfr [0] - sfi [0]; // - sfr [nbr_coef] + df1r [h_nbr_coef] = sfr [h_nbr_coef] * 2; + df2r [h_nbr_coef] = sfi [h_nbr_coef] * 2; + + // Others are conjugate complex numbers + DataType * const df1i = df1r + h_nbr_coef; + DataType * const df2i = df1i + nbr_coef; + for (long i = 1; i < h_nbr_coef; ++ i) + { + df1r [i] = sfr [i] + sfi [-i]; // + sfr [nbr_coef - i] + df1i [i] = sfi [i] - sfi [nbr_coef - i]; + + osc.step (); + const DataType c = osc.get_cos (); + const DataType s = osc.get_sin (); + const DataType vr = sfr [i] - sfi [-i]; // - sfr [nbr_coef - i] + const DataType vi = sfi [i] + sfi [nbr_coef - i]; + + df2r [i] = vr * c + vi * s; + df2i [i] = vi * c - vr * s; + } + + coef_index += d_nbr_coef; + } + while (coef_index < _length); +} + + + +template +void FFTReal
::compute_inverse_pass_3 (DataType df [], const DataType sf []) const +{ + assert (df != 0); + assert (sf != 0); + assert (df != sf); + + const DataType sqrt2_2 = DataType (SQRT2 * 0.5); + long coef_index = 0; + do + { + df [coef_index] = sf [coef_index] + sf [coef_index + 4]; + df [coef_index + 4] = sf [coef_index] - sf [coef_index + 4]; + df [coef_index + 2] = sf [coef_index + 2] * 2; + df [coef_index + 6] = sf [coef_index + 6] * 2; + + df [coef_index + 1] = sf [coef_index + 1] + sf [coef_index + 3]; + df [coef_index + 3] = sf [coef_index + 5] - sf [coef_index + 7]; + + const DataType vr = sf [coef_index + 1] - sf [coef_index + 3]; + const DataType vi = sf [coef_index + 5] + sf [coef_index + 7]; + + df [coef_index + 5] = (vr + vi) * sqrt2_2; + df [coef_index + 7] = (vi - vr) * sqrt2_2; + + coef_index += 8; + } + while (coef_index < _length); +} + + + +template +void FFTReal
::compute_inverse_pass_1_2 (DataType x [], const DataType sf []) const +{ + assert (x != 0); + assert (sf != 0); + assert (x != sf); + + const long * bit_rev_lut_ptr = get_br_ptr (); + const DataType * sf2 = sf; + long coef_index = 0; + do + { + { + const DataType b_0 = sf2 [0] + sf2 [2]; + const DataType b_2 = sf2 [0] - sf2 [2]; + const DataType b_1 = sf2 [1] * 2; + const DataType b_3 = sf2 [3] * 2; + + x [bit_rev_lut_ptr [0]] = b_0 + b_1; + x [bit_rev_lut_ptr [1]] = b_0 - b_1; + x [bit_rev_lut_ptr [2]] = b_2 + b_3; + x [bit_rev_lut_ptr [3]] = b_2 - b_3; + } + { + const DataType b_0 = sf2 [4] + sf2 [6]; + const DataType b_2 = sf2 [4] - sf2 [6]; + const DataType b_1 = sf2 [5] * 2; + const DataType b_3 = sf2 [7] * 2; + + x [bit_rev_lut_ptr [4]] = b_0 + b_1; + x [bit_rev_lut_ptr [5]] = b_0 - b_1; + x [bit_rev_lut_ptr [6]] = b_2 + b_3; + x [bit_rev_lut_ptr [7]] = b_2 - b_3; + } + + sf2 += 8; + coef_index += 8; + bit_rev_lut_ptr += 8; + } + while (coef_index < _length); +} + + + +} // namespace ffft + + + +#endif // ffft_FFTReal_CODEHEADER_INCLUDED + +#undef ffft_FFTReal_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTRealFixLen.h b/plugins/Cardinal/src/sassy/fftreal/FFTRealFixLen.h new file mode 100644 index 00000000..3c087a8a --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTRealFixLen.h @@ -0,0 +1,131 @@ +/***************************************************************************** + + FFTRealFixLen.h + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if ! defined (ffft_FFTRealFixLen_HEADER_INCLUDED) +#define ffft_FFTRealFixLen_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "Array.h" +#include "DynArray.h" +#include "FFTRealFixLenParam.h" +#include "OscSinCos.h" + + + +namespace ffft +{ + + + +template +class FFTRealFixLen +{ + typedef int CompileTimeCheck1 [(LL2 >= 0) ? 1 : -1]; + typedef int CompileTimeCheck2 [(LL2 <= 30) ? 1 : -1]; + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef FFTRealFixLenParam::DataType DataType; + typedef OscSinCos OscType; + + enum { FFT_LEN_L2 = LL2 }; + enum { FFT_LEN = 1 << FFT_LEN_L2 }; + + FFTRealFixLen (); + + inline long get_length () const; + void do_fft (DataType f [], const DataType x []); + void do_ifft (const DataType f [], DataType x []); + void rescale (DataType x []) const; + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + enum { TRIGO_BD_LIMIT = FFTRealFixLenParam::TRIGO_BD_LIMIT }; + + enum { BR_ARR_SIZE_L2 = ((FFT_LEN_L2 - 3) < 0) ? 0 : (FFT_LEN_L2 - 2) }; + enum { BR_ARR_SIZE = 1 << BR_ARR_SIZE_L2 }; + + enum { TRIGO_BD = ((FFT_LEN_L2 - TRIGO_BD_LIMIT) < 0) + ? (int)FFT_LEN_L2 + : (int)TRIGO_BD_LIMIT }; + enum { TRIGO_TABLE_ARR_SIZE_L2 = (LL2 < 4) ? 0 : (TRIGO_BD - 2) }; + enum { TRIGO_TABLE_ARR_SIZE = 1 << TRIGO_TABLE_ARR_SIZE_L2 }; + + enum { NBR_TRIGO_OSC = FFT_LEN_L2 - TRIGO_BD }; + enum { TRIGO_OSC_ARR_SIZE = (NBR_TRIGO_OSC > 0) ? NBR_TRIGO_OSC : 1 }; + + void build_br_lut (); + void build_trigo_lut (); + void build_trigo_osc (); + + DynArray + _buffer; + DynArray + _br_data; + DynArray + _trigo_data; + Array + _trigo_osc; + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTRealFixLen (const FFTRealFixLen &other); + FFTRealFixLen& operator = (const FFTRealFixLen &other); + bool operator == (const FFTRealFixLen &other); + bool operator != (const FFTRealFixLen &other); + +}; // class FFTRealFixLen + + + +} // namespace ffft + + + +#include "FFTRealFixLen.hpp" + + + +#endif // ffft_FFTRealFixLen_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTRealFixLen.hpp b/plugins/Cardinal/src/sassy/fftreal/FFTRealFixLen.hpp new file mode 100644 index 00000000..d8ac5c56 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTRealFixLen.hpp @@ -0,0 +1,323 @@ +/***************************************************************************** + + FFTRealFixLen.hpp + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if defined (ffft_FFTRealFixLen_CURRENT_CODEHEADER) + #error Recursive inclusion of FFTRealFixLen code header. +#endif +#define ffft_FFTRealFixLen_CURRENT_CODEHEADER + +#if ! defined (ffft_FFTRealFixLen_CODEHEADER_INCLUDED) +#define ffft_FFTRealFixLen_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" +#include "FFTRealPassDirect.h" +#include "FFTRealPassInverse.h" +#include "FFTRealSelect.h" + +#include +#include + +namespace std { } + + + +namespace ffft +{ + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +FFTRealFixLen ::FFTRealFixLen () +: _buffer (FFT_LEN) +, _br_data (BR_ARR_SIZE) +, _trigo_data (TRIGO_TABLE_ARR_SIZE) +, _trigo_osc () +{ + build_br_lut (); + build_trigo_lut (); + build_trigo_osc (); +} + + + +template +long FFTRealFixLen ::get_length () const +{ + return (FFT_LEN); +} + + + +// General case +template +void FFTRealFixLen ::do_fft (DataType f [], const DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + assert (FFT_LEN_L2 >= 3); + + // Do the transform in several passes + const DataType * cos_ptr = &_trigo_data [0]; + const long * br_ptr = &_br_data [0]; + + FFTRealPassDirect ::process ( + FFT_LEN, + f, + &_buffer [0], + x, + cos_ptr, + TRIGO_TABLE_ARR_SIZE, + br_ptr, + &_trigo_osc [0] + ); +} + +// 4-point FFT +template <> +inline void FFTRealFixLen <2>::do_fft (DataType f [], const DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + + f [1] = x [0] - x [2]; + f [3] = x [1] - x [3]; + + const DataType b_0 = x [0] + x [2]; + const DataType b_2 = x [1] + x [3]; + + f [0] = b_0 + b_2; + f [2] = b_0 - b_2; +} + +// 2-point FFT +template <> +inline void FFTRealFixLen <1>::do_fft (DataType f [], const DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + + f [0] = x [0] + x [1]; + f [1] = x [0] - x [1]; +} + +// 1-point FFT +template <> +inline void FFTRealFixLen <0>::do_fft (DataType f [], const DataType x []) +{ + assert (f != 0); + assert (x != 0); + + f [0] = x [0]; +} + + + +// General case +template +void FFTRealFixLen ::do_ifft (const DataType f [], DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + assert (FFT_LEN_L2 >= 3); + + // Do the transform in several passes + DataType * s_ptr = + FFTRealSelect ::sel_bin (&_buffer [0], x); + DataType * d_ptr = + FFTRealSelect ::sel_bin (x, &_buffer [0]); + const DataType * cos_ptr = &_trigo_data [0]; + const long * br_ptr = &_br_data [0]; + + FFTRealPassInverse ::process ( + FFT_LEN, + d_ptr, + s_ptr, + f, + cos_ptr, + TRIGO_TABLE_ARR_SIZE, + br_ptr, + &_trigo_osc [0] + ); +} + +// 4-point IFFT +template <> +inline void FFTRealFixLen <2>::do_ifft (const DataType f [], DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + + const DataType b_0 = f [0] + f [2]; + const DataType b_2 = f [0] - f [2]; + + x [0] = b_0 + f [1] * 2; + x [2] = b_0 - f [1] * 2; + x [1] = b_2 + f [3] * 2; + x [3] = b_2 - f [3] * 2; +} + +// 2-point IFFT +template <> +inline void FFTRealFixLen <1>::do_ifft (const DataType f [], DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + + x [0] = f [0] + f [1]; + x [1] = f [0] - f [1]; +} + +// 1-point IFFT +template <> +inline void FFTRealFixLen <0>::do_ifft (const DataType f [], DataType x []) +{ + assert (f != 0); + assert (x != 0); + assert (x != f); + + x [0] = f [0]; +} + + + + +template +void FFTRealFixLen ::rescale (DataType x []) const +{ + assert (x != 0); + + const DataType mul = DataType (1.0 / FFT_LEN); + + if (FFT_LEN < 4) + { + long i = FFT_LEN - 1; + do + { + x [i] *= mul; + --i; + } + while (i >= 0); + } + + else + { + assert ((FFT_LEN & 3) == 0); + + // Could be optimized with SIMD instruction sets (needs alignment check) + long i = FFT_LEN - 4; + do + { + x [i + 0] *= mul; + x [i + 1] *= mul; + x [i + 2] *= mul; + x [i + 3] *= mul; + i -= 4; + } + while (i >= 0); + } +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +void FFTRealFixLen ::build_br_lut () +{ + _br_data [0] = 0; + for (long cnt = 1; cnt < BR_ARR_SIZE; ++cnt) + { + long index = cnt << 2; + long br_index = 0; + + int bit_cnt = FFT_LEN_L2; + do + { + br_index <<= 1; + br_index += (index & 1); + index >>= 1; + + -- bit_cnt; + } + while (bit_cnt > 0); + + _br_data [cnt] = br_index; + } +} + + + +template +void FFTRealFixLen ::build_trigo_lut () +{ + const double mul = (0.5 * PI) / TRIGO_TABLE_ARR_SIZE; + for (long i = 0; i < TRIGO_TABLE_ARR_SIZE; ++ i) + { + using namespace std; + + _trigo_data [i] = DataType (cos (i * mul)); + } +} + + + +template +void FFTRealFixLen ::build_trigo_osc () +{ + for (int i = 0; i < NBR_TRIGO_OSC; ++i) + { + OscType & osc = _trigo_osc [i]; + + const long len = static_cast (TRIGO_TABLE_ARR_SIZE) << (i + 1); + const double mul = (0.5 * PI) / len; + osc.set_step (mul); + } +} + + + +} // namespace ffft + + + +#endif // ffft_FFTRealFixLen_CODEHEADER_INCLUDED + +#undef ffft_FFTRealFixLen_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTRealFixLenParam.h b/plugins/Cardinal/src/sassy/fftreal/FFTRealFixLenParam.h new file mode 100644 index 00000000..2fde41ca --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTRealFixLenParam.h @@ -0,0 +1,90 @@ +/***************************************************************************** + + FFTRealFixLenParam.h + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if ! defined (ffft_FFTRealFixLenParam_HEADER_INCLUDED) +#define ffft_FFTRealFixLenParam_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +namespace ffft +{ + + + +class FFTRealFixLenParam +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + // Over this bit depth, we use direct calculation for sin/cos + enum { TRIGO_BD_LIMIT = 12 }; + + typedef float DataType; + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTRealFixLenParam (); + FFTRealFixLenParam (const FFTRealFixLenParam &other); + FFTRealFixLenParam & + operator = (const FFTRealFixLenParam &other); + bool operator == (const FFTRealFixLenParam &other); + bool operator != (const FFTRealFixLenParam &other); + +}; // class FFTRealFixLenParam + + + +} // namespace ffft + + + +//#include "ffft/FFTRealFixLenParam.hpp" + + + +#endif // ffft_FFTRealFixLenParam_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTRealPassDirect.h b/plugins/Cardinal/src/sassy/fftreal/FFTRealPassDirect.h new file mode 100644 index 00000000..7aa5816c --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTRealPassDirect.h @@ -0,0 +1,96 @@ +/***************************************************************************** + + FFTRealPassDirect.h + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if ! defined (ffft_FFTRealPassDirect_HEADER_INCLUDED) +#define ffft_FFTRealPassDirect_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" +#include "FFTRealFixLenParam.h" +#include "OscSinCos.h" + + + +namespace ffft +{ + + + +template +class FFTRealPassDirect +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef FFTRealFixLenParam::DataType DataType; + typedef OscSinCos OscType; + + ffft_FORCEINLINE static void + process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType x_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTRealPassDirect (); + FFTRealPassDirect (const FFTRealPassDirect &other); + FFTRealPassDirect & + operator = (const FFTRealPassDirect &other); + bool operator == (const FFTRealPassDirect &other); + bool operator != (const FFTRealPassDirect &other); + +}; // class FFTRealPassDirect + + + +} // namespace ffft + + + +#include "FFTRealPassDirect.hpp" + + + +#endif // ffft_FFTRealPassDirect_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTRealPassDirect.hpp b/plugins/Cardinal/src/sassy/fftreal/FFTRealPassDirect.hpp new file mode 100644 index 00000000..2cbc5bf4 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTRealPassDirect.hpp @@ -0,0 +1,205 @@ +/***************************************************************************** + + FFTRealPassDirect.hpp + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if defined (ffft_FFTRealPassDirect_CURRENT_CODEHEADER) + #error Recursive inclusion of FFTRealPassDirect code header. +#endif +#define ffft_FFTRealPassDirect_CURRENT_CODEHEADER + +#if ! defined (ffft_FFTRealPassDirect_CODEHEADER_INCLUDED) +#define ffft_FFTRealPassDirect_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "FFTRealUseTrigo.h" + + + +namespace ffft +{ + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template <> +inline void FFTRealPassDirect <1>::process (long len, DataType dest_ptr [], DataType [], const DataType x_ptr [], const DataType [], long , const long br_ptr [], OscType []) +{ + // First and second pass at once + const long qlen = len >> 2; + + long coef_index = 0; + do + { + // To do: unroll the loop (2x). + const long ri_0 = br_ptr [coef_index >> 2]; + const long ri_1 = ri_0 + 2 * qlen; // bit_rev_lut_ptr [coef_index + 1]; + const long ri_2 = ri_0 + 1 * qlen; // bit_rev_lut_ptr [coef_index + 2]; + const long ri_3 = ri_0 + 3 * qlen; // bit_rev_lut_ptr [coef_index + 3]; + + DataType * const df2 = dest_ptr + coef_index; + df2 [1] = x_ptr [ri_0] - x_ptr [ri_1]; + df2 [3] = x_ptr [ri_2] - x_ptr [ri_3]; + + const DataType sf_0 = x_ptr [ri_0] + x_ptr [ri_1]; + const DataType sf_2 = x_ptr [ri_2] + x_ptr [ri_3]; + + df2 [0] = sf_0 + sf_2; + df2 [2] = sf_0 - sf_2; + + coef_index += 4; + } + while (coef_index < len); +} + +template <> +inline void FFTRealPassDirect <2>::process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType x_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + // Executes "previous" passes first. Inverts source and destination buffers + FFTRealPassDirect <1>::process ( + len, + src_ptr, + dest_ptr, + x_ptr, + cos_ptr, + cos_len, + br_ptr, + osc_list + ); + + // Third pass + const DataType sqrt2_2 = DataType (SQRT2 * 0.5); + + long coef_index = 0; + do + { + dest_ptr [coef_index ] = src_ptr [coef_index] + src_ptr [coef_index + 4]; + dest_ptr [coef_index + 4] = src_ptr [coef_index] - src_ptr [coef_index + 4]; + dest_ptr [coef_index + 2] = src_ptr [coef_index + 2]; + dest_ptr [coef_index + 6] = src_ptr [coef_index + 6]; + + DataType v; + + v = (src_ptr [coef_index + 5] - src_ptr [coef_index + 7]) * sqrt2_2; + dest_ptr [coef_index + 1] = src_ptr [coef_index + 1] + v; + dest_ptr [coef_index + 3] = src_ptr [coef_index + 1] - v; + + v = (src_ptr [coef_index + 5] + src_ptr [coef_index + 7]) * sqrt2_2; + dest_ptr [coef_index + 5] = v + src_ptr [coef_index + 3]; + dest_ptr [coef_index + 7] = v - src_ptr [coef_index + 3]; + + coef_index += 8; + } + while (coef_index < len); +} + +template +void FFTRealPassDirect ::process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType x_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + // Executes "previous" passes first. Inverts source and destination buffers + FFTRealPassDirect ::process ( + len, + src_ptr, + dest_ptr, + x_ptr, + cos_ptr, + cos_len, + br_ptr, + osc_list + ); + + const long dist = 1L << (PASS - 1); + const long c1_r = 0; + const long c1_i = dist; + const long c2_r = dist * 2; + const long c2_i = dist * 3; + const long cend = dist * 4; + const long table_step = cos_len >> (PASS - 1); + + enum { TRIGO_OSC = PASS - FFTRealFixLenParam::TRIGO_BD_LIMIT }; + enum { TRIGO_DIRECT = (TRIGO_OSC >= 0) ? 1 : 0 }; + + long coef_index = 0; + do + { + const DataType * const sf = src_ptr + coef_index; + DataType * const df = dest_ptr + coef_index; + + // Extreme coefficients are always real + df [c1_r] = sf [c1_r] + sf [c2_r]; + df [c2_r] = sf [c1_r] - sf [c2_r]; + df [c1_i] = sf [c1_i]; + df [c2_i] = sf [c2_i]; + + FFTRealUseTrigo ::prepare (osc_list [TRIGO_OSC]); + + // Others are conjugate complex numbers + for (long i = 1; i < dist; ++ i) + { + DataType c; + DataType s; + FFTRealUseTrigo ::iterate ( + osc_list [TRIGO_OSC], + c, + s, + cos_ptr, + i * table_step, + (dist - i) * table_step + ); + + const DataType sf_r_i = sf [c1_r + i]; + const DataType sf_i_i = sf [c1_i + i]; + + const DataType v1 = sf [c2_r + i] * c - sf [c2_i + i] * s; + df [c1_r + i] = sf_r_i + v1; + df [c2_r - i] = sf_r_i - v1; + + const DataType v2 = sf [c2_r + i] * s + sf [c2_i + i] * c; + df [c2_r + i] = v2 + sf_i_i; + df [cend - i] = v2 - sf_i_i; + } + + coef_index += cend; + } + while (coef_index < len); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +} // namespace ffft + + + +#endif // ffft_FFTRealPassDirect_CODEHEADER_INCLUDED + +#undef ffft_FFTRealPassDirect_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTRealPassInverse.h b/plugins/Cardinal/src/sassy/fftreal/FFTRealPassInverse.h new file mode 100644 index 00000000..f822231f --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTRealPassInverse.h @@ -0,0 +1,101 @@ +/***************************************************************************** + + FFTRealPassInverse.h + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if ! defined (ffft_FFTRealPassInverse_HEADER_INCLUDED) +#define ffft_FFTRealPassInverse_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" +#include "FFTRealFixLenParam.h" +#include "OscSinCos.h" + + + + +namespace ffft +{ + + + +template +class FFTRealPassInverse +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef FFTRealFixLenParam::DataType DataType; + typedef OscSinCos OscType; + + ffft_FORCEINLINE static void + process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType f_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []); + ffft_FORCEINLINE static void + process_rec (long len, DataType dest_ptr [], DataType src_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []); + ffft_FORCEINLINE static void + process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTRealPassInverse (); + FFTRealPassInverse (const FFTRealPassInverse &other); + FFTRealPassInverse & + operator = (const FFTRealPassInverse &other); + bool operator == (const FFTRealPassInverse &other); + bool operator != (const FFTRealPassInverse &other); + +}; // class FFTRealPassInverse + + + +} // namespace ffft + + + +#include "FFTRealPassInverse.hpp" + + + +#endif // ffft_FFTRealPassInverse_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTRealPassInverse.hpp b/plugins/Cardinal/src/sassy/fftreal/FFTRealPassInverse.hpp new file mode 100644 index 00000000..f93ef209 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTRealPassInverse.hpp @@ -0,0 +1,230 @@ +/***************************************************************************** + + FFTRealPassInverse.hpp + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if defined (ffft_FFTRealPassInverse_CURRENT_CODEHEADER) + #error Recursive inclusion of FFTRealPassInverse code header. +#endif +#define ffft_FFTRealPassInverse_CURRENT_CODEHEADER + +#if ! defined (ffft_FFTRealPassInverse_CODEHEADER_INCLUDED) +#define ffft_FFTRealPassInverse_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "FFTRealUseTrigo.h" + + + +namespace ffft +{ + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +void FFTRealPassInverse ::process (long len, DataType dest_ptr [], DataType src_ptr [], const DataType f_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + process_internal ( + len, + dest_ptr, + f_ptr, + cos_ptr, + cos_len, + br_ptr, + osc_list + ); + FFTRealPassInverse ::process_rec ( + len, + src_ptr, + dest_ptr, + cos_ptr, + cos_len, + br_ptr, + osc_list + ); +} + + + +template +void FFTRealPassInverse ::process_rec (long len, DataType dest_ptr [], DataType src_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + process_internal ( + len, + dest_ptr, + src_ptr, + cos_ptr, + cos_len, + br_ptr, + osc_list + ); + FFTRealPassInverse ::process_rec ( + len, + src_ptr, + dest_ptr, + cos_ptr, + cos_len, + br_ptr, + osc_list + ); +} + +template <> +inline void FFTRealPassInverse <0>::process_rec (long , DataType [], DataType [], const DataType [], long , const long [], OscType []) +{ + // Stops recursion +} + + + +template +void FFTRealPassInverse ::process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], const DataType cos_ptr [], long cos_len, const long br_ptr [], OscType osc_list []) +{ + const long dist = 1L << (PASS - 1); + const long c1_r = 0; + const long c1_i = dist; + const long c2_r = dist * 2; + const long c2_i = dist * 3; + const long cend = dist * 4; + const long table_step = cos_len >> (PASS - 1); + + enum { TRIGO_OSC = PASS - FFTRealFixLenParam::TRIGO_BD_LIMIT }; + enum { TRIGO_DIRECT = (TRIGO_OSC >= 0) ? 1 : 0 }; + + long coef_index = 0; + do + { + const DataType * const sf = src_ptr + coef_index; + DataType * const df = dest_ptr + coef_index; + + // Extreme coefficients are always real + df [c1_r] = sf [c1_r] + sf [c2_r]; + df [c2_r] = sf [c1_r] - sf [c2_r]; + df [c1_i] = sf [c1_i] * 2; + df [c2_i] = sf [c2_i] * 2; + + FFTRealUseTrigo ::prepare (osc_list [TRIGO_OSC]); + + // Others are conjugate complex numbers + for (long i = 1; i < dist; ++ i) + { + df [c1_r + i] = sf [c1_r + i] + sf [c2_r - i]; + df [c1_i + i] = sf [c2_r + i] - sf [cend - i]; + + DataType c; + DataType s; + FFTRealUseTrigo ::iterate ( + osc_list [TRIGO_OSC], + c, + s, + cos_ptr, + i * table_step, + (dist - i) * table_step + ); + + const DataType vr = sf [c1_r + i] - sf [c2_r - i]; + const DataType vi = sf [c2_r + i] + sf [cend - i]; + + df [c2_r + i] = vr * c + vi * s; + df [c2_i + i] = vi * c - vr * s; + } + + coef_index += cend; + } + while (coef_index < len); +} + +template <> +inline void FFTRealPassInverse <2>::process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], const DataType [], long , const long [], OscType []) +{ + // Antepenultimate pass + const DataType sqrt2_2 = DataType (SQRT2 * 0.5); + + long coef_index = 0; + do + { + dest_ptr [coef_index ] = src_ptr [coef_index] + src_ptr [coef_index + 4]; + dest_ptr [coef_index + 4] = src_ptr [coef_index] - src_ptr [coef_index + 4]; + dest_ptr [coef_index + 2] = src_ptr [coef_index + 2] * 2; + dest_ptr [coef_index + 6] = src_ptr [coef_index + 6] * 2; + + dest_ptr [coef_index + 1] = src_ptr [coef_index + 1] + src_ptr [coef_index + 3]; + dest_ptr [coef_index + 3] = src_ptr [coef_index + 5] - src_ptr [coef_index + 7]; + + const DataType vr = src_ptr [coef_index + 1] - src_ptr [coef_index + 3]; + const DataType vi = src_ptr [coef_index + 5] + src_ptr [coef_index + 7]; + + dest_ptr [coef_index + 5] = (vr + vi) * sqrt2_2; + dest_ptr [coef_index + 7] = (vi - vr) * sqrt2_2; + + coef_index += 8; + } + while (coef_index < len); +} + +template <> +inline void FFTRealPassInverse <1>::process_internal (long len, DataType dest_ptr [], const DataType src_ptr [], const DataType [], long , const long br_ptr [], OscType []) +{ + // Penultimate and last pass at once + const long qlen = len >> 2; + + long coef_index = 0; + do + { + const long ri_0 = br_ptr [coef_index >> 2]; + + const DataType b_0 = src_ptr [coef_index ] + src_ptr [coef_index + 2]; + const DataType b_2 = src_ptr [coef_index ] - src_ptr [coef_index + 2]; + const DataType b_1 = src_ptr [coef_index + 1] * 2; + const DataType b_3 = src_ptr [coef_index + 3] * 2; + + dest_ptr [ri_0 ] = b_0 + b_1; + dest_ptr [ri_0 + 2 * qlen] = b_0 - b_1; + dest_ptr [ri_0 + 1 * qlen] = b_2 + b_3; + dest_ptr [ri_0 + 3 * qlen] = b_2 - b_3; + + coef_index += 4; + } + while (coef_index < len); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +} // namespace ffft + + + +#endif // ffft_FFTRealPassInverse_CODEHEADER_INCLUDED + +#undef ffft_FFTRealPassInverse_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTRealSelect.h b/plugins/Cardinal/src/sassy/fftreal/FFTRealSelect.h new file mode 100644 index 00000000..c8bed63f --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTRealSelect.h @@ -0,0 +1,78 @@ +/***************************************************************************** + + FFTRealSelect.h + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if ! defined (ffft_FFTRealSelect_HEADER_INCLUDED) +#define ffft_FFTRealSelect_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" + + + +namespace ffft +{ + + + +template +class FFTRealSelect +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + ffft_FORCEINLINE static float * + sel_bin (float *e_ptr, float *o_ptr); + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTRealSelect (); + ~FFTRealSelect (); + FFTRealSelect (const FFTRealSelect &other); + FFTRealSelect& operator = (const FFTRealSelect &other); + bool operator == (const FFTRealSelect &other); + bool operator != (const FFTRealSelect &other); + +}; // class FFTRealSelect + + + +} // namespace ffft + + + +#include "FFTRealSelect.hpp" + + + +#endif // ffft_FFTRealSelect_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTRealSelect.hpp b/plugins/Cardinal/src/sassy/fftreal/FFTRealSelect.hpp new file mode 100644 index 00000000..a8ed9f1e --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTRealSelect.hpp @@ -0,0 +1,63 @@ +/***************************************************************************** + + FFTRealSelect.hpp + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if defined (ffft_FFTRealSelect_CURRENT_CODEHEADER) + #error Recursive inclusion of FFTRealSelect code header. +#endif +#define ffft_FFTRealSelect_CURRENT_CODEHEADER + +#if ! defined (ffft_FFTRealSelect_CODEHEADER_INCLUDED) +#define ffft_FFTRealSelect_CODEHEADER_INCLUDED + + + +namespace ffft +{ + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +float * FFTRealSelect

::sel_bin (float *e_ptr, float *o_ptr) +{ + return (o_ptr); +} + + + +template <> +inline float * FFTRealSelect <0>::sel_bin (float *e_ptr, float *) +{ + return (e_ptr); +} + + + +} // namespace ffft + + + +#endif // ffft_FFTRealSelect_CODEHEADER_INCLUDED + +#undef ffft_FFTRealSelect_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTRealUseTrigo.h b/plugins/Cardinal/src/sassy/fftreal/FFTRealUseTrigo.h new file mode 100644 index 00000000..47067f04 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTRealUseTrigo.h @@ -0,0 +1,99 @@ +/***************************************************************************** + + FFTRealUseTrigo.h + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if ! defined (ffft_FFTRealUseTrigo_HEADER_INCLUDED) +#define ffft_FFTRealUseTrigo_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" +#include "FFTRealFixLenParam.h" +#include "OscSinCos.h" + + + +namespace ffft +{ + + + +template +class FFTRealUseTrigo +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef FFTRealFixLenParam::DataType DataType; + typedef OscSinCos OscType; + + ffft_FORCEINLINE static void + prepare (OscType &osc); + ffft_FORCEINLINE static void + iterate (OscType &osc, DataType &c, DataType &s, const DataType cos_ptr [], long index_c, long index_s); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + FFTRealUseTrigo (); + ~FFTRealUseTrigo (); + FFTRealUseTrigo (const FFTRealUseTrigo &other); + FFTRealUseTrigo & + operator = (const FFTRealUseTrigo &other); + bool operator == (const FFTRealUseTrigo &other); + bool operator != (const FFTRealUseTrigo &other); + +}; // class FFTRealUseTrigo + + + +} // namespace ffft + + + +#include "FFTRealUseTrigo.hpp" + + + +#endif // ffft_FFTRealUseTrigo_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/FFTRealUseTrigo.hpp b/plugins/Cardinal/src/sassy/fftreal/FFTRealUseTrigo.hpp new file mode 100644 index 00000000..a6d5cb12 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/FFTRealUseTrigo.hpp @@ -0,0 +1,92 @@ +/***************************************************************************** + + FFTRealUseTrigo.hpp + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if defined (ffft_FFTRealUseTrigo_CURRENT_CODEHEADER) + #error Recursive inclusion of FFTRealUseTrigo code header. +#endif +#define ffft_FFTRealUseTrigo_CURRENT_CODEHEADER + +#if ! defined (ffft_FFTRealUseTrigo_CODEHEADER_INCLUDED) +#define ffft_FFTRealUseTrigo_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "OscSinCos.h" + + + +namespace ffft +{ + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +void FFTRealUseTrigo ::prepare (OscType &osc) +{ + osc.clear_buffers (); +} + +template <> +inline void FFTRealUseTrigo <0>::prepare (OscType &) +{ + // Nothing +} + + + +template +void FFTRealUseTrigo ::iterate (OscType &osc, DataType &c, DataType &s, const DataType cos_ptr [], long index_c, long index_s) +{ + osc.step (); + c = osc.get_cos (); + s = osc.get_sin (); +} + +template <> +inline void FFTRealUseTrigo <0>::iterate (OscType &, DataType &c, DataType &s, const DataType cos_ptr [], long index_c, long index_s) +{ + c = cos_ptr [index_c]; + s = cos_ptr [index_s]; +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +} // namespace ffft + + + +#endif // ffft_FFTRealUseTrigo_CODEHEADER_INCLUDED + +#undef ffft_FFTRealUseTrigo_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/OscSinCos.h b/plugins/Cardinal/src/sassy/fftreal/OscSinCos.h new file mode 100644 index 00000000..c4539f93 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/OscSinCos.h @@ -0,0 +1,107 @@ +/***************************************************************************** + + OscSinCos.h + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if ! defined (ffft_OscSinCos_HEADER_INCLUDED) +#define ffft_OscSinCos_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include "def.h" + + + +namespace ffft +{ + + + +template +class OscSinCos +{ + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +public: + + typedef T DataType; + + OscSinCos (); + + ffft_FORCEINLINE void + set_step (double angle_rad); + + ffft_FORCEINLINE DataType + get_cos () const; + ffft_FORCEINLINE DataType + get_sin () const; + ffft_FORCEINLINE void + step (); + ffft_FORCEINLINE void + clear_buffers (); + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +protected: + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + DataType _pos_cos; // Current phase expressed with sin and cos. [-1 ; 1] + DataType _pos_sin; // - + DataType _step_cos; // Phase increment per step, [-1 ; 1] + DataType _step_sin; // - + + + +/*\\\ FORBIDDEN MEMBER FUNCTIONS \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +private: + + OscSinCos (const OscSinCos &other); + OscSinCos & operator = (const OscSinCos &other); + bool operator == (const OscSinCos &other); + bool operator != (const OscSinCos &other); + +}; // class OscSinCos + + + +} // namespace ffft + + + +#include "OscSinCos.hpp" + + + +#endif // ffft_OscSinCos_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/OscSinCos.hpp b/plugins/Cardinal/src/sassy/fftreal/OscSinCos.hpp new file mode 100644 index 00000000..b565ad12 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/OscSinCos.hpp @@ -0,0 +1,123 @@ +/***************************************************************************** + + OscSinCos.hpp + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if defined (ffft_OscSinCos_CURRENT_CODEHEADER) + #error Recursive inclusion of OscSinCos code header. +#endif +#define ffft_OscSinCos_CURRENT_CODEHEADER + +#if ! defined (ffft_OscSinCos_CODEHEADER_INCLUDED) +#define ffft_OscSinCos_CODEHEADER_INCLUDED + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + +#include + +namespace std { } + + + +namespace ffft +{ + + + +/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +template +OscSinCos ::OscSinCos () +: _pos_cos (1) +, _pos_sin (0) +, _step_cos (1) +, _step_sin (0) +{ + // Nothing +} + + + +template +void OscSinCos ::set_step (double angle_rad) +{ + using namespace std; + + _step_cos = static_cast (cos (angle_rad)); + _step_sin = static_cast (sin (angle_rad)); +} + + + +template +typename OscSinCos ::DataType OscSinCos ::get_cos () const +{ + return (_pos_cos); +} + + + +template +typename OscSinCos ::DataType OscSinCos ::get_sin () const +{ + return (_pos_sin); +} + + + +template +void OscSinCos ::step () +{ + const DataType old_cos = _pos_cos; + const DataType old_sin = _pos_sin; + + _pos_cos = old_cos * _step_cos - old_sin * _step_sin; + _pos_sin = old_cos * _step_sin + old_sin * _step_cos; +} + + + +template +void OscSinCos ::clear_buffers () +{ + _pos_cos = static_cast (1); + _pos_sin = static_cast (0); +} + + + +/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +} // namespace ffft + + + +#endif // ffft_OscSinCos_CODEHEADER_INCLUDED + +#undef ffft_OscSinCos_CURRENT_CODEHEADER + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/def.h b/plugins/Cardinal/src/sassy/fftreal/def.h new file mode 100644 index 00000000..f2269695 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/def.h @@ -0,0 +1,60 @@ +/***************************************************************************** + + def.h + By Laurent de Soras + +--- Legal stuff --- + +This program is free software. It comes without any warranty, to +the extent permitted by applicable law. You can redistribute it +and/or modify it under the terms of the Do What The Fuck You Want +To Public License, Version 2, as published by Sam Hocevar. See +http://sam.zoy.org/wtfpl/COPYING for more details. + +*Tab=3***********************************************************************/ + + + +#if ! defined (ffft_def_HEADER_INCLUDED) +#define ffft_def_HEADER_INCLUDED + +#if defined (_MSC_VER) + #pragma once + #pragma warning (4 : 4250) // "Inherits via dominance." +#endif + + + +/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ + + + +namespace ffft +{ + + + +const double PI = 3.1415926535897932384626433832795; +const double SQRT2 = 1.41421356237309514547462185873883; + +#if defined (_MSC_VER) + + #define ffft_FORCEINLINE __forceinline + +#else + + #define ffft_FORCEINLINE inline + +#endif + + + +} // namespace ffft + + + +#endif // ffft_def_HEADER_INCLUDED + + + +/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ diff --git a/plugins/Cardinal/src/sassy/fftreal/license.txt b/plugins/Cardinal/src/sassy/fftreal/license.txt new file mode 100644 index 00000000..5a8e3325 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/license.txt @@ -0,0 +1,14 @@ + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + Version 2, December 2004 + + Copyright (C) 2004 Sam Hocevar + + Everyone is permitted to copy and distribute verbatim or modified + copies of this license document, and changing it is allowed as long + as the name is changed. + + DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. You just DO WHAT THE FUCK YOU WANT TO. + diff --git a/plugins/Cardinal/src/sassy/fftreal/readme.txt b/plugins/Cardinal/src/sassy/fftreal/readme.txt new file mode 100644 index 00000000..abce4e61 --- /dev/null +++ b/plugins/Cardinal/src/sassy/fftreal/readme.txt @@ -0,0 +1,293 @@ +============================================================================== + + FFTReal + Version 2.11 + + Fourier transformation (FFT, IFFT) library specialised for real data + Portable ISO C++ + + Copyright (c) 1999-2010 Laurent de Soras + Object Pascal port (c) Frederic Vanmol + +============================================================================== + + + +Contents: + +1. Legal +2. Content +3. Using FFTReal +3.1 FFTReal - Length fixed at run-time +3.2 FFTRealFixLen - Length fixed at compile-time +3.3 Data organisation +4. Compilation and testing +5. History +6. Contact + + + +1. Legal +-------- + +FFTReal is distributed under the terms of the Do What The Fuck You Want To +Public License. + +Check the file license.txt to get full information about the license. + + + +2. Content +---------- + +FFTReal is a library to compute Discrete Fourier Transforms (DFT) with the +FFT algorithm (Fast Fourier Transform) on arrays of real numbers. It can +also compute the inverse transform. + +You should find in this package a lot of files ; some of them are of +particular interest: +- readme.txt : you are reading it +- ffft/FFTReal.h : FFT, length fixed at run-time +- ffft/FFTRealFixLen.h: FFT, length fixed at compile-time +- delphi/FFTReal.pas : Pascal implementation (working but not up-to-date) + + + +3. Using FFTReal +---------------- + +Important - if you were using older versions of FFTReal (up to 1.03), some +things have changed. FFTReal is now a template. Therefore use FFTReal +or FFTReal in your code depending on the application datatype. The +flt_t typedef has been removed. And if you were previously using FFTReal 2.0, +note that all the classes have moved to the ffft namespace. + +You have two ways to use FFTReal. In the first way, the FFT has its length +fixed at run-time, when the object is instanciated. It means that you have +not to know the length when you write the code. This is the usual way of +proceeding. + + +3.1 FFTReal - Length fixed at run-time +-------------------------------------- + +Just instanciate one time a FFTReal object. Specify the data type you want +as template parameter (only floating point: float, double, long double or +custom type). The constructor precompute a lot of things, so it may be a bit +long. The parameter is the number of points used for the next FFTs. It must +be a power of 2: + + #include "ffft/FFTReal.h" + ... + long len = 1024; + ... + // 1024-point FFT object constructed. + ffft::FFTReal fft_object (len); + +Then you can use this object to compute as many FFTs and IFFTs as you want. +They will be computed very quickly because a lot of work has been done in the +object construction. + + float x [1024]; + float f [1024]; + + ... + fft_object.do_fft (f, x); // x (real) --FFT---> f (complex) + ... + fft_object.do_ifft (f, x); // f (complex) --IFFT--> x (real) + fft_object.rescale (x); // Post-scaling should be done after FFT+IFFT + ... + +x [] and f [] are floating point number arrays. x [] is the real number +sequence which we want to compute the FFT. f [] is the result, in the +"frequency" domain. f has the same number of elements as x [], but f [] +elements are complex numbers. The routine uses some FFT properties to +optimize memory and to reduce calculations: the transformaton of a real +number sequence is a conjugate complex number sequence: F [k] = F [-k]*. + + +3.2 FFTRealFixLen - Length fixed at compile-time +------------------------------------------------ + +This class is significantly faster than the previous one, giving a speed +gain between 50 and 100 %. The template parameter is the base-2 logarithm of +the FFT length. The datatype is float; it can be changed by modifying the +DataType typedef in FFTRealFixLenParam.h. As FFTReal class, it supports +only floating-point types or equivalent. + +Use is similar as the one of FFTReal. To instanciate the object, just proceed +as indicated below: + + #include "ffft/FFTRealFixLen.h" + ... + // 1024-point (2^10) FFT object constructed. + ffft::FFTRealFixLen <10> fft_object; + +Warning: long FFT objects may take a very long time to compile, depending on +the compiler and its optimisation options. If compilation time is too high, +encapsulate the FFT object in a seprate class whose header doesn't need +to include FFTRealFixLen.h, so you just have to compile the wrapper once +and only link it the other times. For example (quick, dirty and incomplete): + +ffft/FFTWrapper.h: | ffft/FFTWrapper.cpp: + | +class FFTWrapper | #include "ffft/FFTRealFixLen.h" +{ | #include "ffft/FFTWrapper.h" +public: | + FFTWrapper (); | FFTWrapper::FFTWrapper () + ~FFTWrapper (); | : _impl_ptr ((void*) new FTRealFixLen <10>) + void do_fft (...); | { + void do_ifft (...); | } +private: | + void *_impl_ptr; | ... +} | + + +3.3 Data organisation +--------------------- + +Mathematically speaking, DFT formulas below show what does FFTReal: + +do_fft() : f(k) = sum (p = 0, N-1, x(p) * exp (+j*2*pi*k*p/N)) +do_ifft(): x(k) = sum (p = 0, N-1, f(p) * exp (-j*2*pi*k*p/N)) + +Where j is the square root of -1. The formulas differ only by the sign of +the exponential. When the sign is positive, the transform is called positive. +Common formulas for Fourier transform are negative for the direct tranform and +positive for the inverse one. + +However in these formulas, f is an array of complex numbers and doesn't +correspound exactly to the f[] array taken as function parameter. The +following table shows how the f[] sequence is mapped onto the usable FFT +coefficients (called bins): + + FFTReal output | Positive FFT equiv. | Negative FFT equiv. + ---------------+-----------------------+----------------------- + f [0] | Real (bin 0) | Real (bin 0) + f [...] | Real (bin ...) | Real (bin ...) + f [length/2] | Real (bin length/2) | Real (bin length/2) + f [length/2+1] | Imag (bin 1) | -Imag (bin 1) + f [...] | Imag (bin ...) | -Imag (bin ...) + f [length-1] | Imag (bin length/2-1) | -Imag (bin length/2-1) + +And FFT bins are distributed in f [] as above: + + | | Positive FFT | Negative FFT + Bin | Real part | imaginary part | imaginary part + ------------+----------------+-----------------+--------------- + 0 | f [0] | 0 | 0 + 1 | f [1] | f [length/2+1] | -f [length/2+1] + ... | f [...], | f [...] | -f [...] + length/2-1 | f [length/2-1] | f [length-1] | -f [length-1] + length/2 | f [length/2] | 0 | 0 + length/2+1 | f [length/2-1] | -f [length-1] | f [length-1] + ... | f [...] | -f [...] | f [...] + length-1 | f [1] | -f [length/2+1] | f [length/2+1] + +f [] coefficients have the same layout for FFT and IFFT functions. You may +notice that scaling must be done if you want to retrieve x after FFT and IFFT. +Actually, IFFT (FFT (x)) = x * length(x). This is a not a problem because +most of the applications don't care about absolute values. Thus, the operation +requires less calculation. If you want to use the FFT and IFFT to transform a +signal, you have to apply post- (or pre-) processing yourself. Multiplying +or dividing floating point numbers by a power of 2 doesn't generate extra +computation noise. + + + +4. Compilation and testing +-------------------------- + +Drop the following files into your project or makefile: + +ffft/Array.* +ffft/def.h +ffft/DynArray.* +ffft/FFTReal*.h* +ffft/OscSinCos.* + +Other files are for testing purpose only, do not include them if you just need +to use the library; they are not needed to use FFTReal in your own programs. + +FFTReal may be compiled in two versions: release and debug. Debug version +has checks that could slow down the code. Define NDEBUG to set the Release +mode. For example, the command line to compile the test bench on GCC would +look like: + +Debug mode: +g++ -Wall -I. -o ./fftreal_debug.exe ffft/test/*.cpp ffft/test/stopwatch/*.cpp + +Release mode: +g++ -Wall -I. -o ./fftreal_release.exe -DNDEBUG -O3 ffft/test/*.cpp ffft/test/stopwatch/*.cpp + +It may be tricky to compile the test bench because the speed tests use the +stopwatch sub-library, which is not that cross-platform. If you encounter +any problem that you cannot easily fix while compiling it, edit the file +ffft/test/conf.h and un-define the speed test macro. Remove the stopwatch +directory from your source file list, too. + +If it's not done by default, you should activate the exception handling +of your compiler to get the class memory-leak-safe. Thus, when a memory +allocation fails (in the constructor), an exception is thrown and the entire +object is safely destructed. It reduces the permanent error checking overhead +in the client code. Also, the test bench requires Run-Time Type Information +(RTTI) to be enabled in order to display the names of the tested classes - +sometimes mangled, depending on the compiler. + +Please note: the test bench may take an insane time to compile, especially in +Release mode, because a lot of recursive templates are instanciated. + + + +5. History +---------- + +v2.11 (2010.09.12) +- The LGPL was not well suited to 100% template code, therefore I changed +the license again. Everything is released under the WTFPL. +- Removed warnings in the testcode on MSVC++ 8.0 +- Fixed the multiple definition linking error with template specialisations +on GCC 4. + +v2.10 (2008.05.28) +- Classes are now in the ffft namespace +- Changed directory structure +- Fixed compilation information in the documentation + +v2.00 (2005.10.18) +- Turned FFTReal class into template (data type as parameter) +- Added FFTRealFixLen +- Trigonometric tables are size-limited in order to preserve cache memory; +over a given size, sin/cos functions are computed on the fly. +- Better test bench for accuracy and speed +- Changed license to LGPL + +v1.03 (2001.06.15) +- Thanks to Frederic Vanmol for the Pascal port (works with Delphi). +- Documentation improvement + +v1.02 (2001.03.25) +- sqrt() is now precomputed when the object FFTReal is constructed, resulting +in speed impovement for small size FFT. + +v1.01 (2000) +- Small modifications, I don't remember what. + +v1.00 (1999.08.14) +- First version released + + + +6. Contact +---------- + +Please address any comment, bug report or flame to: + +Laurent de Soras +laurent.de.soras@free.fr +http://ldesoras.free.fr + +For the Pascal port: +Frederic Vanmol +frederic@fruityloops.com + diff --git a/plugins/Cardinal/src/sassy/sassy.hpp b/plugins/Cardinal/src/sassy/sassy.hpp new file mode 100644 index 00000000..254db7fd --- /dev/null +++ b/plugins/Cardinal/src/sassy/sassy.hpp @@ -0,0 +1,131 @@ +/* + * Sassy scope exported API + * Copyright (C) 2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +/** + * This file contains a substantial amount of code from Sassy Audio Spreadsheet + * Copyright (c) 2022 Jari Komppa. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#pragma once + +#include "fftreal/FFTReal.h" + +// int gFFTAverage = 1; +// int gSamplerate; +// float mUIScale; +// // gScope + +struct ScopeData { + int mIndex = 0; + int mSampleRate = 0; + float mScroll = 0; + float mTimeScale = 0.01f; + int mTimeScaleSlider = 0; + int mSyncMode = 0; + int mSyncChannel = 0; + int mMode = 0; + int mDisplay = 0; + int mFFTZoom = 0; + int mPot = 0; + float fft1[65536 * 2]; + float fft2[65536 * 2]; + float ffta[65536 * 2]; + unsigned int colors[4] = { + 0xffc0c0c0, + 0xffa0a0ff, + 0xffffa0a0, + 0xff30d0d0 + }; + + struct Channel { + bool mEnabled = true; + float mScale = 1.0f / 5.0f; + int mScaleSlider = 0; + float mOffset = 0; + float* mData = nullptr; + + ~Channel() + { + delete[] mData; + } + + void realloc(const int sampleRate) + { + mData = new float[sampleRate * 10]; + memset(mData, 0, sizeof(float) * sampleRate * 10); + } + } mCh[4]; + + struct { + int average; + ffft::FFTReal* obj16; + ffft::FFTReal* obj32; + ffft::FFTReal* obj64; + ffft::FFTReal* obj128; + ffft::FFTReal* obj256; + ffft::FFTReal* obj512; + ffft::FFTReal* obj1024; + ffft::FFTReal* obj2048; + ffft::FFTReal* obj4096; + ffft::FFTReal* obj8192; + ffft::FFTReal* obj16384; + ffft::FFTReal* obj32768; + ffft::FFTReal* obj65536; + } fft; + + void realloc(const int sampleRate) + { + mIndex = 0; + mSampleRate = sampleRate; + + for (int i = 0; i < 4; i++) + mCh[i].realloc(sampleRate); + } + + inline void probe(float data1, float data2, float data3, float data4) + { + // since probe has several channels, need to deal with index here + if (mMode == 0) + { + mCh[0].mData[mIndex] = data1; + mCh[1].mData[mIndex] = data2; + mCh[2].mData[mIndex] = data3; + mCh[3].mData[mIndex] = data4; + mIndex = (mIndex + 1) % (mSampleRate * 10); + } + } +}; + +void do_show_scope_window(ScopeData* scope, float uiScale); diff --git a/plugins/Cardinal/src/sassy/sassy_scope.cpp b/plugins/Cardinal/src/sassy/sassy_scope.cpp new file mode 100644 index 00000000..2904be7c --- /dev/null +++ b/plugins/Cardinal/src/sassy/sassy_scope.cpp @@ -0,0 +1,879 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +/** + * This file is copied and adapted from Sassy Audio Spreadsheet (sassy_scope.cpp) + * Copyright (c) 2022 Jari Komppa. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "sassy.hpp" + +#define POW_2_3_4TH 1.6817928305074290860622509524664297900800685247135690216264521719 + +static double catmullrom(double t, double p0, double p1, double p2, double p3) +{ + return 0.5 * ( + (2 * p1) + + (-p0 + p2) * t + + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t * t + + (-p0 + 3 * p1 - 3 * p2 + p3) * t * t * t + ); +} + +static const char* gNotestr[128] = +{ + "C0-1","C#-1","D-1","D#-1","E-1","F-1","F#-1","G-1","G#-1","A-1","A#-1","B-1", + "C0","C#0","D0","D#0","E0","F0","F#0","G0","G#0","A0","A#0","B0", + "C1","C#1","D1","D#1","E1","F1","F#1","G1","G#1","A1","A#1","B1", + "C2","C#2","D2","D#2","E2","F2","F#2","G2","G#2","A2","A#2","B2", + "C3","C#3","D3","D#3","E3","F3","F#3","G3","G#3","A3","A#3","B3", + "C4","C#4","D4","D#4","E4","F4","F#4","G4","G#4","A4","A#4","B4", + "C5","C#5","D5","D#5","E5","F5","F#5","G5","G#5","A5","A#5","B5", + "C6","C#6","D6","D#6","E6","F6","F#6","G6","G#6","A6","A#6","B6", + "C7","C#7","D7","D#7","E7","F7","F#7","G7","G#7","A7","A#7","B7", + "C8","C#8","D8","D#8","E8","F8","F#8","G8","G#8","A8","A#8","B8", + "C9","C#9","D9","D#9","E9","F9","F#9","G9" +}; + +static const float timescalesteps[5] = +{ + 0.0001f, + 0.001f, + 0.01f, + 0.1f, + 1.0f, +}; + +static const char* timescaletext[5] = +{ + "0.1ms", + "1ms", + "10ms", + "100ms", + "1000ms" +}; + +static const float scalesteps[9] = +{ + 1.0f / 32.0f, + 1.0f / 16.0f, + 1.0f / 10.0f, + 1.0f / 8.0f, + 1.0f / 5.0f, + 1.0f / 4.0f, + 1.0f / 2.0f, + 1.0f, + 2.0f, +}; + +static const char* scaletexts[9] = { + "x1/32", + "x1/16", + "x1/10", + "x1/8", + "x1/5", + "x1/4", + "x1/2", + "x1", + "x2", +}; + +static constexpr const int grid_size = 340; +static constexpr const int grid_half_size = grid_size / 2; +static constexpr const int grid_quarter_size = static_cast(grid_half_size / 2); +static constexpr const int grid_1_8_size = grid_quarter_size / 2; +static constexpr const int grid_3_8_size = grid_quarter_size + grid_quarter_size / 2; + +static void scope_grid(const float uiScale) +{ + ImVec2 p = ImGui::GetItemRectMin(); + + // zero + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x, p.y + (grid_size / 2) * uiScale), ImVec2(p.x + (grid_size) * uiScale, p.y + (grid_size / 2) * uiScale), 0xff000000, 3.0f); + // 1.0 + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x, p.y + (grid_size / 2 - grid_quarter_size) * uiScale), ImVec2(p.x + (grid_size) * uiScale, p.y + (grid_size / 2 - grid_quarter_size) * uiScale), 0xff000000); + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x, p.y + (grid_size / 2 + grid_quarter_size) * uiScale), ImVec2(p.x + (grid_size) * uiScale, p.y + (grid_size / 2 + grid_quarter_size) * uiScale), 0xff000000); + // 0.5 + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x, p.y + (grid_size / 2 - grid_1_8_size) * uiScale), ImVec2(p.x + (grid_size) * uiScale, p.y + (grid_size / 2 - grid_1_8_size) * uiScale), 0x3f000000); + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x, p.y + (grid_size / 2 + grid_1_8_size) * uiScale), ImVec2(p.x + (grid_size) * uiScale, p.y + (grid_size / 2 + grid_1_8_size) * uiScale), 0x3f000000); + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x, p.y + (grid_size / 2 - grid_3_8_size) * uiScale), ImVec2(p.x + (grid_size) * uiScale, p.y + (grid_size / 2 - grid_3_8_size) * uiScale), 0x3f000000); + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x, p.y + (grid_size / 2 + grid_3_8_size) * uiScale), ImVec2(p.x + (grid_size) * uiScale, p.y + (grid_size / 2 + grid_3_8_size) * uiScale), 0x3f000000); + + // zero + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x + (grid_size / 2) * uiScale, p.y), ImVec2(p.x + (grid_size / 2) * uiScale, p.y + (grid_size) * uiScale), 0xff000000, 3.0f); + // 1.0 + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x + (grid_size / 2 - grid_quarter_size) * uiScale, p.y), ImVec2(p.x + (grid_size / 2 - grid_quarter_size) * uiScale, p.y + (grid_size) * uiScale), 0xff000000); + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x + (grid_size / 2 + grid_quarter_size) * uiScale, p.y), ImVec2(p.x + (grid_size / 2 + grid_quarter_size) * uiScale, p.y + (grid_size) * uiScale), 0xff000000); + // 0.5 + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x + (grid_size / 2 - grid_1_8_size) * uiScale, p.y), ImVec2(p.x + (grid_size / 2 - grid_1_8_size) * uiScale, p.y + (grid_size) * uiScale), 0x3f000000); + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x + (grid_size / 2 + grid_1_8_size) * uiScale, p.y), ImVec2(p.x + (grid_size / 2 + grid_1_8_size) * uiScale, p.y + (grid_size) * uiScale), 0x3f000000); + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x + (grid_size / 2 - grid_3_8_size) * uiScale, p.y), ImVec2(p.x + (grid_size / 2 - grid_3_8_size) * uiScale, p.y + (grid_size) * uiScale), 0x3f000000); + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x + (grid_size / 2 + grid_3_8_size) * uiScale, p.y), ImVec2(p.x + (grid_size / 2 + grid_3_8_size) * uiScale, p.y + (grid_size) * uiScale), 0x3f000000); +} + + +static int scope_sync(ScopeData* gScope, int index) +{ + const float gSamplerate = gScope->mSampleRate; + int samples = (int)(gSamplerate * gScope->mTimeScale); + int cycle = gSamplerate * 10; + int ofs = samples; + + if (gScope->mMode == 0) + { + // calculate sync + if (gScope->mSyncMode == 0) + { + float* graphdata = gScope->mCh[gScope->mSyncChannel].mData; + int over = ofs; + while (over < (cycle - ofs) && graphdata[(index - over + cycle) % cycle] < 0) over++; + int under = over; + while (under < (cycle - ofs) && graphdata[(index - under + cycle) % cycle] > 0) under++; + ofs = under; + } + else + if (gScope->mSyncMode == 1) + { + float* graphdata = gScope->mCh[gScope->mSyncChannel].mData; + int under = ofs; + while (under < (cycle - ofs) && graphdata[(index - under + cycle) % cycle] > 0) under++; + int over = under; + while (over < (cycle - ofs) && graphdata[(index - over + cycle) % cycle] < 0) over++; + ofs = over; + } + // default: ofs = samples + } + else + { + // pause mode, scroll bar is active + ofs = -(int)(gScope->mScroll * gSamplerate); + if (ofs < samples) + ofs = samples; + if (ofs > gSamplerate * 10 - samples) + ofs = gSamplerate * 10 - samples; + } + gScope->mScroll = -((float)ofs / gSamplerate); + + return ofs; +} + +#if 0 +static void scope_plot(ScopeData* gScope, const float uiScale, int index) +{ + ImVec2 p = ImGui::GetItemRectMin(); + const float gSamplerate = gScope->mSampleRate; + int cycle = gSamplerate * 10; + /* + Okay, max scale is 1 second, so.. + */ + int samples = (int)(gSamplerate * gScope->mTimeScale); + + scope_grid(uiScale); + + int ofs = scope_sync(gScope, index); + + if (gScope->mDisplay == 2) + { + for (int i = 0; i < 16384; i++) + { + for (int j = 0; j < 4; j++) + { + if (gScope->mCh[j].mEnabled) + { + float* graphdata = gScope->mCh[j].mData; + float y = graphdata[(index - ofs + i * samples / 16384 + cycle) % cycle]; + float x = graphdata[(index - ofs + i * samples / 16384 + cycle - 1) % cycle]; + x = x * gScope->mCh[j].mScale; + y = y * gScope->mCh[j].mScale - gScope->mCh[j].mOffset; + ImGui::GetWindowDrawList()->AddCircleFilled( + ImVec2(p.x + (grid_size / 2 + x * grid_quarter_size) * uiScale, p.y + (grid_size / 2 + y * grid_quarter_size) * uiScale), + 1, + (gScope->colors[j] & 0xffffff) | 0x3f000000); + } + } + } + } + else + { + for (int i = 0; i < 32768; i++) + { + for (int j = 0; j < 2; j++) + { + if (gScope->mCh[j*2].mEnabled) + { + float* graphdata = gScope->mCh[j * 2].mData; + float x = graphdata[(index - ofs + i * samples / 32768 + cycle) % cycle]; + graphdata = gScope->mCh[j * 2 + 1].mData; + float y = graphdata[(index - ofs + i * samples / 32768 + cycle) % cycle]; + x = x * gScope->mCh[j * 2].mScale - gScope->mCh[j * 2].mOffset; + y = y * gScope->mCh[j * 2 + 1].mScale - gScope->mCh[j * 2 + 1].mOffset; + ImGui::GetWindowDrawList()->AddCircleFilled( + ImVec2(p.x + (grid_size / 2 + x * grid_quarter_size) * uiScale, p.y + (grid_size / 2 + y * grid_quarter_size) * uiScale), + 1, + (gScope->colors[j*2] & 0xffffff) | 0x3f000000); + } + } + } + } + +} +#endif + +static void scope_time(ScopeData* gScope, const float uiScale, int index) +{ + ImVec2 p = ImGui::GetItemRectMin(); + const float gSamplerate = gScope->mSampleRate; + int cycle = gSamplerate * 10; + ImDrawList* dl = ImGui::GetWindowDrawList(); + /* + Okay, max scale is 1 second, so.. + */ + int samples = (int)(gSamplerate * gScope->mTimeScale); + + scope_grid(uiScale); + + int ofs = scope_sync(gScope, index); + + if (samples > grid_size) + { + for (int j = 0; j < 4; j++) + { + if (gScope->mCh[j].mEnabled) + { + float* graphdata = gScope->mCh[j].mData; + ImVec2 vert[grid_size]; + for (int i = 0; i < grid_size; i++) + { + float v0 = -graphdata[(index - ofs + i * samples / grid_size + cycle) % cycle]; + float v1 = -graphdata[(index - ofs + (i + 1) * samples / grid_size + cycle) % cycle]; + v0 = v0 * gScope->mCh[j].mScale - gScope->mCh[j].mOffset; + v1 = v1 * gScope->mCh[j].mScale - gScope->mCh[j].mOffset; + vert[i].x = p.x + i * uiScale; + vert[i].y = p.y + (grid_size / 2 + v0 * grid_quarter_size) * uiScale; + } + float v0 = p.y + (grid_size / 2 + (-gScope->mCh[j].mOffset) * grid_quarter_size) * uiScale; + dl->Flags = 0; + for (int i = 0; i < grid_size-1; i++) + { + ImVec2 quad[4]; + quad[0] = ImVec2(vert[i].x, v0); + quad[1] = ImVec2(vert[i].x, vert[i].y); + quad[2] = ImVec2(vert[i + 1].x, vert[i + 1].y); + quad[3] = ImVec2(vert[i + 1].x, v0); + dl->AddConvexPolyFilled(quad, 4, (gScope->colors[j] & 0xffffff) | 0x3f000000 ); + + } + + if (gScope->mTimeScale < 0.1) + { + dl->Flags = ImDrawListFlags_AntiAliasedLines; + dl->AddPolyline(vert, grid_size, gScope->colors[j], false, 2 * uiScale); + } + else + { + dl->Flags = ImDrawListFlags_AntiAliasedLines; + dl->AddPolyline(vert, grid_size, gScope->colors[j], false, 1); + + } + } + } + } + else + { + // less than 1 sample per pixel + for (int j = 0; j < 4; j++) + { + if (gScope->mCh[j].mEnabled) + { + float* graphdata = gScope->mCh[j].mData; + for (int i = 0; i < samples; i++) + { + float v0 = -graphdata[(index - ofs + i + cycle) % cycle]; + float v1 = 0; + v0 = v0 * gScope->mCh[j].mScale - gScope->mCh[j].mOffset; + v1 = v1 * gScope->mCh[j].mScale - gScope->mCh[j].mOffset; + float x0 = p.x + (i * grid_size / samples) * uiScale; + ImGui::GetWindowDrawList()->AddCircleFilled( + ImVec2(x0, p.y + (grid_size / 2 + v0 * grid_quarter_size) * uiScale), + 4 * uiScale, + gScope->colors[j]); + ImGui::GetWindowDrawList()->AddLine( + ImVec2(x0, p.y + (grid_size / 2 + v0 * grid_quarter_size) * uiScale), + ImVec2(x0, p.y + (grid_size / 2 + v1 * grid_quarter_size) * uiScale), + gScope->colors[j]); + } + } + } + } + + ImGui::GetWindowDrawList()->AddText(p, 0xffc0c0c0, timescaletext[gScope->mTimeScaleSlider + 2]); + ImGui::GetWindowDrawList()->AddText(ImVec2(p.x, p.y + (grid_size / 2 - grid_quarter_size - 7) * uiScale), 0xffc0c0c0, "+1"); + ImGui::GetWindowDrawList()->AddText(ImVec2(p.x, p.y + (grid_size / 2 + grid_quarter_size - 7) * uiScale), 0xffc0c0c0, "-1"); + + ImVec2 mp = ImGui::GetMousePos(); + mp.x -= p.x; + mp.y -= p.y; + if (mp.x > 0 && mp.x < grid_size * uiScale && + mp.y > 0 && mp.y < grid_size * uiScale) + { + ImGui::GetWindowDrawList()->AddLine( + ImVec2(p.x + mp.x, p.y), + ImVec2(p.x + mp.x, p.y + grid_size * uiScale), + 0xff00ff00, 1 * uiScale); + if (gScope->mCh[0].mEnabled || gScope->mCh[1].mEnabled || gScope->mCh[2].mEnabled || gScope->mCh[3].mEnabled) + { + ImGui::BeginTooltip(); + if (gScope->mCh[0].mEnabled) ImGui::Text("Ch 0: %3.3f", gScope->mCh[0].mData[(index - ofs + ((int)mp.x / (int)uiScale) * samples / grid_size + cycle) % cycle]); + if (gScope->mCh[1].mEnabled) ImGui::Text("Ch 1: %3.3f", gScope->mCh[1].mData[(index - ofs + ((int)mp.x / (int)uiScale) * samples / grid_size + cycle) % cycle]); + if (gScope->mCh[2].mEnabled) ImGui::Text("Ch 2: %3.3f", gScope->mCh[2].mData[(index - ofs + ((int)mp.x / (int)uiScale) * samples / grid_size + cycle) % cycle]); + if (gScope->mCh[3].mEnabled) ImGui::Text("Ch 3: %3.3f", gScope->mCh[3].mData[(index - ofs + ((int)mp.x / (int)uiScale) * samples / grid_size + cycle) % cycle]); + ImGui::EndTooltip(); + } + } +} + + +static void vertline(const float uiScale, const float x, const float w) +{ + ImVec2 p = ImGui::GetItemRectMin(); + ImGui::GetWindowDrawList()->AddLine(ImVec2(p.x + x * uiScale, p.y), ImVec2(p.x + x * uiScale, p.y + (grid_size) * uiScale), 0xff000000, w); +} + +static void scope_freq(ScopeData* gScope, const float uiScale, int index) +{ + ImVec2 p = ImGui::GetItemRectMin(); + ImDrawList* dl = ImGui::GetWindowDrawList(); + const float gSamplerate = gScope->mSampleRate; + int cycle = gSamplerate * 10; + /* + Okay, max scale is 1 second, so.. + */ + int samples = (int)(gSamplerate * gScope->mTimeScale); + + // what's the biggest PoT < samples? + // 192000 takes 18 bits to encode. + // Fill 32 bits: + int pot = samples | (samples >> 16); + pot = pot | (pot >> 8); + pot = pot | (pot >> 4); + pot = pot | (pot >> 2); + pot = pot | (pot >> 1); + // Shift down and add one to round it up + pot = (pot >> 1) + 1; + + if (pot < 16) pot = 16; + if (pot > 65536) pot = 65536; + + gScope->mPot = pot; + + ffft::FFTReal* fft = NULL; + switch (pot) + { + case 16: fft = gScope->fft.obj16; break; + case 32: fft = gScope->fft.obj32; break; + case 64: fft = gScope->fft.obj64; break; + case 128: fft = gScope->fft.obj128; break; + case 256: fft = gScope->fft.obj256; break; + case 512: fft = gScope->fft.obj512; break; + case 1024: fft = gScope->fft.obj1024; break; + case 2048: fft = gScope->fft.obj2048; break; + case 4096: fft = gScope->fft.obj4096; break; + case 8192: fft = gScope->fft.obj8192; break; + case 16384: fft = gScope->fft.obj16384; break; + case 32768: fft = gScope->fft.obj32768; break; + case 65536: fft = gScope->fft.obj65536; break; + } + if (!fft) return; + + int average = gScope->fft.average; + int ofs = scope_sync(gScope, index); + int size = grid_size - 1; + float sizef = size; + float freqbin = gSamplerate / (float)(pot / 2); + float freqbins[size]; + float zoom = 1.0f / (1 << gScope->mFFTZoom); + + for (int i = 0; i < 10; i++) + { + vertline(uiScale, sqrt(100 / freqbin * i / (pot / 4)) / zoom * sizef, 1); + vertline(uiScale, sqrt(1000 / freqbin * i / (pot / 4)) / zoom * sizef, 1); + vertline(uiScale, sqrt(10000 / freqbin * i / (pot / 4)) / zoom * sizef, 1); + } + + for (int j = 0; j < 4; j++) + { + if (gScope->mCh[j].mEnabled) + { + + + memset(gScope->ffta, 0, sizeof(float) * 65536 * 2); + for (int k = 0; k < average; k++) + { + float* graphdata = gScope->mCh[j].mData; + + for (int i = 0; i < pot; i++) + { + gScope->fft1[i * 2] = graphdata[(index - ofs + i + cycle - k) % cycle]; + gScope->fft1[i * 2 + 1] = 0; + } + + fft->do_fft(gScope->fft2, gScope->fft1); + + for (int i = 0; i < pot / 4; i++) + gScope->ffta[i] += (1.0f / average) * sqrt(gScope->fft2[i * 2 + 0] * gScope->fft2[i * 2 + 0] + gScope->fft2[i * 2 + 1] * gScope->fft2[i * 2 + 1]); + } + + ImVec2 vert[size]; + + for (int i = 0; i < size; i++) + { + float ppos = powf(zoom * i / sizef, 2.0f) * pot / 4; + freqbins[i] = ppos * freqbin; + + float f = ppos - (int)ppos; + float a = i ? gScope->ffta[(int)ppos - 1] : 0; + float b = gScope->ffta[(int)ppos]; + float c = i < size ? gScope->ffta[(int)ppos + 1] : 0; + float d = i < (size-1) ? gScope->ffta[(int)ppos + 2] : 0; + + float v0 = (float)catmullrom(f, a, b, c, d); + + v0 = v0 * gScope->mCh[j].mScale + gScope->mCh[j].mOffset * 50; + vert[i] = ImVec2(p.x + i * uiScale, + p.y + (sizef - v0 * 4) * uiScale); + } + float v0 = p.y + (size - gScope->mCh[j].mOffset * 50 * 4) * uiScale; + dl->Flags = 0; + for (int i = 0; i < size-1; i++) + { + ImVec2 quad[4]; + quad[0] = ImVec2(vert[i].x, v0); + quad[1] = ImVec2(vert[i].x, vert[i].y); + quad[2] = ImVec2(vert[i + 1].x, vert[i + 1].y); + quad[3] = ImVec2(vert[i + 1].x, v0); + dl->AddConvexPolyFilled(quad, 4, (gScope->colors[j] & 0xffffff) | 0x3f000000); + + } + + dl->Flags = ImDrawListFlags_AntiAliasedLines; + dl->AddPolyline(vert, size, gScope->colors[j], false, 1); + + } + } + + if (!ImGui::IsPopupOpen("Freq Context",ImGuiPopupFlags_AnyPopupId)) + if (gScope->mCh[0].mEnabled || gScope->mCh[1].mEnabled || gScope->mCh[2].mEnabled || gScope->mCh[3].mEnabled) + { + ImVec2 mp = ImGui::GetMousePos(); + mp.x -= p.x; + mp.y -= p.y; + if (mp.x > 0 && mp.x < size * uiScale && + mp.y > 0 && mp.y < size * uiScale) + { + ImGui::GetWindowDrawList()->AddLine( + ImVec2(p.x + mp.x, p.y), + ImVec2(p.x + mp.x, p.y + grid_size * uiScale), + 0xff00ff00, 1 * uiScale); + ImGui::BeginTooltip(); + int note = (int)(12 * log(32 * POW_2_3_4TH * (freqbins[(int)(mp.x / uiScale)] / (sizef-1))) / log(2)); + if (note < 0 || note > 127) note = -1; + ImGui::Text("%3.3fHz%s%s", freqbins[(int)(mp.x / uiScale)], note==-1?"":"\n", note==-1?"":gNotestr[note]); + ImGui::EndTooltip(); + } + } +} + +#if 0 +static int groups(ScopeData* gScope, double h) +{ + int count = 0; + for (int i = 1; i < gScope->mPot / 4; i++) + { + if (gScope->fft1[i - 1] < h && gScope->fft1[i] > h) + count++; + } + return count; +} + +static void detect_fundamentals(ScopeData* gScope) +{ + // gScope->fft1[1..pot/4] has our mags + double maxmag = 0; + for (int i = 0; i < gScope->mPot / 4; i++) + if (maxmag < gScope->fft1[i]) + maxmag = gScope->fft1[i]; + + double minmag = 0; + int count = 0; + int iters = 0; + double h = (minmag + maxmag) / 2; + double step = h / 2; + while (iters < 100 && count != 16) + { + count = groups(gScope, h); + if (count < 16) + { + h -= step; + } + else + { + h += step; + } + step /= 2; + iters++; + } + char temp[1024]; + int ofs = 0; + temp[0] = 0; + const float gSamplerate = gScope->mSampleRate; + float freqbin = gSamplerate / (float)(gScope->mPot / 2); + + int startbin = 0; + for (int i = 2; i < gScope->mPot / 4; i++) + { + if (gScope->fft1[i - 1] < h && gScope->fft1[i] > h) + { + startbin = i; + } + if (gScope->fft1[i - 1] > h && gScope->fft1[i] < h) + { + double sum = 0; + double magsum = 0; + for (int j = startbin; j < i; j++) + { + sum += gScope->fft1[j]; + magsum += gScope->fft1[j] * j * freqbin; + } + if (sum != 0) + { + magsum /= sum; + sum /= i - startbin; + sum /= maxmag / 2; // normalize + ofs += sprintf(temp + ofs, "%3.3f\t%3.3f\n", magsum, sum); + } + } + } + + + for (int i = 0; i < count; i++) + { + } + ImGui::SetClipboardText(temp); +} +#endif + +void do_show_scope_window(ScopeData* gScope, const float uiScale) +{ + // Data is updated live, so let's take local copies of critical stuff. + int index = gScope->mIndex; + + ImGui::Begin("Scope", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize); + + ImGui::BeginChild("Channel options", ImVec2((4 * 25)*uiScale, (2 * 152 + 32) * uiScale)); + ImGui::Checkbox("###ea", &gScope->mCh[0].mEnabled); ImGui::SameLine(); + ImGui::Checkbox("###eb", &gScope->mCh[1].mEnabled); ImGui::SameLine(); + ImGui::Checkbox("###ec", &gScope->mCh[2].mEnabled); ImGui::SameLine(); + ImGui::Checkbox("###ed", &gScope->mCh[3].mEnabled); + + ImGui::PushStyleColor(ImGuiCol_SliderGrab, gScope->colors[0]); ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, gScope->colors[0]); + if (ImGui::VSliderInt("###0a", ImVec2(19 * uiScale, 150 * uiScale), &gScope->mCh[0].mScaleSlider, -4, 4, "")) + { + gScope->mCh[0].mScale = scalesteps[gScope->mCh[0].mScaleSlider + 4]; + } + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("%s", scaletexts[gScope->mCh[0].mScaleSlider + 4]); + ImGui::EndTooltip(); + } + ImGui::PopStyleColor(2); ImGui::SameLine(); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, gScope->colors[1]); ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, gScope->colors[1]); + if (ImGui::VSliderInt("###1a", ImVec2(19 * uiScale, 150 * uiScale), &gScope->mCh[1].mScaleSlider, -4, 4, "")) + { + gScope->mCh[1].mScale = scalesteps[gScope->mCh[1].mScaleSlider + 4]; + } + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("%s", scaletexts[gScope->mCh[1].mScaleSlider + 4]); + ImGui::EndTooltip(); + } + ImGui::PopStyleColor(2); ImGui::SameLine(); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, gScope->colors[2]); ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, gScope->colors[2]); + if (ImGui::VSliderInt("###2a", ImVec2(19 * uiScale, 150 * uiScale), &gScope->mCh[2].mScaleSlider, -4, 4, "")) + { + gScope->mCh[2].mScale = scalesteps[gScope->mCh[2].mScaleSlider + 4]; + } + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("%s", scaletexts[gScope->mCh[2].mScaleSlider + 4]); + ImGui::EndTooltip(); + } + ImGui::PopStyleColor(2); ImGui::SameLine(); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, gScope->colors[3]); ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, gScope->colors[3]); + if (ImGui::VSliderInt("###3a", ImVec2(19 * uiScale, 150 * uiScale), &gScope->mCh[3].mScaleSlider, -4, 4, "")) + { + gScope->mCh[3].mScale = scalesteps[gScope->mCh[3].mScaleSlider + 4]; + } + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("%s", scaletexts[gScope->mCh[3].mScaleSlider + 4]); + ImGui::EndTooltip(); + } + ImGui::PopStyleColor(2); + + ImGui::PushStyleColor(ImGuiCol_SliderGrab, gScope->colors[0]); + ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, gScope->colors[0]); + ImGui::VSliderFloat("###0b", ImVec2(19 * uiScale, 150 * uiScale), &gScope->mCh[0].mOffset, -2, 2, ""); + ImGui::PopStyleColor(2); + ImGui::SameLine(); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("%3.3f", gScope->mCh[0].mOffset); + ImGui::EndTooltip(); + } + ImGui::PushStyleColor(ImGuiCol_SliderGrab, gScope->colors[1]); + ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, gScope->colors[1]); + ImGui::VSliderFloat("###1b", ImVec2(19 * uiScale, 150 * uiScale), &gScope->mCh[1].mOffset, -2, 2, ""); + ImGui::PopStyleColor(2); + ImGui::SameLine(); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("%3.3f", gScope->mCh[1].mOffset); + ImGui::EndTooltip(); + } + ImGui::PushStyleColor(ImGuiCol_SliderGrab, gScope->colors[2]); + ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, gScope->colors[2]); + ImGui::VSliderFloat("###2b", ImVec2(19 * uiScale, 150 * uiScale), &gScope->mCh[2].mOffset, -2, 2, ""); + ImGui::PopStyleColor(2); + ImGui::SameLine(); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("%3.3f", gScope->mCh[2].mOffset); + ImGui::EndTooltip(); + } + ImGui::PushStyleColor(ImGuiCol_SliderGrab, gScope->colors[3]); + ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, gScope->colors[3]); + ImGui::VSliderFloat("###3b", ImVec2(19 * uiScale, 150 * uiScale), &gScope->mCh[3].mOffset, -2, 2, ""); + ImGui::PopStyleColor(2); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("%3.3f", gScope->mCh[3].mOffset); + ImGui::EndTooltip(); + } + ImGui::EndChild(); + + ImGui::SameLine(); + + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::GetStyle().Colors[ImGuiCol_FrameBg]); + ImGui::BeginChild("Scope and scroll", ImVec2(grid_size * uiScale, (grid_size + 24)* uiScale)); + ImGui::BeginChild("Scope proper", ImVec2(grid_size * uiScale, grid_size * uiScale)); + + if (gScope->mDisplay == 0) + scope_time(gScope, uiScale, index); + if (gScope->mDisplay == 1) + scope_freq(gScope, uiScale, index); + /* + if (gScope->mDisplay == 2 || gScope->mDisplay == 3) + scope_plot(gScope, uiScale, index); + */ + + ImGui::EndChild(); + ImGui::PopStyleColor(1); + /* + if (gScope->mDisplay == 1) + { + if (ImGui::BeginPopupContextItem("Freq Context")) + { + if (ImGui::BeginMenu("Experimental..")) + { + if (ImGui::MenuItem("Detect and copy fundamental frequencies")) + { + detect_fundamentals(gScope); + } + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Averaging..")) + { + if (ImGui::MenuItem("1x")) + gScope->fft.average = 1; + if (ImGui::MenuItem("4x")) + gScope->fft.average = 4; + if (ImGui::MenuItem("16x")) + gScope->fft.average = 16; + if (ImGui::MenuItem("64x")) + gScope->fft.average = 64; + if (ImGui::MenuItem("256x")) + gScope->fft.average = 256; + ImGui::EndMenu(); + } + + ImGui::EndPopup(); + } + } + //context_menu(1, 1, 1); + */ + + if (gScope->mMode) + { + ImGui::SetNextItemWidth(grid_size * uiScale); + ImGui::SliderFloat("###scroll", &gScope->mScroll, -10.0f, 0.0f, "%.3f s"); + } + else + { + ImGui::PushStyleColor(ImGuiCol_FrameBg, 0xff3f3f3f); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, 0xff3f3f3f); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, 0xff3f3f3f); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, 0xff7f7f7f); + ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, 0xff7f7f7f); + ImGui::SetNextItemWidth(grid_size * uiScale); + float x = gScope->mScroll; + ImGui::SliderFloat("###scroll", &x, -10.0f, 0.0f, "%.3f s"); + ImGui::PopStyleColor(5); + } + ImGui::EndChild(); + + ImGui::SameLine(); + + ImGui::BeginChild("Scope options", ImVec2((4 * 21) * uiScale, 364 * uiScale)); + if (ImGui::VSliderInt("###0a", ImVec2(19 * uiScale, 155 * uiScale), &gScope->mTimeScaleSlider, -2, 2, "")) + { + gScope->mTimeScale = timescalesteps[gScope->mTimeScaleSlider + 2]; + } + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("%s", timescaletext[gScope->mTimeScaleSlider + 2]); + ImGui::EndTooltip(); + } + ImGui::SameLine(); + ImGui::BeginChild("moderadio", ImVec2(100 * uiScale, 155 * uiScale)); + if (ImGui::RadioButton("Time", gScope->mDisplay == 0)) gScope->mDisplay = 0; + if (ImGui::RadioButton("Freq", gScope->mDisplay == 1)) gScope->mDisplay = 1; + /* + if (ImGui::RadioButton("X,X'", gScope->mDisplay == 2)) gScope->mDisplay = 2; + if (ImGui::RadioButton("X,Y", gScope->mDisplay == 3)) gScope->mDisplay = 3; + */ + ImGui::Separator(); + ImGui::Text("FFT"); + if (ImGui::RadioButton("1x", gScope->mFFTZoom == 0)) gScope->mFFTZoom = 0; + if (ImGui::RadioButton("2x", gScope->mFFTZoom == 1)) gScope->mFFTZoom = 1; + if (ImGui::RadioButton("4x", gScope->mFFTZoom == 2)) gScope->mFFTZoom = 2; + if (ImGui::RadioButton("8x", gScope->mFFTZoom == 3)) gScope->mFFTZoom = 3; + ImGui::EndChild(); + char temp[64]; + sprintf(temp, "Sync ch %d###sc", gScope->mSyncChannel + 1); + if (ImGui::Button(temp, ImVec2(80 * uiScale, 20 * uiScale))) + gScope->mSyncChannel = (gScope->mSyncChannel + 1) % 4; + const char* syncmodes[3] = { "^", "v", "off" }; + sprintf(temp, "Sync %s###sm", syncmodes[gScope->mSyncMode]); + if (ImGui::Button(temp, ImVec2(80 * uiScale, 20 * uiScale))) + gScope->mSyncMode = (gScope->mSyncMode + 1) % 3; + + if (gScope->mMode == 0) + { + if (ImGui::Button("Pause", ImVec2(80 * uiScale, 20 * uiScale))) + gScope->mMode = 1; + ImGui::Text("Nudge (ms)"); + ImGui::PushStyleColor(ImGuiCol_Button, 0xff3f3f3f); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, 0xff3f3f3f); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, 0xff3f3f3f); + ImGui::Button("-0.1", ImVec2(38 * uiScale, 20 * uiScale)); + ImGui::SameLine(); + ImGui::Button("+0.1", ImVec2(38 * uiScale, 20 * uiScale)); + ImGui::Button("-1", ImVec2(38 * uiScale, 20 * uiScale)); + ImGui::SameLine(); + ImGui::Button("+1", ImVec2(38 * uiScale, 20 * uiScale)); + ImGui::Button("-10", ImVec2(38 * uiScale, 20 * uiScale)); + ImGui::SameLine(); + ImGui::Button("+10", ImVec2(38 * uiScale, 20 * uiScale)); + ImGui::Button("-100", ImVec2(38 * uiScale, 20 * uiScale)); + ImGui::SameLine(); + ImGui::Button("+100", ImVec2(38 * uiScale, 20 * uiScale)); + ImGui::PopStyleColor(3); + } + else + { + if (ImGui::Button("Capture", ImVec2(80 * uiScale, 20 * uiScale))) + gScope->mMode = 0; + ImGui::Text("Nudge (ms)"); + if (ImGui::Button("-0.1", ImVec2(38 * uiScale, 20 * uiScale))) + { + gScope->mScroll -= 0.0001f; + } + ImGui::SameLine(); + if (ImGui::Button("+0.1", ImVec2(38 * uiScale, 20 * uiScale))) + { + gScope->mScroll += 0.0001f; + } + if (ImGui::Button("-1", ImVec2(38 * uiScale, 20 * uiScale))) + { + gScope->mScroll -= 0.001f; + } + ImGui::SameLine(); + if (ImGui::Button("+1", ImVec2(38 * uiScale, 20 * uiScale))) + { + gScope->mScroll += 0.001f; + } + if (ImGui::Button("-10", ImVec2(38 * uiScale, 20 * uiScale))) + { + gScope->mScroll -= 0.01f; + } + ImGui::SameLine(); + if (ImGui::Button("+10", ImVec2(38 * uiScale, 20 * uiScale))) + { + gScope->mScroll += 0.01f; + } + if (ImGui::Button("-100", ImVec2(38 * uiScale, 20 * uiScale))) + { + gScope->mScroll -= 0.1f; + } + ImGui::SameLine(); + if (ImGui::Button("+100", ImVec2(38 * uiScale, 20 * uiScale))) + { + gScope->mScroll += 0.1f; + } + } + ImGui::EndChild(); + + ImGui::End(); + +} diff --git a/plugins/ChowDSP b/plugins/ChowDSP index 52f89b94..871f712f 160000 --- a/plugins/ChowDSP +++ b/plugins/ChowDSP @@ -1 +1 @@ -Subproject commit 52f89b94a25828f9debf8bca4d58854fb1e70228 +Subproject commit 871f712f3eb95ada1c34bf3d8170690eb4aec8d0 diff --git a/plugins/DrumKit b/plugins/DrumKit index 8d78f221..7681d30a 160000 --- a/plugins/DrumKit +++ b/plugins/DrumKit @@ -1 +1 @@ -Subproject commit 8d78f221927f5aa75d99e4fb8a6b8750141e0933 +Subproject commit 7681d30ac0b9246605d3d8d71dc7e25030748ec6 diff --git a/plugins/Fundamental b/plugins/Fundamental index 48bf3c84..9ac0cdb9 160000 --- a/plugins/Fundamental +++ b/plugins/Fundamental @@ -1 +1 @@ -Subproject commit 48bf3c84ebafc9effe7e565d8cdbf8a46b9d503c +Subproject commit 9ac0cdb93938c3f01aba58ec01fdd01257abf353 diff --git a/plugins/GrandeModular b/plugins/GrandeModular index b0d8a6fc..3d652432 160000 --- a/plugins/GrandeModular +++ b/plugins/GrandeModular @@ -1 +1 @@ -Subproject commit b0d8a6fcdb28d2e56d6b024326a7378a2c8ee45d +Subproject commit 3d6524320ce33569e3553a53571c45425ba5d078 diff --git a/plugins/ImpromptuModular b/plugins/ImpromptuModular index 2bd5691c..eb514f1e 160000 --- a/plugins/ImpromptuModular +++ b/plugins/ImpromptuModular @@ -1 +1 @@ -Subproject commit 2bd5691c8f12e21e1e6db33e42fe2fe3db7726a3 +Subproject commit eb514f1e867a5626918dd70b947908b3181f66b8 diff --git a/plugins/ImpromptuModularDark/PanelTheme.cpp b/plugins/ImpromptuModularDark/PanelTheme.cpp index d2dfcc1c..6106d31c 100644 --- a/plugins/ImpromptuModularDark/PanelTheme.cpp +++ b/plugins/ImpromptuModularDark/PanelTheme.cpp @@ -17,12 +17,12 @@ void writeThemeAndContrastAsDefault() {} void saveThemeAndContrastAsDefault(int, float) {} void loadThemeAndContrastFromDefault(int* panelTheme, float* panelContrast) { - *panelTheme = 1; + *panelTheme = rack::settings::darkMode ? 1 : 0; *panelContrast = panelContrastDefault; } bool isDark(int*) { - return true; + return rack::settings::darkMode; } void readThemeAndContrastFromDefault() {} @@ -47,7 +47,7 @@ void PanelBaseWidget::draw(const DrawArgs& args) { void InverterWidget::draw(const DrawArgs& args) { TransparentWidget::draw(args); - { + if (rack::settings::darkMode) { // nvgSave(args.vg); nvgBeginPath(args.vg); nvgFillColor(args.vg, SCHEME_WHITE);// this is the source, the current framebuffer is the dest @@ -64,4 +64,3 @@ void InverterWidget::draw(const DrawArgs& args) { // nvgRestore(args.vg); } } - diff --git a/plugins/LilacLoop b/plugins/LilacLoop index 69d8d665..cf9bb5cf 160000 --- a/plugins/LilacLoop +++ b/plugins/LilacLoop @@ -1 +1 @@ -Subproject commit 69d8d66521175cd561d53e65728d460b398950c9 +Subproject commit cf9bb5cfa5fd41ecfc9976bb106c2f4a7667c9d7 diff --git a/plugins/LomasModules b/plugins/LomasModules index a4b802ae..b714cdb0 160000 --- a/plugins/LomasModules +++ b/plugins/LomasModules @@ -1 +1 @@ -Subproject commit a4b802ae1ac12415cbeaeaef5f949dd8d38dfc5c +Subproject commit b714cdb0c662503bc6cf60c06765b426a4caa17f diff --git a/plugins/ML_modules b/plugins/ML_modules index 788ceb73..66527f10 160000 --- a/plugins/ML_modules +++ b/plugins/ML_modules @@ -1 +1 @@ -Subproject commit 788ceb73cfabddaff7245b0df072b0e22a19b360 +Subproject commit 66527f10d0ad18d03aca3bbabceb198396da5d81 diff --git a/plugins/Makefile b/plugins/Makefile index 09db238c..95645538 100644 --- a/plugins/Makefile +++ b/plugins/Makefile @@ -7,7 +7,10 @@ # -------------------------------------------------------------- # Import base definitions +DISTRHO_NAMESPACE = CardinalDISTRHO +DGL_NAMESPACE = CardinalDGL USE_NANOVG_FBO = true +WASM_EXCEPTIONS = true include ../dpf/Makefile.base.mk # -------------------------------------------------------------- @@ -23,8 +26,8 @@ endif # List of drwav functions, used in several modules DRWAV = drwav -DRWAV += drwav__on_seek DRWAV += drwav__on_read +DRWAV += drwav__on_seek DRWAV += drwav__read_and_close_f32 DRWAV += drwav__read_and_close_s16 DRWAV += drwav__read_and_close_s32 @@ -32,6 +35,13 @@ DRWAV += drwav_alaw_to_f32 DRWAV += drwav_alaw_to_s16 DRWAV += drwav_alaw_to_s16 DRWAV += drwav_alaw_to_s32 +DRWAV += drwav_bytes_to_f32 +DRWAV += drwav_bytes_to_s16 +DRWAV += drwav_bytes_to_s32 +DRWAV += drwav_bytes_to_s64 +DRWAV += drwav_bytes_to_u16 +DRWAV += drwav_bytes_to_u32 +DRWAV += drwav_bytes_to_u64 DRWAV += drwav_close DRWAV += drwav_close DRWAV += drwav_container @@ -44,29 +54,49 @@ DRWAV += drwav_f64_to_f32 DRWAV += drwav_f64_to_s16 DRWAV += drwav_f64_to_s16 DRWAV += drwav_f64_to_s32 +DRWAV += drwav_fmt_get_format DRWAV += drwav_fopen +DRWAV += drwav_fourcc_equal DRWAV += drwav_free +DRWAV += drwav_get_cursor_in_pcm_frames +DRWAV += drwav_get_length_in_pcm_frames +DRWAV += drwav_guid_equal DRWAV += drwav_init DRWAV += drwav_init_ex DRWAV += drwav_init_file DRWAV += drwav_init_file_ex +DRWAV += drwav_init_file_ex_w +DRWAV += drwav_init_file_w +DRWAV += drwav_init_file_with_metadata +DRWAV += drwav_init_file_with_metadata_w DRWAV += drwav_init_file_write DRWAV += drwav_init_file_write DRWAV += drwav_init_file_write__internal DRWAV += drwav_init_file_write__internal DRWAV += drwav_init_file_write_sequential DRWAV += drwav_init_file_write_sequential +DRWAV += drwav_init_file_write_sequential_pcm_frames +DRWAV += drwav_init_file_write_sequential_pcm_frames_w +DRWAV += drwav_init_file_write_sequential_w +DRWAV += drwav_init_file_write_w DRWAV += drwav_init_memory DRWAV += drwav_init_memory_ex +DRWAV += drwav_init_memory_with_metadata DRWAV += drwav_init_memory_write DRWAV += drwav_init_memory_write DRWAV += drwav_init_memory_write__internal DRWAV += drwav_init_memory_write__internal DRWAV += drwav_init_memory_write_sequential +DRWAV += drwav_init_memory_write_sequential_pcm_frames +DRWAV += drwav_init_with_metadata DRWAV += drwav_init_write DRWAV += drwav_init_write DRWAV += drwav_init_write__internal DRWAV += drwav_init_write_sequential +DRWAV += drwav_init_write_sequential_pcm_frames +DRWAV += drwav_init_write_with_metadata +DRWAV += drwav_metadata +DRWAV += drwav__metadata_parser DRWAV += drwav_mulaw_to_f32 DRWAV += drwav_mulaw_to_s16 DRWAV += drwav_mulaw_to_s16 @@ -88,8 +118,11 @@ DRWAV += drwav_open_ex DRWAV += drwav_open_file DRWAV += drwav_open_file_and_read_f32 DRWAV += drwav_open_file_and_read_pcm_frames_f32 +DRWAV += drwav_open_file_and_read_pcm_frames_f32_w DRWAV += drwav_open_file_and_read_pcm_frames_s16 +DRWAV += drwav_open_file_and_read_pcm_frames_s16_w DRWAV += drwav_open_file_and_read_pcm_frames_s32 +DRWAV += drwav_open_file_and_read_pcm_frames_s32_w DRWAV += drwav_open_file_and_read_s16 DRWAV += drwav_open_file_and_read_s32 DRWAV += drwav_open_file_ex @@ -131,9 +164,17 @@ DRWAV += drwav_read_f32__mulaw DRWAV += drwav_read_f32__pcm DRWAV += drwav_read_f32__pcm DRWAV += drwav_read_pcm_frames +DRWAV += drwav_read_pcm_frames_be DRWAV += drwav_read_pcm_frames_f32 +DRWAV += drwav_read_pcm_frames_f32be +DRWAV += drwav_read_pcm_frames_f32le +DRWAV += drwav_read_pcm_frames_le DRWAV += drwav_read_pcm_frames_s16 +DRWAV += drwav_read_pcm_frames_s16be +DRWAV += drwav_read_pcm_frames_s16le DRWAV += drwav_read_pcm_frames_s32 +DRWAV += drwav_read_pcm_frames_s32be +DRWAV += drwav_read_pcm_frames_s32le DRWAV += drwav_read_raw DRWAV += drwav_read_s16 DRWAV += drwav_read_s16__alaw @@ -171,14 +212,20 @@ DRWAV += drwav_seek_to_sample DRWAV += drwav_seek_to_sample DRWAV += drwav_smpl DRWAV += drwav_smpl_loop +DRWAV += drwav_take_ownership_of_metadata +DRWAV += drwav_target_write_size_bytes DRWAV += drwav_u8_to_f32 DRWAV += drwav_u8_to_s16 DRWAV += drwav_u8_to_s16 DRWAV += drwav_u8_to_s32 DRWAV += drwav_uninit +DRWAV += drwav_version +DRWAV += drwav_version_string DRWAV += drwav_write DRWAV += drwav_write DRWAV += drwav_write_pcm_frames +DRWAV += drwav_write_pcm_frames_be +DRWAV += drwav_write_pcm_frames_le DRWAV += drwav_write_raw # -------------------------------------------------------------- @@ -192,7 +239,6 @@ PLUGIN_FILES = plugins.cpp PLUGIN_FILES += Cardinal/src/Blank.cpp PLUGIN_FILES += Cardinal/src/ExpanderInputMIDI.cpp PLUGIN_FILES += Cardinal/src/ExpanderOutputMIDI.cpp -PLUGIN_FILES += Cardinal/src/glBars.cpp PLUGIN_FILES += Cardinal/src/HostAudio.cpp PLUGIN_FILES += Cardinal/src/HostCV.cpp PLUGIN_FILES += Cardinal/src/HostMIDI.cpp @@ -200,12 +246,21 @@ PLUGIN_FILES += Cardinal/src/HostMIDI-CC.cpp PLUGIN_FILES += Cardinal/src/HostMIDI-Gate.cpp PLUGIN_FILES += Cardinal/src/HostMIDI-Map.cpp PLUGIN_FILES += Cardinal/src/HostParameters.cpp +PLUGIN_FILES += Cardinal/src/HostParameters-Map.cpp PLUGIN_FILES += Cardinal/src/HostTime.cpp PLUGIN_FILES += Cardinal/src/TextEditor.cpp +ifneq ($(USE_GLES2),true) +ifneq ($(USE_GLES3),true) +PLUGIN_FILES += Cardinal/src/glBars.cpp +endif +endif + ifneq ($(STATIC_BUILD),true) PLUGIN_FILES += Cardinal/src/AudioFile.cpp +ifneq ($(WASM),true) PLUGIN_FILES += Cardinal/src/Carla.cpp +endif PLUGIN_FILES += Cardinal/src/Ildaeil.cpp ifneq ($(HEADLESS),true) ifeq ($(HAVE_X11),true) @@ -218,8 +273,14 @@ endif ifneq ($(HEADLESS),true) PLUGIN_FILES += Cardinal/src/ImGuiWidget.cpp PLUGIN_FILES += Cardinal/src/ImGuiTextEditor.cpp -PLUGIN_FILES += $(wildcard Cardinal/src/DearImGui/*.cpp) -PLUGIN_FILES += $(wildcard Cardinal/src/DearImGuiColorTextEditor/*.cpp) +PLUGIN_FILES += Cardinal/src/SassyScope.cpp +PLUGIN_FILES += Cardinal/src/DearImGui.cpp +PLUGIN_FILES += Cardinal/src/DearImGuiColorTextEditor.cpp +endif + +ifeq ($(shell $(PKG_CONFIG) --exists fftw3f && echo true),true) +PLUGIN_FILES += Cardinal/src/AudioToCVPitch.cpp +BASE_FLAGS += -DHAVE_FFTW3F endif # -------------------------------------------------------------- @@ -231,6 +292,11 @@ PLUGIN_FILES += Fundamental/src/dr_wav.c # modules/types which are present in other plugins FUNDAMENTAL_CUSTOM = $(DRWAV) +# -------------------------------------------------------------- +# ZamAudio (always enabled) + +PLUGIN_FILES += $(wildcard ZamAudio/src/*.cpp) + ifneq ($(NOPLUGINS),true) # -------------------------------------------------------------- # 21kHz @@ -309,6 +375,16 @@ PLUGIN_FILES += AriaModules/src/Undular.cpp # modules/types which are present in other plugins ARIA_CUSTOM = Blank +# -------------------------------------------------------------- +# AS + +PLUGIN_FILES += $(filter-out AS/src/AS.cpp,$(wildcard AS/src/*.cpp)) +PLUGIN_FILES += AS/freeverb/revmodel.cpp + +# modules/types which are present in other plugins +AS_CUSTOM = ADSR BpmDisplayWidget LabelDisplayWidget LedLight LowFrequencyOscillator SigDisplayWidget VCA WaveShaper YellowRedLight allpass comb revmodel +AS_CUSTOM_PER_FILE = NumberDisplayWidget + # -------------------------------------------------------------- # AudibleInstruments @@ -444,7 +520,7 @@ PLUGIN_FILES += $(filter-out Bidoo/src/plugin.cpp Bidoo/src/ANTN.cpp,$(wildcard PLUGIN_FILES += $(wildcard Bidoo/src/dep/*.cpp) PLUGIN_FILES += $(wildcard Bidoo/src/dep/filters/*.cpp) PLUGIN_FILES += $(wildcard Bidoo/src/dep/freeverb/*.cpp) -PLUGIN_FILES += $(wildcard Bidoo/src/dep/lodepng/*.cpp) +PLUGIN_FILES += $(filter-out Bidoo/src/dep/lodepng/pngdetail.cpp,$(wildcard Bidoo/src/dep/lodepng/*.cpp)) PLUGIN_FILES += $(filter-out Bidoo/src/dep/resampler/main.cpp,$(wildcard Bidoo/src/dep/resampler/*.cpp)) PLUGIN_FILES += BidooDark/plugin.cpp @@ -483,6 +559,9 @@ CATROMODULO_CUSTOM = LowFrequencyOscillator NumDisplayWidget PLUGIN_FILES += $(filter-out cf/src/plugin.cpp,$(wildcard cf/src/*.cpp)) +# modules/types which are present in other plugins +CF_CUSTOM = $(DRWAV) + # -------------------------------------------------------------- # DrumKit @@ -517,7 +596,12 @@ PLUGIN_FILES += $(filter-out Extratone/src/plugin.cpp,$(wildcard Extratone/src/* PLUGIN_FILES += $(filter-out FehlerFabrik/src/plugin.cpp,$(wildcard FehlerFabrik/src/*.cpp)) # modules/types which are present in other plugins -FEHLERFABRIK_CUSTOM = Operator Sequencer SlewLimiter +FEHLERFABRIK_CUSTOM = Operator Sequencer SlewLimiter SimpleDelay + +# -------------------------------------------------------------- +# forsitan modulare + +PLUGIN_FILES += $(filter-out forsitan-modulare/src/forsitan.cpp,$(wildcard forsitan-modulare/src/*.cpp)) # -------------------------------------------------------------- # GlueTheGiant @@ -645,6 +729,11 @@ PLUGIN_FILES += $(filter-out LyraeModules/src/plugin.cpp,$(wildcard LyraeModules # modules/types which are present in other plugins LYRAE_CUSTOM = Delta +# -------------------------------------------------------------- +# Meander + +PLUGIN_FILES += $(filter-out Meander/src/plugin.cpp,$(wildcard Meander/src/*.cpp)) + # -------------------------------------------------------------- # MindMeld @@ -697,6 +786,11 @@ PLUGIN_FILES += $(filter-out MSM/src/MSM.cpp,$(wildcard MSM/src/*.cpp)) # modules/types which are present in other plugins MSM_CUSTOM = ADSR BlankPanel Delay LFO LowFrequencyOscillator Mult Noise OP VCA VCO sawTable triTable +# -------------------------------------------------------------- +# myth-modules + +PLUGIN_FILES += $(filter-out myth-modules/src/plugin.cpp,$(wildcard myth-modules/src/*.cpp)) + # -------------------------------------------------------------- # Nonlinear Circuits @@ -736,6 +830,9 @@ PLUGIN_FILES += $(filter-out PathSet/src/plugin.cpp,$(wildcard PathSet/src/*.cpp PLUGIN_FILES += $(filter-out PinkTrombone/src/plugin.cpp,$(wildcard PinkTrombone/src/*.cpp)) PLUGIN_FILES += $(wildcard PinkTrombone/src/PinkTrombone/*.cpp) +# modules/types which are present in other plugins +PINKTROMBONE_CUSTOM = WhiteNoise + # -------------------------------------------------------------- # Prism @@ -869,8 +966,13 @@ VALLEYAUDIO_CUSTOM_PER_FILE = TempoKnob PLUGIN_FILES += $(filter-out voxglitch/src/plugin.cpp,$(wildcard voxglitch/src/*.cpp)) # modules/types which are present in other plugins -VOXGLITCH_CUSTOM = $(DRWAV) AudioFile Looper Readout -VOXGLITCH_CUSTOM_PER_FILE = AudioBuffer GateSequencer Grain Sequencer SequencerDisplay VoltageSequencer +VOXGLITCH_CUSTOM = $(DRWAV) ADSR AudioFile Looper Readout +VOXGLITCH_CUSTOM_PER_FILE = AudioBuffer GateSequencer Grain SamplePlayer Sequencer SequencerDisplay VoltageSequencer + +# -------------------------------------------------------------- +# WhatTheRack + +PLUGIN_FILES += $(filter-out WhatTheRack/src/WhatTheRack.cpp,$(wildcard WhatTheRack/src/*.cpp)) # -------------------------------------------------------------- # ZetaCarinaeModules @@ -880,9 +982,9 @@ PLUGIN_FILES += $(filter-out ZetaCarinaeModules/src/plugin.cpp,$(wildcard ZetaCa # -------------------------------------------------------------- # ZZC -PLUGIN_FILES += $(filter-out ZZC/src/ZZC.cpp,$(wildcard ZZC/src/*.cpp)) -PLUGIN_FILES += ZZC/src/dsp/Wavetable.cpp -PLUGIN_FILES += ZZC/src/filetypes/WavSupport.cpp +PLUGIN_FILES += $(filter-out ZZC/src/ZZC.cpp ZZC/src/WavetablePlayer.cpp,$(wildcard ZZC/src/*.cpp)) +# PLUGIN_FILES += ZZC/src/dsp/Wavetable.cpp +# PLUGIN_FILES += ZZC/src/filetypes/WavSupport.cpp # modules/types which are present in other plugins ZZC_CUSTOM = Clock LowFrequencyOscillator @@ -909,7 +1011,8 @@ BASE_FLAGS += -I../dpf/dgl/src/nanovg BASE_FLAGS += -I../dpf/distrho BASE_FLAGS += -I../include -BASE_FLAGS += -I../include/neon-compat +BASE_FLAGS += -I../include/osdialog-stub +BASE_FLAGS += -I../include/simd-compat ifeq ($(HAVE_X11),true) BASE_FLAGS += -DHAVE_X11 @@ -917,7 +1020,7 @@ endif ifeq ($(SYSDEPS),true) BASE_FLAGS += -DCARDINAL_SYSDEPS -BASE_FLAGS += $(shell pkg-config --cflags jansson libarchive samplerate speexdsp) +BASE_FLAGS += $(shell $(PKG_CONFIG) --cflags jansson libarchive samplerate speexdsp) BASE_FLAGS += -I../deps/sysroot/include else BASE_FLAGS += -DZSTDLIB_VISIBILITY= @@ -931,12 +1034,15 @@ BASE_FLAGS += -I../src/Rack/dep/filesystem/include # # BASE_FLAGS += -I../src/Rack/dep/fuzzysearchdatabase/src BASE_FLAGS += -I../src/Rack/dep/glfw/include BASE_FLAGS += -I../src/Rack/dep/nanosvg/src -BASE_FLAGS += -I../src/Rack/dep/osdialog BASE_FLAGS += -I../src/Rack/dep/oui-blendish BASE_FLAGS += -I../src/Rack/dep/pffft ifeq ($(DEBUG),true) BASE_FLAGS += -UDEBUG +ifeq ($(WASM),true) +# SSE must always be enabled on wasm, even in debug builds +BASE_FLAGS += -msse -msse2 -msse3 -msimd128 +endif endif ifeq ($(HEADLESS),true) @@ -946,17 +1052,16 @@ BASE_FLAGS += -ffat-lto-objects endif endif -ifeq ($(BSD),true) +ifeq ($(BSD)$(WASM),true) BASE_FLAGS += -D'aligned_alloc_16(ptr)'='aligned_alloc(16,ptr)' BASE_FLAGS += -D'aligned_free_16(ptr)'='free(ptr)' endif -ifeq ($(WASM),true) -BASE_FLAGS += -DNANOVG_GLES2=1 -BASE_FLAGS += -msse -msse2 -msse3 -msimd128 -else ifneq ($(HAIKU),true) +ifneq ($(WASM),true) +ifneq ($(HAIKU),true) BASE_FLAGS += -pthread endif +endif ifeq ($(WINDOWS),true) BASE_FLAGS += -D_USE_MATH_DEFINES @@ -969,17 +1074,34 @@ ifeq ($(NOPLUGINS),true) BASE_FLAGS += -DNOPLUGINS endif +ifeq ($(USE_GLES2),true) +BASE_FLAGS += -DNANOVG_GLES2_FORCED +else ifeq ($(USE_GLES3),true) +BASE_FLAGS += -DNANOVG_GLES3_FORCED +endif + ifeq ($(shell $(PKG_CONFIG) --exists sndfile && echo true),true) BASE_FLAGS += -DHAVE_SNDFILE endif BUILD_C_FLAGS += -std=gnu11 BUILD_C_FLAGS += -fno-finite-math-only -fno-strict-aliasing -BUILD_CXX_FLAGS += -fno-finite-math-only -fno-strict-aliasing -faligned-new +BUILD_CXX_FLAGS += -fno-finite-math-only -fno-strict-aliasing + +ifneq ($(MACOS),true) +BUILD_CXX_FLAGS += -faligned-new -Wno-abi +endif # Rack code is not tested for this flag, unset it BUILD_CXX_FLAGS += -U_GLIBCXX_ASSERTIONS -Wp,-U_GLIBCXX_ASSERTIONS +# Ignore bad behaviour from Rack API +BUILD_CXX_FLAGS += -Wno-format-security + +ifeq ($(WASM),true) +BUILD_CXX_FLAGS += -fexceptions +endif + # -------------------------------------------------------------- # lots of warnings from VCV side @@ -995,6 +1117,23 @@ ifeq ($(MACOS),true) BASE_FLAGS += -Wno-unknown-warning-option endif +# -------------------------------------------------------------- +# Carla and friends build flags + +CARLA_FLAGS = \ + -DCARLA_BACKEND_NAMESPACE=Cardinal \ + -DREAL_BUILD \ + -DSTATIC_PLUGIN_TARGET \ + -I../deps/aubio/src \ + -I../carla/source/backend \ + -I../carla/source/includes \ + -I../carla/source/modules \ + -I../carla/source/utils + +ifeq ($(WASM),true) +CARLA_FLAGS += -DDISTRHO_RUNNER_INDIRECT_WASM_CALLS +endif + # -------------------------------------------------------------- # Build targets @@ -1009,12 +1148,19 @@ clean: # -------------------------------------------------------------- ifeq ($(NOPLUGINS),true) -PLUGIN_LIST = Cardinal +PLUGIN_LIST = Cardinal Fundamental ZamAudio + +RESOURCE_FILES = \ + $(wildcard Cardinal/res/*.svg) \ + $(wildcard Fundamental/res/*.svg) \ + $(wildcard Fundamental/res/components/*.svg) \ + $(wildcard ZamAudio/res/*.svg) \ + Fundamental/presets else PLUGIN_LIST = $(subst /plugin.json,,$(wildcard */plugin.json)) -endif UNWANTED_FILES = HetrickCV/res/illustrator - deprecated/MyModule.svg +UNWANTED_FILES += $(wildcard Meander/res/*) UNWANTED_FILES += $(wildcard Mog/res/*) UNWANTED_FILES += $(wildcard Mog/res/*/*) UNWANTED_FILES += $(wildcard nonlinearcircuits/res/*) @@ -1038,13 +1184,13 @@ RESOURCE_FILES += BaconPlugs/res/Keypunch029.json RESOURCE_FILES += BaconPlugs/res/midi/chopin RESOURCE_FILES += BaconPlugs/res/midi/debussy RESOURCE_FILES += BaconPlugs/res/midi/goldberg -RESOURCE_FILES += Cardinal/res/Miku/Miku.png RESOURCE_FILES += cf/playeroscs RESOURCE_FILES += DrumKit/res/samples RESOURCE_FILES += MindMeldModular/res/ShapeMaster/CommunityPresets RESOURCE_FILES += MindMeldModular/res/ShapeMaster/CommunityShapes RESOURCE_FILES += MindMeldModular/res/ShapeMaster/MindMeldPresets RESOURCE_FILES += MindMeldModular/res/ShapeMaster/MindMeldShapes +RESOURCE_FILES += Meander/res RESOURCE_FILES += Mog/res RESOURCE_FILES += nonlinearcircuits/res RESOURCE_FILES += ParableInstruments/res/Neil.png @@ -1052,12 +1198,26 @@ RESOURCE_FILES += $(wildcard unless_modules/art/*.art) RESOURCE_FILES += $(wildcard unless_modules/art/svg/*/*.svg) RESOURCE_FILES += $(wildcard unless_modules/font/*.ttf) # RESOURCE_FILES += $(wildcard unless_modules/manual/*) +endif -# MOD builds only have LV2 FX variant for now +RESOURCE_FILES += Cardinal/res/Miku/Miku.png + +# MOD builds only have LV2 main and FX variant ifeq ($(MOD_BUILD),true) -LV2_RESOURCES = $(PLUGIN_LIST:%=../bin/CardinalFX.lv2/resources/PluginManifests/%.json) + +LV2_RESOURCES = $(PLUGIN_LIST:%=../bin/Cardinal.lv2/resources/PluginManifests/%.json) +LV2_RESOURCES += $(PLUGIN_LIST:%=../bin/CardinalFX.lv2/resources/PluginManifests/%.json) +LV2_RESOURCES += $(RESOURCE_FILES:%=../bin/Cardinal.lv2/resources/%) LV2_RESOURCES += $(RESOURCE_FILES:%=../bin/CardinalFX.lv2/resources/%) + +# MOD builds only have LV2 FX variant for now +else ifeq ($(WASM),true) + +LV2_RESOURCES = $(PLUGIN_LIST:%=../bin/CardinalNative.lv2/resources/PluginManifests/%.json) +LV2_RESOURCES += $(RESOURCE_FILES:%=../bin/CardinalNative.lv2/resources/%) + else + LV2_RESOURCES = $(PLUGIN_LIST:%=../bin/Cardinal.lv2/resources/PluginManifests/%.json) LV2_RESOURCES += $(PLUGIN_LIST:%=../bin/CardinalFX.lv2/resources/PluginManifests/%.json) LV2_RESOURCES += $(PLUGIN_LIST:%=../bin/CardinalSynth.lv2/resources/PluginManifests/%.json) @@ -1070,9 +1230,13 @@ VST2_RESOURCES = $(PLUGIN_LIST:%=../bin/CardinalFX.vst/Contents/Resources/Plugi VST2_RESOURCES += $(PLUGIN_LIST:%=../bin/CardinalSynth.vst/Contents/Resources/PluginManifests/%.json) VST2_RESOURCES += $(RESOURCE_FILES:%=../bin/CardinalFX.vst/Contents/Resources/%) VST2_RESOURCES += $(RESOURCE_FILES:%=../bin/CardinalSynth.vst/Contents/Resources/%) +CLAP_RESOURCES = $(PLUGIN_LIST:%=../bin/CardinalFX.clap/Contents/Resources/PluginManifests/%.json) +CLAP_RESOURCES += $(RESOURCE_FILES:%=../bin/CardinalFX.clap/Contents/Resources/%) else VST2_RESOURCES = $(PLUGIN_LIST:%=../bin/Cardinal.vst/resources/PluginManifests/%.json) VST2_RESOURCES += $(RESOURCE_FILES:%=../bin/Cardinal.vst/resources/%) +CLAP_RESOURCES = $(PLUGIN_LIST:%=../bin/Cardinal.clap/resources/PluginManifests/%.json) +CLAP_RESOURCES += $(RESOURCE_FILES:%=../bin/Cardinal.clap/resources/%) endif VST3_RESOURCES = $(PLUGIN_LIST:%=../bin/Cardinal.vst3/Contents/Resources/PluginManifests/%.json) @@ -1081,9 +1245,10 @@ VST3_RESOURCES += $(PLUGIN_LIST:%=../bin/CardinalSynth.vst3/Contents/Resources/P VST3_RESOURCES += $(RESOURCE_FILES:%=../bin/Cardinal.vst3/Contents/Resources/%) VST3_RESOURCES += $(RESOURCE_FILES:%=../bin/CardinalFX.vst3/Contents/Resources/%) VST3_RESOURCES += $(RESOURCE_FILES:%=../bin/CardinalSynth.vst3/Contents/Resources/%) + endif -resources: $(LV2_RESOURCES) $(VST2_RESOURCES) $(VST3_RESOURCES) +resources: $(LV2_RESOURCES) $(VST2_RESOURCES) $(VST3_RESOURCES) $(CLAP_RESOURCES) ../bin/Cardinal.lv2/resources/%: % -@mkdir -p "$(shell dirname $@)" @@ -1093,6 +1258,10 @@ resources: $(LV2_RESOURCES) $(VST2_RESOURCES) $(VST3_RESOURCES) -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ +../bin/CardinalNative.lv2/resources/%: % + -@mkdir -p "$(shell dirname $@)" + $(SILENT)ln -sf $(abspath $<) $@ + ../bin/CardinalSynth.lv2/resources/%: % -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ @@ -1111,6 +1280,10 @@ endif -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ +../bin/CardinalNative.lv2/resources/PluginManifests/%.json: %/plugin.json + -@mkdir -p "$(shell dirname $@)" + $(SILENT)ln -sf $(abspath $<) $@ + ../bin/CardinalSynth.lv2/resources/PluginManifests/%.json: %/plugin.json -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ @@ -1144,6 +1317,10 @@ ifeq ($(MACOS),true) -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ +../bin/CardinalFX.clap/Contents/Resources/%: % + -@mkdir -p "$(shell dirname $@)" + $(SILENT)ln -sf $(abspath $<) $@ + ../bin/CardinalSynth.vst/Contents/Resources/%: % -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ @@ -1152,6 +1329,10 @@ ifeq ($(MACOS),true) -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ +../bin/CardinalFX.clap/Contents/Resources/PluginManifests/%.json: %/plugin.json + -@mkdir -p "$(shell dirname $@)" + $(SILENT)ln -sf $(abspath $<) $@ + ../bin/CardinalSynth.vst/Contents/Resources/PluginManifests/%.json: %/plugin.json -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ @@ -1160,9 +1341,17 @@ else -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ +../bin/Cardinal.clap/resources/%: % + -@mkdir -p "$(shell dirname $@)" + $(SILENT)ln -sf $(abspath $<) $@ + ../bin/Cardinal.vst/resources/PluginManifests/%.json: %/plugin.json -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ + +../bin/Cardinal.clap/resources/PluginManifests/%.json: %/plugin.json + -@mkdir -p "$(shell dirname $@)" + $(SILENT)ln -sf $(abspath $<) $@ endif # -------------------------------------------------------------- @@ -1207,13 +1396,7 @@ $(BUILD_DIR)/Cardinal/%.cpp.o: Cardinal/%.cpp -Dstbtt_fontinfo=stbtt_fontinfo_cardinal \ -Dstbrp_node=stbrp_node_cardinal \ -Dstbrp_rect=stbrp_rect_cardinal \ - -DCARLA_BACKEND_NAMESPACE=Cardinal \ - -DREAL_BUILD \ - -DSTATIC_PLUGIN_TARGET \ - -I../carla/source/backend \ - -I../carla/source/includes \ - -I../carla/source/modules \ - -I../carla/source/utils + $(CARLA_FLAGS) $(BUILD_DIR)/21kHz/%.cpp.o: 21kHz/%.cpp -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" @@ -1277,6 +1460,15 @@ $(BUILD_DIR)/AriaModules/%.cpp.o: AriaModules/%.cpp -DpluginInstance=pluginInstance__Aria \ -Wno-cast-function-type +$(BUILD_DIR)/AS/%.cpp.o: AS/%.cpp + -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" + @echo "Compiling $<" + $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -c -o $@ \ + $(foreach m,$(AS_CUSTOM),$(call custom_module_names,$(m),AS)) \ + $(foreach m,$(AS_CUSTOM_PER_FILE),$(call custom_per_file_names,$(m),AS_$(shell basename $*))) \ + -DpluginInstance=pluginInstance__AS \ + -Wno-unused-private-field + $(BUILD_DIR)/AudibleInstruments/%.o: AudibleInstruments/% -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" @echo "Compiling $<" @@ -1384,7 +1576,7 @@ $(BUILD_DIR)/ChowDSP/%.cpp.o: ChowDSP/%.cpp -DUSE_EIGEN \ -DSKIP_MINGW_FORMAT \ -IChowDSP/lib \ - -IChowDSP/lib/chowdsp_utils/DSP/WDF \ + -IChowDSP/lib/chowdsp_utils/modules/chowdsp_dsp/WDF \ -Wno-deprecated-copy $(BUILD_DIR)/DrumKit/%.cpp.o: DrumKit/%.cpp @@ -1424,6 +1616,13 @@ $(BUILD_DIR)/FehlerFabrik/%.cpp.o: FehlerFabrik/%.cpp $(foreach m,$(FEHLERFABRIK_CUSTOM),$(call custom_module_names,$(m),FehlerFabrik)) \ -DpluginInstance=pluginInstance__FehlerFabrik +$(BUILD_DIR)/forsitan-modulare/%.cpp.o: forsitan-modulare/%.cpp + -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" + @echo "Compiling $<" + $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -c -o $@ \ + $(foreach m,$(GLUETHEGIANT_CUSTOM),$(call custom_module_names,$(m),forsitan)) \ + -DpluginInstance=pluginInstance__forsitan + $(BUILD_DIR)/Fundamental/%.c.o: Fundamental/%.c -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" @echo "Compiling $<" @@ -1590,6 +1789,15 @@ $(BUILD_DIR)/LyraeModules/%.cpp.o: LyraeModules/%.cpp $(foreach m,$(LYRAE_CUSTOM),$(call custom_module_names,$(m),Lyrae)) \ -DpluginInstance=pluginInstance__Lyrae +$(BUILD_DIR)/Meander/src/Meander.cpp.o: Meander/src/Meander.cpp + -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" + @echo "Compiling $<" + $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -c -o $@ \ + $(foreach m,$(MEANDER_CUSTOM),$(call custom_module_names,$(m),Meander)) \ + -DpluginInstance=pluginInstance__Meander \ + -Wno-format-security \ + -Wno-format-zero-length + $(BUILD_DIR)/MindMeldModular/src/MindMeldModular.cpp.o: MindMeldModular/src/MindMeldModular.cpp -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" @echo "Compiling $<" @@ -1647,6 +1855,13 @@ $(BUILD_DIR)/MSM/%.cpp.o: MSM/%.cpp -DpluginInstance=pluginInstance__MSM \ -DDARKTHEME +$(BUILD_DIR)/myth-modules/%.cpp.o: myth-modules/%.cpp + -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" + @echo "Compiling $<" + $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -c -o $@ \ + $(foreach m,$(MYTH_MODULES_CUSTOM),$(call custom_module_names,$(m),myth_modules)) \ + -DpluginInstance=pluginInstance__myth_modules + $(BUILD_DIR)/nonlinearcircuits/%.cpp.o: nonlinearcircuits/%.cpp -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" @echo "Compiling $<" @@ -1766,6 +1981,20 @@ $(BUILD_DIR)/voxglitch/%.cpp.o: voxglitch/%.cpp -DpluginInstance=pluginInstance__Voxglitch \ -DSKIP_MINGW_FORMAT +$(BUILD_DIR)/WhatTheRack/%.cpp.o: WhatTheRack/%.cpp + -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" + @echo "Compiling $<" + $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -c -o $@ \ + $(foreach m,$(WHATTHERACK_CUSTOM),$(call custom_module_names,$(m),WhatTheRack)) \ + -DpluginInstance=pluginInstance__WhatTheRack + +$(BUILD_DIR)/ZamAudio/%.cpp.o: ZamAudio/%.cpp + -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" + @echo "Compiling $<" + $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -c -o $@ \ + $(foreach m,$(ZAMAUDIO_CUSTOM),$(call custom_module_names,$(m),ZamAudio)) \ + -DpluginInstance=pluginInstance__ZamAudio + $(BUILD_DIR)/ZetaCarinaeModules/%.cpp.o: ZetaCarinaeModules/%.cpp -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" @echo "Compiling $<" diff --git a/plugins/Meander b/plugins/Meander new file mode 160000 index 00000000..c0958247 --- /dev/null +++ b/plugins/Meander @@ -0,0 +1 @@ +Subproject commit c095824708947630d9db6a6b7afcd51bdaa0a009 diff --git a/plugins/MindMeldModular b/plugins/MindMeldModular index a721e381..f526208d 160000 --- a/plugins/MindMeldModular +++ b/plugins/MindMeldModular @@ -1 +1 @@ -Subproject commit a721e381fa1d72d738c9c2daae08c740107e3d5e +Subproject commit f526208d9b54f9fc8950919ed3f9d9793c6e54e2 diff --git a/plugins/PathSet b/plugins/PathSet index d03e8b48..de53c786 160000 --- a/plugins/PathSet +++ b/plugins/PathSet @@ -1 +1 @@ -Subproject commit d03e8b486deba4740bc7f15ae95a08d823a7d00a +Subproject commit de53c78658c42638b7c356b78d1559634644f733 diff --git a/plugins/PinkTrombone b/plugins/PinkTrombone index ea6ab0c6..87ecd0ff 160000 --- a/plugins/PinkTrombone +++ b/plugins/PinkTrombone @@ -1 +1 @@ -Subproject commit ea6ab0c6887102ebbf6e3534e0e891b867b130cc +Subproject commit 87ecd0ff5212a65b064444362e76c9bf94c01826 diff --git a/plugins/Prism b/plugins/Prism index 8a9cc034..4d95ace8 160000 --- a/plugins/Prism +++ b/plugins/Prism @@ -1 +1 @@ -Subproject commit 8a9cc034d905079f156ed6c64efaeb4baf81490f +Subproject commit 4d95ace8b073e9e8e30b8671ecdb04101d943905 diff --git a/plugins/ValleyAudio b/plugins/ValleyAudio index 98698dc2..9745a4c6 160000 --- a/plugins/ValleyAudio +++ b/plugins/ValleyAudio @@ -1 +1 @@ -Subproject commit 98698dc28e6ed7aec56e4ab8280171a160d673ef +Subproject commit 9745a4c63747a2225a31da69b085e6185b4c8407 diff --git a/plugins/WhatTheRack b/plugins/WhatTheRack new file mode 160000 index 00000000..e3733784 --- /dev/null +++ b/plugins/WhatTheRack @@ -0,0 +1 @@ +Subproject commit e373378491d2cf3b8257137d154aef1d389c5204 diff --git a/plugins/ZamAudio/LICENSE b/plugins/ZamAudio/LICENSE new file mode 100644 index 00000000..d8cf7d46 --- /dev/null +++ b/plugins/ZamAudio/LICENSE @@ -0,0 +1,280 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/plugins/ZamAudio/plugin.json b/plugins/ZamAudio/plugin.json new file mode 100644 index 00000000..d1e1422e --- /dev/null +++ b/plugins/ZamAudio/plugin.json @@ -0,0 +1,26 @@ +{ + "slug": "ZamAudio", + "name": "ZamAudio", + "version": "1.0.0", + "license": "GPL-2.0-or-later", + "brand": "ZamAudio", + "author": "Damien Zammit and falkTX", + "authorEmail": "falktx@falktx.com", + "authorUrl": "http://www.zamaudio.com/", + "pluginUrl": "https://github.com/DISTRHO/Cardinal", + "manualUrl": "", + "sourceUrl": "https://github.com/DISTRHO/Cardinal", + "changelogUrl": "", + "modules": [ + { + "slug": "ZamComp", + "name": "Compressor", + "description": "A powerful mono compressor strip. Adds real beef to a kick or snare drum with the right settings.", + "manualUrl": "", + "tags": [ + "Effect", + "Compressor" + ] + } + ] +} diff --git a/plugins/ZamAudio/res/ZamComp.svg b/plugins/ZamAudio/res/ZamComp.svg new file mode 100644 index 00000000..81602f7e --- /dev/null +++ b/plugins/ZamAudio/res/ZamComp.svg @@ -0,0 +1,6345 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +   + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ZamAudio/res/components/ADSR-bg.svg b/plugins/ZamAudio/res/components/ADSR-bg.svg new file mode 100644 index 00000000..7d387d31 --- /dev/null +++ b/plugins/ZamAudio/res/components/ADSR-bg.svg @@ -0,0 +1,284 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ZamAudio/res/components/Scope-bg.svg b/plugins/ZamAudio/res/components/Scope-bg.svg new file mode 100644 index 00000000..e3cb21ee --- /dev/null +++ b/plugins/ZamAudio/res/components/Scope-bg.svg @@ -0,0 +1,282 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ZamAudio/res/components/button-off.svg b/plugins/ZamAudio/res/components/button-off.svg new file mode 100644 index 00000000..c335696f --- /dev/null +++ b/plugins/ZamAudio/res/components/button-off.svg @@ -0,0 +1,181 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ZamAudio/res/components/button-on.svg b/plugins/ZamAudio/res/components/button-on.svg new file mode 100644 index 00000000..67311501 --- /dev/null +++ b/plugins/ZamAudio/res/components/button-on.svg @@ -0,0 +1,265 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ZamAudio/res/components/knob-marker-small.svg b/plugins/ZamAudio/res/components/knob-marker-small.svg new file mode 100644 index 00000000..46e8a138 --- /dev/null +++ b/plugins/ZamAudio/res/components/knob-marker-small.svg @@ -0,0 +1,119 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ZamAudio/res/components/knob-marker.svg b/plugins/ZamAudio/res/components/knob-marker.svg new file mode 100644 index 00000000..d74efc60 --- /dev/null +++ b/plugins/ZamAudio/res/components/knob-marker.svg @@ -0,0 +1,144 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ZamAudio/res/components/knob-small.svg b/plugins/ZamAudio/res/components/knob-small.svg new file mode 100644 index 00000000..a84c54b6 --- /dev/null +++ b/plugins/ZamAudio/res/components/knob-small.svg @@ -0,0 +1,158 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ZamAudio/res/components/knob.svg b/plugins/ZamAudio/res/components/knob.svg new file mode 100644 index 00000000..5a4ec0a7 --- /dev/null +++ b/plugins/ZamAudio/res/components/knob.svg @@ -0,0 +1,229 @@ + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ZamAudio/res/components/port.svg b/plugins/ZamAudio/res/components/port.svg new file mode 100644 index 00000000..440fd3cd --- /dev/null +++ b/plugins/ZamAudio/res/components/port.svg @@ -0,0 +1,121 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/ZamAudio/src/compressor.cpp b/plugins/ZamAudio/src/compressor.cpp new file mode 100644 index 00000000..c52f6de1 --- /dev/null +++ b/plugins/ZamAudio/src/compressor.cpp @@ -0,0 +1,195 @@ +/* + * ZamComp mono compressor for Cardinal + * Copyright (C) 2014-2019 Damien Zammit + * Copyright (C) 2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +#include "plugin.hpp" +#include "widgets.hpp" + +// -------------------------------------------------------------------------------------------------------------------- + +struct ZamAudioCompModule : Module { + enum ParamIds { + PARAM_ATTACK, + PARAM_RELEASE, + PARAM_THRESHOLD, + PARAM_RATIO, + PARAM_KNEE, + PARAM_SLEW, + PARAM_MAKEUP, + NUM_PARAMS + }; + enum InputIds { + AUDIO_INPUT, + SIDECHAIN_INPUT, + NUM_INPUTS + }; + enum OutputIds { + AUDIO_OUTPUT, + NUM_OUTPUTS + }; + enum LightIds { + OUTLEVEL, + GAINREDUCTION, + NUM_LIGHTS + }; + + float gainred,outlevel; //lights + float oldL_yl, oldL_y1, oldL_yg; //temp + + static inline float + sanitize_denormal(float v) { + if(!std::isnormal(v)) + return 0.f; + return v; + } + + static inline float + from_dB(float gdb) { + return (expf(0.05f*gdb*logf(10.f))); + } + + static inline float + to_dB(float g) { + return (20.f*log10f(g)); + } + + ZamAudioCompModule() + { + config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); + + configParam(PARAM_ATTACK, 0.1f, 100.f, 10.f, "Attack", " ms"); + configParam(PARAM_RELEASE, 1.f, 500.f, 80.f, "Release", " ms"); + configParam(PARAM_THRESHOLD, -80.f, 0.f, 0.f, "Threshold", " db"); + configParam(PARAM_RATIO, 1.f, 20.f, 4.f, "Ratio"); + configParam(PARAM_KNEE, 0.f, 8.f, 0.f, "Knee", " dB"); + configParam(PARAM_SLEW, 1.f, 150.f, 1.f, "Slew"); + configParam(PARAM_MAKEUP, 0.f, 30.f, 0.f, "Makeup", " dB"); + configInput(AUDIO_INPUT, "Audio"); + configInput(SIDECHAIN_INPUT, "Sidechain"); + configOutput(AUDIO_OUTPUT, "Audio"); + configLight(OUTLEVEL, "Output Level"); + configLight(GAINREDUCTION, "Gain Reduction"); + + gainred = 0.0f; + outlevel = -45.0f; + oldL_yl = oldL_y1 = oldL_yg = 0.f; + } + + void process(const ProcessArgs& args) override + { + const float attack = params[PARAM_ATTACK].getValue(); + const float release = params[PARAM_RELEASE].getValue(); + const float thresdb = params[PARAM_THRESHOLD].getValue(); + const float ratio = params[PARAM_RATIO].getValue(); + const float knee = params[PARAM_KNEE].getValue(); + const float slewfactor = params[PARAM_SLEW].getValue(); + const float makeup = params[PARAM_MAKEUP].getValue(); + + const float srate = args.sampleRate; + const float width = (6.f * knee) + 0.01; + const float slewwidth = 1.8f; + const float release_coeff = exp(-1000.f/(release * srate)); + + // const float gain = std::pow(params[0].getValue(), 2.f); + + const float in0 = inputs[AUDIO_INPUT].getVoltageSum() * 0.1f; + const float in = inputs[SIDECHAIN_INPUT].isConnected() + ? inputs[SIDECHAIN_INPUT].getVoltageSum() * 0.1f + : in0; + + const float Lxg = sanitize_denormal(in == 0.f ? -160.f : to_dB(fabsf(in))); + + const float checkwidth = 2.f*fabsf(Lxg-thresdb); + + bool attslew = false; + float Lyg; + if (2.f*(Lxg-thresdb) < -width) { + Lyg = Lxg; + } else if (checkwidth <= width) { + Lyg = thresdb + (Lxg-thresdb)/ratio; + Lyg = sanitize_denormal(Lyg); + if (checkwidth <= slewwidth) { + if (Lyg >= oldL_yg) { + attslew = true; + } + } + } else if (2.f*(Lxg-thresdb) > width) { + Lyg = thresdb + (Lxg-thresdb)/ratio; + Lyg = sanitize_denormal(Lyg); + } else { + Lyg = Lxg + (1.f/ratio-1.f)*(Lxg-thresdb+width/2.f)*(Lxg-thresdb+width/2.f)/(2.f*width); + } + + const float attack_coeff = attslew + ? exp(-1000.f/((attack + 2.0*(slewfactor - 1)) * srate)) + : exp(-1000.f/(attack * srate)); + // Don't slew on release + + const float Lxl = Lxg - Lyg; + + const float Lyl = sanitize_denormal(Lxl < oldL_yl ? release_coeff * oldL_yl + (1.f-release_coeff)*Lxl + : Lxl > oldL_yl ? attack_coeff * oldL_yl+(1.f-attack_coeff)*Lxl : Lxl); + + const float Lgain = from_dB(-Lyl); + + const float out = in0 * Lgain * from_dB(makeup); + outputs[AUDIO_OUTPUT].setVoltage(out * 10.0f); + + oldL_yl = Lyl; + oldL_yg = Lyg; + + gainred = Lyl; + // const float max = (fabsf(out) > max) ? fabsf(outputs[0][i]) : sanitize_denormal(max); + // outlevel = (max == 0.f) ? -45.f : to_dB(max); // relative to - thresdb; + } +}; + +// -------------------------------------------------------------------------------------------------------------------- + +struct ZamAudioCompModuleWidget : ZamAudioModuleWidget { + typedef FundamentalBlackKnob<36> BigKnob; + + ZamAudioCompModule* const module; + + ZamAudioCompModuleWidget(ZamAudioCompModule* const m) + : ZamAudioModuleWidget(), + module(m) + { + setModule(module); + setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/ZamComp.svg"))); + + addInput(createInput(Vec(32, 280), m, ZamAudioCompModule::AUDIO_INPUT)); + addInput(createInput(Vec(32, 310), m, ZamAudioCompModule::SIDECHAIN_INPUT)); + addOutput(createOutput(Vec(100, 310), m, ZamAudioCompModule::AUDIO_OUTPUT)); + + const float scale = 0.8f; + addParam(createParamCentered(Vec(45.75f * scale, 121.25f * scale), m, ZamAudioCompModule::PARAM_ATTACK)); + addParam(createParamCentered(Vec(127.75f * scale, 121.25f * scale), m, ZamAudioCompModule::PARAM_RELEASE)); + + addParam(createParamCentered(Vec(48.25f * scale, 208.f * scale), m, ZamAudioCompModule::PARAM_THRESHOLD)); + addParam(createParamCentered(Vec(130.75f * scale, 208.f * scale), m, ZamAudioCompModule::PARAM_RATIO)); + + addParam(createParamCentered(Vec(48.25f * scale, 305.f * scale), m, ZamAudioCompModule::PARAM_KNEE)); + addParam(createParamCentered(Vec(130.75f * scale, 305.f * scale), m, ZamAudioCompModule::PARAM_SLEW)); + } +}; + +// -------------------------------------------------------------------------------------------------------------------- + +Model* modelZamComp = createModel("ZamComp"); + +// -------------------------------------------------------------------------------------------------------------------- diff --git a/plugins/ZamAudio/src/plugin.hpp b/plugins/ZamAudio/src/plugin.hpp new file mode 100644 index 00000000..b4be0918 --- /dev/null +++ b/plugins/ZamAudio/src/plugin.hpp @@ -0,0 +1,27 @@ +/* + * ZamAudio plugins For Cardinal + * Copyright (C) 2014-2019 Damien Zammit + * Copyright (C) 2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +#pragma once + +#include "rack.hpp" + +using namespace rack; + +extern Plugin* pluginInstance; + +extern Model* modelZamComp; diff --git a/plugins/ZamAudio/src/widgets.hpp b/plugins/ZamAudio/src/widgets.hpp new file mode 100644 index 00000000..437a1500 --- /dev/null +++ b/plugins/ZamAudio/src/widgets.hpp @@ -0,0 +1,52 @@ +/* + * ZamAudio plugins For Cardinal + * Copyright (C) 2014-2019 Damien Zammit + * Copyright (C) 2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +#pragma once + +#include "plugin.hpp" + +struct ZamAudioModuleWidget : ModuleWidget { +}; + +template +struct FundamentalBlackKnob : RoundKnob { + static constexpr const float kSize = size; + static constexpr const float kHalfSize = size * 0.5f; + float scale; + + FundamentalBlackKnob() { + if (size <= 22) { + setSvg(Svg::load(asset::plugin(pluginInstance, "res/components/knob-marker-small.svg"))); + bg->setSvg(Svg::load(asset::plugin(pluginInstance, "res/components/knob-small.svg"))); + } else { + setSvg(Svg::load(asset::plugin(pluginInstance, "res/components/knob-marker.svg"))); + bg->setSvg(Svg::load(asset::plugin(pluginInstance, "res/components/knob.svg"))); + } + + scale = size / sw->box.size.x; + box.size = Vec(size, size); + bg->box.size = Vec(size, size); + } + + void draw(const DrawArgs& args) override { + nvgSave(args.vg); + nvgScale(args.vg, scale, scale); + RoundKnob::draw(args); + nvgRestore(args.vg); + } +}; diff --git a/plugins/cf b/plugins/cf index 16470fb9..b6c4a66f 160000 --- a/plugins/cf +++ b/plugins/cf @@ -1 +1 @@ -Subproject commit 16470fb91bc14a7bb1aa8e646b6461af82f81275 +Subproject commit b6c4a66ffc153d78c7efa00fa886657eb182b15d diff --git a/plugins/forsitan-modulare b/plugins/forsitan-modulare new file mode 160000 index 00000000..056cc2ec --- /dev/null +++ b/plugins/forsitan-modulare @@ -0,0 +1 @@ +Subproject commit 056cc2ec9186a4175d9214eee91e4ff5cc2e5fb1 diff --git a/plugins/kocmoc b/plugins/kocmoc index f2a8c19f..eb46ce3a 160000 --- a/plugins/kocmoc +++ b/plugins/kocmoc @@ -1 +1 @@ -Subproject commit f2a8c19f8aa81769e13d085d69a44de5afaacfaa +Subproject commit eb46ce3a8b5795d61c2e3eb60f6ca58799a8cee2 diff --git a/plugins/mscHack b/plugins/mscHack index cf6b1aa5..80883512 160000 --- a/plugins/mscHack +++ b/plugins/mscHack @@ -1 +1 @@ -Subproject commit cf6b1aa5ae47a9e56a0f2ddb0c1aa54927134fb5 +Subproject commit 80883512cc397c173e40e3bc014640b838ab343a diff --git a/plugins/myth-modules b/plugins/myth-modules new file mode 160000 index 00000000..e511dd95 --- /dev/null +++ b/plugins/myth-modules @@ -0,0 +1 @@ +Subproject commit e511dd95eca830ee74fef23bddc195696603125f diff --git a/plugins/plugins.cpp b/plugins/plugins.cpp index 0d12be0c..efdd1ba2 100644 --- a/plugins/plugins.cpp +++ b/plugins/plugins.cpp @@ -26,6 +26,9 @@ // Fundamental (always enabled) #include "Fundamental/src/plugin.hpp" +// ZamAudio (always enabled) +#include "ZamAudio/src/plugin.hpp" + #ifndef NOPLUGINS // 21kHz #include "21kHz/src/21kHz.hpp" @@ -77,6 +80,19 @@ extern Model* modelUndular; extern Model* modelBlank; #undef modelBlank +// AS +#define modelADSR modelASADSR +#define modelVCA modelASVCA +#define modelWaveShaper modelASWaveShaper +#define LedLight ASLedLight +#define YellowRedLight ASYellowRedLight +#include "AS/src/AS.hpp" +#undef modelADSR +#undef modelVCA +#undef modelWaveShaper +#undef LedLight +#undef YellowRedLight + // AudibleInstruments #include "AudibleInstruments/src/plugin.hpp" @@ -309,6 +325,9 @@ void setupSamples(); // FehlerFabrik #include "FehlerFabrik/src/plugin.hpp" +// forsitan modulare +#include "forsitan-modulare/src/forsitan.hpp" + // GlueTheGiant #include "GlueTheGiant/src/plugin.hpp" bool audition_mixer = false; @@ -401,12 +420,13 @@ extern Model* modelPhraseSeq16; extern Model* modelPhraseSeq32; extern Model* modelPhraseSeqExpander; extern Model* modelProbKey; -// extern Model* modelProbKeyExpander; extern Model* modelSemiModularSynth; +extern Model* modelSygen; extern Model* modelTact; extern Model* modelTact1; extern Model* modelTactG; extern Model* modelTwelveKey; +extern Model* modelVariations; extern Model* modelWriteSeq32; extern Model* modelWriteSeq64; extern Model* modelBlankPanel; @@ -467,6 +487,10 @@ extern Model* modelBD383238; extern Model* modelZeta; #undef modelDelta +// Meander +extern int panelTheme; +#include "Meander/src/plugin.hpp" + // MindMeldModular /* NOTE too much noise in original include, do this a different way // #include "MindMeldModular/src/MindMeldModular.hpp" @@ -610,6 +634,9 @@ extern Model* modelBlankPanel; #undef modelVCA #undef modelVCO +// myth-modules +#include "myth-modules/src/plugin.hpp" + // Nonlinear Circuits #include "nonlinearcircuits/src/NLC.hpp" @@ -667,6 +694,9 @@ extern Model* modelBlankPanel; #include "voxglitch/src/plugin.hpp" #undef modelLooper +// WhatTheRack +#include "WhatTheRack/src/WhatTheRack.hpp" + // ZetaCarinaeModules #include "ZetaCarinaeModules/src/plugin.hpp" @@ -694,6 +724,7 @@ void saveHighQualityAsDefault(bool) {} // plugin instances Plugin* pluginInstance__Cardinal; Plugin* pluginInstance__Fundamental; +Plugin* pluginInstance__ZamAudio; #ifndef NOPLUGINS Plugin* pluginInstance__21kHz; Plugin* pluginInstance__8Mode; @@ -703,6 +734,7 @@ Plugin* pluginInstance__AmalgamatedHarmonics; Plugin* pluginInstance__ArableInstruments; Plugin* pluginInstance__AnimatedCircuits; Plugin* pluginInstance__Aria; +Plugin* pluginInstance__AS; Plugin* pluginInstance__AudibleInstruments; extern Plugin* pluginInstance__Autinn; Plugin* pluginInstance__Axioma; @@ -718,6 +750,7 @@ Plugin* pluginInstance__ESeries; Plugin* pluginInstance__ExpertSleepersEncoders; Plugin* pluginInstance__Extratone; Plugin* pluginInstance__FehlerFabrik; +Plugin* pluginInstance__forsitan; Plugin* pluginInstance__GlueTheGiant; Plugin* pluginInstance__GoodSheperd; Plugin* pluginInstance__GrandeModular; @@ -732,12 +765,14 @@ Plugin* pluginInstance__LilacLoop; Plugin* pluginInstance__LittleUtils; Plugin* pluginInstance__Lomas; Plugin* pluginInstance__Lyrae; +Plugin* pluginInstance__Meander; extern Plugin* pluginInstance__MindMeld; Plugin* pluginInstance__ML; Plugin* pluginInstance__MockbaModular; Plugin* pluginInstance__Mog; extern Plugin* pluginInstance__mscHack; Plugin* pluginInstance__MSM; +Plugin* pluginInstance__myth_modules; Plugin* pluginInstance__nonlinearcircuits; Plugin* pluginInstance__Orbits; Plugin* pluginInstance__ParableInstruments; @@ -752,6 +787,7 @@ Plugin* pluginInstance__stocaudio; Plugin* pluginInstance__unless_modules; Plugin* pluginInstance__ValleyAudio; Plugin* pluginInstance__Voxglitch; +Plugin* pluginInstance__WhatTheRack; Plugin* pluginInstance__ZetaCarinaeModules; Plugin* pluginInstance__ZZC; #endif // NOPLUGINS @@ -800,13 +836,23 @@ struct StaticPluginLoader { json_t* const version = json_string((APP_VERSION_MAJOR + ".0").c_str()); json_object_set(rootJ, "version", version); json_decref(version); + + // Load manifest + p->fromJson(rootJ); + + // Reject plugin if slug already exists + if (Plugin* const existingPlugin = getPlugin(p->slug)) + throw Exception("Plugin %s is already loaded, not attempting to load it again", p->slug.c_str()); } ~StaticPluginLoader() { if (rootJ != nullptr) { - plugin->fromJson(rootJ); + // Load modules manifest + json_t* const modulesJ = json_object_get(rootJ, "modules"); + plugin->modulesFromJson(modulesJ); + json_decref(rootJ); plugins.push_back(plugin); } @@ -855,7 +901,6 @@ static void initStatic__Cardinal() p->addModel(modelCardinalBlank); p->addModel(modelExpanderInputMIDI); p->addModel(modelExpanderOutputMIDI); - p->addModel(modelGlBars); p->addModel(modelHostAudio2); p->addModel(modelHostAudio8); p->addModel(modelHostCV); @@ -864,22 +909,41 @@ static void initStatic__Cardinal() p->addModel(modelHostMIDIGate); p->addModel(modelHostMIDIMap); p->addModel(modelHostParameters); + p->addModel(modelHostParametersMap); p->addModel(modelHostTime); p->addModel(modelTextEditor); + #ifndef DGL_USE_GLES + p->addModel(modelGlBars); + #else + spl.removeModule("glBars"); + #endif #ifndef STATIC_BUILD p->addModel(modelAudioFile); - p->addModel(modelCarla); p->addModel(modelIldaeil); #else spl.removeModule("AudioFile"); - spl.removeModule("Carla"); spl.removeModule("Ildaeil"); #endif + #if !(defined(DISTRHO_OS_WASM) || defined(STATIC_BUILD)) + p->addModel(modelCarla); + #else + spl.removeModule("Carla"); + #endif + #ifndef HEADLESS + p->addModel(modelSassyScope); + #else + spl.removeModule("SassyScope"); + #endif #if defined(HAVE_X11) && !defined(HEADLESS) && !defined(STATIC_BUILD) p->addModel(modelMPV); #else spl.removeModule("MPV"); #endif + #ifdef HAVE_FFTW3F + p->addModel(modelAudioToCVPitch); + #else + spl.removeModule("AudioToCVPitch"); + #endif hostTerminalModels = { modelHostAudio2, @@ -890,6 +954,7 @@ static void initStatic__Cardinal() modelHostMIDIGate, modelHostMIDIMap, modelHostParameters, + modelHostParametersMap, modelHostTime, }; } @@ -932,6 +997,18 @@ static void initStatic__Fundamental() } } +static void initStatic__ZamAudio() +{ + Plugin* const p = new Plugin; + pluginInstance__ZamAudio = p; + + const StaticPluginLoader spl(p, "ZamAudio"); + if (spl.ok()) + { + p->addModel(modelZamComp); + } +} + #ifndef NOPLUGINS static void initStatic__21kHz() { @@ -1087,6 +1164,70 @@ static void initStatic__Aria() } } +static void initStatic__AS() +{ + Plugin* const p = new Plugin; + pluginInstance__AS = p; + const StaticPluginLoader spl(p, "AS"); + if (spl.ok()) + { +#define modelADSR modelASADSR +#define modelVCA modelASVCA +#define modelWaveShaper modelASWaveShaper + //OSCILLATORS + p->addModel(modelSineOsc); + p->addModel(modelSawOsc); + //TOOLS + p->addModel(modelADSR); + p->addModel(modelVCA); + p->addModel(modelQuadVCA); + p->addModel(modelTriLFO); + p->addModel(modelAtNuVrTr); + p->addModel(modelBPMClock); + p->addModel(modelSEQ16); + p->addModel(modelMixer2ch); + p->addModel(modelMixer4ch); + p->addModel(modelMixer8ch); + p->addModel(modelMonoVUmeter); + p->addModel(modelStereoVUmeter); + p->addModel(modelMultiple2_5); + p->addModel(modelMerge2_5); + p->addModel(modelSteps); + p->addModel(modelLaunchGate); + p->addModel(modelKillGate); + p->addModel(modelFlow); + p->addModel(modelSignalDelay); + p->addModel(modelTriggersMKI); + p->addModel(modelTriggersMKII); + p->addModel(modelTriggersMKIII); + p->addModel(modelBPMCalc); + p->addModel(modelBPMCalc2); + p->addModel(modelCv2T); + p->addModel(modelZeroCV2T); + p->addModel(modelReScale); + //EFFECTS + p->addModel(modelDelayPlusFx); + p->addModel(modelDelayPlusStereoFx); + p->addModel(modelPhaserFx); + p->addModel(modelReverbFx); + p->addModel(modelReverbStereoFx); + p->addModel(modelSuperDriveFx); + p->addModel(modelSuperDriveStereoFx); + p->addModel(modelTremoloFx); + p->addModel(modelTremoloStereoFx); + p->addModel(modelWaveShaper); + p->addModel(modelWaveShaperStereo); + //BLANK PANELS + p->addModel(modelBlankPanel4); + p->addModel(modelBlankPanel6); + p->addModel(modelBlankPanel8); + p->addModel(modelBlankPanelSpecial); +#undef modelADSR +#undef modelVCA +#undef modelWaveShaper + } +} + static void initStatic__AudibleInstruments() { Plugin* const p = new Plugin; @@ -1233,6 +1374,7 @@ static void initStatic__Befaco() p->addModel(modelMuxlicer); p->addModel(modelMex); p->addModel(modelNoisePlethora); + p->addModel(modelChannelStrip); #undef modelADSR #undef modelMixer } @@ -1253,6 +1395,8 @@ static void initStatic__Bidoo() p->addModel(modelBORDL); p->addModel(modelZOUMAI); p->addModel(modelZOUMAIExpander); + p->addModel(modelENCORE); + p->addModel(modelENCOREExpander); p->addModel(modelMU); p->addModel(modelCHUTE); p->addModel(modelLOURDE); @@ -1634,6 +1778,22 @@ static void initStatic__FehlerFabrik() } } +static void initStatic__forsitan() +{ + Plugin* const p = new Plugin; + pluginInstance__forsitan = p; + + const StaticPluginLoader spl(p, "forsitan-modulare"); + if (spl.ok()) + { + p->addModel(alea); + p->addModel(interea); + p->addModel(cumuli); + p->addModel(deinde); + p->addModel(pavo); + } +} + static void initStatic__GlueTheGiant() { Plugin* const p = new Plugin; @@ -1701,6 +1861,7 @@ static void initStatic__GrandeModular() p->addModel(modelTails); p->addModel(modelVarSampleDelays); p->addModel(modelVCA3); + p->addModel(modelVCA4); } } @@ -1805,12 +1966,13 @@ static void initStatic__ImpromptuModular() p->addModel(modelPhraseSeq32); p->addModel(modelPhraseSeqExpander); p->addModel(modelProbKey); - // p->addModel(modelProbKeyExpander); p->addModel(modelSemiModularSynth); + p->addModel(modelSygen); p->addModel(modelTact); p->addModel(modelTact1); p->addModel(modelTactG); p->addModel(modelTwelveKey); + p->addModel(modelVariations); p->addModel(modelWriteSeq32); p->addModel(modelWriteSeq64); p->addModel(modelBlankPanel); @@ -1982,6 +2144,20 @@ static void initStatic__Lyrae() } } +static void initStatic__Meander() +{ + Plugin* const p = new Plugin; + pluginInstance__Meander = p; + + const StaticPluginLoader spl(p, "Meander"); + if (spl.ok()) + { + // for dark theme + panelTheme = 1; + p->addModel(modelMeander); + } +} + static void initStatic__MindMeld() { Plugin* const p = new Plugin; @@ -2203,6 +2379,19 @@ static void initStatic__MSM() } } +static void initStatic__myth_modules() +{ + Plugin* const p = new Plugin; + pluginInstance__myth_modules = p; + + const StaticPluginLoader spl(p, "myth-modules"); + if (spl.ok()) + { + p->addModel(modelMavka); + p->addModel(modelMolphar); + } +} + static void initStatic__nonlinearcircuits() { Plugin* const p = new Plugin; @@ -2263,8 +2452,11 @@ static void initStatic__PathSet() if (spl.ok()) { p->addModel(modelShiftyMod); + p->addModel(modelShiftyExpander); p->addModel(modelIceTray); p->addModel(modelAstroVibe); + p->addModel(modelGlassPane); + p->addModel(modelNudge); } } @@ -2490,6 +2682,8 @@ static void initStatic__Voxglitch() p->addModel(modelRepeater); p->addModel(modelSamplerX8); p->addModel(modelSatanonaut); + p->addModel(modelGrooveBox); + p->addModel(modelGrooveBoxExpander); p->addModel(modelWavBank); p->addModel(modelWavBankMC); p->addModel(modelXY); @@ -2497,6 +2691,20 @@ static void initStatic__Voxglitch() } } +static void initStatic__WhatTheRack() +{ + Plugin* p = new Plugin; + pluginInstance__WhatTheRack = p; + + const StaticPluginLoader spl(p, "WhatTheRack"); + if (spl.ok()) + { + p->addModel(modelWhatTheRack); + p->addModel(modelWhatTheMod); + p->addModel(modelWhatTheJack); + } +} + static void initStatic__ZetaCarinaeModules() { Plugin* p = new Plugin; @@ -2543,6 +2751,7 @@ void initStaticPlugins() { initStatic__Cardinal(); initStatic__Fundamental(); + initStatic__ZamAudio(); #ifndef NOPLUGINS initStatic__21kHz(); initStatic__8Mode(); @@ -2552,6 +2761,7 @@ void initStaticPlugins() initStatic__AnimatedCircuits(); initStatic__ArableInstruments(); initStatic__Aria(); + initStatic__AS(); initStatic__AudibleInstruments(); initStatic__Autinn(); initStatic__Axioma(); @@ -2567,6 +2777,7 @@ void initStaticPlugins() initStatic__ExpertSleepersEncoders(); initStatic__Extratone(); initStatic__FehlerFabrik(); + initStatic__forsitan(); initStatic__GlueTheGiant(); initStatic__GoodSheperd(); initStatic__GrandeModular(); @@ -2581,12 +2792,14 @@ void initStaticPlugins() initStatic__LittleUtils(); initStatic__Lomas(); initStatic__Lyrae(); + initStatic__Meander(); initStatic__MindMeld(); initStatic__ML(); initStatic__MockbaModular(); initStatic__Mog(); initStatic__mscHack(); initStatic__MSM(); + initStatic__myth_modules(); initStatic__nonlinearcircuits(); initStatic__Orbits(); initStatic__ParableInstruments(); @@ -2601,6 +2814,7 @@ void initStaticPlugins() initStatic__unless_modules(); initStatic__ValleyAudio(); initStatic__Voxglitch(); + initStatic__WhatTheRack(); initStatic__ZetaCarinaeModules(); initStatic__ZZC(); #endif // NOPLUGINS @@ -2613,5 +2827,26 @@ void destroyStaticPlugins() plugins.clear(); } +void updateStaticPluginsDarkMode() +{ +#ifndef NOPLUGINS + const bool darkMode = settings::darkMode; + // bogaudio + { + Skins& skins(Skins::skins()); + skins._default = darkMode ? "dark" : "light"; + + std::lock_guard lock(skins._defaultSkinListenersLock); + for (auto listener : skins._defaultSkinListeners) { + listener->defaultSkinChanged(skins._default); + } + } + // meander + { + panelTheme = darkMode ? 1 : 0; + } +#endif +} + } } diff --git a/plugins/repelzen b/plugins/repelzen index f812cc56..428f76c3 160000 --- a/plugins/repelzen +++ b/plugins/repelzen @@ -1 +1 @@ -Subproject commit f812cc56b7fe9e41bb13da99ef23f014015c86c1 +Subproject commit 428f76c3509e4d71489daf075c48ae4b995a0786 diff --git a/plugins/sonusmodular b/plugins/sonusmodular index b63a685c..407829b0 160000 --- a/plugins/sonusmodular +++ b/plugins/sonusmodular @@ -1 +1 @@ -Subproject commit b63a685c6c68be188f5a3d5d9f6582eb94d62e53 +Subproject commit 407829b0341dc04aa8530bd14a739c9f222930ed diff --git a/plugins/unless_modules b/plugins/unless_modules index 3f895c76..7c15142c 160000 --- a/plugins/unless_modules +++ b/plugins/unless_modules @@ -1 +1 @@ -Subproject commit 3f895c7663e3e54c4e30c406c56d420ea407133e +Subproject commit 7c15142c4e7adb174f92d7ad54c819970ac4bda4 diff --git a/plugins/voxglitch b/plugins/voxglitch index 03f4fc5c..e856cfb4 160000 --- a/plugins/voxglitch +++ b/plugins/voxglitch @@ -1 +1 @@ -Subproject commit 03f4fc5cebb5d8eb152ac59d3a51ce0ec87a2740 +Subproject commit e856cfb4dbc255165d22294e80e13957241d2c80 diff --git a/src/AsyncDialog.cpp b/src/AsyncDialog.cpp index 3c046e5b..1009eace 100644 --- a/src/AsyncDialog.cpp +++ b/src/AsyncDialog.cpp @@ -44,7 +44,7 @@ struct AsyncDialog : OpaqueWidget Label* label; AsyncDialog(const char* const message) - { + { setup(message); struct AsyncDismissButton : Button { @@ -61,7 +61,7 @@ struct AsyncDialog : OpaqueWidget } AsyncDialog(const char* const message, const std::function action) - { + { setup(message); struct AsyncCancelButton : Button { @@ -131,7 +131,7 @@ struct AsyncDialog : OpaqueWidget } void draw(const DrawArgs& args) override - { + { bndMenuBackground(args.vg, 0.0, 0.0, box.size.x, box.size.y, 0); Widget::draw(args); } @@ -261,13 +261,13 @@ struct AsyncTextInput : OpaqueWidget } void step() override - { + { OpaqueWidget::step(); box.pos = parent->box.size.minus(box.size).div(2).round(); } void draw(const DrawArgs& args) override - { + { bndMenuBackground(args.vg, 0.0, 0.0, box.size.x, box.size.y, 0); Widget::draw(args); } diff --git a/src/Cardinal/DistrhoPluginInfo.h b/src/Cardinal/DistrhoPluginInfo.h index a107e366..f08793d0 100644 --- a/src/Cardinal/DistrhoPluginInfo.h +++ b/src/Cardinal/DistrhoPluginInfo.h @@ -1,6 +1,6 @@ /* * DISTRHO Cardinal Plugin - * Copyright (C) 2021 Filipe Coelho + * Copyright (C) 2021-2022 Filipe Coelho * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -18,9 +18,10 @@ #ifndef DISTRHO_PLUGIN_INFO_H_INCLUDED #define DISTRHO_PLUGIN_INFO_H_INCLUDED -#define CARDINAL_VARIANT_MAIN 1 -#define CARDINAL_VARIANT_FX 0 -#define CARDINAL_VARIANT_SYNTH 0 +#define CARDINAL_VARIANT_MAIN 1 +#define CARDINAL_VARIANT_FX 0 +#define CARDINAL_VARIANT_NATIVE 0 +#define CARDINAL_VARIANT_SYNTH 0 #define CARDINAL_NUM_AUDIO_INPUTS 8 #define CARDINAL_NUM_AUDIO_OUTPUTS 8 @@ -35,8 +36,11 @@ #else #define DISTRHO_PLUGIN_HAS_UI 1 #define DISTRHO_PLUGIN_WANT_DIRECT_ACCESS 1 +#define DISTRHO_UI_FILE_BROWSER 1 #define DISTRHO_UI_USE_NANOVG 1 #define DISTRHO_UI_USER_RESIZABLE 1 +#define DISTRHO_UI_DEFAULT_WIDTH 1228 +#define DISTRHO_UI_DEFAULT_HEIGHT 666 #endif #define DISTRHO_PLUGIN_IS_SYNTH 0 #define DISTRHO_PLUGIN_NUM_INPUTS CARDINAL_NUM_AUDIO_INPUTS + 10 diff --git a/src/Cardinal/glfw.cpp b/src/Cardinal/glfw.cpp new file mode 120000 index 00000000..8c6a6e44 --- /dev/null +++ b/src/Cardinal/glfw.cpp @@ -0,0 +1 @@ +../custom/glfw.cpp \ No newline at end of file diff --git a/src/CardinalCommon.cpp b/src/CardinalCommon.cpp index c5414baa..4329e046 100644 --- a/src/CardinalCommon.cpp +++ b/src/CardinalCommon.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -52,16 +53,17 @@ # include #endif -const std::string CARDINAL_VERSION = "22.04"; +#ifdef DISTRHO_OS_WASM +# include +#endif + +const std::string CARDINAL_VERSION = "22.09"; namespace rack { -namespace settings { -int rateLimit = 0; -} bool isStandalone() { - return std::strstr(getPluginFormatName(), "JACK") != nullptr; + return std::strstr(getPluginFormatName(), "Standalone") != nullptr; } #ifdef ARCH_WIN @@ -76,6 +78,12 @@ std::string getSpecialPath(const SpecialPath type) case kSpecialPathCommonProgramFiles: csidl = CSIDL_PROGRAM_FILES_COMMON; break; + case kSpecialPathProgramFiles: + csidl = CSIDL_PROGRAM_FILES; + break; + case kSpecialPathAppData: + csidl = CSIDL_APPDATA; + break; default: return {}; } @@ -88,8 +96,28 @@ std::string getSpecialPath(const SpecialPath type) return {}; } #endif + +#ifdef DISTRHO_OS_WASM +char* patchFromURL = nullptr; +char* patchRemoteURL = nullptr; +char* patchStorageSlug = nullptr; +#endif + +std::string homeDir() +{ +# ifdef ARCH_WIN + return getSpecialPath(kSpecialPathUserProfile); +# else + if (const char* const home = getenv("HOME")) + return home; + if (struct passwd* const pwd = getpwuid(getuid())) + return pwd->pw_dir; +# endif + return {}; } +} // namespace rack + namespace patchUtils { @@ -103,19 +131,6 @@ static void promptClear(const char* const message, const std::function a asyncDialog::create(message, action); } - -static std::string homeDir() -{ -# ifdef ARCH_WIN - return getSpecialPath(kSpecialPathUserProfile); -# else - if (const char* const home = getenv("HOME")) - return home; - if (struct passwd* const pwd = getpwuid(getuid())) - return pwd->pw_dir; -# endif - return {}; -} #endif void loadDialog() @@ -134,20 +149,26 @@ void loadDialog() CardinalBaseUI* const ui = static_cast(pcontext->ui); DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,); - FileBrowserOptions opts; - opts.startDir = dir.c_str(); + DISTRHO_NAMESPACE::FileBrowserOptions opts; opts.saving = ui->saving = false; + opts.startDir = dir.c_str(); opts.title = "Open patch"; ui->openFileBrowser(opts); }); #endif } -void loadPathDialog(const std::string& path) +void loadPathDialog(const std::string& path, const bool asTemplate) { #ifndef HEADLESS - promptClear("The current patch is unsaved. Clear it and open the new patch?", [path]() { + promptClear("The current patch is unsaved. Clear it and open the new patch?", [path, asTemplate]() { APP->patch->loadAction(path); + + if (asTemplate) + { + APP->patch->path = ""; + APP->history->setSaved(); + } }); #endif } @@ -159,7 +180,7 @@ void loadSelectionDialog() std::string selectionDir = asset::user("selections"); system::createDirectories(selectionDir); - async_dialog_filebrowser(false, selectionDir.c_str(), "Import selection", [w](char* pathC) { + async_dialog_filebrowser(false, nullptr, selectionDir.c_str(), "Import selection", [w](char* pathC) { if (!pathC) { // No path selected return; @@ -231,9 +252,10 @@ static void saveAsDialog(const bool uncompressed) CardinalBaseUI* const ui = static_cast(pcontext->ui); DISTRHO_SAFE_ASSERT_RETURN(ui != nullptr,); - FileBrowserOptions opts; - opts.startDir = dir.c_str(); + DISTRHO_NAMESPACE::FileBrowserOptions opts; opts.saving = ui->saving = true; + opts.defaultName = "patch.vcv"; + opts.startDir = dir.c_str(); opts.title = "Save patch"; ui->savingUncompressed = uncompressed; ui->openFileBrowser(opts); @@ -254,9 +276,21 @@ void saveAsDialogUncompressed() #endif } +void openBrowser(const std::string& url) +{ +#ifdef DISTRHO_OS_WASM + EM_ASM({ + window.open(UTF8ToString($0), '_blank'); + }, url.c_str()); +#else + system::openBrowser(url); +#endif +} + } void async_dialog_filebrowser(const bool saving, + const char* const defaultName, const char* const startDir, const char* const title, const std::function action) @@ -271,8 +305,9 @@ void async_dialog_filebrowser(const bool saving, // only 1 dialog possible at a time DISTRHO_SAFE_ASSERT_RETURN(ui->filebrowserhandle == nullptr,); - FileBrowserOptions opts; + DISTRHO_NAMESPACE::FileBrowserOptions opts; opts.saving = saving; + opts.defaultName = defaultName; opts.startDir = startDir; opts.title = title; diff --git a/src/CardinalCommon.hpp b/src/CardinalCommon.hpp index e7584c85..188a454c 100644 --- a/src/CardinalCommon.hpp +++ b/src/CardinalCommon.hpp @@ -25,14 +25,18 @@ # define REMOTE_HOST_PORT "2228" #endif +#ifdef DISTRHO_OS_WASM +# ifdef STATIC_BUILD +# define CARDINAL_WASM_WELCOME_TEMPLATE_FILENAME "welcome-wasm-mini.vcv" +# else +# define CARDINAL_WASM_WELCOME_TEMPLATE_FILENAME "welcome-wasm.vcv" +# endif +#endif + extern const std::string CARDINAL_VERSION; namespace rack { -namespace settings { -extern int rateLimit; -} - namespace ui { struct Menu; } @@ -47,16 +51,24 @@ bool isStandalone(); enum SpecialPath { kSpecialPathUserProfile, kSpecialPathCommonProgramFiles, + kSpecialPathProgramFiles, + kSpecialPathAppData, }; std::string getSpecialPath(SpecialPath type); #endif +#ifdef DISTRHO_OS_WASM +extern char* patchFromURL; +extern char* patchRemoteURL; +extern char* patchStorageSlug; +#endif + } // namespace rack namespace patchUtils { void loadDialog(); -void loadPathDialog(const std::string& path); +void loadPathDialog(const std::string& path, bool asTemplate = false); void loadSelectionDialog(); void loadTemplateDialog(); void revertDialog(); @@ -64,6 +76,7 @@ void saveDialog(const std::string& path); void saveAsDialog(); void saveAsDialogUncompressed(); void appendSelectionContextMenu(rack::ui::Menu* menu); +void openBrowser(const std::string& url); bool connectToRemote(); bool isRemoteConnected(); diff --git a/src/CardinalFX/DistrhoPluginInfo.h b/src/CardinalFX/DistrhoPluginInfo.h index d9a9b903..ca175203 100644 --- a/src/CardinalFX/DistrhoPluginInfo.h +++ b/src/CardinalFX/DistrhoPluginInfo.h @@ -18,9 +18,10 @@ #ifndef DISTRHO_PLUGIN_INFO_H_INCLUDED #define DISTRHO_PLUGIN_INFO_H_INCLUDED -#define CARDINAL_VARIANT_MAIN 0 -#define CARDINAL_VARIANT_FX 1 -#define CARDINAL_VARIANT_SYNTH 0 +#define CARDINAL_VARIANT_MAIN 0 +#define CARDINAL_VARIANT_FX 1 +#define CARDINAL_VARIANT_NATIVE 0 +#define CARDINAL_VARIANT_SYNTH 0 #define CARDINAL_NUM_AUDIO_INPUTS 2 #define CARDINAL_NUM_AUDIO_OUTPUTS 2 @@ -28,12 +29,12 @@ #define DISTRHO_PLUGIN_BRAND "DISTRHO" #define DISTRHO_PLUGIN_URI "https://distrho.kx.studio/plugins/cardinal#fx" -#ifdef __MOD_DEVICES__ -#define DISTRHO_PLUGIN_NAME "Cardinal Mini" -#define DISTRHO_PLUGIN_LABEL "CardinalMini" +#if defined(__MOD_DEVICES__) +# define DISTRHO_PLUGIN_NAME "Cardinal Mini" +# define DISTRHO_PLUGIN_LABEL "CardinalMini" #else -#define DISTRHO_PLUGIN_NAME "Cardinal FX" -#define DISTRHO_PLUGIN_LABEL "CardinalFX" +# define DISTRHO_PLUGIN_NAME "Cardinal FX" +# define DISTRHO_PLUGIN_LABEL "CardinalFX" #endif #ifdef HEADLESS @@ -41,8 +42,11 @@ #else #define DISTRHO_PLUGIN_HAS_UI 1 #define DISTRHO_PLUGIN_WANT_DIRECT_ACCESS 1 +#define DISTRHO_UI_FILE_BROWSER 1 #define DISTRHO_UI_USE_NANOVG 1 #define DISTRHO_UI_USER_RESIZABLE 1 +#define DISTRHO_UI_DEFAULT_WIDTH 1228 +#define DISTRHO_UI_DEFAULT_HEIGHT 666 #endif #define DISTRHO_PLUGIN_IS_SYNTH 0 #define DISTRHO_PLUGIN_NUM_INPUTS CARDINAL_NUM_AUDIO_INPUTS diff --git a/src/CardinalFX/glfw.cpp b/src/CardinalFX/glfw.cpp new file mode 120000 index 00000000..8c6a6e44 --- /dev/null +++ b/src/CardinalFX/glfw.cpp @@ -0,0 +1 @@ +../custom/glfw.cpp \ No newline at end of file diff --git a/src/CardinalModuleWidget.cpp b/src/CardinalModuleWidget.cpp index 57f3ec32..39aa43ab 100644 --- a/src/CardinalModuleWidget.cpp +++ b/src/CardinalModuleWidget.cpp @@ -65,7 +65,7 @@ static void CardinalModuleWidget__loadDialog(ModuleWidget* const w) WeakPtr weakThis = w; - async_dialog_filebrowser(false, presetDir.c_str(), "Load preset", [=](char* pathC) { + async_dialog_filebrowser(false, nullptr, presetDir.c_str(), "Load preset", [=](char* pathC) { // Delete directories if empty DEFER({ try { @@ -100,7 +100,7 @@ void CardinalModuleWidget__saveDialog(ModuleWidget* const w) WeakPtr weakThis = w; - async_dialog_filebrowser(true, presetDir.c_str(), "Save preset", [=](char* pathC) { + async_dialog_filebrowser(true, "preset.vcvm", presetDir.c_str(), "Save preset", [=](char* pathC) { // Delete directories if empty DEFER({ try { @@ -132,9 +132,9 @@ void CardinalModuleWidget__saveDialog(ModuleWidget* const w) static void appendPresetItems(ui::Menu* menu, WeakPtr moduleWidget, std::string presetDir) { bool foundPresets = false; - // Note: This is not cached, so opening this menu each time might have a bit of latency. if (system::isDirectory(presetDir)) { + // Note: This is not cached, so opening this menu each time might have a bit of latency. std::vector entries = system::getEntries(presetDir); std::sort(entries.begin(), entries.end()); for (std::string path : entries) { @@ -143,7 +143,7 @@ static void appendPresetItems(ui::Menu* menu, WeakPtr moduleWidget std::regex r("^\\d+_"); name = std::regex_replace(name, r, ""); - if (system::getExtension(path) == ".vcvm") + if (system::getExtension(path) == ".vcvm" && name != "template") { if (!foundPresets) menu->addChild(new ui::MenuSeparator); @@ -281,7 +281,13 @@ static void CardinalModuleWidget__saveSelectionDialog(RackWidget* const w) std::string selectionDir = asset::user("selections"); system::createDirectories(selectionDir); - async_dialog_filebrowser(true, selectionDir.c_str(), "Save selection as", [w](char* pathC) { + async_dialog_filebrowser(true, "selection.vcvs", selectionDir.c_str(), + #ifdef DISTRHO_OS_WASM + "Save selection", + #else + "Save selection as...", + #endif + [w](char* pathC) { if (!pathC) { // No path selected return; @@ -321,6 +327,11 @@ void CardinalModuleWidget::onButton(const ButtonEvent& e) return; } + // If module positions are locked, don't consume left-click + if (settings::lockModules) { + return; + } + internal->dragOffset = e.pos; } @@ -400,7 +411,13 @@ void appendSelectionContextMenu(ui::Menu* const menu) }, false, true)); // Save - menu->addChild(createMenuItem("Save selection as", "", [w]() { + menu->addChild(createMenuItem( + #ifdef DISTRHO_OS_WASM + "Save selection", + #else + "Save selection as...", + #endif + "", [w]() { CardinalModuleWidget__saveSelectionDialog(w); }, n == 0)); diff --git a/src/CardinalNative/CardinalCommon.cpp b/src/CardinalNative/CardinalCommon.cpp new file mode 120000 index 00000000..76b4b5f3 --- /dev/null +++ b/src/CardinalNative/CardinalCommon.cpp @@ -0,0 +1 @@ +../CardinalCommon.cpp \ No newline at end of file diff --git a/src/CardinalNative/CardinalPlugin.cpp b/src/CardinalNative/CardinalPlugin.cpp new file mode 120000 index 00000000..c0c7e71e --- /dev/null +++ b/src/CardinalNative/CardinalPlugin.cpp @@ -0,0 +1 @@ +../CardinalPlugin.cpp \ No newline at end of file diff --git a/src/CardinalNative/CardinalUI.cpp b/src/CardinalNative/CardinalUI.cpp new file mode 120000 index 00000000..5558256b --- /dev/null +++ b/src/CardinalNative/CardinalUI.cpp @@ -0,0 +1 @@ +../CardinalUI.cpp \ No newline at end of file diff --git a/src/CardinalNative/DistrhoPluginInfo.h b/src/CardinalNative/DistrhoPluginInfo.h new file mode 100644 index 00000000..b820481a --- /dev/null +++ b/src/CardinalNative/DistrhoPluginInfo.h @@ -0,0 +1,62 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +#ifndef DISTRHO_PLUGIN_INFO_H_INCLUDED +#define DISTRHO_PLUGIN_INFO_H_INCLUDED + +#define CARDINAL_VARIANT_MAIN 0 +#define CARDINAL_VARIANT_FX 0 +#define CARDINAL_VARIANT_NATIVE 1 +#define CARDINAL_VARIANT_SYNTH 0 + +#define CARDINAL_NUM_AUDIO_INPUTS 2 +#define CARDINAL_NUM_AUDIO_OUTPUTS 2 + +#define DISTRHO_PLUGIN_BRAND "DISTRHO" +#define DISTRHO_PLUGIN_URI "https://distrho.kx.studio/plugins/cardinal" + +#if defined(DISTRHO_OS_WASM) && defined(STATIC_BUILD) +# define DISTRHO_PLUGIN_NAME "Mini Cardinal" +# define DISTRHO_PLUGIN_LABEL "MiniCardinal" +#else +# define DISTRHO_PLUGIN_NAME "Cardinal" +# define DISTRHO_PLUGIN_LABEL "Cardinal" +#endif + +#ifdef HEADLESS +#define DISTRHO_PLUGIN_HAS_UI 0 +#else +#define DISTRHO_PLUGIN_HAS_UI 1 +#define DISTRHO_PLUGIN_WANT_DIRECT_ACCESS 1 +#define DISTRHO_UI_FILE_BROWSER 1 +#define DISTRHO_UI_USE_NANOVG 1 +#define DISTRHO_UI_USER_RESIZABLE 1 +#define DISTRHO_UI_DEFAULT_WIDTH 1228 +#define DISTRHO_UI_DEFAULT_HEIGHT 666 +#endif +#define DISTRHO_PLUGIN_IS_SYNTH 0 +#define DISTRHO_PLUGIN_NUM_INPUTS CARDINAL_NUM_AUDIO_INPUTS +#define DISTRHO_PLUGIN_NUM_OUTPUTS CARDINAL_NUM_AUDIO_OUTPUTS +#define DISTRHO_PLUGIN_WANT_MIDI_INPUT 1 +#define DISTRHO_PLUGIN_WANT_MIDI_OUTPUT 1 +#define DISTRHO_PLUGIN_WANT_FULL_STATE 1 +#define DISTRHO_PLUGIN_WANT_STATE 1 +#define DISTRHO_PLUGIN_WANT_TIMEPOS 1 +#define DISTRHO_PLUGIN_LV2_CATEGORY "lv2:UtilityPlugin" +#define DISTRHO_PLUGIN_VST3_CATEGORIES "Fx|Generator" + +#endif // DISTRHO_PLUGIN_INFO_H_INCLUDED diff --git a/src/CardinalNative/Makefile b/src/CardinalNative/Makefile new file mode 100644 index 00000000..9798d7eb --- /dev/null +++ b/src/CardinalNative/Makefile @@ -0,0 +1,8 @@ +#!/usr/bin/make -f +# Makefile for DISTRHO Plugins # +# ---------------------------- # +# Created by falkTX +# + +NAME = CardinalNative +include ../Makefile.cardinal.mk diff --git a/src/CardinalNative/RemoteNanoVG.cpp b/src/CardinalNative/RemoteNanoVG.cpp new file mode 120000 index 00000000..a6394af3 --- /dev/null +++ b/src/CardinalNative/RemoteNanoVG.cpp @@ -0,0 +1 @@ +../custom/RemoteNanoVG.cpp \ No newline at end of file diff --git a/src/CardinalNative/RemoteWindow.cpp b/src/CardinalNative/RemoteWindow.cpp new file mode 120000 index 00000000..7e00fed5 --- /dev/null +++ b/src/CardinalNative/RemoteWindow.cpp @@ -0,0 +1 @@ +../custom/RemoteWindow.cpp \ No newline at end of file diff --git a/src/CardinalNative/Window.cpp b/src/CardinalNative/Window.cpp new file mode 120000 index 00000000..759f2728 --- /dev/null +++ b/src/CardinalNative/Window.cpp @@ -0,0 +1 @@ +../override/Window.cpp \ No newline at end of file diff --git a/src/CardinalNative/common.cpp b/src/CardinalNative/common.cpp new file mode 120000 index 00000000..915948e3 --- /dev/null +++ b/src/CardinalNative/common.cpp @@ -0,0 +1 @@ +../override/common.cpp \ No newline at end of file diff --git a/src/CardinalNative/glfw.cpp b/src/CardinalNative/glfw.cpp new file mode 120000 index 00000000..8c6a6e44 --- /dev/null +++ b/src/CardinalNative/glfw.cpp @@ -0,0 +1 @@ +../custom/glfw.cpp \ No newline at end of file diff --git a/src/CardinalPlugin.cpp b/src/CardinalPlugin.cpp index 80514052..d7e6f750 100644 --- a/src/CardinalPlugin.cpp +++ b/src/CardinalPlugin.cpp @@ -34,24 +34,38 @@ # undef DEBUG #endif -#ifdef HAVE_LIBLO -# ifdef HEADLESS -# include -# include "extra/Thread.hpp" -# endif -# include "CardinalCommon.hpp" +#if defined(HAVE_LIBLO) && defined(HEADLESS) +# include +# include "extra/Thread.hpp" #endif #include +#include "CardinalCommon.hpp" #include "DistrhoPluginUtils.hpp" #include "PluginContext.hpp" #include "extra/Base64.hpp" -#include "extra/SharedResourcePointer.hpp" + +#ifdef DISTRHO_OS_WASM +# include +#else +# include "extra/SharedResourcePointer.hpp" +#endif + +#if CARDINAL_VARIANT_FX +# define CARDINAL_TEMPLATE_NAME "init/fx.vcv" +#elif CARDINAL_VARIANT_NATIVE +# define CARDINAL_TEMPLATE_NAME "init/native.vcv" +#elif CARDINAL_VARIANT_SYNTH +# define CARDINAL_TEMPLATE_NAME "init/synth.vcv" +#else +# define CARDINAL_TEMPLATE_NAME "init/main.vcv" +#endif static const constexpr uint kCardinalStateBaseCount = 3; // patch, screenshot, comment #ifndef HEADLESS +# include "extra/ScopedValueSetter.hpp" # include "WindowParameters.hpp" static const constexpr uint kCardinalStateCount = kCardinalStateBaseCount + 2; // moduleInfos, windowSize #else @@ -59,28 +73,77 @@ static const constexpr uint kCardinalStateCount = kCardinalStateBaseCount + 2; / static const constexpr uint kCardinalStateCount = kCardinalStateBaseCount; #endif -#if CARDINAL_VARIANT_FX -# define CARDINAL_TEMPLATE_NAME "template-fx.vcv" -#elif CARDINAL_VARIANT_SYNTH -# define CARDINAL_TEMPLATE_NAME "template-synth.vcv" -#else -# define CARDINAL_TEMPLATE_NAME "template.vcv" -#endif - namespace rack { +namespace asset { +std::string patchesPath(); +void destroy(); +} +namespace engine { +void Engine_setAboutToClose(Engine*); +} namespace plugin { - void initStaticPlugins(); - void destroyStaticPlugins(); +void initStaticPlugins(); +void destroyStaticPlugins(); } #ifndef HEADLESS namespace window { - void WindowInit(Window* window, DISTRHO_NAMESPACE::Plugin* plugin); +void WindowInit(Window* window, DISTRHO_NAMESPACE::Plugin* plugin); } #endif } START_NAMESPACE_DISTRHO +template +static inline +bool d_isDiffHigherThanLimit(const T& v1, const T& v2, const T& limit) +{ + return v1 != v2 ? (v1 > v2 ? v1 - v2 : v2 - v1) > limit : false; +} + +// ----------------------------------------------------------------------------------------------------------- + +#ifdef DISTRHO_OS_WASM +static char* getPatchFileEncodedInURL() { + return static_cast(EM_ASM_PTR({ + var searchParams = new URLSearchParams(window.location.search); + var patch = searchParams.get('patch'); + if (!patch) + return null; + var length = lengthBytesUTF8(patch) + 1; + var str = _malloc(length); + stringToUTF8(patch, str, length); + return str; + })); +}; + +static char* getPatchRemoteURL() { + return static_cast(EM_ASM_PTR({ + var searchParams = new URLSearchParams(window.location.search); + var patch = searchParams.get('patchurl'); + if (!patch) + return null; + var length = lengthBytesUTF8(patch) + 1; + var str = _malloc(length); + stringToUTF8(patch, str, length); + return str; + })); +}; + +static char* getPatchStorageSlug() { + return static_cast(EM_ASM_PTR({ + var searchParams = new URLSearchParams(window.location.search); + var patch = searchParams.get('patchstorage'); + if (!patch) + return null; + var length = lengthBytesUTF8(patch) + 1; + var str = _malloc(length); + stringToUTF8(patch, str, length); + return str; + })); +}; +#endif + // ----------------------------------------------------------------------------------------------------------- struct Initializer @@ -93,16 +156,20 @@ struct Initializer CardinalBasePlugin* oscPlugin = nullptr; #endif std::string templatePath; + std::string factoryTemplatePath; Initializer(const CardinalBasePlugin* const plugin) { using namespace rack; +#ifdef DISTRHO_OS_WASM + settings::allowCursorLock = true; +#else settings::allowCursorLock = false; +#endif settings::autoCheckUpdates = false; settings::autosaveInterval = 0; settings::devMode = true; - settings::discordUpdateActivity = false; settings::isPlugin = true; settings::skipLoadOnLaunch = true; settings::showTipsOnLaunch = false; @@ -142,27 +209,25 @@ struct Initializer { if (const char* const resourcePath = getResourcePath(bundlePath)) { - asset::bundlePath = system::join(resourcePath, "PluginManifests"); asset::systemDir = resourcePath; - templatePath = system::join(asset::systemDir, CARDINAL_TEMPLATE_NAME); + asset::bundlePath = system::join(asset::systemDir, "PluginManifests"); } } - if (asset::systemDir.empty() || ! system::exists(asset::systemDir)) + if (asset::systemDir.empty() || ! system::exists(asset::systemDir) || ! system::exists(asset::bundlePath)) { #ifdef CARDINAL_PLUGIN_SOURCE_DIR // Make system dir point to source code location as fallback asset::systemDir = CARDINAL_PLUGIN_SOURCE_DIR DISTRHO_OS_SEP_STR "Rack"; + asset::bundlePath.clear(); - if (system::exists(system::join(asset::systemDir, "res"))) - { - templatePath = CARDINAL_PLUGIN_SOURCE_DIR DISTRHO_OS_SEP_STR CARDINAL_TEMPLATE_NAME; - } // If source code dir does not exist use install target prefix as system dir - else + if (!system::exists(system::join(asset::systemDir, "res"))) #endif { - #if defined(ARCH_MAC) + #if defined(DISTRHO_OS_WASM) + asset::systemDir = "/resources"; + #elif defined(ARCH_MAC) asset::systemDir = "/Library/Application Support/Cardinal"; #elif defined(ARCH_WIN) const std::string commonprogfiles = getSpecialPath(kSpecialPathCommonProgramFiles); @@ -172,17 +237,21 @@ struct Initializer asset::systemDir = CARDINAL_PLUGIN_PREFIX "/share/cardinal"; #endif - if (! asset::systemDir.empty()) - { - asset::bundlePath = system::join(asset::systemDir, "PluginManifests"); - templatePath = system::join(asset::systemDir, CARDINAL_TEMPLATE_NAME); - } + asset::bundlePath = system::join(asset::systemDir, "PluginManifests"); } } asset::userDir = asset::systemDir; } + const std::string patchesPath = asset::patchesPath(); + #ifdef DISTRHO_OS_WASM + templatePath = system::join(patchesPath, CARDINAL_WASM_WELCOME_TEMPLATE_FILENAME); + #else + templatePath = system::join(patchesPath, CARDINAL_TEMPLATE_NAME); + #endif + factoryTemplatePath = system::join(patchesPath, CARDINAL_TEMPLATE_NAME); + // Log environment INFO("%s %s v%s", APP_NAME.c_str(), APP_EDITION.c_str(), APP_VERSION.c_str()); INFO("%s", system::getOperatingSystemInfo().c_str()); @@ -191,6 +260,7 @@ struct Initializer INFO("System directory: %s", asset::systemDir.c_str()); INFO("User directory: %s", asset::userDir.c_str()); INFO("Template patch: %s", templatePath.c_str()); + INFO("System template patch: %s", factoryTemplatePath.c_str()); // Report to user if something is wrong with the installation if (asset::systemDir.empty()) @@ -248,6 +318,12 @@ struct Initializer INFO("Destroying plugins"); plugin::destroyStaticPlugins(); + INFO("Destroying colourized assets"); + asset::destroy(); + + INFO("Destroying settings"); + settings::destroy(); + INFO("Destroying logger"); logger::destroy(); } @@ -438,7 +514,11 @@ struct ScopedContext { class CardinalPlugin : public CardinalBasePlugin { + #ifdef DISTRHO_OS_WASM + ScopedPointer fInitializer; + #else SharedResourcePointer fInitializer; + #endif #if DISTRHO_PLUGIN_NUM_INPUTS != 0 /* If host audio ins == outs we can get issues for inplace processing. @@ -448,7 +528,7 @@ class CardinalPlugin : public CardinalBasePlugin #endif std::string fAutosavePath; - uint64_t fPreviousFrame; + uint64_t fNextExpectedFrame; struct { String comment; @@ -470,11 +550,15 @@ class CardinalPlugin : public CardinalBasePlugin public: CardinalPlugin() : CardinalBasePlugin(kModuleParameters + kWindowParameterCount + 1, 0, kCardinalStateCount), + #ifdef DISTRHO_OS_WASM + fInitializer(new Initializer(this)), + #else fInitializer(this), + #endif #if DISTRHO_PLUGIN_NUM_INPUTS != 0 fAudioBufferCopy(nullptr), #endif - fPreviousFrame(0), + fNextExpectedFrame(0), fWasBypassed(false) { #ifndef HEADLESS @@ -491,6 +575,7 @@ class CardinalPlugin : public CardinalBasePlugin fWindowParameters[kWindowParameterBrowserSort] = 3.0f; fWindowParameters[kWindowParameterBrowserZoom] = 50.0f; fWindowParameters[kWindowParameterInvertZoom] = 0.0f; + fWindowParameters[kWindowParameterSqueezeModulePositions] = 1.0f; #endif // create unique temporary path for this instance @@ -537,6 +622,7 @@ class CardinalPlugin : public CardinalBasePlugin context->patch = new rack::patch::Manager; context->patch->autosavePath = fAutosavePath; context->patch->templatePath = fInitializer->templatePath; + context->patch->factoryTemplatePath = fInitializer->factoryTemplatePath; context->event = new rack::widget::EventState; context->scene = new rack::app::Scene; @@ -545,23 +631,38 @@ class CardinalPlugin : public CardinalBasePlugin if (! isDummyInstance()) context->window = new rack::window::Window; - context->patch->loadTemplate(); - context->scene->rackScroll->reset(); + #ifdef DISTRHO_OS_WASM + if ((rack::patchStorageSlug = getPatchStorageSlug()) == nullptr && + (rack::patchRemoteURL = getPatchRemoteURL()) == nullptr && + (rack::patchFromURL = getPatchFileEncodedInURL()) == nullptr) + #endif + { + context->patch->loadTemplate(); + context->scene->rackScroll->reset(); + // swap to factory template after first load + context->patch->templatePath = context->patch->factoryTemplatePath; + } -#if defined(HAVE_LIBLO) && defined(HEADLESS) + #if defined(HAVE_LIBLO) && defined(HEADLESS) fInitializer->oscPlugin = this; -#endif + #endif } ~CardinalPlugin() override { -#if defined(HAVE_LIBLO) && defined(HEADLESS) + #if defined(HAVE_LIBLO) && defined(HEADLESS) fInitializer->oscPlugin = nullptr; -#endif + #endif { const ScopedContext sc(this); context->patch->clear(); + + // do a little dance to prevent context scene deletion from saving to temp dir + #ifndef HEADLESS + const ScopedValueSetter svs(rack::settings::headless, true); + #endif + Engine_setAboutToClose(context->engine); delete context; } @@ -611,12 +712,12 @@ class CardinalPlugin : public CardinalBasePlugin uint32_t getVersion() const override { - return d_version(0, 22, 4); + return d_version(0, 22, 9); } int64_t getUniqueId() const override { - #if CARDINAL_VARIANT_MAIN + #if CARDINAL_VARIANT_MAIN || CARDINAL_VARIANT_NATIVE return d_cconst('d', 'C', 'd', 'n'); #elif CARDINAL_VARIANT_FX return d_cconst('d', 'C', 'n', 'F'); @@ -632,15 +733,49 @@ class CardinalPlugin : public CardinalBasePlugin void initAudioPort(const bool input, uint32_t index, AudioPort& port) override { - if (index >= 8) + #if CARDINAL_VARIANT_MAIN + if (index < 8) + { + port.groupId = index / 2; + } + else { port.hints = kAudioPortIsCV | kCVPortHasPositiveUnipolarRange | kCVPortHasScaledRange; index -= 8; } + #elif CARDINAL_VARIANT_FX || CARDINAL_VARIANT_NATIVE || CARDINAL_VARIANT_SYNTH + if (index < 2) + port.groupId = kPortGroupStereo; + #endif CardinalBasePlugin::initAudioPort(input, index, port); } + #if CARDINAL_VARIANT_MAIN + void initPortGroup(const uint32_t index, PortGroup& portGroup) override + { + switch (index) + { + case 0: + portGroup.name = "Audio 1+2"; + portGroup.symbol = "audio_1_and_2"; + break; + case 1: + portGroup.name = "Audio 3+4"; + portGroup.symbol = "audio_3_and_4"; + break; + case 2: + portGroup.name = "Audio 5+6"; + portGroup.symbol = "audio_5_and_6"; + break; + case 3: + portGroup.name = "Audio 7+8"; + portGroup.symbol = "audio_7_and_8"; + break; + } + } + #endif + void initParameter(const uint32_t index, Parameter& parameter) override { if (index < kModuleParameters) @@ -825,6 +960,14 @@ class CardinalPlugin : public CardinalBasePlugin parameter.ranges.min = 0.0f; parameter.ranges.max = 1.0f; break; + case kWindowParameterSqueezeModulePositions: + parameter.name = "Auto-squeeze module positions"; + parameter.symbol = "squeezeModules"; + parameter.hints = kParameterIsAutomatable|kParameterIsInteger|kParameterIsBoolean; + parameter.ranges.def = 1.0f; + parameter.ranges.min = 0.0f; + parameter.ranges.max = 1.0f; + break; } #endif } @@ -1057,11 +1200,29 @@ class CardinalPlugin : public CardinalBasePlugin const std::vector data(d_getChunkFromBase64String(value)); + DISTRHO_SAFE_ASSERT_RETURN(data.size() >= 4,); + const ScopedContext sc(this); rack::system::removeRecursively(fAutosavePath); rack::system::createDirectories(fAutosavePath); - rack::system::unarchiveToDirectory(data, fAutosavePath); + + static constexpr const char zstdMagic[] = "\x28\xb5\x2f\xfd"; + + if (std::memcmp(data.data(), zstdMagic, sizeof(zstdMagic)) != 0) + { + FILE* const f = std::fopen(rack::system::join(fAutosavePath, "patch.json").c_str(), "w"); + DISTRHO_SAFE_ASSERT_RETURN(f != nullptr,); + + std::fwrite(data.data(), data.size(), 1, f); + std::fclose(f); + } + else + { + try { + rack::system::unarchiveToDirectory(data, fAutosavePath); + } DISTRHO_SAFE_EXCEPTION_RETURN("setState unarchiveToDirectory",); + } try { context->patch->loadAutosave(); @@ -1075,14 +1236,15 @@ class CardinalPlugin : public CardinalBasePlugin void activate() override { + context->bufferSize = getBufferSize(); + #if DISTRHO_PLUGIN_NUM_INPUTS != 0 - const uint32_t bufferSize = getBufferSize(); fAudioBufferCopy = new float*[DISTRHO_PLUGIN_NUM_INPUTS]; for (int i=0; ibufferSize]; #endif - fPreviousFrame = 0; + fNextExpectedFrame = 0; } void deactivate() override @@ -1108,7 +1270,7 @@ class CardinalPlugin : public CardinalBasePlugin { const TimePosition& timePos(getTimePosition()); - const bool reset = timePos.playing && (timePos.frame == 0 || fPreviousFrame + frames != timePos.frame); + const bool reset = timePos.playing && (timePos.frame == 0 || d_isDiffHigherThanLimit(fNextExpectedFrame, timePos.frame, (uint64_t)2)); context->playing = timePos.playing; context->bbtValid = timePos.bbt.valid; @@ -1133,7 +1295,7 @@ class CardinalPlugin : public CardinalBasePlugin } context->reset = reset; - fPreviousFrame = timePos.frame; + fNextExpectedFrame = timePos.playing ? timePos.frame + frames : 0; } // separate buffers, use them @@ -1147,7 +1309,13 @@ class CardinalPlugin : public CardinalBasePlugin { #if DISTRHO_PLUGIN_NUM_INPUTS != 0 for (int i=0; idataIns = fAudioBufferCopy; #else context->dataIns = nullptr; @@ -1156,7 +1324,13 @@ class CardinalPlugin : public CardinalBasePlugin } for (int i=0; ibufferSize = newBufferSize; - } - void sampleRateChanged(const double newSampleRate) override { rack::contextSet(context); diff --git a/src/CardinalRemote/CardinalCommon.cpp b/src/CardinalRemote/CardinalCommon.cpp new file mode 120000 index 00000000..76b4b5f3 --- /dev/null +++ b/src/CardinalRemote/CardinalCommon.cpp @@ -0,0 +1 @@ +../CardinalCommon.cpp \ No newline at end of file diff --git a/src/CardinalRemote/DistrhoPluginInfo.h b/src/CardinalRemote/DistrhoPluginInfo.h new file mode 120000 index 00000000..8c390222 --- /dev/null +++ b/src/CardinalRemote/DistrhoPluginInfo.h @@ -0,0 +1 @@ +../Cardinal/DistrhoPluginInfo.h \ No newline at end of file diff --git a/src/CardinalRemote/Makefile b/src/CardinalRemote/Makefile new file mode 100644 index 00000000..8c0666f1 --- /dev/null +++ b/src/CardinalRemote/Makefile @@ -0,0 +1,292 @@ +#!/usr/bin/make -f +# Makefile for DISTRHO Plugins # +# ---------------------------- # +# Created by falkTX +# + +# -------------------------------------------------------------- +# Carla stuff + +CWD = ../../carla/source +STATIC_PLUGIN_TARGET = true +include $(CWD)/Makefile.deps.mk + +CARLA_BUILD_DIR = ../../carla/build +ifeq ($(DEBUG),true) +CARLA_BUILD_TYPE = Debug +else +CARLA_BUILD_TYPE = Release +endif + +CARLA_EXTRA_LIBS = $(CARLA_BUILD_DIR)/plugin/$(CARLA_BUILD_TYPE)/carla-host-plugin.cpp.o +CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/carla_engine_plugin.a +CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/carla_plugin.a +CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/native-plugins.a +CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/audio_decoder.a +CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/jackbridge.min.a +CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/lilv.a +CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/rtmempool.a +CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/sfzero.a +CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/water.a +CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/ysfx.a +CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/zita-resampler.a + +# -------------------------------------------------------------- +# Import base definitions + +USE_NANOVG_FBO = true +include ../../dpf/Makefile.base.mk + +# -------------------------------------------------------------- +# Build config + +PREFIX ?= /usr/local + +ifeq ($(BSD),true) +SYSDEPS ?= true +else +SYSDEPS ?= false +endif + +ifeq ($(SYSDEPS),true) +DEP_LIB_PATH = $(abspath ../../deps/sysroot/lib) +else +DEP_LIB_PATH = $(abspath ../Rack/dep/lib) +endif + +# -------------------------------------------------------------- +# Extra libraries to link against + +RACK_EXTRA_LIBS = ../../plugins/plugins.a +RACK_EXTRA_LIBS += ../rack.a +RACK_EXTRA_LIBS += $(DEP_LIB_PATH)/libquickjs.a + +ifneq ($(SYSDEPS),true) +RACK_EXTRA_LIBS += $(DEP_LIB_PATH)/libjansson.a +RACK_EXTRA_LIBS += $(DEP_LIB_PATH)/libsamplerate.a +RACK_EXTRA_LIBS += $(DEP_LIB_PATH)/libspeexdsp.a +ifeq ($(WINDOWS),true) +RACK_EXTRA_LIBS += $(DEP_LIB_PATH)/libarchive_static.a +else +RACK_EXTRA_LIBS += $(DEP_LIB_PATH)/libarchive.a +endif +RACK_EXTRA_LIBS += $(DEP_LIB_PATH)/libzstd.a +endif + +# -------------------------------------------------------------- + +EXTRA_DEPENDENCIES = $(RACK_EXTRA_LIBS) $(CARLA_EXTRA_LIBS) +EXTRA_LIBS = $(RACK_EXTRA_LIBS) $(CARLA_EXTRA_LIBS) $(STATIC_CARLA_PLUGIN_LIBS) + +ifeq ($(shell pkg-config --exists fftw3f && echo true),true) +EXTRA_DEPENDENCIES += ../../deps/aubio/libaubio.a +EXTRA_LIBS += ../../deps/aubio/libaubio.a +EXTRA_LIBS += $(shell $(PKG_CONFIG) --libs fftw3f) +endif + +# -------------------------------------------------------------- +# Extra flags for liblo + +BASE_FLAGS += -DHAVE_LIBLO +BASE_FLAGS += $(LIBLO_FLAGS) +LINK_FLAGS += $(LIBLO_LIBS) + +# -------------------------------------------------------------- +# Extra flags for VCV stuff + +ifeq ($(MACOS),true) +BASE_FLAGS += -DARCH_MAC +else ifeq ($(WINDOWS),true) +BASE_FLAGS += -DARCH_WIN +else +BASE_FLAGS += -DARCH_LIN +endif + +BASE_FLAGS += -DPRIVATE= +BASE_FLAGS += -I.. +BASE_FLAGS += -I../../dpf/dgl/src/nanovg +BASE_FLAGS += -I../../include +BASE_FLAGS += -I../../include/neon-compat +BASE_FLAGS += -I../Rack/include +ifeq ($(SYSDEPS),true) +BASE_FLAGS += -DCARDINAL_SYSDEPS +BASE_FLAGS += $(shell pkg-config --cflags jansson libarchive samplerate speexdsp) +else +BASE_FLAGS += -DZSTDLIB_VISIBILITY= +BASE_FLAGS += -I../Rack/dep/include +endif +BASE_FLAGS += -I../Rack/dep/glfw/include +BASE_FLAGS += -I../Rack/dep/nanosvg/src +BASE_FLAGS += -I../Rack/dep/oui-blendish + +ifeq ($(WASM),true) +BASE_FLAGS += -DNANOVG_GLES2=1 +BASE_FLAGS += -msse -msse2 -msse3 -msimd128 +else ifneq ($(HAIKU),true) +BASE_FLAGS += -pthread +endif + +ifeq ($(WINDOWS),true) +BASE_FLAGS += -D_USE_MATH_DEFINES +BASE_FLAGS += -DWIN32_LEAN_AND_MEAN +BASE_FLAGS += -I../../include/mingw-compat +BASE_FLAGS += -I../../include/mingw-std-threads +endif + +BUILD_C_FLAGS += -std=gnu11 +BUILD_C_FLAGS += -fno-finite-math-only -fno-strict-aliasing +BUILD_CXX_FLAGS += -fno-finite-math-only -fno-strict-aliasing + +ifneq ($(MACOS),true) +BUILD_CXX_FLAGS += -faligned-new -Wno-abi +endif + +# Rack code is not tested for this flag, unset it +BUILD_CXX_FLAGS += -U_GLIBCXX_ASSERTIONS -Wp,-U_GLIBCXX_ASSERTIONS + +# -------------------------------------------------------------- +# FIXME lots of warnings from VCV side + +BASE_FLAGS += -Wno-unused-parameter +BASE_FLAGS += -Wno-unused-variable + +# -------------------------------------------------------------- +# extra linker flags + +ifeq ($(HAIKU),true) +LINK_FLAGS += -lpthread +else +LINK_FLAGS += -pthread +endif + +ifneq ($(HAIKU_OR_MACOS_OR_WINDOWS),true) +ifneq ($(STATIC_BUILD),true) +LINK_FLAGS += -ldl +endif +endif + +ifeq ($(BSD),true) +ifeq ($(DEBUG),true) +LINK_FLAGS += -lexecinfo +endif +endif + +ifeq ($(MACOS),true) +LINK_FLAGS += -framework IOKit +else ifeq ($(WINDOWS),true) +# needed by VCVRack +EXTRA_LIBS += -ldbghelp -lshlwapi -Wl,--stack,0x100000 +# needed by JW-Modules +EXTRA_LIBS += -lws2_32 -lwinmm +endif + +ifeq ($(SYSDEPS),true) +EXTRA_LIBS += $(shell pkg-config --libs jansson libarchive samplerate speexdsp) +endif + +ifeq ($(WITH_LTO),true) +# false positive +LINK_FLAGS += -Wno-alloc-size-larger-than +ifneq ($(SYSDEPS),true) +# triggered by jansson +LINK_FLAGS += -Wno-stringop-overflow +endif +endif + +# -------------------------------------------------------------- +# fallback path to resource files + +ifneq ($(CIBUILD),true) +ifneq ($(SYSDEPS),true) + +ifeq ($(EXE_WRAPPER),wine) +SOURCE_DIR = Z:$(subst /,\\,$(abspath $(CURDIR)/..)) +else +SOURCE_DIR = $(abspath $(CURDIR)/..) +endif + +BUILD_CXX_FLAGS += -DCARDINAL_PLUGIN_SOURCE_DIR='"$(SOURCE_DIR)"' + +endif +endif + +# -------------------------------------------------------------- +# install path prefix for resource files + +BUILD_CXX_FLAGS += -DCARDINAL_PLUGIN_PREFIX='"$(PREFIX)"' + +# -------------------------------------------------------------- +# Files to build + +FILES = main.cpp +FILES += RemoteUI.cpp +FILES += CardinalCommon.cpp +FILES += common.cpp +FILES += glfw.cpp +FILES += Window.cpp + +ifeq ($(WINDOWS),true) +FILES += distrho.rc +endif + +# -------------------------------------------------------------- +# Build setup + +TARGET_DIR = ../../bin +BUILD_DIR = ../../build/CardinalRemote +DPF_PATH = ../../dpf + +DGL_FLAGS += -DDGL_OPENGL -DHAVE_DGL +DGL_FLAGS += $(OPENGL_FLAGS) +DGL_LIBS += $(OPENGL_LIBS) +DGL_LIBS += $(DGL_SYSTEM_LIBS) -lm +DGL_LIB = $(DPF_PATH)/build/libdgl-opengl.a + +BUILD_C_FLAGS += -I. +BUILD_CXX_FLAGS += -I. -I$(DPF_PATH)/distrho -I$(DPF_PATH)/dgl + +OBJS = $(FILES:%=$(BUILD_DIR)/%.o) + +all: $(TARGET_DIR)/CardinalRemote$(APP_EXT) + +# --------------------------------------------------------------------------------------------------------------------- + +$(TARGET_DIR)/CardinalRemote$(APP_EXT): $(OBJS) $(DGL_LIB) + -@mkdir -p $(shell dirname $@) + @echo "Linking CardinalRemote" + $(SILENT)$(CXX) $^ $(BUILD_CXX_FLAGS) $(LINK_FLAGS) $(EXTRA_LIBS) $(DGL_LIBS) $(JACK_LIBS) -o $@ + +# --------------------------------------------------------------------------------------------------------------------- +# Common + +$(BUILD_DIR)/%.S.o: %.S + -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" + @echo "Compiling $<" + @$(CC) $< $(BUILD_C_FLAGS) -c -o $@ + +$(BUILD_DIR)/%.c.o: %.c + -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" + @echo "Compiling $<" + $(SILENT)$(CC) $< $(BUILD_C_FLAGS) -c -o $@ + +$(BUILD_DIR)/%.cc.o: %.cc + -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" + @echo "Compiling $<" + $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -c -o $@ + +$(BUILD_DIR)/%.cpp.o: %.cpp + -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" + @echo "Compiling $<" + $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -c -o $@ + +# -------------------------------------------------------------- +# Extra rules for Windows icon + +ifeq ($(WINDOWS),true) +JACK_LIBS += -Wl,-subsystem,windows + +$(BUILD_DIR)/distrho.rc.o: ../../utils/distrho.rc ../../utils/distrho.ico + -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" + @echo "Compiling distrho.rc" + $(SILENT)$(WINDRES) $< -O coff -o $@ +endif diff --git a/src/CardinalRemote/RemoteUI.cpp b/src/CardinalRemote/RemoteUI.cpp new file mode 100644 index 00000000..1295f13c --- /dev/null +++ b/src/CardinalRemote/RemoteUI.cpp @@ -0,0 +1,91 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +#include "RemoteUI.hpp" + +// #include +// #include +#include +#include +#include + +#include +#include + +CardinalRemoteUI::CardinalRemoteUI(Window& window, const std::string& templatePath) + : NanoTopLevelWidget(window), + context(nullptr) +{ + // create unique temporary path for this instance + try { + char uidBuf[24]; + const std::string tmp = rack::system::getTempDirectory(); + + for (int i=1;; ++i) + { + std::snprintf(uidBuf, sizeof(uidBuf), "CardinalRemote.%04d", i); + const std::string trypath = rack::system::join(tmp, uidBuf); + + if (! rack::system::exists(trypath)) + { + if (rack::system::createDirectories(trypath)) + autosavePath = trypath; + break; + } + } + } DISTRHO_SAFE_EXCEPTION("create unique temporary path"); + + rack::contextSet(&context); + + context.bufferSize = 512; + rack::settings::sampleRate = context.sampleRate = 48000; + + context.engine = new rack::engine::Engine; + context.engine->setSampleRate(context.sampleRate); + + context.history = new rack::history::State; + context.patch = new rack::patch::Manager; + context.patch->autosavePath = autosavePath; + context.patch->templatePath = templatePath; + + context.event = new rack::widget::EventState; + context.scene = new rack::app::Scene; + context.event->rootWidget = context.scene; + context.window = new rack::window::Window; + + context.patch->loadTemplate(); + context.scene->rackScroll->reset(); + + context.nativeWindowId = getWindow().getNativeWindowHandle(); +} + +CardinalRemoteUI::~CardinalRemoteUI() +{ + rack::contextSet(&context); + + context.nativeWindowId = 0; + context.patch->clear(); + + if (! autosavePath.empty()) + rack::system::removeRecursively(autosavePath); +} + +void CardinalRemoteUI::onNanoDisplay() +{ + rack::contextSet(&context); + context.window->step(); +} diff --git a/src/CardinalRemote/RemoteUI.hpp b/src/CardinalRemote/RemoteUI.hpp new file mode 100644 index 00000000..1ed46965 --- /dev/null +++ b/src/CardinalRemote/RemoteUI.hpp @@ -0,0 +1,36 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +#pragma once + +#include "NanoVG.hpp" +#include "PluginContext.hpp" + +class CardinalRemoteUI : public NanoTopLevelWidget +{ + CardinalPluginContext context; + std::string autosavePath; + +public: + explicit CardinalRemoteUI(Window& window, const std::string& templatePath); + ~CardinalRemoteUI() override; + +protected: + void onNanoDisplay() override; + + DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CardinalRemoteUI) +}; diff --git a/src/CardinalRemote/Window.cpp b/src/CardinalRemote/Window.cpp new file mode 120000 index 00000000..759f2728 --- /dev/null +++ b/src/CardinalRemote/Window.cpp @@ -0,0 +1 @@ +../override/Window.cpp \ No newline at end of file diff --git a/src/CardinalRemote/common.cpp b/src/CardinalRemote/common.cpp new file mode 120000 index 00000000..915948e3 --- /dev/null +++ b/src/CardinalRemote/common.cpp @@ -0,0 +1 @@ +../override/common.cpp \ No newline at end of file diff --git a/src/CardinalRemote/glfw.cpp b/src/CardinalRemote/glfw.cpp new file mode 120000 index 00000000..8c6a6e44 --- /dev/null +++ b/src/CardinalRemote/glfw.cpp @@ -0,0 +1 @@ +../custom/glfw.cpp \ No newline at end of file diff --git a/src/CardinalRemote/main.cpp b/src/CardinalRemote/main.cpp new file mode 100644 index 00000000..4ac0be22 --- /dev/null +++ b/src/CardinalRemote/main.cpp @@ -0,0 +1,160 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +#include "Application.hpp" +#include "Window.hpp" +#include "RemoteUI.hpp" + +#include +#include +#include +#include + +#include +#include + +namespace rack { +namespace plugin { + void initStaticPlugins(); + void destroyStaticPlugins(); +} +} + +int main(const int argc, const char* argv[]) +{ + using namespace rack; + + settings::allowCursorLock = false; + settings::autoCheckUpdates = false; + settings::autosaveInterval = 0; + settings::devMode = true; + settings::discordUpdateActivity = false; + settings::isPlugin = true; + settings::skipLoadOnLaunch = true; + settings::showTipsOnLaunch = false; + settings::windowPos = math::Vec(0, 0); + + // copied from https://community.vcvrack.com/t/16-colour-cable-palette/15951 + settings::cableColors = { + color::fromHexString("#ff5252"), + color::fromHexString("#ff9352"), + color::fromHexString("#ffd452"), + color::fromHexString("#e8ff52"), + color::fromHexString("#a8ff52"), + color::fromHexString("#67ff52"), + color::fromHexString("#52ff7d"), + color::fromHexString("#52ffbe"), + color::fromHexString("#52ffff"), + color::fromHexString("#52beff"), + color::fromHexString("#527dff"), + color::fromHexString("#6752ff"), + color::fromHexString("#a852ff"), + color::fromHexString("#e952ff"), + color::fromHexString("#ff52d4"), + color::fromHexString("#ff5293"), + }; + + system::init(); + logger::init(); + random::init(); + ui::init(); + + std::string templatePath; + #ifdef CARDINAL_PLUGIN_SOURCE_DIR + // Make system dir point to source code location as fallback + asset::systemDir = CARDINAL_PLUGIN_SOURCE_DIR DISTRHO_OS_SEP_STR "Rack"; + + if (system::exists(system::join(asset::systemDir, "res"))) + { + templatePath = CARDINAL_PLUGIN_SOURCE_DIR DISTRHO_OS_SEP_STR "template.vcv"; + } + // If source code dir does not exist use install target prefix as system dir + else + #endif + { + #if defined(ARCH_MAC) + asset::systemDir = "/Library/Application Support/Cardinal"; + #elif defined(ARCH_WIN) + const std::string commonprogfiles = getSpecialPath(kSpecialPathCommonProgramFiles); + if (! commonprogfiles.empty()) + asset::systemDir = system::join(commonprogfiles, "Cardinal"); + #else + asset::systemDir = CARDINAL_PLUGIN_PREFIX "/share/cardinal"; + #endif + + if (! asset::systemDir.empty()) + { + asset::bundlePath = system::join(asset::systemDir, "PluginManifests"); + templatePath = system::join(asset::systemDir, "template.vcv"); + } + } + + asset::userDir = asset::systemDir; + + // Log environment + INFO("%s %s v%s", APP_NAME.c_str(), APP_EDITION.c_str(), APP_VERSION.c_str()); + INFO("%s", system::getOperatingSystemInfo().c_str()); +// INFO("Binary filename: %s", getBinaryFilename()); + INFO("System directory: %s", asset::systemDir.c_str()); + INFO("User directory: %s", asset::userDir.c_str()); + INFO("Template patch: %s", templatePath.c_str()); + + // Report to user if something is wrong with the installation + if (asset::systemDir.empty()) + { + d_stderr2("Failed to locate Cardinal plugin bundle.\n" + "Install Cardinal with its bundle folder intact and try again."); + } + else if (! system::exists(asset::systemDir)) + { + d_stderr2("System directory \"%s\" does not exist.\n" + "Make sure Cardinal was downloaded and installed correctly.", asset::systemDir.c_str()); + } + + INFO("Initializing plugins"); + plugin::initStaticPlugins(); + + INFO("Initializing plugin browser DB"); + app::browserInit(); + + Application app; + Window win(app); + win.setTitle("CardinalRemote"); + ScopedPointer remoteUI; + + { + remoteUI = new CardinalRemoteUI(win, templatePath); + } + + app.exec(); + + INFO("Clearing asset paths"); + asset::bundlePath.clear(); + asset::systemDir.clear(); + asset::userDir.clear(); + + INFO("Destroying plugins"); + plugin::destroyStaticPlugins(); + + INFO("Destroying settings"); + settings::destroy(); + + INFO("Destroying logger"); + logger::destroy(); + + return 0; +} diff --git a/src/CardinalSynth/DistrhoPluginInfo.h b/src/CardinalSynth/DistrhoPluginInfo.h index 6d4aee12..1d1ac1fc 100644 --- a/src/CardinalSynth/DistrhoPluginInfo.h +++ b/src/CardinalSynth/DistrhoPluginInfo.h @@ -1,6 +1,6 @@ /* * DISTRHO Cardinal Plugin - * Copyright (C) 2021 Filipe Coelho + * Copyright (C) 2021-2022 Filipe Coelho * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -18,9 +18,10 @@ #ifndef DISTRHO_PLUGIN_INFO_H_INCLUDED #define DISTRHO_PLUGIN_INFO_H_INCLUDED -#define CARDINAL_VARIANT_MAIN 0 -#define CARDINAL_VARIANT_FX 0 -#define CARDINAL_VARIANT_SYNTH 1 +#define CARDINAL_VARIANT_MAIN 0 +#define CARDINAL_VARIANT_FX 0 +#define CARDINAL_VARIANT_NATIVE 0 +#define CARDINAL_VARIANT_SYNTH 1 #define CARDINAL_NUM_AUDIO_INPUTS 0 #define CARDINAL_NUM_AUDIO_OUTPUTS 2 @@ -35,8 +36,11 @@ #else #define DISTRHO_PLUGIN_HAS_UI 1 #define DISTRHO_PLUGIN_WANT_DIRECT_ACCESS 1 +#define DISTRHO_UI_FILE_BROWSER 1 #define DISTRHO_UI_USE_NANOVG 1 #define DISTRHO_UI_USER_RESIZABLE 1 +#define DISTRHO_UI_DEFAULT_WIDTH 1228 +#define DISTRHO_UI_DEFAULT_HEIGHT 666 #endif #define DISTRHO_PLUGIN_IS_SYNTH 1 #define DISTRHO_PLUGIN_NUM_INPUTS CARDINAL_NUM_AUDIO_INPUTS diff --git a/src/CardinalSynth/glfw.cpp b/src/CardinalSynth/glfw.cpp new file mode 120000 index 00000000..8c6a6e44 --- /dev/null +++ b/src/CardinalSynth/glfw.cpp @@ -0,0 +1 @@ +../custom/glfw.cpp \ No newline at end of file diff --git a/src/CardinalUI.cpp b/src/CardinalUI.cpp index c7875559..5b1496e2 100644 --- a/src/CardinalUI.cpp +++ b/src/CardinalUI.cpp @@ -30,6 +30,19 @@ #include #include +#ifdef DPF_RUNTIME_TESTING +# include +#endif + +#ifdef DISTRHO_OS_WASM +# include +# include +# include +# include +# include "CardinalCommon.hpp" +# include +#endif + #ifdef NDEBUG # undef DEBUG #endif @@ -39,157 +52,6 @@ #include "PluginContext.hpp" #include "WindowParameters.hpp" -GLFWAPI int glfwGetKeyScancode(int) { return 0; } - -GLFWAPI const char* glfwGetClipboardString(GLFWwindow*) -{ - CardinalPluginContext* const context = static_cast(APP); - DISTRHO_SAFE_ASSERT_RETURN(context != nullptr, nullptr); - DISTRHO_SAFE_ASSERT_RETURN(context->ui != nullptr, nullptr); - - const char* mimeType = nullptr; - size_t dataSize = 0; - - if (const void* const clipboard = context->ui->getClipboard(mimeType, dataSize)) - { - if (mimeType == nullptr || std::strcmp(mimeType, "text/plain") != 0) - return nullptr; - return static_cast(clipboard); - } - - return nullptr; -} - -GLFWAPI void glfwSetClipboardString(GLFWwindow*, const char* const text) -{ - DISTRHO_SAFE_ASSERT_RETURN(text != nullptr,); - - CardinalPluginContext* const context = static_cast(APP); - DISTRHO_SAFE_ASSERT_RETURN(context != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(context->ui != nullptr,); - - context->ui->setClipboard(nullptr, text, std::strlen(text)+1); -} - -GLFWAPI void glfwSetCursor(GLFWwindow*, GLFWcursor* const cursor) -{ - CardinalPluginContext* const context = static_cast(APP); - DISTRHO_SAFE_ASSERT_RETURN(context != nullptr,); - DISTRHO_SAFE_ASSERT_RETURN(context->ui != nullptr,); - - context->ui->setCursor(cursor != nullptr ? kMouseCursorDiagonal : kMouseCursorArrow); -} - -GLFWAPI double glfwGetTime(void) -{ - CardinalPluginContext* const context = static_cast(APP); - DISTRHO_SAFE_ASSERT_RETURN(context != nullptr, 0.0); - DISTRHO_SAFE_ASSERT_RETURN(context->ui != nullptr, 0.0); - - return context->ui->getApp().getTime(); -} - -GLFWAPI const char* glfwGetKeyName(const int key, int) -{ - switch (key) - { - case '\"': return "\""; - case '\'': return "\'"; - case '\\': return "\\"; - case ' ': return " "; - case '!': return "!"; - case '#': return "#"; - case '$': return "$"; - case '%': return "%"; - case '&': return "&"; - case '(': return "("; - case ')': return ")"; - case '*': return "*"; - case '+': return "+"; - case ',': return ","; - case '-': return "-"; - case '.': return "."; - case '/': return "/"; - case '0': return "0"; - case '1': return "1"; - case '2': return "2"; - case '3': return "3"; - case '4': return "4"; - case '5': return "5"; - case '6': return "6"; - case '7': return "7"; - case '8': return "8"; - case '9': return "9"; - case ':': return ":"; - case ';': return ";"; - case '<': return "<"; - case '=': return "="; - case '>': return ">"; - case '?': return "?"; - case '@': return "@"; - /* Rack expects lowercase, forced below - case 'A': return "A"; - case 'B': return "B"; - case 'C': return "C"; - case 'D': return "D"; - case 'E': return "E"; - case 'F': return "F"; - case 'G': return "G"; - case 'H': return "H"; - case 'I': return "I"; - case 'J': return "J"; - case 'K': return "K"; - case 'L': return "L"; - case 'M': return "M"; - case 'N': return "N"; - case 'O': return "O"; - case 'P': return "P"; - case 'Q': return "Q"; - case 'R': return "R"; - case 'S': return "S"; - case 'T': return "T"; - case 'U': return "U"; - case 'V': return "V"; - case 'W': return "W"; - case 'X': return "X"; - case 'Y': return "Y"; - case 'Z': return "Z"; - */ - case '[': return "["; - case ']': return "]"; - case '^': return "^"; - case '_': return "_"; - case '`': return "`"; - case 'a': case 'A': return "a"; - case 'b': case 'B': return "b"; - case 'c': case 'C': return "c"; - case 'd': case 'D': return "d"; - case 'e': case 'E': return "e"; - case 'f': case 'F': return "f"; - case 'g': case 'G': return "g"; - case 'h': case 'H': return "h"; - case 'i': case 'I': return "i"; - case 'j': case 'J': return "j"; - case 'k': case 'K': return "k"; - case 'l': case 'L': return "l"; - case 'm': case 'M': return "m"; - case 'n': case 'N': return "n"; - case 'o': case 'O': return "o"; - case 'p': case 'P': return "p"; - case 'q': case 'Q': return "q"; - case 'r': case 'R': return "r"; - case 's': case 'S': return "s"; - case 't': case 'T': return "t"; - case 'u': case 'U': return "u"; - case 'v': case 'V': return "v"; - case 'w': case 'W': return "w"; - case 'x': case 'X': return "x"; - case 'y': case 'Y': return "y"; - case 'z': case 'Z': return "z"; - default: return nullptr; - } -} - namespace rack { namespace app { widget::Widget* createMenuBar(bool isStandalone); @@ -197,6 +59,7 @@ namespace app { namespace window { void WindowSetPluginUI(Window* window, DISTRHO_NAMESPACE::UI* ui); void WindowSetMods(Window* window, int mods); + void WindowSetInternalSize(rack::window::Window* window, math::Vec size); } } @@ -238,13 +101,216 @@ void handleHostParameterDrag(const CardinalPluginContext* pcontext, uint index, // ----------------------------------------------------------------------------------------------------------- +#ifdef DISTRHO_OS_WASM +struct WasmWelcomeDialog : rack::widget::OpaqueWidget +{ + static const constexpr float margin = 10; + static const constexpr float buttonWidth = 110; + + WasmWelcomeDialog() + { + using rack::ui::Button; + using rack::ui::Label; + using rack::ui::MenuOverlay; + using rack::ui::SequentialLayout; + + box.size = rack::math::Vec(550, 310); + + SequentialLayout* const layout = new SequentialLayout; + layout->box.pos = rack::math::Vec(0, 0); + layout->box.size = box.size; + layout->orientation = SequentialLayout::VERTICAL_ORIENTATION; + layout->margin = rack::math::Vec(margin, margin); + layout->spacing = rack::math::Vec(margin, margin); + layout->wrap = false; + addChild(layout); + + SequentialLayout* const contentLayout = new SequentialLayout; + contentLayout->spacing = rack::math::Vec(margin, margin); + layout->addChild(contentLayout); + + SequentialLayout* const buttonLayout = new SequentialLayout; + buttonLayout->alignment = SequentialLayout::CENTER_ALIGNMENT; + buttonLayout->box.size = box.size; + buttonLayout->spacing = rack::math::Vec(margin, margin); + layout->addChild(buttonLayout); + + Label* const label = new Label; + label->box.size.x = box.size.x - 2*margin; + label->box.size.y = box.size.y - 2*margin - 40; + label->fontSize = 20; + label->text = "" + "Welcome to Cardinal on the Web!\n" + "\n" + "If using mobile/touch devices, please note:\n" + " - Single quick press does simple mouse click\n" + " - Press & move does click & drag action\n" + " - Press & hold does right-click (and opens module browser)\n" + "\n" + "Still a bit experimental, so proceed with caution.\n" + "Have fun!"; + contentLayout->addChild(label); + + struct JoinDiscussionButton : Button { + WasmWelcomeDialog* dialog; + void onAction(const ActionEvent& e) override { + patchUtils::openBrowser("https://github.com/DISTRHO/Cardinal/issues/287"); + dialog->getParent()->requestDelete(); + } + }; + JoinDiscussionButton* const discussionButton = new JoinDiscussionButton; + discussionButton->box.size.x = buttonWidth; + discussionButton->text = "Join discussion"; + discussionButton->dialog = this; + buttonLayout->addChild(discussionButton); + + struct DismissButton : Button { + WasmWelcomeDialog* dialog; + void onAction(const ActionEvent& e) override { + dialog->getParent()->requestDelete(); + } + }; + DismissButton* const dismissButton = new DismissButton; + dismissButton->box.size.x = buttonWidth; + dismissButton->text = "Dismiss"; + dismissButton->dialog = this; + buttonLayout->addChild(dismissButton); + + MenuOverlay* const overlay = new MenuOverlay; + overlay->bgColor = nvgRGBAf(0, 0, 0, 0.33); + overlay->addChild(this); + APP->scene->addChild(overlay); + } + + void step() override + { + OpaqueWidget::step(); + box.pos = parent->box.size.minus(box.size).div(2).round(); + } + + void draw(const DrawArgs& args) override + { + bndMenuBackground(args.vg, 0.0, 0.0, box.size.x, box.size.y, 0); + Widget::draw(args); + } +}; + +struct WasmRemotePatchLoadingDialog : rack::widget::OpaqueWidget +{ + static const constexpr float margin = 10; + + rack::ui::MenuOverlay* overlay; + + WasmRemotePatchLoadingDialog(const bool isFromPatchStorage) + { + using rack::ui::Label; + using rack::ui::MenuOverlay; + using rack::ui::SequentialLayout; + + box.size = rack::math::Vec(300, 40); + + SequentialLayout* const layout = new SequentialLayout; + layout->box.pos = rack::math::Vec(0, 0); + layout->box.size = box.size; + layout->alignment = SequentialLayout::CENTER_ALIGNMENT; + layout->margin = rack::math::Vec(margin, margin); + layout->spacing = rack::math::Vec(margin, margin); + layout->wrap = false; + addChild(layout); + + Label* const label = new Label; + label->box.size.x = box.size.x - 2*margin; + label->box.size.y = box.size.y - 2*margin; + label->fontSize = 16; + label->text = isFromPatchStorage + ? "Loading patch from PatchStorage...\n" + : "Loading remote patch...\n"; + layout->addChild(label); + + overlay = new MenuOverlay; + overlay->bgColor = nvgRGBAf(0, 0, 0, 0.33); + overlay->addChild(this); + APP->scene->addChild(overlay); + } + + void step() override + { + OpaqueWidget::step(); + box.pos = parent->box.size.minus(box.size).div(2).round(); + } + + void draw(const DrawArgs& args) override + { + bndMenuBackground(args.vg, 0.0, 0.0, box.size.x, box.size.y, 0); + Widget::draw(args); + } +}; + +static void downloadRemotePatchFailed(const char* const filename) +{ + d_stdout("downloadRemotePatchFailed %s", filename); + CardinalPluginContext* const context = static_cast(APP); + CardinalBaseUI* const ui = static_cast(context->ui); + + if (ui->psDialog != nullptr) + { + ui->psDialog->overlay->requestDelete(); + ui->psDialog = nullptr; + asyncDialog::create("Failed to fetch remote patch"); + } + + using namespace rack; + context->patch->templatePath = system::join(asset::systemDir, "init/wasm.vcv"); // FIXME + context->patch->loadTemplate(); + context->scene->rackScroll->reset(); +} + +static void downloadRemotePatchSucceeded(const char* const filename) +{ + d_stdout("downloadRemotePatchSucceeded %s | %s", filename, APP->patch->templatePath.c_str()); + CardinalPluginContext* const context = static_cast(APP); + CardinalBaseUI* const ui = static_cast(context->ui); + + ui->psDialog->overlay->requestDelete(); + ui->psDialog = nullptr; + + if (FILE* f = fopen(filename, "r")) + { + uint8_t buf[8] = {}; + fread(buf, 8, 1, f); + d_stdout("read patch %x %x %x %x %x %x %x %x", + buf[0],buf[1],buf[2],buf[3],buf[4],buf[5],buf[6],buf[7]); + fclose(f); + } + + try { + context->patch->load(filename); + } catch (rack::Exception& e) { + const std::string message = rack::string::f("Could not load patch: %s", e.what()); + asyncDialog::create(message.c_str()); + return; + } + + context->scene->rackScroll->reset(); + context->patch->path = ""; + context->history->setSaved(); +} +#endif + +// ----------------------------------------------------------------------------------------------------------- + class CardinalUI : public CardinalBaseUI, public WindowParametersCallback { rack::math::Vec lastMousePos; WindowParameters windowParameters; int rateLimitStep = 0; - bool firstIdle = true; + #ifdef DISTRHO_OS_WASM + int8_t counterForFirstIdlePoint = 0; + #endif + #ifdef DPF_RUNTIME_TESTING + bool inSelfTest = false; + #endif struct ScopedContext { CardinalPluginContext* const context; @@ -268,13 +334,12 @@ class CardinalUI : public CardinalBaseUI, { if (context->window != nullptr) WindowParametersSave(context->window); - rack::contextSet(nullptr); } }; public: CardinalUI() - : CardinalBaseUI(1228, 666) + : CardinalBaseUI(DISTRHO_UI_DEFAULT_WIDTH, DISTRHO_UI_DEFAULT_HEIGHT) { Window& window(getWindow()); @@ -286,7 +351,7 @@ class CardinalUI : public CardinalBaseUI, setGeometryConstraints(648 * scaleFactor, 538 * scaleFactor); if (scaleFactor != 1.0) - setSize(1228 * scaleFactor, 666 * scaleFactor); + setSize(DISTRHO_UI_DEFAULT_WIDTH * scaleFactor, DISTRHO_UI_DEFAULT_HEIGHT * scaleFactor); rack::contextSet(context); @@ -333,6 +398,26 @@ class CardinalUI : public CardinalBaseUI, } } + #ifdef DISTRHO_OS_WASM + if (rack::patchStorageSlug != nullptr) + { + psDialog = new WasmRemotePatchLoadingDialog(true); + } + else if (rack::patchRemoteURL != nullptr) + { + psDialog = new WasmRemotePatchLoadingDialog(false); + } + else if (rack::patchFromURL != nullptr) + { + static_cast(context->plugin)->setState("patch", rack::patchFromURL); + rack::contextSet(context); + } + else + { + new WasmWelcomeDialog(); + } + #endif + context->window->step(); rack::contextSet(nullptr); @@ -368,12 +453,96 @@ class CardinalUI : public CardinalBaseUI, void uiIdle() override { - if (firstIdle) + #ifdef DPF_RUNTIME_TESTING + if (inSelfTest) { - firstIdle = false; - getWindow().focus(); + context->window->step(); + return; } + if (context->plugin->isSelfTestInstance()) + { + inSelfTest = true; + + Application& app(getApp()); + + const ScopedContext sc(this); + + context->patch->clear(); + app.idle(); + + const rack::math::Vec mousePos(getWidth()/2,getHeight()/2); + context->event->handleButton(mousePos, GLFW_MOUSE_BUTTON_LEFT, GLFW_RELEASE, 0x0); + context->event->handleHover(mousePos, rack::math::Vec(0,0)); + app.idle(); + + for (rack::plugin::Plugin* p : rack::plugin::plugins) + { + for (rack::plugin::Model* m : p->models) + { + d_stdout(">>>>>>>>>>>>>>>>> LOADING module %s : %s", p->slug.c_str(), m->slug.c_str()); + rack::engine::Module* const module = m->createModule(); + DISTRHO_SAFE_ASSERT_CONTINUE(module != nullptr); + + rack::CardinalPluginModelHelper* const helper = dynamic_cast(m); + DISTRHO_SAFE_ASSERT_CONTINUE(helper != nullptr); + + d_stdout(">>>>>>>>>>>>>>>>> LOADING moduleWidget %s : %s", p->slug.c_str(), m->slug.c_str()); + rack::app::ModuleWidget* const moduleWidget = helper->createModuleWidget(module); + DISTRHO_SAFE_ASSERT_CONTINUE(moduleWidget != nullptr); + + d_stdout(">>>>>>>>>>>>>>>>> ADDING TO ENGINE %s : %s", p->slug.c_str(), m->slug.c_str()); + context->engine->addModule(module); + + d_stdout(">>>>>>>>>>>>>>>>> ADDING TO RACK VIEW %s : %s", p->slug.c_str(), m->slug.c_str()); + context->scene->rack->addModuleAtMouse(moduleWidget); + + for (int i=5; --i>=0;) + app.idle(); + + d_stdout(">>>>>>>>>>>>>>>>> REMOVING FROM RACK VIEW %s : %s", p->slug.c_str(), m->slug.c_str()); + context->scene->rack->removeModule(moduleWidget); + app.idle(); + + d_stdout(">>>>>>>>>>>>>>>>> DELETING module + moduleWidget %s : %s", p->slug.c_str(), m->slug.c_str()); + delete moduleWidget; + + app.idle(); + } + } + + inSelfTest = false; + } + #endif + + #ifdef DISTRHO_OS_WASM + if (counterForFirstIdlePoint >= 0 && ++counterForFirstIdlePoint == 30) + { + counterForFirstIdlePoint = -1; + + if (rack::patchStorageSlug != nullptr) + { + std::string url("/patchstorage.php?slug="); + url += rack::patchStorageSlug; + std::free(rack::patchStorageSlug); + rack::patchStorageSlug = nullptr; + + emscripten_async_wget(url.c_str(), context->patch->templatePath.c_str(), + downloadRemotePatchSucceeded, downloadRemotePatchFailed); + } + else if (rack::patchRemoteURL != nullptr) + { + std::string url("/patchurl.php?url="); + url += rack::patchRemoteURL; + std::free(rack::patchRemoteURL); + rack::patchRemoteURL = nullptr; + + emscripten_async_wget(url.c_str(), context->patch->templatePath.c_str(), + downloadRemotePatchSucceeded, downloadRemotePatchFailed); + } + } + #endif + if (filebrowserhandle != nullptr && fileBrowserIdle(filebrowserhandle)) { { @@ -461,6 +630,9 @@ class CardinalUI : public CardinalBaseUI, case kWindowParameterInvertZoom: windowParameters.invertZoom = value > 0.5f; break; + case kWindowParameterSqueezeModulePositions: + windowParameters.squeezeModules = value > 0.5f; + break; default: return; } @@ -557,6 +729,9 @@ class CardinalUI : public CardinalBaseUI, case kWindowParameterInvertZoom: windowParameters.invertZoom = value > 0.5f; break; + case kWindowParameterSqueezeModulePositions: + windowParameters.squeezeModules = value > 0.5f; + break; default: return; } @@ -611,40 +786,40 @@ class CardinalUI : public CardinalBaseUI, bool onMouse(const MouseEvent& ev) override { + #ifdef DPF_RUNTIME_TESTING + if (inSelfTest) return false; + #endif + + if (ev.press) + getWindow().focus(); + const int action = ev.press ? GLFW_PRESS : GLFW_RELEASE; - const int mods = glfwMods(ev.mod); + int mods = glfwMods(ev.mod); int button; switch (ev.button) { case 1: button = GLFW_MOUSE_BUTTON_LEFT; break; -#ifdef DISTRHO_OS_MAC case 2: button = GLFW_MOUSE_BUTTON_RIGHT; break; case 3: button = GLFW_MOUSE_BUTTON_MIDDLE; break; -#else - case 2: button = GLFW_MOUSE_BUTTON_MIDDLE; break; - case 3: button = GLFW_MOUSE_BUTTON_RIGHT; break; -#endif default: button = ev.button; break; } - /* - #if defined ARCH_MAC - // Remap Ctrl-left click to right click on Mac + #ifdef DISTRHO_OS_MAC + // Remap Ctrl-left click to right click on macOS if (button == GLFW_MOUSE_BUTTON_LEFT && (mods & RACK_MOD_MASK) == GLFW_MOD_CONTROL) { button = GLFW_MOUSE_BUTTON_RIGHT; mods &= ~GLFW_MOD_CONTROL; } - // Remap Ctrl-shift-left click to middle click on Mac + // Remap Ctrl-shift-left click to middle click on macOS if (button == GLFW_MOUSE_BUTTON_LEFT && (mods & RACK_MOD_MASK) == (GLFW_MOD_CONTROL | GLFW_MOD_SHIFT)) { button = GLFW_MOUSE_BUTTON_MIDDLE; mods &= ~(GLFW_MOD_CONTROL | GLFW_MOD_SHIFT); } - #endif - */ + #endif const ScopedContext sc(this, mods); return context->event->handleButton(lastMousePos, button, action, mods); @@ -652,6 +827,10 @@ class CardinalUI : public CardinalBaseUI, bool onMotion(const MotionEvent& ev) override { + #ifdef DPF_RUNTIME_TESTING + if (inSelfTest) return false; + #endif + const rack::math::Vec mousePos = rack::math::Vec(ev.pos.getX(), ev.pos.getY()).div(getScaleFactor()).round(); const rack::math::Vec mouseDelta = mousePos.minus(lastMousePos); @@ -663,10 +842,12 @@ class CardinalUI : public CardinalBaseUI, bool onScroll(const ScrollEvent& ev) override { + #ifdef DPF_RUNTIME_TESTING + if (inSelfTest) return false; + #endif + rack::math::Vec scrollDelta = rack::math::Vec(ev.delta.getX(), ev.delta.getY()); -#ifdef DISTRHO_OS_MAC - scrollDelta = scrollDelta.mult(10.0); -#else +#ifndef DISTRHO_OS_MAC scrollDelta = scrollDelta.mult(50.0); #endif @@ -677,6 +858,10 @@ class CardinalUI : public CardinalBaseUI, bool onCharacterInput(const CharacterInputEvent& ev) override { + #ifdef DPF_RUNTIME_TESTING + if (inSelfTest) return false; + #endif + if (ev.character < ' ' || ev.character >= kKeyDelete) return false; @@ -687,6 +872,10 @@ class CardinalUI : public CardinalBaseUI, bool onKeyboard(const KeyboardEvent& ev) override { + #ifdef DPF_RUNTIME_TESTING + if (inSelfTest) return false; + #endif + const int action = ev.press ? GLFW_PRESS : GLFW_RELEASE; const int mods = glfwMods(ev.mod); @@ -771,7 +960,7 @@ class CardinalUI : public CardinalBaseUI, UI::onResize(ev); if (context->window != nullptr) - context->window->setSize(rack::math::Vec(ev.size.getWidth(), ev.size.getHeight())); + WindowSetInternalSize(context->window, rack::math::Vec(ev.size.getWidth(), ev.size.getHeight())); const double scaleFactor = getScaleFactor(); char sizeString[64]; @@ -780,14 +969,13 @@ class CardinalUI : public CardinalBaseUI, setState("windowSize", sizeString); } - void uiFocus(const bool focus, const CrossingMode mode) override + void uiFocus(const bool focus, CrossingMode) override { - if (focus) - { - if (mode == kCrossingNormal) - getWindow().focus(); - } - else + #ifdef DPF_RUNTIME_TESTING + if (inSelfTest) return; + #endif + + if (!focus) { const ScopedContext sc(this, 0); context->event->handleLeave(); diff --git a/src/MOD/Cardinal.lv2/Plateau_Reverb.ttl b/src/MOD/Cardinal.lv2/Plateau_Reverb.ttl new file mode 100644 index 00000000..dbb93bbd --- /dev/null +++ b/src/MOD/Cardinal.lv2/Plateau_Reverb.ttl @@ -0,0 +1,96 @@ +@prefix atom: . +@prefix lv2: . +@prefix pset: . +@prefix rdf: . +@prefix rdfs: . +@prefix state: . +@prefix xsd: . + +<> + a pset:Preset ; + lv2:appliesTo ; + lv2:port [ + lv2:symbol "lv2_enabled" ; + pset:value 1.0 + ] , [ + lv2:symbol "param_1" ; + pset:value 3.0 + ] , [ + lv2:symbol "param_10" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_11" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_12" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_13" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_14" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_15" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_16" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_17" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_18" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_19" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_2" ; + pset:value 5.0 + ] , [ + lv2:symbol "param_20" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_21" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_22" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_23" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_24" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_3" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_4" ; + pset:value 5.0 + ] , [ + lv2:symbol "param_5" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_6" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_7" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_8" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_9" ; + pset:value 0.0 + ] ; + state:state [ + "KLUv/QBIXR0AZrOOIiAR9Ly6CNQEzyzK+CwIw5H3QvHuEkY2KVmv3eQESAkA+gOGAIAAjQDTgneRB8Qu8lJbrrWmliuWWrVOOmB3F3ms5RZbrLlXSim3Ere7izyswlRGy6IQGWiCd5FHJ2kVtpgzg3eRh6wQXYWjvICRU3kXebAniVdhZzIRJC94F9HodSSl3H+5+1qsux3OjCoSCgkKH4GkHd0OCNKoOn4dTKnWvarX8t527H/rbodAEquwIzMmtLDCkMLIEIu08uca+9XqU3sn9wDH2n3/at9JO/ulGkmP+PtzLTlz77fc2f9y5U99a+u5d6qdveQl39jtVTgynPQqLGsDL3h31wJC8OGuUFLYLPAq3Mg4LRhDNg104FXYYSZq8zzaJfeWcvfum7e2CkeGd3d3EY1INjUGnyJIUmkBIbjAXLHHVLdvzdl7c0jShjGQiIt4mkysAzSaBw10mAhBAqWe60+JvX+7ZqtwZBiBUPNh5u1Vr1+FZZwJTxSdyVAIVQoZaH1onRiUuWAoEzmSgdbHYSJHMjgQYMBGFkjo4VWY1sdBkFFdFiZG6VTKq7BsMChDIx34yGZiYjbIDCmhhXdl1MAlGwjELhLbsqR/qts3tp6/V73gp3fPseav2h9bzZfFSeWvMfZrdVtvpfdqxdTf7dkzX92Sa5fcHVvtUmIt+evn1Gu2mnn7a/evuf/29Bxbyr//13u9OH36ZQHgVRiazZRwh3EYRqD1oXUiyKbGmUDrQ+t85p0cU6tfat1SBJQIgKeoEVFmAEZGIJowRhA0AOACAJAhIgMSYGAIQCBIYgADQQwBQzIMROgoATAAGCAwQgjB4LBBADT1bxCWZ3XXFUabMDuaLONUf0bQ7TgesmQFW2K0AIC4DIQl6tqRPtTyQ0noFFHLQLAATUPeplJl0koHLuVhRjg4NPbs9Wj4AfakXtrVG9Ad+CrbZ0A7Je11icVN+xCwTDBY4Kno85VOIgGk9RzZ1xnpmiObAcD2we4MScUkfADxZIwmSY1vfFxeBnO2iMzNnVOizhd5nU4xNop8kqWVGCB1KmgvNEkW+hzkks3EyByFzDwFDlF2lniRVMGMMof+Y3EQBeSTGEBSh4gEX4611XB1fbturqxt69SVkxPISckW8aolo/yTNVoJCBspCeshPp+jqj7FYS6yDMBKLRy7IHXc+R+MwTYm+KQQqLmmbcdm0+47HTL1RQKZwQ4vBxDovJ+HmZDDJMrAgYowZEBNGMD3FABjnGbw" ; + "" ; + """Activated by parameters. +1 - Dry Level +2 - Wet Level +3 - Low-Cut +4 - Decay""" ; + ] . diff --git a/src/MOD/Cardinal.lv2/modgui.ttl b/src/MOD/Cardinal.lv2/modgui.ttl new file mode 100644 index 00000000..d3a05e11 --- /dev/null +++ b/src/MOD/Cardinal.lv2/modgui.ttl @@ -0,0 +1,29 @@ +@prefix lv2: . +@prefix mod: . +@prefix modgui: . +@prefix pset: . +@prefix rdfs: . +@prefix state: . + + + lv2:requiredFeature state:loadDefaultState ; + modgui:gui [ + modgui:resourcesDirectory ; + modgui:documentation ; + modgui:iconTemplate ; + modgui:javascript ; + modgui:stylesheet ; + modgui:screenshot ; + modgui:thumbnail ; + ] ; + state:state [ + "" ; + """Welcome to Cardinal. +If this is your first time, make sure to check out the documentation link on the plugin info, have fun!""" ; + ] . + + + a pset:Preset ; + lv2:appliesTo ; + rdfs:label "Plateau Reverb" ; + rdfs:seeAlso . diff --git a/src/MOD/Cardinal.lv2/modgui/distrho.svg b/src/MOD/Cardinal.lv2/modgui/distrho.svg new file mode 100644 index 00000000..30b9d9bc --- /dev/null +++ b/src/MOD/Cardinal.lv2/modgui/distrho.svg @@ -0,0 +1,99 @@ + + + +image/svg+xml + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/MOD/Cardinal.lv2/modgui/icon.html b/src/MOD/Cardinal.lv2/modgui/icon.html new file mode 100644 index 00000000..08259594 --- /dev/null +++ b/src/MOD/Cardinal.lv2/modgui/icon.html @@ -0,0 +1,248 @@ +

+
+
+
+
+
+ +
DISTRHO
Cardinal
+
+ Show Audio + Show CV +
+
+
+
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+
+
+
+ PARAM 1 +
+
+
+ PARAM 2 +
+
+
+ PARAM 3 +
+
+
+ PARAM 4 +
+
+
+ PARAM 5 +
+
+
+ PARAM 6 +
+
+
+ PARAM 7 +
+
+
+ PARAM 8 +
+
+
+ PARAM 9 +
+
+
+ PARAM 10 +
+
+
+ PARAM 11 +
+
+
+ PARAM 12 +
+
+
+ PARAM 13 +
+
+
+ PARAM 14 +
+
+
+ PARAM 15 +
+
+
+ PARAM 16 +
+
+
+ PARAM 17 +
+
+
+ PARAM 18 +
+
+
+ PARAM 19 +
+
+
+ PARAM 20 +
+
+
+ PARAM 21 +
+
+
+ PARAM 22 +
+
+
+ PARAM 23 +
+
+
+ PARAM 24 +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/MOD/Cardinal.lv2/modgui/javascript.js b/src/MOD/Cardinal.lv2/modgui/javascript.js new file mode 100644 index 00000000..cffff383 --- /dev/null +++ b/src/MOD/Cardinal.lv2/modgui/javascript.js @@ -0,0 +1,66 @@ +function (event) { + + function hideAllIfConnectionsPresent() { + if (event.icon.find('.input-connected').length === 0 && event.icon.find('.output-connected').length === 0) + return; + event.icon.find('.mod-pedal-input .mod-audio-input').removeClass('cardinal-expanded'); + event.icon.find('.mod-pedal-output .mod-audio-output').removeClass('cardinal-expanded'); + event.icon.find('.mod-pedal-input .mod-cv-input').removeClass('cardinal-expanded'); + event.icon.find('.mod-pedal-output .mod-cv-output').removeClass('cardinal-expanded'); + event.icon.find('.visibility-audio').text('Show Audio'); + event.icon.find('.visibility-cv').text('Show CV'); + } + + if (event.type == 'start') { + event.data['visibility-audio'] = true; + event.data['visibility-cv'] = true; + event.data['visibility-triggered'] = false; + event.icon.find('.visibility-audio').click(function() { + var visible = event.data['visibility-audio']; + if (visible) { + event.icon.find('.mod-pedal-input .mod-audio-input').addClass('cardinal-expanded'); + event.icon.find('.mod-pedal-output .mod-audio-output').addClass('cardinal-expanded'); + $(this).text('Hide Audio'); + } else { + event.icon.find('.mod-pedal-input .mod-audio-input').removeClass('cardinal-expanded'); + event.icon.find('.mod-pedal-output .mod-audio-output').removeClass('cardinal-expanded'); + $(this).text('Show Audio'); + } + event.data['visibility-audio'] = !visible; + event.data['visibility-triggered'] = true; + }); + event.icon.find('.visibility-cv').click(function() { + var visible = event.data['visibility-cv']; + if (visible) { + event.icon.find('.mod-pedal-input .mod-cv-input').addClass('cardinal-expanded'); + event.icon.find('.mod-pedal-output .mod-cv-output').addClass('cardinal-expanded'); + $(this).text('Hide CV'); + } else { + event.icon.find('.mod-pedal-input .mod-cv-input').removeClass('cardinal-expanded'); + event.icon.find('.mod-pedal-output .mod-cv-output').removeClass('cardinal-expanded'); + $(this).text('Show CV'); + } + event.data['visibility-cv'] = !visible; + }); + return; + } + + if (event.type == 'change') { + if (event.uri === "https://distrho.kx.studio/plugins/cardinal#screenshot") { + if (event.value) { + event.icon.find('.screenshot').css({'background-image':'url(data:image/png;base64,'+event.value+')'}); + event.icon.find('.cardinal-main.mod-pedal .cardinal-patch-comment').hide(); + event.icon.find('.cardinal-main.mod-pedal .cardinal-patch-screeenshot').show(); + } else { + event.icon.find('.cardinal-main.mod-pedal .cardinal-patch-screeenshot').hide(); + event.icon.find('.cardinal-main.mod-pedal .cardinal-patch-comment').show(); + } + // if we got a screenshot without the user ever triggering a visibility change, it is like from PB load + if (!event.data['visibility-triggered']) { + event.data['visibility-triggered'] = true; + setTimeout(hideAllIfConnectionsPresent, 500); + } + } + return; + } +} diff --git a/src/MOD/Cardinal.lv2/modgui/orange-knob.png b/src/MOD/Cardinal.lv2/modgui/orange-knob.png new file mode 100644 index 00000000..2f08b7d9 Binary files /dev/null and b/src/MOD/Cardinal.lv2/modgui/orange-knob.png differ diff --git a/src/MOD/Cardinal.lv2/modgui/screenshot.png b/src/MOD/Cardinal.lv2/modgui/screenshot.png new file mode 100644 index 00000000..ea78bb37 Binary files /dev/null and b/src/MOD/Cardinal.lv2/modgui/screenshot.png differ diff --git a/src/MOD/Cardinal.lv2/modgui/stylesheet.css b/src/MOD/Cardinal.lv2/modgui/stylesheet.css new file mode 100644 index 00000000..6065621e --- /dev/null +++ b/src/MOD/Cardinal.lv2/modgui/stylesheet.css @@ -0,0 +1,230 @@ +/* main pedal */ +.cardinal-main.mod-pedal { + background: #333333; + background: linear-gradient(to bottom, #181919, #333333); + width: 540px; + height: 565px; + font-size: 20px; + margin: 0; + padding: 0; +} +.cardinal-main.mod-pedal .border { + border: 2px solid #4c4d4d; + width: 540px; + height: 565px; + position: absolute; +} + +.cardinal-main.mod-pedal .mod-control-group { + position: relative; + z-index: 35; +} + +/* top and bottom area split */ +.cardinal-main.mod-pedal .cardinal-main-top { + width: 100%; + height: 230px; + position: absolute; + top: 0px; + color: white; +} + +.cardinal-main.mod-pedal .cardinal-main-bottom { + width: 100%; + height: 345px; + position: absolute; + top: 220px; + color: white; +} + +/* top area split */ +.cardinal-main.mod-pedal .cardinal-main-top-left { + width: 190px; + height: 230px; + position: absolute; + top: 0px; + left: 0px; + display: flex; + flex-direction: column; + justify-content: space-around; + text-align: center; +} + +.cardinal-main.mod-pedal .cardinal-main-top-right { + width: 350px; + height: 230px; + position: absolute; + top: 0px; + left: 190px; +} + +.cardinal-main.mod-pedal .cardinal-patch-comment, +.cardinal-main.mod-pedal .cardinal-patch-screeenshot { + width: 340px; + height: 210px; + margin: 10px 10px 10px 0px; +} + +.cardinal-main.mod-pedal .visibility-buttons { + width: 100%; + height: 34px; + font-size: 17px; + display: flex; + align-items: center; + justify-content: space-evenly; + justify-content: space-between; +} + +.cardinal-main.mod-pedal .visibility-buttons span { + cursor: pointer; + background-color: #181919; + border: 2px solid #4c4d4d; + border-radius: 6px; + padding: 1px 4px; +} +.cardinal-main.mod-pedal .visibility-buttons span:hover { + background-color: #333333; +} +.cardinal-main.mod-pedal .visibility-buttons span:first-child { + width: 52%; +} +.cardinal-main.mod-pedal .visibility-buttons span:nth-child(2) { + width: 40%; +} + +.cardinal-main.mod-pedal .cardinal-main-knobs { + margin: 10px; + display: flex; + flex-wrap: wrap; + justify-content: center; + text-align: center; + background-color: #181919; + border: 2px solid #4c4d4d; + border-radius: 10px; +} + +/* widgets */ +.cardinal-main.mod-pedal .mod-switch-image { + background-image: url(/resources/switch.png{{{ns}}}); + background-position: left center; + background-repeat: no-repeat; + background-size: auto 50px; + font-weight: bold; + width: 100px; + height: 50px; + cursor: pointer; + margin: 0 auto; +} +.cardinal-main.mod-pedal .mod-switch-image.off { + background-position: right center !important; +} +.cardinal-main.mod-pedal .mod-switch-image.on { + background-position: left center !important; +} + +.cardinal-main.mod-pedal .title { + font-size: 15px; + font-weight: bold; +} + +.cardinal-main.mod-pedal .mod-knob { + padding: 0px 5px; + width: 85px; +} + +.cardinal-main.mod-pedal .mod-knob-image { + background-image: url(/resources/orange-knob.png{{{ns}}}); + background-position: left center; + background-repeat: no-repeat; + background-size: auto 52px; + font-weight: bold; + height: 52px; + width: 52px; + margin: 0 auto; + position: relative; + overflow: hidden; +} + +.cardinal-main.mod-pedal .distrho-logo { + background-image: url(/resources/distrho.svg{{{ns}}}); + background-size: cover; + background-repeat: no-repeat; + height: 48px; + width: 48px; + margin: 0 auto; +} + +.cardinal-main.mod-pedal .cardinal-text { + font-size: 24px; +} + +.cardinal-main.mod-pedal .mod-string-value { + border: 2px solid #4c4d4d; +} + +.cardinal-main.mod-pedal .mod-string-content, +.cardinal-main.mod-pedal .mod-string-value { + height: 100%; + width: 100%; +} + +.cardinal-main.mod-pedal textarea { + background: black; + color: white; + resize: none; + white-space: pre-wrap; +} + .cardinal-main.mod-pedal textarea::selection { + background: #4c4d4d; +} + +.cardinal-main.mod-pedal .screenshot { + /* 1x1px black png */ + background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2NgYGD4DwABBAEAwS2OUAAAAABJRU5ErkJggg==); + background-position: center; + background-repeat: no-repeat; + background-size: cover; + width: 100%; + height: 100%; + border: 2px solid #4c4d4d; + border-radius: 6px; + border-style: ridge; +} + +.cardinal-main.mod-pedal .mod-pedal-input, +.cardinal-main.mod-pedal .mod-pedal-output { + top: 10px; +} + +.cardinal-main.mod-pedal .jack-disconnected { + top: 0px !important; +} + +.cardinal-main.mod-pedal .mod-pedal-input .mod-audio-input, +.cardinal-main.mod-pedal .mod-pedal-input .mod-midi-input, +.cardinal-main.mod-pedal .mod-pedal-input .mod-cv-input, +.cardinal-main.mod-pedal .mod-pedal-output .mod-audio-output, +.cardinal-main.mod-pedal .mod-pedal-output .mod-midi-output, +.cardinal-main.mod-pedal .mod-pedal-output .mod-cv-output { + margin-bottom: 0px; +} + +.cardinal-main.mod-pedal .mod-pedal-input .mod-audio-input.input-disconnected:not(.cardinal-expanded), +.cardinal-main.mod-pedal .mod-pedal-input .mod-cv-input.input-disconnected:not(.cardinal-expanded), +.cardinal-main.mod-pedal .mod-pedal-output .mod-audio-output.output-disconnected:not(.cardinal-expanded), +.cardinal-main.mod-pedal .mod-pedal-output .mod-cv-output.output-disconnected:not(.cardinal-expanded) { + display: none; +} + +.dummy > .cardinal-main.mod-pedal .mod-pedal-input > .mod-audio-input:not(.cardinal-expanded), +.dummy > .cardinal-main.mod-pedal .mod-pedal-input > .mod-cv-input:not(.cardinal-expanded), +.dummy > .cardinal-main.mod-pedal .mod-pedal-output > .mod-audio-output:not(.cardinal-expanded), +.dummy > .cardinal-main.mod-pedal .mod-pedal-output > .mod-cv-output:not(.cardinal-expanded) { + display: none; +} + +/* initial state */ +/*.cardinal-main.mod-pedal .cardinal-patch-comment,*/ +.cardinal-main.mod-pedal .cardinal-patch-screeenshot { + display: none; +} diff --git a/src/MOD/Cardinal.lv2/modgui/switch.png b/src/MOD/Cardinal.lv2/modgui/switch.png new file mode 100644 index 00000000..b576339a Binary files /dev/null and b/src/MOD/Cardinal.lv2/modgui/switch.png differ diff --git a/src/MOD/Cardinal.lv2/modgui/thumbnail.png b/src/MOD/Cardinal.lv2/modgui/thumbnail.png new file mode 100644 index 00000000..021793f4 Binary files /dev/null and b/src/MOD/Cardinal.lv2/modgui/thumbnail.png differ diff --git a/src/MOD/CardinalFX.lv2/Plateau_Reverb.ttl b/src/MOD/CardinalFX.lv2/Plateau_Reverb.ttl new file mode 100644 index 00000000..cc0d795b --- /dev/null +++ b/src/MOD/CardinalFX.lv2/Plateau_Reverb.ttl @@ -0,0 +1,96 @@ +@prefix atom: . +@prefix lv2: . +@prefix pset: . +@prefix rdf: . +@prefix rdfs: . +@prefix state: . +@prefix xsd: . + +<> + a pset:Preset ; + lv2:appliesTo ; + lv2:port [ + lv2:symbol "lv2_enabled" ; + pset:value 1.0 + ] , [ + lv2:symbol "param_1" ; + pset:value 3.0 + ] , [ + lv2:symbol "param_10" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_11" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_12" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_13" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_14" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_15" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_16" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_17" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_18" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_19" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_2" ; + pset:value 5.0 + ] , [ + lv2:symbol "param_20" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_21" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_22" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_23" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_24" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_3" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_4" ; + pset:value 5.0 + ] , [ + lv2:symbol "param_5" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_6" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_7" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_8" ; + pset:value 0.0 + ] , [ + lv2:symbol "param_9" ; + pset:value 0.0 + ] ; + state:state [ + "KLUv/QBIXR0AZrOOIiAR9Ly6CNQEzyzK+CwIw5H3QvHuEkY2KVmv3eQESAkA+gOGAIAAjQDTgneRB8Qu8lJbrrWmliuWWrVOOmB3F3ms5RZbrLlXSim3Ere7izyswlRGy6IQGWiCd5FHJ2kVtpgzg3eRh6wQXYWjvICRU3kXebAniVdhZzIRJC94F9HodSSl3H+5+1qsux3OjCoSCgkKH4GkHd0OCNKoOn4dTKnWvUml5b3t2P/W3Q6BJKuwIzMmtLDCkMLIEIu08uca+9XqU3sn9wDH2n3/at9JO/ulGkmP+PtzLTlz77fc2f9y5U99a+u5d6qdveQl39jtVTgynPQqLGsDL3h31wJC8OGuUFLYLPAq3Mg4LRhDNg104FXYYSZq8zzaJfeWcvfum7e2CkeGd3d3EY1INjUGnyJIUmkBIbjAXLHHVLdvzdl7c0jShjGQiIt4mkysAzSaBw10mAhBAqWe60+JvX+7ZqtwZBiBUPNh5u1Vr1+FZZwJTxSdyVAIVQoZaH1onRiUuWAoEzmSgdbHYSJHMjgQYMBGFkjo4VWY1sdBkFFdFiZG6VTKq7BsMChDIx34yGZiYjbIDCmhhXdl1MAlGwjELhLbsqR/qts3tp6/V73gp3fPseav2h9bzZfFSeWvMfZrdVtvpfdqxdTf7dkzX92Sa5fcHVvtUmIt+evn1Gu2mnn7a/evuf/29Bxbyr//13u9OH36ZQHgVRiazZRwh3EYRqD1oXUiyKbGmUDrQ+t85p0cU6tfat1SBJQIgKeoEVFmAEZGIJowRhA0AOACAJAhIgMSYGAIQCBIYgADQQwBQzIMROgoATAAGCAwQgjB4LBBADT1bxCWZ3XXFUabMDuaLONUf0bQ7TgesmQFW2K0AIC4DIQl6tqRPtTyQ0noFFHLQLAATUPeplJl0koHLuVhRjg4NPbs9Wj4AfakXtrVG9Ad+CrbZ0A7Je11icVN+xCwTDBY4Kno85VOIgGk9RzZ1xnpmiObAcD2we4MScUkfADxZIwmSY1vfFxeBnO2iMzNnVOizhd5nU4xNop8kqWVGCB1KmgvNEkW+hzkks3EyByFzDwFDlF2lniRVMGMMof+Y3EQBeSTGEBSh4gEX4611XB1fbturqxt69SVkxPISckW8aolo/yTNVoJCBspCeshPp+jqj7FYS6yDMBKLRy7IHXc+R+MwTYm+KQQqLmmbcdm0+47HTL1RQKZwQ4vBxDovJ+HmZDDJMrAgYowZEBNGMD3FABjnGbw" ; + "" ; + """Activated by parameters. +1 - Dry Level +2 - Wet Level +3 - Low-Cut +4 - Decay""" ; + ] . diff --git a/src/MOD/CardinalFX.lv2/modgui.ttl b/src/MOD/CardinalFX.lv2/modgui.ttl index 9988dca0..98d95eb5 100644 --- a/src/MOD/CardinalFX.lv2/modgui.ttl +++ b/src/MOD/CardinalFX.lv2/modgui.ttl @@ -1,6 +1,8 @@ @prefix lv2: . @prefix mod: . @prefix modgui: . +@prefix pset: . +@prefix rdfs: . @prefix state: . @@ -19,3 +21,9 @@ """Welcome to Cardinal. If this is your first time, make sure to check out the documentation link on the plugin info, have fun!""" ; ] . + + + a pset:Preset ; + lv2:appliesTo ; + rdfs:label "Plateau Reverb" ; + rdfs:seeAlso . diff --git a/src/MOD/CardinalFX.lv2/modgui/screenshot.png b/src/MOD/CardinalFX.lv2/modgui/screenshot.png index 8b81b668..016c4c88 100644 Binary files a/src/MOD/CardinalFX.lv2/modgui/screenshot.png and b/src/MOD/CardinalFX.lv2/modgui/screenshot.png differ diff --git a/src/MOD/CardinalFX.lv2/modgui/stylesheet.css b/src/MOD/CardinalFX.lv2/modgui/stylesheet.css index de03ec0e..cbc8f74e 100644 --- a/src/MOD/CardinalFX.lv2/modgui/stylesheet.css +++ b/src/MOD/CardinalFX.lv2/modgui/stylesheet.css @@ -2,9 +2,8 @@ .cardinal-fx.mod-pedal { background: #333333; background: linear-gradient(to bottom, #181919, #333333); - color: white; width: 480px; - height: 420px; + height: 390px; font-size: 20px; margin: 0; padding: 0; @@ -12,7 +11,7 @@ .cardinal-fx.mod-pedal .border { border: 2px solid #4c4d4d; width: 480px; - height: 420px; + height: 390px; position: absolute; } @@ -24,22 +23,24 @@ /* top and bottom area split */ .cardinal-fx.mod-pedal .cardinal-fx-top { width: 100%; - height: 240px; + height: 210px; position: absolute; top: 0px; + color: white; } .cardinal-fx.mod-pedal .cardinal-fx-bottom { width: 100%; height: 180px; position: absolute; - top: 240px; + top: 210px; + color: white; } /* top area split */ .cardinal-fx.mod-pedal .cardinal-fx-top-left { - width: 120px; - height: 240px; + width: 140px; + height: 210px; position: absolute; top: 0px; left: 0px; @@ -50,18 +51,18 @@ } .cardinal-fx.mod-pedal .cardinal-fx-top-right { - width: 350px; - height: 240px; + width: 340px; + height: 210px; position: absolute; top: 0px; - left: 120px; + left: 140px; } .cardinal-fx.mod-pedal .cardinal-patch-comment, .cardinal-fx.mod-pedal .cardinal-patch-screeenshot { - width: 340px; - height: 210px; - margin: 20px 20px 10px 0px; + width: 330px; + height: 190px; + margin: 10px 10px 10px 0px; } /* bottom section split */ @@ -149,7 +150,7 @@ } .cardinal-fx.mod-pedal .mod-string-value { - border: 1px solid #4c4d4d; + border: 2px solid #4c4d4d; } .cardinal-fx.mod-pedal .mod-string-content, @@ -173,9 +174,12 @@ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2NgYGD4DwABBAEAwS2OUAAAAABJRU5ErkJggg==); background-position: center; background-repeat: no-repeat; - background-size: contain; + background-size: cover; width: 100%; height: 100%; + border: 2px solid #4c4d4d; + border-radius: 6px; + border-style: ridge; } .cardinal-fx.mod-pedal .cardinal-fx-knob-page-selector > span { diff --git a/src/MOD/CardinalFX.lv2/modgui/thumbnail.png b/src/MOD/CardinalFX.lv2/modgui/thumbnail.png index 25b329aa..8bd7f497 100644 Binary files a/src/MOD/CardinalFX.lv2/modgui/thumbnail.png and b/src/MOD/CardinalFX.lv2/modgui/thumbnail.png differ diff --git a/src/Makefile b/src/Makefile index d9e5ee69..9b1c3d03 100644 --- a/src/Makefile +++ b/src/Makefile @@ -7,7 +7,10 @@ # -------------------------------------------------------------- # Import base definitions +DISTRHO_NAMESPACE = CardinalDISTRHO +DGL_NAMESPACE = CardinalDGL USE_NANOVG_FBO = true +WASM_EXCEPTIONS = true include ../dpf/Makefile.base.mk # -------------------------------------------------------------- @@ -33,14 +36,16 @@ BASE_FLAGS += -DARCH_LIN endif ifeq ($(HAIKU),true) -BASE_FLAGS += -I../include/haiku-compat +BASE_FLAGS += -I../include/linux-compat +else ifeq ($(WASM),true) +BASE_FLAGS += -I../include/linux-compat endif BASE_FLAGS += -DPRIVATE= BASE_FLAGS += -I../dpf/dgl/src/nanovg BASE_FLAGS += -I../dpf/distrho BASE_FLAGS += -I../include -BASE_FLAGS += -I../include/neon-compat +BASE_FLAGS += -I../include/simd-compat BASE_FLAGS += -IRack/include ifeq ($(SYSDEPS),true) BASE_FLAGS += -DCARDINAL_SYSDEPS @@ -59,6 +64,10 @@ BASE_FLAGS += -IRack/dep/pffft ifeq ($(DEBUG),true) BASE_FLAGS += -UDEBUG +ifeq ($(WASM),true) +# SSE must always be enabled on wasm, even in debug builds +BASE_FLAGS += -msse -msse2 -msse3 -msimd128 +endif endif ifeq ($(HAVE_LIBLO),true) @@ -77,14 +86,11 @@ ifeq ($(HAIKU),true) BASE_FLAGS += -DCLOCK_MONOTONIC_RAW=CLOCK_MONOTONIC endif -ifeq ($(WASM),true) -BASE_FLAGS += -DNANOVG_GLES2=1 -BASE_FLAGS += -msse -msse2 -msse3 -msimd128 -# FIXME -BASE_FLAGS += -DRTLD_DEEPBIND=0 -else ifneq ($(HAIKU),true) +ifneq ($(WASM),true) +ifneq ($(HAIKU),true) BASE_FLAGS += -pthread endif +endif ifeq ($(WINDOWS),true) BASE_FLAGS += -D_USE_MATH_DEFINES @@ -93,16 +99,30 @@ BASE_FLAGS += -I../include/mingw-compat BASE_FLAGS += -I../include/mingw-std-threads endif +ifeq ($(USE_GLES2),true) +BASE_FLAGS += -DNANOVG_GLES2_FORCED +else ifeq ($(USE_GLES3),true) +BASE_FLAGS += -DNANOVG_GLES3_FORCED +endif + BUILD_C_FLAGS += -std=gnu11 BUILD_C_FLAGS += -fno-finite-math-only -fno-strict-aliasing -BUILD_CXX_FLAGS += -fno-finite-math-only -fno-strict-aliasing -faligned-new +BUILD_CXX_FLAGS += -fno-finite-math-only -fno-strict-aliasing + +ifneq ($(MACOS),true) +BUILD_CXX_FLAGS += -faligned-new -Wno-abi +endif # use our custom function to invert some colors +BUILD_CXX_FLAGS += -DnsvgDelete=nsvgDeleteCardinal BUILD_CXX_FLAGS += -DnsvgParseFromFile=nsvgParseFromFileCardinal # Rack code is not tested for this flag, unset it BUILD_CXX_FLAGS += -U_GLIBCXX_ASSERTIONS -Wp,-U_GLIBCXX_ASSERTIONS +# Ignore bad behaviour from Rack API +BUILD_CXX_FLAGS += -Wno-format-security + # -------------------------------------------------------------- # Rack files to build @@ -120,6 +140,7 @@ RACK_FILES += override/plugin.cpp RACK_FILES += override/Engine.cpp RACK_FILES += override/MenuBar.cpp RACK_FILES += override/Model.cpp +RACK_FILES += override/OpenGlWidget.cpp RACK_FILES += override/Scene.cpp RACK_FILES += Rack/dep/pffft/pffft.c @@ -148,6 +169,7 @@ IGNORED_FILES += Rack/src/app/TipWindow.cpp IGNORED_FILES += Rack/src/dsp/minblep.cpp IGNORED_FILES += Rack/src/engine/Engine.cpp IGNORED_FILES += Rack/src/plugin/Model.cpp +IGNORED_FILES += Rack/src/widget/OpenGlWidget.cpp IGNORED_FILES += Rack/src/window/Window.cpp IGNORED_FILES += $(wildcard Rack/src/core/*.cpp) @@ -156,6 +178,10 @@ RACK_FILES += $(wildcard Rack/src/*/*.c) RACK_FILES += $(filter-out $(IGNORED_FILES),$(wildcard Rack/src/*.cpp)) RACK_FILES += $(filter-out $(IGNORED_FILES), $(wildcard Rack/src/*/*.cpp)) +ifeq ($(WASM),true) +RACK_FILES += emscripten/WasmUtils.cpp +endif + # -------------------------------------------------------------- # lots of warnings from VCV side @@ -174,15 +200,19 @@ endif TARGET = rack.a ifneq ($(MACOS),true) -CARDINAL_FX_ARGS = VST2_FILENAME=Cardinal.vst/CardinalFX$(LIB_EXT) -CARDINAL_SYNTH_ARGS = VST2_FILENAME=Cardinal.vst/CardinalSynth$(LIB_EXT) +CARDINAL_FX_ARGS = VST2_FILENAME=Cardinal.vst/CardinalFX$(LIB_EXT) CLAP_FILENAME=Cardinal.clap/CardinalFX.clap +CARDINAL_SYNTH_ARGS = VST2_FILENAME=Cardinal.vst/CardinalSynth$(LIB_EXT) CLAP_FILENAME=Cardinal.clap/CardinalSynth.clap endif all: $(TARGET) ifeq ($(MOD_BUILD),true) + $(MAKE) -C Cardinal lv2 $(MAKE) -C CardinalFX lv2 +else ifeq ($(WASM),true) + $(MAKE) -C CardinalNative else $(MAKE) -C Cardinal + $(MAKE) -C CardinalNative $(MAKE) -C CardinalFX $(CARDINAL_FX_ARGS) $(MAKE) -C CardinalSynth $(CARDINAL_SYNTH_ARGS) endif @@ -190,6 +220,9 @@ endif jack: $(TARGET) $(MAKE) jack -C Cardinal +native: $(TARGET) + $(MAKE) jack -C CardinalNative + lv2: $(TARGET) $(MAKE) lv2 -C Cardinal $(MAKE) lv2 -C CardinalFX $(CARDINAL_FX_ARGS) @@ -204,6 +237,9 @@ vst3: $(TARGET) $(MAKE) vst3 -C CardinalFX $(CARDINAL_FX_ARGS) $(MAKE) vst3 -C CardinalSynth $(CARDINAL_SYNTH_ARGS) +clap: $(TARGET) + $(MAKE) clap -C CardinalFX $(CARDINAL_FX_ARGS) + clean: rm -f $(TARGET) rm -rf $(BUILD_DIR) @@ -226,16 +262,13 @@ $(BUILD_DIR)/%.c.o: %.c @echo "Compiling $<" $(SILENT)$(CC) $< $(BUILD_C_FLAGS) -c -o $@ -$(BUILD_DIR)/override/MIDI_CV.cpp.o: override/MIDI_CV.cpp - -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" - @echo "Compiling $<" - $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -UPRIVATE -c -o $@ - $(BUILD_DIR)/%.cpp.o: %.cpp -@mkdir -p "$(shell dirname $(BUILD_DIR)/$<)" @echo "Compiling $<" $(SILENT)$(CXX) $< $(BUILD_CXX_FLAGS) -c -o $@ +$(BUILD_DIR)/emscripten/WasmUtils.cpp.o: BUILD_CXX_FLAGS += -fno-exceptions + # -------------------------------------------------------------- -include $(RACK_OBJS:%.o=%.d) diff --git a/src/Makefile.cardinal.mk b/src/Makefile.cardinal.mk index 45661a2a..a03f2680 100644 --- a/src/Makefile.cardinal.mk +++ b/src/Makefile.cardinal.mk @@ -10,6 +10,8 @@ ifeq ($(NAME),Cardinal) CARDINAL_VARIANT = main else ifeq ($(NAME),CardinalFX) CARDINAL_VARIANT = fx +else ifeq ($(NAME),CardinalNative) +CARDINAL_VARIANT = native else ifeq ($(NAME),CardinalSynth) CARDINAL_VARIANT = synth endif @@ -19,10 +21,6 @@ endif ifneq ($(STATIC_BUILD),true) -ifneq ($(DEBUG),true) -EXTERNAL_PLUGINS = true -endif - CWD = ../../carla/source include $(CWD)/Makefile.deps.mk @@ -38,11 +36,14 @@ CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/carla_engine_ CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/carla_plugin.a CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/native-plugins.a CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/audio_decoder.a +ifneq ($(WASM),true) CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/jackbridge.min.a +endif CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/lilv.a CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/rtmempool.a CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/sfzero.a CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/water.a +CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/ysfx.a CARLA_EXTRA_LIBS += $(CARLA_BUILD_DIR)/modules/$(CARLA_BUILD_TYPE)/zita-resampler.a endif # STATIC_BUILD @@ -50,7 +51,21 @@ endif # STATIC_BUILD # -------------------------------------------------------------- # Import base definitions +DISTRHO_NAMESPACE = CardinalDISTRHO +DGL_NAMESPACE = CardinalDGL +NVG_DISABLE_SKIPPING_WHITESPACE = true +NVG_FONT_TEXTURE_FLAGS = NVG_IMAGE_NEAREST USE_NANOVG_FBO = true +WASM_EXCEPTIONS = true + +ifeq ($(CARDINAL_VARIANT),main) +# main variant should not use rtaudio/sdl2 fallback (it has CV ports) +SKIP_NATIVE_AUDIO_FALLBACK = true +else +# fx and synth variants should only use rtaudio/sdl2 fallbacks +FORCE_NATIVE_AUDIO_FALLBACK = true +endif + include ../../dpf/Makefile.base.mk # -------------------------------------------------------------- @@ -82,6 +97,7 @@ FILES_DSP += RemoteNanoVG.cpp FILES_DSP += RemoteWindow.cpp else FILES_UI = CardinalUI.cpp +FILES_UI += glfw.cpp FILES_UI += Window.cpp endif @@ -110,16 +126,65 @@ endif # -------------------------------------------------------------- +# FIXME +ifeq ($(WASM),true) +ifneq ($(STATIC_BUILD),true) +STATIC_CARLA_PLUGIN_LIBS = -lsndfile -lopus -lFLAC -lvorbisenc -lvorbis -logg -lm +endif +endif + EXTRA_DEPENDENCIES = $(RACK_EXTRA_LIBS) $(CARLA_EXTRA_LIBS) EXTRA_LIBS = $(RACK_EXTRA_LIBS) $(CARLA_EXTRA_LIBS) $(STATIC_CARLA_PLUGIN_LIBS) +ifeq ($(shell $(PKG_CONFIG) --exists fftw3f && echo true),true) +EXTRA_DEPENDENCIES += ../../deps/aubio/libaubio.a +EXTRA_LIBS += ../../deps/aubio/libaubio.a +EXTRA_LIBS += $(shell $(PKG_CONFIG) --libs fftw3f) +endif + +# -------------------------------------------------------------- +# Setup resources + +CORE_RESOURCES = patches +CORE_RESOURCES += $(subst ../Rack/res/,,$(wildcard ../Rack/res/ComponentLibrary/*.svg ../Rack/res/fonts/*.ttf)) + +LV2_RESOURCES = $(CORE_RESOURCES:%=$(TARGET_DIR)/$(NAME).lv2/resources/%) +VST3_RESOURCES = $(CORE_RESOURCES:%=$(TARGET_DIR)/$(NAME).vst3/Contents/Resources/%) + +# Install modgui resources if MOD build +ifeq ($(MOD_BUILD),true) +LV2_RESOURCES += $(TARGET_DIR)/$(NAME).lv2/Plateau_Reverb.ttl +LV2_RESOURCES += $(TARGET_DIR)/$(NAME).lv2/modgui.ttl +LV2_RESOURCES += $(TARGET_DIR)/$(NAME).lv2/modgui/documentation.pdf +LV2_RESOURCES += $(TARGET_DIR)/$(NAME).lv2/modgui +endif + +# Cardinal main variant is not available as VST2 due to lack of CV ports +ifneq ($(CARDINAL_VARIANT),main) +ifeq ($(MACOS),true) +VST2_RESOURCES = $(CORE_RESOURCES:%=$(TARGET_DIR)/$(NAME).vst/Contents/Resources/%) +CLAP_RESOURCES = $(CORE_RESOURCES:%=$(TARGET_DIR)/$(NAME).clap/Contents/Resources/%) +else +VST2_RESOURCES = $(CORE_RESOURCES:%=$(TARGET_DIR)/Cardinal.vst/resources/%) +CLAP_RESOURCES = $(CORE_RESOURCES:%=$(TARGET_DIR)/Cardinal.clap/resources/%) +endif +endif + +ifeq ($(WASM),true) +WASM_RESOURCES = $(LV2_RESOURCES) + +ifneq ($(STATIC_BUILD),true) +WASM_RESOURCES += $(CURDIR)/lv2 +endif + +EXTRA_DEPENDENCIES += $(WASM_RESOURCES) +endif + # -------------------------------------------------------------- # Do some magic -NVG_DISABLE_SKIPPING_WHITESPACE = true -NVG_FONT_TEXTURE_FLAGS = NVG_IMAGE_NEAREST -USE_NANOVG_FBO = true USE_VST2_BUNDLE = true +USE_CLAP_BUNDLE = true include ../../dpf/Makefile.plugins.mk # -------------------------------------------------------------- @@ -137,11 +202,11 @@ BASE_FLAGS += -DPRIVATE= BASE_FLAGS += -I.. BASE_FLAGS += -I../../dpf/dgl/src/nanovg BASE_FLAGS += -I../../include -BASE_FLAGS += -I../../include/neon-compat +BASE_FLAGS += -I../../include/simd-compat BASE_FLAGS += -I../Rack/include ifeq ($(SYSDEPS),true) BASE_FLAGS += -DCARDINAL_SYSDEPS -BASE_FLAGS += $(shell pkg-config --cflags jansson libarchive samplerate speexdsp) +BASE_FLAGS += $(shell $(PKG_CONFIG) --cflags jansson libarchive samplerate speexdsp) else BASE_FLAGS += -DZSTDLIB_VISIBILITY= BASE_FLAGS += -I../Rack/dep/include @@ -158,12 +223,11 @@ ifeq ($(MOD_BUILD),true) BASE_FLAGS += -DDISTRHO_PLUGIN_USES_MODGUI=1 -DDISTRHO_PLUGIN_MINIMUM_BUFFER_SIZE=0xffff endif -ifeq ($(WASM),true) -BASE_FLAGS += -DNANOVG_GLES2=1 -BASE_FLAGS += -msse -msse2 -msse3 -msimd128 -else ifneq ($(HAIKU),true) +ifneq ($(WASM),true) +ifneq ($(HAIKU),true) BASE_FLAGS += -pthread endif +endif ifeq ($(WINDOWS),true) BASE_FLAGS += -D_USE_MATH_DEFINES @@ -172,13 +236,26 @@ BASE_FLAGS += -I../../include/mingw-compat BASE_FLAGS += -I../../include/mingw-std-threads endif +ifeq ($(USE_GLES2),true) +BASE_FLAGS += -DNANOVG_GLES2_FORCED +else ifeq ($(USE_GLES3),true) +BASE_FLAGS += -DNANOVG_GLES3_FORCED +endif + BUILD_C_FLAGS += -std=gnu11 BUILD_C_FLAGS += -fno-finite-math-only -fno-strict-aliasing -BUILD_CXX_FLAGS += -fno-finite-math-only -fno-strict-aliasing -faligned-new +BUILD_CXX_FLAGS += -fno-finite-math-only -fno-strict-aliasing + +ifneq ($(MACOS),true) +BUILD_CXX_FLAGS += -faligned-new -Wno-abi +endif # Rack code is not tested for this flag, unset it BUILD_CXX_FLAGS += -U_GLIBCXX_ASSERTIONS -Wp,-U_GLIBCXX_ASSERTIONS +# Ignore bad behaviour from Rack API +BUILD_CXX_FLAGS += -Wno-format-security + # -------------------------------------------------------------- # FIXME lots of warnings from VCV side @@ -188,7 +265,19 @@ BASE_FLAGS += -Wno-unused-variable # -------------------------------------------------------------- # extra linker flags -ifeq ($(HAIKU),true) +ifeq ($(WASM),true) +ifneq ($(STATIC_BUILD),true) +LINK_FLAGS += --use-preload-plugins +LINK_FLAGS += --preload-file=./jsfx +LINK_FLAGS += --preload-file=./lv2 +endif +LINK_FLAGS += --preload-file=../../bin/CardinalNative.lv2/resources@/resources +LINK_FLAGS += -sALLOW_MEMORY_GROWTH +LINK_FLAGS += -sINITIAL_MEMORY=64Mb +LINK_FLAGS += -sLZ4=1 +LINK_FLAGS += --shell-file=../emscripten/shell.html +LINK_FLAGS += -O3 +else ifeq ($(HAIKU),true) LINK_FLAGS += -lpthread else LINK_FLAGS += -pthread @@ -216,7 +305,7 @@ EXTRA_LIBS += -lws2_32 -lwinmm endif ifeq ($(SYSDEPS),true) -EXTRA_LIBS += $(shell pkg-config --libs jansson libarchive samplerate speexdsp) +EXTRA_LIBS += $(shell $(PKG_CONFIG) --libs jansson libarchive samplerate speexdsp) endif ifeq ($(WITH_LTO),true) @@ -262,45 +351,49 @@ BUILD_CXX_FLAGS += -DCARDINAL_PLUGIN_PREFIX='"$(PREFIX)"' # Enable all possible plugin types and setup resources ifeq ($(CARDINAL_VARIANT),main) -ifneq ($(STATIC_BUILD),true) -all: jack lv2 vst3 -else -all: lv2 vst3 -endif # STATIC_BUILD -else -all: lv2 vst2 vst3 static -endif - -CORE_RESOURCES = $(subst ../Rack/res/,,$(wildcard ../Rack/res/ComponentLibrary/*.svg ../Rack/res/fonts/*.ttf)) -CORE_RESOURCES += $(subst ../,,$(wildcard ../template*.vcv)) - -LV2_RESOURCES = $(CORE_RESOURCES:%=$(TARGET_DIR)/$(NAME).lv2/resources/%) -VST3_RESOURCES = $(CORE_RESOURCES:%=$(TARGET_DIR)/$(NAME).vst3/Contents/Resources/%) - -# Install modgui resources if MOD build -ifeq ($(MOD_BUILD),true) -LV2_RESOURCES += $(TARGET_DIR)/$(NAME).lv2/modgui.ttl -LV2_RESOURCES += $(TARGET_DIR)/$(NAME).lv2/modgui/documentation.pdf -LV2_RESOURCES += $(TARGET_DIR)/$(NAME).lv2/modgui -endif - -# Cardinal main variant should not use rtaudio fallback (it has CV ports) -ifeq ($(CARDINAL_VARIANT),main) -jack: BUILD_CXX_FLAGS += -DDPF_JACK_STANDALONE_SKIP_RTAUDIO_FALLBACK +TARGETS = lv2 vst3 +ifeq ($(HAVE_JACK),true) +TARGETS += jack endif - -# Cardinal main variant is not available as VST2 due to lack of CV ports -ifneq ($(CARDINAL_VARIANT),main) -ifeq ($(MACOS),true) -VST2_RESOURCES = $(CORE_RESOURCES:%=$(TARGET_DIR)/$(NAME).vst/Contents/Resources/%) +else ifeq ($(CARDINAL_VARIANT),native) +TARGETS = jack else -VST2_RESOURCES = $(CORE_RESOURCES:%=$(TARGET_DIR)/Cardinal.vst/resources/%) +TARGETS = lv2 vst2 vst3 static endif + +# TESTING +ifeq ($(CARDINAL_VARIANT),fx) +TARGETS += clap endif +all: $(TARGETS) lv2: $(LV2_RESOURCES) vst2: $(VST2_RESOURCES) vst3: $(VST3_RESOURCES) +clap: $(CLAP_RESOURCES) + +# -------------------------------------------------------------- +# Extra rules for macOS app bundle + +$(TARGET_DIR)/Cardinal.app/Contents/Info.plist: ../../utils/macOS/Info_JACK.plist $(TARGET_DIR)/Cardinal.app/Contents/Resources/distrho.icns + -@mkdir -p $(shell dirname $@) + cp $< $@ + +$(TARGET_DIR)/CardinalNative.app/Contents/Info.plist: ../../utils/macOS/Info_Native.plist $(TARGET_DIR)/CardinalNative.app/Contents/Resources/distrho.icns + -@mkdir -p $(shell dirname $@) + cp $< $@ + +$(TARGET_DIR)/%.app/Contents/Resources/distrho.icns: ../../utils/distrho.icns + -@mkdir -p $(shell dirname $@) + cp $< $@ + +# -------------------------------------------------------------- +# Extra rules for wasm resources + +ifeq ($(WASM),true) +$(CURDIR)/lv2: $(LV2_RESOURCES) + wget -O - https://falktx.com/data/wasm-things-2022-08-15.tar.gz | tar xz -C $(CURDIR) +endif # -------------------------------------------------------------- # Extra rules for Windows icon @@ -316,17 +409,13 @@ endif # -------------------------------------------------------------- -$(TARGET_DIR)/%/template.vcv: ../template.vcv - -@mkdir -p "$(shell dirname $@)" - $(SILENT)ln -sf $(abspath $<) $@ - -$(TARGET_DIR)/%/template-fx.vcv: ../template-fx.vcv - -@mkdir -p "$(shell dirname $@)" - $(SILENT)ln -sf $(abspath $<) $@ - -$(TARGET_DIR)/%/template-synth.vcv: ../template-synth.vcv +$(TARGET_DIR)/%/patches: ../../patches -@mkdir -p "$(shell dirname $@)" +ifeq ($(WASM),true) + cp -rL $< $@ +else $(SILENT)ln -sf $(abspath $<) $@ +endif $(TARGET_DIR)/$(NAME).lv2/resources/%: ../Rack/res/% -@mkdir -p "$(shell dirname $@)" @@ -341,6 +430,10 @@ $(TARGET_DIR)/$(NAME).lv2/mod%: ../MOD/$(NAME).lv2/mod% -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ +$(TARGET_DIR)/$(NAME).lv2/%.ttl: ../MOD/$(NAME).lv2/%.ttl + -@mkdir -p "$(shell dirname $@)" + $(SILENT)ln -sf $(abspath $<) $@ + $(TARGET_DIR)/$(NAME).lv2/modgui/documentation.pdf: ../../docs/MODDEVICES.md $(TARGET_DIR)/$(NAME).lv2/modgui (cd ../../docs/ && pandoc MODDEVICES.md -f markdown+implicit_figures -o $(abspath $@)) endif @@ -349,6 +442,10 @@ $(TARGET_DIR)/Cardinal.vst/resources/%: ../Rack/res/% -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ +$(TARGET_DIR)/Cardinal.clap/resources/%: ../Rack/res/% + -@mkdir -p "$(shell dirname $@)" + $(SILENT)ln -sf $(abspath $<) $@ + $(TARGET_DIR)/$(NAME).vst/Contents/Resources/%: ../Rack/res/% -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ @@ -357,4 +454,8 @@ $(TARGET_DIR)/$(NAME).vst3/Contents/Resources/%: ../Rack/res/% -@mkdir -p "$(shell dirname $@)" $(SILENT)ln -sf $(abspath $<) $@ +$(TARGET_DIR)/$(NAME).clap/Contents/Resources/%: ../Rack/res/% + -@mkdir -p "$(shell dirname $@)" + $(SILENT)ln -sf $(abspath $<) $@ + # -------------------------------------------------------------- diff --git a/src/PluginContext.hpp b/src/PluginContext.hpp index 0aa9edc9..c5a22920 100644 --- a/src/PluginContext.hpp +++ b/src/PluginContext.hpp @@ -30,7 +30,6 @@ #ifndef HEADLESS # include "DistrhoUI.hpp" -# include "extra/FileBrowserDialog.hpp" #endif START_NAMESPACE_DISTRHO @@ -42,6 +41,7 @@ static constexpr const uint kModuleParameters = 24; enum CardinalVariant { kCardinalVariantMain, kCardinalVariantFX, + kCardinalVariantNative, kCardinalVariantSynth, }; @@ -75,6 +75,8 @@ struct CardinalPluginContext : rack::Context { variant(kCardinalVariantMain), #elif CARDINAL_VARIANT_FX variant(kCardinalVariantFX), + #elif CARDINAL_VARIANT_NATIVE + variant(kCardinalVariantNative), #elif CARDINAL_VARIANT_SYNTH variant(kCardinalVariantSynth), #else @@ -123,10 +125,6 @@ void handleHostParameterDrag(const CardinalPluginContext* pcontext, uint index, // ----------------------------------------------------------------------------------------------------------- -struct CardinalAudioDevice; -struct CardinalMidiInputDevice; -struct CardinalMidiOutputDevice; - CardinalPluginContext* getRackContextFromPlugin(void* ptr); class CardinalBasePlugin : public Plugin { @@ -137,15 +135,25 @@ class CardinalBasePlugin : public Plugin { : Plugin(parameterCount, programCount, stateCount), context(new CardinalPluginContext(this)) {} ~CardinalBasePlugin() override {} + +#ifndef HEADLESS + friend class CardinalUI; +#endif }; #ifndef HEADLESS +struct WasmRemotePatchLoadingDialog; + class CardinalBaseUI : public UI { public: CardinalPluginContext* const context; bool saving; bool savingUncompressed; + #ifdef DISTRHO_OS_WASM + WasmRemotePatchLoadingDialog* psDialog; + #endif + // for 3rd party modules std::function filebrowseraction; FileBrowserHandle filebrowserhandle; @@ -155,6 +163,9 @@ class CardinalBaseUI : public UI { context(getRackContextFromPlugin(getPluginInstancePointer())), saving(false), savingUncompressed(false), + #ifdef DISTRHO_OS_WASM + psDialog(nullptr), + #endif filebrowseraction(), filebrowserhandle(nullptr) { diff --git a/src/Rack b/src/Rack index 30665d62..5551617a 160000 --- a/src/Rack +++ b/src/Rack @@ -1 +1 @@ -Subproject commit 30665d62801c2ced7260a37a2d0214edfe6528a9 +Subproject commit 5551617afff182925940908eaf73a7d7361303cc diff --git a/src/WindowParameters.hpp b/src/WindowParameters.hpp index 58bd83ee..55c28323 100644 --- a/src/WindowParameters.hpp +++ b/src/WindowParameters.hpp @@ -33,6 +33,7 @@ START_NAMESPACE_DISTRHO // ----------------------------------------------------------------------------------------------------------- +// NOTE make sure to never change the order, parameters indexes are based on this enum WindowParameterList { kWindowParameterShowTooltips, kWindowParameterCableOpacity, @@ -47,6 +48,7 @@ enum WindowParameterList { kWindowParameterBrowserSort, kWindowParameterBrowserZoom, kWindowParameterInvertZoom, + kWindowParameterSqueezeModulePositions, kWindowParameterCount, }; @@ -62,6 +64,7 @@ struct WindowParameters { bool tooltips = true; bool knobScroll = false; bool lockModules = false; + bool squeezeModules = true; bool invertZoom = false; // cardinal specific int rateLimit = 0; diff --git a/src/custom/RemoteNanoVG.cpp b/src/custom/RemoteNanoVG.cpp index 70910977..a299cf05 100644 --- a/src/custom/RemoteNanoVG.cpp +++ b/src/custom/RemoteNanoVG.cpp @@ -54,6 +54,7 @@ typedef struct GLFWwindow GLFWwindow; GLFWAPI const char* glfwGetClipboardString(GLFWwindow*) { return nullptr; } GLFWAPI void glfwSetClipboardString(GLFWwindow*, const char*) {} +GLFWAPI GLFWcursor* glfwCreateStandardCursor(int) { return nullptr; } GLFWAPI void glfwSetCursor(GLFWwindow*, GLFWcursor*) {} GLFWAPI const char* glfwGetKeyName(int, int) { return nullptr; } GLFWAPI int glfwGetKeyScancode(int) { return 0; } diff --git a/src/custom/asset.cpp b/src/custom/asset.cpp index ef110212..40ee4f27 100644 --- a/src/custom/asset.cpp +++ b/src/custom/asset.cpp @@ -50,34 +50,24 @@ std::string user(std::string filename) { // get system resource, trimming "res/" prefix if we are loaded as a plugin bundle std::string system(std::string filename) { - // Always use dark screws - if (string::endsWith(filename, "/ScrewSilver.svg")) - filename = filename.substr(0, filename.size()-10) + "Black.svg"; return system::join(systemDir, bundlePath.empty() ? filename : trim(filename)); } // get plugin resource std::string plugin(plugin::Plugin* plugin, std::string filename) { DISTRHO_SAFE_ASSERT_RETURN(plugin != nullptr, {}); - // always use dark scheme - if (plugin->slug == "GlueTheGiant") - { - if (filename == "res/BusDepot.svg" - || filename == "res/BusRoute.svg" - || filename == "res/EnterBus.svg" - || filename == "res/ExitBus.svg" - || filename == "res/GigBus.svg" - || filename == "res/MetroCityBus.svg" - || filename == "res/MiniBus.svg" - || filename == "res/Road.svg" - || filename == "res/SchoolBus.svg") - { - filename = filename.substr(0, filename.size()-4) + "_Night.svg"; - } - } return system::join(plugin->path, filename); } +// path to demo patch files +std::string patchesPath() { + // no bundlePath set, assume local source build + if (bundlePath.empty()) + return system::join(systemDir, "..", "..", "patches"); + // bundlePath is present, use resources from bundle + return system::join(systemDir, "patches"); +} + // path to plugin manifest std::string pluginManifest(const std::string& dirname) { // no bundlePath set, assume local source build diff --git a/src/custom/dep.cpp b/src/custom/dep.cpp index 6e26b1f8..278368e1 100644 --- a/src/custom/dep.cpp +++ b/src/custom/dep.cpp @@ -1,6 +1,6 @@ /* * DISTRHO Cardinal Plugin - * Copyright (C) 2021 Filipe Coelho + * Copyright (C) 2021-2022 Filipe Coelho * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -19,6 +19,15 @@ #include #include +#include +#include + +namespace rack { +namespace settings { +bool darkMode = true; +int rateLimit = 0; +} +} #include "nanovg.h" @@ -34,15 +43,16 @@ float FollowerBase::efGainMaxDecibelsDebug = 12.0f; // Special nvgRGB for blank panels extern "C" { -NVGcolor nvgRGBblank(unsigned char, unsigned char, unsigned char) +NVGcolor nvgRGBblank(const unsigned char r, const unsigned char g, const unsigned char b) { - return nvgRGB(0x20, 0x20, 0x20); + return rack::settings::darkMode ? nvgRGB(0x20, 0x20, 0x20) : nvgRGB(r, g, b); } } // Compile those nice implementation-in-header little libraries #define NANOSVG_IMPLEMENTATION #define NANOSVG_ALL_COLOR_KEYWORDS +#undef nsvgDelete #undef nsvgParseFromFile #include @@ -51,7 +61,7 @@ static const struct { const char* const filename; const char* shapeIdsToIgnore[5]; const int shapeNumberToIgnore; -} svgFilesToInvert[] = { +} svgFilesToInvertForDarkMode[] = { // MIT { "/21kHz/res/Panels/D_Inf.svg", {}, -1 }, { "/21kHz/res/Panels/PalmLoop.svg", {}, -1 }, @@ -268,25 +278,31 @@ static const struct { { "/kocmoc/res/SKF.svg", {}, -1 }, { "/kocmoc/res/SVF.svg", {}, -1 }, { "/kocmoc/res/TRG.svg", {}, -1 }, + // GPL-3.0-or-later + { "/myth-modules/res/Mavka.svg", {}, -1 }, + { "/myth-modules/res/Molphar.svg", {}, -1 }, // CC0-1.0 + { "/nonlinearcircuits/res/BOOLs2.svg", {}, -1 }, + { "/nonlinearcircuits/res/DoubleNeuronRef.svg", {}, -1 }, + { "/nonlinearcircuits/res/LetsSplosh.svg", {}, -1 }, { "/nonlinearcircuits/res/NLC - 4seq.svg", {}, -1 }, { "/nonlinearcircuits/res/NLC - 8 BIT CIPHER.svg", {}, -1 }, - { "/nonlinearcircuits/res/BOOLs2.svg", {}, -1 }, { "/nonlinearcircuits/res/NLC - DIVIDE & CONQUER.svg", {}, -1 }, { "/nonlinearcircuits/res/NLC - DIVINE CMOS.svg", {}, -1 }, - { "/nonlinearcircuits/res/DoubleNeuronRef.svg", {}, -1 }, { "/nonlinearcircuits/res/NLC - GENiE.svg", {}, -1 }, - { "/nonlinearcircuits/res/LetsSplosh.svg", {}, -1 }, { "/nonlinearcircuits/res/NLC - NEURON.svg", {}, -1 }, { "/nonlinearcircuits/res/NLC - NUMBERWANG.svg", {}, -1 }, { "/nonlinearcircuits/res/NLC - SEGUE.svg", {}, -1 }, - { "/nonlinearcircuits/res/squid-axon-papernoise-panel2.svg", {}, -1 }, { "/nonlinearcircuits/res/NLC - STATUES.svg", {}, -1 }, + { "/nonlinearcircuits/res/squid-axon-papernoise-panel2.svg", {}, -1 }, // Custom, runtime dark mode used with permission { "/ParableInstruments/res/Neil.svg", {}, -1 }, // GPL-3.0-or-later { "/PathSet/res/AstroVibe.svg", {}, -1 }, + { "/PathSet/res/GlassPane.svg", {}, -1 }, { "/PathSet/res/IceTray.svg", {}, -1 }, + { "/PathSet/res/Nudge.svg", {}, -1 }, + { "/PathSet/res/ShiftyExpander.svg", {}, -1 }, { "/PathSet/res/ShiftyMod.svg", {}, -1 }, // BSD-3-Clause { "/voxglitch/res/autobreak_front_panel.svg", {}, -1 }, @@ -308,15 +324,171 @@ static const struct { { "/voxglitch/res/wav_bank_front_panel.svg", {}, -1 }, { "/voxglitch/res/wav_bank_mc_front_panel_v2.svg", {}, -1 }, { "/voxglitch/res/xy_front_panel.svg", {}, -1 }, + // WTFPL + { "/WhatTheRack/res/WhatTheJack.svg", {}, -1 }, + { "/WhatTheRack/res/WhatTheMod.svg", {}, -1 }, + { "/WhatTheRack/res/WhatTheRack.svg", {}, -1 }, }; -static inline bool invertPaint(NSVGshape* const shape, NSVGpaint& paint, const char* const svgFileToInvert = nullptr) +static const struct { + const char* const filename; + const char* shapeIdsToIgnore[5]; + const int shapeNumberToIgnore; +} svgFilesToInvertForLightMode[] = { + // GPLv3+ + /* FIXME does not work very well + { "/Autinn/res/AmpModule.svg", {}, -1 }, + { "/Autinn/res/BassModule.svg", {}, -1 }, + { "/Autinn/res/CVConverterModule.svg", {}, -1 }, + { "/Autinn/res/ComponentLibrary", {}, -1 }, + { "/Autinn/res/DeadbandModule.svg", {}, -1 }, + { "/Autinn/res/DigiModule.svg", {}, -1 }, + { "/Autinn/res/DiseeModule.svg", {}, -1 }, + { "/Autinn/res/FilModule.svg", {}, -1 }, + { "/Autinn/res/FlopperModule.svg", {}, -1 }, + { "/Autinn/res/ImpModule.svg", {}, -1 }, + { "/Autinn/res/JetteModule.svg", {}, -1 }, + { "/Autinn/res/MelodyModule.svg", {}, -1 }, + { "/Autinn/res/MeraModule.svg", {}, -1 }, + { "/Autinn/res/Mixer6Module.svg", {}, -1 }, + { "/Autinn/res/NapModule.svg", {}, -1 }, + { "/Autinn/res/NonModule.svg", {}, -1 }, + { "/Autinn/res/OxcartModule.svg", {}, -1 }, + { "/Autinn/res/RebelModule.svg", {}, -1 }, + { "/Autinn/res/RetriModule.svg", {}, -1 }, + { "/Autinn/res/SawModule.svg", {}, -1 }, + { "/Autinn/res/SjipModule.svg", {}, -1 }, + { "/Autinn/res/SquareModule.svg", {}, -1 }, + { "/Autinn/res/VibratoModule.svg", {}, -1 }, + { "/Autinn/res/VxyModule.svg", {}, -1 }, + { "/Autinn/res/ZodModule.svg", {}, -1 }, + */ + // ??? used for testing, might get turned off + { "/Befaco/res/components/Knurlie.svg", {}, -1 }, + { "/Befaco/res/panels/ABC.svg", {}, -1 }, + { "/Befaco/res/panels/ADSR.svg", {}, -1 }, + { "/Befaco/res/panels/ChoppingKinky.svg", {}, -1 }, + { "/Befaco/res/panels/DualAtenuverter.svg", {}, -1 }, + { "/Befaco/res/panels/EvenVCO.svg", {}, -1 }, + { "/Befaco/res/panels/HexmixVCA.svg", {}, -1 }, + { "/Befaco/res/panels/Kickall.svg", {}, -1 }, + { "/Befaco/res/panels/Mex.svg", {}, -1 }, + { "/Befaco/res/panels/Mixer.svg", {}, -1 }, + { "/Befaco/res/panels/Morphader.svg", {}, -1 }, + { "/Befaco/res/panels/Muxlicer.svg", {}, -1 }, + { "/Befaco/res/panels/NoisePlethora.svg", {}, -1 }, + { "/Befaco/res/panels/Percall.svg", {}, -1 }, + { "/Befaco/res/panels/Rampage.svg", {}, -1 }, + { "/Befaco/res/panels/STMix.svg", {}, -1 }, + { "/Befaco/res/panels/SamplingModulator.svg", {}, -1 }, + { "/Befaco/res/panels/SlewLimiter.svg", {}, -1 }, + { "/Befaco/res/panels/SpringReverb.svg", {}, -1 }, + { "/Befaco/res/panels/StereoStrip.svg", {}, -1 }, + // GPLv3+ + { "/Cardinal/res/AudioFile.svg", {}, -1 }, + { "/Cardinal/res/AudioToCVPitch.svg", {}, -1 }, + { "/Cardinal/res/Carla.svg", {}, -1 }, + { "/Cardinal/res/ExpanderMIDI.svg", {}, -1 }, + { "/Cardinal/res/glBars.svg", {}, -1 }, + { "/Cardinal/res/HostAudio.svg", {}, -1 }, + { "/Cardinal/res/HostCV.svg", {}, -1 }, + { "/Cardinal/res/HostMIDI.svg", {}, -1 }, + { "/Cardinal/res/HostMIDICC.svg", {}, -1 }, + { "/Cardinal/res/HostMIDIGate.svg", {}, -1 }, + { "/Cardinal/res/HostMIDIMap.svg", {}, -1 }, + { "/Cardinal/res/HostParameters.svg", {}, -1 }, + { "/Cardinal/res/HostParamsMap.svg", {}, -1 }, + { "/Cardinal/res/HostTime.svg", {}, -1 }, + { "/Cardinal/res/Ildaeil.svg", {}, -1 }, + // GPLv3+ + { "/forsitan-modulare/res/alea.svg", {}, -1 }, + { "/forsitan-modulare/res/cumuli.svg", {}, -1 }, + { "/forsitan-modulare/res/deinde.svg", {}, -1 }, + { "/forsitan-modulare/res/interea.svg", {}, -1 }, + { "/forsitan-modulare/res/palette.svg", {}, -1 }, + { "/forsitan-modulare/res/pavo.svg", {}, -1 }, + // GPLv3+ + { "/Fundamental/res/8vert.svg", {}, -1 }, + { "/Fundamental/res/ADSR.svg", {}, -1 }, + { "/Fundamental/res/Delay.svg", {}, -1 }, + { "/Fundamental/res/LFO.svg", {}, -1 }, + { "/Fundamental/res/Merge.svg", {}, -1 }, + { "/Fundamental/res/MidSide.svg", {}, -1 }, + { "/Fundamental/res/Mixer.svg", {}, -1 }, + { "/Fundamental/res/Mutes.svg", {}, -1 }, + { "/Fundamental/res/Noise.svg", {}, -1 }, + { "/Fundamental/res/Octave.svg", {}, -1 }, + { "/Fundamental/res/Pulses.svg", {}, -1 }, + { "/Fundamental/res/Quantizer.svg", {}, -1 }, + { "/Fundamental/res/Random.svg", {}, -1 }, + { "/Fundamental/res/SEQ3.svg", {}, -1 }, + { "/Fundamental/res/Scope.svg", {}, -1 }, + { "/Fundamental/res/SequentialSwitch1.svg", {}, -1 }, + { "/Fundamental/res/SequentialSwitch2.svg", {}, -1 }, + { "/Fundamental/res/Split.svg", {}, -1 }, + { "/Fundamental/res/Sum.svg", {}, -1 }, + { "/Fundamental/res/VCA-1.svg", {}, -1 }, + { "/Fundamental/res/VCA.svg", {}, -1 }, + { "/Fundamental/res/VCF.svg", {}, -1 }, + { "/Fundamental/res/VCMixer.svg", {}, -1 }, + { "/Fundamental/res/VCO.svg", {}, -1 }, + { "/Fundamental/res/WTLFO.svg", {}, -1 }, + { "/Fundamental/res/WTVCO.svg", {}, -1 }, + // MIT + { "/HamptonHarmonics/res/Arp.svg", {}, -1 }, + { "/HamptonHarmonics/res/Progress.svg", {}, -1 }, + // GPLv3+ + { "/LomasModules/res/AdvancedSampler.svg", {}, -1 }, + { "/LomasModules/res/GateSequencer.svg", {}, -1 }, + // GPLv3+ + { "/sonusmodular/res/addiction.svg", {}, -1 }, + { "/sonusmodular/res/bitter.svg", {}, -1 }, + { "/sonusmodular/res/bymidside.svg", {}, -1 }, + { "/sonusmodular/res/campione.svg", {}, -1 }, + { "/sonusmodular/res/chainsaw.svg", {}, -1 }, + { "/sonusmodular/res/ctrl.svg", {}, -1 }, + { "/sonusmodular/res/deathcrush.svg", {}, -1 }, + { "/sonusmodular/res/fraction.svg", {}, -1 }, + { "/sonusmodular/res/harmony.svg", {}, -1 }, + { "/sonusmodular/res/ladrone.svg", {}, -1 }, + { "/sonusmodular/res/luppolo.svg", {}, -1 }, + { "/sonusmodular/res/luppolo3.svg", {}, -1 }, + { "/sonusmodular/res/micromacro.svg", {}, -1 }, + { "/sonusmodular/res/mrcheb.svg", {}, -1 }, + { "/sonusmodular/res/multimulti.svg", {}, -1 }, + { "/sonusmodular/res/neurosc.svg", {}, -1 }, + { "/sonusmodular/res/oktagon.svg", {}, -1 }, + { "/sonusmodular/res/osculum.svg", {}, -1 }, + { "/sonusmodular/res/paramath.svg", {}, -1 }, + { "/sonusmodular/res/piconoise.svg", {}, -1 }, + { "/sonusmodular/res/pith.svg", {}, -1 }, + { "/sonusmodular/res/pusher.svg", {}, -1 }, + { "/sonusmodular/res/ringo.svg", {}, -1 }, + { "/sonusmodular/res/scramblase.svg", {}, -1 }, + { "/sonusmodular/res/tropicana.svg", {}, -1 }, + { "/sonusmodular/res/twoff.svg", {}, -1 }, + { "/sonusmodular/res/yabp.svg", {}, -1 }, + // TODO bacon, chowdsp, ??? +}; + +static inline +unsigned int invertColor(const unsigned int color) noexcept +{ + return (color & 0xff000000) + | (0xff0000 - (color & 0xff0000)) + | (0xff00 - (color & 0xff00)) + | (0xff - (color & 0xff)); +} + +static inline +bool invertPaintForDarkMode(NSVGshape* const shape, NSVGpaint& paint, const char* const svgFileToInvert = nullptr) { if (paint.type == NSVG_PAINT_LINEAR_GRADIENT && svgFileToInvert != nullptr) { // Special case for DrumKit background gradient if (std::strncmp(svgFileToInvert, "/DrumKit/", 9) == 0) { + std::free(paint.gradient); paint.type = NSVG_PAINT_COLOR; paint.color = 0xff191919; return true; @@ -445,56 +617,78 @@ static inline bool invertPaint(NSVGshape* const shape, NSVGpaint& paint, const c // Special case for PathSet colors if (svgFileToInvert != nullptr && std::strncmp(svgFileToInvert, "/PathSet/", 9) == 0) { - switch (paint.color) + // only invert main colors for Nudge.svg + if (std::strcmp(svgFileToInvert, "/PathSet/res/Nudge.svg") == 0) { - // main blue tone - case 0xffdf7a1a: - if (shape->opacity == 0.5f && std::strcmp(svgFileToInvert, "/PathSet/res/AstroVibe.svg") == 0) + switch (paint.color) { - shape->opacity = 0.2f; + case 0xffe6e6e6: + paint.color = 0xff191919; + return true; + case 0xff000000: + paint.color = 0xffffffff; return true; + default: + return false; } - if (shape->opacity == 0.25f) - shape->opacity = 0.75f; - return false; - // bottom logo stuff, set to full white - case 0xff000000: - if (shape->stroke.type != NSVG_PAINT_NONE) + } + // everything else + else + { + switch (paint.color) { - paint.color = 0xffffffff; + // main blue tone + case 0xffdf7a1a: + if (shape->opacity == 0.5f && std::strcmp(svgFileToInvert, "/PathSet/res/AstroVibe.svg") == 0) + { + shape->opacity = 0.2f; + return true; + } + if (shape->opacity == 0.25f) + shape->opacity = 0.75f; + return false; + // bottom logo stuff, set to full white + case 0xff000000: + if (shape->stroke.type != NSVG_PAINT_NONE) + { + paint.color = 0xffffffff; + return true; + } + break; + // pink step 2 (pink with 50% opacity on bg) + case 0xffef73ea: + paint.color = 0xff812d7d; + return true; + // pink step 3 (pink with 33.3% opacity on bg) + case 0xfff49ff0: + paint.color = 0xff4d234c; + return true; + // pink and orange + case 0xffe941e2: + case 0xff698efb: + // pink and orange (translucent) + case 0x4de941e2: + case 0x62698efb: + return false; + // blue darker 1 (blue with 50% opacity on bg) + case 0xffde944f: + case 0xffe3b080: + case 0xffe4cbb3: + case 0xfff5c99f: + case 0xfff6d1b0: + paint.color = 0xff7c4919; + return true; + // blue darker 2 (blue with 33.3% opacity on bg) + case 0xffe5d9cd: + case 0xfff8dcc2: + case 0xffe1a265: + paint.color = 0xff5b3a1a; + return true; + // blue darker 3 (blue with 25% opacity on bg) + case 0xffe5cbb3: + paint.color = 0xff4b321a; return true; } - break; - // pink step 2 (pink with 50% opacity on bg) - case 0xffef73ea: - paint.color = 0xff812d7d; - return true; - // pink step 3 (pink with 33.3% opacity on bg) - case 0xfff49ff0: - paint.color = 0xff4d234c; - return true; - // pink and orange - case 0xffe941e2: - case 0xff698efb: - return false; - // blue darker 1 (blue with 50% opacity on bg) - case 0xffde944f: - case 0xffe3b080: - case 0xffe4cbb3: - case 0xfff5c99f: - case 0xfff6d1b0: - paint.color = 0xff7c4919; - return true; - // blue darker 2 (blue with 33.3% opacity on bg) - case 0xffe5d9cd: - case 0xfff8dcc2: - case 0xffe1a265: - paint.color = 0xff5b3a1a; - return true; - // blue darker 3 (blue with 25% opacity on bg) - case 0xffe5cbb3: - paint.color = 0xff4b321a; - return true; } } @@ -520,6 +714,7 @@ static inline bool invertPaint(NSVGshape* const shape, NSVGpaint& paint, const c { // scopes or other special things (do nothing) case 0x40ffffff: + case 0xff0000aa: case 0xff004200: case 0xff2b281e: case 0xff2d2827: @@ -550,26 +745,180 @@ static inline bool invertPaint(NSVGshape* const shape, NSVGpaint& paint, const c return true; // all others (direct invert) default: - paint.color = (paint.color & 0xff000000) - | (0xff0000 - (paint.color & 0xff0000)) - | (0xff00 - (paint.color & 0xff00)) - | (0xff - (paint.color & 0xff)); + paint.color = invertColor(paint.color); + return true; + } +} + +static inline +bool invertPaintForLightMode(NSVGshape* const shape, NSVGpaint& paint) +{ + switch(paint.type) + { + case NSVG_PAINT_NONE: + return true; + case NSVG_PAINT_LINEAR_GRADIENT: + for (int i=0; instops; ++i) + paint.gradient->stops[i].color = invertColor(paint.gradient->stops[i].color); + return true; + case NSVG_PAINT_COLOR: + paint.color = invertColor(paint.color); return true; + default: + return false; } } extern "C" { NSVGimage* nsvgParseFromFileCardinal(const char* filename, const char* units, float dpi); +void nsvgDeleteCardinal(NSVGimage*); +} + +struct ExtendedNSVGimage { + NSVGimage* const handle; + NSVGimage* handleOrig; + NSVGimage* handleMOD; + NSVGshape* shapesOrig; + NSVGshape* shapesMOD; +}; + +static std::list loadedDarkSVGs; +static std::list loadedLightSVGs; + +static inline +void nsvg__duplicatePaint(NSVGpaint& dst, NSVGpaint& src) +{ + if (dst.type == NSVG_PAINT_LINEAR_GRADIENT || dst.type == NSVG_PAINT_RADIAL_GRADIENT) + { + const size_t size = sizeof(NSVGgradient) + sizeof(NSVGgradientStop)*(src.gradient->nstops-1); + dst.gradient = static_cast(malloc(size)); + std::memcpy(dst.gradient, src.gradient, size); + } +} + +static inline +NSVGshape* nsvg__duplicateShapes(NSVGshape* const orig) +{ + NSVGshape* const dup = static_cast(malloc(sizeof(NSVGshape))); + std::memcpy(dup, orig, sizeof(NSVGshape)); + nsvg__duplicatePaint(dup->fill, orig->fill); + nsvg__duplicatePaint(dup->stroke, orig->stroke); + + for (NSVGshape* shape2 = dup;;) + { + if (shape2->next == nullptr) + break; + + NSVGshape* const shapedup = static_cast(malloc(sizeof(NSVGshape))); + std::memcpy(shapedup, shape2->next, sizeof(NSVGshape)); + nsvg__duplicatePaint(shapedup->fill, shape2->next->fill); + nsvg__duplicatePaint(shapedup->stroke, shape2->next->stroke); + shape2->next = shapedup; + shape2 = shapedup; + } + + return dup; +} + +static inline +void deleteExtendedNSVGimage(ExtendedNSVGimage& ext) +{ + if (ext.shapesMOD != nullptr) + { + // delete duplicated resources + for (NSVGshape *next, *shape = ext.shapesMOD;;) + { + next = shape->next; + + nsvg__deletePaint(&shape->fill); + nsvg__deletePaint(&shape->stroke); + std::free(shape); + + if (next == nullptr) + break; + + shape = next; + } + + // revert shapes back to original + ext.handle->shapes = ext.shapesOrig; + ext.shapesMOD = nullptr; + } + + if (ext.handleMOD != nullptr) + { + nsvgDelete(ext.handleMOD); + ext.handleMOD = nullptr; + } + + if (ext.handleOrig != nullptr) + { + std::memcpy(ext.handle, ext.handleOrig, sizeof(NSVGimage)); + std::free(ext.handleOrig); + ext.handleOrig = nullptr; + } } NSVGimage* nsvgParseFromFileCardinal(const char* const filename, const char* const units, const float dpi) { if (NSVGimage* const handle = nsvgParseFromFile(filename, units, dpi)) { - for (size_t i = 0; i < sizeof(svgFilesToInvert)/sizeof(svgFilesToInvert[0]); ++i) + const size_t filenamelen = std::strlen(filename); + + bool hasDarkMode = false; + bool hasLightMode = false; + NSVGimage* handleOrig; + NSVGimage* handleMOD = nullptr; + NSVGshape* shapesOrig; + NSVGshape* shapesMOD; + + // Special case for light/dark screws + if (std::strncmp(filename + (filenamelen-16), "/ScrewSilver.svg", 16) == 0) { - const char* const svgFileToInvert = svgFilesToInvert[i].filename; - const size_t filenamelen = std::strlen(filename); + const std::string blackfilename = std::string(filename).substr(0, filenamelen-10) + "Black.svg"; + hasDarkMode = true; + shapesOrig = shapesMOD = nullptr; + handleMOD = nsvgParseFromFile(blackfilename.c_str(), units, dpi); + goto postparse; + } + + if (std::strncmp(filename + (filenamelen-15), "/ScrewBlack.svg", 15) == 0) + { + const std::string silverfilename = std::string(filename).substr(0, filenamelen-9) + "Silver.svg"; + hasLightMode = true; + shapesOrig = shapesMOD = nullptr; + handleMOD = nsvgParseFromFile(silverfilename.c_str(), units, dpi); + goto postparse; + } + +#if 0 + // Special case for GlueTheGiant + if (std::strstr(filename, "/GlueTheGiant/res/") != nullptr) + { + printf("special hack for glue\n"); + if (std::strncmp(filename + (filenamelen - 13), "/BusDepot.svg", 13) == 0 || + std::strncmp(filename + (filenamelen - 13), "/BusRoute.svg", 13) == 0 || + std::strncmp(filename + (filenamelen - 13), "/EnterBus.svg", 13) == 0 || + std::strncmp(filename + (filenamelen - 12), "/ExitBus.svg", 12) == 0 || + std::strncmp(filename + (filenamelen - 11), "/GigBus.svg", 11) == 0 || + std::strncmp(filename + (filenamelen - 17), "/MetroCityBus.svg", 17) == 0 || + std::strncmp(filename + (filenamelen - 12), "/MiniBus.svg", 12) == 0 || + std::strncmp(filename + (filenamelen - 9), "/Road.svg", 9) == 0 || + std::strncmp(filename + (filenamelen - 14), "/SchoolBus.svg", 14) == 0) + { + const std::string nightfilename = std::string(filename).substr(0, filenamelen-4) + "_Night.svg"; + hasDarkMode = true; + shapesOrig = shapesMOD = nullptr; + handleMOD = nsvgParseFromFile(nightfilename.c_str(), units, dpi); + printf("special hack for glue: %s -> %s\n", filename, nightfilename.c_str()); + goto postparse; + } + } +#endif + + for (size_t i = 0; i < sizeof(svgFilesToInvertForDarkMode)/sizeof(svgFilesToInvertForDarkMode[0]); ++i) + { + const char* const svgFileToInvert = svgFilesToInvertForDarkMode[i].filename; const size_t filterlen = std::strlen(svgFileToInvert); if (filenamelen < filterlen) @@ -577,11 +926,17 @@ NSVGimage* nsvgParseFromFileCardinal(const char* const filename, const char* con if (std::strncmp(filename + (filenamelen-filterlen), svgFileToInvert, filterlen) != 0) continue; - const char* const* const shapeIdsToIgnore = svgFilesToInvert[i].shapeIdsToIgnore; - const int shapeNumberToIgnore = svgFilesToInvert[i].shapeNumberToIgnore; + const char* const* const shapeIdsToIgnore = svgFilesToInvertForDarkMode[i].shapeIdsToIgnore; + const int shapeNumberToIgnore = svgFilesToInvertForDarkMode[i].shapeNumberToIgnore; int shapeCounter = 0; - for (NSVGshape* shape = handle->shapes; shape != nullptr; shape = shape->next, ++shapeCounter) + hasDarkMode = true; + handleMOD = nullptr; + shapesOrig = handle->shapes; + shapesMOD = nsvg__duplicateShapes(shapesOrig); + + // shape paint inversion + for (NSVGshape* shape = shapesMOD; shape != nullptr; shape = shape->next, ++shapeCounter) { if (shapeNumberToIgnore == shapeCounter) continue; @@ -598,11 +953,37 @@ NSVGimage* nsvgParseFromFileCardinal(const char* const filename, const char* con if (ignore) continue; - if (invertPaint(shape, shape->fill, svgFileToInvert)) - invertPaint(shape, shape->stroke, svgFileToInvert); + if (invertPaintForDarkMode(shape, shape->fill, svgFileToInvert)) + invertPaintForDarkMode(shape, shape->stroke, svgFileToInvert); + } + + goto postparse; + } + + for (size_t i = 0; i < sizeof(svgFilesToInvertForLightMode)/sizeof(svgFilesToInvertForLightMode[0]); ++i) + { + const char* const svgFileToInvert = svgFilesToInvertForLightMode[i].filename; + const size_t filenamelen = std::strlen(filename); + const size_t filterlen = std::strlen(svgFileToInvert); + + if (filenamelen < filterlen) + continue; + if (std::strncmp(filename + (filenamelen-filterlen), svgFileToInvert, filterlen) != 0) + continue; + + hasLightMode = true; + handleMOD = nullptr; + shapesOrig = handle->shapes; + shapesMOD = nsvg__duplicateShapes(shapesOrig); + + // shape paint inversion + for (NSVGshape* shape = shapesMOD; shape != nullptr; shape = shape->next) + { + if (invertPaintForLightMode(shape, shape->fill)) + invertPaintForLightMode(shape, shape->stroke); } - return handle; + goto postparse; } // Special case for AmalgamatedHarmonics background color @@ -610,8 +991,123 @@ NSVGimage* nsvgParseFromFileCardinal(const char* const filename, const char* con if (std::strstr(filename, "/AmalgamatedHarmonics/") != nullptr) handle->shapes->fill.color = 0xff191919; +postparse: + if (handleMOD != nullptr) + { + handleOrig = static_cast(malloc(sizeof(NSVGimage))); + std::memcpy(handleOrig, handle, sizeof(NSVGimage)); + } + else + { + handleOrig = nullptr; + } + + if (hasDarkMode) + { + const ExtendedNSVGimage ext = { handle, handleOrig, handleMOD, shapesOrig, shapesMOD }; + loadedDarkSVGs.push_back(ext); + + if (rack::settings::darkMode) + { + if (shapesMOD != nullptr) + handle->shapes = shapesMOD; + else if (handleMOD != nullptr) + std::memcpy(handle, handleMOD, sizeof(NSVGimage)); + } + } + + if (hasLightMode) + { + const ExtendedNSVGimage ext = { handle, handleOrig, handleMOD, shapesOrig, shapesMOD }; + loadedLightSVGs.push_back(ext); + + if (!rack::settings::darkMode) + { + if (shapesMOD != nullptr) + handle->shapes = shapesMOD; + else if (handleMOD != nullptr) + std::memcpy(handle, handleMOD, sizeof(NSVGimage)); + } + } + return handle; } return nullptr; } + +void nsvgDeleteCardinal(NSVGimage* const handle) +{ + for (auto it = loadedDarkSVGs.begin(), end = loadedDarkSVGs.end(); it != end; ++it) + { + ExtendedNSVGimage& ext(*it); + + if (ext.handle != handle) + continue; + + deleteExtendedNSVGimage(ext); + loadedDarkSVGs.erase(it); + break; + } + + for (auto it = loadedLightSVGs.begin(), end = loadedLightSVGs.end(); it != end; ++it) + { + ExtendedNSVGimage& ext(*it); + + if (ext.handle != handle) + continue; + + deleteExtendedNSVGimage(ext); + loadedLightSVGs.erase(it); + break; + } + + nsvgDelete(handle); +} + +void switchDarkMode(const bool darkMode) +{ + if (rack::settings::darkMode == darkMode) + return; + + rack::settings::darkMode = darkMode; + + for (ExtendedNSVGimage& ext : loadedDarkSVGs) + { + if (ext.shapesMOD != nullptr) + ext.handle->shapes = darkMode ? ext.shapesMOD : ext.shapesOrig; + else if (ext.handleMOD != nullptr) + std::memcpy(ext.handle, darkMode ? ext.handleMOD : ext.handleOrig, sizeof(NSVGimage)); + } + + for (ExtendedNSVGimage& ext : loadedLightSVGs) + { + if (ext.shapesMOD != nullptr) + ext.handle->shapes = !darkMode ? ext.shapesMOD : ext.shapesOrig; + else if (ext.handleMOD != nullptr) + std::memcpy(ext.handle, !darkMode ? ext.handleMOD : ext.handleOrig, sizeof(NSVGimage)); + } +} + +namespace rack { +namespace asset { + +void destroy() { + for (auto it = loadedDarkSVGs.begin(), end = loadedDarkSVGs.end(); it != end; ++it) + { + ExtendedNSVGimage& ext(*it); + deleteExtendedNSVGimage(ext); + } + + for (auto it = loadedLightSVGs.begin(), end = loadedLightSVGs.end(); it != end; ++it) + { + ExtendedNSVGimage& ext(*it); + deleteExtendedNSVGimage(ext); + } + + loadedDarkSVGs.clear(); + loadedLightSVGs.clear(); +} + +} +} diff --git a/src/custom/glfw.cpp b/src/custom/glfw.cpp new file mode 100644 index 00000000..250586e9 --- /dev/null +++ b/src/custom/glfw.cpp @@ -0,0 +1,207 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +#include "Application.hpp" +#include "PluginContext.hpp" + +#include + +typedef struct GLFWcursor { + DGL_NAMESPACE::MouseCursor cursorId; +} GLFWcursor; + +GLFWAPI int glfwGetKeyScancode(int) { return 0; } + +GLFWAPI const char* glfwGetClipboardString(GLFWwindow*) +{ + CardinalPluginContext* const context = static_cast(APP); + DISTRHO_SAFE_ASSERT_RETURN(context != nullptr, nullptr); + DISTRHO_SAFE_ASSERT_RETURN(context->ui != nullptr, nullptr); + + size_t dataSize; + return static_cast(context->ui->getClipboard(dataSize)); +} + +GLFWAPI void glfwSetClipboardString(GLFWwindow*, const char* const text) +{ + DISTRHO_SAFE_ASSERT_RETURN(text != nullptr,); + + CardinalPluginContext* const context = static_cast(APP); + DISTRHO_SAFE_ASSERT_RETURN(context != nullptr,); + DISTRHO_SAFE_ASSERT_RETURN(context->ui != nullptr,); + + context->ui->setClipboard(nullptr, text, std::strlen(text)+1); +} + +GLFWAPI GLFWcursor* glfwCreateStandardCursor(const int shape) +{ + static GLFWcursor cursors[] = { + { kMouseCursorArrow }, // GLFW_ARROW_CURSOR + { kMouseCursorCaret }, // GLFW_IBEAM_CURSOR + { kMouseCursorCrosshair }, // GLFW_CROSSHAIR_CURSOR + { kMouseCursorHand }, // GLFW_POINTING_HAND_CURSOR + { kMouseCursorNotAllowed }, // GLFW_NOT_ALLOWED_CURSOR + { kMouseCursorLeftRight }, // GLFW_RESIZE_EW_CURSOR + { kMouseCursorUpDown }, // GLFW_RESIZE_NS_CURSOR + { kMouseCursorDiagonal }, // GLFW_RESIZE_NWSE_CURSOR + { kMouseCursorAntiDiagonal }, // GLFW_RESIZE_NESW_CURSOR + // NOTE GLFW_RESIZE_ALL_CURSOR is unsupported in pugl + }; + + switch (shape) + { + case GLFW_ARROW_CURSOR: + return &cursors[kMouseCursorArrow]; + case GLFW_IBEAM_CURSOR: + return &cursors[kMouseCursorCaret]; + case GLFW_CROSSHAIR_CURSOR: + return &cursors[kMouseCursorCrosshair]; + case GLFW_POINTING_HAND_CURSOR: + return &cursors[kMouseCursorHand]; + case GLFW_NOT_ALLOWED_CURSOR: + return &cursors[kMouseCursorNotAllowed]; + case GLFW_RESIZE_EW_CURSOR: + return &cursors[kMouseCursorLeftRight]; + case GLFW_RESIZE_NS_CURSOR: + return &cursors[kMouseCursorUpDown]; + case GLFW_RESIZE_NWSE_CURSOR: + return &cursors[kMouseCursorDiagonal]; + case GLFW_RESIZE_NESW_CURSOR: + return &cursors[kMouseCursorAntiDiagonal]; + default: + return nullptr; + } +} + +GLFWAPI void glfwSetCursor(GLFWwindow*, GLFWcursor* const cursor) +{ + CardinalPluginContext* const context = static_cast(APP); + DISTRHO_SAFE_ASSERT_RETURN(context != nullptr,); + DISTRHO_SAFE_ASSERT_RETURN(context->ui != nullptr,); + + context->ui->setCursor(cursor != nullptr ? cursor->cursorId : kMouseCursorArrow); +} + +GLFWAPI double glfwGetTime(void) +{ + CardinalPluginContext* const context = static_cast(APP); + DISTRHO_SAFE_ASSERT_RETURN(context != nullptr, 0.0); + DISTRHO_SAFE_ASSERT_RETURN(context->ui != nullptr, 0.0); + + return context->ui->getApp().getTime(); +} + +GLFWAPI const char* glfwGetKeyName(const int key, int) +{ + switch (key) + { + case '\"': return "\""; + case '\'': return "\'"; + case '\\': return "\\"; + case ' ': return " "; + case '!': return "!"; + case '#': return "#"; + case '$': return "$"; + case '%': return "%"; + case '&': return "&"; + case '(': return "("; + case ')': return ")"; + case '*': return "*"; + case '+': return "+"; + case ',': return ","; + case '-': return "-"; + case '.': return "."; + case '/': return "/"; + case '0': return "0"; + case '1': return "1"; + case '2': return "2"; + case '3': return "3"; + case '4': return "4"; + case '5': return "5"; + case '6': return "6"; + case '7': return "7"; + case '8': return "8"; + case '9': return "9"; + case ':': return ":"; + case ';': return ";"; + case '<': return "<"; + case '=': return "="; + case '>': return ">"; + case '?': return "?"; + case '@': return "@"; + /* Rack expects lowercase, forced below + case 'A': return "A"; + case 'B': return "B"; + case 'C': return "C"; + case 'D': return "D"; + case 'E': return "E"; + case 'F': return "F"; + case 'G': return "G"; + case 'H': return "H"; + case 'I': return "I"; + case 'J': return "J"; + case 'K': return "K"; + case 'L': return "L"; + case 'M': return "M"; + case 'N': return "N"; + case 'O': return "O"; + case 'P': return "P"; + case 'Q': return "Q"; + case 'R': return "R"; + case 'S': return "S"; + case 'T': return "T"; + case 'U': return "U"; + case 'V': return "V"; + case 'W': return "W"; + case 'X': return "X"; + case 'Y': return "Y"; + case 'Z': return "Z"; + */ + case '[': return "["; + case ']': return "]"; + case '^': return "^"; + case '_': return "_"; + case '`': return "`"; + case 'a': case 'A': return "a"; + case 'b': case 'B': return "b"; + case 'c': case 'C': return "c"; + case 'd': case 'D': return "d"; + case 'e': case 'E': return "e"; + case 'f': case 'F': return "f"; + case 'g': case 'G': return "g"; + case 'h': case 'H': return "h"; + case 'i': case 'I': return "i"; + case 'j': case 'J': return "j"; + case 'k': case 'K': return "k"; + case 'l': case 'L': return "l"; + case 'm': case 'M': return "m"; + case 'n': case 'N': return "n"; + case 'o': case 'O': return "o"; + case 'p': case 'P': return "p"; + case 'q': case 'Q': return "q"; + case 'r': case 'R': return "r"; + case 's': case 'S': return "s"; + case 't': case 'T': return "t"; + case 'u': case 'U': return "u"; + case 'v': case 'V': return "v"; + case 'w': case 'W': return "w"; + case 'x': case 'X': return "x"; + case 'y': case 'Y': return "y"; + case 'z': case 'Z': return "z"; + default: return nullptr; + } +} diff --git a/src/custom/osdialog.cpp b/src/custom/osdialog.cpp index 39d7452d..f881ad8d 100644 --- a/src/custom/osdialog.cpp +++ b/src/custom/osdialog.cpp @@ -1,6 +1,6 @@ /* * DISTRHO Cardinal Plugin - * Copyright (C) 2021 Filipe Coelho + * Copyright (C) 2021-2022 Filipe Coelho * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -17,17 +17,22 @@ #include +#include "DistrhoUtils.hpp" + char* osdialog_file(osdialog_file_action action, const char* path, const char* filename, osdialog_filters* filters) { + d_stderr2("[Cardinal] osdialog_file called %d %s %s", action, path, filename); return nullptr; } int osdialog_message(osdialog_message_level level, osdialog_message_buttons buttons, const char* message) { + d_stderr2("[Cardinal] osdialog_message called %d %d %s", level, buttons, message); return 0; } char* osdialog_prompt(osdialog_message_level level, const char* message, const char* text) { + d_stderr2("[Cardinal] osdialog_prompt called %d %s %s", level, message, text); return nullptr; } diff --git a/src/emscripten/WasmUtils.cpp b/src/emscripten/WasmUtils.cpp new file mode 100644 index 00000000..09b30ec4 --- /dev/null +++ b/src/emscripten/WasmUtils.cpp @@ -0,0 +1,36 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +#include + +// ----------------------------------------------------------------------------------------------------------- + +namespace CardinalDISTRHO { + +long d_emscripten_set_interval(void (*cb)(void* userData), double intervalMsecs, void* userData) +{ + return emscripten_set_interval(cb, intervalMsecs, userData); +} + +void d_emscripten_clear_interval(long setIntervalId) +{ + emscripten_clear_interval(setIntervalId); +} + +} + +// ----------------------------------------------------------------------------------------------------------- diff --git a/src/emscripten/htaccess b/src/emscripten/htaccess new file mode 100644 index 00000000..b47b6ab4 --- /dev/null +++ b/src/emscripten/htaccess @@ -0,0 +1,13 @@ +RewriteEngine on +RewriteCond %{HTTP:Accept-Encoding} gzip +RewriteCond %{REQUEST_URI} .*\.(data|js|wasm) +#RewriteCond %{REQUEST_FILENAME}.gz -s +RewriteRule ^(.+) $1.gz +RewriteRule "\.data\.gz$" "-" [T=application/octet-stream,E=no-brotli,E=no-gzip] +RewriteRule "\.js\.gz$" "-" [T=application/javascript,E=no-brotli,E=no-gzip] +RewriteRule "\.wasm\.gz$" "-" [T=application/wasm,E=no-brotli,E=no-gzip] + + + Header set Content-Encoding gzip + Header append Vary Accept-Encoding + diff --git a/src/emscripten/patchstorage.php b/src/emscripten/patchstorage.php new file mode 100644 index 00000000..b73b6b6d --- /dev/null +++ b/src/emscripten/patchstorage.php @@ -0,0 +1,43 @@ + diff --git a/src/emscripten/shell.html b/src/emscripten/shell.html new file mode 100644 index 00000000..8a372f87 --- /dev/null +++ b/src/emscripten/shell.html @@ -0,0 +1,201 @@ + + + + + + + + + Cardinal + + + +
+
+
Cardinal
+
+
+
Downloading...
+
+ +
+
+ + +
+ + + {{{ SCRIPT }}} + + diff --git a/src/extra/ScopedValueSetter.hpp b/src/extra/ScopedValueSetter.hpp new file mode 100644 index 00000000..93472410 --- /dev/null +++ b/src/extra/ScopedValueSetter.hpp @@ -0,0 +1,90 @@ +/* + * Scope value setter, taken from JUCE v4 + * Copyright (C) 2013 Raw Material Software Ltd. + * Copyright (c) 2016 ROLI Ltd. + * Copyright (C) 2013-2020 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 2 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the doc/GPL.txt file. + */ + +#pragma once + +#include "DistrhoUtils.hpp" + +START_NAMESPACE_DISTRHO + +//===================================================================================================================== +/** + Helper class providing an RAII-based mechanism for temporarily setting and + then re-setting a value. + + E.g. @code + int x = 1; + + { + ScopedValueSetter setter (x, 2); + + // x is now 2 + } + + // x is now 1 again + + { + ScopedValueSetter setter (x, 3, 4); + + // x is now 3 + } + + // x is now 4 + @endcode +*/ +template +class ScopedValueSetter +{ +public: + /** Creates a ScopedValueSetter that will immediately change the specified value to the + given new value, and will then reset it to its original value when this object is deleted. + Must be used only for 'noexcept' compatible types. + */ + ScopedValueSetter(ValueType& valueToSet, ValueType newValue) noexcept + : value(valueToSet), + originalValue(valueToSet) + { + valueToSet = newValue; + } + + /** Creates a ScopedValueSetter that will immediately change the specified value to the + given new value, and will then reset it to be valueWhenDeleted when this object is deleted. + */ + ScopedValueSetter(ValueType& valueToSet, ValueType newValue, ValueType valueWhenDeleted) noexcept + : value(valueToSet), + originalValue(valueWhenDeleted) + { + valueToSet = newValue; + } + + ~ScopedValueSetter() noexcept + { + value = originalValue; + } + +private: + //================================================================================================================= + ValueType& value; + const ValueType originalValue; + + DISTRHO_DECLARE_NON_COPYABLE(ScopedValueSetter) + DISTRHO_PREVENT_HEAP_ALLOCATION +}; + +END_NAMESPACE_DISTRHO diff --git a/src/override/.generate-diffs.sh b/src/override/.generate-diffs.sh index 68b2646b..887e2933 100755 --- a/src/override/.generate-diffs.sh +++ b/src/override/.generate-diffs.sh @@ -10,4 +10,5 @@ diff -U3 ../Rack/src/app/MenuBar.cpp MenuBar.cpp > diffs/MenuBar.cpp.diff diff -U3 ../Rack/src/app/Scene.cpp Scene.cpp > diffs/Scene.cpp.diff diff -U3 ../Rack/src/engine/Engine.cpp Engine.cpp > diffs/Engine.cpp.diff diff -U3 ../Rack/src/plugin/Model.cpp Model.cpp > diffs/Model.cpp.diff +diff -U3 ../Rack/src/widget/OpenGlWidget.cpp OpenGlWidget.cpp > diffs/OpenGlWidget.cpp.diff diff -U3 ../Rack/src/window/Window.cpp Window.cpp > diffs/Window.cpp.diff diff --git a/src/override/Engine.cpp b/src/override/Engine.cpp index 2cdf7562..2a31fe87 100644 --- a/src/override/Engine.cpp +++ b/src/override/Engine.cpp @@ -79,6 +79,7 @@ struct Engine::Internal { int64_t blockFrame = 0; double blockTime = 0.0; int blockFrames = 0; + bool aboutToClose = false; #ifndef HEADLESS // Meter @@ -776,6 +777,8 @@ void Engine::prepareSaveModule(Module* module) { void Engine::prepareSave() { + if (internal->aboutToClose) + return; SharedLock lock(internal->mutex); for (Module* module : internal->modules) { Module::SaveEvent e; @@ -1175,5 +1178,10 @@ void Engine::startFallbackThread() { } +void Engine_setAboutToClose(Engine* const engine) { + engine->internal->aboutToClose = true; +} + + } // namespace engine } // namespace rack diff --git a/src/override/MenuBar.cpp b/src/override/MenuBar.cpp index ae98ddfe..1b2326ea 100644 --- a/src/override/MenuBar.cpp +++ b/src/override/MenuBar.cpp @@ -40,6 +40,7 @@ #include #include #include +#include #include #include #include @@ -50,13 +51,24 @@ #include #include +#include "../CardinalCommon.hpp" +#include "DistrhoStandaloneUtils.hpp" + #ifdef HAVE_LIBLO # include #endif -#include "../CardinalCommon.hpp" +void switchDarkMode(bool darkMode); namespace rack { +namespace asset { +std::string patchesPath(); +} + +namespace plugin { +void updateStaticPluginsDarkMode(); +} + namespace app { namespace menuBar { @@ -85,19 +97,41 @@ struct MenuButton : ui::Button { struct FileButton : MenuButton { const bool isStandalone; +#if !(defined(DISTRHO_OS_WASM) && defined(STATIC_BUILD)) + std::vector demoPatches; +#endif FileButton(const bool standalone) - : MenuButton(), isStandalone(standalone) {} + : MenuButton(), isStandalone(standalone) + { +#if !(defined(DISTRHO_OS_WASM) && defined(STATIC_BUILD)) + const std::string patchesDir = asset::patchesPath() + DISTRHO_OS_SEP_STR "examples"; + + if (system::isDirectory(patchesDir)) + { + demoPatches = system::getEntries(patchesDir); + std::sort(demoPatches.begin(), demoPatches.end(), [](const std::string& a, const std::string& b){ + return string::lowercase(a) < string::lowercase(b); + }); + } +#endif + } void onAction(const ActionEvent& e) override { ui::Menu* menu = createMenu(); menu->cornerFlags = BND_CORNER_TOP; menu->box.pos = getAbsoluteOffset(math::Vec(0, box.size.y)); - menu->addChild(createMenuItem("New", RACK_MOD_CTRL_NAME "+N", []() { +#ifndef DISTRHO_OS_WASM + const char* const NewShortcut = RACK_MOD_CTRL_NAME "+N"; +#else + const char* const NewShortcut = ""; +#endif + menu->addChild(createMenuItem("New", NewShortcut, []() { patchUtils::loadTemplateDialog(); })); +#ifndef DISTRHO_OS_WASM menu->addChild(createMenuItem("Open / Import...", RACK_MOD_CTRL_NAME "+O", []() { patchUtils::loadDialog(); })); @@ -110,12 +144,31 @@ struct FileButton : MenuButton { menu->addChild(createMenuItem("Save as / Export...", RACK_MOD_CTRL_NAME "+Shift+S", []() { patchUtils::saveAsDialog(); })); +#else + menu->addChild(createMenuItem("Import patch...", RACK_MOD_CTRL_NAME "+O", []() { + patchUtils::loadDialog(); + })); - menu->addChild(createMenuItem("Export uncompressed json...", "", []() { + menu->addChild(createMenuItem("Import selection...", "", [=]() { + patchUtils::loadSelectionDialog(); + }, false, true)); + + menu->addChild(createMenuItem("Save and download compressed", RACK_MOD_CTRL_NAME "+Shift+S", []() { + patchUtils::saveAsDialog(); + })); + + menu->addChild(createMenuItem("Save and download uncompressed", "", []() { patchUtils::saveAsDialogUncompressed(); })); +#endif + + menu->addChild(createMenuItem("Revert", RACK_MOD_CTRL_NAME "+" RACK_MOD_SHIFT_NAME "+O", []() { + patchUtils::revertDialog(); + }, APP->patch->path.empty())); #ifdef HAVE_LIBLO + menu->addChild(new ui::MenuSeparator); + if (patchUtils::isRemoteConnected()) { menu->addChild(createMenuItem("Deploy to MOD", "F7", []() { patchUtils::deployToRemote(); @@ -133,24 +186,56 @@ struct FileButton : MenuButton { } #endif - menu->addChild(createMenuItem("Revert", RACK_MOD_CTRL_NAME "+" RACK_MOD_SHIFT_NAME "+O", []() { - patchUtils::revertDialog(); - }, APP->patch->path.empty())); - +#ifndef DISTRHO_OS_WASM menu->addChild(new ui::MenuSeparator); // Load selection - menu->addChild(createMenuItem("Import selection", "", [=]() { + menu->addChild(createMenuItem("Import selection...", "", [=]() { patchUtils::loadSelectionDialog(); }, false, true)); + menu->addChild(createMenuItem("Export uncompressed json...", "", []() { + patchUtils::saveAsDialogUncompressed(); + })); +#endif + +#if !(defined(DISTRHO_OS_WASM) && defined(STATIC_BUILD)) + if (!demoPatches.empty()) + { + menu->addChild(new ui::MenuSeparator); + + menu->addChild(createSubmenuItem("Open Demo / Example project", "", [=](ui::Menu* const menu) { + for (std::string path : demoPatches) { + std::string label = system::getStem(path); + + for (size_t i=0, len=label.size(); iaddChild(createMenuItem(label, "", [path]() { + patchUtils::loadPathDialog(path, true); + })); + } + + menu->addChild(new ui::MenuSeparator); + + menu->addChild(createMenuItem("Open PatchStorage.com for more patches", "", []() { + patchUtils::openBrowser("https://patchstorage.com/platform/cardinal/"); + })); + })); + } +#endif + +#ifndef DISTRHO_OS_WASM if (isStandalone) { menu->addChild(new ui::MenuSeparator); menu->addChild(createMenuItem("Quit", RACK_MOD_CTRL_NAME "+Q", []() { APP->window->close(); })); - }; + } +#endif } }; @@ -423,12 +508,37 @@ struct KnobScrollSensitivitySlider : ui::Slider { }; +static void setAllFramebufferWidgetsDirty(widget::Widget* const widget) +{ + for (widget::Widget* child : widget->children) + { + if (widget::FramebufferWidget* const fbw = dynamic_cast(child)) + { + fbw->setDirty(); + break; + } + setAllFramebufferWidgetsDirty(child); + } +} + + struct ViewButton : MenuButton { void onAction(const ActionEvent& e) override { ui::Menu* menu = createMenu(); menu->cornerFlags = BND_CORNER_TOP; menu->box.pos = getAbsoluteOffset(math::Vec(0, box.size.y)); + menu->addChild(createMenuLabel("Appearance")); + + std::string darkModeText; + if (settings::darkMode) + darkModeText = CHECKMARK_STRING; + menu->addChild(createMenuItem("Dark Mode", darkModeText, []() { + switchDarkMode(!settings::darkMode); + plugin::updateStaticPluginsDarkMode(); + setAllFramebufferWidgetsDirty(APP->scene); + })); + menu->addChild(createBoolPtrMenuItem("Show tooltips", "", &settings::tooltips)); ZoomSlider* zoomSlider = new ZoomSlider; @@ -452,8 +562,18 @@ struct ViewButton : MenuButton { menu->addChild(haloBrightnessSlider); menu->addChild(new ui::MenuSeparator); + menu->addChild(createMenuLabel("Module dragging")); - // menu->addChild(createBoolPtrMenuItem("Hide cursor while dragging", "", &settings::allowCursorLock)); + menu->addChild(createBoolPtrMenuItem("Lock module positions", "", &settings::lockModules)); + + menu->addChild(createBoolPtrMenuItem("Auto-squeeze modules when dragging", "", &settings::squeezeModules)); + + menu->addChild(new ui::MenuSeparator); + menu->addChild(createMenuLabel("Parameters")); + +#ifdef DISTRHO_OS_WASM + menu->addChild(createBoolPtrMenuItem("Lock cursor while dragging", "", &settings::allowCursorLock)); +#endif static const std::vector knobModeLabels = { "Linear", @@ -477,12 +597,21 @@ struct ViewButton : MenuButton { knobScrollSensitivitySlider->box.size.x = 250.0; menu->addChild(knobScrollSensitivitySlider); - menu->addChild(createBoolPtrMenuItem("Lock module positions", "", &settings::lockModules)); + menu->addChild(new ui::MenuSeparator); + menu->addChild(createMenuLabel("Window")); + +#ifdef DISTRHO_OS_WASM + const bool fullscreen = APP->window->isFullScreen(); + std::string rightText = "F11"; + if (fullscreen) + rightText += " " CHECKMARK_STRING; + menu->addChild(createMenuItem("Fullscreen", rightText, [=]() { + APP->window->setFullScreen(!fullscreen); + })); +#endif menu->addChild(createBoolPtrMenuItem("Invert zoom", "", &settings::invertZoom)); - menu->addChild(new ui::MenuSeparator); - static const std::vector rateLimitLabels = { "None", "2x", @@ -518,6 +647,41 @@ struct EngineButton : MenuButton { menu->addChild(createMenuItem("Performance meters", cpuMeterText, [=]() { settings::cpuMeter ^= true; })); + + if (isUsingNativeAudio()) { + if (supportsAudioInput()) { + const bool enabled = isAudioInputEnabled(); + std::string rightText; + if (enabled) + rightText = CHECKMARK_STRING; + menu->addChild(createMenuItem("Enable Audio Input", rightText, [enabled]() { + if (!enabled) + requestAudioInput(); + })); + } + + if (supportsMIDI()) { + std::string rightText; + if (isMIDIEnabled()) + rightText = CHECKMARK_STRING; + menu->addChild(createMenuItem("Enable/Reconnect MIDI", rightText, []() { + requestMIDI(); + })); + } + + if (supportsBufferSizeChanges()) { + static const std::vector bufferSizes = {256, 512, 1024, 2048, 4096, 8192, 16384}; + const uint32_t currentBufferSize = getBufferSize(); + menu->addChild(createSubmenuItem("Buffer Size", std::to_string(currentBufferSize), [=](ui::Menu* menu) { + for (uint32_t bufferSize : bufferSizes) { + menu->addChild(createCheckMenuItem(std::to_string(bufferSize), "", + [=]() {return currentBufferSize == bufferSize;}, + [=]() {requestBufferSizeChange(bufferSize);} + )); + } + })); + } + } } }; @@ -534,11 +698,11 @@ struct HelpButton : MenuButton { menu->box.pos = getAbsoluteOffset(math::Vec(0, box.size.y)); menu->addChild(createMenuItem("Rack User manual", "F1", [=]() { - system::openBrowser("https://vcvrack.com/manual"); + patchUtils::openBrowser("https://vcvrack.com/manual"); })); menu->addChild(createMenuItem("Cardinal Project page", "", [=]() { - system::openBrowser("https://github.com/DISTRHO/Cardinal/"); + patchUtils::openBrowser("https://github.com/DISTRHO/Cardinal/"); })); menu->addChild(new ui::MenuSeparator); @@ -596,7 +760,7 @@ struct MenuBar : widget::OpaqueWidget { MenuBar(const bool isStandalone) : widget::OpaqueWidget() - { + { const float margin = 5; box.size.y = BND_WIDGET_HEIGHT + 2 * margin; diff --git a/src/override/Model.cpp b/src/override/Model.cpp index 7ddafb02..a2541be1 100644 --- a/src/override/Model.cpp +++ b/src/override/Model.cpp @@ -38,6 +38,8 @@ #include #include +#include "../CardinalCommon.hpp" + namespace rack { namespace plugin { @@ -120,7 +122,7 @@ std::string Model::getManualUrl() { void Model::appendContextMenu(ui::Menu* menu, bool inBrowser) { // plugin menu->addChild(createMenuItem("Plugin: " + plugin->name, "", [=]() { - system::openBrowser(plugin->pluginUrl); + patchUtils::openBrowser(plugin->pluginUrl); }, plugin->pluginUrl == "")); // version @@ -129,7 +131,7 @@ void Model::appendContextMenu(ui::Menu* menu, bool inBrowser) { // author if (plugin->author != "") { menu->addChild(createMenuItem("Author: " + plugin->author, "", [=]() { - system::openBrowser(plugin->authorUrl); + patchUtils::openBrowser(plugin->authorUrl); }, plugin->authorUrl.empty())); } @@ -137,7 +139,7 @@ void Model::appendContextMenu(ui::Menu* menu, bool inBrowser) { std::string license = plugin->license; if (string::startsWith(license, "https://") || string::startsWith(license, "http://")) { menu->addChild(createMenuItem("License: Open in browser", "", [=]() { - system::openBrowser(license); + patchUtils::openBrowser(license); })); } else if (license != "") { @@ -158,28 +160,28 @@ void Model::appendContextMenu(ui::Menu* menu, bool inBrowser) { std::string manualUrl = getManualUrl(); if (manualUrl != "") { menu->addChild(createMenuItem("User manual", RACK_MOD_CTRL_NAME "+F1", [=]() { - system::openBrowser(manualUrl); + patchUtils::openBrowser(manualUrl); })); } // donate if (plugin->donateUrl != "") { menu->addChild(createMenuItem("Donate", "", [=]() { - system::openBrowser(plugin->donateUrl); + patchUtils::openBrowser(plugin->donateUrl); })); } // source code if (plugin->sourceUrl != "") { menu->addChild(createMenuItem("Source code", "", [=]() { - system::openBrowser(plugin->sourceUrl); + patchUtils::openBrowser(plugin->sourceUrl); })); } // changelog if (plugin->changelogUrl != "") { menu->addChild(createMenuItem("Changelog", "", [=]() { - system::openBrowser(plugin->changelogUrl); + patchUtils::openBrowser(plugin->changelogUrl); })); } diff --git a/src/override/OpenGlWidget.cpp b/src/override/OpenGlWidget.cpp new file mode 100644 index 00000000..a8aad193 --- /dev/null +++ b/src/override/OpenGlWidget.cpp @@ -0,0 +1,48 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * For a full copy of the GNU General Public License see the LICENSE file. + */ + +/** + * This file is an edited version of VCVRack's OpenGlWidget.cpp + * Copyright (C) 2016-2021 VCV. + * + * This program is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation; either version 3 of + * the License, or (at your option) any later version. + */ + +#include +#include + + +namespace rack { +namespace widget { + + +void OpenGlWidget::step() { + // Render every frame + dirty = true; + FramebufferWidget::step(); +} + + +void OpenGlWidget::drawFramebuffer() { +} + + +} // namespace widget +} // namespace rack diff --git a/src/override/Scene.cpp b/src/override/Scene.cpp index 03c4354e..8f4a9e8c 100644 --- a/src/override/Scene.cpp +++ b/src/override/Scene.cpp @@ -108,11 +108,11 @@ struct ResizeHandle : widget::OpaqueWidget { } void onEnter(const EnterEvent& e) override { - glfwSetCursor(nullptr, (GLFWcursor*)0x1); + glfwSetCursor(APP->window->win, glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR)); } void onLeave(const LeaveEvent& e) override { - glfwSetCursor(nullptr, nullptr); + glfwSetCursor(APP->window->win, nullptr); } void onDragStart(const DragStartEvent&) override { @@ -299,11 +299,13 @@ void Scene::onHoverKey(const HoverKeyEvent& e) { patchUtils::revertDialog(); e.consume(this); } +#ifndef DISTRHO_OS_WASM if (e.keyName == "s" && (e.mods & RACK_MOD_MASK) == RACK_MOD_CTRL) { // NOTE: will do nothing if path is empty, intentionally patchUtils::saveDialog(APP->patch->path); e.consume(this); } +#endif if (e.keyName == "s" && (e.mods & RACK_MOD_MASK) == (RACK_MOD_CTRL | GLFW_MOD_SHIFT)) { patchUtils::saveAsDialog(); e.consume(this); @@ -342,7 +344,7 @@ void Scene::onHoverKey(const HoverKeyEvent& e) { e.consume(this); } if (e.key == GLFW_KEY_F1 && (e.mods & RACK_MOD_MASK) == 0) { - system::openBrowser("https://vcvrack.com/manual/"); + patchUtils::openBrowser("https://vcvrack.com/manual/"); e.consume(this); } if (e.key == GLFW_KEY_F3 && (e.mods & RACK_MOD_MASK) == 0) { @@ -358,6 +360,12 @@ void Scene::onHoverKey(const HoverKeyEvent& e) { window::generateScreenshot(); e.consume(this); } +#ifdef DISTRHO_OS_WASM + if (e.key == GLFW_KEY_F11 && (e.mods & RACK_MOD_MASK) == 0) { + APP->window->setFullScreen(!APP->window->isFullScreen()); + e.consume(this); + } +#endif // Module selections if (e.keyName == "a" && (e.mods & RACK_MOD_MASK) == RACK_MOD_CTRL) { diff --git a/src/override/Window.cpp b/src/override/Window.cpp index ff8f969d..7c9d481b 100644 --- a/src/override/Window.cpp +++ b/src/override/Window.cpp @@ -62,6 +62,10 @@ # include "src/Resources.hpp" #endif +#ifdef DISTRHO_OS_WASM +# include +#endif + namespace rack { namespace window { @@ -157,7 +161,9 @@ struct Window::Internal { int frame = 0; int frameSwapInterval = 1; +#ifndef DGL_USE_GLES int generateScreenshotStep = kScreenshotStepNone; +#endif double monitorRefreshRate = 60.0; double frameTime = 0.0; double lastFrameDuration = 0.0; @@ -170,7 +176,11 @@ struct Window::Internal { Internal() : hiddenApp(false), - hiddenWindow(hiddenApp) { hiddenApp.idle(); } + hiddenWindow(hiddenApp) + { + hiddenWindow.setIgnoringKeyRepeat(true); + hiddenApp.idle(); + } }; @@ -222,10 +232,30 @@ Window::Window() { if (uiFont != nullptr) bndSetFont(uiFont->handle); + +#ifdef DISTRHO_OS_WASM + emscripten_lock_orientation(EMSCRIPTEN_ORIENTATION_LANDSCAPE_PRIMARY); +#endif } void WindowSetPluginUI(Window* const window, DISTRHO_NAMESPACE::UI* const ui) { + // if nanovg context failed, init only bare minimum + if (window->vg == nullptr) + { + if (ui != nullptr) + { + window->internal->ui = ui; + window->internal->size = rack::math::Vec(ui->getWidth(), ui->getHeight()); + } + else + { + window->internal->ui = nullptr; + window->internal->callback = nullptr; + } + return; + } + if (ui != nullptr) { const GLubyte* vendor = glGetString(GL_VENDOR); @@ -329,13 +359,16 @@ Window::~Window() { internal->fontCache.clear(); internal->imageCache.clear(); + if (vg != nullptr) + { #if defined NANOVG_GLES2 - nvgDeleteGLES2(internal->o_fbVg != nullptr ? internal->o_fbVg : fbVg); - nvgDeleteGLES2(internal->o_vg != nullptr ? internal->o_vg : vg); + nvgDeleteGLES2(internal->o_fbVg != nullptr ? internal->o_fbVg : fbVg); + nvgDeleteGLES2(internal->o_vg != nullptr ? internal->o_vg : vg); #else - nvgDeleteGL2(internal->o_fbVg != nullptr ? internal->o_fbVg : fbVg); - nvgDeleteGL2(internal->o_vg != nullptr ? internal->o_vg : vg); + nvgDeleteGL2(internal->o_fbVg != nullptr ? internal->o_fbVg : fbVg); + nvgDeleteGL2(internal->o_vg != nullptr ? internal->o_vg : vg); #endif + } } delete internal; @@ -355,12 +388,18 @@ void Window::setSize(math::Vec size) { ui->setSize(internal->size.x, internal->size.y); } +void WindowSetInternalSize(rack::window::Window* const window, math::Vec size) { + size = size.max(WINDOW_SIZE_MIN); + window->internal->size = size; +} + void Window::run() { internal->frame = 0; } +#ifndef DGL_USE_GLES static void Window__flipBitmap(uint8_t* pixels, const int width, const int height, const int depth) { for (int y = 0; y < height / 2; y++) { const int flipY = height - y - 1; @@ -410,11 +449,15 @@ static void Window__writeImagePNG(void* context, void* data, int size) { ui->setState("screenshot", String::asBase64(data, size).buffer()); } #endif +#endif void Window::step() { DISTRHO_SAFE_ASSERT_RETURN(internal->ui != nullptr,); + if (vg == nullptr) + return; + double frameTime = system::getTime(); double lastFrameTime = internal->frameTime; internal->frameTime = frameTime; @@ -448,6 +491,7 @@ void Window::step() { APP->event->handleDirty(); } +#ifndef DGL_USE_GLES // Hide menu and background if generating screenshot if (internal->generateScreenshotStep == kScreenshotStepStarted) { #ifdef CARDINAL_TRANSPARENT_SCREENSHOTS @@ -457,6 +501,7 @@ void Window::step() { internal->generateScreenshotStep = kScreenshotStepSecondPass; #endif } +#endif // Get framebuffer/window ratio int winWidth = internal->ui->getWidth(); @@ -496,6 +541,7 @@ void Window::step() { ++internal->frame; +#ifndef DGL_USE_GLES if (internal->generateScreenshotStep != kScreenshotStepNone) { ++internal->generateScreenshotStep; @@ -524,7 +570,7 @@ void Window::step() { #ifdef STBI_WRITE_NO_STDIO Window__downscaleBitmap(pixelsWithOffset, winWidth, winHeight); stbi_write_png_to_func(Window__writeImagePNG, internal->ui, - winWidth, winHeight, depth, pixelsWithOffset, stride); + winWidth, winHeight, depth, pixelsWithOffset, stride); #else stbi_write_png("screenshot.png", winWidth, winHeight, depth, pixelsWithOffset, stride); #endif @@ -536,6 +582,7 @@ void Window::step() { delete[] pixels; } +#endif } @@ -559,14 +606,31 @@ void Window::close() { void Window::cursorLock() { +#ifdef DISTRHO_OS_WASM + if (!settings::allowCursorLock) + return; + + emscripten_request_pointerlock(internal->ui->getWindow().getApp().getClassName(), false); +#endif } void Window::cursorUnlock() { +#ifdef DISTRHO_OS_WASM + if (!settings::allowCursorLock) + return; + + emscripten_exit_pointerlock(); +#endif } bool Window::isCursorLocked() { +#ifdef DISTRHO_OS_WASM + EmscriptenPointerlockChangeEvent status; + if (emscripten_get_pointerlock_status(&status) == EMSCRIPTEN_RESULT_SUCCESS) + return status.isActive; +#endif return false; } @@ -576,19 +640,29 @@ int Window::getMods() { } -void Window::setFullScreen(bool) { +void Window::setFullScreen(const bool fullscreen) { +#ifdef DISTRHO_OS_WASM + if (fullscreen) + emscripten_request_fullscreen(internal->ui->getWindow().getApp().getClassName(), false); + else + emscripten_exit_fullscreen(); +#endif } bool Window::isFullScreen() { -#ifdef CARDINAL_TRANSPARENT_SCREENSHOTS +#ifdef DISTRHO_OS_WASM + EmscriptenFullscreenChangeEvent status; + if (emscripten_get_fullscreen_status(&status) == EMSCRIPTEN_RESULT_SUCCESS) + return status.isFullscreen; + return false; +#elif defined(CARDINAL_TRANSPARENT_SCREENSHOTS) && !defined(DGL_USE_GLES) return internal->generateScreenshotStep != kScreenshotStepNone; #else return false; #endif } - double Window::getMonitorRefreshRate() { return internal->monitorRefreshRate; } @@ -663,7 +737,9 @@ int& Window::fbCount() { void generateScreenshot() { +#ifndef DGL_USE_GLES APP->window->internal->generateScreenshotStep = kScreenshotStepStarted; +#endif } @@ -760,6 +836,13 @@ void WindowParametersSave(rack::window::Window* const window) window->internal->callback->WindowParametersChanged(kWindowParameterLockModulePositions, rack::settings::lockModules); } + if (window->internal->params.squeezeModules != rack::settings::squeezeModules) + { + window->internal->params.squeezeModules = rack::settings::squeezeModules; + if (window->internal->callback != nullptr) + window->internal->callback->WindowParametersChanged(kWindowParameterSqueezeModulePositions, + rack::settings::squeezeModules); + } if (window->internal->params.invertZoom != rack::settings::invertZoom) { window->internal->params.invertZoom = rack::settings::invertZoom; @@ -789,6 +872,7 @@ void WindowParametersRestore(rack::window::Window* const window) rack::settings::tooltips = window->internal->params.tooltips; rack::settings::knobScroll = window->internal->params.knobScroll; rack::settings::lockModules = window->internal->params.lockModules; + rack::settings::squeezeModules = window->internal->params.squeezeModules; rack::settings::invertZoom = window->internal->params.invertZoom; rack::settings::rateLimit = window->internal->params.rateLimit; } diff --git a/src/override/common.cpp b/src/override/common.cpp index c1c9e709..191914e3 100644 --- a/src/override/common.cpp +++ b/src/override/common.cpp @@ -34,13 +34,24 @@ #include "DistrhoPluginUtils.hpp" -#if defined ARCH_WIN +#if defined(ARCH_WIN) #include FILE* fopen_u8(const char* filename, const char* mode) { + if (std::strncmp(filename, "\\\\?\\", 4) == 0 && std::getenv("CARDINAL_UNDER_WINE") != nullptr) + filename = "Z:\\dev\\null"; return _wfopen(rack::string::UTF8toUTF16(filename).c_str(), rack::string::UTF8toUTF16(mode).c_str()); } +#elif defined(DISTRHO_OS_WASM) +#include +#undef fopen + +FILE* fopen_wasm(const char* filename, const char* mode) { + chmod(filename, 0777); + return std::fopen(filename, mode); +} + #endif @@ -50,7 +61,7 @@ const std::string APP_NAME = "Cardinal"; const std::string APP_EDITION = getPluginFormatName(); const std::string APP_EDITION_NAME = "Audio Plugin"; const std::string APP_VERSION_MAJOR = "2"; -const std::string APP_VERSION = "2.1"; +const std::string APP_VERSION = "2.1.2"; #if defined ARCH_WIN const std::string APP_OS = "win"; #elif defined ARCH_MAC diff --git a/src/override/diffs/Engine.cpp.diff b/src/override/diffs/Engine.cpp.diff index bd223789..7a58e95b 100644 --- a/src/override/diffs/Engine.cpp.diff +++ b/src/override/diffs/Engine.cpp.diff @@ -1,5 +1,5 @@ ---- ../Rack/src/engine/Engine.cpp 2022-02-05 22:30:09.253393116 +0000 -+++ Engine.cpp 2022-02-10 18:51:20.077011285 +0000 +--- ../Rack/src/engine/Engine.cpp 2022-04-11 20:05:02.011283836 +0100 ++++ Engine.cpp 2022-06-29 01:30:02.024102120 +0100 @@ -1,3 +1,30 @@ +/* + * DISTRHO Cardinal Plugin @@ -224,15 +224,17 @@ // moduleId std::map modulesCache; -@@ -199,6 +80,7 @@ +@@ -198,7 +79,9 @@ + int64_t blockFrame = 0; double blockTime = 0.0; int blockFrames = 0; ++ bool aboutToClose = false; +#ifndef HEADLESS // Meter int meterCount = 0; double meterTotal = 0.0; -@@ -206,6 +88,7 @@ +@@ -206,6 +89,7 @@ double meterLastTime = -INFINITY; double meterLastAverage = 0.0; double meterLastMax = 0.0; @@ -240,7 +242,7 @@ // Parameter smoothing Module* smoothModule = NULL; -@@ -217,22 +100,6 @@ +@@ -217,22 +101,6 @@ Readers lock when using the engine's state. */ SharedMutex mutex; @@ -263,7 +265,7 @@ }; -@@ -260,76 +127,11 @@ +@@ -260,76 +128,11 @@ } @@ -341,7 +343,7 @@ // Copy all voltages from output to input for (int c = 0; c < channels; c++) { float v = output->voltages[c]; -@@ -346,6 +148,53 @@ +@@ -346,6 +149,53 @@ } @@ -395,7 +397,7 @@ /** Steps a single frame */ static void Engine_stepFrame(Engine* that) { -@@ -372,13 +221,8 @@ +@@ -372,13 +222,8 @@ } } @@ -410,7 +412,7 @@ if (module->leftExpander.messageFlipRequested) { std::swap(module->leftExpander.producerMessage, module->leftExpander.consumerMessage); module->leftExpander.messageFlipRequested = false; -@@ -389,13 +233,32 @@ +@@ -389,13 +234,32 @@ } } @@ -449,7 +451,7 @@ } -@@ -416,32 +279,45 @@ +@@ -416,32 +280,45 @@ static void Engine_updateConnected(Engine* that) { // Find disconnected ports @@ -506,7 +508,7 @@ } } -@@ -460,37 +336,23 @@ +@@ -460,37 +337,23 @@ Engine::Engine() { internal = new Internal; @@ -552,7 +554,7 @@ delete internal; } -@@ -519,18 +381,22 @@ +@@ -519,18 +382,22 @@ removeModule_NoLock(module); delete module; } @@ -578,7 +580,7 @@ random::init(); internal->blockFrame = internal->frame; -@@ -543,18 +409,14 @@ +@@ -543,18 +410,14 @@ Engine_updateExpander_NoLock(this, module, true); } @@ -598,7 +600,7 @@ // Stop timer double endTime = system::getTime(); double meter = (endTime - startTime) / (frames * internal->sampleTime); -@@ -572,47 +434,20 @@ +@@ -572,47 +435,20 @@ internal->meterTotal = 0.0; internal->meterMax = 0.0; } @@ -648,7 +650,7 @@ } -@@ -635,20 +470,13 @@ +@@ -635,20 +471,13 @@ for (Module* module : internal->modules) { module->onSampleRateChange(e); } @@ -672,7 +674,7 @@ } -@@ -658,7 +486,6 @@ +@@ -658,7 +487,6 @@ void Engine::yieldWorkers() { @@ -680,7 +682,7 @@ } -@@ -698,17 +525,25 @@ +@@ -698,17 +526,25 @@ double Engine::getMeterAverage() { @@ -707,7 +709,7 @@ } -@@ -718,8 +553,12 @@ +@@ -718,8 +554,12 @@ for (Module* m : internal->modules) { if (i >= len) break; @@ -722,7 +724,7 @@ } return i; } -@@ -728,27 +567,43 @@ +@@ -728,27 +568,43 @@ std::vector Engine::getModuleIds() { SharedLock lock(internal->mutex); std::vector moduleIds; @@ -770,7 +772,7 @@ internal->modulesCache[module->id] = module; // Dispatch AddEvent Module::AddEvent eAdd; -@@ -772,11 +627,11 @@ +@@ -772,11 +628,11 @@ } @@ -787,7 +789,7 @@ // Dispatch RemoveEvent Module::RemoveEvent eRemove; module->onRemove(eRemove); -@@ -785,18 +640,14 @@ +@@ -785,18 +641,14 @@ if (paramHandle->moduleId == module->id) paramHandle->module = NULL; } @@ -808,7 +810,7 @@ } // Update expanders of other modules for (Module* m : internal->modules) { -@@ -809,14 +660,31 @@ +@@ -809,14 +661,31 @@ m->rightExpander.module = NULL; } } @@ -843,7 +845,7 @@ } -@@ -824,7 +692,8 @@ +@@ -824,7 +693,8 @@ SharedLock lock(internal->mutex); // TODO Performance could be improved by searching modulesCache, but more testing would be needed to make sure it's always valid. auto it = std::find(internal->modules.begin(), internal->modules.end(), module); @@ -853,7 +855,7 @@ } -@@ -844,7 +713,7 @@ +@@ -844,7 +714,7 @@ void Engine::resetModule(Module* module) { std::lock_guard lock(internal->mutex); @@ -862,7 +864,7 @@ Module::ResetEvent eReset; module->onReset(eReset); -@@ -853,7 +722,7 @@ +@@ -853,7 +723,7 @@ void Engine::randomizeModule(Module* module) { std::lock_guard lock(internal->mutex); @@ -871,7 +873,7 @@ Module::RandomizeEvent eRandomize; module->onRandomize(eRandomize); -@@ -861,7 +730,7 @@ +@@ -861,7 +731,7 @@ void Engine::bypassModule(Module* module, bool bypassed) { @@ -880,7 +882,14 @@ if (module->isBypassed() == bypassed) return; -@@ -912,6 +781,10 @@ +@@ -907,11 +777,17 @@ + + + void Engine::prepareSave() { ++ if (internal->aboutToClose) ++ return; + SharedLock lock(internal->mutex); + for (Module* module : internal->modules) { Module::SaveEvent e; module->onSave(e); } @@ -891,7 +900,7 @@ } -@@ -946,16 +819,16 @@ +@@ -946,16 +822,16 @@ void Engine::addCable(Cable* cable) { std::lock_guard lock(internal->mutex); @@ -913,7 +922,7 @@ // Get connected status of output, to decide whether we need to call a PortChangeEvent. // It's best to not trust `cable->outputModule->outputs[cable->outputId]->isConnected()` if (cable2->outputModule == cable->outputModule && cable2->outputId == cable->outputId) -@@ -969,6 +842,8 @@ +@@ -969,6 +845,8 @@ // Add the cable internal->cables.push_back(cable); internal->cablesCache[cable->id] = cable; @@ -922,7 +931,7 @@ Engine_updateConnected(this); // Dispatch input port event { -@@ -996,10 +871,12 @@ +@@ -996,10 +874,12 @@ void Engine::removeCable_NoLock(Cable* cable) { @@ -937,7 +946,7 @@ // Remove the cable internal->cablesCache.erase(cable->id); internal->cables.erase(it); -@@ -1085,11 +962,11 @@ +@@ -1085,11 +965,11 @@ std::lock_guard lock(internal->mutex); // New ParamHandles must be blank. // This means we don't have to refresh the cache. @@ -951,7 +960,7 @@ // Add it internal->paramHandles.insert(paramHandle); -@@ -1106,7 +983,7 @@ +@@ -1106,7 +986,7 @@ void Engine::removeParamHandle_NoLock(ParamHandle* paramHandle) { // Check that the ParamHandle is already added auto it = internal->paramHandles.find(paramHandle); @@ -960,7 +969,7 @@ // Remove it paramHandle->module = NULL; -@@ -1143,7 +1020,7 @@ +@@ -1143,7 +1023,7 @@ void Engine::updateParamHandle_NoLock(ParamHandle* paramHandle, int64_t moduleId, int paramId, bool overwrite) { // Check that it exists auto it = internal->paramHandles.find(paramHandle); @@ -969,7 +978,7 @@ // Set IDs paramHandle->moduleId = moduleId; -@@ -1187,6 +1064,10 @@ +@@ -1187,6 +1067,10 @@ json_t* moduleJ = module->toJson(); json_array_append_new(modulesJ, moduleJ); } @@ -980,7 +989,7 @@ json_object_set_new(rootJ, "modules", modulesJ); // cables -@@ -1197,11 +1078,6 @@ +@@ -1197,11 +1081,6 @@ } json_object_set_new(rootJ, "cables", cablesJ); @@ -992,7 +1001,7 @@ return rootJ; } -@@ -1225,14 +1101,20 @@ +@@ -1225,14 +1104,20 @@ } catch (Exception& e) { WARN("Cannot load model: %s", e.what()); @@ -1017,7 +1026,7 @@ try { // This doesn't need a lock because the Module is not added to the Engine yet. -@@ -1248,7 +1130,8 @@ +@@ -1248,7 +1133,8 @@ } catch (Exception& e) { WARN("Cannot load module: %s", e.what()); @@ -1027,7 +1036,7 @@ delete module; continue; } -@@ -1285,67 +1168,10 @@ +@@ -1285,67 +1171,15 @@ continue; } } @@ -1038,9 +1047,9 @@ - Module* masterModule = getModule(json_integer_value(masterModuleIdJ)); - setMasterModule(masterModule); - } --} -- -- + } + + -void EngineWorker::run() { - // Configure thread - contextSet(engine->internal->context); @@ -1083,15 +1092,18 @@ - }); - } - } ++void Engine::startFallbackThread() { } - void Engine::startFallbackThread() { +-void Engine::startFallbackThread() { - if (internal->fallbackThread.joinable()) - return; - - internal->fallbackRunning = true; - internal->fallbackThread = std::thread(Engine_fallbackRun, this); ++void Engine_setAboutToClose(Engine* const engine) { ++ engine->internal->aboutToClose = true; } diff --git a/src/override/diffs/MenuBar.cpp.diff b/src/override/diffs/MenuBar.cpp.diff index d4b9535f..5a32860c 100644 --- a/src/override/diffs/MenuBar.cpp.diff +++ b/src/override/diffs/MenuBar.cpp.diff @@ -1,5 +1,5 @@ ---- ../Rack/src/app/MenuBar.cpp 2022-02-26 23:08:06.697192725 +0000 -+++ MenuBar.cpp 2022-04-27 17:30:16.653341980 +0100 +--- ../Rack/src/app/MenuBar.cpp 2022-07-12 09:46:20.716165650 +0100 ++++ MenuBar.cpp 2022-07-12 09:45:31.518663160 +0100 @@ -1,8 +1,33 @@ +/* + * DISTRHO Cardinal Plugin @@ -36,19 +36,29 @@ #include #include #include -@@ -25,6 +50,11 @@ +@@ -25,8 +50,21 @@ #include #include ++#include "../CardinalCommon.hpp" ++ +#ifdef HAVE_LIBLO +# include +#endif + -+#include "../CardinalCommon.hpp" ++#ifdef DISTRHO_OS_WASM ++# include "DistrhoStandaloneUtils.hpp" ++#endif namespace rack { ++namespace asset { ++std::string patchesPath(); ++} ++ namespace app { -@@ -48,79 +78,79 @@ + namespace menuBar { + +@@ -48,79 +86,140 @@ }; @@ -72,22 +82,41 @@ struct FileButton : MenuButton { + const bool isStandalone; ++ std::vector demoPatches; + + FileButton(const bool standalone) -+ : MenuButton(), isStandalone(standalone) {} ++ : MenuButton(), isStandalone(standalone) ++ { ++ const std::string patchesDir = asset::patchesPath(); ++ ++ if (system::isDirectory(patchesDir)) ++ { ++ demoPatches = system::getEntries(patchesDir); ++ std::sort(demoPatches.begin(), demoPatches.end(), [](const std::string& a, const std::string& b){ ++ return string::lowercase(a) < string::lowercase(b); ++ }); ++ } ++ } + void onAction(const ActionEvent& e) override { ui::Menu* menu = createMenu(); menu->cornerFlags = BND_CORNER_TOP; menu->box.pos = getAbsoluteOffset(math::Vec(0, box.size.y)); - menu->addChild(createMenuItem("New", RACK_MOD_CTRL_NAME "+N", []() { +- menu->addChild(createMenuItem("New", RACK_MOD_CTRL_NAME "+N", []() { - APP->patch->loadTemplateDialog(); ++#ifndef DISTRHO_OS_WASM ++ const char* const NewShortcut = RACK_MOD_CTRL_NAME "+N"; ++#else ++ const char* const NewShortcut = ""; ++#endif ++ menu->addChild(createMenuItem("New", NewShortcut, []() { + patchUtils::loadTemplateDialog(); })); - menu->addChild(createMenuItem("Open", RACK_MOD_CTRL_NAME "+O", []() { - APP->patch->loadDialog(); ++#ifndef DISTRHO_OS_WASM + menu->addChild(createMenuItem("Open / Import...", RACK_MOD_CTRL_NAME "+O", []() { + patchUtils::loadDialog(); })); @@ -103,35 +132,52 @@ - menu->addChild(createMenuItem("Save", RACK_MOD_CTRL_NAME "+S", []() { - APP->patch->saveDialog(); -- })); + // NOTE: will do nothing if path is empty, intentionally + patchUtils::saveDialog(APP->patch->path); + }, APP->patch->path.empty())); ++ ++ menu->addChild(createMenuItem("Save as / Export...", RACK_MOD_CTRL_NAME "+Shift+S", []() { ++ patchUtils::saveAsDialog(); ++ })); ++#else ++ menu->addChild(createMenuItem("Import patch...", RACK_MOD_CTRL_NAME "+O", []() { ++ patchUtils::loadDialog(); + })); - menu->addChild(createMenuItem("Save as", RACK_MOD_CTRL_NAME "+Shift+S", []() { - APP->patch->saveAsDialog(); -+ menu->addChild(createMenuItem("Save as / Export...", RACK_MOD_CTRL_NAME "+Shift+S", []() { ++ menu->addChild(createMenuItem("Import selection...", "", [=]() { ++ patchUtils::loadSelectionDialog(); ++ }, false, true)); ++ ++ menu->addChild(createMenuItem("Save and download compressed", RACK_MOD_CTRL_NAME "+Shift+S", []() { + patchUtils::saveAsDialog(); })); - menu->addChild(createMenuItem("Save a copy", "", []() { - APP->patch->saveAsDialog(false); -+ menu->addChild(createMenuItem("Export uncompressed json...", "", []() { ++ menu->addChild(createMenuItem("Save and download uncompressed", "", []() { + patchUtils::saveAsDialogUncompressed(); })); ++#endif -- menu->addChild(createMenuItem("Revert", RACK_MOD_CTRL_NAME "+" RACK_MOD_SHIFT_NAME "+O", []() { + menu->addChild(createMenuItem("Revert", RACK_MOD_CTRL_NAME "+" RACK_MOD_SHIFT_NAME "+O", []() { - APP->patch->revertDialog(); - }, APP->patch->path == "")); ++ patchUtils::revertDialog(); ++ }, APP->patch->path.empty())); + +- menu->addChild(createMenuItem("Overwrite template", "", []() { +- APP->patch->saveTemplateDialog(); +- })); +#ifdef HAVE_LIBLO ++ menu->addChild(new ui::MenuSeparator); ++ + if (patchUtils::isRemoteConnected()) { + menu->addChild(createMenuItem("Deploy to MOD", "F7", []() { + patchUtils::deployToRemote(); + })); - -- menu->addChild(createMenuItem("Overwrite template", "", []() { -- APP->patch->saveTemplateDialog(); -- })); ++ + const bool autoDeploy = patchUtils::isRemoteAutoDeployed(); + menu->addChild(createCheckMenuItem("Auto deploy to MOD", "", + [=]() {return autoDeploy;}, @@ -143,34 +189,59 @@ + })); + } +#endif -+ -+ menu->addChild(createMenuItem("Revert", RACK_MOD_CTRL_NAME "+" RACK_MOD_SHIFT_NAME "+O", []() { -+ patchUtils::revertDialog(); -+ }, APP->patch->path.empty())); ++#ifndef DISTRHO_OS_WASM menu->addChild(new ui::MenuSeparator); // Load selection - menu->addChild(createMenuItem("Import selection", "", [=]() { +- menu->addChild(createMenuItem("Import selection", "", [=]() { - APP->scene->rack->loadSelectionDialog(); ++ menu->addChild(createMenuItem("Import selection...", "", [=]() { + patchUtils::loadSelectionDialog(); }, false, true)); - menu->addChild(new ui::MenuSeparator); -+ if (isStandalone) { -+ menu->addChild(new ui::MenuSeparator); - +- - menu->addChild(createMenuItem("Quit", RACK_MOD_CTRL_NAME "+Q", []() { - APP->window->close(); -- })); ++ menu->addChild(createMenuItem("Export uncompressed json...", "", []() { ++ patchUtils::saveAsDialogUncompressed(); + })); ++#endif ++ ++ if (!demoPatches.empty()) ++ { ++ menu->addChild(new ui::MenuSeparator); ++ ++ menu->addChild(createSubmenuItem("Open Demo / Example project", "", [=](ui::Menu* const menu) { ++ for (std::string path : demoPatches) { ++ std::string label = system::getStem(path); ++ ++ for (size_t i=0, len=label.size(); iaddChild(createMenuItem(label, "", [path]() { ++ patchUtils::loadPathDialog(path, true); ++ })); ++ } ++ })); ++ } ++ ++#ifndef DISTRHO_OS_WASM ++ if (isStandalone) { ++ menu->addChild(new ui::MenuSeparator); ++ + menu->addChild(createMenuItem("Quit", RACK_MOD_CTRL_NAME "+Q", []() { + APP->window->close(); + })); -+ }; ++ } ++#endif } }; -@@ -166,7 +196,7 @@ +@@ -166,7 +265,7 @@ menu->addChild(new ui::MenuSeparator); @@ -179,7 +250,7 @@ } }; -@@ -256,7 +286,7 @@ +@@ -256,7 +355,7 @@ return settings::cableTension; } float getDefaultValue() override { @@ -188,10 +259,20 @@ } float getDisplayValue() override { return getValue() * 100; -@@ -421,28 +451,9 @@ - haloBrightnessSlider->box.size.x = 250.0; - menu->addChild(haloBrightnessSlider); +@@ -399,28 +498,6 @@ + menu->cornerFlags = BND_CORNER_TOP; + menu->box.pos = getAbsoluteOffset(math::Vec(0, box.size.y)); +- menu->addChild(createMenuLabel("Window")); +- +- bool fullscreen = APP->window->isFullScreen(); +- std::string fullscreenText = "F11"; +- if (fullscreen) +- fullscreenText += " " CHECKMARK_STRING; +- menu->addChild(createMenuItem("Fullscreen", fullscreenText, [=]() { +- APP->window->setFullScreen(!fullscreen); +- })); +- - double frameRate = APP->window->getMonitorRefreshRate() / settings::frameSwapInterval; - menu->addChild(createSubmenuItem("Frame rate", string::f("%.0f Hz", frameRate), [=](ui::Menu* menu) { - for (int i = 1; i <= 6; i++) { @@ -203,35 +284,70 @@ - } - })); - -- bool fullscreen = APP->window->isFullScreen(); -- std::string fullscreenText = "F11"; -- if (fullscreen) -- fullscreenText += " " CHECKMARK_STRING; -- menu->addChild(createMenuItem("Fullscreen", fullscreenText, [=]() { -- APP->window->setFullScreen(!fullscreen); -- })); -- +- menu->addChild(new ui::MenuSeparator); + menu->addChild(createMenuLabel("Appearance")); + + menu->addChild(createBoolPtrMenuItem("Show tooltips", "", &settings::tooltips)); +@@ -446,9 +523,18 @@ + menu->addChild(haloBrightnessSlider); + menu->addChild(new ui::MenuSeparator); ++ menu->addChild(createMenuLabel("Module dragging")); ++ ++ menu->addChild(createBoolPtrMenuItem("Lock module positions", "", &settings::lockModules)); ++ ++ menu->addChild(createBoolPtrMenuItem("Auto-squeeze modules when dragging", "", &settings::squeezeModules)); ++ ++ menu->addChild(new ui::MenuSeparator); + menu->addChild(createMenuLabel("Parameters")); -- menu->addChild(createBoolPtrMenuItem("Lock cursor while dragging params", "", &settings::allowCursorLock)); -+ // menu->addChild(createBoolPtrMenuItem("Hide cursor while dragging", "", &settings::allowCursorLock)); ++#ifdef DISTRHO_OS_WASM + menu->addChild(createBoolPtrMenuItem("Lock cursor while dragging", "", &settings::allowCursorLock)); ++#endif static const std::vector knobModeLabels = { "Linear", -@@ -467,56 +478,34 @@ +@@ -473,11 +559,34 @@ menu->addChild(knobScrollSensitivitySlider); - menu->addChild(createBoolPtrMenuItem("Lock module positions", "", &settings::lockModules)); -- } --}; -- + menu->addChild(new ui::MenuSeparator); +- menu->addChild(createMenuLabel("Module dragging")); ++ menu->addChild(createMenuLabel("Window")); + +- menu->addChild(createBoolPtrMenuItem("Lock positions", "", &settings::lockModules)); ++#ifdef DISTRHO_OS_WASM ++ const bool fullscreen = APP->window->isFullScreen(); ++ std::string fullscreenText = "F11"; ++ if (fullscreen) ++ fullscreenText += " " CHECKMARK_STRING; ++ menu->addChild(createMenuItem("Fullscreen", fullscreenText, [=]() { ++ APP->window->setFullScreen(!fullscreen); ++ })); ++#endif --//////////////////// --// Engine --//////////////////// +- menu->addChild(createBoolPtrMenuItem("Auto-squeeze algorithm (experimental)", "", &settings::squeezeModules)); + menu->addChild(createBoolPtrMenuItem("Invert zoom", "", &settings::invertZoom)); ++ ++ static const std::vector rateLimitLabels = { ++ "None", ++ "2x", ++ "4x", ++ }; ++ static const std::vector rateLimits = {0, 1, 2}; ++ menu->addChild(createSubmenuItem("Update rate limit", rateLimitLabels[settings::rateLimit], [=](ui::Menu* menu) { ++ for (int rateLimit : rateLimits) { ++ menu->addChild(createCheckMenuItem(rateLimitLabels[rateLimit], "", ++ [=]() {return settings::rateLimit == rateLimit;}, ++ [=]() {settings::rateLimit = rateLimit;} ++ )); ++ } ++ })); + } + }; + +@@ -487,47 +596,6 @@ + //////////////////// -+ menu->addChild(new ui::MenuSeparator); -struct SampleRateItem : ui::MenuItem { - ui::Menu* createChildMenu() override { @@ -266,39 +382,21 @@ - menu->addChild(createCheckMenuItem(text, rightText, - [=]() {return settings::sampleRate == sampleRate;}, - [=]() {settings::sampleRate = sampleRate;} -+ static const std::vector rateLimitLabels = { -+ "None", -+ "2x", -+ "4x", -+ }; -+ static const std::vector rateLimits = {0, 1, 2}; -+ menu->addChild(createSubmenuItem("Update rate limit", rateLimitLabels[settings::rateLimit], [=](ui::Menu* menu) { -+ for (int rateLimit : rateLimits) { -+ menu->addChild(createCheckMenuItem(rateLimitLabels[rateLimit], "", -+ [=]() {return settings::rateLimit == rateLimit;}, -+ [=]() {settings::rateLimit = rateLimit;} - )); - } +- )); +- } - } - return menu; -+ })); - } - }; - - -+//////////////////// -+// Engine -+//////////////////// -+ -+ +- } +-}; +- +- struct EngineButton : MenuButton { void onAction(const ActionEvent& e) override { ui::Menu* menu = createMenu(); -@@ -529,269 +518,6 @@ - menu->addChild(createMenuItem("Performance meters", cpuMeterText, [=]() { +@@ -541,268 +609,42 @@ settings::cpuMeter ^= true; })); -- + - menu->addChild(createMenuItem("Sample rate", RIGHT_ARROW)); - - menu->addChild(createSubmenuItem("Threads", string::f("%d", settings::threadCount), [=](ui::Menu* menu) { @@ -480,7 +578,16 @@ - else if (!library::isLoggedIn()) { - addChild(createMenuItem("Register VCV account", "", [=]() { - system::openBrowser("https://vcvrack.com/login"); -- })); ++#ifdef DISTRHO_OS_WASM ++ if (supportsAudioInput()) { ++ const bool enabled = isAudioInputEnabled(); ++ std::string text = "Enable Audio Input"; ++ if (enabled) ++ text += " " CHECKMARK_STRING; ++ menu->addChild(createMenuItem(text, "", [enabled]() { ++ if (!enabled) ++ requestAudioInput(); + })); - - ui::TextField* emailField = new ui::TextField; - emailField->placeholder = "Email"; @@ -499,15 +606,23 @@ - logInItem->passwordField = passwordField; - passwordField->logInItem = logInItem; - addChild(logInItem); -- } + } - else { - addChild(createMenuItem("Log out", "", [=]() { - library::logOut(); - })); -- + - addChild(createMenuItem("Browse VCV Library", "", [=]() { - system::openBrowser("https://library.vcvrack.com/"); -- })); ++ if (supportsMIDI()) { ++ const bool enabled = isMIDIEnabled(); ++ std::string text = "Enable MIDI"; ++ if (enabled) ++ text += " " CHECKMARK_STRING; ++ menu->addChild(createMenuItem(text, "", [enabled]() { ++ if (!enabled) ++ requestMIDI(); + })); - - SyncUpdatesItem* syncItem = new SyncUpdatesItem; - syncItem->text = "Update all"; @@ -523,11 +638,11 @@ - addChild(updateItem); - } - } -- } + } - } -}; - -- + -struct LibraryButton : MenuButton { - NotificationIcon* notification; - @@ -558,13 +673,25 @@ - if (osdialog_message(OSDIALOG_INFO, OSDIALOG_OK_CANCEL, "All plugins have been downloaded. Close and re-launch Rack to load new updates.")) { - APP->window->close(); - } -- } ++ if (supportsBufferSizeChanges()) { ++ static const std::vector bufferSizes = {256, 512, 1024, 2048, 4096, 8192, 16384}; ++ const uint32_t currentBufferSize = getBufferSize(); ++ menu->addChild(createSubmenuItem("Buffer Size", std::to_string(currentBufferSize), [=](ui::Menu* menu) { ++ for (uint32_t bufferSize : bufferSizes) { ++ menu->addChild(createCheckMenuItem(std::to_string(bufferSize), "", ++ [=]() {return currentBufferSize == bufferSize;}, ++ [=]() {requestBufferSizeChange(bufferSize);} ++ )); ++ } ++ })); + } - - MenuButton::step(); ++#endif } }; -@@ -802,65 +528,23 @@ +@@ -813,65 +655,23 @@ struct HelpButton : MenuButton { @@ -582,13 +709,14 @@ - menu->addChild(createMenuItem("Tips", "", [=]() { - APP->scene->addChild(tipWindowCreate()); -- })); -- -- menu->addChild(createMenuItem("User manual", "F1", [=]() { + menu->addChild(createMenuItem("Rack User manual", "F1", [=]() { - system::openBrowser("https://vcvrack.com/manual"); ++ patchUtils::openBrowser("https://vcvrack.com/manual"); })); +- menu->addChild(createMenuItem("User manual", "F1", [=]() { +- system::openBrowser("https://vcvrack.com/manual"); +- })); +- - menu->addChild(createMenuItem("Support", "", [=]() { - system::openBrowser("https://vcvrack.com/support"); - })); @@ -596,7 +724,7 @@ - menu->addChild(createMenuItem("VCVRack.com", "", [=]() { - system::openBrowser("https://vcvrack.com/"); + menu->addChild(createMenuItem("Cardinal Project page", "", [=]() { -+ system::openBrowser("https://github.com/DISTRHO/Cardinal/"); ++ patchUtils::openBrowser("https://github.com/DISTRHO/Cardinal/"); })); menu->addChild(new ui::MenuSeparator); @@ -635,18 +763,18 @@ } }; -@@ -910,7 +594,9 @@ +@@ -921,7 +721,9 @@ struct MenuBar : widget::OpaqueWidget { MeterLabel* meterLabel; - MenuBar() { + MenuBar(const bool isStandalone) + : widget::OpaqueWidget() -+ { ++ { const float margin = 5; box.size.y = BND_WIDGET_HEIGHT + 2 * margin; -@@ -919,7 +605,7 @@ +@@ -930,7 +732,7 @@ layout->spacing = math::Vec(0, 0); addChild(layout); @@ -655,7 +783,7 @@ fileButton->text = "File"; layout->addChild(fileButton); -@@ -935,10 +621,6 @@ +@@ -946,10 +748,6 @@ engineButton->text = "Engine"; layout->addChild(engineButton); @@ -666,7 +794,7 @@ HelpButton* helpButton = new HelpButton; helpButton->text = "Help"; layout->addChild(helpButton); -@@ -973,7 +655,11 @@ +@@ -984,7 +782,11 @@ widget::Widget* createMenuBar() { diff --git a/src/override/diffs/Model.cpp.diff b/src/override/diffs/Model.cpp.diff index 50c88176..b1f5617c 100644 --- a/src/override/diffs/Model.cpp.diff +++ b/src/override/diffs/Model.cpp.diff @@ -1,5 +1,5 @@ ---- ../Rack/src/plugin/Model.cpp 2021-10-17 13:57:23.257633662 +0100 -+++ Model.cpp 2022-04-27 17:55:57.362107553 +0100 +--- ../Rack/src/plugin/Model.cpp 2022-07-12 09:46:20.716165650 +0100 ++++ Model.cpp 2022-07-06 16:19:37.977002863 +0100 @@ -1,3 +1,30 @@ +/* + * DISTRHO Cardinal Plugin @@ -31,7 +31,17 @@ #include #include -@@ -17,7 +44,7 @@ +@@ -10,7 +37,8 @@ + #include + #include + #include +-#include ++ ++#include "../CardinalCommon.hpp" + + + namespace rack { +@@ -18,7 +46,7 @@ void Model::fromJson(json_t* rootJ) { @@ -40,7 +50,7 @@ json_t* nameJ = json_object_get(rootJ, "name"); if (nameJ) -@@ -54,11 +81,6 @@ +@@ -55,11 +83,6 @@ if (manualUrlJ) manualUrl = json_string_value(manualUrlJ); @@ -52,7 +62,7 @@ // hidden json_t* hiddenJ = json_object_get(rootJ, "hidden"); // Use `disabled` as an alias which was deprecated in Rack 2.0 -@@ -73,7 +95,7 @@ +@@ -74,7 +97,7 @@ std::string Model::getFullName() { @@ -61,7 +71,34 @@ return plugin->getBrand() + " " + name; } -@@ -132,18 +154,6 @@ +@@ -99,7 +122,7 @@ + void Model::appendContextMenu(ui::Menu* menu, bool inBrowser) { + // plugin + menu->addChild(createMenuItem("Plugin: " + plugin->name, "", [=]() { +- system::openBrowser(plugin->pluginUrl); ++ patchUtils::openBrowser(plugin->pluginUrl); + }, plugin->pluginUrl == "")); + + // version +@@ -108,7 +131,7 @@ + // author + if (plugin->author != "") { + menu->addChild(createMenuItem("Author: " + plugin->author, "", [=]() { +- system::openBrowser(plugin->authorUrl); ++ patchUtils::openBrowser(plugin->authorUrl); + }, plugin->authorUrl.empty())); + } + +@@ -116,7 +139,7 @@ + std::string license = plugin->license; + if (string::startsWith(license, "https://") || string::startsWith(license, "http://")) { + menu->addChild(createMenuItem("License: Open in browser", "", [=]() { +- system::openBrowser(license); ++ patchUtils::openBrowser(license); + })); + } + else if (license != "") { +@@ -133,58 +156,32 @@ menu->addChild(new ui::MenuSeparator); @@ -80,17 +117,47 @@ // manual std::string manualUrl = getManualUrl(); if (manualUrl != "") { -@@ -173,13 +183,6 @@ + menu->addChild(createMenuItem("User manual", RACK_MOD_CTRL_NAME "+F1", [=]() { +- system::openBrowser(manualUrl); ++ patchUtils::openBrowser(manualUrl); + })); + } + + // donate + if (plugin->donateUrl != "") { + menu->addChild(createMenuItem("Donate", "", [=]() { +- system::openBrowser(plugin->donateUrl); ++ patchUtils::openBrowser(plugin->donateUrl); + })); + } + + // source code + if (plugin->sourceUrl != "") { + menu->addChild(createMenuItem("Source code", "", [=]() { +- system::openBrowser(plugin->sourceUrl); ++ patchUtils::openBrowser(plugin->sourceUrl); })); } + // changelog + if (plugin->changelogUrl != "") { + menu->addChild(createMenuItem("Changelog", "", [=]() { +- system::openBrowser(plugin->changelogUrl); +- })); +- } +- +- // author email +- if (plugin->authorEmail != "") { +- menu->addChild(createMenuItem("Author email", "Copy to clipboard", [=]() { +- glfwSetClipboardString(APP->window->win, plugin->authorEmail.c_str()); +- })); +- } +- - // plugin folder - if (plugin->path != "") { - menu->addChild(createMenuItem("Open plugin folder", "", [=]() { - system::openDirectory(plugin->path); -- })); -- } -- - // Favorite - std::string favoriteRightText = inBrowser ? (RACK_MOD_CTRL_NAME "+click") : ""; - if (isFavorite()) ++ patchUtils::openBrowser(plugin->changelogUrl); + })); + } + diff --git a/src/override/diffs/OpenGlWidget.cpp.diff b/src/override/diffs/OpenGlWidget.cpp.diff new file mode 100644 index 00000000..1ada3cd0 --- /dev/null +++ b/src/override/diffs/OpenGlWidget.cpp.diff @@ -0,0 +1,57 @@ +--- ../Rack/src/widget/OpenGlWidget.cpp 2022-04-11 20:05:02.023283713 +0100 ++++ OpenGlWidget.cpp 2022-07-14 01:14:57.028367786 +0100 +@@ -1,3 +1,30 @@ ++/* ++ * DISTRHO Cardinal Plugin ++ * Copyright (C) 2021-2022 Filipe Coelho ++ * ++ * This program is free software; you can redistribute it and/or ++ * modify it under the terms of the GNU General Public License as ++ * published by the Free Software Foundation; either version 3 of ++ * the License, or any later version. ++ * ++ * This program is distributed in the hope that it will be useful, ++ * but WITHOUT ANY WARRANTY; without even the implied warranty of ++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ++ * GNU General Public License for more details. ++ * ++ * For a full copy of the GNU General Public License see the LICENSE file. ++ */ ++ ++/** ++ * This file is an edited version of VCVRack's OpenGlWidget.cpp ++ * Copyright (C) 2016-2021 VCV. ++ * ++ * This program is free software: you can redistribute it and/or ++ * modify it under the terms of the GNU General Public License as ++ * published by the Free Software Foundation; either version 3 of ++ * the License, or (at your option) any later version. ++ */ ++ + #include + #include + +@@ -14,23 +41,6 @@ + + + void OpenGlWidget::drawFramebuffer() { +- math::Vec fbSize = getFramebufferSize(); +- glViewport(0.0, 0.0, fbSize.x, fbSize.y); +- glClearColor(0.0, 0.0, 0.0, 1.0); +- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); +- +- glMatrixMode(GL_PROJECTION); +- glLoadIdentity(); +- glOrtho(0.0, fbSize.x, 0.0, fbSize.y, -1.0, 1.0); +- +- glBegin(GL_TRIANGLES); +- glColor3f(1, 0, 0); +- glVertex3f(0, 0, 0); +- glColor3f(0, 1, 0); +- glVertex3f(fbSize.x, 0, 0); +- glColor3f(0, 0, 1); +- glVertex3f(0, fbSize.y, 0); +- glEnd(); + } + + diff --git a/src/override/diffs/Scene.cpp.diff b/src/override/diffs/Scene.cpp.diff index cb11e92c..3d338e9f 100644 --- a/src/override/diffs/Scene.cpp.diff +++ b/src/override/diffs/Scene.cpp.diff @@ -1,5 +1,5 @@ ---- ../Rack/src/app/Scene.cpp 2022-02-26 23:08:06.701192797 +0000 -+++ Scene.cpp 2022-04-02 03:13:14.856813800 +0100 +--- ../Rack/src/app/Scene.cpp 2022-04-11 20:05:02.007283878 +0100 ++++ Scene.cpp 2022-07-12 09:45:31.518663160 +0100 @@ -1,3 +1,30 @@ +/* + * DISTRHO Cardinal Plugin @@ -112,11 +112,11 @@ + } + + void onEnter(const EnterEvent& e) override { -+ glfwSetCursor(nullptr, (GLFWcursor*)0x1); ++ glfwSetCursor(APP->window->win, glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR)); + } + + void onLeave(const LeaveEvent& e) override { -+ glfwSetCursor(nullptr, nullptr); ++ glfwSetCursor(APP->window->win, nullptr); } - void onDragStart(const DragStartEvent& e) override { @@ -242,7 +242,7 @@ e.consume(this); } if (e.keyName == "q" && (e.mods & RACK_MOD_MASK) == RACK_MOD_CTRL) { -@@ -180,19 +292,20 @@ +@@ -180,19 +292,22 @@ e.consume(this); } if (e.keyName == "o" && (e.mods & RACK_MOD_MASK) == RACK_MOD_CTRL) { @@ -255,19 +255,21 @@ + patchUtils::revertDialog(); e.consume(this); } ++#ifndef DISTRHO_OS_WASM if (e.keyName == "s" && (e.mods & RACK_MOD_MASK) == RACK_MOD_CTRL) { - APP->patch->saveDialog(); + // NOTE: will do nothing if path is empty, intentionally + patchUtils::saveDialog(APP->patch->path); e.consume(this); } ++#endif if (e.keyName == "s" && (e.mods & RACK_MOD_MASK) == (RACK_MOD_CTRL | GLFW_MOD_SHIFT)) { - APP->patch->saveAsDialog(); + patchUtils::saveAsDialog(); e.consume(this); } if (e.keyName == "z" && (e.mods & RACK_MOD_MASK) == RACK_MOD_CTRL) { -@@ -220,10 +333,14 @@ +@@ -220,24 +335,37 @@ APP->scene->rackScroll->setZoom(std::pow(2.f, zoom)); e.consume(this); } @@ -281,16 +283,14 @@ + e.consume(this); + } if (e.key == GLFW_KEY_F1 && (e.mods & RACK_MOD_MASK) == 0) { - system::openBrowser("https://vcvrack.com/manual/"); +- system::openBrowser("https://vcvrack.com/manual/"); ++ patchUtils::openBrowser("https://vcvrack.com/manual/"); e.consume(this); -@@ -232,10 +349,13 @@ + } + if (e.key == GLFW_KEY_F3 && (e.mods & RACK_MOD_MASK) == 0) { settings::cpuMeter ^= true; e.consume(this); } -- if (e.key == GLFW_KEY_F11 && (e.mods & RACK_MOD_MASK) == 0) { -- APP->window->setFullScreen(!APP->window->isFullScreen()); -- // The MenuBar will be hidden when the mouse moves over the RackScrollWidget. -- // menuBar->hide(); + if (e.key == GLFW_KEY_F7 && (e.mods & RACK_MOD_MASK) == 0) { + patchUtils::deployToRemote(); + window::generateScreenshot(); @@ -298,10 +298,20 @@ + } + if (e.key == GLFW_KEY_F9 && (e.mods & RACK_MOD_MASK) == 0) { + window::generateScreenshot(); ++ e.consume(this); ++ } ++#ifdef DISTRHO_OS_WASM + if (e.key == GLFW_KEY_F11 && (e.mods & RACK_MOD_MASK) == 0) { + APP->window->setFullScreen(!APP->window->isFullScreen()); +- // The MenuBar will be hidden when the mouse moves over the RackScrollWidget. +- // menuBar->hide(); e.consume(this); } ++#endif -@@ -326,13 +446,6 @@ + // Module selections + if (e.keyName == "a" && (e.mods & RACK_MOD_MASK) == RACK_MOD_CTRL) { +@@ -326,13 +454,6 @@ // Key commands that can be overridden by children if (e.action == GLFW_PRESS || e.action == GLFW_REPEAT) { @@ -315,7 +325,7 @@ if (e.keyName == "v" && (e.mods & RACK_MOD_MASK) == RACK_MOD_CTRL) { rack->pasteClipboardAction(); e.consume(this); -@@ -351,7 +464,7 @@ +@@ -351,7 +472,7 @@ std::string extension = system::getExtension(path); if (extension == ".vcv") { @@ -324,7 +334,7 @@ e.consume(this); return; } -@@ -368,3 +481,94 @@ +@@ -368,3 +489,94 @@ } // namespace app } // namespace rack diff --git a/src/override/diffs/Window.cpp.diff b/src/override/diffs/Window.cpp.diff index 0f6d5bfc..2082672a 100644 --- a/src/override/diffs/Window.cpp.diff +++ b/src/override/diffs/Window.cpp.diff @@ -1,6 +1,6 @@ ---- ../Rack/src/window/Window.cpp 2022-02-09 15:35:19.238863170 +0000 -+++ Window.cpp 2022-04-27 16:53:59.743671091 +0100 -@@ -1,33 +1,83 @@ +--- ../Rack/src/window/Window.cpp 2022-04-11 20:05:02.023283713 +0100 ++++ Window.cpp 2022-07-12 09:45:31.518663160 +0100 +@@ -1,33 +1,87 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho @@ -75,6 +75,10 @@ + +#ifndef DGL_NO_SHARED_RESOURCES +# include "src/Resources.hpp" ++#endif ++ ++#ifdef DISTRHO_OS_WASM ++# include +#endif namespace rack { @@ -97,7 +101,7 @@ Font::~Font() { -@@ -42,9 +92,8 @@ +@@ -42,9 +96,8 @@ // Transfer ownership of font data to font object uint8_t* data = system::readFile(filename, &size); // Don't use nvgCreateFont because it doesn't properly handle UTF-8 filenames on Windows. @@ -108,7 +112,7 @@ throw Exception("Failed to load font %s", filename.c_str()); } INFO("Loaded font %s", filename.c_str()); -@@ -79,375 +128,308 @@ +@@ -79,375 +132,325 @@ } @@ -148,7 +152,9 @@ - int frameSwapInterval = -1; - double monitorRefreshRate = 0.0; + int frameSwapInterval = 1; ++#ifndef DGL_USE_GLES + int generateScreenshotStep = kScreenshotStepNone; ++#endif + double monitorRefreshRate = 60.0; double frameTime = 0.0; double lastFrameDuration = 0.0; @@ -165,7 +171,11 @@ + + Internal() + : hiddenApp(false), -+ hiddenWindow(hiddenApp) { hiddenApp.idle(); } ++ hiddenWindow(hiddenApp) ++ { ++ hiddenWindow.setIgnoringKeyRepeat(true); ++ hiddenApp.idle(); ++ } }; @@ -200,14 +210,18 @@ + return nvgCreateFontMem(vg, NANOVG_DEJAVU_SANS_TTF, + (uchar*)dejavusans_ttf, dejavusans_ttf_size, 0); } -- -- ++#endif + + -static void windowMaximizeCallback(GLFWwindow* win, int maximized) { - settings::windowMaximized = maximized; - // DEBUG("windowMaximizeCallback %d", maximized); -} -- -- ++Window::Window() { ++ internal = new Internal; + ++ DGL_NAMESPACE::Window::ScopedGraphicsContext sgc(internal->hiddenWindow); + -static void mouseButtonCallback(GLFWwindow* win, int button, int action, int mods) { - contextSet((Context*) glfwGetWindowUserPointer(win)); -#if defined ARCH_MAC @@ -221,49 +235,30 @@ - button = GLFW_MOUSE_BUTTON_MIDDLE; - mods &= ~(GLFW_MOD_CONTROL | GLFW_MOD_SHIFT); - } ++ // Set up NanoVG ++ const int nvgFlags = NVG_ANTIALIAS; ++ vg = nvgCreateGL(nvgFlags); ++ DISTRHO_SAFE_ASSERT_RETURN(vg != nullptr,); ++#ifdef NANOVG_GLES2 ++ fbVg = nvgCreateSharedGLES2(vg, nvgFlags); ++#else ++ fbVg = nvgCreateSharedGL2(vg, nvgFlags); #endif - APP->event->handleButton(APP->window->internal->lastMousePos, button, action, mods); -} - - +- -static void cursorPosCallback(GLFWwindow* win, double xpos, double ypos) { - contextSet((Context*) glfwGetWindowUserPointer(win)); - math::Vec mousePos = math::Vec(xpos, ypos).div(APP->window->pixelRatio / APP->window->windowRatio).round(); - math::Vec mouseDelta = mousePos.minus(APP->window->internal->lastMousePos); -+Window::Window() { -+ internal = new Internal; - +- - // Workaround for GLFW warping mouse to a different position when the cursor is locked or unlocked. - if (APP->window->internal->ignoreNextMouseDelta) { - APP->window->internal->ignoreNextMouseDelta = false; - mouseDelta = math::Vec(); - } -+ DGL_NAMESPACE::Window::ScopedGraphicsContext sgc(internal->hiddenWindow); - -- int cursorMode = glfwGetInputMode(win, GLFW_CURSOR); -- (void) cursorMode; -+ // Set up NanoVG -+ const int nvgFlags = NVG_ANTIALIAS; -+ vg = nvgCreateGL(nvgFlags); -+ DISTRHO_SAFE_ASSERT_RETURN(vg != nullptr,); -+#ifdef NANOVG_GLES2 -+ fbVg = nvgCreateSharedGLES2(vg, nvgFlags); -+#else -+ fbVg = nvgCreateSharedGL2(vg, nvgFlags); -+#endif - --#if defined ARCH_MAC -- // Workaround for Mac. We can't use GLFW_CURSOR_DISABLED because it's buggy, so implement it on our own. -- // This is not an ideal implementation. For example, if the user drags off the screen, the new mouse position will be clamped. -- if (cursorMode == GLFW_CURSOR_HIDDEN) { -- // CGSetLocalEventsSuppressionInterval(0.0); -- glfwSetCursorPos(win, APP->window->internal->lastMousePos.x, APP->window->internal->lastMousePos.y); -- CGAssociateMouseAndMouseCursorPosition(true); -- mousePos = APP->window->internal->lastMousePos; -- } -- // Because sometimes the cursor turns into an arrow when its position is on the boundary of the window -- glfwSetCursor(win, NULL); + // Load default Blendish font +#ifndef DGL_NO_SHARED_RESOURCES + uiFont = std::make_shared(); @@ -278,13 +273,31 @@ + internal->fontCache[uiFont2->ofilename] = uiFont2; +#else + uiFont = loadFont(asset::system("res/fonts/DejaVuSans.ttf")); - #endif ++#endif -- APP->window->internal->lastMousePos = mousePos; +- int cursorMode = glfwGetInputMode(win, GLFW_CURSOR); +- (void) cursorMode; + if (uiFont != nullptr) + bndSetFont(uiFont->handle); + +-#if defined ARCH_MAC +- // Workaround for Mac. We can't use GLFW_CURSOR_DISABLED because it's buggy, so implement it on our own. +- // This is not an ideal implementation. For example, if the user drags off the screen, the new mouse position will be clamped. +- if (cursorMode == GLFW_CURSOR_HIDDEN) { +- // CGSetLocalEventsSuppressionInterval(0.0); +- glfwSetCursorPos(win, APP->window->internal->lastMousePos.x, APP->window->internal->lastMousePos.y); +- CGAssociateMouseAndMouseCursorPosition(true); +- mousePos = APP->window->internal->lastMousePos; +- } +- // Because sometimes the cursor turns into an arrow when its position is on the boundary of the window +- glfwSetCursor(win, NULL); ++#ifdef DISTRHO_OS_WASM ++ emscripten_lock_orientation(EMSCRIPTEN_ORIENTATION_LANDSCAPE_PRIMARY); + #endif +} +- APP->window->internal->lastMousePos = mousePos; +- - APP->event->handleHover(mousePos, mouseDelta); +void WindowSetPluginUI(Window* const window, DISTRHO_NAMESPACE::UI* const ui) +{ @@ -458,7 +471,10 @@ -Window::Window() { - internal = new Internal; - int err; -- ++void Window::setSize(math::Vec size) { ++ size = size.max(WINDOW_SIZE_MIN); ++ internal->size = size; + - // Set window hints -#if defined NANOVG_GL2 - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); @@ -539,12 +555,16 @@ - const GLubyte* version = glGetString(GL_VERSION); - INFO("Renderer: %s %s", vendor, renderer); - INFO("OpenGL: %s", version); -- ++ if (DISTRHO_NAMESPACE::UI* const ui = internal->ui) ++ ui->setSize(internal->size.x, internal->size.y); ++} + - // GLEW generates GL error because it calls glGetString(GL_EXTENSIONS), we'll consume it here. - glGetError(); -+void Window::setSize(math::Vec size) { ++void WindowSetInternalSize(rack::window::Window* const window, math::Vec size) { + size = size.max(WINDOW_SIZE_MIN); -+ internal->size = size; ++ window->internal->size = size; ++} - // Set up NanoVG - int nvgFlags = NVG_ANTIALIAS; @@ -560,14 +580,11 @@ - osdialog_message(OSDIALOG_ERROR, OSDIALOG_OK, "Could not initialize NanoVG. Does your graphics card support OpenGL 2.0 or greater? If so, make sure you have the latest graphics drivers installed."); - throw Exception("Could not initialize NanoVG"); - } -+ if (DISTRHO_NAMESPACE::UI* const ui = internal->ui) -+ ui->setSize(internal->size.x, internal->size.y); -+} - // Load default Blendish font - uiFont = loadFont(asset::system("res/fonts/DejaVuSans.ttf")); - bndSetFont(uiFont->handle); - +- - if (APP->scene) { - widget::Widget::ContextCreateEvent e; - APP->scene->onContextCreate(e); @@ -581,6 +598,7 @@ - if (APP->scene) { - widget::Widget::ContextDestroyEvent e; - APP->scene->onContextDestroy(e); ++#ifndef DGL_USE_GLES +static void Window__flipBitmap(uint8_t* pixels, const int width, const int height, const int depth) { + for (int y = 0; y < height / 2; y++) { + const int flipY = height - y - 1; @@ -663,6 +681,7 @@ + ui->setState("screenshot", String::asBase64(data, size).buffer()); } +#endif ++#endif void Window::step() { @@ -710,7 +729,7 @@ if (APP->patch->path != "") { windowTitle += " - "; if (!APP->history->isSaved()) -@@ -455,243 +437,155 @@ +@@ -455,246 +458,189 @@ windowTitle += system::getFilename(APP->patch->path); } if (windowTitle != internal->lastWindowTitle) { @@ -734,6 +753,7 @@ APP->event->handleDirty(); } ++#ifndef DGL_USE_GLES + // Hide menu and background if generating screenshot + if (internal->generateScreenshotStep == kScreenshotStepStarted) { +#ifdef CARDINAL_TRANSPARENT_SCREENSHOTS @@ -743,6 +763,7 @@ + internal->generateScreenshotStep = kScreenshotStepSecondPass; +#endif + } ++#endif + // Get framebuffer/window ratio - int fbWidth, fbHeight; @@ -815,9 +836,10 @@ - // ); - internal->frame++; -} ++#ifndef DGL_USE_GLES + if (internal->generateScreenshotStep != kScreenshotStepNone) { + ++internal->generateScreenshotStep; - ++ + int y = 0; +#ifdef CARDINAL_TRANSPARENT_SCREENSHOTS + constexpr const int depth = 4; @@ -826,23 +848,16 @@ + constexpr const int depth = 3; +#endif --void Window::activateContext() { -- glfwMakeContextCurrent(win); --} + // Allocate pixel color buffer + uint8_t* const pixels = new uint8_t[winHeight * winWidth * 4]; +-void Window::activateContext() { +- glfwMakeContextCurrent(win); +-} + // glReadPixels defaults to GL_BACK, but the back-buffer is unstable, so use the front buffer (what the user sees) + glReadBuffer(GL_FRONT); + glReadPixels(0, 0, winWidth, winHeight, depth == 3 ? GL_RGB : GL_RGBA, GL_UNSIGNED_BYTE, pixels); --static void flipBitmap(uint8_t* pixels, int width, int height, int depth) { -- for (int y = 0; y < height / 2; y++) { -- int flipY = height - y - 1; -- uint8_t tmp[width * depth]; -- std::memcpy(tmp, &pixels[y * width * depth], width * depth); -- std::memcpy(&pixels[y * width * depth], &pixels[flipY * width * depth], width * depth); -- std::memcpy(&pixels[flipY * width * depth], tmp, width * depth); + if (internal->generateScreenshotStep == kScreenshotStepSaving) + { + // Write pixels to PNG @@ -853,11 +868,18 @@ +#ifdef STBI_WRITE_NO_STDIO + Window__downscaleBitmap(pixelsWithOffset, winWidth, winHeight); + stbi_write_png_to_func(Window__writeImagePNG, internal->ui, -+ winWidth, winHeight, depth, pixelsWithOffset, stride); ++ winWidth, winHeight, depth, pixelsWithOffset, stride); +#else + stbi_write_png("screenshot.png", winWidth, winHeight, depth, pixelsWithOffset, stride); +#endif -+ + +-static void flipBitmap(uint8_t* pixels, int width, int height, int depth) { +- for (int y = 0; y < height / 2; y++) { +- int flipY = height - y - 1; +- uint8_t tmp[width * depth]; +- std::memcpy(tmp, &pixels[y * width * depth], width * depth); +- std::memcpy(&pixels[y * width * depth], &pixels[flipY * width * depth], width * depth); +- std::memcpy(&pixels[flipY * width * depth], tmp, width * depth); + internal->generateScreenshotStep = kScreenshotStepNone; + APP->scene->menuBar->show(); + APP->scene->rack->children.front()->show(); @@ -865,6 +887,7 @@ + + delete[] pixels; } ++#endif } @@ -963,29 +986,39 @@ void Window::cursorLock() { -- if (!settings::allowCursorLock) -- return; -- ++#ifdef DISTRHO_OS_WASM + if (!settings::allowCursorLock) + return; + -#if defined ARCH_MAC - glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); -#else - glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_DISABLED); --#endif ++ emscripten_request_pointerlock(internal->ui->getWindow().getApp().getClassName(), false); + #endif - internal->ignoreNextMouseDelta = true; } void Window::cursorUnlock() { -- if (!settings::allowCursorLock) -- return; -- ++#ifdef DISTRHO_OS_WASM + if (!settings::allowCursorLock) + return; + - glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_NORMAL); - internal->ignoreNextMouseDelta = true; ++ emscripten_exit_pointerlock(); ++#endif } bool Window::isCursorLocked() { - return glfwGetInputMode(win, GLFW_CURSOR) != GLFW_CURSOR_NORMAL; ++#ifdef DISTRHO_OS_WASM ++ EmscriptenPointerlockChangeEvent status; ++ if (emscripten_get_pointerlock_status(&status) == EMSCRIPTEN_RESULT_SUCCESS) ++ return status.isActive; ++#endif + return false; } @@ -1016,22 +1049,36 @@ - const GLFWvidmode* mode = glfwGetVideoMode(monitor); - glfwSetWindowMonitor(win, monitor, 0, 0, mode->width, mode->height, mode->refreshRate); - } -+void Window::setFullScreen(bool) { ++void Window::setFullScreen(const bool fullscreen) { ++#ifdef DISTRHO_OS_WASM ++ if (fullscreen) ++ emscripten_request_fullscreen(internal->ui->getWindow().getApp().getClassName(), false); ++ else ++ emscripten_exit_fullscreen(); ++#endif } bool Window::isFullScreen() { - GLFWmonitor* monitor = glfwGetWindowMonitor(win); - return monitor != NULL; -+#ifdef CARDINAL_TRANSPARENT_SCREENSHOTS ++#ifdef DISTRHO_OS_WASM ++ EmscriptenFullscreenChangeEvent status; ++ if (emscripten_get_fullscreen_status(&status) == EMSCRIPTEN_RESULT_SUCCESS) ++ return status.isFullscreen; ++ return false; ++#elif defined(CARDINAL_TRANSPARENT_SCREENSHOTS) && !defined(DGL_USE_GLES) + return internal->generateScreenshotStep != kScreenshotStepNone; +#else + return false; +#endif } - -@@ -722,14 +616,15 @@ +- + double Window::getMonitorRefreshRate() { + return internal->monitorRefreshRate; + } +@@ -722,14 +668,15 @@ return pair->second; // Load font @@ -1050,7 +1097,7 @@ } internal->fontCache[filename] = font; return font; -@@ -742,14 +637,15 @@ +@@ -742,14 +689,15 @@ return pair->second; // Load image @@ -1069,21 +1116,22 @@ } internal->imageCache[filename] = image; return image; -@@ -766,28 +662,146 @@ +@@ -766,28 +714,156 @@ } -void init() { - int err; -+void generateScreenshot() { -+ APP->window->internal->generateScreenshotStep = kScreenshotStepStarted; -+} - +- - // Set up GLFW -#if defined ARCH_MAC - glfwInitHint(GLFW_COCOA_CHDIR_RESOURCES, GLFW_TRUE); - glfwInitHint(GLFW_COCOA_MENUBAR, GLFW_FALSE); --#endif ++void generateScreenshot() { ++#ifndef DGL_USE_GLES ++ APP->window->internal->generateScreenshotStep = kScreenshotStepStarted; + #endif ++} - glfwSetErrorCallback(errorCallback); - err = glfwInit(); @@ -1091,6 +1139,7 @@ - osdialog_message(OSDIALOG_ERROR, OSDIALOG_OK, "Could not initialize GLFW."); - throw Exception("Could not initialize GLFW"); - } ++ +void init() { } @@ -1185,6 +1234,13 @@ + window->internal->callback->WindowParametersChanged(kWindowParameterLockModulePositions, + rack::settings::lockModules); + } ++ if (window->internal->params.squeezeModules != rack::settings::squeezeModules) ++ { ++ window->internal->params.squeezeModules = rack::settings::squeezeModules; ++ if (window->internal->callback != nullptr) ++ window->internal->callback->WindowParametersChanged(kWindowParameterSqueezeModulePositions, ++ rack::settings::squeezeModules); ++ } + if (window->internal->params.invertZoom != rack::settings::invertZoom) + { + window->internal->params.invertZoom = rack::settings::invertZoom; @@ -1214,6 +1270,7 @@ + rack::settings::tooltips = window->internal->params.tooltips; + rack::settings::knobScroll = window->internal->params.knobScroll; + rack::settings::lockModules = window->internal->params.lockModules; ++ rack::settings::squeezeModules = window->internal->params.squeezeModules; + rack::settings::invertZoom = window->internal->params.invertZoom; + rack::settings::rateLimit = window->internal->params.rateLimit; +} diff --git a/src/override/diffs/blendish.c.diff b/src/override/diffs/blendish.c.diff index 79696cdd..69f860af 100644 --- a/src/override/diffs/blendish.c.diff +++ b/src/override/diffs/blendish.c.diff @@ -1,5 +1,5 @@ ---- ../Rack/dep/oui-blendish/blendish.c 2021-10-17 13:57:24.613620711 +0100 -+++ blendish.c 2021-12-13 09:36:22.182673256 +0000 +--- ../Rack/dep/oui-blendish/blendish.c 2022-04-11 20:05:39.202902589 +0100 ++++ blendish.c 2022-04-11 19:51:05.409742542 +0100 @@ -61,7 +61,7 @@ } diff --git a/src/override/diffs/common.cpp.diff b/src/override/diffs/common.cpp.diff index ac85f16b..78d1a3d6 100644 --- a/src/override/diffs/common.cpp.diff +++ b/src/override/diffs/common.cpp.diff @@ -1,6 +1,6 @@ ---- ../Rack/src/common.cpp 2021-11-23 19:57:23.719015894 +0000 -+++ common.cpp 2022-03-14 23:25:17.492322806 +0000 -@@ -1,6 +1,38 @@ +--- ../Rack/src/common.cpp 2022-04-11 20:05:02.007283878 +0100 ++++ common.cpp 2022-07-12 09:45:31.518663160 +0100 +@@ -1,33 +1,77 @@ +/* + * DISTRHO Cardinal Plugin + * Copyright (C) 2021-2022 Filipe Coelho @@ -37,9 +37,27 @@ + +#include "DistrhoPluginUtils.hpp" - #if defined ARCH_WIN +-#if defined ARCH_WIN ++#if defined(ARCH_WIN) #include -@@ -14,20 +46,21 @@ + + FILE* fopen_u8(const char* filename, const char* mode) { ++ if (std::strncmp(filename, "\\\\?\\", 4) == 0 && std::getenv("CARDINAL_UNDER_WINE") != nullptr) ++ filename = "Z:\\dev\\null"; + return _wfopen(rack::string::UTF8toUTF16(filename).c_str(), rack::string::UTF8toUTF16(mode).c_str()); + } + ++#elif defined(DISTRHO_OS_WASM) ++#include ++#undef fopen ++ ++FILE* fopen_wasm(const char* filename, const char* mode) { ++ chmod(filename, 0777); ++ return std::fopen(filename, mode); ++} ++ + #endif + namespace rack { @@ -52,7 +70,7 @@ +const std::string APP_EDITION_NAME = "Audio Plugin"; const std::string APP_VERSION_MAJOR = "2"; -const std::string APP_VERSION = TOSTRING(_APP_VERSION); -+const std::string APP_VERSION = "2.1"; ++const std::string APP_VERSION = "2.1.2"; #if defined ARCH_WIN const std::string APP_OS = "win"; -#elif ARCH_MAC diff --git a/src/override/diffs/context.cpp.diff b/src/override/diffs/context.cpp.diff index 72729b9d..875e354b 100644 --- a/src/override/diffs/context.cpp.diff +++ b/src/override/diffs/context.cpp.diff @@ -1,5 +1,5 @@ ---- ../Rack/src/context.cpp 2022-02-05 22:30:09.253393116 +0000 -+++ context.cpp 2022-01-23 17:13:11.652514338 +0000 +--- ../Rack/src/context.cpp 2022-04-11 20:05:02.007283878 +0100 ++++ context.cpp 2022-04-11 19:51:05.409742542 +0100 @@ -1,3 +1,30 @@ +/* + * DISTRHO Cardinal Plugin diff --git a/src/override/diffs/plugin.cpp.diff b/src/override/diffs/plugin.cpp.diff index 73c7cb70..6e8392e6 100644 --- a/src/override/diffs/plugin.cpp.diff +++ b/src/override/diffs/plugin.cpp.diff @@ -1,6 +1,6 @@ ---- ../Rack/src/plugin.cpp 2022-02-05 22:30:09.265393248 +0000 -+++ plugin.cpp 2022-01-30 00:24:49.375329910 +0000 -@@ -1,308 +1,40 @@ +--- ../Rack/src/plugin.cpp 2022-07-12 09:46:20.716165650 +0100 ++++ plugin.cpp 2022-05-27 23:15:35.681273727 +0100 +@@ -1,342 +1,41 @@ -#include -#include -#include @@ -72,6 +72,18 @@ -// private API -//////////////////// - +- +-static void* getSymbol(void* handle, const char* name) { +- if (!handle) +- return NULL; +- +-#if defined ARCH_WIN +- return (void*) GetProcAddress((HMODULE) handle, name); +-#else +- return dlsym(handle, name); +-#endif +-} +- -/** Returns library handle */ -static void* loadLibrary(std::string libraryPath) { -#if defined ARCH_WIN @@ -131,12 +143,7 @@ - plugin->handle = loadLibrary(libraryPath); - - // Get plugin's init() function -- InitCallback initCallback; --#if defined ARCH_WIN -- initCallback = (InitCallback) GetProcAddress((HMODULE) plugin->handle, "init"); --#else -- initCallback = (InitCallback) dlsym(plugin->handle, "init"); --#endif +- InitCallback initCallback = (InitCallback) getSymbol(plugin->handle, "init"); - if (!initCallback) - throw Exception("Failed to read init() symbol in %s", libraryPath.c_str()); - @@ -183,6 +190,14 @@ - throw Exception("JSON parsing error at %s %d:%d %s", manifestFilename.c_str(), error.line, error.column, error.text); - DEFER({json_decref(rootJ);}); - +- // Load manifest +- plugin->fromJson(rootJ); +- +- // Reject plugin if slug already exists +- Plugin* existingPlugin = getPlugin(plugin->slug); +- if (existingPlugin) +- throw Exception("Plugin %s is already loaded, not attempting to load it again", plugin->slug.c_str()); +- - // Call init callback - InitCallback initCallback; - if (path == "") { @@ -193,13 +208,18 @@ - } - initCallback(plugin); - -- // Load manifest -- plugin->fromJson(rootJ); -- -- // Reject plugin if slug already exists -- Plugin* existingPlugin = getPlugin(plugin->slug); -- if (existingPlugin) -- throw Exception("Plugin %s is already loaded, not attempting to load it again", plugin->slug.c_str()); +- // Load modules manifest +- json_t* modulesJ = json_object_get(rootJ, "modules"); +- plugin->modulesFromJson(modulesJ); +- +- // Call settingsFromJson() if exists +- // Returns NULL for Core. +- auto settingsFromJson = (decltype(&::settingsFromJson)) getSymbol(plugin->handle, "settingsFromJson"); +- if (settingsFromJson) { +- json_t* settingsJ = json_object_get(settings::pluginSettingsJ, plugin->slug.c_str()); +- if (settingsJ) +- settingsFromJson(settingsJ); +- } - } - catch (Exception& e) { - WARN("Could not load plugin %s: %s", path.c_str(), e.what()); @@ -267,6 +287,10 @@ - // Get user plugins directory - system::createDirectory(pluginsPath); - +- // Don't load plugins if safe mode is enabled +- if (settings::safeMode) +- return; +- - // Extract packages and load plugins - extractPackages(pluginsPath); - loadPlugins(pluginsPath); @@ -296,11 +320,7 @@ - typedef void (*DestroyCallback)(); - DestroyCallback destroyCallback = NULL; - if (handle) { --#if defined ARCH_WIN -- destroyCallback = (DestroyCallback) GetProcAddress((HMODULE) handle, "destroy"); --#else -- destroyCallback = (DestroyCallback) dlsym(handle, "destroy"); --#endif +- destroyCallback = (DestroyCallback) getSymbol(handle, "destroy"); - } - if (destroyCallback) { - try { @@ -326,18 +346,33 @@ - - -void destroy() { -- for (Plugin* plugin : plugins) { +- while (!plugins.empty()) { +- Plugin* plugin = plugins.back(); - INFO("Destroying plugin %s", plugin->name.c_str()); - destroyPlugin(plugin); +- plugins.pop_back(); - } -- plugins.clear(); +- assert(plugins.empty()); -} - - +-void settingsMergeJson(json_t* rootJ) { +- for (Plugin* plugin : plugins) { +- auto settingsToJson = (decltype(&::settingsToJson)) getSymbol(plugin->handle, "settingsToJson"); +- if (settingsToJson) { +- json_t* settingsJ = settingsToJson(); +- json_object_set_new(rootJ, plugin->slug.c_str(), settingsJ); +- } +- else { +- json_object_del(rootJ, plugin->slug.c_str()); +- } +- } +-} ++void settingsMergeJson(json_t*) {} + + /** Given slug => fallback slug. - Correctly handles bidirectional fallbacks. - To request fallback slugs to be added to this list, open a GitHub issue. -@@ -352,8 +84,19 @@ +@@ -389,8 +88,19 @@ */ using PluginModuleSlug = std::tuple; static const std::map moduleSlugFallbacks = { @@ -358,7 +393,7 @@ // {{"", ""}, {"", ""}}, }; -@@ -441,7 +184,6 @@ +@@ -478,7 +188,6 @@ } diff --git a/src/override/plugin.cpp b/src/override/plugin.cpp index 76d10aad..a23b26cb 100644 --- a/src/override/plugin.cpp +++ b/src/override/plugin.cpp @@ -35,6 +35,9 @@ namespace rack { namespace plugin { +void settingsMergeJson(json_t*) {} + + /** Given slug => fallback slug. Correctly handles bidirectional fallbacks. To request fallback slugs to be added to this list, open a GitHub issue. @@ -43,6 +46,7 @@ static const std::map pluginSlugFallbacks = { {"VultModulesFree", "VultModules"}, {"VultModules", "VultModulesFree"}, {"AudibleInstrumentsPreview", "AudibleInstruments"}, + {"SequelSequencers", "DanielDavies"}, // {"", ""}, }; diff --git a/utils/create-macos-installer.sh b/utils/create-macos-installer.sh index 4ab84dd1..a465d2dc 100755 --- a/utils/create-macos-installer.sh +++ b/utils/create-macos-installer.sh @@ -9,13 +9,12 @@ else exit fi -rm -rf res -rm -rf au -rm -rf lv2 -rm -rf vst2 -rm -rf vst3 +rm -rf res jack native au lv2 vst2 vst3 +mkdir jack native au lv2 vst2 vst3 + +mv Cardinal.app jack/CardinalJACK.app +mv CardinalNative.app native/CardinalNative.app -mkdir au lv2 vst2 vst3 mv *.component au/ mv *.lv2 lv2/ mv *.vst vst2/ @@ -31,6 +30,18 @@ pkgbuild \ --root "${PWD}/res/" \ ../dpf-cardinal-resources.pkg +pkgbuild \ + --identifier "studio.kx.distrho.plugins.cardinal.jack" \ + --install-location "/Applications/" \ + --root "${PWD}/jack/" \ + ../dpf-cardinal-jack.pkg + +pkgbuild \ + --identifier "studio.kx.distrho.plugins.cardinal.native" \ + --install-location "/Applications/" \ + --root "${PWD}/native/" \ + ../dpf-cardinal-native.pkg + pkgbuild \ --identifier "studio.kx.distrho.plugins.cardinal.components" \ --install-location "/Library/Audio/Plug-Ins/Components/" \ @@ -57,7 +68,9 @@ pkgbuild \ cd .. -sed -e "s|@builddir@|${PWD}/build|" utils/macOS/package.xml.in > build/package.xml +sed -e "s|@builddir@|${PWD}/build|" \ + -e "s|@buildarchs@|${MACOS_ARCHS}|" \ + utils/macOS/package.xml.in > build/package.xml productbuild \ --distribution build/package.xml \ diff --git a/utils/create-windows-installer.sh b/utils/create-windows-installer.sh index a8b9c587..a6f2a213 100755 --- a/utils/create-windows-installer.sh +++ b/utils/create-windows-installer.sh @@ -19,7 +19,7 @@ iscc="${innodir}/drive_c/InnoSetup/ISCC.exe" # download it if [ ! -f "${dlfile}" ]; then # FIXME proper dl version - curl -L https://jrsoftware.org/download.php/is.exe?site=2 -o "${dlfile}" + curl -L https://jrsoftware.org/download.php/is.exe -o "${dlfile}" fi # initialize wine diff --git a/utils/distrho.icns b/utils/distrho.icns new file mode 100644 index 00000000..fd96fc6a Binary files /dev/null and b/utils/distrho.icns differ diff --git a/utils/inno/win32.iss b/utils/inno/win32.iss index 402ca24b..cff7ed9a 100644 --- a/utils/inno/win32.iss +++ b/utils/inno/win32.iss @@ -16,16 +16,17 @@ OutputDir=. UsePreviousAppDir=no [Types] -Name: "full"; Description: "Full installation"; +Name: "normal"; Description: "Full installation"; Name: "custom"; Description: "Custom installation"; Flags: iscustom; [Components] -Name: resources; Description: "Resources"; Types: full custom; Flags: fixed; -Name: carla; Description: "Carla/Ildaeil host tools"; Types: full; -Name: jack; Description: "JACK Standalone"; Types: full; -Name: lv2; Description: "LV2 plugin"; Types: full; -Name: vst2; Description: "VST2 plugin"; Types: full; -Name: vst3; Description: "VST3 plugin"; Types: full; +Name: resources; Description: "Resources"; Types: normal custom; Flags: fixed; +Name: carla; Description: "Carla/Ildaeil host tools"; Types: normal; +Name: jack; Description: "Standalone (JACK)"; Types: custom; +Name: native; Description: "Standalone (Native)"; Types: custom; +Name: lv2; Description: "LV2 plugin"; Types: normal; +Name: vst2; Description: "VST2 plugin"; Types: normal; +Name: vst3; Description: "VST3 plugin"; Types: normal; [Files] #include "resources.iss" @@ -46,6 +47,8 @@ Source: "..\..\carla\build\Carla\resources\lib\*.*"; DestDir: "{commoncf32}\Card Source: "..\..\carla\build\Carla\resources\lib\PyQt5\*.*"; DestDir: "{commoncf32}\Cardinal\Carla\resources\lib\PyQt5"; Components: carla; Flags: ignoreversion; ; jack Source: "..\..\bin\Cardinal.exe"; DestDir: "{app}"; Components: jack; Flags: ignoreversion; +; native +Source: "..\..\bin\CardinalNative.exe"; DestDir: "{app}"; Components: native; Flags: ignoreversion; ; lv2 Source: "..\..\bin\Cardinal.lv2\*.*"; DestDir: "{commoncf32}\LV2\Cardinal.lv2"; Components: lv2; Flags: ignoreversion; Source: "..\..\bin\CardinalFX.lv2\*.*"; DestDir: "{commoncf32}\LV2\CardinalFX.lv2"; Components: lv2; Flags: ignoreversion; @@ -58,4 +61,5 @@ Source: "..\..\bin\CardinalFX.vst3\Contents\x86-win\CardinalFX.vst3"; DestDir: " Source: "..\..\bin\CardinalSynth.vst3\Contents\x86-win\CardinalSynth.vst3"; DestDir: "{commoncf32}\VST3\CardinalSynth.vst3\Contents\x86-win"; Components: vst3; Flags: ignoreversion; [Icons] -Name: "{commonprograms}\Cardinal"; Filename: "{app}\Cardinal.exe"; IconFilename: "{app}\distrho.ico"; WorkingDir: "{app}"; Comment: "Virtual modular synthesizer plugin"; Components: jack; +Name: "{commonprograms}\Cardinal (JACK)"; Filename: "{app}\Cardinal.exe"; IconFilename: "{app}\distrho.ico"; WorkingDir: "{app}"; Comment: "Virtual modular synthesizer plugin (JACK variant)"; Components: jack; +Name: "{commonprograms}\Cardinal (Native)"; Filename: "{app}\CardinalNative.exe"; IconFilename: "{app}\distrho.ico"; WorkingDir: "{app}"; Comment: "Virtual modular synthesizer plugin (Native variant)"; Components: native; diff --git a/utils/inno/win64.iss b/utils/inno/win64.iss index 88fc0c9b..90cfa810 100644 --- a/utils/inno/win64.iss +++ b/utils/inno/win64.iss @@ -17,16 +17,17 @@ OutputDir=. UsePreviousAppDir=no [Types] -Name: "full"; Description: "Full installation"; +Name: "normal"; Description: "Full installation"; Name: "custom"; Description: "Custom installation"; Flags: iscustom; [Components] -Name: resources; Description: "Resources"; Types: full custom; Flags: fixed; -Name: carla; Description: "Carla/Ildaeil host tools"; Types: full; -Name: jack; Description: "JACK Standalone"; Types: full; -Name: lv2; Description: "LV2 plugin"; Types: full; -Name: vst2; Description: "VST2 plugin"; Types: full; -Name: vst3; Description: "VST3 plugin"; Types: full; +Name: resources; Description: "Resources"; Types: normal custom; Flags: fixed; +Name: carla; Description: "Carla/Ildaeil host tools"; Types: normal; +Name: jack; Description: "Standalone (JACK)"; Types: custom; +Name: native; Description: "Standalone (Native)"; Types: custom; +Name: lv2; Description: "LV2 plugin"; Types: normal; +Name: vst2; Description: "VST2 plugin"; Types: normal; +Name: vst3; Description: "VST3 plugin"; Types: normal; [Files] #include "resources.iss" @@ -47,6 +48,8 @@ Source: "..\..\carla\build\Carla\resources\lib\*.*"; DestDir: "{commoncf64}\Card Source: "..\..\carla\build\Carla\resources\lib\PyQt5\*.*"; DestDir: "{commoncf64}\Cardinal\Carla\resources\lib\PyQt5"; Components: carla; Flags: ignoreversion; ; jack Source: "..\..\bin\Cardinal.exe"; DestDir: "{app}"; Components: jack; Flags: ignoreversion; +; native +Source: "..\..\bin\CardinalNative.exe"; DestDir: "{app}"; Components: native; Flags: ignoreversion; ; lv2 Source: "..\..\bin\Cardinal.lv2\*.*"; DestDir: "{commoncf64}\LV2\Cardinal.lv2"; Components: lv2; Flags: ignoreversion; Source: "..\..\bin\CardinalFX.lv2\*.*"; DestDir: "{commoncf64}\LV2\CardinalFX.lv2"; Components: lv2; Flags: ignoreversion; @@ -59,4 +62,5 @@ Source: "..\..\bin\CardinalFX.vst3\Contents\x86_64-win\CardinalFX.vst3"; DestDir Source: "..\..\bin\CardinalSynth.vst3\Contents\x86_64-win\CardinalSynth.vst3"; DestDir: "{commoncf64}\VST3\CardinalSynth.vst3\Contents\x86_64-win"; Components: vst3; Flags: ignoreversion; [Icons] -Name: "{commonprograms}\Cardinal"; Filename: "{app}\Cardinal.exe"; IconFilename: "{app}\distrho.ico"; WorkingDir: "{app}"; Comment: "Virtual modular synthesizer plugin"; Components: jack; +Name: "{commonprograms}\Cardinal (JACK)"; Filename: "{app}\Cardinal.exe"; IconFilename: "{app}\distrho.ico"; WorkingDir: "{app}"; Comment: "Virtual modular synthesizer plugin (JACK variant)"; Components: jack; +Name: "{commonprograms}\Cardinal (Native)"; Filename: "{app}\CardinalNative.exe"; IconFilename: "{app}\distrho.ico"; WorkingDir: "{app}"; Comment: "Virtual modular synthesizer plugin (Native variant)"; Components: native; diff --git a/utils/macOS/Info_JACK.plist b/utils/macOS/Info_JACK.plist new file mode 100644 index 00000000..40d6d665 --- /dev/null +++ b/utils/macOS/Info_JACK.plist @@ -0,0 +1,20 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + Cardinal + CFBundleIconFile + distrho.icns + CFBundleIdentifier + Cardinal + NSHighResolutionCapable + + NSRequiresAquaSystemAppearance + + NSLocalNetworkUsageDescription + Cardinal requires network permissions for remote OSC control. + + diff --git a/utils/macOS/Info_Native.plist b/utils/macOS/Info_Native.plist new file mode 100644 index 00000000..bfc67c13 --- /dev/null +++ b/utils/macOS/Info_Native.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + CardinalNative + CFBundleIconFile + distrho.icns + CFBundleIdentifier + CardinalNative + NSHighResolutionCapable + + NSRequiresAquaSystemAppearance + + NSLocalNetworkUsageDescription + Cardinal requires network permissions for remote OSC control. + NSMicrophoneUsageDescription + Cardinal requires microphone permissions for audio input. + + diff --git a/utils/macOS/package.xml.in b/utils/macOS/package.xml.in index b2c8d9cb..381a28bb 100644 --- a/utils/macOS/package.xml.in +++ b/utils/macOS/package.xml.in @@ -3,12 +3,18 @@ Cardinal - + dpf-cardinal-resources.pkg + + dpf-cardinal-jack.pkg + + + dpf-cardinal-native.pkg + dpf-cardinal-components.pkg @@ -23,6 +29,8 @@ + + diff --git a/utils/macOS/welcome.txt b/utils/macOS/welcome.txt index 3fa7d291..48a4ca01 100644 --- a/utils/macOS/welcome.txt +++ b/utils/macOS/welcome.txt @@ -2,13 +2,12 @@ Cardinal is a free and open-source virtual modular synthesizer plugin. It is based on the popular VCV Rack but with a focus on being a fully self-contained plugin version. Cardinal provides 3 plugin variants - "main", Synth and FX. -They are all equivalent in performance and behaviour, with only the IO and metadata that changes. - +They are all equivalent in performance and behaviour. FX and Synth variants both have 2 audio outputs, while "main" has 8. All variants have MIDI input and output support. -This package provides the AU, LV2, VST2 and VST3 audio plugins for macOS. +This package provides the AU, LV2, VST2 and VST3 audio plugins, plus standalones for both JACK and native audio/MIDI. Notes: - - Due to AU and VST2 not supporting CV ports, the main variant is not available for these formats. - - The VST3 version is in progress, already part of the build but still experimental. + - Due to AU and VST2 not supporting CV ports, the main variant is not available for these formats + - The standalones are intentionally very barebones in terms of system integration, prefer to use the plugin versions if you can