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