Skip to content

πŸŽ› πŸ”Š A Python library for audio.

Get CI working properly. (#1)

Peter Sobotb3caaa0f8299
diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml
new file mode 100644
index 0000000..a055931
--- /dev/null
+++ b/.github/workflows/wheels.yml
@@ -0,0 +1,221 @@
+name: Compile, Test, and Deploy
+
+on:
+ pull_request: {}
+ push:
+ branches:
+ - master
+ release:
+ types: [created]
+
+jobs:
+ lint-python:
+ runs-on: ${{ matrix.os }}
+ continue-on-error: true
+ strategy:
+ matrix:
+ python-version: ['3.6', '3.7', '3.8', '3.9', '3.x']
+ os: [ubuntu-latest]
+ name: Lint Python
+ steps:
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v2
+ with:
+ python-version: ${{ matrix.python-version }}
+ - uses: actions/checkout@v2
+ with:
+ submodules: recursive
+ - name: Install lint dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install wheel
+ pip install -r test-requirements.txt
+ - name: Lint Python code
+ run: flake8 . --count --ignore=W503,E203 --exclude .git,dist,doc,build --show-source --statistics --max-line-length 100
+ - name: Check Python formatting
+ run: black pedalboard tests --line-length 100 --experimental-string-processing --diff --check
+
+ lint-cpp:
+ runs-on: ubuntu-latest
+ continue-on-error: true
+ name: Lint C++
+ steps:
+ - uses: actions/checkout@v2
+ # Don't check out submodules, as the action below will look at ALL C++ code!
+ - name: Check C++ Formatting
+ uses: jidicula/[email protected]
+ with:
+ clang-format-version: 11
+ fallback-style: LLVM
+
+ run-tests:
+ runs-on: ${{ matrix.os }}
+ continue-on-error: true
+ env:
+ MINIMUM_COVERAGE_PERCENTAGE: 90
+ strategy:
+ matrix:
+ python-version: ['3.6', '3.7', '3.8', '3.9', '3.x']
+ os: [ubuntu-18.04, ubuntu-latest, windows-latest, macos-10.15, macos-latest]
+ name: Test with Python ${{ matrix.python-version }} on ${{ matrix.os }}
+ steps:
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v2
+ with:
+ python-version: ${{ matrix.python-version }}
+ - uses: actions/checkout@v2
+ with:
+ submodules: recursive
+ - name: Install Linux dependencies
+ if: runner.os == 'Linux'
+ run: |
+ sudo apt-get update \
+ && sudo apt-get install -y pkg-config libsndfile1 \
+ libx11-dev libxrandr-dev libxinerama-dev \
+ libxrender-dev libxcomposite-dev libxcb-xinerama0-dev \
+ libxcursor-dev libfreetype6 libfreetype6-dev
+ - name: Install test dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install wheel
+ pip install -r test-requirements.txt
+ - name: Install JQ for coverage badge on Linux
+ run: sudo apt-get install -y jq
+ if: runner.os == 'Linux'
+ - name: Install JQ for coverage badge on macOS
+ run: brew install jq
+ if: runner.os == 'macOS'
+ - name: Install JQ for coverage badge on Windows
+ run: chocolatey install jq
+ if: runner.os == 'Windows'
+ - name: Build pedalboard locally
+ run: python setup.py install
+ - name: Run tests
+ if: matrix.os != 'ubuntu-latest' || matrix.python-version != '3.6'
+ run: pytest -v --cov-report term --cov-fail-under=${{ env.MINIMUM_COVERAGE_PERCENTAGE }} --cov=pedalboard
+ - name: Run tests with coverage reporting
+ if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.6'
+ run: |
+ pytest -v --cov-report term --cov-fail-under=${{ env.MINIMUM_COVERAGE_PERCENTAGE }} --cov=pedalboard \
+ && coverage json --fail-under=${{ env.MINIMUM_COVERAGE_PERCENTAGE }} \
+ && jq -r 'def roundit: .*100.0 + 0.5|floor/100.0; .totals.percent_covered | round | "COVERAGE_PERCENTAGE=" + (. | tostring) + "%" ' coverage.json >> $GITHUB_ENV \
+ && jq -r 'if .totals.percent_covered > ${{ env.MINIMUM_COVERAGE_PERCENTAGE }} then "COVERAGE_COLOR=green" else "COVERAGE_COLOR=red" end' coverage.json >> $GITHUB_ENV
+ - name: Create coverage badge
+ uses: schneegans/[email protected]
+ if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.6' && github.event_name == 'release' && github.event.action == 'published'
+ with:
+ auth: ${{ secrets.COVERAGE_GIST_SECRET }}
+ gistID: 8736467e9952991ef44a67915ee7c762
+ filename: coverage.json
+ label: Test Coverage
+ message: ${{ env.COVERAGE_PERCENTAGE }}
+ color: ${{ env.COVERAGE_COLOR }}
+
+ run-tests-with-address-sanitizer:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ python-version: ['3.6', '3.7', '3.8', '3.9', '3.x']
+ os: [ubuntu-latest]
+ name: Test with Python ${{ matrix.python-version }} + Address Sanitizer
+ steps:
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v2
+ with:
+ python-version: ${{ matrix.python-version }}
+ - uses: actions/checkout@v2
+ with:
+ submodules: recursive
+ - name: Install Linux dependencies
+ if: runner.os == 'Linux'
+ run: |
+ sudo apt-get update \
+ && sudo apt-get install -y pkg-config libsndfile1 \
+ libx11-dev libxrandr-dev libxinerama-dev \
+ libxrender-dev libxcomposite-dev libxcb-xinerama0-dev \
+ libxcursor-dev libfreetype6 libfreetype6-dev
+ - name: Install test dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install wheel
+ pip install -r test-requirements.txt
+ - name: Build pedalboard locally
+ env:
+ DEBUG: "1"
+ USE_ASAN: "1"
+ CC: clang
+ CXX: clang++
+ run: python setup.py install
+ - name: Run tests with ASan loaded
+ # pytest can exit before all Python objects have been destroyed,
+ # so we tell ASan to ignore leaks.
+ run: |
+ ASAN_OPTIONS=detect_leaks=0 \
+ LD_PRELOAD=$(clang -print-file-name=libclang_rt.asan-x86_64.so) \
+ pytest -v
+
+ build-wheels:
+ runs-on: ${{ matrix.os }}
+ continue-on-error: false
+ strategy:
+ matrix:
+ python-version: ['3.8']
+ os: [ubuntu-latest, windows-latest, macos-10.15, macos-latest]
+ name: Build wheels on ${{ matrix.os }}
+ steps:
+ - uses: actions/checkout@v2
+ with:
+ submodules: recursive
+
+ # Used to host cibuildwheel, so version doesn't really matter
+ - uses: actions/setup-python@v2
+ with:
+ python-version: ${{ matrix.python-version }}
+ - name: Install cibuildwheel
+ run: python -m pip install cibuildwheel>=2.0.0a4
+
+ - name: Build wheels
+ run: python -m cibuildwheel --output-dir wheelhouse
+ env:
+ CIBW_TEST_REQUIRES: -r test-requirements.txt
+ CIBW_TEST_COMMAND: "pytest {project}/tests"
+ CIBW_ARCHS: auto64 # Only support building 64-bit wheels. It's 2021!
+ CIBW_SKIP: '*27* *35*' # Ignore Python 2.x and 3.5. Again, it's 2021!
+ CIBW_ARCHS_MACOS: x86_64 universal2 # Support Apple Silicon
+ CIBW_REPAIR_WHEEL_COMMAND_LINUX: pip install auditwheel-symbols && (auditwheel repair -w {dest_dir} {wheel} || auditwheel-symbols --manylinux 2010 {wheel})
+ CIBW_BEFORE_BUILD_LINUX: |
+ yum install -y libsndfile \
+ libX11-devel \
+ libXrandr-devel \
+ libXinerama-devel \
+ libXrender-devel \
+ libXcomposite-devel \
+ libXinerama-devel \
+ libXcursor-devel \
+ freetype-devel
+ # The manylinux container doesn't have a new enough glibc version,
+ # so we can't run post-wheel-build tests there.
+ # Also testing any pypy versions fails, as TensorFlow isn't pypy compatible.
+ CIBW_TEST_SKIP: "*manylinux* *pp*"
+
+ - uses: actions/upload-artifact@v2
+ with:
+ path: ./wheelhouse/*.whl
+
+ upload-pypi:
+ needs: [lint-python, lint-cpp, build-wheels, run-tests, run-tests-with-address-sanitizer]
+ runs-on: ubuntu-latest
+ name: "Upload wheels to PyPI"
+ # alternatively, to publish when a GitHub Release is created, use the following rule:
+ if: github.event_name == 'release' && github.event.action == 'published'
+ steps:
+ - uses: actions/download-artifact@v2
+ with:
+ name: artifact
+ path: dist
+
+ - uses: pypa/[email protected]
+ with:
+ user: __token__
+ password: ${{ secrets.PYPI_DEPLOY_TOKEN }}
+ repository_url: https://test.pypi.org/legacy/
\ No newline at end of file
diff --git a/README.md b/README.md
index e04c4bb..fafc57a 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,14 @@
![Pedalboard](https://user-images.githubusercontent.com/213293/124613247-0733ae00-de41-11eb-8b14-e990c08e597d.png)
-<!-- TODO: Add badges here -->
+[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
+![PyPI - Python Version](https://img.shields.io/pypi/pyversions/pedalboard)
+![PyPI - Wheel](https://img.shields.io/pypi/wheel/pedalboard)
+[![Test Badge](https://github.com/spotify/pedalboard/actions/workflows/wheels.yml/badge.svg)](https://github.com/spotify/pedalboard/actions/workflows/wheels.yml)
+![GitHub Workflow Status](https://img.shields.io/github/workflow/status/spotify/pedalboard/wheels)
+![Coverage Badge](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/psobot/8736467e9952991ef44a67915ee7c762/raw/coverage.json)
+![GitHub Repo stars](https://img.shields.io/github/stars/spotify/pedalboard?style=social)
+![Supported Platforms](https://img.shields.io/badge/platforms-macOS%20%7C%20Windows%20%7C%20Linux-green)
+![Apple Silicon supported](https://img.shields.io/badge/Apple%20Silicon-supported-brightgreen)
`pedalboard` is a Python library for adding effects to audio. It supports a number of common audio effects out of the box, and also allows the use of [VST3](https://www.steinberg.net/en/company/technologies/vst3.html) and [Audio Unit](https://en.wikipedia.org/wiki/Audio_Units) plugin formats for third-party effects. It was built by [Spotify's Audio Intelligence Lab](https://research.atspotify.com/audio-intelligence/) to enable using studio-quality audio effects from within Python and TensorFlow.
diff --git a/pedalboard/ExternalPlugin.h b/pedalboard/ExternalPlugin.h
index 402f352..9ede37b 100644
--- a/pedalboard/ExternalPlugin.h
+++ b/pedalboard/ExternalPlugin.h
@@ -1,7 +1,24 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#pragma once
-#include <optional>
#include <mutex>
+#include <optional>
#include "JuceHeader.h"
#if JUCE_LINUX
@@ -111,12 +128,15 @@ public:
"Plugin not found or not in the appropriate format.";
pluginFormatManager.addDefaultFormats();
- auto pluginFileStripped = pathToPluginFile.trimCharactersAtEnd(juce::File::getSeparatorString());
- auto fileExists = juce::File::createFileWithoutCheckingPath(pluginFileStripped).exists();
+ auto pluginFileStripped =
+ pathToPluginFile.trimCharactersAtEnd(juce::File::getSeparatorString());
+ auto fileExists =
+ juce::File::createFileWithoutCheckingPath(pluginFileStripped).exists();
if (!fileExists) {
- throw pybind11::import_error("Unable to load plugin " + pathToPluginFile.toStdString() +
- ": plugin file not found.");
+ throw pybind11::import_error("Unable to load plugin " +
+ pathToPluginFile.toStdString() +
+ ": plugin file not found.");
}
pluginList.scanAndAddFile(pluginFileStripped, false, typesFound, format);
@@ -126,33 +146,33 @@ public:
reinstantiatePlugin();
} else {
#if JUCE_LINUX
- auto machineName = []() -> juce::String
- {
- struct utsname unameData;
- auto res = uname (&unameData);
+ auto machineName = []() -> juce::String {
+ struct utsname unameData;
+ auto res = uname(&unameData);
- if (res != 0)
- return {};
+ if (res != 0)
+ return {};
- return unameData.machine;
+ return unameData.machine;
}();
juce::File pluginBundle(pluginFileStripped);
- auto pathToSharedObjectFile = pluginBundle.getChildFile("Contents")
- .getChildFile(machineName + "-linux")
- .getChildFile(pluginBundle.getFileNameWithoutExtension() + ".so");
+ auto pathToSharedObjectFile =
+ pluginBundle.getChildFile("Contents")
+ .getChildFile(machineName + "-linux")
+ .getChildFile(pluginBundle.getFileNameWithoutExtension() + ".so");
throw pybind11::import_error(
- "Unable to load plugin " + pathToPluginFile.toStdString() +
- ": unsupported plugin format or load failure. Plugin files or " +
- "shared library dependencies may be missing. (Try running `ldd \"" +
- pathToSharedObjectFile.getFullPathName().toStdString() + "\"` to " +
- "see which dependencies might be missing.).");
+ "Unable to load plugin " + pathToPluginFile.toStdString() +
+ ": unsupported plugin format or load failure. Plugin files or " +
+ "shared library dependencies may be missing. (Try running `ldd \"" +
+ pathToSharedObjectFile.getFullPathName().toStdString() + "\"` to " +
+ "see which dependencies might be missing.).");
#else
throw pybind11::import_error(
- "Unable to load plugin " + pathToPluginFile.toStdString() +
- ": unsupported plugin format or load failure.");
+ "Unable to load plugin " + pathToPluginFile.toStdString() +
+ ": unsupported plugin format or load failure.");
#endif
}
}
@@ -188,13 +208,13 @@ public:
{
std::lock_guard<std::mutex> lock(EXTERNAL_PLUGIN_MUTEX);
pluginInstance = pluginFormatManager.createPluginInstance(
- foundPluginDescription, ExternalLoadSampleRate,
- ExternalLoadMaximumBlockSize, loadError);
+ foundPluginDescription, ExternalLoadSampleRate,
+ ExternalLoadMaximumBlockSize, loadError);
if (!pluginInstance) {
throw pybind11::import_error("Unable to load plugin " +
- pathToPluginFile.toStdString() + ": " +
- loadError.toStdString());
+ pathToPluginFile.toStdString() + ": " +
+ loadError.toStdString());
}
NUM_ACTIVE_EXTERNAL_PLUGINS++;
@@ -300,7 +320,8 @@ public:
size_t pluginBufferChannelCount = 0;
// Iterate through all input busses and add their input channels to our
// buffer:
- for (size_t i = 0; i < static_cast<size_t>(pluginInstance->getBusCount(true)); i++) {
+ for (size_t i = 0;
+ i < static_cast<size_t>(pluginInstance->getBusCount(true)); i++) {
if (pluginInstance->getBus(true, i)->isEnabled()) {
pluginBufferChannelCount +=
pluginInstance->getBus(true, i)->getNumberOfChannels();
@@ -309,7 +330,7 @@ public:
juce::dsp::AudioBlock<float> &outputBlock = context.getOutputBlock();
- float *channelPointers[pluginBufferChannelCount];
+ std::vector<float *> channelPointers(pluginBufferChannelCount);
for (size_t i = 0; i < outputBlock.getNumChannels(); i++) {
channelPointers[i] = outputBlock.getChannelPointer(i);
@@ -350,7 +371,7 @@ public:
// Create an audio buffer that doesn't actually allocate anything, but
// just points to the data in the ProcessContext.
- juce::AudioBuffer<float> audioBuffer(channelPointers,
+ juce::AudioBuffer<float> audioBuffer(channelPointers.data(),
pluginBufferChannelCount,
outputBlock.getNumSamples());
pluginInstance->processBlock(audioBuffer, emptyMidiBuffer);
@@ -366,6 +387,15 @@ public:
return parameters;
}
+ juce::AudioProcessorParameter *getParameter(const std::string &name) const {
+ for (auto *parameter : pluginInstance->getParameters()) {
+ if (parameter->getName(512).toStdString() == name) {
+ return parameter;
+ }
+ }
+ return nullptr;
+ }
+
private:
constexpr static int ExternalLoadSampleRate = 44100,
ExternalLoadMaximumBlockSize = 8192;
@@ -377,10 +407,9 @@ private:
inline void init_external_plugins(py::module &m) {
py::class_<juce::AudioProcessorParameter>(
- m, "AudioProcessorParameter",
+ m, "_AudioProcessorParameter",
"An abstract base class for parameter objects that can be added to an "
- "AudioProcessor.",
- py::dynamic_attr())
+ "AudioProcessor.")
.def("__repr__",
[](juce::AudioProcessorParameter &parameter) {
std::ostringstream ss;
@@ -514,7 +543,10 @@ inline void init_external_plugins(py::module &m) {
"Pedalboard.")
.def_property_readonly(
"_parameters", &ExternalPlugin<juce::VST3PluginFormat>::getParameters,
- py::return_value_policy::reference_internal);
+ py::return_value_policy::reference_internal)
+ .def("_get_parameter",
+ &ExternalPlugin<juce::VST3PluginFormat>::getParameter,
+ py::return_value_policy::reference_internal);
#endif
#if JUCE_PLUGINHOST_AU && JUCE_MAC
@@ -548,7 +580,11 @@ inline void init_external_plugins(py::module &m) {
"Pedalboard.")
.def_property_readonly(
"_parameters",
- &ExternalPlugin<juce::AudioUnitPluginFormat>::getParameters);
+ &ExternalPlugin<juce::AudioUnitPluginFormat>::getParameters,
+ py::return_value_policy::reference_internal)
+ .def("_get_parameter",
+ &ExternalPlugin<juce::AudioUnitPluginFormat>::getParameter,
+ py::return_value_policy::reference_internal);
#endif
}
diff --git a/pedalboard/JuceHeader.h b/pedalboard/JuceHeader.h
index cb6fa6b..cf5522b 100644
--- a/pedalboard/JuceHeader.h
+++ b/pedalboard/JuceHeader.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
/*
This file is usually created by the Projucer, but as we're building a Python
package, this is custom-managed.
diff --git a/pedalboard/JucePlugin.h b/pedalboard/JucePlugin.h
index d43dbb9..cb83144 100644
--- a/pedalboard/JucePlugin.h
+++ b/pedalboard/JucePlugin.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#pragma once
#include "JuceHeader.h"
diff --git a/pedalboard/Plugin.h b/pedalboard/Plugin.h
index b30b456..ac1789e 100644
--- a/pedalboard/Plugin.h
+++ b/pedalboard/Plugin.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#pragma once
#include "JuceHeader.h"
diff --git a/pedalboard/__init__.py b/pedalboard/__init__.py
index 4a96004..6a7101f 100644
--- a/pedalboard/__init__.py
+++ b/pedalboard/__init__.py
@@ -1,3 +1,20 @@
+#! /usr/bin/env python
+#
+# Copyright 2021 Spotify AB
+#
+# Licensed under the GNU Public License, Version 3.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.gnu.org/licenses/gpl-3.0.html
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
from pedalboard_native import * # noqa: F403, F401
from .pedalboard import Pedalboard, AVAILABLE_PLUGIN_CLASSES, load_plugin # noqa: F401
diff --git a/pedalboard/pedalboard.py b/pedalboard/pedalboard.py
index d3a1bb1..bd080ae 100644
--- a/pedalboard/pedalboard.py
+++ b/pedalboard/pedalboard.py
@@ -1,12 +1,29 @@
+#! /usr/bin/env python
+#
+# Copyright 2021 Spotify AB
+#
+# Licensed under the GNU Public License, Version 3.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.gnu.org/licenses/gpl-3.0.html
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
import collections
import platform
import weakref
from functools import update_wrapper
+from contextlib import contextmanager
from typing import List, Optional, Dict, Union, Tuple, Iterable
import numpy as np
-from pedalboard_native import Plugin, process, AudioProcessorParameter
+from pedalboard_native import Plugin, process, _AudioProcessorParameter
class Pedalboard(collections.MutableSequence):
@@ -138,9 +155,9 @@ def wrap_type(base_type):
return base_type.__new__(cls)
def __init__(self, *args, **kwargs):
- if 'wrapped' in kwargs:
- self._wrapped = weakref.ref(kwargs['wrapped'])
- del kwargs['wrapped']
+ if "wrapped" in kwargs:
+ self._wrapped = weakref.ref(kwargs["wrapped"])
+ del kwargs["wrapped"]
else:
raise ValueError(
"WeakTypeWrapper({}) expected to be passed a 'wrapped' keyword argument."
@@ -201,11 +218,16 @@ FloatWithParameter = wrap_type(float)
BooleanWithParameter = wrap_type(WrappedBool)
-TRUE_BOOLEANS = {'on', 'yes', 'true', 'enabled'}
+TRUE_BOOLEANS = {"on", "yes", "true", "enabled"}
-def supplement_parameter(self: AudioProcessorParameter, search_steps: int = 1000):
+class AudioProcessorParameter(object):
"""
+ The C++ version of this class (`_AudioProcessorParameter`) is owned
+ by the ExternalPlugin object and is not guaranteed to exist at the
+ same memory address every time we might need it. This Python wrapper
+ looks it up dynamically.
+
VSTs and Audio Units don't always consistently give parameter values,
types, or names - all we get is APIs that map float values on [0, 1]
to strings, which may represent floats, strings, integers, enums, etc.
@@ -218,70 +240,138 @@ def supplement_parameter(self: AudioProcessorParameter, search_steps: int = 1000
we could do this in C++, but doing this in Python uses much less code
and is (roughly) as performant as it should only run once per parameter.
"""
- if getattr(self, "__supplemented__", False):
- # Very quick sanity check: has the C++ parameter instance
- # changed identities from under us? This could happen if the C++
- # instance uses the same object in memory but changes its parameters.
- if self.__supplemented_name != self.name:
- raise NotImplementedError(
- "Parameter '{}' has been changed by the plugin instance. (It is now: {}) This may"
- " cause plugin parameter changes to throw undefined exceptions. Pedalboard is"
- " currently unable to accommodate plugins that change their parameters like this."
- .format(self.__supplemented_name, self)
+
+ def __init__(self, plugin, parameter_name, search_steps: int = 1000):
+ self.__plugin = plugin
+ self.__parameter_name = parameter_name
+
+ self.ranges: Dict[Tuple[float, float], Union[str, float, bool]] = {}
+
+ with self.__get_cpp_parameter() as cpp_parameter:
+ start_of_range = 0
+ text_value = None
+ for x in range(0, search_steps + 1):
+ raw_value = x / search_steps
+ x_text_value = cpp_parameter.get_text_for_raw_value(raw_value)
+ if text_value is None:
+ text_value = x_text_value
+ elif x_text_value != text_value:
+ # End current range and start a new one
+ self.ranges[(start_of_range, raw_value)] = text_value
+ text_value = x_text_value
+ start_of_range = raw_value
+ self.ranges[(start_of_range, 1)] = text_value
+
+ self.python_name = to_python_parameter_name(cpp_parameter)
+
+ self.min_value = None
+ self.max_value = None
+ self.step_size = None
+ self.approximate_step_size = None
+ self.valid_values = list(self.ranges.values())
+ self.type = str
+
+ if all(looks_like_float(v) for v in self.ranges.values()):
+ self.type = float
+ self.ranges = {
+ k: float(v.rstrip(FLOAT_SUFFIXES_TO_IGNORE)) for k, v in self.ranges.items()
+ }
+ self.min_value = min(self.ranges.values())
+ self.max_value = max(self.ranges.values())
+
+ sorted_values = sorted(self.ranges.values())
+ first_derivative_steps = set(
+ [round(abs(b - a), 8) for a, b in zip(sorted_values, sorted_values[1:])]
)
- else:
+ if len(first_derivative_steps) == 1:
+ self.step_size = next(iter(first_derivative_steps))
+ elif first_derivative_steps:
+ self.approximate_step_size = sum(first_derivative_steps) / len(
+ first_derivative_steps
+ )
+ elif len(self.valid_values) == 2 and (
+ TRUE_BOOLEANS & {v.lower() for v in self.valid_values}
+ ):
+ self.type = bool
+ self.ranges = {k: v.lower() in TRUE_BOOLEANS for k, v in self.ranges.items()}
+ self.min_value = False
+ self.max_value = True
+ self.step_size = 1
+
+ self.range = self.min_value, self.max_value, self.step_size
+ self._value_to_raw_value_ranges = {value: _range for _range, value in self.ranges.items()}
+
+ @contextmanager
+ def __get_cpp_parameter(self):
+ # Re-fetch the parameter by name every time, as it may have changed.
+ _parameter = self.__plugin._get_parameter(self.__parameter_name)
+ if _parameter and _parameter.name == self.__parameter_name:
+ yield _parameter
return
-
- self.ranges: Dict[Tuple[float, float], Union[str, float, bool]] = {}
-
- start_of_range = 0
- text_value = None
- for x in range(0, search_steps + 1):
- raw_value = x / search_steps
- x_text_value = self.get_text_for_raw_value(raw_value)
- if text_value is None:
- text_value = x_text_value
- elif x_text_value != text_value:
- # End current range and start a new one
- self.ranges[(start_of_range, raw_value)] = text_value
- text_value = x_text_value
- start_of_range = raw_value
- self.ranges[(start_of_range, 1)] = text_value
-
- self.python_name = to_python_parameter_name(self)
-
- self.min_value = None
- self.max_value = None
- self.step_size = None
- self.approximate_step_size = None
- self.valid_values = list(self.ranges.values())
- self.type = str
-
- if all(looks_like_float(v) for v in self.ranges.values()):
- self.type = float
- self.ranges = {k: float(v.rstrip(FLOAT_SUFFIXES_TO_IGNORE)) for k, v in self.ranges.items()}
- self.min_value = min(self.ranges.values())
- self.max_value = max(self.ranges.values())
-
- sorted_values = sorted(self.ranges.values())
- first_derivative_steps = set(
- [round(abs(b - a), 8) for a, b in zip(sorted_values, sorted_values[1:])]
+ raise RuntimeError(
+ "Parameter {} on plugin {} is no longer available. This could indicate that the plugin"
+ " has changed parameters.".format(self.__parameter_name, self.__plugin)
)
- if len(first_derivative_steps) == 1:
- self.step_size = next(iter(first_derivative_steps))
- elif first_derivative_steps:
- self.approximate_step_size = sum(first_derivative_steps) / len(first_derivative_steps)
- elif len(self.valid_values) == 2 and (TRUE_BOOLEANS & {v.lower() for v in self.valid_values}):
- self.type = bool
- self.ranges = {k: v.lower() in TRUE_BOOLEANS for k, v in self.ranges.items()}
- self.min_value = False
- self.max_value = True
- self.step_size = 1
-
- self.range = self.min_value, self.max_value, self.step_size
- self._value_to_raw_value_ranges = {value: _range for _range, value in self.ranges.items()}
-
- def _get_raw_value_for(new_value) -> float:
+
+ def __repr__(self):
+ with self.__get_cpp_parameter() as parameter:
+ cpp_repr_value = repr(parameter)
+ cpp_repr_value = cpp_repr_value.rstrip(">")
+ if self.type is float:
+ if self.step_size:
+ return "{} value={} range=({}, {}, {})>".format(
+ cpp_repr_value,
+ self.string_value,
+ self.min_value,
+ self.max_value,
+ self.step_size,
+ )
+ elif self.approximate_step_size:
+ return "{} value={} range=({}, {}, ~{})>".format(
+ cpp_repr_value,
+ self.string_value,
+ self.min_value,
+ self.max_value,
+ self.approximate_step_size,
+ )
+ elif self.type is str:
+ return '{} value="{}" ({} valid string value{})>'.format(
+ cpp_repr_value,
+ self.string_value,
+ len(self.valid_values),
+ "" if len(self.valid_values) == 1 else "s",
+ )
+ elif self.type is bool:
+ return '{} value={} boolean ("{}" and "{}")>'.format(
+ cpp_repr_value, self.string_value, self.valid_values[0], self.valid_values[1]
+ )
+ else:
+ raise ValueError(
+ f"Parameter {self.python_name} has an unknown type. (Found '{self.type}')"
+ )
+
+ def __getattr__(self, name: str):
+ if not name.startswith("_"):
+ try:
+ with self.__get_cpp_parameter() as parameter:
+ return getattr(parameter, name)
+ except RuntimeError:
+ pass
+ if hasattr(super(), "__getattr__"):
+ return super().__getattr__(name)
+ raise AttributeError("'{}' has no attribute '{}'".format(self.__class__.__name__, name))
+
+ def __setattr__(self, name: str, value):
+ if not name.startswith("_"):
+ try:
+ with self.__get_cpp_parameter() as parameter:
+ if hasattr(parameter, name):
+ return setattr(parameter, name, value)
+ except RuntimeError:
+ pass
+ return super().__setattr__(name, value)
+
+ def get_raw_value_for(self, new_value) -> float:
if self.type is float:
try:
new_value = float(new_value)
@@ -366,71 +456,20 @@ def supplement_parameter(self: AudioProcessorParameter, search_steps: int = 1000
"Parameter has invalid type: {}. This should not be possible!".format(self.type)
)
- self.get_raw_value_for = _get_raw_value_for
- self.__supplemented_name = self.name
- self.__supplemented__ = True
- return self
-
-
-CPP_AUDIO_PROCESSOR_PARAMETER_REPR = AudioProcessorParameter.__repr__
-
-"""
-Monkey patch the C++ __repr__ of AudioProcessorParameter to add our Python functionality.
-"""
-
-
-def python_audio_processor_parameter_repr(self):
- cpp_repr_value = CPP_AUDIO_PROCESSOR_PARAMETER_REPR(self)
- if hasattr(self, '__supplemented__'):
- cpp_repr_value = cpp_repr_value.rstrip(">")
- if self.type is float:
- if self.step_size:
- return "{} value={} range=({}, {}, {})>".format(
- cpp_repr_value,
- self.string_value,
- self.min_value,
- self.max_value,
- self.step_size,
- )
- elif self.approximate_step_size:
- return "{} value={} range=({}, {}, ~{})>".format(
- cpp_repr_value,
- self.string_value,
- self.min_value,
- self.max_value,
- self.approximate_step_size,
- )
- elif self.type is str:
- return "{} value=\"{}\" ({} valid string value{})>".format(
- cpp_repr_value,
- self.string_value,
- len(self.valid_values),
- "" if len(self.valid_values) == 1 else "s",
- )
- elif self.type is bool:
- return "{} value={} boolean (\"{}\" and \"{}\")>".format(
- cpp_repr_value, self.string_value, self.valid_values[0], self.valid_values[1]
- )
- else:
- return cpp_repr_value
-
-AudioProcessorParameter.__repr__ = python_audio_processor_parameter_repr
-
-
-def to_python_parameter_name(parameter: AudioProcessorParameter) -> Optional[str]:
+def to_python_parameter_name(parameter: _AudioProcessorParameter) -> Optional[str]:
if not parameter.name and not parameter.label:
return None
name = parameter.name.lower().strip()
- if parameter.label and not parameter.label.startswith(':'):
+ if parameter.label and not parameter.label.startswith(":"):
name = "{} {}".format(name, parameter.label.lower())
# Replace all non-alphanumeric characters with underscores
name = [c if c.isalpha() or c.isnumeric() else "_" for c in name]
# Remove any double-underscores:
name = [a for a, b in zip(name, name[1:]) if a != b or b != "_"] + [name[-1]]
# Remove any leading or trailing underscores:
- name = ''.join(name).strip('_')
+ name = "".join(name).strip("_")
return name
@@ -438,16 +477,11 @@ class ExternalPlugin(object):
def __set_initial_parameter_values__(
self, parameter_values: Dict[str, Union[str, int, float, bool]] = {}
):
- # Manually clear the "__supplemented__" flag on any parameter
- # objects, as pybind11 may have reused the same memory:
- for parameter in self._parameters:
- parameter.__supplemented__ = False
-
parameters = self.parameters
for key, value in parameter_values.items():
if key not in parameters:
raise AttributeError(
- "Parameter named \"{}\" not found. Valid options: {}".format(
+ 'Parameter named "{}" not found. Valid options: {}'.format(
key, ", ".join(self._parameter_weakrefs.keys())
)
)
@@ -455,13 +489,46 @@ class ExternalPlugin(object):
@property
def parameters(self) -> Dict[str, AudioProcessorParameter]:
+ return self._get_parameters()
+
+ def _get_parameters(self):
+ if not hasattr(self, "__python_parameter_cache__"):
+ self.__python_parameter_cache__ = {}
+ if not hasattr(self, "__python_to_cpp_names__"):
+ self.__python_to_cpp_names__ = {}
+
parameters = {}
- for parameter in self._parameters:
- supplement_parameter(parameter)
+ for cpp_parameter in self._parameters:
+ if cpp_parameter.name not in self.__python_parameter_cache__:
+ self.__python_parameter_cache__[cpp_parameter.name] = AudioProcessorParameter(
+ self, cpp_parameter.name
+ )
+ parameter = self.__python_parameter_cache__[cpp_parameter.name]
if parameter.python_name:
parameters[parameter.python_name] = parameter
+ self.__python_to_cpp_names__[parameter.python_name] = cpp_parameter.name
return parameters
+ def _get_parameter_by_python_name(self, python_name: str) -> AudioProcessorParameter:
+ if not hasattr(self, "__python_parameter_cache__"):
+ self.__python_parameter_cache__ = {}
+ if not hasattr(self, "__python_to_cpp_names__"):
+ self.__python_to_cpp_names__ = {}
+
+ cpp_name = self.__python_to_cpp_names__.get(python_name)
+ if not cpp_name:
+ return self._get_parameters().get(python_name)
+
+ cpp_parameter = self._get_parameter(cpp_name)
+ if not cpp_parameter:
+ return None
+
+ if cpp_parameter.name not in self.__python_parameter_cache__:
+ self.__python_parameter_cache__[cpp_parameter.name] = AudioProcessorParameter(
+ self, cpp_parameter.name
+ )
+ return self.__python_parameter_cache__[cpp_parameter.name]
+
def __dir__(self):
parameter_names = []
for parameter in self._parameters:
@@ -471,30 +538,32 @@ class ExternalPlugin(object):
return super().__dir__() + parameter_names
def __getattr__(self, name: str):
- parameter = self.parameters.get(name)
- if parameter:
- string_value = parameter.string_value
- if parameter.type is float:
- return FloatWithParameter(
- float(string_value.rstrip(FLOAT_SUFFIXES_TO_IGNORE)), wrapped=parameter
- )
- elif parameter.type is bool:
- return BooleanWithParameter(parameter.raw_value >= 0.5, wrapped=parameter)
- elif parameter.type is str:
- return StringWithParameter(str(string_value), wrapped=parameter)
- else:
- raise ValueError(
- f"Parameter {parameter.python_name} has an unknown type. (Found"
- f" '{parameter.type}')"
- )
- raise AttributeError(name)
+ if not name.startswith("_"):
+ parameter = self._get_parameter_by_python_name(name)
+ if parameter:
+ string_value = parameter.string_value
+ if parameter.type is float:
+ return FloatWithParameter(
+ float(string_value.rstrip(FLOAT_SUFFIXES_TO_IGNORE)), wrapped=parameter
+ )
+ elif parameter.type is bool:
+ return BooleanWithParameter(parameter.raw_value >= 0.5, wrapped=parameter)
+ elif parameter.type is str:
+ return StringWithParameter(str(string_value), wrapped=parameter)
+ else:
+ raise ValueError(
+ f"Parameter {parameter.python_name} has an unknown type. (Found"
+ f" '{parameter.type}')"
+ )
+ return getattr(super(), name)
def __setattr__(self, name: str, value):
- parameter = self.parameters.get(name)
- if parameter:
- parameter.raw_value = parameter.get_raw_value_for(value)
- else:
- super().__setattr__(name, value)
+ if not name.startswith("__"):
+ parameter = self._get_parameter_by_python_name(name)
+ if parameter:
+ parameter.raw_value = parameter.get_raw_value_for(value)
+ return
+ super().__setattr__(name, value)
try:
diff --git a/pedalboard/plugins/Chorus.h b/pedalboard/plugins/Chorus.h
index b8d8173..aba1346 100644
--- a/pedalboard/plugins/Chorus.h
+++ b/pedalboard/plugins/Chorus.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
diff --git a/pedalboard/plugins/Compressor.h b/pedalboard/plugins/Compressor.h
index e242762..75618ba 100644
--- a/pedalboard/plugins/Compressor.h
+++ b/pedalboard/plugins/Compressor.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
diff --git a/pedalboard/plugins/Convolution.h b/pedalboard/plugins/Convolution.h
index 196575d..b9994d1 100644
--- a/pedalboard/plugins/Convolution.h
+++ b/pedalboard/plugins/Convolution.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
diff --git a/pedalboard/plugins/Gain.h b/pedalboard/plugins/Gain.h
index 23dd8b0..d2781dd 100644
--- a/pedalboard/plugins/Gain.h
+++ b/pedalboard/plugins/Gain.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
diff --git a/pedalboard/plugins/HighpassFilter.h b/pedalboard/plugins/HighpassFilter.h
index e86d51d..4a2f650 100644
--- a/pedalboard/plugins/HighpassFilter.h
+++ b/pedalboard/plugins/HighpassFilter.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
diff --git a/pedalboard/plugins/LadderFilter.h b/pedalboard/plugins/LadderFilter.h
index 4534b13..fd3c680 100644
--- a/pedalboard/plugins/LadderFilter.h
+++ b/pedalboard/plugins/LadderFilter.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
@@ -81,19 +98,26 @@ inline void init_ladderfilter(py::module &m) {
ss << " mode=";
switch (plugin.getMode()) {
case juce::dsp::LadderFilterMode::LPF12:
- ss << "pedalboard.LadderFilter.LPF12"; break;
+ ss << "pedalboard.LadderFilter.LPF12";
+ break;
case juce::dsp::LadderFilterMode::HPF12:
- ss << "pedalboard.LadderFilter.HPF12"; break;
+ ss << "pedalboard.LadderFilter.HPF12";
+ break;
case juce::dsp::LadderFilterMode::BPF12:
- ss << "pedalboard.LadderFilter.BPF12"; break;
+ ss << "pedalboard.LadderFilter.BPF12";
+ break;
case juce::dsp::LadderFilterMode::LPF24:
- ss << "pedalboard.LadderFilter.LPF24"; break;
+ ss << "pedalboard.LadderFilter.LPF24";
+ break;
case juce::dsp::LadderFilterMode::HPF24:
- ss << "pedalboard.LadderFilter.HPF24"; break;
+ ss << "pedalboard.LadderFilter.HPF24";
+ break;
case juce::dsp::LadderFilterMode::BPF24:
- ss << "pedalboard.LadderFilter.BPF24"; break;
+ ss << "pedalboard.LadderFilter.BPF24";
+ break;
default:
- ss << "unknown"; break;
+ ss << "unknown";
+ break;
}
ss << " cutoff_hz=" << plugin.getCutoffFrequencyHz();
ss << " resonance=" << plugin.getResonance();
diff --git a/pedalboard/plugins/Limiter.h b/pedalboard/plugins/Limiter.h
index 44060cb..703f7a5 100644
--- a/pedalboard/plugins/Limiter.h
+++ b/pedalboard/plugins/Limiter.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
diff --git a/pedalboard/plugins/LowpassFilter.h b/pedalboard/plugins/LowpassFilter.h
index b629c9e..dcf7c58 100644
--- a/pedalboard/plugins/LowpassFilter.h
+++ b/pedalboard/plugins/LowpassFilter.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
diff --git a/pedalboard/plugins/NoiseGate.h b/pedalboard/plugins/NoiseGate.h
index 18e962f..4b0a856 100644
--- a/pedalboard/plugins/NoiseGate.h
+++ b/pedalboard/plugins/NoiseGate.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
diff --git a/pedalboard/plugins/Phaser.h b/pedalboard/plugins/Phaser.h
index 9931830..becd4db 100644
--- a/pedalboard/plugins/Phaser.h
+++ b/pedalboard/plugins/Phaser.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
diff --git a/pedalboard/plugins/Reverb.h b/pedalboard/plugins/Reverb.h
index 0a22867..52588b0 100644
--- a/pedalboard/plugins/Reverb.h
+++ b/pedalboard/plugins/Reverb.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
diff --git a/pedalboard/process.h b/pedalboard/process.h
index fede9fc..c804522 100644
--- a/pedalboard/process.h
+++ b/pedalboard/process.h
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#pragma once
#include "JuceHeader.h"
@@ -141,23 +158,25 @@ process<float>(const py::array_t<float, py::array::c_style> inputArray,
plugin->reset();
}
+ juce::dsp::ProcessSpec spec;
+ spec.sampleRate = sampleRate;
+ spec.maximumBlockSize = static_cast<juce::uint32>(bufferSize);
+ spec.numChannels = static_cast<juce::uint32>(numChannels);
+
for (auto *plugin : plugins) {
if (plugin == nullptr)
continue;
- plugin->prepare(
- {.sampleRate = sampleRate,
- .maximumBlockSize = static_cast<juce::uint32>(bufferSize),
- .numChannels = static_cast<juce::uint32>(numChannels)});
+ plugin->prepare(spec);
}
// Manually construct channel pointers to pass to AudioBuffer.
- float *ioBufferChannelPointers[numChannels];
+ std::vector<float *> ioBufferChannelPointers(numChannels);
for (unsigned int i = 0; i < numChannels; i++) {
ioBufferChannelPointers[i] = ((float *)outputInfo.ptr) + (i * numSamples);
}
- juce::AudioBuffer<float> ioBuffer(ioBufferChannelPointers, numChannels,
- numSamples);
+ juce::AudioBuffer<float> ioBuffer(ioBufferChannelPointers.data(),
+ numChannels, numSamples);
for (unsigned int blockStart = 0; blockStart < numSamples;
blockStart += bufferSize) {
@@ -192,7 +211,7 @@ process<float>(const py::array_t<float, py::array::c_style> inputArray,
}
auto ioBlock = juce::dsp::AudioBlock<float>(
- ioBufferChannelPointers, numChannels, blockStart, blockSize);
+ ioBufferChannelPointers.data(), numChannels, blockStart, blockSize);
juce::dsp::ProcessContextReplacing<float> context(ioBlock);
// Now all of the pointers in context are pointing to valid input data,
diff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cpp
index 038a5e3..bf4aefb 100644
--- a/pedalboard/python_bindings.cpp
+++ b/pedalboard/python_bindings.cpp
@@ -1,3 +1,20 @@
+/*
+ * pedalboard
+ * Copyright 2021 Spotify AB
+ *
+ * Licensed under the GNU Public License, Version 3.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://www.gnu.org/licenses/gpl-3.0.html
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
#include <chrono>
#include <thread>
#include <variant>
diff --git a/setup.py b/setup.py
index d83f305..943037e 100644
--- a/setup.py
+++ b/setup.py
@@ -1,9 +1,25 @@
+#! /usr/bin/env python
+#
+# Copyright 2021 Spotify AB
+#
+# Licensed under the GNU Public License, Version 3.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.gnu.org/licenses/gpl-3.0.html
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
import os
import platform
from subprocess import check_output
from pybind11.setup_helpers import Pybind11Extension
from pathlib import Path
-from distutils import sysconfig
from distutils.core import setup
from distutils.unixccompiler import UnixCCompiler
@@ -71,6 +87,8 @@ if DEBUG:
if bool(int(os.environ.get('USE_ASAN', 0))):
JUCE_CPPFLAGS += ['-fsanitize=address', '-fno-omit-frame-pointer']
LINK_ARGS += ['-fsanitize=address']
+ if platform.system() == "Linux":
+ LINK_ARGS += ['-shared-libasan']
elif bool(int(os.environ.get('USE_TSAN', 0))):
JUCE_CPPFLAGS += ['-fsanitize=thread']
LINK_ARGS += ['-fsanitize=thread']
@@ -78,13 +96,14 @@ if DEBUG:
JUCE_CPPFLAGS += ['-fsanitize=memory', '-fsanitize-memory-track-origins']
LINK_ARGS += ['-fsanitize=memory']
else:
- JUCE_CPPFLAGS += ['-O3']
+ JUCE_CPPFLAGS += ['/Ox' if platform.system() == "Windows" else '-O3']
# Regardless of platform, allow our compiler to compile .mm files as Objective-C (required on MacOS)
UnixCCompiler.src_extensions.append(".mm")
UnixCCompiler.language_map[".mm"] = "objc++"
+LIBS = []
if platform.system() == "Darwin":
MACOS_FRAMEWORKS = [
'Accelerate',
@@ -125,7 +144,7 @@ if platform.system() == "Darwin":
if matching_cpp_source:
sources[sources.index(matching_cpp_source)] = objc_source
PEDALBOARD_SOURCES = [str(p.resolve()) for p in sources]
-else:
+elif platform.system() == "Linux":
for package in ['freetype2']:
flags = (
check_output(['pkg-config', '--cflags-only-I', package])
@@ -138,6 +157,30 @@ else:
LINK_ARGS += ['-lfreetype']
PEDALBOARD_SOURCES = [str(p.resolve()) for p in (list(Path("pedalboard").glob("**/*.cpp")))]
+elif platform.system() == "Windows":
+ JUCE_CPPFLAGS += ['-DJUCE_DLL_BUILD=1']
+ # https://forum.juce.com/t/statically-linked-exe-in-win-10-not-working/25574/3
+ LIBS.extend(
+ [
+ "kernel32",
+ "user32",
+ "gdi32",
+ "winspool",
+ "comdlg32",
+ "advapi32",
+ "shell32",
+ "ole32",
+ "oleaut32",
+ "uuid",
+ "odbc32",
+ "odbccp32",
+ ]
+ )
+ PEDALBOARD_SOURCES = [str(p.resolve()) for p in (list(Path("pedalboard").glob("**/*.cpp")))]
+else:
+ raise NotImplementedError(
+ "Not sure how to build JUCE on platform: {}!".format(platform.system())
+ )
pedalboard_cpp = Pybind11Extension(
'pedalboard_native',
@@ -145,6 +188,7 @@ pedalboard_cpp = Pybind11Extension(
include_dirs=JUCE_INCLUDES,
extra_compile_args=JUCE_CPPFLAGS + JUCE_CPPFLAGS_CONSOLEAPP,
extra_link_args=LINK_ARGS,
+ libraries=LIBS,
language="c++",
cxx_std=17,
)
@@ -154,28 +198,26 @@ if DEBUG:
# Why does Pybind11 always remove debugging symbols?
pedalboard_cpp.extra_compile_args.remove('-g0')
-
-if platform.system() == "Darwin":
- # On some macOS installations, CFLAGS includes a macOS SDK
- # that inserts the wrong <math> header into the search path
- # for C++ code. This is a somewhat hacky fix for those who
- # try to build this package on machines configured this way.
- # See:
- # - https://guihao-liang.github.io/2020/03/26/compiler-search-oder
- # - https://stackoverflow.com/q/58628377/679081
- cflags = sysconfig.get_config_vars()['CFLAGS'].split()
- for arg in list(cflags):
- if 'MacOS' in arg and '.sdk' in arg:
- cflags.remove(arg)
- sysconfig.get_config_vars()['CFLAGS'] = " ".join(cflags)
-
-
setup(
name='pedalboard',
- version='0.3.2',
+ version='0.3.3',
author='Peter Sobot',
author_email='[email protected]',
description='A Python library for adding effects to audio.',
+ classifiers=[
+ "Development Status :: 4 - Beta",
+ "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
+ "Operating System :: MacOS",
+ "Operating System :: Microsoft :: Windows",
+ "Operating System :: POSIX :: Linux",
+ "Programming Language :: C++",
+ "Programming Language :: Python",
+ "Topic :: Multimedia :: Sound/Audio",
+ "Programming Language :: Python :: 3.6",
+ "Programming Language :: Python :: 3.7",
+ "Programming Language :: Python :: 3.8",
+ "Programming Language :: Python :: 3.9",
+ ],
ext_modules=[pedalboard_cpp],
install_requires=['numpy'],
packages=['pedalboard'],
diff --git a/test-requirements.txt b/test-requirements.txt
index 468465d..fdefc1c 100644
--- a/test-requirements.txt
+++ b/test-requirements.txt
@@ -2,7 +2,13 @@ coverage==5.0.2
pytest==5.3.2
pytest-cov==2.8.1
pytest-mock==3.3.1
+pybind11>=2.6.0
+setuptools>=42
+wheel
+flake8
+black
+interrogate
+
librosa
sox
-soxbindings
tensorflow
\ No newline at end of file
diff --git a/tests/plugins/Linux/CHOWTapeModel.vst3/Contents/x86_64-linux/CHOWTapeModel.so b/tests/plugins/Linux/CHOWTapeModel.vst3/Contents/x86_64-linux/CHOWTapeModel.so
new file mode 100755
index 0000000..7b2ebbc
Binary files /dev/null and b/tests/plugins/Linux/CHOWTapeModel.vst3/Contents/x86_64-linux/CHOWTapeModel.so differ
diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py
index f03f48b..db4629b 100644
--- a/tests/test_benchmark.py
+++ b/tests/test_benchmark.py
@@ -1,3 +1,20 @@
+#! /usr/bin/env python
+#
+# Copyright 2021 Spotify AB
+#
+# Licensed under the GNU Public License, Version 3.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.gnu.org/licenses/gpl-3.0.html
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
import time
import pytest
diff --git a/tests/test_external_plugins.py b/tests/test_external_plugins.py
index 7c09559..b2291fa 100644
--- a/tests/test_external_plugins.py
+++ b/tests/test_external_plugins.py
@@ -1,3 +1,20 @@
+#! /usr/bin/env python
+#
+# Copyright 2021 Spotify AB
+#
+# Licensed under the GNU Public License, Version 3.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.gnu.org/licenses/gpl-3.0.html
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
import os
import math
import platform
@@ -9,13 +26,20 @@ import pedalboard
import numpy as np
-TEST_PLUGIN_BASE_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'plugins')
+TEST_PLUGIN_BASE_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), "plugins")
AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT = [
os.path.basename(filename)
- for filename in glob(os.path.join(TEST_PLUGIN_BASE_PATH, platform.system(), '*'))
+ for filename in glob(os.path.join(TEST_PLUGIN_BASE_PATH, platform.system(), "*"))
]
+# Disable Audio Unit tests on GitHub Actions, as the
+# action container fails to load Audio Units:
+if os.getenv("CIBW_TEST_REQUIRES") or os.getenv("CI"):
+ AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT = [
+ f for f in AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT if "component" not in f
+ ]
+
def get_parameters(plugin_filename: str):
try:
@@ -38,11 +62,9 @@ def load_test_plugin(plugin_filename: str, *args, **kwargs):
key = repr((plugin_filename, args, tuple(kwargs.items())))
if key not in TEST_PLUGIN_CACHE:
- os.environ['LD_DEBUG'] = 'libs'
TEST_PLUGIN_CACHE[key] = pedalboard.load_plugin(
os.path.join(TEST_PLUGIN_BASE_PATH, platform.system(), plugin_filename), *args, **kwargs
)
- os.environ['LD_DEBUG'] = ''
return TEST_PLUGIN_CACHE[key]
@@ -50,7 +72,7 @@ def test_at_least_one_plugin_is_available_for_testing():
assert AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT
[email protected]('plugin_filename', AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
[email protected]("plugin_filename", AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
def test_at_least_one_parameter(plugin_filename: str):
"""
Many tests below are parametrized on the parameters of the plugin;
@@ -61,7 +83,7 @@ def test_at_least_one_parameter(plugin_filename: str):
assert get_parameters(plugin_filename)
[email protected]('plugin_filename', AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
[email protected]("plugin_filename", AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
def test_initial_parameters(plugin_filename: str):
parameters = {
k: v.min_value for k, v in get_parameters(plugin_filename).items() if v.type == float
@@ -75,7 +97,7 @@ def test_initial_parameters(plugin_filename: str):
@pytest.mark.parametrize(
- 'plugin_filename,parameter_name',
+ "plugin_filename,parameter_name",
[
(path, parameter)
for path in AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT
@@ -90,7 +112,7 @@ def test_initial_parameter_validation(plugin_filename: str, parameter_name: str)
)
[email protected]('plugin_filename', AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
[email protected]("plugin_filename", AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
def test_initial_parameter_validation_missing(plugin_filename: str):
with pytest.raises(AttributeError):
load_test_plugin(plugin_filename, {"missing_parameter": 123})
@@ -102,7 +124,7 @@ def test_import_error_on_missing_path(loader):
loader("./")
[email protected]('plugin_filename', AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
[email protected]("plugin_filename", AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
@pytest.mark.parametrize(
"num_channels,sample_rate",
[(1, 48000), (2, 48000), (1, 44100), (2, 44100), (1, 22050), (2, 22050)],
@@ -116,7 +138,7 @@ def test_plugin_accepts_variable_channel_count(
assert effected.shape == noise.shape
[email protected]('plugin_filename', AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
[email protected]("plugin_filename", AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
def test_all_parameters_are_accessible_as_properties(plugin_filename: str):
plugin = load_test_plugin(plugin_filename)
assert plugin.parameters
@@ -124,21 +146,21 @@ def test_all_parameters_are_accessible_as_properties(plugin_filename: str):
assert hasattr(plugin, parameter_name)
[email protected]('plugin_filename', AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
[email protected]("plugin_filename", AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
def test_all_parameters_have_accessors(plugin_filename: str):
plugin = load_test_plugin(plugin_filename)
assert plugin.parameters
for parameter_name, parameter in plugin.parameters.items():
assert parameter_name in dir(plugin)
parameter_value = getattr(plugin, parameter_name)
- assert hasattr(parameter_value, 'raw_value')
+ assert hasattr(parameter_value, "raw_value")
assert repr(parameter)
assert isinstance(parameter_value, (float, WrappedBool, str))
assert parameter_value.raw_value == parameter.raw_value
assert parameter_value.range is not None
[email protected]('plugin_filename', AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
[email protected]("plugin_filename", AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
def test_attributes_proxy(plugin_filename: str):
plugin = load_test_plugin(plugin_filename)
@@ -151,7 +173,7 @@ def test_attributes_proxy(plugin_filename: str):
@pytest.mark.parametrize(
- 'plugin_filename,parameter_name',
+ "plugin_filename,parameter_name",
[
(path, parameter)
for path in AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT
@@ -170,13 +192,13 @@ def test_bool_parameters(plugin_filename: str, parameter_name: str):
# Ensure that if we access an attribute that we're not adding to the value,
# we fall back to the underlying type (bool) or we raise an exception if not:
- assert hasattr(parameter_value, 'bit_length')
+ assert hasattr(parameter_value, "bit_length")
with pytest.raises(AttributeError):
parameter_value.something_that_doesnt_exist
@pytest.mark.parametrize(
- 'plugin_filename,parameter_name',
+ "plugin_filename,parameter_name",
[
(path, parameter)
for path in AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT
@@ -190,7 +212,7 @@ def test_bool_parameter_valdation(plugin_filename: str, parameter_name: str):
@pytest.mark.parametrize(
- 'plugin_filename,parameter_name',
+ "plugin_filename,parameter_name",
[
(path, parameter)
for path in AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT
@@ -217,7 +239,7 @@ def test_float_parameters(plugin_filename: str, parameter_name: str):
@pytest.mark.parametrize(
- 'plugin_filename,parameter_name',
+ "plugin_filename,parameter_name",
[
(path, parameter)
for path in AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT
@@ -242,7 +264,7 @@ def test_float_parameter_valdation(plugin_filename: str, parameter_name: str):
@pytest.mark.parametrize(
- 'plugin_filename,parameter_name',
+ "plugin_filename,parameter_name",
[
(path, parameter)
for path in AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT
@@ -267,7 +289,7 @@ def test_str_parameters(plugin_filename: str, parameter_name: str):
@pytest.mark.parametrize(
- 'plugin_filename,parameter_name',
+ "plugin_filename,parameter_name",
[
(path, parameter)
for path in AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT
@@ -285,7 +307,7 @@ def test_string_parameter_valdation(plugin_filename: str, parameter_name: str):
setattr(plugin, parameter_name, "some value not present")
[email protected]('plugin_filename', AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
[email protected]("plugin_filename", AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
def test_plugin_state_cleared_between_invocations(plugin_filename: str):
plugin = load_test_plugin(plugin_filename)
sr = 44100
diff --git a/tests/test_filters.py b/tests/test_filters.py
index fe95504..55627e4 100644
--- a/tests/test_filters.py
+++ b/tests/test_filters.py
@@ -1,3 +1,20 @@
+#! /usr/bin/env python
+#
+# Copyright 2021 Spotify AB
+#
+# Licensed under the GNU Public License, Version 3.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.gnu.org/licenses/gpl-3.0.html
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
import pytest
import numpy as np
from pedalboard import HighpassFilter, LowpassFilter
@@ -23,9 +40,9 @@ def octaves_between(a_hz: float, b_hz: float) -> float:
return np.log2(a_hz / b_hz)
[email protected]('filter_type', [HighpassFilter, LowpassFilter])
[email protected]('fundamental_hz', [440, 880])
[email protected]('sample_rate', [22050, 44100, 48000])
[email protected]("filter_type", [HighpassFilter, LowpassFilter])
[email protected]("fundamental_hz", [440, 880])
[email protected]("sample_rate", [22050, 44100, 48000])
def test_filter_attenutation(filter_type, fundamental_hz, sample_rate):
num_seconds = 10.0
samples = np.arange(num_seconds * sample_rate)
@@ -36,9 +53,9 @@ def test_filter_attenutation(filter_type, fundamental_hz, sample_rate):
assert np.allclose(rms(filtered) / rms(sine_wave), db_to_gain(-3), rtol=0.01, atol=0.01)
[email protected]('cutoff_frequency_hz', [440, 880])
[email protected]('fundamental_hz', [880, 1760])
[email protected]('sample_rate', [22050, 44100, 48000])
[email protected]("cutoff_frequency_hz", [440, 880])
[email protected]("fundamental_hz", [880, 1760])
[email protected]("sample_rate", [22050, 44100, 48000])
def test_lowpass_slope(cutoff_frequency_hz, fundamental_hz, sample_rate):
num_seconds = 1.0
samples = np.arange(num_seconds * sample_rate)
@@ -47,7 +64,8 @@ def test_lowpass_slope(cutoff_frequency_hz, fundamental_hz, sample_rate):
filtered = LowpassFilter(cutoff_frequency_hz=cutoff_frequency_hz)(sine_wave, sample_rate)
num_octaves = octaves_between(fundamental_hz, cutoff_frequency_hz)
- # The volume of the fundamental frequency should be (-3dB * number of octaves) of the input volume
+ # The volume of the fundamental frequency should
+ # be (-3dB * number of octaves) of the input volume
assert np.allclose(
rms(filtered) / rms(sine_wave), db_to_gain((num_octaves + 1) * -3), rtol=0.1, atol=0.1
)
diff --git a/tests/test_locking.py b/tests/test_locking.py
index ea90099..c0947b9 100644
--- a/tests/test_locking.py
+++ b/tests/test_locking.py
@@ -1,3 +1,20 @@
+#! /usr/bin/env python
+#
+# Copyright 2021 Spotify AB
+#
+# Licensed under the GNU Public License, Version 3.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.gnu.org/licenses/gpl-3.0.html
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
import random
import pytest
from concurrent.futures import ThreadPoolExecutor
@@ -7,7 +24,7 @@ import numpy as np
import pedalboard
[email protected]('num_concurrent_chains', [10, 24, 50])
[email protected]("num_concurrent_chains", [10, 24, 50])
def test_multiple_threads_using_same_plugin_instances(num_concurrent_chains: int):
"""
Instantiate a large number of stateful plugins, then run audio through them
diff --git a/tests/test_memory_leaks.py b/tests/test_memory_leaks.py
index 48cbd42..184a2a0 100644
--- a/tests/test_memory_leaks.py
+++ b/tests/test_memory_leaks.py
@@ -1,3 +1,20 @@
+#! /usr/bin/env python
+#
+# Copyright 2021 Spotify AB
+#
+# Licensed under the GNU Public License, Version 3.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.gnu.org/licenses/gpl-3.0.html
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
import os
import gc
import weakref
@@ -8,7 +25,7 @@ import pedalboard
from .test_external_plugins import TEST_PLUGIN_BASE_PATH, AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT
[email protected]('plugin_path', AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
[email protected]("plugin_path", AVAILABLE_PLUGINS_IN_TEST_ENVIRONMENT)
def test_plugin_can_be_garbage_collected(plugin_path: str):
# Load a VST3 plugin from disk:
plugin = pedalboard.load_plugin(
@@ -27,7 +44,10 @@ def test_plugin_can_be_garbage_collected(plugin_path: str):
# However, we still have a parameter referring to this, so it won't be removed yet:
del plugin
gc.collect()
- assert _plugin_ref()
+ assert _plugin_ref(), (
+ f"Expected plugin to not have been garbage collected, as a parameter ({param_name},"
+ f" {param}) still exists."
+ )
assert set(dir(initial_value)).issubset(set(dir(value)))
assert value == initial_value # value should not change
diff --git a/tests/test_native_module.py b/tests/test_native_module.py
index b7e920e..4ecd232 100644
--- a/tests/test_native_module.py
+++ b/tests/test_native_module.py
@@ -1,9 +1,30 @@
+#! /usr/bin/env python
+#
+# Copyright 2021 Spotify AB
+#
+# Licensed under the GNU Public License, Version 3.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.gnu.org/licenses/gpl-3.0.html
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import os
import pytest
import numpy as np
from pedalboard import process, Gain, Compressor, Convolution
[email protected]('shape', [(44100,), (44100, 1), (44100, 2), (1, 4), (2, 4)])
+IMPULSE_RESPONSE_PATH = os.path.join(os.path.dirname(__file__), "impulse_response.wav")
+
+
[email protected]("shape", [(44100,), (44100, 1), (44100, 2), (1, 4), (2, 4)])
def test_no_transforms(shape, sr=44100):
_input = np.random.rand(*shape).astype(np.float32)
@@ -13,7 +34,7 @@ def test_no_transforms(shape, sr=44100):
assert np.allclose(_input, output, rtol=0.0001)
[email protected]('shape', [(44100,), (44100, 1), (44100, 2), (1, 4), (2, 4)])
[email protected]("shape", [(44100,), (44100, 1), (44100, 2), (1, 4), (2, 4)])
def test_noise_gain(shape, sr=44100):
full_scale_noise = np.random.rand(*shape).astype(np.float32)
@@ -35,17 +56,24 @@ def test_throw_on_invalid_compressor_ratio(sr=44100):
Compressor(ratio=0.1)
+def test_convolution_file_exists():
+ """
+ A meta-test - if this fails, we can't find the file, so the following two tests will fail!
+ """
+ assert os.path.isfile(IMPULSE_RESPONSE_PATH)
+
+
def test_convolution_works(sr=44100, duration=10):
full_scale_noise = np.random.rand(sr * duration).astype(np.float32)
- result = process(full_scale_noise, sr, [Convolution('./tests/impulse_response.wav', 0.5)])
+ result = process(full_scale_noise, sr, [Convolution(IMPULSE_RESPONSE_PATH, 0.5)])
assert not np.allclose(full_scale_noise, result, rtol=0.1)
def test_throw_on_inaccessible_convolution_file():
# Should work:
- Convolution('./tests/impulse_response.wav')
+ Convolution(IMPULSE_RESPONSE_PATH)
# Should fail:
with pytest.raises(RuntimeError):
- Convolution('./tests/missing_impulse_response.wav')
+ Convolution("missing_impulse_response.wav")
diff --git a/tests/test_python_interface.py b/tests/test_python_interface.py
index 264f067..f4fe267 100644
--- a/tests/test_python_interface.py
+++ b/tests/test_python_interface.py
@@ -1,9 +1,26 @@
+#! /usr/bin/env python
+#
+# Copyright 2021 Spotify AB
+#
+# Licensed under the GNU Public License, Version 3.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.gnu.org/licenses/gpl-3.0.html
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
import pytest
import numpy as np
-from pedalboard import Pedalboard, Gain, Compressor, Convolution
+from pedalboard import Pedalboard, Gain
[email protected]('shape', [(44100,), (44100, 1), (44100, 2), (1, 4), (2, 4)])
[email protected]("shape", [(44100,), (44100, 1), (44100, 2), (1, 4), (2, 4)])
def test_no_transforms(shape, sr=44100):
_input = np.random.rand(*shape).astype(np.float32)
@@ -15,19 +32,19 @@ def test_no_transforms(shape, sr=44100):
def test_fail_on_invalid_plugin():
with pytest.raises(TypeError):
- Pedalboard(['I want a reverb please'], 44100)
+ Pedalboard(["I want a reverb please"], 44100)
def test_fail_on_invalid_sample_rate():
with pytest.raises(TypeError):
- Pedalboard([], 'fourty four one hundred')
+ Pedalboard([], "fourty four one hundred")
with pytest.raises(TypeError):
- Pedalboard([]).process([], 'fourty four one hundred')
+ Pedalboard([]).process([], "fourty four one hundred")
def test_fail_on_invalid_buffer_size():
with pytest.raises(TypeError):
- Pedalboard([]).process([], 44100, 'very big buffer please')
+ Pedalboard([]).process([], 44100, "very big buffer please")
def test_repr():
@@ -88,57 +105,3 @@ def test_process_validates_sample_rate():
pb = Pedalboard([Gain(-6)])
with pytest.raises(ValueError):
pb.process(full_scale_noise)
-
-
- 'shape,buffer_size',
- sum(
- [
- [
- ((44100,), buffer_size),
- ((44100, 1), buffer_size),
- ((44100, 2), buffer_size),
- ((1, 4), buffer_size),
- ((2, 4), buffer_size),
- ]
- for buffer_size in (None, 128, 4096, 2 ** 16)
- ],
- [],
- ),
-)
-def test_noise_gain(shape, buffer_size, sr=44100):
- full_scale_noise = np.random.rand(*shape).astype(np.float32)
-
- # Use the Gain transform to scale down the noise by 6dB (0.5x)
- half_noise = Pedalboard([Gain(-6)], sr).process(full_scale_noise, buffer_size=buffer_size)
- assert full_scale_noise.shape == half_noise.shape
- assert np.allclose(full_scale_noise / 2.0, half_noise, rtol=0.01)
-
-
-def test_throw_on_invalid_compressor_ratio(sr=44100):
- full_scale_noise = np.random.rand(sr, 1).astype(np.float32)
-
- # Should work:
- Pedalboard([Compressor(ratio=1.1)], sr).process(full_scale_noise)
-
- # Should fail:
- with pytest.raises(ValueError):
- Compressor(ratio=0.1)
-
-
-def test_convolution_works(sr=44100, duration=10):
- full_scale_noise = np.random.rand(sr * duration).astype(np.float32)
-
- result = Pedalboard([Convolution('./tests/impulse_response.wav', 0.5)], sr).process(
- full_scale_noise
- )
- assert not np.allclose(full_scale_noise, result, rtol=0.1)
-
-
-def test_throw_on_inaccessible_convolution_file():
- # Should work:
- Convolution('./tests/impulse_response.wav')
-
- # Should fail:
- with pytest.raises(RuntimeError):
- Convolution('./tests/missing_impulse_response.wav')
diff --git a/tests/test_tensorflow.py b/tests/test_tensorflow.py
index bdb728f..06271e8 100644
--- a/tests/test_tensorflow.py
+++ b/tests/test_tensorflow.py
@@ -1,3 +1,20 @@
+#! /usr/bin/env python
+#
+# Copyright 2021 Spotify AB
+#
+# Licensed under the GNU Public License, Version 3.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.gnu.org/licenses/gpl-3.0.html
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
import numpy as np
import tensorflow as tf
@@ -18,7 +35,7 @@ def test_can_be_called_in_tensorflow_data_pipeline():
[tf.keras.layers.InputLayer(input_shape=(sr,)), tf.keras.layers.Dense(1)]
)
# Train a dummy model just to ensure nothing explodes:
- model.compile(loss='mse')
+ model.compile(loss="mse")
model.fit(ds.map(lambda effected: (effected, 1)).batch(1), epochs=10)
assert np.allclose(plugins.process(noise), np.array([tensor.numpy() for tensor in ds]))
diff --git a/tox.ini b/tox.ini
index e4b84f3..6b21d13 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,14 +1,12 @@
[tox]
-envlist = py38,docs,check-formatting,lint
+envlist = py,docs,check-formatting,lint
skipsdist = True
usedevelop = True
-indexserver =
- spotify = https://artifactory.spotify.net/artifactory/api/pypi/pypi/simple
[testenv]
-basepython = python3.8
+basepython = python3
deps =
- :spotify:-r{toxinidir}/dev-requirements.txt
+ -r{toxinidir}/dev-requirements.txt
commands =
coverage run -m pytest {posargs}
@@ -22,7 +20,7 @@ commands =
; This env just runs `black` and fails tox if it's not formatted correctly.
; If this env fails on Tingle, run `tox -e format` locally in order to apply changes.
[testenv:check-formatting]
-basepython = python3.8
+basepython = python3
deps = black
skip_install = true
commands =
@@ -30,7 +28,7 @@ commands =
# clang-format -style=LLVM pedalboard.cpp
[testenv:format]
-basepython = python3.8
+basepython = python3
deps = black
skip_install = true
commands =
@@ -40,7 +38,7 @@ commands =
[testenv:lint]
; feel free to add flake8 plugins (i.e. flake8-import-order), add isort,
; or use another linter of your choice
-basepython = python3.8
+basepython = python3
deps = flake8
skip_install = true
commands = flake8