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