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