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