Skip to content

Latest commit

 

History

History
2151 lines (1873 loc) · 73.7 KB

SDL_wave.c

File metadata and controls

2151 lines (1873 loc) · 73.7 KB
 
1
2
/*
Simple DirectMedia Layer
Jan 5, 2019
Jan 5, 2019
3
Copyright (C) 1997-2019 Sam Lantinga <slouken@libsdl.org>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../SDL_internal.h"
Jun 9, 2019
Jun 9, 2019
23
24
25
26
27
28
29
30
#ifdef HAVE_LIMITS_H
#include <limits.h>
#else
#ifndef SIZE_MAX
#define SIZE_MAX ((size_t)-1)
#endif
#ifndef INT_MAX
/* Make a lucky guess. */
Jun 9, 2019
Jun 9, 2019
31
#define INT_MAX SDL_MAX_SINT32
Jun 9, 2019
Jun 9, 2019
32
33
34
#endif
#endif
35
36
/* Microsoft WAVE file loading routines */
Jun 9, 2019
Jun 9, 2019
37
38
#include "SDL_log.h"
#include "SDL_hints.h"
39
40
41
#include "SDL_audio.h"
#include "SDL_wave.h"
Jun 9, 2019
Jun 9, 2019
42
/* Reads the value stored at the location of the f1 pointer, multiplies it
Jun 9, 2019
Jun 9, 2019
43
44
45
* with the second argument and then stores the result to f1.
* Returns 0 on success, or -1 if the multiplication overflows, in which case f1
* does not get modified.
Jun 9, 2019
Jun 9, 2019
46
*/
Jun 9, 2019
Jun 9, 2019
47
48
static int
SafeMult(size_t *f1, size_t f2)
Jun 9, 2019
Jun 9, 2019
49
50
{
if (*f1 > 0 && SIZE_MAX / *f1 <= f2) {
Jun 9, 2019
Jun 9, 2019
51
return -1;
Jun 9, 2019
Jun 9, 2019
52
53
}
*f1 *= f2;
Jun 9, 2019
Jun 9, 2019
54
return 0;
Jun 9, 2019
Jun 9, 2019
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
}
typedef struct ADPCM_DecoderState
{
Uint32 channels; /* Number of channels. */
size_t blocksize; /* Size of an ADPCM block in bytes. */
size_t blockheadersize; /* Size of an ADPCM block header in bytes. */
size_t samplesperblock; /* Number of samples per channel in an ADPCM block. */
size_t framesize; /* Size of a sample frame (16-bit PCM) in bytes. */
Sint64 framestotal; /* Total number of sample frames. */
Sint64 framesleft; /* Number of sample frames still to be decoded. */
void *ddata; /* Decoder data from initialization. */
void *cstate; /* Decoding state for each channel. */
/* ADPCM data. */
struct {
Uint8 *data;
size_t size;
size_t pos;
} input;
/* Current ADPCM block in the ADPCM data above. */
struct {
Uint8 *data;
size_t size;
size_t pos;
} block;
/* Decoded 16-bit PCM data. */
struct {
Sint16 *data;
size_t size;
size_t pos;
} output;
} ADPCM_DecoderState;
typedef struct MS_ADPCM_CoeffData
{
Uint16 coeffcount;
Sint16 *coeff;
Sint16 aligndummy; /* Has to be last member. */
} MS_ADPCM_CoeffData;
typedef struct MS_ADPCM_ChannelState
{
Uint16 delta;
Sint16 coeff1;
Sint16 coeff2;
} MS_ADPCM_ChannelState;
#ifdef SDL_WAVE_DEBUG_LOG_FORMAT
static void
WaveDebugLogFormat(WaveFile *file)
{
WaveFormat *format = &file->format;
const char *fmtstr = "WAVE file: %s, %u Hz, %s, %u bits, %u %s/s";
const char *waveformat, *wavechannel, *wavebpsunit = "B";
Uint32 wavebps = format->byterate;
Jun 10, 2019
Jun 10, 2019
113
114
115
char channelstr[64];
SDL_zero(channelstr);
Jun 9, 2019
Jun 9, 2019
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
switch (format->encoding) {
case PCM_CODE:
waveformat = "PCM";
break;
case IEEE_FLOAT_CODE:
waveformat = "IEEE Float";
break;
case ALAW_CODE:
waveformat = "A-law";
break;
case MULAW_CODE:
waveformat = "\xc2\xb5-law";
break;
case MS_ADPCM_CODE:
waveformat = "MS ADPCM";
break;
case IMA_ADPCM_CODE:
waveformat = "IMA ADPCM";
break;
default:
waveformat = "Unknown";
break;
}
#define SDL_WAVE_DEBUG_CHANNELCFG(STR, CODE) case CODE: wavechannel = STR; break;
#define SDL_WAVE_DEBUG_CHANNELSTR(STR, CODE) if (format->channelmask & CODE) { \
SDL_strlcat(channelstr, channelstr[0] ? "-" STR : STR, sizeof(channelstr));}
if (format->formattag == EXTENSIBLE_CODE && format->channelmask > 0) {
switch (format->channelmask) {
SDL_WAVE_DEBUG_CHANNELCFG("1.0 Mono", 0x4)
SDL_WAVE_DEBUG_CHANNELCFG("1.1 Mono", 0xc)
SDL_WAVE_DEBUG_CHANNELCFG("2.0 Stereo", 0x3)
SDL_WAVE_DEBUG_CHANNELCFG("2.1 Stereo", 0xb)
SDL_WAVE_DEBUG_CHANNELCFG("3.0 Stereo", 0x7)
SDL_WAVE_DEBUG_CHANNELCFG("3.1 Stereo", 0xf)
SDL_WAVE_DEBUG_CHANNELCFG("3.0 Surround", 0x103)
SDL_WAVE_DEBUG_CHANNELCFG("3.1 Surround", 0x10b)
SDL_WAVE_DEBUG_CHANNELCFG("4.0 Quad", 0x33)
SDL_WAVE_DEBUG_CHANNELCFG("4.1 Quad", 0x3b)
SDL_WAVE_DEBUG_CHANNELCFG("4.0 Surround", 0x107)
SDL_WAVE_DEBUG_CHANNELCFG("4.1 Surround", 0x10f)
SDL_WAVE_DEBUG_CHANNELCFG("5.0", 0x37)
SDL_WAVE_DEBUG_CHANNELCFG("5.1", 0x3f)
SDL_WAVE_DEBUG_CHANNELCFG("5.0 Side", 0x607)
SDL_WAVE_DEBUG_CHANNELCFG("5.1 Side", 0x60f)
SDL_WAVE_DEBUG_CHANNELCFG("6.0", 0x137)
SDL_WAVE_DEBUG_CHANNELCFG("6.1", 0x13f)
SDL_WAVE_DEBUG_CHANNELCFG("6.0 Side", 0x707)
SDL_WAVE_DEBUG_CHANNELCFG("6.1 Side", 0x70f)
SDL_WAVE_DEBUG_CHANNELCFG("7.0", 0xf7)
SDL_WAVE_DEBUG_CHANNELCFG("7.1", 0xff)
SDL_WAVE_DEBUG_CHANNELCFG("7.0 Side", 0x6c7)
SDL_WAVE_DEBUG_CHANNELCFG("7.1 Side", 0x6cf)
SDL_WAVE_DEBUG_CHANNELCFG("7.0 Surround", 0x637)
SDL_WAVE_DEBUG_CHANNELCFG("7.1 Surround", 0x63f)
SDL_WAVE_DEBUG_CHANNELCFG("9.0 Surround", 0x5637)
SDL_WAVE_DEBUG_CHANNELCFG("9.1 Surround", 0x563f)
SDL_WAVE_DEBUG_CHANNELCFG("11.0 Surround", 0x56f7)
SDL_WAVE_DEBUG_CHANNELCFG("11.1 Surround", 0x56ff)
default:
SDL_WAVE_DEBUG_CHANNELSTR("FL", 0x1)
SDL_WAVE_DEBUG_CHANNELSTR("FR", 0x2)
SDL_WAVE_DEBUG_CHANNELSTR("FC", 0x4)
SDL_WAVE_DEBUG_CHANNELSTR("LF", 0x8)
SDL_WAVE_DEBUG_CHANNELSTR("BL", 0x10)
SDL_WAVE_DEBUG_CHANNELSTR("BR", 0x20)
SDL_WAVE_DEBUG_CHANNELSTR("FLC", 0x40)
SDL_WAVE_DEBUG_CHANNELSTR("FRC", 0x80)
SDL_WAVE_DEBUG_CHANNELSTR("BC", 0x100)
SDL_WAVE_DEBUG_CHANNELSTR("SL", 0x200)
SDL_WAVE_DEBUG_CHANNELSTR("SR", 0x400)
SDL_WAVE_DEBUG_CHANNELSTR("TC", 0x800)
SDL_WAVE_DEBUG_CHANNELSTR("TFL", 0x1000)
SDL_WAVE_DEBUG_CHANNELSTR("TFC", 0x2000)
SDL_WAVE_DEBUG_CHANNELSTR("TFR", 0x4000)
SDL_WAVE_DEBUG_CHANNELSTR("TBL", 0x8000)
SDL_WAVE_DEBUG_CHANNELSTR("TBC", 0x10000)
SDL_WAVE_DEBUG_CHANNELSTR("TBR", 0x20000)
break;
}
} else {
switch (format->channels) {
default:
if (SDL_snprintf(channelstr, sizeof(channelstr), "%u channels", format->channels) >= 0) {
wavechannel = channelstr;
break;
}
case 0:
wavechannel = "Unknown";
break;
case 1:
wavechannel = "Mono";
break;
case 2:
wavechannel = "Setero";
break;
}
}
#undef SDL_WAVE_DEBUG_CHANNELCFG
#undef SDL_WAVE_DEBUG_CHANNELSTR
if (wavebps >= 1024) {
wavebpsunit = "KiB";
wavebps = wavebps / 1024 + (wavebps & 0x3ff ? 1 : 0);
}
SDL_LogDebug(SDL_LOG_CATEGORY_AUDIO, fmtstr, waveformat, format->frequency, wavechannel, format->bitspersample, wavebps, wavebpsunit);
}
#endif
#ifdef SDL_WAVE_DEBUG_DUMP_FORMAT
static void
WaveDebugDumpFormat(WaveFile *file, Uint32 rifflen, Uint32 fmtlen, Uint32 datalen)
{
WaveFormat *format = &file->format;
const char *fmtstr1 = "WAVE chunk dump:\n"
"-------------------------------------------\n"
"RIFF %11u\n"
"-------------------------------------------\n"
" fmt %11u\n"
" wFormatTag 0x%04x\n"
" nChannels %11u\n"
" nSamplesPerSec %11u\n"
" nAvgBytesPerSec %11u\n"
" nBlockAlign %11u\n";
const char *fmtstr2 = " wBitsPerSample %11u\n";
const char *fmtstr3 = " cbSize %11u\n";
const char *fmtstr4a = " wValidBitsPerSample %11u\n";
const char *fmtstr4b = " wSamplesPerBlock %11u\n";
const char *fmtstr5 = " dwChannelMask 0x%08x\n"
" SubFormat\n"
" %08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x\n";
const char *fmtstr6 = "-------------------------------------------\n"
" fact\n"
" dwSampleLength %11u\n";
const char *fmtstr7 = "-------------------------------------------\n"
" data %11u\n"
"-------------------------------------------\n";
char *dumpstr;
size_t dumppos = 0;
const size_t bufsize = 1024;
int res;
dumpstr = SDL_malloc(bufsize);
if (dumpstr == NULL) {
return;
}
dumpstr[0] = 0;
res = SDL_snprintf(dumpstr, bufsize, fmtstr1, rifflen, fmtlen, format->formattag, format->channels, format->frequency, format->byterate, format->blockalign);
dumppos += res > 0 ? res : 0;
if (fmtlen >= 16) {
res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr2, format->bitspersample);
dumppos += res > 0 ? res : 0;
}
if (fmtlen >= 18) {
res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr3, format->extsize);
dumppos += res > 0 ? res : 0;
}
if (format->formattag == EXTENSIBLE_CODE && fmtlen >= 40 && format->extsize >= 22) {
const Uint8 *g = format->subformat;
const Uint32 g1 = g[0] | ((Uint32)g[1] << 8) | ((Uint32)g[2] << 16) | ((Uint32)g[3] << 24);
const Uint32 g2 = g[4] | ((Uint32)g[5] << 8);
const Uint32 g3 = g[6] | ((Uint32)g[7] << 8);
switch (format->encoding) {
default:
res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4a, format->validsamplebits);
dumppos += res > 0 ? res : 0;
break;
case MS_ADPCM_CODE:
case IMA_ADPCM_CODE:
res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4b, format->samplesperblock);
dumppos += res > 0 ? res : 0;
break;
}
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]);
dumppos += res > 0 ? res : 0;
} else {
switch (format->encoding) {
case MS_ADPCM_CODE:
case IMA_ADPCM_CODE:
if (fmtlen >= 20 && format->extsize >= 2) {
res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr4b, format->samplesperblock);
dumppos += res > 0 ? res : 0;
}
break;
}
}
if (file->fact.status >= 1) {
res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr6, file->fact.samplelength);
dumppos += res > 0 ? res : 0;
}
res = SDL_snprintf(dumpstr + dumppos, bufsize - dumppos, fmtstr7, datalen);
dumppos += res > 0 ? res : 0;
SDL_LogDebug(SDL_LOG_CATEGORY_AUDIO, "%s", dumpstr);
free(dumpstr);
}
#endif
static Sint64
WaveAdjustToFactValue(WaveFile *file, Sint64 sampleframes)
{
if (file->fact.status == 2) {
if (file->facthint == FactStrict && sampleframes < file->fact.samplelength) {
return SDL_SetError("Invalid number of sample frames in WAVE fact chunk (too many)");
} else if (sampleframes > file->fact.samplelength) {
return file->fact.samplelength;
}
}
return sampleframes;
}
static int
MS_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength)
{
WaveFormat *format = &file->format;
Jun 9, 2019
Jun 9, 2019
339
const size_t blockheadersize = (size_t)file->format.channels * 7;
Jun 9, 2019
Jun 9, 2019
340
const size_t availableblocks = datalength / file->format.blockalign;
Jun 9, 2019
Jun 9, 2019
341
const size_t blockframebitsize = (size_t)file->format.bitspersample * file->format.channels;
Jun 9, 2019
Jun 9, 2019
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
const size_t trailingdata = datalength % file->format.blockalign;
if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) {
/* The size of the data chunk must be a multiple of the block size. */
if (datalength < blockheadersize || trailingdata > 0) {
return SDL_SetError("Truncated MS ADPCM block");
}
}
/* Calculate number of sample frames that will be decoded. */
file->sampleframes = (Sint64)availableblocks * format->samplesperblock;
if (trailingdata > 0) {
/* The last block is truncated. Check if we can get any samples out of it. */
if (file->trunchint == TruncDropFrame) {
/* Drop incomplete sample frame. */
if (trailingdata >= blockheadersize) {
size_t trailingsamples = 2 + (trailingdata - blockheadersize) * 8 / blockframebitsize;
if (trailingsamples > format->samplesperblock) {
trailingsamples = format->samplesperblock;
}
file->sampleframes += trailingsamples;
}
}
}
file->sampleframes = WaveAdjustToFactValue(file, file->sampleframes);
if (file->sampleframes < 0) {
return -1;
}
return 0;
}
static int
MS_ADPCM_Init(WaveFile *file, size_t datalength)
{
WaveFormat *format = &file->format;
WaveChunk *chunk = &file->chunk;
Jun 9, 2019
Jun 9, 2019
380
const size_t blockheadersize = (size_t)format->channels * 7;
Jun 9, 2019
Jun 9, 2019
381
const size_t blockdatasize = (size_t)format->blockalign - blockheadersize;
Jun 9, 2019
Jun 9, 2019
382
const size_t blockframebitsize = (size_t)format->bitspersample * format->channels;
Jun 9, 2019
Jun 9, 2019
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize;
const Sint16 presetcoeffs[14] = {256, 0, 512, -256, 0, 0, 192, 64, 240, 0, 460, -208, 392, -232};
size_t i, coeffcount;
MS_ADPCM_CoeffData *coeffdata;
/* Sanity checks. */
/* While it's clear how IMA ADPCM handles more than two channels, the nibble
* order of MS ADPCM makes it awkward. The Standards Update does not talk
* about supporting more than stereo anyway.
*/
if (format->channels > 2) {
return SDL_SetError("Invalid number of channels");
}
if (format->bitspersample != 4) {
Jun 9, 2019
Jun 9, 2019
399
return SDL_SetError("Invalid MS ADPCM bits per sample of %u", (unsigned int)format->bitspersample);
Jun 9, 2019
Jun 9, 2019
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
}
/* The block size must be big enough to contain the block header. */
if (format->blockalign < blockheadersize) {
return SDL_SetError("Invalid MS ADPCM block size (nBlockAlign)");
}
if (format->formattag == EXTENSIBLE_CODE) {
/* Does have a GUID (like all format tags), but there's no specification
* for how the data is packed into the extensible header. Making
* assumptions here could lead to new formats nobody wants to support.
*/
return SDL_SetError("MS ADPCM with the extensible header is not supported");
}
/* There are wSamplesPerBlock, wNumCoef, and at least 7 coefficient pairs in
* the extended part of the header.
*/
if (chunk->size < 22) {
return SDL_SetError("Could not read MS ADPCM format header");
}
format->samplesperblock = chunk->data[18] | ((Uint16)chunk->data[19] << 8);
/* Number of coefficient pairs. A pair has two 16-bit integers. */
coeffcount = chunk->data[20] | ((size_t)chunk->data[21] << 8);
/* bPredictor, the integer offset into the coefficients array, is only
* 8 bits. It can only address the first 256 coefficients. Let's limit
* the count number here.
*/
if (coeffcount > 256) {
coeffcount = 256;
}
if (chunk->size < 22 + coeffcount * 4) {
return SDL_SetError("Could not read custom coefficients in MS ADPCM format header");
} else if (format->extsize < 4 + coeffcount * 4) {
return SDL_SetError("Invalid MS ADPCM format header (too small)");
} else if (coeffcount < 7) {
return SDL_SetError("Missing required coefficients in MS ADPCM format header");
}
coeffdata = (MS_ADPCM_CoeffData *)SDL_malloc(sizeof(MS_ADPCM_CoeffData) + coeffcount * 4);
file->decoderdata = coeffdata; /* Freed in cleanup. */
if (coeffdata == NULL) {
return SDL_OutOfMemory();
}
coeffdata->coeff = &coeffdata->aligndummy;
coeffdata->coeffcount = (Uint16)coeffcount;
/* Copy the 16-bit pairs. */
for (i = 0; i < coeffcount * 2; i++) {
Sint32 c = chunk->data[22 + i * 2] | ((Sint32)chunk->data[23 + i * 2] << 8);
if (c >= 0x8000) {
c -= 0x10000;
}
if (i < 14 && c != presetcoeffs[i]) {
return SDL_SetError("Wrong preset coefficients in MS ADPCM format header");
}
coeffdata->coeff[i] = (Sint16)c;
}
/* Technically, wSamplesPerBlock is required, but we have all the
* information in the other fields to calculate it, if it's zero.
*/
if (format->samplesperblock == 0) {
/* Let's be nice to the encoders that didn't know how to fill this.
* The Standards Update calculates it this way:
*
* x = Block size (in bits) minus header size (in bits)
* y = Bit depth multiplied by channel count
* z = Number of samples per channel in block header
* wSamplesPerBlock = x / y + z
*/
format->samplesperblock = (Uint32)blockdatasamples + 2;
}
/* nBlockAlign can be in conflict with wSamplesPerBlock. For example, if
* the number of samples doesn't fit into the block. The Standards Update
* also describes wSamplesPerBlock with a formula that makes it necessary to
* always fill the block with the maximum amount of samples, but this is not
* enforced here as there are no compatibility issues.
* A truncated block header with just one sample is not supported.
*/
if (format->samplesperblock == 1 || blockdatasamples < format->samplesperblock - 2) {
return SDL_SetError("Invalid number of samples per MS ADPCM block (wSamplesPerBlock)");
}
if (MS_ADPCM_CalculateSampleFrames(file, datalength) < 0) {
return -1;
}
return 0;
}
static Sint16
MS_ADPCM_ProcessNibble(MS_ADPCM_ChannelState *cstate, Sint32 sample1, Sint32 sample2, Uint8 nybble)
{
const Sint32 max_audioval = 32767;
const Sint32 min_audioval = -32768;
const Uint16 max_deltaval = 65535;
const Uint16 adaptive[] = {
230, 230, 230, 230, 307, 409, 512, 614,
768, 614, 512, 409, 307, 230, 230, 230
};
Sint32 new_sample;
Sint32 errordelta;
Uint32 delta = cstate->delta;
new_sample = (sample1 * cstate->coeff1 + sample2 * cstate->coeff2) / 256;
/* The nibble is a signed 4-bit error delta. */
errordelta = (Sint32)nybble - (nybble >= 0x08 ? 0x10 : 0);
new_sample += (Sint32)delta * errordelta;
if (new_sample < min_audioval) {
new_sample = min_audioval;
} else if (new_sample > max_audioval) {
new_sample = max_audioval;
}
delta = (delta * adaptive[nybble]) / 256;
if (delta < 16) {
delta = 16;
} else if (delta > max_deltaval) {
/* This issue is not described in the Standards Update and therefore
* undefined. It seems sensible to prevent overflows with a limit.
*/
delta = max_deltaval;
}
cstate->delta = (Uint16)delta;
return (Sint16)new_sample;
}
static int
MS_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
{
Uint8 coeffindex;
const Uint32 channels = state->channels;
Sint32 sample;
Uint32 c;
MS_ADPCM_ChannelState *cstate = (MS_ADPCM_ChannelState *)state->cstate;
MS_ADPCM_CoeffData *ddata = (MS_ADPCM_CoeffData *)state->ddata;
for (c = 0; c < channels; c++) {
size_t o = c;
/* Load the coefficient pair into the channel state. */
coeffindex = state->block.data[o];
if (coeffindex > ddata->coeffcount) {
return SDL_SetError("Invalid MS ADPCM coefficient index in block header");
}
cstate[c].coeff1 = ddata->coeff[coeffindex * 2];
cstate[c].coeff2 = ddata->coeff[coeffindex * 2 + 1];
/* Initial delta value. */
o = channels + c * 2;
cstate[c].delta = state->block.data[o] | ((Uint16)state->block.data[o + 1] << 8);
/* Load the samples from the header. Interestingly, the sample later in
* the output stream comes first.
*/
o = channels * 3 + c * 2;
sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8);
if (sample >= 0x8000) {
sample -= 0x10000;
}
state->output.data[state->output.pos + channels] = (Sint16)sample;
o = channels * 5 + c * 2;
sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8);
if (sample >= 0x8000) {
sample -= 0x10000;
}
state->output.data[state->output.pos] = (Sint16)sample;
state->output.pos++;
}
state->block.pos += state->blockheadersize;
/* Skip second sample frame that came from the header. */
state->output.pos += state->channels;
/* Header provided two sample frames. */
state->framesleft -= 2;
return 0;
}
/* Decodes the data of the MS ADPCM block. Decoding will stop if a block is too
* short, returning with none or partially decoded data. The partial data
* will always contain full sample frames (same sample count for each channel).
* Incomplete sample frames are discarded.
*/
static int
MS_ADPCM_DecodeBlockData(ADPCM_DecoderState *state)
{
Uint16 nybble = 0;
Sint16 sample1, sample2;
const Uint32 channels = state->channels;
Uint32 c;
MS_ADPCM_ChannelState *cstate = (MS_ADPCM_ChannelState *)state->cstate;
size_t blockpos = state->block.pos;
size_t blocksize = state->block.size;
size_t outpos = state->output.pos;
Sint64 blockframesleft = state->samplesperblock - 2;
if (blockframesleft > state->framesleft) {
blockframesleft = state->framesleft;
}
while (blockframesleft > 0) {
for (c = 0; c < channels; c++) {
Jun 9, 2019
Jun 9, 2019
613
if (nybble & 0x4000) {
Jun 9, 2019
Jun 9, 2019
614
615
nybble <<= 4;
} else if (blockpos < blocksize) {
Jun 9, 2019
Jun 9, 2019
616
nybble = state->block.data[blockpos++] | 0x4000;
Jun 9, 2019
Jun 9, 2019
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
} else {
/* Out of input data. Drop the incomplete frame and return. */
state->output.pos = outpos - c;
return -1;
}
/* Load previous samples which may come from the block header. */
sample1 = state->output.data[outpos - channels];
sample2 = state->output.data[outpos - channels * 2];
sample1 = MS_ADPCM_ProcessNibble(cstate + c, sample1, sample2, (nybble >> 4) & 0x0f);
state->output.data[outpos++] = sample1;
}
state->framesleft--;
blockframesleft--;
}
state->output.pos = outpos;
return 0;
}
static int
MS_ADPCM_Decode(WaveFile *file, Uint8 **audio_buf, Uint32 *audio_len)
{
int result;
size_t bytesleft, outputsize;
WaveChunk *chunk = &file->chunk;
Jun 10, 2019
Jun 10, 2019
646
ADPCM_DecoderState state;
Jun 9, 2019
Jun 9, 2019
647
648
MS_ADPCM_ChannelState cstate[2];
Jun 10, 2019
Jun 10, 2019
649
650
SDL_zero(state);
SDL_zero(cstate);
Jun 9, 2019
Jun 9, 2019
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
if (chunk->size != chunk->length) {
/* Could not read everything. Recalculate number of sample frames. */
if (MS_ADPCM_CalculateSampleFrames(file, chunk->size) < 0) {
return -1;
}
}
/* Nothing to decode, nothing to return. */
if (file->sampleframes == 0) {
*audio_buf = NULL;
*audio_len = 0;
return 0;
}
state.blocksize = file->format.blockalign;
state.channels = file->format.channels;
Jun 9, 2019
Jun 9, 2019
668
state.blockheadersize = (size_t)state.channels * 7;
Jun 9, 2019
Jun 9, 2019
669
670
671
672
673
674
675
676
677
678
679
680
state.samplesperblock = file->format.samplesperblock;
state.framesize = state.channels * sizeof(Sint16);
state.ddata = file->decoderdata;
state.framestotal = file->sampleframes;
state.framesleft = state.framestotal;
state.input.data = chunk->data;
state.input.size = chunk->size;
state.input.pos = 0;
/* The output size in bytes. May get modified if data is truncated. */
outputsize = (size_t)state.framestotal;
Jun 9, 2019
Jun 9, 2019
681
if (SafeMult(&outputsize, state.framesize)) {
Jun 9, 2019
Jun 9, 2019
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
return SDL_OutOfMemory();
} else if (outputsize > SDL_MAX_UINT32 || state.framestotal > SIZE_MAX) {
return SDL_SetError("WAVE file too big");
}
state.output.pos = 0;
state.output.size = outputsize / sizeof(Sint16);
state.output.data = (Sint16 *)SDL_malloc(outputsize);
if (state.output.data == NULL) {
return SDL_OutOfMemory();
}
state.cstate = &cstate;
/* Decode block by block. A truncated block will stop the decoding. */
bytesleft = state.input.size - state.input.pos;
while (state.framesleft > 0 && bytesleft >= state.blockheadersize) {
state.block.data = state.input.data + state.input.pos;
state.block.size = bytesleft < state.blocksize ? bytesleft : state.blocksize;
state.block.pos = 0;
if (state.output.size - state.output.pos < (Uint64)state.framesleft * state.channels) {
/* Somehow didn't allocate enough space for the output. */
SDL_free(state.output.data);
return SDL_SetError("Unexpected overflow in MS ADPCM decoder");
}
/* Initialize decoder with the values from the block header. */
result = MS_ADPCM_DecodeBlockHeader(&state);
if (result == -1) {
SDL_free(state.output.data);
return -1;
}
/* Decode the block data. It stores the samples directly in the output. */
result = MS_ADPCM_DecodeBlockData(&state);
if (result == -1) {
/* Unexpected end. Stop decoding and return partial data if necessary. */
if (file->trunchint == TruncVeryStrict || file->trunchint == TruncVeryStrict) {
SDL_free(state.output.data);
return SDL_SetError("Truncated data chunk");
} else if (file->trunchint != TruncDropFrame) {
state.output.pos -= state.output.pos % (state.samplesperblock * state.channels);
}
outputsize = state.output.pos * sizeof(Sint16); /* Can't overflow, is always smaller. */
break;
}
state.input.pos += state.block.size;
bytesleft = state.input.size - state.input.pos;
}
*audio_buf = (Uint8 *)state.output.data;
*audio_len = (Uint32)outputsize;
return 0;
}
static int
IMA_ADPCM_CalculateSampleFrames(WaveFile *file, size_t datalength)
{
WaveFormat *format = &file->format;
Jun 9, 2019
Jun 9, 2019
744
745
const size_t blockheadersize = (size_t)format->channels * 4;
const size_t subblockframesize = (size_t)format->channels * 4;
Jun 9, 2019
Jun 9, 2019
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
const size_t availableblocks = datalength / format->blockalign;
const size_t trailingdata = datalength % format->blockalign;
if (file->trunchint == TruncVeryStrict || file->trunchint == TruncStrict) {
/* The size of the data chunk must be a multiple of the block size. */
if (datalength < blockheadersize || trailingdata > 0) {
return SDL_SetError("Truncated IMA ADPCM block");
}
}
/* Calculate number of sample frames that will be decoded. */
file->sampleframes = (Uint64)availableblocks * format->samplesperblock;
if (trailingdata > 0) {
/* The last block is truncated. Check if we can get any samples out of it. */
if (file->trunchint == TruncDropFrame && trailingdata > blockheadersize - 2) {
/* The sample frame in the header of the truncated block is present.
* Drop incomplete sample frames.
*/
size_t trailingsamples = 1;
if (trailingdata > blockheadersize) {
/* More data following after the header. */
const size_t trailingblockdata = trailingdata - blockheadersize;
const size_t trailingsubblockdata = trailingblockdata % subblockframesize;
trailingsamples += (trailingblockdata / subblockframesize) * 8;
/* Due to the interleaved sub-blocks, the last 4 bytes determine
* how many samples of the truncated sub-block are lost.
*/
if (trailingsubblockdata > subblockframesize - 4) {
trailingsamples += (trailingsubblockdata % 4) * 2;
}
}
if (trailingsamples > format->samplesperblock) {
trailingsamples = format->samplesperblock;
}
file->sampleframes += trailingsamples;
}
}
file->sampleframes = WaveAdjustToFactValue(file, file->sampleframes);
if (file->sampleframes < 0) {
return -1;
}
return 0;
}
static int
IMA_ADPCM_Init(WaveFile *file, size_t datalength)
{
WaveFormat *format = &file->format;
WaveChunk *chunk = &file->chunk;
Jun 9, 2019
Jun 9, 2019
799
const size_t blockheadersize = (size_t)format->channels * 4;
Jun 9, 2019
Jun 9, 2019
800
const size_t blockdatasize = (size_t)format->blockalign - blockheadersize;
Jun 9, 2019
Jun 9, 2019
801
const size_t blockframebitsize = (size_t)format->bitspersample * format->channels;
Jun 9, 2019
Jun 9, 2019
802
803
804
805
const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize;
/* Sanity checks. */
Jun 9, 2019
Jun 9, 2019
806
/* IMA ADPCM can also have 3-bit samples, but it's not supported by SDL at this time. */
Jun 9, 2019
Jun 9, 2019
807
808
809
if (format->bitspersample == 3) {
return SDL_SetError("3-bit IMA ADPCM currently not supported");
} else if (format->bitspersample != 4) {
Jun 9, 2019
Jun 9, 2019
810
return SDL_SetError("Invalid IMA ADPCM bits per sample of %u", (unsigned int)format->bitspersample);
Jun 9, 2019
Jun 9, 2019
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
}
/* The block size is required to be a multiple of 4 and it must be able to
* hold a block header.
*/
if (format->blockalign < blockheadersize || format->blockalign % 4) {
return SDL_SetError("Invalid IMA ADPCM block size (nBlockAlign)");
}
if (format->formattag == EXTENSIBLE_CODE) {
/* There's no specification for this, but it's basically the same
* format because the extensible header has wSampePerBlocks too.
*/
} else {
/* The Standards Update says there 'should' be 2 bytes for wSamplesPerBlock. */
if (chunk->size >= 20 && format->extsize >= 2) {
format->samplesperblock = chunk->data[18] | ((Uint16)chunk->data[19] << 8);
}
}
if (format->samplesperblock == 0) {
/* Field zero? No problem. We just assume the encoder packed the block.
* The specification calculates it this way:
*
* x = Block size (in bits) minus header size (in bits)
* y = Bit depth multiplied by channel count
* z = Number of samples per channel in header
* wSamplesPerBlock = x / y + z
*/
format->samplesperblock = (Uint32)blockdatasamples + 1;
}
/* nBlockAlign can be in conflict with wSamplesPerBlock. For example, if
* the number of samples doesn't fit into the block. The Standards Update
* also describes wSamplesPerBlock with a formula that makes it necessary
* to always fill the block with the maximum amount of samples, but this is
* not enforced here as there are no compatibility issues.
*/
if (blockdatasamples < format->samplesperblock - 1) {
return SDL_SetError("Invalid number of samples per IMA ADPCM block (wSamplesPerBlock)");
}
if (IMA_ADPCM_CalculateSampleFrames(file, datalength) < 0) {
return -1;
}
return 0;
}
static Sint16
IMA_ADPCM_ProcessNibble(Sint8 *cindex, Sint16 lastsample, Uint8 nybble)
{
const Sint32 max_audioval = 32767;
const Sint32 min_audioval = -32768;
const Sint8 index_table_4b[16] = {
-1, -1, -1, -1,
2, 4, 6, 8,
-1, -1, -1, -1,
2, 4, 6, 8
};
const Uint16 step_table[89] = {
7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31,
34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130,
143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408,
449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282,
1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327,
3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630,
9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350,
22385, 24623, 27086, 29794, 32767
};
Uint32 step;
Sint32 sample, delta;
Sint8 index = *cindex;
/* Clamp index into valid range. */
if (index > 88) {
index = 88;
} else if (index < 0) {
index = 0;
}
/* explicit cast to avoid gcc warning about using 'char' as array index */
step = step_table[(size_t)index];
/* Update index value */
*cindex = index + index_table_4b[nybble];
/* This calculation uses shifts and additions because multiplications were
* much slower back then. Sadly, this can't just be replaced with an actual
* multiplication now as the old algorithm drops some bits. The closest
* approximation I could find is something like this:
* (nybble & 0x8 ? -1 : 1) * ((nybble & 0x7) * step / 4 + step / 8)
*/
delta = step >> 3;
if (nybble & 0x04)
delta += step;
if (nybble & 0x02)
delta += step >> 1;
if (nybble & 0x01)
delta += step >> 2;
if (nybble & 0x08)
delta = -delta;
sample = lastsample + delta;
/* Clamp output sample */
if (sample > max_audioval) {
sample = max_audioval;
} else if (sample < min_audioval) {
sample = min_audioval;
}
return (Sint16)sample;
}
static int
IMA_ADPCM_DecodeBlockHeader(ADPCM_DecoderState *state)
{
Sint16 step;
Uint32 c;
Uint8 *cstate = state->cstate;
for (c = 0; c < state->channels; c++) {
size_t o = state->block.pos + c * 4;
/* Extract the sample from the header. */
Sint32 sample = state->block.data[o] | ((Sint32)state->block.data[o + 1] << 8);
if (sample >= 0x8000) {
sample -= 0x10000;
}
state->output.data[state->output.pos++] = (Sint16)sample;
/* Channel step index. */
step = (Sint16)state->block.data[o + 2];
cstate[c] = (Sint8)(step > 0x80 ? step - 0x100 : step);
/* Reserved byte in block header, should be 0. */
if (state->block.data[o + 3] != 0) {
/* Uh oh, corrupt data? Buggy code? */ ;
}
}
state->block.pos += state->blockheadersize;
/* Header provided one sample frame. */
state->framesleft--;
return 0;
}
/* Decodes the data of the IMA ADPCM block. Decoding will stop if a block is too
* short, returning with none or partially decoded data. The partial data always
* contains full sample frames (same sample count for each channel).
* Incomplete sample frames are discarded.
*/
static int
IMA_ADPCM_DecodeBlockData(ADPCM_DecoderState *state)
{
size_t i;
int retval = 0;
const Uint32 channels = state->channels;
const size_t subblockframesize = channels * 4;
Uint64 bytesrequired;
Uint32 c;
size_t blockpos = state->block.pos;
size_t blocksize = state->block.size;
size_t blockleft = blocksize - blockpos;
size_t outpos = state->output.pos;
Sint64 blockframesleft = state->samplesperblock - 1;
if (blockframesleft > state->framesleft) {
blockframesleft = state->framesleft;
}
bytesrequired = (blockframesleft + 7) / 8 * subblockframesize;
if (blockleft < bytesrequired) {
/* Data truncated. Calculate how many samples we can get out if it. */
const size_t guaranteedframes = blockleft / subblockframesize;
const size_t remainingbytes = blockleft % subblockframesize;
blockframesleft = guaranteedframes;
if (remainingbytes > subblockframesize - 4) {
blockframesleft += (remainingbytes % 4) * 2;
}
/* Signal the truncation. */
retval = -1;
}
/* Each channel has their nibbles packed into 32-bit blocks. These blocks