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