MediaCodec.cpp revision c22c695660ed9edaba0d4cd7c0ab3a794216fe80
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(actionCode == ACTION_CODE_FATAL ?
737                                    UNINITIALIZED : INITIALIZED);
738                            break;
739                        }
740
741                        case STARTING:
742                        {
743                            setState(actionCode == ACTION_CODE_FATAL ?
744                                    UNINITIALIZED : CONFIGURED);
745                            break;
746                        }
747
748                        case STOPPING:
749                        case RELEASING:
750                        {
751                            // Ignore the error, assuming we'll still get
752                            // the shutdown complete notification.
753
754                            sendErrorResponse = false;
755
756                            if (mFlags & kFlagSawMediaServerDie) {
757                                // MediaServer died, there definitely won't
758                                // be a shutdown complete notification after
759                                // all.
760
761                                // note that we're directly going from
762                                // STOPPING->UNINITIALIZED, instead of the
763                                // usual STOPPING->INITIALIZED state.
764                                setState(UNINITIALIZED);
765
766                                (new AMessage)->postReply(mReplyID);
767                            }
768                            break;
769                        }
770
771                        case FLUSHING:
772                        {
773                            if (actionCode == ACTION_CODE_FATAL) {
774                                setState(UNINITIALIZED);
775                            } else {
776                                setState(
777                                        (mFlags & kFlagIsAsync) ? FLUSHED : STARTED);
778                            }
779                            break;
780                        }
781
782                        case FLUSHED:
783                        case STARTED:
784                        {
785                            sendErrorResponse = false;
786
787                            setStickyError(err);
788                            postActivityNotificationIfPossible();
789
790                            cancelPendingDequeueOperations();
791
792                            if (mFlags & kFlagIsAsync) {
793                                onError(err, actionCode);
794                            }
795                            switch (actionCode) {
796                            case ACTION_CODE_TRANSIENT:
797                                break;
798                            case ACTION_CODE_RECOVERABLE:
799                                setState(INITIALIZED);
800                                break;
801                            default:
802                                setState(UNINITIALIZED);
803                                break;
804                            }
805                            break;
806                        }
807
808                        default:
809                        {
810                            sendErrorResponse = false;
811
812                            setStickyError(err);
813                            postActivityNotificationIfPossible();
814
815                            // actionCode in an uninitialized state is always fatal.
816                            if (mState == UNINITIALIZED) {
817                                actionCode = ACTION_CODE_FATAL;
818                            }
819                            if (mFlags & kFlagIsAsync) {
820                                onError(err, actionCode);
821                            }
822                            switch (actionCode) {
823                            case ACTION_CODE_TRANSIENT:
824                                break;
825                            case ACTION_CODE_RECOVERABLE:
826                                setState(INITIALIZED);
827                                break;
828                            default:
829                                setState(UNINITIALIZED);
830                                break;
831                            }
832                            break;
833                        }
834                    }
835
836                    if (sendErrorResponse) {
837                        PostReplyWithError(mReplyID, err);
838                    }
839                    break;
840                }
841
842                case CodecBase::kWhatComponentAllocated:
843                {
844                    CHECK_EQ(mState, INITIALIZING);
845                    setState(INITIALIZED);
846
847                    CHECK(msg->findString("componentName", &mComponentName));
848
849                    if (mComponentName.startsWith("OMX.google.")) {
850                        mFlags |= kFlagIsSoftwareCodec;
851                    } else {
852                        mFlags &= ~kFlagIsSoftwareCodec;
853                    }
854
855                    if (mComponentName.endsWith(".secure")) {
856                        mFlags |= kFlagIsSecure;
857                    } else {
858                        mFlags &= ~kFlagIsSecure;
859                    }
860
861                    (new AMessage)->postReply(mReplyID);
862                    break;
863                }
864
865                case CodecBase::kWhatComponentConfigured:
866                {
867                    CHECK_EQ(mState, CONFIGURING);
868
869                    // reset input surface flag
870                    mHaveInputSurface = false;
871
872                    CHECK(msg->findMessage("input-format", &mInputFormat));
873                    CHECK(msg->findMessage("output-format", &mOutputFormat));
874
875                    setState(CONFIGURED);
876                    (new AMessage)->postReply(mReplyID);
877                    break;
878                }
879
880                case CodecBase::kWhatInputSurfaceCreated:
881                {
882                    // response to initiateCreateInputSurface()
883                    status_t err = NO_ERROR;
884                    sp<AMessage> response = new AMessage();
885                    if (!msg->findInt32("err", &err)) {
886                        sp<RefBase> obj;
887                        msg->findObject("input-surface", &obj);
888                        CHECK(obj != NULL);
889                        response->setObject("input-surface", obj);
890                        mHaveInputSurface = true;
891                    } else {
892                        response->setInt32("err", err);
893                    }
894                    response->postReply(mReplyID);
895                    break;
896                }
897
898                case CodecBase::kWhatSignaledInputEOS:
899                {
900                    // response to signalEndOfInputStream()
901                    sp<AMessage> response = new AMessage();
902                    status_t err;
903                    if (msg->findInt32("err", &err)) {
904                        response->setInt32("err", err);
905                    }
906                    response->postReply(mReplyID);
907                    break;
908                }
909
910
911                case CodecBase::kWhatBuffersAllocated:
912                {
913                    Mutex::Autolock al(mBufferLock);
914                    int32_t portIndex;
915                    CHECK(msg->findInt32("portIndex", &portIndex));
916
917                    ALOGV("%s buffers allocated",
918                          portIndex == kPortIndexInput ? "input" : "output");
919
920                    CHECK(portIndex == kPortIndexInput
921                            || portIndex == kPortIndexOutput);
922
923                    mPortBuffers[portIndex].clear();
924
925                    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
926
927                    sp<RefBase> obj;
928                    CHECK(msg->findObject("portDesc", &obj));
929
930                    sp<CodecBase::PortDescription> portDesc =
931                        static_cast<CodecBase::PortDescription *>(obj.get());
932
933                    size_t numBuffers = portDesc->countBuffers();
934
935                    for (size_t i = 0; i < numBuffers; ++i) {
936                        BufferInfo info;
937                        info.mBufferID = portDesc->bufferIDAt(i);
938                        info.mOwnedByClient = false;
939                        info.mData = portDesc->bufferAt(i);
940
941                        if (portIndex == kPortIndexInput && mCrypto != NULL) {
942                            info.mEncryptedData =
943                                new ABuffer(info.mData->capacity());
944                        }
945
946                        buffers->push_back(info);
947                    }
948
949                    if (portIndex == kPortIndexOutput) {
950                        if (mState == STARTING) {
951                            // We're always allocating output buffers after
952                            // allocating input buffers, so this is a good
953                            // indication that now all buffers are allocated.
954                            setState(STARTED);
955                            (new AMessage)->postReply(mReplyID);
956                        } else {
957                            mFlags |= kFlagOutputBuffersChanged;
958                            postActivityNotificationIfPossible();
959                        }
960                    }
961                    break;
962                }
963
964                case CodecBase::kWhatOutputFormatChanged:
965                {
966                    ALOGV("codec output format changed");
967
968                    if (mSoftRenderer == NULL &&
969                            mNativeWindow != NULL &&
970                            (mFlags & kFlagIsSoftwareCodec)) {
971                        AString mime;
972                        CHECK(msg->findString("mime", &mime));
973
974                        if (mime.startsWithIgnoreCase("video/")) {
975                            mSoftRenderer = new SoftwareRenderer(mNativeWindow);
976                        }
977                    }
978
979                    mOutputFormat = msg;
980
981                    if (mFlags & kFlagIsEncoder) {
982                        // Before we announce the format change we should
983                        // collect codec specific data and amend the output
984                        // format as necessary.
985                        mFlags |= kFlagGatherCodecSpecificData;
986                    } else if (mFlags & kFlagIsAsync) {
987                        onOutputFormatChanged();
988                    } else {
989                        mFlags |= kFlagOutputFormatChanged;
990                        postActivityNotificationIfPossible();
991                    }
992                    break;
993                }
994
995                case CodecBase::kWhatFillThisBuffer:
996                {
997                    /* size_t index = */updateBuffers(kPortIndexInput, msg);
998
999                    if (mState == FLUSHING
1000                            || mState == STOPPING
1001                            || mState == RELEASING) {
1002                        returnBuffersToCodecOnPort(kPortIndexInput);
1003                        break;
1004                    }
1005
1006                    if (!mCSD.empty()) {
1007                        ssize_t index = dequeuePortBuffer(kPortIndexInput);
1008                        CHECK_GE(index, 0);
1009
1010                        // If codec specific data had been specified as
1011                        // part of the format in the call to configure and
1012                        // if there's more csd left, we submit it here
1013                        // clients only get access to input buffers once
1014                        // this data has been exhausted.
1015
1016                        status_t err = queueCSDInputBuffer(index);
1017
1018                        if (err != OK) {
1019                            ALOGE("queueCSDInputBuffer failed w/ error %d",
1020                                  err);
1021
1022                            setStickyError(err);
1023                            postActivityNotificationIfPossible();
1024
1025                            cancelPendingDequeueOperations();
1026                        }
1027                        break;
1028                    }
1029
1030                    if (mFlags & kFlagIsAsync) {
1031                        onInputBufferAvailable();
1032                    } else if (mFlags & kFlagDequeueInputPending) {
1033                        CHECK(handleDequeueInputBuffer(mDequeueInputReplyID));
1034
1035                        ++mDequeueInputTimeoutGeneration;
1036                        mFlags &= ~kFlagDequeueInputPending;
1037                        mDequeueInputReplyID = 0;
1038                    } else {
1039                        postActivityNotificationIfPossible();
1040                    }
1041                    break;
1042                }
1043
1044                case CodecBase::kWhatDrainThisBuffer:
1045                {
1046                    /* size_t index = */updateBuffers(kPortIndexOutput, msg);
1047
1048                    if (mState == FLUSHING
1049                            || mState == STOPPING
1050                            || mState == RELEASING) {
1051                        returnBuffersToCodecOnPort(kPortIndexOutput);
1052                        break;
1053                    }
1054
1055                    sp<ABuffer> buffer;
1056                    CHECK(msg->findBuffer("buffer", &buffer));
1057
1058                    int32_t omxFlags;
1059                    CHECK(msg->findInt32("flags", &omxFlags));
1060
1061                    buffer->meta()->setInt32("omxFlags", omxFlags);
1062
1063                    if (mFlags & kFlagGatherCodecSpecificData) {
1064                        // This is the very first output buffer after a
1065                        // format change was signalled, it'll either contain
1066                        // the one piece of codec specific data we can expect
1067                        // or there won't be codec specific data.
1068                        if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) {
1069                            status_t err =
1070                                amendOutputFormatWithCodecSpecificData(buffer);
1071
1072                            if (err != OK) {
1073                                ALOGE("Codec spit out malformed codec "
1074                                      "specific data!");
1075                            }
1076                        }
1077
1078                        mFlags &= ~kFlagGatherCodecSpecificData;
1079                        if (mFlags & kFlagIsAsync) {
1080                            onOutputFormatChanged();
1081                        } else {
1082                            mFlags |= kFlagOutputFormatChanged;
1083                        }
1084                    }
1085
1086                    if (mFlags & kFlagIsAsync) {
1087                        onOutputBufferAvailable();
1088                    } else if (mFlags & kFlagDequeueOutputPending) {
1089                        CHECK(handleDequeueOutputBuffer(mDequeueOutputReplyID));
1090
1091                        ++mDequeueOutputTimeoutGeneration;
1092                        mFlags &= ~kFlagDequeueOutputPending;
1093                        mDequeueOutputReplyID = 0;
1094                    } else {
1095                        postActivityNotificationIfPossible();
1096                    }
1097
1098                    break;
1099                }
1100
1101                case CodecBase::kWhatEOS:
1102                {
1103                    // We already notify the client of this by using the
1104                    // corresponding flag in "onOutputBufferReady".
1105                    break;
1106                }
1107
1108                case CodecBase::kWhatShutdownCompleted:
1109                {
1110                    if (mState == STOPPING) {
1111                        setState(INITIALIZED);
1112                    } else {
1113                        CHECK_EQ(mState, RELEASING);
1114                        setState(UNINITIALIZED);
1115                    }
1116
1117                    (new AMessage)->postReply(mReplyID);
1118                    break;
1119                }
1120
1121                case CodecBase::kWhatFlushCompleted:
1122                {
1123                    if (mState != FLUSHING) {
1124                        ALOGW("received FlushCompleted message in state %d",
1125                                mState);
1126                        break;
1127                    }
1128
1129                    if (mFlags & kFlagIsAsync) {
1130                        setState(FLUSHED);
1131                    } else {
1132                        setState(STARTED);
1133                        mCodec->signalResume();
1134                    }
1135
1136                    (new AMessage)->postReply(mReplyID);
1137                    break;
1138                }
1139
1140                default:
1141                    TRESPASS();
1142            }
1143            break;
1144        }
1145
1146        case kWhatInit:
1147        {
1148            uint32_t replyID;
1149            CHECK(msg->senderAwaitsResponse(&replyID));
1150
1151            if (mState != UNINITIALIZED) {
1152                PostReplyWithError(replyID, INVALID_OPERATION);
1153                break;
1154            }
1155
1156            mReplyID = replyID;
1157            setState(INITIALIZING);
1158
1159            AString name;
1160            CHECK(msg->findString("name", &name));
1161
1162            int32_t nameIsType;
1163            int32_t encoder = false;
1164            CHECK(msg->findInt32("nameIsType", &nameIsType));
1165            if (nameIsType) {
1166                CHECK(msg->findInt32("encoder", &encoder));
1167            }
1168
1169            sp<AMessage> format = new AMessage;
1170
1171            if (nameIsType) {
1172                format->setString("mime", name.c_str());
1173                format->setInt32("encoder", encoder);
1174            } else {
1175                format->setString("componentName", name.c_str());
1176            }
1177
1178            mCodec->initiateAllocateComponent(format);
1179            break;
1180        }
1181
1182        case kWhatSetCallback:
1183        {
1184            uint32_t replyID;
1185            CHECK(msg->senderAwaitsResponse(&replyID));
1186
1187            if (mState == UNINITIALIZED
1188                    || mState == INITIALIZING
1189                    || isExecuting()) {
1190                // callback can't be set after codec is executing,
1191                // or before it's initialized (as the callback
1192                // will be cleared when it goes to INITIALIZED)
1193                PostReplyWithError(replyID, INVALID_OPERATION);
1194                break;
1195            }
1196
1197            sp<AMessage> callback;
1198            CHECK(msg->findMessage("callback", &callback));
1199
1200            mCallback = callback;
1201
1202            if (mCallback != NULL) {
1203                ALOGI("MediaCodec will operate in async mode");
1204                mFlags |= kFlagIsAsync;
1205            } else {
1206                mFlags &= ~kFlagIsAsync;
1207            }
1208
1209            sp<AMessage> response = new AMessage;
1210            response->postReply(replyID);
1211            break;
1212        }
1213
1214        case kWhatConfigure:
1215        {
1216            uint32_t replyID;
1217            CHECK(msg->senderAwaitsResponse(&replyID));
1218
1219            if (mState != INITIALIZED) {
1220                PostReplyWithError(replyID, INVALID_OPERATION);
1221                break;
1222            }
1223
1224            sp<RefBase> obj;
1225            if (!msg->findObject("native-window", &obj)) {
1226                obj.clear();
1227            }
1228
1229            sp<AMessage> format;
1230            CHECK(msg->findMessage("format", &format));
1231
1232            if (obj != NULL) {
1233                format->setObject("native-window", obj);
1234
1235                status_t err = setNativeWindow(
1236                    static_cast<NativeWindowWrapper *>(obj.get())
1237                        ->getSurfaceTextureClient());
1238
1239                if (err != OK) {
1240                    PostReplyWithError(replyID, err);
1241                    break;
1242                }
1243            } else {
1244                setNativeWindow(NULL);
1245            }
1246
1247            mReplyID = replyID;
1248            setState(CONFIGURING);
1249
1250            void *crypto;
1251            if (!msg->findPointer("crypto", &crypto)) {
1252                crypto = NULL;
1253            }
1254
1255            mCrypto = static_cast<ICrypto *>(crypto);
1256
1257            uint32_t flags;
1258            CHECK(msg->findInt32("flags", (int32_t *)&flags));
1259
1260            if (flags & CONFIGURE_FLAG_ENCODE) {
1261                format->setInt32("encoder", true);
1262                mFlags |= kFlagIsEncoder;
1263            }
1264
1265            extractCSD(format);
1266
1267            mCodec->initiateConfigureComponent(format);
1268            break;
1269        }
1270
1271        case kWhatCreateInputSurface:
1272        {
1273            uint32_t replyID;
1274            CHECK(msg->senderAwaitsResponse(&replyID));
1275
1276            // Must be configured, but can't have been started yet.
1277            if (mState != CONFIGURED) {
1278                PostReplyWithError(replyID, INVALID_OPERATION);
1279                break;
1280            }
1281
1282            mReplyID = replyID;
1283            mCodec->initiateCreateInputSurface();
1284            break;
1285        }
1286
1287        case kWhatStart:
1288        {
1289            uint32_t replyID;
1290            CHECK(msg->senderAwaitsResponse(&replyID));
1291
1292            if (mState == FLUSHED) {
1293                mCodec->signalResume();
1294                PostReplyWithError(replyID, OK);
1295            } else if (mState != CONFIGURED) {
1296                PostReplyWithError(replyID, INVALID_OPERATION);
1297                break;
1298            }
1299
1300            mReplyID = replyID;
1301            setState(STARTING);
1302
1303            mCodec->initiateStart();
1304            break;
1305        }
1306
1307        case kWhatStop:
1308        case kWhatRelease:
1309        {
1310            State targetState =
1311                (msg->what() == kWhatStop) ? INITIALIZED : UNINITIALIZED;
1312
1313            uint32_t replyID;
1314            CHECK(msg->senderAwaitsResponse(&replyID));
1315
1316            if (mState != INITIALIZED
1317                    && mState != CONFIGURED && !isExecuting()) {
1318                // We may be in "UNINITIALIZED" state already without the
1319                // client being aware of this if media server died while
1320                // we were being stopped. The client would assume that
1321                // after stop() returned, it would be safe to call release()
1322                // and it should be in this case, no harm to allow a release()
1323                // if we're already uninitialized.
1324                // Similarly stopping a stopped MediaCodec should be benign.
1325                sp<AMessage> response = new AMessage;
1326                response->setInt32(
1327                        "err",
1328                        mState == targetState ? OK : INVALID_OPERATION);
1329
1330                response->postReply(replyID);
1331                break;
1332            }
1333
1334            if (mFlags & kFlagSawMediaServerDie) {
1335                // It's dead, Jim. Don't expect initiateShutdown to yield
1336                // any useful results now...
1337                setState(UNINITIALIZED);
1338                (new AMessage)->postReply(replyID);
1339                break;
1340            }
1341
1342            mReplyID = replyID;
1343            setState(msg->what() == kWhatStop ? STOPPING : RELEASING);
1344
1345            mCodec->initiateShutdown(
1346                    msg->what() == kWhatStop /* keepComponentAllocated */);
1347
1348            returnBuffersToCodec();
1349            break;
1350        }
1351
1352        case kWhatDequeueInputBuffer:
1353        {
1354            uint32_t replyID;
1355            CHECK(msg->senderAwaitsResponse(&replyID));
1356
1357            if (mFlags & kFlagIsAsync) {
1358                ALOGE("dequeueOutputBuffer can't be used in async mode");
1359                PostReplyWithError(replyID, INVALID_OPERATION);
1360                break;
1361            }
1362
1363            if (mHaveInputSurface) {
1364                ALOGE("dequeueInputBuffer can't be used with input surface");
1365                PostReplyWithError(replyID, INVALID_OPERATION);
1366                break;
1367            }
1368
1369            if (handleDequeueInputBuffer(replyID, true /* new request */)) {
1370                break;
1371            }
1372
1373            int64_t timeoutUs;
1374            CHECK(msg->findInt64("timeoutUs", &timeoutUs));
1375
1376            if (timeoutUs == 0ll) {
1377                PostReplyWithError(replyID, -EAGAIN);
1378                break;
1379            }
1380
1381            mFlags |= kFlagDequeueInputPending;
1382            mDequeueInputReplyID = replyID;
1383
1384            if (timeoutUs > 0ll) {
1385                sp<AMessage> timeoutMsg =
1386                    new AMessage(kWhatDequeueInputTimedOut, id());
1387                timeoutMsg->setInt32(
1388                        "generation", ++mDequeueInputTimeoutGeneration);
1389                timeoutMsg->post(timeoutUs);
1390            }
1391            break;
1392        }
1393
1394        case kWhatDequeueInputTimedOut:
1395        {
1396            int32_t generation;
1397            CHECK(msg->findInt32("generation", &generation));
1398
1399            if (generation != mDequeueInputTimeoutGeneration) {
1400                // Obsolete
1401                break;
1402            }
1403
1404            CHECK(mFlags & kFlagDequeueInputPending);
1405
1406            PostReplyWithError(mDequeueInputReplyID, -EAGAIN);
1407
1408            mFlags &= ~kFlagDequeueInputPending;
1409            mDequeueInputReplyID = 0;
1410            break;
1411        }
1412
1413        case kWhatQueueInputBuffer:
1414        {
1415            uint32_t replyID;
1416            CHECK(msg->senderAwaitsResponse(&replyID));
1417
1418            if (!isExecuting()) {
1419                PostReplyWithError(replyID, INVALID_OPERATION);
1420                break;
1421            } else if (mFlags & kFlagStickyError) {
1422                PostReplyWithError(replyID, getStickyError());
1423                break;
1424            }
1425
1426            status_t err = onQueueInputBuffer(msg);
1427
1428            PostReplyWithError(replyID, err);
1429            break;
1430        }
1431
1432        case kWhatDequeueOutputBuffer:
1433        {
1434            uint32_t replyID;
1435            CHECK(msg->senderAwaitsResponse(&replyID));
1436
1437            if (mFlags & kFlagIsAsync) {
1438                ALOGE("dequeueOutputBuffer can't be used in async mode");
1439                PostReplyWithError(replyID, INVALID_OPERATION);
1440                break;
1441            }
1442
1443            if (handleDequeueOutputBuffer(replyID, true /* new request */)) {
1444                break;
1445            }
1446
1447            int64_t timeoutUs;
1448            CHECK(msg->findInt64("timeoutUs", &timeoutUs));
1449
1450            if (timeoutUs == 0ll) {
1451                PostReplyWithError(replyID, -EAGAIN);
1452                break;
1453            }
1454
1455            mFlags |= kFlagDequeueOutputPending;
1456            mDequeueOutputReplyID = replyID;
1457
1458            if (timeoutUs > 0ll) {
1459                sp<AMessage> timeoutMsg =
1460                    new AMessage(kWhatDequeueOutputTimedOut, id());
1461                timeoutMsg->setInt32(
1462                        "generation", ++mDequeueOutputTimeoutGeneration);
1463                timeoutMsg->post(timeoutUs);
1464            }
1465            break;
1466        }
1467
1468        case kWhatDequeueOutputTimedOut:
1469        {
1470            int32_t generation;
1471            CHECK(msg->findInt32("generation", &generation));
1472
1473            if (generation != mDequeueOutputTimeoutGeneration) {
1474                // Obsolete
1475                break;
1476            }
1477
1478            CHECK(mFlags & kFlagDequeueOutputPending);
1479
1480            PostReplyWithError(mDequeueOutputReplyID, -EAGAIN);
1481
1482            mFlags &= ~kFlagDequeueOutputPending;
1483            mDequeueOutputReplyID = 0;
1484            break;
1485        }
1486
1487        case kWhatReleaseOutputBuffer:
1488        {
1489            uint32_t replyID;
1490            CHECK(msg->senderAwaitsResponse(&replyID));
1491
1492            if (!isExecuting()) {
1493                PostReplyWithError(replyID, INVALID_OPERATION);
1494                break;
1495            } else if (mFlags & kFlagStickyError) {
1496                PostReplyWithError(replyID, getStickyError());
1497                break;
1498            }
1499
1500            status_t err = onReleaseOutputBuffer(msg);
1501
1502            PostReplyWithError(replyID, err);
1503            break;
1504        }
1505
1506        case kWhatSignalEndOfInputStream:
1507        {
1508            uint32_t replyID;
1509            CHECK(msg->senderAwaitsResponse(&replyID));
1510
1511            if (!isExecuting()) {
1512                PostReplyWithError(replyID, INVALID_OPERATION);
1513                break;
1514            } else if (mFlags & kFlagStickyError) {
1515                PostReplyWithError(replyID, getStickyError());
1516                break;
1517            }
1518
1519            mReplyID = replyID;
1520            mCodec->signalEndOfInputStream();
1521            break;
1522        }
1523
1524        case kWhatGetBuffers:
1525        {
1526            uint32_t replyID;
1527            CHECK(msg->senderAwaitsResponse(&replyID));
1528
1529            if (!isExecuting() || (mFlags & kFlagIsAsync)) {
1530                PostReplyWithError(replyID, INVALID_OPERATION);
1531                break;
1532            } else if (mFlags & kFlagStickyError) {
1533                PostReplyWithError(replyID, getStickyError());
1534                break;
1535            }
1536
1537            int32_t portIndex;
1538            CHECK(msg->findInt32("portIndex", &portIndex));
1539
1540            Vector<sp<ABuffer> > *dstBuffers;
1541            CHECK(msg->findPointer("buffers", (void **)&dstBuffers));
1542
1543            dstBuffers->clear();
1544            const Vector<BufferInfo> &srcBuffers = mPortBuffers[portIndex];
1545
1546            for (size_t i = 0; i < srcBuffers.size(); ++i) {
1547                const BufferInfo &info = srcBuffers.itemAt(i);
1548
1549                dstBuffers->push_back(
1550                        (portIndex == kPortIndexInput && mCrypto != NULL)
1551                                ? info.mEncryptedData : info.mData);
1552            }
1553
1554            (new AMessage)->postReply(replyID);
1555            break;
1556        }
1557
1558        case kWhatFlush:
1559        {
1560            uint32_t replyID;
1561            CHECK(msg->senderAwaitsResponse(&replyID));
1562
1563            if (!isExecuting()) {
1564                PostReplyWithError(replyID, INVALID_OPERATION);
1565                break;
1566            } else if (mFlags & kFlagStickyError) {
1567                PostReplyWithError(replyID, getStickyError());
1568                break;
1569            }
1570
1571            mReplyID = replyID;
1572            // TODO: skip flushing if already FLUSHED
1573            setState(FLUSHING);
1574
1575            mCodec->signalFlush();
1576            returnBuffersToCodec();
1577            break;
1578        }
1579
1580        case kWhatGetInputFormat:
1581        case kWhatGetOutputFormat:
1582        {
1583            sp<AMessage> format =
1584                (msg->what() == kWhatGetOutputFormat ? mOutputFormat : mInputFormat);
1585
1586            uint32_t replyID;
1587            CHECK(msg->senderAwaitsResponse(&replyID));
1588
1589            if ((mState != CONFIGURED && mState != STARTING &&
1590                 mState != STARTED && mState != FLUSHING &&
1591                 mState != FLUSHED)
1592                    || format == NULL) {
1593                PostReplyWithError(replyID, INVALID_OPERATION);
1594                break;
1595            } else if (mFlags & kFlagStickyError) {
1596                PostReplyWithError(replyID, getStickyError());
1597                break;
1598            }
1599
1600            sp<AMessage> response = new AMessage;
1601            response->setMessage("format", format);
1602            response->postReply(replyID);
1603            break;
1604        }
1605
1606        case kWhatRequestIDRFrame:
1607        {
1608            mCodec->signalRequestIDRFrame();
1609            break;
1610        }
1611
1612        case kWhatRequestActivityNotification:
1613        {
1614            CHECK(mActivityNotify == NULL);
1615            CHECK(msg->findMessage("notify", &mActivityNotify));
1616
1617            postActivityNotificationIfPossible();
1618            break;
1619        }
1620
1621        case kWhatGetName:
1622        {
1623            uint32_t replyID;
1624            CHECK(msg->senderAwaitsResponse(&replyID));
1625
1626            if (mComponentName.empty()) {
1627                PostReplyWithError(replyID, INVALID_OPERATION);
1628                break;
1629            }
1630
1631            sp<AMessage> response = new AMessage;
1632            response->setString("name", mComponentName.c_str());
1633            response->postReply(replyID);
1634            break;
1635        }
1636
1637        case kWhatSetParameters:
1638        {
1639            uint32_t replyID;
1640            CHECK(msg->senderAwaitsResponse(&replyID));
1641
1642            sp<AMessage> params;
1643            CHECK(msg->findMessage("params", &params));
1644
1645            status_t err = onSetParameters(params);
1646
1647            PostReplyWithError(replyID, err);
1648            break;
1649        }
1650
1651        default:
1652            TRESPASS();
1653    }
1654}
1655
1656void MediaCodec::extractCSD(const sp<AMessage> &format) {
1657    mCSD.clear();
1658
1659    size_t i = 0;
1660    for (;;) {
1661        sp<ABuffer> csd;
1662        if (!format->findBuffer(StringPrintf("csd-%u", i).c_str(), &csd)) {
1663            break;
1664        }
1665
1666        mCSD.push_back(csd);
1667        ++i;
1668    }
1669
1670    ALOGV("Found %zu pieces of codec specific data.", mCSD.size());
1671}
1672
1673status_t MediaCodec::queueCSDInputBuffer(size_t bufferIndex) {
1674    CHECK(!mCSD.empty());
1675
1676    const BufferInfo *info =
1677        &mPortBuffers[kPortIndexInput].itemAt(bufferIndex);
1678
1679    sp<ABuffer> csd = *mCSD.begin();
1680    mCSD.erase(mCSD.begin());
1681
1682    const sp<ABuffer> &codecInputData =
1683        (mCrypto != NULL) ? info->mEncryptedData : info->mData;
1684
1685    if (csd->size() > codecInputData->capacity()) {
1686        return -EINVAL;
1687    }
1688
1689    memcpy(codecInputData->data(), csd->data(), csd->size());
1690
1691    AString errorDetailMsg;
1692
1693    sp<AMessage> msg = new AMessage(kWhatQueueInputBuffer, id());
1694    msg->setSize("index", bufferIndex);
1695    msg->setSize("offset", 0);
1696    msg->setSize("size", csd->size());
1697    msg->setInt64("timeUs", 0ll);
1698    msg->setInt32("flags", BUFFER_FLAG_CODECCONFIG);
1699    msg->setPointer("errorDetailMsg", &errorDetailMsg);
1700
1701    return onQueueInputBuffer(msg);
1702}
1703
1704void MediaCodec::setState(State newState) {
1705    if (newState == INITIALIZED || newState == UNINITIALIZED) {
1706        delete mSoftRenderer;
1707        mSoftRenderer = NULL;
1708
1709        mCrypto.clear();
1710        setNativeWindow(NULL);
1711
1712        mInputFormat.clear();
1713        mOutputFormat.clear();
1714        mFlags &= ~kFlagOutputFormatChanged;
1715        mFlags &= ~kFlagOutputBuffersChanged;
1716        mFlags &= ~kFlagStickyError;
1717        mFlags &= ~kFlagIsEncoder;
1718        mFlags &= ~kFlagGatherCodecSpecificData;
1719        mFlags &= ~kFlagIsAsync;
1720        mStickyError = OK;
1721
1722        mActivityNotify.clear();
1723        mCallback.clear();
1724    }
1725
1726    if (newState == UNINITIALIZED) {
1727        // return any straggling buffers, e.g. if we got here on an error
1728        returnBuffersToCodec();
1729
1730        mComponentName.clear();
1731
1732        // The component is gone, mediaserver's probably back up already
1733        // but should definitely be back up should we try to instantiate
1734        // another component.. and the cycle continues.
1735        mFlags &= ~kFlagSawMediaServerDie;
1736    }
1737
1738    mState = newState;
1739
1740    cancelPendingDequeueOperations();
1741
1742    updateBatteryStat();
1743}
1744
1745void MediaCodec::returnBuffersToCodec() {
1746    returnBuffersToCodecOnPort(kPortIndexInput);
1747    returnBuffersToCodecOnPort(kPortIndexOutput);
1748}
1749
1750void MediaCodec::returnBuffersToCodecOnPort(int32_t portIndex) {
1751    CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput);
1752    Mutex::Autolock al(mBufferLock);
1753
1754    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
1755
1756    for (size_t i = 0; i < buffers->size(); ++i) {
1757        BufferInfo *info = &buffers->editItemAt(i);
1758
1759        if (info->mNotify != NULL) {
1760            sp<AMessage> msg = info->mNotify;
1761            info->mNotify = NULL;
1762            info->mOwnedByClient = false;
1763
1764            if (portIndex == kPortIndexInput) {
1765                /* no error, just returning buffers */
1766                msg->setInt32("err", OK);
1767            }
1768            msg->post();
1769        }
1770    }
1771
1772    mAvailPortBuffers[portIndex].clear();
1773}
1774
1775size_t MediaCodec::updateBuffers(
1776        int32_t portIndex, const sp<AMessage> &msg) {
1777    CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput);
1778
1779    uint32_t bufferID;
1780    CHECK(msg->findInt32("buffer-id", (int32_t*)&bufferID));
1781
1782    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
1783
1784    for (size_t i = 0; i < buffers->size(); ++i) {
1785        BufferInfo *info = &buffers->editItemAt(i);
1786
1787        if (info->mBufferID == bufferID) {
1788            CHECK(info->mNotify == NULL);
1789            CHECK(msg->findMessage("reply", &info->mNotify));
1790
1791            info->mFormat =
1792                (portIndex == kPortIndexInput) ? mInputFormat : mOutputFormat;
1793            mAvailPortBuffers[portIndex].push_back(i);
1794
1795            return i;
1796        }
1797    }
1798
1799    TRESPASS();
1800
1801    return 0;
1802}
1803
1804status_t MediaCodec::onQueueInputBuffer(const sp<AMessage> &msg) {
1805    size_t index;
1806    size_t offset;
1807    size_t size;
1808    int64_t timeUs;
1809    uint32_t flags;
1810    CHECK(msg->findSize("index", &index));
1811    CHECK(msg->findSize("offset", &offset));
1812    CHECK(msg->findInt64("timeUs", &timeUs));
1813    CHECK(msg->findInt32("flags", (int32_t *)&flags));
1814
1815    const CryptoPlugin::SubSample *subSamples;
1816    size_t numSubSamples;
1817    const uint8_t *key;
1818    const uint8_t *iv;
1819    CryptoPlugin::Mode mode = CryptoPlugin::kMode_Unencrypted;
1820
1821    // We allow the simpler queueInputBuffer API to be used even in
1822    // secure mode, by fabricating a single unencrypted subSample.
1823    CryptoPlugin::SubSample ss;
1824
1825    if (msg->findSize("size", &size)) {
1826        if (mCrypto != NULL) {
1827            ss.mNumBytesOfClearData = size;
1828            ss.mNumBytesOfEncryptedData = 0;
1829
1830            subSamples = &ss;
1831            numSubSamples = 1;
1832            key = NULL;
1833            iv = NULL;
1834        }
1835    } else {
1836        if (mCrypto == NULL) {
1837            return -EINVAL;
1838        }
1839
1840        CHECK(msg->findPointer("subSamples", (void **)&subSamples));
1841        CHECK(msg->findSize("numSubSamples", &numSubSamples));
1842        CHECK(msg->findPointer("key", (void **)&key));
1843        CHECK(msg->findPointer("iv", (void **)&iv));
1844
1845        int32_t tmp;
1846        CHECK(msg->findInt32("mode", &tmp));
1847
1848        mode = (CryptoPlugin::Mode)tmp;
1849
1850        size = 0;
1851        for (size_t i = 0; i < numSubSamples; ++i) {
1852            size += subSamples[i].mNumBytesOfClearData;
1853            size += subSamples[i].mNumBytesOfEncryptedData;
1854        }
1855    }
1856
1857    if (index >= mPortBuffers[kPortIndexInput].size()) {
1858        return -ERANGE;
1859    }
1860
1861    BufferInfo *info = &mPortBuffers[kPortIndexInput].editItemAt(index);
1862
1863    if (info->mNotify == NULL || !info->mOwnedByClient) {
1864        return -EACCES;
1865    }
1866
1867    if (offset + size > info->mData->capacity()) {
1868        return -EINVAL;
1869    }
1870
1871    sp<AMessage> reply = info->mNotify;
1872    info->mData->setRange(offset, size);
1873    info->mData->meta()->setInt64("timeUs", timeUs);
1874
1875    if (flags & BUFFER_FLAG_EOS) {
1876        info->mData->meta()->setInt32("eos", true);
1877    }
1878
1879    if (flags & BUFFER_FLAG_CODECCONFIG) {
1880        info->mData->meta()->setInt32("csd", true);
1881    }
1882
1883    if (mCrypto != NULL) {
1884        if (size > info->mEncryptedData->capacity()) {
1885            return -ERANGE;
1886        }
1887
1888        AString *errorDetailMsg;
1889        CHECK(msg->findPointer("errorDetailMsg", (void **)&errorDetailMsg));
1890
1891        ssize_t result = mCrypto->decrypt(
1892                (mFlags & kFlagIsSecure) != 0,
1893                key,
1894                iv,
1895                mode,
1896                info->mEncryptedData->base() + offset,
1897                subSamples,
1898                numSubSamples,
1899                info->mData->base(),
1900                errorDetailMsg);
1901
1902        if (result < 0) {
1903            return result;
1904        }
1905
1906        info->mData->setRange(0, result);
1907    }
1908
1909    // synchronization boundary for getBufferAndFormat
1910    {
1911        Mutex::Autolock al(mBufferLock);
1912        info->mOwnedByClient = false;
1913    }
1914    reply->setBuffer("buffer", info->mData);
1915    reply->post();
1916
1917    info->mNotify = NULL;
1918
1919    return OK;
1920}
1921
1922status_t MediaCodec::onReleaseOutputBuffer(const sp<AMessage> &msg) {
1923    size_t index;
1924    CHECK(msg->findSize("index", &index));
1925
1926    int32_t render;
1927    if (!msg->findInt32("render", &render)) {
1928        render = 0;
1929    }
1930
1931    if (!isExecuting()) {
1932        return -EINVAL;
1933    }
1934
1935    if (index >= mPortBuffers[kPortIndexOutput].size()) {
1936        return -ERANGE;
1937    }
1938
1939    BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index);
1940
1941    if (info->mNotify == NULL || !info->mOwnedByClient) {
1942        return -EACCES;
1943    }
1944
1945    // synchronization boundary for getBufferAndFormat
1946    {
1947        Mutex::Autolock al(mBufferLock);
1948        info->mOwnedByClient = false;
1949    }
1950
1951    if (render && info->mData != NULL && info->mData->size() != 0) {
1952        info->mNotify->setInt32("render", true);
1953
1954        int64_t timestampNs = 0;
1955        if (msg->findInt64("timestampNs", &timestampNs)) {
1956            info->mNotify->setInt64("timestampNs", timestampNs);
1957        } else {
1958            // TODO: it seems like we should use the timestamp
1959            // in the (media)buffer as it potentially came from
1960            // an input surface, but we did not propagate it prior to
1961            // API 20.  Perhaps check for target SDK version.
1962#if 0
1963            if (info->mData->meta()->findInt64("timeUs", &timestampNs)) {
1964                ALOGV("using buffer PTS of %" PRId64, timestampNs);
1965                timestampNs *= 1000;
1966            }
1967#endif
1968        }
1969
1970        if (mSoftRenderer != NULL) {
1971            mSoftRenderer->render(
1972                    info->mData->data(), info->mData->size(),
1973                    timestampNs, NULL, info->mFormat);
1974        }
1975    }
1976
1977    info->mNotify->post();
1978    info->mNotify = NULL;
1979
1980    return OK;
1981}
1982
1983ssize_t MediaCodec::dequeuePortBuffer(int32_t portIndex) {
1984    CHECK(portIndex == kPortIndexInput || portIndex == kPortIndexOutput);
1985
1986    List<size_t> *availBuffers = &mAvailPortBuffers[portIndex];
1987
1988    if (availBuffers->empty()) {
1989        return -EAGAIN;
1990    }
1991
1992    size_t index = *availBuffers->begin();
1993    availBuffers->erase(availBuffers->begin());
1994
1995    BufferInfo *info = &mPortBuffers[portIndex].editItemAt(index);
1996    CHECK(!info->mOwnedByClient);
1997    {
1998        Mutex::Autolock al(mBufferLock);
1999        info->mOwnedByClient = true;
2000
2001        // set image-data
2002        if (info->mFormat != NULL) {
2003            sp<ABuffer> imageData;
2004            if (info->mFormat->findBuffer("image-data", &imageData)) {
2005                info->mData->meta()->setBuffer("image-data", imageData);
2006            }
2007            int32_t left, top, right, bottom;
2008            if (info->mFormat->findRect("crop", &left, &top, &right, &bottom)) {
2009                info->mData->meta()->setRect("crop-rect", left, top, right, bottom);
2010            }
2011        }
2012    }
2013
2014    return index;
2015}
2016
2017status_t MediaCodec::setNativeWindow(
2018        const sp<Surface> &surfaceTextureClient) {
2019    status_t err;
2020
2021    if (mNativeWindow != NULL) {
2022        err = native_window_api_disconnect(
2023                mNativeWindow.get(), NATIVE_WINDOW_API_MEDIA);
2024
2025        if (err != OK) {
2026            ALOGW("native_window_api_disconnect returned an error: %s (%d)",
2027                    strerror(-err), err);
2028        }
2029
2030        mNativeWindow.clear();
2031    }
2032
2033    if (surfaceTextureClient != NULL) {
2034        err = native_window_api_connect(
2035                surfaceTextureClient.get(), NATIVE_WINDOW_API_MEDIA);
2036
2037        if (err != OK) {
2038            ALOGE("native_window_api_connect returned an error: %s (%d)",
2039                    strerror(-err), err);
2040
2041            return err;
2042        }
2043
2044        mNativeWindow = surfaceTextureClient;
2045    }
2046
2047    return OK;
2048}
2049
2050void MediaCodec::onInputBufferAvailable() {
2051    int32_t index;
2052    while ((index = dequeuePortBuffer(kPortIndexInput)) >= 0) {
2053        sp<AMessage> msg = mCallback->dup();
2054        msg->setInt32("callbackID", CB_INPUT_AVAILABLE);
2055        msg->setInt32("index", index);
2056        msg->post();
2057    }
2058}
2059
2060void MediaCodec::onOutputBufferAvailable() {
2061    int32_t index;
2062    while ((index = dequeuePortBuffer(kPortIndexOutput)) >= 0) {
2063        const sp<ABuffer> &buffer =
2064            mPortBuffers[kPortIndexOutput].itemAt(index).mData;
2065        sp<AMessage> msg = mCallback->dup();
2066        msg->setInt32("callbackID", CB_OUTPUT_AVAILABLE);
2067        msg->setInt32("index", index);
2068        msg->setSize("offset", buffer->offset());
2069        msg->setSize("size", buffer->size());
2070
2071        int64_t timeUs;
2072        CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
2073
2074        msg->setInt64("timeUs", timeUs);
2075
2076        int32_t omxFlags;
2077        CHECK(buffer->meta()->findInt32("omxFlags", &omxFlags));
2078
2079        uint32_t flags = 0;
2080        if (omxFlags & OMX_BUFFERFLAG_SYNCFRAME) {
2081            flags |= BUFFER_FLAG_SYNCFRAME;
2082        }
2083        if (omxFlags & OMX_BUFFERFLAG_CODECCONFIG) {
2084            flags |= BUFFER_FLAG_CODECCONFIG;
2085        }
2086        if (omxFlags & OMX_BUFFERFLAG_EOS) {
2087            flags |= BUFFER_FLAG_EOS;
2088        }
2089
2090        msg->setInt32("flags", flags);
2091
2092        msg->post();
2093    }
2094}
2095
2096void MediaCodec::onError(status_t err, int32_t actionCode, const char *detail) {
2097    if (mCallback != NULL) {
2098        sp<AMessage> msg = mCallback->dup();
2099        msg->setInt32("callbackID", CB_ERROR);
2100        msg->setInt32("err", err);
2101        msg->setInt32("actionCode", actionCode);
2102
2103        if (detail != NULL) {
2104            msg->setString("detail", detail);
2105        }
2106
2107        msg->post();
2108    }
2109}
2110
2111void MediaCodec::onOutputFormatChanged() {
2112    if (mCallback != NULL) {
2113        sp<AMessage> msg = mCallback->dup();
2114        msg->setInt32("callbackID", CB_OUTPUT_FORMAT_CHANGED);
2115        msg->setMessage("format", mOutputFormat);
2116        msg->post();
2117    }
2118}
2119
2120
2121void MediaCodec::postActivityNotificationIfPossible() {
2122    if (mActivityNotify == NULL) {
2123        return;
2124    }
2125
2126    if ((mFlags & (kFlagStickyError
2127                    | kFlagOutputBuffersChanged
2128                    | kFlagOutputFormatChanged))
2129            || !mAvailPortBuffers[kPortIndexInput].empty()
2130            || !mAvailPortBuffers[kPortIndexOutput].empty()) {
2131        mActivityNotify->post();
2132        mActivityNotify.clear();
2133    }
2134}
2135
2136status_t MediaCodec::setParameters(const sp<AMessage> &params) {
2137    sp<AMessage> msg = new AMessage(kWhatSetParameters, id());
2138    msg->setMessage("params", params);
2139
2140    sp<AMessage> response;
2141    return PostAndAwaitResponse(msg, &response);
2142}
2143
2144status_t MediaCodec::onSetParameters(const sp<AMessage> &params) {
2145    mCodec->signalSetParameters(params);
2146
2147    return OK;
2148}
2149
2150status_t MediaCodec::amendOutputFormatWithCodecSpecificData(
2151        const sp<ABuffer> &buffer) {
2152    AString mime;
2153    CHECK(mOutputFormat->findString("mime", &mime));
2154
2155    if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_VIDEO_AVC)) {
2156        // Codec specific data should be SPS and PPS in a single buffer,
2157        // each prefixed by a startcode (0x00 0x00 0x00 0x01).
2158        // We separate the two and put them into the output format
2159        // under the keys "csd-0" and "csd-1".
2160
2161        unsigned csdIndex = 0;
2162
2163        const uint8_t *data = buffer->data();
2164        size_t size = buffer->size();
2165
2166        const uint8_t *nalStart;
2167        size_t nalSize;
2168        while (getNextNALUnit(&data, &size, &nalStart, &nalSize, true) == OK) {
2169            sp<ABuffer> csd = new ABuffer(nalSize + 4);
2170            memcpy(csd->data(), "\x00\x00\x00\x01", 4);
2171            memcpy(csd->data() + 4, nalStart, nalSize);
2172
2173            mOutputFormat->setBuffer(
2174                    StringPrintf("csd-%u", csdIndex).c_str(), csd);
2175
2176            ++csdIndex;
2177        }
2178
2179        if (csdIndex != 2) {
2180            return ERROR_MALFORMED;
2181        }
2182    } else {
2183        // For everything else we just stash the codec specific data into
2184        // the output format as a single piece of csd under "csd-0".
2185        mOutputFormat->setBuffer("csd-0", buffer);
2186    }
2187
2188    return OK;
2189}
2190
2191void MediaCodec::updateBatteryStat() {
2192    if (mState == CONFIGURED && !mBatteryStatNotified) {
2193        AString mime;
2194        CHECK(mOutputFormat != NULL &&
2195                mOutputFormat->findString("mime", &mime));
2196
2197        mIsVideo = mime.startsWithIgnoreCase("video/");
2198
2199        BatteryNotifier& notifier(BatteryNotifier::getInstance());
2200
2201        if (mIsVideo) {
2202            notifier.noteStartVideo();
2203        } else {
2204            notifier.noteStartAudio();
2205        }
2206
2207        mBatteryStatNotified = true;
2208    } else if (mState == UNINITIALIZED && mBatteryStatNotified) {
2209        BatteryNotifier& notifier(BatteryNotifier::getInstance());
2210
2211        if (mIsVideo) {
2212            notifier.noteStopVideo();
2213        } else {
2214            notifier.noteStopAudio();
2215        }
2216
2217        mBatteryStatNotified = false;
2218    }
2219}
2220
2221}  // namespace android
2222