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