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