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