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