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