AwesomePlayer.cpp revision 6511c9755c3a3360ba869772600c7aae048a7ffc
1/* 2 * Copyright (C) 2009 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 DEBUG_HDCP 18 19//#define LOG_NDEBUG 0 20#define LOG_TAG "AwesomePlayer" 21#include <utils/Log.h> 22 23#include <dlfcn.h> 24 25#include "include/ARTSPController.h" 26#include "include/AwesomePlayer.h" 27#include "include/SoftwareRenderer.h" 28#include "include/NuCachedSource2.h" 29#include "include/ThrottledSource.h" 30#include "include/MPEG2TSExtractor.h" 31 32#include <binder/IPCThreadState.h> 33#include <binder/IServiceManager.h> 34#include <media/IMediaPlayerService.h> 35#include <media/stagefright/foundation/hexdump.h> 36#include <media/stagefright/foundation/ADebug.h> 37#include <media/stagefright/AudioPlayer.h> 38#include <media/stagefright/DataSource.h> 39#include <media/stagefright/FileSource.h> 40#include <media/stagefright/MediaBuffer.h> 41#include <media/stagefright/MediaDefs.h> 42#include <media/stagefright/MediaExtractor.h> 43#include <media/stagefright/MediaSource.h> 44#include <media/stagefright/MetaData.h> 45#include <media/stagefright/OMXCodec.h> 46 47#include <surfaceflinger/Surface.h> 48#include <gui/ISurfaceTexture.h> 49#include <gui/SurfaceTextureClient.h> 50#include <surfaceflinger/ISurfaceComposer.h> 51 52#include <media/stagefright/foundation/ALooper.h> 53#include <media/stagefright/foundation/AMessage.h> 54 55#include <cutils/properties.h> 56 57#define USE_SURFACE_ALLOC 1 58#define FRAME_DROP_FREQ 0 59 60namespace android { 61 62static int64_t kLowWaterMarkUs = 2000000ll; // 2secs 63static int64_t kHighWaterMarkUs = 10000000ll; // 10secs 64static int64_t kHighWaterMarkRTSPUs = 4000000ll; // 4secs 65static const size_t kLowWaterMarkBytes = 40000; 66static const size_t kHighWaterMarkBytes = 200000; 67 68struct AwesomeEvent : public TimedEventQueue::Event { 69 AwesomeEvent( 70 AwesomePlayer *player, 71 void (AwesomePlayer::*method)()) 72 : mPlayer(player), 73 mMethod(method) { 74 } 75 76protected: 77 virtual ~AwesomeEvent() {} 78 79 virtual void fire(TimedEventQueue *queue, int64_t /* now_us */) { 80 (mPlayer->*mMethod)(); 81 } 82 83private: 84 AwesomePlayer *mPlayer; 85 void (AwesomePlayer::*mMethod)(); 86 87 AwesomeEvent(const AwesomeEvent &); 88 AwesomeEvent &operator=(const AwesomeEvent &); 89}; 90 91struct AwesomeLocalRenderer : public AwesomeRenderer { 92 AwesomeLocalRenderer( 93 const sp<ANativeWindow> &nativeWindow, const sp<MetaData> &meta) 94 : mTarget(new SoftwareRenderer(nativeWindow, meta)) { 95 } 96 97 virtual void render(MediaBuffer *buffer) { 98 render((const uint8_t *)buffer->data() + buffer->range_offset(), 99 buffer->range_length()); 100 } 101 102 void render(const void *data, size_t size) { 103 mTarget->render(data, size, NULL); 104 } 105 106protected: 107 virtual ~AwesomeLocalRenderer() { 108 delete mTarget; 109 mTarget = NULL; 110 } 111 112private: 113 SoftwareRenderer *mTarget; 114 115 AwesomeLocalRenderer(const AwesomeLocalRenderer &); 116 AwesomeLocalRenderer &operator=(const AwesomeLocalRenderer &);; 117}; 118 119struct AwesomeNativeWindowRenderer : public AwesomeRenderer { 120 AwesomeNativeWindowRenderer( 121 const sp<ANativeWindow> &nativeWindow, 122 int32_t rotationDegrees) 123 : mNativeWindow(nativeWindow) { 124 applyRotation(rotationDegrees); 125 } 126 127 virtual void render(MediaBuffer *buffer) { 128 status_t err = mNativeWindow->queueBuffer( 129 mNativeWindow.get(), buffer->graphicBuffer().get()); 130 if (err != 0) { 131 LOGE("queueBuffer failed with error %s (%d)", strerror(-err), 132 -err); 133 return; 134 } 135 136 sp<MetaData> metaData = buffer->meta_data(); 137 metaData->setInt32(kKeyRendered, 1); 138 } 139 140protected: 141 virtual ~AwesomeNativeWindowRenderer() {} 142 143private: 144 sp<ANativeWindow> mNativeWindow; 145 146 void applyRotation(int32_t rotationDegrees) { 147 uint32_t transform; 148 switch (rotationDegrees) { 149 case 0: transform = 0; break; 150 case 90: transform = HAL_TRANSFORM_ROT_90; break; 151 case 180: transform = HAL_TRANSFORM_ROT_180; break; 152 case 270: transform = HAL_TRANSFORM_ROT_270; break; 153 default: transform = 0; break; 154 } 155 156 if (transform) { 157 CHECK_EQ(0, native_window_set_buffers_transform( 158 mNativeWindow.get(), transform)); 159 } 160 } 161 162 AwesomeNativeWindowRenderer(const AwesomeNativeWindowRenderer &); 163 AwesomeNativeWindowRenderer &operator=( 164 const AwesomeNativeWindowRenderer &); 165}; 166 167// To collect the decoder usage 168void addBatteryData(uint32_t params) { 169 sp<IBinder> binder = 170 defaultServiceManager()->getService(String16("media.player")); 171 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder); 172 CHECK(service.get() != NULL); 173 174 service->addBatteryData(params); 175} 176 177//////////////////////////////////////////////////////////////////////////////// 178AwesomePlayer::AwesomePlayer() 179 : mQueueStarted(false), 180 mTimeSource(NULL), 181 mVideoRendererIsPreview(false), 182 mAudioPlayer(NULL), 183 mDisplayWidth(0), 184 mDisplayHeight(0), 185 mFlags(0), 186 mExtractorFlags(0), 187 mVideoBuffer(NULL), 188 mDecryptHandle(NULL) { 189 CHECK_EQ(mClient.connect(), (status_t)OK); 190 191 DataSource::RegisterDefaultSniffers(); 192 193 mVideoEvent = new AwesomeEvent(this, &AwesomePlayer::onVideoEvent); 194 mVideoEventPending = false; 195 mStreamDoneEvent = new AwesomeEvent(this, &AwesomePlayer::onStreamDone); 196 mStreamDoneEventPending = false; 197 mBufferingEvent = new AwesomeEvent(this, &AwesomePlayer::onBufferingUpdate); 198 mBufferingEventPending = false; 199 mVideoLagEvent = new AwesomeEvent(this, &AwesomePlayer::onVideoLagUpdate); 200 mVideoEventPending = false; 201 202 mCheckAudioStatusEvent = new AwesomeEvent( 203 this, &AwesomePlayer::onCheckAudioStatus); 204 205 mAudioStatusEventPending = false; 206 207 reset(); 208} 209 210AwesomePlayer::~AwesomePlayer() { 211 if (mQueueStarted) { 212 mQueue.stop(); 213 } 214 215 reset(); 216 217 mClient.disconnect(); 218} 219 220void AwesomePlayer::cancelPlayerEvents(bool keepBufferingGoing) { 221 mQueue.cancelEvent(mVideoEvent->eventID()); 222 mVideoEventPending = false; 223 mQueue.cancelEvent(mStreamDoneEvent->eventID()); 224 mStreamDoneEventPending = false; 225 mQueue.cancelEvent(mCheckAudioStatusEvent->eventID()); 226 mAudioStatusEventPending = false; 227 mQueue.cancelEvent(mVideoLagEvent->eventID()); 228 mVideoLagEventPending = false; 229 230 if (!keepBufferingGoing) { 231 mQueue.cancelEvent(mBufferingEvent->eventID()); 232 mBufferingEventPending = false; 233 } 234} 235 236void AwesomePlayer::setListener(const wp<MediaPlayerBase> &listener) { 237 Mutex::Autolock autoLock(mLock); 238 mListener = listener; 239} 240 241status_t AwesomePlayer::setDataSource( 242 const char *uri, const KeyedVector<String8, String8> *headers) { 243 Mutex::Autolock autoLock(mLock); 244 return setDataSource_l(uri, headers); 245} 246 247status_t AwesomePlayer::setDataSource_l( 248 const char *uri, const KeyedVector<String8, String8> *headers) { 249 reset_l(); 250 251 mUri = uri; 252 253 if (headers) { 254 mUriHeaders = *headers; 255 256 ssize_t index = mUriHeaders.indexOfKey(String8("x-hide-urls-from-log")); 257 if (index >= 0) { 258 // Browser is in "incognito" mode, suppress logging URLs. 259 260 // This isn't something that should be passed to the server. 261 mUriHeaders.removeItemsAt(index); 262 263 mFlags |= INCOGNITO; 264 } 265 } 266 267 if (!(mFlags & INCOGNITO)) { 268 LOGI("setDataSource_l('%s')", mUri.string()); 269 } else { 270 LOGI("setDataSource_l(URL suppressed)"); 271 } 272 273 // The actual work will be done during preparation in the call to 274 // ::finishSetDataSource_l to avoid blocking the calling thread in 275 // setDataSource for any significant time. 276 277 return OK; 278} 279 280status_t AwesomePlayer::setDataSource( 281 int fd, int64_t offset, int64_t length) { 282 Mutex::Autolock autoLock(mLock); 283 284 reset_l(); 285 286 sp<DataSource> dataSource = new FileSource(fd, offset, length); 287 288 status_t err = dataSource->initCheck(); 289 290 if (err != OK) { 291 return err; 292 } 293 294 mFileSource = dataSource; 295 296 return setDataSource_l(dataSource); 297} 298 299status_t AwesomePlayer::setDataSource(const sp<IStreamSource> &source) { 300 return INVALID_OPERATION; 301} 302 303status_t AwesomePlayer::setDataSource_l( 304 const sp<DataSource> &dataSource) { 305 sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource); 306 307 if (extractor == NULL) { 308 return UNKNOWN_ERROR; 309 } 310 311 dataSource->getDrmInfo(mDecryptHandle, &mDrmManagerClient); 312 if (mDecryptHandle != NULL) { 313 CHECK(mDrmManagerClient); 314 if (RightsStatus::RIGHTS_VALID != mDecryptHandle->status) { 315 notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_NO_LICENSE); 316 } 317 } 318 319 return setDataSource_l(extractor); 320} 321 322status_t AwesomePlayer::setDataSource_l(const sp<MediaExtractor> &extractor) { 323 // Attempt to approximate overall stream bitrate by summing all 324 // tracks' individual bitrates, if not all of them advertise bitrate, 325 // we have to fail. 326 327 int64_t totalBitRate = 0; 328 329 for (size_t i = 0; i < extractor->countTracks(); ++i) { 330 sp<MetaData> meta = extractor->getTrackMetaData(i); 331 332 int32_t bitrate; 333 if (!meta->findInt32(kKeyBitRate, &bitrate)) { 334 totalBitRate = -1; 335 break; 336 } 337 338 totalBitRate += bitrate; 339 } 340 341 mBitrate = totalBitRate; 342 343 LOGV("mBitrate = %lld bits/sec", mBitrate); 344 345 bool haveAudio = false; 346 bool haveVideo = false; 347 for (size_t i = 0; i < extractor->countTracks(); ++i) { 348 sp<MetaData> meta = extractor->getTrackMetaData(i); 349 350 const char *mime; 351 CHECK(meta->findCString(kKeyMIMEType, &mime)); 352 353 if (!haveVideo && !strncasecmp(mime, "video/", 6)) { 354 setVideoSource(extractor->getTrack(i)); 355 haveVideo = true; 356 357 // Set the presentation/display size 358 int32_t displayWidth, displayHeight; 359 bool success = meta->findInt32(kKeyDisplayWidth, &displayWidth); 360 if (success) { 361 success = meta->findInt32(kKeyDisplayHeight, &displayHeight); 362 } 363 if (success) { 364 mDisplayWidth = displayWidth; 365 mDisplayHeight = displayHeight; 366 } 367 368 } else if (!haveAudio && !strncasecmp(mime, "audio/", 6)) { 369 setAudioSource(extractor->getTrack(i)); 370 haveAudio = true; 371 372 if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)) { 373 // Only do this for vorbis audio, none of the other audio 374 // formats even support this ringtone specific hack and 375 // retrieving the metadata on some extractors may turn out 376 // to be very expensive. 377 sp<MetaData> fileMeta = extractor->getMetaData(); 378 int32_t loop; 379 if (fileMeta != NULL 380 && fileMeta->findInt32(kKeyAutoLoop, &loop) && loop != 0) { 381 mFlags |= AUTO_LOOPING; 382 } 383 } 384 } 385 386 if (haveAudio && haveVideo) { 387 break; 388 } 389 } 390 391 if (!haveAudio && !haveVideo) { 392 return UNKNOWN_ERROR; 393 } 394 395 mExtractorFlags = extractor->flags(); 396 397 return OK; 398} 399 400void AwesomePlayer::reset() { 401 Mutex::Autolock autoLock(mLock); 402 reset_l(); 403} 404 405void AwesomePlayer::reset_l() { 406 mDisplayWidth = 0; 407 mDisplayHeight = 0; 408 409 if (mDecryptHandle != NULL) { 410 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 411 Playback::STOP, 0); 412 mDecryptHandle = NULL; 413 mDrmManagerClient = NULL; 414 } 415 416 if (mFlags & PLAYING) { 417 uint32_t params = IMediaPlayerService::kBatteryDataTrackDecoder; 418 if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) { 419 params |= IMediaPlayerService::kBatteryDataTrackAudio; 420 } 421 if (mVideoSource != NULL) { 422 params |= IMediaPlayerService::kBatteryDataTrackVideo; 423 } 424 addBatteryData(params); 425 } 426 427 if (mFlags & PREPARING) { 428 mFlags |= PREPARE_CANCELLED; 429 if (mConnectingDataSource != NULL) { 430 LOGI("interrupting the connection process"); 431 mConnectingDataSource->disconnect(); 432 } else if (mConnectingRTSPController != NULL) { 433 LOGI("interrupting the connection process"); 434 mConnectingRTSPController->disconnect(); 435 } 436 437 if (mFlags & PREPARING_CONNECTED) { 438 // We are basically done preparing, we're just buffering 439 // enough data to start playback, we can safely interrupt that. 440 finishAsyncPrepare_l(); 441 } 442 } 443 444 while (mFlags & PREPARING) { 445 mPreparedCondition.wait(mLock); 446 } 447 448 cancelPlayerEvents(); 449 450 mCachedSource.clear(); 451 mAudioTrack.clear(); 452 mVideoTrack.clear(); 453 454 // Shutdown audio first, so that the respone to the reset request 455 // appears to happen instantaneously as far as the user is concerned 456 // If we did this later, audio would continue playing while we 457 // shutdown the video-related resources and the player appear to 458 // not be as responsive to a reset request. 459 if (mAudioPlayer == NULL && mAudioSource != NULL) { 460 // If we had an audio player, it would have effectively 461 // taken possession of the audio source and stopped it when 462 // _it_ is stopped. Otherwise this is still our responsibility. 463 mAudioSource->stop(); 464 } 465 mAudioSource.clear(); 466 467 mTimeSource = NULL; 468 469 delete mAudioPlayer; 470 mAudioPlayer = NULL; 471 472 mVideoRenderer.clear(); 473 474 if (mVideoBuffer) { 475 mVideoBuffer->release(); 476 mVideoBuffer = NULL; 477 } 478 479 if (mRTSPController != NULL) { 480 mRTSPController->disconnect(); 481 mRTSPController.clear(); 482 } 483 484 if (mVideoSource != NULL) { 485 mVideoSource->stop(); 486 487 // The following hack is necessary to ensure that the OMX 488 // component is completely released by the time we may try 489 // to instantiate it again. 490 wp<MediaSource> tmp = mVideoSource; 491 mVideoSource.clear(); 492 while (tmp.promote() != NULL) { 493 usleep(1000); 494 } 495 IPCThreadState::self()->flushCommands(); 496 } 497 498 mDurationUs = -1; 499 mFlags = 0; 500 mExtractorFlags = 0; 501 mTimeSourceDeltaUs = 0; 502 mVideoTimeUs = 0; 503 504 mSeeking = NO_SEEK; 505 mSeekNotificationSent = false; 506 mSeekTimeUs = 0; 507 508 mUri.setTo(""); 509 mUriHeaders.clear(); 510 511 mFileSource.clear(); 512 513 mBitrate = -1; 514} 515 516void AwesomePlayer::notifyListener_l(int msg, int ext1, int ext2) { 517 if (mListener != NULL) { 518 sp<MediaPlayerBase> listener = mListener.promote(); 519 520 if (listener != NULL) { 521 listener->sendEvent(msg, ext1, ext2); 522 } 523 } 524} 525 526bool AwesomePlayer::getBitrate(int64_t *bitrate) { 527 off64_t size; 528 if (mDurationUs >= 0 && mCachedSource != NULL 529 && mCachedSource->getSize(&size) == OK) { 530 *bitrate = size * 8000000ll / mDurationUs; // in bits/sec 531 return true; 532 } 533 534 if (mBitrate >= 0) { 535 *bitrate = mBitrate; 536 return true; 537 } 538 539 *bitrate = 0; 540 541 return false; 542} 543 544// Returns true iff cached duration is available/applicable. 545bool AwesomePlayer::getCachedDuration_l(int64_t *durationUs, bool *eos) { 546 int64_t bitrate; 547 548 if (mRTSPController != NULL) { 549 *durationUs = mRTSPController->getQueueDurationUs(eos); 550 return true; 551 } else if (mCachedSource != NULL && getBitrate(&bitrate)) { 552 status_t finalStatus; 553 size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus); 554 *durationUs = cachedDataRemaining * 8000000ll / bitrate; 555 *eos = (finalStatus != OK); 556 return true; 557 } 558 559 return false; 560} 561 562void AwesomePlayer::ensureCacheIsFetching_l() { 563 if (mCachedSource != NULL) { 564 mCachedSource->resumeFetchingIfNecessary(); 565 } 566} 567 568void AwesomePlayer::onVideoLagUpdate() { 569 Mutex::Autolock autoLock(mLock); 570 if (!mVideoLagEventPending) { 571 return; 572 } 573 mVideoLagEventPending = false; 574 575 int64_t audioTimeUs = mAudioPlayer->getMediaTimeUs(); 576 int64_t videoLateByUs = audioTimeUs - mVideoTimeUs; 577 578 if (!(mFlags & VIDEO_AT_EOS) && videoLateByUs > 300000ll) { 579 LOGV("video late by %lld ms.", videoLateByUs / 1000ll); 580 581 notifyListener_l( 582 MEDIA_INFO, 583 MEDIA_INFO_VIDEO_TRACK_LAGGING, 584 videoLateByUs / 1000ll); 585 } 586 587 postVideoLagEvent_l(); 588} 589 590void AwesomePlayer::onBufferingUpdate() { 591 Mutex::Autolock autoLock(mLock); 592 if (!mBufferingEventPending) { 593 return; 594 } 595 mBufferingEventPending = false; 596 597 if (mCachedSource != NULL) { 598 status_t finalStatus; 599 size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus); 600 bool eos = (finalStatus != OK); 601 602 if (eos) { 603 if (finalStatus == ERROR_END_OF_STREAM) { 604 notifyListener_l(MEDIA_BUFFERING_UPDATE, 100); 605 } 606 if (mFlags & PREPARING) { 607 LOGV("cache has reached EOS, prepare is done."); 608 finishAsyncPrepare_l(); 609 } 610 } else { 611 int64_t bitrate; 612 if (getBitrate(&bitrate)) { 613 size_t cachedSize = mCachedSource->cachedSize(); 614 int64_t cachedDurationUs = cachedSize * 8000000ll / bitrate; 615 616 int percentage = 100.0 * (double)cachedDurationUs / mDurationUs; 617 if (percentage > 100) { 618 percentage = 100; 619 } 620 621 notifyListener_l(MEDIA_BUFFERING_UPDATE, percentage); 622 } else { 623 // We don't know the bitrate of the stream, use absolute size 624 // limits to maintain the cache. 625 626 if ((mFlags & PLAYING) && !eos 627 && (cachedDataRemaining < kLowWaterMarkBytes)) { 628 LOGI("cache is running low (< %d) , pausing.", 629 kLowWaterMarkBytes); 630 mFlags |= CACHE_UNDERRUN; 631 pause_l(); 632 ensureCacheIsFetching_l(); 633 notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START); 634 } else if (eos || cachedDataRemaining > kHighWaterMarkBytes) { 635 if (mFlags & CACHE_UNDERRUN) { 636 LOGI("cache has filled up (> %d), resuming.", 637 kHighWaterMarkBytes); 638 mFlags &= ~CACHE_UNDERRUN; 639 play_l(); 640 notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_END); 641 } else if (mFlags & PREPARING) { 642 LOGV("cache has filled up (> %d), prepare is done", 643 kHighWaterMarkBytes); 644 finishAsyncPrepare_l(); 645 } 646 } 647 } 648 } 649 } 650 651 int64_t cachedDurationUs; 652 bool eos; 653 if (getCachedDuration_l(&cachedDurationUs, &eos)) { 654 LOGV("cachedDurationUs = %.2f secs, eos=%d", 655 cachedDurationUs / 1E6, eos); 656 657 int64_t highWaterMarkUs = 658 (mRTSPController != NULL) ? kHighWaterMarkRTSPUs : kHighWaterMarkUs; 659 660 if ((mFlags & PLAYING) && !eos 661 && (cachedDurationUs < kLowWaterMarkUs)) { 662 LOGI("cache is running low (%.2f secs) , pausing.", 663 cachedDurationUs / 1E6); 664 mFlags |= CACHE_UNDERRUN; 665 pause_l(); 666 ensureCacheIsFetching_l(); 667 notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START); 668 } else if (eos || cachedDurationUs > highWaterMarkUs) { 669 if (mFlags & CACHE_UNDERRUN) { 670 LOGI("cache has filled up (%.2f secs), resuming.", 671 cachedDurationUs / 1E6); 672 mFlags &= ~CACHE_UNDERRUN; 673 play_l(); 674 notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_END); 675 } else if (mFlags & PREPARING) { 676 LOGV("cache has filled up (%.2f secs), prepare is done", 677 cachedDurationUs / 1E6); 678 finishAsyncPrepare_l(); 679 } 680 } 681 } 682 683 postBufferingEvent_l(); 684} 685 686void AwesomePlayer::onStreamDone() { 687 // Posted whenever any stream finishes playing. 688 689 Mutex::Autolock autoLock(mLock); 690 if (!mStreamDoneEventPending) { 691 return; 692 } 693 mStreamDoneEventPending = false; 694 695 if (mStreamDoneStatus != ERROR_END_OF_STREAM) { 696 LOGV("MEDIA_ERROR %d", mStreamDoneStatus); 697 698 notifyListener_l( 699 MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, mStreamDoneStatus); 700 701 pause_l(true /* at eos */); 702 703 mFlags |= AT_EOS; 704 return; 705 } 706 707 const bool allDone = 708 (mVideoSource == NULL || (mFlags & VIDEO_AT_EOS)) 709 && (mAudioSource == NULL || (mFlags & AUDIO_AT_EOS)); 710 711 if (!allDone) { 712 return; 713 } 714 715 if (mFlags & (LOOPING | AUTO_LOOPING)) { 716 seekTo_l(0); 717 718 if (mVideoSource != NULL) { 719 postVideoEvent_l(); 720 } 721 } else { 722 LOGV("MEDIA_PLAYBACK_COMPLETE"); 723 notifyListener_l(MEDIA_PLAYBACK_COMPLETE); 724 725 pause_l(true /* at eos */); 726 727 mFlags |= AT_EOS; 728 } 729} 730 731status_t AwesomePlayer::play() { 732 Mutex::Autolock autoLock(mLock); 733 734 mFlags &= ~CACHE_UNDERRUN; 735 736 return play_l(); 737} 738 739status_t AwesomePlayer::play_l() { 740 mFlags &= ~SEEK_PREVIEW; 741 742 if (mFlags & PLAYING) { 743 return OK; 744 } 745 746 if (!(mFlags & PREPARED)) { 747 status_t err = prepare_l(); 748 749 if (err != OK) { 750 return err; 751 } 752 } 753 754 mFlags |= PLAYING; 755 mFlags |= FIRST_FRAME; 756 757 if (mDecryptHandle != NULL) { 758 int64_t position; 759 getPosition(&position); 760 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 761 Playback::START, position / 1000); 762 } 763 764 if (mAudioSource != NULL) { 765 if (mAudioPlayer == NULL) { 766 if (mAudioSink != NULL) { 767 mAudioPlayer = new AudioPlayer(mAudioSink, this); 768 mAudioPlayer->setSource(mAudioSource); 769 770 mTimeSource = mAudioPlayer; 771 772 // If there was a seek request before we ever started, 773 // honor the request now. 774 // Make sure to do this before starting the audio player 775 // to avoid a race condition. 776 seekAudioIfNecessary_l(); 777 } 778 } 779 780 CHECK(!(mFlags & AUDIO_RUNNING)); 781 782 if (mVideoSource == NULL) { 783 status_t err = startAudioPlayer_l(); 784 785 if (err != OK) { 786 delete mAudioPlayer; 787 mAudioPlayer = NULL; 788 789 mFlags &= ~(PLAYING | FIRST_FRAME); 790 791 if (mDecryptHandle != NULL) { 792 mDrmManagerClient->setPlaybackStatus( 793 mDecryptHandle, Playback::STOP, 0); 794 } 795 796 return err; 797 } 798 } 799 } 800 801 if (mTimeSource == NULL && mAudioPlayer == NULL) { 802 mTimeSource = &mSystemTimeSource; 803 } 804 805 if (mVideoSource != NULL) { 806 // Kick off video playback 807 postVideoEvent_l(); 808 809 if (mAudioSource != NULL && mVideoSource != NULL) { 810 postVideoLagEvent_l(); 811 } 812 } 813 814 if (mFlags & AT_EOS) { 815 // Legacy behaviour, if a stream finishes playing and then 816 // is started again, we play from the start... 817 seekTo_l(0); 818 } 819 820 uint32_t params = IMediaPlayerService::kBatteryDataCodecStarted 821 | IMediaPlayerService::kBatteryDataTrackDecoder; 822 if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) { 823 params |= IMediaPlayerService::kBatteryDataTrackAudio; 824 } 825 if (mVideoSource != NULL) { 826 params |= IMediaPlayerService::kBatteryDataTrackVideo; 827 } 828 addBatteryData(params); 829 830 return OK; 831} 832 833status_t AwesomePlayer::startAudioPlayer_l() { 834 CHECK(!(mFlags & AUDIO_RUNNING)); 835 836 if (mAudioSource == NULL || mAudioPlayer == NULL) { 837 return OK; 838 } 839 840 if (!(mFlags & AUDIOPLAYER_STARTED)) { 841 mFlags |= AUDIOPLAYER_STARTED; 842 843 // We've already started the MediaSource in order to enable 844 // the prefetcher to read its data. 845 status_t err = mAudioPlayer->start( 846 true /* sourceAlreadyStarted */); 847 848 if (err != OK) { 849 notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err); 850 return err; 851 } 852 } else { 853 mAudioPlayer->resume(); 854 } 855 856 mFlags |= AUDIO_RUNNING; 857 858 mWatchForAudioEOS = true; 859 860 return OK; 861} 862 863void AwesomePlayer::notifyVideoSize_l() { 864 sp<MetaData> meta = mVideoSource->getFormat(); 865 866 int32_t cropLeft, cropTop, cropRight, cropBottom; 867 if (!meta->findRect( 868 kKeyCropRect, &cropLeft, &cropTop, &cropRight, &cropBottom)) { 869 int32_t width, height; 870 CHECK(meta->findInt32(kKeyWidth, &width)); 871 CHECK(meta->findInt32(kKeyHeight, &height)); 872 873 cropLeft = cropTop = 0; 874 cropRight = width - 1; 875 cropBottom = height - 1; 876 877 LOGV("got dimensions only %d x %d", width, height); 878 } else { 879 LOGV("got crop rect %d, %d, %d, %d", 880 cropLeft, cropTop, cropRight, cropBottom); 881 } 882 883 int32_t displayWidth; 884 if (meta->findInt32(kKeyDisplayWidth, &displayWidth)) { 885 LOGV("Display width changed (%d=>%d)", mDisplayWidth, displayWidth); 886 mDisplayWidth = displayWidth; 887 } 888 int32_t displayHeight; 889 if (meta->findInt32(kKeyDisplayHeight, &displayHeight)) { 890 LOGV("Display height changed (%d=>%d)", mDisplayHeight, displayHeight); 891 mDisplayHeight = displayHeight; 892 } 893 894 int32_t usableWidth = cropRight - cropLeft + 1; 895 int32_t usableHeight = cropBottom - cropTop + 1; 896 if (mDisplayWidth != 0) { 897 usableWidth = mDisplayWidth; 898 } 899 if (mDisplayHeight != 0) { 900 usableHeight = mDisplayHeight; 901 } 902 903 int32_t rotationDegrees; 904 if (!mVideoTrack->getFormat()->findInt32( 905 kKeyRotation, &rotationDegrees)) { 906 rotationDegrees = 0; 907 } 908 909 if (rotationDegrees == 90 || rotationDegrees == 270) { 910 notifyListener_l( 911 MEDIA_SET_VIDEO_SIZE, usableHeight, usableWidth); 912 } else { 913 notifyListener_l( 914 MEDIA_SET_VIDEO_SIZE, usableWidth, usableHeight); 915 } 916} 917 918void AwesomePlayer::initRenderer_l() { 919 if (mNativeWindow == NULL) { 920 return; 921 } 922 923 sp<MetaData> meta = mVideoSource->getFormat(); 924 925 int32_t format; 926 const char *component; 927 int32_t decodedWidth, decodedHeight; 928 CHECK(meta->findInt32(kKeyColorFormat, &format)); 929 CHECK(meta->findCString(kKeyDecoderComponent, &component)); 930 CHECK(meta->findInt32(kKeyWidth, &decodedWidth)); 931 CHECK(meta->findInt32(kKeyHeight, &decodedHeight)); 932 933 int32_t rotationDegrees; 934 if (!mVideoTrack->getFormat()->findInt32( 935 kKeyRotation, &rotationDegrees)) { 936 rotationDegrees = 0; 937 } 938 939 mVideoRenderer.clear(); 940 941 // Must ensure that mVideoRenderer's destructor is actually executed 942 // before creating a new one. 943 IPCThreadState::self()->flushCommands(); 944 945 if (USE_SURFACE_ALLOC && strncmp(component, "OMX.", 4) == 0) { 946 // Hardware decoders avoid the CPU color conversion by decoding 947 // directly to ANativeBuffers, so we must use a renderer that 948 // just pushes those buffers to the ANativeWindow. 949 mVideoRenderer = 950 new AwesomeNativeWindowRenderer(mNativeWindow, rotationDegrees); 951 } else { 952 // Other decoders are instantiated locally and as a consequence 953 // allocate their buffers in local address space. This renderer 954 // then performs a color conversion and copy to get the data 955 // into the ANativeBuffer. 956 mVideoRenderer = new AwesomeLocalRenderer(mNativeWindow, meta); 957 } 958} 959 960status_t AwesomePlayer::pause() { 961 Mutex::Autolock autoLock(mLock); 962 963 mFlags &= ~CACHE_UNDERRUN; 964 965 return pause_l(); 966} 967 968status_t AwesomePlayer::pause_l(bool at_eos) { 969 if (!(mFlags & PLAYING)) { 970 return OK; 971 } 972 973 cancelPlayerEvents(true /* keepBufferingGoing */); 974 975 if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) { 976 if (at_eos) { 977 // If we played the audio stream to completion we 978 // want to make sure that all samples remaining in the audio 979 // track's queue are played out. 980 mAudioPlayer->pause(true /* playPendingSamples */); 981 } else { 982 mAudioPlayer->pause(); 983 } 984 985 mFlags &= ~AUDIO_RUNNING; 986 } 987 988 mFlags &= ~PLAYING; 989 990 if (mDecryptHandle != NULL) { 991 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 992 Playback::PAUSE, 0); 993 } 994 995 uint32_t params = IMediaPlayerService::kBatteryDataTrackDecoder; 996 if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) { 997 params |= IMediaPlayerService::kBatteryDataTrackAudio; 998 } 999 if (mVideoSource != NULL) { 1000 params |= IMediaPlayerService::kBatteryDataTrackVideo; 1001 } 1002 1003 addBatteryData(params); 1004 1005 return OK; 1006} 1007 1008bool AwesomePlayer::isPlaying() const { 1009 return (mFlags & PLAYING) || (mFlags & CACHE_UNDERRUN); 1010} 1011 1012void AwesomePlayer::setSurface(const sp<Surface> &surface) { 1013 Mutex::Autolock autoLock(mLock); 1014 1015 mSurface = surface; 1016 mNativeWindow = surface; 1017} 1018 1019void AwesomePlayer::setSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture) { 1020 Mutex::Autolock autoLock(mLock); 1021 1022 mSurface.clear(); 1023 if (surfaceTexture != NULL) { 1024 mNativeWindow = new SurfaceTextureClient(surfaceTexture); 1025 } 1026 1027} 1028 1029void AwesomePlayer::setAudioSink( 1030 const sp<MediaPlayerBase::AudioSink> &audioSink) { 1031 Mutex::Autolock autoLock(mLock); 1032 1033 mAudioSink = audioSink; 1034} 1035 1036status_t AwesomePlayer::setLooping(bool shouldLoop) { 1037 Mutex::Autolock autoLock(mLock); 1038 1039 mFlags = mFlags & ~LOOPING; 1040 1041 if (shouldLoop) { 1042 mFlags |= LOOPING; 1043 } 1044 1045 return OK; 1046} 1047 1048status_t AwesomePlayer::getDuration(int64_t *durationUs) { 1049 Mutex::Autolock autoLock(mMiscStateLock); 1050 1051 if (mDurationUs < 0) { 1052 return UNKNOWN_ERROR; 1053 } 1054 1055 *durationUs = mDurationUs; 1056 1057 return OK; 1058} 1059 1060status_t AwesomePlayer::getPosition(int64_t *positionUs) { 1061 if (mRTSPController != NULL) { 1062 *positionUs = mRTSPController->getNormalPlayTimeUs(); 1063 } 1064 else if (mSeeking != NO_SEEK) { 1065 *positionUs = mSeekTimeUs; 1066 } else if (mVideoSource != NULL 1067 && (mAudioPlayer == NULL || !(mFlags & VIDEO_AT_EOS))) { 1068 Mutex::Autolock autoLock(mMiscStateLock); 1069 *positionUs = mVideoTimeUs; 1070 } else if (mAudioPlayer != NULL) { 1071 *positionUs = mAudioPlayer->getMediaTimeUs(); 1072 } else { 1073 *positionUs = 0; 1074 } 1075 1076 return OK; 1077} 1078 1079status_t AwesomePlayer::seekTo(int64_t timeUs) { 1080 if (mExtractorFlags & MediaExtractor::CAN_SEEK) { 1081 Mutex::Autolock autoLock(mLock); 1082 return seekTo_l(timeUs); 1083 } 1084 1085 return OK; 1086} 1087 1088// static 1089void AwesomePlayer::OnRTSPSeekDoneWrapper(void *cookie) { 1090 static_cast<AwesomePlayer *>(cookie)->onRTSPSeekDone(); 1091} 1092 1093void AwesomePlayer::onRTSPSeekDone() { 1094 notifyListener_l(MEDIA_SEEK_COMPLETE); 1095 mSeekNotificationSent = true; 1096} 1097 1098status_t AwesomePlayer::seekTo_l(int64_t timeUs) { 1099 if (mRTSPController != NULL) { 1100 mRTSPController->seekAsync(timeUs, OnRTSPSeekDoneWrapper, this); 1101 return OK; 1102 } 1103 1104 if (mFlags & CACHE_UNDERRUN) { 1105 mFlags &= ~CACHE_UNDERRUN; 1106 play_l(); 1107 } 1108 1109 if ((mFlags & PLAYING) && mVideoSource != NULL && (mFlags & VIDEO_AT_EOS)) { 1110 // Video playback completed before, there's no pending 1111 // video event right now. In order for this new seek 1112 // to be honored, we need to post one. 1113 1114 postVideoEvent_l(); 1115 } 1116 1117 mSeeking = SEEK; 1118 mSeekNotificationSent = false; 1119 mSeekTimeUs = timeUs; 1120 mFlags &= ~(AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS); 1121 1122 seekAudioIfNecessary_l(); 1123 1124 if (!(mFlags & PLAYING)) { 1125 LOGV("seeking while paused, sending SEEK_COMPLETE notification" 1126 " immediately."); 1127 1128 notifyListener_l(MEDIA_SEEK_COMPLETE); 1129 mSeekNotificationSent = true; 1130 1131 if ((mFlags & PREPARED) && mVideoSource != NULL) { 1132 mFlags |= SEEK_PREVIEW; 1133 postVideoEvent_l(); 1134 } 1135 } 1136 1137 return OK; 1138} 1139 1140void AwesomePlayer::seekAudioIfNecessary_l() { 1141 if (mSeeking != NO_SEEK && mVideoSource == NULL && mAudioPlayer != NULL) { 1142 mAudioPlayer->seekTo(mSeekTimeUs); 1143 1144 mWatchForAudioSeekComplete = true; 1145 mWatchForAudioEOS = true; 1146 1147 if (mDecryptHandle != NULL) { 1148 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1149 Playback::PAUSE, 0); 1150 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1151 Playback::START, mSeekTimeUs / 1000); 1152 } 1153 } 1154} 1155 1156void AwesomePlayer::setAudioSource(sp<MediaSource> source) { 1157 CHECK(source != NULL); 1158 1159 mAudioTrack = source; 1160} 1161 1162status_t AwesomePlayer::initAudioDecoder() { 1163 sp<MetaData> meta = mAudioTrack->getFormat(); 1164 1165 const char *mime; 1166 CHECK(meta->findCString(kKeyMIMEType, &mime)); 1167 1168 if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_RAW)) { 1169 mAudioSource = mAudioTrack; 1170 } else { 1171 mAudioSource = OMXCodec::Create( 1172 mClient.interface(), mAudioTrack->getFormat(), 1173 false, // createEncoder 1174 mAudioTrack); 1175 } 1176 1177 if (mAudioSource != NULL) { 1178 int64_t durationUs; 1179 if (mAudioTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) { 1180 Mutex::Autolock autoLock(mMiscStateLock); 1181 if (mDurationUs < 0 || durationUs > mDurationUs) { 1182 mDurationUs = durationUs; 1183 } 1184 } 1185 1186 status_t err = mAudioSource->start(); 1187 1188 if (err != OK) { 1189 mAudioSource.clear(); 1190 return err; 1191 } 1192 } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_QCELP)) { 1193 // For legacy reasons we're simply going to ignore the absence 1194 // of an audio decoder for QCELP instead of aborting playback 1195 // altogether. 1196 return OK; 1197 } 1198 1199 return mAudioSource != NULL ? OK : UNKNOWN_ERROR; 1200} 1201 1202void AwesomePlayer::setVideoSource(sp<MediaSource> source) { 1203 CHECK(source != NULL); 1204 1205 mVideoTrack = source; 1206} 1207 1208status_t AwesomePlayer::initVideoDecoder(uint32_t flags) { 1209 1210 // Either the application or the DRM system can independently say 1211 // that there must be a hardware-protected path to an external video sink. 1212 // For now we always require a hardware-protected path to external video sink 1213 // if content is DRMed, but eventually this could be optional per DRM agent. 1214 // When the application wants protection, then 1215 // (USE_SURFACE_ALLOC && (mSurface != 0) && 1216 // (mSurface->getFlags() & ISurfaceComposer::eProtectedByApp)) 1217 // will be true, but that part is already handled by SurfaceFlinger. 1218 1219#ifdef DEBUG_HDCP 1220 // For debugging, we allow a system property to control the protected usage. 1221 // In case of uninitialized or unexpected property, we default to "DRM only". 1222 bool setProtectionBit = false; 1223 char value[PROPERTY_VALUE_MAX]; 1224 if (property_get("persist.sys.hdcp_checking", value, NULL)) { 1225 if (!strcmp(value, "never")) { 1226 // nop 1227 } else if (!strcmp(value, "always")) { 1228 setProtectionBit = true; 1229 } else if (!strcmp(value, "drm-only")) { 1230 if (mDecryptHandle != NULL) { 1231 setProtectionBit = true; 1232 } 1233 // property value is empty, or unexpected value 1234 } else { 1235 if (mDecryptHandle != NULL) { 1236 setProtectionBit = true; 1237 } 1238 } 1239 // can' read property value 1240 } else { 1241 if (mDecryptHandle != NULL) { 1242 setProtectionBit = true; 1243 } 1244 } 1245 // note that usage bit is already cleared, so no need to clear it in the "else" case 1246 if (setProtectionBit) { 1247 flags |= OMXCodec::kEnableGrallocUsageProtected; 1248 } 1249#else 1250 if (mDecryptHandle != NULL) { 1251 flags |= OMXCodec::kEnableGrallocUsageProtected; 1252 } 1253#endif 1254 LOGV("initVideoDecoder flags=0x%x", flags); 1255 mVideoSource = OMXCodec::Create( 1256 mClient.interface(), mVideoTrack->getFormat(), 1257 false, // createEncoder 1258 mVideoTrack, 1259 NULL, flags, USE_SURFACE_ALLOC ? mNativeWindow : NULL); 1260 1261 if (mVideoSource != NULL) { 1262 int64_t durationUs; 1263 if (mVideoTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) { 1264 Mutex::Autolock autoLock(mMiscStateLock); 1265 if (mDurationUs < 0 || durationUs > mDurationUs) { 1266 mDurationUs = durationUs; 1267 } 1268 } 1269 1270 status_t err = mVideoSource->start(); 1271 1272 if (err != OK) { 1273 mVideoSource.clear(); 1274 return err; 1275 } 1276 } 1277 1278 return mVideoSource != NULL ? OK : UNKNOWN_ERROR; 1279} 1280 1281void AwesomePlayer::finishSeekIfNecessary(int64_t videoTimeUs) { 1282 if (mSeeking == SEEK_VIDEO_ONLY) { 1283 mSeeking = NO_SEEK; 1284 return; 1285 } 1286 1287 if (mSeeking == NO_SEEK || (mFlags & SEEK_PREVIEW)) { 1288 return; 1289 } 1290 1291 if (mAudioPlayer != NULL) { 1292 LOGV("seeking audio to %lld us (%.2f secs).", videoTimeUs, videoTimeUs / 1E6); 1293 1294 // If we don't have a video time, seek audio to the originally 1295 // requested seek time instead. 1296 1297 mAudioPlayer->seekTo(videoTimeUs < 0 ? mSeekTimeUs : videoTimeUs); 1298 mWatchForAudioSeekComplete = true; 1299 mWatchForAudioEOS = true; 1300 } else if (!mSeekNotificationSent) { 1301 // If we're playing video only, report seek complete now, 1302 // otherwise audio player will notify us later. 1303 notifyListener_l(MEDIA_SEEK_COMPLETE); 1304 mSeekNotificationSent = true; 1305 } 1306 1307 mFlags |= FIRST_FRAME; 1308 mSeeking = NO_SEEK; 1309 1310 if (mDecryptHandle != NULL) { 1311 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1312 Playback::PAUSE, 0); 1313 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1314 Playback::START, videoTimeUs / 1000); 1315 } 1316} 1317 1318void AwesomePlayer::onVideoEvent() { 1319 Mutex::Autolock autoLock(mLock); 1320 if (!mVideoEventPending) { 1321 // The event has been cancelled in reset_l() but had already 1322 // been scheduled for execution at that time. 1323 return; 1324 } 1325 mVideoEventPending = false; 1326 1327 if (mSeeking != NO_SEEK) { 1328 if (mVideoBuffer) { 1329 mVideoBuffer->release(); 1330 mVideoBuffer = NULL; 1331 } 1332 1333 if (mSeeking == SEEK && mCachedSource != NULL && mAudioSource != NULL 1334 && !(mFlags & SEEK_PREVIEW)) { 1335 // We're going to seek the video source first, followed by 1336 // the audio source. 1337 // In order to avoid jumps in the DataSource offset caused by 1338 // the audio codec prefetching data from the old locations 1339 // while the video codec is already reading data from the new 1340 // locations, we'll "pause" the audio source, causing it to 1341 // stop reading input data until a subsequent seek. 1342 1343 if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) { 1344 mAudioPlayer->pause(); 1345 1346 mFlags &= ~AUDIO_RUNNING; 1347 } 1348 mAudioSource->pause(); 1349 } 1350 } 1351 1352 if (!mVideoBuffer) { 1353 MediaSource::ReadOptions options; 1354 if (mSeeking != NO_SEEK) { 1355 LOGV("seeking to %lld us (%.2f secs)", mSeekTimeUs, mSeekTimeUs / 1E6); 1356 1357 options.setSeekTo( 1358 mSeekTimeUs, 1359 mSeeking == SEEK_VIDEO_ONLY 1360 ? MediaSource::ReadOptions::SEEK_NEXT_SYNC 1361 : MediaSource::ReadOptions::SEEK_CLOSEST_SYNC); 1362 } 1363 for (;;) { 1364 status_t err = mVideoSource->read(&mVideoBuffer, &options); 1365 options.clearSeekTo(); 1366 1367 if (err != OK) { 1368 CHECK(mVideoBuffer == NULL); 1369 1370 if (err == INFO_FORMAT_CHANGED) { 1371 LOGV("VideoSource signalled format change."); 1372 1373 notifyVideoSize_l(); 1374 1375 if (mVideoRenderer != NULL) { 1376 mVideoRendererIsPreview = false; 1377 initRenderer_l(); 1378 } 1379 continue; 1380 } 1381 1382 // So video playback is complete, but we may still have 1383 // a seek request pending that needs to be applied 1384 // to the audio track. 1385 if (mSeeking != NO_SEEK) { 1386 LOGV("video stream ended while seeking!"); 1387 } 1388 finishSeekIfNecessary(-1); 1389 1390 if (mAudioPlayer != NULL 1391 && !(mFlags & (AUDIO_RUNNING | SEEK_PREVIEW))) { 1392 startAudioPlayer_l(); 1393 } 1394 1395 mFlags |= VIDEO_AT_EOS; 1396 postStreamDoneEvent_l(err); 1397 return; 1398 } 1399 1400 if (mVideoBuffer->range_length() == 0) { 1401 // Some decoders, notably the PV AVC software decoder 1402 // return spurious empty buffers that we just want to ignore. 1403 1404 mVideoBuffer->release(); 1405 mVideoBuffer = NULL; 1406 continue; 1407 } 1408 1409 break; 1410 } 1411 } 1412 1413 int64_t timeUs; 1414 CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &timeUs)); 1415 1416 if (mSeeking == SEEK_VIDEO_ONLY) { 1417 if (mSeekTimeUs > timeUs) { 1418 LOGI("XXX mSeekTimeUs = %lld us, timeUs = %lld us", 1419 mSeekTimeUs, timeUs); 1420 } 1421 } 1422 1423 { 1424 Mutex::Autolock autoLock(mMiscStateLock); 1425 mVideoTimeUs = timeUs; 1426 } 1427 1428 SeekType wasSeeking = mSeeking; 1429 finishSeekIfNecessary(timeUs); 1430 1431 if (mAudioPlayer != NULL && !(mFlags & (AUDIO_RUNNING | SEEK_PREVIEW))) { 1432 status_t err = startAudioPlayer_l(); 1433 if (err != OK) { 1434 LOGE("Startung the audio player failed w/ err %d", err); 1435 return; 1436 } 1437 } 1438 1439 TimeSource *ts = (mFlags & AUDIO_AT_EOS) ? &mSystemTimeSource : mTimeSource; 1440 1441 if (mFlags & FIRST_FRAME) { 1442 mFlags &= ~FIRST_FRAME; 1443 mSinceLastDropped = 0; 1444 mTimeSourceDeltaUs = ts->getRealTimeUs() - timeUs; 1445 } 1446 1447 int64_t realTimeUs, mediaTimeUs; 1448 if (!(mFlags & AUDIO_AT_EOS) && mAudioPlayer != NULL 1449 && mAudioPlayer->getMediaTimeMapping(&realTimeUs, &mediaTimeUs)) { 1450 mTimeSourceDeltaUs = realTimeUs - mediaTimeUs; 1451 } 1452 1453 if (wasSeeking == SEEK_VIDEO_ONLY) { 1454 int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs; 1455 1456 int64_t latenessUs = nowUs - timeUs; 1457 1458 if (latenessUs > 0) { 1459 LOGI("after SEEK_VIDEO_ONLY we're late by %.2f secs", latenessUs / 1E6); 1460 } 1461 } 1462 1463 if (wasSeeking == NO_SEEK) { 1464 // Let's display the first frame after seeking right away. 1465 1466 int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs; 1467 1468 int64_t latenessUs = nowUs - timeUs; 1469 1470 if (latenessUs > 500000ll 1471 && mRTSPController == NULL 1472 && mAudioPlayer != NULL 1473 && mAudioPlayer->getMediaTimeMapping( 1474 &realTimeUs, &mediaTimeUs)) { 1475 LOGI("we're much too late (%.2f secs), video skipping ahead", 1476 latenessUs / 1E6); 1477 1478 mVideoBuffer->release(); 1479 mVideoBuffer = NULL; 1480 1481 mSeeking = SEEK_VIDEO_ONLY; 1482 mSeekTimeUs = mediaTimeUs; 1483 1484 postVideoEvent_l(); 1485 return; 1486 } 1487 1488 if (latenessUs > 40000) { 1489 // We're more than 40ms late. 1490 LOGV("we're late by %lld us (%.2f secs)", latenessUs, latenessUs / 1E6); 1491 if ( mSinceLastDropped > FRAME_DROP_FREQ) 1492 { 1493 LOGV("we're late by %lld us (%.2f secs) dropping one after %d frames", latenessUs, latenessUs / 1E6, mSinceLastDropped); 1494 mSinceLastDropped = 0; 1495 mVideoBuffer->release(); 1496 mVideoBuffer = NULL; 1497 1498 postVideoEvent_l(); 1499 return; 1500 } 1501 } 1502 1503 if (latenessUs < -10000) { 1504 // We're more than 10ms early. 1505 1506 postVideoEvent_l(10000); 1507 return; 1508 } 1509 } 1510 1511 if (mVideoRendererIsPreview || mVideoRenderer == NULL) { 1512 mVideoRendererIsPreview = false; 1513 1514 initRenderer_l(); 1515 } 1516 1517 if (mVideoRenderer != NULL) { 1518 mSinceLastDropped++; 1519 mVideoRenderer->render(mVideoBuffer); 1520 } 1521 1522 mVideoBuffer->release(); 1523 mVideoBuffer = NULL; 1524 1525 if (wasSeeking != NO_SEEK && (mFlags & SEEK_PREVIEW)) { 1526 mFlags &= ~SEEK_PREVIEW; 1527 return; 1528 } 1529 1530 postVideoEvent_l(); 1531} 1532 1533void AwesomePlayer::postVideoEvent_l(int64_t delayUs) { 1534 if (mVideoEventPending) { 1535 return; 1536 } 1537 1538 mVideoEventPending = true; 1539 mQueue.postEventWithDelay(mVideoEvent, delayUs < 0 ? 10000 : delayUs); 1540} 1541 1542void AwesomePlayer::postStreamDoneEvent_l(status_t status) { 1543 if (mStreamDoneEventPending) { 1544 return; 1545 } 1546 mStreamDoneEventPending = true; 1547 1548 mStreamDoneStatus = status; 1549 mQueue.postEvent(mStreamDoneEvent); 1550} 1551 1552void AwesomePlayer::postBufferingEvent_l() { 1553 if (mBufferingEventPending) { 1554 return; 1555 } 1556 mBufferingEventPending = true; 1557 mQueue.postEventWithDelay(mBufferingEvent, 1000000ll); 1558} 1559 1560void AwesomePlayer::postVideoLagEvent_l() { 1561 if (mVideoLagEventPending) { 1562 return; 1563 } 1564 mVideoLagEventPending = true; 1565 mQueue.postEventWithDelay(mVideoLagEvent, 1000000ll); 1566} 1567 1568void AwesomePlayer::postCheckAudioStatusEvent_l(int64_t delayUs) { 1569 if (mAudioStatusEventPending) { 1570 return; 1571 } 1572 mAudioStatusEventPending = true; 1573 mQueue.postEventWithDelay(mCheckAudioStatusEvent, delayUs); 1574} 1575 1576void AwesomePlayer::onCheckAudioStatus() { 1577 Mutex::Autolock autoLock(mLock); 1578 if (!mAudioStatusEventPending) { 1579 // Event was dispatched and while we were blocking on the mutex, 1580 // has already been cancelled. 1581 return; 1582 } 1583 1584 mAudioStatusEventPending = false; 1585 1586 if (mWatchForAudioSeekComplete && !mAudioPlayer->isSeeking()) { 1587 mWatchForAudioSeekComplete = false; 1588 1589 if (!mSeekNotificationSent) { 1590 notifyListener_l(MEDIA_SEEK_COMPLETE); 1591 mSeekNotificationSent = true; 1592 } 1593 1594 mSeeking = NO_SEEK; 1595 } 1596 1597 status_t finalStatus; 1598 if (mWatchForAudioEOS && mAudioPlayer->reachedEOS(&finalStatus)) { 1599 mWatchForAudioEOS = false; 1600 mFlags |= AUDIO_AT_EOS; 1601 mFlags |= FIRST_FRAME; 1602 postStreamDoneEvent_l(finalStatus); 1603 } 1604} 1605 1606status_t AwesomePlayer::prepare() { 1607 Mutex::Autolock autoLock(mLock); 1608 return prepare_l(); 1609} 1610 1611status_t AwesomePlayer::prepare_l() { 1612 if (mFlags & PREPARED) { 1613 return OK; 1614 } 1615 1616 if (mFlags & PREPARING) { 1617 return UNKNOWN_ERROR; 1618 } 1619 1620 mIsAsyncPrepare = false; 1621 status_t err = prepareAsync_l(); 1622 1623 if (err != OK) { 1624 return err; 1625 } 1626 1627 while (mFlags & PREPARING) { 1628 mPreparedCondition.wait(mLock); 1629 } 1630 1631 return mPrepareResult; 1632} 1633 1634status_t AwesomePlayer::prepareAsync() { 1635 Mutex::Autolock autoLock(mLock); 1636 1637 if (mFlags & PREPARING) { 1638 return UNKNOWN_ERROR; // async prepare already pending 1639 } 1640 1641 mIsAsyncPrepare = true; 1642 return prepareAsync_l(); 1643} 1644 1645status_t AwesomePlayer::prepareAsync_l() { 1646 if (mFlags & PREPARING) { 1647 return UNKNOWN_ERROR; // async prepare already pending 1648 } 1649 1650 if (!mQueueStarted) { 1651 mQueue.start(); 1652 mQueueStarted = true; 1653 } 1654 1655 mFlags |= PREPARING; 1656 mAsyncPrepareEvent = new AwesomeEvent( 1657 this, &AwesomePlayer::onPrepareAsyncEvent); 1658 1659 mQueue.postEvent(mAsyncPrepareEvent); 1660 1661 return OK; 1662} 1663 1664status_t AwesomePlayer::finishSetDataSource_l() { 1665 sp<DataSource> dataSource; 1666 1667 if (!strncasecmp("http://", mUri.string(), 7) 1668 || !strncasecmp("https://", mUri.string(), 8)) { 1669 mConnectingDataSource = HTTPBase::Create( 1670 (mFlags & INCOGNITO) 1671 ? HTTPBase::kFlagIncognito 1672 : 0); 1673 1674 mLock.unlock(); 1675 status_t err = mConnectingDataSource->connect(mUri, &mUriHeaders); 1676 mLock.lock(); 1677 1678 if (err != OK) { 1679 mConnectingDataSource.clear(); 1680 1681 LOGI("mConnectingDataSource->connect() returned %d", err); 1682 return err; 1683 } 1684 1685#if 0 1686 mCachedSource = new NuCachedSource2( 1687 new ThrottledSource( 1688 mConnectingDataSource, 50 * 1024 /* bytes/sec */)); 1689#else 1690 mCachedSource = new NuCachedSource2(mConnectingDataSource); 1691#endif 1692 mConnectingDataSource.clear(); 1693 1694 dataSource = mCachedSource; 1695 1696 String8 contentType = dataSource->getMIMEType(); 1697 1698 if (strncasecmp(contentType.string(), "audio/", 6)) { 1699 // We're not doing this for streams that appear to be audio-only 1700 // streams to ensure that even low bandwidth streams start 1701 // playing back fairly instantly. 1702 1703 // We're going to prefill the cache before trying to instantiate 1704 // the extractor below, as the latter is an operation that otherwise 1705 // could block on the datasource for a significant amount of time. 1706 // During that time we'd be unable to abort the preparation phase 1707 // without this prefill. 1708 1709 mLock.unlock(); 1710 1711 for (;;) { 1712 status_t finalStatus; 1713 size_t cachedDataRemaining = 1714 mCachedSource->approxDataRemaining(&finalStatus); 1715 1716 if (finalStatus != OK || cachedDataRemaining >= kHighWaterMarkBytes 1717 || (mFlags & PREPARE_CANCELLED)) { 1718 break; 1719 } 1720 1721 usleep(200000); 1722 } 1723 1724 mLock.lock(); 1725 } 1726 1727 if (mFlags & PREPARE_CANCELLED) { 1728 LOGI("Prepare cancelled while waiting for initial cache fill."); 1729 return UNKNOWN_ERROR; 1730 } 1731 } else if (!strncasecmp("rtsp://", mUri.string(), 7)) { 1732 if (mLooper == NULL) { 1733 mLooper = new ALooper; 1734 mLooper->setName("rtsp"); 1735 mLooper->start(); 1736 } 1737 mRTSPController = new ARTSPController(mLooper); 1738 mConnectingRTSPController = mRTSPController; 1739 1740 mLock.unlock(); 1741 status_t err = mRTSPController->connect(mUri.string()); 1742 mLock.lock(); 1743 1744 mConnectingRTSPController.clear(); 1745 1746 LOGI("ARTSPController::connect returned %d", err); 1747 1748 if (err != OK) { 1749 mRTSPController.clear(); 1750 return err; 1751 } 1752 1753 sp<MediaExtractor> extractor = mRTSPController.get(); 1754 return setDataSource_l(extractor); 1755 } else { 1756 dataSource = DataSource::CreateFromURI(mUri.string(), &mUriHeaders); 1757 } 1758 1759 if (dataSource == NULL) { 1760 return UNKNOWN_ERROR; 1761 } 1762 1763 sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource); 1764 1765 if (extractor == NULL) { 1766 return UNKNOWN_ERROR; 1767 } 1768 1769 dataSource->getDrmInfo(mDecryptHandle, &mDrmManagerClient); 1770 1771 if (mDecryptHandle != NULL) { 1772 CHECK(mDrmManagerClient); 1773 if (RightsStatus::RIGHTS_VALID != mDecryptHandle->status) { 1774 notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_NO_LICENSE); 1775 } 1776 } 1777 1778 return setDataSource_l(extractor); 1779} 1780 1781void AwesomePlayer::abortPrepare(status_t err) { 1782 CHECK(err != OK); 1783 1784 if (mIsAsyncPrepare) { 1785 notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err); 1786 } 1787 1788 mPrepareResult = err; 1789 mFlags &= ~(PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED); 1790 mAsyncPrepareEvent = NULL; 1791 mPreparedCondition.broadcast(); 1792} 1793 1794// static 1795bool AwesomePlayer::ContinuePreparation(void *cookie) { 1796 AwesomePlayer *me = static_cast<AwesomePlayer *>(cookie); 1797 1798 return (me->mFlags & PREPARE_CANCELLED) == 0; 1799} 1800 1801void AwesomePlayer::onPrepareAsyncEvent() { 1802 Mutex::Autolock autoLock(mLock); 1803 1804 if (mFlags & PREPARE_CANCELLED) { 1805 LOGI("prepare was cancelled before doing anything"); 1806 abortPrepare(UNKNOWN_ERROR); 1807 return; 1808 } 1809 1810 if (mUri.size() > 0) { 1811 status_t err = finishSetDataSource_l(); 1812 1813 if (err != OK) { 1814 abortPrepare(err); 1815 return; 1816 } 1817 } 1818 1819 if (mVideoTrack != NULL && mVideoSource == NULL) { 1820 status_t err = initVideoDecoder(); 1821 1822 if (err != OK) { 1823 abortPrepare(err); 1824 return; 1825 } 1826 } 1827 1828 if (mAudioTrack != NULL && mAudioSource == NULL) { 1829 status_t err = initAudioDecoder(); 1830 1831 if (err != OK) { 1832 abortPrepare(err); 1833 return; 1834 } 1835 } 1836 1837 mFlags |= PREPARING_CONNECTED; 1838 1839 if (mCachedSource != NULL || mRTSPController != NULL) { 1840 postBufferingEvent_l(); 1841 } else { 1842 finishAsyncPrepare_l(); 1843 } 1844} 1845 1846void AwesomePlayer::finishAsyncPrepare_l() { 1847 if (mIsAsyncPrepare) { 1848 if (mVideoSource == NULL) { 1849 notifyListener_l(MEDIA_SET_VIDEO_SIZE, 0, 0); 1850 } else { 1851 notifyVideoSize_l(); 1852 } 1853 1854 notifyListener_l(MEDIA_PREPARED); 1855 } 1856 1857 mPrepareResult = OK; 1858 mFlags &= ~(PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED); 1859 mFlags |= PREPARED; 1860 mAsyncPrepareEvent = NULL; 1861 mPreparedCondition.broadcast(); 1862} 1863 1864uint32_t AwesomePlayer::flags() const { 1865 return mExtractorFlags; 1866} 1867 1868void AwesomePlayer::postAudioEOS(int64_t delayUs) { 1869 postCheckAudioStatusEvent_l(delayUs); 1870} 1871 1872void AwesomePlayer::postAudioSeekComplete() { 1873 postCheckAudioStatusEvent_l(0 /* delayUs */); 1874} 1875 1876} // namespace android 1877