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