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