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