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