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