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

flac.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 // Disable symbol overrides for FILE as that is used in FLAC headers
00024 #define FORBIDDEN_SYMBOL_EXCEPTION_FILE
00025 
00026 #include "audio/decoders/flac.h"
00027 
00028 #ifdef USE_FLAC
00029 
00030 #include "common/debug.h"
00031 #include "common/stream.h"
00032 #include "common/textconsole.h"
00033 #include "common/util.h"
00034 
00035 #include "audio/audiostream.h"
00036 
00037 #define FLAC__NO_DLL // that MS-magic gave me headaches - just link the library you like
00038 #include <FLAC/export.h>
00039 
00040 
00041 // check if we have FLAC >= 1.1.3; LEGACY_FLAC code can be removed once FLAC-1.1.3 propagates everywhere
00042 #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT < 8
00043 #define LEGACY_FLAC
00044 #else
00045 #undef LEGACY_FLAC
00046 #endif
00047 
00048 
00049 #ifdef LEGACY_FLAC
00050 
00051 // Before FLAC 1.1.3, we needed to use the stream decoder API.
00052 #include <FLAC/seekable_stream_decoder.h>
00053 typedef uint FLAC_size_t;
00054 
00055 #else
00056 
00057 // With FLAC 1.1.3, the stream decoder API was merged into the regular
00058 // stream API. In order to stay compatible with older FLAC versions, we
00059 // simply add some typedefs and #ifdefs to map between the old and new API.
00060 // We use the typedefs (instead of only #defines) in order to somewhat
00061 // improve the readability of the code.
00062 
00063 #include <FLAC/stream_decoder.h>
00064 typedef size_t FLAC_size_t;
00065 // Add aliases for the old names
00066 typedef FLAC__StreamDecoderState FLAC__SeekableStreamDecoderState;
00067 typedef FLAC__StreamDecoderReadStatus FLAC__SeekableStreamDecoderReadStatus;
00068 typedef FLAC__StreamDecoderSeekStatus FLAC__SeekableStreamDecoderSeekStatus;
00069 typedef FLAC__StreamDecoderTellStatus FLAC__SeekableStreamDecoderTellStatus;
00070 typedef FLAC__StreamDecoderLengthStatus FLAC__SeekableStreamDecoderLengthStatus;
00071 typedef FLAC__StreamDecoder FLAC__SeekableStreamDecoder;
00072 
00073 #endif
00074 
00075 
00076 namespace Audio {
00077 
00078 #pragma mark -
00079 #pragma mark --- FLAC stream ---
00080 #pragma mark -
00081 
00082 static const uint MAX_OUTPUT_CHANNELS = 2;
00083 
00084 
00085 class FLACStream : public SeekableAudioStream {
00086 protected:
00087     Common::SeekableReadStream *_inStream;
00088     bool _disposeAfterUse;
00089 
00090     ::FLAC__SeekableStreamDecoder *_decoder;
00091 
00093     FLAC__StreamMetadata_StreamInfo _streaminfo;
00094 
00096     FLAC__uint64 _lastSample;
00097 
00099     Timestamp _length;
00100 
00102     bool _lastSampleWritten;
00103 
00104     typedef int16 SampleType;
00105     enum { BUFTYPE_BITS = 16 };
00106 
00107     enum {
00108         // Maximal buffer size. According to the FLAC format specification, the  block size is
00109         // a 16 bit value (in fact it seems the maximal block size is 32768, but we play it safe).
00110         BUFFER_SIZE = 65536
00111     };
00112 
00113     struct {
00114         SampleType bufData[BUFFER_SIZE];
00115         SampleType *bufReadPos;
00116         uint bufFill;
00117     } _sampleCache;
00118 
00119     SampleType *_outBuffer;
00120     uint _requestedSamples;
00121 
00122     typedef void (*PFCONVERTBUFFERS)(SampleType*, const FLAC__int32*[], uint, const uint, const uint8);
00123     PFCONVERTBUFFERS _methodConvertBuffers;
00124 
00125 
00126 public:
00127     FLACStream(Common::SeekableReadStream *inStream, bool dispose);
00128     virtual ~FLACStream();
00129 
00130     int readBuffer(int16 *buffer, const int numSamples);
00131 
00132     bool isStereo() const { return _streaminfo.channels >= 2; }
00133     int getRate() const { return _streaminfo.sample_rate; }
00134     bool endOfData() const {
00135         // End of data is reached if there either is no valid stream data available,
00136         // or if we reached the last sample and completely emptied the sample cache.
00137         return _streaminfo.channels == 0 || (_lastSampleWritten && _sampleCache.bufFill == 0);
00138     }
00139 
00140     bool seek(const Timestamp &where);
00141     Timestamp getLength() const { return _length; }
00142 
00143     bool isStreamDecoderReady() const { return getStreamDecoderState() == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; }
00144 protected:
00145     uint getChannels() const { return MIN<uint>(_streaminfo.channels, MAX_OUTPUT_CHANNELS); }
00146 
00147     bool allocateBuffer(uint minSamples);
00148 
00149     inline FLAC__StreamDecoderState getStreamDecoderState() const;
00150 
00151     inline bool processSingleBlock();
00152     inline bool processUntilEndOfMetadata();
00153     bool seekAbsolute(FLAC__uint64 sample);
00154 
00155     inline ::FLAC__SeekableStreamDecoderReadStatus callbackRead(FLAC__byte buffer[], FLAC_size_t *bytes);
00156     inline ::FLAC__SeekableStreamDecoderSeekStatus callbackSeek(FLAC__uint64 absoluteByteOffset);
00157     inline ::FLAC__SeekableStreamDecoderTellStatus callbackTell(FLAC__uint64 *absoluteByteOffset);
00158     inline ::FLAC__SeekableStreamDecoderLengthStatus callbackLength(FLAC__uint64 *streamLength);
00159     inline bool callbackEOF();
00160     inline ::FLAC__StreamDecoderWriteStatus callbackWrite(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
00161     inline void callbackMetadata(const ::FLAC__StreamMetadata *metadata);
00162     inline void callbackError(::FLAC__StreamDecoderErrorStatus status);
00163 
00164 private:
00165     static ::FLAC__SeekableStreamDecoderReadStatus callWrapRead(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__byte buffer[], FLAC_size_t *bytes, void *clientData);
00166     static ::FLAC__SeekableStreamDecoderSeekStatus callWrapSeek(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 absoluteByteOffset, void *clientData);
00167     static ::FLAC__SeekableStreamDecoderTellStatus callWrapTell(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *absoluteByteOffset, void *clientData);
00168     static ::FLAC__SeekableStreamDecoderLengthStatus callWrapLength(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *streamLength, void *clientData);
00169     static FLAC__bool callWrapEOF(const ::FLAC__SeekableStreamDecoder *decoder, void *clientData);
00170     static ::FLAC__StreamDecoderWriteStatus callWrapWrite(const ::FLAC__SeekableStreamDecoder *decoder, const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *clientData);
00171     static void callWrapMetadata(const ::FLAC__SeekableStreamDecoder *decoder, const ::FLAC__StreamMetadata *metadata, void *clientData);
00172     static void callWrapError(const ::FLAC__SeekableStreamDecoder *decoder, ::FLAC__StreamDecoderErrorStatus status, void *clientData);
00173 
00174     void setBestConvertBufferMethod();
00175     static void convertBuffersGeneric(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
00176     static void convertBuffersStereoNS(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
00177     static void convertBuffersStereo8Bit(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
00178     static void convertBuffersMonoNS(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
00179     static void convertBuffersMono8Bit(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
00180 };
00181 
00182 FLACStream::FLACStream(Common::SeekableReadStream *inStream, bool dispose)
00183 #ifdef LEGACY_FLAC
00184             :   _decoder(::FLAC__seekable_stream_decoder_new()),
00185 #else
00186             :   _decoder(::FLAC__stream_decoder_new()),
00187 #endif
00188         _inStream(inStream),
00189         _disposeAfterUse(dispose),
00190         _length(0, 1000), _lastSample(0),
00191         _outBuffer(NULL), _requestedSamples(0), _lastSampleWritten(false),
00192         _methodConvertBuffers(&FLACStream::convertBuffersGeneric)
00193 {
00194     assert(_inStream);
00195     memset(&_streaminfo, 0, sizeof(_streaminfo));
00196 
00197     _sampleCache.bufReadPos = NULL;
00198     _sampleCache.bufFill = 0;
00199 
00200     _methodConvertBuffers = &FLACStream::convertBuffersGeneric;
00201 
00202     bool success;
00203 #ifdef LEGACY_FLAC
00204     ::FLAC__seekable_stream_decoder_set_read_callback(_decoder, &FLACStream::callWrapRead);
00205     ::FLAC__seekable_stream_decoder_set_seek_callback(_decoder, &FLACStream::callWrapSeek);
00206     ::FLAC__seekable_stream_decoder_set_tell_callback(_decoder, &FLACStream::callWrapTell);
00207     ::FLAC__seekable_stream_decoder_set_length_callback(_decoder, &FLACStream::callWrapLength);
00208     ::FLAC__seekable_stream_decoder_set_eof_callback(_decoder, &FLACStream::callWrapEOF);
00209     ::FLAC__seekable_stream_decoder_set_write_callback(_decoder, &FLACStream::callWrapWrite);
00210     ::FLAC__seekable_stream_decoder_set_metadata_callback(_decoder, &FLACStream::callWrapMetadata);
00211     ::FLAC__seekable_stream_decoder_set_error_callback(_decoder, &FLACStream::callWrapError);
00212     ::FLAC__seekable_stream_decoder_set_client_data(_decoder, (void *)this);
00213 
00214     success = (::FLAC__seekable_stream_decoder_init(_decoder) == FLAC__SEEKABLE_STREAM_DECODER_OK);
00215 #else
00216     success = (::FLAC__stream_decoder_init_stream(
00217         _decoder,
00218         &FLACStream::callWrapRead,
00219         &FLACStream::callWrapSeek,
00220         &FLACStream::callWrapTell,
00221         &FLACStream::callWrapLength,
00222         &FLACStream::callWrapEOF,
00223         &FLACStream::callWrapWrite,
00224         &FLACStream::callWrapMetadata,
00225         &FLACStream::callWrapError,
00226         (void *)this
00227     ) == FLAC__STREAM_DECODER_INIT_STATUS_OK);
00228 #endif
00229     if (success) {
00230         if (processUntilEndOfMetadata() && _streaminfo.channels > 0) {
00231             _lastSample = _streaminfo.total_samples + 1;
00232             _length = Timestamp(0, _lastSample - 1, getRate());
00233             return; // no error occurred
00234         }
00235     }
00236 
00237     warning("FLACStream: could not create audio stream");
00238 }
00239 
00240 FLACStream::~FLACStream() {
00241     if (_decoder != NULL) {
00242 #ifdef LEGACY_FLAC
00243         (void) ::FLAC__seekable_stream_decoder_finish(_decoder);
00244         ::FLAC__seekable_stream_decoder_delete(_decoder);
00245 #else
00246         (void) ::FLAC__stream_decoder_finish(_decoder);
00247         ::FLAC__stream_decoder_delete(_decoder);
00248 #endif
00249     }
00250     if (_disposeAfterUse)
00251         delete _inStream;
00252 }
00253 
00254 inline FLAC__StreamDecoderState FLACStream::getStreamDecoderState() const {
00255     assert(_decoder != NULL);
00256 #ifdef LEGACY_FLAC
00257     return ::FLAC__seekable_stream_decoder_get_stream_decoder_state(_decoder);
00258 #else
00259     return ::FLAC__stream_decoder_get_state(_decoder);
00260 #endif
00261 }
00262 
00263 inline bool FLACStream::processSingleBlock() {
00264     assert(_decoder != NULL);
00265 #ifdef LEGACY_FLAC
00266     return 0 != ::FLAC__seekable_stream_decoder_process_single(_decoder);
00267 #else
00268     return 0 != ::FLAC__stream_decoder_process_single(_decoder);
00269 #endif
00270 }
00271 
00272 inline bool FLACStream::processUntilEndOfMetadata() {
00273     assert(_decoder != NULL);
00274 #ifdef LEGACY_FLAC
00275     return 0 != ::FLAC__seekable_stream_decoder_process_until_end_of_metadata(_decoder);
00276 #else
00277     return 0 != ::FLAC__stream_decoder_process_until_end_of_metadata(_decoder);
00278 #endif
00279 }
00280 
00281 bool FLACStream::seekAbsolute(FLAC__uint64 sample) {
00282     assert(_decoder != NULL);
00283 #ifdef LEGACY_FLAC
00284     const bool result = (0 != ::FLAC__seekable_stream_decoder_seek_absolute(_decoder, sample));
00285 #else
00286     const bool result = (0 != ::FLAC__stream_decoder_seek_absolute(_decoder, sample));
00287 #endif
00288     if (result) {
00289         _lastSampleWritten = (_lastSample != 0 && sample >= _lastSample); // only set if we are SURE
00290     }
00291     return result;
00292 }
00293 
00294 bool FLACStream::seek(const Timestamp &where) {
00295     _sampleCache.bufFill = 0;
00296     _sampleCache.bufReadPos = NULL;
00297     // FLAC uses the sample pair number, thus we always use "false" for the isStereo parameter
00298     // of the convertTimeToStreamPos helper.
00299     return seekAbsolute((FLAC__uint64)convertTimeToStreamPos(where, getRate(), false).totalNumberOfFrames());
00300 }
00301 
00302 int FLACStream::readBuffer(int16 *buffer, const int numSamples) {
00303     const uint numChannels = getChannels();
00304 
00305     if (numChannels == 0) {
00306         warning("FLACStream: Stream not successfully initialized, cant playback");
00307         return -1; // streaminfo wasnt read!
00308     }
00309 
00310     assert(numSamples % numChannels == 0); // must be multiple of channels!
00311     assert(buffer != NULL);
00312     assert(_outBuffer == NULL);
00313     assert(_requestedSamples == 0);
00314 
00315     _outBuffer = buffer;
00316     _requestedSamples = numSamples;
00317 
00318     // If there is still data in our buffer from the last time around,
00319     // copy that first.
00320     if (_sampleCache.bufFill > 0) {
00321         assert(_sampleCache.bufReadPos >= _sampleCache.bufData);
00322         assert(_sampleCache.bufFill % numChannels == 0);
00323 
00324         const uint copySamples = MIN((uint)numSamples, _sampleCache.bufFill);
00325         memcpy(buffer, _sampleCache.bufReadPos, copySamples*sizeof(buffer[0]));
00326 
00327         _outBuffer = buffer + copySamples;
00328         _requestedSamples = numSamples - copySamples;
00329         _sampleCache.bufReadPos += copySamples;
00330         _sampleCache.bufFill -= copySamples;
00331     }
00332 
00333     bool decoderOk = true;
00334 
00335     FLAC__StreamDecoderState state = getStreamDecoderState();
00336 
00337     // Keep poking FLAC to process more samples until we completely satisfied the request
00338     // respectively until we run out of data.
00339     while (!_lastSampleWritten && _requestedSamples > 0 && state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) {
00340         assert(_sampleCache.bufFill == 0);
00341         assert(_requestedSamples % numChannels == 0);
00342         processSingleBlock();
00343         state = getStreamDecoderState();
00344 
00345         if (state == FLAC__STREAM_DECODER_END_OF_STREAM)
00346             _lastSampleWritten = true;
00347     }
00348 
00349     // Error handling
00350     switch (state) {
00351     case FLAC__STREAM_DECODER_END_OF_STREAM:
00352         _lastSampleWritten = true;
00353         break;
00354     case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
00355         break;
00356     default:
00357         decoderOk = false;
00358         warning("FLACStream: An error occurred while decoding. DecoderState is: %d", getStreamDecoderState());
00359     }
00360 
00361     // Compute how many samples we actually produced
00362     const int samples = (int)(_outBuffer - buffer);
00363     assert(samples % numChannels == 0);
00364 
00365     _outBuffer = NULL; // basically unnecessary, only for the purpose of the asserts
00366     _requestedSamples = 0; // basically unnecessary, only for the purpose of the asserts
00367 
00368     return decoderOk ? samples : -1;
00369 }
00370 
00371 inline ::FLAC__SeekableStreamDecoderReadStatus FLACStream::callbackRead(FLAC__byte buffer[], FLAC_size_t *bytes) {
00372     if (*bytes == 0) {
00373 #ifdef LEGACY_FLAC
00374         return FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_ERROR; /* abort to avoid a deadlock */
00375 #else
00376         return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
00377 #endif
00378     }
00379 
00380     const uint32 bytesRead = _inStream->read(buffer, *bytes);
00381 
00382     if (bytesRead == 0) {
00383 #ifdef LEGACY_FLAC
00384         return _inStream->eos() ? FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK : FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_ERROR;
00385 #else
00386         return _inStream->eos() ? FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM : FLAC__STREAM_DECODER_READ_STATUS_ABORT;
00387 #endif
00388     }
00389 
00390     *bytes = static_cast<uint>(bytesRead);
00391 #ifdef LEGACY_FLAC
00392     return FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK;
00393 #else
00394     return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
00395 #endif
00396 }
00397 
00398 void FLACStream::setBestConvertBufferMethod() {
00399     PFCONVERTBUFFERS tempMethod = &FLACStream::convertBuffersGeneric;
00400 
00401     const uint numChannels = getChannels();
00402     const uint8 numBits = (uint8)_streaminfo.bits_per_sample;
00403 
00404     assert(numChannels >= 1);
00405     assert(numBits >= 4 && numBits <=32);
00406 
00407     if (numChannels == 1) {
00408         if (numBits == 8)
00409             tempMethod = &FLACStream::convertBuffersMono8Bit;
00410         if (numBits == BUFTYPE_BITS)
00411             tempMethod = &FLACStream::convertBuffersMonoNS;
00412     } else if (numChannels == 2) {
00413         if (numBits == 8)
00414             tempMethod = &FLACStream::convertBuffersStereo8Bit;
00415         if (numBits == BUFTYPE_BITS)
00416             tempMethod = &FLACStream::convertBuffersStereoNS;
00417     } /* else ... */
00418 
00419     _methodConvertBuffers = tempMethod;
00420 }
00421 
00422 // 1 channel, no scaling
00423 void FLACStream::convertBuffersMonoNS(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
00424     assert(numChannels == 1);
00425     assert(numBits == BUFTYPE_BITS);
00426 
00427     FLAC__int32 const* inChannel1 = inChannels[0];
00428 
00429     while (numSamples >= 4) {
00430         bufDestination[0] = static_cast<SampleType>(inChannel1[0]);
00431         bufDestination[1] = static_cast<SampleType>(inChannel1[1]);
00432         bufDestination[2] = static_cast<SampleType>(inChannel1[2]);
00433         bufDestination[3] = static_cast<SampleType>(inChannel1[3]);
00434         bufDestination += 4;
00435         inChannel1 += 4;
00436         numSamples -= 4;
00437     }
00438 
00439     for (; numSamples > 0; --numSamples) {
00440         *bufDestination++ = static_cast<SampleType>(*inChannel1++);
00441     }
00442 
00443     inChannels[0] = inChannel1;
00444     assert(numSamples == 0); // dint copy too many samples
00445 }
00446 
00447 // 1 channel, scaling from 8Bit
00448 void FLACStream::convertBuffersMono8Bit(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
00449     assert(numChannels == 1);
00450     assert(numBits == 8);
00451     assert(8 < BUFTYPE_BITS);
00452 
00453     FLAC__int32 const* inChannel1 = inChannels[0];
00454 
00455     while (numSamples >= 4) {
00456         bufDestination[0] = static_cast<SampleType>(inChannel1[0]) << (BUFTYPE_BITS - 8);
00457         bufDestination[1] = static_cast<SampleType>(inChannel1[1]) << (BUFTYPE_BITS - 8);
00458         bufDestination[2] = static_cast<SampleType>(inChannel1[2]) << (BUFTYPE_BITS - 8);
00459         bufDestination[3] = static_cast<SampleType>(inChannel1[3]) << (BUFTYPE_BITS - 8);
00460         bufDestination += 4;
00461         inChannel1 += 4;
00462         numSamples -= 4;
00463     }
00464 
00465     for (; numSamples > 0; --numSamples) {
00466         *bufDestination++ = static_cast<SampleType>(*inChannel1++) << (BUFTYPE_BITS - 8);
00467     }
00468 
00469     inChannels[0] = inChannel1;
00470     assert(numSamples == 0); // dint copy too many samples
00471 }
00472 
00473 // 2 channels, no scaling
00474 void FLACStream::convertBuffersStereoNS(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
00475     assert(numChannels == 2);
00476     assert(numBits == BUFTYPE_BITS);
00477     assert(numSamples % 2 == 0); // must be integral multiply of channels
00478 
00479 
00480     FLAC__int32 const* inChannel1 = inChannels[0];  // Left Channel
00481     FLAC__int32 const* inChannel2 = inChannels[1];  // Right Channel
00482 
00483     while (numSamples >= 2*2) {
00484         bufDestination[0] = static_cast<SampleType>(inChannel1[0]);
00485         bufDestination[1] = static_cast<SampleType>(inChannel2[0]);
00486         bufDestination[2] = static_cast<SampleType>(inChannel1[1]);
00487         bufDestination[3] = static_cast<SampleType>(inChannel2[1]);
00488         bufDestination += 2 * 2;
00489         inChannel1 += 2;
00490         inChannel2 += 2;
00491         numSamples -= 2 * 2;
00492     }
00493 
00494     while (numSamples > 0) {
00495         bufDestination[0] = static_cast<SampleType>(*inChannel1++);
00496         bufDestination[1] = static_cast<SampleType>(*inChannel2++);
00497         bufDestination += 2;
00498         numSamples -= 2;
00499     }
00500 
00501     inChannels[0] = inChannel1;
00502     inChannels[1] = inChannel2;
00503     assert(numSamples == 0); // dint copy too many samples
00504 }
00505 
00506 // 2 channels, scaling from 8Bit
00507 void FLACStream::convertBuffersStereo8Bit(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
00508     assert(numChannels == 2);
00509     assert(numBits == 8);
00510     assert(numSamples % 2 == 0); // must be integral multiply of channels
00511     assert(8 < BUFTYPE_BITS);
00512 
00513     FLAC__int32 const* inChannel1 = inChannels[0];  // Left Channel
00514     FLAC__int32 const* inChannel2 = inChannels[1];  // Right Channel
00515 
00516     while (numSamples >= 2*2) {
00517         bufDestination[0] = static_cast<SampleType>(inChannel1[0]) << (BUFTYPE_BITS - 8);
00518         bufDestination[1] = static_cast<SampleType>(inChannel2[0]) << (BUFTYPE_BITS - 8);
00519         bufDestination[2] = static_cast<SampleType>(inChannel1[1]) << (BUFTYPE_BITS - 8);
00520         bufDestination[3] = static_cast<SampleType>(inChannel2[1]) << (BUFTYPE_BITS - 8);
00521         bufDestination += 2 * 2;
00522         inChannel1 += 2;
00523         inChannel2 += 2;
00524         numSamples -= 2 * 2;
00525     }
00526 
00527     while (numSamples > 0) {
00528         bufDestination[0] = static_cast<SampleType>(*inChannel1++) << (BUFTYPE_BITS - 8);
00529         bufDestination[1] = static_cast<SampleType>(*inChannel2++) << (BUFTYPE_BITS - 8);
00530         bufDestination += 2;
00531         numSamples -= 2;
00532     }
00533 
00534     inChannels[0] = inChannel1;
00535     inChannels[1] = inChannel2;
00536     assert(numSamples == 0); // dint copy too many samples
00537 }
00538 
00539 // all Purpose-conversion - slowest of em all
00540 void FLACStream::convertBuffersGeneric(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
00541     assert(numSamples % numChannels == 0); // must be integral multiply of channels
00542 
00543     if (numBits < BUFTYPE_BITS) {
00544         const uint8 kPower = (uint8)(BUFTYPE_BITS - numBits);
00545 
00546         for (; numSamples > 0; numSamples -= numChannels) {
00547             for (uint i = 0; i < numChannels; ++i)
00548                 *bufDestination++ = static_cast<SampleType>(*(inChannels[i]++)) << kPower;
00549         }
00550     } else if (numBits > BUFTYPE_BITS) {
00551         const uint8 kPower = (uint8)(numBits - BUFTYPE_BITS);
00552 
00553         for (; numSamples > 0; numSamples -= numChannels) {
00554             for (uint i = 0; i < numChannels; ++i)
00555                 *bufDestination++ = static_cast<SampleType>(*(inChannels[i]++) >> kPower);
00556         }
00557     } else {
00558         for (; numSamples > 0; numSamples -= numChannels) {
00559             for (uint i = 0; i < numChannels; ++i)
00560                 *bufDestination++ = static_cast<SampleType>(*(inChannels[i]++));
00561         }
00562     }
00563 
00564     assert(numSamples == 0); // dint copy too many samples
00565 }
00566 
00567 inline ::FLAC__StreamDecoderWriteStatus FLACStream::callbackWrite(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]) {
00568     assert(frame->header.channels == _streaminfo.channels);
00569     assert(frame->header.sample_rate == _streaminfo.sample_rate);
00570     assert(frame->header.bits_per_sample == _streaminfo.bits_per_sample);
00571     assert(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER || _streaminfo.min_blocksize == _streaminfo.max_blocksize);
00572 
00573     // We require that either the sample cache is empty, or that no samples were requested
00574     assert(_sampleCache.bufFill == 0 || _requestedSamples == 0);
00575 
00576     uint numSamples = frame->header.blocksize;
00577     const uint numChannels = getChannels();
00578     const uint8 numBits = (uint8)_streaminfo.bits_per_sample;
00579 
00580     assert(_requestedSamples % numChannels == 0); // must be integral multiply of channels
00581 
00582     const FLAC__uint64 firstSampleNumber = (frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER) ?
00583         frame->header.number.sample_number : (static_cast<FLAC__uint64>(frame->header.number.frame_number)) * _streaminfo.max_blocksize;
00584 
00585     // Check whether we are about to reach beyond the last sample we are supposed to play.
00586     if (_lastSample != 0 && firstSampleNumber + numSamples >= _lastSample) {
00587         numSamples = (uint)(firstSampleNumber >= _lastSample ? 0 : _lastSample - firstSampleNumber);
00588         _lastSampleWritten = true;
00589     }
00590 
00591     // The value in _requestedSamples counts raw samples, so if there are more than one
00592     // channel, we have to multiply the number of available sample "pairs" by numChannels
00593     numSamples *= numChannels;
00594 
00595     const FLAC__int32 *inChannels[MAX_OUTPUT_CHANNELS];
00596     for (uint i = 0; i < numChannels; ++i)
00597         inChannels[i] = buffer[i];
00598 
00599     // write the incoming samples directly into the buffer provided to us by the mixer
00600     if (_requestedSamples > 0) {
00601         assert(_requestedSamples % numChannels == 0);
00602         assert(_outBuffer != NULL);
00603 
00604         // Copy & convert the available samples (limited both by how many we have available, and
00605         // by how many are actually needed).
00606         const uint copySamples = MIN(_requestedSamples, numSamples);
00607         (*_methodConvertBuffers)(_outBuffer, inChannels, copySamples, numChannels, numBits);
00608 
00609         _requestedSamples -= copySamples;
00610         numSamples -= copySamples;
00611         _outBuffer += copySamples;
00612     }
00613 
00614     // Write all remaining samples (i.e. those which didn't fit into the mixer buffer)
00615     // into the sample cache.
00616     if (_sampleCache.bufFill == 0)
00617         _sampleCache.bufReadPos = _sampleCache.bufData;
00618     const uint cacheSpace = (_sampleCache.bufData + BUFFER_SIZE) - (_sampleCache.bufReadPos + _sampleCache.bufFill);
00619     assert(numSamples <= cacheSpace);
00620     (*_methodConvertBuffers)(_sampleCache.bufReadPos + _sampleCache.bufFill, inChannels, numSamples, numChannels, numBits);
00621 
00622     _sampleCache.bufFill += numSamples;
00623 
00624     return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
00625 }
00626 
00627 inline ::FLAC__SeekableStreamDecoderSeekStatus FLACStream::callbackSeek(FLAC__uint64 absoluteByteOffset) {
00628     _inStream->seek(absoluteByteOffset, SEEK_SET);
00629     const bool result = (absoluteByteOffset == (FLAC__uint64)_inStream->pos());
00630 
00631 #ifdef LEGACY_FLAC
00632     return result ? FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK : FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_ERROR;
00633 #else
00634     return result ? FLAC__STREAM_DECODER_SEEK_STATUS_OK : FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
00635 #endif
00636 }
00637 
00638 inline ::FLAC__SeekableStreamDecoderTellStatus FLACStream::callbackTell(FLAC__uint64 *absoluteByteOffset) {
00639     *absoluteByteOffset = static_cast<FLAC__uint64>(_inStream->pos());
00640 #ifdef LEGACY_FLAC
00641     return FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK;
00642 #else
00643     return FLAC__STREAM_DECODER_TELL_STATUS_OK;
00644 #endif
00645 }
00646 
00647 inline ::FLAC__SeekableStreamDecoderLengthStatus FLACStream::callbackLength(FLAC__uint64 *streamLength) {
00648     *streamLength = static_cast<FLAC__uint64>(_inStream->size());
00649 #ifdef LEGACY_FLAC
00650     return FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK;
00651 #else
00652     return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
00653 #endif
00654 }
00655 
00656 inline bool FLACStream::callbackEOF() {
00657     return _inStream->eos();
00658 }
00659 
00660 
00661 inline void FLACStream::callbackMetadata(const ::FLAC__StreamMetadata *metadata) {
00662     assert(_decoder != NULL);
00663     assert(metadata->type == FLAC__METADATA_TYPE_STREAMINFO); // others arent really interesting
00664 
00665     _streaminfo = metadata->data.stream_info;
00666     setBestConvertBufferMethod(); // should be set after getting stream-information. FLAC always parses the info first
00667 }
00668 inline void FLACStream::callbackError(::FLAC__StreamDecoderErrorStatus status) {
00669     // some of these are non-critical-Errors
00670     debug(1, "FLACStream: An error occurred while decoding. DecoderStateError is: %d", status);
00671 }
00672 
00673 /* Static Callback Wrappers */
00674 ::FLAC__SeekableStreamDecoderReadStatus FLACStream::callWrapRead(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__byte buffer[], FLAC_size_t *bytes, void *clientData) {
00675     FLACStream *instance = (FLACStream *)clientData;
00676     assert(0 != instance);
00677     return instance->callbackRead(buffer, bytes);
00678 }
00679 
00680 ::FLAC__SeekableStreamDecoderSeekStatus FLACStream::callWrapSeek(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 absoluteByteOffset, void *clientData) {
00681     FLACStream *instance = (FLACStream *)clientData;
00682     assert(0 != instance);
00683     return instance->callbackSeek(absoluteByteOffset);
00684 }
00685 
00686 ::FLAC__SeekableStreamDecoderTellStatus FLACStream::callWrapTell(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *absoluteByteOffset, void *clientData) {
00687     FLACStream *instance = (FLACStream *)clientData;
00688     assert(0 != instance);
00689     return instance->callbackTell(absoluteByteOffset);
00690 }
00691 
00692 ::FLAC__SeekableStreamDecoderLengthStatus FLACStream::callWrapLength(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *streamLength, void *clientData) {
00693     FLACStream *instance = (FLACStream *)clientData;
00694     assert(0 != instance);
00695     return instance->callbackLength(streamLength);
00696 }
00697 
00698 FLAC__bool FLACStream::callWrapEOF(const ::FLAC__SeekableStreamDecoder *decoder, void *clientData) {
00699     FLACStream *instance = (FLACStream *)clientData;
00700     assert(0 != instance);
00701     return instance->callbackEOF();
00702 }
00703 
00704 ::FLAC__StreamDecoderWriteStatus FLACStream::callWrapWrite(const ::FLAC__SeekableStreamDecoder *decoder, const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *clientData) {
00705     FLACStream *instance = (FLACStream *)clientData;
00706     assert(0 != instance);
00707     return instance->callbackWrite(frame, buffer);
00708 }
00709 
00710 void FLACStream::callWrapMetadata(const ::FLAC__SeekableStreamDecoder *decoder, const ::FLAC__StreamMetadata *metadata, void *clientData) {
00711     FLACStream *instance = (FLACStream *)clientData;
00712     assert(0 != instance);
00713     instance->callbackMetadata(metadata);
00714 }
00715 
00716 void FLACStream::callWrapError(const ::FLAC__SeekableStreamDecoder *decoder, ::FLAC__StreamDecoderErrorStatus status, void *clientData) {
00717     FLACStream *instance = (FLACStream *)clientData;
00718     assert(0 != instance);
00719     instance->callbackError(status);
00720 }
00721 
00722 
00723 #pragma mark -
00724 #pragma mark --- FLAC factory functions ---
00725 #pragma mark -
00726 
00727 SeekableAudioStream *makeFLACStream(
00728     Common::SeekableReadStream *stream,
00729     DisposeAfterUse::Flag disposeAfterUse) {
00730     SeekableAudioStream *s = new FLACStream(stream, disposeAfterUse);
00731     if (s && s->endOfData()) {
00732         delete s;
00733         return 0;
00734     } else {
00735         return s;
00736     }
00737 }
00738 
00739 } // End of namespace Audio
00740 
00741 #endif // #ifdef USE_FLAC


Generated on Sat Aug 15 2020 05:00:57 for ResidualVM by doxygen 1.7.1
curved edge   curved edge