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