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