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