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