1
/* ScummVM - Graphic Adventure Engine
3
* ScummVM is the legal property of its developers, whose names
4
* are too numerous to list here. Please refer to the COPYRIGHT
5
* file distributed with this source distribution.
7
* This program is free software; you can redistribute it and/or
8
* modify it under the terms of the GNU General Public License
9
* as published by the Free Software Foundation; either version 2
10
* of the License, or (at your option) any later version.
12
* This program is distributed in the hope that it will be useful,
13
* but WITHOUT ANY WARRANTY; without even the implied warranty of
14
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
* GNU General Public License for more details.
17
* You should have received a copy of the GNU General Public License
18
* along with this program; if not, write to the Free Software
19
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21
* $URL: https://scummvm.svn.sourceforge.net/svnroot/scummvm/scummvm/tags/release-1-2-1/sound/decoders/mp3.cpp $
22
* $Id: mp3.cpp 52272 2010-08-22 12:04:44Z lordhoto $
26
#include "sound/decoders/mp3.h"
30
#include "common/debug.h"
31
#include "common/stream.h"
32
#include "common/util.h"
34
#include "sound/audiocd.h"
35
#include "sound/audiostream.h"
40
#include "backends/platform/psp/mp3.h"
46
#pragma mark --- MP3 (MAD) stream ---
50
class MP3Stream : public SeekableAudioStream {
53
MP3_STATE_INIT, // Need to init the decoder
54
MP3_STATE_READY, // ready for processing data
55
MP3_STATE_EOS // end of data reached (may need to loop)
58
Common::SeekableReadStream *_inStream;
59
DisposeAfterUse::Flag _disposeAfterUse;
65
mad_timer_t _totalTime;
72
BUFFER_SIZE = 5 * 8192
75
// This buffer contains a slab of input data
76
byte _buf[BUFFER_SIZE + MAD_BUFFER_GUARD];
79
MP3Stream(Common::SeekableReadStream *inStream,
80
DisposeAfterUse::Flag dispose);
83
int readBuffer(int16 *buffer, const int numSamples);
85
bool endOfData() const { return _state == MP3_STATE_EOS; }
86
bool isStereo() const { return MAD_NCHANNELS(&_frame.header) == 2; }
87
int getRate() const { return _frame.header.samplerate; }
89
bool seek(const Timestamp &where);
90
Timestamp getLength() const { return _length; }
100
MP3Stream::MP3Stream(Common::SeekableReadStream *inStream, DisposeAfterUse::Flag dispose) :
102
_disposeAfterUse(dispose),
104
_state(MP3_STATE_INIT),
106
_totalTime(mad_timer_zero) {
108
// The MAD_BUFFER_GUARD must always contain zeros (the reason
109
// for this is that the Layer III Huffman decoder of libMAD
110
// may read a few bytes beyond the end of the input buffer).
111
memset(_buf + BUFFER_SIZE, 0, MAD_BUFFER_GUARD);
113
// Calculate the length of the stream
116
while (_state != MP3_STATE_EOS)
119
// To rule out any invalid sample rate to be encountered here, say in case the
120
// MP3 stream is invalid, we just check the MAD error code here.
121
// We need to assure this, since else we might trigger an assertion in Timestamp
122
// (When getRate() returns 0 or a negative number to be precise).
123
// Note that we allow "MAD_ERROR_BUFLEN" as error code here, since according
124
// to mad.h it is also set on EOF.
125
if ((_stream.error == MAD_ERROR_NONE || _stream.error == MAD_ERROR_BUFLEN) && getRate() > 0)
126
_length = Timestamp(mad_timer_count(_totalTime, MAD_UNITS_MILLISECONDS), getRate());
131
_state = MP3_STATE_INIT;
133
// Decode the first chunk of data. This is necessary so that _frame
134
// is setup and isStereo() and getRate() return correct results.
138
MP3Stream::~MP3Stream() {
141
if (_disposeAfterUse == DisposeAfterUse::YES)
145
void MP3Stream::decodeMP3Data() {
147
if (_state == MP3_STATE_INIT)
150
if (_state == MP3_STATE_EOS)
153
// If necessary, load more data into the stream decoder
154
if (_stream.error == MAD_ERROR_BUFLEN)
157
while (_state == MP3_STATE_READY) {
158
_stream.error = MAD_ERROR_NONE;
160
// Decode the next frame
161
if (mad_frame_decode(&_frame, &_stream) == -1) {
162
if (_stream.error == MAD_ERROR_BUFLEN) {
163
break; // Read more data
164
} else if (MAD_RECOVERABLE(_stream.error)) {
165
// Note: we will occasionally see MAD_ERROR_BADDATAPTR errors here.
166
// These are normal and expected (caused by our frame skipping (i.e. "seeking")
168
debug(6, "MP3Stream: Recoverable error in mad_frame_decode (%s)", mad_stream_errorstr(&_stream));
171
warning("MP3Stream: Unrecoverable error in mad_frame_decode (%s)", mad_stream_errorstr(&_stream));
176
// Synthesize PCM data
177
mad_synth_frame(&_synth, &_frame);
181
} while (_state != MP3_STATE_EOS && _stream.error == MAD_ERROR_BUFLEN);
183
if (_stream.error != MAD_ERROR_NONE)
184
_state = MP3_STATE_EOS;
187
void MP3Stream::readMP3Data() {
188
uint32 remaining = 0;
190
// Give up immediately if we already used up all data in the stream
191
if (_inStream->eos()) {
192
_state = MP3_STATE_EOS;
196
if (_stream.next_frame) {
197
// If there is still data in the MAD stream, we need to preserve it.
198
// Note that we use memmove, as we are reusing the same buffer,
199
// and hence the data regions we copy from and to may overlap.
200
remaining = _stream.bufend - _stream.next_frame;
201
assert(remaining < BUFFER_SIZE); // Paranoia check
202
memmove(_buf, _stream.next_frame, remaining);
205
// Try to read the next block
206
uint32 size = _inStream->read(_buf + remaining, BUFFER_SIZE - remaining);
208
_state = MP3_STATE_EOS;
212
// Feed the data we just read into the stream decoder
213
_stream.error = MAD_ERROR_NONE;
214
mad_stream_buffer(&_stream, _buf, size + remaining);
217
bool MP3Stream::seek(const Timestamp &where) {
218
if (where == _length) {
219
_state = MP3_STATE_EOS;
221
} else if (where > _length) {
225
const uint32 time = where.msecs();
227
mad_timer_t destination;
228
mad_timer_set(&destination, time / 1000, time % 1000, 1000);
230
if (_state != MP3_STATE_READY || mad_timer_compare(destination, _totalTime) < 0)
233
while (mad_timer_compare(destination, _totalTime) > 0 && _state != MP3_STATE_EOS)
238
return (_state != MP3_STATE_EOS);
241
void MP3Stream::initStream() {
242
if (_state != MP3_STATE_INIT)
246
mad_stream_init(&_stream);
247
mad_frame_init(&_frame);
248
mad_synth_init(&_synth);
250
// Reset the stream data
251
_inStream->seek(0, SEEK_SET);
252
_totalTime = mad_timer_zero;
256
_state = MP3_STATE_READY;
258
// Read the first few sample bytes
262
void MP3Stream::readHeader() {
263
if (_state != MP3_STATE_READY)
266
// If necessary, load more data into the stream decoder
267
if (_stream.error == MAD_ERROR_BUFLEN)
270
while (_state != MP3_STATE_EOS) {
271
_stream.error = MAD_ERROR_NONE;
273
// Decode the next header. Note: mad_frame_decode would do this for us, too.
274
// However, for seeking we don't want to decode the full frame (else it would
275
// be far too slow). Hence we perform this explicitly in a separate step.
276
if (mad_header_decode(&_frame.header, &_stream) == -1) {
277
if (_stream.error == MAD_ERROR_BUFLEN) {
278
readMP3Data(); // Read more data
280
} else if (MAD_RECOVERABLE(_stream.error)) {
281
debug(6, "MP3Stream: Recoverable error in mad_header_decode (%s)", mad_stream_errorstr(&_stream));
284
warning("MP3Stream: Unrecoverable error in mad_header_decode (%s)", mad_stream_errorstr(&_stream));
289
// Sum up the total playback time so far
290
mad_timer_add(&_totalTime, _frame.header.duration);
294
if (_stream.error != MAD_ERROR_NONE)
295
_state = MP3_STATE_EOS;
298
void MP3Stream::deinitStream() {
299
if (_state == MP3_STATE_INIT)
303
mad_synth_finish(&_synth);
304
mad_frame_finish(&_frame);
305
mad_stream_finish(&_stream);
307
_state = MP3_STATE_EOS;
310
static inline int scale_sample(mad_fixed_t sample) {
312
sample += (1L << (MAD_F_FRACBITS - 16));
315
if (sample > MAD_F_ONE - 1)
316
sample = MAD_F_ONE - 1;
317
else if (sample < -MAD_F_ONE)
320
// quantize and scale to not saturate when mixing a lot of channels
321
return sample >> (MAD_F_FRACBITS + 1 - 16);
324
int MP3Stream::readBuffer(int16 *buffer, const int numSamples) {
326
// Keep going as long as we have input available
327
while (samples < numSamples && _state != MP3_STATE_EOS) {
328
const int len = MIN(numSamples, samples + (int)(_synth.pcm.length - _posInFrame) * MAD_NCHANNELS(&_frame.header));
329
while (samples < len) {
330
*buffer++ = (int16)scale_sample(_synth.pcm.samples[0][_posInFrame]);
332
if (MAD_NCHANNELS(&_frame.header) == 2) {
333
*buffer++ = (int16)scale_sample(_synth.pcm.samples[1][_posInFrame]);
338
if (_posInFrame >= _synth.pcm.length) {
339
// We used up all PCM data in the current frame -- read & decode more
348
#pragma mark --- MP3 factory functions ---
351
SeekableAudioStream *makeMP3Stream(
352
Common::SeekableReadStream *stream,
353
DisposeAfterUse::Flag disposeAfterUse) {
356
SeekableAudioStream *s = 0;
358
if (Mp3PspStream::isOkToCreateStream())
359
s = new Mp3PspStream(stream, disposeAfterUse);
361
if (!s) // go to regular MAD mp3 stream if ME fails
362
s = new MP3Stream(stream, disposeAfterUse);
364
SeekableAudioStream *s = new MP3Stream(stream, disposeAfterUse);
366
if (s && s->endOfData()) {
374
} // End of namespace Audio
376
#endif // #ifdef USE_MAD