forked from WohlSoft/SDL-Mixer-X
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmusic_wav.c
2068 lines (1823 loc) · 65.5 KB
/
music_wav.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
113
114
115
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
339
340
341
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
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
613
614
615
616
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
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
744
745
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
799
800
801
802
803
804
805
806
807
808
809
810
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
/*
SDL_mixer: An audio mixer library based on the SDL library
Copyright (C) 1997-2024 Sam Lantinga <[email protected]>
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.
*/
#ifdef MUSIC_WAV
/* This file supports streaming WAV files */
#include "music_wav.h"
#include "mp3utils.h"
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. */
void *ddata; /* Decoder data from initialization. */
void *cstate; /* Decoding state for each channel. */
/* Current ADPCM block */
struct
{
Uint8 *data;
size_t size;
size_t pos;
} block;
/* Decoded 16-bit PCM data. */
struct
{
Sint16 *data;
size_t size;
size_t pos;
size_t read;
} 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;
typedef struct {
SDL_bool active;
Uint32 start;
Uint32 stop;
Uint32 initial_play_count;
Uint32 current_play_count;
} WAVLoopPoint;
typedef struct {
SDL_RWops *src;
int freesrc;
SDL_AudioSpec spec;
int volume;
int play_count;
Sint64 start;
Sint64 stop;
Sint64 samplesize;
Uint8 *buffer;
size_t buflen;
size_t buffered;
SDL_AudioStream *stream;
ADPCM_DecoderState adpcm_state;
unsigned int numloops;
WAVLoopPoint *loops;
Mix_MusicMetaTags tags;
Uint16 encoding;
int (*decode)(void *music, int length);
} WAV_Music;
/*
Taken with permission from SDL_wave.h, part of the SDL library,
available at: http://www.libsdl.org/
and placed under the same license as this mixer library.
*/
/* WAVE files are little-endian */
/*******************************************/
/* Define values for Microsoft WAVE format */
/*******************************************/
#define RIFF 0x46464952 /* "RIFF" */
#define WAVE 0x45564157 /* "WAVE" */
#define FMT 0x20746D66 /* "fmt " */
#define DATA 0x61746164 /* "data" */
#define SMPL 0x6c706d73 /* "smpl" */
#define LIST 0x5453494c /* "LIST" */
#define ID3_ 0x20336469 /* "id3 " */
#define UNKNOWN_CODE 0x0000
#define PCM_CODE 0x0001 /* WAVE_FORMAT_PCM */
#define MS_ADPCM_CODE 0x0002 /* WAVE_FORMAT_ADPCM */
#define IEEE_FLOAT_CODE 0x0003 /* WAVE_FORMAT_IEEE_FLOAT */
#define ALAW_CODE 0x0006 /* WAVE_FORMAT_ALAW */
#define MULAW_CODE 0x0007 /* WAVE_FORMAT_MULAW */
#define IMA_ADPCM_CODE 0x0011
#define MPEG_CODE 0x0050
#define MPEGLAYER3_CODE 0x0055
#define EXTENSIBLE_CODE 0xFFFE
#define WAVE_MONO 1
#define WAVE_STEREO 2
#pragma pack(push, 1)
typedef struct {
/* Not saved in the chunk we read:
Uint32 chunkID;
Uint32 chunkLen;
*/
Uint16 encoding;
Uint16 channels; /* 1 = mono, 2 = stereo */
Uint32 frequency; /* One of 11025, 22050, or 44100 Hz */
Uint32 byterate; /* Average bytes per second */
Uint16 blockalign; /* Bytes per sample block */
Uint16 bitspersample; /* One of 8, 12, 16, or 4 for ADPCM */
} WaveFMT;
typedef struct {
WaveFMT format;
Uint16 cbSize;
union {
Uint16 validbitspersample; /* bits of precision */
Uint16 samplesperblock; /* valid if wBitsPerSample==0 */
Uint16 reserved; /* If neither applies, set to zero. */
} Samples;
Uint32 channelsmask;
/* GUID subFormat 16 bytes */
Uint32 subencoding;
Uint16 sub_data2;
Uint16 sub_data3;
Uint8 sub_data[8];
} WaveFMTEx;
typedef struct {
Uint32 identifier;
Uint32 type;
Uint32 start;
Uint32 end;
Uint32 fraction;
Uint32 play_count;
} SampleLoop;
typedef struct {
/* Not saved in the chunk we read:
Uint32 chunkID;
Uint32 chunkLen;
*/
Uint32 manufacturer;
Uint32 product;
Uint32 sample_period;
Uint32 MIDI_unity_note;
Uint32 MIDI_pitch_fraction;
Uint32 SMTPE_format;
Uint32 SMTPE_offset;
Uint32 sample_loops;
Uint32 sampler_data;
SampleLoop loops[1];
} SamplerChunk;
#pragma pack(pop)
/*********************************************/
/* Define values for AIFF (IFF audio) format */
/*********************************************/
#define FORM 0x4d524f46 /* "FORM" */
#define AIFF 0x46464941 /* "AIFF" */
#define AIFC 0x43464941 /* "AIFС" */
#define FVER 0x52455646 /* "FVER" */
#define SSND 0x444e5353 /* "SSND" */
#define COMM 0x4d4d4f43 /* "COMM" */
#define AIFF_ID3_ 0x20334449 /* "ID3 " */
#define MARK 0x4B52414D /* "MARK" */
#define INST 0x54534E49 /* "INST" */
#define AUTH 0x48545541 /* "AUTH" */
#define NAME 0x454D414E /* "NAME" */
#define _c__ 0x20296328 /* "(c) " */
#define _8SVX 0x58565338 /* "8SVX" */
#define VHDR 0x52444856 /* "VHDR" */
#define BODY 0x59444F42 /* "BODY" */
/* Supported compression types */
#define NONE 0x454E4F4E /* "NONE" */
#define sowt 0x74776F73 /* "sowt" */
#define raw_ 0x20776172 /* "raw " */
#define ulaw 0x77616C75 /* "ulaw" */
#define alaw 0x77616C61 /* "alaw" */
#define ULAW 0x57414C55 /* "ULAW" */
#define ALAW 0x57414C41 /* "ALAW" */
#define fl32 0x32336C66 /* "fl32" */
#define fl64 0x34366C66 /* "fl64" */
#define FL32 0x32334C46 /* "FL32" */
/* Function to load the WAV/AIFF stream */
static SDL_bool LoadWAVMusic(WAV_Music *wave);
static SDL_bool LoadAIFFMusic(WAV_Music *wave);
static void WAV_Delete(void *context);
static int fetch_pcm(void *context, int length);
/* Load a WAV stream from the given RWops object */
static void *WAV_CreateFromRW(SDL_RWops *src, int freesrc)
{
WAV_Music *music;
Uint32 magic;
SDL_bool loaded = SDL_FALSE;
music = (WAV_Music *)SDL_calloc(1, sizeof(*music));
if (!music) {
Mix_OutOfMemory();
return NULL;
}
music->src = src;
music->volume = MIX_MAX_VOLUME;
/* Default decoder is PCM */
music->decode = fetch_pcm;
music->encoding = PCM_CODE;
magic = SDL_ReadLE32(src);
if (magic == RIFF || magic == WAVE) {
loaded = LoadWAVMusic(music);
} else if (magic == FORM) {
loaded = LoadAIFFMusic(music);
} else {
Mix_SetError("Unknown WAVE format");
}
if (!loaded) {
WAV_Delete(music);
return NULL;
}
music->buflen = SDL_AUDIO_BITSIZE(music->spec.format) / 8;
music->buflen *= music->spec.channels;
music->buflen *= 4096; /* Good default sample frame count */
music->buffer = (Uint8*)SDL_malloc(music->buflen);
if (!music->buffer) {
Mix_OutOfMemory();
WAV_Delete(music);
return NULL;
}
music->stream = SDL_NewAudioStream(
music->spec.format, music->spec.channels, music->spec.freq,
music_spec.format, music_spec.channels, music_spec.freq);
if (!music->stream) {
WAV_Delete(music);
return NULL;
}
music->freesrc = freesrc;
return music;
}
static void WAV_SetVolume(void *context, int volume)
{
WAV_Music *music = (WAV_Music *)context;
music->volume = volume;
}
static int WAV_GetVolume(void *context)
{
WAV_Music *music = (WAV_Music *)context;
return music->volume;
}
/* Start playback of a given WAV stream */
static int WAV_Play(void *context, int play_count)
{
WAV_Music *music = (WAV_Music *)context;
unsigned int i;
for (i = 0; i < music->numloops; ++i) {
WAVLoopPoint *loop = &music->loops[i];
loop->active = SDL_TRUE;
loop->current_play_count = loop->initial_play_count;
}
music->play_count = play_count;
if (SDL_RWseek(music->src, music->start, RW_SEEK_SET) < 0) {
return -1;
}
return 0;
}
static void WAV_Stop(void *context)
{
WAV_Music *music = (WAV_Music *)context;
SDL_AudioStreamClear(music->stream);
}
static int fetch_pcm(void *context, int length)
{
WAV_Music *music = (WAV_Music *)context;
return (int)SDL_RWread(music->src, music->buffer, 1, (size_t)length);
}
static Uint32 PCM_S24_to_S32_BE(Uint8 *x) {
const Uint32 bits = 24;
Uint32 in = (((Uint32)x[0] << 0) & 0x0000FF) |
(((Uint32)x[1] << 8) & 0x00FF00) |
(((Uint32)x[2] << 16) & 0xFF0000);
Uint32 m = 1u << (bits - 1);
return (in ^ m) - m;
}
static Uint32 PCM_S24_to_S32_LE(Uint8 *x) {
const Uint32 bits = 24;
Uint32 in = (((Uint32)x[2] << 0) & 0x0000FF) |
(((Uint32)x[1] << 8) & 0x00FF00) |
(((Uint32)x[0] << 16) & 0xFF0000);
Uint32 m = 1u << (bits - 1);
return (in ^ m) - m;
}
static int fetch_pcm24be(void *context, int length)
{
WAV_Music *music = (WAV_Music *)context;
int i = 0, o = 0;
length = (int)SDL_RWread(music->src, music->buffer, 1, (size_t)((length / 4) * 3));
if (length % music->samplesize != 0) {
length -= length % music->samplesize;
}
for (i = length - 3, o = ((length - 3) / 3) * 4; i >= 0; i -= 3, o -= 4) {
Uint32 decoded = PCM_S24_to_S32_BE(music->buffer + i);
music->buffer[o + 0] = (decoded >> 0) & 0xFF;
music->buffer[o + 1] = (decoded >> 8) & 0xFF;
music->buffer[o + 2] = (decoded >> 16) & 0xFF;
music->buffer[o + 3] = (decoded >> 24) & 0xFF;
}
return (length / 3) * 4;
}
static int fetch_pcm24le(void *context, int length)
{
WAV_Music *music = (WAV_Music *)context;
int i = 0, o = 0;
length = (int)SDL_RWread(music->src, music->buffer, 1, (size_t)((length / 4) * 3));
if (length % music->samplesize != 0) {
length -= length % music->samplesize;
}
for (i = length - 3, o = ((length - 3) / 3) * 4; i >= 0; i -= 3, o -= 4) {
Uint32 decoded = PCM_S24_to_S32_LE(music->buffer + i);
music->buffer[o + 3] = (decoded >> 0) & 0xFF;
music->buffer[o + 2] = (decoded >> 8) & 0xFF;
music->buffer[o + 1] = (decoded >> 16) & 0xFF;
music->buffer[o + 0] = (decoded >> 24) & 0xFF;
}
return (length / 3) * 4;
}
SDL_FORCE_INLINE double
Mix_SwapDouble(double x)
{
union
{
double f;
Uint64 ui64;
} swapper;
swapper.f = x;
swapper.ui64 = SDL_Swap64(swapper.ui64);
return swapper.f;
}
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
#define Mix_SwapDoubleLE(X) (X)
#define Mix_SwapDoubleBE(X) Mix_SwapDouble(X)
#else
#define Mix_SwapDoubleLE(X) Mix_SwapDouble(X)
#define Mix_SwapDoubleBE(X) (X)
#endif
static int fetch_float64be(void *context, int length)
{
WAV_Music *music = (WAV_Music *)context;
int i = 0, o = 0;
length = (int)SDL_RWread(music->src, music->buffer, 1, (size_t)(length));
if (length % music->samplesize != 0) {
length -= length % music->samplesize;
}
for (i = 0, o = 0; i < length; i += 8, o += 4) {
union
{
float f;
Uint32 ui32;
} sample;
sample.f = (float)Mix_SwapDoubleBE(*(double*)(music->buffer + i));
music->buffer[o + 0] = (sample.ui32 >> 0) & 0xFF;
music->buffer[o + 1] = (sample.ui32 >> 8) & 0xFF;
music->buffer[o + 2] = (sample.ui32 >> 16) & 0xFF;
music->buffer[o + 3] = (sample.ui32 >> 24) & 0xFF;
}
return length / 2;
}
static int fetch_float64le(void *context, int length)
{
WAV_Music *music = (WAV_Music *)context;
int i = 0, o = 0;
length = (int)SDL_RWread(music->src, music->buffer, 1, (size_t)(length));
if (length % music->samplesize != 0) {
length -= length % music->samplesize;
}
for (i = 0, o = 0; i < length; i += 8, o += 4) {
union
{
float f;
Uint32 ui32;
} sample;
sample.f = (float)Mix_SwapDoubleLE(*(double*)(music->buffer + i));
music->buffer[o + 0] = (sample.ui32 >> 0) & 0xFF;
music->buffer[o + 1] = (sample.ui32 >> 8) & 0xFF;
music->buffer[o + 2] = (sample.ui32 >> 16) & 0xFF;
music->buffer[o + 3] = (sample.ui32 >> 24) & 0xFF;
}
return length / 2;
}
static int MS_ADPCM_Init(ADPCM_DecoderState *state, const Uint8 *chunk_data, Uint32 chunk_length)
{
const WaveFMTEx *fmt = (WaveFMTEx *)chunk_data;
const Uint16 channels = SDL_SwapLE16(fmt->format.channels);
const Uint16 blockalign = SDL_SwapLE16(fmt->format.blockalign);
const Uint16 bitspersample = SDL_SwapLE16(fmt->format.bitspersample);
const size_t blockheadersize = (size_t)channels * 7;
const size_t blockdatasize = (size_t)blockalign - blockheadersize;
const size_t blockframebitsize = (size_t)bitspersample * channels;
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 };
Uint16 cbExtSize, samplesperblock;
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 (channels > 2) {
return Mix_SetError("Invalid number of channels");
}
if (bitspersample != 4) {
return Mix_SetError("Invalid MS ADPCM bits per sample of %u", (unsigned int)bitspersample);
}
/* The block size must be big enough to contain the block header. */
if (blockalign < blockheadersize) {
return Mix_SetError("Invalid MS ADPCM block size (nBlockAlign)");
}
/* There are wSamplesPerBlock, wNumCoef, and at least 7 coefficient pairs in
* the extended part of the header.
*/
if (chunk_length < 22) {
return Mix_SetError("Could not read MS ADPCM format header");
}
cbExtSize = SDL_SwapLE16(fmt->cbSize);
samplesperblock = SDL_SwapLE16(fmt->Samples.samplesperblock);
/* 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_length < 22 + coeffcount * 4) {
return Mix_SetError("Could not read custom coefficients in MS ADPCM format header");
} else if (cbExtSize < 4 + coeffcount * 4) {
return Mix_SetError("Invalid MS ADPCM format header (too small)");
} else if (coeffcount < 7) {
return Mix_SetError("Missing required coefficients in MS ADPCM format header");
}
coeffdata = (MS_ADPCM_CoeffData *)SDL_malloc(sizeof(MS_ADPCM_CoeffData) + coeffcount * 4);
if (coeffdata == NULL) {
return Mix_OutOfMemory();
}
coeffdata->coeff = &coeffdata->aligndummy;
coeffdata->coeffcount = (Uint16)coeffcount;
state->ddata = coeffdata; /* Freed in cleanup. */
/* 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 Mix_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 (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
*/
samplesperblock = (Uint16)(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 (samplesperblock == 1 || blockdatasamples < (size_t)(samplesperblock - 2)) {
return Mix_SetError("Invalid number of samples per MS ADPCM block (wSamplesPerBlock)");
}
state->blocksize = blockalign;
state->channels = channels;
state->blockheadersize = blockheadersize;
state->samplesperblock = samplesperblock;
state->cstate = SDL_calloc(channels, sizeof(MS_ADPCM_ChannelState));
if (!state->cstate) {
return Mix_OutOfMemory();
}
state->block.pos = 0;
state->block.size = blockalign;
state->block.data = (Uint8 *)SDL_malloc(state->block.size);
if (!state->block.data) {
return Mix_OutOfMemory();
}
state->output.read = 0;
state->output.pos = 0;
state->output.size = state->samplesperblock * state->channels;
state->output.data = (Sint16 *)SDL_malloc(state->output.size * sizeof(Sint16));
if (!state->output.data) {
return Mix_OutOfMemory();
}
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;
if (state->block.size < state->blockheadersize) {
return Mix_SetError("Invalid ADPCM header");
}
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 Mix_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 = (size_t)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 = (size_t)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 = (size_t)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;
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;
size_t blockframesleft = state->samplesperblock - 2;
while (blockframesleft > 0) {
for (c = 0; c < channels; c++) {
if (nybble & 0x4000) {
nybble <<= 4;
} else if (blockpos < blocksize) {
nybble = state->block.data[blockpos++] | 0x4000;
} 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;
}
blockframesleft--;
}
state->output.pos = outpos;
return 0;
}
static int IMA_ADPCM_Init(ADPCM_DecoderState *state, const Uint8 *chunk_data, Uint32 chunk_length)
{
const WaveFMTEx *fmt = (WaveFMTEx *)chunk_data;
const Uint16 formattag = SDL_SwapLE16(fmt->format.encoding);
const Uint16 channels = SDL_SwapLE16(fmt->format.channels);
const Uint16 blockalign = SDL_SwapLE16(fmt->format.blockalign);
const Uint16 bitspersample = SDL_SwapLE16(fmt->format.bitspersample);
const size_t blockheadersize = (size_t)channels * 4;
const size_t blockdatasize = (size_t)blockalign - blockheadersize;
const size_t blockframebitsize = (size_t)bitspersample * channels;
const size_t blockdatasamples = (blockdatasize * 8) / blockframebitsize;
Uint16 samplesperblock = 0;
/* Sanity checks. */
/* IMA ADPCM can also have 3-bit samples, but it's not supported by SDL at this time. */
if (bitspersample == 3) {
return Mix_SetError("3-bit IMA ADPCM currently not supported");
} else if (bitspersample != 4) {
return Mix_SetError("Invalid IMA ADPCM bits per sample of %u", (unsigned int)bitspersample);
}
/* The block size is required to be a multiple of 4 and it must be able to
* hold a block header.
*/
if (blockalign < blockheadersize || blockalign % 4) {
return Mix_SetError("Invalid IMA ADPCM block size (nBlockAlign)");
}
if (formattag == EXTENSIBLE_CODE) {
/* There's no specification for this, but it's basically the same
* format because the extensible header has wSampePerBlocks too.
*/
} else if (chunk_length >= 20) {
Uint16 cbExtSize = SDL_SwapLE16(fmt->cbSize);
if (cbExtSize >= 2) {
samplesperblock = SDL_SwapLE16(fmt->Samples.samplesperblock);
}
}
if (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
*/
samplesperblock = (Uint16)(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 < (size_t)(samplesperblock - 1)) {
return Mix_SetError("Invalid number of samples per IMA ADPCM block (wSamplesPerBlock)");
}
state->blocksize = blockalign;
state->channels = channels;
state->blockheadersize = blockheadersize;
state->samplesperblock = samplesperblock;
state->cstate = SDL_calloc(channels, sizeof(Sint8));
if (!state->cstate) {
return Mix_OutOfMemory();
}
state->block.pos = 0;
state->block.size = blockalign;
state->block.data = (Uint8 *)SDL_malloc(state->block.size);
if (!state->block.data) {
return Mix_OutOfMemory();
}
state->output.read = 0;
state->output.pos = 0;
state->output.size = state->samplesperblock * state->channels;
state->output.data = (Sint16 *)SDL_malloc(state->output.size * sizeof(Sint16));
if (!state->output.data) {
return Mix_OutOfMemory();
}
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 = (Uint8 *)state->cstate;
if (state->block.size < state->blockheadersize) {
return Mix_SetError("Invalid ADPCM header");
}
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;
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 = (size_t)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;
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
* are interleaved and make up the data part of the ADPCM block. This loop
* decodes the samples as they come from the input data and puts them at
* the appropriate places in the output data.
*/
while (blockframesleft > 0) {
const size_t subblocksamples = blockframesleft < 8 ? (size_t)blockframesleft : 8;
for (c = 0; c < channels; c++) {
Uint8 nybble = 0;
/* Load previous sample which may come from the block header. */
Sint16 sample = state->output.data[outpos + c - channels];
for (i = 0; i < subblocksamples; i++) {
if (i & 1) {
nybble >>= 4;
} else {
nybble = state->block.data[blockpos++];
}
sample = IMA_ADPCM_ProcessNibble((Sint8 *)state->cstate + c, sample, nybble & 0x0f);
state->output.data[outpos + c + i * channels] = sample;
}
}
outpos += channels * subblocksamples;
blockframesleft -= subblocksamples;
}
state->block.pos = blockpos;
state->output.pos = outpos;
return retval;
}
static void ADPCM_Cleanup(ADPCM_DecoderState *state)
{
if (state->ddata) {
SDL_free(state->ddata);
state->ddata = NULL;
}
if (state->cstate) {
SDL_free(state->cstate);
state->cstate = NULL;
}
if (state->block.data) {
SDL_free(state->block.data);
SDL_zero(state->block);
}
if (state->output.data) {
SDL_free(state->output.data);
SDL_zero(state->output);
}
}