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