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