OMXCodec.cpp revision d5623ca906f64cc257cd695abd2a6b52b085f65f
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    OMX_PARAM_PORTDEFINITIONTYPE def;
1647    InitOMXParams(&def);
1648    def.nPortIndex = portIndex;
1649
1650    status_t err = mOMX->getParameter(
1651            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1652
1653    if (err != OK) {
1654        return err;
1655    }
1656
1657    if (mIsMetaDataStoredInVideoBuffers && portIndex == kPortIndexInput) {
1658        err = mOMX->storeMetaDataInBuffers(mNode, kPortIndexInput, OMX_TRUE);
1659        if (err != OK) {
1660            LOGE("Storing meta data in video buffers is not supported");
1661            return err;
1662        }
1663    }
1664
1665    CODEC_LOGI("allocating %lu buffers of size %lu on %s port",
1666            def.nBufferCountActual, def.nBufferSize,
1667            portIndex == kPortIndexInput ? "input" : "output");
1668
1669    size_t totalSize = def.nBufferCountActual * def.nBufferSize;
1670    mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec");
1671
1672    for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
1673        sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize);
1674        CHECK(mem.get() != NULL);
1675
1676        BufferInfo info;
1677        info.mData = NULL;
1678        info.mSize = def.nBufferSize;
1679
1680        IOMX::buffer_id buffer;
1681        if (portIndex == kPortIndexInput
1682                && (mQuirks & kRequiresAllocateBufferOnInputPorts)) {
1683            if (mOMXLivesLocally) {
1684                mem.clear();
1685
1686                err = mOMX->allocateBuffer(
1687                        mNode, portIndex, def.nBufferSize, &buffer,
1688                        &info.mData);
1689            } else {
1690                err = mOMX->allocateBufferWithBackup(
1691                        mNode, portIndex, mem, &buffer);
1692            }
1693        } else if (portIndex == kPortIndexOutput
1694                && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) {
1695            if (mOMXLivesLocally) {
1696                mem.clear();
1697
1698                err = mOMX->allocateBuffer(
1699                        mNode, portIndex, def.nBufferSize, &buffer,
1700                        &info.mData);
1701            } else {
1702                err = mOMX->allocateBufferWithBackup(
1703                        mNode, portIndex, mem, &buffer);
1704            }
1705        } else {
1706            err = mOMX->useBuffer(mNode, portIndex, mem, &buffer);
1707        }
1708
1709        if (err != OK) {
1710            LOGE("allocate_buffer_with_backup failed");
1711            return err;
1712        }
1713
1714        if (mem != NULL) {
1715            info.mData = mem->pointer();
1716        }
1717
1718        info.mBuffer = buffer;
1719        info.mStatus = OWNED_BY_US;
1720        info.mMem = mem;
1721        info.mMediaBuffer = NULL;
1722
1723        if (portIndex == kPortIndexOutput) {
1724            if (!(mOMXLivesLocally
1725                        && (mQuirks & kRequiresAllocateBufferOnOutputPorts)
1726                        && (mQuirks & kDefersOutputBufferAllocation))) {
1727                // If the node does not fill in the buffer ptr at this time,
1728                // we will defer creating the MediaBuffer until receiving
1729                // the first FILL_BUFFER_DONE notification instead.
1730                info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize);
1731                info.mMediaBuffer->setObserver(this);
1732            }
1733        }
1734
1735        mPortBuffers[portIndex].push(info);
1736
1737        CODEC_LOGV("allocated buffer %p on %s port", buffer,
1738             portIndex == kPortIndexInput ? "input" : "output");
1739    }
1740
1741    // dumpPortStatus(portIndex);
1742
1743    return OK;
1744}
1745
1746status_t OMXCodec::applyRotation() {
1747    sp<MetaData> meta = mSource->getFormat();
1748
1749    int32_t rotationDegrees;
1750    if (!meta->findInt32(kKeyRotation, &rotationDegrees)) {
1751        rotationDegrees = 0;
1752    }
1753
1754    uint32_t transform;
1755    switch (rotationDegrees) {
1756        case 0: transform = 0; break;
1757        case 90: transform = HAL_TRANSFORM_ROT_90; break;
1758        case 180: transform = HAL_TRANSFORM_ROT_180; break;
1759        case 270: transform = HAL_TRANSFORM_ROT_270; break;
1760        default: transform = 0; break;
1761    }
1762
1763    status_t err = OK;
1764
1765    if (transform) {
1766        err = native_window_set_buffers_transform(
1767                mNativeWindow.get(), transform);
1768    }
1769
1770    return err;
1771}
1772
1773status_t OMXCodec::allocateOutputBuffersFromNativeWindow() {
1774    // Get the number of buffers needed.
1775    OMX_PARAM_PORTDEFINITIONTYPE def;
1776    InitOMXParams(&def);
1777    def.nPortIndex = kPortIndexOutput;
1778
1779    status_t err = mOMX->getParameter(
1780            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1781    if (err != OK) {
1782        return err;
1783    }
1784
1785    err = native_window_set_buffers_geometry(
1786            mNativeWindow.get(),
1787            def.format.video.nFrameWidth,
1788            def.format.video.nFrameHeight,
1789            def.format.video.eColorFormat);
1790
1791    if (err != 0) {
1792        LOGE("native_window_set_buffers_geometry failed: %s (%d)",
1793                strerror(-err), -err);
1794        return err;
1795    }
1796
1797    err = applyRotation();
1798    if (err != OK) {
1799        return err;
1800    }
1801
1802    // Set up the native window.
1803    OMX_U32 usage = 0;
1804    err = mOMX->getGraphicBufferUsage(mNode, kPortIndexOutput, &usage);
1805    if (err != 0) {
1806        LOGW("querying usage flags from OMX IL component failed: %d", err);
1807        // XXX: Currently this error is logged, but not fatal.
1808        usage = 0;
1809    }
1810    if (mEnableGrallocUsageProtected) {
1811        usage |= GRALLOC_USAGE_PROTECTED;
1812    }
1813
1814    // Make sure to check whether either Stagefright or the video decoder
1815    // requested protected buffers.
1816    if (usage & GRALLOC_USAGE_PROTECTED) {
1817        // Verify that the ANativeWindow sends images directly to
1818        // SurfaceFlinger.
1819        int queuesToNativeWindow = 0;
1820        err = mNativeWindow->query(
1821                mNativeWindow.get(), NATIVE_WINDOW_QUEUES_TO_WINDOW_COMPOSER,
1822                &queuesToNativeWindow);
1823        if (err != 0) {
1824            LOGE("error authenticating native window: %d", err);
1825            return err;
1826        }
1827        if (queuesToNativeWindow != 1) {
1828            LOGE("native window could not be authenticated");
1829            return PERMISSION_DENIED;
1830        }
1831    }
1832
1833    LOGV("native_window_set_usage usage=0x%x", usage);
1834    err = native_window_set_usage(
1835            mNativeWindow.get(), usage | GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_EXTERNAL_DISP);
1836    if (err != 0) {
1837        LOGE("native_window_set_usage failed: %s (%d)", strerror(-err), -err);
1838        return err;
1839    }
1840
1841    int minUndequeuedBufs = 0;
1842    err = mNativeWindow->query(mNativeWindow.get(),
1843            NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBufs);
1844    if (err != 0) {
1845        LOGE("NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS query failed: %s (%d)",
1846                strerror(-err), -err);
1847        return err;
1848    }
1849
1850    // XXX: Is this the right logic to use?  It's not clear to me what the OMX
1851    // buffer counts refer to - how do they account for the renderer holding on
1852    // to buffers?
1853    if (def.nBufferCountActual < def.nBufferCountMin + minUndequeuedBufs) {
1854        OMX_U32 newBufferCount = def.nBufferCountMin + minUndequeuedBufs;
1855        def.nBufferCountActual = newBufferCount;
1856        err = mOMX->setParameter(
1857                mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1858        if (err != OK) {
1859            CODEC_LOGE("setting nBufferCountActual to %lu failed: %d",
1860                    newBufferCount, err);
1861            return err;
1862        }
1863    }
1864
1865    err = native_window_set_buffer_count(
1866            mNativeWindow.get(), def.nBufferCountActual);
1867    if (err != 0) {
1868        LOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err),
1869                -err);
1870        return err;
1871    }
1872
1873    CODEC_LOGI("allocating %lu buffers from a native window of size %lu on "
1874            "output port", def.nBufferCountActual, def.nBufferSize);
1875
1876    // Dequeue buffers and send them to OMX
1877    for (OMX_U32 i = 0; i < def.nBufferCountActual; i++) {
1878        ANativeWindowBuffer* buf;
1879        err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf);
1880        if (err != 0) {
1881            LOGE("dequeueBuffer failed: %s (%d)", strerror(-err), -err);
1882            break;
1883        }
1884
1885        sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(buf, false));
1886        BufferInfo info;
1887        info.mData = NULL;
1888        info.mSize = def.nBufferSize;
1889        info.mStatus = OWNED_BY_US;
1890        info.mMem = NULL;
1891        info.mMediaBuffer = new MediaBuffer(graphicBuffer);
1892        info.mMediaBuffer->setObserver(this);
1893        mPortBuffers[kPortIndexOutput].push(info);
1894
1895        IOMX::buffer_id bufferId;
1896        err = mOMX->useGraphicBuffer(mNode, kPortIndexOutput, graphicBuffer,
1897                &bufferId);
1898        if (err != 0) {
1899            CODEC_LOGE("registering GraphicBuffer with OMX IL component "
1900                    "failed: %d", err);
1901            break;
1902        }
1903
1904        mPortBuffers[kPortIndexOutput].editItemAt(i).mBuffer = bufferId;
1905
1906        CODEC_LOGV("registered graphic buffer with ID %p (pointer = %p)",
1907                bufferId, graphicBuffer.get());
1908    }
1909
1910    OMX_U32 cancelStart;
1911    OMX_U32 cancelEnd;
1912    if (err != 0) {
1913        // If an error occurred while dequeuing we need to cancel any buffers
1914        // that were dequeued.
1915        cancelStart = 0;
1916        cancelEnd = mPortBuffers[kPortIndexOutput].size();
1917    } else {
1918        // Return the last two buffers to the native window.
1919        cancelStart = def.nBufferCountActual - minUndequeuedBufs;
1920        cancelEnd = def.nBufferCountActual;
1921    }
1922
1923    for (OMX_U32 i = cancelStart; i < cancelEnd; i++) {
1924        BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(i);
1925        cancelBufferToNativeWindow(info);
1926    }
1927
1928    return err;
1929}
1930
1931status_t OMXCodec::cancelBufferToNativeWindow(BufferInfo *info) {
1932    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
1933    CODEC_LOGV("Calling cancelBuffer on buffer %p", info->mBuffer);
1934    int err = mNativeWindow->cancelBuffer(
1935        mNativeWindow.get(), info->mMediaBuffer->graphicBuffer().get());
1936    if (err != 0) {
1937      CODEC_LOGE("cancelBuffer failed w/ error 0x%08x", err);
1938
1939      setState(ERROR);
1940      return err;
1941    }
1942    info->mStatus = OWNED_BY_NATIVE_WINDOW;
1943    return OK;
1944}
1945
1946OMXCodec::BufferInfo* OMXCodec::dequeueBufferFromNativeWindow() {
1947    // Dequeue the next buffer from the native window.
1948    ANativeWindowBuffer* buf;
1949    int err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf);
1950    if (err != 0) {
1951      CODEC_LOGE("dequeueBuffer failed w/ error 0x%08x", err);
1952
1953      setState(ERROR);
1954      return 0;
1955    }
1956
1957    // Determine which buffer we just dequeued.
1958    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
1959    BufferInfo *bufInfo = 0;
1960    for (size_t i = 0; i < buffers->size(); i++) {
1961      sp<GraphicBuffer> graphicBuffer = buffers->itemAt(i).
1962          mMediaBuffer->graphicBuffer();
1963      if (graphicBuffer->handle == buf->handle) {
1964        bufInfo = &buffers->editItemAt(i);
1965        break;
1966      }
1967    }
1968
1969    if (bufInfo == 0) {
1970        CODEC_LOGE("dequeued unrecognized buffer: %p", buf);
1971
1972        setState(ERROR);
1973        return 0;
1974    }
1975
1976    // The native window no longer owns the buffer.
1977    CHECK_EQ((int)bufInfo->mStatus, (int)OWNED_BY_NATIVE_WINDOW);
1978    bufInfo->mStatus = OWNED_BY_US;
1979
1980    return bufInfo;
1981}
1982
1983void OMXCodec::on_message(const omx_message &msg) {
1984    if (mState == ERROR) {
1985        LOGW("Dropping OMX message - we're in ERROR state.");
1986        return;
1987    }
1988
1989    switch (msg.type) {
1990        case omx_message::EVENT:
1991        {
1992            onEvent(
1993                 msg.u.event_data.event, msg.u.event_data.data1,
1994                 msg.u.event_data.data2);
1995
1996            break;
1997        }
1998
1999        case omx_message::EMPTY_BUFFER_DONE:
2000        {
2001            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
2002
2003            CODEC_LOGV("EMPTY_BUFFER_DONE(buffer: %p)", buffer);
2004
2005            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2006            size_t i = 0;
2007            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
2008                ++i;
2009            }
2010
2011            CHECK(i < buffers->size());
2012            if ((*buffers)[i].mStatus != OWNED_BY_COMPONENT) {
2013                LOGW("We already own input buffer %p, yet received "
2014                     "an EMPTY_BUFFER_DONE.", buffer);
2015            }
2016
2017            BufferInfo* info = &buffers->editItemAt(i);
2018            info->mStatus = OWNED_BY_US;
2019
2020            // Buffer could not be released until empty buffer done is called.
2021            if (info->mMediaBuffer != NULL) {
2022                if (mIsEncoder &&
2023                    (mQuirks & kAvoidMemcopyInputRecordingFrames)) {
2024                    // If zero-copy mode is enabled this will send the
2025                    // input buffer back to the upstream source.
2026                    restorePatchedDataPointer(info);
2027                }
2028
2029                info->mMediaBuffer->release();
2030                info->mMediaBuffer = NULL;
2031            }
2032
2033            if (mPortStatus[kPortIndexInput] == DISABLING) {
2034                CODEC_LOGV("Port is disabled, freeing buffer %p", buffer);
2035
2036                status_t err = freeBuffer(kPortIndexInput, i);
2037                CHECK_EQ(err, (status_t)OK);
2038            } else if (mState != ERROR
2039                    && mPortStatus[kPortIndexInput] != SHUTTING_DOWN) {
2040                CHECK_EQ((int)mPortStatus[kPortIndexInput], (int)ENABLED);
2041                drainInputBuffer(&buffers->editItemAt(i));
2042            }
2043            break;
2044        }
2045
2046        case omx_message::FILL_BUFFER_DONE:
2047        {
2048            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
2049            OMX_U32 flags = msg.u.extended_buffer_data.flags;
2050
2051            CODEC_LOGV("FILL_BUFFER_DONE(buffer: %p, size: %ld, flags: 0x%08lx, timestamp: %lld us (%.2f secs))",
2052                 buffer,
2053                 msg.u.extended_buffer_data.range_length,
2054                 flags,
2055                 msg.u.extended_buffer_data.timestamp,
2056                 msg.u.extended_buffer_data.timestamp / 1E6);
2057
2058            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2059            size_t i = 0;
2060            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
2061                ++i;
2062            }
2063
2064            CHECK(i < buffers->size());
2065            BufferInfo *info = &buffers->editItemAt(i);
2066
2067            if (info->mStatus != OWNED_BY_COMPONENT) {
2068                LOGW("We already own output buffer %p, yet received "
2069                     "a FILL_BUFFER_DONE.", buffer);
2070            }
2071
2072            info->mStatus = OWNED_BY_US;
2073
2074            if (mPortStatus[kPortIndexOutput] == DISABLING) {
2075                CODEC_LOGV("Port is disabled, freeing buffer %p", buffer);
2076
2077                status_t err = freeBuffer(kPortIndexOutput, i);
2078                CHECK_EQ(err, (status_t)OK);
2079
2080#if 0
2081            } else if (mPortStatus[kPortIndexOutput] == ENABLED
2082                       && (flags & OMX_BUFFERFLAG_EOS)) {
2083                CODEC_LOGV("No more output data.");
2084                mNoMoreOutputData = true;
2085                mBufferFilled.signal();
2086#endif
2087            } else if (mPortStatus[kPortIndexOutput] != SHUTTING_DOWN) {
2088                CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED);
2089
2090                if (info->mMediaBuffer == NULL) {
2091                    CHECK(mOMXLivesLocally);
2092                    CHECK(mQuirks & kRequiresAllocateBufferOnOutputPorts);
2093                    CHECK(mQuirks & kDefersOutputBufferAllocation);
2094
2095                    // The qcom video decoders on Nexus don't actually allocate
2096                    // output buffer memory on a call to OMX_AllocateBuffer
2097                    // the "pBuffer" member of the OMX_BUFFERHEADERTYPE
2098                    // structure is only filled in later.
2099
2100                    info->mMediaBuffer = new MediaBuffer(
2101                            msg.u.extended_buffer_data.data_ptr,
2102                            info->mSize);
2103                    info->mMediaBuffer->setObserver(this);
2104                }
2105
2106                MediaBuffer *buffer = info->mMediaBuffer;
2107                bool isGraphicBuffer = buffer->graphicBuffer() != NULL;
2108
2109                if (!isGraphicBuffer
2110                    && msg.u.extended_buffer_data.range_offset
2111                        + msg.u.extended_buffer_data.range_length
2112                            > buffer->size()) {
2113                    CODEC_LOGE(
2114                            "Codec lied about its buffer size requirements, "
2115                            "sending a buffer larger than the originally "
2116                            "advertised size in FILL_BUFFER_DONE!");
2117                }
2118                buffer->set_range(
2119                        msg.u.extended_buffer_data.range_offset,
2120                        msg.u.extended_buffer_data.range_length);
2121
2122                buffer->meta_data()->clear();
2123
2124                buffer->meta_data()->setInt64(
2125                        kKeyTime, msg.u.extended_buffer_data.timestamp);
2126
2127                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_SYNCFRAME) {
2128                    buffer->meta_data()->setInt32(kKeyIsSyncFrame, true);
2129                }
2130                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_CODECCONFIG) {
2131                    buffer->meta_data()->setInt32(kKeyIsCodecConfig, true);
2132                }
2133
2134                if (isGraphicBuffer || mQuirks & kOutputBuffersAreUnreadable) {
2135                    buffer->meta_data()->setInt32(kKeyIsUnreadable, true);
2136                }
2137
2138                buffer->meta_data()->setPointer(
2139                        kKeyPlatformPrivate,
2140                        msg.u.extended_buffer_data.platform_private);
2141
2142                buffer->meta_data()->setPointer(
2143                        kKeyBufferID,
2144                        msg.u.extended_buffer_data.buffer);
2145
2146                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_EOS) {
2147                    CODEC_LOGV("No more output data.");
2148                    mNoMoreOutputData = true;
2149                }
2150
2151                if (mTargetTimeUs >= 0) {
2152                    CHECK(msg.u.extended_buffer_data.timestamp <= mTargetTimeUs);
2153
2154                    if (msg.u.extended_buffer_data.timestamp < mTargetTimeUs) {
2155                        CODEC_LOGV(
2156                                "skipping output buffer at timestamp %lld us",
2157                                msg.u.extended_buffer_data.timestamp);
2158
2159                        fillOutputBuffer(info);
2160                        break;
2161                    }
2162
2163                    CODEC_LOGV(
2164                            "returning output buffer at target timestamp "
2165                            "%lld us",
2166                            msg.u.extended_buffer_data.timestamp);
2167
2168                    mTargetTimeUs = -1;
2169                }
2170
2171                mFilledBuffers.push_back(i);
2172                mBufferFilled.signal();
2173                if (mIsEncoder) {
2174                    sched_yield();
2175                }
2176            }
2177
2178            break;
2179        }
2180
2181        default:
2182        {
2183            CHECK(!"should not be here.");
2184            break;
2185        }
2186    }
2187}
2188
2189// Has the format changed in any way that the client would have to be aware of?
2190static bool formatHasNotablyChanged(
2191        const sp<MetaData> &from, const sp<MetaData> &to) {
2192    if (from.get() == NULL && to.get() == NULL) {
2193        return false;
2194    }
2195
2196    if ((from.get() == NULL && to.get() != NULL)
2197        || (from.get() != NULL && to.get() == NULL)) {
2198        return true;
2199    }
2200
2201    const char *mime_from, *mime_to;
2202    CHECK(from->findCString(kKeyMIMEType, &mime_from));
2203    CHECK(to->findCString(kKeyMIMEType, &mime_to));
2204
2205    if (strcasecmp(mime_from, mime_to)) {
2206        return true;
2207    }
2208
2209    if (!strcasecmp(mime_from, MEDIA_MIMETYPE_VIDEO_RAW)) {
2210        int32_t colorFormat_from, colorFormat_to;
2211        CHECK(from->findInt32(kKeyColorFormat, &colorFormat_from));
2212        CHECK(to->findInt32(kKeyColorFormat, &colorFormat_to));
2213
2214        if (colorFormat_from != colorFormat_to) {
2215            return true;
2216        }
2217
2218        int32_t width_from, width_to;
2219        CHECK(from->findInt32(kKeyWidth, &width_from));
2220        CHECK(to->findInt32(kKeyWidth, &width_to));
2221
2222        if (width_from != width_to) {
2223            return true;
2224        }
2225
2226        int32_t height_from, height_to;
2227        CHECK(from->findInt32(kKeyHeight, &height_from));
2228        CHECK(to->findInt32(kKeyHeight, &height_to));
2229
2230        if (height_from != height_to) {
2231            return true;
2232        }
2233
2234        int32_t left_from, top_from, right_from, bottom_from;
2235        CHECK(from->findRect(
2236                    kKeyCropRect,
2237                    &left_from, &top_from, &right_from, &bottom_from));
2238
2239        int32_t left_to, top_to, right_to, bottom_to;
2240        CHECK(to->findRect(
2241                    kKeyCropRect,
2242                    &left_to, &top_to, &right_to, &bottom_to));
2243
2244        if (left_to != left_from || top_to != top_from
2245                || right_to != right_from || bottom_to != bottom_from) {
2246            return true;
2247        }
2248    } else if (!strcasecmp(mime_from, MEDIA_MIMETYPE_AUDIO_RAW)) {
2249        int32_t numChannels_from, numChannels_to;
2250        CHECK(from->findInt32(kKeyChannelCount, &numChannels_from));
2251        CHECK(to->findInt32(kKeyChannelCount, &numChannels_to));
2252
2253        if (numChannels_from != numChannels_to) {
2254            return true;
2255        }
2256
2257        int32_t sampleRate_from, sampleRate_to;
2258        CHECK(from->findInt32(kKeySampleRate, &sampleRate_from));
2259        CHECK(to->findInt32(kKeySampleRate, &sampleRate_to));
2260
2261        if (sampleRate_from != sampleRate_to) {
2262            return true;
2263        }
2264    }
2265
2266    return false;
2267}
2268
2269void OMXCodec::onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) {
2270    switch (event) {
2271        case OMX_EventCmdComplete:
2272        {
2273            onCmdComplete((OMX_COMMANDTYPE)data1, data2);
2274            break;
2275        }
2276
2277        case OMX_EventError:
2278        {
2279            CODEC_LOGE("ERROR(0x%08lx, %ld)", data1, data2);
2280
2281            setState(ERROR);
2282            break;
2283        }
2284
2285        case OMX_EventPortSettingsChanged:
2286        {
2287            CODEC_LOGV("OMX_EventPortSettingsChanged(port=%ld, data2=0x%08lx)",
2288                       data1, data2);
2289
2290            if (data2 == 0 || data2 == OMX_IndexParamPortDefinition) {
2291                onPortSettingsChanged(data1);
2292            } else if (data1 == kPortIndexOutput &&
2293                        (data2 == OMX_IndexConfigCommonOutputCrop ||
2294                         data2 == OMX_IndexConfigCommonScale)) {
2295
2296                sp<MetaData> oldOutputFormat = mOutputFormat;
2297                initOutputFormat(mSource->getFormat());
2298
2299                if (data2 == OMX_IndexConfigCommonOutputCrop &&
2300                    formatHasNotablyChanged(oldOutputFormat, mOutputFormat)) {
2301                    mOutputPortSettingsHaveChanged = true;
2302
2303                    if (mNativeWindow != NULL) {
2304                        int32_t left, top, right, bottom;
2305                        CHECK(mOutputFormat->findRect(
2306                                    kKeyCropRect,
2307                                    &left, &top, &right, &bottom));
2308
2309                        android_native_rect_t crop;
2310                        crop.left = left;
2311                        crop.top = top;
2312                        crop.right = right + 1;
2313                        crop.bottom = bottom + 1;
2314
2315                        // We'll ignore any errors here, if the surface is
2316                        // already invalid, we'll know soon enough.
2317                        native_window_set_crop(mNativeWindow.get(), &crop);
2318                    }
2319                } else if (data2 == OMX_IndexConfigCommonScale) {
2320                    OMX_CONFIG_SCALEFACTORTYPE scale;
2321                    InitOMXParams(&scale);
2322                    scale.nPortIndex = kPortIndexOutput;
2323
2324                    // Change display dimension only when necessary.
2325                    if (OK == mOMX->getConfig(
2326                                        mNode,
2327                                        OMX_IndexConfigCommonScale,
2328                                        &scale, sizeof(scale))) {
2329                        int32_t left, top, right, bottom;
2330                        CHECK(mOutputFormat->findRect(kKeyCropRect,
2331                                                      &left, &top,
2332                                                      &right, &bottom));
2333
2334                        // The scale is in 16.16 format.
2335                        // scale 1.0 = 0x010000. When there is no
2336                        // need to change the display, skip it.
2337                        LOGV("Get OMX_IndexConfigScale: 0x%lx/0x%lx",
2338                                scale.xWidth, scale.xHeight);
2339
2340                        if (scale.xWidth != 0x010000) {
2341                            mOutputFormat->setInt32(kKeyDisplayWidth,
2342                                    ((right - left +  1) * scale.xWidth)  >> 16);
2343                            mOutputPortSettingsHaveChanged = true;
2344                        }
2345
2346                        if (scale.xHeight != 0x010000) {
2347                            mOutputFormat->setInt32(kKeyDisplayHeight,
2348                                    ((bottom  - top + 1) * scale.xHeight) >> 16);
2349                            mOutputPortSettingsHaveChanged = true;
2350                        }
2351                    }
2352                }
2353            }
2354            break;
2355        }
2356
2357#if 0
2358        case OMX_EventBufferFlag:
2359        {
2360            CODEC_LOGV("EVENT_BUFFER_FLAG(%ld)", data1);
2361
2362            if (data1 == kPortIndexOutput) {
2363                mNoMoreOutputData = true;
2364            }
2365            break;
2366        }
2367#endif
2368
2369        default:
2370        {
2371            CODEC_LOGV("EVENT(%d, %ld, %ld)", event, data1, data2);
2372            break;
2373        }
2374    }
2375}
2376
2377void OMXCodec::onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data) {
2378    switch (cmd) {
2379        case OMX_CommandStateSet:
2380        {
2381            onStateChange((OMX_STATETYPE)data);
2382            break;
2383        }
2384
2385        case OMX_CommandPortDisable:
2386        {
2387            OMX_U32 portIndex = data;
2388            CODEC_LOGV("PORT_DISABLED(%ld)", portIndex);
2389
2390            CHECK(mState == EXECUTING || mState == RECONFIGURING);
2391            CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLING);
2392            CHECK_EQ(mPortBuffers[portIndex].size(), 0u);
2393
2394            mPortStatus[portIndex] = DISABLED;
2395
2396            if (mState == RECONFIGURING) {
2397                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2398
2399                sp<MetaData> oldOutputFormat = mOutputFormat;
2400                initOutputFormat(mSource->getFormat());
2401
2402                // Don't notify clients if the output port settings change
2403                // wasn't of importance to them, i.e. it may be that just the
2404                // number of buffers has changed and nothing else.
2405                mOutputPortSettingsHaveChanged =
2406                    formatHasNotablyChanged(oldOutputFormat, mOutputFormat);
2407
2408                enablePortAsync(portIndex);
2409
2410                status_t err = allocateBuffersOnPort(portIndex);
2411
2412                if (err != OK) {
2413                    CODEC_LOGE("allocateBuffersOnPort failed (err = %d)", err);
2414                    setState(ERROR);
2415                }
2416            }
2417            break;
2418        }
2419
2420        case OMX_CommandPortEnable:
2421        {
2422            OMX_U32 portIndex = data;
2423            CODEC_LOGV("PORT_ENABLED(%ld)", portIndex);
2424
2425            CHECK(mState == EXECUTING || mState == RECONFIGURING);
2426            CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLING);
2427
2428            mPortStatus[portIndex] = ENABLED;
2429
2430            if (mState == RECONFIGURING) {
2431                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2432
2433                setState(EXECUTING);
2434
2435                fillOutputBuffers();
2436            }
2437            break;
2438        }
2439
2440        case OMX_CommandFlush:
2441        {
2442            OMX_U32 portIndex = data;
2443
2444            CODEC_LOGV("FLUSH_DONE(%ld)", portIndex);
2445
2446            CHECK_EQ((int)mPortStatus[portIndex], (int)SHUTTING_DOWN);
2447            mPortStatus[portIndex] = ENABLED;
2448
2449            CHECK_EQ(countBuffersWeOwn(mPortBuffers[portIndex]),
2450                     mPortBuffers[portIndex].size());
2451
2452            if (mState == RECONFIGURING) {
2453                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2454
2455                disablePortAsync(portIndex);
2456            } else if (mState == EXECUTING_TO_IDLE) {
2457                if (mPortStatus[kPortIndexInput] == ENABLED
2458                    && mPortStatus[kPortIndexOutput] == ENABLED) {
2459                    CODEC_LOGV("Finished flushing both ports, now completing "
2460                         "transition from EXECUTING to IDLE.");
2461
2462                    mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
2463                    mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
2464
2465                    status_t err =
2466                        mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
2467                    CHECK_EQ(err, (status_t)OK);
2468                }
2469            } else {
2470                // We're flushing both ports in preparation for seeking.
2471
2472                if (mPortStatus[kPortIndexInput] == ENABLED
2473                    && mPortStatus[kPortIndexOutput] == ENABLED) {
2474                    CODEC_LOGV("Finished flushing both ports, now continuing from"
2475                         " seek-time.");
2476
2477                    // We implicitly resume pulling on our upstream source.
2478                    mPaused = false;
2479
2480                    drainInputBuffers();
2481                    fillOutputBuffers();
2482                }
2483
2484                if (mOutputPortSettingsChangedPending) {
2485                    CODEC_LOGV(
2486                            "Honoring deferred output port settings change.");
2487
2488                    mOutputPortSettingsChangedPending = false;
2489                    onPortSettingsChanged(kPortIndexOutput);
2490                }
2491            }
2492
2493            break;
2494        }
2495
2496        default:
2497        {
2498            CODEC_LOGV("CMD_COMPLETE(%d, %ld)", cmd, data);
2499            break;
2500        }
2501    }
2502}
2503
2504void OMXCodec::onStateChange(OMX_STATETYPE newState) {
2505    CODEC_LOGV("onStateChange %d", newState);
2506
2507    switch (newState) {
2508        case OMX_StateIdle:
2509        {
2510            CODEC_LOGV("Now Idle.");
2511            if (mState == LOADED_TO_IDLE) {
2512                status_t err = mOMX->sendCommand(
2513                        mNode, OMX_CommandStateSet, OMX_StateExecuting);
2514
2515                CHECK_EQ(err, (status_t)OK);
2516
2517                setState(IDLE_TO_EXECUTING);
2518            } else {
2519                CHECK_EQ((int)mState, (int)EXECUTING_TO_IDLE);
2520
2521                CHECK_EQ(
2522                    countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
2523                    mPortBuffers[kPortIndexInput].size());
2524
2525                CHECK_EQ(
2526                    countBuffersWeOwn(mPortBuffers[kPortIndexOutput]),
2527                    mPortBuffers[kPortIndexOutput].size());
2528
2529                status_t err = mOMX->sendCommand(
2530                        mNode, OMX_CommandStateSet, OMX_StateLoaded);
2531
2532                CHECK_EQ(err, (status_t)OK);
2533
2534                err = freeBuffersOnPort(kPortIndexInput);
2535                CHECK_EQ(err, (status_t)OK);
2536
2537                err = freeBuffersOnPort(kPortIndexOutput);
2538                CHECK_EQ(err, (status_t)OK);
2539
2540                mPortStatus[kPortIndexInput] = ENABLED;
2541                mPortStatus[kPortIndexOutput] = ENABLED;
2542
2543                setState(IDLE_TO_LOADED);
2544            }
2545            break;
2546        }
2547
2548        case OMX_StateExecuting:
2549        {
2550            CHECK_EQ((int)mState, (int)IDLE_TO_EXECUTING);
2551
2552            CODEC_LOGV("Now Executing.");
2553
2554            mOutputPortSettingsChangedPending = false;
2555
2556            setState(EXECUTING);
2557
2558            // Buffers will be submitted to the component in the first
2559            // call to OMXCodec::read as mInitialBufferSubmit is true at
2560            // this point. This ensures that this on_message call returns,
2561            // releases the lock and ::init can notice the state change and
2562            // itself return.
2563            break;
2564        }
2565
2566        case OMX_StateLoaded:
2567        {
2568            CHECK_EQ((int)mState, (int)IDLE_TO_LOADED);
2569
2570            CODEC_LOGV("Now Loaded.");
2571
2572            setState(LOADED);
2573            break;
2574        }
2575
2576        case OMX_StateInvalid:
2577        {
2578            setState(ERROR);
2579            break;
2580        }
2581
2582        default:
2583        {
2584            CHECK(!"should not be here.");
2585            break;
2586        }
2587    }
2588}
2589
2590// static
2591size_t OMXCodec::countBuffersWeOwn(const Vector<BufferInfo> &buffers) {
2592    size_t n = 0;
2593    for (size_t i = 0; i < buffers.size(); ++i) {
2594        if (buffers[i].mStatus != OWNED_BY_COMPONENT) {
2595            ++n;
2596        }
2597    }
2598
2599    return n;
2600}
2601
2602status_t OMXCodec::freeBuffersOnPort(
2603        OMX_U32 portIndex, bool onlyThoseWeOwn) {
2604    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
2605
2606    status_t stickyErr = OK;
2607
2608    for (size_t i = buffers->size(); i-- > 0;) {
2609        BufferInfo *info = &buffers->editItemAt(i);
2610
2611        if (onlyThoseWeOwn && info->mStatus == OWNED_BY_COMPONENT) {
2612            continue;
2613        }
2614
2615        CHECK(info->mStatus == OWNED_BY_US
2616                || info->mStatus == OWNED_BY_NATIVE_WINDOW);
2617
2618        CODEC_LOGV("freeing buffer %p on port %ld", info->mBuffer, portIndex);
2619
2620        status_t err = freeBuffer(portIndex, i);
2621
2622        if (err != OK) {
2623            stickyErr = err;
2624        }
2625
2626    }
2627
2628    CHECK(onlyThoseWeOwn || buffers->isEmpty());
2629
2630    return stickyErr;
2631}
2632
2633status_t OMXCodec::freeBuffer(OMX_U32 portIndex, size_t bufIndex) {
2634    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
2635
2636    BufferInfo *info = &buffers->editItemAt(bufIndex);
2637
2638    status_t err = mOMX->freeBuffer(mNode, portIndex, info->mBuffer);
2639
2640    if (err == OK && info->mMediaBuffer != NULL) {
2641        CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2642        info->mMediaBuffer->setObserver(NULL);
2643
2644        // Make sure nobody but us owns this buffer at this point.
2645        CHECK_EQ(info->mMediaBuffer->refcount(), 0);
2646
2647        // Cancel the buffer if it belongs to an ANativeWindow.
2648        sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer();
2649        if (info->mStatus == OWNED_BY_US && graphicBuffer != 0) {
2650            err = cancelBufferToNativeWindow(info);
2651        }
2652
2653        info->mMediaBuffer->release();
2654        info->mMediaBuffer = NULL;
2655    }
2656
2657    if (err == OK) {
2658        buffers->removeAt(bufIndex);
2659    }
2660
2661    return err;
2662}
2663
2664void OMXCodec::onPortSettingsChanged(OMX_U32 portIndex) {
2665    CODEC_LOGV("PORT_SETTINGS_CHANGED(%ld)", portIndex);
2666
2667    CHECK_EQ((int)mState, (int)EXECUTING);
2668    CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2669    CHECK(!mOutputPortSettingsChangedPending);
2670
2671    if (mPortStatus[kPortIndexOutput] != ENABLED) {
2672        CODEC_LOGV("Deferring output port settings change.");
2673        mOutputPortSettingsChangedPending = true;
2674        return;
2675    }
2676
2677    setState(RECONFIGURING);
2678
2679    if (mQuirks & kNeedsFlushBeforeDisable) {
2680        if (!flushPortAsync(portIndex)) {
2681            onCmdComplete(OMX_CommandFlush, portIndex);
2682        }
2683    } else {
2684        disablePortAsync(portIndex);
2685    }
2686}
2687
2688bool OMXCodec::flushPortAsync(OMX_U32 portIndex) {
2689    CHECK(mState == EXECUTING || mState == RECONFIGURING
2690            || mState == EXECUTING_TO_IDLE);
2691
2692    CODEC_LOGV("flushPortAsync(%ld): we own %d out of %d buffers already.",
2693         portIndex, countBuffersWeOwn(mPortBuffers[portIndex]),
2694         mPortBuffers[portIndex].size());
2695
2696    CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED);
2697    mPortStatus[portIndex] = SHUTTING_DOWN;
2698
2699    if ((mQuirks & kRequiresFlushCompleteEmulation)
2700        && countBuffersWeOwn(mPortBuffers[portIndex])
2701                == mPortBuffers[portIndex].size()) {
2702        // No flush is necessary and this component fails to send a
2703        // flush-complete event in this case.
2704
2705        return false;
2706    }
2707
2708    status_t err =
2709        mOMX->sendCommand(mNode, OMX_CommandFlush, portIndex);
2710    CHECK_EQ(err, (status_t)OK);
2711
2712    return true;
2713}
2714
2715void OMXCodec::disablePortAsync(OMX_U32 portIndex) {
2716    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2717
2718    CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED);
2719    mPortStatus[portIndex] = DISABLING;
2720
2721    CODEC_LOGV("sending OMX_CommandPortDisable(%ld)", portIndex);
2722    status_t err =
2723        mOMX->sendCommand(mNode, OMX_CommandPortDisable, portIndex);
2724    CHECK_EQ(err, (status_t)OK);
2725
2726    freeBuffersOnPort(portIndex, true);
2727}
2728
2729void OMXCodec::enablePortAsync(OMX_U32 portIndex) {
2730    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2731
2732    CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLED);
2733    mPortStatus[portIndex] = ENABLING;
2734
2735    CODEC_LOGV("sending OMX_CommandPortEnable(%ld)", portIndex);
2736    status_t err =
2737        mOMX->sendCommand(mNode, OMX_CommandPortEnable, portIndex);
2738    CHECK_EQ(err, (status_t)OK);
2739}
2740
2741void OMXCodec::fillOutputBuffers() {
2742    CHECK_EQ((int)mState, (int)EXECUTING);
2743
2744    // This is a workaround for some decoders not properly reporting
2745    // end-of-output-stream. If we own all input buffers and also own
2746    // all output buffers and we already signalled end-of-input-stream,
2747    // the end-of-output-stream is implied.
2748    if (mSignalledEOS
2749            && countBuffersWeOwn(mPortBuffers[kPortIndexInput])
2750                == mPortBuffers[kPortIndexInput].size()
2751            && countBuffersWeOwn(mPortBuffers[kPortIndexOutput])
2752                == mPortBuffers[kPortIndexOutput].size()) {
2753        mNoMoreOutputData = true;
2754        mBufferFilled.signal();
2755
2756        return;
2757    }
2758
2759    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2760    for (size_t i = 0; i < buffers->size(); ++i) {
2761        BufferInfo *info = &buffers->editItemAt(i);
2762        if (info->mStatus == OWNED_BY_US) {
2763            fillOutputBuffer(&buffers->editItemAt(i));
2764        }
2765    }
2766}
2767
2768void OMXCodec::drainInputBuffers() {
2769    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2770
2771    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2772    for (size_t i = 0; i < buffers->size(); ++i) {
2773        BufferInfo *info = &buffers->editItemAt(i);
2774
2775        if (info->mStatus != OWNED_BY_US) {
2776            continue;
2777        }
2778
2779        if (!drainInputBuffer(info)) {
2780            break;
2781        }
2782
2783        if (mOnlySubmitOneBufferAtOneTime) {
2784            break;
2785        }
2786    }
2787}
2788
2789bool OMXCodec::drainInputBuffer(BufferInfo *info) {
2790    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
2791
2792    if (mSignalledEOS) {
2793        return false;
2794    }
2795
2796    if (mCodecSpecificDataIndex < mCodecSpecificData.size()) {
2797        const CodecSpecificData *specific =
2798            mCodecSpecificData[mCodecSpecificDataIndex];
2799
2800        size_t size = specific->mSize;
2801
2802        if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mMIME)
2803                && !(mQuirks & kWantsNALFragments)) {
2804            static const uint8_t kNALStartCode[4] =
2805                    { 0x00, 0x00, 0x00, 0x01 };
2806
2807            CHECK(info->mSize >= specific->mSize + 4);
2808
2809            size += 4;
2810
2811            memcpy(info->mData, kNALStartCode, 4);
2812            memcpy((uint8_t *)info->mData + 4,
2813                   specific->mData, specific->mSize);
2814        } else {
2815            CHECK(info->mSize >= specific->mSize);
2816            memcpy(info->mData, specific->mData, specific->mSize);
2817        }
2818
2819        mNoMoreOutputData = false;
2820
2821        CODEC_LOGV("calling emptyBuffer with codec specific data");
2822
2823        status_t err = mOMX->emptyBuffer(
2824                mNode, info->mBuffer, 0, size,
2825                OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG,
2826                0);
2827        CHECK_EQ(err, (status_t)OK);
2828
2829        info->mStatus = OWNED_BY_COMPONENT;
2830
2831        ++mCodecSpecificDataIndex;
2832        return true;
2833    }
2834
2835    if (mPaused) {
2836        return false;
2837    }
2838
2839    status_t err;
2840
2841    bool signalEOS = false;
2842    int64_t timestampUs = 0;
2843
2844    size_t offset = 0;
2845    int32_t n = 0;
2846
2847    for (;;) {
2848        MediaBuffer *srcBuffer;
2849        if (mSeekTimeUs >= 0) {
2850            if (mLeftOverBuffer) {
2851                mLeftOverBuffer->release();
2852                mLeftOverBuffer = NULL;
2853            }
2854
2855            MediaSource::ReadOptions options;
2856            options.setSeekTo(mSeekTimeUs, mSeekMode);
2857
2858            mSeekTimeUs = -1;
2859            mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC;
2860            mBufferFilled.signal();
2861
2862            err = mSource->read(&srcBuffer, &options);
2863
2864            if (err == OK) {
2865                int64_t targetTimeUs;
2866                if (srcBuffer->meta_data()->findInt64(
2867                            kKeyTargetTime, &targetTimeUs)
2868                        && targetTimeUs >= 0) {
2869                    CODEC_LOGV("targetTimeUs = %lld us", targetTimeUs);
2870                    mTargetTimeUs = targetTimeUs;
2871                } else {
2872                    mTargetTimeUs = -1;
2873                }
2874            }
2875        } else if (mLeftOverBuffer) {
2876            srcBuffer = mLeftOverBuffer;
2877            mLeftOverBuffer = NULL;
2878
2879            err = OK;
2880        } else {
2881            err = mSource->read(&srcBuffer);
2882        }
2883
2884        if (err != OK) {
2885            signalEOS = true;
2886            mFinalStatus = err;
2887            mSignalledEOS = true;
2888            mBufferFilled.signal();
2889            break;
2890        }
2891
2892        size_t remainingBytes = info->mSize - offset;
2893
2894        if (srcBuffer->range_length() > remainingBytes) {
2895            if (offset == 0) {
2896                CODEC_LOGE(
2897                     "Codec's input buffers are too small to accomodate "
2898                     "buffer read from source (info->mSize = %d, srcLength = %d)",
2899                     info->mSize, srcBuffer->range_length());
2900
2901                srcBuffer->release();
2902                srcBuffer = NULL;
2903
2904                setState(ERROR);
2905                return false;
2906            }
2907
2908            mLeftOverBuffer = srcBuffer;
2909            break;
2910        }
2911
2912        bool releaseBuffer = true;
2913        if (mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames)) {
2914            CHECK(mOMXLivesLocally && offset == 0);
2915
2916            OMX_BUFFERHEADERTYPE *header =
2917                (OMX_BUFFERHEADERTYPE *)info->mBuffer;
2918
2919            CHECK(header->pBuffer == info->mData);
2920
2921            header->pBuffer =
2922                (OMX_U8 *)srcBuffer->data() + srcBuffer->range_offset();
2923
2924            releaseBuffer = false;
2925            info->mMediaBuffer = srcBuffer;
2926        } else {
2927            if (mIsMetaDataStoredInVideoBuffers) {
2928                releaseBuffer = false;
2929                info->mMediaBuffer = srcBuffer;
2930            }
2931            memcpy((uint8_t *)info->mData + offset,
2932                    (const uint8_t *)srcBuffer->data()
2933                        + srcBuffer->range_offset(),
2934                    srcBuffer->range_length());
2935        }
2936
2937        int64_t lastBufferTimeUs;
2938        CHECK(srcBuffer->meta_data()->findInt64(kKeyTime, &lastBufferTimeUs));
2939        CHECK(lastBufferTimeUs >= 0);
2940
2941        if (offset == 0) {
2942            timestampUs = lastBufferTimeUs;
2943        }
2944
2945        offset += srcBuffer->range_length();
2946
2947        if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_VORBIS, mMIME)) {
2948            CHECK(!(mQuirks & kSupportsMultipleFramesPerInputBuffer));
2949            CHECK_GE(info->mSize, offset + sizeof(int32_t));
2950
2951            int32_t numPageSamples;
2952            if (!srcBuffer->meta_data()->findInt32(
2953                        kKeyValidSamples, &numPageSamples)) {
2954                numPageSamples = -1;
2955            }
2956
2957            memcpy((uint8_t *)info->mData + offset,
2958                   &numPageSamples,
2959                   sizeof(numPageSamples));
2960
2961            offset += sizeof(numPageSamples);
2962        }
2963
2964        if (releaseBuffer) {
2965            srcBuffer->release();
2966            srcBuffer = NULL;
2967        }
2968
2969        ++n;
2970
2971        if (!(mQuirks & kSupportsMultipleFramesPerInputBuffer)) {
2972            break;
2973        }
2974
2975        int64_t coalescedDurationUs = lastBufferTimeUs - timestampUs;
2976
2977        if (coalescedDurationUs > 250000ll) {
2978            // Don't coalesce more than 250ms worth of encoded data at once.
2979            break;
2980        }
2981    }
2982
2983    if (n > 1) {
2984        LOGV("coalesced %d frames into one input buffer", n);
2985    }
2986
2987    OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME;
2988
2989    if (signalEOS) {
2990        flags |= OMX_BUFFERFLAG_EOS;
2991    } else {
2992        mNoMoreOutputData = false;
2993    }
2994
2995    CODEC_LOGV("Calling emptyBuffer on buffer %p (length %d), "
2996               "timestamp %lld us (%.2f secs)",
2997               info->mBuffer, offset,
2998               timestampUs, timestampUs / 1E6);
2999
3000    err = mOMX->emptyBuffer(
3001            mNode, info->mBuffer, 0, offset,
3002            flags, timestampUs);
3003
3004    if (err != OK) {
3005        setState(ERROR);
3006        return false;
3007    }
3008
3009    info->mStatus = OWNED_BY_COMPONENT;
3010
3011    // This component does not ever signal the EOS flag on output buffers,
3012    // Thanks for nothing.
3013    if (mSignalledEOS && !strcmp(mComponentName, "OMX.TI.Video.encoder")) {
3014        mNoMoreOutputData = true;
3015        mBufferFilled.signal();
3016    }
3017
3018    return true;
3019}
3020
3021void OMXCodec::fillOutputBuffer(BufferInfo *info) {
3022    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
3023
3024    if (mNoMoreOutputData) {
3025        CODEC_LOGV("There is no more output data available, not "
3026             "calling fillOutputBuffer");
3027        return;
3028    }
3029
3030    if (info->mMediaBuffer != NULL) {
3031        sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer();
3032        if (graphicBuffer != 0) {
3033            // When using a native buffer we need to lock the buffer before
3034            // giving it to OMX.
3035            CODEC_LOGV("Calling lockBuffer on %p", info->mBuffer);
3036            int err = mNativeWindow->lockBuffer(mNativeWindow.get(),
3037                    graphicBuffer.get());
3038            if (err != 0) {
3039                CODEC_LOGE("lockBuffer failed w/ error 0x%08x", err);
3040
3041                setState(ERROR);
3042                return;
3043            }
3044        }
3045    }
3046
3047    CODEC_LOGV("Calling fillBuffer on buffer %p", info->mBuffer);
3048    status_t err = mOMX->fillBuffer(mNode, info->mBuffer);
3049
3050    if (err != OK) {
3051        CODEC_LOGE("fillBuffer failed w/ error 0x%08x", err);
3052
3053        setState(ERROR);
3054        return;
3055    }
3056
3057    info->mStatus = OWNED_BY_COMPONENT;
3058}
3059
3060bool OMXCodec::drainInputBuffer(IOMX::buffer_id buffer) {
3061    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
3062    for (size_t i = 0; i < buffers->size(); ++i) {
3063        if ((*buffers)[i].mBuffer == buffer) {
3064            return drainInputBuffer(&buffers->editItemAt(i));
3065        }
3066    }
3067
3068    CHECK(!"should not be here.");
3069
3070    return false;
3071}
3072
3073void OMXCodec::fillOutputBuffer(IOMX::buffer_id buffer) {
3074    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
3075    for (size_t i = 0; i < buffers->size(); ++i) {
3076        if ((*buffers)[i].mBuffer == buffer) {
3077            fillOutputBuffer(&buffers->editItemAt(i));
3078            return;
3079        }
3080    }
3081
3082    CHECK(!"should not be here.");
3083}
3084
3085void OMXCodec::setState(State newState) {
3086    mState = newState;
3087    mAsyncCompletion.signal();
3088
3089    // This may cause some spurious wakeups but is necessary to
3090    // unblock the reader if we enter ERROR state.
3091    mBufferFilled.signal();
3092}
3093
3094void OMXCodec::setRawAudioFormat(
3095        OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels) {
3096
3097    // port definition
3098    OMX_PARAM_PORTDEFINITIONTYPE def;
3099    InitOMXParams(&def);
3100    def.nPortIndex = portIndex;
3101    status_t err = mOMX->getParameter(
3102            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3103    CHECK_EQ(err, (status_t)OK);
3104    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
3105    CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition,
3106            &def, sizeof(def)), (status_t)OK);
3107
3108    // pcm param
3109    OMX_AUDIO_PARAM_PCMMODETYPE pcmParams;
3110    InitOMXParams(&pcmParams);
3111    pcmParams.nPortIndex = portIndex;
3112
3113    err = mOMX->getParameter(
3114            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
3115
3116    CHECK_EQ(err, (status_t)OK);
3117
3118    pcmParams.nChannels = numChannels;
3119    pcmParams.eNumData = OMX_NumericalDataSigned;
3120    pcmParams.bInterleaved = OMX_TRUE;
3121    pcmParams.nBitPerSample = 16;
3122    pcmParams.nSamplingRate = sampleRate;
3123    pcmParams.ePCMMode = OMX_AUDIO_PCMModeLinear;
3124
3125    if (numChannels == 1) {
3126        pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelCF;
3127    } else {
3128        CHECK_EQ(numChannels, 2);
3129
3130        pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelLF;
3131        pcmParams.eChannelMapping[1] = OMX_AUDIO_ChannelRF;
3132    }
3133
3134    err = mOMX->setParameter(
3135            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
3136
3137    CHECK_EQ(err, (status_t)OK);
3138}
3139
3140static OMX_AUDIO_AMRBANDMODETYPE pickModeFromBitRate(bool isAMRWB, int32_t bps) {
3141    if (isAMRWB) {
3142        if (bps <= 6600) {
3143            return OMX_AUDIO_AMRBandModeWB0;
3144        } else if (bps <= 8850) {
3145            return OMX_AUDIO_AMRBandModeWB1;
3146        } else if (bps <= 12650) {
3147            return OMX_AUDIO_AMRBandModeWB2;
3148        } else if (bps <= 14250) {
3149            return OMX_AUDIO_AMRBandModeWB3;
3150        } else if (bps <= 15850) {
3151            return OMX_AUDIO_AMRBandModeWB4;
3152        } else if (bps <= 18250) {
3153            return OMX_AUDIO_AMRBandModeWB5;
3154        } else if (bps <= 19850) {
3155            return OMX_AUDIO_AMRBandModeWB6;
3156        } else if (bps <= 23050) {
3157            return OMX_AUDIO_AMRBandModeWB7;
3158        }
3159
3160        // 23850 bps
3161        return OMX_AUDIO_AMRBandModeWB8;
3162    } else {  // AMRNB
3163        if (bps <= 4750) {
3164            return OMX_AUDIO_AMRBandModeNB0;
3165        } else if (bps <= 5150) {
3166            return OMX_AUDIO_AMRBandModeNB1;
3167        } else if (bps <= 5900) {
3168            return OMX_AUDIO_AMRBandModeNB2;
3169        } else if (bps <= 6700) {
3170            return OMX_AUDIO_AMRBandModeNB3;
3171        } else if (bps <= 7400) {
3172            return OMX_AUDIO_AMRBandModeNB4;
3173        } else if (bps <= 7950) {
3174            return OMX_AUDIO_AMRBandModeNB5;
3175        } else if (bps <= 10200) {
3176            return OMX_AUDIO_AMRBandModeNB6;
3177        }
3178
3179        // 12200 bps
3180        return OMX_AUDIO_AMRBandModeNB7;
3181    }
3182}
3183
3184void OMXCodec::setAMRFormat(bool isWAMR, int32_t bitRate) {
3185    OMX_U32 portIndex = mIsEncoder ? kPortIndexOutput : kPortIndexInput;
3186
3187    OMX_AUDIO_PARAM_AMRTYPE def;
3188    InitOMXParams(&def);
3189    def.nPortIndex = portIndex;
3190
3191    status_t err =
3192        mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
3193
3194    CHECK_EQ(err, (status_t)OK);
3195
3196    def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
3197
3198    def.eAMRBandMode = pickModeFromBitRate(isWAMR, bitRate);
3199    err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
3200    CHECK_EQ(err, (status_t)OK);
3201
3202    ////////////////////////
3203
3204    if (mIsEncoder) {
3205        sp<MetaData> format = mSource->getFormat();
3206        int32_t sampleRate;
3207        int32_t numChannels;
3208        CHECK(format->findInt32(kKeySampleRate, &sampleRate));
3209        CHECK(format->findInt32(kKeyChannelCount, &numChannels));
3210
3211        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
3212    }
3213}
3214
3215void OMXCodec::setAACFormat(int32_t numChannels, int32_t sampleRate, int32_t bitRate) {
3216    CHECK(numChannels == 1 || numChannels == 2);
3217    if (mIsEncoder) {
3218        //////////////// input port ////////////////////
3219        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
3220
3221        //////////////// output port ////////////////////
3222        // format
3223        OMX_AUDIO_PARAM_PORTFORMATTYPE format;
3224        format.nPortIndex = kPortIndexOutput;
3225        format.nIndex = 0;
3226        status_t err = OMX_ErrorNone;
3227        while (OMX_ErrorNone == err) {
3228            CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioPortFormat,
3229                    &format, sizeof(format)), (status_t)OK);
3230            if (format.eEncoding == OMX_AUDIO_CodingAAC) {
3231                break;
3232            }
3233            format.nIndex++;
3234        }
3235        CHECK_EQ((status_t)OK, err);
3236        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioPortFormat,
3237                &format, sizeof(format)), (status_t)OK);
3238
3239        // port definition
3240        OMX_PARAM_PORTDEFINITIONTYPE def;
3241        InitOMXParams(&def);
3242        def.nPortIndex = kPortIndexOutput;
3243        CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamPortDefinition,
3244                &def, sizeof(def)), (status_t)OK);
3245        def.format.audio.bFlagErrorConcealment = OMX_TRUE;
3246        def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
3247        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition,
3248                &def, sizeof(def)), (status_t)OK);
3249
3250        // profile
3251        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
3252        InitOMXParams(&profile);
3253        profile.nPortIndex = kPortIndexOutput;
3254        CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioAac,
3255                &profile, sizeof(profile)), (status_t)OK);
3256        profile.nChannels = numChannels;
3257        profile.eChannelMode = (numChannels == 1?
3258                OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo);
3259        profile.nSampleRate = sampleRate;
3260        profile.nBitRate = bitRate;
3261        profile.nAudioBandWidth = 0;
3262        profile.nFrameLength = 0;
3263        profile.nAACtools = OMX_AUDIO_AACToolAll;
3264        profile.nAACERtools = OMX_AUDIO_AACERNone;
3265        profile.eAACProfile = OMX_AUDIO_AACObjectLC;
3266        profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
3267        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioAac,
3268                &profile, sizeof(profile)), (status_t)OK);
3269
3270    } else {
3271        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
3272        InitOMXParams(&profile);
3273        profile.nPortIndex = kPortIndexInput;
3274
3275        status_t err = mOMX->getParameter(
3276                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
3277        CHECK_EQ(err, (status_t)OK);
3278
3279        profile.nChannels = numChannels;
3280        profile.nSampleRate = sampleRate;
3281        profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4ADTS;
3282
3283        err = mOMX->setParameter(
3284                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
3285        CHECK_EQ(err, (status_t)OK);
3286    }
3287}
3288
3289void OMXCodec::setG711Format(int32_t numChannels) {
3290    CHECK(!mIsEncoder);
3291    setRawAudioFormat(kPortIndexInput, 8000, numChannels);
3292}
3293
3294void OMXCodec::setImageOutputFormat(
3295        OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height) {
3296    CODEC_LOGV("setImageOutputFormat(%ld, %ld)", width, height);
3297
3298#if 0
3299    OMX_INDEXTYPE index;
3300    status_t err = mOMX->get_extension_index(
3301            mNode, "OMX.TI.JPEG.decode.Config.OutputColorFormat", &index);
3302    CHECK_EQ(err, (status_t)OK);
3303
3304    err = mOMX->set_config(mNode, index, &format, sizeof(format));
3305    CHECK_EQ(err, (status_t)OK);
3306#endif
3307
3308    OMX_PARAM_PORTDEFINITIONTYPE def;
3309    InitOMXParams(&def);
3310    def.nPortIndex = kPortIndexOutput;
3311
3312    status_t err = mOMX->getParameter(
3313            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3314    CHECK_EQ(err, (status_t)OK);
3315
3316    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage);
3317
3318    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3319
3320    CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingUnused);
3321    imageDef->eColorFormat = format;
3322    imageDef->nFrameWidth = width;
3323    imageDef->nFrameHeight = height;
3324
3325    switch (format) {
3326        case OMX_COLOR_FormatYUV420PackedPlanar:
3327        case OMX_COLOR_FormatYUV411Planar:
3328        {
3329            def.nBufferSize = (width * height * 3) / 2;
3330            break;
3331        }
3332
3333        case OMX_COLOR_FormatCbYCrY:
3334        {
3335            def.nBufferSize = width * height * 2;
3336            break;
3337        }
3338
3339        case OMX_COLOR_Format32bitARGB8888:
3340        {
3341            def.nBufferSize = width * height * 4;
3342            break;
3343        }
3344
3345        case OMX_COLOR_Format16bitARGB4444:
3346        case OMX_COLOR_Format16bitARGB1555:
3347        case OMX_COLOR_Format16bitRGB565:
3348        case OMX_COLOR_Format16bitBGR565:
3349        {
3350            def.nBufferSize = width * height * 2;
3351            break;
3352        }
3353
3354        default:
3355            CHECK(!"Should not be here. Unknown color format.");
3356            break;
3357    }
3358
3359    def.nBufferCountActual = def.nBufferCountMin;
3360
3361    err = mOMX->setParameter(
3362            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3363    CHECK_EQ(err, (status_t)OK);
3364}
3365
3366void OMXCodec::setJPEGInputFormat(
3367        OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize) {
3368    OMX_PARAM_PORTDEFINITIONTYPE def;
3369    InitOMXParams(&def);
3370    def.nPortIndex = kPortIndexInput;
3371
3372    status_t err = mOMX->getParameter(
3373            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3374    CHECK_EQ(err, (status_t)OK);
3375
3376    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage);
3377    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3378
3379    CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingJPEG);
3380    imageDef->nFrameWidth = width;
3381    imageDef->nFrameHeight = height;
3382
3383    def.nBufferSize = compressedSize;
3384    def.nBufferCountActual = def.nBufferCountMin;
3385
3386    err = mOMX->setParameter(
3387            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3388    CHECK_EQ(err, (status_t)OK);
3389}
3390
3391void OMXCodec::addCodecSpecificData(const void *data, size_t size) {
3392    CodecSpecificData *specific =
3393        (CodecSpecificData *)malloc(sizeof(CodecSpecificData) + size - 1);
3394
3395    specific->mSize = size;
3396    memcpy(specific->mData, data, size);
3397
3398    mCodecSpecificData.push(specific);
3399}
3400
3401void OMXCodec::clearCodecSpecificData() {
3402    for (size_t i = 0; i < mCodecSpecificData.size(); ++i) {
3403        free(mCodecSpecificData.editItemAt(i));
3404    }
3405    mCodecSpecificData.clear();
3406    mCodecSpecificDataIndex = 0;
3407}
3408
3409status_t OMXCodec::start(MetaData *meta) {
3410    Mutex::Autolock autoLock(mLock);
3411
3412    if (mState != LOADED) {
3413        return UNKNOWN_ERROR;
3414    }
3415
3416    sp<MetaData> params = new MetaData;
3417    if (mQuirks & kWantsNALFragments) {
3418        params->setInt32(kKeyWantsNALFragments, true);
3419    }
3420    if (meta) {
3421        int64_t startTimeUs = 0;
3422        int64_t timeUs;
3423        if (meta->findInt64(kKeyTime, &timeUs)) {
3424            startTimeUs = timeUs;
3425        }
3426        params->setInt64(kKeyTime, startTimeUs);
3427    }
3428    status_t err = mSource->start(params.get());
3429
3430    if (err != OK) {
3431        return err;
3432    }
3433
3434    mCodecSpecificDataIndex = 0;
3435    mInitialBufferSubmit = true;
3436    mSignalledEOS = false;
3437    mNoMoreOutputData = false;
3438    mOutputPortSettingsHaveChanged = false;
3439    mSeekTimeUs = -1;
3440    mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC;
3441    mTargetTimeUs = -1;
3442    mFilledBuffers.clear();
3443    mPaused = false;
3444
3445    return init();
3446}
3447
3448status_t OMXCodec::stop() {
3449    CODEC_LOGI("stop mState=%d", mState);
3450
3451    Mutex::Autolock autoLock(mLock);
3452
3453    while (isIntermediateState(mState)) {
3454        mAsyncCompletion.wait(mLock);
3455    }
3456
3457    switch (mState) {
3458        case LOADED:
3459        case ERROR:
3460            break;
3461
3462        case EXECUTING:
3463        {
3464            setState(EXECUTING_TO_IDLE);
3465
3466            if (mQuirks & kRequiresFlushBeforeShutdown) {
3467                CODEC_LOGV("This component requires a flush before transitioning "
3468                     "from EXECUTING to IDLE...");
3469
3470                bool emulateInputFlushCompletion =
3471                    !flushPortAsync(kPortIndexInput);
3472
3473                bool emulateOutputFlushCompletion =
3474                    !flushPortAsync(kPortIndexOutput);
3475
3476                if (emulateInputFlushCompletion) {
3477                    onCmdComplete(OMX_CommandFlush, kPortIndexInput);
3478                }
3479
3480                if (emulateOutputFlushCompletion) {
3481                    onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
3482                }
3483            } else {
3484                mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
3485                mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
3486
3487                status_t err =
3488                    mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
3489                CHECK_EQ(err, (status_t)OK);
3490            }
3491
3492            while (mState != LOADED && mState != ERROR) {
3493                mAsyncCompletion.wait(mLock);
3494            }
3495
3496            break;
3497        }
3498
3499        default:
3500        {
3501            CHECK(!"should not be here.");
3502            break;
3503        }
3504    }
3505
3506    if (mLeftOverBuffer) {
3507        mLeftOverBuffer->release();
3508        mLeftOverBuffer = NULL;
3509    }
3510
3511    CODEC_LOGI("stopping video source");
3512    mSource->stop();
3513
3514    CODEC_LOGI("stopped in state %d", mState);
3515
3516    return OK;
3517}
3518
3519sp<MetaData> OMXCodec::getFormat() {
3520    Mutex::Autolock autoLock(mLock);
3521
3522    return mOutputFormat;
3523}
3524
3525status_t OMXCodec::read(
3526        MediaBuffer **buffer, const ReadOptions *options) {
3527    *buffer = NULL;
3528
3529    Mutex::Autolock autoLock(mLock);
3530
3531    if (mState != EXECUTING && mState != RECONFIGURING) {
3532        return UNKNOWN_ERROR;
3533    }
3534
3535    bool seeking = false;
3536    int64_t seekTimeUs;
3537    ReadOptions::SeekMode seekMode;
3538    if (options && options->getSeekTo(&seekTimeUs, &seekMode)) {
3539        seeking = true;
3540    }
3541
3542    if (mInitialBufferSubmit) {
3543        mInitialBufferSubmit = false;
3544
3545        if (seeking) {
3546            CHECK(seekTimeUs >= 0);
3547            mSeekTimeUs = seekTimeUs;
3548            mSeekMode = seekMode;
3549
3550            // There's no reason to trigger the code below, there's
3551            // nothing to flush yet.
3552            seeking = false;
3553            mPaused = false;
3554        }
3555
3556        drainInputBuffers();
3557
3558        if (mState == EXECUTING) {
3559            // Otherwise mState == RECONFIGURING and this code will trigger
3560            // after the output port is reenabled.
3561            fillOutputBuffers();
3562        }
3563    }
3564
3565    if (seeking) {
3566        while (mState == RECONFIGURING) {
3567            mBufferFilled.wait(mLock);
3568        }
3569
3570        if (mState != EXECUTING) {
3571            return UNKNOWN_ERROR;
3572        }
3573
3574        CODEC_LOGV("seeking to %lld us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6);
3575
3576        mSignalledEOS = false;
3577
3578        CHECK(seekTimeUs >= 0);
3579        mSeekTimeUs = seekTimeUs;
3580        mSeekMode = seekMode;
3581
3582        mFilledBuffers.clear();
3583
3584        CHECK_EQ((int)mState, (int)EXECUTING);
3585
3586        bool emulateInputFlushCompletion = !flushPortAsync(kPortIndexInput);
3587        bool emulateOutputFlushCompletion = !flushPortAsync(kPortIndexOutput);
3588
3589        if (emulateInputFlushCompletion) {
3590            onCmdComplete(OMX_CommandFlush, kPortIndexInput);
3591        }
3592
3593        if (emulateOutputFlushCompletion) {
3594            onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
3595        }
3596
3597        while (mSeekTimeUs >= 0) {
3598            mBufferFilled.wait(mLock);
3599        }
3600    }
3601
3602    while (mState != ERROR && !mNoMoreOutputData && mFilledBuffers.empty()) {
3603        if (mIsEncoder) {
3604            if (NO_ERROR != mBufferFilled.waitRelative(mLock, 3000000000LL)) {
3605                LOGW("Timed out waiting for buffers from video encoder: %d/%d",
3606                    countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
3607                    countBuffersWeOwn(mPortBuffers[kPortIndexOutput]));
3608            }
3609        } else {
3610            mBufferFilled.wait(mLock);
3611        }
3612    }
3613
3614    if (mState == ERROR) {
3615        return UNKNOWN_ERROR;
3616    }
3617
3618    if (mFilledBuffers.empty()) {
3619        return mSignalledEOS ? mFinalStatus : ERROR_END_OF_STREAM;
3620    }
3621
3622    if (mOutputPortSettingsHaveChanged) {
3623        mOutputPortSettingsHaveChanged = false;
3624
3625        return INFO_FORMAT_CHANGED;
3626    }
3627
3628    size_t index = *mFilledBuffers.begin();
3629    mFilledBuffers.erase(mFilledBuffers.begin());
3630
3631    BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index);
3632    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
3633    info->mStatus = OWNED_BY_CLIENT;
3634
3635    info->mMediaBuffer->add_ref();
3636    *buffer = info->mMediaBuffer;
3637
3638    return OK;
3639}
3640
3641void OMXCodec::signalBufferReturned(MediaBuffer *buffer) {
3642    Mutex::Autolock autoLock(mLock);
3643
3644    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
3645    for (size_t i = 0; i < buffers->size(); ++i) {
3646        BufferInfo *info = &buffers->editItemAt(i);
3647
3648        if (info->mMediaBuffer == buffer) {
3649            CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED);
3650            CHECK_EQ((int)info->mStatus, (int)OWNED_BY_CLIENT);
3651
3652            info->mStatus = OWNED_BY_US;
3653
3654            if (buffer->graphicBuffer() == 0) {
3655                fillOutputBuffer(info);
3656            } else {
3657                sp<MetaData> metaData = info->mMediaBuffer->meta_data();
3658                int32_t rendered = 0;
3659                if (!metaData->findInt32(kKeyRendered, &rendered)) {
3660                    rendered = 0;
3661                }
3662                if (!rendered) {
3663                    status_t err = cancelBufferToNativeWindow(info);
3664                    if (err < 0) {
3665                        return;
3666                    }
3667                }
3668
3669                info->mStatus = OWNED_BY_NATIVE_WINDOW;
3670
3671                // Dequeue the next buffer from the native window.
3672                BufferInfo *nextBufInfo = dequeueBufferFromNativeWindow();
3673                if (nextBufInfo == 0) {
3674                    return;
3675                }
3676
3677                // Give the buffer to the OMX node to fill.
3678                fillOutputBuffer(nextBufInfo);
3679            }
3680            return;
3681        }
3682    }
3683
3684    CHECK(!"should not be here.");
3685}
3686
3687static const char *imageCompressionFormatString(OMX_IMAGE_CODINGTYPE type) {
3688    static const char *kNames[] = {
3689        "OMX_IMAGE_CodingUnused",
3690        "OMX_IMAGE_CodingAutoDetect",
3691        "OMX_IMAGE_CodingJPEG",
3692        "OMX_IMAGE_CodingJPEG2K",
3693        "OMX_IMAGE_CodingEXIF",
3694        "OMX_IMAGE_CodingTIFF",
3695        "OMX_IMAGE_CodingGIF",
3696        "OMX_IMAGE_CodingPNG",
3697        "OMX_IMAGE_CodingLZW",
3698        "OMX_IMAGE_CodingBMP",
3699    };
3700
3701    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3702
3703    if (type < 0 || (size_t)type >= numNames) {
3704        return "UNKNOWN";
3705    } else {
3706        return kNames[type];
3707    }
3708}
3709
3710static const char *colorFormatString(OMX_COLOR_FORMATTYPE type) {
3711    static const char *kNames[] = {
3712        "OMX_COLOR_FormatUnused",
3713        "OMX_COLOR_FormatMonochrome",
3714        "OMX_COLOR_Format8bitRGB332",
3715        "OMX_COLOR_Format12bitRGB444",
3716        "OMX_COLOR_Format16bitARGB4444",
3717        "OMX_COLOR_Format16bitARGB1555",
3718        "OMX_COLOR_Format16bitRGB565",
3719        "OMX_COLOR_Format16bitBGR565",
3720        "OMX_COLOR_Format18bitRGB666",
3721        "OMX_COLOR_Format18bitARGB1665",
3722        "OMX_COLOR_Format19bitARGB1666",
3723        "OMX_COLOR_Format24bitRGB888",
3724        "OMX_COLOR_Format24bitBGR888",
3725        "OMX_COLOR_Format24bitARGB1887",
3726        "OMX_COLOR_Format25bitARGB1888",
3727        "OMX_COLOR_Format32bitBGRA8888",
3728        "OMX_COLOR_Format32bitARGB8888",
3729        "OMX_COLOR_FormatYUV411Planar",
3730        "OMX_COLOR_FormatYUV411PackedPlanar",
3731        "OMX_COLOR_FormatYUV420Planar",
3732        "OMX_COLOR_FormatYUV420PackedPlanar",
3733        "OMX_COLOR_FormatYUV420SemiPlanar",
3734        "OMX_COLOR_FormatYUV422Planar",
3735        "OMX_COLOR_FormatYUV422PackedPlanar",
3736        "OMX_COLOR_FormatYUV422SemiPlanar",
3737        "OMX_COLOR_FormatYCbYCr",
3738        "OMX_COLOR_FormatYCrYCb",
3739        "OMX_COLOR_FormatCbYCrY",
3740        "OMX_COLOR_FormatCrYCbY",
3741        "OMX_COLOR_FormatYUV444Interleaved",
3742        "OMX_COLOR_FormatRawBayer8bit",
3743        "OMX_COLOR_FormatRawBayer10bit",
3744        "OMX_COLOR_FormatRawBayer8bitcompressed",
3745        "OMX_COLOR_FormatL2",
3746        "OMX_COLOR_FormatL4",
3747        "OMX_COLOR_FormatL8",
3748        "OMX_COLOR_FormatL16",
3749        "OMX_COLOR_FormatL24",
3750        "OMX_COLOR_FormatL32",
3751        "OMX_COLOR_FormatYUV420PackedSemiPlanar",
3752        "OMX_COLOR_FormatYUV422PackedSemiPlanar",
3753        "OMX_COLOR_Format18BitBGR666",
3754        "OMX_COLOR_Format24BitARGB6666",
3755        "OMX_COLOR_Format24BitABGR6666",
3756    };
3757
3758    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3759
3760    if (type == OMX_QCOM_COLOR_FormatYVU420SemiPlanar) {
3761        return "OMX_QCOM_COLOR_FormatYVU420SemiPlanar";
3762    } else if (type < 0 || (size_t)type >= numNames) {
3763        return "UNKNOWN";
3764    } else {
3765        return kNames[type];
3766    }
3767}
3768
3769static const char *videoCompressionFormatString(OMX_VIDEO_CODINGTYPE type) {
3770    static const char *kNames[] = {
3771        "OMX_VIDEO_CodingUnused",
3772        "OMX_VIDEO_CodingAutoDetect",
3773        "OMX_VIDEO_CodingMPEG2",
3774        "OMX_VIDEO_CodingH263",
3775        "OMX_VIDEO_CodingMPEG4",
3776        "OMX_VIDEO_CodingWMV",
3777        "OMX_VIDEO_CodingRV",
3778        "OMX_VIDEO_CodingAVC",
3779        "OMX_VIDEO_CodingMJPEG",
3780    };
3781
3782    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3783
3784    if (type < 0 || (size_t)type >= numNames) {
3785        return "UNKNOWN";
3786    } else {
3787        return kNames[type];
3788    }
3789}
3790
3791static const char *audioCodingTypeString(OMX_AUDIO_CODINGTYPE type) {
3792    static const char *kNames[] = {
3793        "OMX_AUDIO_CodingUnused",
3794        "OMX_AUDIO_CodingAutoDetect",
3795        "OMX_AUDIO_CodingPCM",
3796        "OMX_AUDIO_CodingADPCM",
3797        "OMX_AUDIO_CodingAMR",
3798        "OMX_AUDIO_CodingGSMFR",
3799        "OMX_AUDIO_CodingGSMEFR",
3800        "OMX_AUDIO_CodingGSMHR",
3801        "OMX_AUDIO_CodingPDCFR",
3802        "OMX_AUDIO_CodingPDCEFR",
3803        "OMX_AUDIO_CodingPDCHR",
3804        "OMX_AUDIO_CodingTDMAFR",
3805        "OMX_AUDIO_CodingTDMAEFR",
3806        "OMX_AUDIO_CodingQCELP8",
3807        "OMX_AUDIO_CodingQCELP13",
3808        "OMX_AUDIO_CodingEVRC",
3809        "OMX_AUDIO_CodingSMV",
3810        "OMX_AUDIO_CodingG711",
3811        "OMX_AUDIO_CodingG723",
3812        "OMX_AUDIO_CodingG726",
3813        "OMX_AUDIO_CodingG729",
3814        "OMX_AUDIO_CodingAAC",
3815        "OMX_AUDIO_CodingMP3",
3816        "OMX_AUDIO_CodingSBC",
3817        "OMX_AUDIO_CodingVORBIS",
3818        "OMX_AUDIO_CodingWMA",
3819        "OMX_AUDIO_CodingRA",
3820        "OMX_AUDIO_CodingMIDI",
3821    };
3822
3823    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3824
3825    if (type < 0 || (size_t)type >= numNames) {
3826        return "UNKNOWN";
3827    } else {
3828        return kNames[type];
3829    }
3830}
3831
3832static const char *audioPCMModeString(OMX_AUDIO_PCMMODETYPE type) {
3833    static const char *kNames[] = {
3834        "OMX_AUDIO_PCMModeLinear",
3835        "OMX_AUDIO_PCMModeALaw",
3836        "OMX_AUDIO_PCMModeMULaw",
3837    };
3838
3839    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3840
3841    if (type < 0 || (size_t)type >= numNames) {
3842        return "UNKNOWN";
3843    } else {
3844        return kNames[type];
3845    }
3846}
3847
3848static const char *amrBandModeString(OMX_AUDIO_AMRBANDMODETYPE type) {
3849    static const char *kNames[] = {
3850        "OMX_AUDIO_AMRBandModeUnused",
3851        "OMX_AUDIO_AMRBandModeNB0",
3852        "OMX_AUDIO_AMRBandModeNB1",
3853        "OMX_AUDIO_AMRBandModeNB2",
3854        "OMX_AUDIO_AMRBandModeNB3",
3855        "OMX_AUDIO_AMRBandModeNB4",
3856        "OMX_AUDIO_AMRBandModeNB5",
3857        "OMX_AUDIO_AMRBandModeNB6",
3858        "OMX_AUDIO_AMRBandModeNB7",
3859        "OMX_AUDIO_AMRBandModeWB0",
3860        "OMX_AUDIO_AMRBandModeWB1",
3861        "OMX_AUDIO_AMRBandModeWB2",
3862        "OMX_AUDIO_AMRBandModeWB3",
3863        "OMX_AUDIO_AMRBandModeWB4",
3864        "OMX_AUDIO_AMRBandModeWB5",
3865        "OMX_AUDIO_AMRBandModeWB6",
3866        "OMX_AUDIO_AMRBandModeWB7",
3867        "OMX_AUDIO_AMRBandModeWB8",
3868    };
3869
3870    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3871
3872    if (type < 0 || (size_t)type >= numNames) {
3873        return "UNKNOWN";
3874    } else {
3875        return kNames[type];
3876    }
3877}
3878
3879static const char *amrFrameFormatString(OMX_AUDIO_AMRFRAMEFORMATTYPE type) {
3880    static const char *kNames[] = {
3881        "OMX_AUDIO_AMRFrameFormatConformance",
3882        "OMX_AUDIO_AMRFrameFormatIF1",
3883        "OMX_AUDIO_AMRFrameFormatIF2",
3884        "OMX_AUDIO_AMRFrameFormatFSF",
3885        "OMX_AUDIO_AMRFrameFormatRTPPayload",
3886        "OMX_AUDIO_AMRFrameFormatITU",
3887    };
3888
3889    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3890
3891    if (type < 0 || (size_t)type >= numNames) {
3892        return "UNKNOWN";
3893    } else {
3894        return kNames[type];
3895    }
3896}
3897
3898void OMXCodec::dumpPortStatus(OMX_U32 portIndex) {
3899    OMX_PARAM_PORTDEFINITIONTYPE def;
3900    InitOMXParams(&def);
3901    def.nPortIndex = portIndex;
3902
3903    status_t err = mOMX->getParameter(
3904            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3905    CHECK_EQ(err, (status_t)OK);
3906
3907    printf("%s Port = {\n", portIndex == kPortIndexInput ? "Input" : "Output");
3908
3909    CHECK((portIndex == kPortIndexInput && def.eDir == OMX_DirInput)
3910          || (portIndex == kPortIndexOutput && def.eDir == OMX_DirOutput));
3911
3912    printf("  nBufferCountActual = %ld\n", def.nBufferCountActual);
3913    printf("  nBufferCountMin = %ld\n", def.nBufferCountMin);
3914    printf("  nBufferSize = %ld\n", def.nBufferSize);
3915
3916    switch (def.eDomain) {
3917        case OMX_PortDomainImage:
3918        {
3919            const OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3920
3921            printf("\n");
3922            printf("  // Image\n");
3923            printf("  nFrameWidth = %ld\n", imageDef->nFrameWidth);
3924            printf("  nFrameHeight = %ld\n", imageDef->nFrameHeight);
3925            printf("  nStride = %ld\n", imageDef->nStride);
3926
3927            printf("  eCompressionFormat = %s\n",
3928                   imageCompressionFormatString(imageDef->eCompressionFormat));
3929
3930            printf("  eColorFormat = %s\n",
3931                   colorFormatString(imageDef->eColorFormat));
3932
3933            break;
3934        }
3935
3936        case OMX_PortDomainVideo:
3937        {
3938            OMX_VIDEO_PORTDEFINITIONTYPE *videoDef = &def.format.video;
3939
3940            printf("\n");
3941            printf("  // Video\n");
3942            printf("  nFrameWidth = %ld\n", videoDef->nFrameWidth);
3943            printf("  nFrameHeight = %ld\n", videoDef->nFrameHeight);
3944            printf("  nStride = %ld\n", videoDef->nStride);
3945
3946            printf("  eCompressionFormat = %s\n",
3947                   videoCompressionFormatString(videoDef->eCompressionFormat));
3948
3949            printf("  eColorFormat = %s\n",
3950                   colorFormatString(videoDef->eColorFormat));
3951
3952            break;
3953        }
3954
3955        case OMX_PortDomainAudio:
3956        {
3957            OMX_AUDIO_PORTDEFINITIONTYPE *audioDef = &def.format.audio;
3958
3959            printf("\n");
3960            printf("  // Audio\n");
3961            printf("  eEncoding = %s\n",
3962                   audioCodingTypeString(audioDef->eEncoding));
3963
3964            if (audioDef->eEncoding == OMX_AUDIO_CodingPCM) {
3965                OMX_AUDIO_PARAM_PCMMODETYPE params;
3966                InitOMXParams(&params);
3967                params.nPortIndex = portIndex;
3968
3969                err = mOMX->getParameter(
3970                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
3971                CHECK_EQ(err, (status_t)OK);
3972
3973                printf("  nSamplingRate = %ld\n", params.nSamplingRate);
3974                printf("  nChannels = %ld\n", params.nChannels);
3975                printf("  bInterleaved = %d\n", params.bInterleaved);
3976                printf("  nBitPerSample = %ld\n", params.nBitPerSample);
3977
3978                printf("  eNumData = %s\n",
3979                       params.eNumData == OMX_NumericalDataSigned
3980                        ? "signed" : "unsigned");
3981
3982                printf("  ePCMMode = %s\n", audioPCMModeString(params.ePCMMode));
3983            } else if (audioDef->eEncoding == OMX_AUDIO_CodingAMR) {
3984                OMX_AUDIO_PARAM_AMRTYPE amr;
3985                InitOMXParams(&amr);
3986                amr.nPortIndex = portIndex;
3987
3988                err = mOMX->getParameter(
3989                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
3990                CHECK_EQ(err, (status_t)OK);
3991
3992                printf("  nChannels = %ld\n", amr.nChannels);
3993                printf("  eAMRBandMode = %s\n",
3994                        amrBandModeString(amr.eAMRBandMode));
3995                printf("  eAMRFrameFormat = %s\n",
3996                        amrFrameFormatString(amr.eAMRFrameFormat));
3997            }
3998
3999            break;
4000        }
4001
4002        default:
4003        {
4004            printf("  // Unknown\n");
4005            break;
4006        }
4007    }
4008
4009    printf("}\n");
4010}
4011
4012status_t OMXCodec::initNativeWindow() {
4013    // Enable use of a GraphicBuffer as the output for this node.  This must
4014    // happen before getting the IndexParamPortDefinition parameter because it
4015    // will affect the pixel format that the node reports.
4016    status_t err = mOMX->enableGraphicBuffers(mNode, kPortIndexOutput, OMX_TRUE);
4017    if (err != 0) {
4018        return err;
4019    }
4020
4021    return OK;
4022}
4023
4024void OMXCodec::initOutputFormat(const sp<MetaData> &inputFormat) {
4025    mOutputFormat = new MetaData;
4026    mOutputFormat->setCString(kKeyDecoderComponent, mComponentName);
4027    if (mIsEncoder) {
4028        int32_t timeScale;
4029        if (inputFormat->findInt32(kKeyTimeScale, &timeScale)) {
4030            mOutputFormat->setInt32(kKeyTimeScale, timeScale);
4031        }
4032    }
4033
4034    OMX_PARAM_PORTDEFINITIONTYPE def;
4035    InitOMXParams(&def);
4036    def.nPortIndex = kPortIndexOutput;
4037
4038    status_t err = mOMX->getParameter(
4039            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
4040    CHECK_EQ(err, (status_t)OK);
4041
4042    switch (def.eDomain) {
4043        case OMX_PortDomainImage:
4044        {
4045            OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
4046            CHECK_EQ((int)imageDef->eCompressionFormat,
4047                     (int)OMX_IMAGE_CodingUnused);
4048
4049            mOutputFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
4050            mOutputFormat->setInt32(kKeyColorFormat, imageDef->eColorFormat);
4051            mOutputFormat->setInt32(kKeyWidth, imageDef->nFrameWidth);
4052            mOutputFormat->setInt32(kKeyHeight, imageDef->nFrameHeight);
4053            break;
4054        }
4055
4056        case OMX_PortDomainAudio:
4057        {
4058            OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio;
4059
4060            if (audio_def->eEncoding == OMX_AUDIO_CodingPCM) {
4061                OMX_AUDIO_PARAM_PCMMODETYPE params;
4062                InitOMXParams(&params);
4063                params.nPortIndex = kPortIndexOutput;
4064
4065                err = mOMX->getParameter(
4066                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
4067                CHECK_EQ(err, (status_t)OK);
4068
4069                CHECK_EQ((int)params.eNumData, (int)OMX_NumericalDataSigned);
4070                CHECK_EQ(params.nBitPerSample, 16u);
4071                CHECK_EQ((int)params.ePCMMode, (int)OMX_AUDIO_PCMModeLinear);
4072
4073                int32_t numChannels, sampleRate;
4074                inputFormat->findInt32(kKeyChannelCount, &numChannels);
4075                inputFormat->findInt32(kKeySampleRate, &sampleRate);
4076
4077                if ((OMX_U32)numChannels != params.nChannels) {
4078                    LOGW("Codec outputs a different number of channels than "
4079                         "the input stream contains (contains %d channels, "
4080                         "codec outputs %ld channels).",
4081                         numChannels, params.nChannels);
4082                }
4083
4084                if (sampleRate != (int32_t)params.nSamplingRate) {
4085                    LOGW("Codec outputs at different sampling rate than "
4086                         "what the input stream contains (contains data at "
4087                         "%d Hz, codec outputs %lu Hz)",
4088                         sampleRate, params.nSamplingRate);
4089                }
4090
4091                mOutputFormat->setCString(
4092                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
4093
4094                // Use the codec-advertised number of channels, as some
4095                // codecs appear to output stereo even if the input data is
4096                // mono. If we know the codec lies about this information,
4097                // use the actual number of channels instead.
4098                mOutputFormat->setInt32(
4099                        kKeyChannelCount,
4100                        (mQuirks & kDecoderLiesAboutNumberOfChannels)
4101                            ? numChannels : params.nChannels);
4102
4103                mOutputFormat->setInt32(kKeySampleRate, params.nSamplingRate);
4104            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAMR) {
4105                OMX_AUDIO_PARAM_AMRTYPE amr;
4106                InitOMXParams(&amr);
4107                amr.nPortIndex = kPortIndexOutput;
4108
4109                err = mOMX->getParameter(
4110                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
4111                CHECK_EQ(err, (status_t)OK);
4112
4113                CHECK_EQ(amr.nChannels, 1u);
4114                mOutputFormat->setInt32(kKeyChannelCount, 1);
4115
4116                if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeNB0
4117                    && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeNB7) {
4118                    mOutputFormat->setCString(
4119                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB);
4120                    mOutputFormat->setInt32(kKeySampleRate, 8000);
4121                } else if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeWB0
4122                            && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeWB8) {
4123                    mOutputFormat->setCString(
4124                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB);
4125                    mOutputFormat->setInt32(kKeySampleRate, 16000);
4126                } else {
4127                    CHECK(!"Unknown AMR band mode.");
4128                }
4129            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAAC) {
4130                mOutputFormat->setCString(
4131                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
4132                int32_t numChannels, sampleRate, bitRate;
4133                inputFormat->findInt32(kKeyChannelCount, &numChannels);
4134                inputFormat->findInt32(kKeySampleRate, &sampleRate);
4135                inputFormat->findInt32(kKeyBitRate, &bitRate);
4136                mOutputFormat->setInt32(kKeyChannelCount, numChannels);
4137                mOutputFormat->setInt32(kKeySampleRate, sampleRate);
4138                mOutputFormat->setInt32(kKeyBitRate, bitRate);
4139            } else {
4140                CHECK(!"Should not be here. Unknown audio encoding.");
4141            }
4142            break;
4143        }
4144
4145        case OMX_PortDomainVideo:
4146        {
4147            OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
4148
4149            if (video_def->eCompressionFormat == OMX_VIDEO_CodingUnused) {
4150                mOutputFormat->setCString(
4151                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
4152            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingMPEG4) {
4153                mOutputFormat->setCString(
4154                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
4155            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingH263) {
4156                mOutputFormat->setCString(
4157                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
4158            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingAVC) {
4159                mOutputFormat->setCString(
4160                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
4161            } else {
4162                CHECK(!"Unknown compression format.");
4163            }
4164
4165            mOutputFormat->setInt32(kKeyWidth, video_def->nFrameWidth);
4166            mOutputFormat->setInt32(kKeyHeight, video_def->nFrameHeight);
4167            mOutputFormat->setInt32(kKeyColorFormat, video_def->eColorFormat);
4168
4169            if (!mIsEncoder) {
4170                OMX_CONFIG_RECTTYPE rect;
4171                InitOMXParams(&rect);
4172                rect.nPortIndex = kPortIndexOutput;
4173                status_t err =
4174                        mOMX->getConfig(
4175                            mNode, OMX_IndexConfigCommonOutputCrop,
4176                            &rect, sizeof(rect));
4177
4178                if (err == OK) {
4179                    CHECK_GE(rect.nLeft, 0);
4180                    CHECK_GE(rect.nTop, 0);
4181                    CHECK_GE(rect.nWidth, 0u);
4182                    CHECK_GE(rect.nHeight, 0u);
4183                    CHECK_LE(rect.nLeft + rect.nWidth - 1, video_def->nFrameWidth);
4184                    CHECK_LE(rect.nTop + rect.nHeight - 1, video_def->nFrameHeight);
4185
4186                    mOutputFormat->setRect(
4187                            kKeyCropRect,
4188                            rect.nLeft,
4189                            rect.nTop,
4190                            rect.nLeft + rect.nWidth - 1,
4191                            rect.nTop + rect.nHeight - 1);
4192                } else {
4193                    mOutputFormat->setRect(
4194                            kKeyCropRect,
4195                            0, 0,
4196                            video_def->nFrameWidth - 1,
4197                            video_def->nFrameHeight - 1);
4198                }
4199            }
4200
4201            break;
4202        }
4203
4204        default:
4205        {
4206            CHECK(!"should not be here, neither audio nor video.");
4207            break;
4208        }
4209    }
4210
4211    // If the input format contains rotation information, flag the output
4212    // format accordingly.
4213
4214    int32_t rotationDegrees;
4215    if (mSource->getFormat()->findInt32(kKeyRotation, &rotationDegrees)) {
4216        mOutputFormat->setInt32(kKeyRotation, rotationDegrees);
4217    }
4218}
4219
4220status_t OMXCodec::pause() {
4221    Mutex::Autolock autoLock(mLock);
4222
4223    mPaused = true;
4224
4225    return OK;
4226}
4227
4228////////////////////////////////////////////////////////////////////////////////
4229
4230status_t QueryCodecs(
4231        const sp<IOMX> &omx,
4232        const char *mime, bool queryDecoders,
4233        Vector<CodecCapabilities> *results) {
4234    results->clear();
4235
4236    for (int index = 0;; ++index) {
4237        const char *componentName;
4238
4239        if (!queryDecoders) {
4240            componentName = GetCodec(
4241                    kEncoderInfo, sizeof(kEncoderInfo) / sizeof(kEncoderInfo[0]),
4242                    mime, index);
4243        } else {
4244            componentName = GetCodec(
4245                    kDecoderInfo, sizeof(kDecoderInfo) / sizeof(kDecoderInfo[0]),
4246                    mime, index);
4247        }
4248
4249        if (!componentName) {
4250            return OK;
4251        }
4252
4253        if (strncmp(componentName, "OMX.", 4)) {
4254            // Not an OpenMax component but a software codec.
4255
4256#if HAVE_SOFTWARE_DECODERS
4257            results->push();
4258            CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
4259            caps->mComponentName = componentName;
4260#endif
4261
4262            continue;
4263        }
4264
4265        sp<OMXCodecObserver> observer = new OMXCodecObserver;
4266        IOMX::node_id node;
4267        status_t err = omx->allocateNode(componentName, observer, &node);
4268
4269        if (err != OK) {
4270            continue;
4271        }
4272
4273        OMXCodec::setComponentRole(omx, node, !queryDecoders, mime);
4274
4275        results->push();
4276        CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
4277        caps->mComponentName = componentName;
4278
4279        OMX_VIDEO_PARAM_PROFILELEVELTYPE param;
4280        InitOMXParams(&param);
4281
4282        param.nPortIndex = queryDecoders ? 0 : 1;
4283
4284        for (param.nProfileIndex = 0;; ++param.nProfileIndex) {
4285            err = omx->getParameter(
4286                    node, OMX_IndexParamVideoProfileLevelQuerySupported,
4287                    &param, sizeof(param));
4288
4289            if (err != OK) {
4290                break;
4291            }
4292
4293            CodecProfileLevel profileLevel;
4294            profileLevel.mProfile = param.eProfile;
4295            profileLevel.mLevel = param.eLevel;
4296
4297            caps->mProfileLevels.push(profileLevel);
4298        }
4299
4300        // Color format query
4301        OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat;
4302        InitOMXParams(&portFormat);
4303        portFormat.nPortIndex = queryDecoders ? 1 : 0;
4304        for (portFormat.nIndex = 0;; ++portFormat.nIndex)  {
4305            err = omx->getParameter(
4306                    node, OMX_IndexParamVideoPortFormat,
4307                    &portFormat, sizeof(portFormat));
4308            if (err != OK) {
4309                break;
4310            }
4311            caps->mColorFormats.push(portFormat.eColorFormat);
4312        }
4313
4314        CHECK_EQ(omx->freeNode(node), (status_t)OK);
4315    }
4316}
4317
4318void OMXCodec::restorePatchedDataPointer(BufferInfo *info) {
4319    CHECK(mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames));
4320    CHECK(mOMXLivesLocally);
4321
4322    OMX_BUFFERHEADERTYPE *header = (OMX_BUFFERHEADERTYPE *)info->mBuffer;
4323    header->pBuffer = (OMX_U8 *)info->mData;
4324}
4325
4326}  // namespace android
4327