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