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