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