ResidualVM logo ResidualVM website - Forums - Contact us BuildBot - Doxygen - Wiki curved edge

mp3.cpp

Go to the documentation of this file.
00001 /* ScummVM - Graphic Adventure Engine
00002  *
00003  * ScummVM is the legal property of its developers, whose names
00004  * are too numerous to list here. Please refer to the COPYRIGHT
00005  * file distributed with this source distribution.
00006  *
00007  * This program is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU General Public License
00009  * as published by the Free Software Foundation; either version 2
00010  * of the License, or (at your option) any later version.
00011  *
00012  * This program is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015  * GNU General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU General Public License
00018  * along with this program; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00020  *
00021  */
00022 
00023 #include "audio/decoders/mp3.h"
00024 
00025 #ifdef USE_MAD
00026 
00027 #include "common/debug.h"
00028 #include "common/mutex.h"
00029 #include "common/ptr.h"
00030 #include "common/queue.h"
00031 #include "common/stream.h"
00032 #include "common/substream.h"
00033 #include "common/textconsole.h"
00034 #include "common/util.h"
00035 
00036 #include "audio/audiostream.h"
00037 
00038 #include <mad.h>
00039 
00040 #if defined(__PSP__)
00041     #include "backends/platform/psp/mp3.h"
00042 #endif
00043 namespace Audio {
00044 
00045 
00046 #pragma mark -
00047 #pragma mark --- MP3 (MAD) stream ---
00048 #pragma mark -
00049 
00050 
00051 class BaseMP3Stream : public virtual AudioStream {
00052 public:
00053     BaseMP3Stream();
00054     virtual ~BaseMP3Stream();
00055 
00056     bool endOfData() const { return _state == MP3_STATE_EOS; }
00057     bool isStereo() const { return _channels == 2; }
00058     int getRate() const { return _rate; }
00059 
00060 protected:
00061     void decodeMP3Data(Common::ReadStream &stream);
00062     void readMP3Data(Common::ReadStream &stream);
00063 
00064     void initStream(Common::ReadStream &stream);
00065     void readHeader(Common::ReadStream &stream);
00066     void deinitStream();
00067 
00068     int fillBuffer(Common::ReadStream &stream, int16 *buffer, const int numSamples);
00069 
00070     enum State {
00071         MP3_STATE_INIT, // Need to init the decoder
00072         MP3_STATE_READY,    // ready for processing data
00073         MP3_STATE_EOS       // end of data reached (may need to loop)
00074     };
00075 
00076     uint _posInFrame;
00077     State _state;
00078 
00079     mad_timer_t _curTime;
00080 
00081     mad_stream _stream;
00082     mad_frame _frame;
00083     mad_synth _synth;
00084 
00085     uint _channels;
00086     uint _rate;
00087 
00088     enum {
00089         BUFFER_SIZE = 5 * 8192
00090     };
00091 
00092     // This buffer contains a slab of input data
00093     byte _buf[BUFFER_SIZE + MAD_BUFFER_GUARD];
00094 };
00095 
00096 class MP3Stream : private BaseMP3Stream, public SeekableAudioStream {
00097 public:
00098     MP3Stream(Common::SeekableReadStream *inStream,
00099                    DisposeAfterUse::Flag dispose);
00100 
00101     int readBuffer(int16 *buffer, const int numSamples);
00102     bool seek(const Timestamp &where);
00103     Timestamp getLength() const { return _length; }
00104 
00105 protected:
00106     Common::ScopedPtr<Common::SeekableReadStream> _inStream;
00107 
00108     Timestamp _length;
00109 
00110 private:
00111     static Common::SeekableReadStream *skipID3(Common::SeekableReadStream *stream, DisposeAfterUse::Flag dispose);
00112 };
00113 
00114 class PacketizedMP3Stream : private BaseMP3Stream, public PacketizedAudioStream {
00115 public:
00116     PacketizedMP3Stream(Common::SeekableReadStream &firstPacket);
00117     PacketizedMP3Stream(uint channels, uint rate);
00118     ~PacketizedMP3Stream();
00119 
00120     // AudioStream API
00121     int readBuffer(int16 *buffer, const int numSamples);
00122     bool endOfData() const;
00123     bool endOfStream() const;
00124 
00125     // PacketizedAudioStream API
00126     void queuePacket(Common::SeekableReadStream *packet);
00127     void finish();
00128 
00129 private:
00130     Common::Mutex _mutex;
00131     Common::Queue<Common::SeekableReadStream *> _queue;
00132     bool _finished;
00133 };
00134 
00135 
00136 BaseMP3Stream::BaseMP3Stream() :
00137     _posInFrame(0),
00138     _state(MP3_STATE_INIT),
00139     _curTime(mad_timer_zero) {
00140 
00141     // The MAD_BUFFER_GUARD must always contain zeros (the reason
00142     // for this is that the Layer III Huffman decoder of libMAD
00143     // may read a few bytes beyond the end of the input buffer).
00144     memset(_buf + BUFFER_SIZE, 0, MAD_BUFFER_GUARD);
00145 }
00146 
00147 BaseMP3Stream::~BaseMP3Stream() {
00148     deinitStream();
00149 }
00150 
00151 void BaseMP3Stream::decodeMP3Data(Common::ReadStream &stream) {
00152     do {
00153         if (_state == MP3_STATE_INIT)
00154             initStream(stream);
00155 
00156         if (_state == MP3_STATE_EOS)
00157             return;
00158 
00159         // If necessary, load more data into the stream decoder
00160         if (_stream.error == MAD_ERROR_BUFLEN)
00161             readMP3Data(stream);
00162 
00163         while (_state == MP3_STATE_READY) {
00164             _stream.error = MAD_ERROR_NONE;
00165 
00166             // Decode the next frame
00167             if (mad_frame_decode(&_frame, &_stream) == -1) {
00168                 if (_stream.error == MAD_ERROR_BUFLEN) {
00169                     break; // Read more data
00170                 } else if (MAD_RECOVERABLE(_stream.error)) {
00171                     // Note: we will occasionally see MAD_ERROR_BADDATAPTR errors here.
00172                     // These are normal and expected (caused by our frame skipping (i.e. "seeking")
00173                     // code above).
00174                     debug(6, "MP3Stream: Recoverable error in mad_frame_decode (%s)", mad_stream_errorstr(&_stream));
00175                     continue;
00176                 } else {
00177                     warning("MP3Stream: Unrecoverable error in mad_frame_decode (%s)", mad_stream_errorstr(&_stream));
00178                     break;
00179                 }
00180             }
00181 
00182             // Sum up the total playback time so far
00183             mad_timer_add(&_curTime, _frame.header.duration);
00184             // Synthesize PCM data
00185             mad_synth_frame(&_synth, &_frame);
00186             _posInFrame = 0;
00187             break;
00188         }
00189     } while (_state != MP3_STATE_EOS && _stream.error == MAD_ERROR_BUFLEN);
00190 
00191     if (_stream.error != MAD_ERROR_NONE)
00192         _state = MP3_STATE_EOS;
00193 }
00194 
00195 void BaseMP3Stream::readMP3Data(Common::ReadStream &stream) {
00196     uint32 remaining = 0;
00197 
00198     // Give up immediately if we already used up all data in the stream
00199     if (stream.eos()) {
00200         _state = MP3_STATE_EOS;
00201         return;
00202     }
00203 
00204     if (_stream.next_frame) {
00205         // If there is still data in the MAD stream, we need to preserve it.
00206         // Note that we use memmove, as we are reusing the same buffer,
00207         // and hence the data regions we copy from and to may overlap.
00208         remaining = _stream.bufend - _stream.next_frame;
00209         assert(remaining < BUFFER_SIZE);    // Paranoia check
00210         memmove(_buf, _stream.next_frame, remaining);
00211     }
00212 
00213     // Try to read the next block
00214     uint32 size = stream.read(_buf + remaining, BUFFER_SIZE - remaining);
00215     if (size <= 0) {
00216         _state = MP3_STATE_EOS;
00217         return;
00218     }
00219 
00220     // Feed the data we just read into the stream decoder
00221     _stream.error = MAD_ERROR_NONE;
00222     mad_stream_buffer(&_stream, _buf, size + remaining);
00223 }
00224 
00225 void BaseMP3Stream::initStream(Common::ReadStream &stream) {
00226     if (_state != MP3_STATE_INIT)
00227         deinitStream();
00228 
00229     // Init MAD
00230     mad_stream_init(&_stream);
00231     mad_frame_init(&_frame);
00232     mad_synth_init(&_synth);
00233 
00234     // Reset the stream data
00235     _curTime = mad_timer_zero;
00236     _posInFrame = 0;
00237 
00238     // Update state
00239     _state = MP3_STATE_READY;
00240 
00241     // Read the first few sample bytes
00242     readMP3Data(stream);
00243 }
00244 
00245 void BaseMP3Stream::readHeader(Common::ReadStream &stream) {
00246     if (_state != MP3_STATE_READY)
00247         return;
00248 
00249     // If necessary, load more data into the stream decoder
00250     if (_stream.error == MAD_ERROR_BUFLEN)
00251         readMP3Data(stream);
00252 
00253     while (_state != MP3_STATE_EOS) {
00254         _stream.error = MAD_ERROR_NONE;
00255 
00256         // Decode the next header. Note: mad_frame_decode would do this for us, too.
00257         // However, for seeking we don't want to decode the full frame (else it would
00258         // be far too slow). Hence we perform this explicitly in a separate step.
00259         if (mad_header_decode(&_frame.header, &_stream) == -1) {
00260             if (_stream.error == MAD_ERROR_BUFLEN) {
00261                 readMP3Data(stream);  // Read more data
00262                 continue;
00263             } else if (MAD_RECOVERABLE(_stream.error)) {
00264                 debug(6, "MP3Stream: Recoverable error in mad_header_decode (%s)", mad_stream_errorstr(&_stream));
00265                 continue;
00266             } else {
00267                 warning("MP3Stream: Unrecoverable error in mad_header_decode (%s)", mad_stream_errorstr(&_stream));
00268                 break;
00269             }
00270         }
00271 
00272         // Sum up the total playback time so far
00273         mad_timer_add(&_curTime, _frame.header.duration);
00274         break;
00275     }
00276 
00277     if (_stream.error != MAD_ERROR_NONE)
00278         _state = MP3_STATE_EOS;
00279 }
00280 
00281 void BaseMP3Stream::deinitStream() {
00282     if (_state == MP3_STATE_INIT)
00283         return;
00284 
00285     // Deinit MAD
00286     mad_synth_finish(&_synth);
00287     mad_frame_finish(&_frame);
00288     mad_stream_finish(&_stream);
00289 
00290     _state = MP3_STATE_EOS;
00291 }
00292 
00293 static inline int scaleSample(mad_fixed_t sample) {
00294     // round
00295     sample += (1L << (MAD_F_FRACBITS - 16));
00296 
00297     // clip
00298     if (sample > MAD_F_ONE - 1)
00299         sample = MAD_F_ONE - 1;
00300     else if (sample < -MAD_F_ONE)
00301         sample = -MAD_F_ONE;
00302 
00303     // quantize and scale to not saturate when mixing a lot of channels
00304     return sample >> (MAD_F_FRACBITS + 1 - 16);
00305 }
00306 
00307 int BaseMP3Stream::fillBuffer(Common::ReadStream &stream, int16 *buffer, const int numSamples) {
00308     int samples = 0;
00309     // Keep going as long as we have input available
00310     while (samples < numSamples && _state != MP3_STATE_EOS) {
00311         const int len = MIN(numSamples, samples + (int)(_synth.pcm.length - _posInFrame) * MAD_NCHANNELS(&_frame.header));
00312         while (samples < len) {
00313             *buffer++ = (int16)scaleSample(_synth.pcm.samples[0][_posInFrame]);
00314             samples++;
00315             if (MAD_NCHANNELS(&_frame.header) == 2) {
00316                 *buffer++ = (int16)scaleSample(_synth.pcm.samples[1][_posInFrame]);
00317                 samples++;
00318             }
00319             _posInFrame++;
00320         }
00321         if (_posInFrame >= _synth.pcm.length) {
00322             // We used up all PCM data in the current frame -- read & decode more
00323             decodeMP3Data(stream);
00324         }
00325     }
00326     return samples;
00327 }
00328 
00329 MP3Stream::MP3Stream(Common::SeekableReadStream *inStream, DisposeAfterUse::Flag dispose) :
00330         BaseMP3Stream(),
00331         _inStream(skipID3(inStream, dispose)),
00332         _length(0, 1000) {
00333 
00334     // Initialize the stream with some data and set the channels and rate
00335     // variables
00336     decodeMP3Data(*_inStream);
00337     _channels = MAD_NCHANNELS(&_frame.header);
00338     _rate = _frame.header.samplerate;
00339 
00340     // Calculate the length of the stream
00341     while (_state != MP3_STATE_EOS)
00342         readHeader(*_inStream);
00343 
00344     // To rule out any invalid sample rate to be encountered here, say in case the
00345     // MP3 stream is invalid, we just check the MAD error code here.
00346     // We need to assure this, since else we might trigger an assertion in Timestamp
00347     // (When getRate() returns 0 or a negative number to be precise).
00348     // Note that we allow "MAD_ERROR_BUFLEN" as error code here, since according
00349     // to mad.h it is also set on EOF.
00350     if ((_stream.error == MAD_ERROR_NONE || _stream.error == MAD_ERROR_BUFLEN) && getRate() > 0)
00351         _length = Timestamp(mad_timer_count(_curTime, MAD_UNITS_MILLISECONDS), getRate());
00352 
00353     deinitStream();
00354 
00355     // Reinit stream
00356     _state = MP3_STATE_INIT;
00357     _inStream->seek(0);
00358 
00359     // Decode the first chunk of data to set up the stream again.
00360     decodeMP3Data(*_inStream);
00361 }
00362 
00363 int MP3Stream::readBuffer(int16 *buffer, const int numSamples) {
00364     return fillBuffer(*_inStream, buffer, numSamples);
00365 }
00366 
00367 bool MP3Stream::seek(const Timestamp &where) {
00368     if (where == _length) {
00369         _state = MP3_STATE_EOS;
00370         return true;
00371     } else if (where > _length) {
00372         return false;
00373     }
00374 
00375     const uint32 time = where.msecs();
00376 
00377     mad_timer_t destination;
00378     mad_timer_set(&destination, time / 1000, time % 1000, 1000);
00379 
00380     if (_state != MP3_STATE_READY || mad_timer_compare(destination, _curTime) < 0) {
00381         _inStream->seek(0);
00382         initStream(*_inStream);
00383     }
00384 
00385     while (mad_timer_compare(destination, _curTime) > 0 && _state != MP3_STATE_EOS)
00386         readHeader(*_inStream);
00387 
00388     decodeMP3Data(*_inStream);
00389 
00390     return (_state != MP3_STATE_EOS);
00391 }
00392 
00393 Common::SeekableReadStream *MP3Stream::skipID3(Common::SeekableReadStream *stream, DisposeAfterUse::Flag dispose) {
00394     // Skip ID3 TAG if any
00395     // ID3v1 (beginning with with 'TAG') is located at the end of files. So we can ignore those.
00396     // ID3v2 can be located at the start of files and begins with a 10 bytes header, the first 3 bytes being 'ID3'.
00397     // The tag size is coded on the last 4 bytes of the 10 bytes header as a 32 bit synchsafe integer.
00398     // See http://id3.org/id3v2.4.0-structure for details.
00399     char data[10];
00400     stream->read(data, sizeof(data));
00401 
00402     uint32 offset = 0;
00403     if (!stream->eos() && data[0] == 'I' && data[1] == 'D' && data[2] == '3') {
00404         uint32 size = data[9] + 128 * (data[8] + 128 * (data[7] + 128 * data[6]));
00405         // This size does not include an optional 10 bytes footer. Check if it is present.
00406         if (data[5] & 0x10)
00407             size += 10;
00408 
00409         // Add in the 10 bytes we read in
00410         size += sizeof(data);
00411         debug("Skipping ID3 TAG (%d bytes)", size);
00412         offset = size;
00413     }
00414 
00415     return new Common::SeekableSubReadStream(stream, offset, stream->size(), dispose);
00416 }
00417 
00418 PacketizedMP3Stream::PacketizedMP3Stream(Common::SeekableReadStream &firstPacket) :
00419         BaseMP3Stream(),
00420         _finished(false) {
00421 
00422     // Load some data to get the channels/rate
00423     _queue.push(&firstPacket);
00424     decodeMP3Data(firstPacket);
00425     _channels = MAD_NCHANNELS(&_frame.header);
00426     _rate = _frame.header.samplerate;
00427 
00428     // Clear everything
00429     deinitStream();
00430     _state = MP3_STATE_INIT;
00431     _queue.clear();
00432 }
00433 
00434 PacketizedMP3Stream::PacketizedMP3Stream(uint channels, uint rate) :
00435         BaseMP3Stream(),
00436         _finished(false) {
00437     _channels = channels;
00438     _rate = rate;
00439 }
00440 
00441 PacketizedMP3Stream::~PacketizedMP3Stream() {
00442     Common::StackLock lock(_mutex);
00443     while (!_queue.empty()) {
00444         delete _queue.front();
00445         _queue.pop();
00446     }
00447 }
00448 
00449 int PacketizedMP3Stream::readBuffer(int16 *buffer, const int numSamples) {
00450     int samples = 0;
00451 
00452     Common::StackLock lock(_mutex);
00453     while (samples < numSamples) {
00454         // Empty? Bail out for now, and mark the stream as ended
00455         if (_queue.empty()) {
00456             // EOS state is only valid once a packet has been received at least
00457             // once
00458             if (_state == MP3_STATE_READY)
00459                 _state = MP3_STATE_EOS;
00460             return samples;
00461         }
00462 
00463         Common::SeekableReadStream *packet = _queue.front();
00464 
00465         if (_state == MP3_STATE_INIT) {
00466             // Initialize everything
00467             decodeMP3Data(*packet);
00468         } else if (_state == MP3_STATE_EOS) {
00469             // Reset the end-of-stream setting
00470             _state = MP3_STATE_READY;
00471         }
00472 
00473         samples += fillBuffer(*packet, buffer + samples, numSamples - samples);
00474 
00475         // If the stream is done, kill it
00476         if (packet->pos() >= packet->size()) {
00477             _queue.pop();
00478             delete packet;
00479         }
00480     }
00481 
00482     // This will happen if the audio runs out just as the last sample is
00483     // decoded. But there may still be more audio queued up.
00484     if (_state == MP3_STATE_EOS && !_queue.empty()) {
00485         _state = MP3_STATE_READY;
00486     }
00487 
00488     return samples;
00489 }
00490 
00491 bool PacketizedMP3Stream::endOfData() const {
00492     Common::StackLock lock(_mutex);
00493     return BaseMP3Stream::endOfData();
00494 }
00495 
00496 bool PacketizedMP3Stream::endOfStream() const {
00497     Common::StackLock lock(_mutex);
00498 
00499     if (!endOfData())
00500         return false;
00501 
00502     if (!_queue.empty())
00503         return false;
00504 
00505     return _finished;
00506 }
00507 
00508 void PacketizedMP3Stream::queuePacket(Common::SeekableReadStream *packet) {
00509     Common::StackLock lock(_mutex);
00510     assert(!_finished);
00511     _queue.push(packet);
00512 
00513     // If the audio had finished (buffer underrun?), there is more to
00514     // decode now.
00515     if (_state == MP3_STATE_EOS) {
00516         _state = MP3_STATE_READY;
00517     }
00518 }
00519 
00520 void PacketizedMP3Stream::finish() {
00521     Common::StackLock lock(_mutex);
00522     _finished = true;
00523 }
00524 
00525 
00526 #pragma mark -
00527 #pragma mark --- MP3 factory functions ---
00528 #pragma mark -
00529 
00530 SeekableAudioStream *makeMP3Stream(
00531     Common::SeekableReadStream *stream,
00532     DisposeAfterUse::Flag disposeAfterUse) {
00533 
00534 #if defined(__PSP__)
00535     SeekableAudioStream *s = 0;
00536 
00537     if (Mp3PspStream::isOkToCreateStream())
00538         s = new Mp3PspStream(stream, disposeAfterUse);
00539 
00540     if (!s) // go to regular MAD mp3 stream if ME fails
00541         s = new MP3Stream(stream, disposeAfterUse);
00542 #else
00543     SeekableAudioStream *s = new MP3Stream(stream, disposeAfterUse);
00544 #endif
00545     if (s && s->endOfData()) {
00546         delete s;
00547         return 0;
00548     } else {
00549         return s;
00550     }
00551 }
00552 
00553 PacketizedAudioStream *makePacketizedMP3Stream(Common::SeekableReadStream &firstPacket) {
00554     return new PacketizedMP3Stream(firstPacket);
00555 }
00556 
00557 PacketizedAudioStream *makePacketizedMP3Stream(uint channels, uint rate) {
00558     return new PacketizedMP3Stream(channels, rate);
00559 }
00560 
00561 
00562 } // End of namespace Audio
00563 
00564 #endif // #ifdef USE_MAD


Generated on Sat Aug 17 2019 05:00:25 for ResidualVM by doxygen 1.7.1
curved edge   curved edge