Skip to content

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

Fix remaining MP3 tests.

Peter Sobotc1effefcaa13
diff --git a/pedalboard/io/LameMP3AudioFormat.h b/pedalboard/io/LameMP3AudioFormat.h
index f7dc587..a8f604c 100644
--- a/pedalboard/io/LameMP3AudioFormat.h
+++ b/pedalboard/io/LameMP3AudioFormat.h
@@ -23,6 +23,8 @@ extern "C" {
#include <lame.h>
}
+static const inline int MAXIMUM_MP3_FRAME_SIZE = 7200;
+
namespace Pedalboard {
class LameMP3AudioFormat : public juce::AudioFormat {
public:
@@ -76,9 +78,10 @@ public:
16) {
usesFloatingPointData = false;
- // Suppress all error logging from LAME
- // TODO: find out how to catch and report these errors to Python!
+ // Suppress all error logging from LAME directly to stdout
lame_set_errorf(encoder.getContext(), nullptr);
+ lame_set_debugf(encoder.getContext(), nullptr);
+ lame_set_msgf(encoder.getContext(), nullptr);
if (lame_set_in_samplerate(encoder.getContext(), sampleRate) != 0 ||
lame_set_out_samplerate(encoder.getContext(), sampleRate) != 0) {
@@ -94,14 +97,12 @@ public:
std::to_string(numChannels) + "-channel audio.)");
}
- if (lame_set_VBR(encoder.getContext(), vbr_default) != 0) {
- throw std::domain_error(
- "MP3 encoder failed to set variable bit rate flag.");
- }
-
- juce::StringArray opts(VBR_OPTIONS);
-
if (qualityOptionIndex < NUM_VBR_OPTIONS) {
+ if (lame_set_VBR(encoder.getContext(), vbr_default) != 0) {
+ throw std::domain_error(
+ "MP3 encoder failed to set variable bit rate flag.");
+ }
+
// VBR options:
if (lame_set_VBR_quality(encoder.getContext(), qualityOptionIndex) !=
0) {
@@ -111,6 +112,11 @@ public:
}
} else if (qualityOptionIndex <
(NUM_VBR_OPTIONS + juce::numElementsInArray(CBR_OPTIONS))) {
+ if (lame_set_VBR(encoder.getContext(), vbr_off) != 0) {
+ throw std::domain_error(
+ "MP3 encoder failed to set constant bit rate flag.");
+ }
+
// CBR options:
if (lame_set_brate(encoder.getContext(),
CBR_OPTIONS[qualityOptionIndex - NUM_VBR_OPTIONS]) !=
@@ -135,20 +141,27 @@ public:
// automatically deletes this pointer, and we don't want that
// to happen if our constructor fails.
output = destStream;
+ }
+
+ virtual ~Writer() override {
+ if (!output)
+ return;
+
+ std::vector<unsigned char> mp3buf(MAXIMUM_MP3_FRAME_SIZE);
- // Flush the initial header:
- const int *emptyBuffers[2] = {0};
- if (!write(emptyBuffers, 0)) {
- output = nullptr;
- throw std::runtime_error("Failed to write header!");
+ int bytesWritten =
+ lame_encode_flush(encoder.getContext(), mp3buf.data(), mp3buf.size());
+ if (bytesWritten > 0) {
+ output->write(mp3buf.data(), bytesWritten);
}
- }
- virtual ~Writer() override { flush(); };
+ writeVBRTag();
+ flush();
+ };
virtual bool write(const int **samplesToWrite, int numSamples) {
- // Constants from the LAME docs
- std::vector<unsigned char> encodedMp3Buffer(1.25 * numSamples + 7200);
+ std::vector<unsigned char> encodedMp3Buffer(1.25 * numSamples +
+ MAXIMUM_MP3_FRAME_SIZE);
std::vector<std::vector<short>> shortSamples(numChannels);
for (int c = 0; c < numChannels; c++) {
@@ -162,25 +175,63 @@ public:
encoder.getContext(), shortSamples[0].data(),
numChannels == 1 ? nullptr : shortSamples[1].data(), numSamples,
(unsigned char *)encodedMp3Buffer.data(), encodedMp3Buffer.size());
- return output->write((unsigned char *)encodedMp3Buffer.data(),
- mp3BufferBytesFilled);
+
+ if (mp3BufferBytesFilled < 0) {
+ return false;
+ }
+
+ if (mp3BufferBytesFilled) {
+ return output->write((unsigned char *)encodedMp3Buffer.data(),
+ mp3BufferBytesFilled);
+ }
+
+ return true;
}
virtual bool flush() {
if (!output)
return false;
+ output->flush();
+ return true;
+ }
- std::vector<unsigned char> mp3buf(7200); // Constant from the LAME docs
- int bytesWritten = lame_encode_flush_nogap(encoder.getContext(),
- mp3buf.data(), mp3buf.size());
+ void writeVBRTag() {
+ /**
+ * MP3 files in VBR mode are expected to have
+ * a single frame after their ID3 tags indicating
+ * information about how to seek through the
+ * file effectively.
+ *
+ * The LAME encoder automatically
+ * writes an empty frame at the start of the file
+ * with the expectation that the encoder will
+ * overwrite this frame once the file is done.
+ *
+ * LAME assumes we're writing to a file, which
+ * is not true here - we're writing to a seekable
+ * output stream, so we have to reimplement this
+ * logic ourselves.
+ */
+ if (!output)
+ return;
- if (bytesWritten < 0) {
- return false;
+ size_t currentPosition = output->getPosition();
+
+ uint8_t buffer[MAXIMUM_MP3_FRAME_SIZE];
+ size_t frameTagSize =
+ lame_get_lametag_frame(encoder.getContext(), buffer, sizeof(buffer));
+
+ if (frameTagSize > sizeof(buffer)) {
+ return;
+ } else if (frameTagSize < 1) {
+ return;
}
- output->write(mp3buf.data(), bytesWritten);
- output->flush();
- return true;
+ if (!output->write(buffer, frameTagSize)) {
+ return;
+ }
+
+ output->setPosition(currentPosition);
}
private:
diff --git a/pedalboard/io/WriteableAudioFile.h b/pedalboard/io/WriteableAudioFile.h
index 81731fa..8f650fa 100644
--- a/pedalboard/io/WriteableAudioFile.h
+++ b/pedalboard/io/WriteableAudioFile.h
@@ -462,10 +462,12 @@ public:
}
}
- if (!write(channelPointers, numChannels, samplesToWrite)) {
+ bool writeSuccessful =
+ write(channelPointers, numChannels, samplesToWrite);
+ PythonException::raise();
+ if (!writeSuccessful) {
throw std::runtime_error("Unable to write data to audio file.");
}
- PythonException::raise();
}
break;
@@ -477,10 +479,12 @@ public:
for (int c = 0; c < numChannels; c++) {
channelPointers[c] = ((SampleType *)inputInfo.ptr) + (numSamples * c);
}
- if (!write(channelPointers, numChannels, numSamples)) {
+
+ bool writeSuccessful = write(channelPointers, numChannels, numSamples);
+ PythonException::raise();
+ if (!writeSuccessful) {
throw std::runtime_error("Unable to write data to audio file.");
}
- PythonException::raise();
break;
}
default:
diff --git a/tests/test_io.py b/tests/test_io.py
index e02035e..4171541 100644
--- a/tests/test_io.py
+++ b/tests/test_io.py
@@ -442,12 +442,14 @@ def test_write_to_non_bytes_stream(extension: str):
expected_message = e.args[0]
with pytest.raises(TypeError) as e:
- pedalboard.io.AudioFile(stream, "w", 44100, 2, format=extension)
+ with pedalboard.io.AudioFile(stream, "w", 44100, 2, format=extension) as af:
+ af.write(np.random.rand(1, 2))
assert expected_message in str(e)
with pytest.raises(TypeError) as e:
- pedalboard.io.WriteableAudioFile(stream, 44100, 2, format=extension)
+ with pedalboard.io.WriteableAudioFile(stream, 44100, 2, format=extension) as af:
+ af.write(np.random.rand(1, 2))
assert expected_message in str(e)
@@ -527,6 +529,7 @@ def test_basic_write(
with pedalboard.io.ReadableAudioFile(filename) as af:
assert af.samplerate == samplerate
assert af.num_channels == num_channels
+ assert af.frames >= num_samples
tolerance = get_tolerance_for_format_and_bit_depth(extension, input_format, af.file_dtype)
as_written = af.read(num_samples)
np.testing.assert_allclose(original_audio, np.squeeze(as_written), atol=tolerance)
@@ -693,6 +696,39 @@ def test_fail_to_write_unsigned(tmp_path: pathlib.Path, dtype):
af.write(np.array([1, 2, 3, 4], dtype=dtype))
[email protected]("samplerate", [32000, 44100, 48000])
[email protected]("num_channels", [1, 2])
+ "qualities",
+ [
+ ["V9", "V8", "V7", "V6", "V5", "V4", "V3", "V2", "V1", "V0"],
+ [32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320],
+ ],
+)
+def test_mp3_write(samplerate: float, num_channels: int, qualities):
+ audio = generate_sine_at(samplerate, num_channels=num_channels)
+
+ file_sizes = []
+ for quality in qualities:
+ buffer = io.BytesIO()
+ with pedalboard.io.WriteableAudioFile(
+ buffer,
+ samplerate,
+ num_channels,
+ format="mp3",
+ quality=quality,
+ ) as af:
+ af.write(audio)
+ file_sizes.append(len(buffer.getvalue()))
+
+ # Assert that file sizes change as bitrate changes:
+ assert file_sizes == sorted(file_sizes)
+ # ...and that they don't all share the same output size:
+ # (note that this won't be true for VBR, because it's adaptive)
+ assert len(set(file_sizes)) >= len(file_sizes) // 2
+ assert len(set(file_sizes)) <= len(file_sizes)
+
+
@pytest.mark.parametrize(
"extension,quality,expected",
[