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