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