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