1 /* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 //#define USE_LOG SLAndroidLogLevel_Verbose 18 19 #include "sles_allinclusive.h" 20 #include "android/android_AudioSfDecoder.h" 21 22 #include <binder/IServiceManager.h> 23 #include <media/stagefright/foundation/ADebug.h> 24 25 26 #define SIZE_CACHED_HIGH_BYTES 1000000 27 #define SIZE_CACHED_MED_BYTES 700000 28 #define SIZE_CACHED_LOW_BYTES 400000 29 30 namespace android { 31 32 //-------------------------------------------------------------------------------------------------- 33 AudioSfDecoder::AudioSfDecoder(const AudioPlayback_Parameters* params) : GenericPlayer(params), 34 mDataSource(0), 35 mAudioSource(0), 36 mAudioSourceStarted(false), 37 mBitrate(-1), 38 mDurationUsec(ANDROID_UNKNOWN_TIME), 39 mDecodeBuffer(NULL), 40 mSeekTimeMsec(0), 41 // play event logic depends on the initial time being zero not ANDROID_UNKNOWN_TIME 42 mLastDecodedPositionUs(0) 43 { 44 SL_LOGD("AudioSfDecoder::AudioSfDecoder()"); 45 } 46 47 48 AudioSfDecoder::~AudioSfDecoder() { 49 SL_LOGD("AudioSfDecoder::~AudioSfDecoder()"); 50 } 51 52 53 void AudioSfDecoder::preDestroy() { 54 GenericPlayer::preDestroy(); 55 SL_LOGD("AudioSfDecoder::preDestroy()"); 56 { 57 Mutex::Autolock _l(mBufferSourceLock); 58 59 if (NULL != mDecodeBuffer) { 60 mDecodeBuffer->release(); 61 mDecodeBuffer = NULL; 62 } 63 64 if ((mAudioSource != 0) && mAudioSourceStarted) { 65 mAudioSource->stop(); 66 mAudioSourceStarted = false; 67 } 68 } 69 } 70 71 72 //-------------------------------------------------- 73 void AudioSfDecoder::play() { 74 SL_LOGD("AudioSfDecoder::play"); 75 76 GenericPlayer::play(); 77 (new AMessage(kWhatDecode, id()))->post(); 78 } 79 80 81 void AudioSfDecoder::getPositionMsec(int* msec) { 82 int64_t timeUsec = getPositionUsec(); 83 if (timeUsec == ANDROID_UNKNOWN_TIME) { 84 *msec = ANDROID_UNKNOWN_TIME; 85 } else { 86 *msec = timeUsec / 1000; 87 } 88 } 89 90 91 //-------------------------------------------------- 92 uint32_t AudioSfDecoder::getPcmFormatKeyCount() const { 93 return NB_PCMMETADATA_KEYS; 94 } 95 96 97 //-------------------------------------------------- 98 bool AudioSfDecoder::getPcmFormatKeySize(uint32_t index, uint32_t* pKeySize) { 99 if (index >= NB_PCMMETADATA_KEYS) { 100 return false; 101 } else { 102 *pKeySize = strlen(kPcmDecodeMetadataKeys[index]) +1; 103 return true; 104 } 105 } 106 107 108 //-------------------------------------------------- 109 bool AudioSfDecoder::getPcmFormatKeyName(uint32_t index, uint32_t keySize, char* keyName) { 110 uint32_t actualKeySize; 111 if (!getPcmFormatKeySize(index, &actualKeySize)) { 112 return false; 113 } 114 if (keySize < actualKeySize) { 115 return false; 116 } 117 strncpy(keyName, kPcmDecodeMetadataKeys[index], actualKeySize); 118 return true; 119 } 120 121 122 //-------------------------------------------------- 123 bool AudioSfDecoder::getPcmFormatValueSize(uint32_t index, uint32_t* pValueSize) { 124 if (index >= NB_PCMMETADATA_KEYS) { 125 *pValueSize = 0; 126 return false; 127 } else { 128 *pValueSize = sizeof(uint32_t); 129 return true; 130 } 131 } 132 133 134 //-------------------------------------------------- 135 bool AudioSfDecoder::getPcmFormatKeyValue(uint32_t index, uint32_t size, uint32_t* pValue) { 136 uint32_t valueSize = 0; 137 if (!getPcmFormatValueSize(index, &valueSize)) { 138 return false; 139 } else if (size != valueSize) { 140 // this ensures we are accessing mPcmFormatValues with a valid size for that index 141 SL_LOGE("Error retrieving metadata value at index %d: using size of %d, should be %d", 142 index, size, valueSize); 143 return false; 144 } else { 145 android::Mutex::Autolock autoLock(mPcmFormatLock); 146 *pValue = mPcmFormatValues[index]; 147 return true; 148 } 149 } 150 151 152 //-------------------------------------------------- 153 // Event handlers 154 // it is strictly verboten to call those methods outside of the event loop 155 156 // Initializes the data and audio sources, and update the PCM format info 157 // post-condition: upon successful initialization based on the player data locator 158 // GenericPlayer::onPrepare() was called 159 // mDataSource != 0 160 // mAudioSource != 0 161 // mAudioSourceStarted == true 162 // All error returns from this method are via notifyPrepared(status) followed by "return". 163 void AudioSfDecoder::onPrepare() { 164 SL_LOGD("AudioSfDecoder::onPrepare()"); 165 Mutex::Autolock _l(mBufferSourceLock); 166 167 { 168 android::Mutex::Autolock autoLock(mPcmFormatLock); 169 // Initialize the PCM format info with the known parameters before the start of the decode 170 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_BITSPERSAMPLE] = SL_PCMSAMPLEFORMAT_FIXED_16; 171 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CONTAINERSIZE] = 16; 172 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_ENDIANNESS] = SL_BYTEORDER_LITTLEENDIAN; 173 // initialization with the default values: they will be replaced by the actual values 174 // once the decoder has figured them out 175 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS] = UNKNOWN_NUMCHANNELS; 176 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE] = UNKNOWN_SAMPLERATE; 177 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CHANNELMASK] = UNKNOWN_CHANNELMASK; 178 } 179 180 //--------------------------------- 181 // Instantiate and initialize the data source for the decoder 182 sp<DataSource> dataSource; 183 184 switch (mDataLocatorType) { 185 186 case kDataLocatorNone: 187 SL_LOGE("AudioSfDecoder::onPrepare: no data locator set"); 188 notifyPrepared(MEDIA_ERROR_BASE); 189 return; 190 191 case kDataLocatorUri: 192 dataSource = DataSource::CreateFromURI(mDataLocator.uriRef); 193 if (dataSource == NULL) { 194 SL_LOGE("AudioSfDecoder::onPrepare(): Error opening %s", mDataLocator.uriRef); 195 notifyPrepared(MEDIA_ERROR_BASE); 196 return; 197 } 198 break; 199 200 case kDataLocatorFd: 201 { 202 // As FileSource unconditionally takes ownership of the fd and closes it, then 203 // we have to make a dup for FileSource if the app wants to keep ownership itself 204 int fd = mDataLocator.fdi.fd; 205 if (mDataLocator.fdi.mCloseAfterUse) { 206 mDataLocator.fdi.mCloseAfterUse = false; 207 } else { 208 fd = ::dup(fd); 209 } 210 dataSource = new FileSource(fd, mDataLocator.fdi.offset, mDataLocator.fdi.length); 211 status_t err = dataSource->initCheck(); 212 if (err != OK) { 213 notifyPrepared(err); 214 return; 215 } 216 break; 217 } 218 219 default: 220 TRESPASS(); 221 } 222 223 //--------------------------------- 224 // Instanciate and initialize the decoder attached to the data source 225 sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource); 226 if (extractor == NULL) { 227 SL_LOGE("AudioSfDecoder::onPrepare: Could not instantiate extractor."); 228 notifyPrepared(ERROR_UNSUPPORTED); 229 return; 230 } 231 232 ssize_t audioTrackIndex = -1; 233 bool isRawAudio = false; 234 for (size_t i = 0; i < extractor->countTracks(); ++i) { 235 sp<MetaData> meta = extractor->getTrackMetaData(i); 236 237 const char *mime; 238 CHECK(meta->findCString(kKeyMIMEType, &mime)); 239 240 if (!strncasecmp("audio/", mime, 6)) { 241 if (isSupportedCodec(mime)) { 242 audioTrackIndex = i; 243 244 if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mime)) { 245 isRawAudio = true; 246 } 247 break; 248 } 249 } 250 } 251 252 if (audioTrackIndex < 0) { 253 SL_LOGE("AudioSfDecoder::onPrepare: Could not find a supported audio track."); 254 notifyPrepared(ERROR_UNSUPPORTED); 255 return; 256 } 257 258 sp<MediaSource> source = extractor->getTrack(audioTrackIndex); 259 sp<MetaData> meta = source->getFormat(); 260 261 // we can't trust the OMXCodec (if there is one) to issue a INFO_FORMAT_CHANGED so we want 262 // to have some meaningful values as soon as possible. 263 int32_t channelCount; 264 bool hasChannelCount = meta->findInt32(kKeyChannelCount, &channelCount); 265 int32_t sr; 266 bool hasSampleRate = meta->findInt32(kKeySampleRate, &sr); 267 268 // first compute the duration 269 off64_t size; 270 int64_t durationUs; 271 int32_t durationMsec; 272 if (dataSource->getSize(&size) == OK 273 && meta->findInt64(kKeyDuration, &durationUs)) { 274 if (durationUs != 0) { 275 mBitrate = size * 8000000ll / durationUs; // in bits/sec 276 } else { 277 mBitrate = -1; 278 } 279 mDurationUsec = durationUs; 280 durationMsec = durationUs / 1000; 281 } else { 282 mBitrate = -1; 283 mDurationUsec = ANDROID_UNKNOWN_TIME; 284 durationMsec = ANDROID_UNKNOWN_TIME; 285 } 286 287 // then assign the duration under the settings lock 288 { 289 Mutex::Autolock _l(mSettingsLock); 290 mDurationMsec = durationMsec; 291 } 292 293 // the audio content is not raw PCM, so we need a decoder 294 if (!isRawAudio) { 295 OMXClient client; 296 CHECK_EQ(client.connect(), (status_t)OK); 297 298 source = OMXCodec::Create( 299 client.interface(), meta, false /* createEncoder */, 300 source); 301 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 channelCountToMask(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 366 void AudioSfDecoder::onPause() { 367 SL_LOGV("AudioSfDecoder::onPause()"); 368 GenericPlayer::onPause(); 369 pauseAudioSink(); 370 } 371 372 373 void AudioSfDecoder::onPlay() { 374 SL_LOGV("AudioSfDecoder::onPlay()"); 375 GenericPlayer::onPlay(); 376 startAudioSink(); 377 } 378 379 380 void 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 396 void 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 414 void 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, id()))->post(); 435 } 436 return; 437 } 438 439 msg->post(100000); 440 } 441 442 443 void 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, id()))->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 } 501 } 502 503 { 504 Mutex::Autolock _l(mTimeLock); 505 if (mStateFlags & kFlagSeeking) { 506 mStateFlags &= ~kFlagSeeking; 507 mSeekTimeMsec = ANDROID_UNKNOWN_TIME; 508 } 509 if (timeUsec != ANDROID_UNKNOWN_TIME) { 510 // Note that though we've decoded this position, we haven't rendered it yet. 511 // So a GetPosition called after this point will observe the advanced position, 512 // even though the PCM may not have been supplied to the sink. That's OK as 513 // we don't claim to provide frame-accurate (let alone sample-accurate) GetPosition. 514 mLastDecodedPositionUs = timeUsec; 515 } 516 } 517 518 //-------------------------------- Handle return of decode 519 if (err != OK) { 520 bool continueDecoding = false; 521 switch(err) { 522 case ERROR_END_OF_STREAM: 523 if (0 < mDurationUsec) { 524 Mutex::Autolock _l(mTimeLock); 525 mLastDecodedPositionUs = mDurationUsec; 526 } 527 // handle notification and looping at end of stream 528 if (mStateFlags & kFlagPlaying) { 529 notify(PLAYEREVENT_ENDOFSTREAM, 1, true); 530 } 531 if (mStateFlags & kFlagLooping) { 532 seek(0); 533 // kick-off decoding again 534 continueDecoding = true; 535 } 536 break; 537 case INFO_FORMAT_CHANGED: 538 SL_LOGD("MediaSource::read encountered INFO_FORMAT_CHANGED"); 539 // reconfigure output 540 { 541 Mutex::Autolock _l(mBufferSourceLock); 542 hasNewDecodeParams(); 543 } 544 continueDecoding = true; 545 break; 546 case INFO_DISCONTINUITY: 547 SL_LOGD("MediaSource::read encountered INFO_DISCONTINUITY"); 548 continueDecoding = true; 549 break; 550 default: 551 SL_LOGE("MediaSource::read returned error %d", err); 552 break; 553 } 554 if (continueDecoding) { 555 if (NULL == mDecodeBuffer) { 556 (new AMessage(kWhatDecode, id()))->post(); 557 return; 558 } 559 } else { 560 return; 561 } 562 } 563 564 //-------------------------------- Render 565 sp<AMessage> msg = new AMessage(kWhatRender, id()); 566 msg->post(); 567 568 } 569 570 571 void AudioSfDecoder::onMessageReceived(const sp<AMessage> &msg) { 572 switch (msg->what()) { 573 case kWhatDecode: 574 onDecode(); 575 break; 576 577 case kWhatRender: 578 onRender(); 579 break; 580 581 case kWhatCheckCache: 582 onCheckCache(msg); 583 break; 584 585 default: 586 GenericPlayer::onMessageReceived(msg); 587 break; 588 } 589 } 590 591 //-------------------------------------------------- 592 // Prepared state, prefetch status notifications 593 void AudioSfDecoder::notifyPrepared(status_t prepareRes) { 594 assert(!(mStateFlags & (kFlagPrepared | kFlagPreparedUnsuccessfully))); 595 if (NO_ERROR == prepareRes) { 596 // The "then" fork is not currently used, but is kept here to make it easier 597 // to replace by a new signalPrepareCompletion(status) if we re-visit this later. 598 mStateFlags |= kFlagPrepared; 599 } else { 600 mStateFlags |= kFlagPreparedUnsuccessfully; 601 } 602 // Do not call the superclass onPrepare to notify, because it uses a default error 603 // status code but we can provide a more specific one. 604 // GenericPlayer::onPrepare(); 605 notify(PLAYEREVENT_PREPARED, (int32_t)prepareRes, true); 606 SL_LOGD("AudioSfDecoder::onPrepare() done, mStateFlags=0x%x", mStateFlags); 607 } 608 609 610 void AudioSfDecoder::onNotify(const sp<AMessage> &msg) { 611 notif_cbf_t notifyClient; 612 void* notifyUser; 613 { 614 android::Mutex::Autolock autoLock(mNotifyClientLock); 615 if (NULL == mNotifyClient) { 616 return; 617 } else { 618 notifyClient = mNotifyClient; 619 notifyUser = mNotifyUser; 620 } 621 } 622 int32_t val; 623 if (msg->findInt32(PLAYEREVENT_PREFETCHSTATUSCHANGE, &val)) { 624 SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_PREFETCHSTATUSCHANGE, val); 625 notifyClient(kEventPrefetchStatusChange, val, 0, notifyUser); 626 } 627 else if (msg->findInt32(PLAYEREVENT_PREFETCHFILLLEVELUPDATE, &val)) { 628 SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_PREFETCHFILLLEVELUPDATE, val); 629 notifyClient(kEventPrefetchFillLevelUpdate, val, 0, notifyUser); 630 } 631 else if (msg->findInt32(PLAYEREVENT_ENDOFSTREAM, &val)) { 632 SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_ENDOFSTREAM, val); 633 notifyClient(kEventEndOfStream, val, 0, notifyUser); 634 } 635 else { 636 GenericPlayer::onNotify(msg); 637 } 638 } 639 640 641 //-------------------------------------------------- 642 // Private utility functions 643 644 bool AudioSfDecoder::wantPrefetch() { 645 if (mDataSource != 0) { 646 return (mDataSource->flags() & DataSource::kWantsPrefetching); 647 } else { 648 // happens if an improper data locator was passed, if the media extractor couldn't be 649 // initialized, if there is no audio track in the media, if the OMX decoder couldn't be 650 // instantiated, if the source couldn't be opened, or if the MediaSource 651 // couldn't be started 652 SL_LOGV("AudioSfDecoder::wantPrefetch() tries to access NULL mDataSource"); 653 return false; 654 } 655 } 656 657 658 int64_t AudioSfDecoder::getPositionUsec() { 659 Mutex::Autolock _l(mTimeLock); 660 if (mStateFlags & kFlagSeeking) { 661 return mSeekTimeMsec * 1000; 662 } else { 663 return mLastDecodedPositionUs; 664 } 665 } 666 667 668 CacheStatus_t AudioSfDecoder::getCacheRemaining(bool *eos) { 669 sp<NuCachedSource2> cachedSource = 670 static_cast<NuCachedSource2 *>(mDataSource.get()); 671 672 CacheStatus_t oldStatus = mCacheStatus; 673 674 status_t finalStatus; 675 size_t dataRemaining = cachedSource->approxDataRemaining(&finalStatus); 676 *eos = (finalStatus != OK); 677 678 CHECK_GE(mBitrate, 0); 679 680 int64_t dataRemainingUs = dataRemaining * 8000000ll / mBitrate; 681 //SL_LOGV("AudioSfDecoder::getCacheRemaining: approx %.2f secs remaining (eos=%d)", 682 // dataRemainingUs / 1E6, *eos); 683 684 if (*eos) { 685 // data is buffered up to the end of the stream, it can't get any better than this 686 mCacheStatus = kStatusHigh; 687 mCacheFill = 1000; 688 689 } else { 690 if (mDurationUsec > 0) { 691 // known duration: 692 693 // fill level is ratio of how much has been played + how much is 694 // cached, divided by total duration 695 uint32_t currentPositionUsec = getPositionUsec(); 696 if (currentPositionUsec == ANDROID_UNKNOWN_TIME) { 697 // if we don't know where we are, assume the worst for the fill ratio 698 currentPositionUsec = 0; 699 } 700 if (mDurationUsec > 0) { 701 mCacheFill = (int16_t) ((1000.0 702 * (double)(currentPositionUsec + dataRemainingUs) / mDurationUsec)); 703 } else { 704 mCacheFill = 0; 705 } 706 //SL_LOGV("cacheFill = %d", mCacheFill); 707 708 // cache status is evaluated against duration thresholds 709 if (dataRemainingUs > DURATION_CACHED_HIGH_MS*1000) { 710 mCacheStatus = kStatusHigh; 711 //LOGV("high"); 712 } else if (dataRemainingUs > DURATION_CACHED_MED_MS*1000) { 713 //LOGV("enough"); 714 mCacheStatus = kStatusEnough; 715 } else if (dataRemainingUs < DURATION_CACHED_LOW_MS*1000) { 716 //LOGV("low"); 717 mCacheStatus = kStatusLow; 718 } else { 719 mCacheStatus = kStatusIntermediate; 720 } 721 722 } else { 723 // unknown duration: 724 725 // cache status is evaluated against cache amount thresholds 726 // (no duration so we don't have the bitrate either, could be derived from format?) 727 if (dataRemaining > SIZE_CACHED_HIGH_BYTES) { 728 mCacheStatus = kStatusHigh; 729 } else if (dataRemaining > SIZE_CACHED_MED_BYTES) { 730 mCacheStatus = kStatusEnough; 731 } else if (dataRemaining < SIZE_CACHED_LOW_BYTES) { 732 mCacheStatus = kStatusLow; 733 } else { 734 mCacheStatus = kStatusIntermediate; 735 } 736 } 737 738 } 739 740 if (oldStatus != mCacheStatus) { 741 notifyStatus(); 742 } 743 744 if (abs(mCacheFill - mLastNotifiedCacheFill) > mCacheFillNotifThreshold) { 745 notifyCacheFill(); 746 } 747 748 return mCacheStatus; 749 } 750 751 752 void AudioSfDecoder::hasNewDecodeParams() { 753 754 if ((mAudioSource != 0) && mAudioSourceStarted) { 755 sp<MetaData> meta = mAudioSource->getFormat(); 756 757 int32_t channelCount; 758 CHECK(meta->findInt32(kKeyChannelCount, &channelCount)); 759 int32_t sr; 760 CHECK(meta->findInt32(kKeySampleRate, &sr)); 761 762 // FIXME similar to onPrepare() 763 { 764 android::Mutex::Autolock autoLock(mPcmFormatLock); 765 SL_LOGV("format changed: old sr=%d, channels=%d; new sr=%d, channels=%d", 766 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE], 767 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS], 768 sr, channelCount); 769 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS] = channelCount; 770 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE] = sr; 771 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CHANNELMASK] = 772 channelCountToMask(channelCount); 773 } 774 } 775 776 // alert users of those params 777 updateAudioSink(); 778 } 779 780 static const char* const kPlaybackOnlyCodecs[] = { MEDIA_MIMETYPE_AUDIO_AMR_NB, 781 MEDIA_MIMETYPE_AUDIO_AMR_WB }; 782 #define NB_PLAYBACK_ONLY_CODECS (sizeof(kPlaybackOnlyCodecs)/sizeof(kPlaybackOnlyCodecs[0])) 783 784 bool AudioSfDecoder::isSupportedCodec(const char* mime) { 785 bool codecRequiresPermission = false; 786 for (unsigned int i = 0 ; i < NB_PLAYBACK_ONLY_CODECS ; i++) { 787 if (!strcasecmp(mime, kPlaybackOnlyCodecs[i])) { 788 codecRequiresPermission = true; 789 break; 790 } 791 } 792 if (codecRequiresPermission) { 793 // verify only the system can decode, for playback only 794 return checkCallingPermission( 795 String16("android.permission.ALLOW_ANY_CODEC_FOR_PLAYBACK")); 796 } else { 797 return true; 798 } 799 } 800 801 } // namespace android 802