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