SDL_mixer: mp3_mad: fix crashes when wanted sample rate is higher than the file's.

From 2a5fe7973fc83b3c8323741c65c39f1aa13c413b Mon Sep 17 00:00:00 2001
From: Ozkan Sezer <[EMAIL REDACTED]>
Date: Sun, 4 Apr 2021 04:11:50 +0300
Subject: [PATCH] mp3_mad: fix crashes when wanted sample rate is higher than
 the file's.

The same fix for https://bugzilla.libsdl.org/show_bug.cgi?id=3886 which
was never applied to SDL-1.2 branch.
---
 music_mad.c | 12 +++++++++++-
 music_mad.h |  2 +-
 2 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/music_mad.c b/music_mad.c
index e99084b..d2051e1 100644
--- a/music_mad.c
+++ b/music_mad.c
@@ -52,6 +52,7 @@ mad_openFileRW(SDL_RWops *rw, SDL_AudioSpec *mixer, int freerw)
 	mp3_mad->output_begin = 0;
 	mp3_mad->output_end = 0;
 	mp3_mad->mixer = *mixer;
+	mp3_mad->output_buffer = NULL;
   }
   return mp3_mad;
 }
@@ -66,6 +67,7 @@ mad_closeFile(mad_data *mp3_mad)
   if (mp3_mad->freerw) {
 	SDL_RWclose(mp3_mad->mp3file.rw);
   }
+  SDL_free(mp3_mad->output_buffer);
   SDL_free(mp3_mad);
 }
 
@@ -186,7 +188,6 @@ decode_frame(mad_data *mp3_mad) {
 
   mad_synth_frame(&mp3_mad->synth, &mp3_mad->frame);
   pcm = &mp3_mad->synth.pcm;
-  out = mp3_mad->output_buffer + mp3_mad->output_end;
 
   if ((mp3_mad->status & MS_cvt_decoded) == 0) {
 	mp3_mad->status |= MS_cvt_decoded;
@@ -197,6 +198,15 @@ decode_frame(mad_data *mp3_mad) {
 	SDL_BuildAudioCVT(&mp3_mad->cvt, AUDIO_S16, pcm->channels, mp3_mad->frame.header.samplerate, mp3_mad->mixer.format, mp3_mad->mixer.channels, mp3_mad->mixer.freq);
   }
 
+  if (!mp3_mad->output_buffer) {
+    size_t sz = MAD_OUTPUT_BUFFER_SIZE;
+    if (mp3_mad->cvt.len_mult > 1) {
+        sz *= mp3_mad->cvt.len_mult;
+    }
+    mp3_mad->output_buffer = (unsigned char *) SDL_malloc(sz);
+  }
+  out = mp3_mad->output_buffer + mp3_mad->output_end;
+
   /* pcm->samplerate contains the sampling frequency */
 
   nchannels = pcm->channels;
diff --git a/music_mad.h b/music_mad.h
index 81019fb..faa9660 100644
--- a/music_mad.h
+++ b/music_mad.h
@@ -56,7 +56,7 @@ typedef struct {
   SDL_AudioCVT cvt;
 
   unsigned char input_buffer[MAD_INPUT_BUFFER_SIZE + MAD_BUFFER_GUARD];
-  unsigned char output_buffer[MAD_OUTPUT_BUFFER_SIZE];
+  unsigned char *output_buffer;
 } mad_data;
 
 mad_data *mad_openFileRW(SDL_RWops *rw, SDL_AudioSpec *mixer, int freerw);