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