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     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 
     82     status_t initCheck() const {
     83         return mInitCheck;
     84     }
     85 
     86     // stream properties
     87     unsigned getMaxBlockSize() const {
     88         return mStreamInfo.max_blocksize;
     89     }
     90     unsigned getSampleRate() const {
     91         return mStreamInfo.sample_rate;
     92     }
     93     unsigned getChannels() const {
     94         return mStreamInfo.channels;
     95     }
     96     unsigned getBitsPerSample() const {
     97         return mStreamInfo.bits_per_sample;
     98     }
     99     FLAC__uint64 getTotalSamples() const {
    100         return mStreamInfo.total_samples;
    101     }
    102 
    103     // media buffers
    104     void allocateBuffers();
    105     void releaseBuffers();
    106     MediaBuffer *readBuffer() {
    107         return readBuffer(false, 0LL);
    108     }
    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);
    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 
    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 
    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 
    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 
    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 
    238 FLAC__bool FLACParser::eof_callback(
    239         const FLAC__StreamDecoder *decoder, void *client_data)
    240 {
    241     return ((FLACParser *) client_data)->eofCallback();
    242 }
    243 
    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 
    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 
    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 
    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 
    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 
    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 
    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 
    314 FLAC__bool FLACParser::eofCallback()
    315 {
    316     return mEOF;
    317 }
    318 
    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         LOGE("FLACParser::writeCallback unexpected");
    331         return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
    332     }
    333 }
    334 
    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             LOGE("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) {
    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         LOGW("FLACParser::metadataCallback unexpected type %u", metadata->type);
    370         break;
    371     }
    372 }
    373 
    374 void FLACParser::errorCallback(FLAC__StreamDecoderErrorStatus status)
    375 {
    376     LOGE("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 
    383 static void copyMono8(short *dst, const int *const *src, unsigned nSamples)
    384 {
    385     for (unsigned i = 0; i < nSamples; ++i) {
    386         *dst++ = src[0][i] << 8;
    387     }
    388 }
    389 
    390 static void copyStereo8(short *dst, const int *const *src, unsigned nSamples)
    391 {
    392     for (unsigned i = 0; i < nSamples; ++i) {
    393         *dst++ = src[0][i] << 8;
    394         *dst++ = src[1][i] << 8;
    395     }
    396 }
    397 
    398 static void copyMono16(short *dst, const int *const *src, unsigned nSamples)
    399 {
    400     for (unsigned i = 0; i < nSamples; ++i) {
    401         *dst++ = src[0][i];
    402     }
    403 }
    404 
    405 static void copyStereo16(short *dst, const int *const *src, unsigned nSamples)
    406 {
    407     for (unsigned i = 0; i < nSamples; ++i) {
    408         *dst++ = src[0][i];
    409         *dst++ = src[1][i];
    410     }
    411 }
    412 
    413 // 24-bit versions should do dithering or noise-shaping, here or in AudioFlinger
    414 
    415 static void copyMono24(short *dst, const int *const *src, unsigned nSamples)
    416 {
    417     for (unsigned i = 0; i < nSamples; ++i) {
    418         *dst++ = src[0][i] >> 8;
    419     }
    420 }
    421 
    422 static void copyStereo24(short *dst, const int *const *src, unsigned nSamples)
    423 {
    424     for (unsigned i = 0; i < nSamples; ++i) {
    425         *dst++ = src[0][i] >> 8;
    426         *dst++ = src[1][i] >> 8;
    427     }
    428 }
    429 
    430 static void copyTrespass(short *dst, const int *const *src, unsigned nSamples)
    431 {
    432     TRESPASS();
    433 }
    434 
    435 // FLACParser
    436 
    437 FLACParser::FLACParser(
    438         const sp<DataSource> &dataSource,
    439         const sp<MetaData> &fileMetadata,
    440         const sp<MetaData> &trackMetadata)
    441     : mDataSource(dataSource),
    442       mFileMetadata(fileMetadata),
    443       mTrackMetadata(trackMetadata),
    444       mInitCheck(false),
    445       mMaxBufferSize(0),
    446       mGroup(NULL),
    447       mCopy(copyTrespass),
    448       mDecoder(NULL),
    449       mCurrentPos(0LL),
    450       mEOF(false),
    451       mStreamInfoValid(false),
    452       mWriteRequested(false),
    453       mWriteCompleted(false),
    454       mWriteBuffer(NULL),
    455       mErrorStatus((FLAC__StreamDecoderErrorStatus) -1)
    456 {
    457     LOGV("FLACParser::FLACParser");
    458     memset(&mStreamInfo, 0, sizeof(mStreamInfo));
    459     memset(&mWriteHeader, 0, sizeof(mWriteHeader));
    460     mInitCheck = init();
    461 }
    462 
    463 FLACParser::~FLACParser()
    464 {
    465     LOGV("FLACParser::~FLACParser");
    466     if (mDecoder != NULL) {
    467         FLAC__stream_decoder_delete(mDecoder);
    468         mDecoder = NULL;
    469     }
    470 }
    471 
    472 status_t FLACParser::init()
    473 {
    474     // setup libFLAC parser
    475     mDecoder = FLAC__stream_decoder_new();
    476     if (mDecoder == NULL) {
    477         // The new should succeed, since probably all it does is a malloc
    478         // that always succeeds in Android.  But to avoid dependence on the
    479         // libFLAC internals, we check and log here.
    480         LOGE("new failed");
    481         return NO_INIT;
    482     }
    483     FLAC__stream_decoder_set_md5_checking(mDecoder, false);
    484     FLAC__stream_decoder_set_metadata_ignore_all(mDecoder);
    485     FLAC__stream_decoder_set_metadata_respond(
    486             mDecoder, FLAC__METADATA_TYPE_STREAMINFO);
    487     FLAC__stream_decoder_set_metadata_respond(
    488             mDecoder, FLAC__METADATA_TYPE_PICTURE);
    489     FLAC__stream_decoder_set_metadata_respond(
    490             mDecoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
    491     FLAC__StreamDecoderInitStatus initStatus;
    492     initStatus = FLAC__stream_decoder_init_stream(
    493             mDecoder,
    494             read_callback, seek_callback, tell_callback,
    495             length_callback, eof_callback, write_callback,
    496             metadata_callback, error_callback, (void *) this);
    497     if (initStatus != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
    498         // A failure here probably indicates a programming error and so is
    499         // unlikely to happen. But we check and log here similarly to above.
    500         LOGE("init_stream failed %d", initStatus);
    501         return NO_INIT;
    502     }
    503     // parse all metadata
    504     if (!FLAC__stream_decoder_process_until_end_of_metadata(mDecoder)) {
    505         LOGE("end_of_metadata failed");
    506         return NO_INIT;
    507     }
    508     if (mStreamInfoValid) {
    509         // check channel count
    510         switch (getChannels()) {
    511         case 1:
    512         case 2:
    513             break;
    514         default:
    515             LOGE("unsupported channel count %u", getChannels());
    516             return NO_INIT;
    517         }
    518         // check bit depth
    519         switch (getBitsPerSample()) {
    520         case 8:
    521         case 16:
    522         case 24:
    523             break;
    524         default:
    525             LOGE("unsupported bits per sample %u", getBitsPerSample());
    526             return NO_INIT;
    527         }
    528         // check sample rate
    529         switch (getSampleRate()) {
    530         case  8000:
    531         case 11025:
    532         case 12000:
    533         case 16000:
    534         case 22050:
    535         case 24000:
    536         case 32000:
    537         case 44100:
    538         case 48000:
    539             break;
    540         default:
    541             // 96000 would require a proper downsampler in AudioFlinger
    542             LOGE("unsupported sample rate %u", getSampleRate());
    543             return NO_INIT;
    544         }
    545         // configure the appropriate copy function, defaulting to trespass
    546         static const struct {
    547             unsigned mChannels;
    548             unsigned mBitsPerSample;
    549             void (*mCopy)(short *dst, const int *const *src, unsigned nSamples);
    550         } table[] = {
    551             { 1,  8, copyMono8    },
    552             { 2,  8, copyStereo8  },
    553             { 1, 16, copyMono16   },
    554             { 2, 16, copyStereo16 },
    555             { 1, 24, copyMono24   },
    556             { 2, 24, copyStereo24 },
    557         };
    558         for (unsigned i = 0; i < sizeof(table)/sizeof(table[0]); ++i) {
    559             if (table[i].mChannels == getChannels() &&
    560                     table[i].mBitsPerSample == getBitsPerSample()) {
    561                 mCopy = table[i].mCopy;
    562                 break;
    563             }
    564         }
    565         // populate track metadata
    566         if (mTrackMetadata != 0) {
    567             mTrackMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
    568             mTrackMetadata->setInt32(kKeyChannelCount, getChannels());
    569             mTrackMetadata->setInt32(kKeySampleRate, getSampleRate());
    570             // sample rate is non-zero, so division by zero not possible
    571             mTrackMetadata->setInt64(kKeyDuration,
    572                     (getTotalSamples() * 1000000LL) / getSampleRate());
    573         }
    574     } else {
    575         LOGE("missing STREAMINFO");
    576         return NO_INIT;
    577     }
    578     if (mFileMetadata != 0) {
    579         mFileMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_FLAC);
    580     }
    581     return OK;
    582 }
    583 
    584 void FLACParser::allocateBuffers()
    585 {
    586     CHECK(mGroup == NULL);
    587     mGroup = new MediaBufferGroup;
    588     mMaxBufferSize = getMaxBlockSize() * getChannels() * sizeof(short);
    589     mGroup->add_buffer(new MediaBuffer(mMaxBufferSize));
    590 }
    591 
    592 void FLACParser::releaseBuffers()
    593 {
    594     CHECK(mGroup != NULL);
    595     delete mGroup;
    596     mGroup = NULL;
    597 }
    598 
    599 MediaBuffer *FLACParser::readBuffer(bool doSeek, FLAC__uint64 sample)
    600 {
    601     mWriteRequested = true;
    602     mWriteCompleted = false;
    603     if (doSeek) {
    604         // We implement the seek callback, so this works without explicit flush
    605         if (!FLAC__stream_decoder_seek_absolute(mDecoder, sample)) {
    606             LOGE("FLACParser::readBuffer seek to sample %llu failed", sample);
    607             return NULL;
    608         }
    609         LOGV("FLACParser::readBuffer seek to sample %llu succeeded", sample);
    610     } else {
    611         if (!FLAC__stream_decoder_process_single(mDecoder)) {
    612             LOGE("FLACParser::readBuffer process_single failed");
    613             return NULL;
    614         }
    615     }
    616     if (!mWriteCompleted) {
    617         LOGV("FLACParser::readBuffer write did not complete");
    618         return NULL;
    619     }
    620     // verify that block header keeps the promises made by STREAMINFO
    621     unsigned blocksize = mWriteHeader.blocksize;
    622     if (blocksize == 0 || blocksize > getMaxBlockSize()) {
    623         LOGE("FLACParser::readBuffer write invalid blocksize %u", blocksize);
    624         return NULL;
    625     }
    626     if (mWriteHeader.sample_rate != getSampleRate() ||
    627         mWriteHeader.channels != getChannels() ||
    628         mWriteHeader.bits_per_sample != getBitsPerSample()) {
    629         LOGE("FLACParser::readBuffer write changed parameters mid-stream");
    630     }
    631     // acquire a media buffer
    632     CHECK(mGroup != NULL);
    633     MediaBuffer *buffer;
    634     status_t err = mGroup->acquire_buffer(&buffer);
    635     if (err != OK) {
    636         return NULL;
    637     }
    638     size_t bufferSize = blocksize * getChannels() * sizeof(short);
    639     CHECK(bufferSize <= mMaxBufferSize);
    640     short *data = (short *) buffer->data();
    641     buffer->set_range(0, bufferSize);
    642     // copy PCM from FLAC write buffer to our media buffer, with interleaving
    643     (*mCopy)(data, mWriteBuffer, blocksize);
    644     // fill in buffer metadata
    645     CHECK(mWriteHeader.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
    646     FLAC__uint64 sampleNumber = mWriteHeader.number.sample_number;
    647     int64_t timeUs = (1000000LL * sampleNumber) / getSampleRate();
    648     buffer->meta_data()->setInt64(kKeyTime, timeUs);
    649     buffer->meta_data()->setInt32(kKeyIsSyncFrame, 1);
    650     return buffer;
    651 }
    652 
    653 // FLACsource
    654 
    655 FLACSource::FLACSource(
    656         const sp<DataSource> &dataSource,
    657         const sp<MetaData> &trackMetadata)
    658     : mDataSource(dataSource),
    659       mTrackMetadata(trackMetadata),
    660       mParser(0),
    661       mInitCheck(false),
    662       mStarted(false)
    663 {
    664     LOGV("FLACSource::FLACSource");
    665     mInitCheck = init();
    666 }
    667 
    668 FLACSource::~FLACSource()
    669 {
    670     LOGV("~FLACSource::FLACSource");
    671     if (mStarted) {
    672         stop();
    673     }
    674 }
    675 
    676 status_t FLACSource::start(MetaData *params)
    677 {
    678     LOGV("FLACSource::start");
    679 
    680     CHECK(!mStarted);
    681     mParser->allocateBuffers();
    682     mStarted = true;
    683 
    684     return OK;
    685 }
    686 
    687 status_t FLACSource::stop()
    688 {
    689     LOGV("FLACSource::stop");
    690 
    691     CHECK(mStarted);
    692     mParser->releaseBuffers();
    693     mStarted = false;
    694 
    695     return OK;
    696 }
    697 
    698 sp<MetaData> FLACSource::getFormat()
    699 {
    700     return mTrackMetadata;
    701 }
    702 
    703 status_t FLACSource::read(
    704         MediaBuffer **outBuffer, const ReadOptions *options)
    705 {
    706     MediaBuffer *buffer;
    707     // process an optional seek request
    708     int64_t seekTimeUs;
    709     ReadOptions::SeekMode mode;
    710     if ((NULL != options) && options->getSeekTo(&seekTimeUs, &mode)) {
    711         FLAC__uint64 sample;
    712         if (seekTimeUs <= 0LL) {
    713             sample = 0LL;
    714         } else {
    715             // sample and total samples are both zero-based, and seek to EOF ok
    716             sample = (seekTimeUs * mParser->getSampleRate()) / 1000000LL;
    717             if (sample >= mParser->getTotalSamples()) {
    718                 sample = mParser->getTotalSamples();
    719             }
    720         }
    721         buffer = mParser->readBuffer(sample);
    722     // otherwise read sequentially
    723     } else {
    724         buffer = mParser->readBuffer();
    725     }
    726     *outBuffer = buffer;
    727     return buffer != NULL ? (status_t) OK : (status_t) ERROR_END_OF_STREAM;
    728 }
    729 
    730 status_t FLACSource::init()
    731 {
    732     LOGV("FLACSource::init");
    733     // re-use the same track metadata passed into constructor from FLACExtractor
    734     mParser = new FLACParser(mDataSource);
    735     return mParser->initCheck();
    736 }
    737 
    738 // FLACExtractor
    739 
    740 FLACExtractor::FLACExtractor(
    741         const sp<DataSource> &dataSource)
    742     : mDataSource(dataSource),
    743       mInitCheck(false)
    744 {
    745     LOGV("FLACExtractor::FLACExtractor");
    746     mInitCheck = init();
    747 }
    748 
    749 FLACExtractor::~FLACExtractor()
    750 {
    751     LOGV("~FLACExtractor::FLACExtractor");
    752 }
    753 
    754 size_t FLACExtractor::countTracks()
    755 {
    756     return mInitCheck == OK ? 1 : 0;
    757 }
    758 
    759 sp<MediaSource> FLACExtractor::getTrack(size_t index)
    760 {
    761     if (mInitCheck != OK || index > 0) {
    762         return NULL;
    763     }
    764     return new FLACSource(mDataSource, mTrackMetadata);
    765 }
    766 
    767 sp<MetaData> FLACExtractor::getTrackMetaData(
    768         size_t index, uint32_t flags)
    769 {
    770     if (mInitCheck != OK || index > 0) {
    771         return NULL;
    772     }
    773     return mTrackMetadata;
    774 }
    775 
    776 status_t FLACExtractor::init()
    777 {
    778     mFileMetadata = new MetaData;
    779     mTrackMetadata = new MetaData;
    780     // FLACParser will fill in the metadata for us
    781     mParser = new FLACParser(mDataSource, mFileMetadata, mTrackMetadata);
    782     return mParser->initCheck();
    783 }
    784 
    785 sp<MetaData> FLACExtractor::getMetaData()
    786 {
    787     return mFileMetadata;
    788 }
    789 
    790 // Sniffer
    791 
    792 bool SniffFLAC(
    793         const sp<DataSource> &source, String8 *mimeType, float *confidence,
    794         sp<AMessage> *)
    795 {
    796     // first 4 is the signature word
    797     // second 4 is the sizeof STREAMINFO
    798     // 042 is the mandatory STREAMINFO
    799     // no need to read rest of the header, as a premature EOF will be caught later
    800     uint8_t header[4+4];
    801     if (source->readAt(0, header, sizeof(header)) != sizeof(header)
    802             || memcmp("fLaC\0\0\0\042", header, 4+4))
    803     {
    804         return false;
    805     }
    806 
    807     *mimeType = MEDIA_MIMETYPE_AUDIO_FLAC;
    808     *confidence = 0.5;
    809 
    810     return true;
    811 }
    812 
    813 }  // namespace android
    814