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             // sample rate is non-zero, so division by zero not possible
619             mTrackMetadata->setInt64(kKeyDuration,
620                     (getTotalSamples() * 1000000LL) / getSampleRate());
621         }
622     } else {
623         ALOGE("missing STREAMINFO");
624         return NO_INIT;
625     }
626     if (mFileMetadata != 0) {
627         mFileMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_FLAC);
628     }
629     return OK;
630 }
631 
allocateBuffers()632 void FLACParser::allocateBuffers()
633 {
634     CHECK(mGroup == NULL);
635     mGroup = new MediaBufferGroup;
636     mMaxBufferSize = getMaxBlockSize() * getChannels() * sizeof(short);
637     mGroup->add_buffer(new MediaBuffer(mMaxBufferSize));
638 }
639 
releaseBuffers()640 void FLACParser::releaseBuffers()
641 {
642     CHECK(mGroup != NULL);
643     delete mGroup;
644     mGroup = NULL;
645 }
646 
readBuffer(bool doSeek,FLAC__uint64 sample)647 MediaBuffer *FLACParser::readBuffer(bool doSeek, FLAC__uint64 sample)
648 {
649     mWriteRequested = true;
650     mWriteCompleted = false;
651     if (doSeek) {
652         // We implement the seek callback, so this works without explicit flush
653         if (!FLAC__stream_decoder_seek_absolute(mDecoder, sample)) {
654             ALOGE("FLACParser::readBuffer seek to sample %lld failed", (long long)sample);
655             return NULL;
656         }
657         ALOGV("FLACParser::readBuffer seek to sample %lld succeeded", (long long)sample);
658     } else {
659         if (!FLAC__stream_decoder_process_single(mDecoder)) {
660             ALOGE("FLACParser::readBuffer process_single failed");
661             return NULL;
662         }
663     }
664     if (!mWriteCompleted) {
665         ALOGV("FLACParser::readBuffer write did not complete");
666         return NULL;
667     }
668     // verify that block header keeps the promises made by STREAMINFO
669     unsigned blocksize = mWriteHeader.blocksize;
670     if (blocksize == 0 || blocksize > getMaxBlockSize()) {
671         ALOGE("FLACParser::readBuffer write invalid blocksize %u", blocksize);
672         return NULL;
673     }
674     if (mWriteHeader.sample_rate != getSampleRate() ||
675         mWriteHeader.channels != getChannels() ||
676         mWriteHeader.bits_per_sample != getBitsPerSample()) {
677         ALOGE("FLACParser::readBuffer write changed parameters mid-stream: %d/%d/%d -> %d/%d/%d",
678                 getSampleRate(), getChannels(), getBitsPerSample(),
679                 mWriteHeader.sample_rate, mWriteHeader.channels, mWriteHeader.bits_per_sample);
680         return NULL;
681     }
682     // acquire a media buffer
683     CHECK(mGroup != NULL);
684     MediaBuffer *buffer;
685     status_t err = mGroup->acquire_buffer(&buffer);
686     if (err != OK) {
687         return NULL;
688     }
689     size_t bufferSize = blocksize * getChannels() * sizeof(short);
690     CHECK(bufferSize <= mMaxBufferSize);
691     short *data = (short *) buffer->data();
692     buffer->set_range(0, bufferSize);
693     // copy PCM from FLAC write buffer to our media buffer, with interleaving
694     (*mCopy)(data, mWriteBuffer, blocksize, getChannels());
695     // fill in buffer metadata
696     CHECK(mWriteHeader.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
697     FLAC__uint64 sampleNumber = mWriteHeader.number.sample_number;
698     int64_t timeUs = (1000000LL * sampleNumber) / getSampleRate();
699     buffer->meta_data()->setInt64(kKeyTime, timeUs);
700     buffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
701     return buffer;
702 }
703 
704 // FLACsource
705 
FLACSource(const sp<DataSource> & dataSource,const sp<MetaData> & trackMetadata)706 FLACSource::FLACSource(
707         const sp<DataSource> &dataSource,
708         const sp<MetaData> &trackMetadata)
709     : mDataSource(dataSource),
710       mTrackMetadata(trackMetadata),
711       mParser(0),
712       mInitCheck(false),
713       mStarted(false)
714 {
715     ALOGV("FLACSource::FLACSource");
716     mInitCheck = init();
717 }
718 
~FLACSource()719 FLACSource::~FLACSource()
720 {
721     ALOGV("~FLACSource::FLACSource");
722     if (mStarted) {
723         stop();
724     }
725 }
726 
start(MetaData *)727 status_t FLACSource::start(MetaData * /* params */)
728 {
729     ALOGV("FLACSource::start");
730 
731     CHECK(!mStarted);
732     mParser->allocateBuffers();
733     mStarted = true;
734 
735     return OK;
736 }
737 
stop()738 status_t FLACSource::stop()
739 {
740     ALOGV("FLACSource::stop");
741 
742     CHECK(mStarted);
743     mParser->releaseBuffers();
744     mStarted = false;
745 
746     return OK;
747 }
748 
getFormat()749 sp<MetaData> FLACSource::getFormat()
750 {
751     return mTrackMetadata;
752 }
753 
read(MediaBuffer ** outBuffer,const ReadOptions * options)754 status_t FLACSource::read(
755         MediaBuffer **outBuffer, const ReadOptions *options)
756 {
757     MediaBuffer *buffer;
758     // process an optional seek request
759     int64_t seekTimeUs;
760     ReadOptions::SeekMode mode;
761     if ((NULL != options) && options->getSeekTo(&seekTimeUs, &mode)) {
762         FLAC__uint64 sample;
763         if (seekTimeUs <= 0LL) {
764             sample = 0LL;
765         } else {
766             // sample and total samples are both zero-based, and seek to EOF ok
767             sample = (seekTimeUs * mParser->getSampleRate()) / 1000000LL;
768             if (sample >= mParser->getTotalSamples()) {
769                 sample = mParser->getTotalSamples();
770             }
771         }
772         buffer = mParser->readBuffer(sample);
773     // otherwise read sequentially
774     } else {
775         buffer = mParser->readBuffer();
776     }
777     *outBuffer = buffer;
778     return buffer != NULL ? (status_t) OK : (status_t) ERROR_END_OF_STREAM;
779 }
780 
init()781 status_t FLACSource::init()
782 {
783     ALOGV("FLACSource::init");
784     // re-use the same track metadata passed into constructor from FLACExtractor
785     mParser = new FLACParser(mDataSource);
786     return mParser->initCheck();
787 }
788 
789 // FLACExtractor
790 
FLACExtractor(const sp<DataSource> & dataSource)791 FLACExtractor::FLACExtractor(
792         const sp<DataSource> &dataSource)
793     : mDataSource(dataSource),
794       mInitCheck(false)
795 {
796     ALOGV("FLACExtractor::FLACExtractor");
797     mInitCheck = init();
798 }
799 
~FLACExtractor()800 FLACExtractor::~FLACExtractor()
801 {
802     ALOGV("~FLACExtractor::FLACExtractor");
803 }
804 
countTracks()805 size_t FLACExtractor::countTracks()
806 {
807     return mInitCheck == OK ? 1 : 0;
808 }
809 
getTrack(size_t index)810 sp<MediaSource> FLACExtractor::getTrack(size_t index)
811 {
812     if (mInitCheck != OK || index > 0) {
813         return NULL;
814     }
815     return new FLACSource(mDataSource, mTrackMetadata);
816 }
817 
getTrackMetaData(size_t index,uint32_t)818 sp<MetaData> FLACExtractor::getTrackMetaData(
819         size_t index, uint32_t /* flags */) {
820     if (mInitCheck != OK || index > 0) {
821         return NULL;
822     }
823     return mTrackMetadata;
824 }
825 
init()826 status_t FLACExtractor::init()
827 {
828     mFileMetadata = new MetaData;
829     mTrackMetadata = new MetaData;
830     // FLACParser will fill in the metadata for us
831     mParser = new FLACParser(mDataSource, mFileMetadata, mTrackMetadata);
832     return mParser->initCheck();
833 }
834 
getMetaData()835 sp<MetaData> FLACExtractor::getMetaData()
836 {
837     return mFileMetadata;
838 }
839 
840 // Sniffer
841 
SniffFLAC(const sp<DataSource> & source,String8 * mimeType,float * confidence,sp<AMessage> *)842 bool SniffFLAC(
843         const sp<DataSource> &source, String8 *mimeType, float *confidence,
844         sp<AMessage> *)
845 {
846     // first 4 is the signature word
847     // second 4 is the sizeof STREAMINFO
848     // 042 is the mandatory STREAMINFO
849     // no need to read rest of the header, as a premature EOF will be caught later
850     uint8_t header[4+4];
851     if (source->readAt(0, header, sizeof(header)) != sizeof(header)
852             || memcmp("fLaC\0\0\0\042", header, 4+4))
853     {
854         return false;
855     }
856 
857     *mimeType = MEDIA_MIMETYPE_AUDIO_FLAC;
858     *confidence = 0.5;
859 
860     return true;
861 }
862 
863 }  // namespace android
864