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