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