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