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