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