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