OMXCodec.cpp revision 59e7879a8482284a434268d51b4b438f0625d1be
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      mOutputPortSettingsChangedPending(false),
1438      mLeftOverBuffer(NULL),
1439      mPaused(false),
1440      mNativeWindow(nativeWindow) {
1441    mPortStatus[kPortIndexInput] = ENABLED;
1442    mPortStatus[kPortIndexOutput] = ENABLED;
1443
1444    setComponentRole();
1445}
1446
1447// static
1448void OMXCodec::setComponentRole(
1449        const sp<IOMX> &omx, IOMX::node_id node, bool isEncoder,
1450        const char *mime) {
1451    struct MimeToRole {
1452        const char *mime;
1453        const char *decoderRole;
1454        const char *encoderRole;
1455    };
1456
1457    static const MimeToRole kMimeToRole[] = {
1458        { MEDIA_MIMETYPE_AUDIO_MPEG,
1459            "audio_decoder.mp3", "audio_encoder.mp3" },
1460        { MEDIA_MIMETYPE_AUDIO_AMR_NB,
1461            "audio_decoder.amrnb", "audio_encoder.amrnb" },
1462        { MEDIA_MIMETYPE_AUDIO_AMR_WB,
1463            "audio_decoder.amrwb", "audio_encoder.amrwb" },
1464        { MEDIA_MIMETYPE_AUDIO_AAC,
1465            "audio_decoder.aac", "audio_encoder.aac" },
1466        { MEDIA_MIMETYPE_VIDEO_AVC,
1467            "video_decoder.avc", "video_encoder.avc" },
1468        { MEDIA_MIMETYPE_VIDEO_MPEG4,
1469            "video_decoder.mpeg4", "video_encoder.mpeg4" },
1470        { MEDIA_MIMETYPE_VIDEO_H263,
1471            "video_decoder.h263", "video_encoder.h263" },
1472    };
1473
1474    static const size_t kNumMimeToRole =
1475        sizeof(kMimeToRole) / sizeof(kMimeToRole[0]);
1476
1477    size_t i;
1478    for (i = 0; i < kNumMimeToRole; ++i) {
1479        if (!strcasecmp(mime, kMimeToRole[i].mime)) {
1480            break;
1481        }
1482    }
1483
1484    if (i == kNumMimeToRole) {
1485        return;
1486    }
1487
1488    const char *role =
1489        isEncoder ? kMimeToRole[i].encoderRole
1490                  : kMimeToRole[i].decoderRole;
1491
1492    if (role != NULL) {
1493        OMX_PARAM_COMPONENTROLETYPE roleParams;
1494        InitOMXParams(&roleParams);
1495
1496        strncpy((char *)roleParams.cRole,
1497                role, OMX_MAX_STRINGNAME_SIZE - 1);
1498
1499        roleParams.cRole[OMX_MAX_STRINGNAME_SIZE - 1] = '\0';
1500
1501        status_t err = omx->setParameter(
1502                node, OMX_IndexParamStandardComponentRole,
1503                &roleParams, sizeof(roleParams));
1504
1505        if (err != OK) {
1506            LOGW("Failed to set standard component role '%s'.", role);
1507        }
1508    }
1509}
1510
1511void OMXCodec::setComponentRole() {
1512    setComponentRole(mOMX, mNode, mIsEncoder, mMIME);
1513}
1514
1515OMXCodec::~OMXCodec() {
1516    mSource.clear();
1517
1518    CHECK(mState == LOADED || mState == ERROR || mState == LOADED_TO_IDLE);
1519
1520    status_t err = mOMX->freeNode(mNode);
1521    CHECK_EQ(err, (status_t)OK);
1522
1523    mNode = NULL;
1524    setState(DEAD);
1525
1526    clearCodecSpecificData();
1527
1528    free(mComponentName);
1529    mComponentName = NULL;
1530
1531    free(mMIME);
1532    mMIME = NULL;
1533}
1534
1535status_t OMXCodec::init() {
1536    // mLock is held.
1537
1538    CHECK_EQ((int)mState, (int)LOADED);
1539
1540    status_t err;
1541    if (!(mQuirks & kRequiresLoadedToIdleAfterAllocation)) {
1542        err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
1543        CHECK_EQ(err, (status_t)OK);
1544        setState(LOADED_TO_IDLE);
1545    }
1546
1547    err = allocateBuffers();
1548    if (err != (status_t)OK) {
1549        return err;
1550    }
1551
1552    if (mQuirks & kRequiresLoadedToIdleAfterAllocation) {
1553        err = mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
1554        CHECK_EQ(err, (status_t)OK);
1555
1556        setState(LOADED_TO_IDLE);
1557    }
1558
1559    while (mState != EXECUTING && mState != ERROR) {
1560        mAsyncCompletion.wait(mLock);
1561    }
1562
1563    return mState == ERROR ? UNKNOWN_ERROR : OK;
1564}
1565
1566// static
1567bool OMXCodec::isIntermediateState(State state) {
1568    return state == LOADED_TO_IDLE
1569        || state == IDLE_TO_EXECUTING
1570        || state == EXECUTING_TO_IDLE
1571        || state == IDLE_TO_LOADED
1572        || state == RECONFIGURING;
1573}
1574
1575status_t OMXCodec::allocateBuffers() {
1576    status_t err = allocateBuffersOnPort(kPortIndexInput);
1577
1578    if (err != OK) {
1579        return err;
1580    }
1581
1582    return allocateBuffersOnPort(kPortIndexOutput);
1583}
1584
1585status_t OMXCodec::allocateBuffersOnPort(OMX_U32 portIndex) {
1586    if (mNativeWindow != NULL && portIndex == kPortIndexOutput) {
1587        return allocateOutputBuffersFromNativeWindow();
1588    }
1589
1590    OMX_PARAM_PORTDEFINITIONTYPE def;
1591    InitOMXParams(&def);
1592    def.nPortIndex = portIndex;
1593
1594    status_t err = mOMX->getParameter(
1595            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1596
1597    if (err != OK) {
1598        return err;
1599    }
1600
1601    if (mIsMetaDataStoredInVideoBuffers && portIndex == kPortIndexInput) {
1602        err = mOMX->storeMetaDataInBuffers(mNode, kPortIndexInput, OMX_TRUE);
1603        if (err != OK) {
1604            LOGE("Storing meta data in video buffers is not supported");
1605            return err;
1606        }
1607    }
1608
1609    CODEC_LOGI("allocating %lu buffers of size %lu on %s port",
1610            def.nBufferCountActual, def.nBufferSize,
1611            portIndex == kPortIndexInput ? "input" : "output");
1612
1613    size_t totalSize = def.nBufferCountActual * def.nBufferSize;
1614    mDealer[portIndex] = new MemoryDealer(totalSize, "OMXCodec");
1615
1616    for (OMX_U32 i = 0; i < def.nBufferCountActual; ++i) {
1617        sp<IMemory> mem = mDealer[portIndex]->allocate(def.nBufferSize);
1618        CHECK(mem.get() != NULL);
1619
1620        BufferInfo info;
1621        info.mData = NULL;
1622        info.mSize = def.nBufferSize;
1623
1624        IOMX::buffer_id buffer;
1625        if (portIndex == kPortIndexInput
1626                && (mQuirks & kRequiresAllocateBufferOnInputPorts)) {
1627            if (mOMXLivesLocally) {
1628                mem.clear();
1629
1630                err = mOMX->allocateBuffer(
1631                        mNode, portIndex, def.nBufferSize, &buffer,
1632                        &info.mData);
1633            } else {
1634                err = mOMX->allocateBufferWithBackup(
1635                        mNode, portIndex, mem, &buffer);
1636            }
1637        } else if (portIndex == kPortIndexOutput
1638                && (mQuirks & kRequiresAllocateBufferOnOutputPorts)) {
1639            if (mOMXLivesLocally) {
1640                mem.clear();
1641
1642                err = mOMX->allocateBuffer(
1643                        mNode, portIndex, def.nBufferSize, &buffer,
1644                        &info.mData);
1645            } else {
1646                err = mOMX->allocateBufferWithBackup(
1647                        mNode, portIndex, mem, &buffer);
1648            }
1649        } else {
1650            err = mOMX->useBuffer(mNode, portIndex, mem, &buffer);
1651        }
1652
1653        if (err != OK) {
1654            LOGE("allocate_buffer_with_backup failed");
1655            return err;
1656        }
1657
1658        if (mem != NULL) {
1659            info.mData = mem->pointer();
1660        }
1661
1662        info.mBuffer = buffer;
1663        info.mStatus = OWNED_BY_US;
1664        info.mMem = mem;
1665        info.mMediaBuffer = NULL;
1666
1667        if (portIndex == kPortIndexOutput) {
1668            if (!(mOMXLivesLocally
1669                        && (mQuirks & kRequiresAllocateBufferOnOutputPorts)
1670                        && (mQuirks & kDefersOutputBufferAllocation))) {
1671                // If the node does not fill in the buffer ptr at this time,
1672                // we will defer creating the MediaBuffer until receiving
1673                // the first FILL_BUFFER_DONE notification instead.
1674                info.mMediaBuffer = new MediaBuffer(info.mData, info.mSize);
1675                info.mMediaBuffer->setObserver(this);
1676            }
1677        }
1678
1679        mPortBuffers[portIndex].push(info);
1680
1681        CODEC_LOGV("allocated buffer %p on %s port", buffer,
1682             portIndex == kPortIndexInput ? "input" : "output");
1683    }
1684
1685    // dumpPortStatus(portIndex);
1686
1687    return OK;
1688}
1689
1690status_t OMXCodec::applyRotation() {
1691    sp<MetaData> meta = mSource->getFormat();
1692
1693    int32_t rotationDegrees;
1694    if (!meta->findInt32(kKeyRotation, &rotationDegrees)) {
1695        rotationDegrees = 0;
1696    }
1697
1698    uint32_t transform;
1699    switch (rotationDegrees) {
1700        case 0: transform = 0; break;
1701        case 90: transform = HAL_TRANSFORM_ROT_90; break;
1702        case 180: transform = HAL_TRANSFORM_ROT_180; break;
1703        case 270: transform = HAL_TRANSFORM_ROT_270; break;
1704        default: transform = 0; break;
1705    }
1706
1707    status_t err = OK;
1708
1709    if (transform) {
1710        err = native_window_set_buffers_transform(
1711                mNativeWindow.get(), transform);
1712    }
1713
1714    return err;
1715}
1716
1717status_t OMXCodec::allocateOutputBuffersFromNativeWindow() {
1718    // Get the number of buffers needed.
1719    OMX_PARAM_PORTDEFINITIONTYPE def;
1720    InitOMXParams(&def);
1721    def.nPortIndex = kPortIndexOutput;
1722
1723    status_t err = mOMX->getParameter(
1724            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1725    if (err != OK) {
1726        return err;
1727    }
1728
1729    err = native_window_set_buffers_geometry(
1730            mNativeWindow.get(),
1731            def.format.video.nFrameWidth,
1732            def.format.video.nFrameHeight,
1733            def.format.video.eColorFormat);
1734
1735    if (err != 0) {
1736        LOGE("native_window_set_buffers_geometry failed: %s (%d)",
1737                strerror(-err), -err);
1738        return err;
1739    }
1740
1741    // Increase the buffer count by one to allow for the ANativeWindow to hold
1742    // on to one of the buffers.
1743    def.nBufferCountActual++;
1744    err = mOMX->setParameter(
1745            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
1746    if (err != OK) {
1747        return err;
1748    }
1749
1750    err = applyRotation();
1751    if (err != OK) {
1752        return err;
1753    }
1754
1755    // Set up the native window.
1756    OMX_U32 usage = 0;
1757    err = mOMX->getGraphicBufferUsage(mNode, kPortIndexOutput, &usage);
1758    if (err != 0) {
1759        LOGW("querying usage flags from OMX IL component failed: %d", err);
1760        // XXX: Currently this error is logged, but not fatal.
1761        usage = 0;
1762    }
1763
1764    err = native_window_set_usage(
1765            mNativeWindow.get(), usage | GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_EXTERNAL_DISP);
1766    if (err != 0) {
1767        LOGE("native_window_set_usage failed: %s (%d)", strerror(-err), -err);
1768        return err;
1769    }
1770
1771    err = native_window_set_buffer_count(
1772            mNativeWindow.get(), def.nBufferCountActual);
1773    if (err != 0) {
1774        LOGE("native_window_set_buffer_count failed: %s (%d)", strerror(-err),
1775                -err);
1776        return err;
1777    }
1778
1779    CODEC_LOGI("allocating %lu buffers from a native window of size %lu on "
1780            "output port", def.nBufferCountActual, def.nBufferSize);
1781
1782    // Dequeue buffers and send them to OMX
1783    for (OMX_U32 i = 0; i < def.nBufferCountActual; i++) {
1784        android_native_buffer_t* buf;
1785        err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf);
1786        if (err != 0) {
1787            LOGE("dequeueBuffer failed: %s (%d)", strerror(-err), -err);
1788            break;
1789        }
1790
1791        sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(buf, false));
1792        BufferInfo info;
1793        info.mData = NULL;
1794        info.mSize = def.nBufferSize;
1795        info.mStatus = OWNED_BY_US;
1796        info.mMem = NULL;
1797        info.mMediaBuffer = new MediaBuffer(graphicBuffer);
1798        info.mMediaBuffer->setObserver(this);
1799        mPortBuffers[kPortIndexOutput].push(info);
1800
1801        IOMX::buffer_id bufferId;
1802        err = mOMX->useGraphicBuffer(mNode, kPortIndexOutput, graphicBuffer,
1803                &bufferId);
1804        if (err != 0) {
1805            CODEC_LOGE("registering GraphicBuffer with OMX IL component "
1806                    "failed: %d", err);
1807            break;
1808        }
1809
1810        mPortBuffers[kPortIndexOutput].editItemAt(i).mBuffer = bufferId;
1811
1812        CODEC_LOGV("registered graphic buffer with ID %p (pointer = %p)",
1813                bufferId, graphicBuffer.get());
1814    }
1815
1816    OMX_U32 cancelStart;
1817    OMX_U32 cancelEnd;
1818    if (err != 0) {
1819        // If an error occurred while dequeuing we need to cancel any buffers
1820        // that were dequeued.
1821        cancelStart = 0;
1822        cancelEnd = mPortBuffers[kPortIndexOutput].size();
1823    } else {
1824        // Return the last two buffers to the native window.
1825        // XXX TODO: The number of buffers the native window owns should probably be
1826        // queried from it when we put the native window in fixed buffer pool mode
1827        // (which needs to be implemented).  Currently it's hard-coded to 2.
1828        cancelStart = def.nBufferCountActual - 2;
1829        cancelEnd = def.nBufferCountActual;
1830    }
1831
1832    for (OMX_U32 i = cancelStart; i < cancelEnd; i++) {
1833        BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(i);
1834        cancelBufferToNativeWindow(info);
1835    }
1836
1837    return err;
1838}
1839
1840status_t OMXCodec::cancelBufferToNativeWindow(BufferInfo *info) {
1841    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
1842    CODEC_LOGV("Calling cancelBuffer on buffer %p", info->mBuffer);
1843    int err = mNativeWindow->cancelBuffer(
1844        mNativeWindow.get(), info->mMediaBuffer->graphicBuffer().get());
1845    if (err != 0) {
1846      CODEC_LOGE("cancelBuffer failed w/ error 0x%08x", err);
1847
1848      setState(ERROR);
1849      return err;
1850    }
1851    info->mStatus = OWNED_BY_NATIVE_WINDOW;
1852    return OK;
1853}
1854
1855OMXCodec::BufferInfo* OMXCodec::dequeueBufferFromNativeWindow() {
1856    // Dequeue the next buffer from the native window.
1857    android_native_buffer_t* buf;
1858    int err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf);
1859    if (err != 0) {
1860      CODEC_LOGE("dequeueBuffer failed w/ error 0x%08x", err);
1861
1862      setState(ERROR);
1863      return 0;
1864    }
1865
1866    // Determine which buffer we just dequeued.
1867    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
1868    BufferInfo *bufInfo = 0;
1869    for (size_t i = 0; i < buffers->size(); i++) {
1870      sp<GraphicBuffer> graphicBuffer = buffers->itemAt(i).
1871          mMediaBuffer->graphicBuffer();
1872      if (graphicBuffer->handle == buf->handle) {
1873        bufInfo = &buffers->editItemAt(i);
1874        break;
1875      }
1876    }
1877
1878    if (bufInfo == 0) {
1879        CODEC_LOGE("dequeued unrecognized buffer: %p", buf);
1880
1881        setState(ERROR);
1882        return 0;
1883    }
1884
1885    // The native window no longer owns the buffer.
1886    CHECK_EQ((int)bufInfo->mStatus, (int)OWNED_BY_NATIVE_WINDOW);
1887    bufInfo->mStatus = OWNED_BY_US;
1888
1889    return bufInfo;
1890}
1891
1892void OMXCodec::on_message(const omx_message &msg) {
1893    switch (msg.type) {
1894        case omx_message::EVENT:
1895        {
1896            onEvent(
1897                 msg.u.event_data.event, msg.u.event_data.data1,
1898                 msg.u.event_data.data2);
1899
1900            break;
1901        }
1902
1903        case omx_message::EMPTY_BUFFER_DONE:
1904        {
1905            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
1906
1907            CODEC_LOGV("EMPTY_BUFFER_DONE(buffer: %p)", buffer);
1908
1909            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
1910            size_t i = 0;
1911            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
1912                ++i;
1913            }
1914
1915            CHECK(i < buffers->size());
1916            if ((*buffers)[i].mStatus != OWNED_BY_COMPONENT) {
1917                LOGW("We already own input buffer %p, yet received "
1918                     "an EMPTY_BUFFER_DONE.", buffer);
1919            }
1920
1921            BufferInfo* info = &buffers->editItemAt(i);
1922            info->mStatus = OWNED_BY_US;
1923
1924            // Buffer could not be released until empty buffer done is called.
1925            if (info->mMediaBuffer != NULL) {
1926                if (mIsEncoder &&
1927                    (mQuirks & kAvoidMemcopyInputRecordingFrames)) {
1928                    // If zero-copy mode is enabled this will send the
1929                    // input buffer back to the upstream source.
1930                    restorePatchedDataPointer(info);
1931                }
1932
1933                info->mMediaBuffer->release();
1934                info->mMediaBuffer = NULL;
1935            }
1936
1937            if (mPortStatus[kPortIndexInput] == DISABLING) {
1938                CODEC_LOGV("Port is disabled, freeing buffer %p", buffer);
1939
1940                status_t err = freeBuffer(kPortIndexInput, i);
1941                CHECK_EQ(err, (status_t)OK);
1942            } else if (mState != ERROR
1943                    && mPortStatus[kPortIndexInput] != SHUTTING_DOWN) {
1944                CHECK_EQ((int)mPortStatus[kPortIndexInput], (int)ENABLED);
1945                drainInputBuffer(&buffers->editItemAt(i));
1946            }
1947            break;
1948        }
1949
1950        case omx_message::FILL_BUFFER_DONE:
1951        {
1952            IOMX::buffer_id buffer = msg.u.extended_buffer_data.buffer;
1953            OMX_U32 flags = msg.u.extended_buffer_data.flags;
1954
1955            CODEC_LOGV("FILL_BUFFER_DONE(buffer: %p, size: %ld, flags: 0x%08lx, timestamp: %lld us (%.2f secs))",
1956                 buffer,
1957                 msg.u.extended_buffer_data.range_length,
1958                 flags,
1959                 msg.u.extended_buffer_data.timestamp,
1960                 msg.u.extended_buffer_data.timestamp / 1E6);
1961
1962            Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
1963            size_t i = 0;
1964            while (i < buffers->size() && (*buffers)[i].mBuffer != buffer) {
1965                ++i;
1966            }
1967
1968            CHECK(i < buffers->size());
1969            BufferInfo *info = &buffers->editItemAt(i);
1970
1971            if (info->mStatus != OWNED_BY_COMPONENT) {
1972                LOGW("We already own output buffer %p, yet received "
1973                     "a FILL_BUFFER_DONE.", buffer);
1974            }
1975
1976            info->mStatus = OWNED_BY_US;
1977
1978            if (mPortStatus[kPortIndexOutput] == DISABLING) {
1979                CODEC_LOGV("Port is disabled, freeing buffer %p", buffer);
1980
1981                status_t err = freeBuffer(kPortIndexOutput, i);
1982                CHECK_EQ(err, (status_t)OK);
1983
1984#if 0
1985            } else if (mPortStatus[kPortIndexOutput] == ENABLED
1986                       && (flags & OMX_BUFFERFLAG_EOS)) {
1987                CODEC_LOGV("No more output data.");
1988                mNoMoreOutputData = true;
1989                mBufferFilled.signal();
1990#endif
1991            } else if (mPortStatus[kPortIndexOutput] != SHUTTING_DOWN) {
1992                CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED);
1993
1994                if (info->mMediaBuffer == NULL) {
1995                    CHECK(mOMXLivesLocally);
1996                    CHECK(mQuirks & kRequiresAllocateBufferOnOutputPorts);
1997                    CHECK(mQuirks & kDefersOutputBufferAllocation);
1998
1999                    // The qcom video decoders on Nexus don't actually allocate
2000                    // output buffer memory on a call to OMX_AllocateBuffer
2001                    // the "pBuffer" member of the OMX_BUFFERHEADERTYPE
2002                    // structure is only filled in later.
2003
2004                    info->mMediaBuffer = new MediaBuffer(
2005                            msg.u.extended_buffer_data.data_ptr,
2006                            info->mSize);
2007                    info->mMediaBuffer->setObserver(this);
2008                }
2009
2010                MediaBuffer *buffer = info->mMediaBuffer;
2011                bool isGraphicBuffer = buffer->graphicBuffer() != NULL;
2012
2013                if (!isGraphicBuffer
2014                    && msg.u.extended_buffer_data.range_offset
2015                        + msg.u.extended_buffer_data.range_length
2016                            > buffer->size()) {
2017                    CODEC_LOGE(
2018                            "Codec lied about its buffer size requirements, "
2019                            "sending a buffer larger than the originally "
2020                            "advertised size in FILL_BUFFER_DONE!");
2021                }
2022                buffer->set_range(
2023                        msg.u.extended_buffer_data.range_offset,
2024                        msg.u.extended_buffer_data.range_length);
2025
2026                buffer->meta_data()->clear();
2027
2028                buffer->meta_data()->setInt64(
2029                        kKeyTime, msg.u.extended_buffer_data.timestamp);
2030
2031                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_SYNCFRAME) {
2032                    buffer->meta_data()->setInt32(kKeyIsSyncFrame, true);
2033                }
2034                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_CODECCONFIG) {
2035                    buffer->meta_data()->setInt32(kKeyIsCodecConfig, true);
2036                }
2037
2038                if (isGraphicBuffer || mQuirks & kOutputBuffersAreUnreadable) {
2039                    buffer->meta_data()->setInt32(kKeyIsUnreadable, true);
2040                }
2041
2042                buffer->meta_data()->setPointer(
2043                        kKeyPlatformPrivate,
2044                        msg.u.extended_buffer_data.platform_private);
2045
2046                buffer->meta_data()->setPointer(
2047                        kKeyBufferID,
2048                        msg.u.extended_buffer_data.buffer);
2049
2050                if (msg.u.extended_buffer_data.flags & OMX_BUFFERFLAG_EOS) {
2051                    CODEC_LOGV("No more output data.");
2052                    mNoMoreOutputData = true;
2053                }
2054
2055                if (mTargetTimeUs >= 0) {
2056                    CHECK(msg.u.extended_buffer_data.timestamp <= mTargetTimeUs);
2057
2058                    if (msg.u.extended_buffer_data.timestamp < mTargetTimeUs) {
2059                        CODEC_LOGV(
2060                                "skipping output buffer at timestamp %lld us",
2061                                msg.u.extended_buffer_data.timestamp);
2062
2063                        fillOutputBuffer(info);
2064                        break;
2065                    }
2066
2067                    CODEC_LOGV(
2068                            "returning output buffer at target timestamp "
2069                            "%lld us",
2070                            msg.u.extended_buffer_data.timestamp);
2071
2072                    mTargetTimeUs = -1;
2073                }
2074
2075                mFilledBuffers.push_back(i);
2076                mBufferFilled.signal();
2077                if (mIsEncoder) {
2078                    sched_yield();
2079                }
2080            }
2081
2082            break;
2083        }
2084
2085        default:
2086        {
2087            CHECK(!"should not be here.");
2088            break;
2089        }
2090    }
2091}
2092
2093// Has the format changed in any way that the client would have to be aware of?
2094static bool formatHasNotablyChanged(
2095        const sp<MetaData> &from, const sp<MetaData> &to) {
2096    if (from.get() == NULL && to.get() == NULL) {
2097        return false;
2098    }
2099
2100    if ((from.get() == NULL && to.get() != NULL)
2101        || (from.get() != NULL && to.get() == NULL)) {
2102        return true;
2103    }
2104
2105    const char *mime_from, *mime_to;
2106    CHECK(from->findCString(kKeyMIMEType, &mime_from));
2107    CHECK(to->findCString(kKeyMIMEType, &mime_to));
2108
2109    if (strcasecmp(mime_from, mime_to)) {
2110        return true;
2111    }
2112
2113    if (!strcasecmp(mime_from, MEDIA_MIMETYPE_VIDEO_RAW)) {
2114        int32_t colorFormat_from, colorFormat_to;
2115        CHECK(from->findInt32(kKeyColorFormat, &colorFormat_from));
2116        CHECK(to->findInt32(kKeyColorFormat, &colorFormat_to));
2117
2118        if (colorFormat_from != colorFormat_to) {
2119            return true;
2120        }
2121
2122        int32_t width_from, width_to;
2123        CHECK(from->findInt32(kKeyWidth, &width_from));
2124        CHECK(to->findInt32(kKeyWidth, &width_to));
2125
2126        if (width_from != width_to) {
2127            return true;
2128        }
2129
2130        int32_t height_from, height_to;
2131        CHECK(from->findInt32(kKeyHeight, &height_from));
2132        CHECK(to->findInt32(kKeyHeight, &height_to));
2133
2134        if (height_from != height_to) {
2135            return true;
2136        }
2137
2138        int32_t left_from, top_from, right_from, bottom_from;
2139        CHECK(from->findRect(
2140                    kKeyCropRect,
2141                    &left_from, &top_from, &right_from, &bottom_from));
2142
2143        int32_t left_to, top_to, right_to, bottom_to;
2144        CHECK(to->findRect(
2145                    kKeyCropRect,
2146                    &left_to, &top_to, &right_to, &bottom_to));
2147
2148        if (left_to != left_from || top_to != top_from
2149                || right_to != right_from || bottom_to != bottom_from) {
2150            return true;
2151        }
2152    } else if (!strcasecmp(mime_from, MEDIA_MIMETYPE_AUDIO_RAW)) {
2153        int32_t numChannels_from, numChannels_to;
2154        CHECK(from->findInt32(kKeyChannelCount, &numChannels_from));
2155        CHECK(to->findInt32(kKeyChannelCount, &numChannels_to));
2156
2157        if (numChannels_from != numChannels_to) {
2158            return true;
2159        }
2160
2161        int32_t sampleRate_from, sampleRate_to;
2162        CHECK(from->findInt32(kKeySampleRate, &sampleRate_from));
2163        CHECK(to->findInt32(kKeySampleRate, &sampleRate_to));
2164
2165        if (sampleRate_from != sampleRate_to) {
2166            return true;
2167        }
2168    }
2169
2170    return false;
2171}
2172
2173void OMXCodec::onEvent(OMX_EVENTTYPE event, OMX_U32 data1, OMX_U32 data2) {
2174    switch (event) {
2175        case OMX_EventCmdComplete:
2176        {
2177            onCmdComplete((OMX_COMMANDTYPE)data1, data2);
2178            break;
2179        }
2180
2181        case OMX_EventError:
2182        {
2183            CODEC_LOGE("ERROR(0x%08lx, %ld)", data1, data2);
2184
2185            setState(ERROR);
2186            break;
2187        }
2188
2189        case OMX_EventPortSettingsChanged:
2190        {
2191            CODEC_LOGV("OMX_EventPortSettingsChanged(port=%ld, data2=0x%08lx)",
2192                       data1, data2);
2193
2194            if (data2 == 0 || data2 == OMX_IndexParamPortDefinition) {
2195                onPortSettingsChanged(data1);
2196            } else if (data1 == kPortIndexOutput
2197                    && data2 == OMX_IndexConfigCommonOutputCrop) {
2198
2199                sp<MetaData> oldOutputFormat = mOutputFormat;
2200                initOutputFormat(mSource->getFormat());
2201
2202                if (formatHasNotablyChanged(oldOutputFormat, mOutputFormat)) {
2203                    mOutputPortSettingsHaveChanged = true;
2204
2205                    if (mNativeWindow != NULL) {
2206                        int32_t left, top, right, bottom;
2207                        CHECK(mOutputFormat->findRect(
2208                                    kKeyCropRect,
2209                                    &left, &top, &right, &bottom));
2210
2211                        android_native_rect_t crop;
2212                        crop.left = left;
2213                        crop.top = top;
2214                        crop.right = right;
2215                        crop.bottom = bottom;
2216
2217                        // We'll ignore any errors here, if the surface is
2218                        // already invalid, we'll know soon enough.
2219                        native_window_set_crop(mNativeWindow.get(), &crop);
2220                    }
2221                }
2222            }
2223            break;
2224        }
2225
2226#if 0
2227        case OMX_EventBufferFlag:
2228        {
2229            CODEC_LOGV("EVENT_BUFFER_FLAG(%ld)", data1);
2230
2231            if (data1 == kPortIndexOutput) {
2232                mNoMoreOutputData = true;
2233            }
2234            break;
2235        }
2236#endif
2237
2238        default:
2239        {
2240            CODEC_LOGV("EVENT(%d, %ld, %ld)", event, data1, data2);
2241            break;
2242        }
2243    }
2244}
2245
2246void OMXCodec::onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data) {
2247    switch (cmd) {
2248        case OMX_CommandStateSet:
2249        {
2250            onStateChange((OMX_STATETYPE)data);
2251            break;
2252        }
2253
2254        case OMX_CommandPortDisable:
2255        {
2256            OMX_U32 portIndex = data;
2257            CODEC_LOGV("PORT_DISABLED(%ld)", portIndex);
2258
2259            CHECK(mState == EXECUTING || mState == RECONFIGURING);
2260            CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLING);
2261            CHECK_EQ(mPortBuffers[portIndex].size(), 0u);
2262
2263            mPortStatus[portIndex] = DISABLED;
2264
2265            if (mState == RECONFIGURING) {
2266                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2267
2268                sp<MetaData> oldOutputFormat = mOutputFormat;
2269                initOutputFormat(mSource->getFormat());
2270
2271                // Don't notify clients if the output port settings change
2272                // wasn't of importance to them, i.e. it may be that just the
2273                // number of buffers has changed and nothing else.
2274                mOutputPortSettingsHaveChanged =
2275                    formatHasNotablyChanged(oldOutputFormat, mOutputFormat);
2276
2277                enablePortAsync(portIndex);
2278
2279                status_t err = allocateBuffersOnPort(portIndex);
2280
2281                if (err != OK) {
2282                    CODEC_LOGE("allocateBuffersOnPort failed (err = %d)", err);
2283                    setState(ERROR);
2284                }
2285            }
2286            break;
2287        }
2288
2289        case OMX_CommandPortEnable:
2290        {
2291            OMX_U32 portIndex = data;
2292            CODEC_LOGV("PORT_ENABLED(%ld)", portIndex);
2293
2294            CHECK(mState == EXECUTING || mState == RECONFIGURING);
2295            CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLING);
2296
2297            mPortStatus[portIndex] = ENABLED;
2298
2299            if (mState == RECONFIGURING) {
2300                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2301
2302                setState(EXECUTING);
2303
2304                fillOutputBuffers();
2305            }
2306            break;
2307        }
2308
2309        case OMX_CommandFlush:
2310        {
2311            OMX_U32 portIndex = data;
2312
2313            CODEC_LOGV("FLUSH_DONE(%ld)", portIndex);
2314
2315            CHECK_EQ((int)mPortStatus[portIndex], (int)SHUTTING_DOWN);
2316            mPortStatus[portIndex] = ENABLED;
2317
2318            CHECK_EQ(countBuffersWeOwn(mPortBuffers[portIndex]),
2319                     mPortBuffers[portIndex].size());
2320
2321            if (mState == RECONFIGURING) {
2322                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2323
2324                disablePortAsync(portIndex);
2325            } else if (mState == EXECUTING_TO_IDLE) {
2326                if (mPortStatus[kPortIndexInput] == ENABLED
2327                    && mPortStatus[kPortIndexOutput] == ENABLED) {
2328                    CODEC_LOGV("Finished flushing both ports, now completing "
2329                         "transition from EXECUTING to IDLE.");
2330
2331                    mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
2332                    mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
2333
2334                    status_t err =
2335                        mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
2336                    CHECK_EQ(err, (status_t)OK);
2337                }
2338            } else {
2339                // We're flushing both ports in preparation for seeking.
2340
2341                if (mPortStatus[kPortIndexInput] == ENABLED
2342                    && mPortStatus[kPortIndexOutput] == ENABLED) {
2343                    CODEC_LOGV("Finished flushing both ports, now continuing from"
2344                         " seek-time.");
2345
2346                    // We implicitly resume pulling on our upstream source.
2347                    mPaused = false;
2348
2349                    drainInputBuffers();
2350                    fillOutputBuffers();
2351                }
2352
2353                if (mOutputPortSettingsChangedPending) {
2354                    CODEC_LOGV(
2355                            "Honoring deferred output port settings change.");
2356
2357                    mOutputPortSettingsChangedPending = false;
2358                    onPortSettingsChanged(kPortIndexOutput);
2359                }
2360            }
2361
2362            break;
2363        }
2364
2365        default:
2366        {
2367            CODEC_LOGV("CMD_COMPLETE(%d, %ld)", cmd, data);
2368            break;
2369        }
2370    }
2371}
2372
2373void OMXCodec::onStateChange(OMX_STATETYPE newState) {
2374    CODEC_LOGV("onStateChange %d", newState);
2375
2376    switch (newState) {
2377        case OMX_StateIdle:
2378        {
2379            CODEC_LOGV("Now Idle.");
2380            if (mState == LOADED_TO_IDLE) {
2381                status_t err = mOMX->sendCommand(
2382                        mNode, OMX_CommandStateSet, OMX_StateExecuting);
2383
2384                CHECK_EQ(err, (status_t)OK);
2385
2386                setState(IDLE_TO_EXECUTING);
2387            } else {
2388                CHECK_EQ((int)mState, (int)EXECUTING_TO_IDLE);
2389
2390                CHECK_EQ(
2391                    countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
2392                    mPortBuffers[kPortIndexInput].size());
2393
2394                CHECK_EQ(
2395                    countBuffersWeOwn(mPortBuffers[kPortIndexOutput]),
2396                    mPortBuffers[kPortIndexOutput].size());
2397
2398                status_t err = mOMX->sendCommand(
2399                        mNode, OMX_CommandStateSet, OMX_StateLoaded);
2400
2401                CHECK_EQ(err, (status_t)OK);
2402
2403                err = freeBuffersOnPort(kPortIndexInput);
2404                CHECK_EQ(err, (status_t)OK);
2405
2406                err = freeBuffersOnPort(kPortIndexOutput);
2407                CHECK_EQ(err, (status_t)OK);
2408
2409                mPortStatus[kPortIndexInput] = ENABLED;
2410                mPortStatus[kPortIndexOutput] = ENABLED;
2411
2412                setState(IDLE_TO_LOADED);
2413            }
2414            break;
2415        }
2416
2417        case OMX_StateExecuting:
2418        {
2419            CHECK_EQ((int)mState, (int)IDLE_TO_EXECUTING);
2420
2421            CODEC_LOGV("Now Executing.");
2422
2423            mOutputPortSettingsChangedPending = false;
2424
2425            setState(EXECUTING);
2426
2427            // Buffers will be submitted to the component in the first
2428            // call to OMXCodec::read as mInitialBufferSubmit is true at
2429            // this point. This ensures that this on_message call returns,
2430            // releases the lock and ::init can notice the state change and
2431            // itself return.
2432            break;
2433        }
2434
2435        case OMX_StateLoaded:
2436        {
2437            CHECK_EQ((int)mState, (int)IDLE_TO_LOADED);
2438
2439            CODEC_LOGV("Now Loaded.");
2440
2441            setState(LOADED);
2442            break;
2443        }
2444
2445        case OMX_StateInvalid:
2446        {
2447            setState(ERROR);
2448            break;
2449        }
2450
2451        default:
2452        {
2453            CHECK(!"should not be here.");
2454            break;
2455        }
2456    }
2457}
2458
2459// static
2460size_t OMXCodec::countBuffersWeOwn(const Vector<BufferInfo> &buffers) {
2461    size_t n = 0;
2462    for (size_t i = 0; i < buffers.size(); ++i) {
2463        if (buffers[i].mStatus != OWNED_BY_COMPONENT) {
2464            ++n;
2465        }
2466    }
2467
2468    return n;
2469}
2470
2471status_t OMXCodec::freeBuffersOnPort(
2472        OMX_U32 portIndex, bool onlyThoseWeOwn) {
2473    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
2474
2475    status_t stickyErr = OK;
2476
2477    for (size_t i = buffers->size(); i-- > 0;) {
2478        BufferInfo *info = &buffers->editItemAt(i);
2479
2480        if (onlyThoseWeOwn && info->mStatus == OWNED_BY_COMPONENT) {
2481            continue;
2482        }
2483
2484        CHECK(info->mStatus == OWNED_BY_US
2485                || info->mStatus == OWNED_BY_NATIVE_WINDOW);
2486
2487        CODEC_LOGV("freeing buffer %p on port %ld", info->mBuffer, portIndex);
2488
2489        status_t err = freeBuffer(portIndex, i);
2490
2491        if (err != OK) {
2492            stickyErr = err;
2493        }
2494
2495    }
2496
2497    CHECK(onlyThoseWeOwn || buffers->isEmpty());
2498
2499    return stickyErr;
2500}
2501
2502status_t OMXCodec::freeBuffer(OMX_U32 portIndex, size_t bufIndex) {
2503    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
2504
2505    BufferInfo *info = &buffers->editItemAt(bufIndex);
2506
2507    status_t err = mOMX->freeBuffer(mNode, portIndex, info->mBuffer);
2508
2509    if (err == OK && info->mMediaBuffer != NULL) {
2510        CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2511        info->mMediaBuffer->setObserver(NULL);
2512
2513        // Make sure nobody but us owns this buffer at this point.
2514        CHECK_EQ(info->mMediaBuffer->refcount(), 0);
2515
2516        // Cancel the buffer if it belongs to an ANativeWindow.
2517        sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer();
2518        if (info->mStatus == OWNED_BY_US && graphicBuffer != 0) {
2519            err = cancelBufferToNativeWindow(info);
2520        }
2521
2522        info->mMediaBuffer->release();
2523        info->mMediaBuffer = NULL;
2524    }
2525
2526    if (err == OK) {
2527        buffers->removeAt(bufIndex);
2528    }
2529
2530    return err;
2531}
2532
2533void OMXCodec::onPortSettingsChanged(OMX_U32 portIndex) {
2534    CODEC_LOGV("PORT_SETTINGS_CHANGED(%ld)", portIndex);
2535
2536    CHECK_EQ((int)mState, (int)EXECUTING);
2537    CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2538    CHECK(!mOutputPortSettingsChangedPending);
2539
2540    if (mPortStatus[kPortIndexOutput] != ENABLED) {
2541        CODEC_LOGV("Deferring output port settings change.");
2542        mOutputPortSettingsChangedPending = true;
2543        return;
2544    }
2545
2546    setState(RECONFIGURING);
2547
2548    if (mQuirks & kNeedsFlushBeforeDisable) {
2549        if (!flushPortAsync(portIndex)) {
2550            onCmdComplete(OMX_CommandFlush, portIndex);
2551        }
2552    } else {
2553        disablePortAsync(portIndex);
2554    }
2555}
2556
2557bool OMXCodec::flushPortAsync(OMX_U32 portIndex) {
2558    CHECK(mState == EXECUTING || mState == RECONFIGURING
2559            || mState == EXECUTING_TO_IDLE);
2560
2561    CODEC_LOGV("flushPortAsync(%ld): we own %d out of %d buffers already.",
2562         portIndex, countBuffersWeOwn(mPortBuffers[portIndex]),
2563         mPortBuffers[portIndex].size());
2564
2565    CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED);
2566    mPortStatus[portIndex] = SHUTTING_DOWN;
2567
2568    if ((mQuirks & kRequiresFlushCompleteEmulation)
2569        && countBuffersWeOwn(mPortBuffers[portIndex])
2570                == mPortBuffers[portIndex].size()) {
2571        // No flush is necessary and this component fails to send a
2572        // flush-complete event in this case.
2573
2574        return false;
2575    }
2576
2577    status_t err =
2578        mOMX->sendCommand(mNode, OMX_CommandFlush, portIndex);
2579    CHECK_EQ(err, (status_t)OK);
2580
2581    return true;
2582}
2583
2584void OMXCodec::disablePortAsync(OMX_U32 portIndex) {
2585    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2586
2587    CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED);
2588    mPortStatus[portIndex] = DISABLING;
2589
2590    CODEC_LOGV("sending OMX_CommandPortDisable(%ld)", portIndex);
2591    status_t err =
2592        mOMX->sendCommand(mNode, OMX_CommandPortDisable, portIndex);
2593    CHECK_EQ(err, (status_t)OK);
2594
2595    freeBuffersOnPort(portIndex, true);
2596}
2597
2598void OMXCodec::enablePortAsync(OMX_U32 portIndex) {
2599    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2600
2601    CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLED);
2602    mPortStatus[portIndex] = ENABLING;
2603
2604    CODEC_LOGV("sending OMX_CommandPortEnable(%ld)", portIndex);
2605    status_t err =
2606        mOMX->sendCommand(mNode, OMX_CommandPortEnable, portIndex);
2607    CHECK_EQ(err, (status_t)OK);
2608}
2609
2610void OMXCodec::fillOutputBuffers() {
2611    CHECK_EQ((int)mState, (int)EXECUTING);
2612
2613    // This is a workaround for some decoders not properly reporting
2614    // end-of-output-stream. If we own all input buffers and also own
2615    // all output buffers and we already signalled end-of-input-stream,
2616    // the end-of-output-stream is implied.
2617    if (mSignalledEOS
2618            && countBuffersWeOwn(mPortBuffers[kPortIndexInput])
2619                == mPortBuffers[kPortIndexInput].size()
2620            && countBuffersWeOwn(mPortBuffers[kPortIndexOutput])
2621                == mPortBuffers[kPortIndexOutput].size()) {
2622        mNoMoreOutputData = true;
2623        mBufferFilled.signal();
2624
2625        return;
2626    }
2627
2628    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2629    for (size_t i = 0; i < buffers->size(); ++i) {
2630        BufferInfo *info = &buffers->editItemAt(i);
2631        if (info->mStatus == OWNED_BY_US) {
2632            fillOutputBuffer(&buffers->editItemAt(i));
2633        }
2634    }
2635}
2636
2637void OMXCodec::drainInputBuffers() {
2638    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2639
2640    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2641    for (size_t i = 0; i < buffers->size(); ++i) {
2642        BufferInfo *info = &buffers->editItemAt(i);
2643
2644        if (info->mStatus != OWNED_BY_US) {
2645            continue;
2646        }
2647
2648        if (!drainInputBuffer(info)) {
2649            break;
2650        }
2651
2652        if (mOnlySubmitOneBufferAtOneTime) {
2653            break;
2654        }
2655    }
2656}
2657
2658bool OMXCodec::drainInputBuffer(BufferInfo *info) {
2659    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
2660
2661    if (mSignalledEOS) {
2662        return false;
2663    }
2664
2665    if (mCodecSpecificDataIndex < mCodecSpecificData.size()) {
2666        const CodecSpecificData *specific =
2667            mCodecSpecificData[mCodecSpecificDataIndex];
2668
2669        size_t size = specific->mSize;
2670
2671        if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mMIME)
2672                && !(mQuirks & kWantsNALFragments)) {
2673            static const uint8_t kNALStartCode[4] =
2674                    { 0x00, 0x00, 0x00, 0x01 };
2675
2676            CHECK(info->mSize >= specific->mSize + 4);
2677
2678            size += 4;
2679
2680            memcpy(info->mData, kNALStartCode, 4);
2681            memcpy((uint8_t *)info->mData + 4,
2682                   specific->mData, specific->mSize);
2683        } else {
2684            CHECK(info->mSize >= specific->mSize);
2685            memcpy(info->mData, specific->mData, specific->mSize);
2686        }
2687
2688        mNoMoreOutputData = false;
2689
2690        CODEC_LOGV("calling emptyBuffer with codec specific data");
2691
2692        status_t err = mOMX->emptyBuffer(
2693                mNode, info->mBuffer, 0, size,
2694                OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG,
2695                0);
2696        CHECK_EQ(err, (status_t)OK);
2697
2698        info->mStatus = OWNED_BY_COMPONENT;
2699
2700        ++mCodecSpecificDataIndex;
2701        return true;
2702    }
2703
2704    if (mPaused) {
2705        return false;
2706    }
2707
2708    status_t err;
2709
2710    bool signalEOS = false;
2711    int64_t timestampUs = 0;
2712
2713    size_t offset = 0;
2714    int32_t n = 0;
2715
2716    for (;;) {
2717        MediaBuffer *srcBuffer;
2718        if (mSeekTimeUs >= 0) {
2719            if (mLeftOverBuffer) {
2720                mLeftOverBuffer->release();
2721                mLeftOverBuffer = NULL;
2722            }
2723
2724            MediaSource::ReadOptions options;
2725            options.setSeekTo(mSeekTimeUs, mSeekMode);
2726
2727            mSeekTimeUs = -1;
2728            mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC;
2729            mBufferFilled.signal();
2730
2731            err = mSource->read(&srcBuffer, &options);
2732
2733            if (err == OK) {
2734                int64_t targetTimeUs;
2735                if (srcBuffer->meta_data()->findInt64(
2736                            kKeyTargetTime, &targetTimeUs)
2737                        && targetTimeUs >= 0) {
2738                    CODEC_LOGV("targetTimeUs = %lld us", targetTimeUs);
2739                    mTargetTimeUs = targetTimeUs;
2740                } else {
2741                    mTargetTimeUs = -1;
2742                }
2743            }
2744        } else if (mLeftOverBuffer) {
2745            srcBuffer = mLeftOverBuffer;
2746            mLeftOverBuffer = NULL;
2747
2748            err = OK;
2749        } else {
2750            err = mSource->read(&srcBuffer);
2751        }
2752
2753        if (err != OK) {
2754            signalEOS = true;
2755            mFinalStatus = err;
2756            mSignalledEOS = true;
2757            mBufferFilled.signal();
2758            break;
2759        }
2760
2761        size_t remainingBytes = info->mSize - offset;
2762
2763        if (srcBuffer->range_length() > remainingBytes) {
2764            if (offset == 0) {
2765                CODEC_LOGE(
2766                     "Codec's input buffers are too small to accomodate "
2767                     "buffer read from source (info->mSize = %d, srcLength = %d)",
2768                     info->mSize, srcBuffer->range_length());
2769
2770                srcBuffer->release();
2771                srcBuffer = NULL;
2772
2773                setState(ERROR);
2774                return false;
2775            }
2776
2777            mLeftOverBuffer = srcBuffer;
2778            break;
2779        }
2780
2781        bool releaseBuffer = true;
2782        if (mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames)) {
2783            CHECK(mOMXLivesLocally && offset == 0);
2784
2785            OMX_BUFFERHEADERTYPE *header =
2786                (OMX_BUFFERHEADERTYPE *)info->mBuffer;
2787
2788            CHECK(header->pBuffer == info->mData);
2789
2790            header->pBuffer =
2791                (OMX_U8 *)srcBuffer->data() + srcBuffer->range_offset();
2792
2793            releaseBuffer = false;
2794            info->mMediaBuffer = srcBuffer;
2795        } else {
2796            if (mIsMetaDataStoredInVideoBuffers) {
2797                releaseBuffer = false;
2798                info->mMediaBuffer = srcBuffer;
2799            }
2800            memcpy((uint8_t *)info->mData + offset,
2801                    (const uint8_t *)srcBuffer->data()
2802                        + srcBuffer->range_offset(),
2803                    srcBuffer->range_length());
2804        }
2805
2806        int64_t lastBufferTimeUs;
2807        CHECK(srcBuffer->meta_data()->findInt64(kKeyTime, &lastBufferTimeUs));
2808        CHECK(lastBufferTimeUs >= 0);
2809
2810        if (offset == 0) {
2811            timestampUs = lastBufferTimeUs;
2812        }
2813
2814        offset += srcBuffer->range_length();
2815
2816        if (releaseBuffer) {
2817            srcBuffer->release();
2818            srcBuffer = NULL;
2819        }
2820
2821        ++n;
2822
2823        if (!(mQuirks & kSupportsMultipleFramesPerInputBuffer)) {
2824            break;
2825        }
2826
2827        int64_t coalescedDurationUs = lastBufferTimeUs - timestampUs;
2828
2829        if (coalescedDurationUs > 250000ll) {
2830            // Don't coalesce more than 250ms worth of encoded data at once.
2831            break;
2832        }
2833    }
2834
2835    if (n > 1) {
2836        LOGV("coalesced %d frames into one input buffer", n);
2837    }
2838
2839    OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME;
2840
2841    if (signalEOS) {
2842        flags |= OMX_BUFFERFLAG_EOS;
2843    } else {
2844        mNoMoreOutputData = false;
2845    }
2846
2847    CODEC_LOGV("Calling emptyBuffer on buffer %p (length %d), "
2848               "timestamp %lld us (%.2f secs)",
2849               info->mBuffer, offset,
2850               timestampUs, timestampUs / 1E6);
2851
2852    err = mOMX->emptyBuffer(
2853            mNode, info->mBuffer, 0, offset,
2854            flags, timestampUs);
2855
2856    if (err != OK) {
2857        setState(ERROR);
2858        return false;
2859    }
2860
2861    info->mStatus = OWNED_BY_COMPONENT;
2862
2863    // This component does not ever signal the EOS flag on output buffers,
2864    // Thanks for nothing.
2865    if (mSignalledEOS && !strcmp(mComponentName, "OMX.TI.Video.encoder")) {
2866        mNoMoreOutputData = true;
2867        mBufferFilled.signal();
2868    }
2869
2870    return true;
2871}
2872
2873void OMXCodec::fillOutputBuffer(BufferInfo *info) {
2874    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
2875
2876    if (mNoMoreOutputData) {
2877        CODEC_LOGV("There is no more output data available, not "
2878             "calling fillOutputBuffer");
2879        return;
2880    }
2881
2882    if (info->mMediaBuffer != NULL) {
2883        sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer();
2884        if (graphicBuffer != 0) {
2885            // When using a native buffer we need to lock the buffer before
2886            // giving it to OMX.
2887            CODEC_LOGV("Calling lockBuffer on %p", info->mBuffer);
2888            int err = mNativeWindow->lockBuffer(mNativeWindow.get(),
2889                    graphicBuffer.get());
2890            if (err != 0) {
2891                CODEC_LOGE("lockBuffer failed w/ error 0x%08x", err);
2892
2893                setState(ERROR);
2894                return;
2895            }
2896        }
2897    }
2898
2899    CODEC_LOGV("Calling fillBuffer on buffer %p", info->mBuffer);
2900    status_t err = mOMX->fillBuffer(mNode, info->mBuffer);
2901
2902    if (err != OK) {
2903        CODEC_LOGE("fillBuffer failed w/ error 0x%08x", err);
2904
2905        setState(ERROR);
2906        return;
2907    }
2908
2909    info->mStatus = OWNED_BY_COMPONENT;
2910}
2911
2912bool OMXCodec::drainInputBuffer(IOMX::buffer_id buffer) {
2913    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2914    for (size_t i = 0; i < buffers->size(); ++i) {
2915        if ((*buffers)[i].mBuffer == buffer) {
2916            return drainInputBuffer(&buffers->editItemAt(i));
2917        }
2918    }
2919
2920    CHECK(!"should not be here.");
2921
2922    return false;
2923}
2924
2925void OMXCodec::fillOutputBuffer(IOMX::buffer_id buffer) {
2926    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2927    for (size_t i = 0; i < buffers->size(); ++i) {
2928        if ((*buffers)[i].mBuffer == buffer) {
2929            fillOutputBuffer(&buffers->editItemAt(i));
2930            return;
2931        }
2932    }
2933
2934    CHECK(!"should not be here.");
2935}
2936
2937void OMXCodec::setState(State newState) {
2938    mState = newState;
2939    mAsyncCompletion.signal();
2940
2941    // This may cause some spurious wakeups but is necessary to
2942    // unblock the reader if we enter ERROR state.
2943    mBufferFilled.signal();
2944}
2945
2946void OMXCodec::setRawAudioFormat(
2947        OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels) {
2948
2949    // port definition
2950    OMX_PARAM_PORTDEFINITIONTYPE def;
2951    InitOMXParams(&def);
2952    def.nPortIndex = portIndex;
2953    status_t err = mOMX->getParameter(
2954            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
2955    CHECK_EQ(err, (status_t)OK);
2956    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
2957    CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition,
2958            &def, sizeof(def)), (status_t)OK);
2959
2960    // pcm param
2961    OMX_AUDIO_PARAM_PCMMODETYPE pcmParams;
2962    InitOMXParams(&pcmParams);
2963    pcmParams.nPortIndex = portIndex;
2964
2965    err = mOMX->getParameter(
2966            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
2967
2968    CHECK_EQ(err, (status_t)OK);
2969
2970    pcmParams.nChannels = numChannels;
2971    pcmParams.eNumData = OMX_NumericalDataSigned;
2972    pcmParams.bInterleaved = OMX_TRUE;
2973    pcmParams.nBitPerSample = 16;
2974    pcmParams.nSamplingRate = sampleRate;
2975    pcmParams.ePCMMode = OMX_AUDIO_PCMModeLinear;
2976
2977    if (numChannels == 1) {
2978        pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelCF;
2979    } else {
2980        CHECK_EQ(numChannels, 2);
2981
2982        pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelLF;
2983        pcmParams.eChannelMapping[1] = OMX_AUDIO_ChannelRF;
2984    }
2985
2986    err = mOMX->setParameter(
2987            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
2988
2989    CHECK_EQ(err, (status_t)OK);
2990}
2991
2992static OMX_AUDIO_AMRBANDMODETYPE pickModeFromBitRate(bool isAMRWB, int32_t bps) {
2993    if (isAMRWB) {
2994        if (bps <= 6600) {
2995            return OMX_AUDIO_AMRBandModeWB0;
2996        } else if (bps <= 8850) {
2997            return OMX_AUDIO_AMRBandModeWB1;
2998        } else if (bps <= 12650) {
2999            return OMX_AUDIO_AMRBandModeWB2;
3000        } else if (bps <= 14250) {
3001            return OMX_AUDIO_AMRBandModeWB3;
3002        } else if (bps <= 15850) {
3003            return OMX_AUDIO_AMRBandModeWB4;
3004        } else if (bps <= 18250) {
3005            return OMX_AUDIO_AMRBandModeWB5;
3006        } else if (bps <= 19850) {
3007            return OMX_AUDIO_AMRBandModeWB6;
3008        } else if (bps <= 23050) {
3009            return OMX_AUDIO_AMRBandModeWB7;
3010        }
3011
3012        // 23850 bps
3013        return OMX_AUDIO_AMRBandModeWB8;
3014    } else {  // AMRNB
3015        if (bps <= 4750) {
3016            return OMX_AUDIO_AMRBandModeNB0;
3017        } else if (bps <= 5150) {
3018            return OMX_AUDIO_AMRBandModeNB1;
3019        } else if (bps <= 5900) {
3020            return OMX_AUDIO_AMRBandModeNB2;
3021        } else if (bps <= 6700) {
3022            return OMX_AUDIO_AMRBandModeNB3;
3023        } else if (bps <= 7400) {
3024            return OMX_AUDIO_AMRBandModeNB4;
3025        } else if (bps <= 7950) {
3026            return OMX_AUDIO_AMRBandModeNB5;
3027        } else if (bps <= 10200) {
3028            return OMX_AUDIO_AMRBandModeNB6;
3029        }
3030
3031        // 12200 bps
3032        return OMX_AUDIO_AMRBandModeNB7;
3033    }
3034}
3035
3036void OMXCodec::setAMRFormat(bool isWAMR, int32_t bitRate) {
3037    OMX_U32 portIndex = mIsEncoder ? kPortIndexOutput : kPortIndexInput;
3038
3039    OMX_AUDIO_PARAM_AMRTYPE def;
3040    InitOMXParams(&def);
3041    def.nPortIndex = portIndex;
3042
3043    status_t err =
3044        mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
3045
3046    CHECK_EQ(err, (status_t)OK);
3047
3048    def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
3049
3050    def.eAMRBandMode = pickModeFromBitRate(isWAMR, bitRate);
3051    err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
3052    CHECK_EQ(err, (status_t)OK);
3053
3054    ////////////////////////
3055
3056    if (mIsEncoder) {
3057        sp<MetaData> format = mSource->getFormat();
3058        int32_t sampleRate;
3059        int32_t numChannels;
3060        CHECK(format->findInt32(kKeySampleRate, &sampleRate));
3061        CHECK(format->findInt32(kKeyChannelCount, &numChannels));
3062
3063        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
3064    }
3065}
3066
3067void OMXCodec::setAACFormat(int32_t numChannels, int32_t sampleRate, int32_t bitRate) {
3068    CHECK(numChannels == 1 || numChannels == 2);
3069    if (mIsEncoder) {
3070        //////////////// input port ////////////////////
3071        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
3072
3073        //////////////// output port ////////////////////
3074        // format
3075        OMX_AUDIO_PARAM_PORTFORMATTYPE format;
3076        format.nPortIndex = kPortIndexOutput;
3077        format.nIndex = 0;
3078        status_t err = OMX_ErrorNone;
3079        while (OMX_ErrorNone == err) {
3080            CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioPortFormat,
3081                    &format, sizeof(format)), (status_t)OK);
3082            if (format.eEncoding == OMX_AUDIO_CodingAAC) {
3083                break;
3084            }
3085            format.nIndex++;
3086        }
3087        CHECK_EQ((status_t)OK, err);
3088        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioPortFormat,
3089                &format, sizeof(format)), (status_t)OK);
3090
3091        // port definition
3092        OMX_PARAM_PORTDEFINITIONTYPE def;
3093        InitOMXParams(&def);
3094        def.nPortIndex = kPortIndexOutput;
3095        CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamPortDefinition,
3096                &def, sizeof(def)), (status_t)OK);
3097        def.format.audio.bFlagErrorConcealment = OMX_TRUE;
3098        def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
3099        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition,
3100                &def, sizeof(def)), (status_t)OK);
3101
3102        // profile
3103        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
3104        InitOMXParams(&profile);
3105        profile.nPortIndex = kPortIndexOutput;
3106        CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioAac,
3107                &profile, sizeof(profile)), (status_t)OK);
3108        profile.nChannels = numChannels;
3109        profile.eChannelMode = (numChannels == 1?
3110                OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo);
3111        profile.nSampleRate = sampleRate;
3112        profile.nBitRate = bitRate;
3113        profile.nAudioBandWidth = 0;
3114        profile.nFrameLength = 0;
3115        profile.nAACtools = OMX_AUDIO_AACToolAll;
3116        profile.nAACERtools = OMX_AUDIO_AACERNone;
3117        profile.eAACProfile = OMX_AUDIO_AACObjectLC;
3118        profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
3119        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioAac,
3120                &profile, sizeof(profile)), (status_t)OK);
3121
3122    } else {
3123        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
3124        InitOMXParams(&profile);
3125        profile.nPortIndex = kPortIndexInput;
3126
3127        status_t err = mOMX->getParameter(
3128                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
3129        CHECK_EQ(err, (status_t)OK);
3130
3131        profile.nChannels = numChannels;
3132        profile.nSampleRate = sampleRate;
3133        profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4ADTS;
3134
3135        err = mOMX->setParameter(
3136                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
3137        CHECK_EQ(err, (status_t)OK);
3138    }
3139}
3140
3141void OMXCodec::setImageOutputFormat(
3142        OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height) {
3143    CODEC_LOGV("setImageOutputFormat(%ld, %ld)", width, height);
3144
3145#if 0
3146    OMX_INDEXTYPE index;
3147    status_t err = mOMX->get_extension_index(
3148            mNode, "OMX.TI.JPEG.decode.Config.OutputColorFormat", &index);
3149    CHECK_EQ(err, (status_t)OK);
3150
3151    err = mOMX->set_config(mNode, index, &format, sizeof(format));
3152    CHECK_EQ(err, (status_t)OK);
3153#endif
3154
3155    OMX_PARAM_PORTDEFINITIONTYPE def;
3156    InitOMXParams(&def);
3157    def.nPortIndex = kPortIndexOutput;
3158
3159    status_t err = mOMX->getParameter(
3160            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3161    CHECK_EQ(err, (status_t)OK);
3162
3163    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage);
3164
3165    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3166
3167    CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingUnused);
3168    imageDef->eColorFormat = format;
3169    imageDef->nFrameWidth = width;
3170    imageDef->nFrameHeight = height;
3171
3172    switch (format) {
3173        case OMX_COLOR_FormatYUV420PackedPlanar:
3174        case OMX_COLOR_FormatYUV411Planar:
3175        {
3176            def.nBufferSize = (width * height * 3) / 2;
3177            break;
3178        }
3179
3180        case OMX_COLOR_FormatCbYCrY:
3181        {
3182            def.nBufferSize = width * height * 2;
3183            break;
3184        }
3185
3186        case OMX_COLOR_Format32bitARGB8888:
3187        {
3188            def.nBufferSize = width * height * 4;
3189            break;
3190        }
3191
3192        case OMX_COLOR_Format16bitARGB4444:
3193        case OMX_COLOR_Format16bitARGB1555:
3194        case OMX_COLOR_Format16bitRGB565:
3195        case OMX_COLOR_Format16bitBGR565:
3196        {
3197            def.nBufferSize = width * height * 2;
3198            break;
3199        }
3200
3201        default:
3202            CHECK(!"Should not be here. Unknown color format.");
3203            break;
3204    }
3205
3206    def.nBufferCountActual = def.nBufferCountMin;
3207
3208    err = mOMX->setParameter(
3209            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3210    CHECK_EQ(err, (status_t)OK);
3211}
3212
3213void OMXCodec::setJPEGInputFormat(
3214        OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize) {
3215    OMX_PARAM_PORTDEFINITIONTYPE def;
3216    InitOMXParams(&def);
3217    def.nPortIndex = kPortIndexInput;
3218
3219    status_t err = mOMX->getParameter(
3220            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3221    CHECK_EQ(err, (status_t)OK);
3222
3223    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage);
3224    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3225
3226    CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingJPEG);
3227    imageDef->nFrameWidth = width;
3228    imageDef->nFrameHeight = height;
3229
3230    def.nBufferSize = compressedSize;
3231    def.nBufferCountActual = def.nBufferCountMin;
3232
3233    err = mOMX->setParameter(
3234            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3235    CHECK_EQ(err, (status_t)OK);
3236}
3237
3238void OMXCodec::addCodecSpecificData(const void *data, size_t size) {
3239    CodecSpecificData *specific =
3240        (CodecSpecificData *)malloc(sizeof(CodecSpecificData) + size - 1);
3241
3242    specific->mSize = size;
3243    memcpy(specific->mData, data, size);
3244
3245    mCodecSpecificData.push(specific);
3246}
3247
3248void OMXCodec::clearCodecSpecificData() {
3249    for (size_t i = 0; i < mCodecSpecificData.size(); ++i) {
3250        free(mCodecSpecificData.editItemAt(i));
3251    }
3252    mCodecSpecificData.clear();
3253    mCodecSpecificDataIndex = 0;
3254}
3255
3256status_t OMXCodec::start(MetaData *meta) {
3257    Mutex::Autolock autoLock(mLock);
3258
3259    if (mState != LOADED) {
3260        return UNKNOWN_ERROR;
3261    }
3262
3263    sp<MetaData> params = new MetaData;
3264    if (mQuirks & kWantsNALFragments) {
3265        params->setInt32(kKeyWantsNALFragments, true);
3266    }
3267    if (meta) {
3268        int64_t startTimeUs = 0;
3269        int64_t timeUs;
3270        if (meta->findInt64(kKeyTime, &timeUs)) {
3271            startTimeUs = timeUs;
3272        }
3273        params->setInt64(kKeyTime, startTimeUs);
3274    }
3275    status_t err = mSource->start(params.get());
3276
3277    if (err != OK) {
3278        return err;
3279    }
3280
3281    mCodecSpecificDataIndex = 0;
3282    mInitialBufferSubmit = true;
3283    mSignalledEOS = false;
3284    mNoMoreOutputData = false;
3285    mOutputPortSettingsHaveChanged = false;
3286    mSeekTimeUs = -1;
3287    mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC;
3288    mTargetTimeUs = -1;
3289    mFilledBuffers.clear();
3290    mPaused = false;
3291
3292    return init();
3293}
3294
3295status_t OMXCodec::stop() {
3296    CODEC_LOGV("stop mState=%d", mState);
3297
3298    Mutex::Autolock autoLock(mLock);
3299
3300    while (isIntermediateState(mState)) {
3301        mAsyncCompletion.wait(mLock);
3302    }
3303
3304    switch (mState) {
3305        case LOADED:
3306        case ERROR:
3307            break;
3308
3309        case EXECUTING:
3310        {
3311            setState(EXECUTING_TO_IDLE);
3312
3313            if (mQuirks & kRequiresFlushBeforeShutdown) {
3314                CODEC_LOGV("This component requires a flush before transitioning "
3315                     "from EXECUTING to IDLE...");
3316
3317                bool emulateInputFlushCompletion =
3318                    !flushPortAsync(kPortIndexInput);
3319
3320                bool emulateOutputFlushCompletion =
3321                    !flushPortAsync(kPortIndexOutput);
3322
3323                if (emulateInputFlushCompletion) {
3324                    onCmdComplete(OMX_CommandFlush, kPortIndexInput);
3325                }
3326
3327                if (emulateOutputFlushCompletion) {
3328                    onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
3329                }
3330            } else {
3331                mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
3332                mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
3333
3334                status_t err =
3335                    mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
3336                CHECK_EQ(err, (status_t)OK);
3337            }
3338
3339            while (mState != LOADED && mState != ERROR) {
3340                mAsyncCompletion.wait(mLock);
3341            }
3342
3343            break;
3344        }
3345
3346        default:
3347        {
3348            CHECK(!"should not be here.");
3349            break;
3350        }
3351    }
3352
3353    if (mLeftOverBuffer) {
3354        mLeftOverBuffer->release();
3355        mLeftOverBuffer = NULL;
3356    }
3357
3358    mSource->stop();
3359
3360    CODEC_LOGI("stopped in state %d", mState);
3361
3362    return OK;
3363}
3364
3365sp<MetaData> OMXCodec::getFormat() {
3366    Mutex::Autolock autoLock(mLock);
3367
3368    return mOutputFormat;
3369}
3370
3371status_t OMXCodec::read(
3372        MediaBuffer **buffer, const ReadOptions *options) {
3373    *buffer = NULL;
3374
3375    Mutex::Autolock autoLock(mLock);
3376
3377    if (mState != EXECUTING && mState != RECONFIGURING) {
3378        return UNKNOWN_ERROR;
3379    }
3380
3381    bool seeking = false;
3382    int64_t seekTimeUs;
3383    ReadOptions::SeekMode seekMode;
3384    if (options && options->getSeekTo(&seekTimeUs, &seekMode)) {
3385        seeking = true;
3386    }
3387
3388    if (mInitialBufferSubmit) {
3389        mInitialBufferSubmit = false;
3390
3391        if (seeking) {
3392            CHECK(seekTimeUs >= 0);
3393            mSeekTimeUs = seekTimeUs;
3394            mSeekMode = seekMode;
3395
3396            // There's no reason to trigger the code below, there's
3397            // nothing to flush yet.
3398            seeking = false;
3399            mPaused = false;
3400        }
3401
3402        drainInputBuffers();
3403
3404        if (mState == EXECUTING) {
3405            // Otherwise mState == RECONFIGURING and this code will trigger
3406            // after the output port is reenabled.
3407            fillOutputBuffers();
3408        }
3409    }
3410
3411    if (seeking) {
3412        while (mState == RECONFIGURING) {
3413            mBufferFilled.wait(mLock);
3414        }
3415
3416        if (mState != EXECUTING) {
3417            return UNKNOWN_ERROR;
3418        }
3419
3420        CODEC_LOGV("seeking to %lld us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6);
3421
3422        mSignalledEOS = false;
3423
3424        CHECK(seekTimeUs >= 0);
3425        mSeekTimeUs = seekTimeUs;
3426        mSeekMode = seekMode;
3427
3428        mFilledBuffers.clear();
3429
3430        CHECK_EQ((int)mState, (int)EXECUTING);
3431
3432        bool emulateInputFlushCompletion = !flushPortAsync(kPortIndexInput);
3433        bool emulateOutputFlushCompletion = !flushPortAsync(kPortIndexOutput);
3434
3435        if (emulateInputFlushCompletion) {
3436            onCmdComplete(OMX_CommandFlush, kPortIndexInput);
3437        }
3438
3439        if (emulateOutputFlushCompletion) {
3440            onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
3441        }
3442
3443        while (mSeekTimeUs >= 0) {
3444            mBufferFilled.wait(mLock);
3445        }
3446    }
3447
3448    while (mState != ERROR && !mNoMoreOutputData && mFilledBuffers.empty()) {
3449        if (mIsEncoder) {
3450            if (NO_ERROR != mBufferFilled.waitRelative(mLock, 3000000000LL)) {
3451                LOGW("Timed out waiting for buffers from video encoder: %d/%d",
3452                    countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
3453                    countBuffersWeOwn(mPortBuffers[kPortIndexOutput]));
3454            }
3455        } else {
3456            mBufferFilled.wait(mLock);
3457        }
3458    }
3459
3460    if (mState == ERROR) {
3461        return UNKNOWN_ERROR;
3462    }
3463
3464    if (mFilledBuffers.empty()) {
3465        return mSignalledEOS ? mFinalStatus : ERROR_END_OF_STREAM;
3466    }
3467
3468    if (mOutputPortSettingsHaveChanged) {
3469        mOutputPortSettingsHaveChanged = false;
3470
3471        return INFO_FORMAT_CHANGED;
3472    }
3473
3474    size_t index = *mFilledBuffers.begin();
3475    mFilledBuffers.erase(mFilledBuffers.begin());
3476
3477    BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index);
3478    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
3479    info->mStatus = OWNED_BY_CLIENT;
3480
3481    info->mMediaBuffer->add_ref();
3482    *buffer = info->mMediaBuffer;
3483
3484    return OK;
3485}
3486
3487void OMXCodec::signalBufferReturned(MediaBuffer *buffer) {
3488    Mutex::Autolock autoLock(mLock);
3489
3490    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
3491    for (size_t i = 0; i < buffers->size(); ++i) {
3492        BufferInfo *info = &buffers->editItemAt(i);
3493
3494        if (info->mMediaBuffer == buffer) {
3495            CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED);
3496            CHECK_EQ((int)info->mStatus, (int)OWNED_BY_CLIENT);
3497
3498            info->mStatus = OWNED_BY_US;
3499
3500            if (buffer->graphicBuffer() == 0) {
3501                fillOutputBuffer(info);
3502            } else {
3503                sp<MetaData> metaData = info->mMediaBuffer->meta_data();
3504                int32_t rendered = 0;
3505                if (!metaData->findInt32(kKeyRendered, &rendered)) {
3506                    rendered = 0;
3507                }
3508                if (!rendered) {
3509                    status_t err = cancelBufferToNativeWindow(info);
3510                    if (err < 0) {
3511                        return;
3512                    }
3513                }
3514
3515                info->mStatus = OWNED_BY_NATIVE_WINDOW;
3516
3517                // Dequeue the next buffer from the native window.
3518                BufferInfo *nextBufInfo = dequeueBufferFromNativeWindow();
3519                if (nextBufInfo == 0) {
3520                    return;
3521                }
3522
3523                // Give the buffer to the OMX node to fill.
3524                fillOutputBuffer(nextBufInfo);
3525            }
3526            return;
3527        }
3528    }
3529
3530    CHECK(!"should not be here.");
3531}
3532
3533static const char *imageCompressionFormatString(OMX_IMAGE_CODINGTYPE type) {
3534    static const char *kNames[] = {
3535        "OMX_IMAGE_CodingUnused",
3536        "OMX_IMAGE_CodingAutoDetect",
3537        "OMX_IMAGE_CodingJPEG",
3538        "OMX_IMAGE_CodingJPEG2K",
3539        "OMX_IMAGE_CodingEXIF",
3540        "OMX_IMAGE_CodingTIFF",
3541        "OMX_IMAGE_CodingGIF",
3542        "OMX_IMAGE_CodingPNG",
3543        "OMX_IMAGE_CodingLZW",
3544        "OMX_IMAGE_CodingBMP",
3545    };
3546
3547    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3548
3549    if (type < 0 || (size_t)type >= numNames) {
3550        return "UNKNOWN";
3551    } else {
3552        return kNames[type];
3553    }
3554}
3555
3556static const char *colorFormatString(OMX_COLOR_FORMATTYPE type) {
3557    static const char *kNames[] = {
3558        "OMX_COLOR_FormatUnused",
3559        "OMX_COLOR_FormatMonochrome",
3560        "OMX_COLOR_Format8bitRGB332",
3561        "OMX_COLOR_Format12bitRGB444",
3562        "OMX_COLOR_Format16bitARGB4444",
3563        "OMX_COLOR_Format16bitARGB1555",
3564        "OMX_COLOR_Format16bitRGB565",
3565        "OMX_COLOR_Format16bitBGR565",
3566        "OMX_COLOR_Format18bitRGB666",
3567        "OMX_COLOR_Format18bitARGB1665",
3568        "OMX_COLOR_Format19bitARGB1666",
3569        "OMX_COLOR_Format24bitRGB888",
3570        "OMX_COLOR_Format24bitBGR888",
3571        "OMX_COLOR_Format24bitARGB1887",
3572        "OMX_COLOR_Format25bitARGB1888",
3573        "OMX_COLOR_Format32bitBGRA8888",
3574        "OMX_COLOR_Format32bitARGB8888",
3575        "OMX_COLOR_FormatYUV411Planar",
3576        "OMX_COLOR_FormatYUV411PackedPlanar",
3577        "OMX_COLOR_FormatYUV420Planar",
3578        "OMX_COLOR_FormatYUV420PackedPlanar",
3579        "OMX_COLOR_FormatYUV420SemiPlanar",
3580        "OMX_COLOR_FormatYUV422Planar",
3581        "OMX_COLOR_FormatYUV422PackedPlanar",
3582        "OMX_COLOR_FormatYUV422SemiPlanar",
3583        "OMX_COLOR_FormatYCbYCr",
3584        "OMX_COLOR_FormatYCrYCb",
3585        "OMX_COLOR_FormatCbYCrY",
3586        "OMX_COLOR_FormatCrYCbY",
3587        "OMX_COLOR_FormatYUV444Interleaved",
3588        "OMX_COLOR_FormatRawBayer8bit",
3589        "OMX_COLOR_FormatRawBayer10bit",
3590        "OMX_COLOR_FormatRawBayer8bitcompressed",
3591        "OMX_COLOR_FormatL2",
3592        "OMX_COLOR_FormatL4",
3593        "OMX_COLOR_FormatL8",
3594        "OMX_COLOR_FormatL16",
3595        "OMX_COLOR_FormatL24",
3596        "OMX_COLOR_FormatL32",
3597        "OMX_COLOR_FormatYUV420PackedSemiPlanar",
3598        "OMX_COLOR_FormatYUV422PackedSemiPlanar",
3599        "OMX_COLOR_Format18BitBGR666",
3600        "OMX_COLOR_Format24BitARGB6666",
3601        "OMX_COLOR_Format24BitABGR6666",
3602    };
3603
3604    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3605
3606    if (type == OMX_QCOM_COLOR_FormatYVU420SemiPlanar) {
3607        return "OMX_QCOM_COLOR_FormatYVU420SemiPlanar";
3608    } else if (type < 0 || (size_t)type >= numNames) {
3609        return "UNKNOWN";
3610    } else {
3611        return kNames[type];
3612    }
3613}
3614
3615static const char *videoCompressionFormatString(OMX_VIDEO_CODINGTYPE type) {
3616    static const char *kNames[] = {
3617        "OMX_VIDEO_CodingUnused",
3618        "OMX_VIDEO_CodingAutoDetect",
3619        "OMX_VIDEO_CodingMPEG2",
3620        "OMX_VIDEO_CodingH263",
3621        "OMX_VIDEO_CodingMPEG4",
3622        "OMX_VIDEO_CodingWMV",
3623        "OMX_VIDEO_CodingRV",
3624        "OMX_VIDEO_CodingAVC",
3625        "OMX_VIDEO_CodingMJPEG",
3626    };
3627
3628    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3629
3630    if (type < 0 || (size_t)type >= numNames) {
3631        return "UNKNOWN";
3632    } else {
3633        return kNames[type];
3634    }
3635}
3636
3637static const char *audioCodingTypeString(OMX_AUDIO_CODINGTYPE type) {
3638    static const char *kNames[] = {
3639        "OMX_AUDIO_CodingUnused",
3640        "OMX_AUDIO_CodingAutoDetect",
3641        "OMX_AUDIO_CodingPCM",
3642        "OMX_AUDIO_CodingADPCM",
3643        "OMX_AUDIO_CodingAMR",
3644        "OMX_AUDIO_CodingGSMFR",
3645        "OMX_AUDIO_CodingGSMEFR",
3646        "OMX_AUDIO_CodingGSMHR",
3647        "OMX_AUDIO_CodingPDCFR",
3648        "OMX_AUDIO_CodingPDCEFR",
3649        "OMX_AUDIO_CodingPDCHR",
3650        "OMX_AUDIO_CodingTDMAFR",
3651        "OMX_AUDIO_CodingTDMAEFR",
3652        "OMX_AUDIO_CodingQCELP8",
3653        "OMX_AUDIO_CodingQCELP13",
3654        "OMX_AUDIO_CodingEVRC",
3655        "OMX_AUDIO_CodingSMV",
3656        "OMX_AUDIO_CodingG711",
3657        "OMX_AUDIO_CodingG723",
3658        "OMX_AUDIO_CodingG726",
3659        "OMX_AUDIO_CodingG729",
3660        "OMX_AUDIO_CodingAAC",
3661        "OMX_AUDIO_CodingMP3",
3662        "OMX_AUDIO_CodingSBC",
3663        "OMX_AUDIO_CodingVORBIS",
3664        "OMX_AUDIO_CodingWMA",
3665        "OMX_AUDIO_CodingRA",
3666        "OMX_AUDIO_CodingMIDI",
3667    };
3668
3669    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3670
3671    if (type < 0 || (size_t)type >= numNames) {
3672        return "UNKNOWN";
3673    } else {
3674        return kNames[type];
3675    }
3676}
3677
3678static const char *audioPCMModeString(OMX_AUDIO_PCMMODETYPE type) {
3679    static const char *kNames[] = {
3680        "OMX_AUDIO_PCMModeLinear",
3681        "OMX_AUDIO_PCMModeALaw",
3682        "OMX_AUDIO_PCMModeMULaw",
3683    };
3684
3685    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3686
3687    if (type < 0 || (size_t)type >= numNames) {
3688        return "UNKNOWN";
3689    } else {
3690        return kNames[type];
3691    }
3692}
3693
3694static const char *amrBandModeString(OMX_AUDIO_AMRBANDMODETYPE type) {
3695    static const char *kNames[] = {
3696        "OMX_AUDIO_AMRBandModeUnused",
3697        "OMX_AUDIO_AMRBandModeNB0",
3698        "OMX_AUDIO_AMRBandModeNB1",
3699        "OMX_AUDIO_AMRBandModeNB2",
3700        "OMX_AUDIO_AMRBandModeNB3",
3701        "OMX_AUDIO_AMRBandModeNB4",
3702        "OMX_AUDIO_AMRBandModeNB5",
3703        "OMX_AUDIO_AMRBandModeNB6",
3704        "OMX_AUDIO_AMRBandModeNB7",
3705        "OMX_AUDIO_AMRBandModeWB0",
3706        "OMX_AUDIO_AMRBandModeWB1",
3707        "OMX_AUDIO_AMRBandModeWB2",
3708        "OMX_AUDIO_AMRBandModeWB3",
3709        "OMX_AUDIO_AMRBandModeWB4",
3710        "OMX_AUDIO_AMRBandModeWB5",
3711        "OMX_AUDIO_AMRBandModeWB6",
3712        "OMX_AUDIO_AMRBandModeWB7",
3713        "OMX_AUDIO_AMRBandModeWB8",
3714    };
3715
3716    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3717
3718    if (type < 0 || (size_t)type >= numNames) {
3719        return "UNKNOWN";
3720    } else {
3721        return kNames[type];
3722    }
3723}
3724
3725static const char *amrFrameFormatString(OMX_AUDIO_AMRFRAMEFORMATTYPE type) {
3726    static const char *kNames[] = {
3727        "OMX_AUDIO_AMRFrameFormatConformance",
3728        "OMX_AUDIO_AMRFrameFormatIF1",
3729        "OMX_AUDIO_AMRFrameFormatIF2",
3730        "OMX_AUDIO_AMRFrameFormatFSF",
3731        "OMX_AUDIO_AMRFrameFormatRTPPayload",
3732        "OMX_AUDIO_AMRFrameFormatITU",
3733    };
3734
3735    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3736
3737    if (type < 0 || (size_t)type >= numNames) {
3738        return "UNKNOWN";
3739    } else {
3740        return kNames[type];
3741    }
3742}
3743
3744void OMXCodec::dumpPortStatus(OMX_U32 portIndex) {
3745    OMX_PARAM_PORTDEFINITIONTYPE def;
3746    InitOMXParams(&def);
3747    def.nPortIndex = portIndex;
3748
3749    status_t err = mOMX->getParameter(
3750            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3751    CHECK_EQ(err, (status_t)OK);
3752
3753    printf("%s Port = {\n", portIndex == kPortIndexInput ? "Input" : "Output");
3754
3755    CHECK((portIndex == kPortIndexInput && def.eDir == OMX_DirInput)
3756          || (portIndex == kPortIndexOutput && def.eDir == OMX_DirOutput));
3757
3758    printf("  nBufferCountActual = %ld\n", def.nBufferCountActual);
3759    printf("  nBufferCountMin = %ld\n", def.nBufferCountMin);
3760    printf("  nBufferSize = %ld\n", def.nBufferSize);
3761
3762    switch (def.eDomain) {
3763        case OMX_PortDomainImage:
3764        {
3765            const OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3766
3767            printf("\n");
3768            printf("  // Image\n");
3769            printf("  nFrameWidth = %ld\n", imageDef->nFrameWidth);
3770            printf("  nFrameHeight = %ld\n", imageDef->nFrameHeight);
3771            printf("  nStride = %ld\n", imageDef->nStride);
3772
3773            printf("  eCompressionFormat = %s\n",
3774                   imageCompressionFormatString(imageDef->eCompressionFormat));
3775
3776            printf("  eColorFormat = %s\n",
3777                   colorFormatString(imageDef->eColorFormat));
3778
3779            break;
3780        }
3781
3782        case OMX_PortDomainVideo:
3783        {
3784            OMX_VIDEO_PORTDEFINITIONTYPE *videoDef = &def.format.video;
3785
3786            printf("\n");
3787            printf("  // Video\n");
3788            printf("  nFrameWidth = %ld\n", videoDef->nFrameWidth);
3789            printf("  nFrameHeight = %ld\n", videoDef->nFrameHeight);
3790            printf("  nStride = %ld\n", videoDef->nStride);
3791
3792            printf("  eCompressionFormat = %s\n",
3793                   videoCompressionFormatString(videoDef->eCompressionFormat));
3794
3795            printf("  eColorFormat = %s\n",
3796                   colorFormatString(videoDef->eColorFormat));
3797
3798            break;
3799        }
3800
3801        case OMX_PortDomainAudio:
3802        {
3803            OMX_AUDIO_PORTDEFINITIONTYPE *audioDef = &def.format.audio;
3804
3805            printf("\n");
3806            printf("  // Audio\n");
3807            printf("  eEncoding = %s\n",
3808                   audioCodingTypeString(audioDef->eEncoding));
3809
3810            if (audioDef->eEncoding == OMX_AUDIO_CodingPCM) {
3811                OMX_AUDIO_PARAM_PCMMODETYPE params;
3812                InitOMXParams(&params);
3813                params.nPortIndex = portIndex;
3814
3815                err = mOMX->getParameter(
3816                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
3817                CHECK_EQ(err, (status_t)OK);
3818
3819                printf("  nSamplingRate = %ld\n", params.nSamplingRate);
3820                printf("  nChannels = %ld\n", params.nChannels);
3821                printf("  bInterleaved = %d\n", params.bInterleaved);
3822                printf("  nBitPerSample = %ld\n", params.nBitPerSample);
3823
3824                printf("  eNumData = %s\n",
3825                       params.eNumData == OMX_NumericalDataSigned
3826                        ? "signed" : "unsigned");
3827
3828                printf("  ePCMMode = %s\n", audioPCMModeString(params.ePCMMode));
3829            } else if (audioDef->eEncoding == OMX_AUDIO_CodingAMR) {
3830                OMX_AUDIO_PARAM_AMRTYPE amr;
3831                InitOMXParams(&amr);
3832                amr.nPortIndex = portIndex;
3833
3834                err = mOMX->getParameter(
3835                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
3836                CHECK_EQ(err, (status_t)OK);
3837
3838                printf("  nChannels = %ld\n", amr.nChannels);
3839                printf("  eAMRBandMode = %s\n",
3840                        amrBandModeString(amr.eAMRBandMode));
3841                printf("  eAMRFrameFormat = %s\n",
3842                        amrFrameFormatString(amr.eAMRFrameFormat));
3843            }
3844
3845            break;
3846        }
3847
3848        default:
3849        {
3850            printf("  // Unknown\n");
3851            break;
3852        }
3853    }
3854
3855    printf("}\n");
3856}
3857
3858status_t OMXCodec::initNativeWindow() {
3859    // Enable use of a GraphicBuffer as the output for this node.  This must
3860    // happen before getting the IndexParamPortDefinition parameter because it
3861    // will affect the pixel format that the node reports.
3862    status_t err = mOMX->enableGraphicBuffers(mNode, kPortIndexOutput, OMX_TRUE);
3863    if (err != 0) {
3864        return err;
3865    }
3866
3867    return OK;
3868}
3869
3870void OMXCodec::initOutputFormat(const sp<MetaData> &inputFormat) {
3871    mOutputFormat = new MetaData;
3872    mOutputFormat->setCString(kKeyDecoderComponent, mComponentName);
3873    if (mIsEncoder) {
3874        int32_t timeScale;
3875        if (inputFormat->findInt32(kKeyTimeScale, &timeScale)) {
3876            mOutputFormat->setInt32(kKeyTimeScale, timeScale);
3877        }
3878    }
3879
3880    OMX_PARAM_PORTDEFINITIONTYPE def;
3881    InitOMXParams(&def);
3882    def.nPortIndex = kPortIndexOutput;
3883
3884    status_t err = mOMX->getParameter(
3885            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3886    CHECK_EQ(err, (status_t)OK);
3887
3888    switch (def.eDomain) {
3889        case OMX_PortDomainImage:
3890        {
3891            OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3892            CHECK_EQ((int)imageDef->eCompressionFormat,
3893                     (int)OMX_IMAGE_CodingUnused);
3894
3895            mOutputFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
3896            mOutputFormat->setInt32(kKeyColorFormat, imageDef->eColorFormat);
3897            mOutputFormat->setInt32(kKeyWidth, imageDef->nFrameWidth);
3898            mOutputFormat->setInt32(kKeyHeight, imageDef->nFrameHeight);
3899            break;
3900        }
3901
3902        case OMX_PortDomainAudio:
3903        {
3904            OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio;
3905
3906            if (audio_def->eEncoding == OMX_AUDIO_CodingPCM) {
3907                OMX_AUDIO_PARAM_PCMMODETYPE params;
3908                InitOMXParams(&params);
3909                params.nPortIndex = kPortIndexOutput;
3910
3911                err = mOMX->getParameter(
3912                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
3913                CHECK_EQ(err, (status_t)OK);
3914
3915                CHECK_EQ((int)params.eNumData, (int)OMX_NumericalDataSigned);
3916                CHECK_EQ(params.nBitPerSample, 16u);
3917                CHECK_EQ((int)params.ePCMMode, (int)OMX_AUDIO_PCMModeLinear);
3918
3919                int32_t numChannels, sampleRate;
3920                inputFormat->findInt32(kKeyChannelCount, &numChannels);
3921                inputFormat->findInt32(kKeySampleRate, &sampleRate);
3922
3923                if ((OMX_U32)numChannels != params.nChannels) {
3924                    LOGW("Codec outputs a different number of channels than "
3925                         "the input stream contains (contains %d channels, "
3926                         "codec outputs %ld channels).",
3927                         numChannels, params.nChannels);
3928                }
3929
3930                mOutputFormat->setCString(
3931                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
3932
3933                // Use the codec-advertised number of channels, as some
3934                // codecs appear to output stereo even if the input data is
3935                // mono. If we know the codec lies about this information,
3936                // use the actual number of channels instead.
3937                mOutputFormat->setInt32(
3938                        kKeyChannelCount,
3939                        (mQuirks & kDecoderLiesAboutNumberOfChannels)
3940                            ? numChannels : params.nChannels);
3941
3942                // The codec-reported sampleRate is not reliable...
3943                mOutputFormat->setInt32(kKeySampleRate, sampleRate);
3944            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAMR) {
3945                OMX_AUDIO_PARAM_AMRTYPE amr;
3946                InitOMXParams(&amr);
3947                amr.nPortIndex = kPortIndexOutput;
3948
3949                err = mOMX->getParameter(
3950                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
3951                CHECK_EQ(err, (status_t)OK);
3952
3953                CHECK_EQ(amr.nChannels, 1u);
3954                mOutputFormat->setInt32(kKeyChannelCount, 1);
3955
3956                if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeNB0
3957                    && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeNB7) {
3958                    mOutputFormat->setCString(
3959                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB);
3960                    mOutputFormat->setInt32(kKeySampleRate, 8000);
3961                } else if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeWB0
3962                            && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeWB8) {
3963                    mOutputFormat->setCString(
3964                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB);
3965                    mOutputFormat->setInt32(kKeySampleRate, 16000);
3966                } else {
3967                    CHECK(!"Unknown AMR band mode.");
3968                }
3969            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAAC) {
3970                mOutputFormat->setCString(
3971                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
3972                int32_t numChannels, sampleRate, bitRate;
3973                inputFormat->findInt32(kKeyChannelCount, &numChannels);
3974                inputFormat->findInt32(kKeySampleRate, &sampleRate);
3975                inputFormat->findInt32(kKeyBitRate, &bitRate);
3976                mOutputFormat->setInt32(kKeyChannelCount, numChannels);
3977                mOutputFormat->setInt32(kKeySampleRate, sampleRate);
3978                mOutputFormat->setInt32(kKeyBitRate, bitRate);
3979            } else {
3980                CHECK(!"Should not be here. Unknown audio encoding.");
3981            }
3982            break;
3983        }
3984
3985        case OMX_PortDomainVideo:
3986        {
3987            OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
3988
3989            if (video_def->eCompressionFormat == OMX_VIDEO_CodingUnused) {
3990                mOutputFormat->setCString(
3991                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
3992            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingMPEG4) {
3993                mOutputFormat->setCString(
3994                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
3995            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingH263) {
3996                mOutputFormat->setCString(
3997                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
3998            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingAVC) {
3999                mOutputFormat->setCString(
4000                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
4001            } else {
4002                CHECK(!"Unknown compression format.");
4003            }
4004
4005            mOutputFormat->setInt32(kKeyWidth, video_def->nFrameWidth);
4006            mOutputFormat->setInt32(kKeyHeight, video_def->nFrameHeight);
4007            mOutputFormat->setInt32(kKeyColorFormat, video_def->eColorFormat);
4008
4009            if (!mIsEncoder) {
4010                OMX_CONFIG_RECTTYPE rect;
4011                InitOMXParams(&rect);
4012                rect.nPortIndex = kPortIndexOutput;
4013                status_t err =
4014                        mOMX->getConfig(
4015                            mNode, OMX_IndexConfigCommonOutputCrop,
4016                            &rect, sizeof(rect));
4017
4018                if (err == OK) {
4019                    CHECK_GE(rect.nLeft, 0);
4020                    CHECK_GE(rect.nTop, 0);
4021                    CHECK_GE(rect.nWidth, 0u);
4022                    CHECK_GE(rect.nHeight, 0u);
4023                    CHECK_LE(rect.nLeft + rect.nWidth - 1, video_def->nFrameWidth);
4024                    CHECK_LE(rect.nTop + rect.nHeight - 1, video_def->nFrameHeight);
4025
4026                    mOutputFormat->setRect(
4027                            kKeyCropRect,
4028                            rect.nLeft,
4029                            rect.nTop,
4030                            rect.nLeft + rect.nWidth - 1,
4031                            rect.nTop + rect.nHeight - 1);
4032                } else {
4033                    mOutputFormat->setRect(
4034                            kKeyCropRect,
4035                            0, 0,
4036                            video_def->nFrameWidth - 1,
4037                            video_def->nFrameHeight - 1);
4038                }
4039            }
4040
4041            break;
4042        }
4043
4044        default:
4045        {
4046            CHECK(!"should not be here, neither audio nor video.");
4047            break;
4048        }
4049    }
4050}
4051
4052status_t OMXCodec::pause() {
4053    Mutex::Autolock autoLock(mLock);
4054
4055    mPaused = true;
4056
4057    return OK;
4058}
4059
4060////////////////////////////////////////////////////////////////////////////////
4061
4062status_t QueryCodecs(
4063        const sp<IOMX> &omx,
4064        const char *mime, bool queryDecoders,
4065        Vector<CodecCapabilities> *results) {
4066    results->clear();
4067
4068    for (int index = 0;; ++index) {
4069        const char *componentName;
4070
4071        if (!queryDecoders) {
4072            componentName = GetCodec(
4073                    kEncoderInfo, sizeof(kEncoderInfo) / sizeof(kEncoderInfo[0]),
4074                    mime, index);
4075        } else {
4076            componentName = GetCodec(
4077                    kDecoderInfo, sizeof(kDecoderInfo) / sizeof(kDecoderInfo[0]),
4078                    mime, index);
4079        }
4080
4081        if (!componentName) {
4082            return OK;
4083        }
4084
4085        if (strncmp(componentName, "OMX.", 4)) {
4086            // Not an OpenMax component but a software codec.
4087
4088            results->push();
4089            CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
4090            caps->mComponentName = componentName;
4091
4092            continue;
4093        }
4094
4095        sp<OMXCodecObserver> observer = new OMXCodecObserver;
4096        IOMX::node_id node;
4097        status_t err = omx->allocateNode(componentName, observer, &node);
4098
4099        if (err != OK) {
4100            continue;
4101        }
4102
4103        OMXCodec::setComponentRole(omx, node, !queryDecoders, mime);
4104
4105        results->push();
4106        CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
4107        caps->mComponentName = componentName;
4108
4109        OMX_VIDEO_PARAM_PROFILELEVELTYPE param;
4110        InitOMXParams(&param);
4111
4112        param.nPortIndex = queryDecoders ? 0 : 1;
4113
4114        for (param.nProfileIndex = 0;; ++param.nProfileIndex) {
4115            err = omx->getParameter(
4116                    node, OMX_IndexParamVideoProfileLevelQuerySupported,
4117                    &param, sizeof(param));
4118
4119            if (err != OK) {
4120                break;
4121            }
4122
4123            CodecProfileLevel profileLevel;
4124            profileLevel.mProfile = param.eProfile;
4125            profileLevel.mLevel = param.eLevel;
4126
4127            caps->mProfileLevels.push(profileLevel);
4128        }
4129
4130        // Color format query
4131        OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat;
4132        InitOMXParams(&portFormat);
4133        portFormat.nPortIndex = queryDecoders ? 1 : 0;
4134        for (portFormat.nIndex = 0;; ++portFormat.nIndex)  {
4135            err = omx->getParameter(
4136                    node, OMX_IndexParamVideoPortFormat,
4137                    &portFormat, sizeof(portFormat));
4138            if (err != OK) {
4139                break;
4140            }
4141            caps->mColorFormats.push(portFormat.eColorFormat);
4142        }
4143
4144        CHECK_EQ(omx->freeNode(node), (status_t)OK);
4145    }
4146}
4147
4148void OMXCodec::restorePatchedDataPointer(BufferInfo *info) {
4149    CHECK(mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames));
4150    CHECK(mOMXLivesLocally);
4151
4152    OMX_BUFFERHEADERTYPE *header = (OMX_BUFFERHEADERTYPE *)info->mBuffer;
4153    header->pBuffer = (OMX_U8 *)info->mData;
4154}
4155
4156}  // namespace android
4157