π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
Use the same MP3 parser on macOS, Linux, and Windows.
Peter Sobotcc602c5bbad0
diff --git a/pedalboard/io/AudioFile.h b/pedalboard/io/AudioFile.hindex 462f603..0400ac4 100644--- a/pedalboard/io/AudioFile.h+++ b/pedalboard/io/AudioFile.h@@ -28,12 +28,10 @@ static constexpr const unsigned int DEFAULT_AUDIO_BUFFER_SIZE_FRAMES = 8192;/*** Registers audio formats for reading and writing in a deterministic (but- * configurable) order. On different platforms, different formats are handled by- * different backends (i.e.: CoreAudioFormat handles MP3 on macOS, but only for- * reading) so this method allows us to ensure reproducibility in tests.+ * configurable) order.*/void registerPedalboardAudioFormats(juce::AudioFormatManager &manager,- bool forWriting, bool crossPlatformOnly) {+ bool forWriting) {manager.registerFormat(new juce::WavAudioFormat(), true);manager.registerFormat(new juce::AiffAudioFormat(), false);manager.registerFormat(new juce::PatchedFlacAudioFormat(), false);@@ -42,30 +40,20 @@ void registerPedalboardAudioFormats(juce::AudioFormatManager &manager,manager.registerFormat(new juce::OggVorbisAudioFormat(), false);#endif+#if JUCE_USE_WINDOWS_MEDIA_FORMAT+ manager.registerFormat(new juce::WindowsMediaAudioFormat(), false);+#endif+if (forWriting) {// Prefer our own custom MP3 format (which only writes, doesn't read) over- // MP3AudioFormat (which only reads, doesn't write)+ // PatchedMP3AudioFormat (which only reads, doesn't write)manager.registerFormat(new LameMP3AudioFormat(), false);} else {- // On macOS, CoreAudio can read MP3s better (more fault-tolerantly) than- // MP3AudioFormat can. But sometimes, we still want to use the built-in MP3- // reader so that we can get identical parsing behaviour on both macOS and- // Linux. To do so, we use this flag:-- if (crossPlatformOnly) {- manager.registerFormat(new juce::PatchedMP3AudioFormat(), false);- } else {+ manager.registerFormat(new juce::PatchedMP3AudioFormat(), false);#if JUCE_MAC || JUCE_IOS- manager.registerFormat(new juce::CoreAudioFormat(), false);-#else- manager.registerFormat(new juce::PatchedMP3AudioFormat(), false);+ manager.registerFormat(new juce::CoreAudioFormat(), false);#endif- }}--#if JUCE_USE_WINDOWS_MEDIA_FORMAT- manager.registerFormat(new juce::WindowsMediaAudioFormat(), false);-#endif}class AudioFile {};diff --git a/pedalboard/io/ReadableAudioFile.h b/pedalboard/io/ReadableAudioFile.hindex 5c7132f..2ecd148 100644--- a/pedalboard/io/ReadableAudioFile.h+++ b/pedalboard/io/ReadableAudioFile.h@@ -36,10 +36,8 @@ class ReadableAudioFile: public AudioFile,public std::enable_shared_from_this<ReadableAudioFile> {public:- ReadableAudioFile(std::string filename, bool crossPlatformFormatsOnly = false)- : filename(filename) {- registerPedalboardAudioFormats(formatManager, false,- crossPlatformFormatsOnly);+ ReadableAudioFile(std::string filename) : filename(filename) {+ registerPedalboardAudioFormats(formatManager, false);juce::File file(filename);@@ -61,10 +59,8 @@ public:"\" does not seem to be of a known or supported format.");}- ReadableAudioFile(std::unique_ptr<PythonInputStream> inputStream,- bool crossPlatformFormatsOnly = false) {- registerPedalboardAudioFormats(formatManager, false,- crossPlatformFormatsOnly);+ ReadableAudioFile(std::unique_ptr<PythonInputStream> inputStream) {+ registerPedalboardAudioFormats(formatManager, false);if (!inputStream->isSeekable()) {PythonException::raise();@@ -505,9 +501,7 @@ be readable depending on the operating system and installed system libraries:``.wav``Use :meth:`pedalboard.io.get_supported_read_formats()` to see which-formats or file extensions are supported on the current platform. To use-only audio format parsing libraries that are consistent on all platforms, pass-``cross_platform_formats_only=True`` to this constructor.+formats or file extensions are supported on the current platform.(Note that although an audio file may have a certain file extension, itscontents may be encoded with a compression algorithm unsupported by@@ -528,35 +522,29 @@ inline void init_readable_audio_file(py::class_<ReadableAudioFile, AudioFile, std::shared_ptr<ReadableAudioFile>>&pyReadableAudioFile) {pyReadableAudioFile- .def(py::init([](std::string filename,- bool crossPlatformFormatsOnly) -> ReadableAudioFile * {+ .def(py::init([](std::string filename) -> ReadableAudioFile * {// This definition is only here to provide nice docstrings.throw std::runtime_error("Internal error: __init__ should never be called, as this ""class implements __new__.");}),- py::arg("filename"), py::arg("cross_platform_formats_only") = false)- .def(py::init([](py::object filelike,- bool crossPlatformFormatsOnly) -> ReadableAudioFile * {+ py::arg("filename"))+ .def(py::init([](py::object filelike) -> ReadableAudioFile * {// This definition is only here to provide nice docstrings.throw std::runtime_error("Internal error: __init__ should never be called, as this ""class implements __new__.");}),- py::arg("file_like"), py::arg("cross_platform_formats_only") = false)+ py::arg("file_like")).def_static("__new__",- [](const py::object *, std::string filename,- bool crossPlatformFormatsOnly) {- return std::make_shared<ReadableAudioFile>(- filename, crossPlatformFormatsOnly);+ [](const py::object *, std::string filename) {+ return std::make_shared<ReadableAudioFile>(filename);},- py::arg("cls"), py::arg("filename"),- py::arg("cross_platform_formats_only") = false)+ py::arg("cls"), py::arg("filename")).def_static("__new__",- [](const py::object *, py::object filelike,- bool crossPlatformFormatsOnly) {+ [](const py::object *, py::object filelike) {if (!isReadableFileLike(filelike)) {throw py::type_error("Expected either a filename or a file-like object (with "@@ -565,11 +553,9 @@ inline void init_readable_audio_file(}return std::make_shared<ReadableAudioFile>(- std::make_unique<PythonInputStream>(filelike),- crossPlatformFormatsOnly);+ std::make_unique<PythonInputStream>(filelike));},- py::arg("cls"), py::arg("file_like"),- py::arg("cross_platform_formats_only") = false)+ py::arg("cls"), py::arg("file_like")).def("read", &ReadableAudioFile::read, py::arg("num_frames") = 0,"Read the given number of frames (samples in each channel) from this "@@ -679,36 +665,31 @@ inline void init_readable_audio_file("provided `target_sample_rate`, using a constant amount of ""memory.\n\n*Introduced in v0.6.0.*");- m.def(- "get_supported_read_formats",- [](bool crossPlatformFormatsOnly) {- juce::AudioFormatManager manager;- registerPedalboardAudioFormats(manager, false,- crossPlatformFormatsOnly);-- std::vector<std::string> formatNames(manager.getNumKnownFormats());- juce::StringArray extensions;- for (int i = 0; i < manager.getNumKnownFormats(); i++) {- auto *format = manager.getKnownFormat(i);- extensions.addArray(format->getFileExtensions());- }+ m.def("get_supported_read_formats", []() {+ juce::AudioFormatManager manager;+ registerPedalboardAudioFormats(manager, false);++ std::vector<std::string> formatNames(manager.getNumKnownFormats());+ juce::StringArray extensions;+ for (int i = 0; i < manager.getNumKnownFormats(); i++) {+ auto *format = manager.getKnownFormat(i);+ extensions.addArray(format->getFileExtensions());+ }- extensions.trim();- extensions.removeEmptyStrings();- extensions.removeDuplicates(true);+ extensions.trim();+ extensions.removeEmptyStrings();+ extensions.removeDuplicates(true);- std::vector<std::string> output;- for (juce::String s : extensions) {- output.push_back(s.toStdString());- }+ std::vector<std::string> output;+ for (juce::String s : extensions) {+ output.push_back(s.toStdString());+ }- std::sort(output.begin(), output.end(),- [](const std::string lhs, const std::string rhs) {- return lhs < rhs;- });+ std::sort(+ output.begin(), output.end(),+ [](const std::string lhs, const std::string rhs) { return lhs < rhs; });- return output;- },- py::arg("cross_platform_formats_only") = false);+ return output;+ });}} // namespace Pedalboarddiff --git a/pedalboard/io/WriteableAudioFile.h b/pedalboard/io/WriteableAudioFile.hindex 1046af6..317ab5c 100644--- a/pedalboard/io/WriteableAudioFile.h+++ b/pedalboard/io/WriteableAudioFile.h@@ -248,7 +248,7 @@ public:"non-zero num_channels.");}- registerPedalboardAudioFormats(formatManager, true, false);+ registerPedalboardAudioFormats(formatManager, true);std::unique_ptr<juce::OutputStream> outputStream;juce::AudioFormat *format = nullptr;@@ -966,17 +966,14 @@ inline void init_writeable_audio_file("The strings ``\"best\"``, ``\"worst\"``, ``\"fastest\"``, and ""``\"slowest\"`` will also work for any codec.");- m.def(- "get_supported_write_formats",- [](bool crossPlatformFormatsOnly = false) {- // JUCE doesn't support writing other formats out-of-the-box on all- // 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", ".mp3"};- return formats;- },- py::arg("cross_platform_formats_only") = false);+ m.def("get_supported_write_formats", []() {+ // JUCE doesn't support writing other formats out-of-the-box on all+ // 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",+ ".mp3"};+ return formats;+ });}} // namespace Pedalboard\ No newline at end of filediff --git a/tests/test_io.py b/tests/test_io.pyindex 741ee48..70e2724 100644--- a/tests/test_io.py+++ b/tests/test_io.py@@ -48,17 +48,6 @@ FILENAMES_AND_SAMPLERATES = [if any(filename.endswith(extension) for extension in pedalboard.io.get_supported_read_formats())]-CROSS_PLATFORM_FILENAMES_AND_SAMPLERATES = [- (filename, samplerate)- for samplerate, filenames in TEST_AUDIO_FILES.items()- for filename in filenames- # On some platforms, not all extensions will be available.- if any(- filename.endswith(extension)- for extension in pedalboard.io.get_supported_read_formats(cross_platform_formats_only=True)- )-]-UNSUPPORTED_FILENAMES = [filename@@ -68,15 +57,6 @@ UNSUPPORTED_FILENAMES = [)]-UNSUPPORTED_CROSS_PLATFORM_FILENAMES = [- filename- for filename in sum(TEST_AUDIO_FILES.values(), [])- if not any(- filename.endswith(extension)- for extension in pedalboard.io.get_supported_read_formats(cross_platform_formats_only=True)- )-]-def get_tolerance_for_format_and_bit_depth(extension: str, input_format, file_dtype: str) -> float:if not extension.startswith("."):@@ -165,18 +145,9 @@ def test_basic_formats_available_on_all_platforms(extension: str):assert extension in pedalboard.io.get_supported_read_formats()- "audio_filename,samplerate,cross_platform_formats_only",- [(a, s, False) for a, s in FILENAMES_AND_SAMPLERATES]- + [(a, s, True) for a, s in CROSS_PLATFORM_FILENAMES_AND_SAMPLERATES],-)-def test_basic_read(audio_filename: str, samplerate: float, cross_platform_formats_only: bool):- if cross_platform_formats_only:- af = pedalboard.io.ReadableAudioFile(- audio_filename, cross_platform_formats_only=cross_platform_formats_only- )- else:- af = pedalboard.io.AudioFile(audio_filename)[email protected]("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)+def test_basic_read(audio_filename: str, samplerate: float):+ af = pedalboard.io.AudioFile(audio_filename)assert af.samplerate == samplerateassert af.num_channels == 1if any(ext in audio_filename for ext in EXPECT_LENGTH_TO_BE_EXACT):@@ -280,40 +251,23 @@ def test_context_manager_allows_exceptions():assert af.closed- "cross_platform_formats_only,audio_filename,samplerate",- [(False, f, sr) for f, sr in FILENAMES_AND_SAMPLERATES]- + [(True, f, sr) for f, sr in CROSS_PLATFORM_FILENAMES_AND_SAMPLERATES],-)[email protected]("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)def test_read_okay_without_extension(- tmp_path: pathlib.Path,- audio_filename: str,- samplerate: float,- cross_platform_formats_only: bool,+ tmp_path: pathlib.Path, audio_filename: str, samplerate: float):dest_path = str(tmp_path / "no_extension")shutil.copyfile(audio_filename, dest_path)- with pedalboard.io.ReadableAudioFile(- dest_path, cross_platform_formats_only=cross_platform_formats_only- ) as af:+ with pedalboard.io.AudioFile(dest_path) as af:assert af.samplerate == samplerateassert af.num_channels == 1- "cross_platform_formats_only,audio_filename,samplerate",- [(False, f, sr) for f, sr in FILENAMES_AND_SAMPLERATES]- + [(True, f, sr) for f, sr in CROSS_PLATFORM_FILENAMES_AND_SAMPLERATES],-)-def test_read_from_seekable_stream(- audio_filename: str, samplerate: float, cross_platform_formats_only: bool-):[email protected]("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)+def test_read_from_seekable_stream(audio_filename: str, samplerate: float):with open(audio_filename, "rb") as f:stream = io.BytesIO(f.read())- af = pedalboard.io.ReadableAudioFile(- stream, cross_platform_formats_only=cross_platform_formats_only- )+ af = pedalboard.io.AudioFile(stream)with af:assert af.samplerate == samplerate@@ -496,16 +450,10 @@ def test_fails_gracefully():pass- "cross_platform_formats_only,audio_filename",- [(False, f) for f in UNSUPPORTED_FILENAMES]- + [(True, f) for f in UNSUPPORTED_CROSS_PLATFORM_FILENAMES],-)-def test_fails_on_unsupported_format(cross_platform_formats_only: bool, audio_filename: str):[email protected]("audio_filename", UNSUPPORTED_FILENAMES)+def test_fails_on_unsupported_format(audio_filename: str):with pytest.raises(ValueError):- af = pedalboard.io.ReadableAudioFile(- audio_filename, cross_platform_formats_only=cross_platform_formats_only- )+ af = pedalboard.io.AudioFile(audio_filename)assert not af@@ -829,14 +777,11 @@ def test_write_empty_file(extension: str, samplerate: float, num_channels: int):with pedalboard.io.AudioFile(stream) as af:assert af.samplerate == samplerateassert af.num_channels == num_channels- # The built-in JUCE MP3 reader (only used on Linux and Windows)- # reads zero-length MP3 files as having exactly one frame.- if "mp3" in extension and platform.system() != "Darwin":- assert af.frames <= MP3_FRAME_LENGTH_SAMPLES+ # The built-in JUCE MP3 reader reads zero-length MP3 files as having exactly one frame:+ assert af.frames <= MP3_FRAME_LENGTH_SAMPLES+ if af.frames > 0:contents = af.read(af.frames)np.testing.assert_allclose(np.zeros_like(contents), contents)- else:- assert af.frames == 0@pytest.mark.parametrize(@@ -1025,8 +970,7 @@ def test_file_not_created_if_constructor_error_thrown(tmp_path: pathlib.Path):assert not os.path.exists(filename)[email protected]("cross_platform_formats_only", [True, False])-def test_real_mp3_parsing_with_lyrics3(cross_platform_formats_only: bool):+def test_real_mp3_parsing_with_lyrics3():"""Lyrics3 is a non-standard extension to the MP3 format that appends lyric data after the lastMP3 frame. This data is not read by Pedalboard - but the MP3 parser used on Linux and Windows@@ -1034,9 +978,8 @@ def test_real_mp3_parsing_with_lyrics3(cross_platform_formats_only: bool):use a patched version of JUCE's MP3 parser to allow reading MP3 files that contain Lyrics3data."""- with pedalboard.io.ReadableAudioFile(- os.path.join(os.path.dirname(__file__), "audio", "correct", "bad_audio_file_lyrics3.mp3"),- cross_platform_formats_only=cross_platform_formats_only,+ with pedalboard.io.AudioFile(+ os.path.join(os.path.dirname(__file__), "audio", "correct", "bad_audio_file_lyrics3.mp3")) as f:assert f.frames >= 0assert f.read(f.frames).shape[1] == f.frames@@ -1081,7 +1024,7 @@ def test_22050Hz_mono_mp3(audio_filename: str, samplerate: float):File size estimation was broken for 22kHz mono MP3 files.This test should catch that kind of problem."""- af = pedalboard.io.ReadableAudioFile(audio_filename, cross_platform_formats_only=True)+ af = pedalboard.io.ReadableAudioFile(audio_filename)assert af.duration < 30.5assert af.samplerate == sampleratedata_read_all_at_once = af.read(af.frames)@@ -1121,7 +1064,7 @@ def test_mp3_at_all_samplerates(quality: str, samplerate: float, num_channels: iread_buf = io.BytesIO(buf.getvalue())- with pedalboard.io.ReadableAudioFile(read_buf, cross_platform_formats_only=True) as af:+ with pedalboard.io.ReadableAudioFile(read_buf) as af:# Allow for up to two MP3 frames of padding:assert af.frames <= (signal.shape[-1] + MP3_FRAME_LENGTH_SAMPLES * 2)assert af.frames >= signal.shape[-1]