NuPlayer.cpp revision 341ab6eebb6a992ec7bdf095420cf82bcab1c6b3
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 == NULL || 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        if (mCCDecoder == NULL) {
1189            mCCDecoder = new CCDecoder(ccNotify);
1190        }
1191
1192        if (mSourceFlags & Source::FLAG_SECURE) {
1193            format->setInt32("secure", true);
1194        }
1195
1196        if (mSourceFlags & Source::FLAG_PROTECTED) {
1197            format->setInt32("protected", true);
1198        }
1199    }
1200
1201    if (audio) {
1202        sp<AMessage> notify = new AMessage(kWhatAudioNotify, id());
1203        ++mAudioDecoderGeneration;
1204        notify->setInt32("generation", mAudioDecoderGeneration);
1205
1206        if (mOffloadAudio) {
1207            *decoder = new DecoderPassThrough(notify, mSource, mRenderer);
1208        } else {
1209            *decoder = new Decoder(notify, mSource, mRenderer);
1210        }
1211    } else {
1212        sp<AMessage> notify = new AMessage(kWhatVideoNotify, id());
1213        ++mVideoDecoderGeneration;
1214        notify->setInt32("generation", mVideoDecoderGeneration);
1215
1216        *decoder = new Decoder(
1217                notify, mSource, mRenderer, mNativeWindow, mCCDecoder);
1218
1219        // enable FRC if high-quality AV sync is requested, even if not
1220        // queuing to native window, as this will even improve textureview
1221        // playback.
1222        {
1223            char value[PROPERTY_VALUE_MAX];
1224            if (property_get("persist.sys.media.avsync", value, NULL) &&
1225                    (!strcmp("1", value) || !strcasecmp("true", value))) {
1226                format->setInt32("auto-frc", 1);
1227            }
1228        }
1229    }
1230    (*decoder)->init();
1231    (*decoder)->configure(format);
1232
1233    // allocate buffers to decrypt widevine source buffers
1234    if (!audio && (mSourceFlags & Source::FLAG_SECURE)) {
1235        Vector<sp<ABuffer> > inputBufs;
1236        CHECK_EQ((*decoder)->getInputBuffers(&inputBufs), (status_t)OK);
1237
1238        Vector<MediaBuffer *> mediaBufs;
1239        for (size_t i = 0; i < inputBufs.size(); i++) {
1240            const sp<ABuffer> &buffer = inputBufs[i];
1241            MediaBuffer *mbuf = new MediaBuffer(buffer->data(), buffer->size());
1242            mediaBufs.push(mbuf);
1243        }
1244
1245        status_t err = mSource->setBuffers(audio, mediaBufs);
1246        if (err != OK) {
1247            for (size_t i = 0; i < mediaBufs.size(); ++i) {
1248                mediaBufs[i]->release();
1249            }
1250            mediaBufs.clear();
1251            ALOGE("Secure source didn't support secure mediaBufs.");
1252            return err;
1253        }
1254    }
1255    return OK;
1256}
1257
1258void NuPlayer::updateVideoSize(
1259        const sp<AMessage> &inputFormat,
1260        const sp<AMessage> &outputFormat) {
1261    if (inputFormat == NULL) {
1262        ALOGW("Unknown video size, reporting 0x0!");
1263        notifyListener(MEDIA_SET_VIDEO_SIZE, 0, 0);
1264        return;
1265    }
1266
1267    int32_t displayWidth, displayHeight;
1268    int32_t cropLeft, cropTop, cropRight, cropBottom;
1269
1270    if (outputFormat != NULL) {
1271        int32_t width, height;
1272        CHECK(outputFormat->findInt32("width", &width));
1273        CHECK(outputFormat->findInt32("height", &height));
1274
1275        int32_t cropLeft, cropTop, cropRight, cropBottom;
1276        CHECK(outputFormat->findRect(
1277                    "crop",
1278                    &cropLeft, &cropTop, &cropRight, &cropBottom));
1279
1280        displayWidth = cropRight - cropLeft + 1;
1281        displayHeight = cropBottom - cropTop + 1;
1282
1283        ALOGV("Video output format changed to %d x %d "
1284             "(crop: %d x %d @ (%d, %d))",
1285             width, height,
1286             displayWidth,
1287             displayHeight,
1288             cropLeft, cropTop);
1289    } else {
1290        CHECK(inputFormat->findInt32("width", &displayWidth));
1291        CHECK(inputFormat->findInt32("height", &displayHeight));
1292
1293        ALOGV("Video input format %d x %d", displayWidth, displayHeight);
1294    }
1295
1296    // Take into account sample aspect ratio if necessary:
1297    int32_t sarWidth, sarHeight;
1298    if (inputFormat->findInt32("sar-width", &sarWidth)
1299            && inputFormat->findInt32("sar-height", &sarHeight)) {
1300        ALOGV("Sample aspect ratio %d : %d", sarWidth, sarHeight);
1301
1302        displayWidth = (displayWidth * sarWidth) / sarHeight;
1303
1304        ALOGV("display dimensions %d x %d", displayWidth, displayHeight);
1305    }
1306
1307    int32_t rotationDegrees;
1308    if (!inputFormat->findInt32("rotation-degrees", &rotationDegrees)) {
1309        rotationDegrees = 0;
1310    }
1311
1312    if (rotationDegrees == 90 || rotationDegrees == 270) {
1313        int32_t tmp = displayWidth;
1314        displayWidth = displayHeight;
1315        displayHeight = tmp;
1316    }
1317
1318    notifyListener(
1319            MEDIA_SET_VIDEO_SIZE,
1320            displayWidth,
1321            displayHeight);
1322}
1323
1324void NuPlayer::notifyListener(int msg, int ext1, int ext2, const Parcel *in) {
1325    if (mDriver == NULL) {
1326        return;
1327    }
1328
1329    sp<NuPlayerDriver> driver = mDriver.promote();
1330
1331    if (driver == NULL) {
1332        return;
1333    }
1334
1335    driver->notifyListener(msg, ext1, ext2, in);
1336}
1337
1338void NuPlayer::flushDecoder(bool audio, bool needShutdown) {
1339    ALOGV("[%s] flushDecoder needShutdown=%d",
1340          audio ? "audio" : "video", needShutdown);
1341
1342    const sp<DecoderBase> &decoder = getDecoder(audio);
1343    if (decoder == NULL) {
1344        ALOGI("flushDecoder %s without decoder present",
1345             audio ? "audio" : "video");
1346        return;
1347    }
1348
1349    // Make sure we don't continue to scan sources until we finish flushing.
1350    ++mScanSourcesGeneration;
1351    mScanSourcesPending = false;
1352
1353    decoder->signalFlush();
1354
1355    FlushStatus newStatus =
1356        needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;
1357
1358    mFlushComplete[audio][false /* isDecoder */] = false;
1359    mFlushComplete[audio][true /* isDecoder */] = false;
1360    if (audio) {
1361        ALOGE_IF(mFlushingAudio != NONE,
1362                "audio flushDecoder() is called in state %d", mFlushingAudio);
1363        mFlushingAudio = newStatus;
1364    } else {
1365        ALOGE_IF(mFlushingVideo != NONE,
1366                "video flushDecoder() is called in state %d", mFlushingVideo);
1367        mFlushingVideo = newStatus;
1368    }
1369}
1370
1371void NuPlayer::queueDecoderShutdown(
1372        bool audio, bool video, const sp<AMessage> &reply) {
1373    ALOGI("queueDecoderShutdown audio=%d, video=%d", audio, video);
1374
1375    mDeferredActions.push_back(
1376            new FlushDecoderAction(
1377                audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
1378                video ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE));
1379
1380    mDeferredActions.push_back(
1381            new SimpleAction(&NuPlayer::performScanSources));
1382
1383    mDeferredActions.push_back(new PostMessageAction(reply));
1384
1385    processDeferredActions();
1386}
1387
1388status_t NuPlayer::setVideoScalingMode(int32_t mode) {
1389    mVideoScalingMode = mode;
1390    if (mNativeWindow != NULL) {
1391        status_t ret = native_window_set_scaling_mode(
1392                mNativeWindow->getNativeWindow().get(), mVideoScalingMode);
1393        if (ret != OK) {
1394            ALOGE("Failed to set scaling mode (%d): %s",
1395                -ret, strerror(-ret));
1396            return ret;
1397        }
1398    }
1399    return OK;
1400}
1401
1402status_t NuPlayer::getTrackInfo(Parcel* reply) const {
1403    sp<AMessage> msg = new AMessage(kWhatGetTrackInfo, id());
1404    msg->setPointer("reply", reply);
1405
1406    sp<AMessage> response;
1407    status_t err = msg->postAndAwaitResponse(&response);
1408    return err;
1409}
1410
1411status_t NuPlayer::getSelectedTrack(int32_t type, Parcel* reply) const {
1412    sp<AMessage> msg = new AMessage(kWhatGetSelectedTrack, id());
1413    msg->setPointer("reply", reply);
1414    msg->setInt32("type", type);
1415
1416    sp<AMessage> response;
1417    status_t err = msg->postAndAwaitResponse(&response);
1418    if (err == OK && response != NULL) {
1419        CHECK(response->findInt32("err", &err));
1420    }
1421    return err;
1422}
1423
1424status_t NuPlayer::selectTrack(size_t trackIndex, bool select, int64_t timeUs) {
1425    sp<AMessage> msg = new AMessage(kWhatSelectTrack, id());
1426    msg->setSize("trackIndex", trackIndex);
1427    msg->setInt32("select", select);
1428    msg->setInt64("timeUs", timeUs);
1429
1430    sp<AMessage> response;
1431    status_t err = msg->postAndAwaitResponse(&response);
1432
1433    if (err != OK) {
1434        return err;
1435    }
1436
1437    if (!response->findInt32("err", &err)) {
1438        err = OK;
1439    }
1440
1441    return err;
1442}
1443
1444status_t NuPlayer::getCurrentPosition(int64_t *mediaUs) {
1445    sp<Renderer> renderer = mRenderer;
1446    if (renderer == NULL) {
1447        return NO_INIT;
1448    }
1449
1450    return renderer->getCurrentPosition(mediaUs);
1451}
1452
1453void NuPlayer::getStats(int64_t *numFramesTotal, int64_t *numFramesDropped) {
1454    sp<DecoderBase> decoder = getDecoder(false /* audio */);
1455    if (decoder != NULL) {
1456        decoder->getStats(numFramesTotal, numFramesDropped);
1457    } else {
1458        *numFramesTotal = 0;
1459        *numFramesDropped = 0;
1460    }
1461}
1462
1463sp<MetaData> NuPlayer::getFileMeta() {
1464    return mSource->getFileFormatMeta();
1465}
1466
1467void NuPlayer::schedulePollDuration() {
1468    sp<AMessage> msg = new AMessage(kWhatPollDuration, id());
1469    msg->setInt32("generation", mPollDurationGeneration);
1470    msg->post();
1471}
1472
1473void NuPlayer::cancelPollDuration() {
1474    ++mPollDurationGeneration;
1475}
1476
1477void NuPlayer::processDeferredActions() {
1478    while (!mDeferredActions.empty()) {
1479        // We won't execute any deferred actions until we're no longer in
1480        // an intermediate state, i.e. one more more decoders are currently
1481        // flushing or shutting down.
1482
1483        if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
1484            // We're currently flushing, postpone the reset until that's
1485            // completed.
1486
1487            ALOGV("postponing action mFlushingAudio=%d, mFlushingVideo=%d",
1488                  mFlushingAudio, mFlushingVideo);
1489
1490            break;
1491        }
1492
1493        sp<Action> action = *mDeferredActions.begin();
1494        mDeferredActions.erase(mDeferredActions.begin());
1495
1496        action->execute(this);
1497    }
1498}
1499
1500void NuPlayer::performSeek(int64_t seekTimeUs, bool needNotify) {
1501    ALOGV("performSeek seekTimeUs=%lld us (%.2f secs), needNotify(%d)",
1502          seekTimeUs,
1503          seekTimeUs / 1E6,
1504          needNotify);
1505
1506    if (mSource == NULL) {
1507        // This happens when reset occurs right before the loop mode
1508        // asynchronously seeks to the start of the stream.
1509        LOG_ALWAYS_FATAL_IF(mAudioDecoder != NULL || mVideoDecoder != NULL,
1510                "mSource is NULL and decoders not NULL audio(%p) video(%p)",
1511                mAudioDecoder.get(), mVideoDecoder.get());
1512        return;
1513    }
1514    mSource->seekTo(seekTimeUs);
1515    ++mTimedTextGeneration;
1516
1517    // everything's flushed, continue playback.
1518}
1519
1520void NuPlayer::performDecoderFlush(FlushCommand audio, FlushCommand video) {
1521    ALOGV("performDecoderFlush audio=%d, video=%d", audio, video);
1522
1523    if ((audio == FLUSH_CMD_NONE || mAudioDecoder == NULL)
1524            && (video == FLUSH_CMD_NONE || mVideoDecoder == NULL)) {
1525        return;
1526    }
1527
1528    if (audio != FLUSH_CMD_NONE && mAudioDecoder != NULL) {
1529        flushDecoder(true /* audio */, (audio == FLUSH_CMD_SHUTDOWN));
1530    }
1531
1532    if (video != FLUSH_CMD_NONE && mVideoDecoder != NULL) {
1533        flushDecoder(false /* audio */, (video == FLUSH_CMD_SHUTDOWN));
1534    }
1535}
1536
1537void NuPlayer::performReset() {
1538    ALOGV("performReset");
1539
1540    CHECK(mAudioDecoder == NULL);
1541    CHECK(mVideoDecoder == NULL);
1542
1543    cancelPollDuration();
1544
1545    ++mScanSourcesGeneration;
1546    mScanSourcesPending = false;
1547
1548    if (mRendererLooper != NULL) {
1549        if (mRenderer != NULL) {
1550            mRendererLooper->unregisterHandler(mRenderer->id());
1551        }
1552        mRendererLooper->stop();
1553        mRendererLooper.clear();
1554    }
1555    mRenderer.clear();
1556    ++mRendererGeneration;
1557
1558    if (mSource != NULL) {
1559        mSource->stop();
1560
1561        mSource.clear();
1562    }
1563
1564    if (mDriver != NULL) {
1565        sp<NuPlayerDriver> driver = mDriver.promote();
1566        if (driver != NULL) {
1567            driver->notifyResetComplete();
1568        }
1569    }
1570
1571    mStarted = false;
1572}
1573
1574void NuPlayer::performScanSources() {
1575    ALOGV("performScanSources");
1576
1577    if (!mStarted) {
1578        return;
1579    }
1580
1581    if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
1582        postScanSources();
1583    }
1584}
1585
1586void NuPlayer::performSetSurface(const sp<NativeWindowWrapper> &wrapper) {
1587    ALOGV("performSetSurface");
1588
1589    mNativeWindow = wrapper;
1590
1591    // XXX - ignore error from setVideoScalingMode for now
1592    setVideoScalingMode(mVideoScalingMode);
1593
1594    if (mDriver != NULL) {
1595        sp<NuPlayerDriver> driver = mDriver.promote();
1596        if (driver != NULL) {
1597            driver->notifySetSurfaceComplete();
1598        }
1599    }
1600}
1601
1602void NuPlayer::performResumeDecoders(bool needNotify) {
1603    if (needNotify) {
1604        mResumePending = true;
1605        if (mVideoDecoder == NULL) {
1606            // if audio-only, we can notify seek complete now,
1607            // as the resume operation will be relatively fast.
1608            finishResume();
1609        }
1610    }
1611
1612    if (mVideoDecoder != NULL) {
1613        // When there is continuous seek, MediaPlayer will cache the seek
1614        // position, and send down new seek request when previous seek is
1615        // complete. Let's wait for at least one video output frame before
1616        // notifying seek complete, so that the video thumbnail gets updated
1617        // when seekbar is dragged.
1618        mVideoDecoder->signalResume(needNotify);
1619    }
1620
1621    if (mAudioDecoder != NULL) {
1622        mAudioDecoder->signalResume(false /* needNotify */);
1623    }
1624}
1625
1626void NuPlayer::finishResume() {
1627    if (mResumePending) {
1628        mResumePending = false;
1629        if (mDriver != NULL) {
1630            sp<NuPlayerDriver> driver = mDriver.promote();
1631            if (driver != NULL) {
1632                driver->notifySeekComplete();
1633            }
1634        }
1635    }
1636}
1637
1638void NuPlayer::onSourceNotify(const sp<AMessage> &msg) {
1639    int32_t what;
1640    CHECK(msg->findInt32("what", &what));
1641
1642    switch (what) {
1643        case Source::kWhatPrepared:
1644        {
1645            if (mSource == NULL) {
1646                // This is a stale notification from a source that was
1647                // asynchronously preparing when the client called reset().
1648                // We handled the reset, the source is gone.
1649                break;
1650            }
1651
1652            int32_t err;
1653            CHECK(msg->findInt32("err", &err));
1654
1655            sp<NuPlayerDriver> driver = mDriver.promote();
1656            if (driver != NULL) {
1657                // notify duration first, so that it's definitely set when
1658                // the app received the "prepare complete" callback.
1659                int64_t durationUs;
1660                if (mSource->getDuration(&durationUs) == OK) {
1661                    driver->notifyDuration(durationUs);
1662                }
1663                driver->notifyPrepareCompleted(err);
1664            }
1665
1666            break;
1667        }
1668
1669        case Source::kWhatFlagsChanged:
1670        {
1671            uint32_t flags;
1672            CHECK(msg->findInt32("flags", (int32_t *)&flags));
1673
1674            sp<NuPlayerDriver> driver = mDriver.promote();
1675            if (driver != NULL) {
1676                if ((flags & NuPlayer::Source::FLAG_CAN_SEEK) == 0) {
1677                    driver->notifyListener(
1678                            MEDIA_INFO, MEDIA_INFO_NOT_SEEKABLE, 0);
1679                }
1680                driver->notifyFlagsChanged(flags);
1681            }
1682
1683            if ((mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
1684                    && (!(flags & Source::FLAG_DYNAMIC_DURATION))) {
1685                cancelPollDuration();
1686            } else if (!(mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
1687                    && (flags & Source::FLAG_DYNAMIC_DURATION)
1688                    && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
1689                schedulePollDuration();
1690            }
1691
1692            mSourceFlags = flags;
1693            break;
1694        }
1695
1696        case Source::kWhatVideoSizeChanged:
1697        {
1698            sp<AMessage> format;
1699            CHECK(msg->findMessage("format", &format));
1700
1701            updateVideoSize(format);
1702            break;
1703        }
1704
1705        case Source::kWhatBufferingUpdate:
1706        {
1707            int32_t percentage;
1708            CHECK(msg->findInt32("percentage", &percentage));
1709
1710            notifyListener(MEDIA_BUFFERING_UPDATE, percentage, 0);
1711            break;
1712        }
1713
1714        case Source::kWhatBufferingStart:
1715        {
1716            notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_START, 0);
1717            break;
1718        }
1719
1720        case Source::kWhatBufferingEnd:
1721        {
1722            notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_END, 0);
1723            break;
1724        }
1725
1726        case Source::kWhatSubtitleData:
1727        {
1728            sp<ABuffer> buffer;
1729            CHECK(msg->findBuffer("buffer", &buffer));
1730
1731            sendSubtitleData(buffer, 0 /* baseIndex */);
1732            break;
1733        }
1734
1735        case Source::kWhatTimedTextData:
1736        {
1737            int32_t generation;
1738            if (msg->findInt32("generation", &generation)
1739                    && generation != mTimedTextGeneration) {
1740                break;
1741            }
1742
1743            sp<ABuffer> buffer;
1744            CHECK(msg->findBuffer("buffer", &buffer));
1745
1746            sp<NuPlayerDriver> driver = mDriver.promote();
1747            if (driver == NULL) {
1748                break;
1749            }
1750
1751            int posMs;
1752            int64_t timeUs, posUs;
1753            driver->getCurrentPosition(&posMs);
1754            posUs = posMs * 1000;
1755            CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
1756
1757            if (posUs < timeUs) {
1758                if (!msg->findInt32("generation", &generation)) {
1759                    msg->setInt32("generation", mTimedTextGeneration);
1760                }
1761                msg->post(timeUs - posUs);
1762            } else {
1763                sendTimedTextData(buffer);
1764            }
1765            break;
1766        }
1767
1768        case Source::kWhatQueueDecoderShutdown:
1769        {
1770            int32_t audio, video;
1771            CHECK(msg->findInt32("audio", &audio));
1772            CHECK(msg->findInt32("video", &video));
1773
1774            sp<AMessage> reply;
1775            CHECK(msg->findMessage("reply", &reply));
1776
1777            queueDecoderShutdown(audio, video, reply);
1778            break;
1779        }
1780
1781        case Source::kWhatDrmNoLicense:
1782        {
1783            notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_DRM_NO_LICENSE);
1784            break;
1785        }
1786
1787        default:
1788            TRESPASS();
1789    }
1790}
1791
1792void NuPlayer::onClosedCaptionNotify(const sp<AMessage> &msg) {
1793    int32_t what;
1794    CHECK(msg->findInt32("what", &what));
1795
1796    switch (what) {
1797        case NuPlayer::CCDecoder::kWhatClosedCaptionData:
1798        {
1799            sp<ABuffer> buffer;
1800            CHECK(msg->findBuffer("buffer", &buffer));
1801
1802            size_t inbandTracks = 0;
1803            if (mSource != NULL) {
1804                inbandTracks = mSource->getTrackCount();
1805            }
1806
1807            sendSubtitleData(buffer, inbandTracks);
1808            break;
1809        }
1810
1811        case NuPlayer::CCDecoder::kWhatTrackAdded:
1812        {
1813            notifyListener(MEDIA_INFO, MEDIA_INFO_METADATA_UPDATE, 0);
1814
1815            break;
1816        }
1817
1818        default:
1819            TRESPASS();
1820    }
1821
1822
1823}
1824
1825void NuPlayer::sendSubtitleData(const sp<ABuffer> &buffer, int32_t baseIndex) {
1826    int32_t trackIndex;
1827    int64_t timeUs, durationUs;
1828    CHECK(buffer->meta()->findInt32("trackIndex", &trackIndex));
1829    CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
1830    CHECK(buffer->meta()->findInt64("durationUs", &durationUs));
1831
1832    Parcel in;
1833    in.writeInt32(trackIndex + baseIndex);
1834    in.writeInt64(timeUs);
1835    in.writeInt64(durationUs);
1836    in.writeInt32(buffer->size());
1837    in.writeInt32(buffer->size());
1838    in.write(buffer->data(), buffer->size());
1839
1840    notifyListener(MEDIA_SUBTITLE_DATA, 0, 0, &in);
1841}
1842
1843void NuPlayer::sendTimedTextData(const sp<ABuffer> &buffer) {
1844    const void *data;
1845    size_t size = 0;
1846    int64_t timeUs;
1847    int32_t flag = TextDescriptions::LOCAL_DESCRIPTIONS;
1848
1849    AString mime;
1850    CHECK(buffer->meta()->findString("mime", &mime));
1851    CHECK(strcasecmp(mime.c_str(), MEDIA_MIMETYPE_TEXT_3GPP) == 0);
1852
1853    data = buffer->data();
1854    size = buffer->size();
1855
1856    Parcel parcel;
1857    if (size > 0) {
1858        CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
1859        flag |= TextDescriptions::IN_BAND_TEXT_3GPP;
1860        TextDescriptions::getParcelOfDescriptions(
1861                (const uint8_t *)data, size, flag, timeUs / 1000, &parcel);
1862    }
1863
1864    if ((parcel.dataSize() > 0)) {
1865        notifyListener(MEDIA_TIMED_TEXT, 0, 0, &parcel);
1866    } else {  // send an empty timed text
1867        notifyListener(MEDIA_TIMED_TEXT, 0, 0);
1868    }
1869}
1870////////////////////////////////////////////////////////////////////////////////
1871
1872sp<AMessage> NuPlayer::Source::getFormat(bool audio) {
1873    sp<MetaData> meta = getFormatMeta(audio);
1874
1875    if (meta == NULL) {
1876        return NULL;
1877    }
1878
1879    sp<AMessage> msg = new AMessage;
1880
1881    if(convertMetaDataToMessage(meta, &msg) == OK) {
1882        return msg;
1883    }
1884    return NULL;
1885}
1886
1887void NuPlayer::Source::notifyFlagsChanged(uint32_t flags) {
1888    sp<AMessage> notify = dupNotify();
1889    notify->setInt32("what", kWhatFlagsChanged);
1890    notify->setInt32("flags", flags);
1891    notify->post();
1892}
1893
1894void NuPlayer::Source::notifyVideoSizeChanged(const sp<AMessage> &format) {
1895    sp<AMessage> notify = dupNotify();
1896    notify->setInt32("what", kWhatVideoSizeChanged);
1897    notify->setMessage("format", format);
1898    notify->post();
1899}
1900
1901void NuPlayer::Source::notifyPrepared(status_t err) {
1902    sp<AMessage> notify = dupNotify();
1903    notify->setInt32("what", kWhatPrepared);
1904    notify->setInt32("err", err);
1905    notify->post();
1906}
1907
1908void NuPlayer::Source::onMessageReceived(const sp<AMessage> & /* msg */) {
1909    TRESPASS();
1910}
1911
1912}  // namespace android
1913