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