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