OMXCameraAdapter.cpp revision ba9c1504171d4455f0616c317a1bc42e38f1feb9
1/*
2 * Copyright (C) Texas Instruments - http://www.ti.com/
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/**
18* @file OMXCameraAdapter.cpp
19*
20* This file maps the Camera Hardware Interface to OMX.
21*
22*/
23
24#include "CameraHal.h"
25#include "OMXCameraAdapter.h"
26#include "ErrorUtils.h"
27#include "TICameraParameters.h"
28#include <signal.h>
29#include <math.h>
30
31#include <cutils/properties.h>
32#define UNLIKELY( exp ) (__builtin_expect( (exp) != 0, false ))
33static int mDebugFps = 0;
34
35#define HERE(Msg) {CAMHAL_LOGEB("--===line %d, %s===--\n", __LINE__, Msg);}
36
37namespace android {
38
39#undef LOG_TAG
40///Maintain a separate tag for OMXCameraAdapter logs to isolate issues OMX specific
41#define LOG_TAG "CameraHAL"
42
43//frames skipped before recalculating the framerate
44#define FPS_PERIOD 30
45
46static OMXCameraAdapter *gCameraAdapter = NULL;
47Mutex gAdapterLock;
48
49/*--------------------Camera Adapter Class STARTS here-----------------------------*/
50
51status_t OMXCameraAdapter::initialize(CameraProperties::Properties* caps, int sensor_index)
52{
53    LOG_FUNCTION_NAME;
54
55    char value[PROPERTY_VALUE_MAX];
56    property_get("debug.camera.showfps", value, "0");
57    mDebugFps = atoi(value);
58
59    TIMM_OSAL_ERRORTYPE osalError = OMX_ErrorNone;
60    OMX_ERRORTYPE eError = OMX_ErrorNone;
61    status_t ret = NO_ERROR;
62
63
64    mLocalVersionParam.s.nVersionMajor = 0x1;
65    mLocalVersionParam.s.nVersionMinor = 0x1;
66    mLocalVersionParam.s.nRevision = 0x0 ;
67    mLocalVersionParam.s.nStep =  0x0;
68
69    mPending3Asettings = 0;//E3AsettingsAll;
70
71    if ( 0 != mInitSem.Count() )
72        {
73        CAMHAL_LOGEB("Error mInitSem semaphore count %d", mInitSem.Count());
74        LOG_FUNCTION_NAME_EXIT;
75        return NO_INIT;
76        }
77
78    if (mComponentState != OMX_StateLoaded && mComponentState != OMX_StateInvalid) {
79       LOG_FUNCTION_NAME_EXIT;
80       return NO_INIT;
81    }
82
83    if ( mComponentState != OMX_StateExecuting ){
84        ///Update the preview and image capture port indexes
85        mCameraAdapterParameters.mPrevPortIndex = OMX_CAMERA_PORT_VIDEO_OUT_PREVIEW;
86        // temp changed in order to build OMX_CAMERA_PORT_VIDEO_OUT_IMAGE;
87        mCameraAdapterParameters.mImagePortIndex = OMX_CAMERA_PORT_IMAGE_OUT_IMAGE;
88        mCameraAdapterParameters.mMeasurementPortIndex = OMX_CAMERA_PORT_VIDEO_OUT_MEASUREMENT;
89        //currently not supported use preview port instead
90        mCameraAdapterParameters.mVideoPortIndex = OMX_CAMERA_PORT_VIDEO_OUT_PREVIEW;
91
92        if(!mCameraAdapterParameters.mHandleComp)
93            {
94            ///Initialize the OMX Core
95            eError = OMX_Init();
96
97            if(eError!=OMX_ErrorNone)
98                {
99                CAMHAL_LOGEB("OMX_Init -0x%x", eError);
100                }
101            GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
102
103            ///Setup key parameters to send to Ducati during init
104            OMX_CALLBACKTYPE oCallbacks;
105
106            /* Initialize the callback handles */
107            oCallbacks.EventHandler    = android::OMXCameraAdapterEventHandler;
108            oCallbacks.EmptyBufferDone = android::OMXCameraAdapterEmptyBufferDone;
109            oCallbacks.FillBufferDone  = android::OMXCameraAdapterFillBufferDone;
110
111            ///Get the handle to the OMX Component
112            mCameraAdapterParameters.mHandleComp = NULL;
113            eError = OMX_GetHandle(&(mCameraAdapterParameters.mHandleComp), //     previously used: OMX_GetHandle
114                                        (OMX_STRING)"OMX.TI.DUCATI1.VIDEO.CAMERA" ///@todo Use constant instead of hardcoded name
115                                        , this
116                                        , &oCallbacks);
117
118            if(eError!=OMX_ErrorNone)
119                {
120                CAMHAL_LOGEB("OMX_GetHandle -0x%x", eError);
121                }
122            GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
123
124
125             eError = OMX_SendCommand(mCameraAdapterParameters.mHandleComp,
126                                          OMX_CommandPortDisable,
127                                          OMX_ALL,
128                                          NULL);
129
130             if(eError!=OMX_ErrorNone)
131                 {
132                 CAMHAL_LOGEB("OMX_SendCommand(OMX_CommandPortDisable) -0x%x", eError);
133                 }
134
135             GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
136
137             ///Register for port enable event
138             ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
139                                         OMX_EventCmdComplete,
140                                         OMX_CommandPortEnable,
141                                         mCameraAdapterParameters.mPrevPortIndex,
142                                         mInitSem);
143             if(ret!=NO_ERROR)
144                 {
145                 CAMHAL_LOGEB("Error in registering for event %d", ret);
146                 goto EXIT;
147                 }
148
149            ///Enable PREVIEW Port
150             eError = OMX_SendCommand(mCameraAdapterParameters.mHandleComp,
151                                         OMX_CommandPortEnable,
152                                         mCameraAdapterParameters.mPrevPortIndex,
153                                         NULL);
154
155             if(eError!=OMX_ErrorNone)
156                 {
157                 CAMHAL_LOGEB("OMX_SendCommand(OMX_CommandPortEnable) -0x%x", eError);
158                 }
159
160             GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
161
162             //Wait for the port enable event to occur
163             ret = mInitSem.WaitTimeout(OMX_CMD_TIMEOUT);
164             if ( NO_ERROR == ret )
165                 {
166                 CAMHAL_LOGDA("-Port enable event arrived");
167                 }
168             else
169                 {
170                 ret |= SignalEvent(mCameraAdapterParameters.mHandleComp,
171                                    OMX_EventCmdComplete,
172                                    OMX_CommandPortEnable,
173                                    mCameraAdapterParameters.mPrevPortIndex,
174                                    NULL);
175                 CAMHAL_LOGEA("Timeout for enabling preview port expired!");
176                 goto EXIT;
177                 }
178
179            }
180        else
181            {
182            OMXCameraPortParameters * mPreviewData =
183                &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex];
184
185            //Apply default configs before trying to swtich to a new sensor
186            if ( NO_ERROR != setFormat(OMX_CAMERA_PORT_VIDEO_OUT_PREVIEW, *mPreviewData) )
187                {
188                CAMHAL_LOGEB("Error 0x%x while applying defaults", ret);
189                goto EXIT;
190                }
191            }
192    }
193    ///Select the sensor
194    OMX_CONFIG_SENSORSELECTTYPE sensorSelect;
195    OMX_INIT_STRUCT_PTR (&sensorSelect, OMX_CONFIG_SENSORSELECTTYPE);
196    sensorSelect.eSensor = (OMX_SENSORSELECT)sensor_index;
197    eError = OMX_SetConfig(mCameraAdapterParameters.mHandleComp, ( OMX_INDEXTYPE ) OMX_TI_IndexConfigSensorSelect, &sensorSelect);
198
199    if ( OMX_ErrorNone != eError )
200        {
201        CAMHAL_LOGEB("Error while selecting the sensor index as %d - 0x%x", sensor_index, eError);
202        return BAD_VALUE;
203        }
204    else
205        {
206        CAMHAL_LOGDB("Sensor %d selected successfully", sensor_index);
207        }
208
209    printComponentVersion(mCameraAdapterParameters.mHandleComp);
210
211    mSensorIndex = sensor_index;
212    mBracketingEnabled = false;
213    mBracketingBuffersQueuedCount = 0;
214    mBracketingRange = 1;
215    mLastBracetingBufferIdx = 0;
216    mOMXStateSwitch = false;
217
218    if ( mComponentState != OMX_StateExecuting ){
219        mCaptureSignalled = false;
220        mCaptureConfigured = false;
221        mRecording = false;
222        mWaitingForSnapshot = false;
223        mSnapshotCount = 0;
224        mComponentState = OMX_StateLoaded;
225
226        mCapMode = HIGH_QUALITY;
227        mBurstFrames = 1;
228        mCapturedFrames = 0;
229        mPictureQuality = 100;
230        mCurrentZoomIdx = 0;
231        mTargetZoomIdx = 0;
232        mReturnZoomStatus = false;
233        mZoomInc = 1;
234        mZoomParameterIdx = 0;
235        mExposureBracketingValidEntries = 0;
236        mSensorOverclock = false;
237
238        mDeviceOrientation = 0;
239        mCapabilities = caps;
240
241        mEXIFData.mGPSData.mAltitudeValid = false;
242        mEXIFData.mGPSData.mDatestampValid = false;
243        mEXIFData.mGPSData.mLatValid = false;
244        mEXIFData.mGPSData.mLongValid = false;
245        mEXIFData.mGPSData.mMapDatumValid = false;
246        mEXIFData.mGPSData.mProcMethodValid = false;
247        mEXIFData.mGPSData.mVersionIdValid = false;
248        mEXIFData.mGPSData.mTimeStampValid = false;
249        mEXIFData.mModelValid = false;
250        mEXIFData.mMakeValid = false;
251
252        // initialize command handling thread
253        if(mCommandHandler.get() == NULL)
254            mCommandHandler = new CommandHandler(this);
255
256        if ( NULL == mCommandHandler.get() )
257        {
258            CAMHAL_LOGEA("Couldn't create command handler");
259            return NO_MEMORY;
260        }
261
262        ret = mCommandHandler->run("CallbackThread", PRIORITY_URGENT_DISPLAY);
263        if ( ret != NO_ERROR )
264        {
265            if( ret == INVALID_OPERATION){
266                CAMHAL_LOGDA("command handler thread already runnning!!");
267            }else
268            {
269                CAMHAL_LOGEA("Couldn't run command handlerthread");
270                return ret;
271            }
272        }
273
274        // initialize omx callback handling thread
275        if(mOMXCallbackHandler.get() == NULL)
276            mOMXCallbackHandler = new OMXCallbackHandler(this);
277
278        if ( NULL == mOMXCallbackHandler.get() )
279        {
280            CAMHAL_LOGEA("Couldn't create omx callback handler");
281            return NO_MEMORY;
282        }
283
284        ret = mOMXCallbackHandler->run("OMXCallbackThread", PRIORITY_URGENT_DISPLAY);
285        if ( ret != NO_ERROR )
286        {
287            if( ret == INVALID_OPERATION){
288                CAMHAL_LOGDA("omx callback handler thread already runnning!!");
289            }else
290            {
291                CAMHAL_LOGEA("Couldn't run omx callback handler thread");
292                return ret;
293            }
294        }
295
296        //Remove any unhandled events
297        if ( !mEventSignalQ.isEmpty() )
298            {
299            for (unsigned int i = 0 ; i < mEventSignalQ.size() ; i++ )
300                {
301                TIUTILS::Message *msg = mEventSignalQ.itemAt(i);
302                //remove from queue and free msg
303                mEventSignalQ.removeAt(i);
304                if ( NULL != msg )
305                    {
306                    free(msg);
307                    }
308                }
309            }
310
311        //Setting this flag will that the first setParameter call will apply all 3A settings
312        //and will not conditionally apply based on current values.
313        mFirstTimeInit = true;
314
315        memset(mExposureBracketingValues, 0, EXP_BRACKET_RANGE*sizeof(int));
316        mMeasurementEnabled = false;
317        mFaceDetectionRunning = false;
318
319        memset(&mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mImagePortIndex], 0, sizeof(OMXCameraPortParameters));
320        memset(&mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex], 0, sizeof(OMXCameraPortParameters));
321
322        // TODO(XXX): temporary hack. must remove after setconfig and transition issue
323        //            with secondary camera is fixed
324        mWaitToSetConfig = false;
325    }
326    LOG_FUNCTION_NAME_EXIT;
327    return ErrorUtils::omxToAndroidError(eError);
328
329    EXIT:
330
331    CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, ret, eError);
332
333    if(mCameraAdapterParameters.mHandleComp)
334        {
335        ///Free the OMX component handle in case of error
336        OMX_FreeHandle(mCameraAdapterParameters.mHandleComp);
337        }
338
339    ///De-init the OMX
340    OMX_Deinit();
341
342    LOG_FUNCTION_NAME_EXIT;
343
344    return ErrorUtils::omxToAndroidError(eError);
345}
346
347OMXCameraAdapter::OMXCameraPortParameters *OMXCameraAdapter::getPortParams(CameraFrame::FrameType frameType)
348{
349    OMXCameraAdapter::OMXCameraPortParameters *ret = NULL;
350
351    switch ( frameType )
352    {
353    case CameraFrame::IMAGE_FRAME:
354    case CameraFrame::RAW_FRAME:
355        ret = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mImagePortIndex];
356        break;
357    case CameraFrame::PREVIEW_FRAME_SYNC:
358    case CameraFrame::SNAPSHOT_FRAME:
359    case CameraFrame::VIDEO_FRAME_SYNC:
360        ret = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex];
361        break;
362    case CameraFrame::FRAME_DATA_SYNC:
363        ret = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mMeasurementPortIndex];
364        break;
365    default:
366        break;
367    };
368
369    return ret;
370}
371
372status_t OMXCameraAdapter::fillThisBuffer(void* frameBuf, CameraFrame::FrameType frameType)
373{
374    status_t ret = NO_ERROR;
375    OMXCameraPortParameters *port = NULL;
376    OMX_ERRORTYPE eError = OMX_ErrorNone;
377    BaseCameraAdapter::AdapterState state;
378    BaseCameraAdapter::getState(state);
379
380    if ( ( PREVIEW_ACTIVE & state ) != PREVIEW_ACTIVE )
381        {
382        return NO_INIT;
383        }
384
385    if ( NULL == frameBuf )
386        {
387        return -EINVAL;
388        }
389
390    if ( (NO_ERROR == ret) &&
391         ((CameraFrame::IMAGE_FRAME == frameType) || (CameraFrame::RAW_FRAME == frameType)) &&
392         (1 > mCapturedFrames) &&
393         (!mBracketingEnabled)) {
394        // Signal end of image capture
395        if ( NULL != mEndImageCaptureCallback) {
396            mEndImageCaptureCallback(mEndCaptureData);
397        }
398        return NO_ERROR;
399     }
400
401    if ( NO_ERROR == ret )
402        {
403        port = getPortParams(frameType);
404        if ( NULL == port )
405            {
406            CAMHAL_LOGEB("Invalid frameType 0x%x", frameType);
407            ret = -EINVAL;
408            }
409        }
410
411    if ( NO_ERROR == ret )
412        {
413
414        for ( int i = 0 ; i < port->mNumBufs ; i++)
415            {
416            if ( port->mBufferHeader[i]->pBuffer == frameBuf )
417                {
418                eError = OMX_FillThisBuffer(mCameraAdapterParameters.mHandleComp, port->mBufferHeader[i]);
419                if ( eError != OMX_ErrorNone )
420                    {
421                    CAMHAL_LOGDB("OMX_FillThisBuffer 0x%x", eError);
422                    ret = ErrorUtils::omxToAndroidError(eError);
423                    }
424                break;
425                }
426            }
427
428        }
429
430    return ret;
431}
432
433status_t OMXCameraAdapter::setParameters(const CameraParameters &params)
434{
435    LOG_FUNCTION_NAME;
436
437    const char * str = NULL;
438    int mode = 0;
439    status_t ret = NO_ERROR;
440    bool updateImagePortParams = false;
441    int minFramerate, maxFramerate, frameRate;
442    const char *valstr = NULL;
443    const char *oldstr = NULL;
444    int w, h;
445    OMX_COLOR_FORMATTYPE pixFormat;
446    BaseCameraAdapter::AdapterState state;
447    BaseCameraAdapter::getState(state);
448
449    ///@todo Include more camera parameters
450    if ( (valstr = params.getPreviewFormat()) != NULL )
451        {
452        if (strcmp(valstr, (const char *) CameraParameters::PIXEL_FORMAT_YUV422I) == 0)
453            {
454            CAMHAL_LOGDA("CbYCrY format selected");
455            pixFormat = OMX_COLOR_FormatCbYCrY;
456            }
457        else if(strcmp(valstr, (const char *) CameraParameters::PIXEL_FORMAT_YUV420SP) == 0 ||
458                strcmp(valstr, (const char *) CameraParameters::PIXEL_FORMAT_YUV420P) == 0)
459            {
460            CAMHAL_LOGDA("YUV420SP format selected");
461            pixFormat = OMX_COLOR_FormatYUV420SemiPlanar;
462            }
463        else if(strcmp(valstr, (const char *) CameraParameters::PIXEL_FORMAT_RGB565) == 0)
464            {
465            CAMHAL_LOGDA("RGB565 format selected");
466            pixFormat = OMX_COLOR_Format16bitRGB565;
467            }
468        else
469            {
470            CAMHAL_LOGDA("Invalid format, CbYCrY format selected as default");
471            pixFormat = OMX_COLOR_FormatCbYCrY;
472            }
473        }
474    else
475        {
476        CAMHAL_LOGEA("Preview format is NULL, defaulting to CbYCrY");
477        pixFormat = OMX_COLOR_FormatCbYCrY;
478        }
479
480    OMXCameraPortParameters *cap;
481    cap = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex];
482
483    params.getPreviewSize(&w, &h);
484    frameRate = params.getPreviewFrameRate();
485    minFramerate = params.getInt(TICameraParameters::KEY_MINFRAMERATE);
486    maxFramerate = params.getInt(TICameraParameters::KEY_MAXFRAMERATE);
487    if ( ( 0 < minFramerate ) &&
488         ( 0 < maxFramerate ) )
489        {
490        if ( minFramerate > maxFramerate )
491            {
492             CAMHAL_LOGEA(" Min FPS set higher than MAX. So setting MIN and MAX to the higher value");
493             maxFramerate = minFramerate;
494            }
495
496        if ( 0 >= frameRate )
497            {
498            frameRate = maxFramerate;
499            }
500
501        if( ( cap->mMinFrameRate != minFramerate ) ||
502            ( cap->mMaxFrameRate != maxFramerate ) )
503            {
504            cap->mMinFrameRate = minFramerate;
505            cap->mMaxFrameRate = maxFramerate;
506            setVFramerate(cap->mMinFrameRate, cap->mMaxFrameRate);
507            }
508        }
509
510    if ( 0 < frameRate )
511        {
512        cap->mColorFormat = pixFormat;
513        cap->mWidth = w;
514        cap->mHeight = h;
515        cap->mFrameRate = frameRate;
516
517        CAMHAL_LOGVB("Prev: cap.mColorFormat = %d", (int)cap->mColorFormat);
518        CAMHAL_LOGVB("Prev: cap.mWidth = %d", (int)cap->mWidth);
519        CAMHAL_LOGVB("Prev: cap.mHeight = %d", (int)cap->mHeight);
520        CAMHAL_LOGVB("Prev: cap.mFrameRate = %d", (int)cap->mFrameRate);
521
522        //TODO: Add an additional parameter for video resolution
523       //use preview resolution for now
524        cap = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex];
525        cap->mColorFormat = pixFormat;
526        cap->mWidth = w;
527        cap->mHeight = h;
528        cap->mFrameRate = frameRate;
529
530        CAMHAL_LOGVB("Video: cap.mColorFormat = %d", (int)cap->mColorFormat);
531        CAMHAL_LOGVB("Video: cap.mWidth = %d", (int)cap->mWidth);
532        CAMHAL_LOGVB("Video: cap.mHeight = %d", (int)cap->mHeight);
533        CAMHAL_LOGVB("Video: cap.mFrameRate = %d", (int)cap->mFrameRate);
534
535        ///mStride is set from setBufs() while passing the APIs
536        cap->mStride = 4096;
537        cap->mBufSize = cap->mStride * cap->mHeight;
538        }
539
540    if ( ( cap->mWidth >= 1920 ) &&
541         ( cap->mHeight >= 1080 ) &&
542         ( cap->mFrameRate >= FRAME_RATE_FULL_HD ) &&
543         ( !mSensorOverclock ) )
544        {
545        mOMXStateSwitch = true;
546        }
547    else if ( ( ( cap->mWidth < 1920 ) ||
548               ( cap->mHeight < 1080 ) ||
549               ( cap->mFrameRate < FRAME_RATE_FULL_HD ) ) &&
550               ( mSensorOverclock ) )
551        {
552        mOMXStateSwitch = true;
553        }
554
555    if ( (valstr = params.get(TICameraParameters::KEY_MEASUREMENT_ENABLE)) != NULL )
556        {
557        if (strcmp(valstr, (const char *) TICameraParameters::MEASUREMENT_ENABLE) == 0)
558            {
559            mMeasurementEnabled = true;
560            }
561        else if (strcmp(valstr, (const char *) TICameraParameters::MEASUREMENT_DISABLE) == 0)
562            {
563            mMeasurementEnabled = false;
564            }
565        else
566            {
567            mMeasurementEnabled = false;
568            }
569        }
570    else
571        {
572        //Disable measurement data by default
573        mMeasurementEnabled = false;
574        }
575
576    // TODO(XXX): temporary hack. must remove after setconfig and transition issue
577    //            with secondary camera is fixed
578    if (!mWaitToSetConfig) {
579        ret |= setParametersCapture(params, state);
580
581        ret |= setParameters3A(params, state);
582
583        ret |= setParametersAlgo(params, state);
584
585        ret |= setParametersFocus(params, state);
586
587        ret |= setParametersFD(params, state);
588
589        ret |= setParametersZoom(params, state);
590
591        ret |= setParametersEXIF(params, state);
592
593        mFirstTimeInit = false;
594    }
595
596    mParams = params;
597
598    LOG_FUNCTION_NAME_EXIT;
599    return ret;
600}
601
602void saveFile(unsigned char   *buff, int width, int height, int format) {
603    static int      counter = 1;
604    int             fd = -1;
605    char            fn[256];
606
607    LOG_FUNCTION_NAME;
608
609    fn[0] = 0;
610    sprintf(fn, "/preview%03d.yuv", counter);
611    fd = open(fn, O_CREAT | O_WRONLY | O_SYNC | O_TRUNC, 0777);
612    if(fd < 0) {
613        LOGE("Unable to open file %s: %s", fn, strerror(fd));
614        return;
615    }
616
617    CAMHAL_LOGVB("Copying from 0x%x, size=%d x %d", buff, width, height);
618
619    //method currently supports only nv12 dumping
620    int stride = width;
621    uint8_t *bf = (uint8_t*) buff;
622    for(int i=0;i<height;i++)
623        {
624        write(fd, bf, width);
625        bf += 4096;
626        }
627
628    for(int i=0;i<height/2;i++)
629        {
630        write(fd, bf, stride);
631        bf += 4096;
632        }
633
634    close(fd);
635
636
637    counter++;
638
639    LOG_FUNCTION_NAME_EXIT;
640}
641
642void OMXCameraAdapter::getParameters(CameraParameters& params)
643{
644    status_t ret = NO_ERROR;
645    OMX_CONFIG_EXPOSUREVALUETYPE exp;
646    OMX_ERRORTYPE eError = OMX_ErrorNone;
647    BaseCameraAdapter::AdapterState state;
648    BaseCameraAdapter::getState(state);
649    const char *valstr = NULL;
650    LOG_FUNCTION_NAME;
651
652#ifdef PARAM_FEEDBACK
653
654    OMX_CONFIG_WHITEBALCONTROLTYPE wb;
655    OMX_CONFIG_FLICKERCANCELTYPE flicker;
656    OMX_CONFIG_SCENEMODETYPE scene;
657    OMX_IMAGE_PARAM_FLASHCONTROLTYPE flash;
658    OMX_CONFIG_BRIGHTNESSTYPE brightness;
659    OMX_CONFIG_CONTRASTTYPE contrast;
660    OMX_IMAGE_CONFIG_PROCESSINGLEVELTYPE procSharpness;
661    OMX_CONFIG_SATURATIONTYPE saturation;
662    OMX_CONFIG_IMAGEFILTERTYPE effect;
663    OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE focus;
664
665    exp.nSize = sizeof(OMX_CONFIG_EXPOSURECONTROLTYPE);
666    exp.nVersion = mLocalVersionParam;
667    exp.nPortIndex = OMX_ALL;
668
669    expValues.nSize = sizeof(OMX_CONFIG_EXPOSUREVALUETYPE);
670    expValues.nVersion = mLocalVersionParam;
671    expValues.nPortIndex = OMX_ALL;
672
673    wb.nSize = sizeof(OMX_CONFIG_WHITEBALCONTROLTYPE);
674    wb.nVersion = mLocalVersionParam;
675    wb.nPortIndex = OMX_ALL;
676
677    flicker.nSize = sizeof(OMX_CONFIG_FLICKERCANCELTYPE);
678    flicker.nVersion = mLocalVersionParam;
679    flicker.nPortIndex = OMX_ALL;
680
681    scene.nSize = sizeof(OMX_CONFIG_SCENEMODETYPE);
682    scene.nVersion = mLocalVersionParam;
683    scene.nPortIndex = mCameraAdapterParameters.mPrevPortIndex;
684
685    flash.nSize = sizeof(OMX_IMAGE_PARAM_FLASHCONTROLTYPE);
686    flash.nVersion = mLocalVersionParam;
687    flash.nPortIndex = OMX_ALL;
688
689
690    brightness.nSize = sizeof(OMX_CONFIG_BRIGHTNESSTYPE);
691    brightness.nVersion = mLocalVersionParam;
692    brightness.nPortIndex = OMX_ALL;
693
694    contrast.nSize = sizeof(OMX_CONFIG_CONTRASTTYPE);
695    contrast.nVersion = mLocalVersionParam;
696    contrast.nPortIndex = OMX_ALL;
697
698    procSharpness.nSize = sizeof( OMX_IMAGE_CONFIG_PROCESSINGLEVELTYPE );
699    procSharpness.nVersion = mLocalVersionParam;
700    procSharpness.nPortIndex = OMX_ALL;
701
702    saturation.nSize = sizeof(OMX_CONFIG_SATURATIONTYPE);
703    saturation.nVersion = mLocalVersionParam;
704    saturation.nPortIndex = OMX_ALL;
705
706    effect.nSize = sizeof(OMX_CONFIG_IMAGEFILTERTYPE);
707    effect.nVersion = mLocalVersionParam;
708    effect.nPortIndex = OMX_ALL;
709
710    focus.nSize = sizeof(OMX_IMAGE_CONFIG_FOCUSCONTROLTYPE);
711    focus.nVersion = mLocalVersionParam;
712    focus.nPortIndex = OMX_ALL;
713
714    OMX_GetConfig( mCameraAdapterParameters.mHandleComp,OMX_IndexConfigCommonExposure, &exp);
715    OMX_GetConfig( mCameraAdapterParameters.mHandleComp, OMX_IndexConfigCommonWhiteBalance, &wb);
716    OMX_GetConfig( mCameraAdapterParameters.mHandleComp, (OMX_INDEXTYPE)OMX_IndexConfigFlickerCancel, &flicker );
717    OMX_GetConfig( mCameraAdapterParameters.mHandleComp, (OMX_INDEXTYPE)OMX_IndexParamSceneMode, &scene);
718    OMX_GetParameter( mCameraAdapterParameters.mHandleComp, (OMX_INDEXTYPE)OMX_IndexParamFlashControl, &flash);
719    OMX_GetConfig( mCameraAdapterParameters.mHandleComp, OMX_IndexConfigCommonBrightness, &brightness);
720    OMX_GetConfig( mCameraAdapterParameters.mHandleComp, OMX_IndexConfigCommonContrast, &contrast);
721    OMX_GetConfig( mCameraAdapterParameters.mHandleComp, (OMX_INDEXTYPE)OMX_IndexConfigSharpeningLevel, &procSharpness);
722    OMX_GetConfig( mCameraAdapterParameters.mHandleComp, OMX_IndexConfigCommonSaturation, &saturation);
723    OMX_GetConfig( mCameraAdapterParameters.mHandleComp, OMX_IndexConfigCommonImageFilter, &effect);
724    OMX_GetConfig( mCameraAdapterParameters.mHandleComp, OMX_IndexConfigFocusControl, &focus);
725
726    char * str = NULL;
727
728    for(int i = 0; i < ExpLUT.size; i++)
729        if( ExpLUT.Table[i].omxDefinition == exp.eExposureControl )
730            str = (char*)ExpLUT.Table[i].userDefinition;
731    params.set( TICameraParameters::KEY_EXPOSURE_MODE , str);
732
733    for(int i = 0; i < WBalLUT.size; i++)
734        if( WBalLUT.Table[i].omxDefinition == wb.eWhiteBalControl )
735            str = (char*)WBalLUT.Table[i].userDefinition;
736    params.set( CameraParameters::KEY_WHITE_BALANCE , str );
737
738    for(int i = 0; i < FlickerLUT.size; i++)
739        if( FlickerLUT.Table[i].omxDefinition == flicker.eFlickerCancel )
740            str = (char*)FlickerLUT.Table[i].userDefinition;
741    params.set( CameraParameters::KEY_ANTIBANDING , str );
742
743    for(int i = 0; i < SceneLUT.size; i++)
744        if( SceneLUT.Table[i].omxDefinition == scene.eSceneMode )
745            str = (char*)SceneLUT.Table[i].userDefinition;
746    params.set( CameraParameters::KEY_SCENE_MODE , str );
747
748    for(int i = 0; i < FlashLUT.size; i++)
749        if( FlashLUT.Table[i].omxDefinition == flash.eFlashControl )
750            str = (char*)FlashLUT.Table[i].userDefinition;
751    params.set( CameraParameters::KEY_FLASH_MODE, str );
752
753    for(int i = 0; i < EffLUT.size; i++)
754        if( EffLUT.Table[i].omxDefinition == effect.eImageFilter )
755            str = (char*)EffLUT.Table[i].userDefinition;
756    params.set( CameraParameters::KEY_EFFECT , str );
757
758    for(int i = 0; i < FocusLUT.size; i++)
759        if( FocusLUT.Table[i].omxDefinition == focus.eFocusControl )
760            str = (char*)FocusLUT.Table[i].userDefinition;
761
762    params.set( CameraParameters::KEY_FOCUS_MODE , str );
763
764    int comp = ((expValues.xEVCompensation * 10) >> Q16_OFFSET);
765
766    params.set(CameraParameters::KEY_EXPOSURE_COMPENSATION, comp );
767    params.set( TICameraParameters::KEY_MAN_EXPOSURE, expValues.nShutterSpeedMsec);
768    params.set( TICameraParameters::KEY_BRIGHTNESS, brightness.nBrightness);
769    params.set( TICameraParameters::KEY_CONTRAST, contrast.nContrast );
770    params.set( TICameraParameters::KEY_SHARPNESS, procSharpness.nLevel);
771    params.set( TICameraParameters::KEY_SATURATION, saturation.nSaturation);
772
773#else
774
775    //Query focus distances only during CAF, Infinity
776    //or when focus is running
777    if ( ( AF_ACTIVE & state ) ||
778         ( mParameters3A.Focus == OMX_IMAGE_FocusControlAuto )  ||
779         ( mParameters3A.Focus == OMX_IMAGE_FocusControlAutoInfinity ) ||
780         ( NULL == mParameters.get(CameraParameters::KEY_FOCUS_DISTANCES) ) )
781        {
782        updateFocusDistances(params);
783        }
784    else
785        {
786        params.set(CameraParameters::KEY_FOCUS_DISTANCES,
787                   mParameters.get(CameraParameters::KEY_FOCUS_DISTANCES));
788        }
789
790    OMX_INIT_STRUCT_PTR (&exp, OMX_CONFIG_EXPOSUREVALUETYPE);
791    exp.nPortIndex = OMX_ALL;
792
793    eError = OMX_GetConfig(mCameraAdapterParameters.mHandleComp,
794                           OMX_IndexConfigCommonExposureValue,
795                           &exp);
796    if ( OMX_ErrorNone == eError )
797        {
798        params.set(TICameraParameters::KEY_CURRENT_ISO, exp.nSensitivity);
799        }
800    else
801        {
802        CAMHAL_LOGEB("OMX error 0x%x, while retrieving current ISO value", eError);
803        }
804
805    {
806    Mutex::Autolock lock(mZoomLock);
807    //Immediate zoom should not be avaialable while smooth zoom is running
808    if ( ZOOM_ACTIVE & state )
809        {
810        if ( mZoomParameterIdx != mCurrentZoomIdx )
811            {
812            mZoomParameterIdx += mZoomInc;
813            }
814        params.set( CameraParameters::KEY_ZOOM, mZoomParameterIdx);
815        if ( ( mCurrentZoomIdx == mTargetZoomIdx ) &&
816             ( mZoomParameterIdx == mCurrentZoomIdx ) )
817            {
818
819            if ( NO_ERROR == ret )
820                {
821
822                ret =  BaseCameraAdapter::setState(CAMERA_STOP_SMOOTH_ZOOM);
823
824                if ( NO_ERROR == ret )
825                    {
826                    ret = BaseCameraAdapter::commitState();
827                    }
828                else
829                    {
830                    ret |= BaseCameraAdapter::rollbackState();
831                    }
832
833                }
834
835            }
836
837        CAMHAL_LOGDB("CameraParameters Zoom = %d", mCurrentZoomIdx);
838        }
839    else
840        {
841        params.set( CameraParameters::KEY_ZOOM, mCurrentZoomIdx);
842        }
843    }
844
845    //Populate current lock status
846    if( (valstr = mParams.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK)) != NULL )
847      {
848        CAMHAL_LOGDB("Auto Exposure Lock get %s", mParams.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK));
849        params.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK, valstr);
850      }
851    if( (valstr = mParams.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK)) != NULL )
852      {
853        CAMHAL_LOGDB("Auto WhiteBalance Lock get %s", mParams.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK));
854        params.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK, valstr);
855      }
856
857#endif
858
859    LOG_FUNCTION_NAME_EXIT;
860}
861
862status_t OMXCameraAdapter::setFormat(OMX_U32 port, OMXCameraPortParameters &portParams)
863{
864    size_t bufferCount;
865
866    LOG_FUNCTION_NAME;
867
868    OMX_ERRORTYPE eError = OMX_ErrorNone;
869    OMX_PARAM_PORTDEFINITIONTYPE portCheck;
870
871    OMX_INIT_STRUCT_PTR (&portCheck, OMX_PARAM_PORTDEFINITIONTYPE);
872
873    portCheck.nPortIndex = port;
874
875    eError = OMX_GetParameter (mCameraAdapterParameters.mHandleComp,
876                                OMX_IndexParamPortDefinition, &portCheck);
877    if(eError!=OMX_ErrorNone)
878        {
879        CAMHAL_LOGEB("OMX_GetParameter - %x", eError);
880        }
881    GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
882
883    if ( OMX_CAMERA_PORT_VIDEO_OUT_PREVIEW == port )
884        {
885        portCheck.format.video.nFrameWidth      = portParams.mWidth;
886        portCheck.format.video.nFrameHeight     = portParams.mHeight;
887        portCheck.format.video.eColorFormat     = portParams.mColorFormat;
888        portCheck.format.video.nStride          = portParams.mStride;
889        if( ( portCheck.format.video.nFrameWidth >= 1920 ) &&
890            ( portCheck.format.video.nFrameHeight >= 1080 ) &&
891            ( portParams.mFrameRate >= FRAME_RATE_FULL_HD ) )
892            {
893            setSensorOverclock(true);
894            }
895        else
896            {
897            setSensorOverclock(false);
898            }
899
900        portCheck.format.video.xFramerate       = portParams.mFrameRate<<16;
901        portCheck.nBufferSize                   = portParams.mStride * portParams.mHeight;
902        portCheck.nBufferCountActual = portParams.mNumBufs;
903        mFocusThreshold = FOCUS_THRESHOLD * portParams.mFrameRate;
904        }
905    else if ( OMX_CAMERA_PORT_IMAGE_OUT_IMAGE == port )
906        {
907        portCheck.format.image.nFrameWidth      = portParams.mWidth;
908        portCheck.format.image.nFrameHeight     = portParams.mHeight;
909        if ( OMX_COLOR_FormatUnused == portParams.mColorFormat && mCodingMode == CodingNone )
910            {
911            portCheck.format.image.eColorFormat     = OMX_COLOR_FormatCbYCrY;
912            portCheck.format.image.eCompressionFormat = OMX_IMAGE_CodingJPEG;
913            }
914        else if ( OMX_COLOR_FormatUnused == portParams.mColorFormat && mCodingMode == CodingJPS )
915            {
916            portCheck.format.image.eColorFormat       = OMX_COLOR_FormatCbYCrY;
917            portCheck.format.image.eCompressionFormat = (OMX_IMAGE_CODINGTYPE) OMX_TI_IMAGE_CodingJPS;
918            }
919        else if ( OMX_COLOR_FormatUnused == portParams.mColorFormat && mCodingMode == CodingMPO )
920            {
921            portCheck.format.image.eColorFormat       = OMX_COLOR_FormatCbYCrY;
922            portCheck.format.image.eCompressionFormat = (OMX_IMAGE_CODINGTYPE) OMX_TI_IMAGE_CodingMPO;
923            }
924        else if ( OMX_COLOR_FormatUnused == portParams.mColorFormat && mCodingMode == CodingRAWJPEG )
925            {
926            //TODO: OMX_IMAGE_CodingJPEG should be changed to OMX_IMAGE_CodingRAWJPEG when
927            // RAW format is supported
928            portCheck.format.image.eColorFormat       = OMX_COLOR_FormatCbYCrY;
929            portCheck.format.image.eCompressionFormat = OMX_IMAGE_CodingJPEG;
930            }
931        else if ( OMX_COLOR_FormatUnused == portParams.mColorFormat && mCodingMode == CodingRAWMPO )
932            {
933            //TODO: OMX_IMAGE_CodingJPEG should be changed to OMX_IMAGE_CodingRAWMPO when
934            // RAW format is supported
935            portCheck.format.image.eColorFormat       = OMX_COLOR_FormatCbYCrY;
936            portCheck.format.image.eCompressionFormat = OMX_IMAGE_CodingJPEG;
937            }
938        else
939            {
940            portCheck.format.image.eColorFormat     = portParams.mColorFormat;
941            portCheck.format.image.eCompressionFormat = OMX_IMAGE_CodingUnused;
942            }
943
944        //Stride for 1D tiler buffer is zero
945        portCheck.format.image.nStride          =  0;
946        portCheck.nBufferSize                   =  portParams.mStride * portParams.mWidth * portParams.mHeight;
947        portCheck.nBufferCountActual = portParams.mNumBufs;
948        }
949    else
950        {
951        CAMHAL_LOGEB("Unsupported port index 0x%x", (unsigned int)port);
952        }
953
954    eError = OMX_SetParameter(mCameraAdapterParameters.mHandleComp,
955                            OMX_IndexParamPortDefinition, &portCheck);
956    if(eError!=OMX_ErrorNone)
957        {
958        CAMHAL_LOGEB("OMX_SetParameter - %x", eError);
959        }
960    GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
961
962    /* check if parameters are set correctly by calling GetParameter() */
963    eError = OMX_GetParameter(mCameraAdapterParameters.mHandleComp,
964                                        OMX_IndexParamPortDefinition, &portCheck);
965    if(eError!=OMX_ErrorNone)
966        {
967        CAMHAL_LOGEB("OMX_GetParameter - %x", eError);
968        }
969    GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
970
971    portParams.mBufSize = portCheck.nBufferSize;
972
973    if ( OMX_CAMERA_PORT_IMAGE_OUT_IMAGE == port )
974        {
975        CAMHAL_LOGDB("\n *** IMG Width = %ld", portCheck.format.image.nFrameWidth);
976        CAMHAL_LOGDB("\n ***IMG Height = %ld", portCheck.format.image.nFrameHeight);
977
978        CAMHAL_LOGDB("\n ***IMG IMG FMT = %x", portCheck.format.image.eColorFormat);
979        CAMHAL_LOGDB("\n ***IMG portCheck.nBufferSize = %ld\n",portCheck.nBufferSize);
980        CAMHAL_LOGDB("\n ***IMG portCheck.nBufferCountMin = %ld\n",
981                                                portCheck.nBufferCountMin);
982        CAMHAL_LOGDB("\n ***IMG portCheck.nBufferCountActual = %ld\n",
983                                                portCheck.nBufferCountActual);
984        CAMHAL_LOGDB("\n ***IMG portCheck.format.image.nStride = %ld\n",
985                                                portCheck.format.image.nStride);
986        }
987    else
988        {
989        CAMHAL_LOGDB("\n *** PRV Width = %ld", portCheck.format.video.nFrameWidth);
990        CAMHAL_LOGDB("\n ***PRV Height = %ld", portCheck.format.video.nFrameHeight);
991
992        CAMHAL_LOGDB("\n ***PRV IMG FMT = %x", portCheck.format.video.eColorFormat);
993        CAMHAL_LOGDB("\n ***PRV portCheck.nBufferSize = %ld\n",portCheck.nBufferSize);
994        CAMHAL_LOGDB("\n ***PRV portCheck.nBufferCountMin = %ld\n",
995                                                portCheck.nBufferCountMin);
996        CAMHAL_LOGDB("\n ***PRV portCheck.nBufferCountActual = %ld\n",
997                                                portCheck.nBufferCountActual);
998        CAMHAL_LOGDB("\n ***PRV portCheck.format.video.nStride = %ld\n",
999                                                portCheck.format.video.nStride);
1000        }
1001
1002    LOG_FUNCTION_NAME_EXIT;
1003
1004    return ErrorUtils::omxToAndroidError(eError);
1005
1006    EXIT:
1007
1008    CAMHAL_LOGEB("Exiting function %s because of eError=%x", __FUNCTION__, eError);
1009
1010    LOG_FUNCTION_NAME_EXIT;
1011
1012    return ErrorUtils::omxToAndroidError(eError);
1013}
1014
1015status_t OMXCameraAdapter::flushBuffers()
1016{
1017    status_t ret = NO_ERROR;
1018    OMX_ERRORTYPE eError = OMX_ErrorNone;
1019    TIMM_OSAL_ERRORTYPE err;
1020    TIMM_OSAL_U32 uRequestedEvents = OMXCameraAdapter::CAMERA_PORT_FLUSH;
1021    TIMM_OSAL_U32 pRetrievedEvents;
1022
1023    if ( 0 != mFlushSem.Count() )
1024        {
1025        CAMHAL_LOGEB("Error mFlushSem semaphore count %d", mFlushSem.Count());
1026        LOG_FUNCTION_NAME_EXIT;
1027        return NO_INIT;
1028        }
1029
1030    LOG_FUNCTION_NAME;
1031
1032    OMXCameraPortParameters * mPreviewData = NULL;
1033    mPreviewData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex];
1034
1035    ///Register for the FLUSH event
1036    ///This method just inserts a message in Event Q, which is checked in the callback
1037    ///The sempahore passed is signalled by the callback
1038    ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
1039                                OMX_EventCmdComplete,
1040                                OMX_CommandFlush,
1041                                OMX_CAMERA_PORT_VIDEO_OUT_PREVIEW,
1042                                mFlushSem);
1043    if(ret!=NO_ERROR)
1044        {
1045        CAMHAL_LOGEB("Error in registering for event %d", ret);
1046        goto EXIT;
1047        }
1048
1049    ///Send FLUSH command to preview port
1050    eError = OMX_SendCommand (mCameraAdapterParameters.mHandleComp,
1051                              OMX_CommandFlush,
1052                              mCameraAdapterParameters.mPrevPortIndex,
1053                              NULL);
1054
1055    if(eError!=OMX_ErrorNone)
1056        {
1057        CAMHAL_LOGEB("OMX_SendCommand(OMX_CommandFlush)-0x%x", eError);
1058        }
1059    GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
1060
1061    CAMHAL_LOGDA("Waiting for flush event");
1062
1063    ///Wait for the FLUSH event to occur
1064    ret = mFlushSem.WaitTimeout(OMX_CMD_TIMEOUT);
1065    if ( NO_ERROR == ret )
1066        {
1067        CAMHAL_LOGDA("Flush event received");
1068        }
1069    else
1070        {
1071        ret |= SignalEvent(mCameraAdapterParameters.mHandleComp,
1072                           OMX_EventCmdComplete,
1073                           OMX_CommandFlush,
1074                           OMX_CAMERA_PORT_VIDEO_OUT_PREVIEW,
1075                           NULL);
1076        CAMHAL_LOGDA("Flush event timeout expired");
1077        goto EXIT;
1078        }
1079
1080    LOG_FUNCTION_NAME_EXIT;
1081
1082    return (ret | ErrorUtils::omxToAndroidError(eError));
1083
1084    EXIT:
1085    CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, ret, eError);
1086    LOG_FUNCTION_NAME_EXIT;
1087
1088    return (ret | ErrorUtils::omxToAndroidError(eError));
1089}
1090
1091///API to give the buffers to Adapter
1092status_t OMXCameraAdapter::useBuffers(CameraMode mode, void* bufArr, int num, size_t length, unsigned int queueable)
1093{
1094    OMX_ERRORTYPE eError = OMX_ErrorNone;
1095    status_t ret = NO_ERROR;
1096
1097    LOG_FUNCTION_NAME;
1098
1099    switch(mode)
1100        {
1101        case CAMERA_PREVIEW:
1102            mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex].mNumBufs =  num;
1103            mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex].mMaxQueueable = queueable;
1104            ret = UseBuffersPreview(bufArr, num);
1105            break;
1106
1107        case CAMERA_IMAGE_CAPTURE:
1108            mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mImagePortIndex].mNumBufs = num;
1109            mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mImagePortIndex].mMaxQueueable = queueable;
1110            ret = UseBuffersCapture(bufArr, num);
1111            break;
1112
1113        case CAMERA_VIDEO:
1114            mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex].mNumBufs =  num;
1115            mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex].mMaxQueueable = queueable;
1116            ret = UseBuffersPreview(bufArr, num);
1117            break;
1118
1119        case CAMERA_MEASUREMENT:
1120            mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mMeasurementPortIndex].mNumBufs = num;
1121            mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mMeasurementPortIndex].mMaxQueueable = queueable;
1122            ret = UseBuffersPreviewData(bufArr, num);
1123            break;
1124
1125        }
1126
1127    LOG_FUNCTION_NAME_EXIT;
1128
1129    return ret;
1130}
1131
1132status_t OMXCameraAdapter::UseBuffersPreviewData(void* bufArr, int num)
1133{
1134    status_t ret = NO_ERROR;
1135    OMX_ERRORTYPE eError = OMX_ErrorNone;
1136    OMXCameraPortParameters * measurementData = NULL;
1137    uint32_t *buffers;
1138    Mutex::Autolock lock( mPreviewDataBufferLock);
1139
1140    LOG_FUNCTION_NAME;
1141
1142    if ( mComponentState != OMX_StateLoaded )
1143        {
1144        CAMHAL_LOGEA("Calling UseBuffersPreviewData() when not in LOADED state");
1145        ret = BAD_VALUE;
1146        }
1147
1148    if ( NULL == bufArr )
1149        {
1150        CAMHAL_LOGEA("NULL pointer passed for buffArr");
1151        ret = BAD_VALUE;
1152        }
1153
1154    if ( 0 != mUsePreviewDataSem.Count() )
1155        {
1156        CAMHAL_LOGEB("Error mUsePreviewDataSem semaphore count %d", mUsePreviewDataSem.Count());
1157        LOG_FUNCTION_NAME_EXIT;
1158        return NO_INIT;
1159        }
1160
1161    if ( NO_ERROR == ret )
1162        {
1163        measurementData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mMeasurementPortIndex];
1164        measurementData->mNumBufs = num ;
1165        buffers= (uint32_t*) bufArr;
1166        }
1167
1168    if ( NO_ERROR == ret )
1169        {
1170         ///Register for port enable event on measurement port
1171        ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
1172                                      OMX_EventCmdComplete,
1173                                      OMX_CommandPortEnable,
1174                                      mCameraAdapterParameters.mMeasurementPortIndex,
1175                                      mUsePreviewDataSem);
1176
1177        if ( ret == NO_ERROR )
1178            {
1179            CAMHAL_LOGDB("Registering for event %d", ret);
1180            }
1181        else
1182            {
1183            CAMHAL_LOGEB("Error in registering for event %d", ret);
1184            ret = BAD_VALUE;
1185            }
1186        }
1187
1188    if ( NO_ERROR == ret )
1189        {
1190         ///Enable MEASUREMENT Port
1191         eError = OMX_SendCommand(mCameraAdapterParameters.mHandleComp,
1192                                      OMX_CommandPortEnable,
1193                                      mCameraAdapterParameters.mMeasurementPortIndex,
1194                                      NULL);
1195
1196            if ( eError == OMX_ErrorNone )
1197                {
1198                CAMHAL_LOGDB("OMX_SendCommand(OMX_CommandPortEnable) -0x%x", eError);
1199                }
1200            else
1201                {
1202                CAMHAL_LOGEB("OMX_SendCommand(OMX_CommandPortEnable) -0x%x", eError);
1203                ret = BAD_VALUE;
1204                }
1205        }
1206
1207    if ( NO_ERROR == ret )
1208        {
1209        ret = mUsePreviewDataSem.WaitTimeout(OMX_CMD_TIMEOUT);
1210
1211        if ( NO_ERROR == ret )
1212            {
1213            CAMHAL_LOGDA("Port enable event arrived on measurement port");
1214            }
1215        else
1216            {
1217            ret |= SignalEvent(mCameraAdapterParameters.mHandleComp,
1218                               OMX_EventCmdComplete,
1219                               OMX_CommandPortEnable,
1220                               mCameraAdapterParameters.mMeasurementPortIndex,
1221                               NULL);
1222            CAMHAL_LOGEA("Timeout expoired during port enable on measurement port");
1223            }
1224
1225        CAMHAL_LOGDA("Port enable event arrived on measurement port");
1226        }
1227
1228    LOG_FUNCTION_NAME_EXIT;
1229
1230    return ret;
1231}
1232
1233status_t OMXCameraAdapter::switchToLoaded()
1234{
1235    status_t ret = NO_ERROR;
1236    OMX_ERRORTYPE eError = OMX_ErrorNone;
1237
1238    LOG_FUNCTION_NAME;
1239
1240    if ( mComponentState == OMX_StateLoaded )
1241        {
1242        CAMHAL_LOGDA("Already in OMX_Loaded state");
1243        goto EXIT;
1244        }
1245
1246    if ( 0 != mSwitchToLoadedSem.Count() )
1247        {
1248        CAMHAL_LOGEB("Error mSwitchToLoadedSem semaphore count %d", mSwitchToLoadedSem.Count());
1249        goto EXIT;
1250        }
1251
1252    ///Register for EXECUTING state transition.
1253    ///This method just inserts a message in Event Q, which is checked in the callback
1254    ///The sempahore passed is signalled by the callback
1255    ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
1256                           OMX_EventCmdComplete,
1257                           OMX_CommandStateSet,
1258                           OMX_StateIdle,
1259                           mSwitchToLoadedSem);
1260
1261    if(ret!=NO_ERROR)
1262        {
1263        CAMHAL_LOGEB("Error in registering for event %d", ret);
1264        goto EXIT;
1265        }
1266
1267    eError = OMX_SendCommand (mCameraAdapterParameters.mHandleComp,
1268                              OMX_CommandStateSet,
1269                              OMX_StateIdle,
1270                              NULL);
1271
1272    if(eError!=OMX_ErrorNone)
1273        {
1274        CAMHAL_LOGEB("OMX_SendCommand(OMX_StateIdle) - %x", eError);
1275        }
1276
1277    GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
1278
1279    ///Wait for the EXECUTING ->IDLE transition to arrive
1280
1281    CAMHAL_LOGDA("EXECUTING->IDLE state changed");
1282    ret = mSwitchToLoadedSem.WaitTimeout(OMX_CMD_TIMEOUT);
1283    if ( NO_ERROR == ret )
1284        {
1285        CAMHAL_LOGDA("EXECUTING->IDLE state changed");
1286        }
1287    else
1288        {
1289        ret |= SignalEvent(mCameraAdapterParameters.mHandleComp,
1290                           OMX_EventCmdComplete,
1291                           OMX_CommandStateSet,
1292                           OMX_StateIdle,
1293                           NULL);
1294        CAMHAL_LOGEA("Timeout expired on EXECUTING->IDLE state change");
1295        goto EXIT;
1296        }
1297
1298    ///Register for LOADED state transition.
1299    ///This method just inserts a message in Event Q, which is checked in the callback
1300    ///The sempahore passed is signalled by the callback
1301    ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
1302                           OMX_EventCmdComplete,
1303                           OMX_CommandStateSet,
1304                           OMX_StateLoaded,
1305                           mSwitchToLoadedSem);
1306
1307    if(ret!=NO_ERROR)
1308        {
1309        CAMHAL_LOGEB("Error in registering for event %d", ret);
1310        goto EXIT;
1311        }
1312
1313    eError = OMX_SendCommand (mCameraAdapterParameters.mHandleComp,
1314                              OMX_CommandStateSet,
1315                              OMX_StateLoaded,
1316                              NULL);
1317
1318    if(eError!=OMX_ErrorNone)
1319        {
1320        CAMHAL_LOGEB("OMX_SendCommand(OMX_StateLoaded) - %x", eError);
1321        }
1322    GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
1323
1324    CAMHAL_LOGDA("Switching IDLE->LOADED state");
1325    ret = mSwitchToLoadedSem.WaitTimeout(OMX_CMD_TIMEOUT);
1326    if ( NO_ERROR == ret )
1327        {
1328        CAMHAL_LOGDA("IDLE->LOADED state changed");
1329        }
1330    else
1331        {
1332        ret |= SignalEvent(mCameraAdapterParameters.mHandleComp,
1333                           OMX_EventCmdComplete,
1334                           OMX_CommandStateSet,
1335                           OMX_StateLoaded,
1336                           NULL);
1337        CAMHAL_LOGEA("Timeout expired on IDLE->LOADED state change");
1338        goto EXIT;
1339        }
1340
1341    mComponentState = OMX_StateLoaded;
1342
1343    ///Register for Preview port ENABLE event
1344    ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
1345                           OMX_EventCmdComplete,
1346                           OMX_CommandPortEnable,
1347                           mCameraAdapterParameters.mPrevPortIndex,
1348                           mSwitchToLoadedSem);
1349
1350    if ( NO_ERROR != ret )
1351        {
1352        CAMHAL_LOGEB("Error in registering for event %d", ret);
1353        goto EXIT;
1354        }
1355
1356    ///Enable Preview Port
1357    eError = OMX_SendCommand(mCameraAdapterParameters.mHandleComp,
1358                             OMX_CommandPortEnable,
1359                             mCameraAdapterParameters.mPrevPortIndex,
1360                             NULL);
1361
1362    CAMHAL_LOGDB("OMX_SendCommand(OMX_CommandStateSet) 0x%x", eError);
1363
1364    GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
1365
1366    CAMHAL_LOGDA("Enabling Preview port");
1367    ///Wait for state to switch to idle
1368    ret = mSwitchToLoadedSem.WaitTimeout(OMX_CMD_TIMEOUT);
1369    if ( NO_ERROR == ret )
1370        {
1371        CAMHAL_LOGDA("Preview port enabled!");
1372        }
1373    else
1374        {
1375        ret |= SignalEvent(mCameraAdapterParameters.mHandleComp,
1376                           OMX_EventCmdComplete,
1377                           OMX_CommandPortEnable,
1378                           mCameraAdapterParameters.mPrevPortIndex,
1379                           NULL);
1380        CAMHAL_LOGEA("Preview enable timedout");
1381        goto EXIT;
1382        }
1383
1384    EXIT:
1385
1386    LOG_FUNCTION_NAME_EXIT;
1387
1388    return ret;
1389}
1390
1391status_t OMXCameraAdapter::UseBuffersPreview(void* bufArr, int num)
1392{
1393    status_t ret = NO_ERROR;
1394    OMX_ERRORTYPE eError = OMX_ErrorNone;
1395    int tmpHeight, tmpWidth;
1396
1397    LOG_FUNCTION_NAME;
1398
1399    ///Flag to determine whether it is 3D camera or not
1400    bool isS3d = false;
1401    const char *valstr = NULL;
1402    if ( (valstr = mParams.get(TICameraParameters::KEY_S3D_SUPPORTED)) != NULL) {
1403        isS3d = (strcmp(valstr, "true") == 0);
1404    }
1405
1406    if(!bufArr)
1407        {
1408        CAMHAL_LOGEA("NULL pointer passed for buffArr");
1409        LOG_FUNCTION_NAME_EXIT;
1410        return BAD_VALUE;
1411        }
1412
1413    OMXCameraPortParameters * mPreviewData = NULL;
1414    OMXCameraPortParameters *measurementData = NULL;
1415    mPreviewData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex];
1416    measurementData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mMeasurementPortIndex];
1417    mPreviewData->mNumBufs = num ;
1418    uint32_t *buffers = (uint32_t*)bufArr;
1419
1420    if ( 0 != mUsePreviewSem.Count() )
1421        {
1422        CAMHAL_LOGEB("Error mUsePreviewSem semaphore count %d", mUsePreviewSem.Count());
1423        LOG_FUNCTION_NAME_EXIT;
1424        return NO_INIT;
1425        }
1426
1427    if(mPreviewData->mNumBufs != num)
1428        {
1429        CAMHAL_LOGEA("Current number of buffers doesnt equal new num of buffers passed!");
1430        LOG_FUNCTION_NAME_EXIT;
1431        return BAD_VALUE;
1432        }
1433
1434    if ( mComponentState == OMX_StateLoaded )
1435        {
1436
1437        ret = setLDC(mIPP);
1438        if ( NO_ERROR != ret )
1439            {
1440            CAMHAL_LOGEB("setLDC() failed %d", ret);
1441            LOG_FUNCTION_NAME_EXIT;
1442            return ret;
1443            }
1444
1445        ret = setNSF(mIPP);
1446        if ( NO_ERROR != ret )
1447            {
1448            CAMHAL_LOGEB("setNSF() failed %d", ret);
1449            LOG_FUNCTION_NAME_EXIT;
1450            return ret;
1451            }
1452
1453        ret = setCaptureMode(mCapMode);
1454        if ( NO_ERROR != ret )
1455            {
1456            CAMHAL_LOGEB("setCaptureMode() failed %d", ret);
1457            LOG_FUNCTION_NAME_EXIT;
1458            return ret;
1459            }
1460
1461        CAMHAL_LOGDB("Camera Mode = %d", mCapMode);
1462
1463        if( ( mCapMode == OMXCameraAdapter::VIDEO_MODE ) ||
1464            ( isS3d && (mCapMode == OMXCameraAdapter::HIGH_QUALITY)) )
1465            {
1466            ///Enable/Disable Video Noise Filter
1467            ret = enableVideoNoiseFilter(mVnfEnabled);
1468            if ( NO_ERROR != ret)
1469                {
1470                CAMHAL_LOGEB("Error configuring VNF %x", ret);
1471                return ret;
1472                }
1473
1474            ///Enable/Disable Video Stabilization
1475            ret = enableVideoStabilization(mVstabEnabled);
1476            if ( NO_ERROR != ret)
1477                {
1478                CAMHAL_LOGEB("Error configuring VSTAB %x", ret);
1479                return ret;
1480                }
1481            }
1482        else
1483            {
1484            ret = enableVideoNoiseFilter(false);
1485            if ( NO_ERROR != ret)
1486                {
1487                CAMHAL_LOGEB("Error configuring VNF %x", ret);
1488                return ret;
1489                }
1490            ///Enable/Disable Video Stabilization
1491            ret = enableVideoStabilization(false);
1492            if ( NO_ERROR != ret)
1493                {
1494                CAMHAL_LOGEB("Error configuring VSTAB %x", ret);
1495                return ret;
1496                }
1497            }
1498        }
1499
1500    ret = setSensorOrientation(mSensorOrientation);
1501    if ( NO_ERROR != ret )
1502        {
1503        CAMHAL_LOGEB("Error configuring Sensor Orientation %x", ret);
1504        mSensorOrientation = 0;
1505        }
1506
1507    ret = setVFramerate(mPreviewData->mMinFrameRate, mPreviewData->mMaxFrameRate);
1508    if ( ret != NO_ERROR )
1509        {
1510        CAMHAL_LOGEB("VFR configuration failed 0x%x", ret);
1511        LOG_FUNCTION_NAME_EXIT;
1512        return ret;
1513        }
1514
1515    if ( mComponentState == OMX_StateLoaded )
1516        {
1517        ///Register for IDLE state switch event
1518        ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
1519                               OMX_EventCmdComplete,
1520                               OMX_CommandStateSet,
1521                               OMX_StateIdle,
1522                               mUsePreviewSem);
1523
1524        if(ret!=NO_ERROR)
1525            {
1526            CAMHAL_LOGEB("Error in registering for event %d", ret);
1527            goto EXIT;
1528            }
1529
1530        ///Once we get the buffers, move component state to idle state and pass the buffers to OMX comp using UseBuffer
1531        eError = OMX_SendCommand (mCameraAdapterParameters.mHandleComp ,
1532                                  OMX_CommandStateSet,
1533                                  OMX_StateIdle,
1534                                  NULL);
1535
1536        CAMHAL_LOGDB("OMX_SendCommand(OMX_CommandStateSet) 0x%x", eError);
1537
1538        GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
1539
1540        mComponentState = OMX_StateIdle;
1541        }
1542    else
1543        {
1544            ///Register for Preview port ENABLE event
1545            ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
1546                                   OMX_EventCmdComplete,
1547                                   OMX_CommandPortEnable,
1548                                   mCameraAdapterParameters.mPrevPortIndex,
1549                                   mUsePreviewSem);
1550
1551            if ( NO_ERROR != ret )
1552                {
1553                CAMHAL_LOGEB("Error in registering for event %d", ret);
1554                goto EXIT;
1555                }
1556
1557            ///Enable Preview Port
1558            eError = OMX_SendCommand(mCameraAdapterParameters.mHandleComp,
1559                                     OMX_CommandPortEnable,
1560                                     mCameraAdapterParameters.mPrevPortIndex,
1561                                     NULL);
1562        }
1563
1564
1565    ///Configure DOMX to use either gralloc handles or vptrs
1566    OMX_TI_PARAMUSENATIVEBUFFER domxUseGrallocHandles;
1567    OMX_INIT_STRUCT_PTR (&domxUseGrallocHandles, OMX_TI_PARAMUSENATIVEBUFFER);
1568
1569    domxUseGrallocHandles.nPortIndex = mCameraAdapterParameters.mPrevPortIndex;
1570    domxUseGrallocHandles.bEnable = OMX_TRUE;
1571
1572    eError = OMX_SetParameter(mCameraAdapterParameters.mHandleComp,
1573                            (OMX_INDEXTYPE)OMX_TI_IndexUseNativeBuffers, &domxUseGrallocHandles);
1574    if(eError!=OMX_ErrorNone)
1575        {
1576        CAMHAL_LOGEB("OMX_SetParameter - %x", eError);
1577        }
1578    GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
1579
1580    OMX_BUFFERHEADERTYPE *pBufferHdr;
1581    for(int index=0;index<num;index++) {
1582
1583        CAMHAL_LOGDB("OMX_UseBuffer(0x%x)", buffers[index]);
1584        eError = OMX_UseBuffer( mCameraAdapterParameters.mHandleComp,
1585                                &pBufferHdr,
1586                                mCameraAdapterParameters.mPrevPortIndex,
1587                                0,
1588                                mPreviewData->mBufSize,
1589                                (OMX_U8*)buffers[index]);
1590        if(eError!=OMX_ErrorNone)
1591            {
1592            CAMHAL_LOGEB("OMX_UseBuffer-0x%x", eError);
1593            }
1594        GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
1595
1596        //pBufferHdr->pAppPrivate =  (OMX_PTR)pBufferHdr;
1597        pBufferHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE);
1598        pBufferHdr->nVersion.s.nVersionMajor = 1 ;
1599        pBufferHdr->nVersion.s.nVersionMinor = 1 ;
1600        pBufferHdr->nVersion.s.nRevision = 0 ;
1601        pBufferHdr->nVersion.s.nStep =  0;
1602        mPreviewData->mBufferHeader[index] = pBufferHdr;
1603    }
1604
1605    if ( mMeasurementEnabled )
1606        {
1607
1608        for( int i = 0; i < num; i++ )
1609            {
1610            OMX_BUFFERHEADERTYPE *pBufHdr;
1611            eError = OMX_UseBuffer( mCameraAdapterParameters.mHandleComp,
1612                                    &pBufHdr,
1613                                    mCameraAdapterParameters.mMeasurementPortIndex,
1614                                    0,
1615                                    measurementData->mBufSize,
1616                                    (OMX_U8*)(mPreviewDataBuffers[i]));
1617
1618             if ( eError == OMX_ErrorNone )
1619                {
1620                pBufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE);
1621                pBufHdr->nVersion.s.nVersionMajor = 1 ;
1622                pBufHdr->nVersion.s.nVersionMinor = 1 ;
1623                pBufHdr->nVersion.s.nRevision = 0 ;
1624                pBufHdr->nVersion.s.nStep =  0;
1625                measurementData->mBufferHeader[i] = pBufHdr;
1626                }
1627            else
1628                {
1629                CAMHAL_LOGEB("OMX_UseBuffer -0x%x", eError);
1630                ret = BAD_VALUE;
1631                break;
1632                }
1633            }
1634
1635        }
1636
1637    CAMHAL_LOGDA("Registering preview buffers");
1638
1639    ret = mUsePreviewSem.WaitTimeout(OMX_CMD_TIMEOUT);
1640    if ( NO_ERROR == ret )
1641        {
1642        CAMHAL_LOGDA("Preview buffer registration successfull");
1643        }
1644    else
1645        {
1646        if ( mComponentState == OMX_StateLoaded )
1647            {
1648            ret |= SignalEvent(mCameraAdapterParameters.mHandleComp,
1649                               OMX_EventCmdComplete,
1650                               OMX_CommandStateSet,
1651                               OMX_StateIdle,
1652                               NULL);
1653            }
1654        else
1655            {
1656            ret |= SignalEvent(mCameraAdapterParameters.mHandleComp,
1657                               OMX_EventCmdComplete,
1658                               OMX_CommandPortEnable,
1659                               mCameraAdapterParameters.mPrevPortIndex,
1660                               NULL);
1661            }
1662        CAMHAL_LOGEA("Timeout expired on preview buffer registration");
1663        goto EXIT;
1664        }
1665
1666    LOG_FUNCTION_NAME_EXIT;
1667
1668    return (ret | ErrorUtils::omxToAndroidError(eError));
1669
1670    ///If there is any failure, we reach here.
1671    ///Here, we do any resource freeing and convert from OMX error code to Camera Hal error code
1672    EXIT:
1673
1674    CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, ret, eError);
1675
1676    LOG_FUNCTION_NAME_EXIT;
1677
1678    return (ret | ErrorUtils::omxToAndroidError(eError));
1679}
1680
1681status_t OMXCameraAdapter::startPreview()
1682{
1683    status_t ret = NO_ERROR;
1684    OMX_ERRORTYPE eError = OMX_ErrorNone;
1685    OMXCameraPortParameters *mPreviewData = NULL;
1686    OMXCameraPortParameters *measurementData = NULL;
1687
1688    LOG_FUNCTION_NAME;
1689
1690    if( 0 != mStartPreviewSem.Count() )
1691        {
1692        CAMHAL_LOGEB("Error mStartPreviewSem semaphore count %d", mStartPreviewSem.Count());
1693        LOG_FUNCTION_NAME_EXIT;
1694        return NO_INIT;
1695        }
1696
1697    mPreviewData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex];
1698    measurementData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mMeasurementPortIndex];
1699
1700
1701    if ( mPending3Asettings )
1702        apply3Asettings(mParameters3A);
1703
1704    if( OMX_StateIdle == mComponentState )
1705        {
1706        ///Register for EXECUTING state transition.
1707        ///This method just inserts a message in Event Q, which is checked in the callback
1708        ///The sempahore passed is signalled by the callback
1709        ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
1710                               OMX_EventCmdComplete,
1711                               OMX_CommandStateSet,
1712                               OMX_StateExecuting,
1713                               mStartPreviewSem);
1714
1715        if(ret!=NO_ERROR)
1716            {
1717            CAMHAL_LOGEB("Error in registering for event %d", ret);
1718            goto EXIT;
1719            }
1720
1721        ///Switch to EXECUTING state
1722        eError = OMX_SendCommand(mCameraAdapterParameters.mHandleComp,
1723                                 OMX_CommandStateSet,
1724                                 OMX_StateExecuting,
1725                                 NULL);
1726
1727        if(eError!=OMX_ErrorNone)
1728            {
1729            CAMHAL_LOGEB("OMX_SendCommand(OMX_StateExecuting)-0x%x", eError);
1730            }
1731
1732        CAMHAL_LOGDA("+Waiting for component to go into EXECUTING state");
1733        ret = mStartPreviewSem.WaitTimeout(OMX_CMD_TIMEOUT);
1734        if ( NO_ERROR == ret )
1735            {
1736            CAMHAL_LOGDA("+Great. Component went into executing state!!");
1737            }
1738        else
1739            {
1740            ret |= SignalEvent(mCameraAdapterParameters.mHandleComp,
1741                               OMX_EventCmdComplete,
1742                               OMX_CommandStateSet,
1743                               OMX_StateExecuting,
1744                               NULL);
1745            CAMHAL_LOGDA("Timeout expired on executing state switch!");
1746            goto EXIT;
1747            }
1748
1749        mComponentState = OMX_StateExecuting;
1750
1751        }
1752
1753    //Queue all the buffers on preview port
1754    for(int index=0;index< mPreviewData->mMaxQueueable;index++)
1755        {
1756        CAMHAL_LOGDB("Queuing buffer on Preview port - 0x%x", (uint32_t)mPreviewData->mBufferHeader[index]->pBuffer);
1757        eError = OMX_FillThisBuffer(mCameraAdapterParameters.mHandleComp,
1758                    (OMX_BUFFERHEADERTYPE*)mPreviewData->mBufferHeader[index]);
1759        if(eError!=OMX_ErrorNone)
1760            {
1761            CAMHAL_LOGEB("OMX_FillThisBuffer-0x%x", eError);
1762            }
1763        GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
1764        }
1765
1766    if ( mMeasurementEnabled )
1767        {
1768
1769        for(int index=0;index< mPreviewData->mNumBufs;index++)
1770            {
1771            CAMHAL_LOGDB("Queuing buffer on Measurement port - 0x%x", (uint32_t) measurementData->mBufferHeader[index]->pBuffer);
1772            eError = OMX_FillThisBuffer(mCameraAdapterParameters.mHandleComp,
1773                            (OMX_BUFFERHEADERTYPE*) measurementData->mBufferHeader[index]);
1774            if(eError!=OMX_ErrorNone)
1775                {
1776                CAMHAL_LOGEB("OMX_FillThisBuffer-0x%x", eError);
1777                }
1778            GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
1779            }
1780
1781        }
1782
1783    //Query current focus distance after
1784    //starting the preview
1785    updateFocusDistances(mParameters);
1786
1787    //reset frame rate estimates
1788    mFPS = 0.0f;
1789    mLastFPS = 0.0f;
1790    mFrameCount = 0;
1791    mLastFrameCount = 0;
1792    mIter = 1;
1793    mLastFPSTime = systemTime();
1794
1795    // TODO(XXX): temporary hack. must remove after setconfig and transition issue
1796    //            with secondary camera is fixed
1797    if (mSensorIndex == 1) {
1798        mWaitToSetConfig = true;
1799        mCommandHandler->setWait(true);
1800    }
1801
1802    LOG_FUNCTION_NAME_EXIT;
1803
1804    return ret;
1805
1806    EXIT:
1807
1808    CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, ret, eError);
1809
1810    LOG_FUNCTION_NAME_EXIT;
1811
1812    return (ret | ErrorUtils::omxToAndroidError(eError));
1813
1814}
1815
1816status_t OMXCameraAdapter::stopPreview()
1817{
1818    LOG_FUNCTION_NAME;
1819
1820    OMX_ERRORTYPE eError = OMX_ErrorNone;
1821    status_t ret = NO_ERROR;
1822
1823    OMXCameraPortParameters *mCaptureData , *mPreviewData, *measurementData;
1824    mCaptureData = mPreviewData = measurementData = NULL;
1825
1826    mPreviewData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mPrevPortIndex];
1827    mCaptureData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mImagePortIndex];
1828    measurementData = &mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mMeasurementPortIndex];
1829
1830    if ( mComponentState != OMX_StateExecuting )
1831        {
1832        CAMHAL_LOGEA("Calling StopPreview() when not in EXECUTING state");
1833        LOG_FUNCTION_NAME_EXIT;
1834        return NO_INIT;
1835        }
1836
1837    ret = cancelAutoFocus();
1838    if(ret!=NO_ERROR)
1839    {
1840        CAMHAL_LOGEB("Error canceling autofocus %d", ret);
1841        // Error, but we probably still want to continue to stop preview
1842    }
1843
1844    //Release 3A locks
1845    ret = set3ALock(OMX_FALSE);
1846    if(ret!=NO_ERROR)
1847      {
1848        CAMHAL_LOGEB("Error Releaseing 3A locks%d", ret);
1849      }
1850
1851    if ( 0 != mStopPreviewSem.Count() )
1852        {
1853        CAMHAL_LOGEB("Error mStopPreviewSem semaphore count %d", mStopPreviewSem.Count());
1854        LOG_FUNCTION_NAME_EXIT;
1855        return NO_INIT;
1856        }
1857
1858    CAMHAL_LOGDB("Average framerate: %f", mFPS);
1859
1860    //Avoid state switching of the OMX Component
1861    ret = flushBuffers();
1862    if ( NO_ERROR != ret )
1863        {
1864        CAMHAL_LOGEB("Flush Buffers failed 0x%x", ret);
1865        goto EXIT;
1866        }
1867
1868    ///Register for Preview port Disable event
1869    ret = RegisterForEvent(mCameraAdapterParameters.mHandleComp,
1870                           OMX_EventCmdComplete,
1871                           OMX_CommandPortDisable,
1872                           mCameraAdapterParameters.mPrevPortIndex,
1873                           mStopPreviewSem);
1874
1875    ///Disable Preview Port
1876    eError = OMX_SendCommand(mCameraAdapterParameters.mHandleComp,
1877                             OMX_CommandPortDisable,
1878                             mCameraAdapterParameters.mPrevPortIndex,
1879                             NULL);
1880
1881    ///Free the OMX Buffers
1882    for ( int i = 0 ; i < mPreviewData->mNumBufs ; i++ )
1883        {
1884        eError = OMX_FreeBuffer(mCameraAdapterParameters.mHandleComp,
1885                                mCameraAdapterParameters.mPrevPortIndex,
1886                                mPreviewData->mBufferHeader[i]);
1887
1888        if(eError!=OMX_ErrorNone)
1889            {
1890            CAMHAL_LOGEB("OMX_FreeBuffer - %x", eError);
1891            }
1892        GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
1893        }
1894
1895    if ( mMeasurementEnabled )
1896        {
1897
1898            for ( int i = 0 ; i < measurementData->mNumBufs ; i++ )
1899                {
1900                eError = OMX_FreeBuffer(mCameraAdapterParameters.mHandleComp,
1901                                        mCameraAdapterParameters.mMeasurementPortIndex,
1902                                        measurementData->mBufferHeader[i]);
1903                if(eError!=OMX_ErrorNone)
1904                    {
1905                    CAMHAL_LOGEB("OMX_FreeBuffer - %x", eError);
1906                    }
1907                GOTO_EXIT_IF((eError!=OMX_ErrorNone), eError);
1908                }
1909
1910            {
1911            Mutex::Autolock lock(mPreviewDataBufferLock);
1912            mPreviewDataBuffersAvailable.clear();
1913            }
1914
1915        }
1916
1917    CAMHAL_LOGDA("Disabling preview port");
1918    ret = mStopPreviewSem.WaitTimeout(OMX_CMD_TIMEOUT);
1919    if ( NO_ERROR == ret )
1920        {
1921        CAMHAL_LOGDA("Preview port disabled");
1922        }
1923    else
1924        {
1925        ret |= SignalEvent(mCameraAdapterParameters.mHandleComp,
1926                           OMX_EventCmdComplete,
1927                           OMX_CommandPortDisable,
1928                           mCameraAdapterParameters.mPrevPortIndex,
1929                           NULL);
1930        CAMHAL_LOGEA("Timeout expired on preview port disable");
1931        goto EXIT;
1932        }
1933
1934        {
1935        Mutex::Autolock lock(mPreviewBufferLock);
1936        ///Clear all the available preview buffers
1937        mPreviewBuffersAvailable.clear();
1938        }
1939
1940    switchToLoaded();
1941
1942    mWaitToSetConfig = false;
1943    mCommandHandler->setWait(false);
1944
1945
1946    LOG_FUNCTION_NAME_EXIT;
1947
1948    return (ret | ErrorUtils::omxToAndroidError(eError));
1949
1950    EXIT:
1951
1952    {
1953    Mutex::Autolock lock(mPreviewBufferLock);
1954    ///Clear all the available preview buffers
1955    mPreviewBuffersAvailable.clear();
1956    }
1957
1958    switchToLoaded();
1959
1960    LOG_FUNCTION_NAME_EXIT;
1961
1962    return (ret | ErrorUtils::omxToAndroidError(eError));
1963
1964}
1965
1966status_t OMXCameraAdapter::setSensorOverclock(bool enable)
1967{
1968    status_t ret = NO_ERROR;
1969    OMX_ERRORTYPE eError = OMX_ErrorNone;
1970    OMX_CONFIG_BOOLEANTYPE bOMX;
1971
1972    LOG_FUNCTION_NAME;
1973
1974    if ( OMX_StateLoaded != mComponentState )
1975        {
1976        CAMHAL_LOGDA("OMX component is not in loaded state");
1977        return ret;
1978        }
1979
1980    if ( NO_ERROR == ret )
1981        {
1982        OMX_INIT_STRUCT_PTR (&bOMX, OMX_CONFIG_BOOLEANTYPE);
1983
1984        if ( enable )
1985            {
1986            bOMX.bEnabled = OMX_TRUE;
1987            }
1988        else
1989            {
1990            bOMX.bEnabled = OMX_FALSE;
1991            }
1992
1993        CAMHAL_LOGDB("Configuring Sensor overclock mode 0x%x", bOMX.bEnabled);
1994        eError = OMX_SetParameter(mCameraAdapterParameters.mHandleComp, ( OMX_INDEXTYPE ) OMX_TI_IndexParamSensorOverClockMode, &bOMX);
1995        if ( OMX_ErrorNone != eError )
1996            {
1997            CAMHAL_LOGEB("Error while setting Sensor overclock 0x%x", eError);
1998            ret = BAD_VALUE;
1999            }
2000        else
2001            {
2002            mSensorOverclock = enable;
2003            }
2004        }
2005
2006    LOG_FUNCTION_NAME_EXIT;
2007
2008    return ret;
2009}
2010
2011status_t OMXCameraAdapter::printComponentVersion(OMX_HANDLETYPE handle)
2012{
2013    status_t ret = NO_ERROR;
2014    OMX_ERRORTYPE eError = OMX_ErrorNone;
2015    OMX_VERSIONTYPE compVersion;
2016    char compName[OMX_MAX_STRINGNAME_SIZE];
2017    char *currentUUID = NULL;
2018    size_t offset = 0;
2019
2020    LOG_FUNCTION_NAME;
2021
2022    if ( NULL == handle )
2023        {
2024        CAMHAL_LOGEB("Invalid OMX Handle =0x%x",  ( unsigned int ) handle);
2025        ret = -EINVAL;
2026        }
2027
2028    mCompUUID[0] = 0;
2029
2030    if ( NO_ERROR == ret )
2031        {
2032        eError = OMX_GetComponentVersion(handle,
2033                                      compName,
2034                                      &compVersion,
2035                                      &mCompRevision,
2036                                      &mCompUUID
2037                                    );
2038        if ( OMX_ErrorNone != eError )
2039            {
2040            CAMHAL_LOGEB("OMX_GetComponentVersion returned 0x%x", eError);
2041            ret = BAD_VALUE;
2042            }
2043        }
2044
2045    if ( NO_ERROR == ret )
2046        {
2047        CAMHAL_LOGVB("OMX Component name: [%s]", compName);
2048        CAMHAL_LOGVB("OMX Component version: [%u]", ( unsigned int ) compVersion.nVersion);
2049        CAMHAL_LOGVB("Spec version: [%u]", ( unsigned int ) mCompRevision.nVersion);
2050        CAMHAL_LOGVB("Git Commit ID: [%s]", mCompUUID);
2051        currentUUID = ( char * ) mCompUUID;
2052        }
2053
2054    if ( NULL != currentUUID )
2055        {
2056        offset = strlen( ( const char * ) mCompUUID) + 1;
2057        if ( (int)currentUUID + (int)offset - (int)mCompUUID < OMX_MAX_STRINGNAME_SIZE )
2058            {
2059            currentUUID += offset;
2060            CAMHAL_LOGVB("Git Branch: [%s]", currentUUID);
2061            }
2062        else
2063            {
2064            ret = BAD_VALUE;
2065            }
2066    }
2067
2068    if ( NO_ERROR == ret )
2069        {
2070        offset = strlen( ( const char * ) currentUUID) + 1;
2071
2072        if ( (int)currentUUID + (int)offset - (int)mCompUUID < OMX_MAX_STRINGNAME_SIZE )
2073            {
2074            currentUUID += offset;
2075            CAMHAL_LOGVB("Build date and time: [%s]", currentUUID);
2076            }
2077        else
2078            {
2079            ret = BAD_VALUE;
2080            }
2081        }
2082
2083    if ( NO_ERROR == ret )
2084        {
2085        offset = strlen( ( const char * ) currentUUID) + 1;
2086
2087        if ( (int)currentUUID + (int)offset - (int)mCompUUID < OMX_MAX_STRINGNAME_SIZE )
2088            {
2089            currentUUID += offset;
2090            CAMHAL_LOGVB("Build description: [%s]", currentUUID);
2091            }
2092        else
2093            {
2094            ret = BAD_VALUE;
2095            }
2096        }
2097
2098    LOG_FUNCTION_NAME_EXIT;
2099
2100    return ret;
2101}
2102
2103status_t OMXCameraAdapter::autoFocus()
2104{
2105    status_t ret = NO_ERROR;
2106    TIUTILS::Message msg;
2107
2108    LOG_FUNCTION_NAME;
2109
2110    msg.command = CommandHandler::CAMERA_PERFORM_AUTOFOCUS;
2111    msg.arg1 = mErrorNotifier;
2112    ret = mCommandHandler->put(&msg);
2113
2114    LOG_FUNCTION_NAME;
2115
2116    return ret;
2117}
2118
2119status_t OMXCameraAdapter::takePicture()
2120{
2121    status_t ret = NO_ERROR;
2122    TIUTILS::Message msg;
2123
2124    LOG_FUNCTION_NAME;
2125
2126    msg.command = CommandHandler::CAMERA_START_IMAGE_CAPTURE;
2127    msg.arg1 = mErrorNotifier;
2128    ret = mCommandHandler->put(&msg);
2129
2130    LOG_FUNCTION_NAME_EXIT;
2131
2132    return ret;
2133}
2134
2135status_t OMXCameraAdapter::startVideoCapture()
2136{
2137    return BaseCameraAdapter::startVideoCapture();
2138}
2139
2140status_t OMXCameraAdapter::stopVideoCapture()
2141{
2142    return BaseCameraAdapter::stopVideoCapture();
2143}
2144
2145//API to get the frame size required to be allocated. This size is used to override the size passed
2146//by camera service when VSTAB/VNF is turned ON for example
2147status_t OMXCameraAdapter::getFrameSize(size_t &width, size_t &height)
2148{
2149    status_t ret = NO_ERROR;
2150    OMX_ERRORTYPE eError = OMX_ErrorNone;
2151    OMX_CONFIG_RECTTYPE tFrameDim;
2152
2153    LOG_FUNCTION_NAME;
2154
2155    OMX_INIT_STRUCT_PTR (&tFrameDim, OMX_CONFIG_RECTTYPE);
2156    tFrameDim.nPortIndex = mCameraAdapterParameters.mPrevPortIndex;
2157
2158    if ( mOMXStateSwitch )
2159        {
2160
2161        ret = switchToLoaded();
2162        if ( NO_ERROR != ret )
2163            {
2164            CAMHAL_LOGEB("switchToLoaded() failed 0x%x", ret);
2165            goto exit;
2166            }
2167
2168        mOMXStateSwitch = false;
2169        }
2170
2171    if ( OMX_StateLoaded == mComponentState )
2172        {
2173
2174        ret = setLDC(mIPP);
2175        if ( NO_ERROR != ret )
2176            {
2177            CAMHAL_LOGEB("setLDC() failed %d", ret);
2178            LOG_FUNCTION_NAME_EXIT;
2179            goto exit;
2180            }
2181
2182        ret = setNSF(mIPP);
2183        if ( NO_ERROR != ret )
2184            {
2185            CAMHAL_LOGEB("setNSF() failed %d", ret);
2186            LOG_FUNCTION_NAME_EXIT;
2187            goto exit;
2188            }
2189
2190        ret = setCaptureMode(mCapMode);
2191        if ( NO_ERROR != ret )
2192            {
2193            CAMHAL_LOGEB("setCaptureMode() failed %d", ret);
2194            }
2195
2196        if(mCapMode == OMXCameraAdapter::VIDEO_MODE)
2197            {
2198            if ( NO_ERROR == ret )
2199                {
2200                ///Enable/Disable Video Noise Filter
2201                ret = enableVideoNoiseFilter(mVnfEnabled);
2202                }
2203
2204            if ( NO_ERROR != ret)
2205                {
2206                CAMHAL_LOGEB("Error configuring VNF %x", ret);
2207                }
2208
2209            if ( NO_ERROR == ret )
2210                {
2211                ///Enable/Disable Video Stabilization
2212                ret = enableVideoStabilization(mVstabEnabled);
2213                }
2214
2215            if ( NO_ERROR != ret)
2216                {
2217                CAMHAL_LOGEB("Error configuring VSTAB %x", ret);
2218                }
2219             }
2220        else
2221            {
2222            if ( NO_ERROR == ret )
2223                {
2224                ///Enable/Disable Video Noise Filter
2225                ret = enableVideoNoiseFilter(false);
2226                }
2227
2228            if ( NO_ERROR != ret)
2229                {
2230                CAMHAL_LOGEB("Error configuring VNF %x", ret);
2231                }
2232
2233            if ( NO_ERROR == ret )
2234                {
2235                ///Enable/Disable Video Stabilization
2236                ret = enableVideoStabilization(false);
2237                }
2238
2239            if ( NO_ERROR != ret)
2240                {
2241                CAMHAL_LOGEB("Error configuring VSTAB %x", ret);
2242                }
2243            }
2244
2245        }
2246
2247    ret = setSensorOrientation(mSensorOrientation);
2248    if ( NO_ERROR != ret )
2249        {
2250        CAMHAL_LOGEB("Error configuring Sensor Orientation %x", ret);
2251        mSensorOrientation = 0;
2252        }
2253
2254    if ( NO_ERROR == ret )
2255        {
2256        eError = OMX_GetParameter(mCameraAdapterParameters.mHandleComp, ( OMX_INDEXTYPE ) OMX_TI_IndexParam2DBufferAllocDimension, &tFrameDim);
2257        if ( OMX_ErrorNone == eError)
2258            {
2259            width = tFrameDim.nWidth;
2260            height = tFrameDim.nHeight;
2261            }
2262        }
2263
2264exit:
2265
2266    CAMHAL_LOGDB("Required frame size %dx%d", width, height);
2267
2268    LOG_FUNCTION_NAME_EXIT;
2269
2270    return ret;
2271}
2272
2273status_t OMXCameraAdapter::getFrameDataSize(size_t &dataFrameSize, size_t bufferCount)
2274{
2275    status_t ret = NO_ERROR;
2276    OMX_PARAM_PORTDEFINITIONTYPE portCheck;
2277    OMX_ERRORTYPE eError = OMX_ErrorNone;
2278
2279    LOG_FUNCTION_NAME;
2280
2281    if ( OMX_StateLoaded != mComponentState )
2282        {
2283        CAMHAL_LOGEA("Calling getFrameDataSize() when not in LOADED state");
2284        dataFrameSize = 0;
2285        ret = BAD_VALUE;
2286        }
2287
2288    if ( NO_ERROR == ret  )
2289        {
2290        OMX_INIT_STRUCT_PTR(&portCheck, OMX_PARAM_PORTDEFINITIONTYPE);
2291        portCheck.nPortIndex = mCameraAdapterParameters.mMeasurementPortIndex;
2292
2293        eError = OMX_GetParameter(mCameraAdapterParameters.mHandleComp, OMX_IndexParamPortDefinition, &portCheck);
2294        if ( OMX_ErrorNone != eError )
2295            {
2296            CAMHAL_LOGEB("OMX_GetParameter on OMX_IndexParamPortDefinition returned: 0x%x", eError);
2297            dataFrameSize = 0;
2298            ret = BAD_VALUE;
2299            }
2300        }
2301
2302    if ( NO_ERROR == ret )
2303        {
2304        portCheck.nBufferCountActual = bufferCount;
2305        eError = OMX_SetParameter(mCameraAdapterParameters.mHandleComp, OMX_IndexParamPortDefinition, &portCheck);
2306        if ( OMX_ErrorNone != eError )
2307            {
2308            CAMHAL_LOGEB("OMX_SetParameter on OMX_IndexParamPortDefinition returned: 0x%x", eError);
2309            dataFrameSize = 0;
2310            ret = BAD_VALUE;
2311            }
2312        }
2313
2314    if ( NO_ERROR == ret  )
2315        {
2316        eError = OMX_GetParameter(mCameraAdapterParameters.mHandleComp, OMX_IndexParamPortDefinition, &portCheck);
2317        if ( OMX_ErrorNone != eError )
2318            {
2319            CAMHAL_LOGEB("OMX_GetParameter on OMX_IndexParamPortDefinition returned: 0x%x", eError);
2320            ret = BAD_VALUE;
2321            }
2322        else
2323            {
2324            mCameraAdapterParameters.mCameraPortParams[portCheck.nPortIndex].mBufSize = portCheck.nBufferSize;
2325            dataFrameSize = portCheck.nBufferSize;
2326            }
2327        }
2328
2329    LOG_FUNCTION_NAME_EXIT;
2330
2331    return ret;
2332}
2333
2334void OMXCameraAdapter::onOrientationEvent(uint32_t orientation, uint32_t tilt)
2335{
2336    LOG_FUNCTION_NAME;
2337
2338    static const int DEGREES_TILT_IGNORE = 45;
2339    int device_orientation = 0;
2340    int mount_orientation = 0;
2341    const char *facing_direction = NULL;
2342
2343    // if tilt angle is greater than DEGREES_TILT_IGNORE
2344    // we are going to ignore the orientation returned from
2345    // sensor. the orientation returned from sensor is not
2346    // reliable. Value of DEGREES_TILT_IGNORE may need adjusting
2347    if (tilt > DEGREES_TILT_IGNORE) {
2348        return;
2349    }
2350
2351    if (mCapabilities) {
2352        if (mCapabilities->get(CameraProperties::ORIENTATION_INDEX)) {
2353            mount_orientation = atoi(mCapabilities->get(CameraProperties::ORIENTATION_INDEX));
2354        }
2355        facing_direction = mCapabilities->get(CameraProperties::FACING_INDEX);
2356    }
2357
2358    // calculate device orientation relative to the sensor orientation
2359    // front camera display is mirrored
2360    if (facing_direction && !strcmp(facing_direction, TICameraParameters::FACING_FRONT)) {
2361        device_orientation = (orientation - mount_orientation + 360) % 360;
2362    } else {  // back-facing camera
2363        device_orientation = (orientation + mount_orientation) % 360;
2364    }
2365
2366    if (device_orientation != mDeviceOrientation) {
2367        mDeviceOrientation = device_orientation;
2368
2369        mFaceDetectionLock.lock();
2370        if (mFaceDetectionRunning) {
2371            // restart face detection with new rotation
2372            setFaceDetection(true, mDeviceOrientation);
2373        }
2374        mFaceDetectionLock.unlock();
2375    }
2376    CAMHAL_LOGVB("orientation = %d tilt = %d device_orientation = %d", orientation, tilt, mDeviceOrientation);
2377
2378    LOG_FUNCTION_NAME_EXIT;
2379}
2380
2381/* Application callback Functions */
2382/*========================================================*/
2383/* @ fn SampleTest_EventHandler :: Application callback   */
2384/*========================================================*/
2385OMX_ERRORTYPE OMXCameraAdapterEventHandler(OMX_IN OMX_HANDLETYPE hComponent,
2386                                          OMX_IN OMX_PTR pAppData,
2387                                          OMX_IN OMX_EVENTTYPE eEvent,
2388                                          OMX_IN OMX_U32 nData1,
2389                                          OMX_IN OMX_U32 nData2,
2390                                          OMX_IN OMX_PTR pEventData)
2391{
2392    LOG_FUNCTION_NAME;
2393
2394    CAMHAL_LOGDB("Event %d", eEvent);
2395
2396    OMX_ERRORTYPE ret = OMX_ErrorNone;
2397    OMXCameraAdapter *oca = (OMXCameraAdapter*)pAppData;
2398    ret = oca->OMXCameraAdapterEventHandler(hComponent, eEvent, nData1, nData2, pEventData);
2399
2400    LOG_FUNCTION_NAME_EXIT;
2401    return ret;
2402}
2403
2404/* Application callback Functions */
2405/*========================================================*/
2406/* @ fn SampleTest_EventHandler :: Application callback   */
2407/*========================================================*/
2408OMX_ERRORTYPE OMXCameraAdapter::OMXCameraAdapterEventHandler(OMX_IN OMX_HANDLETYPE hComponent,
2409                                          OMX_IN OMX_EVENTTYPE eEvent,
2410                                          OMX_IN OMX_U32 nData1,
2411                                          OMX_IN OMX_U32 nData2,
2412                                          OMX_IN OMX_PTR pEventData)
2413{
2414
2415    LOG_FUNCTION_NAME;
2416
2417    OMX_ERRORTYPE eError = OMX_ErrorNone;
2418    CAMHAL_LOGDB("+OMX_Event %x, %d %d", eEvent, (int)nData1, (int)nData2);
2419
2420    switch (eEvent) {
2421        case OMX_EventCmdComplete:
2422            CAMHAL_LOGDB("+OMX_EventCmdComplete %d %d", (int)nData1, (int)nData2);
2423
2424            if (OMX_CommandStateSet == nData1) {
2425                mCameraAdapterParameters.mState = (OMX_STATETYPE) nData2;
2426
2427            } else if (OMX_CommandFlush == nData1) {
2428                CAMHAL_LOGDB("OMX_CommandFlush received for port %d", (int)nData2);
2429
2430            } else if (OMX_CommandPortDisable == nData1) {
2431                CAMHAL_LOGDB("OMX_CommandPortDisable received for port %d", (int)nData2);
2432
2433            } else if (OMX_CommandPortEnable == nData1) {
2434                CAMHAL_LOGDB("OMX_CommandPortEnable received for port %d", (int)nData2);
2435
2436            } else if (OMX_CommandMarkBuffer == nData1) {
2437                ///This is not used currently
2438            }
2439
2440            CAMHAL_LOGDA("-OMX_EventCmdComplete");
2441        break;
2442
2443        case OMX_EventIndexSettingChanged:
2444            CAMHAL_LOGDB("OMX_EventIndexSettingChanged event received data1 0x%x, data2 0x%x",
2445                            ( unsigned int ) nData1, ( unsigned int ) nData2);
2446            break;
2447
2448        case OMX_EventError:
2449            CAMHAL_LOGDB("OMX interface failed to execute OMX command %d", (int)nData1);
2450            CAMHAL_LOGDA("See OMX_INDEXTYPE for reference");
2451            if ( NULL != mErrorNotifier && ( ( OMX_U32 ) OMX_ErrorHardware == nData1 ) && mComponentState != OMX_StateInvalid)
2452              {
2453                CAMHAL_LOGEA("***Got Fatal Error Notification***\n");
2454                mComponentState = OMX_StateInvalid;
2455                ///Report Error to App
2456                mErrorNotifier->errorNotify(CAMERA_ERROR_UNKNOWN);
2457              }
2458            break;
2459
2460        case OMX_EventMark:
2461        break;
2462
2463        case OMX_EventPortSettingsChanged:
2464        break;
2465
2466        case OMX_EventBufferFlag:
2467        break;
2468
2469        case OMX_EventResourcesAcquired:
2470        break;
2471
2472        case OMX_EventComponentResumed:
2473        break;
2474
2475        case OMX_EventDynamicResourcesAvailable:
2476        break;
2477
2478        case OMX_EventPortFormatDetected:
2479        break;
2480
2481        default:
2482        break;
2483    }
2484
2485    ///Signal to the thread(s) waiting that the event has occured
2486    SignalEvent(hComponent, eEvent, nData1, nData2, pEventData);
2487
2488   LOG_FUNCTION_NAME_EXIT;
2489   return eError;
2490
2491    EXIT:
2492
2493    CAMHAL_LOGEB("Exiting function %s because of eError=%x", __FUNCTION__, eError);
2494    LOG_FUNCTION_NAME_EXIT;
2495    return eError;
2496}
2497
2498OMX_ERRORTYPE OMXCameraAdapter::SignalEvent(OMX_IN OMX_HANDLETYPE hComponent,
2499                                          OMX_IN OMX_EVENTTYPE eEvent,
2500                                          OMX_IN OMX_U32 nData1,
2501                                          OMX_IN OMX_U32 nData2,
2502                                          OMX_IN OMX_PTR pEventData)
2503{
2504    Mutex::Autolock lock(mEventLock);
2505    TIUTILS::Message *msg;
2506
2507    LOG_FUNCTION_NAME;
2508
2509    if ( !mEventSignalQ.isEmpty() )
2510        {
2511        CAMHAL_LOGDA("Event queue not empty");
2512
2513        for ( unsigned int i = 0 ; i < mEventSignalQ.size() ; i++ )
2514            {
2515            msg = mEventSignalQ.itemAt(i);
2516            if ( NULL != msg )
2517                {
2518                if( ( msg->command != 0 || msg->command == ( unsigned int ) ( eEvent ) )
2519                    && ( !msg->arg1 || ( OMX_U32 ) msg->arg1 == nData1 )
2520                    && ( !msg->arg2 || ( OMX_U32 ) msg->arg2 == nData2 )
2521                    && msg->arg3)
2522                    {
2523                    Semaphore *sem  = (Semaphore*) msg->arg3;
2524                    CAMHAL_LOGDA("Event matched, signalling sem");
2525                    mEventSignalQ.removeAt(i);
2526                    //Signal the semaphore provided
2527                    sem->Signal();
2528                    free(msg);
2529                    break;
2530                    }
2531                }
2532            }
2533        }
2534    else
2535        {
2536        CAMHAL_LOGEA("Event queue empty!!!");
2537        }
2538
2539    LOG_FUNCTION_NAME_EXIT;
2540
2541    return OMX_ErrorNone;
2542}
2543
2544status_t OMXCameraAdapter::RegisterForEvent(OMX_IN OMX_HANDLETYPE hComponent,
2545                                          OMX_IN OMX_EVENTTYPE eEvent,
2546                                          OMX_IN OMX_U32 nData1,
2547                                          OMX_IN OMX_U32 nData2,
2548                                          OMX_IN Semaphore &semaphore)
2549{
2550    status_t ret = NO_ERROR;
2551    ssize_t res;
2552    Mutex::Autolock lock(mEventLock);
2553
2554    LOG_FUNCTION_NAME;
2555
2556    TIUTILS::Message * msg = ( struct TIUTILS::Message * ) malloc(sizeof(struct TIUTILS::Message));
2557    if ( NULL != msg )
2558        {
2559        msg->command = ( unsigned int ) eEvent;
2560        msg->arg1 = ( void * ) nData1;
2561        msg->arg2 = ( void * ) nData2;
2562        msg->arg3 = ( void * ) &semaphore;
2563        msg->arg4 =  ( void * ) hComponent;
2564        res = mEventSignalQ.add(msg);
2565        if ( NO_MEMORY == res )
2566            {
2567            CAMHAL_LOGEA("No ressources for inserting OMX events");
2568            ret = -ENOMEM;
2569            }
2570        }
2571
2572    LOG_FUNCTION_NAME_EXIT;
2573
2574    return ret;
2575}
2576
2577/*========================================================*/
2578/* @ fn SampleTest_EmptyBufferDone :: Application callback*/
2579/*========================================================*/
2580OMX_ERRORTYPE OMXCameraAdapterEmptyBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
2581                                   OMX_IN OMX_PTR pAppData,
2582                                   OMX_IN OMX_BUFFERHEADERTYPE* pBuffHeader)
2583{
2584    LOG_FUNCTION_NAME;
2585
2586    OMX_ERRORTYPE eError = OMX_ErrorNone;
2587
2588    OMXCameraAdapter *oca = (OMXCameraAdapter*)pAppData;
2589    eError = oca->OMXCameraAdapterEmptyBufferDone(hComponent, pBuffHeader);
2590
2591    LOG_FUNCTION_NAME_EXIT;
2592    return eError;
2593}
2594
2595
2596/*========================================================*/
2597/* @ fn SampleTest_EmptyBufferDone :: Application callback*/
2598/*========================================================*/
2599OMX_ERRORTYPE OMXCameraAdapter::OMXCameraAdapterEmptyBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
2600                                   OMX_IN OMX_BUFFERHEADERTYPE* pBuffHeader)
2601{
2602
2603   LOG_FUNCTION_NAME;
2604
2605   LOG_FUNCTION_NAME_EXIT;
2606
2607   return OMX_ErrorNone;
2608}
2609
2610static void debugShowFPS()
2611{
2612    static int mFrameCount = 0;
2613    static int mLastFrameCount = 0;
2614    static nsecs_t mLastFpsTime = 0;
2615    static float mFps = 0;
2616    mFrameCount++;
2617    if (!(mFrameCount & 0x1F)) {
2618        nsecs_t now = systemTime();
2619        nsecs_t diff = now - mLastFpsTime;
2620        mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
2621        mLastFpsTime = now;
2622        mLastFrameCount = mFrameCount;
2623        LOGD("Camera %d Frames, %f FPS", mFrameCount, mFps);
2624    }
2625    // XXX: mFPS has the value we want
2626}
2627
2628/*========================================================*/
2629/* @ fn SampleTest_FillBufferDone ::  Application callback*/
2630/*========================================================*/
2631OMX_ERRORTYPE OMXCameraAdapterFillBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
2632                                   OMX_IN OMX_PTR pAppData,
2633                                   OMX_IN OMX_BUFFERHEADERTYPE* pBuffHeader)
2634{
2635    TIUTILS::Message msg;
2636    OMX_ERRORTYPE eError = OMX_ErrorNone;
2637
2638    if (UNLIKELY(mDebugFps)) {
2639        debugShowFPS();
2640    }
2641
2642    OMXCameraAdapter *adapter =  ( OMXCameraAdapter * ) pAppData;
2643    if ( NULL != adapter )
2644        {
2645        msg.command = OMXCameraAdapter::OMXCallbackHandler::CAMERA_FILL_BUFFER_DONE;
2646        msg.arg1 = ( void * ) hComponent;
2647        msg.arg2 = ( void * ) pBuffHeader;
2648        adapter->mOMXCallbackHandler->put(&msg);
2649        }
2650
2651    return eError;
2652}
2653
2654/*========================================================*/
2655/* @ fn SampleTest_FillBufferDone ::  Application callback*/
2656/*========================================================*/
2657OMX_ERRORTYPE OMXCameraAdapter::OMXCameraAdapterFillBufferDone(OMX_IN OMX_HANDLETYPE hComponent,
2658                                   OMX_IN OMX_BUFFERHEADERTYPE* pBuffHeader)
2659{
2660
2661    status_t  stat = NO_ERROR;
2662    status_t  res1, res2;
2663    OMXCameraPortParameters  *pPortParam;
2664    OMX_ERRORTYPE eError = OMX_ErrorNone;
2665    CameraFrame::FrameType typeOfFrame = CameraFrame::ALL_FRAMES;
2666    unsigned int refCount = 0;
2667    BaseCameraAdapter::AdapterState state;
2668    BaseCameraAdapter::getState(state);
2669    sp<CameraFDResult> fdResult = NULL;
2670
2671    res1 = res2 = NO_ERROR;
2672    pPortParam = &(mCameraAdapterParameters.mCameraPortParams[pBuffHeader->nOutputPortIndex]);
2673    if (pBuffHeader->nOutputPortIndex == OMX_CAMERA_PORT_VIDEO_OUT_PREVIEW)
2674        {
2675
2676        if ( ( PREVIEW_ACTIVE & state ) != PREVIEW_ACTIVE )
2677            {
2678            return OMX_ErrorNone;
2679            }
2680
2681        recalculateFPS();
2682
2683            {
2684            Mutex::Autolock lock(mFaceDetectionLock);
2685            if ( mFaceDetectionRunning ) {
2686                detectFaces(pBuffHeader, fdResult, pPortParam->mWidth, pPortParam->mHeight);
2687                if ( NULL != fdResult.get() ) {
2688                    notifyFaceSubscribers(fdResult);
2689                    fdResult.clear();
2690                }
2691            }
2692            }
2693
2694        stat |= advanceZoom();
2695
2696        ///On the fly update to 3A settings not working
2697        if( mPending3Asettings )
2698            {
2699            apply3Asettings(mParameters3A);
2700            }
2701
2702        ///Prepare the frames to be sent - initialize CameraFrame object and reference count
2703        CameraFrame cameraFrameVideo, cameraFramePreview;
2704        if ( mRecording )
2705            {
2706            res1 = initCameraFrame(cameraFrameVideo,
2707                                   pBuffHeader,
2708                                   CameraFrame::VIDEO_FRAME_SYNC,
2709                                   pPortParam);
2710            }
2711
2712        if( mWaitingForSnapshot )
2713            {
2714            typeOfFrame = CameraFrame::SNAPSHOT_FRAME;
2715            }
2716        else
2717            {
2718            typeOfFrame = CameraFrame::PREVIEW_FRAME_SYNC;
2719            }
2720
2721        LOGV("FBD pBuffer = 0x%x", pBuffHeader->pBuffer);
2722
2723        res2 = initCameraFrame(cameraFramePreview,
2724                               pBuffHeader,
2725                               typeOfFrame,
2726                               pPortParam);
2727
2728        stat |= res1 | res2;
2729
2730        if ( mRecording )
2731            {
2732            res1  = sendFrame(cameraFrameVideo);
2733            }
2734
2735        if( mWaitingForSnapshot )
2736            {
2737            mSnapshotCount++;
2738
2739            if (  ( mSnapshotCount == 1 ) &&
2740                ( HIGH_SPEED == mCapMode ) )
2741                {
2742                notifyShutterSubscribers();
2743                }
2744            }
2745
2746        // TODO(XXX): temporary hack. must remove after setconfig and transition issue
2747        //            with secondary camera is fixed
2748        if (mWaitToSetConfig && mFrameCount == NUM_SKIP_FRAMES) {
2749            mWaitToSetConfig = false;
2750            if (mFaceDetectionRunning) startFaceDetection();
2751            setParameters(mParams);
2752            mCommandHandler->setWait(false);
2753        }
2754
2755        res2 = sendFrame(cameraFramePreview);
2756
2757        stat |= ( ( NO_ERROR == res1 ) || ( NO_ERROR == res2 ) ) ? ( ( int ) NO_ERROR ) : ( -1 );
2758
2759        }
2760    else if( pBuffHeader->nOutputPortIndex == OMX_CAMERA_PORT_VIDEO_OUT_MEASUREMENT )
2761        {
2762        typeOfFrame = CameraFrame::FRAME_DATA_SYNC;
2763        CameraFrame cameraFrame;
2764        stat |= initCameraFrame(cameraFrame,
2765                                pBuffHeader,
2766                                typeOfFrame,
2767                                pPortParam);
2768        stat |= sendFrame(cameraFrame);
2769       }
2770    else if( pBuffHeader->nOutputPortIndex == OMX_CAMERA_PORT_IMAGE_OUT_IMAGE )
2771        {
2772
2773        if ( OMX_COLOR_FormatUnused == mCameraAdapterParameters.mCameraPortParams[mCameraAdapterParameters.mImagePortIndex].mColorFormat )
2774            {
2775            typeOfFrame = CameraFrame::IMAGE_FRAME;
2776            }
2777        else
2778            {
2779            typeOfFrame = CameraFrame::RAW_FRAME;
2780            }
2781
2782            pPortParam->mImageType = typeOfFrame;
2783
2784            if((mCapturedFrames>0) && !mCaptureSignalled)
2785                {
2786                mCaptureSignalled = true;
2787                mCaptureSem.Signal();
2788                }
2789
2790            if( ( CAPTURE_ACTIVE & state ) != CAPTURE_ACTIVE )
2791                {
2792                goto EXIT;
2793                }
2794
2795            {
2796            Mutex::Autolock lock(mBracketingLock);
2797            if ( mBracketingEnabled )
2798                {
2799                doBracketing(pBuffHeader, typeOfFrame);
2800                return eError;
2801                }
2802            }
2803
2804        if ( 1 > mCapturedFrames )
2805            {
2806            goto EXIT;
2807            }
2808
2809        CAMHAL_LOGDB("Captured Frames: %d", mCapturedFrames);
2810
2811        mCapturedFrames--;
2812
2813        CameraFrame cameraFrame;
2814        stat |= initCameraFrame(cameraFrame,
2815                                pBuffHeader,
2816                                typeOfFrame,
2817                                pPortParam);
2818        stat |= sendFrame(cameraFrame);
2819        }
2820    else
2821        {
2822        CAMHAL_LOGEA("Frame received for non-(preview/capture/measure) port. This is yet to be supported");
2823        goto EXIT;
2824        }
2825
2826    if ( NO_ERROR != stat )
2827        {
2828        CAMHAL_LOGDB("sendFrameToSubscribers error: %d", stat);
2829        returnFrame(pBuffHeader->pBuffer, typeOfFrame);
2830        }
2831
2832    return eError;
2833
2834    EXIT:
2835
2836    CAMHAL_LOGEB("Exiting function %s because of ret %d eError=%x", __FUNCTION__, stat, eError);
2837
2838    if ( NO_ERROR != stat )
2839        {
2840        if ( NULL != mErrorNotifier )
2841            {
2842            mErrorNotifier->errorNotify(CAMERA_ERROR_UNKNOWN);
2843            }
2844        }
2845
2846    return eError;
2847}
2848
2849status_t OMXCameraAdapter::recalculateFPS()
2850{
2851    float currentFPS;
2852
2853    mFrameCount++;
2854
2855    if ( ( mFrameCount % FPS_PERIOD ) == 0 )
2856        {
2857        nsecs_t now = systemTime();
2858        nsecs_t diff = now - mLastFPSTime;
2859        currentFPS =  ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
2860        mLastFPSTime = now;
2861        mLastFrameCount = mFrameCount;
2862
2863        if ( 1 == mIter )
2864            {
2865            mFPS = currentFPS;
2866            }
2867        else
2868            {
2869            //cumulative moving average
2870            mFPS = mLastFPS + (currentFPS - mLastFPS)/mIter;
2871            }
2872
2873        mLastFPS = mFPS;
2874        mIter++;
2875        }
2876
2877    return NO_ERROR;
2878}
2879
2880status_t OMXCameraAdapter::sendFrame(CameraFrame &frame)
2881{
2882    status_t ret = NO_ERROR;
2883
2884    LOG_FUNCTION_NAME;
2885
2886
2887    if ( NO_ERROR == ret )
2888        {
2889        ret = sendFrameToSubscribers(&frame);
2890        }
2891
2892    LOG_FUNCTION_NAME_EXIT;
2893
2894    return ret;
2895}
2896
2897status_t OMXCameraAdapter::initCameraFrame( CameraFrame &frame,
2898                                            OMX_IN OMX_BUFFERHEADERTYPE *pBuffHeader,
2899                                            int typeOfFrame,
2900                                            OMXCameraPortParameters *port)
2901{
2902    status_t ret = NO_ERROR;
2903
2904    LOG_FUNCTION_NAME;
2905
2906    if ( NULL == port)
2907        {
2908        CAMHAL_LOGEA("Invalid portParam");
2909        return -EINVAL;
2910        }
2911
2912    if ( NULL == pBuffHeader )
2913        {
2914        CAMHAL_LOGEA("Invalid Buffer header");
2915        return -EINVAL;
2916        }
2917
2918    frame.mFrameType = typeOfFrame;
2919    frame.mBuffer = pBuffHeader->pBuffer;
2920    frame.mLength = pBuffHeader->nFilledLen;
2921    frame.mAlignment = port->mStride;
2922    frame.mOffset = pBuffHeader->nOffset;
2923    frame.mWidth = port->mWidth;
2924    frame.mHeight = port->mHeight;
2925
2926    // Calculating the time source delta of Ducati & system time only once at the start of camera.
2927    // It's seen that there is a one-time constant diff between the ducati source clock &
2928    // System monotonic timer, although both derived from the same 32KHz clock.
2929    // This delta is offsetted to/from ducati timestamp to match with system time so that
2930    // video timestamps are aligned with Audio with a periodic timestamp intervals.
2931    if ( onlyOnce )
2932        {
2933        mTimeSourceDelta = (pBuffHeader->nTimeStamp * 1000) - systemTime(SYSTEM_TIME_MONOTONIC);
2934        onlyOnce = false;
2935        }
2936
2937    // Calculating the new video timestamp based on offset from ducati source.
2938    frame.mTimestamp = (pBuffHeader->nTimeStamp * 1000) - mTimeSourceDelta;
2939
2940        LOG_FUNCTION_NAME_EXIT;
2941
2942    return ret;
2943}
2944
2945bool OMXCameraAdapter::CommandHandler::Handler()
2946{
2947    TIUTILS::Message msg;
2948    volatile int forever = 1;
2949    status_t stat;
2950    ErrorNotifier *errorNotify = NULL;
2951
2952    LOG_FUNCTION_NAME;
2953
2954    while ( forever )
2955    {
2956        stat = NO_ERROR;
2957        CAMHAL_LOGDA("Handler: waiting for messsage...");
2958        TIUTILS::MessageQueue::waitForMsg(&mCommandMsgQ, NULL, NULL, -1);
2959
2960        // TODO(XXX): temporary hack. must remove after setconfig and transition issue
2961        //            with secondary camera is fixed
2962        if (!mWaitToSetConfig && !mForceQuit) {
2963            mCommandMsgQ.get(&msg);
2964            CAMHAL_LOGDB("msg.command = %d", msg.command);
2965            switch ( msg.command ) {
2966                case CommandHandler::CAMERA_START_IMAGE_CAPTURE:
2967                {
2968                    stat = mCameraAdapter->startImageCapture();
2969                    break;
2970                }
2971                case CommandHandler::CAMERA_PERFORM_AUTOFOCUS:
2972                {
2973                    stat = mCameraAdapter->doAutoFocus();
2974                    break;
2975                }
2976                case CommandHandler::COMMAND_EXIT:
2977                {
2978                    CAMHAL_LOGEA("Exiting command handler");
2979                    forever = 0;
2980                    break;
2981               }
2982            }
2983
2984            if ( NO_ERROR != stat )
2985            {
2986                errorNotify = ( ErrorNotifier * ) msg.arg1;
2987                if ( NULL != errorNotify )
2988                {
2989                    errorNotify->errorNotify(CAMERA_ERROR_UNKNOWN);
2990                }
2991            }
2992        } else if (mForceQuit) {
2993            forever = 0;
2994        } else {
2995            usleep(1000 * NUM_SKIP_FRAMES); // sleep thread for X amount of ms.
2996        }
2997    }
2998
2999    LOG_FUNCTION_NAME_EXIT;
3000
3001    return false;
3002}
3003
3004bool OMXCameraAdapter::OMXCallbackHandler::Handler()
3005{
3006    TIUTILS::Message msg;
3007    volatile int forever = 1;
3008    status_t ret = NO_ERROR;
3009
3010    LOG_FUNCTION_NAME;
3011
3012    while(forever){
3013        TIUTILS::MessageQueue::waitForMsg(&mCommandMsgQ, NULL, NULL, -1);
3014        mCommandMsgQ.get(&msg);
3015        switch ( msg.command ) {
3016            case OMXCallbackHandler::CAMERA_FILL_BUFFER_DONE:
3017            {
3018                ret = mCameraAdapter->OMXCameraAdapterFillBufferDone(( OMX_HANDLETYPE ) msg.arg1,
3019                                                                     ( OMX_BUFFERHEADERTYPE *) msg.arg2);
3020                break;
3021            }
3022            case CommandHandler::COMMAND_EXIT:
3023            {
3024                CAMHAL_LOGEA("Exiting OMX callback handler");
3025                forever = 0;
3026                break;
3027            }
3028        }
3029    }
3030
3031    LOG_FUNCTION_NAME_EXIT;
3032    return false;
3033}
3034
3035OMXCameraAdapter::OMXCameraAdapter():mComponentState (OMX_StateInvalid)
3036{
3037    LOG_FUNCTION_NAME;
3038
3039    mPictureRotation = 0;
3040    // Initial values
3041    mTimeSourceDelta = 0;
3042    onlyOnce = true;
3043
3044    mDoAFSem.Create(0);
3045    mInitSem.Create(0);
3046    mFlushSem.Create(0);
3047    mUsePreviewDataSem.Create(0);
3048    mUsePreviewSem.Create(0);
3049    mUseCaptureSem.Create(0);
3050    mStartPreviewSem.Create(0);
3051    mStopPreviewSem.Create(0);
3052    mStartCaptureSem.Create(0);
3053    mStopCaptureSem.Create(0);
3054    mSwitchToLoadedSem.Create(0);
3055    mCaptureSem.Create(0);
3056
3057    mCameraAdapterParameters.mHandleComp = 0;
3058
3059    LOG_FUNCTION_NAME_EXIT;
3060}
3061
3062OMXCameraAdapter::~OMXCameraAdapter()
3063{
3064    LOG_FUNCTION_NAME;
3065
3066    Mutex::Autolock lock(gAdapterLock);
3067
3068    //Return to OMX Loaded state
3069    switchToLoaded();
3070
3071    ///Free the handle for the Camera component
3072    if(mCameraAdapterParameters.mHandleComp)
3073        {
3074        OMX_FreeHandle(mCameraAdapterParameters.mHandleComp);
3075        }
3076
3077    ///De-init the OMX
3078    if( (mComponentState==OMX_StateLoaded) || (mComponentState==OMX_StateInvalid))
3079        {
3080        OMX_Deinit();
3081        }
3082
3083    //Exit and free ref to command handling thread
3084    if ( NULL != mCommandHandler.get() )
3085    {
3086        TIUTILS::Message msg;
3087        msg.command = CommandHandler::COMMAND_EXIT;
3088        msg.arg1 = mErrorNotifier;
3089        mCommandHandler->put(&msg);
3090
3091        // TODO(XXX): temporary hack. must remove after setconfig and transition issue
3092        //            with secondary camera is fixed
3093        if(mWaitToSetConfig) mCommandHandler->setForceQuit();
3094
3095        mCommandHandler->requestExitAndWait();
3096        mCommandHandler.clear();
3097    }
3098
3099    //Exit and free ref to callback handling thread
3100    if ( NULL != mOMXCallbackHandler.get() )
3101    {
3102        TIUTILS::Message msg;
3103        msg.command = OMXCallbackHandler::COMMAND_EXIT;
3104        mOMXCallbackHandler->put(&msg);
3105        mOMXCallbackHandler->requestExitAndWait();
3106        mOMXCallbackHandler.clear();
3107    }
3108
3109    gCameraAdapter = NULL;
3110
3111    LOG_FUNCTION_NAME_EXIT;
3112}
3113
3114extern "C" CameraAdapter* CameraAdapter_Factory()
3115{
3116    Mutex::Autolock lock(gAdapterLock);
3117
3118    LOG_FUNCTION_NAME;
3119
3120    if ( NULL == gCameraAdapter )
3121        {
3122        CAMHAL_LOGDA("Creating new Camera adapter instance");
3123        gCameraAdapter= new OMXCameraAdapter();
3124        }
3125    else
3126        {
3127        CAMHAL_LOGDA("Reusing existing Camera adapter instance");
3128        }
3129
3130    LOG_FUNCTION_NAME_EXIT;
3131
3132    return gCameraAdapter;
3133}
3134
3135extern "C" int CameraAdapter_Capabilities(CameraProperties::Properties* properties_array,
3136                                          const unsigned int starting_camera,
3137                                          const unsigned int max_camera) {
3138    int num_cameras_supported = 0;
3139    CameraProperties::Properties* properties = NULL;
3140    OMX_ERRORTYPE eError = OMX_ErrorNone;
3141    OMX_HANDLETYPE handle = NULL;
3142    OMX_TI_CAPTYPE caps;
3143
3144    LOG_FUNCTION_NAME;
3145
3146    if (!properties_array) {
3147        CAMHAL_LOGEB("invalid param: properties = 0x%p", properties_array);
3148        LOG_FUNCTION_NAME_EXIT;
3149        return -EINVAL;
3150    }
3151
3152    // OMX_Init
3153    eError = OMX_Init();
3154    if (eError != OMX_ErrorNone) {
3155        CAMHAL_LOGEB("OMX_Init -0x%x", eError);
3156        return 0;  // no cameras supported
3157    }
3158
3159    // Setup key parameters to send to Ducati during init
3160    OMX_CALLBACKTYPE oCallbacks;
3161
3162    // Initialize the callback handles
3163    oCallbacks.EventHandler    = android::OMXCameraAdapterEventHandler;
3164    oCallbacks.EmptyBufferDone = android::OMXCameraAdapterEmptyBufferDone;
3165    oCallbacks.FillBufferDone  = android::OMXCameraAdapterFillBufferDone;
3166
3167    // Get Handle
3168    eError = OMX_GetHandle(&handle, (OMX_STRING)"OMX.TI.DUCATI1.VIDEO.CAMERA", NULL, &oCallbacks);
3169    if (eError != OMX_ErrorNone) {
3170        CAMHAL_LOGEB("OMX_GetHandle -0x%x", eError);
3171        goto EXIT;
3172    }
3173
3174    // Continue selecting sensor and then querying OMX Camera for it's capabilities
3175    // When sensor select returns an error, we know to break and stop
3176    while (eError == OMX_ErrorNone &&
3177           (starting_camera + num_cameras_supported) < max_camera) {
3178        // sensor select
3179        OMX_CONFIG_SENSORSELECTTYPE sensorSelect;
3180        OMX_INIT_STRUCT_PTR (&sensorSelect, OMX_CONFIG_SENSORSELECTTYPE);
3181        sensorSelect.eSensor = (OMX_SENSORSELECT) num_cameras_supported;
3182        eError = OMX_SetConfig(handle, ( OMX_INDEXTYPE ) OMX_TI_IndexConfigSensorSelect, &sensorSelect);
3183
3184        if ( OMX_ErrorNone != eError ) {
3185            break;
3186        }
3187
3188        // get and fill capabilities
3189        properties = properties_array + starting_camera + num_cameras_supported;
3190        OMXCameraAdapter::getCaps(properties, handle);
3191
3192        // need to fill facing information
3193        // assume that only sensor 0 is back facing
3194        if (num_cameras_supported == 0) {
3195            properties->set(CameraProperties::FACING_INDEX, TICameraParameters::FACING_BACK);
3196        } else {
3197            properties->set(CameraProperties::FACING_INDEX, TICameraParameters::FACING_FRONT);
3198        }
3199
3200        num_cameras_supported++;
3201    }
3202
3203 EXIT:
3204    // clean up
3205    if(handle) {
3206        OMX_FreeHandle(handle);
3207    }
3208    OMX_Deinit();
3209
3210    LOG_FUNCTION_NAME_EXIT;
3211
3212    return num_cameras_supported;
3213}
3214
3215};
3216
3217
3218/*--------------------Camera Adapter Class ENDS here-----------------------------*/
3219
3220