OMXCodec.cpp revision d20bf0676d6db8f12edcd2307f82409c076c7015
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                } else if (data2 == OMX_IndexConfigCommonScale) {
2355                    OMX_CONFIG_SCALEFACTORTYPE scale;
2356                    InitOMXParams(&scale);
2357                    scale.nPortIndex = kPortIndexOutput;
2358
2359                    // Change display dimension only when necessary.
2360                    if (OK == mOMX->getConfig(
2361                                        mNode,
2362                                        OMX_IndexConfigCommonScale,
2363                                        &scale, sizeof(scale))) {
2364                        int32_t left, top, right, bottom;
2365                        CHECK(mOutputFormat->findRect(kKeyCropRect,
2366                                                      &left, &top,
2367                                                      &right, &bottom));
2368
2369                        // The scale is in 16.16 format.
2370                        // scale 1.0 = 0x010000. When there is no
2371                        // need to change the display, skip it.
2372                        LOGV("Get OMX_IndexConfigScale: 0x%lx/0x%lx",
2373                                scale.xWidth, scale.xHeight);
2374
2375                        if (scale.xWidth != 0x010000) {
2376                            mOutputFormat->setInt32(kKeyDisplayWidth,
2377                                    ((right - left +  1) * scale.xWidth)  >> 16);
2378                            mOutputPortSettingsHaveChanged = true;
2379                        }
2380
2381                        if (scale.xHeight != 0x010000) {
2382                            mOutputFormat->setInt32(kKeyDisplayHeight,
2383                                    ((bottom  - top + 1) * scale.xHeight) >> 16);
2384                            mOutputPortSettingsHaveChanged = true;
2385                        }
2386                    }
2387                }
2388            }
2389            break;
2390        }
2391
2392#if 0
2393        case OMX_EventBufferFlag:
2394        {
2395            CODEC_LOGV("EVENT_BUFFER_FLAG(%ld)", data1);
2396
2397            if (data1 == kPortIndexOutput) {
2398                mNoMoreOutputData = true;
2399            }
2400            break;
2401        }
2402#endif
2403
2404        default:
2405        {
2406            CODEC_LOGV("EVENT(%d, %ld, %ld)", event, data1, data2);
2407            break;
2408        }
2409    }
2410}
2411
2412void OMXCodec::onCmdComplete(OMX_COMMANDTYPE cmd, OMX_U32 data) {
2413    switch (cmd) {
2414        case OMX_CommandStateSet:
2415        {
2416            onStateChange((OMX_STATETYPE)data);
2417            break;
2418        }
2419
2420        case OMX_CommandPortDisable:
2421        {
2422            OMX_U32 portIndex = data;
2423            CODEC_LOGV("PORT_DISABLED(%ld)", portIndex);
2424
2425            CHECK(mState == EXECUTING || mState == RECONFIGURING);
2426            CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLING);
2427            CHECK_EQ(mPortBuffers[portIndex].size(), 0u);
2428
2429            mPortStatus[portIndex] = DISABLED;
2430
2431            if (mState == RECONFIGURING) {
2432                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2433
2434                sp<MetaData> oldOutputFormat = mOutputFormat;
2435                initOutputFormat(mSource->getFormat());
2436
2437                // Don't notify clients if the output port settings change
2438                // wasn't of importance to them, i.e. it may be that just the
2439                // number of buffers has changed and nothing else.
2440                bool formatChanged = formatHasNotablyChanged(oldOutputFormat, mOutputFormat);
2441                if (!mOutputPortSettingsHaveChanged) {
2442                    mOutputPortSettingsHaveChanged = formatChanged;
2443                }
2444
2445                status_t err = enablePortAsync(portIndex);
2446                if (err != OK) {
2447                    CODEC_LOGE("enablePortAsync(%ld) failed (err = %d)", portIndex, err);
2448                    setState(ERROR);
2449                } else {
2450                    err = allocateBuffersOnPort(portIndex);
2451                    if (err != OK) {
2452                        CODEC_LOGE("allocateBuffersOnPort failed (err = %d)", err);
2453                        setState(ERROR);
2454                    }
2455                }
2456            }
2457            break;
2458        }
2459
2460        case OMX_CommandPortEnable:
2461        {
2462            OMX_U32 portIndex = data;
2463            CODEC_LOGV("PORT_ENABLED(%ld)", portIndex);
2464
2465            CHECK(mState == EXECUTING || mState == RECONFIGURING);
2466            CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLING);
2467
2468            mPortStatus[portIndex] = ENABLED;
2469
2470            if (mState == RECONFIGURING) {
2471                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2472
2473                setState(EXECUTING);
2474
2475                fillOutputBuffers();
2476            }
2477            break;
2478        }
2479
2480        case OMX_CommandFlush:
2481        {
2482            OMX_U32 portIndex = data;
2483
2484            CODEC_LOGV("FLUSH_DONE(%ld)", portIndex);
2485
2486            CHECK_EQ((int)mPortStatus[portIndex], (int)SHUTTING_DOWN);
2487            mPortStatus[portIndex] = ENABLED;
2488
2489            CHECK_EQ(countBuffersWeOwn(mPortBuffers[portIndex]),
2490                     mPortBuffers[portIndex].size());
2491
2492            if (mState == RECONFIGURING) {
2493                CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2494
2495                disablePortAsync(portIndex);
2496            } else if (mState == EXECUTING_TO_IDLE) {
2497                if (mPortStatus[kPortIndexInput] == ENABLED
2498                    && mPortStatus[kPortIndexOutput] == ENABLED) {
2499                    CODEC_LOGV("Finished flushing both ports, now completing "
2500                         "transition from EXECUTING to IDLE.");
2501
2502                    mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
2503                    mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
2504
2505                    status_t err =
2506                        mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
2507                    CHECK_EQ(err, (status_t)OK);
2508                }
2509            } else {
2510                // We're flushing both ports in preparation for seeking.
2511
2512                if (mPortStatus[kPortIndexInput] == ENABLED
2513                    && mPortStatus[kPortIndexOutput] == ENABLED) {
2514                    CODEC_LOGV("Finished flushing both ports, now continuing from"
2515                         " seek-time.");
2516
2517                    // We implicitly resume pulling on our upstream source.
2518                    mPaused = false;
2519
2520                    drainInputBuffers();
2521                    fillOutputBuffers();
2522                }
2523
2524                if (mOutputPortSettingsChangedPending) {
2525                    CODEC_LOGV(
2526                            "Honoring deferred output port settings change.");
2527
2528                    mOutputPortSettingsChangedPending = false;
2529                    onPortSettingsChanged(kPortIndexOutput);
2530                }
2531            }
2532
2533            break;
2534        }
2535
2536        default:
2537        {
2538            CODEC_LOGV("CMD_COMPLETE(%d, %ld)", cmd, data);
2539            break;
2540        }
2541    }
2542}
2543
2544void OMXCodec::onStateChange(OMX_STATETYPE newState) {
2545    CODEC_LOGV("onStateChange %d", newState);
2546
2547    switch (newState) {
2548        case OMX_StateIdle:
2549        {
2550            CODEC_LOGV("Now Idle.");
2551            if (mState == LOADED_TO_IDLE) {
2552                status_t err = mOMX->sendCommand(
2553                        mNode, OMX_CommandStateSet, OMX_StateExecuting);
2554
2555                CHECK_EQ(err, (status_t)OK);
2556
2557                setState(IDLE_TO_EXECUTING);
2558            } else {
2559                CHECK_EQ((int)mState, (int)EXECUTING_TO_IDLE);
2560
2561                CHECK_EQ(
2562                    countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
2563                    mPortBuffers[kPortIndexInput].size());
2564
2565                CHECK_EQ(
2566                    countBuffersWeOwn(mPortBuffers[kPortIndexOutput]),
2567                    mPortBuffers[kPortIndexOutput].size());
2568
2569                status_t err = mOMX->sendCommand(
2570                        mNode, OMX_CommandStateSet, OMX_StateLoaded);
2571
2572                CHECK_EQ(err, (status_t)OK);
2573
2574                err = freeBuffersOnPort(kPortIndexInput);
2575                CHECK_EQ(err, (status_t)OK);
2576
2577                err = freeBuffersOnPort(kPortIndexOutput);
2578                CHECK_EQ(err, (status_t)OK);
2579
2580                mPortStatus[kPortIndexInput] = ENABLED;
2581                mPortStatus[kPortIndexOutput] = ENABLED;
2582
2583                setState(IDLE_TO_LOADED);
2584            }
2585            break;
2586        }
2587
2588        case OMX_StateExecuting:
2589        {
2590            CHECK_EQ((int)mState, (int)IDLE_TO_EXECUTING);
2591
2592            CODEC_LOGV("Now Executing.");
2593
2594            mOutputPortSettingsChangedPending = false;
2595
2596            setState(EXECUTING);
2597
2598            // Buffers will be submitted to the component in the first
2599            // call to OMXCodec::read as mInitialBufferSubmit is true at
2600            // this point. This ensures that this on_message call returns,
2601            // releases the lock and ::init can notice the state change and
2602            // itself return.
2603            break;
2604        }
2605
2606        case OMX_StateLoaded:
2607        {
2608            CHECK_EQ((int)mState, (int)IDLE_TO_LOADED);
2609
2610            CODEC_LOGV("Now Loaded.");
2611
2612            setState(LOADED);
2613            break;
2614        }
2615
2616        case OMX_StateInvalid:
2617        {
2618            setState(ERROR);
2619            break;
2620        }
2621
2622        default:
2623        {
2624            CHECK(!"should not be here.");
2625            break;
2626        }
2627    }
2628}
2629
2630// static
2631size_t OMXCodec::countBuffersWeOwn(const Vector<BufferInfo> &buffers) {
2632    size_t n = 0;
2633    for (size_t i = 0; i < buffers.size(); ++i) {
2634        if (buffers[i].mStatus != OWNED_BY_COMPONENT) {
2635            ++n;
2636        }
2637    }
2638
2639    return n;
2640}
2641
2642status_t OMXCodec::freeBuffersOnPort(
2643        OMX_U32 portIndex, bool onlyThoseWeOwn) {
2644    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
2645
2646    status_t stickyErr = OK;
2647
2648    for (size_t i = buffers->size(); i-- > 0;) {
2649        BufferInfo *info = &buffers->editItemAt(i);
2650
2651        if (onlyThoseWeOwn && info->mStatus == OWNED_BY_COMPONENT) {
2652            continue;
2653        }
2654
2655        CHECK(info->mStatus == OWNED_BY_US
2656                || info->mStatus == OWNED_BY_NATIVE_WINDOW);
2657
2658        CODEC_LOGV("freeing buffer %p on port %ld", info->mBuffer, portIndex);
2659
2660        status_t err = freeBuffer(portIndex, i);
2661
2662        if (err != OK) {
2663            stickyErr = err;
2664        }
2665
2666    }
2667
2668    CHECK(onlyThoseWeOwn || buffers->isEmpty());
2669
2670    return stickyErr;
2671}
2672
2673status_t OMXCodec::freeBuffer(OMX_U32 portIndex, size_t bufIndex) {
2674    Vector<BufferInfo> *buffers = &mPortBuffers[portIndex];
2675
2676    BufferInfo *info = &buffers->editItemAt(bufIndex);
2677
2678    status_t err = mOMX->freeBuffer(mNode, portIndex, info->mBuffer);
2679
2680    if (err == OK && info->mMediaBuffer != NULL) {
2681        CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2682        info->mMediaBuffer->setObserver(NULL);
2683
2684        // Make sure nobody but us owns this buffer at this point.
2685        CHECK_EQ(info->mMediaBuffer->refcount(), 0);
2686
2687        // Cancel the buffer if it belongs to an ANativeWindow.
2688        sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer();
2689        if (info->mStatus == OWNED_BY_US && graphicBuffer != 0) {
2690            err = cancelBufferToNativeWindow(info);
2691        }
2692
2693        info->mMediaBuffer->release();
2694        info->mMediaBuffer = NULL;
2695    }
2696
2697    if (err == OK) {
2698        buffers->removeAt(bufIndex);
2699    }
2700
2701    return err;
2702}
2703
2704void OMXCodec::onPortSettingsChanged(OMX_U32 portIndex) {
2705    CODEC_LOGV("PORT_SETTINGS_CHANGED(%ld)", portIndex);
2706
2707    CHECK_EQ((int)mState, (int)EXECUTING);
2708    CHECK_EQ(portIndex, (OMX_U32)kPortIndexOutput);
2709    CHECK(!mOutputPortSettingsChangedPending);
2710
2711    if (mPortStatus[kPortIndexOutput] != ENABLED) {
2712        CODEC_LOGV("Deferring output port settings change.");
2713        mOutputPortSettingsChangedPending = true;
2714        return;
2715    }
2716
2717    setState(RECONFIGURING);
2718
2719    if (mQuirks & kNeedsFlushBeforeDisable) {
2720        if (!flushPortAsync(portIndex)) {
2721            onCmdComplete(OMX_CommandFlush, portIndex);
2722        }
2723    } else {
2724        disablePortAsync(portIndex);
2725    }
2726}
2727
2728bool OMXCodec::flushPortAsync(OMX_U32 portIndex) {
2729    CHECK(mState == EXECUTING || mState == RECONFIGURING
2730            || mState == EXECUTING_TO_IDLE);
2731
2732    CODEC_LOGV("flushPortAsync(%ld): we own %d out of %d buffers already.",
2733         portIndex, countBuffersWeOwn(mPortBuffers[portIndex]),
2734         mPortBuffers[portIndex].size());
2735
2736    CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED);
2737    mPortStatus[portIndex] = SHUTTING_DOWN;
2738
2739    if ((mQuirks & kRequiresFlushCompleteEmulation)
2740        && countBuffersWeOwn(mPortBuffers[portIndex])
2741                == mPortBuffers[portIndex].size()) {
2742        // No flush is necessary and this component fails to send a
2743        // flush-complete event in this case.
2744
2745        return false;
2746    }
2747
2748    status_t err =
2749        mOMX->sendCommand(mNode, OMX_CommandFlush, portIndex);
2750    CHECK_EQ(err, (status_t)OK);
2751
2752    return true;
2753}
2754
2755void OMXCodec::disablePortAsync(OMX_U32 portIndex) {
2756    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2757
2758    CHECK_EQ((int)mPortStatus[portIndex], (int)ENABLED);
2759    mPortStatus[portIndex] = DISABLING;
2760
2761    CODEC_LOGV("sending OMX_CommandPortDisable(%ld)", portIndex);
2762    status_t err =
2763        mOMX->sendCommand(mNode, OMX_CommandPortDisable, portIndex);
2764    CHECK_EQ(err, (status_t)OK);
2765
2766    freeBuffersOnPort(portIndex, true);
2767}
2768
2769status_t OMXCodec::enablePortAsync(OMX_U32 portIndex) {
2770    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2771
2772    CHECK_EQ((int)mPortStatus[portIndex], (int)DISABLED);
2773    mPortStatus[portIndex] = ENABLING;
2774
2775    CODEC_LOGV("sending OMX_CommandPortEnable(%ld)", portIndex);
2776    return mOMX->sendCommand(mNode, OMX_CommandPortEnable, portIndex);
2777}
2778
2779void OMXCodec::fillOutputBuffers() {
2780    CHECK_EQ((int)mState, (int)EXECUTING);
2781
2782    // This is a workaround for some decoders not properly reporting
2783    // end-of-output-stream. If we own all input buffers and also own
2784    // all output buffers and we already signalled end-of-input-stream,
2785    // the end-of-output-stream is implied.
2786    if (mSignalledEOS
2787            && countBuffersWeOwn(mPortBuffers[kPortIndexInput])
2788                == mPortBuffers[kPortIndexInput].size()
2789            && countBuffersWeOwn(mPortBuffers[kPortIndexOutput])
2790                == mPortBuffers[kPortIndexOutput].size()) {
2791        mNoMoreOutputData = true;
2792        mBufferFilled.signal();
2793
2794        return;
2795    }
2796
2797    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
2798    for (size_t i = 0; i < buffers->size(); ++i) {
2799        BufferInfo *info = &buffers->editItemAt(i);
2800        if (info->mStatus == OWNED_BY_US) {
2801            fillOutputBuffer(&buffers->editItemAt(i));
2802        }
2803    }
2804}
2805
2806void OMXCodec::drainInputBuffers() {
2807    CHECK(mState == EXECUTING || mState == RECONFIGURING);
2808
2809    if (mFlags & kUseSecureInputBuffers) {
2810        Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2811        for (size_t i = 0; i < buffers->size(); ++i) {
2812            if (!drainAnyInputBuffer()
2813                    || (mFlags & kOnlySubmitOneInputBufferAtOneTime)) {
2814                break;
2815            }
2816        }
2817    } else {
2818        Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
2819        for (size_t i = 0; i < buffers->size(); ++i) {
2820            BufferInfo *info = &buffers->editItemAt(i);
2821
2822            if (info->mStatus != OWNED_BY_US) {
2823                continue;
2824            }
2825
2826            if (!drainInputBuffer(info)) {
2827                break;
2828            }
2829
2830            if (mFlags & kOnlySubmitOneInputBufferAtOneTime) {
2831                break;
2832            }
2833        }
2834    }
2835}
2836
2837bool OMXCodec::drainAnyInputBuffer() {
2838    return drainInputBuffer((BufferInfo *)NULL);
2839}
2840
2841OMXCodec::BufferInfo *OMXCodec::findInputBufferByDataPointer(void *ptr) {
2842    Vector<BufferInfo> *infos = &mPortBuffers[kPortIndexInput];
2843    for (size_t i = 0; i < infos->size(); ++i) {
2844        BufferInfo *info = &infos->editItemAt(i);
2845
2846        if (info->mData == ptr) {
2847            CODEC_LOGV(
2848                    "input buffer data ptr = %p, buffer_id = %p",
2849                    ptr,
2850                    info->mBuffer);
2851
2852            return info;
2853        }
2854    }
2855
2856    TRESPASS();
2857}
2858
2859OMXCodec::BufferInfo *OMXCodec::findEmptyInputBuffer() {
2860    Vector<BufferInfo> *infos = &mPortBuffers[kPortIndexInput];
2861    for (size_t i = 0; i < infos->size(); ++i) {
2862        BufferInfo *info = &infos->editItemAt(i);
2863
2864        if (info->mStatus == OWNED_BY_US) {
2865            return info;
2866        }
2867    }
2868
2869    TRESPASS();
2870}
2871
2872bool OMXCodec::drainInputBuffer(BufferInfo *info) {
2873    if (info != NULL) {
2874        CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
2875    }
2876
2877    if (mSignalledEOS) {
2878        return false;
2879    }
2880
2881    if (mCodecSpecificDataIndex < mCodecSpecificData.size()) {
2882        CHECK(!(mFlags & kUseSecureInputBuffers));
2883
2884        const CodecSpecificData *specific =
2885            mCodecSpecificData[mCodecSpecificDataIndex];
2886
2887        size_t size = specific->mSize;
2888
2889        if (!strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mMIME)
2890                && !(mQuirks & kWantsNALFragments)) {
2891            static const uint8_t kNALStartCode[4] =
2892                    { 0x00, 0x00, 0x00, 0x01 };
2893
2894            CHECK(info->mSize >= specific->mSize + 4);
2895
2896            size += 4;
2897
2898            memcpy(info->mData, kNALStartCode, 4);
2899            memcpy((uint8_t *)info->mData + 4,
2900                   specific->mData, specific->mSize);
2901        } else {
2902            CHECK(info->mSize >= specific->mSize);
2903            memcpy(info->mData, specific->mData, specific->mSize);
2904        }
2905
2906        mNoMoreOutputData = false;
2907
2908        CODEC_LOGV("calling emptyBuffer with codec specific data");
2909
2910        status_t err = mOMX->emptyBuffer(
2911                mNode, info->mBuffer, 0, size,
2912                OMX_BUFFERFLAG_ENDOFFRAME | OMX_BUFFERFLAG_CODECCONFIG,
2913                0);
2914        CHECK_EQ(err, (status_t)OK);
2915
2916        info->mStatus = OWNED_BY_COMPONENT;
2917
2918        ++mCodecSpecificDataIndex;
2919        return true;
2920    }
2921
2922    if (mPaused) {
2923        return false;
2924    }
2925
2926    status_t err;
2927
2928    bool signalEOS = false;
2929    int64_t timestampUs = 0;
2930
2931    size_t offset = 0;
2932    int32_t n = 0;
2933
2934
2935    for (;;) {
2936        MediaBuffer *srcBuffer;
2937        if (mSeekTimeUs >= 0) {
2938            if (mLeftOverBuffer) {
2939                mLeftOverBuffer->release();
2940                mLeftOverBuffer = NULL;
2941            }
2942
2943            MediaSource::ReadOptions options;
2944            options.setSeekTo(mSeekTimeUs, mSeekMode);
2945
2946            mSeekTimeUs = -1;
2947            mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC;
2948            mBufferFilled.signal();
2949
2950            err = mSource->read(&srcBuffer, &options);
2951
2952            if (err == OK) {
2953                int64_t targetTimeUs;
2954                if (srcBuffer->meta_data()->findInt64(
2955                            kKeyTargetTime, &targetTimeUs)
2956                        && targetTimeUs >= 0) {
2957                    CODEC_LOGV("targetTimeUs = %lld us", targetTimeUs);
2958                    mTargetTimeUs = targetTimeUs;
2959                } else {
2960                    mTargetTimeUs = -1;
2961                }
2962            }
2963        } else if (mLeftOverBuffer) {
2964            srcBuffer = mLeftOverBuffer;
2965            mLeftOverBuffer = NULL;
2966
2967            err = OK;
2968        } else {
2969            err = mSource->read(&srcBuffer);
2970        }
2971
2972        if (err != OK) {
2973            signalEOS = true;
2974            mFinalStatus = err;
2975            mSignalledEOS = true;
2976            mBufferFilled.signal();
2977            break;
2978        }
2979
2980        if (mFlags & kUseSecureInputBuffers) {
2981            info = findInputBufferByDataPointer(srcBuffer->data());
2982            CHECK(info != NULL);
2983        }
2984
2985        size_t remainingBytes = info->mSize - offset;
2986
2987        if (srcBuffer->range_length() > remainingBytes) {
2988            if (offset == 0) {
2989                CODEC_LOGE(
2990                     "Codec's input buffers are too small to accomodate "
2991                     "buffer read from source (info->mSize = %d, srcLength = %d)",
2992                     info->mSize, srcBuffer->range_length());
2993
2994                srcBuffer->release();
2995                srcBuffer = NULL;
2996
2997                setState(ERROR);
2998                return false;
2999            }
3000
3001            mLeftOverBuffer = srcBuffer;
3002            break;
3003        }
3004
3005        bool releaseBuffer = true;
3006        if (mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames)) {
3007            CHECK(mOMXLivesLocally && offset == 0);
3008
3009            OMX_BUFFERHEADERTYPE *header =
3010                (OMX_BUFFERHEADERTYPE *)info->mBuffer;
3011
3012            CHECK(header->pBuffer == info->mData);
3013
3014            header->pBuffer =
3015                (OMX_U8 *)srcBuffer->data() + srcBuffer->range_offset();
3016
3017            releaseBuffer = false;
3018            info->mMediaBuffer = srcBuffer;
3019        } else {
3020            if (mFlags & kStoreMetaDataInVideoBuffers) {
3021                releaseBuffer = false;
3022                info->mMediaBuffer = srcBuffer;
3023            }
3024
3025            if (mFlags & kUseSecureInputBuffers) {
3026                // Data in "info" is already provided at this time.
3027
3028                releaseBuffer = false;
3029
3030                CHECK(info->mMediaBuffer == NULL);
3031                info->mMediaBuffer = srcBuffer;
3032            } else {
3033                CHECK(srcBuffer->data() != NULL) ;
3034                memcpy((uint8_t *)info->mData + offset,
3035                        (const uint8_t *)srcBuffer->data()
3036                            + srcBuffer->range_offset(),
3037                        srcBuffer->range_length());
3038            }
3039        }
3040
3041        int64_t lastBufferTimeUs;
3042        CHECK(srcBuffer->meta_data()->findInt64(kKeyTime, &lastBufferTimeUs));
3043        CHECK(lastBufferTimeUs >= 0);
3044        if (mIsEncoder) {
3045            mDecodingTimeList.push_back(lastBufferTimeUs);
3046        }
3047
3048        if (offset == 0) {
3049            timestampUs = lastBufferTimeUs;
3050        }
3051
3052        offset += srcBuffer->range_length();
3053
3054        if (!strcasecmp(MEDIA_MIMETYPE_AUDIO_VORBIS, mMIME)) {
3055            CHECK(!(mQuirks & kSupportsMultipleFramesPerInputBuffer));
3056            CHECK_GE(info->mSize, offset + sizeof(int32_t));
3057
3058            int32_t numPageSamples;
3059            if (!srcBuffer->meta_data()->findInt32(
3060                        kKeyValidSamples, &numPageSamples)) {
3061                numPageSamples = -1;
3062            }
3063
3064            memcpy((uint8_t *)info->mData + offset,
3065                   &numPageSamples,
3066                   sizeof(numPageSamples));
3067
3068            offset += sizeof(numPageSamples);
3069        }
3070
3071        if (releaseBuffer) {
3072            srcBuffer->release();
3073            srcBuffer = NULL;
3074        }
3075
3076        ++n;
3077
3078        if (!(mQuirks & kSupportsMultipleFramesPerInputBuffer)) {
3079            break;
3080        }
3081
3082        int64_t coalescedDurationUs = lastBufferTimeUs - timestampUs;
3083
3084        if (coalescedDurationUs > 250000ll) {
3085            // Don't coalesce more than 250ms worth of encoded data at once.
3086            break;
3087        }
3088    }
3089
3090    if (n > 1) {
3091        LOGV("coalesced %d frames into one input buffer", n);
3092    }
3093
3094    OMX_U32 flags = OMX_BUFFERFLAG_ENDOFFRAME;
3095
3096    if (signalEOS) {
3097        flags |= OMX_BUFFERFLAG_EOS;
3098    } else {
3099        mNoMoreOutputData = false;
3100    }
3101
3102    CODEC_LOGV("Calling emptyBuffer on buffer %p (length %d), "
3103               "timestamp %lld us (%.2f secs)",
3104               info->mBuffer, offset,
3105               timestampUs, timestampUs / 1E6);
3106
3107    if (info == NULL) {
3108        CHECK(mFlags & kUseSecureInputBuffers);
3109        CHECK(signalEOS);
3110
3111        // This is fishy, there's still a MediaBuffer corresponding to this
3112        // info available to the source at this point even though we're going
3113        // to use it to signal EOS to the codec.
3114        info = findEmptyInputBuffer();
3115    }
3116
3117    err = mOMX->emptyBuffer(
3118            mNode, info->mBuffer, 0, offset,
3119            flags, timestampUs);
3120
3121    if (err != OK) {
3122        setState(ERROR);
3123        return false;
3124    }
3125
3126    info->mStatus = OWNED_BY_COMPONENT;
3127
3128    // This component does not ever signal the EOS flag on output buffers,
3129    // Thanks for nothing.
3130    if (mSignalledEOS && !strcmp(mComponentName, "OMX.TI.Video.encoder")) {
3131        mNoMoreOutputData = true;
3132        mBufferFilled.signal();
3133    }
3134
3135    return true;
3136}
3137
3138void OMXCodec::fillOutputBuffer(BufferInfo *info) {
3139    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
3140
3141    if (mNoMoreOutputData) {
3142        CODEC_LOGV("There is no more output data available, not "
3143             "calling fillOutputBuffer");
3144        return;
3145    }
3146
3147    if (info->mMediaBuffer != NULL) {
3148        sp<GraphicBuffer> graphicBuffer = info->mMediaBuffer->graphicBuffer();
3149        if (graphicBuffer != 0) {
3150            // When using a native buffer we need to lock the buffer before
3151            // giving it to OMX.
3152            CODEC_LOGV("Calling lockBuffer on %p", info->mBuffer);
3153            int err = mNativeWindow->lockBuffer(mNativeWindow.get(),
3154                    graphicBuffer.get());
3155            if (err != 0) {
3156                CODEC_LOGE("lockBuffer failed w/ error 0x%08x", err);
3157
3158                setState(ERROR);
3159                return;
3160            }
3161        }
3162    }
3163
3164    CODEC_LOGV("Calling fillBuffer on buffer %p", info->mBuffer);
3165    status_t err = mOMX->fillBuffer(mNode, info->mBuffer);
3166
3167    if (err != OK) {
3168        CODEC_LOGE("fillBuffer failed w/ error 0x%08x", err);
3169
3170        setState(ERROR);
3171        return;
3172    }
3173
3174    info->mStatus = OWNED_BY_COMPONENT;
3175}
3176
3177bool OMXCodec::drainInputBuffer(IOMX::buffer_id buffer) {
3178    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexInput];
3179    for (size_t i = 0; i < buffers->size(); ++i) {
3180        if ((*buffers)[i].mBuffer == buffer) {
3181            return drainInputBuffer(&buffers->editItemAt(i));
3182        }
3183    }
3184
3185    CHECK(!"should not be here.");
3186
3187    return false;
3188}
3189
3190void OMXCodec::fillOutputBuffer(IOMX::buffer_id buffer) {
3191    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
3192    for (size_t i = 0; i < buffers->size(); ++i) {
3193        if ((*buffers)[i].mBuffer == buffer) {
3194            fillOutputBuffer(&buffers->editItemAt(i));
3195            return;
3196        }
3197    }
3198
3199    CHECK(!"should not be here.");
3200}
3201
3202void OMXCodec::setState(State newState) {
3203    mState = newState;
3204    mAsyncCompletion.signal();
3205
3206    // This may cause some spurious wakeups but is necessary to
3207    // unblock the reader if we enter ERROR state.
3208    mBufferFilled.signal();
3209}
3210
3211status_t OMXCodec::waitForBufferFilled_l() {
3212
3213    if (mIsEncoder) {
3214        // For timelapse video recording, the timelapse video recording may
3215        // not send an input frame for a _long_ time. Do not use timeout
3216        // for video encoding.
3217        return mBufferFilled.wait(mLock);
3218    }
3219    status_t err = mBufferFilled.waitRelative(mLock, kBufferFilledEventTimeOutNs);
3220    if (err != OK) {
3221        CODEC_LOGE("Timed out waiting for output buffers: %d/%d",
3222            countBuffersWeOwn(mPortBuffers[kPortIndexInput]),
3223            countBuffersWeOwn(mPortBuffers[kPortIndexOutput]));
3224    }
3225    return err;
3226}
3227
3228void OMXCodec::setRawAudioFormat(
3229        OMX_U32 portIndex, int32_t sampleRate, int32_t numChannels) {
3230
3231    // port definition
3232    OMX_PARAM_PORTDEFINITIONTYPE def;
3233    InitOMXParams(&def);
3234    def.nPortIndex = portIndex;
3235    status_t err = mOMX->getParameter(
3236            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3237    CHECK_EQ(err, (status_t)OK);
3238    def.format.audio.eEncoding = OMX_AUDIO_CodingPCM;
3239    CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition,
3240            &def, sizeof(def)), (status_t)OK);
3241
3242    // pcm param
3243    OMX_AUDIO_PARAM_PCMMODETYPE pcmParams;
3244    InitOMXParams(&pcmParams);
3245    pcmParams.nPortIndex = portIndex;
3246
3247    err = mOMX->getParameter(
3248            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
3249
3250    CHECK_EQ(err, (status_t)OK);
3251
3252    pcmParams.nChannels = numChannels;
3253    pcmParams.eNumData = OMX_NumericalDataSigned;
3254    pcmParams.bInterleaved = OMX_TRUE;
3255    pcmParams.nBitPerSample = 16;
3256    pcmParams.nSamplingRate = sampleRate;
3257    pcmParams.ePCMMode = OMX_AUDIO_PCMModeLinear;
3258
3259    if (numChannels == 1) {
3260        pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelCF;
3261    } else {
3262        CHECK_EQ(numChannels, 2);
3263
3264        pcmParams.eChannelMapping[0] = OMX_AUDIO_ChannelLF;
3265        pcmParams.eChannelMapping[1] = OMX_AUDIO_ChannelRF;
3266    }
3267
3268    err = mOMX->setParameter(
3269            mNode, OMX_IndexParamAudioPcm, &pcmParams, sizeof(pcmParams));
3270
3271    CHECK_EQ(err, (status_t)OK);
3272}
3273
3274static OMX_AUDIO_AMRBANDMODETYPE pickModeFromBitRate(bool isAMRWB, int32_t bps) {
3275    if (isAMRWB) {
3276        if (bps <= 6600) {
3277            return OMX_AUDIO_AMRBandModeWB0;
3278        } else if (bps <= 8850) {
3279            return OMX_AUDIO_AMRBandModeWB1;
3280        } else if (bps <= 12650) {
3281            return OMX_AUDIO_AMRBandModeWB2;
3282        } else if (bps <= 14250) {
3283            return OMX_AUDIO_AMRBandModeWB3;
3284        } else if (bps <= 15850) {
3285            return OMX_AUDIO_AMRBandModeWB4;
3286        } else if (bps <= 18250) {
3287            return OMX_AUDIO_AMRBandModeWB5;
3288        } else if (bps <= 19850) {
3289            return OMX_AUDIO_AMRBandModeWB6;
3290        } else if (bps <= 23050) {
3291            return OMX_AUDIO_AMRBandModeWB7;
3292        }
3293
3294        // 23850 bps
3295        return OMX_AUDIO_AMRBandModeWB8;
3296    } else {  // AMRNB
3297        if (bps <= 4750) {
3298            return OMX_AUDIO_AMRBandModeNB0;
3299        } else if (bps <= 5150) {
3300            return OMX_AUDIO_AMRBandModeNB1;
3301        } else if (bps <= 5900) {
3302            return OMX_AUDIO_AMRBandModeNB2;
3303        } else if (bps <= 6700) {
3304            return OMX_AUDIO_AMRBandModeNB3;
3305        } else if (bps <= 7400) {
3306            return OMX_AUDIO_AMRBandModeNB4;
3307        } else if (bps <= 7950) {
3308            return OMX_AUDIO_AMRBandModeNB5;
3309        } else if (bps <= 10200) {
3310            return OMX_AUDIO_AMRBandModeNB6;
3311        }
3312
3313        // 12200 bps
3314        return OMX_AUDIO_AMRBandModeNB7;
3315    }
3316}
3317
3318void OMXCodec::setAMRFormat(bool isWAMR, int32_t bitRate) {
3319    OMX_U32 portIndex = mIsEncoder ? kPortIndexOutput : kPortIndexInput;
3320
3321    OMX_AUDIO_PARAM_AMRTYPE def;
3322    InitOMXParams(&def);
3323    def.nPortIndex = portIndex;
3324
3325    status_t err =
3326        mOMX->getParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
3327
3328    CHECK_EQ(err, (status_t)OK);
3329
3330    def.eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF;
3331
3332    def.eAMRBandMode = pickModeFromBitRate(isWAMR, bitRate);
3333    err = mOMX->setParameter(mNode, OMX_IndexParamAudioAmr, &def, sizeof(def));
3334    CHECK_EQ(err, (status_t)OK);
3335
3336    ////////////////////////
3337
3338    if (mIsEncoder) {
3339        sp<MetaData> format = mSource->getFormat();
3340        int32_t sampleRate;
3341        int32_t numChannels;
3342        CHECK(format->findInt32(kKeySampleRate, &sampleRate));
3343        CHECK(format->findInt32(kKeyChannelCount, &numChannels));
3344
3345        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
3346    }
3347}
3348
3349status_t OMXCodec::setAACFormat(int32_t numChannels, int32_t sampleRate, int32_t bitRate) {
3350    if (numChannels > 2)
3351        LOGW("Number of channels: (%d) \n", numChannels);
3352
3353    if (mIsEncoder) {
3354        //////////////// input port ////////////////////
3355        setRawAudioFormat(kPortIndexInput, sampleRate, numChannels);
3356
3357        //////////////// output port ////////////////////
3358        // format
3359        OMX_AUDIO_PARAM_PORTFORMATTYPE format;
3360        format.nPortIndex = kPortIndexOutput;
3361        format.nIndex = 0;
3362        status_t err = OMX_ErrorNone;
3363        while (OMX_ErrorNone == err) {
3364            CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioPortFormat,
3365                    &format, sizeof(format)), (status_t)OK);
3366            if (format.eEncoding == OMX_AUDIO_CodingAAC) {
3367                break;
3368            }
3369            format.nIndex++;
3370        }
3371        CHECK_EQ((status_t)OK, err);
3372        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamAudioPortFormat,
3373                &format, sizeof(format)), (status_t)OK);
3374
3375        // port definition
3376        OMX_PARAM_PORTDEFINITIONTYPE def;
3377        InitOMXParams(&def);
3378        def.nPortIndex = kPortIndexOutput;
3379        CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamPortDefinition,
3380                &def, sizeof(def)), (status_t)OK);
3381        def.format.audio.bFlagErrorConcealment = OMX_TRUE;
3382        def.format.audio.eEncoding = OMX_AUDIO_CodingAAC;
3383        CHECK_EQ(mOMX->setParameter(mNode, OMX_IndexParamPortDefinition,
3384                &def, sizeof(def)), (status_t)OK);
3385
3386        // profile
3387        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
3388        InitOMXParams(&profile);
3389        profile.nPortIndex = kPortIndexOutput;
3390        CHECK_EQ(mOMX->getParameter(mNode, OMX_IndexParamAudioAac,
3391                &profile, sizeof(profile)), (status_t)OK);
3392        profile.nChannels = numChannels;
3393        profile.eChannelMode = (numChannels == 1?
3394                OMX_AUDIO_ChannelModeMono: OMX_AUDIO_ChannelModeStereo);
3395        profile.nSampleRate = sampleRate;
3396        profile.nBitRate = bitRate;
3397        profile.nAudioBandWidth = 0;
3398        profile.nFrameLength = 0;
3399        profile.nAACtools = OMX_AUDIO_AACToolAll;
3400        profile.nAACERtools = OMX_AUDIO_AACERNone;
3401        profile.eAACProfile = OMX_AUDIO_AACObjectLC;
3402        profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4FF;
3403        err = mOMX->setParameter(mNode, OMX_IndexParamAudioAac,
3404                &profile, sizeof(profile));
3405
3406        if (err != OK) {
3407            CODEC_LOGE("setParameter('OMX_IndexParamAudioAac') failed (err = %d)", err);
3408            return err;
3409        }
3410    } else {
3411        OMX_AUDIO_PARAM_AACPROFILETYPE profile;
3412        InitOMXParams(&profile);
3413        profile.nPortIndex = kPortIndexInput;
3414
3415        status_t err = mOMX->getParameter(
3416                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
3417        CHECK_EQ(err, (status_t)OK);
3418
3419        profile.nChannels = numChannels;
3420        profile.nSampleRate = sampleRate;
3421        profile.eAACStreamFormat = OMX_AUDIO_AACStreamFormatMP4ADTS;
3422
3423        err = mOMX->setParameter(
3424                mNode, OMX_IndexParamAudioAac, &profile, sizeof(profile));
3425
3426        if (err != OK) {
3427            CODEC_LOGE("setParameter('OMX_IndexParamAudioAac') failed (err = %d)", err);
3428            return err;
3429        }
3430    }
3431
3432    return OK;
3433}
3434
3435void OMXCodec::setG711Format(int32_t numChannels) {
3436    CHECK(!mIsEncoder);
3437    setRawAudioFormat(kPortIndexInput, 8000, numChannels);
3438}
3439
3440void OMXCodec::setImageOutputFormat(
3441        OMX_COLOR_FORMATTYPE format, OMX_U32 width, OMX_U32 height) {
3442    CODEC_LOGV("setImageOutputFormat(%ld, %ld)", width, height);
3443
3444#if 0
3445    OMX_INDEXTYPE index;
3446    status_t err = mOMX->get_extension_index(
3447            mNode, "OMX.TI.JPEG.decode.Config.OutputColorFormat", &index);
3448    CHECK_EQ(err, (status_t)OK);
3449
3450    err = mOMX->set_config(mNode, index, &format, sizeof(format));
3451    CHECK_EQ(err, (status_t)OK);
3452#endif
3453
3454    OMX_PARAM_PORTDEFINITIONTYPE def;
3455    InitOMXParams(&def);
3456    def.nPortIndex = kPortIndexOutput;
3457
3458    status_t err = mOMX->getParameter(
3459            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3460    CHECK_EQ(err, (status_t)OK);
3461
3462    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage);
3463
3464    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3465
3466    CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingUnused);
3467    imageDef->eColorFormat = format;
3468    imageDef->nFrameWidth = width;
3469    imageDef->nFrameHeight = height;
3470
3471    switch (format) {
3472        case OMX_COLOR_FormatYUV420PackedPlanar:
3473        case OMX_COLOR_FormatYUV411Planar:
3474        {
3475            def.nBufferSize = (width * height * 3) / 2;
3476            break;
3477        }
3478
3479        case OMX_COLOR_FormatCbYCrY:
3480        {
3481            def.nBufferSize = width * height * 2;
3482            break;
3483        }
3484
3485        case OMX_COLOR_Format32bitARGB8888:
3486        {
3487            def.nBufferSize = width * height * 4;
3488            break;
3489        }
3490
3491        case OMX_COLOR_Format16bitARGB4444:
3492        case OMX_COLOR_Format16bitARGB1555:
3493        case OMX_COLOR_Format16bitRGB565:
3494        case OMX_COLOR_Format16bitBGR565:
3495        {
3496            def.nBufferSize = width * height * 2;
3497            break;
3498        }
3499
3500        default:
3501            CHECK(!"Should not be here. Unknown color format.");
3502            break;
3503    }
3504
3505    def.nBufferCountActual = def.nBufferCountMin;
3506
3507    err = mOMX->setParameter(
3508            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3509    CHECK_EQ(err, (status_t)OK);
3510}
3511
3512void OMXCodec::setJPEGInputFormat(
3513        OMX_U32 width, OMX_U32 height, OMX_U32 compressedSize) {
3514    OMX_PARAM_PORTDEFINITIONTYPE def;
3515    InitOMXParams(&def);
3516    def.nPortIndex = kPortIndexInput;
3517
3518    status_t err = mOMX->getParameter(
3519            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3520    CHECK_EQ(err, (status_t)OK);
3521
3522    CHECK_EQ((int)def.eDomain, (int)OMX_PortDomainImage);
3523    OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
3524
3525    CHECK_EQ((int)imageDef->eCompressionFormat, (int)OMX_IMAGE_CodingJPEG);
3526    imageDef->nFrameWidth = width;
3527    imageDef->nFrameHeight = height;
3528
3529    def.nBufferSize = compressedSize;
3530    def.nBufferCountActual = def.nBufferCountMin;
3531
3532    err = mOMX->setParameter(
3533            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
3534    CHECK_EQ(err, (status_t)OK);
3535}
3536
3537void OMXCodec::addCodecSpecificData(const void *data, size_t size) {
3538    CodecSpecificData *specific =
3539        (CodecSpecificData *)malloc(sizeof(CodecSpecificData) + size - 1);
3540
3541    specific->mSize = size;
3542    memcpy(specific->mData, data, size);
3543
3544    mCodecSpecificData.push(specific);
3545}
3546
3547void OMXCodec::clearCodecSpecificData() {
3548    for (size_t i = 0; i < mCodecSpecificData.size(); ++i) {
3549        free(mCodecSpecificData.editItemAt(i));
3550    }
3551    mCodecSpecificData.clear();
3552    mCodecSpecificDataIndex = 0;
3553}
3554
3555status_t OMXCodec::start(MetaData *meta) {
3556    Mutex::Autolock autoLock(mLock);
3557
3558    if (mState != LOADED) {
3559        return UNKNOWN_ERROR;
3560    }
3561
3562    sp<MetaData> params = new MetaData;
3563    if (mQuirks & kWantsNALFragments) {
3564        params->setInt32(kKeyWantsNALFragments, true);
3565    }
3566    if (meta) {
3567        int64_t startTimeUs = 0;
3568        int64_t timeUs;
3569        if (meta->findInt64(kKeyTime, &timeUs)) {
3570            startTimeUs = timeUs;
3571        }
3572        params->setInt64(kKeyTime, startTimeUs);
3573    }
3574    status_t err = mSource->start(params.get());
3575
3576    if (err != OK) {
3577        return err;
3578    }
3579
3580    mCodecSpecificDataIndex = 0;
3581    mInitialBufferSubmit = true;
3582    mSignalledEOS = false;
3583    mNoMoreOutputData = false;
3584    mOutputPortSettingsHaveChanged = false;
3585    mSeekTimeUs = -1;
3586    mSeekMode = ReadOptions::SEEK_CLOSEST_SYNC;
3587    mTargetTimeUs = -1;
3588    mFilledBuffers.clear();
3589    mPaused = false;
3590
3591    return init();
3592}
3593
3594status_t OMXCodec::stop() {
3595    CODEC_LOGV("stop mState=%d", mState);
3596
3597    Mutex::Autolock autoLock(mLock);
3598
3599    while (isIntermediateState(mState)) {
3600        mAsyncCompletion.wait(mLock);
3601    }
3602
3603    switch (mState) {
3604        case LOADED:
3605        case ERROR:
3606            break;
3607
3608        case EXECUTING:
3609        {
3610            setState(EXECUTING_TO_IDLE);
3611
3612            if (mQuirks & kRequiresFlushBeforeShutdown) {
3613                CODEC_LOGV("This component requires a flush before transitioning "
3614                     "from EXECUTING to IDLE...");
3615
3616                bool emulateInputFlushCompletion =
3617                    !flushPortAsync(kPortIndexInput);
3618
3619                bool emulateOutputFlushCompletion =
3620                    !flushPortAsync(kPortIndexOutput);
3621
3622                if (emulateInputFlushCompletion) {
3623                    onCmdComplete(OMX_CommandFlush, kPortIndexInput);
3624                }
3625
3626                if (emulateOutputFlushCompletion) {
3627                    onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
3628                }
3629            } else {
3630                mPortStatus[kPortIndexInput] = SHUTTING_DOWN;
3631                mPortStatus[kPortIndexOutput] = SHUTTING_DOWN;
3632
3633                status_t err =
3634                    mOMX->sendCommand(mNode, OMX_CommandStateSet, OMX_StateIdle);
3635                CHECK_EQ(err, (status_t)OK);
3636            }
3637
3638            while (mState != LOADED && mState != ERROR) {
3639                mAsyncCompletion.wait(mLock);
3640            }
3641
3642            break;
3643        }
3644
3645        default:
3646        {
3647            CHECK(!"should not be here.");
3648            break;
3649        }
3650    }
3651
3652    if (mLeftOverBuffer) {
3653        mLeftOverBuffer->release();
3654        mLeftOverBuffer = NULL;
3655    }
3656
3657    mSource->stop();
3658
3659    CODEC_LOGV("stopped in state %d", mState);
3660
3661    return OK;
3662}
3663
3664sp<MetaData> OMXCodec::getFormat() {
3665    Mutex::Autolock autoLock(mLock);
3666
3667    return mOutputFormat;
3668}
3669
3670status_t OMXCodec::read(
3671        MediaBuffer **buffer, const ReadOptions *options) {
3672    status_t err = OK;
3673    *buffer = NULL;
3674
3675    Mutex::Autolock autoLock(mLock);
3676
3677    if (mState != EXECUTING && mState != RECONFIGURING) {
3678        return UNKNOWN_ERROR;
3679    }
3680
3681    bool seeking = false;
3682    int64_t seekTimeUs;
3683    ReadOptions::SeekMode seekMode;
3684    if (options && options->getSeekTo(&seekTimeUs, &seekMode)) {
3685        seeking = true;
3686    }
3687
3688    if (mInitialBufferSubmit) {
3689        mInitialBufferSubmit = false;
3690
3691        if (seeking) {
3692            CHECK(seekTimeUs >= 0);
3693            mSeekTimeUs = seekTimeUs;
3694            mSeekMode = seekMode;
3695
3696            // There's no reason to trigger the code below, there's
3697            // nothing to flush yet.
3698            seeking = false;
3699            mPaused = false;
3700        }
3701
3702        drainInputBuffers();
3703
3704        if (mState == EXECUTING) {
3705            // Otherwise mState == RECONFIGURING and this code will trigger
3706            // after the output port is reenabled.
3707            fillOutputBuffers();
3708        }
3709    }
3710
3711    if (seeking) {
3712        while (mState == RECONFIGURING) {
3713            if ((err = waitForBufferFilled_l()) != OK) {
3714                return err;
3715            }
3716        }
3717
3718        if (mState != EXECUTING) {
3719            return UNKNOWN_ERROR;
3720        }
3721
3722        CODEC_LOGV("seeking to %lld us (%.2f secs)", seekTimeUs, seekTimeUs / 1E6);
3723
3724        mSignalledEOS = false;
3725
3726        CHECK(seekTimeUs >= 0);
3727        mSeekTimeUs = seekTimeUs;
3728        mSeekMode = seekMode;
3729
3730        mFilledBuffers.clear();
3731
3732        CHECK_EQ((int)mState, (int)EXECUTING);
3733
3734        bool emulateInputFlushCompletion = !flushPortAsync(kPortIndexInput);
3735        bool emulateOutputFlushCompletion = !flushPortAsync(kPortIndexOutput);
3736
3737        if (emulateInputFlushCompletion) {
3738            onCmdComplete(OMX_CommandFlush, kPortIndexInput);
3739        }
3740
3741        if (emulateOutputFlushCompletion) {
3742            onCmdComplete(OMX_CommandFlush, kPortIndexOutput);
3743        }
3744
3745        while (mSeekTimeUs >= 0) {
3746            if ((err = waitForBufferFilled_l()) != OK) {
3747                return err;
3748            }
3749        }
3750    }
3751
3752    while (mState != ERROR && !mNoMoreOutputData && mFilledBuffers.empty()) {
3753        if ((err = waitForBufferFilled_l()) != OK) {
3754            return err;
3755        }
3756    }
3757
3758    if (mState == ERROR) {
3759        return UNKNOWN_ERROR;
3760    }
3761
3762    if (mFilledBuffers.empty()) {
3763        return mSignalledEOS ? mFinalStatus : ERROR_END_OF_STREAM;
3764    }
3765
3766    if (mOutputPortSettingsHaveChanged) {
3767        mOutputPortSettingsHaveChanged = false;
3768
3769        return INFO_FORMAT_CHANGED;
3770    }
3771
3772    size_t index = *mFilledBuffers.begin();
3773    mFilledBuffers.erase(mFilledBuffers.begin());
3774
3775    BufferInfo *info = &mPortBuffers[kPortIndexOutput].editItemAt(index);
3776    CHECK_EQ((int)info->mStatus, (int)OWNED_BY_US);
3777    info->mStatus = OWNED_BY_CLIENT;
3778
3779    info->mMediaBuffer->add_ref();
3780    *buffer = info->mMediaBuffer;
3781
3782    return OK;
3783}
3784
3785void OMXCodec::signalBufferReturned(MediaBuffer *buffer) {
3786    Mutex::Autolock autoLock(mLock);
3787
3788    Vector<BufferInfo> *buffers = &mPortBuffers[kPortIndexOutput];
3789    for (size_t i = 0; i < buffers->size(); ++i) {
3790        BufferInfo *info = &buffers->editItemAt(i);
3791
3792        if (info->mMediaBuffer == buffer) {
3793            CHECK_EQ((int)mPortStatus[kPortIndexOutput], (int)ENABLED);
3794            CHECK_EQ((int)info->mStatus, (int)OWNED_BY_CLIENT);
3795
3796            info->mStatus = OWNED_BY_US;
3797
3798            if (buffer->graphicBuffer() == 0) {
3799                fillOutputBuffer(info);
3800            } else {
3801                sp<MetaData> metaData = info->mMediaBuffer->meta_data();
3802                int32_t rendered = 0;
3803                if (!metaData->findInt32(kKeyRendered, &rendered)) {
3804                    rendered = 0;
3805                }
3806                if (!rendered) {
3807                    status_t err = cancelBufferToNativeWindow(info);
3808                    if (err < 0) {
3809                        return;
3810                    }
3811                }
3812
3813                info->mStatus = OWNED_BY_NATIVE_WINDOW;
3814
3815                // Dequeue the next buffer from the native window.
3816                BufferInfo *nextBufInfo = dequeueBufferFromNativeWindow();
3817                if (nextBufInfo == 0) {
3818                    return;
3819                }
3820
3821                // Give the buffer to the OMX node to fill.
3822                fillOutputBuffer(nextBufInfo);
3823            }
3824            return;
3825        }
3826    }
3827
3828    CHECK(!"should not be here.");
3829}
3830
3831static const char *imageCompressionFormatString(OMX_IMAGE_CODINGTYPE type) {
3832    static const char *kNames[] = {
3833        "OMX_IMAGE_CodingUnused",
3834        "OMX_IMAGE_CodingAutoDetect",
3835        "OMX_IMAGE_CodingJPEG",
3836        "OMX_IMAGE_CodingJPEG2K",
3837        "OMX_IMAGE_CodingEXIF",
3838        "OMX_IMAGE_CodingTIFF",
3839        "OMX_IMAGE_CodingGIF",
3840        "OMX_IMAGE_CodingPNG",
3841        "OMX_IMAGE_CodingLZW",
3842        "OMX_IMAGE_CodingBMP",
3843    };
3844
3845    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3846
3847    if (type < 0 || (size_t)type >= numNames) {
3848        return "UNKNOWN";
3849    } else {
3850        return kNames[type];
3851    }
3852}
3853
3854static const char *colorFormatString(OMX_COLOR_FORMATTYPE type) {
3855    static const char *kNames[] = {
3856        "OMX_COLOR_FormatUnused",
3857        "OMX_COLOR_FormatMonochrome",
3858        "OMX_COLOR_Format8bitRGB332",
3859        "OMX_COLOR_Format12bitRGB444",
3860        "OMX_COLOR_Format16bitARGB4444",
3861        "OMX_COLOR_Format16bitARGB1555",
3862        "OMX_COLOR_Format16bitRGB565",
3863        "OMX_COLOR_Format16bitBGR565",
3864        "OMX_COLOR_Format18bitRGB666",
3865        "OMX_COLOR_Format18bitARGB1665",
3866        "OMX_COLOR_Format19bitARGB1666",
3867        "OMX_COLOR_Format24bitRGB888",
3868        "OMX_COLOR_Format24bitBGR888",
3869        "OMX_COLOR_Format24bitARGB1887",
3870        "OMX_COLOR_Format25bitARGB1888",
3871        "OMX_COLOR_Format32bitBGRA8888",
3872        "OMX_COLOR_Format32bitARGB8888",
3873        "OMX_COLOR_FormatYUV411Planar",
3874        "OMX_COLOR_FormatYUV411PackedPlanar",
3875        "OMX_COLOR_FormatYUV420Planar",
3876        "OMX_COLOR_FormatYUV420PackedPlanar",
3877        "OMX_COLOR_FormatYUV420SemiPlanar",
3878        "OMX_COLOR_FormatYUV422Planar",
3879        "OMX_COLOR_FormatYUV422PackedPlanar",
3880        "OMX_COLOR_FormatYUV422SemiPlanar",
3881        "OMX_COLOR_FormatYCbYCr",
3882        "OMX_COLOR_FormatYCrYCb",
3883        "OMX_COLOR_FormatCbYCrY",
3884        "OMX_COLOR_FormatCrYCbY",
3885        "OMX_COLOR_FormatYUV444Interleaved",
3886        "OMX_COLOR_FormatRawBayer8bit",
3887        "OMX_COLOR_FormatRawBayer10bit",
3888        "OMX_COLOR_FormatRawBayer8bitcompressed",
3889        "OMX_COLOR_FormatL2",
3890        "OMX_COLOR_FormatL4",
3891        "OMX_COLOR_FormatL8",
3892        "OMX_COLOR_FormatL16",
3893        "OMX_COLOR_FormatL24",
3894        "OMX_COLOR_FormatL32",
3895        "OMX_COLOR_FormatYUV420PackedSemiPlanar",
3896        "OMX_COLOR_FormatYUV422PackedSemiPlanar",
3897        "OMX_COLOR_Format18BitBGR666",
3898        "OMX_COLOR_Format24BitARGB6666",
3899        "OMX_COLOR_Format24BitABGR6666",
3900    };
3901
3902    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3903
3904    if (type == OMX_TI_COLOR_FormatYUV420PackedSemiPlanar) {
3905        return "OMX_TI_COLOR_FormatYUV420PackedSemiPlanar";
3906    } else if (type == OMX_QCOM_COLOR_FormatYVU420SemiPlanar) {
3907        return "OMX_QCOM_COLOR_FormatYVU420SemiPlanar";
3908    } else if (type < 0 || (size_t)type >= numNames) {
3909        return "UNKNOWN";
3910    } else {
3911        return kNames[type];
3912    }
3913}
3914
3915static const char *videoCompressionFormatString(OMX_VIDEO_CODINGTYPE type) {
3916    static const char *kNames[] = {
3917        "OMX_VIDEO_CodingUnused",
3918        "OMX_VIDEO_CodingAutoDetect",
3919        "OMX_VIDEO_CodingMPEG2",
3920        "OMX_VIDEO_CodingH263",
3921        "OMX_VIDEO_CodingMPEG4",
3922        "OMX_VIDEO_CodingWMV",
3923        "OMX_VIDEO_CodingRV",
3924        "OMX_VIDEO_CodingAVC",
3925        "OMX_VIDEO_CodingMJPEG",
3926    };
3927
3928    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3929
3930    if (type < 0 || (size_t)type >= numNames) {
3931        return "UNKNOWN";
3932    } else {
3933        return kNames[type];
3934    }
3935}
3936
3937static const char *audioCodingTypeString(OMX_AUDIO_CODINGTYPE type) {
3938    static const char *kNames[] = {
3939        "OMX_AUDIO_CodingUnused",
3940        "OMX_AUDIO_CodingAutoDetect",
3941        "OMX_AUDIO_CodingPCM",
3942        "OMX_AUDIO_CodingADPCM",
3943        "OMX_AUDIO_CodingAMR",
3944        "OMX_AUDIO_CodingGSMFR",
3945        "OMX_AUDIO_CodingGSMEFR",
3946        "OMX_AUDIO_CodingGSMHR",
3947        "OMX_AUDIO_CodingPDCFR",
3948        "OMX_AUDIO_CodingPDCEFR",
3949        "OMX_AUDIO_CodingPDCHR",
3950        "OMX_AUDIO_CodingTDMAFR",
3951        "OMX_AUDIO_CodingTDMAEFR",
3952        "OMX_AUDIO_CodingQCELP8",
3953        "OMX_AUDIO_CodingQCELP13",
3954        "OMX_AUDIO_CodingEVRC",
3955        "OMX_AUDIO_CodingSMV",
3956        "OMX_AUDIO_CodingG711",
3957        "OMX_AUDIO_CodingG723",
3958        "OMX_AUDIO_CodingG726",
3959        "OMX_AUDIO_CodingG729",
3960        "OMX_AUDIO_CodingAAC",
3961        "OMX_AUDIO_CodingMP3",
3962        "OMX_AUDIO_CodingSBC",
3963        "OMX_AUDIO_CodingVORBIS",
3964        "OMX_AUDIO_CodingWMA",
3965        "OMX_AUDIO_CodingRA",
3966        "OMX_AUDIO_CodingMIDI",
3967    };
3968
3969    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
3970
3971    if (type < 0 || (size_t)type >= numNames) {
3972        return "UNKNOWN";
3973    } else {
3974        return kNames[type];
3975    }
3976}
3977
3978static const char *audioPCMModeString(OMX_AUDIO_PCMMODETYPE type) {
3979    static const char *kNames[] = {
3980        "OMX_AUDIO_PCMModeLinear",
3981        "OMX_AUDIO_PCMModeALaw",
3982        "OMX_AUDIO_PCMModeMULaw",
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 *amrBandModeString(OMX_AUDIO_AMRBANDMODETYPE type) {
3995    static const char *kNames[] = {
3996        "OMX_AUDIO_AMRBandModeUnused",
3997        "OMX_AUDIO_AMRBandModeNB0",
3998        "OMX_AUDIO_AMRBandModeNB1",
3999        "OMX_AUDIO_AMRBandModeNB2",
4000        "OMX_AUDIO_AMRBandModeNB3",
4001        "OMX_AUDIO_AMRBandModeNB4",
4002        "OMX_AUDIO_AMRBandModeNB5",
4003        "OMX_AUDIO_AMRBandModeNB6",
4004        "OMX_AUDIO_AMRBandModeNB7",
4005        "OMX_AUDIO_AMRBandModeWB0",
4006        "OMX_AUDIO_AMRBandModeWB1",
4007        "OMX_AUDIO_AMRBandModeWB2",
4008        "OMX_AUDIO_AMRBandModeWB3",
4009        "OMX_AUDIO_AMRBandModeWB4",
4010        "OMX_AUDIO_AMRBandModeWB5",
4011        "OMX_AUDIO_AMRBandModeWB6",
4012        "OMX_AUDIO_AMRBandModeWB7",
4013        "OMX_AUDIO_AMRBandModeWB8",
4014    };
4015
4016    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
4017
4018    if (type < 0 || (size_t)type >= numNames) {
4019        return "UNKNOWN";
4020    } else {
4021        return kNames[type];
4022    }
4023}
4024
4025static const char *amrFrameFormatString(OMX_AUDIO_AMRFRAMEFORMATTYPE type) {
4026    static const char *kNames[] = {
4027        "OMX_AUDIO_AMRFrameFormatConformance",
4028        "OMX_AUDIO_AMRFrameFormatIF1",
4029        "OMX_AUDIO_AMRFrameFormatIF2",
4030        "OMX_AUDIO_AMRFrameFormatFSF",
4031        "OMX_AUDIO_AMRFrameFormatRTPPayload",
4032        "OMX_AUDIO_AMRFrameFormatITU",
4033    };
4034
4035    size_t numNames = sizeof(kNames) / sizeof(kNames[0]);
4036
4037    if (type < 0 || (size_t)type >= numNames) {
4038        return "UNKNOWN";
4039    } else {
4040        return kNames[type];
4041    }
4042}
4043
4044void OMXCodec::dumpPortStatus(OMX_U32 portIndex) {
4045    OMX_PARAM_PORTDEFINITIONTYPE def;
4046    InitOMXParams(&def);
4047    def.nPortIndex = portIndex;
4048
4049    status_t err = mOMX->getParameter(
4050            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
4051    CHECK_EQ(err, (status_t)OK);
4052
4053    printf("%s Port = {\n", portIndex == kPortIndexInput ? "Input" : "Output");
4054
4055    CHECK((portIndex == kPortIndexInput && def.eDir == OMX_DirInput)
4056          || (portIndex == kPortIndexOutput && def.eDir == OMX_DirOutput));
4057
4058    printf("  nBufferCountActual = %ld\n", def.nBufferCountActual);
4059    printf("  nBufferCountMin = %ld\n", def.nBufferCountMin);
4060    printf("  nBufferSize = %ld\n", def.nBufferSize);
4061
4062    switch (def.eDomain) {
4063        case OMX_PortDomainImage:
4064        {
4065            const OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
4066
4067            printf("\n");
4068            printf("  // Image\n");
4069            printf("  nFrameWidth = %ld\n", imageDef->nFrameWidth);
4070            printf("  nFrameHeight = %ld\n", imageDef->nFrameHeight);
4071            printf("  nStride = %ld\n", imageDef->nStride);
4072
4073            printf("  eCompressionFormat = %s\n",
4074                   imageCompressionFormatString(imageDef->eCompressionFormat));
4075
4076            printf("  eColorFormat = %s\n",
4077                   colorFormatString(imageDef->eColorFormat));
4078
4079            break;
4080        }
4081
4082        case OMX_PortDomainVideo:
4083        {
4084            OMX_VIDEO_PORTDEFINITIONTYPE *videoDef = &def.format.video;
4085
4086            printf("\n");
4087            printf("  // Video\n");
4088            printf("  nFrameWidth = %ld\n", videoDef->nFrameWidth);
4089            printf("  nFrameHeight = %ld\n", videoDef->nFrameHeight);
4090            printf("  nStride = %ld\n", videoDef->nStride);
4091
4092            printf("  eCompressionFormat = %s\n",
4093                   videoCompressionFormatString(videoDef->eCompressionFormat));
4094
4095            printf("  eColorFormat = %s\n",
4096                   colorFormatString(videoDef->eColorFormat));
4097
4098            break;
4099        }
4100
4101        case OMX_PortDomainAudio:
4102        {
4103            OMX_AUDIO_PORTDEFINITIONTYPE *audioDef = &def.format.audio;
4104
4105            printf("\n");
4106            printf("  // Audio\n");
4107            printf("  eEncoding = %s\n",
4108                   audioCodingTypeString(audioDef->eEncoding));
4109
4110            if (audioDef->eEncoding == OMX_AUDIO_CodingPCM) {
4111                OMX_AUDIO_PARAM_PCMMODETYPE params;
4112                InitOMXParams(&params);
4113                params.nPortIndex = portIndex;
4114
4115                err = mOMX->getParameter(
4116                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
4117                CHECK_EQ(err, (status_t)OK);
4118
4119                printf("  nSamplingRate = %ld\n", params.nSamplingRate);
4120                printf("  nChannels = %ld\n", params.nChannels);
4121                printf("  bInterleaved = %d\n", params.bInterleaved);
4122                printf("  nBitPerSample = %ld\n", params.nBitPerSample);
4123
4124                printf("  eNumData = %s\n",
4125                       params.eNumData == OMX_NumericalDataSigned
4126                        ? "signed" : "unsigned");
4127
4128                printf("  ePCMMode = %s\n", audioPCMModeString(params.ePCMMode));
4129            } else if (audioDef->eEncoding == OMX_AUDIO_CodingAMR) {
4130                OMX_AUDIO_PARAM_AMRTYPE amr;
4131                InitOMXParams(&amr);
4132                amr.nPortIndex = portIndex;
4133
4134                err = mOMX->getParameter(
4135                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
4136                CHECK_EQ(err, (status_t)OK);
4137
4138                printf("  nChannels = %ld\n", amr.nChannels);
4139                printf("  eAMRBandMode = %s\n",
4140                        amrBandModeString(amr.eAMRBandMode));
4141                printf("  eAMRFrameFormat = %s\n",
4142                        amrFrameFormatString(amr.eAMRFrameFormat));
4143            }
4144
4145            break;
4146        }
4147
4148        default:
4149        {
4150            printf("  // Unknown\n");
4151            break;
4152        }
4153    }
4154
4155    printf("}\n");
4156}
4157
4158status_t OMXCodec::initNativeWindow() {
4159    // Enable use of a GraphicBuffer as the output for this node.  This must
4160    // happen before getting the IndexParamPortDefinition parameter because it
4161    // will affect the pixel format that the node reports.
4162    status_t err = mOMX->enableGraphicBuffers(mNode, kPortIndexOutput, OMX_TRUE);
4163    if (err != 0) {
4164        return err;
4165    }
4166
4167    return OK;
4168}
4169
4170void OMXCodec::initNativeWindowCrop() {
4171    int32_t left, top, right, bottom;
4172
4173    CHECK(mOutputFormat->findRect(
4174                        kKeyCropRect,
4175                        &left, &top, &right, &bottom));
4176
4177    android_native_rect_t crop;
4178    crop.left = left;
4179    crop.top = top;
4180    crop.right = right + 1;
4181    crop.bottom = bottom + 1;
4182
4183    // We'll ignore any errors here, if the surface is
4184    // already invalid, we'll know soon enough.
4185    native_window_set_crop(mNativeWindow.get(), &crop);
4186}
4187
4188void OMXCodec::initOutputFormat(const sp<MetaData> &inputFormat) {
4189    mOutputFormat = new MetaData;
4190    mOutputFormat->setCString(kKeyDecoderComponent, mComponentName);
4191    if (mIsEncoder) {
4192        int32_t timeScale;
4193        if (inputFormat->findInt32(kKeyTimeScale, &timeScale)) {
4194            mOutputFormat->setInt32(kKeyTimeScale, timeScale);
4195        }
4196    }
4197
4198    OMX_PARAM_PORTDEFINITIONTYPE def;
4199    InitOMXParams(&def);
4200    def.nPortIndex = kPortIndexOutput;
4201
4202    status_t err = mOMX->getParameter(
4203            mNode, OMX_IndexParamPortDefinition, &def, sizeof(def));
4204    CHECK_EQ(err, (status_t)OK);
4205
4206    switch (def.eDomain) {
4207        case OMX_PortDomainImage:
4208        {
4209            OMX_IMAGE_PORTDEFINITIONTYPE *imageDef = &def.format.image;
4210            CHECK_EQ((int)imageDef->eCompressionFormat,
4211                     (int)OMX_IMAGE_CodingUnused);
4212
4213            mOutputFormat->setCString(kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
4214            mOutputFormat->setInt32(kKeyColorFormat, imageDef->eColorFormat);
4215            mOutputFormat->setInt32(kKeyWidth, imageDef->nFrameWidth);
4216            mOutputFormat->setInt32(kKeyHeight, imageDef->nFrameHeight);
4217            break;
4218        }
4219
4220        case OMX_PortDomainAudio:
4221        {
4222            OMX_AUDIO_PORTDEFINITIONTYPE *audio_def = &def.format.audio;
4223
4224            if (audio_def->eEncoding == OMX_AUDIO_CodingPCM) {
4225                OMX_AUDIO_PARAM_PCMMODETYPE params;
4226                InitOMXParams(&params);
4227                params.nPortIndex = kPortIndexOutput;
4228
4229                err = mOMX->getParameter(
4230                        mNode, OMX_IndexParamAudioPcm, &params, sizeof(params));
4231                CHECK_EQ(err, (status_t)OK);
4232
4233                CHECK_EQ((int)params.eNumData, (int)OMX_NumericalDataSigned);
4234                CHECK_EQ(params.nBitPerSample, 16u);
4235                CHECK_EQ((int)params.ePCMMode, (int)OMX_AUDIO_PCMModeLinear);
4236
4237                int32_t numChannels, sampleRate;
4238                inputFormat->findInt32(kKeyChannelCount, &numChannels);
4239                inputFormat->findInt32(kKeySampleRate, &sampleRate);
4240
4241                if ((OMX_U32)numChannels != params.nChannels) {
4242                    LOGV("Codec outputs a different number of channels than "
4243                         "the input stream contains (contains %d channels, "
4244                         "codec outputs %ld channels).",
4245                         numChannels, params.nChannels);
4246                }
4247
4248                if (sampleRate != (int32_t)params.nSamplingRate) {
4249                    LOGV("Codec outputs at different sampling rate than "
4250                         "what the input stream contains (contains data at "
4251                         "%d Hz, codec outputs %lu Hz)",
4252                         sampleRate, params.nSamplingRate);
4253                }
4254
4255                mOutputFormat->setCString(
4256                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
4257
4258                // Use the codec-advertised number of channels, as some
4259                // codecs appear to output stereo even if the input data is
4260                // mono. If we know the codec lies about this information,
4261                // use the actual number of channels instead.
4262                mOutputFormat->setInt32(
4263                        kKeyChannelCount,
4264                        (mQuirks & kDecoderLiesAboutNumberOfChannels)
4265                            ? numChannels : params.nChannels);
4266
4267                mOutputFormat->setInt32(kKeySampleRate, params.nSamplingRate);
4268            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAMR) {
4269                OMX_AUDIO_PARAM_AMRTYPE amr;
4270                InitOMXParams(&amr);
4271                amr.nPortIndex = kPortIndexOutput;
4272
4273                err = mOMX->getParameter(
4274                        mNode, OMX_IndexParamAudioAmr, &amr, sizeof(amr));
4275                CHECK_EQ(err, (status_t)OK);
4276
4277                CHECK_EQ(amr.nChannels, 1u);
4278                mOutputFormat->setInt32(kKeyChannelCount, 1);
4279
4280                if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeNB0
4281                    && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeNB7) {
4282                    mOutputFormat->setCString(
4283                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_NB);
4284                    mOutputFormat->setInt32(kKeySampleRate, 8000);
4285                } else if (amr.eAMRBandMode >= OMX_AUDIO_AMRBandModeWB0
4286                            && amr.eAMRBandMode <= OMX_AUDIO_AMRBandModeWB8) {
4287                    mOutputFormat->setCString(
4288                            kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AMR_WB);
4289                    mOutputFormat->setInt32(kKeySampleRate, 16000);
4290                } else {
4291                    CHECK(!"Unknown AMR band mode.");
4292                }
4293            } else if (audio_def->eEncoding == OMX_AUDIO_CodingAAC) {
4294                mOutputFormat->setCString(
4295                        kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_AAC);
4296                int32_t numChannels, sampleRate, bitRate;
4297                inputFormat->findInt32(kKeyChannelCount, &numChannels);
4298                inputFormat->findInt32(kKeySampleRate, &sampleRate);
4299                inputFormat->findInt32(kKeyBitRate, &bitRate);
4300                mOutputFormat->setInt32(kKeyChannelCount, numChannels);
4301                mOutputFormat->setInt32(kKeySampleRate, sampleRate);
4302                mOutputFormat->setInt32(kKeyBitRate, bitRate);
4303            } else {
4304                CHECK(!"Should not be here. Unknown audio encoding.");
4305            }
4306            break;
4307        }
4308
4309        case OMX_PortDomainVideo:
4310        {
4311            OMX_VIDEO_PORTDEFINITIONTYPE *video_def = &def.format.video;
4312
4313            if (video_def->eCompressionFormat == OMX_VIDEO_CodingUnused) {
4314                mOutputFormat->setCString(
4315                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_RAW);
4316            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingMPEG4) {
4317                mOutputFormat->setCString(
4318                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_MPEG4);
4319            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingH263) {
4320                mOutputFormat->setCString(
4321                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_H263);
4322            } else if (video_def->eCompressionFormat == OMX_VIDEO_CodingAVC) {
4323                mOutputFormat->setCString(
4324                        kKeyMIMEType, MEDIA_MIMETYPE_VIDEO_AVC);
4325            } else {
4326                CHECK(!"Unknown compression format.");
4327            }
4328
4329            mOutputFormat->setInt32(kKeyWidth, video_def->nFrameWidth);
4330            mOutputFormat->setInt32(kKeyHeight, video_def->nFrameHeight);
4331            mOutputFormat->setInt32(kKeyColorFormat, video_def->eColorFormat);
4332
4333            if (!mIsEncoder) {
4334                OMX_CONFIG_RECTTYPE rect;
4335                InitOMXParams(&rect);
4336                rect.nPortIndex = kPortIndexOutput;
4337                status_t err =
4338                        mOMX->getConfig(
4339                            mNode, OMX_IndexConfigCommonOutputCrop,
4340                            &rect, sizeof(rect));
4341
4342                CODEC_LOGI(
4343                        "video dimensions are %ld x %ld",
4344                        video_def->nFrameWidth, video_def->nFrameHeight);
4345
4346                if (err == OK) {
4347                    CHECK_GE(rect.nLeft, 0);
4348                    CHECK_GE(rect.nTop, 0);
4349                    CHECK_GE(rect.nWidth, 0u);
4350                    CHECK_GE(rect.nHeight, 0u);
4351                    CHECK_LE(rect.nLeft + rect.nWidth - 1, video_def->nFrameWidth);
4352                    CHECK_LE(rect.nTop + rect.nHeight - 1, video_def->nFrameHeight);
4353
4354                    mOutputFormat->setRect(
4355                            kKeyCropRect,
4356                            rect.nLeft,
4357                            rect.nTop,
4358                            rect.nLeft + rect.nWidth - 1,
4359                            rect.nTop + rect.nHeight - 1);
4360
4361                    CODEC_LOGI(
4362                            "Crop rect is %ld x %ld @ (%ld, %ld)",
4363                            rect.nWidth, rect.nHeight, rect.nLeft, rect.nTop);
4364                } else {
4365                    mOutputFormat->setRect(
4366                            kKeyCropRect,
4367                            0, 0,
4368                            video_def->nFrameWidth - 1,
4369                            video_def->nFrameHeight - 1);
4370                }
4371
4372                if (mNativeWindow != NULL) {
4373                     initNativeWindowCrop();
4374                }
4375            }
4376            break;
4377        }
4378
4379        default:
4380        {
4381            CHECK(!"should not be here, neither audio nor video.");
4382            break;
4383        }
4384    }
4385
4386    // If the input format contains rotation information, flag the output
4387    // format accordingly.
4388
4389    int32_t rotationDegrees;
4390    if (mSource->getFormat()->findInt32(kKeyRotation, &rotationDegrees)) {
4391        mOutputFormat->setInt32(kKeyRotation, rotationDegrees);
4392    }
4393}
4394
4395status_t OMXCodec::pause() {
4396    Mutex::Autolock autoLock(mLock);
4397
4398    mPaused = true;
4399
4400    return OK;
4401}
4402
4403////////////////////////////////////////////////////////////////////////////////
4404
4405status_t QueryCodecs(
4406        const sp<IOMX> &omx,
4407        const char *mime, bool queryDecoders, bool hwCodecOnly,
4408        Vector<CodecCapabilities> *results) {
4409    Vector<String8> matchingCodecs;
4410    results->clear();
4411
4412    OMXCodec::findMatchingCodecs(mime,
4413            !queryDecoders /*createEncoder*/,
4414            NULL /*matchComponentName*/,
4415            hwCodecOnly ? OMXCodec::kHardwareCodecsOnly : 0 /*flags*/,
4416            &matchingCodecs);
4417
4418    for (size_t c = 0; c < matchingCodecs.size(); c++) {
4419        const char *componentName = matchingCodecs.itemAt(c).string();
4420
4421        if (strncmp(componentName, "OMX.", 4)) {
4422            // Not an OpenMax component but a software codec.
4423
4424            results->push();
4425            CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
4426            caps->mComponentName = componentName;
4427            continue;
4428        }
4429
4430        sp<OMXCodecObserver> observer = new OMXCodecObserver;
4431        IOMX::node_id node;
4432        status_t err = omx->allocateNode(componentName, observer, &node);
4433
4434        if (err != OK) {
4435            continue;
4436        }
4437
4438        OMXCodec::setComponentRole(omx, node, !queryDecoders, mime);
4439
4440        results->push();
4441        CodecCapabilities *caps = &results->editItemAt(results->size() - 1);
4442        caps->mComponentName = componentName;
4443
4444        OMX_VIDEO_PARAM_PROFILELEVELTYPE param;
4445        InitOMXParams(&param);
4446
4447        param.nPortIndex = queryDecoders ? 0 : 1;
4448
4449        for (param.nProfileIndex = 0;; ++param.nProfileIndex) {
4450            err = omx->getParameter(
4451                    node, OMX_IndexParamVideoProfileLevelQuerySupported,
4452                    &param, sizeof(param));
4453
4454            if (err != OK) {
4455                break;
4456            }
4457
4458            CodecProfileLevel profileLevel;
4459            profileLevel.mProfile = param.eProfile;
4460            profileLevel.mLevel = param.eLevel;
4461
4462            caps->mProfileLevels.push(profileLevel);
4463        }
4464
4465        // Color format query
4466        OMX_VIDEO_PARAM_PORTFORMATTYPE portFormat;
4467        InitOMXParams(&portFormat);
4468        portFormat.nPortIndex = queryDecoders ? 1 : 0;
4469        for (portFormat.nIndex = 0;; ++portFormat.nIndex)  {
4470            err = omx->getParameter(
4471                    node, OMX_IndexParamVideoPortFormat,
4472                    &portFormat, sizeof(portFormat));
4473            if (err != OK) {
4474                break;
4475            }
4476            caps->mColorFormats.push(portFormat.eColorFormat);
4477        }
4478
4479        CHECK_EQ(omx->freeNode(node), (status_t)OK);
4480    }
4481
4482    return OK;
4483}
4484
4485status_t QueryCodecs(
4486        const sp<IOMX> &omx,
4487        const char *mimeType, bool queryDecoders,
4488        Vector<CodecCapabilities> *results) {
4489    return QueryCodecs(omx, mimeType, queryDecoders, false /*hwCodecOnly*/, results);
4490}
4491
4492void OMXCodec::restorePatchedDataPointer(BufferInfo *info) {
4493    CHECK(mIsEncoder && (mQuirks & kAvoidMemcopyInputRecordingFrames));
4494    CHECK(mOMXLivesLocally);
4495
4496    OMX_BUFFERHEADERTYPE *header = (OMX_BUFFERHEADERTYPE *)info->mBuffer;
4497    header->pBuffer = (OMX_U8 *)info->mData;
4498}
4499
4500}  // namespace android
4501