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