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