Blame SOURCES/md_size.diff

feb818
From: Kurt Roeckx <kurt@roeckx.be>
feb818
Date: Sun, 28 Jan 2018 15:44:08 +0100
feb818
Subject: Check the size of the main data
feb818
feb818
The main data to decode a frame can come from the current frame and part of the
feb818
previous frame, the so called bit reservoir. si.main_data_begin is the part of
feb818
the previous frame we need for this frame. frame_space is the amount of main
feb818
data that can be in this frame, and next_md_begin is the part of this frame that
feb818
is going to be used for the next frame.
feb818
feb818
The maximum amount of data from a previous frame that the format allows is 511
feb818
bytes. The maximum frame size for the defined bitrates is at MPEG 2.5 layer 2
feb818
at 320 kbit/s and 8 kHz sample rate which gives 72 * (320000 / 8000) + 1 = 2881.
feb818
So those defines are not large enough:
feb818
 # define MAD_BUFFER_GUARD      8
feb818
 # define MAD_BUFFER_MDLEN      (511 + 2048 + MAD_BUFFER_GUARD)
feb818
feb818
There is also support for a "free" bitrate which allows you to create any frame
feb818
size, which can be larger than the buffer.
feb818
feb818
Changing the defines is not an option since it's part of the ABI, so we check
feb818
that the main data fits in the bufer.
feb818
feb818
The previous frame data is stored in *stream->main_data and contains
feb818
stream->md_len bytes. If stream->md_len is larger than the data we
feb818
need from the previous frame (si.main_data_begin) it still wouldn't fit
feb818
in the buffer, so just keep the data that we need.
feb818
feb818
Index: libmad-0.15.1b/layer3.c
feb818
===================================================================
feb818
--- libmad-0.15.1b.orig/layer3.c
feb818
+++ libmad-0.15.1b/layer3.c
feb818
@@ -2608,6 +2608,11 @@ int mad_layer_III(struct mad_stream *str
feb818
     next_md_begin = 0;
feb818
 
feb818
   md_len = si.main_data_begin + frame_space - next_md_begin;
feb818
+  if (md_len + MAD_BUFFER_GUARD > MAD_BUFFER_MDLEN) {
feb818
+    stream->error = MAD_ERROR_LOSTSYNC;
feb818
+    stream->sync = 0;
feb818
+    return -1;
feb818
+  }
feb818
 
feb818
   frame_used = 0;
feb818
 
feb818
@@ -2625,8 +2630,11 @@ int mad_layer_III(struct mad_stream *str
feb818
       }
feb818
     }
feb818
     else {
feb818
-      mad_bit_init(&ptr,
feb818
-		   *stream->main_data + stream->md_len - si.main_data_begin);
feb818
+      memmove(stream->main_data,
feb818
+	*stream->main_data + stream->md_len - si.main_data_begin,
feb818
+	si.main_data_begin);
feb818
+      stream->md_len = si.main_data_begin;
feb818
+      mad_bit_init(&ptr, *stream->main_data);
feb818
 
feb818
       if (md_len > si.main_data_begin) {
feb818
 	assert(stream->md_len + md_len -