Skip to content

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

Properly support parsing MP3 files without headers. (#264)

Peter Sobot4012eba1bb81
diff --git a/pedalboard/juce_overrides/juce_PatchedMP3AudioFormat.cpp b/pedalboard/juce_overrides/juce_PatchedMP3AudioFormat.cpp
index d618647..add0ef6 100644
--- a/pedalboard/juce_overrides/juce_PatchedMP3AudioFormat.cpp
+++ b/pedalboard/juce_overrides/juce_PatchedMP3AudioFormat.cpp
@@ -2125,11 +2125,10 @@ private:
auto oldPos = stream.getPosition();
int offset = -3;
uint32 header = 0;
- bool isFirstScanAtThisPosition = true;
+ bool isParsingFirstFrame = oldPos == 0;
for (;;) {
auto streamPos = stream.getPosition();
- bool isParsingFirstFrame = streamPos == 0;
if (stream.isExhausted() || streamPos > oldPos + 32768) {
offset = -1;
@@ -2156,15 +2155,22 @@ private:
break;
}
- if (isFirstScanAtThisPosition && isParsingFirstFrame) {
+ if (isParsingFirstFrame && offset == 0) {
// If we're parsing the first frame of a file/stream, that frame must be
- // at the start of the stream. This prevents accidentally parsing .mp4
- // files (among others) as MP3 files that start with junk.
+ // at the start of the stream (i.e.: the first four bytes must be a
+ // valid MP3 header).
+ //
+ // If the first four bytes were a valid MP3 header, the above `if (...
+ // isValidHeader)` check would have exited the `for` loop, and we'd
+ // never get here.
+ //
+ // This prevents accidentally parsing .mp4 files (among others) as MP3
+ // files that start with junk.
+ offset = -1;
break;
}
++offset;
- isFirstScanAtThisPosition = false;
}
if (offset >= 0) {
diff --git a/tests/audio/correct/no_header.mp3 b/tests/audio/correct/no_header.mp3
new file mode 100644
index 0000000..beb637c
Binary files /dev/null and b/tests/audio/correct/no_header.mp3 differ
diff --git a/tests/test_io.py b/tests/test_io.py
index a98e9a4..a7025b7 100644
--- a/tests/test_io.py
+++ b/tests/test_io.py
@@ -1052,6 +1052,13 @@ def test_real_mp3_parsing_with_lyrics3():
assert f.read(f.frames).shape[1] == f.frames
+def test_real_mp3_parsing_with_no_header():
+ filename = os.path.join(os.path.dirname(__file__), "audio", "correct", "no_header.mp3")
+ with pedalboard.io.AudioFile(filename) as f:
+ assert f.frames >= 40000 and f.frames <= 45000
+ assert f.read(f.frames).shape[1] == f.frames
+
+
@pytest.mark.parametrize("samplerate", [44100, 32000])
@pytest.mark.parametrize("chunk_size", [1, 2, 16])
@pytest.mark.parametrize("target_samplerate", [44100, 32000, 22050, 1234.56])