src/audio/SDL_wave.c
author Ryan C. Gordon <icculus@icculus.org>
Tue, 11 Jun 2019 02:08:31 -0400
changeset 12825 4fb5e61382b7
parent 12814 cee49246e1bc
child 12842 a66900915e4e
permissions -rw-r--r--
windows: Don't let Visual Studio insert an implicit dependency on memset().

Fixes Bugzilla #4662.
     1 /*
     2   Simple DirectMedia Layer
     3   Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org>
     4 
     5   This software is provided 'as-is', without any express or implied
     6   warranty.  In no event will the authors be held liable for any damages
     7   arising from the use of this software.
     8 
     9   Permission is granted to anyone to use this software for any purpose,
    10   including commercial applications, and to alter it and redistribute it
    11   freely, subject to the following restrictions:
    12 
    13   1. The origin of this software must not be misrepresented; you must not
    14      claim that you wrote the original software. If you use this software
    15      in a product, an acknowledgment in the product documentation would be
    16      appreciated but is not required.
    17   2. Altered source versions must be plainly marked as such, and must not be
    18      misrepresented as being the original software.
    19   3. This notice may not be removed or altered from any source distribution.
    20 */
    21 #include "../SDL_internal.h"
    22 
    23 #ifdef HAVE_LIMITS_H
    24 #include <limits.h>
    25 #else
    26 #ifndef SIZE_MAX
    27 #define SIZE_MAX ((size_t)-1)
    28 #endif
    29 #ifndef INT_MAX
    30 /* Make a lucky guess. */
    31 #define INT_MAX SDL_MAX_SINT32
    32 #endif
    33 #endif
    34 
    35 /* Microsoft WAVE file loading routines */
    36 
    37 #include "SDL_log.h"
    38 #include "SDL_hints.h"
    39 #include "SDL_audio.h"
    40 #include "SDL_wave.h"
    41 
    42 /* Reads the value stored at the location of the f1 pointer, multiplies it
    43  * with the second argument and then stores the result to f1.
    44  * Returns 0 on success, or -1 if the multiplication overflows, in which case f1
    45  * does not get modified.
    46  */
    47 static int
    48 SafeMult(size_t *f1, size_t f2)
    49 {
    50     if (*f1 > 0 && SIZE_MAX / *f1 <= f2) {
    51         return -1;
    52     }
    53     *f1 *= f2;
    54     return 0;
    55 }
    56 
    57 typedef struct ADPCM_DecoderState
    58 {
    59     Uint32 channels;        /* Number of channels. */
    60     size_t blocksize;       /* Size of an ADPCM block in bytes. */
    61     size_t blockheadersize; /* Size of an ADPCM block header in bytes. */
    62     size_t samplesperblock; /* Number of samples per channel in an ADPCM block. */
    63     size_t framesize;       /* Size of a sample frame (16-bit PCM) in bytes. */
    64     Sint64 framestotal;     /* Total number of sample frames. */
    65     Sint64 framesleft;      /* Number of sample frames still to be decoded. */
    66     void *ddata;            /* Decoder data from initialization. */
    67     void *cstate;           /* Decoding state for each channel. */
    68 
    69     /* ADPCM data. */
    70     struct {
    71         Uint8 *data;
    72         size_t size;
    73         size_t pos;
    74     } input;
    75 
    76     /* Current ADPCM block in the ADPCM data above. */
    77     struct {
    78         Uint8 *data;
    79         size_t size;
    80         size_t pos;
    81     } block;
    82 
    83     /* Decoded 16-bit PCM data. */
    84     struct {
    85         Sint16 *data;
    86         size_t size;
    87         size_t pos;
    88     } output;
    89 } ADPCM_DecoderState;
    90 
    91 typedef struct MS_ADPCM_CoeffData
    92 {
    93     Uint16 coeffcount;
    94     Sint16 *coeff;
    95     Sint16 aligndummy; /* Has to be last member. */
    96 } MS_ADPCM_CoeffData;
    97 
    98 typedef struct MS_ADPCM_ChannelState
    99 {
   100     Uint16 delta;
   101     Sint16 coeff1;
   102     Sint16 coeff2;
   103 } MS_ADPCM_ChannelState;
   104 
   105 #ifdef SDL_WAVE_DEBUG_LOG_FORMAT
   106 static void
   107 WaveDebugLogFormat(WaveFile *file)
   108 {
   109     WaveFormat *format = &file->format;
   110     const char *fmtstr = "WAVE file: %s, %u Hz, %s, %u bits, %u %s/s";
   111     const char *waveformat, *wavechannel, *wavebpsunit = "B";
   112     Uint32 wavebps = format->byterate;
   113     char channelstr[64];
   114 
   115     SDL_zero(channelstr);
   116 
   117     switch (format->encoding) {
   118     case PCM_CODE:
   119         waveformat = "PCM";
   120         break;
   121     case IEEE_FLOAT_CODE:
   122         waveformat = "IEEE Float";
   123         break;
   124     case ALAW_CODE:
   125         waveformat = "A-law";
   126         break;
   127     case MULAW_CODE:
   128         waveformat = "\xc2\xb5-law";
   129         break;
   130     case MS_ADPCM_CODE:
   131         waveformat = "MS ADPCM";
   132         break;
   133     case IMA_ADPCM_CODE:
   134         waveformat = "IMA ADPCM";
   135         break;
   136     default:
   137         waveformat = "Unknown";
   138         break;
   139     }
   140 
   141 #define SDL_WAVE_DEBUG_CHANNELCFG(STR, CODE) case CODE: wavechannel = STR; break;
   142 #define SDL_WAVE_DEBUG_CHANNELSTR(STR, CODE) if (format->channelmask & CODE) { \
   143     SDL_strlcat(channelstr, channelstr[0] ? "-" STR : STR, sizeof(channelstr));}
   144 
   145     if (format->formattag == EXTENSIBLE_CODE && format->channelmask > 0) {
   146         switch (format->channelmask) {
   147             SDL_WAVE_DEBUG_CHANNELCFG("1.0 Mono",         0x4)
   148             SDL_WAVE_DEBUG_CHANNELCFG("1.1 Mono",         0xc)
   149             SDL_WAVE_DEBUG_CHANNELCFG("2.0 Stereo",       0x3)
   150             SDL_WAVE_DEBUG_CHANNELCFG("2.1 Stereo",       0xb)
   151             SDL_WAVE_DEBUG_CHANNELCFG("3.0 Stereo",       0x7)
   152             SDL_WAVE_DEBUG_CHANNELCFG("3.1 Stereo",       0xf)
   153             SDL_WAVE_DEBUG_CHANNELCFG("3.0 Surround",     0x103)
   154             SDL_WAVE_DEBUG_CHANNELCFG("3.1 Surround",     0x10b)
   155             SDL_WAVE_DEBUG_CHANNELCFG("4.0 Quad",         0x33)
   156             SDL_WAVE_DEBUG_CHANNELCFG("4.1 Quad",         0x3b)
   157             SDL_WAVE_DEBUG_CHANNELCFG("4.0 Surround",     0x107)
   158             SDL_WAVE_DEBUG_CHANNELCFG("4.1 Surround",     0x10f)
   159             SDL_WAVE_DEBUG_CHANNELCFG("5.0",              0x37)
   160             SDL_WAVE_DEBUG_CHANNELCFG("5.1",              0x3f)
   161             SDL_WAVE_DEBUG_CHANNELCFG("5.0 Side",         0x607)
   162             SDL_WAVE_DEBUG_CHANNELCFG("5.1 Side",         0x60f)
   163             SDL_WAVE_DEBUG_CHANNELCFG("6.0",              0x137)
   164             SDL_WAVE_DEBUG_CHANNELCFG("6.1",              0x13f)
   165             SDL_WAVE_DEBUG_CHANNELCFG("6.0 Side",         0x707)
   166             SDL_WAVE_DEBUG_CHANNELCFG("6.1 Side",         0x70f)
   167             SDL_WAVE_DEBUG_CHANNELCFG("7.0",              0xf7)
   168             SDL_WAVE_DEBUG_CHANNELCFG("7.1",              0xff)
   169             SDL_WAVE_DEBUG_CHANNELCFG("7.0 Side",         0x6c7)
   170             SDL_WAVE_DEBUG_CHANNELCFG("7.1 Side",         0x6cf)
   171             SDL_WAVE_DEBUG_CHANNELCFG("7.0 Surround",     0x637)
   172             SDL_WAVE_DEBUG_CHANNELCFG("7.1 Surround",     0x63f)
   173             SDL_WAVE_DEBUG_CHANNELCFG("9.0 Surround",     0x5637)
   174             SDL_WAVE_DEBUG_CHANNELCFG("9.1 Surround",     0x563f)
   175             SDL_WAVE_DEBUG_CHANNELCFG("11.0 Surround",    0x56f7)
   176             SDL_WAVE_DEBUG_CHANNELCFG("11.1 Surround",    0x56ff)
   177         default:
   178             SDL_WAVE_DEBUG_CHANNELSTR("FL",  0x1)
   179             SDL_WAVE_DEBUG_CHANNELSTR("FR",  0x2)
   180             SDL_WAVE_DEBUG_CHANNELSTR("FC",  0x4)
   181             SDL_WAVE_DEBUG_CHANNELSTR("LF",  0x8)
   182             SDL_WAVE_DEBUG_CHANNELSTR("BL",  0x10)
   183             SDL_WAVE_DEBUG_CHANNELSTR("BR",  0x20)
   184             SDL_WAVE_DEBUG_CHANNELSTR("FLC", 0x40)
   185             SDL_WAVE_DEBUG_CHANNELSTR("FRC", 0x80)
   186             SDL_WAVE_DEBUG_CHANNELSTR("BC",  0x100)
   187             SDL_WAVE_DEBUG_CHANNELSTR("SL",  0x200)
   188             SDL_WAVE_DEBUG_CHANNELSTR("SR",  0x400)
   189             SDL_WAVE_DEBUG_CHANNELSTR("TC",  0x800)
   190             SDL_WAVE_DEBUG_CHANNELSTR("TFL", 0x1000)
   191             SDL_WAVE_DEBUG_CHANNELSTR("TFC", 0x2000)
   192             SDL_WAVE_DEBUG_CHANNELSTR("TFR", 0x4000)
   193             SDL_WAVE_DEBUG_CHANNELSTR("TBL", 0x8000)
   194             SDL_WAVE_DEBUG_CHANNELSTR("TBC", 0x10000)
   195             SDL_WAVE_DEBUG_CHANNELSTR("TBR", 0x20000)
   196             break;
   197         }
   198     } else {
   199         switch (format->channels) {
   200         default:
   201             if (SDL_snprintf(channelstr, sizeof(channelstr), "%u channels", format->channels) >= 0) {
   202                 wavechannel = channelstr;
   203                 break;
   204             }
   205         case 0:
   206             wavechannel = "Unknown";
   207             break;
   208         case 1:
   209             wavechannel = "Mono";
   210             break;
   211         case 2:
   212             wavechannel = "Setero";
   213             break;
   214         }
   215     }
   216 
   217 #undef SDL_WAVE_DEBUG_CHANNELCFG
   218 #undef SDL_WAVE_DEBUG_CHANNELSTR
   219 
   220     if (wavebps >= 1024) {
   221         wavebpsunit = "KiB";
   222         wavebps = wavebps / 1024 + (wavebps & 0x3ff ? 1 : 0);
   223     }
   224 
   225     SDL_LogDebug(SDL_LOG_CATEGORY_AUDIO, fmtstr, waveformat, format->frequency, wavechannel, format->bitspersample, wavebps, wavebpsunit);
   226 }
   227 #endif
   228 
   229 #ifdef SDL_WAVE_DEBUG_DUMP_FORMAT
   230 static void
   231 WaveDebugDumpFormat(WaveFile *file, Uint32 rifflen, Uint32 fmtlen, Uint32 datalen)
   232 {
   233     WaveFormat *format = &file->format;
   234     const char *fmtstr1 = "WAVE chunk dump:\n"
   235         "-------------------------------------------\n"
   236         "RIFF                            %11u\n"
   237         "-------------------------------------------\n"
   238         "    fmt                         %11u\n"
   239         "        wFormatTag                   0x%04x\n"
   240         "        nChannels               %11u\n"
   241         "        nSamplesPerSec          %11u\n"
   242         "        nAvgBytesPerSec         %11u\n"
   243         "        nBlockAlign             %11u\n";
   244     const char *fmtstr2 = "        wBitsPerSample          %11u\n";
   245     const char *fmtstr3 = "        cbSize                  %11u\n";
   246     const char *fmtstr4a = "        wValidBitsPerSample     %11u\n";
   247     const char *fmtstr4b = "        wSamplesPerBlock        %11u\n";
   248     const char *fmtstr5 = "        dwChannelMask            0x%08x\n"
   249         "        SubFormat\n"
   250         "        %08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x\n";
   251     const char *fmtstr6 = "-------------------------------------------\n"
   252         " fact\n"
   253         "  dwSampleLength                %11u\n";
   254     const char *fmtstr7 = "-------------------------------------------\n"
   255         " data                           %11u\n"
   256         "-------------------------------------------\n";
   257     char *dumpstr;
   258     size_t dumppos = 0;
   259     const size_t bufsize = 1024;
   260     int res;
   261 
   262     dumpstr = SDL_malloc(bufsize);
   263     if (dumpstr == NULL) {
   264         return;
   265     }
   266     dumpstr[0] = 0;
   267 
   268     res = SDL_snprintf(dumpstr, bufsize, fmtstr1, rifflen, fmtlen, format->formattag, format->channels, format->frequency, format->byterate, format->blockalign);
   269     dumppos += res > 0 ? res : 0;
   270     if (fmtlen >= 16) {
   271         res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr2, format->bitspersample);
   272         dumppos += res > 0 ? res : 0;
   273     }
   274     if (fmtlen >= 18) {
   275         res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr3, format->extsize);
   276         dumppos += res > 0 ? res : 0;
   277     }
   278     if (format->formattag == EXTENSIBLE_CODE && fmtlen >= 40 && format->extsize >= 22) {
   279         const Uint8 *g = format->subformat;
   280         const Uint32 g1 = g[0] | ((Uint32)g[1] << 8) | ((Uint32)g[2] << 16) | ((Uint32)g[3] << 24);
   281         const Uint32 g2 = g[4] | ((Uint32)g[5] << 8);
   282         const Uint32 g3 = g[6] | ((Uint32)g[7] << 8);
   283 
   284         switch (format->encoding) {
   285         default:
   286             res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4a, format->validsamplebits);
   287             dumppos += res > 0 ? res : 0;
   288             break;
   289         case MS_ADPCM_CODE:
   290         case IMA_ADPCM_CODE:
   291             res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4b, format->samplesperblock);
   292             dumppos += res > 0 ? res : 0;
   293             break;
   294         }
   295         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]);
   296         dumppos += res > 0 ? res : 0;
   297     } else {
   298         switch (format->encoding) {
   299         case MS_ADPCM_CODE:
   300         case IMA_ADPCM_CODE:
   301             if (fmtlen >= 20 && format->extsize >= 2) {
   302                 res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4b, format->samplesperblock);
   303                 dumppos += res > 0 ? res : 0;
   304             }
   305             break;
   306         }
   307     }
   308     if (file->fact.status >= 1) {
   309         res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr6, file->fact.samplelength);
   310         dumppos += res > 0 ? res : 0;
   311     }
   312     res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr7, datalen);
   313     dumppos += res > 0 ? res : 0;
   314 
   315     SDL_LogDebug(SDL_LOG_CATEGORY_AUDIO, "%s", dumpstr);
   316 
   317     free(dumpstr);
   318 }
   319 #endif
   320 
   321 static Sint64
   322 WaveAdjustToFactValue(WaveFile *file, Sint64 sampleframes)
   323 {
   324     if (file->fact.status == 2) {
   325         if (file->facthint == FactStrict && sampleframes < file->fact.samplelength) {
   326             return SDL_SetError("Invalid number of sample frames in WAVE fact chunk (too many)");
   327         } else if (sampleframes > file->fact.samplelength) {
   328             return file->fact.samplelength;
   329         }
   330     }
   331 
   332     return sampleframes;
   333 }
   334 
   335 static int
   336 MS_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength)
   337 {
   338     WaveFormat *format = &file->format;
   339     const size_t blockheadersize = (size_t)file->format.channels * 7;
   340     const size_t availableblocks = datalength / file->format.blockalign;
   341     const size_t blockframebitsize = (size_t)file->format.bitspersample * file->format.channels;
   342     const size_t trailingdata = datalength % file->format.blockalign;
   343 
   344     if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) {
   345         /* The size of the data chunk must be a multiple of the block size. */
   346         if (datalength < blockheadersize || trailingdata > 0) {
   347             return SDL_SetError("Truncated MS ADPCM block");
   348         }
   349     }
   350 
   351     /* Calculate number of sample frames that will be decoded. */
   352     file->sampleframes = (Sint64)availableblocks * format->samplesperblock;
   353     if (trailingdata > 0) {
   354         /* The last block is truncated. Check if we can get any samples out of it. */
   355         if (file->trunchint == TruncDropFrame) {
   356             /* Drop incomplete sample frame. */
   357             if (trailingdata >= blockheadersize) {
   358                 size_t trailingsamples = 2 + (trailingdata - blockheadersize) * 8 / blockframebitsize;
   359                 if (trailingsamples > format->samplesperblock) {
   360                     trailingsamples = format->samplesperblock;
   361                 }
   362                 file->sampleframes += trailingsamples;
   363             }
   364         }
   365     }
   366 
   367     file->sampleframes = WaveAdjustToFactValue(file, file->sampleframes);
   368     if (file->sampleframes < 0) {
   369         return -1;
   370     }
   371 
   372     return 0;
   373 }
   374 
   375 static int
   376 MS_ADPCM_Init(WaveFile *file, size_t datalength)
   377 {
   378     WaveFormat *format = &file->format;
   379     WaveChunk *chunk = &file->chunk;
   380     const size_t blockheadersize = (size_t)format->channels * 7;
   381     const size_t blockdatasize = (size_t)format->blockalign - blockheadersize;
   382     const size_t blockframebitsize = (size_t)format->bitspersample * format->channels;
   383     const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize;
   384     const Sint16 presetcoeffs[14] = {256, 0, 512, -256, 0, 0, 192, 64, 240, 0, 460, -208, 392, -232};
   385     size_t i, coeffcount;
   386     MS_ADPCM_CoeffData *coeffdata;
   387 
   388     /* Sanity checks. */
   389 
   390     /* While it's clear how IMA ADPCM handles more than two channels, the nibble
   391      * order of MS ADPCM makes it awkward. The Standards Update does not talk
   392      * about supporting more than stereo anyway.
   393      */
   394     if (format->channels > 2) {
   395         return SDL_SetError("Invalid number of channels");
   396     }
   397 
   398     if (format->bitspersample != 4) {
   399         return SDL_SetError("Invalid MS ADPCM bits per sample of %u", (unsigned int)format->bitspersample);
   400     }
   401 
   402     /* The block size must be big enough to contain the block header. */
   403     if (format->blockalign < blockheadersize) {
   404         return SDL_SetError("Invalid MS ADPCM block size (nBlockAlign)");
   405     }
   406 
   407     if (format->formattag == EXTENSIBLE_CODE) {
   408         /* Does have a GUID (like all format tags), but there's no specification
   409          * for how the data is packed into the extensible header. Making
   410          * assumptions here could lead to new formats nobody wants to support.
   411          */
   412         return SDL_SetError("MS ADPCM with the extensible header is not supported");
   413     }
   414 
   415     /* There are wSamplesPerBlock, wNumCoef, and at least 7 coefficient pairs in
   416      * the extended part of the header.
   417      */
   418     if (chunk->size < 22) {
   419         return SDL_SetError("Could not read MS ADPCM format header");
   420     }
   421 
   422     format->samplesperblock = chunk->data[18] | ((Uint16)chunk->data[19] << 8);
   423     /* Number of coefficient pairs. A pair has two 16-bit integers. */
   424     coeffcount = chunk->data[20] | ((size_t)chunk->data[21] << 8);
   425     /* bPredictor, the integer offset into the coefficients array, is only
   426      * 8 bits. It can only address the first 256 coefficients. Let's limit
   427      * the count number here.
   428      */
   429     if (coeffcount > 256) {
   430         coeffcount = 256;
   431     }
   432 
   433     if (chunk->size < 22 + coeffcount * 4) {
   434         return SDL_SetError("Could not read custom coefficients in MS ADPCM format header");
   435     } else if (format->extsize < 4 + coeffcount * 4) {
   436         return SDL_SetError("Invalid MS ADPCM format header (too small)");
   437     } else if (coeffcount < 7) {
   438         return SDL_SetError("Missing required coefficients in MS ADPCM format header");
   439     }
   440 
   441     coeffdata = (MS_ADPCM_CoeffData *)SDL_malloc(sizeof(MS_ADPCM_CoeffData) + coeffcount * 4);
   442     file->decoderdata = coeffdata; /* Freed in cleanup. */
   443     if (coeffdata == NULL) {
   444         return SDL_OutOfMemory();
   445     }
   446     coeffdata->coeff = &coeffdata->aligndummy;
   447     coeffdata->coeffcount = (Uint16)coeffcount;
   448 
   449     /* Copy the 16-bit pairs. */
   450     for (i = 0; i < coeffcount * 2; i++) {
   451         Sint32 c = chunk->data[22 + i * 2] | ((Sint32)chunk->data[23 + i * 2] << 8);
   452         if (c >= 0x8000) {
   453             c -= 0x10000;
   454         }
   455         if (i < 14 && c != presetcoeffs[i]) {
   456             return SDL_SetError("Wrong preset coefficients in MS ADPCM format header");
   457         }
   458         coeffdata->coeff[i] = (Sint16)c;
   459     }
   460 
   461     /* Technically, wSamplesPerBlock is required, but we have all the
   462      * information in the other fields to calculate it, if it's zero.
   463      */
   464     if (format->samplesperblock == 0) {
   465         /* Let's be nice to the encoders that didn't know how to fill this.
   466          * The Standards Update calculates it this way:
   467          *
   468          *   x = Block size (in bits) minus header size (in bits)
   469          *   y = Bit depth multiplied by channel count
   470          *   z = Number of samples per channel in block header
   471          *   wSamplesPerBlock = x / y + z
   472          */
   473         format->samplesperblock = (Uint32)blockdatasamples + 2;
   474     }
   475 
   476     /* nBlockAlign can be in conflict with wSamplesPerBlock. For example, if
   477      * the number of samples doesn't fit into the block. The Standards Update
   478      * also describes wSamplesPerBlock with a formula that makes it necessary to
   479      * always fill the block with the maximum amount of samples, but this is not
   480      * enforced here as there are no compatibility issues.
   481      * A truncated block header with just one sample is not supported.
   482      */
   483     if (format->samplesperblock == 1 || blockdatasamples < format->samplesperblock - 2) {
   484         return SDL_SetError("Invalid number of samples per MS ADPCM block (wSamplesPerBlock)");
   485     }
   486 
   487     if (MS_ADPCM_CalculateSampleFrames(file, datalength) < 0) {
   488         return -1;
   489     }
   490 
   491     return 0;
   492 }
   493 
   494 static Sint16
   495 MS_ADPCM_ProcessNibble(MS_ADPCM_ChannelState *cstate, Sint32 sample1, Sint32 sample2, Uint8 nybble)
   496 {
   497     const Sint32 max_audioval = 32767;
   498     const Sint32 min_audioval = -32768;
   499     const Uint16 max_deltaval = 65535;
   500     const Uint16 adaptive[] = {
   501         230, 230, 230, 230, 307, 409, 512, 614,
   502         768, 614, 512, 409, 307, 230, 230, 230
   503     };
   504     Sint32 new_sample;
   505     Sint32 errordelta;
   506     Uint32 delta = cstate->delta;
   507 
   508     new_sample = (sample1 * cstate->coeff1 + sample2 * cstate->coeff2) / 256;
   509     /* The nibble is a signed 4-bit error delta. */
   510     errordelta = (Sint32)nybble - (nybble >= 0x08 ? 0x10 : 0);
   511     new_sample += (Sint32)delta * errordelta;
   512     if (new_sample < min_audioval) {
   513         new_sample = min_audioval;
   514     } else if (new_sample > max_audioval) {
   515         new_sample = max_audioval;
   516     }
   517     delta = (delta * adaptive[nybble]) / 256;
   518     if (delta < 16) {
   519         delta = 16;
   520     } else if (delta > max_deltaval) {
   521         /* This issue is not described in the Standards Update and therefore
   522          * undefined. It seems sensible to prevent overflows with a limit.
   523          */
   524         delta = max_deltaval;
   525     }
   526 
   527     cstate->delta = (Uint16)delta;
   528     return (Sint16)new_sample;
   529 }
   530 
   531 static int
   532 MS_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
   533 {
   534     Uint8 coeffindex;
   535     const Uint32 channels = state->channels;
   536     Sint32 sample;
   537     Uint32 c;
   538     MS_ADPCM_ChannelState *cstate = (MS_ADPCM_ChannelState *)state->cstate;
   539     MS_ADPCM_CoeffData *ddata = (MS_ADPCM_CoeffData *)state->ddata;
   540 
   541     for (c = 0; c < channels; c++) {
   542         size_t o = c;
   543 
   544         /* Load the coefficient pair into the channel state. */
   545         coeffindex = state->block.data[o];
   546         if (coeffindex > ddata->coeffcount) {
   547             return SDL_SetError("Invalid MS ADPCM coefficient index in block header");
   548         }
   549         cstate[c].coeff1 = ddata->coeff[coeffindex * 2];
   550         cstate[c].coeff2 = ddata->coeff[coeffindex * 2 + 1];
   551 
   552         /* Initial delta value. */
   553         o = channels + c * 2;
   554         cstate[c].delta = state->block.data[o] | ((Uint16)state->block.data[o + 1] << 8);
   555 
   556         /* Load the samples from the header. Interestingly, the sample later in
   557          * the output stream comes first.
   558          */
   559         o = channels * 3 + c * 2;
   560         sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8);
   561         if (sample >= 0x8000) {
   562             sample -= 0x10000;
   563         }
   564         state->output.data[state->output.pos + channels] = (Sint16)sample;
   565 
   566         o = channels * 5 + c * 2;
   567         sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8);
   568         if (sample >= 0x8000) {
   569             sample -= 0x10000;
   570         }
   571         state->output.data[state->output.pos] = (Sint16)sample;
   572 
   573         state->output.pos++;
   574     }
   575 
   576     state->block.pos += state->blockheadersize;
   577 
   578     /* Skip second sample frame that came from the header. */
   579     state->output.pos += state->channels;
   580 
   581     /* Header provided two sample frames. */
   582     state->framesleft -= 2;
   583 
   584     return 0;
   585 }
   586 
   587 /* Decodes the data of the MS ADPCM block. Decoding will stop if a block is too
   588  * short, returning with none or partially decoded data. The partial data
   589  * will always contain full sample frames (same sample count for each channel).
   590  * Incomplete sample frames are discarded.
   591  */
   592 static int
   593 MS_ADPCM_DecodeBlockData(ADPCM_DecoderState *state)
   594 {
   595     Uint16 nybble = 0;
   596     Sint16 sample1, sample2;
   597     const Uint32 channels = state->channels;
   598     Uint32 c;
   599     MS_ADPCM_ChannelState *cstate = (MS_ADPCM_ChannelState *)state->cstate;
   600 
   601     size_t blockpos = state->block.pos;
   602     size_t blocksize = state->block.size;
   603 
   604     size_t outpos = state->output.pos;
   605 
   606     Sint64 blockframesleft = state->samplesperblock - 2;
   607     if (blockframesleft > state->framesleft) {
   608         blockframesleft = state->framesleft;
   609     }
   610 
   611     while (blockframesleft > 0) {
   612         for (c = 0; c < channels; c++) {
   613             if (nybble & 0x4000) {
   614                 nybble <<= 4;
   615             } else if (blockpos < blocksize) {
   616                 nybble = state->block.data[blockpos++] | 0x4000;
   617             } else {
   618                 /* Out of input data. Drop the incomplete frame and return. */
   619                 state->output.pos = outpos - c;
   620                 return -1;
   621             }
   622 
   623             /* Load previous samples which may come from the block header. */
   624             sample1 = state->output.data[outpos - channels];
   625             sample2 = state->output.data[outpos - channels * 2];
   626 
   627             sample1 = MS_ADPCM_ProcessNibble(cstate + c, sample1, sample2, (nybble >> 4) & 0x0f);
   628             state->output.data[outpos++] = sample1;
   629         }
   630 
   631         state->framesleft--;
   632         blockframesleft--;
   633     }
   634 
   635     state->output.pos = outpos;
   636 
   637     return 0;
   638 }
   639 
   640 static int
   641 MS_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
   642 {
   643     int result;
   644     size_t bytesleft, outputsize;
   645     WaveChunk *chunk = &file->chunk;
   646     ADPCM_DecoderState state;
   647     MS_ADPCM_ChannelState cstate[2];
   648 
   649     SDL_zero(state);
   650     SDL_zero(cstate);
   651 
   652     if (chunk->size != chunk->length) {
   653         /* Could not read everything. Recalculate number of sample frames. */
   654         if (MS_ADPCM_CalculateSampleFrames(file, chunk->size) < 0) {
   655             return -1;
   656         }
   657     }
   658 
   659     /* Nothing to decode, nothing to return. */
   660     if (file->sampleframes == 0) {
   661         *audio_buf = NULL;
   662         *audio_len = 0;
   663         return 0;
   664     }
   665 
   666     state.blocksize = file->format.blockalign;
   667     state.channels = file->format.channels;
   668     state.blockheadersize = (size_t)state.channels * 7;
   669     state.samplesperblock = file->format.samplesperblock;
   670     state.framesize = state.channels * sizeof(Sint16);
   671     state.ddata = file->decoderdata;
   672     state.framestotal = file->sampleframes;
   673     state.framesleft = state.framestotal;
   674 
   675     state.input.data = chunk->data;
   676     state.input.size = chunk->size;
   677     state.input.pos = 0;
   678 
   679     /* The output size in bytes. May get modified if data is truncated. */
   680     outputsize = (size_t)state.framestotal;
   681     if (SafeMult(&outputsize, state.framesize)) {
   682         return SDL_OutOfMemory();
   683     } else if (outputsize > SDL_MAX_UINT32 || state.framestotal > SIZE_MAX) {
   684         return SDL_SetError("WAVE file too big");
   685     }
   686 
   687     state.output.pos = 0;
   688     state.output.size = outputsize / sizeof(Sint16);
   689     state.output.data = (Sint16 *)SDL_malloc(outputsize);
   690     if (state.output.data == NULL) {
   691         return SDL_OutOfMemory();
   692     }
   693 
   694     state.cstate = &cstate;
   695 
   696     /* Decode block by block. A truncated block will stop the decoding. */
   697     bytesleft = state.input.size - state.input.pos;
   698     while (state.framesleft > 0 && bytesleft >= state.blockheadersize) {
   699         state.block.data = state.input.data + state.input.pos;
   700         state.block.size = bytesleft < state.blocksize ? bytesleft : state.blocksize;
   701         state.block.pos = 0;
   702 
   703         if (state.output.size - state.output.pos < (Uint64)state.framesleft * state.channels) {
   704             /* Somehow didn't allocate enough space for the output. */
   705             SDL_free(state.output.data);
   706             return SDL_SetError("Unexpected overflow in MS ADPCM decoder");
   707         }
   708 
   709         /* Initialize decoder with the values from the block header. */
   710         result = MS_ADPCM_DecodeBlockHeader(&state);
   711         if (result == -1) {
   712             SDL_free(state.output.data);
   713             return -1;
   714         }
   715 
   716         /* Decode the block data. It stores the samples directly in the output. */
   717         result = MS_ADPCM_DecodeBlockData(&state);
   718         if (result == -1) {
   719             /* Unexpected end. Stop decoding and return partial data if necessary. */
   720             if (file->trunchint == TruncVeryStrict || file->trunchint == TruncVeryStrict) {
   721                 SDL_free(state.output.data);
   722                 return SDL_SetError("Truncated data chunk");
   723             } else if (file->trunchint != TruncDropFrame) {
   724                 state.output.pos -= state.output.pos % (state.samplesperblock * state.channels);
   725             }
   726             outputsize = state.output.pos * sizeof(Sint16); /* Can't overflow, is always smaller. */
   727             break;
   728         }
   729 
   730         state.input.pos += state.block.size;
   731         bytesleft = state.input.size - state.input.pos;
   732     }
   733 
   734     *audio_buf = (Uint8 *)state.output.data;
   735     *audio_len = (Uint32)outputsize;
   736 
   737     return 0;
   738 }
   739 
   740 static int
   741 IMA_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength)
   742 {
   743     WaveFormat *format = &file->format;
   744     const size_t blockheadersize = (size_t)format->channels * 4;
   745     const size_t subblockframesize = (size_t)format->channels * 4;
   746     const size_t availableblocks = datalength / format->blockalign;
   747     const size_t trailingdata = datalength % format->blockalign;
   748 
   749     if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) {
   750         /* The size of the data chunk must be a multiple of the block size. */
   751         if (datalength < blockheadersize || trailingdata > 0) {
   752             return SDL_SetError("Truncated IMA ADPCM block");
   753         }
   754     }
   755 
   756     /* Calculate number of sample frames that will be decoded. */
   757     file->sampleframes = (Uint64)availableblocks * format->samplesperblock;
   758     if (trailingdata > 0) {
   759         /* The last block is truncated. Check if we can get any samples out of it. */
   760         if (file->trunchint == TruncDropFrame && trailingdata > blockheadersize - 2) {
   761             /* The sample frame in the header of the truncated block is present.
   762              * Drop incomplete sample frames.
   763              */
   764             size_t trailingsamples = 1;
   765 
   766             if (trailingdata > blockheadersize) {
   767                 /* More data following after the header. */
   768                 const size_t trailingblockdata = trailingdata - blockheadersize;
   769                 const size_t trailingsubblockdata = trailingblockdata % subblockframesize;
   770                 trailingsamples += (trailingblockdata / subblockframesize) * 8;
   771                 /* Due to the interleaved sub-blocks, the last 4 bytes determine
   772                  * how many samples of the truncated sub-block are lost.
   773                  */
   774                 if (trailingsubblockdata > subblockframesize - 4) {
   775                     trailingsamples += (trailingsubblockdata % 4) * 2;
   776                 }
   777             }
   778 
   779             if (trailingsamples > format->samplesperblock) {
   780                 trailingsamples = format->samplesperblock;
   781             }
   782             file->sampleframes += trailingsamples;
   783         }
   784     }
   785 
   786     file->sampleframes = WaveAdjustToFactValue(file, file->sampleframes);
   787     if (file->sampleframes < 0) {
   788         return -1;
   789     }
   790 
   791     return 0;
   792 }
   793 
   794 static int
   795 IMA_ADPCM_Init(WaveFile *file, size_t datalength)
   796 {
   797     WaveFormat *format = &file->format;
   798     WaveChunk *chunk = &file->chunk;
   799     const size_t blockheadersize = (size_t)format->channels * 4;
   800     const size_t blockdatasize = (size_t)format->blockalign - blockheadersize;
   801     const size_t blockframebitsize = (size_t)format->bitspersample * format->channels;
   802     const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize;
   803 
   804     /* Sanity checks. */
   805 
   806     /* IMA ADPCM can also have 3-bit samples, but it's not supported by SDL at this time. */
   807     if (format->bitspersample == 3) {
   808         return SDL_SetError("3-bit IMA ADPCM currently not supported");
   809     } else if (format->bitspersample != 4) {
   810         return SDL_SetError("Invalid IMA ADPCM bits per sample of %u", (unsigned int)format->bitspersample);
   811     }
   812 
   813     /* The block size is required to be a multiple of 4 and it must be able to
   814      * hold a block header.
   815      */
   816     if (format->blockalign < blockheadersize || format->blockalign % 4) {
   817         return SDL_SetError("Invalid IMA ADPCM block size (nBlockAlign)");
   818     }
   819 
   820     if (format->formattag == EXTENSIBLE_CODE) {
   821         /* There's no specification for this, but it's basically the same
   822          * format because the extensible header has wSampePerBlocks too.
   823          */
   824     } else  {
   825         /* The Standards Update says there 'should' be 2 bytes for wSamplesPerBlock. */
   826         if (chunk->size >= 20 && format->extsize >= 2) {
   827             format->samplesperblock = chunk->data[18] | ((Uint16)chunk->data[19] << 8);
   828         }
   829     }
   830 
   831     if (format->samplesperblock == 0) {
   832         /* Field zero? No problem. We just assume the encoder packed the block.
   833          * The specification calculates it this way:
   834          *
   835          *   x = Block size (in bits) minus header size (in bits)
   836          *   y = Bit depth multiplied by channel count
   837          *   z = Number of samples per channel in header
   838          *   wSamplesPerBlock = x / y + z
   839          */
   840         format->samplesperblock = (Uint32)blockdatasamples + 1;
   841     }
   842 
   843     /* nBlockAlign can be in conflict with wSamplesPerBlock. For example, if
   844      * the number of samples doesn't fit into the block. The Standards Update
   845      * also describes wSamplesPerBlock with a formula that makes it necessary
   846      * to always fill the block with the maximum amount of samples, but this is
   847      * not enforced here as there are no compatibility issues.
   848      */
   849     if (blockdatasamples < format->samplesperblock - 1) {
   850         return SDL_SetError("Invalid number of samples per IMA ADPCM block (wSamplesPerBlock)");
   851     }
   852 
   853     if (IMA_ADPCM_CalculateSampleFrames(file, datalength) < 0) {
   854         return -1;
   855     }
   856 
   857     return 0;
   858 }
   859 
   860 static Sint16
   861 IMA_ADPCM_ProcessNibble(Sint8 *cindex, Sint16 lastsample, Uint8 nybble)
   862 {
   863     const Sint32 max_audioval = 32767;
   864     const Sint32 min_audioval = -32768;
   865     const Sint8 index_table_4b[16] = {
   866         -1, -1, -1, -1,
   867         2, 4, 6, 8,
   868         -1, -1, -1, -1,
   869         2, 4, 6, 8
   870     };
   871     const Uint16 step_table[89] = {
   872         7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31,
   873         34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130,
   874         143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408,
   875         449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282,
   876         1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327,
   877         3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630,
   878         9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350,
   879         22385, 24623, 27086, 29794, 32767
   880     };
   881     Uint32 step;
   882     Sint32 sample, delta;
   883     Sint8 index = *cindex;
   884 
   885     /* Clamp index into valid range. */
   886     if (index > 88) {
   887         index = 88;
   888     } else if (index < 0) {
   889         index = 0;
   890     }
   891 
   892     /* explicit cast to avoid gcc warning about using 'char' as array index */
   893     step = step_table[(size_t)index];
   894 
   895     /* Update index value */
   896     *cindex = index + index_table_4b[nybble];
   897 
   898     /* This calculation uses shifts and additions because multiplications were
   899      * much slower back then. Sadly, this can't just be replaced with an actual
   900      * multiplication now as the old algorithm drops some bits. The closest
   901      * approximation I could find is something like this:
   902      * (nybble & 0x8 ? -1 : 1) * ((nybble & 0x7) * step / 4 + step / 8)
   903      */
   904     delta = step >> 3;
   905     if (nybble & 0x04)
   906         delta += step;
   907     if (nybble & 0x02)
   908         delta += step >> 1;
   909     if (nybble & 0x01)
   910         delta += step >> 2;
   911     if (nybble & 0x08)
   912         delta = -delta;
   913 
   914     sample = lastsample + delta;
   915 
   916     /* Clamp output sample */
   917     if (sample > max_audioval) {
   918         sample = max_audioval;
   919     } else if (sample < min_audioval) {
   920         sample = min_audioval;
   921     }
   922 
   923     return (Sint16)sample;
   924 }
   925 
   926 static int
   927 IMA_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
   928 {
   929     Sint16 step;
   930     Uint32 c;
   931     Uint8 *cstate = state->cstate;
   932 
   933     for (c = 0; c < state->channels; c++) {
   934         size_t o = state->block.pos + c * 4;
   935 
   936         /* Extract the sample from the header. */
   937         Sint32 sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8);
   938         if (sample >= 0x8000) {
   939             sample -= 0x10000;
   940         }
   941         state->output.data[state->output.pos++] = (Sint16)sample;
   942 
   943         /* Channel step index. */
   944         step = (Sint16)state->block.data[o + 2];
   945         cstate[c] = (Sint8)(step > 0x80 ? step - 0x100 : step);
   946 
   947         /* Reserved byte in block header, should be 0. */
   948         if (state->block.data[o + 3] != 0) {
   949             /* Uh oh, corrupt data?  Buggy code? */ ;
   950         }
   951     }
   952 
   953     state->block.pos += state->blockheadersize;
   954 
   955     /* Header provided one sample frame. */
   956     state->framesleft--;
   957 
   958     return 0;
   959 }
   960 
   961 /* Decodes the data of the IMA ADPCM block. Decoding will stop if a block is too
   962  * short, returning with none or partially decoded data. The partial data always
   963  * contains full sample frames (same sample count for each channel).
   964  * Incomplete sample frames are discarded.
   965  */
   966 static int
   967 IMA_ADPCM_DecodeBlockData(ADPCM_DecoderState *state)
   968 {
   969     size_t i;
   970     int retval = 0;
   971     const Uint32 channels = state->channels;
   972     const size_t subblockframesize = channels * 4;
   973     Uint64 bytesrequired;
   974     Uint32 c;
   975 
   976     size_t blockpos = state->block.pos;
   977     size_t blocksize = state->block.size;
   978     size_t blockleft = blocksize - blockpos;
   979 
   980     size_t outpos = state->output.pos;
   981 
   982     Sint64 blockframesleft = state->samplesperblock - 1;
   983     if (blockframesleft > state->framesleft) {
   984         blockframesleft = state->framesleft;
   985     }
   986 
   987     bytesrequired = (blockframesleft + 7) / 8 * subblockframesize;
   988     if (blockleft < bytesrequired) {
   989         /* Data truncated. Calculate how many samples we can get out if it. */
   990         const size_t guaranteedframes = blockleft / subblockframesize;
   991         const size_t remainingbytes = blockleft % subblockframesize;
   992         blockframesleft = guaranteedframes;
   993         if (remainingbytes > subblockframesize - 4) {
   994             blockframesleft += (remainingbytes % 4) * 2;
   995         }
   996         /* Signal the truncation. */
   997         retval = -1;
   998     }
   999 
  1000     /* Each channel has their nibbles packed into 32-bit blocks. These blocks
  1001      * are interleaved and make up the data part of the ADPCM block. This loop
  1002      * decodes the samples as they come from the input data and puts them at
  1003      * the appropriate places in the output data.
  1004      */
  1005     while (blockframesleft > 0) {
  1006         const size_t subblocksamples = blockframesleft < 8 ? (size_t)blockframesleft : 8;
  1007 
  1008         for (c = 0; c < channels; c++) {
  1009             Uint8 nybble = 0;
  1010             /* Load previous sample which may come from the block header. */
  1011             Sint16 sample = state->output.data[outpos + c - channels];
  1012 
  1013             for (i = 0; i < subblocksamples; i++) {
  1014                 if (i & 1) {
  1015                     nybble >>= 4;
  1016                 } else {
  1017                     nybble = state->block.data[blockpos++];
  1018                 }
  1019 
  1020                 sample = IMA_ADPCM_ProcessNibble((Sint8 *)state->cstate + c, sample, nybble & 0x0f);
  1021                 state->output.data[outpos + c + i * channels] = sample;
  1022             }
  1023         }
  1024 
  1025         outpos += channels * subblocksamples;
  1026         state->framesleft -= subblocksamples;
  1027         blockframesleft -= subblocksamples;
  1028     }
  1029 
  1030     state->block.pos = blockpos;
  1031     state->output.pos = outpos;
  1032 
  1033     return retval;
  1034 }
  1035 
  1036 static int
  1037 IMA_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
  1038 {
  1039     int result;
  1040     size_t bytesleft, outputsize;
  1041     WaveChunk *chunk = &file->chunk;
  1042     ADPCM_DecoderState state;
  1043     Sint8 *cstate;
  1044 
  1045     if (chunk->size != chunk->length) {
  1046         /* Could not read everything. Recalculate number of sample frames. */
  1047         if (IMA_ADPCM_CalculateSampleFrames(file, chunk->size) < 0) {
  1048             return -1;
  1049         }
  1050     }
  1051 
  1052     /* Nothing to decode, nothing to return. */
  1053     if (file->sampleframes == 0) {
  1054         *audio_buf = NULL;
  1055         *audio_len = 0;
  1056         return 0;
  1057     }
  1058 
  1059     SDL_zero(state);
  1060     state.channels = file->format.channels;
  1061     state.blocksize = file->format.blockalign;
  1062     state.blockheadersize = (size_t)state.channels * 4;
  1063     state.samplesperblock = file->format.samplesperblock;
  1064     state.framesize = state.channels * sizeof(Sint16);
  1065     state.framestotal = file->sampleframes;
  1066     state.framesleft = state.framestotal;
  1067 
  1068     state.input.data = chunk->data;
  1069     state.input.size = chunk->size;
  1070     state.input.pos = 0;
  1071 
  1072     /* The output size in bytes. May get modified if data is truncated. */
  1073     outputsize = (size_t)state.framestotal;
  1074     if (SafeMult(&outputsize, state.framesize)) {
  1075         return SDL_OutOfMemory();
  1076     } else if (outputsize > SDL_MAX_UINT32 || state.framestotal > SIZE_MAX) {
  1077         return SDL_SetError("WAVE file too big");
  1078     }
  1079 
  1080     state.output.pos = 0;
  1081     state.output.size = outputsize / sizeof(Sint16);
  1082     state.output.data = (Sint16 *)SDL_malloc(outputsize);
  1083     if (state.output.data == NULL) {
  1084         return SDL_OutOfMemory();
  1085     }
  1086 
  1087     cstate = (Sint8 *)SDL_calloc(state.channels, sizeof(Sint8));
  1088     if (cstate == NULL) {
  1089         SDL_free(state.output.data);
  1090         return SDL_OutOfMemory();
  1091     }
  1092     state.cstate = cstate;
  1093 
  1094     /* Decode block by block. A truncated block will stop the decoding. */
  1095     bytesleft = state.input.size - state.input.pos;
  1096     while (state.framesleft > 0 && bytesleft >= state.blockheadersize) {
  1097         state.block.data = state.input.data + state.input.pos;
  1098         state.block.size = bytesleft < state.blocksize ? bytesleft : state.blocksize;
  1099         state.block.pos = 0;
  1100 
  1101         if (state.output.size - state.output.pos < (Uint64)state.framesleft * state.channels) {
  1102             /* Somehow didn't allocate enough space for the output. */
  1103             SDL_free(state.output.data);
  1104             SDL_free(cstate);
  1105             return SDL_SetError("Unexpected overflow in IMA ADPCM decoder");
  1106         }
  1107 
  1108         /* Initialize decoder with the values from the block header. */
  1109         result = IMA_ADPCM_DecodeBlockHeader(&state);
  1110 
  1111         /* Decode the block data. It stores the samples directly in the output. */
  1112         result = IMA_ADPCM_DecodeBlockData(&state);
  1113         if (result == -1) {
  1114             /* Unexpected end. Stop decoding and return partial data if necessary. */
  1115             if (file->trunchint == TruncVeryStrict || file->trunchint == TruncVeryStrict) {
  1116                 SDL_free(state.output.data);
  1117                 SDL_free(cstate);
  1118                 return SDL_SetError("Truncated data chunk");
  1119             } else if (file->trunchint != TruncDropFrame) {
  1120                 state.output.pos -= state.output.pos % (state.samplesperblock * state.channels);
  1121             }
  1122             outputsize = state.output.pos * sizeof(Sint16); /* Can't overflow, is always smaller. */
  1123             break;
  1124         }
  1125 
  1126         state.input.pos += state.block.size;
  1127         bytesleft = state.input.size - state.input.pos;
  1128     }
  1129 
  1130     *audio_buf = (Uint8 *)state.output.data;
  1131     *audio_len = (Uint32)outputsize;
  1132 
  1133     SDL_free(cstate);
  1134 
  1135     return 0;
  1136 }
  1137 
  1138 static int
  1139 LAW_Init(WaveFile *file, size_t datalength)
  1140 {
  1141     WaveFormat *format = &file->format;
  1142 
  1143     /* Standards Update requires this to be 8. */
  1144     if (format->bitspersample != 8) {
  1145         return SDL_SetError("Invalid companded bits per sample of %u", (unsigned int)format->bitspersample);
  1146     }
  1147 
  1148     /* Not going to bother with weird padding. */
  1149     if (format->blockalign != format->channels) {
  1150         return SDL_SetError("Unsupported block alignment");
  1151     }
  1152 
  1153     if ((file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict)) {
  1154         if (format->blockalign > 1 && datalength % format->blockalign) {
  1155             return SDL_SetError("Truncated data chunk in WAVE file");
  1156         }
  1157     }
  1158 
  1159     file->sampleframes = WaveAdjustToFactValue(file, datalength / format->blockalign);
  1160     if (file->sampleframes < 0) {
  1161         return -1;
  1162     }
  1163 
  1164     return 0;
  1165 }
  1166 
  1167 static int
  1168 LAW_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
  1169 {
  1170 #ifdef SDL_WAVE_LAW_LUT
  1171     const Sint16 alaw_lut[256] = {
  1172         -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736, -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784, -2752,
  1173         -2624, -3008, -2880, -2240, -2112, -2496, -2368, -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392, -22016,
  1174         -20992, -24064, -23040, -17920, -16896, -19968, -18944, -30208, -29184, -32256, -31232, -26112, -25088, -28160, -27136, -11008,
  1175         -10496, -12032, -11520, -8960, -8448, -9984, -9472, -15104, -14592, -16128, -15616, -13056, -12544, -14080, -13568, -344,
  1176         -328, -376, -360, -280, -264, -312, -296, -472, -456, -504, -488, -408, -392, -440, -424, -88,
  1177         -72, -120, -104, -24, -8, -56, -40, -216, -200, -248, -232, -152, -136, -184, -168, -1376,
  1178         -1312, -1504, -1440, -1120, -1056, -1248, -1184, -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696, -688,
  1179         -656, -752, -720, -560, -528, -624, -592, -944, -912, -1008, -976, -816, -784, -880, -848, 5504,
  1180         5248, 6016, 5760, 4480, 4224, 4992, 4736, 7552, 7296, 8064, 7808, 6528, 6272, 7040, 6784, 2752,
  1181         2624, 3008, 2880, 2240, 2112, 2496, 2368, 3776, 3648, 4032, 3904, 3264, 3136, 3520, 3392, 22016,
  1182         20992, 24064, 23040, 17920, 16896, 19968, 18944, 30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136, 11008,
  1183         10496, 12032, 11520, 8960, 8448, 9984, 9472, 15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568, 344,
  1184         328, 376, 360, 280, 264, 312, 296, 472, 456, 504, 488, 408, 392, 440, 424, 88,
  1185         72, 120, 104, 24, 8, 56, 40, 216, 200, 248, 232, 152, 136, 184, 168, 1376,
  1186         1312, 1504, 1440, 1120, 1056, 1248, 1184, 1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696, 688,
  1187         656, 752, 720, 560, 528, 624, 592, 944, 912, 1008, 976, 816, 784, 880, 848
  1188     };
  1189     const Sint16 mulaw_lut[256] = {
  1190         -32124, -31100, -30076, -29052, -28028, -27004, -25980, -24956, -23932, -22908, -21884, -20860, -19836, -18812, -17788, -16764, -15996,
  1191         -15484, -14972, -14460, -13948, -13436, -12924, -12412, -11900, -11388, -10876, -10364, -9852, -9340, -8828, -8316, -7932,
  1192         -7676, -7420, -7164, -6908, -6652, -6396, -6140, -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092, -3900,
  1193         -3772, -3644, -3516, -3388, -3260, -3132, -3004, -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980, -1884,
  1194         -1820, -1756, -1692, -1628, -1564, -1500, -1436, -1372, -1308, -1244, -1180, -1116, -1052, -988, -924, -876,
  1195         -844, -812, -780, -748, -716, -684, -652, -620, -588, -556, -524, -492, -460, -428, -396, -372,
  1196         -356, -340, -324, -308, -292, -276, -260, -244, -228, -212, -196, -180, -164, -148, -132, -120,
  1197         -112, -104, -96, -88, -80, -72, -64, -56, -48, -40, -32, -24, -16, -8, 0, 32124,
  1198         31100, 30076, 29052, 28028, 27004, 25980, 24956, 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, 15996,
  1199         15484, 14972, 14460, 13948, 13436, 12924, 12412, 11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316, 7932,
  1200         7676, 7420, 7164, 6908, 6652, 6396, 6140, 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092, 3900,
  1201         3772, 3644, 3516, 3388, 3260, 3132, 3004, 2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980, 1884,
  1202         1820, 1756, 1692, 1628, 1564, 1500, 1436, 1372, 1308, 1244, 1180, 1116, 1052, 988, 924, 876,
  1203         844, 812, 780, 748, 716, 684, 652, 620, 588, 556, 524, 492, 460, 428, 396, 372,
  1204         356, 340, 324, 308, 292, 276, 260, 244, 228, 212, 196, 180, 164, 148, 132, 120,
  1205         112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0
  1206     };
  1207 #endif
  1208 
  1209     WaveFormat *format = &file->format;
  1210     WaveChunk *chunk = &file->chunk;
  1211     size_t i, sample_count, expanded_len;
  1212     Uint8 *src;
  1213     Sint16 *dst;
  1214 
  1215     if (chunk->length != chunk->size) {
  1216         file->sampleframes = WaveAdjustToFactValue(file, chunk->size / format->blockalign);
  1217         if (file->sampleframes < 0) {
  1218             return -1;
  1219         }
  1220     }
  1221 
  1222     /* Nothing to decode, nothing to return. */
  1223     if (file->sampleframes == 0) {
  1224         *audio_buf = NULL;
  1225         *audio_len = 0;
  1226         return 0;
  1227     }
  1228 
  1229     sample_count = (size_t)file->sampleframes;
  1230     if (SafeMult(&sample_count, format->channels)) {
  1231         return SDL_OutOfMemory();
  1232     }
  1233 
  1234     expanded_len = sample_count;
  1235     if (SafeMult(&expanded_len, sizeof(Sint16))) {
  1236         return SDL_OutOfMemory();
  1237     } else if (expanded_len > SDL_MAX_UINT32 || file->sampleframes > SIZE_MAX) {
  1238         return SDL_SetError("WAVE file too big");
  1239     }
  1240 
  1241     src = (Uint8 *)SDL_realloc(chunk->data, expanded_len);
  1242     if (src == NULL) {
  1243         return SDL_OutOfMemory();
  1244     }
  1245     chunk->data = NULL;
  1246     chunk->size = 0;
  1247 
  1248     dst = (Sint16 *)src;
  1249 
  1250     /* Work backwards, since we're expanding in-place. SDL_AudioSpec.format will
  1251      * inform the caller about the byte order.
  1252      */
  1253     i = sample_count;
  1254     switch (file->format.encoding) {
  1255 #ifdef SDL_WAVE_LAW_LUT
  1256     case ALAW_CODE:
  1257         while (i--) {
  1258             dst[i] = alaw_lut[src[i]];
  1259         }
  1260         break;
  1261     case MULAW_CODE:
  1262         while (i--) {
  1263             dst[i] = mulaw_lut[src[i]];
  1264         }
  1265         break;
  1266 #else
  1267     case ALAW_CODE:
  1268         while (i--) {
  1269             Uint8 nibble = src[i];
  1270             Uint8 exponent = (nibble & 0x7f) ^ 0x55;
  1271             Sint16 mantissa = exponent & 0xf;
  1272 
  1273             exponent >>= 4;
  1274             if (exponent > 0) {
  1275                 mantissa |= 0x10;
  1276             }
  1277             mantissa = (mantissa << 4) | 0x8;
  1278             if (exponent > 1) {
  1279                 mantissa <<= exponent - 1;
  1280             }
  1281 
  1282             dst[i] = nibble & 0x80 ? mantissa : -mantissa;
  1283         }
  1284         break;
  1285     case MULAW_CODE:
  1286         while (i--) {
  1287             Uint8 nibble = ~src[i];
  1288             Sint16 mantissa = nibble & 0xf;
  1289             Uint8 exponent = (nibble >> 4) & 0x7;
  1290             Sint16 step = 4 << (exponent + 1);
  1291 
  1292             mantissa = (0x80 << exponent) + step * mantissa + step / 2 - 132;
  1293 
  1294             dst[i] = nibble & 0x80 ? -mantissa : mantissa;
  1295         }
  1296         break;
  1297 #endif
  1298     default:
  1299         SDL_free(src);
  1300         return SDL_SetError("Unknown companded encoding");
  1301     }
  1302 
  1303     *audio_buf = src;
  1304     *audio_len = (Uint32)expanded_len;
  1305 
  1306     return 0;
  1307 }
  1308 
  1309 static int
  1310 PCM_Init(WaveFile *file, size_t datalength)
  1311 {
  1312     WaveFormat *format = &file->format;
  1313 
  1314     if (format->encoding == PCM_CODE) {
  1315         switch (format->bitspersample) {
  1316         case 8:
  1317         case 16:
  1318         case 24:
  1319         case 32:
  1320             /* These are supported. */
  1321             break;
  1322         default:
  1323             return SDL_SetError("%u-bit PCM format not supported", (unsigned int)format->bitspersample);
  1324         }
  1325     } else if (format->encoding == IEEE_FLOAT_CODE) {
  1326         if (format->bitspersample != 32) {
  1327             return SDL_SetError("%u-bit IEEE floating-point format not supported", (unsigned int)format->bitspersample);
  1328         }
  1329     }
  1330 
  1331     /* It wouldn't be that hard to support more exotic block sizes, but
  1332      * the most common formats should do for now.
  1333      */
  1334     if (format->blockalign * 8 != format->channels * format->bitspersample) {
  1335         return SDL_SetError("Unsupported block alignment");
  1336     }
  1337 
  1338     if ((file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict)) {
  1339         if (format->blockalign > 1 && datalength % format->blockalign) {
  1340             return SDL_SetError("Truncated data chunk in WAVE file");
  1341         }
  1342     }
  1343 
  1344     file->sampleframes = WaveAdjustToFactValue(file, datalength / format->blockalign);
  1345     if (file->sampleframes < 0) {
  1346         return -1;
  1347     }
  1348 
  1349     return 0;
  1350 }
  1351 
  1352 static int
  1353 PCM_ConvertSint24ToSint32(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
  1354 {
  1355     WaveFormat *format = &file->format;
  1356     WaveChunk *chunk = &file->chunk;
  1357     size_t i, expanded_len, sample_count;
  1358     Uint8 *ptr;
  1359 
  1360     sample_count = (size_t)file->sampleframes;
  1361     if (SafeMult(&sample_count, format->channels)) {
  1362         return SDL_OutOfMemory();
  1363     }
  1364 
  1365     expanded_len = sample_count;
  1366     if (SafeMult(&expanded_len, sizeof(Sint32))) {
  1367         return SDL_OutOfMemory();
  1368     } else if (expanded_len > SDL_MAX_UINT32 || file->sampleframes > SIZE_MAX) {
  1369         return SDL_SetError("WAVE file too big");
  1370     }
  1371 
  1372     ptr = (Uint8 *)SDL_realloc(chunk->data, expanded_len);
  1373     if (ptr == NULL) {
  1374         return SDL_OutOfMemory();
  1375     }
  1376 
  1377     /* This pointer is now invalid. */
  1378     chunk->data = NULL;
  1379     chunk->size = 0;
  1380 
  1381     *audio_buf = ptr;
  1382     *audio_len = (Uint32)expanded_len;
  1383 
  1384     /* work from end to start, since we're expanding in-place. */
  1385     for (i = sample_count; i > 0; i--) {
  1386         const size_t o = i - 1;
  1387         uint8_t b[4];
  1388 
  1389         b[0] = 0;
  1390         b[1] = ptr[o * 3];
  1391         b[2] = ptr[o * 3 + 1];
  1392         b[3] = ptr[o * 3 + 2];
  1393 
  1394         ptr[o * 4 + 0] = b[0];
  1395         ptr[o * 4 + 1] = b[1];
  1396         ptr[o * 4 + 2] = b[2];
  1397         ptr[o * 4 + 3] = b[3];
  1398     }
  1399 
  1400     return 0;
  1401 }
  1402 
  1403 static int
  1404 PCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
  1405 {
  1406     WaveFormat *format = &file->format;
  1407     WaveChunk *chunk = &file->chunk;
  1408     size_t outputsize;
  1409 
  1410     if (chunk->length != chunk->size) {
  1411         file->sampleframes = WaveAdjustToFactValue(file, chunk->size / format->blockalign);
  1412         if (file->sampleframes < 0) {
  1413             return -1;
  1414         }
  1415     }
  1416 
  1417     /* Nothing to decode, nothing to return. */
  1418     if (file->sampleframes == 0) {
  1419         *audio_buf = NULL;
  1420         *audio_len = 0;
  1421         return 0;
  1422     }
  1423 
  1424     /* 24-bit samples get shifted to 32 bits. */
  1425     if (format->encoding == PCM_CODE && format->bitspersample == 24) {
  1426         return PCM_ConvertSint24ToSint32(file, audio_buf, audio_len);
  1427     }
  1428 
  1429     outputsize = (size_t)file->sampleframes;
  1430     if (SafeMult(&outputsize, format->blockalign)) {
  1431         return SDL_OutOfMemory();
  1432     } else if (outputsize > SDL_MAX_UINT32 || file->sampleframes > SIZE_MAX) {
  1433         return SDL_SetError("WAVE file too big");
  1434     }
  1435 
  1436     *audio_buf = chunk->data;
  1437     *audio_len = (Uint32)outputsize;
  1438 
  1439     /* This pointer is going to be returned to the caller. Prevent free in cleanup. */
  1440     chunk->data = NULL;
  1441     chunk->size = 0;
  1442 
  1443     return 0;
  1444 }
  1445 
  1446 static WaveRiffSizeHint
  1447 WaveGetRiffSizeHint()
  1448 {
  1449     const char *hint = SDL_GetHint(SDL_HINT_WAVE_RIFF_CHUNK_SIZE);
  1450 
  1451     if (hint != NULL) {
  1452         if (SDL_strcmp(hint, "force") == 0) {
  1453             return RiffSizeForce;
  1454         } else if (SDL_strcmp(hint, "ignore") == 0) {
  1455             return RiffSizeIgnore;
  1456         } else if (SDL_strcmp(hint, "ignorezero") == 0) {
  1457             return RiffSizeIgnoreZero;
  1458         } else if (SDL_strcmp(hint, "maximum") == 0) {
  1459             return RiffSizeMaximum;
  1460         }
  1461     }
  1462 
  1463     return RiffSizeNoHint;
  1464 }
  1465 
  1466 static WaveTruncationHint
  1467 WaveGetTruncationHint()
  1468 {
  1469     const char *hint = SDL_GetHint(SDL_HINT_WAVE_TRUNCATION);
  1470 
  1471     if (hint != NULL) {
  1472         if (SDL_strcmp(hint, "verystrict") == 0) {
  1473             return TruncVeryStrict;
  1474         } else if (SDL_strcmp(hint, "strict") == 0) {
  1475             return TruncStrict;
  1476         } else if (SDL_strcmp(hint, "dropframe") == 0) {
  1477             return TruncDropFrame;
  1478         } else if (SDL_strcmp(hint, "dropblock") == 0) {
  1479             return TruncDropBlock;
  1480         }
  1481     }
  1482 
  1483     return TruncNoHint;
  1484 }
  1485 
  1486 static WaveFactChunkHint
  1487 WaveGetFactChunkHint()
  1488 {
  1489     const char *hint = SDL_GetHint(SDL_HINT_WAVE_FACT_CHUNK);
  1490 
  1491     if (hint != NULL) {
  1492         if (SDL_strcmp(hint, "truncate") == 0) {
  1493             return FactTruncate;
  1494         } else if (SDL_strcmp(hint, "strict") == 0) {
  1495             return FactStrict;
  1496         } else if (SDL_strcmp(hint, "ignorezero") == 0) {
  1497             return FactIgnoreZero;
  1498         } else if (SDL_strcmp(hint, "ignore") == 0) {
  1499             return FactIgnore;
  1500         }
  1501     }
  1502 
  1503     return FactNoHint;
  1504 }
  1505 
  1506 static void
  1507 WaveFreeChunkData(WaveChunk *chunk)
  1508 {
  1509     if (chunk->data != NULL) {
  1510         SDL_free(chunk->data);
  1511         chunk->data = NULL;
  1512     }
  1513     chunk->size = 0;
  1514 }
  1515 
  1516 static int
  1517 WaveNextChunk(SDL_RWops *src, WaveChunk *chunk)
  1518 {
  1519     Uint32 chunkheader[2];
  1520     Sint64 nextposition = chunk->position + chunk->length;
  1521 
  1522     /* Data is no longer valid after this function returns. */
  1523     WaveFreeChunkData(chunk);
  1524 
  1525     /* Error on overflows. */
  1526     if (SDL_MAX_SINT64 - chunk->length < chunk->position || SDL_MAX_SINT64 - 8 < nextposition) {
  1527         return -1;
  1528     }
  1529 
  1530     /* RIFF chunks have a 2-byte alignment. Skip padding byte. */
  1531     if (chunk->length & 1) {
  1532         nextposition++;
  1533     }
  1534 
  1535     if (SDL_RWseek(src, nextposition, RW_SEEK_SET) != nextposition) {
  1536         /* Not sure how we ended up here. Just abort. */
  1537         return -2;
  1538     } else if (SDL_RWread(src, chunkheader, 4, 2) != 2) {
  1539         return -1;
  1540     }
  1541 
  1542     chunk->fourcc = SDL_SwapLE32(chunkheader[0]);
  1543     chunk->length = SDL_SwapLE32(chunkheader[1]);
  1544     chunk->position = nextposition + 8;
  1545 
  1546     return 0;
  1547 }
  1548 
  1549 static int
  1550 WaveReadPartialChunkData(SDL_RWops *src, WaveChunk *chunk, size_t length)
  1551 {
  1552     WaveFreeChunkData(chunk);
  1553 
  1554     if (length > chunk->length) {
  1555         length = chunk->length;
  1556     }
  1557 
  1558     if (length > 0) {
  1559         chunk->data = SDL_malloc(length);
  1560         if (chunk->data == NULL) {
  1561             return SDL_OutOfMemory();
  1562         }
  1563 
  1564         if (SDL_RWseek(src, chunk->position, RW_SEEK_SET) != chunk->position) {
  1565             /* Not sure how we ended up here. Just abort. */
  1566             return -2;
  1567         }
  1568 
  1569         chunk->size = SDL_RWread(src, chunk->data, 1, length);
  1570         if (chunk->size != length) {
  1571             /* Expected to be handled by the caller. */
  1572         }
  1573     }
  1574 
  1575     return 0;
  1576 }
  1577 
  1578 static int
  1579 WaveReadChunkData(SDL_RWops *src, WaveChunk *chunk)
  1580 {
  1581     return WaveReadPartialChunkData(src, chunk, chunk->length);
  1582 }
  1583 
  1584 typedef struct WaveExtensibleGUID {
  1585     Uint16 encoding;
  1586     Uint8 guid[16];
  1587 } WaveExtensibleGUID;
  1588 
  1589 /* Some of the GUIDs that are used by WAVEFORMATEXTENSIBLE. */
  1590 #define WAVE_FORMATTAG_GUID(tag) {(tag) & 0xff, (tag) >> 8, 0, 0, 0, 0, 16, 0, 128, 0, 0, 170, 0, 56, 155, 113}
  1591 static WaveExtensibleGUID extensible_guids[] = {
  1592     {PCM_CODE,        WAVE_FORMATTAG_GUID(PCM_CODE)},
  1593     {MS_ADPCM_CODE,   WAVE_FORMATTAG_GUID(MS_ADPCM_CODE)},
  1594     {IEEE_FLOAT_CODE, WAVE_FORMATTAG_GUID(IEEE_FLOAT_CODE)},
  1595     {ALAW_CODE,       WAVE_FORMATTAG_GUID(ALAW_CODE)},
  1596     {MULAW_CODE,      WAVE_FORMATTAG_GUID(MULAW_CODE)},
  1597     {IMA_ADPCM_CODE,  WAVE_FORMATTAG_GUID(IMA_ADPCM_CODE)}
  1598 };
  1599 
  1600 static Uint16
  1601 WaveGetFormatGUIDEncoding(WaveFormat *format)
  1602 {
  1603     size_t i;
  1604     for (i = 0; i < SDL_arraysize(extensible_guids); i++) {
  1605         if (SDL_memcmp(format->subformat, extensible_guids[i].guid, 16) == 0) {
  1606             return extensible_guids[i].encoding;
  1607         }
  1608     }
  1609     return UNKNOWN_CODE;
  1610 }
  1611 
  1612 static int
  1613 WaveReadFormat(WaveFile *file)
  1614 {
  1615     WaveChunk *chunk = &file->chunk;
  1616     WaveFormat *format = &file->format;
  1617     SDL_RWops *fmtsrc;
  1618     size_t fmtlen = chunk->size;
  1619 
  1620     if (fmtlen > SDL_MAX_SINT32) {
  1621         /* Limit given by SDL_RWFromConstMem. */
  1622         return SDL_SetError("Data of WAVE fmt chunk too big");
  1623     }
  1624     fmtsrc = SDL_RWFromConstMem(chunk->data, (int)chunk->size);
  1625     if (fmtsrc == NULL) {
  1626         return SDL_OutOfMemory();
  1627     }
  1628 
  1629     format->formattag = SDL_ReadLE16(fmtsrc);
  1630     format->encoding = format->formattag;
  1631     format->channels = SDL_ReadLE16(fmtsrc);
  1632     format->frequency = SDL_ReadLE32(fmtsrc);
  1633     format->byterate = SDL_ReadLE32(fmtsrc);
  1634     format->blockalign = SDL_ReadLE16(fmtsrc);
  1635 
  1636     /* This is PCM specific in the first version of the specification. */
  1637     if (fmtlen >= 16) {
  1638         format->bitspersample = SDL_ReadLE16(fmtsrc);
  1639     } else if (format->encoding == PCM_CODE) {
  1640         SDL_RWclose(fmtsrc);
  1641         return SDL_SetError("Missing wBitsPerSample field in WAVE fmt chunk");
  1642     }
  1643 
  1644     /* The earlier versions also don't have this field. */
  1645     if (fmtlen >= 18) {
  1646         format->extsize = SDL_ReadLE16(fmtsrc);
  1647     }
  1648 
  1649     if (format->formattag == EXTENSIBLE_CODE) {
  1650         /* note that this ignores channel masks, smaller valid bit counts
  1651          * inside a larger container, and most subtypes. This is just enough
  1652          * to get things that didn't really _need_ WAVE_FORMAT_EXTENSIBLE
  1653          * to be useful working when they use this format flag.
  1654          */
  1655 
  1656         /* Extensible header must be at least 22 bytes. */
  1657         if (fmtlen < 40 || format->extsize < 22) {
  1658             SDL_RWclose(fmtsrc);
  1659             return SDL_SetError("Extensible WAVE header too small");
  1660         }
  1661 
  1662         format->validsamplebits = SDL_ReadLE16(fmtsrc);
  1663         format->samplesperblock = format->validsamplebits;
  1664         format->channelmask = SDL_ReadLE32(fmtsrc);
  1665         SDL_RWread(fmtsrc, format->subformat, 1, 16);
  1666         format->encoding = WaveGetFormatGUIDEncoding(format);
  1667     }
  1668 
  1669     SDL_RWclose(fmtsrc);
  1670 
  1671     return 0;
  1672 }
  1673 
  1674 static int
  1675 WaveCheckFormat(WaveFile *file, size_t datalength)
  1676 {
  1677     WaveFormat *format = &file->format;
  1678 
  1679     /* Check for some obvious issues. */
  1680 
  1681     if (format->channels == 0) {
  1682         return SDL_SetError("Invalid number of channels");
  1683     } else if (format->channels > 255) {
  1684         /* Limit given by SDL_AudioSpec.channels. */
  1685         return SDL_SetError("Number of channels exceeds limit of 255");
  1686     }
  1687 
  1688     if (format->frequency == 0) {
  1689         return SDL_SetError("Invalid sample rate");
  1690     } else if (format->frequency > INT_MAX) {
  1691         /* Limit given by SDL_AudioSpec.freq. */
  1692         return SDL_SetError("Sample rate exceeds limit of %d", INT_MAX);
  1693     }
  1694 
  1695     /* Reject invalid fact chunks in strict mode. */
  1696     if (file->facthint == FactStrict && file->fact.status == -1) {
  1697         return SDL_SetError("Invalid fact chunk in WAVE file");
  1698     }
  1699 
  1700     /* Check for issues common to all encodings. Some unsupported formats set
  1701      * the bits per sample to zero. These fall through to the 'unsupported
  1702      * format' error.
  1703      */
  1704     switch (format->encoding) {
  1705     case IEEE_FLOAT_CODE:
  1706     case ALAW_CODE:
  1707     case MULAW_CODE:
  1708     case MS_ADPCM_CODE:
  1709     case IMA_ADPCM_CODE:
  1710         /* These formats require a fact chunk. */
  1711         if (file->facthint == FactStrict && file->fact.status <= 0) {
  1712             return SDL_SetError("Missing fact chunk in WAVE file");
  1713         }
  1714         /* fallthrough */
  1715     case PCM_CODE:
  1716         /* All supported formats require a non-zero bit depth. */
  1717         if (file->chunk.size < 16) {
  1718             return SDL_SetError("Missing wBitsPerSample field in WAVE fmt chunk");
  1719         } else if (format->bitspersample == 0) {
  1720             return SDL_SetError("Invalid bits per sample");
  1721         }
  1722 
  1723         /* All supported formats must have a proper block size. */
  1724         if (format->blockalign == 0) {
  1725             return SDL_SetError("Invalid block alignment");
  1726         }
  1727 
  1728         /* If the fact chunk is valid and the appropriate hint is set, the
  1729          * decoders will use the number of sample frames from the fact chunk.
  1730          */
  1731         if (file->fact.status == 1) {
  1732             WaveFactChunkHint hint = file->facthint;
  1733             Uint32 samples = file->fact.samplelength;
  1734             if (hint == FactTruncate || hint == FactStrict || (hint == FactIgnoreZero && samples > 0)) {
  1735                 file->fact.status = 2;
  1736             }
  1737         }
  1738     }
  1739 
  1740     /* Check the format for encoding specific issues and initialize decoders. */
  1741     switch (format->encoding) {
  1742     case PCM_CODE:
  1743     case IEEE_FLOAT_CODE:
  1744         if (PCM_Init(file, datalength) < 0) {
  1745             return -1;
  1746         }
  1747         break;
  1748     case ALAW_CODE:
  1749     case MULAW_CODE:
  1750         if (LAW_Init(file, datalength) < 0) {
  1751             return -1;
  1752         }
  1753         break;
  1754     case MS_ADPCM_CODE:
  1755         if (MS_ADPCM_Init(file, datalength) < 0) {
  1756             return -1;
  1757         }
  1758         break;
  1759     case IMA_ADPCM_CODE:
  1760         if (IMA_ADPCM_Init(file, datalength) < 0) {
  1761             return -1;
  1762         }
  1763         break;
  1764     case MPEG_CODE:
  1765     case MPEGLAYER3_CODE:
  1766         return SDL_SetError("MPEG formats not supported");
  1767     default:
  1768         if (format->formattag == EXTENSIBLE_CODE) {
  1769             const char *errstr = "Unknown WAVE format GUID: %08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x";
  1770             const Uint8 *g = format->subformat;
  1771             const Uint32 g1 = g[0] | ((Uint32)g[1] << 8) | ((Uint32)g[2] << 16) | ((Uint32)g[3] << 24);
  1772             const Uint32 g2 = g[4] | ((Uint32)g[5] << 8);
  1773             const Uint32 g3 = g[6] | ((Uint32)g[7] << 8);
  1774             return SDL_SetError(errstr, g1, g2, g3, g[8], g[9], g[10], g[11], g[12], g[13], g[14], g[15]);
  1775         }
  1776         return SDL_SetError("Unknown WAVE format tag: 0x%04x", (unsigned int)format->encoding);
  1777     }
  1778 
  1779     return 0;
  1780 }
  1781 
  1782 static int
  1783 WaveLoad(SDL_RWops *src, WaveFile *file, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len)
  1784 {
  1785     int result;
  1786     Uint32 chunkcount = 0;
  1787     Uint32 chunkcountlimit = 10000;
  1788     char *envchunkcountlimit;
  1789     Sint64 RIFFstart, RIFFend, lastchunkpos;
  1790     SDL_bool RIFFlengthknown = SDL_FALSE;
  1791     WaveFormat *format = &file->format;
  1792     WaveChunk *chunk = &file->chunk;
  1793     WaveChunk RIFFchunk = {0};
  1794     WaveChunk fmtchunk = {0};
  1795     WaveChunk datachunk = {0};
  1796 
  1797     envchunkcountlimit = SDL_getenv("SDL_WAVE_CHUNK_LIMIT");
  1798     if (envchunkcountlimit != NULL) {
  1799         unsigned int count;
  1800         if (SDL_sscanf(envchunkcountlimit, "%u", &count) == 1) {
  1801             chunkcountlimit = count <= SDL_MAX_UINT32 ? count : SDL_MAX_UINT32;
  1802         }
  1803     }
  1804 
  1805     RIFFstart = SDL_RWtell(src);
  1806     if (RIFFstart < 0) {
  1807         return SDL_SetError("Could not seek in file");
  1808     }
  1809 
  1810     RIFFchunk.position = RIFFstart;
  1811     if (WaveNextChunk(src, &RIFFchunk) < 0) {
  1812         return SDL_SetError("Could not read RIFF header");
  1813     }
  1814 
  1815     /* Check main WAVE file identifiers. */
  1816     if (RIFFchunk.fourcc == RIFF) {
  1817         Uint32 formtype;
  1818         /* Read the form type. "WAVE" expected. */
  1819         if (SDL_RWread(src, &formtype, sizeof(Uint32), 1) != 1) {
  1820             return SDL_SetError("Could not read RIFF form type");
  1821         } else if (SDL_SwapLE32(formtype) != WAVE) {
  1822             return SDL_SetError("RIFF form type is not WAVE (not a Waveform file)");
  1823         }
  1824     } else if (RIFFchunk.fourcc == WAVE) {
  1825         /* RIFF chunk missing or skipped. Length unknown. */
  1826         RIFFchunk.position = 0;
  1827         RIFFchunk.length = 0;
  1828     } else {
  1829         return SDL_SetError("Could not find RIFF or WAVE identifiers (not a Waveform file)");
  1830     }
  1831 
  1832     /* The 4-byte form type is immediately followed by the first chunk.*/
  1833     chunk->position = RIFFchunk.position + 4;
  1834 
  1835     /* Use the RIFF chunk size to limit the search for the chunks. This is not
  1836      * always reliable and the hint can be used to tune the behavior. By
  1837      * default, it will never search past 4 GiB.
  1838      */
  1839     switch (file->riffhint) {
  1840     case RiffSizeIgnore:
  1841         RIFFend = RIFFchunk.position + SDL_MAX_UINT32;
  1842         break;
  1843     default:
  1844     case RiffSizeIgnoreZero:
  1845         if (RIFFchunk.length == 0) {
  1846             RIFFend = RIFFchunk.position + SDL_MAX_UINT32;
  1847             break;
  1848         }
  1849         /* fallthrough */
  1850     case RiffSizeForce:
  1851         RIFFend = RIFFchunk.position + RIFFchunk.length;
  1852         RIFFlengthknown = SDL_TRUE;
  1853         break;
  1854     case RiffSizeMaximum:
  1855         RIFFend = SDL_MAX_SINT64;
  1856         break;
  1857     }
  1858 
  1859     /* Step through all chunks and save information on the fmt, data, and fact
  1860      * chunks. Ignore the chunks we don't know as per specification. This
  1861      * currently also ignores cue, list, and slnt chunks.
  1862      */
  1863     while ((Uint64)RIFFend > (Uint64)chunk->position + chunk->length + (chunk->length & 1)) {
  1864         /* Abort after too many chunks or else corrupt files may waste time. */
  1865         if (chunkcount++ >= chunkcountlimit) {
  1866             return SDL_SetError("Chunk count in WAVE file exceeds limit of %u", chunkcountlimit);
  1867         }
  1868 
  1869         result = WaveNextChunk(src, chunk);
  1870         if (result == -1) {
  1871             /* Unexpected EOF. Corrupt file or I/O issues. */
  1872             if (file->trunchint == TruncVeryStrict) {
  1873                 return SDL_SetError("Unexpected end of WAVE file");
  1874             }
  1875             /* Let the checks after this loop sort this issue out. */
  1876             break;
  1877         } else if (result == -2) {
  1878             return SDL_SetError("Could not seek to WAVE chunk header");
  1879         }
  1880 
  1881         if (chunk->fourcc == FMT) {
  1882             if (fmtchunk.fourcc == FMT) {
  1883                 /* Multiple fmt chunks. Ignore or error? */
  1884             } else {
  1885                 /* The fmt chunk must occur before the data chunk. */
  1886                 if (datachunk.fourcc == DATA) {
  1887                     return SDL_SetError("fmt chunk after data chunk in WAVE file");
  1888                 }
  1889                 fmtchunk = *chunk;
  1890             }
  1891         } else if (chunk->fourcc == DATA) {
  1892             /* Only use the first data chunk. Handling the wavl list madness
  1893              * may require a different approach.
  1894              */
  1895             if (datachunk.fourcc != DATA) {
  1896                 datachunk = *chunk;
  1897             }
  1898         } else if (chunk->fourcc == FACT) {
  1899             /* The fact chunk data must be at least 4 bytes for the
  1900              * dwSampleLength field. Ignore all fact chunks after the first one.
  1901              */
  1902             if (file->fact.status == 0) {
  1903                 if (chunk->length < 4) {
  1904                     file->fact.status = -1;
  1905                 } else {
  1906                     /* Let's use src directly, it's just too convenient. */
  1907                     Sint64 position = SDL_RWseek(src, chunk->position, RW_SEEK_SET);
  1908                     Uint32 samplelength;
  1909                     if (position == chunk->position && SDL_RWread(src, &samplelength, sizeof(Uint32), 1) == 1) {
  1910                         file->fact.status = 1;
  1911                         file->fact.samplelength = SDL_SwapLE32(samplelength);
  1912                     } else {
  1913                         file->fact.status = -1;
  1914                     }
  1915                 }
  1916             }
  1917         }
  1918 
  1919         /* Go through all chunks in verystrict mode or stop the search early if
  1920          * all required chunks were found.
  1921          */
  1922         if (file->trunchint == TruncVeryStrict) {
  1923             if ((Uint64)RIFFend < (Uint64)chunk->position + chunk->length) {
  1924                 return SDL_SetError("RIFF size truncates chunk");
  1925             }
  1926         } else if (fmtchunk.fourcc == FMT && datachunk.fourcc == DATA) {
  1927             if (file->fact.status == 1 || file->facthint == FactIgnore || file->facthint == FactNoHint) {
  1928                 break;
  1929             }
  1930         }
  1931     }
  1932 
  1933     /* Save the position after the last chunk. This position will be used if the
  1934      * RIFF length is unknown.
  1935      */
  1936     lastchunkpos = chunk->position + chunk->length;
  1937 
  1938     /* The fmt chunk is mandatory. */
  1939     if (fmtchunk.fourcc != FMT) {
  1940         return SDL_SetError("Missing fmt chunk in WAVE file");
  1941     }
  1942     /* A data chunk must be present. */
  1943     if (datachunk.fourcc != DATA) {
  1944         return SDL_SetError("Missing data chunk in WAVE file");
  1945     }
  1946     /* Check if the last chunk has all of its data in verystrict mode. */
  1947     if (file->trunchint == TruncVeryStrict) {
  1948         /* data chunk is handled later. */
  1949         if (chunk->fourcc != DATA && chunk->length > 0) {
  1950             Uint8 tmp;
  1951             Uint64 position = (Uint64)chunk->position + chunk->length - 1;
  1952             if (position > SDL_MAX_SINT64 || SDL_RWseek(src, (Sint64)position, RW_SEEK_SET) != (Sint64)position) {
  1953                 return SDL_SetError("Could not seek to WAVE chunk data");
  1954             } else if (SDL_RWread(src, &tmp, 1, 1) != 1) {
  1955                 return SDL_SetError("RIFF size truncates chunk");
  1956             }
  1957         }
  1958     }
  1959 
  1960     /* Process fmt chunk. */
  1961     *chunk = fmtchunk;
  1962 
  1963     /* No need to read more than 1046 bytes of the fmt chunk data with the
  1964      * formats that are currently supported. (1046 because of MS ADPCM coefficients)
  1965      */
  1966     if (WaveReadPartialChunkData(src, chunk, 1046) < 0) {
  1967         return SDL_SetError("Could not read data of WAVE fmt chunk");
  1968     }
  1969 
  1970     /* The fmt chunk data must be at least 14 bytes to include all common fields.
  1971      * It usually is 16 and larger depending on the header and encoding.
  1972      */
  1973     if (chunk->length < 14) {
  1974         return SDL_SetError("Invalid WAVE fmt chunk length (too small)");
  1975     } else if (chunk->size < 14) {
  1976         return SDL_SetError("Could not read data of WAVE fmt chunk");
  1977     } else if (WaveReadFormat(file) < 0) {
  1978         return -1;
  1979     } else if (WaveCheckFormat(file, (size_t)datachunk.length) < 0) {
  1980         return -1;
  1981     }
  1982 
  1983 #ifdef SDL_WAVE_DEBUG_LOG_FORMAT
  1984     WaveDebugLogFormat(file);
  1985 #endif
  1986 #ifdef SDL_WAVE_DEBUG_DUMP_FORMAT
  1987     WaveDebugDumpFormat(file, RIFFchunk.length, fmtchunk.length, datachunk.length);
  1988 #endif
  1989 
  1990     WaveFreeChunkData(chunk);
  1991 
  1992     /* Process data chunk. */
  1993     *chunk = datachunk;
  1994 
  1995     if (chunk->length > 0) {
  1996         result = WaveReadChunkData(src, chunk);
  1997         if (result == -1) {
  1998             return -1;
  1999         } else if (result == -2) {
  2000             return SDL_SetError("Could not seek data of WAVE data chunk");
  2001         }
  2002     }
  2003 
  2004     if (chunk->length != chunk->size) {
  2005         /* I/O issues or corrupt file. */
  2006         if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) {
  2007             return SDL_SetError("Could not read data of WAVE data chunk");
  2008         }
  2009         /* The decoders handle this truncation. */
  2010     }
  2011 
  2012     /* Decode or convert the data if necessary. */
  2013     switch (format->encoding) {
  2014     case PCM_CODE:
  2015     case IEEE_FLOAT_CODE:
  2016         if (PCM_Decode(file, audio_buf, audio_len) < 0) {
  2017             return -1;
  2018         }
  2019         break;
  2020     case ALAW_CODE:
  2021     case MULAW_CODE:
  2022         if (LAW_Decode(file, audio_buf, audio_len) < 0) {
  2023             return -1;
  2024         }
  2025         break;
  2026     case MS_ADPCM_CODE:
  2027         if (MS_ADPCM_Decode(file, audio_buf, audio_len) < 0) {
  2028             return -1;
  2029         }
  2030         break;
  2031     case IMA_ADPCM_CODE:
  2032         if (IMA_ADPCM_Decode(file, audio_buf, audio_len) < 0) {
  2033             return -1;
  2034         }
  2035         break;
  2036     }
  2037 
  2038     /* Setting up the SDL_AudioSpec. All unsupported formats were filtered out
  2039      * by checks earlier in this function.
  2040      */
  2041     SDL_zerop(spec);
  2042     spec->freq = format->frequency;
  2043     spec->channels = (Uint8)format->channels;
  2044     spec->samples = 4096;       /* Good default buffer size */
  2045 
  2046     switch (format->encoding) {
  2047     case MS_ADPCM_CODE:
  2048     case IMA_ADPCM_CODE:
  2049     case ALAW_CODE:
  2050     case MULAW_CODE:
  2051         /* These can be easily stored in the byte order of the system. */
  2052         spec->format = AUDIO_S16SYS;
  2053         break;
  2054     case IEEE_FLOAT_CODE:
  2055         spec->format = AUDIO_F32LSB;
  2056         break;
  2057     case PCM_CODE:
  2058         switch (format->bitspersample) {
  2059         case 8:
  2060             spec->format = AUDIO_U8;
  2061             break;
  2062         case 16:
  2063             spec->format = AUDIO_S16LSB;
  2064             break;
  2065         case 24: /* Has been shifted to 32 bits. */
  2066         case 32:
  2067             spec->format = AUDIO_S32LSB;
  2068             break;
  2069         default:
  2070             /* Just in case something unexpected happened in the checks. */
  2071             return SDL_SetError("Unexpected %u-bit PCM data format", (unsigned int)format->bitspersample);
  2072         }
  2073         break;
  2074     }
  2075 
  2076     /* Report the end position back to the cleanup code. */
  2077     if (RIFFlengthknown) {
  2078         chunk->position = RIFFend;
  2079     } else {
  2080         chunk->position = lastchunkpos;
  2081     }
  2082 
  2083     return 0;
  2084 }
  2085 
  2086 SDL_AudioSpec *
  2087 SDL_LoadWAV_RW(SDL_RWops *src, int freesrc, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len)
  2088 {
  2089     int result;
  2090     WaveFile file;
  2091 
  2092     SDL_zero(file);
  2093 
  2094     /* Make sure we are passed a valid data source */
  2095     if (src == NULL) {
  2096         /* Error may come from RWops. */
  2097         return NULL;
  2098     } else if (spec == NULL) {
  2099         SDL_InvalidParamError("spec");
  2100         return NULL;
  2101     } else if (audio_buf == NULL) {
  2102         SDL_InvalidParamError("audio_buf");
  2103         return NULL;
  2104     } else if (audio_len == NULL) {
  2105         SDL_InvalidParamError("audio_len");
  2106         return NULL;
  2107     }
  2108 
  2109     *audio_buf = NULL;
  2110     *audio_len = 0;
  2111 
  2112     file.riffhint = WaveGetRiffSizeHint();
  2113     file.trunchint = WaveGetTruncationHint();
  2114     file.facthint = WaveGetFactChunkHint();
  2115 
  2116     result = WaveLoad(src, &file, spec, audio_buf, audio_len);
  2117     if (result < 0) {
  2118         SDL_free(*audio_buf);
  2119         spec = NULL;
  2120         audio_buf = NULL;
  2121         audio_len = 0;
  2122     }
  2123 
  2124     /* Cleanup */
  2125     if (freesrc) {
  2126         SDL_RWclose(src);
  2127     } else {
  2128         SDL_RWseek(src, file.chunk.position, RW_SEEK_SET);
  2129     }
  2130     WaveFreeChunkData(&file.chunk);
  2131     SDL_free(file.decoderdata);
  2132 
  2133     return spec;
  2134 }
  2135 
  2136 /* Since the WAV memory is allocated in the shared library, it must also
  2137    be freed here.  (Necessary under Win32, VC++)
  2138  */
  2139 void
  2140 SDL_FreeWAV(Uint8 *audio_buf)
  2141 {
  2142     SDL_free(audio_buf);
  2143 }
  2144 
  2145 /* vi: set ts=4 sw=4 expandtab: */