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