From b7cb0ee8e2542609fd68804c389fd3259468e3d4 Mon Sep 17 00:00:00 2001 From: "Earle F. Philhower, III" Date: Mon, 11 May 2020 02:09:05 -0700 Subject: [PATCH] Redo the last packet handling of the MP3 decoder (#266) Keep track of how many values are actually good in the buffer (before it was always guaranteed to be the full size) and when EOF is detected, only shift out valid, good bytes, and return STOP when the unused bytes are 0 or unchanged from the last pass. Fixes #265 --- src/AudioGeneratorMP3.cpp | 18 ++++++++---------- src/AudioGeneratorMP3.h | 2 +- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/AudioGeneratorMP3.cpp b/src/AudioGeneratorMP3.cpp index 1f45cfc..7c09289 100644 --- a/src/AudioGeneratorMP3.cpp +++ b/src/AudioGeneratorMP3.cpp @@ -108,16 +108,12 @@ enum mad_flow AudioGeneratorMP3::Input() int unused = 0; if (stream->next_frame) { - unused = buffLen - (stream->next_frame - buff); + unused = lastBuffLen - (stream->next_frame - buff); memmove(buff, stream->next_frame, unused); stream->next_frame = NULL; } - if (finishing && (unused == buffLen - 1)) { - return MAD_FLOW_STOP; - } - - if (unused == buffLen) { + if (unused == lastBuffLen) { // Something wicked this way came, throw it all out and try again unused = 0; } @@ -125,11 +121,13 @@ enum mad_flow AudioGeneratorMP3::Input() lastReadPos = file->getPos() - unused; int len = buffLen - unused; len = file->read(buff + unused, len); - if (len == 0) { - finishing = true; + if ((len == 0) && (unused == 0)) { + // Can't read any from the file, and we don't have anything left. It's done.... + return MAD_FLOW_STOP; } - mad_stream_buffer(stream, buff, len + unused); + lastBuffLen = len + unused; + mad_stream_buffer(stream, buff, lastBuffLen); return MAD_FLOW_CONTINUE; } @@ -242,7 +240,7 @@ bool AudioGeneratorMP3::begin(AudioFileSource *source, AudioOutput *output) lastRate = 0; lastChannels = 0; lastReadPos = 0; - finishing = false; + lastBuffLen = 0; // Allocate all large memory chunks if (preallocateSpace) { diff --git a/src/AudioGeneratorMP3.h b/src/AudioGeneratorMP3.h index b1b82d6..750ceca 100644 --- a/src/AudioGeneratorMP3.h +++ b/src/AudioGeneratorMP3.h @@ -43,9 +43,9 @@ class AudioGeneratorMP3 : public AudioGenerator const int buffLen = 0x600; // Slightly larger than largest MP3 frame unsigned char *buff; int lastReadPos; + int lastBuffLen; unsigned int lastRate; int lastChannels; - bool finishing; // Decoding bits bool madInitted;