OMXCodec.cpp revision 76ab6df08a2069eac6317715dadccbb6041e7fab
1/*
2 * Copyright (C) 2009 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 "OMXCodec"
19#include <utils/Log.h>
20
21#include "include/AACEncoder.h"
22
23#include "include/ESDS.h"
24
25#include <binder/IServiceManager.h>
26#include <binder/MemoryDealer.h>
27#include <binder/ProcessState.h>
28#include <HardwareAPI.h>
29#include <media/stagefright/foundation/ADebug.h>
30#include <media/IMediaPlayerService.h>
31#include <media/stagefright/MediaBuffer.h>
32#include <media/stagefright/MediaBufferGroup.h>
33#include <media/stagefright/MediaDefs.h>
34#include <media/stagefright/MediaCodecList.h>
35#include <media/stagefright/MediaExtractor.h>
36#include <media/stagefright/MetaData.h>
37#include <media/stagefright/OMXCodec.h>
38#include <media/stagefright/Utils.h>
39#include <media/stagefright/SkipCutBuffer.h>
40#include <utils/Vector.h>
41
42#include <OMX_Audio.h>
43#include <OMX_Component.h>
44
45#include "include/avc_utils.h"
46
47namespace android {
48
49// Treat time out as an error if we have not received any output
50// buffers after 3 seconds.
51const static int64_t kBufferFilledEventTimeOutNs = 3000000000LL;
52
53// OMX Spec defines less than 50 color formats. If the query for
54// color format is executed for more than kMaxColorFormatSupported,
55// the query will fail to avoid looping forever.
56// 1000 is more than enough for us to tell whether the omx
57// component in question is buggy or not.
58const static uint32_t kMaxColorFormatSupported = 1000;
59
60#define FACTORY_CREATE_ENCODER(name) \
61static sp<MediaSource> Make##name(const sp<MediaSource> &source, const sp<MetaData> &meta) { \
62    return new name(source, meta); \
63}
64
65#define FACTORY_REF(name) { #name, Make##name },
66
67FACTORY_CREATE_ENCODER(AACEncoder)
68
69static sp<MediaSource> InstantiateSoftwareEncoder(
70        const char *name, const sp<MediaSource> &source,
71        const sp<MetaData> &meta) {
72    struct FactoryInfo {
73        const char *name;
74        sp<MediaSource> (*CreateFunc)(const sp<MediaSource> &, const sp<MetaData> &);
75    };
76
77    static const FactoryInfo kFactoryInfo[] = {
78        FACTORY_REF(AACEncoder)
79    };
80    for (size_t i = 0;
81         i < sizeof(kFactoryInfo) / sizeof(kFactoryInfo[0]); ++i) {
82        if (!strcmp(name, kFactoryInfo[i].name)) {
83            return (*kFactoryInfo[i].CreateFunc)(source, meta);
84        }
85    }
86
87    return NULL;
88}
89
90#undef FACTORY_CREATE_ENCODER
91#undef FACTORY_REF
92
93#define CODEC_LOGI(x, ...) ALOGI("[%s] "x, mComponentName, ##__VA_ARGS__)
94#define CODEC_LOGV(x, ...) ALOGV("[%s] "x, mComponentName, ##__VA_ARGS__)
95#define CODEC_LOGE(x, ...) ALOGE("[%s] "x, mComponentName, ##__VA_ARGS__)
96
97struct OMXCodecObserver : public BnOMXObserver {
98    OMXCodecObserver() {
99    }
100
101    void setCodec(const sp<OMXCodec> &target) {
102        mTarget = target;
103    }
104
105    // from IOMXObserver
106    virtual void onMessage(const omx_message &msg) {
107        sp<OMXCodec> codec = mTarget.promote();
108
109        if (codec.get() != NULL) {
110            Mutex::Autolock autoLock(codec->mLock);
111            codec->on_message(msg);
112            codec.clear();
113        }
114    }
115
116protected:
117    virtual ~OMXCodecObserver() {}
118
119private:
120    wp<OMXCodec> mTarget;
121
122    OMXCodecObserver(const OMXCodecObserver &);
123    OMXCodecObserver &operator=(const OMXCodecObserver &);
124};
125
126template<class T>
127static void InitOMXParams(T *params) {
128    params->nSize = sizeof(T);
129    params->nVersion.s.nVersionMajor = 1;
130    params->nVersion.s.nVersionMinor = 0;
131    params->nVersion.s.nRevision = 0;
132    params->nVersion.s.nStep = 0;
133}
134
135static bool IsSoftwareCodec(const char *componentName) {
136    if (!strncmp("OMX.google.", componentName, 11)) {
137        return true;
138    }
139
140    if (!strncmp("OMX.", componentName, 4)) {
141        return false;
142    }
143
144    return true;
145}
146
147// A sort order in which OMX software codecs are first, followed
148// by other (non-OMX) software codecs, followed by everything else.
149static int CompareSoftwareCodecsFirst(
150        const OMXCodec::CodecNameAndQuirks *elem1,
151        const OMXCodec::CodecNameAndQuirks *elem2) {
152    bool isOMX1 = !strncmp(elem1->mName.string(), "OMX.", 4);
153    bool isOMX2 = !strncmp(elem2->mName.string(), "OMX.", 4);
154
155    bool isSoftwareCodec1 = IsSoftwareCodec(elem1->mName.string());
156    bool isSoftwareCodec2 = IsSoftwareCodec(elem2->mName.string());
157
158    if (isSoftwareCodec1) {
159        if (!isSoftwareCodec2) { return -1; }
160
161        if (isOMX1) {
162            if (isOMX2) { return 0; }
163
164            return -1;
165        } else {
166            if (isOMX2) { return 0; }
167
168            return 1;
169        }
170
171        return -1;
172    }
173
174    if (isSoftwareCodec2) {
175        return 1;
176    }
177
178    return 0;
179}
180
181// static
182void OMXCodec::findMatchingCodecs(
183        const char *mime,
184        bool createEncoder, const char *matchComponentName,
185        uint32_t flags,
186        Vector<CodecNameAndQuirks> *matchingCodecs) {
187    matchingCodecs->clear();
188
189    const MediaCodecList *list = MediaCodecList::getInstance();
190    if (list == NULL) {
191        return;
192    }
193
194    size_t index = 0;
195    for (;;) {
196        ssize_t matchIndex =
197            list->findCodecByType(mime, createEncoder, index);
198
199        if (matchIndex < 0) {
200            break;
201        }
202
203        index = matchIndex + 1;
204
205        const char *componentName = list->getCodecName(matchIndex);
206
207        // If a specific codec is requested, skip the non-matching ones.
208        if (matchComponentName && strcmp(componentName, matchComponentName)) {
209            continue;
210        }
211
212        // When requesting software-only codecs, only push software codecs
213        // When requesting hardware-only codecs, only push hardware codecs
214        // When there is request neither for software-only nor for
215        // hardware-only codecs, push all codecs
216        if (((flags & kSoftwareCodecsOnly) &&   IsSoftwareCodec(componentName)) ||
217            ((flags & kHardwareCodecsOnly) &&  !IsSoftwareCodec(componentName)) ||
218            (!(flags & (kSoftwareCodecsOnly | kHardwareCodecsOnly)))) {
219
220            ssize_t index = matchingCodecs->add();
221            CodecNameAndQuirks *entry = &matchingCodecs->editItemAt(index);
222            entry->mName = String8(componentName);
223            entry->mQuirks = getComponentQuirks(list, matchIndex);
224
225            ALOGV("matching '%s' quirks 0x%08x",
226                  entry->mName.string(), entry->mQuirks);
227        }
228    }
229
230    if (flags & kPreferSoftwareCodecs) {
231        matchingCodecs->sort(CompareSoftwareCodecsFirst);
232    }
233}
234
235// static
236uint32_t OMXCodec::getComponentQuirks(
237        const MediaCodecList *list, size_t index) {
238    uint32_t quirks = 0;
239    if (list->codecHasQuirk(
240                index, "requires-allocate-on-input-ports")) {
241        quirks |= kRequiresAllocateBufferOnInputPorts;
242    }
243    if (list->codecHasQuirk(
244                index, "requires-allocate-on-output-ports")) {
245        quirks |= kRequiresAllocateBufferOnOutputPorts;
246    }
247    if (list->codecHasQuirk(
248                index, "output-buffers-are-unreadable")) {
249        quirks |= kOutputBuffersAreUnreadable;
250    }
251
252    return quirks;
253}
254
255// static
256bool OMXCodec::findCodecQuirks(const char *componentName, uint32_t *quirks) {
257    const MediaCodecList *list = MediaCodecList::getInstance();
258
259    if (list == NULL) {
260        return false;
261    }
262
263    ssize_t index = list->findCodecByName(componentName);
264
265    if (index < 0) {
266        return false;
267    }
268
269    *quirks = getComponentQuirks(list, index);
270
271    return true;
272}
273
274// static
275sp<MediaSource> OMXCodec::Create(
276        const sp<IOMX> &omx,
277        const sp<MetaData> &meta, bool createEncoder,
278        const sp<MediaSource> &source,
279        const char *matchComponentName,
280        uint32_t flags,
281        const sp<ANativeWindow> &nativeWindow) {
282    int32_t requiresSecureBuffers;
283    if (source->getFormat()->findInt32(
284                kKeyRequiresSecureBuffers,
285                &requiresSecureBuffers)
286            && requiresSecureBuffers) {
287        flags |= kIgnoreCodecSpecificData;
288        flags |= kUseSecureInputBuffers;
289    }
290
291    const char *mime;
292    bool success = meta->findCString(kKeyMIMEType, &mime);
293    CHECK(success);
294
295    Vector<CodecNameAndQuirks> matchingCodecs;
296    findMatchingCodecs(
297            mime, createEncoder, matchComponentName, flags, &matchingCodecs);
298
299    if (matchingCodecs.isEmpty()) {
300        ALOGV("No matching codecs! (mime: %s, createEncoder: %s, "
301                "matchComponentName: %s, flags: 0x%x)",
302                mime, createEncoder ? "true" : "false", matchComponentName, flags);
303        return NULL;
304    }
305
306    sp<OMXCodecObserver> observer = new OMXCodecObserver;
307    IOMX::node_id node = 0;
308
309    for (size_t i = 0; i < matchingCodecs.size(); ++i) {
310        const char *componentNameBase = matchingCodecs[i].mName.string();
311        uint32_t quirks = matchingCodecs[i].mQuirks;
312        const char *componentName = componentNameBase;
313
314        AString tmp;
315        if (flags & kUseSecureInputBuffers) {
316            tmp = componentNameBase;
317            tmp.append(".secure");
318
319            componentName = tmp.c_str();
320        }
321
322        if (createEncoder) {
323            sp<MediaSource> softwareCodec =
324                InstantiateSoftwareEncoder(componentName, source, meta);
325
326            if (softwareCodec != NULL) {
327                ALOGV("Successfully allocated software codec '%s'", componentName);
328
329                return softwareCodec;
330            }
331        }
332
333        ALOGV("Attempting to allocate OMX node '%s'", componentName);
334
335        if (!createEncoder
336                && (quirks & kOutputBuffersAreUnreadable)
337                && (flags & kClientNeedsFramebuffer)) {
338            if (strncmp(componentName, "OMX.SEC.", 8)) {
339                // For OMX.SEC.* decoders we can enable a special mode that
340                // gives the client access to the framebuffer contents.
341
342                ALOGW("Component '%s' does not give the client access to "
343                     "the framebuffer contents. Skipping.",
344                     componentName);
345
346                continue;
347            }
348        }
349
350        status_t err = omx->allocateNode(componentName, observer, &node);
351        if (err == OK) {
352            ALOGV("Successfully allocated OMX node '%s'", componentName);
353
354            sp<OMXCodec> codec = new OMXCodec(
355                    omx, node, quirks, flags,
356                    createEncoder, mime, componentName,
357                    source, nativeWindow);
358
359            observer->setCodec(codec);
360
361            err = codec->configureCodec(meta);
362
363            if (err == OK) {
364                if (!strcmp("OMX.Nvidia.mpeg2v.decode", componentName)) {
365                    codec->mFlags |= kOnlySubmitOneInputBufferAtOneTime;
366                }
367
368                return codec;
369            }
370
371            ALOGV("Failed to configure codec '%s'", componentName);
372        }
373    }
374
375    return NULL;
376}
377
378status_t OMXCodec::parseAVCCodecSpecificData(
379        const void *data, size_t size,
380        unsigned *profile, unsigned *level) {
381    const uint8_t *ptr = (const uint8_t *)data;
382
383    // verify minimum size and configurationVersion == 1.
384    if (size < 7 || ptr[0] != 1) {
385        return ERROR_MALFORMED;
386    }
387
388    *profile = ptr[1];
389    *level = ptr[3];
390
391    // There is decodable content out there that fails the following
392    // assertion, let's be lenient for now...
393    // CHECK((ptr[4] >> 2) == 0x3f);  // reserved
394
395    size_t lengthSize = 1 + (ptr[4] & 3);
396
397    // commented out check below as H264_QVGA_500_NO_AUDIO.3gp
398    // violates it...
399    // CHECK((ptr[5] >> 5) == 7);  // reserved
400
401    size_t numSeqParameterSets = ptr[5] & 31;
402
403    ptr += 6;
404    size -= 6;
405
406    for (size_t i = 0; i < numSeqParameterSets; ++i) {
407        if (size < 2) {
408            return ERROR_MALFORMED;
409        }
410
411        size_t length = U16_AT(ptr);
412
413        ptr += 2;
414        size -= 2;
415
416        if (size < length) {
417            return ERROR_MALFORMED;
418        }
419
420        addCodecSpecificData(ptr, length);
421
422        ptr += length;
423        size -= length;
424    }
425
426    if (size < 1) {
427        return ERROR_MALFORMED;
428    }
429
430    size_t numPictureParameterSets = *ptr;
431    ++ptr;
432    --size;
433
434    for (size_t i = 0; i < numPictureParameterSets; ++i) {
435        if (size < 2) {
436            return ERROR_MALFORMED;
437        }
438
439        size_t length = U16_AT(ptr);
440
441        ptr += 2;
442        size -= 2;
443
444        if (size < length) {
445            return ERROR_MALFORMED;
446        }
447
448        addCodecSpecificData(ptr, length);
449
450        ptr += length;
451        size -= length;
452    }
453
454    return OK;
455}
456
457status_t OMXCodec::configureCodec(const sp<MetaData> &meta) {
458    ALOGV("configureCodec protected=%d",
459         (mFlags & kEnableGrallocUsageProtected) ? 1 : 0);
460
461    if (!(mFlags & kIgnoreCodecSpecificData)) {
462        uint32_t type;
463        const void *data;
464        size_t size;
465        if (meta->findData(kKeyESDS, &type, &data, &size)) {
466            ESDS esds((const char *)data, size);
467            CHECK_EQ(esds.InitCheck(), (status_t)OK);
468
469            const void *codec_specific_data;
470            size_t codec_specific_data_size;
471            esds.getCodecSpecificInfo(
472                    &codec_specific_data, &codec_specific_data_size);
473
474            addCodecSpecificData(
475                    codec_specific_data, codec_specific_data_size);
476        } else if (meta->findData(kKeyAVCC, &type, &data, &size)) {
477            // Parse the AVCDecoderConfigurationRecord
478
479            unsigned profile, level;
480            status_t err;
481            if ((err = parseAVCCodecSpecificData(
482                            data, size, &profile, &level)) != OK) {
483                ALOGE("Malformed AVC codec specific data.");
484                return err;
485            }
486
487            CODEC_LOGI(
488                    "AVC profile = %u (%s), level = %u",
489                    profile, AVCProfileToString(profile), level);
490        } else if (meta->findData(kKeyVorbisInfo, &type, &data, &size)) {
491            addCodecSpecificData(data, size);
492
493            CHECK(meta->findData(kKeyVorbisBooks, &type, &data, &size));
494            addCodecSpecificData(data, size);
495        }
496    }
497
498    int32_t bitRate = 0;
499    if (mIsEncoder) {
500        CHECK(meta->findInt32(kKeyBitRate, &bitRate));
501    }
502    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mMIME)) {
503        setAMRFormat(false /* isWAMR */, bitRate);
504    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mMIME)) {
505        setAMRFormat(true /* isWAMR */, bitRate);
506    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mMIME)) {
507        int32_t numChannels, sampleRate, aacProfile;
508        CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
509        CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
510
511        if (!meta->findInt32(kKeyAACProfile, &aacProfile)) {
512            aacProfile = OMX_AUDIO_AACObjectNull;
513        }
514
515        int32_t isADTS;
516        if (!meta->findInt32(kKeyIsADTS, &isADTS)) {
517            isADTS = false;
518        }
519
520        status_t err = setAACFormat(numChannels, sampleRate, bitRate, aacProfile, isADTS);
521        if (err != OK) {
522            CODEC_LOGE("setAACFormat() failed (err = %d)", err);
523            return err;
524        }
525    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_ALAW, mMIME)
526            || !strcasecmp(MEDIA_MIMETYPE_AUDIO_G711_MLAW, mMIME)) {
527        // These are PCM-like formats with a fixed sample rate but
528        // a variable number of channels.
529
530        int32_t numChannels;
531        CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
532
533        setG711Format(numChannels);
534    } else if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_RAW, mMIME)) {
535        CHECK(!mIsEncoder);
536
537        int32_t numChannels, sampleRate;
538        CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
539        CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
540
541        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
542    }
543
544    if (!strncasecmp(mMIME, "video/", 6)) {
545
546        if (mIsEncoder) {
547            setVideoInputFormat(mMIME, meta);
548        } else {
549            status_t err = setVideoOutputFormat(
550                    mMIME, meta);
551
552            if (err != OK) {
553                return err;
554            }
555        }
556    }
557
558    int32_t maxInputSize;
559    if (meta->findInt32(kKeyMaxInputSize, &maxInputSize)) {
560        setMinBufferSize(kPortIndexInput, (OMX_U32)maxInputSize);
561    }
562
563    initOutputFormat(meta);
564
565    if ((mFlags & kClientNeedsFramebuffer)
566            && !strncmp(mComponentName, "OMX.SEC.", 8)) {
567        // This appears to no longer be needed???
568
569        OMX_INDEXTYPE index;
570
571        status_t err =
572            mOMX->getExtensionIndex(
573                    mNode,
574                    "OMX.SEC.index.ThumbnailMode",
575                    &index);
576
577        if (err != OK) {
578            return err;
579        }
580
581        OMX_BOOL enable = OMX_TRUE;
582        err = mOMX->setConfig(mNode, index, &enable, sizeof(enable));
583
584        if (err != OK) {
585            CODEC_LOGE("setConfig('OMX.SEC.index.ThumbnailMode') "
586                       "returned error 0x%08x", err);
587
588            return err;
589        }
590
591        mQuirks &= ~kOutputBuffersAreUnreadable;
592    }
593
594    if (mNativeWindow != NULL
595        && !mIsEncoder
596        && !strncasecmp(mMIME, "video/", 6)
597        && !strncmp(mComponentName, "OMX.", 4)) {
598        status_t err = initNativeWindow();
599        if (err != OK) {
600            return err;
601        }
602    }
603
604    return OK;
605}
606
607void OMXCodec::setMinBufferSize(OMX_U32 portIndex, OMX_U32 size) {
608    OMX_PARAM_PORTDEFINITIONTYPE def;
609    InitOMXParams(&def);
610    def.nPortIndex = portIndex;
611
612    status_t err = mOMX->getParameter(
613            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
614    CHECK_EQ(err, (status_t)OK);
615
616    if ((portIndex == kPortIndexInput && (mQuirks & kInputBufferSizesAreBogus))
617        || (def.nBufferSize < size)) {
618        def.nBufferSize = size;
619    }
620
621    err = mOMX->setParameter(
622            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
623    CHECK_EQ(err, (status_t)OK);
624
625    err = mOMX->getParameter(
626            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
627    CHECK_EQ(err, (status_t)OK);
628
629    // Make sure the setting actually stuck.
630    if (portIndex == kPortIndexInput
631            && (mQuirks & kInputBufferSizesAreBogus)) {
632        CHECK_EQ(def.nBufferSize, size);
633    } else {
634        CHECK(def.nBufferSize >= size);
635    }
636}
637
638status_t OMXCodec::setVideoPortFormatType(
639        OMX_U32 portIndex,
640        OMX_VIDEO_CODINGTYPE compressionFormat,
641        OMX_COLOR_FORMATTYPE colorFormat) {
642    OMX_VIDEO_PARAM_PORTFORMATTYPE format;
643    InitOMXParams(&format);
644    format.nPortIndex = portIndex;
645    format.nIndex = 0;
646    bool found = false;
647
648    OMX_U32 index = 0;
649    for (;;) {
650        format.nIndex = index;
651        status_t err = mOMX->getParameter(
652                mNode, OMX_IndexParamVideoPortFormat,
653                &format, sizeof(format));
654
655        if (err != OK) {
656            return err;
657        }
658
659        // The following assertion is violated by TI's video decoder.
660        // CHECK_EQ(format.nIndex, index);
661
662#if 1
663        CODEC_LOGV("portIndex: %ld, index: %ld, eCompressionFormat=%d eColorFormat=%d",
664             portIndex,
665             index, format.eCompressionFormat, format.eColorFormat);
666#endif
667
668        if (format.eCompressionFormat == compressionFormat
669                && format.eColorFormat == colorFormat) {
670            found = true;
671            break;
672        }
673
674        ++index;
675        if (index >= kMaxColorFormatSupported) {
676            CODEC_LOGE("color format %d or compression format %d is not supported",
677                colorFormat, compressionFormat);
678            return UNKNOWN_ERROR;
679        }
680    }
681
682    if (!found) {
683        return UNKNOWN_ERROR;
684    }
685
686    CODEC_LOGV("found a match.");
687    status_t err = mOMX->setParameter(
688            mNode, OMX_IndexParamVideoPortFormat,
689            &format, sizeof(format));
690
691    return err;
692}
693
694static size_t getFrameSize(
695        OMX_COLOR_FORMATTYPE colorFormat, int32_t width, int32_t height) {
696    switch (colorFormat) {
697        case OMX_COLOR_FormatYCbYCr:
698        case OMX_COLOR_FormatCbYCrY:
699            return width * height * 2;
700
701        case OMX_COLOR_FormatYUV420Planar:
702        case OMX_COLOR_FormatYUV420SemiPlanar:
703        case OMX_TI_COLOR_FormatYUV420PackedSemiPlanar:
704        /*
705        * FIXME: For the Opaque color format, the frame size does not
706        * need to be (w*h*3)/2. It just needs to
707        * be larger than certain minimum buffer size. However,
708        * currently, this opaque foramt has been tested only on
709        * YUV420 formats. If that is changed, then we need to revisit
710        * this part in the future
711        */
712        case OMX_COLOR_FormatAndroidOpaque:
713            return (width * height * 3) / 2;
714
715        default:
716            CHECK(!"Should not be here. Unsupported color format.");
717            break;
718    }
719}
720
721status_t OMXCodec::findTargetColorFormat(
722        const sp<MetaData>& meta, OMX_COLOR_FORMATTYPE *colorFormat) {
723    ALOGV("findTargetColorFormat");
724    CHECK(mIsEncoder);
725
726    *colorFormat = OMX_COLOR_FormatYUV420SemiPlanar;
727    int32_t targetColorFormat;
728    if (meta->findInt32(kKeyColorFormat, &targetColorFormat)) {
729        *colorFormat = (OMX_COLOR_FORMATTYPE) targetColorFormat;
730    }
731
732    // Check whether the target color format is supported.
733    return isColorFormatSupported(*colorFormat, kPortIndexInput);
734}
735
736status_t OMXCodec::isColorFormatSupported(
737        OMX_COLOR_FORMATTYPE colorFormat, int portIndex) {
738    ALOGV("isColorFormatSupported: %d", static_cast<int>(colorFormat));
739
740    // Enumerate all the color formats supported by
741    // the omx component to see whether the given
742    // color format is supported.
743    OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat;
744    InitOMXParams(&portFormat);
745    portFormat.nPortIndex = portIndex;
746    OMX_U32 index = 0;
747    portFormat.nIndex = index;
748    while (true) {
749        if (OMX_ErrorNone != mOMX->getParameter(
750                mNode, OMX_IndexParamVideoPortFormat,
751                &portFormat, sizeof(portFormat))) {
752            break;
753        }
754        // Make sure that omx component does not overwrite
755        // the incremented index (bug 2897413).
756        CHECK_EQ(index, portFormat.nIndex);
757        if (portFormat.eColorFormat == colorFormat) {
758            CODEC_LOGV("Found supported color format: %d", portFormat.eColorFormat);
759            return OK;  // colorFormat is supported!
760        }
761        ++index;
762        portFormat.nIndex = index;
763
764        if (index >= kMaxColorFormatSupported) {
765            CODEC_LOGE("More than %ld color formats are supported???", index);
766            break;
767        }
768    }
769
770    CODEC_LOGE("color format %d is not supported", colorFormat);
771    return UNKNOWN_ERROR;
772}
773
774void OMXCodec::setVideoInputFormat(
775        const char *mime, const sp<MetaData>& meta) {
776
777    int32_t width, height, frameRate, bitRate, stride, sliceHeight;
778    bool success = meta->findInt32(kKeyWidth, &width);
779    success = success && meta->findInt32(kKeyHeight, &height);
780    success = success && meta->findInt32(kKeyFrameRate, &frameRate);
781    success = success && meta->findInt32(kKeyBitRate, &bitRate);
782    success = success && meta->findInt32(kKeyStride, &stride);
783    success = success && meta->findInt32(kKeySliceHeight, &sliceHeight);
784    CHECK(success);
785    CHECK(stride != 0);
786
787    OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused;
788    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
789        compressionFormat = OMX_VIDEO_CodingAVC;
790    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
791        compressionFormat = OMX_VIDEO_CodingMPEG4;
792    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
793        compressionFormat = OMX_VIDEO_CodingH263;
794    } else {
795        ALOGE("Not a supported video mime type: %s", mime);
796        CHECK(!"Should not be here. Not a supported video mime type.");
797    }
798
799    OMX_COLOR_FORMATTYPE colorFormat;
800    CHECK_EQ((status_t)OK, findTargetColorFormat(meta, &colorFormat));
801
802    status_t err;
803    OMX_PARAM_PORTDEFINITIONTYPE def;
804    OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
805
806    //////////////////////// Input port /////////////////////////
807    CHECK_EQ(setVideoPortFormatType(
808            kPortIndexInput, OMX_VIDEO_CodingUnused,
809            colorFormat), (status_t)OK);
810
811    InitOMXParams(&def);
812    def.nPortIndex = kPortIndexInput;
813
814    err = mOMX->getParameter(
815            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
816    CHECK_EQ(err, (status_t)OK);
817
818    def.nBufferSize = getFrameSize(colorFormat,
819            stride > 0? stride: -stride, sliceHeight);
820
821    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo);
822
823    video_def->nFrameWidth = width;
824    video_def->nFrameHeight = height;
825    video_def->nStride = stride;
826    video_def->nSliceHeight = sliceHeight;
827    video_def->xFramerate = (frameRate << 16);  // Q16 format
828    video_def->eCompressionFormat = OMX_VIDEO_CodingUnused;
829    video_def->eColorFormat = colorFormat;
830
831    err = mOMX->setParameter(
832            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
833    CHECK_EQ(err, (status_t)OK);
834
835    //////////////////////// Output port /////////////////////////
836    CHECK_EQ(setVideoPortFormatType(
837            kPortIndexOutput, compressionFormat, OMX_COLOR_FormatUnused),
838            (status_t)OK);
839    InitOMXParams(&def);
840    def.nPortIndex = kPortIndexOutput;
841
842    err = mOMX->getParameter(
843            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
844
845    CHECK_EQ(err, (status_t)OK);
846    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo);
847
848    video_def->nFrameWidth = width;
849    video_def->nFrameHeight = height;
850    video_def->xFramerate = 0;      // No need for output port
851    video_def->nBitrate = bitRate;  // Q16 format
852    video_def->eCompressionFormat = compressionFormat;
853    video_def->eColorFormat = OMX_COLOR_FormatUnused;
854    if (mQuirks & kRequiresLargerEncoderOutputBuffer) {
855        // Increases the output buffer size
856        def.nBufferSize = ((def.nBufferSize * 3) >> 1);
857    }
858
859    err = mOMX->setParameter(
860            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
861    CHECK_EQ(err, (status_t)OK);
862
863    /////////////////// Codec-specific ////////////////////////
864    switch (compressionFormat) {
865        case OMX_VIDEO_CodingMPEG4:
866        {
867            CHECK_EQ(setupMPEG4EncoderParameters(meta), (status_t)OK);
868            break;
869        }
870
871        case OMX_VIDEO_CodingH263:
872            CHECK_EQ(setupH263EncoderParameters(meta), (status_t)OK);
873            break;
874
875        case OMX_VIDEO_CodingAVC:
876        {
877            CHECK_EQ(setupAVCEncoderParameters(meta), (status_t)OK);
878            break;
879        }
880
881        default:
882            CHECK(!"Support for this compressionFormat to be implemented.");
883            break;
884    }
885}
886
887static OMX_U32 setPFramesSpacing(int32_t iFramesInterval, int32_t frameRate) {
888    if (iFramesInterval < 0) {
889        return 0xFFFFFFFF;
890    } else if (iFramesInterval == 0) {
891        return 0;
892    }
893    OMX_U32 ret = frameRate * iFramesInterval - 1;
894    CHECK(ret > 1);
895    return ret;
896}
897
898status_t OMXCodec::setupErrorCorrectionParameters() {
899    OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE errorCorrectionType;
900    InitOMXParams(&errorCorrectionType);
901    errorCorrectionType.nPortIndex = kPortIndexOutput;
902
903    status_t err = mOMX->getParameter(
904            mNode, OMX_IndexParamVideoErrorCorrection,
905            &errorCorrectionType, sizeof(errorCorrectionType));
906    if (err != OK) {
907        ALOGW("Error correction param query is not supported");
908        return OK;  // Optional feature. Ignore this failure
909    }
910
911    errorCorrectionType.bEnableHEC = OMX_FALSE;
912    errorCorrectionType.bEnableResync = OMX_TRUE;
913    errorCorrectionType.nResynchMarkerSpacing = 256;
914    errorCorrectionType.bEnableDataPartitioning = OMX_FALSE;
915    errorCorrectionType.bEnableRVLC = OMX_FALSE;
916
917    err = mOMX->setParameter(
918            mNode, OMX_IndexParamVideoErrorCorrection,
919            &errorCorrectionType, sizeof(errorCorrectionType));
920    if (err != OK) {
921        ALOGW("Error correction param configuration is not supported");
922    }
923
924    // Optional feature. Ignore the failure.
925    return OK;
926}
927
928status_t OMXCodec::setupBitRate(int32_t bitRate) {
929    OMX_VIDEO_PARAM_BITRATETYPE bitrateType;
930    InitOMXParams(&bitrateType);
931    bitrateType.nPortIndex = kPortIndexOutput;
932
933    status_t err = mOMX->getParameter(
934            mNode, OMX_IndexParamVideoBitrate,
935            &bitrateType, sizeof(bitrateType));
936    CHECK_EQ(err, (status_t)OK);
937
938    bitrateType.eControlRate = OMX_Video_ControlRateVariable;
939    bitrateType.nTargetBitrate = bitRate;
940
941    err = mOMX->setParameter(
942            mNode, OMX_IndexParamVideoBitrate,
943            &bitrateType, sizeof(bitrateType));
944    CHECK_EQ(err, (status_t)OK);
945    return OK;
946}
947
948status_t OMXCodec::getVideoProfileLevel(
949        const sp<MetaData>& meta,
950        const CodecProfileLevel& defaultProfileLevel,
951        CodecProfileLevel &profileLevel) {
952    CODEC_LOGV("Default profile: %ld, level %ld",
953            defaultProfileLevel.mProfile, defaultProfileLevel.mLevel);
954
955    // Are the default profile and level overwriten?
956    int32_t profile, level;
957    if (!meta->findInt32(kKeyVideoProfile, &profile)) {
958        profile = defaultProfileLevel.mProfile;
959    }
960    if (!meta->findInt32(kKeyVideoLevel, &level)) {
961        level = defaultProfileLevel.mLevel;
962    }
963    CODEC_LOGV("Target profile: %d, level: %d", profile, level);
964
965    // Are the target profile and level supported by the encoder?
966    OMX_VIDEO_PARAM_PROFILELEVELTYPE param;
967    InitOMXParams(&param);
968    param.nPortIndex = kPortIndexOutput;
969    for (param.nProfileIndex = 0;; ++param.nProfileIndex) {
970        status_t err = mOMX->getParameter(
971                mNode, OMX_IndexParamVideoProfileLevelQuerySupported,
972                &param, sizeof(param));
973
974        if (err != OK) break;
975
976        int32_t supportedProfile = static_cast<int32_t>(param.eProfile);
977        int32_t supportedLevel = static_cast<int32_t>(param.eLevel);
978        CODEC_LOGV("Supported profile: %d, level %d",
979            supportedProfile, supportedLevel);
980
981        if (profile == supportedProfile &&
982            level <= supportedLevel) {
983            // We can further check whether the level is a valid
984            // value; but we will leave that to the omx encoder component
985            // via OMX_SetParameter call.
986            profileLevel.mProfile = profile;
987            profileLevel.mLevel = level;
988            return OK;
989        }
990    }
991
992    CODEC_LOGE("Target profile (%d) and level (%d) is not supported",
993            profile, level);
994    return BAD_VALUE;
995}
996
997status_t OMXCodec::setupH263EncoderParameters(const sp<MetaData>& meta) {
998    int32_t iFramesInterval, frameRate, bitRate;
999    bool success = meta->findInt32(kKeyBitRate, &bitRate);
1000    success = success && meta->findInt32(kKeyFrameRate, &frameRate);
1001    success = success && meta->findInt32(kKeyIFramesInterval, &iFramesInterval);
1002    CHECK(success);
1003    OMX_VIDEO_PARAM_H263TYPE h263type;
1004    InitOMXParams(&h263type);
1005    h263type.nPortIndex = kPortIndexOutput;
1006
1007    status_t err = mOMX->getParameter(
1008            mNode, OMX_IndexParamVideoH263, &h263type, sizeof(h263type));
1009    CHECK_EQ(err, (status_t)OK);
1010
1011    h263type.nAllowedPictureTypes =
1012        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
1013
1014    h263type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate);
1015    if (h263type.nPFrames == 0) {
1016        h263type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI;
1017    }
1018    h263type.nBFrames = 0;
1019
1020    // Check profile and level parameters
1021    CodecProfileLevel defaultProfileLevel, profileLevel;
1022    defaultProfileLevel.mProfile = h263type.eProfile;
1023    defaultProfileLevel.mLevel = h263type.eLevel;
1024    err = getVideoProfileLevel(meta, defaultProfileLevel, profileLevel);
1025    if (err != OK) return err;
1026    h263type.eProfile = static_cast<OMX_VIDEO_H263PROFILETYPE>(profileLevel.mProfile);
1027    h263type.eLevel = static_cast<OMX_VIDEO_H263LEVELTYPE>(profileLevel.mLevel);
1028
1029    h263type.bPLUSPTYPEAllowed = OMX_FALSE;
1030    h263type.bForceRoundingTypeToZero = OMX_FALSE;
1031    h263type.nPictureHeaderRepetition = 0;
1032    h263type.nGOBHeaderInterval = 0;
1033
1034    err = mOMX->setParameter(
1035            mNode, OMX_IndexParamVideoH263, &h263type, sizeof(h263type));
1036    CHECK_EQ(err, (status_t)OK);
1037
1038    CHECK_EQ(setupBitRate(bitRate), (status_t)OK);
1039    CHECK_EQ(setupErrorCorrectionParameters(), (status_t)OK);
1040
1041    return OK;
1042}
1043
1044status_t OMXCodec::setupMPEG4EncoderParameters(const sp<MetaData>& meta) {
1045    int32_t iFramesInterval, frameRate, bitRate;
1046    bool success = meta->findInt32(kKeyBitRate, &bitRate);
1047    success = success && meta->findInt32(kKeyFrameRate, &frameRate);
1048    success = success && meta->findInt32(kKeyIFramesInterval, &iFramesInterval);
1049    CHECK(success);
1050    OMX_VIDEO_PARAM_MPEG4TYPE mpeg4type;
1051    InitOMXParams(&mpeg4type);
1052    mpeg4type.nPortIndex = kPortIndexOutput;
1053
1054    status_t err = mOMX->getParameter(
1055            mNode, OMX_IndexParamVideoMpeg4, &mpeg4type, sizeof(mpeg4type));
1056    CHECK_EQ(err, (status_t)OK);
1057
1058    mpeg4type.nSliceHeaderSpacing = 0;
1059    mpeg4type.bSVH = OMX_FALSE;
1060    mpeg4type.bGov = OMX_FALSE;
1061
1062    mpeg4type.nAllowedPictureTypes =
1063        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
1064
1065    mpeg4type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate);
1066    if (mpeg4type.nPFrames == 0) {
1067        mpeg4type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI;
1068    }
1069    mpeg4type.nBFrames = 0;
1070    mpeg4type.nIDCVLCThreshold = 0;
1071    mpeg4type.bACPred = OMX_TRUE;
1072    mpeg4type.nMaxPacketSize = 256;
1073    mpeg4type.nTimeIncRes = 1000;
1074    mpeg4type.nHeaderExtension = 0;
1075    mpeg4type.bReversibleVLC = OMX_FALSE;
1076
1077    // Check profile and level parameters
1078    CodecProfileLevel defaultProfileLevel, profileLevel;
1079    defaultProfileLevel.mProfile = mpeg4type.eProfile;
1080    defaultProfileLevel.mLevel = mpeg4type.eLevel;
1081    err = getVideoProfileLevel(meta, defaultProfileLevel, profileLevel);
1082    if (err != OK) return err;
1083    mpeg4type.eProfile = static_cast<OMX_VIDEO_MPEG4PROFILETYPE>(profileLevel.mProfile);
1084    mpeg4type.eLevel = static_cast<OMX_VIDEO_MPEG4LEVELTYPE>(profileLevel.mLevel);
1085
1086    err = mOMX->setParameter(
1087            mNode, OMX_IndexParamVideoMpeg4, &mpeg4type, sizeof(mpeg4type));
1088    CHECK_EQ(err, (status_t)OK);
1089
1090    CHECK_EQ(setupBitRate(bitRate), (status_t)OK);
1091    CHECK_EQ(setupErrorCorrectionParameters(), (status_t)OK);
1092
1093    return OK;
1094}
1095
1096status_t OMXCodec::setupAVCEncoderParameters(const sp<MetaData>& meta) {
1097    int32_t iFramesInterval, frameRate, bitRate;
1098    bool success = meta->findInt32(kKeyBitRate, &bitRate);
1099    success = success && meta->findInt32(kKeyFrameRate, &frameRate);
1100    success = success && meta->findInt32(kKeyIFramesInterval, &iFramesInterval);
1101    CHECK(success);
1102
1103    OMX_VIDEO_PARAM_AVCTYPE h264type;
1104    InitOMXParams(&h264type);
1105    h264type.nPortIndex = kPortIndexOutput;
1106
1107    status_t err = mOMX->getParameter(
1108            mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type));
1109    CHECK_EQ(err, (status_t)OK);
1110
1111    h264type.nAllowedPictureTypes =
1112        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
1113
1114    // Check profile and level parameters
1115    CodecProfileLevel defaultProfileLevel, profileLevel;
1116    defaultProfileLevel.mProfile = h264type.eProfile;
1117    defaultProfileLevel.mLevel = h264type.eLevel;
1118    err = getVideoProfileLevel(meta, defaultProfileLevel, profileLevel);
1119    if (err != OK) return err;
1120    h264type.eProfile = static_cast<OMX_VIDEO_AVCPROFILETYPE>(profileLevel.mProfile);
1121    h264type.eLevel = static_cast<OMX_VIDEO_AVCLEVELTYPE>(profileLevel.mLevel);
1122
1123    // XXX
1124    if (h264type.eProfile != OMX_VIDEO_AVCProfileBaseline) {
1125        ALOGW("Use baseline profile instead of %d for AVC recording",
1126            h264type.eProfile);
1127        h264type.eProfile = OMX_VIDEO_AVCProfileBaseline;
1128    }
1129
1130    if (h264type.eProfile == OMX_VIDEO_AVCProfileBaseline) {
1131        h264type.nSliceHeaderSpacing = 0;
1132        h264type.bUseHadamard = OMX_TRUE;
1133        h264type.nRefFrames = 1;
1134        h264type.nBFrames = 0;
1135        h264type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate);
1136        if (h264type.nPFrames == 0) {
1137            h264type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI;
1138        }
1139        h264type.nRefIdx10ActiveMinus1 = 0;
1140        h264type.nRefIdx11ActiveMinus1 = 0;
1141        h264type.bEntropyCodingCABAC = OMX_FALSE;
1142        h264type.bWeightedPPrediction = OMX_FALSE;
1143        h264type.bconstIpred = OMX_FALSE;
1144        h264type.bDirect8x8Inference = OMX_FALSE;
1145        h264type.bDirectSpatialTemporal = OMX_FALSE;
1146        h264type.nCabacInitIdc = 0;
1147    }
1148
1149    if (h264type.nBFrames != 0) {
1150        h264type.nAllowedPictureTypes |= OMX_VIDEO_PictureTypeB;
1151    }
1152
1153    h264type.bEnableUEP = OMX_FALSE;
1154    h264type.bEnableFMO = OMX_FALSE;
1155    h264type.bEnableASO = OMX_FALSE;
1156    h264type.bEnableRS = OMX_FALSE;
1157    h264type.bFrameMBsOnly = OMX_TRUE;
1158    h264type.bMBAFF = OMX_FALSE;
1159    h264type.eLoopFilterMode = OMX_VIDEO_AVCLoopFilterEnable;
1160
1161    err = mOMX->setParameter(
1162            mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type));
1163    CHECK_EQ(err, (status_t)OK);
1164
1165    CHECK_EQ(setupBitRate(bitRate), (status_t)OK);
1166
1167    return OK;
1168}
1169
1170status_t OMXCodec::setVideoOutputFormat(
1171        const char *mime, const sp<MetaData>& meta) {
1172
1173    int32_t width, height;
1174    bool success = meta->findInt32(kKeyWidth, &width);
1175    success = success && meta->findInt32(kKeyHeight, &height);
1176    CHECK(success);
1177
1178    CODEC_LOGV("setVideoOutputFormat width=%ld, height=%ld", width, height);
1179
1180    OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused;
1181    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
1182        compressionFormat = OMX_VIDEO_CodingAVC;
1183    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
1184        compressionFormat = OMX_VIDEO_CodingMPEG4;
1185    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
1186        compressionFormat = OMX_VIDEO_CodingH263;
1187    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_VPX, mime)) {
1188        compressionFormat = OMX_VIDEO_CodingVPX;
1189    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG2, mime)) {
1190        compressionFormat = OMX_VIDEO_CodingMPEG2;
1191    } else {
1192        ALOGE("Not a supported video mime type: %s", mime);
1193        CHECK(!"Should not be here. Not a supported video mime type.");
1194    }
1195
1196    status_t err = setVideoPortFormatType(
1197            kPortIndexInput, compressionFormat, OMX_COLOR_FormatUnused);
1198
1199    if (err != OK) {
1200        return err;
1201    }
1202
1203#if 1
1204    {
1205        OMX_VIDEO_PARAM_PORTFORMATTYPE format;
1206        InitOMXParams(&format);
1207        format.nPortIndex = kPortIndexOutput;
1208        format.nIndex = 0;
1209
1210        status_t err = mOMX->getParameter(
1211                mNode, OMX_IndexParamVideoPortFormat,
1212                &format, sizeof(format));
1213        CHECK_EQ(err, (status_t)OK);
1214        CHECK_EQ((int)format.eCompressionFormat, (int)OMX_VIDEO_CodingUnused);
1215
1216        int32_t colorFormat;
1217        if (meta->findInt32(kKeyColorFormat, &colorFormat)
1218                && colorFormat != OMX_COLOR_FormatUnused
1219                && colorFormat != format.eColorFormat) {
1220
1221            while (OMX_ErrorNoMore != err) {
1222                format.nIndex++;
1223                err = mOMX->getParameter(
1224                        mNode, OMX_IndexParamVideoPortFormat,
1225                            &format, sizeof(format));
1226                if (format.eColorFormat == colorFormat) {
1227                    break;
1228                }
1229            }
1230            if (format.eColorFormat != colorFormat) {
1231                CODEC_LOGE("Color format %d is not supported", colorFormat);
1232                return ERROR_UNSUPPORTED;
1233            }
1234        }
1235
1236        err = mOMX->setParameter(
1237                mNode, OMX_IndexParamVideoPortFormat,
1238                &format, sizeof(format));
1239
1240        if (err != OK) {
1241            return err;
1242        }
1243    }
1244#endif
1245
1246    OMX_PARAM_PORTDEFINITIONTYPE def;
1247    InitOMXParams(&def);
1248    def.nPortIndex = kPortIndexInput;
1249
1250    OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
1251
1252    err = mOMX->getParameter(
1253            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1254
1255    CHECK_EQ(err, (status_t)OK);
1256
1257#if 1
1258    // XXX Need a (much) better heuristic to compute input buffer sizes.
1259    const size_t X = 64 * 1024;
1260    if (def.nBufferSize < X) {
1261        def.nBufferSize = X;
1262    }
1263#endif
1264
1265    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo);
1266
1267    video_def->nFrameWidth = width;
1268    video_def->nFrameHeight = height;
1269
1270    video_def->eCompressionFormat = compressionFormat;
1271    video_def->eColorFormat = OMX_COLOR_FormatUnused;
1272
1273    err = mOMX->setParameter(
1274            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1275
1276    if (err != OK) {
1277        return err;
1278    }
1279
1280    ////////////////////////////////////////////////////////////////////////////
1281
1282    InitOMXParams(&def);
1283    def.nPortIndex = kPortIndexOutput;
1284
1285    err = mOMX->getParameter(
1286            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1287    CHECK_EQ(err, (status_t)OK);
1288    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainVideo);
1289
1290#if 0
1291    def.nBufferSize =
1292        (((width + 15) & -16) * ((height + 15) & -16) * 3) / 2;  // YUV420
1293#endif
1294
1295    video_def->nFrameWidth = width;
1296    video_def->nFrameHeight = height;
1297
1298    err = mOMX->setParameter(
1299            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1300
1301    return err;
1302}
1303
1304OMXCodec::OMXCodec(
1305        const sp<IOMX> &omx, IOMX::node_id node,
1306        uint32_t quirks, uint32_t flags,
1307        bool isEncoder,
1308        const char *mime,
1309        const char *componentName,
1310        const sp<MediaSource> &source,
1311        const sp<ANativeWindow> &nativeWindow)
1312    : mOMX(omx),
1313      mOMXLivesLocally(omx->livesLocally(node, getpid())),
1314      mNode(node),
1315      mQuirks(quirks),
1316      mFlags(flags),
1317      mIsEncoder(isEncoder),
1318      mIsVideo(!strncasecmp("video/", mime, 6)),
1319      mMIME(strdup(mime)),
1320      mComponentName(strdup(componentName)),
1321      mSource(source),
1322      mCodecSpecificDataIndex(0),
1323      mState(LOADED),
1324      mInitialBufferSubmit(true),
1325      mSignalledEOS(false),
1326      mNoMoreOutputData(false),
1327      mOutputPortSettingsHaveChanged(false),
1328      mSeekTimeUs(-1),
1329      mSeekMode(ReadOptions::SEEK_CLOSEST_SYNC),
1330      mTargetTimeUs(-1),
1331      mOutputPortSettingsChangedPending(false),
1332      mSkipCutBuffer(NULL),
1333      mLeftOverBuffer(NULL),
1334      mPaused(false),
1335      mNativeWindow(
1336              (!strncmp(componentName, "OMX.google.", 11)
1337              || !strcmp(componentName, "OMX.Nvidia.mpeg2v.decode"))
1338                        ? NULL : nativeWindow) {
1339    mPortStatus[kPortIndexInput] = ENABLED;
1340    mPortStatus[kPortIndexOutput] = ENABLED;
1341
1342    setComponentRole();
1343}
1344
1345// static
1346void OMXCodec::setComponentRole(
1347        const sp<IOMX> &omx, IOMX::node_id node, bool isEncoder,
1348        const char *mime) {
1349    struct MimeToRole {
1350        const char *mime;
1351        const char *decoderRole;
1352        const char *encoderRole;
1353    };
1354
1355    static const MimeToRole kMimeToRole[] = {
1356        { MEDIA_MIMETYPE_AUDIO_MPEG,
1357            "audio_decoder.mp3", "audio_encoder.mp3" },
1358        { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_I,
1359            "audio_decoder.mp1", "audio_encoder.mp1" },
1360        { MEDIA_MIMETYPE_AUDIO_MPEG_LAYER_II,
1361            "audio_decoder.mp2", "audio_encoder.mp2" },
1362        { MEDIA_MIMETYPE_AUDIO_AMR_NB,
1363            "audio_decoder.amrnb", "audio_encoder.amrnb" },
1364        { MEDIA_MIMETYPE_AUDIO_AMR_WB,
1365            "audio_decoder.amrwb", "audio_encoder.amrwb" },
1366        { MEDIA_MIMETYPE_AUDIO_AAC,
1367            "audio_decoder.aac", "audio_encoder.aac" },
1368        { MEDIA_MIMETYPE_AUDIO_VORBIS,
1369            "audio_decoder.vorbis", "audio_encoder.vorbis" },
1370        { MEDIA_MIMETYPE_AUDIO_G711_MLAW,
1371            "audio_decoder.g711mlaw", "audio_encoder.g711mlaw" },
1372        { MEDIA_MIMETYPE_AUDIO_G711_ALAW,
1373            "audio_decoder.g711alaw", "audio_encoder.g711alaw" },
1374        { MEDIA_MIMETYPE_VIDEO_AVC,
1375            "video_decoder.avc", "video_encoder.avc" },
1376        { MEDIA_MIMETYPE_VIDEO_MPEG4,
1377            "video_decoder.mpeg4", "video_encoder.mpeg4" },
1378        { MEDIA_MIMETYPE_VIDEO_H263,
1379            "video_decoder.h263", "video_encoder.h263" },
1380        { MEDIA_MIMETYPE_VIDEO_VPX,
1381            "video_decoder.vpx", "video_encoder.vpx" },
1382        { MEDIA_MIMETYPE_AUDIO_RAW,
1383            "audio_decoder.raw", "audio_encoder.raw" },
1384        { MEDIA_MIMETYPE_AUDIO_FLAC,
1385            "audio_decoder.flac", "audio_encoder.flac" },
1386        { MEDIA_MIMETYPE_AUDIO_MSGSM,
1387            "audio_decoder.gsm", "audio_encoder.gsm" },
1388    };
1389
1390    static const size_t kNumMimeToRole =
1391        sizeof(kMimeToRole) / sizeof(kMimeToRole[0]);
1392
1393    size_t i;
1394    for (i = 0; i < kNumMimeToRole; ++i) {
1395        if (!strcasecmp(mime, kMimeToRole[i].mime)) {
1396            break;
1397        }
1398    }
1399
1400    if (i == kNumMimeToRole) {
1401        return;
1402    }
1403
1404    const char *role =
1405        isEncoder ? kMimeToRole[i].encoderRole
1406                  : kMimeToRole[i].decoderRole;
1407
1408    if (role != NULL) {
1409        OMX_PARAM_COMPONENTROLETYPE roleParams;
1410        InitOMXParams(&roleParams);
1411
1412        strncpy((char *)roleParams.cRole,
1413                role, OMX_MAX_STRINGNAME_SIZE - 1);
1414
1415        roleParams.cRole[OMX_MAX_STRINGNAME_SIZE - 1] = '\0';
1416
1417        status_t err = omx->setParameter(
1418                node, OMX_IndexParamStandardComponentRole,
1419                &roleParams, sizeof(roleParams));
1420
1421        if (err != OK) {
1422            ALOGW("Failed to set standard component role '%s'.", role);
1423        }
1424    }
1425}
1426
1427void OMXCodec::setComponentRole() {
1428    setComponentRole(mOMX, mNode, mIsEncoder, mMIME);
1429}
1430
1431OMXCodec::~OMXCodec() {
1432    mSource.clear();
1433
1434    CHECK(mState == LOADED || mState == ERROR || mState == LOADED_TO_IDLE);
1435
1436    status_t err = mOMX->freeNode(mNode);
1437    CHECK_EQ(err, (status_t)OK);
1438
1439    mNode = NULL;
1440    setState(DEAD);
1441
1442    clearCodecSpecificData();
1443
1444    free(mComponentName);
1445    mComponentName = NULL;
1446
1447    free(mMIME);
1448    mMIME = NULL;
1449}
1450
1451status_t OMXCodec::init() {
1452    // mLock is held.
1453
1454    CHECK_EQ((int)mState, (int)LOADED);
1455
1456    status_t err;
1457    if (!(mQuirks & kRequiresLoadedToIdleAfterAllocation)) {
1458        err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
1459        CHECK_EQ(err, (status_t)OK);
1460        setState(LOADED_TO_IDLE);
1461    }
1462
1463    err = allocateBuffers();
1464    if (err != (status_t)OK) {
1465        return err;
1466    }
1467
1468    if (mQuirks & kRequiresLoadedToIdleAfterAllocation) {
1469        err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
1470        CHECK_EQ(err, (status_t)OK);
1471
1472        setState(LOADED_TO_IDLE);
1473    }
1474
1475    while (mState != EXECUTING && mState != ERROR) {
1476        mAsyncCompletion.wait(mLock);
1477    }
1478
1479    return mState == ERROR ? UNKNOWN_ERROR : OK;
1480}
1481
1482// static
1483bool OMXCodec::isIntermediateState(State state) {
1484    return state == LOADED_TO_IDLE
1485        || state == IDLE_TO_EXECUTING
1486        || state == EXECUTING_TO_IDLE
1487        || state == IDLE_TO_LOADED
1488        || state == RECONFIGURING;
1489}
1490
1491status_t OMXCodec::allocateBuffers() {
1492    status_t err = allocateBuffersOnPort(kPortIndexInput);
1493
1494    if (err != OK) {
1495        return err;
1496    }
1497
1498    return allocateBuffersOnPort(kPortIndexOutput);
1499}
1500
1501status_t OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) {
1502    if (mNativeWindow != NULL && portIndex == kPortIndexOutput) {
1503        return allocateOutputBuffersFromNativeWindow();
1504    }
1505
1506    if ((mFlags & kEnableGrallocUsageProtected) && portIndex == kPortIndexOutput) {
1507        ALOGE("protected output buffers must be stent to an ANativeWindow");
1508        return PERMISSION_DENIED;
1509    }
1510
1511    status_t err = OK;
1512    if ((mFlags & kStoreMetaDataInVideoBuffers)
1513            && portIndex == kPortIndexInput) {
1514        err = mOMX->storeMetaDataInBuffers(mNode, kPortIndexInput, OMX_TRUE);
1515        if (err != OK) {
1516            ALOGE("Storing meta data in video buffers is not supported");
1517            return err;
1518        }
1519    }
1520
1521    OMX_PARAM_PORTDEFINITIONTYPE def;
1522    InitOMXParams(&def);
1523    def.nPortIndex = portIndex;
1524
1525    err = mOMX->getParameter(
1526            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1527
1528    if (err != OK) {
1529        return err;
1530    }
1531
1532    CODEC_LOGV("allocating %lu buffers of size %lu on %s port",
1533            def.nBufferCountActual, def.nBufferSize,
1534            portIndex == kPortIndexInput ? "input" : "output");
1535
1536    size_t totalSize = def.nBufferCountActual * def.nBufferSize;
1537    mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec");
1538
1539    for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
1540        sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize);
1541        CHECK(mem.get() != NULL);
1542
1543        BufferInfo info;
1544        info.mData = NULL;
1545        info.mSize = def.nBufferSize;
1546
1547        IOMX::buffer_id buffer;
1548        if (portIndex == kPortIndexInput
1549                && ((mQuirks & kRequiresAllocateBufferOnInputPorts)
1550                    || (mFlags & kUseSecureInputBuffers))) {
1551            if (mOMXLivesLocally) {
1552                mem.clear();
1553
1554                err = mOMX->allocateBuffer(
1555                        mNode, portIndex, def.nBufferSize, &buffer,
1556                        &info.mData);
1557            } else {
1558                err = mOMX->allocateBufferWithBackup(
1559                        mNode, portIndex, mem, &buffer);
1560            }
1561        } else if (portIndex == kPortIndexOutput
1562                && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) {
1563            if (mOMXLivesLocally) {
1564                mem.clear();
1565
1566                err = mOMX->allocateBuffer(
1567                        mNode, portIndex, def.nBufferSize, &buffer,
1568                        &info.mData);
1569            } else {
1570                err = mOMX->allocateBufferWithBackup(
1571                        mNode, portIndex, mem, &buffer);
1572            }
1573        } else {
1574            err = mOMX->useBuffer(mNode, portIndex, mem, &buffer);
1575        }
1576
1577        if (err != OK) {
1578            ALOGE("allocate_buffer_with_backup failed");
1579            return err;
1580        }
1581
1582        if (mem != NULL) {
1583            info.mData = mem->pointer();
1584        }
1585
1586        info.mBuffer = buffer;
1587        info.mStatus = OWNED_BY_US;
1588        info.mMem = mem;
1589        info.mMediaBuffer = NULL;
1590
1591        if (portIndex == kPortIndexOutput) {
1592            if (!(mOMXLivesLocally
1593                        && (mQuirks & kRequiresAllocateBufferOnOutputPorts)
1594                        && (mQuirks & kDefersOutputBufferAllocation))) {
1595                // If the node does not fill in the buffer ptr at this time,
1596                // we will defer creating the MediaBuffer until receiving
1597                // the first FILL_BUFFER_DONE notification instead.
1598                info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize);
1599                info.mMediaBuffer->setObserver(this);
1600            }
1601        }
1602
1603        mPortBuffers[portIndex].push(info);
1604
1605        CODEC_LOGV("allocated buffer %p on %s port", buffer,
1606             portIndex == kPortIndexInput ? "input" : "output");
1607    }
1608
1609    if (portIndex == kPortIndexOutput) {
1610
1611        sp<MetaData> meta = mSource->getFormat();
1612        int32_t delay = 0;
1613        if (!meta->findInt32(kKeyEncoderDelay, &delay)) {
1614            delay = 0;
1615        }
1616        int32_t padding = 0;
1617        if (!meta->findInt32(kKeyEncoderPadding, &padding)) {
1618            padding = 0;
1619        }
1620        int32_t numchannels = 0;
1621        if (delay + padding) {
1622            if (mOutputFormat->findInt32(kKeyChannelCount, &numchannels)) {
1623                size_t frameSize = numchannels * sizeof(int16_t);
1624                if (mSkipCutBuffer != NULL) {
1625                    size_t prevbuffersize = mSkipCutBuffer->size();
1626                    if (prevbuffersize != 0) {
1627                        ALOGW("Replacing SkipCutBuffer holding %d bytes", prevbuffersize);
1628                    }
1629                }
1630                mSkipCutBuffer = new SkipCutBuffer(delay * frameSize, padding * frameSize);
1631            }
1632        }
1633    }
1634
1635    // dumpPortStatus(portIndex);
1636
1637    if (portIndex == kPortIndexInput && (mFlags & kUseSecureInputBuffers)) {
1638        Vector<MediaBuffer *> buffers;
1639        for (size_t i = 0; i < def.nBufferCountActual; ++i) {
1640            const BufferInfo &info = mPortBuffers[kPortIndexInput].itemAt(i);
1641
1642            MediaBuffer *mbuf = new MediaBuffer(info.mData, info.mSize);
1643            buffers.push(mbuf);
1644        }
1645
1646        status_t err = mSource->setBuffers(buffers);
1647
1648        if (err != OK) {
1649            for (size_t i = 0; i < def.nBufferCountActual; ++i) {
1650                buffers.editItemAt(i)->release();
1651            }
1652            buffers.clear();
1653
1654            CODEC_LOGE(
1655                    "Codec requested to use secure input buffers but "
1656                    "upstream source didn't support that.");
1657
1658            return err;
1659        }
1660    }
1661
1662    return OK;
1663}
1664
1665status_t OMXCodec::applyRotation() {
1666    sp<MetaData> meta = mSource->getFormat();
1667
1668    int32_t rotationDegrees;
1669    if (!meta->findInt32(kKeyRotation, &rotationDegrees)) {
1670        rotationDegrees = 0;
1671    }
1672
1673    uint32_t transform;
1674    switch (rotationDegrees) {
1675        case 0: transform = 0; break;
1676        case 90: transform = HAL_TRANSFORM_ROT_90; break;
1677        case 180: transform = HAL_TRANSFORM_ROT_180; break;
1678        case 270: transform = HAL_TRANSFORM_ROT_270; break;
1679        default: transform = 0; break;
1680    }
1681
1682    status_t err = OK;
1683
1684    if (transform) {
1685        err = native_window_set_buffers_transform(
1686                mNativeWindow.get(), transform);
1687        ALOGE("native_window_set_buffers_transform failed: %s (%d)",
1688                strerror(-err), -err);
1689    }
1690
1691    return err;
1692}
1693
1694status_t OMXCodec::allocateOutputBuffersFromNativeWindow() {
1695    // Get the number of buffers needed.
1696    OMX_PARAM_PORTDEFINITIONTYPE def;
1697    InitOMXParams(&def);
1698    def.nPortIndex = kPortIndexOutput;
1699
1700    status_t err = mOMX->getParameter(
1701            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1702    if (err != OK) {
1703        CODEC_LOGE("getParameter failed: %d", err);
1704        return err;
1705    }
1706
1707    err = native_window_set_buffers_geometry(
1708            mNativeWindow.get(),
1709            def.format.video.nFrameWidth,
1710            def.format.video.nFrameHeight,
1711            def.format.video.eColorFormat);
1712
1713    if (err != 0) {
1714        ALOGE("native_window_set_buffers_geometry failed: %s (%d)",
1715                strerror(-err), -err);
1716        return err;
1717    }
1718
1719    err = applyRotation();
1720    if (err != OK) {
1721        return err;
1722    }
1723
1724    // Set up the native window.
1725    OMX_U32 usage = 0;
1726    err = mOMX->getGraphicBufferUsage(mNode, kPortIndexOutput, &usage);
1727    if (err != 0) {
1728        ALOGW("querying usage flags from OMX IL component failed: %d", err);
1729        // XXX: Currently this error is logged, but not fatal.
1730        usage = 0;
1731    }
1732    if (mFlags & kEnableGrallocUsageProtected) {
1733        usage |= GRALLOC_USAGE_PROTECTED;
1734    }
1735
1736    // Make sure to check whether either Stagefright or the video decoder
1737    // requested protected buffers.
1738    if (usage & GRALLOC_USAGE_PROTECTED) {
1739        // Verify that the ANativeWindow sends images directly to
1740        // SurfaceFlinger.
1741        int queuesToNativeWindow = 0;
1742        err = mNativeWindow->query(
1743                mNativeWindow.get(), NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER,
1744                &queuesToNativeWindow);
1745        if (err != 0) {
1746            ALOGE("error authenticating native window: %d", err);
1747            return err;
1748        }
1749        if (queuesToNativeWindow != 1) {
1750            ALOGE("native window could not be authenticated");
1751            return PERMISSION_DENIED;
1752        }
1753    }
1754
1755    ALOGV("native_window_set_usage usage=0x%lx", usage);
1756    err = native_window_set_usage(
1757            mNativeWindow.get(), usage | GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_EXTERNAL_DISP);
1758    if (err != 0) {
1759        ALOGE("native_window_set_usage failed: %s (%d)", strerror(-err), -err);
1760        return err;
1761    }
1762
1763    int minUndequeuedBufs = 0;
1764    err = mNativeWindow->query(mNativeWindow.get(),
1765            NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufs);
1766    if (err != 0) {
1767        ALOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)",
1768                strerror(-err), -err);
1769        return err;
1770    }
1771
1772    // XXX: Is this the right logic to use?  It's not clear to me what the OMX
1773    // buffer counts refer to - how do they account for the renderer holding on
1774    // to buffers?
1775    if (def.nBufferCountActual < def.nBufferCountMin + minUndequeuedBufs) {
1776        OMX_U32 newBufferCount = def.nBufferCountMin + minUndequeuedBufs;
1777        def.nBufferCountActual = newBufferCount;
1778        err = mOMX->setParameter(
1779                mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1780        if (err != OK) {
1781            CODEC_LOGE("setting nBufferCountActual to %lu failed: %d",
1782                    newBufferCount, err);
1783            return err;
1784        }
1785    }
1786
1787    err = native_window_set_buffer_count(
1788            mNativeWindow.get(), def.nBufferCountActual);
1789    if (err != 0) {
1790        ALOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err),
1791                -err);
1792        return err;
1793    }
1794
1795    CODEC_LOGV("allocating %lu buffers from a native window of size %lu on "
1796            "output port", def.nBufferCountActual, def.nBufferSize);
1797
1798    // Dequeue buffers and send them to OMX
1799    for (OMX_U32 i = 0; i < def.nBufferCountActual; i++) {
1800        ANativeWindowBuffer* buf;
1801        err = native_window_dequeue_buffer_and_wait(mNativeWindow.get(), &buf);
1802        if (err != 0) {
1803            ALOGE("dequeueBuffer failed: %s (%d)", strerror(-err), -err);
1804            break;
1805        }
1806
1807        sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(buf, false));
1808        BufferInfo info;
1809        info.mData = NULL;
1810        info.mSize = def.nBufferSize;
1811        info.mStatus = OWNED_BY_US;
1812        info.mMem = NULL;
1813        info.mMediaBuffer = new MediaBuffer(graphicBuffer);
1814        info.mMediaBuffer->setObserver(this);
1815        mPortBuffers[kPortIndexOutput].push(info);
1816
1817        IOMX::buffer_id bufferId;
1818        err = mOMX->useGraphicBuffer(mNode, kPortIndexOutput, graphicBuffer,
1819                &bufferId);
1820        if (err != 0) {
1821            CODEC_LOGE("registering GraphicBuffer with OMX IL component "
1822                    "failed: %d", err);
1823            break;
1824        }
1825
1826        mPortBuffers[kPortIndexOutput].editItemAt(i).mBuffer = bufferId;
1827
1828        CODEC_LOGV("registered graphic buffer with ID %p (pointer = %p)",
1829                bufferId, graphicBuffer.get());
1830    }
1831
1832    OMX_U32 cancelStart;
1833    OMX_U32 cancelEnd;
1834    if (err != 0) {
1835        // If an error occurred while dequeuing we need to cancel any buffers
1836        // that were dequeued.
1837        cancelStart = 0;
1838        cancelEnd = mPortBuffers[kPortIndexOutput].size();
1839    } else {
1840        // Return the last two buffers to the native window.
1841        cancelStart = def.nBufferCountActual - minUndequeuedBufs;
1842        cancelEnd = def.nBufferCountActual;
1843    }
1844
1845    for (OMX_U32 i = cancelStart; i < cancelEnd; i++) {
1846        BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(i);
1847        cancelBufferToNativeWindow(info);
1848    }
1849
1850    return err;
1851}
1852
1853status_t OMXCodec::cancelBufferToNativeWindow(BufferInfo *info) {
1854    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
1855    CODEC_LOGV("Calling cancelBuffer on buffer %p", info->mBuffer);
1856    int err = mNativeWindow->cancelBuffer(
1857        mNativeWindow.get(), info->mMediaBuffer->graphicBuffer().get(), -1);
1858    if (err != 0) {
1859      CODEC_LOGE("cancelBuffer failed w/ error 0x%08x", err);
1860
1861      setState(ERROR);
1862      return err;
1863    }
1864    info->mStatus = OWNED_BY_NATIVE_WINDOW;
1865    return OK;
1866}
1867
1868OMXCodec::BufferInfo* OMXCodec::dequeueBufferFromNativeWindow() {
1869    // Dequeue the next buffer from the native window.
1870    ANativeWindowBuffer* buf;
1871    int fenceFd = -1;
1872    int err = native_window_dequeue_buffer_and_wait(mNativeWindow.get(), &buf);
1873    if (err != 0) {
1874      CODEC_LOGE("dequeueBuffer failed w/ error 0x%08x", err);
1875
1876      setState(ERROR);
1877      return 0;
1878    }
1879
1880    // Determine which buffer we just dequeued.
1881    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
1882    BufferInfo *bufInfo = 0;
1883    for (size_t i = 0; i < buffers->size(); i++) {
1884      sp<GraphicBuffer> graphicBuffer = buffers->itemAt(i).
1885          mMediaBuffer->graphicBuffer();
1886      if (graphicBuffer->handle == buf->handle) {
1887        bufInfo = &buffers->editItemAt(i);
1888        break;
1889      }
1890    }
1891
1892    if (bufInfo == 0) {
1893        CODEC_LOGE("dequeued unrecognized buffer: %p", buf);
1894
1895        setState(ERROR);
1896        return 0;
1897    }
1898
1899    // The native window no longer owns the buffer.
1900    CHECK_EQ((int)bufInfo->mStatus, (int)OWNED_BY_NATIVE_WINDOW);
1901    bufInfo->mStatus = OWNED_BY_US;
1902
1903    return bufInfo;
1904}
1905
1906status_t OMXCodec::pushBlankBuffersToNativeWindow() {
1907    status_t err = NO_ERROR;
1908    ANativeWindowBuffer* anb = NULL;
1909    int numBufs = 0;
1910    int minUndequeuedBufs = 0;
1911
1912    // We need to reconnect to the ANativeWindow as a CPU client to ensure that
1913    // no frames get dropped by SurfaceFlinger assuming that these are video
1914    // frames.
1915    err = native_window_api_disconnect(mNativeWindow.get(),
1916            NATIVE_WINDOW_API_MEDIA);
1917    if (err != NO_ERROR) {
1918        ALOGE("error pushing blank frames: api_disconnect failed: %s (%d)",
1919                strerror(-err), -err);
1920        return err;
1921    }
1922
1923    err = native_window_api_connect(mNativeWindow.get(),
1924            NATIVE_WINDOW_API_CPU);
1925    if (err != NO_ERROR) {
1926        ALOGE("error pushing blank frames: api_connect failed: %s (%d)",
1927                strerror(-err), -err);
1928        return err;
1929    }
1930
1931    err = native_window_set_buffers_geometry(mNativeWindow.get(), 1, 1,
1932            HAL_PIXEL_FORMAT_RGBX_8888);
1933    if (err != NO_ERROR) {
1934        ALOGE("error pushing blank frames: set_buffers_geometry failed: %s (%d)",
1935                strerror(-err), -err);
1936        goto error;
1937    }
1938
1939    err = native_window_set_usage(mNativeWindow.get(),
1940            GRALLOC_USAGE_SW_WRITE_OFTEN);
1941    if (err != NO_ERROR) {
1942        ALOGE("error pushing blank frames: set_usage failed: %s (%d)",
1943                strerror(-err), -err);
1944        goto error;
1945    }
1946
1947    err = native_window_set_scaling_mode(mNativeWindow.get(),
1948            NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
1949    if (err != OK) {
1950        ALOGE("error pushing blank frames: set_scaling_mode failed: %s (%d)",
1951                strerror(-err), -err);
1952        goto error;
1953    }
1954
1955    err = mNativeWindow->query(mNativeWindow.get(),
1956            NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufs);
1957    if (err != NO_ERROR) {
1958        ALOGE("error pushing blank frames: MIN_UNDEQUEUED_BUFFERS query "
1959                "failed: %s (%d)", strerror(-err), -err);
1960        goto error;
1961    }
1962
1963    numBufs = minUndequeuedBufs + 1;
1964    err = native_window_set_buffer_count(mNativeWindow.get(), numBufs);
1965    if (err != NO_ERROR) {
1966        ALOGE("error pushing blank frames: set_buffer_count failed: %s (%d)",
1967                strerror(-err), -err);
1968        goto error;
1969    }
1970
1971    // We  push numBufs + 1 buffers to ensure that we've drawn into the same
1972    // buffer twice.  This should guarantee that the buffer has been displayed
1973    // on the screen and then been replaced, so an previous video frames are
1974    // guaranteed NOT to be currently displayed.
1975    for (int i = 0; i < numBufs + 1; i++) {
1976        int fenceFd = -1;
1977        err = native_window_dequeue_buffer_and_wait(mNativeWindow.get(), &anb);
1978        if (err != NO_ERROR) {
1979            ALOGE("error pushing blank frames: dequeueBuffer failed: %s (%d)",
1980                    strerror(-err), -err);
1981            goto error;
1982        }
1983
1984        sp<GraphicBuffer> buf(new GraphicBuffer(anb, false));
1985
1986        // Fill the buffer with the a 1x1 checkerboard pattern ;)
1987        uint32_t* img = NULL;
1988        err = buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&img));
1989        if (err != NO_ERROR) {
1990            ALOGE("error pushing blank frames: lock failed: %s (%d)",
1991                    strerror(-err), -err);
1992            goto error;
1993        }
1994
1995        *img = 0;
1996
1997        err = buf->unlock();
1998        if (err != NO_ERROR) {
1999            ALOGE("error pushing blank frames: unlock failed: %s (%d)",
2000                    strerror(-err), -err);
2001            goto error;
2002        }
2003
2004        err = mNativeWindow->queueBuffer(mNativeWindow.get(),
2005                buf->getNativeBuffer(), -1);
2006        if (err != NO_ERROR) {
2007            ALOGE("error pushing blank frames: queueBuffer failed: %s (%d)",
2008                    strerror(-err), -err);
2009            goto error;
2010        }
2011
2012        anb = NULL;
2013    }
2014
2015error:
2016
2017    if (err != NO_ERROR) {
2018        // Clean up after an error.
2019        if (anb != NULL) {
2020            mNativeWindow->cancelBuffer(mNativeWindow.get(), anb, -1);
2021        }
2022
2023        native_window_api_disconnect(mNativeWindow.get(),
2024                NATIVE_WINDOW_API_CPU);
2025        native_window_api_connect(mNativeWindow.get(),
2026                NATIVE_WINDOW_API_MEDIA);
2027
2028        return err;
2029    } else {
2030        // Clean up after success.
2031        err = native_window_api_disconnect(mNativeWindow.get(),
2032                NATIVE_WINDOW_API_CPU);
2033        if (err != NO_ERROR) {
2034            ALOGE("error pushing blank frames: api_disconnect failed: %s (%d)",
2035                    strerror(-err), -err);
2036            return err;
2037        }
2038
2039        err = native_window_api_connect(mNativeWindow.get(),
2040                NATIVE_WINDOW_API_MEDIA);
2041        if (err != NO_ERROR) {
2042            ALOGE("error pushing blank frames: api_connect failed: %s (%d)",
2043                    strerror(-err), -err);
2044            return err;
2045        }
2046
2047        return NO_ERROR;
2048    }
2049}
2050
2051int64_t OMXCodec::getDecodingTimeUs() {
2052    CHECK(mIsEncoder && mIsVideo);
2053
2054    if (mDecodingTimeList.empty()) {
2055        CHECK(mSignalledEOS || mNoMoreOutputData);
2056        // No corresponding input frame available.
2057        // This could happen when EOS is reached.
2058        return 0;
2059    }
2060
2061    List<int64_t>::iterator it = mDecodingTimeList.begin();
2062    int64_t timeUs = *it;
2063    mDecodingTimeList.erase(it);
2064    return timeUs;
2065}
2066
2067void OMXCodec::on_message(const omx_message &msg) {
2068    if (mState == ERROR) {
2069        /*
2070         * only drop EVENT messages, EBD and FBD are still
2071         * processed for bookkeeping purposes
2072         */
2073        if (msg.type == omx_message::EVENT) {
2074            ALOGW("Dropping OMX EVENT message - we're in ERROR state.");
2075            return;
2076        }
2077    }
2078
2079    switch (msg.type) {
2080        case omx_message::EVENT:
2081        {
2082            onEvent(
2083                 msg.u.event_data.event, msg.u.event_data.data1,
2084                 msg.u.event_data.data2);
2085
2086            break;
2087        }
2088
2089        case omx_message::EMPTY_BUFFER_DONE:
2090        {
2091            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
2092
2093            CODEC_LOGV("EMPTY_BUFFER_DONE(buffer: %p)", buffer);
2094
2095            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2096            size_t i = 0;
2097            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
2098                ++i;
2099            }
2100
2101            CHECK(i < buffers->size());
2102            if ((*buffers)[i].mStatus != OWNED_BY_COMPONENT) {
2103                ALOGW("We already own input buffer %p, yet received "
2104                     "an EMPTY_BUFFER_DONE.", buffer);
2105            }
2106
2107            BufferInfo* info = &buffers->editItemAt(i);
2108            info->mStatus = OWNED_BY_US;
2109
2110            // Buffer could not be released until empty buffer done is called.
2111            if (info->mMediaBuffer != NULL) {
2112                info->mMediaBuffer->release();
2113                info->mMediaBuffer = NULL;
2114            }
2115
2116            if (mPortStatus[kPortIndexInput] == DISABLING) {
2117                CODEC_LOGV("Port is disabled, freeing buffer %p", buffer);
2118
2119                status_t err = freeBuffer(kPortIndexInput, i);
2120                CHECK_EQ(err, (status_t)OK);
2121            } else if (mState != ERROR
2122                    && mPortStatus[kPortIndexInput] != SHUTTING_DOWN) {
2123                CHECK_EQ((int)mPortStatus[kPortIndexInput], (int)ENABLED);
2124
2125                if (mFlags & kUseSecureInputBuffers) {
2126                    drainAnyInputBuffer();
2127                } else {
2128                    drainInputBuffer(&buffers->editItemAt(i));
2129                }
2130            }
2131            break;
2132        }
2133
2134        case omx_message::FILL_BUFFER_DONE:
2135        {
2136            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
2137            OMX_U32 flags = msg.u.extended_buffer_data.flags;
2138
2139            CODEC_LOGV("FILL_BUFFER_DONE(buffer: %p, size: %ld, flags: 0x%08lx, timestamp: %lld us (%.2f secs))",
2140                 buffer,
2141                 msg.u.extended_buffer_data.range_length,
2142                 flags,
2143                 msg.u.extended_buffer_data.timestamp,
2144                 msg.u.extended_buffer_data.timestamp / 1E6);
2145
2146            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2147            size_t i = 0;
2148            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
2149                ++i;
2150            }
2151
2152            CHECK(i < buffers->size());
2153            BufferInfo *info = &buffers->editItemAt(i);
2154
2155            if (info->mStatus != OWNED_BY_COMPONENT) {
2156                ALOGW("We already own output buffer %p, yet received "
2157                     "a FILL_BUFFER_DONE.", buffer);
2158            }
2159
2160            info->mStatus = OWNED_BY_US;
2161
2162            if (mPortStatus[kPortIndexOutput] == DISABLING) {
2163                CODEC_LOGV("Port is disabled, freeing buffer %p", buffer);
2164
2165                status_t err = freeBuffer(kPortIndexOutput, i);
2166                CHECK_EQ(err, (status_t)OK);
2167
2168#if 0
2169            } else if (mPortStatus[kPortIndexOutput] == ENABLED
2170                       && (flags & OMX_BUFFERFLAG_EOS)) {
2171                CODEC_LOGV("No more output data.");
2172                mNoMoreOutputData = true;
2173                mBufferFilled.signal();
2174#endif
2175            } else if (mPortStatus[kPortIndexOutput] != SHUTTING_DOWN) {
2176                CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED);
2177
2178                if (info->mMediaBuffer == NULL) {
2179                    CHECK(mOMXLivesLocally);
2180                    CHECK(mQuirks & kRequiresAllocateBufferOnOutputPorts);
2181                    CHECK(mQuirks & kDefersOutputBufferAllocation);
2182
2183                    // The qcom video decoders on Nexus don't actually allocate
2184                    // output buffer memory on a call to OMX_AllocateBuffer
2185                    // the "pBuffer" member of the OMX_BUFFERHEADERTYPE
2186                    // structure is only filled in later.
2187
2188                    info->mMediaBuffer = new MediaBuffer(
2189                            msg.u.extended_buffer_data.data_ptr,
2190                            info->mSize);
2191                    info->mMediaBuffer->setObserver(this);
2192                }
2193
2194                MediaBuffer *buffer = info->mMediaBuffer;
2195                bool isGraphicBuffer = buffer->graphicBuffer() != NULL;
2196
2197                if (!isGraphicBuffer
2198                    && msg.u.extended_buffer_data.range_offset
2199                        + msg.u.extended_buffer_data.range_length
2200                            > buffer->size()) {
2201                    CODEC_LOGE(
2202                            "Codec lied about its buffer size requirements, "
2203                            "sending a buffer larger than the originally "
2204                            "advertised size in FILL_BUFFER_DONE!");
2205                }
2206                buffer->set_range(
2207                        msg.u.extended_buffer_data.range_offset,
2208                        msg.u.extended_buffer_data.range_length);
2209
2210                buffer->meta_data()->clear();
2211
2212                buffer->meta_data()->setInt64(
2213                        kKeyTime, msg.u.extended_buffer_data.timestamp);
2214
2215                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_SYNCFRAME) {
2216                    buffer->meta_data()->setInt32(kKeyIsSyncFrame, true);
2217                }
2218                bool isCodecSpecific = false;
2219                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_CODECCONFIG) {
2220                    buffer->meta_data()->setInt32(kKeyIsCodecConfig, true);
2221                    isCodecSpecific = true;
2222                }
2223
2224                if (isGraphicBuffer || mQuirks & kOutputBuffersAreUnreadable) {
2225                    buffer->meta_data()->setInt32(kKeyIsUnreadable, true);
2226                }
2227
2228                buffer->meta_data()->setPointer(
2229                        kKeyPlatformPrivate,
2230                        msg.u.extended_buffer_data.platform_private);
2231
2232                buffer->meta_data()->setPointer(
2233                        kKeyBufferID,
2234                        msg.u.extended_buffer_data.buffer);
2235
2236                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_EOS) {
2237                    CODEC_LOGV("No more output data.");
2238                    mNoMoreOutputData = true;
2239                }
2240
2241                if (mIsEncoder && mIsVideo) {
2242                    int64_t decodingTimeUs = isCodecSpecific? 0: getDecodingTimeUs();
2243                    buffer->meta_data()->setInt64(kKeyDecodingTime, decodingTimeUs);
2244                }
2245
2246                if (mTargetTimeUs >= 0) {
2247                    CHECK(msg.u.extended_buffer_data.timestamp <= mTargetTimeUs);
2248
2249                    if (msg.u.extended_buffer_data.timestamp < mTargetTimeUs) {
2250                        CODEC_LOGV(
2251                                "skipping output buffer at timestamp %lld us",
2252                                msg.u.extended_buffer_data.timestamp);
2253
2254                        fillOutputBuffer(info);
2255                        break;
2256                    }
2257
2258                    CODEC_LOGV(
2259                            "returning output buffer at target timestamp "
2260                            "%lld us",
2261                            msg.u.extended_buffer_data.timestamp);
2262
2263                    mTargetTimeUs = -1;
2264                }
2265
2266                mFilledBuffers.push_back(i);
2267                mBufferFilled.signal();
2268                if (mIsEncoder) {
2269                    sched_yield();
2270                }
2271            }
2272
2273            break;
2274        }
2275
2276        default:
2277        {
2278            CHECK(!"should not be here.");
2279            break;
2280        }
2281    }
2282}
2283
2284// Has the format changed in any way that the client would have to be aware of?
2285static bool formatHasNotablyChanged(
2286        const sp<MetaData> &from, const sp<MetaData> &to) {
2287    if (from.get() == NULL && to.get() == NULL) {
2288        return false;
2289    }
2290
2291    if ((from.get() == NULL && to.get() != NULL)
2292        || (from.get() != NULL && to.get() == NULL)) {
2293        return true;
2294    }
2295
2296    const char *mime_from, *mime_to;
2297    CHECK(from->findCString(kKeyMIMEType, &mime_from));
2298    CHECK(to->findCString(kKeyMIMEType, &mime_to));
2299
2300    if (strcasecmp(mime_from, mime_to)) {
2301        return true;
2302    }
2303
2304    if (!strcasecmp(mime_from, MEDIA_MIMETYPE_VIDEO_RAW)) {
2305        int32_t colorFormat_from, colorFormat_to;
2306        CHECK(from->findInt32(kKeyColorFormat, &colorFormat_from));
2307        CHECK(to->findInt32(kKeyColorFormat, &colorFormat_to));
2308
2309        if (colorFormat_from != colorFormat_to) {
2310            return true;
2311        }
2312
2313        int32_t width_from, width_to;
2314        CHECK(from->findInt32(kKeyWidth, &width_from));
2315        CHECK(to->findInt32(kKeyWidth, &width_to));
2316
2317        if (width_from != width_to) {
2318            return true;
2319        }
2320
2321        int32_t height_from, height_to;
2322        CHECK(from->findInt32(kKeyHeight, &height_from));
2323        CHECK(to->findInt32(kKeyHeight, &height_to));
2324
2325        if (height_from != height_to) {
2326            return true;
2327        }
2328
2329        int32_t left_from, top_from, right_from, bottom_from;
2330        CHECK(from->findRect(
2331                    kKeyCropRect,
2332                    &left_from, &top_from, &right_from, &bottom_from));
2333
2334        int32_t left_to, top_to, right_to, bottom_to;
2335        CHECK(to->findRect(
2336                    kKeyCropRect,
2337                    &left_to, &top_to, &right_to, &bottom_to));
2338
2339        if (left_to != left_from || top_to != top_from
2340                || right_to != right_from || bottom_to != bottom_from) {
2341            return true;
2342        }
2343    } else if (!strcasecmp(mime_from, MEDIA_MIMETYPE_AUDIO_RAW)) {
2344        int32_t numChannels_from, numChannels_to;
2345        CHECK(from->findInt32(kKeyChannelCount, &numChannels_from));
2346        CHECK(to->findInt32(kKeyChannelCount, &numChannels_to));
2347
2348        if (numChannels_from != numChannels_to) {
2349            return true;
2350        }
2351
2352        int32_t sampleRate_from, sampleRate_to;
2353        CHECK(from->findInt32(kKeySampleRate, &sampleRate_from));
2354        CHECK(to->findInt32(kKeySampleRate, &sampleRate_to));
2355
2356        if (sampleRate_from != sampleRate_to) {
2357            return true;
2358        }
2359    }
2360
2361    return false;
2362}
2363
2364void OMXCodec::onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) {
2365    switch (event) {
2366        case OMX_EventCmdComplete:
2367        {
2368            onCmdComplete((OMX_COMMANDTYPE)data1, data2);
2369            break;
2370        }
2371
2372        case OMX_EventError:
2373        {
2374            CODEC_LOGE("ERROR(0x%08lx, %ld)", data1, data2);
2375
2376            setState(ERROR);
2377            break;
2378        }
2379
2380        case OMX_EventPortSettingsChanged:
2381        {
2382            CODEC_LOGV("OMX_EventPortSettingsChanged(port=%ld, data2=0x%08lx)",
2383                       data1, data2);
2384
2385            if (data2 == 0 || data2 == OMX_IndexParamPortDefinition) {
2386                // There is no need to check whether mFilledBuffers is empty or not
2387                // when the OMX_EventPortSettingsChanged is not meant for reallocating
2388                // the output buffers.
2389                if (data1 == kPortIndexOutput) {
2390                    CHECK(mFilledBuffers.empty());
2391                }
2392                onPortSettingsChanged(data1);
2393            } else if (data1 == kPortIndexOutput &&
2394                        (data2 == OMX_IndexConfigCommonOutputCrop ||
2395                         data2 == OMX_IndexConfigCommonScale)) {
2396
2397                sp<MetaData> oldOutputFormat = mOutputFormat;
2398                initOutputFormat(mSource->getFormat());
2399
2400                if (data2 == OMX_IndexConfigCommonOutputCrop &&
2401                    formatHasNotablyChanged(oldOutputFormat, mOutputFormat)) {
2402                    mOutputPortSettingsHaveChanged = true;
2403
2404                } else if (data2 == OMX_IndexConfigCommonScale) {
2405                    OMX_CONFIG_SCALEFACTORTYPE scale;
2406                    InitOMXParams(&scale);
2407                    scale.nPortIndex = kPortIndexOutput;
2408
2409                    // Change display dimension only when necessary.
2410                    if (OK == mOMX->getConfig(
2411                                        mNode,
2412                                        OMX_IndexConfigCommonScale,
2413                                        &scale, sizeof(scale))) {
2414                        int32_t left, top, right, bottom;
2415                        CHECK(mOutputFormat->findRect(kKeyCropRect,
2416                                                      &left, &top,
2417                                                      &right, &bottom));
2418
2419                        // The scale is in 16.16 format.
2420                        // scale 1.0 = 0x010000. When there is no
2421                        // need to change the display, skip it.
2422                        ALOGV("Get OMX_IndexConfigScale: 0x%lx/0x%lx",
2423                                scale.xWidth, scale.xHeight);
2424
2425                        if (scale.xWidth != 0x010000) {
2426                            mOutputFormat->setInt32(kKeyDisplayWidth,
2427                                    ((right - left +  1) * scale.xWidth)  >> 16);
2428                            mOutputPortSettingsHaveChanged = true;
2429                        }
2430
2431                        if (scale.xHeight != 0x010000) {
2432                            mOutputFormat->setInt32(kKeyDisplayHeight,
2433                                    ((bottom  - top + 1) * scale.xHeight) >> 16);
2434                            mOutputPortSettingsHaveChanged = true;
2435                        }
2436                    }
2437                }
2438            }
2439            break;
2440        }
2441
2442#if 0
2443        case OMX_EventBufferFlag:
2444        {
2445            CODEC_LOGV("EVENT_BUFFER_FLAG(%ld)", data1);
2446
2447            if (data1 == kPortIndexOutput) {
2448                mNoMoreOutputData = true;
2449            }
2450            break;
2451        }
2452#endif
2453
2454        default:
2455        {
2456            CODEC_LOGV("EVENT(%d, %ld, %ld)", event, data1, data2);
2457            break;
2458        }
2459    }
2460}
2461
2462void OMXCodec::onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data) {
2463    switch (cmd) {
2464        case OMX_CommandStateSet:
2465        {
2466            onStateChange((OMX_STATETYPE)data);
2467            break;
2468        }
2469
2470        case OMX_CommandPortDisable:
2471        {
2472            OMX_U32 portIndex = data;
2473            CODEC_LOGV("PORT_DISABLED(%ld)", portIndex);
2474
2475            CHECK(mState == EXECUTING || mState == RECONFIGURING);
2476            CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLING);
2477            CHECK_EQ(mPortBuffers[portIndex].size(), 0u);
2478
2479            mPortStatus[portIndex] = DISABLED;
2480
2481            if (mState == RECONFIGURING) {
2482                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2483
2484                sp<MetaData> oldOutputFormat = mOutputFormat;
2485                initOutputFormat(mSource->getFormat());
2486
2487                // Don't notify clients if the output port settings change
2488                // wasn't of importance to them, i.e. it may be that just the
2489                // number of buffers has changed and nothing else.
2490                bool formatChanged = formatHasNotablyChanged(oldOutputFormat, mOutputFormat);
2491                if (!mOutputPortSettingsHaveChanged) {
2492                    mOutputPortSettingsHaveChanged = formatChanged;
2493                }
2494
2495                status_t err = enablePortAsync(portIndex);
2496                if (err != OK) {
2497                    CODEC_LOGE("enablePortAsync(%ld) failed (err = %d)", portIndex, err);
2498                    setState(ERROR);
2499                } else {
2500                    err = allocateBuffersOnPort(portIndex);
2501                    if (err != OK) {
2502                        CODEC_LOGE("allocateBuffersOnPort (%s) failed "
2503                                   "(err = %d)",
2504                                   portIndex == kPortIndexInput
2505                                        ? "input" : "output",
2506                                   err);
2507
2508                        setState(ERROR);
2509                    }
2510                }
2511            }
2512            break;
2513        }
2514
2515        case OMX_CommandPortEnable:
2516        {
2517            OMX_U32 portIndex = data;
2518            CODEC_LOGV("PORT_ENABLED(%ld)", portIndex);
2519
2520            CHECK(mState == EXECUTING || mState == RECONFIGURING);
2521            CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLING);
2522
2523            mPortStatus[portIndex] = ENABLED;
2524
2525            if (mState == RECONFIGURING) {
2526                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2527
2528                setState(EXECUTING);
2529
2530                fillOutputBuffers();
2531            }
2532            break;
2533        }
2534
2535        case OMX_CommandFlush:
2536        {
2537            OMX_U32 portIndex = data;
2538
2539            CODEC_LOGV("FLUSH_DONE(%ld)", portIndex);
2540
2541            CHECK_EQ((int)mPortStatus[portIndex], (int)SHUTTING_DOWN);
2542            mPortStatus[portIndex] = ENABLED;
2543
2544            CHECK_EQ(countBuffersWeOwn(mPortBuffers[portIndex]),
2545                     mPortBuffers[portIndex].size());
2546
2547            if (mSkipCutBuffer != NULL && mPortStatus[kPortIndexOutput] == ENABLED) {
2548                mSkipCutBuffer->clear();
2549            }
2550
2551            if (mState == RECONFIGURING) {
2552                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2553
2554                disablePortAsync(portIndex);
2555            } else if (mState == EXECUTING_TO_IDLE) {
2556                if (mPortStatus[kPortIndexInput] == ENABLED
2557                    && mPortStatus[kPortIndexOutput] == ENABLED) {
2558                    CODEC_LOGV("Finished flushing both ports, now completing "
2559                         "transition from EXECUTING to IDLE.");
2560
2561                    mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
2562                    mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
2563
2564                    status_t err =
2565                        mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
2566                    CHECK_EQ(err, (status_t)OK);
2567                }
2568            } else {
2569                // We're flushing both ports in preparation for seeking.
2570
2571                if (mPortStatus[kPortIndexInput] == ENABLED
2572                    && mPortStatus[kPortIndexOutput] == ENABLED) {
2573                    CODEC_LOGV("Finished flushing both ports, now continuing from"
2574                         " seek-time.");
2575
2576                    // We implicitly resume pulling on our upstream source.
2577                    mPaused = false;
2578
2579                    drainInputBuffers();
2580                    fillOutputBuffers();
2581                }
2582
2583                if (mOutputPortSettingsChangedPending) {
2584                    CODEC_LOGV(
2585                            "Honoring deferred output port settings change.");
2586
2587                    mOutputPortSettingsChangedPending = false;
2588                    onPortSettingsChanged(kPortIndexOutput);
2589                }
2590            }
2591
2592            break;
2593        }
2594
2595        default:
2596        {
2597            CODEC_LOGV("CMD_COMPLETE(%d, %ld)", cmd, data);
2598            break;
2599        }
2600    }
2601}
2602
2603void OMXCodec::onStateChange(OMX_STATETYPE newState) {
2604    CODEC_LOGV("onStateChange %d", newState);
2605
2606    switch (newState) {
2607        case OMX_StateIdle:
2608        {
2609            CODEC_LOGV("Now Idle.");
2610            if (mState == LOADED_TO_IDLE) {
2611                status_t err = mOMX->sendCommand(
2612                        mNode, OMX_CommandStateSet, OMX_StateExecuting);
2613
2614                CHECK_EQ(err, (status_t)OK);
2615
2616                setState(IDLE_TO_EXECUTING);
2617            } else {
2618                CHECK_EQ((int)mState, (int)EXECUTING_TO_IDLE);
2619
2620                if (countBuffersWeOwn(mPortBuffers[kPortIndexInput]) !=
2621                    mPortBuffers[kPortIndexInput].size()) {
2622                    ALOGE("Codec did not return all input buffers "
2623                          "(received %d / %d)",
2624                            countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
2625                            mPortBuffers[kPortIndexInput].size());
2626                    TRESPASS();
2627                }
2628
2629                if (countBuffersWeOwn(mPortBuffers[kPortIndexOutput]) !=
2630                    mPortBuffers[kPortIndexOutput].size()) {
2631                    ALOGE("Codec did not return all output buffers "
2632                          "(received %d / %d)",
2633                            countBuffersWeOwn(mPortBuffers[kPortIndexOutput]),
2634                            mPortBuffers[kPortIndexOutput].size());
2635                    TRESPASS();
2636                }
2637
2638                status_t err = mOMX->sendCommand(
2639                        mNode, OMX_CommandStateSet, OMX_StateLoaded);
2640
2641                CHECK_EQ(err, (status_t)OK);
2642
2643                err = freeBuffersOnPort(kPortIndexInput);
2644                CHECK_EQ(err, (status_t)OK);
2645
2646                err = freeBuffersOnPort(kPortIndexOutput);
2647                CHECK_EQ(err, (status_t)OK);
2648
2649                mPortStatus[kPortIndexInput] = ENABLED;
2650                mPortStatus[kPortIndexOutput] = ENABLED;
2651
2652                if ((mFlags & kEnableGrallocUsageProtected) &&
2653                        mNativeWindow != NULL) {
2654                    // We push enough 1x1 blank buffers to ensure that one of
2655                    // them has made it to the display.  This allows the OMX
2656                    // component teardown to zero out any protected buffers
2657                    // without the risk of scanning out one of those buffers.
2658                    pushBlankBuffersToNativeWindow();
2659                }
2660
2661                setState(IDLE_TO_LOADED);
2662            }
2663            break;
2664        }
2665
2666        case OMX_StateExecuting:
2667        {
2668            CHECK_EQ((int)mState, (int)IDLE_TO_EXECUTING);
2669
2670            CODEC_LOGV("Now Executing.");
2671
2672            mOutputPortSettingsChangedPending = false;
2673
2674            setState(EXECUTING);
2675
2676            // Buffers will be submitted to the component in the first
2677            // call to OMXCodec::read as mInitialBufferSubmit is true at
2678            // this point. This ensures that this on_message call returns,
2679            // releases the lock and ::init can notice the state change and
2680            // itself return.
2681            break;
2682        }
2683
2684        case OMX_StateLoaded:
2685        {
2686            CHECK_EQ((int)mState, (int)IDLE_TO_LOADED);
2687
2688            CODEC_LOGV("Now Loaded.");
2689
2690            setState(LOADED);
2691            break;
2692        }
2693
2694        case OMX_StateInvalid:
2695        {
2696            setState(ERROR);
2697            break;
2698        }
2699
2700        default:
2701        {
2702            CHECK(!"should not be here.");
2703            break;
2704        }
2705    }
2706}
2707
2708// static
2709size_t OMXCodec::countBuffersWeOwn(const Vector<BufferInfo> &buffers) {
2710    size_t n = 0;
2711    for (size_t i = 0; i < buffers.size(); ++i) {
2712        if (buffers[i].mStatus != OWNED_BY_COMPONENT) {
2713            ++n;
2714        }
2715    }
2716
2717    return n;
2718}
2719
2720status_t OMXCodec::freeBuffersOnPort(
2721        OMX_U32 portIndex, bool onlyThoseWeOwn) {
2722    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
2723
2724    status_t stickyErr = OK;
2725
2726    for (size_t i = buffers->size(); i-- > 0;) {
2727        BufferInfo *info = &buffers->editItemAt(i);
2728
2729        if (onlyThoseWeOwn && info->mStatus == OWNED_BY_COMPONENT) {
2730            continue;
2731        }
2732
2733        CHECK(info->mStatus == OWNED_BY_US
2734                || info->mStatus == OWNED_BY_NATIVE_WINDOW);
2735
2736        CODEC_LOGV("freeing buffer %p on port %ld", info->mBuffer, portIndex);
2737
2738        status_t err = freeBuffer(portIndex, i);
2739
2740        if (err != OK) {
2741            stickyErr = err;
2742        }
2743
2744    }
2745
2746    CHECK(onlyThoseWeOwn || buffers->isEmpty());
2747
2748    return stickyErr;
2749}
2750
2751status_t OMXCodec::freeBuffer(OMX_U32 portIndex, size_t bufIndex) {
2752    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
2753
2754    BufferInfo *info = &buffers->editItemAt(bufIndex);
2755
2756    status_t err = mOMX->freeBuffer(mNode, portIndex, info->mBuffer);
2757
2758    if (err == OK && info->mMediaBuffer != NULL) {
2759        CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2760        info->mMediaBuffer->setObserver(NULL);
2761
2762        // Make sure nobody but us owns this buffer at this point.
2763        CHECK_EQ(info->mMediaBuffer->refcount(), 0);
2764
2765        // Cancel the buffer if it belongs to an ANativeWindow.
2766        sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer();
2767        if (info->mStatus == OWNED_BY_US && graphicBuffer != 0) {
2768            err = cancelBufferToNativeWindow(info);
2769        }
2770
2771        info->mMediaBuffer->release();
2772        info->mMediaBuffer = NULL;
2773    }
2774
2775    if (err == OK) {
2776        buffers->removeAt(bufIndex);
2777    }
2778
2779    return err;
2780}
2781
2782void OMXCodec::onPortSettingsChanged(OMX_U32 portIndex) {
2783    CODEC_LOGV("PORT_SETTINGS_CHANGED(%ld)", portIndex);
2784
2785    CHECK_EQ((int)mState, (int)EXECUTING);
2786    CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2787    CHECK(!mOutputPortSettingsChangedPending);
2788
2789    if (mPortStatus[kPortIndexOutput] != ENABLED) {
2790        CODEC_LOGV("Deferring output port settings change.");
2791        mOutputPortSettingsChangedPending = true;
2792        return;
2793    }
2794
2795    setState(RECONFIGURING);
2796
2797    if (mQuirks & kNeedsFlushBeforeDisable) {
2798        if (!flushPortAsync(portIndex)) {
2799            onCmdComplete(OMX_CommandFlush, portIndex);
2800        }
2801    } else {
2802        disablePortAsync(portIndex);
2803    }
2804}
2805
2806bool OMXCodec::flushPortAsync(OMX_U32 portIndex) {
2807    CHECK(mState == EXECUTING || mState == RECONFIGURING
2808            || mState == EXECUTING_TO_IDLE);
2809
2810    CODEC_LOGV("flushPortAsync(%ld): we own %d out of %d buffers already.",
2811         portIndex, countBuffersWeOwn(mPortBuffers[portIndex]),
2812         mPortBuffers[portIndex].size());
2813
2814    CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED);
2815    mPortStatus[portIndex] = SHUTTING_DOWN;
2816
2817    if ((mQuirks & kRequiresFlushCompleteEmulation)
2818        && countBuffersWeOwn(mPortBuffers[portIndex])
2819                == mPortBuffers[portIndex].size()) {
2820        // No flush is necessary and this component fails to send a
2821        // flush-complete event in this case.
2822
2823        return false;
2824    }
2825
2826    status_t err =
2827        mOMX->sendCommand(mNode, OMX_CommandFlush, portIndex);
2828    CHECK_EQ(err, (status_t)OK);
2829
2830    return true;
2831}
2832
2833void OMXCodec::disablePortAsync(OMX_U32 portIndex) {
2834    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2835
2836    CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED);
2837    mPortStatus[portIndex] = DISABLING;
2838
2839    CODEC_LOGV("sending OMX_CommandPortDisable(%ld)", portIndex);
2840    status_t err =
2841        mOMX->sendCommand(mNode, OMX_CommandPortDisable, portIndex);
2842    CHECK_EQ(err, (status_t)OK);
2843
2844    freeBuffersOnPort(portIndex, true);
2845}
2846
2847status_t OMXCodec::enablePortAsync(OMX_U32 portIndex) {
2848    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2849
2850    CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLED);
2851    mPortStatus[portIndex] = ENABLING;
2852
2853    CODEC_LOGV("sending OMX_CommandPortEnable(%ld)", portIndex);
2854    return mOMX->sendCommand(mNode, OMX_CommandPortEnable, portIndex);
2855}
2856
2857void OMXCodec::fillOutputBuffers() {
2858    CHECK_EQ((int)mState, (int)EXECUTING);
2859
2860    // This is a workaround for some decoders not properly reporting
2861    // end-of-output-stream. If we own all input buffers and also own
2862    // all output buffers and we already signalled end-of-input-stream,
2863    // the end-of-output-stream is implied.
2864    if (mSignalledEOS
2865            && countBuffersWeOwn(mPortBuffers[kPortIndexInput])
2866                == mPortBuffers[kPortIndexInput].size()
2867            && countBuffersWeOwn(mPortBuffers[kPortIndexOutput])
2868                == mPortBuffers[kPortIndexOutput].size()) {
2869        mNoMoreOutputData = true;
2870        mBufferFilled.signal();
2871
2872        return;
2873    }
2874
2875    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2876    for (size_t i = 0; i < buffers->size(); ++i) {
2877        BufferInfo *info = &buffers->editItemAt(i);
2878        if (info->mStatus == OWNED_BY_US) {
2879            fillOutputBuffer(&buffers->editItemAt(i));
2880        }
2881    }
2882}
2883
2884void OMXCodec::drainInputBuffers() {
2885    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2886
2887    if (mFlags & kUseSecureInputBuffers) {
2888        Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2889        for (size_t i = 0; i < buffers->size(); ++i) {
2890            if (!drainAnyInputBuffer()
2891                    || (mFlags & kOnlySubmitOneInputBufferAtOneTime)) {
2892                break;
2893            }
2894        }
2895    } else {
2896        Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2897        for (size_t i = 0; i < buffers->size(); ++i) {
2898            BufferInfo *info = &buffers->editItemAt(i);
2899
2900            if (info->mStatus != OWNED_BY_US) {
2901                continue;
2902            }
2903
2904            if (!drainInputBuffer(info)) {
2905                break;
2906            }
2907
2908            if (mFlags & kOnlySubmitOneInputBufferAtOneTime) {
2909                break;
2910            }
2911        }
2912    }
2913}
2914
2915bool OMXCodec::drainAnyInputBuffer() {
2916    return drainInputBuffer((BufferInfo *)NULL);
2917}
2918
2919OMXCodec::BufferInfo *OMXCodec::findInputBufferByDataPointer(void *ptr) {
2920    Vector<BufferInfo> *infos = &mPortBuffers[kPortIndexInput];
2921    for (size_t i = 0; i < infos->size(); ++i) {
2922        BufferInfo *info = &infos->editItemAt(i);
2923
2924        if (info->mData == ptr) {
2925            CODEC_LOGV(
2926                    "input buffer data ptr = %p, buffer_id = %p",
2927                    ptr,
2928                    info->mBuffer);
2929
2930            return info;
2931        }
2932    }
2933
2934    TRESPASS();
2935}
2936
2937OMXCodec::BufferInfo *OMXCodec::findEmptyInputBuffer() {
2938    Vector<BufferInfo> *infos = &mPortBuffers[kPortIndexInput];
2939    for (size_t i = 0; i < infos->size(); ++i) {
2940        BufferInfo *info = &infos->editItemAt(i);
2941
2942        if (info->mStatus == OWNED_BY_US) {
2943            return info;
2944        }
2945    }
2946
2947    TRESPASS();
2948}
2949
2950bool OMXCodec::drainInputBuffer(BufferInfo *info) {
2951    if (info != NULL) {
2952        CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
2953    }
2954
2955    if (mSignalledEOS) {
2956        return false;
2957    }
2958
2959    if (mCodecSpecificDataIndex < mCodecSpecificData.size()) {
2960        CHECK(!(mFlags & kUseSecureInputBuffers));
2961
2962        const CodecSpecificData *specific =
2963            mCodecSpecificData[mCodecSpecificDataIndex];
2964
2965        size_t size = specific->mSize;
2966
2967        if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mMIME)
2968                && !(mQuirks & kWantsNALFragments)) {
2969            static const uint8_t kNALStartCode[4] =
2970                    { 0x00, 0x00, 0x00, 0x01 };
2971
2972            CHECK(info->mSize >= specific->mSize + 4);
2973
2974            size += 4;
2975
2976            memcpy(info->mData, kNALStartCode, 4);
2977            memcpy((uint8_t *)info->mData + 4,
2978                   specific->mData, specific->mSize);
2979        } else {
2980            CHECK(info->mSize >= specific->mSize);
2981            memcpy(info->mData, specific->mData, specific->mSize);
2982        }
2983
2984        mNoMoreOutputData = false;
2985
2986        CODEC_LOGV("calling emptyBuffer with codec specific data");
2987
2988        status_t err = mOMX->emptyBuffer(
2989                mNode, info->mBuffer, 0, size,
2990                OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG,
2991                0);
2992        CHECK_EQ(err, (status_t)OK);
2993
2994        info->mStatus = OWNED_BY_COMPONENT;
2995
2996        ++mCodecSpecificDataIndex;
2997        return true;
2998    }
2999
3000    if (mPaused) {
3001        return false;
3002    }
3003
3004    status_t err;
3005
3006    bool signalEOS = false;
3007    int64_t timestampUs = 0;
3008
3009    size_t offset = 0;
3010    int32_t n = 0;
3011
3012
3013    for (;;) {
3014        MediaBuffer *srcBuffer;
3015        if (mSeekTimeUs >= 0) {
3016            if (mLeftOverBuffer) {
3017                mLeftOverBuffer->release();
3018                mLeftOverBuffer = NULL;
3019            }
3020
3021            MediaSource::ReadOptions options;
3022            options.setSeekTo(mSeekTimeUs, mSeekMode);
3023
3024            mSeekTimeUs = -1;
3025            mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC;
3026            mBufferFilled.signal();
3027
3028            err = mSource->read(&srcBuffer, &options);
3029
3030            if (err == OK) {
3031                int64_t targetTimeUs;
3032                if (srcBuffer->meta_data()->findInt64(
3033                            kKeyTargetTime, &targetTimeUs)
3034                        && targetTimeUs >= 0) {
3035                    CODEC_LOGV("targetTimeUs = %lld us", targetTimeUs);
3036                    mTargetTimeUs = targetTimeUs;
3037                } else {
3038                    mTargetTimeUs = -1;
3039                }
3040            }
3041        } else if (mLeftOverBuffer) {
3042            srcBuffer = mLeftOverBuffer;
3043            mLeftOverBuffer = NULL;
3044
3045            err = OK;
3046        } else {
3047            err = mSource->read(&srcBuffer);
3048        }
3049
3050        if (err != OK) {
3051            signalEOS = true;
3052            mFinalStatus = err;
3053            mSignalledEOS = true;
3054            mBufferFilled.signal();
3055            break;
3056        }
3057
3058        if (mFlags & kUseSecureInputBuffers) {
3059            info = findInputBufferByDataPointer(srcBuffer->data());
3060            CHECK(info != NULL);
3061        }
3062
3063        size_t remainingBytes = info->mSize - offset;
3064
3065        if (srcBuffer->range_length() > remainingBytes) {
3066            if (offset == 0) {
3067                CODEC_LOGE(
3068                     "Codec's input buffers are too small to accomodate "
3069                     "buffer read from source (info->mSize = %d, srcLength = %d)",
3070                     info->mSize, srcBuffer->range_length());
3071
3072                srcBuffer->release();
3073                srcBuffer = NULL;
3074
3075                setState(ERROR);
3076                return false;
3077            }
3078
3079            mLeftOverBuffer = srcBuffer;
3080            break;
3081        }
3082
3083        bool releaseBuffer = true;
3084        if (mFlags & kStoreMetaDataInVideoBuffers) {
3085                releaseBuffer = false;
3086                info->mMediaBuffer = srcBuffer;
3087        }
3088
3089        if (mFlags & kUseSecureInputBuffers) {
3090                // Data in "info" is already provided at this time.
3091
3092                releaseBuffer = false;
3093
3094                CHECK(info->mMediaBuffer == NULL);
3095                info->mMediaBuffer = srcBuffer;
3096        } else {
3097            CHECK(srcBuffer->data() != NULL) ;
3098            memcpy((uint8_t *)info->mData + offset,
3099                    (const uint8_t *)srcBuffer->data()
3100                        + srcBuffer->range_offset(),
3101                    srcBuffer->range_length());
3102        }
3103
3104        int64_t lastBufferTimeUs;
3105        CHECK(srcBuffer->meta_data()->findInt64(kKeyTime, &lastBufferTimeUs));
3106        CHECK(lastBufferTimeUs >= 0);
3107        if (mIsEncoder && mIsVideo) {
3108            mDecodingTimeList.push_back(lastBufferTimeUs);
3109        }
3110
3111        if (offset == 0) {
3112            timestampUs = lastBufferTimeUs;
3113        }
3114
3115        offset += srcBuffer->range_length();
3116
3117        if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_VORBIS, mMIME)) {
3118            CHECK(!(mQuirks & kSupportsMultipleFramesPerInputBuffer));
3119            CHECK_GE(info->mSize, offset + sizeof(int32_t));
3120
3121            int32_t numPageSamples;
3122            if (!srcBuffer->meta_data()->findInt32(
3123                        kKeyValidSamples, &numPageSamples)) {
3124                numPageSamples = -1;
3125            }
3126
3127            memcpy((uint8_t *)info->mData + offset,
3128                   &numPageSamples,
3129                   sizeof(numPageSamples));
3130
3131            offset += sizeof(numPageSamples);
3132        }
3133
3134        if (releaseBuffer) {
3135            srcBuffer->release();
3136            srcBuffer = NULL;
3137        }
3138
3139        ++n;
3140
3141        if (!(mQuirks & kSupportsMultipleFramesPerInputBuffer)) {
3142            break;
3143        }
3144
3145        int64_t coalescedDurationUs = lastBufferTimeUs - timestampUs;
3146
3147        if (coalescedDurationUs > 250000ll) {
3148            // Don't coalesce more than 250ms worth of encoded data at once.
3149            break;
3150        }
3151    }
3152
3153    if (n > 1) {
3154        ALOGV("coalesced %d frames into one input buffer", n);
3155    }
3156
3157    OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME;
3158
3159    if (signalEOS) {
3160        flags |= OMX_BUFFERFLAG_EOS;
3161    } else {
3162        mNoMoreOutputData = false;
3163    }
3164
3165    if (info == NULL) {
3166        CHECK(mFlags & kUseSecureInputBuffers);
3167        CHECK(signalEOS);
3168
3169        // This is fishy, there's still a MediaBuffer corresponding to this
3170        // info available to the source at this point even though we're going
3171        // to use it to signal EOS to the codec.
3172        info = findEmptyInputBuffer();
3173    }
3174
3175    CODEC_LOGV("Calling emptyBuffer on buffer %p (length %d), "
3176               "timestamp %lld us (%.2f secs)",
3177               info->mBuffer, offset,
3178               timestampUs, timestampUs / 1E6);
3179
3180    err = mOMX->emptyBuffer(
3181            mNode, info->mBuffer, 0, offset,
3182            flags, timestampUs);
3183
3184    if (err != OK) {
3185        setState(ERROR);
3186        return false;
3187    }
3188
3189    info->mStatus = OWNED_BY_COMPONENT;
3190
3191    return true;
3192}
3193
3194void OMXCodec::fillOutputBuffer(BufferInfo *info) {
3195    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
3196
3197    if (mNoMoreOutputData) {
3198        CODEC_LOGV("There is no more output data available, not "
3199             "calling fillOutputBuffer");
3200        return;
3201    }
3202
3203    CODEC_LOGV("Calling fillBuffer on buffer %p", info->mBuffer);
3204    status_t err = mOMX->fillBuffer(mNode, info->mBuffer);
3205
3206    if (err != OK) {
3207        CODEC_LOGE("fillBuffer failed w/ error 0x%08x", err);
3208
3209        setState(ERROR);
3210        return;
3211    }
3212
3213    info->mStatus = OWNED_BY_COMPONENT;
3214}
3215
3216bool OMXCodec::drainInputBuffer(IOMX::buffer_id buffer) {
3217    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
3218    for (size_t i = 0; i < buffers->size(); ++i) {
3219        if ((*buffers)[i].mBuffer == buffer) {
3220            return drainInputBuffer(&buffers->editItemAt(i));
3221        }
3222    }
3223
3224    CHECK(!"should not be here.");
3225
3226    return false;
3227}
3228
3229void OMXCodec::fillOutputBuffer(IOMX::buffer_id buffer) {
3230    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
3231    for (size_t i = 0; i < buffers->size(); ++i) {
3232        if ((*buffers)[i].mBuffer == buffer) {
3233            fillOutputBuffer(&buffers->editItemAt(i));
3234            return;
3235        }
3236    }
3237
3238    CHECK(!"should not be here.");
3239}
3240
3241void OMXCodec::setState(State newState) {
3242    mState = newState;
3243    mAsyncCompletion.signal();
3244
3245    // This may cause some spurious wakeups but is necessary to
3246    // unblock the reader if we enter ERROR state.
3247    mBufferFilled.signal();
3248}
3249
3250status_t OMXCodec::waitForBufferFilled_l() {
3251
3252    if (mIsEncoder) {
3253        // For timelapse video recording, the timelapse video recording may
3254        // not send an input frame for a _long_ time. Do not use timeout
3255        // for video encoding.
3256        return mBufferFilled.wait(mLock);
3257    }
3258    status_t err = mBufferFilled.waitRelative(mLock, kBufferFilledEventTimeOutNs);
3259    if (err != OK) {
3260        CODEC_LOGE("Timed out waiting for output buffers: %d/%d",
3261            countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
3262            countBuffersWeOwn(mPortBuffers[kPortIndexOutput]));
3263    }
3264    return err;
3265}
3266
3267void OMXCodec::setRawAudioFormat(
3268        OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels) {
3269
3270    // port definition
3271    OMX_PARAM_PORTDEFINITIONTYPE def;
3272    InitOMXParams(&def);
3273    def.nPortIndex = portIndex;
3274    status_t err = mOMX->getParameter(
3275            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3276    CHECK_EQ(err, (status_t)OK);
3277    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
3278    CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition,
3279            &def, sizeof(def)), (status_t)OK);
3280
3281    // pcm param
3282    OMX_AUDIO_PARAM_PCMMODETYPE pcmParams;
3283    InitOMXParams(&pcmParams);
3284    pcmParams.nPortIndex = portIndex;
3285
3286    err = mOMX->getParameter(
3287            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
3288
3289    CHECK_EQ(err, (status_t)OK);
3290
3291    pcmParams.nChannels = numChannels;
3292    pcmParams.eNumData = OMX_NumericalDataSigned;
3293    pcmParams.bInterleaved = OMX_TRUE;
3294    pcmParams.nBitPerSample = 16;
3295    pcmParams.nSamplingRate = sampleRate;
3296    pcmParams.ePCMMode = OMX_AUDIO_PCMModeLinear;
3297
3298    CHECK_EQ(getOMXChannelMapping(
3299                numChannels, pcmParams.eChannelMapping), (status_t)OK);
3300
3301    err = mOMX->setParameter(
3302            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
3303
3304    CHECK_EQ(err, (status_t)OK);
3305}
3306
3307static OMX_AUDIO_AMRBANDMODETYPE pickModeFromBitRate(bool isAMRWB, int32_t bps) {
3308    if (isAMRWB) {
3309        if (bps <= 6600) {
3310            return OMX_AUDIO_AMRBandModeWB0;
3311        } else if (bps <= 8850) {
3312            return OMX_AUDIO_AMRBandModeWB1;
3313        } else if (bps <= 12650) {
3314            return OMX_AUDIO_AMRBandModeWB2;
3315        } else if (bps <= 14250) {
3316            return OMX_AUDIO_AMRBandModeWB3;
3317        } else if (bps <= 15850) {
3318            return OMX_AUDIO_AMRBandModeWB4;
3319        } else if (bps <= 18250) {
3320            return OMX_AUDIO_AMRBandModeWB5;
3321        } else if (bps <= 19850) {
3322            return OMX_AUDIO_AMRBandModeWB6;
3323        } else if (bps <= 23050) {
3324            return OMX_AUDIO_AMRBandModeWB7;
3325        }
3326
3327        // 23850 bps
3328        return OMX_AUDIO_AMRBandModeWB8;
3329    } else {  // AMRNB
3330        if (bps <= 4750) {
3331            return OMX_AUDIO_AMRBandModeNB0;
3332        } else if (bps <= 5150) {
3333            return OMX_AUDIO_AMRBandModeNB1;
3334        } else if (bps <= 5900) {
3335            return OMX_AUDIO_AMRBandModeNB2;
3336        } else if (bps <= 6700) {
3337            return OMX_AUDIO_AMRBandModeNB3;
3338        } else if (bps <= 7400) {
3339            return OMX_AUDIO_AMRBandModeNB4;
3340        } else if (bps <= 7950) {
3341            return OMX_AUDIO_AMRBandModeNB5;
3342        } else if (bps <= 10200) {
3343            return OMX_AUDIO_AMRBandModeNB6;
3344        }
3345
3346        // 12200 bps
3347        return OMX_AUDIO_AMRBandModeNB7;
3348    }
3349}
3350
3351void OMXCodec::setAMRFormat(bool isWAMR, int32_t bitRate) {
3352    OMX_U32 portIndex = mIsEncoder ? kPortIndexOutput : kPortIndexInput;
3353
3354    OMX_AUDIO_PARAM_AMRTYPE def;
3355    InitOMXParams(&def);
3356    def.nPortIndex = portIndex;
3357
3358    status_t err =
3359        mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
3360
3361    CHECK_EQ(err, (status_t)OK);
3362
3363    def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
3364
3365    def.eAMRBandMode = pickModeFromBitRate(isWAMR, bitRate);
3366    err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
3367    CHECK_EQ(err, (status_t)OK);
3368
3369    ////////////////////////
3370
3371    if (mIsEncoder) {
3372        sp<MetaData> format = mSource->getFormat();
3373        int32_t sampleRate;
3374        int32_t numChannels;
3375        CHECK(format->findInt32(kKeySampleRate, &sampleRate));
3376        CHECK(format->findInt32(kKeyChannelCount, &numChannels));
3377
3378        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
3379    }
3380}
3381
3382status_t OMXCodec::setAACFormat(
3383        int32_t numChannels, int32_t sampleRate, int32_t bitRate, int32_t aacProfile, bool isADTS) {
3384    if (numChannels > 2) {
3385        ALOGW("Number of channels: (%d) \n", numChannels);
3386    }
3387
3388    if (mIsEncoder) {
3389        if (isADTS) {
3390            return -EINVAL;
3391        }
3392
3393        //////////////// input port ////////////////////
3394        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
3395
3396        //////////////// output port ////////////////////
3397        // format
3398        OMX_AUDIO_PARAM_PORTFORMATTYPE format;
3399        InitOMXParams(&format);
3400        format.nPortIndex = kPortIndexOutput;
3401        format.nIndex = 0;
3402        status_t err = OMX_ErrorNone;
3403        while (OMX_ErrorNone == err) {
3404            CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioPortFormat,
3405                    &format, sizeof(format)), (status_t)OK);
3406            if (format.eEncoding == OMX_AUDIO_CodingAAC) {
3407                break;
3408            }
3409            format.nIndex++;
3410        }
3411        CHECK_EQ((status_t)OK, err);
3412        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioPortFormat,
3413                &format, sizeof(format)), (status_t)OK);
3414
3415        // port definition
3416        OMX_PARAM_PORTDEFINITIONTYPE def;
3417        InitOMXParams(&def);
3418        def.nPortIndex = kPortIndexOutput;
3419        CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamPortDefinition,
3420                &def, sizeof(def)), (status_t)OK);
3421        def.format.audio.bFlagErrorConcealment = OMX_TRUE;
3422        def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
3423        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition,
3424                &def, sizeof(def)), (status_t)OK);
3425
3426        // profile
3427        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
3428        InitOMXParams(&profile);
3429        profile.nPortIndex = kPortIndexOutput;
3430        CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioAac,
3431                &profile, sizeof(profile)), (status_t)OK);
3432        profile.nChannels = numChannels;
3433        profile.eChannelMode = (numChannels == 1?
3434                OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo);
3435        profile.nSampleRate = sampleRate;
3436        profile.nBitRate = bitRate;
3437        profile.nAudioBandWidth = 0;
3438        profile.nFrameLength = 0;
3439        profile.nAACtools = OMX_AUDIO_AACToolAll;
3440        profile.nAACERtools = OMX_AUDIO_AACERNone;
3441        profile.eAACProfile = (OMX_AUDIO_AACPROFILETYPE) aacProfile;
3442        profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
3443        err = mOMX->setParameter(mNode, OMX_IndexParamAudioAac,
3444                &profile, sizeof(profile));
3445
3446        if (err != OK) {
3447            CODEC_LOGE("setParameter('OMX_IndexParamAudioAac') failed "
3448                       "(err = %d)",
3449                       err);
3450            return err;
3451        }
3452    } else {
3453        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
3454        InitOMXParams(&profile);
3455        profile.nPortIndex = kPortIndexInput;
3456
3457        status_t err = mOMX->getParameter(
3458                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
3459        CHECK_EQ(err, (status_t)OK);
3460
3461        profile.nChannels = numChannels;
3462        profile.nSampleRate = sampleRate;
3463
3464        profile.eAACStreamFormat =
3465            isADTS
3466                ? OMX_AUDIO_AACStreamFormatMP4ADTS
3467                : OMX_AUDIO_AACStreamFormatMP4FF;
3468
3469        err = mOMX->setParameter(
3470                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
3471
3472        if (err != OK) {
3473            CODEC_LOGE("setParameter('OMX_IndexParamAudioAac') failed "
3474                       "(err = %d)",
3475                       err);
3476            return err;
3477        }
3478    }
3479
3480    return OK;
3481}
3482
3483void OMXCodec::setG711Format(int32_t numChannels) {
3484    CHECK(!mIsEncoder);
3485    setRawAudioFormat(kPortIndexInput, 8000, numChannels);
3486}
3487
3488void OMXCodec::setImageOutputFormat(
3489        OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height) {
3490    CODEC_LOGV("setImageOutputFormat(%ld, %ld)", width, height);
3491
3492#if 0
3493    OMX_INDEXTYPE index;
3494    status_t err = mOMX->get_extension_index(
3495            mNode, "OMX.TI.JPEG.decode.Config.OutputColorFormat", &index);
3496    CHECK_EQ(err, (status_t)OK);
3497
3498    err = mOMX->set_config(mNode, index, &format, sizeof(format));
3499    CHECK_EQ(err, (status_t)OK);
3500#endif
3501
3502    OMX_PARAM_PORTDEFINITIONTYPE def;
3503    InitOMXParams(&def);
3504    def.nPortIndex = kPortIndexOutput;
3505
3506    status_t err = mOMX->getParameter(
3507            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3508    CHECK_EQ(err, (status_t)OK);
3509
3510    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage);
3511
3512    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3513
3514    CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingUnused);
3515    imageDef->eColorFormat = format;
3516    imageDef->nFrameWidth = width;
3517    imageDef->nFrameHeight = height;
3518
3519    switch (format) {
3520        case OMX_COLOR_FormatYUV420PackedPlanar:
3521        case OMX_COLOR_FormatYUV411Planar:
3522        {
3523            def.nBufferSize = (width * height * 3) / 2;
3524            break;
3525        }
3526
3527        case OMX_COLOR_FormatCbYCrY:
3528        {
3529            def.nBufferSize = width * height * 2;
3530            break;
3531        }
3532
3533        case OMX_COLOR_Format32bitARGB8888:
3534        {
3535            def.nBufferSize = width * height * 4;
3536            break;
3537        }
3538
3539        case OMX_COLOR_Format16bitARGB4444:
3540        case OMX_COLOR_Format16bitARGB1555:
3541        case OMX_COLOR_Format16bitRGB565:
3542        case OMX_COLOR_Format16bitBGR565:
3543        {
3544            def.nBufferSize = width * height * 2;
3545            break;
3546        }
3547
3548        default:
3549            CHECK(!"Should not be here. Unknown color format.");
3550            break;
3551    }
3552
3553    def.nBufferCountActual = def.nBufferCountMin;
3554
3555    err = mOMX->setParameter(
3556            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3557    CHECK_EQ(err, (status_t)OK);
3558}
3559
3560void OMXCodec::setJPEGInputFormat(
3561        OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize) {
3562    OMX_PARAM_PORTDEFINITIONTYPE def;
3563    InitOMXParams(&def);
3564    def.nPortIndex = kPortIndexInput;
3565
3566    status_t err = mOMX->getParameter(
3567            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3568    CHECK_EQ(err, (status_t)OK);
3569
3570    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage);
3571    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3572
3573    CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingJPEG);
3574    imageDef->nFrameWidth = width;
3575    imageDef->nFrameHeight = height;
3576
3577    def.nBufferSize = compressedSize;
3578    def.nBufferCountActual = def.nBufferCountMin;
3579
3580    err = mOMX->setParameter(
3581            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3582    CHECK_EQ(err, (status_t)OK);
3583}
3584
3585void OMXCodec::addCodecSpecificData(const void *data, size_t size) {
3586    CodecSpecificData *specific =
3587        (CodecSpecificData *)malloc(sizeof(CodecSpecificData) + size - 1);
3588
3589    specific->mSize = size;
3590    memcpy(specific->mData, data, size);
3591
3592    mCodecSpecificData.push(specific);
3593}
3594
3595void OMXCodec::clearCodecSpecificData() {
3596    for (size_t i = 0; i < mCodecSpecificData.size(); ++i) {
3597        free(mCodecSpecificData.editItemAt(i));
3598    }
3599    mCodecSpecificData.clear();
3600    mCodecSpecificDataIndex = 0;
3601}
3602
3603status_t OMXCodec::start(MetaData *meta) {
3604    Mutex::Autolock autoLock(mLock);
3605
3606    if (mState != LOADED) {
3607        CODEC_LOGE("called start in the unexpected state: %d", mState);
3608        return UNKNOWN_ERROR;
3609    }
3610
3611    sp<MetaData> params = new MetaData;
3612    if (mQuirks & kWantsNALFragments) {
3613        params->setInt32(kKeyWantsNALFragments, true);
3614    }
3615    if (meta) {
3616        int64_t startTimeUs = 0;
3617        int64_t timeUs;
3618        if (meta->findInt64(kKeyTime, &timeUs)) {
3619            startTimeUs = timeUs;
3620        }
3621        params->setInt64(kKeyTime, startTimeUs);
3622    }
3623
3624    mCodecSpecificDataIndex = 0;
3625    mInitialBufferSubmit = true;
3626    mSignalledEOS = false;
3627    mNoMoreOutputData = false;
3628    mOutputPortSettingsHaveChanged = false;
3629    mSeekTimeUs = -1;
3630    mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC;
3631    mTargetTimeUs = -1;
3632    mFilledBuffers.clear();
3633    mPaused = false;
3634
3635    status_t err;
3636    if (mIsEncoder) {
3637        // Calling init() before starting its source so that we can configure,
3638        // if supported, the source to use exactly the same number of input
3639        // buffers as requested by the encoder.
3640        if ((err = init()) != OK) {
3641            CODEC_LOGE("init failed: %d", err);
3642            return err;
3643        }
3644
3645        params->setInt32(kKeyNumBuffers, mPortBuffers[kPortIndexInput].size());
3646        err = mSource->start(params.get());
3647        if (err != OK) {
3648            CODEC_LOGE("source failed to start: %d", err);
3649            stopOmxComponent_l();
3650        }
3651        return err;
3652    }
3653
3654    // Decoder case
3655    if ((err = mSource->start(params.get())) != OK) {
3656        CODEC_LOGE("source failed to start: %d", err);
3657        return err;
3658    }
3659    return init();
3660}
3661
3662status_t OMXCodec::stop() {
3663    CODEC_LOGV("stop mState=%d", mState);
3664    Mutex::Autolock autoLock(mLock);
3665    status_t err = stopOmxComponent_l();
3666    mSource->stop();
3667
3668    CODEC_LOGV("stopped in state %d", mState);
3669    return err;
3670}
3671
3672status_t OMXCodec::stopOmxComponent_l() {
3673    CODEC_LOGV("stopOmxComponent_l mState=%d", mState);
3674
3675    while (isIntermediateState(mState)) {
3676        mAsyncCompletion.wait(mLock);
3677    }
3678
3679    bool isError = false;
3680    switch (mState) {
3681        case LOADED:
3682            break;
3683
3684        case ERROR:
3685        {
3686            if (mPortStatus[kPortIndexOutput] == ENABLING) {
3687                // Codec is in a wedged state (technical term)
3688                // We've seen an output port settings change from the codec,
3689                // We've disabled the output port, then freed the output
3690                // buffers, initiated re-enabling the output port but
3691                // failed to reallocate the output buffers.
3692                // There doesn't seem to be a way to orderly transition
3693                // from executing->idle and idle->loaded now that the
3694                // output port hasn't been reenabled yet...
3695                // Simply free as many resources as we can and pretend
3696                // that we're in LOADED state so that the destructor
3697                // will free the component instance without asserting.
3698                freeBuffersOnPort(kPortIndexInput, true /* onlyThoseWeOwn */);
3699                freeBuffersOnPort(kPortIndexOutput, true /* onlyThoseWeOwn */);
3700                setState(LOADED);
3701                break;
3702            } else {
3703                OMX_STATETYPE state = OMX_StateInvalid;
3704                status_t err = mOMX->getState(mNode, &state);
3705                CHECK_EQ(err, (status_t)OK);
3706
3707                if (state != OMX_StateExecuting) {
3708                    break;
3709                }
3710                // else fall through to the idling code
3711            }
3712
3713            isError = true;
3714        }
3715
3716        case EXECUTING:
3717        {
3718            setState(EXECUTING_TO_IDLE);
3719
3720            if (mQuirks & kRequiresFlushBeforeShutdown) {
3721                CODEC_LOGV("This component requires a flush before transitioning "
3722                     "from EXECUTING to IDLE...");
3723
3724                bool emulateInputFlushCompletion =
3725                    !flushPortAsync(kPortIndexInput);
3726
3727                bool emulateOutputFlushCompletion =
3728                    !flushPortAsync(kPortIndexOutput);
3729
3730                if (emulateInputFlushCompletion) {
3731                    onCmdComplete(OMX_CommandFlush, kPortIndexInput);
3732                }
3733
3734                if (emulateOutputFlushCompletion) {
3735                    onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
3736                }
3737            } else {
3738                mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
3739                mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
3740
3741                status_t err =
3742                    mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
3743                CHECK_EQ(err, (status_t)OK);
3744            }
3745
3746            while (mState != LOADED && mState != ERROR) {
3747                mAsyncCompletion.wait(mLock);
3748            }
3749
3750            if (isError) {
3751                // We were in the ERROR state coming in, so restore that now
3752                // that we've idled the OMX component.
3753                setState(ERROR);
3754            }
3755
3756            break;
3757        }
3758
3759        default:
3760        {
3761            CHECK(!"should not be here.");
3762            break;
3763        }
3764    }
3765
3766    if (mLeftOverBuffer) {
3767        mLeftOverBuffer->release();
3768        mLeftOverBuffer = NULL;
3769    }
3770
3771    return OK;
3772}
3773
3774sp<MetaData> OMXCodec::getFormat() {
3775    Mutex::Autolock autoLock(mLock);
3776
3777    return mOutputFormat;
3778}
3779
3780status_t OMXCodec::read(
3781        MediaBuffer **buffer, const ReadOptions *options) {
3782    status_t err = OK;
3783    *buffer = NULL;
3784
3785    Mutex::Autolock autoLock(mLock);
3786
3787    if (mState != EXECUTING && mState != RECONFIGURING) {
3788        return UNKNOWN_ERROR;
3789    }
3790
3791    bool seeking = false;
3792    int64_t seekTimeUs;
3793    ReadOptions::SeekMode seekMode;
3794    if (options && options->getSeekTo(&seekTimeUs, &seekMode)) {
3795        seeking = true;
3796    }
3797
3798    if (mInitialBufferSubmit) {
3799        mInitialBufferSubmit = false;
3800
3801        if (seeking) {
3802            CHECK(seekTimeUs >= 0);
3803            mSeekTimeUs = seekTimeUs;
3804            mSeekMode = seekMode;
3805
3806            // There's no reason to trigger the code below, there's
3807            // nothing to flush yet.
3808            seeking = false;
3809            mPaused = false;
3810        }
3811
3812        drainInputBuffers();
3813
3814        if (mState == EXECUTING) {
3815            // Otherwise mState == RECONFIGURING and this code will trigger
3816            // after the output port is reenabled.
3817            fillOutputBuffers();
3818        }
3819    }
3820
3821    if (seeking) {
3822        while (mState == RECONFIGURING) {
3823            if ((err = waitForBufferFilled_l()) != OK) {
3824                return err;
3825            }
3826        }
3827
3828        if (mState != EXECUTING) {
3829            return UNKNOWN_ERROR;
3830        }
3831
3832        CODEC_LOGV("seeking to %lld us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6);
3833
3834        mSignalledEOS = false;
3835
3836        CHECK(seekTimeUs >= 0);
3837        mSeekTimeUs = seekTimeUs;
3838        mSeekMode = seekMode;
3839
3840        mFilledBuffers.clear();
3841
3842        CHECK_EQ((int)mState, (int)EXECUTING);
3843
3844        bool emulateInputFlushCompletion = !flushPortAsync(kPortIndexInput);
3845        bool emulateOutputFlushCompletion = !flushPortAsync(kPortIndexOutput);
3846
3847        if (emulateInputFlushCompletion) {
3848            onCmdComplete(OMX_CommandFlush, kPortIndexInput);
3849        }
3850
3851        if (emulateOutputFlushCompletion) {
3852            onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
3853        }
3854
3855        while (mSeekTimeUs >= 0) {
3856            if ((err = waitForBufferFilled_l()) != OK) {
3857                return err;
3858            }
3859        }
3860    }
3861
3862    while (mState != ERROR && !mNoMoreOutputData && mFilledBuffers.empty()) {
3863        if ((err = waitForBufferFilled_l()) != OK) {
3864            return err;
3865        }
3866    }
3867
3868    if (mState == ERROR) {
3869        return UNKNOWN_ERROR;
3870    }
3871
3872    if (mFilledBuffers.empty()) {
3873        return mSignalledEOS ? mFinalStatus : ERROR_END_OF_STREAM;
3874    }
3875
3876    if (mOutputPortSettingsHaveChanged) {
3877        mOutputPortSettingsHaveChanged = false;
3878
3879        return INFO_FORMAT_CHANGED;
3880    }
3881
3882    size_t index = *mFilledBuffers.begin();
3883    mFilledBuffers.erase(mFilledBuffers.begin());
3884
3885    BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index);
3886    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
3887    info->mStatus = OWNED_BY_CLIENT;
3888
3889    info->mMediaBuffer->add_ref();
3890    if (mSkipCutBuffer != NULL) {
3891        mSkipCutBuffer->submit(info->mMediaBuffer);
3892    }
3893    *buffer = info->mMediaBuffer;
3894
3895    return OK;
3896}
3897
3898void OMXCodec::signalBufferReturned(MediaBuffer *buffer) {
3899    Mutex::Autolock autoLock(mLock);
3900
3901    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
3902    for (size_t i = 0; i < buffers->size(); ++i) {
3903        BufferInfo *info = &buffers->editItemAt(i);
3904
3905        if (info->mMediaBuffer == buffer) {
3906            CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED);
3907            CHECK_EQ((int)info->mStatus, (int)OWNED_BY_CLIENT);
3908
3909            info->mStatus = OWNED_BY_US;
3910
3911            if (buffer->graphicBuffer() == 0) {
3912                fillOutputBuffer(info);
3913            } else {
3914                sp<MetaData> metaData = info->mMediaBuffer->meta_data();
3915                int32_t rendered = 0;
3916                if (!metaData->findInt32(kKeyRendered, &rendered)) {
3917                    rendered = 0;
3918                }
3919                if (!rendered) {
3920                    status_t err = cancelBufferToNativeWindow(info);
3921                    if (err < 0) {
3922                        return;
3923                    }
3924                }
3925
3926                info->mStatus = OWNED_BY_NATIVE_WINDOW;
3927
3928                // Dequeue the next buffer from the native window.
3929                BufferInfo *nextBufInfo = dequeueBufferFromNativeWindow();
3930                if (nextBufInfo == 0) {
3931                    return;
3932                }
3933
3934                // Give the buffer to the OMX node to fill.
3935                fillOutputBuffer(nextBufInfo);
3936            }
3937            return;
3938        }
3939    }
3940
3941    CHECK(!"should not be here.");
3942}
3943
3944static const char *imageCompressionFormatString(OMX_IMAGE_CODINGTYPE type) {
3945    static const char *kNames[] = {
3946        "OMX_IMAGE_CodingUnused",
3947        "OMX_IMAGE_CodingAutoDetect",
3948        "OMX_IMAGE_CodingJPEG",
3949        "OMX_IMAGE_CodingJPEG2K",
3950        "OMX_IMAGE_CodingEXIF",
3951        "OMX_IMAGE_CodingTIFF",
3952        "OMX_IMAGE_CodingGIF",
3953        "OMX_IMAGE_CodingPNG",
3954        "OMX_IMAGE_CodingLZW",
3955        "OMX_IMAGE_CodingBMP",
3956    };
3957
3958    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3959
3960    if (type < 0 || (size_t)type >= numNames) {
3961        return "UNKNOWN";
3962    } else {
3963        return kNames[type];
3964    }
3965}
3966
3967static const char *colorFormatString(OMX_COLOR_FORMATTYPE type) {
3968    static const char *kNames[] = {
3969        "OMX_COLOR_FormatUnused",
3970        "OMX_COLOR_FormatMonochrome",
3971        "OMX_COLOR_Format8bitRGB332",
3972        "OMX_COLOR_Format12bitRGB444",
3973        "OMX_COLOR_Format16bitARGB4444",
3974        "OMX_COLOR_Format16bitARGB1555",
3975        "OMX_COLOR_Format16bitRGB565",
3976        "OMX_COLOR_Format16bitBGR565",
3977        "OMX_COLOR_Format18bitRGB666",
3978        "OMX_COLOR_Format18bitARGB1665",
3979        "OMX_COLOR_Format19bitARGB1666",
3980        "OMX_COLOR_Format24bitRGB888",
3981        "OMX_COLOR_Format24bitBGR888",
3982        "OMX_COLOR_Format24bitARGB1887",
3983        "OMX_COLOR_Format25bitARGB1888",
3984        "OMX_COLOR_Format32bitBGRA8888",
3985        "OMX_COLOR_Format32bitARGB8888",
3986        "OMX_COLOR_FormatYUV411Planar",
3987        "OMX_COLOR_FormatYUV411PackedPlanar",
3988        "OMX_COLOR_FormatYUV420Planar",
3989        "OMX_COLOR_FormatYUV420PackedPlanar",
3990        "OMX_COLOR_FormatYUV420SemiPlanar",
3991        "OMX_COLOR_FormatYUV422Planar",
3992        "OMX_COLOR_FormatYUV422PackedPlanar",
3993        "OMX_COLOR_FormatYUV422SemiPlanar",
3994        "OMX_COLOR_FormatYCbYCr",
3995        "OMX_COLOR_FormatYCrYCb",
3996        "OMX_COLOR_FormatCbYCrY",
3997        "OMX_COLOR_FormatCrYCbY",
3998        "OMX_COLOR_FormatYUV444Interleaved",
3999        "OMX_COLOR_FormatRawBayer8bit",
4000        "OMX_COLOR_FormatRawBayer10bit",
4001        "OMX_COLOR_FormatRawBayer8bitcompressed",
4002        "OMX_COLOR_FormatL2",
4003        "OMX_COLOR_FormatL4",
4004        "OMX_COLOR_FormatL8",
4005        "OMX_COLOR_FormatL16",
4006        "OMX_COLOR_FormatL24",
4007        "OMX_COLOR_FormatL32",
4008        "OMX_COLOR_FormatYUV420PackedSemiPlanar",
4009        "OMX_COLOR_FormatYUV422PackedSemiPlanar",
4010        "OMX_COLOR_Format18BitBGR666",
4011        "OMX_COLOR_Format24BitARGB6666",
4012        "OMX_COLOR_Format24BitABGR6666",
4013    };
4014
4015    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
4016
4017    if (type == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar) {
4018        return "OMX_TI_COLOR_FormatYUV420PackedSemiPlanar";
4019    } else if (type == OMX_QCOM_COLOR_FormatYVU420SemiPlanar) {
4020        return "OMX_QCOM_COLOR_FormatYVU420SemiPlanar";
4021    } else if (type < 0 || (size_t)type >= numNames) {
4022        return "UNKNOWN";
4023    } else {
4024        return kNames[type];
4025    }
4026}
4027
4028static const char *videoCompressionFormatString(OMX_VIDEO_CODINGTYPE type) {
4029    static const char *kNames[] = {
4030        "OMX_VIDEO_CodingUnused",
4031        "OMX_VIDEO_CodingAutoDetect",
4032        "OMX_VIDEO_CodingMPEG2",
4033        "OMX_VIDEO_CodingH263",
4034        "OMX_VIDEO_CodingMPEG4",
4035        "OMX_VIDEO_CodingWMV",
4036        "OMX_VIDEO_CodingRV",
4037        "OMX_VIDEO_CodingAVC",
4038        "OMX_VIDEO_CodingMJPEG",
4039    };
4040
4041    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
4042
4043    if (type < 0 || (size_t)type >= numNames) {
4044        return "UNKNOWN";
4045    } else {
4046        return kNames[type];
4047    }
4048}
4049
4050static const char *audioCodingTypeString(OMX_AUDIO_CODINGTYPE type) {
4051    static const char *kNames[] = {
4052        "OMX_AUDIO_CodingUnused",
4053        "OMX_AUDIO_CodingAutoDetect",
4054        "OMX_AUDIO_CodingPCM",
4055        "OMX_AUDIO_CodingADPCM",
4056        "OMX_AUDIO_CodingAMR",
4057        "OMX_AUDIO_CodingGSMFR",
4058        "OMX_AUDIO_CodingGSMEFR",
4059        "OMX_AUDIO_CodingGSMHR",
4060        "OMX_AUDIO_CodingPDCFR",
4061        "OMX_AUDIO_CodingPDCEFR",
4062        "OMX_AUDIO_CodingPDCHR",
4063        "OMX_AUDIO_CodingTDMAFR",
4064        "OMX_AUDIO_CodingTDMAEFR",
4065        "OMX_AUDIO_CodingQCELP8",
4066        "OMX_AUDIO_CodingQCELP13",
4067        "OMX_AUDIO_CodingEVRC",
4068        "OMX_AUDIO_CodingSMV",
4069        "OMX_AUDIO_CodingG711",
4070        "OMX_AUDIO_CodingG723",
4071        "OMX_AUDIO_CodingG726",
4072        "OMX_AUDIO_CodingG729",
4073        "OMX_AUDIO_CodingAAC",
4074        "OMX_AUDIO_CodingMP3",
4075        "OMX_AUDIO_CodingSBC",
4076        "OMX_AUDIO_CodingVORBIS",
4077        "OMX_AUDIO_CodingWMA",
4078        "OMX_AUDIO_CodingRA",
4079        "OMX_AUDIO_CodingMIDI",
4080    };
4081
4082    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
4083
4084    if (type < 0 || (size_t)type >= numNames) {
4085        return "UNKNOWN";
4086    } else {
4087        return kNames[type];
4088    }
4089}
4090
4091static const char *audioPCMModeString(OMX_AUDIO_PCMMODETYPE type) {
4092    static const char *kNames[] = {
4093        "OMX_AUDIO_PCMModeLinear",
4094        "OMX_AUDIO_PCMModeALaw",
4095        "OMX_AUDIO_PCMModeMULaw",
4096    };
4097
4098    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
4099
4100    if (type < 0 || (size_t)type >= numNames) {
4101        return "UNKNOWN";
4102    } else {
4103        return kNames[type];
4104    }
4105}
4106
4107static const char *amrBandModeString(OMX_AUDIO_AMRBANDMODETYPE type) {
4108    static const char *kNames[] = {
4109        "OMX_AUDIO_AMRBandModeUnused",
4110        "OMX_AUDIO_AMRBandModeNB0",
4111        "OMX_AUDIO_AMRBandModeNB1",
4112        "OMX_AUDIO_AMRBandModeNB2",
4113        "OMX_AUDIO_AMRBandModeNB3",
4114        "OMX_AUDIO_AMRBandModeNB4",
4115        "OMX_AUDIO_AMRBandModeNB5",
4116        "OMX_AUDIO_AMRBandModeNB6",
4117        "OMX_AUDIO_AMRBandModeNB7",
4118        "OMX_AUDIO_AMRBandModeWB0",
4119        "OMX_AUDIO_AMRBandModeWB1",
4120        "OMX_AUDIO_AMRBandModeWB2",
4121        "OMX_AUDIO_AMRBandModeWB3",
4122        "OMX_AUDIO_AMRBandModeWB4",
4123        "OMX_AUDIO_AMRBandModeWB5",
4124        "OMX_AUDIO_AMRBandModeWB6",
4125        "OMX_AUDIO_AMRBandModeWB7",
4126        "OMX_AUDIO_AMRBandModeWB8",
4127    };
4128
4129    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
4130
4131    if (type < 0 || (size_t)type >= numNames) {
4132        return "UNKNOWN";
4133    } else {
4134        return kNames[type];
4135    }
4136}
4137
4138static const char *amrFrameFormatString(OMX_AUDIO_AMRFRAMEFORMATTYPE type) {
4139    static const char *kNames[] = {
4140        "OMX_AUDIO_AMRFrameFormatConformance",
4141        "OMX_AUDIO_AMRFrameFormatIF1",
4142        "OMX_AUDIO_AMRFrameFormatIF2",
4143        "OMX_AUDIO_AMRFrameFormatFSF",
4144        "OMX_AUDIO_AMRFrameFormatRTPPayload",
4145        "OMX_AUDIO_AMRFrameFormatITU",
4146    };
4147
4148    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
4149
4150    if (type < 0 || (size_t)type >= numNames) {
4151        return "UNKNOWN";
4152    } else {
4153        return kNames[type];
4154    }
4155}
4156
4157void OMXCodec::dumpPortStatus(OMX_U32 portIndex) {
4158    OMX_PARAM_PORTDEFINITIONTYPE def;
4159    InitOMXParams(&def);
4160    def.nPortIndex = portIndex;
4161
4162    status_t err = mOMX->getParameter(
4163            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
4164    CHECK_EQ(err, (status_t)OK);
4165
4166    printf("%s Port = {\n", portIndex == kPortIndexInput ? "Input" : "Output");
4167
4168    CHECK((portIndex == kPortIndexInput && def.eDir == OMX_DirInput)
4169          || (portIndex == kPortIndexOutput && def.eDir == OMX_DirOutput));
4170
4171    printf("  nBufferCountActual = %ld\n", def.nBufferCountActual);
4172    printf("  nBufferCountMin = %ld\n", def.nBufferCountMin);
4173    printf("  nBufferSize = %ld\n", def.nBufferSize);
4174
4175    switch (def.eDomain) {
4176        case OMX_PortDomainImage:
4177        {
4178            const OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
4179
4180            printf("\n");
4181            printf("  // Image\n");
4182            printf("  nFrameWidth = %ld\n", imageDef->nFrameWidth);
4183            printf("  nFrameHeight = %ld\n", imageDef->nFrameHeight);
4184            printf("  nStride = %ld\n", imageDef->nStride);
4185
4186            printf("  eCompressionFormat = %s\n",
4187                   imageCompressionFormatString(imageDef->eCompressionFormat));
4188
4189            printf("  eColorFormat = %s\n",
4190                   colorFormatString(imageDef->eColorFormat));
4191
4192            break;
4193        }
4194
4195        case OMX_PortDomainVideo:
4196        {
4197            OMX_VIDEO_PORTDEFINITIONTYPE *videoDef = &def.format.video;
4198
4199            printf("\n");
4200            printf("  // Video\n");
4201            printf("  nFrameWidth = %ld\n", videoDef->nFrameWidth);
4202            printf("  nFrameHeight = %ld\n", videoDef->nFrameHeight);
4203            printf("  nStride = %ld\n", videoDef->nStride);
4204
4205            printf("  eCompressionFormat = %s\n",
4206                   videoCompressionFormatString(videoDef->eCompressionFormat));
4207
4208            printf("  eColorFormat = %s\n",
4209                   colorFormatString(videoDef->eColorFormat));
4210
4211            break;
4212        }
4213
4214        case OMX_PortDomainAudio:
4215        {
4216            OMX_AUDIO_PORTDEFINITIONTYPE *audioDef = &def.format.audio;
4217
4218            printf("\n");
4219            printf("  // Audio\n");
4220            printf("  eEncoding = %s\n",
4221                   audioCodingTypeString(audioDef->eEncoding));
4222
4223            if (audioDef->eEncoding == OMX_AUDIO_CodingPCM) {
4224                OMX_AUDIO_PARAM_PCMMODETYPE params;
4225                InitOMXParams(&params);
4226                params.nPortIndex = portIndex;
4227
4228                err = mOMX->getParameter(
4229                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
4230                CHECK_EQ(err, (status_t)OK);
4231
4232                printf("  nSamplingRate = %ld\n", params.nSamplingRate);
4233                printf("  nChannels = %ld\n", params.nChannels);
4234                printf("  bInterleaved = %d\n", params.bInterleaved);
4235                printf("  nBitPerSample = %ld\n", params.nBitPerSample);
4236
4237                printf("  eNumData = %s\n",
4238                       params.eNumData == OMX_NumericalDataSigned
4239                        ? "signed" : "unsigned");
4240
4241                printf("  ePCMMode = %s\n", audioPCMModeString(params.ePCMMode));
4242            } else if (audioDef->eEncoding == OMX_AUDIO_CodingAMR) {
4243                OMX_AUDIO_PARAM_AMRTYPE amr;
4244                InitOMXParams(&amr);
4245                amr.nPortIndex = portIndex;
4246
4247                err = mOMX->getParameter(
4248                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
4249                CHECK_EQ(err, (status_t)OK);
4250
4251                printf("  nChannels = %ld\n", amr.nChannels);
4252                printf("  eAMRBandMode = %s\n",
4253                        amrBandModeString(amr.eAMRBandMode));
4254                printf("  eAMRFrameFormat = %s\n",
4255                        amrFrameFormatString(amr.eAMRFrameFormat));
4256            }
4257
4258            break;
4259        }
4260
4261        default:
4262        {
4263            printf("  // Unknown\n");
4264            break;
4265        }
4266    }
4267
4268    printf("}\n");
4269}
4270
4271status_t OMXCodec::initNativeWindow() {
4272    // Enable use of a GraphicBuffer as the output for this node.  This must
4273    // happen before getting the IndexParamPortDefinition parameter because it
4274    // will affect the pixel format that the node reports.
4275    status_t err = mOMX->enableGraphicBuffers(mNode, kPortIndexOutput, OMX_TRUE);
4276    if (err != 0) {
4277        return err;
4278    }
4279
4280    return OK;
4281}
4282
4283void OMXCodec::initNativeWindowCrop() {
4284    int32_t left, top, right, bottom;
4285
4286    CHECK(mOutputFormat->findRect(
4287                        kKeyCropRect,
4288                        &left, &top, &right, &bottom));
4289
4290    android_native_rect_t crop;
4291    crop.left = left;
4292    crop.top = top;
4293    crop.right = right + 1;
4294    crop.bottom = bottom + 1;
4295
4296    // We'll ignore any errors here, if the surface is
4297    // already invalid, we'll know soon enough.
4298    native_window_set_crop(mNativeWindow.get(), &crop);
4299}
4300
4301void OMXCodec::initOutputFormat(const sp<MetaData> &inputFormat) {
4302    mOutputFormat = new MetaData;
4303    mOutputFormat->setCString(kKeyDecoderComponent, mComponentName);
4304    if (mIsEncoder) {
4305        int32_t timeScale;
4306        if (inputFormat->findInt32(kKeyTimeScale, &timeScale)) {
4307            mOutputFormat->setInt32(kKeyTimeScale, timeScale);
4308        }
4309    }
4310
4311    OMX_PARAM_PORTDEFINITIONTYPE def;
4312    InitOMXParams(&def);
4313    def.nPortIndex = kPortIndexOutput;
4314
4315    status_t err = mOMX->getParameter(
4316            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
4317    CHECK_EQ(err, (status_t)OK);
4318
4319    switch (def.eDomain) {
4320        case OMX_PortDomainImage:
4321        {
4322            OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
4323            CHECK_EQ((int)imageDef->eCompressionFormat,
4324                     (int)OMX_IMAGE_CodingUnused);
4325
4326            mOutputFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
4327            mOutputFormat->setInt32(kKeyColorFormat, imageDef->eColorFormat);
4328            mOutputFormat->setInt32(kKeyWidth, imageDef->nFrameWidth);
4329            mOutputFormat->setInt32(kKeyHeight, imageDef->nFrameHeight);
4330            break;
4331        }
4332
4333        case OMX_PortDomainAudio:
4334        {
4335            OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio;
4336
4337            if (audio_def->eEncoding == OMX_AUDIO_CodingPCM) {
4338                OMX_AUDIO_PARAM_PCMMODETYPE params;
4339                InitOMXParams(&params);
4340                params.nPortIndex = kPortIndexOutput;
4341
4342                err = mOMX->getParameter(
4343                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
4344                CHECK_EQ(err, (status_t)OK);
4345
4346                CHECK_EQ((int)params.eNumData, (int)OMX_NumericalDataSigned);
4347                CHECK_EQ(params.nBitPerSample, 16u);
4348                CHECK_EQ((int)params.ePCMMode, (int)OMX_AUDIO_PCMModeLinear);
4349
4350                int32_t numChannels, sampleRate;
4351                inputFormat->findInt32(kKeyChannelCount, &numChannels);
4352                inputFormat->findInt32(kKeySampleRate, &sampleRate);
4353
4354                if ((OMX_U32)numChannels != params.nChannels) {
4355                    ALOGV("Codec outputs a different number of channels than "
4356                         "the input stream contains (contains %d channels, "
4357                         "codec outputs %ld channels).",
4358                         numChannels, params.nChannels);
4359                }
4360
4361                if (sampleRate != (int32_t)params.nSamplingRate) {
4362                    ALOGV("Codec outputs at different sampling rate than "
4363                         "what the input stream contains (contains data at "
4364                         "%d Hz, codec outputs %lu Hz)",
4365                         sampleRate, params.nSamplingRate);
4366                }
4367
4368                mOutputFormat->setCString(
4369                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
4370
4371                // Use the codec-advertised number of channels, as some
4372                // codecs appear to output stereo even if the input data is
4373                // mono. If we know the codec lies about this information,
4374                // use the actual number of channels instead.
4375                mOutputFormat->setInt32(
4376                        kKeyChannelCount,
4377                        (mQuirks & kDecoderLiesAboutNumberOfChannels)
4378                            ? numChannels : params.nChannels);
4379
4380                mOutputFormat->setInt32(kKeySampleRate, params.nSamplingRate);
4381            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAMR) {
4382                OMX_AUDIO_PARAM_AMRTYPE amr;
4383                InitOMXParams(&amr);
4384                amr.nPortIndex = kPortIndexOutput;
4385
4386                err = mOMX->getParameter(
4387                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
4388                CHECK_EQ(err, (status_t)OK);
4389
4390                CHECK_EQ(amr.nChannels, 1u);
4391                mOutputFormat->setInt32(kKeyChannelCount, 1);
4392
4393                if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeNB0
4394                    && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeNB7) {
4395                    mOutputFormat->setCString(
4396                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB);
4397                    mOutputFormat->setInt32(kKeySampleRate, 8000);
4398                } else if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeWB0
4399                            && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeWB8) {
4400                    mOutputFormat->setCString(
4401                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB);
4402                    mOutputFormat->setInt32(kKeySampleRate, 16000);
4403                } else {
4404                    CHECK(!"Unknown AMR band mode.");
4405                }
4406            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAAC) {
4407                mOutputFormat->setCString(
4408                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
4409                int32_t numChannels, sampleRate, bitRate;
4410                inputFormat->findInt32(kKeyChannelCount, &numChannels);
4411                inputFormat->findInt32(kKeySampleRate, &sampleRate);
4412                inputFormat->findInt32(kKeyBitRate, &bitRate);
4413                mOutputFormat->setInt32(kKeyChannelCount, numChannels);
4414                mOutputFormat->setInt32(kKeySampleRate, sampleRate);
4415                mOutputFormat->setInt32(kKeyBitRate, bitRate);
4416            } else {
4417                CHECK(!"Should not be here. Unknown audio encoding.");
4418            }
4419            break;
4420        }
4421
4422        case OMX_PortDomainVideo:
4423        {
4424            OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
4425
4426            if (video_def->eCompressionFormat == OMX_VIDEO_CodingUnused) {
4427                mOutputFormat->setCString(
4428                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
4429            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingMPEG4) {
4430                mOutputFormat->setCString(
4431                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
4432            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingH263) {
4433                mOutputFormat->setCString(
4434                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
4435            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingAVC) {
4436                mOutputFormat->setCString(
4437                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
4438            } else {
4439                CHECK(!"Unknown compression format.");
4440            }
4441
4442            mOutputFormat->setInt32(kKeyWidth, video_def->nFrameWidth);
4443            mOutputFormat->setInt32(kKeyHeight, video_def->nFrameHeight);
4444            mOutputFormat->setInt32(kKeyColorFormat, video_def->eColorFormat);
4445
4446            if (!mIsEncoder) {
4447                OMX_CONFIG_RECTTYPE rect;
4448                InitOMXParams(&rect);
4449                rect.nPortIndex = kPortIndexOutput;
4450                status_t err =
4451                        mOMX->getConfig(
4452                            mNode, OMX_IndexConfigCommonOutputCrop,
4453                            &rect, sizeof(rect));
4454
4455                CODEC_LOGI(
4456                        "video dimensions are %ld x %ld",
4457                        video_def->nFrameWidth, video_def->nFrameHeight);
4458
4459                if (err == OK) {
4460                    CHECK_GE(rect.nLeft, 0);
4461                    CHECK_GE(rect.nTop, 0);
4462                    CHECK_GE(rect.nWidth, 0u);
4463                    CHECK_GE(rect.nHeight, 0u);
4464                    CHECK_LE(rect.nLeft + rect.nWidth - 1, video_def->nFrameWidth);
4465                    CHECK_LE(rect.nTop + rect.nHeight - 1, video_def->nFrameHeight);
4466
4467                    mOutputFormat->setRect(
4468                            kKeyCropRect,
4469                            rect.nLeft,
4470                            rect.nTop,
4471                            rect.nLeft + rect.nWidth - 1,
4472                            rect.nTop + rect.nHeight - 1);
4473
4474                    CODEC_LOGI(
4475                            "Crop rect is %ld x %ld @ (%ld, %ld)",
4476                            rect.nWidth, rect.nHeight, rect.nLeft, rect.nTop);
4477                } else {
4478                    mOutputFormat->setRect(
4479                            kKeyCropRect,
4480                            0, 0,
4481                            video_def->nFrameWidth - 1,
4482                            video_def->nFrameHeight - 1);
4483                }
4484
4485                if (mNativeWindow != NULL) {
4486                     initNativeWindowCrop();
4487                }
4488            }
4489            break;
4490        }
4491
4492        default:
4493        {
4494            CHECK(!"should not be here, neither audio nor video.");
4495            break;
4496        }
4497    }
4498
4499    // If the input format contains rotation information, flag the output
4500    // format accordingly.
4501
4502    int32_t rotationDegrees;
4503    if (mSource->getFormat()->findInt32(kKeyRotation, &rotationDegrees)) {
4504        mOutputFormat->setInt32(kKeyRotation, rotationDegrees);
4505    }
4506}
4507
4508status_t OMXCodec::pause() {
4509    Mutex::Autolock autoLock(mLock);
4510
4511    mPaused = true;
4512
4513    return OK;
4514}
4515
4516////////////////////////////////////////////////////////////////////////////////
4517
4518status_t QueryCodecs(
4519        const sp<IOMX> &omx,
4520        const char *mime, bool queryDecoders, bool hwCodecOnly,
4521        Vector<CodecCapabilities> *results) {
4522    Vector<OMXCodec::CodecNameAndQuirks> matchingCodecs;
4523    results->clear();
4524
4525    OMXCodec::findMatchingCodecs(mime,
4526            !queryDecoders /*createEncoder*/,
4527            NULL /*matchComponentName*/,
4528            hwCodecOnly ? OMXCodec::kHardwareCodecsOnly : 0 /*flags*/,
4529            &matchingCodecs);
4530
4531    for (size_t c = 0; c < matchingCodecs.size(); c++) {
4532        const char *componentName = matchingCodecs.itemAt(c).mName.string();
4533
4534        results->push();
4535        CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
4536
4537        status_t err =
4538            QueryCodec(omx, componentName, mime, !queryDecoders, caps);
4539
4540        if (err != OK) {
4541            results->removeAt(results->size() - 1);
4542        }
4543    }
4544
4545    return OK;
4546}
4547
4548status_t QueryCodec(
4549        const sp<IOMX> &omx,
4550        const char *componentName, const char *mime,
4551        bool isEncoder,
4552        CodecCapabilities *caps) {
4553    if (strncmp(componentName, "OMX.", 4)) {
4554        // Not an OpenMax component but a software codec.
4555
4556        caps->mComponentName = componentName;
4557        return OK;
4558    }
4559
4560    sp<OMXCodecObserver> observer = new OMXCodecObserver;
4561    IOMX::node_id node;
4562    status_t err = omx->allocateNode(componentName, observer, &node);
4563
4564    if (err != OK) {
4565        return err;
4566    }
4567
4568    OMXCodec::setComponentRole(omx, node, isEncoder, mime);
4569
4570    caps->mComponentName = componentName;
4571
4572    OMX_VIDEO_PARAM_PROFILELEVELTYPE param;
4573    InitOMXParams(&param);
4574
4575    param.nPortIndex = !isEncoder ? 0 : 1;
4576
4577    for (param.nProfileIndex = 0;; ++param.nProfileIndex) {
4578        err = omx->getParameter(
4579                node, OMX_IndexParamVideoProfileLevelQuerySupported,
4580                &param, sizeof(param));
4581
4582        if (err != OK) {
4583            break;
4584        }
4585
4586        CodecProfileLevel profileLevel;
4587        profileLevel.mProfile = param.eProfile;
4588        profileLevel.mLevel = param.eLevel;
4589
4590        caps->mProfileLevels.push(profileLevel);
4591    }
4592
4593    // Color format query
4594    OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat;
4595    InitOMXParams(&portFormat);
4596    portFormat.nPortIndex = !isEncoder ? 1 : 0;
4597    for (portFormat.nIndex = 0;; ++portFormat.nIndex)  {
4598        err = omx->getParameter(
4599                node, OMX_IndexParamVideoPortFormat,
4600                &portFormat, sizeof(portFormat));
4601        if (err != OK) {
4602            break;
4603        }
4604        caps->mColorFormats.push(portFormat.eColorFormat);
4605    }
4606
4607    CHECK_EQ(omx->freeNode(node), (status_t)OK);
4608
4609    return OK;
4610}
4611
4612status_t QueryCodecs(
4613        const sp<IOMX> &omx,
4614        const char *mimeType, bool queryDecoders,
4615        Vector<CodecCapabilities> *results) {
4616    return QueryCodecs(omx, mimeType, queryDecoders, false /*hwCodecOnly*/, results);
4617}
4618
4619// These are supposed be equivalent to the logic in
4620// "audio_channel_out_mask_from_count".
4621status_t getOMXChannelMapping(size_t numChannels, OMX_AUDIO_CHANNELTYPE map[]) {
4622    switch (numChannels) {
4623        case 1:
4624            map[0] = OMX_AUDIO_ChannelCF;
4625            break;
4626        case 2:
4627            map[0] = OMX_AUDIO_ChannelLF;
4628            map[1] = OMX_AUDIO_ChannelRF;
4629            break;
4630        case 3:
4631            map[0] = OMX_AUDIO_ChannelLF;
4632            map[1] = OMX_AUDIO_ChannelRF;
4633            map[2] = OMX_AUDIO_ChannelCF;
4634            break;
4635        case 4:
4636            map[0] = OMX_AUDIO_ChannelLF;
4637            map[1] = OMX_AUDIO_ChannelRF;
4638            map[2] = OMX_AUDIO_ChannelLR;
4639            map[3] = OMX_AUDIO_ChannelRR;
4640            break;
4641        case 5:
4642            map[0] = OMX_AUDIO_ChannelLF;
4643            map[1] = OMX_AUDIO_ChannelRF;
4644            map[2] = OMX_AUDIO_ChannelCF;
4645            map[3] = OMX_AUDIO_ChannelLR;
4646            map[4] = OMX_AUDIO_ChannelRR;
4647            break;
4648        case 6:
4649            map[0] = OMX_AUDIO_ChannelLF;
4650            map[1] = OMX_AUDIO_ChannelRF;
4651            map[2] = OMX_AUDIO_ChannelCF;
4652            map[3] = OMX_AUDIO_ChannelLFE;
4653            map[4] = OMX_AUDIO_ChannelLR;
4654            map[5] = OMX_AUDIO_ChannelRR;
4655            break;
4656        case 7:
4657            map[0] = OMX_AUDIO_ChannelLF;
4658            map[1] = OMX_AUDIO_ChannelRF;
4659            map[2] = OMX_AUDIO_ChannelCF;
4660            map[3] = OMX_AUDIO_ChannelLFE;
4661            map[4] = OMX_AUDIO_ChannelLR;
4662            map[5] = OMX_AUDIO_ChannelRR;
4663            map[6] = OMX_AUDIO_ChannelCS;
4664            break;
4665        case 8:
4666            map[0] = OMX_AUDIO_ChannelLF;
4667            map[1] = OMX_AUDIO_ChannelRF;
4668            map[2] = OMX_AUDIO_ChannelCF;
4669            map[3] = OMX_AUDIO_ChannelLFE;
4670            map[4] = OMX_AUDIO_ChannelLR;
4671            map[5] = OMX_AUDIO_ChannelRR;
4672            map[6] = OMX_AUDIO_ChannelLS;
4673            map[7] = OMX_AUDIO_ChannelRS;
4674            break;
4675        default:
4676            return -EINVAL;
4677    }
4678
4679    return OK;
4680}
4681
4682}  // namespace android
4683