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