๐ ๐ A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
Added MP3 writing support via LAME.
Peter Sobot339588fb7759
diff --git a/README.md b/README.mdindex c6b69fb..dfbeb50 100644--- a/README.md+++ b/README.md@@ -28,8 +28,7 @@ Internally at Spotify, `pedalboard` is used for [data augmentation](https://en.w- Supports VST3ยฎ plugins on macOS, Windows, and Linux (`pedalboard.load_plugin`)- Supports Audio Units on macOS- Built-in audio I/O utilities (`pedalboard.io.AudioFile`)- - Support for reading AIFF, FLAC, MP3, OGG, and WAV files on all platforms with no dependencies- - Support for writing AIFF, FLAC, OGG, and WAV on all platforms with no dependencies+ - Support for reading and writing AIFF, FLAC, MP3, OGG, and WAV files on all platforms with no dependencies- Additional support for reading AAC, AC3, WMA, and other formats depending on platform- Strong thread-safety, memory usage, and speed guarantees- Releases Python's Global Interpreter Lock (GIL) to allow use of multiple CPU coresdiff --git a/pedalboard/io/LameMP3AudioFormat.h b/pedalboard/io/LameMP3AudioFormat.hnew file mode 100644index 0000000..f7dc587--- /dev/null+++ b/pedalboard/io/LameMP3AudioFormat.h@@ -0,0 +1,200 @@+/*+ * 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.+ */+#pragma once++#include "../JuceHeader.h"+#include "../plugins/MP3Compressor.h"++extern "C" {+#include <lame.h>+}++namespace Pedalboard {+class LameMP3AudioFormat : public juce::AudioFormat {+public:+ LameMP3AudioFormat() : juce::AudioFormat("MP3", ".mp3"){};+ ~LameMP3AudioFormat(){};++ juce::Array<int> getPossibleSampleRates() { return {32000, 44100, 48000}; }+ juce::Array<int> getPossibleBitDepths() { return {16}; }+ bool canDoStereo() { return true; }+ bool canDoMono() { return true; }+ bool isCompressed() { return true; }++ juce::StringArray getQualityOptions() {+ juce::StringArray opts(VBR_OPTIONS);++ for (int i = 0; i < juce::numElementsInArray(CBR_OPTIONS); ++i)+ opts.add(juce::String(CBR_OPTIONS[i]) + " kbps");++ return opts;+ }++ juce::AudioFormatReader *createReaderFor(juce::InputStream *,+ bool deleteStreamIfOpeningFails) {+ return nullptr;+ }++ juce::AudioFormatWriter *+ createWriterFor(juce::OutputStream *out, double sampleRateToUse,+ unsigned int numberOfChannels, int bitsPerSample,+ const juce::StringPairArray &metadataValues,+ int qualityOptionIndex) {++ try {+ if (out != nullptr)+ return new Writer(out, sampleRateToUse, numberOfChannels,+ qualityOptionIndex);+ } catch (...) {+ // TODO: Make WriteableAudioFile exception-safe so we can bubble up more+ // useful error messages.+ }++ return nullptr;+ }+ using juce::AudioFormat::createWriterFor;++ class Writer : public juce::AudioFormatWriter {+ public:+ Writer(juce::OutputStream *destStream, double sampleRate,+ unsigned int numberOfChannels, int qualityOptionIndex)+ : juce::AudioFormatWriter(nullptr, "MP3", sampleRate, numberOfChannels,+ 16) {+ usesFloatingPointData = false;++ // Suppress all error logging from LAME+ // TODO: find out how to catch and report these errors to Python!+ lame_set_errorf(encoder.getContext(), nullptr);++ if (lame_set_in_samplerate(encoder.getContext(), sampleRate) != 0 ||+ lame_set_out_samplerate(encoder.getContext(), sampleRate) != 0) {+ throw std::domain_error(+ "MP3 only supports 32kHz, 44.1kHz, and 48kHz audio. (Was passed "+ "a sample rate of " ++ juce::String(sampleRate / 1000, 1).toStdString() + "kHz.)");+ }++ if (lame_set_num_channels(encoder.getContext(), numChannels) != 0) {+ throw std::domain_error(+ "MP3 only supports mono or stereo audio. (Was passed " ++ std::to_string(numChannels) + "-channel audio.)");+ }++ if (lame_set_VBR(encoder.getContext(), vbr_default) != 0) {+ throw std::domain_error(+ "MP3 encoder failed to set variable bit rate flag.");+ }++ juce::StringArray opts(VBR_OPTIONS);++ if (qualityOptionIndex < NUM_VBR_OPTIONS) {+ // VBR options:+ if (lame_set_VBR_quality(encoder.getContext(), qualityOptionIndex) !=+ 0) {+ throw std::domain_error(+ "MP3 encoder failed to set variable bit rate quality to " ++ std::to_string(qualityOptionIndex) + "!");+ }+ } else if (qualityOptionIndex <+ (NUM_VBR_OPTIONS + juce::numElementsInArray(CBR_OPTIONS))) {+ // CBR options:+ if (lame_set_brate(encoder.getContext(),+ CBR_OPTIONS[qualityOptionIndex - NUM_VBR_OPTIONS]) !=+ 0) {+ throw std::domain_error(+ "MP3 encoder failed to set constant bit rate quality to " ++ std::to_string(+ CBR_OPTIONS[qualityOptionIndex - NUM_VBR_OPTIONS]) ++ "!");+ }+ } else {+ throw std::domain_error("Unsupported quality index!");+ }++ int ret = lame_init_params(encoder.getContext());+ if (ret != 0) {+ throw std::runtime_error("Failed to initialize MP3 encoder! (error " ++ std::to_string(ret) + ")");+ }++ // Assign this at the end, as the AudioFormatWriter destructor+ // automatically deletes this pointer, and we don't want that+ // to happen if our constructor fails.+ output = destStream;++ // Flush the initial header:+ const int *emptyBuffers[2] = {0};+ if (!write(emptyBuffers, 0)) {+ output = nullptr;+ throw std::runtime_error("Failed to write header!");+ }+ }++ virtual ~Writer() override { flush(); };++ virtual bool write(const int **samplesToWrite, int numSamples) {+ // Constants from the LAME docs+ std::vector<unsigned char> encodedMp3Buffer(1.25 * numSamples + 7200);++ std::vector<std::vector<short>> shortSamples(numChannels);+ for (int c = 0; c < numChannels; c++) {+ shortSamples[c].resize(numSamples);+ for (int i = 0; i < numSamples; i++) {+ shortSamples[c][i] = samplesToWrite[c][i] >> 16;+ }+ }++ int mp3BufferBytesFilled = lame_encode_buffer(+ encoder.getContext(), shortSamples[0].data(),+ numChannels == 1 ? nullptr : shortSamples[1].data(), numSamples,+ (unsigned char *)encodedMp3Buffer.data(), encodedMp3Buffer.size());+ return output->write((unsigned char *)encodedMp3Buffer.data(),+ mp3BufferBytesFilled);+ }++ virtual bool flush() {+ if (!output)+ return false;++ std::vector<unsigned char> mp3buf(7200); // Constant from the LAME docs+ int bytesWritten = lame_encode_flush_nogap(encoder.getContext(),+ mp3buf.data(), mp3buf.size());++ if (bytesWritten < 0) {+ return false;+ }++ output->write(mp3buf.data(), bytesWritten);+ output->flush();+ return true;+ }++ private:+ EncoderWrapper encoder;+ };++private:+ static inline const char *VBR_OPTIONS[] = {+ "V0 (best)", "V1", "V2", "V3", "V4 (normal)",+ "V5", "V6", "V7", "V8", "V9 (smallest)",+ nullptr};+ static const int NUM_VBR_OPTIONS = 10;+ static inline const int CBR_OPTIONS[] = {32, 40, 48, 56, 64, 80, 96,+ 112, 128, 160, 192, 224, 256, 320};+};++} // namespace Pedalboarddiff --git a/pedalboard/io/WriteableAudioFile.h b/pedalboard/io/WriteableAudioFile.hindex fc70868..81731fa 100644--- a/pedalboard/io/WriteableAudioFile.h+++ b/pedalboard/io/WriteableAudioFile.h@@ -26,6 +26,7 @@#include "../BufferUtils.h"#include "../JuceHeader.h"#include "AudioFile.h"+#include "LameMP3AudioFormat.h"#include "PythonOutputStream.h"namespace py = pybind11;@@ -66,6 +67,8 @@ int determineQualityOptionIndex(juce::AudioFormat *format,for (int i = 0; i < qualityString.size(); i++) {if (juce::CharacterFunctions::isDigit(qualityString[i])) {numLeadingDigits++;+ } else {+ break;}}@@ -211,7 +214,13 @@ public:"non-zero num_channels.");}- formatManager.registerBasicFormats();+ // Don't use registerBasicFormats(), as it'll register the wrong MP3 format:+ formatManager.registerFormat(new juce::WavAudioFormat(), false);+ formatManager.registerFormat(new juce::AiffAudioFormat(), false);+ formatManager.registerFormat(new juce::FlacAudioFormat(), false);+ formatManager.registerFormat(new juce::OggVorbisAudioFormat(), false);+ formatManager.registerFormat(new LameMP3AudioFormat(), false);+std::unique_ptr<juce::OutputStream> outputStream;juce::AudioFormat *format = nullptr;std::string extension;@@ -318,7 +327,7 @@ public:throw std::domain_error(format->getFormatName().toStdString() +" audio files do not support the provided sample rate of " +- std::to_string(writeSampleRate) ++ juce::String(writeSampleRate, 2).toStdString() +"Hz. Supported sample rates: " + sampleRateString.str());}@@ -913,7 +922,8 @@ inline void init_writeable_audio_file(py::module &m) {// platforms, and there's no easy way to tell which formats are supported// without attempting to create an AudioFileWriter object - so this list is// hardcoded for now.- const std::vector<std::string> formats = {".aiff", ".flac", ".ogg", ".wav"};+ const std::vector<std::string> formats = {".aiff", ".flac", ".ogg", ".wav",+ ".mp3"};return formats;});}diff --git a/pedalboard/plugins/MP3Compressor.h b/pedalboard/plugins/MP3Compressor.hindex 4fc19e4..d1a8ff2 100644--- a/pedalboard/plugins/MP3Compressor.h+++ b/pedalboard/plugins/MP3Compressor.h@@ -14,6 +14,7 @@* See the License for the specific language governing permissions and* limitations under the License.*/+#pragma once#include "../Plugin.h"diff --git a/tests/test_io.py b/tests/test_io.pyindex b52ae02..e02035e 100644--- a/tests/test_io.py+++ b/tests/test_io.py@@ -66,12 +66,9 @@ def get_tolerance_for_format_and_bit_depth(extension: str, input_format, file_dtreturn 4 / (2 ** file_bit_depth)# These formats offset the waveform substantially, and these tests don't do any realignment.- if extension in {".m4a", ".ac3", ".adts", ".mp4", ".mp2"}:+ if extension in {".m4a", ".ac3", ".adts", ".mp4", ".mp2", ".mp3"}:return 3.0- if extension in {".mp3"}:- return 0.8-return 0.12@@ -486,6 +483,11 @@ def test_basic_write(transposed: bool,input_format,):+ if extension == ".mp3":+ if samplerate not in {32000, 44100, 48000}:+ return+ if num_channels > 2:+ returnfilename = str(tmp_path / f"test{extension}")original_audio = generate_sine_at(samplerate, num_channels=num_channels)@@ -604,6 +606,11 @@ def test_basic_write_int32_to_16_bit_wav(tmp_path: pathlib.Path):def test_write_to_seekable_stream(extension: str, samplerate: float, num_channels: int, transposed: bool, input_format):+ if extension == ".mp3":+ if samplerate not in {32000, 44100, 48000}:+ return+ if num_channels > 2:+ returnoriginal_audio = generate_sine_at(samplerate, num_channels=num_channels)write_bit_depth = 16@@ -659,7 +666,7 @@ def test_fractional_sample_rates(tmp_path: pathlib.Path, extension: str, samplerpedalboard.io.WriteableAudioFile(filename, samplerate=samplerate, num_channels=1)[email protected]("extension", pedalboard.io.get_supported_write_formats())[email protected]("extension", set(pedalboard.io.get_supported_write_formats()) - {".mp3"})@pytest.mark.parametrize("samplerate", [123, 999, 48001])def test_uncommon_sample_rates(tmp_path: pathlib.Path, extension: str, samplerate):filename = str(tmp_path / f"test{extension}")@@ -764,6 +771,53 @@ def test_fail_to_write_unsigned(tmp_path: pathlib.Path, dtype):("flac", 6, "6"),("flac", 7, "7"),("flac", 8, "8 (Highest quality)"),+ ("mp3", "V0", "V0 (best)"),+ ("mp3", "V0 (best)", "V0 (best)"),+ ("mp3", "best", "V0 (best)"),+ ("mp3", "V1", "V1"),+ ("mp3", "V2", "V2"),+ ("mp3", "V3", "V3"),+ ("mp3", "V4", "V4 (normal)"),+ ("mp3", "V4 (normal)", "V4 (normal)"),+ ("mp3", "normal", "V4 (normal)"),+ ("mp3", "V5", "V5"),+ ("mp3", "V6", "V6"),+ ("mp3", "V7", "V7"),+ ("mp3", "V8", "V8"),+ ("mp3", "V9", "V9 (smallest)"),+ ("mp3", "V9 (smallest)", "V9 (smallest)"),+ ("mp3", "smallest", "V9 (smallest)"),+ ("mp3", "", "320 kbps"),+ ("mp3", " ", "320 kbps"),+ ("mp3", None, "320 kbps"),+ ("mp3", 32, "32 kbps"),+ ("mp3", 40, "40 kbps"),+ ("mp3", 48, "48 kbps"),+ ("mp3", 56, "56 kbps"),+ ("mp3", 64, "64 kbps"),+ ("mp3", 80, "80 kbps"),+ ("mp3", 96, "96 kbps"),+ ("mp3", 112, "112 kbps"),+ ("mp3", 128, "128 kbps"),+ ("mp3", 160, "160 kbps"),+ ("mp3", 192, "192 kbps"),+ ("mp3", 224, "224 kbps"),+ ("mp3", 256, "256 kbps"),+ ("mp3", 320, "320 kbps"),+ ("mp3", "32 kbps", "32 kbps"),+ ("mp3", "40 kbps", "40 kbps"),+ ("mp3", "48 kbps", "48 kbps"),+ ("mp3", "56 kbps", "56 kbps"),+ ("mp3", "64 kbps", "64 kbps"),+ ("mp3", "80 kbps", "80 kbps"),+ ("mp3", "96 kbps", "96 kbps"),+ ("mp3", "112 kbps", "112 kbps"),+ ("mp3", "128 kbps", "128 kbps"),+ ("mp3", "160 kbps", "160 kbps"),+ ("mp3", "192 kbps", "192 kbps"),+ ("mp3", "224 kbps", "224 kbps"),+ ("mp3", "256 kbps", "256 kbps"),+ ("mp3", "320 kbps", "320 kbps"),("wav", None, None),("wav", "", None),("aiff", None, None),