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