android_AudioSfDecoder.cpp revision d9193f90228723898127d6a21b1404c222a479a3
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 mLastDecodedPositionUs = timeUsec; 512 } 513 } 514 515 //-------------------------------- Handle return of decode 516 if (err != OK) { 517 bool continueDecoding = false; 518 switch(err) { 519 case ERROR_END_OF_STREAM: 520 if (0 < mDurationUsec) { 521 Mutex::Autolock _l(mTimeLock); 522 mLastDecodedPositionUs = mDurationUsec; 523 } 524 // handle notification and looping at end of stream 525 if (mStateFlags & kFlagPlaying) { 526 notify(PLAYEREVENT_ENDOFSTREAM, 1, true); 527 } 528 if (mStateFlags & kFlagLooping) { 529 seek(0); 530 // kick-off decoding again 531 continueDecoding = true; 532 } 533 break; 534 case INFO_FORMAT_CHANGED: 535 SL_LOGD("MediaSource::read encountered INFO_FORMAT_CHANGED"); 536 // reconfigure output 537 { 538 Mutex::Autolock _l(mBufferSourceLock); 539 hasNewDecodeParams(); 540 } 541 continueDecoding = true; 542 break; 543 case INFO_DISCONTINUITY: 544 SL_LOGD("MediaSource::read encountered INFO_DISCONTINUITY"); 545 continueDecoding = true; 546 break; 547 default: 548 SL_LOGE("MediaSource::read returned error %d", err); 549 break; 550 } 551 if (continueDecoding) { 552 if (NULL == mDecodeBuffer) { 553 (new AMessage(kWhatDecode, id()))->post(); 554 return; 555 } 556 } else { 557 return; 558 } 559 } 560 561 //-------------------------------- Render 562 sp<AMessage> msg = new AMessage(kWhatRender, id()); 563 msg->post(); 564} 565 566 567void AudioSfDecoder::onRender() { 568 //SL_LOGV("AudioSfDecoder::onRender"); 569 570 Mutex::Autolock _l(mBufferSourceLock); 571 572 if (NULL == mDecodeBuffer) { 573 // nothing to render, move along 574 SL_LOGV("AudioSfDecoder::onRender NULL buffer, exiting"); 575 return; 576 } 577 578 mDecodeBuffer->release(); 579 mDecodeBuffer = NULL; 580 581} 582 583 584void AudioSfDecoder::onMessageReceived(const sp<AMessage> &msg) { 585 switch (msg->what()) { 586 case kWhatDecode: 587 onDecode(); 588 break; 589 590 case kWhatRender: 591 onRender(); 592 break; 593 594 case kWhatCheckCache: 595 onCheckCache(msg); 596 break; 597 598 default: 599 GenericPlayer::onMessageReceived(msg); 600 break; 601 } 602} 603 604//-------------------------------------------------- 605// Prepared state, prefetch status notifications 606void AudioSfDecoder::notifyPrepared(status_t prepareRes) { 607 assert(!(mStateFlags & (kFlagPrepared | kFlagPreparedUnsuccessfully))); 608 if (NO_ERROR == prepareRes) { 609 // The "then" fork is not currently used, but is kept here to make it easier 610 // to replace by a new signalPrepareCompletion(status) if we re-visit this later. 611 mStateFlags |= kFlagPrepared; 612 } else { 613 mStateFlags |= kFlagPreparedUnsuccessfully; 614 } 615 // Do not call the superclass onPrepare to notify, because it uses a default error 616 // status code but we can provide a more specific one. 617 // GenericPlayer::onPrepare(); 618 notify(PLAYEREVENT_PREPARED, (int32_t)prepareRes, true); 619 SL_LOGD("AudioSfDecoder::onPrepare() done, mStateFlags=0x%x", mStateFlags); 620} 621 622 623void AudioSfDecoder::onNotify(const sp<AMessage> &msg) { 624 notif_cbf_t notifyClient; 625 void* notifyUser; 626 { 627 android::Mutex::Autolock autoLock(mNotifyClientLock); 628 if (NULL == mNotifyClient) { 629 return; 630 } else { 631 notifyClient = mNotifyClient; 632 notifyUser = mNotifyUser; 633 } 634 } 635 int32_t val; 636 if (msg->findInt32(PLAYEREVENT_PREFETCHSTATUSCHANGE, &val)) { 637 SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_PREFETCHSTATUSCHANGE, val); 638 notifyClient(kEventPrefetchStatusChange, val, 0, notifyUser); 639 } 640 else if (msg->findInt32(PLAYEREVENT_PREFETCHFILLLEVELUPDATE, &val)) { 641 SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_PREFETCHFILLLEVELUPDATE, val); 642 notifyClient(kEventPrefetchFillLevelUpdate, val, 0, notifyUser); 643 } 644 else if (msg->findInt32(PLAYEREVENT_ENDOFSTREAM, &val)) { 645 SL_LOGV("\tASfPlayer notifying %s = %d", PLAYEREVENT_ENDOFSTREAM, val); 646 notifyClient(kEventEndOfStream, val, 0, notifyUser); 647 } 648 else { 649 GenericPlayer::onNotify(msg); 650 } 651} 652 653 654//-------------------------------------------------- 655// Private utility functions 656 657bool AudioSfDecoder::wantPrefetch() { 658 if (mDataSource != 0) { 659 return (mDataSource->flags() & DataSource::kWantsPrefetching); 660 } else { 661 // happens if an improper data locator was passed, if the media extractor couldn't be 662 // initialized, if there is no audio track in the media, if the OMX decoder couldn't be 663 // instantiated, if the source couldn't be opened, or if the MediaSource 664 // couldn't be started 665 SL_LOGV("AudioSfDecoder::wantPrefetch() tries to access NULL mDataSource"); 666 return false; 667 } 668} 669 670 671int64_t AudioSfDecoder::getPositionUsec() { 672 Mutex::Autolock _l(mTimeLock); 673 if (mStateFlags & kFlagSeeking) { 674 return mSeekTimeMsec * 1000; 675 } else { 676 return mLastDecodedPositionUs; 677 } 678} 679 680 681CacheStatus_t AudioSfDecoder::getCacheRemaining(bool *eos) { 682 sp<NuCachedSource2> cachedSource = 683 static_cast<NuCachedSource2 *>(mDataSource.get()); 684 685 CacheStatus_t oldStatus = mCacheStatus; 686 687 status_t finalStatus; 688 size_t dataRemaining = cachedSource->approxDataRemaining(&finalStatus); 689 *eos = (finalStatus != OK); 690 691 CHECK_GE(mBitrate, 0); 692 693 int64_t dataRemainingUs = dataRemaining * 8000000ll / mBitrate; 694 //SL_LOGV("AudioSfDecoder::getCacheRemaining: approx %.2f secs remaining (eos=%d)", 695 // dataRemainingUs / 1E6, *eos); 696 697 if (*eos) { 698 // data is buffered up to the end of the stream, it can't get any better than this 699 mCacheStatus = kStatusHigh; 700 mCacheFill = 1000; 701 702 } else { 703 if (mDurationUsec > 0) { 704 // known duration: 705 706 // fill level is ratio of how much has been played + how much is 707 // cached, divided by total duration 708 uint32_t currentPositionUsec = getPositionUsec(); 709 if (currentPositionUsec == ANDROID_UNKNOWN_TIME) { 710 // if we don't know where we are, assume the worst for the fill ratio 711 currentPositionUsec = 0; 712 } 713 if (mDurationUsec > 0) { 714 mCacheFill = (int16_t) ((1000.0 715 * (double)(currentPositionUsec + dataRemainingUs) / mDurationUsec)); 716 } else { 717 mCacheFill = 0; 718 } 719 //SL_LOGV("cacheFill = %d", mCacheFill); 720 721 // cache status is evaluated against duration thresholds 722 if (dataRemainingUs > DURATION_CACHED_HIGH_MS*1000) { 723 mCacheStatus = kStatusHigh; 724 //LOGV("high"); 725 } else if (dataRemainingUs > DURATION_CACHED_MED_MS*1000) { 726 //LOGV("enough"); 727 mCacheStatus = kStatusEnough; 728 } else if (dataRemainingUs < DURATION_CACHED_LOW_MS*1000) { 729 //LOGV("low"); 730 mCacheStatus = kStatusLow; 731 } else { 732 mCacheStatus = kStatusIntermediate; 733 } 734 735 } else { 736 // unknown duration: 737 738 // cache status is evaluated against cache amount thresholds 739 // (no duration so we don't have the bitrate either, could be derived from format?) 740 if (dataRemaining > SIZE_CACHED_HIGH_BYTES) { 741 mCacheStatus = kStatusHigh; 742 } else if (dataRemaining > SIZE_CACHED_MED_BYTES) { 743 mCacheStatus = kStatusEnough; 744 } else if (dataRemaining < SIZE_CACHED_LOW_BYTES) { 745 mCacheStatus = kStatusLow; 746 } else { 747 mCacheStatus = kStatusIntermediate; 748 } 749 } 750 751 } 752 753 if (oldStatus != mCacheStatus) { 754 notifyStatus(); 755 } 756 757 if (abs(mCacheFill - mLastNotifiedCacheFill) > mCacheFillNotifThreshold) { 758 notifyCacheFill(); 759 } 760 761 return mCacheStatus; 762} 763 764 765void AudioSfDecoder::hasNewDecodeParams() { 766 767 if ((mAudioSource != 0) && mAudioSourceStarted) { 768 sp<MetaData> meta = mAudioSource->getFormat(); 769 770 SL_LOGV("old sample rate = %d, channel count = %d", mSampleRateHz, mChannelCount); 771 772 CHECK(meta->findInt32(kKeyChannelCount, &mChannelCount)); 773 int32_t sr; 774 CHECK(meta->findInt32(kKeySampleRate, &sr)); 775 mSampleRateHz = (uint32_t) sr; 776 SL_LOGV("format changed: new sample rate = %d, channel count = %d", 777 mSampleRateHz, mChannelCount); 778 779 // FIXME similar to onPrepare() 780 mChannelMask = channelCountToMask(mChannelCount); 781 782 { 783 android::Mutex::Autolock autoLock(mPcmFormatLock); 784 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_NUMCHANNELS] = mChannelCount; 785 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_SAMPLERATE] = mSampleRateHz; 786 mPcmFormatValues[ANDROID_KEY_INDEX_PCMFORMAT_CHANNELMASK] = mChannelMask; 787 } 788 } 789 790 // alert users of those params 791 updateAudioSink(); 792} 793 794} // namespace android 795