NuPlayer.cpp revision 7c4f0d757bfeedaab4b7ef4ccf5b0a72ec8f4306
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 mRenderer->queueEOS(audio, UNKNOWN_ERROR); 905 } else if (what == Decoder::kWhatDrainThisBuffer) { 906 renderBuffer(audio, msg); 907 } else { 908 ALOGV("Unhandled decoder notification %d '%c%c%c%c'.", 909 what, 910 what >> 24, 911 (what >> 16) & 0xff, 912 (what >> 8) & 0xff, 913 what & 0xff); 914 } 915 916 break; 917 } 918 919 case kWhatRendererNotify: 920 { 921 int32_t what; 922 CHECK(msg->findInt32("what", &what)); 923 924 if (what == Renderer::kWhatEOS) { 925 int32_t audio; 926 CHECK(msg->findInt32("audio", &audio)); 927 928 int32_t finalResult; 929 CHECK(msg->findInt32("finalResult", &finalResult)); 930 931 if (audio) { 932 mAudioEOS = true; 933 } else { 934 mVideoEOS = true; 935 } 936 937 if (finalResult == ERROR_END_OF_STREAM) { 938 ALOGV("reached %s EOS", audio ? "audio" : "video"); 939 } else { 940 ALOGE("%s track encountered an error (%d)", 941 audio ? "audio" : "video", finalResult); 942 943 notifyListener( 944 MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, finalResult); 945 } 946 947 if ((mAudioEOS || mAudioDecoder == NULL) 948 && (mVideoEOS || mVideoDecoder == NULL)) { 949 notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0); 950 } 951 } else if (what == Renderer::kWhatPosition) { 952 int64_t positionUs; 953 CHECK(msg->findInt64("positionUs", &positionUs)); 954 955 CHECK(msg->findInt64("videoLateByUs", &mVideoLateByUs)); 956 957 if (mDriver != NULL) { 958 sp<NuPlayerDriver> driver = mDriver.promote(); 959 if (driver != NULL) { 960 driver->notifyPosition(positionUs); 961 962 driver->notifyFrameStats( 963 mNumFramesTotal, mNumFramesDropped); 964 } 965 } 966 } else if (what == Renderer::kWhatFlushComplete) { 967 int32_t audio; 968 CHECK(msg->findInt32("audio", &audio)); 969 970 ALOGV("renderer %s flush completed.", audio ? "audio" : "video"); 971 } else if (what == Renderer::kWhatVideoRenderingStart) { 972 notifyListener(MEDIA_INFO, MEDIA_INFO_RENDERING_START, 0); 973 } else if (what == Renderer::kWhatMediaRenderingStart) { 974 ALOGV("media rendering started"); 975 notifyListener(MEDIA_STARTED, 0, 0); 976 } else if (what == Renderer::kWhatAudioOffloadTearDown) { 977 ALOGV("Tear down audio offload, fall back to s/w path"); 978 int64_t positionUs; 979 CHECK(msg->findInt64("positionUs", &positionUs)); 980 mAudioSink->close(); 981 mAudioDecoder.clear(); 982 mRenderer->flush(true /* audio */); 983 if (mVideoDecoder != NULL) { 984 mRenderer->flush(false /* audio */); 985 } 986 mRenderer->signalDisableOffloadAudio(); 987 mOffloadAudio = false; 988 989 performSeek(positionUs); 990 instantiateDecoder(true /* audio */, &mAudioDecoder); 991 } 992 break; 993 } 994 995 case kWhatMoreDataQueued: 996 { 997 break; 998 } 999 1000 case kWhatReset: 1001 { 1002 ALOGV("kWhatReset"); 1003 1004 mDeferredActions.push_back( 1005 new ShutdownDecoderAction( 1006 true /* audio */, true /* video */)); 1007 1008 mDeferredActions.push_back( 1009 new SimpleAction(&NuPlayer::performReset)); 1010 1011 processDeferredActions(); 1012 break; 1013 } 1014 1015 case kWhatSeek: 1016 { 1017 int64_t seekTimeUs; 1018 CHECK(msg->findInt64("seekTimeUs", &seekTimeUs)); 1019 1020 ALOGV("kWhatSeek seekTimeUs=%lld us", seekTimeUs); 1021 1022 mDeferredActions.push_back( 1023 new SimpleAction(&NuPlayer::performDecoderFlush)); 1024 1025 mDeferredActions.push_back(new SeekAction(seekTimeUs)); 1026 1027 processDeferredActions(); 1028 break; 1029 } 1030 1031 case kWhatPause: 1032 { 1033 CHECK(mRenderer != NULL); 1034 mSource->pause(); 1035 mRenderer->pause(); 1036 break; 1037 } 1038 1039 case kWhatResume: 1040 { 1041 CHECK(mRenderer != NULL); 1042 mSource->resume(); 1043 mRenderer->resume(); 1044 break; 1045 } 1046 1047 case kWhatSourceNotify: 1048 { 1049 onSourceNotify(msg); 1050 break; 1051 } 1052 1053 case kWhatClosedCaptionNotify: 1054 { 1055 onClosedCaptionNotify(msg); 1056 break; 1057 } 1058 1059 default: 1060 TRESPASS(); 1061 break; 1062 } 1063} 1064 1065void NuPlayer::finishFlushIfPossible() { 1066 if (mFlushingAudio != FLUSHED && mFlushingAudio != SHUT_DOWN) { 1067 return; 1068 } 1069 1070 if (mFlushingVideo != FLUSHED && mFlushingVideo != SHUT_DOWN) { 1071 return; 1072 } 1073 1074 ALOGV("both audio and video are flushed now."); 1075 1076 if (mTimeDiscontinuityPending) { 1077 mRenderer->signalTimeDiscontinuity(); 1078 mTimeDiscontinuityPending = false; 1079 } 1080 1081 if (mAudioDecoder != NULL) { 1082 mAudioDecoder->signalResume(); 1083 } 1084 1085 if (mVideoDecoder != NULL) { 1086 mVideoDecoder->signalResume(); 1087 } 1088 1089 mFlushingAudio = NONE; 1090 mFlushingVideo = NONE; 1091 1092 processDeferredActions(); 1093} 1094 1095void NuPlayer::postScanSources() { 1096 if (mScanSourcesPending) { 1097 return; 1098 } 1099 1100 sp<AMessage> msg = new AMessage(kWhatScanSources, id()); 1101 msg->setInt32("generation", mScanSourcesGeneration); 1102 msg->post(); 1103 1104 mScanSourcesPending = true; 1105} 1106 1107status_t NuPlayer::instantiateDecoder(bool audio, sp<Decoder> *decoder) { 1108 if (*decoder != NULL) { 1109 return OK; 1110 } 1111 1112 sp<AMessage> format = mSource->getFormat(audio); 1113 1114 if (format == NULL) { 1115 return -EWOULDBLOCK; 1116 } 1117 1118 if (!audio) { 1119 AString mime; 1120 CHECK(format->findString("mime", &mime)); 1121 mVideoIsAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str()); 1122 1123 sp<AMessage> ccNotify = new AMessage(kWhatClosedCaptionNotify, id()); 1124 mCCDecoder = new CCDecoder(ccNotify); 1125 1126 if (mSourceFlags & Source::FLAG_SECURE) { 1127 format->setInt32("secure", true); 1128 } 1129 } 1130 1131 sp<AMessage> notify = 1132 new AMessage(audio ? kWhatAudioNotify : kWhatVideoNotify, 1133 id()); 1134 1135 if (audio) { 1136 if (mOffloadAudio) { 1137 *decoder = new DecoderPassThrough(notify); 1138 } else { 1139 *decoder = new Decoder(notify); 1140 } 1141 } else { 1142 *decoder = new Decoder(notify, mNativeWindow); 1143 } 1144 (*decoder)->init(); 1145 (*decoder)->configure(format); 1146 1147 // allocate buffers to decrypt widevine source buffers 1148 if (!audio && (mSourceFlags & Source::FLAG_SECURE)) { 1149 Vector<sp<ABuffer> > inputBufs; 1150 CHECK_EQ((*decoder)->getInputBuffers(&inputBufs), (status_t)OK); 1151 1152 Vector<MediaBuffer *> mediaBufs; 1153 for (size_t i = 0; i < inputBufs.size(); i++) { 1154 const sp<ABuffer> &buffer = inputBufs[i]; 1155 MediaBuffer *mbuf = new MediaBuffer(buffer->data(), buffer->size()); 1156 mediaBufs.push(mbuf); 1157 } 1158 1159 status_t err = mSource->setBuffers(audio, mediaBufs); 1160 if (err != OK) { 1161 for (size_t i = 0; i < mediaBufs.size(); ++i) { 1162 mediaBufs[i]->release(); 1163 } 1164 mediaBufs.clear(); 1165 ALOGE("Secure source didn't support secure mediaBufs."); 1166 return err; 1167 } 1168 } 1169 return OK; 1170} 1171 1172status_t NuPlayer::feedDecoderInputData(bool audio, const sp<AMessage> &msg) { 1173 sp<AMessage> reply; 1174 CHECK(msg->findMessage("reply", &reply)); 1175 1176 if ((audio && IsFlushingState(mFlushingAudio)) 1177 || (!audio && IsFlushingState(mFlushingVideo))) { 1178 reply->setInt32("err", INFO_DISCONTINUITY); 1179 reply->post(); 1180 return OK; 1181 } 1182 1183 sp<ABuffer> accessUnit; 1184 1185 bool dropAccessUnit; 1186 do { 1187 status_t err = mSource->dequeueAccessUnit(audio, &accessUnit); 1188 1189 if (err == -EWOULDBLOCK) { 1190 return err; 1191 } else if (err != OK) { 1192 if (err == INFO_DISCONTINUITY) { 1193 int32_t type; 1194 CHECK(accessUnit->meta()->findInt32("discontinuity", &type)); 1195 1196 bool formatChange = 1197 (audio && 1198 (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT)) 1199 || (!audio && 1200 (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT)); 1201 1202 bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0; 1203 1204 ALOGI("%s discontinuity (formatChange=%d, time=%d)", 1205 audio ? "audio" : "video", formatChange, timeChange); 1206 1207 if (audio) { 1208 mSkipRenderingAudioUntilMediaTimeUs = -1; 1209 } else { 1210 mSkipRenderingVideoUntilMediaTimeUs = -1; 1211 } 1212 1213 if (timeChange) { 1214 sp<AMessage> extra; 1215 if (accessUnit->meta()->findMessage("extra", &extra) 1216 && extra != NULL) { 1217 int64_t resumeAtMediaTimeUs; 1218 if (extra->findInt64( 1219 "resume-at-mediatimeUs", &resumeAtMediaTimeUs)) { 1220 ALOGI("suppressing rendering of %s until %lld us", 1221 audio ? "audio" : "video", resumeAtMediaTimeUs); 1222 1223 if (audio) { 1224 mSkipRenderingAudioUntilMediaTimeUs = 1225 resumeAtMediaTimeUs; 1226 } else { 1227 mSkipRenderingVideoUntilMediaTimeUs = 1228 resumeAtMediaTimeUs; 1229 } 1230 } 1231 } 1232 } 1233 1234 mTimeDiscontinuityPending = 1235 mTimeDiscontinuityPending || timeChange; 1236 1237 if (mFlushingAudio == NONE && mFlushingVideo == NONE) { 1238 // And we'll resume scanning sources once we're done 1239 // flushing. 1240 mDeferredActions.push_front( 1241 new SimpleAction( 1242 &NuPlayer::performScanSources)); 1243 } 1244 1245 if (formatChange || timeChange) { 1246 1247 sp<AMessage> newFormat = mSource->getFormat(audio); 1248 sp<Decoder> &decoder = audio ? mAudioDecoder : mVideoDecoder; 1249 if (formatChange && !decoder->supportsSeamlessFormatChange(newFormat)) { 1250 flushDecoder(audio, /* needShutdown = */ true); 1251 } else { 1252 flushDecoder(audio, /* needShutdown = */ false); 1253 err = OK; 1254 } 1255 } else { 1256 // This stream is unaffected by the discontinuity 1257 1258 if (audio) { 1259 mFlushingAudio = FLUSHED; 1260 } else { 1261 mFlushingVideo = FLUSHED; 1262 } 1263 1264 finishFlushIfPossible(); 1265 1266 return -EWOULDBLOCK; 1267 } 1268 } 1269 1270 reply->setInt32("err", err); 1271 reply->post(); 1272 return OK; 1273 } 1274 1275 if (!audio) { 1276 ++mNumFramesTotal; 1277 } 1278 1279 dropAccessUnit = false; 1280 if (!audio 1281 && !(mSourceFlags & Source::FLAG_SECURE) 1282 && mVideoLateByUs > 100000ll 1283 && mVideoIsAVC 1284 && !IsAVCReferenceFrame(accessUnit)) { 1285 dropAccessUnit = true; 1286 ++mNumFramesDropped; 1287 } 1288 } while (dropAccessUnit); 1289 1290 // ALOGV("returned a valid buffer of %s data", audio ? "audio" : "video"); 1291 1292#if 0 1293 int64_t mediaTimeUs; 1294 CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs)); 1295 ALOGV("feeding %s input buffer at media time %.2f secs", 1296 audio ? "audio" : "video", 1297 mediaTimeUs / 1E6); 1298#endif 1299 1300 if (!audio) { 1301 mCCDecoder->decode(accessUnit); 1302 } 1303 1304 reply->setBuffer("buffer", accessUnit); 1305 reply->post(); 1306 1307 return OK; 1308} 1309 1310void NuPlayer::renderBuffer(bool audio, const sp<AMessage> &msg) { 1311 // ALOGV("renderBuffer %s", audio ? "audio" : "video"); 1312 1313 sp<AMessage> reply; 1314 CHECK(msg->findMessage("reply", &reply)); 1315 1316 if (IsFlushingState(audio ? mFlushingAudio : mFlushingVideo)) { 1317 // We're currently attempting to flush the decoder, in order 1318 // to complete this, the decoder wants all its buffers back, 1319 // so we don't want any output buffers it sent us (from before 1320 // we initiated the flush) to be stuck in the renderer's queue. 1321 1322 ALOGV("we're still flushing the %s decoder, sending its output buffer" 1323 " right back.", audio ? "audio" : "video"); 1324 1325 reply->post(); 1326 return; 1327 } 1328 1329 sp<ABuffer> buffer; 1330 CHECK(msg->findBuffer("buffer", &buffer)); 1331 1332 int64_t mediaTimeUs; 1333 CHECK(buffer->meta()->findInt64("timeUs", &mediaTimeUs)); 1334 1335 int64_t &skipUntilMediaTimeUs = 1336 audio 1337 ? mSkipRenderingAudioUntilMediaTimeUs 1338 : mSkipRenderingVideoUntilMediaTimeUs; 1339 1340 if (skipUntilMediaTimeUs >= 0) { 1341 1342 if (mediaTimeUs < skipUntilMediaTimeUs) { 1343 ALOGV("dropping %s buffer at time %lld as requested.", 1344 audio ? "audio" : "video", 1345 mediaTimeUs); 1346 1347 reply->post(); 1348 return; 1349 } 1350 1351 skipUntilMediaTimeUs = -1; 1352 } 1353 1354 if (!audio && mCCDecoder->isSelected()) { 1355 mCCDecoder->display(mediaTimeUs); 1356 } 1357 1358 mRenderer->queueBuffer(audio, buffer, reply); 1359} 1360 1361void NuPlayer::updateVideoSize( 1362 const sp<AMessage> &inputFormat, 1363 const sp<AMessage> &outputFormat) { 1364 if (inputFormat == NULL) { 1365 ALOGW("Unknown video size, reporting 0x0!"); 1366 notifyListener(MEDIA_SET_VIDEO_SIZE, 0, 0); 1367 return; 1368 } 1369 1370 int32_t displayWidth, displayHeight; 1371 int32_t cropLeft, cropTop, cropRight, cropBottom; 1372 1373 if (outputFormat != NULL) { 1374 int32_t width, height; 1375 CHECK(outputFormat->findInt32("width", &width)); 1376 CHECK(outputFormat->findInt32("height", &height)); 1377 1378 int32_t cropLeft, cropTop, cropRight, cropBottom; 1379 CHECK(outputFormat->findRect( 1380 "crop", 1381 &cropLeft, &cropTop, &cropRight, &cropBottom)); 1382 1383 displayWidth = cropRight - cropLeft + 1; 1384 displayHeight = cropBottom - cropTop + 1; 1385 1386 ALOGV("Video output format changed to %d x %d " 1387 "(crop: %d x %d @ (%d, %d))", 1388 width, height, 1389 displayWidth, 1390 displayHeight, 1391 cropLeft, cropTop); 1392 } else { 1393 CHECK(inputFormat->findInt32("width", &displayWidth)); 1394 CHECK(inputFormat->findInt32("height", &displayHeight)); 1395 1396 ALOGV("Video input format %d x %d", displayWidth, displayHeight); 1397 } 1398 1399 // Take into account sample aspect ratio if necessary: 1400 int32_t sarWidth, sarHeight; 1401 if (inputFormat->findInt32("sar-width", &sarWidth) 1402 && inputFormat->findInt32("sar-height", &sarHeight)) { 1403 ALOGV("Sample aspect ratio %d : %d", sarWidth, sarHeight); 1404 1405 displayWidth = (displayWidth * sarWidth) / sarHeight; 1406 1407 ALOGV("display dimensions %d x %d", displayWidth, displayHeight); 1408 } 1409 1410 int32_t rotationDegrees; 1411 if (!inputFormat->findInt32("rotation-degrees", &rotationDegrees)) { 1412 rotationDegrees = 0; 1413 } 1414 1415 if (rotationDegrees == 90 || rotationDegrees == 270) { 1416 int32_t tmp = displayWidth; 1417 displayWidth = displayHeight; 1418 displayHeight = tmp; 1419 } 1420 1421 notifyListener( 1422 MEDIA_SET_VIDEO_SIZE, 1423 displayWidth, 1424 displayHeight); 1425} 1426 1427void NuPlayer::notifyListener(int msg, int ext1, int ext2, const Parcel *in) { 1428 if (mDriver == NULL) { 1429 return; 1430 } 1431 1432 sp<NuPlayerDriver> driver = mDriver.promote(); 1433 1434 if (driver == NULL) { 1435 return; 1436 } 1437 1438 driver->notifyListener(msg, ext1, ext2, in); 1439} 1440 1441void NuPlayer::flushDecoder(bool audio, bool needShutdown) { 1442 ALOGV("[%s] flushDecoder needShutdown=%d", 1443 audio ? "audio" : "video", needShutdown); 1444 1445 if ((audio && mAudioDecoder == NULL) || (!audio && mVideoDecoder == NULL)) { 1446 ALOGI("flushDecoder %s without decoder present", 1447 audio ? "audio" : "video"); 1448 } 1449 1450 // Make sure we don't continue to scan sources until we finish flushing. 1451 ++mScanSourcesGeneration; 1452 mScanSourcesPending = false; 1453 1454 (audio ? mAudioDecoder : mVideoDecoder)->signalFlush(); 1455 mRenderer->flush(audio); 1456 1457 FlushStatus newStatus = 1458 needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER; 1459 1460 if (audio) { 1461 CHECK(mFlushingAudio == NONE 1462 || mFlushingAudio == AWAITING_DISCONTINUITY); 1463 1464 mFlushingAudio = newStatus; 1465 1466 if (mFlushingVideo == NONE) { 1467 mFlushingVideo = (mVideoDecoder != NULL) 1468 ? AWAITING_DISCONTINUITY 1469 : FLUSHED; 1470 } 1471 } else { 1472 CHECK(mFlushingVideo == NONE 1473 || mFlushingVideo == AWAITING_DISCONTINUITY); 1474 1475 mFlushingVideo = newStatus; 1476 1477 if (mFlushingAudio == NONE) { 1478 mFlushingAudio = (mAudioDecoder != NULL) 1479 ? AWAITING_DISCONTINUITY 1480 : FLUSHED; 1481 } 1482 } 1483} 1484 1485void NuPlayer::queueDecoderShutdown( 1486 bool audio, bool video, const sp<AMessage> &reply) { 1487 ALOGI("queueDecoderShutdown audio=%d, video=%d", audio, video); 1488 1489 mDeferredActions.push_back( 1490 new ShutdownDecoderAction(audio, video)); 1491 1492 mDeferredActions.push_back( 1493 new SimpleAction(&NuPlayer::performScanSources)); 1494 1495 mDeferredActions.push_back(new PostMessageAction(reply)); 1496 1497 processDeferredActions(); 1498} 1499 1500status_t NuPlayer::setVideoScalingMode(int32_t mode) { 1501 mVideoScalingMode = mode; 1502 if (mNativeWindow != NULL) { 1503 status_t ret = native_window_set_scaling_mode( 1504 mNativeWindow->getNativeWindow().get(), mVideoScalingMode); 1505 if (ret != OK) { 1506 ALOGE("Failed to set scaling mode (%d): %s", 1507 -ret, strerror(-ret)); 1508 return ret; 1509 } 1510 } 1511 return OK; 1512} 1513 1514status_t NuPlayer::getTrackInfo(Parcel* reply) const { 1515 sp<AMessage> msg = new AMessage(kWhatGetTrackInfo, id()); 1516 msg->setPointer("reply", reply); 1517 1518 sp<AMessage> response; 1519 status_t err = msg->postAndAwaitResponse(&response); 1520 return err; 1521} 1522 1523status_t NuPlayer::getSelectedTrack(int32_t type, Parcel* reply) const { 1524 sp<AMessage> msg = new AMessage(kWhatGetSelectedTrack, id()); 1525 msg->setPointer("reply", reply); 1526 msg->setInt32("type", type); 1527 1528 sp<AMessage> response; 1529 status_t err = msg->postAndAwaitResponse(&response); 1530 if (err == OK && response != NULL) { 1531 CHECK(response->findInt32("err", &err)); 1532 } 1533 return err; 1534} 1535 1536status_t NuPlayer::selectTrack(size_t trackIndex, bool select) { 1537 sp<AMessage> msg = new AMessage(kWhatSelectTrack, id()); 1538 msg->setSize("trackIndex", trackIndex); 1539 msg->setInt32("select", select); 1540 1541 sp<AMessage> response; 1542 status_t err = msg->postAndAwaitResponse(&response); 1543 1544 if (err != OK) { 1545 return err; 1546 } 1547 1548 if (!response->findInt32("err", &err)) { 1549 err = OK; 1550 } 1551 1552 return err; 1553} 1554 1555void NuPlayer::schedulePollDuration() { 1556 sp<AMessage> msg = new AMessage(kWhatPollDuration, id()); 1557 msg->setInt32("generation", mPollDurationGeneration); 1558 msg->post(); 1559} 1560 1561void NuPlayer::cancelPollDuration() { 1562 ++mPollDurationGeneration; 1563} 1564 1565void NuPlayer::processDeferredActions() { 1566 while (!mDeferredActions.empty()) { 1567 // We won't execute any deferred actions until we're no longer in 1568 // an intermediate state, i.e. one more more decoders are currently 1569 // flushing or shutting down. 1570 1571 if (mRenderer != NULL) { 1572 // There's an edge case where the renderer owns all output 1573 // buffers and is paused, therefore the decoder will not read 1574 // more input data and will never encounter the matching 1575 // discontinuity. To avoid this, we resume the renderer. 1576 1577 if (mFlushingAudio == AWAITING_DISCONTINUITY 1578 || mFlushingVideo == AWAITING_DISCONTINUITY) { 1579 mRenderer->resume(); 1580 } 1581 } 1582 1583 if (mFlushingAudio != NONE || mFlushingVideo != NONE) { 1584 // We're currently flushing, postpone the reset until that's 1585 // completed. 1586 1587 ALOGV("postponing action mFlushingAudio=%d, mFlushingVideo=%d", 1588 mFlushingAudio, mFlushingVideo); 1589 1590 break; 1591 } 1592 1593 sp<Action> action = *mDeferredActions.begin(); 1594 mDeferredActions.erase(mDeferredActions.begin()); 1595 1596 action->execute(this); 1597 } 1598} 1599 1600void NuPlayer::performSeek(int64_t seekTimeUs) { 1601 ALOGV("performSeek seekTimeUs=%lld us (%.2f secs)", 1602 seekTimeUs, 1603 seekTimeUs / 1E6); 1604 1605 mSource->seekTo(seekTimeUs); 1606 ++mTimedTextGeneration; 1607 1608 if (mDriver != NULL) { 1609 sp<NuPlayerDriver> driver = mDriver.promote(); 1610 if (driver != NULL) { 1611 driver->notifyPosition(seekTimeUs); 1612 driver->notifySeekComplete(); 1613 } 1614 } 1615 1616 // everything's flushed, continue playback. 1617} 1618 1619void NuPlayer::performDecoderFlush() { 1620 ALOGV("performDecoderFlush"); 1621 1622 if (mAudioDecoder == NULL && mVideoDecoder == NULL) { 1623 return; 1624 } 1625 1626 mTimeDiscontinuityPending = true; 1627 1628 if (mAudioDecoder != NULL) { 1629 flushDecoder(true /* audio */, false /* needShutdown */); 1630 } 1631 1632 if (mVideoDecoder != NULL) { 1633 flushDecoder(false /* audio */, false /* needShutdown */); 1634 } 1635} 1636 1637void NuPlayer::performDecoderShutdown(bool audio, bool video) { 1638 ALOGV("performDecoderShutdown audio=%d, video=%d", audio, video); 1639 1640 if ((!audio || mAudioDecoder == NULL) 1641 && (!video || mVideoDecoder == NULL)) { 1642 return; 1643 } 1644 1645 mTimeDiscontinuityPending = true; 1646 1647 if (mFlushingAudio == NONE && (!audio || mAudioDecoder == NULL)) { 1648 mFlushingAudio = FLUSHED; 1649 } 1650 1651 if (mFlushingVideo == NONE && (!video || mVideoDecoder == NULL)) { 1652 mFlushingVideo = FLUSHED; 1653 } 1654 1655 if (audio && mAudioDecoder != NULL) { 1656 flushDecoder(true /* audio */, true /* needShutdown */); 1657 } 1658 1659 if (video && mVideoDecoder != NULL) { 1660 flushDecoder(false /* audio */, true /* needShutdown */); 1661 } 1662} 1663 1664void NuPlayer::performReset() { 1665 ALOGV("performReset"); 1666 1667 CHECK(mAudioDecoder == NULL); 1668 CHECK(mVideoDecoder == NULL); 1669 1670 cancelPollDuration(); 1671 1672 ++mScanSourcesGeneration; 1673 mScanSourcesPending = false; 1674 1675 if (mRendererLooper != NULL) { 1676 if (mRenderer != NULL) { 1677 mRendererLooper->unregisterHandler(mRenderer->id()); 1678 } 1679 mRendererLooper->stop(); 1680 mRendererLooper.clear(); 1681 } 1682 mRenderer.clear(); 1683 1684 if (mSource != NULL) { 1685 mSource->stop(); 1686 1687 looper()->unregisterHandler(mSource->id()); 1688 1689 mSource.clear(); 1690 } 1691 1692 if (mDriver != NULL) { 1693 sp<NuPlayerDriver> driver = mDriver.promote(); 1694 if (driver != NULL) { 1695 driver->notifyResetComplete(); 1696 } 1697 } 1698 1699 mStarted = false; 1700} 1701 1702void NuPlayer::performScanSources() { 1703 ALOGV("performScanSources"); 1704 1705 if (!mStarted) { 1706 return; 1707 } 1708 1709 if (mAudioDecoder == NULL || mVideoDecoder == NULL) { 1710 postScanSources(); 1711 } 1712} 1713 1714void NuPlayer::performSetSurface(const sp<NativeWindowWrapper> &wrapper) { 1715 ALOGV("performSetSurface"); 1716 1717 mNativeWindow = wrapper; 1718 1719 // XXX - ignore error from setVideoScalingMode for now 1720 setVideoScalingMode(mVideoScalingMode); 1721 1722 if (mDriver != NULL) { 1723 sp<NuPlayerDriver> driver = mDriver.promote(); 1724 if (driver != NULL) { 1725 driver->notifySetSurfaceComplete(); 1726 } 1727 } 1728} 1729 1730void NuPlayer::onSourceNotify(const sp<AMessage> &msg) { 1731 int32_t what; 1732 CHECK(msg->findInt32("what", &what)); 1733 1734 switch (what) { 1735 case Source::kWhatPrepared: 1736 { 1737 if (mSource == NULL) { 1738 // This is a stale notification from a source that was 1739 // asynchronously preparing when the client called reset(). 1740 // We handled the reset, the source is gone. 1741 break; 1742 } 1743 1744 int32_t err; 1745 CHECK(msg->findInt32("err", &err)); 1746 1747 sp<NuPlayerDriver> driver = mDriver.promote(); 1748 if (driver != NULL) { 1749 // notify duration first, so that it's definitely set when 1750 // the app received the "prepare complete" callback. 1751 int64_t durationUs; 1752 if (mSource->getDuration(&durationUs) == OK) { 1753 driver->notifyDuration(durationUs); 1754 } 1755 driver->notifyPrepareCompleted(err); 1756 } 1757 1758 break; 1759 } 1760 1761 case Source::kWhatFlagsChanged: 1762 { 1763 uint32_t flags; 1764 CHECK(msg->findInt32("flags", (int32_t *)&flags)); 1765 1766 sp<NuPlayerDriver> driver = mDriver.promote(); 1767 if (driver != NULL) { 1768 driver->notifyFlagsChanged(flags); 1769 } 1770 1771 if ((mSourceFlags & Source::FLAG_DYNAMIC_DURATION) 1772 && (!(flags & Source::FLAG_DYNAMIC_DURATION))) { 1773 cancelPollDuration(); 1774 } else if (!(mSourceFlags & Source::FLAG_DYNAMIC_DURATION) 1775 && (flags & Source::FLAG_DYNAMIC_DURATION) 1776 && (mAudioDecoder != NULL || mVideoDecoder != NULL)) { 1777 schedulePollDuration(); 1778 } 1779 1780 mSourceFlags = flags; 1781 break; 1782 } 1783 1784 case Source::kWhatVideoSizeChanged: 1785 { 1786 sp<AMessage> format; 1787 CHECK(msg->findMessage("format", &format)); 1788 1789 updateVideoSize(format); 1790 break; 1791 } 1792 1793 case Source::kWhatBufferingStart: 1794 { 1795 notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_START, 0); 1796 break; 1797 } 1798 1799 case Source::kWhatBufferingEnd: 1800 { 1801 notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_END, 0); 1802 break; 1803 } 1804 1805 case Source::kWhatSubtitleData: 1806 { 1807 sp<ABuffer> buffer; 1808 CHECK(msg->findBuffer("buffer", &buffer)); 1809 1810 sendSubtitleData(buffer, 0 /* baseIndex */); 1811 break; 1812 } 1813 1814 case Source::kWhatTimedTextData: 1815 { 1816 int32_t generation; 1817 if (msg->findInt32("generation", &generation) 1818 && generation != mTimedTextGeneration) { 1819 break; 1820 } 1821 1822 sp<ABuffer> buffer; 1823 CHECK(msg->findBuffer("buffer", &buffer)); 1824 1825 sp<NuPlayerDriver> driver = mDriver.promote(); 1826 if (driver == NULL) { 1827 break; 1828 } 1829 1830 int posMs; 1831 int64_t timeUs, posUs; 1832 driver->getCurrentPosition(&posMs); 1833 posUs = posMs * 1000; 1834 CHECK(buffer->meta()->findInt64("timeUs", &timeUs)); 1835 1836 if (posUs < timeUs) { 1837 if (!msg->findInt32("generation", &generation)) { 1838 msg->setInt32("generation", mTimedTextGeneration); 1839 } 1840 msg->post(timeUs - posUs); 1841 } else { 1842 sendTimedTextData(buffer); 1843 } 1844 break; 1845 } 1846 1847 case Source::kWhatQueueDecoderShutdown: 1848 { 1849 int32_t audio, video; 1850 CHECK(msg->findInt32("audio", &audio)); 1851 CHECK(msg->findInt32("video", &video)); 1852 1853 sp<AMessage> reply; 1854 CHECK(msg->findMessage("reply", &reply)); 1855 1856 queueDecoderShutdown(audio, video, reply); 1857 break; 1858 } 1859 1860 default: 1861 TRESPASS(); 1862 } 1863} 1864 1865void NuPlayer::onClosedCaptionNotify(const sp<AMessage> &msg) { 1866 int32_t what; 1867 CHECK(msg->findInt32("what", &what)); 1868 1869 switch (what) { 1870 case NuPlayer::CCDecoder::kWhatClosedCaptionData: 1871 { 1872 sp<ABuffer> buffer; 1873 CHECK(msg->findBuffer("buffer", &buffer)); 1874 1875 size_t inbandTracks = 0; 1876 if (mSource != NULL) { 1877 inbandTracks = mSource->getTrackCount(); 1878 } 1879 1880 sendSubtitleData(buffer, inbandTracks); 1881 break; 1882 } 1883 1884 case NuPlayer::CCDecoder::kWhatTrackAdded: 1885 { 1886 notifyListener(MEDIA_INFO, MEDIA_INFO_METADATA_UPDATE, 0); 1887 1888 break; 1889 } 1890 1891 default: 1892 TRESPASS(); 1893 } 1894 1895 1896} 1897 1898void NuPlayer::sendSubtitleData(const sp<ABuffer> &buffer, int32_t baseIndex) { 1899 int32_t trackIndex; 1900 int64_t timeUs, durationUs; 1901 CHECK(buffer->meta()->findInt32("trackIndex", &trackIndex)); 1902 CHECK(buffer->meta()->findInt64("timeUs", &timeUs)); 1903 CHECK(buffer->meta()->findInt64("durationUs", &durationUs)); 1904 1905 Parcel in; 1906 in.writeInt32(trackIndex + baseIndex); 1907 in.writeInt64(timeUs); 1908 in.writeInt64(durationUs); 1909 in.writeInt32(buffer->size()); 1910 in.writeInt32(buffer->size()); 1911 in.write(buffer->data(), buffer->size()); 1912 1913 notifyListener(MEDIA_SUBTITLE_DATA, 0, 0, &in); 1914} 1915 1916void NuPlayer::sendTimedTextData(const sp<ABuffer> &buffer) { 1917 const void *data; 1918 size_t size = 0; 1919 int64_t timeUs; 1920 int32_t flag = TextDescriptions::LOCAL_DESCRIPTIONS; 1921 1922 AString mime; 1923 CHECK(buffer->meta()->findString("mime", &mime)); 1924 CHECK(strcasecmp(mime.c_str(), MEDIA_MIMETYPE_TEXT_3GPP) == 0); 1925 1926 data = buffer->data(); 1927 size = buffer->size(); 1928 1929 Parcel parcel; 1930 if (size > 0) { 1931 CHECK(buffer->meta()->findInt64("timeUs", &timeUs)); 1932 flag |= TextDescriptions::IN_BAND_TEXT_3GPP; 1933 TextDescriptions::getParcelOfDescriptions( 1934 (const uint8_t *)data, size, flag, timeUs / 1000, &parcel); 1935 } 1936 1937 if ((parcel.dataSize() > 0)) { 1938 notifyListener(MEDIA_TIMED_TEXT, 0, 0, &parcel); 1939 } else { // send an empty timed text 1940 notifyListener(MEDIA_TIMED_TEXT, 0, 0); 1941 } 1942} 1943//////////////////////////////////////////////////////////////////////////////// 1944 1945sp<AMessage> NuPlayer::Source::getFormat(bool audio) { 1946 sp<MetaData> meta = getFormatMeta(audio); 1947 1948 if (meta == NULL) { 1949 return NULL; 1950 } 1951 1952 sp<AMessage> msg = new AMessage; 1953 1954 if(convertMetaDataToMessage(meta, &msg) == OK) { 1955 return msg; 1956 } 1957 return NULL; 1958} 1959 1960void NuPlayer::Source::notifyFlagsChanged(uint32_t flags) { 1961 sp<AMessage> notify = dupNotify(); 1962 notify->setInt32("what", kWhatFlagsChanged); 1963 notify->setInt32("flags", flags); 1964 notify->post(); 1965} 1966 1967void NuPlayer::Source::notifyVideoSizeChanged(const sp<AMessage> &format) { 1968 sp<AMessage> notify = dupNotify(); 1969 notify->setInt32("what", kWhatVideoSizeChanged); 1970 notify->setMessage("format", format); 1971 notify->post(); 1972} 1973 1974void NuPlayer::Source::notifyPrepared(status_t err) { 1975 sp<AMessage> notify = dupNotify(); 1976 notify->setInt32("what", kWhatPrepared); 1977 notify->setInt32("err", err); 1978 notify->post(); 1979} 1980 1981void NuPlayer::Source::onMessageReceived(const sp<AMessage> & /* msg */) { 1982 TRESPASS(); 1983} 1984 1985} // namespace android 1986