MediaCodec.cpp revision 9b3d384753658a2b7985b1f4d124b09a8fb8f3b6
1/*
2 * Copyright 2012, 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 "MediaCodec"
19#include <inttypes.h>
20
21#include "include/avc_utils.h"
22#include "include/SoftwareRenderer.h"
23
24#include <binder/IBatteryStats.h>
25#include <binder/IServiceManager.h>
26#include <gui/Surface.h>
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/foundation/AString.h>
32#include <media/stagefright/foundation/hexdump.h>
33#include <media/stagefright/ACodec.h>
34#include <media/stagefright/BufferProducerWrapper.h>
35#include <media/stagefright/MediaCodec.h>
36#include <media/stagefright/MediaCodecList.h>
37#include <media/stagefright/MediaDefs.h>
38#include <media/stagefright/MediaErrors.h>
39#include <media/stagefright/MediaFilter.h>
40#include <media/stagefright/MetaData.h>
41#include <media/stagefright/NativeWindowWrapper.h>
42#include <private/android_filesystem_config.h>
43#include <utils/Log.h>
44#include <utils/Singleton.h>
45
46namespace android {
47
48struct MediaCodec::BatteryNotifier : public Singleton<BatteryNotifier> {
49    BatteryNotifier();
50
51    void noteStartVideo();
52    void noteStopVideo();
53    void noteStartAudio();
54    void noteStopAudio();
55
56private:
57    int32_t mVideoRefCount;
58    int32_t mAudioRefCount;
59    sp<IBatteryStats> mBatteryStatService;
60};
61
62ANDROID_SINGLETON_STATIC_INSTANCE(MediaCodec::BatteryNotifier)
63
64MediaCodec::BatteryNotifier::BatteryNotifier() :
65    mVideoRefCount(0),
66    mAudioRefCount(0) {
67    // get battery service
68    const sp<IServiceManager> sm(defaultServiceManager());
69    if (sm != NULL) {
70        const String16 name("batterystats");
71        mBatteryStatService = interface_cast<IBatteryStats>(sm->getService(name));
72        if (mBatteryStatService == NULL) {
73            ALOGE("batterystats service unavailable!");
74        }
75    }
76}
77
78void MediaCodec::BatteryNotifier::noteStartVideo() {
79    if (mVideoRefCount == 0 && mBatteryStatService != NULL) {
80        mBatteryStatService->noteStartVideo(AID_MEDIA);
81    }
82    mVideoRefCount++;
83}
84
85void MediaCodec::BatteryNotifier::noteStopVideo() {
86    if (mVideoRefCount == 0) {
87        ALOGW("BatteryNotifier::noteStop(): video refcount is broken!");
88        return;
89    }
90
91    mVideoRefCount--;
92    if (mVideoRefCount == 0 && mBatteryStatService != NULL) {
93        mBatteryStatService->noteStopVideo(AID_MEDIA);
94    }
95}
96
97void MediaCodec::BatteryNotifier::noteStartAudio() {
98    if (mAudioRefCount == 0 && mBatteryStatService != NULL) {
99        mBatteryStatService->noteStartAudio(AID_MEDIA);
100    }
101    mAudioRefCount++;
102}
103
104void MediaCodec::BatteryNotifier::noteStopAudio() {
105    if (mAudioRefCount == 0) {
106        ALOGW("BatteryNotifier::noteStop(): audio refcount is broken!");
107        return;
108    }
109
110    mAudioRefCount--;
111    if (mAudioRefCount == 0 && mBatteryStatService != NULL) {
112        mBatteryStatService->noteStopAudio(AID_MEDIA);
113    }
114}
115// static
116sp<MediaCodec> MediaCodec::CreateByType(
117        const sp<ALooper> &looper, const char *mime, bool encoder, status_t *err) {
118    sp<MediaCodec> codec = new MediaCodec(looper);
119
120    const status_t ret = codec->init(mime, true /* nameIsType */, encoder);
121    if (err != NULL) {
122        *err = ret;
123    }
124    return ret == OK ? codec : NULL; // NULL deallocates codec.
125}
126
127// static
128sp<MediaCodec> MediaCodec::CreateByComponentName(
129        const sp<ALooper> &looper, const char *name, status_t *err) {
130    sp<MediaCodec> codec = new MediaCodec(looper);
131
132    const status_t ret = codec->init(name, false /* nameIsType */, false /* encoder */);
133    if (err != NULL) {
134        *err = ret;
135    }
136    return ret == OK ? codec : NULL; // NULL deallocates codec.
137}
138
139MediaCodec::MediaCodec(const sp<ALooper> &looper)
140    : mState(UNINITIALIZED),
141      mLooper(looper),
142      mCodec(NULL),
143      mReplyID(0),
144      mFlags(0),
145      mStickyError(OK),
146      mSoftRenderer(NULL),
147      mBatteryStatNotified(false),
148      mIsVideo(false),
149      mDequeueInputTimeoutGeneration(0),
150      mDequeueInputReplyID(0),
151      mDequeueOutputTimeoutGeneration(0),
152      mDequeueOutputReplyID(0),
153      mHaveInputSurface(false) {
154}
155
156MediaCodec::~MediaCodec() {
157    CHECK_EQ(mState, UNINITIALIZED);
158}
159
160// static
161status_t MediaCodec::PostAndAwaitResponse(
162        const sp<AMessage> &msg, sp<AMessage> *response) {
163    status_t err = msg->postAndAwaitResponse(response);
164
165    if (err != OK) {
166        return err;
167    }
168
169    if (!(*response)->findInt32("err", &err)) {
170        err = OK;
171    }
172
173    return err;
174}
175
176// static
177void MediaCodec::PostReplyWithError(int32_t replyID, int32_t err) {
178    sp<AMessage> response = new AMessage;
179    response->setInt32("err", err);
180    response->postReply(replyID);
181}
182
183status_t MediaCodec::init(const AString &name, bool nameIsType, bool encoder) {
184    // save init parameters for reset
185    mInitName = name;
186    mInitNameIsType = nameIsType;
187    mInitIsEncoder = encoder;
188
189    // Current video decoders do not return from OMX_FillThisBuffer
190    // quickly, violating the OpenMAX specs, until that is remedied
191    // we need to invest in an extra looper to free the main event
192    // queue.
193
194    if (nameIsType || !strncasecmp(name.c_str(), "omx.", 4)) {
195        mCodec = new ACodec;
196    } else if (!nameIsType
197            && !strncasecmp(name.c_str(), "android.filter.", 15)) {
198        mCodec = new MediaFilter;
199    } else {
200        return NAME_NOT_FOUND;
201    }
202
203    bool needDedicatedLooper = false;
204    if (nameIsType && !strncasecmp(name.c_str(), "video/", 6)) {
205        needDedicatedLooper = true;
206    } else {
207        AString tmp = name;
208        if (tmp.endsWith(".secure")) {
209            tmp.erase(tmp.size() - 7, 7);
210        }
211        const sp<IMediaCodecList> mcl = MediaCodecList::getInstance();
212        ssize_t codecIdx = mcl->findCodecByName(tmp.c_str());
213        if (codecIdx >= 0) {
214            const sp<MediaCodecInfo> info = mcl->getCodecInfo(codecIdx);
215            Vector<AString> mimes;
216            info->getSupportedMimes(&mimes);
217            for (size_t i = 0; i < mimes.size(); i++) {
218                if (mimes[i].startsWith("video/")) {
219                    needDedicatedLooper = true;
220                    break;
221                }
222            }
223        }
224    }
225
226    if (needDedicatedLooper) {
227        if (mCodecLooper == NULL) {
228            mCodecLooper = new ALooper;
229            mCodecLooper->setName("CodecLooper");
230            mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
231        }
232
233        mCodecLooper->registerHandler(mCodec);
234    } else {
235        mLooper->registerHandler(mCodec);
236    }
237
238    mLooper->registerHandler(this);
239
240    mCodec->setNotificationMessage(new AMessage(kWhatCodecNotify, id()));
241
242    sp<AMessage> msg = new AMessage(kWhatInit, id());
243    msg->setString("name", name);
244    msg->setInt32("nameIsType", nameIsType);
245
246    if (nameIsType) {
247        msg->setInt32("encoder", encoder);
248    }
249
250    sp<AMessage> response;
251    return PostAndAwaitResponse(msg, &response);
252}
253
254status_t MediaCodec::setCallback(const sp<AMessage> &callback) {
255    sp<AMessage> msg = new AMessage(kWhatSetCallback, id());
256    msg->setMessage("callback", callback);
257
258    sp<AMessage> response;
259    return PostAndAwaitResponse(msg, &response);
260}
261
262status_t MediaCodec::configure(
263        const sp<AMessage> &format,
264        const sp<Surface> &nativeWindow,
265        const sp<ICrypto> &crypto,
266        uint32_t flags) {
267    sp<AMessage> msg = new AMessage(kWhatConfigure, id());
268
269    msg->setMessage("format", format);
270    msg->setInt32("flags", flags);
271
272    if (nativeWindow != NULL) {
273        msg->setObject(
274                "native-window",
275                new NativeWindowWrapper(nativeWindow));
276    }
277
278    if (crypto != NULL) {
279        msg->setPointer("crypto", crypto.get());
280    }
281
282    sp<AMessage> response;
283    status_t err = PostAndAwaitResponse(msg, &response);
284
285    if (err != OK && err != INVALID_OPERATION) {
286        // MediaCodec now set state to UNINITIALIZED upon any fatal error.
287        // To maintain backward-compatibility, do a reset() to put codec
288        // back into INITIALIZED state.
289        // But don't reset if the err is INVALID_OPERATION, which means
290        // the configure failure is due to wrong state.
291
292        ALOGE("configure failed with err 0x%08x, resetting...", err);
293        reset();
294    }
295
296    return err;
297}
298
299status_t MediaCodec::createInputSurface(
300        sp<IGraphicBufferProducer>* bufferProducer) {
301    sp<AMessage> msg = new AMessage(kWhatCreateInputSurface, id());
302
303    sp<AMessage> response;
304    status_t err = PostAndAwaitResponse(msg, &response);
305    if (err == NO_ERROR) {
306        // unwrap the sp<IGraphicBufferProducer>
307        sp<RefBase> obj;
308        bool found = response->findObject("input-surface", &obj);
309        CHECK(found);
310        sp<BufferProducerWrapper> wrapper(
311                static_cast<BufferProducerWrapper*>(obj.get()));
312        *bufferProducer = wrapper->getBufferProducer();
313    } else {
314        ALOGW("createInputSurface failed, err=%d", err);
315    }
316    return err;
317}
318
319status_t MediaCodec::start() {
320    sp<AMessage> msg = new AMessage(kWhatStart, id());
321
322    sp<AMessage> response;
323    return PostAndAwaitResponse(msg, &response);
324}
325
326status_t MediaCodec::stop() {
327    sp<AMessage> msg = new AMessage(kWhatStop, id());
328
329    sp<AMessage> response;
330    return PostAndAwaitResponse(msg, &response);
331}
332
333status_t MediaCodec::release() {
334    sp<AMessage> msg = new AMessage(kWhatRelease, id());
335
336    sp<AMessage> response;
337    return PostAndAwaitResponse(msg, &response);
338}
339
340status_t MediaCodec::reset() {
341    /* When external-facing MediaCodec object is created,
342       it is already initialized.  Thus, reset is essentially
343       release() followed by init(), plus clearing the state */
344
345    status_t err = release();
346
347    // unregister handlers
348    if (mCodec != NULL) {
349        if (mCodecLooper != NULL) {
350            mCodecLooper->unregisterHandler(mCodec->id());
351        } else {
352            mLooper->unregisterHandler(mCodec->id());
353        }
354        mCodec = NULL;
355    }
356    mLooper->unregisterHandler(id());
357
358    mFlags = 0;    // clear all flags
359    mStickyError = OK;
360
361    // reset state not reset by setState(UNINITIALIZED)
362    mReplyID = 0;
363    mDequeueInputReplyID = 0;
364    mDequeueOutputReplyID = 0;
365    mDequeueInputTimeoutGeneration = 0;
366    mDequeueOutputTimeoutGeneration = 0;
367    mHaveInputSurface = false;
368
369    if (err == OK) {
370        err = init(mInitName, mInitNameIsType, mInitIsEncoder);
371    }
372    return err;
373}
374
375status_t MediaCodec::queueInputBuffer(
376        size_t index,
377        size_t offset,
378        size_t size,
379        int64_t presentationTimeUs,
380        uint32_t flags,
381        AString *errorDetailMsg) {
382    if (errorDetailMsg != NULL) {
383        errorDetailMsg->clear();
384    }
385
386    sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, id());
387    msg->setSize("index", index);
388    msg->setSize("offset", offset);
389    msg->setSize("size", size);
390    msg->setInt64("timeUs", presentationTimeUs);
391    msg->setInt32("flags", flags);
392    msg->setPointer("errorDetailMsg", errorDetailMsg);
393
394    sp<AMessage> response;
395    return PostAndAwaitResponse(msg, &response);
396}
397
398status_t MediaCodec::queueSecureInputBuffer(
399        size_t index,
400        size_t offset,
401        const CryptoPlugin::SubSample *subSamples,
402        size_t numSubSamples,
403        const uint8_t key[16],
404        const uint8_t iv[16],
405        CryptoPlugin::Mode mode,
406        int64_t presentationTimeUs,
407        uint32_t flags,
408        AString *errorDetailMsg) {
409    if (errorDetailMsg != NULL) {
410        errorDetailMsg->clear();
411    }
412
413    sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, id());
414    msg->setSize("index", index);
415    msg->setSize("offset", offset);
416    msg->setPointer("subSamples", (void *)subSamples);
417    msg->setSize("numSubSamples", numSubSamples);
418    msg->setPointer("key", (void *)key);
419    msg->setPointer("iv", (void *)iv);
420    msg->setInt32("mode", mode);
421    msg->setInt64("timeUs", presentationTimeUs);
422    msg->setInt32("flags", flags);
423    msg->setPointer("errorDetailMsg", errorDetailMsg);
424
425    sp<AMessage> response;
426    status_t err = PostAndAwaitResponse(msg, &response);
427
428    return err;
429}
430
431status_t MediaCodec::dequeueInputBuffer(size_t *index, int64_t timeoutUs) {
432    sp<AMessage> msg = new AMessage(kWhatDequeueInputBuffer, id());
433    msg->setInt64("timeoutUs", timeoutUs);
434
435    sp<AMessage> response;
436    status_t err;
437    if ((err = PostAndAwaitResponse(msg, &response)) != OK) {
438        return err;
439    }
440
441    CHECK(response->findSize("index", index));
442
443    return OK;
444}
445
446status_t MediaCodec::dequeueOutputBuffer(
447        size_t *index,
448        size_t *offset,
449        size_t *size,
450        int64_t *presentationTimeUs,
451        uint32_t *flags,
452        int64_t timeoutUs) {
453    sp<AMessage> msg = new AMessage(kWhatDequeueOutputBuffer, id());
454    msg->setInt64("timeoutUs", timeoutUs);
455
456    sp<AMessage> response;
457    status_t err;
458    if ((err = PostAndAwaitResponse(msg, &response)) != OK) {
459        return err;
460    }
461
462    CHECK(response->findSize("index", index));
463    CHECK(response->findSize("offset", offset));
464    CHECK(response->findSize("size", size));
465    CHECK(response->findInt64("timeUs", presentationTimeUs));
466    CHECK(response->findInt32("flags", (int32_t *)flags));
467
468    return OK;
469}
470
471status_t MediaCodec::renderOutputBufferAndRelease(size_t index) {
472    sp<AMessage> msg = new AMessage(kWhatReleaseOutputBuffer, id());
473    msg->setSize("index", index);
474    msg->setInt32("render", true);
475
476    sp<AMessage> response;
477    return PostAndAwaitResponse(msg, &response);
478}
479
480status_t MediaCodec::renderOutputBufferAndRelease(size_t index, int64_t timestampNs) {
481    sp<AMessage> msg = new AMessage(kWhatReleaseOutputBuffer, id());
482    msg->setSize("index", index);
483    msg->setInt32("render", true);
484    msg->setInt64("timestampNs", timestampNs);
485
486    sp<AMessage> response;
487    return PostAndAwaitResponse(msg, &response);
488}
489
490status_t MediaCodec::releaseOutputBuffer(size_t index) {
491    sp<AMessage> msg = new AMessage(kWhatReleaseOutputBuffer, id());
492    msg->setSize("index", index);
493
494    sp<AMessage> response;
495    return PostAndAwaitResponse(msg, &response);
496}
497
498status_t MediaCodec::signalEndOfInputStream() {
499    sp<AMessage> msg = new AMessage(kWhatSignalEndOfInputStream, id());
500
501    sp<AMessage> response;
502    return PostAndAwaitResponse(msg, &response);
503}
504
505status_t MediaCodec::getOutputFormat(sp<AMessage> *format) const {
506    sp<AMessage> msg = new AMessage(kWhatGetOutputFormat, id());
507
508    sp<AMessage> response;
509    status_t err;
510    if ((err = PostAndAwaitResponse(msg, &response)) != OK) {
511        return err;
512    }
513
514    CHECK(response->findMessage("format", format));
515
516    return OK;
517}
518
519status_t MediaCodec::getInputFormat(sp<AMessage> *format) const {
520    sp<AMessage> msg = new AMessage(kWhatGetInputFormat, id());
521
522    sp<AMessage> response;
523    status_t err;
524    if ((err = PostAndAwaitResponse(msg, &response)) != OK) {
525        return err;
526    }
527
528    CHECK(response->findMessage("format", format));
529
530    return OK;
531}
532
533status_t MediaCodec::getName(AString *name) const {
534    sp<AMessage> msg = new AMessage(kWhatGetName, id());
535
536    sp<AMessage> response;
537    status_t err;
538    if ((err = PostAndAwaitResponse(msg, &response)) != OK) {
539        return err;
540    }
541
542    CHECK(response->findString("name", name));
543
544    return OK;
545}
546
547status_t MediaCodec::getInputBuffers(Vector<sp<ABuffer> > *buffers) const {
548    sp<AMessage> msg = new AMessage(kWhatGetBuffers, id());
549    msg->setInt32("portIndex", kPortIndexInput);
550    msg->setPointer("buffers", buffers);
551
552    sp<AMessage> response;
553    return PostAndAwaitResponse(msg, &response);
554}
555
556status_t MediaCodec::getOutputBuffers(Vector<sp<ABuffer> > *buffers) const {
557    sp<AMessage> msg = new AMessage(kWhatGetBuffers, id());
558    msg->setInt32("portIndex", kPortIndexOutput);
559    msg->setPointer("buffers", buffers);
560
561    sp<AMessage> response;
562    return PostAndAwaitResponse(msg, &response);
563}
564
565status_t MediaCodec::getOutputBuffer(size_t index, sp<ABuffer> *buffer) {
566    sp<AMessage> format;
567    return getBufferAndFormat(kPortIndexOutput, index, buffer, &format);
568}
569
570status_t MediaCodec::getOutputFormat(size_t index, sp<AMessage> *format) {
571    sp<ABuffer> buffer;
572    return getBufferAndFormat(kPortIndexOutput, index, &buffer, format);
573}
574
575status_t MediaCodec::getInputBuffer(size_t index, sp<ABuffer> *buffer) {
576    sp<AMessage> format;
577    return getBufferAndFormat(kPortIndexInput, index, buffer, &format);
578}
579
580bool MediaCodec::isExecuting() const {
581    return mState == STARTED || mState == FLUSHED;
582}
583
584status_t MediaCodec::getBufferAndFormat(
585        size_t portIndex, size_t index,
586        sp<ABuffer> *buffer, sp<AMessage> *format) {
587    // use mutex instead of a context switch
588
589    buffer->clear();
590    format->clear();
591    if (!isExecuting()) {
592        return INVALID_OPERATION;
593    }
594
595    // we do not want mPortBuffers to change during this section
596    // we also don't want mOwnedByClient to change during this
597    Mutex::Autolock al(mBufferLock);
598    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
599    if (index < buffers->size()) {
600        const BufferInfo &info = buffers->itemAt(index);
601        if (info.mOwnedByClient) {
602            // by the time buffers array is initialized, crypto is set
603            if (portIndex == kPortIndexInput && mCrypto != NULL) {
604                *buffer = info.mEncryptedData;
605            } else {
606                *buffer = info.mData;
607            }
608            *format = info.mFormat;
609        }
610    }
611    return OK;
612}
613
614status_t MediaCodec::flush() {
615    sp<AMessage> msg = new AMessage(kWhatFlush, id());
616
617    sp<AMessage> response;
618    return PostAndAwaitResponse(msg, &response);
619}
620
621status_t MediaCodec::requestIDRFrame() {
622    (new AMessage(kWhatRequestIDRFrame, id()))->post();
623
624    return OK;
625}
626
627void MediaCodec::requestActivityNotification(const sp<AMessage> &notify) {
628    sp<AMessage> msg = new AMessage(kWhatRequestActivityNotification, id());
629    msg->setMessage("notify", notify);
630    msg->post();
631}
632
633////////////////////////////////////////////////////////////////////////////////
634
635void MediaCodec::cancelPendingDequeueOperations() {
636    if (mFlags & kFlagDequeueInputPending) {
637        PostReplyWithError(mDequeueInputReplyID, INVALID_OPERATION);
638
639        ++mDequeueInputTimeoutGeneration;
640        mDequeueInputReplyID = 0;
641        mFlags &= ~kFlagDequeueInputPending;
642    }
643
644    if (mFlags & kFlagDequeueOutputPending) {
645        PostReplyWithError(mDequeueOutputReplyID, INVALID_OPERATION);
646
647        ++mDequeueOutputTimeoutGeneration;
648        mDequeueOutputReplyID = 0;
649        mFlags &= ~kFlagDequeueOutputPending;
650    }
651}
652
653bool MediaCodec::handleDequeueInputBuffer(uint32_t replyID, bool newRequest) {
654    if (!isExecuting() || (mFlags & kFlagIsAsync)
655            || (newRequest && (mFlags & kFlagDequeueInputPending))) {
656        PostReplyWithError(replyID, INVALID_OPERATION);
657        return true;
658    } else if (mFlags & kFlagStickyError) {
659        PostReplyWithError(replyID, getStickyError());
660        return true;
661    }
662
663    ssize_t index = dequeuePortBuffer(kPortIndexInput);
664
665    if (index < 0) {
666        CHECK_EQ(index, -EAGAIN);
667        return false;
668    }
669
670    sp<AMessage> response = new AMessage;
671    response->setSize("index", index);
672    response->postReply(replyID);
673
674    return true;
675}
676
677bool MediaCodec::handleDequeueOutputBuffer(uint32_t replyID, bool newRequest) {
678    sp<AMessage> response = new AMessage;
679
680    if (!isExecuting() || (mFlags & kFlagIsAsync)
681            || (newRequest && (mFlags & kFlagDequeueOutputPending))) {
682        response->setInt32("err", INVALID_OPERATION);
683    } else if (mFlags & kFlagStickyError) {
684        response->setInt32("err", getStickyError());
685    } else if (mFlags & kFlagOutputBuffersChanged) {
686        response->setInt32("err", INFO_OUTPUT_BUFFERS_CHANGED);
687        mFlags &= ~kFlagOutputBuffersChanged;
688    } else if (mFlags & kFlagOutputFormatChanged) {
689        response->setInt32("err", INFO_FORMAT_CHANGED);
690        mFlags &= ~kFlagOutputFormatChanged;
691    } else {
692        ssize_t index = dequeuePortBuffer(kPortIndexOutput);
693
694        if (index < 0) {
695            CHECK_EQ(index, -EAGAIN);
696            return false;
697        }
698
699        const sp<ABuffer> &buffer =
700            mPortBuffers[kPortIndexOutput].itemAt(index).mData;
701
702        response->setSize("index", index);
703        response->setSize("offset", buffer->offset());
704        response->setSize("size", buffer->size());
705
706        int64_t timeUs;
707        CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
708
709        response->setInt64("timeUs", timeUs);
710
711        int32_t omxFlags;
712        CHECK(buffer->meta()->findInt32("omxFlags", &omxFlags));
713
714        uint32_t flags = 0;
715        if (omxFlags & OMX_BUFFERFLAG_SYNCFRAME) {
716            flags |= BUFFER_FLAG_SYNCFRAME;
717        }
718        if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) {
719            flags |= BUFFER_FLAG_CODECCONFIG;
720        }
721        if (omxFlags & OMX_BUFFERFLAG_EOS) {
722            flags |= BUFFER_FLAG_EOS;
723        }
724
725        response->setInt32("flags", flags);
726    }
727
728    response->postReply(replyID);
729
730    return true;
731}
732
733void MediaCodec::onMessageReceived(const sp<AMessage> &msg) {
734    switch (msg->what()) {
735        case kWhatCodecNotify:
736        {
737            int32_t what;
738            CHECK(msg->findInt32("what", &what));
739
740            switch (what) {
741                case CodecBase::kWhatError:
742                {
743                    int32_t err, actionCode;
744                    CHECK(msg->findInt32("err", &err));
745                    CHECK(msg->findInt32("actionCode", &actionCode));
746
747                    ALOGE("Codec reported err %#x, actionCode %d, while in state %d",
748                            err, actionCode, mState);
749                    if (err == DEAD_OBJECT) {
750                        mFlags |= kFlagSawMediaServerDie;
751                        mFlags &= ~kFlagIsComponentAllocated;
752                    }
753
754                    bool sendErrorResponse = true;
755
756                    switch (mState) {
757                        case INITIALIZING:
758                        {
759                            setState(UNINITIALIZED);
760                            break;
761                        }
762
763                        case CONFIGURING:
764                        {
765                            setState(actionCode == ACTION_CODE_FATAL ?
766                                    UNINITIALIZED : INITIALIZED);
767                            break;
768                        }
769
770                        case STARTING:
771                        {
772                            setState(actionCode == ACTION_CODE_FATAL ?
773                                    UNINITIALIZED : CONFIGURED);
774                            break;
775                        }
776
777                        case STOPPING:
778                        case RELEASING:
779                        {
780                            // Ignore the error, assuming we'll still get
781                            // the shutdown complete notification.
782
783                            sendErrorResponse = false;
784
785                            if (mFlags & kFlagSawMediaServerDie) {
786                                // MediaServer died, there definitely won't
787                                // be a shutdown complete notification after
788                                // all.
789
790                                // note that we're directly going from
791                                // STOPPING->UNINITIALIZED, instead of the
792                                // usual STOPPING->INITIALIZED state.
793                                setState(UNINITIALIZED);
794                                if (mState == RELEASING) {
795                                    mComponentName.clear();
796                                }
797                                (new AMessage)->postReply(mReplyID);
798                            }
799                            break;
800                        }
801
802                        case FLUSHING:
803                        {
804                            if (actionCode == ACTION_CODE_FATAL) {
805                                setState(UNINITIALIZED);
806                            } else {
807                                setState(
808                                        (mFlags & kFlagIsAsync) ? FLUSHED : STARTED);
809                            }
810                            break;
811                        }
812
813                        case FLUSHED:
814                        case STARTED:
815                        {
816                            sendErrorResponse = false;
817
818                            setStickyError(err);
819                            postActivityNotificationIfPossible();
820
821                            cancelPendingDequeueOperations();
822
823                            if (mFlags & kFlagIsAsync) {
824                                onError(err, actionCode);
825                            }
826                            switch (actionCode) {
827                            case ACTION_CODE_TRANSIENT:
828                                break;
829                            case ACTION_CODE_RECOVERABLE:
830                                setState(INITIALIZED);
831                                break;
832                            default:
833                                setState(UNINITIALIZED);
834                                break;
835                            }
836                            break;
837                        }
838
839                        default:
840                        {
841                            sendErrorResponse = false;
842
843                            setStickyError(err);
844                            postActivityNotificationIfPossible();
845
846                            // actionCode in an uninitialized state is always fatal.
847                            if (mState == UNINITIALIZED) {
848                                actionCode = ACTION_CODE_FATAL;
849                            }
850                            if (mFlags & kFlagIsAsync) {
851                                onError(err, actionCode);
852                            }
853                            switch (actionCode) {
854                            case ACTION_CODE_TRANSIENT:
855                                break;
856                            case ACTION_CODE_RECOVERABLE:
857                                setState(INITIALIZED);
858                                break;
859                            default:
860                                setState(UNINITIALIZED);
861                                break;
862                            }
863                            break;
864                        }
865                    }
866
867                    if (sendErrorResponse) {
868                        PostReplyWithError(mReplyID, err);
869                    }
870                    break;
871                }
872
873                case CodecBase::kWhatComponentAllocated:
874                {
875                    CHECK_EQ(mState, INITIALIZING);
876                    setState(INITIALIZED);
877                    mFlags |= kFlagIsComponentAllocated;
878
879                    CHECK(msg->findString("componentName", &mComponentName));
880
881                    if (mComponentName.startsWith("OMX.google.")) {
882                        mFlags |= kFlagIsSoftwareCodec;
883                    } else {
884                        mFlags &= ~kFlagIsSoftwareCodec;
885                    }
886
887                    if (mComponentName.endsWith(".secure")) {
888                        mFlags |= kFlagIsSecure;
889                    } else {
890                        mFlags &= ~kFlagIsSecure;
891                    }
892
893                    (new AMessage)->postReply(mReplyID);
894                    break;
895                }
896
897                case CodecBase::kWhatComponentConfigured:
898                {
899                    CHECK_EQ(mState, CONFIGURING);
900
901                    // reset input surface flag
902                    mHaveInputSurface = false;
903
904                    CHECK(msg->findMessage("input-format", &mInputFormat));
905                    CHECK(msg->findMessage("output-format", &mOutputFormat));
906
907                    setState(CONFIGURED);
908                    (new AMessage)->postReply(mReplyID);
909                    break;
910                }
911
912                case CodecBase::kWhatInputSurfaceCreated:
913                {
914                    // response to initiateCreateInputSurface()
915                    status_t err = NO_ERROR;
916                    sp<AMessage> response = new AMessage();
917                    if (!msg->findInt32("err", &err)) {
918                        sp<RefBase> obj;
919                        msg->findObject("input-surface", &obj);
920                        CHECK(obj != NULL);
921                        response->setObject("input-surface", obj);
922                        mHaveInputSurface = true;
923                    } else {
924                        response->setInt32("err", err);
925                    }
926                    response->postReply(mReplyID);
927                    break;
928                }
929
930                case CodecBase::kWhatSignaledInputEOS:
931                {
932                    // response to signalEndOfInputStream()
933                    sp<AMessage> response = new AMessage();
934                    status_t err;
935                    if (msg->findInt32("err", &err)) {
936                        response->setInt32("err", err);
937                    }
938                    response->postReply(mReplyID);
939                    break;
940                }
941
942
943                case CodecBase::kWhatBuffersAllocated:
944                {
945                    Mutex::Autolock al(mBufferLock);
946                    int32_t portIndex;
947                    CHECK(msg->findInt32("portIndex", &portIndex));
948
949                    ALOGV("%s buffers allocated",
950                          portIndex == kPortIndexInput ? "input" : "output");
951
952                    CHECK(portIndex == kPortIndexInput
953                            || portIndex == kPortIndexOutput);
954
955                    mPortBuffers[portIndex].clear();
956
957                    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
958
959                    sp<RefBase> obj;
960                    CHECK(msg->findObject("portDesc", &obj));
961
962                    sp<CodecBase::PortDescription> portDesc =
963                        static_cast<CodecBase::PortDescription *>(obj.get());
964
965                    size_t numBuffers = portDesc->countBuffers();
966
967                    for (size_t i = 0; i < numBuffers; ++i) {
968                        BufferInfo info;
969                        info.mBufferID = portDesc->bufferIDAt(i);
970                        info.mOwnedByClient = false;
971                        info.mData = portDesc->bufferAt(i);
972
973                        if (portIndex == kPortIndexInput && mCrypto != NULL) {
974                            info.mEncryptedData =
975                                new ABuffer(info.mData->capacity());
976                        }
977
978                        buffers->push_back(info);
979                    }
980
981                    if (portIndex == kPortIndexOutput) {
982                        if (mState == STARTING) {
983                            // We're always allocating output buffers after
984                            // allocating input buffers, so this is a good
985                            // indication that now all buffers are allocated.
986                            setState(STARTED);
987                            (new AMessage)->postReply(mReplyID);
988                        } else {
989                            mFlags |= kFlagOutputBuffersChanged;
990                            postActivityNotificationIfPossible();
991                        }
992                    }
993                    break;
994                }
995
996                case CodecBase::kWhatOutputFormatChanged:
997                {
998                    ALOGV("codec output format changed");
999
1000                    if (mSoftRenderer == NULL &&
1001                            mNativeWindow != NULL &&
1002                            (mFlags & kFlagIsSoftwareCodec)) {
1003                        AString mime;
1004                        CHECK(msg->findString("mime", &mime));
1005
1006                        if (mime.startsWithIgnoreCase("video/")) {
1007                            mSoftRenderer = new SoftwareRenderer(mNativeWindow);
1008                        }
1009                    }
1010
1011                    mOutputFormat = msg;
1012
1013                    if (mFlags & kFlagIsEncoder) {
1014                        // Before we announce the format change we should
1015                        // collect codec specific data and amend the output
1016                        // format as necessary.
1017                        mFlags |= kFlagGatherCodecSpecificData;
1018                    } else if (mFlags & kFlagIsAsync) {
1019                        onOutputFormatChanged();
1020                    } else {
1021                        mFlags |= kFlagOutputFormatChanged;
1022                        postActivityNotificationIfPossible();
1023                    }
1024                    break;
1025                }
1026
1027                case CodecBase::kWhatFillThisBuffer:
1028                {
1029                    /* size_t index = */updateBuffers(kPortIndexInput, msg);
1030
1031                    if (mState == FLUSHING
1032                            || mState == STOPPING
1033                            || mState == RELEASING) {
1034                        returnBuffersToCodecOnPort(kPortIndexInput);
1035                        break;
1036                    }
1037
1038                    if (!mCSD.empty()) {
1039                        ssize_t index = dequeuePortBuffer(kPortIndexInput);
1040                        CHECK_GE(index, 0);
1041
1042                        // If codec specific data had been specified as
1043                        // part of the format in the call to configure and
1044                        // if there's more csd left, we submit it here
1045                        // clients only get access to input buffers once
1046                        // this data has been exhausted.
1047
1048                        status_t err = queueCSDInputBuffer(index);
1049
1050                        if (err != OK) {
1051                            ALOGE("queueCSDInputBuffer failed w/ error %d",
1052                                  err);
1053
1054                            setStickyError(err);
1055                            postActivityNotificationIfPossible();
1056
1057                            cancelPendingDequeueOperations();
1058                        }
1059                        break;
1060                    }
1061
1062                    if (mFlags & kFlagIsAsync) {
1063                        if (!mHaveInputSurface) {
1064                            onInputBufferAvailable();
1065                        }
1066                    } else if (mFlags & kFlagDequeueInputPending) {
1067                        CHECK(handleDequeueInputBuffer(mDequeueInputReplyID));
1068
1069                        ++mDequeueInputTimeoutGeneration;
1070                        mFlags &= ~kFlagDequeueInputPending;
1071                        mDequeueInputReplyID = 0;
1072                    } else {
1073                        postActivityNotificationIfPossible();
1074                    }
1075                    break;
1076                }
1077
1078                case CodecBase::kWhatDrainThisBuffer:
1079                {
1080                    /* size_t index = */updateBuffers(kPortIndexOutput, msg);
1081
1082                    if (mState == FLUSHING
1083                            || mState == STOPPING
1084                            || mState == RELEASING) {
1085                        returnBuffersToCodecOnPort(kPortIndexOutput);
1086                        break;
1087                    }
1088
1089                    sp<ABuffer> buffer;
1090                    CHECK(msg->findBuffer("buffer", &buffer));
1091
1092                    int32_t omxFlags;
1093                    CHECK(msg->findInt32("flags", &omxFlags));
1094
1095                    buffer->meta()->setInt32("omxFlags", omxFlags);
1096
1097                    if (mFlags & kFlagGatherCodecSpecificData) {
1098                        // This is the very first output buffer after a
1099                        // format change was signalled, it'll either contain
1100                        // the one piece of codec specific data we can expect
1101                        // or there won't be codec specific data.
1102                        if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) {
1103                            status_t err =
1104                                amendOutputFormatWithCodecSpecificData(buffer);
1105
1106                            if (err != OK) {
1107                                ALOGE("Codec spit out malformed codec "
1108                                      "specific data!");
1109                            }
1110                        }
1111
1112                        mFlags &= ~kFlagGatherCodecSpecificData;
1113                        if (mFlags & kFlagIsAsync) {
1114                            onOutputFormatChanged();
1115                        } else {
1116                            mFlags |= kFlagOutputFormatChanged;
1117                        }
1118                    }
1119
1120                    if (mFlags & kFlagIsAsync) {
1121                        onOutputBufferAvailable();
1122                    } else if (mFlags & kFlagDequeueOutputPending) {
1123                        CHECK(handleDequeueOutputBuffer(mDequeueOutputReplyID));
1124
1125                        ++mDequeueOutputTimeoutGeneration;
1126                        mFlags &= ~kFlagDequeueOutputPending;
1127                        mDequeueOutputReplyID = 0;
1128                    } else {
1129                        postActivityNotificationIfPossible();
1130                    }
1131
1132                    break;
1133                }
1134
1135                case CodecBase::kWhatEOS:
1136                {
1137                    // We already notify the client of this by using the
1138                    // corresponding flag in "onOutputBufferReady".
1139                    break;
1140                }
1141
1142                case CodecBase::kWhatShutdownCompleted:
1143                {
1144                    if (mState == STOPPING) {
1145                        setState(INITIALIZED);
1146                    } else {
1147                        CHECK_EQ(mState, RELEASING);
1148                        setState(UNINITIALIZED);
1149                        mComponentName.clear();
1150                    }
1151                    mFlags &= ~kFlagIsComponentAllocated;
1152
1153                    (new AMessage)->postReply(mReplyID);
1154                    break;
1155                }
1156
1157                case CodecBase::kWhatFlushCompleted:
1158                {
1159                    if (mState != FLUSHING) {
1160                        ALOGW("received FlushCompleted message in state %d",
1161                                mState);
1162                        break;
1163                    }
1164
1165                    if (mFlags & kFlagIsAsync) {
1166                        setState(FLUSHED);
1167                    } else {
1168                        setState(STARTED);
1169                        mCodec->signalResume();
1170                    }
1171
1172                    (new AMessage)->postReply(mReplyID);
1173                    break;
1174                }
1175
1176                default:
1177                    TRESPASS();
1178            }
1179            break;
1180        }
1181
1182        case kWhatInit:
1183        {
1184            uint32_t replyID;
1185            CHECK(msg->senderAwaitsResponse(&replyID));
1186
1187            if (mState != UNINITIALIZED) {
1188                PostReplyWithError(replyID, INVALID_OPERATION);
1189                break;
1190            }
1191
1192            mReplyID = replyID;
1193            setState(INITIALIZING);
1194
1195            AString name;
1196            CHECK(msg->findString("name", &name));
1197
1198            int32_t nameIsType;
1199            int32_t encoder = false;
1200            CHECK(msg->findInt32("nameIsType", &nameIsType));
1201            if (nameIsType) {
1202                CHECK(msg->findInt32("encoder", &encoder));
1203            }
1204
1205            sp<AMessage> format = new AMessage;
1206
1207            if (nameIsType) {
1208                format->setString("mime", name.c_str());
1209                format->setInt32("encoder", encoder);
1210            } else {
1211                format->setString("componentName", name.c_str());
1212            }
1213
1214            mCodec->initiateAllocateComponent(format);
1215            break;
1216        }
1217
1218        case kWhatSetCallback:
1219        {
1220            uint32_t replyID;
1221            CHECK(msg->senderAwaitsResponse(&replyID));
1222
1223            if (mState == UNINITIALIZED
1224                    || mState == INITIALIZING
1225                    || isExecuting()) {
1226                // callback can't be set after codec is executing,
1227                // or before it's initialized (as the callback
1228                // will be cleared when it goes to INITIALIZED)
1229                PostReplyWithError(replyID, INVALID_OPERATION);
1230                break;
1231            }
1232
1233            sp<AMessage> callback;
1234            CHECK(msg->findMessage("callback", &callback));
1235
1236            mCallback = callback;
1237
1238            if (mCallback != NULL) {
1239                ALOGI("MediaCodec will operate in async mode");
1240                mFlags |= kFlagIsAsync;
1241            } else {
1242                mFlags &= ~kFlagIsAsync;
1243            }
1244
1245            sp<AMessage> response = new AMessage;
1246            response->postReply(replyID);
1247            break;
1248        }
1249
1250        case kWhatConfigure:
1251        {
1252            uint32_t replyID;
1253            CHECK(msg->senderAwaitsResponse(&replyID));
1254
1255            if (mState != INITIALIZED) {
1256                PostReplyWithError(replyID, INVALID_OPERATION);
1257                break;
1258            }
1259
1260            sp<RefBase> obj;
1261            if (!msg->findObject("native-window", &obj)) {
1262                obj.clear();
1263            }
1264
1265            sp<AMessage> format;
1266            CHECK(msg->findMessage("format", &format));
1267
1268            if (obj != NULL) {
1269                format->setObject("native-window", obj);
1270
1271                status_t err = setNativeWindow(
1272                    static_cast<NativeWindowWrapper *>(obj.get())
1273                        ->getSurfaceTextureClient());
1274
1275                if (err != OK) {
1276                    PostReplyWithError(replyID, err);
1277                    break;
1278                }
1279            } else {
1280                setNativeWindow(NULL);
1281            }
1282
1283            mReplyID = replyID;
1284            setState(CONFIGURING);
1285
1286            void *crypto;
1287            if (!msg->findPointer("crypto", &crypto)) {
1288                crypto = NULL;
1289            }
1290
1291            mCrypto = static_cast<ICrypto *>(crypto);
1292
1293            uint32_t flags;
1294            CHECK(msg->findInt32("flags", (int32_t *)&flags));
1295
1296            if (flags & CONFIGURE_FLAG_ENCODE) {
1297                format->setInt32("encoder", true);
1298                mFlags |= kFlagIsEncoder;
1299            }
1300
1301            extractCSD(format);
1302
1303            mCodec->initiateConfigureComponent(format);
1304            break;
1305        }
1306
1307        case kWhatCreateInputSurface:
1308        {
1309            uint32_t replyID;
1310            CHECK(msg->senderAwaitsResponse(&replyID));
1311
1312            // Must be configured, but can't have been started yet.
1313            if (mState != CONFIGURED) {
1314                PostReplyWithError(replyID, INVALID_OPERATION);
1315                break;
1316            }
1317
1318            mReplyID = replyID;
1319            mCodec->initiateCreateInputSurface();
1320            break;
1321        }
1322
1323        case kWhatStart:
1324        {
1325            uint32_t replyID;
1326            CHECK(msg->senderAwaitsResponse(&replyID));
1327
1328            if (mState == FLUSHED) {
1329                mCodec->signalResume();
1330                PostReplyWithError(replyID, OK);
1331            } else if (mState != CONFIGURED) {
1332                PostReplyWithError(replyID, INVALID_OPERATION);
1333                break;
1334            }
1335
1336            mReplyID = replyID;
1337            setState(STARTING);
1338
1339            mCodec->initiateStart();
1340            break;
1341        }
1342
1343        case kWhatStop:
1344        case kWhatRelease:
1345        {
1346            State targetState =
1347                (msg->what() == kWhatStop) ? INITIALIZED : UNINITIALIZED;
1348
1349            uint32_t replyID;
1350            CHECK(msg->senderAwaitsResponse(&replyID));
1351
1352            if (!(mFlags & kFlagIsComponentAllocated) && mState != INITIALIZED
1353                    && mState != CONFIGURED && !isExecuting()) {
1354                // We may be in "UNINITIALIZED" state already and
1355                // also shutdown the encoder/decoder without the
1356                // client being aware of this if media server died while
1357                // we were being stopped. The client would assume that
1358                // after stop() returned, it would be safe to call release()
1359                // and it should be in this case, no harm to allow a release()
1360                // if we're already uninitialized.
1361                sp<AMessage> response = new AMessage;
1362                status_t err = mState == targetState ? OK : INVALID_OPERATION;
1363                response->setInt32("err", err);
1364                if (err == OK && targetState == UNINITIALIZED) {
1365                    mComponentName.clear();
1366                }
1367                response->postReply(replyID);
1368                break;
1369            }
1370
1371            if (mFlags & kFlagSawMediaServerDie) {
1372                // It's dead, Jim. Don't expect initiateShutdown to yield
1373                // any useful results now...
1374                setState(UNINITIALIZED);
1375                if (targetState == UNINITIALIZED) {
1376                    mComponentName.clear();
1377                }
1378                (new AMessage)->postReply(replyID);
1379                break;
1380            }
1381
1382            mReplyID = replyID;
1383            setState(msg->what() == kWhatStop ? STOPPING : RELEASING);
1384
1385            mCodec->initiateShutdown(
1386                    msg->what() == kWhatStop /* keepComponentAllocated */);
1387
1388            returnBuffersToCodec();
1389            break;
1390        }
1391
1392        case kWhatDequeueInputBuffer:
1393        {
1394            uint32_t replyID;
1395            CHECK(msg->senderAwaitsResponse(&replyID));
1396
1397            if (mFlags & kFlagIsAsync) {
1398                ALOGE("dequeueOutputBuffer can't be used in async mode");
1399                PostReplyWithError(replyID, INVALID_OPERATION);
1400                break;
1401            }
1402
1403            if (mHaveInputSurface) {
1404                ALOGE("dequeueInputBuffer can't be used with input surface");
1405                PostReplyWithError(replyID, INVALID_OPERATION);
1406                break;
1407            }
1408
1409            if (handleDequeueInputBuffer(replyID, true /* new request */)) {
1410                break;
1411            }
1412
1413            int64_t timeoutUs;
1414            CHECK(msg->findInt64("timeoutUs", &timeoutUs));
1415
1416            if (timeoutUs == 0ll) {
1417                PostReplyWithError(replyID, -EAGAIN);
1418                break;
1419            }
1420
1421            mFlags |= kFlagDequeueInputPending;
1422            mDequeueInputReplyID = replyID;
1423
1424            if (timeoutUs > 0ll) {
1425                sp<AMessage> timeoutMsg =
1426                    new AMessage(kWhatDequeueInputTimedOut, id());
1427                timeoutMsg->setInt32(
1428                        "generation", ++mDequeueInputTimeoutGeneration);
1429                timeoutMsg->post(timeoutUs);
1430            }
1431            break;
1432        }
1433
1434        case kWhatDequeueInputTimedOut:
1435        {
1436            int32_t generation;
1437            CHECK(msg->findInt32("generation", &generation));
1438
1439            if (generation != mDequeueInputTimeoutGeneration) {
1440                // Obsolete
1441                break;
1442            }
1443
1444            CHECK(mFlags & kFlagDequeueInputPending);
1445
1446            PostReplyWithError(mDequeueInputReplyID, -EAGAIN);
1447
1448            mFlags &= ~kFlagDequeueInputPending;
1449            mDequeueInputReplyID = 0;
1450            break;
1451        }
1452
1453        case kWhatQueueInputBuffer:
1454        {
1455            uint32_t replyID;
1456            CHECK(msg->senderAwaitsResponse(&replyID));
1457
1458            if (!isExecuting()) {
1459                PostReplyWithError(replyID, INVALID_OPERATION);
1460                break;
1461            } else if (mFlags & kFlagStickyError) {
1462                PostReplyWithError(replyID, getStickyError());
1463                break;
1464            }
1465
1466            status_t err = onQueueInputBuffer(msg);
1467
1468            PostReplyWithError(replyID, err);
1469            break;
1470        }
1471
1472        case kWhatDequeueOutputBuffer:
1473        {
1474            uint32_t replyID;
1475            CHECK(msg->senderAwaitsResponse(&replyID));
1476
1477            if (mFlags & kFlagIsAsync) {
1478                ALOGE("dequeueOutputBuffer can't be used in async mode");
1479                PostReplyWithError(replyID, INVALID_OPERATION);
1480                break;
1481            }
1482
1483            if (handleDequeueOutputBuffer(replyID, true /* new request */)) {
1484                break;
1485            }
1486
1487            int64_t timeoutUs;
1488            CHECK(msg->findInt64("timeoutUs", &timeoutUs));
1489
1490            if (timeoutUs == 0ll) {
1491                PostReplyWithError(replyID, -EAGAIN);
1492                break;
1493            }
1494
1495            mFlags |= kFlagDequeueOutputPending;
1496            mDequeueOutputReplyID = replyID;
1497
1498            if (timeoutUs > 0ll) {
1499                sp<AMessage> timeoutMsg =
1500                    new AMessage(kWhatDequeueOutputTimedOut, id());
1501                timeoutMsg->setInt32(
1502                        "generation", ++mDequeueOutputTimeoutGeneration);
1503                timeoutMsg->post(timeoutUs);
1504            }
1505            break;
1506        }
1507
1508        case kWhatDequeueOutputTimedOut:
1509        {
1510            int32_t generation;
1511            CHECK(msg->findInt32("generation", &generation));
1512
1513            if (generation != mDequeueOutputTimeoutGeneration) {
1514                // Obsolete
1515                break;
1516            }
1517
1518            CHECK(mFlags & kFlagDequeueOutputPending);
1519
1520            PostReplyWithError(mDequeueOutputReplyID, -EAGAIN);
1521
1522            mFlags &= ~kFlagDequeueOutputPending;
1523            mDequeueOutputReplyID = 0;
1524            break;
1525        }
1526
1527        case kWhatReleaseOutputBuffer:
1528        {
1529            uint32_t replyID;
1530            CHECK(msg->senderAwaitsResponse(&replyID));
1531
1532            if (!isExecuting()) {
1533                PostReplyWithError(replyID, INVALID_OPERATION);
1534                break;
1535            } else if (mFlags & kFlagStickyError) {
1536                PostReplyWithError(replyID, getStickyError());
1537                break;
1538            }
1539
1540            status_t err = onReleaseOutputBuffer(msg);
1541
1542            PostReplyWithError(replyID, err);
1543            break;
1544        }
1545
1546        case kWhatSignalEndOfInputStream:
1547        {
1548            uint32_t replyID;
1549            CHECK(msg->senderAwaitsResponse(&replyID));
1550
1551            if (!isExecuting()) {
1552                PostReplyWithError(replyID, INVALID_OPERATION);
1553                break;
1554            } else if (mFlags & kFlagStickyError) {
1555                PostReplyWithError(replyID, getStickyError());
1556                break;
1557            }
1558
1559            mReplyID = replyID;
1560            mCodec->signalEndOfInputStream();
1561            break;
1562        }
1563
1564        case kWhatGetBuffers:
1565        {
1566            uint32_t replyID;
1567            CHECK(msg->senderAwaitsResponse(&replyID));
1568
1569            if (!isExecuting() || (mFlags & kFlagIsAsync)) {
1570                PostReplyWithError(replyID, INVALID_OPERATION);
1571                break;
1572            } else if (mFlags & kFlagStickyError) {
1573                PostReplyWithError(replyID, getStickyError());
1574                break;
1575            }
1576
1577            int32_t portIndex;
1578            CHECK(msg->findInt32("portIndex", &portIndex));
1579
1580            Vector<sp<ABuffer> > *dstBuffers;
1581            CHECK(msg->findPointer("buffers", (void **)&dstBuffers));
1582
1583            dstBuffers->clear();
1584            const Vector<BufferInfo> &srcBuffers = mPortBuffers[portIndex];
1585
1586            for (size_t i = 0; i < srcBuffers.size(); ++i) {
1587                const BufferInfo &info = srcBuffers.itemAt(i);
1588
1589                dstBuffers->push_back(
1590                        (portIndex == kPortIndexInput && mCrypto != NULL)
1591                                ? info.mEncryptedData : info.mData);
1592            }
1593
1594            (new AMessage)->postReply(replyID);
1595            break;
1596        }
1597
1598        case kWhatFlush:
1599        {
1600            uint32_t replyID;
1601            CHECK(msg->senderAwaitsResponse(&replyID));
1602
1603            if (!isExecuting()) {
1604                PostReplyWithError(replyID, INVALID_OPERATION);
1605                break;
1606            } else if (mFlags & kFlagStickyError) {
1607                PostReplyWithError(replyID, getStickyError());
1608                break;
1609            }
1610
1611            mReplyID = replyID;
1612            // TODO: skip flushing if already FLUSHED
1613            setState(FLUSHING);
1614
1615            mCodec->signalFlush();
1616            returnBuffersToCodec();
1617            break;
1618        }
1619
1620        case kWhatGetInputFormat:
1621        case kWhatGetOutputFormat:
1622        {
1623            sp<AMessage> format =
1624                (msg->what() == kWhatGetOutputFormat ? mOutputFormat : mInputFormat);
1625
1626            uint32_t replyID;
1627            CHECK(msg->senderAwaitsResponse(&replyID));
1628
1629            if ((mState != CONFIGURED && mState != STARTING &&
1630                 mState != STARTED && mState != FLUSHING &&
1631                 mState != FLUSHED)
1632                    || format == NULL) {
1633                PostReplyWithError(replyID, INVALID_OPERATION);
1634                break;
1635            } else if (mFlags & kFlagStickyError) {
1636                PostReplyWithError(replyID, getStickyError());
1637                break;
1638            }
1639
1640            sp<AMessage> response = new AMessage;
1641            response->setMessage("format", format);
1642            response->postReply(replyID);
1643            break;
1644        }
1645
1646        case kWhatRequestIDRFrame:
1647        {
1648            mCodec->signalRequestIDRFrame();
1649            break;
1650        }
1651
1652        case kWhatRequestActivityNotification:
1653        {
1654            CHECK(mActivityNotify == NULL);
1655            CHECK(msg->findMessage("notify", &mActivityNotify));
1656
1657            postActivityNotificationIfPossible();
1658            break;
1659        }
1660
1661        case kWhatGetName:
1662        {
1663            uint32_t replyID;
1664            CHECK(msg->senderAwaitsResponse(&replyID));
1665
1666            if (mComponentName.empty()) {
1667                PostReplyWithError(replyID, INVALID_OPERATION);
1668                break;
1669            }
1670
1671            sp<AMessage> response = new AMessage;
1672            response->setString("name", mComponentName.c_str());
1673            response->postReply(replyID);
1674            break;
1675        }
1676
1677        case kWhatSetParameters:
1678        {
1679            uint32_t replyID;
1680            CHECK(msg->senderAwaitsResponse(&replyID));
1681
1682            sp<AMessage> params;
1683            CHECK(msg->findMessage("params", &params));
1684
1685            status_t err = onSetParameters(params);
1686
1687            PostReplyWithError(replyID, err);
1688            break;
1689        }
1690
1691        default:
1692            TRESPASS();
1693    }
1694}
1695
1696void MediaCodec::extractCSD(const sp<AMessage> &format) {
1697    mCSD.clear();
1698
1699    size_t i = 0;
1700    for (;;) {
1701        sp<ABuffer> csd;
1702        if (!format->findBuffer(StringPrintf("csd-%u", i).c_str(), &csd)) {
1703            break;
1704        }
1705
1706        mCSD.push_back(csd);
1707        ++i;
1708    }
1709
1710    ALOGV("Found %zu pieces of codec specific data.", mCSD.size());
1711}
1712
1713status_t MediaCodec::queueCSDInputBuffer(size_t bufferIndex) {
1714    CHECK(!mCSD.empty());
1715
1716    const BufferInfo *info =
1717        &mPortBuffers[kPortIndexInput].itemAt(bufferIndex);
1718
1719    sp<ABuffer> csd = *mCSD.begin();
1720    mCSD.erase(mCSD.begin());
1721
1722    const sp<ABuffer> &codecInputData =
1723        (mCrypto != NULL) ? info->mEncryptedData : info->mData;
1724
1725    if (csd->size() > codecInputData->capacity()) {
1726        return -EINVAL;
1727    }
1728
1729    memcpy(codecInputData->data(), csd->data(), csd->size());
1730
1731    AString errorDetailMsg;
1732
1733    sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, id());
1734    msg->setSize("index", bufferIndex);
1735    msg->setSize("offset", 0);
1736    msg->setSize("size", csd->size());
1737    msg->setInt64("timeUs", 0ll);
1738    msg->setInt32("flags", BUFFER_FLAG_CODECCONFIG);
1739    msg->setPointer("errorDetailMsg", &errorDetailMsg);
1740
1741    return onQueueInputBuffer(msg);
1742}
1743
1744void MediaCodec::setState(State newState) {
1745    if (newState == INITIALIZED || newState == UNINITIALIZED) {
1746        delete mSoftRenderer;
1747        mSoftRenderer = NULL;
1748
1749        mCrypto.clear();
1750        setNativeWindow(NULL);
1751
1752        mInputFormat.clear();
1753        mOutputFormat.clear();
1754        mFlags &= ~kFlagOutputFormatChanged;
1755        mFlags &= ~kFlagOutputBuffersChanged;
1756        mFlags &= ~kFlagStickyError;
1757        mFlags &= ~kFlagIsEncoder;
1758        mFlags &= ~kFlagGatherCodecSpecificData;
1759        mFlags &= ~kFlagIsAsync;
1760        mStickyError = OK;
1761
1762        mActivityNotify.clear();
1763        mCallback.clear();
1764    }
1765
1766    if (newState == UNINITIALIZED) {
1767        // return any straggling buffers, e.g. if we got here on an error
1768        returnBuffersToCodec();
1769
1770        // The component is gone, mediaserver's probably back up already
1771        // but should definitely be back up should we try to instantiate
1772        // another component.. and the cycle continues.
1773        mFlags &= ~kFlagSawMediaServerDie;
1774    }
1775
1776    mState = newState;
1777
1778    cancelPendingDequeueOperations();
1779
1780    updateBatteryStat();
1781}
1782
1783void MediaCodec::returnBuffersToCodec() {
1784    returnBuffersToCodecOnPort(kPortIndexInput);
1785    returnBuffersToCodecOnPort(kPortIndexOutput);
1786}
1787
1788void MediaCodec::returnBuffersToCodecOnPort(int32_t portIndex) {
1789    CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput);
1790    Mutex::Autolock al(mBufferLock);
1791
1792    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
1793
1794    for (size_t i = 0; i < buffers->size(); ++i) {
1795        BufferInfo *info = &buffers->editItemAt(i);
1796
1797        if (info->mNotify != NULL) {
1798            sp<AMessage> msg = info->mNotify;
1799            info->mNotify = NULL;
1800            info->mOwnedByClient = false;
1801
1802            if (portIndex == kPortIndexInput) {
1803                /* no error, just returning buffers */
1804                msg->setInt32("err", OK);
1805            }
1806            msg->post();
1807        }
1808    }
1809
1810    mAvailPortBuffers[portIndex].clear();
1811}
1812
1813size_t MediaCodec::updateBuffers(
1814        int32_t portIndex, const sp<AMessage> &msg) {
1815    CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput);
1816
1817    uint32_t bufferID;
1818    CHECK(msg->findInt32("buffer-id", (int32_t*)&bufferID));
1819
1820    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
1821
1822    for (size_t i = 0; i < buffers->size(); ++i) {
1823        BufferInfo *info = &buffers->editItemAt(i);
1824
1825        if (info->mBufferID == bufferID) {
1826            CHECK(info->mNotify == NULL);
1827            CHECK(msg->findMessage("reply", &info->mNotify));
1828
1829            info->mFormat =
1830                (portIndex == kPortIndexInput) ? mInputFormat : mOutputFormat;
1831            mAvailPortBuffers[portIndex].push_back(i);
1832
1833            return i;
1834        }
1835    }
1836
1837    TRESPASS();
1838
1839    return 0;
1840}
1841
1842status_t MediaCodec::onQueueInputBuffer(const sp<AMessage> &msg) {
1843    size_t index;
1844    size_t offset;
1845    size_t size;
1846    int64_t timeUs;
1847    uint32_t flags;
1848    CHECK(msg->findSize("index", &index));
1849    CHECK(msg->findSize("offset", &offset));
1850    CHECK(msg->findInt64("timeUs", &timeUs));
1851    CHECK(msg->findInt32("flags", (int32_t *)&flags));
1852
1853    const CryptoPlugin::SubSample *subSamples;
1854    size_t numSubSamples;
1855    const uint8_t *key;
1856    const uint8_t *iv;
1857    CryptoPlugin::Mode mode = CryptoPlugin::kMode_Unencrypted;
1858
1859    // We allow the simpler queueInputBuffer API to be used even in
1860    // secure mode, by fabricating a single unencrypted subSample.
1861    CryptoPlugin::SubSample ss;
1862
1863    if (msg->findSize("size", &size)) {
1864        if (mCrypto != NULL) {
1865            ss.mNumBytesOfClearData = size;
1866            ss.mNumBytesOfEncryptedData = 0;
1867
1868            subSamples = &ss;
1869            numSubSamples = 1;
1870            key = NULL;
1871            iv = NULL;
1872        }
1873    } else {
1874        if (mCrypto == NULL) {
1875            return -EINVAL;
1876        }
1877
1878        CHECK(msg->findPointer("subSamples", (void **)&subSamples));
1879        CHECK(msg->findSize("numSubSamples", &numSubSamples));
1880        CHECK(msg->findPointer("key", (void **)&key));
1881        CHECK(msg->findPointer("iv", (void **)&iv));
1882
1883        int32_t tmp;
1884        CHECK(msg->findInt32("mode", &tmp));
1885
1886        mode = (CryptoPlugin::Mode)tmp;
1887
1888        size = 0;
1889        for (size_t i = 0; i < numSubSamples; ++i) {
1890            size += subSamples[i].mNumBytesOfClearData;
1891            size += subSamples[i].mNumBytesOfEncryptedData;
1892        }
1893    }
1894
1895    if (index >= mPortBuffers[kPortIndexInput].size()) {
1896        return -ERANGE;
1897    }
1898
1899    BufferInfo *info = &mPortBuffers[kPortIndexInput].editItemAt(index);
1900
1901    if (info->mNotify == NULL || !info->mOwnedByClient) {
1902        return -EACCES;
1903    }
1904
1905    if (offset + size > info->mData->capacity()) {
1906        return -EINVAL;
1907    }
1908
1909    sp<AMessage> reply = info->mNotify;
1910    info->mData->setRange(offset, size);
1911    info->mData->meta()->setInt64("timeUs", timeUs);
1912
1913    if (flags & BUFFER_FLAG_EOS) {
1914        info->mData->meta()->setInt32("eos", true);
1915    }
1916
1917    if (flags & BUFFER_FLAG_CODECCONFIG) {
1918        info->mData->meta()->setInt32("csd", true);
1919    }
1920
1921    if (mCrypto != NULL) {
1922        if (size > info->mEncryptedData->capacity()) {
1923            return -ERANGE;
1924        }
1925
1926        AString *errorDetailMsg;
1927        CHECK(msg->findPointer("errorDetailMsg", (void **)&errorDetailMsg));
1928
1929        ssize_t result = mCrypto->decrypt(
1930                (mFlags & kFlagIsSecure) != 0,
1931                key,
1932                iv,
1933                mode,
1934                info->mEncryptedData->base() + offset,
1935                subSamples,
1936                numSubSamples,
1937                info->mData->base(),
1938                errorDetailMsg);
1939
1940        if (result < 0) {
1941            return result;
1942        }
1943
1944        info->mData->setRange(0, result);
1945    }
1946
1947    // synchronization boundary for getBufferAndFormat
1948    {
1949        Mutex::Autolock al(mBufferLock);
1950        info->mOwnedByClient = false;
1951    }
1952    reply->setBuffer("buffer", info->mData);
1953    reply->post();
1954
1955    info->mNotify = NULL;
1956
1957    return OK;
1958}
1959
1960status_t MediaCodec::onReleaseOutputBuffer(const sp<AMessage> &msg) {
1961    size_t index;
1962    CHECK(msg->findSize("index", &index));
1963
1964    int32_t render;
1965    if (!msg->findInt32("render", &render)) {
1966        render = 0;
1967    }
1968
1969    if (!isExecuting()) {
1970        return -EINVAL;
1971    }
1972
1973    if (index >= mPortBuffers[kPortIndexOutput].size()) {
1974        return -ERANGE;
1975    }
1976
1977    BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index);
1978
1979    if (info->mNotify == NULL || !info->mOwnedByClient) {
1980        return -EACCES;
1981    }
1982
1983    // synchronization boundary for getBufferAndFormat
1984    {
1985        Mutex::Autolock al(mBufferLock);
1986        info->mOwnedByClient = false;
1987    }
1988
1989    if (render && info->mData != NULL && info->mData->size() != 0) {
1990        info->mNotify->setInt32("render", true);
1991
1992        int64_t timestampNs = 0;
1993        if (msg->findInt64("timestampNs", &timestampNs)) {
1994            info->mNotify->setInt64("timestampNs", timestampNs);
1995        } else {
1996            // TODO: it seems like we should use the timestamp
1997            // in the (media)buffer as it potentially came from
1998            // an input surface, but we did not propagate it prior to
1999            // API 20.  Perhaps check for target SDK version.
2000#if 0
2001            if (info->mData->meta()->findInt64("timeUs", &timestampNs)) {
2002                ALOGV("using buffer PTS of %" PRId64, timestampNs);
2003                timestampNs *= 1000;
2004            }
2005#endif
2006        }
2007
2008        if (mSoftRenderer != NULL) {
2009            mSoftRenderer->render(
2010                    info->mData->data(), info->mData->size(),
2011                    timestampNs, NULL, info->mFormat);
2012        }
2013    }
2014
2015    info->mNotify->post();
2016    info->mNotify = NULL;
2017
2018    return OK;
2019}
2020
2021ssize_t MediaCodec::dequeuePortBuffer(int32_t portIndex) {
2022    CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput);
2023
2024    List<size_t> *availBuffers = &mAvailPortBuffers[portIndex];
2025
2026    if (availBuffers->empty()) {
2027        return -EAGAIN;
2028    }
2029
2030    size_t index = *availBuffers->begin();
2031    availBuffers->erase(availBuffers->begin());
2032
2033    BufferInfo *info = &mPortBuffers[portIndex].editItemAt(index);
2034    CHECK(!info->mOwnedByClient);
2035    {
2036        Mutex::Autolock al(mBufferLock);
2037        info->mOwnedByClient = true;
2038
2039        // set image-data
2040        if (info->mFormat != NULL) {
2041            sp<ABuffer> imageData;
2042            if (info->mFormat->findBuffer("image-data", &imageData)) {
2043                info->mData->meta()->setBuffer("image-data", imageData);
2044            }
2045            int32_t left, top, right, bottom;
2046            if (info->mFormat->findRect("crop", &left, &top, &right, &bottom)) {
2047                info->mData->meta()->setRect("crop-rect", left, top, right, bottom);
2048            }
2049        }
2050    }
2051
2052    return index;
2053}
2054
2055status_t MediaCodec::setNativeWindow(
2056        const sp<Surface> &surfaceTextureClient) {
2057    status_t err;
2058
2059    if (mNativeWindow != NULL) {
2060        err = native_window_api_disconnect(
2061                mNativeWindow.get(), NATIVE_WINDOW_API_MEDIA);
2062
2063        if (err != OK) {
2064            ALOGW("native_window_api_disconnect returned an error: %s (%d)",
2065                    strerror(-err), err);
2066        }
2067
2068        mNativeWindow.clear();
2069    }
2070
2071    if (surfaceTextureClient != NULL) {
2072        err = native_window_api_connect(
2073                surfaceTextureClient.get(), NATIVE_WINDOW_API_MEDIA);
2074
2075        if (err != OK) {
2076            ALOGE("native_window_api_connect returned an error: %s (%d)",
2077                    strerror(-err), err);
2078
2079            return err;
2080        }
2081
2082        mNativeWindow = surfaceTextureClient;
2083    }
2084
2085    return OK;
2086}
2087
2088void MediaCodec::onInputBufferAvailable() {
2089    int32_t index;
2090    while ((index = dequeuePortBuffer(kPortIndexInput)) >= 0) {
2091        sp<AMessage> msg = mCallback->dup();
2092        msg->setInt32("callbackID", CB_INPUT_AVAILABLE);
2093        msg->setInt32("index", index);
2094        msg->post();
2095    }
2096}
2097
2098void MediaCodec::onOutputBufferAvailable() {
2099    int32_t index;
2100    while ((index = dequeuePortBuffer(kPortIndexOutput)) >= 0) {
2101        const sp<ABuffer> &buffer =
2102            mPortBuffers[kPortIndexOutput].itemAt(index).mData;
2103        sp<AMessage> msg = mCallback->dup();
2104        msg->setInt32("callbackID", CB_OUTPUT_AVAILABLE);
2105        msg->setInt32("index", index);
2106        msg->setSize("offset", buffer->offset());
2107        msg->setSize("size", buffer->size());
2108
2109        int64_t timeUs;
2110        CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2111
2112        msg->setInt64("timeUs", timeUs);
2113
2114        int32_t omxFlags;
2115        CHECK(buffer->meta()->findInt32("omxFlags", &omxFlags));
2116
2117        uint32_t flags = 0;
2118        if (omxFlags & OMX_BUFFERFLAG_SYNCFRAME) {
2119            flags |= BUFFER_FLAG_SYNCFRAME;
2120        }
2121        if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) {
2122            flags |= BUFFER_FLAG_CODECCONFIG;
2123        }
2124        if (omxFlags & OMX_BUFFERFLAG_EOS) {
2125            flags |= BUFFER_FLAG_EOS;
2126        }
2127
2128        msg->setInt32("flags", flags);
2129
2130        msg->post();
2131    }
2132}
2133
2134void MediaCodec::onError(status_t err, int32_t actionCode, const char *detail) {
2135    if (mCallback != NULL) {
2136        sp<AMessage> msg = mCallback->dup();
2137        msg->setInt32("callbackID", CB_ERROR);
2138        msg->setInt32("err", err);
2139        msg->setInt32("actionCode", actionCode);
2140
2141        if (detail != NULL) {
2142            msg->setString("detail", detail);
2143        }
2144
2145        msg->post();
2146    }
2147}
2148
2149void MediaCodec::onOutputFormatChanged() {
2150    if (mCallback != NULL) {
2151        sp<AMessage> msg = mCallback->dup();
2152        msg->setInt32("callbackID", CB_OUTPUT_FORMAT_CHANGED);
2153        msg->setMessage("format", mOutputFormat);
2154        msg->post();
2155    }
2156}
2157
2158
2159void MediaCodec::postActivityNotificationIfPossible() {
2160    if (mActivityNotify == NULL) {
2161        return;
2162    }
2163
2164    bool isErrorOrOutputChanged =
2165            (mFlags & (kFlagStickyError
2166                    | kFlagOutputBuffersChanged
2167                    | kFlagOutputFormatChanged));
2168
2169    if (isErrorOrOutputChanged
2170            || !mAvailPortBuffers[kPortIndexInput].empty()
2171            || !mAvailPortBuffers[kPortIndexOutput].empty()) {
2172        mActivityNotify->setInt32("input-buffers",
2173                mAvailPortBuffers[kPortIndexInput].size());
2174
2175        if (isErrorOrOutputChanged) {
2176            // we want consumer to dequeue as many times as it can
2177            mActivityNotify->setInt32("output-buffers", INT32_MAX);
2178        } else {
2179            mActivityNotify->setInt32("output-buffers",
2180                    mAvailPortBuffers[kPortIndexOutput].size());
2181        }
2182        mActivityNotify->post();
2183        mActivityNotify.clear();
2184    }
2185}
2186
2187status_t MediaCodec::setParameters(const sp<AMessage> &params) {
2188    sp<AMessage> msg = new AMessage(kWhatSetParameters, id());
2189    msg->setMessage("params", params);
2190
2191    sp<AMessage> response;
2192    return PostAndAwaitResponse(msg, &response);
2193}
2194
2195status_t MediaCodec::onSetParameters(const sp<AMessage> &params) {
2196    mCodec->signalSetParameters(params);
2197
2198    return OK;
2199}
2200
2201status_t MediaCodec::amendOutputFormatWithCodecSpecificData(
2202        const sp<ABuffer> &buffer) {
2203    AString mime;
2204    CHECK(mOutputFormat->findString("mime", &mime));
2205
2206    if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_VIDEO_AVC)) {
2207        // Codec specific data should be SPS and PPS in a single buffer,
2208        // each prefixed by a startcode (0x00 0x00 0x00 0x01).
2209        // We separate the two and put them into the output format
2210        // under the keys "csd-0" and "csd-1".
2211
2212        unsigned csdIndex = 0;
2213
2214        const uint8_t *data = buffer->data();
2215        size_t size = buffer->size();
2216
2217        const uint8_t *nalStart;
2218        size_t nalSize;
2219        while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
2220            sp<ABuffer> csd = new ABuffer(nalSize + 4);
2221            memcpy(csd->data(), "\x00\x00\x00\x01", 4);
2222            memcpy(csd->data() + 4, nalStart, nalSize);
2223
2224            mOutputFormat->setBuffer(
2225                    StringPrintf("csd-%u", csdIndex).c_str(), csd);
2226
2227            ++csdIndex;
2228        }
2229
2230        if (csdIndex != 2) {
2231            return ERROR_MALFORMED;
2232        }
2233    } else {
2234        // For everything else we just stash the codec specific data into
2235        // the output format as a single piece of csd under "csd-0".
2236        mOutputFormat->setBuffer("csd-0", buffer);
2237    }
2238
2239    return OK;
2240}
2241
2242void MediaCodec::updateBatteryStat() {
2243    if (mState == CONFIGURED && !mBatteryStatNotified) {
2244        AString mime;
2245        CHECK(mOutputFormat != NULL &&
2246                mOutputFormat->findString("mime", &mime));
2247
2248        mIsVideo = mime.startsWithIgnoreCase("video/");
2249
2250        BatteryNotifier& notifier(BatteryNotifier::getInstance());
2251
2252        if (mIsVideo) {
2253            notifier.noteStartVideo();
2254        } else {
2255            notifier.noteStartAudio();
2256        }
2257
2258        mBatteryStatNotified = true;
2259    } else if (mState == UNINITIALIZED && mBatteryStatNotified) {
2260        BatteryNotifier& notifier(BatteryNotifier::getInstance());
2261
2262        if (mIsVideo) {
2263            notifier.noteStopVideo();
2264        } else {
2265            notifier.noteStopAudio();
2266        }
2267
2268        mBatteryStatNotified = false;
2269    }
2270}
2271
2272}  // namespace android
2273