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