GenericSource.cpp revision b41fd0d4929f0a89811bafcc4fd944b128f00ce2
1/* 2 * Copyright (C) 2012 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 "GenericSource" 19 20#include "GenericSource.h" 21 22#include "AnotherPacketSource.h" 23 24#include <media/IMediaHTTPService.h> 25#include <media/stagefright/foundation/ABuffer.h> 26#include <media/stagefright/foundation/ADebug.h> 27#include <media/stagefright/foundation/AMessage.h> 28#include <media/stagefright/DataSource.h> 29#include <media/stagefright/FileSource.h> 30#include <media/stagefright/MediaBuffer.h> 31#include <media/stagefright/MediaDefs.h> 32#include <media/stagefright/MediaExtractor.h> 33#include <media/stagefright/MediaSource.h> 34#include <media/stagefright/MetaData.h> 35#include <media/stagefright/Utils.h> 36#include "../../libstagefright/include/DRMExtractor.h" 37#include "../../libstagefright/include/NuCachedSource2.h" 38#include "../../libstagefright/include/WVMExtractor.h" 39#include "../../libstagefright/include/HTTPBase.h" 40 41namespace android { 42 43static int64_t kLowWaterMarkUs = 2000000ll; // 2secs 44static int64_t kHighWaterMarkUs = 5000000ll; // 5secs 45static const ssize_t kLowWaterMarkBytes = 40000; 46static const ssize_t kHighWaterMarkBytes = 200000; 47 48NuPlayer::GenericSource::GenericSource( 49 const sp<AMessage> ¬ify, 50 bool uidValid, 51 uid_t uid) 52 : Source(notify), 53 mAudioTimeUs(0), 54 mAudioLastDequeueTimeUs(0), 55 mVideoTimeUs(0), 56 mVideoLastDequeueTimeUs(0), 57 mFetchSubtitleDataGeneration(0), 58 mFetchTimedTextDataGeneration(0), 59 mDurationUs(-1ll), 60 mAudioIsVorbis(false), 61 mIsWidevine(false), 62 mIsSecure(false), 63 mIsStreaming(false), 64 mUIDValid(uidValid), 65 mUID(uid), 66 mFd(-1), 67 mDrmManagerClient(NULL), 68 mBitrate(-1ll), 69 mPollBufferingGeneration(0), 70 mPendingReadBufferTypes(0), 71 mBuffering(false), 72 mPrepareBuffering(false), 73 mPrevBufferPercentage(-1) { 74 resetDataSource(); 75 DataSource::RegisterDefaultSniffers(); 76} 77 78void NuPlayer::GenericSource::resetDataSource() { 79 mHTTPService.clear(); 80 mHttpSource.clear(); 81 mUri.clear(); 82 mUriHeaders.clear(); 83 if (mFd >= 0) { 84 close(mFd); 85 mFd = -1; 86 } 87 mOffset = 0; 88 mLength = 0; 89 setDrmPlaybackStatusIfNeeded(Playback::STOP, 0); 90 mDecryptHandle = NULL; 91 mDrmManagerClient = NULL; 92 mStarted = false; 93 mStopRead = true; 94} 95 96status_t NuPlayer::GenericSource::setDataSource( 97 const sp<IMediaHTTPService> &httpService, 98 const char *url, 99 const KeyedVector<String8, String8> *headers) { 100 resetDataSource(); 101 102 mHTTPService = httpService; 103 mUri = url; 104 105 if (headers) { 106 mUriHeaders = *headers; 107 } 108 109 // delay data source creation to prepareAsync() to avoid blocking 110 // the calling thread in setDataSource for any significant time. 111 return OK; 112} 113 114status_t NuPlayer::GenericSource::setDataSource( 115 int fd, int64_t offset, int64_t length) { 116 resetDataSource(); 117 118 mFd = dup(fd); 119 mOffset = offset; 120 mLength = length; 121 122 // delay data source creation to prepareAsync() to avoid blocking 123 // the calling thread in setDataSource for any significant time. 124 return OK; 125} 126 127status_t NuPlayer::GenericSource::setDataSource(const sp<DataSource>& source) { 128 resetDataSource(); 129 mDataSource = source; 130 return OK; 131} 132 133sp<MetaData> NuPlayer::GenericSource::getFileFormatMeta() const { 134 return mFileMeta; 135} 136 137status_t NuPlayer::GenericSource::initFromDataSource() { 138 sp<MediaExtractor> extractor; 139 String8 mimeType; 140 float confidence; 141 sp<AMessage> dummy; 142 bool isWidevineStreaming = false; 143 144 CHECK(mDataSource != NULL); 145 146 if (mIsWidevine) { 147 isWidevineStreaming = SniffWVM( 148 mDataSource, &mimeType, &confidence, &dummy); 149 if (!isWidevineStreaming || 150 strcasecmp( 151 mimeType.string(), MEDIA_MIMETYPE_CONTAINER_WVM)) { 152 ALOGE("unsupported widevine mime: %s", mimeType.string()); 153 return UNKNOWN_ERROR; 154 } 155 } else if (mIsStreaming) { 156 if (!mDataSource->sniff(&mimeType, &confidence, &dummy)) { 157 return UNKNOWN_ERROR; 158 } 159 isWidevineStreaming = !strcasecmp( 160 mimeType.string(), MEDIA_MIMETYPE_CONTAINER_WVM); 161 } 162 163 if (isWidevineStreaming) { 164 // we don't want cached source for widevine streaming. 165 mCachedSource.clear(); 166 mDataSource = mHttpSource; 167 mWVMExtractor = new WVMExtractor(mDataSource); 168 mWVMExtractor->setAdaptiveStreamingMode(true); 169 if (mUIDValid) { 170 mWVMExtractor->setUID(mUID); 171 } 172 extractor = mWVMExtractor; 173 } else { 174 extractor = MediaExtractor::Create(mDataSource, 175 mimeType.isEmpty() ? NULL : mimeType.string()); 176 } 177 178 if (extractor == NULL) { 179 return UNKNOWN_ERROR; 180 } 181 182 if (extractor->getDrmFlag()) { 183 checkDrmStatus(mDataSource); 184 } 185 186 mFileMeta = extractor->getMetaData(); 187 if (mFileMeta != NULL) { 188 int64_t duration; 189 if (mFileMeta->findInt64(kKeyDuration, &duration)) { 190 mDurationUs = duration; 191 } 192 193 if (!mIsWidevine) { 194 // Check mime to see if we actually have a widevine source. 195 // If the data source is not URL-type (eg. file source), we 196 // won't be able to tell until now. 197 const char *fileMime; 198 if (mFileMeta->findCString(kKeyMIMEType, &fileMime) 199 && !strncasecmp(fileMime, "video/wvm", 9)) { 200 mIsWidevine = true; 201 } 202 } 203 } 204 205 int32_t totalBitrate = 0; 206 207 size_t numtracks = extractor->countTracks(); 208 if (numtracks == 0) { 209 return UNKNOWN_ERROR; 210 } 211 212 for (size_t i = 0; i < numtracks; ++i) { 213 sp<MediaSource> track = extractor->getTrack(i); 214 215 sp<MetaData> meta = extractor->getTrackMetaData(i); 216 217 const char *mime; 218 CHECK(meta->findCString(kKeyMIMEType, &mime)); 219 220 // Do the string compare immediately with "mime", 221 // we can't assume "mime" would stay valid after another 222 // extractor operation, some extractors might modify meta 223 // during getTrack() and make it invalid. 224 if (!strncasecmp(mime, "audio/", 6)) { 225 if (mAudioTrack.mSource == NULL) { 226 mAudioTrack.mIndex = i; 227 mAudioTrack.mSource = track; 228 mAudioTrack.mPackets = 229 new AnotherPacketSource(mAudioTrack.mSource->getFormat()); 230 231 if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)) { 232 mAudioIsVorbis = true; 233 } else { 234 mAudioIsVorbis = false; 235 } 236 } 237 } else if (!strncasecmp(mime, "video/", 6)) { 238 if (mVideoTrack.mSource == NULL) { 239 mVideoTrack.mIndex = i; 240 mVideoTrack.mSource = track; 241 mVideoTrack.mPackets = 242 new AnotherPacketSource(mVideoTrack.mSource->getFormat()); 243 244 // check if the source requires secure buffers 245 int32_t secure; 246 if (meta->findInt32(kKeyRequiresSecureBuffers, &secure) 247 && secure) { 248 mIsSecure = true; 249 if (mUIDValid) { 250 extractor->setUID(mUID); 251 } 252 } 253 } 254 } 255 256 if (track != NULL) { 257 mSources.push(track); 258 int64_t durationUs; 259 if (meta->findInt64(kKeyDuration, &durationUs)) { 260 if (durationUs > mDurationUs) { 261 mDurationUs = durationUs; 262 } 263 } 264 265 int32_t bitrate; 266 if (totalBitrate >= 0 && meta->findInt32(kKeyBitRate, &bitrate)) { 267 totalBitrate += bitrate; 268 } else { 269 totalBitrate = -1; 270 } 271 } 272 } 273 274 mBitrate = totalBitrate; 275 276 return OK; 277} 278 279status_t NuPlayer::GenericSource::startSources() { 280 // Start the selected A/V tracks now before we start buffering. 281 // Widevine sources might re-initialize crypto when starting, if we delay 282 // this to start(), all data buffered during prepare would be wasted. 283 // (We don't actually start reading until start().) 284 if (mAudioTrack.mSource != NULL && mAudioTrack.mSource->start() != OK) { 285 ALOGE("failed to start audio track!"); 286 return UNKNOWN_ERROR; 287 } 288 289 if (mVideoTrack.mSource != NULL && mVideoTrack.mSource->start() != OK) { 290 ALOGE("failed to start video track!"); 291 return UNKNOWN_ERROR; 292 } 293 294 return OK; 295} 296 297void NuPlayer::GenericSource::checkDrmStatus(const sp<DataSource>& dataSource) { 298 dataSource->getDrmInfo(mDecryptHandle, &mDrmManagerClient); 299 if (mDecryptHandle != NULL) { 300 CHECK(mDrmManagerClient); 301 if (RightsStatus::RIGHTS_VALID != mDecryptHandle->status) { 302 sp<AMessage> msg = dupNotify(); 303 msg->setInt32("what", kWhatDrmNoLicense); 304 msg->post(); 305 } 306 } 307} 308 309int64_t NuPlayer::GenericSource::getLastReadPosition() { 310 if (mAudioTrack.mSource != NULL) { 311 return mAudioTimeUs; 312 } else if (mVideoTrack.mSource != NULL) { 313 return mVideoTimeUs; 314 } else { 315 return 0; 316 } 317} 318 319status_t NuPlayer::GenericSource::setBuffers( 320 bool audio, Vector<MediaBuffer *> &buffers) { 321 if (mIsSecure && !audio) { 322 return mVideoTrack.mSource->setBuffers(buffers); 323 } 324 return INVALID_OPERATION; 325} 326 327bool NuPlayer::GenericSource::isStreaming() const { 328 return mIsStreaming; 329} 330 331NuPlayer::GenericSource::~GenericSource() { 332 if (mLooper != NULL) { 333 mLooper->unregisterHandler(id()); 334 mLooper->stop(); 335 } 336 resetDataSource(); 337} 338 339void NuPlayer::GenericSource::prepareAsync() { 340 if (mLooper == NULL) { 341 mLooper = new ALooper; 342 mLooper->setName("generic"); 343 mLooper->start(); 344 345 mLooper->registerHandler(this); 346 } 347 348 sp<AMessage> msg = new AMessage(kWhatPrepareAsync, this); 349 msg->post(); 350} 351 352void NuPlayer::GenericSource::onPrepareAsync() { 353 // delayed data source creation 354 if (mDataSource == NULL) { 355 // set to false first, if the extractor 356 // comes back as secure, set it to true then. 357 mIsSecure = false; 358 359 if (!mUri.empty()) { 360 const char* uri = mUri.c_str(); 361 String8 contentType; 362 mIsWidevine = !strncasecmp(uri, "widevine://", 11); 363 364 if (!strncasecmp("http://", uri, 7) 365 || !strncasecmp("https://", uri, 8) 366 || mIsWidevine) { 367 mHttpSource = DataSource::CreateMediaHTTP(mHTTPService); 368 if (mHttpSource == NULL) { 369 ALOGE("Failed to create http source!"); 370 notifyPreparedAndCleanup(UNKNOWN_ERROR); 371 return; 372 } 373 } 374 375 mDataSource = DataSource::CreateFromURI( 376 mHTTPService, uri, &mUriHeaders, &contentType, 377 static_cast<HTTPBase *>(mHttpSource.get())); 378 } else { 379 mIsWidevine = false; 380 381 mDataSource = new FileSource(mFd, mOffset, mLength); 382 mFd = -1; 383 } 384 385 if (mDataSource == NULL) { 386 ALOGE("Failed to create data source!"); 387 notifyPreparedAndCleanup(UNKNOWN_ERROR); 388 return; 389 } 390 } 391 392 if (mDataSource->flags() & DataSource::kIsCachingDataSource) { 393 mCachedSource = static_cast<NuCachedSource2 *>(mDataSource.get()); 394 } 395 396 // For widevine or other cached streaming cases, we need to wait for 397 // enough buffering before reporting prepared. 398 // Note that even when URL doesn't start with widevine://, mIsWidevine 399 // could still be set to true later, if the streaming or file source 400 // is sniffed to be widevine. We don't want to buffer for file source 401 // in that case, so must check the flag now. 402 mIsStreaming = (mIsWidevine || mCachedSource != NULL); 403 404 // init extractor from data source 405 status_t err = initFromDataSource(); 406 407 if (err != OK) { 408 ALOGE("Failed to init from data source!"); 409 notifyPreparedAndCleanup(err); 410 return; 411 } 412 413 if (mVideoTrack.mSource != NULL) { 414 sp<MetaData> meta = doGetFormatMeta(false /* audio */); 415 sp<AMessage> msg = new AMessage; 416 err = convertMetaDataToMessage(meta, &msg); 417 if(err != OK) { 418 notifyPreparedAndCleanup(err); 419 return; 420 } 421 notifyVideoSizeChanged(msg); 422 } 423 424 notifyFlagsChanged( 425 (mIsSecure ? FLAG_SECURE : 0) 426 | (mDecryptHandle != NULL ? FLAG_PROTECTED : 0) 427 | FLAG_CAN_PAUSE 428 | FLAG_CAN_SEEK_BACKWARD 429 | FLAG_CAN_SEEK_FORWARD 430 | FLAG_CAN_SEEK); 431 432 if (mIsSecure) { 433 // secure decoders must be instantiated before starting widevine source 434 sp<AMessage> reply = new AMessage(kWhatSecureDecodersInstantiated, this); 435 notifyInstantiateSecureDecoders(reply); 436 } else { 437 finishPrepareAsync(); 438 } 439} 440 441void NuPlayer::GenericSource::onSecureDecodersInstantiated(status_t err) { 442 if (err != OK) { 443 ALOGE("Failed to instantiate secure decoders!"); 444 notifyPreparedAndCleanup(err); 445 return; 446 } 447 finishPrepareAsync(); 448} 449 450void NuPlayer::GenericSource::finishPrepareAsync() { 451 status_t err = startSources(); 452 if (err != OK) { 453 ALOGE("Failed to init start data source!"); 454 notifyPreparedAndCleanup(err); 455 return; 456 } 457 458 if (mIsStreaming) { 459 mPrepareBuffering = true; 460 461 ensureCacheIsFetching(); 462 restartPollBuffering(); 463 } else { 464 notifyPrepared(); 465 } 466} 467 468void NuPlayer::GenericSource::notifyPreparedAndCleanup(status_t err) { 469 if (err != OK) { 470 { 471 sp<DataSource> dataSource = mDataSource; 472 sp<NuCachedSource2> cachedSource = mCachedSource; 473 sp<DataSource> httpSource = mHttpSource; 474 { 475 Mutex::Autolock _l(mDisconnectLock); 476 mDataSource.clear(); 477 mDrmManagerClient = NULL; 478 mCachedSource.clear(); 479 mHttpSource.clear(); 480 } 481 } 482 mBitrate = -1; 483 484 cancelPollBuffering(); 485 } 486 notifyPrepared(err); 487} 488 489void NuPlayer::GenericSource::start() { 490 ALOGI("start"); 491 492 mStopRead = false; 493 if (mAudioTrack.mSource != NULL) { 494 postReadBuffer(MEDIA_TRACK_TYPE_AUDIO); 495 } 496 497 if (mVideoTrack.mSource != NULL) { 498 postReadBuffer(MEDIA_TRACK_TYPE_VIDEO); 499 } 500 501 setDrmPlaybackStatusIfNeeded(Playback::START, getLastReadPosition() / 1000); 502 mStarted = true; 503 504 (new AMessage(kWhatStart, this))->post(); 505} 506 507void NuPlayer::GenericSource::stop() { 508 // nothing to do, just account for DRM playback status 509 setDrmPlaybackStatusIfNeeded(Playback::STOP, 0); 510 mStarted = false; 511 if (mIsWidevine || mIsSecure) { 512 // For widevine or secure sources we need to prevent any further reads. 513 sp<AMessage> msg = new AMessage(kWhatStopWidevine, this); 514 sp<AMessage> response; 515 (void) msg->postAndAwaitResponse(&response); 516 } 517} 518 519void NuPlayer::GenericSource::pause() { 520 // nothing to do, just account for DRM playback status 521 setDrmPlaybackStatusIfNeeded(Playback::PAUSE, 0); 522 mStarted = false; 523} 524 525void NuPlayer::GenericSource::resume() { 526 // nothing to do, just account for DRM playback status 527 setDrmPlaybackStatusIfNeeded(Playback::START, getLastReadPosition() / 1000); 528 mStarted = true; 529 530 (new AMessage(kWhatResume, this))->post(); 531} 532 533void NuPlayer::GenericSource::disconnect() { 534 sp<DataSource> dataSource, httpSource; 535 { 536 Mutex::Autolock _l(mDisconnectLock); 537 dataSource = mDataSource; 538 httpSource = mHttpSource; 539 } 540 541 if (dataSource != NULL) { 542 // disconnect data source 543 if (dataSource->flags() & DataSource::kIsCachingDataSource) { 544 static_cast<NuCachedSource2 *>(dataSource.get())->disconnect(); 545 } 546 } else if (httpSource != NULL) { 547 static_cast<HTTPBase *>(httpSource.get())->disconnect(); 548 } 549} 550 551void NuPlayer::GenericSource::setDrmPlaybackStatusIfNeeded(int playbackStatus, int64_t position) { 552 if (mDecryptHandle != NULL) { 553 mDrmManagerClient->setPlaybackStatus(mDecryptHandle, playbackStatus, position); 554 } 555 mSubtitleTrack.mPackets = new AnotherPacketSource(NULL); 556 mTimedTextTrack.mPackets = new AnotherPacketSource(NULL); 557} 558 559status_t NuPlayer::GenericSource::feedMoreTSData() { 560 return OK; 561} 562 563void NuPlayer::GenericSource::schedulePollBuffering() { 564 sp<AMessage> msg = new AMessage(kWhatPollBuffering, this); 565 msg->setInt32("generation", mPollBufferingGeneration); 566 msg->post(1000000ll); 567} 568 569void NuPlayer::GenericSource::cancelPollBuffering() { 570 mBuffering = false; 571 ++mPollBufferingGeneration; 572 mPrevBufferPercentage = -1; 573} 574 575void NuPlayer::GenericSource::restartPollBuffering() { 576 if (mIsStreaming) { 577 cancelPollBuffering(); 578 onPollBuffering(); 579 } 580} 581 582void NuPlayer::GenericSource::notifyBufferingUpdate(int32_t percentage) { 583 // Buffering percent could go backward as it's estimated from remaining 584 // data and last access time. This could cause the buffering position 585 // drawn on media control to jitter slightly. Remember previously reported 586 // percentage and don't allow it to go backward. 587 if (percentage < mPrevBufferPercentage) { 588 percentage = mPrevBufferPercentage; 589 } else if (percentage > 100) { 590 percentage = 100; 591 } 592 593 mPrevBufferPercentage = percentage; 594 595 ALOGV("notifyBufferingUpdate: buffering %d%%", percentage); 596 597 sp<AMessage> msg = dupNotify(); 598 msg->setInt32("what", kWhatBufferingUpdate); 599 msg->setInt32("percentage", percentage); 600 msg->post(); 601} 602 603void NuPlayer::GenericSource::startBufferingIfNecessary() { 604 ALOGV("startBufferingIfNecessary: mPrepareBuffering=%d, mBuffering=%d", 605 mPrepareBuffering, mBuffering); 606 607 if (mPrepareBuffering) { 608 return; 609 } 610 611 if (!mBuffering) { 612 mBuffering = true; 613 614 ensureCacheIsFetching(); 615 sendCacheStats(); 616 617 sp<AMessage> notify = dupNotify(); 618 notify->setInt32("what", kWhatPauseOnBufferingStart); 619 notify->post(); 620 } 621} 622 623void NuPlayer::GenericSource::stopBufferingIfNecessary() { 624 ALOGV("stopBufferingIfNecessary: mPrepareBuffering=%d, mBuffering=%d", 625 mPrepareBuffering, mBuffering); 626 627 if (mPrepareBuffering) { 628 mPrepareBuffering = false; 629 notifyPrepared(); 630 return; 631 } 632 633 if (mBuffering) { 634 mBuffering = false; 635 636 sendCacheStats(); 637 638 sp<AMessage> notify = dupNotify(); 639 notify->setInt32("what", kWhatResumeOnBufferingEnd); 640 notify->post(); 641 } 642} 643 644void NuPlayer::GenericSource::sendCacheStats() { 645 int32_t kbps = 0; 646 status_t err = UNKNOWN_ERROR; 647 648 if (mWVMExtractor != NULL) { 649 err = mWVMExtractor->getEstimatedBandwidthKbps(&kbps); 650 } else if (mCachedSource != NULL) { 651 err = mCachedSource->getEstimatedBandwidthKbps(&kbps); 652 } 653 654 if (err == OK) { 655 sp<AMessage> notify = dupNotify(); 656 notify->setInt32("what", kWhatCacheStats); 657 notify->setInt32("bandwidth", kbps); 658 notify->post(); 659 } 660} 661 662void NuPlayer::GenericSource::ensureCacheIsFetching() { 663 if (mCachedSource != NULL) { 664 mCachedSource->resumeFetchingIfNecessary(); 665 } 666} 667 668void NuPlayer::GenericSource::onPollBuffering() { 669 status_t finalStatus = UNKNOWN_ERROR; 670 int64_t cachedDurationUs = -1ll; 671 ssize_t cachedDataRemaining = -1; 672 673 ALOGW_IF(mWVMExtractor != NULL && mCachedSource != NULL, 674 "WVMExtractor and NuCachedSource both present"); 675 676 if (mWVMExtractor != NULL) { 677 cachedDurationUs = 678 mWVMExtractor->getCachedDurationUs(&finalStatus); 679 } else if (mCachedSource != NULL) { 680 cachedDataRemaining = 681 mCachedSource->approxDataRemaining(&finalStatus); 682 683 if (finalStatus == OK) { 684 off64_t size; 685 int64_t bitrate = 0ll; 686 if (mDurationUs > 0 && mCachedSource->getSize(&size) == OK) { 687 bitrate = size * 8000000ll / mDurationUs; 688 } else if (mBitrate > 0) { 689 bitrate = mBitrate; 690 } 691 if (bitrate > 0) { 692 cachedDurationUs = cachedDataRemaining * 8000000ll / bitrate; 693 } 694 } 695 } 696 697 if (finalStatus != OK) { 698 ALOGV("onPollBuffering: EOS (finalStatus = %d)", finalStatus); 699 700 if (finalStatus == ERROR_END_OF_STREAM) { 701 notifyBufferingUpdate(100); 702 } 703 704 stopBufferingIfNecessary(); 705 return; 706 } else if (cachedDurationUs >= 0ll) { 707 if (mDurationUs > 0ll) { 708 int64_t cachedPosUs = getLastReadPosition() + cachedDurationUs; 709 int percentage = 100.0 * cachedPosUs / mDurationUs; 710 if (percentage > 100) { 711 percentage = 100; 712 } 713 714 notifyBufferingUpdate(percentage); 715 } 716 717 ALOGV("onPollBuffering: cachedDurationUs %.1f sec", 718 cachedDurationUs / 1000000.0f); 719 720 if (cachedDurationUs < kLowWaterMarkUs) { 721 startBufferingIfNecessary(); 722 } else if (cachedDurationUs > kHighWaterMarkUs) { 723 stopBufferingIfNecessary(); 724 } 725 } else if (cachedDataRemaining >= 0) { 726 ALOGV("onPollBuffering: cachedDataRemaining %zd bytes", 727 cachedDataRemaining); 728 729 if (cachedDataRemaining < kLowWaterMarkBytes) { 730 startBufferingIfNecessary(); 731 } else if (cachedDataRemaining > kHighWaterMarkBytes) { 732 stopBufferingIfNecessary(); 733 } 734 } 735 736 schedulePollBuffering(); 737} 738 739void NuPlayer::GenericSource::onMessageReceived(const sp<AMessage> &msg) { 740 switch (msg->what()) { 741 case kWhatPrepareAsync: 742 { 743 onPrepareAsync(); 744 break; 745 } 746 case kWhatFetchSubtitleData: 747 { 748 fetchTextData(kWhatSendSubtitleData, MEDIA_TRACK_TYPE_SUBTITLE, 749 mFetchSubtitleDataGeneration, mSubtitleTrack.mPackets, msg); 750 break; 751 } 752 753 case kWhatFetchTimedTextData: 754 { 755 fetchTextData(kWhatSendTimedTextData, MEDIA_TRACK_TYPE_TIMEDTEXT, 756 mFetchTimedTextDataGeneration, mTimedTextTrack.mPackets, msg); 757 break; 758 } 759 760 case kWhatSendSubtitleData: 761 { 762 sendTextData(kWhatSubtitleData, MEDIA_TRACK_TYPE_SUBTITLE, 763 mFetchSubtitleDataGeneration, mSubtitleTrack.mPackets, msg); 764 break; 765 } 766 767 case kWhatSendTimedTextData: 768 { 769 sendTextData(kWhatTimedTextData, MEDIA_TRACK_TYPE_TIMEDTEXT, 770 mFetchTimedTextDataGeneration, mTimedTextTrack.mPackets, msg); 771 break; 772 } 773 774 case kWhatChangeAVSource: 775 { 776 int32_t trackIndex; 777 CHECK(msg->findInt32("trackIndex", &trackIndex)); 778 const sp<MediaSource> source = mSources.itemAt(trackIndex); 779 780 Track* track; 781 const char *mime; 782 media_track_type trackType, counterpartType; 783 sp<MetaData> meta = source->getFormat(); 784 meta->findCString(kKeyMIMEType, &mime); 785 if (!strncasecmp(mime, "audio/", 6)) { 786 track = &mAudioTrack; 787 trackType = MEDIA_TRACK_TYPE_AUDIO; 788 counterpartType = MEDIA_TRACK_TYPE_VIDEO;; 789 } else { 790 CHECK(!strncasecmp(mime, "video/", 6)); 791 track = &mVideoTrack; 792 trackType = MEDIA_TRACK_TYPE_VIDEO; 793 counterpartType = MEDIA_TRACK_TYPE_AUDIO;; 794 } 795 796 797 if (track->mSource != NULL) { 798 track->mSource->stop(); 799 } 800 track->mSource = source; 801 track->mSource->start(); 802 track->mIndex = trackIndex; 803 804 int64_t timeUs, actualTimeUs; 805 const bool formatChange = true; 806 if (trackType == MEDIA_TRACK_TYPE_AUDIO) { 807 timeUs = mAudioLastDequeueTimeUs; 808 } else { 809 timeUs = mVideoLastDequeueTimeUs; 810 } 811 readBuffer(trackType, timeUs, &actualTimeUs, formatChange); 812 readBuffer(counterpartType, -1, NULL, formatChange); 813 ALOGV("timeUs %lld actualTimeUs %lld", (long long)timeUs, (long long)actualTimeUs); 814 815 break; 816 } 817 818 case kWhatStart: 819 case kWhatResume: 820 { 821 restartPollBuffering(); 822 break; 823 } 824 825 case kWhatPollBuffering: 826 { 827 int32_t generation; 828 CHECK(msg->findInt32("generation", &generation)); 829 if (generation == mPollBufferingGeneration) { 830 onPollBuffering(); 831 } 832 break; 833 } 834 835 case kWhatGetFormat: 836 { 837 onGetFormatMeta(msg); 838 break; 839 } 840 841 case kWhatGetSelectedTrack: 842 { 843 onGetSelectedTrack(msg); 844 break; 845 } 846 847 case kWhatSelectTrack: 848 { 849 onSelectTrack(msg); 850 break; 851 } 852 853 case kWhatSeek: 854 { 855 onSeek(msg); 856 break; 857 } 858 859 case kWhatReadBuffer: 860 { 861 onReadBuffer(msg); 862 break; 863 } 864 865 case kWhatSecureDecodersInstantiated: 866 { 867 int32_t err; 868 CHECK(msg->findInt32("err", &err)); 869 onSecureDecodersInstantiated(err); 870 break; 871 } 872 873 case kWhatStopWidevine: 874 { 875 // mStopRead is only used for Widevine to prevent the video source 876 // from being read while the associated video decoder is shutting down. 877 mStopRead = true; 878 if (mVideoTrack.mSource != NULL) { 879 mVideoTrack.mPackets->clear(); 880 } 881 sp<AMessage> response = new AMessage; 882 sp<AReplyToken> replyID; 883 CHECK(msg->senderAwaitsResponse(&replyID)); 884 response->postReply(replyID); 885 break; 886 } 887 default: 888 Source::onMessageReceived(msg); 889 break; 890 } 891} 892 893void NuPlayer::GenericSource::fetchTextData( 894 uint32_t sendWhat, 895 media_track_type type, 896 int32_t curGen, 897 sp<AnotherPacketSource> packets, 898 sp<AMessage> msg) { 899 int32_t msgGeneration; 900 CHECK(msg->findInt32("generation", &msgGeneration)); 901 if (msgGeneration != curGen) { 902 // stale 903 return; 904 } 905 906 int32_t avail; 907 if (packets->hasBufferAvailable(&avail)) { 908 return; 909 } 910 911 int64_t timeUs; 912 CHECK(msg->findInt64("timeUs", &timeUs)); 913 914 int64_t subTimeUs; 915 readBuffer(type, timeUs, &subTimeUs); 916 917 int64_t delayUs = subTimeUs - timeUs; 918 if (msg->what() == kWhatFetchSubtitleData) { 919 const int64_t oneSecUs = 1000000ll; 920 delayUs -= oneSecUs; 921 } 922 sp<AMessage> msg2 = new AMessage(sendWhat, this); 923 msg2->setInt32("generation", msgGeneration); 924 msg2->post(delayUs < 0 ? 0 : delayUs); 925} 926 927void NuPlayer::GenericSource::sendTextData( 928 uint32_t what, 929 media_track_type type, 930 int32_t curGen, 931 sp<AnotherPacketSource> packets, 932 sp<AMessage> msg) { 933 int32_t msgGeneration; 934 CHECK(msg->findInt32("generation", &msgGeneration)); 935 if (msgGeneration != curGen) { 936 // stale 937 return; 938 } 939 940 int64_t subTimeUs; 941 if (packets->nextBufferTime(&subTimeUs) != OK) { 942 return; 943 } 944 945 int64_t nextSubTimeUs; 946 readBuffer(type, -1, &nextSubTimeUs); 947 948 sp<ABuffer> buffer; 949 status_t dequeueStatus = packets->dequeueAccessUnit(&buffer); 950 if (dequeueStatus == OK) { 951 sp<AMessage> notify = dupNotify(); 952 notify->setInt32("what", what); 953 notify->setBuffer("buffer", buffer); 954 notify->post(); 955 956 const int64_t delayUs = nextSubTimeUs - subTimeUs; 957 msg->post(delayUs < 0 ? 0 : delayUs); 958 } 959} 960 961sp<MetaData> NuPlayer::GenericSource::getFormatMeta(bool audio) { 962 sp<AMessage> msg = new AMessage(kWhatGetFormat, this); 963 msg->setInt32("audio", audio); 964 965 sp<AMessage> response; 966 void *format; 967 status_t err = msg->postAndAwaitResponse(&response); 968 if (err == OK && response != NULL) { 969 CHECK(response->findPointer("format", &format)); 970 return (MetaData *)format; 971 } else { 972 return NULL; 973 } 974} 975 976void NuPlayer::GenericSource::onGetFormatMeta(sp<AMessage> msg) const { 977 int32_t audio; 978 CHECK(msg->findInt32("audio", &audio)); 979 980 sp<AMessage> response = new AMessage; 981 sp<MetaData> format = doGetFormatMeta(audio); 982 response->setPointer("format", format.get()); 983 984 sp<AReplyToken> replyID; 985 CHECK(msg->senderAwaitsResponse(&replyID)); 986 response->postReply(replyID); 987} 988 989sp<MetaData> NuPlayer::GenericSource::doGetFormatMeta(bool audio) const { 990 sp<MediaSource> source = audio ? mAudioTrack.mSource : mVideoTrack.mSource; 991 992 if (source == NULL) { 993 return NULL; 994 } 995 996 return source->getFormat(); 997} 998 999status_t NuPlayer::GenericSource::dequeueAccessUnit( 1000 bool audio, sp<ABuffer> *accessUnit) { 1001 Track *track = audio ? &mAudioTrack : &mVideoTrack; 1002 1003 if (track->mSource == NULL) { 1004 return -EWOULDBLOCK; 1005 } 1006 1007 if (mIsWidevine && !audio) { 1008 // try to read a buffer as we may not have been able to the last time 1009 postReadBuffer(MEDIA_TRACK_TYPE_VIDEO); 1010 } 1011 1012 status_t finalResult; 1013 if (!track->mPackets->hasBufferAvailable(&finalResult)) { 1014 if (finalResult == OK) { 1015 postReadBuffer( 1016 audio ? MEDIA_TRACK_TYPE_AUDIO : MEDIA_TRACK_TYPE_VIDEO); 1017 return -EWOULDBLOCK; 1018 } 1019 return finalResult; 1020 } 1021 1022 status_t result = track->mPackets->dequeueAccessUnit(accessUnit); 1023 1024 // start pulling in more buffers if we only have one (or no) buffer left 1025 // so that decoder has less chance of being starved 1026 if (track->mPackets->getAvailableBufferCount(&finalResult) < 2) { 1027 postReadBuffer(audio? MEDIA_TRACK_TYPE_AUDIO : MEDIA_TRACK_TYPE_VIDEO); 1028 } 1029 1030 if (result != OK) { 1031 if (mSubtitleTrack.mSource != NULL) { 1032 mSubtitleTrack.mPackets->clear(); 1033 mFetchSubtitleDataGeneration++; 1034 } 1035 if (mTimedTextTrack.mSource != NULL) { 1036 mTimedTextTrack.mPackets->clear(); 1037 mFetchTimedTextDataGeneration++; 1038 } 1039 return result; 1040 } 1041 1042 int64_t timeUs; 1043 status_t eosResult; // ignored 1044 CHECK((*accessUnit)->meta()->findInt64("timeUs", &timeUs)); 1045 if (audio) { 1046 mAudioLastDequeueTimeUs = timeUs; 1047 } else { 1048 mVideoLastDequeueTimeUs = timeUs; 1049 } 1050 1051 if (mSubtitleTrack.mSource != NULL 1052 && !mSubtitleTrack.mPackets->hasBufferAvailable(&eosResult)) { 1053 sp<AMessage> msg = new AMessage(kWhatFetchSubtitleData, this); 1054 msg->setInt64("timeUs", timeUs); 1055 msg->setInt32("generation", mFetchSubtitleDataGeneration); 1056 msg->post(); 1057 } 1058 1059 if (mTimedTextTrack.mSource != NULL 1060 && !mTimedTextTrack.mPackets->hasBufferAvailable(&eosResult)) { 1061 sp<AMessage> msg = new AMessage(kWhatFetchTimedTextData, this); 1062 msg->setInt64("timeUs", timeUs); 1063 msg->setInt32("generation", mFetchTimedTextDataGeneration); 1064 msg->post(); 1065 } 1066 1067 return result; 1068} 1069 1070status_t NuPlayer::GenericSource::getDuration(int64_t *durationUs) { 1071 *durationUs = mDurationUs; 1072 return OK; 1073} 1074 1075size_t NuPlayer::GenericSource::getTrackCount() const { 1076 return mSources.size(); 1077} 1078 1079sp<AMessage> NuPlayer::GenericSource::getTrackInfo(size_t trackIndex) const { 1080 size_t trackCount = mSources.size(); 1081 if (trackIndex >= trackCount) { 1082 return NULL; 1083 } 1084 1085 sp<AMessage> format = new AMessage(); 1086 sp<MetaData> meta = mSources.itemAt(trackIndex)->getFormat(); 1087 1088 const char *mime; 1089 CHECK(meta->findCString(kKeyMIMEType, &mime)); 1090 format->setString("mime", mime); 1091 1092 int32_t trackType; 1093 if (!strncasecmp(mime, "video/", 6)) { 1094 trackType = MEDIA_TRACK_TYPE_VIDEO; 1095 } else if (!strncasecmp(mime, "audio/", 6)) { 1096 trackType = MEDIA_TRACK_TYPE_AUDIO; 1097 } else if (!strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP)) { 1098 trackType = MEDIA_TRACK_TYPE_TIMEDTEXT; 1099 } else { 1100 trackType = MEDIA_TRACK_TYPE_UNKNOWN; 1101 } 1102 format->setInt32("type", trackType); 1103 1104 const char *lang; 1105 if (!meta->findCString(kKeyMediaLanguage, &lang)) { 1106 lang = "und"; 1107 } 1108 format->setString("language", lang); 1109 1110 if (trackType == MEDIA_TRACK_TYPE_SUBTITLE) { 1111 int32_t isAutoselect = 1, isDefault = 0, isForced = 0; 1112 meta->findInt32(kKeyTrackIsAutoselect, &isAutoselect); 1113 meta->findInt32(kKeyTrackIsDefault, &isDefault); 1114 meta->findInt32(kKeyTrackIsForced, &isForced); 1115 1116 format->setInt32("auto", !!isAutoselect); 1117 format->setInt32("default", !!isDefault); 1118 format->setInt32("forced", !!isForced); 1119 } 1120 1121 return format; 1122} 1123 1124ssize_t NuPlayer::GenericSource::getSelectedTrack(media_track_type type) const { 1125 sp<AMessage> msg = new AMessage(kWhatGetSelectedTrack, this); 1126 msg->setInt32("type", type); 1127 1128 sp<AMessage> response; 1129 int32_t index; 1130 status_t err = msg->postAndAwaitResponse(&response); 1131 if (err == OK && response != NULL) { 1132 CHECK(response->findInt32("index", &index)); 1133 return index; 1134 } else { 1135 return -1; 1136 } 1137} 1138 1139void NuPlayer::GenericSource::onGetSelectedTrack(sp<AMessage> msg) const { 1140 int32_t tmpType; 1141 CHECK(msg->findInt32("type", &tmpType)); 1142 media_track_type type = (media_track_type)tmpType; 1143 1144 sp<AMessage> response = new AMessage; 1145 ssize_t index = doGetSelectedTrack(type); 1146 response->setInt32("index", index); 1147 1148 sp<AReplyToken> replyID; 1149 CHECK(msg->senderAwaitsResponse(&replyID)); 1150 response->postReply(replyID); 1151} 1152 1153ssize_t NuPlayer::GenericSource::doGetSelectedTrack(media_track_type type) const { 1154 const Track *track = NULL; 1155 switch (type) { 1156 case MEDIA_TRACK_TYPE_VIDEO: 1157 track = &mVideoTrack; 1158 break; 1159 case MEDIA_TRACK_TYPE_AUDIO: 1160 track = &mAudioTrack; 1161 break; 1162 case MEDIA_TRACK_TYPE_TIMEDTEXT: 1163 track = &mTimedTextTrack; 1164 break; 1165 case MEDIA_TRACK_TYPE_SUBTITLE: 1166 track = &mSubtitleTrack; 1167 break; 1168 default: 1169 break; 1170 } 1171 1172 if (track != NULL && track->mSource != NULL) { 1173 return track->mIndex; 1174 } 1175 1176 return -1; 1177} 1178 1179status_t NuPlayer::GenericSource::selectTrack(size_t trackIndex, bool select, int64_t timeUs) { 1180 ALOGV("%s track: %zu", select ? "select" : "deselect", trackIndex); 1181 sp<AMessage> msg = new AMessage(kWhatSelectTrack, this); 1182 msg->setInt32("trackIndex", trackIndex); 1183 msg->setInt32("select", select); 1184 msg->setInt64("timeUs", timeUs); 1185 1186 sp<AMessage> response; 1187 status_t err = msg->postAndAwaitResponse(&response); 1188 if (err == OK && response != NULL) { 1189 CHECK(response->findInt32("err", &err)); 1190 } 1191 1192 return err; 1193} 1194 1195void NuPlayer::GenericSource::onSelectTrack(sp<AMessage> msg) { 1196 int32_t trackIndex, select; 1197 int64_t timeUs; 1198 CHECK(msg->findInt32("trackIndex", &trackIndex)); 1199 CHECK(msg->findInt32("select", &select)); 1200 CHECK(msg->findInt64("timeUs", &timeUs)); 1201 1202 sp<AMessage> response = new AMessage; 1203 status_t err = doSelectTrack(trackIndex, select, timeUs); 1204 response->setInt32("err", err); 1205 1206 sp<AReplyToken> replyID; 1207 CHECK(msg->senderAwaitsResponse(&replyID)); 1208 response->postReply(replyID); 1209} 1210 1211status_t NuPlayer::GenericSource::doSelectTrack(size_t trackIndex, bool select, int64_t timeUs) { 1212 if (trackIndex >= mSources.size()) { 1213 return BAD_INDEX; 1214 } 1215 1216 if (!select) { 1217 Track* track = NULL; 1218 if (mSubtitleTrack.mSource != NULL && trackIndex == mSubtitleTrack.mIndex) { 1219 track = &mSubtitleTrack; 1220 mFetchSubtitleDataGeneration++; 1221 } else if (mTimedTextTrack.mSource != NULL && trackIndex == mTimedTextTrack.mIndex) { 1222 track = &mTimedTextTrack; 1223 mFetchTimedTextDataGeneration++; 1224 } 1225 if (track == NULL) { 1226 return INVALID_OPERATION; 1227 } 1228 track->mSource->stop(); 1229 track->mSource = NULL; 1230 track->mPackets->clear(); 1231 return OK; 1232 } 1233 1234 const sp<MediaSource> source = mSources.itemAt(trackIndex); 1235 sp<MetaData> meta = source->getFormat(); 1236 const char *mime; 1237 CHECK(meta->findCString(kKeyMIMEType, &mime)); 1238 if (!strncasecmp(mime, "text/", 5)) { 1239 bool isSubtitle = strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP); 1240 Track *track = isSubtitle ? &mSubtitleTrack : &mTimedTextTrack; 1241 if (track->mSource != NULL && track->mIndex == trackIndex) { 1242 return OK; 1243 } 1244 track->mIndex = trackIndex; 1245 if (track->mSource != NULL) { 1246 track->mSource->stop(); 1247 } 1248 track->mSource = mSources.itemAt(trackIndex); 1249 track->mSource->start(); 1250 if (track->mPackets == NULL) { 1251 track->mPackets = new AnotherPacketSource(track->mSource->getFormat()); 1252 } else { 1253 track->mPackets->clear(); 1254 track->mPackets->setFormat(track->mSource->getFormat()); 1255 1256 } 1257 1258 if (isSubtitle) { 1259 mFetchSubtitleDataGeneration++; 1260 } else { 1261 mFetchTimedTextDataGeneration++; 1262 } 1263 1264 status_t eosResult; // ignored 1265 if (mSubtitleTrack.mSource != NULL 1266 && !mSubtitleTrack.mPackets->hasBufferAvailable(&eosResult)) { 1267 sp<AMessage> msg = new AMessage(kWhatFetchSubtitleData, this); 1268 msg->setInt64("timeUs", timeUs); 1269 msg->setInt32("generation", mFetchSubtitleDataGeneration); 1270 msg->post(); 1271 } 1272 1273 if (mTimedTextTrack.mSource != NULL 1274 && !mTimedTextTrack.mPackets->hasBufferAvailable(&eosResult)) { 1275 sp<AMessage> msg = new AMessage(kWhatFetchTimedTextData, this); 1276 msg->setInt64("timeUs", timeUs); 1277 msg->setInt32("generation", mFetchTimedTextDataGeneration); 1278 msg->post(); 1279 } 1280 1281 return OK; 1282 } else if (!strncasecmp(mime, "audio/", 6) || !strncasecmp(mime, "video/", 6)) { 1283 bool audio = !strncasecmp(mime, "audio/", 6); 1284 Track *track = audio ? &mAudioTrack : &mVideoTrack; 1285 if (track->mSource != NULL && track->mIndex == trackIndex) { 1286 return OK; 1287 } 1288 1289 sp<AMessage> msg = new AMessage(kWhatChangeAVSource, this); 1290 msg->setInt32("trackIndex", trackIndex); 1291 msg->post(); 1292 return OK; 1293 } 1294 1295 return INVALID_OPERATION; 1296} 1297 1298status_t NuPlayer::GenericSource::seekTo(int64_t seekTimeUs) { 1299 sp<AMessage> msg = new AMessage(kWhatSeek, this); 1300 msg->setInt64("seekTimeUs", seekTimeUs); 1301 1302 sp<AMessage> response; 1303 status_t err = msg->postAndAwaitResponse(&response); 1304 if (err == OK && response != NULL) { 1305 CHECK(response->findInt32("err", &err)); 1306 } 1307 1308 return err; 1309} 1310 1311void NuPlayer::GenericSource::onSeek(sp<AMessage> msg) { 1312 int64_t seekTimeUs; 1313 CHECK(msg->findInt64("seekTimeUs", &seekTimeUs)); 1314 1315 sp<AMessage> response = new AMessage; 1316 status_t err = doSeek(seekTimeUs); 1317 response->setInt32("err", err); 1318 1319 sp<AReplyToken> replyID; 1320 CHECK(msg->senderAwaitsResponse(&replyID)); 1321 response->postReply(replyID); 1322} 1323 1324status_t NuPlayer::GenericSource::doSeek(int64_t seekTimeUs) { 1325 // If the Widevine source is stopped, do not attempt to read any 1326 // more buffers. 1327 if (mStopRead) { 1328 return INVALID_OPERATION; 1329 } 1330 if (mVideoTrack.mSource != NULL) { 1331 int64_t actualTimeUs; 1332 readBuffer(MEDIA_TRACK_TYPE_VIDEO, seekTimeUs, &actualTimeUs); 1333 1334 seekTimeUs = actualTimeUs; 1335 mVideoLastDequeueTimeUs = seekTimeUs; 1336 } 1337 1338 if (mAudioTrack.mSource != NULL) { 1339 readBuffer(MEDIA_TRACK_TYPE_AUDIO, seekTimeUs); 1340 mAudioLastDequeueTimeUs = seekTimeUs; 1341 } 1342 1343 setDrmPlaybackStatusIfNeeded(Playback::START, seekTimeUs / 1000); 1344 if (!mStarted) { 1345 setDrmPlaybackStatusIfNeeded(Playback::PAUSE, 0); 1346 } 1347 1348 // If currently buffering, post kWhatBufferingEnd first, so that 1349 // NuPlayer resumes. Otherwise, if cache hits high watermark 1350 // before new polling happens, no one will resume the playback. 1351 stopBufferingIfNecessary(); 1352 restartPollBuffering(); 1353 1354 return OK; 1355} 1356 1357sp<ABuffer> NuPlayer::GenericSource::mediaBufferToABuffer( 1358 MediaBuffer* mb, 1359 media_track_type trackType, 1360 int64_t /* seekTimeUs */, 1361 int64_t *actualTimeUs) { 1362 bool audio = trackType == MEDIA_TRACK_TYPE_AUDIO; 1363 size_t outLength = mb->range_length(); 1364 1365 if (audio && mAudioIsVorbis) { 1366 outLength += sizeof(int32_t); 1367 } 1368 1369 sp<ABuffer> ab; 1370 if (mIsSecure && !audio) { 1371 // data is already provided in the buffer 1372 ab = new ABuffer(NULL, mb->range_length()); 1373 mb->add_ref(); 1374 ab->setMediaBufferBase(mb); 1375 } else { 1376 ab = new ABuffer(outLength); 1377 memcpy(ab->data(), 1378 (const uint8_t *)mb->data() + mb->range_offset(), 1379 mb->range_length()); 1380 } 1381 1382 if (audio && mAudioIsVorbis) { 1383 int32_t numPageSamples; 1384 if (!mb->meta_data()->findInt32(kKeyValidSamples, &numPageSamples)) { 1385 numPageSamples = -1; 1386 } 1387 1388 uint8_t* abEnd = ab->data() + mb->range_length(); 1389 memcpy(abEnd, &numPageSamples, sizeof(numPageSamples)); 1390 } 1391 1392 sp<AMessage> meta = ab->meta(); 1393 1394 int64_t timeUs; 1395 CHECK(mb->meta_data()->findInt64(kKeyTime, &timeUs)); 1396 meta->setInt64("timeUs", timeUs); 1397 1398#if 0 1399 // Temporarily disable pre-roll till we have a full solution to handle 1400 // both single seek and continous seek gracefully. 1401 if (seekTimeUs > timeUs) { 1402 sp<AMessage> extra = new AMessage; 1403 extra->setInt64("resume-at-mediaTimeUs", seekTimeUs); 1404 meta->setMessage("extra", extra); 1405 } 1406#endif 1407 1408 if (trackType == MEDIA_TRACK_TYPE_TIMEDTEXT) { 1409 const char *mime; 1410 CHECK(mTimedTextTrack.mSource != NULL 1411 && mTimedTextTrack.mSource->getFormat()->findCString(kKeyMIMEType, &mime)); 1412 meta->setString("mime", mime); 1413 } 1414 1415 int64_t durationUs; 1416 if (mb->meta_data()->findInt64(kKeyDuration, &durationUs)) { 1417 meta->setInt64("durationUs", durationUs); 1418 } 1419 1420 if (trackType == MEDIA_TRACK_TYPE_SUBTITLE) { 1421 meta->setInt32("trackIndex", mSubtitleTrack.mIndex); 1422 } 1423 1424 uint32_t dataType; // unused 1425 const void *seiData; 1426 size_t seiLength; 1427 if (mb->meta_data()->findData(kKeySEI, &dataType, &seiData, &seiLength)) { 1428 sp<ABuffer> sei = ABuffer::CreateAsCopy(seiData, seiLength);; 1429 meta->setBuffer("sei", sei); 1430 } 1431 1432 if (actualTimeUs) { 1433 *actualTimeUs = timeUs; 1434 } 1435 1436 mb->release(); 1437 mb = NULL; 1438 1439 return ab; 1440} 1441 1442void NuPlayer::GenericSource::postReadBuffer(media_track_type trackType) { 1443 Mutex::Autolock _l(mReadBufferLock); 1444 1445 if ((mPendingReadBufferTypes & (1 << trackType)) == 0) { 1446 mPendingReadBufferTypes |= (1 << trackType); 1447 sp<AMessage> msg = new AMessage(kWhatReadBuffer, this); 1448 msg->setInt32("trackType", trackType); 1449 msg->post(); 1450 } 1451} 1452 1453void NuPlayer::GenericSource::onReadBuffer(sp<AMessage> msg) { 1454 int32_t tmpType; 1455 CHECK(msg->findInt32("trackType", &tmpType)); 1456 media_track_type trackType = (media_track_type)tmpType; 1457 readBuffer(trackType); 1458 { 1459 // only protect the variable change, as readBuffer may 1460 // take considerable time. 1461 Mutex::Autolock _l(mReadBufferLock); 1462 mPendingReadBufferTypes &= ~(1 << trackType); 1463 } 1464} 1465 1466void NuPlayer::GenericSource::readBuffer( 1467 media_track_type trackType, int64_t seekTimeUs, int64_t *actualTimeUs, bool formatChange) { 1468 // Do not read data if Widevine source is stopped 1469 if (mStopRead) { 1470 return; 1471 } 1472 Track *track; 1473 size_t maxBuffers = 1; 1474 switch (trackType) { 1475 case MEDIA_TRACK_TYPE_VIDEO: 1476 track = &mVideoTrack; 1477 if (mIsWidevine) { 1478 maxBuffers = 2; 1479 } else { 1480 maxBuffers = 4; 1481 } 1482 break; 1483 case MEDIA_TRACK_TYPE_AUDIO: 1484 track = &mAudioTrack; 1485 if (mIsWidevine) { 1486 maxBuffers = 8; 1487 } else { 1488 maxBuffers = 64; 1489 } 1490 break; 1491 case MEDIA_TRACK_TYPE_SUBTITLE: 1492 track = &mSubtitleTrack; 1493 break; 1494 case MEDIA_TRACK_TYPE_TIMEDTEXT: 1495 track = &mTimedTextTrack; 1496 break; 1497 default: 1498 TRESPASS(); 1499 } 1500 1501 if (track->mSource == NULL) { 1502 return; 1503 } 1504 1505 if (actualTimeUs) { 1506 *actualTimeUs = seekTimeUs; 1507 } 1508 1509 MediaSource::ReadOptions options; 1510 1511 bool seeking = false; 1512 1513 if (seekTimeUs >= 0) { 1514 options.setSeekTo(seekTimeUs, MediaSource::ReadOptions::SEEK_PREVIOUS_SYNC); 1515 seeking = true; 1516 } 1517 1518 if (mIsWidevine) { 1519 options.setNonBlocking(); 1520 } 1521 1522 for (size_t numBuffers = 0; numBuffers < maxBuffers; ) { 1523 MediaBuffer *mbuf; 1524 status_t err = track->mSource->read(&mbuf, &options); 1525 1526 options.clearSeekTo(); 1527 1528 if (err == OK) { 1529 int64_t timeUs; 1530 CHECK(mbuf->meta_data()->findInt64(kKeyTime, &timeUs)); 1531 if (trackType == MEDIA_TRACK_TYPE_AUDIO) { 1532 mAudioTimeUs = timeUs; 1533 } else if (trackType == MEDIA_TRACK_TYPE_VIDEO) { 1534 mVideoTimeUs = timeUs; 1535 } 1536 1537 queueDiscontinuityIfNeeded(seeking, formatChange, trackType, track); 1538 1539 sp<ABuffer> buffer = mediaBufferToABuffer( 1540 mbuf, trackType, seekTimeUs, actualTimeUs); 1541 track->mPackets->queueAccessUnit(buffer); 1542 formatChange = false; 1543 seeking = false; 1544 ++numBuffers; 1545 } else if (err == WOULD_BLOCK) { 1546 break; 1547 } else if (err == INFO_FORMAT_CHANGED) { 1548#if 0 1549 track->mPackets->queueDiscontinuity( 1550 ATSParser::DISCONTINUITY_FORMATCHANGE, 1551 NULL, 1552 false /* discard */); 1553#endif 1554 } else { 1555 queueDiscontinuityIfNeeded(seeking, formatChange, trackType, track); 1556 track->mPackets->signalEOS(err); 1557 break; 1558 } 1559 } 1560} 1561 1562void NuPlayer::GenericSource::queueDiscontinuityIfNeeded( 1563 bool seeking, bool formatChange, media_track_type trackType, Track *track) { 1564 // formatChange && seeking: track whose source is changed during selection 1565 // formatChange && !seeking: track whose source is not changed during selection 1566 // !formatChange: normal seek 1567 if ((seeking || formatChange) 1568 && (trackType == MEDIA_TRACK_TYPE_AUDIO 1569 || trackType == MEDIA_TRACK_TYPE_VIDEO)) { 1570 ATSParser::DiscontinuityType type = (formatChange && seeking) 1571 ? ATSParser::DISCONTINUITY_FORMATCHANGE 1572 : ATSParser::DISCONTINUITY_NONE; 1573 track->mPackets->queueDiscontinuity(type, NULL /* extra */, true /* discard */); 1574 } 1575} 1576 1577} // namespace android 1578