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