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