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