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