Skip to content

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

Add AudioFile with buggy streaming support.

Peter Sobot3b776c2d31cd
diff --git a/pedalboard/io/AudioFile.h b/pedalboard/io/AudioFile.h
new file mode 100644
index 0000000..e0eeddc
--- /dev/null
+++ b/pedalboard/io/AudioFile.h
@@ -0,0 +1,205 @@
+/*
+ * 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 <mutex>
+#include <optional>
+
+#include <pybind11/numpy.h>
+#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 {
+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();
+ }
+
+
+ if (!reader) {
+ throw std::domain_error("Unable to open audio file from stream.");
+ }
+
+ raisePythonErrorIfNecessary();
+ }
+
+ void raisePythonErrorIfNecessary() {
+ ((PythonInputStream *)reader->input)->raisePythonErrorIfNecessary();
+ }
+
+ bool isSeekable() {
+ ((PythonInputStream *)reader->input)->isSeekable();
+ }
+
+ double getSampleRate() {
+ raisePythonErrorIfNecessary();
+ 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.");
+ }
+ return reader->lengthInSamples;
+ }
+
+ long getNumChannels() {
+ raisePythonErrorIfNecessary();
+ 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");
+
+ const juce::ScopedLock scopedLock(objectLock);
+
+ // 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});
+
+ py::buffer_info outputInfo = buffer.request();
+
+ {
+ py::gil_scoped_release release;
+
+ float *readPointers[numChannels];
+ for (int c = 0; c < numChannels; c++) {
+ readPointers[c] = ((float *)outputInfo.ptr) + (numSamples * c);
+ }
+
+ reader->read(readPointers, numChannels, currentPosition, numSamples);
+ }
+
+ currentPosition += numSamples;
+ return buffer;
+ }
+
+ 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");
+ currentPosition = targetPosition;
+ }
+
+ long long tell() {
+ raisePythonErrorIfNecessary();
+
+ const juce::ScopedLock scopedLock(objectLock);
+ return currentPosition;
+ }
+
+private:
+ juce::AudioFormatManager formatManager;
+ std::unique_ptr<juce::AudioFormatReader> reader = nullptr;
+ juce::CriticalSection objectLock;
+
+ int currentPosition = 0;
+};
+
+
+inline void init_audiofile(py::module &m) {
+ py::class_<AudioFile>(
+ m, "AudioFile",
+ "An audio file reader interface, with native support for Ogg Vorbis, MP3, Wave, FLAC, and AIFF files.")
+ .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);
+}
+} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/io/FileLikeWrapper.h b/pedalboard/io/FileLikeWrapper.h
new file mode 100644
index 0000000..72d9cb5
--- /dev/null
+++ b/pedalboard/io/FileLikeWrapper.h
@@ -0,0 +1,175 @@
+/*
+ * 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 file
diff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cpp
index 26ba373..f275733 100644
--- a/pedalboard/python_bindings.cpp
+++ b/pedalboard/python_bindings.cpp
@@ -61,6 +61,8 @@ namespace py = pybind11;
#include "plugins/PitchShift.h"
#include "plugins/Reverb.h"
+#include "io/AudioFile.h"
+
using namespace Pedalboard;
PYBIND11_MODULE(pedalboard_native, m) {
@@ -186,4 +188,8 @@ PYBIND11_MODULE(pedalboard_native, m) {
init_resample_with_latency(internal);
init_fixed_size_block_test_plugin(internal);
init_force_mono_test_plugin(internal);
+
+ // I/O helpers and utilities:
+ py::module io = m.def_submodule("io");
+ init_audiofile(io);
};
diff --git a/setup.py b/setup.py
index c43ecae..0b5d243 100644
--- a/setup.py
+++ b/setup.py
@@ -72,6 +72,7 @@ ALL_CPPFLAGS.extend(
"-DJUCE_DISABLE_JUCE_VERSION_PRINTING=1",
"-DJUCE_WEB_BROWSER=0",
"-DJUCE_USE_CURL=0",
+ "-DJUCE_USE_MP3AUDIOFORMAT=1",
# "-DJUCE_USE_FREETYPE=0",
"-DJUCE_MODAL_LOOPS_PERMITTED=1",
]