NuPlayer.cpp revision 1713460104b86f6be3a5d9993d9ace864d889b2d
1/* 2 * Copyright (C) 2010 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 "NuPlayer" 19#include <utils/Log.h> 20 21#include "NuPlayer.h" 22 23#include "HTTPLiveSource.h" 24#include "NuPlayerCCDecoder.h" 25#include "NuPlayerDecoder.h" 26#include "NuPlayerDecoderBase.h" 27#include "NuPlayerDecoderPassThrough.h" 28#include "NuPlayerDriver.h" 29#include "NuPlayerRenderer.h" 30#include "NuPlayerSource.h" 31#include "RTSPSource.h" 32#include "StreamingSource.h" 33#include "GenericSource.h" 34#include "TextDescriptions.h" 35 36#include "ATSParser.h" 37 38#include <cutils/properties.h> 39 40#include <media/stagefright/foundation/hexdump.h> 41#include <media/stagefright/foundation/ABuffer.h> 42#include <media/stagefright/foundation/ADebug.h> 43#include <media/stagefright/foundation/AMessage.h> 44#include <media/stagefright/MediaBuffer.h> 45#include <media/stagefright/MediaDefs.h> 46#include <media/stagefright/MediaErrors.h> 47#include <media/stagefright/MetaData.h> 48#include <gui/IGraphicBufferProducer.h> 49 50#include "avc_utils.h" 51 52#include "ESDS.h" 53#include <media/stagefright/Utils.h> 54 55namespace android { 56 57struct NuPlayer::Action : public RefBase { 58 Action() {} 59 60 virtual void execute(NuPlayer *player) = 0; 61 62private: 63 DISALLOW_EVIL_CONSTRUCTORS(Action); 64}; 65 66struct NuPlayer::SeekAction : public Action { 67 SeekAction(int64_t seekTimeUs, bool needNotify) 68 : mSeekTimeUs(seekTimeUs), 69 mNeedNotify(needNotify) { 70 } 71 72 virtual void execute(NuPlayer *player) { 73 player->performSeek(mSeekTimeUs, mNeedNotify); 74 } 75 76private: 77 int64_t mSeekTimeUs; 78 bool mNeedNotify; 79 80 DISALLOW_EVIL_CONSTRUCTORS(SeekAction); 81}; 82 83struct NuPlayer::ResumeDecoderAction : public Action { 84 ResumeDecoderAction(bool needNotify) 85 : mNeedNotify(needNotify) { 86 } 87 88 virtual void execute(NuPlayer *player) { 89 player->performResumeDecoders(mNeedNotify); 90 } 91 92private: 93 bool mNeedNotify; 94 95 DISALLOW_EVIL_CONSTRUCTORS(ResumeDecoderAction); 96}; 97 98struct NuPlayer::SetSurfaceAction : public Action { 99 SetSurfaceAction(const sp<NativeWindowWrapper> &wrapper) 100 : mWrapper(wrapper) { 101 } 102 103 virtual void execute(NuPlayer *player) { 104 player->performSetSurface(mWrapper); 105 } 106 107private: 108 sp<NativeWindowWrapper> mWrapper; 109 110 DISALLOW_EVIL_CONSTRUCTORS(SetSurfaceAction); 111}; 112 113struct NuPlayer::FlushDecoderAction : public Action { 114 FlushDecoderAction(FlushCommand audio, FlushCommand video) 115 : mAudio(audio), 116 mVideo(video) { 117 } 118 119 virtual void execute(NuPlayer *player) { 120 player->performDecoderFlush(mAudio, mVideo); 121 } 122 123private: 124 FlushCommand mAudio; 125 FlushCommand mVideo; 126 127 DISALLOW_EVIL_CONSTRUCTORS(FlushDecoderAction); 128}; 129 130struct NuPlayer::PostMessageAction : public Action { 131 PostMessageAction(const sp<AMessage> &msg) 132 : mMessage(msg) { 133 } 134 135 virtual void execute(NuPlayer *) { 136 mMessage->post(); 137 } 138 139private: 140 sp<AMessage> mMessage; 141 142 DISALLOW_EVIL_CONSTRUCTORS(PostMessageAction); 143}; 144 145// Use this if there's no state necessary to save in order to execute 146// the action. 147struct NuPlayer::SimpleAction : public Action { 148 typedef void (NuPlayer::*ActionFunc)(); 149 150 SimpleAction(ActionFunc func) 151 : mFunc(func) { 152 } 153 154 virtual void execute(NuPlayer *player) { 155 (player->*mFunc)(); 156 } 157 158private: 159 ActionFunc mFunc; 160 161 DISALLOW_EVIL_CONSTRUCTORS(SimpleAction); 162}; 163 164//////////////////////////////////////////////////////////////////////////////// 165 166NuPlayer::NuPlayer() 167 : mUIDValid(false), 168 mSourceFlags(0), 169 mOffloadAudio(false), 170 mAudioDecoderGeneration(0), 171 mVideoDecoderGeneration(0), 172 mRendererGeneration(0), 173 mAudioEOS(false), 174 mVideoEOS(false), 175 mScanSourcesPending(false), 176 mScanSourcesGeneration(0), 177 mPollDurationGeneration(0), 178 mTimedTextGeneration(0), 179 mFlushingAudio(NONE), 180 mFlushingVideo(NONE), 181 mResumePending(false), 182 mVideoScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW), 183 mStarted(false) { 184 clearFlushComplete(); 185} 186 187NuPlayer::~NuPlayer() { 188} 189 190void NuPlayer::setUID(uid_t uid) { 191 mUIDValid = true; 192 mUID = uid; 193} 194 195void NuPlayer::setDriver(const wp<NuPlayerDriver> &driver) { 196 mDriver = driver; 197} 198 199void NuPlayer::setDataSourceAsync(const sp<IStreamSource> &source) { 200 sp<AMessage> msg = new AMessage(kWhatSetDataSource, id()); 201 202 sp<AMessage> notify = new AMessage(kWhatSourceNotify, id()); 203 204 msg->setObject("source", new StreamingSource(notify, source)); 205 msg->post(); 206} 207 208static bool IsHTTPLiveURL(const char *url) { 209 if (!strncasecmp("http://", url, 7) 210 || !strncasecmp("https://", url, 8) 211 || !strncasecmp("file://", url, 7)) { 212 size_t len = strlen(url); 213 if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) { 214 return true; 215 } 216 217 if (strstr(url,"m3u8")) { 218 return true; 219 } 220 } 221 222 return false; 223} 224 225void NuPlayer::setDataSourceAsync( 226 const sp<IMediaHTTPService> &httpService, 227 const char *url, 228 const KeyedVector<String8, String8> *headers) { 229 230 sp<AMessage> msg = new AMessage(kWhatSetDataSource, id()); 231 size_t len = strlen(url); 232 233 sp<AMessage> notify = new AMessage(kWhatSourceNotify, id()); 234 235 sp<Source> source; 236 if (IsHTTPLiveURL(url)) { 237 source = new HTTPLiveSource(notify, httpService, url, headers); 238 } else if (!strncasecmp(url, "rtsp://", 7)) { 239 source = new RTSPSource( 240 notify, httpService, url, headers, mUIDValid, mUID); 241 } else if ((!strncasecmp(url, "http://", 7) 242 || !strncasecmp(url, "https://", 8)) 243 && ((len >= 4 && !strcasecmp(".sdp", &url[len - 4])) 244 || strstr(url, ".sdp?"))) { 245 source = new RTSPSource( 246 notify, httpService, url, headers, mUIDValid, mUID, true); 247 } else { 248 sp<GenericSource> genericSource = 249 new GenericSource(notify, mUIDValid, mUID); 250 // Don't set FLAG_SECURE on mSourceFlags here for widevine. 251 // The correct flags will be updated in Source::kWhatFlagsChanged 252 // handler when GenericSource is prepared. 253 254 status_t err = genericSource->setDataSource(httpService, url, headers); 255 256 if (err == OK) { 257 source = genericSource; 258 } else { 259 ALOGE("Failed to set data source!"); 260 } 261 } 262 msg->setObject("source", source); 263 msg->post(); 264} 265 266void NuPlayer::setDataSourceAsync(int fd, int64_t offset, int64_t length) { 267 sp<AMessage> msg = new AMessage(kWhatSetDataSource, id()); 268 269 sp<AMessage> notify = new AMessage(kWhatSourceNotify, id()); 270 271 sp<GenericSource> source = 272 new GenericSource(notify, mUIDValid, mUID); 273 274 status_t err = source->setDataSource(fd, offset, length); 275 276 if (err != OK) { 277 ALOGE("Failed to set data source!"); 278 source = NULL; 279 } 280 281 msg->setObject("source", source); 282 msg->post(); 283} 284 285void NuPlayer::prepareAsync() { 286 (new AMessage(kWhatPrepare, id()))->post(); 287} 288 289void NuPlayer::setVideoSurfaceTextureAsync( 290 const sp<IGraphicBufferProducer> &bufferProducer) { 291 sp<AMessage> msg = new AMessage(kWhatSetVideoNativeWindow, id()); 292 293 if (bufferProducer == NULL) { 294 msg->setObject("native-window", NULL); 295 } else { 296 msg->setObject( 297 "native-window", 298 new NativeWindowWrapper( 299 new Surface(bufferProducer, true /* controlledByApp */))); 300 } 301 302 msg->post(); 303} 304 305void NuPlayer::setAudioSink(const sp<MediaPlayerBase::AudioSink> &sink) { 306 sp<AMessage> msg = new AMessage(kWhatSetAudioSink, id()); 307 msg->setObject("sink", sink); 308 msg->post(); 309} 310 311void NuPlayer::start() { 312 (new AMessage(kWhatStart, id()))->post(); 313} 314 315void NuPlayer::pause() { 316 (new AMessage(kWhatPause, id()))->post(); 317} 318 319void NuPlayer::resetAsync() { 320 if (mSource != NULL) { 321 // During a reset, the data source might be unresponsive already, we need to 322 // disconnect explicitly so that reads exit promptly. 323 // We can't queue the disconnect request to the looper, as it might be 324 // queued behind a stuck read and never gets processed. 325 // Doing a disconnect outside the looper to allows the pending reads to exit 326 // (either successfully or with error). 327 mSource->disconnect(); 328 } 329 330 (new AMessage(kWhatReset, id()))->post(); 331} 332 333void NuPlayer::seekToAsync(int64_t seekTimeUs, bool needNotify) { 334 sp<AMessage> msg = new AMessage(kWhatSeek, id()); 335 msg->setInt64("seekTimeUs", seekTimeUs); 336 msg->setInt32("needNotify", needNotify); 337 msg->post(); 338} 339 340 341void NuPlayer::writeTrackInfo( 342 Parcel* reply, const sp<AMessage> format) const { 343 int32_t trackType; 344 CHECK(format->findInt32("type", &trackType)); 345 346 AString lang; 347 CHECK(format->findString("language", &lang)); 348 349 reply->writeInt32(2); // write something non-zero 350 reply->writeInt32(trackType); 351 reply->writeString16(String16(lang.c_str())); 352 353 if (trackType == MEDIA_TRACK_TYPE_SUBTITLE) { 354 AString mime; 355 CHECK(format->findString("mime", &mime)); 356 357 int32_t isAuto, isDefault, isForced; 358 CHECK(format->findInt32("auto", &isAuto)); 359 CHECK(format->findInt32("default", &isDefault)); 360 CHECK(format->findInt32("forced", &isForced)); 361 362 reply->writeString16(String16(mime.c_str())); 363 reply->writeInt32(isAuto); 364 reply->writeInt32(isDefault); 365 reply->writeInt32(isForced); 366 } 367} 368 369void NuPlayer::onMessageReceived(const sp<AMessage> &msg) { 370 switch (msg->what()) { 371 case kWhatSetDataSource: 372 { 373 ALOGV("kWhatSetDataSource"); 374 375 CHECK(mSource == NULL); 376 377 status_t err = OK; 378 sp<RefBase> obj; 379 CHECK(msg->findObject("source", &obj)); 380 if (obj != NULL) { 381 mSource = static_cast<Source *>(obj.get()); 382 } else { 383 err = UNKNOWN_ERROR; 384 } 385 386 CHECK(mDriver != NULL); 387 sp<NuPlayerDriver> driver = mDriver.promote(); 388 if (driver != NULL) { 389 driver->notifySetDataSourceCompleted(err); 390 } 391 break; 392 } 393 394 case kWhatPrepare: 395 { 396 mSource->prepareAsync(); 397 break; 398 } 399 400 case kWhatGetTrackInfo: 401 { 402 uint32_t replyID; 403 CHECK(msg->senderAwaitsResponse(&replyID)); 404 405 Parcel* reply; 406 CHECK(msg->findPointer("reply", (void**)&reply)); 407 408 size_t inbandTracks = 0; 409 if (mSource != NULL) { 410 inbandTracks = mSource->getTrackCount(); 411 } 412 413 size_t ccTracks = 0; 414 if (mCCDecoder != NULL) { 415 ccTracks = mCCDecoder->getTrackCount(); 416 } 417 418 // total track count 419 reply->writeInt32(inbandTracks + ccTracks); 420 421 // write inband tracks 422 for (size_t i = 0; i < inbandTracks; ++i) { 423 writeTrackInfo(reply, mSource->getTrackInfo(i)); 424 } 425 426 // write CC track 427 for (size_t i = 0; i < ccTracks; ++i) { 428 writeTrackInfo(reply, mCCDecoder->getTrackInfo(i)); 429 } 430 431 sp<AMessage> response = new AMessage; 432 response->postReply(replyID); 433 break; 434 } 435 436 case kWhatGetSelectedTrack: 437 { 438 status_t err = INVALID_OPERATION; 439 if (mSource != NULL) { 440 err = OK; 441 442 int32_t type32; 443 CHECK(msg->findInt32("type", (int32_t*)&type32)); 444 media_track_type type = (media_track_type)type32; 445 ssize_t selectedTrack = mSource->getSelectedTrack(type); 446 447 Parcel* reply; 448 CHECK(msg->findPointer("reply", (void**)&reply)); 449 reply->writeInt32(selectedTrack); 450 } 451 452 sp<AMessage> response = new AMessage; 453 response->setInt32("err", err); 454 455 uint32_t replyID; 456 CHECK(msg->senderAwaitsResponse(&replyID)); 457 response->postReply(replyID); 458 break; 459 } 460 461 case kWhatSelectTrack: 462 { 463 uint32_t replyID; 464 CHECK(msg->senderAwaitsResponse(&replyID)); 465 466 size_t trackIndex; 467 int32_t select; 468 int64_t timeUs; 469 CHECK(msg->findSize("trackIndex", &trackIndex)); 470 CHECK(msg->findInt32("select", &select)); 471 CHECK(msg->findInt64("timeUs", &timeUs)); 472 473 status_t err = INVALID_OPERATION; 474 475 size_t inbandTracks = 0; 476 if (mSource != NULL) { 477 inbandTracks = mSource->getTrackCount(); 478 } 479 size_t ccTracks = 0; 480 if (mCCDecoder != NULL) { 481 ccTracks = mCCDecoder->getTrackCount(); 482 } 483 484 if (trackIndex < inbandTracks) { 485 err = mSource->selectTrack(trackIndex, select, timeUs); 486 487 if (!select && err == OK) { 488 int32_t type; 489 sp<AMessage> info = mSource->getTrackInfo(trackIndex); 490 if (info != NULL 491 && info->findInt32("type", &type) 492 && type == MEDIA_TRACK_TYPE_TIMEDTEXT) { 493 ++mTimedTextGeneration; 494 } 495 } 496 } else { 497 trackIndex -= inbandTracks; 498 499 if (trackIndex < ccTracks) { 500 err = mCCDecoder->selectTrack(trackIndex, select); 501 } 502 } 503 504 sp<AMessage> response = new AMessage; 505 response->setInt32("err", err); 506 507 response->postReply(replyID); 508 break; 509 } 510 511 case kWhatPollDuration: 512 { 513 int32_t generation; 514 CHECK(msg->findInt32("generation", &generation)); 515 516 if (generation != mPollDurationGeneration) { 517 // stale 518 break; 519 } 520 521 int64_t durationUs; 522 if (mDriver != NULL && mSource->getDuration(&durationUs) == OK) { 523 sp<NuPlayerDriver> driver = mDriver.promote(); 524 if (driver != NULL) { 525 driver->notifyDuration(durationUs); 526 } 527 } 528 529 msg->post(1000000ll); // poll again in a second. 530 break; 531 } 532 533 case kWhatSetVideoNativeWindow: 534 { 535 ALOGV("kWhatSetVideoNativeWindow"); 536 537 sp<RefBase> obj; 538 CHECK(msg->findObject("native-window", &obj)); 539 540 if (mSource == NULL || mSource->getFormat(false /* audio */) == NULL) { 541 performSetSurface(static_cast<NativeWindowWrapper *>(obj.get())); 542 break; 543 } 544 545 mDeferredActions.push_back( 546 new FlushDecoderAction(FLUSH_CMD_FLUSH /* audio */, 547 FLUSH_CMD_SHUTDOWN /* video */)); 548 549 mDeferredActions.push_back( 550 new SetSurfaceAction( 551 static_cast<NativeWindowWrapper *>(obj.get()))); 552 553 if (obj != NULL) { 554 if (mStarted) { 555 // Issue a seek to refresh the video screen only if started otherwise 556 // the extractor may not yet be started and will assert. 557 // If the video decoder is not set (perhaps audio only in this case) 558 // do not perform a seek as it is not needed. 559 int64_t currentPositionUs = 0; 560 if (getCurrentPosition(¤tPositionUs) == OK) { 561 mDeferredActions.push_back( 562 new SeekAction(currentPositionUs, false /* needNotify */)); 563 } 564 } 565 566 // If there is a new surface texture, instantiate decoders 567 // again if possible. 568 mDeferredActions.push_back( 569 new SimpleAction(&NuPlayer::performScanSources)); 570 } 571 572 // After a flush without shutdown, decoder is paused. 573 // Don't resume it until source seek is done, otherwise it could 574 // start pulling stale data too soon. 575 mDeferredActions.push_back( 576 new ResumeDecoderAction(false /* needNotify */)); 577 578 processDeferredActions(); 579 break; 580 } 581 582 case kWhatSetAudioSink: 583 { 584 ALOGV("kWhatSetAudioSink"); 585 586 sp<RefBase> obj; 587 CHECK(msg->findObject("sink", &obj)); 588 589 mAudioSink = static_cast<MediaPlayerBase::AudioSink *>(obj.get()); 590 break; 591 } 592 593 case kWhatStart: 594 { 595 ALOGV("kWhatStart"); 596 if (mStarted) { 597 onResume(); 598 } else { 599 onStart(); 600 } 601 break; 602 } 603 604 case kWhatScanSources: 605 { 606 int32_t generation; 607 CHECK(msg->findInt32("generation", &generation)); 608 if (generation != mScanSourcesGeneration) { 609 // Drop obsolete msg. 610 break; 611 } 612 613 mScanSourcesPending = false; 614 615 ALOGV("scanning sources haveAudio=%d, haveVideo=%d", 616 mAudioDecoder != NULL, mVideoDecoder != NULL); 617 618 bool mHadAnySourcesBefore = 619 (mAudioDecoder != NULL) || (mVideoDecoder != NULL); 620 621 // initialize video before audio because successful initialization of 622 // video may change deep buffer mode of audio. 623 if (mNativeWindow != NULL) { 624 instantiateDecoder(false, &mVideoDecoder); 625 } 626 627 // Don't try to re-open audio sink if there's an existing decoder. 628 if (mAudioSink != NULL && mAudioDecoder == NULL) { 629 sp<MetaData> audioMeta = mSource->getFormatMeta(true /* audio */); 630 sp<AMessage> videoFormat = mSource->getFormat(false /* audio */); 631 audio_stream_type_t streamType = mAudioSink->getAudioStreamType(); 632 const bool hasVideo = (videoFormat != NULL); 633 const bool canOffload = canOffloadStream( 634 audioMeta, hasVideo, true /* is_streaming */, streamType); 635 if (canOffload) { 636 if (!mOffloadAudio) { 637 mRenderer->signalEnableOffloadAudio(); 638 } 639 // open audio sink early under offload mode. 640 sp<AMessage> format = mSource->getFormat(true /*audio*/); 641 tryOpenAudioSinkForOffload(format, hasVideo); 642 } 643 instantiateDecoder(true, &mAudioDecoder); 644 } 645 646 if (!mHadAnySourcesBefore 647 && (mAudioDecoder != NULL || mVideoDecoder != NULL)) { 648 // This is the first time we've found anything playable. 649 650 if (mSourceFlags & Source::FLAG_DYNAMIC_DURATION) { 651 schedulePollDuration(); 652 } 653 } 654 655 status_t err; 656 if ((err = mSource->feedMoreTSData()) != OK) { 657 if (mAudioDecoder == NULL && mVideoDecoder == NULL) { 658 // We're not currently decoding anything (no audio or 659 // video tracks found) and we just ran out of input data. 660 661 if (err == ERROR_END_OF_STREAM) { 662 notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0); 663 } else { 664 notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err); 665 } 666 } 667 break; 668 } 669 670 if ((mAudioDecoder == NULL && mAudioSink != NULL) 671 || (mVideoDecoder == NULL && mNativeWindow != NULL)) { 672 msg->post(100000ll); 673 mScanSourcesPending = true; 674 } 675 break; 676 } 677 678 case kWhatVideoNotify: 679 case kWhatAudioNotify: 680 { 681 bool audio = msg->what() == kWhatAudioNotify; 682 683 int32_t currentDecoderGeneration = 684 (audio? mAudioDecoderGeneration : mVideoDecoderGeneration); 685 int32_t requesterGeneration = currentDecoderGeneration - 1; 686 CHECK(msg->findInt32("generation", &requesterGeneration)); 687 688 if (requesterGeneration != currentDecoderGeneration) { 689 ALOGV("got message from old %s decoder, generation(%d:%d)", 690 audio ? "audio" : "video", requesterGeneration, 691 currentDecoderGeneration); 692 sp<AMessage> reply; 693 if (!(msg->findMessage("reply", &reply))) { 694 return; 695 } 696 697 reply->setInt32("err", INFO_DISCONTINUITY); 698 reply->post(); 699 return; 700 } 701 702 int32_t what; 703 CHECK(msg->findInt32("what", &what)); 704 705 if (what == DecoderBase::kWhatInputDiscontinuity) { 706 int32_t formatChange; 707 CHECK(msg->findInt32("formatChange", &formatChange)); 708 709 ALOGV("%s discontinuity: formatChange %d", 710 audio ? "audio" : "video", formatChange); 711 712 if (formatChange) { 713 mDeferredActions.push_back( 714 new FlushDecoderAction( 715 audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE, 716 audio ? FLUSH_CMD_NONE : FLUSH_CMD_SHUTDOWN)); 717 } 718 719 mDeferredActions.push_back( 720 new SimpleAction( 721 &NuPlayer::performScanSources)); 722 723 processDeferredActions(); 724 } else if (what == DecoderBase::kWhatEOS) { 725 int32_t err; 726 CHECK(msg->findInt32("err", &err)); 727 728 if (err == ERROR_END_OF_STREAM) { 729 ALOGV("got %s decoder EOS", audio ? "audio" : "video"); 730 } else { 731 ALOGV("got %s decoder EOS w/ error %d", 732 audio ? "audio" : "video", 733 err); 734 } 735 736 mRenderer->queueEOS(audio, err); 737 } else if (what == DecoderBase::kWhatFlushCompleted) { 738 ALOGV("decoder %s flush completed", audio ? "audio" : "video"); 739 740 handleFlushComplete(audio, true /* isDecoder */); 741 finishFlushIfPossible(); 742 } else if (what == DecoderBase::kWhatVideoSizeChanged) { 743 sp<AMessage> format; 744 CHECK(msg->findMessage("format", &format)); 745 746 sp<AMessage> inputFormat = 747 mSource->getFormat(false /* audio */); 748 749 updateVideoSize(inputFormat, format); 750 } else if (what == DecoderBase::kWhatShutdownCompleted) { 751 ALOGV("%s shutdown completed", audio ? "audio" : "video"); 752 if (audio) { 753 mAudioDecoder.clear(); 754 ++mAudioDecoderGeneration; 755 756 CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER); 757 mFlushingAudio = SHUT_DOWN; 758 } else { 759 mVideoDecoder.clear(); 760 ++mVideoDecoderGeneration; 761 762 CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER); 763 mFlushingVideo = SHUT_DOWN; 764 } 765 766 finishFlushIfPossible(); 767 } else if (what == DecoderBase::kWhatResumeCompleted) { 768 finishResume(); 769 } else if (what == DecoderBase::kWhatError) { 770 status_t err; 771 if (!msg->findInt32("err", &err) || err == OK) { 772 err = UNKNOWN_ERROR; 773 } 774 775 // Decoder errors can be due to Source (e.g. from streaming), 776 // or from decoding corrupted bitstreams, or from other decoder 777 // MediaCodec operations (e.g. from an ongoing reset or seek). 778 // They may also be due to openAudioSink failure at 779 // decoder start or after a format change. 780 // 781 // We try to gracefully shut down the affected decoder if possible, 782 // rather than trying to force the shutdown with something 783 // similar to performReset(). This method can lead to a hang 784 // if MediaCodec functions block after an error, but they should 785 // typically return INVALID_OPERATION instead of blocking. 786 787 FlushStatus *flushing = audio ? &mFlushingAudio : &mFlushingVideo; 788 ALOGE("received error(%#x) from %s decoder, flushing(%d), now shutting down", 789 err, audio ? "audio" : "video", *flushing); 790 791 switch (*flushing) { 792 case NONE: 793 mDeferredActions.push_back( 794 new FlushDecoderAction( 795 audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE, 796 audio ? FLUSH_CMD_NONE : FLUSH_CMD_SHUTDOWN)); 797 processDeferredActions(); 798 break; 799 case FLUSHING_DECODER: 800 *flushing = FLUSHING_DECODER_SHUTDOWN; // initiate shutdown after flush. 801 break; // Wait for flush to complete. 802 case FLUSHING_DECODER_SHUTDOWN: 803 break; // Wait for flush to complete. 804 case SHUTTING_DOWN_DECODER: 805 break; // Wait for shutdown to complete. 806 case FLUSHED: 807 // Widevine source reads must stop before releasing the video decoder. 808 if (!audio && mSource != NULL && mSourceFlags & Source::FLAG_SECURE) { 809 mSource->stop(); 810 } 811 getDecoder(audio)->initiateShutdown(); // In the middle of a seek. 812 *flushing = SHUTTING_DOWN_DECODER; // Shut down. 813 break; 814 case SHUT_DOWN: 815 finishFlushIfPossible(); // Should not occur. 816 break; // Finish anyways. 817 } 818 notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err); 819 } else { 820 ALOGV("Unhandled decoder notification %d '%c%c%c%c'.", 821 what, 822 what >> 24, 823 (what >> 16) & 0xff, 824 (what >> 8) & 0xff, 825 what & 0xff); 826 } 827 828 break; 829 } 830 831 case kWhatRendererNotify: 832 { 833 int32_t requesterGeneration = mRendererGeneration - 1; 834 CHECK(msg->findInt32("generation", &requesterGeneration)); 835 if (requesterGeneration != mRendererGeneration) { 836 ALOGV("got message from old renderer, generation(%d:%d)", 837 requesterGeneration, mRendererGeneration); 838 return; 839 } 840 841 int32_t what; 842 CHECK(msg->findInt32("what", &what)); 843 844 if (what == Renderer::kWhatEOS) { 845 int32_t audio; 846 CHECK(msg->findInt32("audio", &audio)); 847 848 int32_t finalResult; 849 CHECK(msg->findInt32("finalResult", &finalResult)); 850 851 if (audio) { 852 mAudioEOS = true; 853 } else { 854 mVideoEOS = true; 855 } 856 857 if (finalResult == ERROR_END_OF_STREAM) { 858 ALOGV("reached %s EOS", audio ? "audio" : "video"); 859 } else { 860 ALOGE("%s track encountered an error (%d)", 861 audio ? "audio" : "video", finalResult); 862 863 notifyListener( 864 MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, finalResult); 865 } 866 867 if ((mAudioEOS || mAudioDecoder == NULL) 868 && (mVideoEOS || mVideoDecoder == NULL)) { 869 notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0); 870 } 871 } else if (what == Renderer::kWhatFlushComplete) { 872 int32_t audio; 873 CHECK(msg->findInt32("audio", &audio)); 874 875 ALOGV("renderer %s flush completed.", audio ? "audio" : "video"); 876 handleFlushComplete(audio, false /* isDecoder */); 877 finishFlushIfPossible(); 878 } else if (what == Renderer::kWhatVideoRenderingStart) { 879 notifyListener(MEDIA_INFO, MEDIA_INFO_RENDERING_START, 0); 880 } else if (what == Renderer::kWhatMediaRenderingStart) { 881 ALOGV("media rendering started"); 882 notifyListener(MEDIA_STARTED, 0, 0); 883 } else if (what == Renderer::kWhatAudioOffloadTearDown) { 884 ALOGV("Tear down audio offload, fall back to s/w path if due to error."); 885 int64_t positionUs; 886 CHECK(msg->findInt64("positionUs", &positionUs)); 887 int32_t reason; 888 CHECK(msg->findInt32("reason", &reason)); 889 closeAudioSink(); 890 mAudioDecoder.clear(); 891 ++mAudioDecoderGeneration; 892 mRenderer->flush( 893 true /* audio */, false /* notifyComplete */); 894 if (mVideoDecoder != NULL) { 895 mRenderer->flush( 896 false /* audio */, false /* notifyComplete */); 897 } 898 899 performSeek(positionUs, false /* needNotify */); 900 if (reason == Renderer::kDueToError) { 901 mRenderer->signalDisableOffloadAudio(); 902 mOffloadAudio = false; 903 instantiateDecoder(true /* audio */, &mAudioDecoder); 904 } 905 } 906 break; 907 } 908 909 case kWhatMoreDataQueued: 910 { 911 break; 912 } 913 914 case kWhatReset: 915 { 916 ALOGV("kWhatReset"); 917 918 mDeferredActions.push_back( 919 new FlushDecoderAction( 920 FLUSH_CMD_SHUTDOWN /* audio */, 921 FLUSH_CMD_SHUTDOWN /* video */)); 922 923 mDeferredActions.push_back( 924 new SimpleAction(&NuPlayer::performReset)); 925 926 processDeferredActions(); 927 break; 928 } 929 930 case kWhatSeek: 931 { 932 int64_t seekTimeUs; 933 int32_t needNotify; 934 CHECK(msg->findInt64("seekTimeUs", &seekTimeUs)); 935 CHECK(msg->findInt32("needNotify", &needNotify)); 936 937 ALOGV("kWhatSeek seekTimeUs=%lld us, needNotify=%d", 938 seekTimeUs, needNotify); 939 940 mDeferredActions.push_back( 941 new FlushDecoderAction(FLUSH_CMD_FLUSH /* audio */, 942 FLUSH_CMD_FLUSH /* video */)); 943 944 mDeferredActions.push_back( 945 new SeekAction(seekTimeUs, needNotify)); 946 947 // After a flush without shutdown, decoder is paused. 948 // Don't resume it until source seek is done, otherwise it could 949 // start pulling stale data too soon. 950 mDeferredActions.push_back( 951 new ResumeDecoderAction(needNotify)); 952 953 processDeferredActions(); 954 break; 955 } 956 957 case kWhatPause: 958 { 959 if (mSource != NULL) { 960 mSource->pause(); 961 } else { 962 ALOGW("pause called when source is gone or not set"); 963 } 964 if (mRenderer != NULL) { 965 mRenderer->pause(); 966 } else { 967 ALOGW("pause called when renderer is gone or not set"); 968 } 969 break; 970 } 971 972 case kWhatSourceNotify: 973 { 974 onSourceNotify(msg); 975 break; 976 } 977 978 case kWhatClosedCaptionNotify: 979 { 980 onClosedCaptionNotify(msg); 981 break; 982 } 983 984 default: 985 TRESPASS(); 986 break; 987 } 988} 989 990void NuPlayer::onResume() { 991 if (mSource != NULL) { 992 mSource->resume(); 993 } else { 994 ALOGW("resume called when source is gone or not set"); 995 } 996 // |mAudioDecoder| may have been released due to the pause timeout, so re-create it if 997 // needed. 998 if (audioDecoderStillNeeded() && mAudioDecoder == NULL) { 999 instantiateDecoder(true /* audio */, &mAudioDecoder); 1000 } 1001 if (mRenderer != NULL) { 1002 mRenderer->resume(); 1003 } else { 1004 ALOGW("resume called when renderer is gone or not set"); 1005 } 1006} 1007 1008void NuPlayer::onStart() { 1009 mOffloadAudio = false; 1010 mAudioEOS = false; 1011 mVideoEOS = false; 1012 mStarted = true; 1013 1014 /* instantiate decoders now for secure playback */ 1015 if (mSourceFlags & Source::FLAG_SECURE) { 1016 if (mNativeWindow != NULL) { 1017 instantiateDecoder(false, &mVideoDecoder); 1018 } 1019 1020 if (mAudioSink != NULL) { 1021 instantiateDecoder(true, &mAudioDecoder); 1022 } 1023 } 1024 1025 mSource->start(); 1026 1027 uint32_t flags = 0; 1028 1029 if (mSource->isRealTime()) { 1030 flags |= Renderer::FLAG_REAL_TIME; 1031 } 1032 1033 sp<MetaData> audioMeta = mSource->getFormatMeta(true /* audio */); 1034 audio_stream_type_t streamType = AUDIO_STREAM_MUSIC; 1035 if (mAudioSink != NULL) { 1036 streamType = mAudioSink->getAudioStreamType(); 1037 } 1038 1039 sp<AMessage> videoFormat = mSource->getFormat(false /* audio */); 1040 1041 mOffloadAudio = 1042 canOffloadStream(audioMeta, (videoFormat != NULL), 1043 true /* is_streaming */, streamType); 1044 if (mOffloadAudio) { 1045 flags |= Renderer::FLAG_OFFLOAD_AUDIO; 1046 } 1047 1048 sp<AMessage> notify = new AMessage(kWhatRendererNotify, id()); 1049 ++mRendererGeneration; 1050 notify->setInt32("generation", mRendererGeneration); 1051 mRenderer = new Renderer(mAudioSink, notify, flags); 1052 1053 mRendererLooper = new ALooper; 1054 mRendererLooper->setName("NuPlayerRenderer"); 1055 mRendererLooper->start(false, false, ANDROID_PRIORITY_AUDIO); 1056 mRendererLooper->registerHandler(mRenderer); 1057 1058 sp<MetaData> meta = getFileMeta(); 1059 int32_t rate; 1060 if (meta != NULL 1061 && meta->findInt32(kKeyFrameRate, &rate) && rate > 0) { 1062 mRenderer->setVideoFrameRate(rate); 1063 } 1064 1065 if (mVideoDecoder != NULL) { 1066 mVideoDecoder->setRenderer(mRenderer); 1067 } 1068 if (mAudioDecoder != NULL) { 1069 mAudioDecoder->setRenderer(mRenderer); 1070 } 1071 1072 postScanSources(); 1073} 1074 1075bool NuPlayer::audioDecoderStillNeeded() { 1076 // Audio decoder is no longer needed if it's in shut/shutting down status. 1077 return ((mFlushingAudio != SHUT_DOWN) && (mFlushingAudio != SHUTTING_DOWN_DECODER)); 1078} 1079 1080void NuPlayer::handleFlushComplete(bool audio, bool isDecoder) { 1081 // We wait for both the decoder flush and the renderer flush to complete 1082 // before entering either the FLUSHED or the SHUTTING_DOWN_DECODER state. 1083 1084 mFlushComplete[audio][isDecoder] = true; 1085 if (!mFlushComplete[audio][!isDecoder]) { 1086 return; 1087 } 1088 1089 FlushStatus *state = audio ? &mFlushingAudio : &mFlushingVideo; 1090 switch (*state) { 1091 case FLUSHING_DECODER: 1092 { 1093 *state = FLUSHED; 1094 break; 1095 } 1096 1097 case FLUSHING_DECODER_SHUTDOWN: 1098 { 1099 *state = SHUTTING_DOWN_DECODER; 1100 1101 ALOGV("initiating %s decoder shutdown", audio ? "audio" : "video"); 1102 if (!audio) { 1103 // Widevine source reads must stop before releasing the video decoder. 1104 if (mSource != NULL && mSourceFlags & Source::FLAG_SECURE) { 1105 mSource->stop(); 1106 } 1107 } 1108 getDecoder(audio)->initiateShutdown(); 1109 break; 1110 } 1111 1112 default: 1113 // decoder flush completes only occur in a flushing state. 1114 LOG_ALWAYS_FATAL_IF(isDecoder, "decoder flush in invalid state %d", *state); 1115 break; 1116 } 1117} 1118 1119void NuPlayer::finishFlushIfPossible() { 1120 if (mFlushingAudio != NONE && mFlushingAudio != FLUSHED 1121 && mFlushingAudio != SHUT_DOWN) { 1122 return; 1123 } 1124 1125 if (mFlushingVideo != NONE && mFlushingVideo != FLUSHED 1126 && mFlushingVideo != SHUT_DOWN) { 1127 return; 1128 } 1129 1130 ALOGV("both audio and video are flushed now."); 1131 1132 mFlushingAudio = NONE; 1133 mFlushingVideo = NONE; 1134 1135 clearFlushComplete(); 1136 1137 processDeferredActions(); 1138} 1139 1140void NuPlayer::postScanSources() { 1141 if (mScanSourcesPending) { 1142 return; 1143 } 1144 1145 sp<AMessage> msg = new AMessage(kWhatScanSources, id()); 1146 msg->setInt32("generation", mScanSourcesGeneration); 1147 msg->post(); 1148 1149 mScanSourcesPending = true; 1150} 1151 1152void NuPlayer::tryOpenAudioSinkForOffload(const sp<AMessage> &format, bool hasVideo) { 1153 // Note: This is called early in NuPlayer to determine whether offloading 1154 // is possible; otherwise the decoders call the renderer openAudioSink directly. 1155 1156 status_t err = mRenderer->openAudioSink( 1157 format, true /* offloadOnly */, hasVideo, AUDIO_OUTPUT_FLAG_NONE, &mOffloadAudio); 1158 if (err != OK) { 1159 // Any failure we turn off mOffloadAudio. 1160 mOffloadAudio = false; 1161 } else if (mOffloadAudio) { 1162 sp<MetaData> audioMeta = 1163 mSource->getFormatMeta(true /* audio */); 1164 sendMetaDataToHal(mAudioSink, audioMeta); 1165 } 1166} 1167 1168void NuPlayer::closeAudioSink() { 1169 mRenderer->closeAudioSink(); 1170} 1171 1172status_t NuPlayer::instantiateDecoder(bool audio, sp<DecoderBase> *decoder) { 1173 if (*decoder != NULL) { 1174 return OK; 1175 } 1176 1177 sp<AMessage> format = mSource->getFormat(audio); 1178 1179 if (format == NULL) { 1180 return -EWOULDBLOCK; 1181 } 1182 1183 if (!audio) { 1184 AString mime; 1185 CHECK(format->findString("mime", &mime)); 1186 1187 sp<AMessage> ccNotify = new AMessage(kWhatClosedCaptionNotify, id()); 1188 mCCDecoder = new CCDecoder(ccNotify); 1189 1190 if (mSourceFlags & Source::FLAG_SECURE) { 1191 format->setInt32("secure", true); 1192 } 1193 1194 if (mSourceFlags & Source::FLAG_PROTECTED) { 1195 format->setInt32("protected", true); 1196 } 1197 } 1198 1199 if (audio) { 1200 sp<AMessage> notify = new AMessage(kWhatAudioNotify, id()); 1201 ++mAudioDecoderGeneration; 1202 notify->setInt32("generation", mAudioDecoderGeneration); 1203 1204 if (mOffloadAudio) { 1205 *decoder = new DecoderPassThrough(notify, mSource, mRenderer); 1206 } else { 1207 *decoder = new Decoder(notify, mSource, mRenderer); 1208 } 1209 } else { 1210 sp<AMessage> notify = new AMessage(kWhatVideoNotify, id()); 1211 ++mVideoDecoderGeneration; 1212 notify->setInt32("generation", mVideoDecoderGeneration); 1213 1214 *decoder = new Decoder( 1215 notify, mSource, mRenderer, mNativeWindow, mCCDecoder); 1216 1217 // enable FRC if high-quality AV sync is requested, even if not 1218 // queuing to native window, as this will even improve textureview 1219 // playback. 1220 { 1221 char value[PROPERTY_VALUE_MAX]; 1222 if (property_get("persist.sys.media.avsync", value, NULL) && 1223 (!strcmp("1", value) || !strcasecmp("true", value))) { 1224 format->setInt32("auto-frc", 1); 1225 } 1226 } 1227 } 1228 (*decoder)->init(); 1229 (*decoder)->configure(format); 1230 1231 // allocate buffers to decrypt widevine source buffers 1232 if (!audio && (mSourceFlags & Source::FLAG_SECURE)) { 1233 Vector<sp<ABuffer> > inputBufs; 1234 CHECK_EQ((*decoder)->getInputBuffers(&inputBufs), (status_t)OK); 1235 1236 Vector<MediaBuffer *> mediaBufs; 1237 for (size_t i = 0; i < inputBufs.size(); i++) { 1238 const sp<ABuffer> &buffer = inputBufs[i]; 1239 MediaBuffer *mbuf = new MediaBuffer(buffer->data(), buffer->size()); 1240 mediaBufs.push(mbuf); 1241 } 1242 1243 status_t err = mSource->setBuffers(audio, mediaBufs); 1244 if (err != OK) { 1245 for (size_t i = 0; i < mediaBufs.size(); ++i) { 1246 mediaBufs[i]->release(); 1247 } 1248 mediaBufs.clear(); 1249 ALOGE("Secure source didn't support secure mediaBufs."); 1250 return err; 1251 } 1252 } 1253 return OK; 1254} 1255 1256void NuPlayer::updateVideoSize( 1257 const sp<AMessage> &inputFormat, 1258 const sp<AMessage> &outputFormat) { 1259 if (inputFormat == NULL) { 1260 ALOGW("Unknown video size, reporting 0x0!"); 1261 notifyListener(MEDIA_SET_VIDEO_SIZE, 0, 0); 1262 return; 1263 } 1264 1265 int32_t displayWidth, displayHeight; 1266 int32_t cropLeft, cropTop, cropRight, cropBottom; 1267 1268 if (outputFormat != NULL) { 1269 int32_t width, height; 1270 CHECK(outputFormat->findInt32("width", &width)); 1271 CHECK(outputFormat->findInt32("height", &height)); 1272 1273 int32_t cropLeft, cropTop, cropRight, cropBottom; 1274 CHECK(outputFormat->findRect( 1275 "crop", 1276 &cropLeft, &cropTop, &cropRight, &cropBottom)); 1277 1278 displayWidth = cropRight - cropLeft + 1; 1279 displayHeight = cropBottom - cropTop + 1; 1280 1281 ALOGV("Video output format changed to %d x %d " 1282 "(crop: %d x %d @ (%d, %d))", 1283 width, height, 1284 displayWidth, 1285 displayHeight, 1286 cropLeft, cropTop); 1287 } else { 1288 CHECK(inputFormat->findInt32("width", &displayWidth)); 1289 CHECK(inputFormat->findInt32("height", &displayHeight)); 1290 1291 ALOGV("Video input format %d x %d", displayWidth, displayHeight); 1292 } 1293 1294 // Take into account sample aspect ratio if necessary: 1295 int32_t sarWidth, sarHeight; 1296 if (inputFormat->findInt32("sar-width", &sarWidth) 1297 && inputFormat->findInt32("sar-height", &sarHeight)) { 1298 ALOGV("Sample aspect ratio %d : %d", sarWidth, sarHeight); 1299 1300 displayWidth = (displayWidth * sarWidth) / sarHeight; 1301 1302 ALOGV("display dimensions %d x %d", displayWidth, displayHeight); 1303 } 1304 1305 int32_t rotationDegrees; 1306 if (!inputFormat->findInt32("rotation-degrees", &rotationDegrees)) { 1307 rotationDegrees = 0; 1308 } 1309 1310 if (rotationDegrees == 90 || rotationDegrees == 270) { 1311 int32_t tmp = displayWidth; 1312 displayWidth = displayHeight; 1313 displayHeight = tmp; 1314 } 1315 1316 notifyListener( 1317 MEDIA_SET_VIDEO_SIZE, 1318 displayWidth, 1319 displayHeight); 1320} 1321 1322void NuPlayer::notifyListener(int msg, int ext1, int ext2, const Parcel *in) { 1323 if (mDriver == NULL) { 1324 return; 1325 } 1326 1327 sp<NuPlayerDriver> driver = mDriver.promote(); 1328 1329 if (driver == NULL) { 1330 return; 1331 } 1332 1333 driver->notifyListener(msg, ext1, ext2, in); 1334} 1335 1336void NuPlayer::flushDecoder(bool audio, bool needShutdown) { 1337 ALOGV("[%s] flushDecoder needShutdown=%d", 1338 audio ? "audio" : "video", needShutdown); 1339 1340 const sp<DecoderBase> &decoder = getDecoder(audio); 1341 if (decoder == NULL) { 1342 ALOGI("flushDecoder %s without decoder present", 1343 audio ? "audio" : "video"); 1344 return; 1345 } 1346 1347 // Make sure we don't continue to scan sources until we finish flushing. 1348 ++mScanSourcesGeneration; 1349 mScanSourcesPending = false; 1350 1351 decoder->signalFlush(); 1352 1353 FlushStatus newStatus = 1354 needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER; 1355 1356 mFlushComplete[audio][false /* isDecoder */] = false; 1357 mFlushComplete[audio][true /* isDecoder */] = false; 1358 if (audio) { 1359 ALOGE_IF(mFlushingAudio != NONE, 1360 "audio flushDecoder() is called in state %d", mFlushingAudio); 1361 mFlushingAudio = newStatus; 1362 } else { 1363 ALOGE_IF(mFlushingVideo != NONE, 1364 "video flushDecoder() is called in state %d", mFlushingVideo); 1365 mFlushingVideo = newStatus; 1366 } 1367} 1368 1369void NuPlayer::queueDecoderShutdown( 1370 bool audio, bool video, const sp<AMessage> &reply) { 1371 ALOGI("queueDecoderShutdown audio=%d, video=%d", audio, video); 1372 1373 mDeferredActions.push_back( 1374 new FlushDecoderAction( 1375 audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE, 1376 video ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE)); 1377 1378 mDeferredActions.push_back( 1379 new SimpleAction(&NuPlayer::performScanSources)); 1380 1381 mDeferredActions.push_back(new PostMessageAction(reply)); 1382 1383 processDeferredActions(); 1384} 1385 1386status_t NuPlayer::setVideoScalingMode(int32_t mode) { 1387 mVideoScalingMode = mode; 1388 if (mNativeWindow != NULL) { 1389 status_t ret = native_window_set_scaling_mode( 1390 mNativeWindow->getNativeWindow().get(), mVideoScalingMode); 1391 if (ret != OK) { 1392 ALOGE("Failed to set scaling mode (%d): %s", 1393 -ret, strerror(-ret)); 1394 return ret; 1395 } 1396 } 1397 return OK; 1398} 1399 1400status_t NuPlayer::getTrackInfo(Parcel* reply) const { 1401 sp<AMessage> msg = new AMessage(kWhatGetTrackInfo, id()); 1402 msg->setPointer("reply", reply); 1403 1404 sp<AMessage> response; 1405 status_t err = msg->postAndAwaitResponse(&response); 1406 return err; 1407} 1408 1409status_t NuPlayer::getSelectedTrack(int32_t type, Parcel* reply) const { 1410 sp<AMessage> msg = new AMessage(kWhatGetSelectedTrack, id()); 1411 msg->setPointer("reply", reply); 1412 msg->setInt32("type", type); 1413 1414 sp<AMessage> response; 1415 status_t err = msg->postAndAwaitResponse(&response); 1416 if (err == OK && response != NULL) { 1417 CHECK(response->findInt32("err", &err)); 1418 } 1419 return err; 1420} 1421 1422status_t NuPlayer::selectTrack(size_t trackIndex, bool select, int64_t timeUs) { 1423 sp<AMessage> msg = new AMessage(kWhatSelectTrack, id()); 1424 msg->setSize("trackIndex", trackIndex); 1425 msg->setInt32("select", select); 1426 msg->setInt64("timeUs", timeUs); 1427 1428 sp<AMessage> response; 1429 status_t err = msg->postAndAwaitResponse(&response); 1430 1431 if (err != OK) { 1432 return err; 1433 } 1434 1435 if (!response->findInt32("err", &err)) { 1436 err = OK; 1437 } 1438 1439 return err; 1440} 1441 1442status_t NuPlayer::getCurrentPosition(int64_t *mediaUs) { 1443 sp<Renderer> renderer = mRenderer; 1444 if (renderer == NULL) { 1445 return NO_INIT; 1446 } 1447 1448 return renderer->getCurrentPosition(mediaUs); 1449} 1450 1451void NuPlayer::getStats(int64_t *numFramesTotal, int64_t *numFramesDropped) { 1452 sp<DecoderBase> decoder = getDecoder(false /* audio */); 1453 if (decoder != NULL) { 1454 decoder->getStats(numFramesTotal, numFramesDropped); 1455 } else { 1456 *numFramesTotal = 0; 1457 *numFramesDropped = 0; 1458 } 1459} 1460 1461sp<MetaData> NuPlayer::getFileMeta() { 1462 return mSource->getFileFormatMeta(); 1463} 1464 1465void NuPlayer::schedulePollDuration() { 1466 sp<AMessage> msg = new AMessage(kWhatPollDuration, id()); 1467 msg->setInt32("generation", mPollDurationGeneration); 1468 msg->post(); 1469} 1470 1471void NuPlayer::cancelPollDuration() { 1472 ++mPollDurationGeneration; 1473} 1474 1475void NuPlayer::processDeferredActions() { 1476 while (!mDeferredActions.empty()) { 1477 // We won't execute any deferred actions until we're no longer in 1478 // an intermediate state, i.e. one more more decoders are currently 1479 // flushing or shutting down. 1480 1481 if (mFlushingAudio != NONE || mFlushingVideo != NONE) { 1482 // We're currently flushing, postpone the reset until that's 1483 // completed. 1484 1485 ALOGV("postponing action mFlushingAudio=%d, mFlushingVideo=%d", 1486 mFlushingAudio, mFlushingVideo); 1487 1488 break; 1489 } 1490 1491 sp<Action> action = *mDeferredActions.begin(); 1492 mDeferredActions.erase(mDeferredActions.begin()); 1493 1494 action->execute(this); 1495 } 1496} 1497 1498void NuPlayer::performSeek(int64_t seekTimeUs, bool needNotify) { 1499 ALOGV("performSeek seekTimeUs=%lld us (%.2f secs), needNotify(%d)", 1500 seekTimeUs, 1501 seekTimeUs / 1E6, 1502 needNotify); 1503 1504 if (mSource == NULL) { 1505 // This happens when reset occurs right before the loop mode 1506 // asynchronously seeks to the start of the stream. 1507 LOG_ALWAYS_FATAL_IF(mAudioDecoder != NULL || mVideoDecoder != NULL, 1508 "mSource is NULL and decoders not NULL audio(%p) video(%p)", 1509 mAudioDecoder.get(), mVideoDecoder.get()); 1510 return; 1511 } 1512 mSource->seekTo(seekTimeUs); 1513 ++mTimedTextGeneration; 1514 1515 // everything's flushed, continue playback. 1516} 1517 1518void NuPlayer::performDecoderFlush(FlushCommand audio, FlushCommand video) { 1519 ALOGV("performDecoderFlush audio=%d, video=%d", audio, video); 1520 1521 if ((audio == FLUSH_CMD_NONE || mAudioDecoder == NULL) 1522 && (video == FLUSH_CMD_NONE || mVideoDecoder == NULL)) { 1523 return; 1524 } 1525 1526 if (audio != FLUSH_CMD_NONE && mAudioDecoder != NULL) { 1527 flushDecoder(true /* audio */, (audio == FLUSH_CMD_SHUTDOWN)); 1528 } 1529 1530 if (video != FLUSH_CMD_NONE && mVideoDecoder != NULL) { 1531 flushDecoder(false /* audio */, (video == FLUSH_CMD_SHUTDOWN)); 1532 } 1533} 1534 1535void NuPlayer::performReset() { 1536 ALOGV("performReset"); 1537 1538 CHECK(mAudioDecoder == NULL); 1539 CHECK(mVideoDecoder == NULL); 1540 1541 cancelPollDuration(); 1542 1543 ++mScanSourcesGeneration; 1544 mScanSourcesPending = false; 1545 1546 if (mRendererLooper != NULL) { 1547 if (mRenderer != NULL) { 1548 mRendererLooper->unregisterHandler(mRenderer->id()); 1549 } 1550 mRendererLooper->stop(); 1551 mRendererLooper.clear(); 1552 } 1553 mRenderer.clear(); 1554 ++mRendererGeneration; 1555 1556 if (mSource != NULL) { 1557 mSource->stop(); 1558 1559 mSource.clear(); 1560 } 1561 1562 if (mDriver != NULL) { 1563 sp<NuPlayerDriver> driver = mDriver.promote(); 1564 if (driver != NULL) { 1565 driver->notifyResetComplete(); 1566 } 1567 } 1568 1569 mStarted = false; 1570} 1571 1572void NuPlayer::performScanSources() { 1573 ALOGV("performScanSources"); 1574 1575 if (!mStarted) { 1576 return; 1577 } 1578 1579 if (mAudioDecoder == NULL || mVideoDecoder == NULL) { 1580 postScanSources(); 1581 } 1582} 1583 1584void NuPlayer::performSetSurface(const sp<NativeWindowWrapper> &wrapper) { 1585 ALOGV("performSetSurface"); 1586 1587 mNativeWindow = wrapper; 1588 1589 // XXX - ignore error from setVideoScalingMode for now 1590 setVideoScalingMode(mVideoScalingMode); 1591 1592 if (mDriver != NULL) { 1593 sp<NuPlayerDriver> driver = mDriver.promote(); 1594 if (driver != NULL) { 1595 driver->notifySetSurfaceComplete(); 1596 } 1597 } 1598} 1599 1600void NuPlayer::performResumeDecoders(bool needNotify) { 1601 if (needNotify) { 1602 mResumePending = true; 1603 if (mVideoDecoder == NULL) { 1604 // if audio-only, we can notify seek complete now, 1605 // as the resume operation will be relatively fast. 1606 finishResume(); 1607 } 1608 } 1609 1610 if (mVideoDecoder != NULL) { 1611 // When there is continuous seek, MediaPlayer will cache the seek 1612 // position, and send down new seek request when previous seek is 1613 // complete. Let's wait for at least one video output frame before 1614 // notifying seek complete, so that the video thumbnail gets updated 1615 // when seekbar is dragged. 1616 mVideoDecoder->signalResume(needNotify); 1617 } 1618 1619 if (mAudioDecoder != NULL) { 1620 mAudioDecoder->signalResume(false /* needNotify */); 1621 } 1622} 1623 1624void NuPlayer::finishResume() { 1625 if (mResumePending) { 1626 mResumePending = false; 1627 if (mDriver != NULL) { 1628 sp<NuPlayerDriver> driver = mDriver.promote(); 1629 if (driver != NULL) { 1630 driver->notifySeekComplete(); 1631 } 1632 } 1633 } 1634} 1635 1636void NuPlayer::onSourceNotify(const sp<AMessage> &msg) { 1637 int32_t what; 1638 CHECK(msg->findInt32("what", &what)); 1639 1640 switch (what) { 1641 case Source::kWhatPrepared: 1642 { 1643 if (mSource == NULL) { 1644 // This is a stale notification from a source that was 1645 // asynchronously preparing when the client called reset(). 1646 // We handled the reset, the source is gone. 1647 break; 1648 } 1649 1650 int32_t err; 1651 CHECK(msg->findInt32("err", &err)); 1652 1653 sp<NuPlayerDriver> driver = mDriver.promote(); 1654 if (driver != NULL) { 1655 // notify duration first, so that it's definitely set when 1656 // the app received the "prepare complete" callback. 1657 int64_t durationUs; 1658 if (mSource->getDuration(&durationUs) == OK) { 1659 driver->notifyDuration(durationUs); 1660 } 1661 driver->notifyPrepareCompleted(err); 1662 } 1663 1664 break; 1665 } 1666 1667 case Source::kWhatFlagsChanged: 1668 { 1669 uint32_t flags; 1670 CHECK(msg->findInt32("flags", (int32_t *)&flags)); 1671 1672 sp<NuPlayerDriver> driver = mDriver.promote(); 1673 if (driver != NULL) { 1674 if ((flags & NuPlayer::Source::FLAG_CAN_SEEK) == 0) { 1675 driver->notifyListener( 1676 MEDIA_INFO, MEDIA_INFO_NOT_SEEKABLE, 0); 1677 } 1678 driver->notifyFlagsChanged(flags); 1679 } 1680 1681 if ((mSourceFlags & Source::FLAG_DYNAMIC_DURATION) 1682 && (!(flags & Source::FLAG_DYNAMIC_DURATION))) { 1683 cancelPollDuration(); 1684 } else if (!(mSourceFlags & Source::FLAG_DYNAMIC_DURATION) 1685 && (flags & Source::FLAG_DYNAMIC_DURATION) 1686 && (mAudioDecoder != NULL || mVideoDecoder != NULL)) { 1687 schedulePollDuration(); 1688 } 1689 1690 mSourceFlags = flags; 1691 break; 1692 } 1693 1694 case Source::kWhatVideoSizeChanged: 1695 { 1696 sp<AMessage> format; 1697 CHECK(msg->findMessage("format", &format)); 1698 1699 updateVideoSize(format); 1700 break; 1701 } 1702 1703 case Source::kWhatBufferingUpdate: 1704 { 1705 int32_t percentage; 1706 CHECK(msg->findInt32("percentage", &percentage)); 1707 1708 notifyListener(MEDIA_BUFFERING_UPDATE, percentage, 0); 1709 break; 1710 } 1711 1712 case Source::kWhatBufferingStart: 1713 { 1714 notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_START, 0); 1715 break; 1716 } 1717 1718 case Source::kWhatBufferingEnd: 1719 { 1720 notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_END, 0); 1721 break; 1722 } 1723 1724 case Source::kWhatSubtitleData: 1725 { 1726 sp<ABuffer> buffer; 1727 CHECK(msg->findBuffer("buffer", &buffer)); 1728 1729 sendSubtitleData(buffer, 0 /* baseIndex */); 1730 break; 1731 } 1732 1733 case Source::kWhatTimedTextData: 1734 { 1735 int32_t generation; 1736 if (msg->findInt32("generation", &generation) 1737 && generation != mTimedTextGeneration) { 1738 break; 1739 } 1740 1741 sp<ABuffer> buffer; 1742 CHECK(msg->findBuffer("buffer", &buffer)); 1743 1744 sp<NuPlayerDriver> driver = mDriver.promote(); 1745 if (driver == NULL) { 1746 break; 1747 } 1748 1749 int posMs; 1750 int64_t timeUs, posUs; 1751 driver->getCurrentPosition(&posMs); 1752 posUs = posMs * 1000; 1753 CHECK(buffer->meta()->findInt64("timeUs", &timeUs)); 1754 1755 if (posUs < timeUs) { 1756 if (!msg->findInt32("generation", &generation)) { 1757 msg->setInt32("generation", mTimedTextGeneration); 1758 } 1759 msg->post(timeUs - posUs); 1760 } else { 1761 sendTimedTextData(buffer); 1762 } 1763 break; 1764 } 1765 1766 case Source::kWhatQueueDecoderShutdown: 1767 { 1768 int32_t audio, video; 1769 CHECK(msg->findInt32("audio", &audio)); 1770 CHECK(msg->findInt32("video", &video)); 1771 1772 sp<AMessage> reply; 1773 CHECK(msg->findMessage("reply", &reply)); 1774 1775 queueDecoderShutdown(audio, video, reply); 1776 break; 1777 } 1778 1779 case Source::kWhatDrmNoLicense: 1780 { 1781 notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_DRM_NO_LICENSE); 1782 break; 1783 } 1784 1785 default: 1786 TRESPASS(); 1787 } 1788} 1789 1790void NuPlayer::onClosedCaptionNotify(const sp<AMessage> &msg) { 1791 int32_t what; 1792 CHECK(msg->findInt32("what", &what)); 1793 1794 switch (what) { 1795 case NuPlayer::CCDecoder::kWhatClosedCaptionData: 1796 { 1797 sp<ABuffer> buffer; 1798 CHECK(msg->findBuffer("buffer", &buffer)); 1799 1800 size_t inbandTracks = 0; 1801 if (mSource != NULL) { 1802 inbandTracks = mSource->getTrackCount(); 1803 } 1804 1805 sendSubtitleData(buffer, inbandTracks); 1806 break; 1807 } 1808 1809 case NuPlayer::CCDecoder::kWhatTrackAdded: 1810 { 1811 notifyListener(MEDIA_INFO, MEDIA_INFO_METADATA_UPDATE, 0); 1812 1813 break; 1814 } 1815 1816 default: 1817 TRESPASS(); 1818 } 1819 1820 1821} 1822 1823void NuPlayer::sendSubtitleData(const sp<ABuffer> &buffer, int32_t baseIndex) { 1824 int32_t trackIndex; 1825 int64_t timeUs, durationUs; 1826 CHECK(buffer->meta()->findInt32("trackIndex", &trackIndex)); 1827 CHECK(buffer->meta()->findInt64("timeUs", &timeUs)); 1828 CHECK(buffer->meta()->findInt64("durationUs", &durationUs)); 1829 1830 Parcel in; 1831 in.writeInt32(trackIndex + baseIndex); 1832 in.writeInt64(timeUs); 1833 in.writeInt64(durationUs); 1834 in.writeInt32(buffer->size()); 1835 in.writeInt32(buffer->size()); 1836 in.write(buffer->data(), buffer->size()); 1837 1838 notifyListener(MEDIA_SUBTITLE_DATA, 0, 0, &in); 1839} 1840 1841void NuPlayer::sendTimedTextData(const sp<ABuffer> &buffer) { 1842 const void *data; 1843 size_t size = 0; 1844 int64_t timeUs; 1845 int32_t flag = TextDescriptions::LOCAL_DESCRIPTIONS; 1846 1847 AString mime; 1848 CHECK(buffer->meta()->findString("mime", &mime)); 1849 CHECK(strcasecmp(mime.c_str(), MEDIA_MIMETYPE_TEXT_3GPP) == 0); 1850 1851 data = buffer->data(); 1852 size = buffer->size(); 1853 1854 Parcel parcel; 1855 if (size > 0) { 1856 CHECK(buffer->meta()->findInt64("timeUs", &timeUs)); 1857 flag |= TextDescriptions::IN_BAND_TEXT_3GPP; 1858 TextDescriptions::getParcelOfDescriptions( 1859 (const uint8_t *)data, size, flag, timeUs / 1000, &parcel); 1860 } 1861 1862 if ((parcel.dataSize() > 0)) { 1863 notifyListener(MEDIA_TIMED_TEXT, 0, 0, &parcel); 1864 } else { // send an empty timed text 1865 notifyListener(MEDIA_TIMED_TEXT, 0, 0); 1866 } 1867} 1868//////////////////////////////////////////////////////////////////////////////// 1869 1870sp<AMessage> NuPlayer::Source::getFormat(bool audio) { 1871 sp<MetaData> meta = getFormatMeta(audio); 1872 1873 if (meta == NULL) { 1874 return NULL; 1875 } 1876 1877 sp<AMessage> msg = new AMessage; 1878 1879 if(convertMetaDataToMessage(meta, &msg) == OK) { 1880 return msg; 1881 } 1882 return NULL; 1883} 1884 1885void NuPlayer::Source::notifyFlagsChanged(uint32_t flags) { 1886 sp<AMessage> notify = dupNotify(); 1887 notify->setInt32("what", kWhatFlagsChanged); 1888 notify->setInt32("flags", flags); 1889 notify->post(); 1890} 1891 1892void NuPlayer::Source::notifyVideoSizeChanged(const sp<AMessage> &format) { 1893 sp<AMessage> notify = dupNotify(); 1894 notify->setInt32("what", kWhatVideoSizeChanged); 1895 notify->setMessage("format", format); 1896 notify->post(); 1897} 1898 1899void NuPlayer::Source::notifyPrepared(status_t err) { 1900 sp<AMessage> notify = dupNotify(); 1901 notify->setInt32("what", kWhatPrepared); 1902 notify->setInt32("err", err); 1903 notify->post(); 1904} 1905 1906void NuPlayer::Source::onMessageReceived(const sp<AMessage> & /* msg */) { 1907 TRESPASS(); 1908} 1909 1910} // namespace android 1911