Hooked up the pathfinder so that it seems to work. Animation opcode 0x12.
[scummvm-innocent.git] / sound / mp3.cpp
blobc9cc5d33e70187253d9bfb822f3bfdc0d3ea8638
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$
22 * $Id$
26 #include "sound/mp3.h"
28 #ifdef USE_MAD
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"
37 #include <mad.h>
40 namespace Audio {
43 #pragma mark -
44 #pragma mark --- MP3 (MAD) stream ---
45 #pragma mark -
48 class MP3InputStream : public AudioStream {
49 protected:
50 enum State {
51 MP3_STATE_INIT, // Need to init the decoder
52 MP3_STATE_READY, // ready for processing data
53 MP3_STATE_EOS // end of data reached (may need to loop)
56 Common::SeekableReadStream *_inStream;
57 bool _disposeAfterUse;
59 uint _numLoops;
60 uint _posInFrame;
61 State _state;
63 const mad_timer_t _startTime;
64 const mad_timer_t _endTime;
65 mad_timer_t _totalTime;
67 int32 _totalPlayTime;
69 mad_stream _stream;
70 mad_frame _frame;
71 mad_synth _synth;
73 enum {
74 BUFFER_SIZE = 5 * 8192
77 // This buffer contains a slab of input data
78 byte _buf[BUFFER_SIZE + MAD_BUFFER_GUARD];
80 public:
81 MP3InputStream(Common::SeekableReadStream *inStream,
82 bool dispose,
83 mad_timer_t start = mad_timer_zero,
84 mad_timer_t end = mad_timer_zero,
85 uint numLoops = 1);
86 ~MP3InputStream();
88 int readBuffer(int16 *buffer, const int numSamples);
90 bool endOfData() const { return _state == MP3_STATE_EOS; }
91 bool isStereo() const { return MAD_NCHANNELS(&_frame.header) == 2; }
92 int getRate() const { return _frame.header.samplerate; }
93 int32 getTotalPlayTime() const { return _totalPlayTime; }
95 protected:
96 void decodeMP3Data();
97 void readMP3Data();
100 MP3InputStream::MP3InputStream(Common::SeekableReadStream *inStream, bool dispose, mad_timer_t start, mad_timer_t end, uint numLoops) :
101 _inStream(inStream),
102 _disposeAfterUse(dispose),
103 _numLoops(numLoops),
104 _posInFrame(0),
105 _state(MP3_STATE_INIT),
106 _startTime(start),
107 _endTime(end),
108 _totalTime(mad_timer_zero) {
110 // Make sure that either start < end, or end is zero (indicating "play until end")
111 assert(mad_timer_compare(_startTime, _endTime) < 0 || mad_timer_sign(_endTime) == 0);
113 // The MAD_BUFFER_GUARD must always contain zeros (the reason
114 // for this is that the Layer III Huffman decoder of libMAD
115 // may read a few bytes beyond the end of the input buffer).
116 memset(_buf + BUFFER_SIZE, 0, MAD_BUFFER_GUARD);
118 // Calculate play time
119 mad_timer_t length;
121 mad_timer_set(&length, 0, 0, 1000);
122 mad_timer_add(&length, start);
123 mad_timer_negate(&length);
125 if (mad_timer_sign(end) != 0) {
126 mad_timer_add(&length, end);
127 } else {
128 mad_stream_init(&_stream);
129 mad_frame_init(&_frame);
131 // Reset the stream data
132 _inStream->seek(0, SEEK_SET);
134 // Update state
135 _state = MP3_STATE_READY;
137 // Read the first few sample bytes
138 readMP3Data();
140 do {
141 // If necessary, load more data into the stream decoder
142 if (_stream.error == MAD_ERROR_BUFLEN)
143 readMP3Data();
145 while (_state == MP3_STATE_READY) {
146 _stream.error = MAD_ERROR_NONE;
148 // Decode the next header. Note: mad_frame_decode would do this for us, too.
149 // However, for seeking we don't want to decode the full frame (else it would
150 // be far too slow).
151 if (mad_header_decode(&_frame.header, &_stream) == -1) {
152 if (_stream.error == MAD_ERROR_BUFLEN) {
153 break; // Read more data
154 } else if (MAD_RECOVERABLE(_stream.error)) {
155 debug(6, "MP3InputStream: Recoverable error in mad_header_decode (%s)", mad_stream_errorstr(&_stream));
156 continue;
157 } else {
158 warning("MP3InputStream: Unrecoverable error in mad_header_decode (%s)", mad_stream_errorstr(&_stream));
159 break;
163 // Sum up the total playback time so far
164 mad_timer_add(&length, _frame.header.duration);
166 } while (_state != MP3_STATE_EOS);
168 mad_synth_finish(&_synth);
169 mad_frame_finish(&_frame);
171 // Reinit stream
172 _state = MP3_STATE_INIT;
174 // Reset the stream data
175 _inStream->seek(0, SEEK_SET);
178 _totalPlayTime = mad_timer_count(length, MAD_UNITS_MILLISECONDS);
180 if (numLoops && mad_timer_sign(length) >= 0)
181 _totalPlayTime *= numLoops;
182 else
183 _totalPlayTime = kUnknownPlayTime;
185 // Decode the first chunk of data. This is necessary so that _frame
186 // is setup and isStereo() and getRate() return correct results.
187 decodeMP3Data();
190 MP3InputStream::~MP3InputStream() {
191 if (_state != MP3_STATE_INIT) {
192 // Deinit MAD
193 mad_synth_finish(&_synth);
194 mad_frame_finish(&_frame);
195 mad_stream_finish(&_stream);
198 if (_disposeAfterUse)
199 delete _inStream;
202 void MP3InputStream::decodeMP3Data() {
204 do {
205 if (_state == MP3_STATE_INIT) {
206 // Init MAD
207 mad_stream_init(&_stream);
208 mad_frame_init(&_frame);
209 mad_synth_init(&_synth);
211 // Reset the stream data
212 _inStream->seek(0, SEEK_SET);
213 _totalTime = mad_timer_zero;
214 _posInFrame = 0;
216 // Update state
217 _state = MP3_STATE_READY;
219 // Read the first few sample bytes
220 readMP3Data();
223 if (_state == MP3_STATE_EOS)
224 return;
226 // If necessary, load more data into the stream decoder
227 if (_stream.error == MAD_ERROR_BUFLEN)
228 readMP3Data();
230 while (_state == MP3_STATE_READY) {
231 _stream.error = MAD_ERROR_NONE;
233 // Decode the next header. Note: mad_frame_decode would do this for us, too.
234 // However, for seeking we don't want to decode the full frame (else it would
235 // be far too slow). Hence we perform this explicitly in a separate step.
236 if (mad_header_decode(&_frame.header, &_stream) == -1) {
237 if (_stream.error == MAD_ERROR_BUFLEN) {
238 break; // Read more data
239 } else if (MAD_RECOVERABLE(_stream.error)) {
240 debug(6, "MP3InputStream: Recoverable error in mad_header_decode (%s)", mad_stream_errorstr(&_stream));
241 continue;
242 } else {
243 warning("MP3InputStream: Unrecoverable error in mad_header_decode (%s)", mad_stream_errorstr(&_stream));
244 break;
248 // Sum up the total playback time so far
249 mad_timer_add(&_totalTime, _frame.header.duration);
251 // If we have not yet reached the start point, skip to the next frame
252 if (mad_timer_compare(_totalTime, _startTime) < 0)
253 continue;
255 // If an end time is specified and we are past it, stop
256 if (mad_timer_sign(_endTime) > 0 && mad_timer_compare(_totalTime, _endTime) >= 0) {
257 _state = MP3_STATE_EOS;
258 break;
261 // Decode the next frame
262 if (mad_frame_decode(&_frame, &_stream) == -1) {
263 if (_stream.error == MAD_ERROR_BUFLEN) {
264 break; // Read more data
265 } else if (MAD_RECOVERABLE(_stream.error)) {
266 // Note: we will occasionally see MAD_ERROR_BADDATAPTR errors here.
267 // These are normal and expected (caused by our frame skipping (i.e. "seeking")
268 // code above).
269 debug(6, "MP3InputStream: Recoverable error in mad_frame_decode (%s)", mad_stream_errorstr(&_stream));
270 continue;
271 } else {
272 warning("MP3InputStream: Unrecoverable error in mad_frame_decode (%s)", mad_stream_errorstr(&_stream));
273 break;
277 // Synthesize PCM data
278 mad_synth_frame(&_synth, &_frame);
279 _posInFrame = 0;
280 break;
283 if (_state == MP3_STATE_EOS && _numLoops != 1) {
284 // If looping is on and there are loops left, rewind to the start
285 if (_numLoops != 0)
286 _numLoops--;
288 // Deinit MAD
289 mad_synth_finish(&_synth);
290 mad_frame_finish(&_frame);
291 mad_stream_finish(&_stream);
293 // Reset the decoder state to indicate we should start over
294 _state = MP3_STATE_INIT;
297 } while (_state != MP3_STATE_EOS && _stream.error == MAD_ERROR_BUFLEN);
299 if (_stream.error != MAD_ERROR_NONE)
300 _state = MP3_STATE_EOS;
303 void MP3InputStream::readMP3Data() {
304 uint32 remaining = 0;
306 // Give up immediately if we already used up all data in the stream
307 if (_inStream->eos()) {
308 _state = MP3_STATE_EOS;
309 return;
312 if (_stream.next_frame) {
313 // If there is still data in the MAD stream, we need to preserve it.
314 // Note that we use memmove, as we are reusing the same buffer,
315 // and hence the data regions we copy from and to may overlap.
316 remaining = _stream.bufend - _stream.next_frame;
317 assert(remaining < BUFFER_SIZE); // Paranoia check
318 memmove(_buf, _stream.next_frame, remaining);
321 // Try to read the next block
322 uint32 size = _inStream->read(_buf + remaining, BUFFER_SIZE - remaining);
323 if (size <= 0) {
324 _state = MP3_STATE_EOS;
325 return;
328 // Feed the data we just read into the stream decoder
329 _stream.error = MAD_ERROR_NONE;
330 mad_stream_buffer(&_stream, _buf, size + remaining);
334 static inline int scale_sample(mad_fixed_t sample) {
335 // round
336 sample += (1L << (MAD_F_FRACBITS - 16));
338 // clip
339 if (sample > MAD_F_ONE - 1)
340 sample = MAD_F_ONE - 1;
341 else if (sample < -MAD_F_ONE)
342 sample = -MAD_F_ONE;
344 // quantize and scale to not saturate when mixing a lot of channels
345 return sample >> (MAD_F_FRACBITS + 1 - 16);
348 int MP3InputStream::readBuffer(int16 *buffer, const int numSamples) {
349 int samples = 0;
350 // Keep going as long as we have input available
351 while (samples < numSamples && _state != MP3_STATE_EOS) {
352 const int len = MIN(numSamples, samples + (int)(_synth.pcm.length - _posInFrame) * MAD_NCHANNELS(&_frame.header));
353 while (samples < len) {
354 *buffer++ = (int16)scale_sample(_synth.pcm.samples[0][_posInFrame]);
355 samples++;
356 if (MAD_NCHANNELS(&_frame.header) == 2) {
357 *buffer++ = (int16)scale_sample(_synth.pcm.samples[1][_posInFrame]);
358 samples++;
360 _posInFrame++;
362 if (_posInFrame >= _synth.pcm.length) {
363 // We used up all PCM data in the current frame -- read & decode more
364 decodeMP3Data();
367 return samples;
371 #pragma mark -
372 #pragma mark --- MP3 factory functions ---
373 #pragma mark -
376 AudioStream *makeMP3Stream(
377 Common::SeekableReadStream *stream,
378 bool disposeAfterUse,
379 uint32 startTime,
380 uint32 duration,
381 uint numLoops) {
383 mad_timer_t start;
384 mad_timer_t end;
386 // Both startTime and duration are given in milliseconds.
387 // Calculate the appropriate mad_timer_t values from them.
388 mad_timer_set(&start, startTime / 1000, startTime % 1000, 1000);
389 if (duration == 0) {
390 end = mad_timer_zero;
391 } else {
392 int endTime = startTime + duration;
393 mad_timer_set(&end, endTime / 1000, endTime % 1000, 1000);
396 return new MP3InputStream(stream, disposeAfterUse, start, end, numLoops);
399 } // End of namespace Audio
401 #endif // #ifdef USE_MAD