Skip to content

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

Add ability to specify codec-specific options. (#480)

Peter Sobotf402b848d610
diff --git a/pedalboard/io/AudioFileInit.h b/pedalboard/io/AudioFileInit.h
index f447277..1005388 100644
--- a/pedalboard/io/AudioFileInit.h
+++ b/pedalboard/io/AudioFileInit.h
@@ -25,6 +25,7 @@
#include "../JuceHeader.h"
#include "AudioFile.h"
+#include "WriteableAudioFileFlags.h"
#include "ReadableAudioFile.h"
#include "WriteableAudioFile.h"
@@ -203,7 +204,8 @@ inline void init_audio_file(
"__new__",
[](const py::object *, std::string filename, std::string mode,
std::optional<double> sampleRate, int numChannels, int bitDepth,
- std::optional<std::variant<std::string, float>> quality) {
+ std::optional<std::variant<std::string, float>> quality,
+ CodecOptionsMap codecOptions) {
if (mode == "r") {
throw py::type_error(
"Opening an audio file for reading does not require "
@@ -218,7 +220,8 @@ inline void init_audio_file(
}
return std::make_shared<WriteableAudioFile>(
- filename, *sampleRate, numChannels, bitDepth, quality);
+ filename, *sampleRate, numChannels, bitDepth, quality,
+ codecOptions);
} else {
throw py::type_error("AudioFile instances can only be opened in "
"read mode (\"r\") or write mode (\"w\").");
@@ -226,13 +229,14 @@ inline void init_audio_file(
},
py::arg("cls"), py::arg("filename"), py::arg("mode") = "w",
py::arg("samplerate") = py::none(), py::arg("num_channels") = 1,
- py::arg("bit_depth") = 16, py::arg("quality") = py::none())
+ py::arg("bit_depth") = 16, py::arg("quality") = py::none(),
+ py::arg("codec_options") = CodecOptionsMap{})
.def_static(
"__new__",
[](const py::object *, py::object filelike, std::string mode,
std::optional<double> sampleRate, int numChannels, int bitDepth,
std::optional<std::variant<std::string, float>> quality,
- std::optional<std::string> format) {
+ std::optional<std::string> format, CodecOptionsMap codecOptions) {
if (mode == "r") {
throw py::type_error(
"Opening a file-like object for reading does not require "
@@ -266,7 +270,7 @@ inline void init_audio_file(
return std::make_shared<WriteableAudioFile>(
format.value_or(""), std::move(stream), *sampleRate,
- numChannels, bitDepth, quality);
+ numChannels, bitDepth, quality, codecOptions);
} else {
throw py::type_error("AudioFile instances can only be opened in "
"read mode (\"r\") or write mode (\"w\").");
@@ -275,17 +279,19 @@ inline void init_audio_file(
py::arg("cls"), py::arg("file_like"), py::arg("mode") = "w",
py::arg("samplerate") = py::none(), py::arg("num_channels") = 1,
py::arg("bit_depth") = 16, py::arg("quality") = py::none(),
- py::arg("format") = py::none())
+ py::arg("format") = py::none(),
+ py::arg("codec_options") = CodecOptionsMap{})
.def_static(
"encode",
[](const py::array samples, double sampleRate, std::string format,
int numChannels, int bitDepth,
- std::optional<std::variant<std::string, float>> quality) {
+ std::optional<std::variant<std::string, float>> quality,
+ CodecOptionsMap codecOptions) {
juce::MemoryBlock outputBlock;
auto audioFile = std::make_unique<WriteableAudioFile>(
format,
std::make_unique<juce::MemoryOutputStream>(outputBlock, false),
- sampleRate, numChannels, bitDepth, quality);
+ sampleRate, numChannels, bitDepth, quality, codecOptions);
audioFile->write(samples);
audioFile->close();
@@ -296,6 +302,7 @@ inline void init_audio_file(
py::arg("samples"), py::arg("samplerate"), py::arg("format"),
py::arg("num_channels") = 1, py::arg("bit_depth") = 16,
py::arg("quality") = py::none(),
+ py::arg("codec_options") = CodecOptionsMap{},
R"(
Encode an audio buffer to a Python :class:`bytes` object.
diff --git a/pedalboard/io/LameMP3AudioFormat.h b/pedalboard/io/LameMP3AudioFormat.h
index 463ee8e..3a9cdaa 100644
--- a/pedalboard/io/LameMP3AudioFormat.h
+++ b/pedalboard/io/LameMP3AudioFormat.h
@@ -18,6 +18,7 @@
#include "../JuceHeader.h"
#include "../plugins/MP3Compressor.h"
+#include "WriteableAudioFileFlags.h"
extern "C" {
#include <lame.h>
@@ -56,11 +57,20 @@ public:
unsigned int numberOfChannels, int bitsPerSample,
const juce::StringPairArray &metadataValues,
int qualityOptionIndex) {
+ return createWriterFor(out, sampleRateToUse, numberOfChannels,
+ bitsPerSample, metadataValues, qualityOptionIndex,
+ {});
+ }
+ juce::AudioFormatWriter *
+ createWriterFor(juce::OutputStream *out, double sampleRateToUse,
+ unsigned int numberOfChannels, int bitsPerSample,
+ const juce::StringPairArray &metadataValues,
+ int qualityOptionIndex, const CodecOptionsMap &codecOptions) {
try {
if (out != nullptr)
return new Writer(out, sampleRateToUse, numberOfChannels,
- qualityOptionIndex);
+ qualityOptionIndex, codecOptions);
} catch (...) {
// TODO: Make WriteableAudioFile exception-safe so we can bubble up more
// useful error messages.
@@ -73,7 +83,8 @@ public:
class Writer : public juce::AudioFormatWriter {
public:
Writer(juce::OutputStream *destStream, double sampleRate,
- unsigned int numberOfChannels, int qualityOptionIndex)
+ unsigned int numberOfChannels, int qualityOptionIndex,
+ const CodecOptionsMap &codecOptions = {})
: juce::AudioFormatWriter(nullptr, "MP3", sampleRate, numberOfChannels,
16) {
usesFloatingPointData = false;
@@ -131,6 +142,8 @@ public:
throw std::domain_error("Unsupported quality index!");
}
+ applyCodecOptions(codecOptions);
+
int ret = lame_init_params(encoder.getContext());
if (ret != 0) {
throw std::runtime_error("Failed to initialize MP3 encoder! (error " +
@@ -143,6 +156,34 @@ public:
output = destStream;
}
+ private:
+ void applyCodecOptions(const CodecOptionsMap &options) {
+ for (const auto &[flag, value] : options) {
+ switch (flag) {
+ case WriteableAudioFileFlag::Mp3EnableBitReservoir: {
+ const bool *boolVal = std::get_if<bool>(&value);
+ if (!boolVal) {
+ throw std::domain_error(
+ "Mp3EnableBitReservoir expects a bool value.");
+ }
+ if (lame_set_disable_reservoir(encoder.getContext(),
+ *boolVal ? 0 : 1) != 0) {
+ throw std::domain_error(
+ "MP3 encoder failed to configure bit reservoir.");
+ }
+ break;
+ }
+ default:
+ throw std::domain_error(
+ "The codec option " + flagName(flag) +
+ " was passed in codec_options, but is not supported by the MP3 "
+ "encoder. Supported codec options for MP3: " +
+ supportedFlagNames("MP3") + ".");
+ }
+ }
+ }
+
+ public:
virtual ~Writer() override {
if (!output)
return;
diff --git a/pedalboard/io/WriteableAudioFile.h b/pedalboard/io/WriteableAudioFile.h
index 8a874ba..51a312c 100644
--- a/pedalboard/io/WriteableAudioFile.h
+++ b/pedalboard/io/WriteableAudioFile.h
@@ -28,6 +28,7 @@
#include "AudioFile.h"
#include "LameMP3AudioFormat.h"
#include "PythonOutputStream.h"
+#include "WriteableAudioFileFlags.h"
namespace py = pybind11;
@@ -222,15 +223,17 @@ public:
WriteableAudioFile(
std::string filename, double writeSampleRate, int numChannels = 1,
int bitDepth = 16,
- std::optional<std::variant<std::string, float>> qualityInput = {})
+ std::optional<std::variant<std::string, float>> qualityInput = {},
+ CodecOptionsMap codecOptions = {})
: WriteableAudioFile(filename, nullptr, writeSampleRate, numChannels,
- bitDepth, qualityInput) {}
+ bitDepth, qualityInput, codecOptions) {}
WriteableAudioFile(
std::string filename,
std::unique_ptr<juce::OutputStream> providedOutputStream,
double writeSampleRate, int numChannels = 1, int bitDepth = 16,
- std::optional<std::variant<std::string, float>> qualityInput = {}) {
+ std::optional<std::variant<std::string, float>> qualityInput = {},
+ CodecOptionsMap codecOptions = {}) {
pybind11::gil_scoped_release release;
// This is kind of silly, as nobody else has a reference
@@ -355,10 +358,19 @@ public:
quality = format->getQualityOptions()[qualityOptionIndex].toStdString();
}
+ std::string formatName = format->getFormatName().toStdString();
+ validateCodecOptions(codecOptions, formatName);
+
juce::StringPairArray emptyMetadata;
- writer.reset(format->createWriterFor(outputStream.get(), writeSampleRate,
- numChannels, bitDepth, emptyMetadata,
- qualityOptionIndex));
+ if (auto *lameFormat = dynamic_cast<LameMP3AudioFormat *>(format)) {
+ writer.reset(lameFormat->createWriterFor(
+ outputStream.get(), writeSampleRate, numChannels, bitDepth,
+ emptyMetadata, qualityOptionIndex, codecOptions));
+ } else {
+ writer.reset(format->createWriterFor(outputStream.get(), writeSampleRate,
+ numChannels, bitDepth, emptyMetadata,
+ qualityOptionIndex));
+ }
if (!writer) {
PythonException::raise();
@@ -923,6 +935,14 @@ Args:
may be passed as a string. The strings ``"best"``, ``"worst"``,
``"fastest"``, and ``"slowest"`` will also work for any codec.
+ codec_options:
+ An optional dictionary mapping :class:`WriteableAudioFileFlag` keys to
+ values (``bool``, ``int``, ``float``, or ``str``). These flags control
+ low-level, codec-specific encoder behavior. Not all flags are supported
+ by all codecs; passing an unsupported flag will raise a ``ValueError``.
+
+ See :class:`WriteableAudioFileFlag` for available options.
+
.. note::
You probably don't want to use this class directly: all of the parameters
accepted by the :class:`WriteableAudioFile` constructor will be accepted by
@@ -939,8 +959,8 @@ inline void init_writeable_audio_file(
pyWriteableAudioFile
.def(py::init([](std::string filename, double sampleRate, int numChannels,
int bitDepth,
- std::optional<std::variant<std::string, float>> quality)
- -> WriteableAudioFile * {
+ std::optional<std::variant<std::string, float>> quality,
+ CodecOptionsMap codecOptions) -> WriteableAudioFile * {
// This definition is only here to provide nice docstrings.
throw std::runtime_error(
"Internal error: __init__ should never be called, as this "
@@ -948,42 +968,47 @@ inline void init_writeable_audio_file(
}),
py::arg("filename"), py::arg("samplerate"),
py::arg("num_channels") = 1, py::arg("bit_depth") = 16,
- py::arg("quality") = py::none())
- .def(py::init(
- [](py::object filelike, double sampleRate, int numChannels,
- int bitDepth,
- std::optional<std::variant<std::string, float>> quality,
- std::optional<std::string> format) -> WriteableAudioFile * {
- // 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("quality") = py::none(),
+ py::arg("codec_options") = CodecOptionsMap{})
+ .def(py::init([](py::object filelike, double sampleRate, int numChannels,
+ int bitDepth,
+ std::optional<std::variant<std::string, float>> quality,
+ std::optional<std::string> format,
+ CodecOptionsMap codecOptions) -> WriteableAudioFile * {
+ // 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("samplerate"),
py::arg("num_channels") = 1, py::arg("bit_depth") = 16,
- py::arg("quality") = py::none(), py::arg("format") = py::none())
+ py::arg("quality") = py::none(), py::arg("format") = py::none(),
+ py::arg("codec_options") = CodecOptionsMap{})
.def_static(
"__new__",
[](const py::object *, std::string filename,
std::optional<double> sampleRate, int numChannels, int bitDepth,
- std::optional<std::variant<std::string, float>> quality) {
+ std::optional<std::variant<std::string, float>> quality,
+ CodecOptionsMap codecOptions) {
if (!sampleRate) {
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, bitDepth, quality);
+ return std::make_shared<WriteableAudioFile>(filename, *sampleRate,
+ numChannels, bitDepth,
+ quality, codecOptions);
},
py::arg("cls"), py::arg("filename"),
py::arg("samplerate") = py::none(), py::arg("num_channels") = 1,
- py::arg("bit_depth") = 16, py::arg("quality") = py::none())
+ py::arg("bit_depth") = 16, py::arg("quality") = py::none(),
+ py::arg("codec_options") = CodecOptionsMap{})
.def_static(
"__new__",
[](const py::object *, py::object filelike,
std::optional<double> sampleRate, int numChannels, int bitDepth,
std::optional<std::variant<std::string, float>> quality,
- std::optional<std::string> format) {
+ std::optional<std::string> format, CodecOptionsMap codecOptions) {
if (!sampleRate) {
throw py::type_error(
"Opening an audio file for writing requires a samplerate "
@@ -1009,12 +1034,13 @@ inline void init_writeable_audio_file(
return std::make_shared<WriteableAudioFile>(
format.value_or(""), std::move(stream), *sampleRate,
- numChannels, bitDepth, quality);
+ numChannels, bitDepth, quality, codecOptions);
},
py::arg("cls"), py::arg("file_like"),
py::arg("samplerate") = py::none(), py::arg("num_channels") = 1,
py::arg("bit_depth") = 16, py::arg("quality") = py::none(),
- py::arg("format") = py::none())
+ py::arg("format") = py::none(),
+ py::arg("codec_options") = CodecOptionsMap{})
.def(
"write",
[](WriteableAudioFile &file, py::array samples) {
diff --git a/pedalboard/io/WriteableAudioFileFlags.h b/pedalboard/io/WriteableAudioFileFlags.h
new file mode 100644
index 0000000..3702900
--- /dev/null
+++ b/pedalboard/io/WriteableAudioFileFlags.h
@@ -0,0 +1,187 @@
+/*
+ * pedalboard
+ * Copyright 2026 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 <map>
+#include <set>
+#include <sstream>
+#include <string>
+#include <variant>
+
+#include <pybind11/pybind11.h>
+#include <pybind11/stl.h>
+
+namespace py = pybind11;
+
+namespace Pedalboard {
+
+enum class WriteableAudioFileFlag {
+ Mp3EnableBitReservoir,
+};
+
+using CodecOptionValue = std::variant<bool, float, int, std::string>;
+using CodecOptionsMap = std::map<WriteableAudioFileFlag, CodecOptionValue>;
+
+static inline const std::map<WriteableAudioFileFlag, std::string> FLAG_NAMES = {
+ {WriteableAudioFileFlag::Mp3EnableBitReservoir, "Mp3EnableBitReservoir"},
+};
+
+static inline const std::map<std::string, std::set<WriteableAudioFileFlag>>
+ FORMAT_SUPPORTED_FLAGS = {
+ {"MP3", {WriteableAudioFileFlag::Mp3EnableBitReservoir}},
+};
+
+inline std::string flagName(WriteableAudioFileFlag flag) {
+ auto it = FLAG_NAMES.find(flag);
+ if (it != FLAG_NAMES.end())
+ return it->second;
+ return "<unknown flag>";
+}
+
+inline std::string supportedFlagNames(const std::string &formatName) {
+ auto it = FORMAT_SUPPORTED_FLAGS.find(formatName);
+ if (it == FORMAT_SUPPORTED_FLAGS.end() || it->second.empty())
+ return "";
+
+ std::ostringstream ss;
+ bool first = true;
+ for (const auto &f : it->second) {
+ if (!first)
+ ss << ", ";
+ ss << flagName(f);
+ first = false;
+ }
+ return ss.str();
+}
+
+/**
+ * Expected value type for each flag, used for early validation before the
+ * value reaches the encoder (where errors may be swallowed).
+ */
+enum class CodecOptionType { Bool, Float, Int, String };
+
+static inline const std::map<WriteableAudioFileFlag, CodecOptionType>
+ FLAG_EXPECTED_TYPES = {
+ {WriteableAudioFileFlag::Mp3EnableBitReservoir, CodecOptionType::Bool},
+};
+
+inline std::string codecOptionTypeName(CodecOptionType t) {
+ switch (t) {
+ case CodecOptionType::Bool:
+ return "bool";
+ case CodecOptionType::Float:
+ return "float";
+ case CodecOptionType::Int:
+ return "int";
+ case CodecOptionType::String:
+ return "str";
+ }
+ return "<unknown>";
+}
+
+inline bool valueMatchesExpectedType(const CodecOptionValue &value,
+ CodecOptionType expected) {
+ switch (expected) {
+ case CodecOptionType::Bool:
+ return std::holds_alternative<bool>(value);
+ case CodecOptionType::Float:
+ return std::holds_alternative<float>(value);
+ case CodecOptionType::Int:
+ return std::holds_alternative<int>(value);
+ case CodecOptionType::String:
+ return std::holds_alternative<std::string>(value);
+ }
+ return false;
+}
+
+/**
+ * Validate that all flags in the options map are supported by the given
+ * audio format and that their values have the correct types. Throws
+ * std::domain_error if any flag is unsupported or has the wrong type.
+ */
+inline void validateCodecOptions(const CodecOptionsMap &options,
+ const std::string &formatName) {
+ if (options.empty())
+ return;
+
+ auto it = FORMAT_SUPPORTED_FLAGS.find(formatName);
+ std::set<WriteableAudioFileFlag> supported;
+ if (it != FORMAT_SUPPORTED_FLAGS.end()) {
+ supported = it->second;
+ }
+
+ for (const auto &[flag, value] : options) {
+ if (supported.find(flag) == supported.end()) {
+ std::ostringstream ss;
+ ss << "The codec option " << flagName(flag) << " is not supported by the "
+ << formatName << " encoder.";
+
+ std::string supported_names = supportedFlagNames(formatName);
+ if (supported_names.empty()) {
+ ss << " The " << formatName
+ << " encoder does not support any codec options.";
+ } else {
+ ss << " Supported options for " << formatName << ": " << supported_names
+ << ".";
+ }
+
+ throw std::domain_error(ss.str());
+ }
+
+ auto typeIt = FLAG_EXPECTED_TYPES.find(flag);
+ if (typeIt != FLAG_EXPECTED_TYPES.end() &&
+ !valueMatchesExpectedType(value, typeIt->second)) {
+ throw std::domain_error(flagName(flag) + " expects a " +
+ codecOptionTypeName(typeIt->second) + " value.");
+ }
+ }
+}
+
+inline void init_writeable_audio_file_flags(py::module &m) {
+ py::enum_<WriteableAudioFileFlag>(m, "WriteableAudioFileFlag",
+ R"(
+An enumeration of codec-specific options that can be passed when opening an
+audio file for writing. These flags are used as keys in the ``codec_options``
+dictionary parameter accepted by :class:`WriteableAudioFile` and
+:class:`AudioFile`.
+
+Not all flags are supported by all codecs. Passing an unsupported flag for
+the selected codec will raise a ``ValueError``.
+
+.. note::
+ These flags control low-level encoder behavior. Most users will not need
+ to use them. The ``quality`` parameter is usually sufficient for
+ controlling encoder output.
+)")
+ .value("Mp3EnableBitReservoir",
+ WriteableAudioFileFlag::Mp3EnableBitReservoir,
+ R"(
+When writing MP3 files, controls whether the LAME encoder's bit reservoir
+is enabled. The bit reservoir allows the encoder to use fewer bits on
+simple frames and save them for complex frames, improving overall quality
+at a given bitrate. Disabling it forces each frame to be independently
+decodable at the cost of slightly lower quality.
+
+Set to ``False`` for streaming or seeking applications where individual
+frames need to be independently decodable.
+
+Accepts a ``bool`` value. Defaults to ``True`` (bit reservoir enabled).
+)");
+}
+
+} // namespace Pedalboard
diff --git a/pedalboard/python_bindings.cpp b/pedalboard/python_bindings.cpp
index fd83cf0..0131b00 100644
--- a/pedalboard/python_bindings.cpp
+++ b/pedalboard/python_bindings.cpp
@@ -69,6 +69,7 @@ namespace py = pybind11;
#include "io/ResampledReadableAudioFile.h"
#include "io/StreamResampler.h"
#include "io/WriteableAudioFile.h"
+#include "io/WriteableAudioFileFlags.h"
using namespace Pedalboard;
@@ -248,6 +249,8 @@ If the number of samples and the number of channels are the same, each
io.doc() = "This module provides classes and functions for reading and "
"writing audio files or streams.\n\n*Introduced in v0.5.1.*";
+ init_writeable_audio_file_flags(io);
+
auto pyAudioFile = declare_audio_file(io);
auto pyReadableAudioFile = declare_readable_audio_file(io);
auto pyResampledReadableAudioFile = declare_resampled_readable_audio_file(io);
diff --git a/pedalboard_native/io/__init__.pyi b/pedalboard_native/io/__init__.pyi
index 4ad8369..d89dc1d 100644
--- a/pedalboard_native/io/__init__.pyi
+++ b/pedalboard_native/io/__init__.pyi
@@ -22,10 +22,57 @@ __all__ = [
"ResampledReadableAudioFile",
"StreamResampler",
"WriteableAudioFile",
+ "WriteableAudioFileFlag",
"get_supported_read_formats",
"get_supported_write_formats",
]
+class WriteableAudioFileFlag:
+ """
+ An enumeration of codec-specific options that can be passed when opening an
+ audio file for writing. These flags are used as keys in the ``codec_options``
+ dictionary parameter accepted by :class:`WriteableAudioFile` and
+ :class:`AudioFile`.
+
+ Not all flags are supported by all codecs. Passing an unsupported flag for
+ the selected codec will raise a ``ValueError``.
+
+ .. note::
+ These flags control low-level encoder behavior. Most users will not need
+ to use them. The ``quality`` parameter is usually sufficient for
+ controlling encoder output.
+
+ Members:
+
+ Mp3EnableBitReservoir :
+ When writing MP3 files, controls whether the LAME encoder's bit reservoir
+ is enabled. Defaults to ``True``.
+ """
+
+ Mp3EnableBitReservoir: typing.ClassVar[WriteableAudioFileFlag]
+ """
+ When writing MP3 files, controls whether the LAME encoder's bit reservoir
+ is enabled. The bit reservoir allows the encoder to use fewer bits on
+ simple frames and save them for complex frames, improving overall quality
+ at a given bitrate. Disabling it forces each frame to be independently
+ decodable at the cost of slightly lower quality.
+
+ Set to ``False`` for streaming or seeking applications where individual
+ frames need to be independently decodable.
+
+ Accepts a ``bool`` value. Defaults to ``True`` (bit reservoir enabled).
+ """
+
+ def __eq__(self, other: object) -> bool: ...
+ def __hash__(self) -> int: ...
+ def __index__(self) -> int: ...
+ def __int__(self) -> int: ...
+ def __ne__(self, other: object) -> bool: ...
+ @property
+ def name(self) -> str: ...
+ @property
+ def value(self) -> int: ...
+
class AudioFile:
"""
A base class for readable and writeable audio files.
@@ -150,6 +197,7 @@ class AudioFile:
num_channels: int = 1,
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> WriteableAudioFile: ...
@classmethod
@@ -163,6 +211,7 @@ class AudioFile:
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
format: typing.Optional[str] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> WriteableAudioFile: ...
@staticmethod
@@ -173,6 +222,7 @@ class AudioFile:
num_channels: int = 1,
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> bytes:
"""
Encode an audio buffer to a Python :class:`bytes` object.
@@ -1038,6 +1088,7 @@ class WriteableAudioFile(AudioFile):
num_channels: int = 1,
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> None: ...
@typing.overload
def __init__(
@@ -1048,6 +1099,7 @@ class WriteableAudioFile(AudioFile):
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
format: typing.Optional[str] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> None: ...
@classmethod
@typing.overload
@@ -1058,6 +1110,7 @@ class WriteableAudioFile(AudioFile):
num_channels: int = 1,
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> WriteableAudioFile: ...
@classmethod
@typing.overload
@@ -1069,6 +1122,7 @@ class WriteableAudioFile(AudioFile):
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
format: typing.Optional[str] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> WriteableAudioFile: ...
# This overload does not actually exist; just makes Pyright happy as
@@ -1082,6 +1136,7 @@ class WriteableAudioFile(AudioFile):
num_channels: int = 1,
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> None: ...
# This overload does not actually exist; just makes Pyright happy as
@@ -1096,6 +1151,7 @@ class WriteableAudioFile(AudioFile):
bit_depth: int = 16,
quality: typing.Optional[typing.Union[str, float]] = None,
format: typing.Optional[str] = None,
+ codec_options: typing.Dict[WriteableAudioFileFlag, typing.Union[bool, float, int, str]] = ...,
) -> None: ...
def __repr__(self) -> str: ...
diff --git a/tests/test_io.py b/tests/test_io.py
index b9457d8..3bf1ed1 100644
--- a/tests/test_io.py
+++ b/tests/test_io.py
@@ -1719,3 +1719,144 @@ def test_errno_cleared_after_python_file_operations(format_name: str):
with pedalboard.io.AudioFile(ErrnoTriggeringFileLike(buf)) as af:
assert af.samplerate == 44100
+
+
[email protected]("samplerate", [44100, 48000])
[email protected]("num_channels", [1, 2])
+def test_mp3_codec_options_bit_reservoir_disabled(samplerate: int, num_channels: int):
+ """
+ Writing an MP3 with the bit reservoir disabled should produce a valid file
+ that can be read back. Each frame is independently decodable, so the file
+ may be slightly larger than an equivalent file with the reservoir enabled.
+ """
+ audio = generate_sine_at(samplerate, num_channels=num_channels)
+
+ buffers = {}
+ for enable_reservoir in (True, False):
+ buf = io.BytesIO()
+ with pedalboard.io.WriteableAudioFile(
+ buf,
+ samplerate,
+ num_channels,
+ format="mp3",
+ quality="128 kbps",
+ codec_options={
+ pedalboard.io.WriteableAudioFileFlag.Mp3EnableBitReservoir: enable_reservoir
+ },
+ ) as af:
+ af.write(audio)
+ buffers[enable_reservoir] = buf
+
+ # Both files should be readable:
+ for buf in buffers.values():
+ buf.seek(0)
+ with pedalboard.io.ReadableAudioFile(buf) as af:
+ assert af.samplerate == samplerate
+ assert af.num_channels == num_channels
+ assert af.frames > 0
+
+ # Without the bit reservoir, files are typically at least as large
+ # (each frame must be self-contained):
+ assert len(buffers[False].getvalue()) >= len(buffers[True].getvalue())
+
+
+def test_mp3_codec_options_default_matches_no_options():
+ """
+ Passing Mp3EnableBitReservoir=True (the default) should produce identical
+ output to not passing any codec_options at all.
+ """
+ samplerate = 44100
+ num_channels = 1
+ audio = generate_sine_at(samplerate, num_channels=num_channels)
+
+ buf_default = io.BytesIO()
+ with pedalboard.io.WriteableAudioFile(
+ buf_default, samplerate, num_channels, format="mp3", quality="128 kbps"
+ ) as af:
+ af.write(audio)
+
+ buf_explicit = io.BytesIO()
+ with pedalboard.io.WriteableAudioFile(
+ buf_explicit,
+ samplerate,
+ num_channels,
+ format="mp3",
+ quality="128 kbps",
+ codec_options={pedalboard.io.WriteableAudioFileFlag.Mp3EnableBitReservoir: True},
+ ) as af:
+ af.write(audio)
+
+ assert buf_default.getvalue() == buf_explicit.getvalue()
+
+
+def test_codec_options_via_audio_file_constructor():
+ """
+ codec_options should work when opening files via AudioFile("w") as well.
+ """
+ audio = generate_sine_at(44100, num_channels=1)
+
+ buf = io.BytesIO()
+ with pedalboard.io.AudioFile(
+ buf,
+ "w",
+ samplerate=44100,
+ num_channels=1,
+ format="mp3",
+ codec_options={pedalboard.io.WriteableAudioFileFlag.Mp3EnableBitReservoir: False},
+ ) as af:
+ af.write(audio)
+
+ buf.seek(0)
+ with pedalboard.io.AudioFile(buf) as af:
+ assert af.samplerate == 44100
+ assert af.frames > 0
+
+
+def test_codec_options_via_encode():
+ """
+ codec_options should work through AudioFile.encode() as well.
+ """
+ audio = generate_sine_at(44100, num_channels=1).astype(np.float32)
+
+ result_default = pedalboard.io.AudioFile.encode(audio, 44100, "mp3", quality="128 kbps")
+ result_no_reservoir = pedalboard.io.AudioFile.encode(
+ audio,
+ 44100,
+ "mp3",
+ quality="128 kbps",
+ codec_options={pedalboard.io.WriteableAudioFileFlag.Mp3EnableBitReservoir: False},
+ )
+
+ assert len(result_default) > 0
+ assert len(result_no_reservoir) > 0
+ assert len(result_no_reservoir) >= len(result_default)
+
+
+def test_codec_options_unsupported_format():
+ """
+ Passing an MP3-specific codec option to a non-MP3 format should raise.
+ """
+ buf = io.BytesIO()
+ with pytest.raises(Exception, match="not supported"):
+ pedalboard.io.WriteableAudioFile(
+ buf,
+ 44100,
+ 1,
+ format="wav",
+ codec_options={pedalboard.io.WriteableAudioFileFlag.Mp3EnableBitReservoir: True},
+ )
+
+
+def test_codec_options_wrong_type():
+ """
+ Passing a non-bool value to Mp3EnableBitReservoir should raise.
+ """
+ buf = io.BytesIO()
+ with pytest.raises(Exception, match="bool"):
+ pedalboard.io.WriteableAudioFile(
+ buf,
+ 44100,
+ 1,
+ format="mp3",
+ codec_options={pedalboard.io.WriteableAudioFileFlag.Mp3EnableBitReservoir: "yes"},
+ )