Skip to content

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

Fix inaccuracy when reading integer-valued input formats.

Peter Sobotd870a2581145
diff --git a/pedalboard/io/AudioFile.h b/pedalboard/io/AudioFile.h
index 46f6228..0a35bc4 100644
--- a/pedalboard/io/AudioFile.h
+++ b/pedalboard/io/AudioFile.h
@@ -167,9 +167,51 @@ public:
channelPointers[c] = ((float *)outputInfo.ptr) + (numSamples * c);
}
- if (!reader->read(channelPointers, numChannels, currentPosition,
- numSamples)) {
- throw std::runtime_error("Failed to read from file.");
+ if (reader->usesFloatingPointData || reader->bitsPerSample == 32) {
+ if (!reader->read(channelPointers, numChannels, currentPosition,
+ numSamples)) {
+ throw std::runtime_error("Failed to read from file.");
+ }
+ } else {
+ // If the audio is stored in an integral format, read it as integers
+ // and do the floating-point conversion ourselves to work around
+ // floating-point imprecision in JUCE when reading formats smaller than
+ // 32-bit (i.e.: 16-bit audio is off by about 0.003%)
+
+ if (!reader->readSamples((int **)channelPointers, numChannels, 0,
+ currentPosition, numSamples)) {
+ throw std::runtime_error("Failed to read from file.");
+ }
+
+ // When converting 24-bit, 16-bit, or 8-bit data from int to float,
+ // the values provided by the above read() call are shifted left
+ // (such that the least significant bits are all zero)
+ // JUCE will then divide these values by 0x7FFFFFFF, even though
+ // the least significant bits are zero, effectively losing precision.
+ // Instead, here we set the scale factor appropriately.
+ int maxValueAsInt;
+ switch (reader->bitsPerSample) {
+ case 24:
+ maxValueAsInt = 0x7FFFFF00;
+ break;
+ case 16:
+ maxValueAsInt = 0x7FFF0000;
+ break;
+ case 8:
+ maxValueAsInt = 0x7F000000;
+ break;
+ default:
+ throw std::runtime_error("Not sure how to convert data from " +
+ std::to_string(reader->bitsPerSample) +
+ " bits per sample to floating point!");
+ }
+ float scaleFactor = 1.0f / static_cast<float>(maxValueAsInt);
+
+ for (int c = 0; c < numChannels; c++) {
+ juce::FloatVectorOperations::convertFixedToFloat(
+ channelPointers[c], (const int *)channelPointers[c], scaleFactor,
+ numSamples);
+ }
}
}
diff --git a/tests/test_io.py b/tests/test_io.py
index 98d1147..b43b02b 100644
--- a/tests/test_io.py
+++ b/tests/test_io.py
@@ -331,7 +331,7 @@ def test_basic_write(
np.testing.assert_allclose(original_audio, np.squeeze(as_written), atol=tolerance)
-def test_write_exact_int32_wav(tmp_path: pathlib.Path):
+def test_write_exact_int32_to_16_bit_wav(tmp_path: pathlib.Path):
"""
This test should fail on Windows, where it seems that passing int32 sample
data to WriteableAudioFile#write will invert (!?) the samples written.
@@ -352,6 +352,55 @@ def test_write_exact_int32_wav(tmp_path: pathlib.Path):
np.testing.assert_allclose(encoded, original)
+def test_read_16_bit_wav_matches_stdlib(tmp_path: pathlib.Path):
+ filename = str(tmp_path / f"test-16bit.wav")
+ original = np.array([1, 2, 3, -1, -2, -3]).astype(np.int32)
+ signal = (original << 16).astype(np.int32)
+
+ with pedalboard.io.WriteableAudioFile(filename, samplerate=1) as af:
+ af.write(signal)
+
+ assert os.path.exists(filename)
+
+ # Read the exact wave values out with the `wave` package:
+ with wave.open(filename) as f:
+ assert f.getsampwidth() == 2
+ stdlib_result = np.frombuffer(f.readframes(len(signal)), dtype=np.int16)
+ np.testing.assert_allclose(stdlib_result, original)
+
+ float_signal = signal / np.iinfo(np.int32).max
+ with pedalboard.io.AudioFile(filename) as af:
+ np.testing.assert_allclose(float_signal, af.read(af.frames)[0])
+
+
+def test_basic_write_int32_to_16_bit_wav(tmp_path: pathlib.Path):
+ samplerate = 44100
+ num_channels = 1
+ filename = str(tmp_path / f"test.wav")
+ original = np.linspace(0, 1, 11)
+
+ # As per AES17: the integer value -(2^31) should never show up in the stream.
+ signal = (original * (2**31 - 1)).astype(np.int32)
+
+ with pedalboard.io.WriteableAudioFile(
+ filename,
+ samplerate=samplerate,
+ num_channels=num_channels,
+ bit_depth=16,
+ ) as af:
+ af.write(signal)
+
+ # Read the exact wave values out with the `wave` package:
+ with wave.open(filename) as f:
+ assert f.getsampwidth() == 2
+ stdlib_result = np.frombuffer(f.readframes(len(signal)), dtype=np.int16)
+ assert np.all(np.equal(stdlib_result, signal >> 16))
+
+ with pedalboard.io.ReadableAudioFile(filename) as af:
+ as_written = af.read(len(signal))[0]
+ np.testing.assert_allclose(original, as_written, atol=2 / (2**15))
+
+
@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())
@pytest.mark.parametrize("samplerate", [1234.5, 23.0000000001])
def test_fractional_sample_rates(tmp_path: pathlib.Path, extension: str, samplerate):