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