🎛 🔊 A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
Add MP3 compressor plugin.
Peter Sobot373109f6e96a
diff --git a/.gitmodules b/.gitmodulesindex 05f65fc..eff2e53 100644--- a/.gitmodules+++ b/.gitmodules@@ -4,3 +4,6 @@[submodule "pedalboard/vendors/rubberband"]path = vendors/rubberbandurl = https://github.com/BreakfastQuay/Rubberband.git+[submodule "vendors/lame"]+ path = vendors/lame+ url = https://github.com/lameproject/lame.gitdiff --git a/README.md b/README.mdindex 5ee4fa8..d3fee27 100644--- a/README.md+++ b/README.md@@ -234,11 +234,13 @@ Not yet! The underlying framework (JUCE) supports VST and AU instruments just fiNot yet, either - although the underlying framework (JUCE) supports passing MIDI to plugins, so this would also be possible to add.## License-`pedalboard` is Copyright 2021 Spotify AB.+`pedalboard` is Copyright 2021-2022 Spotify AB.-`pedalboard` is licensed under the [GNU General Public License v3](https://www.gnu.org/licenses/gpl-3.0.en.html), because:- - The core audio processing code is pulled from JUCE 6, which is [dual-licensed under a commercial license and the GPLv3](https://juce.com/juce-6-licence).- - The VST3 SDK, bundled with JUCE, is owned by [Steinberg® Media Technologies GmbH](https://www.steinberg.net/en/home.html) and licensed under the GPLv3.+`pedalboard` is licensed under the [GNU General Public License v3](https://www.gnu.org/licenses/gpl-3.0.en.html). `pedalboard` includes a number of libraries that are statically compiled, and which carry the following licenses:++ - The core audio processing code is pulled from [JUCE 6](https://juce.com/), which is [dual-licensed under a commercial license and the GPLv3](https://juce.com/juce-6-licence).+ - The [VST3 SDK](https://github.com/steinbergmedia/vst3sdk), bundled with JUCE, is owned by [Steinberg® Media Technologies GmbH](https://www.steinberg.net/en/home.html) and licensed under the GPLv3.- The `PitchShift` plugin uses [the Rubber Band Library](https://github.com/breakfastquay/rubberband), which is [dual-licensed under a commercial license](https://breakfastquay.com/technology/license.html) and the GPLv2 (or newer).+ - The `MP3Compressor` plugin uses [`libmp3lame` from the LAME project](https://lame.sourceforge.io/), which is [licensed under the LGPLv2](https://github.com/lameproject/lame/blob/master/README) and [upgraded to the GPLv3 for inclusion in this project (as permitted by the LGPLv2)](https://www.gnu.org/licenses/gpl-faq.html#AllCompatibility)._VST is a registered trademark of Steinberg Media Technologies GmbH._diff --git a/pedalboard/plugins/MP3Compressor.h b/pedalboard/plugins/MP3Compressor.hnew file mode 100644index 0000000..777b0c9--- /dev/null+++ b/pedalboard/plugins/MP3Compressor.h@@ -0,0 +1,303 @@+/*+ * pedalboard+ * Copyright 2022 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 "../Plugin.h"+#include <lame.h>++namespace Pedalboard {++/*+ * A small C++ wrapper around the C-based LAME MP3 encoding functions.+ * Used mostly to avoid leaking memory.+ */+class EncoderWrapper {+public:+ EncoderWrapper() { lame = lame_init(); }+ ~EncoderWrapper() { reset(); }++ operator bool() const { return lame != nullptr; }++ void reset() {+ lame_close(lame);+ lame = nullptr;+ }++ lame_t getContext() {+ if (!lame)+ lame = lame_init();+ return lame;+ }++private:+ lame_t lame;+};++/*+ * A small C++ wrapper around the C-based LAME MP3 decoding functions.+ * Used mostly to avoid leaking memory.+ */+class DecoderWrapper {+public:+ DecoderWrapper() { hip = hip_decode_init(); }+ ~DecoderWrapper() { reset(); }+ operator bool() const { return hip != nullptr; }++ void reset() {+ hip_decode_exit(hip);+ hip = nullptr;+ }++ hip_t getContext() {+ if (!hip)+ hip = hip_decode_init();+ return hip;+ }++private:+ hip_t hip;+};++void lame_throw_error_handler(const char *format, va_list ap) {+ int errorLength = 512;+ char errorBuffer[errorLength + 1];+ snprintf(errorBuffer, errorLength, format, ap);+ throw std::runtime_error("MP3 encoder threw an error: " ++ std::string(errorBuffer));+}++class MP3Compressor : public Plugin {+public:+ virtual ~MP3Compressor(){};++ void setVBRQuality(float newLevel) {+ if (newLevel < 0 || newLevel > 10) {+ throw std::runtime_error("VBR quality must be greater than 0 and less "+ "than 10. (Higher numbers are lower quality.)");+ }++ vbrLevel = newLevel;+ encoder.reset();+ }++ float getVBRQuality() const { return vbrLevel; }++ virtual void prepare(const juce::dsp::ProcessSpec &spec) override {+ bool specChanged = lastSpec.sampleRate != spec.sampleRate ||+ lastSpec.maximumBlockSize < spec.maximumBlockSize ||+ lastSpec.numChannels != spec.numChannels;+ if (!lame || specChanged) {+ reset();++ lame_set_errorf(encoder.getContext(), lame_throw_error_handler);++ if (lame_set_in_samplerate(encoder.getContext(), spec.sampleRate) != 0) {+ throw std::runtime_error(+ "MP3 encoder failed to set input sample rate.");+ }++ if (lame_set_out_samplerate(encoder.getContext(), spec.sampleRate) != 0) {+ throw std::runtime_error(+ "MP3 encoder failed to set output sample rate.");+ }++ if (lame_set_num_channels(encoder.getContext(), spec.numChannels) != 0) {+ throw std::runtime_error(+ "MP3 encoder failed to set number of channels.");+ }++ // TODO: handle when the output sample rate doesn't match one of the+ // expected rates from encoder.++ if (lame_set_VBR(encoder.getContext(), vbr_default) != 0) {+ throw std::runtime_error(+ "MP3 encoder failed to set variable bit rate flag.");+ }++ if (lame_set_VBR_quality(encoder.getContext(), vbrLevel) != 0) {+ throw std::runtime_error(+ "MP3 encoder failed to set variable bit rate quality to " ++ std::to_string(vbrLevel) + "!");+ }++ int ret = lame_init_params(encoder.getContext());+ if (ret != 0) {+ throw std::runtime_error(+ "MP3 encoder failed to initialize MP3 encoder! (error " ++ std::to_string(ret) + ")");+ }++ // Why + 528 + 1? Pulled directly from the libmp3lame code; not 100% sure.+ // Values have been confirmed empirically, however.+ encoderInStreamLatency =+ lame_get_encoder_delay(encoder.getContext()) + 528 + 1;++ int outputBufferSize = (16384 + spec.maximumBlockSize) * sizeof(short);+ for (int i = 0; i < 2; i++) {+ outputBuffers[i].setSize(outputBufferSize);+ outputBuffers[i].fillWith(0);+ }++ outputBufferLastSample = 0;++ lastSpec = spec;+ }+ }++ int process(+ const juce::dsp::ProcessContextReplacing<float> &context) override final {++ auto ioBlock = context.getOutputBlock();+ for (int i = 0; i < ioBlock.getNumSamples();+ i += MAX_MP3_FRAME_SIZE_SAMPLES) {+ jassert(ioBlock.getNumChannels() == 2);++ unsigned char mp3Buffer[MAX_MP3_FRAME_SIZE_BYTES];++ int frameSize =+ std::min(MAX_MP3_FRAME_SIZE_SAMPLES, ioBlock.getNumSamples() - i);++ int numBytesEncoded = lame_encode_buffer_ieee_float(+ encoder.getContext(), ioBlock.getChannelPointer(0) + i,+ ioBlock.getChannelPointer(1) + i, frameSize, mp3Buffer,+ MAX_MP3_FRAME_SIZE_BYTES);++ if (numBytesEncoded < 0) {+ throw std::runtime_error("MP3 encoder failed to encode with error " ++ std::to_string(numBytesEncoded) + ".");+ }++ samplesInEncodingBuffer += frameSize;++ // Decode frames from the buffer as soon as we get them:+ if (numBytesEncoded > 0) {+ int samplesDecoded = hip_decode(+ decoder.getContext(), mp3Buffer, numBytesEncoded,+ (short *)outputBuffers[0].getData() + outputBufferLastSample,+ (short *)outputBuffers[1].getData() + outputBufferLastSample);+ outputBufferLastSample += samplesDecoded;+ samplesInEncodingBuffer -= samplesDecoded;+ if (encodingLatency == 0) {+ encodingLatency = samplesInEncodingBuffer;+ }+ }+ }++ int samplesToOutput = std::min(ioBlock.getNumSamples(),+ (unsigned long)outputBufferLastSample);+ samplesProduced += samplesToOutput;+ int offsetInOutputBuffer = 0;+ if (samplesToOutput < ioBlock.getNumSamples()) {+ offsetInOutputBuffer = ioBlock.getNumSamples() - samplesToOutput;+ }++ for (int c = 0; c < ioBlock.getNumChannels(); c++) {+ juce::AudioDataConverters::convertInt16LEToFloat(+ (short *)outputBuffers[c].getData(),+ ioBlock.getChannelPointer(c) + offsetInOutputBuffer, samplesToOutput);+ }++ // Move the remaining content in the output buffer to the left hand side:+ int numSamplesRemaining =+ std::max(0L, outputBufferLastSample - samplesToOutput);+ if (numSamplesRemaining) {+ for (int c = 0; c < ioBlock.getNumChannels(); c++) {+ std::memmove((short *)outputBuffers[c].getData(),+ (short *)outputBuffers[c].getData() + samplesToOutput,+ numSamplesRemaining * sizeof(short));+ }+ }+ outputBufferLastSample = numSamplesRemaining;++ long usableSamplesProduced = std::max(+ 0L, samplesProduced - (encodingLatency + encoderInStreamLatency));+ int samplesInBuffer = static_cast<int>(+ std::min(usableSamplesProduced, (long)samplesToOutput));+ return samplesInBuffer;+ }++ void reset() override final {+ encoder.reset();+ decoder.reset();++ outputBuffers[0].fillWith(0);+ outputBuffers[1].fillWith(0);++ outputBufferLastSample = 0;+ samplesProduced = 0;+ samplesInEncodingBuffer = 0;+ encodingLatency = 0;+ encoderInStreamLatency = 0;+ }++protected:+ virtual int getLatencyHint() override {+ if (encodingLatency == 0) {+ // If we haven't started encoding yet, over-estimate+ // our latency bounds, as we'll almost always have a fairly large buffer.+ return encoderInStreamLatency + MAX_MP3_FRAME_SIZE_SAMPLES;+ }+ return encoderInStreamLatency + encodingLatency;+ }++private:+ float vbrLevel = 2.0;++ EncoderWrapper encoder;+ DecoderWrapper decoder;++ static constexpr unsigned long MAX_MP3_FRAME_SIZE_BYTES = 4096;+ static constexpr unsigned long MAX_MP3_FRAME_SIZE_SAMPLES = 1152;++ // This should really be an AudioBuffer<short>, but JUCE doesn't offer that.+ // TODO: This should be numChannels to support more than mono and stereo+ // audio!+ juce::MemoryBlock outputBuffers[2];+ long outputBufferLastSample = 0;+ long samplesProduced = 0;+ long samplesInEncodingBuffer = 0;++ // We have two latency numbers to consider here: the amount of latency between+ // supplying samples to LAME and getting samples back, and then the amount of+ // latency within the stream coming out of LAME itself.+ long encodingLatency = 0;+ long encoderInStreamLatency = 0;+};++inline void init_mp3_compressor(py::module &m) {+ py::class_<MP3Compressor, Plugin>(+ m, "MP3Compressor",+ "Apply an MP3 compressor to the audio to reduce its quality.")+ .def(py::init([](float vbr_quality) {+ auto plugin = new MP3Compressor();+ plugin->setVBRQuality(vbr_quality);+ return plugin;+ }),+ py::arg("vbr_quality") = 2.0)+ .def("__repr__",+ [](const MP3Compressor &plugin) {+ std::ostringstream ss;+ ss << "<pedalboard.MP3Compressor";+ ss << " vbr_quality=" << plugin.getVBRQuality();+ ss << " at " << &plugin;+ ss << ">";+ return ss.str();+ })+ .def_property("vbr_quality", &MP3Compressor::getVBRQuality,+ &MP3Compressor::setVBRQuality);+}++}; // namespace Pedalboarddiff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cppindex 61bf115..565cb7e 100644--- a/pedalboard/python_bindings.cpp+++ b/pedalboard/python_bindings.cpp@@ -43,6 +43,7 @@ namespace py = pybind11;#include "plugins/LadderFilter.h"#include "plugins/Limiter.h"#include "plugins/LowpassFilter.h"+#include "plugins/MP3Compressor.h"#include "plugins/NoiseGate.h"#include "plugins/Phaser.h"#include "plugins/PitchShift.h"@@ -144,6 +145,7 @@ PYBIND11_MODULE(pedalboard_native, m) {init_ladderfilter(m);init_limiter(m);init_lowpass(m);+ init_mp3_compressor(m);init_noisegate(m);init_phaser(m);init_pitch_shift(m);diff --git a/setup.py b/setup.pyindex 5dccadf..06de5b2 100644--- a/setup.py+++ b/setup.py@@ -18,99 +18,151 @@import osimport platformfrom subprocess import check_output-from pybind11.setup_helpers import Pybind11Extension+from pybind11.setup_helpers import Pybind11Extension, build_extfrom pathlib import Pathfrom distutils.core import setupfrom distutils.unixccompiler import UnixCCompilerDEBUG = bool(int(os.environ.get('DEBUG', 0)))-JUCE_CPPFLAGS = [- "-DJUCE_DISPLAY_SPLASH_SCREEN=1",- "-DJUCE_USE_DARK_SPLASH_SCREEN=1",- "-DJUCE_MODULE_AVAILABLE_juce_audio_basics=1",- "-DJUCE_MODULE_AVAILABLE_juce_audio_formats=1",- "-DJUCE_MODULE_AVAILABLE_juce_audio_processors=1",- "-DJUCE_MODULE_AVAILABLE_juce_core=1",- "-DJUCE_MODULE_AVAILABLE_juce_data_structures=1",- "-DJUCE_MODULE_AVAILABLE_juce_dsp=1",- "-DJUCE_MODULE_AVAILABLE_juce_events=1",- "-DJUCE_MODULE_AVAILABLE_juce_graphics=1",- "-DJUCE_MODULE_AVAILABLE_juce_gui_basics=1",- "-DJUCE_MODULE_AVAILABLE_juce_gui_extra=1",- "-DJUCE_GLOBAL_MODULE_SETTINGS_INCLUDED=1",- "-DJUCE_STRICT_REFCOUNTEDPOINTER=1",- "-DJUCE_STANDALONE_APPLICATION=1",- "-DJUCER_LINUX_MAKE_6D53C8B4=1",- "-DJUCE_APP_VERSION=1.0.0",- "-DJUCE_APP_VERSION_HEX=0x10000",- "-DUSE_BQRESAMPLER=1",- "-DNO_THREADING=1", # for RubberBand, whose threading we have disabled+# C or C++ flags:+ALL_COMPILER_FLAGS = ['-Wall',]+ALL_INCLUDES = []+ALL_LINK_ARGS = []+ALL_CPPFLAGS = []+ALL_LIBRARIES = []+ALL_SOURCE_PATHS = []+# Add JUCE-related flags:+ALL_CPPFLAGS.extend(+ [+ "-DJUCE_DISPLAY_SPLASH_SCREEN=1",+ "-DJUCE_USE_DARK_SPLASH_SCREEN=1",+ "-DJUCE_MODULE_AVAILABLE_juce_audio_basics=1",+ "-DJUCE_MODULE_AVAILABLE_juce_audio_formats=1",+ "-DJUCE_MODULE_AVAILABLE_juce_audio_processors=1",+ "-DJUCE_MODULE_AVAILABLE_juce_core=1",+ "-DJUCE_MODULE_AVAILABLE_juce_data_structures=1",+ "-DJUCE_MODULE_AVAILABLE_juce_dsp=1",+ "-DJUCE_MODULE_AVAILABLE_juce_events=1",+ "-DJUCE_MODULE_AVAILABLE_juce_graphics=1",+ "-DJUCE_MODULE_AVAILABLE_juce_gui_basics=1",+ "-DJUCE_MODULE_AVAILABLE_juce_gui_extra=1",+ "-DJUCE_GLOBAL_MODULE_SETTINGS_INCLUDED=1",+ "-DJUCE_STRICT_REFCOUNTEDPOINTER=1",+ "-DJUCE_STANDALONE_APPLICATION=1",+ "-DJUCER_LINUX_MAKE_6D53C8B4=1",+ "-DJUCE_APP_VERSION=1.0.0",+ "-DJUCE_APP_VERSION_HEX=0x10000",+ # Consoleapp flags:+ "-DJucePlugin_Build_VST=0",+ "-DJucePlugin_Build_VST3=0",+ "-DJucePlugin_Build_AU=0",+ "-DJucePlugin_Build_AUv3=0",+ "-DJucePlugin_Build_RTAS=0",+ "-DJucePlugin_Build_AAX=0",+ "-DJucePlugin_Build_Standalone=0",+ "-DJucePlugin_Build_Unity=0",+ # "-DJUCE_PLUGINHOST_VST=1", # Include for VST2 support, not licensed by Steinberg+ "-DJUCE_PLUGINHOST_VST3=1",+ # "-DJUCE_PLUGINHOST_LADSPA=1", # Include for LADSPA plugin support, Linux only.+ "-DJUCE_DISABLE_JUCE_VERSION_PRINTING=1",+ "-DJUCE_WEB_BROWSER=0",+ "-DJUCE_USE_CURL=0",+ # "-DJUCE_USE_FREETYPE=0",+ ]+)+ALL_INCLUDES.extend(['JUCE/modules/', 'JUCE/modules/juce_audio_processors/format_types/VST3_SDK/'])++# Rubber Band library:+ALL_CPPFLAGS.extend(+ [+ "-DUSE_BQRESAMPLER=1",+ "-DNO_THREADING=1",+ "-D_HAS_STD_BYTE=0",+ "-DNOMINMAX",+ ]+)+ALL_SOURCE_PATHS += list(Path("vendors/rubberband/single").glob("*.cpp"))++# LAME/mpglib:+# (man, this code is portable)+ALL_COMPILER_FLAGS.extend(+ [+ "-DSIZEOF_DOUBLE=8",+ "-DSIZEOF_FLOAT=4",+ "-DSIZEOF_INT=4",+ "-DSIZEOF_LONG=4",+ "-DSIZEOF_LONG_DOUBLE=12",+ "-DSIZEOF_SHORT=2",+ "-DSIZEOF_UNSIGNED_INT=4",+ "-DSIZEOF_UNSIGNED_LONG=4",+ "-DSIZEOF_UNSIGNED_SHORT=2",+ "-DSTDC_HEADERS",+ "-DHAVE_ERRNO_H",+ "-DHAVE_FCNTL_H",+ "-DHAVE_LIMITS_H",+ "-DPROTOTYPES=1",+ "-DHAVE_STRCHR",+ "-DHAVE_MEMCPY",+ "-Dieee754_float32_t=float",+ "-DHAVE_MPGLIB",+ ]+)+ALL_SOURCE_PATHS += list(Path("vendors/lame/libmp3lame").glob("*.c"))+ALL_SOURCE_PATHS += list(Path("vendors/lame/mpglib").glob("*.c"))+ALL_INCLUDES += [+ 'vendors/lame/include/',+ 'vendors/lame/libmp3lame/',+ 'vendors/lame/',+]+++# Add platform-specific flags:if platform.system() == "Darwin":- JUCE_CPPFLAGS.append("-DMACOS=1")- JUCE_CPPFLAGS.append("-DHAVE_VDSP=1")+ ALL_CPPFLAGS.append("-DMACOS=1")+ ALL_CPPFLAGS.append("-DHAVE_VDSP=1")elif platform.system() == "Linux":- JUCE_CPPFLAGS.append("-DLINUX=1")+ ALL_CPPFLAGS.append("-DLINUX=1")elif platform.system() == "Windows":- JUCE_CPPFLAGS.append("-DWINDOWS=1")- JUCE_CPPFLAGS.append("-D_HAS_STD_BYTE=0")- JUCE_CPPFLAGS.append("-DNOMINMAX")+ ALL_CPPFLAGS.append("-DWINDOWS=1")else:raise NotImplementedError("Not sure how to build JUCE on platform: {}!".format(platform.system()))-JUCE_CPPFLAGS_CONSOLEAPP = [- "-DJucePlugin_Build_VST=0",- "-DJucePlugin_Build_VST3=0",- "-DJucePlugin_Build_AU=0",- "-DJucePlugin_Build_AUv3=0",- "-DJucePlugin_Build_RTAS=0",- "-DJucePlugin_Build_AAX=0",- "-DJucePlugin_Build_Standalone=0",- "-DJucePlugin_Build_Unity=0",- # "-DJUCE_PLUGINHOST_VST=1", # Include for VST2 support, not licensed by Steinberg- "-DJUCE_PLUGINHOST_VST3=1",- # "-DJUCE_PLUGINHOST_LADSPA=1", # Include for LADSPA plugin support, Linux only.- "-DJUCE_DISABLE_JUCE_VERSION_PRINTING=1",- "-DJUCE_WEB_BROWSER=0",- "-DJUCE_USE_CURL=0",- # "-DJUCE_USE_FREETYPE=0",-]--LINK_ARGS = []--JUCE_INCLUDES = ['JUCE/modules/', 'JUCE/modules/juce_audio_processors/format_types/VST3_SDK/']-if DEBUG:- JUCE_CPPFLAGS += ["-DDEBUG=1", "-D_DEBUG=1"]- JUCE_CPPFLAGS += ['-O0', '-g']+ ALL_CPPFLAGS += ["-DDEBUG=1", "-D_DEBUG=1"]+ ALL_CPPFLAGS += ['-O0', '-g']if bool(int(os.environ.get('USE_ASAN', 0))):- JUCE_CPPFLAGS += ['-fsanitize=address', '-fno-omit-frame-pointer']- LINK_ARGS += ['-fsanitize=address']+ ALL_CPPFLAGS += ['-fsanitize=address', '-fno-omit-frame-pointer']+ ALL_LINK_ARGS += ['-fsanitize=address']if platform.system() == "Linux":- LINK_ARGS += ['-shared-libasan']+ ALL_LINK_ARGS += ['-shared-libasan']elif bool(int(os.environ.get('USE_TSAN', 0))):- JUCE_CPPFLAGS += ['-fsanitize=thread']- LINK_ARGS += ['-fsanitize=thread']+ ALL_CPPFLAGS += ['-fsanitize=thread']+ ALL_LINK_ARGS += ['-fsanitize=thread']elif bool(int(os.environ.get('USE_MSAN', 0))):- JUCE_CPPFLAGS += ['-fsanitize=memory', '-fsanitize-memory-track-origins']- LINK_ARGS += ['-fsanitize=memory']+ ALL_CPPFLAGS += ['-fsanitize=memory', '-fsanitize-memory-track-origins']+ ALL_LINK_ARGS += ['-fsanitize=memory']else:- JUCE_CPPFLAGS += ['/Ox' if platform.system() == "Windows" else '-O3']+ ALL_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 = []-sources = list(Path("pedalboard").glob("**/*.cpp"))-sources += list(Path("vendors/rubberband/single").glob("*.cpp"))+# Add all Pedalboard C++ sources:+ALL_SOURCE_PATHS += list(Path("pedalboard").glob("**/*.cpp"))++# Rubber Band pitch shifter/time stretcher+++# LAME MP3 encoder:if platform.system() == "Darwin":MACOS_FRAMEWORKS = [@@ -130,9 +182,9 @@ if platform.system() == "Darwin":# On MacOS, we link against some Objective-C system libraries, so we search# for Objective-C++ files instead of C++ files.for f in MACOS_FRAMEWORKS:- LINK_ARGS += ['-framework', f]- JUCE_CPPFLAGS_CONSOLEAPP += ["-DJUCE_PLUGINHOST_AU=1"]- JUCE_CPPFLAGS.append('-xobjective-c++')+ ALL_LINK_ARGS += ['-framework', f]+ ALL_CPPFLAGS.append("-DJUCE_PLUGINHOST_AU=1")+ ALL_CPPFLAGS.append('-xobjective-c++')# Replace .cpp sources with matching .mm sources on macOS to force the# compiler to use Apple's Objective-C and Objective-C++ code.@@ -141,15 +193,15 @@ if platform.system() == "Darwin":iter([cpp_source- for cpp_source in sources+ for cpp_source in ALL_SOURCE_PATHSif os.path.splitext(objc_source.name)[0] == os.path.splitext(cpp_source.name)[0]]),None,)if matching_cpp_source:- sources[sources.index(matching_cpp_source)] = objc_source- PEDALBOARD_SOURCES = [str(p.resolve()) for p in sources]+ ALL_SOURCE_PATHS[ALL_SOURCE_PATHS.index(matching_cpp_source)] = objc_source+ ALL_RESOLVED_SOURCE_PATHS = [str(p.resolve()) for p in ALL_SOURCE_PATHS]elif platform.system() == "Linux":for package in ['freetype2']:flags = (@@ -159,14 +211,14 @@ elif platform.system() == "Linux":.split(' '))include_paths = [flag[2:] for flag in flags]- JUCE_INCLUDES += include_paths- LINK_ARGS += ['-lfreetype']+ ALL_INCLUDES += include_paths+ ALL_LINK_ARGS += ['-lfreetype']- PEDALBOARD_SOURCES = [str(p.resolve()) for p in sources]+ ALL_RESOLVED_SOURCE_PATHS = [str(p.resolve()) for p in ALL_SOURCE_PATHS]elif platform.system() == "Windows":- JUCE_CPPFLAGS += ['-DJUCE_DLL_BUILD=1']+ ALL_CPPFLAGS += ['-DJUCE_DLL_BUILD=1']# https://forum.juce.com/t/statically-linked-exe-in-win-10-not-working/25574/3- LIBS.extend(+ ALL_LIBRARIES.extend(["kernel32","user32",@@ -182,19 +234,46 @@ elif platform.system() == "Windows":"odbccp32",])- PEDALBOARD_SOURCES = [str(p.resolve()) for p in sources]+ ALL_RESOLVED_SOURCE_PATHS = [str(p.resolve()) for p in ALL_SOURCE_PATHS]else:raise NotImplementedError("Not sure how to build JUCE on platform: {}!".format(platform.system()))++class C_CxxCompiler(UnixCCompiler):+ def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):+ _cc_args = cc_args++ if ext in ('.cpp', '.cxx', '.cc', '.mm'):+ _cc_args = cc_args + ALL_CPPFLAGS+ elif ext in ('.c'):+ # We're compiling C code, remove the -std= arg:+ extra_postargs = [arg for arg in extra_postargs if '-std=' not in arg]++ UnixCCompiler._compile(self, obj, src, ext, _cc_args, extra_postargs, pp_opts)+++class BuildC_CxxExtensions(build_ext):+ def build_extensions(self, *args, **kwargs):+ if self.compiler.compiler_type == 'unix':+ # Replace the compiler+ old_compiler = self.compiler+ self.compiler = C_CxxCompiler()++ # Copy its attributes+ for attr, value in old_compiler.__dict__.items():+ setattr(self.compiler, attr, value)+ build_ext.build_extensions(self, *args, **kwargs)++pedalboard_cpp = Pybind11Extension('pedalboard_native',- sources=PEDALBOARD_SOURCES,- include_dirs=JUCE_INCLUDES,- extra_compile_args=JUCE_CPPFLAGS + JUCE_CPPFLAGS_CONSOLEAPP,- extra_link_args=LINK_ARGS,- libraries=LIBS,+ sources=ALL_RESOLVED_SOURCE_PATHS,+ include_dirs=ALL_INCLUDES,+ extra_compile_args=ALL_COMPILER_FLAGS,+ extra_link_args=ALL_LINK_ARGS,+ libraries=ALL_LIBRARIES,language="c++",cxx_std=17,)@@ -239,4 +318,5 @@ setup(ext_modules=[pedalboard_cpp],install_requires=['numpy'],packages=['pedalboard'],+ cmdclass={"build_ext": BuildC_CxxExtensions},)diff --git a/tests/test_mp3_compressor.py b/tests/test_mp3_compressor.pynew file mode 100644index 0000000..cc28705--- /dev/null+++ b/tests/test_mp3_compressor.py@@ -0,0 +1,33 @@+#! /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 MP3Compressor++[email protected]("vbr_quality", [0.0, 0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9.5])[email protected]("sample_rate", [44100, 48000])+def test_mp3_compressor(vbr_quality: float, sample_rate: int):+ num_seconds = 10.0+ fundamental_hz = 440+ samples = np.arange(num_seconds * sample_rate)+ sine_wave = np.sin(2 * np.pi * fundamental_hz * samples / sample_rate)+ stereo_sine_wave = np.stack([sine_wave, sine_wave])++ compressed = MP3Compressor(vbr_quality)(stereo_sine_wave, sample_rate)+ np.testing.assert_allclose(stereo_sine_wave, compressed, atol=0.25)diff --git a/vendors/lame b/vendors/lamenew file mode 160000index 0000000..1f5cc94--- /dev/null+++ b/vendors/lame@@ -0,0 +1 @@+Subproject commit 1f5cc9487284d5950343aa5d4f70de433468070a