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