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