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