AwesomePlayer.cpp revision 1948eb3ea6eee336e8cdab9b0c693f93f5f19993
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#undef DEBUG_HDCP 18 19//#define LOG_NDEBUG 0 20#define LOG_TAG "AwesomePlayer" 21#include <utils/Log.h> 22 23#include <dlfcn.h> 24 25#include "include/AwesomePlayer.h" 26#include "include/DRMExtractor.h" 27#include "include/SoftwareRenderer.h" 28#include "include/NuCachedSource2.h" 29#include "include/ThrottledSource.h" 30#include "include/MPEG2TSExtractor.h" 31#include "include/WVMExtractor.h" 32 33#include <binder/IPCThreadState.h> 34#include <binder/IServiceManager.h> 35#include <media/IMediaPlayerService.h> 36#include <media/stagefright/foundation/hexdump.h> 37#include <media/stagefright/foundation/ADebug.h> 38#include <media/stagefright/timedtext/TimedTextDriver.h> 39#include <media/stagefright/AudioPlayer.h> 40#include <media/stagefright/DataSource.h> 41#include <media/stagefright/FileSource.h> 42#include <media/stagefright/MediaBuffer.h> 43#include <media/stagefright/MediaDefs.h> 44#include <media/stagefright/MediaExtractor.h> 45#include <media/stagefright/MediaSource.h> 46#include <media/stagefright/MetaData.h> 47#include <media/stagefright/OMXCodec.h> 48 49#include <gui/ISurfaceTexture.h> 50#include <gui/SurfaceTextureClient.h> 51 52#include <media/stagefright/foundation/AMessage.h> 53 54#include <cutils/properties.h> 55 56#define USE_SURFACE_ALLOC 1 57#define FRAME_DROP_FREQ 0 58 59namespace android { 60 61static int64_t kLowWaterMarkUs = 2000000ll; // 2secs 62static int64_t kHighWaterMarkUs = 5000000ll; // 5secs 63static const size_t kLowWaterMarkBytes = 40000; 64static const size_t kHighWaterMarkBytes = 200000; 65 66struct AwesomeEvent : public TimedEventQueue::Event { 67 AwesomeEvent( 68 AwesomePlayer *player, 69 void (AwesomePlayer::*method)()) 70 : mPlayer(player), 71 mMethod(method) { 72 } 73 74protected: 75 virtual ~AwesomeEvent() {} 76 77 virtual void fire(TimedEventQueue *queue, int64_t /* now_us */) { 78 (mPlayer->*mMethod)(); 79 } 80 81private: 82 AwesomePlayer *mPlayer; 83 void (AwesomePlayer::*mMethod)(); 84 85 AwesomeEvent(const AwesomeEvent &); 86 AwesomeEvent &operator=(const AwesomeEvent &); 87}; 88 89struct AwesomeLocalRenderer : public AwesomeRenderer { 90 AwesomeLocalRenderer( 91 const sp<ANativeWindow> &nativeWindow, const sp<MetaData> &meta) 92 : mTarget(new SoftwareRenderer(nativeWindow, meta)) { 93 } 94 95 virtual void render(MediaBuffer *buffer) { 96 render((const uint8_t *)buffer->data() + buffer->range_offset(), 97 buffer->range_length()); 98 } 99 100 void render(const void *data, size_t size) { 101 mTarget->render(data, size, NULL); 102 } 103 104protected: 105 virtual ~AwesomeLocalRenderer() { 106 delete mTarget; 107 mTarget = NULL; 108 } 109 110private: 111 SoftwareRenderer *mTarget; 112 113 AwesomeLocalRenderer(const AwesomeLocalRenderer &); 114 AwesomeLocalRenderer &operator=(const AwesomeLocalRenderer &);; 115}; 116 117struct AwesomeNativeWindowRenderer : public AwesomeRenderer { 118 AwesomeNativeWindowRenderer( 119 const sp<ANativeWindow> &nativeWindow, 120 int32_t rotationDegrees) 121 : mNativeWindow(nativeWindow) { 122 applyRotation(rotationDegrees); 123 } 124 125 virtual void render(MediaBuffer *buffer) { 126 int64_t timeUs; 127 CHECK(buffer->meta_data()->findInt64(kKeyTime, &timeUs)); 128 native_window_set_buffers_timestamp(mNativeWindow.get(), timeUs * 1000); 129 status_t err = mNativeWindow->queueBuffer( 130 mNativeWindow.get(), buffer->graphicBuffer().get()); 131 if (err != 0) { 132 ALOGE("queueBuffer failed with error %s (%d)", strerror(-err), 133 -err); 134 return; 135 } 136 137 sp<MetaData> metaData = buffer->meta_data(); 138 metaData->setInt32(kKeyRendered, 1); 139 } 140 141protected: 142 virtual ~AwesomeNativeWindowRenderer() {} 143 144private: 145 sp<ANativeWindow> mNativeWindow; 146 147 void applyRotation(int32_t rotationDegrees) { 148 uint32_t transform; 149 switch (rotationDegrees) { 150 case 0: transform = 0; break; 151 case 90: transform = HAL_TRANSFORM_ROT_90; break; 152 case 180: transform = HAL_TRANSFORM_ROT_180; break; 153 case 270: transform = HAL_TRANSFORM_ROT_270; break; 154 default: transform = 0; break; 155 } 156 157 if (transform) { 158 CHECK_EQ(0, native_window_set_buffers_transform( 159 mNativeWindow.get(), transform)); 160 } 161 } 162 163 AwesomeNativeWindowRenderer(const AwesomeNativeWindowRenderer &); 164 AwesomeNativeWindowRenderer &operator=( 165 const AwesomeNativeWindowRenderer &); 166}; 167 168// To collect the decoder usage 169void addBatteryData(uint32_t params) { 170 sp<IBinder> binder = 171 defaultServiceManager()->getService(String16("media.player")); 172 sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder); 173 CHECK(service.get() != NULL); 174 175 service->addBatteryData(params); 176} 177 178//////////////////////////////////////////////////////////////////////////////// 179AwesomePlayer::AwesomePlayer() 180 : mQueueStarted(false), 181 mUIDValid(false), 182 mTimeSource(NULL), 183 mVideoRendererIsPreview(false), 184 mAudioPlayer(NULL), 185 mDisplayWidth(0), 186 mDisplayHeight(0), 187 mFlags(0), 188 mExtractorFlags(0), 189 mVideoBuffer(NULL), 190 mDecryptHandle(NULL), 191 mLastVideoTimeUs(-1), 192 mTextDriver(NULL) { 193 CHECK_EQ(mClient.connect(), (status_t)OK); 194 195 DataSource::RegisterDefaultSniffers(); 196 197 mVideoEvent = new AwesomeEvent(this, &AwesomePlayer::onVideoEvent); 198 mVideoEventPending = false; 199 mStreamDoneEvent = new AwesomeEvent(this, &AwesomePlayer::onStreamDone); 200 mStreamDoneEventPending = false; 201 mBufferingEvent = new AwesomeEvent(this, &AwesomePlayer::onBufferingUpdate); 202 mBufferingEventPending = false; 203 mVideoLagEvent = new AwesomeEvent(this, &AwesomePlayer::onVideoLagUpdate); 204 mVideoEventPending = false; 205 206 mCheckAudioStatusEvent = new AwesomeEvent( 207 this, &AwesomePlayer::onCheckAudioStatus); 208 209 mAudioStatusEventPending = false; 210 211 reset(); 212} 213 214AwesomePlayer::~AwesomePlayer() { 215 if (mQueueStarted) { 216 mQueue.stop(); 217 } 218 219 reset(); 220 221 mClient.disconnect(); 222} 223 224void AwesomePlayer::cancelPlayerEvents(bool keepNotifications) { 225 mQueue.cancelEvent(mVideoEvent->eventID()); 226 mVideoEventPending = false; 227 mQueue.cancelEvent(mVideoLagEvent->eventID()); 228 mVideoLagEventPending = false; 229 230 if (!keepNotifications) { 231 mQueue.cancelEvent(mStreamDoneEvent->eventID()); 232 mStreamDoneEventPending = false; 233 mQueue.cancelEvent(mCheckAudioStatusEvent->eventID()); 234 mAudioStatusEventPending = false; 235 236 mQueue.cancelEvent(mBufferingEvent->eventID()); 237 mBufferingEventPending = false; 238 } 239} 240 241void AwesomePlayer::setListener(const wp<MediaPlayerBase> &listener) { 242 Mutex::Autolock autoLock(mLock); 243 mListener = listener; 244} 245 246void AwesomePlayer::setUID(uid_t uid) { 247 ALOGV("AwesomePlayer running on behalf of uid %d", uid); 248 249 mUID = uid; 250 mUIDValid = true; 251} 252 253status_t AwesomePlayer::setDataSource( 254 const char *uri, const KeyedVector<String8, String8> *headers) { 255 Mutex::Autolock autoLock(mLock); 256 return setDataSource_l(uri, headers); 257} 258 259status_t AwesomePlayer::setDataSource_l( 260 const char *uri, const KeyedVector<String8, String8> *headers) { 261 reset_l(); 262 263 mUri = uri; 264 265 if (headers) { 266 mUriHeaders = *headers; 267 268 ssize_t index = mUriHeaders.indexOfKey(String8("x-hide-urls-from-log")); 269 if (index >= 0) { 270 // Browser is in "incognito" mode, suppress logging URLs. 271 272 // This isn't something that should be passed to the server. 273 mUriHeaders.removeItemsAt(index); 274 275 modifyFlags(INCOGNITO, SET); 276 } 277 } 278 279 if (!(mFlags & INCOGNITO)) { 280 ALOGI("setDataSource_l('%s')", mUri.string()); 281 } else { 282 ALOGI("setDataSource_l(URL suppressed)"); 283 } 284 285 // The actual work will be done during preparation in the call to 286 // ::finishSetDataSource_l to avoid blocking the calling thread in 287 // setDataSource for any significant time. 288 289 { 290 Mutex::Autolock autoLock(mStatsLock); 291 mStats.mFd = -1; 292 mStats.mURI = mUri; 293 } 294 295 return OK; 296} 297 298status_t AwesomePlayer::setDataSource( 299 int fd, int64_t offset, int64_t length) { 300 Mutex::Autolock autoLock(mLock); 301 302 reset_l(); 303 304 sp<DataSource> dataSource = new FileSource(fd, offset, length); 305 306 status_t err = dataSource->initCheck(); 307 308 if (err != OK) { 309 return err; 310 } 311 312 mFileSource = dataSource; 313 314 { 315 Mutex::Autolock autoLock(mStatsLock); 316 mStats.mFd = fd; 317 mStats.mURI = String8(); 318 } 319 320 return setDataSource_l(dataSource); 321} 322 323status_t AwesomePlayer::setDataSource(const sp<IStreamSource> &source) { 324 return INVALID_OPERATION; 325} 326 327status_t AwesomePlayer::setDataSource_l( 328 const sp<DataSource> &dataSource) { 329 sp<MediaExtractor> extractor = MediaExtractor::Create(dataSource); 330 331 if (extractor == NULL) { 332 return UNKNOWN_ERROR; 333 } 334 335 if (extractor->getDrmFlag()) { 336 checkDrmStatus(dataSource); 337 } 338 339 return setDataSource_l(extractor); 340} 341 342void AwesomePlayer::checkDrmStatus(const sp<DataSource>& dataSource) { 343 dataSource->getDrmInfo(mDecryptHandle, &mDrmManagerClient); 344 if (mDecryptHandle != NULL) { 345 CHECK(mDrmManagerClient); 346 if (RightsStatus::RIGHTS_VALID != mDecryptHandle->status) { 347 notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_DRM_NO_LICENSE); 348 } 349 } 350} 351 352status_t AwesomePlayer::setDataSource_l(const sp<MediaExtractor> &extractor) { 353 // Attempt to approximate overall stream bitrate by summing all 354 // tracks' individual bitrates, if not all of them advertise bitrate, 355 // we have to fail. 356 357 int64_t totalBitRate = 0; 358 359 mExtractor = extractor; 360 for (size_t i = 0; i < extractor->countTracks(); ++i) { 361 sp<MetaData> meta = extractor->getTrackMetaData(i); 362 363 int32_t bitrate; 364 if (!meta->findInt32(kKeyBitRate, &bitrate)) { 365 const char *mime; 366 CHECK(meta->findCString(kKeyMIMEType, &mime)); 367 ALOGV("track of type '%s' does not publish bitrate", mime); 368 369 totalBitRate = -1; 370 break; 371 } 372 373 totalBitRate += bitrate; 374 } 375 376 mBitrate = totalBitRate; 377 378 ALOGV("mBitrate = %lld bits/sec", mBitrate); 379 380 { 381 Mutex::Autolock autoLock(mStatsLock); 382 mStats.mBitrate = mBitrate; 383 mStats.mTracks.clear(); 384 mStats.mAudioTrackIndex = -1; 385 mStats.mVideoTrackIndex = -1; 386 } 387 388 bool haveAudio = false; 389 bool haveVideo = false; 390 for (size_t i = 0; i < extractor->countTracks(); ++i) { 391 sp<MetaData> meta = extractor->getTrackMetaData(i); 392 393 const char *_mime; 394 CHECK(meta->findCString(kKeyMIMEType, &_mime)); 395 396 String8 mime = String8(_mime); 397 398 if (!haveVideo && !strncasecmp(mime.string(), "video/", 6)) { 399 setVideoSource(extractor->getTrack(i)); 400 haveVideo = true; 401 402 // Set the presentation/display size 403 int32_t displayWidth, displayHeight; 404 bool success = meta->findInt32(kKeyDisplayWidth, &displayWidth); 405 if (success) { 406 success = meta->findInt32(kKeyDisplayHeight, &displayHeight); 407 } 408 if (success) { 409 mDisplayWidth = displayWidth; 410 mDisplayHeight = displayHeight; 411 } 412 413 { 414 Mutex::Autolock autoLock(mStatsLock); 415 mStats.mVideoTrackIndex = mStats.mTracks.size(); 416 mStats.mTracks.push(); 417 TrackStat *stat = 418 &mStats.mTracks.editItemAt(mStats.mVideoTrackIndex); 419 stat->mMIME = mime.string(); 420 } 421 } else if (!haveAudio && !strncasecmp(mime.string(), "audio/", 6)) { 422 setAudioSource(extractor->getTrack(i)); 423 haveAudio = true; 424 425 { 426 Mutex::Autolock autoLock(mStatsLock); 427 mStats.mAudioTrackIndex = mStats.mTracks.size(); 428 mStats.mTracks.push(); 429 TrackStat *stat = 430 &mStats.mTracks.editItemAt(mStats.mAudioTrackIndex); 431 stat->mMIME = mime.string(); 432 } 433 434 if (!strcasecmp(mime.string(), MEDIA_MIMETYPE_AUDIO_VORBIS)) { 435 // Only do this for vorbis audio, none of the other audio 436 // formats even support this ringtone specific hack and 437 // retrieving the metadata on some extractors may turn out 438 // to be very expensive. 439 sp<MetaData> fileMeta = extractor->getMetaData(); 440 int32_t loop; 441 if (fileMeta != NULL 442 && fileMeta->findInt32(kKeyAutoLoop, &loop) && loop != 0) { 443 modifyFlags(AUTO_LOOPING, SET); 444 } 445 } 446 } else if (!strcasecmp(mime.string(), MEDIA_MIMETYPE_TEXT_3GPP)) { 447 addTextSource(i, extractor->getTrack(i)); 448 } 449 } 450 451 if (!haveAudio && !haveVideo) { 452 return UNKNOWN_ERROR; 453 } 454 455 mExtractorFlags = extractor->flags(); 456 457 return OK; 458} 459 460void AwesomePlayer::reset() { 461 Mutex::Autolock autoLock(mLock); 462 reset_l(); 463} 464 465void AwesomePlayer::reset_l() { 466 mDisplayWidth = 0; 467 mDisplayHeight = 0; 468 469 if (mDecryptHandle != NULL) { 470 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 471 Playback::STOP, 0); 472 mDecryptHandle = NULL; 473 mDrmManagerClient = NULL; 474 } 475 476 if (mFlags & PLAYING) { 477 uint32_t params = IMediaPlayerService::kBatteryDataTrackDecoder; 478 if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) { 479 params |= IMediaPlayerService::kBatteryDataTrackAudio; 480 } 481 if (mVideoSource != NULL) { 482 params |= IMediaPlayerService::kBatteryDataTrackVideo; 483 } 484 addBatteryData(params); 485 } 486 487 if (mFlags & PREPARING) { 488 modifyFlags(PREPARE_CANCELLED, SET); 489 if (mConnectingDataSource != NULL) { 490 ALOGI("interrupting the connection process"); 491 mConnectingDataSource->disconnect(); 492 } 493 494 if (mFlags & PREPARING_CONNECTED) { 495 // We are basically done preparing, we're just buffering 496 // enough data to start playback, we can safely interrupt that. 497 finishAsyncPrepare_l(); 498 } 499 } 500 501 while (mFlags & PREPARING) { 502 mPreparedCondition.wait(mLock); 503 } 504 505 cancelPlayerEvents(); 506 507 mWVMExtractor.clear(); 508 mCachedSource.clear(); 509 mAudioTrack.clear(); 510 mVideoTrack.clear(); 511 mExtractor.clear(); 512 513 // Shutdown audio first, so that the respone to the reset request 514 // appears to happen instantaneously as far as the user is concerned 515 // If we did this later, audio would continue playing while we 516 // shutdown the video-related resources and the player appear to 517 // not be as responsive to a reset request. 518 if ((mAudioPlayer == NULL || !(mFlags & AUDIOPLAYER_STARTED)) 519 && mAudioSource != NULL) { 520 // If we had an audio player, it would have effectively 521 // taken possession of the audio source and stopped it when 522 // _it_ is stopped. Otherwise this is still our responsibility. 523 mAudioSource->stop(); 524 } 525 mAudioSource.clear(); 526 527 mTimeSource = NULL; 528 529 delete mAudioPlayer; 530 mAudioPlayer = NULL; 531 532 if (mTextDriver != NULL) { 533 delete mTextDriver; 534 mTextDriver = NULL; 535 } 536 537 mVideoRenderer.clear(); 538 539 if (mVideoSource != NULL) { 540 shutdownVideoDecoder_l(); 541 } 542 543 mDurationUs = -1; 544 modifyFlags(0, ASSIGN); 545 mExtractorFlags = 0; 546 mTimeSourceDeltaUs = 0; 547 mVideoTimeUs = 0; 548 549 mSeeking = NO_SEEK; 550 mSeekNotificationSent = true; 551 mSeekTimeUs = 0; 552 553 mUri.setTo(""); 554 mUriHeaders.clear(); 555 556 mFileSource.clear(); 557 558 mBitrate = -1; 559 mLastVideoTimeUs = -1; 560 561 { 562 Mutex::Autolock autoLock(mStatsLock); 563 mStats.mFd = -1; 564 mStats.mURI = String8(); 565 mStats.mBitrate = -1; 566 mStats.mAudioTrackIndex = -1; 567 mStats.mVideoTrackIndex = -1; 568 mStats.mNumVideoFramesDecoded = 0; 569 mStats.mNumVideoFramesDropped = 0; 570 mStats.mVideoWidth = -1; 571 mStats.mVideoHeight = -1; 572 mStats.mFlags = 0; 573 mStats.mTracks.clear(); 574 } 575 576 mWatchForAudioSeekComplete = false; 577 mWatchForAudioEOS = false; 578} 579 580void AwesomePlayer::notifyListener_l(int msg, int ext1, int ext2) { 581 if (mListener != NULL) { 582 sp<MediaPlayerBase> listener = mListener.promote(); 583 584 if (listener != NULL) { 585 listener->sendEvent(msg, ext1, ext2); 586 } 587 } 588} 589 590bool AwesomePlayer::getBitrate(int64_t *bitrate) { 591 off64_t size; 592 if (mDurationUs >= 0 && mCachedSource != NULL 593 && mCachedSource->getSize(&size) == OK) { 594 *bitrate = size * 8000000ll / mDurationUs; // in bits/sec 595 return true; 596 } 597 598 if (mBitrate >= 0) { 599 *bitrate = mBitrate; 600 return true; 601 } 602 603 *bitrate = 0; 604 605 return false; 606} 607 608// Returns true iff cached duration is available/applicable. 609bool AwesomePlayer::getCachedDuration_l(int64_t *durationUs, bool *eos) { 610 int64_t bitrate; 611 612 if (mCachedSource != NULL && getBitrate(&bitrate)) { 613 status_t finalStatus; 614 size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus); 615 *durationUs = cachedDataRemaining * 8000000ll / bitrate; 616 *eos = (finalStatus != OK); 617 return true; 618 } else if (mWVMExtractor != NULL) { 619 status_t finalStatus; 620 *durationUs = mWVMExtractor->getCachedDurationUs(&finalStatus); 621 *eos = (finalStatus != OK); 622 return true; 623 } 624 625 return false; 626} 627 628void AwesomePlayer::ensureCacheIsFetching_l() { 629 if (mCachedSource != NULL) { 630 mCachedSource->resumeFetchingIfNecessary(); 631 } 632} 633 634void AwesomePlayer::onVideoLagUpdate() { 635 Mutex::Autolock autoLock(mLock); 636 if (!mVideoLagEventPending) { 637 return; 638 } 639 mVideoLagEventPending = false; 640 641 int64_t audioTimeUs = mAudioPlayer->getMediaTimeUs(); 642 int64_t videoLateByUs = audioTimeUs - mVideoTimeUs; 643 644 if (!(mFlags & VIDEO_AT_EOS) && videoLateByUs > 300000ll) { 645 ALOGV("video late by %lld ms.", videoLateByUs / 1000ll); 646 647 notifyListener_l( 648 MEDIA_INFO, 649 MEDIA_INFO_VIDEO_TRACK_LAGGING, 650 videoLateByUs / 1000ll); 651 } 652 653 postVideoLagEvent_l(); 654} 655 656void AwesomePlayer::onBufferingUpdate() { 657 Mutex::Autolock autoLock(mLock); 658 if (!mBufferingEventPending) { 659 return; 660 } 661 mBufferingEventPending = false; 662 663 if (mCachedSource != NULL) { 664 status_t finalStatus; 665 size_t cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus); 666 bool eos = (finalStatus != OK); 667 668 if (eos) { 669 if (finalStatus == ERROR_END_OF_STREAM) { 670 notifyListener_l(MEDIA_BUFFERING_UPDATE, 100); 671 } 672 if (mFlags & PREPARING) { 673 ALOGV("cache has reached EOS, prepare is done."); 674 finishAsyncPrepare_l(); 675 } 676 } else { 677 int64_t bitrate; 678 if (getBitrate(&bitrate)) { 679 size_t cachedSize = mCachedSource->cachedSize(); 680 int64_t cachedDurationUs = cachedSize * 8000000ll / bitrate; 681 682 int percentage = 100.0 * (double)cachedDurationUs / mDurationUs; 683 if (percentage > 100) { 684 percentage = 100; 685 } 686 687 notifyListener_l(MEDIA_BUFFERING_UPDATE, percentage); 688 } else { 689 // We don't know the bitrate of the stream, use absolute size 690 // limits to maintain the cache. 691 692 if ((mFlags & PLAYING) && !eos 693 && (cachedDataRemaining < kLowWaterMarkBytes)) { 694 ALOGI("cache is running low (< %d) , pausing.", 695 kLowWaterMarkBytes); 696 modifyFlags(CACHE_UNDERRUN, SET); 697 pause_l(); 698 ensureCacheIsFetching_l(); 699 sendCacheStats(); 700 notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START); 701 } else if (eos || cachedDataRemaining > kHighWaterMarkBytes) { 702 if (mFlags & CACHE_UNDERRUN) { 703 ALOGI("cache has filled up (> %d), resuming.", 704 kHighWaterMarkBytes); 705 modifyFlags(CACHE_UNDERRUN, CLEAR); 706 play_l(); 707 notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_END); 708 } else if (mFlags & PREPARING) { 709 ALOGV("cache has filled up (> %d), prepare is done", 710 kHighWaterMarkBytes); 711 finishAsyncPrepare_l(); 712 } 713 } 714 } 715 } 716 } else if (mWVMExtractor != NULL) { 717 status_t finalStatus; 718 719 int64_t cachedDurationUs 720 = mWVMExtractor->getCachedDurationUs(&finalStatus); 721 722 bool eos = (finalStatus != OK); 723 724 if (eos) { 725 if (finalStatus == ERROR_END_OF_STREAM) { 726 notifyListener_l(MEDIA_BUFFERING_UPDATE, 100); 727 } 728 if (mFlags & PREPARING) { 729 ALOGV("cache has reached EOS, prepare is done."); 730 finishAsyncPrepare_l(); 731 } 732 } else { 733 int percentage = 100.0 * (double)cachedDurationUs / mDurationUs; 734 if (percentage > 100) { 735 percentage = 100; 736 } 737 738 notifyListener_l(MEDIA_BUFFERING_UPDATE, percentage); 739 } 740 } 741 742 int64_t cachedDurationUs; 743 bool eos; 744 if (getCachedDuration_l(&cachedDurationUs, &eos)) { 745 ALOGV("cachedDurationUs = %.2f secs, eos=%d", 746 cachedDurationUs / 1E6, eos); 747 748 if ((mFlags & PLAYING) && !eos 749 && (cachedDurationUs < kLowWaterMarkUs)) { 750 ALOGI("cache is running low (%.2f secs) , pausing.", 751 cachedDurationUs / 1E6); 752 modifyFlags(CACHE_UNDERRUN, SET); 753 pause_l(); 754 ensureCacheIsFetching_l(); 755 sendCacheStats(); 756 notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_START); 757 } else if (eos || cachedDurationUs > kHighWaterMarkUs) { 758 if (mFlags & CACHE_UNDERRUN) { 759 ALOGI("cache has filled up (%.2f secs), resuming.", 760 cachedDurationUs / 1E6); 761 modifyFlags(CACHE_UNDERRUN, CLEAR); 762 play_l(); 763 notifyListener_l(MEDIA_INFO, MEDIA_INFO_BUFFERING_END); 764 } else if (mFlags & PREPARING) { 765 ALOGV("cache has filled up (%.2f secs), prepare is done", 766 cachedDurationUs / 1E6); 767 finishAsyncPrepare_l(); 768 } 769 } 770 } 771 772 postBufferingEvent_l(); 773} 774 775void AwesomePlayer::sendCacheStats() { 776 sp<MediaPlayerBase> listener = mListener.promote(); 777 if (listener != NULL && mCachedSource != NULL) { 778 int32_t kbps = 0; 779 status_t err = mCachedSource->getEstimatedBandwidthKbps(&kbps); 780 if (err == OK) { 781 listener->sendEvent( 782 MEDIA_INFO, MEDIA_INFO_NETWORK_BANDWIDTH, kbps); 783 } 784 } 785} 786 787void AwesomePlayer::onStreamDone() { 788 // Posted whenever any stream finishes playing. 789 790 Mutex::Autolock autoLock(mLock); 791 if (!mStreamDoneEventPending) { 792 return; 793 } 794 mStreamDoneEventPending = false; 795 796 if (mStreamDoneStatus != ERROR_END_OF_STREAM) { 797 ALOGV("MEDIA_ERROR %d", mStreamDoneStatus); 798 799 notifyListener_l( 800 MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, mStreamDoneStatus); 801 802 pause_l(true /* at eos */); 803 804 modifyFlags(AT_EOS, SET); 805 return; 806 } 807 808 const bool allDone = 809 (mVideoSource == NULL || (mFlags & VIDEO_AT_EOS)) 810 && (mAudioSource == NULL || (mFlags & AUDIO_AT_EOS)); 811 812 if (!allDone) { 813 return; 814 } 815 816 if ((mFlags & LOOPING) 817 || ((mFlags & AUTO_LOOPING) 818 && (mAudioSink == NULL || mAudioSink->realtime()))) { 819 // Don't AUTO_LOOP if we're being recorded, since that cannot be 820 // turned off and recording would go on indefinitely. 821 822 seekTo_l(0); 823 824 if (mVideoSource != NULL) { 825 postVideoEvent_l(); 826 } 827 } else { 828 ALOGV("MEDIA_PLAYBACK_COMPLETE"); 829 notifyListener_l(MEDIA_PLAYBACK_COMPLETE); 830 831 pause_l(true /* at eos */); 832 833 modifyFlags(AT_EOS, SET); 834 } 835} 836 837status_t AwesomePlayer::play() { 838 Mutex::Autolock autoLock(mLock); 839 840 modifyFlags(CACHE_UNDERRUN, CLEAR); 841 842 return play_l(); 843} 844 845status_t AwesomePlayer::play_l() { 846 modifyFlags(SEEK_PREVIEW, CLEAR); 847 848 if (mFlags & PLAYING) { 849 return OK; 850 } 851 852 if (!(mFlags & PREPARED)) { 853 status_t err = prepare_l(); 854 855 if (err != OK) { 856 return err; 857 } 858 } 859 860 modifyFlags(PLAYING, SET); 861 modifyFlags(FIRST_FRAME, SET); 862 863 if (mDecryptHandle != NULL) { 864 int64_t position; 865 getPosition(&position); 866 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 867 Playback::START, position / 1000); 868 } 869 870 if (mAudioSource != NULL) { 871 if (mAudioPlayer == NULL) { 872 if (mAudioSink != NULL) { 873 bool allowDeepBuffering; 874 int64_t cachedDurationUs; 875 bool eos; 876 if (mVideoSource == NULL && (mDurationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US || 877 getCachedDuration_l(&cachedDurationUs, &eos) && 878 cachedDurationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US)) { 879 allowDeepBuffering = true; 880 } else { 881 allowDeepBuffering = false; 882 } 883 884 mAudioPlayer = new AudioPlayer(mAudioSink, allowDeepBuffering, this); 885 mAudioPlayer->setSource(mAudioSource); 886 887 mTimeSource = mAudioPlayer; 888 889 // If there was a seek request before we ever started, 890 // honor the request now. 891 // Make sure to do this before starting the audio player 892 // to avoid a race condition. 893 seekAudioIfNecessary_l(); 894 } 895 } 896 897 CHECK(!(mFlags & AUDIO_RUNNING)); 898 899 if (mVideoSource == NULL) { 900 // We don't want to post an error notification at this point, 901 // the error returned from MediaPlayer::start() will suffice. 902 903 status_t err = startAudioPlayer_l( 904 false /* sendErrorNotification */); 905 906 if (err != OK) { 907 delete mAudioPlayer; 908 mAudioPlayer = NULL; 909 910 modifyFlags((PLAYING | FIRST_FRAME), CLEAR); 911 912 if (mDecryptHandle != NULL) { 913 mDrmManagerClient->setPlaybackStatus( 914 mDecryptHandle, Playback::STOP, 0); 915 } 916 917 return err; 918 } 919 } 920 } 921 922 if (mTimeSource == NULL && mAudioPlayer == NULL) { 923 mTimeSource = &mSystemTimeSource; 924 } 925 926 if (mVideoSource != NULL) { 927 // Kick off video playback 928 postVideoEvent_l(); 929 930 if (mAudioSource != NULL && mVideoSource != NULL) { 931 postVideoLagEvent_l(); 932 } 933 } 934 935 if (mFlags & AT_EOS) { 936 // Legacy behaviour, if a stream finishes playing and then 937 // is started again, we play from the start... 938 seekTo_l(0); 939 } 940 941 uint32_t params = IMediaPlayerService::kBatteryDataCodecStarted 942 | IMediaPlayerService::kBatteryDataTrackDecoder; 943 if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) { 944 params |= IMediaPlayerService::kBatteryDataTrackAudio; 945 } 946 if (mVideoSource != NULL) { 947 params |= IMediaPlayerService::kBatteryDataTrackVideo; 948 } 949 addBatteryData(params); 950 951 return OK; 952} 953 954status_t AwesomePlayer::startAudioPlayer_l(bool sendErrorNotification) { 955 CHECK(!(mFlags & AUDIO_RUNNING)); 956 957 if (mAudioSource == NULL || mAudioPlayer == NULL) { 958 return OK; 959 } 960 961 if (!(mFlags & AUDIOPLAYER_STARTED)) { 962 modifyFlags(AUDIOPLAYER_STARTED, SET); 963 964 bool wasSeeking = mAudioPlayer->isSeeking(); 965 966 // We've already started the MediaSource in order to enable 967 // the prefetcher to read its data. 968 status_t err = mAudioPlayer->start( 969 true /* sourceAlreadyStarted */); 970 971 if (err != OK) { 972 if (sendErrorNotification) { 973 notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err); 974 } 975 976 return err; 977 } 978 979 if (wasSeeking) { 980 CHECK(!mAudioPlayer->isSeeking()); 981 982 // We will have finished the seek while starting the audio player. 983 postAudioSeekComplete(); 984 } 985 } else { 986 mAudioPlayer->resume(); 987 } 988 989 modifyFlags(AUDIO_RUNNING, SET); 990 991 mWatchForAudioEOS = true; 992 993 return OK; 994} 995 996void AwesomePlayer::notifyVideoSize_l() { 997 sp<MetaData> meta = mVideoSource->getFormat(); 998 999 int32_t cropLeft, cropTop, cropRight, cropBottom; 1000 if (!meta->findRect( 1001 kKeyCropRect, &cropLeft, &cropTop, &cropRight, &cropBottom)) { 1002 int32_t width, height; 1003 CHECK(meta->findInt32(kKeyWidth, &width)); 1004 CHECK(meta->findInt32(kKeyHeight, &height)); 1005 1006 cropLeft = cropTop = 0; 1007 cropRight = width - 1; 1008 cropBottom = height - 1; 1009 1010 ALOGV("got dimensions only %d x %d", width, height); 1011 } else { 1012 ALOGV("got crop rect %d, %d, %d, %d", 1013 cropLeft, cropTop, cropRight, cropBottom); 1014 } 1015 1016 int32_t displayWidth; 1017 if (meta->findInt32(kKeyDisplayWidth, &displayWidth)) { 1018 ALOGV("Display width changed (%d=>%d)", mDisplayWidth, displayWidth); 1019 mDisplayWidth = displayWidth; 1020 } 1021 int32_t displayHeight; 1022 if (meta->findInt32(kKeyDisplayHeight, &displayHeight)) { 1023 ALOGV("Display height changed (%d=>%d)", mDisplayHeight, displayHeight); 1024 mDisplayHeight = displayHeight; 1025 } 1026 1027 int32_t usableWidth = cropRight - cropLeft + 1; 1028 int32_t usableHeight = cropBottom - cropTop + 1; 1029 if (mDisplayWidth != 0) { 1030 usableWidth = mDisplayWidth; 1031 } 1032 if (mDisplayHeight != 0) { 1033 usableHeight = mDisplayHeight; 1034 } 1035 1036 { 1037 Mutex::Autolock autoLock(mStatsLock); 1038 mStats.mVideoWidth = usableWidth; 1039 mStats.mVideoHeight = usableHeight; 1040 } 1041 1042 int32_t rotationDegrees; 1043 if (!mVideoTrack->getFormat()->findInt32( 1044 kKeyRotation, &rotationDegrees)) { 1045 rotationDegrees = 0; 1046 } 1047 1048 if (rotationDegrees == 90 || rotationDegrees == 270) { 1049 notifyListener_l( 1050 MEDIA_SET_VIDEO_SIZE, usableHeight, usableWidth); 1051 } else { 1052 notifyListener_l( 1053 MEDIA_SET_VIDEO_SIZE, usableWidth, usableHeight); 1054 } 1055} 1056 1057void AwesomePlayer::initRenderer_l() { 1058 if (mNativeWindow == NULL) { 1059 return; 1060 } 1061 1062 sp<MetaData> meta = mVideoSource->getFormat(); 1063 1064 int32_t format; 1065 const char *component; 1066 int32_t decodedWidth, decodedHeight; 1067 CHECK(meta->findInt32(kKeyColorFormat, &format)); 1068 CHECK(meta->findCString(kKeyDecoderComponent, &component)); 1069 CHECK(meta->findInt32(kKeyWidth, &decodedWidth)); 1070 CHECK(meta->findInt32(kKeyHeight, &decodedHeight)); 1071 1072 int32_t rotationDegrees; 1073 if (!mVideoTrack->getFormat()->findInt32( 1074 kKeyRotation, &rotationDegrees)) { 1075 rotationDegrees = 0; 1076 } 1077 1078 mVideoRenderer.clear(); 1079 1080 // Must ensure that mVideoRenderer's destructor is actually executed 1081 // before creating a new one. 1082 IPCThreadState::self()->flushCommands(); 1083 1084 if (USE_SURFACE_ALLOC 1085 && !strncmp(component, "OMX.", 4) 1086 && strncmp(component, "OMX.google.", 11) 1087 && strcmp(component, "OMX.Nvidia.mpeg2v.decode")) { 1088 // Hardware decoders avoid the CPU color conversion by decoding 1089 // directly to ANativeBuffers, so we must use a renderer that 1090 // just pushes those buffers to the ANativeWindow. 1091 mVideoRenderer = 1092 new AwesomeNativeWindowRenderer(mNativeWindow, rotationDegrees); 1093 } else { 1094 // Other decoders are instantiated locally and as a consequence 1095 // allocate their buffers in local address space. This renderer 1096 // then performs a color conversion and copy to get the data 1097 // into the ANativeBuffer. 1098 mVideoRenderer = new AwesomeLocalRenderer(mNativeWindow, meta); 1099 } 1100} 1101 1102status_t AwesomePlayer::pause() { 1103 Mutex::Autolock autoLock(mLock); 1104 1105 modifyFlags(CACHE_UNDERRUN, CLEAR); 1106 1107 return pause_l(); 1108} 1109 1110status_t AwesomePlayer::pause_l(bool at_eos) { 1111 if (!(mFlags & PLAYING)) { 1112 return OK; 1113 } 1114 1115 cancelPlayerEvents(true /* keepNotifications */); 1116 1117 if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) { 1118 if (at_eos) { 1119 // If we played the audio stream to completion we 1120 // want to make sure that all samples remaining in the audio 1121 // track's queue are played out. 1122 mAudioPlayer->pause(true /* playPendingSamples */); 1123 } else { 1124 mAudioPlayer->pause(); 1125 } 1126 1127 modifyFlags(AUDIO_RUNNING, CLEAR); 1128 } 1129 1130 if (mFlags & TEXTPLAYER_INITIALIZED) { 1131 mTextDriver->pause(); 1132 modifyFlags(TEXT_RUNNING, CLEAR); 1133 } 1134 1135 modifyFlags(PLAYING, CLEAR); 1136 1137 if (mDecryptHandle != NULL) { 1138 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1139 Playback::PAUSE, 0); 1140 } 1141 1142 uint32_t params = IMediaPlayerService::kBatteryDataTrackDecoder; 1143 if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) { 1144 params |= IMediaPlayerService::kBatteryDataTrackAudio; 1145 } 1146 if (mVideoSource != NULL) { 1147 params |= IMediaPlayerService::kBatteryDataTrackVideo; 1148 } 1149 1150 addBatteryData(params); 1151 1152 return OK; 1153} 1154 1155bool AwesomePlayer::isPlaying() const { 1156 return (mFlags & PLAYING) || (mFlags & CACHE_UNDERRUN); 1157} 1158 1159status_t AwesomePlayer::setSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture) { 1160 Mutex::Autolock autoLock(mLock); 1161 1162 status_t err; 1163 if (surfaceTexture != NULL) { 1164 err = setNativeWindow_l(new SurfaceTextureClient(surfaceTexture)); 1165 } else { 1166 err = setNativeWindow_l(NULL); 1167 } 1168 1169 return err; 1170} 1171 1172void AwesomePlayer::shutdownVideoDecoder_l() { 1173 if (mVideoBuffer) { 1174 mVideoBuffer->release(); 1175 mVideoBuffer = NULL; 1176 } 1177 1178 mVideoSource->stop(); 1179 1180 // The following hack is necessary to ensure that the OMX 1181 // component is completely released by the time we may try 1182 // to instantiate it again. 1183 wp<MediaSource> tmp = mVideoSource; 1184 mVideoSource.clear(); 1185 while (tmp.promote() != NULL) { 1186 usleep(1000); 1187 } 1188 IPCThreadState::self()->flushCommands(); 1189 ALOGV("video decoder shutdown completed"); 1190} 1191 1192status_t AwesomePlayer::setNativeWindow_l(const sp<ANativeWindow> &native) { 1193 mNativeWindow = native; 1194 1195 if (mVideoSource == NULL) { 1196 return OK; 1197 } 1198 1199 ALOGV("attempting to reconfigure to use new surface"); 1200 1201 bool wasPlaying = (mFlags & PLAYING) != 0; 1202 1203 pause_l(); 1204 mVideoRenderer.clear(); 1205 1206 shutdownVideoDecoder_l(); 1207 1208 status_t err = initVideoDecoder(); 1209 1210 if (err != OK) { 1211 ALOGE("failed to reinstantiate video decoder after surface change."); 1212 return err; 1213 } 1214 1215 if (mLastVideoTimeUs >= 0) { 1216 mSeeking = SEEK; 1217 mSeekTimeUs = mLastVideoTimeUs; 1218 modifyFlags((AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS), CLEAR); 1219 } 1220 1221 if (wasPlaying) { 1222 play_l(); 1223 } 1224 1225 return OK; 1226} 1227 1228void AwesomePlayer::setAudioSink( 1229 const sp<MediaPlayerBase::AudioSink> &audioSink) { 1230 Mutex::Autolock autoLock(mLock); 1231 1232 mAudioSink = audioSink; 1233} 1234 1235status_t AwesomePlayer::setLooping(bool shouldLoop) { 1236 Mutex::Autolock autoLock(mLock); 1237 1238 modifyFlags(LOOPING, CLEAR); 1239 1240 if (shouldLoop) { 1241 modifyFlags(LOOPING, SET); 1242 } 1243 1244 return OK; 1245} 1246 1247status_t AwesomePlayer::getDuration(int64_t *durationUs) { 1248 Mutex::Autolock autoLock(mMiscStateLock); 1249 1250 if (mDurationUs < 0) { 1251 return UNKNOWN_ERROR; 1252 } 1253 1254 *durationUs = mDurationUs; 1255 1256 return OK; 1257} 1258 1259status_t AwesomePlayer::getPosition(int64_t *positionUs) { 1260 if (mSeeking != NO_SEEK) { 1261 *positionUs = mSeekTimeUs; 1262 } else if (mVideoSource != NULL 1263 && (mAudioPlayer == NULL || !(mFlags & VIDEO_AT_EOS))) { 1264 Mutex::Autolock autoLock(mMiscStateLock); 1265 *positionUs = mVideoTimeUs; 1266 } else if (mAudioPlayer != NULL) { 1267 *positionUs = mAudioPlayer->getMediaTimeUs(); 1268 } else { 1269 *positionUs = 0; 1270 } 1271 1272 return OK; 1273} 1274 1275status_t AwesomePlayer::seekTo(int64_t timeUs) { 1276 if (mExtractorFlags & MediaExtractor::CAN_SEEK) { 1277 Mutex::Autolock autoLock(mLock); 1278 return seekTo_l(timeUs); 1279 } 1280 1281 return OK; 1282} 1283 1284status_t AwesomePlayer::seekTo_l(int64_t timeUs) { 1285 if (mFlags & CACHE_UNDERRUN) { 1286 modifyFlags(CACHE_UNDERRUN, CLEAR); 1287 play_l(); 1288 } 1289 1290 if ((mFlags & PLAYING) && mVideoSource != NULL && (mFlags & VIDEO_AT_EOS)) { 1291 // Video playback completed before, there's no pending 1292 // video event right now. In order for this new seek 1293 // to be honored, we need to post one. 1294 1295 postVideoEvent_l(); 1296 } 1297 1298 mSeeking = SEEK; 1299 mSeekNotificationSent = false; 1300 mSeekTimeUs = timeUs; 1301 modifyFlags((AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS), CLEAR); 1302 1303 seekAudioIfNecessary_l(); 1304 1305 if (mFlags & TEXTPLAYER_INITIALIZED) { 1306 mTextDriver->seekToAsync(mSeekTimeUs); 1307 } 1308 1309 if (!(mFlags & PLAYING)) { 1310 ALOGV("seeking while paused, sending SEEK_COMPLETE notification" 1311 " immediately."); 1312 1313 notifyListener_l(MEDIA_SEEK_COMPLETE); 1314 mSeekNotificationSent = true; 1315 1316 if ((mFlags & PREPARED) && mVideoSource != NULL) { 1317 modifyFlags(SEEK_PREVIEW, SET); 1318 postVideoEvent_l(); 1319 } 1320 } 1321 1322 return OK; 1323} 1324 1325void AwesomePlayer::seekAudioIfNecessary_l() { 1326 if (mSeeking != NO_SEEK && mVideoSource == NULL && mAudioPlayer != NULL) { 1327 mAudioPlayer->seekTo(mSeekTimeUs); 1328 1329 mWatchForAudioSeekComplete = true; 1330 mWatchForAudioEOS = true; 1331 1332 if (mDecryptHandle != NULL) { 1333 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1334 Playback::PAUSE, 0); 1335 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1336 Playback::START, mSeekTimeUs / 1000); 1337 } 1338 } 1339} 1340 1341void AwesomePlayer::setAudioSource(sp<MediaSource> source) { 1342 CHECK(source != NULL); 1343 1344 mAudioTrack = source; 1345} 1346 1347void AwesomePlayer::addTextSource(size_t trackIndex, const sp<MediaSource>& source) { 1348 Mutex::Autolock autoLock(mTimedTextLock); 1349 CHECK(source != NULL); 1350 1351 if (mTextDriver == NULL) { 1352 mTextDriver = new TimedTextDriver(mListener); 1353 } 1354 1355 mTextDriver->addInBandTextSource(trackIndex, source); 1356} 1357 1358status_t AwesomePlayer::initAudioDecoder() { 1359 sp<MetaData> meta = mAudioTrack->getFormat(); 1360 1361 const char *mime; 1362 CHECK(meta->findCString(kKeyMIMEType, &mime)); 1363 1364 if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_RAW)) { 1365 mAudioSource = mAudioTrack; 1366 } else { 1367 mAudioSource = OMXCodec::Create( 1368 mClient.interface(), mAudioTrack->getFormat(), 1369 false, // createEncoder 1370 mAudioTrack); 1371 } 1372 1373 if (mAudioSource != NULL) { 1374 int64_t durationUs; 1375 if (mAudioTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) { 1376 Mutex::Autolock autoLock(mMiscStateLock); 1377 if (mDurationUs < 0 || durationUs > mDurationUs) { 1378 mDurationUs = durationUs; 1379 } 1380 } 1381 1382 status_t err = mAudioSource->start(); 1383 1384 if (err != OK) { 1385 mAudioSource.clear(); 1386 return err; 1387 } 1388 } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_QCELP)) { 1389 // For legacy reasons we're simply going to ignore the absence 1390 // of an audio decoder for QCELP instead of aborting playback 1391 // altogether. 1392 return OK; 1393 } 1394 1395 if (mAudioSource != NULL) { 1396 Mutex::Autolock autoLock(mStatsLock); 1397 TrackStat *stat = &mStats.mTracks.editItemAt(mStats.mAudioTrackIndex); 1398 1399 const char *component; 1400 if (!mAudioSource->getFormat() 1401 ->findCString(kKeyDecoderComponent, &component)) { 1402 component = "none"; 1403 } 1404 1405 stat->mDecoderName = component; 1406 } 1407 1408 return mAudioSource != NULL ? OK : UNKNOWN_ERROR; 1409} 1410 1411void AwesomePlayer::setVideoSource(sp<MediaSource> source) { 1412 CHECK(source != NULL); 1413 1414 mVideoTrack = source; 1415} 1416 1417status_t AwesomePlayer::initVideoDecoder(uint32_t flags) { 1418 1419 // Either the application or the DRM system can independently say 1420 // that there must be a hardware-protected path to an external video sink. 1421 // For now we always require a hardware-protected path to external video sink 1422 // if content is DRMed, but eventually this could be optional per DRM agent. 1423 // When the application wants protection, then 1424 // (USE_SURFACE_ALLOC && (mSurface != 0) && 1425 // (mSurface->getFlags() & ISurfaceComposer::eProtectedByApp)) 1426 // will be true, but that part is already handled by SurfaceFlinger. 1427 1428#ifdef DEBUG_HDCP 1429 // For debugging, we allow a system property to control the protected usage. 1430 // In case of uninitialized or unexpected property, we default to "DRM only". 1431 bool setProtectionBit = false; 1432 char value[PROPERTY_VALUE_MAX]; 1433 if (property_get("persist.sys.hdcp_checking", value, NULL)) { 1434 if (!strcmp(value, "never")) { 1435 // nop 1436 } else if (!strcmp(value, "always")) { 1437 setProtectionBit = true; 1438 } else if (!strcmp(value, "drm-only")) { 1439 if (mDecryptHandle != NULL) { 1440 setProtectionBit = true; 1441 } 1442 // property value is empty, or unexpected value 1443 } else { 1444 if (mDecryptHandle != NULL) { 1445 setProtectionBit = true; 1446 } 1447 } 1448 // can' read property value 1449 } else { 1450 if (mDecryptHandle != NULL) { 1451 setProtectionBit = true; 1452 } 1453 } 1454 // note that usage bit is already cleared, so no need to clear it in the "else" case 1455 if (setProtectionBit) { 1456 flags |= OMXCodec::kEnableGrallocUsageProtected; 1457 } 1458#else 1459 if (mDecryptHandle != NULL) { 1460 flags |= OMXCodec::kEnableGrallocUsageProtected; 1461 } 1462#endif 1463 ALOGV("initVideoDecoder flags=0x%x", flags); 1464 mVideoSource = OMXCodec::Create( 1465 mClient.interface(), mVideoTrack->getFormat(), 1466 false, // createEncoder 1467 mVideoTrack, 1468 NULL, flags, USE_SURFACE_ALLOC ? mNativeWindow : NULL); 1469 1470 if (mVideoSource != NULL) { 1471 int64_t durationUs; 1472 if (mVideoTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) { 1473 Mutex::Autolock autoLock(mMiscStateLock); 1474 if (mDurationUs < 0 || durationUs > mDurationUs) { 1475 mDurationUs = durationUs; 1476 } 1477 } 1478 1479 status_t err = mVideoSource->start(); 1480 1481 if (err != OK) { 1482 mVideoSource.clear(); 1483 return err; 1484 } 1485 } 1486 1487 if (mVideoSource != NULL) { 1488 const char *componentName; 1489 CHECK(mVideoSource->getFormat() 1490 ->findCString(kKeyDecoderComponent, &componentName)); 1491 1492 { 1493 Mutex::Autolock autoLock(mStatsLock); 1494 TrackStat *stat = &mStats.mTracks.editItemAt(mStats.mVideoTrackIndex); 1495 1496 stat->mDecoderName = componentName; 1497 } 1498 1499 static const char *kPrefix = "OMX.Nvidia."; 1500 static const char *kSuffix = ".decode"; 1501 static const size_t kSuffixLength = strlen(kSuffix); 1502 1503 size_t componentNameLength = strlen(componentName); 1504 1505 if (!strncmp(componentName, kPrefix, strlen(kPrefix)) 1506 && componentNameLength >= kSuffixLength 1507 && !strcmp(&componentName[ 1508 componentNameLength - kSuffixLength], kSuffix)) { 1509 modifyFlags(SLOW_DECODER_HACK, SET); 1510 } 1511 } 1512 1513 return mVideoSource != NULL ? OK : UNKNOWN_ERROR; 1514} 1515 1516void AwesomePlayer::finishSeekIfNecessary(int64_t videoTimeUs) { 1517 if (mSeeking == SEEK_VIDEO_ONLY) { 1518 mSeeking = NO_SEEK; 1519 return; 1520 } 1521 1522 if (mSeeking == NO_SEEK || (mFlags & SEEK_PREVIEW)) { 1523 return; 1524 } 1525 1526 if (mAudioPlayer != NULL) { 1527 ALOGV("seeking audio to %lld us (%.2f secs).", videoTimeUs, videoTimeUs / 1E6); 1528 1529 // If we don't have a video time, seek audio to the originally 1530 // requested seek time instead. 1531 1532 mAudioPlayer->seekTo(videoTimeUs < 0 ? mSeekTimeUs : videoTimeUs); 1533 mWatchForAudioSeekComplete = true; 1534 mWatchForAudioEOS = true; 1535 } else if (!mSeekNotificationSent) { 1536 // If we're playing video only, report seek complete now, 1537 // otherwise audio player will notify us later. 1538 notifyListener_l(MEDIA_SEEK_COMPLETE); 1539 mSeekNotificationSent = true; 1540 } 1541 1542 modifyFlags(FIRST_FRAME, SET); 1543 mSeeking = NO_SEEK; 1544 1545 if (mDecryptHandle != NULL) { 1546 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1547 Playback::PAUSE, 0); 1548 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, 1549 Playback::START, videoTimeUs / 1000); 1550 } 1551} 1552 1553void AwesomePlayer::onVideoEvent() { 1554 Mutex::Autolock autoLock(mLock); 1555 if (!mVideoEventPending) { 1556 // The event has been cancelled in reset_l() but had already 1557 // been scheduled for execution at that time. 1558 return; 1559 } 1560 mVideoEventPending = false; 1561 1562 if (mSeeking != NO_SEEK) { 1563 if (mVideoBuffer) { 1564 mVideoBuffer->release(); 1565 mVideoBuffer = NULL; 1566 } 1567 1568 if (mSeeking == SEEK && isStreamingHTTP() && mAudioSource != NULL 1569 && !(mFlags & SEEK_PREVIEW)) { 1570 // We're going to seek the video source first, followed by 1571 // the audio source. 1572 // In order to avoid jumps in the DataSource offset caused by 1573 // the audio codec prefetching data from the old locations 1574 // while the video codec is already reading data from the new 1575 // locations, we'll "pause" the audio source, causing it to 1576 // stop reading input data until a subsequent seek. 1577 1578 if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) { 1579 mAudioPlayer->pause(); 1580 1581 modifyFlags(AUDIO_RUNNING, CLEAR); 1582 } 1583 mAudioSource->pause(); 1584 } 1585 } 1586 1587 if (!mVideoBuffer) { 1588 MediaSource::ReadOptions options; 1589 if (mSeeking != NO_SEEK) { 1590 ALOGV("seeking to %lld us (%.2f secs)", mSeekTimeUs, mSeekTimeUs / 1E6); 1591 1592 options.setSeekTo( 1593 mSeekTimeUs, 1594 mSeeking == SEEK_VIDEO_ONLY 1595 ? MediaSource::ReadOptions::SEEK_NEXT_SYNC 1596 : MediaSource::ReadOptions::SEEK_CLOSEST); 1597 } 1598 for (;;) { 1599 status_t err = mVideoSource->read(&mVideoBuffer, &options); 1600 options.clearSeekTo(); 1601 1602 if (err != OK) { 1603 CHECK(mVideoBuffer == NULL); 1604 1605 if (err == INFO_FORMAT_CHANGED) { 1606 ALOGV("VideoSource signalled format change."); 1607 1608 notifyVideoSize_l(); 1609 1610 if (mVideoRenderer != NULL) { 1611 mVideoRendererIsPreview = false; 1612 initRenderer_l(); 1613 } 1614 continue; 1615 } 1616 1617 // So video playback is complete, but we may still have 1618 // a seek request pending that needs to be applied 1619 // to the audio track. 1620 if (mSeeking != NO_SEEK) { 1621 ALOGV("video stream ended while seeking!"); 1622 } 1623 finishSeekIfNecessary(-1); 1624 1625 if (mAudioPlayer != NULL 1626 && !(mFlags & (AUDIO_RUNNING | SEEK_PREVIEW))) { 1627 startAudioPlayer_l(); 1628 } 1629 1630 modifyFlags(VIDEO_AT_EOS, SET); 1631 postStreamDoneEvent_l(err); 1632 return; 1633 } 1634 1635 if (mVideoBuffer->range_length() == 0) { 1636 // Some decoders, notably the PV AVC software decoder 1637 // return spurious empty buffers that we just want to ignore. 1638 1639 mVideoBuffer->release(); 1640 mVideoBuffer = NULL; 1641 continue; 1642 } 1643 1644 break; 1645 } 1646 1647 { 1648 Mutex::Autolock autoLock(mStatsLock); 1649 ++mStats.mNumVideoFramesDecoded; 1650 } 1651 } 1652 1653 int64_t timeUs; 1654 CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &timeUs)); 1655 1656 mLastVideoTimeUs = timeUs; 1657 1658 if (mSeeking == SEEK_VIDEO_ONLY) { 1659 if (mSeekTimeUs > timeUs) { 1660 ALOGI("XXX mSeekTimeUs = %lld us, timeUs = %lld us", 1661 mSeekTimeUs, timeUs); 1662 } 1663 } 1664 1665 { 1666 Mutex::Autolock autoLock(mMiscStateLock); 1667 mVideoTimeUs = timeUs; 1668 } 1669 1670 SeekType wasSeeking = mSeeking; 1671 finishSeekIfNecessary(timeUs); 1672 1673 if (mAudioPlayer != NULL && !(mFlags & (AUDIO_RUNNING | SEEK_PREVIEW))) { 1674 status_t err = startAudioPlayer_l(); 1675 if (err != OK) { 1676 ALOGE("Starting the audio player failed w/ err %d", err); 1677 return; 1678 } 1679 } 1680 1681 if ((mFlags & TEXTPLAYER_INITIALIZED) && !(mFlags & (TEXT_RUNNING | SEEK_PREVIEW))) { 1682 mTextDriver->start(); 1683 modifyFlags(TEXT_RUNNING, SET); 1684 } 1685 1686 TimeSource *ts = 1687 ((mFlags & AUDIO_AT_EOS) || !(mFlags & AUDIOPLAYER_STARTED)) 1688 ? &mSystemTimeSource : mTimeSource; 1689 1690 if (mFlags & FIRST_FRAME) { 1691 modifyFlags(FIRST_FRAME, CLEAR); 1692 mSinceLastDropped = 0; 1693 mTimeSourceDeltaUs = ts->getRealTimeUs() - timeUs; 1694 } 1695 1696 int64_t realTimeUs, mediaTimeUs; 1697 if (!(mFlags & AUDIO_AT_EOS) && mAudioPlayer != NULL 1698 && mAudioPlayer->getMediaTimeMapping(&realTimeUs, &mediaTimeUs)) { 1699 mTimeSourceDeltaUs = realTimeUs - mediaTimeUs; 1700 } 1701 1702 if (wasSeeking == SEEK_VIDEO_ONLY) { 1703 int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs; 1704 1705 int64_t latenessUs = nowUs - timeUs; 1706 1707 if (latenessUs > 0) { 1708 ALOGI("after SEEK_VIDEO_ONLY we're late by %.2f secs", latenessUs / 1E6); 1709 } 1710 } 1711 1712 if (wasSeeking == NO_SEEK) { 1713 // Let's display the first frame after seeking right away. 1714 1715 int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs; 1716 1717 int64_t latenessUs = nowUs - timeUs; 1718 1719 if (latenessUs > 500000ll 1720 && mAudioPlayer != NULL 1721 && mAudioPlayer->getMediaTimeMapping( 1722 &realTimeUs, &mediaTimeUs)) { 1723 ALOGI("we're much too late (%.2f secs), video skipping ahead", 1724 latenessUs / 1E6); 1725 1726 mVideoBuffer->release(); 1727 mVideoBuffer = NULL; 1728 1729 mSeeking = SEEK_VIDEO_ONLY; 1730 mSeekTimeUs = mediaTimeUs; 1731 1732 postVideoEvent_l(); 1733 return; 1734 } 1735 1736 if (latenessUs > 40000) { 1737 // We're more than 40ms late. 1738 ALOGV("we're late by %lld us (%.2f secs)", 1739 latenessUs, latenessUs / 1E6); 1740 1741 if (!(mFlags & SLOW_DECODER_HACK) 1742 || mSinceLastDropped > FRAME_DROP_FREQ) 1743 { 1744 ALOGV("we're late by %lld us (%.2f secs) dropping " 1745 "one after %d frames", 1746 latenessUs, latenessUs / 1E6, mSinceLastDropped); 1747 1748 mSinceLastDropped = 0; 1749 mVideoBuffer->release(); 1750 mVideoBuffer = NULL; 1751 1752 { 1753 Mutex::Autolock autoLock(mStatsLock); 1754 ++mStats.mNumVideoFramesDropped; 1755 } 1756 1757 postVideoEvent_l(); 1758 return; 1759 } 1760 } 1761 1762 if (latenessUs < -10000) { 1763 // We're more than 10ms early. 1764 1765 postVideoEvent_l(10000); 1766 return; 1767 } 1768 } 1769 1770 if ((mNativeWindow != NULL) 1771 && (mVideoRendererIsPreview || mVideoRenderer == NULL)) { 1772 mVideoRendererIsPreview = false; 1773 1774 initRenderer_l(); 1775 } 1776 1777 if (mVideoRenderer != NULL) { 1778 mSinceLastDropped++; 1779 mVideoRenderer->render(mVideoBuffer); 1780 } 1781 1782 mVideoBuffer->release(); 1783 mVideoBuffer = NULL; 1784 1785 if (wasSeeking != NO_SEEK && (mFlags & SEEK_PREVIEW)) { 1786 modifyFlags(SEEK_PREVIEW, CLEAR); 1787 return; 1788 } 1789 1790 postVideoEvent_l(); 1791} 1792 1793void AwesomePlayer::postVideoEvent_l(int64_t delayUs) { 1794 if (mVideoEventPending) { 1795 return; 1796 } 1797 1798 mVideoEventPending = true; 1799 mQueue.postEventWithDelay(mVideoEvent, delayUs < 0 ? 10000 : delayUs); 1800} 1801 1802void AwesomePlayer::postStreamDoneEvent_l(status_t status) { 1803 if (mStreamDoneEventPending) { 1804 return; 1805 } 1806 mStreamDoneEventPending = true; 1807 1808 mStreamDoneStatus = status; 1809 mQueue.postEvent(mStreamDoneEvent); 1810} 1811 1812void AwesomePlayer::postBufferingEvent_l() { 1813 if (mBufferingEventPending) { 1814 return; 1815 } 1816 mBufferingEventPending = true; 1817 mQueue.postEventWithDelay(mBufferingEvent, 1000000ll); 1818} 1819 1820void AwesomePlayer::postVideoLagEvent_l() { 1821 if (mVideoLagEventPending) { 1822 return; 1823 } 1824 mVideoLagEventPending = true; 1825 mQueue.postEventWithDelay(mVideoLagEvent, 1000000ll); 1826} 1827 1828void AwesomePlayer::postCheckAudioStatusEvent(int64_t delayUs) { 1829 Mutex::Autolock autoLock(mAudioLock); 1830 if (mAudioStatusEventPending) { 1831 return; 1832 } 1833 mAudioStatusEventPending = true; 1834 // Do not honor delay when looping in order to limit audio gap 1835 if (mFlags & (LOOPING | AUTO_LOOPING)) { 1836 delayUs = 0; 1837 } 1838 mQueue.postEventWithDelay(mCheckAudioStatusEvent, delayUs); 1839} 1840 1841void AwesomePlayer::onCheckAudioStatus() { 1842 { 1843 Mutex::Autolock autoLock(mAudioLock); 1844 if (!mAudioStatusEventPending) { 1845 // Event was dispatched and while we were blocking on the mutex, 1846 // has already been cancelled. 1847 return; 1848 } 1849 1850 mAudioStatusEventPending = false; 1851 } 1852 1853 Mutex::Autolock autoLock(mLock); 1854 1855 if (mWatchForAudioSeekComplete && !mAudioPlayer->isSeeking()) { 1856 mWatchForAudioSeekComplete = false; 1857 1858 if (!mSeekNotificationSent) { 1859 notifyListener_l(MEDIA_SEEK_COMPLETE); 1860 mSeekNotificationSent = true; 1861 } 1862 1863 mSeeking = NO_SEEK; 1864 } 1865 1866 status_t finalStatus; 1867 if (mWatchForAudioEOS && mAudioPlayer->reachedEOS(&finalStatus)) { 1868 mWatchForAudioEOS = false; 1869 modifyFlags(AUDIO_AT_EOS, SET); 1870 modifyFlags(FIRST_FRAME, SET); 1871 postStreamDoneEvent_l(finalStatus); 1872 } 1873} 1874 1875status_t AwesomePlayer::prepare() { 1876 Mutex::Autolock autoLock(mLock); 1877 return prepare_l(); 1878} 1879 1880status_t AwesomePlayer::prepare_l() { 1881 if (mFlags & PREPARED) { 1882 return OK; 1883 } 1884 1885 if (mFlags & PREPARING) { 1886 return UNKNOWN_ERROR; 1887 } 1888 1889 mIsAsyncPrepare = false; 1890 status_t err = prepareAsync_l(); 1891 1892 if (err != OK) { 1893 return err; 1894 } 1895 1896 while (mFlags & PREPARING) { 1897 mPreparedCondition.wait(mLock); 1898 } 1899 1900 return mPrepareResult; 1901} 1902 1903status_t AwesomePlayer::prepareAsync() { 1904 Mutex::Autolock autoLock(mLock); 1905 1906 if (mFlags & PREPARING) { 1907 return UNKNOWN_ERROR; // async prepare already pending 1908 } 1909 1910 mIsAsyncPrepare = true; 1911 return prepareAsync_l(); 1912} 1913 1914status_t AwesomePlayer::prepareAsync_l() { 1915 if (mFlags & PREPARING) { 1916 return UNKNOWN_ERROR; // async prepare already pending 1917 } 1918 1919 if (!mQueueStarted) { 1920 mQueue.start(); 1921 mQueueStarted = true; 1922 } 1923 1924 modifyFlags(PREPARING, SET); 1925 mAsyncPrepareEvent = new AwesomeEvent( 1926 this, &AwesomePlayer::onPrepareAsyncEvent); 1927 1928 mQueue.postEvent(mAsyncPrepareEvent); 1929 1930 return OK; 1931} 1932 1933status_t AwesomePlayer::finishSetDataSource_l() { 1934 sp<DataSource> dataSource; 1935 1936 bool isWidevineStreaming = false; 1937 if (!strncasecmp("widevine://", mUri.string(), 11)) { 1938 isWidevineStreaming = true; 1939 1940 String8 newURI = String8("http://"); 1941 newURI.append(mUri.string() + 11); 1942 1943 mUri = newURI; 1944 } 1945 1946 AString sniffedMIME; 1947 1948 if (!strncasecmp("http://", mUri.string(), 7) 1949 || !strncasecmp("https://", mUri.string(), 8) 1950 || isWidevineStreaming) { 1951 mConnectingDataSource = HTTPBase::Create( 1952 (mFlags & INCOGNITO) 1953 ? HTTPBase::kFlagIncognito 1954 : 0); 1955 1956 if (mUIDValid) { 1957 mConnectingDataSource->setUID(mUID); 1958 } 1959 1960 String8 cacheConfig; 1961 bool disconnectAtHighwatermark; 1962 NuCachedSource2::RemoveCacheSpecificHeaders( 1963 &mUriHeaders, &cacheConfig, &disconnectAtHighwatermark); 1964 1965 mLock.unlock(); 1966 status_t err = mConnectingDataSource->connect(mUri, &mUriHeaders); 1967 mLock.lock(); 1968 1969 if (err != OK) { 1970 mConnectingDataSource.clear(); 1971 1972 ALOGI("mConnectingDataSource->connect() returned %d", err); 1973 return err; 1974 } 1975 1976 if (!isWidevineStreaming) { 1977 // The widevine extractor does its own caching. 1978 1979#if 0 1980 mCachedSource = new NuCachedSource2( 1981 new ThrottledSource( 1982 mConnectingDataSource, 50 * 1024 /* bytes/sec */)); 1983#else 1984 mCachedSource = new NuCachedSource2( 1985 mConnectingDataSource, 1986 cacheConfig.isEmpty() ? NULL : cacheConfig.string(), 1987 disconnectAtHighwatermark); 1988#endif 1989 1990 dataSource = mCachedSource; 1991 } else { 1992 dataSource = mConnectingDataSource; 1993 } 1994 1995 mConnectingDataSource.clear(); 1996 1997 String8 contentType = dataSource->getMIMEType(); 1998 1999 if (strncasecmp(contentType.string(), "audio/", 6)) { 2000 // We're not doing this for streams that appear to be audio-only 2001 // streams to ensure that even low bandwidth streams start 2002 // playing back fairly instantly. 2003 2004 // We're going to prefill the cache before trying to instantiate 2005 // the extractor below, as the latter is an operation that otherwise 2006 // could block on the datasource for a significant amount of time. 2007 // During that time we'd be unable to abort the preparation phase 2008 // without this prefill. 2009 if (mCachedSource != NULL) { 2010 // We're going to prefill the cache before trying to instantiate 2011 // the extractor below, as the latter is an operation that otherwise 2012 // could block on the datasource for a significant amount of time. 2013 // During that time we'd be unable to abort the preparation phase 2014 // without this prefill. 2015 2016 mLock.unlock(); 2017 2018 // Initially make sure we have at least 192 KB for the sniff 2019 // to complete without blocking. 2020 static const size_t kMinBytesForSniffing = 192 * 1024; 2021 2022 off64_t metaDataSize = -1ll; 2023 for (;;) { 2024 status_t finalStatus; 2025 size_t cachedDataRemaining = 2026 mCachedSource->approxDataRemaining(&finalStatus); 2027 2028 if (finalStatus != OK 2029 || (metaDataSize >= 0 2030 && cachedDataRemaining >= metaDataSize) 2031 || (mFlags & PREPARE_CANCELLED)) { 2032 break; 2033 } 2034 2035 ALOGV("now cached %d bytes of data", cachedDataRemaining); 2036 2037 if (metaDataSize < 0 2038 && cachedDataRemaining >= kMinBytesForSniffing) { 2039 String8 tmp; 2040 float confidence; 2041 sp<AMessage> meta; 2042 if (!dataSource->sniff(&tmp, &confidence, &meta)) { 2043 mLock.lock(); 2044 return UNKNOWN_ERROR; 2045 } 2046 2047 // We successfully identified the file's extractor to 2048 // be, remember this mime type so we don't have to 2049 // sniff it again when we call MediaExtractor::Create() 2050 // below. 2051 sniffedMIME = tmp.string(); 2052 2053 if (meta == NULL 2054 || !meta->findInt64( 2055 "meta-data-size", &metaDataSize)) { 2056 metaDataSize = kHighWaterMarkBytes; 2057 } 2058 2059 CHECK_GE(metaDataSize, 0ll); 2060 ALOGV("metaDataSize = %lld bytes", metaDataSize); 2061 } 2062 2063 usleep(200000); 2064 } 2065 2066 mLock.lock(); 2067 } 2068 2069 if (mFlags & PREPARE_CANCELLED) { 2070 ALOGI("Prepare cancelled while waiting for initial cache fill."); 2071 return UNKNOWN_ERROR; 2072 } 2073 } 2074 } else { 2075 dataSource = DataSource::CreateFromURI(mUri.string(), &mUriHeaders); 2076 } 2077 2078 if (dataSource == NULL) { 2079 return UNKNOWN_ERROR; 2080 } 2081 2082 sp<MediaExtractor> extractor; 2083 2084 if (isWidevineStreaming) { 2085 String8 mimeType; 2086 float confidence; 2087 sp<AMessage> dummy; 2088 bool success = SniffWVM(dataSource, &mimeType, &confidence, &dummy); 2089 2090 if (!success 2091 || strcasecmp( 2092 mimeType.string(), MEDIA_MIMETYPE_CONTAINER_WVM)) { 2093 return ERROR_UNSUPPORTED; 2094 } 2095 2096 mWVMExtractor = new WVMExtractor(dataSource); 2097 mWVMExtractor->setAdaptiveStreamingMode(true); 2098 if (mUIDValid) 2099 mWVMExtractor->setUID(mUID); 2100 extractor = mWVMExtractor; 2101 } else { 2102 extractor = MediaExtractor::Create( 2103 dataSource, sniffedMIME.empty() ? NULL : sniffedMIME.c_str()); 2104 2105 if (extractor == NULL) { 2106 return UNKNOWN_ERROR; 2107 } 2108 } 2109 2110 if (extractor->getDrmFlag()) { 2111 checkDrmStatus(dataSource); 2112 } 2113 2114 status_t err = setDataSource_l(extractor); 2115 2116 if (err != OK) { 2117 mWVMExtractor.clear(); 2118 2119 return err; 2120 } 2121 2122 return OK; 2123} 2124 2125void AwesomePlayer::abortPrepare(status_t err) { 2126 CHECK(err != OK); 2127 2128 if (mIsAsyncPrepare) { 2129 notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err); 2130 } 2131 2132 mPrepareResult = err; 2133 modifyFlags((PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED), CLEAR); 2134 mAsyncPrepareEvent = NULL; 2135 mPreparedCondition.broadcast(); 2136} 2137 2138// static 2139bool AwesomePlayer::ContinuePreparation(void *cookie) { 2140 AwesomePlayer *me = static_cast<AwesomePlayer *>(cookie); 2141 2142 return (me->mFlags & PREPARE_CANCELLED) == 0; 2143} 2144 2145void AwesomePlayer::onPrepareAsyncEvent() { 2146 Mutex::Autolock autoLock(mLock); 2147 2148 if (mFlags & PREPARE_CANCELLED) { 2149 ALOGI("prepare was cancelled before doing anything"); 2150 abortPrepare(UNKNOWN_ERROR); 2151 return; 2152 } 2153 2154 if (mUri.size() > 0) { 2155 status_t err = finishSetDataSource_l(); 2156 2157 if (err != OK) { 2158 abortPrepare(err); 2159 return; 2160 } 2161 } 2162 2163 if (mVideoTrack != NULL && mVideoSource == NULL) { 2164 status_t err = initVideoDecoder(); 2165 2166 if (err != OK) { 2167 abortPrepare(err); 2168 return; 2169 } 2170 } 2171 2172 if (mAudioTrack != NULL && mAudioSource == NULL) { 2173 status_t err = initAudioDecoder(); 2174 2175 if (err != OK) { 2176 abortPrepare(err); 2177 return; 2178 } 2179 } 2180 2181 modifyFlags(PREPARING_CONNECTED, SET); 2182 2183 if (isStreamingHTTP()) { 2184 postBufferingEvent_l(); 2185 } else { 2186 finishAsyncPrepare_l(); 2187 } 2188} 2189 2190void AwesomePlayer::finishAsyncPrepare_l() { 2191 if (mIsAsyncPrepare) { 2192 if (mVideoSource == NULL) { 2193 notifyListener_l(MEDIA_SET_VIDEO_SIZE, 0, 0); 2194 } else { 2195 notifyVideoSize_l(); 2196 } 2197 2198 notifyListener_l(MEDIA_PREPARED); 2199 } 2200 2201 mPrepareResult = OK; 2202 modifyFlags((PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED), CLEAR); 2203 modifyFlags(PREPARED, SET); 2204 mAsyncPrepareEvent = NULL; 2205 mPreparedCondition.broadcast(); 2206} 2207 2208uint32_t AwesomePlayer::flags() const { 2209 return mExtractorFlags; 2210} 2211 2212void AwesomePlayer::postAudioEOS(int64_t delayUs) { 2213 postCheckAudioStatusEvent(delayUs); 2214} 2215 2216void AwesomePlayer::postAudioSeekComplete() { 2217 postCheckAudioStatusEvent(0); 2218} 2219 2220status_t AwesomePlayer::setParameter(int key, const Parcel &request) { 2221 switch (key) { 2222 case KEY_PARAMETER_CACHE_STAT_COLLECT_FREQ_MS: 2223 { 2224 return setCacheStatCollectFreq(request); 2225 } 2226 case KEY_PARAMETER_PLAYBACK_RATE_PERMILLE: 2227 { 2228 if (mAudioPlayer != NULL) { 2229 return mAudioPlayer->setPlaybackRatePermille(request.readInt32()); 2230 } else { 2231 return NO_INIT; 2232 } 2233 } 2234 default: 2235 { 2236 return ERROR_UNSUPPORTED; 2237 } 2238 } 2239} 2240 2241status_t AwesomePlayer::setCacheStatCollectFreq(const Parcel &request) { 2242 if (mCachedSource != NULL) { 2243 int32_t freqMs = request.readInt32(); 2244 ALOGD("Request to keep cache stats in the past %d ms", 2245 freqMs); 2246 return mCachedSource->setCacheStatCollectFreq(freqMs); 2247 } 2248 return ERROR_UNSUPPORTED; 2249} 2250 2251status_t AwesomePlayer::getParameter(int key, Parcel *reply) { 2252 switch (key) { 2253 case KEY_PARAMETER_AUDIO_CHANNEL_COUNT: 2254 { 2255 int32_t channelCount; 2256 if (mAudioTrack == 0 || 2257 !mAudioTrack->getFormat()->findInt32(kKeyChannelCount, &channelCount)) { 2258 channelCount = 0; 2259 } 2260 reply->writeInt32(channelCount); 2261 } 2262 return OK; 2263 default: 2264 { 2265 return ERROR_UNSUPPORTED; 2266 } 2267 } 2268} 2269 2270status_t AwesomePlayer::getTrackInfo(Parcel *reply) const { 2271 Mutex::Autolock autoLock(mTimedTextLock); 2272 if (mTextDriver == NULL) { 2273 return INVALID_OPERATION; 2274 } 2275 2276 reply->writeInt32(mTextDriver->countExternalTracks() + 2277 mExtractor->countTracks()); 2278 for (size_t i = 0; i < mExtractor->countTracks(); ++i) { 2279 sp<MetaData> meta = mExtractor->getTrackMetaData(i); 2280 2281 const char *_mime; 2282 CHECK(meta->findCString(kKeyMIMEType, &_mime)); 2283 2284 String8 mime = String8(_mime); 2285 2286 reply->writeInt32(2); // 2 fields 2287 2288 if (!strncasecmp(mime.string(), "video/", 6)) { 2289 reply->writeInt32(MEDIA_TRACK_TYPE_VIDEO); 2290 } else if (!strncasecmp(mime.string(), "audio/", 6)) { 2291 reply->writeInt32(MEDIA_TRACK_TYPE_AUDIO); 2292 } else if (!strcasecmp(mime.string(), MEDIA_MIMETYPE_TEXT_3GPP)) { 2293 reply->writeInt32(MEDIA_TRACK_TYPE_TIMEDTEXT); 2294 } else { 2295 reply->writeInt32(MEDIA_TRACK_TYPE_UNKNOWN); 2296 } 2297 2298 const char *lang; 2299 if (meta->findCString(kKeyMediaLanguage, &lang)) { 2300 reply->writeString16(String16(lang)); 2301 } else { 2302 reply->writeString16(String16("")); 2303 } 2304 } 2305 2306 mTextDriver->getExternalTrackInfo(reply); 2307 return OK; 2308} 2309 2310// FIXME: 2311// At present, only timed text track is able to be selected or unselected. 2312status_t AwesomePlayer::selectTrack(size_t trackIndex, bool select) { 2313 Mutex::Autolock autoLock(mTimedTextLock); 2314 if (mTextDriver == NULL) { 2315 return INVALID_OPERATION; 2316 } 2317 2318 if (trackIndex >= mExtractor->countTracks() 2319 + mTextDriver->countExternalTracks()) { 2320 return BAD_VALUE; 2321 } 2322 2323 if (trackIndex < mExtractor->countTracks()) { 2324 sp<MetaData> meta = mExtractor->getTrackMetaData(trackIndex); 2325 const char *_mime; 2326 CHECK(meta->findCString(kKeyMIMEType, &_mime)); 2327 String8 mime = String8(_mime); 2328 2329 if (strcasecmp(mime.string(), MEDIA_MIMETYPE_TEXT_3GPP)) { 2330 return ERROR_UNSUPPORTED; 2331 } 2332 } 2333 2334 status_t err = OK; 2335 if (select) { 2336 err = mTextDriver->selectTrack(trackIndex); 2337 if (err == OK) { 2338 modifyFlags(TEXTPLAYER_INITIALIZED, SET); 2339 if (mFlags & PLAYING && !(mFlags & TEXT_RUNNING)) { 2340 mTextDriver->start(); 2341 modifyFlags(TEXT_RUNNING, SET); 2342 } 2343 } 2344 } else { 2345 err = mTextDriver->unselectTrack(trackIndex); 2346 if (err == OK) { 2347 modifyFlags(TEXTPLAYER_INITIALIZED, CLEAR); 2348 modifyFlags(TEXT_RUNNING, CLEAR); 2349 } 2350 } 2351 return err; 2352} 2353 2354size_t AwesomePlayer::countTracks() const { 2355 return mExtractor->countTracks() + mTextDriver->countExternalTracks(); 2356} 2357 2358status_t AwesomePlayer::invoke(const Parcel &request, Parcel *reply) { 2359 if (NULL == reply) { 2360 return android::BAD_VALUE; 2361 } 2362 int32_t methodId; 2363 status_t ret = request.readInt32(&methodId); 2364 if (ret != android::OK) { 2365 return ret; 2366 } 2367 switch(methodId) { 2368 case INVOKE_ID_GET_TRACK_INFO: 2369 { 2370 return getTrackInfo(reply); 2371 } 2372 case INVOKE_ID_ADD_EXTERNAL_SOURCE: 2373 { 2374 Mutex::Autolock autoLock(mTimedTextLock); 2375 if (mTextDriver == NULL) { 2376 mTextDriver = new TimedTextDriver(mListener); 2377 } 2378 // String values written in Parcel are UTF-16 values. 2379 String8 uri(request.readString16()); 2380 String8 mimeType(request.readString16()); 2381 size_t nTracks = countTracks(); 2382 return mTextDriver->addOutOfBandTextSource(nTracks, uri, mimeType); 2383 } 2384 case INVOKE_ID_ADD_EXTERNAL_SOURCE_FD: 2385 { 2386 Mutex::Autolock autoLock(mTimedTextLock); 2387 if (mTextDriver == NULL) { 2388 mTextDriver = new TimedTextDriver(mListener); 2389 } 2390 int fd = request.readFileDescriptor(); 2391 off64_t offset = request.readInt64(); 2392 off64_t length = request.readInt64(); 2393 String8 mimeType(request.readString16()); 2394 size_t nTracks = countTracks(); 2395 return mTextDriver->addOutOfBandTextSource( 2396 nTracks, fd, offset, length, mimeType); 2397 } 2398 case INVOKE_ID_SELECT_TRACK: 2399 { 2400 int trackIndex = request.readInt32(); 2401 return selectTrack(trackIndex, true); 2402 } 2403 case INVOKE_ID_UNSELECT_TRACK: 2404 { 2405 int trackIndex = request.readInt32(); 2406 return selectTrack(trackIndex, false); 2407 } 2408 default: 2409 { 2410 return ERROR_UNSUPPORTED; 2411 } 2412 } 2413 // It will not reach here. 2414 return OK; 2415} 2416 2417bool AwesomePlayer::isStreamingHTTP() const { 2418 return mCachedSource != NULL || mWVMExtractor != NULL; 2419} 2420 2421status_t AwesomePlayer::dump(int fd, const Vector<String16> &args) const { 2422 Mutex::Autolock autoLock(mStatsLock); 2423 2424 FILE *out = fdopen(dup(fd), "w"); 2425 2426 fprintf(out, " AwesomePlayer\n"); 2427 if (mStats.mFd < 0) { 2428 fprintf(out, " URI(%s)", mStats.mURI.string()); 2429 } else { 2430 fprintf(out, " fd(%d)", mStats.mFd); 2431 } 2432 2433 fprintf(out, ", flags(0x%08x)", mStats.mFlags); 2434 2435 if (mStats.mBitrate >= 0) { 2436 fprintf(out, ", bitrate(%lld bps)", mStats.mBitrate); 2437 } 2438 2439 fprintf(out, "\n"); 2440 2441 for (size_t i = 0; i < mStats.mTracks.size(); ++i) { 2442 const TrackStat &stat = mStats.mTracks.itemAt(i); 2443 2444 fprintf(out, " Track %d\n", i + 1); 2445 fprintf(out, " MIME(%s)", stat.mMIME.string()); 2446 2447 if (!stat.mDecoderName.isEmpty()) { 2448 fprintf(out, ", decoder(%s)", stat.mDecoderName.string()); 2449 } 2450 2451 fprintf(out, "\n"); 2452 2453 if ((ssize_t)i == mStats.mVideoTrackIndex) { 2454 fprintf(out, 2455 " videoDimensions(%d x %d), " 2456 "numVideoFramesDecoded(%lld), " 2457 "numVideoFramesDropped(%lld)\n", 2458 mStats.mVideoWidth, 2459 mStats.mVideoHeight, 2460 mStats.mNumVideoFramesDecoded, 2461 mStats.mNumVideoFramesDropped); 2462 } 2463 } 2464 2465 fclose(out); 2466 out = NULL; 2467 2468 return OK; 2469} 2470 2471void AwesomePlayer::modifyFlags(unsigned value, FlagMode mode) { 2472 switch (mode) { 2473 case SET: 2474 mFlags |= value; 2475 break; 2476 case CLEAR: 2477 mFlags &= ~value; 2478 break; 2479 case ASSIGN: 2480 mFlags = value; 2481 break; 2482 default: 2483 TRESPASS(); 2484 } 2485 2486 { 2487 Mutex::Autolock autoLock(mStatsLock); 2488 mStats.mFlags = mFlags; 2489 } 2490} 2491 2492} // namespace android 2493