AwesomePlayer.cpp revision f1958f9442bc937e1f8c8d9175901500b944b021
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 } else if (mConnectingRTSPController != NULL) { 403 LOGI("interrupting the connection process"); 404 mConnectingRTSPController->disconnect(); 405 } 406 407 if (mFlags & PREPARING_CONNECTED) { 408 // We are basically done preparing, we're just buffering 409 // enough data to start playback, we can safely interrupt that. 410 finishAsyncPrepare_l(); 411 } 412 } 413 414 if (mFlags & PREPARING) { 415 LOGI("waiting until preparation is completed."); 416 } 417 418 while (mFlags & PREPARING) { 419 mPreparedCondition.wait(mLock); 420 } 421 422 cancelPlayerEvents(); 423 424 mCachedSource.clear(); 425 mAudioTrack.clear(); 426 mVideoTrack.clear(); 427 428 // Shutdown audio first, so that the respone to the reset request 429 // appears to happen instantaneously as far as the user is concerned 430 // If we did this later, audio would continue playing while we 431 // shutdown the video-related resources and the player appear to 432 // not be as responsive to a reset request. 433 if (mAudioPlayer == NULL && mAudioSource != NULL) { 434 // If we had an audio player, it would have effectively 435 // taken possession of the audio source and stopped it when 436 // _it_ is stopped. Otherwise this is still our responsibility. 437 mAudioSource->stop(); 438 } 439 mAudioSource.clear(); 440 441 LOGI("audio source cleared"); 442 443 mTimeSource = NULL; 444 445 delete mAudioPlayer; 446 mAudioPlayer = NULL; 447 448 mVideoRenderer.clear(); 449 450 if (mVideoBuffer) { 451 mVideoBuffer->release(); 452 mVideoBuffer = NULL; 453 } 454 455 if (mRTSPController != NULL) { 456 mRTSPController->disconnect(); 457 mRTSPController.clear(); 458 } 459 460 if (mLiveSession != NULL) { 461 mLiveSession->disconnect(); 462 mLiveSession.clear(); 463 } 464 465 if (mVideoSource != NULL) { 466 mVideoSource->stop(); 467 468 // The following hack is necessary to ensure that the OMX 469 // component is completely released by the time we may try 470 // to instantiate it again. 471 wp<MediaSource> tmp = mVideoSource; 472 mVideoSource.clear(); 473 while (tmp.promote() != NULL) { 474 usleep(1000); 475 } 476 IPCThreadState::self()->flushCommands(); 477 } 478 479 LOGI("video source cleared"); 480 481 mDurationUs = -1; 482 mFlags = 0; 483 mExtractorFlags = 0; 484 mTimeSourceDeltaUs = 0; 485 mVideoTimeUs = 0; 486 487 mSeeking = false; 488 mSeekNotificationSent = false; 489 mSeekTimeUs = 0; 490 491 mUri.setTo(""); 492 mUriHeaders.clear(); 493 494 mFileSource.clear(); 495 496 mBitrate = -1; 497 498 LOGI("reset_l completed"); 499} 500 501void AwesomePlayer::notifyListener_l(int msg, int ext1, int ext2) { 502 if (mListener != NULL) { 503 sp<MediaPlayerBase> listener = mListener.promote(); 504 505 if (listener != NULL) { 506 listener->sendEvent(msg, ext1, ext2); 507 } 508 } 509} 510 511bool AwesomePlayer::getBitrate(int64_t *bitrate) { 512 off64_t size; 513 if (mDurationUs >= 0 && mCachedSource != NULL 514 && mCachedSource->getSize(&size) == OK) { 515 *bitrate = size * 8000000ll / mDurationUs; // in bits/sec 516 return true; 517 } 518 519 if (mBitrate >= 0) { 520 *bitrate = mBitrate; 521 return true; 522 } 523 524 *bitrate = 0; 525 526 return false; 527} 528 529// Returns true iff cached duration is available/applicable. 530bool AwesomePlayer::getCachedDuration_l(int64_t *durationUs, bool *eos) { 531 int64_t bitrate; 532 533 if (mRTSPController != NULL) { 534 *durationUs = mRTSPController->getQueueDurationUs(eos); 535 return true; 536 } else if (mCachedSource != NULL && getBitrate(&bitrate)) { 537 status_t finalStatus; 538 size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus); 539 *durationUs = cachedDataRemaining * 8000000ll / bitrate; 540 *eos = (finalStatus != OK); 541 return true; 542 } 543 544 return false; 545} 546 547void AwesomePlayer::ensureCacheIsFetching_l() { 548 if (mCachedSource != NULL) { 549 mCachedSource->resumeFetchingIfNecessary(); 550 } 551} 552 553void AwesomePlayer::onVideoLagUpdate() { 554 Mutex::Autolock autoLock(mLock); 555 if (!mVideoLagEventPending) { 556 return; 557 } 558 mVideoLagEventPending = false; 559 560 int64_t audioTimeUs = mAudioPlayer->getMediaTimeUs(); 561 int64_t videoLateByUs = audioTimeUs - mVideoTimeUs; 562 563 if (videoLateByUs > 300000ll) { 564 LOGV("video late by %lld ms.", videoLateByUs / 1000ll); 565 566 notifyListener_l( 567 MEDIA_INFO, 568 MEDIA_INFO_VIDEO_TRACK_LAGGING, 569 videoLateByUs / 1000ll); 570 } 571 572 postVideoLagEvent_l(); 573} 574 575void AwesomePlayer::onBufferingUpdate() { 576 Mutex::Autolock autoLock(mLock); 577 if (!mBufferingEventPending) { 578 return; 579 } 580 mBufferingEventPending = false; 581 582 if (mCachedSource != NULL) { 583 status_t finalStatus; 584 size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus); 585 bool eos = (finalStatus != OK); 586 587 if (eos) { 588 if (finalStatus == ERROR_END_OF_STREAM) { 589 notifyListener_l(MEDIA_BUFFERING_UPDATE, 100); 590 } 591 if (mFlags & PREPARING) { 592 LOGV("cache has reached EOS, prepare is done."); 593 finishAsyncPrepare_l(); 594 } 595 } else { 596 int64_t bitrate; 597 if (getBitrate(&bitrate)) { 598 size_t cachedSize = mCachedSource->cachedSize(); 599 int64_t cachedDurationUs = cachedSize * 8000000ll / bitrate; 600 601 int percentage = 100.0 * (double)cachedDurationUs / mDurationUs; 602 if (percentage > 100) { 603 percentage = 100; 604 } 605 606 notifyListener_l(MEDIA_BUFFERING_UPDATE, percentage); 607 } else { 608 // We don't know the bitrate of the stream, use absolute size 609 // limits to maintain the cache. 610 611 if ((mFlags & PLAYING) && !eos 612 && (cachedDataRemaining < kLowWaterMarkBytes)) { 613 LOGI("cache is running low (< %d) , pausing.", 614 kLowWaterMarkBytes); 615 mFlags |= CACHE_UNDERRUN; 616 pause_l(); 617 ensureCacheIsFetching_l(); 618 notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START); 619 } else if (eos || cachedDataRemaining > kHighWaterMarkBytes) { 620 if (mFlags & CACHE_UNDERRUN) { 621 LOGI("cache has filled up (> %d), resuming.", 622 kHighWaterMarkBytes); 623 mFlags &= ~CACHE_UNDERRUN; 624 play_l(); 625 notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_END); 626 } else if (mFlags & PREPARING) { 627 LOGV("cache has filled up (> %d), prepare is done", 628 kHighWaterMarkBytes); 629 finishAsyncPrepare_l(); 630 } 631 } 632 } 633 } 634 } 635 636 int64_t cachedDurationUs; 637 bool eos; 638 if (getCachedDuration_l(&cachedDurationUs, &eos)) { 639 LOGV("cachedDurationUs = %.2f secs, eos=%d", 640 cachedDurationUs / 1E6, eos); 641 642 int64_t highWaterMarkUs = 643 (mRTSPController != NULL) ? kHighWaterMarkRTSPUs : kHighWaterMarkUs; 644 645 if ((mFlags & PLAYING) && !eos 646 && (cachedDurationUs < kLowWaterMarkUs)) { 647 LOGI("cache is running low (%.2f secs) , pausing.", 648 cachedDurationUs / 1E6); 649 mFlags |= CACHE_UNDERRUN; 650 pause_l(); 651 ensureCacheIsFetching_l(); 652 notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START); 653 } else if (eos || cachedDurationUs > highWaterMarkUs) { 654 if (mFlags & CACHE_UNDERRUN) { 655 LOGI("cache has filled up (%.2f secs), resuming.", 656 cachedDurationUs / 1E6); 657 mFlags &= ~CACHE_UNDERRUN; 658 play_l(); 659 notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_END); 660 } else if (mFlags & PREPARING) { 661 LOGV("cache has filled up (%.2f secs), prepare is done", 662 cachedDurationUs / 1E6); 663 finishAsyncPrepare_l(); 664 } 665 } 666 } 667 668 postBufferingEvent_l(); 669} 670 671void AwesomePlayer::partial_reset_l() { 672 // Only reset the video renderer and shut down the video decoder. 673 // Then instantiate a new video decoder and resume video playback. 674 675 mVideoRenderer.clear(); 676 677 if (mVideoBuffer) { 678 mVideoBuffer->release(); 679 mVideoBuffer = NULL; 680 } 681 682 { 683 mVideoSource->stop(); 684 685 // The following hack is necessary to ensure that the OMX 686 // component is completely released by the time we may try 687 // to instantiate it again. 688 wp<MediaSource> tmp = mVideoSource; 689 mVideoSource.clear(); 690 while (tmp.promote() != NULL) { 691 usleep(1000); 692 } 693 IPCThreadState::self()->flushCommands(); 694 } 695 696 CHECK_EQ((status_t)OK, 697 initVideoDecoder(OMXCodec::kIgnoreCodecSpecificData)); 698} 699 700void AwesomePlayer::onStreamDone() { 701 // Posted whenever any stream finishes playing. 702 703 Mutex::Autolock autoLock(mLock); 704 if (!mStreamDoneEventPending) { 705 return; 706 } 707 mStreamDoneEventPending = false; 708 709 if (mStreamDoneStatus == INFO_DISCONTINUITY) { 710 // This special status is returned because an http live stream's 711 // video stream switched to a different bandwidth at this point 712 // and future data may have been encoded using different parameters. 713 // This requires us to shutdown the video decoder and reinstantiate 714 // a fresh one. 715 716 LOGV("INFO_DISCONTINUITY"); 717 718 CHECK(mVideoSource != NULL); 719 720 partial_reset_l(); 721 postVideoEvent_l(); 722 return; 723 } else if (mStreamDoneStatus != ERROR_END_OF_STREAM) { 724 LOGV("MEDIA_ERROR %d", mStreamDoneStatus); 725 726 notifyListener_l( 727 MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, mStreamDoneStatus); 728 729 pause_l(true /* at eos */); 730 731 mFlags |= AT_EOS; 732 return; 733 } 734 735 const bool allDone = 736 (mVideoSource == NULL || (mFlags & VIDEO_AT_EOS)) 737 && (mAudioSource == NULL || (mFlags & AUDIO_AT_EOS)); 738 739 if (!allDone) { 740 return; 741 } 742 743 if (mFlags & (LOOPING | AUTO_LOOPING)) { 744 seekTo_l(0); 745 746 if (mVideoSource != NULL) { 747 postVideoEvent_l(); 748 } 749 } else { 750 LOGV("MEDIA_PLAYBACK_COMPLETE"); 751 notifyListener_l(MEDIA_PLAYBACK_COMPLETE); 752 753 pause_l(true /* at eos */); 754 755 mFlags |= AT_EOS; 756 } 757} 758 759status_t AwesomePlayer::play() { 760 Mutex::Autolock autoLock(mLock); 761 762 mFlags &= ~CACHE_UNDERRUN; 763 764 return play_l(); 765} 766 767status_t AwesomePlayer::play_l() { 768 mFlags &= ~SEEK_PREVIEW; 769 770 if (mFlags & PLAYING) { 771 return OK; 772 } 773 774 if (!(mFlags & PREPARED)) { 775 status_t err = prepare_l(); 776 777 if (err != OK) { 778 return err; 779 } 780 } 781 782 mFlags |= PLAYING; 783 mFlags |= FIRST_FRAME; 784 785 bool deferredAudioSeek = false; 786 787 if (mDecryptHandle != NULL) { 788 int64_t position; 789 getPosition(&position); 790 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 791 Playback::START, position / 1000); 792 } 793 794 if (mAudioSource != NULL) { 795 if (mAudioPlayer == NULL) { 796 if (mAudioSink != NULL) { 797 mAudioPlayer = new AudioPlayer(mAudioSink, this); 798 mAudioPlayer->setSource(mAudioSource); 799 800 mTimeSource = mAudioPlayer; 801 802 deferredAudioSeek = true; 803 804 mWatchForAudioSeekComplete = false; 805 mWatchForAudioEOS = true; 806 } 807 } 808 809 CHECK(!(mFlags & AUDIO_RUNNING)); 810 811 if (mVideoSource == NULL) { 812 status_t err = startAudioPlayer_l(); 813 814 if (err != OK) { 815 delete mAudioPlayer; 816 mAudioPlayer = NULL; 817 818 mFlags &= ~(PLAYING | FIRST_FRAME); 819 820 if (mDecryptHandle != NULL) { 821 mDrmManagerClient->setPlaybackStatus( 822 mDecryptHandle, Playback::STOP, 0); 823 } 824 825 return err; 826 } 827 } 828 } 829 830 if (mTimeSource == NULL && mAudioPlayer == NULL) { 831 mTimeSource = &mSystemTimeSource; 832 } 833 834 if (mVideoSource != NULL) { 835 // Kick off video playback 836 postVideoEvent_l(); 837 838 if (mAudioSource != NULL && mVideoSource != NULL) { 839 postVideoLagEvent_l(); 840 } 841 } 842 843 if (deferredAudioSeek) { 844 // If there was a seek request while we were paused 845 // and we're just starting up again, honor the request now. 846 seekAudioIfNecessary_l(); 847 } 848 849 if (mFlags & AT_EOS) { 850 // Legacy behaviour, if a stream finishes playing and then 851 // is started again, we play from the start... 852 seekTo_l(0); 853 } 854 855 return OK; 856} 857 858status_t AwesomePlayer::startAudioPlayer_l() { 859 CHECK(!(mFlags & AUDIO_RUNNING)); 860 861 if (mAudioSource == NULL || mAudioPlayer == NULL) { 862 return OK; 863 } 864 865 if (!(mFlags & AUDIOPLAYER_STARTED)) { 866 mFlags |= AUDIOPLAYER_STARTED; 867 868 // We've already started the MediaSource in order to enable 869 // the prefetcher to read its data. 870 status_t err = mAudioPlayer->start( 871 true /* sourceAlreadyStarted */); 872 873 if (err != OK) { 874 notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err); 875 return err; 876 } 877 } else { 878 mAudioPlayer->resume(); 879 } 880 881 mFlags |= AUDIO_RUNNING; 882 883 mWatchForAudioEOS = true; 884 885 return OK; 886} 887 888void AwesomePlayer::notifyVideoSize_l() { 889 sp<MetaData> meta = mVideoSource->getFormat(); 890 891 int32_t cropLeft, cropTop, cropRight, cropBottom; 892 if (!meta->findRect( 893 kKeyCropRect, &cropLeft, &cropTop, &cropRight, &cropBottom)) { 894 int32_t width, height; 895 CHECK(meta->findInt32(kKeyWidth, &width)); 896 CHECK(meta->findInt32(kKeyHeight, &height)); 897 898 cropLeft = cropTop = 0; 899 cropRight = width - 1; 900 cropBottom = height - 1; 901 902 LOGV("got dimensions only %d x %d", width, height); 903 } else { 904 LOGV("got crop rect %d, %d, %d, %d", 905 cropLeft, cropTop, cropRight, cropBottom); 906 } 907 908 int32_t usableWidth = cropRight - cropLeft + 1; 909 int32_t usableHeight = cropBottom - cropTop + 1; 910 if (mDisplayWidth != 0) { 911 usableWidth = mDisplayWidth; 912 } 913 if (mDisplayHeight != 0) { 914 usableHeight = mDisplayHeight; 915 } 916 917 int32_t rotationDegrees; 918 if (!mVideoTrack->getFormat()->findInt32( 919 kKeyRotation, &rotationDegrees)) { 920 rotationDegrees = 0; 921 } 922 923 if (rotationDegrees == 90 || rotationDegrees == 270) { 924 notifyListener_l( 925 MEDIA_SET_VIDEO_SIZE, usableHeight, usableWidth); 926 } else { 927 notifyListener_l( 928 MEDIA_SET_VIDEO_SIZE, usableWidth, usableHeight); 929 } 930} 931 932void AwesomePlayer::initRenderer_l() { 933 if (mSurface == NULL) { 934 return; 935 } 936 937 sp<MetaData> meta = mVideoSource->getFormat(); 938 939 int32_t format; 940 const char *component; 941 int32_t decodedWidth, decodedHeight; 942 CHECK(meta->findInt32(kKeyColorFormat, &format)); 943 CHECK(meta->findCString(kKeyDecoderComponent, &component)); 944 CHECK(meta->findInt32(kKeyWidth, &decodedWidth)); 945 CHECK(meta->findInt32(kKeyHeight, &decodedHeight)); 946 947 int32_t rotationDegrees; 948 if (!mVideoTrack->getFormat()->findInt32( 949 kKeyRotation, &rotationDegrees)) { 950 rotationDegrees = 0; 951 } 952 953 mVideoRenderer.clear(); 954 955 // Must ensure that mVideoRenderer's destructor is actually executed 956 // before creating a new one. 957 IPCThreadState::self()->flushCommands(); 958 959 if (USE_SURFACE_ALLOC && strncmp(component, "OMX.", 4) == 0) { 960 // Hardware decoders avoid the CPU color conversion by decoding 961 // directly to ANativeBuffers, so we must use a renderer that 962 // just pushes those buffers to the ANativeWindow. 963 mVideoRenderer = 964 new AwesomeNativeWindowRenderer(mSurface, rotationDegrees); 965 } else { 966 // Other decoders are instantiated locally and as a consequence 967 // allocate their buffers in local address space. This renderer 968 // then performs a color conversion and copy to get the data 969 // into the ANativeBuffer. 970 mVideoRenderer = new AwesomeLocalRenderer(mSurface, meta); 971 } 972} 973 974status_t AwesomePlayer::pause() { 975 Mutex::Autolock autoLock(mLock); 976 977 mFlags &= ~CACHE_UNDERRUN; 978 979 return pause_l(); 980} 981 982status_t AwesomePlayer::pause_l(bool at_eos) { 983 if (!(mFlags & PLAYING)) { 984 return OK; 985 } 986 987 cancelPlayerEvents(true /* keepBufferingGoing */); 988 989 if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) { 990 if (at_eos) { 991 // If we played the audio stream to completion we 992 // want to make sure that all samples remaining in the audio 993 // track's queue are played out. 994 mAudioPlayer->pause(true /* playPendingSamples */); 995 } else { 996 mAudioPlayer->pause(); 997 } 998 999 mFlags &= ~AUDIO_RUNNING; 1000 } 1001 1002 mFlags &= ~PLAYING; 1003 1004 if (mDecryptHandle != NULL) { 1005 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1006 Playback::PAUSE, 0); 1007 } 1008 1009 return OK; 1010} 1011 1012bool AwesomePlayer::isPlaying() const { 1013 return (mFlags & PLAYING) || (mFlags & CACHE_UNDERRUN); 1014} 1015 1016void AwesomePlayer::setSurface(const sp<Surface> &surface) { 1017 Mutex::Autolock autoLock(mLock); 1018 1019 mSurface = surface; 1020} 1021 1022void AwesomePlayer::setAudioSink( 1023 const sp<MediaPlayerBase::AudioSink> &audioSink) { 1024 Mutex::Autolock autoLock(mLock); 1025 1026 mAudioSink = audioSink; 1027} 1028 1029status_t AwesomePlayer::setLooping(bool shouldLoop) { 1030 Mutex::Autolock autoLock(mLock); 1031 1032 mFlags = mFlags & ~LOOPING; 1033 1034 if (shouldLoop) { 1035 mFlags |= LOOPING; 1036 } 1037 1038 return OK; 1039} 1040 1041status_t AwesomePlayer::getDuration(int64_t *durationUs) { 1042 Mutex::Autolock autoLock(mMiscStateLock); 1043 1044 if (mDurationUs < 0) { 1045 return UNKNOWN_ERROR; 1046 } 1047 1048 *durationUs = mDurationUs; 1049 1050 return OK; 1051} 1052 1053status_t AwesomePlayer::getPosition(int64_t *positionUs) { 1054 if (mRTSPController != NULL) { 1055 *positionUs = mRTSPController->getNormalPlayTimeUs(); 1056 } 1057 else if (mSeeking) { 1058 *positionUs = mSeekTimeUs; 1059 } else if (mVideoSource != NULL) { 1060 Mutex::Autolock autoLock(mMiscStateLock); 1061 *positionUs = mVideoTimeUs; 1062 } else if (mAudioPlayer != NULL) { 1063 *positionUs = mAudioPlayer->getMediaTimeUs(); 1064 } else { 1065 *positionUs = 0; 1066 } 1067 1068 return OK; 1069} 1070 1071status_t AwesomePlayer::seekTo(int64_t timeUs) { 1072 if (mExtractorFlags & MediaExtractor::CAN_SEEK) { 1073 Mutex::Autolock autoLock(mLock); 1074 return seekTo_l(timeUs); 1075 } 1076 1077 return OK; 1078} 1079 1080// static 1081void AwesomePlayer::OnRTSPSeekDoneWrapper(void *cookie) { 1082 static_cast<AwesomePlayer *>(cookie)->onRTSPSeekDone(); 1083} 1084 1085void AwesomePlayer::onRTSPSeekDone() { 1086 notifyListener_l(MEDIA_SEEK_COMPLETE); 1087 mSeekNotificationSent = true; 1088} 1089 1090status_t AwesomePlayer::seekTo_l(int64_t timeUs) { 1091 if (mRTSPController != NULL) { 1092 mRTSPController->seekAsync(timeUs, OnRTSPSeekDoneWrapper, this); 1093 return OK; 1094 } 1095 1096 if (mFlags & CACHE_UNDERRUN) { 1097 mFlags &= ~CACHE_UNDERRUN; 1098 play_l(); 1099 } 1100 1101 mSeeking = true; 1102 mSeekNotificationSent = false; 1103 mSeekTimeUs = timeUs; 1104 mFlags &= ~(AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS); 1105 1106 seekAudioIfNecessary_l(); 1107 1108 if (!(mFlags & PLAYING)) { 1109 LOGV("seeking while paused, sending SEEK_COMPLETE notification" 1110 " immediately."); 1111 1112 notifyListener_l(MEDIA_SEEK_COMPLETE); 1113 mSeekNotificationSent = true; 1114 1115 if ((mFlags & PREPARED) && mVideoSource != NULL) { 1116 mFlags |= SEEK_PREVIEW; 1117 postVideoEvent_l(); 1118 } 1119 } 1120 1121 return OK; 1122} 1123 1124void AwesomePlayer::seekAudioIfNecessary_l() { 1125 if (mSeeking && mVideoSource == NULL && mAudioPlayer != NULL) { 1126 mAudioPlayer->seekTo(mSeekTimeUs); 1127 1128 mWatchForAudioSeekComplete = true; 1129 mWatchForAudioEOS = true; 1130 mSeekNotificationSent = false; 1131 1132 if (mDecryptHandle != NULL) { 1133 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1134 Playback::PAUSE, 0); 1135 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1136 Playback::START, mSeekTimeUs / 1000); 1137 } 1138 } 1139} 1140 1141void AwesomePlayer::setAudioSource(sp<MediaSource> source) { 1142 CHECK(source != NULL); 1143 1144 mAudioTrack = source; 1145} 1146 1147status_t AwesomePlayer::initAudioDecoder() { 1148 sp<MetaData> meta = mAudioTrack->getFormat(); 1149 1150 const char *mime; 1151 CHECK(meta->findCString(kKeyMIMEType, &mime)); 1152 1153 if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_RAW)) { 1154 mAudioSource = mAudioTrack; 1155 } else { 1156 mAudioSource = OMXCodec::Create( 1157 mClient.interface(), mAudioTrack->getFormat(), 1158 false, // createEncoder 1159 mAudioTrack); 1160 } 1161 1162 if (mAudioSource != NULL) { 1163 int64_t durationUs; 1164 if (mAudioTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) { 1165 Mutex::Autolock autoLock(mMiscStateLock); 1166 if (mDurationUs < 0 || durationUs > mDurationUs) { 1167 mDurationUs = durationUs; 1168 } 1169 } 1170 1171 status_t err = mAudioSource->start(); 1172 1173 if (err != OK) { 1174 mAudioSource.clear(); 1175 return err; 1176 } 1177 } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_QCELP)) { 1178 // For legacy reasons we're simply going to ignore the absence 1179 // of an audio decoder for QCELP instead of aborting playback 1180 // altogether. 1181 return OK; 1182 } 1183 1184 return mAudioSource != NULL ? OK : UNKNOWN_ERROR; 1185} 1186 1187void AwesomePlayer::setVideoSource(sp<MediaSource> source) { 1188 CHECK(source != NULL); 1189 1190 mVideoTrack = source; 1191} 1192 1193status_t AwesomePlayer::initVideoDecoder(uint32_t flags) { 1194 mVideoSource = OMXCodec::Create( 1195 mClient.interface(), mVideoTrack->getFormat(), 1196 false, // createEncoder 1197 mVideoTrack, 1198 NULL, flags, USE_SURFACE_ALLOC ? mSurface : NULL); 1199 1200 if (mVideoSource != NULL) { 1201 int64_t durationUs; 1202 if (mVideoTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) { 1203 Mutex::Autolock autoLock(mMiscStateLock); 1204 if (mDurationUs < 0 || durationUs > mDurationUs) { 1205 mDurationUs = durationUs; 1206 } 1207 } 1208 1209 status_t err = mVideoSource->start(); 1210 1211 if (err != OK) { 1212 mVideoSource.clear(); 1213 return err; 1214 } 1215 } 1216 1217 return mVideoSource != NULL ? OK : UNKNOWN_ERROR; 1218} 1219 1220void AwesomePlayer::finishSeekIfNecessary(int64_t videoTimeUs) { 1221 if (!mSeeking || (mFlags & SEEK_PREVIEW)) { 1222 return; 1223 } 1224 1225 if (mAudioPlayer != NULL) { 1226 LOGV("seeking audio to %lld us (%.2f secs).", videoTimeUs, videoTimeUs / 1E6); 1227 1228 // If we don't have a video time, seek audio to the originally 1229 // requested seek time instead. 1230 1231 mAudioPlayer->seekTo(videoTimeUs < 0 ? mSeekTimeUs : videoTimeUs); 1232 mWatchForAudioSeekComplete = true; 1233 } else if (!mSeekNotificationSent) { 1234 // If we're playing video only, report seek complete now, 1235 // otherwise audio player will notify us later. 1236 notifyListener_l(MEDIA_SEEK_COMPLETE); 1237 } 1238 1239 mFlags |= FIRST_FRAME; 1240 mSeeking = false; 1241 mSeekNotificationSent = false; 1242 1243 if (mDecryptHandle != NULL) { 1244 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1245 Playback::PAUSE, 0); 1246 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1247 Playback::START, videoTimeUs / 1000); 1248 } 1249} 1250 1251void AwesomePlayer::onVideoEvent() { 1252 Mutex::Autolock autoLock(mLock); 1253 if (!mVideoEventPending) { 1254 // The event has been cancelled in reset_l() but had already 1255 // been scheduled for execution at that time. 1256 return; 1257 } 1258 mVideoEventPending = false; 1259 1260 if (mSeeking) { 1261 if (mVideoBuffer) { 1262 mVideoBuffer->release(); 1263 mVideoBuffer = NULL; 1264 } 1265 1266 if (mCachedSource != NULL && mAudioSource != NULL 1267 && !(mFlags & SEEK_PREVIEW)) { 1268 // We're going to seek the video source first, followed by 1269 // the audio source. 1270 // In order to avoid jumps in the DataSource offset caused by 1271 // the audio codec prefetching data from the old locations 1272 // while the video codec is already reading data from the new 1273 // locations, we'll "pause" the audio source, causing it to 1274 // stop reading input data until a subsequent seek. 1275 1276 if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) { 1277 mAudioPlayer->pause(); 1278 1279 mFlags &= ~AUDIO_RUNNING; 1280 } 1281 mAudioSource->pause(); 1282 } 1283 } 1284 1285 if (!mVideoBuffer) { 1286 MediaSource::ReadOptions options; 1287 if (mSeeking) { 1288 LOGV("seeking to %lld us (%.2f secs)", mSeekTimeUs, mSeekTimeUs / 1E6); 1289 1290 options.setSeekTo( 1291 mSeekTimeUs, MediaSource::ReadOptions::SEEK_CLOSEST_SYNC); 1292 } 1293 for (;;) { 1294 status_t err = mVideoSource->read(&mVideoBuffer, &options); 1295 options.clearSeekTo(); 1296 1297 if (err != OK) { 1298 CHECK(mVideoBuffer == NULL); 1299 1300 if (err == INFO_FORMAT_CHANGED) { 1301 LOGV("VideoSource signalled format change."); 1302 1303 notifyVideoSize_l(); 1304 1305 if (mVideoRenderer != NULL) { 1306 mVideoRendererIsPreview = false; 1307 initRenderer_l(); 1308 } 1309 continue; 1310 } 1311 1312 // So video playback is complete, but we may still have 1313 // a seek request pending that needs to be applied 1314 // to the audio track. 1315 if (mSeeking) { 1316 LOGV("video stream ended while seeking!"); 1317 } 1318 finishSeekIfNecessary(-1); 1319 1320 mFlags |= VIDEO_AT_EOS; 1321 postStreamDoneEvent_l(err); 1322 return; 1323 } 1324 1325 if (mVideoBuffer->range_length() == 0) { 1326 // Some decoders, notably the PV AVC software decoder 1327 // return spurious empty buffers that we just want to ignore. 1328 1329 mVideoBuffer->release(); 1330 mVideoBuffer = NULL; 1331 continue; 1332 } 1333 1334 break; 1335 } 1336 } 1337 1338 int64_t timeUs; 1339 CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &timeUs)); 1340 1341 { 1342 Mutex::Autolock autoLock(mMiscStateLock); 1343 mVideoTimeUs = timeUs; 1344 } 1345 1346 bool wasSeeking = mSeeking; 1347 finishSeekIfNecessary(timeUs); 1348 1349 if (mAudioPlayer != NULL && !(mFlags & (AUDIO_RUNNING | SEEK_PREVIEW))) { 1350 status_t err = startAudioPlayer_l(); 1351 if (err != OK) { 1352 LOGE("Startung the audio player failed w/ err %d", err); 1353 return; 1354 } 1355 } 1356 1357 TimeSource *ts = (mFlags & AUDIO_AT_EOS) ? &mSystemTimeSource : mTimeSource; 1358 1359 if (mFlags & FIRST_FRAME) { 1360 mFlags &= ~FIRST_FRAME; 1361 mSinceLastDropped = 0; 1362 mTimeSourceDeltaUs = ts->getRealTimeUs() - timeUs; 1363 } 1364 1365 int64_t realTimeUs, mediaTimeUs; 1366 if (!(mFlags & AUDIO_AT_EOS) && mAudioPlayer != NULL 1367 && mAudioPlayer->getMediaTimeMapping(&realTimeUs, &mediaTimeUs)) { 1368 mTimeSourceDeltaUs = realTimeUs - mediaTimeUs; 1369 } 1370 1371 if (!wasSeeking) { 1372 // Let's display the first frame after seeking right away. 1373 1374 int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs; 1375 1376 int64_t latenessUs = nowUs - timeUs; 1377 1378 if (latenessUs > 40000) { 1379 // We're more than 40ms late. 1380 LOGV("we're late by %lld us (%.2f secs)", latenessUs, latenessUs / 1E6); 1381 if ( mSinceLastDropped > FRAME_DROP_FREQ) 1382 { 1383 LOGV("we're late by %lld us (%.2f secs) dropping one after %d frames", latenessUs, latenessUs / 1E6, mSinceLastDropped); 1384 mSinceLastDropped = 0; 1385 mVideoBuffer->release(); 1386 mVideoBuffer = NULL; 1387 1388 postVideoEvent_l(); 1389 return; 1390 } 1391 } 1392 1393 if (latenessUs < -10000) { 1394 // We're more than 10ms early. 1395 1396 postVideoEvent_l(10000); 1397 return; 1398 } 1399 } 1400 1401 if (mVideoRendererIsPreview || mVideoRenderer == NULL) { 1402 mVideoRendererIsPreview = false; 1403 1404 initRenderer_l(); 1405 } 1406 1407 if (mVideoRenderer != NULL) { 1408 mSinceLastDropped++; 1409 mVideoRenderer->render(mVideoBuffer); 1410 } 1411 1412 mVideoBuffer->release(); 1413 mVideoBuffer = NULL; 1414 1415 if (wasSeeking && (mFlags & SEEK_PREVIEW)) { 1416 mFlags &= ~SEEK_PREVIEW; 1417 return; 1418 } 1419 1420 postVideoEvent_l(); 1421} 1422 1423void AwesomePlayer::postVideoEvent_l(int64_t delayUs) { 1424 if (mVideoEventPending) { 1425 return; 1426 } 1427 1428 mVideoEventPending = true; 1429 mQueue.postEventWithDelay(mVideoEvent, delayUs < 0 ? 10000 : delayUs); 1430} 1431 1432void AwesomePlayer::postStreamDoneEvent_l(status_t status) { 1433 if (mStreamDoneEventPending) { 1434 return; 1435 } 1436 mStreamDoneEventPending = true; 1437 1438 mStreamDoneStatus = status; 1439 mQueue.postEvent(mStreamDoneEvent); 1440} 1441 1442void AwesomePlayer::postBufferingEvent_l() { 1443 if (mBufferingEventPending) { 1444 return; 1445 } 1446 mBufferingEventPending = true; 1447 mQueue.postEventWithDelay(mBufferingEvent, 1000000ll); 1448} 1449 1450void AwesomePlayer::postVideoLagEvent_l() { 1451 if (mVideoLagEventPending) { 1452 return; 1453 } 1454 mVideoLagEventPending = true; 1455 mQueue.postEventWithDelay(mVideoLagEvent, 1000000ll); 1456} 1457 1458void AwesomePlayer::postCheckAudioStatusEvent_l() { 1459 if (mAudioStatusEventPending) { 1460 return; 1461 } 1462 mAudioStatusEventPending = true; 1463 mQueue.postEvent(mCheckAudioStatusEvent); 1464} 1465 1466void AwesomePlayer::onCheckAudioStatus() { 1467 Mutex::Autolock autoLock(mLock); 1468 if (!mAudioStatusEventPending) { 1469 // Event was dispatched and while we were blocking on the mutex, 1470 // has already been cancelled. 1471 return; 1472 } 1473 1474 mAudioStatusEventPending = false; 1475 1476 if (mWatchForAudioSeekComplete && !mAudioPlayer->isSeeking()) { 1477 mWatchForAudioSeekComplete = false; 1478 1479 if (!mSeekNotificationSent) { 1480 notifyListener_l(MEDIA_SEEK_COMPLETE); 1481 mSeekNotificationSent = true; 1482 } 1483 1484 mSeeking = false; 1485 } 1486 1487 status_t finalStatus; 1488 if (mWatchForAudioEOS && mAudioPlayer->reachedEOS(&finalStatus)) { 1489 mWatchForAudioEOS = false; 1490 mFlags |= AUDIO_AT_EOS; 1491 mFlags |= FIRST_FRAME; 1492 postStreamDoneEvent_l(finalStatus); 1493 } 1494} 1495 1496status_t AwesomePlayer::prepare() { 1497 Mutex::Autolock autoLock(mLock); 1498 return prepare_l(); 1499} 1500 1501status_t AwesomePlayer::prepare_l() { 1502 if (mFlags & PREPARED) { 1503 return OK; 1504 } 1505 1506 if (mFlags & PREPARING) { 1507 return UNKNOWN_ERROR; 1508 } 1509 1510 mIsAsyncPrepare = false; 1511 status_t err = prepareAsync_l(); 1512 1513 if (err != OK) { 1514 return err; 1515 } 1516 1517 while (mFlags & PREPARING) { 1518 mPreparedCondition.wait(mLock); 1519 } 1520 1521 return mPrepareResult; 1522} 1523 1524status_t AwesomePlayer::prepareAsync() { 1525 Mutex::Autolock autoLock(mLock); 1526 1527 if (mFlags & PREPARING) { 1528 return UNKNOWN_ERROR; // async prepare already pending 1529 } 1530 1531 mIsAsyncPrepare = true; 1532 return prepareAsync_l(); 1533} 1534 1535status_t AwesomePlayer::prepareAsync_l() { 1536 if (mFlags & PREPARING) { 1537 return UNKNOWN_ERROR; // async prepare already pending 1538 } 1539 1540 if (!mQueueStarted) { 1541 mQueue.start(); 1542 mQueueStarted = true; 1543 } 1544 1545 mFlags |= PREPARING; 1546 mAsyncPrepareEvent = new AwesomeEvent( 1547 this, &AwesomePlayer::onPrepareAsyncEvent); 1548 1549 mQueue.postEvent(mAsyncPrepareEvent); 1550 1551 return OK; 1552} 1553 1554status_t AwesomePlayer::finishSetDataSource_l() { 1555 sp<DataSource> dataSource; 1556 1557 if (!strncasecmp("http://", mUri.string(), 7)) { 1558 mConnectingDataSource = new NuHTTPDataSource; 1559 1560 mLock.unlock(); 1561 status_t err = mConnectingDataSource->connect(mUri, &mUriHeaders); 1562 mLock.lock(); 1563 1564 if (err != OK) { 1565 mConnectingDataSource.clear(); 1566 1567 LOGI("mConnectingDataSource->connect() returned %d", err); 1568 return err; 1569 } 1570 1571#if 0 1572 mCachedSource = new NuCachedSource2( 1573 new ThrottledSource( 1574 mConnectingDataSource, 50 * 1024 /* bytes/sec */)); 1575#else 1576 mCachedSource = new NuCachedSource2(mConnectingDataSource); 1577#endif 1578 mConnectingDataSource.clear(); 1579 1580 dataSource = mCachedSource; 1581 1582 // We're going to prefill the cache before trying to instantiate 1583 // the extractor below, as the latter is an operation that otherwise 1584 // could block on the datasource for a significant amount of time. 1585 // During that time we'd be unable to abort the preparation phase 1586 // without this prefill. 1587 1588 mLock.unlock(); 1589 1590 for (;;) { 1591 status_t finalStatus; 1592 size_t cachedDataRemaining = 1593 mCachedSource->approxDataRemaining(&finalStatus); 1594 1595 if (finalStatus != OK || cachedDataRemaining >= kHighWaterMarkBytes 1596 || (mFlags & PREPARE_CANCELLED)) { 1597 break; 1598 } 1599 1600 usleep(200000); 1601 } 1602 1603 mLock.lock(); 1604 1605 if (mFlags & PREPARE_CANCELLED) { 1606 LOGI("Prepare cancelled while waiting for initial cache fill."); 1607 return UNKNOWN_ERROR; 1608 } 1609 } else if (!strncasecmp(mUri.string(), "httplive://", 11)) { 1610 String8 uri("http://"); 1611 uri.append(mUri.string() + 11); 1612 1613 if (mLooper == NULL) { 1614 mLooper = new ALooper; 1615 mLooper->setName("httplive"); 1616 mLooper->start(); 1617 } 1618 1619 mLiveSession = new LiveSession; 1620 mLooper->registerHandler(mLiveSession); 1621 1622 mLiveSession->connect(uri.string()); 1623 dataSource = mLiveSession->getDataSource(); 1624 1625 sp<MediaExtractor> extractor = 1626 MediaExtractor::Create(dataSource, MEDIA_MIMETYPE_CONTAINER_MPEG2TS); 1627 1628 static_cast<MPEG2TSExtractor *>(extractor.get()) 1629 ->setLiveSession(mLiveSession); 1630 1631 return setDataSource_l(extractor); 1632 } else if (!strncasecmp("rtsp://", mUri.string(), 7)) { 1633 if (mLooper == NULL) { 1634 mLooper = new ALooper; 1635 mLooper->setName("rtsp"); 1636 mLooper->start(); 1637 } 1638 mRTSPController = new ARTSPController(mLooper); 1639 mConnectingRTSPController = mRTSPController; 1640 1641 mLock.unlock(); 1642 status_t err = mRTSPController->connect(mUri.string()); 1643 mLock.lock(); 1644 1645 mConnectingRTSPController.clear(); 1646 1647 LOGI("ARTSPController::connect returned %d", err); 1648 1649 if (err != OK) { 1650 mRTSPController.clear(); 1651 return err; 1652 } 1653 1654 sp<MediaExtractor> extractor = mRTSPController.get(); 1655 return setDataSource_l(extractor); 1656 } else { 1657 dataSource = DataSource::CreateFromURI(mUri.string(), &mUriHeaders); 1658 } 1659 1660 if (dataSource == NULL) { 1661 return UNKNOWN_ERROR; 1662 } 1663 1664 sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource); 1665 1666 if (extractor == NULL) { 1667 return UNKNOWN_ERROR; 1668 } 1669 1670 dataSource->getDrmInfo(&mDecryptHandle, &mDrmManagerClient); 1671 if (mDecryptHandle != NULL) { 1672 CHECK(mDrmManagerClient); 1673 if (RightsStatus::RIGHTS_VALID == mDecryptHandle->status) { 1674 if (DecryptApiType::WV_BASED == mDecryptHandle->decryptApiType) { 1675 LOGD("Setting mCachedSource to NULL for WVM\n"); 1676 mCachedSource.clear(); 1677 } 1678 } else { 1679 notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_NO_LICENSE); 1680 } 1681 } 1682 1683 return setDataSource_l(extractor); 1684} 1685 1686void AwesomePlayer::abortPrepare(status_t err) { 1687 CHECK(err != OK); 1688 1689 if (mIsAsyncPrepare) { 1690 notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err); 1691 } 1692 1693 mPrepareResult = err; 1694 mFlags &= ~(PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED); 1695 mAsyncPrepareEvent = NULL; 1696 mPreparedCondition.broadcast(); 1697} 1698 1699// static 1700bool AwesomePlayer::ContinuePreparation(void *cookie) { 1701 AwesomePlayer *me = static_cast<AwesomePlayer *>(cookie); 1702 1703 return (me->mFlags & PREPARE_CANCELLED) == 0; 1704} 1705 1706void AwesomePlayer::onPrepareAsyncEvent() { 1707 Mutex::Autolock autoLock(mLock); 1708 1709 if (mFlags & PREPARE_CANCELLED) { 1710 LOGI("prepare was cancelled before doing anything"); 1711 abortPrepare(UNKNOWN_ERROR); 1712 return; 1713 } 1714 1715 if (mUri.size() > 0) { 1716 status_t err = finishSetDataSource_l(); 1717 1718 if (err != OK) { 1719 abortPrepare(err); 1720 return; 1721 } 1722 } 1723 1724 if (mVideoTrack != NULL && mVideoSource == NULL) { 1725 status_t err = initVideoDecoder(); 1726 1727 if (err != OK) { 1728 abortPrepare(err); 1729 return; 1730 } 1731 } 1732 1733 if (mAudioTrack != NULL && mAudioSource == NULL) { 1734 status_t err = initAudioDecoder(); 1735 1736 if (err != OK) { 1737 abortPrepare(err); 1738 return; 1739 } 1740 } 1741 1742 mFlags |= PREPARING_CONNECTED; 1743 1744 if (mCachedSource != NULL || mRTSPController != NULL) { 1745 postBufferingEvent_l(); 1746 } else { 1747 finishAsyncPrepare_l(); 1748 } 1749} 1750 1751void AwesomePlayer::finishAsyncPrepare_l() { 1752 if (mIsAsyncPrepare) { 1753 if (mVideoSource == NULL) { 1754 notifyListener_l(MEDIA_SET_VIDEO_SIZE, 0, 0); 1755 } else { 1756 notifyVideoSize_l(); 1757 } 1758 1759 notifyListener_l(MEDIA_PREPARED); 1760 } 1761 1762 mPrepareResult = OK; 1763 mFlags &= ~(PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED); 1764 mFlags |= PREPARED; 1765 mAsyncPrepareEvent = NULL; 1766 mPreparedCondition.broadcast(); 1767} 1768 1769uint32_t AwesomePlayer::flags() const { 1770 return mExtractorFlags; 1771} 1772 1773void AwesomePlayer::postAudioEOS() { 1774 postCheckAudioStatusEvent_l(); 1775} 1776 1777void AwesomePlayer::postAudioSeekComplete() { 1778 postCheckAudioStatusEvent_l(); 1779} 1780 1781} // namespace android 1782