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