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