NuPlayer.cpp revision 202bce11a7f66f27e6dbb6d154ddc123aa62513d
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                const bool hasVideo = (videoFormat != NULL);
633                const bool canOffload = canOffloadStream(
634                        audioMeta, hasVideo, true /* is_streaming */, streamType);
635                if (canOffload) {
636                    if (!mOffloadAudio) {
637                        mRenderer->signalEnableOffloadAudio();
638                    }
639                    // open audio sink early under offload mode.
640                    sp<AMessage> format = mSource->getFormat(true /*audio*/);
641                    tryOpenAudioSinkForOffload(format, hasVideo);
642                }
643                instantiateDecoder(true, &mAudioDecoder);
644            }
645
646            if (!mHadAnySourcesBefore
647                    && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
648                // This is the first time we've found anything playable.
649
650                if (mSourceFlags & Source::FLAG_DYNAMIC_DURATION) {
651                    schedulePollDuration();
652                }
653            }
654
655            status_t err;
656            if ((err = mSource->feedMoreTSData()) != OK) {
657                if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
658                    // We're not currently decoding anything (no audio or
659                    // video tracks found) and we just ran out of input data.
660
661                    if (err == ERROR_END_OF_STREAM) {
662                        notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
663                    } else {
664                        notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
665                    }
666                }
667                break;
668            }
669
670            if ((mAudioDecoder == NULL && mAudioSink != NULL)
671                    || (mVideoDecoder == NULL && mNativeWindow != NULL)) {
672                msg->post(100000ll);
673                mScanSourcesPending = true;
674            }
675            break;
676        }
677
678        case kWhatVideoNotify:
679        case kWhatAudioNotify:
680        {
681            bool audio = msg->what() == kWhatAudioNotify;
682
683            int32_t currentDecoderGeneration =
684                (audio? mAudioDecoderGeneration : mVideoDecoderGeneration);
685            int32_t requesterGeneration = currentDecoderGeneration - 1;
686            CHECK(msg->findInt32("generation", &requesterGeneration));
687
688            if (requesterGeneration != currentDecoderGeneration) {
689                ALOGV("got message from old %s decoder, generation(%d:%d)",
690                        audio ? "audio" : "video", requesterGeneration,
691                        currentDecoderGeneration);
692                sp<AMessage> reply;
693                if (!(msg->findMessage("reply", &reply))) {
694                    return;
695                }
696
697                reply->setInt32("err", INFO_DISCONTINUITY);
698                reply->post();
699                return;
700            }
701
702            int32_t what;
703            CHECK(msg->findInt32("what", &what));
704
705            if (what == DecoderBase::kWhatInputDiscontinuity) {
706                int32_t formatChange;
707                CHECK(msg->findInt32("formatChange", &formatChange));
708
709                ALOGV("%s discontinuity: formatChange %d",
710                        audio ? "audio" : "video", formatChange);
711
712                if (formatChange) {
713                    mDeferredActions.push_back(
714                            new FlushDecoderAction(
715                                audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
716                                audio ? FLUSH_CMD_NONE : FLUSH_CMD_SHUTDOWN));
717                }
718
719                mDeferredActions.push_back(
720                        new SimpleAction(
721                                &NuPlayer::performScanSources));
722
723                processDeferredActions();
724            } else if (what == DecoderBase::kWhatEOS) {
725                int32_t err;
726                CHECK(msg->findInt32("err", &err));
727
728                if (err == ERROR_END_OF_STREAM) {
729                    ALOGV("got %s decoder EOS", audio ? "audio" : "video");
730                } else {
731                    ALOGV("got %s decoder EOS w/ error %d",
732                         audio ? "audio" : "video",
733                         err);
734                }
735
736                mRenderer->queueEOS(audio, err);
737            } else if (what == DecoderBase::kWhatFlushCompleted) {
738                ALOGV("decoder %s flush completed", audio ? "audio" : "video");
739
740                handleFlushComplete(audio, true /* isDecoder */);
741                finishFlushIfPossible();
742            } else if (what == DecoderBase::kWhatVideoSizeChanged) {
743                sp<AMessage> format;
744                CHECK(msg->findMessage("format", &format));
745
746                sp<AMessage> inputFormat =
747                        mSource->getFormat(false /* audio */);
748
749                updateVideoSize(inputFormat, format);
750            } else if (what == DecoderBase::kWhatShutdownCompleted) {
751                ALOGV("%s shutdown completed", audio ? "audio" : "video");
752                if (audio) {
753                    mAudioDecoder.clear();
754                    ++mAudioDecoderGeneration;
755
756                    CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER);
757                    mFlushingAudio = SHUT_DOWN;
758                } else {
759                    mVideoDecoder.clear();
760                    ++mVideoDecoderGeneration;
761
762                    CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER);
763                    mFlushingVideo = SHUT_DOWN;
764                }
765
766                finishFlushIfPossible();
767            } else if (what == DecoderBase::kWhatResumeCompleted) {
768                finishResume();
769            } else if (what == DecoderBase::kWhatError) {
770                status_t err;
771                if (!msg->findInt32("err", &err) || err == OK) {
772                    err = UNKNOWN_ERROR;
773                }
774
775                // Decoder errors can be due to Source (e.g. from streaming),
776                // or from decoding corrupted bitstreams, or from other decoder
777                // MediaCodec operations (e.g. from an ongoing reset or seek).
778                // They may also be due to openAudioSink failure at
779                // decoder start or after a format change.
780                //
781                // We try to gracefully shut down the affected decoder if possible,
782                // rather than trying to force the shutdown with something
783                // similar to performReset(). This method can lead to a hang
784                // if MediaCodec functions block after an error, but they should
785                // typically return INVALID_OPERATION instead of blocking.
786
787                FlushStatus *flushing = audio ? &mFlushingAudio : &mFlushingVideo;
788                ALOGE("received error(%#x) from %s decoder, flushing(%d), now shutting down",
789                        err, audio ? "audio" : "video", *flushing);
790
791                switch (*flushing) {
792                    case NONE:
793                        mDeferredActions.push_back(
794                                new FlushDecoderAction(
795                                    audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
796                                    audio ? FLUSH_CMD_NONE : FLUSH_CMD_SHUTDOWN));
797                        processDeferredActions();
798                        break;
799                    case FLUSHING_DECODER:
800                        *flushing = FLUSHING_DECODER_SHUTDOWN; // initiate shutdown after flush.
801                        break; // Wait for flush to complete.
802                    case FLUSHING_DECODER_SHUTDOWN:
803                        break; // Wait for flush to complete.
804                    case SHUTTING_DOWN_DECODER:
805                        break; // Wait for shutdown to complete.
806                    case FLUSHED:
807                        // Widevine source reads must stop before releasing the video decoder.
808                        if (!audio && mSource != NULL && mSourceFlags & Source::FLAG_SECURE) {
809                            mSource->stop();
810                        }
811                        getDecoder(audio)->initiateShutdown(); // In the middle of a seek.
812                        *flushing = SHUTTING_DOWN_DECODER;     // Shut down.
813                        break;
814                    case SHUT_DOWN:
815                        finishFlushIfPossible();  // Should not occur.
816                        break;                    // Finish anyways.
817                }
818                notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
819            } else {
820                ALOGV("Unhandled decoder notification %d '%c%c%c%c'.",
821                      what,
822                      what >> 24,
823                      (what >> 16) & 0xff,
824                      (what >> 8) & 0xff,
825                      what & 0xff);
826            }
827
828            break;
829        }
830
831        case kWhatRendererNotify:
832        {
833            int32_t requesterGeneration = mRendererGeneration - 1;
834            CHECK(msg->findInt32("generation", &requesterGeneration));
835            if (requesterGeneration != mRendererGeneration) {
836                ALOGV("got message from old renderer, generation(%d:%d)",
837                        requesterGeneration, mRendererGeneration);
838                return;
839            }
840
841            int32_t what;
842            CHECK(msg->findInt32("what", &what));
843
844            if (what == Renderer::kWhatEOS) {
845                int32_t audio;
846                CHECK(msg->findInt32("audio", &audio));
847
848                int32_t finalResult;
849                CHECK(msg->findInt32("finalResult", &finalResult));
850
851                if (audio) {
852                    mAudioEOS = true;
853                } else {
854                    mVideoEOS = true;
855                }
856
857                if (finalResult == ERROR_END_OF_STREAM) {
858                    ALOGV("reached %s EOS", audio ? "audio" : "video");
859                } else {
860                    ALOGE("%s track encountered an error (%d)",
861                         audio ? "audio" : "video", finalResult);
862
863                    notifyListener(
864                            MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, finalResult);
865                }
866
867                if ((mAudioEOS || mAudioDecoder == NULL)
868                        && (mVideoEOS || mVideoDecoder == NULL)) {
869                    notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
870                }
871            } else if (what == Renderer::kWhatFlushComplete) {
872                int32_t audio;
873                CHECK(msg->findInt32("audio", &audio));
874
875                ALOGV("renderer %s flush completed.", audio ? "audio" : "video");
876                handleFlushComplete(audio, false /* isDecoder */);
877                finishFlushIfPossible();
878            } else if (what == Renderer::kWhatVideoRenderingStart) {
879                notifyListener(MEDIA_INFO, MEDIA_INFO_RENDERING_START, 0);
880            } else if (what == Renderer::kWhatMediaRenderingStart) {
881                ALOGV("media rendering started");
882                notifyListener(MEDIA_STARTED, 0, 0);
883            } else if (what == Renderer::kWhatAudioOffloadTearDown) {
884                ALOGV("Tear down audio offload, fall back to s/w path if due to error.");
885                int64_t positionUs;
886                CHECK(msg->findInt64("positionUs", &positionUs));
887                int32_t reason;
888                CHECK(msg->findInt32("reason", &reason));
889                closeAudioSink();
890                mAudioDecoder.clear();
891                ++mAudioDecoderGeneration;
892                mRenderer->flush(
893                        true /* audio */, false /* notifyComplete */);
894                if (mVideoDecoder != NULL) {
895                    mRenderer->flush(
896                            false /* audio */, false /* notifyComplete */);
897                }
898
899                performSeek(positionUs, false /* needNotify */);
900                if (reason == Renderer::kDueToError) {
901                    mRenderer->signalDisableOffloadAudio();
902                    mOffloadAudio = false;
903                    instantiateDecoder(true /* audio */, &mAudioDecoder);
904                }
905            }
906            break;
907        }
908
909        case kWhatMoreDataQueued:
910        {
911            break;
912        }
913
914        case kWhatReset:
915        {
916            ALOGV("kWhatReset");
917
918            mDeferredActions.push_back(
919                    new FlushDecoderAction(
920                        FLUSH_CMD_SHUTDOWN /* audio */,
921                        FLUSH_CMD_SHUTDOWN /* video */));
922
923            mDeferredActions.push_back(
924                    new SimpleAction(&NuPlayer::performReset));
925
926            processDeferredActions();
927            break;
928        }
929
930        case kWhatSeek:
931        {
932            int64_t seekTimeUs;
933            int32_t needNotify;
934            CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
935            CHECK(msg->findInt32("needNotify", &needNotify));
936
937            ALOGV("kWhatSeek seekTimeUs=%lld us, needNotify=%d",
938                    seekTimeUs, needNotify);
939
940            mDeferredActions.push_back(
941                    new FlushDecoderAction(FLUSH_CMD_FLUSH /* audio */,
942                                           FLUSH_CMD_FLUSH /* video */));
943
944            mDeferredActions.push_back(
945                    new SeekAction(seekTimeUs, needNotify));
946
947            // After a flush without shutdown, decoder is paused.
948            // Don't resume it until source seek is done, otherwise it could
949            // start pulling stale data too soon.
950            mDeferredActions.push_back(
951                    new ResumeDecoderAction(needNotify));
952
953            processDeferredActions();
954            break;
955        }
956
957        case kWhatPause:
958        {
959            if (mSource != NULL) {
960                mSource->pause();
961            } else {
962                ALOGW("pause called when source is gone or not set");
963            }
964            if (mRenderer != NULL) {
965                mRenderer->pause();
966            } else {
967                ALOGW("pause called when renderer is gone or not set");
968            }
969            break;
970        }
971
972        case kWhatSourceNotify:
973        {
974            onSourceNotify(msg);
975            break;
976        }
977
978        case kWhatClosedCaptionNotify:
979        {
980            onClosedCaptionNotify(msg);
981            break;
982        }
983
984        default:
985            TRESPASS();
986            break;
987    }
988}
989
990void NuPlayer::onResume() {
991    if (mSource != NULL) {
992        mSource->resume();
993    } else {
994        ALOGW("resume called when source is gone or not set");
995    }
996    // |mAudioDecoder| may have been released due to the pause timeout, so re-create it if
997    // needed.
998    if (audioDecoderStillNeeded() && mAudioDecoder == NULL) {
999        instantiateDecoder(true /* audio */, &mAudioDecoder);
1000    }
1001    if (mRenderer != NULL) {
1002        mRenderer->resume();
1003    } else {
1004        ALOGW("resume called when renderer is gone or not set");
1005    }
1006}
1007
1008void NuPlayer::onStart() {
1009    mOffloadAudio = false;
1010    mAudioEOS = false;
1011    mVideoEOS = false;
1012    mStarted = true;
1013
1014    /* instantiate decoders now for secure playback */
1015    if (mSourceFlags & Source::FLAG_SECURE) {
1016        if (mNativeWindow != NULL) {
1017            instantiateDecoder(false, &mVideoDecoder);
1018        }
1019
1020        if (mAudioSink != NULL) {
1021            instantiateDecoder(true, &mAudioDecoder);
1022        }
1023    }
1024
1025    mSource->start();
1026
1027    uint32_t flags = 0;
1028
1029    if (mSource->isRealTime()) {
1030        flags |= Renderer::FLAG_REAL_TIME;
1031    }
1032
1033    sp<MetaData> audioMeta = mSource->getFormatMeta(true /* audio */);
1034    audio_stream_type_t streamType = AUDIO_STREAM_MUSIC;
1035    if (mAudioSink != NULL) {
1036        streamType = mAudioSink->getAudioStreamType();
1037    }
1038
1039    sp<AMessage> videoFormat = mSource->getFormat(false /* audio */);
1040
1041    mOffloadAudio =
1042        canOffloadStream(audioMeta, (videoFormat != NULL),
1043                         true /* is_streaming */, streamType);
1044    if (mOffloadAudio) {
1045        flags |= Renderer::FLAG_OFFLOAD_AUDIO;
1046    }
1047
1048    sp<AMessage> notify = new AMessage(kWhatRendererNotify, id());
1049    ++mRendererGeneration;
1050    notify->setInt32("generation", mRendererGeneration);
1051    mRenderer = new Renderer(mAudioSink, notify, flags);
1052
1053    mRendererLooper = new ALooper;
1054    mRendererLooper->setName("NuPlayerRenderer");
1055    mRendererLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
1056    mRendererLooper->registerHandler(mRenderer);
1057
1058    sp<MetaData> meta = getFileMeta();
1059    int32_t rate;
1060    if (meta != NULL
1061            && meta->findInt32(kKeyFrameRate, &rate) && rate > 0) {
1062        mRenderer->setVideoFrameRate(rate);
1063    }
1064
1065    if (mVideoDecoder != NULL) {
1066        mVideoDecoder->setRenderer(mRenderer);
1067    }
1068    if (mAudioDecoder != NULL) {
1069        mAudioDecoder->setRenderer(mRenderer);
1070    }
1071
1072    postScanSources();
1073}
1074
1075bool NuPlayer::audioDecoderStillNeeded() {
1076    // Audio decoder is no longer needed if it's in shut/shutting down status.
1077    return ((mFlushingAudio != SHUT_DOWN) && (mFlushingAudio != SHUTTING_DOWN_DECODER));
1078}
1079
1080void NuPlayer::handleFlushComplete(bool audio, bool isDecoder) {
1081    // We wait for both the decoder flush and the renderer flush to complete
1082    // before entering either the FLUSHED or the SHUTTING_DOWN_DECODER state.
1083
1084    mFlushComplete[audio][isDecoder] = true;
1085    if (!mFlushComplete[audio][!isDecoder]) {
1086        return;
1087    }
1088
1089    FlushStatus *state = audio ? &mFlushingAudio : &mFlushingVideo;
1090    switch (*state) {
1091        case FLUSHING_DECODER:
1092        {
1093            *state = FLUSHED;
1094            break;
1095        }
1096
1097        case FLUSHING_DECODER_SHUTDOWN:
1098        {
1099            *state = SHUTTING_DOWN_DECODER;
1100
1101            ALOGV("initiating %s decoder shutdown", audio ? "audio" : "video");
1102            if (!audio) {
1103                // Widevine source reads must stop before releasing the video decoder.
1104                if (mSource != NULL && mSourceFlags & Source::FLAG_SECURE) {
1105                    mSource->stop();
1106                }
1107            }
1108            getDecoder(audio)->initiateShutdown();
1109            break;
1110        }
1111
1112        default:
1113            // decoder flush completes only occur in a flushing state.
1114            LOG_ALWAYS_FATAL_IF(isDecoder, "decoder flush in invalid state %d", *state);
1115            break;
1116    }
1117}
1118
1119void NuPlayer::finishFlushIfPossible() {
1120    if (mFlushingAudio != NONE && mFlushingAudio != FLUSHED
1121            && mFlushingAudio != SHUT_DOWN) {
1122        return;
1123    }
1124
1125    if (mFlushingVideo != NONE && mFlushingVideo != FLUSHED
1126            && mFlushingVideo != SHUT_DOWN) {
1127        return;
1128    }
1129
1130    ALOGV("both audio and video are flushed now.");
1131
1132    mFlushingAudio = NONE;
1133    mFlushingVideo = NONE;
1134
1135    clearFlushComplete();
1136
1137    processDeferredActions();
1138}
1139
1140void NuPlayer::postScanSources() {
1141    if (mScanSourcesPending) {
1142        return;
1143    }
1144
1145    sp<AMessage> msg = new AMessage(kWhatScanSources, id());
1146    msg->setInt32("generation", mScanSourcesGeneration);
1147    msg->post();
1148
1149    mScanSourcesPending = true;
1150}
1151
1152void NuPlayer::tryOpenAudioSinkForOffload(const sp<AMessage> &format, bool hasVideo) {
1153    // Note: This is called early in NuPlayer to determine whether offloading
1154    // is possible; otherwise the decoders call the renderer openAudioSink directly.
1155
1156    status_t err = mRenderer->openAudioSink(
1157            format, true /* offloadOnly */, hasVideo, AUDIO_OUTPUT_FLAG_NONE, &mOffloadAudio);
1158    if (err != OK) {
1159        // Any failure we turn off mOffloadAudio.
1160        mOffloadAudio = false;
1161    } else if (mOffloadAudio) {
1162        sp<MetaData> audioMeta =
1163                mSource->getFormatMeta(true /* audio */);
1164        sendMetaDataToHal(mAudioSink, audioMeta);
1165    }
1166}
1167
1168void NuPlayer::closeAudioSink() {
1169    mRenderer->closeAudioSink();
1170}
1171
1172status_t NuPlayer::instantiateDecoder(bool audio, sp<DecoderBase> *decoder) {
1173    if (*decoder != NULL) {
1174        return OK;
1175    }
1176
1177    sp<AMessage> format = mSource->getFormat(audio);
1178
1179    if (format == NULL) {
1180        return -EWOULDBLOCK;
1181    }
1182
1183    if (!audio) {
1184        AString mime;
1185        CHECK(format->findString("mime", &mime));
1186
1187        sp<AMessage> ccNotify = new AMessage(kWhatClosedCaptionNotify, id());
1188        mCCDecoder = new CCDecoder(ccNotify);
1189
1190        if (mSourceFlags & Source::FLAG_SECURE) {
1191            format->setInt32("secure", true);
1192        }
1193    }
1194
1195    if (audio) {
1196        sp<AMessage> notify = new AMessage(kWhatAudioNotify, id());
1197        ++mAudioDecoderGeneration;
1198        notify->setInt32("generation", mAudioDecoderGeneration);
1199
1200        if (mOffloadAudio) {
1201            *decoder = new DecoderPassThrough(notify, mSource, mRenderer);
1202        } else {
1203            *decoder = new Decoder(notify, mSource, mRenderer);
1204        }
1205    } else {
1206        sp<AMessage> notify = new AMessage(kWhatVideoNotify, id());
1207        ++mVideoDecoderGeneration;
1208        notify->setInt32("generation", mVideoDecoderGeneration);
1209
1210        *decoder = new Decoder(
1211                notify, mSource, mRenderer, mNativeWindow, mCCDecoder);
1212
1213        // enable FRC if high-quality AV sync is requested, even if not
1214        // queuing to native window, as this will even improve textureview
1215        // playback.
1216        {
1217            char value[PROPERTY_VALUE_MAX];
1218            if (property_get("persist.sys.media.avsync", value, NULL) &&
1219                    (!strcmp("1", value) || !strcasecmp("true", value))) {
1220                format->setInt32("auto-frc", 1);
1221            }
1222        }
1223    }
1224    (*decoder)->init();
1225    (*decoder)->configure(format);
1226
1227    // allocate buffers to decrypt widevine source buffers
1228    if (!audio && (mSourceFlags & Source::FLAG_SECURE)) {
1229        Vector<sp<ABuffer> > inputBufs;
1230        CHECK_EQ((*decoder)->getInputBuffers(&inputBufs), (status_t)OK);
1231
1232        Vector<MediaBuffer *> mediaBufs;
1233        for (size_t i = 0; i < inputBufs.size(); i++) {
1234            const sp<ABuffer> &buffer = inputBufs[i];
1235            MediaBuffer *mbuf = new MediaBuffer(buffer->data(), buffer->size());
1236            mediaBufs.push(mbuf);
1237        }
1238
1239        status_t err = mSource->setBuffers(audio, mediaBufs);
1240        if (err != OK) {
1241            for (size_t i = 0; i < mediaBufs.size(); ++i) {
1242                mediaBufs[i]->release();
1243            }
1244            mediaBufs.clear();
1245            ALOGE("Secure source didn't support secure mediaBufs.");
1246            return err;
1247        }
1248    }
1249    return OK;
1250}
1251
1252void NuPlayer::updateVideoSize(
1253        const sp<AMessage> &inputFormat,
1254        const sp<AMessage> &outputFormat) {
1255    if (inputFormat == NULL) {
1256        ALOGW("Unknown video size, reporting 0x0!");
1257        notifyListener(MEDIA_SET_VIDEO_SIZE, 0, 0);
1258        return;
1259    }
1260
1261    int32_t displayWidth, displayHeight;
1262    int32_t cropLeft, cropTop, cropRight, cropBottom;
1263
1264    if (outputFormat != NULL) {
1265        int32_t width, height;
1266        CHECK(outputFormat->findInt32("width", &width));
1267        CHECK(outputFormat->findInt32("height", &height));
1268
1269        int32_t cropLeft, cropTop, cropRight, cropBottom;
1270        CHECK(outputFormat->findRect(
1271                    "crop",
1272                    &cropLeft, &cropTop, &cropRight, &cropBottom));
1273
1274        displayWidth = cropRight - cropLeft + 1;
1275        displayHeight = cropBottom - cropTop + 1;
1276
1277        ALOGV("Video output format changed to %d x %d "
1278             "(crop: %d x %d @ (%d, %d))",
1279             width, height,
1280             displayWidth,
1281             displayHeight,
1282             cropLeft, cropTop);
1283    } else {
1284        CHECK(inputFormat->findInt32("width", &displayWidth));
1285        CHECK(inputFormat->findInt32("height", &displayHeight));
1286
1287        ALOGV("Video input format %d x %d", displayWidth, displayHeight);
1288    }
1289
1290    // Take into account sample aspect ratio if necessary:
1291    int32_t sarWidth, sarHeight;
1292    if (inputFormat->findInt32("sar-width", &sarWidth)
1293            && inputFormat->findInt32("sar-height", &sarHeight)) {
1294        ALOGV("Sample aspect ratio %d : %d", sarWidth, sarHeight);
1295
1296        displayWidth = (displayWidth * sarWidth) / sarHeight;
1297
1298        ALOGV("display dimensions %d x %d", displayWidth, displayHeight);
1299    }
1300
1301    int32_t rotationDegrees;
1302    if (!inputFormat->findInt32("rotation-degrees", &rotationDegrees)) {
1303        rotationDegrees = 0;
1304    }
1305
1306    if (rotationDegrees == 90 || rotationDegrees == 270) {
1307        int32_t tmp = displayWidth;
1308        displayWidth = displayHeight;
1309        displayHeight = tmp;
1310    }
1311
1312    notifyListener(
1313            MEDIA_SET_VIDEO_SIZE,
1314            displayWidth,
1315            displayHeight);
1316}
1317
1318void NuPlayer::notifyListener(int msg, int ext1, int ext2, const Parcel *in) {
1319    if (mDriver == NULL) {
1320        return;
1321    }
1322
1323    sp<NuPlayerDriver> driver = mDriver.promote();
1324
1325    if (driver == NULL) {
1326        return;
1327    }
1328
1329    driver->notifyListener(msg, ext1, ext2, in);
1330}
1331
1332void NuPlayer::flushDecoder(bool audio, bool needShutdown) {
1333    ALOGV("[%s] flushDecoder needShutdown=%d",
1334          audio ? "audio" : "video", needShutdown);
1335
1336    const sp<DecoderBase> &decoder = getDecoder(audio);
1337    if (decoder == NULL) {
1338        ALOGI("flushDecoder %s without decoder present",
1339             audio ? "audio" : "video");
1340        return;
1341    }
1342
1343    // Make sure we don't continue to scan sources until we finish flushing.
1344    ++mScanSourcesGeneration;
1345    mScanSourcesPending = false;
1346
1347    decoder->signalFlush();
1348
1349    FlushStatus newStatus =
1350        needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;
1351
1352    mFlushComplete[audio][false /* isDecoder */] = false;
1353    mFlushComplete[audio][true /* isDecoder */] = false;
1354    if (audio) {
1355        ALOGE_IF(mFlushingAudio != NONE,
1356                "audio flushDecoder() is called in state %d", mFlushingAudio);
1357        mFlushingAudio = newStatus;
1358    } else {
1359        ALOGE_IF(mFlushingVideo != NONE,
1360                "video flushDecoder() is called in state %d", mFlushingVideo);
1361        mFlushingVideo = newStatus;
1362    }
1363}
1364
1365void NuPlayer::queueDecoderShutdown(
1366        bool audio, bool video, const sp<AMessage> &reply) {
1367    ALOGI("queueDecoderShutdown audio=%d, video=%d", audio, video);
1368
1369    mDeferredActions.push_back(
1370            new FlushDecoderAction(
1371                audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
1372                video ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE));
1373
1374    mDeferredActions.push_back(
1375            new SimpleAction(&NuPlayer::performScanSources));
1376
1377    mDeferredActions.push_back(new PostMessageAction(reply));
1378
1379    processDeferredActions();
1380}
1381
1382status_t NuPlayer::setVideoScalingMode(int32_t mode) {
1383    mVideoScalingMode = mode;
1384    if (mNativeWindow != NULL) {
1385        status_t ret = native_window_set_scaling_mode(
1386                mNativeWindow->getNativeWindow().get(), mVideoScalingMode);
1387        if (ret != OK) {
1388            ALOGE("Failed to set scaling mode (%d): %s",
1389                -ret, strerror(-ret));
1390            return ret;
1391        }
1392    }
1393    return OK;
1394}
1395
1396status_t NuPlayer::getTrackInfo(Parcel* reply) const {
1397    sp<AMessage> msg = new AMessage(kWhatGetTrackInfo, id());
1398    msg->setPointer("reply", reply);
1399
1400    sp<AMessage> response;
1401    status_t err = msg->postAndAwaitResponse(&response);
1402    return err;
1403}
1404
1405status_t NuPlayer::getSelectedTrack(int32_t type, Parcel* reply) const {
1406    sp<AMessage> msg = new AMessage(kWhatGetSelectedTrack, id());
1407    msg->setPointer("reply", reply);
1408    msg->setInt32("type", type);
1409
1410    sp<AMessage> response;
1411    status_t err = msg->postAndAwaitResponse(&response);
1412    if (err == OK && response != NULL) {
1413        CHECK(response->findInt32("err", &err));
1414    }
1415    return err;
1416}
1417
1418status_t NuPlayer::selectTrack(size_t trackIndex, bool select, int64_t timeUs) {
1419    sp<AMessage> msg = new AMessage(kWhatSelectTrack, id());
1420    msg->setSize("trackIndex", trackIndex);
1421    msg->setInt32("select", select);
1422    msg->setInt64("timeUs", timeUs);
1423
1424    sp<AMessage> response;
1425    status_t err = msg->postAndAwaitResponse(&response);
1426
1427    if (err != OK) {
1428        return err;
1429    }
1430
1431    if (!response->findInt32("err", &err)) {
1432        err = OK;
1433    }
1434
1435    return err;
1436}
1437
1438status_t NuPlayer::getCurrentPosition(int64_t *mediaUs) {
1439    sp<Renderer> renderer = mRenderer;
1440    if (renderer == NULL) {
1441        return NO_INIT;
1442    }
1443
1444    return renderer->getCurrentPosition(mediaUs);
1445}
1446
1447void NuPlayer::getStats(int64_t *numFramesTotal, int64_t *numFramesDropped) {
1448    sp<DecoderBase> decoder = getDecoder(false /* audio */);
1449    if (decoder != NULL) {
1450        decoder->getStats(numFramesTotal, numFramesDropped);
1451    } else {
1452        *numFramesTotal = 0;
1453        *numFramesDropped = 0;
1454    }
1455}
1456
1457sp<MetaData> NuPlayer::getFileMeta() {
1458    return mSource->getFileFormatMeta();
1459}
1460
1461void NuPlayer::schedulePollDuration() {
1462    sp<AMessage> msg = new AMessage(kWhatPollDuration, id());
1463    msg->setInt32("generation", mPollDurationGeneration);
1464    msg->post();
1465}
1466
1467void NuPlayer::cancelPollDuration() {
1468    ++mPollDurationGeneration;
1469}
1470
1471void NuPlayer::processDeferredActions() {
1472    while (!mDeferredActions.empty()) {
1473        // We won't execute any deferred actions until we're no longer in
1474        // an intermediate state, i.e. one more more decoders are currently
1475        // flushing or shutting down.
1476
1477        if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
1478            // We're currently flushing, postpone the reset until that's
1479            // completed.
1480
1481            ALOGV("postponing action mFlushingAudio=%d, mFlushingVideo=%d",
1482                  mFlushingAudio, mFlushingVideo);
1483
1484            break;
1485        }
1486
1487        sp<Action> action = *mDeferredActions.begin();
1488        mDeferredActions.erase(mDeferredActions.begin());
1489
1490        action->execute(this);
1491    }
1492}
1493
1494void NuPlayer::performSeek(int64_t seekTimeUs, bool needNotify) {
1495    ALOGV("performSeek seekTimeUs=%lld us (%.2f secs), needNotify(%d)",
1496          seekTimeUs,
1497          seekTimeUs / 1E6,
1498          needNotify);
1499
1500    if (mSource == NULL) {
1501        // This happens when reset occurs right before the loop mode
1502        // asynchronously seeks to the start of the stream.
1503        LOG_ALWAYS_FATAL_IF(mAudioDecoder != NULL || mVideoDecoder != NULL,
1504                "mSource is NULL and decoders not NULL audio(%p) video(%p)",
1505                mAudioDecoder.get(), mVideoDecoder.get());
1506        return;
1507    }
1508    mSource->seekTo(seekTimeUs);
1509    ++mTimedTextGeneration;
1510
1511    // everything's flushed, continue playback.
1512}
1513
1514void NuPlayer::performDecoderFlush(FlushCommand audio, FlushCommand video) {
1515    ALOGV("performDecoderFlush audio=%d, video=%d", audio, video);
1516
1517    if ((audio == FLUSH_CMD_NONE || mAudioDecoder == NULL)
1518            && (video == FLUSH_CMD_NONE || mVideoDecoder == NULL)) {
1519        return;
1520    }
1521
1522    if (audio != FLUSH_CMD_NONE && mAudioDecoder != NULL) {
1523        flushDecoder(true /* audio */, (audio == FLUSH_CMD_SHUTDOWN));
1524    }
1525
1526    if (video != FLUSH_CMD_NONE && mVideoDecoder != NULL) {
1527        flushDecoder(false /* audio */, (video == FLUSH_CMD_SHUTDOWN));
1528    }
1529}
1530
1531void NuPlayer::performReset() {
1532    ALOGV("performReset");
1533
1534    CHECK(mAudioDecoder == NULL);
1535    CHECK(mVideoDecoder == NULL);
1536
1537    cancelPollDuration();
1538
1539    ++mScanSourcesGeneration;
1540    mScanSourcesPending = false;
1541
1542    if (mRendererLooper != NULL) {
1543        if (mRenderer != NULL) {
1544            mRendererLooper->unregisterHandler(mRenderer->id());
1545        }
1546        mRendererLooper->stop();
1547        mRendererLooper.clear();
1548    }
1549    mRenderer.clear();
1550    ++mRendererGeneration;
1551
1552    if (mSource != NULL) {
1553        mSource->stop();
1554
1555        mSource.clear();
1556    }
1557
1558    if (mDriver != NULL) {
1559        sp<NuPlayerDriver> driver = mDriver.promote();
1560        if (driver != NULL) {
1561            driver->notifyResetComplete();
1562        }
1563    }
1564
1565    mStarted = false;
1566}
1567
1568void NuPlayer::performScanSources() {
1569    ALOGV("performScanSources");
1570
1571    if (!mStarted) {
1572        return;
1573    }
1574
1575    if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
1576        postScanSources();
1577    }
1578}
1579
1580void NuPlayer::performSetSurface(const sp<NativeWindowWrapper> &wrapper) {
1581    ALOGV("performSetSurface");
1582
1583    mNativeWindow = wrapper;
1584
1585    // XXX - ignore error from setVideoScalingMode for now
1586    setVideoScalingMode(mVideoScalingMode);
1587
1588    if (mDriver != NULL) {
1589        sp<NuPlayerDriver> driver = mDriver.promote();
1590        if (driver != NULL) {
1591            driver->notifySetSurfaceComplete();
1592        }
1593    }
1594}
1595
1596void NuPlayer::performResumeDecoders(bool needNotify) {
1597    if (needNotify) {
1598        mResumePending = true;
1599        if (mVideoDecoder == NULL) {
1600            // if audio-only, we can notify seek complete now,
1601            // as the resume operation will be relatively fast.
1602            finishResume();
1603        }
1604    }
1605
1606    if (mVideoDecoder != NULL) {
1607        // When there is continuous seek, MediaPlayer will cache the seek
1608        // position, and send down new seek request when previous seek is
1609        // complete. Let's wait for at least one video output frame before
1610        // notifying seek complete, so that the video thumbnail gets updated
1611        // when seekbar is dragged.
1612        mVideoDecoder->signalResume(needNotify);
1613    }
1614
1615    if (mAudioDecoder != NULL) {
1616        mAudioDecoder->signalResume(false /* needNotify */);
1617    }
1618}
1619
1620void NuPlayer::finishResume() {
1621    if (mResumePending) {
1622        mResumePending = false;
1623        if (mDriver != NULL) {
1624            sp<NuPlayerDriver> driver = mDriver.promote();
1625            if (driver != NULL) {
1626                driver->notifySeekComplete();
1627            }
1628        }
1629    }
1630}
1631
1632void NuPlayer::onSourceNotify(const sp<AMessage> &msg) {
1633    int32_t what;
1634    CHECK(msg->findInt32("what", &what));
1635
1636    switch (what) {
1637        case Source::kWhatPrepared:
1638        {
1639            if (mSource == NULL) {
1640                // This is a stale notification from a source that was
1641                // asynchronously preparing when the client called reset().
1642                // We handled the reset, the source is gone.
1643                break;
1644            }
1645
1646            int32_t err;
1647            CHECK(msg->findInt32("err", &err));
1648
1649            sp<NuPlayerDriver> driver = mDriver.promote();
1650            if (driver != NULL) {
1651                // notify duration first, so that it's definitely set when
1652                // the app received the "prepare complete" callback.
1653                int64_t durationUs;
1654                if (mSource->getDuration(&durationUs) == OK) {
1655                    driver->notifyDuration(durationUs);
1656                }
1657                driver->notifyPrepareCompleted(err);
1658            }
1659
1660            break;
1661        }
1662
1663        case Source::kWhatFlagsChanged:
1664        {
1665            uint32_t flags;
1666            CHECK(msg->findInt32("flags", (int32_t *)&flags));
1667
1668            sp<NuPlayerDriver> driver = mDriver.promote();
1669            if (driver != NULL) {
1670                driver->notifyFlagsChanged(flags);
1671            }
1672
1673            if ((mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
1674                    && (!(flags & Source::FLAG_DYNAMIC_DURATION))) {
1675                cancelPollDuration();
1676            } else if (!(mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
1677                    && (flags & Source::FLAG_DYNAMIC_DURATION)
1678                    && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
1679                schedulePollDuration();
1680            }
1681
1682            mSourceFlags = flags;
1683            break;
1684        }
1685
1686        case Source::kWhatVideoSizeChanged:
1687        {
1688            sp<AMessage> format;
1689            CHECK(msg->findMessage("format", &format));
1690
1691            updateVideoSize(format);
1692            break;
1693        }
1694
1695        case Source::kWhatBufferingUpdate:
1696        {
1697            int32_t percentage;
1698            CHECK(msg->findInt32("percentage", &percentage));
1699
1700            notifyListener(MEDIA_BUFFERING_UPDATE, percentage, 0);
1701            break;
1702        }
1703
1704        case Source::kWhatBufferingStart:
1705        {
1706            notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_START, 0);
1707            break;
1708        }
1709
1710        case Source::kWhatBufferingEnd:
1711        {
1712            notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_END, 0);
1713            break;
1714        }
1715
1716        case Source::kWhatSubtitleData:
1717        {
1718            sp<ABuffer> buffer;
1719            CHECK(msg->findBuffer("buffer", &buffer));
1720
1721            sendSubtitleData(buffer, 0 /* baseIndex */);
1722            break;
1723        }
1724
1725        case Source::kWhatTimedTextData:
1726        {
1727            int32_t generation;
1728            if (msg->findInt32("generation", &generation)
1729                    && generation != mTimedTextGeneration) {
1730                break;
1731            }
1732
1733            sp<ABuffer> buffer;
1734            CHECK(msg->findBuffer("buffer", &buffer));
1735
1736            sp<NuPlayerDriver> driver = mDriver.promote();
1737            if (driver == NULL) {
1738                break;
1739            }
1740
1741            int posMs;
1742            int64_t timeUs, posUs;
1743            driver->getCurrentPosition(&posMs);
1744            posUs = posMs * 1000;
1745            CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
1746
1747            if (posUs < timeUs) {
1748                if (!msg->findInt32("generation", &generation)) {
1749                    msg->setInt32("generation", mTimedTextGeneration);
1750                }
1751                msg->post(timeUs - posUs);
1752            } else {
1753                sendTimedTextData(buffer);
1754            }
1755            break;
1756        }
1757
1758        case Source::kWhatQueueDecoderShutdown:
1759        {
1760            int32_t audio, video;
1761            CHECK(msg->findInt32("audio", &audio));
1762            CHECK(msg->findInt32("video", &video));
1763
1764            sp<AMessage> reply;
1765            CHECK(msg->findMessage("reply", &reply));
1766
1767            queueDecoderShutdown(audio, video, reply);
1768            break;
1769        }
1770
1771        case Source::kWhatDrmNoLicense:
1772        {
1773            notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_DRM_NO_LICENSE);
1774            break;
1775        }
1776
1777        default:
1778            TRESPASS();
1779    }
1780}
1781
1782void NuPlayer::onClosedCaptionNotify(const sp<AMessage> &msg) {
1783    int32_t what;
1784    CHECK(msg->findInt32("what", &what));
1785
1786    switch (what) {
1787        case NuPlayer::CCDecoder::kWhatClosedCaptionData:
1788        {
1789            sp<ABuffer> buffer;
1790            CHECK(msg->findBuffer("buffer", &buffer));
1791
1792            size_t inbandTracks = 0;
1793            if (mSource != NULL) {
1794                inbandTracks = mSource->getTrackCount();
1795            }
1796
1797            sendSubtitleData(buffer, inbandTracks);
1798            break;
1799        }
1800
1801        case NuPlayer::CCDecoder::kWhatTrackAdded:
1802        {
1803            notifyListener(MEDIA_INFO, MEDIA_INFO_METADATA_UPDATE, 0);
1804
1805            break;
1806        }
1807
1808        default:
1809            TRESPASS();
1810    }
1811
1812
1813}
1814
1815void NuPlayer::sendSubtitleData(const sp<ABuffer> &buffer, int32_t baseIndex) {
1816    int32_t trackIndex;
1817    int64_t timeUs, durationUs;
1818    CHECK(buffer->meta()->findInt32("trackIndex", &trackIndex));
1819    CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
1820    CHECK(buffer->meta()->findInt64("durationUs", &durationUs));
1821
1822    Parcel in;
1823    in.writeInt32(trackIndex + baseIndex);
1824    in.writeInt64(timeUs);
1825    in.writeInt64(durationUs);
1826    in.writeInt32(buffer->size());
1827    in.writeInt32(buffer->size());
1828    in.write(buffer->data(), buffer->size());
1829
1830    notifyListener(MEDIA_SUBTITLE_DATA, 0, 0, &in);
1831}
1832
1833void NuPlayer::sendTimedTextData(const sp<ABuffer> &buffer) {
1834    const void *data;
1835    size_t size = 0;
1836    int64_t timeUs;
1837    int32_t flag = TextDescriptions::LOCAL_DESCRIPTIONS;
1838
1839    AString mime;
1840    CHECK(buffer->meta()->findString("mime", &mime));
1841    CHECK(strcasecmp(mime.c_str(), MEDIA_MIMETYPE_TEXT_3GPP) == 0);
1842
1843    data = buffer->data();
1844    size = buffer->size();
1845
1846    Parcel parcel;
1847    if (size > 0) {
1848        CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
1849        flag |= TextDescriptions::IN_BAND_TEXT_3GPP;
1850        TextDescriptions::getParcelOfDescriptions(
1851                (const uint8_t *)data, size, flag, timeUs / 1000, &parcel);
1852    }
1853
1854    if ((parcel.dataSize() > 0)) {
1855        notifyListener(MEDIA_TIMED_TEXT, 0, 0, &parcel);
1856    } else {  // send an empty timed text
1857        notifyListener(MEDIA_TIMED_TEXT, 0, 0);
1858    }
1859}
1860////////////////////////////////////////////////////////////////////////////////
1861
1862sp<AMessage> NuPlayer::Source::getFormat(bool audio) {
1863    sp<MetaData> meta = getFormatMeta(audio);
1864
1865    if (meta == NULL) {
1866        return NULL;
1867    }
1868
1869    sp<AMessage> msg = new AMessage;
1870
1871    if(convertMetaDataToMessage(meta, &msg) == OK) {
1872        return msg;
1873    }
1874    return NULL;
1875}
1876
1877void NuPlayer::Source::notifyFlagsChanged(uint32_t flags) {
1878    sp<AMessage> notify = dupNotify();
1879    notify->setInt32("what", kWhatFlagsChanged);
1880    notify->setInt32("flags", flags);
1881    notify->post();
1882}
1883
1884void NuPlayer::Source::notifyVideoSizeChanged(const sp<AMessage> &format) {
1885    sp<AMessage> notify = dupNotify();
1886    notify->setInt32("what", kWhatVideoSizeChanged);
1887    notify->setMessage("format", format);
1888    notify->post();
1889}
1890
1891void NuPlayer::Source::notifyPrepared(status_t err) {
1892    sp<AMessage> notify = dupNotify();
1893    notify->setInt32("what", kWhatPrepared);
1894    notify->setInt32("err", err);
1895    notify->post();
1896}
1897
1898void NuPlayer::Source::onMessageReceived(const sp<AMessage> & /* msg */) {
1899    TRESPASS();
1900}
1901
1902}  // namespace android
1903