OMXCodec.cpp revision d2c6894b56a538aa807e20d3ef421807cd55c009
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/AACDecoder.h"
22#include "include/AMRNBDecoder.h"
23#include "include/AMRNBEncoder.h"
24#include "include/AMRWBDecoder.h"
25#include "include/AVCDecoder.h"
26#include "include/M4vH263Decoder.h"
27#include "include/MP3Decoder.h"
28
29#include "include/ESDS.h"
30
31#include <binder/IServiceManager.h>
32#include <binder/MemoryDealer.h>
33#include <binder/ProcessState.h>
34#include <media/IMediaPlayerService.h>
35#include <media/stagefright/MediaBuffer.h>
36#include <media/stagefright/MediaBufferGroup.h>
37#include <media/stagefright/MediaDebug.h>
38#include <media/stagefright/MediaDefs.h>
39#include <media/stagefright/MediaExtractor.h>
40#include <media/stagefright/MetaData.h>
41#include <media/stagefright/OMXCodec.h>
42#include <media/stagefright/Utils.h>
43#include <utils/Vector.h>
44
45#include <OMX_Audio.h>
46#include <OMX_Component.h>
47
48namespace android {
49
50static const int OMX_QCOM_COLOR_FormatYVU420SemiPlanar = 0x7FA30C00;
51
52struct CodecInfo {
53    const char *mime;
54    const char *codec;
55};
56
57#define FACTORY_CREATE(name) \
58static sp<MediaSource> Make##name(const sp<MediaSource> &source) { \
59    return new name(source); \
60}
61
62#define FACTORY_REF(name) { #name, Make##name },
63
64FACTORY_CREATE(MP3Decoder)
65FACTORY_CREATE(AMRNBDecoder)
66FACTORY_CREATE(AMRWBDecoder)
67FACTORY_CREATE(AACDecoder)
68FACTORY_CREATE(AVCDecoder)
69FACTORY_CREATE(M4vH263Decoder)
70FACTORY_CREATE(AMRNBEncoder)
71
72static sp<MediaSource> InstantiateSoftwareCodec(
73        const char *name, const sp<MediaSource> &source) {
74    struct FactoryInfo {
75        const char *name;
76        sp<MediaSource> (*CreateFunc)(const sp<MediaSource> &);
77    };
78
79    static const FactoryInfo kFactoryInfo[] = {
80        FACTORY_REF(MP3Decoder)
81        FACTORY_REF(AMRNBDecoder)
82        FACTORY_REF(AMRWBDecoder)
83        FACTORY_REF(AACDecoder)
84        FACTORY_REF(AVCDecoder)
85        FACTORY_REF(M4vH263Decoder)
86        FACTORY_REF(AMRNBEncoder)
87    };
88    for (size_t i = 0;
89         i < sizeof(kFactoryInfo) / sizeof(kFactoryInfo[0]); ++i) {
90        if (!strcmp(name, kFactoryInfo[i].name)) {
91            return (*kFactoryInfo[i].CreateFunc)(source);
92        }
93    }
94
95    return NULL;
96}
97
98#undef FACTORY_REF
99#undef FACTORY_CREATE
100
101static const CodecInfo kDecoderInfo[] = {
102    { MEDIA_MIMETYPE_IMAGE_JPEG, "OMX.TI.JPEG.decode" },
103    { MEDIA_MIMETYPE_AUDIO_MPEG, "OMX.TI.MP3.decode" },
104    { MEDIA_MIMETYPE_AUDIO_MPEG, "MP3Decoder" },
105//    { MEDIA_MIMETYPE_AUDIO_MPEG, "OMX.PV.mp3dec" },
106//    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.TI.AMR.decode" },
107    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "AMRNBDecoder" },
108//    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.PV.amrdec" },
109    { MEDIA_MIMETYPE_AUDIO_AMR_WB, "OMX.TI.WBAMR.decode" },
110    { MEDIA_MIMETYPE_AUDIO_AMR_WB, "AMRWBDecoder" },
111//    { MEDIA_MIMETYPE_AUDIO_AMR_WB, "OMX.PV.amrdec" },
112    { MEDIA_MIMETYPE_AUDIO_AAC, "OMX.TI.AAC.decode" },
113    { MEDIA_MIMETYPE_AUDIO_AAC, "AACDecoder" },
114//    { MEDIA_MIMETYPE_AUDIO_AAC, "OMX.PV.aacdec" },
115    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.qcom.video.decoder.mpeg4" },
116    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.TI.Video.Decoder" },
117    { MEDIA_MIMETYPE_VIDEO_MPEG4, "M4vH263Decoder" },
118//    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.PV.mpeg4dec" },
119    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.qcom.video.decoder.h263" },
120    { MEDIA_MIMETYPE_VIDEO_H263, "M4vH263Decoder" },
121//    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.PV.h263dec" },
122    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.qcom.video.decoder.avc" },
123    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.TI.Video.Decoder" },
124    { MEDIA_MIMETYPE_VIDEO_AVC, "AVCDecoder" },
125//    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.PV.avcdec" },
126};
127
128static const CodecInfo kEncoderInfo[] = {
129    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.TI.AMR.encode" },
130    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "AMRNBEncoder" },
131    { MEDIA_MIMETYPE_AUDIO_AMR_WB, "OMX.TI.WBAMR.encode" },
132    { MEDIA_MIMETYPE_AUDIO_AAC, "OMX.TI.AAC.encode" },
133    { MEDIA_MIMETYPE_AUDIO_AAC, "OMX.PV.aacenc" },
134    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.qcom.video.encoder.mpeg4" },
135    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.TI.Video.encoder" },
136    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.PV.mpeg4enc" },
137    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.qcom.video.encoder.h263" },
138    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.TI.Video.encoder" },
139    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.PV.h263enc" },
140    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.TI.Video.encoder" },
141    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.PV.avcenc" },
142};
143
144#undef OPTIONAL
145
146#define CODEC_LOGI(x, ...) LOGI("[%s] "x, mComponentName, ##__VA_ARGS__)
147#define CODEC_LOGV(x, ...) LOGV("[%s] "x, mComponentName, ##__VA_ARGS__)
148#define CODEC_LOGE(x, ...) LOGE("[%s] "x, mComponentName, ##__VA_ARGS__)
149
150struct OMXCodecObserver : public BnOMXObserver {
151    OMXCodecObserver() {
152    }
153
154    void setCodec(const sp<OMXCodec> &target) {
155        mTarget = target;
156    }
157
158    // from IOMXObserver
159    virtual void onMessage(const omx_message &msg) {
160        sp<OMXCodec> codec = mTarget.promote();
161
162        if (codec.get() != NULL) {
163            codec->on_message(msg);
164        }
165    }
166
167protected:
168    virtual ~OMXCodecObserver() {}
169
170private:
171    wp<OMXCodec> mTarget;
172
173    OMXCodecObserver(const OMXCodecObserver &);
174    OMXCodecObserver &operator=(const OMXCodecObserver &);
175};
176
177static const char *GetCodec(const CodecInfo *info, size_t numInfos,
178                            const char *mime, int index) {
179    CHECK(index >= 0);
180    for(size_t i = 0; i < numInfos; ++i) {
181        if (!strcasecmp(mime, info[i].mime)) {
182            if (index == 0) {
183                return info[i].codec;
184            }
185
186            --index;
187        }
188    }
189
190    return NULL;
191}
192
193enum {
194    kAVCProfileBaseline      = 0x42,
195    kAVCProfileMain          = 0x4d,
196    kAVCProfileExtended      = 0x58,
197    kAVCProfileHigh          = 0x64,
198    kAVCProfileHigh10        = 0x6e,
199    kAVCProfileHigh422       = 0x7a,
200    kAVCProfileHigh444       = 0xf4,
201    kAVCProfileCAVLC444Intra = 0x2c
202};
203
204static const char *AVCProfileToString(uint8_t profile) {
205    switch (profile) {
206        case kAVCProfileBaseline:
207            return "Baseline";
208        case kAVCProfileMain:
209            return "Main";
210        case kAVCProfileExtended:
211            return "Extended";
212        case kAVCProfileHigh:
213            return "High";
214        case kAVCProfileHigh10:
215            return "High 10";
216        case kAVCProfileHigh422:
217            return "High 422";
218        case kAVCProfileHigh444:
219            return "High 444";
220        case kAVCProfileCAVLC444Intra:
221            return "CAVLC 444 Intra";
222        default:   return "Unknown";
223    }
224}
225
226template<class T>
227static void InitOMXParams(T *params) {
228    params->nSize = sizeof(T);
229    params->nVersion.s.nVersionMajor = 1;
230    params->nVersion.s.nVersionMinor = 0;
231    params->nVersion.s.nRevision = 0;
232    params->nVersion.s.nStep = 0;
233}
234
235static bool IsSoftwareCodec(const char *componentName) {
236    if (!strncmp("OMX.PV.", componentName, 7)) {
237        return true;
238    }
239
240    return false;
241}
242
243// A sort order in which non-OMX components are first,
244// followed by software codecs, i.e. OMX.PV.*, followed
245// by all the others.
246static int CompareSoftwareCodecsFirst(
247        const String8 *elem1, const String8 *elem2) {
248    bool isNotOMX1 = strncmp(elem1->string(), "OMX.", 4);
249    bool isNotOMX2 = strncmp(elem2->string(), "OMX.", 4);
250
251    if (isNotOMX1) {
252        if (isNotOMX2) { return 0; }
253        return -1;
254    }
255    if (isNotOMX2) {
256        return 1;
257    }
258
259    bool isSoftwareCodec1 = IsSoftwareCodec(elem1->string());
260    bool isSoftwareCodec2 = IsSoftwareCodec(elem2->string());
261
262    if (isSoftwareCodec1) {
263        if (isSoftwareCodec2) { return 0; }
264        return -1;
265    }
266
267    if (isSoftwareCodec2) {
268        return 1;
269    }
270
271    return 0;
272}
273
274// static
275uint32_t OMXCodec::getComponentQuirks(const char *componentName) {
276    uint32_t quirks = 0;
277
278    if (!strcmp(componentName, "OMX.PV.avcdec")) {
279        quirks |= kWantsNALFragments;
280    }
281    if (!strcmp(componentName, "OMX.TI.MP3.decode")) {
282        quirks |= kNeedsFlushBeforeDisable;
283        quirks |= kDecoderLiesAboutNumberOfChannels;
284    }
285    if (!strcmp(componentName, "OMX.TI.AAC.decode")) {
286        quirks |= kNeedsFlushBeforeDisable;
287        quirks |= kRequiresFlushCompleteEmulation;
288        quirks |= kSupportsMultipleFramesPerInputBuffer;
289    }
290    if (!strncmp(componentName, "OMX.qcom.video.encoder.", 23)) {
291        quirks |= kRequiresLoadedToIdleAfterAllocation;
292        quirks |= kRequiresAllocateBufferOnInputPorts;
293        quirks |= kRequiresAllocateBufferOnOutputPorts;
294    }
295    if (!strncmp(componentName, "OMX.qcom.video.decoder.", 23)) {
296        quirks |= kRequiresAllocateBufferOnOutputPorts;
297        quirks |= kDefersOutputBufferAllocation;
298    }
299
300    if (!strncmp(componentName, "OMX.TI.", 7)) {
301        // Apparently I must not use OMX_UseBuffer on either input or
302        // output ports on any of the TI components or quote:
303        // "(I) may have unexpected problem (sic) which can be timing related
304        //  and hard to reproduce."
305
306        quirks |= kRequiresAllocateBufferOnInputPorts;
307        quirks |= kRequiresAllocateBufferOnOutputPorts;
308    }
309
310    if (!strcmp(componentName, "OMX.TI.Video.Decoder")) {
311        quirks |= kInputBufferSizesAreBogus;
312    }
313
314    return quirks;
315}
316
317// static
318void OMXCodec::findMatchingCodecs(
319        const char *mime,
320        bool createEncoder, const char *matchComponentName,
321        uint32_t flags,
322        Vector<String8> *matchingCodecs) {
323    matchingCodecs->clear();
324
325    for (int index = 0;; ++index) {
326        const char *componentName;
327
328        if (createEncoder) {
329            componentName = GetCodec(
330                    kEncoderInfo,
331                    sizeof(kEncoderInfo) / sizeof(kEncoderInfo[0]),
332                    mime, index);
333        } else {
334            componentName = GetCodec(
335                    kDecoderInfo,
336                    sizeof(kDecoderInfo) / sizeof(kDecoderInfo[0]),
337                    mime, index);
338        }
339
340        if (!componentName) {
341            break;
342        }
343
344        // If a specific codec is requested, skip the non-matching ones.
345        if (matchComponentName && strcmp(componentName, matchComponentName)) {
346            continue;
347        }
348
349        matchingCodecs->push(String8(componentName));
350    }
351
352    if (flags & kPreferSoftwareCodecs) {
353        matchingCodecs->sort(CompareSoftwareCodecsFirst);
354    }
355}
356
357// static
358sp<MediaSource> OMXCodec::Create(
359        const sp<IOMX> &omx,
360        const sp<MetaData> &meta, bool createEncoder,
361        const sp<MediaSource> &source,
362        const char *matchComponentName,
363        uint32_t flags) {
364    const char *mime;
365    bool success = meta->findCString(kKeyMIMEType, &mime);
366    CHECK(success);
367
368    Vector<String8> matchingCodecs;
369    findMatchingCodecs(
370            mime, createEncoder, matchComponentName, flags, &matchingCodecs);
371
372    if (matchingCodecs.isEmpty()) {
373        return NULL;
374    }
375
376    sp<OMXCodecObserver> observer = new OMXCodecObserver;
377    IOMX::node_id node = 0;
378
379    const char *componentName;
380    for (size_t i = 0; i < matchingCodecs.size(); ++i) {
381        componentName = matchingCodecs[i].string();
382
383#if BUILD_WITH_FULL_STAGEFRIGHT
384        sp<MediaSource> softwareCodec =
385            InstantiateSoftwareCodec(componentName, source);
386
387        if (softwareCodec != NULL) {
388            LOGV("Successfully allocated software codec '%s'", componentName);
389
390            return softwareCodec;
391        }
392#endif
393
394        LOGV("Attempting to allocate OMX node '%s'", componentName);
395
396        status_t err = omx->allocateNode(componentName, observer, &node);
397        if (err == OK) {
398            LOGV("Successfully allocated OMX node '%s'", componentName);
399
400            sp<OMXCodec> codec = new OMXCodec(
401                    omx, node, getComponentQuirks(componentName),
402                    createEncoder, mime, componentName,
403                    source);
404
405            observer->setCodec(codec);
406
407            err = codec->configureCodec(meta);
408
409            if (err == OK) {
410                return codec;
411            }
412
413            LOGV("Failed to configure codec '%s'", componentName);
414        }
415    }
416
417    return NULL;
418}
419
420status_t OMXCodec::configureCodec(const sp<MetaData> &meta) {
421    uint32_t type;
422    const void *data;
423    size_t size;
424    if (meta->findData(kKeyESDS, &type, &data, &size)) {
425        ESDS esds((const char *)data, size);
426        CHECK_EQ(esds.InitCheck(), OK);
427
428        const void *codec_specific_data;
429        size_t codec_specific_data_size;
430        esds.getCodecSpecificInfo(
431                &codec_specific_data, &codec_specific_data_size);
432
433        addCodecSpecificData(
434                codec_specific_data, codec_specific_data_size);
435    } else if (meta->findData(kKeyAVCC, &type, &data, &size)) {
436        // Parse the AVCDecoderConfigurationRecord
437
438        const uint8_t *ptr = (const uint8_t *)data;
439
440        CHECK(size >= 7);
441        CHECK_EQ(ptr[0], 1);  // configurationVersion == 1
442        uint8_t profile = ptr[1];
443        uint8_t level = ptr[3];
444
445        // There is decodable content out there that fails the following
446        // assertion, let's be lenient for now...
447        // CHECK((ptr[4] >> 2) == 0x3f);  // reserved
448
449        size_t lengthSize = 1 + (ptr[4] & 3);
450
451        // commented out check below as H264_QVGA_500_NO_AUDIO.3gp
452        // violates it...
453        // CHECK((ptr[5] >> 5) == 7);  // reserved
454
455        size_t numSeqParameterSets = ptr[5] & 31;
456
457        ptr += 6;
458        size -= 6;
459
460        for (size_t i = 0; i < numSeqParameterSets; ++i) {
461            CHECK(size >= 2);
462            size_t length = U16_AT(ptr);
463
464            ptr += 2;
465            size -= 2;
466
467            CHECK(size >= length);
468
469            addCodecSpecificData(ptr, length);
470
471            ptr += length;
472            size -= length;
473        }
474
475        CHECK(size >= 1);
476        size_t numPictureParameterSets = *ptr;
477        ++ptr;
478        --size;
479
480        for (size_t i = 0; i < numPictureParameterSets; ++i) {
481            CHECK(size >= 2);
482            size_t length = U16_AT(ptr);
483
484            ptr += 2;
485            size -= 2;
486
487            CHECK(size >= length);
488
489            addCodecSpecificData(ptr, length);
490
491            ptr += length;
492            size -= length;
493        }
494
495        LOGV("AVC profile = %d (%s), level = %d",
496             (int)profile, AVCProfileToString(profile), (int)level / 10);
497
498        if (!strcmp(mComponentName, "OMX.TI.Video.Decoder")
499            && (profile != kAVCProfileBaseline || level > 39)) {
500            // This stream exceeds the decoder's capabilities. The decoder
501            // does not handle this gracefully and would clobber the heap
502            // and wreak havoc instead...
503
504            LOGE("Profile and/or level exceed the decoder's capabilities.");
505            return ERROR_UNSUPPORTED;
506        }
507    }
508
509    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mMIME)) {
510        setAMRFormat(false /* isWAMR */);
511    }
512    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mMIME)) {
513        setAMRFormat(true /* isWAMR */);
514    }
515    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mMIME)) {
516        int32_t numChannels, sampleRate;
517        CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
518        CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
519
520        setAACFormat(numChannels, sampleRate);
521    }
522    if (!strncasecmp(mMIME, "video/", 6)) {
523        int32_t width, height;
524        bool success = meta->findInt32(kKeyWidth, &width);
525        success = success && meta->findInt32(kKeyHeight, &height);
526        CHECK(success);
527
528        if (mIsEncoder) {
529            setVideoInputFormat(mMIME, width, height);
530        } else {
531            status_t err = setVideoOutputFormat(
532                    mMIME, width, height);
533
534            if (err != OK) {
535                return err;
536            }
537        }
538    }
539
540    if (!strcasecmp(mMIME, MEDIA_MIMETYPE_IMAGE_JPEG)
541        && !strcmp(mComponentName, "OMX.TI.JPEG.decode")) {
542        OMX_COLOR_FORMATTYPE format =
543            OMX_COLOR_Format32bitARGB8888;
544            // OMX_COLOR_FormatYUV420PackedPlanar;
545            // OMX_COLOR_FormatCbYCrY;
546            // OMX_COLOR_FormatYUV411Planar;
547
548        int32_t width, height;
549        bool success = meta->findInt32(kKeyWidth, &width);
550        success = success && meta->findInt32(kKeyHeight, &height);
551
552        int32_t compressedSize;
553        success = success && meta->findInt32(
554                kKeyMaxInputSize, &compressedSize);
555
556        CHECK(success);
557        CHECK(compressedSize > 0);
558
559        setImageOutputFormat(format, width, height);
560        setJPEGInputFormat(width, height, (OMX_U32)compressedSize);
561    }
562
563    int32_t maxInputSize;
564    if (meta->findInt32(kKeyMaxInputSize, &maxInputSize)) {
565        setMinBufferSize(kPortIndexInput, (OMX_U32)maxInputSize);
566    }
567
568    if (!strcmp(mComponentName, "OMX.TI.AMR.encode")
569        || !strcmp(mComponentName, "OMX.TI.WBAMR.encode")) {
570        setMinBufferSize(kPortIndexOutput, 8192);  // XXX
571    }
572
573    initOutputFormat(meta);
574
575    return OK;
576}
577
578void OMXCodec::setMinBufferSize(OMX_U32 portIndex, OMX_U32 size) {
579    OMX_PARAM_PORTDEFINITIONTYPE def;
580    InitOMXParams(&def);
581    def.nPortIndex = portIndex;
582
583    status_t err = mOMX->getParameter(
584            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
585    CHECK_EQ(err, OK);
586
587    if ((portIndex == kPortIndexInput && (mQuirks & kInputBufferSizesAreBogus))
588        || (def.nBufferSize < size)) {
589        def.nBufferSize = size;
590    }
591
592    err = mOMX->setParameter(
593            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
594    CHECK_EQ(err, OK);
595
596    err = mOMX->getParameter(
597            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
598    CHECK_EQ(err, OK);
599
600    // Make sure the setting actually stuck.
601    if (portIndex == kPortIndexInput
602            && (mQuirks & kInputBufferSizesAreBogus)) {
603        CHECK_EQ(def.nBufferSize, size);
604    } else {
605        CHECK(def.nBufferSize >= size);
606    }
607}
608
609status_t OMXCodec::setVideoPortFormatType(
610        OMX_U32 portIndex,
611        OMX_VIDEO_CODINGTYPE compressionFormat,
612        OMX_COLOR_FORMATTYPE colorFormat) {
613    OMX_VIDEO_PARAM_PORTFORMATTYPE format;
614    InitOMXParams(&format);
615    format.nPortIndex = portIndex;
616    format.nIndex = 0;
617    bool found = false;
618
619    OMX_U32 index = 0;
620    for (;;) {
621        format.nIndex = index;
622        status_t err = mOMX->getParameter(
623                mNode, OMX_IndexParamVideoPortFormat,
624                &format, sizeof(format));
625
626        if (err != OK) {
627            return err;
628        }
629
630        // The following assertion is violated by TI's video decoder.
631        // CHECK_EQ(format.nIndex, index);
632
633#if 1
634        CODEC_LOGV("portIndex: %ld, index: %ld, eCompressionFormat=%d eColorFormat=%d",
635             portIndex,
636             index, format.eCompressionFormat, format.eColorFormat);
637#endif
638
639        if (!strcmp("OMX.TI.Video.encoder", mComponentName)) {
640            if (portIndex == kPortIndexInput
641                    && colorFormat == format.eColorFormat) {
642                // eCompressionFormat does not seem right.
643                found = true;
644                break;
645            }
646            if (portIndex == kPortIndexOutput
647                    && compressionFormat == format.eCompressionFormat) {
648                // eColorFormat does not seem right.
649                found = true;
650                break;
651            }
652        }
653
654        if (format.eCompressionFormat == compressionFormat
655            && format.eColorFormat == colorFormat) {
656            found = true;
657            break;
658        }
659
660        ++index;
661    }
662
663    if (!found) {
664        return UNKNOWN_ERROR;
665    }
666
667    CODEC_LOGV("found a match.");
668    status_t err = mOMX->setParameter(
669            mNode, OMX_IndexParamVideoPortFormat,
670            &format, sizeof(format));
671
672    return err;
673}
674
675static size_t getFrameSize(
676        OMX_COLOR_FORMATTYPE colorFormat, int32_t width, int32_t height) {
677    switch (colorFormat) {
678        case OMX_COLOR_FormatYCbYCr:
679        case OMX_COLOR_FormatCbYCrY:
680            return width * height * 2;
681
682        case OMX_COLOR_FormatYUV420SemiPlanar:
683            return (width * height * 3) / 2;
684
685        default:
686            CHECK(!"Should not be here. Unsupported color format.");
687            break;
688    }
689}
690
691void OMXCodec::setVideoInputFormat(
692        const char *mime, OMX_U32 width, OMX_U32 height) {
693    CODEC_LOGV("setVideoInputFormat width=%ld, height=%ld", width, height);
694
695    OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused;
696    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
697        compressionFormat = OMX_VIDEO_CodingAVC;
698    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
699        compressionFormat = OMX_VIDEO_CodingMPEG4;
700    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
701        compressionFormat = OMX_VIDEO_CodingH263;
702    } else {
703        LOGE("Not a supported video mime type: %s", mime);
704        CHECK(!"Should not be here. Not a supported video mime type.");
705    }
706
707    OMX_COLOR_FORMATTYPE colorFormat = OMX_COLOR_FormatYUV420SemiPlanar;
708    if (!strcasecmp("OMX.TI.Video.encoder", mComponentName)) {
709        colorFormat = OMX_COLOR_FormatYCbYCr;
710    }
711
712    CHECK_EQ(setVideoPortFormatType(
713            kPortIndexInput, OMX_VIDEO_CodingUnused,
714            colorFormat), OK);
715
716    CHECK_EQ(setVideoPortFormatType(
717            kPortIndexOutput, compressionFormat, OMX_COLOR_FormatUnused),
718            OK);
719
720    OMX_PARAM_PORTDEFINITIONTYPE def;
721    InitOMXParams(&def);
722    def.nPortIndex = kPortIndexOutput;
723
724    OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
725
726    status_t err = mOMX->getParameter(
727            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
728
729    CHECK_EQ(err, OK);
730    CHECK_EQ(def.eDomain, OMX_PortDomainVideo);
731
732    video_def->nFrameWidth = width;
733    video_def->nFrameHeight = height;
734
735    video_def->eCompressionFormat = compressionFormat;
736    video_def->eColorFormat = OMX_COLOR_FormatUnused;
737
738    err = mOMX->setParameter(
739            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
740    CHECK_EQ(err, OK);
741
742    ////////////////////////////////////////////////////////////////////////////
743
744    InitOMXParams(&def);
745    def.nPortIndex = kPortIndexInput;
746
747    err = mOMX->getParameter(
748            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
749    CHECK_EQ(err, OK);
750
751    def.nBufferSize = getFrameSize(colorFormat, width, height);
752    CODEC_LOGV("Setting nBufferSize = %ld", def.nBufferSize);
753
754    CHECK_EQ(def.eDomain, OMX_PortDomainVideo);
755
756    video_def->nFrameWidth = width;
757    video_def->nFrameHeight = height;
758    video_def->eCompressionFormat = OMX_VIDEO_CodingUnused;
759    video_def->eColorFormat = colorFormat;
760
761    video_def->xFramerate = 24 << 16;  // XXX crucial!
762
763    err = mOMX->setParameter(
764            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
765    CHECK_EQ(err, OK);
766
767    switch (compressionFormat) {
768        case OMX_VIDEO_CodingMPEG4:
769        {
770            CHECK_EQ(setupMPEG4EncoderParameters(), OK);
771            break;
772        }
773
774        case OMX_VIDEO_CodingH263:
775            break;
776
777        case OMX_VIDEO_CodingAVC:
778        {
779            CHECK_EQ(setupAVCEncoderParameters(), OK);
780            break;
781        }
782
783        default:
784            CHECK(!"Support for this compressionFormat to be implemented.");
785            break;
786    }
787}
788
789status_t OMXCodec::setupMPEG4EncoderParameters() {
790    OMX_VIDEO_PARAM_MPEG4TYPE mpeg4type;
791    InitOMXParams(&mpeg4type);
792    mpeg4type.nPortIndex = kPortIndexOutput;
793
794    status_t err = mOMX->getParameter(
795            mNode, OMX_IndexParamVideoMpeg4, &mpeg4type, sizeof(mpeg4type));
796    CHECK_EQ(err, OK);
797
798    mpeg4type.nSliceHeaderSpacing = 0;
799    mpeg4type.bSVH = OMX_FALSE;
800    mpeg4type.bGov = OMX_FALSE;
801
802    mpeg4type.nAllowedPictureTypes =
803        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
804
805    mpeg4type.nPFrames = 23;
806    mpeg4type.nBFrames = 0;
807
808    mpeg4type.nIDCVLCThreshold = 0;
809    mpeg4type.bACPred = OMX_TRUE;
810    mpeg4type.nMaxPacketSize = 256;
811    mpeg4type.nTimeIncRes = 1000;
812    mpeg4type.nHeaderExtension = 0;
813    mpeg4type.bReversibleVLC = OMX_FALSE;
814
815    mpeg4type.eProfile = OMX_VIDEO_MPEG4ProfileCore;
816    mpeg4type.eLevel = OMX_VIDEO_MPEG4Level2;
817
818    err = mOMX->setParameter(
819            mNode, OMX_IndexParamVideoMpeg4, &mpeg4type, sizeof(mpeg4type));
820    CHECK_EQ(err, OK);
821
822    // ----------------
823
824    OMX_VIDEO_PARAM_BITRATETYPE bitrateType;
825    InitOMXParams(&bitrateType);
826    bitrateType.nPortIndex = kPortIndexOutput;
827
828    err = mOMX->getParameter(
829            mNode, OMX_IndexParamVideoBitrate,
830            &bitrateType, sizeof(bitrateType));
831    CHECK_EQ(err, OK);
832
833    bitrateType.eControlRate = OMX_Video_ControlRateVariable;
834    bitrateType.nTargetBitrate = 1000000;
835
836    err = mOMX->setParameter(
837            mNode, OMX_IndexParamVideoBitrate,
838            &bitrateType, sizeof(bitrateType));
839    CHECK_EQ(err, OK);
840
841    // ----------------
842
843    OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE errorCorrectionType;
844    InitOMXParams(&errorCorrectionType);
845    errorCorrectionType.nPortIndex = kPortIndexOutput;
846
847    err = mOMX->getParameter(
848            mNode, OMX_IndexParamVideoErrorCorrection,
849            &errorCorrectionType, sizeof(errorCorrectionType));
850    CHECK_EQ(err, OK);
851
852    errorCorrectionType.bEnableHEC = OMX_FALSE;
853    errorCorrectionType.bEnableResync = OMX_TRUE;
854    errorCorrectionType.nResynchMarkerSpacing = 256;
855    errorCorrectionType.bEnableDataPartitioning = OMX_FALSE;
856    errorCorrectionType.bEnableRVLC = OMX_FALSE;
857
858    err = mOMX->setParameter(
859            mNode, OMX_IndexParamVideoErrorCorrection,
860            &errorCorrectionType, sizeof(errorCorrectionType));
861    CHECK_EQ(err, OK);
862
863    return OK;
864}
865
866status_t OMXCodec::setupAVCEncoderParameters() {
867    OMX_VIDEO_PARAM_AVCTYPE h264type;
868    InitOMXParams(&h264type);
869    h264type.nPortIndex = kPortIndexOutput;
870
871    status_t err = mOMX->getParameter(
872            mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type));
873    CHECK_EQ(err, OK);
874
875    h264type.nAllowedPictureTypes =
876        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
877
878    h264type.nSliceHeaderSpacing = 0;
879    h264type.nBFrames = 0;
880    h264type.bUseHadamard = OMX_TRUE;
881    h264type.nRefFrames = 1;
882    h264type.nRefIdx10ActiveMinus1 = 0;
883    h264type.nRefIdx11ActiveMinus1 = 0;
884    h264type.bEnableUEP = OMX_FALSE;
885    h264type.bEnableFMO = OMX_FALSE;
886    h264type.bEnableASO = OMX_FALSE;
887    h264type.bEnableRS = OMX_FALSE;
888    h264type.eProfile = OMX_VIDEO_AVCProfileBaseline;
889    h264type.eLevel = OMX_VIDEO_AVCLevel1b;
890    h264type.bFrameMBsOnly = OMX_TRUE;
891    h264type.bMBAFF = OMX_FALSE;
892    h264type.bEntropyCodingCABAC = OMX_FALSE;
893    h264type.bWeightedPPrediction = OMX_FALSE;
894    h264type.bconstIpred = OMX_FALSE;
895    h264type.bDirect8x8Inference = OMX_FALSE;
896    h264type.bDirectSpatialTemporal = OMX_FALSE;
897    h264type.nCabacInitIdc = 0;
898    h264type.eLoopFilterMode = OMX_VIDEO_AVCLoopFilterEnable;
899
900    err = mOMX->setParameter(
901            mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type));
902    CHECK_EQ(err, OK);
903
904    OMX_VIDEO_PARAM_BITRATETYPE bitrateType;
905    InitOMXParams(&bitrateType);
906    bitrateType.nPortIndex = kPortIndexOutput;
907
908    err = mOMX->getParameter(
909            mNode, OMX_IndexParamVideoBitrate,
910            &bitrateType, sizeof(bitrateType));
911    CHECK_EQ(err, OK);
912
913    bitrateType.eControlRate = OMX_Video_ControlRateVariable;
914    bitrateType.nTargetBitrate = 1000000;
915
916    err = mOMX->setParameter(
917            mNode, OMX_IndexParamVideoBitrate,
918            &bitrateType, sizeof(bitrateType));
919    CHECK_EQ(err, OK);
920
921    return OK;
922}
923
924status_t OMXCodec::setVideoOutputFormat(
925        const char *mime, OMX_U32 width, OMX_U32 height) {
926    CODEC_LOGV("setVideoOutputFormat width=%ld, height=%ld", width, height);
927
928    OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused;
929    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
930        compressionFormat = OMX_VIDEO_CodingAVC;
931    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
932        compressionFormat = OMX_VIDEO_CodingMPEG4;
933    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
934        compressionFormat = OMX_VIDEO_CodingH263;
935    } else {
936        LOGE("Not a supported video mime type: %s", mime);
937        CHECK(!"Should not be here. Not a supported video mime type.");
938    }
939
940    status_t err = setVideoPortFormatType(
941            kPortIndexInput, compressionFormat, OMX_COLOR_FormatUnused);
942
943    if (err != OK) {
944        return err;
945    }
946
947#if 1
948    {
949        OMX_VIDEO_PARAM_PORTFORMATTYPE format;
950        InitOMXParams(&format);
951        format.nPortIndex = kPortIndexOutput;
952        format.nIndex = 0;
953
954        status_t err = mOMX->getParameter(
955                mNode, OMX_IndexParamVideoPortFormat,
956                &format, sizeof(format));
957        CHECK_EQ(err, OK);
958        CHECK_EQ(format.eCompressionFormat, OMX_VIDEO_CodingUnused);
959
960        static const int OMX_QCOM_COLOR_FormatYVU420SemiPlanar = 0x7FA30C00;
961
962        CHECK(format.eColorFormat == OMX_COLOR_FormatYUV420Planar
963               || format.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar
964               || format.eColorFormat == OMX_COLOR_FormatCbYCrY
965               || format.eColorFormat == OMX_QCOM_COLOR_FormatYVU420SemiPlanar);
966
967        err = mOMX->setParameter(
968                mNode, OMX_IndexParamVideoPortFormat,
969                &format, sizeof(format));
970
971        if (err != OK) {
972            return err;
973        }
974    }
975#endif
976
977    OMX_PARAM_PORTDEFINITIONTYPE def;
978    InitOMXParams(&def);
979    def.nPortIndex = kPortIndexInput;
980
981    OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
982
983    err = mOMX->getParameter(
984            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
985
986    CHECK_EQ(err, OK);
987
988#if 1
989    // XXX Need a (much) better heuristic to compute input buffer sizes.
990    const size_t X = 64 * 1024;
991    if (def.nBufferSize < X) {
992        def.nBufferSize = X;
993    }
994#endif
995
996    CHECK_EQ(def.eDomain, OMX_PortDomainVideo);
997
998    video_def->nFrameWidth = width;
999    video_def->nFrameHeight = height;
1000
1001    video_def->eCompressionFormat = compressionFormat;
1002    video_def->eColorFormat = OMX_COLOR_FormatUnused;
1003
1004    err = mOMX->setParameter(
1005            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1006
1007    if (err != OK) {
1008        return err;
1009    }
1010
1011    ////////////////////////////////////////////////////////////////////////////
1012
1013    InitOMXParams(&def);
1014    def.nPortIndex = kPortIndexOutput;
1015
1016    err = mOMX->getParameter(
1017            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1018    CHECK_EQ(err, OK);
1019    CHECK_EQ(def.eDomain, OMX_PortDomainVideo);
1020
1021#if 0
1022    def.nBufferSize =
1023        (((width + 15) & -16) * ((height + 15) & -16) * 3) / 2;  // YUV420
1024#endif
1025
1026    video_def->nFrameWidth = width;
1027    video_def->nFrameHeight = height;
1028
1029    err = mOMX->setParameter(
1030            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1031
1032    return err;
1033}
1034
1035OMXCodec::OMXCodec(
1036        const sp<IOMX> &omx, IOMX::node_id node, uint32_t quirks,
1037        bool isEncoder,
1038        const char *mime,
1039        const char *componentName,
1040        const sp<MediaSource> &source)
1041    : mOMX(omx),
1042      mOMXLivesLocally(omx->livesLocally(getpid())),
1043      mNode(node),
1044      mQuirks(quirks),
1045      mIsEncoder(isEncoder),
1046      mMIME(strdup(mime)),
1047      mComponentName(strdup(componentName)),
1048      mSource(source),
1049      mCodecSpecificDataIndex(0),
1050      mState(LOADED),
1051      mInitialBufferSubmit(true),
1052      mSignalledEOS(false),
1053      mNoMoreOutputData(false),
1054      mOutputPortSettingsHaveChanged(false),
1055      mSeekTimeUs(-1),
1056      mLeftOverBuffer(NULL) {
1057    mPortStatus[kPortIndexInput] = ENABLED;
1058    mPortStatus[kPortIndexOutput] = ENABLED;
1059
1060    setComponentRole();
1061}
1062
1063// static
1064void OMXCodec::setComponentRole(
1065        const sp<IOMX> &omx, IOMX::node_id node, bool isEncoder,
1066        const char *mime) {
1067    struct MimeToRole {
1068        const char *mime;
1069        const char *decoderRole;
1070        const char *encoderRole;
1071    };
1072
1073    static const MimeToRole kMimeToRole[] = {
1074        { MEDIA_MIMETYPE_AUDIO_MPEG,
1075            "audio_decoder.mp3", "audio_encoder.mp3" },
1076        { MEDIA_MIMETYPE_AUDIO_AMR_NB,
1077            "audio_decoder.amrnb", "audio_encoder.amrnb" },
1078        { MEDIA_MIMETYPE_AUDIO_AMR_WB,
1079            "audio_decoder.amrwb", "audio_encoder.amrwb" },
1080        { MEDIA_MIMETYPE_AUDIO_AAC,
1081            "audio_decoder.aac", "audio_encoder.aac" },
1082        { MEDIA_MIMETYPE_VIDEO_AVC,
1083            "video_decoder.avc", "video_encoder.avc" },
1084        { MEDIA_MIMETYPE_VIDEO_MPEG4,
1085            "video_decoder.mpeg4", "video_encoder.mpeg4" },
1086        { MEDIA_MIMETYPE_VIDEO_H263,
1087            "video_decoder.h263", "video_encoder.h263" },
1088    };
1089
1090    static const size_t kNumMimeToRole =
1091        sizeof(kMimeToRole) / sizeof(kMimeToRole[0]);
1092
1093    size_t i;
1094    for (i = 0; i < kNumMimeToRole; ++i) {
1095        if (!strcasecmp(mime, kMimeToRole[i].mime)) {
1096            break;
1097        }
1098    }
1099
1100    if (i == kNumMimeToRole) {
1101        return;
1102    }
1103
1104    const char *role =
1105        isEncoder ? kMimeToRole[i].encoderRole
1106                  : kMimeToRole[i].decoderRole;
1107
1108    if (role != NULL) {
1109        OMX_PARAM_COMPONENTROLETYPE roleParams;
1110        InitOMXParams(&roleParams);
1111
1112        strncpy((char *)roleParams.cRole,
1113                role, OMX_MAX_STRINGNAME_SIZE - 1);
1114
1115        roleParams.cRole[OMX_MAX_STRINGNAME_SIZE - 1] = '\0';
1116
1117        status_t err = omx->setParameter(
1118                node, OMX_IndexParamStandardComponentRole,
1119                &roleParams, sizeof(roleParams));
1120
1121        if (err != OK) {
1122            LOGW("Failed to set standard component role '%s'.", role);
1123        }
1124    }
1125}
1126
1127void OMXCodec::setComponentRole() {
1128    setComponentRole(mOMX, mNode, mIsEncoder, mMIME);
1129}
1130
1131OMXCodec::~OMXCodec() {
1132    CHECK(mState == LOADED || mState == ERROR);
1133
1134    status_t err = mOMX->freeNode(mNode);
1135    CHECK_EQ(err, OK);
1136
1137    mNode = NULL;
1138    setState(DEAD);
1139
1140    clearCodecSpecificData();
1141
1142    free(mComponentName);
1143    mComponentName = NULL;
1144
1145    free(mMIME);
1146    mMIME = NULL;
1147}
1148
1149status_t OMXCodec::init() {
1150    // mLock is held.
1151
1152    CHECK_EQ(mState, LOADED);
1153
1154    status_t err;
1155    if (!(mQuirks & kRequiresLoadedToIdleAfterAllocation)) {
1156        err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
1157        CHECK_EQ(err, OK);
1158        setState(LOADED_TO_IDLE);
1159    }
1160
1161    err = allocateBuffers();
1162    CHECK_EQ(err, OK);
1163
1164    if (mQuirks & kRequiresLoadedToIdleAfterAllocation) {
1165        err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
1166        CHECK_EQ(err, OK);
1167
1168        setState(LOADED_TO_IDLE);
1169    }
1170
1171    while (mState != EXECUTING && mState != ERROR) {
1172        mAsyncCompletion.wait(mLock);
1173    }
1174
1175    return mState == ERROR ? UNKNOWN_ERROR : OK;
1176}
1177
1178// static
1179bool OMXCodec::isIntermediateState(State state) {
1180    return state == LOADED_TO_IDLE
1181        || state == IDLE_TO_EXECUTING
1182        || state == EXECUTING_TO_IDLE
1183        || state == IDLE_TO_LOADED
1184        || state == RECONFIGURING;
1185}
1186
1187status_t OMXCodec::allocateBuffers() {
1188    status_t err = allocateBuffersOnPort(kPortIndexInput);
1189
1190    if (err != OK) {
1191        return err;
1192    }
1193
1194    return allocateBuffersOnPort(kPortIndexOutput);
1195}
1196
1197status_t OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) {
1198    OMX_PARAM_PORTDEFINITIONTYPE def;
1199    InitOMXParams(&def);
1200    def.nPortIndex = portIndex;
1201
1202    status_t err = mOMX->getParameter(
1203            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1204
1205    if (err != OK) {
1206        return err;
1207    }
1208
1209    size_t totalSize = def.nBufferCountActual * def.nBufferSize;
1210    mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec");
1211
1212    for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
1213        sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize);
1214        CHECK(mem.get() != NULL);
1215
1216        BufferInfo info;
1217        info.mData = NULL;
1218        info.mSize = def.nBufferSize;
1219
1220        IOMX::buffer_id buffer;
1221        if (portIndex == kPortIndexInput
1222                && (mQuirks & kRequiresAllocateBufferOnInputPorts)) {
1223            if (mOMXLivesLocally) {
1224                mem.clear();
1225
1226                err = mOMX->allocateBuffer(
1227                        mNode, portIndex, def.nBufferSize, &buffer,
1228                        &info.mData);
1229            } else {
1230                err = mOMX->allocateBufferWithBackup(
1231                        mNode, portIndex, mem, &buffer);
1232            }
1233        } else if (portIndex == kPortIndexOutput
1234                && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) {
1235            if (mOMXLivesLocally) {
1236                mem.clear();
1237
1238                err = mOMX->allocateBuffer(
1239                        mNode, portIndex, def.nBufferSize, &buffer,
1240                        &info.mData);
1241            } else {
1242                err = mOMX->allocateBufferWithBackup(
1243                        mNode, portIndex, mem, &buffer);
1244            }
1245        } else {
1246            err = mOMX->useBuffer(mNode, portIndex, mem, &buffer);
1247        }
1248
1249        if (err != OK) {
1250            LOGE("allocate_buffer_with_backup failed");
1251            return err;
1252        }
1253
1254        if (mem != NULL) {
1255            info.mData = mem->pointer();
1256        }
1257
1258        info.mBuffer = buffer;
1259        info.mOwnedByComponent = false;
1260        info.mMem = mem;
1261        info.mMediaBuffer = NULL;
1262
1263        if (portIndex == kPortIndexOutput) {
1264            if (!(mOMXLivesLocally
1265                        && (mQuirks & kRequiresAllocateBufferOnOutputPorts)
1266                        && (mQuirks & kDefersOutputBufferAllocation))) {
1267                // If the node does not fill in the buffer ptr at this time,
1268                // we will defer creating the MediaBuffer until receiving
1269                // the first FILL_BUFFER_DONE notification instead.
1270                info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize);
1271                info.mMediaBuffer->setObserver(this);
1272            }
1273        }
1274
1275        mPortBuffers[portIndex].push(info);
1276
1277        CODEC_LOGV("allocated buffer %p on %s port", buffer,
1278             portIndex == kPortIndexInput ? "input" : "output");
1279    }
1280
1281    // dumpPortStatus(portIndex);
1282
1283    return OK;
1284}
1285
1286void OMXCodec::on_message(const omx_message &msg) {
1287    Mutex::Autolock autoLock(mLock);
1288
1289    switch (msg.type) {
1290        case omx_message::EVENT:
1291        {
1292            onEvent(
1293                 msg.u.event_data.event, msg.u.event_data.data1,
1294                 msg.u.event_data.data2);
1295
1296            break;
1297        }
1298
1299        case omx_message::EMPTY_BUFFER_DONE:
1300        {
1301            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
1302
1303            CODEC_LOGV("EMPTY_BUFFER_DONE(buffer: %p)", buffer);
1304
1305            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
1306            size_t i = 0;
1307            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
1308                ++i;
1309            }
1310
1311            CHECK(i < buffers->size());
1312            if (!(*buffers)[i].mOwnedByComponent) {
1313                LOGW("We already own input buffer %p, yet received "
1314                     "an EMPTY_BUFFER_DONE.", buffer);
1315            }
1316
1317            buffers->editItemAt(i).mOwnedByComponent = false;
1318
1319            if (mPortStatus[kPortIndexInput] == DISABLING) {
1320                CODEC_LOGV("Port is disabled, freeing buffer %p", buffer);
1321
1322                status_t err =
1323                    mOMX->freeBuffer(mNode, kPortIndexInput, buffer);
1324                CHECK_EQ(err, OK);
1325
1326                buffers->removeAt(i);
1327            } else if (mState != ERROR
1328                    && mPortStatus[kPortIndexInput] != SHUTTING_DOWN) {
1329                CHECK_EQ(mPortStatus[kPortIndexInput], ENABLED);
1330                drainInputBuffer(&buffers->editItemAt(i));
1331            }
1332            break;
1333        }
1334
1335        case omx_message::FILL_BUFFER_DONE:
1336        {
1337            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
1338            OMX_U32 flags = msg.u.extended_buffer_data.flags;
1339
1340            CODEC_LOGV("FILL_BUFFER_DONE(buffer: %p, size: %ld, flags: 0x%08lx, timestamp: %lld us (%.2f secs))",
1341                 buffer,
1342                 msg.u.extended_buffer_data.range_length,
1343                 flags,
1344                 msg.u.extended_buffer_data.timestamp,
1345                 msg.u.extended_buffer_data.timestamp / 1E6);
1346
1347            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
1348            size_t i = 0;
1349            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
1350                ++i;
1351            }
1352
1353            CHECK(i < buffers->size());
1354            BufferInfo *info = &buffers->editItemAt(i);
1355
1356            if (!info->mOwnedByComponent) {
1357                LOGW("We already own output buffer %p, yet received "
1358                     "a FILL_BUFFER_DONE.", buffer);
1359            }
1360
1361            info->mOwnedByComponent = false;
1362
1363            if (mPortStatus[kPortIndexOutput] == DISABLING) {
1364                CODEC_LOGV("Port is disabled, freeing buffer %p", buffer);
1365
1366                status_t err =
1367                    mOMX->freeBuffer(mNode, kPortIndexOutput, buffer);
1368                CHECK_EQ(err, OK);
1369
1370                buffers->removeAt(i);
1371#if 0
1372            } else if (mPortStatus[kPortIndexOutput] == ENABLED
1373                       && (flags & OMX_BUFFERFLAG_EOS)) {
1374                CODEC_LOGV("No more output data.");
1375                mNoMoreOutputData = true;
1376                mBufferFilled.signal();
1377#endif
1378            } else if (mPortStatus[kPortIndexOutput] != SHUTTING_DOWN) {
1379                CHECK_EQ(mPortStatus[kPortIndexOutput], ENABLED);
1380
1381                if (info->mMediaBuffer == NULL) {
1382                    CHECK(mOMXLivesLocally);
1383                    CHECK(mQuirks & kRequiresAllocateBufferOnOutputPorts);
1384                    CHECK(mQuirks & kDefersOutputBufferAllocation);
1385
1386                    // The qcom video decoders on Nexus don't actually allocate
1387                    // output buffer memory on a call to OMX_AllocateBuffer
1388                    // the "pBuffer" member of the OMX_BUFFERHEADERTYPE
1389                    // structure is only filled in later.
1390
1391                    info->mMediaBuffer = new MediaBuffer(
1392                            msg.u.extended_buffer_data.data_ptr,
1393                            info->mSize);
1394                    info->mMediaBuffer->setObserver(this);
1395                }
1396
1397                MediaBuffer *buffer = info->mMediaBuffer;
1398
1399                buffer->set_range(
1400                        msg.u.extended_buffer_data.range_offset,
1401                        msg.u.extended_buffer_data.range_length);
1402
1403                buffer->meta_data()->clear();
1404
1405                buffer->meta_data()->setInt64(
1406                        kKeyTime, msg.u.extended_buffer_data.timestamp);
1407
1408                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_SYNCFRAME) {
1409                    buffer->meta_data()->setInt32(kKeyIsSyncFrame, true);
1410                }
1411                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_CODECCONFIG) {
1412                    buffer->meta_data()->setInt32(kKeyIsCodecConfig, true);
1413                }
1414
1415                buffer->meta_data()->setPointer(
1416                        kKeyPlatformPrivate,
1417                        msg.u.extended_buffer_data.platform_private);
1418
1419                buffer->meta_data()->setPointer(
1420                        kKeyBufferID,
1421                        msg.u.extended_buffer_data.buffer);
1422
1423                mFilledBuffers.push_back(i);
1424                mBufferFilled.signal();
1425
1426                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_EOS) {
1427                    CODEC_LOGV("No more output data.");
1428                    mNoMoreOutputData = true;
1429                }
1430            }
1431
1432            break;
1433        }
1434
1435        default:
1436        {
1437            CHECK(!"should not be here.");
1438            break;
1439        }
1440    }
1441}
1442
1443void OMXCodec::onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) {
1444    switch (event) {
1445        case OMX_EventCmdComplete:
1446        {
1447            onCmdComplete((OMX_COMMANDTYPE)data1, data2);
1448            break;
1449        }
1450
1451        case OMX_EventError:
1452        {
1453            LOGE("ERROR(0x%08lx, %ld)", data1, data2);
1454
1455            setState(ERROR);
1456            break;
1457        }
1458
1459        case OMX_EventPortSettingsChanged:
1460        {
1461            onPortSettingsChanged(data1);
1462            break;
1463        }
1464
1465#if 0
1466        case OMX_EventBufferFlag:
1467        {
1468            CODEC_LOGV("EVENT_BUFFER_FLAG(%ld)", data1);
1469
1470            if (data1 == kPortIndexOutput) {
1471                mNoMoreOutputData = true;
1472            }
1473            break;
1474        }
1475#endif
1476
1477        default:
1478        {
1479            CODEC_LOGV("EVENT(%d, %ld, %ld)", event, data1, data2);
1480            break;
1481        }
1482    }
1483}
1484
1485// Has the format changed in any way that the client would have to be aware of?
1486static bool formatHasNotablyChanged(
1487        const sp<MetaData> &from, const sp<MetaData> &to) {
1488    if (from.get() == NULL && to.get() == NULL) {
1489        return false;
1490    }
1491
1492    if ((from.get() == NULL && to.get() != NULL)
1493        || (from.get() != NULL && to.get() == NULL)) {
1494        return true;
1495    }
1496
1497    const char *mime_from, *mime_to;
1498    CHECK(from->findCString(kKeyMIMEType, &mime_from));
1499    CHECK(to->findCString(kKeyMIMEType, &mime_to));
1500
1501    if (strcasecmp(mime_from, mime_to)) {
1502        return true;
1503    }
1504
1505    if (!strcasecmp(mime_from, MEDIA_MIMETYPE_VIDEO_RAW)) {
1506        int32_t colorFormat_from, colorFormat_to;
1507        CHECK(from->findInt32(kKeyColorFormat, &colorFormat_from));
1508        CHECK(to->findInt32(kKeyColorFormat, &colorFormat_to));
1509
1510        if (colorFormat_from != colorFormat_to) {
1511            return true;
1512        }
1513
1514        int32_t width_from, width_to;
1515        CHECK(from->findInt32(kKeyWidth, &width_from));
1516        CHECK(to->findInt32(kKeyWidth, &width_to));
1517
1518        if (width_from != width_to) {
1519            return true;
1520        }
1521
1522        int32_t height_from, height_to;
1523        CHECK(from->findInt32(kKeyHeight, &height_from));
1524        CHECK(to->findInt32(kKeyHeight, &height_to));
1525
1526        if (height_from != height_to) {
1527            return true;
1528        }
1529    } else if (!strcasecmp(mime_from, MEDIA_MIMETYPE_AUDIO_RAW)) {
1530        int32_t numChannels_from, numChannels_to;
1531        CHECK(from->findInt32(kKeyChannelCount, &numChannels_from));
1532        CHECK(to->findInt32(kKeyChannelCount, &numChannels_to));
1533
1534        if (numChannels_from != numChannels_to) {
1535            return true;
1536        }
1537
1538        int32_t sampleRate_from, sampleRate_to;
1539        CHECK(from->findInt32(kKeySampleRate, &sampleRate_from));
1540        CHECK(to->findInt32(kKeySampleRate, &sampleRate_to));
1541
1542        if (sampleRate_from != sampleRate_to) {
1543            return true;
1544        }
1545    }
1546
1547    return false;
1548}
1549
1550void OMXCodec::onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data) {
1551    switch (cmd) {
1552        case OMX_CommandStateSet:
1553        {
1554            onStateChange((OMX_STATETYPE)data);
1555            break;
1556        }
1557
1558        case OMX_CommandPortDisable:
1559        {
1560            OMX_U32 portIndex = data;
1561            CODEC_LOGV("PORT_DISABLED(%ld)", portIndex);
1562
1563            CHECK(mState == EXECUTING || mState == RECONFIGURING);
1564            CHECK_EQ(mPortStatus[portIndex], DISABLING);
1565            CHECK_EQ(mPortBuffers[portIndex].size(), 0);
1566
1567            mPortStatus[portIndex] = DISABLED;
1568
1569            if (mState == RECONFIGURING) {
1570                CHECK_EQ(portIndex, kPortIndexOutput);
1571
1572                sp<MetaData> oldOutputFormat = mOutputFormat;
1573                initOutputFormat(mSource->getFormat());
1574
1575                // Don't notify clients if the output port settings change
1576                // wasn't of importance to them, i.e. it may be that just the
1577                // number of buffers has changed and nothing else.
1578                mOutputPortSettingsHaveChanged =
1579                    formatHasNotablyChanged(oldOutputFormat, mOutputFormat);
1580
1581                enablePortAsync(portIndex);
1582
1583                status_t err = allocateBuffersOnPort(portIndex);
1584                CHECK_EQ(err, OK);
1585            }
1586            break;
1587        }
1588
1589        case OMX_CommandPortEnable:
1590        {
1591            OMX_U32 portIndex = data;
1592            CODEC_LOGV("PORT_ENABLED(%ld)", portIndex);
1593
1594            CHECK(mState == EXECUTING || mState == RECONFIGURING);
1595            CHECK_EQ(mPortStatus[portIndex], ENABLING);
1596
1597            mPortStatus[portIndex] = ENABLED;
1598
1599            if (mState == RECONFIGURING) {
1600                CHECK_EQ(portIndex, kPortIndexOutput);
1601
1602                setState(EXECUTING);
1603
1604                fillOutputBuffers();
1605            }
1606            break;
1607        }
1608
1609        case OMX_CommandFlush:
1610        {
1611            OMX_U32 portIndex = data;
1612
1613            CODEC_LOGV("FLUSH_DONE(%ld)", portIndex);
1614
1615            CHECK_EQ(mPortStatus[portIndex], SHUTTING_DOWN);
1616            mPortStatus[portIndex] = ENABLED;
1617
1618            CHECK_EQ(countBuffersWeOwn(mPortBuffers[portIndex]),
1619                     mPortBuffers[portIndex].size());
1620
1621            if (mState == RECONFIGURING) {
1622                CHECK_EQ(portIndex, kPortIndexOutput);
1623
1624                disablePortAsync(portIndex);
1625            } else if (mState == EXECUTING_TO_IDLE) {
1626                if (mPortStatus[kPortIndexInput] == ENABLED
1627                    && mPortStatus[kPortIndexOutput] == ENABLED) {
1628                    CODEC_LOGV("Finished flushing both ports, now completing "
1629                         "transition from EXECUTING to IDLE.");
1630
1631                    mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
1632                    mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
1633
1634                    status_t err =
1635                        mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
1636                    CHECK_EQ(err, OK);
1637                }
1638            } else {
1639                // We're flushing both ports in preparation for seeking.
1640
1641                if (mPortStatus[kPortIndexInput] == ENABLED
1642                    && mPortStatus[kPortIndexOutput] == ENABLED) {
1643                    CODEC_LOGV("Finished flushing both ports, now continuing from"
1644                         " seek-time.");
1645
1646                    drainInputBuffers();
1647                    fillOutputBuffers();
1648                }
1649            }
1650
1651            break;
1652        }
1653
1654        default:
1655        {
1656            CODEC_LOGV("CMD_COMPLETE(%d, %ld)", cmd, data);
1657            break;
1658        }
1659    }
1660}
1661
1662void OMXCodec::onStateChange(OMX_STATETYPE newState) {
1663    CODEC_LOGV("onStateChange %d", newState);
1664
1665    switch (newState) {
1666        case OMX_StateIdle:
1667        {
1668            CODEC_LOGV("Now Idle.");
1669            if (mState == LOADED_TO_IDLE) {
1670                status_t err = mOMX->sendCommand(
1671                        mNode, OMX_CommandStateSet, OMX_StateExecuting);
1672
1673                CHECK_EQ(err, OK);
1674
1675                setState(IDLE_TO_EXECUTING);
1676            } else {
1677                CHECK_EQ(mState, EXECUTING_TO_IDLE);
1678
1679                CHECK_EQ(
1680                    countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
1681                    mPortBuffers[kPortIndexInput].size());
1682
1683                CHECK_EQ(
1684                    countBuffersWeOwn(mPortBuffers[kPortIndexOutput]),
1685                    mPortBuffers[kPortIndexOutput].size());
1686
1687                status_t err = mOMX->sendCommand(
1688                        mNode, OMX_CommandStateSet, OMX_StateLoaded);
1689
1690                CHECK_EQ(err, OK);
1691
1692                err = freeBuffersOnPort(kPortIndexInput);
1693                CHECK_EQ(err, OK);
1694
1695                err = freeBuffersOnPort(kPortIndexOutput);
1696                CHECK_EQ(err, OK);
1697
1698                mPortStatus[kPortIndexInput] = ENABLED;
1699                mPortStatus[kPortIndexOutput] = ENABLED;
1700
1701                setState(IDLE_TO_LOADED);
1702            }
1703            break;
1704        }
1705
1706        case OMX_StateExecuting:
1707        {
1708            CHECK_EQ(mState, IDLE_TO_EXECUTING);
1709
1710            CODEC_LOGV("Now Executing.");
1711
1712            setState(EXECUTING);
1713
1714            // Buffers will be submitted to the component in the first
1715            // call to OMXCodec::read as mInitialBufferSubmit is true at
1716            // this point. This ensures that this on_message call returns,
1717            // releases the lock and ::init can notice the state change and
1718            // itself return.
1719            break;
1720        }
1721
1722        case OMX_StateLoaded:
1723        {
1724            CHECK_EQ(mState, IDLE_TO_LOADED);
1725
1726            CODEC_LOGV("Now Loaded.");
1727
1728            setState(LOADED);
1729            break;
1730        }
1731
1732        case OMX_StateInvalid:
1733        {
1734            setState(ERROR);
1735            break;
1736        }
1737
1738        default:
1739        {
1740            CHECK(!"should not be here.");
1741            break;
1742        }
1743    }
1744}
1745
1746// static
1747size_t OMXCodec::countBuffersWeOwn(const Vector<BufferInfo> &buffers) {
1748    size_t n = 0;
1749    for (size_t i = 0; i < buffers.size(); ++i) {
1750        if (!buffers[i].mOwnedByComponent) {
1751            ++n;
1752        }
1753    }
1754
1755    return n;
1756}
1757
1758status_t OMXCodec::freeBuffersOnPort(
1759        OMX_U32 portIndex, bool onlyThoseWeOwn) {
1760    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
1761
1762    status_t stickyErr = OK;
1763
1764    for (size_t i = buffers->size(); i-- > 0;) {
1765        BufferInfo *info = &buffers->editItemAt(i);
1766
1767        if (onlyThoseWeOwn && info->mOwnedByComponent) {
1768            continue;
1769        }
1770
1771        CHECK_EQ(info->mOwnedByComponent, false);
1772
1773        CODEC_LOGV("freeing buffer %p on port %ld", info->mBuffer, portIndex);
1774
1775        status_t err =
1776            mOMX->freeBuffer(mNode, portIndex, info->mBuffer);
1777
1778        if (err != OK) {
1779            stickyErr = err;
1780        }
1781
1782        if (info->mMediaBuffer != NULL) {
1783            info->mMediaBuffer->setObserver(NULL);
1784
1785            // Make sure nobody but us owns this buffer at this point.
1786            CHECK_EQ(info->mMediaBuffer->refcount(), 0);
1787
1788            info->mMediaBuffer->release();
1789        }
1790
1791        buffers->removeAt(i);
1792    }
1793
1794    CHECK(onlyThoseWeOwn || buffers->isEmpty());
1795
1796    return stickyErr;
1797}
1798
1799void OMXCodec::onPortSettingsChanged(OMX_U32 portIndex) {
1800    CODEC_LOGV("PORT_SETTINGS_CHANGED(%ld)", portIndex);
1801
1802    CHECK_EQ(mState, EXECUTING);
1803    CHECK_EQ(portIndex, kPortIndexOutput);
1804    setState(RECONFIGURING);
1805
1806    if (mQuirks & kNeedsFlushBeforeDisable) {
1807        if (!flushPortAsync(portIndex)) {
1808            onCmdComplete(OMX_CommandFlush, portIndex);
1809        }
1810    } else {
1811        disablePortAsync(portIndex);
1812    }
1813}
1814
1815bool OMXCodec::flushPortAsync(OMX_U32 portIndex) {
1816    CHECK(mState == EXECUTING || mState == RECONFIGURING
1817            || mState == EXECUTING_TO_IDLE);
1818
1819    CODEC_LOGV("flushPortAsync(%ld): we own %d out of %d buffers already.",
1820         portIndex, countBuffersWeOwn(mPortBuffers[portIndex]),
1821         mPortBuffers[portIndex].size());
1822
1823    CHECK_EQ(mPortStatus[portIndex], ENABLED);
1824    mPortStatus[portIndex] = SHUTTING_DOWN;
1825
1826    if ((mQuirks & kRequiresFlushCompleteEmulation)
1827        && countBuffersWeOwn(mPortBuffers[portIndex])
1828                == mPortBuffers[portIndex].size()) {
1829        // No flush is necessary and this component fails to send a
1830        // flush-complete event in this case.
1831
1832        return false;
1833    }
1834
1835    status_t err =
1836        mOMX->sendCommand(mNode, OMX_CommandFlush, portIndex);
1837    CHECK_EQ(err, OK);
1838
1839    return true;
1840}
1841
1842void OMXCodec::disablePortAsync(OMX_U32 portIndex) {
1843    CHECK(mState == EXECUTING || mState == RECONFIGURING);
1844
1845    CHECK_EQ(mPortStatus[portIndex], ENABLED);
1846    mPortStatus[portIndex] = DISABLING;
1847
1848    status_t err =
1849        mOMX->sendCommand(mNode, OMX_CommandPortDisable, portIndex);
1850    CHECK_EQ(err, OK);
1851
1852    freeBuffersOnPort(portIndex, true);
1853}
1854
1855void OMXCodec::enablePortAsync(OMX_U32 portIndex) {
1856    CHECK(mState == EXECUTING || mState == RECONFIGURING);
1857
1858    CHECK_EQ(mPortStatus[portIndex], DISABLED);
1859    mPortStatus[portIndex] = ENABLING;
1860
1861    status_t err =
1862        mOMX->sendCommand(mNode, OMX_CommandPortEnable, portIndex);
1863    CHECK_EQ(err, OK);
1864}
1865
1866void OMXCodec::fillOutputBuffers() {
1867    CHECK_EQ(mState, EXECUTING);
1868
1869    // This is a workaround for some decoders not properly reporting
1870    // end-of-output-stream. If we own all input buffers and also own
1871    // all output buffers and we already signalled end-of-input-stream,
1872    // the end-of-output-stream is implied.
1873    if (mSignalledEOS
1874            && countBuffersWeOwn(mPortBuffers[kPortIndexInput])
1875                == mPortBuffers[kPortIndexInput].size()
1876            && countBuffersWeOwn(mPortBuffers[kPortIndexOutput])
1877                == mPortBuffers[kPortIndexOutput].size()) {
1878        mNoMoreOutputData = true;
1879        mBufferFilled.signal();
1880
1881        return;
1882    }
1883
1884    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
1885    for (size_t i = 0; i < buffers->size(); ++i) {
1886        fillOutputBuffer(&buffers->editItemAt(i));
1887    }
1888}
1889
1890void OMXCodec::drainInputBuffers() {
1891    CHECK(mState == EXECUTING || mState == RECONFIGURING);
1892
1893    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
1894    for (size_t i = 0; i < buffers->size(); ++i) {
1895        drainInputBuffer(&buffers->editItemAt(i));
1896    }
1897}
1898
1899void OMXCodec::drainInputBuffer(BufferInfo *info) {
1900    CHECK_EQ(info->mOwnedByComponent, false);
1901
1902    if (mSignalledEOS) {
1903        return;
1904    }
1905
1906    if (mCodecSpecificDataIndex < mCodecSpecificData.size()) {
1907        const CodecSpecificData *specific =
1908            mCodecSpecificData[mCodecSpecificDataIndex];
1909
1910        size_t size = specific->mSize;
1911
1912        if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mMIME)
1913                && !(mQuirks & kWantsNALFragments)) {
1914            static const uint8_t kNALStartCode[4] =
1915                    { 0x00, 0x00, 0x00, 0x01 };
1916
1917            CHECK(info->mSize >= specific->mSize + 4);
1918
1919            size += 4;
1920
1921            memcpy(info->mData, kNALStartCode, 4);
1922            memcpy((uint8_t *)info->mData + 4,
1923                   specific->mData, specific->mSize);
1924        } else {
1925            CHECK(info->mSize >= specific->mSize);
1926            memcpy(info->mData, specific->mData, specific->mSize);
1927        }
1928
1929        mNoMoreOutputData = false;
1930
1931        CODEC_LOGV("calling emptyBuffer with codec specific data");
1932
1933        status_t err = mOMX->emptyBuffer(
1934                mNode, info->mBuffer, 0, size,
1935                OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG,
1936                0);
1937        CHECK_EQ(err, OK);
1938
1939        info->mOwnedByComponent = true;
1940
1941        ++mCodecSpecificDataIndex;
1942        return;
1943    }
1944
1945    status_t err;
1946
1947    bool signalEOS = false;
1948    int64_t timestampUs = 0;
1949
1950    size_t offset = 0;
1951    int32_t n = 0;
1952    for (;;) {
1953        MediaBuffer *srcBuffer;
1954        if (mSeekTimeUs >= 0) {
1955            if (mLeftOverBuffer) {
1956                mLeftOverBuffer->release();
1957                mLeftOverBuffer = NULL;
1958            }
1959
1960            MediaSource::ReadOptions options;
1961            options.setSeekTo(mSeekTimeUs);
1962
1963            mSeekTimeUs = -1;
1964            mBufferFilled.signal();
1965
1966            err = mSource->read(&srcBuffer, &options);
1967        } else if (mLeftOverBuffer) {
1968            srcBuffer = mLeftOverBuffer;
1969            mLeftOverBuffer = NULL;
1970
1971            err = OK;
1972        } else {
1973            err = mSource->read(&srcBuffer);
1974        }
1975
1976        if (err != OK) {
1977            signalEOS = true;
1978            mFinalStatus = err;
1979            mSignalledEOS = true;
1980            break;
1981        }
1982
1983        size_t remainingBytes = info->mSize - offset;
1984
1985        if (srcBuffer->range_length() > remainingBytes) {
1986            if (offset == 0) {
1987                CODEC_LOGE(
1988                     "Codec's input buffers are too small to accomodate "
1989                     "buffer read from source (info->mSize = %d, srcLength = %d)",
1990                     info->mSize, srcBuffer->range_length());
1991
1992                srcBuffer->release();
1993                srcBuffer = NULL;
1994
1995                setState(ERROR);
1996                return;
1997            }
1998
1999            mLeftOverBuffer = srcBuffer;
2000            break;
2001        }
2002
2003        memcpy((uint8_t *)info->mData + offset,
2004               (const uint8_t *)srcBuffer->data() + srcBuffer->range_offset(),
2005               srcBuffer->range_length());
2006
2007        int64_t lastBufferTimeUs;
2008        CHECK(srcBuffer->meta_data()->findInt64(kKeyTime, &lastBufferTimeUs));
2009        CHECK(timestampUs >= 0);
2010
2011        if (offset == 0) {
2012            timestampUs = lastBufferTimeUs;
2013        }
2014
2015        offset += srcBuffer->range_length();
2016
2017        srcBuffer->release();
2018        srcBuffer = NULL;
2019
2020        ++n;
2021
2022        if (!(mQuirks & kSupportsMultipleFramesPerInputBuffer)) {
2023            break;
2024        }
2025
2026        int64_t coalescedDurationUs = lastBufferTimeUs - timestampUs;
2027
2028        if (coalescedDurationUs > 250000ll) {
2029            // Don't coalesce more than 250ms worth of encoded data at once.
2030            break;
2031        }
2032    }
2033
2034    if (n > 1) {
2035        LOGV("coalesced %d frames into one input buffer", n);
2036    }
2037
2038    OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME;
2039
2040    if (signalEOS) {
2041        flags |= OMX_BUFFERFLAG_EOS;
2042    } else {
2043        mNoMoreOutputData = false;
2044    }
2045
2046    CODEC_LOGV("Calling emptyBuffer on buffer %p (length %d), "
2047               "timestamp %lld us (%.2f secs)",
2048               info->mBuffer, offset,
2049               timestampUs, timestampUs / 1E6);
2050
2051    err = mOMX->emptyBuffer(
2052            mNode, info->mBuffer, 0, offset,
2053            flags, timestampUs);
2054
2055    if (err != OK) {
2056        setState(ERROR);
2057        return;
2058    }
2059
2060    info->mOwnedByComponent = true;
2061
2062    // This component does not ever signal the EOS flag on output buffers,
2063    // Thanks for nothing.
2064    if (mSignalledEOS && !strcmp(mComponentName, "OMX.TI.Video.encoder")) {
2065        mNoMoreOutputData = true;
2066        mBufferFilled.signal();
2067    }
2068}
2069
2070void OMXCodec::fillOutputBuffer(BufferInfo *info) {
2071    CHECK_EQ(info->mOwnedByComponent, false);
2072
2073    if (mNoMoreOutputData) {
2074        CODEC_LOGV("There is no more output data available, not "
2075             "calling fillOutputBuffer");
2076        return;
2077    }
2078
2079    CODEC_LOGV("Calling fill_buffer on buffer %p", info->mBuffer);
2080    status_t err = mOMX->fillBuffer(mNode, info->mBuffer);
2081
2082    if (err != OK) {
2083        CODEC_LOGE("fillBuffer failed w/ error 0x%08x", err);
2084
2085        setState(ERROR);
2086        return;
2087    }
2088
2089    info->mOwnedByComponent = true;
2090}
2091
2092void OMXCodec::drainInputBuffer(IOMX::buffer_id buffer) {
2093    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2094    for (size_t i = 0; i < buffers->size(); ++i) {
2095        if ((*buffers)[i].mBuffer == buffer) {
2096            drainInputBuffer(&buffers->editItemAt(i));
2097            return;
2098        }
2099    }
2100
2101    CHECK(!"should not be here.");
2102}
2103
2104void OMXCodec::fillOutputBuffer(IOMX::buffer_id buffer) {
2105    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2106    for (size_t i = 0; i < buffers->size(); ++i) {
2107        if ((*buffers)[i].mBuffer == buffer) {
2108            fillOutputBuffer(&buffers->editItemAt(i));
2109            return;
2110        }
2111    }
2112
2113    CHECK(!"should not be here.");
2114}
2115
2116void OMXCodec::setState(State newState) {
2117    mState = newState;
2118    mAsyncCompletion.signal();
2119
2120    // This may cause some spurious wakeups but is necessary to
2121    // unblock the reader if we enter ERROR state.
2122    mBufferFilled.signal();
2123}
2124
2125void OMXCodec::setRawAudioFormat(
2126        OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels) {
2127    OMX_AUDIO_PARAM_PCMMODETYPE pcmParams;
2128    InitOMXParams(&pcmParams);
2129    pcmParams.nPortIndex = portIndex;
2130
2131    status_t err = mOMX->getParameter(
2132            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
2133
2134    CHECK_EQ(err, OK);
2135
2136    pcmParams.nChannels = numChannels;
2137    pcmParams.eNumData = OMX_NumericalDataSigned;
2138    pcmParams.bInterleaved = OMX_TRUE;
2139    pcmParams.nBitPerSample = 16;
2140    pcmParams.nSamplingRate = sampleRate;
2141    pcmParams.ePCMMode = OMX_AUDIO_PCMModeLinear;
2142
2143    if (numChannels == 1) {
2144        pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelCF;
2145    } else {
2146        CHECK_EQ(numChannels, 2);
2147
2148        pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelLF;
2149        pcmParams.eChannelMapping[1] = OMX_AUDIO_ChannelRF;
2150    }
2151
2152    err = mOMX->setParameter(
2153            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
2154
2155    CHECK_EQ(err, OK);
2156}
2157
2158void OMXCodec::setAMRFormat(bool isWAMR) {
2159    OMX_U32 portIndex = mIsEncoder ? kPortIndexOutput : kPortIndexInput;
2160
2161    OMX_AUDIO_PARAM_AMRTYPE def;
2162    InitOMXParams(&def);
2163    def.nPortIndex = portIndex;
2164
2165    status_t err =
2166        mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
2167
2168    CHECK_EQ(err, OK);
2169
2170    def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
2171    def.eAMRBandMode =
2172        isWAMR ? OMX_AUDIO_AMRBandModeWB0 : OMX_AUDIO_AMRBandModeNB0;
2173
2174    err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
2175    CHECK_EQ(err, OK);
2176
2177    ////////////////////////
2178
2179    if (mIsEncoder) {
2180        sp<MetaData> format = mSource->getFormat();
2181        int32_t sampleRate;
2182        int32_t numChannels;
2183        CHECK(format->findInt32(kKeySampleRate, &sampleRate));
2184        CHECK(format->findInt32(kKeyChannelCount, &numChannels));
2185
2186        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
2187    }
2188}
2189
2190void OMXCodec::setAACFormat(int32_t numChannels, int32_t sampleRate) {
2191    if (mIsEncoder) {
2192        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
2193    } else {
2194        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
2195        InitOMXParams(&profile);
2196        profile.nPortIndex = kPortIndexInput;
2197
2198        status_t err = mOMX->getParameter(
2199                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
2200        CHECK_EQ(err, OK);
2201
2202        profile.nChannels = numChannels;
2203        profile.nSampleRate = sampleRate;
2204        profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4ADTS;
2205
2206        err = mOMX->setParameter(
2207                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
2208        CHECK_EQ(err, OK);
2209    }
2210}
2211
2212void OMXCodec::setImageOutputFormat(
2213        OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height) {
2214    CODEC_LOGV("setImageOutputFormat(%ld, %ld)", width, height);
2215
2216#if 0
2217    OMX_INDEXTYPE index;
2218    status_t err = mOMX->get_extension_index(
2219            mNode, "OMX.TI.JPEG.decode.Config.OutputColorFormat", &index);
2220    CHECK_EQ(err, OK);
2221
2222    err = mOMX->set_config(mNode, index, &format, sizeof(format));
2223    CHECK_EQ(err, OK);
2224#endif
2225
2226    OMX_PARAM_PORTDEFINITIONTYPE def;
2227    InitOMXParams(&def);
2228    def.nPortIndex = kPortIndexOutput;
2229
2230    status_t err = mOMX->getParameter(
2231            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2232    CHECK_EQ(err, OK);
2233
2234    CHECK_EQ(def.eDomain, OMX_PortDomainImage);
2235
2236    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
2237
2238    CHECK_EQ(imageDef->eCompressionFormat, OMX_IMAGE_CodingUnused);
2239    imageDef->eColorFormat = format;
2240    imageDef->nFrameWidth = width;
2241    imageDef->nFrameHeight = height;
2242
2243    switch (format) {
2244        case OMX_COLOR_FormatYUV420PackedPlanar:
2245        case OMX_COLOR_FormatYUV411Planar:
2246        {
2247            def.nBufferSize = (width * height * 3) / 2;
2248            break;
2249        }
2250
2251        case OMX_COLOR_FormatCbYCrY:
2252        {
2253            def.nBufferSize = width * height * 2;
2254            break;
2255        }
2256
2257        case OMX_COLOR_Format32bitARGB8888:
2258        {
2259            def.nBufferSize = width * height * 4;
2260            break;
2261        }
2262
2263        case OMX_COLOR_Format16bitARGB4444:
2264        case OMX_COLOR_Format16bitARGB1555:
2265        case OMX_COLOR_Format16bitRGB565:
2266        case OMX_COLOR_Format16bitBGR565:
2267        {
2268            def.nBufferSize = width * height * 2;
2269            break;
2270        }
2271
2272        default:
2273            CHECK(!"Should not be here. Unknown color format.");
2274            break;
2275    }
2276
2277    def.nBufferCountActual = def.nBufferCountMin;
2278
2279    err = mOMX->setParameter(
2280            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2281    CHECK_EQ(err, OK);
2282}
2283
2284void OMXCodec::setJPEGInputFormat(
2285        OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize) {
2286    OMX_PARAM_PORTDEFINITIONTYPE def;
2287    InitOMXParams(&def);
2288    def.nPortIndex = kPortIndexInput;
2289
2290    status_t err = mOMX->getParameter(
2291            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2292    CHECK_EQ(err, OK);
2293
2294    CHECK_EQ(def.eDomain, OMX_PortDomainImage);
2295    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
2296
2297    CHECK_EQ(imageDef->eCompressionFormat, OMX_IMAGE_CodingJPEG);
2298    imageDef->nFrameWidth = width;
2299    imageDef->nFrameHeight = height;
2300
2301    def.nBufferSize = compressedSize;
2302    def.nBufferCountActual = def.nBufferCountMin;
2303
2304    err = mOMX->setParameter(
2305            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2306    CHECK_EQ(err, OK);
2307}
2308
2309void OMXCodec::addCodecSpecificData(const void *data, size_t size) {
2310    CodecSpecificData *specific =
2311        (CodecSpecificData *)malloc(sizeof(CodecSpecificData) + size - 1);
2312
2313    specific->mSize = size;
2314    memcpy(specific->mData, data, size);
2315
2316    mCodecSpecificData.push(specific);
2317}
2318
2319void OMXCodec::clearCodecSpecificData() {
2320    for (size_t i = 0; i < mCodecSpecificData.size(); ++i) {
2321        free(mCodecSpecificData.editItemAt(i));
2322    }
2323    mCodecSpecificData.clear();
2324    mCodecSpecificDataIndex = 0;
2325}
2326
2327status_t OMXCodec::start(MetaData *) {
2328    Mutex::Autolock autoLock(mLock);
2329
2330    if (mState != LOADED) {
2331        return UNKNOWN_ERROR;
2332    }
2333
2334    sp<MetaData> params = new MetaData;
2335    if (mQuirks & kWantsNALFragments) {
2336        params->setInt32(kKeyWantsNALFragments, true);
2337    }
2338    status_t err = mSource->start(params.get());
2339
2340    if (err != OK) {
2341        return err;
2342    }
2343
2344    mCodecSpecificDataIndex = 0;
2345    mInitialBufferSubmit = true;
2346    mSignalledEOS = false;
2347    mNoMoreOutputData = false;
2348    mOutputPortSettingsHaveChanged = false;
2349    mSeekTimeUs = -1;
2350    mFilledBuffers.clear();
2351
2352    return init();
2353}
2354
2355status_t OMXCodec::stop() {
2356    CODEC_LOGV("stop mState=%d", mState);
2357
2358    Mutex::Autolock autoLock(mLock);
2359
2360    while (isIntermediateState(mState)) {
2361        mAsyncCompletion.wait(mLock);
2362    }
2363
2364    switch (mState) {
2365        case LOADED:
2366        case ERROR:
2367            break;
2368
2369        case EXECUTING:
2370        {
2371            setState(EXECUTING_TO_IDLE);
2372
2373            if (mQuirks & kRequiresFlushBeforeShutdown) {
2374                CODEC_LOGV("This component requires a flush before transitioning "
2375                     "from EXECUTING to IDLE...");
2376
2377                bool emulateInputFlushCompletion =
2378                    !flushPortAsync(kPortIndexInput);
2379
2380                bool emulateOutputFlushCompletion =
2381                    !flushPortAsync(kPortIndexOutput);
2382
2383                if (emulateInputFlushCompletion) {
2384                    onCmdComplete(OMX_CommandFlush, kPortIndexInput);
2385                }
2386
2387                if (emulateOutputFlushCompletion) {
2388                    onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
2389                }
2390            } else {
2391                mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
2392                mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
2393
2394                status_t err =
2395                    mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
2396                CHECK_EQ(err, OK);
2397            }
2398
2399            while (mState != LOADED && mState != ERROR) {
2400                mAsyncCompletion.wait(mLock);
2401            }
2402
2403            break;
2404        }
2405
2406        default:
2407        {
2408            CHECK(!"should not be here.");
2409            break;
2410        }
2411    }
2412
2413    if (mLeftOverBuffer) {
2414        mLeftOverBuffer->release();
2415        mLeftOverBuffer = NULL;
2416    }
2417
2418    mSource->stop();
2419
2420    CODEC_LOGV("stopped");
2421
2422    return OK;
2423}
2424
2425sp<MetaData> OMXCodec::getFormat() {
2426    Mutex::Autolock autoLock(mLock);
2427
2428    return mOutputFormat;
2429}
2430
2431status_t OMXCodec::read(
2432        MediaBuffer **buffer, const ReadOptions *options) {
2433    *buffer = NULL;
2434
2435    Mutex::Autolock autoLock(mLock);
2436
2437    if (mState != EXECUTING && mState != RECONFIGURING) {
2438        return UNKNOWN_ERROR;
2439    }
2440
2441    bool seeking = false;
2442    int64_t seekTimeUs;
2443    if (options && options->getSeekTo(&seekTimeUs)) {
2444        seeking = true;
2445    }
2446
2447    if (mInitialBufferSubmit) {
2448        mInitialBufferSubmit = false;
2449
2450        if (seeking) {
2451            CHECK(seekTimeUs >= 0);
2452            mSeekTimeUs = seekTimeUs;
2453
2454            // There's no reason to trigger the code below, there's
2455            // nothing to flush yet.
2456            seeking = false;
2457        }
2458
2459        drainInputBuffers();
2460
2461        if (mState == EXECUTING) {
2462            // Otherwise mState == RECONFIGURING and this code will trigger
2463            // after the output port is reenabled.
2464            fillOutputBuffers();
2465        }
2466    }
2467
2468    if (seeking) {
2469        CODEC_LOGV("seeking to %lld us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6);
2470
2471        mSignalledEOS = false;
2472
2473        CHECK(seekTimeUs >= 0);
2474        mSeekTimeUs = seekTimeUs;
2475
2476        mFilledBuffers.clear();
2477
2478        CHECK_EQ(mState, EXECUTING);
2479
2480        bool emulateInputFlushCompletion = !flushPortAsync(kPortIndexInput);
2481        bool emulateOutputFlushCompletion = !flushPortAsync(kPortIndexOutput);
2482
2483        if (emulateInputFlushCompletion) {
2484            onCmdComplete(OMX_CommandFlush, kPortIndexInput);
2485        }
2486
2487        if (emulateOutputFlushCompletion) {
2488            onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
2489        }
2490
2491        while (mSeekTimeUs >= 0) {
2492            mBufferFilled.wait(mLock);
2493        }
2494    }
2495
2496    while (mState != ERROR && !mNoMoreOutputData && mFilledBuffers.empty()) {
2497        mBufferFilled.wait(mLock);
2498    }
2499
2500    if (mState == ERROR) {
2501        return UNKNOWN_ERROR;
2502    }
2503
2504    if (mFilledBuffers.empty()) {
2505        return mSignalledEOS ? mFinalStatus : ERROR_END_OF_STREAM;
2506    }
2507
2508    if (mOutputPortSettingsHaveChanged) {
2509        mOutputPortSettingsHaveChanged = false;
2510
2511        return INFO_FORMAT_CHANGED;
2512    }
2513
2514    size_t index = *mFilledBuffers.begin();
2515    mFilledBuffers.erase(mFilledBuffers.begin());
2516
2517    BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index);
2518    info->mMediaBuffer->add_ref();
2519    *buffer = info->mMediaBuffer;
2520
2521    return OK;
2522}
2523
2524void OMXCodec::signalBufferReturned(MediaBuffer *buffer) {
2525    Mutex::Autolock autoLock(mLock);
2526
2527    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2528    for (size_t i = 0; i < buffers->size(); ++i) {
2529        BufferInfo *info = &buffers->editItemAt(i);
2530
2531        if (info->mMediaBuffer == buffer) {
2532            CHECK_EQ(mPortStatus[kPortIndexOutput], ENABLED);
2533            fillOutputBuffer(info);
2534            return;
2535        }
2536    }
2537
2538    CHECK(!"should not be here.");
2539}
2540
2541static const char *imageCompressionFormatString(OMX_IMAGE_CODINGTYPE type) {
2542    static const char *kNames[] = {
2543        "OMX_IMAGE_CodingUnused",
2544        "OMX_IMAGE_CodingAutoDetect",
2545        "OMX_IMAGE_CodingJPEG",
2546        "OMX_IMAGE_CodingJPEG2K",
2547        "OMX_IMAGE_CodingEXIF",
2548        "OMX_IMAGE_CodingTIFF",
2549        "OMX_IMAGE_CodingGIF",
2550        "OMX_IMAGE_CodingPNG",
2551        "OMX_IMAGE_CodingLZW",
2552        "OMX_IMAGE_CodingBMP",
2553    };
2554
2555    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2556
2557    if (type < 0 || (size_t)type >= numNames) {
2558        return "UNKNOWN";
2559    } else {
2560        return kNames[type];
2561    }
2562}
2563
2564static const char *colorFormatString(OMX_COLOR_FORMATTYPE type) {
2565    static const char *kNames[] = {
2566        "OMX_COLOR_FormatUnused",
2567        "OMX_COLOR_FormatMonochrome",
2568        "OMX_COLOR_Format8bitRGB332",
2569        "OMX_COLOR_Format12bitRGB444",
2570        "OMX_COLOR_Format16bitARGB4444",
2571        "OMX_COLOR_Format16bitARGB1555",
2572        "OMX_COLOR_Format16bitRGB565",
2573        "OMX_COLOR_Format16bitBGR565",
2574        "OMX_COLOR_Format18bitRGB666",
2575        "OMX_COLOR_Format18bitARGB1665",
2576        "OMX_COLOR_Format19bitARGB1666",
2577        "OMX_COLOR_Format24bitRGB888",
2578        "OMX_COLOR_Format24bitBGR888",
2579        "OMX_COLOR_Format24bitARGB1887",
2580        "OMX_COLOR_Format25bitARGB1888",
2581        "OMX_COLOR_Format32bitBGRA8888",
2582        "OMX_COLOR_Format32bitARGB8888",
2583        "OMX_COLOR_FormatYUV411Planar",
2584        "OMX_COLOR_FormatYUV411PackedPlanar",
2585        "OMX_COLOR_FormatYUV420Planar",
2586        "OMX_COLOR_FormatYUV420PackedPlanar",
2587        "OMX_COLOR_FormatYUV420SemiPlanar",
2588        "OMX_COLOR_FormatYUV422Planar",
2589        "OMX_COLOR_FormatYUV422PackedPlanar",
2590        "OMX_COLOR_FormatYUV422SemiPlanar",
2591        "OMX_COLOR_FormatYCbYCr",
2592        "OMX_COLOR_FormatYCrYCb",
2593        "OMX_COLOR_FormatCbYCrY",
2594        "OMX_COLOR_FormatCrYCbY",
2595        "OMX_COLOR_FormatYUV444Interleaved",
2596        "OMX_COLOR_FormatRawBayer8bit",
2597        "OMX_COLOR_FormatRawBayer10bit",
2598        "OMX_COLOR_FormatRawBayer8bitcompressed",
2599        "OMX_COLOR_FormatL2",
2600        "OMX_COLOR_FormatL4",
2601        "OMX_COLOR_FormatL8",
2602        "OMX_COLOR_FormatL16",
2603        "OMX_COLOR_FormatL24",
2604        "OMX_COLOR_FormatL32",
2605        "OMX_COLOR_FormatYUV420PackedSemiPlanar",
2606        "OMX_COLOR_FormatYUV422PackedSemiPlanar",
2607        "OMX_COLOR_Format18BitBGR666",
2608        "OMX_COLOR_Format24BitARGB6666",
2609        "OMX_COLOR_Format24BitABGR6666",
2610    };
2611
2612    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2613
2614    if (type == OMX_QCOM_COLOR_FormatYVU420SemiPlanar) {
2615        return "OMX_QCOM_COLOR_FormatYVU420SemiPlanar";
2616    } else if (type < 0 || (size_t)type >= numNames) {
2617        return "UNKNOWN";
2618    } else {
2619        return kNames[type];
2620    }
2621}
2622
2623static const char *videoCompressionFormatString(OMX_VIDEO_CODINGTYPE type) {
2624    static const char *kNames[] = {
2625        "OMX_VIDEO_CodingUnused",
2626        "OMX_VIDEO_CodingAutoDetect",
2627        "OMX_VIDEO_CodingMPEG2",
2628        "OMX_VIDEO_CodingH263",
2629        "OMX_VIDEO_CodingMPEG4",
2630        "OMX_VIDEO_CodingWMV",
2631        "OMX_VIDEO_CodingRV",
2632        "OMX_VIDEO_CodingAVC",
2633        "OMX_VIDEO_CodingMJPEG",
2634    };
2635
2636    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2637
2638    if (type < 0 || (size_t)type >= numNames) {
2639        return "UNKNOWN";
2640    } else {
2641        return kNames[type];
2642    }
2643}
2644
2645static const char *audioCodingTypeString(OMX_AUDIO_CODINGTYPE type) {
2646    static const char *kNames[] = {
2647        "OMX_AUDIO_CodingUnused",
2648        "OMX_AUDIO_CodingAutoDetect",
2649        "OMX_AUDIO_CodingPCM",
2650        "OMX_AUDIO_CodingADPCM",
2651        "OMX_AUDIO_CodingAMR",
2652        "OMX_AUDIO_CodingGSMFR",
2653        "OMX_AUDIO_CodingGSMEFR",
2654        "OMX_AUDIO_CodingGSMHR",
2655        "OMX_AUDIO_CodingPDCFR",
2656        "OMX_AUDIO_CodingPDCEFR",
2657        "OMX_AUDIO_CodingPDCHR",
2658        "OMX_AUDIO_CodingTDMAFR",
2659        "OMX_AUDIO_CodingTDMAEFR",
2660        "OMX_AUDIO_CodingQCELP8",
2661        "OMX_AUDIO_CodingQCELP13",
2662        "OMX_AUDIO_CodingEVRC",
2663        "OMX_AUDIO_CodingSMV",
2664        "OMX_AUDIO_CodingG711",
2665        "OMX_AUDIO_CodingG723",
2666        "OMX_AUDIO_CodingG726",
2667        "OMX_AUDIO_CodingG729",
2668        "OMX_AUDIO_CodingAAC",
2669        "OMX_AUDIO_CodingMP3",
2670        "OMX_AUDIO_CodingSBC",
2671        "OMX_AUDIO_CodingVORBIS",
2672        "OMX_AUDIO_CodingWMA",
2673        "OMX_AUDIO_CodingRA",
2674        "OMX_AUDIO_CodingMIDI",
2675    };
2676
2677    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2678
2679    if (type < 0 || (size_t)type >= numNames) {
2680        return "UNKNOWN";
2681    } else {
2682        return kNames[type];
2683    }
2684}
2685
2686static const char *audioPCMModeString(OMX_AUDIO_PCMMODETYPE type) {
2687    static const char *kNames[] = {
2688        "OMX_AUDIO_PCMModeLinear",
2689        "OMX_AUDIO_PCMModeALaw",
2690        "OMX_AUDIO_PCMModeMULaw",
2691    };
2692
2693    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2694
2695    if (type < 0 || (size_t)type >= numNames) {
2696        return "UNKNOWN";
2697    } else {
2698        return kNames[type];
2699    }
2700}
2701
2702static const char *amrBandModeString(OMX_AUDIO_AMRBANDMODETYPE type) {
2703    static const char *kNames[] = {
2704        "OMX_AUDIO_AMRBandModeUnused",
2705        "OMX_AUDIO_AMRBandModeNB0",
2706        "OMX_AUDIO_AMRBandModeNB1",
2707        "OMX_AUDIO_AMRBandModeNB2",
2708        "OMX_AUDIO_AMRBandModeNB3",
2709        "OMX_AUDIO_AMRBandModeNB4",
2710        "OMX_AUDIO_AMRBandModeNB5",
2711        "OMX_AUDIO_AMRBandModeNB6",
2712        "OMX_AUDIO_AMRBandModeNB7",
2713        "OMX_AUDIO_AMRBandModeWB0",
2714        "OMX_AUDIO_AMRBandModeWB1",
2715        "OMX_AUDIO_AMRBandModeWB2",
2716        "OMX_AUDIO_AMRBandModeWB3",
2717        "OMX_AUDIO_AMRBandModeWB4",
2718        "OMX_AUDIO_AMRBandModeWB5",
2719        "OMX_AUDIO_AMRBandModeWB6",
2720        "OMX_AUDIO_AMRBandModeWB7",
2721        "OMX_AUDIO_AMRBandModeWB8",
2722    };
2723
2724    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2725
2726    if (type < 0 || (size_t)type >= numNames) {
2727        return "UNKNOWN";
2728    } else {
2729        return kNames[type];
2730    }
2731}
2732
2733static const char *amrFrameFormatString(OMX_AUDIO_AMRFRAMEFORMATTYPE type) {
2734    static const char *kNames[] = {
2735        "OMX_AUDIO_AMRFrameFormatConformance",
2736        "OMX_AUDIO_AMRFrameFormatIF1",
2737        "OMX_AUDIO_AMRFrameFormatIF2",
2738        "OMX_AUDIO_AMRFrameFormatFSF",
2739        "OMX_AUDIO_AMRFrameFormatRTPPayload",
2740        "OMX_AUDIO_AMRFrameFormatITU",
2741    };
2742
2743    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2744
2745    if (type < 0 || (size_t)type >= numNames) {
2746        return "UNKNOWN";
2747    } else {
2748        return kNames[type];
2749    }
2750}
2751
2752void OMXCodec::dumpPortStatus(OMX_U32 portIndex) {
2753    OMX_PARAM_PORTDEFINITIONTYPE def;
2754    InitOMXParams(&def);
2755    def.nPortIndex = portIndex;
2756
2757    status_t err = mOMX->getParameter(
2758            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2759    CHECK_EQ(err, OK);
2760
2761    printf("%s Port = {\n", portIndex == kPortIndexInput ? "Input" : "Output");
2762
2763    CHECK((portIndex == kPortIndexInput && def.eDir == OMX_DirInput)
2764          || (portIndex == kPortIndexOutput && def.eDir == OMX_DirOutput));
2765
2766    printf("  nBufferCountActual = %ld\n", def.nBufferCountActual);
2767    printf("  nBufferCountMin = %ld\n", def.nBufferCountMin);
2768    printf("  nBufferSize = %ld\n", def.nBufferSize);
2769
2770    switch (def.eDomain) {
2771        case OMX_PortDomainImage:
2772        {
2773            const OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
2774
2775            printf("\n");
2776            printf("  // Image\n");
2777            printf("  nFrameWidth = %ld\n", imageDef->nFrameWidth);
2778            printf("  nFrameHeight = %ld\n", imageDef->nFrameHeight);
2779            printf("  nStride = %ld\n", imageDef->nStride);
2780
2781            printf("  eCompressionFormat = %s\n",
2782                   imageCompressionFormatString(imageDef->eCompressionFormat));
2783
2784            printf("  eColorFormat = %s\n",
2785                   colorFormatString(imageDef->eColorFormat));
2786
2787            break;
2788        }
2789
2790        case OMX_PortDomainVideo:
2791        {
2792            OMX_VIDEO_PORTDEFINITIONTYPE *videoDef = &def.format.video;
2793
2794            printf("\n");
2795            printf("  // Video\n");
2796            printf("  nFrameWidth = %ld\n", videoDef->nFrameWidth);
2797            printf("  nFrameHeight = %ld\n", videoDef->nFrameHeight);
2798            printf("  nStride = %ld\n", videoDef->nStride);
2799
2800            printf("  eCompressionFormat = %s\n",
2801                   videoCompressionFormatString(videoDef->eCompressionFormat));
2802
2803            printf("  eColorFormat = %s\n",
2804                   colorFormatString(videoDef->eColorFormat));
2805
2806            break;
2807        }
2808
2809        case OMX_PortDomainAudio:
2810        {
2811            OMX_AUDIO_PORTDEFINITIONTYPE *audioDef = &def.format.audio;
2812
2813            printf("\n");
2814            printf("  // Audio\n");
2815            printf("  eEncoding = %s\n",
2816                   audioCodingTypeString(audioDef->eEncoding));
2817
2818            if (audioDef->eEncoding == OMX_AUDIO_CodingPCM) {
2819                OMX_AUDIO_PARAM_PCMMODETYPE params;
2820                InitOMXParams(&params);
2821                params.nPortIndex = portIndex;
2822
2823                err = mOMX->getParameter(
2824                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
2825                CHECK_EQ(err, OK);
2826
2827                printf("  nSamplingRate = %ld\n", params.nSamplingRate);
2828                printf("  nChannels = %ld\n", params.nChannels);
2829                printf("  bInterleaved = %d\n", params.bInterleaved);
2830                printf("  nBitPerSample = %ld\n", params.nBitPerSample);
2831
2832                printf("  eNumData = %s\n",
2833                       params.eNumData == OMX_NumericalDataSigned
2834                        ? "signed" : "unsigned");
2835
2836                printf("  ePCMMode = %s\n", audioPCMModeString(params.ePCMMode));
2837            } else if (audioDef->eEncoding == OMX_AUDIO_CodingAMR) {
2838                OMX_AUDIO_PARAM_AMRTYPE amr;
2839                InitOMXParams(&amr);
2840                amr.nPortIndex = portIndex;
2841
2842                err = mOMX->getParameter(
2843                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
2844                CHECK_EQ(err, OK);
2845
2846                printf("  nChannels = %ld\n", amr.nChannels);
2847                printf("  eAMRBandMode = %s\n",
2848                        amrBandModeString(amr.eAMRBandMode));
2849                printf("  eAMRFrameFormat = %s\n",
2850                        amrFrameFormatString(amr.eAMRFrameFormat));
2851            }
2852
2853            break;
2854        }
2855
2856        default:
2857        {
2858            printf("  // Unknown\n");
2859            break;
2860        }
2861    }
2862
2863    printf("}\n");
2864}
2865
2866void OMXCodec::initOutputFormat(const sp<MetaData> &inputFormat) {
2867    mOutputFormat = new MetaData;
2868    mOutputFormat->setCString(kKeyDecoderComponent, mComponentName);
2869
2870    OMX_PARAM_PORTDEFINITIONTYPE def;
2871    InitOMXParams(&def);
2872    def.nPortIndex = kPortIndexOutput;
2873
2874    status_t err = mOMX->getParameter(
2875            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2876    CHECK_EQ(err, OK);
2877
2878    switch (def.eDomain) {
2879        case OMX_PortDomainImage:
2880        {
2881            OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
2882            CHECK_EQ(imageDef->eCompressionFormat, OMX_IMAGE_CodingUnused);
2883
2884            mOutputFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
2885            mOutputFormat->setInt32(kKeyColorFormat, imageDef->eColorFormat);
2886            mOutputFormat->setInt32(kKeyWidth, imageDef->nFrameWidth);
2887            mOutputFormat->setInt32(kKeyHeight, imageDef->nFrameHeight);
2888            break;
2889        }
2890
2891        case OMX_PortDomainAudio:
2892        {
2893            OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio;
2894
2895            if (audio_def->eEncoding == OMX_AUDIO_CodingPCM) {
2896                OMX_AUDIO_PARAM_PCMMODETYPE params;
2897                InitOMXParams(&params);
2898                params.nPortIndex = kPortIndexOutput;
2899
2900                err = mOMX->getParameter(
2901                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
2902                CHECK_EQ(err, OK);
2903
2904                CHECK_EQ(params.eNumData, OMX_NumericalDataSigned);
2905                CHECK_EQ(params.nBitPerSample, 16);
2906                CHECK_EQ(params.ePCMMode, OMX_AUDIO_PCMModeLinear);
2907
2908                int32_t numChannels, sampleRate;
2909                inputFormat->findInt32(kKeyChannelCount, &numChannels);
2910                inputFormat->findInt32(kKeySampleRate, &sampleRate);
2911
2912                if ((OMX_U32)numChannels != params.nChannels) {
2913                    LOGW("Codec outputs a different number of channels than "
2914                         "the input stream contains (contains %d channels, "
2915                         "codec outputs %ld channels).",
2916                         numChannels, params.nChannels);
2917                }
2918
2919                mOutputFormat->setCString(
2920                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
2921
2922                // Use the codec-advertised number of channels, as some
2923                // codecs appear to output stereo even if the input data is
2924                // mono. If we know the codec lies about this information,
2925                // use the actual number of channels instead.
2926                mOutputFormat->setInt32(
2927                        kKeyChannelCount,
2928                        (mQuirks & kDecoderLiesAboutNumberOfChannels)
2929                            ? numChannels : params.nChannels);
2930
2931                // The codec-reported sampleRate is not reliable...
2932                mOutputFormat->setInt32(kKeySampleRate, sampleRate);
2933            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAMR) {
2934                OMX_AUDIO_PARAM_AMRTYPE amr;
2935                InitOMXParams(&amr);
2936                amr.nPortIndex = kPortIndexOutput;
2937
2938                err = mOMX->getParameter(
2939                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
2940                CHECK_EQ(err, OK);
2941
2942                CHECK_EQ(amr.nChannels, 1);
2943                mOutputFormat->setInt32(kKeyChannelCount, 1);
2944
2945                if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeNB0
2946                    && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeNB7) {
2947                    mOutputFormat->setCString(
2948                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB);
2949                    mOutputFormat->setInt32(kKeySampleRate, 8000);
2950                } else if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeWB0
2951                            && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeWB8) {
2952                    mOutputFormat->setCString(
2953                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB);
2954                    mOutputFormat->setInt32(kKeySampleRate, 16000);
2955                } else {
2956                    CHECK(!"Unknown AMR band mode.");
2957                }
2958            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAAC) {
2959                mOutputFormat->setCString(
2960                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
2961            } else {
2962                CHECK(!"Should not be here. Unknown audio encoding.");
2963            }
2964            break;
2965        }
2966
2967        case OMX_PortDomainVideo:
2968        {
2969            OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
2970
2971            if (video_def->eCompressionFormat == OMX_VIDEO_CodingUnused) {
2972                mOutputFormat->setCString(
2973                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
2974            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingMPEG4) {
2975                mOutputFormat->setCString(
2976                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
2977            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingH263) {
2978                mOutputFormat->setCString(
2979                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
2980            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingAVC) {
2981                mOutputFormat->setCString(
2982                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
2983            } else {
2984                CHECK(!"Unknown compression format.");
2985            }
2986
2987            if (!strcmp(mComponentName, "OMX.PV.avcdec")) {
2988                // This component appears to be lying to me.
2989                mOutputFormat->setInt32(
2990                        kKeyWidth, (video_def->nFrameWidth + 15) & -16);
2991                mOutputFormat->setInt32(
2992                        kKeyHeight, (video_def->nFrameHeight + 15) & -16);
2993            } else {
2994                mOutputFormat->setInt32(kKeyWidth, video_def->nFrameWidth);
2995                mOutputFormat->setInt32(kKeyHeight, video_def->nFrameHeight);
2996            }
2997
2998            mOutputFormat->setInt32(kKeyColorFormat, video_def->eColorFormat);
2999            break;
3000        }
3001
3002        default:
3003        {
3004            CHECK(!"should not be here, neither audio nor video.");
3005            break;
3006        }
3007    }
3008}
3009
3010////////////////////////////////////////////////////////////////////////////////
3011
3012status_t QueryCodecs(
3013        const sp<IOMX> &omx,
3014        const char *mime, bool queryDecoders,
3015        Vector<CodecCapabilities> *results) {
3016    results->clear();
3017
3018    for (int index = 0;; ++index) {
3019        const char *componentName;
3020
3021        if (!queryDecoders) {
3022            componentName = GetCodec(
3023                    kEncoderInfo, sizeof(kEncoderInfo) / sizeof(kEncoderInfo[0]),
3024                    mime, index);
3025        } else {
3026            componentName = GetCodec(
3027                    kDecoderInfo, sizeof(kDecoderInfo) / sizeof(kDecoderInfo[0]),
3028                    mime, index);
3029        }
3030
3031        if (!componentName) {
3032            return OK;
3033        }
3034
3035        if (strncmp(componentName, "OMX.", 4)) {
3036            // Not an OpenMax component but a software codec.
3037
3038            results->push();
3039            CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
3040            caps->mComponentName = componentName;
3041
3042            continue;
3043        }
3044
3045        sp<OMXCodecObserver> observer = new OMXCodecObserver;
3046        IOMX::node_id node;
3047        status_t err = omx->allocateNode(componentName, observer, &node);
3048
3049        if (err != OK) {
3050            continue;
3051        }
3052
3053        OMXCodec::setComponentRole(omx, node, !queryDecoders, mime);
3054
3055        results->push();
3056        CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
3057        caps->mComponentName = componentName;
3058
3059        OMX_VIDEO_PARAM_PROFILELEVELTYPE param;
3060        InitOMXParams(&param);
3061
3062        param.nPortIndex = queryDecoders ? 0 : 1;
3063
3064        for (param.nProfileIndex = 0;; ++param.nProfileIndex) {
3065            err = omx->getParameter(
3066                    node, OMX_IndexParamVideoProfileLevelQuerySupported,
3067                    &param, sizeof(param));
3068
3069            if (err != OK) {
3070                break;
3071            }
3072
3073            CodecProfileLevel profileLevel;
3074            profileLevel.mProfile = param.eProfile;
3075            profileLevel.mLevel = param.eLevel;
3076
3077            caps->mProfileLevels.push(profileLevel);
3078        }
3079
3080        CHECK_EQ(omx->freeNode(node), OK);
3081    }
3082}
3083
3084}  // namespace android
3085