OMXCodec.cpp revision 213addfaf4b359c69da4e9b4490c511d116845bb
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        quirks |= kRequiresAllocateBufferOnOutputPorts;
305        quirks |= kDefersOutputBufferAllocation;
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      mOMXLivesLocally(omx->livesLocally(getpid())),
1020      mNode(node),
1021      mQuirks(quirks),
1022      mIsEncoder(isEncoder),
1023      mMIME(strdup(mime)),
1024      mComponentName(strdup(componentName)),
1025      mSource(source),
1026      mCodecSpecificDataIndex(0),
1027      mState(LOADED),
1028      mInitialBufferSubmit(true),
1029      mSignalledEOS(false),
1030      mNoMoreOutputData(false),
1031      mOutputPortSettingsHaveChanged(false),
1032      mSeekTimeUs(-1) {
1033    mPortStatus[kPortIndexInput] = ENABLED;
1034    mPortStatus[kPortIndexOutput] = ENABLED;
1035
1036    setComponentRole();
1037}
1038
1039// static
1040void OMXCodec::setComponentRole(
1041        const sp<IOMX> &omx, IOMX::node_id node, bool isEncoder,
1042        const char *mime) {
1043    struct MimeToRole {
1044        const char *mime;
1045        const char *decoderRole;
1046        const char *encoderRole;
1047    };
1048
1049    static const MimeToRole kMimeToRole[] = {
1050        { MEDIA_MIMETYPE_AUDIO_MPEG,
1051            "audio_decoder.mp3", "audio_encoder.mp3" },
1052        { MEDIA_MIMETYPE_AUDIO_AMR_NB,
1053            "audio_decoder.amrnb", "audio_encoder.amrnb" },
1054        { MEDIA_MIMETYPE_AUDIO_AMR_WB,
1055            "audio_decoder.amrwb", "audio_encoder.amrwb" },
1056        { MEDIA_MIMETYPE_AUDIO_AAC,
1057            "audio_decoder.aac", "audio_encoder.aac" },
1058        { MEDIA_MIMETYPE_VIDEO_AVC,
1059            "video_decoder.avc", "video_encoder.avc" },
1060        { MEDIA_MIMETYPE_VIDEO_MPEG4,
1061            "video_decoder.mpeg4", "video_encoder.mpeg4" },
1062        { MEDIA_MIMETYPE_VIDEO_H263,
1063            "video_decoder.h263", "video_encoder.h263" },
1064    };
1065
1066    static const size_t kNumMimeToRole =
1067        sizeof(kMimeToRole) / sizeof(kMimeToRole[0]);
1068
1069    size_t i;
1070    for (i = 0; i < kNumMimeToRole; ++i) {
1071        if (!strcasecmp(mime, kMimeToRole[i].mime)) {
1072            break;
1073        }
1074    }
1075
1076    if (i == kNumMimeToRole) {
1077        return;
1078    }
1079
1080    const char *role =
1081        isEncoder ? kMimeToRole[i].encoderRole
1082                  : kMimeToRole[i].decoderRole;
1083
1084    if (role != NULL) {
1085        OMX_PARAM_COMPONENTROLETYPE roleParams;
1086        InitOMXParams(&roleParams);
1087
1088        strncpy((char *)roleParams.cRole,
1089                role, OMX_MAX_STRINGNAME_SIZE - 1);
1090
1091        roleParams.cRole[OMX_MAX_STRINGNAME_SIZE - 1] = '\0';
1092
1093        status_t err = omx->setParameter(
1094                node, OMX_IndexParamStandardComponentRole,
1095                &roleParams, sizeof(roleParams));
1096
1097        if (err != OK) {
1098            LOGW("Failed to set standard component role '%s'.", role);
1099        }
1100    }
1101}
1102
1103void OMXCodec::setComponentRole() {
1104    setComponentRole(mOMX, mNode, mIsEncoder, mMIME);
1105}
1106
1107OMXCodec::~OMXCodec() {
1108    CHECK(mState == LOADED || mState == ERROR);
1109
1110    status_t err = mOMX->freeNode(mNode);
1111    CHECK_EQ(err, OK);
1112
1113    mNode = NULL;
1114    setState(DEAD);
1115
1116    clearCodecSpecificData();
1117
1118    free(mComponentName);
1119    mComponentName = NULL;
1120
1121    free(mMIME);
1122    mMIME = NULL;
1123}
1124
1125status_t OMXCodec::init() {
1126    // mLock is held.
1127
1128    CHECK_EQ(mState, LOADED);
1129
1130    status_t err;
1131    if (!(mQuirks & kRequiresLoadedToIdleAfterAllocation)) {
1132        err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
1133        CHECK_EQ(err, OK);
1134        setState(LOADED_TO_IDLE);
1135    }
1136
1137    err = allocateBuffers();
1138    CHECK_EQ(err, OK);
1139
1140    if (mQuirks & kRequiresLoadedToIdleAfterAllocation) {
1141        err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
1142        CHECK_EQ(err, OK);
1143
1144        setState(LOADED_TO_IDLE);
1145    }
1146
1147    while (mState != EXECUTING && mState != ERROR) {
1148        mAsyncCompletion.wait(mLock);
1149    }
1150
1151    return mState == ERROR ? UNKNOWN_ERROR : OK;
1152}
1153
1154// static
1155bool OMXCodec::isIntermediateState(State state) {
1156    return state == LOADED_TO_IDLE
1157        || state == IDLE_TO_EXECUTING
1158        || state == EXECUTING_TO_IDLE
1159        || state == IDLE_TO_LOADED
1160        || state == RECONFIGURING;
1161}
1162
1163status_t OMXCodec::allocateBuffers() {
1164    status_t err = allocateBuffersOnPort(kPortIndexInput);
1165
1166    if (err != OK) {
1167        return err;
1168    }
1169
1170    return allocateBuffersOnPort(kPortIndexOutput);
1171}
1172
1173status_t OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) {
1174    OMX_PARAM_PORTDEFINITIONTYPE def;
1175    InitOMXParams(&def);
1176    def.nPortIndex = portIndex;
1177
1178    status_t err = mOMX->getParameter(
1179            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1180
1181    if (err != OK) {
1182        return err;
1183    }
1184
1185    size_t totalSize = def.nBufferCountActual * def.nBufferSize;
1186    mDealer[portIndex] = new MemoryDealer(totalSize);
1187
1188    for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
1189        sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize);
1190        CHECK(mem.get() != NULL);
1191
1192        BufferInfo info;
1193        info.mData = NULL;
1194        info.mSize = def.nBufferSize;
1195
1196        IOMX::buffer_id buffer;
1197        if (portIndex == kPortIndexInput
1198                && (mQuirks & kRequiresAllocateBufferOnInputPorts)) {
1199            if (mOMXLivesLocally) {
1200                mem.clear();
1201
1202                err = mOMX->allocateBuffer(
1203                        mNode, portIndex, def.nBufferSize, &buffer,
1204                        &info.mData);
1205            } else {
1206                err = mOMX->allocateBufferWithBackup(
1207                        mNode, portIndex, mem, &buffer);
1208            }
1209        } else if (portIndex == kPortIndexOutput
1210                && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) {
1211            if (mOMXLivesLocally) {
1212                mem.clear();
1213
1214                err = mOMX->allocateBuffer(
1215                        mNode, portIndex, def.nBufferSize, &buffer,
1216                        &info.mData);
1217            } else {
1218                err = mOMX->allocateBufferWithBackup(
1219                        mNode, portIndex, mem, &buffer);
1220            }
1221        } else {
1222            err = mOMX->useBuffer(mNode, portIndex, mem, &buffer);
1223        }
1224
1225        if (err != OK) {
1226            LOGE("allocate_buffer_with_backup failed");
1227            return err;
1228        }
1229
1230        if (mem != NULL) {
1231            info.mData = mem->pointer();
1232        }
1233
1234        info.mBuffer = buffer;
1235        info.mOwnedByComponent = false;
1236        info.mMem = mem;
1237        info.mMediaBuffer = NULL;
1238
1239        if (portIndex == kPortIndexOutput) {
1240            if (!(mOMXLivesLocally
1241                        && (mQuirks & kRequiresAllocateBufferOnOutputPorts)
1242                        && (mQuirks & kDefersOutputBufferAllocation))) {
1243                // If the node does not fill in the buffer ptr at this time,
1244                // we will defer creating the MediaBuffer until receiving
1245                // the first FILL_BUFFER_DONE notification instead.
1246                info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize);
1247                info.mMediaBuffer->setObserver(this);
1248            }
1249        }
1250
1251        mPortBuffers[portIndex].push(info);
1252
1253        CODEC_LOGV("allocated buffer %p on %s port", buffer,
1254             portIndex == kPortIndexInput ? "input" : "output");
1255    }
1256
1257    // dumpPortStatus(portIndex);
1258
1259    return OK;
1260}
1261
1262void OMXCodec::on_message(const omx_message &msg) {
1263    Mutex::Autolock autoLock(mLock);
1264
1265    switch (msg.type) {
1266        case omx_message::EVENT:
1267        {
1268            onEvent(
1269                 msg.u.event_data.event, msg.u.event_data.data1,
1270                 msg.u.event_data.data2);
1271
1272            break;
1273        }
1274
1275        case omx_message::EMPTY_BUFFER_DONE:
1276        {
1277            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
1278
1279            CODEC_LOGV("EMPTY_BUFFER_DONE(buffer: %p)", buffer);
1280
1281            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
1282            size_t i = 0;
1283            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
1284                ++i;
1285            }
1286
1287            CHECK(i < buffers->size());
1288            if (!(*buffers)[i].mOwnedByComponent) {
1289                LOGW("We already own input buffer %p, yet received "
1290                     "an EMPTY_BUFFER_DONE.", buffer);
1291            }
1292
1293            buffers->editItemAt(i).mOwnedByComponent = false;
1294
1295            if (mPortStatus[kPortIndexInput] == DISABLING) {
1296                CODEC_LOGV("Port is disabled, freeing buffer %p", buffer);
1297
1298                status_t err =
1299                    mOMX->freeBuffer(mNode, kPortIndexInput, buffer);
1300                CHECK_EQ(err, OK);
1301
1302                buffers->removeAt(i);
1303            } else if (mPortStatus[kPortIndexInput] != SHUTTING_DOWN) {
1304                CHECK_EQ(mPortStatus[kPortIndexInput], ENABLED);
1305                drainInputBuffer(&buffers->editItemAt(i));
1306            }
1307            break;
1308        }
1309
1310        case omx_message::FILL_BUFFER_DONE:
1311        {
1312            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
1313            OMX_U32 flags = msg.u.extended_buffer_data.flags;
1314
1315            CODEC_LOGV("FILL_BUFFER_DONE(buffer: %p, size: %ld, flags: 0x%08lx, timestamp: %lld us (%.2f secs))",
1316                 buffer,
1317                 msg.u.extended_buffer_data.range_length,
1318                 flags,
1319                 msg.u.extended_buffer_data.timestamp,
1320                 msg.u.extended_buffer_data.timestamp / 1E6);
1321
1322            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
1323            size_t i = 0;
1324            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
1325                ++i;
1326            }
1327
1328            CHECK(i < buffers->size());
1329            BufferInfo *info = &buffers->editItemAt(i);
1330
1331            if (!info->mOwnedByComponent) {
1332                LOGW("We already own output buffer %p, yet received "
1333                     "a FILL_BUFFER_DONE.", buffer);
1334            }
1335
1336            info->mOwnedByComponent = false;
1337
1338            if (mPortStatus[kPortIndexOutput] == DISABLING) {
1339                CODEC_LOGV("Port is disabled, freeing buffer %p", buffer);
1340
1341                status_t err =
1342                    mOMX->freeBuffer(mNode, kPortIndexOutput, buffer);
1343                CHECK_EQ(err, OK);
1344
1345                buffers->removeAt(i);
1346#if 0
1347            } else if (mPortStatus[kPortIndexOutput] == ENABLED
1348                       && (flags & OMX_BUFFERFLAG_EOS)) {
1349                CODEC_LOGV("No more output data.");
1350                mNoMoreOutputData = true;
1351                mBufferFilled.signal();
1352#endif
1353            } else if (mPortStatus[kPortIndexOutput] != SHUTTING_DOWN) {
1354                CHECK_EQ(mPortStatus[kPortIndexOutput], ENABLED);
1355
1356                if (info->mMediaBuffer == NULL) {
1357                    CHECK(mOMXLivesLocally);
1358                    CHECK(mQuirks & kRequiresAllocateBufferOnOutputPorts);
1359                    CHECK(mQuirks & kDefersOutputBufferAllocation);
1360
1361                    // The qcom video decoders on Nexus don't actually allocate
1362                    // output buffer memory on a call to OMX_AllocateBuffer
1363                    // the "pBuffer" member of the OMX_BUFFERHEADERTYPE
1364                    // structure is only filled in later.
1365
1366                    info->mMediaBuffer = new MediaBuffer(
1367                            msg.u.extended_buffer_data.data_ptr,
1368                            info->mSize);
1369                    info->mMediaBuffer->setObserver(this);
1370                }
1371
1372                MediaBuffer *buffer = info->mMediaBuffer;
1373
1374                buffer->set_range(
1375                        msg.u.extended_buffer_data.range_offset,
1376                        msg.u.extended_buffer_data.range_length);
1377
1378                buffer->meta_data()->clear();
1379
1380                buffer->meta_data()->setInt64(
1381                        kKeyTime, msg.u.extended_buffer_data.timestamp);
1382
1383                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_SYNCFRAME) {
1384                    buffer->meta_data()->setInt32(kKeyIsSyncFrame, true);
1385                }
1386                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_CODECCONFIG) {
1387                    buffer->meta_data()->setInt32(kKeyIsCodecConfig, true);
1388                }
1389
1390                buffer->meta_data()->setPointer(
1391                        kKeyPlatformPrivate,
1392                        msg.u.extended_buffer_data.platform_private);
1393
1394                buffer->meta_data()->setPointer(
1395                        kKeyBufferID,
1396                        msg.u.extended_buffer_data.buffer);
1397
1398                mFilledBuffers.push_back(i);
1399                mBufferFilled.signal();
1400
1401                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_EOS) {
1402                    CODEC_LOGV("No more output data.");
1403                    mNoMoreOutputData = true;
1404                }
1405            }
1406
1407            break;
1408        }
1409
1410        default:
1411        {
1412            CHECK(!"should not be here.");
1413            break;
1414        }
1415    }
1416}
1417
1418void OMXCodec::onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) {
1419    switch (event) {
1420        case OMX_EventCmdComplete:
1421        {
1422            onCmdComplete((OMX_COMMANDTYPE)data1, data2);
1423            break;
1424        }
1425
1426        case OMX_EventError:
1427        {
1428            LOGE("ERROR(0x%08lx, %ld)", data1, data2);
1429
1430            setState(ERROR);
1431            break;
1432        }
1433
1434        case OMX_EventPortSettingsChanged:
1435        {
1436            onPortSettingsChanged(data1);
1437            break;
1438        }
1439
1440#if 0
1441        case OMX_EventBufferFlag:
1442        {
1443            CODEC_LOGV("EVENT_BUFFER_FLAG(%ld)", data1);
1444
1445            if (data1 == kPortIndexOutput) {
1446                mNoMoreOutputData = true;
1447            }
1448            break;
1449        }
1450#endif
1451
1452        default:
1453        {
1454            CODEC_LOGV("EVENT(%d, %ld, %ld)", event, data1, data2);
1455            break;
1456        }
1457    }
1458}
1459
1460// Has the format changed in any way that the client would have to be aware of?
1461static bool formatHasNotablyChanged(
1462        const sp<MetaData> &from, const sp<MetaData> &to) {
1463    if (from.get() == NULL && to.get() == NULL) {
1464        return false;
1465    }
1466
1467    if ((from.get() == NULL && to.get() != NULL)
1468        || (from.get() != NULL && to.get() == NULL)) {
1469        return true;
1470    }
1471
1472    const char *mime_from, *mime_to;
1473    CHECK(from->findCString(kKeyMIMEType, &mime_from));
1474    CHECK(to->findCString(kKeyMIMEType, &mime_to));
1475
1476    if (strcasecmp(mime_from, mime_to)) {
1477        return true;
1478    }
1479
1480    if (!strcasecmp(mime_from, MEDIA_MIMETYPE_VIDEO_RAW)) {
1481        int32_t colorFormat_from, colorFormat_to;
1482        CHECK(from->findInt32(kKeyColorFormat, &colorFormat_from));
1483        CHECK(to->findInt32(kKeyColorFormat, &colorFormat_to));
1484
1485        if (colorFormat_from != colorFormat_to) {
1486            return true;
1487        }
1488
1489        int32_t width_from, width_to;
1490        CHECK(from->findInt32(kKeyWidth, &width_from));
1491        CHECK(to->findInt32(kKeyWidth, &width_to));
1492
1493        if (width_from != width_to) {
1494            return true;
1495        }
1496
1497        int32_t height_from, height_to;
1498        CHECK(from->findInt32(kKeyHeight, &height_from));
1499        CHECK(to->findInt32(kKeyHeight, &height_to));
1500
1501        if (height_from != height_to) {
1502            return true;
1503        }
1504    } else if (!strcasecmp(mime_from, MEDIA_MIMETYPE_AUDIO_RAW)) {
1505        int32_t numChannels_from, numChannels_to;
1506        CHECK(from->findInt32(kKeyChannelCount, &numChannels_from));
1507        CHECK(to->findInt32(kKeyChannelCount, &numChannels_to));
1508
1509        if (numChannels_from != numChannels_to) {
1510            return true;
1511        }
1512
1513        int32_t sampleRate_from, sampleRate_to;
1514        CHECK(from->findInt32(kKeySampleRate, &sampleRate_from));
1515        CHECK(to->findInt32(kKeySampleRate, &sampleRate_to));
1516
1517        if (sampleRate_from != sampleRate_to) {
1518            return true;
1519        }
1520    }
1521
1522    return false;
1523}
1524
1525void OMXCodec::onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data) {
1526    switch (cmd) {
1527        case OMX_CommandStateSet:
1528        {
1529            onStateChange((OMX_STATETYPE)data);
1530            break;
1531        }
1532
1533        case OMX_CommandPortDisable:
1534        {
1535            OMX_U32 portIndex = data;
1536            CODEC_LOGV("PORT_DISABLED(%ld)", portIndex);
1537
1538            CHECK(mState == EXECUTING || mState == RECONFIGURING);
1539            CHECK_EQ(mPortStatus[portIndex], DISABLING);
1540            CHECK_EQ(mPortBuffers[portIndex].size(), 0);
1541
1542            mPortStatus[portIndex] = DISABLED;
1543
1544            if (mState == RECONFIGURING) {
1545                CHECK_EQ(portIndex, kPortIndexOutput);
1546
1547                sp<MetaData> oldOutputFormat = mOutputFormat;
1548                initOutputFormat(mSource->getFormat());
1549
1550                // Don't notify clients if the output port settings change
1551                // wasn't of importance to them, i.e. it may be that just the
1552                // number of buffers has changed and nothing else.
1553                mOutputPortSettingsHaveChanged =
1554                    formatHasNotablyChanged(oldOutputFormat, mOutputFormat);
1555
1556                enablePortAsync(portIndex);
1557
1558                status_t err = allocateBuffersOnPort(portIndex);
1559                CHECK_EQ(err, OK);
1560            }
1561            break;
1562        }
1563
1564        case OMX_CommandPortEnable:
1565        {
1566            OMX_U32 portIndex = data;
1567            CODEC_LOGV("PORT_ENABLED(%ld)", portIndex);
1568
1569            CHECK(mState == EXECUTING || mState == RECONFIGURING);
1570            CHECK_EQ(mPortStatus[portIndex], ENABLING);
1571
1572            mPortStatus[portIndex] = ENABLED;
1573
1574            if (mState == RECONFIGURING) {
1575                CHECK_EQ(portIndex, kPortIndexOutput);
1576
1577                setState(EXECUTING);
1578
1579                fillOutputBuffers();
1580            }
1581            break;
1582        }
1583
1584        case OMX_CommandFlush:
1585        {
1586            OMX_U32 portIndex = data;
1587
1588            CODEC_LOGV("FLUSH_DONE(%ld)", portIndex);
1589
1590            CHECK_EQ(mPortStatus[portIndex], SHUTTING_DOWN);
1591            mPortStatus[portIndex] = ENABLED;
1592
1593            CHECK_EQ(countBuffersWeOwn(mPortBuffers[portIndex]),
1594                     mPortBuffers[portIndex].size());
1595
1596            if (mState == RECONFIGURING) {
1597                CHECK_EQ(portIndex, kPortIndexOutput);
1598
1599                disablePortAsync(portIndex);
1600            } else if (mState == EXECUTING_TO_IDLE) {
1601                if (mPortStatus[kPortIndexInput] == ENABLED
1602                    && mPortStatus[kPortIndexOutput] == ENABLED) {
1603                    CODEC_LOGV("Finished flushing both ports, now completing "
1604                         "transition from EXECUTING to IDLE.");
1605
1606                    mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
1607                    mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
1608
1609                    status_t err =
1610                        mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
1611                    CHECK_EQ(err, OK);
1612                }
1613            } else {
1614                // We're flushing both ports in preparation for seeking.
1615
1616                if (mPortStatus[kPortIndexInput] == ENABLED
1617                    && mPortStatus[kPortIndexOutput] == ENABLED) {
1618                    CODEC_LOGV("Finished flushing both ports, now continuing from"
1619                         " seek-time.");
1620
1621                    drainInputBuffers();
1622                    fillOutputBuffers();
1623                }
1624            }
1625
1626            break;
1627        }
1628
1629        default:
1630        {
1631            CODEC_LOGV("CMD_COMPLETE(%d, %ld)", cmd, data);
1632            break;
1633        }
1634    }
1635}
1636
1637void OMXCodec::onStateChange(OMX_STATETYPE newState) {
1638    CODEC_LOGV("onStateChange %d", newState);
1639
1640    switch (newState) {
1641        case OMX_StateIdle:
1642        {
1643            CODEC_LOGV("Now Idle.");
1644            if (mState == LOADED_TO_IDLE) {
1645                status_t err = mOMX->sendCommand(
1646                        mNode, OMX_CommandStateSet, OMX_StateExecuting);
1647
1648                CHECK_EQ(err, OK);
1649
1650                setState(IDLE_TO_EXECUTING);
1651            } else {
1652                CHECK_EQ(mState, EXECUTING_TO_IDLE);
1653
1654                CHECK_EQ(
1655                    countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
1656                    mPortBuffers[kPortIndexInput].size());
1657
1658                CHECK_EQ(
1659                    countBuffersWeOwn(mPortBuffers[kPortIndexOutput]),
1660                    mPortBuffers[kPortIndexOutput].size());
1661
1662                status_t err = mOMX->sendCommand(
1663                        mNode, OMX_CommandStateSet, OMX_StateLoaded);
1664
1665                CHECK_EQ(err, OK);
1666
1667                err = freeBuffersOnPort(kPortIndexInput);
1668                CHECK_EQ(err, OK);
1669
1670                err = freeBuffersOnPort(kPortIndexOutput);
1671                CHECK_EQ(err, OK);
1672
1673                mPortStatus[kPortIndexInput] = ENABLED;
1674                mPortStatus[kPortIndexOutput] = ENABLED;
1675
1676                setState(IDLE_TO_LOADED);
1677            }
1678            break;
1679        }
1680
1681        case OMX_StateExecuting:
1682        {
1683            CHECK_EQ(mState, IDLE_TO_EXECUTING);
1684
1685            CODEC_LOGV("Now Executing.");
1686
1687            setState(EXECUTING);
1688
1689            // Buffers will be submitted to the component in the first
1690            // call to OMXCodec::read as mInitialBufferSubmit is true at
1691            // this point. This ensures that this on_message call returns,
1692            // releases the lock and ::init can notice the state change and
1693            // itself return.
1694            break;
1695        }
1696
1697        case OMX_StateLoaded:
1698        {
1699            CHECK_EQ(mState, IDLE_TO_LOADED);
1700
1701            CODEC_LOGV("Now Loaded.");
1702
1703            setState(LOADED);
1704            break;
1705        }
1706
1707        case OMX_StateInvalid:
1708        {
1709            setState(ERROR);
1710            break;
1711        }
1712
1713        default:
1714        {
1715            CHECK(!"should not be here.");
1716            break;
1717        }
1718    }
1719}
1720
1721// static
1722size_t OMXCodec::countBuffersWeOwn(const Vector<BufferInfo> &buffers) {
1723    size_t n = 0;
1724    for (size_t i = 0; i < buffers.size(); ++i) {
1725        if (!buffers[i].mOwnedByComponent) {
1726            ++n;
1727        }
1728    }
1729
1730    return n;
1731}
1732
1733status_t OMXCodec::freeBuffersOnPort(
1734        OMX_U32 portIndex, bool onlyThoseWeOwn) {
1735    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
1736
1737    status_t stickyErr = OK;
1738
1739    for (size_t i = buffers->size(); i-- > 0;) {
1740        BufferInfo *info = &buffers->editItemAt(i);
1741
1742        if (onlyThoseWeOwn && info->mOwnedByComponent) {
1743            continue;
1744        }
1745
1746        CHECK_EQ(info->mOwnedByComponent, false);
1747
1748        CODEC_LOGV("freeing buffer %p on port %ld", info->mBuffer, portIndex);
1749
1750        status_t err =
1751            mOMX->freeBuffer(mNode, portIndex, info->mBuffer);
1752
1753        if (err != OK) {
1754            stickyErr = err;
1755        }
1756
1757        if (info->mMediaBuffer != NULL) {
1758            info->mMediaBuffer->setObserver(NULL);
1759
1760            // Make sure nobody but us owns this buffer at this point.
1761            CHECK_EQ(info->mMediaBuffer->refcount(), 0);
1762
1763            info->mMediaBuffer->release();
1764        }
1765
1766        buffers->removeAt(i);
1767    }
1768
1769    CHECK(onlyThoseWeOwn || buffers->isEmpty());
1770
1771    return stickyErr;
1772}
1773
1774void OMXCodec::onPortSettingsChanged(OMX_U32 portIndex) {
1775    CODEC_LOGV("PORT_SETTINGS_CHANGED(%ld)", portIndex);
1776
1777    CHECK_EQ(mState, EXECUTING);
1778    CHECK_EQ(portIndex, kPortIndexOutput);
1779    setState(RECONFIGURING);
1780
1781    if (mQuirks & kNeedsFlushBeforeDisable) {
1782        if (!flushPortAsync(portIndex)) {
1783            onCmdComplete(OMX_CommandFlush, portIndex);
1784        }
1785    } else {
1786        disablePortAsync(portIndex);
1787    }
1788}
1789
1790bool OMXCodec::flushPortAsync(OMX_U32 portIndex) {
1791    CHECK(mState == EXECUTING || mState == RECONFIGURING
1792            || mState == EXECUTING_TO_IDLE);
1793
1794    CODEC_LOGV("flushPortAsync(%ld): we own %d out of %d buffers already.",
1795         portIndex, countBuffersWeOwn(mPortBuffers[portIndex]),
1796         mPortBuffers[portIndex].size());
1797
1798    CHECK_EQ(mPortStatus[portIndex], ENABLED);
1799    mPortStatus[portIndex] = SHUTTING_DOWN;
1800
1801    if ((mQuirks & kRequiresFlushCompleteEmulation)
1802        && countBuffersWeOwn(mPortBuffers[portIndex])
1803                == mPortBuffers[portIndex].size()) {
1804        // No flush is necessary and this component fails to send a
1805        // flush-complete event in this case.
1806
1807        return false;
1808    }
1809
1810    status_t err =
1811        mOMX->sendCommand(mNode, OMX_CommandFlush, portIndex);
1812    CHECK_EQ(err, OK);
1813
1814    return true;
1815}
1816
1817void OMXCodec::disablePortAsync(OMX_U32 portIndex) {
1818    CHECK(mState == EXECUTING || mState == RECONFIGURING);
1819
1820    CHECK_EQ(mPortStatus[portIndex], ENABLED);
1821    mPortStatus[portIndex] = DISABLING;
1822
1823    status_t err =
1824        mOMX->sendCommand(mNode, OMX_CommandPortDisable, portIndex);
1825    CHECK_EQ(err, OK);
1826
1827    freeBuffersOnPort(portIndex, true);
1828}
1829
1830void OMXCodec::enablePortAsync(OMX_U32 portIndex) {
1831    CHECK(mState == EXECUTING || mState == RECONFIGURING);
1832
1833    CHECK_EQ(mPortStatus[portIndex], DISABLED);
1834    mPortStatus[portIndex] = ENABLING;
1835
1836    status_t err =
1837        mOMX->sendCommand(mNode, OMX_CommandPortEnable, portIndex);
1838    CHECK_EQ(err, OK);
1839}
1840
1841void OMXCodec::fillOutputBuffers() {
1842    CHECK_EQ(mState, EXECUTING);
1843
1844    // This is a workaround for some decoders not properly reporting
1845    // end-of-output-stream. If we own all input buffers and also own
1846    // all output buffers and we already signalled end-of-input-stream,
1847    // the end-of-output-stream is implied.
1848    if (mSignalledEOS
1849            && countBuffersWeOwn(mPortBuffers[kPortIndexInput])
1850                == mPortBuffers[kPortIndexInput].size()
1851            && countBuffersWeOwn(mPortBuffers[kPortIndexOutput])
1852                == mPortBuffers[kPortIndexOutput].size()) {
1853        mNoMoreOutputData = true;
1854        mBufferFilled.signal();
1855
1856        return;
1857    }
1858
1859    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
1860    for (size_t i = 0; i < buffers->size(); ++i) {
1861        fillOutputBuffer(&buffers->editItemAt(i));
1862    }
1863}
1864
1865void OMXCodec::drainInputBuffers() {
1866    CHECK(mState == EXECUTING || mState == RECONFIGURING);
1867
1868    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
1869    for (size_t i = 0; i < buffers->size(); ++i) {
1870        drainInputBuffer(&buffers->editItemAt(i));
1871    }
1872}
1873
1874void OMXCodec::drainInputBuffer(BufferInfo *info) {
1875    CHECK_EQ(info->mOwnedByComponent, false);
1876
1877    if (mSignalledEOS) {
1878        return;
1879    }
1880
1881    if (mCodecSpecificDataIndex < mCodecSpecificData.size()) {
1882        const CodecSpecificData *specific =
1883            mCodecSpecificData[mCodecSpecificDataIndex];
1884
1885        size_t size = specific->mSize;
1886
1887        if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mMIME)
1888                && !(mQuirks & kWantsNALFragments)) {
1889            static const uint8_t kNALStartCode[4] =
1890                    { 0x00, 0x00, 0x00, 0x01 };
1891
1892            CHECK(info->mSize >= specific->mSize + 4);
1893
1894            size += 4;
1895
1896            memcpy(info->mData, kNALStartCode, 4);
1897            memcpy((uint8_t *)info->mData + 4,
1898                   specific->mData, specific->mSize);
1899        } else {
1900            CHECK(info->mSize >= specific->mSize);
1901            memcpy(info->mData, specific->mData, specific->mSize);
1902        }
1903
1904        mNoMoreOutputData = false;
1905
1906        CODEC_LOGV("calling emptyBuffer with codec specific data");
1907
1908        status_t err = mOMX->emptyBuffer(
1909                mNode, info->mBuffer, 0, size,
1910                OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG,
1911                0);
1912        CHECK_EQ(err, OK);
1913
1914        info->mOwnedByComponent = true;
1915
1916        ++mCodecSpecificDataIndex;
1917        return;
1918    }
1919
1920    MediaBuffer *srcBuffer;
1921    status_t err;
1922    if (mSeekTimeUs >= 0) {
1923        MediaSource::ReadOptions options;
1924        options.setSeekTo(mSeekTimeUs);
1925
1926        mSeekTimeUs = -1;
1927        mBufferFilled.signal();
1928
1929        err = mSource->read(&srcBuffer, &options);
1930    } else {
1931        err = mSource->read(&srcBuffer);
1932    }
1933
1934    OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME;
1935    OMX_TICKS timestampUs = 0;
1936    size_t srcLength = 0;
1937
1938    if (err != OK) {
1939        CODEC_LOGV("signalling end of input stream.");
1940        flags |= OMX_BUFFERFLAG_EOS;
1941
1942        mSignalledEOS = true;
1943    } else {
1944        mNoMoreOutputData = false;
1945
1946        srcLength = srcBuffer->range_length();
1947
1948        if (info->mSize < srcLength) {
1949            LOGE("info->mSize = %d, srcLength = %d",
1950                 info->mSize, srcLength);
1951        }
1952        CHECK(info->mSize >= srcLength);
1953        memcpy(info->mData,
1954               (const uint8_t *)srcBuffer->data() + srcBuffer->range_offset(),
1955               srcLength);
1956
1957        if (srcBuffer->meta_data()->findInt64(kKeyTime, &timestampUs)) {
1958            CODEC_LOGV("Calling emptyBuffer on buffer %p (length %d), "
1959                       "timestamp %lld us (%.2f secs)",
1960                       info->mBuffer, srcLength,
1961                       timestampUs, timestampUs / 1E6);
1962        }
1963    }
1964
1965    if (srcBuffer != NULL) {
1966        srcBuffer->release();
1967        srcBuffer = NULL;
1968    }
1969
1970    err = mOMX->emptyBuffer(
1971            mNode, info->mBuffer, 0, srcLength,
1972            flags, timestampUs);
1973
1974    if (err != OK) {
1975        setState(ERROR);
1976        return;
1977    }
1978
1979    info->mOwnedByComponent = true;
1980
1981    // This component does not ever signal the EOS flag on output buffers,
1982    // Thanks for nothing.
1983    if (mSignalledEOS && !strcmp(mComponentName, "OMX.TI.Video.encoder")) {
1984        mNoMoreOutputData = true;
1985        mBufferFilled.signal();
1986    }
1987}
1988
1989void OMXCodec::fillOutputBuffer(BufferInfo *info) {
1990    CHECK_EQ(info->mOwnedByComponent, false);
1991
1992    if (mNoMoreOutputData) {
1993        CODEC_LOGV("There is no more output data available, not "
1994             "calling fillOutputBuffer");
1995        return;
1996    }
1997
1998    CODEC_LOGV("Calling fill_buffer on buffer %p", info->mBuffer);
1999    status_t err = mOMX->fillBuffer(mNode, info->mBuffer);
2000    CHECK_EQ(err, OK);
2001
2002    info->mOwnedByComponent = true;
2003}
2004
2005void OMXCodec::drainInputBuffer(IOMX::buffer_id buffer) {
2006    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2007    for (size_t i = 0; i < buffers->size(); ++i) {
2008        if ((*buffers)[i].mBuffer == buffer) {
2009            drainInputBuffer(&buffers->editItemAt(i));
2010            return;
2011        }
2012    }
2013
2014    CHECK(!"should not be here.");
2015}
2016
2017void OMXCodec::fillOutputBuffer(IOMX::buffer_id buffer) {
2018    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2019    for (size_t i = 0; i < buffers->size(); ++i) {
2020        if ((*buffers)[i].mBuffer == buffer) {
2021            fillOutputBuffer(&buffers->editItemAt(i));
2022            return;
2023        }
2024    }
2025
2026    CHECK(!"should not be here.");
2027}
2028
2029void OMXCodec::setState(State newState) {
2030    mState = newState;
2031    mAsyncCompletion.signal();
2032
2033    // This may cause some spurious wakeups but is necessary to
2034    // unblock the reader if we enter ERROR state.
2035    mBufferFilled.signal();
2036}
2037
2038void OMXCodec::setRawAudioFormat(
2039        OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels) {
2040    OMX_AUDIO_PARAM_PCMMODETYPE pcmParams;
2041    InitOMXParams(&pcmParams);
2042    pcmParams.nPortIndex = portIndex;
2043
2044    status_t err = mOMX->getParameter(
2045            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
2046
2047    CHECK_EQ(err, OK);
2048
2049    pcmParams.nChannels = numChannels;
2050    pcmParams.eNumData = OMX_NumericalDataSigned;
2051    pcmParams.bInterleaved = OMX_TRUE;
2052    pcmParams.nBitPerSample = 16;
2053    pcmParams.nSamplingRate = sampleRate;
2054    pcmParams.ePCMMode = OMX_AUDIO_PCMModeLinear;
2055
2056    if (numChannels == 1) {
2057        pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelCF;
2058    } else {
2059        CHECK_EQ(numChannels, 2);
2060
2061        pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelLF;
2062        pcmParams.eChannelMapping[1] = OMX_AUDIO_ChannelRF;
2063    }
2064
2065    err = mOMX->setParameter(
2066            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
2067
2068    CHECK_EQ(err, OK);
2069}
2070
2071void OMXCodec::setAMRFormat(bool isWAMR) {
2072    OMX_U32 portIndex = mIsEncoder ? kPortIndexOutput : kPortIndexInput;
2073
2074    OMX_AUDIO_PARAM_AMRTYPE def;
2075    InitOMXParams(&def);
2076    def.nPortIndex = portIndex;
2077
2078    status_t err =
2079        mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
2080
2081    CHECK_EQ(err, OK);
2082
2083    def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
2084    def.eAMRBandMode =
2085        isWAMR ? OMX_AUDIO_AMRBandModeWB0 : OMX_AUDIO_AMRBandModeNB0;
2086
2087    err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
2088    CHECK_EQ(err, OK);
2089
2090    ////////////////////////
2091
2092    if (mIsEncoder) {
2093        sp<MetaData> format = mSource->getFormat();
2094        int32_t sampleRate;
2095        int32_t numChannels;
2096        CHECK(format->findInt32(kKeySampleRate, &sampleRate));
2097        CHECK(format->findInt32(kKeyChannelCount, &numChannels));
2098
2099        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
2100    }
2101}
2102
2103void OMXCodec::setAACFormat(int32_t numChannels, int32_t sampleRate) {
2104    if (mIsEncoder) {
2105        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
2106    } else {
2107        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
2108        InitOMXParams(&profile);
2109        profile.nPortIndex = kPortIndexInput;
2110
2111        status_t err = mOMX->getParameter(
2112                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
2113        CHECK_EQ(err, OK);
2114
2115        profile.nChannels = numChannels;
2116        profile.nSampleRate = sampleRate;
2117        profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4ADTS;
2118
2119        err = mOMX->setParameter(
2120                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
2121        CHECK_EQ(err, OK);
2122    }
2123}
2124
2125void OMXCodec::setImageOutputFormat(
2126        OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height) {
2127    CODEC_LOGV("setImageOutputFormat(%ld, %ld)", width, height);
2128
2129#if 0
2130    OMX_INDEXTYPE index;
2131    status_t err = mOMX->get_extension_index(
2132            mNode, "OMX.TI.JPEG.decode.Config.OutputColorFormat", &index);
2133    CHECK_EQ(err, OK);
2134
2135    err = mOMX->set_config(mNode, index, &format, sizeof(format));
2136    CHECK_EQ(err, OK);
2137#endif
2138
2139    OMX_PARAM_PORTDEFINITIONTYPE def;
2140    InitOMXParams(&def);
2141    def.nPortIndex = kPortIndexOutput;
2142
2143    status_t err = mOMX->getParameter(
2144            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2145    CHECK_EQ(err, OK);
2146
2147    CHECK_EQ(def.eDomain, OMX_PortDomainImage);
2148
2149    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
2150
2151    CHECK_EQ(imageDef->eCompressionFormat, OMX_IMAGE_CodingUnused);
2152    imageDef->eColorFormat = format;
2153    imageDef->nFrameWidth = width;
2154    imageDef->nFrameHeight = height;
2155
2156    switch (format) {
2157        case OMX_COLOR_FormatYUV420PackedPlanar:
2158        case OMX_COLOR_FormatYUV411Planar:
2159        {
2160            def.nBufferSize = (width * height * 3) / 2;
2161            break;
2162        }
2163
2164        case OMX_COLOR_FormatCbYCrY:
2165        {
2166            def.nBufferSize = width * height * 2;
2167            break;
2168        }
2169
2170        case OMX_COLOR_Format32bitARGB8888:
2171        {
2172            def.nBufferSize = width * height * 4;
2173            break;
2174        }
2175
2176        case OMX_COLOR_Format16bitARGB4444:
2177        case OMX_COLOR_Format16bitARGB1555:
2178        case OMX_COLOR_Format16bitRGB565:
2179        case OMX_COLOR_Format16bitBGR565:
2180        {
2181            def.nBufferSize = width * height * 2;
2182            break;
2183        }
2184
2185        default:
2186            CHECK(!"Should not be here. Unknown color format.");
2187            break;
2188    }
2189
2190    def.nBufferCountActual = def.nBufferCountMin;
2191
2192    err = mOMX->setParameter(
2193            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2194    CHECK_EQ(err, OK);
2195}
2196
2197void OMXCodec::setJPEGInputFormat(
2198        OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize) {
2199    OMX_PARAM_PORTDEFINITIONTYPE def;
2200    InitOMXParams(&def);
2201    def.nPortIndex = kPortIndexInput;
2202
2203    status_t err = mOMX->getParameter(
2204            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2205    CHECK_EQ(err, OK);
2206
2207    CHECK_EQ(def.eDomain, OMX_PortDomainImage);
2208    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
2209
2210    CHECK_EQ(imageDef->eCompressionFormat, OMX_IMAGE_CodingJPEG);
2211    imageDef->nFrameWidth = width;
2212    imageDef->nFrameHeight = height;
2213
2214    def.nBufferSize = compressedSize;
2215    def.nBufferCountActual = def.nBufferCountMin;
2216
2217    err = mOMX->setParameter(
2218            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2219    CHECK_EQ(err, OK);
2220}
2221
2222void OMXCodec::addCodecSpecificData(const void *data, size_t size) {
2223    CodecSpecificData *specific =
2224        (CodecSpecificData *)malloc(sizeof(CodecSpecificData) + size - 1);
2225
2226    specific->mSize = size;
2227    memcpy(specific->mData, data, size);
2228
2229    mCodecSpecificData.push(specific);
2230}
2231
2232void OMXCodec::clearCodecSpecificData() {
2233    for (size_t i = 0; i < mCodecSpecificData.size(); ++i) {
2234        free(mCodecSpecificData.editItemAt(i));
2235    }
2236    mCodecSpecificData.clear();
2237    mCodecSpecificDataIndex = 0;
2238}
2239
2240status_t OMXCodec::start(MetaData *) {
2241    Mutex::Autolock autoLock(mLock);
2242
2243    if (mState != LOADED) {
2244        return UNKNOWN_ERROR;
2245    }
2246
2247    sp<MetaData> params = new MetaData;
2248    if (mQuirks & kWantsNALFragments) {
2249        params->setInt32(kKeyWantsNALFragments, true);
2250    }
2251    status_t err = mSource->start(params.get());
2252
2253    if (err != OK) {
2254        return err;
2255    }
2256
2257    mCodecSpecificDataIndex = 0;
2258    mInitialBufferSubmit = true;
2259    mSignalledEOS = false;
2260    mNoMoreOutputData = false;
2261    mOutputPortSettingsHaveChanged = false;
2262    mSeekTimeUs = -1;
2263    mFilledBuffers.clear();
2264
2265    return init();
2266}
2267
2268status_t OMXCodec::stop() {
2269    CODEC_LOGV("stop");
2270
2271    Mutex::Autolock autoLock(mLock);
2272
2273    while (isIntermediateState(mState)) {
2274        mAsyncCompletion.wait(mLock);
2275    }
2276
2277    switch (mState) {
2278        case LOADED:
2279        case ERROR:
2280            break;
2281
2282        case EXECUTING:
2283        {
2284            setState(EXECUTING_TO_IDLE);
2285
2286            if (mQuirks & kRequiresFlushBeforeShutdown) {
2287                CODEC_LOGV("This component requires a flush before transitioning "
2288                     "from EXECUTING to IDLE...");
2289
2290                bool emulateInputFlushCompletion =
2291                    !flushPortAsync(kPortIndexInput);
2292
2293                bool emulateOutputFlushCompletion =
2294                    !flushPortAsync(kPortIndexOutput);
2295
2296                if (emulateInputFlushCompletion) {
2297                    onCmdComplete(OMX_CommandFlush, kPortIndexInput);
2298                }
2299
2300                if (emulateOutputFlushCompletion) {
2301                    onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
2302                }
2303            } else {
2304                mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
2305                mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
2306
2307                status_t err =
2308                    mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
2309                CHECK_EQ(err, OK);
2310            }
2311
2312            while (mState != LOADED && mState != ERROR) {
2313                mAsyncCompletion.wait(mLock);
2314            }
2315
2316            break;
2317        }
2318
2319        default:
2320        {
2321            CHECK(!"should not be here.");
2322            break;
2323        }
2324    }
2325
2326    mSource->stop();
2327
2328    return OK;
2329}
2330
2331sp<MetaData> OMXCodec::getFormat() {
2332    Mutex::Autolock autoLock(mLock);
2333
2334    return mOutputFormat;
2335}
2336
2337status_t OMXCodec::read(
2338        MediaBuffer **buffer, const ReadOptions *options) {
2339    *buffer = NULL;
2340
2341    Mutex::Autolock autoLock(mLock);
2342
2343    if (mState != EXECUTING && mState != RECONFIGURING) {
2344        return UNKNOWN_ERROR;
2345    }
2346
2347    bool seeking = false;
2348    int64_t seekTimeUs;
2349    if (options && options->getSeekTo(&seekTimeUs)) {
2350        seeking = true;
2351    }
2352
2353    if (mInitialBufferSubmit) {
2354        mInitialBufferSubmit = false;
2355
2356        if (seeking) {
2357            CHECK(seekTimeUs >= 0);
2358            mSeekTimeUs = seekTimeUs;
2359
2360            // There's no reason to trigger the code below, there's
2361            // nothing to flush yet.
2362            seeking = false;
2363        }
2364
2365        drainInputBuffers();
2366
2367        if (mState == EXECUTING) {
2368            // Otherwise mState == RECONFIGURING and this code will trigger
2369            // after the output port is reenabled.
2370            fillOutputBuffers();
2371        }
2372    }
2373
2374    if (seeking) {
2375        CODEC_LOGV("seeking to %lld us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6);
2376
2377        mSignalledEOS = false;
2378
2379        CHECK(seekTimeUs >= 0);
2380        mSeekTimeUs = seekTimeUs;
2381
2382        mFilledBuffers.clear();
2383
2384        CHECK_EQ(mState, EXECUTING);
2385
2386        bool emulateInputFlushCompletion = !flushPortAsync(kPortIndexInput);
2387        bool emulateOutputFlushCompletion = !flushPortAsync(kPortIndexOutput);
2388
2389        if (emulateInputFlushCompletion) {
2390            onCmdComplete(OMX_CommandFlush, kPortIndexInput);
2391        }
2392
2393        if (emulateOutputFlushCompletion) {
2394            onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
2395        }
2396
2397        while (mSeekTimeUs >= 0) {
2398            mBufferFilled.wait(mLock);
2399        }
2400    }
2401
2402    while (mState != ERROR && !mNoMoreOutputData && mFilledBuffers.empty()) {
2403        mBufferFilled.wait(mLock);
2404    }
2405
2406    if (mState == ERROR) {
2407        return UNKNOWN_ERROR;
2408    }
2409
2410    if (mFilledBuffers.empty()) {
2411        return ERROR_END_OF_STREAM;
2412    }
2413
2414    if (mOutputPortSettingsHaveChanged) {
2415        mOutputPortSettingsHaveChanged = false;
2416
2417        return INFO_FORMAT_CHANGED;
2418    }
2419
2420    size_t index = *mFilledBuffers.begin();
2421    mFilledBuffers.erase(mFilledBuffers.begin());
2422
2423    BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index);
2424    info->mMediaBuffer->add_ref();
2425    *buffer = info->mMediaBuffer;
2426
2427    return OK;
2428}
2429
2430void OMXCodec::signalBufferReturned(MediaBuffer *buffer) {
2431    Mutex::Autolock autoLock(mLock);
2432
2433    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2434    for (size_t i = 0; i < buffers->size(); ++i) {
2435        BufferInfo *info = &buffers->editItemAt(i);
2436
2437        if (info->mMediaBuffer == buffer) {
2438            CHECK_EQ(mPortStatus[kPortIndexOutput], ENABLED);
2439            fillOutputBuffer(info);
2440            return;
2441        }
2442    }
2443
2444    CHECK(!"should not be here.");
2445}
2446
2447static const char *imageCompressionFormatString(OMX_IMAGE_CODINGTYPE type) {
2448    static const char *kNames[] = {
2449        "OMX_IMAGE_CodingUnused",
2450        "OMX_IMAGE_CodingAutoDetect",
2451        "OMX_IMAGE_CodingJPEG",
2452        "OMX_IMAGE_CodingJPEG2K",
2453        "OMX_IMAGE_CodingEXIF",
2454        "OMX_IMAGE_CodingTIFF",
2455        "OMX_IMAGE_CodingGIF",
2456        "OMX_IMAGE_CodingPNG",
2457        "OMX_IMAGE_CodingLZW",
2458        "OMX_IMAGE_CodingBMP",
2459    };
2460
2461    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2462
2463    if (type < 0 || (size_t)type >= numNames) {
2464        return "UNKNOWN";
2465    } else {
2466        return kNames[type];
2467    }
2468}
2469
2470static const char *colorFormatString(OMX_COLOR_FORMATTYPE type) {
2471    static const char *kNames[] = {
2472        "OMX_COLOR_FormatUnused",
2473        "OMX_COLOR_FormatMonochrome",
2474        "OMX_COLOR_Format8bitRGB332",
2475        "OMX_COLOR_Format12bitRGB444",
2476        "OMX_COLOR_Format16bitARGB4444",
2477        "OMX_COLOR_Format16bitARGB1555",
2478        "OMX_COLOR_Format16bitRGB565",
2479        "OMX_COLOR_Format16bitBGR565",
2480        "OMX_COLOR_Format18bitRGB666",
2481        "OMX_COLOR_Format18bitARGB1665",
2482        "OMX_COLOR_Format19bitARGB1666",
2483        "OMX_COLOR_Format24bitRGB888",
2484        "OMX_COLOR_Format24bitBGR888",
2485        "OMX_COLOR_Format24bitARGB1887",
2486        "OMX_COLOR_Format25bitARGB1888",
2487        "OMX_COLOR_Format32bitBGRA8888",
2488        "OMX_COLOR_Format32bitARGB8888",
2489        "OMX_COLOR_FormatYUV411Planar",
2490        "OMX_COLOR_FormatYUV411PackedPlanar",
2491        "OMX_COLOR_FormatYUV420Planar",
2492        "OMX_COLOR_FormatYUV420PackedPlanar",
2493        "OMX_COLOR_FormatYUV420SemiPlanar",
2494        "OMX_COLOR_FormatYUV422Planar",
2495        "OMX_COLOR_FormatYUV422PackedPlanar",
2496        "OMX_COLOR_FormatYUV422SemiPlanar",
2497        "OMX_COLOR_FormatYCbYCr",
2498        "OMX_COLOR_FormatYCrYCb",
2499        "OMX_COLOR_FormatCbYCrY",
2500        "OMX_COLOR_FormatCrYCbY",
2501        "OMX_COLOR_FormatYUV444Interleaved",
2502        "OMX_COLOR_FormatRawBayer8bit",
2503        "OMX_COLOR_FormatRawBayer10bit",
2504        "OMX_COLOR_FormatRawBayer8bitcompressed",
2505        "OMX_COLOR_FormatL2",
2506        "OMX_COLOR_FormatL4",
2507        "OMX_COLOR_FormatL8",
2508        "OMX_COLOR_FormatL16",
2509        "OMX_COLOR_FormatL24",
2510        "OMX_COLOR_FormatL32",
2511        "OMX_COLOR_FormatYUV420PackedSemiPlanar",
2512        "OMX_COLOR_FormatYUV422PackedSemiPlanar",
2513        "OMX_COLOR_Format18BitBGR666",
2514        "OMX_COLOR_Format24BitARGB6666",
2515        "OMX_COLOR_Format24BitABGR6666",
2516    };
2517
2518    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2519
2520    if (type == OMX_QCOM_COLOR_FormatYVU420SemiPlanar) {
2521        return "OMX_QCOM_COLOR_FormatYVU420SemiPlanar";
2522    } else if (type < 0 || (size_t)type >= numNames) {
2523        return "UNKNOWN";
2524    } else {
2525        return kNames[type];
2526    }
2527}
2528
2529static const char *videoCompressionFormatString(OMX_VIDEO_CODINGTYPE type) {
2530    static const char *kNames[] = {
2531        "OMX_VIDEO_CodingUnused",
2532        "OMX_VIDEO_CodingAutoDetect",
2533        "OMX_VIDEO_CodingMPEG2",
2534        "OMX_VIDEO_CodingH263",
2535        "OMX_VIDEO_CodingMPEG4",
2536        "OMX_VIDEO_CodingWMV",
2537        "OMX_VIDEO_CodingRV",
2538        "OMX_VIDEO_CodingAVC",
2539        "OMX_VIDEO_CodingMJPEG",
2540    };
2541
2542    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2543
2544    if (type < 0 || (size_t)type >= numNames) {
2545        return "UNKNOWN";
2546    } else {
2547        return kNames[type];
2548    }
2549}
2550
2551static const char *audioCodingTypeString(OMX_AUDIO_CODINGTYPE type) {
2552    static const char *kNames[] = {
2553        "OMX_AUDIO_CodingUnused",
2554        "OMX_AUDIO_CodingAutoDetect",
2555        "OMX_AUDIO_CodingPCM",
2556        "OMX_AUDIO_CodingADPCM",
2557        "OMX_AUDIO_CodingAMR",
2558        "OMX_AUDIO_CodingGSMFR",
2559        "OMX_AUDIO_CodingGSMEFR",
2560        "OMX_AUDIO_CodingGSMHR",
2561        "OMX_AUDIO_CodingPDCFR",
2562        "OMX_AUDIO_CodingPDCEFR",
2563        "OMX_AUDIO_CodingPDCHR",
2564        "OMX_AUDIO_CodingTDMAFR",
2565        "OMX_AUDIO_CodingTDMAEFR",
2566        "OMX_AUDIO_CodingQCELP8",
2567        "OMX_AUDIO_CodingQCELP13",
2568        "OMX_AUDIO_CodingEVRC",
2569        "OMX_AUDIO_CodingSMV",
2570        "OMX_AUDIO_CodingG711",
2571        "OMX_AUDIO_CodingG723",
2572        "OMX_AUDIO_CodingG726",
2573        "OMX_AUDIO_CodingG729",
2574        "OMX_AUDIO_CodingAAC",
2575        "OMX_AUDIO_CodingMP3",
2576        "OMX_AUDIO_CodingSBC",
2577        "OMX_AUDIO_CodingVORBIS",
2578        "OMX_AUDIO_CodingWMA",
2579        "OMX_AUDIO_CodingRA",
2580        "OMX_AUDIO_CodingMIDI",
2581    };
2582
2583    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2584
2585    if (type < 0 || (size_t)type >= numNames) {
2586        return "UNKNOWN";
2587    } else {
2588        return kNames[type];
2589    }
2590}
2591
2592static const char *audioPCMModeString(OMX_AUDIO_PCMMODETYPE type) {
2593    static const char *kNames[] = {
2594        "OMX_AUDIO_PCMModeLinear",
2595        "OMX_AUDIO_PCMModeALaw",
2596        "OMX_AUDIO_PCMModeMULaw",
2597    };
2598
2599    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2600
2601    if (type < 0 || (size_t)type >= numNames) {
2602        return "UNKNOWN";
2603    } else {
2604        return kNames[type];
2605    }
2606}
2607
2608static const char *amrBandModeString(OMX_AUDIO_AMRBANDMODETYPE type) {
2609    static const char *kNames[] = {
2610        "OMX_AUDIO_AMRBandModeUnused",
2611        "OMX_AUDIO_AMRBandModeNB0",
2612        "OMX_AUDIO_AMRBandModeNB1",
2613        "OMX_AUDIO_AMRBandModeNB2",
2614        "OMX_AUDIO_AMRBandModeNB3",
2615        "OMX_AUDIO_AMRBandModeNB4",
2616        "OMX_AUDIO_AMRBandModeNB5",
2617        "OMX_AUDIO_AMRBandModeNB6",
2618        "OMX_AUDIO_AMRBandModeNB7",
2619        "OMX_AUDIO_AMRBandModeWB0",
2620        "OMX_AUDIO_AMRBandModeWB1",
2621        "OMX_AUDIO_AMRBandModeWB2",
2622        "OMX_AUDIO_AMRBandModeWB3",
2623        "OMX_AUDIO_AMRBandModeWB4",
2624        "OMX_AUDIO_AMRBandModeWB5",
2625        "OMX_AUDIO_AMRBandModeWB6",
2626        "OMX_AUDIO_AMRBandModeWB7",
2627        "OMX_AUDIO_AMRBandModeWB8",
2628    };
2629
2630    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2631
2632    if (type < 0 || (size_t)type >= numNames) {
2633        return "UNKNOWN";
2634    } else {
2635        return kNames[type];
2636    }
2637}
2638
2639static const char *amrFrameFormatString(OMX_AUDIO_AMRFRAMEFORMATTYPE type) {
2640    static const char *kNames[] = {
2641        "OMX_AUDIO_AMRFrameFormatConformance",
2642        "OMX_AUDIO_AMRFrameFormatIF1",
2643        "OMX_AUDIO_AMRFrameFormatIF2",
2644        "OMX_AUDIO_AMRFrameFormatFSF",
2645        "OMX_AUDIO_AMRFrameFormatRTPPayload",
2646        "OMX_AUDIO_AMRFrameFormatITU",
2647    };
2648
2649    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
2650
2651    if (type < 0 || (size_t)type >= numNames) {
2652        return "UNKNOWN";
2653    } else {
2654        return kNames[type];
2655    }
2656}
2657
2658void OMXCodec::dumpPortStatus(OMX_U32 portIndex) {
2659    OMX_PARAM_PORTDEFINITIONTYPE def;
2660    InitOMXParams(&def);
2661    def.nPortIndex = portIndex;
2662
2663    status_t err = mOMX->getParameter(
2664            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2665    CHECK_EQ(err, OK);
2666
2667    printf("%s Port = {\n", portIndex == kPortIndexInput ? "Input" : "Output");
2668
2669    CHECK((portIndex == kPortIndexInput && def.eDir == OMX_DirInput)
2670          || (portIndex == kPortIndexOutput && def.eDir == OMX_DirOutput));
2671
2672    printf("  nBufferCountActual = %ld\n", def.nBufferCountActual);
2673    printf("  nBufferCountMin = %ld\n", def.nBufferCountMin);
2674    printf("  nBufferSize = %ld\n", def.nBufferSize);
2675
2676    switch (def.eDomain) {
2677        case OMX_PortDomainImage:
2678        {
2679            const OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
2680
2681            printf("\n");
2682            printf("  // Image\n");
2683            printf("  nFrameWidth = %ld\n", imageDef->nFrameWidth);
2684            printf("  nFrameHeight = %ld\n", imageDef->nFrameHeight);
2685            printf("  nStride = %ld\n", imageDef->nStride);
2686
2687            printf("  eCompressionFormat = %s\n",
2688                   imageCompressionFormatString(imageDef->eCompressionFormat));
2689
2690            printf("  eColorFormat = %s\n",
2691                   colorFormatString(imageDef->eColorFormat));
2692
2693            break;
2694        }
2695
2696        case OMX_PortDomainVideo:
2697        {
2698            OMX_VIDEO_PORTDEFINITIONTYPE *videoDef = &def.format.video;
2699
2700            printf("\n");
2701            printf("  // Video\n");
2702            printf("  nFrameWidth = %ld\n", videoDef->nFrameWidth);
2703            printf("  nFrameHeight = %ld\n", videoDef->nFrameHeight);
2704            printf("  nStride = %ld\n", videoDef->nStride);
2705
2706            printf("  eCompressionFormat = %s\n",
2707                   videoCompressionFormatString(videoDef->eCompressionFormat));
2708
2709            printf("  eColorFormat = %s\n",
2710                   colorFormatString(videoDef->eColorFormat));
2711
2712            break;
2713        }
2714
2715        case OMX_PortDomainAudio:
2716        {
2717            OMX_AUDIO_PORTDEFINITIONTYPE *audioDef = &def.format.audio;
2718
2719            printf("\n");
2720            printf("  // Audio\n");
2721            printf("  eEncoding = %s\n",
2722                   audioCodingTypeString(audioDef->eEncoding));
2723
2724            if (audioDef->eEncoding == OMX_AUDIO_CodingPCM) {
2725                OMX_AUDIO_PARAM_PCMMODETYPE params;
2726                InitOMXParams(&params);
2727                params.nPortIndex = portIndex;
2728
2729                err = mOMX->getParameter(
2730                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
2731                CHECK_EQ(err, OK);
2732
2733                printf("  nSamplingRate = %ld\n", params.nSamplingRate);
2734                printf("  nChannels = %ld\n", params.nChannels);
2735                printf("  bInterleaved = %d\n", params.bInterleaved);
2736                printf("  nBitPerSample = %ld\n", params.nBitPerSample);
2737
2738                printf("  eNumData = %s\n",
2739                       params.eNumData == OMX_NumericalDataSigned
2740                        ? "signed" : "unsigned");
2741
2742                printf("  ePCMMode = %s\n", audioPCMModeString(params.ePCMMode));
2743            } else if (audioDef->eEncoding == OMX_AUDIO_CodingAMR) {
2744                OMX_AUDIO_PARAM_AMRTYPE amr;
2745                InitOMXParams(&amr);
2746                amr.nPortIndex = portIndex;
2747
2748                err = mOMX->getParameter(
2749                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
2750                CHECK_EQ(err, OK);
2751
2752                printf("  nChannels = %ld\n", amr.nChannels);
2753                printf("  eAMRBandMode = %s\n",
2754                        amrBandModeString(amr.eAMRBandMode));
2755                printf("  eAMRFrameFormat = %s\n",
2756                        amrFrameFormatString(amr.eAMRFrameFormat));
2757            }
2758
2759            break;
2760        }
2761
2762        default:
2763        {
2764            printf("  // Unknown\n");
2765            break;
2766        }
2767    }
2768
2769    printf("}\n");
2770}
2771
2772void OMXCodec::initOutputFormat(const sp<MetaData> &inputFormat) {
2773    mOutputFormat = new MetaData;
2774    mOutputFormat->setCString(kKeyDecoderComponent, mComponentName);
2775
2776    OMX_PARAM_PORTDEFINITIONTYPE def;
2777    InitOMXParams(&def);
2778    def.nPortIndex = kPortIndexOutput;
2779
2780    status_t err = mOMX->getParameter(
2781            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2782    CHECK_EQ(err, OK);
2783
2784    switch (def.eDomain) {
2785        case OMX_PortDomainImage:
2786        {
2787            OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
2788            CHECK_EQ(imageDef->eCompressionFormat, OMX_IMAGE_CodingUnused);
2789
2790            mOutputFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
2791            mOutputFormat->setInt32(kKeyColorFormat, imageDef->eColorFormat);
2792            mOutputFormat->setInt32(kKeyWidth, imageDef->nFrameWidth);
2793            mOutputFormat->setInt32(kKeyHeight, imageDef->nFrameHeight);
2794            break;
2795        }
2796
2797        case OMX_PortDomainAudio:
2798        {
2799            OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio;
2800
2801            if (audio_def->eEncoding == OMX_AUDIO_CodingPCM) {
2802                OMX_AUDIO_PARAM_PCMMODETYPE params;
2803                InitOMXParams(&params);
2804                params.nPortIndex = kPortIndexOutput;
2805
2806                err = mOMX->getParameter(
2807                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
2808                CHECK_EQ(err, OK);
2809
2810                CHECK_EQ(params.eNumData, OMX_NumericalDataSigned);
2811                CHECK_EQ(params.nBitPerSample, 16);
2812                CHECK_EQ(params.ePCMMode, OMX_AUDIO_PCMModeLinear);
2813
2814                int32_t numChannels, sampleRate;
2815                inputFormat->findInt32(kKeyChannelCount, &numChannels);
2816                inputFormat->findInt32(kKeySampleRate, &sampleRate);
2817
2818                if ((OMX_U32)numChannels != params.nChannels) {
2819                    LOGW("Codec outputs a different number of channels than "
2820                         "the input stream contains.");
2821                }
2822
2823                mOutputFormat->setCString(
2824                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
2825
2826                // Use the codec-advertised number of channels, as some
2827                // codecs appear to output stereo even if the input data is
2828                // mono.
2829                mOutputFormat->setInt32(kKeyChannelCount, params.nChannels);
2830
2831                // The codec-reported sampleRate is not reliable...
2832                mOutputFormat->setInt32(kKeySampleRate, sampleRate);
2833            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAMR) {
2834                OMX_AUDIO_PARAM_AMRTYPE amr;
2835                InitOMXParams(&amr);
2836                amr.nPortIndex = kPortIndexOutput;
2837
2838                err = mOMX->getParameter(
2839                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
2840                CHECK_EQ(err, OK);
2841
2842                CHECK_EQ(amr.nChannels, 1);
2843                mOutputFormat->setInt32(kKeyChannelCount, 1);
2844
2845                if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeNB0
2846                    && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeNB7) {
2847                    mOutputFormat->setCString(
2848                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB);
2849                    mOutputFormat->setInt32(kKeySampleRate, 8000);
2850                } else if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeWB0
2851                            && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeWB8) {
2852                    mOutputFormat->setCString(
2853                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB);
2854                    mOutputFormat->setInt32(kKeySampleRate, 16000);
2855                } else {
2856                    CHECK(!"Unknown AMR band mode.");
2857                }
2858            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAAC) {
2859                mOutputFormat->setCString(
2860                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
2861            } else {
2862                CHECK(!"Should not be here. Unknown audio encoding.");
2863            }
2864            break;
2865        }
2866
2867        case OMX_PortDomainVideo:
2868        {
2869            OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
2870
2871            if (video_def->eCompressionFormat == OMX_VIDEO_CodingUnused) {
2872                mOutputFormat->setCString(
2873                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
2874            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingMPEG4) {
2875                mOutputFormat->setCString(
2876                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
2877            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingH263) {
2878                mOutputFormat->setCString(
2879                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
2880            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingAVC) {
2881                mOutputFormat->setCString(
2882                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
2883            } else {
2884                CHECK(!"Unknown compression format.");
2885            }
2886
2887            if (!strcmp(mComponentName, "OMX.PV.avcdec")) {
2888                // This component appears to be lying to me.
2889                mOutputFormat->setInt32(
2890                        kKeyWidth, (video_def->nFrameWidth + 15) & -16);
2891                mOutputFormat->setInt32(
2892                        kKeyHeight, (video_def->nFrameHeight + 15) & -16);
2893            } else {
2894                mOutputFormat->setInt32(kKeyWidth, video_def->nFrameWidth);
2895                mOutputFormat->setInt32(kKeyHeight, video_def->nFrameHeight);
2896            }
2897
2898            mOutputFormat->setInt32(kKeyColorFormat, video_def->eColorFormat);
2899            break;
2900        }
2901
2902        default:
2903        {
2904            CHECK(!"should not be here, neither audio nor video.");
2905            break;
2906        }
2907    }
2908}
2909
2910////////////////////////////////////////////////////////////////////////////////
2911
2912status_t QueryCodecs(
2913        const sp<IOMX> &omx,
2914        const char *mime, bool queryDecoders,
2915        Vector<CodecCapabilities> *results) {
2916    results->clear();
2917
2918    for (int index = 0;; ++index) {
2919        const char *componentName;
2920
2921        if (!queryDecoders) {
2922            componentName = GetCodec(
2923                    kEncoderInfo, sizeof(kEncoderInfo) / sizeof(kEncoderInfo[0]),
2924                    mime, index);
2925        } else {
2926            componentName = GetCodec(
2927                    kDecoderInfo, sizeof(kDecoderInfo) / sizeof(kDecoderInfo[0]),
2928                    mime, index);
2929        }
2930
2931        if (!componentName) {
2932            return OK;
2933        }
2934
2935        sp<OMXCodecObserver> observer = new OMXCodecObserver;
2936        IOMX::node_id node;
2937        status_t err = omx->allocateNode(componentName, observer, &node);
2938
2939        if (err != OK) {
2940            continue;
2941        }
2942
2943        OMXCodec::setComponentRole(omx, node, queryDecoders, mime);
2944
2945        results->push();
2946        CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
2947        caps->mComponentName = componentName;
2948
2949        OMX_VIDEO_PARAM_PROFILELEVELTYPE param;
2950        InitOMXParams(&param);
2951
2952        param.nPortIndex = queryDecoders ? 0 : 1;
2953
2954        for (param.nProfileIndex = 0;; ++param.nProfileIndex) {
2955            err = omx->getParameter(
2956                    node, OMX_IndexParamVideoProfileLevelQuerySupported,
2957                    &param, sizeof(param));
2958
2959            if (err != OK) {
2960                break;
2961            }
2962
2963            CodecProfileLevel profileLevel;
2964            profileLevel.mProfile = param.eProfile;
2965            profileLevel.mLevel = param.eLevel;
2966
2967            caps->mProfileLevels.push(profileLevel);
2968        }
2969
2970        CHECK_EQ(omx->freeNode(node), OK);
2971    }
2972}
2973
2974}  // namespace android
2975