Move actors to the first frame on entering a room.
[scummvm-innocent.git] / sound / audiostream.cpp
blob61a2e778ab2eeacb080a6fcc791918c3edcc1c53
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 "common/debug.h"
27 #include "common/endian.h"
28 #include "common/file.h"
29 #include "common/list.h"
30 #include "common/util.h"
32 #include "sound/audiostream.h"
33 #include "sound/mixer.h"
34 #include "sound/mp3.h"
35 #include "sound/vorbis.h"
36 #include "sound/flac.h"
39 // This used to be an inline template function, but
40 // buggy template function handling in MSVC6 forced
41 // us to go with the macro approach. So far this is
42 // the only template function that MSVC6 seemed to
43 // compile incorrectly. Knock on wood.
44 #define READ_ENDIAN_SAMPLE(is16Bit, isUnsigned, ptr, isLE) \
45 ((is16Bit ? (isLE ? READ_LE_UINT16(ptr) : READ_BE_UINT16(ptr)) : (*ptr << 8)) ^ (isUnsigned ? 0x8000 : 0))
48 namespace Audio {
50 struct StreamFileFormat {
51 /** Decodername */
52 const char* decoderName;
53 const char* fileExtension;
54 /**
55 * Pointer to a function which tries to open a file of type StreamFormat.
56 * Return NULL in case of an error (invalid/nonexisting file).
58 AudioStream* (*openStreamFile)(Common::SeekableReadStream *stream, bool disposeAfterUse,
59 uint32 startTime, uint32 duration, uint numLoops);
62 static const StreamFileFormat STREAM_FILEFORMATS[] = {
63 /* decoderName, fileExt, openStreamFuntion */
64 #ifdef USE_FLAC
65 { "Flac", ".flac", makeFlacStream },
66 { "Flac", ".fla", makeFlacStream },
67 #endif
68 #ifdef USE_VORBIS
69 { "Ogg Vorbis", ".ogg", makeVorbisStream },
70 #endif
71 #ifdef USE_MAD
72 { "MPEG Layer 3", ".mp3", makeMP3Stream },
73 #endif
75 { NULL, NULL, NULL } // Terminator
78 AudioStream* AudioStream::openStreamFile(const Common::String &basename, uint32 startTime, uint32 duration, uint numLoops) {
79 AudioStream* stream = NULL;
80 Common::File *fileHandle = new Common::File();
82 for (int i = 0; i < ARRAYSIZE(STREAM_FILEFORMATS)-1 && stream == NULL; ++i) {
83 Common::String filename = basename + STREAM_FILEFORMATS[i].fileExtension;
84 fileHandle->open(filename);
85 if (fileHandle->isOpen()) {
86 // Create the stream object
87 stream = STREAM_FILEFORMATS[i].openStreamFile(fileHandle, true, startTime, duration, numLoops);
88 fileHandle = 0;
89 break;
93 delete fileHandle;
95 if (stream == NULL) {
96 debug(1, "AudioStream: Could not open compressed AudioFile %s", basename.c_str());
99 return stream;
102 #pragma mark -
103 #pragma mark --- LinearMemoryStream ---
104 #pragma mark -
106 inline int32 calculatePlayTime(int rate, int samples) {
107 int32 seconds = samples / rate;
108 int32 milliseconds = (1000 * (samples % rate)) / rate;
109 return seconds * 1000 + milliseconds;
113 * A simple raw audio stream, purely memory based. It operates on a single
114 * block of data, which is passed to it upon creation.
115 * Optionally supports looping the sound.
117 * Design note: This code tries to be as efficient as possible (without
118 * resorting to assembly, that is). To this end, it is written as a template
119 * class. This way the compiler can create optimized code for each special
120 * case. This results in a total of 12 versions of the code being generated.
122 template<bool stereo, bool is16Bit, bool isUnsigned, bool isLE>
123 class LinearMemoryStream : public AudioStream {
124 protected:
125 const byte *_ptr;
126 const byte *_end;
127 const byte *_loopPtr;
128 const byte *_loopEnd;
129 const int _rate;
130 const byte *_origPtr;
131 const int32 _playtime;
133 public:
134 LinearMemoryStream(int rate, const byte *ptr, uint len, uint loopOffset, uint loopLen, bool autoFreeMemory)
135 : _ptr(ptr), _end(ptr+len), _loopPtr(0), _loopEnd(0), _rate(rate), _playtime(calculatePlayTime(rate, len / (is16Bit ? 2 : 1) / (stereo ? 2 : 1))) {
137 if (loopLen) {
138 _loopPtr = _ptr + loopOffset;
139 _loopEnd = _loopPtr + loopLen;
142 _origPtr = autoFreeMemory ? ptr : 0;
144 virtual ~LinearMemoryStream() {
145 free(const_cast<byte *>(_origPtr));
147 int readBuffer(int16 *buffer, const int numSamples);
149 bool isStereo() const { return stereo; }
150 bool endOfData() const { return _ptr >= _end; }
152 int getRate() const { return _rate; }
153 int32 getTotalPlayTime() const { return _playtime; }
156 template<bool stereo, bool is16Bit, bool isUnsigned, bool isLE>
157 int LinearMemoryStream<stereo, is16Bit, isUnsigned, isLE>::readBuffer(int16 *buffer, const int numSamples) {
158 int samples = numSamples;
159 while (samples > 0 && _ptr < _end) {
160 int len = MIN(samples, (int)(_end - _ptr) / (is16Bit ? 2 : 1));
161 samples -= len;
162 do {
163 *buffer++ = READ_ENDIAN_SAMPLE(is16Bit, isUnsigned, _ptr, isLE);
164 _ptr += (is16Bit ? 2 : 1);
165 } while (--len);
166 // Loop, if looping was specified
167 if (_loopPtr && _ptr >= _end) {
168 _ptr = _loopPtr;
169 _end = _loopEnd;
172 return numSamples-samples;
176 #pragma mark -
177 #pragma mark --- Input stream factory ---
178 #pragma mark -
180 /* In the following, we use preprocessor / macro tricks to simplify the code
181 * which instantiates the input streams. We used to use template functions for
182 * this, but MSVC6 / EVC 3-4 (used for WinCE builds) are extremely buggy when it
183 * comes to this feature of C++... so as a compromise we use macros to cut down
184 * on the (source) code duplication a bit.
185 * So while normally macro tricks are said to make maintenance harder, in this
186 * particular case it should actually help it :-)
189 #define MAKE_LINEAR(STEREO, UNSIGNED) \
190 if (is16Bit) { \
191 if (isLE) \
192 return new LinearMemoryStream<STEREO, true, UNSIGNED, true>(rate, ptr, len, loopOffset, loopLen, autoFree); \
193 else \
194 return new LinearMemoryStream<STEREO, true, UNSIGNED, false>(rate, ptr, len, loopOffset, loopLen, autoFree); \
195 } else \
196 return new LinearMemoryStream<STEREO, false, UNSIGNED, false>(rate, ptr, len, loopOffset, loopLen, autoFree)
198 AudioStream *makeLinearInputStream(const byte *ptr, uint32 len, int rate, byte flags, uint loopStart, uint loopEnd) {
199 const bool isStereo = (flags & Audio::Mixer::FLAG_STEREO) != 0;
200 const bool is16Bit = (flags & Audio::Mixer::FLAG_16BITS) != 0;
201 const bool isUnsigned = (flags & Audio::Mixer::FLAG_UNSIGNED) != 0;
202 const bool isLE = (flags & Audio::Mixer::FLAG_LITTLE_ENDIAN) != 0;
203 const bool autoFree = (flags & Audio::Mixer::FLAG_AUTOFREE) != 0;
205 uint loopOffset = 0, loopLen = 0;
206 if (flags & Audio::Mixer::FLAG_LOOP) {
207 if (loopEnd == 0)
208 loopEnd = len;
209 assert(loopStart <= loopEnd);
210 assert(loopEnd <= len);
212 loopOffset = loopStart;
213 loopLen = loopEnd - loopStart;
216 // Verify the buffer sizes are sane
217 if (is16Bit && isStereo) {
218 assert((len & 3) == 0 && (loopLen & 3) == 0);
219 } else if (is16Bit || isStereo) {
220 assert((len & 1) == 0 && (loopLen & 1) == 0);
223 if (isStereo) {
224 if (isUnsigned) {
225 MAKE_LINEAR(true, true);
226 } else {
227 MAKE_LINEAR(true, false);
229 } else {
230 if (isUnsigned) {
231 MAKE_LINEAR(false, true);
232 } else {
233 MAKE_LINEAR(false, false);
239 #pragma mark -
240 #pragma mark --- Appendable audio stream ---
241 #pragma mark -
243 struct Buffer {
244 byte *start;
245 byte *end;
249 * Wrapped memory stream.
251 class BaseAppendableMemoryStream : public AppendableAudioStream {
252 protected:
254 // A mutex to avoid access problems (causing e.g. corruption of
255 // the linked list) in thread aware environments.
256 Common::Mutex _mutex;
258 // List of all queued buffers
259 Common::List<Buffer> _bufferQueue;
261 // Position in the front buffer, if any
262 bool _finalized;
263 const int _rate;
264 byte *_pos;
266 inline bool eosIntern() const { return _bufferQueue.empty(); };
267 public:
268 BaseAppendableMemoryStream(int rate);
269 ~BaseAppendableMemoryStream();
271 bool endOfStream() const { return _finalized && eosIntern(); }
272 bool endOfData() const { return eosIntern(); }
274 int getRate() const { return _rate; }
276 void finish() { _finalized = true; }
278 void queueBuffer(byte *data, uint32 size);
282 * Wrapped memory stream.
284 template<bool stereo, bool is16Bit, bool isUnsigned, bool isLE>
285 class AppendableMemoryStream : public BaseAppendableMemoryStream {
286 public:
287 AppendableMemoryStream(int rate) : BaseAppendableMemoryStream(rate) {}
289 bool isStereo() const { return stereo; }
291 int readBuffer(int16 *buffer, const int numSamples);
294 BaseAppendableMemoryStream::BaseAppendableMemoryStream(int rate)
295 : _finalized(false), _rate(rate), _pos(0) {
299 BaseAppendableMemoryStream::~BaseAppendableMemoryStream() {
300 // Clear the queue
301 Common::List<Buffer>::iterator iter;
302 for (iter = _bufferQueue.begin(); iter != _bufferQueue.end(); ++iter)
303 delete[] iter->start;
306 template<bool stereo, bool is16Bit, bool isUnsigned, bool isLE>
307 int AppendableMemoryStream<stereo, is16Bit, isUnsigned, isLE>::readBuffer(int16 *buffer, const int numSamples) {
308 Common::StackLock lock(_mutex);
310 int samples = numSamples;
311 while (samples > 0 && !eosIntern()) {
312 Buffer buf = *_bufferQueue.begin();
313 if (_pos == 0)
314 _pos = buf.start;
316 assert(buf.start <= _pos && _pos <= buf.end);
317 const int samplesLeftInCurBuffer = buf.end - _pos;
318 if (samplesLeftInCurBuffer == 0) {
319 delete[] buf.start;
320 _bufferQueue.erase(_bufferQueue.begin());
321 _pos = 0;
322 continue;
325 int len = MIN(samples, samplesLeftInCurBuffer / (is16Bit ? 2 : 1));
326 samples -= len;
327 do {
328 *buffer++ = READ_ENDIAN_SAMPLE(is16Bit, isUnsigned, _pos, isLE);
329 _pos += (is16Bit ? 2 : 1);
330 } while (--len);
333 return numSamples - samples;
336 void BaseAppendableMemoryStream::queueBuffer(byte *data, uint32 size) {
337 Common::StackLock lock(_mutex);
340 // Verify the buffer size is sane
341 if (is16Bit && stereo) {
342 assert((size & 3) == 0);
343 } else if (is16Bit || stereo) {
344 assert((size & 1) == 0);
347 // Verify that the stream has not yet been finalized (by a call to finish())
348 assert(!_finalized);
350 // Queue the buffer
351 Buffer buf = {data, data+size};
352 _bufferQueue.push_back(buf);
355 #if 0
356 // Output some stats
357 uint totalSize = 0;
358 Common::List<Buffer>::iterator iter;
359 for (iter = _bufferQueue.begin(); iter != _bufferQueue.end(); ++iter)
360 totalSize += iter->end - iter->start;
361 printf("AppendableMemoryStream::queueBuffer: added a %d byte buf, a total of %d bytes are queued\n",
362 size, totalSize);
363 #endif
367 #define MAKE_WRAPPED(STEREO, UNSIGNED) \
368 if (is16Bit) { \
369 if (isLE) \
370 return new AppendableMemoryStream<STEREO, true, UNSIGNED, true>(rate); \
371 else \
372 return new AppendableMemoryStream<STEREO, true, UNSIGNED, false>(rate); \
373 } else \
374 return new AppendableMemoryStream<STEREO, false, UNSIGNED, false>(rate)
376 AppendableAudioStream *makeAppendableAudioStream(int rate, byte _flags) {
377 const bool isStereo = (_flags & Audio::Mixer::FLAG_STEREO) != 0;
378 const bool is16Bit = (_flags & Audio::Mixer::FLAG_16BITS) != 0;
379 const bool isUnsigned = (_flags & Audio::Mixer::FLAG_UNSIGNED) != 0;
380 const bool isLE = (_flags & Audio::Mixer::FLAG_LITTLE_ENDIAN) != 0;
382 if (isStereo) {
383 if (isUnsigned) {
384 MAKE_WRAPPED(true, true);
385 } else {
386 MAKE_WRAPPED(true, false);
388 } else {
389 if (isUnsigned) {
390 MAKE_WRAPPED(false, true);
391 } else {
392 MAKE_WRAPPED(false, false);
398 } // End of namespace Audio