1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //#define LOG_NDEBUG 0
18 #define LOG_TAG "FLACExtractor"
19 #include <utils/Log.h>
20 
21 #include "include/FLACExtractor.h"
22 // Vorbis comments
23 #include "include/OggExtractor.h"
24 // libFLAC parser
25 #include "FLAC/stream_decoder.h"
26 
27 #include <media/stagefright/foundation/ADebug.h>
28 #include <media/stagefright/DataSource.h>
29 #include <media/stagefright/MediaBufferGroup.h>
30 #include <media/stagefright/MediaDefs.h>
31 #include <media/stagefright/MetaData.h>
32 #include <media/stagefright/MediaSource.h>
33 #include <media/stagefright/MediaBuffer.h>
34 
35 namespace android {
36 
37 class FLACParser;
38 
39 class FLACSource : public MediaSource {
40 
41 public:
42     FLACSource(
43             const sp<DataSource> &dataSource,
44             const sp<MetaData> &trackMetadata);
45 
46     virtual status_t start(MetaData *params);
47     virtual status_t stop();
48     virtual sp<MetaData> getFormat();
49 
50     virtual status_t read(
51             MediaBuffer **buffer, const ReadOptions *options = NULL);
52 
53 protected:
54     virtual ~FLACSource();
55 
56 private:
57     sp<DataSource> mDataSource;
58     sp<MetaData> mTrackMetadata;
59     sp<FLACParser> mParser;
60     bool mInitCheck;
61     bool mStarted;
62 
63     status_t init();
64 
65     // no copy constructor or assignment
66     FLACSource(const FLACSource &);
67     FLACSource &operator=(const FLACSource &);
68 
69 };
70 
71 // FLACParser wraps a C libFLAC parser aka stream decoder
72 
73 class FLACParser : public RefBase {
74 
75 public:
76     FLACParser(
77         const sp<DataSource> &dataSource,
78         // If metadata pointers aren't provided, we don't fill them
79         const sp<MetaData> &fileMetadata = 0,
80         const sp<MetaData> &trackMetadata = 0);
81 
initCheck() const82     status_t initCheck() const {
83         return mInitCheck;
84     }
85 
86     // stream properties
getMaxBlockSize() const87     unsigned getMaxBlockSize() const {
88         return mStreamInfo.max_blocksize;
89     }
getSampleRate() const90     unsigned getSampleRate() const {
91         return mStreamInfo.sample_rate;
92     }
getChannels() const93     unsigned getChannels() const {
94         return mStreamInfo.channels;
95     }
getBitsPerSample() const96     unsigned getBitsPerSample() const {
97         return mStreamInfo.bits_per_sample;
98     }
getTotalSamples() const99     FLAC__uint64 getTotalSamples() const {
100         return mStreamInfo.total_samples;
101     }
102 
103     // media buffers
104     void allocateBuffers();
105     void releaseBuffers();
readBuffer()106     MediaBuffer *readBuffer() {
107         return readBuffer(false, 0LL);
108     }
readBuffer(FLAC__uint64 sample)109     MediaBuffer *readBuffer(FLAC__uint64 sample) {
110         return readBuffer(true, sample);
111     }
112 
113 protected:
114     virtual ~FLACParser();
115 
116 private:
117     sp<DataSource> mDataSource;
118     sp<MetaData> mFileMetadata;
119     sp<MetaData> mTrackMetadata;
120     bool mInitCheck;
121 
122     // media buffers
123     size_t mMaxBufferSize;
124     MediaBufferGroup *mGroup;
125     void (*mCopy)(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels);
126 
127     // handle to underlying libFLAC parser
128     FLAC__StreamDecoder *mDecoder;
129 
130     // current position within the data source
131     off64_t mCurrentPos;
132     bool mEOF;
133 
134     // cached when the STREAMINFO metadata is parsed by libFLAC
135     FLAC__StreamMetadata_StreamInfo mStreamInfo;
136     bool mStreamInfoValid;
137 
138     // cached when a decoded PCM block is "written" by libFLAC parser
139     bool mWriteRequested;
140     bool mWriteCompleted;
141     FLAC__FrameHeader mWriteHeader;
142     const FLAC__int32 * const *mWriteBuffer;
143 
144     // most recent error reported by libFLAC parser
145     FLAC__StreamDecoderErrorStatus mErrorStatus;
146 
147     status_t init();
148     MediaBuffer *readBuffer(bool doSeek, FLAC__uint64 sample);
149 
150     // no copy constructor or assignment
151     FLACParser(const FLACParser &);
152     FLACParser &operator=(const FLACParser &);
153 
154     // FLAC parser callbacks as C++ instance methods
155     FLAC__StreamDecoderReadStatus readCallback(
156             FLAC__byte buffer[], size_t *bytes);
157     FLAC__StreamDecoderSeekStatus seekCallback(
158             FLAC__uint64 absolute_byte_offset);
159     FLAC__StreamDecoderTellStatus tellCallback(
160             FLAC__uint64 *absolute_byte_offset);
161     FLAC__StreamDecoderLengthStatus lengthCallback(
162             FLAC__uint64 *stream_length);
163     FLAC__bool eofCallback();
164     FLAC__StreamDecoderWriteStatus writeCallback(
165             const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
166     void metadataCallback(const FLAC__StreamMetadata *metadata);
167     void errorCallback(FLAC__StreamDecoderErrorStatus status);
168 
169     // FLAC parser callbacks as C-callable functions
170     static FLAC__StreamDecoderReadStatus read_callback(
171             const FLAC__StreamDecoder *decoder,
172             FLAC__byte buffer[], size_t *bytes,
173             void *client_data);
174     static FLAC__StreamDecoderSeekStatus seek_callback(
175             const FLAC__StreamDecoder *decoder,
176             FLAC__uint64 absolute_byte_offset,
177             void *client_data);
178     static FLAC__StreamDecoderTellStatus tell_callback(
179             const FLAC__StreamDecoder *decoder,
180             FLAC__uint64 *absolute_byte_offset,
181             void *client_data);
182     static FLAC__StreamDecoderLengthStatus length_callback(
183             const FLAC__StreamDecoder *decoder,
184             FLAC__uint64 *stream_length,
185             void *client_data);
186     static FLAC__bool eof_callback(
187             const FLAC__StreamDecoder *decoder,
188             void *client_data);
189     static FLAC__StreamDecoderWriteStatus write_callback(
190             const FLAC__StreamDecoder *decoder,
191             const FLAC__Frame *frame, const FLAC__int32 * const buffer[],
192             void *client_data);
193     static void metadata_callback(
194             const FLAC__StreamDecoder *decoder,
195             const FLAC__StreamMetadata *metadata,
196             void *client_data);
197     static void error_callback(
198             const FLAC__StreamDecoder *decoder,
199             FLAC__StreamDecoderErrorStatus status,
200             void *client_data);
201 
202 };
203 
204 // The FLAC parser calls our C++ static callbacks using C calling conventions,
205 // inside FLAC__stream_decoder_process_until_end_of_metadata
206 // and FLAC__stream_decoder_process_single.
207 // We immediately then call our corresponding C++ instance methods
208 // with the same parameter list, but discard redundant information.
209 
read_callback(const FLAC__StreamDecoder *,FLAC__byte buffer[],size_t * bytes,void * client_data)210 FLAC__StreamDecoderReadStatus FLACParser::read_callback(
211         const FLAC__StreamDecoder * /* decoder */, FLAC__byte buffer[],
212         size_t *bytes, void *client_data)
213 {
214     return ((FLACParser *) client_data)->readCallback(buffer, bytes);
215 }
216 
seek_callback(const FLAC__StreamDecoder *,FLAC__uint64 absolute_byte_offset,void * client_data)217 FLAC__StreamDecoderSeekStatus FLACParser::seek_callback(
218         const FLAC__StreamDecoder * /* decoder */,
219         FLAC__uint64 absolute_byte_offset, void *client_data)
220 {
221     return ((FLACParser *) client_data)->seekCallback(absolute_byte_offset);
222 }
223 
tell_callback(const FLAC__StreamDecoder *,FLAC__uint64 * absolute_byte_offset,void * client_data)224 FLAC__StreamDecoderTellStatus FLACParser::tell_callback(
225         const FLAC__StreamDecoder * /* decoder */,
226         FLAC__uint64 *absolute_byte_offset, void *client_data)
227 {
228     return ((FLACParser *) client_data)->tellCallback(absolute_byte_offset);
229 }
230 
length_callback(const FLAC__StreamDecoder *,FLAC__uint64 * stream_length,void * client_data)231 FLAC__StreamDecoderLengthStatus FLACParser::length_callback(
232         const FLAC__StreamDecoder * /* decoder */,
233         FLAC__uint64 *stream_length, void *client_data)
234 {
235     return ((FLACParser *) client_data)->lengthCallback(stream_length);
236 }
237 
eof_callback(const FLAC__StreamDecoder *,void * client_data)238 FLAC__bool FLACParser::eof_callback(
239         const FLAC__StreamDecoder * /* decoder */, void *client_data)
240 {
241     return ((FLACParser *) client_data)->eofCallback();
242 }
243 
write_callback(const FLAC__StreamDecoder *,const FLAC__Frame * frame,const FLAC__int32 * const buffer[],void * client_data)244 FLAC__StreamDecoderWriteStatus FLACParser::write_callback(
245         const FLAC__StreamDecoder * /* decoder */, const FLAC__Frame *frame,
246         const FLAC__int32 * const buffer[], void *client_data)
247 {
248     return ((FLACParser *) client_data)->writeCallback(frame, buffer);
249 }
250 
metadata_callback(const FLAC__StreamDecoder *,const FLAC__StreamMetadata * metadata,void * client_data)251 void FLACParser::metadata_callback(
252         const FLAC__StreamDecoder * /* decoder */,
253         const FLAC__StreamMetadata *metadata, void *client_data)
254 {
255     ((FLACParser *) client_data)->metadataCallback(metadata);
256 }
257 
error_callback(const FLAC__StreamDecoder *,FLAC__StreamDecoderErrorStatus status,void * client_data)258 void FLACParser::error_callback(
259         const FLAC__StreamDecoder * /* decoder */,
260         FLAC__StreamDecoderErrorStatus status, void *client_data)
261 {
262     ((FLACParser *) client_data)->errorCallback(status);
263 }
264 
265 // These are the corresponding callbacks with C++ calling conventions
266 
readCallback(FLAC__byte buffer[],size_t * bytes)267 FLAC__StreamDecoderReadStatus FLACParser::readCallback(
268         FLAC__byte buffer[], size_t *bytes)
269 {
270     size_t requested = *bytes;
271     ssize_t actual = mDataSource->readAt(mCurrentPos, buffer, requested);
272     if (0 > actual) {
273         *bytes = 0;
274         return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
275     } else if (0 == actual) {
276         *bytes = 0;
277         mEOF = true;
278         return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
279     } else {
280         assert(actual <= requested);
281         *bytes = actual;
282         mCurrentPos += actual;
283         return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
284     }
285 }
286 
seekCallback(FLAC__uint64 absolute_byte_offset)287 FLAC__StreamDecoderSeekStatus FLACParser::seekCallback(
288         FLAC__uint64 absolute_byte_offset)
289 {
290     mCurrentPos = absolute_byte_offset;
291     mEOF = false;
292     return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
293 }
294 
tellCallback(FLAC__uint64 * absolute_byte_offset)295 FLAC__StreamDecoderTellStatus FLACParser::tellCallback(
296         FLAC__uint64 *absolute_byte_offset)
297 {
298     *absolute_byte_offset = mCurrentPos;
299     return FLAC__STREAM_DECODER_TELL_STATUS_OK;
300 }
301 
lengthCallback(FLAC__uint64 * stream_length)302 FLAC__StreamDecoderLengthStatus FLACParser::lengthCallback(
303         FLAC__uint64 *stream_length)
304 {
305     off64_t size;
306     if (OK == mDataSource->getSize(&size)) {
307         *stream_length = size;
308         return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
309     } else {
310         return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
311     }
312 }
313 
eofCallback()314 FLAC__bool FLACParser::eofCallback()
315 {
316     return mEOF;
317 }
318 
writeCallback(const FLAC__Frame * frame,const FLAC__int32 * const buffer[])319 FLAC__StreamDecoderWriteStatus FLACParser::writeCallback(
320         const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
321 {
322     if (mWriteRequested) {
323         mWriteRequested = false;
324         // FLAC parser doesn't free or realloc buffer until next frame or finish
325         mWriteHeader = frame->header;
326         mWriteBuffer = buffer;
327         mWriteCompleted = true;
328         return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
329     } else {
330         ALOGE("FLACParser::writeCallback unexpected");
331         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
332     }
333 }
334 
metadataCallback(const FLAC__StreamMetadata * metadata)335 void FLACParser::metadataCallback(const FLAC__StreamMetadata *metadata)
336 {
337     switch (metadata->type) {
338     case FLAC__METADATA_TYPE_STREAMINFO:
339         if (!mStreamInfoValid) {
340             mStreamInfo = metadata->data.stream_info;
341             mStreamInfoValid = true;
342         } else {
343             ALOGE("FLACParser::metadataCallback unexpected STREAMINFO");
344         }
345         break;
346     case FLAC__METADATA_TYPE_VORBIS_COMMENT:
347         {
348         const FLAC__StreamMetadata_VorbisComment *vc;
349         vc = &metadata->data.vorbis_comment;
350         for (FLAC__uint32 i = 0; i < vc->num_comments; ++i) {
351             FLAC__StreamMetadata_VorbisComment_Entry *vce;
352             vce = &vc->comments[i];
353             if (mFileMetadata != 0 && vce->entry != NULL) {
354                 parseVorbisComment(mFileMetadata, (const char *) vce->entry,
355                         vce->length);
356             }
357         }
358         }
359         break;
360     case FLAC__METADATA_TYPE_PICTURE:
361         if (mFileMetadata != 0) {
362             const FLAC__StreamMetadata_Picture *p = &metadata->data.picture;
363             mFileMetadata->setData(kKeyAlbumArt,
364                     MetaData::TYPE_NONE, p->data, p->data_length);
365             mFileMetadata->setCString(kKeyAlbumArtMIME, p->mime_type);
366         }
367         break;
368     default:
369         ALOGW("FLACParser::metadataCallback unexpected type %u", metadata->type);
370         break;
371     }
372 }
373 
errorCallback(FLAC__StreamDecoderErrorStatus status)374 void FLACParser::errorCallback(FLAC__StreamDecoderErrorStatus status)
375 {
376     ALOGE("FLACParser::errorCallback status=%d", status);
377     mErrorStatus = status;
378 }
379 
380 // Copy samples from FLAC native 32-bit non-interleaved to 16-bit interleaved.
381 // These are candidates for optimization if needed.
382 
copyMono8(short * dst,const int * const * src,unsigned nSamples,unsigned)383 static void copyMono8(
384         short *dst,
385         const int *const *src,
386         unsigned nSamples,
387         unsigned /* nChannels */) {
388     for (unsigned i = 0; i < nSamples; ++i) {
389         *dst++ = src[0][i] << 8;
390     }
391 }
392 
copyStereo8(short * dst,const int * const * src,unsigned nSamples,unsigned)393 static void copyStereo8(
394         short *dst,
395         const int *const *src,
396         unsigned nSamples,
397         unsigned /* nChannels */) {
398     for (unsigned i = 0; i < nSamples; ++i) {
399         *dst++ = src[0][i] << 8;
400         *dst++ = src[1][i] << 8;
401     }
402 }
403 
copyMultiCh8(short * dst,const int * const * src,unsigned nSamples,unsigned nChannels)404 static void copyMultiCh8(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
405 {
406     for (unsigned i = 0; i < nSamples; ++i) {
407         for (unsigned c = 0; c < nChannels; ++c) {
408             *dst++ = src[c][i] << 8;
409         }
410     }
411 }
412 
copyMono16(short * dst,const int * const * src,unsigned nSamples,unsigned)413 static void copyMono16(
414         short *dst,
415         const int *const *src,
416         unsigned nSamples,
417         unsigned /* nChannels */) {
418     for (unsigned i = 0; i < nSamples; ++i) {
419         *dst++ = src[0][i];
420     }
421 }
422 
copyStereo16(short * dst,const int * const * src,unsigned nSamples,unsigned)423 static void copyStereo16(
424         short *dst,
425         const int *const *src,
426         unsigned nSamples,
427         unsigned /* nChannels */) {
428     for (unsigned i = 0; i < nSamples; ++i) {
429         *dst++ = src[0][i];
430         *dst++ = src[1][i];
431     }
432 }
433 
copyMultiCh16(short * dst,const int * const * src,unsigned nSamples,unsigned nChannels)434 static void copyMultiCh16(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
435 {
436     for (unsigned i = 0; i < nSamples; ++i) {
437         for (unsigned c = 0; c < nChannels; ++c) {
438             *dst++ = src[c][i];
439         }
440     }
441 }
442 
443 // 24-bit versions should do dithering or noise-shaping, here or in AudioFlinger
444 
copyMono24(short * dst,const int * const * src,unsigned nSamples,unsigned)445 static void copyMono24(
446         short *dst,
447         const int *const *src,
448         unsigned nSamples,
449         unsigned /* nChannels */) {
450     for (unsigned i = 0; i < nSamples; ++i) {
451         *dst++ = src[0][i] >> 8;
452     }
453 }
454 
copyStereo24(short * dst,const int * const * src,unsigned nSamples,unsigned)455 static void copyStereo24(
456         short *dst,
457         const int *const *src,
458         unsigned nSamples,
459         unsigned /* nChannels */) {
460     for (unsigned i = 0; i < nSamples; ++i) {
461         *dst++ = src[0][i] >> 8;
462         *dst++ = src[1][i] >> 8;
463     }
464 }
465 
copyMultiCh24(short * dst,const int * const * src,unsigned nSamples,unsigned nChannels)466 static void copyMultiCh24(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels)
467 {
468     for (unsigned i = 0; i < nSamples; ++i) {
469         for (unsigned c = 0; c < nChannels; ++c) {
470             *dst++ = src[c][i] >> 8;
471         }
472     }
473 }
474 
copyTrespass(short *,const int * const *,unsigned,unsigned)475 static void copyTrespass(
476         short * /* dst */,
477         const int *const * /* src */,
478         unsigned /* nSamples */,
479         unsigned /* nChannels */) {
480     TRESPASS();
481 }
482 
483 // FLACParser
484 
FLACParser(const sp<DataSource> & dataSource,const sp<MetaData> & fileMetadata,const sp<MetaData> & trackMetadata)485 FLACParser::FLACParser(
486         const sp<DataSource> &dataSource,
487         const sp<MetaData> &fileMetadata,
488         const sp<MetaData> &trackMetadata)
489     : mDataSource(dataSource),
490       mFileMetadata(fileMetadata),
491       mTrackMetadata(trackMetadata),
492       mInitCheck(false),
493       mMaxBufferSize(0),
494       mGroup(NULL),
495       mCopy(copyTrespass),
496       mDecoder(NULL),
497       mCurrentPos(0LL),
498       mEOF(false),
499       mStreamInfoValid(false),
500       mWriteRequested(false),
501       mWriteCompleted(false),
502       mWriteBuffer(NULL),
503       mErrorStatus((FLAC__StreamDecoderErrorStatus) -1)
504 {
505     ALOGV("FLACParser::FLACParser");
506     memset(&mStreamInfo, 0, sizeof(mStreamInfo));
507     memset(&mWriteHeader, 0, sizeof(mWriteHeader));
508     mInitCheck = init();
509 }
510 
~FLACParser()511 FLACParser::~FLACParser()
512 {
513     ALOGV("FLACParser::~FLACParser");
514     if (mDecoder != NULL) {
515         FLAC__stream_decoder_delete(mDecoder);
516         mDecoder = NULL;
517     }
518 }
519 
init()520 status_t FLACParser::init()
521 {
522     // setup libFLAC parser
523     mDecoder = FLAC__stream_decoder_new();
524     if (mDecoder == NULL) {
525         // The new should succeed, since probably all it does is a malloc
526         // that always succeeds in Android.  But to avoid dependence on the
527         // libFLAC internals, we check and log here.
528         ALOGE("new failed");
529         return NO_INIT;
530     }
531     FLAC__stream_decoder_set_md5_checking(mDecoder, false);
532     FLAC__stream_decoder_set_metadata_ignore_all(mDecoder);
533     FLAC__stream_decoder_set_metadata_respond(
534             mDecoder, FLAC__METADATA_TYPE_STREAMINFO);
535     FLAC__stream_decoder_set_metadata_respond(
536             mDecoder, FLAC__METADATA_TYPE_PICTURE);
537     FLAC__stream_decoder_set_metadata_respond(
538             mDecoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
539     FLAC__StreamDecoderInitStatus initStatus;
540     initStatus = FLAC__stream_decoder_init_stream(
541             mDecoder,
542             read_callback, seek_callback, tell_callback,
543             length_callback, eof_callback, write_callback,
544             metadata_callback, error_callback, (void *) this);
545     if (initStatus != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
546         // A failure here probably indicates a programming error and so is
547         // unlikely to happen. But we check and log here similarly to above.
548         ALOGE("init_stream failed %d", initStatus);
549         return NO_INIT;
550     }
551     // parse all metadata
552     if (!FLAC__stream_decoder_process_until_end_of_metadata(mDecoder)) {
553         ALOGE("end_of_metadata failed");
554         return NO_INIT;
555     }
556     if (mStreamInfoValid) {
557         // check channel count
558         if (getChannels() == 0 || getChannels() > 8) {
559             ALOGE("unsupported channel count %u", getChannels());
560             return NO_INIT;
561         }
562         // check bit depth
563         switch (getBitsPerSample()) {
564         case 8:
565         case 16:
566         case 24:
567             break;
568         default:
569             ALOGE("unsupported bits per sample %u", getBitsPerSample());
570             return NO_INIT;
571         }
572         // check sample rate
573         switch (getSampleRate()) {
574         case  8000:
575         case 11025:
576         case 12000:
577         case 16000:
578         case 22050:
579         case 24000:
580         case 32000:
581         case 44100:
582         case 48000:
583         case 88200:
584         case 96000:
585             break;
586         default:
587             ALOGE("unsupported sample rate %u", getSampleRate());
588             return NO_INIT;
589         }
590         // configure the appropriate copy function, defaulting to trespass
591         static const struct {
592             unsigned mChannels;
593             unsigned mBitsPerSample;
594             void (*mCopy)(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels);
595         } table[] = {
596             { 1,  8, copyMono8    },
597             { 2,  8, copyStereo8  },
598             { 8,  8, copyMultiCh8  },
599             { 1, 16, copyMono16   },
600             { 2, 16, copyStereo16 },
601             { 8, 16, copyMultiCh16 },
602             { 1, 24, copyMono24   },
603             { 2, 24, copyStereo24 },
604             { 8, 24, copyMultiCh24 },
605         };
606         for (unsigned i = 0; i < sizeof(table)/sizeof(table[0]); ++i) {
607             if (table[i].mChannels >= getChannels() &&
608                     table[i].mBitsPerSample == getBitsPerSample()) {
609                 mCopy = table[i].mCopy;
610                 break;
611             }
612         }
613         // populate track metadata
614         if (mTrackMetadata != 0) {
615             mTrackMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
616             mTrackMetadata->setInt32(kKeyChannelCount, getChannels());
617             mTrackMetadata->setInt32(kKeySampleRate, getSampleRate());
618             mTrackMetadata->setInt32(kKeyPcmEncoding, kAudioEncodingPcm16bit);
619             // sample rate is non-zero, so division by zero not possible
620             mTrackMetadata->setInt64(kKeyDuration,
621                     (getTotalSamples() * 1000000LL) / getSampleRate());
622         }
623     } else {
624         ALOGE("missing STREAMINFO");
625         return NO_INIT;
626     }
627     if (mFileMetadata != 0) {
628         mFileMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_FLAC);
629     }
630     return OK;
631 }
632 
allocateBuffers()633 void FLACParser::allocateBuffers()
634 {
635     CHECK(mGroup == NULL);
636     mGroup = new MediaBufferGroup;
637     mMaxBufferSize = getMaxBlockSize() * getChannels() * sizeof(short);
638     mGroup->add_buffer(new MediaBuffer(mMaxBufferSize));
639 }
640 
releaseBuffers()641 void FLACParser::releaseBuffers()
642 {
643     CHECK(mGroup != NULL);
644     delete mGroup;
645     mGroup = NULL;
646 }
647 
readBuffer(bool doSeek,FLAC__uint64 sample)648 MediaBuffer *FLACParser::readBuffer(bool doSeek, FLAC__uint64 sample)
649 {
650     mWriteRequested = true;
651     mWriteCompleted = false;
652     if (doSeek) {
653         // We implement the seek callback, so this works without explicit flush
654         if (!FLAC__stream_decoder_seek_absolute(mDecoder, sample)) {
655             ALOGE("FLACParser::readBuffer seek to sample %lld failed", (long long)sample);
656             return NULL;
657         }
658         ALOGV("FLACParser::readBuffer seek to sample %lld succeeded", (long long)sample);
659     } else {
660         if (!FLAC__stream_decoder_process_single(mDecoder)) {
661             ALOGE("FLACParser::readBuffer process_single failed");
662             return NULL;
663         }
664     }
665     if (!mWriteCompleted) {
666         ALOGV("FLACParser::readBuffer write did not complete");
667         return NULL;
668     }
669     // verify that block header keeps the promises made by STREAMINFO
670     unsigned blocksize = mWriteHeader.blocksize;
671     if (blocksize == 0 || blocksize > getMaxBlockSize()) {
672         ALOGE("FLACParser::readBuffer write invalid blocksize %u", blocksize);
673         return NULL;
674     }
675     if (mWriteHeader.sample_rate != getSampleRate() ||
676         mWriteHeader.channels != getChannels() ||
677         mWriteHeader.bits_per_sample != getBitsPerSample()) {
678         ALOGE("FLACParser::readBuffer write changed parameters mid-stream: %d/%d/%d -> %d/%d/%d",
679                 getSampleRate(), getChannels(), getBitsPerSample(),
680                 mWriteHeader.sample_rate, mWriteHeader.channels, mWriteHeader.bits_per_sample);
681         return NULL;
682     }
683     // acquire a media buffer
684     CHECK(mGroup != NULL);
685     MediaBuffer *buffer;
686     status_t err = mGroup->acquire_buffer(&buffer);
687     if (err != OK) {
688         return NULL;
689     }
690     size_t bufferSize = blocksize * getChannels() * sizeof(short);
691     CHECK(bufferSize <= mMaxBufferSize);
692     short *data = (short *) buffer->data();
693     buffer->set_range(0, bufferSize);
694     // copy PCM from FLAC write buffer to our media buffer, with interleaving
695     (*mCopy)(data, mWriteBuffer, blocksize, getChannels());
696     // fill in buffer metadata
697     CHECK(mWriteHeader.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
698     FLAC__uint64 sampleNumber = mWriteHeader.number.sample_number;
699     int64_t timeUs = (1000000LL * sampleNumber) / getSampleRate();
700     buffer->meta_data()->setInt64(kKeyTime, timeUs);
701     buffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
702     return buffer;
703 }
704 
705 // FLACsource
706 
FLACSource(const sp<DataSource> & dataSource,const sp<MetaData> & trackMetadata)707 FLACSource::FLACSource(
708         const sp<DataSource> &dataSource,
709         const sp<MetaData> &trackMetadata)
710     : mDataSource(dataSource),
711       mTrackMetadata(trackMetadata),
712       mParser(0),
713       mInitCheck(false),
714       mStarted(false)
715 {
716     ALOGV("FLACSource::FLACSource");
717     mInitCheck = init();
718 }
719 
~FLACSource()720 FLACSource::~FLACSource()
721 {
722     ALOGV("~FLACSource::FLACSource");
723     if (mStarted) {
724         stop();
725     }
726 }
727 
start(MetaData *)728 status_t FLACSource::start(MetaData * /* params */)
729 {
730     ALOGV("FLACSource::start");
731 
732     CHECK(!mStarted);
733     mParser->allocateBuffers();
734     mStarted = true;
735 
736     return OK;
737 }
738 
stop()739 status_t FLACSource::stop()
740 {
741     ALOGV("FLACSource::stop");
742 
743     CHECK(mStarted);
744     mParser->releaseBuffers();
745     mStarted = false;
746 
747     return OK;
748 }
749 
getFormat()750 sp<MetaData> FLACSource::getFormat()
751 {
752     return mTrackMetadata;
753 }
754 
read(MediaBuffer ** outBuffer,const ReadOptions * options)755 status_t FLACSource::read(
756         MediaBuffer **outBuffer, const ReadOptions *options)
757 {
758     MediaBuffer *buffer;
759     // process an optional seek request
760     int64_t seekTimeUs;
761     ReadOptions::SeekMode mode;
762     if ((NULL != options) && options->getSeekTo(&seekTimeUs, &mode)) {
763         FLAC__uint64 sample;
764         if (seekTimeUs <= 0LL) {
765             sample = 0LL;
766         } else {
767             // sample and total samples are both zero-based, and seek to EOF ok
768             sample = (seekTimeUs * mParser->getSampleRate()) / 1000000LL;
769             if (sample >= mParser->getTotalSamples()) {
770                 sample = mParser->getTotalSamples();
771             }
772         }
773         buffer = mParser->readBuffer(sample);
774     // otherwise read sequentially
775     } else {
776         buffer = mParser->readBuffer();
777     }
778     *outBuffer = buffer;
779     return buffer != NULL ? (status_t) OK : (status_t) ERROR_END_OF_STREAM;
780 }
781 
init()782 status_t FLACSource::init()
783 {
784     ALOGV("FLACSource::init");
785     // re-use the same track metadata passed into constructor from FLACExtractor
786     mParser = new FLACParser(mDataSource);
787     return mParser->initCheck();
788 }
789 
790 // FLACExtractor
791 
FLACExtractor(const sp<DataSource> & dataSource)792 FLACExtractor::FLACExtractor(
793         const sp<DataSource> &dataSource)
794     : mDataSource(dataSource),
795       mInitCheck(false)
796 {
797     ALOGV("FLACExtractor::FLACExtractor");
798     mInitCheck = init();
799 }
800 
~FLACExtractor()801 FLACExtractor::~FLACExtractor()
802 {
803     ALOGV("~FLACExtractor::FLACExtractor");
804 }
805 
countTracks()806 size_t FLACExtractor::countTracks()
807 {
808     return mInitCheck == OK ? 1 : 0;
809 }
810 
getTrack(size_t index)811 sp<IMediaSource> FLACExtractor::getTrack(size_t index)
812 {
813     if (mInitCheck != OK || index > 0) {
814         return NULL;
815     }
816     return new FLACSource(mDataSource, mTrackMetadata);
817 }
818 
getTrackMetaData(size_t index,uint32_t)819 sp<MetaData> FLACExtractor::getTrackMetaData(
820         size_t index, uint32_t /* flags */) {
821     if (mInitCheck != OK || index > 0) {
822         return NULL;
823     }
824     return mTrackMetadata;
825 }
826 
init()827 status_t FLACExtractor::init()
828 {
829     mFileMetadata = new MetaData;
830     mTrackMetadata = new MetaData;
831     // FLACParser will fill in the metadata for us
832     mParser = new FLACParser(mDataSource, mFileMetadata, mTrackMetadata);
833     return mParser->initCheck();
834 }
835 
getMetaData()836 sp<MetaData> FLACExtractor::getMetaData()
837 {
838     return mFileMetadata;
839 }
840 
841 // Sniffer
842 
SniffFLAC(const sp<DataSource> & source,String8 * mimeType,float * confidence,sp<AMessage> *)843 bool SniffFLAC(
844         const sp<DataSource> &source, String8 *mimeType, float *confidence,
845         sp<AMessage> *)
846 {
847     // first 4 is the signature word
848     // second 4 is the sizeof STREAMINFO
849     // 042 is the mandatory STREAMINFO
850     // no need to read rest of the header, as a premature EOF will be caught later
851     uint8_t header[4+4];
852     if (source->readAt(0, header, sizeof(header)) != sizeof(header)
853             || memcmp("fLaC\0\0\0\042", header, 4+4))
854     {
855         return false;
856     }
857 
858     *mimeType = MEDIA_MIMETYPE_AUDIO_FLAC;
859     *confidence = 0.5;
860 
861     return true;
862 }
863 
864 }  // namespace android
865