1 /* ScummVM - Graphic Adventure Engine
2  *
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.
6  *
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.
11  *
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.
16  *
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.
20  *
21  */
22 
23 // Disable symbol overrides for FILE as that is used in FLAC headers
24 #define FORBIDDEN_SYMBOL_EXCEPTION_FILE
25 
26 #include "audio/decoders/flac.h"
27 
28 #ifdef USE_FLAC
29 
30 #include "common/debug.h"
31 #include "common/stream.h"
32 #include "common/textconsole.h"
33 #include "common/util.h"
34 
35 #include "audio/audiostream.h"
36 
37 #define FLAC__NO_DLL // that MS-magic gave me headaches - just link the library you like
38 #include <FLAC/export.h>
39 
40 
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
47 
48 
49 #ifdef LEGACY_FLAC
50 
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;
54 
55 #else
56 
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.
62 
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;
72 
73 #endif
74 
75 
76 namespace Audio {
77 
78 #pragma mark -
79 #pragma mark --- FLAC stream ---
80 #pragma mark -
81 
82 static const uint MAX_OUTPUT_CHANNELS = 2;
83 
84 
85 class FLACStream : public SeekableAudioStream {
86 protected:
87 	Common::SeekableReadStream *_inStream;
88 	bool _disposeAfterUse;
89 
90 	::FLAC__SeekableStreamDecoder *_decoder;
91 
92 	/** Header of the stream */
93 	FLAC__StreamMetadata_StreamInfo _streaminfo;
94 
95 	/** index + 1(!) of the last sample to be played */
96 	FLAC__uint64 _lastSample;
97 
98 	/** total play time */
99 	Timestamp _length;
100 
101 	/** true if the last sample was decoded from the FLAC-API - there might still be data in the buffer */
102 	bool _lastSampleWritten;
103 
104 	typedef int16 SampleType;
105 	enum { BUFTYPE_BITS = 16 };
106 
107 	enum {
108 		// Maximal buffer size. According to the FLAC format specification, the  block size is
109 		// a 16 bit value (in fact it seems the maximal block size is 32768, but we play it safe).
110 		BUFFER_SIZE = 65536
111 	};
112 
113 	struct {
114 		SampleType bufData[BUFFER_SIZE];
115 		SampleType *bufReadPos;
116 		uint bufFill;
117 	} _sampleCache;
118 
119 	SampleType *_outBuffer;
120 	uint _requestedSamples;
121 
122 	typedef void (*PFCONVERTBUFFERS)(SampleType*, const FLAC__int32*[], uint, const uint, const uint8);
123 	PFCONVERTBUFFERS _methodConvertBuffers;
124 
125 
126 public:
127 	FLACStream(Common::SeekableReadStream *inStream, bool dispose);
128 	virtual ~FLACStream();
129 
130 	int readBuffer(int16 *buffer, const int numSamples);
131 
isStereo() const132 	bool isStereo() const { return _streaminfo.channels >= 2; }
getRate() const133 	int getRate() const { return _streaminfo.sample_rate; }
endOfData() const134 	bool endOfData() const {
135 		// End of data is reached if there either is no valid stream data available,
136 		// or if we reached the last sample and completely emptied the sample cache.
137 		return _streaminfo.channels == 0 || (_lastSampleWritten && _sampleCache.bufFill == 0);
138 	}
139 
140 	bool seek(const Timestamp &where);
getLength() const141 	Timestamp getLength() const { return _length; }
142 
isStreamDecoderReady() const143 	bool isStreamDecoderReady() const { return getStreamDecoderState() == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; }
144 protected:
getChannels() const145 	uint getChannels() const { return MIN<uint>(_streaminfo.channels, MAX_OUTPUT_CHANNELS); }
146 
147 	bool allocateBuffer(uint minSamples);
148 
149 	inline FLAC__StreamDecoderState getStreamDecoderState() const;
150 
151 	inline bool processSingleBlock();
152 	inline bool processUntilEndOfMetadata();
153 	bool seekAbsolute(FLAC__uint64 sample);
154 
155 	inline ::FLAC__SeekableStreamDecoderReadStatus callbackRead(FLAC__byte buffer[], FLAC_size_t *bytes);
156 	inline ::FLAC__SeekableStreamDecoderSeekStatus callbackSeek(FLAC__uint64 absoluteByteOffset);
157 	inline ::FLAC__SeekableStreamDecoderTellStatus callbackTell(FLAC__uint64 *absoluteByteOffset);
158 	inline ::FLAC__SeekableStreamDecoderLengthStatus callbackLength(FLAC__uint64 *streamLength);
159 	inline bool callbackEOF();
160 	inline ::FLAC__StreamDecoderWriteStatus callbackWrite(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
161 	inline void callbackMetadata(const ::FLAC__StreamMetadata *metadata);
162 	inline void callbackError(::FLAC__StreamDecoderErrorStatus status);
163 
164 private:
165 	static ::FLAC__SeekableStreamDecoderReadStatus callWrapRead(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__byte buffer[], FLAC_size_t *bytes, void *clientData);
166 	static ::FLAC__SeekableStreamDecoderSeekStatus callWrapSeek(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 absoluteByteOffset, void *clientData);
167 	static ::FLAC__SeekableStreamDecoderTellStatus callWrapTell(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *absoluteByteOffset, void *clientData);
168 	static ::FLAC__SeekableStreamDecoderLengthStatus callWrapLength(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *streamLength, void *clientData);
169 	static FLAC__bool callWrapEOF(const ::FLAC__SeekableStreamDecoder *decoder, void *clientData);
170 	static ::FLAC__StreamDecoderWriteStatus callWrapWrite(const ::FLAC__SeekableStreamDecoder *decoder, const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *clientData);
171 	static void callWrapMetadata(const ::FLAC__SeekableStreamDecoder *decoder, const ::FLAC__StreamMetadata *metadata, void *clientData);
172 	static void callWrapError(const ::FLAC__SeekableStreamDecoder *decoder, ::FLAC__StreamDecoderErrorStatus status, void *clientData);
173 
174 	void setBestConvertBufferMethod();
175 	static void convertBuffersGeneric(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
176 	static void convertBuffersStereoNS(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
177 	static void convertBuffersStereo8Bit(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
178 	static void convertBuffersMonoNS(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
179 	static void convertBuffersMono8Bit(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits);
180 };
181 
FLACStream(Common::SeekableReadStream * inStream,bool dispose)182 FLACStream::FLACStream(Common::SeekableReadStream *inStream, bool dispose)
183 #ifdef LEGACY_FLAC
184 			:	_decoder(::FLAC__seekable_stream_decoder_new()),
185 #else
186 			:	_decoder(::FLAC__stream_decoder_new()),
187 #endif
188 		_inStream(inStream),
189 		_disposeAfterUse(dispose),
190 		_length(0, 1000), _lastSample(0),
191 		_outBuffer(NULL), _requestedSamples(0), _lastSampleWritten(false),
192 		_methodConvertBuffers(&FLACStream::convertBuffersGeneric)
193 {
194 	assert(_inStream);
195 	memset(&_streaminfo, 0, sizeof(_streaminfo));
196 
197 	_sampleCache.bufReadPos = NULL;
198 	_sampleCache.bufFill = 0;
199 
200 	_methodConvertBuffers = &FLACStream::convertBuffersGeneric;
201 
202 	bool success;
203 #ifdef LEGACY_FLAC
204 	::FLAC__seekable_stream_decoder_set_read_callback(_decoder, &FLACStream::callWrapRead);
205 	::FLAC__seekable_stream_decoder_set_seek_callback(_decoder, &FLACStream::callWrapSeek);
206 	::FLAC__seekable_stream_decoder_set_tell_callback(_decoder, &FLACStream::callWrapTell);
207 	::FLAC__seekable_stream_decoder_set_length_callback(_decoder, &FLACStream::callWrapLength);
208 	::FLAC__seekable_stream_decoder_set_eof_callback(_decoder, &FLACStream::callWrapEOF);
209 	::FLAC__seekable_stream_decoder_set_write_callback(_decoder, &FLACStream::callWrapWrite);
210 	::FLAC__seekable_stream_decoder_set_metadata_callback(_decoder, &FLACStream::callWrapMetadata);
211 	::FLAC__seekable_stream_decoder_set_error_callback(_decoder, &FLACStream::callWrapError);
212 	::FLAC__seekable_stream_decoder_set_client_data(_decoder, (void *)this);
213 
214 	success = (::FLAC__seekable_stream_decoder_init(_decoder) == FLAC__SEEKABLE_STREAM_DECODER_OK);
215 #else
216 	success = (::FLAC__stream_decoder_init_stream(
217 		_decoder,
218 		&FLACStream::callWrapRead,
219 		&FLACStream::callWrapSeek,
220 		&FLACStream::callWrapTell,
221 		&FLACStream::callWrapLength,
222 		&FLACStream::callWrapEOF,
223 		&FLACStream::callWrapWrite,
224 		&FLACStream::callWrapMetadata,
225 		&FLACStream::callWrapError,
226 		(void *)this
227 	) == FLAC__STREAM_DECODER_INIT_STATUS_OK);
228 #endif
229 	if (success) {
230 		if (processUntilEndOfMetadata() && _streaminfo.channels > 0) {
231 			_lastSample = _streaminfo.total_samples + 1;
232 			_length = Timestamp(0, _lastSample - 1, getRate());
233 			return; // no error occurred
234 		}
235 	}
236 
237 	warning("FLACStream: could not create audio stream");
238 }
239 
~FLACStream()240 FLACStream::~FLACStream() {
241 	if (_decoder != NULL) {
242 #ifdef LEGACY_FLAC
243 		(void) ::FLAC__seekable_stream_decoder_finish(_decoder);
244 		::FLAC__seekable_stream_decoder_delete(_decoder);
245 #else
246 		(void) ::FLAC__stream_decoder_finish(_decoder);
247 		::FLAC__stream_decoder_delete(_decoder);
248 #endif
249 	}
250 	if (_disposeAfterUse)
251 		delete _inStream;
252 }
253 
getStreamDecoderState() const254 inline FLAC__StreamDecoderState FLACStream::getStreamDecoderState() const {
255 	assert(_decoder != NULL);
256 #ifdef LEGACY_FLAC
257 	return ::FLAC__seekable_stream_decoder_get_stream_decoder_state(_decoder);
258 #else
259 	return ::FLAC__stream_decoder_get_state(_decoder);
260 #endif
261 }
262 
processSingleBlock()263 inline bool FLACStream::processSingleBlock() {
264 	assert(_decoder != NULL);
265 #ifdef LEGACY_FLAC
266 	return 0 != ::FLAC__seekable_stream_decoder_process_single(_decoder);
267 #else
268 	return 0 != ::FLAC__stream_decoder_process_single(_decoder);
269 #endif
270 }
271 
processUntilEndOfMetadata()272 inline bool FLACStream::processUntilEndOfMetadata() {
273 	assert(_decoder != NULL);
274 #ifdef LEGACY_FLAC
275 	return 0 != ::FLAC__seekable_stream_decoder_process_until_end_of_metadata(_decoder);
276 #else
277 	return 0 != ::FLAC__stream_decoder_process_until_end_of_metadata(_decoder);
278 #endif
279 }
280 
seekAbsolute(FLAC__uint64 sample)281 bool FLACStream::seekAbsolute(FLAC__uint64 sample) {
282 	assert(_decoder != NULL);
283 #ifdef LEGACY_FLAC
284 	const bool result = (0 != ::FLAC__seekable_stream_decoder_seek_absolute(_decoder, sample));
285 #else
286 	const bool result = (0 != ::FLAC__stream_decoder_seek_absolute(_decoder, sample));
287 #endif
288 	if (result) {
289 		_lastSampleWritten = (_lastSample != 0 && sample >= _lastSample); // only set if we are SURE
290 	}
291 	return result;
292 }
293 
seek(const Timestamp & where)294 bool FLACStream::seek(const Timestamp &where) {
295 	_sampleCache.bufFill = 0;
296 	_sampleCache.bufReadPos = NULL;
297 	// FLAC uses the sample pair number, thus we always use "false" for the isStereo parameter
298 	// of the convertTimeToStreamPos helper.
299 	return seekAbsolute((FLAC__uint64)convertTimeToStreamPos(where, getRate(), false).totalNumberOfFrames());
300 }
301 
readBuffer(int16 * buffer,const int numSamples)302 int FLACStream::readBuffer(int16 *buffer, const int numSamples) {
303 	const uint numChannels = getChannels();
304 
305 	if (numChannels == 0) {
306 		warning("FLACStream: Stream not successfully initialized, cant playback");
307 		return -1; // streaminfo wasnt read!
308 	}
309 
310 	assert(numSamples % numChannels == 0); // must be multiple of channels!
311 	assert(buffer != NULL);
312 	assert(_outBuffer == NULL);
313 	assert(_requestedSamples == 0);
314 
315 	_outBuffer = buffer;
316 	_requestedSamples = numSamples;
317 
318 	// If there is still data in our buffer from the last time around,
319 	// copy that first.
320 	if (_sampleCache.bufFill > 0) {
321 		assert(_sampleCache.bufReadPos >= _sampleCache.bufData);
322 		assert(_sampleCache.bufFill % numChannels == 0);
323 
324 		const uint copySamples = MIN((uint)numSamples, _sampleCache.bufFill);
325 		memcpy(buffer, _sampleCache.bufReadPos, copySamples*sizeof(buffer[0]));
326 
327 		_outBuffer = buffer + copySamples;
328 		_requestedSamples = numSamples - copySamples;
329 		_sampleCache.bufReadPos += copySamples;
330 		_sampleCache.bufFill -= copySamples;
331 	}
332 
333 	bool decoderOk = true;
334 
335 	FLAC__StreamDecoderState state = getStreamDecoderState();
336 
337 	// Keep poking FLAC to process more samples until we completely satisfied the request
338 	// respectively until we run out of data.
339 	while (!_lastSampleWritten && _requestedSamples > 0 && state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) {
340 		assert(_sampleCache.bufFill == 0);
341 		assert(_requestedSamples % numChannels == 0);
342 		processSingleBlock();
343 		state = getStreamDecoderState();
344 
345 		if (state == FLAC__STREAM_DECODER_END_OF_STREAM)
346 			_lastSampleWritten = true;
347 	}
348 
349 	// Error handling
350 	switch (state) {
351 	case FLAC__STREAM_DECODER_END_OF_STREAM:
352 		_lastSampleWritten = true;
353 		break;
354 	case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
355 		break;
356 	default:
357 		decoderOk = false;
358 		warning("FLACStream: An error occurred while decoding. DecoderState is: %d", getStreamDecoderState());
359 	}
360 
361 	// Compute how many samples we actually produced
362 	const int samples = (int)(_outBuffer - buffer);
363 	assert(samples % numChannels == 0);
364 
365 	_outBuffer = NULL; // basically unnecessary, only for the purpose of the asserts
366 	_requestedSamples = 0; // basically unnecessary, only for the purpose of the asserts
367 
368 	return decoderOk ? samples : -1;
369 }
370 
callbackRead(FLAC__byte buffer[],FLAC_size_t * bytes)371 inline ::FLAC__SeekableStreamDecoderReadStatus FLACStream::callbackRead(FLAC__byte buffer[], FLAC_size_t *bytes) {
372 	if (*bytes == 0) {
373 #ifdef LEGACY_FLAC
374 		return FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_ERROR; /* abort to avoid a deadlock */
375 #else
376 		return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
377 #endif
378 	}
379 
380 	const uint32 bytesRead = _inStream->read(buffer, *bytes);
381 
382 	if (bytesRead == 0) {
383 #ifdef LEGACY_FLAC
384 		return _inStream->eos() ? FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK : FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_ERROR;
385 #else
386 		return _inStream->eos() ? FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM : FLAC__STREAM_DECODER_READ_STATUS_ABORT;
387 #endif
388 	}
389 
390 	*bytes = static_cast<uint>(bytesRead);
391 #ifdef LEGACY_FLAC
392 	return FLAC__SEEKABLE_STREAM_DECODER_READ_STATUS_OK;
393 #else
394 	return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
395 #endif
396 }
397 
setBestConvertBufferMethod()398 void FLACStream::setBestConvertBufferMethod() {
399 	PFCONVERTBUFFERS tempMethod = &FLACStream::convertBuffersGeneric;
400 
401 	const uint numChannels = getChannels();
402 	const uint8 numBits = (uint8)_streaminfo.bits_per_sample;
403 
404 	assert(numChannels >= 1);
405 	assert(numBits >= 4 && numBits <=32);
406 
407 	if (numChannels == 1) {
408 		if (numBits == 8)
409 			tempMethod = &FLACStream::convertBuffersMono8Bit;
410 		if (numBits == BUFTYPE_BITS)
411 			tempMethod = &FLACStream::convertBuffersMonoNS;
412 	} else if (numChannels == 2) {
413 		if (numBits == 8)
414 			tempMethod = &FLACStream::convertBuffersStereo8Bit;
415 		if (numBits == BUFTYPE_BITS)
416 			tempMethod = &FLACStream::convertBuffersStereoNS;
417 	} /* else ... */
418 
419 	_methodConvertBuffers = tempMethod;
420 }
421 
422 // 1 channel, no scaling
convertBuffersMonoNS(SampleType * bufDestination,const FLAC__int32 * inChannels[],uint numSamples,const uint numChannels,const uint8 numBits)423 void FLACStream::convertBuffersMonoNS(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
424 	assert(numChannels == 1);
425 	assert(numBits == BUFTYPE_BITS);
426 
427 	FLAC__int32 const* inChannel1 = inChannels[0];
428 
429 	while (numSamples >= 4) {
430 		bufDestination[0] = static_cast<SampleType>(inChannel1[0]);
431 		bufDestination[1] = static_cast<SampleType>(inChannel1[1]);
432 		bufDestination[2] = static_cast<SampleType>(inChannel1[2]);
433 		bufDestination[3] = static_cast<SampleType>(inChannel1[3]);
434 		bufDestination += 4;
435 		inChannel1 += 4;
436 		numSamples -= 4;
437 	}
438 
439 	for (; numSamples > 0; --numSamples) {
440 		*bufDestination++ = static_cast<SampleType>(*inChannel1++);
441 	}
442 
443 	inChannels[0] = inChannel1;
444 	assert(numSamples == 0); // dint copy too many samples
445 }
446 
447 // 1 channel, scaling from 8Bit
convertBuffersMono8Bit(SampleType * bufDestination,const FLAC__int32 * inChannels[],uint numSamples,const uint numChannels,const uint8 numBits)448 void FLACStream::convertBuffersMono8Bit(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
449 	assert(numChannels == 1);
450 	assert(numBits == 8);
451 	assert(8 < BUFTYPE_BITS);
452 
453 	FLAC__int32 const* inChannel1 = inChannels[0];
454 
455 	while (numSamples >= 4) {
456 		bufDestination[0] = static_cast<SampleType>(inChannel1[0]) << (BUFTYPE_BITS - 8);
457 		bufDestination[1] = static_cast<SampleType>(inChannel1[1]) << (BUFTYPE_BITS - 8);
458 		bufDestination[2] = static_cast<SampleType>(inChannel1[2]) << (BUFTYPE_BITS - 8);
459 		bufDestination[3] = static_cast<SampleType>(inChannel1[3]) << (BUFTYPE_BITS - 8);
460 		bufDestination += 4;
461 		inChannel1 += 4;
462 		numSamples -= 4;
463 	}
464 
465 	for (; numSamples > 0; --numSamples) {
466 		*bufDestination++ = static_cast<SampleType>(*inChannel1++) << (BUFTYPE_BITS - 8);
467 	}
468 
469 	inChannels[0] = inChannel1;
470 	assert(numSamples == 0); // dint copy too many samples
471 }
472 
473 // 2 channels, no scaling
convertBuffersStereoNS(SampleType * bufDestination,const FLAC__int32 * inChannels[],uint numSamples,const uint numChannels,const uint8 numBits)474 void FLACStream::convertBuffersStereoNS(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
475 	assert(numChannels == 2);
476 	assert(numBits == BUFTYPE_BITS);
477 	assert(numSamples % 2 == 0); // must be integral multiply of channels
478 
479 
480 	FLAC__int32 const* inChannel1 = inChannels[0];	// Left Channel
481 	FLAC__int32 const* inChannel2 = inChannels[1];	// Right Channel
482 
483 	while (numSamples >= 2*2) {
484 		bufDestination[0] = static_cast<SampleType>(inChannel1[0]);
485 		bufDestination[1] = static_cast<SampleType>(inChannel2[0]);
486 		bufDestination[2] = static_cast<SampleType>(inChannel1[1]);
487 		bufDestination[3] = static_cast<SampleType>(inChannel2[1]);
488 		bufDestination += 2 * 2;
489 		inChannel1 += 2;
490 		inChannel2 += 2;
491 		numSamples -= 2 * 2;
492 	}
493 
494 	while (numSamples > 0) {
495 		bufDestination[0] = static_cast<SampleType>(*inChannel1++);
496 		bufDestination[1] = static_cast<SampleType>(*inChannel2++);
497 		bufDestination += 2;
498 		numSamples -= 2;
499 	}
500 
501 	inChannels[0] = inChannel1;
502 	inChannels[1] = inChannel2;
503 	assert(numSamples == 0); // dint copy too many samples
504 }
505 
506 // 2 channels, scaling from 8Bit
convertBuffersStereo8Bit(SampleType * bufDestination,const FLAC__int32 * inChannels[],uint numSamples,const uint numChannels,const uint8 numBits)507 void FLACStream::convertBuffersStereo8Bit(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
508 	assert(numChannels == 2);
509 	assert(numBits == 8);
510 	assert(numSamples % 2 == 0); // must be integral multiply of channels
511 	assert(8 < BUFTYPE_BITS);
512 
513 	FLAC__int32 const* inChannel1 = inChannels[0];	// Left Channel
514 	FLAC__int32 const* inChannel2 = inChannels[1];	// Right Channel
515 
516 	while (numSamples >= 2*2) {
517 		bufDestination[0] = static_cast<SampleType>(inChannel1[0]) << (BUFTYPE_BITS - 8);
518 		bufDestination[1] = static_cast<SampleType>(inChannel2[0]) << (BUFTYPE_BITS - 8);
519 		bufDestination[2] = static_cast<SampleType>(inChannel1[1]) << (BUFTYPE_BITS - 8);
520 		bufDestination[3] = static_cast<SampleType>(inChannel2[1]) << (BUFTYPE_BITS - 8);
521 		bufDestination += 2 * 2;
522 		inChannel1 += 2;
523 		inChannel2 += 2;
524 		numSamples -= 2 * 2;
525 	}
526 
527 	while (numSamples > 0) {
528 		bufDestination[0] = static_cast<SampleType>(*inChannel1++) << (BUFTYPE_BITS - 8);
529 		bufDestination[1] = static_cast<SampleType>(*inChannel2++) << (BUFTYPE_BITS - 8);
530 		bufDestination += 2;
531 		numSamples -= 2;
532 	}
533 
534 	inChannels[0] = inChannel1;
535 	inChannels[1] = inChannel2;
536 	assert(numSamples == 0); // dint copy too many samples
537 }
538 
539 // all Purpose-conversion - slowest of em all
convertBuffersGeneric(SampleType * bufDestination,const FLAC__int32 * inChannels[],uint numSamples,const uint numChannels,const uint8 numBits)540 void FLACStream::convertBuffersGeneric(SampleType* bufDestination, const FLAC__int32 *inChannels[], uint numSamples, const uint numChannels, const uint8 numBits) {
541 	assert(numSamples % numChannels == 0); // must be integral multiply of channels
542 
543 	if (numBits < BUFTYPE_BITS) {
544 		const uint8 kPower = (uint8)(BUFTYPE_BITS - numBits);
545 
546 		for (; numSamples > 0; numSamples -= numChannels) {
547 			for (uint i = 0; i < numChannels; ++i)
548 				*bufDestination++ = static_cast<SampleType>(*(inChannels[i]++)) << kPower;
549 		}
550 	} else if (numBits > BUFTYPE_BITS) {
551 		const uint8 kPower = (uint8)(numBits - BUFTYPE_BITS);
552 
553 		for (; numSamples > 0; numSamples -= numChannels) {
554 			for (uint i = 0; i < numChannels; ++i)
555 				*bufDestination++ = static_cast<SampleType>(*(inChannels[i]++) >> kPower);
556 		}
557 	} else {
558 		for (; numSamples > 0; numSamples -= numChannels) {
559 			for (uint i = 0; i < numChannels; ++i)
560 				*bufDestination++ = static_cast<SampleType>(*(inChannels[i]++));
561 		}
562 	}
563 
564 	assert(numSamples == 0); // dint copy too many samples
565 }
566 
callbackWrite(const::FLAC__Frame * frame,const FLAC__int32 * const buffer[])567 inline ::FLAC__StreamDecoderWriteStatus FLACStream::callbackWrite(const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[]) {
568 	assert(frame->header.channels == _streaminfo.channels);
569 	assert(frame->header.sample_rate == _streaminfo.sample_rate);
570 	assert(frame->header.bits_per_sample == _streaminfo.bits_per_sample);
571 	assert(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER || _streaminfo.min_blocksize == _streaminfo.max_blocksize);
572 
573 	// We require that either the sample cache is empty, or that no samples were requested
574 	assert(_sampleCache.bufFill == 0 || _requestedSamples == 0);
575 
576 	uint numSamples = frame->header.blocksize;
577 	const uint numChannels = getChannels();
578 	const uint8 numBits = (uint8)_streaminfo.bits_per_sample;
579 
580 	assert(_requestedSamples % numChannels == 0); // must be integral multiply of channels
581 
582 	const FLAC__uint64 firstSampleNumber = (frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER) ?
583 		frame->header.number.sample_number : (static_cast<FLAC__uint64>(frame->header.number.frame_number)) * _streaminfo.max_blocksize;
584 
585 	// Check whether we are about to reach beyond the last sample we are supposed to play.
586 	if (_lastSample != 0 && firstSampleNumber + numSamples >= _lastSample) {
587 		numSamples = (uint)(firstSampleNumber >= _lastSample ? 0 : _lastSample - firstSampleNumber);
588 		_lastSampleWritten = true;
589 	}
590 
591 	// The value in _requestedSamples counts raw samples, so if there are more than one
592 	// channel, we have to multiply the number of available sample "pairs" by numChannels
593 	numSamples *= numChannels;
594 
595 	const FLAC__int32 *inChannels[MAX_OUTPUT_CHANNELS];
596 	for (uint i = 0; i < numChannels; ++i)
597 		inChannels[i] = buffer[i];
598 
599 	// write the incoming samples directly into the buffer provided to us by the mixer
600 	if (_requestedSamples > 0) {
601 		assert(_requestedSamples % numChannels == 0);
602 		assert(_outBuffer != NULL);
603 
604 		// Copy & convert the available samples (limited both by how many we have available, and
605 		// by how many are actually needed).
606 		const uint copySamples = MIN(_requestedSamples, numSamples);
607 		(*_methodConvertBuffers)(_outBuffer, inChannels, copySamples, numChannels, numBits);
608 
609 		_requestedSamples -= copySamples;
610 		numSamples -= copySamples;
611 		_outBuffer += copySamples;
612 	}
613 
614 	// Write all remaining samples (i.e. those which didn't fit into the mixer buffer)
615 	// into the sample cache.
616 	if (_sampleCache.bufFill == 0)
617 		_sampleCache.bufReadPos = _sampleCache.bufData;
618 	const uint cacheSpace = (_sampleCache.bufData + BUFFER_SIZE) - (_sampleCache.bufReadPos + _sampleCache.bufFill);
619 	assert(numSamples <= cacheSpace);
620 	(*_methodConvertBuffers)(_sampleCache.bufReadPos + _sampleCache.bufFill, inChannels, numSamples, numChannels, numBits);
621 
622 	_sampleCache.bufFill += numSamples;
623 
624 	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
625 }
626 
callbackSeek(FLAC__uint64 absoluteByteOffset)627 inline ::FLAC__SeekableStreamDecoderSeekStatus FLACStream::callbackSeek(FLAC__uint64 absoluteByteOffset) {
628 	_inStream->seek(absoluteByteOffset, SEEK_SET);
629 	const bool result = (absoluteByteOffset == (FLAC__uint64)_inStream->pos());
630 
631 #ifdef LEGACY_FLAC
632 	return result ? FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_OK : FLAC__SEEKABLE_STREAM_DECODER_SEEK_STATUS_ERROR;
633 #else
634 	return result ? FLAC__STREAM_DECODER_SEEK_STATUS_OK : FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
635 #endif
636 }
637 
callbackTell(FLAC__uint64 * absoluteByteOffset)638 inline ::FLAC__SeekableStreamDecoderTellStatus FLACStream::callbackTell(FLAC__uint64 *absoluteByteOffset) {
639 	*absoluteByteOffset = static_cast<FLAC__uint64>(_inStream->pos());
640 #ifdef LEGACY_FLAC
641 	return FLAC__SEEKABLE_STREAM_DECODER_TELL_STATUS_OK;
642 #else
643 	return FLAC__STREAM_DECODER_TELL_STATUS_OK;
644 #endif
645 }
646 
callbackLength(FLAC__uint64 * streamLength)647 inline ::FLAC__SeekableStreamDecoderLengthStatus FLACStream::callbackLength(FLAC__uint64 *streamLength) {
648 	*streamLength = static_cast<FLAC__uint64>(_inStream->size());
649 #ifdef LEGACY_FLAC
650 	return FLAC__SEEKABLE_STREAM_DECODER_LENGTH_STATUS_OK;
651 #else
652 	return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
653 #endif
654 }
655 
callbackEOF()656 inline bool FLACStream::callbackEOF() {
657 	return _inStream->eos();
658 }
659 
660 
callbackMetadata(const::FLAC__StreamMetadata * metadata)661 inline void FLACStream::callbackMetadata(const ::FLAC__StreamMetadata *metadata) {
662 	assert(_decoder != NULL);
663 	assert(metadata->type == FLAC__METADATA_TYPE_STREAMINFO); // others arent really interesting
664 
665 	_streaminfo = metadata->data.stream_info;
666 	setBestConvertBufferMethod(); // should be set after getting stream-information. FLAC always parses the info first
667 }
callbackError(::FLAC__StreamDecoderErrorStatus status)668 inline void FLACStream::callbackError(::FLAC__StreamDecoderErrorStatus status) {
669 	// some of these are non-critical-Errors
670 	debug(1, "FLACStream: An error occurred while decoding. DecoderStateError is: %d", status);
671 }
672 
673 /* Static Callback Wrappers */
callWrapRead(const::FLAC__SeekableStreamDecoder * decoder,FLAC__byte buffer[],FLAC_size_t * bytes,void * clientData)674 ::FLAC__SeekableStreamDecoderReadStatus FLACStream::callWrapRead(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__byte buffer[], FLAC_size_t *bytes, void *clientData) {
675 	FLACStream *instance = (FLACStream *)clientData;
676 	assert(0 != instance);
677 	return instance->callbackRead(buffer, bytes);
678 }
679 
callWrapSeek(const::FLAC__SeekableStreamDecoder * decoder,FLAC__uint64 absoluteByteOffset,void * clientData)680 ::FLAC__SeekableStreamDecoderSeekStatus FLACStream::callWrapSeek(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 absoluteByteOffset, void *clientData) {
681 	FLACStream *instance = (FLACStream *)clientData;
682 	assert(0 != instance);
683 	return instance->callbackSeek(absoluteByteOffset);
684 }
685 
callWrapTell(const::FLAC__SeekableStreamDecoder * decoder,FLAC__uint64 * absoluteByteOffset,void * clientData)686 ::FLAC__SeekableStreamDecoderTellStatus FLACStream::callWrapTell(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *absoluteByteOffset, void *clientData) {
687 	FLACStream *instance = (FLACStream *)clientData;
688 	assert(0 != instance);
689 	return instance->callbackTell(absoluteByteOffset);
690 }
691 
callWrapLength(const::FLAC__SeekableStreamDecoder * decoder,FLAC__uint64 * streamLength,void * clientData)692 ::FLAC__SeekableStreamDecoderLengthStatus FLACStream::callWrapLength(const ::FLAC__SeekableStreamDecoder *decoder, FLAC__uint64 *streamLength, void *clientData) {
693 	FLACStream *instance = (FLACStream *)clientData;
694 	assert(0 != instance);
695 	return instance->callbackLength(streamLength);
696 }
697 
callWrapEOF(const::FLAC__SeekableStreamDecoder * decoder,void * clientData)698 FLAC__bool FLACStream::callWrapEOF(const ::FLAC__SeekableStreamDecoder *decoder, void *clientData) {
699 	FLACStream *instance = (FLACStream *)clientData;
700 	assert(0 != instance);
701 	return instance->callbackEOF();
702 }
703 
callWrapWrite(const::FLAC__SeekableStreamDecoder * decoder,const::FLAC__Frame * frame,const FLAC__int32 * const buffer[],void * clientData)704 ::FLAC__StreamDecoderWriteStatus FLACStream::callWrapWrite(const ::FLAC__SeekableStreamDecoder *decoder, const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *clientData) {
705 	FLACStream *instance = (FLACStream *)clientData;
706 	assert(0 != instance);
707 	return instance->callbackWrite(frame, buffer);
708 }
709 
callWrapMetadata(const::FLAC__SeekableStreamDecoder * decoder,const::FLAC__StreamMetadata * metadata,void * clientData)710 void FLACStream::callWrapMetadata(const ::FLAC__SeekableStreamDecoder *decoder, const ::FLAC__StreamMetadata *metadata, void *clientData) {
711 	FLACStream *instance = (FLACStream *)clientData;
712 	assert(0 != instance);
713 	instance->callbackMetadata(metadata);
714 }
715 
callWrapError(const::FLAC__SeekableStreamDecoder * decoder,::FLAC__StreamDecoderErrorStatus status,void * clientData)716 void FLACStream::callWrapError(const ::FLAC__SeekableStreamDecoder *decoder, ::FLAC__StreamDecoderErrorStatus status, void *clientData) {
717 	FLACStream *instance = (FLACStream *)clientData;
718 	assert(0 != instance);
719 	instance->callbackError(status);
720 }
721 
722 
723 #pragma mark -
724 #pragma mark --- FLAC factory functions ---
725 #pragma mark -
726 
makeFLACStream(Common::SeekableReadStream * stream,DisposeAfterUse::Flag disposeAfterUse)727 SeekableAudioStream *makeFLACStream(
728 	Common::SeekableReadStream *stream,
729 	DisposeAfterUse::Flag disposeAfterUse) {
730 	SeekableAudioStream *s = new FLACStream(stream, disposeAfterUse);
731 	if (s && s->endOfData()) {
732 		delete s;
733 		return 0;
734 	} else {
735 		return s;
736 	}
737 }
738 
739 } // End of namespace Audio
740 
741 #endif // #ifdef USE_FLAC
742