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