Home | History | Annotate | Download | only in nuplayer
      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 "NuPlayerDriver.h"
     26 #include "NuPlayerRenderer.h"
     27 #include "NuPlayerSource.h"
     28 #include "RTSPSource.h"
     29 #include "StreamingSource.h"
     30 #include "GenericSource.h"
     31 #include "mp4/MP4Source.h"
     32 
     33 #include "ATSParser.h"
     34 
     35 #include <cutils/properties.h> // for property_get
     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/ACodec.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 
     51 namespace android {
     52 
     53 struct NuPlayer::Action : public RefBase {
     54     Action() {}
     55 
     56     virtual void execute(NuPlayer *player) = 0;
     57 
     58 private:
     59     DISALLOW_EVIL_CONSTRUCTORS(Action);
     60 };
     61 
     62 struct NuPlayer::SeekAction : public Action {
     63     SeekAction(int64_t seekTimeUs)
     64         : mSeekTimeUs(seekTimeUs) {
     65     }
     66 
     67     virtual void execute(NuPlayer *player) {
     68         player->performSeek(mSeekTimeUs);
     69     }
     70 
     71 private:
     72     int64_t mSeekTimeUs;
     73 
     74     DISALLOW_EVIL_CONSTRUCTORS(SeekAction);
     75 };
     76 
     77 struct NuPlayer::SetSurfaceAction : public Action {
     78     SetSurfaceAction(const sp<NativeWindowWrapper> &wrapper)
     79         : mWrapper(wrapper) {
     80     }
     81 
     82     virtual void execute(NuPlayer *player) {
     83         player->performSetSurface(mWrapper);
     84     }
     85 
     86 private:
     87     sp<NativeWindowWrapper> mWrapper;
     88 
     89     DISALLOW_EVIL_CONSTRUCTORS(SetSurfaceAction);
     90 };
     91 
     92 struct NuPlayer::ShutdownDecoderAction : public Action {
     93     ShutdownDecoderAction(bool audio, bool video)
     94         : mAudio(audio),
     95           mVideo(video) {
     96     }
     97 
     98     virtual void execute(NuPlayer *player) {
     99         player->performDecoderShutdown(mAudio, mVideo);
    100     }
    101 
    102 private:
    103     bool mAudio;
    104     bool mVideo;
    105 
    106     DISALLOW_EVIL_CONSTRUCTORS(ShutdownDecoderAction);
    107 };
    108 
    109 struct NuPlayer::PostMessageAction : public Action {
    110     PostMessageAction(const sp<AMessage> &msg)
    111         : mMessage(msg) {
    112     }
    113 
    114     virtual void execute(NuPlayer *) {
    115         mMessage->post();
    116     }
    117 
    118 private:
    119     sp<AMessage> mMessage;
    120 
    121     DISALLOW_EVIL_CONSTRUCTORS(PostMessageAction);
    122 };
    123 
    124 // Use this if there's no state necessary to save in order to execute
    125 // the action.
    126 struct NuPlayer::SimpleAction : public Action {
    127     typedef void (NuPlayer::*ActionFunc)();
    128 
    129     SimpleAction(ActionFunc func)
    130         : mFunc(func) {
    131     }
    132 
    133     virtual void execute(NuPlayer *player) {
    134         (player->*mFunc)();
    135     }
    136 
    137 private:
    138     ActionFunc mFunc;
    139 
    140     DISALLOW_EVIL_CONSTRUCTORS(SimpleAction);
    141 };
    142 
    143 ////////////////////////////////////////////////////////////////////////////////
    144 
    145 NuPlayer::NuPlayer()
    146     : mUIDValid(false),
    147       mSourceFlags(0),
    148       mVideoIsAVC(false),
    149       mAudioEOS(false),
    150       mVideoEOS(false),
    151       mScanSourcesPending(false),
    152       mScanSourcesGeneration(0),
    153       mPollDurationGeneration(0),
    154       mTimeDiscontinuityPending(false),
    155       mFlushingAudio(NONE),
    156       mFlushingVideo(NONE),
    157       mSkipRenderingAudioUntilMediaTimeUs(-1ll),
    158       mSkipRenderingVideoUntilMediaTimeUs(-1ll),
    159       mVideoLateByUs(0ll),
    160       mNumFramesTotal(0ll),
    161       mNumFramesDropped(0ll),
    162       mVideoScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW),
    163       mStarted(false) {
    164 }
    165 
    166 NuPlayer::~NuPlayer() {
    167 }
    168 
    169 void NuPlayer::setUID(uid_t uid) {
    170     mUIDValid = true;
    171     mUID = uid;
    172 }
    173 
    174 void NuPlayer::setDriver(const wp<NuPlayerDriver> &driver) {
    175     mDriver = driver;
    176 }
    177 
    178 void NuPlayer::setDataSourceAsync(const sp<IStreamSource> &source) {
    179     sp<AMessage> msg = new AMessage(kWhatSetDataSource, id());
    180 
    181     sp<AMessage> notify = new AMessage(kWhatSourceNotify, id());
    182 
    183     char prop[PROPERTY_VALUE_MAX];
    184     if (property_get("media.stagefright.use-mp4source", prop, NULL)
    185             && (!strcmp(prop, "1") || !strcasecmp(prop, "true"))) {
    186         msg->setObject("source", new MP4Source(notify, source));
    187     } else {
    188         msg->setObject("source", new StreamingSource(notify, source));
    189     }
    190 
    191     msg->post();
    192 }
    193 
    194 static bool IsHTTPLiveURL(const char *url) {
    195     if (!strncasecmp("http://", url, 7)
    196             || !strncasecmp("https://", url, 8)
    197             || !strncasecmp("file://", url, 7)) {
    198         size_t len = strlen(url);
    199         if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
    200             return true;
    201         }
    202 
    203         if (strstr(url,"m3u8")) {
    204             return true;
    205         }
    206     }
    207 
    208     return false;
    209 }
    210 
    211 void NuPlayer::setDataSourceAsync(
    212         const char *url, const KeyedVector<String8, String8> *headers) {
    213     sp<AMessage> msg = new AMessage(kWhatSetDataSource, id());
    214     size_t len = strlen(url);
    215 
    216     sp<AMessage> notify = new AMessage(kWhatSourceNotify, id());
    217 
    218     sp<Source> source;
    219     if (IsHTTPLiveURL(url)) {
    220         source = new HTTPLiveSource(notify, url, headers, mUIDValid, mUID);
    221     } else if (!strncasecmp(url, "rtsp://", 7)) {
    222         source = new RTSPSource(notify, url, headers, mUIDValid, mUID);
    223     } else if ((!strncasecmp(url, "http://", 7)
    224                 || !strncasecmp(url, "https://", 8))
    225                     && ((len >= 4 && !strcasecmp(".sdp", &url[len - 4]))
    226                     || strstr(url, ".sdp?"))) {
    227         source = new RTSPSource(notify, url, headers, mUIDValid, mUID, true);
    228     } else {
    229         source = new GenericSource(notify, url, headers, mUIDValid, mUID);
    230     }
    231 
    232     msg->setObject("source", source);
    233     msg->post();
    234 }
    235 
    236 void NuPlayer::setDataSourceAsync(int fd, int64_t offset, int64_t length) {
    237     sp<AMessage> msg = new AMessage(kWhatSetDataSource, id());
    238 
    239     sp<AMessage> notify = new AMessage(kWhatSourceNotify, id());
    240 
    241     sp<Source> source = new GenericSource(notify, fd, offset, length);
    242     msg->setObject("source", source);
    243     msg->post();
    244 }
    245 
    246 void NuPlayer::prepareAsync() {
    247     (new AMessage(kWhatPrepare, id()))->post();
    248 }
    249 
    250 void NuPlayer::setVideoSurfaceTextureAsync(
    251         const sp<IGraphicBufferProducer> &bufferProducer) {
    252     sp<AMessage> msg = new AMessage(kWhatSetVideoNativeWindow, id());
    253 
    254     if (bufferProducer == NULL) {
    255         msg->setObject("native-window", NULL);
    256     } else {
    257         msg->setObject(
    258                 "native-window",
    259                 new NativeWindowWrapper(
    260                     new Surface(bufferProducer)));
    261     }
    262 
    263     msg->post();
    264 }
    265 
    266 void NuPlayer::setAudioSink(const sp<MediaPlayerBase::AudioSink> &sink) {
    267     sp<AMessage> msg = new AMessage(kWhatSetAudioSink, id());
    268     msg->setObject("sink", sink);
    269     msg->post();
    270 }
    271 
    272 void NuPlayer::start() {
    273     (new AMessage(kWhatStart, id()))->post();
    274 }
    275 
    276 void NuPlayer::pause() {
    277     (new AMessage(kWhatPause, id()))->post();
    278 }
    279 
    280 void NuPlayer::resume() {
    281     (new AMessage(kWhatResume, id()))->post();
    282 }
    283 
    284 void NuPlayer::resetAsync() {
    285     (new AMessage(kWhatReset, id()))->post();
    286 }
    287 
    288 void NuPlayer::seekToAsync(int64_t seekTimeUs) {
    289     sp<AMessage> msg = new AMessage(kWhatSeek, id());
    290     msg->setInt64("seekTimeUs", seekTimeUs);
    291     msg->post();
    292 }
    293 
    294 // static
    295 bool NuPlayer::IsFlushingState(FlushStatus state, bool *needShutdown) {
    296     switch (state) {
    297         case FLUSHING_DECODER:
    298             if (needShutdown != NULL) {
    299                 *needShutdown = false;
    300             }
    301             return true;
    302 
    303         case FLUSHING_DECODER_SHUTDOWN:
    304             if (needShutdown != NULL) {
    305                 *needShutdown = true;
    306             }
    307             return true;
    308 
    309         default:
    310             return false;
    311     }
    312 }
    313 
    314 void NuPlayer::onMessageReceived(const sp<AMessage> &msg) {
    315     switch (msg->what()) {
    316         case kWhatSetDataSource:
    317         {
    318             ALOGV("kWhatSetDataSource");
    319 
    320             CHECK(mSource == NULL);
    321 
    322             sp<RefBase> obj;
    323             CHECK(msg->findObject("source", &obj));
    324 
    325             mSource = static_cast<Source *>(obj.get());
    326 
    327             looper()->registerHandler(mSource);
    328 
    329             CHECK(mDriver != NULL);
    330             sp<NuPlayerDriver> driver = mDriver.promote();
    331             if (driver != NULL) {
    332                 driver->notifySetDataSourceCompleted(OK);
    333             }
    334             break;
    335         }
    336 
    337         case kWhatPrepare:
    338         {
    339             mSource->prepareAsync();
    340             break;
    341         }
    342 
    343         case kWhatGetTrackInfo:
    344         {
    345             uint32_t replyID;
    346             CHECK(msg->senderAwaitsResponse(&replyID));
    347 
    348             status_t err = INVALID_OPERATION;
    349             if (mSource != NULL) {
    350                 Parcel* reply;
    351                 CHECK(msg->findPointer("reply", (void**)&reply));
    352                 err = mSource->getTrackInfo(reply);
    353             }
    354 
    355             sp<AMessage> response = new AMessage;
    356             response->setInt32("err", err);
    357 
    358             response->postReply(replyID);
    359             break;
    360         }
    361 
    362         case kWhatSelectTrack:
    363         {
    364             uint32_t replyID;
    365             CHECK(msg->senderAwaitsResponse(&replyID));
    366 
    367             status_t err = INVALID_OPERATION;
    368             if (mSource != NULL) {
    369                 size_t trackIndex;
    370                 int32_t select;
    371                 CHECK(msg->findSize("trackIndex", &trackIndex));
    372                 CHECK(msg->findInt32("select", &select));
    373                 err = mSource->selectTrack(trackIndex, select);
    374             }
    375 
    376             sp<AMessage> response = new AMessage;
    377             response->setInt32("err", err);
    378 
    379             response->postReply(replyID);
    380             break;
    381         }
    382 
    383         case kWhatPollDuration:
    384         {
    385             int32_t generation;
    386             CHECK(msg->findInt32("generation", &generation));
    387 
    388             if (generation != mPollDurationGeneration) {
    389                 // stale
    390                 break;
    391             }
    392 
    393             int64_t durationUs;
    394             if (mDriver != NULL && mSource->getDuration(&durationUs) == OK) {
    395                 sp<NuPlayerDriver> driver = mDriver.promote();
    396                 if (driver != NULL) {
    397                     driver->notifyDuration(durationUs);
    398                 }
    399             }
    400 
    401             msg->post(1000000ll);  // poll again in a second.
    402             break;
    403         }
    404 
    405         case kWhatSetVideoNativeWindow:
    406         {
    407             ALOGV("kWhatSetVideoNativeWindow");
    408 
    409             mDeferredActions.push_back(
    410                     new ShutdownDecoderAction(
    411                         false /* audio */, true /* video */));
    412 
    413             sp<RefBase> obj;
    414             CHECK(msg->findObject("native-window", &obj));
    415 
    416             mDeferredActions.push_back(
    417                     new SetSurfaceAction(
    418                         static_cast<NativeWindowWrapper *>(obj.get())));
    419 
    420             if (obj != NULL) {
    421                 // If there is a new surface texture, instantiate decoders
    422                 // again if possible.
    423                 mDeferredActions.push_back(
    424                         new SimpleAction(&NuPlayer::performScanSources));
    425             }
    426 
    427             processDeferredActions();
    428             break;
    429         }
    430 
    431         case kWhatSetAudioSink:
    432         {
    433             ALOGV("kWhatSetAudioSink");
    434 
    435             sp<RefBase> obj;
    436             CHECK(msg->findObject("sink", &obj));
    437 
    438             mAudioSink = static_cast<MediaPlayerBase::AudioSink *>(obj.get());
    439             break;
    440         }
    441 
    442         case kWhatStart:
    443         {
    444             ALOGV("kWhatStart");
    445 
    446             mVideoIsAVC = false;
    447             mAudioEOS = false;
    448             mVideoEOS = false;
    449             mSkipRenderingAudioUntilMediaTimeUs = -1;
    450             mSkipRenderingVideoUntilMediaTimeUs = -1;
    451             mVideoLateByUs = 0;
    452             mNumFramesTotal = 0;
    453             mNumFramesDropped = 0;
    454             mStarted = true;
    455 
    456             mSource->start();
    457 
    458             uint32_t flags = 0;
    459 
    460             if (mSource->isRealTime()) {
    461                 flags |= Renderer::FLAG_REAL_TIME;
    462             }
    463 
    464             mRenderer = new Renderer(
    465                     mAudioSink,
    466                     new AMessage(kWhatRendererNotify, id()),
    467                     flags);
    468 
    469             looper()->registerHandler(mRenderer);
    470 
    471             postScanSources();
    472             break;
    473         }
    474 
    475         case kWhatScanSources:
    476         {
    477             int32_t generation;
    478             CHECK(msg->findInt32("generation", &generation));
    479             if (generation != mScanSourcesGeneration) {
    480                 // Drop obsolete msg.
    481                 break;
    482             }
    483 
    484             mScanSourcesPending = false;
    485 
    486             ALOGV("scanning sources haveAudio=%d, haveVideo=%d",
    487                  mAudioDecoder != NULL, mVideoDecoder != NULL);
    488 
    489             bool mHadAnySourcesBefore =
    490                 (mAudioDecoder != NULL) || (mVideoDecoder != NULL);
    491 
    492             if (mNativeWindow != NULL) {
    493                 instantiateDecoder(false, &mVideoDecoder);
    494             }
    495 
    496             if (mAudioSink != NULL) {
    497                 instantiateDecoder(true, &mAudioDecoder);
    498             }
    499 
    500             if (!mHadAnySourcesBefore
    501                     && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
    502                 // This is the first time we've found anything playable.
    503 
    504                 if (mSourceFlags & Source::FLAG_DYNAMIC_DURATION) {
    505                     schedulePollDuration();
    506                 }
    507             }
    508 
    509             status_t err;
    510             if ((err = mSource->feedMoreTSData()) != OK) {
    511                 if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
    512                     // We're not currently decoding anything (no audio or
    513                     // video tracks found) and we just ran out of input data.
    514 
    515                     if (err == ERROR_END_OF_STREAM) {
    516                         notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
    517                     } else {
    518                         notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
    519                     }
    520                 }
    521                 break;
    522             }
    523 
    524             if ((mAudioDecoder == NULL && mAudioSink != NULL)
    525                     || (mVideoDecoder == NULL && mNativeWindow != NULL)) {
    526                 msg->post(100000ll);
    527                 mScanSourcesPending = true;
    528             }
    529             break;
    530         }
    531 
    532         case kWhatVideoNotify:
    533         case kWhatAudioNotify:
    534         {
    535             bool audio = msg->what() == kWhatAudioNotify;
    536 
    537             sp<AMessage> codecRequest;
    538             CHECK(msg->findMessage("codec-request", &codecRequest));
    539 
    540             int32_t what;
    541             CHECK(codecRequest->findInt32("what", &what));
    542 
    543             if (what == ACodec::kWhatFillThisBuffer) {
    544                 status_t err = feedDecoderInputData(
    545                         audio, codecRequest);
    546 
    547                 if (err == -EWOULDBLOCK) {
    548                     if (mSource->feedMoreTSData() == OK) {
    549                         msg->post(10000ll);
    550                     }
    551                 }
    552             } else if (what == ACodec::kWhatEOS) {
    553                 int32_t err;
    554                 CHECK(codecRequest->findInt32("err", &err));
    555 
    556                 if (err == ERROR_END_OF_STREAM) {
    557                     ALOGV("got %s decoder EOS", audio ? "audio" : "video");
    558                 } else {
    559                     ALOGV("got %s decoder EOS w/ error %d",
    560                          audio ? "audio" : "video",
    561                          err);
    562                 }
    563 
    564                 mRenderer->queueEOS(audio, err);
    565             } else if (what == ACodec::kWhatFlushCompleted) {
    566                 bool needShutdown;
    567 
    568                 if (audio) {
    569                     CHECK(IsFlushingState(mFlushingAudio, &needShutdown));
    570                     mFlushingAudio = FLUSHED;
    571                 } else {
    572                     CHECK(IsFlushingState(mFlushingVideo, &needShutdown));
    573                     mFlushingVideo = FLUSHED;
    574 
    575                     mVideoLateByUs = 0;
    576                 }
    577 
    578                 ALOGV("decoder %s flush completed", audio ? "audio" : "video");
    579 
    580                 if (needShutdown) {
    581                     ALOGV("initiating %s decoder shutdown",
    582                          audio ? "audio" : "video");
    583 
    584                     (audio ? mAudioDecoder : mVideoDecoder)->initiateShutdown();
    585 
    586                     if (audio) {
    587                         mFlushingAudio = SHUTTING_DOWN_DECODER;
    588                     } else {
    589                         mFlushingVideo = SHUTTING_DOWN_DECODER;
    590                     }
    591                 }
    592 
    593                 finishFlushIfPossible();
    594             } else if (what == ACodec::kWhatOutputFormatChanged) {
    595                 if (audio) {
    596                     int32_t numChannels;
    597                     CHECK(codecRequest->findInt32(
    598                                 "channel-count", &numChannels));
    599 
    600                     int32_t sampleRate;
    601                     CHECK(codecRequest->findInt32("sample-rate", &sampleRate));
    602 
    603                     ALOGV("Audio output format changed to %d Hz, %d channels",
    604                          sampleRate, numChannels);
    605 
    606                     mAudioSink->close();
    607 
    608                     audio_output_flags_t flags;
    609                     int64_t durationUs;
    610                     // FIXME: we should handle the case where the video decoder
    611                     // is created after we receive the format change indication.
    612                     // Current code will just make that we select deep buffer
    613                     // with video which should not be a problem as it should
    614                     // not prevent from keeping A/V sync.
    615                     if (mVideoDecoder == NULL &&
    616                             mSource->getDuration(&durationUs) == OK &&
    617                             durationUs
    618                                 > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US) {
    619                         flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
    620                     } else {
    621                         flags = AUDIO_OUTPUT_FLAG_NONE;
    622                     }
    623 
    624                     int32_t channelMask;
    625                     if (!codecRequest->findInt32("channel-mask", &channelMask)) {
    626                         channelMask = CHANNEL_MASK_USE_CHANNEL_ORDER;
    627                     }
    628 
    629                     CHECK_EQ(mAudioSink->open(
    630                                 sampleRate,
    631                                 numChannels,
    632                                 (audio_channel_mask_t)channelMask,
    633                                 AUDIO_FORMAT_PCM_16_BIT,
    634                                 8 /* bufferCount */,
    635                                 NULL,
    636                                 NULL,
    637                                 flags),
    638                              (status_t)OK);
    639                     mAudioSink->start();
    640 
    641                     mRenderer->signalAudioSinkChanged();
    642                 } else {
    643                     // video
    644 
    645                     int32_t width, height;
    646                     CHECK(codecRequest->findInt32("width", &width));
    647                     CHECK(codecRequest->findInt32("height", &height));
    648 
    649                     int32_t cropLeft, cropTop, cropRight, cropBottom;
    650                     CHECK(codecRequest->findRect(
    651                                 "crop",
    652                                 &cropLeft, &cropTop, &cropRight, &cropBottom));
    653 
    654                     int32_t displayWidth = cropRight - cropLeft + 1;
    655                     int32_t displayHeight = cropBottom - cropTop + 1;
    656 
    657                     ALOGV("Video output format changed to %d x %d "
    658                          "(crop: %d x %d @ (%d, %d))",
    659                          width, height,
    660                          displayWidth,
    661                          displayHeight,
    662                          cropLeft, cropTop);
    663 
    664                     sp<AMessage> videoInputFormat =
    665                         mSource->getFormat(false /* audio */);
    666 
    667                     // Take into account sample aspect ratio if necessary:
    668                     int32_t sarWidth, sarHeight;
    669                     if (videoInputFormat->findInt32("sar-width", &sarWidth)
    670                             && videoInputFormat->findInt32(
    671                                 "sar-height", &sarHeight)) {
    672                         ALOGV("Sample aspect ratio %d : %d",
    673                               sarWidth, sarHeight);
    674 
    675                         displayWidth = (displayWidth * sarWidth) / sarHeight;
    676 
    677                         ALOGV("display dimensions %d x %d",
    678                               displayWidth, displayHeight);
    679                     }
    680 
    681                     notifyListener(
    682                             MEDIA_SET_VIDEO_SIZE, displayWidth, displayHeight);
    683                 }
    684             } else if (what == ACodec::kWhatShutdownCompleted) {
    685                 ALOGV("%s shutdown completed", audio ? "audio" : "video");
    686                 if (audio) {
    687                     mAudioDecoder.clear();
    688 
    689                     CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER);
    690                     mFlushingAudio = SHUT_DOWN;
    691                 } else {
    692                     mVideoDecoder.clear();
    693 
    694                     CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER);
    695                     mFlushingVideo = SHUT_DOWN;
    696                 }
    697 
    698                 finishFlushIfPossible();
    699             } else if (what == ACodec::kWhatError) {
    700                 ALOGE("Received error from %s decoder, aborting playback.",
    701                      audio ? "audio" : "video");
    702 
    703                 mRenderer->queueEOS(audio, UNKNOWN_ERROR);
    704             } else if (what == ACodec::kWhatDrainThisBuffer) {
    705                 renderBuffer(audio, codecRequest);
    706             } else if (what != ACodec::kWhatComponentAllocated
    707                     && what != ACodec::kWhatComponentConfigured
    708                     && what != ACodec::kWhatBuffersAllocated) {
    709                 ALOGV("Unhandled codec notification %d '%c%c%c%c'.",
    710                       what,
    711                       what >> 24,
    712                       (what >> 16) & 0xff,
    713                       (what >> 8) & 0xff,
    714                       what & 0xff);
    715             }
    716 
    717             break;
    718         }
    719 
    720         case kWhatRendererNotify:
    721         {
    722             int32_t what;
    723             CHECK(msg->findInt32("what", &what));
    724 
    725             if (what == Renderer::kWhatEOS) {
    726                 int32_t audio;
    727                 CHECK(msg->findInt32("audio", &audio));
    728 
    729                 int32_t finalResult;
    730                 CHECK(msg->findInt32("finalResult", &finalResult));
    731 
    732                 if (audio) {
    733                     mAudioEOS = true;
    734                 } else {
    735                     mVideoEOS = true;
    736                 }
    737 
    738                 if (finalResult == ERROR_END_OF_STREAM) {
    739                     ALOGV("reached %s EOS", audio ? "audio" : "video");
    740                 } else {
    741                     ALOGE("%s track encountered an error (%d)",
    742                          audio ? "audio" : "video", finalResult);
    743 
    744                     notifyListener(
    745                             MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, finalResult);
    746                 }
    747 
    748                 if ((mAudioEOS || mAudioDecoder == NULL)
    749                         && (mVideoEOS || mVideoDecoder == NULL)) {
    750                     notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
    751                 }
    752             } else if (what == Renderer::kWhatPosition) {
    753                 int64_t positionUs;
    754                 CHECK(msg->findInt64("positionUs", &positionUs));
    755 
    756                 CHECK(msg->findInt64("videoLateByUs", &mVideoLateByUs));
    757 
    758                 if (mDriver != NULL) {
    759                     sp<NuPlayerDriver> driver = mDriver.promote();
    760                     if (driver != NULL) {
    761                         driver->notifyPosition(positionUs);
    762 
    763                         driver->notifyFrameStats(
    764                                 mNumFramesTotal, mNumFramesDropped);
    765                     }
    766                 }
    767             } else if (what == Renderer::kWhatFlushComplete) {
    768                 int32_t audio;
    769                 CHECK(msg->findInt32("audio", &audio));
    770 
    771                 ALOGV("renderer %s flush completed.", audio ? "audio" : "video");
    772             } else if (what == Renderer::kWhatVideoRenderingStart) {
    773                 notifyListener(MEDIA_INFO, MEDIA_INFO_RENDERING_START, 0);
    774             } else if (what == Renderer::kWhatMediaRenderingStart) {
    775                 ALOGV("media rendering started");
    776                 notifyListener(MEDIA_STARTED, 0, 0);
    777             }
    778             break;
    779         }
    780 
    781         case kWhatMoreDataQueued:
    782         {
    783             break;
    784         }
    785 
    786         case kWhatReset:
    787         {
    788             ALOGV("kWhatReset");
    789 
    790             mDeferredActions.push_back(
    791                     new ShutdownDecoderAction(
    792                         true /* audio */, true /* video */));
    793 
    794             mDeferredActions.push_back(
    795                     new SimpleAction(&NuPlayer::performReset));
    796 
    797             processDeferredActions();
    798             break;
    799         }
    800 
    801         case kWhatSeek:
    802         {
    803             int64_t seekTimeUs;
    804             CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
    805 
    806             ALOGV("kWhatSeek seekTimeUs=%lld us", seekTimeUs);
    807 
    808             mDeferredActions.push_back(
    809                     new SimpleAction(&NuPlayer::performDecoderFlush));
    810 
    811             mDeferredActions.push_back(new SeekAction(seekTimeUs));
    812 
    813             processDeferredActions();
    814             break;
    815         }
    816 
    817         case kWhatPause:
    818         {
    819             CHECK(mRenderer != NULL);
    820             mSource->pause();
    821             mRenderer->pause();
    822             break;
    823         }
    824 
    825         case kWhatResume:
    826         {
    827             CHECK(mRenderer != NULL);
    828             mSource->resume();
    829             mRenderer->resume();
    830             break;
    831         }
    832 
    833         case kWhatSourceNotify:
    834         {
    835             onSourceNotify(msg);
    836             break;
    837         }
    838 
    839         default:
    840             TRESPASS();
    841             break;
    842     }
    843 }
    844 
    845 void NuPlayer::finishFlushIfPossible() {
    846     if (mFlushingAudio != FLUSHED && mFlushingAudio != SHUT_DOWN) {
    847         return;
    848     }
    849 
    850     if (mFlushingVideo != FLUSHED && mFlushingVideo != SHUT_DOWN) {
    851         return;
    852     }
    853 
    854     ALOGV("both audio and video are flushed now.");
    855 
    856     if (mTimeDiscontinuityPending) {
    857         mRenderer->signalTimeDiscontinuity();
    858         mTimeDiscontinuityPending = false;
    859     }
    860 
    861     if (mAudioDecoder != NULL) {
    862         mAudioDecoder->signalResume();
    863     }
    864 
    865     if (mVideoDecoder != NULL) {
    866         mVideoDecoder->signalResume();
    867     }
    868 
    869     mFlushingAudio = NONE;
    870     mFlushingVideo = NONE;
    871 
    872     processDeferredActions();
    873 }
    874 
    875 void NuPlayer::postScanSources() {
    876     if (mScanSourcesPending) {
    877         return;
    878     }
    879 
    880     sp<AMessage> msg = new AMessage(kWhatScanSources, id());
    881     msg->setInt32("generation", mScanSourcesGeneration);
    882     msg->post();
    883 
    884     mScanSourcesPending = true;
    885 }
    886 
    887 status_t NuPlayer::instantiateDecoder(bool audio, sp<Decoder> *decoder) {
    888     if (*decoder != NULL) {
    889         return OK;
    890     }
    891 
    892     sp<AMessage> format = mSource->getFormat(audio);
    893 
    894     if (format == NULL) {
    895         return -EWOULDBLOCK;
    896     }
    897 
    898     if (!audio) {
    899         AString mime;
    900         CHECK(format->findString("mime", &mime));
    901         mVideoIsAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
    902     }
    903 
    904     sp<AMessage> notify =
    905         new AMessage(audio ? kWhatAudioNotify : kWhatVideoNotify,
    906                      id());
    907 
    908     *decoder = audio ? new Decoder(notify) :
    909                        new Decoder(notify, mNativeWindow);
    910     looper()->registerHandler(*decoder);
    911 
    912     (*decoder)->configure(format);
    913 
    914     return OK;
    915 }
    916 
    917 status_t NuPlayer::feedDecoderInputData(bool audio, const sp<AMessage> &msg) {
    918     sp<AMessage> reply;
    919     CHECK(msg->findMessage("reply", &reply));
    920 
    921     if ((audio && IsFlushingState(mFlushingAudio))
    922             || (!audio && IsFlushingState(mFlushingVideo))) {
    923         reply->setInt32("err", INFO_DISCONTINUITY);
    924         reply->post();
    925         return OK;
    926     }
    927 
    928     sp<ABuffer> accessUnit;
    929 
    930     bool dropAccessUnit;
    931     do {
    932         status_t err = mSource->dequeueAccessUnit(audio, &accessUnit);
    933 
    934         if (err == -EWOULDBLOCK) {
    935             return err;
    936         } else if (err != OK) {
    937             if (err == INFO_DISCONTINUITY) {
    938                 int32_t type;
    939                 CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
    940 
    941                 bool formatChange =
    942                     (audio &&
    943                      (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
    944                     || (!audio &&
    945                             (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
    946 
    947                 bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
    948 
    949                 ALOGI("%s discontinuity (formatChange=%d, time=%d)",
    950                      audio ? "audio" : "video", formatChange, timeChange);
    951 
    952                 if (audio) {
    953                     mSkipRenderingAudioUntilMediaTimeUs = -1;
    954                 } else {
    955                     mSkipRenderingVideoUntilMediaTimeUs = -1;
    956                 }
    957 
    958                 if (timeChange) {
    959                     sp<AMessage> extra;
    960                     if (accessUnit->meta()->findMessage("extra", &extra)
    961                             && extra != NULL) {
    962                         int64_t resumeAtMediaTimeUs;
    963                         if (extra->findInt64(
    964                                     "resume-at-mediatimeUs", &resumeAtMediaTimeUs)) {
    965                             ALOGI("suppressing rendering of %s until %lld us",
    966                                     audio ? "audio" : "video", resumeAtMediaTimeUs);
    967 
    968                             if (audio) {
    969                                 mSkipRenderingAudioUntilMediaTimeUs =
    970                                     resumeAtMediaTimeUs;
    971                             } else {
    972                                 mSkipRenderingVideoUntilMediaTimeUs =
    973                                     resumeAtMediaTimeUs;
    974                             }
    975                         }
    976                     }
    977                 }
    978 
    979                 mTimeDiscontinuityPending =
    980                     mTimeDiscontinuityPending || timeChange;
    981 
    982                 if (formatChange || timeChange) {
    983                     if (mFlushingAudio == NONE && mFlushingVideo == NONE) {
    984                         // And we'll resume scanning sources once we're done
    985                         // flushing.
    986                         mDeferredActions.push_front(
    987                                 new SimpleAction(
    988                                     &NuPlayer::performScanSources));
    989                     }
    990 
    991                     flushDecoder(audio, formatChange);
    992                 } else {
    993                     // This stream is unaffected by the discontinuity
    994 
    995                     if (audio) {
    996                         mFlushingAudio = FLUSHED;
    997                     } else {
    998                         mFlushingVideo = FLUSHED;
    999                     }
   1000 
   1001                     finishFlushIfPossible();
   1002 
   1003                     return -EWOULDBLOCK;
   1004                 }
   1005             }
   1006 
   1007             reply->setInt32("err", err);
   1008             reply->post();
   1009             return OK;
   1010         }
   1011 
   1012         if (!audio) {
   1013             ++mNumFramesTotal;
   1014         }
   1015 
   1016         dropAccessUnit = false;
   1017         if (!audio
   1018                 && mVideoLateByUs > 100000ll
   1019                 && mVideoIsAVC
   1020                 && !IsAVCReferenceFrame(accessUnit)) {
   1021             dropAccessUnit = true;
   1022             ++mNumFramesDropped;
   1023         }
   1024     } while (dropAccessUnit);
   1025 
   1026     // ALOGV("returned a valid buffer of %s data", audio ? "audio" : "video");
   1027 
   1028 #if 0
   1029     int64_t mediaTimeUs;
   1030     CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
   1031     ALOGV("feeding %s input buffer at media time %.2f secs",
   1032          audio ? "audio" : "video",
   1033          mediaTimeUs / 1E6);
   1034 #endif
   1035 
   1036     reply->setBuffer("buffer", accessUnit);
   1037     reply->post();
   1038 
   1039     return OK;
   1040 }
   1041 
   1042 void NuPlayer::renderBuffer(bool audio, const sp<AMessage> &msg) {
   1043     // ALOGV("renderBuffer %s", audio ? "audio" : "video");
   1044 
   1045     sp<AMessage> reply;
   1046     CHECK(msg->findMessage("reply", &reply));
   1047 
   1048     if (IsFlushingState(audio ? mFlushingAudio : mFlushingVideo)) {
   1049         // We're currently attempting to flush the decoder, in order
   1050         // to complete this, the decoder wants all its buffers back,
   1051         // so we don't want any output buffers it sent us (from before
   1052         // we initiated the flush) to be stuck in the renderer's queue.
   1053 
   1054         ALOGV("we're still flushing the %s decoder, sending its output buffer"
   1055              " right back.", audio ? "audio" : "video");
   1056 
   1057         reply->post();
   1058         return;
   1059     }
   1060 
   1061     sp<ABuffer> buffer;
   1062     CHECK(msg->findBuffer("buffer", &buffer));
   1063 
   1064     int64_t &skipUntilMediaTimeUs =
   1065         audio
   1066             ? mSkipRenderingAudioUntilMediaTimeUs
   1067             : mSkipRenderingVideoUntilMediaTimeUs;
   1068 
   1069     if (skipUntilMediaTimeUs >= 0) {
   1070         int64_t mediaTimeUs;
   1071         CHECK(buffer->meta()->findInt64("timeUs", &mediaTimeUs));
   1072 
   1073         if (mediaTimeUs < skipUntilMediaTimeUs) {
   1074             ALOGV("dropping %s buffer at time %lld as requested.",
   1075                  audio ? "audio" : "video",
   1076                  mediaTimeUs);
   1077 
   1078             reply->post();
   1079             return;
   1080         }
   1081 
   1082         skipUntilMediaTimeUs = -1;
   1083     }
   1084 
   1085     mRenderer->queueBuffer(audio, buffer, reply);
   1086 }
   1087 
   1088 void NuPlayer::notifyListener(int msg, int ext1, int ext2, const Parcel *in) {
   1089     if (mDriver == NULL) {
   1090         return;
   1091     }
   1092 
   1093     sp<NuPlayerDriver> driver = mDriver.promote();
   1094 
   1095     if (driver == NULL) {
   1096         return;
   1097     }
   1098 
   1099     driver->notifyListener(msg, ext1, ext2, in);
   1100 }
   1101 
   1102 void NuPlayer::flushDecoder(bool audio, bool needShutdown) {
   1103     ALOGV("[%s] flushDecoder needShutdown=%d",
   1104           audio ? "audio" : "video", needShutdown);
   1105 
   1106     if ((audio && mAudioDecoder == NULL) || (!audio && mVideoDecoder == NULL)) {
   1107         ALOGI("flushDecoder %s without decoder present",
   1108              audio ? "audio" : "video");
   1109     }
   1110 
   1111     // Make sure we don't continue to scan sources until we finish flushing.
   1112     ++mScanSourcesGeneration;
   1113     mScanSourcesPending = false;
   1114 
   1115     (audio ? mAudioDecoder : mVideoDecoder)->signalFlush();
   1116     mRenderer->flush(audio);
   1117 
   1118     FlushStatus newStatus =
   1119         needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;
   1120 
   1121     if (audio) {
   1122         CHECK(mFlushingAudio == NONE
   1123                 || mFlushingAudio == AWAITING_DISCONTINUITY);
   1124 
   1125         mFlushingAudio = newStatus;
   1126 
   1127         if (mFlushingVideo == NONE) {
   1128             mFlushingVideo = (mVideoDecoder != NULL)
   1129                 ? AWAITING_DISCONTINUITY
   1130                 : FLUSHED;
   1131         }
   1132     } else {
   1133         CHECK(mFlushingVideo == NONE
   1134                 || mFlushingVideo == AWAITING_DISCONTINUITY);
   1135 
   1136         mFlushingVideo = newStatus;
   1137 
   1138         if (mFlushingAudio == NONE) {
   1139             mFlushingAudio = (mAudioDecoder != NULL)
   1140                 ? AWAITING_DISCONTINUITY
   1141                 : FLUSHED;
   1142         }
   1143     }
   1144 }
   1145 
   1146 sp<AMessage> NuPlayer::Source::getFormat(bool audio) {
   1147     sp<MetaData> meta = getFormatMeta(audio);
   1148 
   1149     if (meta == NULL) {
   1150         return NULL;
   1151     }
   1152 
   1153     sp<AMessage> msg = new AMessage;
   1154 
   1155     if(convertMetaDataToMessage(meta, &msg) == OK) {
   1156         return msg;
   1157     }
   1158     return NULL;
   1159 }
   1160 
   1161 status_t NuPlayer::setVideoScalingMode(int32_t mode) {
   1162     mVideoScalingMode = mode;
   1163     if (mNativeWindow != NULL) {
   1164         status_t ret = native_window_set_scaling_mode(
   1165                 mNativeWindow->getNativeWindow().get(), mVideoScalingMode);
   1166         if (ret != OK) {
   1167             ALOGE("Failed to set scaling mode (%d): %s",
   1168                 -ret, strerror(-ret));
   1169             return ret;
   1170         }
   1171     }
   1172     return OK;
   1173 }
   1174 
   1175 status_t NuPlayer::getTrackInfo(Parcel* reply) const {
   1176     sp<AMessage> msg = new AMessage(kWhatGetTrackInfo, id());
   1177     msg->setPointer("reply", reply);
   1178 
   1179     sp<AMessage> response;
   1180     status_t err = msg->postAndAwaitResponse(&response);
   1181     return err;
   1182 }
   1183 
   1184 status_t NuPlayer::selectTrack(size_t trackIndex, bool select) {
   1185     sp<AMessage> msg = new AMessage(kWhatSelectTrack, id());
   1186     msg->setSize("trackIndex", trackIndex);
   1187     msg->setInt32("select", select);
   1188 
   1189     sp<AMessage> response;
   1190     status_t err = msg->postAndAwaitResponse(&response);
   1191 
   1192     return err;
   1193 }
   1194 
   1195 void NuPlayer::schedulePollDuration() {
   1196     sp<AMessage> msg = new AMessage(kWhatPollDuration, id());
   1197     msg->setInt32("generation", mPollDurationGeneration);
   1198     msg->post();
   1199 }
   1200 
   1201 void NuPlayer::cancelPollDuration() {
   1202     ++mPollDurationGeneration;
   1203 }
   1204 
   1205 void NuPlayer::processDeferredActions() {
   1206     while (!mDeferredActions.empty()) {
   1207         // We won't execute any deferred actions until we're no longer in
   1208         // an intermediate state, i.e. one more more decoders are currently
   1209         // flushing or shutting down.
   1210 
   1211         if (mRenderer != NULL) {
   1212             // There's an edge case where the renderer owns all output
   1213             // buffers and is paused, therefore the decoder will not read
   1214             // more input data and will never encounter the matching
   1215             // discontinuity. To avoid this, we resume the renderer.
   1216 
   1217             if (mFlushingAudio == AWAITING_DISCONTINUITY
   1218                     || mFlushingVideo == AWAITING_DISCONTINUITY) {
   1219                 mRenderer->resume();
   1220             }
   1221         }
   1222 
   1223         if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
   1224             // We're currently flushing, postpone the reset until that's
   1225             // completed.
   1226 
   1227             ALOGV("postponing action mFlushingAudio=%d, mFlushingVideo=%d",
   1228                   mFlushingAudio, mFlushingVideo);
   1229 
   1230             break;
   1231         }
   1232 
   1233         sp<Action> action = *mDeferredActions.begin();
   1234         mDeferredActions.erase(mDeferredActions.begin());
   1235 
   1236         action->execute(this);
   1237     }
   1238 }
   1239 
   1240 void NuPlayer::performSeek(int64_t seekTimeUs) {
   1241     ALOGV("performSeek seekTimeUs=%lld us (%.2f secs)",
   1242           seekTimeUs,
   1243           seekTimeUs / 1E6);
   1244 
   1245     mSource->seekTo(seekTimeUs);
   1246 
   1247     if (mDriver != NULL) {
   1248         sp<NuPlayerDriver> driver = mDriver.promote();
   1249         if (driver != NULL) {
   1250             driver->notifyPosition(seekTimeUs);
   1251             driver->notifySeekComplete();
   1252         }
   1253     }
   1254 
   1255     // everything's flushed, continue playback.
   1256 }
   1257 
   1258 void NuPlayer::performDecoderFlush() {
   1259     ALOGV("performDecoderFlush");
   1260 
   1261     if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
   1262         return;
   1263     }
   1264 
   1265     mTimeDiscontinuityPending = true;
   1266 
   1267     if (mAudioDecoder != NULL) {
   1268         flushDecoder(true /* audio */, false /* needShutdown */);
   1269     }
   1270 
   1271     if (mVideoDecoder != NULL) {
   1272         flushDecoder(false /* audio */, false /* needShutdown */);
   1273     }
   1274 }
   1275 
   1276 void NuPlayer::performDecoderShutdown(bool audio, bool video) {
   1277     ALOGV("performDecoderShutdown audio=%d, video=%d", audio, video);
   1278 
   1279     if ((!audio || mAudioDecoder == NULL)
   1280             && (!video || mVideoDecoder == NULL)) {
   1281         return;
   1282     }
   1283 
   1284     mTimeDiscontinuityPending = true;
   1285 
   1286     if (mFlushingAudio == NONE && (!audio || mAudioDecoder == NULL)) {
   1287         mFlushingAudio = FLUSHED;
   1288     }
   1289 
   1290     if (mFlushingVideo == NONE && (!video || mVideoDecoder == NULL)) {
   1291         mFlushingVideo = FLUSHED;
   1292     }
   1293 
   1294     if (audio && mAudioDecoder != NULL) {
   1295         flushDecoder(true /* audio */, true /* needShutdown */);
   1296     }
   1297 
   1298     if (video && mVideoDecoder != NULL) {
   1299         flushDecoder(false /* audio */, true /* needShutdown */);
   1300     }
   1301 }
   1302 
   1303 void NuPlayer::performReset() {
   1304     ALOGV("performReset");
   1305 
   1306     CHECK(mAudioDecoder == NULL);
   1307     CHECK(mVideoDecoder == NULL);
   1308 
   1309     cancelPollDuration();
   1310 
   1311     ++mScanSourcesGeneration;
   1312     mScanSourcesPending = false;
   1313 
   1314     mRenderer.clear();
   1315 
   1316     if (mSource != NULL) {
   1317         mSource->stop();
   1318 
   1319         looper()->unregisterHandler(mSource->id());
   1320 
   1321         mSource.clear();
   1322     }
   1323 
   1324     if (mDriver != NULL) {
   1325         sp<NuPlayerDriver> driver = mDriver.promote();
   1326         if (driver != NULL) {
   1327             driver->notifyResetComplete();
   1328         }
   1329     }
   1330 
   1331     mStarted = false;
   1332 }
   1333 
   1334 void NuPlayer::performScanSources() {
   1335     ALOGV("performScanSources");
   1336 
   1337     if (!mStarted) {
   1338         return;
   1339     }
   1340 
   1341     if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
   1342         postScanSources();
   1343     }
   1344 }
   1345 
   1346 void NuPlayer::performSetSurface(const sp<NativeWindowWrapper> &wrapper) {
   1347     ALOGV("performSetSurface");
   1348 
   1349     mNativeWindow = wrapper;
   1350 
   1351     // XXX - ignore error from setVideoScalingMode for now
   1352     setVideoScalingMode(mVideoScalingMode);
   1353 
   1354     if (mDriver != NULL) {
   1355         sp<NuPlayerDriver> driver = mDriver.promote();
   1356         if (driver != NULL) {
   1357             driver->notifySetSurfaceComplete();
   1358         }
   1359     }
   1360 }
   1361 
   1362 void NuPlayer::onSourceNotify(const sp<AMessage> &msg) {
   1363     int32_t what;
   1364     CHECK(msg->findInt32("what", &what));
   1365 
   1366     switch (what) {
   1367         case Source::kWhatPrepared:
   1368         {
   1369             if (mSource == NULL) {
   1370                 // This is a stale notification from a source that was
   1371                 // asynchronously preparing when the client called reset().
   1372                 // We handled the reset, the source is gone.
   1373                 break;
   1374             }
   1375 
   1376             int32_t err;
   1377             CHECK(msg->findInt32("err", &err));
   1378 
   1379             sp<NuPlayerDriver> driver = mDriver.promote();
   1380             if (driver != NULL) {
   1381                 driver->notifyPrepareCompleted(err);
   1382             }
   1383 
   1384             int64_t durationUs;
   1385             if (mDriver != NULL && mSource->getDuration(&durationUs) == OK) {
   1386                 sp<NuPlayerDriver> driver = mDriver.promote();
   1387                 if (driver != NULL) {
   1388                     driver->notifyDuration(durationUs);
   1389                 }
   1390             }
   1391             break;
   1392         }
   1393 
   1394         case Source::kWhatFlagsChanged:
   1395         {
   1396             uint32_t flags;
   1397             CHECK(msg->findInt32("flags", (int32_t *)&flags));
   1398 
   1399             sp<NuPlayerDriver> driver = mDriver.promote();
   1400             if (driver != NULL) {
   1401                 driver->notifyFlagsChanged(flags);
   1402             }
   1403 
   1404             if ((mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
   1405                     && (!(flags & Source::FLAG_DYNAMIC_DURATION))) {
   1406                 cancelPollDuration();
   1407             } else if (!(mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
   1408                     && (flags & Source::FLAG_DYNAMIC_DURATION)
   1409                     && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
   1410                 schedulePollDuration();
   1411             }
   1412 
   1413             mSourceFlags = flags;
   1414             break;
   1415         }
   1416 
   1417         case Source::kWhatVideoSizeChanged:
   1418         {
   1419             int32_t width, height;
   1420             CHECK(msg->findInt32("width", &width));
   1421             CHECK(msg->findInt32("height", &height));
   1422 
   1423             notifyListener(MEDIA_SET_VIDEO_SIZE, width, height);
   1424             break;
   1425         }
   1426 
   1427         case Source::kWhatBufferingStart:
   1428         {
   1429             notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_START, 0);
   1430             break;
   1431         }
   1432 
   1433         case Source::kWhatBufferingEnd:
   1434         {
   1435             notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_END, 0);
   1436             break;
   1437         }
   1438 
   1439         case Source::kWhatSubtitleData:
   1440         {
   1441             sp<ABuffer> buffer;
   1442             CHECK(msg->findBuffer("buffer", &buffer));
   1443 
   1444             int32_t trackIndex;
   1445             int64_t timeUs, durationUs;
   1446             CHECK(buffer->meta()->findInt32("trackIndex", &trackIndex));
   1447             CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
   1448             CHECK(buffer->meta()->findInt64("durationUs", &durationUs));
   1449 
   1450             Parcel in;
   1451             in.writeInt32(trackIndex);
   1452             in.writeInt64(timeUs);
   1453             in.writeInt64(durationUs);
   1454             in.writeInt32(buffer->size());
   1455             in.writeInt32(buffer->size());
   1456             in.write(buffer->data(), buffer->size());
   1457 
   1458             notifyListener(MEDIA_SUBTITLE_DATA, 0, 0, &in);
   1459             break;
   1460         }
   1461 
   1462         case Source::kWhatQueueDecoderShutdown:
   1463         {
   1464             int32_t audio, video;
   1465             CHECK(msg->findInt32("audio", &audio));
   1466             CHECK(msg->findInt32("video", &video));
   1467 
   1468             sp<AMessage> reply;
   1469             CHECK(msg->findMessage("reply", &reply));
   1470 
   1471             queueDecoderShutdown(audio, video, reply);
   1472             break;
   1473         }
   1474 
   1475         default:
   1476             TRESPASS();
   1477     }
   1478 }
   1479 
   1480 ////////////////////////////////////////////////////////////////////////////////
   1481 
   1482 void NuPlayer::Source::notifyFlagsChanged(uint32_t flags) {
   1483     sp<AMessage> notify = dupNotify();
   1484     notify->setInt32("what", kWhatFlagsChanged);
   1485     notify->setInt32("flags", flags);
   1486     notify->post();
   1487 }
   1488 
   1489 void NuPlayer::Source::notifyVideoSizeChanged(int32_t width, int32_t height) {
   1490     sp<AMessage> notify = dupNotify();
   1491     notify->setInt32("what", kWhatVideoSizeChanged);
   1492     notify->setInt32("width", width);
   1493     notify->setInt32("height", height);
   1494     notify->post();
   1495 }
   1496 
   1497 void NuPlayer::Source::notifyPrepared(status_t err) {
   1498     sp<AMessage> notify = dupNotify();
   1499     notify->setInt32("what", kWhatPrepared);
   1500     notify->setInt32("err", err);
   1501     notify->post();
   1502 }
   1503 
   1504 void NuPlayer::Source::onMessageReceived(const sp<AMessage> &msg) {
   1505     TRESPASS();
   1506 }
   1507 
   1508 void NuPlayer::queueDecoderShutdown(
   1509         bool audio, bool video, const sp<AMessage> &reply) {
   1510     ALOGI("queueDecoderShutdown audio=%d, video=%d", audio, video);
   1511 
   1512     mDeferredActions.push_back(
   1513             new ShutdownDecoderAction(audio, video));
   1514 
   1515     mDeferredActions.push_back(
   1516             new SimpleAction(&NuPlayer::performScanSources));
   1517 
   1518     mDeferredActions.push_back(new PostMessageAction(reply));
   1519 
   1520     processDeferredActions();
   1521 }
   1522 
   1523 }  // namespace android
   1524