1 /*
2 * MP3 decoding support using libmad: Adapted from the SoX library at
3 * http://sourceforge.net/projects/sox/, LGPLv2, Copyright (c) 2007-2009
4 * SoX contributors, written by Fabrizio Gennari <fabrizio.ge@tiscali.it>,
5 * with the decoding part based on the decoder tutorial program madlld
6 * written by Bertrand Petit <madlld@phoe.fmug.org> (BSD license, see at
7 * http://www.bsd-dk.dk/~elrond/audio/madlld/).
8 * Adapted for use in Quake and Hexen II game engines by O.Sezer:
9 * Copyright (C) 2010-2019 O.Sezer <sezero@users.sourceforge.net>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or (at
14 * your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
19 *
20 * See the GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 */
26
27 #include "quakedef.h"
28
29 #if defined(USE_CODEC_MP3)
30 #include "snd_codec.h"
31 #include "snd_codeci.h"
32 #include "snd_mp3.h"
33 #include <mad.h>
34
35 /* Under Windows, importing data from DLLs is a dicey proposition. This is true
36 * when using dlopen, but also true if linking directly against the DLL if the
37 * header does not mark the data as __declspec(dllexport), which mad.h does not.
38 * Sidestep the issue by defining our own mad_timer_zero. This is needed because
39 * mad_timer_zero is used in some of the mad.h macros.
40 */
41 #define mad_timer_zero mad_timer_zero_stub
42 static mad_timer_t const mad_timer_zero_stub = {0, 0};
43
44 /* MAD returns values with MAD_F_FRACBITS (28) bits of precision, though it's
45 not certain that all of them are meaningful. Default to 16 bits to
46 align with most users expectation of output file should be 16 bits. */
47 #define MP3_MAD_SAMPLEBITS 16
48 #define MP3_MAD_SAMPLEWIDTH 2
49 #define MP3_BUFFER_SIZE (5 * 8192)
50
51 /* Private data */
52 typedef struct _mp3_priv_t
53 {
54 unsigned char mp3_buffer[MP3_BUFFER_SIZE];
55 struct mad_stream Stream;
56 struct mad_frame Frame;
57 struct mad_synth Synth;
58 mad_timer_t Timer;
59 ptrdiff_t cursamp;
60 size_t FrameCount;
61 } mp3_priv_t;
62
63
64 /* (Re)fill the stream buffer that is to be decoded. If any data
65 * still exists in the buffer then they are first shifted to be
66 * front of the stream buffer. */
mp3_inputdata(snd_stream_t * stream)67 static int mp3_inputdata(snd_stream_t *stream)
68 {
69 mp3_priv_t *p = (mp3_priv_t *) stream->priv;
70 size_t bytes_read;
71 size_t remaining;
72
73 remaining = p->Stream.bufend - p->Stream.next_frame;
74
75 /* libmad does not consume all the buffer it's given. Some
76 * data, part of a truncated frame, is left unused at the
77 * end of the buffer. That data must be put back at the
78 * beginning of the buffer and taken in account for
79 * refilling the buffer. This means that the input buffer
80 * must be large enough to hold a complete frame at the
81 * highest observable bit-rate (currently 448 kb/s).
82 * TODO: Is 2016 bytes the size of the largest frame?
83 * (448000*(1152/32000))/8
84 */
85 memmove(p->mp3_buffer, p->Stream.next_frame, remaining);
86
87 bytes_read = FS_fread(p->mp3_buffer + remaining, 1,
88 MP3_BUFFER_SIZE - remaining, &stream->fh);
89 if (bytes_read == 0)
90 return -1;
91
92 mad_stream_buffer(&p->Stream, p->mp3_buffer, bytes_read+remaining);
93 p->Stream.error = MAD_ERROR_NONE;
94
95 return 0;
96 }
97
mp3_startread(snd_stream_t * stream)98 static int mp3_startread(snd_stream_t *stream)
99 {
100 mp3_priv_t *p = (mp3_priv_t *) stream->priv;
101 size_t ReadSize;
102
103 mad_stream_init(&p->Stream);
104 mad_frame_init(&p->Frame);
105 mad_synth_init(&p->Synth);
106 mad_timer_reset(&p->Timer);
107
108 /* Decode at least one valid frame to find out the input
109 * format. The decoded frame will be saved off so that it
110 * can be processed later.
111 */
112 ReadSize = FS_fread(p->mp3_buffer, 1, MP3_BUFFER_SIZE, &stream->fh);
113 if (!ReadSize || FS_ferror(&stream->fh))
114 return -1;
115
116 mad_stream_buffer(&p->Stream, p->mp3_buffer, ReadSize);
117
118 /* Find a valid frame before starting up. This makes sure
119 * that we have a valid MP3.
120 */
121 p->Stream.error = MAD_ERROR_NONE;
122 while (mad_frame_decode(&p->Frame,&p->Stream))
123 {
124 /* check whether input buffer needs a refill */
125 if (p->Stream.error == MAD_ERROR_BUFLEN)
126 {
127 if (mp3_inputdata(stream) == -1)
128 return -1;/* EOF with no valid data */
129
130 continue;
131 }
132
133 /* We know that a valid frame hasn't been found yet
134 * so help libmad out and go back into frame seek mode.
135 */
136 mad_stream_sync(&p->Stream);
137 p->Stream.error = MAD_ERROR_NONE;
138 }
139
140 if (p->Stream.error)
141 {
142 Con_Printf("MP3: No valid MP3 frame found\n");
143 return -1;
144 }
145
146 switch(p->Frame.header.mode)
147 {
148 case MAD_MODE_SINGLE_CHANNEL:
149 case MAD_MODE_DUAL_CHANNEL:
150 case MAD_MODE_JOINT_STEREO:
151 case MAD_MODE_STEREO:
152 stream->info.channels = MAD_NCHANNELS(&p->Frame.header);
153 break;
154 default:
155 Con_Printf("MP3: Cannot determine number of channels\n");
156 return -1;
157 }
158
159 p->FrameCount = 1;
160
161 mad_timer_add(&p->Timer,p->Frame.header.duration);
162 mad_synth_frame(&p->Synth,&p->Frame);
163 stream->info.rate = p->Synth.pcm.samplerate;
164 stream->info.bits = MP3_MAD_SAMPLEBITS;
165 stream->info.width = MP3_MAD_SAMPLEWIDTH;
166
167 p->cursamp = 0;
168
169 return 0;
170 }
171
172 /* Read up to len samples from p->Synth
173 * If needed, read some more MP3 data, decode them and synth them
174 * Place in buf[].
175 * Return number of samples read. */
mp3_decode(snd_stream_t * stream,byte * buf,int len)176 static int mp3_decode(snd_stream_t *stream, byte *buf, int len)
177 {
178 mp3_priv_t *p = (mp3_priv_t *) stream->priv;
179 int donow, i, done = 0;
180 mad_fixed_t sample;
181 int chan, x;
182
183 do
184 {
185 x = (p->Synth.pcm.length - p->cursamp) * stream->info.channels;
186 donow = q_min(len, x);
187 i = 0;
188 while (i < donow)
189 {
190 for (chan = 0; chan < stream->info.channels; chan++)
191 {
192 sample = p->Synth.pcm.samples[chan][p->cursamp];
193 /* convert from fixed to short,
194 * write in host-endian format. */
195 if (sample <= -MAD_F_ONE)
196 sample = -0x7FFF;
197 else if (sample >= MAD_F_ONE)
198 sample = 0x7FFF;
199 else
200 sample >>= (MAD_F_FRACBITS + 1 - 16);
201 if (host_bigendian)
202 {
203 *buf++ = (sample >> 8) & 0xFF;
204 *buf++ = sample & 0xFF;
205 }
206 else /* assumed LITTLE_ENDIAN. */
207 {
208 *buf++ = sample & 0xFF;
209 *buf++ = (sample >> 8) & 0xFF;
210 }
211 i++;
212 }
213 p->cursamp++;
214 }
215
216 len -= donow;
217 done += donow;
218
219 if (len == 0)
220 break;
221
222 /* check whether input buffer needs a refill */
223 if (p->Stream.error == MAD_ERROR_BUFLEN)
224 {
225 if (mp3_inputdata(stream) == -1)
226 {
227 /* check feof() ?? */
228 Con_DPrintf("mp3 EOF\n");
229 break;
230 }
231 }
232
233 if (mad_frame_decode(&p->Frame, &p->Stream))
234 {
235 if (MAD_RECOVERABLE(p->Stream.error))
236 {
237 mad_stream_sync(&p->Stream); /* to frame seek mode */
238 continue;
239 }
240 else
241 {
242 if (p->Stream.error == MAD_ERROR_BUFLEN)
243 continue;
244 else
245 {
246 Con_Printf("MP3: unrecoverable frame level error (%s)\n",
247 mad_stream_errorstr(&p->Stream));
248 break;
249 }
250 }
251 }
252 p->FrameCount++;
253 mad_timer_add(&p->Timer, p->Frame.header.duration);
254 mad_synth_frame(&p->Synth, &p->Frame);
255 p->cursamp = 0;
256 } while (1);
257
258 return done;
259 }
260
mp3_stopread(snd_stream_t * stream)261 static int mp3_stopread(snd_stream_t *stream)
262 {
263 mp3_priv_t *p = (mp3_priv_t*) stream->priv;
264
265 mad_synth_finish(&p->Synth);
266 mad_frame_finish(&p->Frame);
267 mad_stream_finish(&p->Stream);
268
269 return 0;
270 }
271
mp3_madseek(snd_stream_t * stream,unsigned long offset)272 static int mp3_madseek(snd_stream_t *stream, unsigned long offset)
273 {
274 mp3_priv_t *p = (mp3_priv_t *) stream->priv;
275 size_t initial_bitrate = p->Frame.header.bitrate;
276 size_t consumed = 0;
277 int vbr = 0; /* Variable Bit Rate, bool */
278 qboolean depadded = false;
279 unsigned long to_skip_samples = 0;
280
281 /* Reset all */
282 FS_rewind(&stream->fh);
283 mad_timer_reset(&p->Timer);
284 p->FrameCount = 0;
285
286 /* They where opened in startread */
287 mad_synth_finish(&p->Synth);
288 mad_frame_finish(&p->Frame);
289 mad_stream_finish(&p->Stream);
290
291 mad_stream_init(&p->Stream);
292 mad_frame_init(&p->Frame);
293 mad_synth_init(&p->Synth);
294
295 offset /= stream->info.channels;
296 to_skip_samples = offset;
297
298 while (1) /* Read data from the MP3 file */
299 {
300 int bytes_read, padding = 0;
301 size_t leftover = p->Stream.bufend - p->Stream.next_frame;
302
303 memcpy(p->mp3_buffer, p->Stream.this_frame, leftover);
304 bytes_read = FS_fread(p->mp3_buffer + leftover, (size_t) 1,
305 MP3_BUFFER_SIZE - leftover, &stream->fh);
306 if (bytes_read <= 0)
307 {
308 Con_DPrintf("seek failure. unexpected EOF (frames=%lu leftover=%lu)\n",
309 (unsigned long)p->FrameCount, (unsigned long)leftover);
310 break;
311 }
312 for ( ; !depadded && padding < bytes_read && !p->mp3_buffer[padding]; ++padding)
313 ;
314 depadded = true;
315 mad_stream_buffer(&p->Stream, p->mp3_buffer + padding, leftover + bytes_read - padding);
316
317 while (1) /* Decode frame headers */
318 {
319 static unsigned short samples;
320 p->Stream.error = MAD_ERROR_NONE;
321
322 /* Not an audio frame */
323 if (mad_header_decode(&p->Frame.header, &p->Stream) == -1)
324 {
325 if (p->Stream.error == MAD_ERROR_BUFLEN)
326 break; /* Normal behaviour; get some more data from the file */
327 if (!MAD_RECOVERABLE(p->Stream.error))
328 {
329 Con_DPrintf("unrecoverable MAD error\n");
330 break;
331 }
332 if (p->Stream.error == MAD_ERROR_LOSTSYNC)
333 {
334 Con_DPrintf("MAD lost sync\n");
335 }
336 else
337 {
338 Con_DPrintf("recoverable MAD error\n");
339 }
340 continue;
341 }
342
343 consumed += p->Stream.next_frame - p->Stream.this_frame;
344 vbr |= (p->Frame.header.bitrate != initial_bitrate);
345
346 samples = 32 * MAD_NSBSAMPLES(&p->Frame.header);
347
348 p->FrameCount++;
349 mad_timer_add(&p->Timer, p->Frame.header.duration);
350
351 if (to_skip_samples <= samples)
352 {
353 mad_frame_decode(&p->Frame,&p->Stream);
354 mad_synth_frame(&p->Synth, &p->Frame);
355 p->cursamp = to_skip_samples;
356 return 0;
357 }
358 else to_skip_samples -= samples;
359
360 /* If not VBR, we can extrapolate frame size */
361 if (p->FrameCount == 64 && !vbr)
362 {
363 p->FrameCount = offset / samples;
364 to_skip_samples = offset % samples;
365 if (0 != FS_fseek(&stream->fh, (p->FrameCount * consumed / 64), SEEK_SET))
366 return -1;
367
368 /* Reset Stream for refilling buffer */
369 mad_stream_finish(&p->Stream);
370 mad_stream_init(&p->Stream);
371 break;
372 }
373 }
374 }
375
376 return -1;
377 }
378
S_MP3_CodecInitialize(void)379 static qboolean S_MP3_CodecInitialize (void)
380 {
381 return true;
382 }
383
S_MP3_CodecShutdown(void)384 static void S_MP3_CodecShutdown (void)
385 {
386 }
387
S_MP3_CodecOpenStream(snd_stream_t * stream)388 static qboolean S_MP3_CodecOpenStream (snd_stream_t *stream)
389 {
390 int err;
391
392 if (mp3_skiptags(stream) < 0)
393 {
394 Con_Printf("Corrupt mp3 file (bad tags.)\n");
395 return false;
396 }
397
398 stream->priv = calloc(1, sizeof(mp3_priv_t));
399 if (!stream->priv)
400 {
401 Con_Printf("Insufficient memory for MP3 audio\n");
402 return false;
403 }
404 err = mp3_startread(stream);
405 if (err != 0)
406 {
407 Con_Printf("%s is not a valid mp3 file\n", stream->name);
408 }
409 else if (stream->info.channels != 1 && stream->info.channels != 2)
410 {
411 Con_Printf("Unsupported number of channels %d in %s\n",
412 stream->info.channels, stream->name);
413 }
414 else
415 {
416 return true;
417 }
418 free(stream->priv);
419 return false;
420 }
421
S_MP3_CodecReadStream(snd_stream_t * stream,int bytes,void * buffer)422 static int S_MP3_CodecReadStream (snd_stream_t *stream, int bytes, void *buffer)
423 {
424 int res = mp3_decode(stream, (byte *)buffer, bytes / stream->info.width);
425 return res * stream->info.width;
426 }
427
S_MP3_CodecCloseStream(snd_stream_t * stream)428 static void S_MP3_CodecCloseStream (snd_stream_t *stream)
429 {
430 mp3_stopread(stream);
431 free(stream->priv);
432 S_CodecUtilClose(&stream);
433 }
434
S_MP3_CodecRewindStream(snd_stream_t * stream)435 static int S_MP3_CodecRewindStream (snd_stream_t *stream)
436 {
437 /*
438 mp3_stopread(stream);
439 FS_rewind(&stream->fh);
440 return mp3_startread(stream);
441 */
442 return mp3_madseek(stream, 0);
443 }
444
445 snd_codec_t mp3_codec =
446 {
447 CODECTYPE_MP3,
448 true, /* always available. */
449 "mp3",
450 S_MP3_CodecInitialize,
451 S_MP3_CodecShutdown,
452 S_MP3_CodecOpenStream,
453 S_MP3_CodecReadStream,
454 S_MP3_CodecRewindStream,
455 NULL, /* jump */
456 S_MP3_CodecCloseStream,
457 NULL
458 };
459
460 #endif /* USE_CODEC_MP3 */
461
462