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