NuPlayer.cpp revision eca36b5a1759970bc3d0373d72d6fec7c9b7e944
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
31#include "ATSParser.h"
32
33#include <media/stagefright/foundation/hexdump.h>
34#include <media/stagefright/foundation/ABuffer.h>
35#include <media/stagefright/foundation/ADebug.h>
36#include <media/stagefright/foundation/AMessage.h>
37#include <media/stagefright/ACodec.h>
38#include <media/stagefright/MediaDefs.h>
39#include <media/stagefright/MediaErrors.h>
40#include <media/stagefright/MetaData.h>
41#include <surfaceflinger/Surface.h>
42#include <gui/ISurfaceTexture.h>
43
44#include "avc_utils.h"
45
46namespace android {
47
48////////////////////////////////////////////////////////////////////////////////
49
50NuPlayer::NuPlayer()
51    : mUIDValid(false),
52      mVideoIsAVC(false),
53      mAudioEOS(false),
54      mVideoEOS(false),
55      mScanSourcesPending(false),
56      mScanSourcesGeneration(0),
57      mTimeDiscontinuityPending(false),
58      mFlushingAudio(NONE),
59      mFlushingVideo(NONE),
60      mResetInProgress(false),
61      mResetPostponed(false),
62      mSkipRenderingAudioUntilMediaTimeUs(-1ll),
63      mSkipRenderingVideoUntilMediaTimeUs(-1ll),
64      mVideoLateByUs(0ll),
65      mNumFramesTotal(0ll),
66      mNumFramesDropped(0ll) {
67}
68
69NuPlayer::~NuPlayer() {
70}
71
72void NuPlayer::setUID(uid_t uid) {
73    mUIDValid = true;
74    mUID = uid;
75}
76
77void NuPlayer::setDriver(const wp<NuPlayerDriver> &driver) {
78    mDriver = driver;
79}
80
81void NuPlayer::setDataSource(const sp<IStreamSource> &source) {
82    sp<AMessage> msg = new AMessage(kWhatSetDataSource, id());
83
84    msg->setObject("source", new StreamingSource(source));
85    msg->post();
86}
87
88void NuPlayer::setDataSource(
89        const char *url, const KeyedVector<String8, String8> *headers) {
90    sp<AMessage> msg = new AMessage(kWhatSetDataSource, id());
91
92    if (!strncasecmp(url, "rtsp://", 7)) {
93        msg->setObject(
94                "source", new RTSPSource(url, headers, mUIDValid, mUID));
95    } else {
96        msg->setObject(
97                "source", new HTTPLiveSource(url, headers, mUIDValid, mUID));
98    }
99
100    msg->post();
101}
102
103void NuPlayer::setVideoSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture) {
104    sp<AMessage> msg = new AMessage(kWhatSetVideoNativeWindow, id());
105    sp<SurfaceTextureClient> surfaceTextureClient(surfaceTexture != NULL ?
106                new SurfaceTextureClient(surfaceTexture) : NULL);
107    msg->setObject("native-window", new NativeWindowWrapper(surfaceTextureClient));
108    msg->post();
109}
110
111void NuPlayer::setAudioSink(const sp<MediaPlayerBase::AudioSink> &sink) {
112    sp<AMessage> msg = new AMessage(kWhatSetAudioSink, id());
113    msg->setObject("sink", sink);
114    msg->post();
115}
116
117void NuPlayer::start() {
118    (new AMessage(kWhatStart, id()))->post();
119}
120
121void NuPlayer::pause() {
122    (new AMessage(kWhatPause, id()))->post();
123}
124
125void NuPlayer::resume() {
126    (new AMessage(kWhatResume, id()))->post();
127}
128
129void NuPlayer::resetAsync() {
130    (new AMessage(kWhatReset, id()))->post();
131}
132
133void NuPlayer::seekToAsync(int64_t seekTimeUs) {
134    sp<AMessage> msg = new AMessage(kWhatSeek, id());
135    msg->setInt64("seekTimeUs", seekTimeUs);
136    msg->post();
137}
138
139// static
140bool NuPlayer::IsFlushingState(FlushStatus state, bool *needShutdown) {
141    switch (state) {
142        case FLUSHING_DECODER:
143            if (needShutdown != NULL) {
144                *needShutdown = false;
145            }
146            return true;
147
148        case FLUSHING_DECODER_SHUTDOWN:
149            if (needShutdown != NULL) {
150                *needShutdown = true;
151            }
152            return true;
153
154        default:
155            return false;
156    }
157}
158
159void NuPlayer::onMessageReceived(const sp<AMessage> &msg) {
160    switch (msg->what()) {
161        case kWhatSetDataSource:
162        {
163            ALOGV("kWhatSetDataSource");
164
165            CHECK(mSource == NULL);
166
167            sp<RefBase> obj;
168            CHECK(msg->findObject("source", &obj));
169
170            mSource = static_cast<Source *>(obj.get());
171            break;
172        }
173
174        case kWhatSetVideoNativeWindow:
175        {
176            ALOGV("kWhatSetVideoNativeWindow");
177
178            sp<RefBase> obj;
179            CHECK(msg->findObject("native-window", &obj));
180
181            mNativeWindow = static_cast<NativeWindowWrapper *>(obj.get());
182            break;
183        }
184
185        case kWhatSetAudioSink:
186        {
187            ALOGV("kWhatSetAudioSink");
188
189            sp<RefBase> obj;
190            CHECK(msg->findObject("sink", &obj));
191
192            mAudioSink = static_cast<MediaPlayerBase::AudioSink *>(obj.get());
193            break;
194        }
195
196        case kWhatStart:
197        {
198            ALOGV("kWhatStart");
199
200            mVideoIsAVC = false;
201            mAudioEOS = false;
202            mVideoEOS = false;
203            mSkipRenderingAudioUntilMediaTimeUs = -1;
204            mSkipRenderingVideoUntilMediaTimeUs = -1;
205            mVideoLateByUs = 0;
206            mNumFramesTotal = 0;
207            mNumFramesDropped = 0;
208
209            mSource->start();
210
211            mRenderer = new Renderer(
212                    mAudioSink,
213                    new AMessage(kWhatRendererNotify, id()));
214
215            looper()->registerHandler(mRenderer);
216
217            postScanSources();
218            break;
219        }
220
221        case kWhatScanSources:
222        {
223            int32_t generation;
224            CHECK(msg->findInt32("generation", &generation));
225            if (generation != mScanSourcesGeneration) {
226                // Drop obsolete msg.
227                break;
228            }
229
230            mScanSourcesPending = false;
231
232            ALOGV("scanning sources haveAudio=%d, haveVideo=%d",
233                 mAudioDecoder != NULL, mVideoDecoder != NULL);
234
235            instantiateDecoder(false, &mVideoDecoder);
236
237            if (mAudioSink != NULL) {
238                instantiateDecoder(true, &mAudioDecoder);
239            }
240
241            status_t err;
242            if ((err = mSource->feedMoreTSData()) != OK) {
243                if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
244                    // We're not currently decoding anything (no audio or
245                    // video tracks found) and we just ran out of input data.
246
247                    if (err == ERROR_END_OF_STREAM) {
248                        notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
249                    } else {
250                        notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
251                    }
252                }
253                break;
254            }
255
256            if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
257                msg->post(100000ll);
258                mScanSourcesPending = true;
259            }
260            break;
261        }
262
263        case kWhatVideoNotify:
264        case kWhatAudioNotify:
265        {
266            bool audio = msg->what() == kWhatAudioNotify;
267
268            sp<AMessage> codecRequest;
269            CHECK(msg->findMessage("codec-request", &codecRequest));
270
271            int32_t what;
272            CHECK(codecRequest->findInt32("what", &what));
273
274            if (what == ACodec::kWhatFillThisBuffer) {
275                status_t err = feedDecoderInputData(
276                        audio, codecRequest);
277
278                if (err == -EWOULDBLOCK) {
279                    if (mSource->feedMoreTSData() == OK) {
280                        msg->post(10000ll);
281                    }
282                }
283            } else if (what == ACodec::kWhatEOS) {
284                int32_t err;
285                CHECK(codecRequest->findInt32("err", &err));
286
287                if (err == ERROR_END_OF_STREAM) {
288                    ALOGV("got %s decoder EOS", audio ? "audio" : "video");
289                } else {
290                    ALOGV("got %s decoder EOS w/ error %d",
291                         audio ? "audio" : "video",
292                         err);
293                }
294
295                mRenderer->queueEOS(audio, err);
296            } else if (what == ACodec::kWhatFlushCompleted) {
297                bool needShutdown;
298
299                if (audio) {
300                    CHECK(IsFlushingState(mFlushingAudio, &needShutdown));
301                    mFlushingAudio = FLUSHED;
302                } else {
303                    CHECK(IsFlushingState(mFlushingVideo, &needShutdown));
304                    mFlushingVideo = FLUSHED;
305
306                    mVideoLateByUs = 0;
307                }
308
309                ALOGV("decoder %s flush completed", audio ? "audio" : "video");
310
311                if (needShutdown) {
312                    ALOGV("initiating %s decoder shutdown",
313                         audio ? "audio" : "video");
314
315                    (audio ? mAudioDecoder : mVideoDecoder)->initiateShutdown();
316
317                    if (audio) {
318                        mFlushingAudio = SHUTTING_DOWN_DECODER;
319                    } else {
320                        mFlushingVideo = SHUTTING_DOWN_DECODER;
321                    }
322                }
323
324                finishFlushIfPossible();
325            } else if (what == ACodec::kWhatOutputFormatChanged) {
326                if (audio) {
327                    int32_t numChannels;
328                    CHECK(codecRequest->findInt32("channel-count", &numChannels));
329
330                    int32_t sampleRate;
331                    CHECK(codecRequest->findInt32("sample-rate", &sampleRate));
332
333                    ALOGV("Audio output format changed to %d Hz, %d channels",
334                         sampleRate, numChannels);
335
336                    mAudioSink->close();
337                    CHECK_EQ(mAudioSink->open(
338                                sampleRate,
339                                numChannels,
340                                AUDIO_FORMAT_PCM_16_BIT,
341                                8 /* bufferCount */),
342                             (status_t)OK);
343                    mAudioSink->start();
344
345                    mRenderer->signalAudioSinkChanged();
346                } else {
347                    // video
348
349                    int32_t width, height;
350                    CHECK(codecRequest->findInt32("width", &width));
351                    CHECK(codecRequest->findInt32("height", &height));
352
353                    int32_t cropLeft, cropTop, cropRight, cropBottom;
354                    CHECK(codecRequest->findRect(
355                                "crop",
356                                &cropLeft, &cropTop, &cropRight, &cropBottom));
357
358                    ALOGV("Video output format changed to %d x %d "
359                         "(crop: %d x %d @ (%d, %d))",
360                         width, height,
361                         (cropRight - cropLeft + 1),
362                         (cropBottom - cropTop + 1),
363                         cropLeft, cropTop);
364
365                    notifyListener(
366                            MEDIA_SET_VIDEO_SIZE,
367                            cropRight - cropLeft + 1,
368                            cropBottom - cropTop + 1);
369                }
370            } else if (what == ACodec::kWhatShutdownCompleted) {
371                ALOGV("%s shutdown completed", audio ? "audio" : "video");
372                if (audio) {
373                    mAudioDecoder.clear();
374
375                    CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER);
376                    mFlushingAudio = SHUT_DOWN;
377                } else {
378                    mVideoDecoder.clear();
379
380                    CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER);
381                    mFlushingVideo = SHUT_DOWN;
382                }
383
384                finishFlushIfPossible();
385            } else if (what == ACodec::kWhatError) {
386                LOGE("Received error from %s decoder, aborting playback.",
387                     audio ? "audio" : "video");
388
389                mRenderer->queueEOS(audio, UNKNOWN_ERROR);
390            } else {
391                CHECK_EQ((int)what, (int)ACodec::kWhatDrainThisBuffer);
392
393                renderBuffer(audio, codecRequest);
394            }
395
396            break;
397        }
398
399        case kWhatRendererNotify:
400        {
401            int32_t what;
402            CHECK(msg->findInt32("what", &what));
403
404            if (what == Renderer::kWhatEOS) {
405                int32_t audio;
406                CHECK(msg->findInt32("audio", &audio));
407
408                int32_t finalResult;
409                CHECK(msg->findInt32("finalResult", &finalResult));
410
411                if (audio) {
412                    mAudioEOS = true;
413                } else {
414                    mVideoEOS = true;
415                }
416
417                if (finalResult == ERROR_END_OF_STREAM) {
418                    ALOGV("reached %s EOS", audio ? "audio" : "video");
419                } else {
420                    LOGE("%s track encountered an error (%d)",
421                         audio ? "audio" : "video", finalResult);
422
423                    notifyListener(
424                            MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, finalResult);
425                }
426
427                if ((mAudioEOS || mAudioDecoder == NULL)
428                        && (mVideoEOS || mVideoDecoder == NULL)) {
429                    notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
430                }
431            } else if (what == Renderer::kWhatPosition) {
432                int64_t positionUs;
433                CHECK(msg->findInt64("positionUs", &positionUs));
434
435                CHECK(msg->findInt64("videoLateByUs", &mVideoLateByUs));
436
437                if (mDriver != NULL) {
438                    sp<NuPlayerDriver> driver = mDriver.promote();
439                    if (driver != NULL) {
440                        driver->notifyPosition(positionUs);
441
442                        driver->notifyFrameStats(
443                                mNumFramesTotal, mNumFramesDropped);
444                    }
445                }
446            } else if (what == Renderer::kWhatFlushComplete) {
447                CHECK_EQ(what, (int32_t)Renderer::kWhatFlushComplete);
448
449                int32_t audio;
450                CHECK(msg->findInt32("audio", &audio));
451
452                ALOGV("renderer %s flush completed.", audio ? "audio" : "video");
453            }
454            break;
455        }
456
457        case kWhatMoreDataQueued:
458        {
459            break;
460        }
461
462        case kWhatReset:
463        {
464            ALOGV("kWhatReset");
465
466            if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
467                // We're currently flushing, postpone the reset until that's
468                // completed.
469
470                ALOGV("postponing reset");
471
472                mResetPostponed = true;
473                break;
474            }
475
476            if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
477                finishReset();
478                break;
479            }
480
481            mTimeDiscontinuityPending = true;
482
483            if (mAudioDecoder != NULL) {
484                flushDecoder(true /* audio */, true /* needShutdown */);
485            }
486
487            if (mVideoDecoder != NULL) {
488                flushDecoder(false /* audio */, true /* needShutdown */);
489            }
490
491            mResetInProgress = true;
492            break;
493        }
494
495        case kWhatSeek:
496        {
497            int64_t seekTimeUs;
498            CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
499
500            ALOGV("kWhatSeek seekTimeUs=%lld us (%.2f secs)",
501                 seekTimeUs, seekTimeUs / 1E6);
502
503            mSource->seekTo(seekTimeUs);
504
505            if (mDriver != NULL) {
506                sp<NuPlayerDriver> driver = mDriver.promote();
507                if (driver != NULL) {
508                    driver->notifySeekComplete();
509                }
510            }
511
512            break;
513        }
514
515        case kWhatPause:
516        {
517            CHECK(mRenderer != NULL);
518            mRenderer->pause();
519            break;
520        }
521
522        case kWhatResume:
523        {
524            CHECK(mRenderer != NULL);
525            mRenderer->resume();
526            break;
527        }
528
529        default:
530            TRESPASS();
531            break;
532    }
533}
534
535void NuPlayer::finishFlushIfPossible() {
536    if (mFlushingAudio != FLUSHED && mFlushingAudio != SHUT_DOWN) {
537        return;
538    }
539
540    if (mFlushingVideo != FLUSHED && mFlushingVideo != SHUT_DOWN) {
541        return;
542    }
543
544    ALOGV("both audio and video are flushed now.");
545
546    if (mTimeDiscontinuityPending) {
547        mRenderer->signalTimeDiscontinuity();
548        mTimeDiscontinuityPending = false;
549    }
550
551    if (mAudioDecoder != NULL) {
552        mAudioDecoder->signalResume();
553    }
554
555    if (mVideoDecoder != NULL) {
556        mVideoDecoder->signalResume();
557    }
558
559    mFlushingAudio = NONE;
560    mFlushingVideo = NONE;
561
562    if (mResetInProgress) {
563        ALOGV("reset completed");
564
565        mResetInProgress = false;
566        finishReset();
567    } else if (mResetPostponed) {
568        (new AMessage(kWhatReset, id()))->post();
569        mResetPostponed = false;
570    } else if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
571        postScanSources();
572    }
573}
574
575void NuPlayer::finishReset() {
576    CHECK(mAudioDecoder == NULL);
577    CHECK(mVideoDecoder == NULL);
578
579    ++mScanSourcesGeneration;
580    mScanSourcesPending = false;
581
582    mRenderer.clear();
583
584    if (mSource != NULL) {
585        mSource->stop();
586        mSource.clear();
587    }
588
589    if (mDriver != NULL) {
590        sp<NuPlayerDriver> driver = mDriver.promote();
591        if (driver != NULL) {
592            driver->notifyResetComplete();
593        }
594    }
595}
596
597void NuPlayer::postScanSources() {
598    if (mScanSourcesPending) {
599        return;
600    }
601
602    sp<AMessage> msg = new AMessage(kWhatScanSources, id());
603    msg->setInt32("generation", mScanSourcesGeneration);
604    msg->post();
605
606    mScanSourcesPending = true;
607}
608
609status_t NuPlayer::instantiateDecoder(bool audio, sp<Decoder> *decoder) {
610    if (*decoder != NULL) {
611        return OK;
612    }
613
614    sp<MetaData> meta = mSource->getFormat(audio);
615
616    if (meta == NULL) {
617        return -EWOULDBLOCK;
618    }
619
620    if (!audio) {
621        const char *mime;
622        CHECK(meta->findCString(kKeyMIMEType, &mime));
623        mVideoIsAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime);
624    }
625
626    sp<AMessage> notify =
627        new AMessage(audio ? kWhatAudioNotify : kWhatVideoNotify,
628                     id());
629
630    *decoder = audio ? new Decoder(notify) :
631                       new Decoder(notify, mNativeWindow);
632    looper()->registerHandler(*decoder);
633
634    (*decoder)->configure(meta);
635
636    int64_t durationUs;
637    if (mDriver != NULL && mSource->getDuration(&durationUs) == OK) {
638        sp<NuPlayerDriver> driver = mDriver.promote();
639        if (driver != NULL) {
640            driver->notifyDuration(durationUs);
641        }
642    }
643
644    return OK;
645}
646
647status_t NuPlayer::feedDecoderInputData(bool audio, const sp<AMessage> &msg) {
648    sp<AMessage> reply;
649    CHECK(msg->findMessage("reply", &reply));
650
651    if ((audio && IsFlushingState(mFlushingAudio))
652            || (!audio && IsFlushingState(mFlushingVideo))) {
653        reply->setInt32("err", INFO_DISCONTINUITY);
654        reply->post();
655        return OK;
656    }
657
658    sp<ABuffer> accessUnit;
659
660    bool dropAccessUnit;
661    do {
662        status_t err = mSource->dequeueAccessUnit(audio, &accessUnit);
663
664        if (err == -EWOULDBLOCK) {
665            return err;
666        } else if (err != OK) {
667            if (err == INFO_DISCONTINUITY) {
668                int32_t type;
669                CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
670
671                bool formatChange =
672                    (audio &&
673                     (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
674                    || (!audio &&
675                            (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
676
677                bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
678
679                LOGI("%s discontinuity (formatChange=%d, time=%d)",
680                     audio ? "audio" : "video", formatChange, timeChange);
681
682                if (audio) {
683                    mSkipRenderingAudioUntilMediaTimeUs = -1;
684                } else {
685                    mSkipRenderingVideoUntilMediaTimeUs = -1;
686                }
687
688                if (timeChange) {
689                    sp<AMessage> extra;
690                    if (accessUnit->meta()->findMessage("extra", &extra)
691                            && extra != NULL) {
692                        int64_t resumeAtMediaTimeUs;
693                        if (extra->findInt64(
694                                    "resume-at-mediatimeUs", &resumeAtMediaTimeUs)) {
695                            LOGI("suppressing rendering of %s until %lld us",
696                                    audio ? "audio" : "video", resumeAtMediaTimeUs);
697
698                            if (audio) {
699                                mSkipRenderingAudioUntilMediaTimeUs =
700                                    resumeAtMediaTimeUs;
701                            } else {
702                                mSkipRenderingVideoUntilMediaTimeUs =
703                                    resumeAtMediaTimeUs;
704                            }
705                        }
706                    }
707                }
708
709                mTimeDiscontinuityPending =
710                    mTimeDiscontinuityPending || timeChange;
711
712                if (formatChange || timeChange) {
713                    flushDecoder(audio, formatChange);
714                } else {
715                    // This stream is unaffected by the discontinuity
716
717                    if (audio) {
718                        mFlushingAudio = FLUSHED;
719                    } else {
720                        mFlushingVideo = FLUSHED;
721                    }
722
723                    finishFlushIfPossible();
724
725                    return -EWOULDBLOCK;
726                }
727            }
728
729            reply->setInt32("err", err);
730            reply->post();
731            return OK;
732        }
733
734        if (!audio) {
735            ++mNumFramesTotal;
736        }
737
738        dropAccessUnit = false;
739        if (!audio
740                && mVideoLateByUs > 100000ll
741                && mVideoIsAVC
742                && !IsAVCReferenceFrame(accessUnit)) {
743            dropAccessUnit = true;
744            ++mNumFramesDropped;
745        }
746    } while (dropAccessUnit);
747
748    // ALOGV("returned a valid buffer of %s data", audio ? "audio" : "video");
749
750#if 0
751    int64_t mediaTimeUs;
752    CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
753    ALOGV("feeding %s input buffer at media time %.2f secs",
754         audio ? "audio" : "video",
755         mediaTimeUs / 1E6);
756#endif
757
758    reply->setObject("buffer", accessUnit);
759    reply->post();
760
761    return OK;
762}
763
764void NuPlayer::renderBuffer(bool audio, const sp<AMessage> &msg) {
765    // ALOGV("renderBuffer %s", audio ? "audio" : "video");
766
767    sp<AMessage> reply;
768    CHECK(msg->findMessage("reply", &reply));
769
770    if (IsFlushingState(audio ? mFlushingAudio : mFlushingVideo)) {
771        // We're currently attempting to flush the decoder, in order
772        // to complete this, the decoder wants all its buffers back,
773        // so we don't want any output buffers it sent us (from before
774        // we initiated the flush) to be stuck in the renderer's queue.
775
776        ALOGV("we're still flushing the %s decoder, sending its output buffer"
777             " right back.", audio ? "audio" : "video");
778
779        reply->post();
780        return;
781    }
782
783    sp<RefBase> obj;
784    CHECK(msg->findObject("buffer", &obj));
785
786    sp<ABuffer> buffer = static_cast<ABuffer *>(obj.get());
787
788    int64_t &skipUntilMediaTimeUs =
789        audio
790            ? mSkipRenderingAudioUntilMediaTimeUs
791            : mSkipRenderingVideoUntilMediaTimeUs;
792
793    if (skipUntilMediaTimeUs >= 0) {
794        int64_t mediaTimeUs;
795        CHECK(buffer->meta()->findInt64("timeUs", &mediaTimeUs));
796
797        if (mediaTimeUs < skipUntilMediaTimeUs) {
798            ALOGV("dropping %s buffer at time %lld as requested.",
799                 audio ? "audio" : "video",
800                 mediaTimeUs);
801
802            reply->post();
803            return;
804        }
805
806        skipUntilMediaTimeUs = -1;
807    }
808
809    mRenderer->queueBuffer(audio, buffer, reply);
810}
811
812void NuPlayer::notifyListener(int msg, int ext1, int ext2) {
813    if (mDriver == NULL) {
814        return;
815    }
816
817    sp<NuPlayerDriver> driver = mDriver.promote();
818
819    if (driver == NULL) {
820        return;
821    }
822
823    driver->notifyListener(msg, ext1, ext2);
824}
825
826void NuPlayer::flushDecoder(bool audio, bool needShutdown) {
827    if ((audio && mAudioDecoder == NULL) || (!audio && mVideoDecoder == NULL)) {
828        LOGI("flushDecoder %s without decoder present",
829             audio ? "audio" : "video");
830    }
831
832    // Make sure we don't continue to scan sources until we finish flushing.
833    ++mScanSourcesGeneration;
834    mScanSourcesPending = false;
835
836    (audio ? mAudioDecoder : mVideoDecoder)->signalFlush();
837    mRenderer->flush(audio);
838
839    FlushStatus newStatus =
840        needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;
841
842    if (audio) {
843        CHECK(mFlushingAudio == NONE
844                || mFlushingAudio == AWAITING_DISCONTINUITY);
845
846        mFlushingAudio = newStatus;
847
848        if (mFlushingVideo == NONE) {
849            mFlushingVideo = (mVideoDecoder != NULL)
850                ? AWAITING_DISCONTINUITY
851                : FLUSHED;
852        }
853    } else {
854        CHECK(mFlushingVideo == NONE
855                || mFlushingVideo == AWAITING_DISCONTINUITY);
856
857        mFlushingVideo = newStatus;
858
859        if (mFlushingAudio == NONE) {
860            mFlushingAudio = (mAudioDecoder != NULL)
861                ? AWAITING_DISCONTINUITY
862                : FLUSHED;
863        }
864    }
865}
866
867}  // namespace android
868