Skip to content

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

Add ReadableAudioFile and WriteableAudioFile subclasses.

Peter Sobot6c0938c519f2
diff --git a/README.md b/README.md
index 953aef3..a50b903 100644
--- a/README.md
+++ b/README.md
@@ -27,11 +27,16 @@ Internally at Spotify, `pedalboard` is used for [data augmentation](https://en.w
- Quality reduction: `Resample`, `Bitcrush`
- 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
+ - 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 cores
- No need to use `multiprocessing`!
- Even when only using one thread:
- Processes audio up to **300x** faster than [pySoX](https://github.com/rabitt/pysox) for single transforms, and 2-5x faster<sup>[1](https://github.com/iCorv/pedalboard_with_tfdata)</sup> than [SoxBindings](https://github.com/pseeth/soxbindings)
+ - Reads audio files up to **20x** faster than [`librosa.load`](https://librosa.org/doc/main/generated/librosa.load.html)
- Tested compatibility with TensorFlow - can be used in `tf.data` pipelines!
## Installation
@@ -88,30 +93,35 @@ to the next in an undesired fashion, try:
### Quick Start
```python
-import soundfile as sf
from pedalboard import Pedalboard, Chorus, Reverb
+from pedalboard.io import AudioFile
-# Read in an audio file:
-audio, sample_rate = sf.read('some-file.wav')
+# Read in a whole audio file:
+with AudioFile('some-file.wav', 'r') as f:
+ audio = f.read(f.frames)
+ samplerate = f.samplerate
# Make a Pedalboard object, containing multiple plugins:
board = Pedalboard([Chorus(), Reverb(room_size=0.25)])
# Run the audio through this pedalboard!
-effected = board(audio, sample_rate)
+effected = board(audio, samplerate)
# Write the audio back as a wav file:
-sf.write('./processed-output.wav', effected, sample_rate)
+with AudioFile('processed-output.wav', 'w', samplerate) as f:
+ f.write(effected)
```
### Making a guitar-style pedalboard
```python
-import soundfile as sf
# Don't do import *! (It just makes this example smaller)
from pedalboard import *
+from pedalboard.io import AudioFile
-audio, sample_rate = sf.read('./guitar-input.wav')
+with AudioFile('guitar-input.wav', 'r') as f:
+ audio = f.read(f.frames)
+ samplerate = f.samplerate
# Make a pretty interesting sounding guitar pedalboard:
board = Pedalboard([
@@ -133,17 +143,18 @@ board.append(Limiter())
board[0].threshold_db = -40
# Run the audio through this pedalboard!
-effected = board(audio, sample_rate)
+effected = board(audio, samplerate)
# Write the audio back as a wav file:
-sf.write('./guitar-output.wav', effected, sample_rate)
+with AudioFile('processed-output.wav', 'w', samplerate) as f:
+ f.write(effected)
```
### Using VST3ยฎ or Audio Unit plugins
```python
-import soundfile as sf
from pedalboard import Pedalboard, Reverb, load_plugin
+from pedalboard.io import AudioFile
# Load a VST3 or Audio Unit plugin from a known path on disk:
vst = load_plugin("./VSTs/RoughRider3.vst3")
@@ -160,13 +171,15 @@ print(vst.parameters.keys())
vst.ratio = 15
# Use this VST to process some audio:
-audio, sample_rate = sf.read('some-file.wav')
-effected = vst(audio, sample_rate)
+with AudioFile('some-file.wav', 'r') as f:
+ audio = f.read(f.frames)
+ samplerate = f.samplerate
+effected = vst(audio, samplerate)
# ...or put this VST into a chain with other plugins:
board = Pedalboard([vst, Reverb()])
# ...and run that pedalboard with the same VST instance!
-effected = board(audio, sample_rate)
+effected = board(audio, samplerate)
```
### Creating parallel effects chains
@@ -177,7 +190,6 @@ objects are themselves `Plugin` objects, so you can nest them
as much as you like:
```python
-import soundfile as sf
from pedalboard import Pedalboard, Compressor, Delay, Distortion, Gain, PitchShift, Reverb, Mix
passthrough = Gain(gain_db=0)
diff --git a/pedalboard/BufferUtils.h b/pedalboard/BufferUtils.h
new file mode 100644
index 0000000..d5f2e40
--- /dev/null
+++ b/pedalboard/BufferUtils.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 "JuceHeader.h"
+
+#include <pybind11/numpy.h>
+#include <pybind11/pybind11.h>
+
+namespace Pedalboard {
+enum class ChannelLayout {
+ Interleaved,
+ NotInterleaved,
+};
+
+template <typename T>
+ChannelLayout
+detectChannelLayout(const py::array_t<T, py::array::c_style> inputArray) {
+ py::buffer_info inputInfo = inputArray.request();
+
+ if (inputInfo.ndim == 1) {
+ return ChannelLayout::NotInterleaved;
+ } else if (inputInfo.ndim == 2) {
+ // Try to auto-detect the channel layout from the shape
+ if (inputInfo.shape[1] < inputInfo.shape[0]) {
+ return ChannelLayout::Interleaved;
+ } else if (inputInfo.shape[0] < inputInfo.shape[1]) {
+ return ChannelLayout::NotInterleaved;
+ } else {
+ throw std::runtime_error(
+ "Unable to determine channel layout from shape!");
+ }
+ } else {
+ throw std::runtime_error("Number of input dimensions must be 1 or 2 (got " +
+ std::to_string(inputInfo.ndim) + ").");
+ }
+}
+
+template <typename T>
+juce::AudioBuffer<T>
+copyPyArrayIntoJuceBuffer(const py::array_t<T, py::array::c_style> inputArray) {
+ // Numpy/Librosa convention is (num_samples, num_channels)
+ py::buffer_info inputInfo = inputArray.request();
+
+ unsigned int numChannels = 0;
+ unsigned int numSamples = 0;
+ ChannelLayout inputChannelLayout = detectChannelLayout(inputArray);
+
+ if (inputInfo.ndim == 1) {
+ numSamples = inputInfo.shape[0];
+ numChannels = 1;
+ } else if (inputInfo.ndim == 2) {
+ // Try to auto-detect the channel layout from the shape
+ if (inputInfo.shape[1] < inputInfo.shape[0]) {
+ numSamples = inputInfo.shape[0];
+ numChannels = inputInfo.shape[1];
+ } else if (inputInfo.shape[0] < inputInfo.shape[1]) {
+ numSamples = inputInfo.shape[1];
+ numChannels = inputInfo.shape[0];
+ } else {
+ throw std::runtime_error("Unable to determine shape of audio input!");
+ }
+ } else {
+ throw std::runtime_error("Number of input dimensions must be 1 or 2 (got " +
+ std::to_string(inputInfo.ndim) + ").");
+ }
+
+ if (numChannels == 0) {
+ throw std::runtime_error("No channels passed!");
+ } else if (numChannels > 2) {
+ throw std::runtime_error("More than two channels received!");
+ }
+
+ juce::AudioBuffer<T> ioBuffer(numChannels, numSamples);
+
+ // Depending on the input channel layout, we need to copy data
+ // differently. This loop is duplicated here to move the if statement
+ // outside of the tight loop, as we don't need to re-check that the input
+ // channel is still the same on every iteration of the loop.
+ switch (inputChannelLayout) {
+ case ChannelLayout::Interleaved:
+ for (unsigned int i = 0; i < numChannels; i++) {
+ T *channelBuffer = ioBuffer.getWritePointer(i);
+ // We're de-interleaving the data here, so we can't use copyFrom.
+ for (unsigned int j = 0; j < numSamples; j++) {
+ channelBuffer[j] = static_cast<T *>(inputInfo.ptr)[j * numChannels + i];
+ }
+ }
+ break;
+ case ChannelLayout::NotInterleaved:
+ for (unsigned int i = 0; i < numChannels; i++) {
+ ioBuffer.copyFrom(
+ i, 0, static_cast<T *>(inputInfo.ptr) + (numSamples * i), numSamples);
+ }
+ break;
+ default:
+ throw std::runtime_error("Internal error: got unexpected channel layout.");
+ }
+
+ return ioBuffer;
+}
+
+template <typename T>
+py::array_t<T> copyJuceBufferIntoPyArray(const juce::AudioBuffer<T> juceBuffer,
+ ChannelLayout channelLayout,
+ int offsetSamples, int ndim = 2) {
+ unsigned int numChannels = juceBuffer.getNumChannels();
+ unsigned int numSamples = juceBuffer.getNumSamples();
+ unsigned int outputSampleCount =
+ std::max((int)numSamples - (int)offsetSamples, 0);
+
+ // TODO: Avoid the need to copy here if offsetSamples is 0!
+ py::array_t<T> outputArray;
+ if (ndim == 2) {
+ switch (channelLayout) {
+ case ChannelLayout::Interleaved:
+ outputArray = py::array_t<T>({outputSampleCount, numChannels});
+ break;
+ case ChannelLayout::NotInterleaved:
+ outputArray = py::array_t<T>({numChannels, outputSampleCount});
+ break;
+ default:
+ throw std::runtime_error(
+ "Internal error: got unexpected channel layout.");
+ }
+ } else {
+ outputArray = py::array_t<T>(outputSampleCount);
+ }
+
+ py::buffer_info outputInfo = outputArray.request();
+
+ // Depending on the input channel layout, we need to copy data
+ // differently. This loop is duplicated here to move the if statement
+ // outside of the tight loop, as we don't need to re-check that the input
+ // channel is still the same on every iteration of the loop.
+ T *outputBasePointer = static_cast<T *>(outputInfo.ptr);
+
+ switch (channelLayout) {
+ case ChannelLayout::Interleaved:
+ for (unsigned int i = 0; i < numChannels; i++) {
+ const T *channelBuffer = juceBuffer.getReadPointer(i, offsetSamples);
+ // We're interleaving the data here, so we can't use copyFrom.
+ for (unsigned int j = 0; j < outputSampleCount; j++) {
+ outputBasePointer[j * numChannels + i] = channelBuffer[j];
+ }
+ }
+ break;
+ case ChannelLayout::NotInterleaved:
+ for (unsigned int i = 0; i < numChannels; i++) {
+ const T *channelBuffer = juceBuffer.getReadPointer(i, offsetSamples);
+ std::copy(channelBuffer, channelBuffer + outputSampleCount,
+ &outputBasePointer[outputSampleCount * i]);
+ }
+ break;
+ default:
+ throw std::runtime_error("Internal error: got unexpected channel layout.");
+ }
+
+ return outputArray;
+}
+} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/io/AudioFile.h b/pedalboard/io/AudioFile.h
index e628a15..a660c1d 100644
--- a/pedalboard/io/AudioFile.h
+++ b/pedalboard/io/AudioFile.h
@@ -23,21 +23,38 @@
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
+#include "../BufferUtils.h"
#include "../JuceHeader.h"
namespace py = pybind11;
namespace Pedalboard {
-class AudioFile : public std::enable_shared_from_this<AudioFile> {
+class AudioFile {};
+
+class ReadableAudioFile
+ : public AudioFile,
+ public std::enable_shared_from_this<ReadableAudioFile> {
public:
- AudioFile(std::string filename) {
+ ReadableAudioFile(std::string filename) : filename(filename) {
formatManager.registerBasicFormats();
juce::File file(filename);
+
+ if (!file.existsAsFile()) {
+ throw std::domain_error(
+ "Failed to open audio file: file does not exist: " + filename);
+ }
+
+ // createReaderFor(juce::File) is fast, as it only looks at file extension:
reader.reset(formatManager.createReaderFor(file));
if (!reader) {
- throw std::domain_error("Unable to open audio file: " + filename);
+ // This is slower but more thorough:
+ reader.reset(formatManager.createReaderFor(file.createInputStream()));
}
+
+ if (!reader)
+ throw std::domain_error("Unable to open audio file for reading: " +
+ filename);
}
double getSampleRate() const {
@@ -61,7 +78,7 @@ public:
py::array_t<float> read(long long numSamples) {
if (numSamples == 0)
throw std::domain_error(
- "AudioFile will not read an entire file at once, due to the "
+ "ReadableAudioFile 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).");
@@ -99,13 +116,15 @@ public:
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
if (targetPosition > reader->lengthInSamples)
- throw std::domain_error("Cannot seek beyond end of file (" + std::to_string(reader->lengthInSamples) + " frames).");
+ throw std::domain_error("Cannot seek beyond end of file (" +
+ std::to_string(reader->lengthInSamples) +
+ " frames).");
if (targetPosition < 0)
throw std::domain_error("Cannot seek before start of file.");
currentPosition = targetPosition;
}
- long long tell() {
+ long long tell() const {
const juce::ScopedLock scopedLock(objectLock);
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
@@ -117,19 +136,22 @@ public:
reader.reset();
}
- bool isClosed() {
+ bool isClosed() const {
const juce::ScopedLock scopedLock(objectLock);
- return reader == nullptr;
+ return !reader;
}
- bool isSeekable() {
+ bool isSeekable() const {
const juce::ScopedLock scopedLock(objectLock);
- // At the moment, AudioFile instances are always seekable, as they're backed by files.
+ // At the moment, ReadableAudioFile instances are always seekable, as
+ // they're backed by files.
return !isClosed();
}
- std::shared_ptr<AudioFile> enter() { return shared_from_this(); }
+ std::string getFilename() const { return filename; }
+
+ std::shared_ptr<ReadableAudioFile> enter() { return shared_from_this(); }
void exit(const py::object &type, const py::object &value,
const py::object &traceback) {
@@ -138,76 +160,485 @@ public:
private:
juce::AudioFormatManager formatManager;
- std::unique_ptr<juce::AudioFormatReader> reader = nullptr;
+ std::string filename;
+ std::unique_ptr<juce::AudioFormatReader> reader;
juce::CriticalSection objectLock;
int currentPosition = 0;
+}; // namespace Pedalboard
+
+bool isInteger(double value) {
+ double intpart;
+ return modf(value, &intpart) == 0.0;
+}
+
+class WriteableAudioFile
+ : public AudioFile,
+ public std::enable_shared_from_this<WriteableAudioFile> {
+public:
+ WriteableAudioFile(std::string filename, double writeSampleRate,
+ int numChannels = 1, int bitsPerSample = 16,
+ int qualityOptionIndex = 0)
+ : filename(filename) {
+ pybind11::gil_scoped_release release;
+
+ if (!isInteger(writeSampleRate)) {
+ throw std::domain_error(
+ "Opening an audio file for writing requires an integer sample rate.");
+ }
+
+ if (writeSampleRate == 0) {
+ throw std::domain_error(
+ "Opening an audio file for writing requires a non-zero sample rate.");
+ }
+
+ if (numChannels == 0) {
+ throw py::type_error("Opening an audio file for writing requires a "
+ "non-zero num_channels.");
+ }
+
+ formatManager.registerBasicFormats();
+ juce::File file(filename);
+
+ std::unique_ptr<juce::FileOutputStream> outputStream =
+ std::make_unique<juce::FileOutputStream>(file);
+ if (!outputStream->openedOk()) {
+ throw std::domain_error("Unable to open audio file for writing: " +
+ filename);
+ }
+
+ outputStream->setPosition(0);
+ outputStream->truncate();
+
+ juce::AudioFormat *format =
+ formatManager.findFormatForFileExtension(file.getFileExtension());
+
+ if (!format) {
+ if (file.getFileExtension().isEmpty()) {
+ throw std::domain_error("No file extension provided - cannot detect "
+ "audio format to write with for file path: " +
+ filename);
+ }
+
+ throw std::domain_error(
+ "Unable to detect audio format for file extension: " +
+ file.getFileExtension().toStdString());
+ }
+
+ juce::StringPairArray emptyMetadata;
+ writer.reset(format->createWriterFor(outputStream.get(), writeSampleRate,
+ numChannels, bitsPerSample,
+ emptyMetadata, qualityOptionIndex));
+ if (!writer) {
+ // Check common errors first:
+ juce::Array<int> possibleSampleRates = format->getPossibleSampleRates();
+
+ if (possibleSampleRates.isEmpty()) {
+ throw std::domain_error(
+ file.getFileExtension().toStdString() +
+ " audio files are not writable with Pedalboard.");
+ }
+
+ if (!possibleSampleRates.contains((int)writeSampleRate)) {
+ std::ostringstream sampleRateString;
+ for (int i = 0; i < possibleSampleRates.size(); i++) {
+ sampleRateString << possibleSampleRates[i];
+ if (i < possibleSampleRates.size() - 1)
+ sampleRateString << ", ";
+ }
+ throw std::domain_error(
+ format->getFormatName().toStdString() +
+ " audio files do not support the provided sample rate of " +
+ std::to_string(writeSampleRate) +
+ "Hz. Supported sample rates: " + sampleRateString.str());
+ }
+
+ throw std::domain_error("Unable to create audio file writer: " +
+ filename);
+ } else {
+ outputStream.release();
+ }
+ }
+
+ // TODO: Support int16, int32, etc
+ void write(py::array_t<float, py::array::c_style> inputArray) {
+ const juce::ScopedLock scopedLock(objectLock);
+
+ if (!writer)
+ throw std::runtime_error("I/O operation on a closed file.");
+
+ // Numpy/Librosa convention is (num_samples, num_channels)
+ py::buffer_info inputInfo = inputArray.request();
+
+ unsigned int numChannels = 0;
+ unsigned int numSamples = 0;
+ ChannelLayout inputChannelLayout = detectChannelLayout(inputArray);
+
+ // Release the GIL when we do the writing, after we
+ // already have a reference to the input array:
+ pybind11::gil_scoped_release release;
+
+ if (inputInfo.ndim == 1) {
+ numSamples = inputInfo.shape[0];
+ numChannels = 1;
+ } else if (inputInfo.ndim == 2) {
+ // Try to auto-detect the channel layout from the shape
+ if (inputInfo.shape[0] == getNumChannels() &&
+ inputInfo.shape[1] == getNumChannels()) {
+ throw std::runtime_error(
+ "Unable to determine shape of audio input! Both dimensions have "
+ "the same shape. Expected " +
+ std::to_string(getNumChannels()) +
+ "-channel audio, with one dimension larger than the other.");
+ } else if (inputInfo.shape[1] == getNumChannels()) {
+ numSamples = inputInfo.shape[0];
+ numChannels = inputInfo.shape[1];
+ } else if (inputInfo.shape[0] == getNumChannels()) {
+ numSamples = inputInfo.shape[1];
+ numChannels = inputInfo.shape[0];
+ } else {
+ throw std::runtime_error(
+ "Unable to determine shape of audio input! Expected " +
+ std::to_string(getNumChannels()) + "-channel audio.");
+ }
+ } else {
+ throw std::runtime_error(
+ "Number of input dimensions must be 1 or 2 (got " +
+ std::to_string(inputInfo.ndim) + ").");
+ }
+
+ if (numChannels == 0) {
+ // No work to do.
+ return;
+ } else if (numChannels != getNumChannels()) {
+ throw std::runtime_error(
+ "WritableAudioFile was opened with num_channels=" +
+ std::to_string(getNumChannels()) +
+ ", but was passed an array containing " +
+ std::to_string(numChannels) + "-channel audio!");
+ }
+
+ // Depending on the input channel layout, we need to copy data
+ // differently. This loop is duplicated here to move the if statement
+ // outside of the tight loop, as we don't need to re-check that the input
+ // channel is still the same on every iteration of the loop.
+ switch (inputChannelLayout) {
+ case ChannelLayout::Interleaved: {
+ // Use a temporary buffer to chunk the audio input
+ // and pass it into the writer, chunk by chunk, rather
+ // than de-interleaving the entire buffer at once:
+ deinterleaveBuffers.resize(numChannels);
+
+ float **channelPointers = (float **)alloca(numChannels * sizeof(float *));
+ for (int startSample = 0; startSample < numSamples;
+ startSample += DEINTERLEAVE_BUFFER_SIZE_FRAMES) {
+ int samplesToWrite =
+ std::min(numSamples - startSample, DEINTERLEAVE_BUFFER_SIZE_FRAMES);
+
+ for (int c = 0; c < numChannels; c++) {
+ deinterleaveBuffers[c].resize(samplesToWrite);
+ channelPointers[c] = deinterleaveBuffers[c].data();
+
+ // We're de-interleaving the data here, so we can't use copyFrom.
+ for (unsigned int i = 0; i < samplesToWrite; i++) {
+ deinterleaveBuffers[c][i] = ((
+ float *)(inputInfo.ptr))[((i + startSample) * numChannels) + c];
+ }
+ }
+
+ if (!writer->writeFromFloatArrays(channelPointers, numChannels,
+ samplesToWrite)) {
+ throw std::runtime_error("Unable to write data to audio file.");
+ }
+ }
+
+ break;
+ }
+ case ChannelLayout::NotInterleaved: {
+ // We can just pass all the data to writeFromFloatArrays:
+ float **channelPointers = (float **)alloca(numChannels * sizeof(float *));
+ for (int c = 0; c < numChannels; c++) {
+ channelPointers[c] = ((float *)inputInfo.ptr) + (numSamples * c);
+ }
+ if (!writer->writeFromFloatArrays(channelPointers, numChannels,
+ numSamples)) {
+ throw std::runtime_error("Unable to write data to audio file.");
+ }
+ break;
+ }
+ default:
+ throw std::runtime_error(
+ "Internal error: got unexpected channel layout.");
+ }
+
+ framesWritten += numSamples;
+ }
+
+ void flush() {
+ if (!writer)
+ throw std::runtime_error("I/O operation on a closed file.");
+ const juce::ScopedLock scopedLock(objectLock);
+ pybind11::gil_scoped_release release;
+
+ if (!writer->flush()) {
+ throw std::runtime_error(
+ "Unable to flush audio file; is the underlying file seekable?");
+ }
+ }
+
+ void close() {
+ if (!writer)
+ throw std::runtime_error("Cannot close closed file.");
+ const juce::ScopedLock scopedLock(objectLock);
+ writer.reset();
+ }
+
+ bool isClosed() const {
+ const juce::ScopedLock scopedLock(objectLock);
+ return !writer;
+ }
+
+ double getSampleRate() const {
+ if (!writer)
+ throw std::runtime_error("I/O operation on a closed file.");
+ return writer->getSampleRate();
+ }
+
+ std::string getFilename() const { return filename; }
+
+ long getFramesWritten() const { return framesWritten; }
+
+ long getNumChannels() const {
+ if (!writer)
+ throw std::runtime_error("I/O operation on a closed file.");
+ return writer->getNumChannels();
+ }
+
+ std::shared_ptr<WriteableAudioFile> 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::string filename;
+ std::unique_ptr<juce::AudioFormatWriter> writer;
+ std::vector<std::vector<float>> deinterleaveBuffers;
+ juce::CriticalSection objectLock;
+ int framesWritten = 0;
+
+ static constexpr const unsigned int DEINTERLEAVE_BUFFER_SIZE_FRAMES = 1024;
};
inline void init_audiofile(py::module &m) {
py::class_<AudioFile, std::shared_ptr<AudioFile>>(
- m, "AudioFile",
- "An audio file reader interface, with native support for for Ogg Vorbis, "
+ m, "AudioFile", "A base class for readable and writeable audio files.")
+ .def(py::init<>()) // Make this class effectively abstract; we can only
+ // instantiate subclasses.
+ .def_static(
+ "__new__",
+ [](const py::object *, std::string filename, std::string mode) {
+ if (mode == "r") {
+ return std::make_shared<ReadableAudioFile>(filename);
+ } else if (mode == "w") {
+ throw py::type_error("Opening an audio file for writing requires "
+ "samplerate and num_channels arguments.");
+ } else {
+ throw py::type_error("AudioFile instances can only be opened in "
+ "read mode (\"r\") and write mode (\"w\").");
+ }
+ },
+ py::arg("cls"), py::arg("filename"), py::arg("mode") = "r")
+ .def_static(
+ "__new__",
+ [](const py::object *, std::string filename, std::string mode,
+ double sampleRate, int numChannels) {
+ if (mode == "r") {
+ throw py::type_error(
+ "Opening an audio file for reading does not require "
+ "samplerate and num_channels arguments - these parameters "
+ "will be read from the file.");
+ } else if (mode == "w") {
+ if (sampleRate == -1) {
+ throw py::type_error(
+ "Opening an audio file for writing requires a samplerate "
+ "argument to be provided.");
+ }
+
+ return std::make_shared<WriteableAudioFile>(filename, sampleRate,
+ numChannels);
+ } else {
+ throw py::type_error("AudioFile instances can only be opened in "
+ "read mode (\"r\") and write mode (\"w\").");
+ }
+ },
+ py::arg("cls"), py::arg("filename"), py::arg("mode") = "w",
+ py::arg("samplerate") = -1, py::arg("num_channels") = 1);
+
+ py::class_<ReadableAudioFile, AudioFile, std::shared_ptr<ReadableAudioFile>>(
+ m, "ReadableAudioFile",
+ "An audio file reader interface, with native support for Ogg Vorbis, "
"MP3, WAV, FLAC, and AIFF files on all operating systems. On some "
- "platforms, other formats may also be supported. (Use "
- "AudioFile.supported_formats to see which formats are supported on the "
- "current platform.)")
+ "platforms, other formats may also be readable. (Use "
+ "AudioFile.supported_read_formats and AudioFile.supported_write_formats "
+ "to see which formats are supported on the current platform.)")
.def(py::init([](std::string filename) {
- return std::make_unique<AudioFile>(filename);
+ return std::make_shared<ReadableAudioFile>(filename);
}),
py::arg("filename"))
- .def("read", &AudioFile::read, py::arg("num_frames") = 0,
+ .def_static(
+ "__new__",
+ [](const py::object *, std::string filename) {
+ return std::make_shared<ReadableAudioFile>(filename);
+ },
+ py::arg("cls"), py::arg("filename"))
+ .def("read", &ReadableAudioFile::read, py::arg("num_frames") = 0,
"Read the given number of frames (samples in each channel) from the "
"audio file at the current position. Audio samples are returned in "
"the shape (channels, samples); i.e.: a stereo audio file will have "
"shape (2, <length>).")
- .def("seekable", &AudioFile::isSeekable,
- "Returns True if the file is currently open and calls to seek() will work.")
- .def("seek", &AudioFile::seek, py::arg("position"),
+ .def("seekable", &ReadableAudioFile::isSeekable,
+ "Returns True if the file is currently open and calls to seek() "
+ "will work.")
+ .def("seek", &ReadableAudioFile::seek, py::arg("position"),
"Seek the file to the provided location in frames.")
- .def("tell", &AudioFile::tell,
+ .def("tell", &ReadableAudioFile::tell,
"Fetch the position in the audio file, in frames.")
- .def("close", &AudioFile::close,
+ .def("close", &ReadableAudioFile::close,
"Close the file, rendering this object unusable.")
- .def("__enter__", &AudioFile::enter)
- .def("__exit__", &AudioFile::exit)
- .def_property_readonly("closed", &AudioFile::isClosed,
- "If the file has been closed, this property will be True.")
- .def_property_readonly("samplerate", &AudioFile::getSampleRate,
+ .def("__enter__", &ReadableAudioFile::enter)
+ .def("__exit__", &ReadableAudioFile::exit)
+ .def("__repr__",
+ [](const ReadableAudioFile &file) {
+ std::ostringstream ss;
+ ss << "<pedalboard.io.ReadableAudioFile";
+ if (!file.getFilename().empty()) {
+ ss << " filename=" << file.getFilename();
+ }
+ if (file.isClosed()) {
+ ss << " closed";
+ } else {
+ ss << " samplerate=" << file.getSampleRate();
+ ss << " channels=" << file.getNumChannels();
+ ss << " frames=" << file.getLengthInSamples();
+ }
+ ss << " at " << &file;
+ ss << ">";
+ return ss.str();
+ })
+ .def_property_readonly(
+ "name", &ReadableAudioFile::getFilename,
+ "If the file has been closed, this property will be True.")
+ .def_property_readonly(
+ "closed", &ReadableAudioFile::isClosed,
+ "If the file has been closed, this property will be True.")
+ .def_property_readonly("samplerate", &ReadableAudioFile::getSampleRate,
"Fetch the sample rate of the file in samples "
"(per channel) per second (Hz).")
- .def_property_readonly("channels", &AudioFile::getNumChannels,
+ .def_property_readonly("channels", &ReadableAudioFile::getNumChannels,
"Fetch the number of channels in the file.")
- .def_property_readonly("frames", &AudioFile::getLengthInSamples,
+ .def_property_readonly("frames", &ReadableAudioFile::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());
+ "channel) in the file.");
+
+ py::class_<WriteableAudioFile, AudioFile,
+ std::shared_ptr<WriteableAudioFile>>(
+ m, "WriteableAudioFile",
+ "An audio file writer interface, with native support for Ogg Vorbis, "
+ "MP3, WAV, FLAC, and AIFF files on all operating systems.")
+ .def(py::init([](std::string filename, double sampleRate,
+ int numChannels) {
+ return std::make_shared<WriteableAudioFile>(filename, sampleRate,
+ numChannels);
+ }),
+ py::arg("filename"), py::arg("samplerate"),
+ py::arg("num_channels") = 1)
+ .def_static(
+ "__new__",
+ [](const py::object *, std::string filename, double sampleRate,
+ int numChannels) {
+ if (sampleRate == -1) {
+ throw py::type_error(
+ "Opening an audio file for writing requires a samplerate "
+ "argument to be provided.");
}
+ return std::make_shared<WriteableAudioFile>(filename, sampleRate,
+ numChannels);
+ },
+ py::arg("cls"), py::arg("filename"), py::arg("samplerate") = -1,
+ py::arg("num_channels") = 1)
+ .def("write", &WriteableAudioFile::write, py::arg("samples"))
+ .def("flush", &WriteableAudioFile::flush)
+ .def("close", &WriteableAudioFile::close,
+ "Close the file, rendering this object unusable.")
+ .def("__enter__", &WriteableAudioFile::enter)
+ .def("__exit__", &WriteableAudioFile::exit)
+ .def("__repr__",
+ [](const WriteableAudioFile &file) {
+ std::ostringstream ss;
+ ss << "<pedalboard.io.WriteableAudioFile";
+ if (!file.getFilename().empty()) {
+ ss << " filename=" << file.getFilename();
+ }
+ if (file.isClosed()) {
+ ss << " closed";
+ } else {
+ ss << " samplerate=" << file.getSampleRate();
+ ss << " channels=" << file.getNumChannels();
+ ss << " frames=" << file.getFramesWritten();
+ }
+ ss << " at " << &file;
+ ss << ">";
+ return ss.str();
+ })
+ .def_property_readonly(
+ "closed", &WriteableAudioFile::isClosed,
+ "If the file has been closed, this property will be True.")
+ .def_property_readonly("samplerate", &WriteableAudioFile::getSampleRate,
+ "Fetch the sample rate of the file in samples "
+ "(per channel) per second (Hz).")
+ .def_property_readonly("channels", &WriteableAudioFile::getNumChannels,
+ "Fetch the number of channels in the file.")
+ .def_property_readonly("frames", &WriteableAudioFile::getFramesWritten,
+ "Fetch the total number of frames (samples per "
+ "channel) written to the file so far.");
- extensions.trim();
- extensions.removeEmptyStrings();
- extensions.removeDuplicates(true);
+ m.def("get_supported_read_formats", []() {
+ juce::AudioFormatManager manager;
+ manager.registerBasicFormats();
- std::vector<std::string> output;
- for (juce::String s : extensions) {
- output.push_back(s.toStdString());
- }
+ 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::sort(output.begin(), output.end(),
- [](const std::string lhs, const std::string rhs) {
- return lhs < rhs;
- });
+ std::vector<std::string> output;
+ for (juce::String s : extensions) {
+ output.push_back(s.toStdString());
+ }
- return output;
- });
+ std::sort(
+ output.begin(), output.end(),
+ [](const std::string lhs, const std::string rhs) { return lhs < rhs; });
+
+ return output;
+ });
+
+ 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"};
+ return formats;
+ });
}
} // namespace Pedalboard
\ No newline at end of file
diff --git a/pedalboard/io/__init__.py b/pedalboard/io/__init__.py
new file mode 100644
index 0000000..75b157f
--- /dev/null
+++ b/pedalboard/io/__init__.py
@@ -0,0 +1 @@
+from pedalboard_native.io import *
\ No newline at end of file
diff --git a/pedalboard/process.h b/pedalboard/process.h
index c48ea4e..8558673 100644
--- a/pedalboard/process.h
+++ b/pedalboard/process.h
@@ -21,15 +21,12 @@
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
+#include "BufferUtils.h"
#include "Plugin.h"
namespace py = pybind11;
namespace Pedalboard {
-enum class ChannelLayout {
- Interleaved,
- NotInterleaved,
-};
/**
* Non-float32 overload.
@@ -57,152 +54,6 @@ processSingle(const py::array_t<SampleType, py::array::c_style> inputArray,
reset);
}
-template <typename T>
-ChannelLayout
-detectChannelLayout(const py::array_t<T, py::array::c_style> inputArray) {
- py::buffer_info inputInfo = inputArray.request();
-
- if (inputInfo.ndim == 1) {
- return ChannelLayout::Interleaved;
- } else if (inputInfo.ndim == 2) {
- // Try to auto-detect the channel layout from the shape
- if (inputInfo.shape[1] < inputInfo.shape[0]) {
- return ChannelLayout::Interleaved;
- } else if (inputInfo.shape[0] < inputInfo.shape[1]) {
- return ChannelLayout::NotInterleaved;
- } else {
- throw std::runtime_error(
- "Unable to determine channel layout from shape!");
- }
- } else {
- throw std::runtime_error("Number of input dimensions must be 1 or 2 (got " +
- std::to_string(inputInfo.ndim) + ").");
- }
-}
-
-template <typename T>
-juce::AudioBuffer<T>
-copyPyArrayIntoJuceBuffer(const py::array_t<T, py::array::c_style> inputArray) {
- // Numpy/Librosa convention is (num_samples, num_channels)
- py::buffer_info inputInfo = inputArray.request();
-
- unsigned int numChannels = 0;
- unsigned int numSamples = 0;
- ChannelLayout inputChannelLayout = detectChannelLayout(inputArray);
-
- if (inputInfo.ndim == 1) {
- numSamples = inputInfo.shape[0];
- numChannels = 1;
- } else if (inputInfo.ndim == 2) {
- // Try to auto-detect the channel layout from the shape
- if (inputInfo.shape[1] < inputInfo.shape[0]) {
- numSamples = inputInfo.shape[0];
- numChannels = inputInfo.shape[1];
- } else if (inputInfo.shape[0] < inputInfo.shape[1]) {
- numSamples = inputInfo.shape[1];
- numChannels = inputInfo.shape[0];
- } else {
- throw std::runtime_error("Unable to determine shape of audio input!");
- }
- } else {
- throw std::runtime_error("Number of input dimensions must be 1 or 2 (got " +
- std::to_string(inputInfo.ndim) + ").");
- }
-
- if (numChannels == 0) {
- throw std::runtime_error("No channels passed!");
- } else if (numChannels > 2) {
- throw std::runtime_error("More than two channels received!");
- }
-
- juce::AudioBuffer<T> ioBuffer(numChannels, numSamples);
-
- // Depending on the input channel layout, we need to copy data
- // differently. This loop is duplicated here to move the if statement
- // outside of the tight loop, as we don't need to re-check that the input
- // channel is still the same on every iteration of the loop.
- switch (inputChannelLayout) {
- case ChannelLayout::Interleaved:
- for (unsigned int i = 0; i < numChannels; i++) {
- T *channelBuffer = ioBuffer.getWritePointer(i);
- // We're de-interleaving the data here, so we can't use copyFrom.
- for (unsigned int j = 0; j < numSamples; j++) {
- channelBuffer[j] = static_cast<T *>(inputInfo.ptr)[j * numChannels + i];
- }
- }
- break;
- case ChannelLayout::NotInterleaved:
- for (unsigned int i = 0; i < numChannels; i++) {
- ioBuffer.copyFrom(
- i, 0, static_cast<T *>(inputInfo.ptr) + (numSamples * i), numSamples);
- }
- break;
- default:
- throw std::runtime_error("Internal error: got unexpected channel layout.");
- }
-
- return ioBuffer;
-}
-
-template <typename T>
-py::array_t<T> copyJuceBufferIntoPyArray(const juce::AudioBuffer<T> juceBuffer,
- ChannelLayout channelLayout,
- int offsetSamples, int ndim = 2) {
- unsigned int numChannels = juceBuffer.getNumChannels();
- unsigned int numSamples = juceBuffer.getNumSamples();
- unsigned int outputSampleCount =
- std::max((int)numSamples - (int)offsetSamples, 0);
-
- // TODO: Avoid the need to copy here if offsetSamples is 0!
- py::array_t<T> outputArray;
- if (ndim == 2) {
- switch (channelLayout) {
- case ChannelLayout::Interleaved:
- outputArray = py::array_t<T>({outputSampleCount, numChannels});
- break;
- case ChannelLayout::NotInterleaved:
- outputArray = py::array_t<T>({numChannels, outputSampleCount});
- break;
- default:
- throw std::runtime_error(
- "Internal error: got unexpected channel layout.");
- }
- } else {
- outputArray = py::array_t<T>(outputSampleCount);
- }
-
- py::buffer_info outputInfo = outputArray.request();
-
- // Depending on the input channel layout, we need to copy data
- // differently. This loop is duplicated here to move the if statement
- // outside of the tight loop, as we don't need to re-check that the input
- // channel is still the same on every iteration of the loop.
- T *outputBasePointer = static_cast<T *>(outputInfo.ptr);
-
- switch (channelLayout) {
- case ChannelLayout::Interleaved:
- for (unsigned int i = 0; i < numChannels; i++) {
- const T *channelBuffer = juceBuffer.getReadPointer(i, offsetSamples);
- // We're interleaving the data here, so we can't use copyFrom.
- for (unsigned int j = 0; j < outputSampleCount; j++) {
- outputBasePointer[j * numChannels + i] = channelBuffer[j];
- }
- }
- break;
- case ChannelLayout::NotInterleaved:
- for (unsigned int i = 0; i < numChannels; i++) {
- const T *channelBuffer = juceBuffer.getReadPointer(i, offsetSamples);
- std::copy(channelBuffer, channelBuffer + outputSampleCount,
- &outputBasePointer[outputSampleCount * i]);
- }
- break;
- default:
- throw std::runtime_error("Internal error: got unexpected channel layout.");
- }
-
- return outputArray;
-}
-
inline int process(juce::AudioBuffer<float> &ioBuffer,
juce::dsp::ProcessSpec spec,
const std::vector<std::shared_ptr<Plugin>> &plugins,
diff --git a/tests/test_io.py b/tests/test_io.py
new file mode 100644
index 0000000..0d1b158
--- /dev/null
+++ b/tests/test_io.py
@@ -0,0 +1,299 @@
+#! /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 pathlib
+import shutil
+import pytest
+import pedalboard
+
+import numpy as np
+
+from .utils import generate_sine_at
+
+EXPECTED_DURATION_SECONDS = 5
+EXPECT_LENGTH_TO_BE_EXACT = {"mp3", "wav", "aiff", "aifc", "caf", "ogg", "m4a", "mp4"}
+
+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.get_supported_read_formats())
+]
+
+UNSUPPORTED_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()
+ )
+]
+
+
+def test_read_constructor_dispatch():
+ filename, _samplerate = FILENAMES_AND_SAMPLERATES[0]
+
+ # Support reading a file with just its filename:
+ assert isinstance(pedalboard.io.AudioFile(filename), pedalboard.io.ReadableAudioFile)
+
+ # Support reading a file with just its filename and an explicit "r" (read) flag:
+ assert isinstance(pedalboard.io.AudioFile(filename, "r"), pedalboard.io.ReadableAudioFile)
+
+ # Support reading a file by using the appropriate subclass constructor just its filename:
+ assert isinstance(pedalboard.io.ReadableAudioFile(filename), pedalboard.io.ReadableAudioFile)
+
+ # Don't support reading a file by passing a mode to the subclass constructor (which would be redundant):
+ with pytest.raises(TypeError) as e:
+ pedalboard.io.ReadableAudioFile(filename, "r")
+ assert "incompatible function arguments" in str(e)
+
+
+def test_write_constructor_dispatch(tmp_path: pathlib.Path):
+ filename = str(tmp_path / "temp.wav")
+
+ # Don't support writing to a file with just its filename and write args:
+ with pytest.raises(TypeError):
+ pedalboard.io.AudioFile(filename, 44100, 1)
+
+ # Support writing to a file with just its filename and an explicit "w" (write) flag:
+ assert isinstance(
+ pedalboard.io.AudioFile(filename, "w", 44100, 1), pedalboard.io.WriteableAudioFile
+ )
+
+ # Support writing to a file by using the appropriate subclass constructor just its filename:
+ assert isinstance(
+ pedalboard.io.WriteableAudioFile(filename, 44100, 1), pedalboard.io.WriteableAudioFile
+ )
+
+ # Don't support writing to a file by passing a mode to the subclass constructor (which would be redundant):
+ with pytest.raises(TypeError) as e:
+ pedalboard.io.WriteableAudioFile(filename, "w", 44100, 1)
+ assert "incompatible function arguments" in str(e)
+
+ # Support writing to a file by omitting num_channels to WriteableAudioFile:
+ assert isinstance(
+ pedalboard.io.WriteableAudioFile(filename, samplerate=44100),
+ pedalboard.io.WriteableAudioFile,
+ )
+
+ # but not if samplerate is missing:
+ with pytest.raises(TypeError) as e:
+ pedalboard.io.WriteableAudioFile(filename, num_channels=1)
+ assert "samplerate" in str(e)
+
+ # ... or to regular AudioFile with a "w" flag:
+ assert isinstance(
+ pedalboard.io.AudioFile(filename, "w", samplerate=44100),
+ pedalboard.io.WriteableAudioFile,
+ )
+
+ # but not if samplerate is missing:
+ with pytest.raises(TypeError) as e:
+ pedalboard.io.AudioFile(filename, "w", num_channels=1)
+ assert "samplerate" in str(e)
+
+
[email protected]("extension", [".mp3", ".wav", ".ogg", ".flac"])
+def test_basic_formats_available_on_all_platforms(extension: str):
+ assert extension in pedalboard.io.get_supported_read_formats()
+
+
[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 == samplerate
+ assert af.channels == 1
+ if any(ext in audio_filename for ext in EXPECT_LENGTH_TO_BE_EXACT):
+ assert af.frames == int(samplerate * EXPECTED_DURATION_SECONDS)
+ else:
+ assert af.frames >= int(samplerate * EXPECTED_DURATION_SECONDS)
+
+ samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
+ assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
+
+ # File should no longer be useful:
+ af.read(1).nbytes == 0
+
+ # Seeking back to the start of the file should work:
+ assert af.seekable()
+ af.seek(0)
+ samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
+ assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
+
+ # Seeking to an arbitrary point should also work
+ af.seek(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
+ samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
+ assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS / 2))
+
+ assert f"samplerate={int(af.samplerate)}" in repr(af)
+ assert f"channels={af.channels}" in repr(af)
+ assert f"frames={af.frames}" in repr(af)
+
+ af.close()
+
+ with pytest.raises(RuntimeError):
+ af.channels
+
+ with pytest.raises(RuntimeError):
+ af.read(1)
+
+
[email protected]("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)
+def test_use_reader_as_context_manager(audio_filename: str, samplerate: float):
+ with pedalboard.io.AudioFile(audio_filename) as af:
+ assert af.samplerate == samplerate
+ assert af.channels == 1
+ if any(ext in audio_filename for ext in EXPECT_LENGTH_TO_BE_EXACT):
+ assert af.frames == int(samplerate * EXPECTED_DURATION_SECONDS)
+ else:
+ assert af.frames >= int(samplerate * EXPECTED_DURATION_SECONDS)
+
+ samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
+ assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
+
+ # File should no longer be useful:
+ af.read(1).nbytes == 0
+
+ # Seeking back to the start of the file should work:
+ assert af.seekable()
+ af.seek(0)
+ samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
+ assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
+
+ # Seeking to an arbitrary point should also work
+ af.seek(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
+ samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
+ assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS / 2))
+
+ assert f"samplerate={int(af.samplerate)}" in repr(af)
+ assert f"channels={af.channels}" in repr(af)
+ assert f"frames={af.frames}" in repr(af)
+
+ with pytest.raises(RuntimeError):
+ af.channels
+
+ with pytest.raises(RuntimeError):
+ af.read(1)
+
+
+def test_context_manager_allows_exceptions():
+ with pytest.raises(AssertionError):
+ with pedalboard.io.AudioFile(FILENAMES_AND_SAMPLERATES[0][0]) as af:
+ assert False
+
+ assert af.closed
+
+
[email protected]("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)
+def test_read_okay_without_extension(
+ 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.AudioFile(dest_path) as af:
+ assert af.samplerate == samplerate
+ assert af.channels == 1
+
+
+def test_write_fails_without_extension(tmp_path: pathlib.Path):
+ dest_path = str(tmp_path / "no_extension")
+ with pytest.raises(ValueError):
+ pedalboard.io.AudioFile(dest_path, "w", 44100, 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
+
+
[email protected]("audio_filename", UNSUPPORTED_FILENAMES)
+def test_fails_on_unsupported_format(audio_filename: str):
+ with pytest.raises(ValueError):
+ pedalboard.io.AudioFile(audio_filename)
+
+
[email protected]("extension", pedalboard.io.get_supported_write_formats())
+ "samplerate",
+ [8000, 11025, 12000, 16000, 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000],
+)
[email protected]("num_channels", [1, 2, 8])
[email protected]("transposed", [False, True])
+def test_basic_write(
+ tmp_path: pathlib.Path,
+ extension: str,
+ samplerate: float,
+ num_channels: int,
+ transposed: bool,
+):
+ filename = str(tmp_path / f"test{extension}")
+ audio = generate_sine_at(samplerate, num_channels=num_channels).astype(np.float32)
+ num_samples = audio.shape[-1]
+ if transposed:
+ audio = audio.T
+ with pedalboard.io.WriteableAudioFile(
+ filename, samplerate=samplerate, num_channels=num_channels
+ ) as af:
+ af.write(audio)
+ assert os.path.exists(filename)
+ assert os.path.getsize(filename) > 0
+ with pedalboard.io.ReadableAudioFile(filename) as af:
+ assert af.samplerate == samplerate
+ assert af.channels == num_channels
+ tolerance = 0.11 if extension == ".ogg" else 2 / (2**16)
+ as_written = af.read(num_samples)
+ if transposed:
+ as_written = as_written.T
+ np.testing.assert_allclose(audio, np.squeeze(as_written), atol=tolerance)
+
+
[email protected]("extension", pedalboard.io.get_supported_write_formats())
[email protected]("samplerate", [1234.5, 23.0000000001])
+def test_fractional_sample_rates(tmp_path: pathlib.Path, extension: str, samplerate):
+ filename = str(tmp_path / f"test{extension}")
+ with pytest.raises(ValueError):
+ pedalboard.io.WriteableAudioFile(filename, samplerate=samplerate, num_channels=1)
+
+
[email protected]("extension", pedalboard.io.get_supported_write_formats())
[email protected]("samplerate", [123, 999, 48001])
+def test_uncommon_sample_rates(tmp_path: pathlib.Path, extension: str, samplerate):
+ filename = str(tmp_path / f"test{extension}")
+ with pedalboard.io.WriteableAudioFile(filename, samplerate=samplerate, num_channels=1):
+ pass
+ with pedalboard.io.ReadableAudioFile(filename) as af:
+ assert af.samplerate == samplerate
+
+
[email protected]("extension", [".flac"])
[email protected]("samplerate", [123456, 234567])
+def test_unusable_sample_rates(tmp_path: pathlib.Path, extension: str, samplerate):
+ filename = str(tmp_path / f"test{extension}")
+ with pytest.raises(ValueError) as e:
+ pedalboard.io.WriteableAudioFile(filename, samplerate=samplerate, num_channels=1)
+ assert "44100" in str(e), "Expected exception to include details about supported sample rates."
diff --git a/tests/test_io_read.py b/tests/test_io_read.py
deleted file mode 100644
index 212a100..0000000
--- a/tests/test_io_read.py
+++ /dev/null
@@ -1,143 +0,0 @@
-#! /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
-
-EXPECTED_DURATION_SECONDS = 5
-EXPECT_LENGTH_TO_BE_EXACT = {"mp3", "wav", "aiff", "aifc", "caf", "ogg", "m4a", "mp4"}
-
-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)
-]
-
-UNSUPPORTED_FILENAMES = [
- filename
- for filename in sum(TEST_AUDIO_FILES.values(), [])
- if not 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
- if any(ext in audio_filename for ext in EXPECT_LENGTH_TO_BE_EXACT):
- assert af.frames == int(samplerate * EXPECTED_DURATION_SECONDS)
- else:
- assert af.frames >= int(samplerate * EXPECTED_DURATION_SECONDS)
-
- samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
- assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
-
- # File should no longer be useful:
- af.read(1).nbytes == 0
-
- # Seeking back to the start of the file should work:
- assert af.seekable()
- af.seek(0)
- samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
- assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
-
- # Seeking to an arbitrary point should also work
- af.seek(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
- samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
- assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS / 2))
-
- af.close()
-
- with pytest.raises(RuntimeError):
- af.channels
-
- with pytest.raises(RuntimeError):
- af.read(1)
-
-
[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
- if any(ext in audio_filename for ext in EXPECT_LENGTH_TO_BE_EXACT):
- assert af.frames == int(samplerate * EXPECTED_DURATION_SECONDS)
- else:
- assert af.frames >= int(samplerate * EXPECTED_DURATION_SECONDS)
-
- samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
- assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
-
- # File should no longer be useful:
- af.read(1).nbytes == 0
-
- # Seeking back to the start of the file should work:
- assert af.seekable()
- af.seek(0)
- samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
- assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
-
- # Seeking to an arbitrary point should also work
- af.seek(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
- samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS / 2))
- assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS / 2))
-
- with pytest.raises(RuntimeError):
- af.channels
-
- with pytest.raises(RuntimeError):
- af.read(1)
-
-
-def test_context_manager_allows_exceptions():
- with pytest.raises(AssertionError):
- with pedalboard.io.AudioFile(FILENAMES_AND_SAMPLERATES[0][0]) as af:
- assert False
-
- assert af.closed
-
-
-def test_fails_gracefully():
- with pytest.raises(ValueError):
- pedalboard.io.AudioFile(__file__)
-
- with pytest.raises(ValueError):
- with pedalboard.io.AudioFile(__file__) as f:
- pass
-
-
[email protected]("audio_filename", UNSUPPORTED_FILENAMES)
-def test_fails_on_unsupported_format(audio_filename: str):
- with pytest.raises(ValueError):
- pedalboard.io.AudioFile(audio_filename)
diff --git a/tests/utils.py b/tests/utils.py
index 55ba88b..61cc6e6 100644
--- a/tests/utils.py
+++ b/tests/utils.py
@@ -18,8 +18,8 @@ def generate_sine_at(
fade_duration = int(sample_rate * 0.1)
sine_wave[:fade_duration] *= np.linspace(0, 1, fade_duration)
sine_wave[-fade_duration:] *= np.linspace(1, 0, fade_duration)
- if num_channels == 2:
- TEST_SINE_WAVE_CACHE[cache_key] = np.stack([sine_wave, sine_wave])
+ if num_channels != 1:
+ TEST_SINE_WAVE_CACHE[cache_key] = np.stack([sine_wave] * num_channels)
else:
TEST_SINE_WAVE_CACHE[cache_key] = sine_wave
return TEST_SINE_WAVE_CACHE[cache_key]