/
music_mad.c
457 lines (378 loc) · 13.7 KB
2
SDL_mixer: An audio mixer library based on the SDL library
3
Copyright (C) 1997-2017 Sam Lantinga <slouken@libsdl.org>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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.
22
#ifdef MUSIC_MP3_MAD
26
27
#include "mad.h"
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
/* NOTE: The dithering functions are GPL, which should be fine if your
application is GPL (which would need to be true if you enabled
libmad support in SDL_mixer). If you're using libmad under the
commercial license, you need to disable this code.
*/
/************************ dithering functions ***************************/
#ifdef MUSIC_MP3_MAD_GPL_DITHERING
/* All dithering done here is taken from the GPL'ed xmms-mad plugin. */
/* Copyright (C) 1997 Makoto Matsumoto and Takuji Nishimura. */
/* Any feedback is very welcome. For any question, comments, */
/* see http://www.math.keio.ac.jp/matumoto/emt.html or email */
/* matumoto@math.keio.ac.jp */
/* Period parameters */
#define MP3_DITH_N 624
#define MP3_DITH_M 397
#define MATRIX_A 0x9908b0df /* constant vector a */
#define UPPER_MASK 0x80000000 /* most significant w-r bits */
#define LOWER_MASK 0x7fffffff /* least significant r bits */
/* Tempering parameters */
#define TEMPERING_MASK_B 0x9d2c5680
#define TEMPERING_MASK_C 0xefc60000
#define TEMPERING_SHIFT_U(y) (y >> 11)
#define TEMPERING_SHIFT_S(y) (y << 7)
#define TEMPERING_SHIFT_T(y) (y << 15)
#define TEMPERING_SHIFT_L(y) (y >> 18)
static unsigned long mt[MP3_DITH_N]; /* the array for the state vector */
static int mti=MP3_DITH_N+1; /* mti==MP3_DITH_N+1 means mt[MP3_DITH_N] is not initialized */
/* initializing the array with a NONZERO seed */
static void sgenrand(unsigned long seed)
{
/* setting initial seeds to mt[MP3_DITH_N] using */
/* the generator Line 25 of Table 1 in */
/* [KNUTH 1981, The Art of Computer Programming */
/* Vol. 2 (2nd Ed.), pp102] */
mt[0]= seed & 0xffffffff;
for (mti=1; mti<MP3_DITH_N; mti++)
mt[mti] = (69069 * mt[mti-1]) & 0xffffffff;
}
static unsigned long genrand(void)
{
unsigned long y;
static unsigned long mag01[2]={0x0, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= MP3_DITH_N) { /* generate MP3_DITH_N words at one time */
int kk;
if (mti == MP3_DITH_N+1) /* if sgenrand() has not been called, */
sgenrand(4357); /* a default initial seed is used */
for (kk=0;kk<MP3_DITH_N-MP3_DITH_M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+MP3_DITH_M] ^ (y >> 1) ^ mag01[y & 0x1];
}
for (;kk<MP3_DITH_N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(MP3_DITH_M-MP3_DITH_N)] ^ (y >> 1) ^ mag01[y & 0x1];
}
y = (mt[MP3_DITH_N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[MP3_DITH_N-1] = mt[MP3_DITH_M-1] ^ (y >> 1) ^ mag01[y & 0x1];
mti = 0;
}
y = mt[mti++];
y ^= TEMPERING_SHIFT_U(y);
y ^= TEMPERING_SHIFT_S(y) & TEMPERING_MASK_B;
y ^= TEMPERING_SHIFT_T(y) & TEMPERING_MASK_C;
y ^= TEMPERING_SHIFT_L(y);
return y;
}
static long triangular_dither_noise(int nbits) {
/* parameter nbits : the peak-to-peak amplitude desired (in bits)
* use with nbits set to 2 + nber of bits to be trimmed.
* (because triangular is made from two uniformly distributed processes,
* it starts at 2 bits peak-to-peak amplitude)
* see The Theory of Dithered Quantization by Robert Alexander Wannamaker
* for complete proof of why that's optimal
*/
long v = (genrand()/2 - genrand()/2); /* in ]-2^31, 2^31[ */
long P = 1 << (32 - nbits); /* the power of 2 */
v /= P;
/* now v in ]-2^(nbits-1), 2^(nbits-1) [ */
return v;
}
#endif /* MUSIC_MP3_MAD_GPL_DITHERING */
129
130
131
132
133
#define MAD_INPUT_BUFFER_SIZE (5*8192)
enum {
MS_input_eof = 0x0001,
MS_input_error = 0x0001,
134
MS_decode_error = 0x0002,
135
136
137
138
MS_error_flags = 0x000f,
};
typedef struct {
139
int play_count;
140
141
142
143
144
145
146
147
SDL_RWops *src;
int freesrc;
struct mad_stream stream;
struct mad_frame frame;
struct mad_synth synth;
mad_timer_t next_frame_start;
int volume;
int status;
148
SDL_AudioStream *audiostream;
149
150
unsigned char input_buffer[MAD_INPUT_BUFFER_SIZE + MAD_BUFFER_GUARD];
151
} MAD_Music;
152
153
154
155
static int MAD_Seek(void *context, double position);
156
static void *MAD_CreateFromRW(SDL_RWops *src, int freesrc)
157
{
158
159
160
161
162
163
MAD_Music *music;
music = (MAD_Music *)SDL_calloc(1, sizeof(MAD_Music));
if (!music) {
SDL_OutOfMemory();
return NULL;
164
}
165
166
167
168
169
170
171
172
173
174
music->src = src;
music->volume = MIX_MAX_VOLUME;
mad_stream_init(&music->stream);
mad_frame_init(&music->frame);
mad_synth_init(&music->synth);
mad_timer_reset(&music->next_frame_start);
music->freesrc = freesrc;
return music;
177
static void MAD_SetVolume(void *context, int volume)
178
{
179
180
MAD_Music *music = (MAD_Music *)context;
music->volume = volume;
184
static int MAD_Play(void *context, int play_count)
185
{
186
187
188
MAD_Music *music = (MAD_Music *)context;
music->play_count = play_count;
return MAD_Seek(music, 0.0);
191
192
193
194
/* Reads the next frame from the file.
Returns true on success or false on failure.
*/
static SDL_bool read_next_frame(MAD_Music *music)
195
{
196
197
if (music->stream.buffer == NULL ||
music->stream.error == MAD_ERROR_BUFLEN) {
198
199
200
201
202
203
204
size_t read_size;
size_t remaining;
unsigned char *read_start;
/* There might be some bytes in the buffer left over from last
time. If so, move them down and read more bytes following
them. */
205
206
207
208
if (music->stream.next_frame != NULL) {
remaining = music->stream.bufend - music->stream.next_frame;
memmove(music->input_buffer, music->stream.next_frame, remaining);
read_start = music->input_buffer + remaining;
209
210
211
212
read_size = MAD_INPUT_BUFFER_SIZE - remaining;
} else {
read_size = MAD_INPUT_BUFFER_SIZE;
213
read_start = music->input_buffer;
214
215
remaining = 0;
}
216
217
/* Now read additional bytes from the input file. */
218
read_size = SDL_RWread(music->src, read_start, 1, read_size);
219
220
if (read_size == 0) {
221
if ((music->status & (MS_input_eof | MS_input_error)) == 0) {
222
/* FIXME: how to detect error? */
223
music->status |= MS_input_eof;
224
225
226
227
228
229
230
/* At the end of the file, we must stuff MAD_BUFFER_GUARD
number of 0 bytes. */
SDL_memset(read_start + read_size, 0, MAD_BUFFER_GUARD);
read_size += MAD_BUFFER_GUARD;
}
}
231
232
/* Now feed those bytes into the libmad stream. */
233
mad_stream_buffer(&music->stream, music->input_buffer,
234
read_size + remaining);
235
music->stream.error = MAD_ERROR_NONE;
236
}
237
238
239
/* Now ask libmad to extract a frame from the data we just put in
its buffer. */
240
241
242
if (mad_frame_decode(&music->frame, &music->stream)) {
if (MAD_RECOVERABLE(music->stream.error)) {
return SDL_FALSE;
243
244
245
} else if (music->stream.error == MAD_ERROR_BUFLEN) {
return SDL_FALSE;
246
247
} else {
248
249
250
Mix_SetError("mad_frame_decode() failed, corrupt stream?");
music->status |= MS_decode_error;
return SDL_FALSE;
251
}
252
253
}
254
mad_timer_add(&music->next_frame_start, music->frame.header.duration);
256
return SDL_TRUE;
260
261
262
263
static Sint16 scale(mad_fixed_t sample)
{
const int n_bits_to_loose = MAD_F_FRACBITS + 1 - 16;
264
/* round */
265
266
267
268
269
sample += (1L << (n_bits_to_loose - 1));
#ifdef MUSIC_MP3_MAD_GPL_DITHERING
sample += triangular_dither_noise(n_bits_to_loose + 1);
#endif
271
272
273
274
275
/* clip */
if (sample >= MAD_F_ONE)
sample = MAD_F_ONE - 1;
else if (sample < -MAD_F_ONE)
sample = -MAD_F_ONE;
277
/* quantize */
278
return (Sint16)(sample >> n_bits_to_loose);
281
/* Once the frame has been read, copies its samples into the output buffer. */
282
283
static SDL_bool decode_frame(MAD_Music *music)
{
284
struct mad_pcm *pcm;
285
unsigned int i, nchannels, nsamples;
286
mad_fixed_t const *left_ch, *right_ch;
287
288
Sint16 *buffer, *dst;
int result;
289
290
291
mad_synth_frame(&music->synth, &music->frame);
pcm = &music->synth.pcm;
292
293
294
295
296
297
298
if (!music->audiostream) {
music->audiostream = SDL_NewAudioStream(AUDIO_S16, pcm->channels, pcm->samplerate, music_spec.format, music_spec.channels, music_spec.freq);
if (!music->audiostream) {
return SDL_FALSE;
}
}
299
300
301
302
303
304
305
306
307
nchannels = pcm->channels;
nsamples = pcm->length;
left_ch = pcm->samples[0];
right_ch = pcm->samples[1];
buffer = SDL_stack_alloc(Sint16, nsamples*nchannels);
if (!buffer) {
SDL_OutOfMemory();
return SDL_FALSE;
308
309
}
310
311
312
313
314
315
316
317
318
dst = buffer;
if (nchannels == 1) {
for (i = nsamples; i--;) {
*dst++ = scale(*left_ch++);
}
} else {
for (i = nsamples; i--;) {
*dst++ = scale(*left_ch++);
*dst++ = scale(*right_ch++);
319
320
}
}
322
323
result = SDL_AudioStreamPut(music->audiostream, buffer, (nsamples * nchannels * sizeof(Sint16)));
SDL_stack_free(buffer);
325
326
327
328
329
if (result < 0) {
return SDL_FALSE;
}
return SDL_TRUE;
}
331
332
333
334
static int MAD_GetSome(void *context, void *data, int bytes, SDL_bool *done)
{
MAD_Music *music = (MAD_Music *)context;
int filled;
336
337
338
339
if (music->audiostream) {
filled = SDL_AudioStreamGet(music->audiostream, data, bytes);
if (filled != 0) {
return filled;
340
}
343
344
345
if (!music->play_count) {
/* All done */
*done = SDL_TRUE;
346
347
348
return 0;
}
349
350
351
if (read_next_frame(music)) {
if (!decode_frame(music)) {
return -1;
352
}
353
} else if (music->status & MS_input_eof) {
354
355
356
357
358
359
int play_count = -1;
if (music->play_count > 0) {
play_count = (music->play_count - 1);
}
if (MAD_Play(music, play_count) < 0) {
return -1;
360
}
361
362
} else if (music->status & MS_decode_error) {
return -1;
363
}
364
365
return 0;
}
366
367
368
369
370
static int MAD_GetAudio(void *context, void *data, int bytes)
{
MAD_Music *music = (MAD_Music *)context;
return music_pcm_getaudio(context, data, bytes, music->volume, MAD_GetSome);
}
371
372
373
static int MAD_Seek(void *context, double position)
{
374
MAD_Music *music = (MAD_Music *)context;
375
376
377
378
379
380
mad_timer_t target;
int int_part;
int_part = (int)position;
mad_timer_set(&target, int_part, (int)((position - int_part) * 1000000), 1000000);
381
if (mad_timer_compare(music->next_frame_start, target) > 0) {
382
383
384
385
386
387
/* In order to seek backwards in a VBR file, we have to rewind and
start again from the beginning. This isn't necessary if the
file happens to be CBR, of course; in that case we could seek
directly to the frame we want. But I leave that little
optimization for the future developer who discovers she really
needs it. */
388
389
mad_timer_reset(&music->next_frame_start);
music->status &= ~MS_error_flags;
390
391
SDL_RWseek(music->src, 0, RW_SEEK_SET);
392
}
394
395
/* Now we have to skip frames until we come to the right one.
Again, only truly necessary if the file is VBR. */
396
397
398
while (mad_timer_compare(music->next_frame_start, target) < 0) {
if (!read_next_frame(music)) {
if ((music->status & MS_error_flags) != 0) {
399
400
401
402
403
/* Couldn't read a frame; either an error condition or
end-of-file. Stop. */
return Mix_SetError("Seek position out of range");
}
}
404
}
406
407
408
409
410
/* Here we are, at the beginning of the frame that contains the
target time. Ehh, I say that's close enough. If we wanted to,
we could get more precise by decoding the frame now and counting
the appropriate number of samples out of it. */
return 0;
413
414
static void MAD_Delete(void *context)
{
415
MAD_Music *music = (MAD_Music *)context;
417
418
419
420
421
422
423
424
425
mad_stream_finish(&music->stream);
mad_frame_finish(&music->frame);
mad_synth_finish(&music->synth);
if (music->audiostream) {
SDL_FreeAudioStream(music->audiostream);
}
if (music->freesrc) {
SDL_RWclose(music->src);
426
}
427
SDL_free(music);
428
429
430
431
432
433
434
435
436
437
}
Mix_MusicInterface Mix_MusicInterface_MAD =
{
"MAD",
MIX_MUSIC_MAD,
MUS_MP3,
SDL_FALSE,
SDL_FALSE,
438
439
NULL, /* Load */
NULL, /* Open */
440
MAD_CreateFromRW,
441
NULL, /* CreateFromFile */
442
443
MAD_SetVolume,
MAD_Play,
444
NULL, /* IsPlaying */
445
446
MAD_GetAudio,
MAD_Seek,
447
448
449
NULL, /* Pause */
NULL, /* Resume */
NULL, /* Stop */
450
MAD_Delete,
451
452
NULL, /* Close */
NULL, /* Unload */
453
454
455
456
457
};
#endif /* MUSIC_MP3_MAD */
/* vi: set ts=4 sw=4 expandtab: */