CameraHal.cpp revision d1e16379476a175660ef8f6934c289edeed6b7fc
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 CameraHal.cpp
19*
20* This file maps the Camera Hardware Interface to V4L2.
21*
22*/
23
24#define LOG_TAG "CameraHAL"
25
26#include "CameraHal.h"
27#include "ANativeWindowDisplayAdapter.h"
28#include "TICameraParameters.h"
29#include "CameraProperties.h"
30#include <cutils/properties.h>
31
32#include <poll.h>
33#include <math.h>
34
35namespace android {
36
37extern "C" CameraAdapter* CameraAdapter_Factory();
38
39/*****************************************************************************/
40
41////Constant definitions and declarations
42////@todo Have a CameraProperties class to store these parameters as constants for every camera
43////       Currently, they are hard-coded
44
45const int CameraHal::NO_BUFFERS_PREVIEW = MAX_CAMERA_BUFFERS;
46const int CameraHal::NO_BUFFERS_IMAGE_CAPTURE = 2;
47
48const uint32_t MessageNotifier::EVENT_BIT_FIELD_POSITION = 0;
49const uint32_t MessageNotifier::FRAME_BIT_FIELD_POSITION = 0;
50
51/******************************************************************************/
52
53#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
54
55struct timeval CameraHal::mStartPreview;
56struct timeval CameraHal::mStartFocus;
57struct timeval CameraHal::mStartCapture;
58
59#endif
60
61static void orientation_cb(uint32_t orientation, uint32_t tilt, void* cookie) {
62    CameraHal *camera = NULL;
63
64    if (cookie) {
65        camera = (CameraHal*) cookie;
66        camera->onOrientationEvent(orientation, tilt);
67    }
68
69}
70/*-------------Camera Hal Interface Method definitions STARTS here--------------------*/
71
72/**
73  Callback function to receive orientation events from SensorListener
74 */
75void CameraHal::onOrientationEvent(uint32_t orientation, uint32_t tilt) {
76    LOG_FUNCTION_NAME;
77
78    if ( NULL != mCameraAdapter ) {
79        mCameraAdapter->onOrientationEvent(orientation, tilt);
80    }
81
82    LOG_FUNCTION_NAME_EXIT;
83}
84
85/**
86   @brief Set the notification and data callbacks
87
88   @param[in] notify_cb Notify callback for notifying the app about events and errors
89   @param[in] data_cb   Buffer callback for sending the preview/raw frames to the app
90   @param[in] data_cb_timestamp Buffer callback for sending the video frames w/ timestamp
91   @param[in] user  Callback cookie
92   @return none
93
94 */
95void CameraHal::setCallbacks(camera_notify_callback notify_cb,
96                            camera_data_callback data_cb,
97                            camera_data_timestamp_callback data_cb_timestamp,
98                            camera_request_memory get_memory,
99                            void *user)
100{
101    LOG_FUNCTION_NAME;
102
103    if ( NULL != mAppCallbackNotifier.get() )
104    {
105            mAppCallbackNotifier->setCallbacks(this,
106                                                notify_cb,
107                                                data_cb,
108                                                data_cb_timestamp,
109                                                get_memory,
110                                                user);
111    }
112
113    LOG_FUNCTION_NAME_EXIT;
114}
115
116/**
117   @brief Enable a message, or set of messages.
118
119   @param[in] msgtype Bitmask of the messages to enable (defined in include/ui/Camera.h)
120   @return none
121
122 */
123void CameraHal::enableMsgType(int32_t msgType)
124{
125    LOG_FUNCTION_NAME;
126
127    if ( ( msgType & CAMERA_MSG_SHUTTER ) && ( !mShutterEnabled ) )
128        {
129        msgType &= ~CAMERA_MSG_SHUTTER;
130        }
131
132    {
133    Mutex::Autolock lock(mLock);
134    mMsgEnabled |= msgType;
135    }
136
137    if(mMsgEnabled & CAMERA_MSG_PREVIEW_FRAME)
138    {
139        if(mDisplayPaused)
140        {
141            CAMHAL_LOGDA("Preview currently paused...will enable preview callback when restarted");
142            msgType &= ~CAMERA_MSG_PREVIEW_FRAME;
143        }else
144        {
145            CAMHAL_LOGDA("Enabling Preview Callback");
146        }
147    }
148    else
149    {
150        CAMHAL_LOGDB("Preview callback not enabled %x", msgType);
151    }
152
153
154    ///Configure app callback notifier with the message callback required
155    mAppCallbackNotifier->enableMsgType (msgType);
156
157    LOG_FUNCTION_NAME_EXIT;
158}
159
160/**
161   @brief Disable a message, or set of messages.
162
163   @param[in] msgtype Bitmask of the messages to disable (defined in include/ui/Camera.h)
164   @return none
165
166 */
167void CameraHal::disableMsgType(int32_t msgType)
168{
169    LOG_FUNCTION_NAME;
170
171        {
172        Mutex::Autolock lock(mLock);
173        mMsgEnabled &= ~msgType;
174        }
175
176    if( msgType & CAMERA_MSG_PREVIEW_FRAME)
177        {
178        CAMHAL_LOGDA("Disabling Preview Callback");
179        }
180
181    ///Configure app callback notifier
182    mAppCallbackNotifier->disableMsgType (msgType);
183
184    LOG_FUNCTION_NAME_EXIT;
185}
186
187/**
188   @brief Query whether a message, or a set of messages, is enabled.
189
190   Note that this is operates as an AND, if any of the messages queried are off, this will
191   return false.
192
193   @param[in] msgtype Bitmask of the messages to query (defined in include/ui/Camera.h)
194   @return true If all message types are enabled
195          false If any message type
196
197 */
198int CameraHal::msgTypeEnabled(int32_t msgType)
199{
200    LOG_FUNCTION_NAME;
201    Mutex::Autolock lock(mLock);
202    LOG_FUNCTION_NAME_EXIT;
203    return (mMsgEnabled & msgType);
204}
205
206/**
207   @brief Set the camera parameters.
208
209   @param[in] params Camera parameters to configure the camera
210   @return NO_ERROR
211   @todo Define error codes
212
213 */
214int CameraHal::setParameters(const char* parameters)
215{
216
217   LOG_FUNCTION_NAME;
218
219    CameraParameters params;
220
221    String8 str_params(parameters);
222    params.unflatten(str_params);
223
224    LOG_FUNCTION_NAME_EXIT;
225
226    return setParameters(params);
227}
228
229/**
230   @brief Set the camera parameters.
231
232   @param[in] params Camera parameters to configure the camera
233   @return NO_ERROR
234   @todo Define error codes
235
236 */
237int CameraHal::setParameters(const CameraParameters& params)
238{
239
240   LOG_FUNCTION_NAME;
241
242    int w, h;
243    int w_orig, h_orig;
244    int framerate,minframerate;
245    int maxFPS, minFPS;
246    int error;
247    int base;
248    const char *valstr = NULL;
249    const char *prevFormat;
250    char *af_coord;
251    TIUTILS::Message msg;
252    status_t ret = NO_ERROR;
253    // Needed for KEY_RECORDING_HINT
254    bool restartPreviewRequired = false;
255    bool updateRequired = false;
256    CameraParameters oldParams(mParameters.flatten());
257    bool videoMode = false;
258    char range[MAX_PROP_VALUE_LENGTH];
259
260    {
261        Mutex::Autolock lock(mLock);
262
263        ///Ensure that preview is not enabled when the below parameters are changed.
264        if(!previewEnabled())
265            {
266
267            CAMHAL_LOGDB("PreviewFormat %s", params.getPreviewFormat());
268
269            if ((valstr = params.getPreviewFormat()) != NULL) {
270                if ( isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_FORMATS))) {
271                    mParameters.setPreviewFormat(valstr);
272                } else {
273                    CAMHAL_LOGEB("Invalid preview format.Supported: %s",  mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_FORMATS));
274                    return -EINVAL;
275                }
276            }
277
278            if ((valstr = params.get(TICameraParameters::KEY_VNF)) != NULL) {
279                if ( (params.getInt(TICameraParameters::KEY_VNF)==0) || (params.getInt(TICameraParameters::KEY_VNF)==1) ) {
280                    CAMHAL_LOGDB("VNF set %s", params.get(TICameraParameters::KEY_VNF));
281                    mParameters.set(TICameraParameters::KEY_VNF, valstr);
282                } else {
283                    CAMHAL_LOGEB("ERROR: Invalid VNF: %s", valstr);
284                    ret = -EINVAL;
285                }
286            }
287
288            if ((valstr = params.get(TICameraParameters::KEY_VSTAB)) != NULL) {
289                if ((params.getInt(TICameraParameters::KEY_VSTAB)==0) || (params.getInt(TICameraParameters::KEY_VSTAB)==1)) {
290                    CAMHAL_LOGDB("VSTAB set %s", params.get(TICameraParameters::KEY_VSTAB));
291                    mParameters.set(TICameraParameters::KEY_VSTAB, valstr);
292                } else {
293                    CAMHAL_LOGEB("ERROR: Invalid VSTAB: %s", valstr);
294                    ret = -EINVAL;
295                }
296            }
297
298            if( (valstr = params.get(TICameraParameters::KEY_CAP_MODE)) != NULL)
299                {
300                CAMHAL_LOGDB("Capture mode set %s", params.get(TICameraParameters::KEY_CAP_MODE));
301                mParameters.set(TICameraParameters::KEY_CAP_MODE, valstr);
302                }
303
304            if ((valstr = params.get(TICameraParameters::KEY_IPP)) != NULL) {
305                if (isParameterValid(valstr,mCameraProperties->get(CameraProperties::SUPPORTED_IPP_MODES))) {
306                    CAMHAL_LOGDB("IPP mode set %s", params.get(TICameraParameters::KEY_IPP));
307                    mParameters.set(TICameraParameters::KEY_IPP, valstr);
308                } else {
309                    CAMHAL_LOGEB("ERROR: Invalid IPP mode: %s", valstr);
310                    ret = -EINVAL;
311                }
312            }
313
314            if((valstr = params.get(TICameraParameters::KEY_S3D2D_PREVIEW)) != NULL)
315                {
316                CAMHAL_LOGDB("Stereo 3D->2D Preview mode is %s", params.get(TICameraParameters::KEY_S3D2D_PREVIEW));
317                mParameters.set(TICameraParameters::KEY_S3D2D_PREVIEW, valstr);
318                }
319
320            if((valstr = params.get(TICameraParameters::KEY_AUTOCONVERGENCE)) != NULL)
321                {
322                CAMHAL_LOGDB("AutoConvergence mode is %s", params.get(TICameraParameters::KEY_AUTOCONVERGENCE));
323                mParameters.set(TICameraParameters::KEY_AUTOCONVERGENCE, valstr);
324                }
325
326            }
327
328        //CTS requirement, we should be able to change the preview resolution
329        //while in paused display state
330        if ( !previewEnabled() || mDisplayPaused )
331            {
332            params.getPreviewSize(&w, &h);
333            if (w == -1 && h == -1) {
334                CAMHAL_LOGEA("Unable to get preview size");
335                return -EINVAL;
336              }
337
338            int oldWidth, oldHeight;
339            mParameters.getPreviewSize(&oldWidth, &oldHeight);
340
341            int orientation =0;
342            if((valstr = params.get(TICameraParameters::KEY_SENSOR_ORIENTATION)) != NULL)
343                {
344                CAMHAL_LOGDB("Sensor Orientation is set to %s", params.get(TICameraParameters::KEY_SENSOR_ORIENTATION));
345                mParameters.set(TICameraParameters::KEY_SENSOR_ORIENTATION, valstr);
346                orientation = params.getInt(TICameraParameters::KEY_SENSOR_ORIENTATION);
347                }
348
349            if(orientation ==90 || orientation ==270)
350           {
351              if ( !isResolutionValid(h,w, mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_SIZES)))
352               {
353                CAMHAL_LOGEB("Invalid preview resolution %d x %d", w, h);
354                return -EINVAL;
355               }
356              else
357              {
358                mParameters.setPreviewSize(w, h);
359               }
360           }
361           else
362           {
363            if ( !isResolutionValid(w, h, mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_SIZES)))
364                {
365                CAMHAL_LOGEB("Invalid preview resolution %d x %d", w, h);
366                return -EINVAL;
367                }
368            else
369                {
370                mParameters.setPreviewSize(w, h);
371                }
372           }
373
374            if ( ( oldWidth != w ) || ( oldHeight != h ) )
375                {
376                mDynamicPreviewSwitch = true;
377                }
378
379            CAMHAL_LOGDB("PreviewResolution by App %d x %d", w, h);
380            }
381
382        // Handle RECORDING_HINT to Set/Reset Video Mode Parameters
383        valstr = params.get(CameraParameters::KEY_RECORDING_HINT);
384        if(valstr != NULL)
385            {
386            if(strcmp(valstr, CameraParameters::TRUE) == 0)
387                {
388                CAMHAL_LOGDB("Recording Hint is set to %s", valstr);
389                mParameters.set(CameraParameters::KEY_RECORDING_HINT, valstr);
390                restartPreviewRequired = setVideoModeParameters();
391                videoMode = true;
392                }
393            else if(strcmp(valstr, CameraParameters::FALSE) == 0)
394                {
395                CAMHAL_LOGDB("Recording Hint is set to %s", valstr);
396                mParameters.set(CameraParameters::KEY_RECORDING_HINT, valstr);
397                restartPreviewRequired = resetVideoModeParameters();
398                }
399            else
400                {
401                CAMHAL_LOGEA("Invalid RECORDING_HINT");
402                return -EINVAL;
403                }
404            }
405        else
406            {
407            // This check is required in following case.
408            // If VideoRecording activity sets KEY_RECORDING_HINT to TRUE and
409            // ImageCapture activity doesnot set KEY_RECORDING_HINT to FALSE (i.e. simply NULL),
410            // then Video Mode parameters may remain present in ImageCapture activity as well.
411            CAMHAL_LOGDA("Recording Hint is set to NULL");
412            mParameters.set(CameraParameters::KEY_RECORDING_HINT, "");
413            restartPreviewRequired = resetVideoModeParameters();
414            }
415
416        ///Below parameters can be changed when the preview is running
417        if ( (valstr = params.getPictureFormat()) != NULL ) {
418            if (isParameterValid(params.getPictureFormat(),mCameraProperties->get(CameraProperties::SUPPORTED_PICTURE_FORMATS))) {
419                mParameters.setPictureFormat(valstr);
420            } else {
421                CAMHAL_LOGEB("ERROR: Invalid picture format: %s",valstr);
422                ret = -EINVAL;
423            }
424            }
425
426        params.getPictureSize(&w, &h);
427        if ( isResolutionValid(w, h, mCameraProperties->get(CameraProperties::SUPPORTED_PICTURE_SIZES))) {
428            mParameters.setPictureSize(w, h);
429        } else {
430            CAMHAL_LOGEB("ERROR: Invalid picture resolution %dx%d", w, h);
431            ret = -EINVAL;
432        }
433
434        CAMHAL_LOGDB("Picture Size by App %d x %d", w, h);
435
436        if ((valstr = params.get(TICameraParameters::KEY_BURST)) != NULL) {
437            if (params.getInt(TICameraParameters::KEY_BURST) >=0) {
438                CAMHAL_LOGDB("Burst set %s", params.get(TICameraParameters::KEY_BURST));
439                mParameters.set(TICameraParameters::KEY_BURST, valstr);
440            } else {
441                CAMHAL_LOGEB("ERROR: Invalid Burst value: %s",valstr);
442                ret = -EINVAL;
443            }
444        }
445
446        framerate = params.getPreviewFrameRate();
447        valstr = params.get(CameraParameters::KEY_PREVIEW_FPS_RANGE);
448        CAMHAL_LOGDB("FRAMERATE %d", framerate);
449
450        CAMHAL_LOGVB("Passed FRR: %s, Supported FRR %s", valstr
451                        , mCameraProperties->get(CameraProperties::FRAMERATE_RANGE_SUPPORTED));
452        CAMHAL_LOGVB("Passed FR: %d, Supported FR %s", framerate
453                        , mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_FRAME_RATES));
454
455
456        //Perform parameter validation
457        if(!isParameterValid(valstr
458                        , mCameraProperties->get(CameraProperties::FRAMERATE_RANGE_SUPPORTED))
459                        || !isParameterValid(framerate,
460                                      mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_FRAME_RATES)))
461        {
462            CAMHAL_LOGEA("Invalid frame rate range or frame rate");
463            return -EINVAL;
464        }
465
466        // Variable framerate ranges have higher priority over
467        // deprecated constant FPS. "KEY_PREVIEW_FPS_RANGE" should
468        // be cleared by the client in order for constant FPS to get
469        // applied.
470        if ( strcmp(valstr, mCameraProperties->get(CameraProperties::FRAMERATE_RANGE))  != 0)
471          {
472            // APP wants to set FPS range
473            //Set framerate = MAXFPS
474            CAMHAL_LOGDA("APP IS CHANGING FRAME RATE RANGE");
475            params.getPreviewFpsRange(&minFPS, &maxFPS);
476
477            if ( ( 0 > minFPS ) || ( 0 > maxFPS ) )
478              {
479                CAMHAL_LOGEA("ERROR: FPS Range is negative!");
480                return -EINVAL;
481              }
482
483            framerate = maxFPS /CameraHal::VFR_SCALE;
484
485          }
486        else
487          {
488              if ( framerate != atoi(mCameraProperties->get(CameraProperties::PREVIEW_FRAME_RATE)) )
489              {
490
491                selectFPSRange(framerate, &minFPS, &maxFPS);
492                CAMHAL_LOGDB("Select FPS Range %d %d", minFPS, maxFPS);
493              }
494              else
495                {
496                    if (videoMode) {
497                        valstr = mCameraProperties->get(CameraProperties::FRAMERATE_RANGE_VIDEO);
498                        CameraParameters temp;
499                        temp.set(CameraParameters::KEY_PREVIEW_FPS_RANGE, valstr);
500                        temp.getPreviewFpsRange(&minFPS, &maxFPS);
501                    }
502                    else {
503                        valstr = mCameraProperties->get(CameraProperties::FRAMERATE_RANGE_IMAGE);
504                        CameraParameters temp;
505                        temp.set(CameraParameters::KEY_PREVIEW_FPS_RANGE, valstr);
506                        temp.getPreviewFpsRange(&minFPS, &maxFPS);
507                    }
508
509                    framerate = maxFPS / CameraHal::VFR_SCALE;
510                }
511
512          }
513
514        CAMHAL_LOGDB("FPS Range = %s", valstr);
515        CAMHAL_LOGDB("DEFAULT FPS Range = %s", mCameraProperties->get(CameraProperties::FRAMERATE_RANGE));
516
517        minFPS /= CameraHal::VFR_SCALE;
518        maxFPS /= CameraHal::VFR_SCALE;
519
520        if ( ( 0 == minFPS ) || ( 0 == maxFPS ) )
521          {
522            CAMHAL_LOGEA("ERROR: FPS Range is invalid!");
523            ret = -EINVAL;
524          }
525
526        if ( maxFPS < minFPS )
527          {
528            CAMHAL_LOGEA("ERROR: Max FPS is smaller than Min FPS!");
529            ret = -EINVAL;
530          }
531        CAMHAL_LOGDB("SET FRAMERATE %d", framerate);
532        mParameters.setPreviewFrameRate(framerate);
533
534        CAMHAL_LOGDB("FPS Range [%d, %d]", minFPS, maxFPS);
535        mParameters.set(TICameraParameters::KEY_MINFRAMERATE, minFPS);
536        mParameters.set(TICameraParameters::KEY_MAXFRAMERATE, maxFPS);
537
538        if( ( valstr = params.get(TICameraParameters::KEY_GBCE) ) != NULL )
539            {
540            CAMHAL_LOGDB("GBCE Value = %s", valstr);
541            mParameters.set(TICameraParameters::KEY_GBCE, valstr);
542            }
543
544        if( ( valstr = params.get(TICameraParameters::KEY_GLBCE) ) != NULL )
545            {
546            CAMHAL_LOGDB("GLBCE Value = %s", valstr);
547            mParameters.set(TICameraParameters::KEY_GLBCE, valstr);
548            }
549
550        ///Update the current parameter set
551        if( (valstr = params.get(TICameraParameters::KEY_AUTOCONVERGENCE)) != NULL)
552            {
553            CAMHAL_LOGDB("AutoConvergence Mode is set = %s", params.get(TICameraParameters::KEY_AUTOCONVERGENCE));
554            mParameters.set(TICameraParameters::KEY_AUTOCONVERGENCE, valstr);
555            }
556
557        if( (valstr = params.get(TICameraParameters::KEY_MANUALCONVERGENCE_VALUES)) !=NULL )
558            {
559            CAMHAL_LOGDB("ManualConvergence Value = %s", params.get(TICameraParameters::KEY_MANUALCONVERGENCE_VALUES));
560            mParameters.set(TICameraParameters::KEY_MANUALCONVERGENCE_VALUES, valstr);
561            }
562
563        if ((valstr = params.get(TICameraParameters::KEY_EXPOSURE_MODE)) != NULL) {
564            if (isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_EXPOSURE_MODES))) {
565                CAMHAL_LOGDB("Exposure set = %s", valstr);
566                mParameters.set(TICameraParameters::KEY_EXPOSURE_MODE, valstr);
567            } else {
568                CAMHAL_LOGEB("ERROR: Invalid Exposure  = %s", valstr);
569                ret = -EINVAL;
570            }
571        }
572
573        if ((valstr = params.get(CameraParameters::KEY_WHITE_BALANCE)) != NULL) {
574           if ( isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_WHITE_BALANCE))) {
575               CAMHAL_LOGDB("White balance set %s", valstr);
576               mParameters.set(CameraParameters::KEY_WHITE_BALANCE, valstr);
577            } else {
578               CAMHAL_LOGEB("ERROR: Invalid white balance  = %s", valstr);
579               ret = -EINVAL;
580            }
581        }
582
583        if ((valstr = params.get(TICameraParameters::KEY_CONTRAST)) != NULL) {
584            if (params.getInt(TICameraParameters::KEY_CONTRAST) >= 0 ) {
585                CAMHAL_LOGDB("Contrast set %s", valstr);
586                mParameters.set(TICameraParameters::KEY_CONTRAST, valstr);
587            } else {
588                CAMHAL_LOGEB("ERROR: Invalid Contrast  = %s", valstr);
589                ret = -EINVAL;
590            }
591        }
592
593        if ((valstr =params.get(TICameraParameters::KEY_SHARPNESS)) != NULL) {
594            if (params.getInt(TICameraParameters::KEY_SHARPNESS) >= 0 ) {
595                CAMHAL_LOGDB("Sharpness set %s", valstr);
596                mParameters.set(TICameraParameters::KEY_SHARPNESS, valstr);
597            } else {
598                CAMHAL_LOGEB("ERROR: Invalid Sharpness = %s", valstr);
599                ret = -EINVAL;
600            }
601        }
602
603        if ((valstr = params.get(TICameraParameters::KEY_SATURATION)) != NULL) {
604            if (params.getInt(TICameraParameters::KEY_SATURATION) >= 0 ) {
605                CAMHAL_LOGDB("Saturation set %s", valstr);
606                mParameters.set(TICameraParameters::KEY_SATURATION, valstr);
607             } else {
608                CAMHAL_LOGEB("ERROR: Invalid Saturation = %s", valstr);
609                ret = -EINVAL;
610            }
611        }
612
613        if ((valstr = params.get(TICameraParameters::KEY_BRIGHTNESS)) != NULL) {
614            if (params.getInt(TICameraParameters::KEY_BRIGHTNESS) >= 0 ) {
615                CAMHAL_LOGDB("Brightness set %s", valstr);
616                mParameters.set(TICameraParameters::KEY_BRIGHTNESS, valstr);
617            } else {
618                CAMHAL_LOGEB("ERROR: Invalid Brightness = %s", valstr);
619                ret = -EINVAL;
620            }
621         }
622
623        if ((valstr = params.get(CameraParameters::KEY_ANTIBANDING)) != NULL) {
624            if (isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_ANTIBANDING))) {
625                CAMHAL_LOGDB("Antibanding set %s", valstr);
626                mParameters.set(CameraParameters::KEY_ANTIBANDING, valstr);
627             } else {
628                CAMHAL_LOGEB("ERROR: Invalid Antibanding = %s", valstr);
629                ret = -EINVAL;
630             }
631         }
632
633        if ((valstr = params.get(TICameraParameters::KEY_ISO)) != NULL) {
634            if (isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_ISO_VALUES))) {
635                CAMHAL_LOGDB("ISO set %s", valstr);
636                mParameters.set(TICameraParameters::KEY_ISO, valstr);
637            } else {
638                CAMHAL_LOGEB("ERROR: Invalid ISO = %s", valstr);
639                ret = -EINVAL;
640            }
641        }
642
643        if ((valstr = params.get(CameraParameters::KEY_FOCUS_MODE)) != NULL) {
644            if (isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_FOCUS_MODES))) {
645                CAMHAL_LOGDB("Focus mode set %s", params.get(CameraParameters::KEY_FOCUS_MODE));
646                mParameters.set(CameraParameters::KEY_FOCUS_MODE, valstr);
647             } else {
648                CAMHAL_LOGEB("ERROR: Invalid FOCUS mode = %s", valstr);
649                ret = -EINVAL;
650             }
651        }
652
653        if( (valstr = params.get(CameraParameters::KEY_FOCUS_AREAS)) != NULL )
654            {
655            CAMHAL_LOGEB("Focus areas position set %s", params.get(CameraParameters::KEY_FOCUS_AREAS));
656            mParameters.set(CameraParameters::KEY_FOCUS_AREAS, valstr);
657            }
658
659        if( (valstr = params.get(TICameraParameters::KEY_MEASUREMENT_ENABLE)) != NULL )
660            {
661            CAMHAL_LOGDB("Measurements set to %s", params.get(TICameraParameters::KEY_MEASUREMENT_ENABLE));
662            mParameters.set(TICameraParameters::KEY_MEASUREMENT_ENABLE, valstr);
663
664            if (strcmp(valstr, (const char *) TICameraParameters::MEASUREMENT_ENABLE) == 0)
665                {
666                mMeasurementEnabled = true;
667                }
668            else if (strcmp(valstr, (const char *) TICameraParameters::MEASUREMENT_DISABLE) == 0)
669                {
670                mMeasurementEnabled = false;
671                }
672            else
673                {
674                mMeasurementEnabled = false;
675                }
676
677            }
678
679        if( (valstr = params.get(CameraParameters::KEY_EXPOSURE_COMPENSATION)) != NULL)
680            {
681            CAMHAL_LOGDB("Exposure compensation set %s", params.get(CameraParameters::KEY_EXPOSURE_COMPENSATION));
682            mParameters.set(CameraParameters::KEY_EXPOSURE_COMPENSATION, valstr);
683            }
684
685        if ((valstr = params.get(CameraParameters::KEY_SCENE_MODE)) != NULL) {
686            if (isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_SCENE_MODES))) {
687                CAMHAL_LOGDB("Scene mode set %s", valstr);
688                mParameters.set(CameraParameters::KEY_SCENE_MODE, valstr);
689            } else {
690                CAMHAL_LOGEB("ERROR: Invalid Scene mode = %s", valstr);
691                ret = -EINVAL;
692            }
693        }
694
695        if ((valstr = params.get(CameraParameters::KEY_FLASH_MODE)) != NULL) {
696            if (isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_FLASH_MODES))) {
697                CAMHAL_LOGDB("Flash mode set %s", valstr);
698                mParameters.set(CameraParameters::KEY_FLASH_MODE, valstr);
699            } else {
700                CAMHAL_LOGEB("ERROR: Invalid Flash mode = %s", valstr);
701                ret = -EINVAL;
702            }
703        }
704
705        if ((valstr = params.get(CameraParameters::KEY_EFFECT)) != NULL) {
706            if (isParameterValid(valstr, mCameraProperties->get(CameraProperties::SUPPORTED_EFFECTS))) {
707                CAMHAL_LOGDB("Effect set %s", valstr);
708                mParameters.set(CameraParameters::KEY_EFFECT, valstr);
709             } else {
710                CAMHAL_LOGEB("ERROR: Invalid Effect = %s", valstr);
711                ret = -EINVAL;
712             }
713        }
714
715        if(( (valstr = params.get(CameraParameters::KEY_ROTATION)) != NULL)
716            && (params.getInt(CameraParameters::KEY_ROTATION) >=0))
717            {
718            CAMHAL_LOGDB("Rotation set %s", params.get(CameraParameters::KEY_ROTATION));
719            mParameters.set(CameraParameters::KEY_ROTATION, valstr);
720            }
721
722        if(( (valstr = params.get(CameraParameters::KEY_JPEG_QUALITY)) != NULL)
723            && (params.getInt(CameraParameters::KEY_JPEG_QUALITY) >=0))
724            {
725            CAMHAL_LOGDB("Jpeg quality set %s", params.get(CameraParameters::KEY_JPEG_QUALITY));
726            mParameters.set(CameraParameters::KEY_JPEG_QUALITY, valstr);
727            }
728
729        if(( (valstr = params.get(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH)) != NULL)
730            && (params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH) >=0))
731            {
732            CAMHAL_LOGDB("Thumbnail width set %s", params.get(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH));
733            mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH, valstr);
734            }
735
736        if(( (valstr = params.get(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT)) != NULL)
737            && (params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT) >=0))
738            {
739            CAMHAL_LOGDB("Thumbnail width set %s", params.get(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT));
740            mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT, valstr);
741            }
742
743        if(( (valstr = params.get(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY)) != NULL )
744            && (params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY) >=0))
745            {
746            CAMHAL_LOGDB("Thumbnail quality set %s", params.get(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY));
747            mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY, valstr);
748            }
749
750        if( (valstr = params.get(CameraParameters::KEY_GPS_LATITUDE)) != NULL )
751            {
752            CAMHAL_LOGDB("GPS latitude set %s", params.get(CameraParameters::KEY_GPS_LATITUDE));
753            mParameters.set(CameraParameters::KEY_GPS_LATITUDE, valstr);
754            }else{
755                mParameters.remove(CameraParameters::KEY_GPS_LATITUDE);
756            }
757
758        if( (valstr = params.get(CameraParameters::KEY_GPS_LONGITUDE)) != NULL )
759            {
760            CAMHAL_LOGDB("GPS longitude set %s", params.get(CameraParameters::KEY_GPS_LONGITUDE));
761            mParameters.set(CameraParameters::KEY_GPS_LONGITUDE, valstr);
762            }else{
763                mParameters.remove(CameraParameters::KEY_GPS_LONGITUDE);
764            }
765
766        if( (valstr = params.get(CameraParameters::KEY_GPS_ALTITUDE)) != NULL )
767            {
768            CAMHAL_LOGDB("GPS altitude set %s", params.get(CameraParameters::KEY_GPS_ALTITUDE));
769            mParameters.set(CameraParameters::KEY_GPS_ALTITUDE, valstr);
770            }else{
771                mParameters.remove(CameraParameters::KEY_GPS_ALTITUDE);
772            }
773
774        if( (valstr = params.get(CameraParameters::KEY_GPS_TIMESTAMP)) != NULL )
775            {
776            CAMHAL_LOGDB("GPS timestamp set %s", params.get(CameraParameters::KEY_GPS_TIMESTAMP));
777            mParameters.set(CameraParameters::KEY_GPS_TIMESTAMP, valstr);
778            }else{
779                mParameters.remove(CameraParameters::KEY_GPS_TIMESTAMP);
780            }
781
782        if( (valstr = params.get(TICameraParameters::KEY_GPS_DATESTAMP)) != NULL )
783            {
784            CAMHAL_LOGDB("GPS datestamp set %s", params.get(TICameraParameters::KEY_GPS_DATESTAMP));
785            mParameters.set(TICameraParameters::KEY_GPS_DATESTAMP, valstr);
786            }else{
787                mParameters.remove(TICameraParameters::KEY_GPS_DATESTAMP);
788            }
789
790        if( (valstr = params.get(CameraParameters::KEY_GPS_PROCESSING_METHOD)) != NULL )
791            {
792            CAMHAL_LOGDB("GPS processing method set %s", params.get(CameraParameters::KEY_GPS_PROCESSING_METHOD));
793            mParameters.set(CameraParameters::KEY_GPS_PROCESSING_METHOD, valstr);
794            }else{
795                mParameters.remove(CameraParameters::KEY_GPS_PROCESSING_METHOD);
796            }
797
798        if( (valstr = params.get(TICameraParameters::KEY_GPS_MAPDATUM )) != NULL )
799            {
800            CAMHAL_LOGDB("GPS MAPDATUM set %s", params.get(TICameraParameters::KEY_GPS_MAPDATUM));
801            mParameters.set(TICameraParameters::KEY_GPS_MAPDATUM, valstr);
802            }else{
803                mParameters.remove(TICameraParameters::KEY_GPS_MAPDATUM);
804            }
805
806        if( (valstr = params.get(TICameraParameters::KEY_GPS_VERSION)) != NULL )
807            {
808            CAMHAL_LOGDB("GPS MAPDATUM set %s", params.get(TICameraParameters::KEY_GPS_VERSION));
809            mParameters.set(TICameraParameters::KEY_GPS_VERSION, valstr);
810            }else{
811                mParameters.remove(TICameraParameters::KEY_GPS_VERSION);
812            }
813
814        if( (valstr = params.get(TICameraParameters::KEY_EXIF_MODEL)) != NULL )
815            {
816            CAMHAL_LOGDB("EXIF Model set %s", params.get(TICameraParameters::KEY_EXIF_MODEL));
817            mParameters.set(TICameraParameters::KEY_EXIF_MODEL, valstr);
818            }
819
820        if( (valstr = params.get(TICameraParameters::KEY_EXIF_MAKE)) != NULL )
821            {
822            CAMHAL_LOGDB("EXIF Make set %s", params.get(TICameraParameters::KEY_EXIF_MAKE));
823            mParameters.set(TICameraParameters::KEY_EXIF_MAKE, valstr);
824            }
825
826        if( (valstr = params.get(TICameraParameters::KEY_EXP_BRACKETING_RANGE)) != NULL )
827            {
828            CAMHAL_LOGDB("Exposure Bracketing set %s", params.get(TICameraParameters::KEY_EXP_BRACKETING_RANGE));
829            mParameters.set(TICameraParameters::KEY_EXP_BRACKETING_RANGE, valstr);
830            }
831        else
832            {
833            mParameters.remove(TICameraParameters::KEY_EXP_BRACKETING_RANGE);
834            }
835
836        if ((valstr = params.get(CameraParameters::KEY_ZOOM)) != NULL ) {
837            if ((params.getInt(CameraParameters::KEY_ZOOM) >= 0 ) &&
838                (params.getInt(CameraParameters::KEY_ZOOM) <= mMaxZoomSupported )) {
839                CAMHAL_LOGDB("Zoom set %s", valstr);
840                doesSetParameterNeedUpdate(valstr,
841                                           mParameters.get(CameraParameters::KEY_ZOOM),
842                                           updateRequired);
843                mParameters.set(CameraParameters::KEY_ZOOM, valstr);
844             } else {
845                CAMHAL_LOGEB("ERROR: Invalid Zoom: %s", valstr);
846                ret = -EINVAL;
847            }
848        }
849
850        if( (valstr = params.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK)) != NULL )
851          {
852            CAMHAL_LOGDB("Auto Exposure Lock set %s", params.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK));
853            doesSetParameterNeedUpdate(valstr,
854                                       mParameters.get(CameraParameters::KEY_AUTO_EXPOSURE_LOCK),
855                                       updateRequired);
856            mParameters.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK, valstr);
857          }
858
859        if( (valstr = params.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK)) != NULL )
860          {
861            CAMHAL_LOGDB("Auto WhiteBalance Lock set %s", params.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK));
862            doesSetParameterNeedUpdate(valstr,
863                                       mParameters.get(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK),
864                                       updateRequired);
865            mParameters.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK, valstr);
866          }
867        if( (valstr = params.get(CameraParameters::KEY_METERING_AREAS)) != NULL )
868            {
869            CAMHAL_LOGEB("Metering areas position set %s", params.get(CameraParameters::KEY_METERING_AREAS));
870            mParameters.set(CameraParameters::KEY_METERING_AREAS, valstr);
871            }
872
873        CameraParameters adapterParams = mParameters;
874
875        // Only send parameters to adapter if preview is already
876        // enabled or doesSetParameterNeedUpdate says so. Initial setParameters to camera adapter,
877        // will be called in startPreview()
878        // TODO(XXX): Need to identify other parameters that need update from camera adapter
879        if ( (NULL != mCameraAdapter) && (mPreviewEnabled || updateRequired) ) {
880            ret |= mCameraAdapter->setParameters(adapterParams);
881        }
882
883        if( NULL != params.get(TICameraParameters::KEY_TEMP_BRACKETING_RANGE_POS) )
884            {
885            int posBracketRange = params.getInt(TICameraParameters::KEY_TEMP_BRACKETING_RANGE_POS);
886            if ( 0 < posBracketRange )
887                {
888                mBracketRangePositive = posBracketRange;
889                }
890            }
891        CAMHAL_LOGDB("Positive bracketing range %d", mBracketRangePositive);
892
893
894        if( NULL != params.get(TICameraParameters::KEY_TEMP_BRACKETING_RANGE_NEG) )
895            {
896            int negBracketRange = params.getInt(TICameraParameters::KEY_TEMP_BRACKETING_RANGE_NEG);
897            if ( 0 < negBracketRange )
898                {
899                mBracketRangeNegative = negBracketRange;
900                }
901            }
902        CAMHAL_LOGDB("Negative bracketing range %d", mBracketRangeNegative);
903
904        if( ( (valstr = params.get(TICameraParameters::KEY_TEMP_BRACKETING)) != NULL) &&
905            ( strcmp(valstr, TICameraParameters::BRACKET_ENABLE) == 0 ))
906            {
907            if ( !mBracketingEnabled )
908                {
909                CAMHAL_LOGDA("Enabling bracketing");
910                mBracketingEnabled = true;
911
912                //Wait for AF events to enable bracketing
913                if ( NULL != mCameraAdapter )
914                    {
915                    setEventProvider( CameraHalEvent::ALL_EVENTS, mCameraAdapter );
916                    }
917                }
918            else
919                {
920                CAMHAL_LOGDA("Bracketing already enabled");
921                }
922            }
923        else if ( ( (valstr = params.get(TICameraParameters::KEY_TEMP_BRACKETING)) != NULL ) &&
924            ( strcmp(valstr, TICameraParameters::BRACKET_DISABLE) == 0 ))
925            {
926            CAMHAL_LOGDA("Disabling bracketing");
927
928            mBracketingEnabled = false;
929            stopImageBracketing();
930
931            //Remove AF events subscription
932            if ( NULL != mEventProvider )
933                {
934                mEventProvider->disableEventNotification( CameraHalEvent::ALL_EVENTS );
935                delete mEventProvider;
936                mEventProvider = NULL;
937                }
938
939            }
940
941        if( ( (valstr = params.get(TICameraParameters::KEY_SHUTTER_ENABLE)) != NULL ) &&
942            ( strcmp(valstr, TICameraParameters::SHUTTER_ENABLE) == 0 ))
943            {
944            CAMHAL_LOGDA("Enabling shutter sound");
945
946            mShutterEnabled = true;
947            mMsgEnabled |= CAMERA_MSG_SHUTTER;
948            mParameters.set(TICameraParameters::KEY_SHUTTER_ENABLE, valstr);
949            }
950        else if ( ( (valstr = params.get(TICameraParameters::KEY_SHUTTER_ENABLE)) != NULL ) &&
951            ( strcmp(valstr, TICameraParameters::SHUTTER_DISABLE) == 0 ))
952            {
953            CAMHAL_LOGDA("Disabling shutter sound");
954
955            mShutterEnabled = false;
956            mMsgEnabled &= ~CAMERA_MSG_SHUTTER;
957            mParameters.set(TICameraParameters::KEY_SHUTTER_ENABLE, valstr);
958            }
959
960    }
961
962    //On fail restore old parameters
963    if ( NO_ERROR != ret ) {
964        mParameters.unflatten(oldParams.flatten());
965    }
966
967    // Restart Preview if needed by KEY_RECODING_HINT only if preview is already running.
968    // If preview is not started yet, Video Mode parameters will take effect on next startPreview()
969    if(restartPreviewRequired && previewEnabled())
970        {
971        CAMHAL_LOGDA("Restarting Preview as needed by KEY_RECODING_HINT");
972        ret = restartPreview();
973        }
974    if (ret != NO_ERROR)
975        {
976        CAMHAL_LOGEA("Failed to restart Preview");
977        return ret;
978        }
979
980    LOG_FUNCTION_NAME_EXIT;
981
982    return ret;
983}
984
985status_t CameraHal::allocPreviewBufs(int width, int height, const char* previewFormat,
986                                        unsigned int buffercount, unsigned int &max_queueable)
987{
988    status_t ret = NO_ERROR;
989
990    LOG_FUNCTION_NAME;
991
992    if(mDisplayAdapter.get() == NULL)
993    {
994        // Memory allocation of preview buffers is now placed in gralloc
995        // CameraHal should not allocate preview buffers without DisplayAdapter
996        return NO_MEMORY;
997    }
998
999    if(!mPreviewBufs)
1000    {
1001        ///@todo Pluralise the name of this method to allocateBuffers
1002        mPreviewLength = 0;
1003        mPreviewBufs = (int32_t *) mDisplayAdapter->allocateBuffer(width, height,
1004                                                                    previewFormat,
1005                                                                    mPreviewLength,
1006                                                                    buffercount);
1007
1008	if (NULL == mPreviewBufs ) {
1009            CAMHAL_LOGEA("Couldn't allocate preview buffers");
1010            return NO_MEMORY;
1011         }
1012
1013        mPreviewOffsets = (uint32_t *) mDisplayAdapter->getOffsets();
1014        if ( NULL == mPreviewOffsets ) {
1015            CAMHAL_LOGEA("Buffer mapping failed");
1016            return BAD_VALUE;
1017         }
1018
1019        mPreviewFd = mDisplayAdapter->getFd();
1020        if ( -1 == mPreviewFd ) {
1021            CAMHAL_LOGEA("Invalid handle");
1022            return BAD_VALUE;
1023          }
1024
1025        mBufProvider = (BufferProvider*) mDisplayAdapter.get();
1026
1027        ret = mDisplayAdapter->maxQueueableBuffers(max_queueable);
1028        if (ret != NO_ERROR) {
1029            return ret;
1030         }
1031
1032    }
1033
1034    LOG_FUNCTION_NAME_EXIT;
1035
1036    return ret;
1037
1038}
1039
1040status_t CameraHal::freePreviewBufs()
1041{
1042    status_t ret = NO_ERROR;
1043    LOG_FUNCTION_NAME;
1044
1045    CAMHAL_LOGDB("mPreviewBufs = 0x%x", (unsigned int)mPreviewBufs);
1046    if(mPreviewBufs)
1047        {
1048        ///@todo Pluralise the name of this method to freeBuffers
1049        ret = mBufProvider->freeBuffer(mPreviewBufs);
1050        mPreviewBufs = NULL;
1051        LOG_FUNCTION_NAME_EXIT;
1052        return ret;
1053        }
1054    LOG_FUNCTION_NAME_EXIT;
1055    return ret;
1056}
1057
1058
1059status_t CameraHal::allocPreviewDataBufs(size_t size, size_t bufferCount)
1060{
1061    status_t ret = NO_ERROR;
1062    int bytes;
1063
1064    LOG_FUNCTION_NAME;
1065
1066    bytes = size;
1067
1068    if ( NO_ERROR == ret )
1069        {
1070        if( NULL != mPreviewDataBufs )
1071            {
1072            ret = freePreviewDataBufs();
1073            }
1074        }
1075
1076    if ( NO_ERROR == ret )
1077        {
1078        bytes = ((bytes+4095)/4096)*4096;
1079        mPreviewDataBufs = (int32_t *)mMemoryManager->allocateBuffer(0, 0, NULL, bytes, bufferCount);
1080
1081        CAMHAL_LOGDB("Size of Preview data buffer = %d", bytes);
1082        if( NULL == mPreviewDataBufs )
1083            {
1084            CAMHAL_LOGEA("Couldn't allocate image buffers using memory manager");
1085            ret = -NO_MEMORY;
1086            }
1087        else
1088            {
1089            bytes = size;
1090            }
1091        }
1092
1093    if ( NO_ERROR == ret )
1094        {
1095        mPreviewDataFd = mMemoryManager->getFd();
1096        mPreviewDataLength = bytes;
1097        mPreviewDataOffsets = mMemoryManager->getOffsets();
1098        }
1099    else
1100        {
1101        mPreviewDataFd = -1;
1102        mPreviewDataLength = 0;
1103        mPreviewDataOffsets = NULL;
1104        }
1105
1106    LOG_FUNCTION_NAME;
1107
1108    return ret;
1109}
1110
1111status_t CameraHal::freePreviewDataBufs()
1112{
1113    status_t ret = NO_ERROR;
1114
1115    LOG_FUNCTION_NAME;
1116
1117    if ( NO_ERROR == ret )
1118        {
1119
1120        if( NULL != mPreviewDataBufs )
1121            {
1122
1123            ///@todo Pluralise the name of this method to freeBuffers
1124            ret = mMemoryManager->freeBuffer(mPreviewDataBufs);
1125            mPreviewDataBufs = NULL;
1126
1127            }
1128        }
1129
1130    LOG_FUNCTION_NAME_EXIT;
1131
1132    return ret;
1133}
1134
1135status_t CameraHal::allocImageBufs(unsigned int width, unsigned int height, size_t size, const char* previewFormat, unsigned int bufferCount)
1136{
1137    status_t ret = NO_ERROR;
1138    int bytes;
1139
1140    LOG_FUNCTION_NAME;
1141
1142    bytes = size;
1143
1144    ///Always allocate the buffers for image capture using MemoryManager
1145    if ( NO_ERROR == ret )
1146        {
1147        if( ( NULL != mImageBufs ) )
1148            {
1149            ret = freeImageBufs();
1150            }
1151        }
1152
1153    if ( NO_ERROR == ret )
1154        {
1155        bytes = ((bytes+4095)/4096)*4096;
1156        mImageBufs = (int32_t *)mMemoryManager->allocateBuffer(0, 0, previewFormat, bytes, bufferCount);
1157
1158        CAMHAL_LOGDB("Size of Image cap buffer = %d", bytes);
1159        if( NULL == mImageBufs )
1160            {
1161            CAMHAL_LOGEA("Couldn't allocate image buffers using memory manager");
1162            ret = -NO_MEMORY;
1163            }
1164        else
1165            {
1166            bytes = size;
1167            }
1168        }
1169
1170    if ( NO_ERROR == ret )
1171        {
1172        mImageFd = mMemoryManager->getFd();
1173        mImageLength = bytes;
1174        mImageOffsets = mMemoryManager->getOffsets();
1175        }
1176    else
1177        {
1178        mImageFd = -1;
1179        mImageLength = 0;
1180        mImageOffsets = NULL;
1181        }
1182
1183    LOG_FUNCTION_NAME;
1184
1185    return ret;
1186}
1187
1188void endImageCapture( void *userData)
1189{
1190    LOG_FUNCTION_NAME;
1191
1192    if ( NULL != userData )
1193        {
1194        CameraHal *c = reinterpret_cast<CameraHal *>(userData);
1195        c->signalEndImageCapture();
1196        }
1197
1198    LOG_FUNCTION_NAME_EXIT;
1199}
1200
1201void releaseImageBuffers(void *userData)
1202{
1203    LOG_FUNCTION_NAME;
1204
1205// Make releaseImageBuffers a no-op for now because it is racing against AppCallbackNotifier
1206// in the home screen use-case. Image capture buffers are anyways reallocated on subsequent
1207// captures and also released as part of final camera hal cleanup
1208#if 0
1209    if ( NULL != userData )
1210        {
1211        CameraHal *c = reinterpret_cast<CameraHal *>(userData);
1212        c->freeImageBufs();
1213        }
1214#endif
1215
1216    LOG_FUNCTION_NAME_EXIT;
1217}
1218
1219status_t CameraHal::signalEndImageCapture()
1220{
1221    status_t ret = NO_ERROR;
1222    int w,h;
1223    CameraParameters adapterParams = mParameters;
1224    Mutex::Autolock lock(mLock);
1225
1226    LOG_FUNCTION_NAME;
1227
1228    mCameraAdapter->sendCommand(CameraAdapter::CAMERA_STOP_IMAGE_CAPTURE);
1229
1230    LOG_FUNCTION_NAME_EXIT;
1231
1232    return ret;
1233}
1234
1235status_t CameraHal::freeImageBufs()
1236{
1237    status_t ret = NO_ERROR;
1238
1239    LOG_FUNCTION_NAME;
1240
1241    if ( NO_ERROR == ret )
1242        {
1243
1244        if( NULL != mImageBufs )
1245            {
1246
1247            ///@todo Pluralise the name of this method to freeBuffers
1248            ret = mMemoryManager->freeBuffer(mImageBufs);
1249            mImageBufs = NULL;
1250
1251            }
1252        else
1253            {
1254            ret = -EINVAL;
1255            }
1256
1257        }
1258
1259    LOG_FUNCTION_NAME_EXIT;
1260
1261    return ret;
1262}
1263
1264
1265
1266/**
1267   @brief Start preview mode.
1268
1269   @param none
1270   @return NO_ERROR Camera switched to VF mode
1271   @todo Update function header with the different errors that are possible
1272
1273 */
1274status_t CameraHal::startPreview()
1275{
1276
1277    status_t ret = NO_ERROR;
1278    CameraAdapter::BuffersDescriptor desc;
1279    CameraFrame frame;
1280    const char *valstr = NULL;
1281    unsigned int required_buffer_count;
1282    unsigned int max_queueble_buffers;
1283
1284#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
1285
1286        gettimeofday(&mStartPreview, NULL);
1287
1288#endif
1289
1290    LOG_FUNCTION_NAME;
1291
1292    if ( mPreviewEnabled )
1293    {
1294    CAMHAL_LOGDA("Preview already running");
1295
1296    LOG_FUNCTION_NAME_EXIT;
1297
1298    return ALREADY_EXISTS;
1299    }
1300
1301    if ( NULL != mCameraAdapter ) {
1302
1303        ret = mCameraAdapter->setParameters(mParameters);
1304    }
1305
1306    ///If we don't have the preview callback enabled and display adapter,
1307    if(!mSetPreviewWindowCalled || (mDisplayAdapter.get() == NULL))
1308    {
1309        CAMHAL_LOGEA("Preview not started. Preview in progress flag set");
1310        mPreviewStartInProgress = true;
1311        return NO_ERROR;
1312    }
1313
1314    if( (mDisplayAdapter.get() != NULL) && ( !mPreviewEnabled ) && ( mDisplayPaused ) )
1315        {
1316        CAMHAL_LOGDA("Preview is in paused state");
1317
1318        mDisplayPaused = false;
1319        mPreviewEnabled = true;
1320        if ( NO_ERROR == ret )
1321            {
1322            ret = mDisplayAdapter->pauseDisplay(mDisplayPaused);
1323
1324            if ( NO_ERROR != ret )
1325                {
1326                CAMHAL_LOGEB("Display adapter resume failed %x", ret);
1327                }
1328            }
1329        //restart preview callbacks
1330        if(mMsgEnabled & CAMERA_MSG_PREVIEW_FRAME)
1331        {
1332            mAppCallbackNotifier->enableMsgType (CAMERA_MSG_PREVIEW_FRAME);
1333        }
1334        if ( mDynamicPreviewSwitch )
1335            {
1336            forceStopPreview();
1337            mDynamicPreviewSwitch = false;
1338            }
1339        else
1340            {
1341            return ret;
1342            }
1343        }
1344
1345    /// Ensure that buffers for preview are allocated before we start the camera
1346    ///Get the updated size from Camera Adapter, to account for padding etc
1347    ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_QUERY_RESOLUTION_PREVIEW,
1348                                      ( int ) &frame);
1349    if ( NO_ERROR != ret )
1350        {
1351        return ret;
1352        }
1353
1354    ///Update the current preview width and height
1355    mPreviewWidth = frame.mWidth;
1356    mPreviewHeight = frame.mHeight;
1357
1358    //Update the padded width and height - required for VNF and VSTAB
1359    mParameters.set(TICameraParameters::KEY_PADDED_WIDTH, mPreviewWidth);
1360    mParameters.set(TICameraParameters::KEY_PADDED_HEIGHT, mPreviewHeight);
1361
1362    required_buffer_count = atoi(mCameraProperties->get(CameraProperties::REQUIRED_PREVIEW_BUFS));
1363
1364    ///Allocate the preview buffers
1365    ret = allocPreviewBufs(frame.mWidth, frame.mHeight, mParameters.getPreviewFormat(), required_buffer_count, max_queueble_buffers);
1366
1367    if ( NO_ERROR != ret )
1368        {
1369        CAMHAL_LOGEA("Couldn't allocate buffers for Preview");
1370        goto error;
1371        }
1372
1373    if ( mMeasurementEnabled )
1374        {
1375
1376        ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_QUERY_BUFFER_SIZE_PREVIEW_DATA,
1377                                          ( int ) &frame,
1378                                          required_buffer_count);
1379        if ( NO_ERROR != ret )
1380            {
1381            return ret;
1382            }
1383
1384         ///Allocate the preview data buffers
1385        ret = allocPreviewDataBufs(frame.mLength, required_buffer_count);
1386        if ( NO_ERROR != ret ) {
1387            CAMHAL_LOGEA("Couldn't allocate preview data buffers");
1388            goto error;
1389           }
1390
1391        if ( NO_ERROR == ret )
1392            {
1393            desc.mBuffers = mPreviewDataBufs;
1394            desc.mOffsets = mPreviewDataOffsets;
1395            desc.mFd = mPreviewDataFd;
1396            desc.mLength = mPreviewDataLength;
1397            desc.mCount = ( size_t ) required_buffer_count;
1398            desc.mMaxQueueable = (size_t) required_buffer_count;
1399
1400            mCameraAdapter->sendCommand(CameraAdapter::CAMERA_USE_BUFFERS_PREVIEW_DATA,
1401                                        ( int ) &desc);
1402            }
1403
1404        }
1405
1406    ///Pass the buffers to Camera Adapter
1407    desc.mBuffers = mPreviewBufs;
1408    desc.mOffsets = mPreviewOffsets;
1409    desc.mFd = mPreviewFd;
1410    desc.mLength = mPreviewLength;
1411    desc.mCount = ( size_t ) required_buffer_count;
1412    desc.mMaxQueueable = (size_t) max_queueble_buffers;
1413
1414    ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_USE_BUFFERS_PREVIEW,
1415                                      ( int ) &desc);
1416
1417    if ( NO_ERROR != ret )
1418        {
1419        CAMHAL_LOGEB("Failed to register preview buffers: 0x%x", ret);
1420        freePreviewBufs();
1421        return ret;
1422        }
1423
1424    mAppCallbackNotifier->startPreviewCallbacks(mParameters, mPreviewBufs, mPreviewOffsets, mPreviewFd, mPreviewLength, required_buffer_count);
1425
1426    ///Start the callback notifier
1427    ret = mAppCallbackNotifier->start();
1428
1429    if( ALREADY_EXISTS == ret )
1430        {
1431        //Already running, do nothing
1432        CAMHAL_LOGDA("AppCallbackNotifier already running");
1433        ret = NO_ERROR;
1434        }
1435    else if ( NO_ERROR == ret ) {
1436        CAMHAL_LOGDA("Started AppCallbackNotifier..");
1437        mAppCallbackNotifier->setMeasurements(mMeasurementEnabled);
1438        }
1439    else
1440        {
1441        CAMHAL_LOGDA("Couldn't start AppCallbackNotifier");
1442        goto error;
1443        }
1444
1445    ///Enable the display adapter if present, actual overlay enable happens when we post the buffer
1446    if(mDisplayAdapter.get() != NULL)
1447        {
1448        CAMHAL_LOGDA("Enabling display");
1449        bool isS3d = false;
1450        DisplayAdapter::S3DParameters s3dParams;
1451        int width, height;
1452        mParameters.getPreviewSize(&width, &height);
1453#if 0 //TODO: s3d is not part of bringup...will reenable
1454        if ( (valstr = mParameters.get(TICameraParameters::KEY_S3D_SUPPORTED)) != NULL) {
1455            isS3d = (strcmp(valstr, "true") == 0);
1456        }
1457        if ( (valstr = mParameters.get(TICameraParameters::KEY_S3D2D_PREVIEW)) != NULL) {
1458            if (strcmp(valstr, "off") == 0)
1459                {
1460                CAMHAL_LOGEA("STEREO 3D->2D PREVIEW MODE IS OFF");
1461                //TODO: obtain the frame packing configuration from camera or user settings
1462                //once side by side configuration is supported
1463                s3dParams.mode = OVERLAY_S3D_MODE_ON;
1464                s3dParams.framePacking = OVERLAY_S3D_FORMAT_OVERUNDER;
1465                s3dParams.order = OVERLAY_S3D_ORDER_LF;
1466                s3dParams.subSampling = OVERLAY_S3D_SS_NONE;
1467                }
1468            else
1469                {
1470                CAMHAL_LOGEA("STEREO 3D->2D PREVIEW MODE IS ON");
1471                s3dParams.mode = OVERLAY_S3D_MODE_OFF;
1472                s3dParams.framePacking = OVERLAY_S3D_FORMAT_OVERUNDER;
1473                s3dParams.order = OVERLAY_S3D_ORDER_LF;
1474                s3dParams.subSampling = OVERLAY_S3D_SS_NONE;
1475                }
1476        }
1477#endif //if 0
1478
1479#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
1480
1481        ret = mDisplayAdapter->enableDisplay(width, height, &mStartPreview, isS3d ? &s3dParams : NULL);
1482
1483#else
1484
1485        ret = mDisplayAdapter->enableDisplay(width, height, NULL, isS3d ? &s3dParams : NULL);
1486
1487#endif
1488
1489        if ( ret != NO_ERROR )
1490            {
1491            CAMHAL_LOGEA("Couldn't enable display");
1492            goto error;
1493            }
1494
1495        }
1496
1497    ///Send START_PREVIEW command to adapter
1498    CAMHAL_LOGDA("Starting CameraAdapter preview mode");
1499
1500    ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_START_PREVIEW);
1501
1502    if(ret!=NO_ERROR)
1503        {
1504        CAMHAL_LOGEA("Couldn't start preview w/ CameraAdapter");
1505        goto error;
1506        }
1507    CAMHAL_LOGDA("Started preview");
1508
1509    mPreviewEnabled = true;
1510    mPreviewStartInProgress = false;
1511    return ret;
1512
1513    error:
1514
1515        CAMHAL_LOGEA("Performing cleanup after error");
1516
1517        //Do all the cleanup
1518        freePreviewBufs();
1519        mCameraAdapter->sendCommand(CameraAdapter::CAMERA_STOP_PREVIEW);
1520        if(mDisplayAdapter.get() != NULL)
1521            {
1522            mDisplayAdapter->disableDisplay(false);
1523            }
1524        mAppCallbackNotifier->stop();
1525        mPreviewStartInProgress = false;
1526        mPreviewEnabled = false;
1527        LOG_FUNCTION_NAME_EXIT;
1528
1529        return ret;
1530}
1531
1532/**
1533   @brief Sets ANativeWindow object.
1534
1535   Preview buffers provided to CameraHal via this object. DisplayAdapter will be interfacing with it
1536   to render buffers to display.
1537
1538   @param[in] window The ANativeWindow object created by Surface flinger
1539   @return NO_ERROR If the ANativeWindow object passes validation criteria
1540   @todo Define validation criteria for ANativeWindow object. Define error codes for scenarios
1541
1542 */
1543status_t CameraHal::setPreviewWindow(struct preview_stream_ops *window)
1544{
1545    status_t ret = NO_ERROR;
1546    CameraAdapter::BuffersDescriptor desc;
1547
1548    LOG_FUNCTION_NAME;
1549    mSetPreviewWindowCalled = true;
1550
1551   ///If the Camera service passes a null window, we destroy existing window and free the DisplayAdapter
1552    if(!window)
1553    {
1554        if(mDisplayAdapter.get() != NULL)
1555        {
1556            ///NULL window passed, destroy the display adapter if present
1557            CAMHAL_LOGEA("NULL window passed, destroying display adapter");
1558            mDisplayAdapter.clear();
1559            ///@remarks If there was a window previously existing, we usually expect another valid window to be passed by the client
1560            ///@remarks so, we will wait until it passes a valid window to begin the preview again
1561            mSetPreviewWindowCalled = false;
1562        }
1563        CAMHAL_LOGEA("NULL ANativeWindow passed to setPreviewWindow");
1564        return NO_ERROR;
1565    }else if(mDisplayAdapter.get() == NULL)
1566    {
1567        // Need to create the display adapter since it has not been created
1568        // Create display adapter
1569        mDisplayAdapter = new ANativeWindowDisplayAdapter();
1570        ret = NO_ERROR;
1571        if(!mDisplayAdapter.get() || ((ret=mDisplayAdapter->initialize())!=NO_ERROR))
1572        {
1573            if(ret!=NO_ERROR)
1574            {
1575                mDisplayAdapter.clear();
1576                CAMHAL_LOGEA("DisplayAdapter initialize failed");
1577                LOG_FUNCTION_NAME_EXIT;
1578                return ret;
1579            }
1580            else
1581            {
1582                CAMHAL_LOGEA("Couldn't create DisplayAdapter");
1583                LOG_FUNCTION_NAME_EXIT;
1584                return NO_MEMORY;
1585            }
1586        }
1587
1588        // DisplayAdapter needs to know where to get the CameraFrames from inorder to display
1589        // Since CameraAdapter is the one that provides the frames, set it as the frame provider for DisplayAdapter
1590        mDisplayAdapter->setFrameProvider(mCameraAdapter);
1591
1592        // Any dynamic errors that happen during the camera use case has to be propagated back to the application
1593        // via CAMERA_MSG_ERROR. AppCallbackNotifier is the class that  notifies such errors to the application
1594        // Set it as the error handler for the DisplayAdapter
1595        mDisplayAdapter->setErrorHandler(mAppCallbackNotifier.get());
1596
1597        // Update the display adapter with the new window that is passed from CameraService
1598        ret  = mDisplayAdapter->setPreviewWindow(window);
1599        if(ret!=NO_ERROR)
1600            {
1601            CAMHAL_LOGEB("DisplayAdapter setPreviewWindow returned error %d", ret);
1602            }
1603
1604        if(mPreviewStartInProgress)
1605        {
1606            CAMHAL_LOGDA("setPreviewWindow called when preview running");
1607            // Start the preview since the window is now available
1608            ret = startPreview();
1609        }
1610    }else
1611    {
1612        /* If mDisplayAdpater is already created. No need to do anything.
1613         * We get a surface handle directly now, so we can reconfigure surface
1614         * itself in DisplayAdapter if dimensions have changed
1615         */
1616    }
1617    LOG_FUNCTION_NAME_EXIT;
1618
1619    return ret;
1620
1621}
1622
1623
1624/**
1625   @brief Stop a previously started preview.
1626
1627   @param none
1628   @return none
1629
1630 */
1631void CameraHal::stopPreview()
1632{
1633    LOG_FUNCTION_NAME;
1634
1635    if(!previewEnabled() && !mDisplayPaused)
1636        {
1637        LOG_FUNCTION_NAME_EXIT;
1638        return;
1639        }
1640
1641    bool imageCaptureRunning = (mCameraAdapter->getState() == CameraAdapter::CAPTURE_STATE) &&
1642                                    (mCameraAdapter->getNextState() != CameraAdapter::PREVIEW_STATE);
1643    if(mDisplayPaused && !imageCaptureRunning)
1644        {
1645        // Display is paused, which essentially means there is no preview active.
1646        // Note: this is done so that when stopPreview is called by client after
1647        // an image capture, we do not de-initialize the camera adapter and
1648        // restart over again.
1649
1650        // Since we are not calling CameraAdapter->stopPreview, we need to
1651        // explicitly release the 3A locks in this first level stopPreview call
1652        // before returning
1653        if ( NULL != mCameraAdapter ) {
1654            CameraParameters adapterParams = mParameters;
1655
1656            adapterParams.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK, CameraParameters::FALSE);
1657            adapterParams.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK, CameraParameters::FALSE);
1658            mCameraAdapter->setParameters(adapterParams);
1659        }
1660
1661        return;
1662        }
1663
1664    forceStopPreview();
1665
1666    // Reset Capture-Mode to default, so that when we switch from VideoRecording
1667    // to ImageCapture, CAPTURE_MODE is not left to VIDEO_MODE.
1668    CAMHAL_LOGDA("Resetting Capture-Mode to default");
1669    mParameters.set(TICameraParameters::KEY_CAP_MODE, "");
1670
1671    LOG_FUNCTION_NAME_EXIT;
1672}
1673
1674/**
1675   @brief Returns true if preview is enabled
1676
1677   @param none
1678   @return true If preview is running currently
1679         false If preview has been stopped
1680
1681 */
1682bool CameraHal::previewEnabled()
1683{
1684    LOG_FUNCTION_NAME;
1685
1686    return (mPreviewEnabled || mPreviewStartInProgress);
1687}
1688
1689/**
1690   @brief Start record mode.
1691
1692  When a record image is available a CAMERA_MSG_VIDEO_FRAME message is sent with
1693  the corresponding frame. Every record frame must be released by calling
1694  releaseRecordingFrame().
1695
1696   @param none
1697   @return NO_ERROR If recording could be started without any issues
1698   @todo Update the header with possible error values in failure scenarios
1699
1700 */
1701status_t CameraHal::startRecording( )
1702{
1703    int w, h;
1704    const char *valstr = NULL;
1705    bool restartPreviewRequired = false;
1706    status_t ret = NO_ERROR;
1707
1708    LOG_FUNCTION_NAME;
1709
1710
1711#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
1712
1713            gettimeofday(&mStartPreview, NULL);
1714
1715#endif
1716
1717    if(!previewEnabled())
1718        {
1719        return NO_INIT;
1720        }
1721
1722    valstr = mParameters.get(CameraParameters::KEY_RECORDING_HINT);
1723    if ( (valstr == NULL) ||
1724         ( (valstr != NULL) && (strcmp(valstr, CameraParameters::TRUE) != 0) ) )
1725        {
1726        restartPreviewRequired = setVideoModeParameters();
1727
1728        if(restartPreviewRequired)
1729            {
1730            ret = restartPreview();
1731            }
1732        }
1733
1734    if ( NO_ERROR == ret )
1735        {
1736         ret = mAppCallbackNotifier->initSharedVideoBuffers(mPreviewBufs, mPreviewOffsets, mPreviewFd, mPreviewLength, atoi(mCameraProperties->get(CameraProperties::REQUIRED_PREVIEW_BUFS)));
1737        }
1738
1739    if ( NO_ERROR == ret )
1740        {
1741         ret = mAppCallbackNotifier->startRecording();
1742        }
1743
1744    if ( NO_ERROR == ret )
1745        {
1746        ///Buffers for video capture (if different from preview) are expected to be allocated within CameraAdapter
1747         ret =  mCameraAdapter->sendCommand(CameraAdapter::CAMERA_START_VIDEO);
1748        }
1749
1750    if ( NO_ERROR == ret )
1751        {
1752        mRecordingEnabled = true;
1753        }
1754
1755    LOG_FUNCTION_NAME_EXIT;
1756
1757    return ret;
1758}
1759
1760/**
1761   @brief Set the camera parameters specific to Video Recording.
1762
1763   This function checks for the camera parameters which have to be set for recording.
1764   Video Recording needs CAPTURE_MODE to be VIDEO_MODE. This function sets it.
1765   This function also enables Video Recording specific functions like VSTAB & VNF.
1766
1767   @param none
1768   @return true if preview needs to be restarted for VIDEO_MODE parameters to take effect.
1769   @todo Modify the policies for enabling VSTAB & VNF usecase based later.
1770
1771 */
1772bool CameraHal::setVideoModeParameters()
1773{
1774    const char *valstr = NULL;
1775    bool restartPreviewRequired = false;
1776    status_t ret = NO_ERROR;
1777
1778    LOG_FUNCTION_NAME;
1779
1780    // Set CAPTURE_MODE to VIDEO_MODE, if not set already and Restart Preview
1781    valstr = mParameters.get(TICameraParameters::KEY_CAP_MODE);
1782    if ( (valstr == NULL) ||
1783        ( (valstr != NULL) && (strcmp(valstr, (const char *) TICameraParameters::VIDEO_MODE) != 0) ) )
1784        {
1785        CAMHAL_LOGDA("Set CAPTURE_MODE to VIDEO_MODE");
1786        mParameters.set(TICameraParameters::KEY_CAP_MODE, (const char *) TICameraParameters::VIDEO_MODE);
1787        restartPreviewRequired = true;
1788        }
1789
1790    // Check if CAPTURE_MODE is VIDEO_MODE, since VSTAB & VNF work only in VIDEO_MODE.
1791    valstr = mParameters.get(TICameraParameters::KEY_CAP_MODE);
1792    if (strcmp(valstr, (const char *) TICameraParameters::VIDEO_MODE) == 0)
1793        {
1794        // Enable VSTAB, if not enabled already
1795        valstr = mParameters.get(TICameraParameters::KEY_VSTAB);
1796        if ( (valstr == NULL) ||
1797            ( (valstr != NULL) && (strcmp(valstr, "1") != 0) ) )
1798            {
1799            CAMHAL_LOGDA("Enable VSTAB");
1800            mParameters.set(TICameraParameters::KEY_VSTAB, "1");
1801            restartPreviewRequired = true;
1802            }
1803
1804        // Enable VNF, if not enabled already
1805        valstr = mParameters.get(TICameraParameters::KEY_VNF);
1806        if ( (valstr == NULL) ||
1807            ( (valstr != NULL) && (strcmp(valstr, "1") != 0) ) )
1808            {
1809            CAMHAL_LOGDA("Enable VNF");
1810            mParameters.set(TICameraParameters::KEY_VNF, "1");
1811            restartPreviewRequired = true;
1812            }
1813
1814        // For VSTAB alone for 1080p resolution, padded width goes > 2048, which cannot be rendered by GPU.
1815        // In such case, there is support in Ducati for combination of VSTAB & VNF requiring padded width < 2048.
1816        // So we are forcefully enabling VNF, if VSTAB is enabled for 1080p resolution.
1817        valstr = mParameters.get(TICameraParameters::KEY_VSTAB);
1818        if ((valstr != NULL) && (strcmp(valstr, "1") == 0) && (mPreviewWidth == 1920))
1819            {
1820            CAMHAL_LOGDA("Force Enable VNF for 1080p");
1821            mParameters.set(TICameraParameters::KEY_VNF, "1");
1822            restartPreviewRequired = true;
1823            }
1824        }
1825
1826    LOG_FUNCTION_NAME_EXIT;
1827
1828    return restartPreviewRequired;
1829}
1830
1831/**
1832   @brief Reset the camera parameters specific to Video Recording.
1833
1834   This function resets CAPTURE_MODE and disables Recording specific functions like VSTAB & VNF.
1835
1836   @param none
1837   @return true if preview needs to be restarted for VIDEO_MODE parameters to take effect.
1838
1839 */
1840bool CameraHal::resetVideoModeParameters()
1841{
1842    const char *valstr = NULL;
1843    bool restartPreviewRequired = false;
1844    status_t ret = NO_ERROR;
1845
1846    LOG_FUNCTION_NAME;
1847
1848    // ignore this if we are already recording
1849    if (mRecordingEnabled) {
1850        return false;
1851    }
1852
1853    // Set CAPTURE_MODE to VIDEO_MODE, if not set already and Restart Preview
1854    valstr = mParameters.get(TICameraParameters::KEY_CAP_MODE);
1855    if ( (valstr != NULL) && (strcmp(valstr, (const char *) TICameraParameters::VIDEO_MODE) == 0) )
1856        {
1857        CAMHAL_LOGDA("Reset Capture-Mode to default");
1858        mParameters.set(TICameraParameters::KEY_CAP_MODE, "");
1859        restartPreviewRequired = true;
1860        }
1861
1862    // Enable VSTAB, if not enabled already
1863    valstr = mParameters.get(TICameraParameters::KEY_VSTAB);
1864    if (  (valstr != NULL) && (strcmp(valstr, "1") == 0) )
1865        {
1866        CAMHAL_LOGDA("Disable VSTAB");
1867        mParameters.set(TICameraParameters::KEY_VSTAB, "0");
1868        restartPreviewRequired = true;
1869        }
1870
1871    // Enable VNF, if not enabled already
1872    valstr = mParameters.get(TICameraParameters::KEY_VNF);
1873    if (  (valstr != NULL) && (strcmp(valstr, "1") == 0) )
1874        {
1875        CAMHAL_LOGDA("Disable VNF");
1876        mParameters.set(TICameraParameters::KEY_VNF, "0");
1877        restartPreviewRequired = true;
1878        }
1879
1880    LOG_FUNCTION_NAME_EXIT;
1881
1882    return restartPreviewRequired;
1883}
1884
1885/**
1886   @brief Restart the preview with setParameter.
1887
1888   This function restarts preview, for some VIDEO_MODE parameters to take effect.
1889
1890   @param none
1891   @return NO_ERROR If recording parameters could be set without any issues
1892
1893 */
1894status_t CameraHal::restartPreview()
1895{
1896    const char *valstr = NULL;
1897    char tmpvalstr[30];
1898    status_t ret = NO_ERROR;
1899
1900    LOG_FUNCTION_NAME;
1901
1902    // Retain CAPTURE_MODE before calling stopPreview(), since it is reset in stopPreview().
1903    tmpvalstr[0] = 0;
1904    valstr = mParameters.get(TICameraParameters::KEY_CAP_MODE);
1905    if(valstr != NULL)
1906        {
1907        if(sizeof(tmpvalstr) < (strlen(valstr)+1))
1908            {
1909            return -EINVAL;
1910            }
1911
1912        strncpy(tmpvalstr, valstr, sizeof(tmpvalstr));
1913        tmpvalstr[sizeof(tmpvalstr)-1] = 0;
1914        }
1915
1916    stopPreview();
1917
1918    {
1919        Mutex::Autolock lock(mLock);
1920        mParameters.set(TICameraParameters::KEY_CAP_MODE, tmpvalstr);
1921        mCameraAdapter->setParameters(mParameters);
1922    }
1923
1924    ret = startPreview();
1925
1926    LOG_FUNCTION_NAME_EXIT;
1927
1928    return ret;
1929}
1930
1931/**
1932   @brief Stop a previously started recording.
1933
1934   @param none
1935   @return none
1936
1937 */
1938void CameraHal::stopRecording()
1939{
1940    CameraAdapter::AdapterState currentState;
1941
1942    LOG_FUNCTION_NAME;
1943
1944    Mutex::Autolock lock(mLock);
1945
1946    if (!mRecordingEnabled )
1947        {
1948        return;
1949        }
1950
1951    currentState = mCameraAdapter->getState();
1952    if (currentState == CameraAdapter::VIDEO_CAPTURE_STATE) {
1953        mCameraAdapter->sendCommand(CameraAdapter::CAMERA_STOP_IMAGE_CAPTURE);
1954    }
1955
1956    mAppCallbackNotifier->stopRecording();
1957
1958    mCameraAdapter->sendCommand(CameraAdapter::CAMERA_STOP_VIDEO);
1959
1960    mRecordingEnabled = false;
1961
1962    LOG_FUNCTION_NAME_EXIT;
1963}
1964
1965/**
1966   @brief Returns true if recording is enabled.
1967
1968   @param none
1969   @return true If recording is currently running
1970         false If recording has been stopped
1971
1972 */
1973int CameraHal::recordingEnabled()
1974{
1975    LOG_FUNCTION_NAME;
1976
1977    LOG_FUNCTION_NAME_EXIT;
1978
1979    return mRecordingEnabled;
1980}
1981
1982/**
1983   @brief Release a record frame previously returned by CAMERA_MSG_VIDEO_FRAME.
1984
1985   @param[in] mem MemoryBase pointer to the frame being released. Must be one of the buffers
1986               previously given by CameraHal
1987   @return none
1988
1989 */
1990void CameraHal::releaseRecordingFrame(const void* mem)
1991{
1992    LOG_FUNCTION_NAME;
1993
1994    //CAMHAL_LOGDB(" 0x%x", mem->pointer());
1995
1996    if ( ( mRecordingEnabled ) && mem != NULL)
1997    {
1998        mAppCallbackNotifier->releaseRecordingFrame(mem);
1999    }
2000
2001    LOG_FUNCTION_NAME_EXIT;
2002
2003    return;
2004}
2005
2006/**
2007   @brief Start auto focus
2008
2009   This call asynchronous.
2010   The notification callback routine is called with CAMERA_MSG_FOCUS once when
2011   focusing is complete. autoFocus() will be called again if another auto focus is
2012   needed.
2013
2014   @param none
2015   @return NO_ERROR
2016   @todo Define the error codes if the focus is not locked
2017
2018 */
2019status_t CameraHal::autoFocus()
2020{
2021    status_t ret = NO_ERROR;
2022
2023#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
2024
2025    gettimeofday(&mStartFocus, NULL);
2026
2027#endif
2028
2029
2030    LOG_FUNCTION_NAME;
2031
2032    if ( NULL != mCameraAdapter )
2033        {
2034
2035#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
2036
2037    //pass the autoFocus timestamp along with the command to camera adapter
2038    ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_PERFORM_AUTOFOCUS, ( int ) &mStartFocus);
2039
2040#else
2041
2042    ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_PERFORM_AUTOFOCUS);
2043
2044#endif
2045
2046        }
2047    else
2048        {
2049            ret = -1;
2050        }
2051
2052    LOG_FUNCTION_NAME_EXIT;
2053
2054    return ret;
2055}
2056
2057/**
2058   @brief Cancels auto-focus function.
2059
2060   If the auto-focus is still in progress, this function will cancel it.
2061   Whether the auto-focus is in progress or not, this function will return the
2062   focus position to the default. If the camera does not support auto-focus, this is a no-op.
2063
2064
2065   @param none
2066   @return NO_ERROR If the cancel succeeded
2067   @todo Define error codes if cancel didnt succeed
2068
2069 */
2070status_t CameraHal::cancelAutoFocus()
2071{
2072    LOG_FUNCTION_NAME;
2073    if( NULL != mCameraAdapter )
2074    {
2075        mCameraAdapter->sendCommand(CameraAdapter::CAMERA_CANCEL_AUTOFOCUS);
2076    }
2077    LOG_FUNCTION_NAME_EXIT;
2078    return NO_ERROR;
2079}
2080
2081void CameraHal::setEventProvider(int32_t eventMask, MessageNotifier * eventNotifier)
2082{
2083
2084    LOG_FUNCTION_NAME;
2085
2086    if ( NULL != mEventProvider )
2087        {
2088        mEventProvider->disableEventNotification(CameraHalEvent::ALL_EVENTS);
2089        delete mEventProvider;
2090        mEventProvider = NULL;
2091        }
2092
2093    mEventProvider = new EventProvider(eventNotifier, this, eventCallbackRelay);
2094    if ( NULL == mEventProvider )
2095        {
2096        CAMHAL_LOGEA("Error in creating EventProvider");
2097        }
2098    else
2099        {
2100        mEventProvider->enableEventNotification(eventMask);
2101        }
2102
2103    LOG_FUNCTION_NAME_EXIT;
2104}
2105
2106void CameraHal::eventCallbackRelay(CameraHalEvent* event)
2107{
2108    LOG_FUNCTION_NAME;
2109
2110    CameraHal *appcbn = ( CameraHal * ) (event->mCookie);
2111    appcbn->eventCallback(event );
2112
2113    LOG_FUNCTION_NAME_EXIT;
2114}
2115
2116void CameraHal::eventCallback(CameraHalEvent* event)
2117{
2118    LOG_FUNCTION_NAME;
2119
2120    if ( NULL != event )
2121        {
2122        switch( event->mEventType )
2123            {
2124            case CameraHalEvent::EVENT_FOCUS_LOCKED:
2125            case CameraHalEvent::EVENT_FOCUS_ERROR:
2126                {
2127                if ( mBracketingEnabled )
2128                    {
2129                    startImageBracketing();
2130                    }
2131                break;
2132                }
2133            default:
2134                {
2135                break;
2136                }
2137            };
2138        }
2139
2140    LOG_FUNCTION_NAME_EXIT;
2141}
2142
2143status_t CameraHal::startImageBracketing()
2144{
2145        status_t ret = NO_ERROR;
2146        CameraFrame frame;
2147        CameraAdapter::BuffersDescriptor desc;
2148
2149#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
2150
2151        gettimeofday(&mStartCapture, NULL);
2152
2153#endif
2154
2155        LOG_FUNCTION_NAME;
2156
2157        if(!previewEnabled() && !mDisplayPaused)
2158            {
2159            LOG_FUNCTION_NAME_EXIT;
2160            return NO_INIT;
2161            }
2162
2163        if ( !mBracketingEnabled )
2164            {
2165            return ret;
2166            }
2167
2168        if ( NO_ERROR == ret )
2169            {
2170            mBracketingRunning = true;
2171            }
2172
2173        if (  (NO_ERROR == ret) && ( NULL != mCameraAdapter ) )
2174            {
2175            ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_QUERY_BUFFER_SIZE_IMAGE_CAPTURE,
2176                                              ( int ) &frame,
2177                                              ( mBracketRangeNegative + 1 ));
2178
2179            if ( NO_ERROR != ret )
2180                {
2181                CAMHAL_LOGEB("CAMERA_QUERY_BUFFER_SIZE_IMAGE_CAPTURE returned error 0x%x", ret);
2182                }
2183            }
2184
2185        if ( NO_ERROR == ret )
2186            {
2187            if ( NULL != mAppCallbackNotifier.get() )
2188                 {
2189                 mAppCallbackNotifier->setBurst(true);
2190                 }
2191            }
2192
2193        if ( NO_ERROR == ret )
2194            {
2195            mParameters.getPictureSize(( int * ) &frame.mWidth,
2196                                       ( int * ) &frame.mHeight);
2197
2198            ret = allocImageBufs(frame.mWidth,
2199                                 frame.mHeight,
2200                                 frame.mLength,
2201                                 mParameters.getPictureFormat(),
2202                                 ( mBracketRangeNegative + 1 ));
2203            if ( NO_ERROR != ret )
2204                {
2205                CAMHAL_LOGEB("allocImageBufs returned error 0x%x", ret);
2206                }
2207            }
2208
2209        if (  (NO_ERROR == ret) && ( NULL != mCameraAdapter ) )
2210            {
2211
2212            desc.mBuffers = mImageBufs;
2213            desc.mOffsets = mImageOffsets;
2214            desc.mFd = mImageFd;
2215            desc.mLength = mImageLength;
2216            desc.mCount = ( size_t ) ( mBracketRangeNegative + 1 );
2217            desc.mMaxQueueable = ( size_t ) ( mBracketRangeNegative + 1 );
2218
2219            ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_USE_BUFFERS_IMAGE_CAPTURE,
2220                                              ( int ) &desc);
2221
2222            if ( NO_ERROR == ret )
2223                {
2224
2225#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
2226
2227                 //pass capture timestamp along with the camera adapter command
2228                ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_START_BRACKET_CAPTURE,  ( mBracketRangePositive + 1 ),  (int) &mStartCapture);
2229
2230#else
2231
2232                ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_START_BRACKET_CAPTURE, ( mBracketRangePositive + 1 ));
2233
2234#endif
2235
2236                }
2237            }
2238
2239        return ret;
2240}
2241
2242status_t CameraHal::stopImageBracketing()
2243{
2244        status_t ret = NO_ERROR;
2245
2246        LOG_FUNCTION_NAME;
2247
2248        if ( !mBracketingRunning )
2249            {
2250            return ret;
2251            }
2252
2253        if ( NO_ERROR == ret )
2254            {
2255            mBracketingRunning = false;
2256            }
2257
2258        if(!previewEnabled() && !mDisplayPaused)
2259            {
2260            return NO_INIT;
2261            }
2262
2263        if ( NO_ERROR == ret )
2264            {
2265            ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_STOP_BRACKET_CAPTURE);
2266            }
2267
2268        LOG_FUNCTION_NAME_EXIT;
2269
2270        return ret;
2271}
2272
2273/**
2274   @brief Take a picture.
2275
2276   @param none
2277   @return NO_ERROR If able to switch to image capture
2278   @todo Define error codes if unable to switch to image capture
2279
2280 */
2281status_t CameraHal::takePicture( )
2282{
2283    status_t ret = NO_ERROR;
2284    CameraFrame frame;
2285    CameraAdapter::BuffersDescriptor desc;
2286    int burst;
2287    const char *valstr = NULL;
2288    unsigned int bufferCount = 1;
2289
2290    Mutex::Autolock lock(mLock);
2291
2292#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
2293
2294    gettimeofday(&mStartCapture, NULL);
2295
2296#endif
2297
2298    LOG_FUNCTION_NAME;
2299
2300    if(!previewEnabled() && !mDisplayPaused)
2301        {
2302        LOG_FUNCTION_NAME_EXIT;
2303        CAMHAL_LOGEA("Preview not started...");
2304        return NO_INIT;
2305        }
2306
2307    // return error if we are already capturing
2308    if ( (mCameraAdapter->getState() == CameraAdapter::CAPTURE_STATE &&
2309          mCameraAdapter->getNextState() != CameraAdapter::PREVIEW_STATE) ||
2310         (mCameraAdapter->getState() == CameraAdapter::VIDEO_CAPTURE_STATE &&
2311          mCameraAdapter->getNextState() != CameraAdapter::VIDEO_STATE) ) {
2312        CAMHAL_LOGEA("Already capturing an image...");
2313        return NO_INIT;
2314    }
2315
2316    // we only support video snapshot if we are in video mode (recording hint is set)
2317    valstr = mParameters.get(TICameraParameters::KEY_CAP_MODE);
2318    if ( (mCameraAdapter->getState() == CameraAdapter::VIDEO_STATE) &&
2319         (valstr && strcmp(valstr, TICameraParameters::VIDEO_MODE)) ) {
2320        CAMHAL_LOGEA("Trying to capture while recording without recording hint set...");
2321        return INVALID_OPERATION;
2322    }
2323
2324    if ( !mBracketingRunning )
2325        {
2326
2327         if ( NO_ERROR == ret )
2328            {
2329            burst = mParameters.getInt(TICameraParameters::KEY_BURST);
2330            }
2331
2332         //Allocate all buffers only in burst capture case
2333         if ( burst > 1 )
2334             {
2335             bufferCount = CameraHal::NO_BUFFERS_IMAGE_CAPTURE;
2336             if ( NULL != mAppCallbackNotifier.get() )
2337                 {
2338                 mAppCallbackNotifier->setBurst(true);
2339                 }
2340             }
2341         else
2342             {
2343             if ( NULL != mAppCallbackNotifier.get() )
2344                 {
2345                 mAppCallbackNotifier->setBurst(false);
2346                 }
2347             }
2348
2349        // pause preview during normal image capture
2350        // do not pause preview if recording (video state)
2351        if (NO_ERROR == ret &&
2352                NULL != mDisplayAdapter.get() &&
2353                burst < 1) {
2354            if (mCameraAdapter->getState() != CameraAdapter::VIDEO_STATE) {
2355                mDisplayPaused = true;
2356                mPreviewEnabled = false;
2357                ret = mDisplayAdapter->pauseDisplay(mDisplayPaused);
2358                // since preview is paused we should stop sending preview frames too
2359                if(mMsgEnabled & CAMERA_MSG_PREVIEW_FRAME) {
2360                    mAppCallbackNotifier->disableMsgType (CAMERA_MSG_PREVIEW_FRAME);
2361                }
2362            }
2363
2364#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
2365            mDisplayAdapter->setSnapshotTimeRef(&mStartCapture);
2366#endif
2367        }
2368
2369        if ( (NO_ERROR == ret) && (NULL != mCameraAdapter) )
2370            {
2371            if ( NO_ERROR == ret )
2372                ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_QUERY_BUFFER_SIZE_IMAGE_CAPTURE,
2373                                                  ( int ) &frame,
2374                                                  bufferCount);
2375
2376            if ( NO_ERROR != ret )
2377                {
2378                CAMHAL_LOGEB("CAMERA_QUERY_BUFFER_SIZE_IMAGE_CAPTURE returned error 0x%x", ret);
2379                }
2380            }
2381
2382        if ( NO_ERROR == ret )
2383            {
2384            mParameters.getPictureSize(( int * ) &frame.mWidth,
2385                                       ( int * ) &frame.mHeight);
2386
2387            ret = allocImageBufs(frame.mWidth,
2388                                 frame.mHeight,
2389                                 frame.mLength,
2390                                 mParameters.getPictureFormat(),
2391                                 bufferCount);
2392            if ( NO_ERROR != ret )
2393                {
2394                CAMHAL_LOGEB("allocImageBufs returned error 0x%x", ret);
2395                }
2396            }
2397
2398        if (  (NO_ERROR == ret) && ( NULL != mCameraAdapter ) )
2399            {
2400            desc.mBuffers = mImageBufs;
2401            desc.mOffsets = mImageOffsets;
2402            desc.mFd = mImageFd;
2403            desc.mLength = mImageLength;
2404            desc.mCount = ( size_t ) bufferCount;
2405            desc.mMaxQueueable = ( size_t ) bufferCount;
2406
2407            ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_USE_BUFFERS_IMAGE_CAPTURE,
2408                                              ( int ) &desc);
2409            }
2410        }
2411    else
2412        {
2413        mBracketingRunning = false;
2414        }
2415
2416    if ( ( NO_ERROR == ret ) && ( NULL != mCameraAdapter ) )
2417        {
2418
2419#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
2420
2421         //pass capture timestamp along with the camera adapter command
2422        ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_START_IMAGE_CAPTURE,  (int) &mStartCapture);
2423
2424#else
2425
2426        ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_START_IMAGE_CAPTURE);
2427
2428#endif
2429
2430        }
2431
2432    return ret;
2433}
2434
2435/**
2436   @brief Cancel a picture that was started with takePicture.
2437
2438   Calling this method when no picture is being taken is a no-op.
2439
2440   @param none
2441   @return NO_ERROR If cancel succeeded. Cancel can succeed if image callback is not sent
2442   @todo Define error codes
2443
2444 */
2445status_t CameraHal::cancelPicture( )
2446{
2447    LOG_FUNCTION_NAME;
2448
2449    Mutex::Autolock lock(mLock);
2450
2451    mCameraAdapter->sendCommand(CameraAdapter::CAMERA_STOP_IMAGE_CAPTURE);
2452
2453    return NO_ERROR;
2454}
2455
2456/**
2457   @brief Return the camera parameters.
2458
2459   @param none
2460   @return Currently configured camera parameters
2461
2462 */
2463char* CameraHal::getParameters()
2464{
2465    String8 params_str8;
2466    char* params_string;
2467
2468    LOG_FUNCTION_NAME;
2469
2470    if( NULL != mCameraAdapter )
2471    {
2472        mCameraAdapter->getParameters(mParameters);
2473    }
2474
2475
2476    params_str8 = mParameters.flatten();
2477
2478    // camera service frees this string...
2479    params_string = (char*) malloc(sizeof(char) * (params_str8.length()+1));
2480    strcpy(params_string, params_str8.string());
2481
2482    LOG_FUNCTION_NAME_EXIT;
2483
2484    ///Return the current set of parameters
2485
2486    return params_string;
2487}
2488
2489void CameraHal::putParameters(char *parms)
2490{
2491    free(parms);
2492}
2493
2494/**
2495   @brief Send command to camera driver.
2496
2497   @param none
2498   @return NO_ERROR If the command succeeds
2499   @todo Define the error codes that this function can return
2500
2501 */
2502status_t CameraHal::sendCommand(int32_t cmd, int32_t arg1, int32_t arg2)
2503{
2504    status_t ret = NO_ERROR;
2505
2506    LOG_FUNCTION_NAME;
2507
2508
2509    if ( ( NO_ERROR == ret ) && ( NULL == mCameraAdapter ) )
2510        {
2511        CAMHAL_LOGEA("No CameraAdapter instance");
2512        ret = -EINVAL;
2513        }
2514
2515    if ( ( NO_ERROR == ret ) && ( !previewEnabled() ))
2516        {
2517        CAMHAL_LOGEA("Preview is not running");
2518        ret = -EINVAL;
2519        }
2520
2521    if ( NO_ERROR == ret )
2522        {
2523        switch(cmd)
2524            {
2525            case CAMERA_CMD_START_SMOOTH_ZOOM:
2526
2527                ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_START_SMOOTH_ZOOM, arg1);
2528
2529                break;
2530            case CAMERA_CMD_STOP_SMOOTH_ZOOM:
2531
2532                ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_STOP_SMOOTH_ZOOM);
2533
2534            case CAMERA_CMD_START_FACE_DETECTION:
2535
2536                ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_START_FD);
2537
2538                break;
2539
2540            case CAMERA_CMD_STOP_FACE_DETECTION:
2541
2542                ret = mCameraAdapter->sendCommand(CameraAdapter::CAMERA_STOP_FD);
2543
2544                break;
2545
2546            default:
2547                break;
2548            };
2549        }
2550
2551    LOG_FUNCTION_NAME_EXIT;
2552
2553    return ret;
2554}
2555
2556/**
2557   @brief Release the hardware resources owned by this object.
2558
2559   Note that this is *not* done in the destructor.
2560
2561   @param none
2562   @return none
2563
2564 */
2565void CameraHal::release()
2566{
2567    LOG_FUNCTION_NAME;
2568    ///@todo Investigate on how release is used by CameraService. Vaguely remember that this is called
2569    ///just before CameraHal object destruction
2570    deinitialize();
2571    LOG_FUNCTION_NAME_EXIT;
2572}
2573
2574
2575/**
2576   @brief Dump state of the camera hardware
2577
2578   @param[in] fd    File descriptor
2579   @param[in] args  Arguments
2580   @return NO_ERROR Dump succeeded
2581   @todo  Error codes for dump fail
2582
2583 */
2584status_t  CameraHal::dump(int fd) const
2585{
2586    LOG_FUNCTION_NAME;
2587    ///Implement this method when the h/w dump function is supported on Ducati side
2588    return NO_ERROR;
2589}
2590
2591/*-------------Camera Hal Interface Method definitions ENDS here--------------------*/
2592
2593
2594
2595
2596/*-------------Camera Hal Internal Method definitions STARTS here--------------------*/
2597
2598/**
2599   @brief Constructor of CameraHal
2600
2601   Member variables are initialized here.  No allocations should be done here as we
2602   don't use c++ exceptions in the code.
2603
2604 */
2605CameraHal::CameraHal(int cameraId)
2606{
2607    LOG_FUNCTION_NAME;
2608
2609    ///Initialize all the member variables to their defaults
2610    mPreviewEnabled = false;
2611    mPreviewBufs = NULL;
2612    mImageBufs = NULL;
2613    mBufProvider = NULL;
2614    mPreviewStartInProgress = false;
2615    mVideoBufs = NULL;
2616    mVideoBufProvider = NULL;
2617    mRecordingEnabled = false;
2618    mDisplayPaused = false;
2619    mSetPreviewWindowCalled = false;
2620    mMsgEnabled = 0;
2621    mAppCallbackNotifier = NULL;
2622    mMemoryManager = NULL;
2623    mCameraAdapter = NULL;
2624    mBracketingEnabled = false;
2625    mBracketingRunning = false;
2626    mEventProvider = NULL;
2627    mBracketRangePositive = 1;
2628    mBracketRangeNegative = 1;
2629    mMaxZoomSupported = 0;
2630    mShutterEnabled = true;
2631    mMeasurementEnabled = false;
2632    mPreviewDataBufs = NULL;
2633    mCameraProperties = NULL;
2634    mCurrentTime = 0;
2635    mFalsePreview = 0;
2636    mImageOffsets = NULL;
2637    mImageLength = 0;
2638    mImageFd = 0;
2639    mVideoOffsets = NULL;
2640    mVideoFd = 0;
2641    mVideoLength = 0;
2642    mPreviewDataOffsets = NULL;
2643    mPreviewDataFd = 0;
2644    mPreviewDataLength = 0;
2645    mPreviewFd = 0;
2646    mPreviewWidth = 0;
2647    mPreviewHeight = 0;
2648    mPreviewLength = 0;
2649    mPreviewOffsets = NULL;
2650    mPreviewRunning = 0;
2651    mPreviewStateOld = 0;
2652    mRecordingEnabled = 0;
2653    mRecordEnabled = 0;
2654    mSensorListener = NULL;
2655    mDynamicPreviewSwitch = false;
2656
2657#if PPM_INSTRUMENTATION || PPM_INSTRUMENTATION_ABS
2658
2659    //Initialize the CameraHAL constructor timestamp, which is used in the
2660    // PPM() method as time reference if the user does not supply one.
2661    gettimeofday(&ppm_start, NULL);
2662
2663#endif
2664
2665    mCameraIndex = cameraId;
2666
2667    LOG_FUNCTION_NAME_EXIT;
2668}
2669
2670/**
2671   @brief Destructor of CameraHal
2672
2673   This function simply calls deinitialize() to free up memory allocate during construct
2674   phase
2675 */
2676CameraHal::~CameraHal()
2677{
2678    LOG_FUNCTION_NAME;
2679
2680    ///Call de-initialize here once more - it is the last chance for us to relinquish all the h/w and s/w resources
2681    deinitialize();
2682
2683    if ( NULL != mEventProvider )
2684        {
2685        mEventProvider->disableEventNotification(CameraHalEvent::ALL_EVENTS);
2686        delete mEventProvider;
2687        mEventProvider = NULL;
2688        }
2689
2690    /// Free the callback notifier
2691    mAppCallbackNotifier.clear();
2692
2693    /// Free the display adapter
2694    mDisplayAdapter.clear();
2695
2696    if ( NULL != mCameraAdapter ) {
2697        int strongCount = mCameraAdapter->getStrongCount();
2698
2699        mCameraAdapter->decStrong(mCameraAdapter);
2700
2701        mCameraAdapter = NULL;
2702    }
2703
2704    freeImageBufs();
2705
2706    /// Free the memory manager
2707    mMemoryManager.clear();
2708
2709    LOG_FUNCTION_NAME_EXIT;
2710}
2711
2712/**
2713   @brief Initialize the Camera HAL
2714
2715   Creates CameraAdapter, AppCallbackNotifier, DisplayAdapter and MemoryManager
2716
2717   @param None
2718   @return NO_ERROR - On success
2719         NO_MEMORY - On failure to allocate memory for any of the objects
2720   @remarks Camera Hal internal function
2721
2722 */
2723
2724status_t CameraHal::initialize(CameraProperties::Properties* properties)
2725{
2726    LOG_FUNCTION_NAME;
2727
2728    int sensor_index = 0;
2729
2730    ///Initialize the event mask used for registering an event provider for AppCallbackNotifier
2731    ///Currently, registering all events as to be coming from CameraAdapter
2732    int32_t eventMask = CameraHalEvent::ALL_EVENTS;
2733
2734    // Get my camera properties
2735    mCameraProperties = properties;
2736
2737    if(!mCameraProperties)
2738    {
2739        goto fail_loop;
2740    }
2741
2742    // Dump the properties of this Camera
2743    // will only print if DEBUG macro is defined
2744    mCameraProperties->dump();
2745
2746    if (strcmp(CameraProperties::DEFAULT_VALUE, mCameraProperties->get(CameraProperties::CAMERA_SENSOR_INDEX)) != 0 )
2747        {
2748        sensor_index = atoi(mCameraProperties->get(CameraProperties::CAMERA_SENSOR_INDEX));
2749        }
2750
2751    CAMHAL_LOGDB("Sensor index %d", sensor_index);
2752
2753    mCameraAdapter = CameraAdapter_Factory();
2754    if ( ( NULL == mCameraAdapter ) || (mCameraAdapter->initialize(properties, sensor_index)!=NO_ERROR))
2755        {
2756        CAMHAL_LOGEA("Unable to create or initialize CameraAdapter");
2757        mCameraAdapter = NULL;
2758        goto fail_loop;
2759        }
2760
2761    mCameraAdapter->incStrong(mCameraAdapter);
2762    mCameraAdapter->registerImageReleaseCallback(releaseImageBuffers, (void *) this);
2763    mCameraAdapter->registerEndCaptureCallback(endImageCapture, (void *)this);
2764
2765    if(!mAppCallbackNotifier.get())
2766        {
2767        /// Create the callback notifier
2768        mAppCallbackNotifier = new AppCallbackNotifier();
2769        if( ( NULL == mAppCallbackNotifier.get() ) || ( mAppCallbackNotifier->initialize() != NO_ERROR))
2770            {
2771            CAMHAL_LOGEA("Unable to create or initialize AppCallbackNotifier");
2772            goto fail_loop;
2773            }
2774        }
2775
2776    if(!mMemoryManager.get())
2777        {
2778        /// Create Memory Manager
2779        mMemoryManager = new MemoryManager();
2780        if( ( NULL == mMemoryManager.get() ) || ( mMemoryManager->initialize() != NO_ERROR))
2781            {
2782            CAMHAL_LOGEA("Unable to create or initialize MemoryManager");
2783            goto fail_loop;
2784            }
2785        }
2786
2787    ///Setup the class dependencies...
2788
2789    ///AppCallbackNotifier has to know where to get the Camera frames and the events like auto focus lock etc from.
2790    ///CameraAdapter is the one which provides those events
2791    ///Set it as the frame and event providers for AppCallbackNotifier
2792    ///@remarks  setEventProvider API takes in a bit mask of events for registering a provider for the different events
2793    ///         That way, if events can come from DisplayAdapter in future, we will be able to add it as provider
2794    ///         for any event
2795    mAppCallbackNotifier->setEventProvider(eventMask, mCameraAdapter);
2796    mAppCallbackNotifier->setFrameProvider(mCameraAdapter);
2797
2798    ///Any dynamic errors that happen during the camera use case has to be propagated back to the application
2799    ///via CAMERA_MSG_ERROR. AppCallbackNotifier is the class that  notifies such errors to the application
2800    ///Set it as the error handler for CameraAdapter
2801    mCameraAdapter->setErrorHandler(mAppCallbackNotifier.get());
2802
2803    ///Start the callback notifier
2804    if(mAppCallbackNotifier->start() != NO_ERROR)
2805      {
2806        CAMHAL_LOGEA("Couldn't start AppCallbackNotifier");
2807        goto fail_loop;
2808      }
2809
2810    CAMHAL_LOGDA("Started AppCallbackNotifier..");
2811    mAppCallbackNotifier->setMeasurements(mMeasurementEnabled);
2812
2813    ///Initialize default parameters
2814    initDefaultParameters();
2815
2816
2817    if ( setParameters(mParameters) != NO_ERROR )
2818        {
2819        CAMHAL_LOGEA("Failed to set default parameters?!");
2820        }
2821
2822    // register for sensor events
2823    mSensorListener = new SensorListener();
2824    if (mSensorListener.get()) {
2825        if (mSensorListener->initialize() == NO_ERROR) {
2826            mSensorListener->setCallbacks(orientation_cb, this);
2827            mSensorListener->enableSensor(SensorListener::SENSOR_ORIENTATION);
2828        } else {
2829            CAMHAL_LOGEA("Error initializing SensorListener. not fatal, continuing");
2830            mSensorListener.clear();
2831            mSensorListener = NULL;
2832        }
2833    }
2834
2835    LOG_FUNCTION_NAME_EXIT;
2836
2837    return NO_ERROR;
2838
2839    fail_loop:
2840
2841        ///Free up the resources because we failed somewhere up
2842        deinitialize();
2843        LOG_FUNCTION_NAME_EXIT;
2844
2845        return NO_MEMORY;
2846
2847}
2848
2849bool CameraHal::isResolutionValid(unsigned int width, unsigned int height, const char *supportedResolutions)
2850{
2851    bool ret = true;
2852    status_t status = NO_ERROR;
2853    char tmpBuffer[PARAM_BUFFER + 1];
2854    char *pos = NULL;
2855
2856    LOG_FUNCTION_NAME;
2857
2858    if ( NULL == supportedResolutions )
2859        {
2860        CAMHAL_LOGEA("Invalid supported resolutions string");
2861        ret = false;
2862        goto exit;
2863        }
2864
2865    status = snprintf(tmpBuffer, PARAM_BUFFER, "%dx%d", width, height);
2866    if ( 0 > status )
2867        {
2868        CAMHAL_LOGEA("Error encountered while generating validation string");
2869        ret = false;
2870        goto exit;
2871        }
2872
2873    pos = strstr(supportedResolutions, tmpBuffer);
2874    if ( NULL == pos )
2875        {
2876        ret = false;
2877        }
2878    else
2879        {
2880        ret = true;
2881        }
2882
2883exit:
2884
2885    LOG_FUNCTION_NAME_EXIT;
2886
2887    return ret;
2888}
2889
2890bool CameraHal::isParameterValid(const char *param, const char *supportedParams)
2891{
2892    bool ret = true;
2893    char *pos = NULL;
2894
2895    LOG_FUNCTION_NAME;
2896
2897    if ( NULL == supportedParams )
2898        {
2899        CAMHAL_LOGEA("Invalid supported parameters string");
2900        ret = false;
2901        goto exit;
2902        }
2903
2904    if ( NULL == param )
2905        {
2906        CAMHAL_LOGEA("Invalid parameter string");
2907        ret = false;
2908        goto exit;
2909        }
2910
2911    pos = strstr(supportedParams, param);
2912    if ( NULL == pos )
2913        {
2914        ret = false;
2915        }
2916    else
2917        {
2918        ret = true;
2919        }
2920
2921exit:
2922
2923    LOG_FUNCTION_NAME_EXIT;
2924
2925    return ret;
2926}
2927
2928bool CameraHal::isParameterValid(int param, const char *supportedParams)
2929{
2930    bool ret = true;
2931    char *pos = NULL;
2932    status_t status;
2933    char tmpBuffer[PARAM_BUFFER + 1];
2934
2935    LOG_FUNCTION_NAME;
2936
2937    if ( NULL == supportedParams )
2938        {
2939        CAMHAL_LOGEA("Invalid supported parameters string");
2940        ret = false;
2941        goto exit;
2942        }
2943
2944    status = snprintf(tmpBuffer, PARAM_BUFFER, "%d", param);
2945    if ( 0 > status )
2946        {
2947        CAMHAL_LOGEA("Error encountered while generating validation string");
2948        ret = false;
2949        goto exit;
2950        }
2951
2952    pos = strstr(supportedParams, tmpBuffer);
2953    if ( NULL == pos )
2954        {
2955        ret = false;
2956        }
2957    else
2958        {
2959        ret = true;
2960        }
2961
2962exit:
2963
2964    LOG_FUNCTION_NAME_EXIT;
2965
2966    return ret;
2967}
2968
2969status_t CameraHal::doesSetParameterNeedUpdate(const char* new_param, const char* old_param, bool& update) {
2970    if (!new_param || !old_param) {
2971        return -EINVAL;
2972    }
2973
2974    // if params mismatch we should update parameters for camera adapter
2975    if ((strcmp(new_param, old_param) != 0)) {
2976       update = true;
2977    }
2978
2979   return NO_ERROR;
2980}
2981
2982status_t CameraHal::parseResolution(const char *resStr, int &width, int &height)
2983{
2984    status_t ret = NO_ERROR;
2985    char *ctx, *pWidth, *pHeight;
2986    const char *sep = "x";
2987    char *tmp = NULL;
2988
2989    LOG_FUNCTION_NAME;
2990
2991    if ( NULL == resStr )
2992        {
2993        return -EINVAL;
2994        }
2995
2996    //This fixes "Invalid input resolution"
2997    char *resStr_copy = (char *)malloc(strlen(resStr) + 1);
2998    if ( NULL!=resStr_copy ) {
2999    if ( NO_ERROR == ret )
3000        {
3001        strcpy(resStr_copy, resStr);
3002        pWidth = strtok_r( (char *) resStr_copy, sep, &ctx);
3003
3004        if ( NULL != pWidth )
3005            {
3006            width = atoi(pWidth);
3007            }
3008        else
3009            {
3010            CAMHAL_LOGEB("Invalid input resolution %s", resStr);
3011            ret = -EINVAL;
3012            }
3013        }
3014
3015    if ( NO_ERROR == ret )
3016        {
3017        pHeight = strtok_r(NULL, sep, &ctx);
3018
3019        if ( NULL != pHeight )
3020            {
3021            height = atoi(pHeight);
3022            }
3023        else
3024            {
3025            CAMHAL_LOGEB("Invalid input resolution %s", resStr);
3026            ret = -EINVAL;
3027            }
3028        }
3029
3030        free(resStr_copy);
3031        resStr_copy = NULL;
3032     }
3033    LOG_FUNCTION_NAME_EXIT;
3034
3035    return ret;
3036}
3037
3038void CameraHal::insertSupportedParams()
3039{
3040    char tmpBuffer[PARAM_BUFFER + 1];
3041
3042    LOG_FUNCTION_NAME;
3043
3044    CameraParameters &p = mParameters;
3045
3046    ///Set the name of the camera
3047    p.set(TICameraParameters::KEY_CAMERA_NAME, mCameraProperties->get(CameraProperties::CAMERA_NAME));
3048
3049    mMaxZoomSupported = atoi(mCameraProperties->get(CameraProperties::SUPPORTED_ZOOM_STAGES));
3050
3051    p.set(CameraParameters::KEY_SUPPORTED_PICTURE_SIZES, mCameraProperties->get(CameraProperties::SUPPORTED_PICTURE_SIZES));
3052    p.set(CameraParameters::KEY_SUPPORTED_PICTURE_FORMATS, mCameraProperties->get(CameraProperties::SUPPORTED_PICTURE_FORMATS));
3053    p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_SIZES, mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_SIZES));
3054    p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FORMATS, mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_FORMATS));
3055    p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FRAME_RATES, mCameraProperties->get(CameraProperties::SUPPORTED_PREVIEW_FRAME_RATES));
3056    p.set(CameraParameters::KEY_SUPPORTED_JPEG_THUMBNAIL_SIZES, mCameraProperties->get(CameraProperties::SUPPORTED_THUMBNAIL_SIZES));
3057    p.set(CameraParameters::KEY_SUPPORTED_WHITE_BALANCE, mCameraProperties->get(CameraProperties::SUPPORTED_WHITE_BALANCE));
3058    p.set(CameraParameters::KEY_SUPPORTED_EFFECTS, mCameraProperties->get(CameraProperties::SUPPORTED_EFFECTS));
3059    p.set(CameraParameters::KEY_SUPPORTED_SCENE_MODES, mCameraProperties->get(CameraProperties::SUPPORTED_SCENE_MODES));
3060    p.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES, mCameraProperties->get(CameraProperties::SUPPORTED_FLASH_MODES));
3061    p.set(CameraParameters::KEY_SUPPORTED_FOCUS_MODES, mCameraProperties->get(CameraProperties::SUPPORTED_FOCUS_MODES));
3062    p.set(CameraParameters::KEY_SUPPORTED_ANTIBANDING, mCameraProperties->get(CameraProperties::SUPPORTED_ANTIBANDING));
3063    p.set(CameraParameters::KEY_MAX_EXPOSURE_COMPENSATION, mCameraProperties->get(CameraProperties::SUPPORTED_EV_MAX));
3064    p.set(CameraParameters::KEY_MIN_EXPOSURE_COMPENSATION, mCameraProperties->get(CameraProperties::SUPPORTED_EV_MIN));
3065    p.set(CameraParameters::KEY_EXPOSURE_COMPENSATION_STEP, mCameraProperties->get(CameraProperties::SUPPORTED_EV_STEP));
3066    p.set(CameraParameters::KEY_SUPPORTED_SCENE_MODES, mCameraProperties->get(CameraProperties::SUPPORTED_SCENE_MODES));
3067    p.set(TICameraParameters::KEY_SUPPORTED_EXPOSURE, mCameraProperties->get(CameraProperties::SUPPORTED_EXPOSURE_MODES));
3068    p.set(TICameraParameters::KEY_SUPPORTED_ISO_VALUES, mCameraProperties->get(CameraProperties::SUPPORTED_ISO_VALUES));
3069    p.set(CameraParameters::KEY_ZOOM_RATIOS, mCameraProperties->get(CameraProperties::SUPPORTED_ZOOM_RATIOS));
3070    p.set(CameraParameters::KEY_MAX_ZOOM, mCameraProperties->get(CameraProperties::SUPPORTED_ZOOM_STAGES));
3071    p.set(CameraParameters::KEY_ZOOM_SUPPORTED, mCameraProperties->get(CameraProperties::ZOOM_SUPPORTED));
3072    p.set(CameraParameters::KEY_SMOOTH_ZOOM_SUPPORTED, mCameraProperties->get(CameraProperties::SMOOTH_ZOOM_SUPPORTED));
3073    p.set(TICameraParameters::KEY_SUPPORTED_IPP, mCameraProperties->get(CameraProperties::SUPPORTED_IPP_MODES));
3074    p.set(TICameraParameters::KEY_S3D_SUPPORTED,mCameraProperties->get(CameraProperties::S3D_SUPPORTED));
3075    p.set(TICameraParameters::KEY_S3D2D_PREVIEW_MODE,mCameraProperties->get(CameraProperties::S3D2D_PREVIEW_MODES));
3076    p.set(TICameraParameters::KEY_AUTOCONVERGENCE_MODE, mCameraProperties->get(CameraProperties::AUTOCONVERGENCE_MODE));
3077    p.set(TICameraParameters::KEY_MANUALCONVERGENCE_VALUES, mCameraProperties->get(CameraProperties::MANUALCONVERGENCE_VALUES));
3078    p.set(TICameraParameters::KEY_VSTAB,mCameraProperties->get(CameraProperties::VSTAB));
3079    p.set(TICameraParameters::KEY_VSTAB_VALUES,mCameraProperties->get(CameraProperties::VSTAB_VALUES));
3080    p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FPS_RANGE, mCameraProperties->get(CameraProperties::FRAMERATE_RANGE_SUPPORTED));
3081    p.set(TICameraParameters::KEY_SENSOR_ORIENTATION, mCameraProperties->get(CameraProperties::SENSOR_ORIENTATION));
3082    p.set(TICameraParameters::KEY_SENSOR_ORIENTATION_VALUES, mCameraProperties->get(CameraProperties::SENSOR_ORIENTATION_VALUES));
3083    p.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK_SUPPORTED, mCameraProperties->get(CameraProperties::AUTO_EXPOSURE_LOCK_SUPPORTED));
3084    p.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK_SUPPORTED, mCameraProperties->get(CameraProperties::AUTO_WHITEBALANCE_LOCK_SUPPORTED));
3085    p.set(CameraParameters::KEY_VIDEO_SNAPSHOT_SUPPORTED, mCameraProperties->get(CameraProperties::VIDEO_SNAPSHOT_SUPPORTED));
3086
3087    LOG_FUNCTION_NAME_EXIT;
3088
3089}
3090
3091void CameraHal::initDefaultParameters()
3092{
3093    //Purpose of this function is to initialize the default current and supported parameters for the currently
3094    //selected camera.
3095
3096    CameraParameters &p = mParameters;
3097    int currentRevision, adapterRevision;
3098    status_t ret = NO_ERROR;
3099    int width, height;
3100
3101    LOG_FUNCTION_NAME;
3102
3103    ret = parseResolution(mCameraProperties->get(CameraProperties::PREVIEW_SIZE), width, height);
3104
3105    if ( NO_ERROR == ret )
3106        {
3107        p.setPreviewSize(width, height);
3108        }
3109    else
3110        {
3111        p.setPreviewSize(MIN_WIDTH, MIN_HEIGHT);
3112        }
3113
3114    ret = parseResolution(mCameraProperties->get(CameraProperties::PICTURE_SIZE), width, height);
3115
3116    if ( NO_ERROR == ret )
3117        {
3118        p.setPictureSize(width, height);
3119        }
3120    else
3121        {
3122        p.setPictureSize(PICTURE_WIDTH, PICTURE_HEIGHT);
3123        }
3124
3125    ret = parseResolution(mCameraProperties->get(CameraProperties::JPEG_THUMBNAIL_SIZE), width, height);
3126
3127    if ( NO_ERROR == ret )
3128        {
3129        p.set(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH, width);
3130        p.set(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT, height);
3131        }
3132    else
3133        {
3134        p.set(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH, MIN_WIDTH);
3135        p.set(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT, MIN_HEIGHT);
3136        }
3137
3138    insertSupportedParams();
3139
3140    //Insert default values
3141    p.setPreviewFrameRate(atoi(mCameraProperties->get(CameraProperties::PREVIEW_FRAME_RATE)));
3142    p.setPreviewFormat(mCameraProperties->get(CameraProperties::PREVIEW_FORMAT));
3143    p.setPictureFormat(mCameraProperties->get(CameraProperties::PICTURE_FORMAT));
3144    p.set(CameraParameters::KEY_JPEG_QUALITY, mCameraProperties->get(CameraProperties::JPEG_QUALITY));
3145    p.set(CameraParameters::KEY_WHITE_BALANCE, mCameraProperties->get(CameraProperties::WHITEBALANCE));
3146    p.set(CameraParameters::KEY_EFFECT,  mCameraProperties->get(CameraProperties::EFFECT));
3147    p.set(CameraParameters::KEY_ANTIBANDING, mCameraProperties->get(CameraProperties::ANTIBANDING));
3148    p.set(CameraParameters::KEY_FLASH_MODE, mCameraProperties->get(CameraProperties::FLASH_MODE));
3149    p.set(CameraParameters::KEY_FOCUS_MODE, mCameraProperties->get(CameraProperties::FOCUS_MODE));
3150    p.set(CameraParameters::KEY_EXPOSURE_COMPENSATION, mCameraProperties->get(CameraProperties::EV_COMPENSATION));
3151    p.set(CameraParameters::KEY_SCENE_MODE, mCameraProperties->get(CameraProperties::SCENE_MODE));
3152    p.set(CameraParameters::KEY_FLASH_MODE, mCameraProperties->get(CameraProperties::FLASH_MODE));
3153    p.set(CameraParameters::KEY_ZOOM, mCameraProperties->get(CameraProperties::ZOOM));
3154    p.set(TICameraParameters::KEY_CONTRAST, mCameraProperties->get(CameraProperties::CONTRAST));
3155    p.set(TICameraParameters::KEY_SATURATION, mCameraProperties->get(CameraProperties::SATURATION));
3156    p.set(TICameraParameters::KEY_BRIGHTNESS, mCameraProperties->get(CameraProperties::BRIGHTNESS));
3157    p.set(TICameraParameters::KEY_SHARPNESS, mCameraProperties->get(CameraProperties::SHARPNESS));
3158    p.set(TICameraParameters::KEY_EXPOSURE_MODE, mCameraProperties->get(CameraProperties::EXPOSURE_MODE));
3159    p.set(TICameraParameters::KEY_ISO, mCameraProperties->get(CameraProperties::ISO_MODE));
3160    p.set(TICameraParameters::KEY_IPP, mCameraProperties->get(CameraProperties::IPP));
3161    p.set(TICameraParameters::KEY_GBCE, mCameraProperties->get(CameraProperties::GBCE));
3162    p.set(TICameraParameters::KEY_S3D2D_PREVIEW, mCameraProperties->get(CameraProperties::S3D2D_PREVIEW));
3163    p.set(TICameraParameters::KEY_AUTOCONVERGENCE, mCameraProperties->get(CameraProperties::AUTOCONVERGENCE));
3164    p.set(TICameraParameters::KEY_MANUALCONVERGENCE_VALUES, mCameraProperties->get(CameraProperties::MANUALCONVERGENCE_VALUES));
3165    p.set(TICameraParameters::KEY_VSTAB,mCameraProperties->get(CameraProperties::VSTAB));
3166    p.set(TICameraParameters::KEY_VSTAB_VALUES,mCameraProperties->get(CameraProperties::VSTAB_VALUES));
3167    p.set(CameraParameters::KEY_FOCAL_LENGTH, mCameraProperties->get(CameraProperties::FOCAL_LENGTH));
3168    p.set(CameraParameters::KEY_HORIZONTAL_VIEW_ANGLE, mCameraProperties->get(CameraProperties::HOR_ANGLE));
3169    p.set(CameraParameters::KEY_VERTICAL_VIEW_ANGLE, mCameraProperties->get(CameraProperties::VER_ANGLE));
3170    p.set(CameraParameters::KEY_PREVIEW_FPS_RANGE,mCameraProperties->get(CameraProperties::FRAMERATE_RANGE));
3171    p.set(TICameraParameters::KEY_SENSOR_ORIENTATION, mCameraProperties->get(CameraProperties::SENSOR_ORIENTATION));
3172    p.set(TICameraParameters::KEY_SENSOR_ORIENTATION_VALUES, mCameraProperties->get(CameraProperties::SENSOR_ORIENTATION_VALUES));
3173    p.set(TICameraParameters::KEY_EXIF_MAKE, mCameraProperties->get(CameraProperties::EXIF_MAKE));
3174    p.set(TICameraParameters::KEY_EXIF_MODEL, mCameraProperties->get(CameraProperties::EXIF_MODEL));
3175    p.set(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY, mCameraProperties->get(CameraProperties::JPEG_THUMBNAIL_QUALITY));
3176    p.set(CameraParameters::KEY_VIDEO_FRAME_FORMAT, "OMX_TI_COLOR_FormatYUV420PackedSemiPlanar");
3177    p.set(CameraParameters::KEY_MAX_NUM_DETECTED_FACES_HW, mCameraProperties->get(CameraProperties::MAX_FD_HW_FACES));
3178    p.set(CameraParameters::KEY_MAX_NUM_DETECTED_FACES_SW, mCameraProperties->get(CameraProperties::MAX_FD_SW_FACES));
3179
3180    // Only one area a.k.a Touch AF for now.
3181    // TODO: Add support for multiple focus areas.
3182    p.set(CameraParameters::KEY_MAX_NUM_FOCUS_AREAS, mCameraProperties->get(CameraProperties::MAX_FOCUS_AREAS));
3183    p.set(CameraParameters::KEY_AUTO_EXPOSURE_LOCK, mCameraProperties->get(CameraProperties::AUTO_EXPOSURE_LOCK));
3184    p.set(CameraParameters::KEY_AUTO_WHITEBALANCE_LOCK, mCameraProperties->get(CameraProperties::AUTO_WHITEBALANCE_LOCK));
3185    p.set(CameraParameters::KEY_MAX_NUM_METERING_AREAS, mCameraProperties->get(CameraProperties::MAX_NUM_METERING_AREAS));
3186
3187    LOG_FUNCTION_NAME_EXIT;
3188}
3189
3190/**
3191   @brief Stop a previously started preview.
3192   @param none
3193   @return none
3194
3195 */
3196void CameraHal::forceStopPreview()
3197{
3198    LOG_FUNCTION_NAME;
3199
3200    // stop bracketing if it is running
3201    stopImageBracketing();
3202
3203    if(mDisplayAdapter.get() != NULL) {
3204        ///Stop the buffer display first
3205        mDisplayAdapter->disableDisplay();
3206    }
3207
3208    if(mAppCallbackNotifier.get() != NULL) {
3209        //Stop the callback sending
3210        mAppCallbackNotifier->stop();
3211        mAppCallbackNotifier->flushAndReturnFrames();
3212        mAppCallbackNotifier->stopPreviewCallbacks();
3213    }
3214
3215    if ( NULL != mCameraAdapter ) {
3216        CameraAdapter::AdapterState currentState;
3217        CameraAdapter::AdapterState nextState;
3218
3219        currentState = mCameraAdapter->getState();
3220        nextState = mCameraAdapter->getNextState();
3221
3222        // since prerequisite for capturing is for camera system
3223        // to be previewing...cancel all captures before stopping
3224        // preview
3225        if ( (currentState == CameraAdapter::CAPTURE_STATE) &&
3226             (nextState != CameraAdapter::PREVIEW_STATE)) {
3227            mCameraAdapter->sendCommand(CameraAdapter::CAMERA_STOP_IMAGE_CAPTURE);
3228        }
3229
3230        // only need to send these control commands to state machine if we are
3231        // passed the LOADED_PREVIEW_STATE
3232        if (currentState > CameraAdapter::LOADED_PREVIEW_STATE) {
3233           // according to javadoc...FD should be stopped in stopPreview
3234           // and application needs to call startFaceDection again
3235           // to restart FD
3236           mCameraAdapter->sendCommand(CameraAdapter::CAMERA_STOP_FD);
3237
3238           cancelAutoFocus();
3239        }
3240
3241        // only need to send these control commands to state machine if we are
3242        // passed the INITIALIZED_STATE
3243        if (currentState > CameraAdapter::INTIALIZED_STATE) {
3244           //Stop the source of frames
3245           mCameraAdapter->sendCommand(CameraAdapter::CAMERA_STOP_PREVIEW);
3246        }
3247    }
3248
3249    freePreviewBufs();
3250    freePreviewDataBufs();
3251
3252    mPreviewEnabled = false;
3253    mDisplayPaused = false;
3254    mPreviewStartInProgress = false;
3255
3256    LOG_FUNCTION_NAME_EXIT;
3257}
3258
3259/**
3260   @brief Deallocates memory for all the resources held by Camera HAL.
3261
3262   Frees the following objects- CameraAdapter, AppCallbackNotifier, DisplayAdapter,
3263   and Memory Manager
3264
3265   @param none
3266   @return none
3267
3268 */
3269void CameraHal::deinitialize()
3270{
3271    LOG_FUNCTION_NAME;
3272
3273    if ( mPreviewEnabled || mDisplayPaused ) {
3274        forceStopPreview();
3275    }
3276
3277    mSetPreviewWindowCalled = false;
3278
3279    if (mSensorListener.get()) {
3280        mSensorListener->disableSensor(SensorListener::SENSOR_ORIENTATION);
3281        mSensorListener.clear();
3282        mSensorListener = NULL;
3283    }
3284
3285    LOG_FUNCTION_NAME_EXIT;
3286
3287}
3288
3289status_t CameraHal::storeMetaDataInBuffers(bool enable)
3290{
3291    LOG_FUNCTION_NAME;
3292
3293    return mAppCallbackNotifier->useMetaDataBufferMode(enable);
3294
3295    LOG_FUNCTION_NAME_EXIT;
3296}
3297
3298void CameraHal::selectFPSRange(int framerate, int *min_fps, int *max_fps)
3299{
3300  char * ptr;
3301  char supported[MAX_PROP_VALUE_LENGTH];
3302  int fpsrangeArray[2];
3303  int i = 0;
3304
3305  LOG_FUNCTION_NAME;
3306  size_t size = strlen(mCameraProperties->get(CameraProperties::FRAMERATE_RANGE_SUPPORTED))+1;
3307  strncpy(supported, mCameraProperties->get(CameraProperties::FRAMERATE_RANGE_SUPPORTED), size);
3308
3309  ptr = strtok (supported," (,)");
3310
3311  while (ptr != NULL)
3312    {
3313      fpsrangeArray[i]= atoi(ptr)/CameraHal::VFR_SCALE;
3314      if (i == 1)
3315        {
3316          if (framerate == fpsrangeArray[i])
3317            {
3318              CAMHAL_LOGDB("SETTING FPS RANGE min = %d max = %d \n", fpsrangeArray[0], fpsrangeArray[1]);
3319              *min_fps = fpsrangeArray[0]*CameraHal::VFR_SCALE;
3320              *max_fps = fpsrangeArray[1]*CameraHal::VFR_SCALE;
3321              break;
3322            }
3323        }
3324      ptr = strtok (NULL, " (,)");
3325      i++;
3326      i%=2;
3327    }
3328
3329  LOG_FUNCTION_NAME_EXIT;
3330
3331}
3332
3333};
3334
3335
3336