NuPlayer.cpp revision afed0e1fa37473a4cd30018577b560acc79d9a3f
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            instantiateDecoder(false, &mVideoDecoder);
262
263            if (mAudioSink != NULL) {
264                instantiateDecoder(true, &mAudioDecoder);
265            }
266
267            status_t err;
268            if ((err = mSource->feedMoreTSData()) != OK) {
269                if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
270                    // We're not currently decoding anything (no audio or
271                    // video tracks found) and we just ran out of input data.
272
273                    if (err == ERROR_END_OF_STREAM) {
274                        notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
275                    } else {
276                        notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
277                    }
278                }
279                break;
280            }
281
282            if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
283                msg->post(100000ll);
284                mScanSourcesPending = true;
285            }
286            break;
287        }
288
289        case kWhatVideoNotify:
290        case kWhatAudioNotify:
291        {
292            bool audio = msg->what() == kWhatAudioNotify;
293
294            sp<AMessage> codecRequest;
295            CHECK(msg->findMessage("codec-request", &codecRequest));
296
297            int32_t what;
298            CHECK(codecRequest->findInt32("what", &what));
299
300            if (what == ACodec::kWhatFillThisBuffer) {
301                status_t err = feedDecoderInputData(
302                        audio, codecRequest);
303
304                if (err == -EWOULDBLOCK) {
305                    if (mSource->feedMoreTSData() == OK) {
306                        msg->post(10000ll);
307                    }
308                }
309            } else if (what == ACodec::kWhatEOS) {
310                int32_t err;
311                CHECK(codecRequest->findInt32("err", &err));
312
313                if (err == ERROR_END_OF_STREAM) {
314                    ALOGV("got %s decoder EOS", audio ? "audio" : "video");
315                } else {
316                    ALOGV("got %s decoder EOS w/ error %d",
317                         audio ? "audio" : "video",
318                         err);
319                }
320
321                mRenderer->queueEOS(audio, err);
322            } else if (what == ACodec::kWhatFlushCompleted) {
323                bool needShutdown;
324
325                if (audio) {
326                    CHECK(IsFlushingState(mFlushingAudio, &needShutdown));
327                    mFlushingAudio = FLUSHED;
328                } else {
329                    CHECK(IsFlushingState(mFlushingVideo, &needShutdown));
330                    mFlushingVideo = FLUSHED;
331
332                    mVideoLateByUs = 0;
333                }
334
335                ALOGV("decoder %s flush completed", audio ? "audio" : "video");
336
337                if (needShutdown) {
338                    ALOGV("initiating %s decoder shutdown",
339                         audio ? "audio" : "video");
340
341                    (audio ? mAudioDecoder : mVideoDecoder)->initiateShutdown();
342
343                    if (audio) {
344                        mFlushingAudio = SHUTTING_DOWN_DECODER;
345                    } else {
346                        mFlushingVideo = SHUTTING_DOWN_DECODER;
347                    }
348                }
349
350                finishFlushIfPossible();
351            } else if (what == ACodec::kWhatOutputFormatChanged) {
352                if (audio) {
353                    int32_t numChannels;
354                    CHECK(codecRequest->findInt32("channel-count", &numChannels));
355
356                    int32_t sampleRate;
357                    CHECK(codecRequest->findInt32("sample-rate", &sampleRate));
358
359                    ALOGV("Audio output format changed to %d Hz, %d channels",
360                         sampleRate, numChannels);
361
362                    mAudioSink->close();
363                    CHECK_EQ(mAudioSink->open(
364                                sampleRate,
365                                numChannels,
366                                CHANNEL_MASK_USE_CHANNEL_ORDER,
367                                AUDIO_FORMAT_PCM_16_BIT,
368                                8 /* bufferCount */),
369                             (status_t)OK);
370                    mAudioSink->start();
371
372                    mRenderer->signalAudioSinkChanged();
373                } else {
374                    // video
375
376                    int32_t width, height;
377                    CHECK(codecRequest->findInt32("width", &width));
378                    CHECK(codecRequest->findInt32("height", &height));
379
380                    int32_t cropLeft, cropTop, cropRight, cropBottom;
381                    CHECK(codecRequest->findRect(
382                                "crop",
383                                &cropLeft, &cropTop, &cropRight, &cropBottom));
384
385                    ALOGV("Video output format changed to %d x %d "
386                         "(crop: %d x %d @ (%d, %d))",
387                         width, height,
388                         (cropRight - cropLeft + 1),
389                         (cropBottom - cropTop + 1),
390                         cropLeft, cropTop);
391
392                    notifyListener(
393                            MEDIA_SET_VIDEO_SIZE,
394                            cropRight - cropLeft + 1,
395                            cropBottom - cropTop + 1);
396                }
397            } else if (what == ACodec::kWhatShutdownCompleted) {
398                ALOGV("%s shutdown completed", audio ? "audio" : "video");
399                if (audio) {
400                    mAudioDecoder.clear();
401
402                    CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER);
403                    mFlushingAudio = SHUT_DOWN;
404                } else {
405                    mVideoDecoder.clear();
406
407                    CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER);
408                    mFlushingVideo = SHUT_DOWN;
409                }
410
411                finishFlushIfPossible();
412            } else if (what == ACodec::kWhatError) {
413                ALOGE("Received error from %s decoder, aborting playback.",
414                     audio ? "audio" : "video");
415
416                mRenderer->queueEOS(audio, UNKNOWN_ERROR);
417            } else if (what == ACodec::kWhatDrainThisBuffer) {
418                renderBuffer(audio, codecRequest);
419            } else {
420                ALOGV("Unhandled codec notification %d.", what);
421            }
422
423            break;
424        }
425
426        case kWhatRendererNotify:
427        {
428            int32_t what;
429            CHECK(msg->findInt32("what", &what));
430
431            if (what == Renderer::kWhatEOS) {
432                int32_t audio;
433                CHECK(msg->findInt32("audio", &audio));
434
435                int32_t finalResult;
436                CHECK(msg->findInt32("finalResult", &finalResult));
437
438                if (audio) {
439                    mAudioEOS = true;
440                } else {
441                    mVideoEOS = true;
442                }
443
444                if (finalResult == ERROR_END_OF_STREAM) {
445                    ALOGV("reached %s EOS", audio ? "audio" : "video");
446                } else {
447                    ALOGE("%s track encountered an error (%d)",
448                         audio ? "audio" : "video", finalResult);
449
450                    notifyListener(
451                            MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, finalResult);
452                }
453
454                if ((mAudioEOS || mAudioDecoder == NULL)
455                        && (mVideoEOS || mVideoDecoder == NULL)) {
456                    notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
457                }
458            } else if (what == Renderer::kWhatPosition) {
459                int64_t positionUs;
460                CHECK(msg->findInt64("positionUs", &positionUs));
461
462                CHECK(msg->findInt64("videoLateByUs", &mVideoLateByUs));
463
464                if (mDriver != NULL) {
465                    sp<NuPlayerDriver> driver = mDriver.promote();
466                    if (driver != NULL) {
467                        driver->notifyPosition(positionUs);
468
469                        driver->notifyFrameStats(
470                                mNumFramesTotal, mNumFramesDropped);
471                    }
472                }
473            } else if (what == Renderer::kWhatFlushComplete) {
474                CHECK_EQ(what, (int32_t)Renderer::kWhatFlushComplete);
475
476                int32_t audio;
477                CHECK(msg->findInt32("audio", &audio));
478
479                ALOGV("renderer %s flush completed.", audio ? "audio" : "video");
480            }
481            break;
482        }
483
484        case kWhatMoreDataQueued:
485        {
486            break;
487        }
488
489        case kWhatReset:
490        {
491            ALOGV("kWhatReset");
492
493            if (mRenderer != NULL) {
494                // There's an edge case where the renderer owns all output
495                // buffers and is paused, therefore the decoder will not read
496                // more input data and will never encounter the matching
497                // discontinuity. To avoid this, we resume the renderer.
498
499                if (mFlushingAudio == AWAITING_DISCONTINUITY
500                        || mFlushingVideo == AWAITING_DISCONTINUITY) {
501                    mRenderer->resume();
502                }
503            }
504
505            if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
506                // We're currently flushing, postpone the reset until that's
507                // completed.
508
509                ALOGV("postponing reset mFlushingAudio=%d, mFlushingVideo=%d",
510                      mFlushingAudio, mFlushingVideo);
511
512                mResetPostponed = true;
513                break;
514            }
515
516            if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
517                finishReset();
518                break;
519            }
520
521            mTimeDiscontinuityPending = true;
522
523            if (mAudioDecoder != NULL) {
524                flushDecoder(true /* audio */, true /* needShutdown */);
525            }
526
527            if (mVideoDecoder != NULL) {
528                flushDecoder(false /* audio */, true /* needShutdown */);
529            }
530
531            mResetInProgress = true;
532            break;
533        }
534
535        case kWhatSeek:
536        {
537            int64_t seekTimeUs;
538            CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
539
540            ALOGV("kWhatSeek seekTimeUs=%lld us (%.2f secs)",
541                 seekTimeUs, seekTimeUs / 1E6);
542
543            mSource->seekTo(seekTimeUs);
544
545            if (mDriver != NULL) {
546                sp<NuPlayerDriver> driver = mDriver.promote();
547                if (driver != NULL) {
548                    driver->notifySeekComplete();
549                }
550            }
551
552            break;
553        }
554
555        case kWhatPause:
556        {
557            CHECK(mRenderer != NULL);
558            mRenderer->pause();
559            break;
560        }
561
562        case kWhatResume:
563        {
564            CHECK(mRenderer != NULL);
565            mRenderer->resume();
566            break;
567        }
568
569        default:
570            TRESPASS();
571            break;
572    }
573}
574
575void NuPlayer::finishFlushIfPossible() {
576    if (mFlushingAudio != FLUSHED && mFlushingAudio != SHUT_DOWN) {
577        return;
578    }
579
580    if (mFlushingVideo != FLUSHED && mFlushingVideo != SHUT_DOWN) {
581        return;
582    }
583
584    ALOGV("both audio and video are flushed now.");
585
586    if (mTimeDiscontinuityPending) {
587        mRenderer->signalTimeDiscontinuity();
588        mTimeDiscontinuityPending = false;
589    }
590
591    if (mAudioDecoder != NULL) {
592        mAudioDecoder->signalResume();
593    }
594
595    if (mVideoDecoder != NULL) {
596        mVideoDecoder->signalResume();
597    }
598
599    mFlushingAudio = NONE;
600    mFlushingVideo = NONE;
601
602    if (mResetInProgress) {
603        ALOGV("reset completed");
604
605        mResetInProgress = false;
606        finishReset();
607    } else if (mResetPostponed) {
608        (new AMessage(kWhatReset, id()))->post();
609        mResetPostponed = false;
610    } else if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
611        postScanSources();
612    }
613}
614
615void NuPlayer::finishReset() {
616    CHECK(mAudioDecoder == NULL);
617    CHECK(mVideoDecoder == NULL);
618
619    ++mScanSourcesGeneration;
620    mScanSourcesPending = false;
621
622    mRenderer.clear();
623
624    if (mSource != NULL) {
625        mSource->stop();
626        mSource.clear();
627    }
628
629    if (mDriver != NULL) {
630        sp<NuPlayerDriver> driver = mDriver.promote();
631        if (driver != NULL) {
632            driver->notifyResetComplete();
633        }
634    }
635}
636
637void NuPlayer::postScanSources() {
638    if (mScanSourcesPending) {
639        return;
640    }
641
642    sp<AMessage> msg = new AMessage(kWhatScanSources, id());
643    msg->setInt32("generation", mScanSourcesGeneration);
644    msg->post();
645
646    mScanSourcesPending = true;
647}
648
649status_t NuPlayer::instantiateDecoder(bool audio, sp<Decoder> *decoder) {
650    if (*decoder != NULL) {
651        return OK;
652    }
653
654    sp<MetaData> meta = mSource->getFormat(audio);
655
656    if (meta == NULL) {
657        return -EWOULDBLOCK;
658    }
659
660    if (!audio) {
661        const char *mime;
662        CHECK(meta->findCString(kKeyMIMEType, &mime));
663        mVideoIsAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime);
664    }
665
666    sp<AMessage> notify =
667        new AMessage(audio ? kWhatAudioNotify : kWhatVideoNotify,
668                     id());
669
670    *decoder = audio ? new Decoder(notify) :
671                       new Decoder(notify, mNativeWindow);
672    looper()->registerHandler(*decoder);
673
674    (*decoder)->configure(meta);
675
676    int64_t durationUs;
677    if (mDriver != NULL && mSource->getDuration(&durationUs) == OK) {
678        sp<NuPlayerDriver> driver = mDriver.promote();
679        if (driver != NULL) {
680            driver->notifyDuration(durationUs);
681        }
682    }
683
684    return OK;
685}
686
687status_t NuPlayer::feedDecoderInputData(bool audio, const sp<AMessage> &msg) {
688    sp<AMessage> reply;
689    CHECK(msg->findMessage("reply", &reply));
690
691    if ((audio && IsFlushingState(mFlushingAudio))
692            || (!audio && IsFlushingState(mFlushingVideo))) {
693        reply->setInt32("err", INFO_DISCONTINUITY);
694        reply->post();
695        return OK;
696    }
697
698    sp<ABuffer> accessUnit;
699
700    bool dropAccessUnit;
701    do {
702        status_t err = mSource->dequeueAccessUnit(audio, &accessUnit);
703
704        if (err == -EWOULDBLOCK) {
705            return err;
706        } else if (err != OK) {
707            if (err == INFO_DISCONTINUITY) {
708                int32_t type;
709                CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
710
711                bool formatChange =
712                    (audio &&
713                     (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
714                    || (!audio &&
715                            (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
716
717                bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
718
719                ALOGI("%s discontinuity (formatChange=%d, time=%d)",
720                     audio ? "audio" : "video", formatChange, timeChange);
721
722                if (audio) {
723                    mSkipRenderingAudioUntilMediaTimeUs = -1;
724                } else {
725                    mSkipRenderingVideoUntilMediaTimeUs = -1;
726                }
727
728                if (timeChange) {
729                    sp<AMessage> extra;
730                    if (accessUnit->meta()->findMessage("extra", &extra)
731                            && extra != NULL) {
732                        int64_t resumeAtMediaTimeUs;
733                        if (extra->findInt64(
734                                    "resume-at-mediatimeUs", &resumeAtMediaTimeUs)) {
735                            ALOGI("suppressing rendering of %s until %lld us",
736                                    audio ? "audio" : "video", resumeAtMediaTimeUs);
737
738                            if (audio) {
739                                mSkipRenderingAudioUntilMediaTimeUs =
740                                    resumeAtMediaTimeUs;
741                            } else {
742                                mSkipRenderingVideoUntilMediaTimeUs =
743                                    resumeAtMediaTimeUs;
744                            }
745                        }
746                    }
747                }
748
749                mTimeDiscontinuityPending =
750                    mTimeDiscontinuityPending || timeChange;
751
752                if (formatChange || timeChange) {
753                    flushDecoder(audio, formatChange);
754                } else {
755                    // This stream is unaffected by the discontinuity
756
757                    if (audio) {
758                        mFlushingAudio = FLUSHED;
759                    } else {
760                        mFlushingVideo = FLUSHED;
761                    }
762
763                    finishFlushIfPossible();
764
765                    return -EWOULDBLOCK;
766                }
767            }
768
769            reply->setInt32("err", err);
770            reply->post();
771            return OK;
772        }
773
774        if (!audio) {
775            ++mNumFramesTotal;
776        }
777
778        dropAccessUnit = false;
779        if (!audio
780                && mVideoLateByUs > 100000ll
781                && mVideoIsAVC
782                && !IsAVCReferenceFrame(accessUnit)) {
783            dropAccessUnit = true;
784            ++mNumFramesDropped;
785        }
786    } while (dropAccessUnit);
787
788    // ALOGV("returned a valid buffer of %s data", audio ? "audio" : "video");
789
790#if 0
791    int64_t mediaTimeUs;
792    CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
793    ALOGV("feeding %s input buffer at media time %.2f secs",
794         audio ? "audio" : "video",
795         mediaTimeUs / 1E6);
796#endif
797
798    reply->setBuffer("buffer", accessUnit);
799    reply->post();
800
801    return OK;
802}
803
804void NuPlayer::renderBuffer(bool audio, const sp<AMessage> &msg) {
805    // ALOGV("renderBuffer %s", audio ? "audio" : "video");
806
807    sp<AMessage> reply;
808    CHECK(msg->findMessage("reply", &reply));
809
810    if (IsFlushingState(audio ? mFlushingAudio : mFlushingVideo)) {
811        // We're currently attempting to flush the decoder, in order
812        // to complete this, the decoder wants all its buffers back,
813        // so we don't want any output buffers it sent us (from before
814        // we initiated the flush) to be stuck in the renderer's queue.
815
816        ALOGV("we're still flushing the %s decoder, sending its output buffer"
817             " right back.", audio ? "audio" : "video");
818
819        reply->post();
820        return;
821    }
822
823    sp<ABuffer> buffer;
824    CHECK(msg->findBuffer("buffer", &buffer));
825
826    int64_t &skipUntilMediaTimeUs =
827        audio
828            ? mSkipRenderingAudioUntilMediaTimeUs
829            : mSkipRenderingVideoUntilMediaTimeUs;
830
831    if (skipUntilMediaTimeUs >= 0) {
832        int64_t mediaTimeUs;
833        CHECK(buffer->meta()->findInt64("timeUs", &mediaTimeUs));
834
835        if (mediaTimeUs < skipUntilMediaTimeUs) {
836            ALOGV("dropping %s buffer at time %lld as requested.",
837                 audio ? "audio" : "video",
838                 mediaTimeUs);
839
840            reply->post();
841            return;
842        }
843
844        skipUntilMediaTimeUs = -1;
845    }
846
847    mRenderer->queueBuffer(audio, buffer, reply);
848}
849
850void NuPlayer::notifyListener(int msg, int ext1, int ext2) {
851    if (mDriver == NULL) {
852        return;
853    }
854
855    sp<NuPlayerDriver> driver = mDriver.promote();
856
857    if (driver == NULL) {
858        return;
859    }
860
861    driver->notifyListener(msg, ext1, ext2);
862}
863
864void NuPlayer::flushDecoder(bool audio, bool needShutdown) {
865    if ((audio && mAudioDecoder == NULL) || (!audio && mVideoDecoder == NULL)) {
866        ALOGI("flushDecoder %s without decoder present",
867             audio ? "audio" : "video");
868    }
869
870    // Make sure we don't continue to scan sources until we finish flushing.
871    ++mScanSourcesGeneration;
872    mScanSourcesPending = false;
873
874    (audio ? mAudioDecoder : mVideoDecoder)->signalFlush();
875    mRenderer->flush(audio);
876
877    FlushStatus newStatus =
878        needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;
879
880    if (audio) {
881        CHECK(mFlushingAudio == NONE
882                || mFlushingAudio == AWAITING_DISCONTINUITY);
883
884        mFlushingAudio = newStatus;
885
886        if (mFlushingVideo == NONE) {
887            mFlushingVideo = (mVideoDecoder != NULL)
888                ? AWAITING_DISCONTINUITY
889                : FLUSHED;
890        }
891    } else {
892        CHECK(mFlushingVideo == NONE
893                || mFlushingVideo == AWAITING_DISCONTINUITY);
894
895        mFlushingVideo = newStatus;
896
897        if (mFlushingAudio == NONE) {
898            mFlushingAudio = (mAudioDecoder != NULL)
899                ? AWAITING_DISCONTINUITY
900                : FLUSHED;
901        }
902    }
903}
904
905}  // namespace android
906