NuPlayer.cpp revision 14f7672b5d450ed26a06fd3bb3ce045ea78b11b2
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 "NuPlayerDriver.h"
26#include "NuPlayerRenderer.h"
27#include "NuPlayerSource.h"
28#include "RTSPSource.h"
29#include "StreamingSource.h"
30#include "GenericSource.h"
31#include "mp4/MP4Source.h"
32
33#include "ATSParser.h"
34
35#include <cutils/properties.h> // for property_get
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/ACodec.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      mAudioEOS(false),
150      mVideoEOS(false),
151      mScanSourcesPending(false),
152      mScanSourcesGeneration(0),
153      mPollDurationGeneration(0),
154      mTimeDiscontinuityPending(false),
155      mFlushingAudio(NONE),
156      mFlushingVideo(NONE),
157      mSkipRenderingAudioUntilMediaTimeUs(-1ll),
158      mSkipRenderingVideoUntilMediaTimeUs(-1ll),
159      mVideoLateByUs(0ll),
160      mNumFramesTotal(0ll),
161      mNumFramesDropped(0ll),
162      mVideoScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW),
163      mStarted(false) {
164}
165
166NuPlayer::~NuPlayer() {
167}
168
169void NuPlayer::setUID(uid_t uid) {
170    mUIDValid = true;
171    mUID = uid;
172}
173
174void NuPlayer::setDriver(const wp<NuPlayerDriver> &driver) {
175    mDriver = driver;
176}
177
178void NuPlayer::setDataSourceAsync(const sp<IStreamSource> &source) {
179    sp<AMessage> msg = new AMessage(kWhatSetDataSource, id());
180
181    sp<AMessage> notify = new AMessage(kWhatSourceNotify, id());
182
183    char prop[PROPERTY_VALUE_MAX];
184    if (property_get("media.stagefright.use-mp4source", prop, NULL)
185            && (!strcmp(prop, "1") || !strcasecmp(prop, "true"))) {
186        msg->setObject("source", new MP4Source(notify, source));
187    } else {
188        msg->setObject("source", new StreamingSource(notify, source));
189    }
190
191    msg->post();
192}
193
194static bool IsHTTPLiveURL(const char *url) {
195    if (!strncasecmp("http://", url, 7)
196            || !strncasecmp("https://", url, 8)
197            || !strncasecmp("file://", url, 7)) {
198        size_t len = strlen(url);
199        if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
200            return true;
201        }
202
203        if (strstr(url,"m3u8")) {
204            return true;
205        }
206    }
207
208    return false;
209}
210
211void NuPlayer::setDataSourceAsync(
212        const char *url, const KeyedVector<String8, String8> *headers) {
213    sp<AMessage> msg = new AMessage(kWhatSetDataSource, id());
214    size_t len = strlen(url);
215
216    sp<AMessage> notify = new AMessage(kWhatSourceNotify, id());
217
218    sp<Source> source;
219    if (IsHTTPLiveURL(url)) {
220        source = new HTTPLiveSource(notify, url, headers, mUIDValid, mUID);
221    } else if (!strncasecmp(url, "rtsp://", 7)) {
222        source = new RTSPSource(notify, url, headers, mUIDValid, mUID);
223    } else if ((!strncasecmp(url, "http://", 7)
224                || !strncasecmp(url, "https://", 8))
225                    && ((len >= 4 && !strcasecmp(".sdp", &url[len - 4]))
226                    || strstr(url, ".sdp?"))) {
227        source = new RTSPSource(notify, url, headers, mUIDValid, mUID, true);
228    } else {
229        source = new GenericSource(notify, url, headers, mUIDValid, mUID);
230    }
231
232    msg->setObject("source", source);
233    msg->post();
234}
235
236void NuPlayer::setDataSourceAsync(int fd, int64_t offset, int64_t length) {
237    sp<AMessage> msg = new AMessage(kWhatSetDataSource, id());
238
239    sp<AMessage> notify = new AMessage(kWhatSourceNotify, id());
240
241    sp<Source> source = new GenericSource(notify, fd, offset, length);
242    msg->setObject("source", source);
243    msg->post();
244}
245
246void NuPlayer::prepareAsync() {
247    (new AMessage(kWhatPrepare, id()))->post();
248}
249
250void NuPlayer::setVideoSurfaceTextureAsync(
251        const sp<IGraphicBufferProducer> &bufferProducer) {
252    sp<AMessage> msg = new AMessage(kWhatSetVideoNativeWindow, id());
253
254    if (bufferProducer == NULL) {
255        msg->setObject("native-window", NULL);
256    } else {
257        msg->setObject(
258                "native-window",
259                new NativeWindowWrapper(
260                    new Surface(bufferProducer)));
261    }
262
263    msg->post();
264}
265
266void NuPlayer::setAudioSink(const sp<MediaPlayerBase::AudioSink> &sink) {
267    sp<AMessage> msg = new AMessage(kWhatSetAudioSink, id());
268    msg->setObject("sink", sink);
269    msg->post();
270}
271
272void NuPlayer::start() {
273    (new AMessage(kWhatStart, id()))->post();
274}
275
276void NuPlayer::pause() {
277    (new AMessage(kWhatPause, id()))->post();
278}
279
280void NuPlayer::resume() {
281    (new AMessage(kWhatResume, id()))->post();
282}
283
284void NuPlayer::resetAsync() {
285    (new AMessage(kWhatReset, id()))->post();
286}
287
288void NuPlayer::seekToAsync(int64_t seekTimeUs) {
289    sp<AMessage> msg = new AMessage(kWhatSeek, id());
290    msg->setInt64("seekTimeUs", seekTimeUs);
291    msg->post();
292}
293
294// static
295bool NuPlayer::IsFlushingState(FlushStatus state, bool *needShutdown) {
296    switch (state) {
297        case FLUSHING_DECODER:
298            if (needShutdown != NULL) {
299                *needShutdown = false;
300            }
301            return true;
302
303        case FLUSHING_DECODER_SHUTDOWN:
304            if (needShutdown != NULL) {
305                *needShutdown = true;
306            }
307            return true;
308
309        default:
310            return false;
311    }
312}
313
314void NuPlayer::onMessageReceived(const sp<AMessage> &msg) {
315    switch (msg->what()) {
316        case kWhatSetDataSource:
317        {
318            ALOGV("kWhatSetDataSource");
319
320            CHECK(mSource == NULL);
321
322            sp<RefBase> obj;
323            CHECK(msg->findObject("source", &obj));
324
325            mSource = static_cast<Source *>(obj.get());
326
327            looper()->registerHandler(mSource);
328
329            CHECK(mDriver != NULL);
330            sp<NuPlayerDriver> driver = mDriver.promote();
331            if (driver != NULL) {
332                driver->notifySetDataSourceCompleted(OK);
333            }
334            break;
335        }
336
337        case kWhatPrepare:
338        {
339            mSource->prepareAsync();
340            break;
341        }
342
343        case kWhatPollDuration:
344        {
345            int32_t generation;
346            CHECK(msg->findInt32("generation", &generation));
347
348            if (generation != mPollDurationGeneration) {
349                // stale
350                break;
351            }
352
353            int64_t durationUs;
354            if (mDriver != NULL && mSource->getDuration(&durationUs) == OK) {
355                sp<NuPlayerDriver> driver = mDriver.promote();
356                if (driver != NULL) {
357                    driver->notifyDuration(durationUs);
358                }
359            }
360
361            msg->post(1000000ll);  // poll again in a second.
362            break;
363        }
364
365        case kWhatSetVideoNativeWindow:
366        {
367            ALOGV("kWhatSetVideoNativeWindow");
368
369            mDeferredActions.push_back(
370                    new ShutdownDecoderAction(
371                        false /* audio */, true /* video */));
372
373            sp<RefBase> obj;
374            CHECK(msg->findObject("native-window", &obj));
375
376            mDeferredActions.push_back(
377                    new SetSurfaceAction(
378                        static_cast<NativeWindowWrapper *>(obj.get())));
379
380            if (obj != NULL) {
381                // If there is a new surface texture, instantiate decoders
382                // again if possible.
383                mDeferredActions.push_back(
384                        new SimpleAction(&NuPlayer::performScanSources));
385            }
386
387            processDeferredActions();
388            break;
389        }
390
391        case kWhatSetAudioSink:
392        {
393            ALOGV("kWhatSetAudioSink");
394
395            sp<RefBase> obj;
396            CHECK(msg->findObject("sink", &obj));
397
398            mAudioSink = static_cast<MediaPlayerBase::AudioSink *>(obj.get());
399            break;
400        }
401
402        case kWhatStart:
403        {
404            ALOGV("kWhatStart");
405
406            mVideoIsAVC = false;
407            mAudioEOS = false;
408            mVideoEOS = false;
409            mSkipRenderingAudioUntilMediaTimeUs = -1;
410            mSkipRenderingVideoUntilMediaTimeUs = -1;
411            mVideoLateByUs = 0;
412            mNumFramesTotal = 0;
413            mNumFramesDropped = 0;
414            mStarted = true;
415
416            mSource->start();
417
418            uint32_t flags = 0;
419
420            if (mSource->isRealTime()) {
421                flags |= Renderer::FLAG_REAL_TIME;
422            }
423
424            mRenderer = new Renderer(
425                    mAudioSink,
426                    new AMessage(kWhatRendererNotify, id()),
427                    flags);
428
429            looper()->registerHandler(mRenderer);
430
431            postScanSources();
432            break;
433        }
434
435        case kWhatScanSources:
436        {
437            int32_t generation;
438            CHECK(msg->findInt32("generation", &generation));
439            if (generation != mScanSourcesGeneration) {
440                // Drop obsolete msg.
441                break;
442            }
443
444            mScanSourcesPending = false;
445
446            ALOGV("scanning sources haveAudio=%d, haveVideo=%d",
447                 mAudioDecoder != NULL, mVideoDecoder != NULL);
448
449            bool mHadAnySourcesBefore =
450                (mAudioDecoder != NULL) || (mVideoDecoder != NULL);
451
452            if (mNativeWindow != NULL) {
453                instantiateDecoder(false, &mVideoDecoder);
454            }
455
456            if (mAudioSink != NULL) {
457                instantiateDecoder(true, &mAudioDecoder);
458            }
459
460            if (!mHadAnySourcesBefore
461                    && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
462                // This is the first time we've found anything playable.
463
464                if (mSourceFlags & Source::FLAG_DYNAMIC_DURATION) {
465                    schedulePollDuration();
466                }
467            }
468
469            status_t err;
470            if ((err = mSource->feedMoreTSData()) != OK) {
471                if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
472                    // We're not currently decoding anything (no audio or
473                    // video tracks found) and we just ran out of input data.
474
475                    if (err == ERROR_END_OF_STREAM) {
476                        notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
477                    } else {
478                        notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
479                    }
480                }
481                break;
482            }
483
484            if ((mAudioDecoder == NULL && mAudioSink != NULL)
485                    || (mVideoDecoder == NULL && mNativeWindow != NULL)) {
486                msg->post(100000ll);
487                mScanSourcesPending = true;
488            }
489            break;
490        }
491
492        case kWhatVideoNotify:
493        case kWhatAudioNotify:
494        {
495            bool audio = msg->what() == kWhatAudioNotify;
496
497            sp<AMessage> codecRequest;
498            CHECK(msg->findMessage("codec-request", &codecRequest));
499
500            int32_t what;
501            CHECK(codecRequest->findInt32("what", &what));
502
503            if (what == ACodec::kWhatFillThisBuffer) {
504                status_t err = feedDecoderInputData(
505                        audio, codecRequest);
506
507                if (err == -EWOULDBLOCK) {
508                    if (mSource->feedMoreTSData() == OK) {
509                        msg->post(10000ll);
510                    }
511                }
512            } else if (what == ACodec::kWhatEOS) {
513                int32_t err;
514                CHECK(codecRequest->findInt32("err", &err));
515
516                if (err == ERROR_END_OF_STREAM) {
517                    ALOGV("got %s decoder EOS", audio ? "audio" : "video");
518                } else {
519                    ALOGV("got %s decoder EOS w/ error %d",
520                         audio ? "audio" : "video",
521                         err);
522                }
523
524                mRenderer->queueEOS(audio, err);
525            } else if (what == ACodec::kWhatFlushCompleted) {
526                bool needShutdown;
527
528                if (audio) {
529                    CHECK(IsFlushingState(mFlushingAudio, &needShutdown));
530                    mFlushingAudio = FLUSHED;
531                } else {
532                    CHECK(IsFlushingState(mFlushingVideo, &needShutdown));
533                    mFlushingVideo = FLUSHED;
534
535                    mVideoLateByUs = 0;
536                }
537
538                ALOGV("decoder %s flush completed", audio ? "audio" : "video");
539
540                if (needShutdown) {
541                    ALOGV("initiating %s decoder shutdown",
542                         audio ? "audio" : "video");
543
544                    (audio ? mAudioDecoder : mVideoDecoder)->initiateShutdown();
545
546                    if (audio) {
547                        mFlushingAudio = SHUTTING_DOWN_DECODER;
548                    } else {
549                        mFlushingVideo = SHUTTING_DOWN_DECODER;
550                    }
551                }
552
553                finishFlushIfPossible();
554            } else if (what == ACodec::kWhatOutputFormatChanged) {
555                if (audio) {
556                    int32_t numChannels;
557                    CHECK(codecRequest->findInt32(
558                                "channel-count", &numChannels));
559
560                    int32_t sampleRate;
561                    CHECK(codecRequest->findInt32("sample-rate", &sampleRate));
562
563                    ALOGV("Audio output format changed to %d Hz, %d channels",
564                         sampleRate, numChannels);
565
566                    mAudioSink->close();
567
568                    audio_output_flags_t flags;
569                    int64_t durationUs;
570                    // FIXME: we should handle the case where the video decoder
571                    // is created after we receive the format change indication.
572                    // Current code will just make that we select deep buffer
573                    // with video which should not be a problem as it should
574                    // not prevent from keeping A/V sync.
575                    if (mVideoDecoder == NULL &&
576                            mSource->getDuration(&durationUs) == OK &&
577                            durationUs
578                                > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US) {
579                        flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
580                    } else {
581                        flags = AUDIO_OUTPUT_FLAG_NONE;
582                    }
583
584                    int32_t channelMask;
585                    if (!codecRequest->findInt32("channel-mask", &channelMask)) {
586                        channelMask = CHANNEL_MASK_USE_CHANNEL_ORDER;
587                    }
588
589                    CHECK_EQ(mAudioSink->open(
590                                sampleRate,
591                                numChannels,
592                                (audio_channel_mask_t)channelMask,
593                                AUDIO_FORMAT_PCM_16_BIT,
594                                8 /* bufferCount */,
595                                NULL,
596                                NULL,
597                                flags),
598                             (status_t)OK);
599                    mAudioSink->start();
600
601                    mRenderer->signalAudioSinkChanged();
602                } else {
603                    // video
604
605                    int32_t width, height;
606                    CHECK(codecRequest->findInt32("width", &width));
607                    CHECK(codecRequest->findInt32("height", &height));
608
609                    int32_t cropLeft, cropTop, cropRight, cropBottom;
610                    CHECK(codecRequest->findRect(
611                                "crop",
612                                &cropLeft, &cropTop, &cropRight, &cropBottom));
613
614                    int32_t displayWidth = cropRight - cropLeft + 1;
615                    int32_t displayHeight = cropBottom - cropTop + 1;
616
617                    ALOGV("Video output format changed to %d x %d "
618                         "(crop: %d x %d @ (%d, %d))",
619                         width, height,
620                         displayWidth,
621                         displayHeight,
622                         cropLeft, cropTop);
623
624                    sp<AMessage> videoInputFormat =
625                        mSource->getFormat(false /* audio */);
626
627                    // Take into account sample aspect ratio if necessary:
628                    int32_t sarWidth, sarHeight;
629                    if (videoInputFormat->findInt32("sar-width", &sarWidth)
630                            && videoInputFormat->findInt32(
631                                "sar-height", &sarHeight)) {
632                        ALOGV("Sample aspect ratio %d : %d",
633                              sarWidth, sarHeight);
634
635                        displayWidth = (displayWidth * sarWidth) / sarHeight;
636
637                        ALOGV("display dimensions %d x %d",
638                              displayWidth, displayHeight);
639                    }
640
641                    notifyListener(
642                            MEDIA_SET_VIDEO_SIZE, displayWidth, displayHeight);
643                }
644            } else if (what == ACodec::kWhatShutdownCompleted) {
645                ALOGV("%s shutdown completed", audio ? "audio" : "video");
646                if (audio) {
647                    mAudioDecoder.clear();
648
649                    CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER);
650                    mFlushingAudio = SHUT_DOWN;
651                } else {
652                    mVideoDecoder.clear();
653
654                    CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER);
655                    mFlushingVideo = SHUT_DOWN;
656                }
657
658                finishFlushIfPossible();
659            } else if (what == ACodec::kWhatError) {
660                ALOGE("Received error from %s decoder, aborting playback.",
661                     audio ? "audio" : "video");
662
663                mRenderer->queueEOS(audio, UNKNOWN_ERROR);
664            } else if (what == ACodec::kWhatDrainThisBuffer) {
665                renderBuffer(audio, codecRequest);
666            } else if (what != ACodec::kWhatComponentAllocated
667                    && what != ACodec::kWhatComponentConfigured
668                    && what != ACodec::kWhatBuffersAllocated) {
669                ALOGV("Unhandled codec notification %d '%c%c%c%c'.",
670                      what,
671                      what >> 24,
672                      (what >> 16) & 0xff,
673                      (what >> 8) & 0xff,
674                      what & 0xff);
675            }
676
677            break;
678        }
679
680        case kWhatRendererNotify:
681        {
682            int32_t what;
683            CHECK(msg->findInt32("what", &what));
684
685            if (what == Renderer::kWhatEOS) {
686                int32_t audio;
687                CHECK(msg->findInt32("audio", &audio));
688
689                int32_t finalResult;
690                CHECK(msg->findInt32("finalResult", &finalResult));
691
692                if (audio) {
693                    mAudioEOS = true;
694                } else {
695                    mVideoEOS = true;
696                }
697
698                if (finalResult == ERROR_END_OF_STREAM) {
699                    ALOGV("reached %s EOS", audio ? "audio" : "video");
700                } else {
701                    ALOGE("%s track encountered an error (%d)",
702                         audio ? "audio" : "video", finalResult);
703
704                    notifyListener(
705                            MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, finalResult);
706                }
707
708                if ((mAudioEOS || mAudioDecoder == NULL)
709                        && (mVideoEOS || mVideoDecoder == NULL)) {
710                    notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
711                }
712            } else if (what == Renderer::kWhatPosition) {
713                int64_t positionUs;
714                CHECK(msg->findInt64("positionUs", &positionUs));
715
716                CHECK(msg->findInt64("videoLateByUs", &mVideoLateByUs));
717
718                if (mDriver != NULL) {
719                    sp<NuPlayerDriver> driver = mDriver.promote();
720                    if (driver != NULL) {
721                        driver->notifyPosition(positionUs);
722
723                        driver->notifyFrameStats(
724                                mNumFramesTotal, mNumFramesDropped);
725                    }
726                }
727            } else if (what == Renderer::kWhatFlushComplete) {
728                int32_t audio;
729                CHECK(msg->findInt32("audio", &audio));
730
731                ALOGV("renderer %s flush completed.", audio ? "audio" : "video");
732            } else if (what == Renderer::kWhatVideoRenderingStart) {
733                notifyListener(MEDIA_INFO, MEDIA_INFO_RENDERING_START, 0);
734            }
735            break;
736        }
737
738        case kWhatMoreDataQueued:
739        {
740            break;
741        }
742
743        case kWhatReset:
744        {
745            ALOGV("kWhatReset");
746
747            mDeferredActions.push_back(
748                    new ShutdownDecoderAction(
749                        true /* audio */, true /* video */));
750
751            mDeferredActions.push_back(
752                    new SimpleAction(&NuPlayer::performReset));
753
754            processDeferredActions();
755            break;
756        }
757
758        case kWhatSeek:
759        {
760            int64_t seekTimeUs;
761            CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
762
763            ALOGV("kWhatSeek seekTimeUs=%lld us", seekTimeUs);
764
765            mDeferredActions.push_back(
766                    new SimpleAction(&NuPlayer::performDecoderFlush));
767
768            mDeferredActions.push_back(new SeekAction(seekTimeUs));
769
770            processDeferredActions();
771            break;
772        }
773
774        case kWhatPause:
775        {
776            CHECK(mRenderer != NULL);
777            mSource->pause();
778            mRenderer->pause();
779            break;
780        }
781
782        case kWhatResume:
783        {
784            CHECK(mRenderer != NULL);
785            mSource->resume();
786            mRenderer->resume();
787            break;
788        }
789
790        case kWhatSourceNotify:
791        {
792            onSourceNotify(msg);
793            break;
794        }
795
796        default:
797            TRESPASS();
798            break;
799    }
800}
801
802void NuPlayer::finishFlushIfPossible() {
803    if (mFlushingAudio != FLUSHED && mFlushingAudio != SHUT_DOWN) {
804        return;
805    }
806
807    if (mFlushingVideo != FLUSHED && mFlushingVideo != SHUT_DOWN) {
808        return;
809    }
810
811    ALOGV("both audio and video are flushed now.");
812
813    if (mTimeDiscontinuityPending) {
814        mRenderer->signalTimeDiscontinuity();
815        mTimeDiscontinuityPending = false;
816    }
817
818    if (mAudioDecoder != NULL) {
819        mAudioDecoder->signalResume();
820    }
821
822    if (mVideoDecoder != NULL) {
823        mVideoDecoder->signalResume();
824    }
825
826    mFlushingAudio = NONE;
827    mFlushingVideo = NONE;
828
829    processDeferredActions();
830}
831
832void NuPlayer::postScanSources() {
833    if (mScanSourcesPending) {
834        return;
835    }
836
837    sp<AMessage> msg = new AMessage(kWhatScanSources, id());
838    msg->setInt32("generation", mScanSourcesGeneration);
839    msg->post();
840
841    mScanSourcesPending = true;
842}
843
844status_t NuPlayer::instantiateDecoder(bool audio, sp<Decoder> *decoder) {
845    if (*decoder != NULL) {
846        return OK;
847    }
848
849    sp<AMessage> format = mSource->getFormat(audio);
850
851    if (format == NULL) {
852        return -EWOULDBLOCK;
853    }
854
855    if (!audio) {
856        AString mime;
857        CHECK(format->findString("mime", &mime));
858        mVideoIsAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
859    }
860
861    sp<AMessage> notify =
862        new AMessage(audio ? kWhatAudioNotify : kWhatVideoNotify,
863                     id());
864
865    *decoder = audio ? new Decoder(notify) :
866                       new Decoder(notify, mNativeWindow);
867    looper()->registerHandler(*decoder);
868
869    (*decoder)->configure(format);
870
871    return OK;
872}
873
874status_t NuPlayer::feedDecoderInputData(bool audio, const sp<AMessage> &msg) {
875    sp<AMessage> reply;
876    CHECK(msg->findMessage("reply", &reply));
877
878    if ((audio && IsFlushingState(mFlushingAudio))
879            || (!audio && IsFlushingState(mFlushingVideo))) {
880        reply->setInt32("err", INFO_DISCONTINUITY);
881        reply->post();
882        return OK;
883    }
884
885    sp<ABuffer> accessUnit;
886
887    bool dropAccessUnit;
888    do {
889        status_t err = mSource->dequeueAccessUnit(audio, &accessUnit);
890
891        if (err == -EWOULDBLOCK) {
892            return err;
893        } else if (err != OK) {
894            if (err == INFO_DISCONTINUITY) {
895                int32_t type;
896                CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
897
898                bool formatChange =
899                    (audio &&
900                     (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
901                    || (!audio &&
902                            (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
903
904                bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
905
906                ALOGI("%s discontinuity (formatChange=%d, time=%d)",
907                     audio ? "audio" : "video", formatChange, timeChange);
908
909                if (audio) {
910                    mSkipRenderingAudioUntilMediaTimeUs = -1;
911                } else {
912                    mSkipRenderingVideoUntilMediaTimeUs = -1;
913                }
914
915                if (timeChange) {
916                    sp<AMessage> extra;
917                    if (accessUnit->meta()->findMessage("extra", &extra)
918                            && extra != NULL) {
919                        int64_t resumeAtMediaTimeUs;
920                        if (extra->findInt64(
921                                    "resume-at-mediatimeUs", &resumeAtMediaTimeUs)) {
922                            ALOGI("suppressing rendering of %s until %lld us",
923                                    audio ? "audio" : "video", resumeAtMediaTimeUs);
924
925                            if (audio) {
926                                mSkipRenderingAudioUntilMediaTimeUs =
927                                    resumeAtMediaTimeUs;
928                            } else {
929                                mSkipRenderingVideoUntilMediaTimeUs =
930                                    resumeAtMediaTimeUs;
931                            }
932                        }
933                    }
934                }
935
936                mTimeDiscontinuityPending =
937                    mTimeDiscontinuityPending || timeChange;
938
939                if (formatChange || timeChange) {
940                    if (mFlushingAudio == NONE && mFlushingVideo == NONE) {
941                        // And we'll resume scanning sources once we're done
942                        // flushing.
943                        mDeferredActions.push_front(
944                                new SimpleAction(
945                                    &NuPlayer::performScanSources));
946                    }
947
948                    flushDecoder(audio, formatChange);
949                } else {
950                    // This stream is unaffected by the discontinuity
951
952                    if (audio) {
953                        mFlushingAudio = FLUSHED;
954                    } else {
955                        mFlushingVideo = FLUSHED;
956                    }
957
958                    finishFlushIfPossible();
959
960                    return -EWOULDBLOCK;
961                }
962            }
963
964            reply->setInt32("err", err);
965            reply->post();
966            return OK;
967        }
968
969        if (!audio) {
970            ++mNumFramesTotal;
971        }
972
973        dropAccessUnit = false;
974        if (!audio
975                && mVideoLateByUs > 100000ll
976                && mVideoIsAVC
977                && !IsAVCReferenceFrame(accessUnit)) {
978            dropAccessUnit = true;
979            ++mNumFramesDropped;
980        }
981    } while (dropAccessUnit);
982
983    // ALOGV("returned a valid buffer of %s data", audio ? "audio" : "video");
984
985#if 0
986    int64_t mediaTimeUs;
987    CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
988    ALOGV("feeding %s input buffer at media time %.2f secs",
989         audio ? "audio" : "video",
990         mediaTimeUs / 1E6);
991#endif
992
993    reply->setBuffer("buffer", accessUnit);
994    reply->post();
995
996    return OK;
997}
998
999void NuPlayer::renderBuffer(bool audio, const sp<AMessage> &msg) {
1000    // ALOGV("renderBuffer %s", audio ? "audio" : "video");
1001
1002    sp<AMessage> reply;
1003    CHECK(msg->findMessage("reply", &reply));
1004
1005    if (IsFlushingState(audio ? mFlushingAudio : mFlushingVideo)) {
1006        // We're currently attempting to flush the decoder, in order
1007        // to complete this, the decoder wants all its buffers back,
1008        // so we don't want any output buffers it sent us (from before
1009        // we initiated the flush) to be stuck in the renderer's queue.
1010
1011        ALOGV("we're still flushing the %s decoder, sending its output buffer"
1012             " right back.", audio ? "audio" : "video");
1013
1014        reply->post();
1015        return;
1016    }
1017
1018    sp<ABuffer> buffer;
1019    CHECK(msg->findBuffer("buffer", &buffer));
1020
1021    int64_t &skipUntilMediaTimeUs =
1022        audio
1023            ? mSkipRenderingAudioUntilMediaTimeUs
1024            : mSkipRenderingVideoUntilMediaTimeUs;
1025
1026    if (skipUntilMediaTimeUs >= 0) {
1027        int64_t mediaTimeUs;
1028        CHECK(buffer->meta()->findInt64("timeUs", &mediaTimeUs));
1029
1030        if (mediaTimeUs < skipUntilMediaTimeUs) {
1031            ALOGV("dropping %s buffer at time %lld as requested.",
1032                 audio ? "audio" : "video",
1033                 mediaTimeUs);
1034
1035            reply->post();
1036            return;
1037        }
1038
1039        skipUntilMediaTimeUs = -1;
1040    }
1041
1042    mRenderer->queueBuffer(audio, buffer, reply);
1043}
1044
1045void NuPlayer::notifyListener(int msg, int ext1, int ext2) {
1046    if (mDriver == NULL) {
1047        return;
1048    }
1049
1050    sp<NuPlayerDriver> driver = mDriver.promote();
1051
1052    if (driver == NULL) {
1053        return;
1054    }
1055
1056    driver->notifyListener(msg, ext1, ext2);
1057}
1058
1059void NuPlayer::flushDecoder(bool audio, bool needShutdown) {
1060    ALOGV("[%s] flushDecoder needShutdown=%d",
1061          audio ? "audio" : "video", needShutdown);
1062
1063    if ((audio && mAudioDecoder == NULL) || (!audio && mVideoDecoder == NULL)) {
1064        ALOGI("flushDecoder %s without decoder present",
1065             audio ? "audio" : "video");
1066    }
1067
1068    // Make sure we don't continue to scan sources until we finish flushing.
1069    ++mScanSourcesGeneration;
1070    mScanSourcesPending = false;
1071
1072    (audio ? mAudioDecoder : mVideoDecoder)->signalFlush();
1073    mRenderer->flush(audio);
1074
1075    FlushStatus newStatus =
1076        needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;
1077
1078    if (audio) {
1079        CHECK(mFlushingAudio == NONE
1080                || mFlushingAudio == AWAITING_DISCONTINUITY);
1081
1082        mFlushingAudio = newStatus;
1083
1084        if (mFlushingVideo == NONE) {
1085            mFlushingVideo = (mVideoDecoder != NULL)
1086                ? AWAITING_DISCONTINUITY
1087                : FLUSHED;
1088        }
1089    } else {
1090        CHECK(mFlushingVideo == NONE
1091                || mFlushingVideo == AWAITING_DISCONTINUITY);
1092
1093        mFlushingVideo = newStatus;
1094
1095        if (mFlushingAudio == NONE) {
1096            mFlushingAudio = (mAudioDecoder != NULL)
1097                ? AWAITING_DISCONTINUITY
1098                : FLUSHED;
1099        }
1100    }
1101}
1102
1103sp<AMessage> NuPlayer::Source::getFormat(bool audio) {
1104    sp<MetaData> meta = getFormatMeta(audio);
1105
1106    if (meta == NULL) {
1107        return NULL;
1108    }
1109
1110    sp<AMessage> msg = new AMessage;
1111
1112    if(convertMetaDataToMessage(meta, &msg) == OK) {
1113        return msg;
1114    }
1115    return NULL;
1116}
1117
1118status_t NuPlayer::setVideoScalingMode(int32_t mode) {
1119    mVideoScalingMode = mode;
1120    if (mNativeWindow != NULL) {
1121        status_t ret = native_window_set_scaling_mode(
1122                mNativeWindow->getNativeWindow().get(), mVideoScalingMode);
1123        if (ret != OK) {
1124            ALOGE("Failed to set scaling mode (%d): %s",
1125                -ret, strerror(-ret));
1126            return ret;
1127        }
1128    }
1129    return OK;
1130}
1131
1132void NuPlayer::schedulePollDuration() {
1133    sp<AMessage> msg = new AMessage(kWhatPollDuration, id());
1134    msg->setInt32("generation", mPollDurationGeneration);
1135    msg->post();
1136}
1137
1138void NuPlayer::cancelPollDuration() {
1139    ++mPollDurationGeneration;
1140}
1141
1142void NuPlayer::processDeferredActions() {
1143    while (!mDeferredActions.empty()) {
1144        // We won't execute any deferred actions until we're no longer in
1145        // an intermediate state, i.e. one more more decoders are currently
1146        // flushing or shutting down.
1147
1148        if (mRenderer != NULL) {
1149            // There's an edge case where the renderer owns all output
1150            // buffers and is paused, therefore the decoder will not read
1151            // more input data and will never encounter the matching
1152            // discontinuity. To avoid this, we resume the renderer.
1153
1154            if (mFlushingAudio == AWAITING_DISCONTINUITY
1155                    || mFlushingVideo == AWAITING_DISCONTINUITY) {
1156                mRenderer->resume();
1157            }
1158        }
1159
1160        if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
1161            // We're currently flushing, postpone the reset until that's
1162            // completed.
1163
1164            ALOGV("postponing action mFlushingAudio=%d, mFlushingVideo=%d",
1165                  mFlushingAudio, mFlushingVideo);
1166
1167            break;
1168        }
1169
1170        sp<Action> action = *mDeferredActions.begin();
1171        mDeferredActions.erase(mDeferredActions.begin());
1172
1173        action->execute(this);
1174    }
1175}
1176
1177void NuPlayer::performSeek(int64_t seekTimeUs) {
1178    ALOGV("performSeek seekTimeUs=%lld us (%.2f secs)",
1179          seekTimeUs,
1180          seekTimeUs / 1E6);
1181
1182    mSource->seekTo(seekTimeUs);
1183
1184    if (mDriver != NULL) {
1185        sp<NuPlayerDriver> driver = mDriver.promote();
1186        if (driver != NULL) {
1187            driver->notifyPosition(seekTimeUs);
1188            driver->notifySeekComplete();
1189        }
1190    }
1191
1192    // everything's flushed, continue playback.
1193}
1194
1195void NuPlayer::performDecoderFlush() {
1196    ALOGV("performDecoderFlush");
1197
1198    if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
1199        return;
1200    }
1201
1202    mTimeDiscontinuityPending = true;
1203
1204    if (mAudioDecoder != NULL) {
1205        flushDecoder(true /* audio */, false /* needShutdown */);
1206    }
1207
1208    if (mVideoDecoder != NULL) {
1209        flushDecoder(false /* audio */, false /* needShutdown */);
1210    }
1211}
1212
1213void NuPlayer::performDecoderShutdown(bool audio, bool video) {
1214    ALOGV("performDecoderShutdown audio=%d, video=%d", audio, video);
1215
1216    if ((!audio || mAudioDecoder == NULL)
1217            && (!video || mVideoDecoder == NULL)) {
1218        return;
1219    }
1220
1221    mTimeDiscontinuityPending = true;
1222
1223    if (mFlushingAudio == NONE && (!audio || mAudioDecoder == NULL)) {
1224        mFlushingAudio = FLUSHED;
1225    }
1226
1227    if (mFlushingVideo == NONE && (!video || mVideoDecoder == NULL)) {
1228        mFlushingVideo = FLUSHED;
1229    }
1230
1231    if (audio && mAudioDecoder != NULL) {
1232        flushDecoder(true /* audio */, true /* needShutdown */);
1233    }
1234
1235    if (video && mVideoDecoder != NULL) {
1236        flushDecoder(false /* audio */, true /* needShutdown */);
1237    }
1238}
1239
1240void NuPlayer::performReset() {
1241    ALOGV("performReset");
1242
1243    CHECK(mAudioDecoder == NULL);
1244    CHECK(mVideoDecoder == NULL);
1245
1246    cancelPollDuration();
1247
1248    ++mScanSourcesGeneration;
1249    mScanSourcesPending = false;
1250
1251    mRenderer.clear();
1252
1253    if (mSource != NULL) {
1254        mSource->stop();
1255
1256        looper()->unregisterHandler(mSource->id());
1257
1258        mSource.clear();
1259    }
1260
1261    if (mDriver != NULL) {
1262        sp<NuPlayerDriver> driver = mDriver.promote();
1263        if (driver != NULL) {
1264            driver->notifyResetComplete();
1265        }
1266    }
1267
1268    mStarted = false;
1269}
1270
1271void NuPlayer::performScanSources() {
1272    ALOGV("performScanSources");
1273
1274    if (!mStarted) {
1275        return;
1276    }
1277
1278    if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
1279        postScanSources();
1280    }
1281}
1282
1283void NuPlayer::performSetSurface(const sp<NativeWindowWrapper> &wrapper) {
1284    ALOGV("performSetSurface");
1285
1286    mNativeWindow = wrapper;
1287
1288    // XXX - ignore error from setVideoScalingMode for now
1289    setVideoScalingMode(mVideoScalingMode);
1290
1291    if (mDriver != NULL) {
1292        sp<NuPlayerDriver> driver = mDriver.promote();
1293        if (driver != NULL) {
1294            driver->notifySetSurfaceComplete();
1295        }
1296    }
1297}
1298
1299void NuPlayer::onSourceNotify(const sp<AMessage> &msg) {
1300    int32_t what;
1301    CHECK(msg->findInt32("what", &what));
1302
1303    switch (what) {
1304        case Source::kWhatPrepared:
1305        {
1306            if (mSource == NULL) {
1307                // This is a stale notification from a source that was
1308                // asynchronously preparing when the client called reset().
1309                // We handled the reset, the source is gone.
1310                break;
1311            }
1312
1313            int32_t err;
1314            CHECK(msg->findInt32("err", &err));
1315
1316            sp<NuPlayerDriver> driver = mDriver.promote();
1317            if (driver != NULL) {
1318                driver->notifyPrepareCompleted(err);
1319            }
1320
1321            int64_t durationUs;
1322            if (mDriver != NULL && mSource->getDuration(&durationUs) == OK) {
1323                sp<NuPlayerDriver> driver = mDriver.promote();
1324                if (driver != NULL) {
1325                    driver->notifyDuration(durationUs);
1326                }
1327            }
1328            break;
1329        }
1330
1331        case Source::kWhatFlagsChanged:
1332        {
1333            uint32_t flags;
1334            CHECK(msg->findInt32("flags", (int32_t *)&flags));
1335
1336            if ((mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
1337                    && (!(flags & Source::FLAG_DYNAMIC_DURATION))) {
1338                cancelPollDuration();
1339            } else if (!(mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
1340                    && (flags & Source::FLAG_DYNAMIC_DURATION)
1341                    && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
1342                schedulePollDuration();
1343            }
1344
1345            mSourceFlags = flags;
1346            break;
1347        }
1348
1349        case Source::kWhatVideoSizeChanged:
1350        {
1351            int32_t width, height;
1352            CHECK(msg->findInt32("width", &width));
1353            CHECK(msg->findInt32("height", &height));
1354
1355            notifyListener(MEDIA_SET_VIDEO_SIZE, width, height);
1356            break;
1357        }
1358
1359        case Source::kWhatBufferingStart:
1360        {
1361            notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_START, 0);
1362            break;
1363        }
1364
1365        case Source::kWhatBufferingEnd:
1366        {
1367            notifyListener(MEDIA_INFO, MEDIA_INFO_BUFFERING_END, 0);
1368            break;
1369        }
1370
1371        case Source::kWhatQueueDecoderShutdown:
1372        {
1373            int32_t audio, video;
1374            CHECK(msg->findInt32("audio", &audio));
1375            CHECK(msg->findInt32("video", &video));
1376
1377            sp<AMessage> reply;
1378            CHECK(msg->findMessage("reply", &reply));
1379
1380            queueDecoderShutdown(audio, video, reply);
1381            break;
1382        }
1383
1384        default:
1385            TRESPASS();
1386    }
1387}
1388
1389////////////////////////////////////////////////////////////////////////////////
1390
1391void NuPlayer::Source::notifyFlagsChanged(uint32_t flags) {
1392    sp<AMessage> notify = dupNotify();
1393    notify->setInt32("what", kWhatFlagsChanged);
1394    notify->setInt32("flags", flags);
1395    notify->post();
1396}
1397
1398void NuPlayer::Source::notifyVideoSizeChanged(int32_t width, int32_t height) {
1399    sp<AMessage> notify = dupNotify();
1400    notify->setInt32("what", kWhatVideoSizeChanged);
1401    notify->setInt32("width", width);
1402    notify->setInt32("height", height);
1403    notify->post();
1404}
1405
1406void NuPlayer::Source::notifyPrepared(status_t err) {
1407    sp<AMessage> notify = dupNotify();
1408    notify->setInt32("what", kWhatPrepared);
1409    notify->setInt32("err", err);
1410    notify->post();
1411}
1412
1413void NuPlayer::Source::onMessageReceived(const sp<AMessage> &msg) {
1414    TRESPASS();
1415}
1416
1417void NuPlayer::queueDecoderShutdown(
1418        bool audio, bool video, const sp<AMessage> &reply) {
1419    ALOGI("queueDecoderShutdown audio=%d, video=%d", audio, video);
1420
1421    mDeferredActions.push_back(
1422            new ShutdownDecoderAction(audio, video));
1423
1424    mDeferredActions.push_back(
1425            new SimpleAction(&NuPlayer::performScanSources));
1426
1427    mDeferredActions.push_back(new PostMessageAction(reply));
1428
1429    processDeferredActions();
1430}
1431
1432}  // namespace android
1433