Fixed bug 3894 - Fuzzing crashes for SDL_LoadWAV
authorSam Lantinga
Sat, 08 Jun 2019 19:02:42 -0700
changeset 12806b06fa7da012b
parent 12805 00a1aa5a1fc0
child 12807 a39d8cdf50f4
Fixed bug 3894 - Fuzzing crashes for SDL_LoadWAV

Simon Hug

I had a look at this and made some additions to SDL_wave.c.

The attached patch adds many checks and error messages. For some reason I also added A-law and µ-law decoders. Forgot exactly why... but hey, they're small.

The WAVE format is seriously underspecified (at least by the documents that are publicly available on the internet) and it's a shame Microsoft never put something better out there. The language used in them is so loose at times, it's not surprising the encoders and decoders behave very differently. The Windows Media Player doesn't even support MS ADPCM correctly.

The patch also adds some hints to make the decoder more strict at the cost of compatibility with weird WAVE files.

I still think it needs a bit of cleaning up (Not happy with the MultiplySize function. Don't like the name and other SDL code may want to use something like this too.) and some duplicated code may be folded together. It does work in this state and I have thrown all kinds of WAVE files at it. The AFL files also pass with it and some even play (obviously just noise). Crafty little fuzzer.

Any critique would be welcome. I have a fork of SDL with a audio-loadwav branch over here if someone wants to use the commenting feature of Bitbucket:

https://bitbucket.org/ChliHug/SDL

I also cobbled some Lua scripts together to create WAVE test files:

https://bitbucket.org/ChliHug/gendat
include/SDL_audio.h
include/SDL_hints.h
src/audio/SDL_wave.c
src/audio/SDL_wave.h
     1.1 --- a/include/SDL_audio.h	Sat Jun 08 18:40:11 2019 -0700
     1.2 +++ b/include/SDL_audio.h	Sat Jun 08 19:02:42 2019 -0700
     1.3 @@ -420,23 +420,56 @@
     1.4  /* @} *//* Pause audio functions */
     1.5  
     1.6  /**
     1.7 - *  This function loads a WAVE from the data source, automatically freeing
     1.8 - *  that source if \c freesrc is non-zero.  For example, to load a WAVE file,
     1.9 - *  you could do:
    1.10 + *  \brief Load the audio data of a WAVE file into memory
    1.11 + *
    1.12 + *  Loading a WAVE file requires \c src, \c spec, \c audio_buf and \c audio_len
    1.13 + *  to be valid pointers. The entire data portion of the file is then loaded
    1.14 + *  into memory and decoded if necessary.
    1.15 + *
    1.16 + *  If \c freesrc is non-zero, the data source gets automatically closed and
    1.17 + *  freed before the function returns.
    1.18 + *
    1.19 + *  Supported are RIFF WAVE files with the formats PCM (8, 16, 24, and 32 bits),
    1.20 + *  IEEE Float (32 bits), Microsoft ADPCM and IMA ADPCM (4 bits), and A-law and
    1.21 + *  µ-law (8 bits). Other formats are currently unsupported and cause an error.
    1.22 + *
    1.23 + *  If this function succeeds, the pointer returned by it is equal to \c spec
    1.24 + *  and the pointer to the audio data allocated by the function is written to
    1.25 + *  \c audio_buf and its length in bytes to \c audio_len. The \ref SDL_AudioSpec
    1.26 + *  members \c freq, \c channels, and \c format are set to the values of the
    1.27 + *  audio data in the buffer. The \c samples member is set to a sane default and
    1.28 + *  all others are set to zero.
    1.29 + *
    1.30 + *  It's necessary to use SDL_FreeWAV() to free the audio data returned in
    1.31 + *  \c audio_buf when it is no longer used.
    1.32 + *
    1.33 + *  Because of the underspecification of the Waveform format, there are many
    1.34 + *  problematic files in the wild that cause issues with strict decoders. To
    1.35 + *  provide compatibility with these files, this decoder is lenient in regards
    1.36 + *  to the truncation of the file, the fact chunk, and the size of the RIFF
    1.37 + *  chunk. The hints SDL_HINT_WAVE_RIFF_CHUNK_SIZE, SDL_HINT_WAVE_TRUNCATION,
    1.38 + *  and SDL_HINT_WAVE_FACT_CHUNK can be used to tune the behavior of the
    1.39 + *  loading process.
    1.40 + *
    1.41 + *  Any file that is invalid (due to truncation, corruption, or wrong values in
    1.42 + *  the headers), too big, or unsupported causes an error. Additionally, any
    1.43 + *  critical I/O error from the data source will terminate the loading process
    1.44 + *  with an error. The function returns NULL on error and in all cases (with the
    1.45 + *  exception of \c src being NULL), an appropriate error message will be set.
    1.46 + *
    1.47 + *  It is required that the data source supports seeking.
    1.48 + *
    1.49 + *  Example:
    1.50   *  \code
    1.51   *      SDL_LoadWAV_RW(SDL_RWFromFile("sample.wav", "rb"), 1, ...);
    1.52   *  \endcode
    1.53   *
    1.54 - *  If this function succeeds, it returns the given SDL_AudioSpec,
    1.55 - *  filled with the audio data format of the wave data, and sets
    1.56 - *  \c *audio_buf to a malloc()'d buffer containing the audio data,
    1.57 - *  and sets \c *audio_len to the length of that audio buffer, in bytes.
    1.58 - *  You need to free the audio buffer with SDL_FreeWAV() when you are
    1.59 - *  done with it.
    1.60 - *
    1.61 - *  This function returns NULL and sets the SDL error message if the
    1.62 - *  wave file cannot be opened, uses an unknown data format, or is
    1.63 - *  corrupt.  Currently raw and MS-ADPCM WAVE files are supported.
    1.64 + *  \param src The data source with the WAVE data
    1.65 + *  \param freesrc A integer value that makes the function close the data source if non-zero
    1.66 + *  \param spec A pointer filled with the audio format of the audio data
    1.67 + *  \param audio_buf A pointer filled with the audio data allocated by the function
    1.68 + *  \param audio_len A pointer filled with the length of the audio data buffer in bytes
    1.69 + *  \return NULL on error, or non-NULL on success.
    1.70   */
    1.71  extern DECLSPEC SDL_AudioSpec *SDLCALL SDL_LoadWAV_RW(SDL_RWops * src,
    1.72                                                        int freesrc,
     2.1 --- a/include/SDL_hints.h	Sat Jun 08 18:40:11 2019 -0700
     2.2 +++ b/include/SDL_hints.h	Sat Jun 08 19:02:42 2019 -0700
     2.3 @@ -1122,6 +1122,70 @@
     2.4  
     2.5  
     2.6  /**
     2.7 + *  \brief  Controls how the size of the RIFF chunk affects the loading of a WAVE file.
     2.8 + *
     2.9 + *  The size of the RIFF chunk (which includes all the sub-chunks of the WAVE
    2.10 + *  file) is not always reliable. In case the size is wrong, it's possible to
    2.11 + *  just ignore it and step through the chunks until a fixed limit is reached.
    2.12 + *
    2.13 + *  Note that files that have trailing data unrelated to the WAVE file or
    2.14 + *  corrupt files may slow down the loading process without a reliable boundary.
    2.15 + *  By default, SDL stops after 10000 chunks to prevent wasting time. Use the
    2.16 + *  environment variable SDL_WAVE_CHUNK_LIMIT to adjust this value.
    2.17 + *
    2.18 + *  This variable can be set to the following values:
    2.19 + *
    2.20 + *    "chunksearch"  - Use the RIFF chunk size as a boundary for the chunk search
    2.21 + *    "ignorezero"   - Like "chunksearch", but a zero size searches up to 4 GiB (default)
    2.22 + *    "ignore"       - Ignore the RIFF chunk size and always search up to 4 GiB
    2.23 + *    "maximum"      - Search for chunks until the end of file (not recommended)
    2.24 + */
    2.25 +#define SDL_HINT_WAVE_RIFF_CHUNK_SIZE   "SDL_WAVE_RIFF_CHUNK_SIZE"
    2.26 +
    2.27 +/**
    2.28 + *  \brief  Controls how a truncated WAVE file is handled.
    2.29 + *
    2.30 + *  A WAVE file is considered truncated if any of the chunks are incomplete or
    2.31 + *  the data chunk size is not a multiple of the block size. By default, SDL
    2.32 + *  decodes until the first incomplete block, as most applications seem to do.
    2.33 + *
    2.34 + *  This variable can be set to the following values:
    2.35 + *
    2.36 + *    "verystrict" - Raise an error if the file is truncated
    2.37 + *    "strict"     - Like "verystrict", but the size of the RIFF chunk is ignored
    2.38 + *    "dropframe"  - Decode until the first incomplete sample frame
    2.39 + *    "dropblock"  - Decode until the first incomplete block (default)
    2.40 + */
    2.41 +#define SDL_HINT_WAVE_TRUNCATION   "SDL_WAVE_TRUNCATION"
    2.42 +
    2.43 +/**
    2.44 + *  \brief  Controls how the fact chunk affects the loading of a WAVE file.
    2.45 + *
    2.46 + *  The fact chunk stores information about the number of samples of a WAVE
    2.47 + *  file. The Standards Update from Microsoft notes that this value can be used
    2.48 + *  to 'determine the length of the data in seconds'. This is especially useful
    2.49 + *  for compressed formats (for which this is a mandatory chunk) if they produce
    2.50 + *  multiple sample frames per block and truncating the block is not allowed.
    2.51 + *  The fact chunk can exactly specify how many sample frames there should be
    2.52 + *  in this case.
    2.53 + *
    2.54 + *  Unfortunately, most application seem to ignore the fact chunk and so SDL
    2.55 + *  ignores it by default as well.
    2.56 + *
    2.57 + *  This variable can be set to the following values:
    2.58 + *
    2.59 + *    "truncate"    - Use the number of samples to truncate the wave data if
    2.60 + *                    the fact chunk is present and valid
    2.61 + *    "strict"      - Like "truncate", but raise an error if the fact chunk
    2.62 + *                    is invalid, not present for non-PCM formats, or if the
    2.63 + *                    data chunk doesn't have that many samples
    2.64 + *    "ignorezero"  - Like "truncate", but ignore fact chunk if the number of
    2.65 + *                    samples is zero
    2.66 + *    "ignore"      - Ignore fact chunk entirely (default)
    2.67 + */
    2.68 +#define SDL_HINT_WAVE_FACT_CHUNK   "SDL_WAVE_FACT_CHUNK"
    2.69 +
    2.70 +/**
    2.71   *  \brief  An enumeration of hint priorities
    2.72   */
    2.73  typedef enum
     3.1 --- a/src/audio/SDL_wave.c	Sat Jun 08 18:40:11 2019 -0700
     3.2 +++ b/src/audio/SDL_wave.c	Sat Jun 08 19:02:42 2019 -0700
     3.3 @@ -20,253 +20,849 @@
     3.4  */
     3.5  #include "../SDL_internal.h"
     3.6  
     3.7 +#ifdef HAVE_LIMITS_H
     3.8 +#include <limits.h>
     3.9 +#else
    3.10 +#ifndef SIZE_MAX
    3.11 +#define SIZE_MAX ((size_t)-1)
    3.12 +#endif
    3.13 +#ifndef INT_MAX
    3.14 +/* Make a lucky guess. */
    3.15 +#define INT_MAX (SDL_MAX_SINT32)
    3.16 +#endif
    3.17 +#endif
    3.18 +
    3.19  /* Microsoft WAVE file loading routines */
    3.20  
    3.21 +#include "SDL_log.h"
    3.22 +#include "SDL_hints.h"
    3.23  #include "SDL_audio.h"
    3.24  #include "SDL_wave.h"
    3.25  
    3.26 +/* Reads the value stored at the location of the f1 pointer, multiplies it
    3.27 + * with the second argument, and then stores it back to f1 again.
    3.28 + * Returns SDL_TRUE if the multiplication overflows, f1 does not get modified.
    3.29 + */
    3.30 +static SDL_bool
    3.31 +MultiplySize(size_t *f1, size_t f2)
    3.32 +{
    3.33 +    if (*f1 > 0 && SIZE_MAX / *f1 <= f2) {
    3.34 +        return SDL_TRUE;
    3.35 +    }
    3.36 +    *f1 *= f2;
    3.37 +    return SDL_FALSE;
    3.38 +}
    3.39  
    3.40 -static int ReadChunk(SDL_RWops * src, Chunk * chunk);
    3.41 +typedef struct ADPCM_DecoderState
    3.42 +{
    3.43 +    Uint32 channels;        /* Number of channels. */
    3.44 +    size_t blocksize;       /* Size of an ADPCM block in bytes. */
    3.45 +    size_t blockheadersize; /* Size of an ADPCM block header in bytes. */
    3.46 +    size_t samplesperblock; /* Number of samples per channel in an ADPCM block. */
    3.47 +    size_t framesize;       /* Size of a sample frame (16-bit PCM) in bytes. */
    3.48 +    Sint64 framestotal;     /* Total number of sample frames. */
    3.49 +    Sint64 framesleft;      /* Number of sample frames still to be decoded. */
    3.50 +    void *ddata;            /* Decoder data from initialization. */
    3.51 +    void *cstate;           /* Decoding state for each channel. */
    3.52 +
    3.53 +    /* ADPCM data. */
    3.54 +    struct {
    3.55 +        Uint8 *data;
    3.56 +        size_t size;
    3.57 +        size_t pos;
    3.58 +    } input;
    3.59 +
    3.60 +    /* Current ADPCM block in the ADPCM data above. */
    3.61 +    struct {
    3.62 +        Uint8 *data;
    3.63 +        size_t size;
    3.64 +        size_t pos;
    3.65 +    } block;
    3.66  
    3.67 -struct MS_ADPCM_decodestate
    3.68 +    /* Decoded 16-bit PCM data. */
    3.69 +    struct {
    3.70 +        Sint16 *data;
    3.71 +        size_t size;
    3.72 +        size_t pos;
    3.73 +    } output;
    3.74 +} ADPCM_DecoderState;
    3.75 +
    3.76 +typedef struct MS_ADPCM_CoeffData
    3.77 +{
    3.78 +    Uint16 coeffcount;
    3.79 +    Sint16 *coeff;
    3.80 +    Sint16 aligndummy; /* Has to be last member. */
    3.81 +} MS_ADPCM_CoeffData;
    3.82 +
    3.83 +typedef struct MS_ADPCM_ChannelState
    3.84 +{
    3.85 +    Uint16 delta;
    3.86 +    Sint16 coeff1;
    3.87 +    Sint16 coeff2;
    3.88 +} MS_ADPCM_ChannelState;
    3.89 +
    3.90 +#ifdef SDL_WAVE_DEBUG_LOG_FORMAT
    3.91 +static void
    3.92 +WaveDebugLogFormat(WaveFile *file)
    3.93  {
    3.94 -    Uint8 hPredictor;
    3.95 -    Uint16 iDelta;
    3.96 -    Sint16 iSamp1;
    3.97 -    Sint16 iSamp2;
    3.98 -};
    3.99 -static struct MS_ADPCM_decoder
   3.100 +    WaveFormat *format = &file->format;
   3.101 +    const char *fmtstr = "WAVE file: %s, %u Hz, %s, %u bits, %u %s/s";
   3.102 +    const char *waveformat, *wavechannel, *wavebpsunit = "B";
   3.103 +    Uint32 wavebps = format->byterate;
   3.104 +    char channelstr[64] = {0};
   3.105 +
   3.106 +    switch (format->encoding) {
   3.107 +    case PCM_CODE:
   3.108 +        waveformat = "PCM";
   3.109 +        break;
   3.110 +    case IEEE_FLOAT_CODE:
   3.111 +        waveformat = "IEEE Float";
   3.112 +        break;
   3.113 +    case ALAW_CODE:
   3.114 +        waveformat = "A-law";
   3.115 +        break;
   3.116 +    case MULAW_CODE:
   3.117 +        waveformat = "\xc2\xb5-law";
   3.118 +        break;
   3.119 +    case MS_ADPCM_CODE:
   3.120 +        waveformat = "MS ADPCM";
   3.121 +        break;
   3.122 +    case IMA_ADPCM_CODE:
   3.123 +        waveformat = "IMA ADPCM";
   3.124 +        break;
   3.125 +    default:
   3.126 +        waveformat = "Unknown";
   3.127 +        break;
   3.128 +    }
   3.129 +
   3.130 +#define SDL_WAVE_DEBUG_CHANNELCFG(STR, CODE) case CODE: wavechannel = STR; break;
   3.131 +#define SDL_WAVE_DEBUG_CHANNELSTR(STR, CODE) if (format->channelmask & CODE) { \
   3.132 +    SDL_strlcat(channelstr, channelstr[0] ? "-" STR : STR, sizeof(channelstr));}
   3.133 +
   3.134 +    if (format->formattag == EXTENSIBLE_CODE && format->channelmask > 0) {
   3.135 +        switch (format->channelmask) {
   3.136 +            SDL_WAVE_DEBUG_CHANNELCFG("1.0 Mono",         0x4)
   3.137 +            SDL_WAVE_DEBUG_CHANNELCFG("1.1 Mono",         0xc)
   3.138 +            SDL_WAVE_DEBUG_CHANNELCFG("2.0 Stereo",       0x3)
   3.139 +            SDL_WAVE_DEBUG_CHANNELCFG("2.1 Stereo",       0xb)
   3.140 +            SDL_WAVE_DEBUG_CHANNELCFG("3.0 Stereo",       0x7)
   3.141 +            SDL_WAVE_DEBUG_CHANNELCFG("3.1 Stereo",       0xf)
   3.142 +            SDL_WAVE_DEBUG_CHANNELCFG("3.0 Surround",     0x103)
   3.143 +            SDL_WAVE_DEBUG_CHANNELCFG("3.1 Surround",     0x10b)
   3.144 +            SDL_WAVE_DEBUG_CHANNELCFG("4.0 Quad",         0x33)
   3.145 +            SDL_WAVE_DEBUG_CHANNELCFG("4.1 Quad",         0x3b)
   3.146 +            SDL_WAVE_DEBUG_CHANNELCFG("4.0 Surround",     0x107)
   3.147 +            SDL_WAVE_DEBUG_CHANNELCFG("4.1 Surround",     0x10f)
   3.148 +            SDL_WAVE_DEBUG_CHANNELCFG("5.0",              0x37)
   3.149 +            SDL_WAVE_DEBUG_CHANNELCFG("5.1",              0x3f)
   3.150 +            SDL_WAVE_DEBUG_CHANNELCFG("5.0 Side",         0x607)
   3.151 +            SDL_WAVE_DEBUG_CHANNELCFG("5.1 Side",         0x60f)
   3.152 +            SDL_WAVE_DEBUG_CHANNELCFG("6.0",              0x137)
   3.153 +            SDL_WAVE_DEBUG_CHANNELCFG("6.1",              0x13f)
   3.154 +            SDL_WAVE_DEBUG_CHANNELCFG("6.0 Side",         0x707)
   3.155 +            SDL_WAVE_DEBUG_CHANNELCFG("6.1 Side",         0x70f)
   3.156 +            SDL_WAVE_DEBUG_CHANNELCFG("7.0",              0xf7)
   3.157 +            SDL_WAVE_DEBUG_CHANNELCFG("7.1",              0xff)
   3.158 +            SDL_WAVE_DEBUG_CHANNELCFG("7.0 Side",         0x6c7)
   3.159 +            SDL_WAVE_DEBUG_CHANNELCFG("7.1 Side",         0x6cf)
   3.160 +            SDL_WAVE_DEBUG_CHANNELCFG("7.0 Surround",     0x637)
   3.161 +            SDL_WAVE_DEBUG_CHANNELCFG("7.1 Surround",     0x63f)
   3.162 +            SDL_WAVE_DEBUG_CHANNELCFG("9.0 Surround",     0x5637)
   3.163 +            SDL_WAVE_DEBUG_CHANNELCFG("9.1 Surround",     0x563f)
   3.164 +            SDL_WAVE_DEBUG_CHANNELCFG("11.0 Surround",    0x56f7)
   3.165 +            SDL_WAVE_DEBUG_CHANNELCFG("11.1 Surround",    0x56ff)
   3.166 +        default:
   3.167 +            SDL_WAVE_DEBUG_CHANNELSTR("FL",  0x1)
   3.168 +            SDL_WAVE_DEBUG_CHANNELSTR("FR",  0x2)
   3.169 +            SDL_WAVE_DEBUG_CHANNELSTR("FC",  0x4)
   3.170 +            SDL_WAVE_DEBUG_CHANNELSTR("LF",  0x8)
   3.171 +            SDL_WAVE_DEBUG_CHANNELSTR("BL",  0x10)
   3.172 +            SDL_WAVE_DEBUG_CHANNELSTR("BR",  0x20)
   3.173 +            SDL_WAVE_DEBUG_CHANNELSTR("FLC", 0x40)
   3.174 +            SDL_WAVE_DEBUG_CHANNELSTR("FRC", 0x80)
   3.175 +            SDL_WAVE_DEBUG_CHANNELSTR("BC",  0x100)
   3.176 +            SDL_WAVE_DEBUG_CHANNELSTR("SL",  0x200)
   3.177 +            SDL_WAVE_DEBUG_CHANNELSTR("SR",  0x400)
   3.178 +            SDL_WAVE_DEBUG_CHANNELSTR("TC",  0x800)
   3.179 +            SDL_WAVE_DEBUG_CHANNELSTR("TFL", 0x1000)
   3.180 +            SDL_WAVE_DEBUG_CHANNELSTR("TFC", 0x2000)
   3.181 +            SDL_WAVE_DEBUG_CHANNELSTR("TFR", 0x4000)
   3.182 +            SDL_WAVE_DEBUG_CHANNELSTR("TBL", 0x8000)
   3.183 +            SDL_WAVE_DEBUG_CHANNELSTR("TBC", 0x10000)
   3.184 +            SDL_WAVE_DEBUG_CHANNELSTR("TBR", 0x20000)
   3.185 +            break;
   3.186 +        }
   3.187 +    } else {
   3.188 +        switch (format->channels) {
   3.189 +        default:
   3.190 +            if (SDL_snprintf(channelstr, sizeof(channelstr), "%u channels", format->channels) >= 0) {
   3.191 +                wavechannel = channelstr;
   3.192 +                break;
   3.193 +            }
   3.194 +        case 0:
   3.195 +            wavechannel = "Unknown";
   3.196 +            break;
   3.197 +        case 1:
   3.198 +            wavechannel = "Mono";
   3.199 +            break;
   3.200 +        case 2:
   3.201 +            wavechannel = "Setero";
   3.202 +            break;
   3.203 +        }
   3.204 +    }
   3.205 +
   3.206 +#undef SDL_WAVE_DEBUG_CHANNELCFG
   3.207 +#undef SDL_WAVE_DEBUG_CHANNELSTR
   3.208 +
   3.209 +    if (wavebps >= 1024) {
   3.210 +        wavebpsunit = "KiB";
   3.211 +        wavebps = wavebps / 1024 + (wavebps & 0x3ff ? 1 : 0);
   3.212 +    }
   3.213 +
   3.214 +    SDL_LogDebug(SDL_LOG_CATEGORY_AUDIO, fmtstr, waveformat, format->frequency, wavechannel, format->bitspersample, wavebps, wavebpsunit);
   3.215 +}
   3.216 +#endif
   3.217 +
   3.218 +#ifdef SDL_WAVE_DEBUG_DUMP_FORMAT
   3.219 +static void
   3.220 +WaveDebugDumpFormat(WaveFile *file, Uint32 rifflen, Uint32 fmtlen, Uint32 datalen)
   3.221  {
   3.222 -    WaveFMT wavefmt;
   3.223 -    Uint16 wSamplesPerBlock;
   3.224 -    Uint16 wNumCoef;
   3.225 -    Sint16 aCoeff[7][2];
   3.226 -    /* * * */
   3.227 -    struct MS_ADPCM_decodestate state[2];
   3.228 -} MS_ADPCM_state;
   3.229 +    WaveFormat *format = &file->format;
   3.230 +    const char *fmtstr1 = "WAVE chunk dump:\n"
   3.231 +        "-------------------------------------------\n"
   3.232 +        "RIFF                            %11u\n"
   3.233 +        "-------------------------------------------\n"
   3.234 +        "    fmt                         %11u\n"
   3.235 +        "        wFormatTag                   0x%04x\n"
   3.236 +        "        nChannels               %11u\n"
   3.237 +        "        nSamplesPerSec          %11u\n"
   3.238 +        "        nAvgBytesPerSec         %11u\n"
   3.239 +        "        nBlockAlign             %11u\n";
   3.240 +    const char *fmtstr2 = "        wBitsPerSample          %11u\n";
   3.241 +    const char *fmtstr3 = "        cbSize                  %11u\n";
   3.242 +    const char *fmtstr4a = "        wValidBitsPerSample     %11u\n";
   3.243 +    const char *fmtstr4b = "        wSamplesPerBlock        %11u\n";
   3.244 +    const char *fmtstr5 = "        dwChannelMask            0x%08x\n"
   3.245 +        "        SubFormat\n"
   3.246 +        "        %08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x\n";
   3.247 +    const char *fmtstr6 = "-------------------------------------------\n"
   3.248 +        " fact\n"
   3.249 +        "  dwSampleLength                %11u\n";
   3.250 +    const char *fmtstr7 = "-------------------------------------------\n"
   3.251 +        " data                           %11u\n"
   3.252 +        "-------------------------------------------\n";
   3.253 +    char *dumpstr;
   3.254 +    size_t dumppos = 0;
   3.255 +    const size_t bufsize = 1024;
   3.256 +    int res;
   3.257 +
   3.258 +    dumpstr = SDL_malloc(bufsize);
   3.259 +    if (dumpstr == NULL) {
   3.260 +        return;
   3.261 +    }
   3.262 +    dumpstr[0] = 0;
   3.263 +
   3.264 +    res = SDL_snprintf(dumpstr, bufsize, fmtstr1, rifflen, fmtlen, format->formattag, format->channels, format->frequency, format->byterate, format->blockalign);
   3.265 +    dumppos += res > 0 ? res : 0;
   3.266 +    if (fmtlen >= 16) {
   3.267 +        res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr2, format->bitspersample);
   3.268 +        dumppos += res > 0 ? res : 0;
   3.269 +    }
   3.270 +    if (fmtlen >= 18) {
   3.271 +        res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr3, format->extsize);
   3.272 +        dumppos += res > 0 ? res : 0;
   3.273 +    }
   3.274 +    if (format->formattag == EXTENSIBLE_CODE && fmtlen >= 40 && format->extsize >= 22) {
   3.275 +        const Uint8 *g = format->subformat;
   3.276 +        const Uint32 g1 = g[0] | ((Uint32)g[1] << 8) | ((Uint32)g[2] << 16) | ((Uint32)g[3] << 24);
   3.277 +        const Uint32 g2 = g[4] | ((Uint32)g[5] << 8);
   3.278 +        const Uint32 g3 = g[6] | ((Uint32)g[7] << 8);
   3.279 +
   3.280 +        switch (format->encoding) {
   3.281 +        default:
   3.282 +            res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4a, format->validsamplebits);
   3.283 +            dumppos += res > 0 ? res : 0;
   3.284 +            break;
   3.285 +        case MS_ADPCM_CODE:
   3.286 +        case IMA_ADPCM_CODE:
   3.287 +            res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4b, format->samplesperblock);
   3.288 +            dumppos += res > 0 ? res : 0;
   3.289 +            break;
   3.290 +        }
   3.291 +        res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr5, format->channelmask, g1, g2, g3, g[8], g[9], g[10], g[11], g[12], g[13], g[14], g[15]);
   3.292 +        dumppos += res > 0 ? res : 0;
   3.293 +    } else {
   3.294 +        switch (format->encoding) {
   3.295 +        case MS_ADPCM_CODE:
   3.296 +        case IMA_ADPCM_CODE:
   3.297 +            if (fmtlen >= 20 && format->extsize >= 2) {
   3.298 +                res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4b, format->samplesperblock);
   3.299 +                dumppos += res > 0 ? res : 0;
   3.300 +            }
   3.301 +            break;
   3.302 +        }
   3.303 +    }
   3.304 +    if (file->fact.status >= 1) {
   3.305 +        res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr6, file->fact.samplelength);
   3.306 +        dumppos += res > 0 ? res : 0;
   3.307 +    }
   3.308 +    res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr7, datalen);
   3.309 +    dumppos += res > 0 ? res : 0;
   3.310 +
   3.311 +    SDL_LogDebug(SDL_LOG_CATEGORY_AUDIO, "%s", dumpstr);
   3.312 +
   3.313 +    free(dumpstr);
   3.314 +}
   3.315 +#endif
   3.316 +
   3.317 +static Sint64
   3.318 +WaveAdjustToFactValue(WaveFile *file, Sint64 sampleframes)
   3.319 +{
   3.320 +    if (file->fact.status == 2) {
   3.321 +        if (file->facthint == FactStrict && sampleframes < file->fact.samplelength) {
   3.322 +            return SDL_SetError("Invalid number of sample frames in WAVE fact chunk (too many)");
   3.323 +        } else if (sampleframes > file->fact.samplelength) {
   3.324 +            return file->fact.samplelength;
   3.325 +        }
   3.326 +    }
   3.327 +
   3.328 +    return sampleframes;
   3.329 +}
   3.330  
   3.331  static int
   3.332 -InitMS_ADPCM(WaveFMT * format)
   3.333 +MS_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength)
   3.334  {
   3.335 -    Uint8 *rogue_feel;
   3.336 -    int i;
   3.337 +    WaveFormat *format = &file->format;
   3.338 +    const size_t blockheadersize = file->format.channels * 7;
   3.339 +    const size_t availableblocks = datalength / file->format.blockalign;
   3.340 +    const size_t blockframebitsize = file->format.bitspersample * file->format.channels;
   3.341 +    const size_t trailingdata = datalength % file->format.blockalign;
   3.342 +
   3.343 +    if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) {
   3.344 +        /* The size of the data chunk must be a multiple of the block size. */
   3.345 +        if (datalength < blockheadersize || trailingdata > 0) {
   3.346 +            return SDL_SetError("Truncated MS ADPCM block");
   3.347 +        }
   3.348 +    }
   3.349  
   3.350 -    /* Set the rogue pointer to the MS_ADPCM specific data */
   3.351 -    MS_ADPCM_state.wavefmt.encoding = SDL_SwapLE16(format->encoding);
   3.352 -    MS_ADPCM_state.wavefmt.channels = SDL_SwapLE16(format->channels);
   3.353 -    MS_ADPCM_state.wavefmt.frequency = SDL_SwapLE32(format->frequency);
   3.354 -    MS_ADPCM_state.wavefmt.byterate = SDL_SwapLE32(format->byterate);
   3.355 -    MS_ADPCM_state.wavefmt.blockalign = SDL_SwapLE16(format->blockalign);
   3.356 -    MS_ADPCM_state.wavefmt.bitspersample =
   3.357 -        SDL_SwapLE16(format->bitspersample);
   3.358 -    rogue_feel = (Uint8 *) format + sizeof(*format);
   3.359 -    if (sizeof(*format) == 16) {
   3.360 -        /* const Uint16 extra_info = ((rogue_feel[1] << 8) | rogue_feel[0]); */
   3.361 -        rogue_feel += sizeof(Uint16);
   3.362 +    /* Calculate number of sample frames that will be decoded. */
   3.363 +    file->sampleframes = (Sint64)availableblocks * format->samplesperblock;
   3.364 +    if (trailingdata > 0) {
   3.365 +        /* The last block is truncated. Check if we can get any samples out of it. */
   3.366 +        if (file->trunchint == TruncDropFrame) {
   3.367 +            /* Drop incomplete sample frame. */
   3.368 +            if (trailingdata >= blockheadersize) {
   3.369 +                size_t trailingsamples = 2 + (trailingdata - blockheadersize) * 8 / blockframebitsize;
   3.370 +                if (trailingsamples > format->samplesperblock) {
   3.371 +                    trailingsamples = format->samplesperblock;
   3.372 +                }
   3.373 +                file->sampleframes += trailingsamples;
   3.374 +            }
   3.375 +        }
   3.376      }
   3.377 -    MS_ADPCM_state.wSamplesPerBlock = ((rogue_feel[1] << 8) | rogue_feel[0]);
   3.378 -    rogue_feel += sizeof(Uint16);
   3.379 -    MS_ADPCM_state.wNumCoef = ((rogue_feel[1] << 8) | rogue_feel[0]);
   3.380 -    rogue_feel += sizeof(Uint16);
   3.381 -    if (MS_ADPCM_state.wNumCoef != 7) {
   3.382 -        SDL_SetError("Unknown set of MS_ADPCM coefficients");
   3.383 -        return (-1);
   3.384 +
   3.385 +    file->sampleframes = WaveAdjustToFactValue(file, file->sampleframes);
   3.386 +    if (file->sampleframes < 0) {
   3.387 +        return -1;
   3.388      }
   3.389 -    for (i = 0; i < MS_ADPCM_state.wNumCoef; ++i) {
   3.390 -        MS_ADPCM_state.aCoeff[i][0] = ((rogue_feel[1] << 8) | rogue_feel[0]);
   3.391 -        rogue_feel += sizeof(Uint16);
   3.392 -        MS_ADPCM_state.aCoeff[i][1] = ((rogue_feel[1] << 8) | rogue_feel[0]);
   3.393 -        rogue_feel += sizeof(Uint16);
   3.394 -    }
   3.395 -    return (0);
   3.396 +
   3.397 +    return 0;
   3.398  }
   3.399  
   3.400 -static Sint32
   3.401 -MS_ADPCM_nibble(struct MS_ADPCM_decodestate *state,
   3.402 -                Uint8 nybble, Sint16 * coeff)
   3.403 +static int
   3.404 +MS_ADPCM_Init(WaveFile *file, size_t datalength)
   3.405  {
   3.406 -    const Sint32 max_audioval = ((1 << (16 - 1)) - 1);
   3.407 -    const Sint32 min_audioval = -(1 << (16 - 1));
   3.408 -    const Sint32 adaptive[] = {
   3.409 +    WaveFormat *format = &file->format;
   3.410 +    WaveChunk *chunk = &file->chunk;
   3.411 +    const size_t blockheadersize = format->channels * 7;
   3.412 +    const size_t blockdatasize = (size_t)format->blockalign - blockheadersize;
   3.413 +    const size_t blockframebitsize = format->bitspersample * format->channels;
   3.414 +    const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize;
   3.415 +    const Sint16 presetcoeffs[14] = {256, 0, 512, -256, 0, 0, 192, 64, 240, 0, 460, -208, 392, -232};
   3.416 +    size_t i, coeffcount;
   3.417 +    MS_ADPCM_CoeffData *coeffdata;
   3.418 +
   3.419 +    /* Sanity checks. */
   3.420 +
   3.421 +    /* While it's clear how IMA ADPCM handles more than two channels, the nibble
   3.422 +     * order of MS ADPCM makes it awkward. The Standards Update does not talk
   3.423 +     * about supporting more than stereo anyway.
   3.424 +     */
   3.425 +    if (format->channels > 2) {
   3.426 +        return SDL_SetError("Invalid number of channels");
   3.427 +    }
   3.428 +
   3.429 +    if (format->bitspersample != 4) {
   3.430 +        return SDL_SetError("Invalid MS ADPCM bits per sample of %d", (int)format->bitspersample);
   3.431 +    }
   3.432 +
   3.433 +    /* The block size must be big enough to contain the block header. */
   3.434 +    if (format->blockalign < blockheadersize) {
   3.435 +        return SDL_SetError("Invalid MS ADPCM block size (nBlockAlign)");
   3.436 +    }
   3.437 +
   3.438 +    if (format->formattag == EXTENSIBLE_CODE) {
   3.439 +        /* Does have a GUID (like all format tags), but there's no specification
   3.440 +         * for how the data is packed into the extensible header. Making
   3.441 +         * assumptions here could lead to new formats nobody wants to support.
   3.442 +         */
   3.443 +        return SDL_SetError("MS ADPCM with the extensible header is not supported");
   3.444 +    }
   3.445 +
   3.446 +    /* There are wSamplesPerBlock, wNumCoef, and at least 7 coefficient pairs in
   3.447 +     * the extended part of the header.
   3.448 +     */
   3.449 +    if (chunk->size < 22) {
   3.450 +        return SDL_SetError("Could not read MS ADPCM format header");
   3.451 +    }
   3.452 +
   3.453 +    format->samplesperblock = chunk->data[18] | ((Uint16)chunk->data[19] << 8);
   3.454 +    /* Number of coefficient pairs. A pair has two 16-bit integers. */
   3.455 +    coeffcount = chunk->data[20] | ((size_t)chunk->data[21] << 8);
   3.456 +    /* bPredictor, the integer offset into the coefficients array, is only
   3.457 +     * 8 bits. It can only address the first 256 coefficients. Let's limit
   3.458 +     * the count number here.
   3.459 +     */
   3.460 +    if (coeffcount > 256) {
   3.461 +        coeffcount = 256;
   3.462 +    }
   3.463 +
   3.464 +    if (chunk->size < 22 + coeffcount * 4) {
   3.465 +        return SDL_SetError("Could not read custom coefficients in MS ADPCM format header");
   3.466 +    } else if (format->extsize < 4 + coeffcount * 4) {
   3.467 +        return SDL_SetError("Invalid MS ADPCM format header (too small)");
   3.468 +    } else if (coeffcount < 7) {
   3.469 +        return SDL_SetError("Missing required coefficients in MS ADPCM format header");
   3.470 +    }
   3.471 +
   3.472 +    coeffdata = (MS_ADPCM_CoeffData *)SDL_malloc(sizeof(MS_ADPCM_CoeffData) + coeffcount * 4);
   3.473 +    file->decoderdata = coeffdata; /* Freed in cleanup. */
   3.474 +    if (coeffdata == NULL) {
   3.475 +        return SDL_OutOfMemory();
   3.476 +    }
   3.477 +    coeffdata->coeff = &coeffdata->aligndummy;
   3.478 +    coeffdata->coeffcount = (Uint16)coeffcount;
   3.479 +
   3.480 +    /* Copy the 16-bit pairs. */
   3.481 +    for (i = 0; i < coeffcount * 2; i++) {
   3.482 +        Sint32 c = chunk->data[22 + i * 2] | ((Sint32)chunk->data[23 + i * 2] << 8);
   3.483 +        if (c >= 0x8000) {
   3.484 +            c -= 0x10000;
   3.485 +        }
   3.486 +        if (i < 14 && c != presetcoeffs[i]) {
   3.487 +            return SDL_SetError("Wrong preset coefficients in MS ADPCM format header");
   3.488 +        }
   3.489 +        coeffdata->coeff[i] = (Sint16)c;
   3.490 +    }
   3.491 +
   3.492 +    /* Technically, wSamplesPerBlock is required, but we have all the
   3.493 +     * information in the other fields to calculate it, if it's zero.
   3.494 +     */
   3.495 +    if (format->samplesperblock == 0) {
   3.496 +        /* Let's be nice to the encoders that didn't know how to fill this.
   3.497 +         * The Standards Update calculates it this way:
   3.498 +         *
   3.499 +         *   x = Block size (in bits) minus header size (in bits)
   3.500 +         *   y = Bit depth multiplied by channel count
   3.501 +         *   z = Number of samples per channel in block header
   3.502 +         *   wSamplesPerBlock = x / y + z
   3.503 +         */
   3.504 +        format->samplesperblock = (Uint32)blockdatasamples + 2;
   3.505 +    }
   3.506 +
   3.507 +    /* nBlockAlign can be in conflict with wSamplesPerBlock. For example, if
   3.508 +     * the number of samples doesn't fit into the block. The Standards Update
   3.509 +     * also describes wSamplesPerBlock with a formula that makes it necessary to
   3.510 +     * always fill the block with the maximum amount of samples, but this is not
   3.511 +     * enforced here as there are no compatibility issues.
   3.512 +     * A truncated block header with just one sample is not supported.
   3.513 +     */
   3.514 +    if (format->samplesperblock == 1 || blockdatasamples < format->samplesperblock - 2) {
   3.515 +        return SDL_SetError("Invalid number of samples per MS ADPCM block (wSamplesPerBlock)");
   3.516 +    }
   3.517 +
   3.518 +    if (MS_ADPCM_CalculateSampleFrames(file, datalength) < 0) {
   3.519 +        return -1;
   3.520 +    }
   3.521 +
   3.522 +    return 0;
   3.523 +}
   3.524 +
   3.525 +static Sint16
   3.526 +MS_ADPCM_ProcessNibble(MS_ADPCM_ChannelState *cstate, Sint32 sample1, Sint32 sample2, Uint8 nybble)
   3.527 +{
   3.528 +    const Sint32 max_audioval = 32767;
   3.529 +    const Sint32 min_audioval = -32768;
   3.530 +    const Uint16 max_deltaval = 65535;
   3.531 +    const Uint16 adaptive[] = {
   3.532          230, 230, 230, 230, 307, 409, 512, 614,
   3.533          768, 614, 512, 409, 307, 230, 230, 230
   3.534      };
   3.535 -    Sint32 new_sample, delta;
   3.536 +    Sint32 new_sample;
   3.537 +    Sint32 errordelta;
   3.538 +    Uint32 delta = cstate->delta;
   3.539  
   3.540 -    new_sample = ((state->iSamp1 * coeff[0]) +
   3.541 -                  (state->iSamp2 * coeff[1])) / 256;
   3.542 -    if (nybble & 0x08) {
   3.543 -        new_sample += state->iDelta * (nybble - 0x10);
   3.544 -    } else {
   3.545 -        new_sample += state->iDelta * nybble;
   3.546 -    }
   3.547 +    new_sample = (sample1 * cstate->coeff1 + sample2 * cstate->coeff2) / 256;
   3.548 +    /* The nibble is a signed 4-bit error delta. */
   3.549 +    errordelta = (Sint32)nybble - (nybble >= 0x08 ? 0x10 : 0);
   3.550 +    new_sample += (Sint32)delta * errordelta;
   3.551      if (new_sample < min_audioval) {
   3.552          new_sample = min_audioval;
   3.553      } else if (new_sample > max_audioval) {
   3.554          new_sample = max_audioval;
   3.555      }
   3.556 -    delta = ((Sint32) state->iDelta * adaptive[nybble]) / 256;
   3.557 +    delta = (delta * adaptive[nybble]) / 256;
   3.558      if (delta < 16) {
   3.559          delta = 16;
   3.560 +    } else if (delta > max_deltaval) {
   3.561 +        /* This issue is not described in the Standards Update and therefore
   3.562 +         * undefined. It seems sensible to prevent overflows with a limit.
   3.563 +         */
   3.564 +        delta = max_deltaval;
   3.565      }
   3.566 -    state->iDelta = (Uint16) delta;
   3.567 -    state->iSamp2 = state->iSamp1;
   3.568 -    state->iSamp1 = (Sint16) new_sample;
   3.569 -    return (new_sample);
   3.570 +
   3.571 +    cstate->delta = (Uint16)delta;
   3.572 +    return (Sint16)new_sample;
   3.573 +}
   3.574 +
   3.575 +static int
   3.576 +MS_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
   3.577 +{
   3.578 +    Uint8 coeffindex;
   3.579 +    const Uint32 channels = state->channels;
   3.580 +    Sint32 sample;
   3.581 +    Uint32 c;
   3.582 +    MS_ADPCM_ChannelState *cstate = (MS_ADPCM_ChannelState *)state->cstate;
   3.583 +    MS_ADPCM_CoeffData *ddata = (MS_ADPCM_CoeffData *)state->ddata;
   3.584 +
   3.585 +    for (c = 0; c < channels; c++) {
   3.586 +        size_t o = c;
   3.587 +
   3.588 +        /* Load the coefficient pair into the channel state. */
   3.589 +        coeffindex = state->block.data[o];
   3.590 +        if (coeffindex > ddata->coeffcount) {
   3.591 +            return SDL_SetError("Invalid MS ADPCM coefficient index in block header");
   3.592 +        }
   3.593 +        cstate[c].coeff1 = ddata->coeff[coeffindex * 2];
   3.594 +        cstate[c].coeff2 = ddata->coeff[coeffindex * 2 + 1];
   3.595 +
   3.596 +        /* Initial delta value. */
   3.597 +        o = channels + c * 2;
   3.598 +        cstate[c].delta = state->block.data[o] | ((Uint16)state->block.data[o + 1] << 8);
   3.599 +
   3.600 +        /* Load the samples from the header. Interestingly, the sample later in
   3.601 +         * the output stream comes first.
   3.602 +         */
   3.603 +        o = channels * 3 + c * 2;
   3.604 +        sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8);
   3.605 +        if (sample >= 0x8000) {
   3.606 +            sample -= 0x10000;
   3.607 +        }
   3.608 +        state->output.data[state->output.pos + channels] = (Sint16)sample;
   3.609 +
   3.610 +        o = channels * 5 + c * 2;
   3.611 +        sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8);
   3.612 +        if (sample >= 0x8000) {
   3.613 +            sample -= 0x10000;
   3.614 +        }
   3.615 +        state->output.data[state->output.pos] = (Sint16)sample;
   3.616 +
   3.617 +        state->output.pos++;
   3.618 +    }
   3.619 +
   3.620 +    state->block.pos += state->blockheadersize;
   3.621 +
   3.622 +    /* Skip second sample frame that came from the header. */
   3.623 +    state->output.pos += state->channels;
   3.624 +
   3.625 +    /* Header provided two sample frames. */
   3.626 +    state->framesleft -= 2;
   3.627 +
   3.628 +    return 0;
   3.629 +}
   3.630 +
   3.631 +/* Decodes the data of the MS ADPCM block. Decoding will stop if a block is too
   3.632 + * short, returning with none or partially decoded data. The partial data
   3.633 + * will always contain full sample frames (same sample count for each channel).
   3.634 + * Incomplete sample frames are discarded.
   3.635 + */
   3.636 +static int
   3.637 +MS_ADPCM_DecodeBlockData(ADPCM_DecoderState *state)
   3.638 +{
   3.639 +    Uint16 nybble = 0;
   3.640 +    Sint16 sample1, sample2;
   3.641 +    const Uint32 channels = state->channels;
   3.642 +    Uint32 c;
   3.643 +    MS_ADPCM_ChannelState *cstate = (MS_ADPCM_ChannelState *)state->cstate;
   3.644 +
   3.645 +    size_t blockpos = state->block.pos;
   3.646 +    size_t blocksize = state->block.size;
   3.647 +
   3.648 +    size_t outpos = state->output.pos;
   3.649 +
   3.650 +    Sint64 blockframesleft = state->samplesperblock - 2;
   3.651 +    if (blockframesleft > state->framesleft) {
   3.652 +        blockframesleft = state->framesleft;
   3.653 +    }
   3.654 +
   3.655 +    while (blockframesleft > 0) {
   3.656 +        for (c = 0; c < channels; c++) {
   3.657 +            if (nybble & 0x8000) {
   3.658 +                nybble <<= 4;
   3.659 +            } else if (blockpos < blocksize) {
   3.660 +                nybble = state->block.data[blockpos++] | 0x8000;
   3.661 +            } else {
   3.662 +                /* Out of input data. Drop the incomplete frame and return. */
   3.663 +                state->output.pos = outpos - c;
   3.664 +                return -1;
   3.665 +            }
   3.666 +
   3.667 +            /* Load previous samples which may come from the block header. */
   3.668 +            sample1 = state->output.data[outpos - channels];
   3.669 +            sample2 = state->output.data[outpos - channels * 2];
   3.670 +
   3.671 +            sample1 = MS_ADPCM_ProcessNibble(cstate + c, sample1, sample2, (nybble >> 4) & 0x0f);
   3.672 +            state->output.data[outpos++] = sample1;
   3.673 +        }
   3.674 +
   3.675 +        state->framesleft--;
   3.676 +        blockframesleft--;
   3.677 +    }
   3.678 +
   3.679 +    state->output.pos = outpos;
   3.680 +
   3.681 +    return 0;
   3.682  }
   3.683  
   3.684  static int
   3.685 -MS_ADPCM_decode(Uint8 ** audio_buf, Uint32 * audio_len)
   3.686 +MS_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
   3.687  {
   3.688 -    struct MS_ADPCM_decodestate *state[2];
   3.689 -    Uint8 *freeable, *encoded, *decoded;
   3.690 -    Sint32 encoded_len, samplesleft;
   3.691 -    Sint8 nybble;
   3.692 -    Uint8 stereo;
   3.693 -    Sint16 *coeff[2];
   3.694 -    Sint32 new_sample;
   3.695 +    int result;
   3.696 +    size_t bytesleft, outputsize;
   3.697 +    WaveChunk *chunk = &file->chunk;
   3.698 +    ADPCM_DecoderState state = {0};
   3.699 +    MS_ADPCM_ChannelState cstate[2] = {0};
   3.700 +
   3.701 +    if (chunk->size != chunk->length) {
   3.702 +        /* Could not read everything. Recalculate number of sample frames. */
   3.703 +        if (MS_ADPCM_CalculateSampleFrames(file, chunk->size) < 0) {
   3.704 +            return -1;
   3.705 +        }
   3.706 +    }
   3.707 +
   3.708 +    /* Nothing to decode, nothing to return. */
   3.709 +    if (file->sampleframes == 0) {
   3.710 +        *audio_buf = NULL;
   3.711 +        *audio_len = 0;
   3.712 +        return 0;
   3.713 +    }
   3.714  
   3.715 -    /* Allocate the proper sized output buffer */
   3.716 -    encoded_len = *audio_len;
   3.717 -    encoded = *audio_buf;
   3.718 -    freeable = *audio_buf;
   3.719 -    *audio_len = (encoded_len / MS_ADPCM_state.wavefmt.blockalign) *
   3.720 -        MS_ADPCM_state.wSamplesPerBlock *
   3.721 -        MS_ADPCM_state.wavefmt.channels * sizeof(Sint16);
   3.722 -    *audio_buf = (Uint8 *) SDL_malloc(*audio_len);
   3.723 -    if (*audio_buf == NULL) {
   3.724 +    state.blocksize = file->format.blockalign;
   3.725 +    state.channels = file->format.channels;
   3.726 +    state.blockheadersize = state.channels * 7;
   3.727 +    state.samplesperblock = file->format.samplesperblock;
   3.728 +    state.framesize = state.channels * sizeof(Sint16);
   3.729 +    state.ddata = file->decoderdata;
   3.730 +    state.framestotal = file->sampleframes;
   3.731 +    state.framesleft = state.framestotal;
   3.732 +
   3.733 +    state.input.data = chunk->data;
   3.734 +    state.input.size = chunk->size;
   3.735 +    state.input.pos = 0;
   3.736 +
   3.737 +    /* The output size in bytes. May get modified if data is truncated. */
   3.738 +    outputsize = (size_t)state.framestotal;
   3.739 +    if (MultiplySize(&outputsize, state.framesize)) {
   3.740 +        return SDL_OutOfMemory();
   3.741 +    } else if (outputsize > SDL_MAX_UINT32 || state.framestotal > SIZE_MAX) {
   3.742 +        return SDL_SetError("WAVE file too big");
   3.743 +    }
   3.744 +
   3.745 +    state.output.pos = 0;
   3.746 +    state.output.size = outputsize / sizeof(Sint16);
   3.747 +    state.output.data = (Sint16 *)SDL_malloc(outputsize);
   3.748 +    if (state.output.data == NULL) {
   3.749          return SDL_OutOfMemory();
   3.750      }
   3.751 -    decoded = *audio_buf;
   3.752 +
   3.753 +    state.cstate = &cstate;
   3.754  
   3.755 -    /* Get ready... Go! */
   3.756 -    stereo = (MS_ADPCM_state.wavefmt.channels == 2);
   3.757 -    state[0] = &MS_ADPCM_state.state[0];
   3.758 -    state[1] = &MS_ADPCM_state.state[stereo];
   3.759 -    while (encoded_len >= MS_ADPCM_state.wavefmt.blockalign) {
   3.760 -        /* Grab the initial information for this block */
   3.761 -        state[0]->hPredictor = *encoded++;
   3.762 -        if (stereo) {
   3.763 -            state[1]->hPredictor = *encoded++;
   3.764 -        }
   3.765 -        state[0]->iDelta = ((encoded[1] << 8) | encoded[0]);
   3.766 -        encoded += sizeof(Sint16);
   3.767 -        if (stereo) {
   3.768 -            state[1]->iDelta = ((encoded[1] << 8) | encoded[0]);
   3.769 -            encoded += sizeof(Sint16);
   3.770 -        }
   3.771 -        state[0]->iSamp1 = ((encoded[1] << 8) | encoded[0]);
   3.772 -        encoded += sizeof(Sint16);
   3.773 -        if (stereo) {
   3.774 -            state[1]->iSamp1 = ((encoded[1] << 8) | encoded[0]);
   3.775 -            encoded += sizeof(Sint16);
   3.776 +    /* Decode block by block. A truncated block will stop the decoding. */
   3.777 +    bytesleft = state.input.size - state.input.pos;
   3.778 +    while (state.framesleft > 0 && bytesleft >= state.blockheadersize) {
   3.779 +        state.block.data = state.input.data + state.input.pos;
   3.780 +        state.block.size = bytesleft < state.blocksize ? bytesleft : state.blocksize;
   3.781 +        state.block.pos = 0;
   3.782 +
   3.783 +        if (state.output.size - state.output.pos < (Uint64)state.framesleft * state.channels) {
   3.784 +            /* Somehow didn't allocate enough space for the output. */
   3.785 +            SDL_free(state.output.data);
   3.786 +            return SDL_SetError("Unexpected overflow in MS ADPCM decoder");
   3.787          }
   3.788 -        state[0]->iSamp2 = ((encoded[1] << 8) | encoded[0]);
   3.789 -        encoded += sizeof(Sint16);
   3.790 -        if (stereo) {
   3.791 -            state[1]->iSamp2 = ((encoded[1] << 8) | encoded[0]);
   3.792 -            encoded += sizeof(Sint16);
   3.793 +
   3.794 +        /* Initialize decoder with the values from the block header. */
   3.795 +        result = MS_ADPCM_DecodeBlockHeader(&state);
   3.796 +        if (result == -1) {
   3.797 +            SDL_free(state.output.data);
   3.798 +            return -1;
   3.799          }
   3.800 -        coeff[0] = MS_ADPCM_state.aCoeff[state[0]->hPredictor];
   3.801 -        coeff[1] = MS_ADPCM_state.aCoeff[state[1]->hPredictor];
   3.802  
   3.803 -        /* Store the two initial samples we start with */
   3.804 -        decoded[0] = state[0]->iSamp2 & 0xFF;
   3.805 -        decoded[1] = state[0]->iSamp2 >> 8;
   3.806 -        decoded += 2;
   3.807 -        if (stereo) {
   3.808 -            decoded[0] = state[1]->iSamp2 & 0xFF;
   3.809 -            decoded[1] = state[1]->iSamp2 >> 8;
   3.810 -            decoded += 2;
   3.811 -        }
   3.812 -        decoded[0] = state[0]->iSamp1 & 0xFF;
   3.813 -        decoded[1] = state[0]->iSamp1 >> 8;
   3.814 -        decoded += 2;
   3.815 -        if (stereo) {
   3.816 -            decoded[0] = state[1]->iSamp1 & 0xFF;
   3.817 -            decoded[1] = state[1]->iSamp1 >> 8;
   3.818 -            decoded += 2;
   3.819 +        /* Decode the block data. It stores the samples directly in the output. */
   3.820 +        result = MS_ADPCM_DecodeBlockData(&state);
   3.821 +        if (result == -1) {
   3.822 +            /* Unexpected end. Stop decoding and return partial data if necessary. */
   3.823 +            if (file->trunchint == TruncVeryStrict || file->trunchint == TruncVeryStrict) {
   3.824 +                SDL_free(state.output.data);
   3.825 +                return SDL_SetError("Truncated data chunk");
   3.826 +            } else if (file->trunchint != TruncDropFrame) {
   3.827 +                state.output.pos -= state.output.pos % (state.samplesperblock * state.channels);
   3.828 +            }
   3.829 +            outputsize = state.output.pos * sizeof(Sint16); /* Can't overflow, is always smaller. */
   3.830 +            break;
   3.831          }
   3.832  
   3.833 -        /* Decode and store the other samples in this block */
   3.834 -        samplesleft = (MS_ADPCM_state.wSamplesPerBlock - 2) *
   3.835 -            MS_ADPCM_state.wavefmt.channels;
   3.836 -        while (samplesleft > 0) {
   3.837 -            nybble = (*encoded) >> 4;
   3.838 -            new_sample = MS_ADPCM_nibble(state[0], nybble, coeff[0]);
   3.839 -            decoded[0] = new_sample & 0xFF;
   3.840 -            new_sample >>= 8;
   3.841 -            decoded[1] = new_sample & 0xFF;
   3.842 -            decoded += 2;
   3.843 +        state.input.pos += state.block.size;
   3.844 +        bytesleft = state.input.size - state.input.pos;
   3.845 +    }
   3.846 +
   3.847 +    *audio_buf = (Uint8 *)state.output.data;
   3.848 +    *audio_len = (Uint32)outputsize;
   3.849 +
   3.850 +    return 0;
   3.851 +}
   3.852 +
   3.853 +static int
   3.854 +IMA_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength)
   3.855 +{
   3.856 +    WaveFormat *format = &file->format;
   3.857 +    const size_t blockheadersize = format->channels * 4;
   3.858 +    const size_t subblockframesize = format->channels * 4;
   3.859 +    const size_t availableblocks = datalength / format->blockalign;
   3.860 +    const size_t trailingdata = datalength % format->blockalign;
   3.861 +
   3.862 +    if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) {
   3.863 +        /* The size of the data chunk must be a multiple of the block size. */
   3.864 +        if (datalength < blockheadersize || trailingdata > 0) {
   3.865 +            return SDL_SetError("Truncated IMA ADPCM block");
   3.866 +        }
   3.867 +    }
   3.868  
   3.869 -            nybble = (*encoded) & 0x0F;
   3.870 -            new_sample = MS_ADPCM_nibble(state[1], nybble, coeff[1]);
   3.871 -            decoded[0] = new_sample & 0xFF;
   3.872 -            new_sample >>= 8;
   3.873 -            decoded[1] = new_sample & 0xFF;
   3.874 -            decoded += 2;
   3.875 +    /* Calculate number of sample frames that will be decoded. */
   3.876 +    file->sampleframes = (Uint64)availableblocks * format->samplesperblock;
   3.877 +    if (trailingdata > 0) {
   3.878 +        /* The last block is truncated. Check if we can get any samples out of it. */
   3.879 +        if (file->trunchint == TruncDropFrame && trailingdata > blockheadersize - 2) {
   3.880 +            /* The sample frame in the header of the truncated block is present.
   3.881 +             * Drop incomplete sample frames.
   3.882 +             */
   3.883 +            size_t trailingsamples = 1;
   3.884  
   3.885 -            ++encoded;
   3.886 -            samplesleft -= 2;
   3.887 +            if (trailingdata > blockheadersize) {
   3.888 +                /* More data following after the header. */
   3.889 +                const size_t trailingblockdata = trailingdata - blockheadersize;
   3.890 +                const size_t trailingsubblockdata = trailingblockdata % subblockframesize;
   3.891 +                trailingsamples += (trailingblockdata / subblockframesize) * 8;
   3.892 +                /* Due to the interleaved sub-blocks, the last 4 bytes determine
   3.893 +                 * how many samples of the truncated sub-block are lost.
   3.894 +                 */
   3.895 +                if (trailingsubblockdata > subblockframesize - 4) {
   3.896 +                    trailingsamples += (trailingsubblockdata % 4) * 2;
   3.897 +                }
   3.898 +            }
   3.899 +
   3.900 +            if (trailingsamples > format->samplesperblock) {
   3.901 +                trailingsamples = format->samplesperblock;
   3.902 +            }
   3.903 +            file->sampleframes += trailingsamples;
   3.904          }
   3.905 -        encoded_len -= MS_ADPCM_state.wavefmt.blockalign;
   3.906      }
   3.907 -    SDL_free(freeable);
   3.908 -    return (0);
   3.909 +
   3.910 +    file->sampleframes = WaveAdjustToFactValue(file, file->sampleframes);
   3.911 +    if (file->sampleframes < 0) {
   3.912 +        return -1;
   3.913 +    }
   3.914 +
   3.915 +    return 0;
   3.916  }
   3.917  
   3.918 -struct IMA_ADPCM_decodestate
   3.919 -{
   3.920 -    Sint32 sample;
   3.921 -    Sint8 index;
   3.922 -};
   3.923 -static struct IMA_ADPCM_decoder
   3.924 +static int
   3.925 +IMA_ADPCM_Init(WaveFile *file, size_t datalength)
   3.926  {
   3.927 -    WaveFMT wavefmt;
   3.928 -    Uint16 wSamplesPerBlock;
   3.929 -    /* * * */
   3.930 -    struct IMA_ADPCM_decodestate state[2];
   3.931 -} IMA_ADPCM_state;
   3.932 +    WaveFormat *format = &file->format;
   3.933 +    WaveChunk *chunk = &file->chunk;
   3.934 +    const size_t blockheadersize = format->channels * 4;
   3.935 +    const size_t blockdatasize = (size_t)format->blockalign - blockheadersize;
   3.936 +    const size_t blockframebitsize = format->bitspersample * format->channels;
   3.937 +    const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize;
   3.938 +
   3.939 +    /* Sanity checks. */
   3.940  
   3.941 -static int
   3.942 -InitIMA_ADPCM(WaveFMT * format, int length)
   3.943 -{
   3.944 -    Uint8 *rogue_feel, *rogue_feel_end;
   3.945 +    /* IMA ADPCAM can also have 3-bit samples, but it's not supported by SDL at this time. */
   3.946 +    if (format->bitspersample == 3) {
   3.947 +        return SDL_SetError("3-bit IMA ADPCM currently not supported");
   3.948 +    } else if (format->bitspersample != 4) {
   3.949 +        return SDL_SetError("Invalid IMA ADPCM bits per sample of %d", (int)format->bitspersample);
   3.950 +    }
   3.951 +
   3.952 +    /* The block size is required to be a multiple of 4 and it must be able to
   3.953 +     * hold a block header.
   3.954 +     */
   3.955 +    if (format->blockalign < blockheadersize || format->blockalign % 4) {
   3.956 +        return SDL_SetError("Invalid IMA ADPCM block size (nBlockAlign)");
   3.957 +    }
   3.958  
   3.959 -    /* Set the rogue pointer to the IMA_ADPCM specific data */
   3.960 -    if (length < sizeof(*format)) goto too_short;
   3.961 -    IMA_ADPCM_state.wavefmt.encoding = SDL_SwapLE16(format->encoding);
   3.962 -    IMA_ADPCM_state.wavefmt.channels = SDL_SwapLE16(format->channels);
   3.963 -    IMA_ADPCM_state.wavefmt.frequency = SDL_SwapLE32(format->frequency);
   3.964 -    IMA_ADPCM_state.wavefmt.byterate = SDL_SwapLE32(format->byterate);
   3.965 -    IMA_ADPCM_state.wavefmt.blockalign = SDL_SwapLE16(format->blockalign);
   3.966 -    IMA_ADPCM_state.wavefmt.bitspersample = SDL_SwapLE16(format->bitspersample);
   3.967 -    rogue_feel = (Uint8 *) format + sizeof(*format);
   3.968 -    rogue_feel_end = (Uint8 *) format + length;
   3.969 -    if (sizeof(*format) == 16) {
   3.970 -        /* const Uint16 extra_info = ((rogue_feel[1] << 8) | rogue_feel[0]); */
   3.971 -        rogue_feel += sizeof(Uint16);
   3.972 +    if (format->formattag == EXTENSIBLE_CODE) {
   3.973 +        /* There's no specification for this, but it's basically the same
   3.974 +         * format because the extensible header has wSampePerBlocks too.
   3.975 +         */
   3.976 +    } else  {
   3.977 +        /* The Standards Update says there 'should' be 2 bytes for wSamplesPerBlock. */
   3.978 +        if (chunk->size >= 20 && format->extsize >= 2) {
   3.979 +            format->samplesperblock = chunk->data[18] | ((Uint16)chunk->data[19] << 8);
   3.980 +        }
   3.981      }
   3.982 -    if (rogue_feel + 2 > rogue_feel_end) goto too_short;
   3.983 -    IMA_ADPCM_state.wSamplesPerBlock = ((rogue_feel[1] << 8) | rogue_feel[0]);
   3.984 -    return (0);
   3.985 -too_short:
   3.986 -    SDL_SetError("Unexpected length of a chunk with an IMA ADPCM format");
   3.987 -    return (-1);
   3.988 +
   3.989 +    if (format->samplesperblock == 0) {
   3.990 +        /* Field zero? No problem. We just assume the encoder packed the block.
   3.991 +         * The specification calculates it this way:
   3.992 +         *
   3.993 +         *   x = Block size (in bits) minus header size (in bits)
   3.994 +         *   y = Bit depth multiplied by channel count
   3.995 +         *   z = Number of samples per channel in header
   3.996 +         *   wSamplesPerBlock = x / y + z
   3.997 +         */
   3.998 +        format->samplesperblock = (Uint32)blockdatasamples + 1;
   3.999 +    }
  3.1000 +
  3.1001 +    /* nBlockAlign can be in conflict with wSamplesPerBlock. For example, if
  3.1002 +     * the number of samples doesn't fit into the block. The Standards Update
  3.1003 +     * also describes wSamplesPerBlock with a formula that makes it necessary
  3.1004 +     * to always fill the block with the maximum amount of samples, but this is
  3.1005 +     * not enforced here as there are no compatibility issues.
  3.1006 +     */
  3.1007 +    if (blockdatasamples < format->samplesperblock - 1) {
  3.1008 +        return SDL_SetError("Invalid number of samples per IMA ADPCM block (wSamplesPerBlock)");
  3.1009 +    }
  3.1010 +
  3.1011 +    if (IMA_ADPCM_CalculateSampleFrames(file, datalength) < 0) {
  3.1012 +        return -1;
  3.1013 +    }
  3.1014 +
  3.1015 +    return 0;
  3.1016  }
  3.1017  
  3.1018 -static Sint32
  3.1019 -IMA_ADPCM_nibble(struct IMA_ADPCM_decodestate *state, Uint8 nybble)
  3.1020 +static Sint16
  3.1021 +IMA_ADPCM_ProcessNibble(Sint8 *cindex, Sint16 lastsample, Uint8 nybble)
  3.1022  {
  3.1023 -    const Sint32 max_audioval = ((1 << (16 - 1)) - 1);
  3.1024 -    const Sint32 min_audioval = -(1 << (16 - 1));
  3.1025 -    const int index_table[16] = {
  3.1026 +    const Sint32 max_audioval = 32767;
  3.1027 +    const Sint32 min_audioval = -32768;
  3.1028 +    const Sint8 index_table_4b[16] = {
  3.1029          -1, -1, -1, -1,
  3.1030          2, 4, 6, 8,
  3.1031          -1, -1, -1, -1,
  3.1032          2, 4, 6, 8
  3.1033      };
  3.1034 -    const Sint32 step_table[89] = {
  3.1035 +    const Uint16 step_table[89] = {
  3.1036          7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31,
  3.1037          34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130,
  3.1038          143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408,
  3.1039 @@ -276,424 +872,1260 @@
  3.1040          9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350,
  3.1041          22385, 24623, 27086, 29794, 32767
  3.1042      };
  3.1043 -    Sint32 delta, step;
  3.1044 +    Uint32 step;
  3.1045 +    Sint32 sample, delta;
  3.1046 +    Sint8 index = *cindex;
  3.1047 +
  3.1048 +    /* Clamp index into valid range. */
  3.1049 +    if (index > 88) {
  3.1050 +        index = 88;
  3.1051 +    } else if (index < 0) {
  3.1052 +        index = 0;
  3.1053 +    }
  3.1054  
  3.1055 -    /* Compute difference and new sample value */
  3.1056 -    if (state->index > 88) {
  3.1057 -        state->index = 88;
  3.1058 -    } else if (state->index < 0) {
  3.1059 -        state->index = 0;
  3.1060 -    }
  3.1061      /* explicit cast to avoid gcc warning about using 'char' as array index */
  3.1062 -    step = step_table[(int)state->index];
  3.1063 +    step = step_table[(size_t)index];
  3.1064 +
  3.1065 +    /* Update index value */
  3.1066 +    *cindex = index + index_table_4b[nybble];
  3.1067 +
  3.1068 +    /* This calculation uses shifts and additions because multiplications were
  3.1069 +     * much slower back then. Sadly, this can't just be replaced with an actual
  3.1070 +     * multiplication now as the old algorithm drops some bits. The closest
  3.1071 +     * approximation I could find is something like this:
  3.1072 +     * (nybble & 0x8 ? -1 : 1) * ((nybble & 0x7) * step / 4 + step / 8)
  3.1073 +     */
  3.1074      delta = step >> 3;
  3.1075      if (nybble & 0x04)
  3.1076          delta += step;
  3.1077      if (nybble & 0x02)
  3.1078 -        delta += (step >> 1);
  3.1079 +        delta += step >> 1;
  3.1080      if (nybble & 0x01)
  3.1081 -        delta += (step >> 2);
  3.1082 +        delta += step >> 2;
  3.1083      if (nybble & 0x08)
  3.1084          delta = -delta;
  3.1085 -    state->sample += delta;
  3.1086  
  3.1087 -    /* Update index value */
  3.1088 -    state->index += index_table[nybble];
  3.1089 +    sample = lastsample + delta;
  3.1090  
  3.1091      /* Clamp output sample */
  3.1092 -    if (state->sample > max_audioval) {
  3.1093 -        state->sample = max_audioval;
  3.1094 -    } else if (state->sample < min_audioval) {
  3.1095 -        state->sample = min_audioval;
  3.1096 +    if (sample > max_audioval) {
  3.1097 +        sample = max_audioval;
  3.1098 +    } else if (sample < min_audioval) {
  3.1099 +        sample = min_audioval;
  3.1100      }
  3.1101 -    return (state->sample);
  3.1102 +
  3.1103 +    return (Sint16)sample;
  3.1104 +}
  3.1105 +
  3.1106 +static int
  3.1107 +IMA_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
  3.1108 +{
  3.1109 +    Sint16 step;
  3.1110 +    Uint32 c;
  3.1111 +    Uint8 *cstate = state->cstate;
  3.1112 +
  3.1113 +    for (c = 0; c < state->channels; c++) {
  3.1114 +        size_t o = state->block.pos + c * 4;
  3.1115 +
  3.1116 +        /* Extract the sample from the header. */
  3.1117 +        Sint32 sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8);
  3.1118 +        if (sample >= 0x8000) {
  3.1119 +            sample -= 0x10000;
  3.1120 +        }
  3.1121 +        state->output.data[state->output.pos++] = (Sint16)sample;
  3.1122 +
  3.1123 +        /* Channel step index. */
  3.1124 +        step = (Sint16)state->block.data[o + 2];
  3.1125 +        cstate[c] = (Sint8)(step > 0x80 ? step - 0x100 : step);
  3.1126 +
  3.1127 +        /* Reserved byte in block header, should be 0. */
  3.1128 +        if (state->block.data[o + 3] != 0) {
  3.1129 +            /* Uh oh, corrupt data?  Buggy code? */ ;
  3.1130 +        }
  3.1131 +    }
  3.1132 +
  3.1133 +    state->block.pos += state->blockheadersize;
  3.1134 +
  3.1135 +    /* Header provided one sample frame. */
  3.1136 +    state->framesleft--;
  3.1137 +
  3.1138 +    return 0;
  3.1139  }
  3.1140  
  3.1141 -/* Fill the decode buffer with a channel block of data (8 samples) */
  3.1142 -static void
  3.1143 -Fill_IMA_ADPCM_block(Uint8 * decoded, Uint8 * encoded,
  3.1144 -                     int channel, int numchannels,
  3.1145 -                     struct IMA_ADPCM_decodestate *state)
  3.1146 +/* Decodes the data of the IMA ADPCM block. Decoding will stop if a block is too
  3.1147 + * short, returning with none or partially decoded data. The partial data always
  3.1148 + * contains full sample frames (same sample count for each channel).
  3.1149 + * Incomplete sample frames are discarded.
  3.1150 + */
  3.1151 +static int
  3.1152 +IMA_ADPCM_DecodeBlockData(ADPCM_DecoderState *state)
  3.1153  {
  3.1154 -    int i;
  3.1155 -    Sint8 nybble;
  3.1156 -    Sint32 new_sample;
  3.1157 +    size_t i;
  3.1158 +    int retval = 0;
  3.1159 +    const Uint32 channels = state->channels;
  3.1160 +    const size_t subblockframesize = channels * 4;
  3.1161 +    Uint64 bytesrequired;
  3.1162 +    Uint32 c;
  3.1163 +
  3.1164 +    size_t blockpos = state->block.pos;
  3.1165 +    size_t blocksize = state->block.size;
  3.1166 +    size_t blockleft = blocksize - blockpos;
  3.1167 +
  3.1168 +    size_t outpos = state->output.pos;
  3.1169 +
  3.1170 +    Sint64 blockframesleft = state->samplesperblock - 1;
  3.1171 +    if (blockframesleft > state->framesleft) {
  3.1172 +        blockframesleft = state->framesleft;
  3.1173 +    }
  3.1174 +
  3.1175 +    bytesrequired = (blockframesleft + 7) / 8 * subblockframesize;
  3.1176 +    if (blockleft < bytesrequired) {
  3.1177 +        /* Data truncated. Calculate how many samples we can get out if it. */
  3.1178 +        const size_t guaranteedframes = blockleft / subblockframesize;
  3.1179 +        const size_t remainingbytes = blockleft % subblockframesize;
  3.1180 +        blockframesleft = guaranteedframes;
  3.1181 +        if (remainingbytes > subblockframesize - 4) {
  3.1182 +            blockframesleft += (remainingbytes % 4) * 2;
  3.1183 +        }
  3.1184 +        /* Signal the truncation. */
  3.1185 +        retval = -1;
  3.1186 +    }
  3.1187 +
  3.1188 +    /* Each channel has their nibbles packed into 32-bit blocks. These blocks
  3.1189 +     * are interleaved and make up the data part of the ADPCM block. This loop
  3.1190 +     * decodes the samples as they come from the input data and puts them at
  3.1191 +     * the appropriate places in the output data.
  3.1192 +     */
  3.1193 +    while (blockframesleft > 0) {
  3.1194 +        const size_t subblocksamples = blockframesleft < 8 ? (size_t)blockframesleft : 8;
  3.1195 +
  3.1196 +        for (c = 0; c < channels; c++) {
  3.1197 +            Uint8 nybble = 0;
  3.1198 +            /* Load previous sample which may come from the block header. */
  3.1199 +            Sint16 sample = state->output.data[outpos + c - channels];
  3.1200 +
  3.1201 +            for (i = 0; i < subblocksamples; i++) {
  3.1202 +                if (i & 1) {
  3.1203 +                    nybble >>= 4;
  3.1204 +                } else {
  3.1205 +                    nybble = state->block.data[blockpos++];
  3.1206 +                }
  3.1207 +
  3.1208 +                sample = IMA_ADPCM_ProcessNibble((Sint8 *)state->cstate + c, sample, nybble & 0x0f);
  3.1209 +                state->output.data[outpos + c + i * channels] = sample;
  3.1210 +            }
  3.1211 +        }
  3.1212 +
  3.1213 +        outpos += channels * subblocksamples;
  3.1214 +        state->framesleft -= subblocksamples;
  3.1215 +        blockframesleft -= subblocksamples;
  3.1216 +    }
  3.1217 +
  3.1218 +    state->block.pos = blockpos;
  3.1219 +    state->output.pos = outpos;
  3.1220 +
  3.1221 +    return retval;
  3.1222 +}
  3.1223 +
  3.1224 +static int
  3.1225 +IMA_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
  3.1226 +{
  3.1227 +    int result;
  3.1228 +    size_t bytesleft, outputsize;
  3.1229 +    WaveChunk *chunk = &file->chunk;
  3.1230 +    ADPCM_DecoderState state = {0};
  3.1231 +    Sint8 *cstate;
  3.1232  
  3.1233 -    decoded += (channel * 2);
  3.1234 -    for (i = 0; i < 4; ++i) {
  3.1235 -        nybble = (*encoded) & 0x0F;
  3.1236 -        new_sample = IMA_ADPCM_nibble(state, nybble);
  3.1237 -        decoded[0] = new_sample & 0xFF;
  3.1238 -        new_sample >>= 8;
  3.1239 -        decoded[1] = new_sample & 0xFF;
  3.1240 -        decoded += 2 * numchannels;
  3.1241 +    if (chunk->size != chunk->length) {
  3.1242 +        /* Could not read everything. Recalculate number of sample frames. */
  3.1243 +        if (IMA_ADPCM_CalculateSampleFrames(file, chunk->size) < 0) {
  3.1244 +            return -1;
  3.1245 +        }
  3.1246 +    }
  3.1247 +
  3.1248 +    /* Nothing to decode, nothing to return. */
  3.1249 +    if (file->sampleframes == 0) {
  3.1250 +        *audio_buf = NULL;
  3.1251 +        *audio_len = 0;
  3.1252 +        return 0;
  3.1253 +    }
  3.1254 +
  3.1255 +    state.channels = file->format.channels;
  3.1256 +    state.blocksize = file->format.blockalign;
  3.1257 +    state.blockheadersize = state.channels * 4;
  3.1258 +    state.samplesperblock = file->format.samplesperblock;
  3.1259 +    state.framesize = state.channels * sizeof(Sint16);
  3.1260 +    state.framestotal = file->sampleframes;
  3.1261 +    state.framesleft = state.framestotal;
  3.1262 +
  3.1263 +    state.input.data = chunk->data;
  3.1264 +    state.input.size = chunk->size;
  3.1265 +    state.input.pos = 0;
  3.1266 +
  3.1267 +    /* The output size in bytes. May get modified if data is truncated. */
  3.1268 +    outputsize = (size_t)state.framestotal;
  3.1269 +    if (MultiplySize(&outputsize, state.framesize)) {
  3.1270 +        return SDL_OutOfMemory();
  3.1271 +    } else if (outputsize > SDL_MAX_UINT32 || state.framestotal > SIZE_MAX) {
  3.1272 +        return SDL_SetError("WAVE file too big");
  3.1273 +    }
  3.1274 +
  3.1275 +    state.output.pos = 0;
  3.1276 +    state.output.size = outputsize / sizeof(Sint16);
  3.1277 +    state.output.data = (Sint16 *)SDL_malloc(outputsize);
  3.1278 +    if (state.output.data == NULL) {
  3.1279 +        return SDL_OutOfMemory();
  3.1280 +    }
  3.1281  
  3.1282 -        nybble = (*encoded) >> 4;
  3.1283 -        new_sample = IMA_ADPCM_nibble(state, nybble);
  3.1284 -        decoded[0] = new_sample & 0xFF;
  3.1285 -        new_sample >>= 8;
  3.1286 -        decoded[1] = new_sample & 0xFF;
  3.1287 -        decoded += 2 * numchannels;
  3.1288 +    cstate = (Sint8 *)SDL_calloc(state.channels, sizeof(Sint8));
  3.1289 +    if (cstate == NULL) {
  3.1290 +        SDL_free(state.output.data);
  3.1291 +        return SDL_OutOfMemory();
  3.1292 +    }
  3.1293 +    state.cstate = cstate;
  3.1294 +
  3.1295 +    /* Decode block by block. A truncated block will stop the decoding. */
  3.1296 +    bytesleft = state.input.size - state.input.pos;
  3.1297 +    while (state.framesleft > 0 && bytesleft >= state.blockheadersize) {
  3.1298 +        state.block.data = state.input.data + state.input.pos;
  3.1299 +        state.block.size = bytesleft < state.blocksize ? bytesleft : state.blocksize;
  3.1300 +        state.block.pos = 0;
  3.1301 +
  3.1302 +        if (state.output.size - state.output.pos < (Uint64)state.framesleft * state.channels) {
  3.1303 +            /* Somehow didn't allocate enough space for the output. */
  3.1304 +            SDL_free(state.output.data);
  3.1305 +            SDL_free(cstate);
  3.1306 +            return SDL_SetError("Unexpected overflow in IMA ADPCM decoder");
  3.1307 +        }
  3.1308 +
  3.1309 +        /* Initialize decoder with the values from the block header. */
  3.1310 +        result = IMA_ADPCM_DecodeBlockHeader(&state);
  3.1311  
  3.1312 -        ++encoded;
  3.1313 +        /* Decode the block data. It stores the samples directly in the output. */
  3.1314 +        result = IMA_ADPCM_DecodeBlockData(&state);
  3.1315 +        if (result == -1) {
  3.1316 +            /* Unexpected end. Stop decoding and return partial data if necessary. */
  3.1317 +            if (file->trunchint == TruncVeryStrict || file->trunchint == TruncVeryStrict) {
  3.1318 +                SDL_free(state.output.data);
  3.1319 +                SDL_free(cstate);
  3.1320 +                return SDL_SetError("Truncated data chunk");
  3.1321 +            } else if (file->trunchint != TruncDropFrame) {
  3.1322 +                state.output.pos -= state.output.pos % (state.samplesperblock * state.channels);
  3.1323 +            }
  3.1324 +            outputsize = state.output.pos * sizeof(Sint16); /* Can't overflow, is always smaller. */
  3.1325 +            break;
  3.1326 +        }
  3.1327 +
  3.1328 +        state.input.pos += state.block.size;
  3.1329 +        bytesleft = state.input.size - state.input.pos;
  3.1330      }
  3.1331 +
  3.1332 +    *audio_buf = (Uint8 *)state.output.data;
  3.1333 +    *audio_len = (Uint32)outputsize;
  3.1334 +
  3.1335 +    SDL_free(cstate);
  3.1336 +
  3.1337 +    return 0;
  3.1338  }
  3.1339  
  3.1340  static int
  3.1341 -IMA_ADPCM_decode(Uint8 ** audio_buf, Uint32 * audio_len)
  3.1342 +LAW_Init(WaveFile *file, size_t datalength)
  3.1343  {
  3.1344 -    struct IMA_ADPCM_decodestate *state;
  3.1345 -    Uint8 *freeable, *encoded, *decoded;
  3.1346 -    Sint32 encoded_len, samplesleft;
  3.1347 -    unsigned int c, channels;
  3.1348 +    WaveFormat *format = &file->format;
  3.1349  
  3.1350 -    /* Check to make sure we have enough variables in the state array */
  3.1351 -    channels = IMA_ADPCM_state.wavefmt.channels;
  3.1352 -    if (channels > SDL_arraysize(IMA_ADPCM_state.state)) {
  3.1353 -        SDL_SetError("IMA ADPCM decoder can only handle %u channels",
  3.1354 -                     (unsigned int)SDL_arraysize(IMA_ADPCM_state.state));
  3.1355 -        return (-1);
  3.1356 +    /* Standards Update requires this to be 8. */
  3.1357 +    if (format->bitspersample != 8) {
  3.1358 +        return SDL_SetError("Invalid companded bits per sample of %d", (int)format->bitspersample);
  3.1359      }
  3.1360 -    state = IMA_ADPCM_state.state;
  3.1361 -
  3.1362 -    /* Allocate the proper sized output buffer */
  3.1363 -    encoded_len = *audio_len;
  3.1364 -    encoded = *audio_buf;
  3.1365 -    freeable = *audio_buf;
  3.1366 -    *audio_len = (encoded_len / IMA_ADPCM_state.wavefmt.blockalign) *
  3.1367 -        IMA_ADPCM_state.wSamplesPerBlock *
  3.1368 -        IMA_ADPCM_state.wavefmt.channels * sizeof(Sint16);
  3.1369 -    *audio_buf = (Uint8 *) SDL_malloc(*audio_len);
  3.1370 -    if (*audio_buf == NULL) {
  3.1371 -        return SDL_OutOfMemory();
  3.1372 -    }
  3.1373 -    decoded = *audio_buf;
  3.1374  
  3.1375 -    /* Get ready... Go! */
  3.1376 -    while (encoded_len >= IMA_ADPCM_state.wavefmt.blockalign) {
  3.1377 -        /* Grab the initial information for this block */
  3.1378 -        for (c = 0; c < channels; ++c) {
  3.1379 -            /* Fill the state information for this block */
  3.1380 -            state[c].sample = ((encoded[1] << 8) | encoded[0]);
  3.1381 -            encoded += 2;
  3.1382 -            if (state[c].sample & 0x8000) {
  3.1383 -                state[c].sample -= 0x10000;
  3.1384 -            }
  3.1385 -            state[c].index = *encoded++;
  3.1386 -            /* Reserved byte in buffer header, should be 0 */
  3.1387 -            if (*encoded++ != 0) {
  3.1388 -                /* Uh oh, corrupt data?  Buggy code? */ ;
  3.1389 -            }
  3.1390 +    /* Not going to bother with weird padding. */
  3.1391 +    if (format->blockalign != format->channels) {
  3.1392 +        return SDL_SetError("Unsupported block alignment");
  3.1393 +    }
  3.1394  
  3.1395 -            /* Store the initial sample we start with */
  3.1396 -            decoded[0] = (Uint8) (state[c].sample & 0xFF);
  3.1397 -            decoded[1] = (Uint8) (state[c].sample >> 8);
  3.1398 -            decoded += 2;
  3.1399 +    if ((file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict)) {
  3.1400 +        if (format->blockalign > 1 && datalength % format->blockalign) {
  3.1401 +            return SDL_SetError("Truncated data chunk in WAVE file");
  3.1402          }
  3.1403 +    }
  3.1404  
  3.1405 -        /* Decode and store the other samples in this block */
  3.1406 -        samplesleft = (IMA_ADPCM_state.wSamplesPerBlock - 1) * channels;
  3.1407 -        while (samplesleft > 0) {
  3.1408 -            for (c = 0; c < channels; ++c) {
  3.1409 -                Fill_IMA_ADPCM_block(decoded, encoded,
  3.1410 -                                     c, channels, &state[c]);
  3.1411 -                encoded += 4;
  3.1412 -                samplesleft -= 8;
  3.1413 -            }
  3.1414 -            decoded += (channels * 8 * 2);
  3.1415 -        }
  3.1416 -        encoded_len -= IMA_ADPCM_state.wavefmt.blockalign;
  3.1417 +    file->sampleframes = WaveAdjustToFactValue(file, datalength / format->blockalign);
  3.1418 +    if (file->sampleframes < 0) {
  3.1419 +        return -1;
  3.1420      }
  3.1421 -    SDL_free(freeable);
  3.1422 -    return (0);
  3.1423 +
  3.1424 +    return 0;
  3.1425  }
  3.1426  
  3.1427 -
  3.1428  static int
  3.1429 -ConvertSint24ToSint32(Uint8 ** audio_buf, Uint32 * audio_len)
  3.1430 +LAW_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
  3.1431  {
  3.1432 -    const double DIVBY8388608 = 0.00000011920928955078125;
  3.1433 -    const Uint32 original_len = *audio_len;
  3.1434 -    const Uint32 samples = original_len / 3;
  3.1435 -    const Uint32 expanded_len = samples * sizeof (Uint32);
  3.1436 -    Uint8 *ptr = (Uint8 *) SDL_realloc(*audio_buf, expanded_len);
  3.1437 -    const Uint8 *src;
  3.1438 -    Uint32 *dst;
  3.1439 -    Uint32 i;
  3.1440 +#ifdef SDL_WAVE_LAW_LUT
  3.1441 +    const Sint16 alaw_lut[256] = {
  3.1442 +        -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736, -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784, -2752,
  3.1443 +        -2624, -3008, -2880, -2240, -2112, -2496, -2368, -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392, -22016,
  3.1444 +        -20992, -24064, -23040, -17920, -16896, -19968, -18944, -30208, -29184, -32256, -31232, -26112, -25088, -28160, -27136, -11008,
  3.1445 +        -10496, -12032, -11520, -8960, -8448, -9984, -9472, -15104, -14592, -16128, -15616, -13056, -12544, -14080, -13568, -344,
  3.1446 +        -328, -376, -360, -280, -264, -312, -296, -472, -456, -504, -488, -408, -392, -440, -424, -88,
  3.1447 +        -72, -120, -104, -24, -8, -56, -40, -216, -200, -248, -232, -152, -136, -184, -168, -1376,
  3.1448 +        -1312, -1504, -1440, -1120, -1056, -1248, -1184, -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696, -688,
  3.1449 +        -656, -752, -720, -560, -528, -624, -592, -944, -912, -1008, -976, -816, -784, -880, -848, 5504,
  3.1450 +        5248, 6016, 5760, 4480, 4224, 4992, 4736, 7552, 7296, 8064, 7808, 6528, 6272, 7040, 6784, 2752,
  3.1451 +        2624, 3008, 2880, 2240, 2112, 2496, 2368, 3776, 3648, 4032, 3904, 3264, 3136, 3520, 3392, 22016,
  3.1452 +        20992, 24064, 23040, 17920, 16896, 19968, 18944, 30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136, 11008,
  3.1453 +        10496, 12032, 11520, 8960, 8448, 9984, 9472, 15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568, 344,
  3.1454 +        328, 376, 360, 280, 264, 312, 296, 472, 456, 504, 488, 408, 392, 440, 424, 88,
  3.1455 +        72, 120, 104, 24, 8, 56, 40, 216, 200, 248, 232, 152, 136, 184, 168, 1376,
  3.1456 +        1312, 1504, 1440, 1120, 1056, 1248, 1184, 1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696, 688,
  3.1457 +        656, 752, 720, 560, 528, 624, 592, 944, 912, 1008, 976, 816, 784, 880, 848
  3.1458 +    };
  3.1459 +    const Sint16 mulaw_lut[256] = {
  3.1460 +        -32124, -31100, -30076, -29052, -28028, -27004, -25980, -24956, -23932, -22908, -21884, -20860, -19836, -18812, -17788, -16764, -15996,
  3.1461 +        -15484, -14972, -14460, -13948, -13436, -12924, -12412, -11900, -11388, -10876, -10364, -9852, -9340, -8828, -8316, -7932,
  3.1462 +        -7676, -7420, -7164, -6908, -6652, -6396, -6140, -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092, -3900,
  3.1463 +        -3772, -3644, -3516, -3388, -3260, -3132, -3004, -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980, -1884,
  3.1464 +        -1820, -1756, -1692, -1628, -1564, -1500, -1436, -1372, -1308, -1244, -1180, -1116, -1052, -988, -924, -876,
  3.1465 +        -844, -812, -780, -748, -716, -684, -652, -620, -588, -556, -524, -492, -460, -428, -396, -372,
  3.1466 +        -356, -340, -324, -308, -292, -276, -260, -244, -228, -212, -196, -180, -164, -148, -132, -120,
  3.1467 +        -112, -104, -96, -88, -80, -72, -64, -56, -48, -40, -32, -24, -16, -8, 0, 32124,
  3.1468 +        31100, 30076, 29052, 28028, 27004, 25980, 24956, 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, 15996,
  3.1469 +        15484, 14972, 14460, 13948, 13436, 12924, 12412, 11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316, 7932,
  3.1470 +        7676, 7420, 7164, 6908, 6652, 6396, 6140, 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092, 3900,
  3.1471 +        3772, 3644, 3516, 3388, 3260, 3132, 3004, 2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980, 1884,
  3.1472 +        1820, 1756, 1692, 1628, 1564, 1500, 1436, 1372, 1308, 1244, 1180, 1116, 1052, 988, 924, 876,
  3.1473 +        844, 812, 780, 748, 716, 684, 652, 620, 588, 556, 524, 492, 460, 428, 396, 372,
  3.1474 +        356, 340, 324, 308, 292, 276, 260, 244, 228, 212, 196, 180, 164, 148, 132, 120,
  3.1475 +        112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0
  3.1476 +    };
  3.1477 +#endif
  3.1478  
  3.1479 -    if (!ptr) {
  3.1480 +    WaveFormat *format = &file->format;
  3.1481 +    WaveChunk *chunk = &file->chunk;
  3.1482 +    size_t i, sample_count, expanded_len;
  3.1483 +    Uint8 *src;
  3.1484 +    Sint16 *dst;
  3.1485 +
  3.1486 +    if (chunk->length != chunk->size) {
  3.1487 +        file->sampleframes = WaveAdjustToFactValue(file, chunk->size / format->blockalign);
  3.1488 +        if (file->sampleframes < 0) {
  3.1489 +            return -1;
  3.1490 +        }
  3.1491 +    }
  3.1492 +
  3.1493 +    /* Nothing to decode, nothing to return. */
  3.1494 +    if (file->sampleframes == 0) {
  3.1495 +        *audio_buf = NULL;
  3.1496 +        *audio_len = 0;
  3.1497 +        return 0;
  3.1498 +    }
  3.1499 +
  3.1500 +    sample_count = (size_t)file->sampleframes;
  3.1501 +    if (MultiplySize(&sample_count, format->channels)) {
  3.1502          return SDL_OutOfMemory();
  3.1503      }
  3.1504  
  3.1505 +    expanded_len = sample_count;
  3.1506 +    if (MultiplySize(&expanded_len, sizeof(Sint16))) {
  3.1507 +        return SDL_OutOfMemory();
  3.1508 +    } else if (expanded_len > SDL_MAX_UINT32 || file->sampleframes > SIZE_MAX) {
  3.1509 +        return SDL_SetError("WAVE file too big");
  3.1510 +    }
  3.1511 +
  3.1512 +    src = (Uint8 *)SDL_realloc(chunk->data, expanded_len);
  3.1513 +    if (src == NULL) {
  3.1514 +        return SDL_OutOfMemory();
  3.1515 +    }
  3.1516 +    chunk->data = NULL;
  3.1517 +    chunk->size = 0;
  3.1518 +
  3.1519 +    dst = (Sint16 *)src;
  3.1520 +
  3.1521 +    /* Work backwards, since we're expanding in-place. SDL_AudioSpec.format will
  3.1522 +     * inform the caller about the byte order.
  3.1523 +     */
  3.1524 +    i = sample_count;
  3.1525 +    switch (file->format.encoding) {
  3.1526 +#ifdef SDL_WAVE_LAW_LUT
  3.1527 +    case ALAW_CODE:
  3.1528 +        while (i--) {
  3.1529 +            dst[i] = alaw_lut[src[i]];
  3.1530 +        }
  3.1531 +        break;
  3.1532 +    case MULAW_CODE:
  3.1533 +        while (i--) {
  3.1534 +            dst[i] = mulaw_lut[src[i]];
  3.1535 +        }
  3.1536 +        break;
  3.1537 +#else
  3.1538 +    case ALAW_CODE:
  3.1539 +        while (i--) {
  3.1540 +            Uint8 nibble = src[i];
  3.1541 +            Uint8 exponent = (nibble & 0x7f) ^ 0x55;
  3.1542 +            Sint16 mantissa = exponent & 0xf;
  3.1543 +
  3.1544 +            exponent >>= 4;
  3.1545 +            if (exponent > 0) {
  3.1546 +                mantissa |= 0x10;
  3.1547 +            }
  3.1548 +            mantissa = mantissa << 4 | 0x8;
  3.1549 +            if (exponent > 1) {
  3.1550 +                mantissa <<= exponent - 1;
  3.1551 +            }
  3.1552 +
  3.1553 +            dst[i] = nibble & 0x80 ? mantissa : -mantissa;
  3.1554 +        }
  3.1555 +        break;
  3.1556 +    case MULAW_CODE:
  3.1557 +        while (i--) {
  3.1558 +            Uint8 nibble = ~src[i];
  3.1559 +            Sint16 mantissa = nibble & 0xf;
  3.1560 +            Uint8 exponent = nibble >> 4 & 0x7;
  3.1561 +            Sint16 step = 4 << (exponent + 1);
  3.1562 +
  3.1563 +            mantissa = (0x80 << exponent) + step * mantissa + step / 2 - 132;
  3.1564 +
  3.1565 +            dst[i] = nibble & 0x80 ? -mantissa : mantissa;
  3.1566 +        }
  3.1567 +        break;
  3.1568 +#endif
  3.1569 +    default:
  3.1570 +        SDL_free(src);
  3.1571 +        return SDL_SetError("Unknown companded encoding");
  3.1572 +    }
  3.1573 +
  3.1574 +    *audio_buf = src;
  3.1575 +    *audio_len = (Uint32)expanded_len;
  3.1576 +
  3.1577 +    return 0;
  3.1578 +}
  3.1579 +
  3.1580 +static int
  3.1581 +PCM_Init(WaveFile *file, size_t datalength)
  3.1582 +{
  3.1583 +    WaveFormat *format = &file->format;
  3.1584 +
  3.1585 +    if (format->encoding == PCM_CODE) {
  3.1586 +        switch (format->bitspersample) {
  3.1587 +        case 8:
  3.1588 +        case 16:
  3.1589 +        case 24:
  3.1590 +        case 32:
  3.1591 +            /* These are supported. */
  3.1592 +            break;
  3.1593 +        default:
  3.1594 +            return SDL_SetError("%d-bit PCM format not supported", (int)format->bitspersample);
  3.1595 +        }
  3.1596 +    } else if (format->encoding == IEEE_FLOAT_CODE) {
  3.1597 +        if (format->bitspersample != 32) {
  3.1598 +            return SDL_SetError("%d-bit IEEE floating-point format not supported", (int)format->bitspersample);
  3.1599 +        }
  3.1600 +    }
  3.1601 +
  3.1602 +    /* It wouldn't be that hard to support more exotic block sizes, but
  3.1603 +     * the most common formats should do for now.
  3.1604 +     */
  3.1605 +    if (format->blockalign * 8 != format->channels * format->bitspersample) {
  3.1606 +        return SDL_SetError("Unsupported block alignment");
  3.1607 +    }
  3.1608 +
  3.1609 +    if ((file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict)) {
  3.1610 +        if (format->blockalign > 1 && datalength % format->blockalign) {
  3.1611 +            return SDL_SetError("Truncated data chunk in WAVE file");
  3.1612 +        }
  3.1613 +    }
  3.1614 +
  3.1615 +    file->sampleframes = WaveAdjustToFactValue(file, datalength / format->blockalign);
  3.1616 +    if (file->sampleframes < 0) {
  3.1617 +        return -1;
  3.1618 +    }
  3.1619 +
  3.1620 +    return 0;
  3.1621 +}
  3.1622 +
  3.1623 +static int
  3.1624 +PCM_ConvertSint24ToSint32(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
  3.1625 +{
  3.1626 +    WaveFormat *format = &file->format;
  3.1627 +    WaveChunk *chunk = &file->chunk;
  3.1628 +    size_t i, expanded_len, sample_count;
  3.1629 +    Uint8 *ptr;
  3.1630 +
  3.1631 +    sample_count = (size_t)file->sampleframes;
  3.1632 +    if (MultiplySize(&sample_count, format->channels)) {
  3.1633 +        return SDL_OutOfMemory();
  3.1634 +    }
  3.1635 +
  3.1636 +    expanded_len = sample_count;
  3.1637 +    if (MultiplySize(&expanded_len, sizeof(Sint32))) {
  3.1638 +        return SDL_OutOfMemory();
  3.1639 +    } else if (expanded_len > SDL_MAX_UINT32 || file->sampleframes > SIZE_MAX) {
  3.1640 +        return SDL_SetError("WAVE file too big");
  3.1641 +    }
  3.1642 +
  3.1643 +    ptr = (Uint8 *)SDL_realloc(chunk->data, expanded_len);
  3.1644 +    if (ptr == NULL) {
  3.1645 +        return SDL_OutOfMemory();
  3.1646 +    }
  3.1647 +
  3.1648 +    /* This pointer is now invalid. */
  3.1649 +    chunk->data = NULL;
  3.1650 +    chunk->size = 0;
  3.1651 +
  3.1652      *audio_buf = ptr;
  3.1653 -    *audio_len = expanded_len;
  3.1654 +    *audio_len = (Uint32)expanded_len;
  3.1655  
  3.1656      /* work from end to start, since we're expanding in-place. */
  3.1657 -    src = (ptr + original_len) - 3;
  3.1658 -    dst = ((Uint32 *) (ptr + expanded_len)) - 1;
  3.1659 -    for (i = 0; i < samples; i++) {
  3.1660 -        /* There's probably a faster way to do all this. */
  3.1661 -        const Sint32 converted = ((Sint32) ( (((Uint32) src[2]) << 24) |
  3.1662 -                                             (((Uint32) src[1]) << 16) |
  3.1663 -                                             (((Uint32) src[0]) << 8) )) >> 8;
  3.1664 -        const double scaled = (((double) converted) * DIVBY8388608);
  3.1665 -        src -= 3;
  3.1666 -        *(dst--) = (Sint32) (scaled * 2147483647.0);
  3.1667 +    for (i = sample_count; i > 0; i--) {
  3.1668 +        const size_t o = i - 1;
  3.1669 +        uint8_t b[4];
  3.1670 +
  3.1671 +        b[0] = 0;
  3.1672 +        b[1] = ptr[o * 3];
  3.1673 +        b[2] = ptr[o * 3 + 1];
  3.1674 +        b[3] = ptr[o * 3 + 2];
  3.1675 +
  3.1676 +        ptr[o * 4 + 0] = b[0];
  3.1677 +        ptr[o * 4 + 1] = b[1];
  3.1678 +        ptr[o * 4 + 2] = b[2];
  3.1679 +        ptr[o * 4 + 3] = b[3];
  3.1680      }
  3.1681  
  3.1682      return 0;
  3.1683  }
  3.1684  
  3.1685 +static int
  3.1686 +PCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
  3.1687 +{
  3.1688 +    WaveFormat *format = &file->format;
  3.1689 +    WaveChunk *chunk = &file->chunk;
  3.1690 +    size_t outputsize;
  3.1691  
  3.1692 -/* GUIDs that are used by WAVE_FORMAT_EXTENSIBLE */
  3.1693 -static const Uint8 extensible_pcm_guid[16] = { 1, 0, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113 };
  3.1694 -static const Uint8 extensible_ieee_guid[16] = { 3, 0, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113 };
  3.1695 +    if (chunk->length != chunk->size) {
  3.1696 +        file->sampleframes = WaveAdjustToFactValue(file, chunk->size / format->blockalign);
  3.1697 +        if (file->sampleframes < 0) {
  3.1698 +            return -1;
  3.1699 +        }
  3.1700 +    }
  3.1701 +
  3.1702 +    /* Nothing to decode, nothing to return. */
  3.1703 +    if (file->sampleframes == 0) {
  3.1704 +        *audio_buf = NULL;
  3.1705 +        *audio_len = 0;
  3.1706 +        return 0;
  3.1707 +    }
  3.1708 +
  3.1709 +    /* 24-bit samples get shifted to 32 bits. */
  3.1710 +    if (format->encoding == PCM_CODE && format->bitspersample == 24) {
  3.1711 +        return PCM_ConvertSint24ToSint32(file, audio_buf, audio_len);
  3.1712 +    }
  3.1713 +
  3.1714 +    outputsize = (size_t)file->sampleframes;
  3.1715 +    if (MultiplySize(&outputsize, format->blockalign)) {
  3.1716 +        return SDL_OutOfMemory();
  3.1717 +    } else if (outputsize > SDL_MAX_UINT32 || file->sampleframes > SIZE_MAX) {
  3.1718 +        return SDL_SetError("WAVE file too big");
  3.1719 +    }
  3.1720 +
  3.1721 +    *audio_buf = chunk->data;
  3.1722 +    *audio_len = (Uint32)outputsize;
  3.1723 +
  3.1724 +    /* This pointer is going to be returned to the caller. Prevent free in cleanup. */
  3.1725 +    chunk->data = NULL;
  3.1726 +    chunk->size = 0;
  3.1727 +
  3.1728 +    return 0;
  3.1729 +}
  3.1730 +
  3.1731 +static WaveRiffSizeHint
  3.1732 +WaveGetRiffSizeHint()
  3.1733 +{
  3.1734 +    const char *hint = SDL_GetHint(SDL_HINT_WAVE_RIFF_CHUNK_SIZE);
  3.1735 +
  3.1736 +    if (hint != NULL) {
  3.1737 +        if (SDL_strcmp(hint, "chunksearch") == 0) {
  3.1738 +            return RiffSizeChunkSearch;
  3.1739 +        } else if (SDL_strcmp(hint, "ignore") == 0) {
  3.1740 +            return RiffSizeIgnore;
  3.1741 +        } else if (SDL_strcmp(hint, "ignorezero") == 0) {
  3.1742 +            return RiffSizeIgnoreZero;
  3.1743 +        } else if (SDL_strcmp(hint, "maximum") == 0) {
  3.1744 +            return RiffSizeMaximum;
  3.1745 +        }
  3.1746 +    }
  3.1747 +
  3.1748 +    return RiffSizeNoHint;
  3.1749 +}
  3.1750 +
  3.1751 +static WaveTruncationHint
  3.1752 +WaveGetTruncationHint()
  3.1753 +{
  3.1754 +    const char *hint = SDL_GetHint(SDL_HINT_WAVE_TRUNCATION);
  3.1755  
  3.1756 -SDL_AudioSpec *
  3.1757 -SDL_LoadWAV_RW(SDL_RWops * src, int freesrc,
  3.1758 -               SDL_AudioSpec * spec, Uint8 ** audio_buf, Uint32 * audio_len)
  3.1759 +    if (hint != NULL) {
  3.1760 +        if (SDL_strcmp(hint, "verystrict") == 0) {
  3.1761 +            return TruncVeryStrict;
  3.1762 +        } else if (SDL_strcmp(hint, "strict") == 0) {
  3.1763 +            return TruncStrict;
  3.1764 +        } else if (SDL_strcmp(hint, "dropframe") == 0) {
  3.1765 +            return TruncDropFrame;
  3.1766 +        } else if (SDL_strcmp(hint, "dropblock") == 0) {
  3.1767 +            return TruncDropBlock;
  3.1768 +        }
  3.1769 +    }
  3.1770 +
  3.1771 +    return TruncNoHint;
  3.1772 +}
  3.1773 +
  3.1774 +static WaveFactChunkHint
  3.1775 +WaveGetFactChunkHint()
  3.1776  {
  3.1777 -    int was_error;
  3.1778 -    Chunk chunk;
  3.1779 -    int lenread;
  3.1780 -    int IEEE_float_encoded, MS_ADPCM_encoded, IMA_ADPCM_encoded;
  3.1781 -    int samplesize;
  3.1782 +    const char *hint = SDL_GetHint(SDL_HINT_WAVE_FACT_CHUNK);
  3.1783 +
  3.1784 +    if (hint != NULL) {
  3.1785 +        if (SDL_strcmp(hint, "truncate") == 0) {
  3.1786 +            return FactTruncate;
  3.1787 +        } else if (SDL_strcmp(hint, "strict") == 0) {
  3.1788 +            return FactStrict;
  3.1789 +        } else if (SDL_strcmp(hint, "ignorezero") == 0) {
  3.1790 +            return FactIgnoreZero;
  3.1791 +        } else if (SDL_strcmp(hint, "ignore") == 0) {
  3.1792 +            return FactIgnore;
  3.1793 +        }
  3.1794 +    }
  3.1795 +
  3.1796 +    return FactNoHint;
  3.1797 +}
  3.1798 +
  3.1799 +static void
  3.1800 +WaveFreeChunkData(WaveChunk *chunk)
  3.1801 +{
  3.1802 +    if (chunk->data != NULL) {
  3.1803 +        SDL_free(chunk->data);
  3.1804 +        chunk->data = NULL;
  3.1805 +    }
  3.1806 +    chunk->size = 0;
  3.1807 +}
  3.1808 +
  3.1809 +static int
  3.1810 +WaveNextChunk(SDL_RWops *src, WaveChunk *chunk)
  3.1811 +{
  3.1812 +    Uint32 chunkheader[2];
  3.1813 +    Sint64 nextposition = chunk->position + chunk->length;
  3.1814 +
  3.1815 +    /* Data is no longer valid after this function returns. */
  3.1816 +    WaveFreeChunkData(chunk);
  3.1817 +
  3.1818 +    /* RIFF chunks have a 2-byte alignment. Skip padding byte. */
  3.1819 +    if (chunk->length & 1) {
  3.1820 +        nextposition++;
  3.1821 +    }
  3.1822 +
  3.1823 +    if (SDL_RWseek(src, nextposition, RW_SEEK_SET) != nextposition) {
  3.1824 +        /* Not sure how we ended up here. Just abort. */
  3.1825 +        return -2;
  3.1826 +    } else if (SDL_RWread(src, chunkheader, 4, 2) != 2) {
  3.1827 +        return -1;
  3.1828 +    }
  3.1829 +
  3.1830 +    chunk->fourcc = SDL_SwapLE32(chunkheader[0]);
  3.1831 +    chunk->length = SDL_SwapLE32(chunkheader[1]);
  3.1832 +    chunk->position = nextposition + 8;
  3.1833 +
  3.1834 +    return 0;
  3.1835 +}
  3.1836  
  3.1837 -    /* WAV magic header */
  3.1838 -    Uint32 RIFFchunk;
  3.1839 -    Uint32 wavelen = 0;
  3.1840 -    Uint32 WAVEmagic;
  3.1841 -    Uint32 headerDiff = 0;
  3.1842 +static int
  3.1843 +WaveReadPartialChunkData(SDL_RWops *src, WaveChunk *chunk, size_t length)
  3.1844 +{
  3.1845 +    WaveFreeChunkData(chunk);
  3.1846 +
  3.1847 +    if (length > chunk->length) {
  3.1848 +        length = chunk->length;
  3.1849 +    }
  3.1850 +
  3.1851 +    if (length > 0) {
  3.1852 +        chunk->data = SDL_malloc(length);
  3.1853 +        if (chunk->data == NULL) {
  3.1854 +            return SDL_OutOfMemory();
  3.1855 +        }
  3.1856 +
  3.1857 +        if (SDL_RWseek(src, chunk->position, RW_SEEK_SET) != chunk->position) {
  3.1858 +            /* Not sure how we ended up here. Just abort. */
  3.1859 +            return -2;
  3.1860 +        }
  3.1861 +
  3.1862 +        chunk->size = SDL_RWread(src, chunk->data, 1, length);
  3.1863 +        if (chunk->size != length) {
  3.1864 +            /* Expected to be handled by the caller. */
  3.1865 +        }
  3.1866 +    }
  3.1867 +
  3.1868 +    return 0;
  3.1869 +}
  3.1870 +
  3.1871 +static int
  3.1872 +WaveReadChunkData(SDL_RWops *src, WaveChunk *chunk)
  3.1873 +{
  3.1874 +    return WaveReadPartialChunkData(src, chunk, chunk->length);
  3.1875 +}
  3.1876 +
  3.1877 +typedef struct WaveExtensibleGUID {
  3.1878 +    Uint16 encoding;
  3.1879 +    Uint8 guid[16];
  3.1880 +} WaveExtensibleGUID;
  3.1881 +
  3.1882 +/* Some of the GUIDs that are used by WAVEFORMATEXTENSIBLE. */
  3.1883 +#define WAVE_FORMATTAG_GUID(tag) {(tag) & 0xff, (tag) >> 8, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113}
  3.1884 +static WaveExtensibleGUID extensible_guids[] = {
  3.1885 +    {PCM_CODE,        WAVE_FORMATTAG_GUID(PCM_CODE)},
  3.1886 +    {MS_ADPCM_CODE,   WAVE_FORMATTAG_GUID(MS_ADPCM_CODE)},
  3.1887 +    {IEEE_FLOAT_CODE, WAVE_FORMATTAG_GUID(IEEE_FLOAT_CODE)},
  3.1888 +    {ALAW_CODE,       WAVE_FORMATTAG_GUID(ALAW_CODE)},
  3.1889 +    {MULAW_CODE,      WAVE_FORMATTAG_GUID(MULAW_CODE)},
  3.1890 +    {IMA_ADPCM_CODE,  WAVE_FORMATTAG_GUID(IMA_ADPCM_CODE)}
  3.1891 +};
  3.1892 +
  3.1893 +static Uint16
  3.1894 +WaveGetFormatGUIDEncoding(WaveFormat *format)
  3.1895 +{
  3.1896 +    size_t i;
  3.1897 +    for (i = 0; i < SDL_arraysize(extensible_guids); i++) {
  3.1898 +        if (SDL_memcmp(format->subformat, extensible_guids[i].guid, 16) == 0) {
  3.1899 +            return extensible_guids[i].encoding;
  3.1900 +        }
  3.1901 +    }
  3.1902 +    return UNKNOWN_CODE;
  3.1903 +}
  3.1904 +
  3.1905 +static int
  3.1906 +WaveReadFormat(WaveFile *file)
  3.1907 +{
  3.1908 +    WaveChunk *chunk = &file->chunk;
  3.1909 +    WaveFormat *format = &file->format;
  3.1910 +    SDL_RWops *fmtsrc;
  3.1911 +    size_t fmtlen = chunk->size;
  3.1912  
  3.1913 -    /* FMT chunk */
  3.1914 -    WaveFMT *format = NULL;
  3.1915 -    WaveExtensibleFMT *ext = NULL;
  3.1916 +    if (fmtlen > SDL_MAX_SINT32) {
  3.1917 +        /* Limit given by SDL_RWFromConstMem. */
  3.1918 +        return SDL_SetError("Data of WAVE fmt chunk too big");
  3.1919 +    }
  3.1920 +    fmtsrc = SDL_RWFromConstMem(chunk->data, (int)chunk->size);
  3.1921 +    if (fmtsrc == NULL) {
  3.1922 +        return SDL_OutOfMemory();
  3.1923 +    }
  3.1924 +
  3.1925 +    format->formattag = SDL_ReadLE16(fmtsrc);
  3.1926 +    format->encoding = format->formattag;
  3.1927 +    format->channels = SDL_ReadLE16(fmtsrc);
  3.1928 +    format->frequency = SDL_ReadLE32(fmtsrc);
  3.1929 +    format->byterate = SDL_ReadLE32(fmtsrc);
  3.1930 +    format->blockalign = SDL_ReadLE16(fmtsrc);
  3.1931  
  3.1932 -    SDL_zero(chunk);
  3.1933 +    /* This is PCM specific in the first version of the specification. */
  3.1934 +    if (fmtlen >= 16) {
  3.1935 +        format->bitspersample = SDL_ReadLE16(fmtsrc);
  3.1936 +    } else if (format->encoding == PCM_CODE) {
  3.1937 +        SDL_RWclose(fmtsrc);
  3.1938 +        return SDL_SetError("Missing wBitsPerSample field in WAVE fmt chunk");
  3.1939 +    }
  3.1940 +
  3.1941 +    /* The earlier versions also don't have this field. */
  3.1942 +    if (fmtlen >= 18) {
  3.1943 +        format->extsize = SDL_ReadLE16(fmtsrc);
  3.1944 +    }
  3.1945 +
  3.1946 +    if (format->formattag == EXTENSIBLE_CODE) {
  3.1947 +        /* note that this ignores channel masks, smaller valid bit counts
  3.1948 +         * inside a larger container, and most subtypes. This is just enough
  3.1949 +         * to get things that didn't really _need_ WAVE_FORMAT_EXTENSIBLE
  3.1950 +         * to be useful working when they use this format flag.
  3.1951 +         */
  3.1952  
  3.1953 -    /* Make sure we are passed a valid data source */
  3.1954 -    was_error = 0;
  3.1955 -    if (src == NULL) {
  3.1956 -        was_error = 1;
  3.1957 -        goto done;
  3.1958 +        /* Extensible header must be at least 22 bytes. */
  3.1959 +        if (fmtlen < 40 || format->extsize < 22) {
  3.1960 +            SDL_RWclose(fmtsrc);
  3.1961 +            return SDL_SetError("Extensible WAVE header too small");
  3.1962 +        }
  3.1963 +
  3.1964 +        format->validsamplebits = SDL_ReadLE16(fmtsrc);
  3.1965 +        format->samplesperblock = format->validsamplebits;
  3.1966 +        format->channelmask = SDL_ReadLE32(fmtsrc);
  3.1967 +        SDL_RWread(fmtsrc, format->subformat, 1, 16);
  3.1968 +        format->encoding = WaveGetFormatGUIDEncoding(format);
  3.1969 +    }
  3.1970 +
  3.1971 +    SDL_RWclose(fmtsrc);
  3.1972 +
  3.1973 +    return 0;
  3.1974 +}
  3.1975 +
  3.1976 +static int
  3.1977 +WaveCheckFormat(WaveFile *file, size_t datalength)
  3.1978 +{
  3.1979 +    WaveFormat *format = &file->format;
  3.1980 +
  3.1981 +    /* Check for some obvious issues. */
  3.1982 +
  3.1983 +    if (format->channels == 0) {
  3.1984 +        return SDL_SetError("Invalid number of channels");
  3.1985 +    } else if (format->channels > 255) {
  3.1986 +        /* Limit given by SDL_AudioSpec.channels. */
  3.1987 +        return SDL_SetError("Number of channels exceeds limit of 255");
  3.1988 +    }
  3.1989 +
  3.1990 +    if (format->frequency == 0) {
  3.1991 +        return SDL_SetError("Invalid sample rate");
  3.1992 +    } else if (format->frequency > INT_MAX) {
  3.1993 +        /* Limit given by SDL_AudioSpec.freq. */
  3.1994 +        return SDL_SetError("Sample rate exceeds limit of %d", INT_MAX);
  3.1995 +    }
  3.1996 +
  3.1997 +    /* Reject invalid fact chunks in strict mode. */
  3.1998 +    if (file->facthint == FactStrict && file->fact.status == -1) {
  3.1999 +        return SDL_SetError("Invalid fact chunk in WAVE file");
  3.2000      }
  3.2001  
  3.2002 -    /* Check the magic header */
  3.2003 -    RIFFchunk = SDL_ReadLE32(src);
  3.2004 -    wavelen = SDL_ReadLE32(src);
  3.2005 -    if (wavelen == WAVE) {      /* The RIFFchunk has already been read */
  3.2006 -        WAVEmagic = wavelen;
  3.2007 -        wavelen = RIFFchunk;
  3.2008 -        RIFFchunk = RIFF;
  3.2009 -    } else {
  3.2010 -        WAVEmagic = SDL_ReadLE32(src);
  3.2011 -    }
  3.2012 -    if ((RIFFchunk != RIFF) || (WAVEmagic != WAVE)) {
  3.2013 -        SDL_SetError("Unrecognized file type (not WAVE)");
  3.2014 -        was_error = 1;
  3.2015 -        goto done;
  3.2016 -    }
  3.2017 -    headerDiff += sizeof(Uint32);       /* for WAVE */
  3.2018 +    /* Check the issues common to all encodings. Some unsupported formats set
  3.2019 +     * the bits per sample to zero. These fall through to the 'unsupported
  3.2020 +     * format' error.
  3.2021 +     */
  3.2022 +    switch (format->encoding) {
  3.2023 +    case IEEE_FLOAT_CODE:
  3.2024 +    case ALAW_CODE:
  3.2025 +    case MULAW_CODE:
  3.2026 +    case MS_ADPCM_CODE:
  3.2027 +    case IMA_ADPCM_CODE:
  3.2028 +        /* These formats require a fact chunk. */
  3.2029 +        if (file->facthint == FactStrict && file->fact.status <= 0) {
  3.2030 +            return SDL_SetError("Missing fact chunk in WAVE file");
  3.2031 +        }
  3.2032 +        /* fallthrough */
  3.2033 +    case PCM_CODE:
  3.2034 +        /* All supported formats require a non-zero bit depth. */
  3.2035 +        if (file->chunk.size < 16) {
  3.2036 +            return SDL_SetError("Missing wBitsPerSample field in WAVE fmt chunk");
  3.2037 +        } else if (format->bitspersample == 0) {
  3.2038 +            return SDL_SetError("Invalid bits per sample");
  3.2039 +        }
  3.2040  
  3.2041 -    /* Read the audio data format chunk */
  3.2042 -    chunk.data = NULL;
  3.2043 -    do {
  3.2044 -        SDL_free(chunk.data);
  3.2045 -        chunk.data = NULL;
  3.2046 -        lenread = ReadChunk(src, &chunk);
  3.2047 -        if (lenread < 0) {
  3.2048 -            was_error = 1;
  3.2049 -            goto done;
  3.2050 +        /* All supported formats must have a proper block size. */
  3.2051 +        if (format->blockalign == 0) {
  3.2052 +            return SDL_SetError("Invalid block alignment");
  3.2053          }
  3.2054 -        /* 2 Uint32's for chunk header+len, plus the lenread */
  3.2055 -        headerDiff += lenread + 2 * sizeof(Uint32);
  3.2056 -    } while ((chunk.magic == FACT) || (chunk.magic == LIST) || (chunk.magic == BEXT) || (chunk.magic == JUNK));
  3.2057  
  3.2058 -    /* Decode the audio data format */
  3.2059 -    format = (WaveFMT *) chunk.data;
  3.2060 -    if (chunk.magic != FMT) {
  3.2061 -        SDL_SetError("Complex WAVE files not supported");
  3.2062 -        was_error = 1;
  3.2063 -        goto done;
  3.2064 +        /* If the fact chunk is valid and the appropriate hint is set, the
  3.2065 +         * decoders will use the number of sample frames from the fact chunk.
  3.2066 +         */
  3.2067 +        if (file->fact.status == 1) {
  3.2068 +            WaveFactChunkHint hint = file->facthint;
  3.2069 +            Uint32 samples = file->fact.samplelength;
  3.2070 +            if (hint == FactTruncate || hint == FactStrict || (hint == FactIgnoreZero && samples > 0)) {
  3.2071 +                file->fact.status = 2;
  3.2072 +            }
  3.2073 +        }
  3.2074      }
  3.2075 -    IEEE_float_encoded = MS_ADPCM_encoded = IMA_ADPCM_encoded = 0;
  3.2076 -    switch (SDL_SwapLE16(format->encoding)) {
  3.2077 +
  3.2078 +    /* Check the format for encoding specific issues and initialize decoders. */
  3.2079 +    switch (format->encoding) {
  3.2080      case PCM_CODE:
  3.2081 -        /* We can understand this */
  3.2082 +    case IEEE_FLOAT_CODE:
  3.2083 +        if (PCM_Init(file, datalength) < 0) {
  3.2084 +            return -1;
  3.2085 +        }
  3.2086          break;
  3.2087 -    case IEEE_FLOAT_CODE:
  3.2088 -        IEEE_float_encoded = 1;
  3.2089 -        /* We can understand this */
  3.2090 +    case ALAW_CODE:
  3.2091 +    case MULAW_CODE:
  3.2092 +        if (LAW_Init(file, datalength) < 0) {
  3.2093 +            return -1;
  3.2094 +        }
  3.2095          break;
  3.2096      case MS_ADPCM_CODE:
  3.2097 -        /* Try to understand this */
  3.2098 -        if (InitMS_ADPCM(format) < 0) {
  3.2099 -            was_error = 1;
  3.2100 -            goto done;
  3.2101 +        if (MS_ADPCM_Init(file, datalength) < 0) {
  3.2102 +            return -1;
  3.2103          }
  3.2104 -        MS_ADPCM_encoded = 1;
  3.2105          break;
  3.2106      case IMA_ADPCM_CODE:
  3.2107 -        /* Try to understand this */
  3.2108 -        if (InitIMA_ADPCM(format, lenread) < 0) {
  3.2109 -            was_error = 1;
  3.2110 -            goto done;
  3.2111 -        }
  3.2112 -        IMA_ADPCM_encoded = 1;
  3.2113 -        break;
  3.2114 -    case EXTENSIBLE_CODE:
  3.2115 -        /* note that this ignores channel masks, smaller valid bit counts
  3.2116 -           inside a larger container, and most subtypes. This is just enough
  3.2117 -           to get things that didn't really _need_ WAVE_FORMAT_EXTENSIBLE
  3.2118 -           to be useful working when they use this format flag. */
  3.2119 -        ext = (WaveExtensibleFMT *) format;
  3.2120 -        if (SDL_SwapLE16(ext->size) < 22) {
  3.2121 -            SDL_SetError("bogus extended .wav header");
  3.2122 -            was_error = 1;
  3.2123 -            goto done;
  3.2124 -        }
  3.2125 -        if (SDL_memcmp(ext->subformat, extensible_pcm_guid, 16) == 0) {
  3.2126 -            break;  /* cool. */
  3.2127 -        } else if (SDL_memcmp(ext->subformat, extensible_ieee_guid, 16) == 0) {
  3.2128 -            IEEE_float_encoded = 1;
  3.2129 -            break;
  3.2130 +        if (IMA_ADPCM_Init(file, datalength) < 0) {
  3.2131 +            return -1;
  3.2132          }
  3.2133          break;
  3.2134 -    case MP3_CODE:
  3.2135 -        SDL_SetError("MPEG Layer 3 data not supported");
  3.2136 -        was_error = 1;
  3.2137 -        goto done;
  3.2138 +    case MPEG_CODE:
  3.2139 +    case MPEGLAYER3_CODE:
  3.2140 +        return SDL_SetError("MPEG formats not supported");
  3.2141      default:
  3.2142 -        SDL_SetError("Unknown WAVE data format: 0x%.4x",
  3.2143 -                     SDL_SwapLE16(format->encoding));
  3.2144 -        was_error = 1;
  3.2145 -        goto done;
  3.2146 +        if (format->formattag == EXTENSIBLE_CODE) {
  3.2147 +            const char *errstr = "Unknown WAVE format GUID: %08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x";
  3.2148 +            const Uint8 *g = format->subformat;
  3.2149 +            const Uint32 g1 = g[0] | ((Uint32)g[1] << 8) | ((Uint32)g[2] << 16) | ((Uint32)g[3] << 24);
  3.2150 +            const Uint32 g2 = g[4] | ((Uint32)g[5] << 8);
  3.2151 +            const Uint32 g3 = g[6] | ((Uint32)g[7] << 8);
  3.2152 +            return SDL_SetError(errstr, g1, g2, g3, g[8], g[9], g[10], g[11], g[12], g[13], g[14], g[15]);
  3.2153 +        }
  3.2154 +        return SDL_SetError("Unknown WAVE format tag: 0x%04x", (int)format->encoding);
  3.2155 +    }
  3.2156 +
  3.2157 +    return 0;
  3.2158 +}
  3.2159 +
  3.2160 +static int
  3.2161 +WaveLoad(SDL_RWops *src, WaveFile *file, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len)
  3.2162 +{
  3.2163 +    int result;
  3.2164 +    Uint32 chunkcount = 0;
  3.2165 +    Uint32 chunkcountlimit = 10000;
  3.2166 +    char *envchunkcountlimit;
  3.2167 +    Sint64 RIFFstart, RIFFend, lastchunkpos;
  3.2168 +    SDL_bool RIFFlengthknown = SDL_FALSE;
  3.2169 +    WaveFormat *format = &file->format;
  3.2170 +    WaveChunk *chunk = &file->chunk;
  3.2171 +    WaveChunk RIFFchunk = {0};
  3.2172 +    WaveChunk fmtchunk = {0};
  3.2173 +    WaveChunk datachunk = {0};
  3.2174 +
  3.2175 +    envchunkcountlimit = SDL_getenv("SDL_WAVE_CHUNK_LIMIT");
  3.2176 +    if (envchunkcountlimit != NULL) {
  3.2177 +        unsigned int count;
  3.2178 +        if (SDL_sscanf(envchunkcountlimit, "%u", &count) == 1) {
  3.2179 +            chunkcountlimit = count <= SDL_MAX_UINT32 ? count : SDL_MAX_UINT32;
  3.2180 +        }
  3.2181 +    }
  3.2182 +
  3.2183 +    RIFFstart = SDL_RWtell(src);
  3.2184 +    if (RIFFstart < 0) {
  3.2185 +        return SDL_SetError("Could not seek in file");
  3.2186 +    }
  3.2187 +
  3.2188 +    RIFFchunk.position = RIFFstart;
  3.2189 +    if (WaveNextChunk(src, &RIFFchunk) < 0) {
  3.2190 +        return SDL_SetError("Could not read RIFF header");
  3.2191      }
  3.2192 -    SDL_zerop(spec);
  3.2193 -    spec->freq = SDL_SwapLE32(format->frequency);
  3.2194 +
  3.2195 +    /* Check main WAVE file identifiers. */
  3.2196 +    if (RIFFchunk.fourcc == RIFF) {
  3.2197 +        Uint32 formtype;
  3.2198 +        /* Read the form type. "WAVE" expected. */
  3.2199 +        if (SDL_RWread(src, &formtype, sizeof(Uint32), 1) != 1) {
  3.2200 +            return SDL_SetError("Could not read RIFF form type");
  3.2201 +        } else if (SDL_SwapLE32(formtype) != WAVE) {
  3.2202 +            return SDL_SetError("RIFF form type is not WAVE (not a Waveform file)");
  3.2203 +        }
  3.2204 +    } else if (RIFFchunk.fourcc == WAVE) {
  3.2205 +        /* RIFF chunk missing or skipped. Length unknown. */
  3.2206 +        RIFFchunk.position = 0;
  3.2207 +        RIFFchunk.length = 0;
  3.2208 +    } else {
  3.2209 +        return SDL_SetError("Could not find RIFF or WAVE identifiers (not a Waveform file)");
  3.2210 +    }
  3.2211 +
  3.2212 +    /* The 4-byte form type is immediately followed by the first chunk.*/
  3.2213 +    chunk->position = RIFFchunk.position + 4;
  3.2214 +
  3.2215 +    /* Use the RIFF chunk size to limit the search for the chunks. This is not
  3.2216 +     * always reliable and the hint can be used to tune the behavior. By
  3.2217 +     * default, it will never search past 4 GiB.
  3.2218 +     */
  3.2219 +    switch (file->riffhint) {
  3.2220 +    case RiffSizeIgnore:
  3.2221 +        RIFFend = RIFFchunk.position + SDL_MAX_UINT32;
  3.2222 +        break;
  3.2223 +    default:
  3.2224 +    case RiffSizeIgnoreZero:
  3.2225 +        if (RIFFchunk.length == 0) {
  3.2226 +            RIFFend = RIFFchunk.position + SDL_MAX_UINT32;
  3.2227 +            break;
  3.2228 +        }
  3.2229 +        /* fallthrough */
  3.2230 +    case RiffSizeChunkSearch:
  3.2231 +        RIFFend = RIFFchunk.position + RIFFchunk.length;
  3.2232 +        RIFFlengthknown = SDL_TRUE;
  3.2233 +        break;
  3.2234 +    case RiffSizeMaximum:
  3.2235 +        RIFFend = SDL_MAX_SINT64;
  3.2236 +        break;
  3.2237 +    }
  3.2238 +
  3.2239 +    /* Step through all chunks and save information on the fmt, data, and fact
  3.2240 +     * chunks. Ignore the chunks we don't know as per specification. This
  3.2241 +     * currently also ignores cue, list, and slnt chunks.
  3.2242 +     */
  3.2243 +    while (RIFFend > chunk->position + chunk->length + (chunk->length & 1)) {
  3.2244 +        /* Abort after too many chunks or else corrupt files may waste time. */
  3.2245 +        if (chunkcount++ >= chunkcountlimit) {
  3.2246 +            return SDL_SetError("Chunk count in WAVE file exceeds limit of %u", chunkcountlimit);
  3.2247 +        }
  3.2248 +
  3.2249 +        result = WaveNextChunk(src, chunk);
  3.2250 +        if (result == -1) {
  3.2251 +            /* Unexpected EOF. Corrupt file or I/O issues. */
  3.2252 +            if (file->trunchint == TruncVeryStrict) {
  3.2253 +                return SDL_SetError("Unexpected end of WAVE file");
  3.2254 +            }
  3.2255 +            /* Let the checks after this loop sort this issue out. */
  3.2256 +            break;
  3.2257 +        } else if (result == -2) {
  3.2258 +            return SDL_SetError("Could not seek to WAVE chunk header");
  3.2259 +        }
  3.2260  
  3.2261 -    if (IEEE_float_encoded) {
  3.2262 -        if ((SDL_SwapLE16(format->bitspersample)) != 32) {
  3.2263 -            was_error = 1;
  3.2264 -        } else {
  3.2265 -            spec->format = AUDIO_F32;
  3.2266 +        if (chunk->fourcc == FMT) {
  3.2267 +            if (fmtchunk.fourcc == FMT) {
  3.2268 +                /* Multiple fmt chunks. Ignore or error? */
  3.2269 +            } else {
  3.2270 +                /* The fmt chunk must occur before the data chunk. */
  3.2271 +                if (datachunk.fourcc == DATA) {
  3.2272 +                    return SDL_SetError("fmt chunk after data chunk in WAVE file");
  3.2273 +                }
  3.2274 +                fmtchunk = *chunk;
  3.2275 +            }
  3.2276 +        } else if (chunk->fourcc == DATA) {
  3.2277 +            /* Only use the first data chunk. Handling the wavl list madness
  3.2278 +             * may require a different approach.
  3.2279 +             */
  3.2280 +            if (datachunk.fourcc != DATA) {
  3.2281 +                datachunk = *chunk;
  3.2282 +            }
  3.2283 +        } else if (chunk->fourcc == FACT) {
  3.2284 +            /* The fact chunk data must be at least 4 bytes for the
  3.2285 +             * dwSampleLength field. Ignore all fact chunks after the first one.
  3.2286 +             */
  3.2287 +            if (file->fact.status == 0) {
  3.2288 +                if (chunk->length < 4) {
  3.2289 +                    file->fact.status = -1;
  3.2290 +                } else {
  3.2291 +                    /* Let's use src directly, it's just too convenient. */
  3.2292 +                    Sint64 position = SDL_RWseek(src, chunk->position, RW_SEEK_SET);
  3.2293 +                    Uint32 samplelength;
  3.2294 +                    if (position == chunk->position && SDL_RWread(src, &samplelength, sizeof(Uint32), 1) == 1) {
  3.2295 +                        file->fact.status = 1;
  3.2296 +                        file->fact.samplelength = SDL_SwapLE32(samplelength);
  3.2297 +                    } else {
  3.2298 +                        file->fact.status = -1;
  3.2299 +                    }
  3.2300 +                }
  3.2301 +            }
  3.2302 +        }
  3.2303 +
  3.2304 +        /* Go through all chunks in verystrict mode or stop the search early if
  3.2305 +         * all required chunks were found.
  3.2306 +         */
  3.2307 +        if (file->trunchint == TruncVeryStrict) {
  3.2308 +            if (RIFFend < chunk->position + chunk->length) {
  3.2309 +                return SDL_SetError("RIFF size truncates chunk");
  3.2310 +            }
  3.2311 +        } else if (fmtchunk.fourcc == FMT && datachunk.fourcc == DATA) {
  3.2312 +            if (file->fact.status == 1 || file->facthint == FactIgnore || file->facthint == FactNoHint) {
  3.2313 +                break;
  3.2314 +            }
  3.2315 +        }
  3.2316 +    }
  3.2317 +
  3.2318 +    /* Save the position after the last chunk. This position will be used if the
  3.2319 +     * RIFF length is unknown.
  3.2320 +     */
  3.2321 +    lastchunkpos = chunk->position + chunk->length;
  3.2322 +
  3.2323 +    /* The fmt chunk is mandatory. */
  3.2324 +    if (fmtchunk.fourcc != FMT) {
  3.2325 +        return SDL_SetError("Missing fmt chunk in WAVE file");
  3.2326 +    }
  3.2327 +    /* A data chunk must be present. */
  3.2328 +    if (datachunk.fourcc != DATA) {
  3.2329 +        return SDL_SetError("Missing data chunk in WAVE file");
  3.2330 +    }
  3.2331 +    /* Check if the last chunk has all of its data in verystrict mode. */
  3.2332 +    if (file->trunchint == TruncVeryStrict) {
  3.2333 +        /* data chunk is handled later. */
  3.2334 +        if (chunk->fourcc != DATA && chunk->length > 0) {
  3.2335 +            Uint8 tmp;
  3.2336 +            Sint64 position = chunk->position + chunk->length - 1;
  3.2337 +            if (SDL_RWseek(src, position, RW_SEEK_SET) != position) {
  3.2338 +                return SDL_SetError("Could not seek to WAVE chunk data");
  3.2339 +            } else if (SDL_RWread(src, &tmp, 1, 1) != 1) {
  3.2340 +                return SDL_SetError("RIFF size truncates chunk");
  3.2341 +            }
  3.2342          }
  3.2343 -    } else {
  3.2344 -        switch (SDL_SwapLE16(format->bitspersample)) {
  3.2345 -        case 4:
  3.2346 -            if (MS_ADPCM_encoded || IMA_ADPCM_encoded) {
  3.2347 -                spec->format = AUDIO_S16;
  3.2348 -            } else {
  3.2349 -                was_error = 1;
  3.2350 -            }
  3.2351 -            break;
  3.2352 +    }
  3.2353 +
  3.2354 +    /* Process fmt chunk. */
  3.2355 +    *chunk = fmtchunk;
  3.2356 +
  3.2357 +    /* No need to read more than 1046 bytes of the fmt chunk data with the
  3.2358 +     * formats that are currently supported. (1046 because of MS ADPCM coefficients)
  3.2359 +     */
  3.2360 +    if (WaveReadPartialChunkData(src, chunk, 1046) < 0) {
  3.2361 +        return SDL_SetError("Could not read data of WAVE fmt chunk");
  3.2362 +    }
  3.2363 +
  3.2364 +    /* The fmt chunk data must be at least 14 bytes to include all common fields.
  3.2365 +     * It usually is 16 and larger depending on the header and encoding.
  3.2366 +     */
  3.2367 +    if (chunk->length < 14) {
  3.2368 +        return SDL_SetError("Invalid WAVE fmt chunk length (too small)");
  3.2369 +    } else if (chunk->size < 14) {
  3.2370 +        return SDL_SetError("Could not read data of WAVE fmt chunk");
  3.2371 +    } else if (WaveReadFormat(file) < 0) {
  3.2372 +        return -1;
  3.2373 +    } else if (WaveCheckFormat(file, (size_t)datachunk.length) < 0) {
  3.2374 +        return -1;
  3.2375 +    }
  3.2376 +
  3.2377 +#ifdef SDL_WAVE_DEBUG_LOG_FORMAT
  3.2378 +    WaveDebugLogFormat(file);
  3.2379 +#endif
  3.2380 +#ifdef SDL_WAVE_DEBUG_DUMP_FORMAT
  3.2381 +    WaveDebugDumpFormat(file, RIFFchunk.length, fmtchunk.length, datachunk.length);
  3.2382 +#endif
  3.2383 +
  3.2384 +    WaveFreeChunkData(chunk);
  3.2385 +
  3.2386 +    /* Process data chunk. */
  3.2387 +    *chunk = datachunk;
  3.2388 +
  3.2389 +    if (chunk->length > 0) {
  3.2390 +        result = WaveReadChunkData(src, chunk);
  3.2391 +        if (result == -1) {
  3.2392 +            return -1;
  3.2393 +        } else if (result == -2) {
  3.2394 +            return SDL_SetError("Could not seek data of WAVE data chunk");
  3.2395 +        }
  3.2396 +    }
  3.2397 +
  3.2398 +    if (chunk->length != chunk->size) {
  3.2399 +        /* I/O issues or corrupt file. */
  3.2400 +        if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) {
  3.2401 +            return SDL_SetError("Could not read data of WAVE data chunk");
  3.2402 +        }
  3.2403 +        /* The decoders handle this truncation. */
  3.2404 +    }
  3.2405 +
  3.2406 +    /* Decode or convert the data if necessary. */
  3.2407 +    switch (format->encoding) {
  3.2408 +    case PCM_CODE:
  3.2409 +    case IEEE_FLOAT_CODE:
  3.2410 +        if (PCM_Decode(file, audio_buf, audio_len) < 0) {
  3.2411 +            return -1;
  3.2412 +        }
  3.2413 +        break;
  3.2414 +    case ALAW_CODE:
  3.2415 +    case MULAW_CODE:
  3.2416 +        if (LAW_Decode(file, audio_buf, audio_len) < 0) {
  3.2417 +            return -1;
  3.2418 +        }
  3.2419 +        break;
  3.2420 +    case MS_ADPCM_CODE:
  3.2421 +        if (MS_ADPCM_Decode(file, audio_buf, audio_len) < 0) {
  3.2422 +            return -1;
  3.2423 +        }
  3.2424 +        break;
  3.2425 +    case IMA_ADPCM_CODE:
  3.2426 +        if (IMA_ADPCM_Decode(file, audio_buf, audio_len) < 0) {
  3.2427 +            return -1;
  3.2428 +        }
  3.2429 +        break;
  3.2430 +    }
  3.2431 +
  3.2432 +    /* Setting up the SDL_AudioSpec. All unsupported formats were filtered out
  3.2433 +     * by checks earlier in this function.
  3.2434 +     */
  3.2435 +    SDL_zerop(spec);
  3.2436 +    spec->freq = format->frequency;
  3.2437 +    spec->channels = (Uint8)format->channels;
  3.2438 +    spec->samples = 4096;       /* Good default buffer size */
  3.2439 +
  3.2440 +    switch (format->encoding) {
  3.2441 +    case MS_ADPCM_CODE:
  3.2442 +    case IMA_ADPCM_CODE:
  3.2443 +    case ALAW_CODE:
  3.2444 +    case MULAW_CODE:
  3.2445 +        /* These can be easily stored in the byte order of the system. */
  3.2446 +        spec->format = AUDIO_S16SYS;
  3.2447 +        break;
  3.2448 +    case IEEE_FLOAT_CODE:
  3.2449 +        spec->format = AUDIO_F32LSB;
  3.2450 +        break;
  3.2451 +    case PCM_CODE:
  3.2452 +        switch (format->bitspersample) {
  3.2453          case 8:
  3.2454              spec->format = AUDIO_U8;
  3.2455              break;
  3.2456          case 16:
  3.2457 -            spec->format = AUDIO_S16;
  3.2458 +            spec->format = AUDIO_S16LSB;
  3.2459              break;
  3.2460 -        case 24:  /* convert this. */
  3.2461 -            spec->format = AUDIO_S32;
  3.2462 -            break;
  3.2463 +        case 24: /* Has been shifted to 32 bits. */
  3.2464          case 32:
  3.2465 -            spec->format = AUDIO_S32;
  3.2466 +            spec->format = AUDIO_S32LSB;
  3.2467              break;
  3.2468          default:
  3.2469 -            was_error = 1;
  3.2470 -            break;
  3.2471 +            /* Just in case something unexpected happened in the checks. */
  3.2472 +            return SDL_SetError("Unexpected %d-bit PCM data format", format->bitspersample);
  3.2473          }
  3.2474 +        break;
  3.2475 +    }
  3.2476 +
  3.2477 +    /* Report the end position back to the cleanup code. */
  3.2478 +    if (RIFFlengthknown) {
  3.2479 +        chunk->position = RIFFend;
  3.2480 +    } else {
  3.2481 +        chunk->position = lastchunkpos;
  3.2482      }
  3.2483  
  3.2484 -    if (was_error) {
  3.2485 -        SDL_SetError("Unknown %d-bit PCM data format",
  3.2486 -                     SDL_SwapLE16(format->bitspersample));
  3.2487 -        goto done;
  3.2488 -    }
  3.2489 -    spec->channels = (Uint8) SDL_SwapLE16(format->channels);
  3.2490 -    spec->samples = 4096;       /* Good default buffer size */
  3.2491 +    return 0;
  3.2492 +}
  3.2493 +
  3.2494 +SDL_AudioSpec *
  3.2495 +SDL_LoadWAV_RW(SDL_RWops *src, int freesrc, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len)
  3.2496 +{
  3.2497 +    int result;
  3.2498 +    WaveFile file = {0};
  3.2499  
  3.2500 -    /* Read the audio data chunk */
  3.2501 -    *audio_buf = NULL;
  3.2502 -    do {
  3.2503 -        SDL_free(*audio_buf);
  3.2504 -        *audio_buf = NULL;
  3.2505 -        lenread = ReadChunk(src, &chunk);
  3.2506 -        if (lenread < 0) {
  3.2507 -            was_error = 1;
  3.2508 -            goto done;
  3.2509 -        }
  3.2510 -        *audio_len = lenread;
  3.2511 -        *audio_buf = chunk.data;
  3.2512 -        if (chunk.magic != DATA)
  3.2513 -            headerDiff += lenread + 2 * sizeof(Uint32);
  3.2514 -    } while (chunk.magic != DATA);
  3.2515 -    headerDiff += 2 * sizeof(Uint32);   /* for the data chunk and len */
  3.2516 -
  3.2517 -    if (MS_ADPCM_encoded) {
  3.2518 -        if (MS_ADPCM_decode(audio_buf, audio_len) < 0) {
  3.2519 -            was_error = 1;
  3.2520 -            goto done;
  3.2521 -        }
  3.2522 -    }
  3.2523 -    if (IMA_ADPCM_encoded) {
  3.2524 -        if (IMA_ADPCM_decode(audio_buf, audio_len) < 0) {
  3.2525 -            was_error = 1;
  3.2526 -            goto done;
  3.2527 -        }
  3.2528 +    /* Make sure we are passed a valid data source */
  3.2529 +    if (src == NULL) {
  3.2530 +        /* Error may come from RWops. */
  3.2531 +        return NULL;
  3.2532 +    } else if (spec == NULL) {
  3.2533 +        SDL_InvalidParamError("spec");
  3.2534 +        return NULL;
  3.2535 +    } else if (audio_buf == NULL) {
  3.2536 +        SDL_InvalidParamError("audio_buf");
  3.2537 +        return NULL;
  3.2538 +    } else if (audio_len == NULL) {
  3.2539 +        SDL_InvalidParamError("audio_len");
  3.2540 +        return NULL;
  3.2541      }
  3.2542  
  3.2543 -    if (SDL_SwapLE16(format->bitspersample) == 24) {
  3.2544 -        if (ConvertSint24ToSint32(audio_buf, audio_len) < 0) {
  3.2545 -            was_error = 1;
  3.2546 -            goto done;
  3.2547 -        }
  3.2548 +    *audio_buf = NULL;
  3.2549 +    *audio_len = 0;
  3.2550 +
  3.2551 +    file.riffhint = WaveGetRiffSizeHint();
  3.2552 +    file.trunchint = WaveGetTruncationHint();
  3.2553 +    file.facthint = WaveGetFactChunkHint();
  3.2554 +
  3.2555 +    result = WaveLoad(src, &file, spec, audio_buf, audio_len);
  3.2556 +    if (result < 0) {
  3.2557 +        SDL_free(*audio_buf);
  3.2558 +        spec = NULL;
  3.2559 +        audio_buf = NULL;
  3.2560 +        audio_len = 0;
  3.2561      }
  3.2562  
  3.2563 -    /* Don't return a buffer that isn't a multiple of samplesize */
  3.2564 -    samplesize = ((SDL_AUDIO_BITSIZE(spec->format)) / 8) * spec->channels;
  3.2565 -    *audio_len &= ~(samplesize - 1);
  3.2566 +    /* Cleanup */
  3.2567 +    if (freesrc) {
  3.2568 +        SDL_RWclose(src);
  3.2569 +    } else {
  3.2570 +        SDL_RWseek(src, file.chunk.position, RW_SEEK_SET);
  3.2571 +    }
  3.2572 +    WaveFreeChunkData(&file.chunk);
  3.2573 +    SDL_free(file.decoderdata);
  3.2574  
  3.2575 -  done:
  3.2576 -    SDL_free(format);
  3.2577 -    if (src) {
  3.2578 -        if (freesrc) {
  3.2579 -            SDL_RWclose(src);
  3.2580 -        } else {
  3.2581 -            /* seek to the end of the file (given by the RIFF chunk) */
  3.2582 -            SDL_RWseek(src, wavelen - chunk.length - headerDiff, RW_SEEK_CUR);
  3.2583 -        }
  3.2584 -    }
  3.2585 -    if (was_error) {
  3.2586 -        spec = NULL;
  3.2587 -    }
  3.2588 -    return (spec);
  3.2589 +    return spec;
  3.2590  }
  3.2591  
  3.2592  /* Since the WAV memory is allocated in the shared library, it must also
  3.2593     be freed here.  (Necessary under Win32, VC++)
  3.2594   */
  3.2595  void
  3.2596 -SDL_FreeWAV(Uint8 * audio_buf)
  3.2597 +SDL_FreeWAV(Uint8 *audio_buf)
  3.2598  {
  3.2599      SDL_free(audio_buf);
  3.2600  }
  3.2601  
  3.2602 -static int
  3.2603 -ReadChunk(SDL_RWops * src, Chunk * chunk)
  3.2604 -{
  3.2605 -    chunk->magic = SDL_ReadLE32(src);
  3.2606 -    chunk->length = SDL_ReadLE32(src);
  3.2607 -    chunk->data = (Uint8 *) SDL_malloc(chunk->length);
  3.2608 -    if (chunk->data == NULL) {
  3.2609 -        return SDL_OutOfMemory();
  3.2610 -    }
  3.2611 -    if (SDL_RWread(src, chunk->data, chunk->length, 1) != 1) {
  3.2612 -        SDL_free(chunk->data);
  3.2613 -        chunk->data = NULL;
  3.2614 -        return SDL_Error(SDL_EFREAD);
  3.2615 -    }
  3.2616 -    return (chunk->length);
  3.2617 -}
  3.2618 -
  3.2619  /* vi: set ts=4 sw=4 expandtab: */
     4.1 --- a/src/audio/SDL_wave.h	Sat Jun 08 18:40:11 2019 -0700
     4.2 +++ b/src/audio/SDL_wave.h	Sat Jun 08 19:02:42 2019 -0700
     4.3 @@ -20,11 +20,12 @@
     4.4  */
     4.5  #include "../SDL_internal.h"
     4.6  
     4.7 -/* WAVE files are little-endian */
     4.8 +/* RIFF WAVE files are little-endian */
     4.9  
    4.10  /*******************************************/
    4.11  /* Define values for Microsoft WAVE format */
    4.12  /*******************************************/
    4.13 +/* FOURCC */
    4.14  #define RIFF            0x46464952      /* "RIFF" */
    4.15  #define WAVE            0x45564157      /* "WAVE" */
    4.16  #define FACT            0x74636166      /* "fact" */
    4.17 @@ -33,45 +34,116 @@
    4.18  #define JUNK            0x4B4E554A      /* "JUNK" */
    4.19  #define FMT             0x20746D66      /* "fmt " */
    4.20  #define DATA            0x61746164      /* "data" */
    4.21 +/* Format tags */
    4.22 +#define UNKNOWN_CODE    0x0000
    4.23  #define PCM_CODE        0x0001
    4.24  #define MS_ADPCM_CODE   0x0002
    4.25  #define IEEE_FLOAT_CODE 0x0003
    4.26 +#define ALAW_CODE       0x0006
    4.27 +#define MULAW_CODE      0x0007
    4.28  #define IMA_ADPCM_CODE  0x0011
    4.29 -#define MP3_CODE        0x0055
    4.30 +#define MPEG_CODE       0x0050
    4.31 +#define MPEGLAYER3_CODE 0x0055
    4.32  #define EXTENSIBLE_CODE 0xFFFE
    4.33 -#define WAVE_MONO       1
    4.34 -#define WAVE_STEREO     2
    4.35  
    4.36 -/* Normally, these three chunks come consecutively in a WAVE file */
    4.37 -typedef struct WaveFMT
    4.38 +/* Stores the WAVE format information. */
    4.39 +typedef struct WaveFormat
    4.40  {
    4.41 -/* Not saved in the chunk we read:
    4.42 -    Uint32  FMTchunk;
    4.43 -    Uint32  fmtlen;
    4.44 -*/
    4.45 -    Uint16 encoding;
    4.46 -    Uint16 channels;            /* 1 = mono, 2 = stereo */
    4.47 -    Uint32 frequency;           /* One of 11025, 22050, or 44100 Hz */
    4.48 -    Uint32 byterate;            /* Average bytes per second */
    4.49 -    Uint16 blockalign;          /* Bytes per sample block */
    4.50 -    Uint16 bitspersample;       /* One of 8, 12, 16, or 4 for ADPCM */
    4.51 -} WaveFMT;
    4.52 +    Uint16 formattag;       /* Raw value of the first field in the fmt chunk data. */
    4.53 +    Uint16 encoding;        /* Actual encoding, possibly from the extensible header. */
    4.54 +    Uint16 channels;        /* Number of channels. */
    4.55 +    Uint32 frequency;       /* Sampling rate in Hz. */
    4.56 +    Uint32 byterate;        /* Average bytes per second. */
    4.57 +    Uint16 blockalign;      /* Bytes per block. */
    4.58 +    Uint16 bitspersample;   /* Currently supported are 8, 16, 24, 32, and 4 for ADPCM. */
    4.59 +
    4.60 +    /* Extra information size. Number of extra bytes starting at byte 18 in the
    4.61 +     * fmt chunk data. This is at least 22 for the extensible header.
    4.62 +     */
    4.63 +    Uint16 extsize;
    4.64 +
    4.65 +    /* Extensible WAVE header fields */
    4.66 +    Uint16 validsamplebits;
    4.67 +    Uint32 samplesperblock; /* For compressed formats. Can be zero. Actually 16 bits in the header. */
    4.68 +    Uint32 channelmask;
    4.69 +    Uint8 subformat[16];    /* A format GUID. */
    4.70 +} WaveFormat;
    4.71 +
    4.72 +/* Stores information on the fact chunk. */
    4.73 +typedef struct WaveFact {
    4.74 +    /* Represents the state of the fact chunk in the WAVE file.
    4.75 +     * Set to -1 if the fact chunk is invalid.
    4.76 +     * Set to 0 if the fact chunk is not present
    4.77 +     * Set to 1 if the fact chunk is present and valid.
    4.78 +     * Set to 2 if samplelength is going to be used as the number of sample frames.
    4.79 +     */
    4.80 +    Sint32 status;
    4.81 +
    4.82 +    /* Version 1 of the RIFF specification calls the field in the fact chunk
    4.83 +     * dwFileSize. The Standards Update then calls it dwSampleLength and specifies
    4.84 +     * that it is 'the length of the data in samples'. WAVE files from Windows
    4.85 +     * with this chunk have it set to the samples per channel (sample frames).
    4.86 +     * This is useful to truncate compressed audio to a specific sample count
    4.87 +     * because a compressed block is usually decoded to a fixed number of
    4.88 +     * sample frames.
    4.89 +     */
    4.90 +    Uint32 samplelength; /* Raw sample length value from the fact chunk. */
    4.91 +} WaveFact;
    4.92  
    4.93 -/* The general chunk found in the WAVE file */
    4.94 -typedef struct Chunk
    4.95 +/* Generic struct for the chunks in the WAVE file. */
    4.96 +typedef struct WaveChunk
    4.97  {
    4.98 -    Uint32 magic;
    4.99 -    Uint32 length;
   4.100 -    Uint8 *data;
   4.101 -} Chunk;
   4.102 +    Uint32 fourcc;   /* FOURCC of the chunk. */
   4.103 +    Uint32 length;   /* Size of the chunk data. */
   4.104 +    Sint64 position; /* Position of the data in the stream. */
   4.105 +    Uint8 *data;     /* When allocated, this points to the chunk data. length is used for the malloc size. */
   4.106 +    size_t size;     /* Number of bytes in data that could be read from the stream. Can be smaller than length. */
   4.107 +} WaveChunk;
   4.108 +
   4.109 +/* Controls how the size of the RIFF chunk affects the loading of a WAVE file. */
   4.110 +typedef enum WaveRiffSizeHint {
   4.111 +    RiffSizeNoHint,
   4.112 +    RiffSizeChunkSearch,
   4.113 +    RiffSizeIgnoreZero,
   4.114 +    RiffSizeIgnore,
   4.115 +    RiffSizeMaximum,
   4.116 +} WaveRiffSizeHint;
   4.117 +
   4.118 +/* Controls how a truncated WAVE file is handled. */
   4.119 +typedef enum WaveTruncationHint {
   4.120 +    TruncNoHint,
   4.121 +    TruncVeryStrict,
   4.122 +    TruncStrict,
   4.123 +    TruncDropFrame,
   4.124 +    TruncDropBlock,
   4.125 +} WaveTruncationHint;
   4.126  
   4.127 -typedef struct WaveExtensibleFMT
   4.128 +/* Controls how the fact chunk affects the loading of a WAVE file. */
   4.129 +typedef enum WaveFactChunkHint {
   4.130 +    FactNoHint,
   4.131 +    FactTruncate,
   4.132 +    FactStrict,
   4.133 +    FactIgnoreZero,
   4.134 +    FactIgnore,
   4.135 +} WaveFactChunkHint;
   4.136 +
   4.137 +typedef struct WaveFile
   4.138  {
   4.139 -    WaveFMT format;
   4.140 -    Uint16 size;
   4.141 -    Uint16 validbits;
   4.142 -    Uint32 channelmask;
   4.143 -    Uint8 subformat[16];  /* a GUID. */
   4.144 -} WaveExtensibleFMT;
   4.145 +    WaveChunk chunk;
   4.146 +    WaveFormat format;
   4.147 +    WaveFact fact;
   4.148 +
   4.149 +    /* Number of sample frames that will be decoded. Calculated either with the
   4.150 +     * size of the data chunk or, if the appropriate hint is enabled, with the
   4.151 +     * sample length value from the fact chunk.
   4.152 +     */
   4.153 +    Sint64 sampleframes;
   4.154 +
   4.155 +    void *decoderdata;   /* Some decoders require extra data for a state. */
   4.156 +
   4.157 +    WaveRiffSizeHint riffhint;
   4.158 +    WaveTruncationHint trunchint;
   4.159 +    WaveFactChunkHint facthint;
   4.160 +} WaveFile;
   4.161  
   4.162  /* vi: set ts=4 sw=4 expandtab: */