NuPlayer.cpp revision fbbeeeb87c55c3eca94a709f9f8986190f6472a1
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            postScanSources();
647            break;
648        }
649
650        case kWhatScanSources:
651        {
652            int32_t generation;
653            CHECK(msg->findInt32("generation", &generation));
654            if (generation != mScanSourcesGeneration) {
655                // Drop obsolete msg.
656                break;
657            }
658
659            mScanSourcesPending = false;
660
661            ALOGV("scanning sources haveAudio=%d, haveVideo=%d",
662                 mAudioDecoder != NULL, mVideoDecoder != NULL);
663
664            bool mHadAnySourcesBefore =
665                (mAudioDecoder != NULL) || (mVideoDecoder != NULL);
666
667            // initialize video before audio because successful initialization of
668            // video may change deep buffer mode of audio.
669            if (mNativeWindow != NULL) {
670                instantiateDecoder(false, &mVideoDecoder);
671            }
672
673            if (mAudioSink != NULL) {
674                if (mOffloadAudio) {
675                    // open audio sink early under offload mode.
676                    sp<AMessage> format = mSource->getFormat(true /*audio*/);
677                    openAudioSink(format, true /*offloadOnly*/);
678                }
679                instantiateDecoder(true, &mAudioDecoder);
680            }
681
682            if (!mHadAnySourcesBefore
683                    && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
684                // This is the first time we've found anything playable.
685
686                if (mSourceFlags & Source::FLAG_DYNAMIC_DURATION) {
687                    schedulePollDuration();
688                }
689            }
690
691            status_t err;
692            if ((err = mSource->feedMoreTSData()) != OK) {
693                if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
694                    // We're not currently decoding anything (no audio or
695                    // video tracks found) and we just ran out of input data.
696
697                    if (err == ERROR_END_OF_STREAM) {
698                        notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
699                    } else {
700                        notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
701                    }
702                }
703                break;
704            }
705
706            if ((mAudioDecoder == NULL && mAudioSink != NULL)
707                    || (mVideoDecoder == NULL && mNativeWindow != NULL)) {
708                msg->post(100000ll);
709                mScanSourcesPending = true;
710            }
711            break;
712        }
713
714        case kWhatVideoNotify:
715        case kWhatAudioNotify:
716        {
717            bool audio = msg->what() == kWhatAudioNotify;
718
719            int32_t currentDecoderGeneration =
720                (audio? mAudioDecoderGeneration : mVideoDecoderGeneration);
721            int32_t requesterGeneration = currentDecoderGeneration - 1;
722            CHECK(msg->findInt32("generation", &requesterGeneration));
723
724            if (requesterGeneration != currentDecoderGeneration) {
725                ALOGV("got message from old %s decoder, generation(%d:%d)",
726                        audio ? "audio" : "video", requesterGeneration,
727                        currentDecoderGeneration);
728                sp<AMessage> reply;
729                if (!(msg->findMessage("reply", &reply))) {
730                    return;
731                }
732
733                reply->setInt32("err", INFO_DISCONTINUITY);
734                reply->post();
735                return;
736            }
737
738            int32_t what;
739            CHECK(msg->findInt32("what", &what));
740
741            if (what == Decoder::kWhatFillThisBuffer) {
742                status_t err = feedDecoderInputData(
743                        audio, msg);
744
745                if (err == -EWOULDBLOCK) {
746                    if (mSource->feedMoreTSData() == OK) {
747                        msg->post(10 * 1000ll);
748                    }
749                }
750            } else if (what == Decoder::kWhatEOS) {
751                int32_t err;
752                CHECK(msg->findInt32("err", &err));
753
754                if (err == ERROR_END_OF_STREAM) {
755                    ALOGV("got %s decoder EOS", audio ? "audio" : "video");
756                } else {
757                    ALOGV("got %s decoder EOS w/ error %d",
758                         audio ? "audio" : "video",
759                         err);
760                }
761
762                mRenderer->queueEOS(audio, err);
763            } else if (what == Decoder::kWhatFlushCompleted) {
764                bool needShutdown;
765
766                if (audio) {
767                    CHECK(IsFlushingState(mFlushingAudio, &needShutdown));
768                    mFlushingAudio = FLUSHED;
769                } else {
770                    CHECK(IsFlushingState(mFlushingVideo, &needShutdown));
771                    mFlushingVideo = FLUSHED;
772
773                    mVideoLateByUs = 0;
774                }
775
776                ALOGV("decoder %s flush completed", audio ? "audio" : "video");
777
778                if (needShutdown) {
779                    ALOGV("initiating %s decoder shutdown",
780                         audio ? "audio" : "video");
781
782                    getDecoder(audio)->initiateShutdown();
783
784                    if (audio) {
785                        mFlushingAudio = SHUTTING_DOWN_DECODER;
786                    } else {
787                        mFlushingVideo = SHUTTING_DOWN_DECODER;
788                    }
789                }
790
791                finishFlushIfPossible();
792            } else if (what == Decoder::kWhatOutputFormatChanged) {
793                sp<AMessage> format;
794                CHECK(msg->findMessage("format", &format));
795
796                if (audio) {
797                    openAudioSink(format, false /*offloadOnly*/);
798                } else {
799                    // video
800                    sp<AMessage> inputFormat =
801                            mSource->getFormat(false /* audio */);
802
803                    updateVideoSize(inputFormat, format);
804                }
805            } else if (what == Decoder::kWhatShutdownCompleted) {
806                ALOGV("%s shutdown completed", audio ? "audio" : "video");
807                if (audio) {
808                    mAudioDecoder.clear();
809
810                    CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER);
811                    mFlushingAudio = SHUT_DOWN;
812                } else {
813                    mVideoDecoder.clear();
814
815                    CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER);
816                    mFlushingVideo = SHUT_DOWN;
817                }
818
819                finishFlushIfPossible();
820            } else if (what == Decoder::kWhatError) {
821                ALOGE("Received error from %s decoder, aborting playback.",
822                     audio ? "audio" : "video");
823
824                status_t err;
825                if (!msg->findInt32("err", &err)) {
826                    err = UNKNOWN_ERROR;
827                }
828                mRenderer->queueEOS(audio, err);
829                if (audio && mFlushingAudio != NONE) {
830                    mAudioDecoder.clear();
831                    mFlushingAudio = SHUT_DOWN;
832                } else if (!audio && mFlushingVideo != NONE){
833                    mVideoDecoder.clear();
834                    mFlushingVideo = SHUT_DOWN;
835                }
836                finishFlushIfPossible();
837            } else if (what == Decoder::kWhatDrainThisBuffer) {
838                renderBuffer(audio, msg);
839            } else {
840                ALOGV("Unhandled decoder notification %d '%c%c%c%c'.",
841                      what,
842                      what >> 24,
843                      (what >> 16) & 0xff,
844                      (what >> 8) & 0xff,
845                      what & 0xff);
846            }
847
848            break;
849        }
850
851        case kWhatRendererNotify:
852        {
853            int32_t what;
854            CHECK(msg->findInt32("what", &what));
855
856            if (what == Renderer::kWhatEOS) {
857                int32_t audio;
858                CHECK(msg->findInt32("audio", &audio));
859
860                int32_t finalResult;
861                CHECK(msg->findInt32("finalResult", &finalResult));
862
863                if (audio) {
864                    mAudioEOS = true;
865                } else {
866                    mVideoEOS = true;
867                }
868
869                if (finalResult == ERROR_END_OF_STREAM) {
870                    ALOGV("reached %s EOS", audio ? "audio" : "video");
871                } else {
872                    ALOGE("%s track encountered an error (%d)",
873                         audio ? "audio" : "video", finalResult);
874
875                    notifyListener(
876                            MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, finalResult);
877                }
878
879                if ((mAudioEOS || mAudioDecoder == NULL)
880                        && (mVideoEOS || mVideoDecoder == NULL)) {
881                    notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
882                }
883            } else if (what == Renderer::kWhatPosition) {
884                int64_t positionUs;
885                CHECK(msg->findInt64("positionUs", &positionUs));
886                mCurrentPositionUs = positionUs;
887
888                CHECK(msg->findInt64("videoLateByUs", &mVideoLateByUs));
889
890                if (mDriver != NULL) {
891                    sp<NuPlayerDriver> driver = mDriver.promote();
892                    if (driver != NULL) {
893                        driver->notifyPosition(positionUs);
894
895                        driver->notifyFrameStats(
896                                mNumFramesTotal, mNumFramesDropped);
897                    }
898                }
899            } else if (what == Renderer::kWhatFlushComplete) {
900                int32_t audio;
901                CHECK(msg->findInt32("audio", &audio));
902
903                ALOGV("renderer %s flush completed.", audio ? "audio" : "video");
904            } else if (what == Renderer::kWhatVideoRenderingStart) {
905                notifyListener(MEDIA_INFO, MEDIA_INFO_RENDERING_START, 0);
906            } else if (what == Renderer::kWhatMediaRenderingStart) {
907                ALOGV("media rendering started");
908                notifyListener(MEDIA_STARTED, 0, 0);
909            } else if (what == Renderer::kWhatAudioOffloadTearDown) {
910                ALOGV("Tear down audio offload, fall back to s/w path");
911                int64_t positionUs;
912                CHECK(msg->findInt64("positionUs", &positionUs));
913                closeAudioSink();
914                mAudioDecoder.clear();
915                mRenderer->flush(true /* audio */);
916                if (mVideoDecoder != NULL) {
917                    mRenderer->flush(false /* audio */);
918                }
919                mRenderer->signalDisableOffloadAudio();
920                mOffloadAudio = false;
921
922                performSeek(positionUs);
923                instantiateDecoder(true /* audio */, &mAudioDecoder);
924            }
925            break;
926        }
927
928        case kWhatMoreDataQueued:
929        {
930            break;
931        }
932
933        case kWhatReset:
934        {
935            ALOGV("kWhatReset");
936
937            mDeferredActions.push_back(
938                    new ShutdownDecoderAction(
939                        true /* audio */, true /* video */));
940
941            mDeferredActions.push_back(
942                    new SimpleAction(&NuPlayer::performReset));
943
944            processDeferredActions();
945            break;
946        }
947
948        case kWhatSeek:
949        {
950            int64_t seekTimeUs;
951            CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
952
953            ALOGV("kWhatSeek seekTimeUs=%lld us", seekTimeUs);
954
955            mDeferredActions.push_back(
956                    new SimpleAction(&NuPlayer::performDecoderFlush));
957
958            mDeferredActions.push_back(new SeekAction(seekTimeUs));
959
960            processDeferredActions();
961            break;
962        }
963
964        case kWhatPause:
965        {
966            CHECK(mRenderer != NULL);
967            mSource->pause();
968            mRenderer->pause();
969            break;
970        }
971
972        case kWhatResume:
973        {
974            CHECK(mRenderer != NULL);
975            mSource->resume();
976            mRenderer->resume();
977            break;
978        }
979
980        case kWhatSourceNotify:
981        {
982            onSourceNotify(msg);
983            break;
984        }
985
986        case kWhatClosedCaptionNotify:
987        {
988            onClosedCaptionNotify(msg);
989            break;
990        }
991
992        default:
993            TRESPASS();
994            break;
995    }
996}
997
998void NuPlayer::finishFlushIfPossible() {
999    if (mFlushingAudio != NONE && mFlushingAudio != FLUSHED
1000            && mFlushingAudio != SHUT_DOWN) {
1001        return;
1002    }
1003
1004    if (mFlushingVideo != NONE && mFlushingVideo != FLUSHED
1005            && mFlushingVideo != SHUT_DOWN) {
1006        return;
1007    }
1008
1009    ALOGV("both audio and video are flushed now.");
1010
1011    mPendingAudioAccessUnit.clear();
1012    mAggregateBuffer.clear();
1013
1014    if (mTimeDiscontinuityPending) {
1015        mRenderer->signalTimeDiscontinuity();
1016        mTimeDiscontinuityPending = false;
1017    }
1018
1019    if (mAudioDecoder != NULL && mFlushingAudio == FLUSHED) {
1020        mAudioDecoder->signalResume();
1021    }
1022
1023    if (mVideoDecoder != NULL && mFlushingVideo == FLUSHED) {
1024        mVideoDecoder->signalResume();
1025    }
1026
1027    mFlushingAudio = NONE;
1028    mFlushingVideo = NONE;
1029
1030    processDeferredActions();
1031}
1032
1033void NuPlayer::postScanSources() {
1034    if (mScanSourcesPending) {
1035        return;
1036    }
1037
1038    sp<AMessage> msg = new AMessage(kWhatScanSources, id());
1039    msg->setInt32("generation", mScanSourcesGeneration);
1040    msg->post();
1041
1042    mScanSourcesPending = true;
1043}
1044
1045void NuPlayer::openAudioSink(const sp<AMessage> &format, bool offloadOnly) {
1046    ALOGV("openAudioSink: offloadOnly(%d) mOffloadAudio(%d)",
1047            offloadOnly, mOffloadAudio);
1048    bool audioSinkChanged = false;
1049
1050    int32_t numChannels;
1051    CHECK(format->findInt32("channel-count", &numChannels));
1052
1053    int32_t channelMask;
1054    if (!format->findInt32("channel-mask", &channelMask)) {
1055        // signal to the AudioSink to derive the mask from count.
1056        channelMask = CHANNEL_MASK_USE_CHANNEL_ORDER;
1057    }
1058
1059    int32_t sampleRate;
1060    CHECK(format->findInt32("sample-rate", &sampleRate));
1061
1062    uint32_t flags;
1063    int64_t durationUs;
1064    // FIXME: we should handle the case where the video decoder
1065    // is created after we receive the format change indication.
1066    // Current code will just make that we select deep buffer
1067    // with video which should not be a problem as it should
1068    // not prevent from keeping A/V sync.
1069    if (mVideoDecoder == NULL &&
1070            mSource->getDuration(&durationUs) == OK &&
1071            durationUs
1072                > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US) {
1073        flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1074    } else {
1075        flags = AUDIO_OUTPUT_FLAG_NONE;
1076    }
1077
1078    if (mOffloadAudio) {
1079        audio_format_t audioFormat = AUDIO_FORMAT_PCM_16_BIT;
1080        AString mime;
1081        CHECK(format->findString("mime", &mime));
1082        status_t err = mapMimeToAudioFormat(audioFormat, mime.c_str());
1083
1084        if (err != OK) {
1085            ALOGE("Couldn't map mime \"%s\" to a valid "
1086                    "audio_format", mime.c_str());
1087            mOffloadAudio = false;
1088        } else {
1089            ALOGV("Mime \"%s\" mapped to audio_format 0x%x",
1090                    mime.c_str(), audioFormat);
1091
1092            int avgBitRate = -1;
1093            format->findInt32("bit-rate", &avgBitRate);
1094
1095            int32_t aacProfile = -1;
1096            if (audioFormat == AUDIO_FORMAT_AAC
1097                    && format->findInt32("aac-profile", &aacProfile)) {
1098                // Redefine AAC format as per aac profile
1099                mapAACProfileToAudioFormat(
1100                        audioFormat,
1101                        aacProfile);
1102            }
1103
1104            audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
1105            offloadInfo.duration_us = -1;
1106            format->findInt64(
1107                    "durationUs", &offloadInfo.duration_us);
1108            offloadInfo.sample_rate = sampleRate;
1109            offloadInfo.channel_mask = channelMask;
1110            offloadInfo.format = audioFormat;
1111            offloadInfo.stream_type = AUDIO_STREAM_MUSIC;
1112            offloadInfo.bit_rate = avgBitRate;
1113            offloadInfo.has_video = (mVideoDecoder != NULL);
1114            offloadInfo.is_streaming = true;
1115
1116            if (memcmp(&mCurrentOffloadInfo, &offloadInfo, sizeof(offloadInfo)) == 0) {
1117                ALOGV("openAudioSink: no change in offload mode");
1118                return;  // no change from previous configuration, everything ok.
1119            }
1120            ALOGV("openAudioSink: try to open AudioSink in offload mode");
1121            flags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
1122            flags &= ~AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1123            audioSinkChanged = true;
1124            mAudioSink->close();
1125            err = mAudioSink->open(
1126                    sampleRate,
1127                    numChannels,
1128                    (audio_channel_mask_t)channelMask,
1129                    audioFormat,
1130                    8 /* bufferCount */,
1131                    &NuPlayer::Renderer::AudioSinkCallback,
1132                    mRenderer.get(),
1133                    (audio_output_flags_t)flags,
1134                    &offloadInfo);
1135
1136            if (err == OK) {
1137                // If the playback is offloaded to h/w, we pass
1138                // the HAL some metadata information.
1139                // We don't want to do this for PCM because it
1140                // will be going through the AudioFlinger mixer
1141                // before reaching the hardware.
1142                sp<MetaData> audioMeta =
1143                        mSource->getFormatMeta(true /* audio */);
1144                sendMetaDataToHal(mAudioSink, audioMeta);
1145                mCurrentOffloadInfo = offloadInfo;
1146                err = mAudioSink->start();
1147                ALOGV_IF(err == OK, "openAudioSink: offload succeeded");
1148            }
1149            if (err != OK) {
1150                // Clean up, fall back to non offload mode.
1151                mAudioSink->close();
1152                mRenderer->signalDisableOffloadAudio();
1153                mOffloadAudio = false;
1154                mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER;
1155                ALOGV("openAudioSink: offload failed");
1156            }
1157        }
1158    }
1159    if (!offloadOnly && !mOffloadAudio) {
1160        flags &= ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
1161        ALOGV("openAudioSink: open AudioSink in NON-offload mode");
1162
1163        audioSinkChanged = true;
1164        mAudioSink->close();
1165        mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER;
1166        CHECK_EQ(mAudioSink->open(
1167                    sampleRate,
1168                    numChannels,
1169                    (audio_channel_mask_t)channelMask,
1170                    AUDIO_FORMAT_PCM_16_BIT,
1171                    8 /* bufferCount */,
1172                    NULL,
1173                    NULL,
1174                    (audio_output_flags_t)flags),
1175                 (status_t)OK);
1176        mAudioSink->start();
1177    }
1178    if (audioSinkChanged) {
1179        mRenderer->signalAudioSinkChanged();
1180    }
1181}
1182
1183void NuPlayer::closeAudioSink() {
1184    mAudioSink->close();
1185    mCurrentOffloadInfo = AUDIO_INFO_INITIALIZER;
1186}
1187
1188status_t NuPlayer::instantiateDecoder(bool audio, sp<Decoder> *decoder) {
1189    if (*decoder != NULL) {
1190        return OK;
1191    }
1192
1193    sp<AMessage> format = mSource->getFormat(audio);
1194
1195    if (format == NULL) {
1196        return -EWOULDBLOCK;
1197    }
1198
1199    if (!audio) {
1200        AString mime;
1201        CHECK(format->findString("mime", &mime));
1202        mVideoIsAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
1203
1204        sp<AMessage> ccNotify = new AMessage(kWhatClosedCaptionNotify, id());
1205        mCCDecoder = new CCDecoder(ccNotify);
1206
1207        if (mSourceFlags & Source::FLAG_SECURE) {
1208            format->setInt32("secure", true);
1209        }
1210    }
1211
1212    if (audio) {
1213        sp<AMessage> notify = new AMessage(kWhatAudioNotify, id());
1214        ++mAudioDecoderGeneration;
1215        notify->setInt32("generation", mAudioDecoderGeneration);
1216
1217        if (mOffloadAudio) {
1218            *decoder = new DecoderPassThrough(notify);
1219        } else {
1220            *decoder = new Decoder(notify);
1221        }
1222    } else {
1223        sp<AMessage> notify = new AMessage(kWhatVideoNotify, id());
1224        ++mVideoDecoderGeneration;
1225        notify->setInt32("generation", mVideoDecoderGeneration);
1226
1227        *decoder = new Decoder(notify, mNativeWindow);
1228    }
1229    (*decoder)->init();
1230    (*decoder)->configure(format);
1231
1232    // allocate buffers to decrypt widevine source buffers
1233    if (!audio && (mSourceFlags & Source::FLAG_SECURE)) {
1234        Vector<sp<ABuffer> > inputBufs;
1235        CHECK_EQ((*decoder)->getInputBuffers(&inputBufs), (status_t)OK);
1236
1237        Vector<MediaBuffer *> mediaBufs;
1238        for (size_t i = 0; i < inputBufs.size(); i++) {
1239            const sp<ABuffer> &buffer = inputBufs[i];
1240            MediaBuffer *mbuf = new MediaBuffer(buffer->data(), buffer->size());
1241            mediaBufs.push(mbuf);
1242        }
1243
1244        status_t err = mSource->setBuffers(audio, mediaBufs);
1245        if (err != OK) {
1246            for (size_t i = 0; i < mediaBufs.size(); ++i) {
1247                mediaBufs[i]->release();
1248            }
1249            mediaBufs.clear();
1250            ALOGE("Secure source didn't support secure mediaBufs.");
1251            return err;
1252        }
1253    }
1254    return OK;
1255}
1256
1257status_t NuPlayer::feedDecoderInputData(bool audio, const sp<AMessage> &msg) {
1258    sp<AMessage> reply;
1259    CHECK(msg->findMessage("reply", &reply));
1260
1261    if ((audio && mFlushingAudio != NONE)
1262            || (!audio && mFlushingVideo != NONE)
1263            || mSource == NULL) {
1264        reply->setInt32("err", INFO_DISCONTINUITY);
1265        reply->post();
1266        return OK;
1267    }
1268
1269    sp<ABuffer> accessUnit;
1270
1271    // Aggregate smaller buffers into a larger buffer.
1272    // The goal is to reduce power consumption.
1273    // Unfortunately this does not work with the software AAC decoder.
1274    bool doBufferAggregation = (audio && mOffloadAudio);;
1275    bool needMoreData = false;
1276
1277    bool dropAccessUnit;
1278    do {
1279        status_t err;
1280        // Did we save an accessUnit earlier because of a discontinuity?
1281        if (audio && (mPendingAudioAccessUnit != NULL)) {
1282            accessUnit = mPendingAudioAccessUnit;
1283            mPendingAudioAccessUnit.clear();
1284            err = mPendingAudioErr;
1285            ALOGV("feedDecoderInputData() use mPendingAudioAccessUnit");
1286        } else {
1287            err = mSource->dequeueAccessUnit(audio, &accessUnit);
1288        }
1289
1290        if (err == -EWOULDBLOCK) {
1291            return err;
1292        } else if (err != OK) {
1293            if (err == INFO_DISCONTINUITY) {
1294                if (mAggregateBuffer != NULL) {
1295                    // We already have some data so save this for later.
1296                    mPendingAudioErr = err;
1297                    mPendingAudioAccessUnit = accessUnit;
1298                    accessUnit.clear();
1299                    ALOGD("feedDecoderInputData() save discontinuity for later");
1300                    break;
1301                }
1302                int32_t type;
1303                CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
1304
1305                bool formatChange =
1306                    (audio &&
1307                     (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
1308                    || (!audio &&
1309                            (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
1310
1311                bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
1312
1313                ALOGI("%s discontinuity (formatChange=%d, time=%d)",
1314                     audio ? "audio" : "video", formatChange, timeChange);
1315
1316                if (audio) {
1317                    mSkipRenderingAudioUntilMediaTimeUs = -1;
1318                } else {
1319                    mSkipRenderingVideoUntilMediaTimeUs = -1;
1320                }
1321
1322                if (timeChange) {
1323                    sp<AMessage> extra;
1324                    if (accessUnit->meta()->findMessage("extra", &extra)
1325                            && extra != NULL) {
1326                        int64_t resumeAtMediaTimeUs;
1327                        if (extra->findInt64(
1328                                    "resume-at-mediatimeUs", &resumeAtMediaTimeUs)) {
1329                            ALOGI("suppressing rendering of %s until %lld us",
1330                                    audio ? "audio" : "video", resumeAtMediaTimeUs);
1331
1332                            if (audio) {
1333                                mSkipRenderingAudioUntilMediaTimeUs =
1334                                    resumeAtMediaTimeUs;
1335                            } else {
1336                                mSkipRenderingVideoUntilMediaTimeUs =
1337                                    resumeAtMediaTimeUs;
1338                            }
1339                        }
1340                    }
1341                }
1342
1343                mTimeDiscontinuityPending =
1344                    mTimeDiscontinuityPending || timeChange;
1345
1346                bool seamlessFormatChange = false;
1347                sp<AMessage> newFormat = mSource->getFormat(audio);
1348                if (formatChange) {
1349                    seamlessFormatChange =
1350                        getDecoder(audio)->supportsSeamlessFormatChange(newFormat);
1351                    // treat seamless format change separately
1352                    formatChange = !seamlessFormatChange;
1353                }
1354                bool shutdownOrFlush = formatChange || timeChange;
1355
1356                // We want to queue up scan-sources only once per discontinuity.
1357                // We control this by doing it only if neither audio nor video are
1358                // flushing or shutting down.  (After handling 1st discontinuity, one
1359                // of the flushing states will not be NONE.)
1360                // No need to scan sources if this discontinuity does not result
1361                // in a flush or shutdown, as the flushing state will stay NONE.
1362                if (mFlushingAudio == NONE && mFlushingVideo == NONE &&
1363                        shutdownOrFlush) {
1364                    // And we'll resume scanning sources once we're done
1365                    // flushing.
1366                    mDeferredActions.push_front(
1367                            new SimpleAction(
1368                                &NuPlayer::performScanSources));
1369                }
1370
1371                if (formatChange /* not seamless */) {
1372                    // must change decoder
1373                    flushDecoder(audio, /* needShutdown = */ true);
1374                } else if (timeChange) {
1375                    // need to flush
1376                    flushDecoder(audio, /* needShutdown = */ false, newFormat);
1377                    err = OK;
1378                } else if (seamlessFormatChange) {
1379                    // reuse existing decoder and don't flush
1380                    updateDecoderFormatWithoutFlush(audio, newFormat);
1381                    err = OK;
1382                } else {
1383                    // This stream is unaffected by the discontinuity
1384                    return -EWOULDBLOCK;
1385                }
1386            }
1387
1388            reply->setInt32("err", err);
1389            reply->post();
1390            return OK;
1391        }
1392
1393        if (!audio) {
1394            ++mNumFramesTotal;
1395        }
1396
1397        dropAccessUnit = false;
1398        if (!audio
1399                && !(mSourceFlags & Source::FLAG_SECURE)
1400                && mVideoLateByUs > 100000ll
1401                && mVideoIsAVC
1402                && !IsAVCReferenceFrame(accessUnit)) {
1403            dropAccessUnit = true;
1404            ++mNumFramesDropped;
1405        }
1406
1407        size_t smallSize = accessUnit->size();
1408        needMoreData = false;
1409        if (doBufferAggregation && (mAggregateBuffer == NULL)
1410                // Don't bother if only room for a few small buffers.
1411                && (smallSize < (kAggregateBufferSizeBytes / 3))) {
1412            // Create a larger buffer for combining smaller buffers from the extractor.
1413            mAggregateBuffer = new ABuffer(kAggregateBufferSizeBytes);
1414            mAggregateBuffer->setRange(0, 0); // start empty
1415        }
1416
1417        if (mAggregateBuffer != NULL) {
1418            int64_t timeUs;
1419            int64_t dummy;
1420            bool smallTimestampValid = accessUnit->meta()->findInt64("timeUs", &timeUs);
1421            bool bigTimestampValid = mAggregateBuffer->meta()->findInt64("timeUs", &dummy);
1422            // Will the smaller buffer fit?
1423            size_t bigSize = mAggregateBuffer->size();
1424            size_t roomLeft = mAggregateBuffer->capacity() - bigSize;
1425            // Should we save this small buffer for the next big buffer?
1426            // If the first small buffer did not have a timestamp then save
1427            // any buffer that does have a timestamp until the next big buffer.
1428            if ((smallSize > roomLeft)
1429                || (!bigTimestampValid && (bigSize > 0) && smallTimestampValid)) {
1430                mPendingAudioErr = err;
1431                mPendingAudioAccessUnit = accessUnit;
1432                accessUnit.clear();
1433            } else {
1434                // Grab time from first small buffer if available.
1435                if ((bigSize == 0) && smallTimestampValid) {
1436                    mAggregateBuffer->meta()->setInt64("timeUs", timeUs);
1437                }
1438                // Append small buffer to the bigger buffer.
1439                memcpy(mAggregateBuffer->base() + bigSize, accessUnit->data(), smallSize);
1440                bigSize += smallSize;
1441                mAggregateBuffer->setRange(0, bigSize);
1442
1443                // Keep looping until we run out of room in the mAggregateBuffer.
1444                needMoreData = true;
1445
1446                ALOGV("feedDecoderInputData() smallSize = %zu, bigSize = %zu, capacity = %zu",
1447                        smallSize, bigSize, mAggregateBuffer->capacity());
1448            }
1449        }
1450    } while (dropAccessUnit || needMoreData);
1451
1452    // ALOGV("returned a valid buffer of %s data", audio ? "audio" : "video");
1453
1454#if 0
1455    int64_t mediaTimeUs;
1456    CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
1457    ALOGV("feeding %s input buffer at media time %.2f secs",
1458         audio ? "audio" : "video",
1459         mediaTimeUs / 1E6);
1460#endif
1461
1462    if (!audio) {
1463        mCCDecoder->decode(accessUnit);
1464    }
1465
1466    if (mAggregateBuffer != NULL) {
1467        ALOGV("feedDecoderInputData() reply with aggregated buffer, %zu",
1468                mAggregateBuffer->size());
1469        reply->setBuffer("buffer", mAggregateBuffer);
1470        mAggregateBuffer.clear();
1471    } else {
1472        reply->setBuffer("buffer", accessUnit);
1473    }
1474
1475    reply->post();
1476
1477    return OK;
1478}
1479
1480void NuPlayer::renderBuffer(bool audio, const sp<AMessage> &msg) {
1481    // ALOGV("renderBuffer %s", audio ? "audio" : "video");
1482
1483    sp<AMessage> reply;
1484    CHECK(msg->findMessage("reply", &reply));
1485
1486    if ((audio && mFlushingAudio != NONE)
1487            || (!audio && mFlushingVideo != NONE)) {
1488        // We're currently attempting to flush the decoder, in order
1489        // to complete this, the decoder wants all its buffers back,
1490        // so we don't want any output buffers it sent us (from before
1491        // we initiated the flush) to be stuck in the renderer's queue.
1492
1493        ALOGV("we're still flushing the %s decoder, sending its output buffer"
1494             " right back.", audio ? "audio" : "video");
1495
1496        reply->post();
1497        return;
1498    }
1499
1500    sp<ABuffer> buffer;
1501    CHECK(msg->findBuffer("buffer", &buffer));
1502
1503    int64_t mediaTimeUs;
1504    CHECK(buffer->meta()->findInt64("timeUs", &mediaTimeUs));
1505
1506    int64_t &skipUntilMediaTimeUs =
1507        audio
1508            ? mSkipRenderingAudioUntilMediaTimeUs
1509            : mSkipRenderingVideoUntilMediaTimeUs;
1510
1511    if (skipUntilMediaTimeUs >= 0) {
1512
1513        if (mediaTimeUs < skipUntilMediaTimeUs) {
1514            ALOGV("dropping %s buffer at time %lld as requested.",
1515                 audio ? "audio" : "video",
1516                 mediaTimeUs);
1517
1518            reply->post();
1519            return;
1520        }
1521
1522        skipUntilMediaTimeUs = -1;
1523    }
1524
1525    if (!audio && mCCDecoder->isSelected()) {
1526        mCCDecoder->display(mediaTimeUs);
1527    }
1528
1529    mRenderer->queueBuffer(audio, buffer, reply);
1530}
1531
1532void NuPlayer::updateVideoSize(
1533        const sp<AMessage> &inputFormat,
1534        const sp<AMessage> &outputFormat) {
1535    if (inputFormat == NULL) {
1536        ALOGW("Unknown video size, reporting 0x0!");
1537        notifyListener(MEDIA_SET_VIDEO_SIZE, 0, 0);
1538        return;
1539    }
1540
1541    int32_t displayWidth, displayHeight;
1542    int32_t cropLeft, cropTop, cropRight, cropBottom;
1543
1544    if (outputFormat != NULL) {
1545        int32_t width, height;
1546        CHECK(outputFormat->findInt32("width", &width));
1547        CHECK(outputFormat->findInt32("height", &height));
1548
1549        int32_t cropLeft, cropTop, cropRight, cropBottom;
1550        CHECK(outputFormat->findRect(
1551                    "crop",
1552                    &cropLeft, &cropTop, &cropRight, &cropBottom));
1553
1554        displayWidth = cropRight - cropLeft + 1;
1555        displayHeight = cropBottom - cropTop + 1;
1556
1557        ALOGV("Video output format changed to %d x %d "
1558             "(crop: %d x %d @ (%d, %d))",
1559             width, height,
1560             displayWidth,
1561             displayHeight,
1562             cropLeft, cropTop);
1563    } else {
1564        CHECK(inputFormat->findInt32("width", &displayWidth));
1565        CHECK(inputFormat->findInt32("height", &displayHeight));
1566
1567        ALOGV("Video input format %d x %d", displayWidth, displayHeight);
1568    }
1569
1570    // Take into account sample aspect ratio if necessary:
1571    int32_t sarWidth, sarHeight;
1572    if (inputFormat->findInt32("sar-width", &sarWidth)
1573            && inputFormat->findInt32("sar-height", &sarHeight)) {
1574        ALOGV("Sample aspect ratio %d : %d", sarWidth, sarHeight);
1575
1576        displayWidth = (displayWidth * sarWidth) / sarHeight;
1577
1578        ALOGV("display dimensions %d x %d", displayWidth, displayHeight);
1579    }
1580
1581    int32_t rotationDegrees;
1582    if (!inputFormat->findInt32("rotation-degrees", &rotationDegrees)) {
1583        rotationDegrees = 0;
1584    }
1585
1586    if (rotationDegrees == 90 || rotationDegrees == 270) {
1587        int32_t tmp = displayWidth;
1588        displayWidth = displayHeight;
1589        displayHeight = tmp;
1590    }
1591
1592    notifyListener(
1593            MEDIA_SET_VIDEO_SIZE,
1594            displayWidth,
1595            displayHeight);
1596}
1597
1598void NuPlayer::notifyListener(int msg, int ext1, int ext2, const Parcel *in) {
1599    if (mDriver == NULL) {
1600        return;
1601    }
1602
1603    sp<NuPlayerDriver> driver = mDriver.promote();
1604
1605    if (driver == NULL) {
1606        return;
1607    }
1608
1609    driver->notifyListener(msg, ext1, ext2, in);
1610}
1611
1612void NuPlayer::flushDecoder(
1613        bool audio, bool needShutdown, const sp<AMessage> &newFormat) {
1614    ALOGV("[%s] flushDecoder needShutdown=%d",
1615          audio ? "audio" : "video", needShutdown);
1616
1617    const sp<Decoder> &decoder = getDecoder(audio);
1618    if (decoder == NULL) {
1619        ALOGI("flushDecoder %s without decoder present",
1620             audio ? "audio" : "video");
1621        return;
1622    }
1623
1624    // Make sure we don't continue to scan sources until we finish flushing.
1625    ++mScanSourcesGeneration;
1626    mScanSourcesPending = false;
1627
1628    decoder->signalFlush(newFormat);
1629    mRenderer->flush(audio);
1630
1631    FlushStatus newStatus =
1632        needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;
1633
1634    if (audio) {
1635        ALOGE_IF(mFlushingAudio != NONE,
1636                "audio flushDecoder() is called in state %d", mFlushingAudio);
1637        mFlushingAudio = newStatus;
1638    } else {
1639        ALOGE_IF(mFlushingVideo != NONE,
1640                "video flushDecoder() is called in state %d", mFlushingVideo);
1641        mFlushingVideo = newStatus;
1642
1643        if (mCCDecoder != NULL) {
1644            mCCDecoder->flush();
1645        }
1646    }
1647}
1648
1649void NuPlayer::updateDecoderFormatWithoutFlush(
1650        bool audio, const sp<AMessage> &format) {
1651    ALOGV("[%s] updateDecoderFormatWithoutFlush", audio ? "audio" : "video");
1652
1653    const sp<Decoder> &decoder = getDecoder(audio);
1654    if (decoder == NULL) {
1655        ALOGI("updateDecoderFormatWithoutFlush %s without decoder present",
1656             audio ? "audio" : "video");
1657        return;
1658    }
1659
1660    decoder->signalUpdateFormat(format);
1661}
1662
1663void NuPlayer::queueDecoderShutdown(
1664        bool audio, bool video, const sp<AMessage> &reply) {
1665    ALOGI("queueDecoderShutdown audio=%d, video=%d", audio, video);
1666
1667    mDeferredActions.push_back(
1668            new ShutdownDecoderAction(audio, video));
1669
1670    mDeferredActions.push_back(
1671            new SimpleAction(&NuPlayer::performScanSources));
1672
1673    mDeferredActions.push_back(new PostMessageAction(reply));
1674
1675    processDeferredActions();
1676}
1677
1678status_t NuPlayer::setVideoScalingMode(int32_t mode) {
1679    mVideoScalingMode = mode;
1680    if (mNativeWindow != NULL) {
1681        status_t ret = native_window_set_scaling_mode(
1682                mNativeWindow->getNativeWindow().get(), mVideoScalingMode);
1683        if (ret != OK) {
1684            ALOGE("Failed to set scaling mode (%d): %s",
1685                -ret, strerror(-ret));
1686            return ret;
1687        }
1688    }
1689    return OK;
1690}
1691
1692status_t NuPlayer::getTrackInfo(Parcel* reply) const {
1693    sp<AMessage> msg = new AMessage(kWhatGetTrackInfo, id());
1694    msg->setPointer("reply", reply);
1695
1696    sp<AMessage> response;
1697    status_t err = msg->postAndAwaitResponse(&response);
1698    return err;
1699}
1700
1701status_t NuPlayer::getSelectedTrack(int32_t type, Parcel* reply) const {
1702    sp<AMessage> msg = new AMessage(kWhatGetSelectedTrack, id());
1703    msg->setPointer("reply", reply);
1704    msg->setInt32("type", type);
1705
1706    sp<AMessage> response;
1707    status_t err = msg->postAndAwaitResponse(&response);
1708    if (err == OK && response != NULL) {
1709        CHECK(response->findInt32("err", &err));
1710    }
1711    return err;
1712}
1713
1714status_t NuPlayer::selectTrack(size_t trackIndex, bool select) {
1715    sp<AMessage> msg = new AMessage(kWhatSelectTrack, id());
1716    msg->setSize("trackIndex", trackIndex);
1717    msg->setInt32("select", select);
1718
1719    sp<AMessage> response;
1720    status_t err = msg->postAndAwaitResponse(&response);
1721
1722    if (err != OK) {
1723        return err;
1724    }
1725
1726    if (!response->findInt32("err", &err)) {
1727        err = OK;
1728    }
1729
1730    return err;
1731}
1732
1733void NuPlayer::schedulePollDuration() {
1734    sp<AMessage> msg = new AMessage(kWhatPollDuration, id());
1735    msg->setInt32("generation", mPollDurationGeneration);
1736    msg->post();
1737}
1738
1739void NuPlayer::cancelPollDuration() {
1740    ++mPollDurationGeneration;
1741}
1742
1743void NuPlayer::processDeferredActions() {
1744    while (!mDeferredActions.empty()) {
1745        // We won't execute any deferred actions until we're no longer in
1746        // an intermediate state, i.e. one more more decoders are currently
1747        // flushing or shutting down.
1748
1749        if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
1750            // We're currently flushing, postpone the reset until that's
1751            // completed.
1752
1753            ALOGV("postponing action mFlushingAudio=%d, mFlushingVideo=%d",
1754                  mFlushingAudio, mFlushingVideo);
1755
1756            break;
1757        }
1758
1759        sp<Action> action = *mDeferredActions.begin();
1760        mDeferredActions.erase(mDeferredActions.begin());
1761
1762        action->execute(this);
1763    }
1764}
1765
1766void NuPlayer::performSeek(int64_t seekTimeUs) {
1767    ALOGV("performSeek seekTimeUs=%lld us (%.2f secs)",
1768          seekTimeUs,
1769          seekTimeUs / 1E6);
1770
1771    if (mSource == NULL) {
1772        // This happens when reset occurs right before the loop mode
1773        // asynchronously seeks to the start of the stream.
1774        LOG_ALWAYS_FATAL_IF(mAudioDecoder != NULL || mVideoDecoder != NULL,
1775                "mSource is NULL and decoders not NULL audio(%p) video(%p)",
1776                mAudioDecoder.get(), mVideoDecoder.get());
1777        return;
1778    }
1779    mSource->seekTo(seekTimeUs);
1780    ++mTimedTextGeneration;
1781
1782    if (mDriver != NULL) {
1783        sp<NuPlayerDriver> driver = mDriver.promote();
1784        if (driver != NULL) {
1785            driver->notifyPosition(seekTimeUs);
1786            driver->notifySeekComplete();
1787        }
1788    }
1789
1790    // everything's flushed, continue playback.
1791}
1792
1793void NuPlayer::performDecoderFlush() {
1794    ALOGV("performDecoderFlush");
1795
1796    if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
1797        return;
1798    }
1799
1800    mTimeDiscontinuityPending = true;
1801
1802    if (mAudioDecoder != NULL) {
1803        flushDecoder(true /* audio */, false /* needShutdown */);
1804    }
1805
1806    if (mVideoDecoder != NULL) {
1807        flushDecoder(false /* audio */, false /* needShutdown */);
1808    }
1809}
1810
1811void NuPlayer::performDecoderShutdown(bool audio, bool video) {
1812    ALOGV("performDecoderShutdown audio=%d, video=%d", audio, video);
1813
1814    if ((!audio || mAudioDecoder == NULL)
1815            && (!video || mVideoDecoder == NULL)) {
1816        return;
1817    }
1818
1819    mTimeDiscontinuityPending = true;
1820
1821    if (audio && mAudioDecoder != NULL) {
1822        flushDecoder(true /* audio */, true /* needShutdown */);
1823    }
1824
1825    if (video && mVideoDecoder != NULL) {
1826        flushDecoder(false /* audio */, true /* needShutdown */);
1827    }
1828}
1829
1830void NuPlayer::performReset() {
1831    ALOGV("performReset");
1832
1833    CHECK(mAudioDecoder == NULL);
1834    CHECK(mVideoDecoder == NULL);
1835
1836    cancelPollDuration();
1837
1838    ++mScanSourcesGeneration;
1839    mScanSourcesPending = false;
1840
1841    ++mAudioDecoderGeneration;
1842    ++mVideoDecoderGeneration;
1843
1844    if (mRendererLooper != NULL) {
1845        if (mRenderer != NULL) {
1846            mRendererLooper->unregisterHandler(mRenderer->id());
1847        }
1848        mRendererLooper->stop();
1849        mRendererLooper.clear();
1850    }
1851    mRenderer.clear();
1852
1853    if (mSource != NULL) {
1854        mSource->stop();
1855
1856        mSource.clear();
1857    }
1858
1859    if (mDriver != NULL) {
1860        sp<NuPlayerDriver> driver = mDriver.promote();
1861        if (driver != NULL) {
1862            driver->notifyResetComplete();
1863        }
1864    }
1865
1866    mStarted = false;
1867}
1868
1869void NuPlayer::performScanSources() {
1870    ALOGV("performScanSources");
1871
1872    if (!mStarted) {
1873        return;
1874    }
1875
1876    if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
1877        postScanSources();
1878    }
1879}
1880
1881void NuPlayer::performSetSurface(const sp<NativeWindowWrapper> &wrapper) {
1882    ALOGV("performSetSurface");
1883
1884    mNativeWindow = wrapper;
1885
1886    // XXX - ignore error from setVideoScalingMode for now
1887    setVideoScalingMode(mVideoScalingMode);
1888
1889    if (mDriver != NULL) {
1890        sp<NuPlayerDriver> driver = mDriver.promote();
1891        if (driver != NULL) {
1892            driver->notifySetSurfaceComplete();
1893        }
1894    }
1895}
1896
1897void NuPlayer::onSourceNotify(const sp<AMessage> &msg) {
1898    int32_t what;
1899    CHECK(msg->findInt32("what", &what));
1900
1901    switch (what) {
1902        case Source::kWhatPrepared:
1903        {
1904            if (mSource == NULL) {
1905                // This is a stale notification from a source that was
1906                // asynchronously preparing when the client called reset().
1907                // We handled the reset, the source is gone.
1908                break;
1909            }
1910
1911            int32_t err;
1912            CHECK(msg->findInt32("err", &err));
1913
1914            sp<NuPlayerDriver> driver = mDriver.promote();
1915            if (driver != NULL) {
1916                // notify duration first, so that it's definitely set when
1917                // the app received the "prepare complete" callback.
1918                int64_t durationUs;
1919                if (mSource->getDuration(&durationUs) == OK) {
1920                    driver->notifyDuration(durationUs);
1921                }
1922                driver->notifyPrepareCompleted(err);
1923            }
1924
1925            break;
1926        }
1927
1928        case Source::kWhatFlagsChanged:
1929        {
1930            uint32_t flags;
1931            CHECK(msg->findInt32("flags", (int32_t *)&flags));
1932
1933            sp<NuPlayerDriver> driver = mDriver.promote();
1934            if (driver != NULL) {
1935                driver->notifyFlagsChanged(flags);
1936            }
1937
1938            if ((mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
1939                    && (!(flags & Source::FLAG_DYNAMIC_DURATION))) {
1940                cancelPollDuration();
1941            } else if (!(mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
1942                    && (flags & Source::FLAG_DYNAMIC_DURATION)
1943                    && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
1944                schedulePollDuration();
1945            }
1946
1947            mSourceFlags = flags;
1948            break;
1949        }
1950
1951        case Source::kWhatVideoSizeChanged:
1952        {
1953            sp<AMessage> format;
1954            CHECK(msg->findMessage("format", &format));
1955
1956            updateVideoSize(format);
1957            break;
1958        }
1959
1960        case Source::kWhatBufferingUpdate:
1961        {
1962            int32_t percentage;
1963            CHECK(msg->findInt32("percentage", &percentage));
1964
1965            notifyListener(MEDIA_BUFFERING_UPDATE, percentage, 0);
1966            break;
1967        }
1968
1969        case Source::kWhatBufferingStart:
1970        {
1971            notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_START, 0);
1972            break;
1973        }
1974
1975        case Source::kWhatBufferingEnd:
1976        {
1977            notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_END, 0);
1978            break;
1979        }
1980
1981        case Source::kWhatSubtitleData:
1982        {
1983            sp<ABuffer> buffer;
1984            CHECK(msg->findBuffer("buffer", &buffer));
1985
1986            sendSubtitleData(buffer, 0 /* baseIndex */);
1987            break;
1988        }
1989
1990        case Source::kWhatTimedTextData:
1991        {
1992            int32_t generation;
1993            if (msg->findInt32("generation", &generation)
1994                    && generation != mTimedTextGeneration) {
1995                break;
1996            }
1997
1998            sp<ABuffer> buffer;
1999            CHECK(msg->findBuffer("buffer", &buffer));
2000
2001            sp<NuPlayerDriver> driver = mDriver.promote();
2002            if (driver == NULL) {
2003                break;
2004            }
2005
2006            int posMs;
2007            int64_t timeUs, posUs;
2008            driver->getCurrentPosition(&posMs);
2009            posUs = posMs * 1000;
2010            CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2011
2012            if (posUs < timeUs) {
2013                if (!msg->findInt32("generation", &generation)) {
2014                    msg->setInt32("generation", mTimedTextGeneration);
2015                }
2016                msg->post(timeUs - posUs);
2017            } else {
2018                sendTimedTextData(buffer);
2019            }
2020            break;
2021        }
2022
2023        case Source::kWhatQueueDecoderShutdown:
2024        {
2025            int32_t audio, video;
2026            CHECK(msg->findInt32("audio", &audio));
2027            CHECK(msg->findInt32("video", &video));
2028
2029            sp<AMessage> reply;
2030            CHECK(msg->findMessage("reply", &reply));
2031
2032            queueDecoderShutdown(audio, video, reply);
2033            break;
2034        }
2035
2036        case Source::kWhatDrmNoLicense:
2037        {
2038            notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_DRM_NO_LICENSE);
2039            break;
2040        }
2041
2042        default:
2043            TRESPASS();
2044    }
2045}
2046
2047void NuPlayer::onClosedCaptionNotify(const sp<AMessage> &msg) {
2048    int32_t what;
2049    CHECK(msg->findInt32("what", &what));
2050
2051    switch (what) {
2052        case NuPlayer::CCDecoder::kWhatClosedCaptionData:
2053        {
2054            sp<ABuffer> buffer;
2055            CHECK(msg->findBuffer("buffer", &buffer));
2056
2057            size_t inbandTracks = 0;
2058            if (mSource != NULL) {
2059                inbandTracks = mSource->getTrackCount();
2060            }
2061
2062            sendSubtitleData(buffer, inbandTracks);
2063            break;
2064        }
2065
2066        case NuPlayer::CCDecoder::kWhatTrackAdded:
2067        {
2068            notifyListener(MEDIA_INFO, MEDIA_INFO_METADATA_UPDATE, 0);
2069
2070            break;
2071        }
2072
2073        default:
2074            TRESPASS();
2075    }
2076
2077
2078}
2079
2080void NuPlayer::sendSubtitleData(const sp<ABuffer> &buffer, int32_t baseIndex) {
2081    int32_t trackIndex;
2082    int64_t timeUs, durationUs;
2083    CHECK(buffer->meta()->findInt32("trackIndex", &trackIndex));
2084    CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2085    CHECK(buffer->meta()->findInt64("durationUs", &durationUs));
2086
2087    Parcel in;
2088    in.writeInt32(trackIndex + baseIndex);
2089    in.writeInt64(timeUs);
2090    in.writeInt64(durationUs);
2091    in.writeInt32(buffer->size());
2092    in.writeInt32(buffer->size());
2093    in.write(buffer->data(), buffer->size());
2094
2095    notifyListener(MEDIA_SUBTITLE_DATA, 0, 0, &in);
2096}
2097
2098void NuPlayer::sendTimedTextData(const sp<ABuffer> &buffer) {
2099    const void *data;
2100    size_t size = 0;
2101    int64_t timeUs;
2102    int32_t flag = TextDescriptions::LOCAL_DESCRIPTIONS;
2103
2104    AString mime;
2105    CHECK(buffer->meta()->findString("mime", &mime));
2106    CHECK(strcasecmp(mime.c_str(), MEDIA_MIMETYPE_TEXT_3GPP) == 0);
2107
2108    data = buffer->data();
2109    size = buffer->size();
2110
2111    Parcel parcel;
2112    if (size > 0) {
2113        CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2114        flag |= TextDescriptions::IN_BAND_TEXT_3GPP;
2115        TextDescriptions::getParcelOfDescriptions(
2116                (const uint8_t *)data, size, flag, timeUs / 1000, &parcel);
2117    }
2118
2119    if ((parcel.dataSize() > 0)) {
2120        notifyListener(MEDIA_TIMED_TEXT, 0, 0, &parcel);
2121    } else {  // send an empty timed text
2122        notifyListener(MEDIA_TIMED_TEXT, 0, 0);
2123    }
2124}
2125////////////////////////////////////////////////////////////////////////////////
2126
2127sp<AMessage> NuPlayer::Source::getFormat(bool audio) {
2128    sp<MetaData> meta = getFormatMeta(audio);
2129
2130    if (meta == NULL) {
2131        return NULL;
2132    }
2133
2134    sp<AMessage> msg = new AMessage;
2135
2136    if(convertMetaDataToMessage(meta, &msg) == OK) {
2137        return msg;
2138    }
2139    return NULL;
2140}
2141
2142void NuPlayer::Source::notifyFlagsChanged(uint32_t flags) {
2143    sp<AMessage> notify = dupNotify();
2144    notify->setInt32("what", kWhatFlagsChanged);
2145    notify->setInt32("flags", flags);
2146    notify->post();
2147}
2148
2149void NuPlayer::Source::notifyVideoSizeChanged(const sp<AMessage> &format) {
2150    sp<AMessage> notify = dupNotify();
2151    notify->setInt32("what", kWhatVideoSizeChanged);
2152    notify->setMessage("format", format);
2153    notify->post();
2154}
2155
2156void NuPlayer::Source::notifyPrepared(status_t err) {
2157    sp<AMessage> notify = dupNotify();
2158    notify->setInt32("what", kWhatPrepared);
2159    notify->setInt32("err", err);
2160    notify->post();
2161}
2162
2163void NuPlayer::Source::onMessageReceived(const sp<AMessage> & /* msg */) {
2164    TRESPASS();
2165}
2166
2167}  // namespace android
2168