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