android_AudioSfDecoder.cpp revision 3597268c2bf4ff71521e3cbe522d7ee02c41f175
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 USE_LOG SLAndroidLogLevel_Verbose
18
19#include "sles_allinclusive.h"
20#include "android/android_AudioSfDecoder.h"
21
22#include <media/stagefright/foundation/ADebug.h>
23
24
25#define SIZE_CACHED_HIGH_BYTES 1000000
26#define SIZE_CACHED_MED_BYTES   700000
27#define SIZE_CACHED_LOW_BYTES   400000
28
29namespace android {
30
31//--------------------------------------------------------------------------------------------------
32AudioSfDecoder::AudioSfDecoder(const AudioPlayback_Parameters* params) : GenericPlayer(params),
33        mDataSource(0),
34        mAudioSource(0),
35        mAudioSourceStarted(false),
36        mBitrate(-1),
37        mDurationUsec(ANDROID_UNKNOWN_TIME),
38        mDecodeBuffer(NULL),
39        mSeekTimeMsec(0),
40        // play event logic depends on the initial time being zero not ANDROID_UNKNOWN_TIME
41        mLastDecodedPositionUs(0)
42{
43    SL_LOGD("AudioSfDecoder::AudioSfDecoder()");
44}
45
46
47AudioSfDecoder::~AudioSfDecoder() {
48    SL_LOGD("AudioSfDecoder::~AudioSfDecoder()");
49}
50
51
52void AudioSfDecoder::preDestroy() {
53    GenericPlayer::preDestroy();
54    SL_LOGD("AudioSfDecoder::preDestroy()");
55    {
56        Mutex::Autolock _l(mBufferSourceLock);
57
58        if (NULL != mDecodeBuffer) {
59            mDecodeBuffer->release();
60            mDecodeBuffer = NULL;
61        }
62
63        if ((mAudioSource != 0) && mAudioSourceStarted) {
64            mAudioSource->stop();
65            mAudioSourceStarted = false;
66        }
67    }
68}
69
70
71//--------------------------------------------------
72void AudioSfDecoder::play() {
73    SL_LOGD("AudioSfDecoder::play");
74
75    GenericPlayer::play();
76    (new AMessage(kWhatDecode, id()))->post();
77}
78
79
80void AudioSfDecoder::getPositionMsec(int* msec) {
81    int64_t timeUsec = getPositionUsec();
82    if (timeUsec == ANDROID_UNKNOWN_TIME) {
83        *msec = ANDROID_UNKNOWN_TIME;
84    } else {
85        *msec = timeUsec / 1000;
86    }
87}
88
89
90//--------------------------------------------------
91uint32_t AudioSfDecoder::getPcmFormatKeyCount() const {
92    return NB_PCMMETADATA_KEYS;
93}
94
95
96//--------------------------------------------------
97bool AudioSfDecoder::getPcmFormatKeySize(uint32_t index, uint32_t* pKeySize) {
98    if (index >= NB_PCMMETADATA_KEYS) {
99        return false;
100    } else {
101        *pKeySize = strlen(kPcmDecodeMetadataKeys[index]) +1;
102        return true;
103    }
104}
105
106
107//--------------------------------------------------
108bool AudioSfDecoder::getPcmFormatKeyName(uint32_t index, uint32_t keySize, char* keyName) {
109    uint32_t actualKeySize;
110    if (!getPcmFormatKeySize(index, &actualKeySize)) {
111        return false;
112    }
113    if (keySize < actualKeySize) {
114        return false;
115    }
116    strncpy(keyName, kPcmDecodeMetadataKeys[index], actualKeySize);
117    return true;
118}
119
120
121//--------------------------------------------------
122bool AudioSfDecoder::getPcmFormatValueSize(uint32_t index, uint32_t* pValueSize) {
123    if (index >= NB_PCMMETADATA_KEYS) {
124        *pValueSize = 0;
125        return false;
126    } else {
127        *pValueSize = sizeof(uint32_t);
128        return true;
129    }
130}
131
132
133//--------------------------------------------------
134bool AudioSfDecoder::getPcmFormatKeyValue(uint32_t index, uint32_t size, uint32_t* pValue) {
135    uint32_t valueSize = 0;
136    if (!getPcmFormatValueSize(index, &valueSize)) {
137        return false;
138    } else if (size != valueSize) {
139        // this ensures we are accessing mPcmFormatValues with a valid size for that index
140        SL_LOGE("Error retrieving metadata value at index %d: using size of %d, should be %d",
141                index, size, valueSize);
142        return false;
143    } else {
144        android::Mutex::Autolock autoLock(mPcmFormatLock);
145        *pValue = mPcmFormatValues[index];
146        return true;
147    }
148}
149
150
151//--------------------------------------------------
152// Event handlers
153//  it is strictly verboten to call those methods outside of the event loop
154
155// Initializes the data and audio sources, and update the PCM format info
156// post-condition: upon successful initialization based on the player data locator
157//    GenericPlayer::onPrepare() was called
158//    mDataSource != 0
159//    mAudioSource != 0
160//    mAudioSourceStarted == true
161// All error returns from this method are via notifyPrepared(status) followed by "return".
162void AudioSfDecoder::onPrepare() {
163    SL_LOGD("AudioSfDecoder::onPrepare()");
164    Mutex::Autolock _l(mBufferSourceLock);
165
166    {
167    android::Mutex::Autolock autoLock(mPcmFormatLock);
168    // Initialize the PCM format info with the known parameters before the start of the decode
169    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_BITSPERSAMPLE] = SL_PCMSAMPLEFORMAT_FIXED_16;
170    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CONTAINERSIZE] = 16;
171    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_ENDIANNESS] = SL_BYTEORDER_LITTLEENDIAN;
172    //    initialization with the default values: they will be replaced by the actual values
173    //      once the decoder has figured them out
174    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS] = UNKNOWN_NUMCHANNELS;
175    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE] = UNKNOWN_SAMPLERATE;
176    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CHANNELMASK] = UNKNOWN_CHANNELMASK;
177    }
178
179    //---------------------------------
180    // Instantiate and initialize the data source for the decoder
181    sp<DataSource> dataSource;
182
183    switch (mDataLocatorType) {
184
185    case kDataLocatorNone:
186        SL_LOGE("AudioSfDecoder::onPrepare: no data locator set");
187        notifyPrepared(MEDIA_ERROR_BASE);
188        return;
189
190    case kDataLocatorUri:
191        dataSource = DataSource::CreateFromURI(mDataLocator.uriRef);
192        if (dataSource == NULL) {
193            SL_LOGE("AudioSfDecoder::onPrepare(): Error opening %s", mDataLocator.uriRef);
194            notifyPrepared(MEDIA_ERROR_BASE);
195            return;
196        }
197        break;
198
199    case kDataLocatorFd:
200    {
201        // As FileSource unconditionally takes ownership of the fd and closes it, then
202        // we have to make a dup for FileSource if the app wants to keep ownership itself
203        int fd = mDataLocator.fdi.fd;
204        if (mDataLocator.fdi.mCloseAfterUse) {
205            mDataLocator.fdi.mCloseAfterUse = false;
206        } else {
207            fd = ::dup(fd);
208        }
209        dataSource = new FileSource(fd, mDataLocator.fdi.offset, mDataLocator.fdi.length);
210        status_t err = dataSource->initCheck();
211        if (err != OK) {
212            notifyPrepared(err);
213            return;
214        }
215        break;
216    }
217
218    default:
219        TRESPASS();
220    }
221
222    //---------------------------------
223    // Instanciate and initialize the decoder attached to the data source
224    sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource);
225    if (extractor == NULL) {
226        SL_LOGE("AudioSfDecoder::onPrepare: Could not instantiate extractor.");
227        notifyPrepared(ERROR_UNSUPPORTED);
228        return;
229    }
230
231    ssize_t audioTrackIndex = -1;
232    bool isRawAudio = false;
233    for (size_t i = 0; i < extractor->countTracks(); ++i) {
234        sp<MetaData> meta = extractor->getTrackMetaData(i);
235
236        const char *mime;
237        CHECK(meta->findCString(kKeyMIMEType, &mime));
238
239        if (!strncasecmp("audio/", mime, 6)) {
240            if (isSupportedCodec(mime)) {
241                audioTrackIndex = i;
242
243                if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mime)) {
244                    isRawAudio = true;
245                }
246                break;
247            }
248        }
249    }
250
251    if (audioTrackIndex < 0) {
252        SL_LOGE("AudioSfDecoder::onPrepare: Could not find a supported audio track.");
253        notifyPrepared(ERROR_UNSUPPORTED);
254        return;
255    }
256
257    sp<MediaSource> source = extractor->getTrack(audioTrackIndex);
258    sp<MetaData> meta = source->getFormat();
259
260    // we can't trust the OMXCodec (if there is one) to issue a INFO_FORMAT_CHANGED so we want
261    // to have some meaningful values as soon as possible.
262    int32_t channelCount;
263    bool hasChannelCount = meta->findInt32(kKeyChannelCount, &channelCount);
264    int32_t sr;
265    bool hasSampleRate = meta->findInt32(kKeySampleRate, &sr);
266
267    off64_t size;
268    int64_t durationUs;
269    if (dataSource->getSize(&size) == OK
270            && meta->findInt64(kKeyDuration, &durationUs)) {
271        if (durationUs != 0) {
272            mBitrate = size * 8000000ll / durationUs;  // in bits/sec
273        } else {
274            mBitrate = -1;
275        }
276        mDurationUsec = durationUs;
277        mDurationMsec = durationUs / 1000;
278    } else {
279        mBitrate = -1;
280        mDurationUsec = ANDROID_UNKNOWN_TIME;
281        mDurationMsec = ANDROID_UNKNOWN_TIME;
282    }
283
284    // the audio content is not raw PCM, so we need a decoder
285    if (!isRawAudio) {
286        OMXClient client;
287        CHECK_EQ(client.connect(), (status_t)OK);
288
289        source = OMXCodec::Create(
290                client.interface(), meta, false /* createEncoder */,
291                source);
292
293        if (source == NULL) {
294            SL_LOGE("AudioSfDecoder::onPrepare: Could not instantiate decoder.");
295            notifyPrepared(ERROR_UNSUPPORTED);
296            return;
297        }
298
299        meta = source->getFormat();
300    }
301
302
303    if (source->start() != OK) {
304        SL_LOGE("AudioSfDecoder::onPrepare: Failed to start source/decoder.");
305        notifyPrepared(MEDIA_ERROR_BASE);
306        return;
307    }
308
309    //---------------------------------
310    // The data source, and audio source (a decoder if required) are ready to be used
311    mDataSource = dataSource;
312    mAudioSource = source;
313    mAudioSourceStarted = true;
314
315    if (!hasChannelCount) {
316        CHECK(meta->findInt32(kKeyChannelCount, &channelCount));
317    }
318
319    if (!hasSampleRate) {
320        CHECK(meta->findInt32(kKeySampleRate, &sr));
321    }
322    // FIXME add code below once channel mask support is in, currently initialized to default
323    //       value computed from the channel count
324    //    if (!hasChannelMask) {
325    //        CHECK(meta->findInt32(kKeyChannelMask, &channelMask));
326    //    }
327
328    if (!wantPrefetch()) {
329        SL_LOGV("AudioSfDecoder::onPrepare: no need to prefetch");
330        // doesn't need prefetching, notify good to go
331        mCacheStatus = kStatusHigh;
332        mCacheFill = 1000;
333        notifyStatus();
334        notifyCacheFill();
335    }
336
337    {
338        android::Mutex::Autolock autoLock(mPcmFormatLock);
339        mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE] = sr;
340        mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS] = channelCount;
341        mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CHANNELMASK] =
342                channelCountToMask(channelCount);
343    }
344
345    // at this point we have enough information about the source to create the sink that
346    // will consume the data
347    createAudioSink();
348
349    // signal successful completion of prepare
350    mStateFlags |= kFlagPrepared;
351
352    GenericPlayer::onPrepare();
353    SL_LOGD("AudioSfDecoder::onPrepare() done, mStateFlags=0x%x", mStateFlags);
354}
355
356
357void AudioSfDecoder::onPause() {
358    SL_LOGV("AudioSfDecoder::onPause()");
359    GenericPlayer::onPause();
360    pauseAudioSink();
361}
362
363
364void AudioSfDecoder::onPlay() {
365    SL_LOGV("AudioSfDecoder::onPlay()");
366    GenericPlayer::onPlay();
367    startAudioSink();
368}
369
370
371void AudioSfDecoder::onSeek(const sp<AMessage> &msg) {
372    SL_LOGV("AudioSfDecoder::onSeek");
373    int64_t timeMsec;
374    CHECK(msg->findInt64(WHATPARAM_SEEK_SEEKTIME_MS, &timeMsec));
375
376    Mutex::Autolock _l(mTimeLock);
377    mStateFlags |= kFlagSeeking;
378    mSeekTimeMsec = timeMsec;
379    // don't set mLastDecodedPositionUs to ANDROID_UNKNOWN_TIME; getPositionUsec
380    // ignores mLastDecodedPositionUs while seeking, and substitutes the seek goal instead
381
382    // nop for now
383    GenericPlayer::onSeek(msg);
384}
385
386
387void AudioSfDecoder::onLoop(const sp<AMessage> &msg) {
388    SL_LOGV("AudioSfDecoder::onLoop");
389    int32_t loop;
390    CHECK(msg->findInt32(WHATPARAM_LOOP_LOOPING, &loop));
391
392    if (loop) {
393        //SL_LOGV("AudioSfDecoder::onLoop start looping");
394        mStateFlags |= kFlagLooping;
395    } else {
396        //SL_LOGV("AudioSfDecoder::onLoop stop looping");
397        mStateFlags &= ~kFlagLooping;
398    }
399
400    // nop for now
401    GenericPlayer::onLoop(msg);
402}
403
404
405void AudioSfDecoder::onCheckCache(const sp<AMessage> &msg) {
406    //SL_LOGV("AudioSfDecoder::onCheckCache");
407    bool eos;
408    CacheStatus_t status = getCacheRemaining(&eos);
409
410    if (eos || status == kStatusHigh
411            || ((mStateFlags & kFlagPreparing) && (status >= kStatusEnough))) {
412        if (mStateFlags & kFlagPlaying) {
413            startAudioSink();
414        }
415        mStateFlags &= ~kFlagBuffering;
416
417        SL_LOGV("AudioSfDecoder::onCheckCache: buffering done.");
418
419        if (mStateFlags & kFlagPreparing) {
420            //SL_LOGV("AudioSfDecoder::onCheckCache: preparation done.");
421            mStateFlags &= ~kFlagPreparing;
422        }
423
424        if (mStateFlags & kFlagPlaying) {
425            (new AMessage(kWhatDecode, id()))->post();
426        }
427        return;
428    }
429
430    msg->post(100000);
431}
432
433
434void AudioSfDecoder::onDecode() {
435    SL_LOGV("AudioSfDecoder::onDecode");
436
437    //-------------------------------- Need to buffer some more before decoding?
438    bool eos;
439    if (mDataSource == 0) {
440        // application set play state to paused which failed, then set play state to playing
441        return;
442    }
443
444    if (wantPrefetch()
445            && (getCacheRemaining(&eos) == kStatusLow)
446            && !eos) {
447        SL_LOGV("buffering more.");
448
449        if (mStateFlags & kFlagPlaying) {
450            pauseAudioSink();
451        }
452        mStateFlags |= kFlagBuffering;
453        (new AMessage(kWhatCheckCache, id()))->post(100000);
454        return;
455    }
456
457    if (!(mStateFlags & (kFlagPlaying | kFlagBuffering | kFlagPreparing))) {
458        // don't decode if we're not buffering, prefetching or playing
459        //SL_LOGV("don't decode: not buffering, prefetching or playing");
460        return;
461    }
462
463    //-------------------------------- Decode
464    status_t err;
465    MediaSource::ReadOptions readOptions;
466    if (mStateFlags & kFlagSeeking) {
467        assert(mSeekTimeMsec != ANDROID_UNKNOWN_TIME);
468        readOptions.setSeekTo(mSeekTimeMsec * 1000);
469    }
470
471    int64_t timeUsec = ANDROID_UNKNOWN_TIME;
472    {
473        Mutex::Autolock _l(mBufferSourceLock);
474
475        if (NULL != mDecodeBuffer) {
476            // the current decoded buffer hasn't been rendered, drop it
477            mDecodeBuffer->release();
478            mDecodeBuffer = NULL;
479        }
480        if(!mAudioSourceStarted) {
481            return;
482        }
483        err = mAudioSource->read(&mDecodeBuffer, &readOptions);
484        if (err == OK) {
485            // FIXME workaround apparent bug in AAC decoder: kKeyTime is 3 frames old if length is 0
486            if (mDecodeBuffer->range_length() == 0) {
487                timeUsec = ANDROID_UNKNOWN_TIME;
488            } else {
489                CHECK(mDecodeBuffer->meta_data()->findInt64(kKeyTime, &timeUsec));
490            }
491        }
492    }
493
494    {
495        Mutex::Autolock _l(mTimeLock);
496        if (mStateFlags & kFlagSeeking) {
497            mStateFlags &= ~kFlagSeeking;
498            mSeekTimeMsec = ANDROID_UNKNOWN_TIME;
499        }
500        if (timeUsec != ANDROID_UNKNOWN_TIME) {
501            // Note that though we've decoded this position, we haven't rendered it yet.
502            // So a GetPosition called after this point will observe the advanced position,
503            // even though the PCM may not have been supplied to the sink.  That's OK as
504            // we don't claim to provide frame-accurate (let alone sample-accurate) GetPosition.
505            mLastDecodedPositionUs = timeUsec;
506        }
507    }
508
509    //-------------------------------- Handle return of decode
510    if (err != OK) {
511        bool continueDecoding = false;
512        switch(err) {
513            case ERROR_END_OF_STREAM:
514                if (0 < mDurationUsec) {
515                    Mutex::Autolock _l(mTimeLock);
516                    mLastDecodedPositionUs = mDurationUsec;
517                }
518                // handle notification and looping at end of stream
519                if (mStateFlags & kFlagPlaying) {
520                    notify(PLAYEREVENT_ENDOFSTREAM, 1, true);
521                }
522                if (mStateFlags & kFlagLooping) {
523                    seek(0);
524                    // kick-off decoding again
525                    continueDecoding = true;
526                }
527                break;
528            case INFO_FORMAT_CHANGED:
529                SL_LOGD("MediaSource::read encountered INFO_FORMAT_CHANGED");
530                // reconfigure output
531                {
532                    Mutex::Autolock _l(mBufferSourceLock);
533                    hasNewDecodeParams();
534                }
535                continueDecoding = true;
536                break;
537            case INFO_DISCONTINUITY:
538                SL_LOGD("MediaSource::read encountered INFO_DISCONTINUITY");
539                continueDecoding = true;
540                break;
541            default:
542                SL_LOGE("MediaSource::read returned error %d", err);
543                break;
544        }
545        if (continueDecoding) {
546            if (NULL == mDecodeBuffer) {
547                (new AMessage(kWhatDecode, id()))->post();
548                return;
549            }
550        } else {
551            return;
552        }
553    }
554
555    //-------------------------------- Render
556    sp<AMessage> msg = new AMessage(kWhatRender, id());
557    msg->post();
558
559}
560
561
562void AudioSfDecoder::onMessageReceived(const sp<AMessage> &msg) {
563    switch (msg->what()) {
564        case kWhatDecode:
565            onDecode();
566            break;
567
568        case kWhatRender:
569            onRender();
570            break;
571
572        case kWhatCheckCache:
573            onCheckCache(msg);
574            break;
575
576        default:
577            GenericPlayer::onMessageReceived(msg);
578            break;
579    }
580}
581
582//--------------------------------------------------
583// Prepared state, prefetch status notifications
584void AudioSfDecoder::notifyPrepared(status_t prepareRes) {
585    assert(!(mStateFlags & (kFlagPrepared | kFlagPreparedUnsuccessfully)));
586    if (NO_ERROR == prepareRes) {
587        // The "then" fork is not currently used, but is kept here to make it easier
588        // to replace by a new signalPrepareCompletion(status) if we re-visit this later.
589        mStateFlags |= kFlagPrepared;
590    } else {
591        mStateFlags |= kFlagPreparedUnsuccessfully;
592    }
593    // Do not call the superclass onPrepare to notify, because it uses a default error
594    // status code but we can provide a more specific one.
595    // GenericPlayer::onPrepare();
596    notify(PLAYEREVENT_PREPARED, (int32_t)prepareRes, true);
597    SL_LOGD("AudioSfDecoder::onPrepare() done, mStateFlags=0x%x", mStateFlags);
598}
599
600
601void AudioSfDecoder::onNotify(const sp<AMessage> &msg) {
602    notif_cbf_t notifyClient;
603    void*       notifyUser;
604    {
605        android::Mutex::Autolock autoLock(mNotifyClientLock);
606        if (NULL == mNotifyClient) {
607            return;
608        } else {
609            notifyClient = mNotifyClient;
610            notifyUser   = mNotifyUser;
611        }
612    }
613    int32_t val;
614    if (msg->findInt32(PLAYEREVENT_PREFETCHSTATUSCHANGE, &val)) {
615        SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_PREFETCHSTATUSCHANGE, val);
616        notifyClient(kEventPrefetchStatusChange, val, 0, notifyUser);
617    }
618    else if (msg->findInt32(PLAYEREVENT_PREFETCHFILLLEVELUPDATE, &val)) {
619        SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_PREFETCHFILLLEVELUPDATE, val);
620        notifyClient(kEventPrefetchFillLevelUpdate, val, 0, notifyUser);
621    }
622    else if (msg->findInt32(PLAYEREVENT_ENDOFSTREAM, &val)) {
623        SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_ENDOFSTREAM, val);
624        notifyClient(kEventEndOfStream, val, 0, notifyUser);
625    }
626    else {
627        GenericPlayer::onNotify(msg);
628    }
629}
630
631
632//--------------------------------------------------
633// Private utility functions
634
635bool AudioSfDecoder::wantPrefetch() {
636    if (mDataSource != 0) {
637        return (mDataSource->flags() & DataSource::kWantsPrefetching);
638    } else {
639        // happens if an improper data locator was passed, if the media extractor couldn't be
640        //  initialized, if there is no audio track in the media, if the OMX decoder couldn't be
641        //  instantiated, if the source couldn't be opened, or if the MediaSource
642        //  couldn't be started
643        SL_LOGV("AudioSfDecoder::wantPrefetch() tries to access NULL mDataSource");
644        return false;
645    }
646}
647
648
649int64_t AudioSfDecoder::getPositionUsec() {
650    Mutex::Autolock _l(mTimeLock);
651    if (mStateFlags & kFlagSeeking) {
652        return mSeekTimeMsec * 1000;
653    } else {
654        return mLastDecodedPositionUs;
655    }
656}
657
658
659CacheStatus_t AudioSfDecoder::getCacheRemaining(bool *eos) {
660    sp<NuCachedSource2> cachedSource =
661        static_cast<NuCachedSource2 *>(mDataSource.get());
662
663    CacheStatus_t oldStatus = mCacheStatus;
664
665    status_t finalStatus;
666    size_t dataRemaining = cachedSource->approxDataRemaining(&finalStatus);
667    *eos = (finalStatus != OK);
668
669    CHECK_GE(mBitrate, 0);
670
671    int64_t dataRemainingUs = dataRemaining * 8000000ll / mBitrate;
672    //SL_LOGV("AudioSfDecoder::getCacheRemaining: approx %.2f secs remaining (eos=%d)",
673    //       dataRemainingUs / 1E6, *eos);
674
675    if (*eos) {
676        // data is buffered up to the end of the stream, it can't get any better than this
677        mCacheStatus = kStatusHigh;
678        mCacheFill = 1000;
679
680    } else {
681        if (mDurationUsec > 0) {
682            // known duration:
683
684            //   fill level is ratio of how much has been played + how much is
685            //   cached, divided by total duration
686            uint32_t currentPositionUsec = getPositionUsec();
687            if (currentPositionUsec == ANDROID_UNKNOWN_TIME) {
688                // if we don't know where we are, assume the worst for the fill ratio
689                currentPositionUsec = 0;
690            }
691            if (mDurationUsec > 0) {
692                mCacheFill = (int16_t) ((1000.0
693                        * (double)(currentPositionUsec + dataRemainingUs) / mDurationUsec));
694            } else {
695                mCacheFill = 0;
696            }
697            //SL_LOGV("cacheFill = %d", mCacheFill);
698
699            //   cache status is evaluated against duration thresholds
700            if (dataRemainingUs > DURATION_CACHED_HIGH_MS*1000) {
701                mCacheStatus = kStatusHigh;
702                //LOGV("high");
703            } else if (dataRemainingUs > DURATION_CACHED_MED_MS*1000) {
704                //LOGV("enough");
705                mCacheStatus = kStatusEnough;
706            } else if (dataRemainingUs < DURATION_CACHED_LOW_MS*1000) {
707                //LOGV("low");
708                mCacheStatus = kStatusLow;
709            } else {
710                mCacheStatus = kStatusIntermediate;
711            }
712
713        } else {
714            // unknown duration:
715
716            //   cache status is evaluated against cache amount thresholds
717            //   (no duration so we don't have the bitrate either, could be derived from format?)
718            if (dataRemaining > SIZE_CACHED_HIGH_BYTES) {
719                mCacheStatus = kStatusHigh;
720            } else if (dataRemaining > SIZE_CACHED_MED_BYTES) {
721                mCacheStatus = kStatusEnough;
722            } else if (dataRemaining < SIZE_CACHED_LOW_BYTES) {
723                mCacheStatus = kStatusLow;
724            } else {
725                mCacheStatus = kStatusIntermediate;
726            }
727        }
728
729    }
730
731    if (oldStatus != mCacheStatus) {
732        notifyStatus();
733    }
734
735    if (abs(mCacheFill - mLastNotifiedCacheFill) > mCacheFillNotifThreshold) {
736        notifyCacheFill();
737    }
738
739    return mCacheStatus;
740}
741
742
743void AudioSfDecoder::hasNewDecodeParams() {
744
745    if ((mAudioSource != 0) && mAudioSourceStarted) {
746        sp<MetaData> meta = mAudioSource->getFormat();
747
748        int32_t channelCount;
749        CHECK(meta->findInt32(kKeyChannelCount, &channelCount));
750        int32_t sr;
751        CHECK(meta->findInt32(kKeySampleRate, &sr));
752
753        // FIXME similar to onPrepare()
754        {
755            android::Mutex::Autolock autoLock(mPcmFormatLock);
756            SL_LOGV("format changed: old sr=%d, channels=%d; new sr=%d, channels=%d",
757                    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE],
758                    mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS],
759                    sr, channelCount);
760            mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS] = channelCount;
761            mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE] = sr;
762            mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CHANNELMASK] =
763                    channelCountToMask(channelCount);
764        }
765    }
766
767    // alert users of those params
768    updateAudioSink();
769}
770
771static const char* const kUnsupportedCodecs[] = { MEDIA_MIMETYPE_AUDIO_AMR_NB,
772        MEDIA_MIMETYPE_AUDIO_AMR_WB };
773#define NB_UNSUPPORTED_CODECS (sizeof(kUnsupportedCodecs)/sizeof(kUnsupportedCodecs[0]))
774
775bool AudioSfDecoder::isSupportedCodec(const char* mime) {
776    for (unsigned int i = 0 ; i < NB_UNSUPPORTED_CODECS ; i++) {
777        if (!strcasecmp(mime, kUnsupportedCodecs[i])) {
778            return false;
779        }
780    }
781    return true;
782}
783
784} // namespace android
785