SDL_wave.c 75 KB

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