1/*
2**
3** Copyright 2008, The Android Open Source Project
4** Copyright 2010, Samsung Electronics Co. LTD
5**
6** Licensed under the Apache License, Version 2.0 (the "License");
7** you may not use this file except in compliance with the License.
8** You may obtain a copy of the License at
9**
10**     http://www.apache.org/licenses/LICENSE-2.0
11**
12** Unless required by applicable law or agreed to in writing, software
13** distributed under the License is distributed on an "AS IS" BASIS,
14** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15** See the License for the specific language governing permissions and
16** limitations under the License.
17*/
18
19//#define LOG_NDEBUG 0
20#define LOG_TAG "CameraHardwareSec"
21#include <utils/Log.h>
22
23#include "SecCameraHWInterface.h"
24#include <utils/threads.h>
25#include <fcntl.h>
26#include <sys/mman.h>
27#include <camera/Camera.h>
28#include <MetadataBufferType.h>
29
30#define VIDEO_COMMENT_MARKER_H          0xFFBE
31#define VIDEO_COMMENT_MARKER_L          0xFFBF
32#define VIDEO_COMMENT_MARKER_LENGTH     4
33#define JPEG_EOI_MARKER                 0xFFD9
34#define HIBYTE(x) (((x) >> 8) & 0xFF)
35#define LOBYTE(x) ((x) & 0xFF)
36
37#define BACK_CAMERA_AUTO_FOCUS_DISTANCES_STR       "0.10,1.20,Infinity"
38#define BACK_CAMERA_MACRO_FOCUS_DISTANCES_STR      "0.10,0.20,Infinity"
39#define BACK_CAMERA_INFINITY_FOCUS_DISTANCES_STR   "0.10,1.20,Infinity"
40#define FRONT_CAMERA_FOCUS_DISTANCES_STR           "0.20,0.25,Infinity"
41
42// FIXME:
43// -- The actual preview color is set to YV12. The preview frames
44//    returned via preview callback must be generated by color
45//    conversion if the requested preview color format for the
46//    preview frames is _not_ YV12. The reason that YV12 is used
47//    for actual preview is because that is the only color format
48//    supported by gralloc. Matching the preview cor format with
49//    gralloc color format improves performance since no color
50//    conversion is needed for preview.
51//
52// -- we only support two preview color formats that client
53//    applications can set: NV21 and YUV420/YV12.
54
55namespace android {
56
57struct addrs {
58    uint32_t type;  // make sure that this is 4 byte.
59    unsigned int addr_y;
60    unsigned int addr_cbcr;
61    unsigned int buf_index;
62    unsigned int reserved;
63};
64
65struct addrs_cap {
66    unsigned int addr_y;
67    unsigned int width;
68    unsigned int height;
69};
70
71static const int INITIAL_SKIP_FRAME = 3;
72static const int EFFECT_SKIP_FRAME = 1;
73
74gralloc_module_t const* CameraHardwareSec::mGrallocHal;
75
76CameraHardwareSec::CameraHardwareSec(int cameraId, camera_device_t *dev)
77        :
78          mCaptureInProgress(false),
79          mParameters(),
80          mCameraSensorName(NULL),
81          mSkipFrame(0),
82          mNotifyCb(0),
83          mDataCb(0),
84          mDataCbTimestamp(0),
85          mCallbackCookie(0),
86          mMsgEnabled(0),
87          mRecordRunning(false),
88          mPostViewWidth(0),
89          mPostViewHeight(0),
90          mPostViewSize(0),
91          mHalDevice(dev)
92{
93    ALOGV("%s :", __func__);
94    int ret = 0;
95
96    mPreviewWindow = NULL;
97    mSecCamera = SecCamera::createInstance();
98
99    mRawHeap = NULL;
100    mPreviewHeap = NULL;
101    mRecordHeap = NULL;
102
103    if (!mGrallocHal) {
104        ret = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, (const hw_module_t **)&mGrallocHal);
105        if (ret)
106            ALOGE("ERR(%s):Fail on loading gralloc HAL", __func__);
107    }
108
109    ret = mSecCamera->initCamera(cameraId);
110    if (ret < 0) {
111        ALOGE("ERR(%s):Fail on mSecCamera init", __func__);
112    }
113
114    mSecCamera->getPostViewConfig(&mPostViewWidth, &mPostViewHeight, &mPostViewSize);
115    ALOGV("mPostViewWidth = %d mPostViewHeight = %d mPostViewSize = %d",
116            mPostViewWidth,mPostViewHeight,mPostViewSize);
117
118    initDefaultParameters(cameraId);
119
120    mExitAutoFocusThread = false;
121    mExitPreviewThread = false;
122    /* whether the PreviewThread is active in preview or stopped.  we
123     * create the thread but it is initially in stopped state.
124     */
125    mPreviewRunning = false;
126    mPreviewStartDeferred = false;
127    mPreviewThread = new PreviewThread(this);
128    mAutoFocusThread = new AutoFocusThread(this);
129    mPictureThread = new PictureThread(this);
130}
131
132int CameraHardwareSec::getCameraId() const
133{
134    return mSecCamera->getCameraId();
135}
136
137void CameraHardwareSec::initDefaultParameters(int cameraId)
138{
139    if (mSecCamera == NULL) {
140        ALOGE("ERR(%s):mSecCamera object is NULL", __func__);
141        return;
142    }
143
144    CameraParameters p;
145    CameraParameters ip;
146
147    mCameraSensorName = mSecCamera->getCameraSensorName();
148    ALOGV("CameraSensorName: %s", mCameraSensorName);
149
150    int preview_max_width   = 0;
151    int preview_max_height  = 0;
152    int snapshot_max_width  = 0;
153    int snapshot_max_height = 0;
154
155    if (cameraId == SecCamera::CAMERA_ID_BACK) {
156        p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_SIZES,
157              "720x480,640x480,352x288,176x144");
158        p.set(CameraParameters::KEY_SUPPORTED_PICTURE_SIZES,
159              "2560x1920,2048x1536,1600x1200,1280x960,640x480");
160    } else {
161        p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_SIZES,
162              "640x480,320x240,176x144");
163        p.set(CameraParameters::KEY_SUPPORTED_PICTURE_SIZES,
164              "640x480");
165    }
166
167    p.getSupportedPreviewSizes(mSupportedPreviewSizes);
168
169    // If these fail, then we are using an invalid cameraId and we'll leave the
170    // sizes at zero to catch the error.
171    if (mSecCamera->getPreviewMaxSize(&preview_max_width,
172                                      &preview_max_height) < 0)
173        ALOGE("getPreviewMaxSize fail (%d / %d) \n",
174             preview_max_width, preview_max_height);
175    if (mSecCamera->getSnapshotMaxSize(&snapshot_max_width,
176                                       &snapshot_max_height) < 0)
177        ALOGE("getSnapshotMaxSize fail (%d / %d) \n",
178             snapshot_max_width, snapshot_max_height);
179    String8 previewColorString;
180    previewColorString = CameraParameters::PIXEL_FORMAT_YUV420SP;
181    previewColorString.append(",");
182    previewColorString.append(CameraParameters::PIXEL_FORMAT_YUV420P);
183    p.setPreviewFormat(CameraParameters::PIXEL_FORMAT_YUV420SP);
184    p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FORMATS, previewColorString.string());
185    p.set(CameraParameters::KEY_VIDEO_FRAME_FORMAT, CameraParameters::PIXEL_FORMAT_YUV420P);
186    p.setPreviewSize(preview_max_width, preview_max_height);
187
188    p.setPictureFormat(CameraParameters::PIXEL_FORMAT_JPEG);
189    p.setPictureSize(snapshot_max_width, snapshot_max_height);
190    p.set(CameraParameters::KEY_JPEG_QUALITY, "100"); // maximum quality
191    p.set(CameraParameters::KEY_SUPPORTED_PICTURE_FORMATS,
192          CameraParameters::PIXEL_FORMAT_JPEG);
193
194    String8 parameterString;
195
196    if (cameraId == SecCamera::CAMERA_ID_BACK) {
197        parameterString = CameraParameters::FOCUS_MODE_AUTO;
198        parameterString.append(",");
199        parameterString.append(CameraParameters::FOCUS_MODE_INFINITY);
200        parameterString.append(",");
201        parameterString.append(CameraParameters::FOCUS_MODE_MACRO);
202        p.set(CameraParameters::KEY_SUPPORTED_FOCUS_MODES,
203              parameterString.string());
204        p.set(CameraParameters::KEY_FOCUS_MODE,
205              CameraParameters::FOCUS_MODE_AUTO);
206        p.set(CameraParameters::KEY_FOCUS_DISTANCES,
207              BACK_CAMERA_AUTO_FOCUS_DISTANCES_STR);
208        p.set(CameraParameters::KEY_SUPPORTED_JPEG_THUMBNAIL_SIZES,
209              "320x240,0x0");
210        p.set(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH, "320");
211        p.set(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT, "240");
212        p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FRAME_RATES, "30");
213        p.setPreviewFrameRate(30);
214    } else {
215        parameterString = CameraParameters::FOCUS_MODE_FIXED;
216        p.set(CameraParameters::KEY_SUPPORTED_FOCUS_MODES,
217              parameterString.string());
218        p.set(CameraParameters::KEY_FOCUS_MODE,
219              CameraParameters::FOCUS_MODE_FIXED);
220        p.set(CameraParameters::KEY_FOCUS_DISTANCES,
221              FRONT_CAMERA_FOCUS_DISTANCES_STR);
222        p.set(CameraParameters::KEY_SUPPORTED_JPEG_THUMBNAIL_SIZES,
223              "160x120,0x0");
224        p.set(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH, "160");
225        p.set(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT, "120");
226        p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FRAME_RATES, "15");
227        p.setPreviewFrameRate(15);
228    }
229
230    parameterString = CameraParameters::EFFECT_NONE;
231    parameterString.append(",");
232    parameterString.append(CameraParameters::EFFECT_MONO);
233    parameterString.append(",");
234    parameterString.append(CameraParameters::EFFECT_NEGATIVE);
235    parameterString.append(",");
236    parameterString.append(CameraParameters::EFFECT_SEPIA);
237    p.set(CameraParameters::KEY_SUPPORTED_EFFECTS, parameterString.string());
238
239    if (cameraId == SecCamera::CAMERA_ID_BACK) {
240        parameterString = CameraParameters::FLASH_MODE_ON;
241        parameterString.append(",");
242        parameterString.append(CameraParameters::FLASH_MODE_OFF);
243        parameterString.append(",");
244        parameterString.append(CameraParameters::FLASH_MODE_AUTO);
245        parameterString.append(",");
246        parameterString.append(CameraParameters::FLASH_MODE_TORCH);
247        p.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES,
248              parameterString.string());
249        p.set(CameraParameters::KEY_FLASH_MODE,
250              CameraParameters::FLASH_MODE_OFF);
251
252        parameterString = CameraParameters::SCENE_MODE_AUTO;
253        parameterString.append(",");
254        parameterString.append(CameraParameters::SCENE_MODE_PORTRAIT);
255        parameterString.append(",");
256        parameterString.append(CameraParameters::SCENE_MODE_LANDSCAPE);
257        parameterString.append(",");
258        parameterString.append(CameraParameters::SCENE_MODE_NIGHT);
259        parameterString.append(",");
260        parameterString.append(CameraParameters::SCENE_MODE_BEACH);
261        parameterString.append(",");
262        parameterString.append(CameraParameters::SCENE_MODE_SNOW);
263        parameterString.append(",");
264        parameterString.append(CameraParameters::SCENE_MODE_SUNSET);
265        parameterString.append(",");
266        parameterString.append(CameraParameters::SCENE_MODE_FIREWORKS);
267        parameterString.append(",");
268        parameterString.append(CameraParameters::SCENE_MODE_SPORTS);
269        parameterString.append(",");
270        parameterString.append(CameraParameters::SCENE_MODE_PARTY);
271        parameterString.append(",");
272        parameterString.append(CameraParameters::SCENE_MODE_CANDLELIGHT);
273        p.set(CameraParameters::KEY_SUPPORTED_SCENE_MODES,
274              parameterString.string());
275        p.set(CameraParameters::KEY_SCENE_MODE,
276              CameraParameters::SCENE_MODE_AUTO);
277
278        /* we have two ranges, 4-30fps for night mode and
279         * 15-30fps for all others
280         */
281        p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FPS_RANGE, "(15000,30000)");
282        p.set(CameraParameters::KEY_PREVIEW_FPS_RANGE, "15000,30000");
283
284        p.set(CameraParameters::KEY_FOCAL_LENGTH, "3.43");
285    } else {
286        p.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FPS_RANGE, "(7500,30000)");
287        p.set(CameraParameters::KEY_PREVIEW_FPS_RANGE, "7500,30000");
288
289        p.set(CameraParameters::KEY_FOCAL_LENGTH, "0.9");
290    }
291
292    parameterString = CameraParameters::WHITE_BALANCE_AUTO;
293    parameterString.append(",");
294    parameterString.append(CameraParameters::WHITE_BALANCE_INCANDESCENT);
295    parameterString.append(",");
296    parameterString.append(CameraParameters::WHITE_BALANCE_FLUORESCENT);
297    parameterString.append(",");
298    parameterString.append(CameraParameters::WHITE_BALANCE_DAYLIGHT);
299    parameterString.append(",");
300    parameterString.append(CameraParameters::WHITE_BALANCE_CLOUDY_DAYLIGHT);
301    p.set(CameraParameters::KEY_SUPPORTED_WHITE_BALANCE,
302          parameterString.string());
303
304    ip.set("sharpness-min", 0);
305    ip.set("sharpness-max", 4);
306    ip.set("saturation-min", 0);
307    ip.set("saturation-max", 4);
308    ip.set("contrast-min", 0);
309    ip.set("contrast-max", 4);
310
311    p.set(CameraParameters::KEY_JPEG_THUMBNAIL_QUALITY, "100");
312
313    p.set(CameraParameters::KEY_ROTATION, 0);
314    p.set(CameraParameters::KEY_WHITE_BALANCE, CameraParameters::WHITE_BALANCE_AUTO);
315
316    p.set(CameraParameters::KEY_EFFECT, CameraParameters::EFFECT_NONE);
317
318    ip.set("sharpness", SHARPNESS_DEFAULT);
319    ip.set("contrast", CONTRAST_DEFAULT);
320    ip.set("saturation", SATURATION_DEFAULT);
321    ip.set("iso", "auto");
322    ip.set("metering", "center");
323
324    ip.set("wdr", 0);
325    ip.set("chk_dataline", 0);
326    if (cameraId == SecCamera::CAMERA_ID_FRONT) {
327        ip.set("vtmode", 0);
328        ip.set("blur", 0);
329    }
330
331    p.set(CameraParameters::KEY_HORIZONTAL_VIEW_ANGLE, "51.2");
332    p.set(CameraParameters::KEY_VERTICAL_VIEW_ANGLE, "39.4");
333
334    p.set(CameraParameters::KEY_EXPOSURE_COMPENSATION, "0");
335    p.set(CameraParameters::KEY_MAX_EXPOSURE_COMPENSATION, "4");
336    p.set(CameraParameters::KEY_MIN_EXPOSURE_COMPENSATION, "-4");
337    p.set(CameraParameters::KEY_EXPOSURE_COMPENSATION_STEP, "0.5");
338
339    mParameters = p;
340    mInternalParameters = ip;
341
342    /* make sure mSecCamera has all the settings we do.  applications
343     * aren't required to call setParameters themselves (only if they
344     * want to change something.
345     */
346    setParameters(p);
347    mSecCamera->setISO(ISO_AUTO);
348    mSecCamera->setMetering(METERING_CENTER);
349    mSecCamera->setContrast(CONTRAST_DEFAULT);
350    mSecCamera->setSharpness(SHARPNESS_DEFAULT);
351    mSecCamera->setSaturation(SATURATION_DEFAULT);
352    if (cameraId == SecCamera::CAMERA_ID_BACK)
353        mSecCamera->setFrameRate(30);
354    else
355        mSecCamera->setFrameRate(15);
356}
357
358CameraHardwareSec::~CameraHardwareSec()
359{
360    ALOGV("%s", __func__);
361    mSecCamera->DeinitCamera();
362}
363
364status_t CameraHardwareSec::setPreviewWindow(preview_stream_ops *w)
365{
366    int min_bufs;
367
368    mPreviewWindow = w;
369    ALOGV("%s: mPreviewWindow %p", __func__, mPreviewWindow);
370
371    if (!w) {
372        ALOGE("preview window is NULL!");
373        return OK;
374    }
375
376    mPreviewLock.lock();
377
378    if (mPreviewRunning && !mPreviewStartDeferred) {
379        ALOGI("stop preview (window change)");
380        stopPreviewInternal();
381    }
382
383    if (w->get_min_undequeued_buffer_count(w, &min_bufs)) {
384        ALOGE("%s: could not retrieve min undequeued buffer count", __func__);
385        return INVALID_OPERATION;
386    }
387
388    if (min_bufs >= kBufferCount) {
389        ALOGE("%s: min undequeued buffer count %d is too high (expecting at most %d)", __func__,
390             min_bufs, kBufferCount - 1);
391    }
392
393    ALOGV("%s: setting buffer count to %d", __func__, kBufferCount);
394    if (w->set_buffer_count(w, kBufferCount)) {
395        ALOGE("%s: could not set buffer count", __func__);
396        return INVALID_OPERATION;
397    }
398
399    int preview_width;
400    int preview_height;
401    mParameters.getPreviewSize(&preview_width, &preview_height);
402    int hal_pixel_format = HAL_PIXEL_FORMAT_YV12;
403
404    const char *str_preview_format = mParameters.getPreviewFormat();
405    ALOGV("%s: preview format %s", __func__, str_preview_format);
406
407    if (w->set_usage(w, GRALLOC_USAGE_SW_WRITE_OFTEN)) {
408        ALOGE("%s: could not set usage on gralloc buffer", __func__);
409        return INVALID_OPERATION;
410    }
411
412    if (w->set_buffers_geometry(w,
413                                preview_width, preview_height,
414                                hal_pixel_format)) {
415        ALOGE("%s: could not set buffers geometry to %s",
416             __func__, str_preview_format);
417        return INVALID_OPERATION;
418    }
419
420    if (mPreviewRunning && mPreviewStartDeferred) {
421        ALOGV("start/resume preview");
422        status_t ret = startPreviewInternal();
423        if (ret == OK) {
424            mPreviewStartDeferred = false;
425            mPreviewCondition.signal();
426        }
427    }
428    mPreviewLock.unlock();
429
430    return OK;
431}
432
433void CameraHardwareSec::setCallbacks(camera_notify_callback notify_cb,
434                                     camera_data_callback data_cb,
435                                     camera_data_timestamp_callback data_cb_timestamp,
436                                     camera_request_memory get_memory,
437                                     void *user)
438{
439    mNotifyCb = notify_cb;
440    mDataCb = data_cb;
441    mDataCbTimestamp = data_cb_timestamp;
442    mGetMemoryCb = get_memory;
443    mCallbackCookie = user;
444}
445
446void CameraHardwareSec::enableMsgType(int32_t msgType)
447{
448    ALOGV("%s : msgType = 0x%x, mMsgEnabled before = 0x%x",
449         __func__, msgType, mMsgEnabled);
450    mMsgEnabled |= msgType;
451
452    ALOGV("%s : mMsgEnabled = 0x%x", __func__, mMsgEnabled);
453}
454
455void CameraHardwareSec::disableMsgType(int32_t msgType)
456{
457    ALOGV("%s : msgType = 0x%x, mMsgEnabled before = 0x%x",
458         __func__, msgType, mMsgEnabled);
459    mMsgEnabled &= ~msgType;
460    ALOGV("%s : mMsgEnabled = 0x%x", __func__, mMsgEnabled);
461}
462
463bool CameraHardwareSec::msgTypeEnabled(int32_t msgType)
464{
465    return (mMsgEnabled & msgType);
466}
467
468// ---------------------------------------------------------------------------
469void CameraHardwareSec::setSkipFrame(int frame)
470{
471    Mutex::Autolock lock(mSkipFrameLock);
472    if (frame < mSkipFrame)
473        return;
474
475    mSkipFrame = frame;
476}
477
478int CameraHardwareSec::previewThreadWrapper()
479{
480    ALOGI("%s: starting", __func__);
481    while (1) {
482        mPreviewLock.lock();
483        while (!mPreviewRunning) {
484            ALOGI("%s: calling mSecCamera->stopPreview() and waiting", __func__);
485            mSecCamera->stopPreview();
486            /* signal that we're stopping */
487            mPreviewStoppedCondition.signal();
488            mPreviewCondition.wait(mPreviewLock);
489            ALOGI("%s: return from wait", __func__);
490        }
491        mPreviewLock.unlock();
492
493        if (mExitPreviewThread) {
494            ALOGI("%s: exiting", __func__);
495            mSecCamera->stopPreview();
496            return 0;
497        }
498        previewThread();
499    }
500}
501
502int CameraHardwareSec::previewThread()
503{
504    int index;
505    nsecs_t timestamp;
506    unsigned int phyYAddr;
507    unsigned int phyCAddr;
508    struct addrs *addrs;
509
510    index = mSecCamera->getPreview();
511    if (index < 0) {
512        ALOGE("ERR(%s):Fail on SecCamera->getPreview()", __func__);
513        return UNKNOWN_ERROR;
514    }
515
516//  ALOGV("%s: index %d", __func__, index);
517
518    mSkipFrameLock.lock();
519    if (mSkipFrame > 0) {
520        mSkipFrame--;
521        mSkipFrameLock.unlock();
522        ALOGV("%s: index %d skipping frame", __func__, index);
523        return NO_ERROR;
524    }
525    mSkipFrameLock.unlock();
526
527    timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
528
529    phyYAddr = mSecCamera->getPhyAddrY(index);
530    phyCAddr = mSecCamera->getPhyAddrC(index);
531
532    if (phyYAddr == 0xffffffff || phyCAddr == 0xffffffff) {
533        ALOGE("ERR(%s):Fail on SecCamera getPhyAddr Y addr = %0x C addr = %0x",
534             __func__, phyYAddr, phyCAddr);
535        return UNKNOWN_ERROR;
536     }
537
538    int width, height, frame_size, offset;
539
540    mSecCamera->getPreviewSize(&width, &height, &frame_size);
541
542    offset = frame_size * index;
543
544    if (mPreviewWindow && mGrallocHal) {
545        buffer_handle_t *buf_handle;
546        int stride;
547        if (0 != mPreviewWindow->dequeue_buffer(mPreviewWindow, &buf_handle, &stride)) {
548            ALOGE("Could not dequeue gralloc buffer!\n");
549            goto callbacks;
550        }
551
552        void *vaddr;
553        if (!mGrallocHal->lock(mGrallocHal,
554                               *buf_handle,
555                               GRALLOC_USAGE_SW_WRITE_OFTEN,
556                               0, 0, width, height, &vaddr)) {
557            char *frame = ((char *)mPreviewHeap->data) + offset;
558
559            // the code below assumes YUV, not RGB
560            {
561                int h;
562                char *src = frame;
563                char *ptr = (char *)vaddr;
564
565                // Copy the Y plane, while observing the stride
566                for (h = 0; h < height; h++) {
567                    memcpy(ptr, src, width);
568                    ptr += stride;
569                    src += width;
570                }
571
572                {
573                    // U
574                    char *v = ptr;
575                    ptr += stride * height / 4;
576                    for (h = 0; h < height / 2; h++) {
577                        memcpy(ptr, src, width / 2);
578                        ptr += stride / 2;
579                        src += width / 2;
580                    }
581                    // V
582                    ptr = v;
583                    for (h = 0; h < height / 2; h++) {
584                        memcpy(ptr, src, width / 2);
585                        ptr += stride / 2;
586                        src += width / 2;
587                    }
588                }
589            }
590
591            mGrallocHal->unlock(mGrallocHal, *buf_handle);
592        }
593        else
594            ALOGE("%s: could not obtain gralloc buffer", __func__);
595
596        if (0 != mPreviewWindow->enqueue_buffer(mPreviewWindow, buf_handle)) {
597            ALOGE("Could not enqueue gralloc buffer!\n");
598            goto callbacks;
599        }
600    }
601
602callbacks:
603    // Notify the client of a new frame.
604    if (mMsgEnabled & CAMERA_MSG_PREVIEW_FRAME) {
605        const char * preview_format = mParameters.getPreviewFormat();
606        if (!strcmp(preview_format, CameraParameters::PIXEL_FORMAT_YUV420SP)) {
607            // Color conversion from YUV420 to NV21
608            char *vu = ((char *)mPreviewHeap->data) + offset + width * height;
609            const int uv_size = (width * height) >> 1;
610            char saved_uv[uv_size];
611            memcpy(saved_uv, vu, uv_size);
612            char *u = saved_uv;
613            char *v = u + (uv_size >> 1);
614
615            int h = 0;
616            while (h < width * height / 4) {
617                *vu++ = *v++;
618                *vu++ = *u++;
619                ++h;
620            }
621        }
622        mDataCb(CAMERA_MSG_PREVIEW_FRAME, mPreviewHeap, index, NULL, mCallbackCookie);
623    }
624
625    Mutex::Autolock lock(mRecordLock);
626    if (mRecordRunning == true) {
627        index = mSecCamera->getRecordFrame();
628        if (index < 0) {
629            ALOGE("ERR(%s):Fail on SecCamera->getRecord()", __func__);
630            return UNKNOWN_ERROR;
631        }
632
633        phyYAddr = mSecCamera->getRecPhyAddrY(index);
634        phyCAddr = mSecCamera->getRecPhyAddrC(index);
635
636        if (phyYAddr == 0xffffffff || phyCAddr == 0xffffffff) {
637            ALOGE("ERR(%s):Fail on SecCamera getRectPhyAddr Y addr = %0x C addr = %0x", __func__,
638                 phyYAddr, phyCAddr);
639            return UNKNOWN_ERROR;
640        }
641
642        addrs = (struct addrs *)mRecordHeap->data;
643
644        addrs[index].type   = kMetadataBufferTypeCameraSource;
645        addrs[index].addr_y = phyYAddr;
646        addrs[index].addr_cbcr = phyCAddr;
647        addrs[index].buf_index = index;
648
649        // Notify the client of a new frame.
650        if (mMsgEnabled & CAMERA_MSG_VIDEO_FRAME) {
651            mDataCbTimestamp(timestamp, CAMERA_MSG_VIDEO_FRAME,
652                             mRecordHeap, index, mCallbackCookie);
653        } else {
654            mSecCamera->releaseRecordFrame(index);
655        }
656    }
657
658    return NO_ERROR;
659}
660
661status_t CameraHardwareSec::startPreview()
662{
663    int ret = 0;        //s1 [Apply factory standard]
664
665    ALOGV("%s :", __func__);
666
667    if (waitCaptureCompletion() != NO_ERROR) {
668        return TIMED_OUT;
669    }
670
671    mPreviewLock.lock();
672    if (mPreviewRunning) {
673        // already running
674        ALOGE("%s : preview thread already running", __func__);
675        mPreviewLock.unlock();
676        return INVALID_OPERATION;
677    }
678
679    mPreviewRunning = true;
680    mPreviewStartDeferred = false;
681
682    if (!mPreviewWindow) {
683        ALOGI("%s : deferring", __func__);
684        mPreviewStartDeferred = true;
685        mPreviewLock.unlock();
686        return NO_ERROR;
687    }
688
689    ret = startPreviewInternal();
690    if (ret == OK)
691        mPreviewCondition.signal();
692
693    mPreviewLock.unlock();
694    return ret;
695}
696
697status_t CameraHardwareSec::startPreviewInternal()
698{
699    ALOGV("%s", __func__);
700
701    int ret  = mSecCamera->startPreview();
702    ALOGV("%s : mSecCamera->startPreview() returned %d", __func__, ret);
703
704    if (ret < 0) {
705        ALOGE("ERR(%s):Fail on mSecCamera->startPreview()", __func__);
706        return UNKNOWN_ERROR;
707    }
708
709    setSkipFrame(INITIAL_SKIP_FRAME);
710
711    int width, height, frame_size;
712
713    mSecCamera->getPreviewSize(&width, &height, &frame_size);
714
715    ALOGD("mPreviewHeap(fd(%d), size(%d), width(%d), height(%d))",
716         mSecCamera->getCameraFd(), frame_size, width, height);
717    if (mPreviewHeap) {
718        mPreviewHeap->release(mPreviewHeap);
719        mPreviewHeap = 0;
720    }
721
722    mPreviewHeap = mGetMemoryCb((int)mSecCamera->getCameraFd(),
723                                frame_size,
724                                kBufferCount,
725                                0); // no cookie
726
727    mSecCamera->getPostViewConfig(&mPostViewWidth, &mPostViewHeight, &mPostViewSize);
728    ALOGV("CameraHardwareSec: mPostViewWidth = %d mPostViewHeight = %d mPostViewSize = %d",
729         mPostViewWidth,mPostViewHeight,mPostViewSize);
730
731    return NO_ERROR;
732}
733
734void CameraHardwareSec::stopPreviewInternal()
735{
736    ALOGV("%s :", __func__);
737
738    /* request that the preview thread stop. */
739    if (mPreviewRunning) {
740        mPreviewRunning = false;
741        if (!mPreviewStartDeferred) {
742            mPreviewCondition.signal();
743            /* wait until preview thread is stopped */
744            mPreviewStoppedCondition.wait(mPreviewLock);
745        }
746        else
747            ALOGV("%s : preview running but deferred, doing nothing", __func__);
748    } else
749        ALOGI("%s : preview not running, doing nothing", __func__);
750}
751
752void CameraHardwareSec::stopPreview()
753{
754    ALOGV("%s :", __func__);
755
756    /* request that the preview thread stop. */
757    mPreviewLock.lock();
758    stopPreviewInternal();
759    mPreviewLock.unlock();
760}
761
762bool CameraHardwareSec::previewEnabled()
763{
764    Mutex::Autolock lock(mPreviewLock);
765    ALOGV("%s : %d", __func__, mPreviewRunning);
766    return mPreviewRunning;
767}
768
769// ---------------------------------------------------------------------------
770
771status_t CameraHardwareSec::startRecording()
772{
773    ALOGV("%s :", __func__);
774
775    Mutex::Autolock lock(mRecordLock);
776
777    if (mRecordHeap) {
778        mRecordHeap->release(mRecordHeap);
779        mRecordHeap = 0;
780    }
781    mRecordHeap = mGetMemoryCb(-1, sizeof(struct addrs), kBufferCount, NULL);
782    if (!mRecordHeap) {
783        ALOGE("ERR(%s): Record heap creation fail", __func__);
784        return UNKNOWN_ERROR;
785    }
786
787    if (mRecordRunning == false) {
788        if (mSecCamera->startRecord() < 0) {
789            ALOGE("ERR(%s):Fail on mSecCamera->startRecord()", __func__);
790            return UNKNOWN_ERROR;
791        }
792        mRecordRunning = true;
793    }
794    return NO_ERROR;
795}
796
797void CameraHardwareSec::stopRecording()
798{
799    ALOGV("%s :", __func__);
800
801    Mutex::Autolock lock(mRecordLock);
802
803    if (mRecordRunning == true) {
804        if (mSecCamera->stopRecord() < 0) {
805            ALOGE("ERR(%s):Fail on mSecCamera->stopRecord()", __func__);
806            return;
807        }
808        mRecordRunning = false;
809    }
810}
811
812bool CameraHardwareSec::recordingEnabled()
813{
814    ALOGV("%s :", __func__);
815
816    return mRecordRunning;
817}
818
819void CameraHardwareSec::releaseRecordingFrame(const void *opaque)
820{
821    struct addrs *addrs = (struct addrs *)opaque;
822    mSecCamera->releaseRecordFrame(addrs->buf_index);
823}
824
825// ---------------------------------------------------------------------------
826
827int CameraHardwareSec::autoFocusThread()
828{
829    int count =0;
830    int af_status =0 ;
831
832    ALOGV("%s : starting", __func__);
833
834    /* block until we're told to start.  we don't want to use
835     * a restartable thread and requestExitAndWait() in cancelAutoFocus()
836     * because it would cause deadlock between our callbacks and the
837     * caller of cancelAutoFocus() which both want to grab the same lock
838     * in CameraServices layer.
839     */
840    mFocusLock.lock();
841    /* check early exit request */
842    if (mExitAutoFocusThread) {
843        mFocusLock.unlock();
844        ALOGV("%s : exiting on request0", __func__);
845        return NO_ERROR;
846    }
847    mFocusCondition.wait(mFocusLock);
848    /* check early exit request */
849    if (mExitAutoFocusThread) {
850        mFocusLock.unlock();
851        ALOGV("%s : exiting on request1", __func__);
852        return NO_ERROR;
853    }
854    mFocusLock.unlock();
855
856    ALOGV("%s : calling setAutoFocus", __func__);
857    if (mSecCamera->setAutofocus() < 0) {
858        ALOGE("ERR(%s):Fail on mSecCamera->setAutofocus()", __func__);
859        return UNKNOWN_ERROR;
860    }
861
862    af_status = mSecCamera->getAutoFocusResult();
863
864    if (af_status == 0x01) {
865        ALOGV("%s : AF Success!!", __func__);
866        if (mMsgEnabled & CAMERA_MSG_FOCUS)
867            mNotifyCb(CAMERA_MSG_FOCUS, true, 0, mCallbackCookie);
868    } else if (af_status == 0x02) {
869        ALOGV("%s : AF Cancelled !!", __func__);
870        if (mMsgEnabled & CAMERA_MSG_FOCUS) {
871            /* CAMERA_MSG_FOCUS only takes a bool.  true for
872             * finished and false for failure.  cancel is still
873             * considered a true result.
874             */
875            mNotifyCb(CAMERA_MSG_FOCUS, true, 0, mCallbackCookie);
876        }
877    } else {
878        ALOGV("%s : AF Fail !!", __func__);
879        ALOGV("%s : mMsgEnabled = 0x%x", __func__, mMsgEnabled);
880        if (mMsgEnabled & CAMERA_MSG_FOCUS)
881            mNotifyCb(CAMERA_MSG_FOCUS, false, 0, mCallbackCookie);
882    }
883
884    ALOGV("%s : exiting with no error", __func__);
885    return NO_ERROR;
886}
887
888status_t CameraHardwareSec::autoFocus()
889{
890    ALOGV("%s :", __func__);
891    /* signal autoFocusThread to run once */
892    mFocusCondition.signal();
893    return NO_ERROR;
894}
895
896/* 2009.10.14 by icarus for added interface */
897status_t CameraHardwareSec::cancelAutoFocus()
898{
899    ALOGV("%s :", __func__);
900
901    // If preview is not running, cancel autofocus can still be called.
902    // Since the camera subsystem is completely reset on preview start,
903    // cancel AF is a no-op.
904    if (!mPreviewRunning) return NO_ERROR;
905
906    // cancelAutoFocus should be allowed after preview is started. But if
907    // the preview is deferred, cancelAutoFocus will fail. Ignore it if that is
908    // the case.
909    if (mPreviewRunning && mPreviewStartDeferred) return NO_ERROR;
910
911    if (mSecCamera->cancelAutofocus() < 0) {
912        ALOGE("ERR(%s):Fail on mSecCamera->cancelAutofocus()", __func__);
913        return UNKNOWN_ERROR;
914    }
915
916    return NO_ERROR;
917}
918
919int CameraHardwareSec::save_jpeg( unsigned char *real_jpeg, int jpeg_size)
920{
921    FILE *yuv_fp = NULL;
922    char filename[100], *buffer = NULL;
923
924    /* file create/open, note to "wb" */
925    yuv_fp = fopen("/data/camera_dump.jpeg", "wb");
926    if (yuv_fp == NULL) {
927        ALOGE("Save jpeg file open error");
928        return -1;
929    }
930
931    ALOGV("[BestIQ]  real_jpeg size ========>  %d\n", jpeg_size);
932    buffer = (char *) malloc(jpeg_size);
933    if (buffer == NULL) {
934        ALOGE("Save YUV] buffer alloc failed");
935        if (yuv_fp)
936            fclose(yuv_fp);
937
938        return -1;
939    }
940
941    memcpy(buffer, real_jpeg, jpeg_size);
942
943    fflush(stdout);
944
945    fwrite(buffer, 1, jpeg_size, yuv_fp);
946
947    fflush(yuv_fp);
948
949    if (yuv_fp)
950            fclose(yuv_fp);
951    if (buffer)
952            free(buffer);
953
954    return 0;
955}
956
957void CameraHardwareSec::save_postview(const char *fname, uint8_t *buf, uint32_t size)
958{
959    int nw;
960    int cnt = 0;
961    uint32_t written = 0;
962
963    ALOGD("opening file [%s]\n", fname);
964    int fd = open(fname, O_RDWR | O_CREAT);
965    if (fd < 0) {
966        ALOGE("failed to create file [%s]: %s", fname, strerror(errno));
967    return;
968    }
969
970    ALOGD("writing %d bytes to file [%s]\n", size, fname);
971    while (written < size) {
972        nw = ::write(fd, buf + written, size - written);
973        if (nw < 0) {
974            ALOGE("failed to write to file %d [%s]: %s",written,fname, strerror(errno));
975            break;
976        }
977        written += nw;
978        cnt++;
979    }
980    ALOGD("done writing %d bytes to file [%s] in %d passes\n",size, fname, cnt);
981    ::close(fd);
982}
983
984bool CameraHardwareSec::scaleDownYuv422(char *srcBuf, uint32_t srcWidth, uint32_t srcHeight,
985                                        char *dstBuf, uint32_t dstWidth, uint32_t dstHeight)
986{
987    int32_t step_x, step_y;
988    int32_t iXsrc, iXdst;
989    int32_t x, y, src_y_start_pos, dst_pos, src_pos;
990
991    if (dstWidth % 2 != 0 || dstHeight % 2 != 0){
992        ALOGE("scale_down_yuv422: invalid width, height for scaling");
993        return false;
994    }
995
996    step_x = srcWidth / dstWidth;
997    step_y = srcHeight / dstHeight;
998
999    dst_pos = 0;
1000    for (uint32_t y = 0; y < dstHeight; y++) {
1001        src_y_start_pos = (y * step_y * (srcWidth * 2));
1002
1003        for (uint32_t x = 0; x < dstWidth; x += 2) {
1004            src_pos = src_y_start_pos + (x * (step_x * 2));
1005
1006            dstBuf[dst_pos++] = srcBuf[src_pos    ];
1007            dstBuf[dst_pos++] = srcBuf[src_pos + 1];
1008            dstBuf[dst_pos++] = srcBuf[src_pos + 2];
1009            dstBuf[dst_pos++] = srcBuf[src_pos + 3];
1010        }
1011    }
1012
1013    return true;
1014}
1015
1016bool CameraHardwareSec::YUY2toNV21(void *srcBuf, void *dstBuf, uint32_t srcWidth, uint32_t srcHeight)
1017{
1018    int32_t        x, y, src_y_start_pos, dst_cbcr_pos, dst_pos, src_pos;
1019    unsigned char *srcBufPointer = (unsigned char *)srcBuf;
1020    unsigned char *dstBufPointer = (unsigned char *)dstBuf;
1021
1022    dst_pos = 0;
1023    dst_cbcr_pos = srcWidth*srcHeight;
1024    for (uint32_t y = 0; y < srcHeight; y++) {
1025        src_y_start_pos = (y * (srcWidth * 2));
1026
1027        for (uint32_t x = 0; x < (srcWidth * 2); x += 2) {
1028            src_pos = src_y_start_pos + x;
1029
1030            dstBufPointer[dst_pos++] = srcBufPointer[src_pos];
1031        }
1032    }
1033    for (uint32_t y = 0; y < srcHeight; y += 2) {
1034        src_y_start_pos = (y * (srcWidth * 2));
1035
1036        for (uint32_t x = 0; x < (srcWidth * 2); x += 4) {
1037            src_pos = src_y_start_pos + x;
1038
1039            dstBufPointer[dst_cbcr_pos++] = srcBufPointer[src_pos + 3];
1040            dstBufPointer[dst_cbcr_pos++] = srcBufPointer[src_pos + 1];
1041        }
1042    }
1043
1044    return true;
1045}
1046
1047int CameraHardwareSec::pictureThread()
1048{
1049    ALOGV("%s :", __func__);
1050
1051    int jpeg_size = 0;
1052    int ret = NO_ERROR;
1053    unsigned char *jpeg_data = NULL;
1054    int postview_offset = 0;
1055    unsigned char *postview_data = NULL;
1056
1057    unsigned char *addr = NULL;
1058    int mPostViewWidth, mPostViewHeight, mPostViewSize;
1059    int mThumbWidth, mThumbHeight, mThumbSize;
1060    int cap_width, cap_height, cap_frame_size;
1061    int JpegImageSize, JpegExifSize;
1062    bool isLSISensor = false;
1063
1064    unsigned int output_size = 0;
1065
1066    mSecCamera->getPostViewConfig(&mPostViewWidth, &mPostViewHeight, &mPostViewSize);
1067    mSecCamera->getThumbnailConfig(&mThumbWidth, &mThumbHeight, &mThumbSize);
1068    int postviewHeapSize = mPostViewSize;
1069    mSecCamera->getSnapshotSize(&cap_width, &cap_height, &cap_frame_size);
1070    int mJpegHeapSize;
1071    if (mSecCamera->getCameraId() == SecCamera::CAMERA_ID_BACK)
1072        mJpegHeapSize = cap_frame_size * SecCamera::getJpegRatio();
1073    else
1074        mJpegHeapSize = cap_frame_size;
1075
1076    LOG_TIME_DEFINE(0)
1077    LOG_TIME_START(0)
1078//    sp<MemoryBase> buffer = new MemoryBase(mRawHeap, 0, mPostViewSize + 8);
1079
1080    struct addrs_cap *addrs = (struct addrs_cap *)mRawHeap->data;
1081
1082    addrs[0].width = mPostViewWidth;
1083    addrs[0].height = mPostViewHeight;
1084    ALOGV("[5B] mPostViewWidth = %d mPostViewHeight = %d\n",mPostViewWidth,mPostViewHeight);
1085
1086    camera_memory_t *JpegHeap = mGetMemoryCb(-1, mJpegHeapSize, 1, 0);
1087    sp<MemoryHeapBase> PostviewHeap = new MemoryHeapBase(mPostViewSize);
1088    sp<MemoryHeapBase> ThumbnailHeap = new MemoryHeapBase(mThumbSize);
1089
1090    LOG_TIME_DEFINE(1)
1091    LOG_TIME_START(1)
1092
1093    int picture_size, picture_width, picture_height;
1094    mSecCamera->getSnapshotSize(&picture_width, &picture_height, &picture_size);
1095    int picture_format = mSecCamera->getSnapshotPixelFormat();
1096
1097    unsigned int phyAddr;
1098
1099    // Modified the shutter sound timing for Jpeg capture
1100    if (mSecCamera->getCameraId() == SecCamera::CAMERA_ID_BACK)
1101        mSecCamera->setSnapshotCmd();
1102    if (mMsgEnabled & CAMERA_MSG_SHUTTER) {
1103        mNotifyCb(CAMERA_MSG_SHUTTER, 0, 0, mCallbackCookie);
1104    }
1105
1106    if (mSecCamera->getCameraId() == SecCamera::CAMERA_ID_BACK){
1107        jpeg_data = mSecCamera->getJpeg(&jpeg_size, &phyAddr);
1108        if (jpeg_data == NULL) {
1109            ALOGE("ERR(%s):Fail on SecCamera->getSnapshot()", __func__);
1110            ret = UNKNOWN_ERROR;
1111            goto out;
1112        }
1113    } else {
1114        if (mSecCamera->getSnapshotAndJpeg((unsigned char*)PostviewHeap->base(),
1115                (unsigned char*)JpegHeap->data, &output_size) < 0) {
1116            ret = UNKNOWN_ERROR;
1117            goto out;
1118        }
1119        ALOGI("snapshotandjpeg done\n");
1120    }
1121
1122    LOG_TIME_END(1)
1123    LOG_CAMERA("getSnapshotAndJpeg interval: %lu us", LOG_TIME(1));
1124
1125    if (mSecCamera->getCameraId() == SecCamera::CAMERA_ID_BACK) {
1126        isLSISensor = !strncmp((const char*)mCameraSensorName, "S5K4ECGX", 8);
1127        if(isLSISensor) {
1128            ALOGI("== Camera Sensor Detect %s - Samsung LSI SOC 5M ==\n", mCameraSensorName);
1129            // LSI 5M SOC
1130            if (!SplitFrame(jpeg_data, SecCamera::getInterleaveDataSize(),
1131                            SecCamera::getJpegLineLength(),
1132                            mPostViewWidth * 2, mPostViewWidth,
1133                            JpegHeap->data, &JpegImageSize,
1134                            PostviewHeap->base(), &mPostViewSize)) {
1135                ret = UNKNOWN_ERROR;
1136                goto out;
1137            }
1138        } else {
1139            ALOGI("== Camera Sensor Detect %s Sony SOC 5M ==\n", mCameraSensorName);
1140            decodeInterleaveData(jpeg_data,
1141                                 SecCamera::getInterleaveDataSize(),
1142                                 mPostViewWidth, mPostViewHeight,
1143                                 &JpegImageSize, JpegHeap->data, PostviewHeap->base());
1144        }
1145    } else {
1146        JpegImageSize = static_cast<int>(output_size);
1147    }
1148    scaleDownYuv422((char *)PostviewHeap->base(), mPostViewWidth, mPostViewHeight,
1149                    (char *)ThumbnailHeap->base(), mThumbWidth, mThumbHeight);
1150
1151    memcpy(mRawHeap->data, PostviewHeap->base(), postviewHeapSize);
1152
1153    if (mMsgEnabled & CAMERA_MSG_RAW_IMAGE) {
1154        mDataCb(CAMERA_MSG_RAW_IMAGE, mRawHeap, 0, NULL, mCallbackCookie);
1155    } else if (mMsgEnabled & CAMERA_MSG_RAW_IMAGE_NOTIFY) {
1156        mNotifyCb(CAMERA_MSG_RAW_IMAGE_NOTIFY, 0, 0, mCallbackCookie);
1157    }
1158
1159    if (mMsgEnabled & CAMERA_MSG_COMPRESSED_IMAGE) {
1160        camera_memory_t *ExifHeap =
1161            mGetMemoryCb(-1, EXIF_FILE_SIZE + JPG_STREAM_BUF_SIZE, 1, 0);
1162        JpegExifSize = mSecCamera->getExif((unsigned char *)ExifHeap->data,
1163                                           (unsigned char *)ThumbnailHeap->base());
1164
1165        ALOGV("JpegExifSize=%d", JpegExifSize);
1166
1167        if (JpegExifSize < 0) {
1168            ret = UNKNOWN_ERROR;
1169            ExifHeap->release(ExifHeap);
1170            goto out;
1171        }
1172
1173        camera_memory_t *mem = mGetMemoryCb(-1, JpegImageSize + JpegExifSize, 1, 0);
1174        uint8_t *ptr = (uint8_t *) mem->data;
1175        memcpy(ptr, JpegHeap->data, 2); ptr += 2;
1176        memcpy(ptr, ExifHeap->data, JpegExifSize); ptr += JpegExifSize;
1177        memcpy(ptr, (uint8_t *) JpegHeap->data + 2, JpegImageSize - 2);
1178        mDataCb(CAMERA_MSG_COMPRESSED_IMAGE, mem, 0, NULL, mCallbackCookie);
1179        mem->release(mem);
1180        ExifHeap->release(ExifHeap);
1181    }
1182
1183    LOG_TIME_END(0)
1184    LOG_CAMERA("pictureThread interval: %lu us", LOG_TIME(0));
1185
1186    ALOGV("%s : pictureThread end", __func__);
1187
1188out:
1189    JpegHeap->release(JpegHeap);
1190    mSecCamera->endSnapshot();
1191    mCaptureLock.lock();
1192    mCaptureInProgress = false;
1193    mCaptureCondition.broadcast();
1194    mCaptureLock.unlock();
1195
1196    return ret;
1197}
1198
1199status_t CameraHardwareSec::waitCaptureCompletion() {
1200    // 5 seconds timeout
1201    nsecs_t endTime = 5000000000LL + systemTime(SYSTEM_TIME_MONOTONIC);
1202    Mutex::Autolock lock(mCaptureLock);
1203    while (mCaptureInProgress) {
1204        nsecs_t remainingTime = endTime - systemTime(SYSTEM_TIME_MONOTONIC);
1205        if (remainingTime <= 0) {
1206            ALOGE("Timed out waiting picture thread.");
1207            return TIMED_OUT;
1208        }
1209        ALOGD("Waiting for picture thread to complete.");
1210        mCaptureCondition.waitRelative(mCaptureLock, remainingTime);
1211    }
1212    return NO_ERROR;
1213}
1214
1215status_t CameraHardwareSec::takePicture()
1216{
1217    ALOGV("%s :", __func__);
1218
1219    stopPreview();
1220
1221    if (!mRawHeap) {
1222        int rawHeapSize = mPostViewSize;
1223        ALOGV("mRawHeap : MemoryHeapBase(previewHeapSize(%d))", rawHeapSize);
1224        mRawHeap = mGetMemoryCb(-1, rawHeapSize, 1, 0);
1225        if (!mRawHeap) {
1226            ALOGE("ERR(%s): Raw heap creation fail", __func__);
1227        }
1228    }
1229
1230    if (waitCaptureCompletion() != NO_ERROR) {
1231        return TIMED_OUT;
1232    }
1233
1234    if (mPictureThread->run("CameraPictureThread", PRIORITY_DEFAULT) != NO_ERROR) {
1235        ALOGE("%s : couldn't run picture thread", __func__);
1236        return INVALID_OPERATION;
1237    }
1238    mCaptureLock.lock();
1239    mCaptureInProgress = true;
1240    mCaptureLock.unlock();
1241
1242    return NO_ERROR;
1243}
1244
1245status_t CameraHardwareSec::cancelPicture()
1246{
1247    ALOGV("%s", __func__);
1248
1249    if (mPictureThread.get()) {
1250        ALOGV("%s: waiting for picture thread to exit", __func__);
1251        mPictureThread->requestExitAndWait();
1252        ALOGV("%s: picture thread has exited", __func__);
1253    }
1254
1255    return NO_ERROR;
1256}
1257
1258bool CameraHardwareSec::CheckVideoStartMarker(unsigned char *pBuf)
1259{
1260    if (!pBuf) {
1261        ALOGE("CheckVideoStartMarker() => pBuf is NULL\n");
1262        return false;
1263    }
1264
1265    if (HIBYTE(VIDEO_COMMENT_MARKER_H) == * pBuf      && LOBYTE(VIDEO_COMMENT_MARKER_H) == *(pBuf + 1) &&
1266        HIBYTE(VIDEO_COMMENT_MARKER_L) == *(pBuf + 2) && LOBYTE(VIDEO_COMMENT_MARKER_L) == *(pBuf + 3))
1267        return true;
1268
1269    return false;
1270}
1271
1272bool CameraHardwareSec::CheckEOIMarker(unsigned char *pBuf)
1273{
1274    if (!pBuf) {
1275        ALOGE("CheckEOIMarker() => pBuf is NULL\n");
1276        return false;
1277    }
1278
1279    // EOI marker [FF D9]
1280    if (HIBYTE(JPEG_EOI_MARKER) == *pBuf && LOBYTE(JPEG_EOI_MARKER) == *(pBuf + 1))
1281        return true;
1282
1283    return false;
1284}
1285
1286bool CameraHardwareSec::FindEOIMarkerInJPEG(unsigned char *pBuf, int dwBufSize, int *pnJPEGsize)
1287{
1288    if (NULL == pBuf || 0 >= dwBufSize) {
1289        ALOGE("FindEOIMarkerInJPEG() => There is no contents.");
1290        return false;
1291    }
1292
1293    unsigned char *pBufEnd = pBuf + dwBufSize;
1294
1295    while (pBuf < pBufEnd) {
1296        if (CheckEOIMarker(pBuf++))
1297            return true;
1298
1299        (*pnJPEGsize)++;
1300    }
1301
1302    return false;
1303}
1304
1305bool CameraHardwareSec::SplitFrame(unsigned char *pFrame, int dwSize,
1306                    int dwJPEGLineLength, int dwVideoLineLength, int dwVideoHeight,
1307                    void *pJPEG, int *pdwJPEGSize,
1308                    void *pVideo, int *pdwVideoSize)
1309{
1310    ALOGV("===========SplitFrame Start==============");
1311
1312    if (NULL == pFrame || 0 >= dwSize) {
1313        ALOGE("There is no contents (pFrame=%p, dwSize=%d", pFrame, dwSize);
1314        return false;
1315    }
1316
1317    if (0 == dwJPEGLineLength || 0 == dwVideoLineLength) {
1318        ALOGE("There in no input information for decoding interleaved jpeg");
1319        return false;
1320    }
1321
1322    unsigned char *pSrc = pFrame;
1323    unsigned char *pSrcEnd = pFrame + dwSize;
1324
1325    unsigned char *pJ = (unsigned char *)pJPEG;
1326    int dwJSize = 0;
1327    unsigned char *pV = (unsigned char *)pVideo;
1328    int dwVSize = 0;
1329
1330    bool bRet = false;
1331    bool isFinishJpeg = false;
1332
1333    while (pSrc < pSrcEnd) {
1334        // Check video start marker
1335        if (CheckVideoStartMarker(pSrc)) {
1336            int copyLength;
1337
1338            if (pSrc + dwVideoLineLength <= pSrcEnd)
1339                copyLength = dwVideoLineLength;
1340            else
1341                copyLength = pSrcEnd - pSrc - VIDEO_COMMENT_MARKER_LENGTH;
1342
1343            // Copy video data
1344            if (pV) {
1345                memcpy(pV, pSrc + VIDEO_COMMENT_MARKER_LENGTH, copyLength);
1346                pV += copyLength;
1347                dwVSize += copyLength;
1348            }
1349
1350            pSrc += copyLength + VIDEO_COMMENT_MARKER_LENGTH;
1351        } else {
1352            // Copy pure JPEG data
1353            int size = 0;
1354            int dwCopyBufLen = dwJPEGLineLength <= pSrcEnd-pSrc ? dwJPEGLineLength : pSrcEnd - pSrc;
1355
1356            if (FindEOIMarkerInJPEG((unsigned char *)pSrc, dwCopyBufLen, &size)) {
1357                isFinishJpeg = true;
1358                size += 2;  // to count EOF marker size
1359            } else {
1360                if ((dwCopyBufLen == 1) && (pJPEG < pJ)) {
1361                    unsigned char checkBuf[2] = { *(pJ - 1), *pSrc };
1362
1363                    if (CheckEOIMarker(checkBuf))
1364                        isFinishJpeg = true;
1365                }
1366                size = dwCopyBufLen;
1367            }
1368
1369            memcpy(pJ, pSrc, size);
1370
1371            dwJSize += size;
1372
1373            pJ += dwCopyBufLen;
1374            pSrc += dwCopyBufLen;
1375        }
1376        if (isFinishJpeg)
1377            break;
1378    }
1379
1380    if (isFinishJpeg) {
1381        bRet = true;
1382        if(pdwJPEGSize)
1383            *pdwJPEGSize = dwJSize;
1384        if(pdwVideoSize)
1385            *pdwVideoSize = dwVSize;
1386    } else {
1387        ALOGE("DecodeInterleaveJPEG_WithOutDT() => Can not find EOI");
1388        bRet = false;
1389        if(pdwJPEGSize)
1390            *pdwJPEGSize = 0;
1391        if(pdwVideoSize)
1392            *pdwVideoSize = 0;
1393    }
1394    ALOGV("===========SplitFrame end==============");
1395
1396    return bRet;
1397}
1398
1399int CameraHardwareSec::decodeInterleaveData(unsigned char *pInterleaveData,
1400                                                 int interleaveDataSize,
1401                                                 int yuvWidth,
1402                                                 int yuvHeight,
1403                                                 int *pJpegSize,
1404                                                 void *pJpegData,
1405                                                 void *pYuvData)
1406{
1407    if (pInterleaveData == NULL)
1408        return false;
1409
1410    bool ret = true;
1411    unsigned int *interleave_ptr = (unsigned int *)pInterleaveData;
1412    unsigned char *jpeg_ptr = (unsigned char *)pJpegData;
1413    unsigned char *yuv_ptr = (unsigned char *)pYuvData;
1414    unsigned char *p;
1415    int jpeg_size = 0;
1416    int yuv_size = 0;
1417
1418    int i = 0;
1419
1420    ALOGV("decodeInterleaveData Start~~~");
1421    while (i < interleaveDataSize) {
1422        if ((*interleave_ptr == 0xFFFFFFFF) || (*interleave_ptr == 0x02FFFFFF) ||
1423                (*interleave_ptr == 0xFF02FFFF)) {
1424            // Padding Data
1425//            ALOGE("%d(%x) padding data\n", i, *interleave_ptr);
1426            interleave_ptr++;
1427            i += 4;
1428        }
1429        else if ((*interleave_ptr & 0xFFFF) == 0x05FF) {
1430            // Start-code of YUV Data
1431//            ALOGE("%d(%x) yuv data\n", i, *interleave_ptr);
1432            p = (unsigned char *)interleave_ptr;
1433            p += 2;
1434            i += 2;
1435
1436            // Extract YUV Data
1437            if (pYuvData != NULL) {
1438                memcpy(yuv_ptr, p, yuvWidth * 2);
1439                yuv_ptr += yuvWidth * 2;
1440                yuv_size += yuvWidth * 2;
1441            }
1442            p += yuvWidth * 2;
1443            i += yuvWidth * 2;
1444
1445            // Check End-code of YUV Data
1446            if ((*p == 0xFF) && (*(p + 1) == 0x06)) {
1447                interleave_ptr = (unsigned int *)(p + 2);
1448                i += 2;
1449            } else {
1450                ret = false;
1451                break;
1452            }
1453        } else {
1454            // Extract JPEG Data
1455//            ALOGE("%d(%x) jpg data, jpeg_size = %d bytes\n", i, *interleave_ptr, jpeg_size);
1456            if (pJpegData != NULL) {
1457                memcpy(jpeg_ptr, interleave_ptr, 4);
1458                jpeg_ptr += 4;
1459                jpeg_size += 4;
1460            }
1461            interleave_ptr++;
1462            i += 4;
1463        }
1464    }
1465    if (ret) {
1466        if (pJpegData != NULL) {
1467            // Remove Padding after EOI
1468            for (i = 0; i < 3; i++) {
1469                if (*(--jpeg_ptr) != 0xFF) {
1470                    break;
1471                }
1472                jpeg_size--;
1473            }
1474            *pJpegSize = jpeg_size;
1475
1476        }
1477        // Check YUV Data Size
1478        if (pYuvData != NULL) {
1479            if (yuv_size != (yuvWidth * yuvHeight * 2)) {
1480                ret = false;
1481            }
1482        }
1483    }
1484    ALOGV("decodeInterleaveData End~~~");
1485    return ret;
1486}
1487
1488status_t CameraHardwareSec::dump(int fd) const
1489{
1490    const size_t SIZE = 256;
1491    char buffer[SIZE];
1492    String8 result;
1493    const Vector<String16> args;
1494
1495    if (mSecCamera != 0) {
1496        mSecCamera->dump(fd);
1497        mParameters.dump(fd, args);
1498        mInternalParameters.dump(fd, args);
1499        snprintf(buffer, 255, " preview running(%s)\n", mPreviewRunning?"true": "false");
1500        result.append(buffer);
1501    } else {
1502        result.append("No camera client yet.\n");
1503    }
1504    write(fd, result.string(), result.size());
1505    return NO_ERROR;
1506}
1507
1508bool CameraHardwareSec::isSupportedPreviewSize(const int width,
1509                                               const int height) const
1510{
1511    unsigned int i;
1512
1513    for (i = 0; i < mSupportedPreviewSizes.size(); i++) {
1514        if (mSupportedPreviewSizes[i].width == width &&
1515                mSupportedPreviewSizes[i].height == height)
1516            return true;
1517    }
1518
1519    return false;
1520}
1521
1522bool CameraHardwareSec::isSupportedParameter(const char * const parm,
1523        const char * const supported_parm) const
1524{
1525    const char *pStart;
1526    const char *pEnd;
1527
1528    if (!parm || !supported_parm)
1529        return false;
1530
1531    pStart = supported_parm;
1532
1533    while (true) {
1534        pEnd = strchr(pStart, ',');
1535        if (!pEnd) {
1536            if (!strcmp(parm, pStart))
1537                return true;
1538            else
1539                return false;
1540        }
1541        if (!strncmp(parm, pStart, pEnd - pStart)) {
1542            return true;
1543        }
1544        pStart = pEnd + 1;
1545    }
1546    /* NOTREACHED */
1547}
1548
1549status_t CameraHardwareSec::setParameters(const CameraParameters& params)
1550{
1551    ALOGV("%s :", __func__);
1552
1553    status_t ret = NO_ERROR;
1554
1555    /* if someone calls us while picture thread is running, it could screw
1556     * up the sensor quite a bit so return error.
1557     */
1558    if (waitCaptureCompletion() != NO_ERROR) {
1559        return TIMED_OUT;
1560    }
1561
1562    // preview size
1563    int new_preview_width  = 0;
1564    int new_preview_height = 0;
1565    params.getPreviewSize(&new_preview_width, &new_preview_height);
1566    const char *new_str_preview_format = params.getPreviewFormat();
1567    ALOGV("%s : new_preview_width x new_preview_height = %dx%d, format = %s",
1568         __func__, new_preview_width, new_preview_height, new_str_preview_format);
1569
1570    if (strcmp(new_str_preview_format, CameraParameters::PIXEL_FORMAT_YUV420SP) &&
1571        strcmp(new_str_preview_format, CameraParameters::PIXEL_FORMAT_YUV420P)) {
1572        ALOGE("Unsupported preview color format: %s", new_str_preview_format);
1573        return BAD_VALUE;
1574    }
1575
1576    if (0 < new_preview_width && 0 < new_preview_height &&
1577            new_str_preview_format != NULL &&
1578            isSupportedPreviewSize(new_preview_width, new_preview_height)) {
1579        int new_preview_format = V4L2_PIX_FMT_YUV420;
1580
1581        int current_preview_width, current_preview_height, current_frame_size;
1582        mSecCamera->getPreviewSize(&current_preview_width,
1583                                   &current_preview_height,
1584                                   &current_frame_size);
1585        int current_pixel_format = mSecCamera->getPreviewPixelFormat();
1586
1587        if (current_preview_width != new_preview_width ||
1588                    current_preview_height != new_preview_height ||
1589                    current_pixel_format != new_preview_format) {
1590            if (mSecCamera->setPreviewSize(new_preview_width, new_preview_height,
1591                                           new_preview_format) < 0) {
1592                ALOGE("ERR(%s):Fail on mSecCamera->setPreviewSize(width(%d), height(%d), format(%d))",
1593                     __func__, new_preview_width, new_preview_height, new_preview_format);
1594                ret = UNKNOWN_ERROR;
1595            } else {
1596                if (mPreviewWindow) {
1597                    if (mPreviewRunning && !mPreviewStartDeferred) {
1598                        ALOGE("ERR(%s): preview is running, cannot change size and format!",
1599                             __func__);
1600                        ret = INVALID_OPERATION;
1601                    }
1602
1603                    ALOGV("%s: mPreviewWindow (%p) set_buffers_geometry", __func__, mPreviewWindow);
1604                    ALOGV("%s: mPreviewWindow->set_buffers_geometry (%p)", __func__,
1605                         mPreviewWindow->set_buffers_geometry);
1606                    mPreviewWindow->set_buffers_geometry(mPreviewWindow,
1607                                                         new_preview_width, new_preview_height,
1608                                                         new_preview_format);
1609                    ALOGV("%s: DONE mPreviewWindow (%p) set_buffers_geometry", __func__, mPreviewWindow);
1610                }
1611
1612                mParameters.setPreviewSize(new_preview_width, new_preview_height);
1613                mParameters.setPreviewFormat(new_str_preview_format);
1614            }
1615        }
1616        else ALOGV("%s: preview size and format has not changed", __func__);
1617    } else {
1618        ALOGE("%s: Invalid preview size(%dx%d)",
1619                __func__, new_preview_width, new_preview_height);
1620
1621        ret = INVALID_OPERATION;
1622    }
1623
1624    int new_picture_width  = 0;
1625    int new_picture_height = 0;
1626
1627    params.getPictureSize(&new_picture_width, &new_picture_height);
1628    ALOGV("%s : new_picture_width x new_picture_height = %dx%d", __func__, new_picture_width, new_picture_height);
1629    if (0 < new_picture_width && 0 < new_picture_height) {
1630        ALOGV("%s: setSnapshotSize", __func__);
1631        if (mSecCamera->setSnapshotSize(new_picture_width, new_picture_height) < 0) {
1632            ALOGE("ERR(%s):Fail on mSecCamera->setSnapshotSize(width(%d), height(%d))",
1633                    __func__, new_picture_width, new_picture_height);
1634            ret = UNKNOWN_ERROR;
1635        } else {
1636            mParameters.setPictureSize(new_picture_width, new_picture_height);
1637        }
1638    }
1639
1640    // picture format
1641    const char *new_str_picture_format = params.getPictureFormat();
1642    ALOGV("%s : new_str_picture_format %s", __func__, new_str_picture_format);
1643    if (new_str_picture_format != NULL) {
1644        int new_picture_format = 0;
1645
1646        if (!strcmp(new_str_picture_format, CameraParameters::PIXEL_FORMAT_RGB565))
1647            new_picture_format = V4L2_PIX_FMT_RGB565;
1648        else if (!strcmp(new_str_picture_format, CameraParameters::PIXEL_FORMAT_RGBA8888))
1649            new_picture_format = V4L2_PIX_FMT_RGB32;
1650        else if (!strcmp(new_str_picture_format, CameraParameters::PIXEL_FORMAT_YUV420SP))
1651            new_picture_format = V4L2_PIX_FMT_NV21;
1652        else if (!strcmp(new_str_picture_format, "yuv420sp_custom"))
1653            new_picture_format = V4L2_PIX_FMT_NV12T;
1654        else if (!strcmp(new_str_picture_format, "yuv420p"))
1655            new_picture_format = V4L2_PIX_FMT_YUV420;
1656        else if (!strcmp(new_str_picture_format, "yuv422i"))
1657            new_picture_format = V4L2_PIX_FMT_YUYV;
1658        else if (!strcmp(new_str_picture_format, "uyv422i_custom")) //Zero copy UYVY format
1659            new_picture_format = V4L2_PIX_FMT_UYVY;
1660        else if (!strcmp(new_str_picture_format, "uyv422i")) //Non-zero copy UYVY format
1661            new_picture_format = V4L2_PIX_FMT_UYVY;
1662        else if (!strcmp(new_str_picture_format, CameraParameters::PIXEL_FORMAT_JPEG))
1663            new_picture_format = V4L2_PIX_FMT_YUYV;
1664        else if (!strcmp(new_str_picture_format, "yuv422p"))
1665            new_picture_format = V4L2_PIX_FMT_YUV422P;
1666        else
1667            new_picture_format = V4L2_PIX_FMT_NV21; //for 3rd party
1668
1669        if (mSecCamera->setSnapshotPixelFormat(new_picture_format) < 0) {
1670            ALOGE("ERR(%s):Fail on mSecCamera->setSnapshotPixelFormat(format(%d))", __func__, new_picture_format);
1671            ret = UNKNOWN_ERROR;
1672        } else {
1673            mParameters.setPictureFormat(new_str_picture_format);
1674        }
1675    }
1676
1677    //JPEG image quality
1678    int new_jpeg_quality = params.getInt(CameraParameters::KEY_JPEG_QUALITY);
1679    ALOGV("%s : new_jpeg_quality %d", __func__, new_jpeg_quality);
1680    /* we ignore bad values */
1681    if (new_jpeg_quality >=1 && new_jpeg_quality <= 100) {
1682        if (mSecCamera->setJpegQuality(new_jpeg_quality) < 0) {
1683            ALOGE("ERR(%s):Fail on mSecCamera->setJpegQuality(quality(%d))", __func__, new_jpeg_quality);
1684            ret = UNKNOWN_ERROR;
1685        } else {
1686            mParameters.set(CameraParameters::KEY_JPEG_QUALITY, new_jpeg_quality);
1687        }
1688    }
1689
1690    // JPEG thumbnail size
1691    int new_jpeg_thumbnail_width = params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH);
1692    int new_jpeg_thumbnail_height= params.getInt(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT);
1693    if (0 <= new_jpeg_thumbnail_width && 0 <= new_jpeg_thumbnail_height) {
1694        if (mSecCamera->setJpegThumbnailSize(new_jpeg_thumbnail_width, new_jpeg_thumbnail_height) < 0) {
1695            ALOGE("ERR(%s):Fail on mSecCamera->setJpegThumbnailSize(width(%d), height(%d))", __func__, new_jpeg_thumbnail_width, new_jpeg_thumbnail_height);
1696            ret = UNKNOWN_ERROR;
1697        } else {
1698            mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_WIDTH, new_jpeg_thumbnail_width);
1699            mParameters.set(CameraParameters::KEY_JPEG_THUMBNAIL_HEIGHT, new_jpeg_thumbnail_height);
1700        }
1701    }
1702
1703    // frame rate
1704    int new_frame_rate = params.getPreviewFrameRate();
1705    /* ignore any fps request, we're determine fps automatically based
1706     * on scene mode.  don't return an error because it causes CTS failure.
1707     */
1708    if (new_frame_rate != mParameters.getPreviewFrameRate()) {
1709        ALOGW("WARN(%s): request for preview frame %d not allowed, != %d\n",
1710             __func__, new_frame_rate, mParameters.getPreviewFrameRate());
1711    }
1712
1713    // rotation
1714    int new_rotation = params.getInt(CameraParameters::KEY_ROTATION);
1715    ALOGV("%s : new_rotation %d", __func__, new_rotation);
1716    if (0 <= new_rotation) {
1717        ALOGV("%s : set orientation:%d\n", __func__, new_rotation);
1718        if (mSecCamera->setExifOrientationInfo(new_rotation) < 0) {
1719            ALOGE("ERR(%s):Fail on mSecCamera->setExifOrientationInfo(%d)", __func__, new_rotation);
1720            ret = UNKNOWN_ERROR;
1721        } else {
1722            mParameters.set(CameraParameters::KEY_ROTATION, new_rotation);
1723        }
1724    }
1725
1726    // brightness
1727    int new_exposure_compensation = params.getInt(CameraParameters::KEY_EXPOSURE_COMPENSATION);
1728    int max_exposure_compensation = params.getInt(CameraParameters::KEY_MAX_EXPOSURE_COMPENSATION);
1729    int min_exposure_compensation = params.getInt(CameraParameters::KEY_MIN_EXPOSURE_COMPENSATION);
1730    ALOGV("%s : new_exposure_compensation %d", __func__, new_exposure_compensation);
1731    if ((min_exposure_compensation <= new_exposure_compensation) &&
1732        (max_exposure_compensation >= new_exposure_compensation)) {
1733        if (mSecCamera->setBrightness(new_exposure_compensation) < 0) {
1734            ALOGE("ERR(%s):Fail on mSecCamera->setBrightness(brightness(%d))", __func__, new_exposure_compensation);
1735            ret = UNKNOWN_ERROR;
1736        } else {
1737            mParameters.set(CameraParameters::KEY_EXPOSURE_COMPENSATION, new_exposure_compensation);
1738        }
1739    }
1740
1741    // whitebalance
1742    const char *new_white_str = params.get(CameraParameters::KEY_WHITE_BALANCE);
1743    ALOGV("%s : new_white_str %s", __func__, new_white_str);
1744    if (new_white_str != NULL) {
1745        int new_white = -1;
1746
1747        if (!strcmp(new_white_str, CameraParameters::WHITE_BALANCE_AUTO))
1748            new_white = WHITE_BALANCE_AUTO;
1749        else if (!strcmp(new_white_str,
1750                         CameraParameters::WHITE_BALANCE_DAYLIGHT))
1751            new_white = WHITE_BALANCE_SUNNY;
1752        else if (!strcmp(new_white_str,
1753                         CameraParameters::WHITE_BALANCE_CLOUDY_DAYLIGHT))
1754            new_white = WHITE_BALANCE_CLOUDY;
1755        else if (!strcmp(new_white_str,
1756                         CameraParameters::WHITE_BALANCE_FLUORESCENT))
1757            new_white = WHITE_BALANCE_FLUORESCENT;
1758        else if (!strcmp(new_white_str,
1759                         CameraParameters::WHITE_BALANCE_INCANDESCENT))
1760            new_white = WHITE_BALANCE_TUNGSTEN;
1761        else {
1762            ALOGE("ERR(%s):Invalid white balance(%s)", __func__, new_white_str); //twilight, shade, warm_flourescent
1763            ret = UNKNOWN_ERROR;
1764        }
1765
1766        if (0 <= new_white) {
1767            if (mSecCamera->setWhiteBalance(new_white) < 0) {
1768                ALOGE("ERR(%s):Fail on mSecCamera->setWhiteBalance(white(%d))", __func__, new_white);
1769                ret = UNKNOWN_ERROR;
1770            } else {
1771                mParameters.set(CameraParameters::KEY_WHITE_BALANCE, new_white_str);
1772            }
1773        }
1774    }
1775
1776    // scene mode
1777    const char *new_scene_mode_str = params.get(CameraParameters::KEY_SCENE_MODE);
1778    const char *current_scene_mode_str = mParameters.get(CameraParameters::KEY_SCENE_MODE);
1779
1780    // fps range
1781    int new_min_fps = 0;
1782    int new_max_fps = 0;
1783    int current_min_fps, current_max_fps;
1784    params.getPreviewFpsRange(&new_min_fps, &new_max_fps);
1785    mParameters.getPreviewFpsRange(&current_min_fps, &current_max_fps);
1786    /* our fps range is determined by the sensor, reject any request
1787     * that isn't exactly what we're already at.
1788     * but the check is performed when requesting only changing fps range
1789     */
1790    if (new_scene_mode_str && current_scene_mode_str) {
1791        if (!strcmp(new_scene_mode_str, current_scene_mode_str)) {
1792            if ((new_min_fps != current_min_fps) || (new_max_fps != current_max_fps)) {
1793                ALOGW("%s : requested new_min_fps = %d, new_max_fps = %d not allowed",
1794                        __func__, new_min_fps, new_max_fps);
1795                ALOGE("%s : current_min_fps = %d, current_max_fps = %d",
1796                        __func__, current_min_fps, current_max_fps);
1797                ret = UNKNOWN_ERROR;
1798            }
1799        }
1800    } else {
1801        /* Check basic validation if scene mode is different */
1802        if ((new_min_fps > new_max_fps) ||
1803            (new_min_fps < 0) || (new_max_fps < 0))
1804        ret = UNKNOWN_ERROR;
1805    }
1806
1807    const char *new_focus_mode_str = params.get(CameraParameters::KEY_FOCUS_MODE);
1808
1809    if (mSecCamera->getCameraId() == SecCamera::CAMERA_ID_BACK) {
1810        int  new_scene_mode = -1;
1811
1812        const char *new_flash_mode_str = params.get(CameraParameters::KEY_FLASH_MODE);
1813
1814        // fps range is (15000,30000) by default.
1815        mParameters.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FPS_RANGE, "(15000,30000)");
1816        mParameters.set(CameraParameters::KEY_PREVIEW_FPS_RANGE,
1817                "15000,30000");
1818
1819        if (!strcmp(new_scene_mode_str, CameraParameters::SCENE_MODE_AUTO)) {
1820            new_scene_mode = SCENE_MODE_NONE;
1821            mParameters.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES, "on,off,auto,torch");
1822        } else {
1823            // defaults for non-auto scene modes
1824            if (mSecCamera->getCameraId() == SecCamera::CAMERA_ID_BACK) {
1825                new_focus_mode_str = CameraParameters::FOCUS_MODE_AUTO;
1826            }
1827            new_flash_mode_str = CameraParameters::FLASH_MODE_OFF;
1828
1829            if (!strcmp(new_scene_mode_str,
1830                       CameraParameters::SCENE_MODE_PORTRAIT)) {
1831                new_scene_mode = SCENE_MODE_PORTRAIT;
1832                new_flash_mode_str = CameraParameters::FLASH_MODE_AUTO;
1833                mParameters.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES, "auto");
1834            } else if (!strcmp(new_scene_mode_str,
1835                               CameraParameters::SCENE_MODE_LANDSCAPE)) {
1836                new_scene_mode = SCENE_MODE_LANDSCAPE;
1837                new_flash_mode_str = CameraParameters::FLASH_MODE_OFF;
1838                mParameters.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES, "off");
1839            } else if (!strcmp(new_scene_mode_str,
1840                               CameraParameters::SCENE_MODE_SPORTS)) {
1841                new_scene_mode = SCENE_MODE_SPORTS;
1842                new_flash_mode_str = CameraParameters::FLASH_MODE_OFF;
1843                mParameters.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES, "off");
1844            } else if (!strcmp(new_scene_mode_str,
1845                               CameraParameters::SCENE_MODE_PARTY)) {
1846                new_scene_mode = SCENE_MODE_PARTY_INDOOR;
1847                new_flash_mode_str = CameraParameters::FLASH_MODE_AUTO;
1848                mParameters.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES, "auto");
1849            } else if ((!strcmp(new_scene_mode_str,
1850                                CameraParameters::SCENE_MODE_BEACH)) ||
1851                        (!strcmp(new_scene_mode_str,
1852                                 CameraParameters::SCENE_MODE_SNOW))) {
1853                new_scene_mode = SCENE_MODE_BEACH_SNOW;
1854                new_flash_mode_str = CameraParameters::FLASH_MODE_OFF;
1855                mParameters.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES, "off");
1856            } else if (!strcmp(new_scene_mode_str,
1857                               CameraParameters::SCENE_MODE_SUNSET)) {
1858                new_scene_mode = SCENE_MODE_SUNSET;
1859                new_flash_mode_str = CameraParameters::FLASH_MODE_OFF;
1860                mParameters.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES, "off");
1861            } else if (!strcmp(new_scene_mode_str,
1862                               CameraParameters::SCENE_MODE_NIGHT)) {
1863                new_scene_mode = SCENE_MODE_NIGHTSHOT;
1864                mParameters.set(CameraParameters::KEY_SUPPORTED_PREVIEW_FPS_RANGE, "(4000,30000)");
1865                mParameters.set(CameraParameters::KEY_PREVIEW_FPS_RANGE,
1866                                "4000,30000");
1867                new_flash_mode_str = CameraParameters::FLASH_MODE_OFF;
1868                mParameters.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES, "off");
1869            } else if (!strcmp(new_scene_mode_str,
1870                               CameraParameters::SCENE_MODE_FIREWORKS)) {
1871                new_scene_mode = SCENE_MODE_FIREWORKS;
1872                new_flash_mode_str = CameraParameters::FLASH_MODE_OFF;
1873                mParameters.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES, "off");
1874            } else if (!strcmp(new_scene_mode_str,
1875                               CameraParameters::SCENE_MODE_CANDLELIGHT)) {
1876                new_scene_mode = SCENE_MODE_CANDLE_LIGHT;
1877                new_flash_mode_str = CameraParameters::FLASH_MODE_OFF;
1878                mParameters.set(CameraParameters::KEY_SUPPORTED_FLASH_MODES, "off");
1879            } else {
1880                ALOGE("%s::unmatched scene_mode(%s)",
1881                        __func__, new_scene_mode_str); //action, night-portrait, theatre, steadyphoto
1882                ret = UNKNOWN_ERROR;
1883            }
1884        }
1885
1886        // focus mode
1887        if (new_focus_mode_str != NULL) {
1888            int  new_focus_mode = -1;
1889
1890            if (!strcmp(new_focus_mode_str,
1891                        CameraParameters::FOCUS_MODE_AUTO)) {
1892                new_focus_mode = FOCUS_MODE_AUTO;
1893                mParameters.set(CameraParameters::KEY_FOCUS_DISTANCES,
1894                                BACK_CAMERA_AUTO_FOCUS_DISTANCES_STR);
1895            }
1896            else if (!strcmp(new_focus_mode_str,
1897                             CameraParameters::FOCUS_MODE_MACRO)) {
1898                new_focus_mode = FOCUS_MODE_MACRO;
1899                mParameters.set(CameraParameters::KEY_FOCUS_DISTANCES,
1900                                BACK_CAMERA_MACRO_FOCUS_DISTANCES_STR);
1901            }
1902            else if (!strcmp(new_focus_mode_str,
1903                             CameraParameters::FOCUS_MODE_INFINITY)) {
1904                new_focus_mode = FOCUS_MODE_INFINITY;
1905                mParameters.set(CameraParameters::KEY_FOCUS_DISTANCES,
1906                                BACK_CAMERA_INFINITY_FOCUS_DISTANCES_STR);
1907            }
1908            else {
1909                ALOGE("%s::unmatched focus_mode(%s)", __func__, new_focus_mode_str);
1910                ret = UNKNOWN_ERROR;
1911            }
1912
1913            if (0 <= new_focus_mode) {
1914                if (mSecCamera->setFocusMode(new_focus_mode) < 0) {
1915                    ALOGE("%s::mSecCamera->setFocusMode(%d) fail", __func__, new_focus_mode);
1916                    ret = UNKNOWN_ERROR;
1917                } else {
1918                    mParameters.set(CameraParameters::KEY_FOCUS_MODE, new_focus_mode_str);
1919                }
1920            }
1921        }
1922
1923        // flash..
1924        if (new_flash_mode_str != NULL) {
1925            int  new_flash_mode = -1;
1926
1927            if (!strcmp(new_flash_mode_str, CameraParameters::FLASH_MODE_OFF))
1928                new_flash_mode = FLASH_MODE_OFF;
1929            else if (!strcmp(new_flash_mode_str, CameraParameters::FLASH_MODE_AUTO))
1930                new_flash_mode = FLASH_MODE_AUTO;
1931            else if (!strcmp(new_flash_mode_str, CameraParameters::FLASH_MODE_ON))
1932                new_flash_mode = FLASH_MODE_ON;
1933            else if (!strcmp(new_flash_mode_str, CameraParameters::FLASH_MODE_TORCH))
1934                new_flash_mode = FLASH_MODE_TORCH;
1935            else {
1936                ALOGE("%s::unmatched flash_mode(%s)", __func__, new_flash_mode_str); //red-eye
1937                ret = UNKNOWN_ERROR;
1938            }
1939            if (0 <= new_flash_mode) {
1940                if (mSecCamera->setFlashMode(new_flash_mode) < 0) {
1941                    ALOGE("%s::mSecCamera->setFlashMode(%d) fail", __func__, new_flash_mode);
1942                    ret = UNKNOWN_ERROR;
1943                } else {
1944                    mParameters.set(CameraParameters::KEY_FLASH_MODE, new_flash_mode_str);
1945                }
1946            }
1947        }
1948
1949        //  scene..
1950        if (0 <= new_scene_mode) {
1951            if (mSecCamera->setSceneMode(new_scene_mode) < 0) {
1952                ALOGE("%s::mSecCamera->setSceneMode(%d) fail", __func__, new_scene_mode);
1953                ret = UNKNOWN_ERROR;
1954            } else {
1955                mParameters.set(CameraParameters::KEY_SCENE_MODE, new_scene_mode_str);
1956            }
1957        }
1958    } else {
1959        if (!isSupportedParameter(new_focus_mode_str,
1960                    mParameters.get(CameraParameters::KEY_SUPPORTED_FOCUS_MODES))) {
1961            ALOGE("%s: Unsupported focus mode: %s", __func__, new_focus_mode_str);
1962            ret = UNKNOWN_ERROR;
1963        }
1964    }
1965
1966    // ---------------------------------------------------------------------------
1967
1968    // image effect
1969    const char *new_image_effect_str = params.get(CameraParameters::KEY_EFFECT);
1970    if (new_image_effect_str != NULL) {
1971
1972        int  new_image_effect = -1;
1973
1974        if (!strcmp(new_image_effect_str, CameraParameters::EFFECT_NONE))
1975            new_image_effect = IMAGE_EFFECT_NONE;
1976        else if (!strcmp(new_image_effect_str, CameraParameters::EFFECT_MONO))
1977            new_image_effect = IMAGE_EFFECT_BNW;
1978        else if (!strcmp(new_image_effect_str, CameraParameters::EFFECT_SEPIA))
1979            new_image_effect = IMAGE_EFFECT_SEPIA;
1980        else if (!strcmp(new_image_effect_str, CameraParameters::EFFECT_AQUA))
1981            new_image_effect = IMAGE_EFFECT_AQUA;
1982        else if (!strcmp(new_image_effect_str, CameraParameters::EFFECT_NEGATIVE))
1983            new_image_effect = IMAGE_EFFECT_NEGATIVE;
1984        else {
1985            //posterize, whiteboard, blackboard, solarize
1986            ALOGE("ERR(%s):Invalid effect(%s)", __func__, new_image_effect_str);
1987            ret = UNKNOWN_ERROR;
1988        }
1989
1990        if (new_image_effect >= 0) {
1991            if (mSecCamera->setImageEffect(new_image_effect) < 0) {
1992                ALOGE("ERR(%s):Fail on mSecCamera->setImageEffect(effect(%d))", __func__, new_image_effect);
1993                ret = UNKNOWN_ERROR;
1994            } else {
1995                const char *old_image_effect_str = mParameters.get(CameraParameters::KEY_EFFECT);
1996
1997                if (old_image_effect_str) {
1998                    if (strcmp(old_image_effect_str, new_image_effect_str)) {
1999                        setSkipFrame(EFFECT_SKIP_FRAME);
2000                    }
2001                }
2002
2003                mParameters.set(CameraParameters::KEY_EFFECT, new_image_effect_str);
2004            }
2005        }
2006    }
2007
2008    //vt mode
2009    int new_vtmode = mInternalParameters.getInt("vtmode");
2010    if (0 <= new_vtmode) {
2011        if (mSecCamera->setVTmode(new_vtmode) < 0) {
2012            ALOGE("ERR(%s):Fail on mSecCamera->setVTMode(%d)", __func__, new_vtmode);
2013            ret = UNKNOWN_ERROR;
2014        }
2015    }
2016
2017    //contrast
2018    int new_contrast = mInternalParameters.getInt("contrast");
2019
2020    if (0 <= new_contrast) {
2021        if (mSecCamera->setContrast(new_contrast) < 0) {
2022            ALOGE("ERR(%s):Fail on mSecCamera->setContrast(%d)", __func__, new_contrast);
2023            ret = UNKNOWN_ERROR;
2024        }
2025    }
2026
2027    //WDR
2028    int new_wdr = mInternalParameters.getInt("wdr");
2029
2030    if (0 <= new_wdr) {
2031        if (mSecCamera->setWDR(new_wdr) < 0) {
2032            ALOGE("ERR(%s):Fail on mSecCamera->setWDR(%d)", __func__, new_wdr);
2033            ret = UNKNOWN_ERROR;
2034        }
2035    }
2036
2037    //anti shake
2038    int new_anti_shake = mInternalParameters.getInt("anti-shake");
2039
2040    if (0 <= new_anti_shake) {
2041        if (mSecCamera->setAntiShake(new_anti_shake) < 0) {
2042            ALOGE("ERR(%s):Fail on mSecCamera->setWDR(%d)", __func__, new_anti_shake);
2043            ret = UNKNOWN_ERROR;
2044        }
2045    }
2046
2047    // gps latitude
2048    const char *new_gps_latitude_str = params.get(CameraParameters::KEY_GPS_LATITUDE);
2049    if (mSecCamera->setGPSLatitude(new_gps_latitude_str) < 0) {
2050        ALOGE("%s::mSecCamera->setGPSLatitude(%s) fail", __func__, new_gps_latitude_str);
2051        ret = UNKNOWN_ERROR;
2052    } else {
2053        if (new_gps_latitude_str) {
2054            mParameters.set(CameraParameters::KEY_GPS_LATITUDE, new_gps_latitude_str);
2055        } else {
2056            mParameters.remove(CameraParameters::KEY_GPS_LATITUDE);
2057        }
2058    }
2059
2060    // gps longitude
2061    const char *new_gps_longitude_str = params.get(CameraParameters::KEY_GPS_LONGITUDE);
2062
2063    if (mSecCamera->setGPSLongitude(new_gps_longitude_str) < 0) {
2064        ALOGE("%s::mSecCamera->setGPSLongitude(%s) fail", __func__, new_gps_longitude_str);
2065        ret = UNKNOWN_ERROR;
2066    } else {
2067        if (new_gps_longitude_str) {
2068            mParameters.set(CameraParameters::KEY_GPS_LONGITUDE, new_gps_longitude_str);
2069        } else {
2070            mParameters.remove(CameraParameters::KEY_GPS_LONGITUDE);
2071        }
2072    }
2073
2074    // gps altitude
2075    const char *new_gps_altitude_str = params.get(CameraParameters::KEY_GPS_ALTITUDE);
2076
2077    if (mSecCamera->setGPSAltitude(new_gps_altitude_str) < 0) {
2078        ALOGE("%s::mSecCamera->setGPSAltitude(%s) fail", __func__, new_gps_altitude_str);
2079        ret = UNKNOWN_ERROR;
2080    } else {
2081        if (new_gps_altitude_str) {
2082            mParameters.set(CameraParameters::KEY_GPS_ALTITUDE, new_gps_altitude_str);
2083        } else {
2084            mParameters.remove(CameraParameters::KEY_GPS_ALTITUDE);
2085        }
2086    }
2087
2088    // gps timestamp
2089    const char *new_gps_timestamp_str = params.get(CameraParameters::KEY_GPS_TIMESTAMP);
2090
2091    if (mSecCamera->setGPSTimeStamp(new_gps_timestamp_str) < 0) {
2092        ALOGE("%s::mSecCamera->setGPSTimeStamp(%s) fail", __func__, new_gps_timestamp_str);
2093        ret = UNKNOWN_ERROR;
2094    } else {
2095        if (new_gps_timestamp_str) {
2096            mParameters.set(CameraParameters::KEY_GPS_TIMESTAMP, new_gps_timestamp_str);
2097        } else {
2098            mParameters.remove(CameraParameters::KEY_GPS_TIMESTAMP);
2099        }
2100    }
2101
2102    // gps processing method
2103    const char *new_gps_processing_method_str = params.get(CameraParameters::KEY_GPS_PROCESSING_METHOD);
2104
2105    if (mSecCamera->setGPSProcessingMethod(new_gps_processing_method_str) < 0) {
2106        ALOGE("%s::mSecCamera->setGPSProcessingMethod(%s) fail", __func__, new_gps_processing_method_str);
2107        ret = UNKNOWN_ERROR;
2108    } else {
2109        if (new_gps_processing_method_str) {
2110            mParameters.set(CameraParameters::KEY_GPS_PROCESSING_METHOD, new_gps_processing_method_str);
2111        } else {
2112            mParameters.remove(CameraParameters::KEY_GPS_PROCESSING_METHOD);
2113        }
2114    }
2115
2116    // Recording size
2117    int new_recording_width = mInternalParameters.getInt("recording-size-width");
2118    int new_recording_height= mInternalParameters.getInt("recording-size-height");
2119
2120    if (0 < new_recording_width && 0 < new_recording_height) {
2121        if (mSecCamera->setRecordingSize(new_recording_width, new_recording_height) < 0) {
2122            ALOGE("ERR(%s):Fail on mSecCamera->setRecordingSize(width(%d), height(%d))", __func__, new_recording_width, new_recording_height);
2123            ret = UNKNOWN_ERROR;
2124        }
2125    } else {
2126        if (mSecCamera->setRecordingSize(new_preview_width, new_preview_height) < 0) {
2127            ALOGE("ERR(%s):Fail on mSecCamera->setRecordingSize(width(%d), height(%d))", __func__, new_preview_width, new_preview_height);
2128            ret = UNKNOWN_ERROR;
2129        }
2130    }
2131
2132    //gamma
2133    const char *new_gamma_str = mInternalParameters.get("video_recording_gamma");
2134
2135    if (new_gamma_str != NULL) {
2136        int new_gamma = -1;
2137        if (!strcmp(new_gamma_str, "off"))
2138            new_gamma = GAMMA_OFF;
2139        else if (!strcmp(new_gamma_str, "on"))
2140            new_gamma = GAMMA_ON;
2141        else {
2142            ALOGE("%s::unmatched gamma(%s)", __func__, new_gamma_str);
2143            ret = UNKNOWN_ERROR;
2144        }
2145
2146        if (0 <= new_gamma) {
2147            if (mSecCamera->setGamma(new_gamma) < 0) {
2148                ALOGE("%s::mSecCamera->setGamma(%d) fail", __func__, new_gamma);
2149                ret = UNKNOWN_ERROR;
2150            }
2151        }
2152    }
2153
2154    //slow ae
2155    const char *new_slow_ae_str = mInternalParameters.get("slow_ae");
2156
2157    if (new_slow_ae_str != NULL) {
2158        int new_slow_ae = -1;
2159
2160        if (!strcmp(new_slow_ae_str, "off"))
2161            new_slow_ae = SLOW_AE_OFF;
2162        else if (!strcmp(new_slow_ae_str, "on"))
2163            new_slow_ae = SLOW_AE_ON;
2164        else {
2165            ALOGE("%s::unmatched slow_ae(%s)", __func__, new_slow_ae_str);
2166            ret = UNKNOWN_ERROR;
2167        }
2168
2169        if (0 <= new_slow_ae) {
2170            if (mSecCamera->setSlowAE(new_slow_ae) < 0) {
2171                ALOGE("%s::mSecCamera->setSlowAE(%d) fail", __func__, new_slow_ae);
2172                ret = UNKNOWN_ERROR;
2173            }
2174        }
2175    }
2176
2177    /*Camcorder fix fps*/
2178    int new_sensor_mode = mInternalParameters.getInt("cam_mode");
2179
2180    if (0 <= new_sensor_mode) {
2181        if (mSecCamera->setSensorMode(new_sensor_mode) < 0) {
2182            ALOGE("ERR(%s):Fail on mSecCamera->setSensorMode(%d)", __func__, new_sensor_mode);
2183            ret = UNKNOWN_ERROR;
2184        }
2185    } else {
2186        new_sensor_mode=0;
2187    }
2188
2189    /*Shot mode*/
2190    int new_shot_mode = mInternalParameters.getInt("shot_mode");
2191
2192    if (0 <= new_shot_mode) {
2193        if (mSecCamera->setShotMode(new_shot_mode) < 0) {
2194            ALOGE("ERR(%s):Fail on mSecCamera->setShotMode(%d)", __func__, new_shot_mode);
2195            ret = UNKNOWN_ERROR;
2196        }
2197    } else {
2198        new_shot_mode=0;
2199    }
2200
2201    //blur for Video call
2202    int new_blur_level = mInternalParameters.getInt("blur");
2203
2204    if (0 <= new_blur_level) {
2205        if (mSecCamera->setBlur(new_blur_level) < 0) {
2206            ALOGE("ERR(%s):Fail on mSecCamera->setBlur(%d)", __func__, new_blur_level);
2207            ret = UNKNOWN_ERROR;
2208        }
2209    }
2210
2211
2212    // chk_dataline
2213    int new_dataline = mInternalParameters.getInt("chk_dataline");
2214
2215    if (0 <= new_dataline) {
2216        if (mSecCamera->setDataLineCheck(new_dataline) < 0) {
2217            ALOGE("ERR(%s):Fail on mSecCamera->setDataLineCheck(%d)", __func__, new_dataline);
2218            ret = UNKNOWN_ERROR;
2219        }
2220    }
2221    ALOGV("%s return ret = %d", __func__, ret);
2222
2223    return ret;
2224}
2225
2226CameraParameters CameraHardwareSec::getParameters() const
2227{
2228    ALOGV("%s :", __func__);
2229    return mParameters;
2230}
2231
2232status_t CameraHardwareSec::sendCommand(int32_t command, int32_t arg1, int32_t arg2)
2233{
2234    return BAD_VALUE;
2235}
2236
2237void CameraHardwareSec::release()
2238{
2239    ALOGV("%s", __func__);
2240
2241    /* shut down any threads we have that might be running.  do it here
2242     * instead of the destructor.  we're guaranteed to be on another thread
2243     * than the ones below.  if we used the destructor, since the threads
2244     * have a reference to this object, we could wind up trying to wait
2245     * for ourself to exit, which is a deadlock.
2246     */
2247    if (mPreviewThread != NULL) {
2248        /* this thread is normally already in it's threadLoop but blocked
2249         * on the condition variable or running.  signal it so it wakes
2250         * up and can exit.
2251         */
2252        mPreviewThread->requestExit();
2253        mExitPreviewThread = true;
2254        mPreviewRunning = true; /* let it run so it can exit */
2255        mPreviewCondition.signal();
2256        mPreviewThread->requestExitAndWait();
2257        mPreviewThread.clear();
2258    }
2259    if (mAutoFocusThread != NULL) {
2260        /* this thread is normally already in it's threadLoop but blocked
2261         * on the condition variable.  signal it so it wakes up and can exit.
2262         */
2263        mFocusLock.lock();
2264        mAutoFocusThread->requestExit();
2265        mExitAutoFocusThread = true;
2266        mFocusCondition.signal();
2267        mFocusLock.unlock();
2268        mAutoFocusThread->requestExitAndWait();
2269        mAutoFocusThread.clear();
2270    }
2271    if (mPictureThread != NULL) {
2272        mPictureThread->requestExitAndWait();
2273        mPictureThread.clear();
2274    }
2275
2276    if (mRawHeap) {
2277        mRawHeap->release(mRawHeap);
2278        mRawHeap = 0;
2279    }
2280    if (mPreviewHeap) {
2281        mPreviewHeap->release(mPreviewHeap);
2282        mPreviewHeap = 0;
2283    }
2284    if (mRecordHeap) {
2285        mRecordHeap->release(mRecordHeap);
2286        mRecordHeap = 0;
2287    }
2288
2289     /* close after all the heaps are cleared since those
2290     * could have dup'd our file descriptor.
2291     */
2292    mSecCamera->DeinitCamera();
2293}
2294
2295status_t CameraHardwareSec::storeMetaDataInBuffers(bool enable)
2296{
2297    // FIXME:
2298    // metadata buffer mode can be turned on or off.
2299    // Samsung needs to fix this.
2300    if (!enable) {
2301        ALOGE("Non-metadata buffer mode is not supported!");
2302        return INVALID_OPERATION;
2303    }
2304    return OK;
2305}
2306
2307static CameraInfo sCameraInfo[] = {
2308    {
2309        CAMERA_FACING_BACK,
2310        90,  /* orientation */
2311    },
2312    {
2313        CAMERA_FACING_FRONT,
2314        270,  /* orientation */
2315    }
2316};
2317
2318/** Close this device */
2319
2320static camera_device_t *g_cam_device;
2321
2322static int HAL_camera_device_close(struct hw_device_t* device)
2323{
2324    ALOGI("%s", __func__);
2325    if (device) {
2326        camera_device_t *cam_device = (camera_device_t *)device;
2327        delete static_cast<CameraHardwareSec *>(cam_device->priv);
2328        free(cam_device);
2329        g_cam_device = 0;
2330    }
2331    return 0;
2332}
2333
2334static inline CameraHardwareSec *obj(struct camera_device *dev)
2335{
2336    return reinterpret_cast<CameraHardwareSec *>(dev->priv);
2337}
2338
2339/** Set the preview_stream_ops to which preview frames are sent */
2340static int HAL_camera_device_set_preview_window(struct camera_device *dev,
2341                                                struct preview_stream_ops *buf)
2342{
2343    ALOGV("%s", __func__);
2344    return obj(dev)->setPreviewWindow(buf);
2345}
2346
2347/** Set the notification and data callbacks */
2348static void HAL_camera_device_set_callbacks(struct camera_device *dev,
2349        camera_notify_callback notify_cb,
2350        camera_data_callback data_cb,
2351        camera_data_timestamp_callback data_cb_timestamp,
2352        camera_request_memory get_memory,
2353        void* user)
2354{
2355    ALOGV("%s", __func__);
2356    obj(dev)->setCallbacks(notify_cb, data_cb, data_cb_timestamp,
2357                           get_memory,
2358                           user);
2359}
2360
2361/**
2362 * The following three functions all take a msg_type, which is a bitmask of
2363 * the messages defined in include/ui/Camera.h
2364 */
2365
2366/**
2367 * Enable a message, or set of messages.
2368 */
2369static void HAL_camera_device_enable_msg_type(struct camera_device *dev, int32_t msg_type)
2370{
2371    ALOGV("%s", __func__);
2372    obj(dev)->enableMsgType(msg_type);
2373}
2374
2375/**
2376 * Disable a message, or a set of messages.
2377 *
2378 * Once received a call to disableMsgType(CAMERA_MSG_VIDEO_FRAME), camera
2379 * HAL should not rely on its client to call releaseRecordingFrame() to
2380 * release video recording frames sent out by the cameral HAL before and
2381 * after the disableMsgType(CAMERA_MSG_VIDEO_FRAME) call. Camera HAL
2382 * clients must not modify/access any video recording frame after calling
2383 * disableMsgType(CAMERA_MSG_VIDEO_FRAME).
2384 */
2385static void HAL_camera_device_disable_msg_type(struct camera_device *dev, int32_t msg_type)
2386{
2387    ALOGV("%s", __func__);
2388    obj(dev)->disableMsgType(msg_type);
2389}
2390
2391/**
2392 * Query whether a message, or a set of messages, is enabled.  Note that
2393 * this is operates as an AND, if any of the messages queried are off, this
2394 * will return false.
2395 */
2396static int HAL_camera_device_msg_type_enabled(struct camera_device *dev, int32_t msg_type)
2397{
2398    ALOGV("%s", __func__);
2399    return obj(dev)->msgTypeEnabled(msg_type);
2400}
2401
2402/**
2403 * Start preview mode.
2404 */
2405static int HAL_camera_device_start_preview(struct camera_device *dev)
2406{
2407    ALOGV("%s", __func__);
2408    return obj(dev)->startPreview();
2409}
2410
2411/**
2412 * Stop a previously started preview.
2413 */
2414static void HAL_camera_device_stop_preview(struct camera_device *dev)
2415{
2416    ALOGV("%s", __func__);
2417    obj(dev)->stopPreview();
2418}
2419
2420/**
2421 * Returns true if preview is enabled.
2422 */
2423static int HAL_camera_device_preview_enabled(struct camera_device *dev)
2424{
2425    ALOGV("%s", __func__);
2426    return obj(dev)->previewEnabled();
2427}
2428
2429/**
2430 * Request the camera HAL to store meta data or real YUV data in the video
2431 * buffers sent out via CAMERA_MSG_VIDEO_FRAME for a recording session. If
2432 * it is not called, the default camera HAL behavior is to store real YUV
2433 * data in the video buffers.
2434 *
2435 * This method should be called before startRecording() in order to be
2436 * effective.
2437 *
2438 * If meta data is stored in the video buffers, it is up to the receiver of
2439 * the video buffers to interpret the contents and to find the actual frame
2440 * data with the help of the meta data in the buffer. How this is done is
2441 * outside of the scope of this method.
2442 *
2443 * Some camera HALs may not support storing meta data in the video buffers,
2444 * but all camera HALs should support storing real YUV data in the video
2445 * buffers. If the camera HAL does not support storing the meta data in the
2446 * video buffers when it is requested to do do, INVALID_OPERATION must be
2447 * returned. It is very useful for the camera HAL to pass meta data rather
2448 * than the actual frame data directly to the video encoder, since the
2449 * amount of the uncompressed frame data can be very large if video size is
2450 * large.
2451 *
2452 * @param enable if true to instruct the camera HAL to store
2453 *      meta data in the video buffers; false to instruct
2454 *      the camera HAL to store real YUV data in the video
2455 *      buffers.
2456 *
2457 * @return OK on success.
2458 */
2459static int HAL_camera_device_store_meta_data_in_buffers(struct camera_device *dev, int enable)
2460{
2461    ALOGV("%s", __func__);
2462    return obj(dev)->storeMetaDataInBuffers(enable);
2463}
2464
2465/**
2466 * Start record mode. When a record image is available, a
2467 * CAMERA_MSG_VIDEO_FRAME message is sent with the corresponding
2468 * frame. Every record frame must be released by a camera HAL client via
2469 * releaseRecordingFrame() before the client calls
2470 * disableMsgType(CAMERA_MSG_VIDEO_FRAME). After the client calls
2471 * disableMsgType(CAMERA_MSG_VIDEO_FRAME), it is the camera HAL's
2472 * responsibility to manage the life-cycle of the video recording frames,
2473 * and the client must not modify/access any video recording frames.
2474 */
2475static int HAL_camera_device_start_recording(struct camera_device *dev)
2476{
2477    ALOGV("%s", __func__);
2478    return obj(dev)->startRecording();
2479}
2480
2481/**
2482 * Stop a previously started recording.
2483 */
2484static void HAL_camera_device_stop_recording(struct camera_device *dev)
2485{
2486    ALOGV("%s", __func__);
2487    obj(dev)->stopRecording();
2488}
2489
2490/**
2491 * Returns true if recording is enabled.
2492 */
2493static int HAL_camera_device_recording_enabled(struct camera_device *dev)
2494{
2495    ALOGV("%s", __func__);
2496    return obj(dev)->recordingEnabled();
2497}
2498
2499/**
2500 * Release a record frame previously returned by CAMERA_MSG_VIDEO_FRAME.
2501 *
2502 * It is camera HAL client's responsibility to release video recording
2503 * frames sent out by the camera HAL before the camera HAL receives a call
2504 * to disableMsgType(CAMERA_MSG_VIDEO_FRAME). After it receives the call to
2505 * disableMsgType(CAMERA_MSG_VIDEO_FRAME), it is the camera HAL's
2506 * responsibility to manage the life-cycle of the video recording frames.
2507 */
2508static void HAL_camera_device_release_recording_frame(struct camera_device *dev,
2509                                const void *opaque)
2510{
2511    ALOGV("%s", __func__);
2512    obj(dev)->releaseRecordingFrame(opaque);
2513}
2514
2515/**
2516 * Start auto focus, the notification callback routine is called with
2517 * CAMERA_MSG_FOCUS once when focusing is complete. autoFocus() will be
2518 * called again if another auto focus is needed.
2519 */
2520static int HAL_camera_device_auto_focus(struct camera_device *dev)
2521{
2522    ALOGV("%s", __func__);
2523    return obj(dev)->autoFocus();
2524}
2525
2526/**
2527 * Cancels auto-focus function. If the auto-focus is still in progress,
2528 * this function will cancel it. Whether the auto-focus is in progress or
2529 * not, this function will return the focus position to the default.  If
2530 * the camera does not support auto-focus, this is a no-op.
2531 */
2532static int HAL_camera_device_cancel_auto_focus(struct camera_device *dev)
2533{
2534    ALOGV("%s", __func__);
2535    return obj(dev)->cancelAutoFocus();
2536}
2537
2538/**
2539 * Take a picture.
2540 */
2541static int HAL_camera_device_take_picture(struct camera_device *dev)
2542{
2543    ALOGV("%s", __func__);
2544    return obj(dev)->takePicture();
2545}
2546
2547/**
2548 * Cancel a picture that was started with takePicture. Calling this method
2549 * when no picture is being taken is a no-op.
2550 */
2551static int HAL_camera_device_cancel_picture(struct camera_device *dev)
2552{
2553    ALOGV("%s", __func__);
2554    return obj(dev)->cancelPicture();
2555}
2556
2557/**
2558 * Set the camera parameters. This returns BAD_VALUE if any parameter is
2559 * invalid or not supported.
2560 */
2561static int HAL_camera_device_set_parameters(struct camera_device *dev,
2562                                            const char *parms)
2563{
2564    ALOGV("%s", __func__);
2565    String8 str(parms);
2566    CameraParameters p(str);
2567    return obj(dev)->setParameters(p);
2568}
2569
2570/** Return the camera parameters. */
2571char *HAL_camera_device_get_parameters(struct camera_device *dev)
2572{
2573    ALOGV("%s", __func__);
2574    String8 str;
2575    CameraParameters parms = obj(dev)->getParameters();
2576    str = parms.flatten();
2577    return strdup(str.string());
2578}
2579
2580void HAL_camera_device_put_parameters(struct camera_device *dev, char *parms)
2581{
2582    ALOGV("%s", __func__);
2583    free(parms);
2584}
2585
2586/**
2587 * Send command to camera driver.
2588 */
2589static int HAL_camera_device_send_command(struct camera_device *dev,
2590                    int32_t cmd, int32_t arg1, int32_t arg2)
2591{
2592    ALOGV("%s", __func__);
2593    return obj(dev)->sendCommand(cmd, arg1, arg2);
2594}
2595
2596/**
2597 * Release the hardware resources owned by this object.  Note that this is
2598 * *not* done in the destructor.
2599 */
2600static void HAL_camera_device_release(struct camera_device *dev)
2601{
2602    ALOGV("%s", __func__);
2603    obj(dev)->release();
2604}
2605
2606/**
2607 * Dump state of the camera hardware
2608 */
2609static int HAL_camera_device_dump(struct camera_device *dev, int fd)
2610{
2611    ALOGV("%s", __func__);
2612    return obj(dev)->dump(fd);
2613}
2614
2615static int HAL_getNumberOfCameras()
2616{
2617    ALOGV("%s", __func__);
2618    return sizeof(sCameraInfo) / sizeof(sCameraInfo[0]);
2619}
2620
2621static int HAL_getCameraInfo(int cameraId, struct camera_info *cameraInfo)
2622{
2623    ALOGV("%s", __func__);
2624    memcpy(cameraInfo, &sCameraInfo[cameraId], sizeof(CameraInfo));
2625    return 0;
2626}
2627
2628#define SET_METHOD(m) m : HAL_camera_device_##m
2629
2630static camera_device_ops_t camera_device_ops = {
2631        SET_METHOD(set_preview_window),
2632        SET_METHOD(set_callbacks),
2633        SET_METHOD(enable_msg_type),
2634        SET_METHOD(disable_msg_type),
2635        SET_METHOD(msg_type_enabled),
2636        SET_METHOD(start_preview),
2637        SET_METHOD(stop_preview),
2638        SET_METHOD(preview_enabled),
2639        SET_METHOD(store_meta_data_in_buffers),
2640        SET_METHOD(start_recording),
2641        SET_METHOD(stop_recording),
2642        SET_METHOD(recording_enabled),
2643        SET_METHOD(release_recording_frame),
2644        SET_METHOD(auto_focus),
2645        SET_METHOD(cancel_auto_focus),
2646        SET_METHOD(take_picture),
2647        SET_METHOD(cancel_picture),
2648        SET_METHOD(set_parameters),
2649        SET_METHOD(get_parameters),
2650        SET_METHOD(put_parameters),
2651        SET_METHOD(send_command),
2652        SET_METHOD(release),
2653        SET_METHOD(dump),
2654};
2655
2656#undef SET_METHOD
2657
2658static int HAL_camera_device_open(const struct hw_module_t* module,
2659                                  const char *id,
2660                                  struct hw_device_t** device)
2661{
2662    ALOGV("%s", __func__);
2663
2664    int cameraId = atoi(id);
2665    if (cameraId < 0 || cameraId >= HAL_getNumberOfCameras()) {
2666        ALOGE("Invalid camera ID %s", id);
2667        return -EINVAL;
2668    }
2669
2670    if (g_cam_device) {
2671        if (obj(g_cam_device)->getCameraId() == cameraId) {
2672            ALOGV("returning existing camera ID %s", id);
2673            goto done;
2674        } else {
2675            ALOGE("Cannot open camera %d. camera %d is already running!",
2676                    cameraId, obj(g_cam_device)->getCameraId());
2677            return -ENOSYS;
2678        }
2679    }
2680
2681    g_cam_device = (camera_device_t *)malloc(sizeof(camera_device_t));
2682    if (!g_cam_device)
2683        return -ENOMEM;
2684
2685    g_cam_device->common.tag     = HARDWARE_DEVICE_TAG;
2686    g_cam_device->common.version = 1;
2687    g_cam_device->common.module  = const_cast<hw_module_t *>(module);
2688    g_cam_device->common.close   = HAL_camera_device_close;
2689
2690    g_cam_device->ops = &camera_device_ops;
2691
2692    ALOGI("%s: open camera %s", __func__, id);
2693
2694    g_cam_device->priv = new CameraHardwareSec(cameraId, g_cam_device);
2695
2696done:
2697    *device = (hw_device_t *)g_cam_device;
2698    ALOGI("%s: opened camera %s (%p)", __func__, id, *device);
2699    return 0;
2700}
2701
2702static hw_module_methods_t camera_module_methods = {
2703            open : HAL_camera_device_open
2704};
2705
2706extern "C" {
2707    struct camera_module HAL_MODULE_INFO_SYM = {
2708      common : {
2709          tag           : HARDWARE_MODULE_TAG,
2710          version_major : 1,
2711          version_minor : 0,
2712          id            : CAMERA_HARDWARE_MODULE_ID,
2713          name          : "Crespo camera HAL",
2714          author        : "Samsung Corporation",
2715          methods       : &camera_module_methods,
2716      },
2717      get_number_of_cameras : HAL_getNumberOfCameras,
2718      get_camera_info       : HAL_getCameraInfo
2719    };
2720}
2721
2722}; // namespace android
2723