Repository: acids-ircam/nn_tilde
Branch: master
Commit: ca97f8259442
Files: 107
Total size: 2.9 MB
Directory structure:
gitextract_nq2axijl/
├── .github/
│ └── workflows/
│ ├── build.yaml
│ └── python-publish.yaml
├── .gitignore
├── .gitmodules
├── LICENSE
├── MANIFEST.in
├── README.md
├── docs/
│ └── index.md
├── extras/
│ ├── 01_nn_attributes.maxpat
│ └── generate_test_model.py
├── install/
│ ├── MaxAPI.lib
│ ├── dylib_fix.py
│ ├── macos_max_makeub.sh
│ ├── macos_pd_makeub.sh
│ ├── max-linker-flags.txt
│ ├── mkl.cmake
│ └── patch_with_vst.sh
├── package-info.json.in
├── python_tools/
│ ├── __init__.py
│ ├── buffer.py
│ ├── codegen.py
│ ├── module.py
│ ├── templates/
│ │ ├── __init__.py
│ │ ├── attributes.py
│ │ └── buffers.py
│ └── test/
│ ├── test_attributes.maxpat
│ ├── test_attributes.py
│ ├── test_buffers.py
│ ├── test_list_attributes.maxpat
│ └── utils.py
├── requirements.txt
├── requirements_darwin_x64.txt
├── scripting/
│ ├── README.md
│ ├── effects.py
│ ├── effects.ts
│ ├── features.py
│ ├── features.ts
│ ├── scripting.maxpat
│ └── unmix.py
├── setup.py
└── src/
├── .nojekyll
├── CMakeLists.txt
├── backend/
│ ├── CMakeLists.txt
│ ├── backend.cpp
│ ├── backend.h
│ ├── parsing_utils.cpp
│ └── parsing_utils.h
├── cmake/
│ └── add_torch.cmake
├── extras/
│ ├── nn~ Overview.maxpat
│ └── patch_with_vst.sh
├── frontend/
│ ├── maxmsp/
│ │ ├── mc.nn_tilde/
│ │ │ ├── CMakeLists.txt
│ │ │ └── mc.nn_tilde.cpp
│ │ ├── mcs.nn_tilde/
│ │ │ ├── CMakeLists.txt
│ │ │ └── mcs.nn_tilde.cpp
│ │ ├── nn.info/
│ │ │ ├── CMakeLists.txt
│ │ │ └── nn.info.cpp
│ │ ├── nn_tilde/
│ │ │ ├── CMakeLists.txt
│ │ │ ├── nn_tilde.cpp
│ │ │ ├── nn_tilde_test.cpp
│ │ │ └── nn~.maxhelp
│ │ └── shared/
│ │ ├── array_tools.h
│ │ ├── buffer_tools.h
│ │ ├── dict_utils.h
│ │ ├── max_model_download.h
│ │ └── nn_base.h
│ └── puredata/
│ ├── nn_tilde/
│ │ ├── CMakeLists.txt
│ │ ├── nn_tilde.cpp
│ │ └── nn~-help.pd
│ └── shared/
│ ├── pd_buffer_manager.h
│ └── pd_model_download.h
├── help/
│ ├── mc.nn~.maxhelp
│ ├── mcs.nn~.maxhelp
│ ├── nn.info.maxhelp
│ └── nn~.maxhelp
├── models/
│ ├── demo_attributes.ts
│ ├── demo_buffers.ts
│ ├── demo_mc.ts
│ ├── effects.ts
│ ├── features.ts
│ └── wavetable.ts
├── patchers/
│ ├── after_help.maxpat
│ ├── help_hub.maxpat
│ ├── latent_remote/
│ │ ├── M4L.latent_remote.js
│ │ ├── M4L.latent_remote.maxhelp
│ │ ├── M4L.latent_remote.maxpat
│ │ ├── M4L.latent_slider.maxhelp
│ │ ├── M4L.latent_slider.maxpat
│ │ ├── M4L.latent_slider_component.maxpat
│ │ ├── frand.maxpat
│ │ ├── ierf.gendsp
│ │ ├── latent_remote.js
│ │ ├── latent_remote.maxhelp
│ │ ├── latent_remote.maxpat
│ │ ├── latent_slider.maxhelp
│ │ ├── latent_slider.maxpat
│ │ └── latent_slider_component.maxpat
│ ├── rave_help.maxpat
│ ├── ts_help.maxpat
│ └── vschaos_help.maxpat
├── shared/
│ ├── circular_buffer.h
│ ├── model_download.h
│ └── static_buffer.h
└── source/
├── attributes.py
├── buffers.py
├── effects.py
├── features.py
└── unmix.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/build.yaml
================================================
name: Build nn_tilde
on:
push:
tags:
- "v*"
jobs:
osx-arm64-build:
runs-on: macos-latest
steps:
- name: Check out code
uses: actions/checkout@v2
- run: |
git submodule update --init --recursive
git fetch --tags
curl -L ${{ secrets.WHEEL_PATH }} -o src/models/wheel.ts
du -sh src/models/*
- name: Setup LLVM
run: |
brew install llvm
- name: Setup miniconda
run: |
curl -L https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.sh > miniconda.sh
chmod +x ./miniconda.sh
bash ./miniconda.sh -b -u -p ./env
source ./env/bin/activate
conda install python=3.11
- name: Installing torch and requirements
run: |
source ./env/bin/activate
conda install -c conda-forge curl
pip install -r requirements.txt
- name: Setup puredata
run: |
mkdir puredata_include
curl -L https://raw.githubusercontent.com/pure-data/pure-data/master/src/m_pd.h -o ${{ github.workspace }}/puredata_include/m_pd.h
cat ${{ github.workspace }}/puredata_include/m_pd.h
- name: Build
run: |
mkdir build
export CC=$(brew --prefix llvm)/bin/clang
export CXX=$(brew --prefix llvm)/bin/clang++
export SIGN_ID=${{ secrets.SIGN_ID }}
cd build
cmake ../src -DCMAKE_C_COMPILER=$CC -DCMAKE_CXX_COMPILER=$CXX -DTORCH_MAC_UB_URL=${{ secrets.TORCH_UB_PATH }} -DCMAKE_BUILD_TYPE=Release -DCMAKE_OSX_ARCHITECTURES=arm64
make
- name: Max/MSP Package creation
run: |
mkdir nn_tilde
mkdir nn_tilde/help
mv src/externals src/help src/support src/patchers src/extras src/package-info.json src/icon.png src/source src/models src/misc nn_tilde
tar -czvf nn_max_msp_macOS_arm64.tar.gz nn_tilde
- name: PureData Package creation
run: |
rm -fr nn_tilde
mv build/frontend/puredata/nn_tilde .
mv src/frontend/puredata/nn_tilde/nn~-help.pd nn_tilde
rm -fr nn_tilde/CMakeFiles/ nn_tilde/*.cmake nn_tilde/Makefile
tar -czvf nn_puredata_macOS_arm64.tar.gz nn_tilde
- name: Upload binaries
uses: actions/upload-artifact@v4
with:
name: nn_tilde_mac_arm64
path: |
nn_max_msp_macOS_arm64.tar.gz
nn_puredata_macOS_arm64.tar.gz
osx-x64-build:
runs-on: macos-latest
steps:
- name: Check out code
uses: actions/checkout@v2
- uses: actions/setup-python@v5
with:
python-version: "3.11"
- run: |
git submodule update --init --recursive
git fetch --tags
git describe --tags --always
curl -L ${{ secrets.WHEEL_PATH }} -o src/models/wheel.ts
- name: Install x86_64 Homebrew
run: |
sudo rm -rf /opt/homebrew
sudo rm -rf /usr/local/homebrew
sudo mkdir -p /usr/local/homebrew
sudo chown -R $(whoami) /usr/local/homebrew
arch -x86_64 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" --prefix=/usr/local/homebrew
arch -x86_64 /usr/local/bin/brew shellenv >> $GITHUB_ENV
- name: Downloading wheels & libtorch for x64
run: |
curl -L ${{ secrets.TORCH_WHEEL }} > torch-2.5.1-cp313-cp313-macosx_14_0_x86_64.whl
curl -L ${{ secrets.TORCH_UB_PATH }} > torch_ub.zip
mkdir torch
unzip torch_ub.zip -d torch
mv torch/torch torch/libtorch
- name: Installing miniconda and dependencies...
run: |
ls
curl -L https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh > miniconda.sh
chmod 777 ./miniconda.sh
bash ./miniconda.sh -b -u -p ./env
source ./env/bin/activate
- name: Installing torch
run : |
source ./env/bin/activate
export DYLD_LIBRARY_PATH=${{ github.workspace }}/torch/lib:$DYLD_LIBRARY_PATH
arch -x86_64 conda install -c conda-forge cmake ninja numpy setuptools mkl mkl-include typing_extensions protobuf
arch -x86_64 pip install ./torch-2.5.1-cp313-cp313-macosx_14_0_x86_64.whl
arch -x86_64 pip install cached_conv>=2.5.0
arch -x86_64 pip install cmake==3.28
arch -x86_64 conda install -c conda-forge curl
TARGET_DIR=$(find env/lib -type d -name "python3*")
TARGET_DIR="${TARGET_DIR}/site-packages/torch/share/cmake/Caffe2/public"
cp install/mkl.cmake "${TARGET_DIR}"
- name: Setup LLVM
run: |
rm '/usr/local/bin/pydoc3'
rm /usr/local/bin/pydoc3.13
rm /usr/local/bin/python3
rm /usr/local/bin/python3-config
rm /usr/local/bin/python3.13
rm /usr/local/bin/python3.13-config
rm '/usr/local/bin/pip3.13'
rm '/usr/local/bin/idle3'
rm '/usr/local/bin/idle3.13'
arch -x86_64 /usr/local/bin/brew install llvm
export LDFLAGS="-L/usr/local/opt/llvm/lib"
export CPPFLAGS="-I/usr/local/opt/llvm/include"
- name: Setup puredata
run: |
mkdir puredata_include
curl -L https://raw.githubusercontent.com/pure-data/pure-data/master/src/m_pd.h -o puredata_include/m_pd.h
- name: Build
run: |
mkdir build
export CC=$(/usr/local/bin/brew --prefix llvm)/bin/clang
export CXX=$(/usr/local/bin/brew --prefix llvm)/bin/clang++
export SIGN_ID=${{ secrets.SIGN_ID }}
cd build
arch -x86_64 ../env/bin/cmake ../src -DCMAKE_C_COMPILER=$CC -DCMAKE_CXX_COMPILER=$CXX -DCMAKE_BUILD_TYPE=Release -DPUREDATA_INCLUDE_DIR=${{ github.workspace }}/puredata_include -DCMAKE_OSX_ARCHITECTURES=x86_64
arch -x86_64 make
- name: Max/MSP Package creation
run: |
mkdir nn_tilde
mkdir nn_tilde/help
mv src/externals src/help src/support src/patchers src/extras src/package-info.json src/icon.png src/source src/models src/misc nn_tilde
tar -czvf nn_max_msp_macOS_x64.tar.gz nn_tilde
- name: PureData Package creation
run: |
rm -fr nn_tilde
mv build/frontend/puredata/nn_tilde .
mv src/frontend/puredata/nn_tilde/nn~-help.pd nn_tilde
rm -fr nn_tilde/CMakeFiles/ nn_tilde/*.cmake nn_tilde/Makefile
tar -czvf nn_puredata_macOS_x64.tar.gz nn_tilde
- name: Upload binaries
uses: actions/upload-artifact@v4
with:
name: nn_tilde_mac_x86_64
path: |
nn_max_msp_macOS_x64.tar.gz
nn_puredata_macOS_x64.tar.gz
linux:
runs-on: ${{ matrix.runs-on }}
strategy:
matrix:
arch: [amd64]
include:
- arch: amd64
runs-on: ubuntu-latest
artifact-name: nn_linux_puredata_x86_64
conda-url: https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
steps:
- name: Check out code
uses: actions/checkout@v2
- run: |
git submodule update --init --recursive
git fetch --tags
GIT_TRACE=1 git describe --tags --always
- name: Setup LLVM
run: |
sudo apt-get install -y ca-certificates
sudo apt install gcc-10 g++-10
- name: Setup miniconda
run: |
echo "architecture : $(uname -m)"
curl --cacert /etc/ssl/certs/ca-certificates.crt -L ${{ matrix.conda-url }} > miniconda.sh
chmod +x ./miniconda.sh
bash ./miniconda.sh -b -u -p ./env
source ./env/bin/activate
conda install python=3.11
pip3 install torch --index-url https://download.pytorch.org/whl/cpu
conda install -c conda-forge curl
# conda install -c pytorch torch==2.5.1 torchaudio==2.5.1
# pip install -r requirements.txt
- name: Setup puredata
run: |
mkdir puredata_include
curl --cacert /etc/ssl/certs/ca-certificates.crt -L https://raw.githubusercontent.com/pure-data/pure-data/master/src/m_pd.h -o puredata_include/m_pd.h
- name: Build
run: |
mkdir build
export CC=$(which gcc-10)
export CXX=$(which g++-10)
cd build
cmake ../src -DCMAKE_C_COMPILER=$CC -DCMAKE_CXX_COMPILER=$CXX -DCMAKE_PREFIX_PATH=${{ github.workspace }}/env/lib/python3.12/site-packages/torch -DCMAKE_BUILD_TYPE=Release -DPUREDATA_INCLUDE_DIR=${{ github.workspace }}/puredata_include
make
- name: PureData Package creation
run: |
mkdir nn_tilde
mv build/frontend/puredata/nn_tilde .
mv src/frontend/puredata/nn_tilde/nn~-help.pd nn_tilde
rm -fr nn_tilde/CMakeFiles/ nn_tilde/*.cmake nn_tilde/Makefile
tar -czvf ${{ matrix.artifact-name }}.tar.gz nn_tilde
- name: Upload binaries
uses: actions/upload-artifact@v4
with:
name: ${{ matrix.artifact-name }}
path:
${{ matrix.artifact-name }}.tar.gz
windows-x64-build:
runs-on: windows-latest
steps:
- name: Check out code
uses: actions/checkout@v2
- run: |
git submodule update --init --recursive
git fetch --tags
curl -L ${{ secrets.WHEEL_PATH }} -o src/models/wheel.ts
- name: Setup puredata
run: |
mkdir pd
cd pd
curl -L https://msp.ucsd.edu/Software/pd-0.55-2.msw.zip -o pd.zip
unzip pd.zip
mv pd*/src .
mv pd*/bin .
cd ..
- name: Installing dependencies with vcpkg
run: |
git clone https://github.com/microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.bat
./vcpkg.exe integrate install
./vcpkg.exe install curl
cd ..
- name: Build
run: |
mkdir build
cd build
cmake ../src -G "Visual Studio 17 2022" -DPUREDATA_INCLUDE_DIR=${{ github.workspace }}/pd/src -DPUREDATA_BIN_DIR=${{ github.workspace }}/pd/bin -A x64
cmake --build . --config Release
- name: Max/MSP Package creation
run: |
mkdir nn_tilde
mkdir nn_tilde/support
ls
cp torch/libtorch/lib/* nn_tilde/support
cp vcpkg/installed/x64-windows/lib/*.lib nn_tilde/support
cp vcpkg/installed/x64-windows/bin/*.dll nn_tilde/support
curl -L https://curl.se/ca/cacert.pem -o nn_tilde/support/cacert.pem
$files = @("src\externals", "src\help", "src\patchers", "src\extras", "src\package-info.json", "src\icon.png", "src\source", "src\models", "src\misc")
foreach ($file in $files) {
mv $file nn_tilde
}
curl -L https://nubo.ircam.fr/index.php/s/7xBPxJZA6nJFHkG -o ${{ secrets.WHEEL_PATH }}
tar -czvf nn_max_msp_windows_x64.tar.gz nn_tilde
- name: PureData Package creation
run: |
Remove-Item -Recurse -Force nn_tilde
mkdir nn_tilde
mv build/frontend/puredata/nn_tilde/Release/* nn_tilde/
cp torch/libtorch/lib/* nn_tilde/
cp vcpkg/installed/x64-windows/lib/*.lib nn_tilde/
cp vcpkg/installed/x64-windows/bin/*.dll nn_tilde/
curl -L https://curl.se/ca/cacert.pem -o nn_tilde/cacert.pem
tar -czvf nn_puredata_windows_x64.tar.gz nn_tilde
- name: Upload binaries
uses: actions/upload-artifact@v4
with:
name: nn_tilde_win_x64
path: |
nn_max_msp_windows_x64.tar.gz
nn_puredata_windows_x64.tar.gz
MakeMaxUniversalForMac:
runs-on: macos-latest
needs: [osx-arm64-build, osx-x64-build]
steps:
- name: Download build binaries (arm64)
uses: actions/download-artifact@v4
with:
name: nn_tilde_mac_arm64
- name: Download build binaries (x86)
uses: actions/download-artifact@v4
with:
name: nn_tilde_mac_x86_64
- name: Build ub max with lipo
run: |
tar -xvf nn_max_msp_macOS_arm64.tar.gz
mv nn_tilde nn_tilde_arm64
tar -xvf nn_max_msp_macOS_x64.tar.gz
mv nn_tilde nn_tilde_x64
curl -L https://raw.githubusercontent.com/domkirke/nn_tilde/refs/heads/dev/install/macos_max_makeub.sh > macos_max_makeub.sh
chmod 777 ./macos_max_makeub.sh
./macos_max_makeub.sh
- name: Install signing certificate
run: |
CERT_PATH="$RUNNER_TEMP/signing-identity.p12"
echo "${{ secrets.CERT }}" | base64 -D > $CERT_PATH
security create-keychain -p "" build.keychain
security default-keychain -s build.keychain
security unlock-keychain -p "" build.keychain
security import $CERT_PATH -k build.keychain -P "${{ secrets.CERT_PASSWORD }}" -T /usr/bin/codesign
security set-key-partition-list -S apple-tool:,apple: -s -k "" build.keychain
codesign --deep --force --sign ${{ secrets.SIGN_ID }} nn_tilde/support/*.dylib
for i in $(find nn_tilde/externals/*/Contents/MacOS -type f -perm -111); do codesign --deep --force --sign ${{ secrets.SIGN_ID }} nn_tilde/externals/$(basename $i).mxo/Contents/MacOS/$(basename $i); done
- name: Compressing...
run: tar -czvf nn_max_msp_macos_ub.tar.gz nn_tilde
- name: Upload UB
uses: actions/upload-artifact@v4
with:
name: nn_tilde_macos_max_ub
path: |
nn_max_msp_macos_ub.tar.gz
MakePdUniversalForMac:
runs-on: macos-latest
needs: [osx-arm64-build, osx-x64-build]
steps:
- name: Download build binaries (arm64)
uses: actions/download-artifact@v4
with:
name: nn_tilde_mac_arm64
- name: Download build binaries (x86)
uses: actions/download-artifact@v4
with:
name: nn_tilde_mac_x86_64
- name: build ub max with lipo
run: |
tar -xvf nn_puredata_macOS_arm64.tar.gz
mv nn_tilde nn_tilde_arm64
tar -xvf nn_puredata_macOS_x64.tar.gz
mv nn_tilde nn_tilde_x64
curl -L https://raw.githubusercontent.com/domkirke/nn_tilde/refs/heads/dev/install/macos_pd_makeub.sh > macos_pd_makeub.sh
chmod 777 ./macos_pd_makeub.sh
./macos_pd_makeub.sh
- name: Install signing certificate
run: |
CERT_PATH="$RUNNER_TEMP/signing-identity.p12"
echo "${{ secrets.CERT }}" | base64 -D > $CERT_PATH
security create-keychain -p "" build.keychain
security default-keychain -s build.keychain
security unlock-keychain -p "" build.keychain
security import $CERT_PATH -k build.keychain -P "${{ secrets.CERT_PASSWORD }}" -T /usr/bin/codesign
security set-key-partition-list -S apple-tool:,apple: -s -k "" build.keychain
codesign --deep --force --sign ${{ secrets.SIGN_ID }} nn_tilde/*.dylib
codesign --deep --force --sign ${{ secrets.SIGN_ID }} nn_tilde/nn~.pd_darwin
- name: Compressing archive...
run: tar -czvf nn_puredata_macos_ub.tar.gz nn_tilde
- name: Upload UB
uses: actions/upload-artifact@v4
with:
name: nn_tilde_macos_pd_ub
path: |
nn_puredata_macos_ub.tar.gz
AutomaticRelease:
runs-on: ubuntu-latest
needs: [MakeMaxUniversalForMac, MakePdUniversalForMac, linux, windows-x64-build]
steps:
- name: Download Max build binaries (mac)
uses: actions/download-artifact@v4
with:
name: nn_tilde_macos_max_ub
- name: Download Pd binaries (mac)
uses: actions/download-artifact@v4
with:
name: nn_tilde_macos_pd_ub
- name: Download build binaries (linux_x86_64)
uses: actions/download-artifact@v4
with:
name: nn_linux_puredata_x86_64
- name: Download build binaries (windows mac_x86_64)
uses: actions/download-artifact@v4
with:
name: nn_tilde_win_x64
- name: Automated Release
uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
prerelease: false
files: |
nn_max_msp_macos_ub.tar.gz
nn_puredata_macos_ub.tar.gz
nn_linux_puredata_x86_64.tar.gz
nn_max_msp_windows_x64.tar.gz
nn_puredata_windows_x64.tar.gz
================================================
FILE: .github/workflows/python-publish.yaml
================================================
name: Upload Python Package
on:
push:
tags:
- "v*"
permissions:
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v3
with:
python-version: '3.10'
- name: Install dependencies
run: |
python -m pip install --upgrade pip setuptools wheel build
python -m pip install -r requirements.txt
- name: Build package
run: NN_TILDE_VERSION=${{ github.ref_name }} python -m build
- name: Publish package
uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
with:
verbose: true
user: __token__
password: ${{ secrets.PYPI_TOKEN }}
================================================
FILE: .gitignore
================================================
*build
src/externals
src/frontend/tests
src/tests
.vscode
*libtorch
*DS_Store*
src/docs
dist/
*.egg-info*
================================================
FILE: .gitmodules
================================================
[submodule "src/frontend/maxmsp/min-api"]
path = src/frontend/maxmsp/min-api
url = https://github.com/Cycling74/min-api.git
[submodule "src/json"]
path = src/json
url = https://github.com/nlohmann/json.git
================================================
FILE: LICENSE
================================================
Creative Commons Attribution-NonCommercial 4.0 International
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright and
certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
- Considerations for licensors: Our public licenses are intended for
use by those authorized to give the public permission to use
material in ways otherwise restricted by copyright and certain other
rights. Our licenses are irrevocable. Licensors should read and
understand the terms and conditions of the license they choose
before applying it. Licensors should also secure all rights
necessary before applying our licenses so that the public can reuse
the material as expected. Licensors should clearly mark any material
not subject to the license. This includes other CC-licensed
material, or material used under an exception or limitation to
copyright. More considerations for licensors :
wiki.creativecommons.org/Considerations_for_licensors
- Considerations for the public: By using one of our public licenses,
a licensor grants the public permission to use the licensed material
under specified terms and conditions. If the licensor's permission
is not necessary for any reason–for example, because of any
applicable exception or limitation to copyright–then that use is not
regulated by the license. Our licenses grant only permissions under
copyright and certain other rights that a licensor has authority to
grant. Use of the licensed material may still be restricted for
other reasons, including because others have copyright or other
rights in the material. A licensor may make special requests, such
as asking that all changes be marked or described. Although not
required by our licenses, you are encouraged to respect those
requests where reasonable. More considerations for the public :
wiki.creativecommons.org/Considerations_for_licensees
Creative Commons Attribution-NonCommercial 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and conditions.
- Section 1 – Definitions.
- a. Adapted Material means material subject to Copyright and
Similar Rights that is derived from or based upon the Licensed
Material and in which the Licensed Material is translated,
altered, arranged, transformed, or otherwise modified in a
manner requiring permission under the Copyright and Similar
Rights held by the Licensor. For purposes of this Public
License, where the Licensed Material is a musical work,
performance, or sound recording, Adapted Material is always
produced where the Licensed Material is synched in timed
relation with a moving image.
- b. Adapter's License means the license You apply to Your
Copyright and Similar Rights in Your contributions to Adapted
Material in accordance with the terms and conditions of this
Public License.
- c. Copyright and Similar Rights means copyright and/or similar
rights closely related to copyright including, without
limitation, performance, broadcast, sound recording, and Sui
Generis Database Rights, without regard to how the rights are
labeled or categorized. For purposes of this Public License, the
rights specified in Section 2(b)(1)-(2) are not Copyright and
Similar Rights.
- d. Effective Technological Measures means those measures that,
in the absence of proper authority, may not be circumvented
under laws fulfilling obligations under Article 11 of the WIPO
Copyright Treaty adopted on December 20, 1996, and/or similar
international agreements.
- e. Exceptions and Limitations means fair use, fair dealing,
and/or any other exception or limitation to Copyright and
Similar Rights that applies to Your use of the Licensed
Material.
- f. Licensed Material means the artistic or literary work,
database, or other material to which the Licensor applied this
Public License.
- g. Licensed Rights means the rights granted to You subject to
the terms and conditions of this Public License, which are
limited to all Copyright and Similar Rights that apply to Your
use of the Licensed Material and that the Licensor has authority
to license.
- h. Licensor means the individual(s) or entity(ies) granting
rights under this Public License.
- i. NonCommercial means not primarily intended for or directed
towards commercial advantage or monetary compensation. For
purposes of this Public License, the exchange of the Licensed
Material for other material subject to Copyright and Similar
Rights by digital file-sharing or similar means is NonCommercial
provided there is no payment of monetary compensation in
connection with the exchange.
- j. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance,
distribution, dissemination, communication, or importation, and
to make material available to the public including in ways that
members of the public may access the material from a place and
at a time individually chosen by them.
- k. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and
of the Council of 11 March 1996 on the legal protection of
databases, as amended and/or succeeded, as well as other
essentially equivalent rights anywhere in the world.
- l. You means the individual or entity exercising the Licensed
Rights under this Public License. Your has a corresponding
meaning.
- Section 2 – Scope.
- a. License grant.
- 1. Subject to the terms and conditions of this Public
License, the Licensor hereby grants You a worldwide,
royalty-free, non-sublicensable, non-exclusive, irrevocable
license to exercise the Licensed Rights in the Licensed
Material to:
- A. reproduce and Share the Licensed Material, in whole
or in part, for NonCommercial purposes only; and
- B. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
- 2. Exceptions and Limitations. For the avoidance of doubt,
where Exceptions and Limitations apply to Your use, this
Public License does not apply, and You do not need to comply
with its terms and conditions.
- 3. Term. The term of this Public License is specified in
Section 6(a).
- 4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter
created, and to make technical modifications necessary to do
so. The Licensor waives and/or agrees not to assert any
right or authority to forbid You from making technical
modifications necessary to exercise the Licensed Rights,
including technical modifications necessary to circumvent
Effective Technological Measures. For purposes of this
Public License, simply making modifications authorized by
this Section 2(a)(4) never produces Adapted Material.
- 5. Downstream recipients.
- A. Offer from the Licensor – Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
- B. No downstream restrictions. You may not offer or
impose any additional or different terms or conditions
on, or apply any Effective Technological Measures to,
the Licensed Material if doing so restricts exercise of
the Licensed Rights by any recipient of the Licensed
Material.
- 6. No endorsement. Nothing in this Public License
constitutes or may be construed as permission to assert or
imply that You are, or that Your use of the Licensed
Material is, connected with, or sponsored, endorsed, or
granted official status by, the Licensor or others
designated to receive attribution as provided in Section
3(a)(1)(A)(i).
- b. Other rights.
- 1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however,
to the extent possible, the Licensor waives and/or agrees
not to assert any such rights held by the Licensor to the
limited extent necessary to allow You to exercise the
Licensed Rights, but not otherwise.
- 2. Patent and trademark rights are not licensed under this
Public License.
- 3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
- Section 3 – License Conditions.
Your exercise of the Licensed Rights is expressly made subject to
the following conditions.
- a. Attribution.
- 1. If You Share the Licensed Material (including in modified
form), You must:
- A. retain the following if it is supplied by the
Licensor with the Licensed Material:
- i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if designated);
- ii. a copyright notice;
- iii. a notice that refers to this Public License;
- iv. a notice that refers to the disclaimer of
warranties;
- v. a URI or hyperlink to the Licensed Material to
the extent reasonably practicable;
- B. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
- C. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
- 2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may
be reasonable to satisfy the conditions by providing a URI
or hyperlink to a resource that includes the required
information.
- 3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
- 4. If You Share Adapted Material You produce, the Adapter's
License You apply must not prevent recipients of the Adapted
Material from complying with this Public License.
- Section 4 – Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
- a. for the avoidance of doubt, Section 2(a)(1) grants You the
right to extract, reuse, reproduce, and Share all or a
substantial portion of the contents of the database for
NonCommercial purposes only;
- b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material;
and
- c. You must comply with the conditions in Section 3(a) if You
Share all or a substantial portion of the contents of the
database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the
Licensed Rights include other Copyright and Similar Rights.
- Section 5 – Disclaimer of Warranties and Limitation of Liability.
- a. Unless otherwise separately undertaken by the Licensor, to
the extent possible, the Licensor offers the Licensed Material
as-is and as-available, and makes no representations or
warranties of any kind concerning the Licensed Material, whether
express, implied, statutory, or other. This includes, without
limitation, warranties of title, merchantability, fitness for a
particular purpose, non-infringement, absence of latent or other
defects, accuracy, or the presence or absence of errors, whether
or not known or discoverable. Where disclaimers of warranties
are not allowed in full or in part, this disclaimer may not
apply to You.
- b. To the extent possible, in no event will the Licensor be
liable to You on any legal theory (including, without
limitation, negligence) or otherwise for any direct, special,
indirect, incidental, consequential, punitive, exemplary, or
other losses, costs, expenses, or damages arising out of this
Public License or use of the Licensed Material, even if the
Licensor has been advised of the possibility of such losses,
costs, expenses, or damages. Where a limitation of liability is
not allowed in full or in part, this limitation may not apply to
You.
- c. The disclaimer of warranties and limitation of liability
provided above shall be interpreted in a manner that, to the
extent possible, most closely approximates an absolute
disclaimer and waiver of all liability.
- Section 6 – Term and Termination.
- a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply
with this Public License, then Your rights under this Public
License terminate automatically.
- b. Where Your right to use the Licensed Material has terminated
under Section 6(a), it reinstates:
- 1. automatically as of the date the violation is cured,
provided it is cured within 30 days of Your discovery of the
violation; or
- 2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect
any right the Licensor may have to seek remedies for Your
violations of this Public License.
- c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing
so will not terminate this Public License.
- d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
- Section 7 – Other Terms and Conditions.
- a. The Licensor shall not be bound by any additional or
different terms or conditions communicated by You unless
expressly agreed.
- b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
- Section 8 – Interpretation.
- a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could
lawfully be made without permission under this Public License.
- b. To the extent possible, if any provision of this Public
License is deemed unenforceable, it shall be automatically
reformed to the minimum extent necessary to make it enforceable.
If the provision cannot be reformed, it shall be severed from
this Public License without affecting the enforceability of the
remaining terms and conditions.
- c. No term or condition of this Public License will be waived
and no failure to comply consented to unless expressly agreed to
by the Licensor.
- d. Nothing in this Public License constitutes or may be
interpreted as a limitation upon, or waiver of, any privileges
and immunities that apply to the Licensor or You, including from
the legal processes of any jurisdiction or authority.
Creative Commons is not a party to its public licenses. Notwithstanding,
Creative Commons may elect to apply one of its public licenses to
material it publishes and in those instances will be considered the
"Licensor." The text of the Creative Commons public licenses is
dedicated to the public domain under the CC0 Public Domain Dedication.
Except for the limited purpose of indicating that material is shared
under a Creative Commons public license or as otherwise permitted by the
Creative Commons policies published at creativecommons.org/policies,
Creative Commons does not authorize the use of the trademark "Creative
Commons" or any other trademark or logo of Creative Commons without its
prior written consent including, without limitation, in connection with
any unauthorized modifications to any of its public licenses or any
other arrangements, understandings, or agreements concerning use of
licensed material. For the avoidance of doubt, this paragraph does not
form part of the public licenses.
Creative Commons may be contacted at creativecommons.org.
================================================
FILE: MANIFEST.in
================================================
include requirements.txt
================================================
FILE: README.md
================================================

# Demonstration video
[](https://www.youtube.com/watch?v=dMZs04TzxUI)
# Installation
Grab the [latest release of nn~](https://github.com/acids-ircam/nn_tilde/releases/latest) ! Be sure to download the correct version for your installation.
## MaxMSP
Uncompress the `.tar.gz` file in the Package folder of your Max installation, i.e. in `Documents/Max [your version]/Packages/`. You can then instantiate an `nn~` object! Alt-click the `nn~` object to open the help patch, or access the nn~ Overview patch in the Extras menu.
##### Mac alert : codesigned with IRCAM identity and not trigger MacOS quarantine ; if it does so, please launch in the terminal :
```bash
cd "~/Max X/Packages/nn_tilde
sudo codesign --deep --force --sign - support/*.dylib
sudo codesign --deep --force --sign - externals/*/Contents/MacOS/*
xattr -r -d com.apple.quarantine externals/*/Contents/MacOS/*
```
Alt+click on the `nn~` object to open the help patch, and follow the tabs to learn more about this project.
## PureData
Uncompress the `.tar.gz` file in the Package folder of your Pd installation, i.e. in `Documents/Pd/externals/`. You can then add a new path in the `Pd/File/Preferences/Path` menu pointing to the `nn_tilde` folder.
Similarly, the external should not be blocked on recent MacOS systems. It it still is, `cd` to the `nn_tilde` folder and fix with
```bash
xattr -r -d com.apple.quarantine Documents/Pd/externals/nn_tilde
sudo codesign --deep --force --sign - Documents/Pd/externals/nn_tilde/*.dylib
sudo codesign --deep --force --sign - Documents/Pd/externals/nn_tilde/nn\~.pd_darwin
```
# Usage
## Pretrained models
At its core, `nn~` is a translation layer between Max/MSP or PureData and the [libtorch c++ interface for deep learning](https://pytorch.org/). Alone, `nn~` is like an empty shell, and **requires pretrained models** to operate. Since v1.6.0, you can download them directly through Forum IRCAM API. Alternatively, you can find a few [RAVE](https://github.com/acids-ircam/RAVE) models [here](https://acids-ircam.github.io/rave_models_download) or [here](https://huggingface.co/Intelligent-Instruments-Lab/rave-models). Few [vschaos2](https://github.com/acids-ircam/vschaos2) models are also available[here](https://www.dropbox.com/sh/avdeiza7c6bn2of/AAAGZsnRo9ZVMa0iFhouCBL-a?dl=0).
Pretrained model for `nn~` are **torchscript files**, with a `.ts` extension. You can add these files to `nn_tilde/models` folders, or any place accessible through Max / Pd filesystem (Max: `Options/File Preferences`, PureData: `File/Preferences/Path`).
**New** : since v1.6.0, some models are directly downloadable through IRCAM Forum API.
Once this is done, you can load a model with `nn~` by providing its name as first argument (for example, here `isis.ts` located inside `nn_tilde/models` for Max, or among the PureData patch):
| Max / MSP |
PureData |
 |
 |
## Model information fetching
## Model information fetching
Coming with v1.6.0, the `nn.info` object allows model inspection and fetching avilable models for download on the IRCAM-API. With this object, you can get available methods and attributes for a given model. For example, you can see below that a RAVE model has three different methods : `encode`, `decode`, and `forward`.
### Methods
Models can have several _methods_, that correspond to several processing pipelines the model can achieve. Hence, each method can have a different number in inlets / outlets. The method is given as the third argument (for exemple, `decode` above), and equals `forward` by default.
### Attributes
It is possible the internal state of the module through _attributes_, that are **model-dependent** and defined at exportation. Model attributes can be set using _messages_, with the following syntax:
```bash
set ATTRIBUTE_NAME ATTRIBUTE_VAL_1 ATTRIBUTE_VAL_2
```
Using Max/MSP and PureData graphical objects, this can lead to an intuitive way to modify the behavior of the model, as shown below where we have two model attributes (i.e. generation temperature and generation mode), and the special `enable` attribute.
| Max / MSP |
PureData |
 |
 |
**New in 1.6.0**
- Buffers (Max) / Array (Pd) attribute setting to allow the `.ts` model to access internal buffers / arrays.
- `torch.Tensor` attributes can be set through Max/MSP `[array]`, allowing to set attributes of unlimited size.
## Buffer configuration
Internally, `nn~` has a circular buffer mechanism that helps maintain a reasonable computational load, if the given buffer size is greater tha 0. You can modify its size through the use of an additional integer after the method declaration, as shown below.
**Important**For Windows users, the circular buffer is automatically disabled because of a memory leak [that occurs when a TorchScript model is used in a separate thread](https://github.com/pytorch/pytorch/issues/24237). Unfortunately, this implies a much lower efficiency in terms of CPU.
| Max / MSP |
PureData |
 |
 |
## Multichannel (Max/MSP)
The Max/MSP release of `nn~` includes additional externals, namely `mc.nn~` and `mcs.nn~`, allowing the use of the multicanal abilities of Max 8+ to simplify the patching process with `nn~` and optionally decrease the computational load.
In the following examples, two audio files are being encoded then decoded by the same model in parallel

This patch can be improved both visually _and_ computationally speaking by using `mc.nn~` and using _batch operations_

Using `mc.nn~` we build the multicanal signals **over the different batches**. In the example above, each multicanal signal will have 2 different canals. We also propose the `mcs.nn~` external that builds multicanal signals **over the different dimensions**, as shown in the example below

In the example above, the two multicanals signals yielded by the `nn~ rave encode 2` object have 16 canals each, corresponding to the 16 latent dimensions. This can help patching, while keeping the batching abilities of `mc.nn~` by creating an explicit number of inlets / oulets corresponding to the number of examples we want to process in parallel.
To recap, the regular `nn~` operates on a single example, and has as many inlets / outlets as the model has inputs / outputs. The `mc.nn~` external is like `nn~`, but can process multiple examples _at the same time_. The `mcs.nn~` variant is a bit different, and can process mulitple examples at the same time, but will **have one inlet / outlet per examples**.
## Lazy mode (Max/MSP)
Since v1.6.0, nn~ has a `void` mode, that allows to initialise it with a fixed number of inlets / outlets, and may be attached to a model afterwards. This can be done with the `void` special model, that enables this lazy initialisation.
## Special messages
### enable [0 / 1]
Enable / Disable computation to save up computation without deleting the model. Similar to how a _bypass_ function would work.
### reload
Dynamically reloads the model. Can be useful if you want to periodically update the state of a model during a training.
### dump
Prints methods / attributes of the loaded model.
### print_available_models
Prints models downloadable through API.
### download
Download a model from the API.
### delete
Deletes a downloaded model.
### load
Change dynamically the incoming model.
### method
Change dynamically the used method.
# Scripting any PyTorch model in nn~
In the [`scripting`](https://github.com/acids-ircam/nn_tilde/tree/master/scripting) subfolder, you can find a series of examples that demonstrate how to write simple scripts to incorporate any type of deep models from PyTorch into MaxMSP (and potentially running on GPU). The examples show different use cases that also help to understand the input/output shapes relationships.
- `effects.py` : apply simple effects to the input (identical input and output shapes)
- `features.py` : compute spectral descriptors from the PyTorch audio library (each input audio buffer produces a single float as output)
- `unmix.py` : apply the unmix deep source separation model (input is split into 4 different audio streams containing « drums », « vocals », « bass » and « others »)
# Build Instructions
## macOS
- Download the latest libtorch (CPU) [here](https://pytorch.org/get-started/locally/) and unzip it to a known directory
- Run the following commands:
```bash
git clone https://github.com/acids-ircam/nn_tilde --recurse-submodules
cd nn_tilde
curl -L https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.sh > miniconda.sh
chmod +x ./miniconda.sh
bash ./miniconda.sh -b -u -p ./env
source ./env/bin/activate
pip install -r requirements.txt
conda install -c conda-forge curl
mkdir build
cd build
mkdir puredata_include
curl -L https://raw.githubusercontent.com/pure-data/pure-data/master/src/m_pd.h -o puredata_include/m_pd.h
export CC=$(brew --prefix llvm)/bin/clang
export CXX=$(brew --prefix llvm)/bin/clang++
cd build
cmake ../src -DCMAKE_C_COMPILER=$CC -DCMAKE_CXX_COMPILER=$CXX -DCMAKE_PREFIX_PATH=../env/lib/python3.12/site-packages/torch -DCMAKE_BUILD_TYPE=Release -DPUREDATA_INCLUDE_DIR=../puredata_include -DCMAKE_OSX_ARCHITECTURES=arm64
cmake --build . --config Release
```
please replace `arm64` in the last line by `x86_64` if you want compile for 64 bits. You can remove `-DPUREDATA_INCLUDE_DIR=../puredata_include` to compile only for Max. The Max package is produced in `src/`, and Pd external in `build/frontend/puredata/Release`.
## Windows
- Download Libtorch (CPU) and dependencies [here](https://pytorch.org/get-started/locally/) and unzip to a known directory.
- Install [Visual Studio Redistribuable](https://learn.microsoft.com/fr-fr/cpp/windows/latest-supported-vc-redist?view=msvc-170)
- Run the following commands (here for Git Bash):
```bash
git clone https://github.com/acids-ircam/nn_tilde --recurse-submodules
cd nn_tilde
curl -L https://download.pytorch.org/libtorch/cpu/libtorch-win-shared-with-deps-2.6.0%2Bcpu.zip > "libtorch.zip"
unzip libtorch.zip
mkdir pd
cd pd
curl -L https://msp.ucsd.edu/Software/pd-0.55-2.msw.zip -o pd.zip
unzip pd.zip
mv pd*/src .
mv pd*/bin .
cd ..
git clone https://github.com/microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.bat
./vcpkg.exe integrate install
./vcpkg.exe install curl
cd ..
mkdir build
cd build
mkdir puredata_include
curl -L https://raw.githubusercontent.com/pure-data/pure-data/master/src/m_pd.h -o puredata_include/m_pd.h
export CC=$(brew --prefix llvm)/bin/clang
export CXX=$(brew --prefix llvm)/bin/clang++
cd build
cmake ../src -G "Visual Studio 17 2022" -DTorch_DIR=../libtorch/share/cmake/Torch -DPUREDATA_INCLUDE_DIR=../pd/src -DPUREDATA_BIN_DIR=../pd/bin -A x64
cmake --build . --config Release
```
You can remove `-DPUREDATA_INCLUDE_DIR=../puredata_include` to compile only for Max. The Max package is produced in `src/`, and Pd external in `build/frontend/puredata/Release`.
## Raspberry Pi
**not availble in v1.6.0, planned in next version ; please take previous versions if needed**
While nn~ can be compiled and used on Raspberry Pi, you may have to consider using lighter deep learning models. We currently only support 64bit OS.
Install nn~ for PureData using
```bash
curl -s https://raw.githubusercontent.com/acids-ircam/nn_tilde/master/install/raspberrypi.sh | bash
```
# Funding
This work is led at IRCAM, and has been funded by the following projects
* [ANR MakiMono](https://acids.ircam.fr/course/makimono/)
* [ACTOR](https://www.actorproject.org/)
* [DAFNE+](https://dafneplus.eu/) N° 101061548
================================================
FILE: docs/index.md
================================================

# Demonstration video
[](https://www.youtube.com/watch?v=dMZs04TzxUI)
# Installation
Grab the [latest release of nn~](https://github.com/acids-ircam/nn_tilde/releases/latest) ! Be sure to download the correct version for your installation.
## MaxMSP
Uncompress the `.tar.gz` file in the Package folder of your Max installation, i.e. in `Documents/Max [your version]/Packages/`. You can then instantiate an `nn~` object! Alt-click the `nn~` object to open the help patch, or access the nn~ Overview patch in the Extras menu.
##### Mac alert : codesigned with IRCAM identity and not trigger MacOS quarantine ; if it does so, please launch in the terminal :
```bash
cd "~/Max X/Packages/nn_tilde
sudo codesign --deep --force --sign - support/*.dylib
sudo codesign --deep --force --sign - externals/*/Contents/MacOS/*
xattr -r -d com.apple.quarantine externals/*/Contents/MacOS/*
```
Alt+click on the `nn~` object to open the help patch, and follow the tabs to learn more about this project.
## PureData
Uncompress the `.tar.gz` file in the Package folder of your Pd installation, i.e. in `Documents/Pd/externals/`. You can then add a new path in the `Pd/File/Preferences/Path` menu pointing to the `nn_tilde` folder.
Similarly, the external should not be blocked on recent MacOS systems. It it still is, `cd` to the `nn_tilde` folder and fix with
```bash
xattr -r -d com.apple.quarantine Documents/Pd/externals/nn_tilde
sudo codesign --deep --force --sign - Documents/Pd/externals/nn_tilde/*.dylib
sudo codesign --deep --force --sign - Documents/Pd/externals/nn_tilde/nn\~.pd_darwin
```
# Usage
## Pretrained models
At its core, `nn~` is a translation layer between Max/MSP or PureData and the [libtorch c++ interface for deep learning](https://pytorch.org/). Alone, `nn~` is like an empty shell, and **requires pretrained models** to operate. Since v1.6.0, you can download them directly through Forum IRCAM API. Alternatively, you can find a few [RAVE](https://github.com/acids-ircam/RAVE) models [here](https://acids-ircam.github.io/rave_models_download) or [here](https://huggingface.co/Intelligent-Instruments-Lab/rave-models). Few [vschaos2](https://github.com/acids-ircam/vschaos2) models are also available[here](https://www.dropbox.com/sh/avdeiza7c6bn2of/AAAGZsnRo9ZVMa0iFhouCBL-a?dl=0).
Pretrained model for `nn~` are **torchscript files**, with a `.ts` extension. You can add these files to `nn_tilde/models` folders, or any place accessible through Max / Pd filesystem (Max: `Options/File Preferences`, PureData: `File/Preferences/Path`).
**New** : since v1.6.0, some models are directly downloadable through IRCAM Forum API.
Once this is done, you can load a model with `nn~` by providing its name as first argument (for example, here `isis.ts` located inside `nn_tilde/models` for Max, or among the PureData patch):
| Max / MSP |
PureData |
 |
 |
## Model information fetching
## Model information fetching
Coming with v1.6.0, the `nn.info` object allows model inspection and fetching avilable models for download on the IRCAM-API. With this object, you can get available methods and attributes for a given model. For example, you can see below that a RAVE model has three different methods : `encode`, `decode`, and `forward`.
### Methods
Models can have several _methods_, that correspond to several processing pipelines the model can achieve. Hence, each method can have a different number in inlets / outlets. The method is given as the third argument (for exemple, `decode` above), and equals `forward` by default.
### Attributes
It is possible the internal state of the module through _attributes_, that are **model-dependent** and defined at exportation. Model attributes can be set using _messages_, with the following syntax:
```bash
set ATTRIBUTE_NAME ATTRIBUTE_VAL_1 ATTRIBUTE_VAL_2
```
Using Max/MSP and PureData graphical objects, this can lead to an intuitive way to modify the behavior of the model, as shown below where we have two model attributes (i.e. generation temperature and generation mode), and the special `enable` attribute.
| Max / MSP |
PureData |
 |
 |
**New in 1.6.0**
- Buffers (Max) / Array (Pd) attribute setting to allow the `.ts` model to access internal buffers / arrays.
- `torch.Tensor` attributes can be set through Max/MSP `[array]`, allowing to set attributes of unlimited size.
## Buffer configuration
Internally, `nn~` has a circular buffer mechanism that helps maintain a reasonable computational load, if the given buffer size is greater tha 0. You can modify its size through the use of an additional integer after the method declaration, as shown below.
**Important**For Windows users, the circular buffer is automatically disabled because of a memory leak [that occurs when a TorchScript model is used in a separate thread](https://github.com/pytorch/pytorch/issues/24237). Unfortunately, this implies a much lower efficiency in terms of CPU.
| Max / MSP |
PureData |
 |
 |
## Multichannel (Max/MSP)
The Max/MSP release of `nn~` includes additional externals, namely `mc.nn~` and `mcs.nn~`, allowing the use of the multicanal abilities of Max 8+ to simplify the patching process with `nn~` and optionally decrease the computational load.
In the following examples, two audio files are being encoded then decoded by the same model in parallel

This patch can be improved both visually _and_ computationally speaking by using `mc.nn~` and using _batch operations_

Using `mc.nn~` we build the multicanal signals **over the different batches**. In the example above, each multicanal signal will have 2 different canals. We also propose the `mcs.nn~` external that builds multicanal signals **over the different dimensions**, as shown in the example below

In the example above, the two multicanals signals yielded by the `nn~ rave encode 2` object have 16 canals each, corresponding to the 16 latent dimensions. This can help patching, while keeping the batching abilities of `mc.nn~` by creating an explicit number of inlets / oulets corresponding to the number of examples we want to process in parallel.
To recap, the regular `nn~` operates on a single example, and has as many inlets / outlets as the model has inputs / outputs. The `mc.nn~` external is like `nn~`, but can process multiple examples _at the same time_. The `mcs.nn~` variant is a bit different, and can process mulitple examples at the same time, but will **have one inlet / outlet per examples**.
## Lazy mode (Max/MSP)
Since v1.6.0, nn~ has a `void` mode, that allows to initialise it with a fixed number of inlets / outlets, and may be attached to a model afterwards. This can be done with the `void` special model, that enables this lazy initialisation.
## Special messages
### enable [0 / 1]
Enable / Disable computation to save up computation without deleting the model. Similar to how a _bypass_ function would work.
### reload
Dynamically reloads the model. Can be useful if you want to periodically update the state of a model during a training.
### dump
Prints methods / attributes of the loaded model.
### print_available_models
Prints models downloadable through API.
### download
Download a model from the API.
### delete
Deletes a downloaded model.
### load
Change dynamically the incoming model.
### method
Change dynamically the used method.
# Build Instructions
## macOS
- Download the latest libtorch (CPU) [here](https://pytorch.org/get-started/locally/) and unzip it to a known directory
- Run the following commands:
```bash
git clone https://github.com/acids-ircam/nn_tilde --recurse-submodules
cd nn_tilde
curl -L https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.sh > miniconda.sh
chmod +x ./miniconda.sh
bash ./miniconda.sh -b -u -p ./env
source ./env/bin/activate
pip install -r requirements.txt
conda install -c conda-forge curl
mkdir build
cd build
mkdir puredata_include
curl -L https://raw.githubusercontent.com/pure-data/pure-data/master/src/m_pd.h -o puredata_include/m_pd.h
export CC=$(brew --prefix llvm)/bin/clang
export CXX=$(brew --prefix llvm)/bin/clang++
cd build
cmake ../src -DCMAKE_C_COMPILER=$CC -DCMAKE_CXX_COMPILER=$CXX -DCMAKE_PREFIX_PATH=../env/lib/python3.12/site-packages/torch -DCMAKE_BUILD_TYPE=Release -DPUREDATA_INCLUDE_DIR=../puredata_include -DCMAKE_OSX_ARCHITECTURES=arm64
cmake --build . --config Release
```
please replace `arm64` in the last line by `x86_64` if you want compile for 64 bits. You can remove `-DPUREDATA_INCLUDE_DIR=../puredata_include` to compile only for Max. The Max package is produced in `src/`, and Pd external in `build/frontend/puredata/Release`.
## Windows
- Download Libtorch (CPU) and dependencies [here](https://pytorch.org/get-started/locally/) and unzip to a known directory.
- Install [Visual Studio Redistribuable](https://learn.microsoft.com/fr-fr/cpp/windows/latest-supported-vc-redist?view=msvc-170)
- Run the following commands (here for Git Bash):
```bash
git clone https://github.com/acids-ircam/nn_tilde --recurse-submodules
cd nn_tilde
curl -L https://download.pytorch.org/libtorch/cpu/libtorch-win-shared-with-deps-2.6.0%2Bcpu.zip > "libtorch.zip"
unzip libtorch.zip
mkdir pd
cd pd
curl -L https://msp.ucsd.edu/Software/pd-0.55-2.msw.zip -o pd.zip
unzip pd.zip
mv pd*/src .
mv pd*/bin .
cd ..
git clone https://github.com/microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.bat
./vcpkg.exe integrate install
./vcpkg.exe install curl
cd ..
mkdir build
cd build
mkdir puredata_include
curl -L https://raw.githubusercontent.com/pure-data/pure-data/master/src/m_pd.h -o puredata_include/m_pd.h
export CC=$(brew --prefix llvm)/bin/clang
export CXX=$(brew --prefix llvm)/bin/clang++
cd build
cmake ../src -G "Visual Studio 17 2022" -DTorch_DIR=../libtorch/share/cmake/Torch -DPUREDATA_INCLUDE_DIR=../pd/src -DPUREDATA_BIN_DIR=../pd/bin -A x64
cmake --build . --config Release
```
You can remove `-DPUREDATA_INCLUDE_DIR=../puredata_include` to compile only for Max. The Max package is produced in `src/`, and Pd external in `build/frontend/puredata/Release`.
## Raspberry Pi
**not availble in v1.6.0, planned in next version ; please take previous versions if needed**
While nn~ can be compiled and used on Raspberry Pi, you may have to consider using lighter deep learning models. We currently only support 64bit OS.
Install nn~ for PureData using
```bash
curl -s https://raw.githubusercontent.com/acids-ircam/nn_tilde/master/install/raspberrypi.sh | bash
```
# Funding
This work is led at IRCAM, and has been funded by the following projects
* [ANR MakiMono](https://acids.ircam.fr/course/makimono/)
* [ACTOR](https://www.actorproject.org/)
* [DAFNE+](https://dafneplus.eu/) N° 101061548
================================================
FILE: extras/01_nn_attributes.maxpat
================================================
{
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 8,
"minor" : 3,
"revision" : 1,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 34.0, 87.0, 1489.0, 821.0 ],
"bglocked" : 1,
"openinpresentation" : 0,
"default_fontsize" : 12.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 1,
"gridsize" : [ 15.0, 15.0 ],
"gridsnaponopen" : 1,
"objectsnaponopen" : 1,
"statusbarvisible" : 2,
"toolbarvisible" : 1,
"lefttoolbarpinned" : 0,
"toptoolbarpinned" : 0,
"righttoolbarpinned" : 0,
"bottomtoolbarpinned" : 0,
"toolbars_unpinned_last_save" : 0,
"tallnewobj" : 0,
"boxanimatetime" : 200,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"description" : "",
"digest" : "",
"tags" : "",
"style" : "",
"subpatcher_template" : "",
"assistshowspatchername" : 0,
"boxes" : [ {
"box" : {
"id" : "obj-52",
"maxclass" : "newobj",
"numinlets" : 3,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 733.5, 638.0, 142.0, 22.0 ],
"text" : "rampsmooth~ 2048 2048"
}
}
, {
"box" : {
"format" : 6,
"id" : "obj-49",
"maxclass" : "flonum",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "", "bang" ],
"parameter_enable" : 0,
"patching_rect" : [ 888.5, 671.0, 50.0, 22.0 ]
}
}
, {
"box" : {
"id" : "obj-36",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "float" ],
"patching_rect" : [ 888.5, 638.0, 98.0, 22.0 ],
"text" : "snapshot~ 0.046"
}
}
, {
"box" : {
"id" : "obj-23",
"linecount" : 3,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 717.0, 464.5, 198.0, 47.0 ],
"presentation_linecount" : 3,
"text" : "models that output downsampled signals can be discretized using a snapshot~ object"
}
}
, {
"box" : {
"id" : "obj-16",
"maxclass" : "scope~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 807.5, 676.0, 71.0, 78.0 ]
}
}
, {
"box" : {
"id" : "obj-14",
"maxclass" : "scope~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 717.0, 676.0, 83.0, 78.0 ]
}
}
, {
"box" : {
"basictuning" : 440,
"data" : {
"clips" : [ {
"absolutepath" : "drumLoop.aif",
"filename" : "drumLoop.aif",
"filekind" : "audiofile",
"id" : "u599005403",
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-10",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 717.0, 535.0, 150.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"id" : "obj-8",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 717.0, 579.0, 140.0, 22.0 ],
"text" : "nn~ multieffect rms 2048"
}
}
, {
"box" : {
"hidden" : 1,
"id" : "obj-78",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 757.0, 127.0, 73.0, 22.0 ],
"text" : "loadmess 1."
}
}
, {
"box" : {
"id" : "obj-75",
"linecount" : 5,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 297.0, 127.0, 199.0, 74.0 ],
"text" : "an given attribute can be printed with the get method, followed by the attribute name.\nsimilarly, attributes can be changed using the set method."
}
}
, {
"box" : {
"id" : "obj-74",
"linecount" : 4,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 481.0, 520.0, 198.0, 60.0 ],
"text" : "arguments can also comprise several values, with different types. You can refer to the given python code to see how it is implemented."
}
}
, {
"box" : {
"id" : "obj-73",
"linecount" : 2,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 297.0, 241.5, 197.0, 33.0 ],
"text" : "for a boolean, either true or false must be sent"
}
}
, {
"box" : {
"id" : "obj-72",
"linecount" : 2,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 297.0, 205.0, 197.0, 33.0 ],
"text" : "there can be three types ofd attribute : int, str, and string"
}
}
, {
"box" : {
"id" : "obj-71",
"linecount" : 2,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 706.0, 241.5, 197.0, 33.0 ],
"text" : "for strings, int and floats, arguments can be sent directly."
}
}
, {
"box" : {
"id" : "obj-70",
"linecount" : 2,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 356.0, 63.0, 439.0, 33.0 ],
"text" : "also, attributes accesible from Max can also be listed by sending the get_settable_attributes message"
}
}
, {
"box" : {
"id" : "obj-69",
"linecount" : 2,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 356.0, 29.0, 439.0, 33.0 ],
"text" : "methods available for a given model can be printed by sending the get_available_methods message to nn~"
}
}
, {
"box" : {
"id" : "obj-66",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 356.0, 554.0, 94.0, 22.0 ],
"text" : "set fractal $1 $2"
}
}
, {
"box" : {
"id" : "obj-64",
"maxclass" : "number",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "", "bang" ],
"parameter_enable" : 0,
"patching_rect" : [ 356.0, 479.0, 50.0, 22.0 ]
}
}
, {
"box" : {
"id" : "obj-62",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 356.0, 520.0, 41.0, 22.0 ],
"text" : "pak i f"
}
}
, {
"box" : {
"id" : "obj-57",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 106.0, 132.0, 96.0, 22.0 ],
"text" : "get invert_signal"
}
}
, {
"box" : {
"id" : "obj-55",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 40.0, 74.0, 111.0, 22.0 ],
"text" : "nn~ multieffect thru"
}
}
, {
"box" : {
"id" : "obj-54",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 186.0, 29.0, 130.0, 22.0 ],
"text" : "get_settable_attributes"
}
}
, {
"box" : {
"id" : "obj-53",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 40.0, 29.0, 132.0, 22.0 ],
"text" : "get_available_methods"
}
}
, {
"box" : {
"id" : "obj-51",
"maxclass" : "scope~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 356.0, 660.0, 130.0, 130.0 ]
}
}
, {
"box" : {
"format" : 6,
"id" : "obj-50",
"maxclass" : "flonum",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "", "bang" ],
"parameter_enable" : 0,
"patching_rect" : [ 436.0, 479.0, 50.0, 22.0 ]
}
}
, {
"box" : {
"id" : "obj-46",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 356.0, 605.0, 138.0, 22.0 ],
"text" : "nn~ multieffect fractalize"
}
}
, {
"box" : {
"id" : "obj-45",
"maxclass" : "scope~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 1334.0, 356.0, 130.0, 130.0 ]
}
}
, {
"box" : {
"id" : "obj-44",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 1334.0, 301.0, 110.0, 22.0 ],
"text" : "nn~ multieffect rms"
}
}
, {
"box" : {
"id" : "obj-43",
"maxclass" : "scope~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 1175.0, 356.0, 130.0, 130.0 ]
}
}
, {
"box" : {
"id" : "obj-42",
"maxclass" : "scope~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 1030.0, 356.0, 130.0, 130.0 ]
}
}
, {
"box" : {
"id" : "obj-41",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "signal" ],
"patching_rect" : [ 1030.0, 301.0, 164.0, 22.0 ],
"text" : "nn~ multieffect midside"
}
}
, {
"box" : {
"basictuning" : 440,
"data" : {
"clips" : [ {
"absolutepath" : "drumLoop.aif",
"filename" : "drumLoop.aif",
"filekind" : "audiofile",
"id" : "u599005403",
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-40",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 1030.0, 238.0, 150.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"id" : "obj-38",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 159.0, 191.0, 124.0, 22.0 ],
"text" : "set invert_signal false"
}
}
, {
"box" : {
"id" : "obj-37",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 136.0, 162.0, 119.0, 22.0 ],
"text" : "set invert_signal true"
}
}
, {
"box" : {
"id" : "obj-35",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 50.0, 132.0, 53.0, 22.0 ],
"text" : "cycle~ 2"
}
}
, {
"box" : {
"id" : "obj-34",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 50.0, 247.0, 119.0, 22.0 ],
"text" : "nn~ multieffect invert"
}
}
, {
"box" : {
"id" : "obj-32",
"maxclass" : "scope~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 193.0, 285.0, 130.0, 130.0 ]
}
}
, {
"box" : {
"id" : "obj-33",
"maxclass" : "scope~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 50.0, 285.0, 130.0, 130.0 ]
}
}
, {
"box" : {
"id" : "obj-31",
"maxclass" : "scope~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 44.0, 660.0, 130.0, 130.0 ]
}
}
, {
"box" : {
"id" : "obj-30",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 118.0, 554.0, 195.0, 22.0 ],
"text" : "set polynomial_factors $1 $2 $3 $4"
}
}
, {
"box" : {
"id" : "obj-28",
"maxclass" : "newobj",
"numinlets" : 4,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 118.0, 520.0, 55.0, 22.0 ],
"text" : "pak f f f f"
}
}
, {
"box" : {
"format" : 6,
"id" : "obj-27",
"maxclass" : "flonum",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "", "bang" ],
"parameter_enable" : 0,
"patching_rect" : [ 290.0, 477.0, 50.0, 22.0 ]
}
}
, {
"box" : {
"format" : 6,
"id" : "obj-26",
"maxclass" : "flonum",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "", "bang" ],
"parameter_enable" : 0,
"patching_rect" : [ 233.0, 477.0, 50.0, 22.0 ]
}
}
, {
"box" : {
"format" : 6,
"id" : "obj-25",
"maxclass" : "flonum",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "", "bang" ],
"parameter_enable" : 0,
"patching_rect" : [ 176.0, 477.0, 50.0, 22.0 ]
}
}
, {
"box" : {
"format" : 6,
"id" : "obj-24",
"maxclass" : "flonum",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "", "bang" ],
"parameter_enable" : 0,
"patching_rect" : [ 118.0, 477.0, 50.0, 22.0 ]
}
}
, {
"box" : {
"id" : "obj-22",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 44.0, 477.0, 53.0, 22.0 ],
"text" : "cycle~ 2"
}
}
, {
"box" : {
"id" : "obj-21",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 44.0, 611.0, 147.0, 22.0 ],
"text" : "nn~ multieffect polynomial"
}
}
, {
"box" : {
"id" : "obj-20",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 620.0, 198.0, 129.0, 22.0 ],
"text" : "set saturate_mode clip"
}
}
, {
"box" : {
"id" : "obj-19",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 597.0, 162.0, 135.0, 22.0 ],
"text" : "set saturate_mode tanh"
}
}
, {
"box" : {
"format" : 6,
"id" : "obj-17",
"maxclass" : "flonum",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "", "bang" ],
"parameter_enable" : 0,
"patching_rect" : [ 757.0, 162.0, 50.0, 22.0 ]
}
}
, {
"box" : {
"id" : "obj-15",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 757.0, 198.0, 104.0, 22.0 ],
"text" : "set gain_factor $1"
}
}
, {
"box" : {
"id" : "obj-11",
"maxclass" : "scope~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 548.0, 285.0, 130.0, 130.0 ]
}
}
, {
"box" : {
"id" : "obj-12",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 548.0, 247.0, 133.0, 22.0 ],
"text" : "nn~ multieffect saturate"
}
}
, {
"box" : {
"id" : "obj-13",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 548.0, 132.0, 53.0, 22.0 ],
"text" : "cycle~ 2"
}
}
, {
"box" : {
"id" : "obj-9",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 1298.0, 20.0, 53.0, 22.0 ],
"text" : "cycle~ 8"
}
}
, {
"box" : {
"id" : "obj-5",
"maxclass" : "scope~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 1207.0, 90.0, 130.0, 130.0 ]
}
}
, {
"box" : {
"id" : "obj-6",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 1207.0, 52.0, 110.0, 22.0 ],
"text" : "nn~ multieffect add"
}
}
, {
"box" : {
"id" : "obj-7",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 1207.0, 20.0, 53.0, 22.0 ],
"text" : "cycle~ 2"
}
}
, {
"box" : {
"id" : "obj-3",
"maxclass" : "scope~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 1030.0, 90.0, 130.0, 130.0 ]
}
}
, {
"box" : {
"id" : "obj-2",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 1030.0, 52.0, 111.0, 22.0 ],
"text" : "nn~ multieffect thru"
}
}
, {
"box" : {
"id" : "obj-1",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 1030.0, 20.0, 53.0, 22.0 ],
"text" : "cycle~ 2"
}
}
, {
"box" : {
"angle" : 270.0,
"background" : 1,
"grad1" : [ 0.631372549019608, 0.631372549019608, 0.631372549019608, 1.0 ],
"grad2" : [ 0.76078431372549, 0.76078431372549, 0.76078431372549, 1.0 ],
"id" : "obj-67",
"maxclass" : "panel",
"mode" : 1,
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 35.5, 444.0, 657.5, 366.0 ],
"proportion" : 0.5
}
}
, {
"box" : {
"angle" : 270.0,
"background" : 1,
"grad1" : [ 0.631372549019608, 0.631372549019608, 0.631372549019608, 1.0 ],
"grad2" : [ 0.76078431372549, 0.76078431372549, 0.76078431372549, 1.0 ],
"id" : "obj-58",
"maxclass" : "panel",
"mode" : 1,
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 31.5, 13.0, 968.5, 95.0 ],
"proportion" : 0.5
}
}
, {
"box" : {
"angle" : 270.0,
"background" : 1,
"grad1" : [ 0.631372549019608, 0.631372549019608, 0.631372549019608, 1.0 ],
"grad2" : [ 0.76078431372549, 0.76078431372549, 0.76078431372549, 1.0 ],
"id" : "obj-60",
"maxclass" : "panel",
"mode" : 1,
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 35.5, 119.0, 475.5, 307.0 ],
"proportion" : 0.5
}
}
, {
"box" : {
"angle" : 270.0,
"background" : 1,
"grad1" : [ 0.631372549019608, 0.631372549019608, 0.631372549019608, 1.0 ],
"grad2" : [ 0.76078431372549, 0.76078431372549, 0.76078431372549, 1.0 ],
"id" : "obj-61",
"maxclass" : "panel",
"mode" : 1,
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 524.5, 119.0, 475.5, 307.0 ],
"proportion" : 0.5
}
}
, {
"box" : {
"angle" : 270.0,
"background" : 1,
"grad1" : [ 0.631372549019608, 0.631372549019608, 0.631372549019608, 1.0 ],
"grad2" : [ 0.76078431372549, 0.76078431372549, 0.76078431372549, 1.0 ],
"id" : "obj-4",
"maxclass" : "panel",
"mode" : 1,
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 706.0, 444.0, 294.0, 366.0 ],
"proportion" : 0.5
}
}
],
"lines" : [ {
"patchline" : {
"destination" : [ "obj-2", 0 ],
"source" : [ "obj-1", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-8", 0 ],
"source" : [ "obj-10", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-11", 0 ],
"source" : [ "obj-12", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-12", 0 ],
"source" : [ "obj-13", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-12", 0 ],
"midpoints" : [ 766.5, 232.0, 557.5, 232.0 ],
"source" : [ "obj-15", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-15", 0 ],
"source" : [ "obj-17", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-12", 0 ],
"midpoints" : [ 606.5, 187.0, 607.0, 187.0, 607.0, 232.0, 557.5, 232.0 ],
"source" : [ "obj-19", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-3", 0 ],
"source" : [ "obj-2", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-12", 0 ],
"midpoints" : [ 629.5, 232.0, 557.5, 232.0 ],
"source" : [ "obj-20", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-31", 0 ],
"source" : [ "obj-21", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-21", 0 ],
"order" : 1,
"source" : [ "obj-22", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-46", 0 ],
"midpoints" : [ 53.5, 597.0, 365.5, 597.0 ],
"order" : 0,
"source" : [ "obj-22", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-28", 0 ],
"midpoints" : [ 127.5, 502.0, 127.5, 502.0 ],
"source" : [ "obj-24", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-28", 1 ],
"midpoints" : [ 185.5, 502.0, 142.0, 502.0, 142.0, 514.0, 139.5, 514.0 ],
"source" : [ "obj-25", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-28", 2 ],
"midpoints" : [ 242.5, 514.0, 151.5, 514.0 ],
"source" : [ "obj-26", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-28", 3 ],
"midpoints" : [ 299.5, 514.0, 163.5, 514.0 ],
"source" : [ "obj-27", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-30", 0 ],
"source" : [ "obj-28", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-21", 0 ],
"source" : [ "obj-30", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-33", 0 ],
"source" : [ "obj-34", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-32", 0 ],
"midpoints" : [ 59.5, 230.0, 202.5, 230.0 ],
"order" : 0,
"source" : [ "obj-35", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-34", 0 ],
"midpoints" : [ 59.5, 187.0, 59.5, 187.0 ],
"order" : 1,
"source" : [ "obj-35", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-49", 0 ],
"source" : [ "obj-36", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-34", 0 ],
"midpoints" : [ 145.5, 239.0, 59.5, 239.0 ],
"source" : [ "obj-37", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-34", 0 ],
"midpoints" : [ 168.5, 239.0, 59.5, 239.0 ],
"source" : [ "obj-38", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-41", 1 ],
"midpoints" : [ 1072.25, 288.0, 1184.5, 288.0 ],
"source" : [ "obj-40", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-41", 0 ],
"order" : 1,
"source" : [ "obj-40", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-44", 0 ],
"midpoints" : [ 1039.5, 289.0, 1343.5, 289.0 ],
"order" : 0,
"source" : [ "obj-40", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-42", 0 ],
"source" : [ "obj-41", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-43", 0 ],
"source" : [ "obj-41", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-45", 0 ],
"source" : [ "obj-44", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-51", 0 ],
"source" : [ "obj-46", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-62", 1 ],
"source" : [ "obj-50", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-16", 0 ],
"source" : [ "obj-52", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-55", 0 ],
"source" : [ "obj-53", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-55", 0 ],
"midpoints" : [ 195.5, 64.0, 49.5, 64.0 ],
"source" : [ "obj-54", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-34", 0 ],
"midpoints" : [ 115.5, 238.0, 59.5, 238.0 ],
"source" : [ "obj-57", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-5", 0 ],
"source" : [ "obj-6", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-66", 0 ],
"source" : [ "obj-62", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-62", 0 ],
"source" : [ "obj-64", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-46", 0 ],
"source" : [ "obj-66", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 0 ],
"source" : [ "obj-7", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-17", 0 ],
"hidden" : 1,
"source" : [ "obj-78", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-14", 0 ],
"order" : 2,
"source" : [ "obj-8", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-36", 0 ],
"order" : 0,
"source" : [ "obj-8", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-52", 0 ],
"order" : 1,
"source" : [ "obj-8", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 1 ],
"source" : [ "obj-9", 0 ]
}
}
],
"dependency_cache" : [ {
"name" : "drumLoop.aif",
"bootpath" : "C74:/media/msp",
"type" : "AIFF",
"implicit" : 1
}
, {
"name" : "nn~.mxo",
"type" : "iLaX"
}
],
"autosave" : 0
}
}
================================================
FILE: extras/generate_test_model.py
================================================
from typing import List, Tuple
import torch
import torch.nn as nn
import nn_tilde
class AudioUtils(nn_tilde.Module):
def __init__(self):
super().__init__()
# REGISTER ATTRIBUTES
self.register_attribute('gain_factor', 1.)
self.register_attribute('polynomial_factors', (1., 0., 0., 0.))
self.register_attribute('saturate_mode', 'tanh')
self.register_attribute('invert_signal', False)
self.register_attribute('fractal', (2, 0.))
# REGISTER METHODS
self.register_method(
'thru',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=1,
input_labels=['(signal) input signal'],
output_labels=['(signal) output signal'],
)
self.register_method(
'invert',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=1,
input_labels=['(signal) input signal'],
output_labels=['(signal) output signal'],
)
self.register_method(
'add',
in_channels=2,
in_ratio=1,
out_channels=1,
out_ratio=1,
input_labels=['(signal) first signal', '(signal) second signal'],
output_labels=['(signal) output signal'],
)
self.register_method(
'saturate',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=1,
input_labels=['(signal) signal to saturate'],
output_labels=['(signal) saturated signal'],
)
self.register_method(
'midside',
in_channels=2,
in_ratio=1,
out_channels=2,
out_ratio=1,
input_labels=['(signal) L channel', '(signal) R channel'],
output_labels=['(signal) Mid channel', '(signal) Side channel'],
)
self.register_method(
'rms',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=1024,
input_labels=['(signal) signal to monitor'],
output_labels=['(signal) rms value'],
)
self.register_method(
'polynomial',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=1,
input_labels=['(signal) signal to distort'],
output_labels=['(signal) distorted signal'],
)
self.register_method(
'fractalize',
in_channels=1,
in_ratio=512,
out_channels=1,
out_ratio=512,
input_labels=['(signal) signal to replicate'],
output_labels=['(signal) fractalized signal'],
)
@torch.jit.export
def thru(self, x: torch.Tensor):
return x
# defining main methods
@torch.jit.export
def invert(self, x: torch.Tensor):
if self.invert_signal[0]:
return x
else:
return -x
@torch.jit.export
def add(self, x: torch.Tensor):
return x.sum(-2, keepdim=True) / 2
@torch.jit.export
def fractalize(self, x: torch.Tensor):
fractal_order = int(self.fractal[0])
fractal_amount = float(self.fractal[1])
downsampled_signal = x[..., ::fractal_order]
return x
@torch.jit.export
def polynomial(self, x: torch.Tensor):
out = torch.zeros_like(x)
for i in range(4):
out += self.polynomial_factors[i] * x.pow(i + 1)
return out
@torch.jit.export
def saturate(self, x: torch.Tensor):
saturate_mode = self.saturate_mode[0]
if saturate_mode == 'tanh':
return torch.tanh(x * self.gain_factor[0])
elif saturate_mode == 'clip':
return torch.clamp(x * self.gain_factor[0], -1, 1)
@torch.jit.export
def midside(self, x: torch.Tensor):
l, r = x[..., 0, :], x[..., 1, :]
return torch.stack([(l + r) / 2, (l - r) / 2], dim=-2)
@torch.jit.export
def rms(self, x: torch.Tensor):
x = x.reshape(x.shape[0], x.shape[1], 1024, -1)
rms = x.pow(2).sum(-2).sqrt() / x.size(-1)
return rms
# defining attribute getters
# WARNING : typing the function's ouptut is mandatory
@torch.jit.export
def get_gain_factor(self) -> float:
return float(self.gain_factor[0])
@torch.jit.export
def get_polynomial_factors(self) -> List[float]:
polynomial_factors: List[float] = []
for p in self.polynomial_factors:
polynomial_factors.append(float(p))
return polynomial_factors
@torch.jit.export
def get_saturate_mode(self) -> str:
return self.saturate_mode[0]
@torch.jit.export
def get_invert_signal(self) -> bool:
return self.invert_signal[0]
@torch.jit.export
def get_fractal(self) -> Tuple[int, float]:
return (int(self.fractal[0]), float(self.fractal[1]))
# defining attribute setter
# setters must return an error code :
# return 0 if the attribute has been adequately set,
# return -1 if the attribute was wrong.
@torch.jit.export
def set_gain_factor(self, x: float) -> int:
self.gain_factor = (x, )
return 0
@torch.jit.export
def set_polynomial_factors(self, factor1: float, factor2: float,
factor3: float, factor4: float) -> int:
factors = (factor1, factor2, factor3, factor4)
self.polynomial_factors = factors
return 0
@torch.jit.export
def set_saturate_mode(self, x: str):
if (x == 'tanh') or (x == 'clip'):
self.saturate_mode = (x, )
return 0
else:
return -1
@torch.jit.export
def set_invert_signal(self, x: bool):
self.invert_signal = (x, )
return 0
@torch.jit.export
def set_fractal(self, factor: int, amount: float):
if factor <= 0:
return -1
elif factor % 2 != 0:
return -1
self.fractal = (factor, float(amount))
return 0
if __name__ == '__main__':
model = AudioUtils()
model.export_to_ts('multieffect.ts')
================================================
FILE: install/dylib_fix.py
================================================
import argparse
import fnmatch
import tqdm
import re
import subprocess
import stat
import sys, os
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--path', type=Path, required=True)
parser.add_argument('-l', '--lib_paths', nargs="*")
parser.add_argument('-o', '--out_dir', type=Path, default=None, help="optional directory for copying dylibs")
parser.add_argument('--safe', action="store_true", help="safe mode")
parser.add_argument('--sign_id', type=str, default="-", help="codesign sign")
parser.add_argument('--noclean_rpath', action="store_true", help="does not clean rpath")
parser.add_argument('--verbose', action="store_true", help="verbose output")
args = parser.parse_args()
DEFAULT_EXCLUDE_PATHS_SOLVE = ['/System/Library/Frameworks', '@executable_path', '/usr/lib']
DEFAULT_EXCLUDE_LIBS = [r'libc\+\+.*', r'libSystem\.B\.*', r'libobjc\.A\.*']
def is_executable(file_path):
# Check if the file exists and is a regular file
if not os.path.isfile(file_path):
return False
try:
result = subprocess.run(
['file', '--brief', file_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True
)
output = result.stdout.strip()
# Check if the file is considered a Mach-O dynamically linked shared library or executable
if 'Mach-O' in output and ('executable' in output or 'dynamically linked shared library' in output or 'bundle' in output):
return True
except subprocess.CalledProcessError:
pass
return False
def extract_rpaths(executable_path, replace_dynamic_paths = True):
# Run otool to get load commands
try:
result = subprocess.run(['otool', '-l', executable_path],
check=True,
text=True,
capture_output=True)
output = result.stdout
# Regex pattern to capture RPATH entries
rpath_pattern = re.compile(r'LC_RPATH.*?\n.*?path (.*?) \(offset', re.S)
# Find all RPATH entries
rpaths = rpath_pattern.findall(output)
if replace_dynamic_paths:
for i, r in enumerate(rpaths):
rpaths[i] = re.sub("@loader_path", str(executable_path.parent), r)
for i, r in enumerate(rpaths):
if r.startswith("@loader_path") or r.startswith("@loader_path") or r.startswith("@executable_path"):
continue
rpaths[i] = Path(r)
return rpaths
except subprocess.CalledProcessError as e:
print(f"An error occurred: {e}")
return []
def get_library_name(libname):
return os.path.splitext(os.path.basename(libname))[0].split('.')[0]
def get_dependencies(filepath, dir_filter=[], lib_filter=[], rpath=None):
if not os.path.exists(filepath): return None
rpath = rpath or extract_rpaths(filepath)
try:
result = subprocess.run(['otool', '-L', filepath],
check=True,
text=True,
capture_output=True)
# Return the output
except subprocess.CalledProcessError as e:
return f"An error occurred: {e}"
result_lines = result.stdout.split('\n')
deps = {}
for r in result_lines:
result_parsed = re.match(r"\s*(.+)\s+\((.+)\)$", r)
if result_parsed is None:
continue
outs = result_parsed.groups()
path = outs[0]
dep_name = path.split('/')[-1]
original_path = str(path)
for rp in rpath:
path_tmp = Path(str(path).replace('@rpath', str(rp)))
if os.path.exists(path_tmp):
path = path_tmp
break
if True in [Path(path).is_relative_to(r) for r in dir_filter]: continue
if True in [re.search(f, str(path)) is not None for f in lib_filter]: continue
deps[get_library_name(dep_name)] = {'path': path, 'version': outs[1], 'origin': filepath, 'linked': original_path}
return deps
def get_architectures(file_path):
try:
result = subprocess.run(
['file', file_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
check=True
)
output = result.stdout.strip()
return output.split(" ")[-1]
except subprocess.CalledProcessError as e:
return f"Error: {e.stderr.strip()}"
def get_find_results(directory, pattern):
try:
# Run the find command
command = ['find', directory, '-name', pattern]
print(" ".join(command))
result = subprocess.run(command,
check=True,
text=True,
capture_output=True)
file_list = result.stdout.strip().split('\n')
file_list = [f for f in file_list if f]
return file_list
except subprocess.CalledProcessError as e:
return []
def find_candidates_for(lib_name, lib_dir, lib_arch, allow_different_arch: bool = True):
lib_name, lib_ext = os.path.splitext(lib_name)
lib_name_parts = lib_name.split('.')
candidates = []
for l in lib_dir:
print('parsing %s'%lib_name_parts)
for i in reversed(range(1, len(lib_name_parts)+1)):
results = get_find_results(l, ".".join(lib_name_parts[:i]) + "*" + lib_ext)
if len(results) > 0:
break
candidates.extend(results)
print("candidates before filtering : ", candidates)
if len(candidates) == 0:
return []
candidates_filt_arch = list(filter(lambda x: get_architectures(x) == lib_arch, candidates))
if len(candidates_filt_arch) == 0:
print('[Warning] Candidates found for %s, but with wrong architecture'%lib_name)
if not allow_different_arch:
return []
else:
candidates = candidates_filt_arch
print(candidates)
for i, c in enumerate(candidates):
while os.path.islink(c):
c = os.readlink(os.path.abspath(c))
if not os.path.isabs(c):
c = os.path.join(os.path.dirname(candidates[i]), c)
candidates[i] = c
return list(set(candidates))
def find_most_relevant_dylib_candidate(name, candidates, accept_weak_matching=False):
name_ext = os.path.splitext(name)[1][1:]
re_result = re.match(rf"^([\d\w_]+)\.?([\d\.]*)\.{name_ext}$", name)
if re_result is None:
print(f'[Warning] Could not parse name {name} for dynamic lib retrieving ; taking first : {candidates[0]}')
return candidates[0]
lib_name, lib_version = re_result.groups()
matching_name_and_version = []
matching_name = []
matching = []
for c in candidates:
c_name = os.path.basename(c)
re_result = re.match(rf"^([\d\w_]+)\.?([\d\.]*)\.{name_ext}$", c_name)
if re_result is not None:
c_name, c_version = re_result.groups()
if lib_name == c_name and c_version.startswith(lib_version):
matching_name_and_version.append(c)
elif lib_name == c_name:
matching_name.append(c)
else:
matching.append(c)
if len(matching_name_and_version) > 0:
return matching_name_and_version[0]
elif len(matching_name) > 0:
print(f'[Warning] Could only find candidate with different version : {matching_name[0]}')
return matching_name[0]
else:
if accept_weak_matching:
print(f'[Warning] Could only find weakly matching library : {matching[0]}')
return matching[0]
else:
return None
def clean_rpath_for_target_executable(lib_path):
actions = []
rpaths = extract_rpaths(lib_path, replace_dynamic_paths=False)
for p in rpaths:
if not str(p).startswith('@loader_path'): actions.append(['-delete_rpath', p, lib_path])
return actions
def most_relevant_lib(lib_name, path_dicts, dep_paths=[], arch="arm64"):
path_list = [Path(p['path']) for p in path_dicts]
path_filtered_list = []
for p in path_list:
print('looking in %s...'%p)
while os.path.islink(p):
p = Path(p.parent / os.readlink(p)).resolve().absolute()
if not p.exists(): continue
if not is_executable(p): continue
path_filtered_list.append(p)
path_list = list(set(path_filtered_list))
path_list = filter(lambda x: x.exists(), path_list)
path_list = filter(lambda x: is_executable(x), path_list)
path_list = list(path_list)
if len(path_list) == 0:
# not found; look for candidate
candidates = find_candidates_for(f"{lib_name}.dylib", dep_paths, arch)
candidate = find_most_relevant_dylib_candidate(f"{lib_name}.dylib", candidates)
if candidate is None:
raise RuntimeError('no valid library found for %s in %s (candidates : %s)'%(lib_name, dep_paths, candidates))
return candidate
# find in priority the librairies given in arguments
for libdir in map(Path, dep_paths):
for path in path_list:
if path.is_relative_to(libdir): return path
return path_list[0]
def lib_from_exc_path(exc_path, lib_path):
exc_parts = exc_path.parts
lib_parts = lib_path.parts
assert exc_parts[0] == lib_parts[0], "files do not have a single common root"
i = 0
while exc_parts[i] == lib_parts[i]:
i+=1
return os.path.join(*([".."] * (len(exc_parts[i:])-1) + list(lib_parts[i:])))
def parse_actions_from_executable(exec_path, dep_paths=[], main_dir = None, verbose=False):
if not os.path.exists(exec_path):
raise FileNotFoundError(exec_path)
if verbose: print(f'parsing {str(exec_path)}...')
libs_deps = {}
libs_paths = {}
libs_analysed = []
libs_to_analyse = [exec_path]
libs_hash = {}
libs_hash_linked = {}
arch = get_architectures(exec_path)
# analyse dependencies
while len(libs_to_analyse) != 0:
if verbose: print('anlysing librairies %s'%libs_to_analyse)
parsed_deps = []
# fetch dependencies
for current_lib in libs_to_analyse:
if verbose: print('fetching dependencies from %s'%(current_lib))
lib_deps = get_dependencies(current_lib, dir_filter=DEFAULT_EXCLUDE_PATHS_SOLVE, lib_filter=DEFAULT_EXCLUDE_LIBS)
for dep_name, dep_params in lib_deps.items():
parsed_deps.append(dep_name)
libs_deps[dep_name] = libs_deps.get(dep_name, []) + [dep_params]
libs_hash[get_library_name(dep_params['path'])] = libs_hash.get(get_library_name(dep_params['path']), []) + [dep_params['origin']]
libs_hash_linked[get_library_name(dep_params['path'])] = libs_hash_linked.get(get_library_name(dep_params['path']), []) + [dep_params['linked']]
del libs_to_analyse[libs_to_analyse.index(current_lib)]
libs_analysed.append(get_library_name(current_lib))
# parse dependencies
for p in parsed_deps:
if verbose: print('fetching paths for %s'%p)
if p not in libs_paths:
lib_path = most_relevant_lib(p, libs_deps[p], dep_paths, arch)
print('found lib : %s'%lib_path)
libs_paths[p] = Path(lib_path)
if p not in libs_analysed:
print('adding %s for parsing'%p)
libs_to_analyse.append(libs_paths[p])
actions = []
exec_dir = exec_path.parent
os.makedirs(str(main_dir.resolve()), exist_ok=True)
for k, v in libs_paths.items():
if not (main_dir / v.name).resolve().exists():
actions.append(['copy', str(v), str(main_dir)])
for k, v in libs_hash.items():
for i, v_tmp in enumerate(v):
# if str(libs_hash_linked[k][i]).startswith('@rpath'):
# continue
if get_library_name(libs_hash_linked[k][i]) == get_library_name(v_tmp.name):
if v_tmp.stem == exec_path.stem:
actions.append(['-id', f"@loader_path/{v_tmp.name}", str(exec_dir / v_tmp.name)])
else:
actions.append(['-id', f"@loader_path/{v_tmp.name}", str(main_dir / v_tmp.name)])
else:
current_dep = str(libs_hash_linked[k][i])
# new_dep = f"@loader_path/{libs_paths[get_library_name(current_dep)].name}"
if v_tmp.stem == exec_path.stem:
new_dep = f"@loader_path/{lib_from_exc_path(exec_path, main_dir / libs_paths[get_library_name(current_dep)].name)}"
actions.append(['-change', current_dep, new_dep, str(exec_dir / v_tmp.name)])
else:
new_dep = f"@loader_path/{libs_paths[get_library_name(current_dep)].name}"
actions.append(['-change', current_dep, new_dep, str(main_dir / v_tmp.name)])
return actions
def perform_action(action, main_dir):
try:
if action[0] == "-change":
# Run the find command
result = subprocess.run(['install_name_tool',
'-change',
action[1],
action[2],
action[3]],
check=True,
text=True,
capture_output=False)
return
elif action[0] == "-id":
target_path = str(main_dir / os.path.split(action[1])[-1])
result = subprocess.run(['install_name_tool',
'-id',
action[1],
target_path],
check=True,
text=True,
capture_output=False)
elif action[0] == "copy":
target_path = main_dir / os.path.split(action[1])[-1]
if not target_path.exists():
result = subprocess.run(['cp',
action[1],
str(target_path)],
check=True,
text=True,
capture_output=False)
elif action[0] == "-delete_rpath":
target_path = str(main_dir / os.path.split(action[2])[-1])
result = subprocess.run(['install_name_tool',
'-delete_rpath',
action[1],
target_path],
check=True,
text=True,
capture_output=False)
elif action[0] == "-add_rpath":
target_path = str(main_dir / os.path.split(action[2])[-1])
result = subprocess.run(['install_name_tool',
'-add_rpath',
action[1],
target_path],
check=True,
text=True,
capture_outpu=False)
elif action[0] == "clean_rpath":
rpaths = extract_rpaths(str(main_dir / action[1]), replace_dynamic_paths=False)
for r in rpaths:
try:
subprocess.run(['install_name_tool', '-delete_rpath', str(r), str(action[1])])
except subprocess.SubprocessError as e:
print("problem with clean_rpath : %s"%e)
pass
else:
print('[Warning] not known action : %s'%action)
except subprocess.CalledProcessError as e:
raise e
def print_action(idx, action):
if action[0] == "copy":
print(f'{idx:02d} cp {"|".join(action[1:])} -> @rpath')
elif action[0] == "-change":
print(f"{idx:02d} -change: {os.path.basename(action[3])}: {action[1]}->{action[2]}")
elif action[0] == "-id":
print(f"{idx:02d} -id: {os.path.basename(action[1])}")
elif action[0] == "-delete_rpath":
print(f"{idx:02d} -delete_rpath: {action[1]} -> {action[2]}")
elif action[0] == "clean_rpath":
print(f"{idx:02d} clean_rpath: {action[1]}")
else:
print(idx, action)
if __name__ == "__main__":
exec_path = Path(args.path)
main_dir = args.out_dir or args.path.parent
actions = parse_actions_from_executable(exec_path, args.lib_paths, main_dir, args.verbose)
if args.safe:
for i, a in enumerate(actions):
print_action(i, a)
print('continue?')
answ = ""
while answ.lower() not in ['y', 'n']:
answ = input('[y/n] : ')
if answ.lower() == "n": raise SystemExit("raised by user")
os.makedirs(str(main_dir.resolve()), exist_ok=True)
for a in tqdm.tqdm(actions):
perform_action(a, main_dir = main_dir)
if not args.noclean_rpath:
for m in [os.path.join(main_dir, m) for m in os.listdir(main_dir)] + [args.path]:
if is_executable(m):
perform_action(['clean_rpath', m], main_dir)
if args.sign_id == "": args.sign_id = "-"
for m in [os.path.join(main_dir, m) for m in os.listdir(main_dir)] + [args.path]:
try:
subprocess.run(['chmod', '+x', m])
subprocess.run(['codesign', '--deep', '--force', '--options=runtime', '--sign', args.sign_id, m])
subprocess.run(["xattr", "-r", "-d", "com.apple.quarantine", m])
except subprocess.CalledProcessError as e:
print(f'Could not chmod / codesign file {m} ; codesign needed')
================================================
FILE: install/macos_max_makeub.sh
================================================
TARGET_DIR=$1
if [ -z $TARGET_DIR ]; then
TARGET_DIR="nn_tilde"
fi
echo "${TARGET_DIR}"
if [[ ! -d "${TARGET_DIR}_arm64" ]]; then
echo "[Error] folder ${TARGET_DIR}_arm64 not found"
exit
fi
if [[ ! -d "${TARGET_DIR}_x64" ]]; then
echo "[Error] folder ${TARGET_DIR}_arm64 not found"
exit
fi
if [[ ! -d "${TARGET_DIR}" ]]; then
cp -r ${TARGET_DIR}_arm64 ${TARGET_DIR}
fi
for i in $(find ${TARGET_DIR}_x64/externals/*/Contents/MacOS -type f -perm -111)
do
echo "UBing file $i..."
lipo -create "${TARGET_DIR}_arm64/externals/$(basename $i).mxo/Contents/MacOS/$(basename $i)" "${TARGET_DIR}_x64/externals/$(basename $i).mxo/Contents/MacOS/$(basename $i)" -output "${TARGET_DIR}/externals/$(basename $i).mxo/Contents/MacOS/$(basename $i)"
done
for i in $(find ${TARGET_DIR}_x64/support/*.dylib)
do
arch1=""
arch2=""
if [[ ! -f "${TARGET_DIR}_x64/support/$(basename $i)" || ! -f "${TARGET_DIR}_arm64/support/$(basename $i)" ]]
then
echo "skipping $i"
continue
fi
is_ub=$(file "${TARGET_DIR}_x64/support/$(basename $i)" | grep -Eo '2 architectures')
if [[ -n "$is_ub" ]]; then
echo "$i / universal binary; skipping"
continue
fi
arch1=$(file -b "${TARGET_DIR}_x64/support/$(basename $i)" | grep -Eo 'x86_64|arm64')
arch2=$(file -b "${TARGET_DIR}_arm64/support/$(basename $i)" | grep -Eo 'x86_64|arm64')
if [[ -z "$arch1" || -z "$arch2" ]]; then
echo "skipping $i"
continue
fi
if [[ ! "$arch1" == "$arch2" ]]; then
echo "$i / arch1 : $arch1; arch2 : $arch2"
lipo -create "${TARGET_DIR}_arm64/support/$(basename $i)" "${TARGET_DIR}_x64/support/$(basename $i)" -output "${TARGET_DIR}/support/$(basename $i)"
fi
done
================================================
FILE: install/macos_pd_makeub.sh
================================================
TARGET_DIR=$1
if [ -z $TARGET_DIR ]; then
TARGET_DIR="nn_tilde"
fi
echo "${TARGET_DIR}"
if [[ ! -d "${TARGET_DIR}_arm64" ]]; then
echo "[Error] folder ${TARGET_DIR}_arm64 not found"
exit
fi
if [[ ! -d "${TARGET_DIR}_x64" ]]; then
echo "[Error] folder ${TARGET_DIR}_arm64 not found"
exit
fi
if [[ ! -d "${TARGET_DIR}" ]]; then
cp -r ${TARGET_DIR}_arm64 ${TARGET_DIR}
fi
lipo -create "${TARGET_DIR}_arm64/nn~.pd_darwin" "${TARGET_DIR}_x64/nn~.pd_darwin" -output "${TARGET_DIR}/nn~.pd_darwin"
for i in $(find ${TARGET_DIR}_x64/*.dylib)
do
arch1=""
arch2=""
if [[ ! -f "${TARGET_DIR}_x64$(basename $i)" || ! -f "${TARGET_DIR}_arm64/$(basename $i)" ]]
then
echo "skipping $i"
continue
fi
is_ub=$(file "${TARGET_DIR}_x64/$(basename $i)" | grep -Eo '2 architectures')
if [[ -n "$is_ub" ]]; then
echo "$i / universal binary; skipping"
continue
fi
arch1=$(file -b "${TARGET_DIR}_x64/$(basename $i)" | grep -Eo 'x86_64|arm64')
arch2=$(file -b "${TARGET_DIR}_arm64/$(basename $i)" | grep -Eo 'x86_64|arm64')
if [[ -z "$arch1" || -z "$arch2" ]]; then
echo "skipping $i"
continue
fi
if [[ ! "$arch1" == "$arch2" ]]; then
echo "$i / arch1 : $arch1; arch2 : $arch2"
lipo -create "${TARGET_DIR}_arm64/$(basename $i)" "${TARGET_DIR}_x64/$(basename $i)" -output "${TARGET_DIR}/$(basename $i)"
fi
done
================================================
FILE: install/max-linker-flags.txt
================================================
'-Wl,-U,_addbang' '-Wl,-U,_addfloat' '-Wl,-U,_addftx' '-Wl,-U,_addint' '-Wl,-U,_addinx' '-Wl,-U,_addmess' '-Wl,-U,_advise' '-Wl,-U,_advise_explain' '-Wl,-U,_alias' '-Wl,-U,_AnyKeyDown' '-Wl,-U,_appbuilder_keyword' '-Wl,-U,_appbuilder_register' '-Wl,-U,_argpad' '-Wl,-U,_assist_string' '-Wl,-U,_asyncfile_callback_free' '-Wl,-U,_asyncfile_callback_new' '-Wl,-U,_asyncfile_close' '-Wl,-U,_asyncfile_create' '-Wl,-U,_asyncfile_geteof' '-Wl,-U,_asyncfile_makerequest' '-Wl,-U,_asyncfile_object_method' '-Wl,-U,_asyncfile_params_default' '-Wl,-U,_asyncfile_params_free' '-Wl,-U,_asyncfile_params_new' '-Wl,-U,_asyncfile_read' '-Wl,-U,_asyncfile_seteof' '-Wl,-U,_asyncfile_write' '-Wl,-U,_atom_alloc' '-Wl,-U,_atom_alloc_array' '-Wl,-U,_atom_arg_getdouble' '-Wl,-U,_atom_arg_getfloat' '-Wl,-U,_atom_arg_getlong' '-Wl,-U,_atom_arg_getsym' '-Wl,-U,_atom_dynamic_end' '-Wl,-U,_atom_dynamic_start' '-Wl,-U,_atom_equal' '-Wl,-U,_atom_getatom_array' '-Wl,-U,_atom_getchar_array' '-Wl,-U,_atom_getcharfix' '-Wl,-U,_atom_getdouble_array' '-Wl,-U,_atom_getfloat' '-Wl,-U,_atom_getfloat_array' '-Wl,-U,_atom_getformat' '-Wl,-U,_atom_getlong' '-Wl,-U,_atom_getlong_array' '-Wl,-U,_atom_getobj' '-Wl,-U,_atom_getobj_array' '-Wl,-U,_atom_getsym' '-Wl,-U,_atom_getsym_array' '-Wl,-U,_atom_gettext' '-Wl,-U,_atom_gettext_precision' '-Wl,-U,_atom_gettype' '-Wl,-U,_atom_setatom_array' '-Wl,-U,_atom_setattrval' '-Wl,-U,_atom_setbinbuf' '-Wl,-U,_atom_setchar_array' '-Wl,-U,_atom_setdouble_array' '-Wl,-U,_atom_setfloat' '-Wl,-U,_atom_setfloat_array' '-Wl,-U,_atom_setformat' '-Wl,-U,_atom_setlong' '-Wl,-U,_atom_setlong_array' '-Wl,-U,_atom_setobj' '-Wl,-U,_atom_setobj_array' '-Wl,-U,_atom_setobjval' '-Wl,-U,_atom_setparse' '-Wl,-U,_atom_setsym' '-Wl,-U,_atom_setsym_array' '-Wl,-U,_atom_string' '-Wl,-U,_atombuf_append' '-Wl,-U,_atombuf_count' '-Wl,-U,_atombuf_eval' '-Wl,-U,_atombuf_firstatom' '-Wl,-U,_atombuf_free' '-Wl,-U,_atombuf_misc' '-Wl,-U,_atombuf_new' '-Wl,-U,_atombuf_next' '-Wl,-U,_atombuf_prepend' '-Wl,-U,_atombuf_replace' '-Wl,-U,_atombuf_replacepoundargs' '-Wl,-U,_atombuf_save' '-Wl,-U,_atombuf_set' '-Wl,-U,_atombuf_subst' '-Wl,-U,_atombuf_text' '-Wl,-U,_atombuf_totext' '-Wl,-U,_atomisatomarray' '-Wl,-U,_atomisdictionary' '-Wl,-U,_atomisstring' '-Wl,-U,_atoms_totext' '-Wl,-U,_attr_addfilter_clip' '-Wl,-U,_attr_addfilter_clip_scale' '-Wl,-U,_attr_addfilterget_clip' '-Wl,-U,_attr_addfilterget_clip_scale' '-Wl,-U,_attr_addfilterget_proc' '-Wl,-U,_attr_addfilterset_clip' '-Wl,-U,_attr_addfilterset_clip_scale' '-Wl,-U,_attr_addfilterset_proc' '-Wl,-U,_attr_args_dictionary' '-Wl,-U,_attr_args_offset' '-Wl,-U,_attr_args_process' '-Wl,-U,_attr_args_process_flags' '-Wl,-U,_attr_dictionary_process' '-Wl,-U,_attr_dictionary_check' '-Wl,-U,_attr_filter_clip_new' '-Wl,-U,_attr_filter_proc_new' '-Wl,-U,_attr_offset_array_new' '-Wl,-U,_attr_offset_new' '-Wl,-U,_attr_typedfun_set' '-Wl,-U,_attribute_new' '-Wl,-U,_attribute_new_sym' '-Wl,-U,_attribute_new_long' '-Wl,-U,_attribute_new_float' '-Wl,-U,_attribute_new_obj' '-Wl,-U,_attribute_new_atoms' '-Wl,-U,_attribute_new_attrval' '-Wl,-U,_attribute_new_binbuf' '-Wl,-U,_attribute_new_format' '-Wl,-U,_attribute_new_objval' '-Wl,-U,_attribute_new_parse' '-Wl,-U,_auxtable_checksym' '-Wl,-U,_bangout' '-Wl,-U,_bf_singlefast' '-Wl,-U,_binbuf_addtext' '-Wl,-U,_binbuf_append' '-Wl,-U,_binbuf_delete' '-Wl,-U,_binbuf_eval' '-Wl,-U,_binbuf_getatom' '-Wl,-U,_binbuf_gethandle' '-Wl,-U,_binbuf_insert' '-Wl,-U,_binbuf_inshandle' '-Wl,-U,_binbuf_make' '-Wl,-U,_binbuf_new' '-Wl,-U,_binbuf_read' '-Wl,-U,_binbuf_set' '-Wl,-U,_binbuf_text' '-Wl,-U,_binbuf_totext' '-Wl,-U,_binbuf_vinsert' '-Wl,-U,_binbuf_write' '-Wl,-U,_bitwrap_bell_filter' '-Wl,-U,_bitwrap_box_filter' '-Wl,-U,_bitwrap_bspline_filter' '-Wl,-U,_bitwrap_filter_default' '-Wl,-U,_bitwrap_filter_filter' '-Wl,-U,_bitwrap_interp' '-Wl,-U,_bitwrap_lanczos3_filter' '-Wl,-U,_bitwrap_mitchell_filter' '-Wl,-U,_bitwrap_triangle_filter' '-Wl,-U,_bitwrap_wrap_gworld' '-Wl,-U,_box_getcolor' '-Wl,-U,_boxcolor_rgb2index' '-Wl,-U,_call_method_attrval' '-Wl,-U,_call_method_binbuf' '-Wl,-U,_call_method_char' '-Wl,-U,_call_method_char_array' '-Wl,-U,_call_method_double' '-Wl,-U,_call_method_double_array' '-Wl,-U,_call_method_float' '-Wl,-U,_call_method_float_array' '-Wl,-U,_call_method_format' '-Wl,-U,_call_method_long' '-Wl,-U,_call_method_long_array' '-Wl,-U,_call_method_obj' '-Wl,-U,_call_method_obj_array' '-Wl,-U,_call_method_objval' '-Wl,-U,_call_method_parse' '-Wl,-U,_call_method_sym' '-Wl,-U,_call_method_sym_array' '-Wl,-U,_call_method_typed' '-Wl,-U,_charset_convert' '-Wl,-U,_charset_utf8tounicode' '-Wl,-U,_charset_unicodetoutf8' '-Wl,-U,_charset_isvalidutf8' '-Wl,-U,_charset_utf8_count' '-Wl,-U,_charset_utf8_offset' '-Wl,-U,_charset_isspace' '-Wl,-U,_class_addadornment' '-Wl,-U,_class_addattr' '-Wl,-U,_class_addattr_atoms' '-Wl,-U,_class_addattr_atoms' '-Wl,-U,_class_addattr_format' '-Wl,-U,_class_addattr_format' '-Wl,-U,_class_addattr_parse' '-Wl,-U,_class_addattr_parse' '-Wl,-U,_class_addcommand' '-Wl,-U,_class_addmethod' '-Wl,-U,_class_addtypedwrapper' '-Wl,-U,_class_addtransform' '-Wl,-U,_class_adornment_get' '-Wl,-U,_class_attr_addattr' '-Wl,-U,_class_attr_addattr_atoms' '-Wl,-U,_class_attr_addattr_atoms' '-Wl,-U,_class_attr_addattr_format' '-Wl,-U,_class_attr_addattr_format' '-Wl,-U,_class_attr_addattr_parse' '-Wl,-U,_class_attr_addattr_parse' '-Wl,-U,_class_attr_attr_get' '-Wl,-U,_class_attr_attr_getvalueof' '-Wl,-U,_class_attr_attr_setvalueof' '-Wl,-U,_class_attr_get' '-Wl,-U,_class_attr_method' '-Wl,-U,_class_buildprototype' '-Wl,-U,_class_clonable' '-Wl,-U,_class_cloneprototype' '-Wl,-U,_class_extra_lookup' '-Wl,-U,_class_extra_store' '-Wl,-U,_class_extra_storeflags' '-Wl,-U,_class_findbyname' '-Wl,-U,_class_findbyname_casefree' '-Wl,-U,_class_getifloaded' '-Wl,-U,_class_getifloaded_casefree' '-Wl,-U,_class_free' '-Wl,-U,_class_getmethod_object' '-Wl,-U,_class_getpath' '-Wl,-U,_class_is_ui' '-Wl,-U,_class_is_box' '-Wl,-U,_class_mess' '-Wl,-U,_class_method' '-Wl,-U,_class_nameget' '-Wl,-U,_class_new' '-Wl,-U,_class_noinlet' '-Wl,-U,_class_obexoffset_get' '-Wl,-U,_class_obexoffset_set' '-Wl,-U,_class_register' '-Wl,-U,_class_alias' '-Wl,-U,_class_copy' '-Wl,-U,_class_dumpout_wrap' '-Wl,-U,_class_setname' '-Wl,-U,_class_namespace_fromsym' '-Wl,-U,_class_namespace_getclassnames' '-Wl,-U,_class_setpath' '-Wl,-U,_class_sticky' '-Wl,-U,_class_sticky_clear' '-Wl,-U,_class_typedwrapper_get' '-Wl,-U,_classname_openhelp' '-Wl,-U,_classname_openrefpage' '-Wl,-U,_classname_openquery' '-Wl,-U,_clock_delay' '-Wl,-U,_clock_fdelay' '-Wl,-U,_clock_fdelay2' '-Wl,-U,_clock_fset' '-Wl,-U,_clock_fset2' '-Wl,-U,_clock_getextfmt' '-Wl,-U,_clock_getftime' '-Wl,-U,_clock_getftime_nocache' '-Wl,-U,_clock_new' '-Wl,-U,_clock_new_withscheduler' '-Wl,-U,_clock_set' '-Wl,-U,_clock_unset' '-Wl,-U,_clock_xdelay' '-Wl,-U,_clock_xset' '-Wl,-U,_clock_xunset' '-Wl,-U,_clock_setowner' '-Wl,-U,_CmdKeyDown' '-Wl,-U,_compression_compressjson_headless' '-Wl,-U,_compression_decompressjson_headless' '-Wl,-U,_connection_client' '-Wl,-U,_connection_delete' '-Wl,-U,_connection_send' '-Wl,-U,_connection_server' '-Wl,-U,_CopyFromGWorld' '-Wl,-U,_cpost' '-Wl,-U,_critical_enter' '-Wl,-U,_critical_exit' '-Wl,-U,_critical_free' '-Wl,-U,_critical_new' '-Wl,-U,_critical_tryenter' '-Wl,-U,_crosshatch' '-Wl,-U,_CtrlKeyDown' '-Wl,-U,_CurrentOptionKeysDown' '-Wl,-U,_debug_printf' '-Wl,-U,_defer' '-Wl,-U,_defer_front' '-Wl,-U,_defer_low' '-Wl,-U,_defer_medium' '-Wl,-U,_defer_sys_low' '-Wl,-U,_defvolume' '-Wl,-U,_dialog_setkey' '-Wl,-U,_dictionary_appendatom' '-Wl,-U,_dictionary_appendatom_flags' '-Wl,-U,_dictionary_appendatomarray' '-Wl,-U,_dictionary_appendatoms' '-Wl,-U,_dictionary_appendatoms_flags' '-Wl,-U,_dictionary_appendattribute' '-Wl,-U,_dictionary_appendbinbuf' '-Wl,-U,_dictionary_appenddictionary' '-Wl,-U,_dictionary_appendfloat' '-Wl,-U,_dictionary_appendlong' '-Wl,-U,_dictionary_appendobject' '-Wl,-U,_dictionary_appendobject_flags' '-Wl,-U,_dictionary_appendstring' '-Wl,-U,_dictionary_appendsym' '-Wl,-U,_dictionary_chuckentry' '-Wl,-U,_dictionary_clear' '-Wl,-U,_dictionary_copyatoms' '-Wl,-U,_dictionary_copyatoms_ext' '-Wl,-U,_dictionary_copydefatoms' '-Wl,-U,_dictionary_copyentries' '-Wl,-U,_dictionary_copyunique' '-Wl,-U,_dictionary_deleteentry' '-Wl,-U,_dictionary_dump' '-Wl,-U,_dictionary_entry_getkey' '-Wl,-U,_dictionary_entry_getvalue' '-Wl,-U,_dictionary_entry_getvalues' '-Wl,-U,_dictionary_entryisatomarray' '-Wl,-U,_dictionary_entryisdictionary' '-Wl,-U,_dictionary_entryisstring' '-Wl,-U,_dictionary_freekeys' '-Wl,-U,_dictionary_funall' '-Wl,-U,_dictionary_getatom' '-Wl,-U,_dictionary_getatom_ext' '-Wl,-U,_dictionary_getatomarray' '-Wl,-U,_dictionary_getatoms' '-Wl,-U,_dictionary_getatoms_ext' '-Wl,-U,_dictionary_getattribute' '-Wl,-U,_dictionary_getdefatom' '-Wl,-U,_dictionary_getdefatoms' '-Wl,-U,_dictionary_getdeffloat' '-Wl,-U,_dictionary_getdeflong' '-Wl,-U,_dictionary_getdefstring' '-Wl,-U,_dictionary_getdefsym' '-Wl,-U,_dictionary_getdictionary' '-Wl,-U,_dictionary_getentrycount' '-Wl,-U,_dictionary_getfloat' '-Wl,-U,_dictionary_getkeys' '-Wl,-U,_dictionary_getkeys_ordered' '-Wl,-U,_dictionary_getlong' '-Wl,-U,_dictionary_getobject' '-Wl,-U,_dictionary_getobject_ext' '-Wl,-U,_dictionary_getstring' '-Wl,-U,_dictionary_getsym' '-Wl,-U,_dictionary_get_ex' '-Wl,-U,_dictionary_hasentry' '-Wl,-U,_dictionary_new' '-Wl,-U,_dictionary_prototypefromclass' '-Wl,-U,_dictionary_read' '-Wl,-U,_dictionary_sprintf' '-Wl,-U,_dictionary_write' '-Wl,-U,_dictobj_register' '-Wl,-U,_dictobj_unregister' '-Wl,-U,_dictobj_findregistered_clone' '-Wl,-U,_dictobj_findregistered_retain' '-Wl,-U,_dictobj_release' '-Wl,-U,_dictobj_namefromptr' '-Wl,-U,_dictobj_outlet_atoms' '-Wl,-U,_dictobj_atom_safety' '-Wl,-U,_dictobj_atom_safety_flags' '-Wl,-U,_dictobj_atom_release' '-Wl,-U,_dictobj_validate' '-Wl,-U,_dictobj_jsonfromstring' '-Wl,-U,_dictobj_dictionaryfromstring' '-Wl,-U,_dictobj_dictionaryfromatoms' '-Wl,-U,_dictobj_dictionaryfromatoms_extended' '-Wl,-U,_dictobj_dictionarytoatoms' '-Wl,-U,_dictobj_key_parse' '-Wl,-U,_dictobj_modify' '-Wl,-U,_dictobj_convertatoms' '-Wl,-U,_dictobj_convertatoms2' '-Wl,-U,_dictobj_atomtotype' '-Wl,-U,_dictobj_outlet_atoms_prefix' '-Wl,-U,_dictobj_outlet_atoms_prefix_ext' '-Wl,-U,_arrayobj_register' '-Wl,-U,_arrayobj_unregister' '-Wl,-U,_arrayobj_findregistered_retain' '-Wl,-U,_arrayobj_findregistered_clone' '-Wl,-U,_arrayobj_release' '-Wl,-U,_arrayobj_namefromptr' '-Wl,-U,_stringobj_register' '-Wl,-U,_stringobj_unregister' '-Wl,-U,_stringobj_findregistered_retain' '-Wl,-U,_stringobj_findregistered_clone' '-Wl,-U,_stringobj_release' '-Wl,-U,_stringobj_namefromptr' '-Wl,-U,_disposhandle' '-Wl,-U,_drawstr' '-Wl,-U,_ed_new' '-Wl,-U,_ed_settext' '-Wl,-U,_ed_vis' '-Wl,-U,_egetfn' '-Wl,-U,_error' '-Wl,-U,_error_subscribe' '-Wl,-U,_error_sym' '-Wl,-U,_error_unsubscribe' '-Wl,-U,_errorcount_get' '-Wl,-U,_errorcount_set' '-Wl,-U,_evnum_get' '-Wl,-U,_evnum_incr' '-Wl,-U,_expr_eval' '-Wl,-U,_expr_new' '-Wl,-U,_fileformat_filetype' '-Wl,-U,_fileformat_installsniffer' '-Wl,-U,_fileformat_sniff' '-Wl,-U,_fileformat_sniffdata' '-Wl,-U,_fileformat_stripsuffix' '-Wl,-U,_fileformat_typesuffix' '-Wl,-U,_fileformat_suffixtotype' '-Wl,-U,_fileformat_suffix' '-Wl,-U,_fileformat_divide' '-Wl,-U,_fileformat_cstrtofiletype' '-Wl,-U,_fileformat_symtofiletype' '-Wl,-U,_fileformat_filetypetosym' '-Wl,-U,_fileformat_typetosuffix' '-Wl,-U,_filekind_getfiletypes' '-Wl,-U,_filekind_getname' '-Wl,-U,_filekind_nametoicon' '-Wl,-U,_fileload' '-Wl,-U,_fileload_extended' '-Wl,-U,_fileload_type' '-Wl,-U,_fileusage_addfile' '-Wl,-U,_fileusage_addfilename' '-Wl,-U,_fileusage_addpackage' '-Wl,-U,_fileusage_addpathname' '-Wl,-U,_fileusage_copyfolder' '-Wl,-U,_fileusage_makefolder' '-Wl,-U,_fileusage_addfolder' '-Wl,-U,_filewatcher_new' '-Wl,-U,_filewatcher_start' '-Wl,-U,_filewatcher_stop' '-Wl,-U,_finder_addclass' '-Wl,-U,_floatin' '-Wl,-U,_floatout' '-Wl,-U,_fontinfo_getname' '-Wl,-U,_fontinfo_getnumber' '-Wl,-U,_fontinfo_getsize' '-Wl,-U,_fontmap_getmapping' '-Wl,-U,_force_install' '-Wl,-U,_freebytes' '-Wl,-U,_freeobject' '-Wl,-U,_gensym' '-Wl,-U,_gensym_tr' '-Wl,-U,_getbytes' '-Wl,-U,_getexttime' '-Wl,-U,_getfn' '-Wl,-U,_getfolder' '-Wl,-U,_getschedtime' '-Wl,-U,_gettime' '-Wl,-U,_gettime_forobject' '-Wl,-U,_globalmouse_addlistener' '-Wl,-U,_globalmouse_removelistener' '-Wl,-U,_globalsymbol_reference' '-Wl,-U,_globalsymbol_dereference' '-Wl,-U,_globalsymbol_bind' '-Wl,-U,_globalsymbol_unbind' '-Wl,-U,_globalsymbol_notify' '-Wl,-U,_growhandle' '-Wl,-U,_GWorldFromPict' '-Wl,-U,_handle2tempfile' '-Wl,-U,_hashtab_chuck' '-Wl,-U,_hashtab_chuckkey' '-Wl,-U,_hashtab_clear' '-Wl,-U,_hashtab_delete' '-Wl,-U,_hashtab_findfirst' '-Wl,-U,_hashtab_flags' '-Wl,-U,_hashtab_funall' '-Wl,-U,_hashtab_getflags' '-Wl,-U,_hashtab_getkeyflags' '-Wl,-U,_hashtab_getkeys' '-Wl,-U,_hashtab_getsize' '-Wl,-U,_hashtab_keyflags' '-Wl,-U,_hashtab_lookup' '-Wl,-U,_hashtab_lookupentry' '-Wl,-U,_hashtab_lookupflags' '-Wl,-U,_hashtab_lookuplong' '-Wl,-U,_hashtab_lookupsym' '-Wl,-U,_hashtab_methodall' '-Wl,-U,_hashtab_methodall_imp' '-Wl,-U,_hashtab_new' '-Wl,-U,_hashtab_objfunall' '-Wl,-U,_hashtab_print' '-Wl,-U,_hashtab_readonly' '-Wl,-U,_hashtab_store' '-Wl,-U,_hashtab_store_safe' '-Wl,-U,_hashtab_storeflags' '-Wl,-U,_hashtab_storelong' '-Wl,-U,_hashtab_storesym' '-Wl,-U,_helpstring' '-Wl,-U,_inisr_set' '-Wl,-U,_inlet_append' '-Wl,-U,_inlet_insert_after' '-Wl,-U,_inlet_count' '-Wl,-U,_inlet_new' '-Wl,-U,_inlet_nth' '-Wl,-U,_inlet_to' '-Wl,-U,_inlet4' '-Wl,-U,_inspector_open' '-Wl,-U,_intin' '-Wl,-U,_intload' '-Wl,-U,_intout' '-Wl,-U,_IsKeyDown' '-Wl,-U,_isbpatcher' '-Wl,-U,_isnewex' '-Wl,-U,_ispatcher' '-Wl,-U,_isr' '-Wl,-U,_isr_set' '-Wl,-U,_linklist_append' '-Wl,-U,_linklist_chuck' '-Wl,-U,_linklist_chuckindex' '-Wl,-U,_linklist_chuckptr' '-Wl,-U,_linklist_clear' '-Wl,-U,_linklist_deleteindex' '-Wl,-U,_linklist_findall' '-Wl,-U,_linklist_findfirst' '-Wl,-U,_linklist_flags' '-Wl,-U,_linklist_funall' '-Wl,-U,_linklist_funall_break' '-Wl,-U,_linklist_funindex' '-Wl,-U,_linklist_getflags' '-Wl,-U,_linklist_getindex' '-Wl,-U,_linklist_getsize' '-Wl,-U,_linklist_insert_sorted' '-Wl,-U,_linklist_insertafterobjptr' '-Wl,-U,_linklist_insertbeforeobjptr' '-Wl,-U,_linklist_insertindex' '-Wl,-U,_linklist_last' '-Wl,-U,_linklist_makearray' '-Wl,-U,_linklist_methodall' '-Wl,-U,_linklist_methodall_imp' '-Wl,-U,_linklist_methodindex' '-Wl,-U,_linklist_methodindex_imp' '-Wl,-U,_linklist_moveafterobjptr' '-Wl,-U,_linklist_movebeforeobjptr' '-Wl,-U,_linklist_new' '-Wl,-U,_linklist_next' '-Wl,-U,_linklist_objptr2index' '-Wl,-U,_linklist_prev' '-Wl,-U,_linklist_readonly' '-Wl,-U,_linklist_reverse' '-Wl,-U,_linklist_rotate' '-Wl,-U,_linklist_shuffle' '-Wl,-U,_linklist_sort' '-Wl,-U,_linklist_substitute' '-Wl,-U,_linklist_swap' '-Wl,-U,_linklist_match' '-Wl,-U,_linklist_chuckobject' '-Wl,-U,_linklist_deleteobject' '-Wl,-U,_linklist_prune' '-Wl,-U,_listout' '-Wl,-U,_loadbang_disabled' '-Wl,-U,_loadbang_dequeue' '-Wl,-U,_loadbang_queueobject' '-Wl,-U,_loadbang_resume' '-Wl,-U,_loadbang_suspend' '-Wl,-U,_loader_setpath' '-Wl,-U,_locatefile' '-Wl,-U,_locatefile_extended' '-Wl,-U,_locatefilelist' '-Wl,-U,_locatefiletype' '-Wl,-U,_lockout_set' '-Wl,-U,_lowload_jpatcher_frombuffer' '-Wl,-U,_lowload_jpatcher_frombuffer_withobexprototype' '-Wl,-U,_lowload_jpatcher_fromamxd_data' '-Wl,-U,_loader_loadamxd_tohandle' '-Wl,-U,_maxlogger_log' '-Wl,-U,_maxversion' '-Wl,-U,_max_unicodekeydown' '-Wl,-U,_max_unicodekeyup' '-Wl,-U,_maxcache_getpath' '-Wl,-U,_maxcache_checkfile' '-Wl,-U,_maxcache_usefile' '-Wl,-U,_maxdb_search' '-Wl,-U,_maxdb_search_sprintf' '-Wl,-U,_maxdb_tag' '-Wl,-U,_maxdb_filter' '-Wl,-U,_maxdb_getstate' '-Wl,-U,_maxdb_query' '-Wl,-U,_maxdb_query_direct' '-Wl,-U,_mayquote' '-Wl,-U,_method_false' '-Wl,-U,_method_object_free' '-Wl,-U,_method_object_getmesslist' '-Wl,-U,_method_object_getmethod' '-Wl,-U,_method_object_getname' '-Wl,-U,_method_object_new' '-Wl,-U,_method_object_new_messlist' '-Wl,-U,_method_object_setmesslist' '-Wl,-U,_method_object_setmethod' '-Wl,-U,_method_object_setname' '-Wl,-U,_method_true' '-Wl,-U,_mfl_guiidle' '-Wl,-U,_mfl_idle' '-Wl,-U,_mfl_init' '-Wl,-U,_mfl_exit' '-Wl,-U,_path_mfl_getapppath' '-Wl,-U,_movecursor' '-Wl,-U,_namedpipeconnection_isconnected' '-Wl,-U,_nameinpath' '-Wl,-U,_nameload' '-Wl,-U,_nameload_unique' '-Wl,-U,_nameload_unique_internal' '-Wl,-U,_nametab_filename' '-Wl,-U,_nametab_getmatches' '-Wl,-U,_newex_knows' '-Wl,-U,_newhandle' '-Wl,-U,_newinstance' '-Wl,-U,_newobject' '-Wl,-U,_newobject_fromdictionary' '-Wl,-U,_newobject_fromboxtext' '-Wl,-U,_newobject_sprintf' '-Wl,-U,_noloadbangdisable_get' '-Wl,-U,_noloadbangdisable_set' '-Wl,-U,_notify_free' '-Wl,-U,_nullfn' '-Wl,-U,_object_addattr' '-Wl,-U,_object_addattr_atoms' '-Wl,-U,_object_addattr_atoms' '-Wl,-U,_object_addattr_format' '-Wl,-U,_object_addattr_format' '-Wl,-U,_object_addattr_parse' '-Wl,-U,_object_addattr_parse' '-Wl,-U,_object_addmethod' '-Wl,-U,_object_alloc' '-Wl,-U,_object_attach' '-Wl,-U,_object_attach_byptr' '-Wl,-U,_object_attach_byptr_register' '-Wl,-U,_object_attr_addattr' '-Wl,-U,_object_attr_addattr_atoms' '-Wl,-U,_object_attr_addattr_atoms' '-Wl,-U,_object_attr_addattr_format' '-Wl,-U,_object_attr_addattr_format' '-Wl,-U,_object_attr_addattr_parse' '-Wl,-U,_object_attr_addattr_parse' '-Wl,-U,_object_attr_attr_get' '-Wl,-U,_object_attr_attr_getvalueof' '-Wl,-U,_object_attr_attr_setvalueof' '-Wl,-U,_object_attr_enforcelocal' '-Wl,-U,_object_attr_freeze' '-Wl,-U,_object_attr_get' '-Wl,-U,_object_attr_getchar' '-Wl,-U,_object_attr_getchar_array' '-Wl,-U,_object_attr_getdisabled' '-Wl,-U,_object_attr_getdouble_array' '-Wl,-U,_object_attr_getdump' '-Wl,-U,_object_attr_getfloat' '-Wl,-U,_object_attr_getfloat_array' '-Wl,-U,_object_attr_getinvisible' '-Wl,-U,_object_attr_getlong' '-Wl,-U,_object_attr_getlong_array' '-Wl,-U,_object_attr_getnames' '-Wl,-U,_object_attr_getobj' '-Wl,-U,_object_attr_getsym' '-Wl,-U,_object_attr_getsym_array' '-Wl,-U,_object_attr_getvalueof' '-Wl,-U,_object_attr_method' '-Wl,-U,_object_attr_setattrval' '-Wl,-U,_object_attr_setbinbuf' '-Wl,-U,_object_attr_setchar' '-Wl,-U,_object_attr_setchar_array' '-Wl,-U,_object_attr_setdisabled' '-Wl,-U,_object_attr_setdouble_array' '-Wl,-U,_object_attr_setfloat' '-Wl,-U,_object_attr_setfloat_array' '-Wl,-U,_object_attr_setformat' '-Wl,-U,_object_attr_setinvisible' '-Wl,-U,_object_attr_setlong' '-Wl,-U,_object_attr_setlong_array' '-Wl,-U,_object_attr_setobj' '-Wl,-U,_object_attr_setobjval' '-Wl,-U,_object_attr_setparse' '-Wl,-U,_object_attr_setsym' '-Wl,-U,_object_attr_setsym_array' '-Wl,-U,_object_attr_setvalueof' '-Wl,-U,_object_attr_usercanget' '-Wl,-U,_object_attr_usercanset' '-Wl,-U,_object_attr_getdirty' '-Wl,-U,_object_attrhash_apply' '-Wl,-U,_object_bug' '-Wl,-U,_object_chuckattr' '-Wl,-U,_object_chuckmethod' '-Wl,-U,_object_class' '-Wl,-U,_object_classname' '-Wl,-U,_object_namespace' '-Wl,-U,_class_namespace' '-Wl,-U,_object_classname_compare' '-Wl,-U,_object_clonable' '-Wl,-U,_object_clone' '-Wl,-U,_object_clone_generic' '-Wl,-U,_object_commandenabled' '-Wl,-U,_object_deleteattr' '-Wl,-U,_object_deletemethod' '-Wl,-U,_object_detach' '-Wl,-U,_object_detach_byptr' '-Wl,-U,_object_dictionary_fromnewargs' '-Wl,-U,_object_dictionaryarg' '-Wl,-U,_object_error' '-Wl,-U,_object_error_obtrusive' '-Wl,-U,_jpatcher_error_obtrusive' '-Wl,-U,_object_findregistered' '-Wl,-U,_object_findregisteredbyptr' '-Wl,-U,_object_free' '-Wl,-U,_object_getattrlist' '-Wl,-U,_object_getcommand' '-Wl,-U,_object_getenabler' '-Wl,-U,_object_getmethod' '-Wl,-U,_object_getmethod_object' '-Wl,-U,_object_getftime' '-Wl,-U,_object_getvalueof' '-Wl,-U,_object_getvalueof_ext' '-Wl,-U,_object_handlecommand' '-Wl,-U,_object_inspect' '-Wl,-U,_object_mess' '-Wl,-U,_object_method' '-Wl,-U,_object_method_imp' '-Wl,-U,_object_method_attrval' '-Wl,-U,_object_method_binbuf' '-Wl,-U,_object_method_char' '-Wl,-U,_object_method_char_array' '-Wl,-U,_object_method_double' '-Wl,-U,_object_method_double_array' '-Wl,-U,_object_method_float' '-Wl,-U,_object_method_float_array' '-Wl,-U,_object_method_format' '-Wl,-U,_object_method_long' '-Wl,-U,_object_method_long_array' '-Wl,-U,_object_method_obj' '-Wl,-U,_object_method_obj_array' '-Wl,-U,_object_method_objval' '-Wl,-U,_object_method_parse' '-Wl,-U,_object_method_sym' '-Wl,-U,_object_method_sym_array' '-Wl,-U,_object_method_typed' '-Wl,-U,_object_method_typedfun' '-Wl,-U,_object_new' '-Wl,-U,_object_new_imp' '-Wl,-U,_object_new_attrval' '-Wl,-U,_object_new_binbuf' '-Wl,-U,_object_new_format' '-Wl,-U,_object_new_objval' '-Wl,-U,_object_new_parse' '-Wl,-U,_object_new_typed' '-Wl,-U,_object_notify' '-Wl,-U,_object_obex_dumpout' '-Wl,-U,_object_obex_free' '-Wl,-U,_object_obex_get' '-Wl,-U,_object_obex_lookup' '-Wl,-U,_object_obex_lookuplong' '-Wl,-U,_object_obex_lookupsym' '-Wl,-U,_object_obex_quickref' '-Wl,-U,_object_obex_set' '-Wl,-U,_object_obex_store' '-Wl,-U,_object_obex_storelong' '-Wl,-U,_object_obex_storesym' '-Wl,-U,_object_post' '-Wl,-U,_object_poststring' '-Wl,-U,_object_refpage_get_class_info' '-Wl,-U,_object_refpage_get_class_info_fromclassname' '-Wl,-U,_object_refpage_method_is_undocumented' '-Wl,-U,_object_refpage_method_is_groupreference' '-Wl,-U,_object_register' '-Wl,-U,_object_register_unique' '-Wl,-U,_object_replaceargs' '-Wl,-U,_object_reveal' '-Wl,-U,_object_setvalueof' '-Wl,-U,_object_setvalueof_ext' '-Wl,-U,_object_show' '-Wl,-U,_object_sticky' '-Wl,-U,_object_sticky_clear' '-Wl,-U,_object_subpatcher' '-Wl,-U,_object_unregister' '-Wl,-U,_object_warn' '-Wl,-U,_object_zero' '-Wl,-U,_object_isnogood' '-Wl,-U,_onecopy_fileload' '-Wl,-U,_open_dialog' '-Wl,-U,_open_dialog_filetypelist' '-Wl,-U,_opendialog_pathset' '-Wl,-U,_open_messageset' '-Wl,-U,_open_promptset' '-Wl,-U,_OptionKeyDown' '-Wl,-U,_ouchstring' '-Wl,-U,_outlet_add' '-Wl,-U,_outlet_addmonitor' '-Wl,-U,_outlet_anything' '-Wl,-U,_outlet_append' '-Wl,-U,_outlet_insert_after' '-Wl,-U,_outlet_atoms' '-Wl,-U,_outlet_atoms_ext' '-Wl,-U,_outlet_bang' '-Wl,-U,_outlet_canadd' '-Wl,-U,_outlet_count' '-Wl,-U,_outlet_enable' '-Wl,-U,_outlet_float' '-Wl,-U,_outlet_int' '-Wl,-U,_outlet_list' '-Wl,-U,_outlet_msg' '-Wl,-U,_outlet_new' '-Wl,-U,_outlet_notify' '-Wl,-U,_outlet_nth' '-Wl,-U,_outlet_removemonitor' '-Wl,-U,_outlet_rm' '-Wl,-U,_outlet_array' '-Wl,-U,_outlet_string' '-Wl,-U,_packages_getpackagepath' '-Wl,-U,_packages_createsubpathlist' '-Wl,-U,_packages_getsubpathcontents' '-Wl,-U,_palette_getcolor' '-Wl,-U,_patcher_eachdo' '-Wl,-U,_path_addnamed' '-Wl,-U,_path_addpath' '-Wl,-U,_path_build' '-Wl,-U,_path_closefolder' '-Wl,-U,_path_copyfile' '-Wl,-U,_path_copyfolder' '-Wl,-U,_path_copytotempfile' '-Wl,-U,_path_createfolder' '-Wl,-U,_path_createressysfile' '-Wl,-U,_path_createsysfile' '-Wl,-U,_path_deletefile' '-Wl,-U,_path_tempfolder' '-Wl,-U,_path_desktopfolder' '-Wl,-U,_path_userdocfolder' '-Wl,-U,_path_usermaxfolder' '-Wl,-U,_path_extendedfileinfo' '-Wl,-U,_path_fileinfo' '-Wl,-U,_path_fileisresource' '-Wl,-U,_path_foldernextfile' '-Wl,-U,_path_frompathname' '-Wl,-U,_path_fromunicodepathname' '-Wl,-U,_path_toabsolutesystempath' '-Wl,-U,_path_absolutepath' '-Wl,-U,_path_absolutepath_filetypelist' '-Wl,-U,_path_getapppath' '-Wl,-U,_path_getdefault' '-Wl,-U,_path_getfilecreationdate' '-Wl,-U,_path_getfilemoddate' '-Wl,-U,_path_getmoddate' '-Wl,-U,_path_getname' '-Wl,-U,_path_getnext' '-Wl,-U,_path_getpath' '-Wl,-U,_path_getprefstring' '-Wl,-U,_path_getseparator' '-Wl,-U,_path_getstyle' '-Wl,-U,_path_getsupportpath' '-Wl,-U,_path_infoforopensysfile' '-Wl,-U,_path_movefile' '-Wl,-U,_path_nameconform' '-Wl,-U,_path_nameinpath' '-Wl,-U,_path_nameisrelative' '-Wl,-U,_path_openfolder' '-Wl,-U,_path_openresfile' '-Wl,-U,_path_openressysfile' '-Wl,-U,_path_opensysfile' '-Wl,-U,_path_removefromlist' '-Wl,-U,_path_removepath' '-Wl,-U,_path_renamefile' '-Wl,-U,_path_resolvefile' '-Wl,-U,_path_setdefault' '-Wl,-U,_path_setfileinfo' '-Wl,-U,_path_setpermanent' '-Wl,-U,_path_setprefstring' '-Wl,-U,_path_sysnameinpath' '-Wl,-U,_path_collpathnamefrompath' '-Wl,-U,_path_tempfilename' '-Wl,-U,_path_topathname' '-Wl,-U,_path_topotentialname' '-Wl,-U,_path_topotentialunicodename' '-Wl,-U,_path_frompotentialpathname' '-Wl,-U,_path_splitnames' '-Wl,-U,_path_usermaxfolder' '-Wl,-U,_path_addfiles' '-Wl,-U,_path_addfolders' '-Wl,-U,_path_removefiles' '-Wl,-U,_path_exists' '-Wl,-U,_path_inpath' '-Wl,-U,_plug_free' '-Wl,-U,_plug_init' '-Wl,-U,_plug_setloopfun' '-Wl,-U,_popup_free' '-Wl,-U,_popup_new' '-Wl,-U,_popup_show' '-Wl,-U,_post' '-Wl,-U,_post_displayrecent' '-Wl,-U,_post_getpos' '-Wl,-U,_post_sym' '-Wl,-U,_postatom' '-Wl,-U,_postdictionary' '-Wl,-U,_poststring' '-Wl,-U,_preferences_class_define' '-Wl,-U,_preferences_class_defineoption' '-Wl,-U,_preferences_define' '-Wl,-U,_preferences_defineoption' '-Wl,-U,_preferences_getatomforkey' '-Wl,-U,_preferences_getatoms' '-Wl,-U,_preferences_getchar' '-Wl,-U,_preferences_getlong' '-Wl,-U,_preferences_getsym' '-Wl,-U,_preferences_path' '-Wl,-U,_preferences_readdictionary' '-Wl,-U,_preferences_setatoms' '-Wl,-U,_preferences_setchar' '-Wl,-U,_preferences_setlong' '-Wl,-U,_preferences_setsym' '-Wl,-U,_preferences_subpath' '-Wl,-U,_preferences_writedictionary' '-Wl,-U,_preset_int' '-Wl,-U,_preset_set' '-Wl,-U,_preset_store' '-Wl,-U,_proxy_getinlet' '-Wl,-U,_proxy_new' '-Wl,-U,_qelem_free' '-Wl,-U,_qelem_front' '-Wl,-U,_qelem_idlefree' '-Wl,-U,_qelem_idlefront' '-Wl,-U,_qelem_idleset' '-Wl,-U,_qelem_idleunset' '-Wl,-U,_qelem_new' '-Wl,-U,_qelem_set' '-Wl,-U,_qelem_unset' '-Wl,-U,_qelem_setowner' '-Wl,-U,_quotestring' '-Wl,-U,_versioncmp' '-Wl,-U,_versioncanparse' '-Wl,-U,_qti_extra_flags_get' '-Wl,-U,_qti_extra_flags_set' '-Wl,-U,_qti_extra_free' '-Wl,-U,_qti_extra_matrix_get' '-Wl,-U,_qti_extra_matrix_set' '-Wl,-U,_qti_extra_new' '-Wl,-U,_qti_extra_pixelformat_get' '-Wl,-U,_qti_extra_pixelformat_set' '-Wl,-U,_qti_extra_rect_get' '-Wl,-U,_qti_extra_rect_set' '-Wl,-U,_qti_extra_scalemode_get' '-Wl,-U,_qti_extra_scalemode_set' '-Wl,-U,_qti_extra_time_get' '-Wl,-U,_qti_extra_time_set' '-Wl,-U,_qtimage_getrect' '-Wl,-U,_qtimage_open' '-Wl,-U,_quickmap_add' '-Wl,-U,_quickmap_drop' '-Wl,-U,_quickmap_lookup_key1' '-Wl,-U,_quickmap_lookup_key2' '-Wl,-U,_quickmap_readonly' '-Wl,-U,_quickmap_new' '-Wl,-U,_quittask_install' '-Wl,-U,_quittask_remove' '-Wl,-U,_quittask_remove2' '-Wl,-U,_readatom' '-Wl,-U,_readatom_flags' '-Wl,-U,_readtohandle' '-Wl,-U,_recent_add' '-Wl,-U,_recent_getlist' '-Wl,-U,_recent_project_getlist' '-Wl,-U,_reg_object_namespace_lookup' '-Wl,-U,_reg_object_singlesym' '-Wl,-U,_rerand' '-Wl,-U,_saveas_autoextension' '-Wl,-U,_saveas_dialog' '-Wl,-U,_saveas_messageset' '-Wl,-U,_saveas_promptset' '-Wl,-U,_saveas_setselectedtype' '-Wl,-U,_saveasdialog_extended' '-Wl,-U,_saveasdialog_extended_filetypelist' '-Wl,-U,_saveasdialog_pathset' '-Wl,-U,_sched_idledequeue' '-Wl,-U,_sched_isinpoll' '-Wl,-U,_sched_isinqueue' '-Wl,-U,_sched_resume' '-Wl,-U,_sched_set_takeover' '-Wl,-U,_sched_setpollthrottle' '-Wl,-U,_sched_setqueuethrottle' '-Wl,-U,_sched_suspend' '-Wl,-U,_schedule' '-Wl,-U,_schedule_defer' '-Wl,-U,_schedule_delay' '-Wl,-U,_schedule_fdefer' '-Wl,-U,_schedule_fdelay' '-Wl,-U,_schedulef' '-Wl,-U,_scheduler_gettime' '-Wl,-U,_scheduler_getaudiooffset' '-Wl,-U,_scheduler_new' '-Wl,-U,_scheduler_run' '-Wl,-U,_scheduler_get' '-Wl,-U,_scheduler_set' '-Wl,-U,_scheduler_settime' '-Wl,-U,_scheduler_setaudioschedulertime' '-Wl,-U,_scheduler_fromobject' '-Wl,-U,_scheduler_shift' '-Wl,-U,_serialno' '-Wl,-U,_setclock_delay' '-Wl,-U,_setclock_fdelay' '-Wl,-U,_setclock_fgettime' '-Wl,-U,_setclock_getftime' '-Wl,-U,_setclock_gettime' '-Wl,-U,_setclock_unset' '-Wl,-U,_setup' '-Wl,-U,_ShiftKeyDown' '-Wl,-U,_simpleprefs_dictionary' '-Wl,-U,_sndfile_info' '-Wl,-U,_sndfile_writeheader' '-Wl,-U,_sprintf' '-Wl,-U,_sscanf' '-Wl,-U,_sprintf_tr' '-Wl,-U,_stdinletinfo' '-Wl,-U,_stdlist' '-Wl,-U,_str_tr' '-Wl,-U,_string_getptr' '-Wl,-U,_string_new' '-Wl,-U,_string_reserve' '-Wl,-U,_string_append' '-Wl,-U,_string_chop' '-Wl,-U,_string_clone_to_existing' '-Wl,-U,_stringload' '-Wl,-U,_strncpy_zero' '-Wl,-U,_snprintf_zero' '-Wl,-U,_strncat_zero' '-Wl,-U,_symbol_tr' '-Wl,-U,_symbol_unique' '-Wl,-U,_symbolarray_sort' '-Wl,-U,_symobject_new' '-Wl,-U,_symobject_linklist_match' '-Wl,-U,_sysdateformat_strftimetodatetime' '-Wl,-U,_sysdateformat_formatdatetime' '-Wl,-U,_sysfile_close' '-Wl,-U,_sysfile_geteof' '-Wl,-U,_sysfile_geteof_64' '-Wl,-U,_sysfile_getpos' '-Wl,-U,_sysfile_getpos_64' '-Wl,-U,_sysfile_openhandle' '-Wl,-U,_sysfile_openptrsize' '-Wl,-U,_sysfile_read' '-Wl,-U,_sysfile_readtextfile' '-Wl,-U,_sysfile_readtohandle' '-Wl,-U,_sysfile_readtoptr' '-Wl,-U,_sysfile_seteof' '-Wl,-U,_sysfile_setobject' '-Wl,-U,_sysfile_setpos' '-Wl,-U,_sysfile_setpos_64' '-Wl,-U,_sysfile_spoolcopy' '-Wl,-U,_sysfile_write' '-Wl,-U,_sysfile_writetextfile' '-Wl,-U,_sysmem_copyptr' '-Wl,-U,_sysmem_freehandle' '-Wl,-U,_sysmem_freeptr' '-Wl,-U,_sysmem_handlesize' '-Wl,-U,_sysmem_lockhandle' '-Wl,-U,_sysmem_newhandle' '-Wl,-U,_sysmem_newhandleclear' '-Wl,-U,_sysmem_newptr' '-Wl,-U,_sysmem_newptrclear' '-Wl,-U,_sysmem_nullterminatehandle' '-Wl,-U,_sysmem_ptrandhand' '-Wl,-U,_sysmem_ptrbeforehand' '-Wl,-U,_sysmem_ptrsize' '-Wl,-U,_sysmem_resizehandle' '-Wl,-U,_sysmem_resizeptr' '-Wl,-U,_sysmem_resizeptrclear' '-Wl,-U,_sysmenu_appenditem' '-Wl,-U,_sysmenu_appendrawitem' '-Wl,-U,_sysmenu_appendseparator' '-Wl,-U,_sysmenu_assignsubmenu' '-Wl,-U,_sysmenu_checkitem' '-Wl,-U,_sysmenu_cmdid_popup' '-Wl,-U,_sysmenu_cmdid_set' '-Wl,-U,_sysmenu_copyitems' '-Wl,-U,_sysmenu_deleteallitems' '-Wl,-U,_sysmenu_deleteitem' '-Wl,-U,_sysmenu_dispose' '-Wl,-U,_sysmenu_getcheck' '-Wl,-U,_sysmenu_gethelp' '-Wl,-U,_sysmenu_getid' '-Wl,-U,_sysmenu_gettext' '-Wl,-U,_sysmenu_gettitle' '-Wl,-U,_sysmenu_insert' '-Wl,-U,_sysmenu_insertsubmenu' '-Wl,-U,_sysmenu_itemcount' '-Wl,-U,_sysmenu_new' '-Wl,-U,_sysmenu_setitem' '-Wl,-U,_sysmenu_setreference' '-Wl,-U,_sysmenu_setshortcut' '-Wl,-U,_sysmenu_settext' '-Wl,-U,_sysmidi_createport' '-Wl,-U,_sysmidi_deletemarked' '-Wl,-U,_sysmidi_enqbigpacket' '-Wl,-U,_sysmidi_getinstance' '-Wl,-U,_sysmidi_idtoport' '-Wl,-U,_sysmidi_indextoname' '-Wl,-U,_sysmidi_iterate' '-Wl,-U,_sysmidi_numinports' '-Wl,-U,_sysmidi_numoutports' '-Wl,-U,_sysmidi_uniqueid' '-Wl,-U,_sysmidi_data1toport' '-Wl,-U,_sysmidi_nametoport' '-Wl,-U,_sysparallel_processorcount' '-Wl,-U,_sysparallel_physical_processorcount' '-Wl,-U,_sysparallel_task_benchprint' '-Wl,-U,_sysparallel_task_cancel' '-Wl,-U,_sysparallel_task_data' '-Wl,-U,_sysparallel_task_execute' '-Wl,-U,_sysparallel_task_free' '-Wl,-U,_sysparallel_task_new' '-Wl,-U,_sysparallel_task_workerproc' '-Wl,-U,_sysparallel_worker_execute' '-Wl,-U,_sysparallel_worker_free' '-Wl,-U,_sysparallel_worker_new' '-Wl,-U,_systhread_cond_broadcast' '-Wl,-U,_systhread_cond_free' '-Wl,-U,_systhread_cond_new' '-Wl,-U,_systhread_cond_signal' '-Wl,-U,_systhread_cond_wait' '-Wl,-U,_systhread_create' '-Wl,-U,_systhread_exit' '-Wl,-U,_systhread_getspecific' '-Wl,-U,_systhread_ismainthread' '-Wl,-U,_systhread_istimerthread' '-Wl,-U,_systhread_isaudiothread' '-Wl,-U,_systhread_set_name' '-Wl,-U,_systhread_markasaudiothread_begin' '-Wl,-U,_systhread_markasaudiothread_end' '-Wl,-U,_systhread_join' '-Wl,-U,_systhread_timedjoin' '-Wl,-U,_systhread_detach' '-Wl,-U,_systhread_mutex_free' '-Wl,-U,_systhread_mutex_lock' '-Wl,-U,_systhread_mutex_new' '-Wl,-U,_systhread_mutex_newlock' '-Wl,-U,_systhread_mutex_trylock' '-Wl,-U,_systhread_mutex_unlock' '-Wl,-U,_systhread_rwlock_new' '-Wl,-U,_systhread_rwlock_free' '-Wl,-U,_systhread_rwlock_rdlock' '-Wl,-U,_systhread_rwlock_tryrdlock' '-Wl,-U,_systhread_rwlock_rdunlock' '-Wl,-U,_systhread_rwlock_wrlock' '-Wl,-U,_systhread_rwlock_trywrlock' '-Wl,-U,_systhread_rwlock_wrunlock' '-Wl,-U,_systhread_rwlock_setspintime' '-Wl,-U,_systhread_rwlock_getspintime' '-Wl,-U,_systhread_key_create' '-Wl,-U,_systhread_key_delete' '-Wl,-U,_systhread_self' '-Wl,-U,_systhread_equal' '-Wl,-U,_systhread_setpriority' '-Wl,-U,_systhread_getpriority' '-Wl,-U,_systhread_setspecific' '-Wl,-U,_systhread_eliminatedenormals' '-Wl,-U,_systhread_sleep' '-Wl,-U,_systhread_terminate' '-Wl,-U,_systime_datetime' '-Wl,-U,_systime_datetoseconds' '-Wl,-U,_systime_datetime_milliseconds' '-Wl,-U,_systime_ms' '-Wl,-U,_systime_seconds' '-Wl,-U,_systime_secondstodate' '-Wl,-U,_systime_ticks' '-Wl,-U,_systimer_gettime' '-Wl,-U,_tabfromhandle' '-Wl,-U,_table_dirty' '-Wl,-U,_table_get' '-Wl,-U,_textpreferences_add' '-Wl,-U,_textpreferences_addoption' '-Wl,-U,_textpreferences_addraw' '-Wl,-U,_textpreferences_addrect' '-Wl,-U,_textpreferences_close' '-Wl,-U,_textpreferences_default' '-Wl,-U,_textpreferences_open' '-Wl,-U,_textpreferences_read' '-Wl,-U,_time_stop' '-Wl,-U,_time_tick' '-Wl,-U,_time_getms' '-Wl,-U,_time_getticks' '-Wl,-U,_time_listen' '-Wl,-U,_time_getphase' '-Wl,-U,_time_setvalue' '-Wl,-U,_class_time_addattr' '-Wl,-U,_time_new' '-Wl,-U,_time_new_custom' '-Wl,-U,_time_getnamed' '-Wl,-U,_time_enable_attributes' '-Wl,-U,_time_isfixedunit' '-Wl,-U,_time_schedule' '-Wl,-U,_time_schedule_limit' '-Wl,-U,_time_setticks' '-Wl,-U,_time_now' '-Wl,-U,_time_getitm' '-Wl,-U,_time_calcquantize' '-Wl,-U,_time_setclock' '-Wl,-U,_toolfile_fread' '-Wl,-U,_toolfile_fwrite' '-Wl,-U,_toolfile_getc' '-Wl,-U,_toolfile_new' '-Wl,-U,_translation_getinterfacepath' '-Wl,-U,_typedmess' '-Wl,-U,_typelist_make' '-Wl,-U,_utils_setcontext' '-Wl,-U,_utils_usecontext' '-Wl,-U,_utils_getcontextnumber' '-Wl,-U,_utils_contextinuse' '-Wl,-U,_wind_advise' '-Wl,-U,_wind_advise_explain' '-Wl,-U,_wind_nocancel' '-Wl,-U,_wind_setcursor' '-Wl,-U,_xmltree_attr_symcompare' '-Wl,-U,_xmltree_attribute_free' '-Wl,-U,_xmltree_attribute_new' '-Wl,-U,_xmltree_cdata_free' '-Wl,-U,_xmltree_cdata_new' '-Wl,-U,_xmltree_cdata_splittext' '-Wl,-U,_xmltree_charnode_addinterface' '-Wl,-U,_xmltree_charnode_appenddata' '-Wl,-U,_xmltree_charnode_deletedata' '-Wl,-U,_xmltree_charnode_free' '-Wl,-U,_xmltree_charnode_insertdata' '-Wl,-U,_xmltree_charnode_new' '-Wl,-U,_xmltree_charnode_replacedata' '-Wl,-U,_xmltree_charnode_substringdata' '-Wl,-U,_xmltree_comment_free' '-Wl,-U,_xmltree_comment_new' '-Wl,-U,_xmltree_document_createattribute' '-Wl,-U,_xmltree_document_createcdatasection' '-Wl,-U,_xmltree_document_createcomment' '-Wl,-U,_xmltree_document_createelement' '-Wl,-U,_xmltree_document_createheader' '-Wl,-U,_xmltree_document_createtextnode' '-Wl,-U,_xmltree_document_filename' '-Wl,-U,_xmltree_document_free' '-Wl,-U,_xmltree_document_getelementsbytagname' '-Wl,-U,_xmltree_document_new' '-Wl,-U,_xmltree_document_print' '-Wl,-U,_xmltree_document_read' '-Wl,-U,_xmltree_document_write' '-Wl,-U,_xmltree_document_xmlparse_cdata_end' '-Wl,-U,_xmltree_document_xmlparse_cdata_start' '-Wl,-U,_xmltree_document_xmlparse_characterdata' '-Wl,-U,_xmltree_document_xmlparse_comment' '-Wl,-U,_xmltree_document_xmlparse_default' '-Wl,-U,_xmltree_document_xmlparse_doctype_end' '-Wl,-U,_xmltree_document_xmlparse_doctype_start' '-Wl,-U,_xmltree_document_xmlparse_element_end' '-Wl,-U,_xmltree_document_xmlparse_element_start' '-Wl,-U,_xmltree_element_free' '-Wl,-U,_xmltree_element_getattribute' '-Wl,-U,_xmltree_element_getattribute_float' '-Wl,-U,_xmltree_element_getattribute_float_array' '-Wl,-U,_xmltree_element_getattribute_long' '-Wl,-U,_xmltree_element_getattribute_long_array' '-Wl,-U,_xmltree_element_getattribute_sym' '-Wl,-U,_xmltree_element_getattribute_sym_array' '-Wl,-U,_xmltree_element_getattributenode' '-Wl,-U,_xmltree_element_getelementsbytagname' '-Wl,-U,_xmltree_element_new' '-Wl,-U,_xmltree_element_removeattribute' '-Wl,-U,_xmltree_element_removeattributenode' '-Wl,-U,_xmltree_element_setattribute' '-Wl,-U,_xmltree_element_setattribute_float' '-Wl,-U,_xmltree_element_setattribute_float_array' '-Wl,-U,_xmltree_element_setattribute_long' '-Wl,-U,_xmltree_element_setattribute_long_array' '-Wl,-U,_xmltree_element_setattribute_sym' '-Wl,-U,_xmltree_element_setattribute_sym_array' '-Wl,-U,_xmltree_element_setattributenode' '-Wl,-U,_xmltree_element_symcompare' '-Wl,-U,_xmltree_init' '-Wl,-U,_xmltree_node_addinterface' '-Wl,-U,_xmltree_node_appendchild' '-Wl,-U,_xmltree_node_clonenode' '-Wl,-U,_xmltree_node_free' '-Wl,-U,_xmltree_node_getnodevalasstring' '-Wl,-U,_xmltree_node_getnodevalue' '-Wl,-U,_xmltree_node_getnodevalue_float' '-Wl,-U,_xmltree_node_getnodevalue_float_array' '-Wl,-U,_xmltree_node_getnodevalue_long' '-Wl,-U,_xmltree_node_getnodevalue_long_array' '-Wl,-U,_xmltree_node_getnodevalue_sym' '-Wl,-U,_xmltree_node_getnodevalue_sym_array' '-Wl,-U,_xmltree_node_haschildnodes' '-Wl,-U,_xmltree_node_insertbefore' '-Wl,-U,_xmltree_node_new' '-Wl,-U,_xmltree_node_nodevalue' '-Wl,-U,_xmltree_node_nodevalue_float' '-Wl,-U,_xmltree_node_nodevalue_float_array' '-Wl,-U,_xmltree_node_nodevalue_long' '-Wl,-U,_xmltree_node_nodevalue_long_array' '-Wl,-U,_xmltree_node_nodevalue_sym' '-Wl,-U,_xmltree_node_nodevalue_sym_array' '-Wl,-U,_xmltree_node_removeallchildren' '-Wl,-U,_xmltree_node_removechild' '-Wl,-U,_xmltree_node_replacechild' '-Wl,-U,_xmltree_node_setnodevalasstring' '-Wl,-U,_xmltree_node_write' '-Wl,-U,_xmltree_text_free' '-Wl,-U,_xmltree_text_new' '-Wl,-U,_xmltree_text_splittext' '-Wl,-U,_xpcoll_dereference' '-Wl,-U,_xpcoll_load' '-Wl,-U,_xpcoll_open' '-Wl,-U,_xpcoll_opensysfile' '-Wl,-U,_xpcoll_reference' '-Wl,-U,_xpcoll_setclientcallback' '-Wl,-U,_xpcoll_getvol' '-Wl,-U,_xpcoll_openfile' '-Wl,-U,_xpcoll_fromnameddata' '-Wl,-U,_xpcoll_unfreezedevice' '-Wl,-U,_xsetpost' '-Wl,-U,_zgetfn' '-Wl,-U,_jbox_initclass' '-Wl,-U,_jbox_new' '-Wl,-U,_jbox_free' '-Wl,-U,_jbox_ready' '-Wl,-U,_jbox_redraw' '-Wl,-U,_jbox_redrawcontents' '-Wl,-U,_jbox_getoutlet' '-Wl,-U,_jbox_getinlet' '-Wl,-U,_jbox_updatetextfield' '-Wl,-U,_jbox_updatetextfield_safe' '-Wl,-U,_jbox_updatetextfield_lockmutex' '-Wl,-U,_jbox_grabfocus' '-Wl,-U,_jbox_show_caption' '-Wl,-U,_jbox_hide_caption' '-Wl,-U,_jbox_invalidate_layer' '-Wl,-U,_jbox_remove_layer' '-Wl,-U,_jbox_start_layer' '-Wl,-U,_jbox_end_layer' '-Wl,-U,_jbox_paint_layer' '-Wl,-U,_jbox_get_boxpath' '-Wl,-U,_jbox_validaterects' '-Wl,-U,_jbox_processlegacydefaults' '-Wl,-U,_jbox_isdefaultattribute' '-Wl,-U,_jpatcher_deleteobj' '-Wl,-U,_jpatcher_is_patcher' '-Wl,-U,_jpatcher_get_box' '-Wl,-U,_jpatcher_get_count' '-Wl,-U,_jpatcher_get_firstobject' '-Wl,-U,_jpatcher_get_lastobject' '-Wl,-U,_jpatcher_get_firstline' '-Wl,-U,_jpatcher_get_firstview' '-Wl,-U,_jpatcher_set_locked' '-Wl,-U,_jpatcher_get_title' '-Wl,-U,_jpatcher_set_title' '-Wl,-U,_jpatcher_get_name' '-Wl,-U,_jpatcher_get_filename' '-Wl,-U,_jpatcher_get_filepath' '-Wl,-U,_jpatcher_get_dirty' '-Wl,-U,_jpatcher_set_dirty' '-Wl,-U,_jpatcher_get_bgcolor' '-Wl,-U,_jpatcher_set_bgcolor' '-Wl,-U,_jpatcher_get_gridsize' '-Wl,-U,_jpatcher_set_gridsize' '-Wl,-U,_jpatcher_get_parentpatcher' '-Wl,-U,_jpatcher_get_toppatcher' '-Wl,-U,_jpatcher_get_hubholder' '-Wl,-U,_jpatcher_get_maxclass' '-Wl,-U,_jpatcher_get_parentclass' '-Wl,-U,_jpatcher_get_rect' '-Wl,-U,_jpatcher_set_rect' '-Wl,-U,_jpatcher_get_noedit' '-Wl,-U,_jpatcher_uniqueboxname' '-Wl,-U,_jpatcher_getboxfont' '-Wl,-U,_jpatcher_get_controller' '-Wl,-U,_jpatcher_addboxlistener' '-Wl,-U,_jpatcher_removeboxlistener' '-Wl,-U,_jpatcher_get_fileversion' '-Wl,-U,_jpatcher_get_currentfileversion' '-Wl,-U,_jpatcher_get_bglocked' '-Wl,-U,_jpatcher_get_presentation' '-Wl,-U,_jpatcher_inc_maxsendcontext' '-Wl,-U,_jpatcher_dictionary_modernui' '-Wl,-U,_jpatcher_dictionary_version' '-Wl,-U,_jpatcher_sortdictionary' '-Wl,-U,_jpatcher_getboxfromid' '-Wl,-U,_jpatcher_endlognewobjects' '-Wl,-U,_jpatcher_swapboxlist' '-Wl,-U,_jpatcher_swaplinelist' '-Wl,-U,_systemfontname' '-Wl,-U,_systemfontsym' '-Wl,-U,_jpatchercontroller_createobject' '-Wl,-U,_jpatchercontroller_setpatcherview' '-Wl,-U,_jpatchercontroller_pastefileintoobject' '-Wl,-U,_jpatchercontroller_pastefileat' '-Wl,-U,_jpatchercontroller_connectobjects' '-Wl,-U,_jpatchercontroller_begintransaction' '-Wl,-U,_jpatchercontroller_endtransaction' '-Wl,-U,_jpatchercontroller_setattr' '-Wl,-U,_jpatchercontroller_dictionary_setattr' '-Wl,-U,_object_attr_get_rect' '-Wl,-U,_object_attr_set_rect' '-Wl,-U,_object_attr_getcolor' '-Wl,-U,_object_attr_setcolor' '-Wl,-U,_object_attr_getpt' '-Wl,-U,_object_attr_setpt' '-Wl,-U,_object_attr_getsize' '-Wl,-U,_object_attr_setsize' '-Wl,-U,_jbox_get_maxclass' '-Wl,-U,_jbox_get_patcher' '-Wl,-U,_jbox_get_object' '-Wl,-U,_jbox_get_rect_for_view' '-Wl,-U,_jbox_set_rect_for_view' '-Wl,-U,_jbox_get_rect_for_sym' '-Wl,-U,_jbox_set_rect_for_sym' '-Wl,-U,_jbox_set_rect' '-Wl,-U,_jbox_get_patching_rect' '-Wl,-U,_jbox_set_patching_rect' '-Wl,-U,_jbox_get_presentation_rect' '-Wl,-U,_jbox_set_presentation_rect' '-Wl,-U,_jbox_set_position' '-Wl,-U,_jbox_get_patching_position' '-Wl,-U,_jbox_set_patching_position' '-Wl,-U,_jbox_get_presentation_position' '-Wl,-U,_jbox_set_presentation_position' '-Wl,-U,_jbox_set_size' '-Wl,-U,_jbox_get_patching_size' '-Wl,-U,_jbox_set_patching_size' '-Wl,-U,_jbox_get_presentation_size' '-Wl,-U,_jbox_set_presentation_size' '-Wl,-U,_jbox_get_hidden' '-Wl,-U,_jbox_set_hidden' '-Wl,-U,_jbox_get_fontname' '-Wl,-U,_jbox_set_fontname' '-Wl,-U,_jbox_get_fontsize' '-Wl,-U,_jbox_createfont' '-Wl,-U,_jbox_set_fontsize' '-Wl,-U,_jbox_fontface_to_weight_slant' '-Wl,-U,_jbox_get_font_slant' '-Wl,-U,_jbox_get_font_weight' '-Wl,-U,_jbox_get_color' '-Wl,-U,_jbox_set_color' '-Wl,-U,_jbox_get_nextobject' '-Wl,-U,_jbox_get_prevobject' '-Wl,-U,_jbox_get_varname' '-Wl,-U,_jbox_set_varname' '-Wl,-U,_jbox_get_id' '-Wl,-U,_jbox_get_canhilite' '-Wl,-U,_jbox_get_background' '-Wl,-U,_jbox_set_background' '-Wl,-U,_jbox_get_ignoreclick' '-Wl,-U,_jbox_set_ignoreclick' '-Wl,-U,_jbox_get_drawfirstin' '-Wl,-U,_jbox_get_outline' '-Wl,-U,_jbox_set_outline' '-Wl,-U,_jbox_get_growy' '-Wl,-U,_jbox_get_growboth' '-Wl,-U,_jbox_get_nogrow' '-Wl,-U,_jbox_get_drawinlast' '-Wl,-U,_jbox_get_mousedragdelta' '-Wl,-U,_jbox_set_mousedragdelta' '-Wl,-U,_jbox_get_textfield' '-Wl,-U,_jbox_set_hinttrack' '-Wl,-U,_jbox_get_hinttrack' '-Wl,-U,_jbox_set_hintstring' '-Wl,-U,_jpatchline_get_startpoint' '-Wl,-U,_jpatchline_get_endpoint' '-Wl,-U,_jpatchline_get_nummidpoints' '-Wl,-U,_jpatchline_get_pending' '-Wl,-U,_jpatchline_get_box1' '-Wl,-U,_jpatchline_get_outletnum' '-Wl,-U,_jpatchline_get_box2' '-Wl,-U,_jpatchline_get_inletnum' '-Wl,-U,_jpatchline_get_straightthresh' '-Wl,-U,_jpatchline_set_straightthresh' '-Wl,-U,_jpatchline_get_straightstart' '-Wl,-U,_jpatchline_get_straightend' '-Wl,-U,_jpatchline_set_straightstart' '-Wl,-U,_jpatchline_set_straightend' '-Wl,-U,_jpatchline_get_nextline' '-Wl,-U,_jpatchline_get_hidden' '-Wl,-U,_jpatchline_set_hidden' '-Wl,-U,_jpatchline_get_color' '-Wl,-U,_jpatchline_set_color' '-Wl,-U,_jpatchline_addpaintmethod' '-Wl,-U,_patcherview_get_visible' '-Wl,-U,_patcherview_set_visible' '-Wl,-U,_patcherview_get_locked' '-Wl,-U,_patcherview_set_locked' '-Wl,-U,_patcherview_get_zoomfactor' '-Wl,-U,_patcherview_set_zoomfactor' '-Wl,-U,_patcherview_get_nextview' '-Wl,-U,_patcherview_get_topview' '-Wl,-U,_patcherview_get_jgraphics' '-Wl,-U,_patcherview_set_jgraphics' '-Wl,-U,_patcherview_get_patcher' '-Wl,-U,_patcherview_get_rect' '-Wl,-U,_patcherview_set_rect' '-Wl,-U,_patcherview_canvas_to_screen' '-Wl,-U,_patcherview_screen_to_canvas' '-Wl,-U,_patcherview_get_presentation' '-Wl,-U,_textfield_get_owner' '-Wl,-U,_textfield_get_textcolor' '-Wl,-U,_textfield_set_textcolor' '-Wl,-U,_textfield_get_bgcolor' '-Wl,-U,_textfield_set_bgcolor' '-Wl,-U,_textfield_get_textmargins' '-Wl,-U,_textfield_set_textmargins' '-Wl,-U,_textfield_get_editonclick' '-Wl,-U,_textfield_set_editonclick' '-Wl,-U,_textfield_get_selectallonedit' '-Wl,-U,_textfield_set_selectallonedit' '-Wl,-U,_textfield_get_noactivate' '-Wl,-U,_textfield_set_noactivate' '-Wl,-U,_textfield_get_readonly' '-Wl,-U,_textfield_set_readonly' '-Wl,-U,_textfield_get_wordwrap' '-Wl,-U,_textfield_set_wordwrap' '-Wl,-U,_textfield_get_useellipsis' '-Wl,-U,_textfield_set_useellipsis' '-Wl,-U,_textfield_get_autoscroll' '-Wl,-U,_textfield_set_autoscroll' '-Wl,-U,_textfield_get_wantsreturn' '-Wl,-U,_textfield_set_wantsreturn' '-Wl,-U,_textfield_get_wantstab' '-Wl,-U,_textfield_set_wantstab' '-Wl,-U,_textfield_get_autofixwidth' '-Wl,-U,_textfield_set_autofixwidth' '-Wl,-U,_textfield_set_emptytext' '-Wl,-U,_textfield_get_emptytext' '-Wl,-U,_textfield_set_underline' '-Wl,-U,_textfield_get_underline' '-Wl,-U,_textfield_set_justification' '-Wl,-U,_textfield_get_justification' '-Wl,-U,_jdrag_getitemstring' '-Wl,-U,_jdrag_getobject' '-Wl,-U,_jdrag_getlocation' '-Wl,-U,_jdrag_createobject' '-Wl,-U,_jdrag_createnewobj' '-Wl,-U,_jdrag_createmessage' '-Wl,-U,_jdrag_add' '-Wl,-U,_jdrag_process_drop' '-Wl,-U,_jdrag_matchdragrole' '-Wl,-U,_jdrag_setboxlocation' '-Wl,-U,_jdrag_box_add' '-Wl,-U,_jdrag_object_add' '-Wl,-U,_jdrag_itemcount' '-Wl,-U,_jgraphics_getfiletypes' '-Wl,-U,_jgraphics_round' '-Wl,-U,_jgraphics_image_surface_clear' '-Wl,-U,_jgraphics_image_surface_create' '-Wl,-U,_jgraphics_image_surface_create_referenced' '-Wl,-U,_jgraphics_image_surface_create_from_file' '-Wl,-U,_jgraphics_image_surface_create_for_data' '-Wl,-U,_jgraphics_image_surface_create_from_filedata' '-Wl,-U,_jgraphics_image_surface_create_from_resource' '-Wl,-U,_jgraphics_image_surface_writepng' '-Wl,-U,_jgraphics_image_surface_writejpeg' '-Wl,-U,_jgraphics_surface_reference' '-Wl,-U,_jgraphics_surface_destroy' '-Wl,-U,_jgraphics_surface_set_device_offset' '-Wl,-U,_jgraphics_surface_get_device_offset' '-Wl,-U,_jgraphics_image_surface_get_width' '-Wl,-U,_jgraphics_image_surface_get_height' '-Wl,-U,_jgraphics_image_surface_set_pixel' '-Wl,-U,_jgraphics_image_surface_get_pixel' '-Wl,-U,_jgraphics_image_surface_scroll' '-Wl,-U,_jgraphics_image_surface_lockpixels_readonly' '-Wl,-U,_jgraphics_image_surface_unlockpixels_readonly' '-Wl,-U,_jgraphics_image_surface_lockpixels' '-Wl,-U,_jgraphics_image_surface_unlockpixels' '-Wl,-U,_jgraphics_image_surface_draw' '-Wl,-U,_jgraphics_image_surface_draw_fast' '-Wl,-U,_jgraphics_getfontscale' '-Wl,-U,_jgraphics_get_resource_data' '-Wl,-U,_jsvg_create_from_file' '-Wl,-U,_jsvg_create_from_resource' '-Wl,-U,_jsvg_create_from_xmlstring' '-Wl,-U,_jsvg_get_size' '-Wl,-U,_jsvg_destroy' '-Wl,-U,_jsvg_render' '-Wl,-U,_jgraphics_create' '-Wl,-U,_jgraphics_reference' '-Wl,-U,_jgraphics_destroy' '-Wl,-U,_jgraphics_new_path' '-Wl,-U,_jgraphics_copy_path' '-Wl,-U,_jgraphics_path_destroy' '-Wl,-U,_jgraphics_append_path' '-Wl,-U,_jgraphics_close_path' '-Wl,-U,_jgraphics_path_roundcorners' '-Wl,-U,_jgraphics_get_current_point' '-Wl,-U,_jgraphics_diagonal_line_fill' '-Wl,-U,_jgraphics_arc' '-Wl,-U,_jgraphics_arc_negative' '-Wl,-U,_jgraphics_piesegment' '-Wl,-U,_jgraphics_curve_to' '-Wl,-U,_jgraphics_rel_curve_to' '-Wl,-U,_jgraphics_line_to' '-Wl,-U,_jgraphics_rel_line_to' '-Wl,-U,_jgraphics_move_to' '-Wl,-U,_jgraphics_rel_move_to' '-Wl,-U,_jgraphics_rectangle' '-Wl,-U,_jgraphics_rectangle_rounded' '-Wl,-U,_jgraphics_ellipse' '-Wl,-U,_jgraphics_oval' '-Wl,-U,_jgraphics_ovalarc' '-Wl,-U,_jgraphics_in_fill' '-Wl,-U,_jgraphics_line_intersects_rect' '-Wl,-U,_jgraphics_path_intersects_line' '-Wl,-U,_jgraphics_path_intersectsline' '-Wl,-U,_jgraphics_path_getpathelems' '-Wl,-U,_jgraphics_rectintersectsrect' '-Wl,-U,_jgraphics_rectcontainsrect' '-Wl,-U,_jgraphics_ptinrect' '-Wl,-U,_jgraphics_ptinroundedrect' '-Wl,-U,_jgraphics_fill_extents' '-Wl,-U,_jgraphics_select_font_face' '-Wl,-U,_jgraphics_select_jfont' '-Wl,-U,_jgraphics_set_font_size' '-Wl,-U,_jgraphics_set_underline' '-Wl,-U,_jgraphics_show_text' '-Wl,-U,_jgraphics_font_extents' '-Wl,-U,_jgraphics_text_measure' '-Wl,-U,_jgraphics_text_measuretext_wrapped' '-Wl,-U,_jgraphics_text_path' '-Wl,-U,_jgraphics_jrgba_contrasting' '-Wl,-U,_jgraphics_jrgba_contrastwith' '-Wl,-U,_jgraphics_jrgba_darker' '-Wl,-U,_jgraphics_jrgba_brighter' '-Wl,-U,_jgraphics_jrgba_overlay' '-Wl,-U,_jgraphics_jrgba_interpolate' '-Wl,-U,_jgraphics_jrgba_gethsb' '-Wl,-U,_jgraphics_jrgba_fromhsb' '-Wl,-U,_jgraphics_clip' '-Wl,-U,_jfont_create_from_maxfont' '-Wl,-U,_jfont_create' '-Wl,-U,_jfont_reference' '-Wl,-U,_jfont_destroy' '-Wl,-U,_jfont_ellipsifytext' '-Wl,-U,_jfont_isequalto' '-Wl,-U,_jfont_set_family' '-Wl,-U,_jfont_get_family' '-Wl,-U,_jfont_set_slant' '-Wl,-U,_jfont_get_slant' '-Wl,-U,_jfont_set_weight' '-Wl,-U,_jfont_get_weight' '-Wl,-U,_jfont_set_font_size' '-Wl,-U,_jfont_get_font_size' '-Wl,-U,_jfont_set_underline' '-Wl,-U,_jfont_get_underline' '-Wl,-U,_jfont_get_heighttocharheightratio' '-Wl,-U,_jfont_extents' '-Wl,-U,_jfont_text_measure' '-Wl,-U,_jfont_text_measuretext_wrapped' '-Wl,-U,_jfont_getfontlist' '-Wl,-U,_jfont_get_em_dimensions' '-Wl,-U,_jgraphics_system_canantialiastexttotransparentbg' '-Wl,-U,_jtextlayout_create' '-Wl,-U,_jtextlayout_withbgcolor' '-Wl,-U,_jtextlayout_destroy' '-Wl,-U,_jtextlayout_set' '-Wl,-U,_jtextlayout_settext' '-Wl,-U,_jtextlayout_settextcolor' '-Wl,-U,_jtextlayout_measuretext' '-Wl,-U,_jtextlayout_draw' '-Wl,-U,_jtextlayout_getnumchars' '-Wl,-U,_jtextlayout_getcharbox' '-Wl,-U,_jtextlayout_getchar' '-Wl,-U,_jtextlayout_createpath' '-Wl,-U,_jgraphics_matrix_init' '-Wl,-U,_jgraphics_matrix_init_identity' '-Wl,-U,_jgraphics_matrix_init_translate' '-Wl,-U,_jgraphics_matrix_init_scale' '-Wl,-U,_jgraphics_matrix_init_rotate' '-Wl,-U,_jgraphics_matrix_translate' '-Wl,-U,_jgraphics_matrix_scale' '-Wl,-U,_jgraphics_matrix_rotate' '-Wl,-U,_jgraphics_matrix_invert' '-Wl,-U,_jgraphics_matrix_multiply' '-Wl,-U,_jgraphics_matrix_transform_point' '-Wl,-U,_jgraphics_pattern_create_rgba' '-Wl,-U,_jgraphics_pattern_create_for_surface' '-Wl,-U,_jgraphics_pattern_create_linear' '-Wl,-U,_jgraphics_pattern_create_radial' '-Wl,-U,_jgraphics_pattern_add_color_stop_rgba' '-Wl,-U,_jgraphics_pattern_reference' '-Wl,-U,_jgraphics_pattern_destroy' '-Wl,-U,_jgraphics_pattern_get_type' '-Wl,-U,_jgraphics_pattern_set_extend' '-Wl,-U,_jgraphics_pattern_get_extend' '-Wl,-U,_jgraphics_pattern_set_matrix' '-Wl,-U,_jgraphics_pattern_get_matrix' '-Wl,-U,_jgraphics_pattern_get_surface' '-Wl,-U,_jgraphics_pattern_translate' '-Wl,-U,_jgraphics_pattern_scale' '-Wl,-U,_jgraphics_pattern_rotate' '-Wl,-U,_jgraphics_translate' '-Wl,-U,_jgraphics_scale' '-Wl,-U,_jgraphics_rotate' '-Wl,-U,_jgraphics_transform' '-Wl,-U,_jgraphics_set_matrix' '-Wl,-U,_jgraphics_get_matrix' '-Wl,-U,_jgraphics_identity_matrix' '-Wl,-U,_jgraphics_user_to_device' '-Wl,-U,_jgraphics_device_to_user' '-Wl,-U,_jgraphics_save' '-Wl,-U,_jgraphics_restore' '-Wl,-U,_jgraphics_set_source_rgba' '-Wl,-U,_jgraphics_set_source_jrgba' '-Wl,-U,_jgraphics_set_source_rgb' '-Wl,-U,_jgraphics_set_source' '-Wl,-U,_jgraphics_set_source_surface' '-Wl,-U,_jgraphics_set_source_shared' '-Wl,-U,_jgraphics_scale_source_rgba' '-Wl,-U,_jgraphics_translate_source_rgba' '-Wl,-U,_jgraphics_set_dash' '-Wl,-U,_jgraphics_set_fill_rule' '-Wl,-U,_jgraphics_get_fill_rule' '-Wl,-U,_jgraphics_set_line_cap' '-Wl,-U,_jgraphics_get_line_cap' '-Wl,-U,_jgraphics_set_line_join' '-Wl,-U,_jgraphics_get_line_join' '-Wl,-U,_jgraphics_set_line_width' '-Wl,-U,_jgraphics_get_line_width' '-Wl,-U,_jgraphics_paint' '-Wl,-U,_jgraphics_paint_with_alpha' '-Wl,-U,_jgraphics_fill' '-Wl,-U,_jgraphics_fill_preserve' '-Wl,-U,_jgraphics_fill_preserve_with_alpha' '-Wl,-U,_jgraphics_fill_with_alpha' '-Wl,-U,_jgraphics_stroke' '-Wl,-U,_jgraphics_stroke_preserve' '-Wl,-U,_jgraphics_stroke_preserve_with_alpha' '-Wl,-U,_jgraphics_stroke_with_alpha' '-Wl,-U,_get_boxcolor_index_from_jrgba' '-Wl,-U,_set_jrgba_from_palette_index' '-Wl,-U,_set_jrgba_from_boxcolor_index' '-Wl,-U,_jgraphics_clip_rgba' '-Wl,-U,_jpopupmenu_create' '-Wl,-U,_jpopupmenu_destroy' '-Wl,-U,_jpopupmenu_clear' '-Wl,-U,_jpopupmenu_default_options' '-Wl,-U,_jpopupmenu_setcolors' '-Wl,-U,_jpopupmenu_setfont' '-Wl,-U,_jpopupmenu_additem' '-Wl,-U,_jpopupmenu_additemwithshortcut' '-Wl,-U,_jpopupmenu_addsubmenu' '-Wl,-U,_jpopupmenu_addsubmenu_owned' '-Wl,-U,_jpopupmenu_addseparator' '-Wl,-U,_jpopupmenu_addseperator' '-Wl,-U,_jpopupmenu_addownerdrawitem' '-Wl,-U,_jpopupmenu_popup' '-Wl,-U,_jpopupmenu_popup_nearbox' '-Wl,-U,_jpopupmenu_popup_nearbox_with_options' '-Wl,-U,_jpopupmenu_popup_abovebox' '-Wl,-U,_jpopupmenu_popup_belowrect' '-Wl,-U,_jpopupmenu_popup_leftofpt' '-Wl,-U,_jpopupmenu_closeall' '-Wl,-U,_jpopupmenu_setstandardstyle' '-Wl,-U,_jpopupmenu_setfixedwidth' '-Wl,-U,_jmouse_getposition_global' '-Wl,-U,_jmouse_setposition_global' '-Wl,-U,_jmouse_setposition_view' '-Wl,-U,_jmouse_setposition_box' '-Wl,-U,_jmouse_setcursor' '-Wl,-U,_jmouse_setcursor_surface' '-Wl,-U,_dictionary_appendjrgba' '-Wl,-U,_dictionary_getdefjrgba' '-Wl,-U,_dictionary_gettrect' '-Wl,-U,_dictionary_appendtrect' '-Wl,-U,_dictionary_gettpt' '-Wl,-U,_dictionary_appendtpt' '-Wl,-U,_atomstojrgba' '-Wl,-U,_jrgbatoatoms' '-Wl,-U,_qd_new' '-Wl,-U,_qd_initialize' '-Wl,-U,_qd_copystate' '-Wl,-U,_qd_PenNormal' '-Wl,-U,_qd_RGBForeColor' '-Wl,-U,_qd_RGBBackColor' '-Wl,-U,_qd_BoxcolorIndexForeColor' '-Wl,-U,_qd_InsetTRect' '-Wl,-U,_qd_OffsetTRect' '-Wl,-U,_qd_EqualTRect' '-Wl,-U,_qd_JRGBAToRGBColor' '-Wl,-U,_qd_GetForeColor' '-Wl,-U,_qd_GetBackColor' '-Wl,-U,_qd_GetForeJColor' '-Wl,-U,_qd_GetBackJColor' '-Wl,-U,_qd_Black' '-Wl,-U,_qd_White' '-Wl,-U,_qd_MoveTo' '-Wl,-U,_qd_LineTo' '-Wl,-U,_qd_Line' '-Wl,-U,_qd_EraseRect' '-Wl,-U,_qd_TRectToRect' '-Wl,-U,_qd_RectToTRect' '-Wl,-U,_qd_RGBColorToJRGBA' '-Wl,-U,_qd_TRectToRectZero' '-Wl,-U,_qd_InsetRect' '-Wl,-U,_qd_OffsetRect' '-Wl,-U,_qd_PaintTRect' '-Wl,-U,_qd_PaintRect' '-Wl,-U,_qd_FrameRect' '-Wl,-U,_qd_PenSize' '-Wl,-U,_qd_Move' '-Wl,-U,_qd_SetBackJColor' '-Wl,-U,_qd_SetRect' '-Wl,-U,_qd_PaintOval' '-Wl,-U,_qd_FrameOval' '-Wl,-U,_qd_PaintRoundRect' '-Wl,-U,_qd_FrameRoundRect' '-Wl,-U,_qd_GetPenLoc' '-Wl,-U,_qd_GetCPixel' '-Wl,-U,_qd_SetCPixel' '-Wl,-U,_qd_PaintArc' '-Wl,-U,_qd_FrameArc' '-Wl,-U,_qd_SetForeJColor' '-Wl,-U,_qd_KillPoly' '-Wl,-U,_qd_PaintPoly' '-Wl,-U,_qd_ClosePoly' '-Wl,-U,_qd_OpenPoly' '-Wl,-U,_qd_LineSegment' '-Wl,-U,_qd_TPtInTRect' '-Wl,-U,_qd_FramePoly' '-Wl,-U,_qd_CloseRgn' '-Wl,-U,_qd_DisposeRgn' '-Wl,-U,_qd_FrameRgn' '-Wl,-U,_qd_OpenRgn' '-Wl,-U,_qd_PaintRgn' '-Wl,-U,_jmenu_init' '-Wl,-U,_jmenu_command_setstate' '-Wl,-U,_jmenu_process' '-Wl,-U,_jmenu_command_enable' '-Wl,-U,_jmenu_command_getstate' '-Wl,-U,_jmenu_command_invert' '-Wl,-U,_jmenu_command_invalidate' '-Wl,-U,_jmenu_command_settext' '-Wl,-U,_jmenu_new' '-Wl,-U,_jmenu_addsubmenu' '-Wl,-U,_jmenu_addseparator' '-Wl,-U,_jmenu_appenditem' '-Wl,-U,_jmenu_interface_fromfile' '-Wl,-U,_jmenu_clearenums' '-Wl,-U,_jmenu_command_setid' '-Wl,-U,_jmenu_enumerate_getfile' '-Wl,-U,_jmenu_enumerate_path' '-Wl,-U,_jmenu_enumerate_data' '-Wl,-U,_jmenu_lookup' '-Wl,-U,_jcolor_getcolor' '-Wl,-U,_jcolor_linkcolor' '-Wl,-U,_jcommand_lookup' '-Wl,-U,_jmenu_update' '-Wl,-U,_jmenu_command_enableall_fortarget' '-Wl,-U,_jmenu_proxy_popup' '-Wl,-U,_jmonitor_getnumdisplays' '-Wl,-U,_jmonitor_getdisplayrect_foralldisplays' '-Wl,-U,_jmonitor_getdisplayrect' '-Wl,-U,_jmonitor_getdisplayrect_forpoint' '-Wl,-U,_jmonitor_getdisplayscalefactor' '-Wl,-U,_jmonitor_getdisplayscalefactor_forpoint' '-Wl,-U,_jmonitor_scale_pt' '-Wl,-U,_jmonitor_unscale_pt' '-Wl,-U,_jkeyboard_getcurrentmodifiers' '-Wl,-U,_jbox_notify' '-Wl,-U,_jgraphics_attr_setrgba' '-Wl,-U,_jgraphics_attr_getrgba' '-Wl,-U,_jgraphics_attr_setrgb_alias' '-Wl,-U,_jcolumn_setcheckbox' '-Wl,-U,_jcolumn_setvaluemsg' '-Wl,-U,_jcolumn_setrowcomponentmsg' '-Wl,-U,_jcolumn_setmaxwidth' '-Wl,-U,_jcolumn_setminwidth' '-Wl,-U,_jcolumn_setwidth' '-Wl,-U,_jcolumn_setlabel' '-Wl,-U,_jcolumn_sethideable' '-Wl,-U,_jcolumn_setvisible' '-Wl,-U,_jcolumn_getvisible' '-Wl,-U,_jcolumn_setinitiallysorted' '-Wl,-U,_jcolumn_setnumeric' '-Wl,-U,_jcolumn_setoverridesort' '-Wl,-U,_jcolumn_setcustomsort' '-Wl,-U,_jcolumn_getid' '-Wl,-U,_jcolumn_update' '-Wl,-U,_jcolumn_getname' '-Wl,-U,_jcolumn_getreference' '-Wl,-U,_jcolumn_setdraggable' '-Wl,-U,_jcolumn_setindentspacing' '-Wl,-U,_jcolumn_setreference' '-Wl,-U,_jcolumn_setsortable' '-Wl,-U,_jcolumn_setcustompaint' '-Wl,-U,_jcolumn_setcellcluemsg' '-Wl,-U,_jcolumn_setcelltextcolormsg' '-Wl,-U,_jcolumn_setcelltextstylemsg' '-Wl,-U,_jdataview_addcolumn' '-Wl,-U,_jdataview_addcolumn_hidden' '-Wl,-U,_jdataview_addrows' '-Wl,-U,_jdataview_addrow' '-Wl,-U,_jdataview_clear' '-Wl,-U,_jdataview_containersizechange' '-Wl,-U,_jdataview_deletecolumn' '-Wl,-U,_jdataview_deleterows' '-Wl,-U,_jdataview_deleterow' '-Wl,-U,_jdataview_editcell' '-Wl,-U,_jdataview_forcecellvisible' '-Wl,-U,_jdataview_getfontname' '-Wl,-U,_jdataview_getfontsize' '-Wl,-U,_jdataview_gethorizscrollvalues' '-Wl,-U,_jdataview_getnamedcolumn' '-Wl,-U,_jdataview_getnthcolumn' '-Wl,-U,_jdataview_getnumcolumns' '-Wl,-U,_jdataview_getnumrows' '-Wl,-U,_jdataview_getvertscrollvalues' '-Wl,-U,_jdataview_resort' '-Wl,-U,_jdataview_restorecolumnwidths' '-Wl,-U,_jdataview_savecolumnwidths' '-Wl,-U,_jdataview_setautosizeright' '-Wl,-U,_jdataview_setautosizebottom' '-Wl,-U,_jdataview_setautosizerightcolumn' '-Wl,-U,_jdataview_setbordercolor' '-Wl,-U,_jdataview_setborderthickness' '-Wl,-U,_jdataview_setcolumnheadercluemsg' '-Wl,-U,_jdataview_setcolumnheaderheight' '-Wl,-U,_jdataview_setcustomselectcolor' '-Wl,-U,_jdataview_setdragenabled' '-Wl,-U,_jdataview_setdrawgrid' '-Wl,-U,_jdataview_setfontname' '-Wl,-U,_jdataview_setfontsize' '-Wl,-U,_jdataview_setheight' '-Wl,-U,_jdataview_sethorizscrollvalues' '-Wl,-U,_jdataview_setkeyfocusable' '-Wl,-U,_jdataview_setscrollvisible' '-Wl,-U,_jdataview_setselectcolor' '-Wl,-U,_jdataview_setrowcolor2' '-Wl,-U,_jdataview_setrowcolor1' '-Wl,-U,_jdataview_setusegradient' '-Wl,-U,_jdataview_setusesystemfont' '-Wl,-U,_jdataview_setvertscrollvalues' '-Wl,-U,_jdataview_setclient' '-Wl,-U,_jdataview_new' '-Wl,-U,_jdataview_newsection' '-Wl,-U,_jdataview_numsections' '-Wl,-U,_jdataview_getnthsection' '-Wl,-U,_jdataview_section_getnumrows' '-Wl,-U,_jdataview_section_getallrows' '-Wl,-U,_jdataview_section_isopen' '-Wl,-U,_jdataview_section_setopen' '-Wl,-U,_jdataview_getsectionopenness' '-Wl,-U,_jdataview_setsectionopenness' '-Wl,-U,_jdataview_section_headervisible' '-Wl,-U,_jdataview_section_setheadervisible' '-Wl,-U,_jdataview_section_getname' '-Wl,-U,_jdataview_section_geticon' '-Wl,-U,_jdataview_scrolltosection' '-Wl,-U,_jdataview_scrolltotop' '-Wl,-U,_jdataview_addrowtosection' '-Wl,-U,_jdataview_addrowstosection' '-Wl,-U,_jdataview_deleterowfromsection' '-Wl,-U,_jdataview_deleterowsfromsection' '-Wl,-U,_jdataview_deleteselectedrows' '-Wl,-U,_jdataview_deleteselectedrowsforview' '-Wl,-U,_jdataview_gettextinrows' '-Wl,-U,_jdataview_iscelltextselected' '-Wl,-U,_jdataview_selectedrowcountforview' '-Wl,-U,_jdataview_selectedrowcount' '-Wl,-U,_jdataview_getselectedrowsforview' '-Wl,-U,_jdataview_applytoselectedrows' '-Wl,-U,_jdataview_applytorows' '-Wl,-U,_jdataview_cellcut' '-Wl,-U,_jdataview_cellcopy' '-Wl,-U,_jdataview_cellpaste' '-Wl,-U,_jdataview_setcancopy' '-Wl,-U,_jdataview_getcancopy' '-Wl,-U,_jdataview_setcanpaste' '-Wl,-U,_jdataview_getcanpaste' '-Wl,-U,_jdataview_getsortcolumn' '-Wl,-U,_jdataview_sortcolumn' '-Wl,-U,_jdataview_redrawcolumn' '-Wl,-U,_jdataview_repaintforview' '-Wl,-U,_jdataview_obscuring' '-Wl,-U,_jdataview_id2colname' '-Wl,-U,_jdataview_colname2id' '-Wl,-U,_jdataview_enablecell' '-Wl,-U,_jdataview_enablerow' '-Wl,-U,_jdataview_colname_setvisible' '-Wl,-U,_jdataview_colname_getvisible' '-Wl,-U,_jdataview_colname_delete' '-Wl,-U,_jdataview_patchervis' '-Wl,-U,_jdataview_patcherinvis' '-Wl,-U,_jdataview_showrow' '-Wl,-U,_jdataview_redrawcell' '-Wl,-U,_jdataview_redrawrow' '-Wl,-U,_jdataview_row2id' '-Wl,-U,_jdataview_selectcell' '-Wl,-U,_jdataview_selectcellinview' '-Wl,-U,_jdataview_sort' '-Wl,-U,_jdataview_setusecharheightfont' '-Wl,-U,_jdialog_showtext' '-Wl,-U,_jdialog_show2button_async' '-Wl,-U,_jdialog_cancel_async' '-Wl,-U,_newobject_sprintf' '-Wl,-U,_itm_initclass' '-Wl,-U,_itm_new' '-Wl,-U,_itm_getglobal' '-Wl,-U,_itm_getnamed' '-Wl,-U,_itm_clocksource_getnamed' '-Wl,-U,_itm_getclocksources' '-Wl,-U,_itmclock_new' '-Wl,-U,_itm_poke' '-Wl,-U,_itm_gettime' '-Wl,-U,_itm_getticks' '-Wl,-U,_itmclock_delay' '-Wl,-U,_itmclock_set' '-Wl,-U,_itmclock_unset' '-Wl,-U,_itm_sync' '-Wl,-U,_itm_settimesignature' '-Wl,-U,_itm_seek' '-Wl,-U,_itm_pause' '-Wl,-U,_itm_resume' '-Wl,-U,_itm_setresolution' '-Wl,-U,_itm_reference' '-Wl,-U,_itm_dereference' '-Wl,-U,_itm_tickstobarbeatunits_timesig' '-Wl,-U,_itm_barbeatunitstoticks_timesig' '-Wl,-U,_itm_barbeatunitstoticks' '-Wl,-U,_itm_tickstobarbeatunits' '-Wl,-U,_itm_nextbeat' '-Wl,-U,_itm_nextunit' '-Wl,-U,_itm_parse' '-Wl,-U,_itm_deleteeventlist' '-Wl,-U,_itm_geteventlistnames' '-Wl,-U,_itm_switcheventlist' '-Wl,-U,_itm_gettimesignature' '-Wl,-U,_itm_getstate' '-Wl,-U,_itm_getresolution' '-Wl,-U,_itm_dump' '-Wl,-U,_itm_getfromarg' '-Wl,-U,_itm_getglobal' '-Wl,-U,_itm_getnamed' '-Wl,-U,_itm_getfromarg' '-Wl,-U,_itm_reference' '-Wl,-U,_itm_dereference' '-Wl,-U,_itm_deleteeventlist' '-Wl,-U,_itm_eventlistseek' '-Wl,-U,_itm_geteventlistnames' '-Wl,-U,_itm_switcheventlist' '-Wl,-U,_itm_gettime' '-Wl,-U,_itm_getticks' '-Wl,-U,_itm_dump' '-Wl,-U,_itm_sync' '-Wl,-U,_itm_settimesignature' '-Wl,-U,_itm_gettimesignature' '-Wl,-U,_itm_seek' '-Wl,-U,_itm_pause' '-Wl,-U,_itm_resume' '-Wl,-U,_itm_getstate' '-Wl,-U,_itm_setresolution' '-Wl,-U,_itm_getresolution' '-Wl,-U,_itm_getname' '-Wl,-U,_itm_parse' '-Wl,-U,_itm_tickstoms' '-Wl,-U,_itm_mstoticks' '-Wl,-U,_itm_mstosamps' '-Wl,-U,_itm_sampstoms' '-Wl,-U,_itm_barbeatunitstoticks' '-Wl,-U,_itm_tickstobarbeatunits' '-Wl,-U,_itm_format' '-Wl,-U,_itm_isunitfixed' '-Wl,-U,_itm_gettempo' '-Wl,-U,_itm_getsr' '-Wl,-U,_itmclock_new' '-Wl,-U,_itmclock_delay' '-Wl,-U,_itmclock_set' '-Wl,-U,_itmclock_unset' '-Wl,-U,_patcher_removedefault' '-Wl,-U,_patcher_setdefault' '-Wl,-U,_patcher_getdefault' '-Wl,-U,_patcher_removedefault' '-Wl,-U,_patcher_setdefault' '-Wl,-U,_patcher_boxname' '-Wl,-U,_atom_alloc_array' '-Wl,-U,_atomarray_decodebinarydata' '-Wl,-U,_jgraphics_write_image_surface_to_filedata' '-Wl,-U,_binarydata_appendtodictionary' '-Wl,-U,_patcherview_findpatcherview' '-Wl,-U,_jpatcher_resolvepatcher' '-Wl,-U,_jpatcher_resolvebox' '-Wl,-U,_jpatcher_resolvebox_ex' '-Wl,-U,_jpatcher_resolveobj' '-Wl,-U,_jpatcher_resolvebox_boxpath' '-Wl,-U,_jpatcher_resolveobj_boxpath' '-Wl,-U,_jwind_canfullscreen' '-Wl,-U,_jwind_getactive' '-Wl,-U,_jwind_getcount' '-Wl,-U,_jwind_getat' '-Wl,-U,_jwind_nextuntitled' '-Wl,-U,_jgraphics_rectangle_fill_fast' '-Wl,-U,_jgraphics_rectangle_draw_fast' '-Wl,-U,_jgraphics_line_draw_fast' '-Wl,-U,_atomarray_new' '-Wl,-U,_atomarray_flags' '-Wl,-U,_atomarray_getflags' '-Wl,-U,_atomarray_setatoms' '-Wl,-U,_atomarray_getatoms' '-Wl,-U,_atomarray_copyatoms' '-Wl,-U,_atomarray_getsize' '-Wl,-U,_atomarray_getindex' '-Wl,-U,_atomarray_duplicate' '-Wl,-U,_atomarray_clone' '-Wl,-U,_atomarray_clone_to_existing' '-Wl,-U,_atomarray_setatoms_clone' '-Wl,-U,_atomarray_appendatom' '-Wl,-U,_atomarray_appendatoms' '-Wl,-U,_atomarray_chuckindex' '-Wl,-U,_atomarray_clear' '-Wl,-U,_atomarray_funall' '-Wl,-U,_atomarray_dispose' '-Wl,-U,_atomarray_insertatom_atindex' '-Wl,-U,_atomarray_prependatom' '-Wl,-U,_atomarray_prependatoms' '-Wl,-U,_common_symbols_gettable' '-Wl,-U,_object_obex_storeflags' '-Wl,-U,_object_obex_enforce' '-Wl,-U,_object_attr_getjrgba' '-Wl,-U,_object_attr_setjrgba' '-Wl,-U,_jrgba_to_atoms' '-Wl,-U,_atoms_to_jrgba' '-Wl,-U,_jrgba_set' '-Wl,-U,_jrgba_copy' '-Wl,-U,_jrgba_compare' '-Wl,-U,_jrgba_attr_set' '-Wl,-U,_class_parameter_init' '-Wl,-U,_class_parameter_mappable' '-Wl,-U,_class_parameter_setinfo' '-Wl,-U,_class_parameter_getinfo' '-Wl,-U,_class_parameter_register_default_color' '-Wl,-U,_object_parameter_init' '-Wl,-U,_object_parameter_init_flags' '-Wl,-U,_object_parameter_dictionary_process' '-Wl,-U,_object_parameter_hasminmax_true' '-Wl,-U,_object_parameter_hasminmax_false' '-Wl,-U,_class_parameter_addmethod' '-Wl,-U,_parameter_default_int' '-Wl,-U,_parameter_default_float' '-Wl,-U,_parameter_default_anything' '-Wl,-U,_object_parameter_free' '-Wl,-U,_object_parameter_notify' '-Wl,-U,_object_parameter_getinfo' '-Wl,-U,_object_parameter_setinfo' '-Wl,-U,_object_parameter_string_get' '-Wl,-U,_object_parameter_stringtovalue' '-Wl,-U,_object_parameter_value_set' '-Wl,-U,_object_parameter_value_get' '-Wl,-U,_object_parameter_color_get' '-Wl,-U,_object_parameter_value_getvalueof' '-Wl,-U,_object_parameter_value_setvalueof' '-Wl,-U,_object_parameter_value_setvalueof_nonotify' '-Wl,-U,_object_parameter_value_changed' '-Wl,-U,_object_parameter_value_changed_nonotify' '-Wl,-U,_object_parameter_current_to_initial' '-Wl,-U,_object_parameter_is_initialized' '-Wl,-U,_object_parameter_is_in_Live' '-Wl,-U,_object_parameter_is_automated' '-Wl,-U,_object_parameter_wants_focus' '-Wl,-U,_object_parameter_is_parameter' '-Wl,-U,_object_parameter_get_order' '-Wl,-U,_object_parameter_is_in_maxtilde' '-Wl,-U,_object_parameter_getenable_savestate' '-Wl,-U,_live_default_color_count' '-Wl,-U,_live_default_color_string' '-Wl,-U,_live_default_dynamic_color_string' '-Wl,-U,_live_default_color_symbol' '-Wl,-U,_live_default_color_rgbastring' '-Wl,-U,_live_default_color_rgba' '-Wl,-U,_live_default_color_rgba_from_symbol' '-Wl,-U,_param_global_initializecolors' '-Wl,-U,_project_newfromdevicepatcher' '-Wl,-U,_remote_object_new_typed' '-Wl,-U,_remote_object_new_typed_flags' '-Wl,-U,_remote_object_get' '-Wl,-U,_remote_object_get_flags' '-Wl,-U,_remote_object_method_typed' '-Wl,-U,_remote_object_method_typed_flags' '-Wl,-U,_remote_object_attr_setvalueof' '-Wl,-U,_remote_object_attr_setvalueof_flags' '-Wl,-U,_remote_object_attr_getvalueof' '-Wl,-U,_remote_object_attr_getvalueof_flags' '-Wl,-U,_maxserver_getremoteurl' '-Wl,-U,_maxserver_getcontent' '-Wl,-U,_sysshmem_alloc' '-Wl,-U,_sysshmem_open' '-Wl,-U,_sysshmem_close' '-Wl,-U,_sysshmem_getsize' '-Wl,-U,_sysshmem_getptr' '-Wl,-U,_syssem_create' '-Wl,-U,_syssem_open' '-Wl,-U,_syssem_close' '-Wl,-U,_syssem_wait' '-Wl,-U,_syssem_trywait' '-Wl,-U,_syssem_post' '-Wl,-U,_sysprocess_isrunning' '-Wl,-U,_sysprocess_isrunning_with_returnvalue' '-Wl,-U,_sysprocess_kill' '-Wl,-U,_sysprocess_launch' '-Wl,-U,_sysprocess_launch_withflags' '-Wl,-U,_sysprocess_activate' '-Wl,-U,_sysprocess_getid' '-Wl,-U,_sysprocess_getcurrentid' '-Wl,-U,_sysprocess_getpath' '-Wl,-U,_sysprocesswatcher_new' '-Wl,-U,_sysprocess_fitsarch' '-Wl,-U,_object_retain' '-Wl,-U,_object_release' '-Wl,-U,_multigraph_add' '-Wl,-U,_multigraph_remove' '-Wl,-U,_multinode_resizeio' '-Wl,-U,_multinode_hasdescendant' '-Wl,-U,_multigraph_connect' '-Wl,-U,_multigraph_connect_relaxed' '-Wl,-U,_multigraph_disconnect' '-Wl,-U,_multigraph_disconnectnode' '-Wl,-U,_multigraph_dependency_chain' '-Wl,-U,_multigraph_new' '-Wl,-U,_multinode_new' '-Wl,-U,_multinode_connect' '-Wl,-U,_multinode_disconnect' '-Wl,-U,_multinode_iterfun' '-Wl,-U,_multinode_dependency_chain' '-Wl,-U,_multiedge_disconnect' '-Wl,-U,_multiedge_new' '-Wl,-U,_multigraph_scheduler_new' '-Wl,-U,_multigraph_scheduler_acquire' '-Wl,-U,_multigraph_scheduler_release' '-Wl,-U,_multigraph_scheduler_complete' '-Wl,-U,_multigraph_parallel_iterator_new' '-Wl,-U,_multigraph_parallel_iterator_free' '-Wl,-U,_multigraph_parallel_iterator_scheduler' '-Wl,-U,_multigraph_parallel_iterator_data' '-Wl,-U,_multigraph_parallel_iterator_execute' '-Wl,-U,_multigraph_parallel_iterator_workerproc' '-Wl,-U,_jpatcher_bulk_load_begin' '-Wl,-U,_jpatcher_bulk_load_end' '-Wl,-U,_jpatcher_load' '-Wl,-U,_jpatcher_load_frombuffer' '-Wl,-U,_jpatcher_load_fromdictionary' '-Wl,-U,_jpatcher_load_namespace' '-Wl,-U,_jpatcher_load_frombuffer_namespace' '-Wl,-U,_jpatcher_load_fromdictionary_namespace' '-Wl,-U,_jdesktopui_new' '-Wl,-U,_jdesktopui_destroy' '-Wl,-U,_jdesktopui_setvisible' '-Wl,-U,_jdesktopui_setalwaysontop' '-Wl,-U,_jdesktopui_setrect' '-Wl,-U,_jdesktopui_getrect' '-Wl,-U,_jdesktopui_setposition' '-Wl,-U,_jdesktopui_setfadetimes' '-Wl,-U,_jdesktopui_get_jgraphics' '-Wl,-U,_jdesktopui_redraw' '-Wl,-U,_jdesktopui_redrawrect' '-Wl,-U,_object_subscribe' '-Wl,-U,_object_unsubscribe' '-Wl,-U,_sysparallel_task_workercount' '-Wl,-U,_backgroundtask_execute' '-Wl,-U,_backgroundtask_execute_method' '-Wl,-U,_backgroundtask_purge_object' '-Wl,-U,_backgroundtask_join_object' '-Wl,-U,_backgroundtask_cancel' '-Wl,-U,_backgroundtask_join' '-Wl,-U,_jgraphics_image_surface_create_for_data_premult' '-Wl,-U,_jgraphics_create_zoomed' '-Wl,-U,_jgraphics_get_target' '-Wl,-U,_jgraphics_pop_group' '-Wl,-U,_jgraphics_get_group_target' '-Wl,-U,_jgraphics_pop_group_surface' '-Wl,-U,_syntax_addtoken' '-Wl,-U,_object_register_getnames' '-Wl,-U,_dictionary_clone_to_existing' '-Wl,-U,_dictionary_clone' '-Wl,-U,_dictionary_merge_to_existing' '-Wl,-U,_dictionary_copy_nonunique_to_existing' '-Wl,-U,_patcherdomain_namespace_init' '-Wl,-U,_patcherdomain_node_new' '-Wl,-U,_patcherdomain_node_free' '-Wl,-U,_patcherdomain_makeinlets' '-Wl,-U,_patcherdomain_makeoutlets' '-Wl,-U,_patcherdomain_inlets_resize' '-Wl,-U,_patcherdomain_outlets_resize' '-Wl,-U,_patcherdomain_freeinlets' '-Wl,-U,_patcherdomain_freeoutlets' '-Wl,-U,_patcherdomain_class_register' '-Wl,-U,_patcherdomain_simple_connectionaccept' '-Wl,-U,_patcherdomain_simple_patchlineupdate' '-Wl,-U,_inlet_delete' '-Wl,-U,_outlet_delete' '-Wl,-U,_proxy_append' '-Wl,-U,_proxy_insert' '-Wl,-U,_proxy_new_forinlet' '-Wl,-U,_proxy_delete' '-Wl,-U,_proxy_setinletptr' '-Wl,-U,_proxy_getinletptr' '-Wl,-U,_jgraphics_bubble' '-Wl,-U,_class_subclass' '-Wl,-U,_class_super_construct' '-Wl,-U,_class_super_construct_imp' '-Wl,-U,_object_super_method' '-Wl,-U,_object_super_method_imp' '-Wl,-U,_object_this_method' '-Wl,-U,_object_this_method_imp' '-Wl,-U,_object_obex_chuck' '-Wl,-U,_object_attr_touch' '-Wl,-U,_object_attr_touch_parse' '-Wl,-U,_object_method_direct_getmethod' '-Wl,-U,_object_method_direct_getobject' '-Wl,-U,_object_super_getmethod' '-Wl,-U,_object_typedwrapper_get' '-Wl,-U,_usergesture_begin' '-Wl,-U,_usergesture_end' '-Wl,-U,_usergesture_add_live_undo_subscriber' '-Wl,-U,_db_open' '-Wl,-U,_db_close' '-Wl,-U,_db_query' '-Wl,-U,_db_query_direct' '-Wl,-U,_db_query_silent' '-Wl,-U,_db_query_getlastinsertid' '-Wl,-U,_db_query_table_new' '-Wl,-U,_db_query_table_addcolumn' '-Wl,-U,_db_transaction_start' '-Wl,-U,_db_transaction_end' '-Wl,-U,_db_transaction_flush' '-Wl,-U,_db_view_create' '-Wl,-U,_db_view_remove' '-Wl,-U,_db_view_getresult' '-Wl,-U,_db_view_setquery' '-Wl,-U,_db_result_nextrecord' '-Wl,-U,_db_result_reset' '-Wl,-U,_db_result_clear' '-Wl,-U,_db_result_numrecords' '-Wl,-U,_db_result_numfields' '-Wl,-U,_db_result_fieldname' '-Wl,-U,_db_result_string' '-Wl,-U,_db_result_long' '-Wl,-U,_db_result_float' '-Wl,-U,_db_result_datetimeinseconds' '-Wl,-U,_db_util_stringtodate' '-Wl,-U,_db_util_datetostring' '-Wl,-U,_eventcontext_begin' '-Wl,-U,_eventcontext_end' '-Wl,-U,_eventcontext_get' '-Wl,-U,_eventcontext_set' '-Wl,-U,_collectionlist_read' '-Wl,-U,_collection_updatefromdictionary' '-Wl,-U,_collection_deletenamed' '-Wl,-U,_collection_renamenamed' '-Wl,-U,_collection_getallnames' '-Wl,-U,_schedule_queue_new' '-Wl,-U,_schedule_queue' '-Wl,-U,_lockfreequeue_free' '-Wl,-U,_lockfreequeue_new' '-Wl,-U,_lockfreequeue_pop' '-Wl,-U,_lockfreequeue_push' '-Wl,-U,_lockfreequeue_isempty' '-Wl,-U,_class_attr_setstyle' '-Wl,-U,_class_attr_style_alias' '-Wl,-U,_class_attr_setfill' '-Wl,-U,_class_addstyleattr' '-Wl,-U,_style_getmenu' '-Wl,-U,_style_handlemenu' '-Wl,-U,_dynamiccolor_getmenu' '-Wl,-U,_dynamiccolor_handlemenu' '-Wl,-U,_object_attr_getinherited' '-Wl,-U,_object_attr_setinherited' '-Wl,-U,_object_style_setfillattribute' '-Wl,-U,_class_attr_stylemap' '-Wl,-U,_object_attr_attrname_forstylemap' '-Wl,-U,_object_attr_stylemapname' '-Wl,-U,_jgraphics_triangle' '-Wl,-U,_jgraphics_jrgba_set_brightness' '-Wl,-U,_jpopupmenu_setstandardstyle' '-Wl,-U,_jgraphics_attr_setfill' '-Wl,-U,_jgraphics_attr_setfill_transformed' '-Wl,-U,_jgraphics_attr_fillrect' '-Wl,-U,_object_attr_getfillcolor_atposition' '-Wl,-U,_object_attr_getfill' '-Wl,-U,_jsvg_remap_create' '-Wl,-U,_jsvg_remap_destroy' '-Wl,-U,_jsvg_remap_addcolor' '-Wl,-U,_jsvg_remap_addsinglecolor' '-Wl,-U,_jsvg_remap_perform' '-Wl,-U,_jsvg_load_cached' '-Wl,-U,_jgraphics_draw_jsvg' '-Wl,-U,_objectcollection_addobject' '-Wl,-U,_objectcollection_addtext' '-Wl,-U,_ctopcpy' '-Wl,-U,_ptoccpy' '-Wl,-U,_pstrcpy' '-Wl,-U,_plug_getoptions' '-Wl,-U,_path_fromfsref' '-Wl,-U,_path_tofsref' '-Wl,-U,_fontinfo_prefcheckencoding' '-Wl,-U,_fontinfo_getencoding' '-Wl,-U,_fontinfo_reconverthandle' '-Wl,-U,_fontinfo_convert' '-Wl,-U,_rescopy' '-Wl,-U,_max_debug_is_debugger_attached' '-Wl,-U,_unibrowser_search_dosearch' '-Wl,-U,_unibrowser_search_autocomplete_dosearch' '-Wl,-U,_unibrowser_search_collection_getall' '-Wl,-U,_unibrowser_search_snippets_dosearch' '-Wl,-U,_unibrowser_search_getsnippetdictionary' '-Wl,-U,_snapshotwriter_addpayload' '-Wl,-U,_snapshotwriter_addlist' '-Wl,-U,_snapshotreader_from_dictionary' '-Wl,-U,_snapshotreader_from_userpath' '-Wl,-U,_snapshotreader_fitstype' '-Wl,-U,_snapshotreader_getpayload' '-Wl,-U,_snapshotreader_getlist' '-Wl,-U,_snapshotreader_haspayload' '-Wl,-U,_snapshotreader_haslist' '-Wl,-U,_snapshotreader_getname' '-Wl,-U,_snapshotreader_getorigin' '-Wl,-U,_snapshotlist_setup' '-Wl,-U,_snapshotlist_will_restore' '-Wl,-U,_snapshotlist_initial_restore' '-Wl,-U,_snapshotlist_momentary_snapshot' '-Wl,-U,_snapshotlist_devalidate_snapshot' '-Wl,-U,_snapshotlist_forceupdatefilesnapshots' '-Wl,-U,_snapshotlist_appendtodictionary' '-Wl,-U,_snapshotlist_getvalueof' '-Wl,-U,_snapshotlist_setvalueof' '-Wl,-U,_snapshotlist_fileusage' '-Wl,-U,_object_attr_obsolete_getter' '-Wl,-U,_object_attr_obsolete_setter' '-Wl,-U,_object_method_obsolete' '-Wl,-U,_updatepath_pathhaschanged' '-Wl,-U,_sysinfo_getosversion' '-Wl,-U,_object_attr_lock' '-Wl,-U,_object_attr_unlock' '-Wl,-U,_dictionary_transaction_lock' '-Wl,-U,_dictionary_transaction_unlock' '-Wl,-U,_charset_urlencode' '-Wl,-U,_jpatcher_setnextobexprototype' '-Wl,-U,_jpatcher_getnextobexprototype' '-Wl,-U,_sysinfo_gestalt_get_sysv' '-Wl,-U,_sysinfo_gestalt_get_sysvers' '-Wl,-U,_sysinfo_gestalt_get_systemversion' '-Wl,-U,_sysinfo_gestalt_get_pid' '-Wl,-U,_sysinfo_gestalt_get_processname' '-Wl,-U,_sysinfo_gestalt_get_processorcount' '-Wl,-U,_sysinfo_gestalt_get_physicalmemory' '-Wl,-U,_sysinfo_gestalt_get_hostname' '-Wl,-U,_sysinfo_gestalt_get_arguments' '-Wl,-U,_sysinfo_gestalt_get_environment' '-Wl,-U,_sysinfo_getappname' '-Wl,-U,_sysinfo_getarchitecture' '-Wl,-U,_jgraphics_path_getpointalongpath' '-Wl,-U,_jgraphics_path_getnearestpoint' '-Wl,-U,_jgraphics_path_getlength' '-Wl,-U,_class_attr_dynamiccolor_init' '-Wl,-U,_object_attr_dynamiccolor_supported' '-Wl,-U,_object_attr_dynamiccolor_setsym_setup' '-Wl,-U,_object_attr_dynamiccolor_getname' '-Wl,-U,_object_attr_dynamiccolor_setname' '-Wl,-U,_object_attr_dynamiccolor_geton' '-Wl,-U,_object_attr_dynamiccolor_seton' '-Wl,-U,_object_attr_dynamiccolor_getregular' '-Wl,-U,_object_attr_dynamiccolor_setregular' '-Wl,-U,_object_attr_dynamiccolor_getregularrgba' '-Wl,-U,_object_attr_dynamiccolor_setregularrgba' '-Wl,-U,_object_attr_dynamiccolor_gethumanname' '-Wl,-U,_object_attr_dynamiccolor_apply' '-Wl,-U,_filetypelist_file_matches' '-Wl,-U,_filetypelist_gettypes' '-Wl,-U,_filetypelist_addtypes' '-Wl,-U,_filetypelist_gettypesym' '-Wl,-U,_filetypelist_to_types_and_suffixes' '-Wl,-U,_filetypelist_from_types_and_suffixes' '-Wl,-U,_filetypelist_from_types' '-Wl,-U,_types_and_suffixes_setup' '-Wl,-U,_types_and_suffixes_cleanup' '-Wl,-U,_types_and_suffixes_free' '-Wl,-U,_fuzzy_floatcmp' '-Wl,-U,_copyatoms' '-Wl,-U,_cloneatoms'
================================================
FILE: install/mkl.cmake
================================================
find_package(MKL QUIET)
if(NOT TARGET caffe2::mkl)
add_library(caffe2::mkl INTERFACE IMPORTED)
endif()
target_include_directories(caffe2::mkl INTERFACE ${MKL_INCLUDE_DIR})
#target_link_libraries(caffe2::mkl INTERFACE ${MKL_LIBRARIES})
foreach(MKL_LIB IN LISTS MKL_LIBRARIES)
if(EXISTS "${MKL_LIB}")
get_filename_component(MKL_LINK_DIR "${MKL_LIB}" DIRECTORY)
if(IS_DIRECTORY "${MKL_LINK_DIR}")
target_link_directories(caffe2::mkl INTERFACE "${MKL_LINK_DIR}")
endif()
endif()
endforeach()
# TODO: This is a hack, it will not pick up architecture dependent
# MKL libraries correctly; see https://github.com/pytorch/pytorch/issues/73008
set_property(
TARGET caffe2::mkl PROPERTY INTERFACE_LINK_DIRECTORIES
${MKL_ROOT}/lib ${MKL_ROOT}/lib/intel64 ${MKL_ROOT}/lib/intel64_win ${MKL_ROOT}/lib/win-x64)
================================================
FILE: install/patch_with_vst.sh
================================================
#!/bin/bash
# Default values
pd=0
max=0
function print_help() {
echo "Usage: $0 [--pd_path[=val]] (default: ~/Documents/Pd) [--max[=val]] (by default, look in all ~/Documents/Max X/ ; if specified, look for externals sub-folder)"
}
# Parse arguments
while [[ $# -gt 0 ]]; do
case "$1" in
--pd=*)
pd=1
pd_path="${1#*=}"
shift
;;
--pd)
pd=1
shift
;;
--max=*)
max=1
max_path="${1#*=}"
shift
;;
--max)
max=1
shift
;;
--help|-h)
print_help
exit 0
;;
*)
echo "Unknown option: $1"
shift
;;
esac
done
function patch_max_external() {
find "$1" -name "nn_tilde" -type d -mindepth 2 -print0 | while IFS= read -r -d '' ext_dir; do
if [[ -d "$ext_dir/externals" ]]; then
echo "found nn_tilde at $ext_dir";
find "$ext_dir/externals" -name "*.mxo" -print0 | while IFS= read -r -d '' ext_path; do
# echo "found external at $ext_path";
ext_name=$(basename "$ext_path")
find "$ext_dir/support" -name "*.dylib" -print0 | while IFS= read -r -d '' dylib_path; do
dylib_name=$(basename "$dylib_path")
echo "fixing library : $dylib_name"
new_path="/Library/Application Support/ACIDS/RAVE/$dylib_name"
if [[ ! -e "$new_path" ]]; then
echo "[WARNING] library not found : $new_path. Patch may not work"
fi
install_name_tool -change "@loader_path/../../../../support/$dylib_name" "/Library/Application Support/ACIDS/RAVE/$dylib_name" "${ext_path}/Contents/MacOS/${ext_name%.*}" 2> /dev/null
done
codesign --deep --force --sign - "${ext_path}/Contents/MacOS/${ext_name%.*}"
done
fi
done
}
function patch_pd_external() {
ext_dir=$1
if [[ ! "$(basename $ext_dir)" == "nn_tilde" ]]; then
ext_dir="${ext_dir}/externals/nn_tilde"
fi
if [[ -e $(realpath $ext_dir) ]]; then
find "$ext_dir" -name "nn~.pd_*" -print0 | while IFS= read -r -d '' ext_path; do
ext_name=$(basename "$ext_path")
find "$ext_dir" -name "*.dylib" -print0 | while IFS= read -r -d '' dylib_path; do
dylib_name=$(basename "$dylib_path")
echo "fixing library : $dylib_name"
new_path="/Library/Application Support/ACIDS/RAVE/$dylib_name"
if [[ ! -e "$new_path" ]]; then
echo "[WARNING] library not found : $new_path. Patch may not work"
fi
echo install_name_tool -change "@rpath/$dylib_name" "/Library/Application Support/ACIDS/RAVE/$dylib_name" "${ext_path}" 2> /dev/null
done
codesign --deep --force --sign - "${ext_path}"
done
else
echo "folder $ext_dir not found".
fi
}
if [[ "$max" -eq 1 ]]; then
if [[ -n "$max_path" ]]; then
patch_max_external "$max_path"
else
find ~/Documents -maxdepth 1 -name "Max *" -type d -print0 | while IFS= read -r -d '' max_dir; do
if [[ -d $max_dir ]]; then
patch_max_external "$max_dir"
else
echo "$max_dir does not exists"
fi
done
fi
fi
if [[ "$pd" -eq 1 ]]; then
if [[ -n "$max_path" ]]; then
patch_pd_external "$pd_path"
else
patch_pd_external "$HOME/Documents/Pd"
fi
fi
================================================
FILE: package-info.json.in
================================================
{
"name" : "nn_tilde",
"displayname" : "nn~",
"version" : "${VERSION}",
"author" : "ACIDS",
"authors" : [ "Antoine Caillon", "Axel Chemla--Romeu-Santos", "Philippe Esling", "Nils Demerlé"],
"description" : "Max interfaces for deep neural generation",
"tags" : [ "audio", "ai", "neural synthesis"],
"website" : "http://www.github.com/acids-ircam/nn_tilde",
"extends" : "",
"extensible" : 1,
"max_version_min" : "8.0.2",
"max_version_max" : "none",
"os" : {
"macintosh" : {
"min_version" : "10.12.x",
"platform" : [ "x64", "aarch64" ]
}
,
"windows" : {
"min_version" : "7",
"platform" : [ "x64" ]
}
}
,
"homepatcher" : "help_hub.maxpat",
"package_extra" : {
}
,
"c74install" : 1,
"installdate" : 3745215604
}
================================================
FILE: python_tools/__init__.py
================================================
import pathlib
import torch
TMP_FILE_OUTPUT = pathlib.Path(__file__).parent / ".tmpfile"
from .buffer import Buffer
TYPE_HASH = {bool: 0, int: 1, float: 2, str: 3, torch.Tensor: 4, Buffer: 5}
from . import templates
from .module import Module
================================================
FILE: python_tools/buffer.py
================================================
import torch
from typing import List, Dict, Optional
class Buffer():
value: torch.Tensor
min_samples: int
max_samples: int
def __init__(self, tensor: Optional[torch.Tensor] = None,
min_samples: int = -1,
max_samples: int = -1,
sr: int | float | None = -1):
self.value = torch.tensor(0)
self.init_value()
if tensor is not None:
self.value = tensor
self.min_samples = min_samples
self.max_samples = max_samples
self.sr = -1 if sr is None else int(sr)
def check_bounds(self, x: torch.Tensor) -> bool:
is_ok = True
if self.min_samples != -1:
is_ok = is_ok and x.shape[-1] >= self.min_samples
if self.max_samples != -1:
is_ok = is_ok and x.shape[-1] <= self.max_samples
return is_ok
def from_buffer(self, buffer: "Buffer"):
return self.set_value(buffer.value, sr = buffer.sr)
@staticmethod
def copy(buffer: "Buffer"):
buffer_n = Buffer()
buffer_n.from_buffer(buffer)
return buffer_n
def set_value(self, x: torch.Tensor, sr: int | float | None = None) -> int:
_has_valid_bounds = self.check_bounds(x)
if not _has_valid_bounds:
return -1
if sr is None:
self.sr = -1
else:
self.sr = int(sr)
self.value = x.clone()
return 0
@property
def shape(self) -> List[int]:
if self.has_value:
return self.value.shape
else:
return torch.Size([])
@property
def has_value(self) -> bool:
return self.value.numel() != 0
def get_value(self) -> torch.Tensor:
return self.value
def init_value(self) -> None:
self.value = torch.zeros(0, 0, 0)
def to_str(self) -> str:
if self.has_value:
out = f"Buffer(min={self.value.min()}, max={self.value.max()}, sr={self.sr}, shape={self.shape})"
else:
out = "Buffer(empty)"
return out
BUFFER_ATTRIBUTES_TYPE = Dict[str, Buffer]
================================================
FILE: python_tools/codegen.py
================================================
import os
import shutil
import uuid
from . import TMP_FILE_OUTPUT
class TmpFileSession(object):
def __init__(self, obj):
self._path = (TMP_FILE_OUTPUT / f"{id(obj)}").resolve()
def get(self):
if not self._path.exists():
os.makedirs(self._path)
unique_id = str(uuid.uuid4())
return self._path / f"{unique_id}.py"
def close(self):
if len(os.listdir(TMP_FILE_OUTPUT)) == 0:
shutil.rmtree(TMP_FILE_OUTPUT, True)
else:
shutil.rmtree(self._path, True)
def tmp_file_session(obj):
return TmpFileSession(obj)
def method_from_template(file_session: TmpFileSession, template: str, gl = {}, lo = {}):
target_path = file_session.get()
with open(target_path, 'w+') as f:
f.write(template)
code_compiled = compile(template, target_path, 'exec')
exec(code_compiled, gl, lo)
return lo
================================================
FILE: python_tools/module.py
================================================
import inspect
import logging
from typing import Any, List, Optional, Sequence, Tuple, Union
from types import MethodType
import cached_conv as cc
import torch
from . import TYPE_HASH
from .buffer import Buffer, BUFFER_ATTRIBUTES_TYPE
from . import templates
from .codegen import *
class Module(torch.nn.Module):
__reserved_attribute_names__ = ['sr']
def __init__(self, sr: int | None = None) -> None:
super().__init__()
self._methods = []
self._attributes = torch.jit.Attribute([], List[str])
self._buffer_attributes = torch.jit.Attribute([], List[str])
self.tmp_file_session = tmp_file_session(self)
self._ready = False
self.sr = torch.jit.Attribute(sr, int | None)
def register_method(
self,
method_name: str,
in_channels: int,
in_ratio: int,
out_channels: int,
out_ratio: int,
input_labels: Optional[Sequence[str]] = None,
output_labels: Optional[Sequence[str]] = None,
test_method: bool = True,
test_buffer_size: int = 8192,
):
"""Register a class method as usable by nn~.
The method must take as input and return a single 3D tensor.
Args:
method_name: name of the method to register
in_channels: number of channels of the input tensor
in_ratio: temporal compression ratio of the input tensor
in_channels: number of channels of the output tensor
in_ratio: temporal compression ratio of the output tensor
input_labels: labels used by max for the inlets
output_labels: labels used by max for the outlets
test_method: weither the method is tested during registration or not
test_buffer_size: duration of the test buffer
"""
logging.info(f'Registering method "{method_name}"')
self.register_buffer(
f'{method_name}_params',
torch.tensor([
in_channels,
in_ratio,
out_channels,
out_ratio,
]))
if input_labels is None:
input_labels = [
f"(signal) model input {i}" for i in range(in_channels)
]
if len(input_labels) != in_channels:
raise ValueError(
(f"Method {method_name}, expected "
f"{in_channels} input labels, got {len(input_labels)}"))
setattr(self, f"{method_name}_input_labels", input_labels)
if output_labels is None:
output_labels = [
f"(signal) model output {i}" for i in range(out_channels)
]
if len(output_labels) != out_channels:
raise ValueError(
(f"Method {method_name}, expected "
f"{out_channels} output labels, got {len(output_labels)}"))
setattr(self, f"{method_name}_output_labels", output_labels)
if test_method:
logging.info(f"Testing method {method_name} with nn~ API")
x = torch.zeros(1, in_channels, test_buffer_size // in_ratio)
y = getattr(self, method_name)(x)
if len(y.shape) != 3:
raise ValueError(
("Output tensor must have exactly 3 dimensions, "
f"got {len(y.shape)}"))
if y.shape[0] != 1:
raise ValueError(
f"Expecting single batch output, got {y.shape[0]}")
if y.shape[1] != out_channels:
raise ValueError((
f"Wrong number of output channels for method \"{method_name}\", "
f"expected {out_channels} got {y.shape[1]}"))
if y.shape[2] != test_buffer_size // out_ratio:
raise ValueError(
(f"Wrong output length for method \"{method_name}\", "
f"expected {test_buffer_size//out_ratio} "
f"got {y.shape[2]}"))
if y.dtype != torch.float:
raise ValueError(f"Output tensor must be of type float, got {y.dtype}")
if cc.MAX_BATCH_SIZE > 1:
logging.info(f"Testing method {method_name} with mc.nn~ API")
x = torch.zeros(4, in_channels, test_buffer_size // in_ratio)
y = getattr(self, method_name)(x)
if len(y.shape) != 3:
raise ValueError(
("Output tensor must have exactly 3 dimensions, "
f"got {len(y.shape)}"))
if y.shape[0] != 4:
raise ValueError(
f"Expecting 4 batch output, got {y.shape[0]}")
if y.shape[1] != out_channels:
raise ValueError((
f"Wrong number of output channels for method \"{method_name}\", "
f"expected {out_channels} got {y.shape[1]}"))
if y.shape[2] != test_buffer_size // out_ratio:
raise ValueError(
(f"Wrong output length for method \"{method_name}\", "
f"expected {test_buffer_size//out_ratio} "
f"got {y.shape[2]}"))
logging.info((f"Added method \"{method_name}\" "
f"tested with buffer size {test_buffer_size}"))
else:
logging.info(
f"Skipping method {method_name} with mc.nn~ API as cc.MAX_BATCH_SIZE={cc.MAX_BATCH_SIZE}"
)
else:
logging.warn(f"Added method \"{method_name}\" without testing it.")
self._methods.append(method_name)
def register_attribute(self, attribute_name: str,
values: Union[Any, Tuple[Any]]):
"""Register an attribute visible by nn~.
Args:
attribute_name: name of the attribute to register
values: a default value or tuple of default values
"""
assert attribute_name not in self.__reserved_attribute_names__, f"attribute_name {attribute_name} is reserved."
if not isinstance(values, (List, Tuple)):
values = list([values])
else:
values = list(values)
type_hash = []
for v in values:
type_hash.append(TYPE_HASH[type(v)])
# if not hasattr(self, f"get_{attribute_name}"):
# raise AttributeError(f"Getter for {attribute_name} not defined")
# if not hasattr(self, f"set_{attribute_name}"):
# raise AttributeError(f"Setter for {attribute_name} not defined")
# signature = inspect.signature(getattr(self, f"get_{attribute_name}"))
# if signature.return_annotation == inspect._empty:
# raise TypeError(
# f"Output type not defined for getter get_{attribute_name}")
self.__setattr__(attribute_name, tuple(values))
self._attributes.value.append(attribute_name)
for i, v in enumerate(values):
if isinstance(v, Buffer):
self._buffer_attributes.value.append(f"{attribute_name}#{i}")
self.register_buffer(f"{attribute_name}_params", torch.LongTensor(type_hash))
@torch.jit.export
def get_methods(self):
return self._methods
@torch.jit.export
def get_attributes(self) -> List[str]:
return self._attributes
def export_to_ts(self, path):
self.eval()
scripted = torch.jit.script(self)
scripted.save(path)
# buffer attributes handling
@torch.jit.export
def get_buffer_attributes(self) -> List[str]:
if torch.jit.is_scripting():
return self._buffer_attributes
else:
return self._buffer_attributes.value
@torch.jit.export
def is_buffer_empty(self, buffer_name: str) -> bool:
if buffer_name not in self.get_buffer_attributes():
return True
if torch.jit.is_scripting():
for k, v in self._buffer_attributes.items():
if k == buffer_name:
return v.has_value
else:
for k, v in self._buffer_attributes.value.items():
if k == buffer_name:
return v.has_value
return True
@torch.jit.export
def get_sample_rate(self) -> int:
sr = self.sr
if torch.jit.isinstance(sr, Optional[int]):
if sr is None:
return -1
else:
return int(sr)
else:
if sr.value is None:
return -1
else:
return int(sr.value)
@torch.jit.export
def set_sample_rate(self, sample_rate: int | None) -> None:
"""set the operative sampling rate of the module on inference."""
if sample_rate is not None:
self.sr = sample_rate
def __prepare_scriptable__(self):
if not self._ready:
self.finish()
return self
def finish(self):
self._build_buffer_attribute_methods()
self._build_missing_attribute_callbacks()
self._ready = True
def _build_buffer_attribute_methods(self):
self.set_buffer_attribute = MethodType(
method_from_template(
self.tmp_file_session,
templates.buffers.set_buffer_attribute_template(self._buffer_attributes),
globals(), locals()
)["set_buffer_attribute"],
self)
self.clear_buffer_attribute = MethodType(
method_from_template(
self.tmp_file_session,
templates.buffers.clear_buffer_attribute_template(self._buffer_attributes),
globals(), locals()
)["clear_buffer_attribute"],
self)
self.is_buffer_empty = MethodType(
method_from_template(
self.tmp_file_session,
templates.buffers.is_buffer_empty_template(self._buffer_attributes),
globals(), locals()
)["is_buffer_empty"],
self)
def _build_missing_attribute_callbacks(self):
for attr_name in self._attributes.value:
getter_name = f"get_{attr_name}"
if not hasattr(self, getter_name):
getter_cb = MethodType(
method_from_template(
self.tmp_file_session,
templates.attributes.get_attribute_getter(attr_name, getattr(self, f"{attr_name}_params")),
globals(), locals()
)[getter_name],
self)
setattr(self, getter_name, getter_cb)
setter_name = f"set_{attr_name}"
if not hasattr(self, setter_name):
setter_cb = MethodType(
method_from_template(
self.tmp_file_session,
templates.attributes.get_attribute_setter(attr_name, getattr(self, f"{attr_name}_params")),
globals(), locals()
)[setter_name],
self)
setattr(self, setter_name, setter_cb)
def __del__(self):
if getattr(self, "tmp_file_session", None):
self.tmp_file_session.close()
================================================
FILE: python_tools/templates/__init__.py
================================================
from .buffers import *
from .attributes import *
================================================
FILE: python_tools/templates/attributes.py
================================================
import torch
from .. import TYPE_HASH, Buffer
TYPE_HASH_R = {v: k for k, v in TYPE_HASH.items()}
def _get_sig_type(param):
param = TYPE_HASH_R.get(int(param), None)
if param in [int, float, bool, str]:
return param.__name__
elif param in [torch.Tensor]:
return "torch.Tensor"
elif param in [Buffer]:
# return "Tuple[torch.Tensor, int]"
return "str"
else:
raise TypeError('type %s not known'%type(param))
def get_attribute_setter(attribute_name, attribute_params):
signature_atoms = [f'{attribute_name}{i}: {_get_sig_type(attribute_params[i])}' for i in range(len(attribute_params))]
signature = ", ".join(signature_atoms)
setter_atoms = []
for i in range(len(attribute_params)):
if attribute_params[i] == TYPE_HASH[Buffer]:
setter_atoms.append(f'Buffer.copy(self.{attribute_name}[{i}])')
else:
setter_atoms.append(f"{attribute_name}{i}")
setter = f"self.{attribute_name} = (" + ", ".join(setter_atoms) + ",)"
template = f"@torch.jit.export\ndef set_{attribute_name}(self, {signature}) -> int:\n\tres=0\n"
template += f"\t{setter}\n"
template += "\treturn res"
return template
def get_attribute_getter(attribute_name, attribute_params):
def _export_arg(attribute_name, attribute_params, i):
if attribute_params[i] == TYPE_HASH[Buffer]:
return 'self.' + attribute_name+'['+str(i)+'].to_str()'
else:
return 'self.' + attribute_name+'['+str(i)+']'
template = f"@torch.jit.export\ndef get_{attribute_name}(self):\n"
template+= f"\treturn {', '.join([_export_arg(attribute_name, attribute_params, i) for i in range(len(attribute_params))])},"
return template
================================================
FILE: python_tools/templates/buffers.py
================================================
def set_buffer_attribute_template(buffer_names):
template = "@torch.jit.export\ndef set_buffer_attribute(self, buffer_name: str, buffer: torch.Tensor, sr: int) -> int:\n"
if len(buffer_names.value) == 0:
template += "\treturn -1"
return template
for b in buffer_names.value:
buffer_names_parts = b.split('#')
if len(buffer_names_parts) != 2:
raise ValueError('Invalid buffer name : '%b)
attribute_name, buffer_idx = buffer_names_parts
template += f"\tif (buffer_name == \"{b}\"): return self.{attribute_name}[{buffer_idx}].set_value(buffer, sr)\n"
template += "\treturn -1"
return template
def clear_buffer_attribute_template(buffer_names):
template = "@torch.jit.export\ndef clear_buffer_attribute(self, buffer_name: str) -> None:\n"
if len(buffer_names.value) == 0:
template += "\treturn"
return template
for b in buffer_names.value:
buffer_names_parts = b.split('#')
if len(buffer_names_parts) != 2:
raise ValueError('Invalid buffer name : '%b)
attribute_name, buffer_idx = buffer_names_parts
template += f"\tif (buffer_name == \"{b}\"): return self.{attribute_name}[{buffer_idx}].init_value()\n"
return template
def is_buffer_empty_template(buffer_names):
template = "@torch.jit.export\ndef is_buffer_empty(self, buffer_name: str) -> bool:\n"
if len(buffer_names.value) == 0:
template += "\treturn True"
return template
for b in buffer_names.value:
buffer_names_parts = b.split('#')
if len(buffer_names_parts) != 2:
raise ValueError('Invalid buffer name : '%b)
attribute_name, buffer_idx = buffer_names_parts
template += f"\tif (buffer_name == \"{b}\"): return not self.{attribute_name}[{buffer_idx}].has_value\n"
template += "\treturn True"
return template
================================================
FILE: python_tools/test/test_attributes.maxpat
================================================
{
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 8,
"minor" : 6,
"revision" : 5,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 607.0, 354.0, 767.0, 480.0 ],
"bglocked" : 0,
"openinpresentation" : 0,
"default_fontsize" : 12.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 1,
"gridsize" : [ 15.0, 15.0 ],
"gridsnaponopen" : 1,
"objectsnaponopen" : 1,
"statusbarvisible" : 2,
"toolbarvisible" : 1,
"lefttoolbarpinned" : 0,
"toptoolbarpinned" : 0,
"righttoolbarpinned" : 0,
"bottomtoolbarpinned" : 0,
"toolbars_unpinned_last_save" : 0,
"tallnewobj" : 0,
"boxanimatetime" : 200,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"description" : "",
"digest" : "",
"tags" : "",
"style" : "",
"subpatcher_template" : "",
"assistshowspatchername" : 0,
"boxes" : [ {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-4",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 153.666666666666686, 278.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-2",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 69.0, 278.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"id" : "obj-19",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 602.0, 154.0, 75.0, 22.0 ],
"text" : "get attr_bool"
}
}
, {
"box" : {
"id" : "obj-18",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 525.0, 154.0, 66.0, 22.0 ],
"text" : "get attr_str"
}
}
, {
"box" : {
"id" : "obj-17",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 454.0, 154.0, 65.0, 22.0 ],
"text" : "get attr_int"
}
}
, {
"box" : {
"id" : "obj-16",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 378.0, 154.0, 65.0, 22.0 ],
"text" : "get attr_int"
}
}
, {
"box" : {
"id" : "obj-14",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 419.0, 92.0, 91.0, 22.0 ],
"text" : "set attr_bool $1"
}
}
, {
"box" : {
"id" : "obj-13",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 296.0, 92.0, 82.0, 22.0 ],
"text" : "set attr_str $1"
}
}
, {
"box" : {
"id" : "obj-12",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 174.0, 92.0, 91.0, 22.0 ],
"text" : "set attr_float $1"
}
}
, {
"box" : {
"id" : "obj-11",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 69.0, 92.0, 81.0, 22.0 ],
"text" : "set attr_int $1"
}
}
, {
"box" : {
"id" : "obj-9",
"maxclass" : "toggle",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "int" ],
"parameter_enable" : 0,
"patching_rect" : [ 419.0, 37.0, 24.0, 24.0 ]
}
}
, {
"box" : {
"id" : "obj-7",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 296.0, 49.0, 42.0, 22.0 ],
"text" : "cherry"
}
}
, {
"box" : {
"format" : 6,
"id" : "obj-5",
"maxclass" : "flonum",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "", "bang" ],
"parameter_enable" : 0,
"patching_rect" : [ 174.0, 49.0, 50.0, 22.0 ]
}
}
, {
"box" : {
"id" : "obj-3",
"maxclass" : "number",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "", "bang" ],
"parameter_enable" : 0,
"patching_rect" : [ 69.0, 44.0, 50.0, 22.0 ]
}
}
, {
"box" : {
"id" : "obj-1",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 4,
"outlettype" : [ "signal", "signal", "signal", "signal" ],
"patching_rect" : [ 69.0, 214.0, 273.0, 22.0 ],
"text" : "nn~ test_attributes[AttributeFoo]"
}
}
],
"lines" : [ {
"patchline" : {
"destination" : [ "obj-2", 0 ],
"source" : [ "obj-1", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-4", 0 ],
"source" : [ "obj-1", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"source" : [ "obj-11", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"source" : [ "obj-12", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"source" : [ "obj-13", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"source" : [ "obj-14", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"source" : [ "obj-16", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"source" : [ "obj-17", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"source" : [ "obj-18", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"source" : [ "obj-19", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-11", 0 ],
"source" : [ "obj-3", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-12", 0 ],
"source" : [ "obj-5", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-13", 0 ],
"source" : [ "obj-7", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-14", 0 ],
"source" : [ "obj-9", 0 ]
}
}
],
"dependency_cache" : [ {
"name" : "nn~.mxo",
"type" : "iLaX"
}
],
"autosave" : 0
}
}
================================================
FILE: python_tools/test/test_attributes.py
================================================
import sys, os
import torch
import pytest
from pathlib import Path
sys.path.append(str(Path(__file__).parent / ".." / ".."))
from python_tools import Module, TYPE_HASH, Buffer
from types import MethodType
from typing import NoReturn
from utils import out_dir, test_name, import_code
class AttributeFoo(Module):
def __init__(self):
super().__init__()
self.register_attribute("attr_int", 0)
self.register_attribute("attr_float", 0.)
self.register_attribute("attr_str", "apple")
self.register_attribute("attr_bool", False)
self.register_method("forward", 1, 1, 2, 1, test_method=False)
self.finish()
@torch.jit.export
def forward(self, x: torch.Tensor):
x = torch.zeros(x.shape[:-2] + (2, x.shape[-1]))
x[..., 0, :] = self.attr_int[0]
x[..., 1, :] = self.attr_float[0]
return x
class ListAttributeFoo(Module):
def __init__(self, n: int, attribute_type: type):
super().__init__()
self.n = n
if attribute_type == torch.Tensor:
attr = tuple([torch.tensor(i) for i in range(n)])
else:
attr = tuple([attribute_type(i) for i in range(n)])
self.register_attribute("attr", attr)
self.register_method("forward", 1, 1, n, 1, output_labels=["attribute %d"%i for i in range(len(attr))])
self.finish()
def forward(self, x):
out = torch.zeros(x.shape[:1] + (len(self.attr),) + x.shape[2:])
for i, val in enumerate(self.attr):
out[..., i, :] = float(val)
return out
def _default(attr_hash: int):
type_hash_r = {v: k for k, v in TYPE_HASH.items()}
attr_hash = type_hash_r[int(attr_hash)]
if attr_hash in [bool, int, float, str]:
return attr_hash(1)
elif attr_hash in [torch.Tensor]:
return torch.tensor(0)
elif attr_hash in [Buffer]:
return (torch.tensor(0), 44100)
else:
raise TypeError('type not known')
class TensorAttributeFoo(Module):
def __init__(self):
super().__init__()
self.register_attribute("a", torch.zeros(4))
self.register_method("forward", 1, 1, 4, 1, test_method=False)
self.finish()
@torch.jit.export
def forward(self, x: torch.Tensor):
out = torch.zeros(x.shape[0], 4, x.shape[2])
for i in range(4):
out[:, i] = self.a[0][None, i]
return out
@pytest.mark.parametrize('module_class', [AttributeFoo])
def test_attributes(module_class, out_dir, test_name):
module = module_class()
for attr_name in module.get_attributes().value:
# test getter
attr_params = getattr(module, f"{attr_name}_params")
getattr(module, f"get_{attr_name}")()
# test setter
getattr(module, f"set_{attr_name}")(_default(attr_params[0]))
module(torch.zeros(1, 1, 16))
scripted = torch.jit.script(module)
torch.jit.save(scripted, out_dir/f"{test_name}.ts")
@pytest.mark.parametrize('n', [1, 4])
@pytest.mark.parametrize('attr_type', [str, bool, int, float])
@pytest.mark.parametrize('module_class', [ListAttributeFoo])
def test_list_attributes(n, attr_type, module_class, out_dir, test_name):
module = module_class(n, attr_type)
module.get_attr()
module.set_attr(*([_default(module.attr_params[0])] * n))
module(torch.zeros(1, 1, 16))
scripted = torch.jit.script(module)
torch.jit.save(scripted, out_dir/f"{test_name}.ts")
@pytest.mark.parametrize('n', [1, 4])
@pytest.mark.parametrize('attr_type', [str, bool, int, float])
@pytest.mark.parametrize('module_class', [ListAttributeFoo])
def test_list_attributes(n, attr_type, module_class, out_dir, test_name):
module = module_class(n, attr_type)
module.get_attr()
module.set_attr(*([_default(module.attr_params[0])] * n))
module(torch.zeros(1, 1, 16))
scripted = torch.jit.script(module)
torch.jit.save(scripted, out_dir/f"{test_name}.ts")
@pytest.mark.parametrize('module_class', [TensorAttributeFoo])
def test_tensor_attributes(module_class, out_dir, test_name):
module = module_class()
target_attr = torch.Tensor([1,2,3,4])
module.set_a(torch.Tensor(target_attr))
out = module.get_a()[0]
assert out.eq(target_attr).all()
module(torch.zeros(1, 1, 16))
scripted = torch.jit.script(module)
torch.jit.save(scripted, out_dir/f"{test_name}.ts")
================================================
FILE: python_tools/test/test_buffers.py
================================================
import sys, os
import torch
import pytest
from pathlib import Path
sys.path.append(str(Path(__file__).parent / ".." / ".."))
from python_tools import Module, Buffer
from utils import out_dir, test_name, import_code
from typing import Tuple
class BufferFoo(Module):
buffer: Tuple[Buffer]
def __init__(self, test_method: bool = False):
super().__init__()
self.register_attribute("buf", Buffer(None, 64, 2048))
self.register_method('loudness', 1, 1, 1, 1, test_method=test_method)
self.register_method('shape', 1, 1, 2, 1, test_method=test_method)
self.register_method('get_sr', 1, 1, 1, 1, test_method=test_method)
self.finish()
def get_loudness(self, x: torch.Tensor) -> float:
return x.pow(2).mean().sqrt().item()
@torch.jit.export
def loudness(self, x: torch.Tensor):
buffer = self.buf[0]
if buffer.has_value:
loudness = self.get_loudness(buffer.value)
return torch.full_like(x, fill_value=loudness)
else:
return torch.zeros_like(x)
@torch.jit.export
def shape(self, x: torch.Tensor):
is_batched = x.ndim > 2
if not is_batched:
x = x[None]
buffer = self.buf[0]
if buffer.has_value:
out = torch.zeros(x.shape[0], 2, x.shape[-1])
out[:, 0, :] = buffer.value.shape[0]
out[:, 1, :] = buffer.value.shape[1]
if not is_batched:
out = out[0]
else:
out = torch.zeros_like(x)
return out
@torch.jit.export
def get_sr(self, x: torch.Tensor):
buffer = self.buf[0]
if buffer.has_value:
if self.buf[0].sr is None:
sr = -1
else:
sr = buffer.sr
return torch.full_like(x, fill_value=sr)
else:
return torch.zeros_like(x)
@pytest.mark.parametrize('module_class', [BufferFoo])
def test_buffer_attributes(module_class, out_dir, test_name):
module = module_class()
module.loudness(torch.randn(1, 1, 16))
module.shape(torch.randn(1, 1, 16))
module.get_sr(torch.randn(1, 1, 16))
module.get_buf()
module.set_buf((torch.zeros(1, 64), 44100))
module.set_buffer_attribute("buffer#0", torch.zeros(1, 64), 44100)
@pytest.mark.parametrize('module_class', [BufferFoo])
def test_scripted_buffer_attributes(module_class, out_dir, test_name):
module = module_class()
scripted = torch.jit.script(module)
module.loudness(torch.randn(1, 1, 16))
module.shape(torch.randn(1, 1, 16))
module.get_sr(torch.randn(1, 1, 16))
module.get_buf()
module.set_buf((torch.zeros(1, 64), 44100))
module.set_buffer_attribute("buffer#0", torch.zeros(1, 64), 44100)
module.get_buffer_attributes()
torch.jit.save(scripted, out_dir/f"{test_name}.ts")
================================================
FILE: python_tools/test/test_list_attributes.maxpat
================================================
{
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 8,
"minor" : 6,
"revision" : 5,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 572.0, 172.0, 681.0, 480.0 ],
"bglocked" : 0,
"openinpresentation" : 0,
"default_fontsize" : 12.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 1,
"gridsize" : [ 15.0, 15.0 ],
"gridsnaponopen" : 1,
"objectsnaponopen" : 1,
"statusbarvisible" : 2,
"toolbarvisible" : 1,
"lefttoolbarpinned" : 0,
"toptoolbarpinned" : 0,
"righttoolbarpinned" : 0,
"bottomtoolbarpinned" : 0,
"toolbars_unpinned_last_save" : 0,
"tallnewobj" : 0,
"boxanimatetime" : 200,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"description" : "",
"digest" : "",
"tags" : "",
"style" : "",
"subpatcher_template" : "",
"assistshowspatchername" : 0,
"boxes" : [ {
"box" : {
"id" : "obj-21",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 532.0, 218.0, 46.0, 22.0 ],
"text" : "get attr"
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-22",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 589.0, 347.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"id" : "obj-23",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 351.0, 218.0, 167.0, 22.0 ],
"text" : "set attr Pipi caca boudin prout"
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-24",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 510.0, 347.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-25",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 430.0, 347.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-26",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 351.0, 347.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"id" : "obj-27",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 4,
"outlettype" : [ "signal", "signal", "signal", "signal" ],
"patching_rect" : [ 351.0, 279.0, 248.0, 22.0 ],
"text" : "nn~ test_list_attributes[ListAttributeFoo-str-4]"
}
}
, {
"box" : {
"id" : "obj-20",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 216.0, 218.0, 46.0, 22.0 ],
"text" : "get attr"
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-13",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 273.0, 347.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"id" : "obj-14",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 39.0, 218.0, 85.0, 22.0 ],
"text" : "set attr 1 0 1 0"
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-15",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 193.666666666666657, 347.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-16",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 114.333333333333329, 347.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-17",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 35.0, 347.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"id" : "obj-18",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 4,
"outlettype" : [ "signal", "signal", "signal", "signal" ],
"patching_rect" : [ 35.0, 279.0, 257.0, 22.0 ],
"text" : "nn~ test_list_attributes[ListAttributeFoo-bool-4]"
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-6",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 579.0, 146.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"id" : "obj-8",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 351.0, 43.0, 105.0, 22.0 ],
"text" : "set attr 0. 1. 3. 23."
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-9",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 503.0, 146.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-10",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 427.0, 146.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-11",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 351.0, 146.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"id" : "obj-12",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 4,
"outlettype" : [ "signal", "signal", "signal", "signal" ],
"patching_rect" : [ 351.0, 78.0, 257.0, 22.0 ],
"text" : "nn~ test_list_attributes[ListAttributeFoo-float-4]"
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-2",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 263.0, 146.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"id" : "obj-7",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 35.0, 43.0, 105.0, 22.0 ],
"text" : "set attr 0. 1. 3. 23."
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-5",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 187.0, 146.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-4",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 111.0, 146.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-3",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 35.0, 146.0, 56.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"id" : "obj-1",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 4,
"outlettype" : [ "signal", "signal", "signal", "signal" ],
"patching_rect" : [ 35.0, 78.0, 247.0, 22.0 ],
"text" : "nn~ test_list_attributes[ListAttributeFoo-int-4]"
}
}
],
"lines" : [ {
"patchline" : {
"destination" : [ "obj-2", 0 ],
"source" : [ "obj-1", 3 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-3", 0 ],
"source" : [ "obj-1", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-4", 0 ],
"source" : [ "obj-1", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-5", 0 ],
"source" : [ "obj-1", 2 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-10", 0 ],
"source" : [ "obj-12", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-11", 0 ],
"source" : [ "obj-12", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 0 ],
"source" : [ "obj-12", 3 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-9", 0 ],
"source" : [ "obj-12", 2 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-18", 0 ],
"source" : [ "obj-14", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-13", 0 ],
"source" : [ "obj-18", 3 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-15", 0 ],
"source" : [ "obj-18", 2 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-16", 0 ],
"source" : [ "obj-18", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-17", 0 ],
"source" : [ "obj-18", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-18", 0 ],
"source" : [ "obj-20", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-27", 0 ],
"source" : [ "obj-21", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-27", 0 ],
"source" : [ "obj-23", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-22", 0 ],
"source" : [ "obj-27", 3 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-24", 0 ],
"source" : [ "obj-27", 2 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-25", 0 ],
"source" : [ "obj-27", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-26", 0 ],
"source" : [ "obj-27", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"source" : [ "obj-7", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-12", 0 ],
"source" : [ "obj-8", 0 ]
}
}
],
"dependency_cache" : [ {
"name" : "nn~.mxo",
"type" : "iLaX"
}
],
"autosave" : 0
}
}
================================================
FILE: python_tools/test/utils.py
================================================
import os
import importlib
import time
import sys
import pytest
from pathlib import Path
@pytest.fixture
def out_dir() -> Path:
out_dir = (Path(__file__).parent / "model_out").resolve()
if not out_dir.exists():
os.makedirs(out_dir)
return out_dir
@pytest.fixture
def test_name(request):
return request.node.name
def import_code(code, glob, loc):
outdir = Path('/tmp') / "nn_tilde" / "code"
os.makedirs(outdir, exist_ok=True)
module_name = f"nntilde_tmp_{int(time.time())}"
outpath = outdir / f"{module_name}.py"
with open(outpath, "w+") as f:
f.write(code)
# Load the module
spec = importlib.util.spec_from_file_location(module_name, outpath)
module = importlib.util.module_from_spec(spec)
exec(spec.loader.get_code(module_name), glob)
loc.update(module.__dict__)
================================================
FILE: requirements.txt
================================================
torch==2.5
cached_conv>=2.5.0
================================================
FILE: requirements_darwin_x64.txt
================================================
torch1
cached_conv>=2.5.0
================================================
FILE: scripting/README.md
================================================
# Scripting examples in nn~
These examples demonstrate how to write simple scripts to incorporate any type of deep models from PyTorch into MaxMSP (and potentially running on GPU). The examples show a variety of different use cases that also help to understand the input/output shapes relationships.
- `effects.py` : apply simple effects to the input (identical input and output shapes)
- `features.py` : compute spectral descriptors from the PyTorch audio library (each input audio buffer produces a single float as output)
- `unmix.py` : apply the unmix deep source separation model (input is split into 4 different audio streams containing « drums », « vocals », « bass » and « others »)
================================================
FILE: scripting/effects.py
================================================
#
# NN~ - Scripting library
# effects.py : Intermediate scripting example for waveform-to-waveform case.
#
# We provide here a simple example of how to use nn~ in order to transform incoming audio.
# In this example, we do not rely on any ML model, but simply apply effects on input buffers.
#
# ACIDS - IRCAM : Philippe Esling, Axel Chemla--Romeu-Santos, Antoine Caillon
#
from typing import List, Tuple
import torch
import torch.nn as nn
import nn_tilde
class AudioUtils(nn_tilde.Module):
def __init__(self):
super().__init__()
# REGISTER ATTRIBUTES
self.register_attribute('gain_factor', 1.)
self.register_attribute('polynomial_factors', (1., 0., 0., 0.))
self.register_attribute('saturate_mode', 'tanh')
self.register_attribute('invert_signal', False)
self.register_attribute('fractal', (2, 0.))
# REGISTER METHODS
self.register_method(
'thru',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=1,
input_labels=['(signal) input signal'],
output_labels=['(signal) output signal'],
)
self.register_method(
'invert',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=1,
input_labels=['(signal) input signal'],
output_labels=['(signal) output signal'],
)
self.register_method(
'add',
in_channels=2,
in_ratio=1,
out_channels=1,
out_ratio=1,
input_labels=['(signal) first signal', '(signal) second signal'],
output_labels=['(signal) output signal'],
)
self.register_method(
'saturate',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=1,
input_labels=['(signal) signal to saturate'],
output_labels=['(signal) saturated signal'],
)
self.register_method(
'midside',
in_channels=2,
in_ratio=1,
out_channels=2,
out_ratio=1,
input_labels=['(signal) L channel', '(signal) R channel'],
output_labels=['(signal) Mid channel', '(signal) Side channel'],
)
self.register_method(
'rms',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=1024,
input_labels=['(signal) signal to monitor'],
output_labels=['(signal) rms value'],
)
self.register_method(
'polynomial',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=1,
input_labels=['(signal) signal to distort'],
output_labels=['(signal) distorted signal'],
)
self.register_method(
'fractalize',
in_channels=1,
in_ratio=512,
out_channels=1,
out_ratio=512,
input_labels=['(signal) signal to replicate'],
output_labels=['(signal) fractalized signal'],
)
@torch.jit.export
def thru(self, x: torch.Tensor):
return x
# defining main methods
@torch.jit.export
def invert(self, x: torch.Tensor):
if self.invert_signal[0]:
return x
else:
return -x
@torch.jit.export
def add(self, x: torch.Tensor):
return x.sum(-2, keepdim=True) / 2
@torch.jit.export
def fractalize(self, x: torch.Tensor):
fractal_order = int(self.fractal[0])
fractal_amount = float(self.fractal[1])
downsampled_signal = x[..., ::fractal_order]
return x
@torch.jit.export
def polynomial(self, x: torch.Tensor):
out = torch.zeros_like(x)
for i in range(4):
out += self.polynomial_factors[i] * x.pow(i + 1)
return out
@torch.jit.export
def saturate(self, x: torch.Tensor):
saturate_mode = self.saturate_mode[0]
if saturate_mode == 'tanh':
return torch.tanh(x * self.gain_factor[0])
elif saturate_mode == 'clip':
return torch.clamp(x * self.gain_factor[0], -1, 1)
@torch.jit.export
def midside(self, x: torch.Tensor):
l, r = x[..., 0, :], x[..., 1, :]
return torch.stack([(l + r) / 2, (l - r) / 2], dim=-2)
@torch.jit.export
def rms(self, x: torch.Tensor):
x = x.reshape(x.shape[0], x.shape[1], 1024, -1)
rms = x.pow(2).sum(-2).sqrt() / x.size(-1)
return rms
# defining attribute getters
# WARNING : typing the function's ouptut is mandatory
@torch.jit.export
def get_gain_factor(self) -> float:
return float(self.gain_factor[0])
@torch.jit.export
def get_polynomial_factors(self) -> List[float]:
polynomial_factors: List[float] = []
for p in self.polynomial_factors:
polynomial_factors.append(float(p))
return polynomial_factors
@torch.jit.export
def get_saturate_mode(self) -> str:
return self.saturate_mode[0]
@torch.jit.export
def get_invert_signal(self) -> bool:
return self.invert_signal[0]
@torch.jit.export
def get_fractal(self) -> Tuple[int, float]:
return (int(self.fractal[0]), float(self.fractal[1]))
# defining attribute setter
# setters must return an error code :
# return 0 if the attribute has been adequately set,
# return -1 if the attribute was wrong.
@torch.jit.export
def set_gain_factor(self, x: float) -> int:
self.gain_factor = (x, )
return 0
@torch.jit.export
def set_polynomial_factors(self, factor1: float, factor2: float,
factor3: float, factor4: float) -> int:
factors = (factor1, factor2, factor3, factor4)
self.polynomial_factors = factors
return 0
@torch.jit.export
def set_saturate_mode(self, x: str):
if (x == 'tanh') or (x == 'clip'):
self.saturate_mode = (x, )
return 0
else:
return -1
@torch.jit.export
def set_invert_signal(self, x: bool):
self.invert_signal = (x, )
return 0
@torch.jit.export
def set_fractal(self, factor: int, amount: float):
if factor <= 0:
return -1
elif factor % 2 != 0:
return -1
self.fractal = (factor, float(amount))
return 0
if __name__ == '__main__':
model = AudioUtils()
model.export_to_ts('effects.ts')
================================================
FILE: scripting/features.py
================================================
#
# NN~ - Scripting library
# features.py : Simple scripting example for waveform-to-float case.
#
# We demonstrate the basic mecanisms for using the nn~ environment.
# In this case, any function from Python can be used to wrap it inside a nn~ model.
#
# ACIDS - IRCAM : Philippe Esling, Axel Chemla--Romeu-Santos, Antoine Caillon
#
from typing import List, Tuple
import librosa
# Pytorch audio operations
import torch
import torchaudio.functional as F
from torchaudio.transforms import Spectrogram
# Import the nn~ library
import nn_tilde
import numpy as np
class AudioFeatures(nn_tilde.Module):
def __init__(self,
nfft=1024,
hop_size=256,
skip_features=None):
super().__init__()
self.nfft = nfft
self.hop_size = hop_size
transform = Spectrogram(n_fft=nfft,
win_length=nfft,
hop_length=hop_size,
center=False,
normalized=True)
self.transform = transform
self.skip_features = skip_features
# -----------------
# Register attributes
# -----------------
self.register_attribute('sr', 44100)
self.register_buffer('audio_buffer', torch.zeros((1, 1, nfft - hop_size)))
# Pre-compute frequency bins
self.freq = torch.fft.rfftfreq(n = nfft, d = 1.0 / self.sr[0])
# -----------------
# Register methods
# -----------------
self.register_method(
'rms',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=1024,
input_labels=['(signal) signal to monitor'],
output_labels=['(signal) rms value'],
)
# REGISTER METHODS
self.register_method(
'centroid',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=self.hop_size,
input_labels=['(signal) signal to monitor'],
output_labels=['(signal) spectral centroid value'],
)
# REGISTER METHODS
self.register_method(
'flatness',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=self.hop_size,
input_labels=['(signal) signal to monitor'],
output_labels=['(signal) flatness value'],
)
# REGISTER METHODS
self.register_method(
'bandwidth',
in_channels=1,
in_ratio=1,
out_channels=1,
out_ratio=self.hop_size,
input_labels=['(signal) signal to monitor'],
output_labels=['(signal) bandwidth value'],
)
def _compute_spectrogram(self, x: torch.Tensor):
# X : B x hop_size
if self.audio_buffer.shape[0] != x.shape[0]:
print("Resizing and resetting buffer - the batch size has changed")
self.audio_buffer = torch.zeros((x.shape[0], 1, self.nfft - self.hop_size)).to(x)
self.freq = torch.fft.rfftfreq(n = self.nfft, d = 1.0 / self.sr[0])
# Using the previous buffer information
x = torch.cat([self.audio_buffer, x], dim=-1)
# Compute the transform
spec = self.transform(x)[:, 0]
self.audio_buffer = x[..., -(self.nfft - self.hop_size):]
if self.skip_features is not None:
spec = spec[:, :self.skip_features]
return spec
@torch.jit.export
def rms(self, x: torch.Tensor):
x = x.reshape(x.shape[0], x.shape[1], 1024, -1)
rms = x.pow(2).sum(-2).sqrt() / x.size(-1)
return rms
@torch.jit.export
def centroid(self, x: torch.Tensor):
# Compute the current spectrogram
spectro = self._compute_spectrogram(x)
# Compute the center frequencies of each bin
if self.freq is None:
self.freq = torch.fft.rfftfreq(n = self.nfft, d = 1.0 / self.sr[0])
if len(self.freq.shape) == 1:
self.freq = self.freq[None, :, None].expand_as(spectro)
# Column-normalize S
centroid = torch.sum(self.freq * torch.nn.functional.normalize(spectro, p=1.0, dim=-2), dim=-2)
return centroid[:, None, :]
@torch.jit.export
def bandwidth(self, x: torch.Tensor, amin: float = 1e-10, power: float = 2.0, p: float = 2.0):
# Compute the current spectrogram
spectro = self._compute_spectrogram(x)
# Compute the center frequencies of each bin
if self.freq is None:
self.freq = torch.fft.rfftfreq(n = self.nfft, d = 1.0 / self.sr[0])
if len(self.freq.shape) == 1:
self.freq = self.freq[None, :, None].expand_as(spectro)
# Normalize spectro
spectro_normed = torch.nn.functional.normalize(spectro, p=1.0, dim=-2)
# Compute centroid
centroid = torch.sum(self.freq * spectro_normed, dim=-2)[:, None, :]
# Compute the deviation
deviation = torch.abs(self.freq - centroid)
# Compute bandwidth
bandwidth = torch.sum(spectro_normed * deviation**p, dim=-2, keepdim=True) ** (1.0 / p)
return bandwidth
@torch.jit.export
def flatness(self, x: torch.Tensor, amin: float = 1e-10, power: float = 2.0):
# Compute the current spectrogram
spectro = self._compute_spectrogram(x)
S_thresh = torch.maximum(spectro**power, torch.zeros(1) + amin)
gmean = torch.exp(torch.mean(torch.log(S_thresh), dim=-2, keepdim=True))
amean = torch.mean(S_thresh, dim=-2, keepdim=True)
flatness = gmean / amean
print(flatness.shape)
return flatness
# defining attribute getters
# WARNING : typing the function's ouptut is mandatory
@torch.jit.export
def get_sr(self) -> int:
return int(self.sr[0])
# defining attribute setter
# setters must return an error code :
# return 0 if the attribute has been adequately set,
# return -1 if the attribute was wrong.
@torch.jit.export
def set_sr(self, x: int) -> int:
self.sr = (x, )
return 0
if __name__ == '__main__':
# Create your target class
model = AudioFeatures()
# Export it to a torchscript model
model.export_to_ts('features.ts')
================================================
FILE: scripting/scripting.maxpat
================================================
{
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 9,
"minor" : 0,
"revision" : 2,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 134.0, 124.0, 1000.0, 959.0 ],
"gridsize" : [ 15.0, 15.0 ],
"boxes" : [ {
"box" : {
"id" : "obj-7",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 193.0, 342.0, 121.0, 20.0 ],
"text" : "Spectral centroid"
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-9",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 193.0, 317.0, 87.0, 22.0 ],
"sig" : 2408.747314453125
}
}
, {
"box" : {
"id" : "obj-11",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 193.0, 288.0, 152.0, 22.0 ],
"text" : "nn~ features centroid 8192"
}
}
, {
"box" : {
"id" : "obj-2",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 247.0, 243.0, 44.0, 22.0 ],
"text" : "noise~"
}
}
, {
"box" : {
"id" : "obj-71",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 32.0, 91.0, 505.0, 20.0 ],
"text" : "Check the \"scripting\" documentation to see how to code your own nn~ models in Python :)"
}
}
, {
"box" : {
"id" : "obj-68",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 461.0, 305.0, 73.0, 20.0 ],
"text" : "Saturate"
}
}
, {
"box" : {
"id" : "obj-67",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 461.0, 289.0, 73.0, 20.0 ],
"text" : "DC Invert"
}
}
, {
"box" : {
"id" : "obj-66",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 461.0, 273.0, 73.0, 20.0 ],
"text" : "Mute"
}
}
, {
"box" : {
"id" : "obj-63",
"maxclass" : "ezdac~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 367.0, 381.0, 45.0, 45.0 ]
}
}
, {
"box" : {
"disabled" : [ 0, 0, 0 ],
"id" : "obj-62",
"itemtype" : 0,
"maxclass" : "radiogroup",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "" ],
"parameter_enable" : 0,
"patching_rect" : [ 441.0, 274.0, 18.0, 50.0 ],
"size" : 3,
"value" : 0
}
}
, {
"box" : {
"id" : "obj-60",
"maxclass" : "newobj",
"numinlets" : 3,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 367.0, 341.0, 68.0, 22.0 ],
"text" : "selector~ 2"
}
}
, {
"box" : {
"id" : "obj-57",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "multichannelsignal" ],
"patching_rect" : [ 625.0, 487.0, 92.0, 22.0 ],
"text" : "mc.mixdown~ 1"
}
}
, {
"box" : {
"fontsize" : 12.0,
"id" : "obj-56",
"maxclass" : "newobj",
"numinlets" : 4,
"numoutlets" : 1,
"outlettype" : [ "multichannelsignal" ],
"patching_rect" : [ 625.0, 449.0, 220.0, 22.0 ],
"text" : "mc.pack~ 4"
}
}
, {
"box" : {
"id" : "obj-54",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 492.0, 233.0, 114.0, 22.0 ],
"text" : "nn~ effects saturate"
}
}
, {
"box" : {
"id" : "obj-53",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 367.0, 233.0, 100.0, 22.0 ],
"text" : "nn~ effects invert"
}
}
, {
"box" : {
"id" : "obj-52",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 625.0, 151.0, 346.0, 20.0 ],
"text" : "Waveform-to-multiple waveform deep model example"
}
}
, {
"box" : {
"id" : "obj-51",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 367.0, 152.0, 212.0, 20.0 ],
"text" : "Waveform-to-waveform examples"
}
}
, {
"box" : {
"id" : "obj-50",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 32.0, 152.0, 212.0, 20.0 ],
"text" : "Waveform-to-label examples"
}
}
, {
"box" : {
"fontsize" : 18.0,
"id" : "obj-37",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 173.0, 14.0, 532.0, 27.0 ],
"text" : "Adding your own Python-scripted real-time deep models"
}
}
, {
"box" : {
"fontsize" : 48.0,
"id" : "obj-40",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 14.0, 14.0, 149.0, 62.0 ],
"text" : "nn~"
}
}
, {
"box" : {
"id" : "obj-4",
"linecount" : 2,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 174.0, 40.0, 453.0, 33.0 ],
"text" : "Here we demonstrate how nn~ can actually host any type of models scripted from Python by using the Torchscript formalism"
}
}
, {
"box" : {
"basictuning" : 440,
"data" : {
"clips" : [ {
"absolutepath" : "social.aif",
"filename" : "social.aif",
"filekind" : "audiofile",
"id" : "u068005979",
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-49",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 367.0, 183.0, 150.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"saved_attribute_attributes" : {
"candicane2" : {
"expression" : ""
}
,
"candicane3" : {
"expression" : ""
}
,
"candicane4" : {
"expression" : ""
}
,
"candicane5" : {
"expression" : ""
}
,
"candicane6" : {
"expression" : ""
}
,
"candicane7" : {
"expression" : ""
}
,
"candicane8" : {
"expression" : ""
}
}
,
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"fontface" : 1,
"fontsize" : 16.0,
"id" : "obj-48",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 367.0, 126.0, 212.0, 24.0 ],
"text" : "Audio effects"
}
}
, {
"box" : {
"fontface" : 1,
"fontsize" : 16.0,
"id" : "obj-47",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 625.0, 126.0, 260.0, 24.0 ],
"text" : "Deep audio source separation"
}
}
, {
"box" : {
"basictuning" : 440,
"clipheight" : 29.0,
"data" : {
"clips" : [ {
"absolutepath" : "Macintosh HD:/Users/esling/Downloads/Massive Attack - Angel [YTmp3.net].mp3",
"filename" : "Massive Attack - Angel [YTmp3.net].mp3",
"filekind" : "audiofile",
"id" : "u418005003",
"selection" : [ 0.442176870748299, 0.707482993197279 ],
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-44",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 792.0, 183.0, 143.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"saved_attribute_attributes" : {
"candicane2" : {
"expression" : ""
}
,
"candicane3" : {
"expression" : ""
}
,
"candicane4" : {
"expression" : ""
}
,
"candicane5" : {
"expression" : ""
}
,
"candicane6" : {
"expression" : ""
}
,
"candicane7" : {
"expression" : ""
}
,
"candicane8" : {
"expression" : ""
}
}
,
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"fontface" : 1,
"fontsize" : 16.0,
"id" : "obj-42",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 32.0, 126.0, 212.0, 24.0 ],
"text" : "Audio features"
}
}
, {
"box" : {
"id" : "obj-39",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 160.0, 429.0, 121.0, 20.0 ],
"text" : "Spectral bandwidth"
}
}
, {
"box" : {
"id" : "obj-38",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 32.0, 362.0, 78.0, 20.0 ],
"text" : "RMS (dB)"
}
}
, {
"box" : {
"id" : "obj-35",
"maxclass" : "gain~",
"multichannelvariant" : 0,
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "signal", "" ],
"parameter_enable" : 0,
"patching_rect" : [ 32.0, 222.0, 37.0, 64.0 ]
}
}
, {
"box" : {
"fontface" : 1,
"id" : "obj-34",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 844.0, 269.0, 51.0, 20.0 ],
"text" : "Others"
}
}
, {
"box" : {
"fontface" : 1,
"id" : "obj-33",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 774.0, 269.0, 51.0, 20.0 ],
"text" : "Bass"
}
}
, {
"box" : {
"fontface" : 1,
"id" : "obj-32",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 640.0, 269.0, 51.0, 20.0 ],
"text" : "Vocal"
}
}
, {
"box" : {
"fontface" : 1,
"id" : "obj-31",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 705.0, 269.0, 52.0, 20.0 ],
"text" : "Drums"
}
}
, {
"box" : {
"id" : "obj-29",
"maxclass" : "gain~",
"multichannelvariant" : 0,
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "signal", "" ],
"parameter_enable" : 0,
"patching_rect" : [ 826.0, 293.0, 35.0, 137.0 ]
}
}
, {
"box" : {
"id" : "obj-27",
"maxclass" : "gain~",
"multichannelvariant" : 0,
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "signal", "" ],
"parameter_enable" : 0,
"patching_rect" : [ 759.0, 293.0, 35.0, 137.0 ]
}
}
, {
"box" : {
"id" : "obj-26",
"maxclass" : "gain~",
"multichannelvariant" : 0,
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "signal", "" ],
"parameter_enable" : 0,
"patching_rect" : [ 692.0, 293.0, 35.0, 137.0 ]
}
}
, {
"box" : {
"id" : "obj-24",
"maxclass" : "gain~",
"multichannelvariant" : 0,
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "signal", "" ],
"parameter_enable" : 0,
"patching_rect" : [ 625.0, 295.0, 35.0, 137.0 ]
}
}
, {
"box" : {
"basictuning" : 440,
"data" : {
"clips" : [ {
"absolutepath" : "social.aif",
"filename" : "social.aif",
"filekind" : "audiofile",
"id" : "u068005979",
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-22",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 625.0, 183.0, 150.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"saved_attribute_attributes" : {
"candicane2" : {
"expression" : ""
}
,
"candicane3" : {
"expression" : ""
}
,
"candicane4" : {
"expression" : ""
}
,
"candicane5" : {
"expression" : ""
}
,
"candicane6" : {
"expression" : ""
}
,
"candicane7" : {
"expression" : ""
}
,
"candicane8" : {
"expression" : ""
}
}
,
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"id" : "obj-18",
"maxclass" : "live.dial",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "", "float" ],
"parameter_enable" : 1,
"patching_rect" : [ 160.0, 174.0, 41.0, 48.0 ],
"saved_attribute_attributes" : {
"valueof" : {
"parameter_longname" : "live.dial",
"parameter_mmax" : 1000.0,
"parameter_mmin" : 40.0,
"parameter_modmode" : 3,
"parameter_osc_name" : "",
"parameter_shortname" : "Frequency",
"parameter_type" : 0,
"parameter_unitstyle" : 0
}
}
,
"varname" : "live.dial"
}
}
, {
"box" : {
"id" : "obj-14",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 32.0, 187.0, 66.0, 22.0 ],
"text" : "cycle~ 500"
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-15",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 32.0, 336.0, 87.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"id" : "obj-16",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 32.0, 294.0, 99.0, 22.0 ],
"text" : "nn~ features rms"
}
}
, {
"box" : {
"id" : "obj-10",
"maxclass" : "ezdac~",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 625.0, 547.0, 45.0, 45.0 ]
}
}
, {
"box" : {
"id" : "obj-1",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 4,
"outlettype" : [ "signal", "signal", "signal", "signal" ],
"patching_rect" : [ 625.0, 233.0, 220.0, 22.0 ],
"text" : "nn~ unmix forward 16384"
}
}
, {
"box" : {
"id" : "obj-8",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 160.0, 243.0, 60.0, 22.0 ],
"text" : "saw~ 500"
}
}
, {
"box" : {
"fontface" : 0,
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-5",
"maxclass" : "number~",
"mode" : 2,
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "signal", "float" ],
"patching_rect" : [ 160.0, 404.0, 87.0, 22.0 ],
"sig" : 0.0
}
}
, {
"box" : {
"id" : "obj-3",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 160.0, 375.0, 134.0, 22.0 ],
"text" : "nn~ features bandwidth"
}
}
],
"lines" : [ {
"patchline" : {
"destination" : [ "obj-24", 0 ],
"source" : [ "obj-1", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-26", 0 ],
"source" : [ "obj-1", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-27", 0 ],
"source" : [ "obj-1", 2 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-29", 0 ],
"source" : [ "obj-1", 3 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-9", 0 ],
"source" : [ "obj-11", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-35", 0 ],
"source" : [ "obj-14", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-15", 0 ],
"source" : [ "obj-16", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 0 ],
"order" : 0,
"source" : [ "obj-18", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-8", 0 ],
"order" : 1,
"source" : [ "obj-18", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"source" : [ "obj-22", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-56", 0 ],
"source" : [ "obj-24", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-56", 1 ],
"source" : [ "obj-26", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-56", 2 ],
"source" : [ "obj-27", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-56", 3 ],
"source" : [ "obj-29", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-5", 0 ],
"source" : [ "obj-3", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-16", 0 ],
"source" : [ "obj-35", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"midpoints" : [ 801.5, 222.5, 634.5, 222.5 ],
"source" : [ "obj-44", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-53", 0 ],
"order" : 1,
"source" : [ "obj-49", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-54", 0 ],
"midpoints" : [ 376.5, 223.85546875, 501.5, 223.85546875 ],
"order" : 0,
"source" : [ "obj-49", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-60", 1 ],
"midpoints" : [ 376.5, 265.27734375, 401.0, 265.27734375 ],
"source" : [ "obj-53", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-60", 2 ],
"midpoints" : [ 501.5, 263.68359375, 425.5, 263.68359375 ],
"source" : [ "obj-54", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-57", 0 ],
"source" : [ "obj-56", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-10", 1 ],
"order" : 0,
"source" : [ "obj-57", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-10", 0 ],
"order" : 1,
"source" : [ "obj-57", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-63", 1 ],
"order" : 0,
"source" : [ "obj-60", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-63", 0 ],
"order" : 1,
"source" : [ "obj-60", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-60", 0 ],
"midpoints" : [ 450.5, 331.5, 376.5, 331.5 ],
"source" : [ "obj-62", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-11", 0 ],
"order" : 0,
"source" : [ "obj-8", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-3", 0 ],
"order" : 1,
"source" : [ "obj-8", 0 ]
}
}
],
"originid" : "pat-10",
"parameters" : {
"obj-18" : [ "live.dial", "Frequency", 0 ],
"parameterbanks" : {
"0" : {
"index" : 0,
"name" : "",
"parameters" : [ "-", "-", "-", "-", "-", "-", "-", "-" ]
}
}
,
"inherited_shortname" : 1
}
,
"dependency_cache" : [ {
"name" : "Massive Attack - Angel [YTmp3.net].mp3",
"bootpath" : "~/Downloads",
"patcherrelativepath" : "../../../Downloads",
"type" : "Mp3",
"implicit" : 1
}
, {
"name" : "nn~.mxo",
"type" : "iLaX"
}
, {
"name" : "social.aif",
"bootpath" : "C74:/packages/max-mxj/examples",
"type" : "AIFF",
"implicit" : 1
}
],
"autosave" : 0
}
}
================================================
FILE: scripting/unmix.py
================================================
#
# NN~ - Scripting library
# unmix.py : Advanced scripting example for integrating a deep waveform-to-waveform model.
#
# We provide here a simple example of how to use nn~ in order to transform incoming audio.
# In this example, we do not rely on any ML model, but simply apply effects on input buffers.
#
# ACIDS - IRCAM : Philippe Esling, Axel Chemla--Romeu-Santos, Antoine Caillon
#
# System imports
from typing import List, Tuple
import os
import math
# Pytorch imports
import torch
import torch.nn as nn
import torch
import torchaudio
# NN~ imports
import nn_tilde
class Unmix(nn_tilde.Module):
def __init__(self,
pretrained):
super().__init__()
# REGISTER ATTRIBUTES
self.register_attribute('sr', 44100)
self.pretrained = pretrained
# REGISTER METHODS
self.register_method(
'forward',
in_channels=1,
in_ratio=1,
out_channels=4,
out_ratio=1,
input_labels=['(signal) signal to monitor'],
output_labels=['drums', 'bass', 'vocals', 'others'],
)
@torch.jit.export
def forward(self, input: torch.Tensor):
# Preprocess the input buffer (representation)
in_r = preprocess(input, int(self.sr[0]), int(self.pretrained.sample_rate))
# Pass through the deep audio separation
out = self.pretrained(in_r)
# Return the separated channels
return out.mean(dim=2)
# defining attribute getters
# WARNING : typing the function's ouptut is mandatory
@torch.jit.export
def get_sr(self) -> int:
return int(self.sr[0])
# defining attribute setter
# setters must return an error code :
# return 0 if the attribute has been adequately set,
# return -1 if the attribute was wrong.
@torch.jit.export
def set_sr(self, x: int) -> int:
self.sr = (x, )
return 0
def preprocess(
audio: torch.Tensor,
rate: int,
model_rate: int,
) -> torch.Tensor:
"""
From an input tensor, convert it to a tensor of shape
shape=(nb_samples, nb_channels, nb_timesteps). This includes:
- if input is 1D, adding the samples and channels dimensions.
- if input is 2D
o and the smallest dimension is 1 or 2, adding the samples one.
o and all dimensions are > 2, assuming the smallest is the samples
one, and adding the channel one
- at the end, if the number of channels is greater than the number
of time steps, swap those two.
- resampling to target rate if necessary
Args:
audio (Tensor): input waveform
rate (float): sample rate for the audio
model_rate (float): sample rate for the model
Returns:
Tensor: [shape=(nb_samples, nb_channels=2, nb_timesteps)]
"""
shape = torch.as_tensor(audio.shape, device=audio.device)
if len(shape) == 1:
# assuming only time dimension is provided.
audio = audio[None, None, ...]
elif len(shape) == 2:
if shape.min() <= 2:
# assuming sample dimension is missing
audio = audio[None, ...]
else:
# assuming channel dimension is missing
audio = audio[:, None, ...]
if audio.shape[1] > audio.shape[2]:
# swapping channel and time
audio = audio.transpose(1, 2)
if audio.shape[1] > 2:
audio = audio[..., :2]
if audio.shape[1] == 1:
# if we have mono, we duplicate it to get stereo
audio = torch.repeat_interleave(audio, 2, dim=1)
if rate != model_rate:
# we have to resample to model samplerate if needed
# this makes sure we resample input only once
audio = torchaudio.functional.resample(audio,
orig_freq=rate, new_freq=model_rate, resampling_method="sinc_interpolation"
).to(audio.device)
return audio
if __name__ == '__main__':
pretrained = torch.jit.load("unmix.pt") # Pretrained weights
model = Unmix(pretrained)
model.export_to_ts('unmix.ts')
================================================
FILE: setup.py
================================================
import os
import setuptools
VERSION = os.environ["NN_TILDE_VERSION"]
with open("README.md", "r") as readme:
readme = readme.read()
with open("requirements.txt", "r") as requirements:
requirements = requirements.read()
setuptools.setup(
name="nn_tilde",
version=VERSION,
author="Antoine CAILLON & Axel CHEMLA--ROMEU-SANTOS",
author_email="chemla@ircam.fr",
description="Set of tools to create nn_tilde compatible models.",
long_description=readme,
long_description_content_type="text/markdown",
packages=['nn_tilde', 'nn_tilde.templates'],
package_dir={'nn_tilde': 'python_tools'},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
install_requires=requirements.split("\n"),
python_requires='>=3.11',
)
================================================
FILE: src/.nojekyll
================================================
================================================
FILE: src/CMakeLists.txt
================================================
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
project(nn_tilde)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
configure_file(
"${CMAKE_SOURCE_DIR}/../install/max-linker-flags.txt" "${CMAKE_SOURCE_DIR}/frontend/maxmsp/min-api/max-sdk-base/script/max-linker-flags.txt"
COPYONLY
)
if (NOT DEFINED SIGN_ID)
if (DEFINED $ENV{SIGN_ID})
set(SIGN_ID $ENV{SIGN_ID})
else()
set(SIGN_ID "-")
endif()
endif()
message("Copying ${CMAKE_SOURCE_DIR}/../install/MaxAPI.lib" "${CMAKE_SOURCE_DIR}/frontend/maxmsp/min-api/max-sdk-base/c74support/max-includes/x64" )
configure_file(
"${CMAKE_SOURCE_DIR}/../install/MaxAPI.lib" "${CMAKE_SOURCE_DIR}/frontend/maxmsp/min-api/max-sdk-base/c74support/max-includes/x64/MaxAPI.lib"
COPYONLY
)
configure_file(
"${CMAKE_SOURCE_DIR}/../install/patch_with_vst.sh" "${CMAKE_SOURCE_DIR}/extras"
COPYONLY
)
include(${CMAKE_SOURCE_DIR}/cmake/add_torch.cmake)
list(PREPEND CMAKE_PREFIX_PATH "${torch_dir}/libtorch")
find_package(Torch REQUIRED PATHS ${torch_dir}/libtorch/lib)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")
set(CONDA_ENV_PATH "${CMAKE_SOURCE_DIR}/../env")
if (MSVC)
set(CMAKE_PREFIX_PATH "${CMAKE_PREFIX_PATH}:${CONDA_ENV_PATH}")
else()
set(CMAKE_PREFIX_PATH "${CMAKE_PREFIX_PATH};${CONDA_ENV_PATH}")
endif()
if (APPLE)
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.12")
endif()
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(SET CMP00076)
# import json
add_subdirectory(json)
if (UNIX)
if (APPLE)
add_compile_options(-std=c++20)
set(CMAKE_CXX_FLAGS "-faligned-allocation")
if (CMAKE_OSX_ARCHITECTURES STREQUAL "")
set(CMAKE_OSX_ARCHITECTURES ${CMAKE_HOST_SYSTEM_PROCESSOR})
endif()
message("Building for architecture : ${CMAKE_OSX_ARCHITECTURES} ")
endif()
endif()
add_subdirectory(backend) # DEEP LEARNING BACKEND
execute_process(
COMMAND git describe --tags
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
OUTPUT_VARIABLE VERSION
OUTPUT_STRIP_TRAILING_WHITESPACE
)
if (NOT DEFINED NO_PUREDATA)
set(NO_PUREDATA 0)
endif()
if (NO_PUREDATA EQUAL 0)
if ("${PUREDATA_INCLUDE_DIR}" STREQUAL "")
set(PUREDATA_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/pd_include")
execute_process(
COMMAND cmake -E make_directory "${PUREDATA_INCLUDE_DIR}"
)
file(DOWNLOAD "https://raw.githubusercontent.com/pure-data/pure-data/master/src/m_pd.h" "${PUREDATA_INCLUDE_DIR}/m_pd.h")
endif()
add_subdirectory(frontend/puredata/nn_tilde) # PURE DATA EXTERNAL
else()
if (UNIX AND NOT APPLE)
message(FATAL_ERROR "NO_PUREDATA needs to be off on Linux, otherwise no task are available")
endif()
endif()
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/../package-info.json.in "${CMAKE_CURRENT_SOURCE_DIR}/package-info.json")
if(APPLE OR MSVC)
# MAX MSP EXTERNAL
add_subdirectory(frontend/maxmsp/nn.info)
add_subdirectory(frontend/maxmsp/nn_tilde)
add_subdirectory(frontend/maxmsp/mc.nn_tilde)
add_subdirectory(frontend/maxmsp/mcs.nn_tilde)
endif()
================================================
FILE: src/backend/CMakeLists.txt
================================================
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
project(backend)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")
add_library(backend STATIC parsing_utils.cpp backend.cpp)
target_link_libraries(backend "${TORCH_LIBRARIES}")
set_property(TARGET backend PROPERTY CXX_STANDARD 20)
if(MSVC)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")
set(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} /MT")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /MT")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MT")
endif()
================================================
FILE: src/backend/backend.cpp
================================================
#include "backend.h"
#include
#include "parsing_utils.h"
#include
#include
#include
#include
#include
#define CPU torch::kCPU
#define CUDA torch::kCUDA
#define MPS torch::kMPS
#define REFRESH_THREAD_INTERVAL 50
std::string tensor_to_str(torch::Tensor &tsr) {
std::stringstream ss;
ss << "Tensor(dim: ";
for (int i = 0; i < tsr.dim(); i++) {
ss << tsr.size(i);
if (i != tsr.dim() - 1)
ss << ", ";
}
ss << ")";
return ss.str();
}
Backend::Backend() : m_loaded(0), m_device(CPU), m_use_gpu(false) {
at::init_num_threads();
}
void Backend::perform(std::vector &in_buffer,
std::vector &out_buffer,
std::string method,
int n_batches, int n_out_channels, int n_vec) {
c10::InferenceMode guard;
auto params = get_method_params(method);
if (!params.size())
return;
auto in_dim = params[0];
auto in_ratio = params[1];
auto out_dim = params[2];
auto out_ratio = params[3];
if (!m_loaded)
return;
// COPY BUFFER INTO A TENSOR
std::vector tensor_in;
// for (auto buf : in_buffer)
for (int i(0); i < in_dim * n_batches; i++) {
if (i < in_buffer.size()) {
tensor_in.push_back(torch::from_blob(in_buffer[i], {1, 1, n_vec}).clone());
} else {
tensor_in.push_back(torch::zeros({1, 1, n_vec}));
}
}
auto cat_tensor_in = torch::cat(tensor_in, 1);
cat_tensor_in = cat_tensor_in.reshape({in_dim, n_batches, -1, in_ratio});
cat_tensor_in = cat_tensor_in.select(-1, -1);
cat_tensor_in = cat_tensor_in.permute({1, 0, 2});
// SEND TENSOR TO DEVICE
std::unique_lock model_lock(m_model_mutex);
cat_tensor_in = cat_tensor_in.to(m_device);
std::vector inputs = {cat_tensor_in};
auto kwargs = empty_kwargs();
// PROCESS TENSOR
at::Tensor tensor_out;
try {
tensor_out = m_model.get_method(method)(inputs, kwargs).toTensor();
tensor_out = tensor_out.repeat_interleave(out_ratio).reshape(
{n_batches, out_dim, -1});
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
return;
}
model_lock.unlock();
int out_batches(tensor_out.size(0)), out_channels(tensor_out.size(1)),
out_n_vec(tensor_out.size(2));
if (out_n_vec != n_vec) {
std::cout << "model output size is not consistent, expected " << n_vec
<< " samples, got " << out_n_vec << "!\n";
return;
}
tensor_out = tensor_out.to(CPU);
for (int i(0); i < n_out_channels; i++) {
for (int j(0); j < n_batches; j++) {
if (i < tensor_out.size(1)) {
auto out_ptr = tensor_out.index({j, i}).contiguous().data_ptr();
memcpy(out_buffer[j * n_out_channels + i], out_ptr, n_vec * sizeof(float));
} else {
// put zeros
memset(out_buffer[j * n_out_channels + i], 0, n_vec *sizeof(float));
}
}
}
}
int Backend::load(std::string path, double sampleRate, const std::string* target_method) {
try {
auto model = torch::jit::load(path);
if (target_method != nullptr) {
if (!(*target_method).empty()) {
// if target_method is not null, check if loaded model has it
auto locked_model = LockedModel();
locked_model.model = &model;
auto methods = get_available_methods(&locked_model);
if (std::find(methods.begin(), methods.end(), *target_method) == methods.end()) {
throw "path " + path + " does not contain target method " + (*target_method);
}
}
}
model.eval();
model.to(m_device);
std::unique_lock model_lock(m_model_mutex);
m_model = model;
model_lock.unlock();
m_available_methods = get_available_methods();
m_buffer_attributes = retrieve_buffer_attributes();
m_path = path;
set_sample_rate(sampleRate);
m_loaded = 1;
return 0;
} catch (const std::exception &e) {
throw "problem loading model " + path + ". Exception : " + e.what();
}
}
void Backend::set_sample_rate(double sampleRate) {
if (has_method("set_sample_rate")) {
m_sr = sampleRate;
std::vector sr_input = {sampleRate};
std::unique_lock model_lock(m_model_mutex);
auto args = empty_args(); args.push_back((int)sampleRate);
auto kwargs = empty_kwargs();
std::string method_name = "set_sample_rate";
m_model.get_method(method_name)(args, kwargs);
model_lock.unlock();
}
}
int Backend::reload() {
auto return_code = load(m_path, m_sr);
return return_code;
}
bool Backend::has_method(std::string method_name) {
if (!is_loaded()){
return false;
}
std::unique_lock model_lock(m_model_mutex);
for (const auto &m : m_model.get_methods()) {
if (m.name() == method_name)
return true;
}
return false;
}
bool Backend::has_settable_attribute(std::string attribute) {
for (const auto &a : get_settable_attributes()) {
if (a == attribute)
return true;
}
return false;
}
std::vector Backend::get_available_methods(LockedModel *target_model) {
std::vector methods;
torch::jit::script::Module *model;
std::mutex *mutex;
if (target_model == nullptr) {
model = &m_model;
mutex = &m_model_mutex;
} else {
model = target_model->model;
mutex = &target_model->mutex;
}
try {
std::vector dumb_input = {};
std::unique_lock model_lock(*mutex);
auto methods_from_model =
model->get_method("get_methods")(dumb_input).toList();
model_lock.unlock();
for (int i = 0; i < methods_from_model.size(); i++) {
methods.push_back(methods_from_model.get(i).toStringRef());
}
} catch (...) {
std::unique_lock model_lock(*mutex);
for (const auto &m : model->get_methods()) {
try {
auto method_params = model->attr(m.name() + "_params");
methods.push_back(m.name());
} catch (...) {
}
}
model_lock.unlock();
}
return methods;
}
std::vector Backend::get_available_attributes() {
std::vector attributes;
std::unique_lock model_lock(m_model_mutex);
for (const auto &attribute : m_model.named_attributes())
attributes.push_back(attribute.name);
return attributes;
}
std::vector Backend::get_settable_attributes() {
std::vector attributes;
try {
std::vector dumb_input = {};
std::unique_lock model_lock(m_model_mutex);
auto methods_from_model =
m_model.get_method("get_attributes")(dumb_input).toList();
model_lock.unlock();
for (int i = 0; i < methods_from_model.size(); i++) {
auto attr_name = methods_from_model.get(i).toStringRef();
if (attr_name != "none") {
attributes.push_back(attr_name);
}
}
} catch (...) {
std::unique_lock model_lock(m_model_mutex);
for (const auto &a : m_model.named_attributes()) {
try {
auto method_params = m_model.attr(a.name + "_params");
if (a.name != "none") {
attributes.push_back(a.name);
}
} catch (...) {
}
}
model_lock.unlock();
}
return attributes;
}
std::vector Backend::get_attribute(std::string attribute_name) {
std::string attribute_getter_name = "get_" + attribute_name;
std::unique_lock model_lock(m_model_mutex);
try {
auto attribute_getter = m_model.get_method(attribute_getter_name);
} catch (...) {
model_lock.unlock();
throw "getter for attribute " + attribute_name + " not found in model";
}
std::vector getter_inputs = {}, attributes;
auto kwargs = empty_kwargs();
try {
try {
auto output_list = m_model.get_method(attribute_getter_name)(getter_inputs, kwargs).toList();
attributes = output_list.vec();
} catch (...) {
auto output_tuple_ref =
m_model.get_method(attribute_getter_name)(getter_inputs, kwargs).toTuple();
attributes = (*output_tuple_ref.get()).elements();
}
} catch (...) {
model_lock.unlock();
throw ("could not access method " + attribute_getter_name + " from original script.");
}
model_lock.unlock();
return attributes;
}
std::string Backend::get_attribute_as_string(std::string attribute_name) {
std::vector getter_outputs = get_attribute(attribute_name);
// finstringd arguments
torch::Tensor setter_params;
std::unique_lock model_lock(m_model_mutex);
try {
setter_params = m_model.attr(attribute_name + "_params").toTensor();
model_lock.unlock();
} catch (...) {
model_lock.unlock();
throw "parameters to get attribute " + attribute_name +
" not found in model";
}
std::string current_attr = "";
for (int i = 0; i < setter_params.size(0); i++) {
int current_id = setter_params[i].item().toInt();
switch (current_id) {
// bool case
case 0: {
current_attr += (getter_outputs[i].toBool()) ? "true" : "false";
break;
}
// int case
case 1: {
current_attr += std::to_string(getter_outputs[i].toInt());
break;
}
// float case
case 2: {
float result = getter_outputs[i].to();
current_attr += std::to_string(result);
break;
}
// str case
case 3: {
current_attr += getter_outputs[i].toStringRef();
break;
}
// tensor case
case 4: {
auto tensor = getter_outputs[i].toTensor();
current_attr += tensor_to_str(tensor);
break;
}
case 5: {
current_attr += getter_outputs[i].toStringRef();
break;
}
default: {
throw "bad type id : " + std::to_string(current_id) + " at index " +
std::to_string(i);
break;
}
}
if (i < setter_params.size(0) - 1)
current_attr += " ";
}
return current_attr;
}
void Backend::set_attribute(std::string attribute_name,
std::vector attribute_args,
const Backend::BufferMap &buffer_array) {
// find setter
std::string attribute_setter_name = "set_" + attribute_name;
std::unique_lock model_lock(m_model_mutex);
try {
auto attribute_setter = m_model.get_method(attribute_setter_name);
} catch (...) {
model_lock.unlock();
throw "setter for attribute " + attribute_name + " not found in model";
}
// find arguments
torch::Tensor setter_params;
try {
setter_params = m_model.attr(attribute_name + "_params").toTensor();
} catch (...) {
model_lock.unlock();
throw "parameters to set attribute " + attribute_name +
" not found in model";
}
model_lock.unlock();
// check attribute params
int setter_elements = setter_params.numel();
if (attribute_args.size() != setter_elements) {
std::stringstream exception;
exception << "wrong number of elements : setter seems to have " << std::to_string(setter_params.numel());
exception << ", but " << attribute_args.size() << " was given";
throw exception.str();
}
// process inputs
std::vector setter_inputs = {};
auto n_args = setter_params.size(0);
for (int i = 0; i < n_args; i++) {
int current_id = setter_params[i].item().toInt();
switch (current_id) {
// bool case
case 0:
setter_inputs.push_back(c10::IValue(to_bool(attribute_args[i])));
break;
// int case
case 1:
setter_inputs.push_back(c10::IValue(to_int(attribute_args[i])));
break;
// float case
case 2:
setter_inputs.push_back(c10::IValue(to_float(attribute_args[i])));
break;
// str case
case 3:
setter_inputs.push_back(c10::IValue(attribute_args[i]));
break;
// tensor case
case 4: {
auto buffer_name = get_buffer_name(attribute_name, i);
if (!buffer_array.contains(buffer_name)) {
throw std::string("buffer for argument ") + buffer_name + std::string(" not found. Did you initialise it?");
} else {
auto buffer = buffer_array.at(buffer_name);
auto buf_tensor = buffer.to_tensor().index({0});
setter_inputs.push_back(buf_tensor.clone());
}
break;
}
case 5: {
auto buffer_name = get_buffer_name(attribute_name, i);
if (!buffer_array.contains(buffer_name)) {
throw std::string("buffer for argument ") + buffer_name + std::string(" not found. Did you initialise it?");
} else {
auto buffer = buffer_array.at(buffer_name);
update_buffer(buffer_name, buffer);
setter_inputs.push_back(c10::IValue(buffer_name));
}
break;
}
default:
throw "bad type id : " + std::to_string(current_id) + "at index " +
std::to_string(i);
break;
}
}
try {
std::unique_lock model_lock(m_model_mutex);
auto kwargs = empty_kwargs();
auto setter_out = m_model.get_method(attribute_setter_name)(setter_inputs, kwargs);
model_lock.unlock();
int setter_result = setter_out.toInt();
if (setter_result != 0) {
throw "setter returned -1";
}
} catch (std::string &e) {
throw "setter for " + attribute_name + " failed : " + e;
} catch (std::exception &e) {
throw "setter for " + attribute_name + " failed : " + e.what();
} catch (...) {
throw "setter for " + attribute_name + " failed";
}
}
std::vector Backend::get_method_params(std::string method) {
std::vector params;
if (std::find(m_available_methods.begin(), m_available_methods.end(),
method) != m_available_methods.end()) {
try {
std::unique_lock model_lock(m_model_mutex);
auto p = m_model.attr(method + "_params").toTensor();
model_lock.unlock();
for (int i(0); i < 4; i++)
params.push_back(p[i].item().to());
} catch (...) {
}
}
return params;
}
int Backend::get_higher_ratio() {
int higher_ratio = 1;
for (const auto &method : m_available_methods) {
auto params = get_method_params(method);
if (!params.size())
continue; // METHOD NOT USABLE, SKIPPING
int max_ratio = std::max(params[1], params[3]);
higher_ratio = std::max(higher_ratio, max_ratio);
}
return higher_ratio;
}
bool Backend::is_loaded() { return m_loaded; }
void Backend::use_gpu(bool value) {
std::unique_lock model_lock(m_model_mutex);
if (value) {
if (torch::hasCUDA()) {
std::cout << "sending model to cuda" << std::endl;
m_device = CUDA;
} else if (torch::hasMPS()) {
std::cout << "sending model to mps" << std::endl;
m_device = MPS;
} else {
std::cout << "sending model to cpu" << std::endl;
m_device = CPU;
}
} else {
m_device = CPU;
}
m_model.to(m_device);
}
std::string Backend::get_buffer_name(std::string attribute_name, int attribute_elt_idx) {
return attribute_name + "#" + std::to_string(attribute_elt_idx);
}
bool Backend::is_buffer_element_of_attribute(std::string attribute_name, int attribute_elt_idx) {
std::string target_buffer_name = get_buffer_name(attribute_name, attribute_elt_idx);
// std::cout << "current registered buffers : " << m_buffer_attributes.size() << std::endl;
for (auto buffer_name: m_buffer_attributes) {
// std::cout << "target buffer name : " << target_buffer_name << "; compared buffer name : " << buffer_name << std::endl;
if (buffer_name == target_buffer_name) {
return true;
}
}
return false;
}
bool Backend::is_tensor_element_of_attribute(std::string attribute_name, int attribute_elt_idx) {
auto attribute_params = m_model.attr(attribute_name + "_params").toTensor();
if (id_to_string_hash.at(attribute_params.item().toInt()) == "tensor") {
return true;
} else {
return false;
}
}
std::vector Backend::retrieve_buffer_attributes() {
std::vector bufferNames = {};
std::string getter_name = "get_buffer_attributes";
if (has_method(getter_name)) {
std::unique_lock model_lock(m_model_mutex);
try {
auto model_method = m_model.get_method(getter_name);
auto model_out = model_method(empty_args(), empty_kwargs()).toList().vec();
for (int i = 0; i < model_out.size(); i++) {
// std::cout << "adding " << model_out[i].toStringRef() << " to buffer list" << std::endl;
bufferNames.push_back(model_out[i].toStringRef());
}
model_lock.unlock();
} catch (std::exception& e) {
model_lock.unlock();
throw e;
}
}
return bufferNames;
}
std::vector Backend::get_buffer_attributes() {
return m_buffer_attributes;
}
int Backend::reset_buffer(std::string buffer_name) {
std::string clear_method = "clear_buffer_attribute";
auto args = empty_args(); auto kwargs = empty_kwargs();
args.push_back(buffer_name);
std::unique_lock model_lock(m_model_mutex);
auto model_out = m_model.get_method(clear_method)(args, kwargs);
int result = model_out.toInt();
return result;
}
int Backend::update_buffer(std::string buffer_name, StaticBuffer &buffer) {
std::string setter_method = "set_buffer_attribute";
auto args = empty_args(); auto kwargs = empty_kwargs();
auto tensor = buffer.to_tensor().to(m_device); auto sr = static_cast(buffer.sr());
// auto tensor_min = tensor.min(); auto tensor_max = tensor.max();
auto tensor_size = {tensor.size(0), tensor.size(1)};
args.push_back(buffer_name); args.push_back(tensor); args.push_back(sr);
std::unique_lock model_lock(m_model_mutex);
auto model_out = m_model.get_method(setter_method)(args, kwargs);
model_lock.unlock();
int result = model_out.toInt();
return result;
}
ModelInfo Backend::get_model_info() {
if (!m_loaded) {
throw "no model loaded; cannot retrieve model information";
}
auto methods = get_available_methods();
auto attributes = get_settable_attributes();
auto method_dict = ModelInfo::MethodDict();
auto attribute_dict = ModelInfo::AttributeDict();
std::unique_lock model_lock(m_model_mutex);
model_lock.unlock();
try {
for (auto method : methods) {
auto method_properties = MethodProperties();
model_lock.lock();
auto setter_params = m_model.attr(method + "_params").toTensor();
model_lock.unlock();
method_properties.name = method;
method_properties.channels_in = setter_params[0].item().toInt();
method_properties.ratio_in = setter_params[1].item().toInt();
method_properties.channels_out = setter_params[2].item().toInt();
method_properties.ratio_out = setter_params[3].item().toInt();
method_dict.insert({method, method_properties});
}
for (auto attribute: attributes) {
model_lock.lock();
auto attribute_params = m_model.attr(attribute + "_params").toTensor();
model_lock.unlock();
auto attribute_properties = AttributeProperties();
attribute_properties.name = attribute;
auto attribute_types = std::vector();
for (int i = 0; i < attribute_params.size(0); i++) {
auto param_idx = attribute_params[i].item().toInt();
auto param_str = this->id_to_string_hash.at(param_idx);
attribute_types.push_back(param_str);
}
attribute_properties.attribute_types = attribute_types;
attribute_dict.insert({attribute, attribute_properties});
}
auto model_info = ModelInfo();
model_info.method_properties = method_dict;
model_info.attribute_properties = attribute_dict;
return model_info;
} catch (std::exception& e) {
model_lock.unlock();
throw "error fetching model information for model " + m_path + ". Caught error : " + e.what();
}
}
================================================
FILE: src/backend/backend.h
================================================
#pragma once
#include
#include
#include
#include "../shared/static_buffer.h"
#include
#include
struct MethodProperties {
std::string name = "";
int channels_in = -1;
int channels_out = -1;
int ratio_in = -1;
int ratio_out = -1;
};
struct AttributeProperties {
std::string name = "";
std::vector attribute_types = {};
};
struct ModelInfo {
using MethodDict = std::unordered_map;
using AttributeDict = std::unordered_map;
MethodDict method_properties = {};
AttributeDict attribute_properties = {};
};
struct LockedModel {
torch::jit::script::Module* model;
std::mutex mutex;
};
class Backend {
protected:
torch::jit::script::Module m_model;
int m_loaded, m_in_dim, m_in_ratio, m_out_dim, m_out_ratio;
std::string m_path;
std::mutex m_model_mutex;
std::vector m_available_methods;
std::vector m_buffer_attributes;
c10::DeviceType m_device;
bool m_use_gpu;
std::vector retrieve_buffer_attributes();
std::unique_ptr set_attribute_thread;
double m_sr;
public:
using DataType = float;
using ArgsType = std::vector;
using KwargsType = std::unordered_map;
using BufferMap = std::map>;
Backend();
void perform(std::vector &in_buffer,
std::vector &out_buffer,
std::string method,
int n_batches, int n_out_channels, int n_vec);
bool has_method(std::string method_name);
bool has_settable_attribute(std::string attribute);
std::vector get_available_methods(LockedModel *model = nullptr);
std::vector get_available_attributes();
std::vector get_settable_attributes();
std::vector get_attribute(std::string attribute_name);
std::string get_attribute_as_string(std::string attribute_name);
void set_attribute(std::string attribute_name,
std::vector attribute_args,
const Backend::BufferMap &buffer_array);
// buffer attributes
bool is_buffer_element_of_attribute(std::string attribute_name, int attribute_elt_idx);
bool is_tensor_element_of_attribute(std::string attribute_name, int attribute_elt_idx);
// auto get_buffer_attribtues() { return m_buffer_attributes; }
std::string get_buffer_name(std::string attribute_name, int attribute_elt_idx);
int update_buffer(std::string buffer_id, StaticBuffer &buffer);
int reset_buffer(std::string);
std::vector get_method_params(std::string method);
int get_higher_ratio();
int load(std::string path, double sampleRate, const std::string* target_method = nullptr);
int reload();
void set_sample_rate(double sampleRate);
bool is_loaded();
torch::jit::script::Module get_model() { return m_model; }
void use_gpu(bool value);
std::vector get_buffer_attributes();
ArgsType empty_args() { return ArgsType(); }
KwargsType empty_kwargs() { return KwargsType(); }
std::pair empty_inputs() {
return std::make_pair(empty_args(), empty_kwargs());
}
ModelInfo get_model_info();
const std::unordered_map id_to_string_hash = {
{0, "bool"},
{1, "int"},
{2, "float"},
{3, "string"},
{4, "tensor"},
{5, "buffer"}
};
};
================================================
FILE: src/backend/parsing_utils.cpp
================================================
#include "parsing_utils.h"
bool to_bool(std::string str) {
if ((str == "0") || (str == "false")) {
return false;
} else {
return true;
}
}
int to_int(std::string str) { return stoi(str); }
float to_float(std::string str) { return stof(str); }
================================================
FILE: src/backend/parsing_utils.h
================================================
#pragma once
#include
#include
#include
#include
#include
bool to_bool(std::string str);
int to_int(std::string str);
float to_float(std::string str);
================================================
FILE: src/cmake/add_torch.cmake
================================================
set(torch_dir ${CMAKE_CURRENT_BINARY_DIR}/../torch)
set(torch_lib_name torch)
message("first looking for lib in : ${torch_dir}")
find_library(torch_lib
NAMES ${torch_lib_name}
PATHS ${torch_dir}/libtorch/lib
)
function (download_library url out)
message("download ${url} to ${out}...")
file(DOWNLOAD
${url}
${out}/torch_cc.zip
SHOW_PROGRESS
)
execute_process(COMMAND ${CMAKE_COMMAND} -E tar -xf torch_cc.zip
COMMAND remove -f ${out}/torch_cc.zip
WORKING_DIRECTORY ${out})
endfunction()
if (DEFINED torch_version)
message("setting torch version : ${torch_version}")
else()
set(torch_version "2.5.1")
message("torch version : ${torch_version}")
endif()
if (NOT torch_lib)
set(NEEDS_DL TRUE)
else()
set(NEEDS_DL FALSE)
if (UNIX AND NOT APPLE)
if (torch_lib STREQUAL "/usr/lib/libtorch.so")
set(NEEDS_DL TRUE)
endif()
endif()
endif()
if (NEEDS_DL)
message(STATUS "Downloading torch C API pre-built")
# Download
if (UNIX AND NOT APPLE) # Linux
set(torch_url "https://download.pytorch.org/libtorch/cpu/libtorch-shared-with-deps-${torch_version}%2Bcpu.zip")
download_library(${torch_url} ${torch_dir})
elseif (UNIX AND APPLE) # OSX
if (NOT IS_DIRECTORY ${torch_dir})
if (EXISTS ${CMAKE_SOURCE_DIR}/../install/torch_ub)
execute_process(COMMAND cp -r ${CMAKE_SOURCE_DIR}/../install/torch_ub ${torch_dir})
elseif(DEFINED TORCH_MAC_UB_URL)
download_library(${TORCH_MAC_UB_URL} /tmp)
execute_process(
COMMAND mkdir -p ${torch_dir}
COMMAND echo $(ls /tmp)
COMMAND mv /tmp/torch ${torch_dir}/libtorch
)
else()
execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${torch_dir})
set(torch_url "https://download.pytorch.org/libtorch/cpu/libtorch-macos-arm64-${torch_version}.zip")
download_library(${torch_url} ${torch_dir})
endif()
endif()
else()
execute_process(COMMAND ${CMAKE_COMMAND} -E make_directory ${torch_dir})
download_library("https://download.pytorch.org/libtorch/cpu/libtorch-win-shared-with-deps-${torch_version}%2Bcpu.zip" ${torch_dir})
endif()
# Check if architecutre == ARM64
# if (NOT DEFINED APPLE_ARM64)
# set (APPLE_ARM64 (CMAKE_SYSTEM_PROCESSOR STREQUAL "arm64"))
# endif()
## If ARM, download both libraries and pre-compile UB libraries
# if (APPLE_ARM64)
# download arm64 library
# if (NOT IS_DIRECTORY ${torch_dir})
# download_library("https://anaconda.org/pytorch/pytorch/${torch_version}/download/osx-arm64/pytorch-${torch_version}-py3.10_0.tar.bz2" ${torch_dir}-arm64)
# execute_process(COMMAND mkdir ${torch_dir})
# execute_process(COMMAND cp -r ${torch_dir}-arm64/lib/python3.10/site-packages/torch ${torch_dir}/libtorch)
# endif()
# # download x86 library
# if (EXISTS ${CMAKE_SOURCE_DIR}/../install/torch_x86)
# execute_process(COMMAND cp -r ${CMAKE_SOURCE_DIR}/../install/torch_x86 ${torch_dir}-x86)
# else()
# if (NOT DEFINED TORCH_MAC_UB_URL)
# message(FATAL_ERROR "If not provided, please give a valid URL for Apple universal library")
# endif()
# download_library(${TORCH_MAC_X86_URL} ${torch_dir})
# endif()
# message("found libtorch for x86 at : " ${torch_dir}-x86)
# # export UB libs to main path
# execute_process(COMMAND mkdir ${torch_dir}-x86)
# execute_process(COMMAND cp /opt/homebrew/opt/llvm/lib/libomp.dylib ${torch_dir}/libtorch/lib/)
# execute_process(COMMAND find ${torch_dir}/libtorch/lib -maxdepth 1 -type f -execdir lipo -create ${torch_dir}/libtorch/lib/{} ${torch_dir}-x86/libtorch/lib/{} -output ${torch_dir}/libtorch/lib/{} \;)
# else()
# if (EXISTS ${CMAKE_SOURCE_DIR}/../install/torch_x86)
# execute_process(COMMAND cp ${CMAKE_SOURCE_DIR}/../install/torch_x86 ${torch_dir})
# else()
# if (NOT DEFINED TORCH_MAC_X86_URL)
# message(FATAL_ERROR "If not provided, please give a valid URL for Apple x86 library")
# endif()
# download_library(${TORCH_MAC_X86_URL} ${torch_dir})
# endif()
# message("found libtorch for x86 at : " ${torch_dir})
endif()
# Find the libraries again
message("${torch_dir}")
find_library(torch_lib
NAMES ${torch_lib_name}
PATHS ${torch_dir}/libtorch/lib
)
if (NOT torch_lib)
message(FATAL_ERROR "torch could not be included")
endif()
================================================
FILE: src/extras/nn~ Overview.maxpat
================================================
{
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 9,
"minor" : 0,
"revision" : 0,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 59.0, 106.0, 1000.0, 780.0 ],
"gridsize" : [ 15.0, 15.0 ],
"boxes" : [ ],
"lines" : [ ],
"originid" : "pat-152",
"dependency_cache" : [ ],
"autosave" : 0
}
}
================================================
FILE: src/extras/patch_with_vst.sh
================================================
#!/bin/bash
# Default values
pd=0
max=0
function print_help() {
echo "Usage: $0 [--pd_path[=val]] (default: ~/Documents/Pd) [--max[=val]] (by default, look in all ~/Documents/Max X/ ; if specified, look for externals sub-folder)"
}
# Parse arguments
while [[ $# -gt 0 ]]; do
case "$1" in
--pd=*)
pd=1
pd_path="${1#*=}"
shift
;;
--pd)
pd=1
shift
;;
--max=*)
max=1
max_path="${1#*=}"
shift
;;
--max)
max=1
shift
;;
--help|-h)
print_help
exit 0
;;
*)
echo "Unknown option: $1"
shift
;;
esac
done
function patch_max_external() {
find "$1" -name "nn_tilde" -type d -mindepth 2 -print0 | while IFS= read -r -d '' ext_dir; do
if [[ -d "$ext_dir/externals" ]]; then
echo "found nn_tilde at $ext_dir";
find "$ext_dir/externals" -name "*.mxo" -print0 | while IFS= read -r -d '' ext_path; do
# echo "found external at $ext_path";
ext_name=$(basename "$ext_path")
find "$ext_dir/support" -name "*.dylib" -print0 | while IFS= read -r -d '' dylib_path; do
dylib_name=$(basename "$dylib_path")
echo "fixing library : $dylib_name"
new_path="/Library/Application Support/ACIDS/RAVE/$dylib_name"
if [[ ! -e "$new_path" ]]; then
echo "[WARNING] library not found : $new_path. Patch may not work"
fi
install_name_tool -change "@loader_path/../../../../support/$dylib_name" "/Library/Application Support/ACIDS/RAVE/$dylib_name" "${ext_path}/Contents/MacOS/${ext_name%.*}" 2> /dev/null
done
codesign --deep --force --sign - "${ext_path}/Contents/MacOS/${ext_name%.*}"
done
fi
done
}
function patch_pd_external() {
ext_dir=$1
if [[ ! "$(basename $ext_dir)" == "nn_tilde" ]]; then
ext_dir="${ext_dir}/externals/nn_tilde"
fi
if [[ -e $(realpath $ext_dir) ]]; then
find "$ext_dir" -name "nn~.pd_*" -print0 | while IFS= read -r -d '' ext_path; do
ext_name=$(basename "$ext_path")
find "$ext_dir" -name "*.dylib" -print0 | while IFS= read -r -d '' dylib_path; do
dylib_name=$(basename "$dylib_path")
echo "fixing library : $dylib_name"
new_path="/Library/Application Support/ACIDS/RAVE/$dylib_name"
if [[ ! -e "$new_path" ]]; then
echo "[WARNING] library not found : $new_path. Patch may not work"
fi
echo install_name_tool -change "@rpath/$dylib_name" "/Library/Application Support/ACIDS/RAVE/$dylib_name" "${ext_path}" 2> /dev/null
done
codesign --deep --force --sign - "${ext_path}"
done
else
echo "folder $ext_dir not found".
fi
}
if [[ "$max" -eq 1 ]]; then
if [[ -n "$max_path" ]]; then
patch_max_external "$max_path"
else
find ~/Documents -maxdepth 1 -name "Max *" -type d -print0 | while IFS= read -r -d '' max_dir; do
if [[ -d $max_dir ]]; then
patch_max_external "$max_dir"
else
echo "$max_dir does not exists"
fi
done
fi
fi
if [[ "$pd" -eq 1 ]]; then
if [[ -n "$max_path" ]]; then
patch_pd_external "$pd_path"
else
patch_pd_external "$HOME/Documents/Pd"
fi
fi
================================================
FILE: src/frontend/maxmsp/mc.nn_tilde/CMakeLists.txt
================================================
# Copyright 2018 The Min-DevKit Authors. All rights reserved.
# Use of this source code is governed by the MIT License found in the License.md file.
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(C74_MIN_API_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../min-api)
include(${C74_MIN_API_DIR}/script/min-pretarget.cmake)
if (APPLE)
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.12")
endif()
#############################################################
# MAX EXTERNAL
#############################################################
execute_process(
COMMAND git describe --tags
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
OUTPUT_VARIABLE VERSION
OUTPUT_STRIP_TRAILING_WHITESPACE
)
message(${VERSION})
add_definitions(-DVERSION="${VERSION}")
set(
SOURCE_FILES
mc.nn_tilde.cpp
)
add_library(
${PROJECT_NAME}
MODULE
${SOURCE_FILES}
)
include(${C74_MIN_API_DIR}/script/min-posttarget.cmake)
if (MSVC)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20)
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD_REQUIRED ON)
target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_20)
endif()
include_directories(
"${C74_INCLUDES}"
"${CMAKE_CURRENT_SOURCE_DIR}/../shared"
"${CMAKE_CURRENT_SOURCE_DIR}/../../shared"
)
if (MSVC)
include_directories(${VCPKG_INCLUDE_DIR})
link_directories(${VCPKG_LIB_DIR})
endif()
target_link_libraries(${PROJECT_NAME} PRIVATE backend)
if (UNIX)
set(CONDA_ENV_PATH "${CMAKE_SOURCE_DIR}/../env")
set(CURL_INCLUDE_DIR "${CONDA_ENV_PATH}/include")
set(CURL_LIBRARY "${CONDA_ENV_PATH}/lib/libcurl.dylib")
include_directories(${CURL_INCLUDE_DIR})
elseif(MSVC)
set(VCPKG_PATH "${CMAKE_SOURCE_DIR}/../vcpkg")
set(CURL_INCLUDE_DIR "${VCPKG_PATH}/packages/curl_x64-windows/include")
set(CURL_LIBRARY "${VCPKG_PATH}/packages/curl_x64-windows/lib/libcurl.lib")
endif()
target_link_libraries(${PROJECT_NAME} PRIVATE nlohmann_json::nlohmann_json)
target_link_libraries(${PROJECT_NAME} PRIVATE ${CURL_LIBRARY})
if (APPLE) # SEARCH FOR TORCH DYLIB IN THE LOADER FOLDER
set_target_properties(${PROJECT_NAME} PROPERTIES
BUILD_WITH_INSTALL_RPATH FALSE
LINK_FLAGS "-Wl,-rpath,@loader_path/"
)
endif()
if (APPLE) # COPY DYLIBS IN THE LOADER FOLDER
add_custom_command(
TARGET ${PROJECT_NAME}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_SOURCE_DIR}/../env/ssl/cert.pem" "$"
COMMAND ${CMAKE_SOURCE_DIR}/../env/bin/python ${CMAKE_SOURCE_DIR}/../install/dylib_fix.py -p "$" -o "${CMAKE_SOURCE_DIR}/support" -l "${torch_dir}/libtorch" "${CMAKE_BINARY_DIR}/_deps" "${CMAKE_SOURCE_DIR}/../env" "${HOMEBREW_PREFIX}" --sign_id "${SIGN_ID}"
COMMENT "Fixing libraries, certificates, permissions, codesigning, quarantine"
)
endif()
================================================
FILE: src/frontend/maxmsp/mc.nn_tilde/mc.nn_tilde.cpp
================================================
#include "../shared/nn_base.h"
#include "c74_min.h"
template
void model_perform(nn_class* nn_instance) {
std::vector in_model, out_model;
for (int c(0); c < nn_instance->n_inlets; c++)
in_model.push_back(nn_instance->m_in_model[c].get());
for (int c(0); c < nn_instance->n_outlets; c++)
out_model.push_back(nn_instance->m_out_model[c].get());
if (nn_instance->wait_for_buffer_reset) {
nn_instance->init_buffers();
}
nn_instance->m_model->perform(in_model, out_model, nn_instance->m_method,
nn_instance->get_batches(), nn_instance->n_outlets, nn_instance->m_buffer_size);
}
template
void model_perform_async(nn_class* nn_instance) {
while (!nn_instance->can_perform()) {
std::this_thread::sleep_for(std::chrono::milliseconds(REFRESH_THREAD_INTERVAL));
if (nn_instance->m_should_stop_perform_thread) {
return;
}
}
std::vector in_model, out_model;
if (nn_instance->wait_for_buffer_reset) {
nn_instance->init_buffers();
}
for (int c(0); c < nn_instance->n_inlets; c++)
in_model.push_back(nn_instance->m_in_model[c].get());
for (int c(0); c < nn_instance->n_outlets; c++)
out_model.push_back(nn_instance->m_out_model[c].get());
while (!nn_instance->m_should_stop_perform_thread) {
if (nn_instance->m_data_available_lock.try_acquire_for(
std::chrono::milliseconds(REFRESH_THREAD_INTERVAL))) {
if (nn_instance->wait_for_buffer_reset) {
nn_instance->init_buffers();
}
if (nn_instance->had_buffer_reset) {
in_model.clear();
for (int c(0); c < nn_instance->m_model_in * nn_instance->get_batches(); c++) {
in_model.push_back(nn_instance->m_in_model[c].get());
}
out_model.clear();
for (int c(0); c < nn_instance->m_model_out * nn_instance->get_batches(); c++) {
out_model.push_back(nn_instance->m_out_model[c].get());
}
}
nn_instance->m_model->perform(in_model,
out_model,
nn_instance->m_method,
nn_instance->get_batches(),
nn_instance->m_out_model.size() / nn_instance->get_batches(),
nn_instance->m_buffer_size);
nn_instance->m_result_available_lock.release();
}
}
}
long simplemc_multichanneloutputs(c74::max::t_object *x, long index,
long count);
long simplemc_inputchanged(c74::max::t_object *x, long index, long count);
class mc_nn: public nn_base> {
public:
MIN_DESCRIPTION{"Multi-channel interface for deep learning models"};
MIN_TAGS{"audio, deep learning, ai"};
MIN_AUTHOR{"Antoine Caillon & Axel Chemla--Romeu-Santos"};
MIN_RELATED{"nn.info, nn~, mcs.nn~"};
static std::string get_external_name() { return "mc.nn~";}
mc_nn(const atoms &args = {}) {
init_external(args);
}
int get_sample_rate() override {
return samplerate();
}
void init_external(const atoms &args) override {
init_model();
init_downloader();
if (!args.size()) { return; }
init_inputs_and_outputs(args);
init_inlets_and_outlets();
// init_buffers();
init_process();
}
void perform(audio_bundle input, audio_bundle output) override;
// channel handling
std::vector channel_map;
int n_batches_arg = 0;
int get_batches();
int get_batches_out();
void init_inputs_and_outputs(const atoms& atoms) override;
void init_inlets_and_outlets() override;
void init_buffers() override;
void init_process() override;
bool init_buffers_at_init() override { return true; }
bool update_channel_map(const long& index, const long& count);
message<> maxclass_setup{
this, "maxclass_setup",
[this](const c74::min::atoms &args, const int inlet) -> c74::min::atoms {
cout << "mc.nn~ " << VERSION << " - torch " << TORCH_VERSION
<< " - 2024-2025 - Antoine Caillon & Axel Chemla--Romeu-Santos" << endl;
cout << "visit https://www.github.com/acids-ircam" << endl;
c74::max::t_class *c = args[0];
c74::max::class_addmethod(
c, (c74::max::method)simplemc_multichanneloutputs,
"multichanneloutputs", c74::max::A_CANT, 0);
c74::max::class_addmethod(c, (c74::max::method)simplemc_inputchanged,
"inputchanged", c74::max::A_CANT, 0);
return {};
}};
attribute chans_attr {
this,
"chans",
0,
description{"set a fixed number of output channels"},
setter{
MIN_FUNCTION {
if (args.size() == 0)
return args;
int in_chans = args[0];
if (in_chans > 0) {
n_batches_arg = in_chans;
DEBUG_PRINT("setting out channels to %d", in_chans);
}
return args;
}
}};
};
int mc_nn::get_batches() {
if (channel_map.size() > 0) {
return *std::max_element(channel_map.begin(), channel_map.end());
} else {
return 1;
}
}
int mc_nn::get_batches_out() {
if (n_batches_arg > 0) {
return n_batches_arg;
} else {
return get_batches();
}
}
void mc_nn::init_inputs_and_outputs(const atoms& args) {
nn_base::init_inputs_and_outputs(args);
for (int i(0); i < m_model_in; i++)
channel_map.push_back(1);
}
void mc_nn::init_inlets_and_outlets() {
for (int i(0); i < n_inlets; i++) {
std::string input_label = "";
try {
input_label = m_model->get_model()
.attr(m_method + "_input_labels")
.toList()
.get(i)
.toStringRef();
} catch (...) {
input_label = "(multichannel) model input " + std::to_string(i);
}
m_inlets.push_back(std::make_unique>(this, input_label, "multichannelsignal"));
}
for (int i(0); i < n_outlets; i++) {
std::string output_label = "";
try {
output_label = m_model->get_model()
.attr(m_method + "_output_labels")
.toList()
.get(i)
.toStringRef();
} catch (...) {
output_label = "(multichannel) model output " + std::to_string(i);
}
m_outlets.push_back(
std::make_unique>(this, output_label, "multichannelsignal"));
}
}
void mc_nn::init_buffers() {
if (channel_map.size() == 0) {
for (int i(0); i < n_inlets; i++)
channel_map.push_back(1);
}
update_method();
// if (m_buffer_size == -1) {
// // NO THREAD MODE
// m_buffer_size = DEFAULT_BUFFER_SIZE;
// }
// if (m_buffer_size < m_higher_ratio) {
// cerr << "buffer size too small, switching to " << m_buffer_size << endl;
// m_buffer_size = m_higher_ratio;
// } else {
// m_buffer_size = power_ceil(m_buffer_size);
// }
m_buffer_in = n_inlets * get_batches();
if (m_in_buffer.get() != nullptr) { m_in_buffer.release(); }
m_in_buffer = std::make_unique[]>(m_buffer_in);
for (int i = 0; i < m_buffer_in; i++) {
m_in_buffer[i].initialize(m_buffer_size);
}
m_buffer_out = n_outlets * get_batches_out();
if (m_out_buffer.get() == nullptr) { m_out_buffer.release(); }
m_out_buffer = std::make_unique[]>(m_buffer_out);
for (int i = 0; i < m_buffer_out; i++) {
m_out_buffer[i].initialize(m_buffer_size);
}
m_in_model.clear();
for (int i = 0; i < m_model_in * get_batches(); i++) {
m_in_model.push_back(std::make_unique(m_buffer_size));
std::fill(m_in_model[i].get(), m_in_model[i].get() + m_buffer_size, 0.);
}
m_out_model.clear();
for (int i = 0; i < m_model_out * get_batches(); i++) {
m_out_model.push_back(std::make_unique(m_buffer_size));
std::fill(m_out_model[i].get(), m_out_model[i].get() + m_buffer_size, 0.);
}
wait_for_buffer_reset = false;
had_buffer_reset = true;
buffer_initialised = true;
}
void mc_nn::init_process() {
nn_base>::init_process();
if (m_use_thread) {
m_compute_thread = std::make_unique(model_perform_async, this);
}
}
void mc_nn::perform(audio_bundle input, audio_bundle output) {
auto vec_size = input.frame_count();
auto chan_size = input.channel_count();
// COPY INPUT TO CIRCULAR BUFFER
int current_batch = 0;
int current_chan = 0;
int n_batches = get_batches();
for (int c_in(0); c_in < chan_size; c_in++) {
auto in = input.samples(c_in);
auto buf_idx = current_batch * n_batches + current_chan;
if (buf_idx < m_buffer_in) {
m_in_buffer[buf_idx].put(in, vec_size);
}
current_chan++;
if (current_chan >= channel_map[current_batch]) {
current_batch++;
current_chan=0;
}
}
if (m_in_buffer[0].full()) { // BUFFER IS FULL
if (!m_use_thread) {
// TRANSFER MEMORY BETWEEN INPUT CIRCULAR BUFFER AND MODEL BUFFER
auto n_ins = std::min(n_inlets, m_model_in);
for (int b(0); b < n_batches; b++) {
for (int c(0); c < n_ins; c++) {
auto buf_idx = c * get_batches() + b;
if ((buf_idx < m_buffer_in) && (c * n_batches + b < m_in_model.size()))
m_in_buffer[buf_idx].get(m_in_model[c * n_batches + b].get(), m_buffer_size);
}
}
// CALL MODEL PERFORM IN CURRENT THREAD
model_perform(this);
// TRANSFER MEMORY BETWEEN OUTPUT CIRCULAR BUFFER AND MODEL BUFFER
auto n_outs = std::min(n_outlets, m_model_out);
auto n_batches_out = std::min(get_batches_out(), n_batches);
for (int b(0); b < n_batches_out; b++) {
for (int c(0); c < n_outs; c++) {
auto b_idx = c * get_batches_out() + b;
if ((b_idx < m_buffer_out) && (b * m_model_out + c < m_out_model.size()))
m_out_buffer[b_idx].put(m_out_model[b * m_model_out + c].get(), m_buffer_size);
}
}
} else if (m_result_available_lock.try_acquire()) {
// TRANSFER MEMORY BETWEEN INPUT CIRCULAR BUFFER AND MODEL BUFFER
auto n_ins = std::min(n_inlets, m_model_in);
for (int b(0); b < n_batches; b++) {
for (int c(0); c < n_ins; c++) {
auto buf_idx = c * get_batches() + b;
if ((buf_idx < m_buffer_in) && (c * n_batches + b < m_in_model.size()))
m_in_buffer[buf_idx].get(m_in_model[c * n_batches + b].get(), m_buffer_size);
}
}
// TRANSFER MEMORY BETWEEN OUTPUT CIRCULAR BUFFER AND MODEL BUFFER
auto n_outs = std::min(n_outlets, m_model_out);
auto n_batches_out = std::min(get_batches_out(), n_batches);
for (int b(0); b < n_batches_out; b++) {
for (int c(0); c < n_outs; c++) {
auto b_idx = c * get_batches_out() + b;
if ((b_idx < m_buffer_out) && (b * m_model_out + c < m_out_model.size()))
m_out_buffer[b_idx].put(m_out_model[b * m_model_out + c].get(), m_buffer_size);
}
}
// SIGNAL PERFORM THREAD THAT DATA IS AVAILABLE
m_data_available_lock.release();
}
}
// COPY CIRCULAR BUFFER TO OUTPUT
for (int b(0); b < output.channel_count() ; b++) {
if (b < m_buffer_out) {
auto out = output.samples(b);
m_out_buffer[b].get(out, vec_size);
}
}
}
bool mc_nn::update_channel_map(const long& index, const long& count) {
bool needs_refresh = false;
if (channel_map.size() == 0) {
for (int i(0); i < n_inlets; i++)
channel_map.push_back(1);
}
if (index > channel_map.size()) {
return false;
}
if (channel_map[index] != count) {
channel_map[index] = count;
wait_for_buffer_reset = true;
}
return true;
}
long simplemc_multichanneloutputs(c74::max::t_object *x, long index,
long count) {
minwrap *ob = (minwrap *)(x);
return ob->m_min_object.get_batches_out();
}
long simplemc_inputchanged(c74::max::t_object *x, long index, long count) {
minwrap *ob = (minwrap *)(x);
ob->m_min_object.update_channel_map(index, count);
return true;
}
MIN_EXTERNAL(mc_nn);
================================================
FILE: src/frontend/maxmsp/mcs.nn_tilde/CMakeLists.txt
================================================
# Copyright 2018 The Min-DevKit Authors. All rights reserved.
# Use of this source code is governed by the MIT License found in the License.md file.
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(C74_MIN_API_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../min-api)
include(${C74_MIN_API_DIR}/script/min-pretarget.cmake)
if (APPLE)
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.12")
endif()
#############################################################
# MAX EXTERNAL
#############################################################
execute_process(
COMMAND git describe --tags
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
OUTPUT_VARIABLE VERSION
OUTPUT_STRIP_TRAILING_WHITESPACE
)
message(${VERSION})
add_definitions(-DVERSION="${VERSION}")
set(
SOURCE_FILES
mcs.nn_tilde.cpp
)
add_library(
${PROJECT_NAME}
MODULE
${SOURCE_FILES}
)
include(${C74_MIN_API_DIR}/script/min-posttarget.cmake)
if (MSVC)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20)
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD_REQUIRED ON)
target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_20)
endif()
include_directories(
"${C74_INCLUDES}"
"${CMAKE_CURRENT_SOURCE_DIR}/../shared"
"${CMAKE_CURRENT_SOURCE_DIR}/../../shared"
)
if (MSVC)
include_directories(${VCPKG_INCLUDE_DIR})
link_directories(${VCPKG_LIB_DIR})
endif()
target_link_libraries(${PROJECT_NAME} PRIVATE backend)
if (UNIX)
set(CONDA_ENV_PATH "${CMAKE_SOURCE_DIR}/../env")
set(CURL_INCLUDE_DIR "${CONDA_ENV_PATH}/include")
set(CURL_LIBRARY "${CONDA_ENV_PATH}/lib/libcurl.dylib")
include_directories(${CURL_INCLUDE_DIR})
elseif(MSVC)
set(VCPKG_PATH "${CMAKE_SOURCE_DIR}/../vcpkg")
set(CURL_INCLUDE_DIR "${VCPKG_PATH}/packages/curl_x64-windows/include")
set(CURL_LIBRARY "${VCPKG_PATH}/packages/curl_x64-windows/lib/libcurl.lib")
endif()
target_link_libraries(${PROJECT_NAME} PRIVATE nlohmann_json::nlohmann_json)
target_link_libraries(${PROJECT_NAME} PRIVATE ${CURL_LIBRARY})
if (APPLE) # SEARCH FOR TORCH DYLIB IN THE LOADER FOLDER
set_target_properties(${PROJECT_NAME} PROPERTIES
BUILD_WITH_INSTALL_RPATH FALSE
LINK_FLAGS "-Wl,-rpath,@loader_path/"
)
endif()
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g")
if (APPLE) # COPY DYLIBS IN THE LOADER FOLDER
add_custom_command(
TARGET ${PROJECT_NAME}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_SOURCE_DIR}/../env/ssl/cert.pem" "$"
COMMAND ${CMAKE_SOURCE_DIR}/../env/bin/python ${CMAKE_SOURCE_DIR}/../install/dylib_fix.py -p "$" -o "${CMAKE_SOURCE_DIR}/support" -l "${torch_dir}/libtorch" "${CMAKE_BINARY_DIR}/_deps" "${CMAKE_SOURCE_DIR}/../env" "${HOMEBREW_PREFIX}" --sign_id "${SIGN_ID}"
COMMENT "Fixing libraries, certificates, permissions, codesigning, quarantine"
)
endif()
================================================
FILE: src/frontend/maxmsp/mcs.nn_tilde/mcs.nn_tilde.cpp
================================================
#include "../shared/nn_base.h"
#include "c74_min.h"
template
void model_perform(nn_class* nn_instance) {
std::vector in_model, out_model;
for (int c(0); c < nn_instance->m_model_in * nn_instance->n_batches; c++)
in_model.push_back(nn_instance->m_in_model[c].get());
for (int c(0); c < nn_instance->m_model_out * nn_instance->n_batches; c++)
out_model.push_back(nn_instance->m_out_model[c].get());
if (nn_instance->had_buffer_reset) {
nn_instance->had_buffer_reset = false;
}
nn_instance->m_model->perform(in_model, out_model, nn_instance->m_method,
nn_instance->n_inlets, nn_instance->m_model_out, nn_instance->m_buffer_size);
}
template
void model_perform_async(nn_class* nn_instance) {
while (!nn_instance->can_perform()){
std::this_thread::sleep_for(std::chrono::milliseconds(REFRESH_THREAD_INTERVAL));
if (nn_instance->m_should_stop_perform_thread) {
return;
}
}
if (nn_instance->wait_for_buffer_reset) {
nn_instance->init_buffers();
}
std::vector in_model, out_model;
for (int c(0); c < nn_instance->m_model_in * nn_instance->n_batches; c++)
in_model.push_back(nn_instance->m_in_model[c].get());
for (int c(0); c < nn_instance->m_model_out * nn_instance->n_batches; c++)
out_model.push_back(nn_instance->m_out_model[c].get());
while (!nn_instance->m_should_stop_perform_thread) {
if (nn_instance->wait_for_buffer_reset) {
nn_instance->init_buffers();
}
if (nn_instance->had_buffer_reset) {
in_model.clear();
for (int c(0); c < nn_instance->m_model_in * nn_instance->n_batches; c++) {
in_model.push_back(nn_instance->m_in_model[c].get());
}
out_model.clear();
for (int c(0); c < nn_instance->m_model_out * nn_instance->n_batches; c++) {
out_model.push_back(nn_instance->m_out_model[c].get());
}
nn_instance->had_buffer_reset = false;
}
if (nn_instance->m_data_available_lock.try_acquire_for(
std::chrono::milliseconds(REFRESH_THREAD_INTERVAL))) {
nn_instance->m_model->perform(in_model, out_model, nn_instance->m_method,
nn_instance->n_inlets, nn_instance->m_model_out, nn_instance->m_buffer_size);
nn_instance->m_result_available_lock.release();
}
}
}
long simplemc_multichanneloutputs(c74::max::t_object *x, long index,
long count);
long simplemc_inputchanged(c74::max::t_object *x, long index, long count);
class mcs_nn: public nn_base> {
public:
MIN_DESCRIPTION{"Multi-channel interface for deep learning models"};
MIN_TAGS{"audio, deep learning, ai"};
MIN_AUTHOR{"Antoine Caillon & Axel Chemla--Romeu-Santos"};
MIN_RELATED{"nn.info, nn~, mc.nn~"};
static std::string get_external_name() { return "mcs.nn~";}
mcs_nn(const atoms &args = {}) {
init_external(args);
}
int get_sample_rate() override {
return samplerate();
}
void init_external(const atoms &args) override {
init_model();
init_downloader();
if (!args.size()) { return; }
init_inputs_and_outputs(args);
init_inlets_and_outlets();
// init_buffers();
wait_for_buffer_reset = true;
init_process();
}
void perform(audio_bundle input, audio_bundle output) override;
void dump_object() override;
// channel handling
int get_batches();
int n_mc_inputs() {
return std::accumulate(channel_map.begin(), channel_map.end(), 0);
}
bool check_inputs();
std::vector channel_map;
void init_inputs_and_outputs(const atoms& atoms) override;
void init_inlets_and_outlets() override;
void init_buffers() override;
void init_process() override;
void update_method(std::string method = "") override;
bool update_channel_map(const long& index, const long& count);
int m_out_channels = 0;
int m_out_channels_arg = 0;
void update_out_channels() {
if ((m_out_channels_arg == 0) && (m_model_out != m_out_channels)) {
DEBUG_PRINT("updating out channels to %d", m_model_out);
m_out_channels = m_model_out;
wait_for_buffer_reset = true;
}
// if method is changed, multi channels outputs will stay the same.
}
message<> maxclass_setup{
this, "maxclass_setup",
[this](const c74::min::atoms &args, const int inlet) -> c74::min::atoms {
cout << "mcs.nn~ " << VERSION << " - torch " << TORCH_VERSION
<< " - 2024-2025 - Antoine Caillon & Axel Chemla--Romeu-Santos" << endl;
cout << "visit https://www.github.com/acids-ircam" << endl;
c74::max::t_class *c = args[0];
c74::max::class_addmethod(
c, (c74::max::method)simplemc_multichanneloutputs,
"multichanneloutputs", c74::max::A_CANT, 0);
c74::max::class_addmethod(c, (c74::max::method)simplemc_inputchanged,
"inputchanged", c74::max::A_CANT, 0);
return {};
}};
attribute chans_attr {
this,
"chans",
0,
description{"set a fixed number of output channels"},
setter{
MIN_FUNCTION {
if (args.size() == 0)
return args;
int in_chans = args[0];
if (in_chans > 0) {
m_out_channels_arg = in_chans;
m_out_channels = in_chans;
DEBUG_PRINT("setting out channels to %d", in_chans);
}
return args;
}
}};
};
bool mcs_nn::check_inputs() {
return true;
}
int mcs_nn::get_batches() {
return *std::max_element(channel_map.begin(), channel_map.end());
}
void mcs_nn::init_inputs_and_outputs(const atoms &args) {
bool empty_mode = false;
DEBUG_PRINT("parsing inputs & outputs...");
if (args.size() > 0) { // ONE ARGUMENT IS GIVEN
auto model_path = std::string(args[0]);
if (model_path == "void") {
empty_mode = true;
m_model_in = 1;
m_model_out = 1;
} else {
try {
m_path = to_model_path(model_path);
} catch (std::string &e) {
error(e);
}
}
}
if (empty_mode) {
DEBUG_PRINT("empty mode");
if (args.size() > 1) { // FOUR ARGUMENTS ARE GIVEN
n_batches = int(args[1]);
}
if (args.size() > 2) { // THREE ARGUMENTS ARE GIVEN
m_buffer_size = int(args[2]);
}
channel_map = std::vector(n_batches, 1);
} else {
if (args.size() > 1) { // TWO ARGUMENTS ARE GIVEN
m_method = std::string(args[1]);
}
if (args.size() > 2) { // TWO ARGUMENTS ARE GIVEN
n_batches = int(args[2]);
}
if (args.size() > 3) { // THREE ARGUMENTS ARE GIVEN
m_buffer_size = int(args[3]);
}
channel_map = std::vector(n_batches, 1);
DEBUG_PRINT("loading model...");
load_model(m_path);
if (m_ready) {
m_out_channels = m_model_out;
}
}
if (m_buffer_size == -1) {
// NO THREAD MODE
m_buffer_size = DEFAULT_BUFFER_SIZE;
}
}
bool mcs_nn::update_channel_map(const long& index, const long& count)
{
if (channel_map[index] != count) {
channel_map[index] = count;
wait_for_buffer_reset = true;
if (count != m_model_in) {
return false;
} else {
return true;
}
}
return true;
}
void mcs_nn::init_inlets_and_outlets() {
DEBUG_PRINT("loading model...");
DEBUG_PRINT("n_batches : %d", n_batches);
std::string input_label;
for (int i(0); i < n_batches; i++) {
if (m_model_in > 0) {
input_label = "(multichannel) batch " + std::to_string(i) + "(" + std::to_string(m_model_in) + " dimensions)";
} else {
input_label = "(multichannel) batch " + std::to_string(i);
}
m_inlets.push_back(
std::make_unique>(this, input_label, "multichannelsignal"));
}
std::string output_label;
for (int i(0); i < n_batches; i++) {
output_label = "(multichannel) batch " + std::to_string(i) + "(" + std::to_string(m_out_channels) + " dimensions)";
m_outlets.push_back(
std::make_unique>(this, output_label, "multichannelsignal"));
}
n_inlets = n_batches;
n_outlets = n_batches;
}
void mcs_nn::init_buffers() {
update_method();
if (m_out_channels == 0) {
error("could not retrieve number of output channels");
}
DEBUG_PRINT("initializing buffers...");
if (!m_ready) { return; }
if (m_buffer_size == -1) {
// NO THREAD MODE
m_buffer_size = DEFAULT_BUFFER_SIZE;
}
DEBUG_PRINT("buffer size : %d", m_buffer_size);
if (m_buffer_size == 0) {
m_use_thread = false;
m_buffer_size = m_higher_ratio;
} else {
if (m_buffer_size < m_higher_ratio) {
cerr << "buffer size too small, switching to " << m_buffer_size << endl;
m_buffer_size = m_higher_ratio;
} else {
m_buffer_size = power_ceil(m_buffer_size);
}
}
m_buffer_in = n_mc_inputs();
DEBUG_PRINT("initializing with n_mc_inputs : %d", m_buffer_in);
if (m_in_buffer.get() != nullptr) { m_in_buffer.release(); }
m_in_buffer = std::make_unique[]>(m_buffer_in);
for (int i = 0; i < m_buffer_in; i++) {
m_in_buffer[i].initialize(m_buffer_size);
}
DEBUG_PRINT("initializing with outputs : %d x %d", n_outlets, m_out_channels);
if (m_out_buffer.get() != nullptr) { m_out_buffer.release(); }
m_buffer_out = n_outlets * m_out_channels;
m_out_buffer = std::make_unique[]>(m_buffer_out);
for (int i = 0; i < m_buffer_out; i++) {
m_out_buffer[i].initialize(m_buffer_size);
}
DEBUG_PRINT("initializing with model buffer inputs : %d x %d", m_model_in, n_inlets);
m_in_model.clear();
for (int i = 0; i < m_model_in * n_inlets; i++) {
m_in_model.push_back(std::make_unique(m_buffer_size));
std::fill(m_in_model[i].get(), m_in_model[i].get() + m_buffer_size, 0.);
}
DEBUG_PRINT("initializing with model buffer outputs : %d x %d", m_model_out, n_outlets);
m_out_model.clear();
for (int i = 0; i < m_model_out * n_outlets; i++) {
m_out_model.push_back(std::make_unique(m_buffer_size));
std::fill(m_out_model[i].get(), m_out_model[i].get() + m_buffer_size, 0.);
}
DEBUG_PRINT("buffers initialized");
wait_for_buffer_reset = false;
had_buffer_reset = true;
buffer_initialised = true;
}
void mcs_nn::update_method(std::string method) {
if (!method.empty()) {
set_method(method);
}
if (!m_model->is_loaded()) {
cerr << "no model is set yet" << endl;
return;
}
if (m_model->has_method(m_method)) {
auto params = m_model->get_method_params(m_method);
// input parameters
m_model_in = params[0];
m_in_ratio = params[1];
// output parameters
m_model_out = params[2];
m_out_ratio = params[3];
if (m_out_channels == 0) {
m_out_channels = m_model_out;
}
wait_for_buffer_reset = true;
} else {
cerr << "method " << method << " not present in model" << endl;
m_ready = false;
}
}
void mcs_nn::init_process() {
nn_base>::init_process();
if (m_use_thread) {
m_compute_thread = std::make_unique(model_perform_async, this);
}
}
void mcs_nn::perform(audio_bundle input, audio_bundle output) {
auto chan_size = input.channel_count();
auto vec_size = input.frame_count();
// if (buffer_initialised) {
int current_batch = 0;
int current_channel = 0;
int n_channels_in = std::min(chan_size, m_buffer_in);
for (int in_c(0); in_c < n_channels_in; in_c++) {
auto in = input.samples(in_c);
m_in_buffer[in_c].put(in, vec_size);
}
if (m_in_buffer[0].full()) { // BUFFER IS FULL
if (!m_use_thread) {
// TRANSFER MEMORY BETWEEN INPUT CIRCULAR BUFFER AND MODEL BUFFER
int current_chan = 0;
int current_batch = 0;
for (int i(0); i < m_buffer_in; i++) {
if (current_chan < m_model_in) {
auto c_idx = current_chan * n_batches + current_batch;
m_in_buffer[i].get(m_in_model[c_idx].get(), m_buffer_size);
}
current_chan++;
if (current_chan >= channel_map[current_batch]) {
current_batch += 1;
current_chan = 0;
}
}
// CALL MODEL PERFORM IN CURRENT THREAD
model_perform(this);
// TRANSFER MEMORY BETWEEN OUTPUT CIRCULAR BUFFER AND MODEL BUFFER
auto current_idx = 0;
for (int c(0); c < n_outlets * m_model_out; c++){
m_out_buffer[c].put(m_out_model[c].get(), m_buffer_size);
}
} else if (m_result_available_lock.try_acquire()) {
// TRANSFER MEMORY BETWEEN INPUT CIRCULAR BUFFER AND MODEL BUFFER
// for (int c(0); c < m_model_in * get_batches(); c++)
int current_chan = 0;
int current_batch = 0;
int i = 0;
while (i < n_channels_in) {
if (current_chan >= m_model_in) {
i += (channel_map[current_batch] - current_chan);
current_batch += 1;
current_chan = 0;
} else {
if (current_chan < m_model_in) {
auto c_idx = current_chan * n_batches + current_batch;
m_in_buffer[i].get(m_in_model[c_idx].get(), m_buffer_size);
}
current_chan++;
if (current_chan >= channel_map[current_batch]) {
current_batch += 1;
current_chan = 0;
}
i++;
}
}
// TRANSFER MEMORY BETWEEN OUTPUT CIRCULAR BUFFER AND MODEL BUFFER
auto current_idx = 0;
auto n_channels = std::min(m_model_out, m_out_channels);
for (int b(0); b < n_outlets; b++) {
for (int c(0); c < n_channels; c++){
m_out_buffer[b * m_out_channels + c].put(m_out_model[b * m_model_out + c].get(), m_buffer_size);
}
}
// SIGNAL PERFORM THREAD THAT DATA IS AVAILABLE
m_data_available_lock.release();
}
}
// for (int b(0); b < n_outlets; b++) {
// for (int c(0); c < n_channels; c++) {
for (int i(0); i < m_buffer_out; i++) {
auto out = output.samples(i);
m_out_buffer[i].get(out, vec_size);
}
// }
}
long simplemc_multichanneloutputs(c74::max::t_object *x, long index,
long count) {
minwrap *ob = (minwrap *)(x);
return ob->m_min_object.m_out_channels;
}
long simplemc_inputchanged(c74::max::t_object *x, long index, long count) {
minwrap *ob = (minwrap *)(x);
auto is_full = ob->m_min_object.update_channel_map(index, count);
ob->m_min_object.update_out_channels();
if (!is_full) {
auto n_channels = ob->m_min_object.m_model_in;
c74::max::object_warn(
x, (std::string("got " + std::to_string(count) +
" for " + std::to_string(n_channels) +
" model inputs").c_str())
);
}
return true;
}
void mcs_nn::dump_object() {
cout << "model_path: " << std::string(m_path) << endl;
if (m_model) {
if (m_model->is_loaded()) {
cout << "input dimension: " << m_model_in << endl;
cout << "output dimension: " << m_model_out << endl;
} else {
cout << "input dimension: no model yet" << endl;
cout << "output dimension: no model yet" << endl;
}
} else {
cout << "input dimension: no model yet" << endl;
cout << "output dimension: no model yet" << endl;
}
cout << "input ratio: " << std::to_string(m_in_ratio) << endl;
cout << "output ratio: " << std::to_string(m_out_ratio) << endl;
cout << "methods: ";
for (auto method: m_model->get_available_methods())
cout << method << "; ";
cout << endl;
cout << "attributes: ";
for (auto attribute: m_model->get_settable_attributes())
cout << attribute << "; ";
cout << endl;
}
MIN_EXTERNAL(mcs_nn);
================================================
FILE: src/frontend/maxmsp/nn.info/CMakeLists.txt
================================================
# Copyright 2018 The Min-DevKit Authors. All rights reserved.
# Use of this source code is governed by the MIT License found in the License.md file.
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(C74_MIN_API_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../min-api)
include(${C74_MIN_API_DIR}/script/min-pretarget.cmake)
if (APPLE)
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.12")
endif()
#############################################################
# MAX EXTERNAL
#############################################################
execute_process(
COMMAND git describe --tags
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
OUTPUT_VARIABLE VERSION
OUTPUT_STRIP_TRAILING_WHITESPACE
)
message("version : ${VERSION}")
add_definitions(-DVERSION="${VERSION}")
set(
SOURCE_FILES
nn.info.cpp
)
add_library(
${PROJECT_NAME}
MODULE
${SOURCE_FILES}
)
include_directories(
"${C74_INCLUDES}",
"${CMAKE_CURRENT_SOURCE_DIR}/../shared"
"${CMAKE_CURRENT_SOURCE_DIR}/../../shared"
)
if (MSVC)
include_directories(${VCPKG_INCLUDE_DIR})
link_directories(${VCPKG_LIB_DIR})
endif()
target_link_libraries(${PROJECT_NAME} PRIVATE backend)
if (UNIX)
set(CONDA_ENV_PATH "${CMAKE_SOURCE_DIR}/../env")
set(CURL_INCLUDE_DIR "${CONDA_ENV_PATH}/include")
set(CURL_LIBRARY "${CONDA_ENV_PATH}/lib/libcurl.dylib")
include_directories(${CURL_INCLUDE_DIR})
elseif(MSVC)
set(VCPKG_PATH "${CMAKE_SOURCE_DIR}/../vcpkg")
set(CURL_INCLUDE_DIR "${VCPKG_PATH}/packages/curl_x64-windows/include")
set(CURL_LIBRARY "${VCPKG_PATH}/packages/curl_x64-windows/lib/libcurl.lib")
endif()
target_link_libraries(${PROJECT_NAME} PRIVATE nlohmann_json::nlohmann_json)
target_link_libraries(${PROJECT_NAME} PRIVATE ${CURL_LIBRARY})
include(${C74_MIN_API_DIR}/script/min-posttarget.cmake)
if (MSVC)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20)
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD_REQUIRED ON)
target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_20)
endif()
if (APPLE) # SEARCH FOR TORCH DYLIB IN THE LOADER FOLDER
set_target_properties(${PROJECT_NAME} PROPERTIES
BUILD_WITH_INSTALL_RPATH FALSE
LINK_FLAGS "-Wl,-rpath,@loader_path/"
)
endif()
if (APPLE) # COPY DYLIBS IN THE LOADER FOLDER
add_custom_command(
TARGET ${PROJECT_NAME}
POST_BUILD
COMMAND echo "signing with ${SIGN_ID}"
COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_SOURCE_DIR}/../env/ssl/cert.pem" "$"
COMMAND ${CMAKE_SOURCE_DIR}/../env/bin/python ${CMAKE_SOURCE_DIR}/../install/dylib_fix.py -p "$" -o "${CMAKE_SOURCE_DIR}/support" -l "${torch_dir}/libtorch" "${CMAKE_BINARY_DIR}/_deps" "${CMAKE_SOURCE_DIR}/../env" "${HOMEBREW_PREFIX}" --sign_id "${SIGN_ID}"
COMMENT "Fixing libraries, certificates, permissions, codesigning, quarantine"
)
endif()
================================================
FILE: src/frontend/maxmsp/nn.info/nn.info.cpp
================================================
#include "../../../backend/backend.h"
#include "../shared/max_model_download.h"
#include "../shared/buffer_tools.h"
#include "../shared/dict_utils.h"
#include "c74_min.h"
#include
#include
#include
#include
#include
#ifndef VERSION
#define VERSION "UNDEFINED"
#endif
using namespace c74::min;
class nn_info : public object, public vector_operator<> {
public:
MIN_DESCRIPTION{"Fetching information from deep learning models"};
MIN_TAGS{"audio, deep learning, ai"};
MIN_AUTHOR{"Axel Chemla--Romeu-Santos"};
MIN_RELATED{ "nn~, mc.nn~, mcs.nn~"};
nn_info(const atoms &args = {});
~nn_info();
// INLETS OUTLETS
std::vector>> m_inlets;
std::vector>> m_outlets;
// BACKEND RELATED MEMBERS
ModelInfo m_model_info;
std::string m_path;
bool has_model = false;
std::unique_ptr m_model_dict;
std::unique_ptr m_available_models_dict;
std::unique_ptr m_downloader;
bool is_valid_print_key(std::string string);
// ONLY FOR DOCUMENTATION
argument path_arg{this, "model path",
"Absolute path to the pretrained model."};
// FUNCTION
void set_model_path(const std::string& model_path);
void dump_path();
void dump_methods();
void dump_attributes();
void dump_method_parameters(const std::string& method);
void dump_attribute_parameters(const std::string& method);
void dump_dictionary();
void dump_object();
void dump_downloadable_models();
void scan_model(const path path);
void update_dictionary();
void bind_dictionary(const std::string &dict_name);
void operator()(audio_bundle input, audio_bundle output) {}
void perform(audio_bundle input, audio_bundle output) {}
// BOOT STAMP
message<> maxclass_setup{
this, "maxclass_setup",
[this](const c74::min::atoms &args, const int inlet) -> c74::min::atoms {
cout << "nn.info " << VERSION << " - torch " << TORCH_VERSION
<< " - 2025 - Antoine Caillon & Axel Chemla--Romeu-Santos" << endl;
cout << "visit https://forum.ircam.fr" << endl;
return {};
}};
// ATTRIBUTES
attribute dict_attribute{
this, "dict", symbol(""),
description{"bind model information to target dictionary"},
setter{ MIN_FUNCTION {
std::string dictionary_name = args[0];
this->bind_dictionary(dictionary_name);
return {};
}}
};
message<> print {
this, "print",
MIN_FUNCTION {
bool is_valid = is_valid_print_key(args[0]);
if (!is_valid) {
return {};
}
if (args[1] == "cout") {
cout << args[2] << endl;
} else if (args[1] == "cerr") {
cerr << args[2] << endl;
} else if (args[1] == "cwarn") {
cwarn << args[2] << endl;
}
return {};
}
};
// MESSAGES
message<> bang_callback{
this, "bang",
description{"dumps every model information available"},
MIN_FUNCTION {
this->dump_object();
return {};
}};
// MESSAGES
message<> dump_callback{
this, "dump",
description{"dumps every model information available"},
MIN_FUNCTION {
this->dump_object();
return {};
}};
message<> set_model_callback{
this, "set",
description{"set model path"},
MIN_FUNCTION {
if (args.size() == 0) {
cerr << "set message needs a path to a valid model." << endl;
}
std::string model_path = args[0];
set_model_path(model_path);
return {};
}};
message<> get_path_callback {
this, "path",
description{"dumps current model path"},
MIN_FUNCTION {
this->dump_path();
return {};
}};
message<> get_methods_callback {
this, "methods",
description{"get available methods for provided path"},
MIN_FUNCTION {
this->dump_methods();
return {};
}};
message<> get_attributes_callback {
this, "attributes",
description{"provides settable attributes for provided path"},
MIN_FUNCTION{
this->dump_attributes();
return {};
}
};
message<> get_params_callback {
this, "parameters",
description{"provides processing parameters for the given method"},
MIN_FUNCTION{
if (args.size() == 0) {
cerr << "parameters takes a valid method as first argument." << endl;
return {};
}
std::string method_or_attribute = args[0];
if (m_model_info.attribute_properties.contains(method_or_attribute)) {
this->dump_attribute_parameters(method_or_attribute);
} else if (m_model_info.method_properties.contains(method_or_attribute)) {
this->dump_method_parameters(method_or_attribute);
} else {
cerr << method_or_attribute << " not found in model" << endl;
}
return {};
}
};
message<> get_dict_callback {
this, "dump_dict",
description{"dump information as dictionary"},
MIN_FUNCTION{
this->dump_dictionary();
return {};
}
};
message<> get_models_callback {
this, "get_available_models",
description{"dump available models as a dictionary, with additional informations"},
MIN_FUNCTION{
this->dump_downloadable_models();
return {};
}
};
message <> download_models {
this, "download",
description{"download a model from IRCAM Forum API"},
MIN_FUNCTION {
std::string model_card, optional_name;
if (args.size() == 0) {
cerr << "please provide a model card (print downloadable models with get_available_models messages)" << endl;
} else if (args.size() == 1) {
min::symbol model_card_s = args[0];
model_card = std::string(model_card_s.c_str());
optional_name = "";
} else {
min::symbol model_card_s = args[0];
min::symbol optional_name_s = args[1];
model_card = std::string(model_card_s.c_str());
optional_name = std::string(optional_name_s.c_str());
}
try {
if (this->m_downloader.get()->is_ready())
this->m_downloader.get()->download(model_card, optional_name);
} catch (std::string &e) {
cerr << e << endl;
}
return {};
}
};
message <> delete_models {
this, "delete",
description{"delete a model downloaded from IRCAM Forum API"},
MIN_FUNCTION {
if (args.size() == 0) {
cerr << "please provide a model to delete" << endl;
}
std::string model_card = args[0];
try {
if (this->m_downloader.get()->is_ready())
this->m_downloader.get()->remove(model_card);
} catch (std::string &e) {
cerr << e << endl;
}
return {};
}};
};
nn_info::nn_info(const atoms &args)
{
// make inlets
m_inlets.push_back(std::make_unique>(this, "input for nn.info"));
// make outlets
m_outlets.push_back(
std::make_unique>(this, "model path", "symbol")
);
m_outlets.push_back(
std::make_unique>(this, "available methods")
);
m_outlets.push_back(
std::make_unique>(this, "available attributes")
);
m_outlets.push_back(
std::make_unique>(this, "processing parameters")
);
m_outlets.push_back(
std::make_unique>(this, "dict output", "dictionary")
);
m_outlets.push_back(
std::make_unique>(this, "available models for download", "dictionary")
);
try {
m_downloader = std::make_unique(this, std::string("nn.info"));
} catch (...) {
cwarn << "could not initialise model downloader" << endl;
}
// import informations from model
if (args.size() > 0) { // ONE ARGUMENT IS GIVEN
auto model_path = std::string(args[0]);
set_model_path(model_path);
if (m_path == "") {
error(std::string("could not find model : ") + model_path);
}
}
}
bool nn_info::is_valid_print_key(std::string id_string) {
if (id_string == m_downloader.get()->string_id()) {
return true;
}
return false;
}
void nn_info::update_dictionary() {
if ((m_model_dict.get() == nullptr) || (!has_model)) {
return;
}
auto dict_ref = m_model_dict.get();
if (!dict_ref->valid()) {
cwarn << "problem with dictionary : " << dict_ref->name() << " seems to be unvalid" << endl;
return;
}
dict_ref->clear();
auto model_dict = nn_tools::dict_from_model_info(m_model_info);
dict_ref->copyunique(model_dict);
return;
}
void nn_info::bind_dictionary(const std::string& dict_name) {
if (m_model_dict.get() != nullptr) {
m_model_dict.release();
}
if (dict_name == "") {
m_model_dict = std::make_unique(symbol(true));
} else {
m_model_dict = std::make_unique(symbol(dict_name));
}
update_dictionary();
}
void nn_info::scan_model(path path) {
std::string model_path = path;
cout << "parsing model : " << model_path << endl;
auto m_model = Backend();
if (m_model.load(model_path, samplerate())) {
// cerr << "error loading path " << model_path << endl;
throw "error loading path " + model_path;
return;
}
// parse things
try {
m_model_info = m_model.get_model_info();
has_model = true;
m_path = model_path;
update_dictionary();
} catch (std::string &error) {
throw error;
}
}
void nn_info::set_model_path(const std::string& model_path) {
auto model_path_checked = model_path;
try {
if (model_path.substr(model_path.length() - 3) != ".ts")
model_path_checked = model_path_checked + ".ts";
min::path current_path;
if (m_downloader) {
auto download_path = m_downloader->get_download_path() / model_path_checked;
if (std::filesystem::exists(download_path)) {
current_path = path(download_path.string());
scan_model(current_path);
return;
}
}
current_path = path(model_path_checked);
scan_model(current_path);
} catch (std::string& stringerr) {
cerr << stringerr << endl;
} catch (std::exception& e) {
cerr << e.what() << endl;
}
}
void nn_info::dump_path() {
// Iterating over the keys
auto outlet = m_outlets[0].get();
if (!has_model) {
outlet->send(symbol("none"));
} else {
std::string path = m_path;
outlet->send(symbol(path));
}
}
void nn_info::dump_methods() {
if (!has_model) {
cerr << "please set a model before" << endl;
return;
}
// Iterating over the keys
auto outlet = m_outlets[1].get();
for (const auto& pair : m_model_info.method_properties) {
auto key = pair.first;
outlet->send({symbol("method"), symbol(key)});
}
}
void nn_info::dump_attributes() {
if (!has_model) {
cerr << "please set a model before" << endl;
return;
}
// Iterating over the keys
auto outlet = m_outlets[2].get();
for (const auto& pair : m_model_info.attribute_properties) {
auto key = pair.first;
outlet->send({symbol("attribute"), symbol(key)});
}
}
void nn_info::dump_method_parameters(const std::string& method) {
if (!has_model) {
cerr << "please set a model before" << endl;
return;
}
auto method_props = m_model_info.method_properties;
if (method_props.find(method) == method_props.end()) {
cerr << "method " << method << " does not seem to be valid." << endl;
return;
}
// Iterating over the keys
auto outlet = m_outlets[3].get();
auto params = m_model_info.method_properties[method];
outlet->send({symbol(params.name), symbol("channels_in"), params.channels_in});
outlet->send({symbol(params.name), symbol("channels_out"), params.channels_in});
outlet->send({symbol(params.name), symbol("ratio_in"), params.ratio_out});
outlet->send({symbol(params.name), symbol("ratio_out"), params.ratio_out});
}
void nn_info::dump_attribute_parameters(const std::string& attribute) {
if (!has_model) {
cerr << "please set a model before" << endl;
return;
}
auto attribute_props = m_model_info.attribute_properties;
if (attribute_props.find(attribute) == attribute_props.end()) {
cerr << "attribute " << attribute << " does not seem to be valid." << endl;
return;
}
// Iterating over the keys
auto outlet = m_outlets[3].get();
auto params = m_model_info.attribute_properties[attribute];
atoms attr_types = {symbol(params.name), symbol("attribute_type")};
for (auto attr_type: params.attribute_types)
attr_types.push_back(symbol(attr_type));
outlet->send(attr_types);
}
void nn_info::dump_dictionary() {
// if (!has_model) {
// cerr << "please set a model before" << endl;
// }
// auto dict = nn_tools::dict_from_model_info(m_model_info);
auto outlet = m_outlets[4].get();
auto dict_ref = m_model_dict.get();
if (dict_ref->valid()) {
std::string name = dict_ref->name();
outlet->send({"dictionary", symbol(name)});
} else {
cerr << "internal dictionary (id: )" << dict_ref->name() << " is invalid." << endl;
}
}
void nn_info::dump_downloadable_models() {
auto outlet = m_outlets[5].get();
if (m_available_models_dict.get() == nullptr) {
m_available_models_dict = std::make_unique(symbol(true));
}
try {
if (m_downloader.get()->is_ready()) {
m_downloader.get()->fill_dict(m_available_models_dict.get());
outlet->send({"dictionary", symbol(m_available_models_dict.get()->name())});
}
} catch (std::string& e) {
cerr << "could not get models from api" << endl;
cerr << "reason : " << e << endl;
}
}
void nn_info::dump_object() {
if (!has_model) {
cerr << "please set a model before" << endl;
}
this->dump_methods();
this->dump_attributes();
for (const auto& pair : m_model_info.attribute_properties)
this->dump_attribute_parameters({pair.first});
for (const auto& pair : m_model_info.method_properties)
this->dump_method_parameters({pair.first});
this->dump_dictionary();
this->dump_downloadable_models();
}
nn_info::~nn_info() {
}
MIN_EXTERNAL(nn_info);
================================================
FILE: src/frontend/maxmsp/nn_tilde/CMakeLists.txt
================================================
# Copyright 2018 The Min-DevKit Authors. All rights reserved.
# Use of this source code is governed by the MIT License found in the License.md file.
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(C74_MIN_API_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../min-api)
include(${C74_MIN_API_DIR}/script/min-pretarget.cmake)
if (APPLE)
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.12")
endif()
#############################################################
# MAX EXTERNAL
#############################################################
execute_process(
COMMAND git describe --tags
WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}
OUTPUT_VARIABLE VERSION
OUTPUT_STRIP_TRAILING_WHITESPACE
)
message(${VERSION})
add_definitions(-DVERSION="${VERSION}")
set(
SOURCE_FILES
nn_tilde.cpp
)
add_library(
${PROJECT_NAME}
MODULE
${SOURCE_FILES}
)
include(${C74_MIN_API_DIR}/script/min-posttarget.cmake)
if (MSVC)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT")
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20)
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD_REQUIRED ON)
target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_20)
endif()
include_directories(
"${C74_INCLUDES}"
"${CMAKE_CURRENT_SOURCE_DIR}/../shared"
"${CMAKE_CURRENT_SOURCE_DIR}/../../shared"
)
include_directories(
"${MAX_SDK_INCLUDES}"
"${MAX_SDK_MSP_INCLUDES}"
"${MAX_SDK_JIT_INCLUDES}"
)
if (MSVC)
include_directories(${VCPKG_INCLUDE_DIR})
link_directories(${VCPKG_LIB_DIR})
endif()
target_include_directories(${PROJECT_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/frontend/maxmsp/min-api/max-sdk-base/c74support/max-includes")
target_link_libraries(${PROJECT_NAME} PRIVATE backend)
if (UNIX)
set(CONDA_ENV_PATH "${CMAKE_SOURCE_DIR}/../env")
set(CURL_INCLUDE_DIR "${CONDA_ENV_PATH}/include")
set(CURL_LIBRARY "${CONDA_ENV_PATH}/lib/libcurl.dylib")
include_directories(${CURL_INCLUDE_DIR})
elseif(MSVC)
set(VCPKG_PATH "${CMAKE_SOURCE_DIR}/../vcpkg")
set(CURL_INCLUDE_DIR "${VCPKG_PATH}/packages/curl_x64-windows/include")
set(CURL_LIBRARY "${VCPKG_PATH}/packages/curl_x64-windows/lib/libcurl.lib")
endif()
target_link_libraries(${PROJECT_NAME} PRIVATE nlohmann_json::nlohmann_json)
target_link_libraries(${PROJECT_NAME} PRIVATE ${CURL_LIBRARY})
if (APPLE) # SEARCH FOR TORCH DYLIB IN THE LOADER FOLDER
set_target_properties(${PROJECT_NAME} PROPERTIES
BUILD_WITH_INSTALL_RPATH FALSE
# LINK_FLAGS "-Wl,-rpath,@loader_path/"
LINK_FLAGS "-Wl"
)
add_custom_command(
TARGET ${PROJECT_NAME}
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_SOURCE_DIR}/../env/ssl/cert.pem" "$"
COMMAND ${CMAKE_SOURCE_DIR}/../env/bin/python ${CMAKE_SOURCE_DIR}/../install/dylib_fix.py -p "$" -o "${CMAKE_SOURCE_DIR}/support" -l "${torch_dir}/libtorch" "${CMAKE_BINARY_DIR}/_deps" "${CMAKE_SOURCE_DIR}/../env" "${HOMEBREW_PREFIX}" --sign_id "${SIGN_ID}"
COMMENT "Fixing libraries, certificates, permissions, codesigning, quarantine"
)
endif()
if (MSVC)
set_property(TARGET ${PROJECT_NAME} PROPERTY CXX_STANDARD 20)
endif()
================================================
FILE: src/frontend/maxmsp/nn_tilde/nn_tilde.cpp
================================================
#include "../shared/nn_base.h"
#include "c74_min.h"
template
void model_perform(nn_class* nn_instance) {
std::vector in_model, out_model;
for (int c(0); c < nn_instance->m_model_in; c++)
in_model.push_back(nn_instance->m_in_model[c].get());
for (int c(0); c < nn_instance->m_model_out; c++)
out_model.push_back(nn_instance->m_out_model[c].get());
if (nn_instance->had_buffer_reset) {
nn_instance->had_buffer_reset = false;
}
nn_instance->m_model->perform(in_model, out_model,
nn_instance->m_method,
1, nn_instance->m_out_model.size(), nn_instance->m_buffer_size);
}
template
void model_perform_async(nn_class *nn_instance) {
while (!nn_instance->can_perform()){
std::this_thread::sleep_for(std::chrono::milliseconds(REFRESH_THREAD_INTERVAL));
if (nn_instance->m_should_stop_perform_thread) {
return;
}
}
std::vector in_model, out_model;
if (nn_instance->wait_for_buffer_reset) {
nn_instance->init_buffers();
}
for (int c(0); c < nn_instance->m_model_in; c++)
in_model.push_back(nn_instance->m_in_model[c].get());
for (int c(0); c < nn_instance->m_model_out; c++)
out_model.push_back(nn_instance->m_out_model[c].get());
while (!nn_instance->m_should_stop_perform_thread) {
if (nn_instance->m_data_available_lock.try_acquire_for(
std::chrono::milliseconds(REFRESH_THREAD_INTERVAL))) {
if (nn_instance->wait_for_buffer_reset) {
nn_instance->init_buffers();
}
if (nn_instance->had_buffer_reset) {
in_model.clear();
for (int c(0); c < nn_instance->m_model_in; c++) {
in_model.push_back(nn_instance->m_in_model[c].get());
}
out_model.clear();
for (int c(0); c < nn_instance->m_model_out; c++) {
out_model.push_back(nn_instance->m_out_model[c].get());
}
nn_instance->had_buffer_reset = false;
}
nn_instance->m_model->perform(in_model, out_model,
nn_instance->m_method,
1, nn_instance->m_out_model.size(), nn_instance->m_buffer_size);
nn_instance->m_result_available_lock.release();
}
}
}
class nn: public nn_base> {
public:
MIN_DESCRIPTION{"Interface for deep learning models"};
MIN_TAGS{"audio, deep learning, ai"};
MIN_AUTHOR{"Antoine Caillon & Axel Chemla--Romeu-Santos"};
MIN_RELATED{"nn.info, mc.nn~, mcs.nn~"};
static std::string get_external_name() {
return std::string("nn~");
}
nn(const atoms &args = {}) {
init_external(args);
}
int get_sample_rate() override {
return samplerate();
}
void init_process() override {
nn_base::init_process();
if (m_use_thread) {
m_compute_thread = std::make_unique(model_perform_async, this);
}
}
void init_external(const atoms &args) override {
DEBUG_PRINT("initializing model");
init_model();
DEBUG_PRINT("initializing downloader");
init_downloader();
if (!args.size()) { return; }
DEBUG_PRINT("initializing inputs & outputs");
init_inputs_and_outputs(args);
DEBUG_PRINT("initializing inlets & outlets");
init_inlets_and_outlets();
// DEBUG_PRINT("initializing buffers");
// init_buffers();
DEBUG_PRINT("initializing process");
init_process();
}
void perform(audio_bundle input, audio_bundle output) override;
message<> maxclass_setup{
this, "maxclass_setup",
[this](const c74::min::atoms &args, const int inlet) -> c74::min::atoms {
cout << "nn~ " << VERSION << " - torch " << TORCH_VERSION
<< " - 2023-2025 - Antoine Caillon & Axel Chemla--Romeu-Santos" << endl;
cout << "visit https://www.github.com/acids-ircam" << endl;
return {};
}};
};
void nn::perform(audio_bundle input, audio_bundle output) {
auto vec_size = input.frame_count();
if (m_ready) {
// COPY INPUT TO CIRCULAR BUFFER
for (int c(0); c < input.channel_count(); c++) {
auto in = input.samples(c);
m_in_buffer[c].put(in, vec_size);
}
if (m_in_buffer[0].full()) { // BUFFER IS FULL
if (!m_use_thread) {
if (wait_for_buffer_reset) {
init_buffers();
}
// TRANSFER MEMORY BETWEEN INPUT CIRCULAR BUFFER AND MODEL BUFFER
auto n_ins = std::min(n_inlets, m_model_in);
for (int c(0); c < n_ins; c++)
m_in_buffer[c].get(m_in_model[c].get(), m_buffer_size);
// CALL MODEL PERFORM IN CURRENT THREAD
model_perform(this);
// TRANSFER MEMORY BETWEEN OUTPUT CIRCULAR BUFFER AND MODEL BUFFER
auto n_outs = std::min(n_outlets, m_model_out);
for (int c(0); c < n_outs; c++)
m_out_buffer[c].put(m_out_model[c].get(), m_buffer_size);
} else {
if (m_result_available_lock.try_acquire()) {
// TRANSFER MEMORY BETWEEN INPUT CIRCULAR BUFFER AND MODEL BUFFER
if (wait_for_buffer_reset) {
init_buffers();
}
auto n_ins = std::min(n_inlets, m_model_in);
for (int c(0); c < n_ins; c++)
m_in_buffer[c].get(m_in_model[c].get(), m_buffer_size);
// TRANSFER MEMORY BETWEEN OUTPUT CIRCULAR BUFFER AND MODEL BUFFER
auto n_outs = std::min(n_outlets, m_model_out);
for (int c(0); c < n_outs; c++)
m_out_buffer[c].put(m_out_model[c].get(), m_buffer_size);
// SIGNAL PERFORM THREAD THAT DATA IS AVAILABLE
m_data_available_lock.release();
}
}
}
// COPY CIRCULAR BUFFER TO OUTPUT
for (int c(0); c < output.channel_count(); c++) {
auto out = output.samples(c);
m_out_buffer[c].get(out, vec_size);
}
}
}
MIN_EXTERNAL(nn);
================================================
FILE: src/frontend/maxmsp/nn_tilde/nn_tilde_test.cpp
================================================
#include "c74_min.h"
#include "c74_min_unittest.h"
#include "nn_tilde.cpp"
#include
SCENARIO("object produces correct output") {
ext_main(nullptr);
GIVEN("An instance of nn~ without parameters") {
nn my_object;
WHEN("a buffer is given") {
sample_vector input(4096);
sample_vector output;
for (int i(0); i < 10; i++) {
for (auto x : input) {
auto y = my_object(x);
output.push_back(y);
}
}
}
}
GIVEN("An instance of nn~ with parameters") {
atom path("/Users/acaillon/Desktop/nn.ts"), method("forward");
atoms args = {path, method};
nn my_object = nn(args);
WHEN("a buffer is given") {
sample_vector input(4096);
sample_vector output;
for (int i(0); i < 10; i++) {
for (auto x : input) {
auto y = my_object(x);
output.push_back(y);
}
}
}
}
}
================================================
FILE: src/frontend/maxmsp/nn_tilde/nn~.maxhelp
================================================
{
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 8,
"minor" : 6,
"revision" : 5,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 361.0, 234.0, 733.0, 542.0 ],
"bglocked" : 0,
"openinpresentation" : 0,
"default_fontsize" : 12.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 1,
"gridsize" : [ 15.0, 15.0 ],
"gridsnaponopen" : 1,
"objectsnaponopen" : 1,
"statusbarvisible" : 2,
"toolbarvisible" : 1,
"lefttoolbarpinned" : 0,
"toptoolbarpinned" : 0,
"righttoolbarpinned" : 0,
"bottomtoolbarpinned" : 0,
"toolbars_unpinned_last_save" : 2,
"tallnewobj" : 0,
"boxanimatetime" : 200,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"description" : "",
"digest" : "",
"tags" : "",
"style" : "",
"subpatcher_template" : "",
"showontab" : 1,
"assistshowspatchername" : 0,
"boxes" : [ {
"box" : {
"id" : "obj-4",
"maxclass" : "newobj",
"numinlets" : 0,
"numoutlets" : 0,
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 8,
"minor" : 6,
"revision" : 5,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 0.0, 26.0, 733.0, 516.0 ],
"bglocked" : 0,
"openinpresentation" : 0,
"default_fontsize" : 12.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 1,
"gridsize" : [ 15.0, 15.0 ],
"gridsnaponopen" : 1,
"objectsnaponopen" : 1,
"statusbarvisible" : 2,
"toolbarvisible" : 1,
"lefttoolbarpinned" : 0,
"toptoolbarpinned" : 0,
"righttoolbarpinned" : 0,
"bottomtoolbarpinned" : 0,
"toolbars_unpinned_last_save" : 0,
"tallnewobj" : 0,
"boxanimatetime" : 200,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"description" : "",
"digest" : "",
"tags" : "",
"style" : "",
"subpatcher_template" : "",
"showontab" : 1,
"assistshowspatchername" : 0,
"boxes" : [ {
"box" : {
"hidden" : 1,
"id" : "obj-27",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 512.0, 196.0, 70.0, 22.0 ],
"text" : "loadmess 0"
}
}
, {
"box" : {
"attr" : "enable",
"hidden" : 1,
"id" : "obj-28",
"maxclass" : "attrui",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "" ],
"parameter_enable" : 0,
"patching_rect" : [ 512.0, 227.0, 150.0, 22.0 ]
}
}
, {
"box" : {
"fontface" : 1,
"id" : "obj-26",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 353.0, 425.0, 111.5, 20.0 ],
"text" : "mcs.nn~ version"
}
}
, {
"box" : {
"id" : "obj-25",
"maxclass" : "mc.ezdac~",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 353.0, 371.0, 45.0, 45.0 ]
}
}
, {
"box" : {
"id" : "obj-24",
"maxclass" : "newobj",
"numinlets" : 3,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 353.0, 320.0, 142.0, 22.0 ],
"text" : "mcs.nn~ wheel decode 3"
}
}
, {
"box" : {
"basictuning" : 440,
"data" : {
"clips" : [ {
"absolutepath" : "morph.256.rom.aif",
"filename" : "morph.256.rom.aif",
"filekind" : "audiofile",
"id" : "u741009561",
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-21",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 414.5, 115.0, 150.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"basictuning" : 440,
"data" : {
"clips" : [ {
"absolutepath" : "eroica.aiff",
"filename" : "eroica.aiff",
"filekind" : "audiofile",
"id" : "u702009436",
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-22",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 476.0, 157.0, 150.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"basictuning" : 440,
"data" : {
"clips" : [ {
"absolutepath" : "drumLoop.aif",
"filename" : "drumLoop.aif",
"filekind" : "audiofile",
"id" : "u689009351",
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-23",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 353.0, 75.0, 150.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"id" : "obj-20",
"maxclass" : "newobj",
"numinlets" : 3,
"numoutlets" : 3,
"outlettype" : [ "", "", "" ],
"patching_rect" : [ 353.0, 264.0, 142.0, 22.0 ],
"text" : "mcs.nn~ wheel encode 3"
}
}
, {
"box" : {
"fontface" : 1,
"id" : "obj-16",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 24.0, 425.0, 101.0, 20.0 ],
"text" : "mc.nn~ version"
}
}
, {
"box" : {
"id" : "obj-14",
"maxclass" : "mc.ezdac~",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 24.0, 371.0, 45.0, 45.0 ]
}
}
, {
"box" : {
"id" : "obj-9",
"maxclass" : "newobj",
"numinlets" : 3,
"numoutlets" : 1,
"outlettype" : [ "multichannelsignal" ],
"patching_rect" : [ 24.0, 219.0, 70.0, 22.0 ],
"text" : "mc.pack~ 3"
}
}
, {
"box" : {
"basictuning" : 440,
"data" : {
"clips" : [ {
"absolutepath" : "morph.256.rom.aif",
"filename" : "morph.256.rom.aif",
"filekind" : "audiofile",
"id" : "u741009561",
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-8",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 49.5, 115.0, 150.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"basictuning" : 440,
"data" : {
"clips" : [ {
"absolutepath" : "eroica.aiff",
"filename" : "eroica.aiff",
"filekind" : "audiofile",
"id" : "u702009436",
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-6",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 75.0, 157.0, 150.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"basictuning" : 440,
"data" : {
"clips" : [ {
"absolutepath" : "drumLoop.aif",
"filename" : "drumLoop.aif",
"filekind" : "audiofile",
"id" : "u689009351",
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-4",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 24.0, 75.0, 150.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"id" : "obj-2",
"maxclass" : "newobj",
"numinlets" : 8,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 24.0, 320.0, 176.5, 22.0 ],
"text" : "mc.nn~ wheel decode"
}
}
, {
"box" : {
"id" : "obj-1",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 8,
"outlettype" : [ "", "", "", "", "", "", "", "" ],
"patching_rect" : [ 24.0, 264.0, 176.5, 22.0 ],
"text" : "mc.nn~ wheel encode"
}
}
, {
"box" : {
"id" : "obj-18",
"linecount" : 3,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 13.0, 11.0, 321.0, 47.0 ],
"text" : "nn~ has two multi-channel versions : \n - mc.nn~ that batches inputs among mc channels\n - mcs.nn~ that batches inputs among inlets"
}
}
],
"lines" : [ {
"patchline" : {
"destination" : [ "obj-2", 7 ],
"source" : [ "obj-1", 7 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 6 ],
"source" : [ "obj-1", 6 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 5 ],
"source" : [ "obj-1", 5 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 4 ],
"source" : [ "obj-1", 4 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 3 ],
"source" : [ "obj-1", 3 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 2 ],
"source" : [ "obj-1", 2 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 1 ],
"source" : [ "obj-1", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 0 ],
"source" : [ "obj-1", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-14", 0 ],
"source" : [ "obj-2", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-24", 2 ],
"source" : [ "obj-20", 2 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-24", 1 ],
"source" : [ "obj-20", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-24", 0 ],
"source" : [ "obj-20", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-20", 1 ],
"source" : [ "obj-21", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-20", 2 ],
"source" : [ "obj-22", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-20", 0 ],
"source" : [ "obj-23", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-25", 0 ],
"source" : [ "obj-24", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-28", 0 ],
"hidden" : 1,
"midpoints" : [ 521.5, 219.0, 521.5, 219.0 ],
"source" : [ "obj-27", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"hidden" : 1,
"order" : 3,
"source" : [ "obj-28", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 0 ],
"hidden" : 1,
"order" : 2,
"source" : [ "obj-28", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-20", 0 ],
"hidden" : 1,
"order" : 1,
"source" : [ "obj-28", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-24", 0 ],
"hidden" : 1,
"order" : 0,
"source" : [ "obj-28", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-9", 0 ],
"source" : [ "obj-4", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-9", 2 ],
"source" : [ "obj-6", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-9", 1 ],
"source" : [ "obj-8", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"source" : [ "obj-9", 0 ]
}
}
]
}
,
"patching_rect" : [ 320.0, 32.0, 86.0, 22.0 ],
"saved_object_attributes" : {
"description" : "",
"digest" : "",
"globalpatchername" : "",
"tags" : ""
}
,
"text" : "p \"mc support\""
}
}
, {
"box" : {
"id" : "obj-3",
"maxclass" : "newobj",
"numinlets" : 0,
"numoutlets" : 0,
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 8,
"minor" : 6,
"revision" : 5,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 0.0, 26.0, 733.0, 516.0 ],
"bglocked" : 0,
"openinpresentation" : 0,
"default_fontsize" : 12.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 1,
"gridsize" : [ 15.0, 15.0 ],
"gridsnaponopen" : 1,
"objectsnaponopen" : 1,
"statusbarvisible" : 2,
"toolbarvisible" : 1,
"lefttoolbarpinned" : 0,
"toptoolbarpinned" : 0,
"righttoolbarpinned" : 0,
"bottomtoolbarpinned" : 0,
"toolbars_unpinned_last_save" : 0,
"tallnewobj" : 0,
"boxanimatetime" : 200,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"description" : "",
"digest" : "",
"tags" : "",
"style" : "",
"subpatcher_template" : "",
"showontab" : 1,
"assistshowspatchername" : 0,
"boxes" : [ {
"box" : {
"fontface" : 1,
"fontsize" : 24.0,
"id" : "obj-3",
"linecount" : 2,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 23.0, 32.0, 284.0, 60.0 ],
"text" : "UnConDiTiOnAl GeNeRAtiOn"
}
}
, {
"box" : {
"id" : "obj-7",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 23.0, 310.0, 35.0, 22.0 ],
"text" : "dac~"
}
}
, {
"box" : {
"id" : "obj-6",
"maxclass" : "newobj",
"numinlets" : 8,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 23.0, 261.0, 106.0, 22.0 ],
"text" : "nn~ wheel decode"
}
}
, {
"box" : {
"id" : "obj-14",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 23.0, 124.0, 70.0, 22.0 ],
"text" : "loadmess 0"
}
}
, {
"box" : {
"id" : "obj-2",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 8,
"outlettype" : [ "signal", "signal", "signal", "signal", "signal", "signal", "signal", "signal" ],
"patching_rect" : [ 23.0, 220.0, 105.999999999999986, 22.0 ],
"text" : "nn~ wheel prior"
}
}
, {
"box" : {
"attr" : "enable",
"id" : "obj-8",
"maxclass" : "attrui",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "" ],
"parameter_enable" : 0,
"patching_rect" : [ 23.0, 175.0, 150.0, 22.0 ]
}
}
],
"lines" : [ {
"patchline" : {
"destination" : [ "obj-8", 0 ],
"midpoints" : [ 32.5, 169.0, 32.5, 169.0 ],
"source" : [ "obj-14", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 7 ],
"source" : [ "obj-2", 7 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 6 ],
"source" : [ "obj-2", 6 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 5 ],
"source" : [ "obj-2", 5 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 4 ],
"source" : [ "obj-2", 4 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 3 ],
"source" : [ "obj-2", 3 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 2 ],
"source" : [ "obj-2", 2 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 1 ],
"source" : [ "obj-2", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 0 ],
"source" : [ "obj-2", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-7", 1 ],
"order" : 0,
"source" : [ "obj-6", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-7", 0 ],
"order" : 1,
"source" : [ "obj-6", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 0 ],
"midpoints" : [ 32.5, 199.0, 32.5, 199.0 ],
"order" : 1,
"source" : [ "obj-8", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 0 ],
"order" : 0,
"source" : [ "obj-8", 0 ]
}
}
]
}
,
"patching_rect" : [ 506.0, 32.0, 51.0, 22.0 ],
"saved_object_attributes" : {
"description" : "",
"digest" : "",
"globalpatchername" : "",
"tags" : ""
}
,
"text" : "p bonus"
}
}
, {
"box" : {
"id" : "obj-2",
"maxclass" : "newobj",
"numinlets" : 0,
"numoutlets" : 0,
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 8,
"minor" : 6,
"revision" : 5,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 0.0, 26.0, 733.0, 516.0 ],
"bglocked" : 0,
"openinpresentation" : 0,
"default_fontsize" : 12.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 1,
"gridsize" : [ 15.0, 15.0 ],
"gridsnaponopen" : 1,
"objectsnaponopen" : 1,
"statusbarvisible" : 2,
"toolbarvisible" : 1,
"lefttoolbarpinned" : 0,
"toptoolbarpinned" : 0,
"righttoolbarpinned" : 0,
"bottomtoolbarpinned" : 0,
"toolbars_unpinned_last_save" : 0,
"tallnewobj" : 0,
"boxanimatetime" : 200,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"description" : "",
"digest" : "",
"tags" : "",
"style" : "",
"subpatcher_template" : "",
"showontab" : 1,
"assistshowspatchername" : 0,
"boxes" : [ {
"box" : {
"id" : "obj-18",
"linecount" : 3,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 21.0, 26.0, 321.0, 47.0 ],
"text" : "instead of the forward operation, you can for example use the combination of encode and decode to get control over the generation !"
}
}
, {
"box" : {
"id" : "obj-16",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 389.0, 331.0, 41.0, 22.0 ],
"text" : "sig~"
}
}
, {
"box" : {
"id" : "obj-15",
"maxclass" : "newobj",
"numinlets" : 6,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 389.0, 301.0, 107.0, 22.0 ],
"text" : "scale 0. 127. -3. 3."
}
}
, {
"box" : {
"id" : "obj-13",
"maxclass" : "newobj",
"numinlets" : 6,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 339.0, 259.0, 107.0, 22.0 ],
"text" : "scale 0. 127. -3. 3."
}
}
, {
"box" : {
"id" : "obj-11",
"maxclass" : "pictslider",
"numinlets" : 2,
"numoutlets" : 2,
"outlettype" : [ "int", "int" ],
"parameter_enable" : 0,
"patching_rect" : [ 339.0, 126.0, 147.0, 125.0 ]
}
}
, {
"box" : {
"id" : "obj-6",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 339.0, 288.0, 41.0, 22.0 ],
"text" : "sig~"
}
}
, {
"box" : {
"id" : "obj-3",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 94.0, 455.0, 35.0, 22.0 ],
"text" : "dac~"
}
}
, {
"box" : {
"id" : "obj-1",
"maxclass" : "newobj",
"numinlets" : 8,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 94.0, 400.0, 203.0, 22.0 ],
"text" : "nn~ wheel decode"
}
}
, {
"box" : {
"basictuning" : 440,
"data" : {
"clips" : [ {
"absolutepath" : "huge.aiff",
"filename" : "huge.aiff",
"filekind" : "audiofile",
"id" : "u374011037",
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-24",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 180.0, 167.0, 150.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"id" : "obj-14",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 21.0, 140.0, 70.0, 22.0 ],
"text" : "loadmess 0"
}
}
, {
"box" : {
"id" : "obj-2",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 8,
"outlettype" : [ "signal", "signal", "signal", "signal", "signal", "signal", "signal", "signal" ],
"patching_rect" : [ 94.0, 279.0, 203.0, 22.0 ],
"text" : "nn~ wheel encode"
}
}
, {
"box" : {
"attr" : "enable",
"id" : "obj-8",
"maxclass" : "attrui",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "" ],
"parameter_enable" : 0,
"patching_rect" : [ 21.0, 171.0, 150.0, 22.0 ]
}
}
],
"lines" : [ {
"patchline" : {
"destination" : [ "obj-3", 1 ],
"midpoints" : [ 103.5, 442.0, 119.5, 442.0 ],
"order" : 0,
"source" : [ "obj-1", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-3", 0 ],
"midpoints" : [ 103.5, 424.0, 103.5, 424.0 ],
"order" : 1,
"source" : [ "obj-1", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-13", 0 ],
"midpoints" : [ 348.5, 253.0, 348.5, 253.0 ],
"source" : [ "obj-11", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-15", 0 ],
"midpoints" : [ 476.5, 286.0, 398.5, 286.0 ],
"source" : [ "obj-11", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 0 ],
"midpoints" : [ 348.5, 283.0, 348.5, 283.0 ],
"source" : [ "obj-13", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-8", 0 ],
"midpoints" : [ 30.5, 163.0, 30.5, 163.0 ],
"source" : [ "obj-14", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-16", 0 ],
"midpoints" : [ 398.5, 325.0, 398.5, 325.0 ],
"source" : [ "obj-15", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 4 ],
"source" : [ "obj-16", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 7 ],
"midpoints" : [ 287.5, 304.0, 287.5, 304.0 ],
"source" : [ "obj-2", 7 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 6 ],
"midpoints" : [ 261.214285714285722, 304.0, 261.214285714285722, 304.0 ],
"source" : [ "obj-2", 6 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 5 ],
"midpoints" : [ 234.928571428571416, 304.0, 234.928571428571416, 304.0 ],
"source" : [ "obj-2", 5 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 3 ],
"midpoints" : [ 182.357142857142861, 304.0, 182.357142857142861, 304.0 ],
"source" : [ "obj-2", 3 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 2 ],
"midpoints" : [ 156.071428571428555, 304.0, 156.071428571428555, 304.0 ],
"source" : [ "obj-2", 2 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"midpoints" : [ 103.5, 304.0, 103.5, 304.0 ],
"source" : [ "obj-2", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 0 ],
"midpoints" : [ 189.5, 265.0, 103.5, 265.0 ],
"source" : [ "obj-24", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 1 ],
"source" : [ "obj-6", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-1", 0 ],
"midpoints" : [ 30.5, 385.0, 103.5, 385.0 ],
"order" : 0,
"source" : [ "obj-8", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 0 ],
"midpoints" : [ 30.5, 265.0, 103.5, 265.0 ],
"order" : 1,
"source" : [ "obj-8", 0 ]
}
}
]
}
,
"patching_rect" : [ 143.0, 32.0, 71.0, 22.0 ],
"saved_object_attributes" : {
"description" : "",
"digest" : "",
"globalpatchername" : "",
"tags" : ""
}
,
"text" : "p advanced"
}
}
, {
"box" : {
"id" : "obj-1",
"maxclass" : "newobj",
"numinlets" : 0,
"numoutlets" : 0,
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 8,
"minor" : 6,
"revision" : 5,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 0.0, 26.0, 733.0, 516.0 ],
"bglocked" : 0,
"openinpresentation" : 0,
"default_fontsize" : 12.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 1,
"gridsize" : [ 15.0, 15.0 ],
"gridsnaponopen" : 1,
"objectsnaponopen" : 1,
"statusbarvisible" : 2,
"toolbarvisible" : 1,
"lefttoolbarpinned" : 0,
"toptoolbarpinned" : 0,
"righttoolbarpinned" : 0,
"bottomtoolbarpinned" : 0,
"toolbars_unpinned_last_save" : 0,
"tallnewobj" : 0,
"boxanimatetime" : 200,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"description" : "",
"digest" : "",
"tags" : "",
"style" : "",
"subpatcher_template" : "",
"showontab" : 1,
"assistshowspatchername" : 0,
"boxes" : [ {
"box" : {
"bubble" : 1,
"bubblepoint" : 0.2,
"bubbleside" : 2,
"id" : "obj-1",
"linecount" : 4,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 135.5, 83.0, 194.0, 79.0 ],
"presentation_linecount" : 2,
"text" : "trick : the enable flag allows you to enable / disable the internal calculation, saving CPU if you're not using the object."
}
}
, {
"box" : {
"bubble" : 1,
"bubbleside" : 0,
"id" : "obj-55",
"linecount" : 8,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 273.0, 250.0, 371.0, 133.0 ],
"text" : "nn~ is a wrapper that needs : \n- a pretrained checkpoint (here wheel.ts), exported to be compatible with nn~\n- a method (here forward) that will process its inputs. \n\nHere, wheel is a RAVE model whose forward function takes audio as an input, and processes it through its auto-encoder to re-generate the incoming sound. "
}
}
, {
"box" : {
"basictuning" : 440,
"data" : {
"clips" : [ {
"absolutepath" : "huge.aiff",
"filename" : "huge.aiff",
"filekind" : "audiofile",
"id" : "u374011037",
"loop" : 1,
"content_state" : {
"loop" : 1
}
}
]
}
,
"followglobaltempo" : 0,
"formantcorrection" : 0,
"id" : "obj-24",
"maxclass" : "playlist~",
"mode" : "basic",
"numinlets" : 1,
"numoutlets" : 5,
"originallength" : [ 0.0, "ticks" ],
"originaltempo" : 120.0,
"outlettype" : [ "signal", "signal", "signal", "", "dictionary" ],
"parameter_enable" : 0,
"patching_rect" : [ 215.0, 171.0, 150.0, 30.0 ],
"pitchcorrection" : 0,
"quality" : "basic",
"timestretch" : [ 0 ]
}
}
, {
"box" : {
"id" : "obj-17",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 0,
"patching_rect" : [ 215.0, 262.0, 35.0, 22.0 ],
"text" : "dac~"
}
}
, {
"box" : {
"id" : "obj-14",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 52.0, 140.0, 70.0, 22.0 ],
"text" : "loadmess 0"
}
}
, {
"box" : {
"id" : "obj-2",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 215.0, 223.0, 425.0, 22.0 ],
"text" : "nn~ wheel forward"
}
}
, {
"box" : {
"attr" : "enable",
"id" : "obj-8",
"maxclass" : "attrui",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "" ],
"parameter_enable" : 0,
"patching_rect" : [ 52.0, 171.0, 150.0, 22.0 ]
}
}
],
"lines" : [ {
"patchline" : {
"destination" : [ "obj-8", 0 ],
"midpoints" : [ 61.5, 165.0, 61.5, 165.0 ],
"source" : [ "obj-14", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-17", 1 ],
"order" : 0,
"source" : [ "obj-2", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-17", 0 ],
"midpoints" : [ 224.5, 248.0, 224.5, 248.0 ],
"order" : 1,
"source" : [ "obj-2", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 0 ],
"midpoints" : [ 224.5, 203.0, 224.5, 203.0 ],
"source" : [ "obj-24", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 0 ],
"midpoints" : [ 61.5, 215.0, 224.5, 215.0 ],
"source" : [ "obj-8", 0 ]
}
}
]
}
,
"patching_rect" : [ 83.0, 32.0, 51.0, 22.0 ],
"saved_object_attributes" : {
"description" : "",
"digest" : "",
"globalpatchername" : "",
"tags" : ""
}
,
"text" : "p usage"
}
}
, {
"box" : {
"id" : "obj-7",
"maxclass" : "newobj",
"numinlets" : 0,
"numoutlets" : 0,
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 8,
"minor" : 6,
"revision" : 5,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 0.0, 26.0, 733.0, 516.0 ],
"bglocked" : 0,
"openinpresentation" : 0,
"default_fontsize" : 12.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 1,
"gridsize" : [ 15.0, 15.0 ],
"gridsnaponopen" : 1,
"objectsnaponopen" : 1,
"statusbarvisible" : 2,
"toolbarvisible" : 1,
"lefttoolbarpinned" : 0,
"toptoolbarpinned" : 0,
"righttoolbarpinned" : 0,
"bottomtoolbarpinned" : 0,
"toolbars_unpinned_last_save" : 0,
"tallnewobj" : 0,
"boxanimatetime" : 200,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"description" : "",
"digest" : "",
"tags" : "",
"style" : "",
"subpatcher_template" : "",
"showontab" : 1,
"assistshowspatchername" : 0,
"boxes" : [ {
"box" : {
"id" : "obj-3",
"linecount" : 7,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 195.0, 32.0, 232.0, 100.0 ],
"text" : "the last parameter is the buffer size. Increasing it adds latency, but decreases your CPU load. \n\nSetting buffer size to 0 puts your computer under a lot of stress, but allows you to achieve even lower latencies"
}
}
, {
"box" : {
"id" : "obj-14",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 22.0, 25.0, 70.0, 22.0 ],
"text" : "loadmess 0"
}
}
, {
"box" : {
"id" : "obj-2",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "signal" ],
"patching_rect" : [ 22.0, 121.0, 137.0, 22.0 ],
"text" : "nn~ wheel forward 8192"
}
}
, {
"box" : {
"attr" : "enable",
"id" : "obj-8",
"maxclass" : "attrui",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "" ],
"parameter_enable" : 0,
"patching_rect" : [ 22.0, 76.0, 150.0, 22.0 ]
}
}
],
"lines" : [ {
"patchline" : {
"destination" : [ "obj-8", 0 ],
"midpoints" : [ 31.5, 70.0, 31.5, 70.0 ],
"source" : [ "obj-14", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-2", 0 ],
"midpoints" : [ 31.5, 100.0, 31.5, 100.0 ],
"source" : [ "obj-8", 0 ]
}
}
]
}
,
"patching_rect" : [ 221.0, 32.0, 86.0, 22.0 ],
"saved_object_attributes" : {
"description" : "",
"digest" : "",
"globalpatchername" : "",
"tags" : ""
}
,
"text" : "p performance"
}
}
, {
"box" : {
"id" : "obj-5",
"maxclass" : "newobj",
"numinlets" : 0,
"numoutlets" : 0,
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 8,
"minor" : 6,
"revision" : 5,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 0.0, 26.0, 733.0, 516.0 ],
"bglocked" : 0,
"openinpresentation" : 0,
"default_fontsize" : 12.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 1,
"gridsize" : [ 15.0, 15.0 ],
"gridsnaponopen" : 1,
"objectsnaponopen" : 1,
"statusbarvisible" : 2,
"toolbarvisible" : 1,
"lefttoolbarpinned" : 0,
"toptoolbarpinned" : 0,
"righttoolbarpinned" : 0,
"bottomtoolbarpinned" : 0,
"toolbars_unpinned_last_save" : 0,
"tallnewobj" : 0,
"boxanimatetime" : 200,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"description" : "",
"digest" : "",
"tags" : "",
"style" : "",
"subpatcher_template" : "",
"showontab" : 1,
"assistshowspatchername" : 0,
"boxes" : [ {
"box" : {
"fontsize" : 18.0,
"id" : "obj-2",
"linecount" : 7,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 14.0, 97.0, 538.0, 147.0 ],
"presentation_linecount" : 15,
"text" : "nn~ is a general wrapper to embed generative machine learning in Max & PureData. \n\nIt can be used with compatible pre-trained models such as RAVE, AFTER, or vschaos2. You can also use nn~ to interface your own generators by using the provided Python interface (see documentation for advanced use)."
}
}
, {
"box" : {
"fontsize" : 12.0,
"id" : "obj-13",
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 173.0, 56.0, 355.0, 20.0 ],
"text" : "Antoine Caillon & Axel Chemla--Romeu-Santos - ACIDS - ircam"
}
}
, {
"box" : {
"fontsize" : 18.0,
"id" : "obj-9",
"linecount" : 2,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 173.0, 14.0, 233.0, 47.0 ],
"text" : "a max external for real-time ai audio processing"
}
}
, {
"box" : {
"fontsize" : 48.0,
"id" : "obj-1",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 14.0, 14.0, 149.0, 62.0 ],
"text" : "nn~"
}
}
, {
"box" : {
"id" : "obj-60",
"maxclass" : "toggle",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "int" ],
"parameter_enable" : 0,
"patching_rect" : [ 23.0, 346.0, 43.0, 43.0 ]
}
}
, {
"box" : {
"id" : "obj-55",
"linecount" : 9,
"maxclass" : "comment",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 101.0, 270.0, 160.0, 141.0 ],
"text" : "First time here ? Download a pretrained RAVE model by clicking this button ! (~160MB)\n\nOnce downloaded (toggle enabled), re-open this help patch.\n\n"
}
}
, {
"box" : {
"id" : "obj-49",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "int" ],
"patcher" : {
"fileversion" : 1,
"appversion" : {
"major" : 8,
"minor" : 6,
"revision" : 5,
"architecture" : "x64",
"modernui" : 1
}
,
"classnamespace" : "box",
"rect" : [ 615.0, 160.0, 676.0, 522.0 ],
"bglocked" : 0,
"openinpresentation" : 0,
"default_fontsize" : 12.0,
"default_fontface" : 0,
"default_fontname" : "Arial",
"gridonopen" : 1,
"gridsize" : [ 15.0, 15.0 ],
"gridsnaponopen" : 1,
"objectsnaponopen" : 1,
"statusbarvisible" : 2,
"toolbarvisible" : 1,
"lefttoolbarpinned" : 0,
"toptoolbarpinned" : 0,
"righttoolbarpinned" : 0,
"bottomtoolbarpinned" : 0,
"toolbars_unpinned_last_save" : 0,
"tallnewobj" : 0,
"boxanimatetime" : 200,
"enablehscroll" : 1,
"enablevscroll" : 1,
"devicewidth" : 0.0,
"description" : "",
"digest" : "",
"tags" : "",
"style" : "",
"subpatcher_template" : "",
"assistshowspatchername" : 0,
"boxes" : [ {
"box" : {
"comment" : "",
"id" : "obj-12",
"index" : 1,
"maxclass" : "outlet",
"numinlets" : 1,
"numoutlets" : 0,
"patching_rect" : [ 113.0, 455.0, 30.0, 30.0 ]
}
}
, {
"box" : {
"id" : "obj-7",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "int" ],
"patching_rect" : [ 160.0, 311.0, 29.5, 22.0 ],
"text" : "!= 0"
}
}
, {
"box" : {
"id" : "obj-6",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "int" ],
"patching_rect" : [ 113.0, 360.0, 29.5, 22.0 ],
"text" : "&&"
}
}
, {
"box" : {
"comment" : "",
"id" : "obj-1",
"index" : 1,
"maxclass" : "inlet",
"numinlets" : 0,
"numoutlets" : 1,
"outlettype" : [ "bang" ],
"patching_rect" : [ 113.0, 67.0, 30.0, 30.0 ]
}
}
, {
"box" : {
"id" : "obj-43",
"maxclass" : "newobj",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "int" ],
"patching_rect" : [ 113.0, 311.0, 29.5, 22.0 ],
"text" : "=="
}
}
, {
"box" : {
"id" : "obj-42",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 5,
"outlettype" : [ "", "int", "int", "int", "int" ],
"patching_rect" : [ 113.0, 281.0, 113.0, 22.0 ],
"text" : "unpack sym 0 0 0 0"
}
}
, {
"box" : {
"id" : "obj-36",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 113.0, 216.0, 381.0, 22.0 ],
"text" : "get https://nubo.ircam.fr/index.php/s/KdG9Gim46qLnZeL/download $1"
}
}
, {
"box" : {
"id" : "obj-34",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "dictionary", "" ],
"patching_rect" : [ 113.0, 249.0, 45.0, 22.0 ],
"text" : "maxurl"
}
}
, {
"box" : {
"id" : "obj-30",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 113.0, 180.0, 66.0, 22.0 ],
"text" : "$1wheel.ts"
}
}
, {
"box" : {
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-24",
"maxclass" : "message",
"numinlets" : 2,
"numoutlets" : 1,
"outlettype" : [ "" ],
"patching_rect" : [ 113.0, 112.0, 34.0, 22.0 ],
"text" : "path"
}
}
, {
"box" : {
"fontname" : "Arial",
"fontsize" : 12.0,
"id" : "obj-18",
"maxclass" : "newobj",
"numinlets" : 1,
"numoutlets" : 2,
"outlettype" : [ "", "" ],
"patching_rect" : [ 113.0, 149.0, 69.0, 22.0 ],
"save" : [ "#N", "thispatcher", ";", "#Q", "end", ";" ],
"text" : "thispatcher"
}
}
],
"lines" : [ {
"patchline" : {
"destination" : [ "obj-24", 0 ],
"source" : [ "obj-1", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-30", 0 ],
"source" : [ "obj-18", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-18", 0 ],
"source" : [ "obj-24", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-36", 0 ],
"source" : [ "obj-30", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-42", 0 ],
"source" : [ "obj-34", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-34", 0 ],
"source" : [ "obj-36", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-43", 1 ],
"order" : 1,
"source" : [ "obj-42", 2 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-43", 0 ],
"source" : [ "obj-42", 1 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-7", 0 ],
"order" : 0,
"source" : [ "obj-42", 2 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 0 ],
"source" : [ "obj-43", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-12", 0 ],
"source" : [ "obj-6", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-6", 1 ],
"source" : [ "obj-7", 0 ]
}
}
]
}
,
"patching_rect" : [ 23.0, 319.0, 74.0, 22.0 ],
"saved_object_attributes" : {
"description" : "",
"digest" : "",
"globalpatchername" : "",
"tags" : ""
}
,
"text" : "p get_wheel"
}
}
, {
"box" : {
"id" : "obj-26",
"maxclass" : "button",
"numinlets" : 1,
"numoutlets" : 1,
"outlettype" : [ "bang" ],
"parameter_enable" : 0,
"patching_rect" : [ 23.0, 270.0, 43.0, 43.0 ]
}
}
],
"lines" : [ {
"patchline" : {
"destination" : [ "obj-49", 0 ],
"source" : [ "obj-26", 0 ]
}
}
, {
"patchline" : {
"destination" : [ "obj-60", 0 ],
"source" : [ "obj-49", 0 ]
}
}
]
}
,
"patching_rect" : [ 26.0, 32.0, 47.0, 22.0 ],
"saved_object_attributes" : {
"description" : "",
"digest" : "",
"globalpatchername" : "",
"tags" : ""
}
,
"text" : "p basic"
}
}
],
"lines" : [ ],
"dependency_cache" : [ {
"name" : "drumLoop.aif",
"bootpath" : "C74:/media/msp",
"type" : "AIFF",
"implicit" : 1
}
, {
"name" : "eroica.aiff",
"bootpath" : "C74:/docs/tutorial-patchers/msp-tut",
"type" : "AIFF",
"implicit" : 1
}
, {
"name" : "huge.aiff",
"bootpath" : "C74:/docs/tutorial-patchers/msp-tut",
"type" : "AIFF",
"implicit" : 1
}
, {
"name" : "morph.256.rom.aif",
"bootpath" : "C74:/packages/BEAP/misc",
"type" : "AIFF",
"implicit" : 1
}
, {
"name" : "nn~.mxo",
"type" : "iLaX"
}
],
"autosave" : 0
}
}
================================================
FILE: src/frontend/maxmsp/shared/array_tools.h
================================================
#include "ext.h" // standard Max include, always required
#include "ext_obex.h" // required for new style Max object
#include "ext_atomarray.h" // atomarrays
#include "../../../shared/static_buffer.h"
#include
namespace ArrayTools {
namespace min = c74::min;
namespace max = c74::max;
extern "C" max::t_atomarray* arrayobj_findregistered_retain(max::t_symbol* name);
extern "C" max::t_max_err arrayobj_release(max::t_atomarray* aa);
// extern void atomarray_dispose(max::t_atomarray* x);
// extern max::t_atomarray* arrayobj_register(max::t_atomarray* aa, max::t_symbol** name);
// extern max::t_max_err arrayobj_unregister(max::t_atomarray* aa);
// extern max::t_atomarray* arrayobj_findregistered_clone(max::t_symbol* name);
// extern max::t_symbol* arrayobj_namefromptr(max::t_atomarray* aa);
// extern void* max::outlet_array(max::t_outlet* x, max::t_symbol* s);
bool is_array(const min::atom &atom) {
bool result = false;
auto name_max = max::atom_getsym(&atom);
max::t_atomarray* aa = arrayobj_findregistered_retain(name_max);
if (aa) {
arrayobj_release(aa);
return true;
}
return false;
}
long get_length(const min::atom &atom) {
bool result = false;
auto name_max = max::atom_getsym(&atom);
max::t_atomarray* aa = arrayobj_findregistered_retain(name_max);
if (aa) {
long size = atomarray_getsize(aa);
arrayobj_release(aa);
return size;
}
return -1;
}
void fill_long_vector(std::vector &array, const min::atom &atom) {
auto name_max = max::atom_getsym(&atom);
max::t_atomarray* aa = arrayobj_findregistered_retain(name_max);
if (aa) {
if (array.size() != 0) {
throw "array not empty";
}
max::t_atomarray* clone = (max::t_atomarray*)object_clone((max::t_object*)aa); // CLONE, do not potentially modify upstream data
max::t_atom atom_elt;
for (long i = 0; i < max::atomarray_getsize(clone); i++) {
max::atomarray_getindex(clone, i, &atom_elt);
array.emplace_back(max::atom_getlong(&atom_elt));
}
arrayobj_release(aa);
max::atomarray_clear(clone);
max::object_free(clone);
} else {
throw "could not create array";
}
}
void fill_float_vector(std::vector &array, const min::atom &atom) {
auto name_max = max::atom_getsym(&atom);
max::t_atomarray* aa = arrayobj_findregistered_retain(name_max);
if (aa) {
if (array.size() != 0) {
throw "array not empty";
}
max::t_atomarray* clone = (max::t_atomarray*)object_clone((max::t_object*)aa); // CLONE, do not potentially modify upstream data
max::t_atom atom_elt;
for (long i = 0; i < max::atomarray_getsize(clone); i++) {
max::atomarray_getindex(clone, i, &atom_elt);
array.emplace_back(max::atom_getfloat(&atom_elt));
}
arrayobj_release(aa);
max::atomarray_clear(clone);
max::object_free(clone);
} else {
throw "could not create array";
}
}
StaticBuffer static_buffer_from_array(const min::atom &atom) {
auto name_max = max::atom_getsym(&atom);
max::t_atomarray* aa = arrayobj_findregistered_retain(name_max);
if (aa) {
max::t_atomarray* clone = (max::t_atomarray*)object_clone((max::t_object*)aa); // CLONE, do not potentially modify upstream data
long array_size = max::atomarray_getsize(clone);
StaticBuffer out_buffer(1, array_size);
max::t_atom atom_elt;
for (long i = 0; i < max::atomarray_getsize(clone); i++) {
max::atomarray_getindex(clone, i, &atom_elt);
out_buffer.put(max::atom_getfloat(&atom_elt), 0, i);
}
arrayobj_release(aa);
max::atomarray_clear(clone);
max::object_free(clone);
return out_buffer;
} else {
throw std::string("could not create array");
}
}
}
================================================
FILE: src/frontend/maxmsp/shared/buffer_tools.h
================================================
#pragma once
#include "array_tools.h"
#include "../../../backend/backend.h"
#include "../../../shared/static_buffer.h"
#include "c74_min.h"
class BufferManager {
std::vector> m_max_buffers;
std::vector buffer_attributes;
bool buffer_track = false;
public:
BufferManager();
void init_buffer_list(Backend *backend, c74::min::object_base* object);
void link_attribute_to_buffer(std::string buffer_name, c74::min::symbol target_max_buffer);
void append_if_buffer_element(Backend *model, Backend::BufferMap &buffers, c74::min::symbol target_max_buffer, std::string attribute_name, int index);
static int get_buffer_index(std::vector buffer_attributes, std::string buffer_name);
void set_buffer_tracking(bool buffer_tracking) { buffer_track = buffer_tracking; }
int bind_buffer_attribute(Backend* backend, std::string element, c74::min::object_base* object);
int unbind_buffer_attribute(Backend* backend, std::string element, c74::min::object_base* object);
int modify_buffer_attribute(Backend* backend, std::string element, c74::min::object_base* object);
template
StaticBuffer static_buffer_from_name(std::string buffer_name);
template
static StaticBuffer static_buffer_from_max_buffer(c74::min::buffer_reference* max_buffer);
c74::min::function get_notification_callback(std::string element, c74::min::object_base* object, Backend* backend);
using iterator = std::vector>::iterator;
auto begin() { return m_max_buffers.begin(); }
auto end() { return m_max_buffers.end(); }
std::string string_id() {
std::stringstream str_id;
str_id << this;
return str_id.str();
}
};
BufferManager::BufferManager() {
}
int BufferManager::get_buffer_index(std::vector buffer_attributes, std::string buffer_name) {
int buffer_idx = -1;
for (int i = 0; i < buffer_attributes.size(); i++) {
if (buffer_name == buffer_attributes[i]) {
buffer_idx = i;
break;
}
}
return buffer_idx;
}
void BufferManager::link_attribute_to_buffer(std::string buffer_name, c74::min::symbol target_max_buffer) {
int buffer_index = get_buffer_index(buffer_attributes, buffer_name);
if (buffer_index > -1) {
m_max_buffers[buffer_index].get()->set(target_max_buffer);
} else {
throw "could not link" + buffer_name + "to max buffer" + target_max_buffer.c_str();
}
}
void BufferManager::append_if_buffer_element(Backend *model, Backend::BufferMap &buffers, c74::min::symbol target_max_buffer, std::string attribute_name, int index)
{
if (model->is_buffer_element_of_attribute(attribute_name, index)) {
auto buffer_name = model->get_buffer_name(attribute_name, index);
link_attribute_to_buffer(buffer_name, target_max_buffer);
buffers[buffer_name] = static_buffer_from_name(buffer_name);
} else if (model->is_tensor_element_of_attribute(attribute_name, index)) {
try {
auto buffer_name = model->get_buffer_name(attribute_name, index);
buffers[buffer_name] = ArrayTools::static_buffer_from_array(target_max_buffer);
} catch (std::string &e) {
throw "could not populate element " + std::to_string(index) + " of " + attribute_name + ". Got : " + e;
}
}
}
template
StaticBuffer BufferManager::static_buffer_from_name(std::string buffer_name) {
int buffer_idx = get_buffer_index(buffer_attributes, buffer_name);
if ((buffer_idx == -1) || (buffer_idx > m_max_buffers.size())) {
throw std::string("could not retrieve buffer from name") + buffer_name;
}
c74::min::buffer_reference *buffer_ref = m_max_buffers[buffer_idx].get();
try {
return static_buffer_from_max_buffer(buffer_ref);
} catch (std::string &e) {
// cerr << "could not link buffer " << buffer_name;
// if (buffer_ref->name() != symbol()) {
// cerr << "; buffer name " << buffer_ref->name() << " seems to be invalid.";
// }
// cerr << endl;
throw e;
}
}
template
StaticBuffer BufferManager::static_buffer_from_max_buffer(c74::min::buffer_reference* max_buffer) {
c74::min::buffer_lock b(*max_buffer);
const size_t n_channels = b.channel_count();
const size_t n_samples = b.frame_count();
const double sample_rate = b.samplerate();
if (b.valid()) {
auto data = StaticBuffer(n_channels, n_samples, sample_rate);
for (auto c = 0; c < n_channels; c++) {
for (auto t = 0; t < n_samples; t++) {
data.put(b.lookup(t, c), c, t);
}
}
return data;
} else {
throw "given max buffer is invalid.";
}
};
int BufferManager::bind_buffer_attribute(Backend *backend, std::string element, c74::min::object_base* object) {
if (this->buffer_track) {
std::string method = "print";
// c74::min::atoms args = {string_id(), "cout", element + " modified"};
// object->try_call(method, args);
int buffer_idx = get_buffer_index(buffer_attributes, element);
if (buffer_idx == -1) { return -1; }
auto buffer_name = m_max_buffers[buffer_idx].get()->name();
m_max_buffers[buffer_idx].release();
m_max_buffers[buffer_idx] = std::make_unique(object, get_notification_callback(element, object, backend), false);
m_max_buffers[buffer_idx].get()->set(buffer_name);
// if (current_buffer_ref != bufferRef) {
// m_max_buffers[buffer_idx].release();
// m_max_buffers[buffer_idx] = std::unique_ptr(bufferRef);
// }
try {
auto buffer = static_buffer_from_max_buffer(m_max_buffers[buffer_idx].get());
int res = backend->update_buffer(element, buffer);
return res;
} catch (...) {
c74::min::atoms args = {string_id(), "cerr", "failed to bind buffer " + element};
object->try_call(method, args);
}
}
return -1;
}
int BufferManager::unbind_buffer_attribute(Backend *backend, std::string element, c74::min::object_base* object) {
if (this->buffer_track) {
std::string method = "print";
// c74::min::atoms args = {string_id(), "cout", element + " unbounded"};
// object->try_call(method, args);
// get buffer
int buffer_idx = get_buffer_index(buffer_attributes, element);
if (buffer_idx == -1) { return -1; }
auto current_buffer_ref = m_max_buffers[buffer_idx].get();
// if (current_buffer_ref != bufferRef) {
// m_max_buffers[buffer_idx].release();
// m_max_buffers[buffer_idx] = std::unique_ptr(bufferRef);
// }
try {
int res = backend->reset_buffer(element);
return res;
} catch (...) {
c74::min::atoms args = {string_id(), "cerr", "failed to unbind buffer " + element};
object->try_call(method, args);
}
}
return -1;
}
int BufferManager::modify_buffer_attribute(Backend *backend, std::string element, c74::min::object_base* object) {
if (this->buffer_track) {
std::string method = "print";
// c74::min::atoms args = {string_id(), "cout", element + " modified"};
// object->try_call(method, args);
int buffer_idx = get_buffer_index(buffer_attributes, element);
if (buffer_idx == -1) { return -1; }
auto buffer_name = m_max_buffers[buffer_idx].get()->name();
m_max_buffers[buffer_idx].release();
m_max_buffers[buffer_idx] = std::make_unique(object, get_notification_callback(element, object, backend), false);
m_max_buffers[buffer_idx].get()->set(buffer_name);
// if (current_buffer_ref != bufferRef) {
// m_max_buffers[buffer_idx].release();
// m_max_buffers[buffer_idx] = std::unique_ptr(bufferRef);
// }
try {
auto buffer = static_buffer_from_max_buffer(m_max_buffers[buffer_idx].get());
int res = backend->update_buffer(element, buffer);
return res;
} catch (...) {
c74::min::atoms args = {string_id(), "cerr", "failed to bind buffer " + element};
object->try_call(method, args);
}
}
return -1;
}
c74::min::function BufferManager::get_notification_callback(std::string element, c74::min::object_base* object, Backend* backend) {
c74::min::function bufferCallback =
[this, object, element, backend](const c74::min::atoms& args, const int inlet) -> c74::min::atoms {
int out;
c74::min::symbol buffer_message = args[0];
// cout << "callback" << buffer_message << "for element " << element << "called" << endl;
if (buffer_message == "binding") {
out = this->bind_buffer_attribute(backend, element, object);
} else if (buffer_message == "unbinding") {
out = this->unbind_buffer_attribute(backend, element, object);
} else if (buffer_message == "modified") {
out = this->modify_buffer_attribute(backend, element, object);
} else {
// cerr << "got unsupported buffer notification " << args << "for element" << element << endl;
}
if (out != 0) {
// cerr << "problem setting buffer " << element << endl;
}
return std::vector();
};
return bufferCallback;
}
void BufferManager::init_buffer_list(Backend *backend, c74::min::object_base* object) {
// clear previous buffers
m_max_buffers.clear();
buffer_attributes.clear();
// init model buffers
std::vector model_buffers;
try {
model_buffers = backend->get_buffer_attributes();
} catch (std::exception &e) {
throw std::string("could not retrieve buffers from model. Caught error : ") + e.what();
}
// create buffer references for each of model buffers
for (auto & element : model_buffers) {
std::unique_ptr bufferRef;
// m_max_buffer_callbacks.push_back(bufferCallback);
// add buffer id to buffer_attributes
buffer_attributes.push_back(element);
// add pointer to buffer_reference
m_max_buffers.push_back(std::make_unique(object, get_notification_callback(element, object, backend), false));
}
}
void fill_with_zero(c74::min::audio_bundle output) {
for (int c(0); c < output.channel_count(); c++) {
auto out = output.samples(c);
for (int i(0); i < output.frame_count(); i++) {
out[i] = 0.;
}
}
}
================================================
FILE: src/frontend/maxmsp/shared/dict_utils.h
================================================
#pragma once
#include "c74_min.h"
#include
#include "../../../backend/backend.h"
namespace nn_tools {
namespace min = c74::min;
namespace max = c74::max;
void append_to_dictionary(max::t_dictionary* d, max::t_symbol* key, max::t_dictionary* value) {
auto parsed_value = reinterpret_cast(value);
max::dictionary_appenddictionary(d, key, parsed_value);
}
min::dict dict_from_model_info(const ModelInfo & info) {
auto str = std::stringstream();
auto new_dict = max::dictionary_new();
// // append methods
std::vector method_names {};
auto method_dict = max::dictionary_new();
for (auto method_pair: info.method_properties) {
method_names.push_back(method_pair.first);
auto current_method_dict = max::dictionary_new();
auto method_props = method_pair.second;
max::dictionary_appendlong(current_method_dict, min::symbol("channels_in"), (long)method_props.channels_in);
max::dictionary_appendlong(current_method_dict, min::symbol("channels_out"), (long)method_props.channels_out);
max::dictionary_appendlong(current_method_dict, min::symbol("ratio_in"), (long)method_props.ratio_in);
max::dictionary_appendlong(current_method_dict, min::symbol("ratio_out"), (long)method_props.ratio_out);
append_to_dictionary(method_dict, min::symbol(method_pair.first), current_method_dict);
}
append_to_dictionary(new_dict, min::symbol("methods"), method_dict);
// // append methods
std::vector attribute_names {};
auto attribute_dict = max::dictionary_new();
for (auto attribute_pair: info.attribute_properties) {
attribute_names.push_back(attribute_pair.first);
auto current_attribute_dict = max::dictionary_new();
auto attr_types = attribute_pair.second.attribute_types;
min::atoms attr_types_atoms(attr_types.size());
std::transform(attr_types.begin(), attr_types.end(), attr_types_atoms.begin(),
[](const std::string& str) {
return min::atom(str);
});
max::dictionary_appendatoms(current_attribute_dict, min::symbol("attribute_type"), attr_types_atoms.size(), attr_types_atoms.data());
append_to_dictionary(attribute_dict, min::symbol(attribute_pair.first), current_attribute_dict);
}
append_to_dictionary(new_dict, min::symbol("attributes"), attribute_dict);
auto out_dict = min::dict(new_dict);
return out_dict;
}
void json_walk(max::t_dictionary* dict, nlohmann::json json) {
for (auto& el : json.items()) {
// std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
min::symbol key = el.key();
auto val = el.value();
if (val.is_null()) {
} else if ((json.is_boolean())||(json.is_number_integer())||(json.is_number_unsigned())) {
max::dictionary_appendlong(dict, key, val.get());
} else if (val.is_number_float()) {
max::dictionary_appendfloat(dict, key, val.get());
} else if (val.is_string()) {
max::dictionary_appendsym(dict, key, min::symbol(val.get()));
} else if (val.is_array()) {
std::vector atoms;
for (const auto& v: val){
if ((v.is_boolean())||(v.is_number_integer())||(v.is_number_unsigned())) {
atoms.emplace_back(v.get());
} else if (v.is_number_float()) {
atoms.emplace_back(v.get());
} else if (v.is_string()) {
atoms.emplace_back(v.get());
}
}
max::dictionary_appendatoms(dict, key, atoms.size(), atoms.data());
} else if (val.is_object()) {
auto sub_dict = max::dictionary_new();
json_walk(sub_dict, val);
append_to_dictionary(dict, key, sub_dict);
} else {
std::cerr << "Unknown type" << std::endl;
}
}
}
void fill_dict_with_json(min::dict* dict_to_fill, nlohmann::json json) {
auto global_dict = max::dictionary_new();
json_walk(global_dict, json);
auto min_dict = min::dict(global_dict);
dict_to_fill->copyunique(min_dict);
}
}
================================================
FILE: src/frontend/maxmsp/shared/max_model_download.h
================================================
#pragma once
#include
#include
#include
#include
#include
#include
#include "c74_min.h"
#include
#include "dict_utils.h"
#include "../../../shared/model_download.h"
#ifndef MAX_DOWNLOADS
#define MAX_DOWNLOADS 2
#endif
namespace max = c74::max;
namespace min = c74::min;
class MaxModelDownloader: public ModelDownloader {
c74::min::object_base* d_parent;
public:
MaxModelDownloader(c74::min::object_base* obj);
MaxModelDownloader(c74::min::object_base* obj, std::string external_name);
MaxModelDownloader(c74::min::object_base* obj, fs::path download_location);
void fill_dict(void* dict_to_fill);
void print_to_parent(const std::string &message, const std::string &canal);
fs::path cert_path_from_path(fs::path path) {
#if defined(_WIN32) || defined(_WIN64)
std::string perm_path = (path / ".." / ".." / "support" / "cacert.pem").string();
find_and_replace_char(perm_path, '/', '\\');
#elif defined(__APPLE__) || defined(__MACH__)
std::string perm_path = path / "Contents" / "MacOS" / "cert.pem";
#else
std::string perm_path = (path / "..").string();
#endif
return perm_path;
}
void set_model_directory(const std::string &external_path) {
d_path = fs::absolute(fs::path(external_path) / ".." / ".." / "models");
if (!fs::exists(d_path)) {
fs::create_directories(d_path);
}
}
};
MaxModelDownloader::MaxModelDownloader(c74::min::object_base* obj): d_parent(obj) {
// d_path = d_path / ".." / "nn_tilde" / "models";
min::path path = min::path("nn~", min::path::filetype::external);
std::string path_str = path;
if (path) {
set_model_directory(path_str);
d_cert_path = cert_path_from_path(fs::path(path_str));
}
}
MaxModelDownloader::MaxModelDownloader(c74::min::object_base* obj, std::string external_name): d_parent(obj) {
min::path path = min::path(external_name, min::path::filetype::external);
std::string path_str = path;
fs::path fs_path(path_str);
if (path) {
d_cert_path = cert_path_from_path(fs::path(path_str));
set_model_directory(path_str);
}
}
MaxModelDownloader::MaxModelDownloader(c74::min::object_base* obj, fs::path download_location): ModelDownloader(download_location), d_parent(obj) {
d_path = download_location;
}
void MaxModelDownloader::print_to_parent(const std::string &message, const std::string &canal) {
std::string method = "print";
min::atoms args = {string_id(), canal, message};
d_parent->try_call(method, args);
}
void MaxModelDownloader::fill_dict(void* dict_to_fill) {
if (dict_to_fill == nullptr) {
throw "dict is empty";
}
min::dict* max_dict = static_cast(dict_to_fill);
if (!max_dict->valid()) {
throw "dict is invalid";
}
auto json_models = d_available_models;
nn_tools::fill_dict_with_json(max_dict, json_models);
}
================================================
FILE: src/frontend/maxmsp/shared/nn_base.h
================================================
#include
#include
#include
#include
#include
#include
#include "c74_min.h"
#include "max_model_download.h"
#ifndef CLASS_FLAG_OBJECTAWARE
#define CLASS_FLAG_OBJECTAWARE (0x10000000L) ///< this object can work with 'array' and 'string' objects
#endif
#include "buffer_tools.h"
#include "dict_utils.h"
#include "../../../backend/backend.h"
#include "../../../shared/circular_buffer.h"
#include "../../../shared/static_buffer.h"
#ifndef VERSION
#define VERSION "UNDEFINED"
#endif
#ifndef REFRESH_THREAD_INTERVAL
#define REFRESH_THREAD_INTERVAL 100
#endif
#ifndef DEFAULT_BUFFER_SIZE
#define DEFAULT_BUFFER_SIZE 4096
#endif
using namespace c74::min;
#define DEBUG 0
#ifdef DEBUG
#if DEBUG == 1
#define DEBUG_PRINT(fmt, ...) printf("DEBUG: " fmt "\n", ##__VA_ARGS__)
#else
#define DEBUG_PRINT(fmt, ...)
#endif
#else
#define DEBUG_PRINT(fmt, ...)
#endif
unsigned power_ceil(unsigned x) {
if (x <= 1)
return 1;
int power = 2;
x--;
while (x >>= 1)
power <<= 1;
return power;
}
template
void dumb(nn_name* obj) {
}
template >
class nn_base : public object, public op_type {
public:
using BufferList = std::map>;
nn_base(const atoms &args = {});
~nn_base();
static std::string get_external_name() { return ""; }
// INLETS OUTLETS
std::vector>> m_inlets;
std::vector>> m_outlets;
virtual void init_model();
virtual void init_downloader();
virtual void init_inputs_and_outputs(const atoms& args);
virtual void init_inlets_and_outlets();
virtual void init_buffers();
virtual void init_process();
virtual int get_sample_rate() = 0;
virtual void init_external(const atoms &args) {
init_model();
init_downloader();
if (!args.size()) { return; }
init_inputs_and_outputs(args);
init_inlets_and_outlets();
if (init_buffers_at_init()) {
init_buffers();
} else {
wait_for_buffer_reset = true;
}
init_process();
}
virtual bool init_buffers_at_init() { return true; }
// BACKEND RELATED MEMBERS
std::unique_ptr m_model;
bool m_is_backend_init = false;
bool m_ready = false;
std::string m_method;
std::vector settable_attributes;
c74::min::path m_path;
int n_inlets, m_model_in, m_in_ratio, n_outlets, m_model_out, m_out_ratio, m_higher_ratio, n_batches;
bool has_settable_attribute(std::string attribute);
bool is_valid_print_key(std::string string);
bool buffer_initialised = false;
bool wait_for_buffer_reset = false;
bool had_buffer_reset = true;
bool can_perform() {
if (m_model->is_loaded()) {
if (m_model->has_method(m_method)) {
return true;
}
}
return false;
}
void update_model(const std::string &model);
virtual void load_model(const std::string &model);
virtual void set_method(std::string method);
virtual void update_method(std::string method = "");
path to_model_path(std::string model_path);
// BUFFER ATTRIBUTES MANAGER
BufferManager m_buffer_manager;
// BUFFER RELATED MEMBERS
int m_buffer_size;
int m_buffer_in, m_buffer_out;
std::unique_ptr[]> m_in_buffer;
std::unique_ptr[]> m_out_buffer;
std::vector> m_in_model, m_out_model;
// AUDIO PERFORM
bool m_force_refresh, m_use_thread, m_should_stop_perform_thread;
std::binary_semaphore m_data_available_lock, m_result_available_lock;
std::unique_ptr m_compute_thread;
void operator()(audio_bundle input, audio_bundle output);
virtual void perform(audio_bundle input, audio_bundle output) { }
// FLUX
logger cout;
logger cerr;
logger cwarn;
// HELPERS
virtual void dump_object();
void print_to_cout(std::string &message);
void print_to_cerr(std::string &message);
// DOWNLOAD RELATED ATTRIBUTES
std::unique_ptr m_downloader;
void dump_available_models();
// ONLY FOR DOCUMENTATION
argument path_arg{this, "model path",
"Absolute path to the pretrained model."};
argument method_arg{this, "method",
"Name of the method to call during synthesis."};
argument buffer_arg{
this, "buffer size",
"Size of the internal buffer (can't be lower than the method's ratio)."};
// ENABLE / DISABLE ATTRIBUTE
attribute enable{this, "enable", true,
description{"Enable / disable tensor computation"}};
// ENABLE / DISABLE ATTRIBUTE
attribute gpu{this, "gpu", false,
description{"Enable / disable gpu usage when available"},
setter{[this](const c74::min::atoms &args,
const int inlet) -> c74::min::atoms {
if (m_is_backend_init)
m_model->use_gpu(bool(args[0]));
return args;
}}};
// TRACK BUFFER ATTRIBUTE
attribute track_buffers{this,
"track_buffers",
false,
description{"tracks buffer change for buffer attributes"},
setter{
MIN_FUNCTION{
bool enable_buffer_tracking = args[0];
if (m_is_backend_init) {
this->m_buffer_manager.set_buffer_tracking(enable_buffer_tracking);
}
return args;
}}};
// BOOT STAMP
// message<> maxclass_setup;
message<> print {
this, "print",
MIN_FUNCTION {
bool is_valid = is_valid_print_key(args[0]);
if (!is_valid) {
return {};
}
DEBUG_PRINT("asked to print %s on %s", std::string(args[2]).c_str(), std::string(args[1]).c_str());
if (args[1] == "cout") {
cout << args[2] << endl;
} else if (args[1] == "cerr") {
cerr << args[2] << endl;
} else if (args[1] == "cwarn") {
cwarn << args[2] << endl;
}
return {};
}
};
message<> buffer_notify{
this, "notify",
MIN_FUNCTION {
return buffer_reference::handle_notification(
this,
args,
m_buffer_manager.begin(),
m_buffer_manager.end()
);
}};
message<> dump_callback{
this, "dump",
description{"dumps model information to console"},
MIN_FUNCTION {
this->dump_object();
return {};
}};
message <> get_available_models_callback{
this, "print_available_models",
description{"print available models to console"},
MIN_FUNCTION {
this->dump_available_models();
return {};
}};
message <> download_models {
this, "download",
description{"download a model from IRCAM Forum API"},
MIN_FUNCTION {
std::string model_card, optional_name;
if (args.size() == 0) {
cerr << "please provide a model card (print downloadable models with get_available_models messages)" << endl;
} else if (args.size() == 1) {
min::symbol model_card_s = args[0];
model_card = std::string(model_card_s.c_str());
optional_name = "";
} else {
min::symbol model_card_s = args[0];
min::symbol optional_name_s = args[1];
model_card = std::string(model_card_s.c_str());
optional_name = std::string(optional_name_s.c_str());
}
try {
if (this->m_downloader.get()->is_ready())
this->m_downloader.get()->download(model_card, optional_name);
} catch (std::string &e) {
cerr << e << endl;
}
return {};
}
};
message <> update_method_fn {
this, "method",
description{"set the current method of model"},
MIN_FUNCTION {
if (args.size() == 0) {
cerr << "please provide a method" << endl;
}
std::string method = args[0];
try {
if (m_model->is_loaded()) {
if (!m_model->has_method(method)) {
cerr << "current model does not have method " << method << endl;
return args;
}
}
this->set_method(method);
this->wait_for_buffer_reset = true;
} catch (std::string &e) {
cerr << e << endl;
}
return {};
}
};
message <> delete_models {
this, "delete",
description{"delete a model downloaded from IRCAM Forum API"},
MIN_FUNCTION {
if (args.size() == 0) {
cerr << "please provide a model to delete" << endl;
}
std::string model_card = args[0];
try {
if (this->m_downloader.get()->is_ready())
this->m_downloader.get()->remove(model_card);
} catch (std::string &e) {
cerr << e << endl;
}
return {};
}};
message<> anything{
this, "anything", "callback for attributes",
[this](const c74::min::atoms &args, const int inlet) -> c74::min::atoms {
symbol attribute_name = args[0];
if (attribute_name == "reload") {
m_model->reload();
} else if (attribute_name == "load") {
if (args.size() < 2) {
cerr << "a model path must be given along the model message" << endl;
} else {
std::string model_path = args[1];
update_model(model_path);
}
return {};
} else if (attribute_name == "get_attributes") {
for (std::string attr : settable_attributes) {
cout << attr << endl;
}
return {};
} else if (attribute_name == "get_methods") {
for (std::string method : m_model->get_available_methods())
cout << method << endl;
return {};
} else if (attribute_name == "get") {
if (args.size() < 2) {
cerr << "get must be given an attribute name" << endl;
return {};
}
attribute_name = args[1];
if (m_model->has_settable_attribute(attribute_name)) {
try {
cout << attribute_name << ": "
<< m_model->get_attribute_as_string(attribute_name) << endl;
} catch (std::string& e) {
cout << e << endl;
}
} else {
cerr << "no attribute " << attribute_name << " found in model"
<< endl;
}
return {};
} else if (attribute_name == "set") {
if (args.size() < 3) {
cerr << "set must be given an attribute name and corresponding "
"arguments"
<< endl;
return {};
}
attribute_name = args[1];
std::vector attribute_args;
BufferList buffers;
if (has_settable_attribute(attribute_name)) {
for (int i = 2; i < args.size(); i++) {
// get if argument is buffer
attribute_args.push_back(args[i]);
try {
m_buffer_manager.append_if_buffer_element(m_model.get(), buffers, args[i], attribute_name, i - 2);
} catch (std::string &message) {
cerr << message << endl;
return args;
}
}
try {
m_model->set_attribute(attribute_name, attribute_args, buffers);
} catch (std::string message) {
cerr << message << endl;
}
} else {
cerr << "model does not have attribute " << attribute_name << endl;
}
} else {
cerr << "no corresponding method for " << attribute_name << endl;
}
return {};
}};
};
template
bool nn_base