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