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