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