Only set interface palette when painting backdrop. (This fixes movie palette.)
[scummvm-innocent.git] / sound / flac.cpp
blobbb633b83520d532194fd1fe9d159a0d2d10a2bdc
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/flac.h"
28 #ifdef USE_FLAC
30 #include "common/debug.h"
31 #include "common/stream.h"
32 #include "common/util.h"
34 #include "sound/audiostream.h"
35 #include "sound/audiocd.h"
37 #define FLAC__NO_DLL // that MS-magic gave me headaches - just link the library you like
38 #include <FLAC/export.h>
41 // check if we have FLAC >= 1.1.3; LEGACY_FLAC code can be removed once FLAC-1.1.3 propagates everywhere
42 #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT < 8
43 #define LEGACY_FLAC
44 #else
45 #undef LEGACY_FLAC
46 #endif
49 #ifdef LEGACY_FLAC
51 // Before FLAC 1.1.3, we needed to use the stream decoder API.
52 #include <FLAC/seekable_stream_decoder.h>
53 typedef uint FLAC_size_t;
55 #else
57 // With FLAC 1.1.3, the stream decoder API was merged into the regular
58 // stream API. In order to stay compatible with older FLAC versions, we
59 // simply add some typedefs and #ifdefs to map between the old and new API.
60 // We use the typedefs (instead of only #defines) in order to somewhat
61 // improve the readability of the code.
63 #include <FLAC/stream_decoder.h>
64 typedef size_t FLAC_size_t;
65 // Add aliases for the old names
66 typedef FLAC__StreamDecoderState FLAC__SeekableStreamDecoderState;
67 typedef FLAC__StreamDecoderReadStatus FLAC__SeekableStreamDecoderReadStatus;
68 typedef FLAC__StreamDecoderSeekStatus FLAC__SeekableStreamDecoderSeekStatus;
69 typedef FLAC__StreamDecoderTellStatus FLAC__SeekableStreamDecoderTellStatus;
70 typedef FLAC__StreamDecoderLengthStatus FLAC__SeekableStreamDecoderLengthStatus;
71 typedef FLAC__StreamDecoder FLAC__SeekableStreamDecoder;
73 #endif
76 namespace Audio {
78 #pragma mark -
79 #pragma mark --- Flac stream ---
80 #pragma mark -
82 static const uint MAX_OUTPUT_CHANNELS = 2;
85 class FlacInputStream : public AudioStream {
86 protected:
87 Common::SeekableReadStream *_inStream;
88 bool _disposeAfterUse;
90 uint _numLoops;
92 ::FLAC__SeekableStreamDecoder *_decoder;
94 /** Header of the stream */
95 FLAC__StreamMetadata_StreamInfo _streaminfo;
97 /** index of the first sample to be played */
98 FLAC__uint64 _firstSample;
100 /** index + 1(!) of the last sample to be played - 0 is end of stream */
101 FLAC__uint64 _lastSample;
103 /** total play time */
104 int32 _totalPlayTime;
106 /** true if the last sample was decoded from the FLAC-API - there might still be data in the buffer */
107 bool _lastSampleWritten;
109 typedef int16 SampleType;
110 enum { BUFTYPE_BITS = 16 };
112 enum {
113 // Maximal buffer size. According to the FLAC format specification, the block size is
114 // a 16 bit value (in fact it seems the maximal block size is 32768, but we play it safe).
115 BUFFER_SIZE = 65536
118 struct {
119 SampleType bufData[BUFFER_SIZE];
120 SampleType *bufReadPos;
121 uint bufFill;
122 } _sampleCache;
124 SampleType *_outBuffer;
125 uint _requestedSamples;
127 typedef void (*PFCONVERTBUFFERS)(SampleType*, const FLAC__int32*[], uint, const uint, const uint8);
128 PFCONVERTBUFFERS _methodConvertBuffers;
131 public:
132 FlacInputStream(Common::SeekableReadStream *inStream, bool dispose, uint startTime = 0, uint endTime = 0, uint numLoops = 1);
133 virtual ~FlacInputStream();
135 int readBuffer(int16 *buffer, const int numSamples);
137 bool isStereo() const { return _streaminfo.channels >= 2; }
138 int getRate() const { return _streaminfo.sample_rate; }
139 bool endOfData() const {
140 // End of data is reached if there either is no valid stream data available,
141 // or if we reached the last sample and completely emptied the sample cache.
142 return _streaminfo.channels == 0 || (_lastSampleWritten && _sampleCache.bufFill == 0);
145 int32 getTotalPlayTime() const { return _totalPlayTime; }
147 bool isStreamDecoderReady() const { return getStreamDecoderState() == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC ; }
149 protected:
150 uint getChannels() const { return MIN<uint>(_streaminfo.channels, MAX_OUTPUT_CHANNELS); }
152 bool allocateBuffer(uint minSamples);
154 inline FLAC__StreamDecoderState getStreamDecoderState() const;
156 inline bool processSingleBlock();
157 inline bool processUntilEndOfMetadata();
158 bool seekAbsolute(FLAC__uint64 sample);
160 inline ::FLAC__SeekableStreamDecoderReadStatus callbackRead(FLAC__byte buffer[], FLAC_size_t *bytes);
161 inline ::FLAC__SeekableStreamDecoderSeekStatus callbackSeek(FLAC__uint64 absoluteByteOffset);
162 inline ::FLAC__SeekableStreamDecoderTellStatus callbackTell(FLAC__uint64 *absoluteByteOffset);
163 inline ::FLAC__SeekableStreamDecoderLengthStatus callbackLength(FLAC__uint64 *streamLength);
164 inline bool callbackEOF();
165 inline ::FLAC__StreamDecoderWriteStatus callbackWrite(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
166 inline void callbackMetadata(const ::FLAC__StreamMetadata *metadata);
167 inline void callbackError(::FLAC__StreamDecoderErrorStatus status);
169 private:
170 static ::FLAC__SeekableStreamDecoderReadStatus callWrapRead(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__byte buffer[], FLAC_size_t *bytes, void *clientData);
171 static ::FLAC__SeekableStreamDecoderSeekStatus callWrapSeek(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 absoluteByteOffset, void *clientData);
172 static ::FLAC__SeekableStreamDecoderTellStatus callWrapTell(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *absoluteByteOffset, void *clientData);
173 static ::FLAC__SeekableStreamDecoderLengthStatus callWrapLength(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *streamLength, void *clientData);
174 static FLAC__bool callWrapEOF(const ::FLAC__SeekableStreamDecoder *decoder, void *clientData);
175 static ::FLAC__StreamDecoderWriteStatus callWrapWrite(const ::FLAC__SeekableStreamDecoder *decoder, const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *clientData);
176 static void callWrapMetadata(const ::FLAC__SeekableStreamDecoder *decoder, const ::FLAC__StreamMetadata *metadata, void *clientData);
177 static void callWrapError(const ::FLAC__SeekableStreamDecoder *decoder, ::FLAC__StreamDecoderErrorStatus status, void *clientData);
179 void setBestConvertBufferMethod();
180 static void convertBuffersGeneric(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
181 static void convertBuffersStereoNS(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
182 static void convertBuffersStereo8Bit(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
183 static void convertBuffersMonoNS(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
184 static void convertBuffersMono8Bit(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
187 FlacInputStream::FlacInputStream(Common::SeekableReadStream *inStream, bool dispose, uint startTime, uint endTime, uint numLoops)
188 #ifdef LEGACY_FLAC
189 : _decoder(::FLAC__seekable_stream_decoder_new()),
190 #else
191 : _decoder(::FLAC__stream_decoder_new()),
192 #endif
193 _inStream(inStream),
194 _disposeAfterUse(dispose),
195 _numLoops(numLoops),
196 _firstSample(0), _lastSample(0),
197 _outBuffer(NULL), _requestedSamples(0), _lastSampleWritten(false),
198 _methodConvertBuffers(&FlacInputStream::convertBuffersGeneric)
200 assert(_inStream);
201 memset(&_streaminfo, 0, sizeof(_streaminfo));
203 _sampleCache.bufReadPos = NULL;
204 _sampleCache.bufFill = 0;
206 _methodConvertBuffers = &FlacInputStream::convertBuffersGeneric;
208 bool success;
209 #ifdef LEGACY_FLAC
210 ::FLAC__seekable_stream_decoder_set_read_callback(_decoder, &FlacInputStream::callWrapRead);
211 ::FLAC__seekable_stream_decoder_set_seek_callback(_decoder, &FlacInputStream::callWrapSeek);
212 ::FLAC__seekable_stream_decoder_set_tell_callback(_decoder, &FlacInputStream::callWrapTell);
213 ::FLAC__seekable_stream_decoder_set_length_callback(_decoder, &FlacInputStream::callWrapLength);
214 ::FLAC__seekable_stream_decoder_set_eof_callback(_decoder, &FlacInputStream::callWrapEOF);
215 ::FLAC__seekable_stream_decoder_set_write_callback(_decoder, &FlacInputStream::callWrapWrite);
216 ::FLAC__seekable_stream_decoder_set_metadata_callback(_decoder, &FlacInputStream::callWrapMetadata);
217 ::FLAC__seekable_stream_decoder_set_error_callback(_decoder, &FlacInputStream::callWrapError);
218 ::FLAC__seekable_stream_decoder_set_client_data(_decoder, (void*)this);
220 success = (::FLAC__seekable_stream_decoder_init(_decoder) == FLAC__SEEKABLE_STREAM_DECODER_OK);
221 #else
222 success = (::FLAC__stream_decoder_init_stream(
223 _decoder,
224 &FlacInputStream::callWrapRead,
225 &FlacInputStream::callWrapSeek,
226 &FlacInputStream::callWrapTell,
227 &FlacInputStream::callWrapLength,
228 &FlacInputStream::callWrapEOF,
229 &FlacInputStream::callWrapWrite,
230 &FlacInputStream::callWrapMetadata,
231 &FlacInputStream::callWrapError,
232 (void*)this
233 ) == FLAC__STREAM_DECODER_INIT_STATUS_OK);
234 #endif
235 if (success) {
236 if (processUntilEndOfMetadata() && _streaminfo.channels > 0) {
237 // Compute the start/end sample (we use floating point arithmetics here to
238 // avoid overflows).
239 _firstSample = (FLAC__uint64)(startTime * (_streaminfo.sample_rate / 1000.0));
240 _lastSample = (FLAC__uint64)(endTime * (_streaminfo.sample_rate / 1000.0));
242 if (_firstSample == 0 || seekAbsolute(_firstSample)) {
243 int32 samples = kUnknownPlayTime;
245 if (!_lastSample) {
246 if (_streaminfo.total_samples)
247 samples = _streaminfo.total_samples - _firstSample;
248 } else {
249 samples = _lastSample - _firstSample - 1;
252 if (samples != kUnknownPlayTime && samples >= 0 && numLoops) {
253 const int32 rate = _streaminfo.sample_rate;
255 int32 seconds = samples / rate;
256 int32 milliseconds = (1000 * (samples % rate)) / rate;
258 _totalPlayTime = (seconds * 1000 + milliseconds) * numLoops;
259 } else {
260 _totalPlayTime = kUnknownPlayTime;
263 return; // no error occured
268 warning("FlacInputStream: could not create audio stream");
271 FlacInputStream::~FlacInputStream() {
272 if (_decoder != NULL) {
273 #ifdef LEGACY_FLAC
274 (void) ::FLAC__seekable_stream_decoder_finish(_decoder);
275 ::FLAC__seekable_stream_decoder_delete(_decoder);
276 #else
277 (void) ::FLAC__stream_decoder_finish(_decoder);
278 ::FLAC__stream_decoder_delete(_decoder);
279 #endif
281 if (_disposeAfterUse)
282 delete _inStream;
285 inline FLAC__StreamDecoderState FlacInputStream::getStreamDecoderState() const {
286 assert(_decoder != NULL);
287 #ifdef LEGACY_FLAC
288 return ::FLAC__seekable_stream_decoder_get_stream_decoder_state(_decoder);
289 #else
290 return ::FLAC__stream_decoder_get_state(_decoder);
291 #endif
294 inline bool FlacInputStream::processSingleBlock() {
295 assert(_decoder != NULL);
296 #ifdef LEGACY_FLAC
297 return 0 != ::FLAC__seekable_stream_decoder_process_single(_decoder);
298 #else
299 return 0 != ::FLAC__stream_decoder_process_single(_decoder);
300 #endif
303 inline bool FlacInputStream::processUntilEndOfMetadata() {
304 assert(_decoder != NULL);
305 #ifdef LEGACY_FLAC
306 return 0 != ::FLAC__seekable_stream_decoder_process_until_end_of_metadata(_decoder);
307 #else
308 return 0 != ::FLAC__stream_decoder_process_until_end_of_metadata(_decoder);
309 #endif
312 bool FlacInputStream::seekAbsolute(FLAC__uint64 sample) {
313 assert(_decoder != NULL);
314 #ifdef LEGACY_FLAC
315 const bool result = (0 != ::FLAC__seekable_stream_decoder_seek_absolute(_decoder, sample));
316 #else
317 const bool result = (0 != ::FLAC__stream_decoder_seek_absolute(_decoder, sample));
318 #endif
319 if (result) {
320 _lastSampleWritten = (_lastSample != 0 && sample >= _lastSample); // only set if we are SURE
322 return result;
325 int FlacInputStream::readBuffer(int16 *buffer, const int numSamples) {
326 const uint numChannels = getChannels();
328 if (numChannels == 0) {
329 warning("FlacInputStream: Stream not sucessfully initialised, cant playback");
330 return -1; // streaminfo wasnt read!
333 assert(numSamples % numChannels == 0); // must be multiple of channels!
334 assert(buffer != NULL);
335 assert(_outBuffer == NULL);
336 assert(_requestedSamples == 0);
338 _outBuffer = buffer;
339 _requestedSamples = numSamples;
341 // If there is still data in our buffer from the last time around,
342 // copy that first.
343 if (_sampleCache.bufFill > 0) {
344 assert(_sampleCache.bufReadPos >= _sampleCache.bufData);
345 assert(_sampleCache.bufFill % numChannels == 0);
347 const uint copySamples = MIN((uint)numSamples, _sampleCache.bufFill);
348 memcpy(buffer, _sampleCache.bufReadPos, copySamples*sizeof(buffer[0]));
350 _outBuffer = buffer + copySamples;
351 _requestedSamples = numSamples - copySamples;
352 _sampleCache.bufReadPos += copySamples;
353 _sampleCache.bufFill -= copySamples;
356 bool decoderOk = true;
358 FLAC__StreamDecoderState state = getStreamDecoderState();
360 // Keep poking FLAC to process more samples until we completely satisfied the request
361 // respectively until we run out of data.
362 while (!_lastSampleWritten && _requestedSamples > 0 && state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) {
363 assert(_sampleCache.bufFill == 0);
364 assert(_requestedSamples % numChannels == 0);
365 processSingleBlock();
366 state = getStreamDecoderState();
368 if (state == FLAC__STREAM_DECODER_END_OF_STREAM) {
369 _lastSampleWritten = true;
372 // If we reached the end of the stream, and looping is enabled: Try to rewind
373 if (_lastSampleWritten && _numLoops != 1) {
374 if (_numLoops != 0)
375 _numLoops--;
376 seekAbsolute(_firstSample);
377 state = getStreamDecoderState();
381 // Error handling
382 switch (state) {
383 case FLAC__STREAM_DECODER_END_OF_STREAM:
384 _lastSampleWritten = true;
385 break;
386 case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
387 break;
388 default:
389 decoderOk = false;
390 warning("FlacInputStream: An error occured while decoding. DecoderState is: %s",
391 FLAC__StreamDecoderStateString[getStreamDecoderState()]);
394 // Compute how many samples we actually produced
395 const int samples = (int)(_outBuffer - buffer);
396 assert(samples % numChannels == 0);
398 _outBuffer = NULL; // basically unnecessary, only for the purpose of the asserts
399 _requestedSamples = 0; // basically unnecessary, only for the purpose of the asserts
401 return decoderOk ? samples : -1;
404 inline ::FLAC__SeekableStreamDecoderReadStatus FlacInputStream::callbackRead(FLAC__byte buffer[], FLAC_size_t *bytes) {
405 if (*bytes == 0) {
406 #ifdef LEGACY_FLAC
407 return FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_ERROR; /* abort to avoid a deadlock */
408 #else
409 return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
410 #endif
413 const uint32 bytesRead = _inStream->read(buffer, *bytes);
415 if (bytesRead == 0) {
416 #ifdef LEGACY_FLAC
417 return _inStream->eos() ? FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK : FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_ERROR;
418 #else
419 return _inStream->eos() ? FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM : FLAC__STREAM_DECODER_READ_STATUS_ABORT;
420 #endif
423 *bytes = static_cast<uint>(bytesRead);
424 #ifdef LEGACY_FLAC
425 return FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK;
426 #else
427 return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
428 #endif
431 void FlacInputStream::setBestConvertBufferMethod() {
432 PFCONVERTBUFFERS tempMethod = &FlacInputStream::convertBuffersGeneric;
434 const uint numChannels = getChannels();
435 const uint8 numBits = (uint8)_streaminfo.bits_per_sample;
437 assert(numChannels >= 1);
438 assert(numBits >= 4 && numBits <=32);
440 if (numChannels == 1) {
441 if (numBits == 8)
442 tempMethod = &FlacInputStream::convertBuffersMono8Bit;
443 if (numBits == BUFTYPE_BITS)
444 tempMethod = &FlacInputStream::convertBuffersMonoNS;
445 } else if (numChannels == 2) {
446 if (numBits == 8)
447 tempMethod = &FlacInputStream::convertBuffersStereo8Bit;
448 if (numBits == BUFTYPE_BITS)
449 tempMethod = &FlacInputStream::convertBuffersStereoNS;
450 } /* else ... */
452 _methodConvertBuffers = tempMethod;
455 // 1 channel, no scaling
456 void FlacInputStream::convertBuffersMonoNS(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
457 assert(numChannels == 1);
458 assert(numBits == BUFTYPE_BITS);
460 FLAC__int32 const* inChannel1 = inChannels[0];
462 while (numSamples >= 4) {
463 bufDestination[0] = static_cast<SampleType>(inChannel1[0]);
464 bufDestination[1] = static_cast<SampleType>(inChannel1[1]);
465 bufDestination[2] = static_cast<SampleType>(inChannel1[2]);
466 bufDestination[3] = static_cast<SampleType>(inChannel1[3]);
467 bufDestination += 4;
468 inChannel1 += 4;
469 numSamples -= 4;
472 for (; numSamples > 0; --numSamples) {
473 *bufDestination++ = static_cast<SampleType>(*inChannel1++);
476 inChannels[0] = inChannel1;
477 assert(numSamples == 0); // dint copy too many samples
480 // 1 channel, scaling from 8Bit
481 void FlacInputStream::convertBuffersMono8Bit(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
482 assert(numChannels == 1);
483 assert(numBits == 8);
484 assert(8 < BUFTYPE_BITS);
486 FLAC__int32 const* inChannel1 = inChannels[0];
488 while (numSamples >= 4) {
489 bufDestination[0] = static_cast<SampleType>(inChannel1[0]) << (BUFTYPE_BITS - 8);
490 bufDestination[1] = static_cast<SampleType>(inChannel1[1]) << (BUFTYPE_BITS - 8);
491 bufDestination[2] = static_cast<SampleType>(inChannel1[2]) << (BUFTYPE_BITS - 8);
492 bufDestination[3] = static_cast<SampleType>(inChannel1[3]) << (BUFTYPE_BITS - 8);
493 bufDestination += 4;
494 inChannel1 += 4;
495 numSamples -= 4;
498 for (; numSamples > 0; --numSamples) {
499 *bufDestination++ = static_cast<SampleType>(*inChannel1++) << (BUFTYPE_BITS - 8);
502 inChannels[0] = inChannel1;
503 assert(numSamples == 0); // dint copy too many samples
506 // 2 channels, no scaling
507 void FlacInputStream::convertBuffersStereoNS(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
508 assert(numChannels == 2);
509 assert(numBits == BUFTYPE_BITS);
510 assert(numSamples % 2 == 0); // must be integral multiply of channels
513 FLAC__int32 const* inChannel1 = inChannels[0]; // Left Channel
514 FLAC__int32 const* inChannel2 = inChannels[1]; // Right Channel
516 while (numSamples >= 2*2) {
517 bufDestination[0] = static_cast<SampleType>(inChannel1[0]);
518 bufDestination[1] = static_cast<SampleType>(inChannel2[0]);
519 bufDestination[2] = static_cast<SampleType>(inChannel1[1]);
520 bufDestination[3] = static_cast<SampleType>(inChannel2[1]);
521 bufDestination += 2 * 2;
522 inChannel1 += 2;
523 inChannel2 += 2;
524 numSamples -= 2 * 2;
527 while (numSamples > 0) {
528 bufDestination[0] = static_cast<SampleType>(*inChannel1++);
529 bufDestination[1] = static_cast<SampleType>(*inChannel2++);
530 bufDestination += 2;
531 numSamples -= 2;
534 inChannels[0] = inChannel1;
535 inChannels[1] = inChannel2;
536 assert(numSamples == 0); // dint copy too many samples
539 // 2 channels, scaling from 8Bit
540 void FlacInputStream::convertBuffersStereo8Bit(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
541 assert(numChannels == 2);
542 assert(numBits == 8);
543 assert(numSamples % 2 == 0); // must be integral multiply of channels
544 assert(8 < BUFTYPE_BITS);
546 FLAC__int32 const* inChannel1 = inChannels[0]; // Left Channel
547 FLAC__int32 const* inChannel2 = inChannels[1]; // Right Channel
549 while (numSamples >= 2*2) {
550 bufDestination[0] = static_cast<SampleType>(inChannel1[0]) << (BUFTYPE_BITS - 8);
551 bufDestination[1] = static_cast<SampleType>(inChannel2[0]) << (BUFTYPE_BITS - 8);
552 bufDestination[2] = static_cast<SampleType>(inChannel1[1]) << (BUFTYPE_BITS - 8);
553 bufDestination[3] = static_cast<SampleType>(inChannel2[1]) << (BUFTYPE_BITS - 8);
554 bufDestination += 2 * 2;
555 inChannel1 += 2;
556 inChannel2 += 2;
557 numSamples -= 2 * 2;
560 while (numSamples > 0) {
561 bufDestination[0] = static_cast<SampleType>(*inChannel1++) << (BUFTYPE_BITS - 8);
562 bufDestination[1] = static_cast<SampleType>(*inChannel2++) << (BUFTYPE_BITS - 8);
563 bufDestination += 2;
564 numSamples -= 2;
567 inChannels[0] = inChannel1;
568 inChannels[1] = inChannel2;
569 assert(numSamples == 0); // dint copy too many samples
572 // all Purpose-conversion - slowest of em all
573 void FlacInputStream::convertBuffersGeneric(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
574 assert(numSamples % numChannels == 0); // must be integral multiply of channels
576 if (numBits < BUFTYPE_BITS) {
577 const uint8 kPower = (uint8)(BUFTYPE_BITS - numBits);
579 for (; numSamples > 0; numSamples -= numChannels) {
580 for (uint i = 0; i < numChannels; ++i)
581 *bufDestination++ = static_cast<SampleType>(*(inChannels[i]++)) << kPower;
583 } else if (numBits > BUFTYPE_BITS) {
584 const uint8 kPower = (uint8)(numBits - BUFTYPE_BITS);
586 for (; numSamples > 0; numSamples -= numChannels) {
587 for (uint i = 0; i < numChannels; ++i)
588 *bufDestination++ = static_cast<SampleType>(*(inChannels[i]++) >> kPower) ;
590 } else {
591 for (; numSamples > 0; numSamples -= numChannels) {
592 for (uint i = 0; i < numChannels; ++i)
593 *bufDestination++ = static_cast<SampleType>(*(inChannels[i]++));
597 assert(numSamples == 0); // dint copy too many samples
600 inline ::FLAC__StreamDecoderWriteStatus FlacInputStream::callbackWrite(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]) {
601 assert(frame->header.channels == _streaminfo.channels);
602 assert(frame->header.sample_rate == _streaminfo.sample_rate);
603 assert(frame->header.bits_per_sample == _streaminfo.bits_per_sample);
604 assert(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER || _streaminfo.min_blocksize == _streaminfo.max_blocksize);
606 // We require that either the sample cache is empty, or that no samples were requested
607 assert(_sampleCache.bufFill == 0 || _requestedSamples == 0);
609 uint numSamples = frame->header.blocksize;
610 const uint numChannels = getChannels();
611 const uint8 numBits = (uint8)_streaminfo.bits_per_sample;
613 assert(_requestedSamples % numChannels == 0); // must be integral multiply of channels
615 const FLAC__uint64 firstSampleNumber = (frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER) ?
616 frame->header.number.sample_number : (static_cast<FLAC__uint64>(frame->header.number.frame_number)) * _streaminfo.max_blocksize;
618 // Check whether we are about to reach beyond the last sample we are supposed to play.
619 if (_lastSample != 0 && firstSampleNumber + numSamples >= _lastSample) {
620 numSamples = (uint)(firstSampleNumber >= _lastSample ? 0 : _lastSample - firstSampleNumber);
621 _lastSampleWritten = true;
624 // The value in _requestedSamples counts raw samples, so if there are more than one
625 // channel, we have to multiply the number of available sample "pairs" by numChannels
626 numSamples *= numChannels;
628 const FLAC__int32 *inChannels[MAX_OUTPUT_CHANNELS];
629 for (uint i = 0; i < numChannels; ++i)
630 inChannels[i] = buffer[i];
632 // write the incoming samples directly into the buffer provided to us by the mixer
633 if (_requestedSamples > 0) {
634 assert(_requestedSamples % numChannels == 0);
635 assert(_outBuffer != NULL);
637 // Copy & convert the available samples (limited both by how many we have available, and
638 // by how many are actually needed).
639 const uint copySamples = MIN(_requestedSamples, numSamples);
640 (*_methodConvertBuffers)(_outBuffer, inChannels, copySamples, numChannels, numBits);
642 _requestedSamples -= copySamples;
643 numSamples -= copySamples;
644 _outBuffer += copySamples;
647 // Write all remaining samples (i.e. those which didn't fit into the mixer buffer)
648 // into the sample cache.
649 if (_sampleCache.bufFill == 0)
650 _sampleCache.bufReadPos = _sampleCache.bufData;
651 const uint cacheSpace = (_sampleCache.bufData + BUFFER_SIZE) - (_sampleCache.bufReadPos + _sampleCache.bufFill);
652 assert(numSamples <= cacheSpace);
653 (*_methodConvertBuffers)(_sampleCache.bufReadPos + _sampleCache.bufFill, inChannels, numSamples, numChannels, numBits);
655 _sampleCache.bufFill += numSamples;
657 return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
660 inline ::FLAC__SeekableStreamDecoderSeekStatus FlacInputStream::callbackSeek(FLAC__uint64 absoluteByteOffset) {
661 _inStream->seek(absoluteByteOffset, SEEK_SET);
662 const bool result = (absoluteByteOffset == (FLAC__uint64)_inStream->pos());
664 #ifdef LEGACY_FLAC
665 return result ? FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK : FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_ERROR;
666 #else
667 return result ? FLAC__STREAM_DECODER_SEEK_STATUS_OK : FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
668 #endif
671 inline ::FLAC__SeekableStreamDecoderTellStatus FlacInputStream::callbackTell(FLAC__uint64 *absoluteByteOffset) {
672 *absoluteByteOffset = static_cast<FLAC__uint64>(_inStream->pos());
673 #ifdef LEGACY_FLAC
674 return FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK;
675 #else
676 return FLAC__STREAM_DECODER_TELL_STATUS_OK;
677 #endif
680 inline ::FLAC__SeekableStreamDecoderLengthStatus FlacInputStream::callbackLength(FLAC__uint64 *streamLength) {
681 *streamLength = static_cast<FLAC__uint64>(_inStream->size());
682 #ifdef LEGACY_FLAC
683 return FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK;
684 #else
685 return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
686 #endif
689 inline bool FlacInputStream::callbackEOF() {
690 return _inStream->eos();
694 inline void FlacInputStream::callbackMetadata(const ::FLAC__StreamMetadata *metadata) {
695 assert(_decoder != NULL);
696 assert(metadata->type == FLAC__METADATA_TYPE_STREAMINFO); // others arent really interesting
698 _streaminfo = metadata->data.stream_info;
699 setBestConvertBufferMethod(); // should be set after getting stream-information. FLAC always parses the info first
701 inline void FlacInputStream::callbackError(::FLAC__StreamDecoderErrorStatus status) {
702 // some of these are non-critical-Errors
703 debug(1, "FlacInputStream: An error occured while decoding. DecoderState is: %s",
704 FLAC__StreamDecoderErrorStatusString[status]);
707 /* Static Callback Wrappers */
708 ::FLAC__SeekableStreamDecoderReadStatus FlacInputStream::callWrapRead(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__byte buffer[], FLAC_size_t *bytes, void *clientData) {
709 FlacInputStream *instance = (FlacInputStream *)clientData;
710 assert(0 != instance);
711 return instance->callbackRead(buffer, bytes);
714 ::FLAC__SeekableStreamDecoderSeekStatus FlacInputStream::callWrapSeek(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 absoluteByteOffset, void *clientData) {
715 FlacInputStream *instance = (FlacInputStream *)clientData;
716 assert(0 != instance);
717 return instance->callbackSeek(absoluteByteOffset);
720 ::FLAC__SeekableStreamDecoderTellStatus FlacInputStream::callWrapTell(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *absoluteByteOffset, void *clientData) {
721 FlacInputStream *instance = (FlacInputStream *)clientData;
722 assert(0 != instance);
723 return instance->callbackTell(absoluteByteOffset);
726 ::FLAC__SeekableStreamDecoderLengthStatus FlacInputStream::callWrapLength(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *streamLength, void *clientData) {
727 FlacInputStream *instance = (FlacInputStream *)clientData;
728 assert(0 != instance);
729 return instance->callbackLength(streamLength);
732 FLAC__bool FlacInputStream::callWrapEOF(const ::FLAC__SeekableStreamDecoder *decoder, void *clientData) {
733 FlacInputStream *instance = (FlacInputStream *)clientData;
734 assert(0 != instance);
735 return instance->callbackEOF();
738 ::FLAC__StreamDecoderWriteStatus FlacInputStream::callWrapWrite(const ::FLAC__SeekableStreamDecoder *decoder, const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *clientData) {
739 FlacInputStream *instance = (FlacInputStream *)clientData;
740 assert(0 != instance);
741 return instance->callbackWrite(frame, buffer);
744 void FlacInputStream::callWrapMetadata(const ::FLAC__SeekableStreamDecoder *decoder, const ::FLAC__StreamMetadata *metadata, void *clientData) {
745 FlacInputStream *instance = (FlacInputStream *)clientData;
746 assert(0 != instance);
747 instance->callbackMetadata(metadata);
750 void FlacInputStream::callWrapError(const ::FLAC__SeekableStreamDecoder *decoder, ::FLAC__StreamDecoderErrorStatus status, void *clientData) {
751 FlacInputStream *instance = (FlacInputStream *)clientData;
752 assert(0 != instance);
753 instance->callbackError(status);
757 #pragma mark -
758 #pragma mark --- Flac factory functions ---
759 #pragma mark -
762 AudioStream *makeFlacStream(
763 Common::SeekableReadStream *stream,
764 bool disposeAfterUse,
765 uint32 startTime,
766 uint32 duration,
767 uint numLoops) {
769 uint32 endTime = duration ? (startTime + duration) : 0;
771 FlacInputStream *input = new FlacInputStream(stream, disposeAfterUse, startTime, endTime, numLoops);
772 if (!input->isStreamDecoderReady()) {
773 delete input;
774 return 0;
776 return input;
779 } // End of namespace Audio
781 #endif // #ifdef USE_FLAC