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