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