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