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