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