π π A Python library for audio.
C audioaudio-processingaudio-productionaudio-researchaudio-unitaugmentationjucemachine-learningpybind11pythonvst3vst3-host
Remove stream functionality and added tests for file reading.
Peter Sobot2e3ca23fca54
diff --git a/pedalboard/io/AudioFile.h b/pedalboard/io/AudioFile.hindex e0eeddc..50382d0 100644--- a/pedalboard/io/AudioFile.h+++ b/pedalboard/io/AudioFile.h@@ -24,121 +24,58 @@#include <pybind11/pybind11.h>#include "../JuceHeader.h"-#include "./FileLikeWrapper.h"namespace py = pybind11;-// Returned by the Ogg Vorbis code if an error occurs:-// 2^32 - 131 ("OV_EINVAL")-long OGG_FORMAT_ERROR = 4294967165;-namespace Pedalboard {-/**- * A juce::AudioFile subclass that fetches its- * data from a provided Python file-like object.- */-class AudioFile {+class AudioFile : public std::enable_shared_from_this<AudioFile> {public:- static constexpr const int BUFFER_SIZE = 1024 * 16;-AudioFile(std::string filename) {- formatManager.registerBasicFormats();- juce::File file(filename);- reader.reset(formatManager.createReaderFor(file));- if (!reader) {- throw std::domain_error("Unable to open audio file: " + filename);- }- }-- AudioFile(std::unique_ptr<PythonInputStream> inputStream, std::string formatHint) {- if (!inputStream) {- throw std::domain_error("file-like must not be None");- }-- // There are a couple important edge cases to consider here:- // - To auto-detect the audio format, an input stream must be seekable- // - Some formats detect length by doing three commands in sequence:- // - setPosition(getTotalLength())- // - getPosition()- // - setPosition(0)- // TODO: Write a custom BufferedInputStream-like subclass that buffers:- // - the first ~10kB of the file- // - the previous ~10kB prior to the current read pointer- // - allows seeking to the start of the file and back to the pointer- if (inputStream->isSeekable() && formatHint.empty()) {- formatManager.registerBasicFormats();- reader.reset(formatManager.createReaderFor(std::move(inputStream)));- } else {- if (formatHint.empty()) {- // TODO: Try to identify the file type somehow- // TODO: Can we subclass InputStream to allow peeking at the first 4 bytes?- // urllib3.response.HTTPResponse provides `getheader("Content-Type")`- throw std::runtime_error("Passing a file-like requires a file format hint to be passed as the second argument.");- }-- if (formatHint.find("ogg") != std::string::npos) {- juce::OggVorbisAudioFormat format;- reader.reset(format.createReaderFor(inputStream.get(), false));- } else if (formatHint.find("mp3") != std::string::npos) {- juce::MP3AudioFormat format;- reader.reset(format.createReaderFor(inputStream.get(), false));- } else if (formatHint.find("wav") != std::string::npos) {- juce::WavAudioFormat format;- reader.reset(format.createReaderFor(inputStream.get(), false));- } else {- throw std::domain_error("Unknown format hint: expected one of 'ogg', 'mp3', or 'wav'.");- }-- if (reader) inputStream.release();- }--+ formatManager.registerBasicFormats();+ juce::File file(filename);+ reader.reset(formatManager.createReaderFor(file));if (!reader) {- throw std::domain_error("Unable to open audio file from stream.");+ throw std::domain_error("Unable to open audio file: " + filename);}-- raisePythonErrorIfNecessary();- }-- void raisePythonErrorIfNecessary() {- ((PythonInputStream *)reader->input)->raisePythonErrorIfNecessary();- }-- bool isSeekable() {- ((PythonInputStream *)reader->input)->isSeekable();}- double getSampleRate() {- raisePythonErrorIfNecessary();+ double getSampleRate() const {+ if (!reader)+ throw std::runtime_error("I/O operation on a closed file.");return reader->sampleRate;}- long getLengthInSamples() {- raisePythonErrorIfNecessary();-- if (reader->lengthInSamples < 0 || reader->lengthInSamples == OGG_FORMAT_ERROR) {- throw std::domain_error("Unknown number of samples available in file.");- }+ long getLengthInSamples() const {+ if (!reader)+ throw std::runtime_error("I/O operation on a closed file.");return reader->lengthInSamples;}- long getNumChannels() {- raisePythonErrorIfNecessary();+ long getNumChannels() const {+ if (!reader)+ throw std::runtime_error("I/O operation on a closed file.");return reader->numChannels;}py::array_t<float> read(long long numSamples) {- raisePythonErrorIfNecessary();-- if (numSamples == 0) throw std::domain_error("AudioFile will not read an entire file at once, due to the possibility that a file may be larger than available memory");+ if (numSamples == 0)+ throw std::domain_error(+ "AudioFile will not read an entire file at once, due to the "+ "possibility that a file may be larger than available memory. Please "+ "pass a number of frames to read (available from the 'frames' "+ "attribute).");const juce::ScopedLock scopedLock(objectLock);+ if (!reader)+ throw std::runtime_error("I/O operation on a closed file.");// Allocate a buffer to return of up to numSamples:int numChannels = reader->numChannels;- numSamples = std::min(numSamples, reader->lengthInSamples - currentPosition);- py::array_t<float> buffer = py::array_t<float>({(int) numChannels, (int)numSamples});+ numSamples =+ std::min(numSamples, reader->lengthInSamples - currentPosition);+ py::array_t<float> buffer =+ py::array_t<float>({(int)numChannels, (int)numSamples});py::buffer_info outputInfo = buffer.request();@@ -158,22 +95,35 @@ public:}void seek(long long targetPosition) {- if (!isSeekable()) throw std::runtime_error("Underlying stream is not seekable.");- raisePythonErrorIfNecessary();-const juce::ScopedLock scopedLock(objectLock);- if (targetPosition > reader->lengthInSamples) throw std::domain_error("Seek out of bounds");- if (targetPosition < 0) throw std::domain_error("Seek out of bounds");+ if (!reader)+ throw std::runtime_error("I/O operation on a closed file.");+ if (targetPosition > reader->lengthInSamples)+ throw std::domain_error("Seek out of bounds");+ if (targetPosition < 0)+ throw std::domain_error("Seek out of bounds");currentPosition = targetPosition;}long long tell() {- raisePythonErrorIfNecessary();-const juce::ScopedLock scopedLock(objectLock);+ if (!reader)+ throw std::runtime_error("I/O operation on a closed file.");return currentPosition;}+ void close() {+ const juce::ScopedLock scopedLock(objectLock);+ reader.reset();+ }++ std::shared_ptr<AudioFile> enter() { return shared_from_this(); }++ void exit(const py::object &type, const py::object &value,+ const py::object &traceback) {+ close();+ }+private:juce::AudioFormatManager formatManager;std::unique_ptr<juce::AudioFormatReader> reader = nullptr;@@ -182,24 +132,64 @@ private:int currentPosition = 0;};-inline void init_audiofile(py::module &m) {- py::class_<AudioFile>(+ py::class_<AudioFile, std::shared_ptr<AudioFile>>(m, "AudioFile",- "An audio file reader interface, with native support for Ogg Vorbis, MP3, Wave, FLAC, and AIFF files.")+ "An audio file reader interface, with native support for "+ "for Ogg Vorbis, MP3, WAV, FLAC, and AIFF files on all operating "+ "systems. On some platforms, the output").def(py::init([](std::string filename) {return std::make_unique<AudioFile>(filename);}),py::arg("filename"))- .def(py::init([](py::object fileLike, std::string formatHint) {- return std::make_unique<AudioFile>(std::make_unique<PythonInputStream>(fileLike), formatHint);- }),- py::arg("file_like"), py::arg("format_hint") = "")- .def("read", &AudioFile::read)- .def("seek", &AudioFile::seek)- .def("tell", &AudioFile::tell)- .def_property_readonly("samplerate", &AudioFile::getSampleRate)- .def_property_readonly("channels", &AudioFile::getNumChannels)- .def_property_readonly("frames", &AudioFile::getLengthInSamples);+ .def("read", &AudioFile::read, py::arg("num_frames") = 0,+ "Read the given number of frames (samples in each channel) from the "+ "audio file at the current position.")+ .def("seek", &AudioFile::seek, py::arg("position"),+ "Seek the file to the provided location in frames.")+ .def("tell", &AudioFile::tell,+ "Fetch the position in the audio file, in frames.")+ .def("close", &AudioFile::close,+ "Close the file, rendering this object unusable.")+ .def("__enter__", &AudioFile::enter)+ .def("__exit__", &AudioFile::exit)+ .def_property_readonly("samplerate", &AudioFile::getSampleRate,+ "Fetch the sample rate of the file in samples "+ "(per channel) per second (Hz).")+ .def_property_readonly("channels", &AudioFile::getNumChannels,+ "Fetch the number of channels in the file.")+ .def_property_readonly("frames", &AudioFile::getLengthInSamples,+ "Fetch the total number of frames (samples per "+ "channel) in the file.")+ .def_property_readonly_static(+ "supported_formats", [](py::object /* cls */) {+ juce::AudioFormatManager manager;+ manager.registerBasicFormats();++ 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);++ 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;+ });+++ return output;+ });}} // namespace Pedalboard\ No newline at end of filediff --git a/pedalboard/io/FileLikeWrapper.h b/pedalboard/io/FileLikeWrapper.hdeleted file mode 100644index 72d9cb5..0000000--- a/pedalboard/io/FileLikeWrapper.h+++ /dev/null@@ -1,175 +0,0 @@-/*- * 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 <mutex>-#include <optional>--namespace py = pybind11;--#include "../JuceHeader.h"--namespace Pedalboard {--/**- * A juce::InputStream subclass that fetches its- * data from a provided Python file-like object.- */-class PythonInputStream : public juce::InputStream {-public:-- PythonInputStream(py::object fileLike): fileLike(fileLike) {- if (!py::hasattr(fileLike, "read") || !py::hasattr(fileLike, "seek") || !py::hasattr(fileLike, "tell") || !py::hasattr(fileLike, "seekable")) {- throw py::type_error("Expected a file-like object (with read, seek, seekable, and tell methods).");- }- }-- bool isSeekable() {- try {- return fileLike.attr("seekable")().cast<bool>();- } catch (py::error_already_set) {- printf("[PythonInputStream] Error raised\n");- pythonErrorRaised = true;- return false;- }- }-- juce::int64 getTotalLength() {- py::gil_scoped_acquire acquire;-- // TODO: Try reading a couple of Python properties that may contain the total length:- // urllib3.response.HTTPResponse provides `length_remaining`-- try {- if (!fileLike.attr("seekable")().cast<bool>()) {- printf("[PythonInputStream] getTotalLength => -1\n");- return -1;- }- } catch (py::error_already_set) {- printf("[PythonInputStream] Error raised\n");- pythonErrorRaised = true;- return 0;- }-- if (totalLength == -1) {- try {- juce::int64 pos = fileLike.attr("tell")().cast<juce::int64>();- fileLike.attr("seek")(0, 2);- totalLength = fileLike.attr("tell")().cast<juce::int64>();- fileLike.attr("seek")(pos, 0);- } catch (py::error_already_set) {- pythonErrorRaised = true;- return -1;- }- }-- printf("[PythonInputStream] getTotalLength => %d\n", totalLength);- return totalLength;- }-- int read (void* buffer, int bytesToRead)- {- // The buffer should never be null, and a negative size is probably a- // sign that something is broken!- jassert (buffer != nullptr && bytesToRead >= 0);-- py::bytes result;- {- py::gil_scoped_acquire acquire;- try {- result = fileLike.attr("read")(bytesToRead).cast<py::bytes>();- } catch (py::error_already_set) {- printf("[PythonInputStream] Error raised\n");- pythonErrorRaised = true;- return 0;- }- }-- std::string resultAsString = result;- std::memcpy((char *)buffer, (char *)resultAsString.data(), resultAsString.size());-- int bytesCopied = resultAsString.size();- printf("[PythonInputStream] read(%p, %d) => %d\n", buffer, bytesToRead, bytesCopied);-- lastReadWasSmallerThanExpected = bytesToRead > bytesCopied;- return bytesCopied;- }-- bool isExhausted()- {- if (lastReadWasSmallerThanExpected) {- return true;- }-- try {- py::gil_scoped_acquire acquire;- return fileLike.attr("tell")().cast<juce::int64>() == getTotalLength();- } catch (py::error_already_set) {- printf("[PythonInputStream] Error raised\n");- pythonErrorRaised = true;- return true;- }- }-- juce::int64 getPosition() {- printf("[PythonInputStream] getPosition() => %d\n", fileLike.attr("tell")().cast<juce::int64>());- try {- py::gil_scoped_acquire acquire;- return fileLike.attr("tell")().cast<juce::int64>();- } catch (py::error_already_set) {- printf("[PythonInputStream] Error raised\n");- pythonErrorRaised = true;- return 0;- }- }-- bool setPosition (juce::int64 pos)- {- printf("[PythonInputStream] setPosition(%d)\n", pos);- try {- py::gil_scoped_acquire acquire;-- if (fileLike.attr("seekable")().cast<bool>()) {- fileLike.attr("seek")(pos);- }-- return fileLike.attr("tell")().cast<juce::int64>() == pos;- } catch (py::error_already_set) {- printf("[PythonInputStream] Error raised\n");- pythonErrorRaised = true;- return false;- }- }-- void raisePythonErrorIfNecessary() {- py::gil_scoped_acquire acquire;- if (pythonErrorRaised) throw py::error_already_set();- }--private:- py::object fileLike;- juce::int64 totalLength = -1;- bool lastReadWasSmallerThanExpected = false;-- // the juce::InputStream interface is not exception-safe, so we have to- // change the behaviour of this subclass if an exception gets thrown,- // then throw the exception ourselves when we have the opportunity.- bool pythonErrorRaised = false;-};--} // namespace Pedalboard\ No newline at end of filediff --git a/tests/audio/correct/mono_sine_at_44100.aiff b/tests/audio/correct/mono_sine_at_44100.aiffnew file mode 100644index 0000000..f627182Binary files /dev/null and b/tests/audio/correct/mono_sine_at_44100.aiff differdiff --git a/tests/audio/correct/mono_sine_at_44100Hz.flac b/tests/audio/correct/mono_sine_at_44100Hz.flacnew file mode 100644index 0000000..987f566Binary files /dev/null and b/tests/audio/correct/mono_sine_at_44100Hz.flac differdiff --git a/tests/audio/correct/mono_sine_at_44100Hz.mp3 b/tests/audio/correct/mono_sine_at_44100Hz.mp3new file mode 100644index 0000000..f23ccaaBinary files /dev/null and b/tests/audio/correct/mono_sine_at_44100Hz.mp3 differdiff --git a/tests/audio/correct/mono_sine_at_44100Hz.ogg b/tests/audio/correct/mono_sine_at_44100Hz.oggnew file mode 100644index 0000000..c63b9a9Binary files /dev/null and b/tests/audio/correct/mono_sine_at_44100Hz.ogg differdiff --git a/tests/audio/correct/mono_sine_at_44100Hz.wav b/tests/audio/correct/mono_sine_at_44100Hz.wavnew file mode 100644index 0000000..794ecc2Binary files /dev/null and b/tests/audio/correct/mono_sine_at_44100Hz.wav differdiff --git a/tests/audio/correct/mono_sine_at_48000.aiff b/tests/audio/correct/mono_sine_at_48000.aiffnew file mode 100644index 0000000..7dd0122Binary files /dev/null and b/tests/audio/correct/mono_sine_at_48000.aiff differdiff --git a/tests/audio/correct/mono_sine_at_48000Hz.flac b/tests/audio/correct/mono_sine_at_48000Hz.flacnew file mode 100644index 0000000..ad9478aBinary files /dev/null and b/tests/audio/correct/mono_sine_at_48000Hz.flac differdiff --git a/tests/audio/correct/mono_sine_at_48000Hz.mp3 b/tests/audio/correct/mono_sine_at_48000Hz.mp3new file mode 100644index 0000000..fb61440Binary files /dev/null and b/tests/audio/correct/mono_sine_at_48000Hz.mp3 differdiff --git a/tests/audio/correct/mono_sine_at_48000Hz.ogg b/tests/audio/correct/mono_sine_at_48000Hz.oggnew file mode 100644index 0000000..c63993cBinary files /dev/null and b/tests/audio/correct/mono_sine_at_48000Hz.ogg differdiff --git a/tests/audio/correct/mono_sine_at_48000Hz.wav b/tests/audio/correct/mono_sine_at_48000Hz.wavnew file mode 100644index 0000000..26cd903Binary files /dev/null and b/tests/audio/correct/mono_sine_at_48000Hz.wav differdiff --git a/tests/audio/incorrect/mono_sine_at_44100.m4a b/tests/audio/incorrect/mono_sine_at_44100.m4anew file mode 100644index 0000000..3d8f641Binary files /dev/null and b/tests/audio/incorrect/mono_sine_at_44100.m4a differdiff --git a/tests/audio/incorrect/mono_sine_at_48000.m4a b/tests/audio/incorrect/mono_sine_at_48000.m4anew file mode 100644index 0000000..85dc411Binary files /dev/null and b/tests/audio/incorrect/mono_sine_at_48000.m4a differdiff --git a/tests/test_io_read.py b/tests/test_io_read.pynew file mode 100644index 0000000..d557522--- /dev/null+++ b/tests/test_io_read.py@@ -0,0 +1,82 @@+#! /usr/bin/env python+#+# 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.+++import os+import glob+import pytest+import pedalboard++TEST_AUDIO_FILES = {+ 44100: glob.glob(os.path.join(os.path.dirname(__file__), "audio", "correct", "*44100*")),+ 48000: glob.glob(os.path.join(os.path.dirname(__file__), "audio", "correct", "*48000*")),+}++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.AudioFile.supported_formats)+]++[email protected]("extension", [".mp3", ".wav", ".ogg", ".flac"])+def test_basic_formats_available_on_all_platforms(extension: str):+ assert extension in pedalboard.io.AudioFile.supported_formats++[email protected]("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)+def test_basic_load(audio_filename: str, samplerate: float):+ af = pedalboard.io.AudioFile(audio_filename)+ assert af.samplerate == samplerate+ assert af.channels == 1+ assert af.frames == int(samplerate * 5)++ samples = af.read(af.frames)+ assert samples.shape == (1, int(samplerate * 5))++ # File should no longer be useful:+ af.read(1).nbytes == 0++[email protected]("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)+def test_use_as_context_manager(audio_filename: str, samplerate: float):+ with pedalboard.io.AudioFile(audio_filename) as af:+ assert af.samplerate == samplerate+ assert af.channels == 1+ assert af.frames == int(samplerate * 5)++ samples = af.read(af.frames)+ assert samples.shape == (1, int(samplerate * 5))++ # File should no longer be useful:+ af.read(1).nbytes == 0++ with pytest.raises(RuntimeError):+ af.channels++ with pytest.raises(RuntimeError):+ af.read(1)+++def test_fails_gracefully():+ with pytest.raises(ValueError):+ pedalboard.io.AudioFile(__file__)++ with pytest.raises(ValueError):+ with pedalboard.io.AudioFile(__file__) as f:+ pass