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