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