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