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