NuPlayerDecoder.cpp revision 43cc944ecdc1634dccd92a1aad559f0caa13b53c
1/*
2 * Copyright 2014 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 "NuPlayerDecoder"
19#include <utils/Log.h>
20#include <inttypes.h>
21
22#include "NuPlayerCCDecoder.h"
23#include "NuPlayerDecoder.h"
24#include "NuPlayerRenderer.h"
25#include "NuPlayerSource.h"
26
27#include <media/ICrypto.h>
28#include <media/stagefright/foundation/ABuffer.h>
29#include <media/stagefright/foundation/ADebug.h>
30#include <media/stagefright/foundation/AMessage.h>
31#include <media/stagefright/MediaBuffer.h>
32#include <media/stagefright/MediaCodec.h>
33#include <media/stagefright/MediaDefs.h>
34#include <media/stagefright/MediaErrors.h>
35
36#include "avc_utils.h"
37#include "ATSParser.h"
38
39namespace android {
40
41NuPlayer::Decoder::Decoder(
42        const sp<AMessage> &notify,
43        const sp<Source> &source,
44        const sp<Renderer> &renderer,
45        const sp<NativeWindowWrapper> &nativeWindow,
46        const sp<CCDecoder> &ccDecoder)
47    : DecoderBase(notify),
48      mNativeWindow(nativeWindow),
49      mSource(source),
50      mRenderer(renderer),
51      mCCDecoder(ccDecoder),
52      mSkipRenderingUntilMediaTimeUs(-1ll),
53      mNumFramesTotal(0ll),
54      mNumFramesDropped(0ll),
55      mIsAudio(true),
56      mIsVideoAVC(false),
57      mIsSecure(false),
58      mFormatChangePending(false),
59      mTimeChangePending(false),
60      mPaused(true),
61      mResumePending(false),
62      mComponentName("decoder") {
63    mCodecLooper = new ALooper;
64    mCodecLooper->setName("NPDecoder-CL");
65    mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
66}
67
68NuPlayer::Decoder::~Decoder() {
69    releaseAndResetMediaBuffers();
70}
71
72void NuPlayer::Decoder::getStats(
73        int64_t *numFramesTotal,
74        int64_t *numFramesDropped) const {
75    *numFramesTotal = mNumFramesTotal;
76    *numFramesDropped = mNumFramesDropped;
77}
78
79void NuPlayer::Decoder::onMessageReceived(const sp<AMessage> &msg) {
80    ALOGV("[%s] onMessage: %s", mComponentName.c_str(), msg->debugString().c_str());
81
82    switch (msg->what()) {
83        case kWhatCodecNotify:
84        {
85            if (mPaused) {
86                break;
87            }
88
89            int32_t cbID;
90            CHECK(msg->findInt32("callbackID", &cbID));
91
92            ALOGV("kWhatCodecNotify: cbID = %d", cbID);
93            switch (cbID) {
94                case MediaCodec::CB_INPUT_AVAILABLE:
95                {
96                    int32_t index;
97                    CHECK(msg->findInt32("index", &index));
98
99                    handleAnInputBuffer(index);
100                    break;
101                }
102
103                case MediaCodec::CB_OUTPUT_AVAILABLE:
104                {
105                    int32_t index;
106                    size_t offset;
107                    size_t size;
108                    int64_t timeUs;
109                    int32_t flags;
110
111                    CHECK(msg->findInt32("index", &index));
112                    CHECK(msg->findSize("offset", &offset));
113                    CHECK(msg->findSize("size", &size));
114                    CHECK(msg->findInt64("timeUs", &timeUs));
115                    CHECK(msg->findInt32("flags", &flags));
116
117                    handleAnOutputBuffer(index, offset, size, timeUs, flags);
118                    break;
119                }
120
121                case MediaCodec::CB_OUTPUT_FORMAT_CHANGED:
122                {
123                    sp<AMessage> format;
124                    CHECK(msg->findMessage("format", &format));
125
126                    handleOutputFormatChange(format);
127                    break;
128                }
129
130                case MediaCodec::CB_ERROR:
131                {
132                    status_t err;
133                    CHECK(msg->findInt32("err", &err));
134                    ALOGE("Decoder (%s) reported error : 0x%x",
135                            mIsAudio ? "audio" : "video", err);
136
137                    handleError(err);
138                    break;
139                }
140
141                default:
142                {
143                    TRESPASS();
144                    break;
145                }
146            }
147
148            break;
149        }
150
151        case kWhatRenderBuffer:
152        {
153            if (!isStaleReply(msg)) {
154                onRenderBuffer(msg);
155            }
156            break;
157        }
158
159        default:
160            DecoderBase::onMessageReceived(msg);
161            break;
162    }
163}
164
165void NuPlayer::Decoder::onConfigure(const sp<AMessage> &format) {
166    CHECK(mCodec == NULL);
167
168    mFormatChangePending = false;
169    mTimeChangePending = false;
170
171    ++mBufferGeneration;
172
173    AString mime;
174    CHECK(format->findString("mime", &mime));
175
176    mIsAudio = !strncasecmp("audio/", mime.c_str(), 6);
177    mIsVideoAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
178
179    sp<Surface> surface = NULL;
180    if (mNativeWindow != NULL) {
181        surface = mNativeWindow->getSurfaceTextureClient();
182    }
183
184    mComponentName = mime;
185    mComponentName.append(" decoder");
186    ALOGV("[%s] onConfigure (surface=%p)", mComponentName.c_str(), surface.get());
187
188    mCodec = MediaCodec::CreateByType(mCodecLooper, mime.c_str(), false /* encoder */);
189    int32_t secure = 0;
190    if (format->findInt32("secure", &secure) && secure != 0) {
191        if (mCodec != NULL) {
192            mCodec->getName(&mComponentName);
193            mComponentName.append(".secure");
194            mCodec->release();
195            ALOGI("[%s] creating", mComponentName.c_str());
196            mCodec = MediaCodec::CreateByComponentName(
197                    mCodecLooper, mComponentName.c_str());
198        }
199    }
200    if (mCodec == NULL) {
201        ALOGE("Failed to create %s%s decoder",
202                (secure ? "secure " : ""), mime.c_str());
203        handleError(UNKNOWN_ERROR);
204        return;
205    }
206    mIsSecure = secure;
207
208    mCodec->getName(&mComponentName);
209
210    status_t err;
211    if (mNativeWindow != NULL) {
212        // disconnect from surface as MediaCodec will reconnect
213        err = native_window_api_disconnect(
214                surface.get(), NATIVE_WINDOW_API_MEDIA);
215        // We treat this as a warning, as this is a preparatory step.
216        // Codec will try to connect to the surface, which is where
217        // any error signaling will occur.
218        ALOGW_IF(err != OK, "failed to disconnect from surface: %d", err);
219    }
220    err = mCodec->configure(
221            format, surface, NULL /* crypto */, 0 /* flags */);
222    if (err != OK) {
223        ALOGE("Failed to configure %s decoder (err=%d)", mComponentName.c_str(), err);
224        mCodec->release();
225        mCodec.clear();
226        handleError(err);
227        return;
228    }
229    rememberCodecSpecificData(format);
230
231    // the following should work in configured state
232    CHECK_EQ((status_t)OK, mCodec->getOutputFormat(&mOutputFormat));
233    CHECK_EQ((status_t)OK, mCodec->getInputFormat(&mInputFormat));
234
235    sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
236    mCodec->setCallback(reply);
237
238    err = mCodec->start();
239    if (err != OK) {
240        ALOGE("Failed to start %s decoder (err=%d)", mComponentName.c_str(), err);
241        mCodec->release();
242        mCodec.clear();
243        handleError(err);
244        return;
245    }
246
247    releaseAndResetMediaBuffers();
248
249    mPaused = false;
250    mResumePending = false;
251}
252
253void NuPlayer::Decoder::onSetRenderer(const sp<Renderer> &renderer) {
254    bool hadNoRenderer = (mRenderer == NULL);
255    mRenderer = renderer;
256    if (hadNoRenderer && mRenderer != NULL) {
257        // this means that the widevine legacy source is ready
258        onRequestInputBuffers();
259    }
260}
261
262void NuPlayer::Decoder::onGetInputBuffers(
263        Vector<sp<ABuffer> > *dstBuffers) {
264    CHECK_EQ((status_t)OK, mCodec->getWidevineLegacyBuffers(dstBuffers));
265}
266
267void NuPlayer::Decoder::onResume(bool notifyComplete) {
268    mPaused = false;
269
270    if (notifyComplete) {
271        mResumePending = true;
272    }
273    mCodec->start();
274}
275
276void NuPlayer::Decoder::doFlush(bool notifyComplete) {
277    if (mCCDecoder != NULL) {
278        mCCDecoder->flush();
279    }
280
281    if (mRenderer != NULL) {
282        mRenderer->flush(mIsAudio, notifyComplete);
283        mRenderer->signalTimeDiscontinuity();
284    }
285
286    status_t err = OK;
287    if (mCodec != NULL) {
288        err = mCodec->flush();
289        mCSDsToSubmit = mCSDsForCurrentFormat; // copy operator
290        ++mBufferGeneration;
291    }
292
293    if (err != OK) {
294        ALOGE("failed to flush %s (err=%d)", mComponentName.c_str(), err);
295        handleError(err);
296        // finish with posting kWhatFlushCompleted.
297        // we attempt to release the buffers even if flush fails.
298    }
299    releaseAndResetMediaBuffers();
300    mPaused = true;
301}
302
303
304void NuPlayer::Decoder::onFlush() {
305    doFlush(true);
306
307    if (isDiscontinuityPending()) {
308        // This could happen if the client starts seeking/shutdown
309        // after we queued an EOS for discontinuities.
310        // We can consider discontinuity handled.
311        finishHandleDiscontinuity(false /* flushOnTimeChange */);
312    }
313
314    sp<AMessage> notify = mNotify->dup();
315    notify->setInt32("what", kWhatFlushCompleted);
316    notify->post();
317}
318
319void NuPlayer::Decoder::onShutdown(bool notifyComplete) {
320    status_t err = OK;
321
322    // if there is a pending resume request, notify complete now
323    notifyResumeCompleteIfNecessary();
324
325    if (mCodec != NULL) {
326        err = mCodec->release();
327        mCodec = NULL;
328        ++mBufferGeneration;
329
330        if (mNativeWindow != NULL) {
331            // reconnect to surface as MediaCodec disconnected from it
332            status_t error =
333                    native_window_api_connect(
334                            mNativeWindow->getNativeWindow().get(),
335                            NATIVE_WINDOW_API_MEDIA);
336            ALOGW_IF(error != NO_ERROR,
337                    "[%s] failed to connect to native window, error=%d",
338                    mComponentName.c_str(), error);
339        }
340        mComponentName = "decoder";
341    }
342
343    releaseAndResetMediaBuffers();
344
345    if (err != OK) {
346        ALOGE("failed to release %s (err=%d)", mComponentName.c_str(), err);
347        handleError(err);
348        // finish with posting kWhatShutdownCompleted.
349    }
350
351    if (notifyComplete) {
352        sp<AMessage> notify = mNotify->dup();
353        notify->setInt32("what", kWhatShutdownCompleted);
354        notify->post();
355        mPaused = true;
356    }
357}
358
359void NuPlayer::Decoder::doRequestBuffers() {
360    // mRenderer is only NULL if we have a legacy widevine source that
361    // is not yet ready. In this case we must not fetch input.
362    if (isDiscontinuityPending() || mRenderer == NULL) {
363        return;
364    }
365    status_t err = OK;
366    while (err == OK && !mDequeuedInputBuffers.empty()) {
367        size_t bufferIx = *mDequeuedInputBuffers.begin();
368        sp<AMessage> msg = new AMessage();
369        msg->setSize("buffer-ix", bufferIx);
370        err = fetchInputData(msg);
371        if (err != OK && err != ERROR_END_OF_STREAM) {
372            // if EOS, need to queue EOS buffer
373            break;
374        }
375        mDequeuedInputBuffers.erase(mDequeuedInputBuffers.begin());
376
377        if (!mPendingInputMessages.empty()
378                || !onInputBufferFetched(msg)) {
379            mPendingInputMessages.push_back(msg);
380        }
381    }
382
383    if (err == -EWOULDBLOCK
384            && mSource->feedMoreTSData() == OK) {
385        scheduleRequestBuffers();
386    }
387}
388
389void NuPlayer::Decoder::handleError(int32_t err)
390{
391    // We cannot immediately release the codec due to buffers still outstanding
392    // in the renderer.  We signal to the player the error so it can shutdown/release the
393    // decoder after flushing and increment the generation to discard unnecessary messages.
394
395    ++mBufferGeneration;
396
397    sp<AMessage> notify = mNotify->dup();
398    notify->setInt32("what", kWhatError);
399    notify->setInt32("err", err);
400    notify->post();
401}
402
403bool NuPlayer::Decoder::handleAnInputBuffer(size_t index) {
404    if (isDiscontinuityPending()) {
405        return false;
406    }
407
408    sp<ABuffer> buffer;
409    mCodec->getInputBuffer(index, &buffer);
410
411    if (index >= mInputBuffers.size()) {
412        for (size_t i = mInputBuffers.size(); i <= index; ++i) {
413            mInputBuffers.add();
414            mMediaBuffers.add();
415            mInputBufferIsDequeued.add();
416            mMediaBuffers.editItemAt(i) = NULL;
417            mInputBufferIsDequeued.editItemAt(i) = false;
418        }
419    }
420    mInputBuffers.editItemAt(index) = buffer;
421
422    //CHECK_LT(bufferIx, mInputBuffers.size());
423
424    if (mMediaBuffers[index] != NULL) {
425        mMediaBuffers[index]->release();
426        mMediaBuffers.editItemAt(index) = NULL;
427    }
428    mInputBufferIsDequeued.editItemAt(index) = true;
429
430    if (!mCSDsToSubmit.isEmpty()) {
431        sp<AMessage> msg = new AMessage();
432        msg->setSize("buffer-ix", index);
433
434        sp<ABuffer> buffer = mCSDsToSubmit.itemAt(0);
435        ALOGI("[%s] resubmitting CSD", mComponentName.c_str());
436        msg->setBuffer("buffer", buffer);
437        mCSDsToSubmit.removeAt(0);
438        CHECK(onInputBufferFetched(msg));
439        return true;
440    }
441
442    while (!mPendingInputMessages.empty()) {
443        sp<AMessage> msg = *mPendingInputMessages.begin();
444        if (!onInputBufferFetched(msg)) {
445            break;
446        }
447        mPendingInputMessages.erase(mPendingInputMessages.begin());
448    }
449
450    if (!mInputBufferIsDequeued.editItemAt(index)) {
451        return true;
452    }
453
454    mDequeuedInputBuffers.push_back(index);
455
456    onRequestInputBuffers();
457    return true;
458}
459
460bool NuPlayer::Decoder::handleAnOutputBuffer(
461        size_t index,
462        size_t offset,
463        size_t size,
464        int64_t timeUs,
465        int32_t flags) {
466//    CHECK_LT(bufferIx, mOutputBuffers.size());
467    sp<ABuffer> buffer;
468    mCodec->getOutputBuffer(index, &buffer);
469
470    if (index >= mOutputBuffers.size()) {
471        for (size_t i = mOutputBuffers.size(); i <= index; ++i) {
472            mOutputBuffers.add();
473        }
474    }
475
476    mOutputBuffers.editItemAt(index) = buffer;
477
478    buffer->setRange(offset, size);
479    buffer->meta()->clear();
480    buffer->meta()->setInt64("timeUs", timeUs);
481
482    bool eos = flags & MediaCodec::BUFFER_FLAG_EOS;
483    // we do not expect CODECCONFIG or SYNCFRAME for decoder
484
485    sp<AMessage> reply = new AMessage(kWhatRenderBuffer, this);
486    reply->setSize("buffer-ix", index);
487    reply->setInt32("generation", mBufferGeneration);
488
489    if (eos) {
490        ALOGI("[%s] saw output EOS", mIsAudio ? "audio" : "video");
491
492        buffer->meta()->setInt32("eos", true);
493        reply->setInt32("eos", true);
494    } else if (mSkipRenderingUntilMediaTimeUs >= 0) {
495        if (timeUs < mSkipRenderingUntilMediaTimeUs) {
496            ALOGV("[%s] dropping buffer at time %lld as requested.",
497                     mComponentName.c_str(), (long long)timeUs);
498
499            reply->post();
500            return true;
501        }
502
503        mSkipRenderingUntilMediaTimeUs = -1;
504    }
505
506    // wait until 1st frame comes out to signal resume complete
507    notifyResumeCompleteIfNecessary();
508
509    if (mRenderer != NULL) {
510        // send the buffer to renderer.
511        mRenderer->queueBuffer(mIsAudio, buffer, reply);
512        if (eos && !isDiscontinuityPending()) {
513            mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
514        }
515    }
516
517    return true;
518}
519
520void NuPlayer::Decoder::handleOutputFormatChange(const sp<AMessage> &format) {
521    if (!mIsAudio) {
522        sp<AMessage> notify = mNotify->dup();
523        notify->setInt32("what", kWhatVideoSizeChanged);
524        notify->setMessage("format", format);
525        notify->post();
526    } else if (mRenderer != NULL) {
527        uint32_t flags;
528        int64_t durationUs;
529        bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
530        if (!hasVideo &&
531                mSource->getDuration(&durationUs) == OK &&
532                durationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US) {
533            flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
534        } else {
535            flags = AUDIO_OUTPUT_FLAG_NONE;
536        }
537
538        mRenderer->openAudioSink(
539                format, false /* offloadOnly */, hasVideo, flags, NULL /* isOffloaed */);
540    }
541}
542
543void NuPlayer::Decoder::releaseAndResetMediaBuffers() {
544    for (size_t i = 0; i < mMediaBuffers.size(); i++) {
545        if (mMediaBuffers[i] != NULL) {
546            mMediaBuffers[i]->release();
547            mMediaBuffers.editItemAt(i) = NULL;
548        }
549    }
550    mMediaBuffers.resize(mInputBuffers.size());
551    for (size_t i = 0; i < mMediaBuffers.size(); i++) {
552        mMediaBuffers.editItemAt(i) = NULL;
553    }
554    mInputBufferIsDequeued.clear();
555    mInputBufferIsDequeued.resize(mInputBuffers.size());
556    for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
557        mInputBufferIsDequeued.editItemAt(i) = false;
558    }
559
560    mPendingInputMessages.clear();
561    mDequeuedInputBuffers.clear();
562    mSkipRenderingUntilMediaTimeUs = -1;
563}
564
565void NuPlayer::Decoder::requestCodecNotification() {
566    if (mCodec != NULL) {
567        sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
568        reply->setInt32("generation", mBufferGeneration);
569        mCodec->requestActivityNotification(reply);
570    }
571}
572
573bool NuPlayer::Decoder::isStaleReply(const sp<AMessage> &msg) {
574    int32_t generation;
575    CHECK(msg->findInt32("generation", &generation));
576    return generation != mBufferGeneration;
577}
578
579status_t NuPlayer::Decoder::fetchInputData(sp<AMessage> &reply) {
580    sp<ABuffer> accessUnit;
581    bool dropAccessUnit;
582    do {
583        status_t err = mSource->dequeueAccessUnit(mIsAudio, &accessUnit);
584
585        if (err == -EWOULDBLOCK) {
586            return err;
587        } else if (err != OK) {
588            if (err == INFO_DISCONTINUITY) {
589                int32_t type;
590                CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
591
592                bool formatChange =
593                    (mIsAudio &&
594                     (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
595                    || (!mIsAudio &&
596                            (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
597
598                bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
599
600                ALOGI("%s discontinuity (format=%d, time=%d)",
601                        mIsAudio ? "audio" : "video", formatChange, timeChange);
602
603                bool seamlessFormatChange = false;
604                sp<AMessage> newFormat = mSource->getFormat(mIsAudio);
605                if (formatChange) {
606                    seamlessFormatChange =
607                        supportsSeamlessFormatChange(newFormat);
608                    // treat seamless format change separately
609                    formatChange = !seamlessFormatChange;
610                }
611
612                // For format or time change, return EOS to queue EOS input,
613                // then wait for EOS on output.
614                if (formatChange /* not seamless */) {
615                    mFormatChangePending = true;
616                    err = ERROR_END_OF_STREAM;
617                } else if (timeChange) {
618                    rememberCodecSpecificData(newFormat);
619                    mTimeChangePending = true;
620                    err = ERROR_END_OF_STREAM;
621                } else if (seamlessFormatChange) {
622                    // reuse existing decoder and don't flush
623                    rememberCodecSpecificData(newFormat);
624                    continue;
625                } else {
626                    // This stream is unaffected by the discontinuity
627                    return -EWOULDBLOCK;
628                }
629            }
630
631            // reply should only be returned without a buffer set
632            // when there is an error (including EOS)
633            CHECK(err != OK);
634
635            reply->setInt32("err", err);
636            return ERROR_END_OF_STREAM;
637        }
638
639        if (!mIsAudio) {
640            ++mNumFramesTotal;
641        }
642
643        dropAccessUnit = false;
644        if (!mIsAudio
645                && !mIsSecure
646                && mRenderer->getVideoLateByUs() > 100000ll
647                && mIsVideoAVC
648                && !IsAVCReferenceFrame(accessUnit)) {
649            dropAccessUnit = true;
650            ++mNumFramesDropped;
651        }
652    } while (dropAccessUnit);
653
654    // ALOGV("returned a valid buffer of %s data", mIsAudio ? "mIsAudio" : "video");
655#if 0
656    int64_t mediaTimeUs;
657    CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
658    ALOGV("[%s] feeding input buffer at media time %" PRId64,
659         mIsAudio ? "audio" : "video",
660         mediaTimeUs / 1E6);
661#endif
662
663    if (mCCDecoder != NULL) {
664        mCCDecoder->decode(accessUnit);
665    }
666
667    reply->setBuffer("buffer", accessUnit);
668
669    return OK;
670}
671
672bool NuPlayer::Decoder::onInputBufferFetched(const sp<AMessage> &msg) {
673    size_t bufferIx;
674    CHECK(msg->findSize("buffer-ix", &bufferIx));
675    CHECK_LT(bufferIx, mInputBuffers.size());
676    sp<ABuffer> codecBuffer = mInputBuffers[bufferIx];
677
678    sp<ABuffer> buffer;
679    bool hasBuffer = msg->findBuffer("buffer", &buffer);
680
681    // handle widevine classic source - that fills an arbitrary input buffer
682    MediaBuffer *mediaBuffer = NULL;
683    if (hasBuffer) {
684        mediaBuffer = (MediaBuffer *)(buffer->getMediaBufferBase());
685        if (mediaBuffer != NULL) {
686            // likely filled another buffer than we requested: adjust buffer index
687            size_t ix;
688            for (ix = 0; ix < mInputBuffers.size(); ix++) {
689                const sp<ABuffer> &buf = mInputBuffers[ix];
690                if (buf->data() == mediaBuffer->data()) {
691                    // all input buffers are dequeued on start, hence the check
692                    if (!mInputBufferIsDequeued[ix]) {
693                        ALOGV("[%s] received MediaBuffer for #%zu instead of #%zu",
694                                mComponentName.c_str(), ix, bufferIx);
695                        mediaBuffer->release();
696                        return false;
697                    }
698
699                    // TRICKY: need buffer for the metadata, so instead, set
700                    // codecBuffer to the same (though incorrect) buffer to
701                    // avoid a memcpy into the codecBuffer
702                    codecBuffer = buffer;
703                    codecBuffer->setRange(
704                            mediaBuffer->range_offset(),
705                            mediaBuffer->range_length());
706                    bufferIx = ix;
707                    break;
708                }
709            }
710            CHECK(ix < mInputBuffers.size());
711        }
712    }
713
714    if (buffer == NULL /* includes !hasBuffer */) {
715        int32_t streamErr = ERROR_END_OF_STREAM;
716        CHECK(msg->findInt32("err", &streamErr) || !hasBuffer);
717
718        CHECK(streamErr != OK);
719
720        // attempt to queue EOS
721        status_t err = mCodec->queueInputBuffer(
722                bufferIx,
723                0,
724                0,
725                0,
726                MediaCodec::BUFFER_FLAG_EOS);
727        if (err == OK) {
728            mInputBufferIsDequeued.editItemAt(bufferIx) = false;
729        } else if (streamErr == ERROR_END_OF_STREAM) {
730            streamErr = err;
731            // err will not be ERROR_END_OF_STREAM
732        }
733
734        if (streamErr != ERROR_END_OF_STREAM) {
735            ALOGE("Stream error for %s (err=%d), EOS %s queued",
736                    mComponentName.c_str(),
737                    streamErr,
738                    err == OK ? "successfully" : "unsuccessfully");
739            handleError(streamErr);
740        }
741    } else {
742        sp<AMessage> extra;
743        if (buffer->meta()->findMessage("extra", &extra) && extra != NULL) {
744            int64_t resumeAtMediaTimeUs;
745            if (extra->findInt64(
746                        "resume-at-mediaTimeUs", &resumeAtMediaTimeUs)) {
747                ALOGI("[%s] suppressing rendering until %lld us",
748                        mComponentName.c_str(), (long long)resumeAtMediaTimeUs);
749                mSkipRenderingUntilMediaTimeUs = resumeAtMediaTimeUs;
750            }
751        }
752
753        int64_t timeUs = 0;
754        uint32_t flags = 0;
755        CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
756
757        int32_t eos, csd;
758        // we do not expect SYNCFRAME for decoder
759        if (buffer->meta()->findInt32("eos", &eos) && eos) {
760            flags |= MediaCodec::BUFFER_FLAG_EOS;
761        } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
762            flags |= MediaCodec::BUFFER_FLAG_CODECCONFIG;
763        }
764
765        // copy into codec buffer
766        if (buffer != codecBuffer) {
767            CHECK_LE(buffer->size(), codecBuffer->capacity());
768            codecBuffer->setRange(0, buffer->size());
769            memcpy(codecBuffer->data(), buffer->data(), buffer->size());
770        }
771
772        status_t err = mCodec->queueInputBuffer(
773                        bufferIx,
774                        codecBuffer->offset(),
775                        codecBuffer->size(),
776                        timeUs,
777                        flags);
778        if (err != OK) {
779            if (mediaBuffer != NULL) {
780                mediaBuffer->release();
781            }
782            ALOGE("Failed to queue input buffer for %s (err=%d)",
783                    mComponentName.c_str(), err);
784            handleError(err);
785        } else {
786            mInputBufferIsDequeued.editItemAt(bufferIx) = false;
787            if (mediaBuffer != NULL) {
788                CHECK(mMediaBuffers[bufferIx] == NULL);
789                mMediaBuffers.editItemAt(bufferIx) = mediaBuffer;
790            }
791        }
792    }
793    return true;
794}
795
796void NuPlayer::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
797    status_t err;
798    int32_t render;
799    size_t bufferIx;
800    int32_t eos;
801    CHECK(msg->findSize("buffer-ix", &bufferIx));
802
803    if (!mIsAudio) {
804        int64_t timeUs;
805        sp<ABuffer> buffer = mOutputBuffers[bufferIx];
806        buffer->meta()->findInt64("timeUs", &timeUs);
807
808        if (mCCDecoder != NULL && mCCDecoder->isSelected()) {
809            mCCDecoder->display(timeUs);
810        }
811    }
812
813    if (msg->findInt32("render", &render) && render) {
814        int64_t timestampNs;
815        CHECK(msg->findInt64("timestampNs", &timestampNs));
816        err = mCodec->renderOutputBufferAndRelease(bufferIx, timestampNs);
817    } else {
818        err = mCodec->releaseOutputBuffer(bufferIx);
819    }
820    if (err != OK) {
821        ALOGE("failed to release output buffer for %s (err=%d)",
822                mComponentName.c_str(), err);
823        handleError(err);
824    }
825    if (msg->findInt32("eos", &eos) && eos
826            && isDiscontinuityPending()) {
827        finishHandleDiscontinuity(true /* flushOnTimeChange */);
828    }
829}
830
831bool NuPlayer::Decoder::isDiscontinuityPending() const {
832    return mFormatChangePending || mTimeChangePending;
833}
834
835void NuPlayer::Decoder::finishHandleDiscontinuity(bool flushOnTimeChange) {
836    ALOGV("finishHandleDiscontinuity: format %d, time %d, flush %d",
837            mFormatChangePending, mTimeChangePending, flushOnTimeChange);
838
839    // If we have format change, pause and wait to be killed;
840    // If we have time change only, flush and restart fetching.
841
842    if (mFormatChangePending) {
843        mPaused = true;
844    } else if (mTimeChangePending) {
845        if (flushOnTimeChange) {
846            doFlush(false /* notifyComplete */);
847            signalResume(false /* notifyComplete */);
848        }
849
850        // restart fetching input
851        scheduleRequestBuffers();
852    }
853
854    // Notify NuPlayer to either shutdown decoder, or rescan sources
855    sp<AMessage> msg = mNotify->dup();
856    msg->setInt32("what", kWhatInputDiscontinuity);
857    msg->setInt32("formatChange", mFormatChangePending);
858    msg->post();
859
860    mFormatChangePending = false;
861    mTimeChangePending = false;
862}
863
864bool NuPlayer::Decoder::supportsSeamlessAudioFormatChange(
865        const sp<AMessage> &targetFormat) const {
866    if (targetFormat == NULL) {
867        return true;
868    }
869
870    AString mime;
871    if (!targetFormat->findString("mime", &mime)) {
872        return false;
873    }
874
875    if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
876        // field-by-field comparison
877        const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
878        for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
879            int32_t oldVal, newVal;
880            if (!mInputFormat->findInt32(keys[i], &oldVal) ||
881                    !targetFormat->findInt32(keys[i], &newVal) ||
882                    oldVal != newVal) {
883                return false;
884            }
885        }
886
887        sp<ABuffer> oldBuf, newBuf;
888        if (mInputFormat->findBuffer("csd-0", &oldBuf) &&
889                targetFormat->findBuffer("csd-0", &newBuf)) {
890            if (oldBuf->size() != newBuf->size()) {
891                return false;
892            }
893            return !memcmp(oldBuf->data(), newBuf->data(), oldBuf->size());
894        }
895    }
896    return false;
897}
898
899bool NuPlayer::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
900    if (mInputFormat == NULL) {
901        return false;
902    }
903
904    if (targetFormat == NULL) {
905        return true;
906    }
907
908    AString oldMime, newMime;
909    if (!mInputFormat->findString("mime", &oldMime)
910            || !targetFormat->findString("mime", &newMime)
911            || !(oldMime == newMime)) {
912        return false;
913    }
914
915    bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
916    bool seamless;
917    if (audio) {
918        seamless = supportsSeamlessAudioFormatChange(targetFormat);
919    } else {
920        int32_t isAdaptive;
921        seamless = (mCodec != NULL &&
922                mInputFormat->findInt32("adaptive-playback", &isAdaptive) &&
923                isAdaptive);
924    }
925
926    ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
927    return seamless;
928}
929
930void NuPlayer::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
931    if (format == NULL) {
932        return;
933    }
934    mCSDsForCurrentFormat.clear();
935    for (int32_t i = 0; ; ++i) {
936        AString tag = "csd-";
937        tag.append(i);
938        sp<ABuffer> buffer;
939        if (!format->findBuffer(tag.c_str(), &buffer)) {
940            break;
941        }
942        mCSDsForCurrentFormat.push(buffer);
943    }
944}
945
946void NuPlayer::Decoder::notifyResumeCompleteIfNecessary() {
947    if (mResumePending) {
948        mResumePending = false;
949
950        sp<AMessage> notify = mNotify->dup();
951        notify->setInt32("what", kWhatResumeCompleted);
952        notify->post();
953    }
954}
955
956}  // namespace android
957
958