NuPlayerRenderer.cpp revision 202bce11a7f66f27e6dbb6d154ddc123aa62513d
1/* 2 * Copyright (C) 2010 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 LOG_NDEBUG 0 18#define LOG_TAG "NuPlayerRenderer" 19#include <utils/Log.h> 20 21#include "NuPlayerRenderer.h" 22 23#include <media/stagefright/foundation/ABuffer.h> 24#include <media/stagefright/foundation/ADebug.h> 25#include <media/stagefright/foundation/AMessage.h> 26#include <media/stagefright/foundation/AUtils.h> 27#include <media/stagefright/MediaErrors.h> 28#include <media/stagefright/MetaData.h> 29#include <media/stagefright/Utils.h> 30 31#include <VideoFrameScheduler.h> 32 33#include <inttypes.h> 34 35namespace android { 36 37// Maximum time in paused state when offloading audio decompression. When elapsed, the AudioSink 38// is closed to allow the audio DSP to power down. 39static const int64_t kOffloadPauseMaxUs = 10000000ll; 40 41// static 42const int64_t NuPlayer::Renderer::kMinPositionUpdateDelayUs = 100000ll; 43 44NuPlayer::Renderer::Renderer( 45 const sp<MediaPlayerBase::AudioSink> &sink, 46 const sp<AMessage> ¬ify, 47 uint32_t flags) 48 : mAudioSink(sink), 49 mNotify(notify), 50 mFlags(flags), 51 mNumFramesWritten(0), 52 mDrainAudioQueuePending(false), 53 mDrainVideoQueuePending(false), 54 mAudioQueueGeneration(0), 55 mVideoQueueGeneration(0), 56 mAudioFirstAnchorTimeMediaUs(-1), 57 mAnchorTimeMediaUs(-1), 58 mAnchorTimeRealUs(-1), 59 mAnchorNumFramesWritten(-1), 60 mAnchorMaxMediaUs(-1), 61 mVideoLateByUs(0ll), 62 mHasAudio(false), 63 mHasVideo(false), 64 mPauseStartedTimeRealUs(-1), 65 mFlushingAudio(false), 66 mFlushingVideo(false), 67 mNotifyCompleteAudio(false), 68 mNotifyCompleteVideo(false), 69 mSyncQueues(false), 70 mPaused(false), 71 mVideoSampleReceived(false), 72 mVideoRenderingStarted(false), 73 mVideoRenderingStartGeneration(0), 74 mAudioRenderingStartGeneration(0), 75 mAudioOffloadPauseTimeoutGeneration(0), 76 mAudioOffloadTornDown(false), 77 mCurrentOffloadInfo(AUDIO_INFO_INITIALIZER), 78 mTotalBuffersQueued(0), 79 mLastAudioBufferDrained(0) { 80} 81 82NuPlayer::Renderer::~Renderer() { 83 if (offloadingAudio()) { 84 mAudioSink->stop(); 85 mAudioSink->flush(); 86 mAudioSink->close(); 87 } 88} 89 90void NuPlayer::Renderer::queueBuffer( 91 bool audio, 92 const sp<ABuffer> &buffer, 93 const sp<AMessage> ¬ifyConsumed) { 94 sp<AMessage> msg = new AMessage(kWhatQueueBuffer, id()); 95 msg->setInt32("audio", static_cast<int32_t>(audio)); 96 msg->setBuffer("buffer", buffer); 97 msg->setMessage("notifyConsumed", notifyConsumed); 98 msg->post(); 99} 100 101void NuPlayer::Renderer::queueEOS(bool audio, status_t finalResult) { 102 CHECK_NE(finalResult, (status_t)OK); 103 104 sp<AMessage> msg = new AMessage(kWhatQueueEOS, id()); 105 msg->setInt32("audio", static_cast<int32_t>(audio)); 106 msg->setInt32("finalResult", finalResult); 107 msg->post(); 108} 109 110void NuPlayer::Renderer::flush(bool audio, bool notifyComplete) { 111 { 112 Mutex::Autolock autoLock(mFlushLock); 113 if (audio) { 114 mNotifyCompleteAudio |= notifyComplete; 115 if (mFlushingAudio) { 116 return; 117 } 118 mFlushingAudio = true; 119 } else { 120 mNotifyCompleteVideo |= notifyComplete; 121 if (mFlushingVideo) { 122 return; 123 } 124 mFlushingVideo = true; 125 } 126 } 127 128 sp<AMessage> msg = new AMessage(kWhatFlush, id()); 129 msg->setInt32("audio", static_cast<int32_t>(audio)); 130 msg->post(); 131} 132 133void NuPlayer::Renderer::signalTimeDiscontinuity() { 134 Mutex::Autolock autoLock(mLock); 135 // CHECK(mAudioQueue.empty()); 136 // CHECK(mVideoQueue.empty()); 137 setAudioFirstAnchorTime(-1); 138 setAnchorTime(-1, -1); 139 setVideoLateByUs(0); 140 mSyncQueues = false; 141} 142 143void NuPlayer::Renderer::signalAudioSinkChanged() { 144 (new AMessage(kWhatAudioSinkChanged, id()))->post(); 145} 146 147void NuPlayer::Renderer::signalDisableOffloadAudio() { 148 (new AMessage(kWhatDisableOffloadAudio, id()))->post(); 149} 150 151void NuPlayer::Renderer::signalEnableOffloadAudio() { 152 (new AMessage(kWhatEnableOffloadAudio, id()))->post(); 153} 154 155void NuPlayer::Renderer::pause() { 156 (new AMessage(kWhatPause, id()))->post(); 157} 158 159void NuPlayer::Renderer::resume() { 160 (new AMessage(kWhatResume, id()))->post(); 161} 162 163void NuPlayer::Renderer::setVideoFrameRate(float fps) { 164 sp<AMessage> msg = new AMessage(kWhatSetVideoFrameRate, id()); 165 msg->setFloat("frame-rate", fps); 166 msg->post(); 167} 168 169status_t NuPlayer::Renderer::getCurrentPosition(int64_t *mediaUs) { 170 return getCurrentPosition(mediaUs, ALooper::GetNowUs()); 171} 172 173status_t NuPlayer::Renderer::getCurrentPosition( 174 int64_t *mediaUs, int64_t nowUs, bool allowPastQueuedVideo) { 175 Mutex::Autolock autoLock(mTimeLock); 176 if (!mHasAudio && !mHasVideo) { 177 return NO_INIT; 178 } 179 180 if (mAnchorTimeMediaUs < 0) { 181 return NO_INIT; 182 } 183 184 int64_t positionUs = (nowUs - mAnchorTimeRealUs) + mAnchorTimeMediaUs; 185 186 if (mPauseStartedTimeRealUs != -1) { 187 positionUs -= (nowUs - mPauseStartedTimeRealUs); 188 } 189 190 // limit position to the last queued media time (for video only stream 191 // position will be discrete as we don't know how long each frame lasts) 192 if (mAnchorMaxMediaUs >= 0 && !allowPastQueuedVideo) { 193 if (positionUs > mAnchorMaxMediaUs) { 194 positionUs = mAnchorMaxMediaUs; 195 } 196 } 197 198 if (positionUs < mAudioFirstAnchorTimeMediaUs) { 199 positionUs = mAudioFirstAnchorTimeMediaUs; 200 } 201 202 *mediaUs = (positionUs <= 0) ? 0 : positionUs; 203 return OK; 204} 205 206void NuPlayer::Renderer::setHasMedia(bool audio) { 207 Mutex::Autolock autoLock(mTimeLock); 208 if (audio) { 209 mHasAudio = true; 210 } else { 211 mHasVideo = true; 212 } 213} 214 215void NuPlayer::Renderer::setAudioFirstAnchorTime(int64_t mediaUs) { 216 Mutex::Autolock autoLock(mTimeLock); 217 mAudioFirstAnchorTimeMediaUs = mediaUs; 218} 219 220void NuPlayer::Renderer::setAudioFirstAnchorTimeIfNeeded(int64_t mediaUs) { 221 Mutex::Autolock autoLock(mTimeLock); 222 if (mAudioFirstAnchorTimeMediaUs == -1) { 223 mAudioFirstAnchorTimeMediaUs = mediaUs; 224 } 225} 226 227void NuPlayer::Renderer::setAnchorTime( 228 int64_t mediaUs, int64_t realUs, int64_t numFramesWritten, bool resume) { 229 Mutex::Autolock autoLock(mTimeLock); 230 mAnchorTimeMediaUs = mediaUs; 231 mAnchorTimeRealUs = realUs; 232 mAnchorNumFramesWritten = numFramesWritten; 233 if (resume) { 234 mPauseStartedTimeRealUs = -1; 235 } 236} 237 238void NuPlayer::Renderer::setVideoLateByUs(int64_t lateUs) { 239 Mutex::Autolock autoLock(mTimeLock); 240 mVideoLateByUs = lateUs; 241} 242 243int64_t NuPlayer::Renderer::getVideoLateByUs() { 244 Mutex::Autolock autoLock(mTimeLock); 245 return mVideoLateByUs; 246} 247 248void NuPlayer::Renderer::setPauseStartedTimeRealUs(int64_t realUs) { 249 Mutex::Autolock autoLock(mTimeLock); 250 mPauseStartedTimeRealUs = realUs; 251} 252 253status_t NuPlayer::Renderer::openAudioSink( 254 const sp<AMessage> &format, 255 bool offloadOnly, 256 bool hasVideo, 257 uint32_t flags, 258 bool *isOffloaded) { 259 sp<AMessage> msg = new AMessage(kWhatOpenAudioSink, id()); 260 msg->setMessage("format", format); 261 msg->setInt32("offload-only", offloadOnly); 262 msg->setInt32("has-video", hasVideo); 263 msg->setInt32("flags", flags); 264 265 sp<AMessage> response; 266 msg->postAndAwaitResponse(&response); 267 268 int32_t err; 269 if (!response->findInt32("err", &err)) { 270 err = INVALID_OPERATION; 271 } else if (err == OK && isOffloaded != NULL) { 272 int32_t offload; 273 CHECK(response->findInt32("offload", &offload)); 274 *isOffloaded = (offload != 0); 275 } 276 return err; 277} 278 279void NuPlayer::Renderer::closeAudioSink() { 280 sp<AMessage> msg = new AMessage(kWhatCloseAudioSink, id()); 281 282 sp<AMessage> response; 283 msg->postAndAwaitResponse(&response); 284} 285 286void NuPlayer::Renderer::onMessageReceived(const sp<AMessage> &msg) { 287 switch (msg->what()) { 288 case kWhatOpenAudioSink: 289 { 290 sp<AMessage> format; 291 CHECK(msg->findMessage("format", &format)); 292 293 int32_t offloadOnly; 294 CHECK(msg->findInt32("offload-only", &offloadOnly)); 295 296 int32_t hasVideo; 297 CHECK(msg->findInt32("has-video", &hasVideo)); 298 299 uint32_t flags; 300 CHECK(msg->findInt32("flags", (int32_t *)&flags)); 301 302 status_t err = onOpenAudioSink(format, offloadOnly, hasVideo, flags); 303 304 sp<AMessage> response = new AMessage; 305 response->setInt32("err", err); 306 response->setInt32("offload", offloadingAudio()); 307 308 uint32_t replyID; 309 CHECK(msg->senderAwaitsResponse(&replyID)); 310 response->postReply(replyID); 311 312 break; 313 } 314 315 case kWhatCloseAudioSink: 316 { 317 uint32_t replyID; 318 CHECK(msg->senderAwaitsResponse(&replyID)); 319 320 onCloseAudioSink(); 321 322 sp<AMessage> response = new AMessage; 323 response->postReply(replyID); 324 break; 325 } 326 327 case kWhatStopAudioSink: 328 { 329 mAudioSink->stop(); 330 break; 331 } 332 333 case kWhatDrainAudioQueue: 334 { 335 int32_t generation; 336 CHECK(msg->findInt32("generation", &generation)); 337 if (generation != mAudioQueueGeneration) { 338 break; 339 } 340 341 mDrainAudioQueuePending = false; 342 343 if (onDrainAudioQueue()) { 344 uint32_t numFramesPlayed; 345 CHECK_EQ(mAudioSink->getPosition(&numFramesPlayed), 346 (status_t)OK); 347 348 uint32_t numFramesPendingPlayout = 349 mNumFramesWritten - numFramesPlayed; 350 351 // This is how long the audio sink will have data to 352 // play back. 353 int64_t delayUs = 354 mAudioSink->msecsPerFrame() 355 * numFramesPendingPlayout * 1000ll; 356 357 // Let's give it more data after about half that time 358 // has elapsed. 359 // kWhatDrainAudioQueue is used for non-offloading mode, 360 // and mLock is used only for offloading mode. Therefore, 361 // no need to acquire mLock here. 362 postDrainAudioQueue_l(delayUs / 2); 363 } 364 break; 365 } 366 367 case kWhatDrainVideoQueue: 368 { 369 int32_t generation; 370 CHECK(msg->findInt32("generation", &generation)); 371 if (generation != mVideoQueueGeneration) { 372 break; 373 } 374 375 mDrainVideoQueuePending = false; 376 377 onDrainVideoQueue(); 378 379 postDrainVideoQueue(); 380 break; 381 } 382 383 case kWhatPostDrainVideoQueue: 384 { 385 int32_t generation; 386 CHECK(msg->findInt32("generation", &generation)); 387 if (generation != mVideoQueueGeneration) { 388 break; 389 } 390 391 mDrainVideoQueuePending = false; 392 postDrainVideoQueue(); 393 break; 394 } 395 396 case kWhatQueueBuffer: 397 { 398 onQueueBuffer(msg); 399 break; 400 } 401 402 case kWhatQueueEOS: 403 { 404 onQueueEOS(msg); 405 break; 406 } 407 408 case kWhatFlush: 409 { 410 onFlush(msg); 411 break; 412 } 413 414 case kWhatAudioSinkChanged: 415 { 416 onAudioSinkChanged(); 417 break; 418 } 419 420 case kWhatDisableOffloadAudio: 421 { 422 onDisableOffloadAudio(); 423 break; 424 } 425 426 case kWhatEnableOffloadAudio: 427 { 428 onEnableOffloadAudio(); 429 break; 430 } 431 432 case kWhatPause: 433 { 434 onPause(); 435 break; 436 } 437 438 case kWhatResume: 439 { 440 onResume(); 441 break; 442 } 443 444 case kWhatSetVideoFrameRate: 445 { 446 float fps; 447 CHECK(msg->findFloat("frame-rate", &fps)); 448 onSetVideoFrameRate(fps); 449 break; 450 } 451 452 case kWhatAudioOffloadTearDown: 453 { 454 onAudioOffloadTearDown(kDueToError); 455 break; 456 } 457 458 case kWhatAudioOffloadPauseTimeout: 459 { 460 int32_t generation; 461 CHECK(msg->findInt32("generation", &generation)); 462 if (generation != mAudioOffloadPauseTimeoutGeneration) { 463 break; 464 } 465 ALOGV("Audio Offload tear down due to pause timeout."); 466 onAudioOffloadTearDown(kDueToTimeout); 467 break; 468 } 469 470 default: 471 TRESPASS(); 472 break; 473 } 474} 475 476void NuPlayer::Renderer::postDrainAudioQueue_l(int64_t delayUs) { 477 if (mDrainAudioQueuePending || mSyncQueues || mPaused 478 || offloadingAudio()) { 479 return; 480 } 481 482 if (mAudioQueue.empty()) { 483 return; 484 } 485 486 mDrainAudioQueuePending = true; 487 sp<AMessage> msg = new AMessage(kWhatDrainAudioQueue, id()); 488 msg->setInt32("generation", mAudioQueueGeneration); 489 msg->post(delayUs); 490} 491 492void NuPlayer::Renderer::prepareForMediaRenderingStart() { 493 mAudioRenderingStartGeneration = mAudioQueueGeneration; 494 mVideoRenderingStartGeneration = mVideoQueueGeneration; 495} 496 497void NuPlayer::Renderer::notifyIfMediaRenderingStarted() { 498 if (mVideoRenderingStartGeneration == mVideoQueueGeneration && 499 mAudioRenderingStartGeneration == mAudioQueueGeneration) { 500 mVideoRenderingStartGeneration = -1; 501 mAudioRenderingStartGeneration = -1; 502 503 sp<AMessage> notify = mNotify->dup(); 504 notify->setInt32("what", kWhatMediaRenderingStart); 505 notify->post(); 506 } 507} 508 509// static 510size_t NuPlayer::Renderer::AudioSinkCallback( 511 MediaPlayerBase::AudioSink * /* audioSink */, 512 void *buffer, 513 size_t size, 514 void *cookie, 515 MediaPlayerBase::AudioSink::cb_event_t event) { 516 NuPlayer::Renderer *me = (NuPlayer::Renderer *)cookie; 517 518 switch (event) { 519 case MediaPlayerBase::AudioSink::CB_EVENT_FILL_BUFFER: 520 { 521 return me->fillAudioBuffer(buffer, size); 522 break; 523 } 524 525 case MediaPlayerBase::AudioSink::CB_EVENT_STREAM_END: 526 { 527 me->notifyEOS(true /* audio */, ERROR_END_OF_STREAM); 528 break; 529 } 530 531 case MediaPlayerBase::AudioSink::CB_EVENT_TEAR_DOWN: 532 { 533 me->notifyAudioOffloadTearDown(); 534 break; 535 } 536 } 537 538 return 0; 539} 540 541size_t NuPlayer::Renderer::fillAudioBuffer(void *buffer, size_t size) { 542 Mutex::Autolock autoLock(mLock); 543 544 if (!offloadingAudio() || mPaused) { 545 return 0; 546 } 547 548 bool hasEOS = false; 549 550 size_t sizeCopied = 0; 551 bool firstEntry = true; 552 while (sizeCopied < size && !mAudioQueue.empty()) { 553 QueueEntry *entry = &*mAudioQueue.begin(); 554 555 if (entry->mBuffer == NULL) { // EOS 556 hasEOS = true; 557 mAudioQueue.erase(mAudioQueue.begin()); 558 entry = NULL; 559 break; 560 } 561 562 if (firstEntry && entry->mOffset == 0) { 563 firstEntry = false; 564 int64_t mediaTimeUs; 565 CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs)); 566 ALOGV("rendering audio at media time %.2f secs", mediaTimeUs / 1E6); 567 setAudioFirstAnchorTimeIfNeeded(mediaTimeUs); 568 } 569 570 size_t copy = entry->mBuffer->size() - entry->mOffset; 571 size_t sizeRemaining = size - sizeCopied; 572 if (copy > sizeRemaining) { 573 copy = sizeRemaining; 574 } 575 576 memcpy((char *)buffer + sizeCopied, 577 entry->mBuffer->data() + entry->mOffset, 578 copy); 579 580 entry->mOffset += copy; 581 if (entry->mOffset == entry->mBuffer->size()) { 582 entry->mNotifyConsumed->post(); 583 mAudioQueue.erase(mAudioQueue.begin()); 584 entry = NULL; 585 } 586 sizeCopied += copy; 587 notifyIfMediaRenderingStarted(); 588 } 589 590 if (mAudioFirstAnchorTimeMediaUs >= 0) { 591 int64_t nowUs = ALooper::GetNowUs(); 592 setAnchorTime(mAudioFirstAnchorTimeMediaUs, nowUs - getPlayedOutAudioDurationUs(nowUs)); 593 } 594 595 // we don't know how much data we are queueing for offloaded tracks 596 mAnchorMaxMediaUs = -1; 597 598 if (hasEOS) { 599 (new AMessage(kWhatStopAudioSink, id()))->post(); 600 } 601 602 return sizeCopied; 603} 604 605bool NuPlayer::Renderer::onDrainAudioQueue() { 606 uint32_t numFramesPlayed; 607 if (mAudioSink->getPosition(&numFramesPlayed) != OK) { 608 return false; 609 } 610 611 ssize_t numFramesAvailableToWrite = 612 mAudioSink->frameCount() - (mNumFramesWritten - numFramesPlayed); 613 614#if 0 615 if (numFramesAvailableToWrite == mAudioSink->frameCount()) { 616 ALOGI("audio sink underrun"); 617 } else { 618 ALOGV("audio queue has %d frames left to play", 619 mAudioSink->frameCount() - numFramesAvailableToWrite); 620 } 621#endif 622 623 size_t numBytesAvailableToWrite = 624 numFramesAvailableToWrite * mAudioSink->frameSize(); 625 626 while (numBytesAvailableToWrite > 0 && !mAudioQueue.empty()) { 627 QueueEntry *entry = &*mAudioQueue.begin(); 628 629 mLastAudioBufferDrained = entry->mBufferOrdinal; 630 631 if (entry->mBuffer == NULL) { 632 // EOS 633 int64_t postEOSDelayUs = 0; 634 if (mAudioSink->needsTrailingPadding()) { 635 postEOSDelayUs = getPendingAudioPlayoutDurationUs(ALooper::GetNowUs()); 636 } 637 notifyEOS(true /* audio */, entry->mFinalResult, postEOSDelayUs); 638 639 mAudioQueue.erase(mAudioQueue.begin()); 640 entry = NULL; 641 // Need to stop the track here, because that will play out the last 642 // little bit at the end of the file. Otherwise short files won't play. 643 mAudioSink->stop(); 644 mNumFramesWritten = 0; 645 return false; 646 } 647 648 if (entry->mOffset == 0) { 649 int64_t mediaTimeUs; 650 CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs)); 651 ALOGV("rendering audio at media time %.2f secs", mediaTimeUs / 1E6); 652 onNewAudioMediaTime(mediaTimeUs); 653 } 654 655 size_t copy = entry->mBuffer->size() - entry->mOffset; 656 if (copy > numBytesAvailableToWrite) { 657 copy = numBytesAvailableToWrite; 658 } 659 660 ssize_t written = mAudioSink->write(entry->mBuffer->data() + entry->mOffset, copy); 661 if (written < 0) { 662 // An error in AudioSink write. Perhaps the AudioSink was not properly opened. 663 ALOGE("AudioSink write error(%zd) when writing %zu bytes", written, copy); 664 break; 665 } 666 667 entry->mOffset += written; 668 if (entry->mOffset == entry->mBuffer->size()) { 669 entry->mNotifyConsumed->post(); 670 mAudioQueue.erase(mAudioQueue.begin()); 671 672 entry = NULL; 673 } 674 675 numBytesAvailableToWrite -= written; 676 size_t copiedFrames = written / mAudioSink->frameSize(); 677 mNumFramesWritten += copiedFrames; 678 679 notifyIfMediaRenderingStarted(); 680 681 if (written != (ssize_t)copy) { 682 // A short count was received from AudioSink::write() 683 // 684 // AudioSink write should block until exactly the number of bytes are delivered. 685 // But it may return with a short count (without an error) when: 686 // 687 // 1) Size to be copied is not a multiple of the frame size. We consider this fatal. 688 // 2) AudioSink is an AudioCache for data retrieval, and the AudioCache is exceeded. 689 690 // (Case 1) 691 // Must be a multiple of the frame size. If it is not a multiple of a frame size, it 692 // needs to fail, as we should not carry over fractional frames between calls. 693 CHECK_EQ(copy % mAudioSink->frameSize(), 0); 694 695 // (Case 2) 696 // Return early to the caller. 697 // Beware of calling immediately again as this may busy-loop if you are not careful. 698 ALOGW("AudioSink write short frame count %zd < %zu", written, copy); 699 break; 700 } 701 } 702 mAnchorMaxMediaUs = 703 mAnchorTimeMediaUs + 704 (int64_t)(max((long long)mNumFramesWritten - mAnchorNumFramesWritten, 0LL) 705 * 1000LL * mAudioSink->msecsPerFrame()); 706 707 return !mAudioQueue.empty(); 708} 709 710int64_t NuPlayer::Renderer::getPendingAudioPlayoutDurationUs(int64_t nowUs) { 711 int64_t writtenAudioDurationUs = 712 mNumFramesWritten * 1000LL * mAudioSink->msecsPerFrame(); 713 return writtenAudioDurationUs - getPlayedOutAudioDurationUs(nowUs); 714} 715 716int64_t NuPlayer::Renderer::getRealTimeUs(int64_t mediaTimeUs, int64_t nowUs) { 717 int64_t currentPositionUs; 718 if (getCurrentPosition(¤tPositionUs, nowUs, true /* allowPastQueuedVideo */) != OK) { 719 // If failed to get current position, e.g. due to audio clock is not ready, then just 720 // play out video immediately without delay. 721 return nowUs; 722 } 723 return (mediaTimeUs - currentPositionUs) + nowUs; 724} 725 726void NuPlayer::Renderer::onNewAudioMediaTime(int64_t mediaTimeUs) { 727 // TRICKY: vorbis decoder generates multiple frames with the same 728 // timestamp, so only update on the first frame with a given timestamp 729 if (mediaTimeUs == mAnchorTimeMediaUs) { 730 return; 731 } 732 setAudioFirstAnchorTimeIfNeeded(mediaTimeUs); 733 int64_t nowUs = ALooper::GetNowUs(); 734 setAnchorTime( 735 mediaTimeUs, nowUs + getPendingAudioPlayoutDurationUs(nowUs), mNumFramesWritten); 736} 737 738void NuPlayer::Renderer::postDrainVideoQueue() { 739 if (mDrainVideoQueuePending 740 || mSyncQueues 741 || (mPaused && mVideoSampleReceived)) { 742 return; 743 } 744 745 if (mVideoQueue.empty()) { 746 return; 747 } 748 749 QueueEntry &entry = *mVideoQueue.begin(); 750 751 sp<AMessage> msg = new AMessage(kWhatDrainVideoQueue, id()); 752 msg->setInt32("generation", mVideoQueueGeneration); 753 754 if (entry.mBuffer == NULL) { 755 // EOS doesn't carry a timestamp. 756 msg->post(); 757 mDrainVideoQueuePending = true; 758 return; 759 } 760 761 int64_t delayUs; 762 int64_t nowUs = ALooper::GetNowUs(); 763 int64_t realTimeUs; 764 if (mFlags & FLAG_REAL_TIME) { 765 int64_t mediaTimeUs; 766 CHECK(entry.mBuffer->meta()->findInt64("timeUs", &mediaTimeUs)); 767 realTimeUs = mediaTimeUs; 768 } else { 769 int64_t mediaTimeUs; 770 CHECK(entry.mBuffer->meta()->findInt64("timeUs", &mediaTimeUs)); 771 772 if (mAnchorTimeMediaUs < 0) { 773 setAnchorTime(mediaTimeUs, nowUs); 774 realTimeUs = nowUs; 775 } else { 776 realTimeUs = getRealTimeUs(mediaTimeUs, nowUs); 777 } 778 if (!mHasAudio) { 779 mAnchorMaxMediaUs = mediaTimeUs + 100000; // smooth out videos >= 10fps 780 } 781 782 // Heuristics to handle situation when media time changed without a 783 // discontinuity. If we have not drained an audio buffer that was 784 // received after this buffer, repost in 10 msec. Otherwise repost 785 // in 500 msec. 786 delayUs = realTimeUs - nowUs; 787 if (delayUs > 500000) { 788 int64_t postDelayUs = 500000; 789 if (mHasAudio && (mLastAudioBufferDrained - entry.mBufferOrdinal) <= 0) { 790 postDelayUs = 10000; 791 } 792 msg->setWhat(kWhatPostDrainVideoQueue); 793 msg->post(postDelayUs); 794 mVideoScheduler->restart(); 795 ALOGI("possible video time jump of %dms, retrying in %dms", 796 (int)(delayUs / 1000), (int)(postDelayUs / 1000)); 797 mDrainVideoQueuePending = true; 798 return; 799 } 800 } 801 802 realTimeUs = mVideoScheduler->schedule(realTimeUs * 1000) / 1000; 803 int64_t twoVsyncsUs = 2 * (mVideoScheduler->getVsyncPeriod() / 1000); 804 805 delayUs = realTimeUs - nowUs; 806 807 ALOGW_IF(delayUs > 500000, "unusually high delayUs: %" PRId64, delayUs); 808 // post 2 display refreshes before rendering is due 809 msg->post(delayUs > twoVsyncsUs ? delayUs - twoVsyncsUs : 0); 810 811 mDrainVideoQueuePending = true; 812} 813 814void NuPlayer::Renderer::onDrainVideoQueue() { 815 if (mVideoQueue.empty()) { 816 return; 817 } 818 819 QueueEntry *entry = &*mVideoQueue.begin(); 820 821 if (entry->mBuffer == NULL) { 822 // EOS 823 824 notifyEOS(false /* audio */, entry->mFinalResult); 825 826 mVideoQueue.erase(mVideoQueue.begin()); 827 entry = NULL; 828 829 setVideoLateByUs(0); 830 return; 831 } 832 833 int64_t nowUs = -1; 834 int64_t realTimeUs; 835 if (mFlags & FLAG_REAL_TIME) { 836 CHECK(entry->mBuffer->meta()->findInt64("timeUs", &realTimeUs)); 837 } else { 838 int64_t mediaTimeUs; 839 CHECK(entry->mBuffer->meta()->findInt64("timeUs", &mediaTimeUs)); 840 841 nowUs = ALooper::GetNowUs(); 842 realTimeUs = getRealTimeUs(mediaTimeUs, nowUs); 843 } 844 845 bool tooLate = false; 846 847 if (!mPaused) { 848 if (nowUs == -1) { 849 nowUs = ALooper::GetNowUs(); 850 } 851 setVideoLateByUs(nowUs - realTimeUs); 852 tooLate = (mVideoLateByUs > 40000); 853 854 if (tooLate) { 855 ALOGV("video late by %lld us (%.2f secs)", 856 mVideoLateByUs, mVideoLateByUs / 1E6); 857 } else { 858 ALOGV("rendering video at media time %.2f secs", 859 (mFlags & FLAG_REAL_TIME ? realTimeUs : 860 (realTimeUs + mAnchorTimeMediaUs - mAnchorTimeRealUs)) / 1E6); 861 } 862 } else { 863 setVideoLateByUs(0); 864 if (!mVideoSampleReceived && !mHasAudio) { 865 // This will ensure that the first frame after a flush won't be used as anchor 866 // when renderer is in paused state, because resume can happen any time after seek. 867 setAnchorTime(-1, -1); 868 } 869 } 870 871 entry->mNotifyConsumed->setInt64("timestampNs", realTimeUs * 1000ll); 872 entry->mNotifyConsumed->setInt32("render", !tooLate); 873 entry->mNotifyConsumed->post(); 874 mVideoQueue.erase(mVideoQueue.begin()); 875 entry = NULL; 876 877 mVideoSampleReceived = true; 878 879 if (!mPaused) { 880 if (!mVideoRenderingStarted) { 881 mVideoRenderingStarted = true; 882 notifyVideoRenderingStart(); 883 } 884 notifyIfMediaRenderingStarted(); 885 } 886} 887 888void NuPlayer::Renderer::notifyVideoRenderingStart() { 889 sp<AMessage> notify = mNotify->dup(); 890 notify->setInt32("what", kWhatVideoRenderingStart); 891 notify->post(); 892} 893 894void NuPlayer::Renderer::notifyEOS(bool audio, status_t finalResult, int64_t delayUs) { 895 sp<AMessage> notify = mNotify->dup(); 896 notify->setInt32("what", kWhatEOS); 897 notify->setInt32("audio", static_cast<int32_t>(audio)); 898 notify->setInt32("finalResult", finalResult); 899 notify->post(delayUs); 900} 901 902void NuPlayer::Renderer::notifyAudioOffloadTearDown() { 903 (new AMessage(kWhatAudioOffloadTearDown, id()))->post(); 904} 905 906void NuPlayer::Renderer::onQueueBuffer(const sp<AMessage> &msg) { 907 int32_t audio; 908 CHECK(msg->findInt32("audio", &audio)); 909 910 setHasMedia(audio); 911 912 if (mHasVideo) { 913 if (mVideoScheduler == NULL) { 914 mVideoScheduler = new VideoFrameScheduler(); 915 mVideoScheduler->init(); 916 } 917 } 918 919 if (dropBufferWhileFlushing(audio, msg)) { 920 return; 921 } 922 923 sp<ABuffer> buffer; 924 CHECK(msg->findBuffer("buffer", &buffer)); 925 926 sp<AMessage> notifyConsumed; 927 CHECK(msg->findMessage("notifyConsumed", ¬ifyConsumed)); 928 929 QueueEntry entry; 930 entry.mBuffer = buffer; 931 entry.mNotifyConsumed = notifyConsumed; 932 entry.mOffset = 0; 933 entry.mFinalResult = OK; 934 entry.mBufferOrdinal = ++mTotalBuffersQueued; 935 936 if (audio) { 937 Mutex::Autolock autoLock(mLock); 938 mAudioQueue.push_back(entry); 939 postDrainAudioQueue_l(); 940 } else { 941 mVideoQueue.push_back(entry); 942 postDrainVideoQueue(); 943 } 944 945 Mutex::Autolock autoLock(mLock); 946 if (!mSyncQueues || mAudioQueue.empty() || mVideoQueue.empty()) { 947 return; 948 } 949 950 sp<ABuffer> firstAudioBuffer = (*mAudioQueue.begin()).mBuffer; 951 sp<ABuffer> firstVideoBuffer = (*mVideoQueue.begin()).mBuffer; 952 953 if (firstAudioBuffer == NULL || firstVideoBuffer == NULL) { 954 // EOS signalled on either queue. 955 syncQueuesDone_l(); 956 return; 957 } 958 959 int64_t firstAudioTimeUs; 960 int64_t firstVideoTimeUs; 961 CHECK(firstAudioBuffer->meta() 962 ->findInt64("timeUs", &firstAudioTimeUs)); 963 CHECK(firstVideoBuffer->meta() 964 ->findInt64("timeUs", &firstVideoTimeUs)); 965 966 int64_t diff = firstVideoTimeUs - firstAudioTimeUs; 967 968 ALOGV("queueDiff = %.2f secs", diff / 1E6); 969 970 if (diff > 100000ll) { 971 // Audio data starts More than 0.1 secs before video. 972 // Drop some audio. 973 974 (*mAudioQueue.begin()).mNotifyConsumed->post(); 975 mAudioQueue.erase(mAudioQueue.begin()); 976 return; 977 } 978 979 syncQueuesDone_l(); 980} 981 982void NuPlayer::Renderer::syncQueuesDone_l() { 983 if (!mSyncQueues) { 984 return; 985 } 986 987 mSyncQueues = false; 988 989 if (!mAudioQueue.empty()) { 990 postDrainAudioQueue_l(); 991 } 992 993 if (!mVideoQueue.empty()) { 994 postDrainVideoQueue(); 995 } 996} 997 998void NuPlayer::Renderer::onQueueEOS(const sp<AMessage> &msg) { 999 int32_t audio; 1000 CHECK(msg->findInt32("audio", &audio)); 1001 1002 if (dropBufferWhileFlushing(audio, msg)) { 1003 return; 1004 } 1005 1006 int32_t finalResult; 1007 CHECK(msg->findInt32("finalResult", &finalResult)); 1008 1009 QueueEntry entry; 1010 entry.mOffset = 0; 1011 entry.mFinalResult = finalResult; 1012 1013 if (audio) { 1014 Mutex::Autolock autoLock(mLock); 1015 if (mAudioQueue.empty() && mSyncQueues) { 1016 syncQueuesDone_l(); 1017 } 1018 mAudioQueue.push_back(entry); 1019 postDrainAudioQueue_l(); 1020 } else { 1021 if (mVideoQueue.empty() && mSyncQueues) { 1022 Mutex::Autolock autoLock(mLock); 1023 syncQueuesDone_l(); 1024 } 1025 mVideoQueue.push_back(entry); 1026 postDrainVideoQueue(); 1027 } 1028} 1029 1030void NuPlayer::Renderer::onFlush(const sp<AMessage> &msg) { 1031 int32_t audio, notifyComplete; 1032 CHECK(msg->findInt32("audio", &audio)); 1033 1034 { 1035 Mutex::Autolock autoLock(mFlushLock); 1036 if (audio) { 1037 mFlushingAudio = false; 1038 notifyComplete = mNotifyCompleteAudio; 1039 mNotifyCompleteAudio = false; 1040 } else { 1041 mFlushingVideo = false; 1042 notifyComplete = mNotifyCompleteVideo; 1043 mNotifyCompleteVideo = false; 1044 } 1045 } 1046 1047 // If we're currently syncing the queues, i.e. dropping audio while 1048 // aligning the first audio/video buffer times and only one of the 1049 // two queues has data, we may starve that queue by not requesting 1050 // more buffers from the decoder. If the other source then encounters 1051 // a discontinuity that leads to flushing, we'll never find the 1052 // corresponding discontinuity on the other queue. 1053 // Therefore we'll stop syncing the queues if at least one of them 1054 // is flushed. 1055 { 1056 Mutex::Autolock autoLock(mLock); 1057 syncQueuesDone_l(); 1058 setPauseStartedTimeRealUs(-1); 1059 setAnchorTime(-1, -1); 1060 } 1061 1062 ALOGV("flushing %s", audio ? "audio" : "video"); 1063 if (audio) { 1064 { 1065 Mutex::Autolock autoLock(mLock); 1066 flushQueue(&mAudioQueue); 1067 1068 ++mAudioQueueGeneration; 1069 prepareForMediaRenderingStart(); 1070 1071 if (offloadingAudio()) { 1072 setAudioFirstAnchorTime(-1); 1073 } 1074 } 1075 1076 mDrainAudioQueuePending = false; 1077 1078 if (offloadingAudio()) { 1079 mAudioSink->pause(); 1080 mAudioSink->flush(); 1081 mAudioSink->start(); 1082 } 1083 } else { 1084 flushQueue(&mVideoQueue); 1085 1086 mDrainVideoQueuePending = false; 1087 ++mVideoQueueGeneration; 1088 1089 if (mVideoScheduler != NULL) { 1090 mVideoScheduler->restart(); 1091 } 1092 1093 prepareForMediaRenderingStart(); 1094 } 1095 1096 mVideoSampleReceived = false; 1097 1098 if (notifyComplete) { 1099 notifyFlushComplete(audio); 1100 } 1101} 1102 1103void NuPlayer::Renderer::flushQueue(List<QueueEntry> *queue) { 1104 while (!queue->empty()) { 1105 QueueEntry *entry = &*queue->begin(); 1106 1107 if (entry->mBuffer != NULL) { 1108 entry->mNotifyConsumed->post(); 1109 } 1110 1111 queue->erase(queue->begin()); 1112 entry = NULL; 1113 } 1114} 1115 1116void NuPlayer::Renderer::notifyFlushComplete(bool audio) { 1117 sp<AMessage> notify = mNotify->dup(); 1118 notify->setInt32("what", kWhatFlushComplete); 1119 notify->setInt32("audio", static_cast<int32_t>(audio)); 1120 notify->post(); 1121} 1122 1123bool NuPlayer::Renderer::dropBufferWhileFlushing( 1124 bool audio, const sp<AMessage> &msg) { 1125 bool flushing = false; 1126 1127 { 1128 Mutex::Autolock autoLock(mFlushLock); 1129 if (audio) { 1130 flushing = mFlushingAudio; 1131 } else { 1132 flushing = mFlushingVideo; 1133 } 1134 } 1135 1136 if (!flushing) { 1137 return false; 1138 } 1139 1140 sp<AMessage> notifyConsumed; 1141 if (msg->findMessage("notifyConsumed", ¬ifyConsumed)) { 1142 notifyConsumed->post(); 1143 } 1144 1145 return true; 1146} 1147 1148void NuPlayer::Renderer::onAudioSinkChanged() { 1149 if (offloadingAudio()) { 1150 return; 1151 } 1152 CHECK(!mDrainAudioQueuePending); 1153 mNumFramesWritten = 0; 1154 mAnchorNumFramesWritten = -1; 1155 uint32_t written; 1156 if (mAudioSink->getFramesWritten(&written) == OK) { 1157 mNumFramesWritten = written; 1158 } 1159} 1160 1161void NuPlayer::Renderer::onDisableOffloadAudio() { 1162 Mutex::Autolock autoLock(mLock); 1163 mFlags &= ~FLAG_OFFLOAD_AUDIO; 1164 ++mAudioQueueGeneration; 1165} 1166 1167void NuPlayer::Renderer::onEnableOffloadAudio() { 1168 Mutex::Autolock autoLock(mLock); 1169 mFlags |= FLAG_OFFLOAD_AUDIO; 1170 ++mAudioQueueGeneration; 1171} 1172 1173void NuPlayer::Renderer::onPause() { 1174 if (mPaused) { 1175 ALOGW("Renderer::onPause() called while already paused!"); 1176 return; 1177 } 1178 { 1179 Mutex::Autolock autoLock(mLock); 1180 ++mAudioQueueGeneration; 1181 ++mVideoQueueGeneration; 1182 prepareForMediaRenderingStart(); 1183 mPaused = true; 1184 setPauseStartedTimeRealUs(ALooper::GetNowUs()); 1185 } 1186 1187 mDrainAudioQueuePending = false; 1188 mDrainVideoQueuePending = false; 1189 1190 if (mHasAudio) { 1191 mAudioSink->pause(); 1192 startAudioOffloadPauseTimeout(); 1193 } 1194 1195 ALOGV("now paused audio queue has %d entries, video has %d entries", 1196 mAudioQueue.size(), mVideoQueue.size()); 1197} 1198 1199void NuPlayer::Renderer::onResume() { 1200 if (!mPaused) { 1201 return; 1202 } 1203 1204 if (mHasAudio) { 1205 cancelAudioOffloadPauseTimeout(); 1206 mAudioSink->start(); 1207 } 1208 1209 Mutex::Autolock autoLock(mLock); 1210 mPaused = false; 1211 if (mPauseStartedTimeRealUs != -1) { 1212 int64_t newAnchorRealUs = 1213 mAnchorTimeRealUs + ALooper::GetNowUs() - mPauseStartedTimeRealUs; 1214 setAnchorTime( 1215 mAnchorTimeMediaUs, newAnchorRealUs, mAnchorNumFramesWritten, true /* resume */); 1216 } 1217 1218 if (!mAudioQueue.empty()) { 1219 postDrainAudioQueue_l(); 1220 } 1221 1222 if (!mVideoQueue.empty()) { 1223 postDrainVideoQueue(); 1224 } 1225} 1226 1227void NuPlayer::Renderer::onSetVideoFrameRate(float fps) { 1228 if (mVideoScheduler == NULL) { 1229 mVideoScheduler = new VideoFrameScheduler(); 1230 } 1231 mVideoScheduler->init(fps); 1232} 1233 1234// TODO: Remove unnecessary calls to getPlayedOutAudioDurationUs() 1235// as it acquires locks and may query the audio driver. 1236// 1237// Some calls could conceivably retrieve extrapolated data instead of 1238// accessing getTimestamp() or getPosition() every time a data buffer with 1239// a media time is received. 1240// 1241int64_t NuPlayer::Renderer::getPlayedOutAudioDurationUs(int64_t nowUs) { 1242 uint32_t numFramesPlayed; 1243 int64_t numFramesPlayedAt; 1244 AudioTimestamp ts; 1245 static const int64_t kStaleTimestamp100ms = 100000; 1246 1247 status_t res = mAudioSink->getTimestamp(ts); 1248 if (res == OK) { // case 1: mixing audio tracks and offloaded tracks. 1249 numFramesPlayed = ts.mPosition; 1250 numFramesPlayedAt = 1251 ts.mTime.tv_sec * 1000000LL + ts.mTime.tv_nsec / 1000; 1252 const int64_t timestampAge = nowUs - numFramesPlayedAt; 1253 if (timestampAge > kStaleTimestamp100ms) { 1254 // This is an audio FIXME. 1255 // getTimestamp returns a timestamp which may come from audio mixing threads. 1256 // After pausing, the MixerThread may go idle, thus the mTime estimate may 1257 // become stale. Assuming that the MixerThread runs 20ms, with FastMixer at 5ms, 1258 // the max latency should be about 25ms with an average around 12ms (to be verified). 1259 // For safety we use 100ms. 1260 ALOGV("getTimestamp: returned stale timestamp nowUs(%lld) numFramesPlayedAt(%lld)", 1261 (long long)nowUs, (long long)numFramesPlayedAt); 1262 numFramesPlayedAt = nowUs - kStaleTimestamp100ms; 1263 } 1264 //ALOGD("getTimestamp: OK %d %lld", numFramesPlayed, (long long)numFramesPlayedAt); 1265 } else if (res == WOULD_BLOCK) { // case 2: transitory state on start of a new track 1266 numFramesPlayed = 0; 1267 numFramesPlayedAt = nowUs; 1268 //ALOGD("getTimestamp: WOULD_BLOCK %d %lld", 1269 // numFramesPlayed, (long long)numFramesPlayedAt); 1270 } else { // case 3: transitory at new track or audio fast tracks. 1271 res = mAudioSink->getPosition(&numFramesPlayed); 1272 CHECK_EQ(res, (status_t)OK); 1273 numFramesPlayedAt = nowUs; 1274 numFramesPlayedAt += 1000LL * mAudioSink->latency() / 2; /* XXX */ 1275 //ALOGD("getPosition: %d %lld", numFramesPlayed, numFramesPlayedAt); 1276 } 1277 1278 // TODO: remove the (int32_t) casting below as it may overflow at 12.4 hours. 1279 //CHECK_EQ(numFramesPlayed & (1 << 31), 0); // can't be negative until 12.4 hrs, test 1280 int64_t durationUs = (int64_t)((int32_t)numFramesPlayed * 1000LL * mAudioSink->msecsPerFrame()) 1281 + nowUs - numFramesPlayedAt; 1282 if (durationUs < 0) { 1283 // Occurs when numFramesPlayed position is very small and the following: 1284 // (1) In case 1, the time nowUs is computed before getTimestamp() is called and 1285 // numFramesPlayedAt is greater than nowUs by time more than numFramesPlayed. 1286 // (2) In case 3, using getPosition and adding mAudioSink->latency() to 1287 // numFramesPlayedAt, by a time amount greater than numFramesPlayed. 1288 // 1289 // Both of these are transitory conditions. 1290 ALOGV("getPlayedOutAudioDurationUs: negative duration %lld set to zero", (long long)durationUs); 1291 durationUs = 0; 1292 } 1293 ALOGV("getPlayedOutAudioDurationUs(%lld) nowUs(%lld) frames(%u) framesAt(%lld)", 1294 (long long)durationUs, (long long)nowUs, numFramesPlayed, (long long)numFramesPlayedAt); 1295 return durationUs; 1296} 1297 1298void NuPlayer::Renderer::onAudioOffloadTearDown(AudioOffloadTearDownReason reason) { 1299 if (mAudioOffloadTornDown) { 1300 return; 1301 } 1302 mAudioOffloadTornDown = true; 1303 1304 int64_t currentPositionUs; 1305 if (getCurrentPosition(¤tPositionUs) != OK) { 1306 currentPositionUs = 0; 1307 } 1308 1309 mAudioSink->stop(); 1310 mAudioSink->flush(); 1311 1312 sp<AMessage> notify = mNotify->dup(); 1313 notify->setInt32("what", kWhatAudioOffloadTearDown); 1314 notify->setInt64("positionUs", currentPositionUs); 1315 notify->setInt32("reason", reason); 1316 notify->post(); 1317} 1318 1319void NuPlayer::Renderer::startAudioOffloadPauseTimeout() { 1320 if (offloadingAudio()) { 1321 sp<AMessage> msg = new AMessage(kWhatAudioOffloadPauseTimeout, id()); 1322 msg->setInt32("generation", mAudioOffloadPauseTimeoutGeneration); 1323 msg->post(kOffloadPauseMaxUs); 1324 } 1325} 1326 1327void NuPlayer::Renderer::cancelAudioOffloadPauseTimeout() { 1328 if (offloadingAudio()) { 1329 ++mAudioOffloadPauseTimeoutGeneration; 1330 } 1331} 1332 1333status_t NuPlayer::Renderer::onOpenAudioSink( 1334 const sp<AMessage> &format, 1335 bool offloadOnly, 1336 bool hasVideo, 1337 uint32_t flags) { 1338 ALOGV("openAudioSink: offloadOnly(%d) offloadingAudio(%d)", 1339 offloadOnly, offloadingAudio()); 1340 bool audioSinkChanged = false; 1341 1342 int32_t numChannels; 1343 CHECK(format->findInt32("channel-count", &numChannels)); 1344 1345 int32_t channelMask; 1346 if (!format->findInt32("channel-mask", &channelMask)) { 1347 // signal to the AudioSink to derive the mask from count. 1348 channelMask = CHANNEL_MASK_USE_CHANNEL_ORDER; 1349 } 1350 1351 int32_t sampleRate; 1352 CHECK(format->findInt32("sample-rate", &sampleRate)); 1353 1354 if (offloadingAudio()) { 1355 audio_format_t audioFormat = AUDIO_FORMAT_PCM_16_BIT; 1356 AString mime; 1357 CHECK(format->findString("mime", &mime)); 1358 status_t err = mapMimeToAudioFormat(audioFormat, mime.c_str()); 1359 1360 if (err != OK) { 1361 ALOGE("Couldn't map mime \"%s\" to a valid " 1362 "audio_format", mime.c_str()); 1363 onDisableOffloadAudio(); 1364 } else { 1365 ALOGV("Mime \"%s\" mapped to audio_format 0x%x", 1366 mime.c_str(), audioFormat); 1367 1368 int avgBitRate = -1; 1369 format->findInt32("bit-rate", &avgBitRate); 1370 1371 int32_t aacProfile = -1; 1372 if (audioFormat == AUDIO_FORMAT_AAC 1373 && format->findInt32("aac-profile", &aacProfile)) { 1374 // Redefine AAC format as per aac profile 1375 mapAACProfileToAudioFormat( 1376 audioFormat, 1377 aacProfile); 1378 } 1379 1380 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER; 1381 offloadInfo.duration_us = -1; 1382 format->findInt64( 1383 "durationUs", &offloadInfo.duration_us); 1384 offloadInfo.sample_rate = sampleRate; 1385 offloadInfo.channel_mask = channelMask; 1386 offloadInfo.format = audioFormat; 1387 offloadInfo.stream_type = AUDIO_STREAM_MUSIC; 1388 offloadInfo.bit_rate = avgBitRate; 1389 offloadInfo.has_video = hasVideo; 1390 offloadInfo.is_streaming = true; 1391 1392 if (memcmp(&mCurrentOffloadInfo, &offloadInfo, sizeof(offloadInfo)) == 0) { 1393 ALOGV("openAudioSink: no change in offload mode"); 1394 // no change from previous configuration, everything ok. 1395 return OK; 1396 } 1397 ALOGV("openAudioSink: try to open AudioSink in offload mode"); 1398 uint32_t offloadFlags = flags; 1399 offloadFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD; 1400 offloadFlags &= ~AUDIO_OUTPUT_FLAG_DEEP_BUFFER; 1401 audioSinkChanged = true; 1402 mAudioSink->close(); 1403 err = mAudioSink->open( 1404 sampleRate, 1405 numChannels, 1406 (audio_channel_mask_t)channelMask, 1407 audioFormat, 1408 8 /* bufferCount */, 1409 &NuPlayer::Renderer::AudioSinkCallback, 1410 this, 1411 (audio_output_flags_t)offloadFlags, 1412 &offloadInfo); 1413 1414 if (err == OK) { 1415 // If the playback is offloaded to h/w, we pass 1416 // the HAL some metadata information. 1417 // We don't want to do this for PCM because it 1418 // will be going through the AudioFlinger mixer 1419 // before reaching the hardware. 1420 // TODO 1421 mCurrentOffloadInfo = offloadInfo; 1422 err = mAudioSink->start(); 1423 ALOGV_IF(err == OK, "openAudioSink: offload succeeded"); 1424 } 1425 if (err != OK) { 1426 // Clean up, fall back to non offload mode. 1427 mAudioSink->close(); 1428 onDisableOffloadAudio(); 1429 mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER; 1430 ALOGV("openAudioSink: offload failed"); 1431 } 1432 } 1433 } 1434 if (!offloadOnly && !offloadingAudio()) { 1435 ALOGV("openAudioSink: open AudioSink in NON-offload mode"); 1436 uint32_t pcmFlags = flags; 1437 pcmFlags &= ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD; 1438 audioSinkChanged = true; 1439 mAudioSink->close(); 1440 mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER; 1441 status_t err = mAudioSink->open( 1442 sampleRate, 1443 numChannels, 1444 (audio_channel_mask_t)channelMask, 1445 AUDIO_FORMAT_PCM_16_BIT, 1446 8 /* bufferCount */, 1447 NULL, 1448 NULL, 1449 (audio_output_flags_t)pcmFlags); 1450 if (err != OK) { 1451 ALOGW("openAudioSink: non offloaded open failed status: %d", err); 1452 return err; 1453 } 1454 mAudioSink->start(); 1455 } 1456 if (audioSinkChanged) { 1457 onAudioSinkChanged(); 1458 } 1459 if (offloadingAudio()) { 1460 mAudioOffloadTornDown = false; 1461 } 1462 return OK; 1463} 1464 1465void NuPlayer::Renderer::onCloseAudioSink() { 1466 mAudioSink->close(); 1467 mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER; 1468} 1469 1470} // namespace android 1471 1472