OMXCodec.cpp revision b50a8033f1c7c2b58913212825f9200f1a9e5652
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 "include/AACDecoder.h"
22#include "include/AACEncoder.h"
23#include "include/AMRNBDecoder.h"
24#include "include/AMRNBEncoder.h"
25#include "include/AMRWBDecoder.h"
26#include "include/AMRWBEncoder.h"
27#include "include/AVCDecoder.h"
28#include "include/AVCEncoder.h"
29#include "include/G711Decoder.h"
30#include "include/M4vH263Decoder.h"
31#include "include/M4vH263Encoder.h"
32#include "include/MP3Decoder.h"
33#include "include/VorbisDecoder.h"
34#include "include/VPXDecoder.h"
35
36#include "include/ESDS.h"
37
38#include <binder/IServiceManager.h>
39#include <binder/MemoryDealer.h>
40#include <binder/ProcessState.h>
41#include <media/IMediaPlayerService.h>
42#include <media/stagefright/HardwareAPI.h>
43#include <media/stagefright/MediaBuffer.h>
44#include <media/stagefright/MediaBufferGroup.h>
45#include <media/stagefright/MediaDebug.h>
46#include <media/stagefright/MediaDefs.h>
47#include <media/stagefright/MediaExtractor.h>
48#include <media/stagefright/MetaData.h>
49#include <media/stagefright/OMXCodec.h>
50#include <media/stagefright/Utils.h>
51#include <utils/Vector.h>
52
53#include <OMX_Audio.h>
54#include <OMX_Component.h>
55
56#include "include/ThreadedSource.h"
57
58namespace android {
59
60static const int OMX_QCOM_COLOR_FormatYVU420SemiPlanar = 0x7FA30C00;
61
62struct CodecInfo {
63    const char *mime;
64    const char *codec;
65};
66
67#define FACTORY_CREATE(name) \
68static sp<MediaSource> Make##name(const sp<MediaSource> &source) { \
69    return new name(source); \
70}
71
72#define FACTORY_CREATE_ENCODER(name) \
73static sp<MediaSource> Make##name(const sp<MediaSource> &source, const sp<MetaData> &meta) { \
74    return new name(source, meta); \
75}
76
77#define FACTORY_REF(name) { #name, Make##name },
78
79FACTORY_CREATE(MP3Decoder)
80FACTORY_CREATE(AMRNBDecoder)
81FACTORY_CREATE(AMRWBDecoder)
82FACTORY_CREATE(AACDecoder)
83FACTORY_CREATE(AVCDecoder)
84FACTORY_CREATE(G711Decoder)
85FACTORY_CREATE(M4vH263Decoder)
86FACTORY_CREATE(VorbisDecoder)
87FACTORY_CREATE(VPXDecoder)
88FACTORY_CREATE_ENCODER(AMRNBEncoder)
89FACTORY_CREATE_ENCODER(AMRWBEncoder)
90FACTORY_CREATE_ENCODER(AACEncoder)
91FACTORY_CREATE_ENCODER(AVCEncoder)
92FACTORY_CREATE_ENCODER(M4vH263Encoder)
93
94static sp<MediaSource> InstantiateSoftwareEncoder(
95        const char *name, const sp<MediaSource> &source,
96        const sp<MetaData> &meta) {
97    struct FactoryInfo {
98        const char *name;
99        sp<MediaSource> (*CreateFunc)(const sp<MediaSource> &, const sp<MetaData> &);
100    };
101
102    static const FactoryInfo kFactoryInfo[] = {
103        FACTORY_REF(AMRNBEncoder)
104        FACTORY_REF(AMRWBEncoder)
105        FACTORY_REF(AACEncoder)
106        FACTORY_REF(AVCEncoder)
107        FACTORY_REF(M4vH263Encoder)
108    };
109    for (size_t i = 0;
110         i < sizeof(kFactoryInfo) / sizeof(kFactoryInfo[0]); ++i) {
111        if (!strcmp(name, kFactoryInfo[i].name)) {
112            return (*kFactoryInfo[i].CreateFunc)(source, meta);
113        }
114    }
115
116    return NULL;
117}
118
119static sp<MediaSource> InstantiateSoftwareCodec(
120        const char *name, const sp<MediaSource> &source) {
121    struct FactoryInfo {
122        const char *name;
123        sp<MediaSource> (*CreateFunc)(const sp<MediaSource> &);
124    };
125
126    static const FactoryInfo kFactoryInfo[] = {
127        FACTORY_REF(MP3Decoder)
128        FACTORY_REF(AMRNBDecoder)
129        FACTORY_REF(AMRWBDecoder)
130        FACTORY_REF(AACDecoder)
131        FACTORY_REF(AVCDecoder)
132        FACTORY_REF(G711Decoder)
133        FACTORY_REF(M4vH263Decoder)
134        FACTORY_REF(VorbisDecoder)
135        FACTORY_REF(VPXDecoder)
136    };
137    for (size_t i = 0;
138         i < sizeof(kFactoryInfo) / sizeof(kFactoryInfo[0]); ++i) {
139        if (!strcmp(name, kFactoryInfo[i].name)) {
140            if (!strcmp(name, "VPXDecoder")) {
141                return new ThreadedSource(
142                        (*kFactoryInfo[i].CreateFunc)(source));
143            }
144            return (*kFactoryInfo[i].CreateFunc)(source);
145        }
146    }
147
148    return NULL;
149}
150
151#undef FACTORY_REF
152#undef FACTORY_CREATE
153
154static const CodecInfo kDecoderInfo[] = {
155    { MEDIA_MIMETYPE_IMAGE_JPEG, "OMX.TI.JPEG.decode" },
156//    { MEDIA_MIMETYPE_AUDIO_MPEG, "OMX.Nvidia.mp3.decoder" },
157//    { MEDIA_MIMETYPE_AUDIO_MPEG, "OMX.TI.MP3.decode" },
158    { MEDIA_MIMETYPE_AUDIO_MPEG, "MP3Decoder" },
159//    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.TI.AMR.decode" },
160//    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.Nvidia.amr.decoder" },
161    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "AMRNBDecoder" },
162//    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.Nvidia.amrwb.decoder" },
163    { MEDIA_MIMETYPE_AUDIO_AMR_WB, "OMX.TI.WBAMR.decode" },
164    { MEDIA_MIMETYPE_AUDIO_AMR_WB, "AMRWBDecoder" },
165//    { MEDIA_MIMETYPE_AUDIO_AAC, "OMX.Nvidia.aac.decoder" },
166    { MEDIA_MIMETYPE_AUDIO_AAC, "OMX.TI.AAC.decode" },
167    { MEDIA_MIMETYPE_AUDIO_AAC, "AACDecoder" },
168    { MEDIA_MIMETYPE_AUDIO_G711_ALAW, "G711Decoder" },
169    { MEDIA_MIMETYPE_AUDIO_G711_MLAW, "G711Decoder" },
170    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.Nvidia.mp4.decode" },
171    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.qcom.7x30.video.decoder.mpeg4" },
172    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.qcom.video.decoder.mpeg4" },
173    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.TI.Video.Decoder" },
174    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.SEC.MPEG4.Decoder" },
175    { MEDIA_MIMETYPE_VIDEO_MPEG4, "M4vH263Decoder" },
176    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.Nvidia.h263.decode" },
177    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.qcom.7x30.video.decoder.h263" },
178    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.qcom.video.decoder.h263" },
179    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.SEC.H263.Decoder" },
180    { MEDIA_MIMETYPE_VIDEO_H263, "M4vH263Decoder" },
181    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.Nvidia.h264.decode" },
182    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.qcom.7x30.video.decoder.avc" },
183    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.qcom.video.decoder.avc" },
184    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.TI.Video.Decoder" },
185    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.SEC.AVC.Decoder" },
186    { MEDIA_MIMETYPE_VIDEO_AVC, "AVCDecoder" },
187    { MEDIA_MIMETYPE_AUDIO_VORBIS, "VorbisDecoder" },
188    { MEDIA_MIMETYPE_VIDEO_VPX, "VPXDecoder" },
189};
190
191static const CodecInfo kEncoderInfo[] = {
192    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "OMX.TI.AMR.encode" },
193    { MEDIA_MIMETYPE_AUDIO_AMR_NB, "AMRNBEncoder" },
194    { MEDIA_MIMETYPE_AUDIO_AMR_WB, "OMX.TI.WBAMR.encode" },
195    { MEDIA_MIMETYPE_AUDIO_AMR_WB, "AMRWBEncoder" },
196    { MEDIA_MIMETYPE_AUDIO_AAC, "OMX.TI.AAC.encode" },
197    { MEDIA_MIMETYPE_AUDIO_AAC, "AACEncoder" },
198    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.qcom.7x30.video.encoder.mpeg4" },
199    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.qcom.video.encoder.mpeg4" },
200    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.TI.Video.encoder" },
201    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.Nvidia.mp4.encoder" },
202    { MEDIA_MIMETYPE_VIDEO_MPEG4, "OMX.SEC.MPEG4.Encoder" },
203    { MEDIA_MIMETYPE_VIDEO_MPEG4, "M4vH263Encoder" },
204    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.qcom.7x30.video.encoder.h263" },
205    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.qcom.video.encoder.h263" },
206    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.TI.Video.encoder" },
207    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.Nvidia.h263.encoder" },
208    { MEDIA_MIMETYPE_VIDEO_H263, "OMX.SEC.H263.Encoder" },
209    { MEDIA_MIMETYPE_VIDEO_H263, "M4vH263Encoder" },
210    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.qcom.7x30.video.encoder.avc" },
211    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.qcom.video.encoder.avc" },
212    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.TI.Video.encoder" },
213    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.Nvidia.h264.encoder" },
214    { MEDIA_MIMETYPE_VIDEO_AVC, "OMX.SEC.AVC.Encoder" },
215    { MEDIA_MIMETYPE_VIDEO_AVC, "AVCEncoder" },
216};
217
218#undef OPTIONAL
219
220#define CODEC_LOGI(x, ...) LOGI("[%s] "x, mComponentName, ##__VA_ARGS__)
221#define CODEC_LOGV(x, ...) LOGV("[%s] "x, mComponentName, ##__VA_ARGS__)
222#define CODEC_LOGE(x, ...) LOGE("[%s] "x, mComponentName, ##__VA_ARGS__)
223
224struct OMXCodecObserver : public BnOMXObserver {
225    OMXCodecObserver() {
226    }
227
228    void setCodec(const sp<OMXCodec> &target) {
229        mTarget = target;
230    }
231
232    // from IOMXObserver
233    virtual void onMessage(const omx_message &msg) {
234        sp<OMXCodec> codec = mTarget.promote();
235
236        if (codec.get() != NULL) {
237            codec->on_message(msg);
238        }
239    }
240
241protected:
242    virtual ~OMXCodecObserver() {}
243
244private:
245    wp<OMXCodec> mTarget;
246
247    OMXCodecObserver(const OMXCodecObserver &);
248    OMXCodecObserver &operator=(const OMXCodecObserver &);
249};
250
251static const char *GetCodec(const CodecInfo *info, size_t numInfos,
252                            const char *mime, int index) {
253    CHECK(index >= 0);
254    for(size_t i = 0; i < numInfos; ++i) {
255        if (!strcasecmp(mime, info[i].mime)) {
256            if (index == 0) {
257                return info[i].codec;
258            }
259
260            --index;
261        }
262    }
263
264    return NULL;
265}
266
267enum {
268    kAVCProfileBaseline      = 0x42,
269    kAVCProfileMain          = 0x4d,
270    kAVCProfileExtended      = 0x58,
271    kAVCProfileHigh          = 0x64,
272    kAVCProfileHigh10        = 0x6e,
273    kAVCProfileHigh422       = 0x7a,
274    kAVCProfileHigh444       = 0xf4,
275    kAVCProfileCAVLC444Intra = 0x2c
276};
277
278static const char *AVCProfileToString(uint8_t profile) {
279    switch (profile) {
280        case kAVCProfileBaseline:
281            return "Baseline";
282        case kAVCProfileMain:
283            return "Main";
284        case kAVCProfileExtended:
285            return "Extended";
286        case kAVCProfileHigh:
287            return "High";
288        case kAVCProfileHigh10:
289            return "High 10";
290        case kAVCProfileHigh422:
291            return "High 422";
292        case kAVCProfileHigh444:
293            return "High 444";
294        case kAVCProfileCAVLC444Intra:
295            return "CAVLC 444 Intra";
296        default:   return "Unknown";
297    }
298}
299
300template<class T>
301static void InitOMXParams(T *params) {
302    params->nSize = sizeof(T);
303    params->nVersion.s.nVersionMajor = 1;
304    params->nVersion.s.nVersionMinor = 0;
305    params->nVersion.s.nRevision = 0;
306    params->nVersion.s.nStep = 0;
307}
308
309static bool IsSoftwareCodec(const char *componentName) {
310    if (!strncmp("OMX.", componentName, 4)) {
311        return false;
312    }
313
314    return true;
315}
316
317// A sort order in which non-OMX components are first,
318// followed by software codecs, and followed by all the others.
319static int CompareSoftwareCodecsFirst(
320        const String8 *elem1, const String8 *elem2) {
321    bool isNotOMX1 = strncmp(elem1->string(), "OMX.", 4);
322    bool isNotOMX2 = strncmp(elem2->string(), "OMX.", 4);
323
324    if (isNotOMX1) {
325        if (isNotOMX2) { return 0; }
326        return -1;
327    }
328    if (isNotOMX2) {
329        return 1;
330    }
331
332    bool isSoftwareCodec1 = IsSoftwareCodec(elem1->string());
333    bool isSoftwareCodec2 = IsSoftwareCodec(elem2->string());
334
335    if (isSoftwareCodec1) {
336        if (isSoftwareCodec2) { return 0; }
337        return -1;
338    }
339
340    if (isSoftwareCodec2) {
341        return 1;
342    }
343
344    return 0;
345}
346
347// static
348uint32_t OMXCodec::getComponentQuirks(
349        const char *componentName, bool isEncoder) {
350    uint32_t quirks = 0;
351
352    if (!strcmp(componentName, "OMX.Nvidia.amr.decoder") ||
353         !strcmp(componentName, "OMX.Nvidia.amrwb.decoder") ||
354         !strcmp(componentName, "OMX.Nvidia.aac.decoder") ||
355         !strcmp(componentName, "OMX.Nvidia.mp3.decoder")) {
356        quirks |= kDecoderLiesAboutNumberOfChannels;
357    }
358
359    if (!strcmp(componentName, "OMX.TI.MP3.decode")) {
360        quirks |= kNeedsFlushBeforeDisable;
361        quirks |= kDecoderLiesAboutNumberOfChannels;
362    }
363    if (!strcmp(componentName, "OMX.TI.AAC.decode")) {
364        quirks |= kNeedsFlushBeforeDisable;
365        quirks |= kRequiresFlushCompleteEmulation;
366        quirks |= kSupportsMultipleFramesPerInputBuffer;
367    }
368    if (!strncmp(componentName, "OMX.qcom.video.encoder.", 23)) {
369        quirks |= kRequiresLoadedToIdleAfterAllocation;
370        quirks |= kRequiresAllocateBufferOnInputPorts;
371        quirks |= kRequiresAllocateBufferOnOutputPorts;
372        if (!strncmp(componentName, "OMX.qcom.video.encoder.avc", 26)) {
373
374            // The AVC encoder advertises the size of output buffers
375            // based on the input video resolution and assumes
376            // the worst/least compression ratio is 0.5. It is found that
377            // sometimes, the output buffer size is larger than
378            // size advertised by the encoder.
379            quirks |= kRequiresLargerEncoderOutputBuffer;
380        }
381    }
382    if (!strncmp(componentName, "OMX.qcom.7x30.video.encoder.", 28)) {
383    }
384    if (!strncmp(componentName, "OMX.qcom.video.decoder.", 23)) {
385        quirks |= kRequiresAllocateBufferOnOutputPorts;
386        quirks |= kDefersOutputBufferAllocation;
387    }
388    if (!strncmp(componentName, "OMX.qcom.7x30.video.decoder.", 28)) {
389        quirks |= kRequiresAllocateBufferOnInputPorts;
390        quirks |= kRequiresAllocateBufferOnOutputPorts;
391        quirks |= kDefersOutputBufferAllocation;
392    }
393
394    if (!strncmp(componentName, "OMX.TI.", 7)) {
395        // Apparently I must not use OMX_UseBuffer on either input or
396        // output ports on any of the TI components or quote:
397        // "(I) may have unexpected problem (sic) which can be timing related
398        //  and hard to reproduce."
399
400        quirks |= kRequiresAllocateBufferOnInputPorts;
401        quirks |= kRequiresAllocateBufferOnOutputPorts;
402        if (!strncmp(componentName, "OMX.TI.Video.encoder", 20)) {
403            quirks |= kAvoidMemcopyInputRecordingFrames;
404        }
405    }
406
407    if (!strcmp(componentName, "OMX.TI.Video.Decoder")) {
408        quirks |= kInputBufferSizesAreBogus;
409    }
410
411    if (!strncmp(componentName, "OMX.SEC.", 8) && !isEncoder) {
412        // These output buffers contain no video data, just some
413        // opaque information that allows the overlay to display their
414        // contents.
415        quirks |= kOutputBuffersAreUnreadable;
416    }
417
418    return quirks;
419}
420
421// static
422void OMXCodec::findMatchingCodecs(
423        const char *mime,
424        bool createEncoder, const char *matchComponentName,
425        uint32_t flags,
426        Vector<String8> *matchingCodecs) {
427    matchingCodecs->clear();
428
429    for (int index = 0;; ++index) {
430        const char *componentName;
431
432        if (createEncoder) {
433            componentName = GetCodec(
434                    kEncoderInfo,
435                    sizeof(kEncoderInfo) / sizeof(kEncoderInfo[0]),
436                    mime, index);
437        } else {
438            componentName = GetCodec(
439                    kDecoderInfo,
440                    sizeof(kDecoderInfo) / sizeof(kDecoderInfo[0]),
441                    mime, index);
442        }
443
444        if (!componentName) {
445            break;
446        }
447
448        // If a specific codec is requested, skip the non-matching ones.
449        if (matchComponentName && strcmp(componentName, matchComponentName)) {
450            continue;
451        }
452
453        // When requesting software-only codecs, only push software codecs
454        // When requesting hardware-only codecs, only push hardware codecs
455        // When there is request neither for software-only nor for
456        // hardware-only codecs, push all codecs
457        if (((flags & kSoftwareCodecsOnly) &&   IsSoftwareCodec(componentName)) ||
458            ((flags & kHardwareCodecsOnly) &&  !IsSoftwareCodec(componentName)) ||
459            (!(flags & (kSoftwareCodecsOnly | kHardwareCodecsOnly)))) {
460
461            matchingCodecs->push(String8(componentName));
462        }
463    }
464
465    if (flags & kPreferSoftwareCodecs) {
466        matchingCodecs->sort(CompareSoftwareCodecsFirst);
467    }
468}
469
470// static
471sp<MediaSource> OMXCodec::Create(
472        const sp<IOMX> &omx,
473        const sp<MetaData> &meta, bool createEncoder,
474        const sp<MediaSource> &source,
475        const char *matchComponentName,
476        uint32_t flags,
477        const sp<ANativeWindow> &nativeWindow) {
478    const char *mime;
479    bool success = meta->findCString(kKeyMIMEType, &mime);
480    CHECK(success);
481
482    Vector<String8> matchingCodecs;
483    findMatchingCodecs(
484            mime, createEncoder, matchComponentName, flags, &matchingCodecs);
485
486    if (matchingCodecs.isEmpty()) {
487        return NULL;
488    }
489
490    sp<OMXCodecObserver> observer = new OMXCodecObserver;
491    IOMX::node_id node = 0;
492
493    const char *componentName;
494    for (size_t i = 0; i < matchingCodecs.size(); ++i) {
495        componentName = matchingCodecs[i].string();
496
497        sp<MediaSource> softwareCodec = createEncoder?
498            InstantiateSoftwareEncoder(componentName, source, meta):
499            InstantiateSoftwareCodec(componentName, source);
500
501        if (softwareCodec != NULL) {
502            LOGV("Successfully allocated software codec '%s'", componentName);
503
504            return softwareCodec;
505        }
506
507        LOGV("Attempting to allocate OMX node '%s'", componentName);
508
509        uint32_t quirks = getComponentQuirks(componentName, createEncoder);
510
511        if (!createEncoder
512                && (quirks & kOutputBuffersAreUnreadable)
513                && (flags & kClientNeedsFramebuffer)) {
514            if (strncmp(componentName, "OMX.SEC.", 8)) {
515                // For OMX.SEC.* decoders we can enable a special mode that
516                // gives the client access to the framebuffer contents.
517
518                LOGW("Component '%s' does not give the client access to "
519                     "the framebuffer contents. Skipping.",
520                     componentName);
521
522                continue;
523            }
524        }
525
526        status_t err = omx->allocateNode(componentName, observer, &node);
527        if (err == OK) {
528            LOGV("Successfully allocated OMX node '%s'", componentName);
529
530            sp<OMXCodec> codec = new OMXCodec(
531                    omx, node, quirks,
532                    createEncoder, mime, componentName,
533                    source, nativeWindow);
534
535            observer->setCodec(codec);
536
537            err = codec->configureCodec(meta, flags);
538
539            if (err == OK) {
540                return codec;
541            }
542
543            LOGV("Failed to configure codec '%s'", componentName);
544        }
545    }
546
547    return NULL;
548}
549
550status_t OMXCodec::configureCodec(const sp<MetaData> &meta, uint32_t flags) {
551    mIsMetaDataStoredInVideoBuffers = false;
552    if (flags & kStoreMetaDataInVideoBuffers) {
553        mIsMetaDataStoredInVideoBuffers = true;
554    }
555    if (!(flags & kIgnoreCodecSpecificData)) {
556        uint32_t type;
557        const void *data;
558        size_t size;
559        if (meta->findData(kKeyESDS, &type, &data, &size)) {
560            ESDS esds((const char *)data, size);
561            CHECK_EQ(esds.InitCheck(), OK);
562
563            const void *codec_specific_data;
564            size_t codec_specific_data_size;
565            esds.getCodecSpecificInfo(
566                    &codec_specific_data, &codec_specific_data_size);
567
568            addCodecSpecificData(
569                    codec_specific_data, codec_specific_data_size);
570        } else if (meta->findData(kKeyAVCC, &type, &data, &size)) {
571            // Parse the AVCDecoderConfigurationRecord
572
573            const uint8_t *ptr = (const uint8_t *)data;
574
575            CHECK(size >= 7);
576            CHECK_EQ(ptr[0], 1);  // configurationVersion == 1
577            uint8_t profile = ptr[1];
578            uint8_t level = ptr[3];
579
580            // There is decodable content out there that fails the following
581            // assertion, let's be lenient for now...
582            // CHECK((ptr[4] >> 2) == 0x3f);  // reserved
583
584            size_t lengthSize = 1 + (ptr[4] & 3);
585
586            // commented out check below as H264_QVGA_500_NO_AUDIO.3gp
587            // violates it...
588            // CHECK((ptr[5] >> 5) == 7);  // reserved
589
590            size_t numSeqParameterSets = ptr[5] & 31;
591
592            ptr += 6;
593            size -= 6;
594
595            for (size_t i = 0; i < numSeqParameterSets; ++i) {
596                CHECK(size >= 2);
597                size_t length = U16_AT(ptr);
598
599                ptr += 2;
600                size -= 2;
601
602                CHECK(size >= length);
603
604                addCodecSpecificData(ptr, length);
605
606                ptr += length;
607                size -= length;
608            }
609
610            CHECK(size >= 1);
611            size_t numPictureParameterSets = *ptr;
612            ++ptr;
613            --size;
614
615            for (size_t i = 0; i < numPictureParameterSets; ++i) {
616                CHECK(size >= 2);
617                size_t length = U16_AT(ptr);
618
619                ptr += 2;
620                size -= 2;
621
622                CHECK(size >= length);
623
624                addCodecSpecificData(ptr, length);
625
626                ptr += length;
627                size -= length;
628            }
629
630            CODEC_LOGV(
631                    "AVC profile = %d (%s), level = %d",
632                    (int)profile, AVCProfileToString(profile), level);
633
634            if (!strcmp(mComponentName, "OMX.TI.Video.Decoder")
635                && (profile != kAVCProfileBaseline || level > 30)) {
636                // This stream exceeds the decoder's capabilities. The decoder
637                // does not handle this gracefully and would clobber the heap
638                // and wreak havoc instead...
639
640                LOGE("Profile and/or level exceed the decoder's capabilities.");
641                return ERROR_UNSUPPORTED;
642            }
643        }
644    }
645
646    int32_t bitRate = 0;
647    if (mIsEncoder) {
648        CHECK(meta->findInt32(kKeyBitRate, &bitRate));
649    }
650    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_NB, mMIME)) {
651        setAMRFormat(false /* isWAMR */, bitRate);
652    }
653    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AMR_WB, mMIME)) {
654        setAMRFormat(true /* isWAMR */, bitRate);
655    }
656    if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_AAC, mMIME)) {
657        int32_t numChannels, sampleRate;
658        CHECK(meta->findInt32(kKeyChannelCount, &numChannels));
659        CHECK(meta->findInt32(kKeySampleRate, &sampleRate));
660
661        setAACFormat(numChannels, sampleRate, bitRate);
662    }
663
664    if (!strncasecmp(mMIME, "video/", 6)) {
665
666        if (mIsEncoder) {
667            setVideoInputFormat(mMIME, meta);
668        } else {
669            int32_t width, height;
670            bool success = meta->findInt32(kKeyWidth, &width);
671            success = success && meta->findInt32(kKeyHeight, &height);
672            CHECK(success);
673            status_t err = setVideoOutputFormat(
674                    mMIME, width, height);
675
676            if (err != OK) {
677                return err;
678            }
679        }
680    }
681
682    if (!strcasecmp(mMIME, MEDIA_MIMETYPE_IMAGE_JPEG)
683        && !strcmp(mComponentName, "OMX.TI.JPEG.decode")) {
684        OMX_COLOR_FORMATTYPE format =
685            OMX_COLOR_Format32bitARGB8888;
686            // OMX_COLOR_FormatYUV420PackedPlanar;
687            // OMX_COLOR_FormatCbYCrY;
688            // OMX_COLOR_FormatYUV411Planar;
689
690        int32_t width, height;
691        bool success = meta->findInt32(kKeyWidth, &width);
692        success = success && meta->findInt32(kKeyHeight, &height);
693
694        int32_t compressedSize;
695        success = success && meta->findInt32(
696                kKeyMaxInputSize, &compressedSize);
697
698        CHECK(success);
699        CHECK(compressedSize > 0);
700
701        setImageOutputFormat(format, width, height);
702        setJPEGInputFormat(width, height, (OMX_U32)compressedSize);
703    }
704
705    int32_t maxInputSize;
706    if (meta->findInt32(kKeyMaxInputSize, &maxInputSize)) {
707        setMinBufferSize(kPortIndexInput, (OMX_U32)maxInputSize);
708    }
709
710    if (!strcmp(mComponentName, "OMX.TI.AMR.encode")
711        || !strcmp(mComponentName, "OMX.TI.WBAMR.encode")
712        || !strcmp(mComponentName, "OMX.TI.AAC.encode")) {
713        setMinBufferSize(kPortIndexOutput, 8192);  // XXX
714    }
715
716    initOutputFormat(meta);
717
718    if ((flags & kClientNeedsFramebuffer)
719            && !strncmp(mComponentName, "OMX.SEC.", 8)) {
720        OMX_INDEXTYPE index;
721
722        status_t err =
723            mOMX->getExtensionIndex(
724                    mNode,
725                    "OMX.SEC.index.ThumbnailMode",
726                    &index);
727
728        if (err != OK) {
729            return err;
730        }
731
732        OMX_BOOL enable = OMX_TRUE;
733        err = mOMX->setConfig(mNode, index, &enable, sizeof(enable));
734
735        if (err != OK) {
736            CODEC_LOGE("setConfig('OMX.SEC.index.ThumbnailMode') "
737                       "returned error 0x%08x", err);
738
739            return err;
740        }
741
742        mQuirks &= ~kOutputBuffersAreUnreadable;
743    }
744
745    if (mNativeWindow != NULL
746        && !mIsEncoder
747        && !strncasecmp(mMIME, "video/", 6)
748        && !strncmp(mComponentName, "OMX.", 4)) {
749        status_t err = initNativeWindow();
750        if (err != OK) {
751            return err;
752        }
753    }
754
755    return OK;
756}
757
758void OMXCodec::setMinBufferSize(OMX_U32 portIndex, OMX_U32 size) {
759    OMX_PARAM_PORTDEFINITIONTYPE def;
760    InitOMXParams(&def);
761    def.nPortIndex = portIndex;
762
763    status_t err = mOMX->getParameter(
764            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
765    CHECK_EQ(err, OK);
766
767    if ((portIndex == kPortIndexInput && (mQuirks & kInputBufferSizesAreBogus))
768        || (def.nBufferSize < size)) {
769        def.nBufferSize = size;
770    }
771
772    err = mOMX->setParameter(
773            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
774    CHECK_EQ(err, OK);
775
776    err = mOMX->getParameter(
777            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
778    CHECK_EQ(err, OK);
779
780    // Make sure the setting actually stuck.
781    if (portIndex == kPortIndexInput
782            && (mQuirks & kInputBufferSizesAreBogus)) {
783        CHECK_EQ(def.nBufferSize, size);
784    } else {
785        CHECK(def.nBufferSize >= size);
786    }
787}
788
789status_t OMXCodec::setVideoPortFormatType(
790        OMX_U32 portIndex,
791        OMX_VIDEO_CODINGTYPE compressionFormat,
792        OMX_COLOR_FORMATTYPE colorFormat) {
793    OMX_VIDEO_PARAM_PORTFORMATTYPE format;
794    InitOMXParams(&format);
795    format.nPortIndex = portIndex;
796    format.nIndex = 0;
797    bool found = false;
798
799    OMX_U32 index = 0;
800    for (;;) {
801        format.nIndex = index;
802        status_t err = mOMX->getParameter(
803                mNode, OMX_IndexParamVideoPortFormat,
804                &format, sizeof(format));
805
806        if (err != OK) {
807            return err;
808        }
809
810        // The following assertion is violated by TI's video decoder.
811        // CHECK_EQ(format.nIndex, index);
812
813#if 1
814        CODEC_LOGV("portIndex: %ld, index: %ld, eCompressionFormat=%d eColorFormat=%d",
815             portIndex,
816             index, format.eCompressionFormat, format.eColorFormat);
817#endif
818
819        if (!strcmp("OMX.TI.Video.encoder", mComponentName)) {
820            if (portIndex == kPortIndexInput
821                    && colorFormat == format.eColorFormat) {
822                // eCompressionFormat does not seem right.
823                found = true;
824                break;
825            }
826            if (portIndex == kPortIndexOutput
827                    && compressionFormat == format.eCompressionFormat) {
828                // eColorFormat does not seem right.
829                found = true;
830                break;
831            }
832        }
833
834        if (format.eCompressionFormat == compressionFormat
835            && format.eColorFormat == colorFormat) {
836            found = true;
837            break;
838        }
839
840        ++index;
841    }
842
843    if (!found) {
844        return UNKNOWN_ERROR;
845    }
846
847    CODEC_LOGV("found a match.");
848    status_t err = mOMX->setParameter(
849            mNode, OMX_IndexParamVideoPortFormat,
850            &format, sizeof(format));
851
852    return err;
853}
854
855static size_t getFrameSize(
856        OMX_COLOR_FORMATTYPE colorFormat, int32_t width, int32_t height) {
857    switch (colorFormat) {
858        case OMX_COLOR_FormatYCbYCr:
859        case OMX_COLOR_FormatCbYCrY:
860            return width * height * 2;
861
862        case OMX_COLOR_FormatYUV420Planar:
863        case OMX_COLOR_FormatYUV420SemiPlanar:
864            return (width * height * 3) / 2;
865
866        default:
867            CHECK(!"Should not be here. Unsupported color format.");
868            break;
869    }
870}
871
872status_t OMXCodec::findTargetColorFormat(
873        const sp<MetaData>& meta, OMX_COLOR_FORMATTYPE *colorFormat) {
874    LOGV("findTargetColorFormat");
875    CHECK(mIsEncoder);
876
877    *colorFormat = OMX_COLOR_FormatYUV420SemiPlanar;
878    int32_t targetColorFormat;
879    if (meta->findInt32(kKeyColorFormat, &targetColorFormat)) {
880        *colorFormat = (OMX_COLOR_FORMATTYPE) targetColorFormat;
881    } else {
882        if (!strcasecmp("OMX.TI.Video.encoder", mComponentName)) {
883            *colorFormat = OMX_COLOR_FormatYCbYCr;
884        }
885    }
886
887    // Check whether the target color format is supported.
888    return isColorFormatSupported(*colorFormat, kPortIndexInput);
889}
890
891status_t OMXCodec::isColorFormatSupported(
892        OMX_COLOR_FORMATTYPE colorFormat, int portIndex) {
893    LOGV("isColorFormatSupported: %d", static_cast<int>(colorFormat));
894
895    // Enumerate all the color formats supported by
896    // the omx component to see whether the given
897    // color format is supported.
898    OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat;
899    InitOMXParams(&portFormat);
900    portFormat.nPortIndex = portIndex;
901    OMX_U32 index = 0;
902    portFormat.nIndex = index;
903    while (true) {
904        if (OMX_ErrorNone != mOMX->getParameter(
905                mNode, OMX_IndexParamVideoPortFormat,
906                &portFormat, sizeof(portFormat))) {
907            break;
908        }
909        // Make sure that omx component does not overwrite
910        // the incremented index (bug 2897413).
911        CHECK_EQ(index, portFormat.nIndex);
912        if ((portFormat.eColorFormat == colorFormat)) {
913            LOGV("Found supported color format: %d", portFormat.eColorFormat);
914            return OK;  // colorFormat is supported!
915        }
916        ++index;
917        portFormat.nIndex = index;
918
919        // OMX Spec defines less than 50 color formats
920        // 1000 is more than enough for us to tell whether the omx
921        // component in question is buggy or not.
922        if (index >= 1000) {
923            LOGE("More than %ld color formats are supported???", index);
924            break;
925        }
926    }
927
928    LOGE("color format %d is not supported", colorFormat);
929    return UNKNOWN_ERROR;
930}
931
932void OMXCodec::setVideoInputFormat(
933        const char *mime, const sp<MetaData>& meta) {
934
935    int32_t width, height, frameRate, bitRate, stride, sliceHeight;
936    bool success = meta->findInt32(kKeyWidth, &width);
937    success = success && meta->findInt32(kKeyHeight, &height);
938    success = success && meta->findInt32(kKeySampleRate, &frameRate);
939    success = success && meta->findInt32(kKeyBitRate, &bitRate);
940    success = success && meta->findInt32(kKeyStride, &stride);
941    success = success && meta->findInt32(kKeySliceHeight, &sliceHeight);
942    CHECK(success);
943    CHECK(stride != 0);
944
945    OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused;
946    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
947        compressionFormat = OMX_VIDEO_CodingAVC;
948    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
949        compressionFormat = OMX_VIDEO_CodingMPEG4;
950    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
951        compressionFormat = OMX_VIDEO_CodingH263;
952    } else {
953        LOGE("Not a supported video mime type: %s", mime);
954        CHECK(!"Should not be here. Not a supported video mime type.");
955    }
956
957    OMX_COLOR_FORMATTYPE colorFormat;
958    CHECK_EQ(OK, findTargetColorFormat(meta, &colorFormat));
959
960    status_t err;
961    OMX_PARAM_PORTDEFINITIONTYPE def;
962    OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
963
964    //////////////////////// Input port /////////////////////////
965    CHECK_EQ(setVideoPortFormatType(
966            kPortIndexInput, OMX_VIDEO_CodingUnused,
967            colorFormat), OK);
968
969    InitOMXParams(&def);
970    def.nPortIndex = kPortIndexInput;
971
972    err = mOMX->getParameter(
973            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
974    CHECK_EQ(err, OK);
975
976    def.nBufferSize = getFrameSize(colorFormat,
977            stride > 0? stride: -stride, sliceHeight);
978
979    CHECK_EQ(def.eDomain, OMX_PortDomainVideo);
980
981    video_def->nFrameWidth = width;
982    video_def->nFrameHeight = height;
983    video_def->nStride = stride;
984    video_def->nSliceHeight = sliceHeight;
985    video_def->xFramerate = (frameRate << 16);  // Q16 format
986    video_def->eCompressionFormat = OMX_VIDEO_CodingUnused;
987    video_def->eColorFormat = colorFormat;
988
989    err = mOMX->setParameter(
990            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
991    CHECK_EQ(err, OK);
992
993    //////////////////////// Output port /////////////////////////
994    CHECK_EQ(setVideoPortFormatType(
995            kPortIndexOutput, compressionFormat, OMX_COLOR_FormatUnused),
996            OK);
997    InitOMXParams(&def);
998    def.nPortIndex = kPortIndexOutput;
999
1000    err = mOMX->getParameter(
1001            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1002
1003    CHECK_EQ(err, OK);
1004    CHECK_EQ(def.eDomain, OMX_PortDomainVideo);
1005
1006    video_def->nFrameWidth = width;
1007    video_def->nFrameHeight = height;
1008    video_def->xFramerate = 0;      // No need for output port
1009    video_def->nBitrate = bitRate;  // Q16 format
1010    video_def->eCompressionFormat = compressionFormat;
1011    video_def->eColorFormat = OMX_COLOR_FormatUnused;
1012    if (mQuirks & kRequiresLargerEncoderOutputBuffer) {
1013        // Increases the output buffer size
1014        def.nBufferSize = ((def.nBufferSize * 3) >> 1);
1015    }
1016
1017    err = mOMX->setParameter(
1018            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1019    CHECK_EQ(err, OK);
1020
1021    /////////////////// Codec-specific ////////////////////////
1022    switch (compressionFormat) {
1023        case OMX_VIDEO_CodingMPEG4:
1024        {
1025            CHECK_EQ(setupMPEG4EncoderParameters(meta), OK);
1026            break;
1027        }
1028
1029        case OMX_VIDEO_CodingH263:
1030            CHECK_EQ(setupH263EncoderParameters(meta), OK);
1031            break;
1032
1033        case OMX_VIDEO_CodingAVC:
1034        {
1035            CHECK_EQ(setupAVCEncoderParameters(meta), OK);
1036            break;
1037        }
1038
1039        default:
1040            CHECK(!"Support for this compressionFormat to be implemented.");
1041            break;
1042    }
1043}
1044
1045static OMX_U32 setPFramesSpacing(int32_t iFramesInterval, int32_t frameRate) {
1046    if (iFramesInterval < 0) {
1047        return 0xFFFFFFFF;
1048    } else if (iFramesInterval == 0) {
1049        return 0;
1050    }
1051    OMX_U32 ret = frameRate * iFramesInterval;
1052    CHECK(ret > 1);
1053    return ret;
1054}
1055
1056status_t OMXCodec::setupErrorCorrectionParameters() {
1057    OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE errorCorrectionType;
1058    InitOMXParams(&errorCorrectionType);
1059    errorCorrectionType.nPortIndex = kPortIndexOutput;
1060
1061    status_t err = mOMX->getParameter(
1062            mNode, OMX_IndexParamVideoErrorCorrection,
1063            &errorCorrectionType, sizeof(errorCorrectionType));
1064    if (err != OK) {
1065        LOGW("Error correction param query is not supported");
1066        return OK;  // Optional feature. Ignore this failure
1067    }
1068
1069    errorCorrectionType.bEnableHEC = OMX_FALSE;
1070    errorCorrectionType.bEnableResync = OMX_TRUE;
1071    errorCorrectionType.nResynchMarkerSpacing = 256;
1072    errorCorrectionType.bEnableDataPartitioning = OMX_FALSE;
1073    errorCorrectionType.bEnableRVLC = OMX_FALSE;
1074
1075    err = mOMX->setParameter(
1076            mNode, OMX_IndexParamVideoErrorCorrection,
1077            &errorCorrectionType, sizeof(errorCorrectionType));
1078    if (err != OK) {
1079        LOGW("Error correction param configuration is not supported");
1080    }
1081
1082    // Optional feature. Ignore the failure.
1083    return OK;
1084}
1085
1086status_t OMXCodec::setupBitRate(int32_t bitRate) {
1087    OMX_VIDEO_PARAM_BITRATETYPE bitrateType;
1088    InitOMXParams(&bitrateType);
1089    bitrateType.nPortIndex = kPortIndexOutput;
1090
1091    status_t err = mOMX->getParameter(
1092            mNode, OMX_IndexParamVideoBitrate,
1093            &bitrateType, sizeof(bitrateType));
1094    CHECK_EQ(err, OK);
1095
1096    bitrateType.eControlRate = OMX_Video_ControlRateVariable;
1097    bitrateType.nTargetBitrate = bitRate;
1098
1099    err = mOMX->setParameter(
1100            mNode, OMX_IndexParamVideoBitrate,
1101            &bitrateType, sizeof(bitrateType));
1102    CHECK_EQ(err, OK);
1103    return OK;
1104}
1105
1106status_t OMXCodec::getVideoProfileLevel(
1107        const sp<MetaData>& meta,
1108        const CodecProfileLevel& defaultProfileLevel,
1109        CodecProfileLevel &profileLevel) {
1110    CODEC_LOGV("Default profile: %ld, level %ld",
1111            defaultProfileLevel.mProfile, defaultProfileLevel.mLevel);
1112
1113    // Are the default profile and level overwriten?
1114    int32_t profile, level;
1115    if (!meta->findInt32(kKeyVideoProfile, &profile)) {
1116        profile = defaultProfileLevel.mProfile;
1117    }
1118    if (!meta->findInt32(kKeyVideoLevel, &level)) {
1119        level = defaultProfileLevel.mLevel;
1120    }
1121    CODEC_LOGV("Target profile: %d, level: %d", profile, level);
1122
1123    // Are the target profile and level supported by the encoder?
1124    OMX_VIDEO_PARAM_PROFILELEVELTYPE param;
1125    InitOMXParams(&param);
1126    param.nPortIndex = kPortIndexOutput;
1127    for (param.nProfileIndex = 0;; ++param.nProfileIndex) {
1128        status_t err = mOMX->getParameter(
1129                mNode, OMX_IndexParamVideoProfileLevelQuerySupported,
1130                &param, sizeof(param));
1131
1132        if (err != OK) break;
1133
1134        int32_t supportedProfile = static_cast<int32_t>(param.eProfile);
1135        int32_t supportedLevel = static_cast<int32_t>(param.eLevel);
1136        CODEC_LOGV("Supported profile: %d, level %d",
1137            supportedProfile, supportedLevel);
1138
1139        if (profile == supportedProfile &&
1140            level <= supportedLevel) {
1141            // We can further check whether the level is a valid
1142            // value; but we will leave that to the omx encoder component
1143            // via OMX_SetParameter call.
1144            profileLevel.mProfile = profile;
1145            profileLevel.mLevel = level;
1146            return OK;
1147        }
1148    }
1149
1150    CODEC_LOGE("Target profile (%d) and level (%d) is not supported",
1151            profile, level);
1152    return BAD_VALUE;
1153}
1154
1155status_t OMXCodec::setupH263EncoderParameters(const sp<MetaData>& meta) {
1156    int32_t iFramesInterval, frameRate, bitRate;
1157    bool success = meta->findInt32(kKeyBitRate, &bitRate);
1158    success = success && meta->findInt32(kKeySampleRate, &frameRate);
1159    success = success && meta->findInt32(kKeyIFramesInterval, &iFramesInterval);
1160    CHECK(success);
1161    OMX_VIDEO_PARAM_H263TYPE h263type;
1162    InitOMXParams(&h263type);
1163    h263type.nPortIndex = kPortIndexOutput;
1164
1165    status_t err = mOMX->getParameter(
1166            mNode, OMX_IndexParamVideoH263, &h263type, sizeof(h263type));
1167    CHECK_EQ(err, OK);
1168
1169    h263type.nAllowedPictureTypes =
1170        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
1171
1172    h263type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate);
1173    if (h263type.nPFrames == 0) {
1174        h263type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI;
1175    }
1176    h263type.nBFrames = 0;
1177
1178    // Check profile and level parameters
1179    CodecProfileLevel defaultProfileLevel, profileLevel;
1180    defaultProfileLevel.mProfile = h263type.eProfile;
1181    defaultProfileLevel.mLevel = h263type.eLevel;
1182    err = getVideoProfileLevel(meta, defaultProfileLevel, profileLevel);
1183    if (err != OK) return err;
1184    h263type.eProfile = static_cast<OMX_VIDEO_H263PROFILETYPE>(profileLevel.mProfile);
1185    h263type.eLevel = static_cast<OMX_VIDEO_H263LEVELTYPE>(profileLevel.mLevel);
1186
1187    h263type.bPLUSPTYPEAllowed = OMX_FALSE;
1188    h263type.bForceRoundingTypeToZero = OMX_FALSE;
1189    h263type.nPictureHeaderRepetition = 0;
1190    h263type.nGOBHeaderInterval = 0;
1191
1192    err = mOMX->setParameter(
1193            mNode, OMX_IndexParamVideoH263, &h263type, sizeof(h263type));
1194    CHECK_EQ(err, OK);
1195
1196    CHECK_EQ(setupBitRate(bitRate), OK);
1197    CHECK_EQ(setupErrorCorrectionParameters(), OK);
1198
1199    return OK;
1200}
1201
1202status_t OMXCodec::setupMPEG4EncoderParameters(const sp<MetaData>& meta) {
1203    int32_t iFramesInterval, frameRate, bitRate;
1204    bool success = meta->findInt32(kKeyBitRate, &bitRate);
1205    success = success && meta->findInt32(kKeySampleRate, &frameRate);
1206    success = success && meta->findInt32(kKeyIFramesInterval, &iFramesInterval);
1207    CHECK(success);
1208    OMX_VIDEO_PARAM_MPEG4TYPE mpeg4type;
1209    InitOMXParams(&mpeg4type);
1210    mpeg4type.nPortIndex = kPortIndexOutput;
1211
1212    status_t err = mOMX->getParameter(
1213            mNode, OMX_IndexParamVideoMpeg4, &mpeg4type, sizeof(mpeg4type));
1214    CHECK_EQ(err, OK);
1215
1216    mpeg4type.nSliceHeaderSpacing = 0;
1217    mpeg4type.bSVH = OMX_FALSE;
1218    mpeg4type.bGov = OMX_FALSE;
1219
1220    mpeg4type.nAllowedPictureTypes =
1221        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
1222
1223    mpeg4type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate);
1224    if (mpeg4type.nPFrames == 0) {
1225        mpeg4type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI;
1226    }
1227    mpeg4type.nBFrames = 0;
1228    mpeg4type.nIDCVLCThreshold = 0;
1229    mpeg4type.bACPred = OMX_TRUE;
1230    mpeg4type.nMaxPacketSize = 256;
1231    mpeg4type.nTimeIncRes = 1000;
1232    mpeg4type.nHeaderExtension = 0;
1233    mpeg4type.bReversibleVLC = OMX_FALSE;
1234
1235    // Check profile and level parameters
1236    CodecProfileLevel defaultProfileLevel, profileLevel;
1237    defaultProfileLevel.mProfile = mpeg4type.eProfile;
1238    defaultProfileLevel.mLevel = mpeg4type.eLevel;
1239    err = getVideoProfileLevel(meta, defaultProfileLevel, profileLevel);
1240    if (err != OK) return err;
1241    mpeg4type.eProfile = static_cast<OMX_VIDEO_MPEG4PROFILETYPE>(profileLevel.mProfile);
1242    mpeg4type.eLevel = static_cast<OMX_VIDEO_MPEG4LEVELTYPE>(profileLevel.mLevel);
1243
1244    err = mOMX->setParameter(
1245            mNode, OMX_IndexParamVideoMpeg4, &mpeg4type, sizeof(mpeg4type));
1246    CHECK_EQ(err, OK);
1247
1248    CHECK_EQ(setupBitRate(bitRate), OK);
1249    CHECK_EQ(setupErrorCorrectionParameters(), OK);
1250
1251    return OK;
1252}
1253
1254status_t OMXCodec::setupAVCEncoderParameters(const sp<MetaData>& meta) {
1255    int32_t iFramesInterval, frameRate, bitRate;
1256    bool success = meta->findInt32(kKeyBitRate, &bitRate);
1257    success = success && meta->findInt32(kKeySampleRate, &frameRate);
1258    success = success && meta->findInt32(kKeyIFramesInterval, &iFramesInterval);
1259    CHECK(success);
1260
1261    OMX_VIDEO_PARAM_AVCTYPE h264type;
1262    InitOMXParams(&h264type);
1263    h264type.nPortIndex = kPortIndexOutput;
1264
1265    status_t err = mOMX->getParameter(
1266            mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type));
1267    CHECK_EQ(err, OK);
1268
1269    h264type.nAllowedPictureTypes =
1270        OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP;
1271
1272    h264type.nSliceHeaderSpacing = 0;
1273    h264type.nBFrames = 0;   // No B frames support yet
1274    h264type.nPFrames = setPFramesSpacing(iFramesInterval, frameRate);
1275    if (h264type.nPFrames == 0) {
1276        h264type.nAllowedPictureTypes = OMX_VIDEO_PictureTypeI;
1277    }
1278
1279    // Check profile and level parameters
1280    CodecProfileLevel defaultProfileLevel, profileLevel;
1281    defaultProfileLevel.mProfile = h264type.eProfile;
1282    defaultProfileLevel.mLevel = h264type.eLevel;
1283    err = getVideoProfileLevel(meta, defaultProfileLevel, profileLevel);
1284    if (err != OK) return err;
1285    h264type.eProfile = static_cast<OMX_VIDEO_AVCPROFILETYPE>(profileLevel.mProfile);
1286    h264type.eLevel = static_cast<OMX_VIDEO_AVCLEVELTYPE>(profileLevel.mLevel);
1287
1288    if (h264type.eProfile == OMX_VIDEO_AVCProfileBaseline) {
1289        h264type.bUseHadamard = OMX_TRUE;
1290        h264type.nRefFrames = 1;
1291        h264type.nRefIdx10ActiveMinus1 = 0;
1292        h264type.nRefIdx11ActiveMinus1 = 0;
1293        h264type.bEntropyCodingCABAC = OMX_FALSE;
1294        h264type.bWeightedPPrediction = OMX_FALSE;
1295        h264type.bconstIpred = OMX_FALSE;
1296        h264type.bDirect8x8Inference = OMX_FALSE;
1297        h264type.bDirectSpatialTemporal = OMX_FALSE;
1298        h264type.nCabacInitIdc = 0;
1299    }
1300
1301    if (h264type.nBFrames != 0) {
1302        h264type.nAllowedPictureTypes |= OMX_VIDEO_PictureTypeB;
1303    }
1304
1305    h264type.bEnableUEP = OMX_FALSE;
1306    h264type.bEnableFMO = OMX_FALSE;
1307    h264type.bEnableASO = OMX_FALSE;
1308    h264type.bEnableRS = OMX_FALSE;
1309    h264type.bFrameMBsOnly = OMX_TRUE;
1310    h264type.bMBAFF = OMX_FALSE;
1311    h264type.eLoopFilterMode = OMX_VIDEO_AVCLoopFilterEnable;
1312
1313    if (!strcasecmp("OMX.Nvidia.h264.encoder", mComponentName)) {
1314        h264type.eLevel = OMX_VIDEO_AVCLevelMax;
1315    }
1316
1317    err = mOMX->setParameter(
1318            mNode, OMX_IndexParamVideoAvc, &h264type, sizeof(h264type));
1319    CHECK_EQ(err, OK);
1320
1321    CHECK_EQ(setupBitRate(bitRate), OK);
1322
1323    return OK;
1324}
1325
1326status_t OMXCodec::setVideoOutputFormat(
1327        const char *mime, OMX_U32 width, OMX_U32 height) {
1328    CODEC_LOGV("setVideoOutputFormat width=%ld, height=%ld", width, height);
1329
1330    OMX_VIDEO_CODINGTYPE compressionFormat = OMX_VIDEO_CodingUnused;
1331    if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime)) {
1332        compressionFormat = OMX_VIDEO_CodingAVC;
1333    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_MPEG4, mime)) {
1334        compressionFormat = OMX_VIDEO_CodingMPEG4;
1335    } else if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_H263, mime)) {
1336        compressionFormat = OMX_VIDEO_CodingH263;
1337    } else {
1338        LOGE("Not a supported video mime type: %s", mime);
1339        CHECK(!"Should not be here. Not a supported video mime type.");
1340    }
1341
1342    status_t err = setVideoPortFormatType(
1343            kPortIndexInput, compressionFormat, OMX_COLOR_FormatUnused);
1344
1345    if (err != OK) {
1346        return err;
1347    }
1348
1349#if 1
1350    {
1351        OMX_VIDEO_PARAM_PORTFORMATTYPE format;
1352        InitOMXParams(&format);
1353        format.nPortIndex = kPortIndexOutput;
1354        format.nIndex = 0;
1355
1356        status_t err = mOMX->getParameter(
1357                mNode, OMX_IndexParamVideoPortFormat,
1358                &format, sizeof(format));
1359        CHECK_EQ(err, OK);
1360        CHECK_EQ(format.eCompressionFormat, OMX_VIDEO_CodingUnused);
1361
1362        static const int OMX_QCOM_COLOR_FormatYVU420SemiPlanar = 0x7FA30C00;
1363
1364        CHECK(format.eColorFormat == OMX_COLOR_FormatYUV420Planar
1365               || format.eColorFormat == OMX_COLOR_FormatYUV420SemiPlanar
1366               || format.eColorFormat == OMX_COLOR_FormatCbYCrY
1367               || format.eColorFormat == OMX_QCOM_COLOR_FormatYVU420SemiPlanar);
1368
1369        err = mOMX->setParameter(
1370                mNode, OMX_IndexParamVideoPortFormat,
1371                &format, sizeof(format));
1372
1373        if (err != OK) {
1374            return err;
1375        }
1376    }
1377#endif
1378
1379    OMX_PARAM_PORTDEFINITIONTYPE def;
1380    InitOMXParams(&def);
1381    def.nPortIndex = kPortIndexInput;
1382
1383    OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
1384
1385    err = mOMX->getParameter(
1386            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1387
1388    CHECK_EQ(err, OK);
1389
1390#if 1
1391    // XXX Need a (much) better heuristic to compute input buffer sizes.
1392    const size_t X = 64 * 1024;
1393    if (def.nBufferSize < X) {
1394        def.nBufferSize = X;
1395    }
1396#endif
1397
1398    CHECK_EQ(def.eDomain, OMX_PortDomainVideo);
1399
1400    video_def->nFrameWidth = width;
1401    video_def->nFrameHeight = height;
1402
1403    video_def->eCompressionFormat = compressionFormat;
1404    video_def->eColorFormat = OMX_COLOR_FormatUnused;
1405
1406    err = mOMX->setParameter(
1407            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1408
1409    if (err != OK) {
1410        return err;
1411    }
1412
1413    ////////////////////////////////////////////////////////////////////////////
1414
1415    InitOMXParams(&def);
1416    def.nPortIndex = kPortIndexOutput;
1417
1418    err = mOMX->getParameter(
1419            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1420    CHECK_EQ(err, OK);
1421    CHECK_EQ(def.eDomain, OMX_PortDomainVideo);
1422
1423#if 0
1424    def.nBufferSize =
1425        (((width + 15) & -16) * ((height + 15) & -16) * 3) / 2;  // YUV420
1426#endif
1427
1428    video_def->nFrameWidth = width;
1429    video_def->nFrameHeight = height;
1430
1431    err = mOMX->setParameter(
1432            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1433
1434    return err;
1435}
1436
1437OMXCodec::OMXCodec(
1438        const sp<IOMX> &omx, IOMX::node_id node, uint32_t quirks,
1439        bool isEncoder,
1440        const char *mime,
1441        const char *componentName,
1442        const sp<MediaSource> &source,
1443        const sp<ANativeWindow> &nativeWindow)
1444    : mOMX(omx),
1445      mOMXLivesLocally(omx->livesLocally(getpid())),
1446      mNode(node),
1447      mQuirks(quirks),
1448      mIsEncoder(isEncoder),
1449      mMIME(strdup(mime)),
1450      mComponentName(strdup(componentName)),
1451      mSource(source),
1452      mCodecSpecificDataIndex(0),
1453      mState(LOADED),
1454      mInitialBufferSubmit(true),
1455      mSignalledEOS(false),
1456      mNoMoreOutputData(false),
1457      mOutputPortSettingsHaveChanged(false),
1458      mSeekTimeUs(-1),
1459      mSeekMode(ReadOptions::SEEK_CLOSEST_SYNC),
1460      mTargetTimeUs(-1),
1461      mSkipTimeUs(-1),
1462      mLeftOverBuffer(NULL),
1463      mPaused(false),
1464      mNativeWindow(nativeWindow) {
1465    mPortStatus[kPortIndexInput] = ENABLED;
1466    mPortStatus[kPortIndexOutput] = ENABLED;
1467
1468    setComponentRole();
1469}
1470
1471// static
1472void OMXCodec::setComponentRole(
1473        const sp<IOMX> &omx, IOMX::node_id node, bool isEncoder,
1474        const char *mime) {
1475    struct MimeToRole {
1476        const char *mime;
1477        const char *decoderRole;
1478        const char *encoderRole;
1479    };
1480
1481    static const MimeToRole kMimeToRole[] = {
1482        { MEDIA_MIMETYPE_AUDIO_MPEG,
1483            "audio_decoder.mp3", "audio_encoder.mp3" },
1484        { MEDIA_MIMETYPE_AUDIO_AMR_NB,
1485            "audio_decoder.amrnb", "audio_encoder.amrnb" },
1486        { MEDIA_MIMETYPE_AUDIO_AMR_WB,
1487            "audio_decoder.amrwb", "audio_encoder.amrwb" },
1488        { MEDIA_MIMETYPE_AUDIO_AAC,
1489            "audio_decoder.aac", "audio_encoder.aac" },
1490        { MEDIA_MIMETYPE_VIDEO_AVC,
1491            "video_decoder.avc", "video_encoder.avc" },
1492        { MEDIA_MIMETYPE_VIDEO_MPEG4,
1493            "video_decoder.mpeg4", "video_encoder.mpeg4" },
1494        { MEDIA_MIMETYPE_VIDEO_H263,
1495            "video_decoder.h263", "video_encoder.h263" },
1496    };
1497
1498    static const size_t kNumMimeToRole =
1499        sizeof(kMimeToRole) / sizeof(kMimeToRole[0]);
1500
1501    size_t i;
1502    for (i = 0; i < kNumMimeToRole; ++i) {
1503        if (!strcasecmp(mime, kMimeToRole[i].mime)) {
1504            break;
1505        }
1506    }
1507
1508    if (i == kNumMimeToRole) {
1509        return;
1510    }
1511
1512    const char *role =
1513        isEncoder ? kMimeToRole[i].encoderRole
1514                  : kMimeToRole[i].decoderRole;
1515
1516    if (role != NULL) {
1517        OMX_PARAM_COMPONENTROLETYPE roleParams;
1518        InitOMXParams(&roleParams);
1519
1520        strncpy((char *)roleParams.cRole,
1521                role, OMX_MAX_STRINGNAME_SIZE - 1);
1522
1523        roleParams.cRole[OMX_MAX_STRINGNAME_SIZE - 1] = '\0';
1524
1525        status_t err = omx->setParameter(
1526                node, OMX_IndexParamStandardComponentRole,
1527                &roleParams, sizeof(roleParams));
1528
1529        if (err != OK) {
1530            LOGW("Failed to set standard component role '%s'.", role);
1531        }
1532    }
1533}
1534
1535void OMXCodec::setComponentRole() {
1536    setComponentRole(mOMX, mNode, mIsEncoder, mMIME);
1537}
1538
1539OMXCodec::~OMXCodec() {
1540    mSource.clear();
1541
1542    CHECK(mState == LOADED || mState == ERROR);
1543
1544    status_t err = mOMX->freeNode(mNode);
1545    CHECK_EQ(err, OK);
1546
1547    mNode = NULL;
1548    setState(DEAD);
1549
1550    clearCodecSpecificData();
1551
1552    free(mComponentName);
1553    mComponentName = NULL;
1554
1555    free(mMIME);
1556    mMIME = NULL;
1557}
1558
1559status_t OMXCodec::init() {
1560    // mLock is held.
1561
1562    CHECK_EQ(mState, LOADED);
1563
1564    status_t err;
1565    if (!(mQuirks & kRequiresLoadedToIdleAfterAllocation)) {
1566        err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
1567        CHECK_EQ(err, OK);
1568        setState(LOADED_TO_IDLE);
1569    }
1570
1571    err = allocateBuffers();
1572    CHECK_EQ(err, OK);
1573
1574    if (mQuirks & kRequiresLoadedToIdleAfterAllocation) {
1575        err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
1576        CHECK_EQ(err, OK);
1577
1578        setState(LOADED_TO_IDLE);
1579    }
1580
1581    while (mState != EXECUTING && mState != ERROR) {
1582        mAsyncCompletion.wait(mLock);
1583    }
1584
1585    return mState == ERROR ? UNKNOWN_ERROR : OK;
1586}
1587
1588// static
1589bool OMXCodec::isIntermediateState(State state) {
1590    return state == LOADED_TO_IDLE
1591        || state == IDLE_TO_EXECUTING
1592        || state == EXECUTING_TO_IDLE
1593        || state == IDLE_TO_LOADED
1594        || state == RECONFIGURING;
1595}
1596
1597status_t OMXCodec::allocateBuffers() {
1598    status_t err = allocateBuffersOnPort(kPortIndexInput);
1599
1600    if (err != OK) {
1601        return err;
1602    }
1603
1604    return allocateBuffersOnPort(kPortIndexOutput);
1605}
1606
1607status_t OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) {
1608    if (mNativeWindow != NULL && portIndex == kPortIndexOutput) {
1609        return allocateOutputBuffersFromNativeWindow();
1610    }
1611
1612    OMX_PARAM_PORTDEFINITIONTYPE def;
1613    InitOMXParams(&def);
1614    def.nPortIndex = portIndex;
1615
1616    status_t err = mOMX->getParameter(
1617            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1618
1619    if (err != OK) {
1620        return err;
1621    }
1622
1623    if (mIsMetaDataStoredInVideoBuffers && portIndex == kPortIndexInput) {
1624        err = mOMX->storeMetaDataInBuffers(mNode, kPortIndexInput, OMX_TRUE);
1625        if (err != OK) {
1626            LOGE("Storing meta data in video buffers is not supported");
1627            return err;
1628        }
1629    }
1630
1631    CODEC_LOGI("allocating %lu buffers of size %lu on %s port",
1632            def.nBufferCountActual, def.nBufferSize,
1633            portIndex == kPortIndexInput ? "input" : "output");
1634
1635    size_t totalSize = def.nBufferCountActual * def.nBufferSize;
1636    mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec");
1637
1638    for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
1639        sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize);
1640        CHECK(mem.get() != NULL);
1641
1642        BufferInfo info;
1643        info.mData = NULL;
1644        info.mSize = def.nBufferSize;
1645
1646        IOMX::buffer_id buffer;
1647        if (portIndex == kPortIndexInput
1648                && (mQuirks & kRequiresAllocateBufferOnInputPorts)) {
1649            if (mOMXLivesLocally) {
1650                mem.clear();
1651
1652                err = mOMX->allocateBuffer(
1653                        mNode, portIndex, def.nBufferSize, &buffer,
1654                        &info.mData);
1655            } else {
1656                err = mOMX->allocateBufferWithBackup(
1657                        mNode, portIndex, mem, &buffer);
1658            }
1659        } else if (portIndex == kPortIndexOutput
1660                && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) {
1661            if (mOMXLivesLocally) {
1662                mem.clear();
1663
1664                err = mOMX->allocateBuffer(
1665                        mNode, portIndex, def.nBufferSize, &buffer,
1666                        &info.mData);
1667            } else {
1668                err = mOMX->allocateBufferWithBackup(
1669                        mNode, portIndex, mem, &buffer);
1670            }
1671        } else {
1672            err = mOMX->useBuffer(mNode, portIndex, mem, &buffer);
1673        }
1674
1675        if (err != OK) {
1676            LOGE("allocate_buffer_with_backup failed");
1677            return err;
1678        }
1679
1680        if (mem != NULL) {
1681            info.mData = mem->pointer();
1682        }
1683
1684        info.mBuffer = buffer;
1685        info.mOwnedByComponent = false;
1686        info.mOwnedByNativeWindow = false;
1687        info.mMem = mem;
1688        info.mMediaBuffer = NULL;
1689
1690        if (portIndex == kPortIndexOutput) {
1691            if (!(mOMXLivesLocally
1692                        && (mQuirks & kRequiresAllocateBufferOnOutputPorts)
1693                        && (mQuirks & kDefersOutputBufferAllocation))) {
1694                // If the node does not fill in the buffer ptr at this time,
1695                // we will defer creating the MediaBuffer until receiving
1696                // the first FILL_BUFFER_DONE notification instead.
1697                info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize);
1698                info.mMediaBuffer->setObserver(this);
1699            }
1700        }
1701
1702        mPortBuffers[portIndex].push(info);
1703
1704        CODEC_LOGV("allocated buffer %p on %s port", buffer,
1705             portIndex == kPortIndexInput ? "input" : "output");
1706    }
1707
1708    // dumpPortStatus(portIndex);
1709
1710    return OK;
1711}
1712
1713status_t OMXCodec::allocateOutputBuffersFromNativeWindow() {
1714    // Get the number of buffers needed.
1715    OMX_PARAM_PORTDEFINITIONTYPE def;
1716    InitOMXParams(&def);
1717    def.nPortIndex = kPortIndexOutput;
1718
1719    status_t err = mOMX->getParameter(
1720            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1721    if (err != OK) {
1722        return err;
1723    }
1724
1725    err = native_window_set_buffers_geometry(
1726            mNativeWindow.get(),
1727            def.format.video.nFrameWidth,
1728            def.format.video.nFrameHeight,
1729            def.format.video.eColorFormat);
1730
1731    if (err != 0) {
1732        LOGE("native_window_set_buffers_geometry failed: %s (%d)",
1733                strerror(-err), -err);
1734        return err;
1735    }
1736
1737    // Increase the buffer count by one to allow for the ANativeWindow to hold
1738    // on to one of the buffers.
1739    def.nBufferCountActual++;
1740    err = mOMX->setParameter(
1741            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1742    if (err != OK) {
1743        return err;
1744    }
1745
1746    // Set up the native window.
1747    // XXX TODO: Get the gralloc usage flags from the OMX plugin!
1748    err = native_window_set_usage(
1749            mNativeWindow.get(), GRALLOC_USAGE_HW_TEXTURE);
1750    if (err != 0) {
1751        LOGE("native_window_set_usage failed: %s (%d)", strerror(-err), -err);
1752        return err;
1753    }
1754
1755    err = native_window_set_buffer_count(
1756            mNativeWindow.get(), def.nBufferCountActual);
1757    if (err != 0) {
1758        LOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err),
1759                -err);
1760        return err;
1761    }
1762
1763    // XXX TODO: Do something so the ANativeWindow knows that we'll need to get
1764    // the same set of buffers.
1765
1766    CODEC_LOGI("allocating %lu buffers from a native window of size %lu on "
1767            "output port", def.nBufferCountActual, def.nBufferSize);
1768
1769    // Dequeue buffers and send them to OMX
1770    OMX_U32 i;
1771    for (i = 0; i < def.nBufferCountActual; i++) {
1772        android_native_buffer_t* buf;
1773        err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf);
1774        if (err != 0) {
1775            LOGE("dequeueBuffer failed: %s (%d)", strerror(-err), -err);
1776            break;
1777        }
1778
1779        sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(buf, false));
1780        IOMX::buffer_id bufferId;
1781        err = mOMX->useGraphicBuffer(mNode, kPortIndexOutput, graphicBuffer,
1782                &bufferId);
1783        if (err != 0) {
1784            break;
1785        }
1786
1787        CODEC_LOGV("registered graphic buffer with ID %p (pointer = %p)",
1788                bufferId, graphicBuffer.get());
1789
1790        BufferInfo info;
1791        info.mData = NULL;
1792        info.mSize = def.nBufferSize;
1793        info.mBuffer = bufferId;
1794        info.mOwnedByComponent = false;
1795        info.mOwnedByNativeWindow = false;
1796        info.mMem = NULL;
1797        info.mMediaBuffer = new MediaBuffer(graphicBuffer);
1798        info.mMediaBuffer->setObserver(this);
1799
1800        mPortBuffers[kPortIndexOutput].push(info);
1801    }
1802
1803    OMX_U32 cancelStart;
1804    OMX_U32 cancelEnd;
1805
1806    if (err != 0) {
1807        // If an error occurred while dequeuing we need to cancel any buffers
1808        // that were dequeued.
1809        cancelStart = 0;
1810        cancelEnd = i;
1811    } else {
1812        // Return the last two buffers to the native window.
1813        // XXX TODO: The number of buffers the native window owns should probably be
1814        // queried from it when we put the native window in fixed buffer pool mode
1815        // (which needs to be implemented).  Currently it's hard-coded to 2.
1816        cancelStart = def.nBufferCountActual - 2;
1817        cancelEnd = def.nBufferCountActual;
1818    }
1819
1820    for (OMX_U32 i = cancelStart; i < cancelEnd; i++) {
1821        BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(i);
1822        cancelBufferToNativeWindow(info);
1823    }
1824
1825    return err;
1826}
1827
1828status_t OMXCodec::cancelBufferToNativeWindow(BufferInfo *info) {
1829    CHECK(!info->mOwnedByNativeWindow);
1830    CODEC_LOGV("Calling cancelBuffer on buffer %p", info->mBuffer);
1831    int err = mNativeWindow->cancelBuffer(
1832        mNativeWindow.get(), info->mMediaBuffer->graphicBuffer().get());
1833    if (err != 0) {
1834      CODEC_LOGE("cancelBuffer failed w/ error 0x%08x", err);
1835
1836      setState(ERROR);
1837      return err;
1838    }
1839    info->mOwnedByNativeWindow = true;
1840    return OK;
1841}
1842
1843OMXCodec::BufferInfo* OMXCodec::dequeueBufferFromNativeWindow() {
1844    // Dequeue the next buffer from the native window.
1845    android_native_buffer_t* buf;
1846    int err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf);
1847    if (err != 0) {
1848      CODEC_LOGE("dequeueBuffer failed w/ error 0x%08x", err);
1849
1850      setState(ERROR);
1851      return 0;
1852    }
1853
1854    // Determine which buffer we just dequeued.
1855    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
1856    BufferInfo *bufInfo = 0;
1857    for (size_t i = 0; i < buffers->size(); i++) {
1858      sp<GraphicBuffer> graphicBuffer = buffers->itemAt(i).
1859          mMediaBuffer->graphicBuffer();
1860      if (graphicBuffer->handle == buf->handle) {
1861        bufInfo = &buffers->editItemAt(i);
1862        break;
1863      }
1864    }
1865
1866    if (bufInfo == 0) {
1867        CODEC_LOGE("dequeued unrecognized buffer: %p", buf);
1868
1869        setState(ERROR);
1870        return 0;
1871    }
1872
1873    // The native window no longer owns the buffer.
1874    CHECK(bufInfo->mOwnedByNativeWindow);
1875    bufInfo->mOwnedByNativeWindow = false;
1876
1877    return bufInfo;
1878}
1879
1880void OMXCodec::on_message(const omx_message &msg) {
1881    Mutex::Autolock autoLock(mLock);
1882
1883    switch (msg.type) {
1884        case omx_message::EVENT:
1885        {
1886            onEvent(
1887                 msg.u.event_data.event, msg.u.event_data.data1,
1888                 msg.u.event_data.data2);
1889
1890            break;
1891        }
1892
1893        case omx_message::EMPTY_BUFFER_DONE:
1894        {
1895            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
1896
1897            CODEC_LOGV("EMPTY_BUFFER_DONE(buffer: %p)", buffer);
1898
1899            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
1900            size_t i = 0;
1901            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
1902                ++i;
1903            }
1904
1905            CHECK(i < buffers->size());
1906            if (!(*buffers)[i].mOwnedByComponent) {
1907                LOGW("We already own input buffer %p, yet received "
1908                     "an EMPTY_BUFFER_DONE.", buffer);
1909            }
1910
1911            BufferInfo* info = &buffers->editItemAt(i);
1912            info->mOwnedByComponent = false;
1913
1914            // Buffer could not be released until empty buffer done is called.
1915            if (info->mMediaBuffer != NULL) {
1916                if (mIsEncoder &&
1917                    (mQuirks & kAvoidMemcopyInputRecordingFrames)) {
1918                    // If zero-copy mode is enabled this will send the
1919                    // input buffer back to the upstream source.
1920                    restorePatchedDataPointer(info);
1921                }
1922
1923                info->mMediaBuffer->release();
1924                info->mMediaBuffer = NULL;
1925            }
1926
1927            if (mPortStatus[kPortIndexInput] == DISABLING) {
1928                CODEC_LOGV("Port is disabled, freeing buffer %p", buffer);
1929
1930                status_t err = freeBuffer(kPortIndexInput, i);
1931                CHECK_EQ(err, OK);
1932            } else if (mState != ERROR
1933                    && mPortStatus[kPortIndexInput] != SHUTTING_DOWN) {
1934                CHECK_EQ(mPortStatus[kPortIndexInput], ENABLED);
1935                drainInputBuffer(&buffers->editItemAt(i));
1936            }
1937            break;
1938        }
1939
1940        case omx_message::FILL_BUFFER_DONE:
1941        {
1942            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
1943            OMX_U32 flags = msg.u.extended_buffer_data.flags;
1944
1945            CODEC_LOGV("FILL_BUFFER_DONE(buffer: %p, size: %ld, flags: 0x%08lx, timestamp: %lld us (%.2f secs))",
1946                 buffer,
1947                 msg.u.extended_buffer_data.range_length,
1948                 flags,
1949                 msg.u.extended_buffer_data.timestamp,
1950                 msg.u.extended_buffer_data.timestamp / 1E6);
1951
1952            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
1953            size_t i = 0;
1954            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
1955                ++i;
1956            }
1957
1958            CHECK(i < buffers->size());
1959            BufferInfo *info = &buffers->editItemAt(i);
1960
1961            if (!info->mOwnedByComponent) {
1962                LOGW("We already own output buffer %p, yet received "
1963                     "a FILL_BUFFER_DONE.", buffer);
1964            }
1965
1966            info->mOwnedByComponent = false;
1967
1968            if (mPortStatus[kPortIndexOutput] == DISABLING) {
1969                CODEC_LOGV("Port is disabled, freeing buffer %p", buffer);
1970
1971                status_t err = freeBuffer(kPortIndexOutput, i);
1972                CHECK_EQ(err, OK);
1973
1974#if 0
1975            } else if (mPortStatus[kPortIndexOutput] == ENABLED
1976                       && (flags & OMX_BUFFERFLAG_EOS)) {
1977                CODEC_LOGV("No more output data.");
1978                mNoMoreOutputData = true;
1979                mBufferFilled.signal();
1980#endif
1981            } else if (mPortStatus[kPortIndexOutput] != SHUTTING_DOWN) {
1982                CHECK_EQ(mPortStatus[kPortIndexOutput], ENABLED);
1983
1984                if (info->mMediaBuffer == NULL) {
1985                    CHECK(mOMXLivesLocally);
1986                    CHECK(mQuirks & kRequiresAllocateBufferOnOutputPorts);
1987                    CHECK(mQuirks & kDefersOutputBufferAllocation);
1988
1989                    // The qcom video decoders on Nexus don't actually allocate
1990                    // output buffer memory on a call to OMX_AllocateBuffer
1991                    // the "pBuffer" member of the OMX_BUFFERHEADERTYPE
1992                    // structure is only filled in later.
1993
1994                    info->mMediaBuffer = new MediaBuffer(
1995                            msg.u.extended_buffer_data.data_ptr,
1996                            info->mSize);
1997                    info->mMediaBuffer->setObserver(this);
1998                }
1999
2000                MediaBuffer *buffer = info->mMediaBuffer;
2001                bool isGraphicBuffer = buffer->graphicBuffer() != NULL;
2002
2003                if (!isGraphicBuffer
2004                    && msg.u.extended_buffer_data.range_offset
2005                        + msg.u.extended_buffer_data.range_length
2006                            > buffer->size()) {
2007                    CODEC_LOGE(
2008                            "Codec lied about its buffer size requirements, "
2009                            "sending a buffer larger than the originally "
2010                            "advertised size in FILL_BUFFER_DONE!");
2011                }
2012                buffer->set_range(
2013                        msg.u.extended_buffer_data.range_offset,
2014                        msg.u.extended_buffer_data.range_length);
2015
2016                buffer->meta_data()->clear();
2017
2018                buffer->meta_data()->setInt64(
2019                        kKeyTime, msg.u.extended_buffer_data.timestamp);
2020
2021                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_SYNCFRAME) {
2022                    buffer->meta_data()->setInt32(kKeyIsSyncFrame, true);
2023                }
2024                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_CODECCONFIG) {
2025                    buffer->meta_data()->setInt32(kKeyIsCodecConfig, true);
2026                }
2027
2028                if (isGraphicBuffer || mQuirks & kOutputBuffersAreUnreadable) {
2029                    buffer->meta_data()->setInt32(kKeyIsUnreadable, true);
2030                }
2031
2032                buffer->meta_data()->setPointer(
2033                        kKeyPlatformPrivate,
2034                        msg.u.extended_buffer_data.platform_private);
2035
2036                buffer->meta_data()->setPointer(
2037                        kKeyBufferID,
2038                        msg.u.extended_buffer_data.buffer);
2039
2040                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_EOS) {
2041                    CODEC_LOGV("No more output data.");
2042                    mNoMoreOutputData = true;
2043                }
2044
2045                if (mTargetTimeUs >= 0) {
2046                    CHECK(msg.u.extended_buffer_data.timestamp <= mTargetTimeUs);
2047
2048                    if (msg.u.extended_buffer_data.timestamp < mTargetTimeUs) {
2049                        CODEC_LOGV(
2050                                "skipping output buffer at timestamp %lld us",
2051                                msg.u.extended_buffer_data.timestamp);
2052
2053                        fillOutputBuffer(info);
2054                        break;
2055                    }
2056
2057                    CODEC_LOGV(
2058                            "returning output buffer at target timestamp "
2059                            "%lld us",
2060                            msg.u.extended_buffer_data.timestamp);
2061
2062                    mTargetTimeUs = -1;
2063                }
2064
2065                mFilledBuffers.push_back(i);
2066                mBufferFilled.signal();
2067            }
2068
2069            break;
2070        }
2071
2072        default:
2073        {
2074            CHECK(!"should not be here.");
2075            break;
2076        }
2077    }
2078}
2079
2080void OMXCodec::onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) {
2081    switch (event) {
2082        case OMX_EventCmdComplete:
2083        {
2084            onCmdComplete((OMX_COMMANDTYPE)data1, data2);
2085            break;
2086        }
2087
2088        case OMX_EventError:
2089        {
2090            CODEC_LOGE("ERROR(0x%08lx, %ld)", data1, data2);
2091
2092            setState(ERROR);
2093            break;
2094        }
2095
2096        case OMX_EventPortSettingsChanged:
2097        {
2098            CODEC_LOGV("OMX_EventPortSettingsChanged(port=%ld, data2=0x%08lx)",
2099                       data1, data2);
2100
2101            if (data2 == 0 || data2 == OMX_IndexParamPortDefinition) {
2102                onPortSettingsChanged(data1);
2103            } else if (data1 == kPortIndexOutput
2104                    && data2 == OMX_IndexConfigCommonOutputCrop) {
2105
2106                OMX_CONFIG_RECTTYPE rect;
2107                rect.nPortIndex = kPortIndexOutput;
2108                InitOMXParams(&rect);
2109
2110                status_t err =
2111                         mOMX->getConfig(
2112                             mNode, OMX_IndexConfigCommonOutputCrop,
2113                             &rect, sizeof(rect));
2114
2115                if (err == OK) {
2116                    CODEC_LOGV(
2117                            "output crop (%ld, %ld, %ld, %ld)",
2118                            rect.nLeft, rect.nTop, rect.nWidth, rect.nHeight);
2119
2120                    if (mNativeWindow != NULL) {
2121                        android_native_rect_t crop;
2122                        crop.left = rect.nLeft;
2123                        crop.top = rect.nTop;
2124                        crop.right = crop.left + rect.nWidth - 1;
2125                        crop.bottom = crop.top + rect.nHeight - 1;
2126
2127                        CHECK_EQ(0, native_window_set_crop(
2128                                    mNativeWindow.get(), &crop));
2129                    }
2130                } else {
2131                    CODEC_LOGE("getConfig(OMX_IndexConfigCommonOutputCrop) "
2132                               "returned error 0x%08x", err);
2133                }
2134            }
2135            break;
2136        }
2137
2138#if 0
2139        case OMX_EventBufferFlag:
2140        {
2141            CODEC_LOGV("EVENT_BUFFER_FLAG(%ld)", data1);
2142
2143            if (data1 == kPortIndexOutput) {
2144                mNoMoreOutputData = true;
2145            }
2146            break;
2147        }
2148#endif
2149
2150        default:
2151        {
2152            CODEC_LOGV("EVENT(%d, %ld, %ld)", event, data1, data2);
2153            break;
2154        }
2155    }
2156}
2157
2158// Has the format changed in any way that the client would have to be aware of?
2159static bool formatHasNotablyChanged(
2160        const sp<MetaData> &from, const sp<MetaData> &to) {
2161    if (from.get() == NULL && to.get() == NULL) {
2162        return false;
2163    }
2164
2165    if ((from.get() == NULL && to.get() != NULL)
2166        || (from.get() != NULL && to.get() == NULL)) {
2167        return true;
2168    }
2169
2170    const char *mime_from, *mime_to;
2171    CHECK(from->findCString(kKeyMIMEType, &mime_from));
2172    CHECK(to->findCString(kKeyMIMEType, &mime_to));
2173
2174    if (strcasecmp(mime_from, mime_to)) {
2175        return true;
2176    }
2177
2178    if (!strcasecmp(mime_from, MEDIA_MIMETYPE_VIDEO_RAW)) {
2179        int32_t colorFormat_from, colorFormat_to;
2180        CHECK(from->findInt32(kKeyColorFormat, &colorFormat_from));
2181        CHECK(to->findInt32(kKeyColorFormat, &colorFormat_to));
2182
2183        if (colorFormat_from != colorFormat_to) {
2184            return true;
2185        }
2186
2187        int32_t width_from, width_to;
2188        CHECK(from->findInt32(kKeyWidth, &width_from));
2189        CHECK(to->findInt32(kKeyWidth, &width_to));
2190
2191        if (width_from != width_to) {
2192            return true;
2193        }
2194
2195        int32_t height_from, height_to;
2196        CHECK(from->findInt32(kKeyHeight, &height_from));
2197        CHECK(to->findInt32(kKeyHeight, &height_to));
2198
2199        if (height_from != height_to) {
2200            return true;
2201        }
2202    } else if (!strcasecmp(mime_from, MEDIA_MIMETYPE_AUDIO_RAW)) {
2203        int32_t numChannels_from, numChannels_to;
2204        CHECK(from->findInt32(kKeyChannelCount, &numChannels_from));
2205        CHECK(to->findInt32(kKeyChannelCount, &numChannels_to));
2206
2207        if (numChannels_from != numChannels_to) {
2208            return true;
2209        }
2210
2211        int32_t sampleRate_from, sampleRate_to;
2212        CHECK(from->findInt32(kKeySampleRate, &sampleRate_from));
2213        CHECK(to->findInt32(kKeySampleRate, &sampleRate_to));
2214
2215        if (sampleRate_from != sampleRate_to) {
2216            return true;
2217        }
2218    }
2219
2220    return false;
2221}
2222
2223void OMXCodec::onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data) {
2224    switch (cmd) {
2225        case OMX_CommandStateSet:
2226        {
2227            onStateChange((OMX_STATETYPE)data);
2228            break;
2229        }
2230
2231        case OMX_CommandPortDisable:
2232        {
2233            OMX_U32 portIndex = data;
2234            CODEC_LOGV("PORT_DISABLED(%ld)", portIndex);
2235
2236            CHECK(mState == EXECUTING || mState == RECONFIGURING);
2237            CHECK_EQ(mPortStatus[portIndex], DISABLING);
2238            CHECK_EQ(mPortBuffers[portIndex].size(), 0);
2239
2240            mPortStatus[portIndex] = DISABLED;
2241
2242            if (mState == RECONFIGURING) {
2243                CHECK_EQ(portIndex, kPortIndexOutput);
2244
2245                sp<MetaData> oldOutputFormat = mOutputFormat;
2246                initOutputFormat(mSource->getFormat());
2247
2248                // Don't notify clients if the output port settings change
2249                // wasn't of importance to them, i.e. it may be that just the
2250                // number of buffers has changed and nothing else.
2251                mOutputPortSettingsHaveChanged =
2252                    formatHasNotablyChanged(oldOutputFormat, mOutputFormat);
2253
2254                enablePortAsync(portIndex);
2255
2256                status_t err = allocateBuffersOnPort(portIndex);
2257                CHECK_EQ(err, OK);
2258            }
2259            break;
2260        }
2261
2262        case OMX_CommandPortEnable:
2263        {
2264            OMX_U32 portIndex = data;
2265            CODEC_LOGV("PORT_ENABLED(%ld)", portIndex);
2266
2267            CHECK(mState == EXECUTING || mState == RECONFIGURING);
2268            CHECK_EQ(mPortStatus[portIndex], ENABLING);
2269
2270            mPortStatus[portIndex] = ENABLED;
2271
2272            if (mState == RECONFIGURING) {
2273                CHECK_EQ(portIndex, kPortIndexOutput);
2274
2275                setState(EXECUTING);
2276
2277                fillOutputBuffers();
2278            }
2279            break;
2280        }
2281
2282        case OMX_CommandFlush:
2283        {
2284            OMX_U32 portIndex = data;
2285
2286            CODEC_LOGV("FLUSH_DONE(%ld)", portIndex);
2287
2288            CHECK_EQ(mPortStatus[portIndex], SHUTTING_DOWN);
2289            mPortStatus[portIndex] = ENABLED;
2290
2291            CHECK_EQ(countBuffersWeOwn(mPortBuffers[portIndex]),
2292                     mPortBuffers[portIndex].size());
2293
2294            if (mState == RECONFIGURING) {
2295                CHECK_EQ(portIndex, kPortIndexOutput);
2296
2297                disablePortAsync(portIndex);
2298            } else if (mState == EXECUTING_TO_IDLE) {
2299                if (mPortStatus[kPortIndexInput] == ENABLED
2300                    && mPortStatus[kPortIndexOutput] == ENABLED) {
2301                    CODEC_LOGV("Finished flushing both ports, now completing "
2302                         "transition from EXECUTING to IDLE.");
2303
2304                    mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
2305                    mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
2306
2307                    status_t err =
2308                        mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
2309                    CHECK_EQ(err, OK);
2310                }
2311            } else {
2312                // We're flushing both ports in preparation for seeking.
2313
2314                if (mPortStatus[kPortIndexInput] == ENABLED
2315                    && mPortStatus[kPortIndexOutput] == ENABLED) {
2316                    CODEC_LOGV("Finished flushing both ports, now continuing from"
2317                         " seek-time.");
2318
2319                    // We implicitly resume pulling on our upstream source.
2320                    mPaused = false;
2321
2322                    drainInputBuffers();
2323                    fillOutputBuffers();
2324                }
2325            }
2326
2327            break;
2328        }
2329
2330        default:
2331        {
2332            CODEC_LOGV("CMD_COMPLETE(%d, %ld)", cmd, data);
2333            break;
2334        }
2335    }
2336}
2337
2338void OMXCodec::onStateChange(OMX_STATETYPE newState) {
2339    CODEC_LOGV("onStateChange %d", newState);
2340
2341    switch (newState) {
2342        case OMX_StateIdle:
2343        {
2344            CODEC_LOGV("Now Idle.");
2345            if (mState == LOADED_TO_IDLE) {
2346                status_t err = mOMX->sendCommand(
2347                        mNode, OMX_CommandStateSet, OMX_StateExecuting);
2348
2349                CHECK_EQ(err, OK);
2350
2351                setState(IDLE_TO_EXECUTING);
2352            } else {
2353                CHECK_EQ(mState, EXECUTING_TO_IDLE);
2354
2355                CHECK_EQ(
2356                    countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
2357                    mPortBuffers[kPortIndexInput].size());
2358
2359                CHECK_EQ(
2360                    countBuffersWeOwn(mPortBuffers[kPortIndexOutput]),
2361                    mPortBuffers[kPortIndexOutput].size());
2362
2363                status_t err = mOMX->sendCommand(
2364                        mNode, OMX_CommandStateSet, OMX_StateLoaded);
2365
2366                CHECK_EQ(err, OK);
2367
2368                err = freeBuffersOnPort(kPortIndexInput);
2369                CHECK_EQ(err, OK);
2370
2371                err = freeBuffersOnPort(kPortIndexOutput);
2372                CHECK_EQ(err, OK);
2373
2374                mPortStatus[kPortIndexInput] = ENABLED;
2375                mPortStatus[kPortIndexOutput] = ENABLED;
2376
2377                setState(IDLE_TO_LOADED);
2378            }
2379            break;
2380        }
2381
2382        case OMX_StateExecuting:
2383        {
2384            CHECK_EQ(mState, IDLE_TO_EXECUTING);
2385
2386            CODEC_LOGV("Now Executing.");
2387
2388            setState(EXECUTING);
2389
2390            // Buffers will be submitted to the component in the first
2391            // call to OMXCodec::read as mInitialBufferSubmit is true at
2392            // this point. This ensures that this on_message call returns,
2393            // releases the lock and ::init can notice the state change and
2394            // itself return.
2395            break;
2396        }
2397
2398        case OMX_StateLoaded:
2399        {
2400            CHECK_EQ(mState, IDLE_TO_LOADED);
2401
2402            CODEC_LOGV("Now Loaded.");
2403
2404            setState(LOADED);
2405            break;
2406        }
2407
2408        case OMX_StateInvalid:
2409        {
2410            setState(ERROR);
2411            break;
2412        }
2413
2414        default:
2415        {
2416            CHECK(!"should not be here.");
2417            break;
2418        }
2419    }
2420}
2421
2422// static
2423size_t OMXCodec::countBuffersWeOwn(const Vector<BufferInfo> &buffers) {
2424    size_t n = 0;
2425    for (size_t i = 0; i < buffers.size(); ++i) {
2426        if (!buffers[i].mOwnedByComponent) {
2427            ++n;
2428        }
2429    }
2430
2431    return n;
2432}
2433
2434status_t OMXCodec::freeBuffersOnPort(
2435        OMX_U32 portIndex, bool onlyThoseWeOwn) {
2436    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
2437
2438    status_t stickyErr = OK;
2439
2440    for (size_t i = buffers->size(); i-- > 0;) {
2441        BufferInfo *info = &buffers->editItemAt(i);
2442
2443        if (onlyThoseWeOwn && info->mOwnedByComponent) {
2444            continue;
2445        }
2446
2447        CHECK_EQ(info->mOwnedByComponent, false);
2448
2449        CODEC_LOGV("freeing buffer %p on port %ld", info->mBuffer, portIndex);
2450
2451        status_t err = freeBuffer(portIndex, i);
2452
2453        if (err != OK) {
2454            stickyErr = err;
2455        }
2456
2457    }
2458
2459    CHECK(onlyThoseWeOwn || buffers->isEmpty());
2460
2461    return stickyErr;
2462}
2463
2464status_t OMXCodec::freeBuffer(OMX_U32 portIndex, size_t bufIndex) {
2465    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
2466
2467    BufferInfo *info = &buffers->editItemAt(bufIndex);
2468
2469    status_t err = mOMX->freeBuffer(mNode, portIndex, info->mBuffer);
2470
2471    if (err == OK && info->mMediaBuffer != NULL) {
2472        CHECK_EQ(portIndex, kPortIndexOutput);
2473        info->mMediaBuffer->setObserver(NULL);
2474
2475        // Make sure nobody but us owns this buffer at this point.
2476        CHECK_EQ(info->mMediaBuffer->refcount(), 0);
2477
2478        // Cancel the buffer if it belongs to an ANativeWindow.
2479        sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer();
2480        if (!info->mOwnedByNativeWindow && graphicBuffer != 0) {
2481            err = cancelBufferToNativeWindow(info);
2482        }
2483
2484        info->mMediaBuffer->release();
2485        info->mMediaBuffer = NULL;
2486    }
2487
2488    if (err == OK) {
2489        buffers->removeAt(bufIndex);
2490    }
2491
2492    return err;
2493}
2494
2495void OMXCodec::onPortSettingsChanged(OMX_U32 portIndex) {
2496    CODEC_LOGV("PORT_SETTINGS_CHANGED(%ld)", portIndex);
2497
2498    CHECK_EQ(mState, EXECUTING);
2499    CHECK_EQ(portIndex, kPortIndexOutput);
2500    setState(RECONFIGURING);
2501
2502    if (mQuirks & kNeedsFlushBeforeDisable) {
2503        if (!flushPortAsync(portIndex)) {
2504            onCmdComplete(OMX_CommandFlush, portIndex);
2505        }
2506    } else {
2507        disablePortAsync(portIndex);
2508    }
2509}
2510
2511bool OMXCodec::flushPortAsync(OMX_U32 portIndex) {
2512    CHECK(mState == EXECUTING || mState == RECONFIGURING
2513            || mState == EXECUTING_TO_IDLE);
2514
2515    CODEC_LOGV("flushPortAsync(%ld): we own %d out of %d buffers already.",
2516         portIndex, countBuffersWeOwn(mPortBuffers[portIndex]),
2517         mPortBuffers[portIndex].size());
2518
2519    CHECK_EQ(mPortStatus[portIndex], ENABLED);
2520    mPortStatus[portIndex] = SHUTTING_DOWN;
2521
2522    if ((mQuirks & kRequiresFlushCompleteEmulation)
2523        && countBuffersWeOwn(mPortBuffers[portIndex])
2524                == mPortBuffers[portIndex].size()) {
2525        // No flush is necessary and this component fails to send a
2526        // flush-complete event in this case.
2527
2528        return false;
2529    }
2530
2531    status_t err =
2532        mOMX->sendCommand(mNode, OMX_CommandFlush, portIndex);
2533    CHECK_EQ(err, OK);
2534
2535    return true;
2536}
2537
2538void OMXCodec::disablePortAsync(OMX_U32 portIndex) {
2539    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2540
2541    CHECK_EQ(mPortStatus[portIndex], ENABLED);
2542    mPortStatus[portIndex] = DISABLING;
2543
2544    CODEC_LOGV("sending OMX_CommandPortDisable(%ld)", portIndex);
2545    status_t err =
2546        mOMX->sendCommand(mNode, OMX_CommandPortDisable, portIndex);
2547    CHECK_EQ(err, OK);
2548
2549    freeBuffersOnPort(portIndex, true);
2550}
2551
2552void OMXCodec::enablePortAsync(OMX_U32 portIndex) {
2553    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2554
2555    CHECK_EQ(mPortStatus[portIndex], DISABLED);
2556    mPortStatus[portIndex] = ENABLING;
2557
2558    CODEC_LOGV("sending OMX_CommandPortEnable(%ld)", portIndex);
2559    status_t err =
2560        mOMX->sendCommand(mNode, OMX_CommandPortEnable, portIndex);
2561    CHECK_EQ(err, OK);
2562}
2563
2564void OMXCodec::fillOutputBuffers() {
2565    CHECK_EQ(mState, EXECUTING);
2566
2567    // This is a workaround for some decoders not properly reporting
2568    // end-of-output-stream. If we own all input buffers and also own
2569    // all output buffers and we already signalled end-of-input-stream,
2570    // the end-of-output-stream is implied.
2571    if (mSignalledEOS
2572            && countBuffersWeOwn(mPortBuffers[kPortIndexInput])
2573                == mPortBuffers[kPortIndexInput].size()
2574            && countBuffersWeOwn(mPortBuffers[kPortIndexOutput])
2575                == mPortBuffers[kPortIndexOutput].size()) {
2576        mNoMoreOutputData = true;
2577        mBufferFilled.signal();
2578
2579        return;
2580    }
2581
2582    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2583    for (size_t i = 0; i < buffers->size(); ++i) {
2584        BufferInfo *info = &buffers->editItemAt(i);
2585        if (!info->mOwnedByNativeWindow) {
2586            fillOutputBuffer(&buffers->editItemAt(i));
2587        }
2588    }
2589}
2590
2591void OMXCodec::drainInputBuffers() {
2592    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2593
2594    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2595    for (size_t i = 0; i < buffers->size(); ++i) {
2596        drainInputBuffer(&buffers->editItemAt(i));
2597    }
2598}
2599
2600void OMXCodec::drainInputBuffer(BufferInfo *info) {
2601    CHECK_EQ(info->mOwnedByComponent, false);
2602
2603    if (mSignalledEOS) {
2604        return;
2605    }
2606
2607    if (mCodecSpecificDataIndex < mCodecSpecificData.size()) {
2608        const CodecSpecificData *specific =
2609            mCodecSpecificData[mCodecSpecificDataIndex];
2610
2611        size_t size = specific->mSize;
2612
2613        if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mMIME)
2614                && !(mQuirks & kWantsNALFragments)) {
2615            static const uint8_t kNALStartCode[4] =
2616                    { 0x00, 0x00, 0x00, 0x01 };
2617
2618            CHECK(info->mSize >= specific->mSize + 4);
2619
2620            size += 4;
2621
2622            memcpy(info->mData, kNALStartCode, 4);
2623            memcpy((uint8_t *)info->mData + 4,
2624                   specific->mData, specific->mSize);
2625        } else {
2626            CHECK(info->mSize >= specific->mSize);
2627            memcpy(info->mData, specific->mData, specific->mSize);
2628        }
2629
2630        mNoMoreOutputData = false;
2631
2632        CODEC_LOGV("calling emptyBuffer with codec specific data");
2633
2634        status_t err = mOMX->emptyBuffer(
2635                mNode, info->mBuffer, 0, size,
2636                OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG,
2637                0);
2638        CHECK_EQ(err, OK);
2639
2640        info->mOwnedByComponent = true;
2641
2642        ++mCodecSpecificDataIndex;
2643        return;
2644    }
2645
2646    if (mPaused) {
2647        return;
2648    }
2649
2650    status_t err;
2651
2652    bool signalEOS = false;
2653    int64_t timestampUs = 0;
2654
2655    size_t offset = 0;
2656    int32_t n = 0;
2657    for (;;) {
2658        MediaBuffer *srcBuffer;
2659        MediaSource::ReadOptions options;
2660        if (mSkipTimeUs >= 0) {
2661            options.setSkipFrame(mSkipTimeUs);
2662        }
2663        if (mSeekTimeUs >= 0) {
2664            if (mLeftOverBuffer) {
2665                mLeftOverBuffer->release();
2666                mLeftOverBuffer = NULL;
2667            }
2668            options.setSeekTo(mSeekTimeUs, mSeekMode);
2669
2670            mSeekTimeUs = -1;
2671            mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC;
2672            mBufferFilled.signal();
2673
2674            err = mSource->read(&srcBuffer, &options);
2675
2676            if (err == OK) {
2677                int64_t targetTimeUs;
2678                if (srcBuffer->meta_data()->findInt64(
2679                            kKeyTargetTime, &targetTimeUs)
2680                        && targetTimeUs >= 0) {
2681                    mTargetTimeUs = targetTimeUs;
2682                } else {
2683                    mTargetTimeUs = -1;
2684                }
2685            }
2686        } else if (mLeftOverBuffer) {
2687            srcBuffer = mLeftOverBuffer;
2688            mLeftOverBuffer = NULL;
2689
2690            err = OK;
2691        } else {
2692            err = mSource->read(&srcBuffer, &options);
2693        }
2694
2695        if (err != OK) {
2696            signalEOS = true;
2697            mFinalStatus = err;
2698            mSignalledEOS = true;
2699            break;
2700        }
2701
2702        size_t remainingBytes = info->mSize - offset;
2703
2704        if (srcBuffer->range_length() > remainingBytes) {
2705            if (offset == 0) {
2706                CODEC_LOGE(
2707                     "Codec's input buffers are too small to accomodate "
2708                     "buffer read from source (info->mSize = %d, srcLength = %d)",
2709                     info->mSize, srcBuffer->range_length());
2710
2711                srcBuffer->release();
2712                srcBuffer = NULL;
2713
2714                setState(ERROR);
2715                return;
2716            }
2717
2718            mLeftOverBuffer = srcBuffer;
2719            break;
2720        }
2721
2722        bool releaseBuffer = true;
2723        if (mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames)) {
2724            CHECK(mOMXLivesLocally && offset == 0);
2725            OMX_BUFFERHEADERTYPE *header = (OMX_BUFFERHEADERTYPE *) info->mBuffer;
2726            CHECK(header->pBuffer == info->mData);
2727            header->pBuffer = (OMX_U8 *) srcBuffer->data() + srcBuffer->range_offset();
2728            releaseBuffer = false;
2729            info->mMediaBuffer = srcBuffer;
2730        } else {
2731            if (mIsMetaDataStoredInVideoBuffers) {
2732                releaseBuffer = false;
2733                info->mMediaBuffer = srcBuffer;
2734            }
2735            memcpy((uint8_t *)info->mData + offset,
2736                    (const uint8_t *)srcBuffer->data() + srcBuffer->range_offset(),
2737                    srcBuffer->range_length());
2738        }
2739
2740        int64_t lastBufferTimeUs;
2741        CHECK(srcBuffer->meta_data()->findInt64(kKeyTime, &lastBufferTimeUs));
2742        CHECK(lastBufferTimeUs >= 0);
2743
2744        if (offset == 0) {
2745            timestampUs = lastBufferTimeUs;
2746        }
2747
2748        offset += srcBuffer->range_length();
2749
2750        if (releaseBuffer) {
2751            srcBuffer->release();
2752            srcBuffer = NULL;
2753        }
2754
2755        ++n;
2756
2757        if (!(mQuirks & kSupportsMultipleFramesPerInputBuffer)) {
2758            break;
2759        }
2760
2761        int64_t coalescedDurationUs = lastBufferTimeUs - timestampUs;
2762
2763        if (coalescedDurationUs > 250000ll) {
2764            // Don't coalesce more than 250ms worth of encoded data at once.
2765            break;
2766        }
2767    }
2768
2769    if (n > 1) {
2770        LOGV("coalesced %d frames into one input buffer", n);
2771    }
2772
2773    OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME;
2774
2775    if (signalEOS) {
2776        flags |= OMX_BUFFERFLAG_EOS;
2777    } else {
2778        mNoMoreOutputData = false;
2779    }
2780
2781    CODEC_LOGV("Calling emptyBuffer on buffer %p (length %d), "
2782               "timestamp %lld us (%.2f secs)",
2783               info->mBuffer, offset,
2784               timestampUs, timestampUs / 1E6);
2785
2786    err = mOMX->emptyBuffer(
2787            mNode, info->mBuffer, 0, offset,
2788            flags, timestampUs);
2789
2790    if (err != OK) {
2791        setState(ERROR);
2792        return;
2793    }
2794
2795    info->mOwnedByComponent = true;
2796
2797    // This component does not ever signal the EOS flag on output buffers,
2798    // Thanks for nothing.
2799    if (mSignalledEOS && !strcmp(mComponentName, "OMX.TI.Video.encoder")) {
2800        mNoMoreOutputData = true;
2801        mBufferFilled.signal();
2802    }
2803}
2804
2805void OMXCodec::fillOutputBuffer(BufferInfo *info) {
2806    CHECK_EQ(info->mOwnedByComponent, false);
2807
2808    if (mNoMoreOutputData) {
2809        CODEC_LOGV("There is no more output data available, not "
2810             "calling fillOutputBuffer");
2811        return;
2812    }
2813
2814    sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer();
2815    if (graphicBuffer != 0) {
2816        // When using a native buffer we need to lock the buffer before giving
2817        // it to OMX.
2818        CHECK(!info->mOwnedByNativeWindow);
2819        CODEC_LOGV("Calling lockBuffer on %p", info->mBuffer);
2820        int err = mNativeWindow->lockBuffer(mNativeWindow.get(),
2821                graphicBuffer.get());
2822        if (err != 0) {
2823            CODEC_LOGE("lockBuffer failed w/ error 0x%08x", err);
2824
2825            setState(ERROR);
2826            return;
2827        }
2828    }
2829
2830    CODEC_LOGV("Calling fillBuffer on buffer %p", info->mBuffer);
2831    status_t err = mOMX->fillBuffer(mNode, info->mBuffer);
2832
2833    if (err != OK) {
2834        CODEC_LOGE("fillBuffer failed w/ error 0x%08x", err);
2835
2836        setState(ERROR);
2837        return;
2838    }
2839
2840    info->mOwnedByComponent = true;
2841}
2842
2843void OMXCodec::drainInputBuffer(IOMX::buffer_id buffer) {
2844    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2845    for (size_t i = 0; i < buffers->size(); ++i) {
2846        if ((*buffers)[i].mBuffer == buffer) {
2847            drainInputBuffer(&buffers->editItemAt(i));
2848            return;
2849        }
2850    }
2851
2852    CHECK(!"should not be here.");
2853}
2854
2855void OMXCodec::fillOutputBuffer(IOMX::buffer_id buffer) {
2856    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2857    for (size_t i = 0; i < buffers->size(); ++i) {
2858        if ((*buffers)[i].mBuffer == buffer) {
2859            fillOutputBuffer(&buffers->editItemAt(i));
2860            return;
2861        }
2862    }
2863
2864    CHECK(!"should not be here.");
2865}
2866
2867void OMXCodec::setState(State newState) {
2868    mState = newState;
2869    mAsyncCompletion.signal();
2870
2871    // This may cause some spurious wakeups but is necessary to
2872    // unblock the reader if we enter ERROR state.
2873    mBufferFilled.signal();
2874}
2875
2876void OMXCodec::setRawAudioFormat(
2877        OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels) {
2878
2879    // port definition
2880    OMX_PARAM_PORTDEFINITIONTYPE def;
2881    InitOMXParams(&def);
2882    def.nPortIndex = portIndex;
2883    status_t err = mOMX->getParameter(
2884            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2885    CHECK_EQ(err, OK);
2886    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
2887    CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition,
2888            &def, sizeof(def)), OK);
2889
2890    // pcm param
2891    OMX_AUDIO_PARAM_PCMMODETYPE pcmParams;
2892    InitOMXParams(&pcmParams);
2893    pcmParams.nPortIndex = portIndex;
2894
2895    err = mOMX->getParameter(
2896            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
2897
2898    CHECK_EQ(err, OK);
2899
2900    pcmParams.nChannels = numChannels;
2901    pcmParams.eNumData = OMX_NumericalDataSigned;
2902    pcmParams.bInterleaved = OMX_TRUE;
2903    pcmParams.nBitPerSample = 16;
2904    pcmParams.nSamplingRate = sampleRate;
2905    pcmParams.ePCMMode = OMX_AUDIO_PCMModeLinear;
2906
2907    if (numChannels == 1) {
2908        pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelCF;
2909    } else {
2910        CHECK_EQ(numChannels, 2);
2911
2912        pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelLF;
2913        pcmParams.eChannelMapping[1] = OMX_AUDIO_ChannelRF;
2914    }
2915
2916    err = mOMX->setParameter(
2917            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
2918
2919    CHECK_EQ(err, OK);
2920}
2921
2922static OMX_AUDIO_AMRBANDMODETYPE pickModeFromBitRate(bool isAMRWB, int32_t bps) {
2923    if (isAMRWB) {
2924        if (bps <= 6600) {
2925            return OMX_AUDIO_AMRBandModeWB0;
2926        } else if (bps <= 8850) {
2927            return OMX_AUDIO_AMRBandModeWB1;
2928        } else if (bps <= 12650) {
2929            return OMX_AUDIO_AMRBandModeWB2;
2930        } else if (bps <= 14250) {
2931            return OMX_AUDIO_AMRBandModeWB3;
2932        } else if (bps <= 15850) {
2933            return OMX_AUDIO_AMRBandModeWB4;
2934        } else if (bps <= 18250) {
2935            return OMX_AUDIO_AMRBandModeWB5;
2936        } else if (bps <= 19850) {
2937            return OMX_AUDIO_AMRBandModeWB6;
2938        } else if (bps <= 23050) {
2939            return OMX_AUDIO_AMRBandModeWB7;
2940        }
2941
2942        // 23850 bps
2943        return OMX_AUDIO_AMRBandModeWB8;
2944    } else {  // AMRNB
2945        if (bps <= 4750) {
2946            return OMX_AUDIO_AMRBandModeNB0;
2947        } else if (bps <= 5150) {
2948            return OMX_AUDIO_AMRBandModeNB1;
2949        } else if (bps <= 5900) {
2950            return OMX_AUDIO_AMRBandModeNB2;
2951        } else if (bps <= 6700) {
2952            return OMX_AUDIO_AMRBandModeNB3;
2953        } else if (bps <= 7400) {
2954            return OMX_AUDIO_AMRBandModeNB4;
2955        } else if (bps <= 7950) {
2956            return OMX_AUDIO_AMRBandModeNB5;
2957        } else if (bps <= 10200) {
2958            return OMX_AUDIO_AMRBandModeNB6;
2959        }
2960
2961        // 12200 bps
2962        return OMX_AUDIO_AMRBandModeNB7;
2963    }
2964}
2965
2966void OMXCodec::setAMRFormat(bool isWAMR, int32_t bitRate) {
2967    OMX_U32 portIndex = mIsEncoder ? kPortIndexOutput : kPortIndexInput;
2968
2969    OMX_AUDIO_PARAM_AMRTYPE def;
2970    InitOMXParams(&def);
2971    def.nPortIndex = portIndex;
2972
2973    status_t err =
2974        mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
2975
2976    CHECK_EQ(err, OK);
2977
2978    def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
2979
2980    def.eAMRBandMode = pickModeFromBitRate(isWAMR, bitRate);
2981    err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
2982    CHECK_EQ(err, OK);
2983
2984    ////////////////////////
2985
2986    if (mIsEncoder) {
2987        sp<MetaData> format = mSource->getFormat();
2988        int32_t sampleRate;
2989        int32_t numChannels;
2990        CHECK(format->findInt32(kKeySampleRate, &sampleRate));
2991        CHECK(format->findInt32(kKeyChannelCount, &numChannels));
2992
2993        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
2994    }
2995}
2996
2997void OMXCodec::setAACFormat(int32_t numChannels, int32_t sampleRate, int32_t bitRate) {
2998    CHECK(numChannels == 1 || numChannels == 2);
2999    if (mIsEncoder) {
3000        //////////////// input port ////////////////////
3001        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
3002
3003        //////////////// output port ////////////////////
3004        // format
3005        OMX_AUDIO_PARAM_PORTFORMATTYPE format;
3006        format.nPortIndex = kPortIndexOutput;
3007        format.nIndex = 0;
3008        status_t err = OMX_ErrorNone;
3009        while (OMX_ErrorNone == err) {
3010            CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioPortFormat,
3011                    &format, sizeof(format)), OK);
3012            if (format.eEncoding == OMX_AUDIO_CodingAAC) {
3013                break;
3014            }
3015            format.nIndex++;
3016        }
3017        CHECK_EQ(OK, err);
3018        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioPortFormat,
3019                &format, sizeof(format)), OK);
3020
3021        // port definition
3022        OMX_PARAM_PORTDEFINITIONTYPE def;
3023        InitOMXParams(&def);
3024        def.nPortIndex = kPortIndexOutput;
3025        CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamPortDefinition,
3026                &def, sizeof(def)), OK);
3027        def.format.audio.bFlagErrorConcealment = OMX_TRUE;
3028        def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
3029        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition,
3030                &def, sizeof(def)), OK);
3031
3032        // profile
3033        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
3034        InitOMXParams(&profile);
3035        profile.nPortIndex = kPortIndexOutput;
3036        CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioAac,
3037                &profile, sizeof(profile)), OK);
3038        profile.nChannels = numChannels;
3039        profile.eChannelMode = (numChannels == 1?
3040                OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo);
3041        profile.nSampleRate = sampleRate;
3042        profile.nBitRate = bitRate;
3043        profile.nAudioBandWidth = 0;
3044        profile.nFrameLength = 0;
3045        profile.nAACtools = OMX_AUDIO_AACToolAll;
3046        profile.nAACERtools = OMX_AUDIO_AACERNone;
3047        profile.eAACProfile = OMX_AUDIO_AACObjectLC;
3048        profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
3049        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioAac,
3050                &profile, sizeof(profile)), OK);
3051
3052    } else {
3053        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
3054        InitOMXParams(&profile);
3055        profile.nPortIndex = kPortIndexInput;
3056
3057        status_t err = mOMX->getParameter(
3058                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
3059        CHECK_EQ(err, OK);
3060
3061        profile.nChannels = numChannels;
3062        profile.nSampleRate = sampleRate;
3063        profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4ADTS;
3064
3065        err = mOMX->setParameter(
3066                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
3067        CHECK_EQ(err, OK);
3068    }
3069}
3070
3071void OMXCodec::setImageOutputFormat(
3072        OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height) {
3073    CODEC_LOGV("setImageOutputFormat(%ld, %ld)", width, height);
3074
3075#if 0
3076    OMX_INDEXTYPE index;
3077    status_t err = mOMX->get_extension_index(
3078            mNode, "OMX.TI.JPEG.decode.Config.OutputColorFormat", &index);
3079    CHECK_EQ(err, OK);
3080
3081    err = mOMX->set_config(mNode, index, &format, sizeof(format));
3082    CHECK_EQ(err, OK);
3083#endif
3084
3085    OMX_PARAM_PORTDEFINITIONTYPE def;
3086    InitOMXParams(&def);
3087    def.nPortIndex = kPortIndexOutput;
3088
3089    status_t err = mOMX->getParameter(
3090            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3091    CHECK_EQ(err, OK);
3092
3093    CHECK_EQ(def.eDomain, OMX_PortDomainImage);
3094
3095    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3096
3097    CHECK_EQ(imageDef->eCompressionFormat, OMX_IMAGE_CodingUnused);
3098    imageDef->eColorFormat = format;
3099    imageDef->nFrameWidth = width;
3100    imageDef->nFrameHeight = height;
3101
3102    switch (format) {
3103        case OMX_COLOR_FormatYUV420PackedPlanar:
3104        case OMX_COLOR_FormatYUV411Planar:
3105        {
3106            def.nBufferSize = (width * height * 3) / 2;
3107            break;
3108        }
3109
3110        case OMX_COLOR_FormatCbYCrY:
3111        {
3112            def.nBufferSize = width * height * 2;
3113            break;
3114        }
3115
3116        case OMX_COLOR_Format32bitARGB8888:
3117        {
3118            def.nBufferSize = width * height * 4;
3119            break;
3120        }
3121
3122        case OMX_COLOR_Format16bitARGB4444:
3123        case OMX_COLOR_Format16bitARGB1555:
3124        case OMX_COLOR_Format16bitRGB565:
3125        case OMX_COLOR_Format16bitBGR565:
3126        {
3127            def.nBufferSize = width * height * 2;
3128            break;
3129        }
3130
3131        default:
3132            CHECK(!"Should not be here. Unknown color format.");
3133            break;
3134    }
3135
3136    def.nBufferCountActual = def.nBufferCountMin;
3137
3138    err = mOMX->setParameter(
3139            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3140    CHECK_EQ(err, OK);
3141}
3142
3143void OMXCodec::setJPEGInputFormat(
3144        OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize) {
3145    OMX_PARAM_PORTDEFINITIONTYPE def;
3146    InitOMXParams(&def);
3147    def.nPortIndex = kPortIndexInput;
3148
3149    status_t err = mOMX->getParameter(
3150            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3151    CHECK_EQ(err, OK);
3152
3153    CHECK_EQ(def.eDomain, OMX_PortDomainImage);
3154    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3155
3156    CHECK_EQ(imageDef->eCompressionFormat, OMX_IMAGE_CodingJPEG);
3157    imageDef->nFrameWidth = width;
3158    imageDef->nFrameHeight = height;
3159
3160    def.nBufferSize = compressedSize;
3161    def.nBufferCountActual = def.nBufferCountMin;
3162
3163    err = mOMX->setParameter(
3164            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3165    CHECK_EQ(err, OK);
3166}
3167
3168void OMXCodec::addCodecSpecificData(const void *data, size_t size) {
3169    CodecSpecificData *specific =
3170        (CodecSpecificData *)malloc(sizeof(CodecSpecificData) + size - 1);
3171
3172    specific->mSize = size;
3173    memcpy(specific->mData, data, size);
3174
3175    mCodecSpecificData.push(specific);
3176}
3177
3178void OMXCodec::clearCodecSpecificData() {
3179    for (size_t i = 0; i < mCodecSpecificData.size(); ++i) {
3180        free(mCodecSpecificData.editItemAt(i));
3181    }
3182    mCodecSpecificData.clear();
3183    mCodecSpecificDataIndex = 0;
3184}
3185
3186status_t OMXCodec::start(MetaData *meta) {
3187    Mutex::Autolock autoLock(mLock);
3188
3189    if (mState != LOADED) {
3190        return UNKNOWN_ERROR;
3191    }
3192
3193    sp<MetaData> params = new MetaData;
3194    if (mQuirks & kWantsNALFragments) {
3195        params->setInt32(kKeyWantsNALFragments, true);
3196    }
3197    if (meta) {
3198        int64_t startTimeUs = 0;
3199        int64_t timeUs;
3200        if (meta->findInt64(kKeyTime, &timeUs)) {
3201            startTimeUs = timeUs;
3202        }
3203        params->setInt64(kKeyTime, startTimeUs);
3204    }
3205    status_t err = mSource->start(params.get());
3206
3207    if (err != OK) {
3208        return err;
3209    }
3210
3211    mCodecSpecificDataIndex = 0;
3212    mInitialBufferSubmit = true;
3213    mSignalledEOS = false;
3214    mNoMoreOutputData = false;
3215    mOutputPortSettingsHaveChanged = false;
3216    mSeekTimeUs = -1;
3217    mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC;
3218    mTargetTimeUs = -1;
3219    mFilledBuffers.clear();
3220    mPaused = false;
3221
3222    return init();
3223}
3224
3225status_t OMXCodec::stop() {
3226    CODEC_LOGV("stop mState=%d", mState);
3227
3228    Mutex::Autolock autoLock(mLock);
3229
3230    while (isIntermediateState(mState)) {
3231        mAsyncCompletion.wait(mLock);
3232    }
3233
3234    switch (mState) {
3235        case LOADED:
3236        case ERROR:
3237            break;
3238
3239        case EXECUTING:
3240        {
3241            setState(EXECUTING_TO_IDLE);
3242
3243            if (mQuirks & kRequiresFlushBeforeShutdown) {
3244                CODEC_LOGV("This component requires a flush before transitioning "
3245                     "from EXECUTING to IDLE...");
3246
3247                bool emulateInputFlushCompletion =
3248                    !flushPortAsync(kPortIndexInput);
3249
3250                bool emulateOutputFlushCompletion =
3251                    !flushPortAsync(kPortIndexOutput);
3252
3253                if (emulateInputFlushCompletion) {
3254                    onCmdComplete(OMX_CommandFlush, kPortIndexInput);
3255                }
3256
3257                if (emulateOutputFlushCompletion) {
3258                    onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
3259                }
3260            } else {
3261                mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
3262                mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
3263
3264                status_t err =
3265                    mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
3266                CHECK_EQ(err, OK);
3267            }
3268
3269            while (mState != LOADED && mState != ERROR) {
3270                mAsyncCompletion.wait(mLock);
3271            }
3272
3273            break;
3274        }
3275
3276        default:
3277        {
3278            CHECK(!"should not be here.");
3279            break;
3280        }
3281    }
3282
3283    if (mLeftOverBuffer) {
3284        mLeftOverBuffer->release();
3285        mLeftOverBuffer = NULL;
3286    }
3287
3288    mSource->stop();
3289
3290    CODEC_LOGV("stopped");
3291
3292    return OK;
3293}
3294
3295sp<MetaData> OMXCodec::getFormat() {
3296    Mutex::Autolock autoLock(mLock);
3297
3298    return mOutputFormat;
3299}
3300
3301status_t OMXCodec::read(
3302        MediaBuffer **buffer, const ReadOptions *options) {
3303    *buffer = NULL;
3304
3305    Mutex::Autolock autoLock(mLock);
3306
3307    if (mState != EXECUTING && mState != RECONFIGURING) {
3308        return UNKNOWN_ERROR;
3309    }
3310
3311    bool seeking = false;
3312    int64_t seekTimeUs;
3313    ReadOptions::SeekMode seekMode;
3314    if (options && options->getSeekTo(&seekTimeUs, &seekMode)) {
3315        seeking = true;
3316    }
3317    int64_t skipTimeUs;
3318    if (options && options->getSkipFrame(&skipTimeUs)) {
3319        mSkipTimeUs = skipTimeUs;
3320    } else {
3321        mSkipTimeUs = -1;
3322    }
3323
3324    if (mInitialBufferSubmit) {
3325        mInitialBufferSubmit = false;
3326
3327        if (seeking) {
3328            CHECK(seekTimeUs >= 0);
3329            mSeekTimeUs = seekTimeUs;
3330            mSeekMode = seekMode;
3331
3332            // There's no reason to trigger the code below, there's
3333            // nothing to flush yet.
3334            seeking = false;
3335            mPaused = false;
3336        }
3337
3338        drainInputBuffers();
3339
3340        if (mState == EXECUTING) {
3341            // Otherwise mState == RECONFIGURING and this code will trigger
3342            // after the output port is reenabled.
3343            fillOutputBuffers();
3344        }
3345    }
3346
3347    if (seeking) {
3348        CODEC_LOGV("seeking to %lld us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6);
3349
3350        mSignalledEOS = false;
3351
3352        CHECK(seekTimeUs >= 0);
3353        mSeekTimeUs = seekTimeUs;
3354        mSeekMode = seekMode;
3355
3356        mFilledBuffers.clear();
3357
3358        CHECK_EQ(mState, EXECUTING);
3359
3360        bool emulateInputFlushCompletion = !flushPortAsync(kPortIndexInput);
3361        bool emulateOutputFlushCompletion = !flushPortAsync(kPortIndexOutput);
3362
3363        if (emulateInputFlushCompletion) {
3364            onCmdComplete(OMX_CommandFlush, kPortIndexInput);
3365        }
3366
3367        if (emulateOutputFlushCompletion) {
3368            onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
3369        }
3370
3371        while (mSeekTimeUs >= 0) {
3372            mBufferFilled.wait(mLock);
3373        }
3374    }
3375
3376    while (mState != ERROR && !mNoMoreOutputData && mFilledBuffers.empty()) {
3377        mBufferFilled.wait(mLock);
3378    }
3379
3380    if (mState == ERROR) {
3381        return UNKNOWN_ERROR;
3382    }
3383
3384    if (mFilledBuffers.empty()) {
3385        return mSignalledEOS ? mFinalStatus : ERROR_END_OF_STREAM;
3386    }
3387
3388    if (mOutputPortSettingsHaveChanged) {
3389        mOutputPortSettingsHaveChanged = false;
3390
3391        return INFO_FORMAT_CHANGED;
3392    }
3393
3394    size_t index = *mFilledBuffers.begin();
3395    mFilledBuffers.erase(mFilledBuffers.begin());
3396
3397    BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index);
3398    info->mMediaBuffer->add_ref();
3399    *buffer = info->mMediaBuffer;
3400
3401    return OK;
3402}
3403
3404void OMXCodec::signalBufferReturned(MediaBuffer *buffer) {
3405    Mutex::Autolock autoLock(mLock);
3406
3407    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
3408    for (size_t i = 0; i < buffers->size(); ++i) {
3409        BufferInfo *info = &buffers->editItemAt(i);
3410
3411        if (info->mMediaBuffer == buffer) {
3412            CHECK_EQ(mPortStatus[kPortIndexOutput], ENABLED);
3413            if (buffer->graphicBuffer() == 0) {
3414                fillOutputBuffer(info);
3415            } else {
3416                sp<MetaData> metaData = info->mMediaBuffer->meta_data();
3417                int32_t rendered = 0;
3418                if (!metaData->findInt32(kKeyRendered, &rendered)) {
3419                    rendered = 0;
3420                }
3421                if (!rendered) {
3422                    status_t err = cancelBufferToNativeWindow(info);
3423                    if (err < 0) {
3424                        return;
3425                    }
3426                } else {
3427                    info->mOwnedByNativeWindow = true;
3428                }
3429
3430                // Dequeue the next buffer from the native window.
3431                BufferInfo *nextBufInfo = dequeueBufferFromNativeWindow();
3432                if (nextBufInfo == 0) {
3433                    return;
3434                }
3435
3436                // Give the buffer to the OMX node to fill.
3437                fillOutputBuffer(nextBufInfo);
3438            }
3439            return;
3440        }
3441    }
3442
3443    CHECK(!"should not be here.");
3444}
3445
3446static const char *imageCompressionFormatString(OMX_IMAGE_CODINGTYPE type) {
3447    static const char *kNames[] = {
3448        "OMX_IMAGE_CodingUnused",
3449        "OMX_IMAGE_CodingAutoDetect",
3450        "OMX_IMAGE_CodingJPEG",
3451        "OMX_IMAGE_CodingJPEG2K",
3452        "OMX_IMAGE_CodingEXIF",
3453        "OMX_IMAGE_CodingTIFF",
3454        "OMX_IMAGE_CodingGIF",
3455        "OMX_IMAGE_CodingPNG",
3456        "OMX_IMAGE_CodingLZW",
3457        "OMX_IMAGE_CodingBMP",
3458    };
3459
3460    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3461
3462    if (type < 0 || (size_t)type >= numNames) {
3463        return "UNKNOWN";
3464    } else {
3465        return kNames[type];
3466    }
3467}
3468
3469static const char *colorFormatString(OMX_COLOR_FORMATTYPE type) {
3470    static const char *kNames[] = {
3471        "OMX_COLOR_FormatUnused",
3472        "OMX_COLOR_FormatMonochrome",
3473        "OMX_COLOR_Format8bitRGB332",
3474        "OMX_COLOR_Format12bitRGB444",
3475        "OMX_COLOR_Format16bitARGB4444",
3476        "OMX_COLOR_Format16bitARGB1555",
3477        "OMX_COLOR_Format16bitRGB565",
3478        "OMX_COLOR_Format16bitBGR565",
3479        "OMX_COLOR_Format18bitRGB666",
3480        "OMX_COLOR_Format18bitARGB1665",
3481        "OMX_COLOR_Format19bitARGB1666",
3482        "OMX_COLOR_Format24bitRGB888",
3483        "OMX_COLOR_Format24bitBGR888",
3484        "OMX_COLOR_Format24bitARGB1887",
3485        "OMX_COLOR_Format25bitARGB1888",
3486        "OMX_COLOR_Format32bitBGRA8888",
3487        "OMX_COLOR_Format32bitARGB8888",
3488        "OMX_COLOR_FormatYUV411Planar",
3489        "OMX_COLOR_FormatYUV411PackedPlanar",
3490        "OMX_COLOR_FormatYUV420Planar",
3491        "OMX_COLOR_FormatYUV420PackedPlanar",
3492        "OMX_COLOR_FormatYUV420SemiPlanar",
3493        "OMX_COLOR_FormatYUV422Planar",
3494        "OMX_COLOR_FormatYUV422PackedPlanar",
3495        "OMX_COLOR_FormatYUV422SemiPlanar",
3496        "OMX_COLOR_FormatYCbYCr",
3497        "OMX_COLOR_FormatYCrYCb",
3498        "OMX_COLOR_FormatCbYCrY",
3499        "OMX_COLOR_FormatCrYCbY",
3500        "OMX_COLOR_FormatYUV444Interleaved",
3501        "OMX_COLOR_FormatRawBayer8bit",
3502        "OMX_COLOR_FormatRawBayer10bit",
3503        "OMX_COLOR_FormatRawBayer8bitcompressed",
3504        "OMX_COLOR_FormatL2",
3505        "OMX_COLOR_FormatL4",
3506        "OMX_COLOR_FormatL8",
3507        "OMX_COLOR_FormatL16",
3508        "OMX_COLOR_FormatL24",
3509        "OMX_COLOR_FormatL32",
3510        "OMX_COLOR_FormatYUV420PackedSemiPlanar",
3511        "OMX_COLOR_FormatYUV422PackedSemiPlanar",
3512        "OMX_COLOR_Format18BitBGR666",
3513        "OMX_COLOR_Format24BitARGB6666",
3514        "OMX_COLOR_Format24BitABGR6666",
3515    };
3516
3517    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3518
3519    if (type == OMX_QCOM_COLOR_FormatYVU420SemiPlanar) {
3520        return "OMX_QCOM_COLOR_FormatYVU420SemiPlanar";
3521    } else if (type < 0 || (size_t)type >= numNames) {
3522        return "UNKNOWN";
3523    } else {
3524        return kNames[type];
3525    }
3526}
3527
3528static const char *videoCompressionFormatString(OMX_VIDEO_CODINGTYPE type) {
3529    static const char *kNames[] = {
3530        "OMX_VIDEO_CodingUnused",
3531        "OMX_VIDEO_CodingAutoDetect",
3532        "OMX_VIDEO_CodingMPEG2",
3533        "OMX_VIDEO_CodingH263",
3534        "OMX_VIDEO_CodingMPEG4",
3535        "OMX_VIDEO_CodingWMV",
3536        "OMX_VIDEO_CodingRV",
3537        "OMX_VIDEO_CodingAVC",
3538        "OMX_VIDEO_CodingMJPEG",
3539    };
3540
3541    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3542
3543    if (type < 0 || (size_t)type >= numNames) {
3544        return "UNKNOWN";
3545    } else {
3546        return kNames[type];
3547    }
3548}
3549
3550static const char *audioCodingTypeString(OMX_AUDIO_CODINGTYPE type) {
3551    static const char *kNames[] = {
3552        "OMX_AUDIO_CodingUnused",
3553        "OMX_AUDIO_CodingAutoDetect",
3554        "OMX_AUDIO_CodingPCM",
3555        "OMX_AUDIO_CodingADPCM",
3556        "OMX_AUDIO_CodingAMR",
3557        "OMX_AUDIO_CodingGSMFR",
3558        "OMX_AUDIO_CodingGSMEFR",
3559        "OMX_AUDIO_CodingGSMHR",
3560        "OMX_AUDIO_CodingPDCFR",
3561        "OMX_AUDIO_CodingPDCEFR",
3562        "OMX_AUDIO_CodingPDCHR",
3563        "OMX_AUDIO_CodingTDMAFR",
3564        "OMX_AUDIO_CodingTDMAEFR",
3565        "OMX_AUDIO_CodingQCELP8",
3566        "OMX_AUDIO_CodingQCELP13",
3567        "OMX_AUDIO_CodingEVRC",
3568        "OMX_AUDIO_CodingSMV",
3569        "OMX_AUDIO_CodingG711",
3570        "OMX_AUDIO_CodingG723",
3571        "OMX_AUDIO_CodingG726",
3572        "OMX_AUDIO_CodingG729",
3573        "OMX_AUDIO_CodingAAC",
3574        "OMX_AUDIO_CodingMP3",
3575        "OMX_AUDIO_CodingSBC",
3576        "OMX_AUDIO_CodingVORBIS",
3577        "OMX_AUDIO_CodingWMA",
3578        "OMX_AUDIO_CodingRA",
3579        "OMX_AUDIO_CodingMIDI",
3580    };
3581
3582    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3583
3584    if (type < 0 || (size_t)type >= numNames) {
3585        return "UNKNOWN";
3586    } else {
3587        return kNames[type];
3588    }
3589}
3590
3591static const char *audioPCMModeString(OMX_AUDIO_PCMMODETYPE type) {
3592    static const char *kNames[] = {
3593        "OMX_AUDIO_PCMModeLinear",
3594        "OMX_AUDIO_PCMModeALaw",
3595        "OMX_AUDIO_PCMModeMULaw",
3596    };
3597
3598    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3599
3600    if (type < 0 || (size_t)type >= numNames) {
3601        return "UNKNOWN";
3602    } else {
3603        return kNames[type];
3604    }
3605}
3606
3607static const char *amrBandModeString(OMX_AUDIO_AMRBANDMODETYPE type) {
3608    static const char *kNames[] = {
3609        "OMX_AUDIO_AMRBandModeUnused",
3610        "OMX_AUDIO_AMRBandModeNB0",
3611        "OMX_AUDIO_AMRBandModeNB1",
3612        "OMX_AUDIO_AMRBandModeNB2",
3613        "OMX_AUDIO_AMRBandModeNB3",
3614        "OMX_AUDIO_AMRBandModeNB4",
3615        "OMX_AUDIO_AMRBandModeNB5",
3616        "OMX_AUDIO_AMRBandModeNB6",
3617        "OMX_AUDIO_AMRBandModeNB7",
3618        "OMX_AUDIO_AMRBandModeWB0",
3619        "OMX_AUDIO_AMRBandModeWB1",
3620        "OMX_AUDIO_AMRBandModeWB2",
3621        "OMX_AUDIO_AMRBandModeWB3",
3622        "OMX_AUDIO_AMRBandModeWB4",
3623        "OMX_AUDIO_AMRBandModeWB5",
3624        "OMX_AUDIO_AMRBandModeWB6",
3625        "OMX_AUDIO_AMRBandModeWB7",
3626        "OMX_AUDIO_AMRBandModeWB8",
3627    };
3628
3629    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3630
3631    if (type < 0 || (size_t)type >= numNames) {
3632        return "UNKNOWN";
3633    } else {
3634        return kNames[type];
3635    }
3636}
3637
3638static const char *amrFrameFormatString(OMX_AUDIO_AMRFRAMEFORMATTYPE type) {
3639    static const char *kNames[] = {
3640        "OMX_AUDIO_AMRFrameFormatConformance",
3641        "OMX_AUDIO_AMRFrameFormatIF1",
3642        "OMX_AUDIO_AMRFrameFormatIF2",
3643        "OMX_AUDIO_AMRFrameFormatFSF",
3644        "OMX_AUDIO_AMRFrameFormatRTPPayload",
3645        "OMX_AUDIO_AMRFrameFormatITU",
3646    };
3647
3648    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3649
3650    if (type < 0 || (size_t)type >= numNames) {
3651        return "UNKNOWN";
3652    } else {
3653        return kNames[type];
3654    }
3655}
3656
3657void OMXCodec::dumpPortStatus(OMX_U32 portIndex) {
3658    OMX_PARAM_PORTDEFINITIONTYPE def;
3659    InitOMXParams(&def);
3660    def.nPortIndex = portIndex;
3661
3662    status_t err = mOMX->getParameter(
3663            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3664    CHECK_EQ(err, OK);
3665
3666    printf("%s Port = {\n", portIndex == kPortIndexInput ? "Input" : "Output");
3667
3668    CHECK((portIndex == kPortIndexInput && def.eDir == OMX_DirInput)
3669          || (portIndex == kPortIndexOutput && def.eDir == OMX_DirOutput));
3670
3671    printf("  nBufferCountActual = %ld\n", def.nBufferCountActual);
3672    printf("  nBufferCountMin = %ld\n", def.nBufferCountMin);
3673    printf("  nBufferSize = %ld\n", def.nBufferSize);
3674
3675    switch (def.eDomain) {
3676        case OMX_PortDomainImage:
3677        {
3678            const OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3679
3680            printf("\n");
3681            printf("  // Image\n");
3682            printf("  nFrameWidth = %ld\n", imageDef->nFrameWidth);
3683            printf("  nFrameHeight = %ld\n", imageDef->nFrameHeight);
3684            printf("  nStride = %ld\n", imageDef->nStride);
3685
3686            printf("  eCompressionFormat = %s\n",
3687                   imageCompressionFormatString(imageDef->eCompressionFormat));
3688
3689            printf("  eColorFormat = %s\n",
3690                   colorFormatString(imageDef->eColorFormat));
3691
3692            break;
3693        }
3694
3695        case OMX_PortDomainVideo:
3696        {
3697            OMX_VIDEO_PORTDEFINITIONTYPE *videoDef = &def.format.video;
3698
3699            printf("\n");
3700            printf("  // Video\n");
3701            printf("  nFrameWidth = %ld\n", videoDef->nFrameWidth);
3702            printf("  nFrameHeight = %ld\n", videoDef->nFrameHeight);
3703            printf("  nStride = %ld\n", videoDef->nStride);
3704
3705            printf("  eCompressionFormat = %s\n",
3706                   videoCompressionFormatString(videoDef->eCompressionFormat));
3707
3708            printf("  eColorFormat = %s\n",
3709                   colorFormatString(videoDef->eColorFormat));
3710
3711            break;
3712        }
3713
3714        case OMX_PortDomainAudio:
3715        {
3716            OMX_AUDIO_PORTDEFINITIONTYPE *audioDef = &def.format.audio;
3717
3718            printf("\n");
3719            printf("  // Audio\n");
3720            printf("  eEncoding = %s\n",
3721                   audioCodingTypeString(audioDef->eEncoding));
3722
3723            if (audioDef->eEncoding == OMX_AUDIO_CodingPCM) {
3724                OMX_AUDIO_PARAM_PCMMODETYPE params;
3725                InitOMXParams(&params);
3726                params.nPortIndex = portIndex;
3727
3728                err = mOMX->getParameter(
3729                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
3730                CHECK_EQ(err, OK);
3731
3732                printf("  nSamplingRate = %ld\n", params.nSamplingRate);
3733                printf("  nChannels = %ld\n", params.nChannels);
3734                printf("  bInterleaved = %d\n", params.bInterleaved);
3735                printf("  nBitPerSample = %ld\n", params.nBitPerSample);
3736
3737                printf("  eNumData = %s\n",
3738                       params.eNumData == OMX_NumericalDataSigned
3739                        ? "signed" : "unsigned");
3740
3741                printf("  ePCMMode = %s\n", audioPCMModeString(params.ePCMMode));
3742            } else if (audioDef->eEncoding == OMX_AUDIO_CodingAMR) {
3743                OMX_AUDIO_PARAM_AMRTYPE amr;
3744                InitOMXParams(&amr);
3745                amr.nPortIndex = portIndex;
3746
3747                err = mOMX->getParameter(
3748                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
3749                CHECK_EQ(err, OK);
3750
3751                printf("  nChannels = %ld\n", amr.nChannels);
3752                printf("  eAMRBandMode = %s\n",
3753                        amrBandModeString(amr.eAMRBandMode));
3754                printf("  eAMRFrameFormat = %s\n",
3755                        amrFrameFormatString(amr.eAMRFrameFormat));
3756            }
3757
3758            break;
3759        }
3760
3761        default:
3762        {
3763            printf("  // Unknown\n");
3764            break;
3765        }
3766    }
3767
3768    printf("}\n");
3769}
3770
3771status_t OMXCodec::initNativeWindow() {
3772    // Enable use of a GraphicBuffer as the output for this node.  This must
3773    // happen before getting the IndexParamPortDefinition parameter because it
3774    // will affect the pixel format that the node reports.
3775    status_t err = mOMX->enableGraphicBuffers(mNode, kPortIndexOutput, OMX_TRUE);
3776    if (err != 0) {
3777        return err;
3778    }
3779
3780    return OK;
3781}
3782
3783void OMXCodec::initOutputFormat(const sp<MetaData> &inputFormat) {
3784    mOutputFormat = new MetaData;
3785    mOutputFormat->setCString(kKeyDecoderComponent, mComponentName);
3786    if (mIsEncoder) {
3787        int32_t timeScale;
3788        if (inputFormat->findInt32(kKeyTimeScale, &timeScale)) {
3789            mOutputFormat->setInt32(kKeyTimeScale, timeScale);
3790        }
3791    }
3792
3793    OMX_PARAM_PORTDEFINITIONTYPE def;
3794    InitOMXParams(&def);
3795    def.nPortIndex = kPortIndexOutput;
3796
3797    status_t err = mOMX->getParameter(
3798            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3799    CHECK_EQ(err, OK);
3800
3801    switch (def.eDomain) {
3802        case OMX_PortDomainImage:
3803        {
3804            OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3805            CHECK_EQ(imageDef->eCompressionFormat, OMX_IMAGE_CodingUnused);
3806
3807            mOutputFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
3808            mOutputFormat->setInt32(kKeyColorFormat, imageDef->eColorFormat);
3809            mOutputFormat->setInt32(kKeyWidth, imageDef->nFrameWidth);
3810            mOutputFormat->setInt32(kKeyHeight, imageDef->nFrameHeight);
3811            break;
3812        }
3813
3814        case OMX_PortDomainAudio:
3815        {
3816            OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio;
3817
3818            if (audio_def->eEncoding == OMX_AUDIO_CodingPCM) {
3819                OMX_AUDIO_PARAM_PCMMODETYPE params;
3820                InitOMXParams(&params);
3821                params.nPortIndex = kPortIndexOutput;
3822
3823                err = mOMX->getParameter(
3824                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
3825                CHECK_EQ(err, OK);
3826
3827                CHECK_EQ(params.eNumData, OMX_NumericalDataSigned);
3828                CHECK_EQ(params.nBitPerSample, 16);
3829                CHECK_EQ(params.ePCMMode, OMX_AUDIO_PCMModeLinear);
3830
3831                int32_t numChannels, sampleRate;
3832                inputFormat->findInt32(kKeyChannelCount, &numChannels);
3833                inputFormat->findInt32(kKeySampleRate, &sampleRate);
3834
3835                if ((OMX_U32)numChannels != params.nChannels) {
3836                    LOGW("Codec outputs a different number of channels than "
3837                         "the input stream contains (contains %d channels, "
3838                         "codec outputs %ld channels).",
3839                         numChannels, params.nChannels);
3840                }
3841
3842                mOutputFormat->setCString(
3843                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
3844
3845                // Use the codec-advertised number of channels, as some
3846                // codecs appear to output stereo even if the input data is
3847                // mono. If we know the codec lies about this information,
3848                // use the actual number of channels instead.
3849                mOutputFormat->setInt32(
3850                        kKeyChannelCount,
3851                        (mQuirks & kDecoderLiesAboutNumberOfChannels)
3852                            ? numChannels : params.nChannels);
3853
3854                // The codec-reported sampleRate is not reliable...
3855                mOutputFormat->setInt32(kKeySampleRate, sampleRate);
3856            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAMR) {
3857                OMX_AUDIO_PARAM_AMRTYPE amr;
3858                InitOMXParams(&amr);
3859                amr.nPortIndex = kPortIndexOutput;
3860
3861                err = mOMX->getParameter(
3862                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
3863                CHECK_EQ(err, OK);
3864
3865                CHECK_EQ(amr.nChannels, 1);
3866                mOutputFormat->setInt32(kKeyChannelCount, 1);
3867
3868                if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeNB0
3869                    && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeNB7) {
3870                    mOutputFormat->setCString(
3871                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB);
3872                    mOutputFormat->setInt32(kKeySampleRate, 8000);
3873                } else if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeWB0
3874                            && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeWB8) {
3875                    mOutputFormat->setCString(
3876                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB);
3877                    mOutputFormat->setInt32(kKeySampleRate, 16000);
3878                } else {
3879                    CHECK(!"Unknown AMR band mode.");
3880                }
3881            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAAC) {
3882                mOutputFormat->setCString(
3883                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
3884                int32_t numChannels, sampleRate, bitRate;
3885                inputFormat->findInt32(kKeyChannelCount, &numChannels);
3886                inputFormat->findInt32(kKeySampleRate, &sampleRate);
3887                inputFormat->findInt32(kKeyBitRate, &bitRate);
3888                mOutputFormat->setInt32(kKeyChannelCount, numChannels);
3889                mOutputFormat->setInt32(kKeySampleRate, sampleRate);
3890                mOutputFormat->setInt32(kKeyBitRate, bitRate);
3891            } else {
3892                CHECK(!"Should not be here. Unknown audio encoding.");
3893            }
3894            break;
3895        }
3896
3897        case OMX_PortDomainVideo:
3898        {
3899            OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
3900
3901            if (video_def->eCompressionFormat == OMX_VIDEO_CodingUnused) {
3902                mOutputFormat->setCString(
3903                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
3904            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingMPEG4) {
3905                mOutputFormat->setCString(
3906                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
3907            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingH263) {
3908                mOutputFormat->setCString(
3909                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
3910            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingAVC) {
3911                mOutputFormat->setCString(
3912                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
3913            } else {
3914                CHECK(!"Unknown compression format.");
3915            }
3916
3917            mOutputFormat->setInt32(kKeyWidth, video_def->nFrameWidth);
3918            mOutputFormat->setInt32(kKeyHeight, video_def->nFrameHeight);
3919            mOutputFormat->setInt32(kKeyColorFormat, video_def->eColorFormat);
3920            break;
3921        }
3922
3923        default:
3924        {
3925            CHECK(!"should not be here, neither audio nor video.");
3926            break;
3927        }
3928    }
3929}
3930
3931status_t OMXCodec::pause() {
3932    Mutex::Autolock autoLock(mLock);
3933
3934    mPaused = true;
3935
3936    return OK;
3937}
3938
3939////////////////////////////////////////////////////////////////////////////////
3940
3941status_t QueryCodecs(
3942        const sp<IOMX> &omx,
3943        const char *mime, bool queryDecoders,
3944        Vector<CodecCapabilities> *results) {
3945    results->clear();
3946
3947    for (int index = 0;; ++index) {
3948        const char *componentName;
3949
3950        if (!queryDecoders) {
3951            componentName = GetCodec(
3952                    kEncoderInfo, sizeof(kEncoderInfo) / sizeof(kEncoderInfo[0]),
3953                    mime, index);
3954        } else {
3955            componentName = GetCodec(
3956                    kDecoderInfo, sizeof(kDecoderInfo) / sizeof(kDecoderInfo[0]),
3957                    mime, index);
3958        }
3959
3960        if (!componentName) {
3961            return OK;
3962        }
3963
3964        if (strncmp(componentName, "OMX.", 4)) {
3965            // Not an OpenMax component but a software codec.
3966
3967            results->push();
3968            CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
3969            caps->mComponentName = componentName;
3970
3971            continue;
3972        }
3973
3974        sp<OMXCodecObserver> observer = new OMXCodecObserver;
3975        IOMX::node_id node;
3976        status_t err = omx->allocateNode(componentName, observer, &node);
3977
3978        if (err != OK) {
3979            continue;
3980        }
3981
3982        OMXCodec::setComponentRole(omx, node, !queryDecoders, mime);
3983
3984        results->push();
3985        CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
3986        caps->mComponentName = componentName;
3987
3988        OMX_VIDEO_PARAM_PROFILELEVELTYPE param;
3989        InitOMXParams(&param);
3990
3991        param.nPortIndex = queryDecoders ? 0 : 1;
3992
3993        for (param.nProfileIndex = 0;; ++param.nProfileIndex) {
3994            err = omx->getParameter(
3995                    node, OMX_IndexParamVideoProfileLevelQuerySupported,
3996                    &param, sizeof(param));
3997
3998            if (err != OK) {
3999                break;
4000            }
4001
4002            CodecProfileLevel profileLevel;
4003            profileLevel.mProfile = param.eProfile;
4004            profileLevel.mLevel = param.eLevel;
4005
4006            caps->mProfileLevels.push(profileLevel);
4007        }
4008
4009        // Color format query
4010        OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat;
4011        InitOMXParams(&portFormat);
4012        portFormat.nPortIndex = queryDecoders ? 1 : 0;
4013        for (portFormat.nIndex = 0;; ++portFormat.nIndex)  {
4014            err = omx->getParameter(
4015                    node, OMX_IndexParamVideoPortFormat,
4016                    &portFormat, sizeof(portFormat));
4017            if (err != OK) {
4018                break;
4019            }
4020            caps->mColorFormats.push(portFormat.eColorFormat);
4021        }
4022
4023        CHECK_EQ(omx->freeNode(node), OK);
4024    }
4025}
4026
4027void OMXCodec::restorePatchedDataPointer(BufferInfo *info) {
4028    CHECK(mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames));
4029    CHECK(mOMXLivesLocally);
4030
4031    OMX_BUFFERHEADERTYPE *header = (OMX_BUFFERHEADERTYPE *)info->mBuffer;
4032    header->pBuffer = (OMX_U8 *)info->mData;
4033}
4034
4035}  // namespace android
4036