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