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.
26 #include "sound/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"
44 #pragma mark --- MP3 (MAD) stream ---
48 class MP3InputStream
: public AudioStream
{
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
;
63 const mad_timer_t _startTime
;
64 const mad_timer_t _endTime
;
65 mad_timer_t _totalTime
;
74 BUFFER_SIZE
= 5 * 8192
77 // This buffer contains a slab of input data
78 byte _buf
[BUFFER_SIZE
+ MAD_BUFFER_GUARD
];
81 MP3InputStream(Common::SeekableReadStream
*inStream
,
83 mad_timer_t start
= mad_timer_zero
,
84 mad_timer_t end
= mad_timer_zero
,
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
; }
100 MP3InputStream::MP3InputStream(Common::SeekableReadStream
*inStream
, bool dispose
, mad_timer_t start
, mad_timer_t end
, uint numLoops
) :
102 _disposeAfterUse(dispose
),
105 _state(MP3_STATE_INIT
),
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
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
);
128 mad_stream_init(&_stream
);
129 mad_frame_init(&_frame
);
131 // Reset the stream data
132 _inStream
->seek(0, SEEK_SET
);
135 _state
= MP3_STATE_READY
;
137 // Read the first few sample bytes
141 // If necessary, load more data into the stream decoder
142 if (_stream
.error
== MAD_ERROR_BUFLEN
)
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
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
));
158 warning("MP3InputStream: Unrecoverable error in mad_header_decode (%s)", mad_stream_errorstr(&_stream
));
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
);
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
;
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.
190 MP3InputStream::~MP3InputStream() {
191 if (_state
!= MP3_STATE_INIT
) {
193 mad_synth_finish(&_synth
);
194 mad_frame_finish(&_frame
);
195 mad_stream_finish(&_stream
);
198 if (_disposeAfterUse
)
202 void MP3InputStream::decodeMP3Data() {
205 if (_state
== MP3_STATE_INIT
) {
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
;
217 _state
= MP3_STATE_READY
;
219 // Read the first few sample bytes
223 if (_state
== MP3_STATE_EOS
)
226 // If necessary, load more data into the stream decoder
227 if (_stream
.error
== MAD_ERROR_BUFLEN
)
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
));
243 warning("MP3InputStream: Unrecoverable error in mad_header_decode (%s)", mad_stream_errorstr(&_stream
));
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)
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
;
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")
269 debug(6, "MP3InputStream: Recoverable error in mad_frame_decode (%s)", mad_stream_errorstr(&_stream
));
272 warning("MP3InputStream: Unrecoverable error in mad_frame_decode (%s)", mad_stream_errorstr(&_stream
));
277 // Synthesize PCM data
278 mad_synth_frame(&_synth
, &_frame
);
283 if (_state
== MP3_STATE_EOS
&& _numLoops
!= 1) {
284 // If looping is on and there are loops left, rewind to the start
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
;
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
);
324 _state
= MP3_STATE_EOS
;
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
) {
336 sample
+= (1L << (MAD_F_FRACBITS
- 16));
339 if (sample
> MAD_F_ONE
- 1)
340 sample
= MAD_F_ONE
- 1;
341 else if (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
) {
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
]);
356 if (MAD_NCHANNELS(&_frame
.header
) == 2) {
357 *buffer
++ = (int16
)scale_sample(_synth
.pcm
.samples
[1][_posInFrame
]);
362 if (_posInFrame
>= _synth
.pcm
.length
) {
363 // We used up all PCM data in the current frame -- read & decode more
372 #pragma mark --- MP3 factory functions ---
376 AudioStream
*makeMP3Stream(
377 Common::SeekableReadStream
*stream
,
378 bool disposeAfterUse
,
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);
390 end
= mad_timer_zero
;
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