1 /*
2 ** Copyright (c) 2012 The Linux Foundation. All rights reserved.
3 **
4 ** Not a Contribution, Apache license notifications and license are retained
5 ** for attribution purposes only.
6 **
7 ** Licensed under the Apache License, Version 2.0 (the "License");
8 ** you may not use this file except in compliance with the License.
9 ** You may obtain a copy of the License at
10 **
11 **     http://www.apache.org/licenses/LICENSE-2.0
12 **
13 ** Unless required by applicable law or agreed to in writing, software
14 ** distributed under the License is distributed on an "AS IS" BASIS,
15 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 ** See the License for the specific language governing permissions and
17 ** limitations under the License.
18 */
19 
20 /*#error uncomment this for compiler test!*/
21 
22 #define ALOG_NIDEBUG 0
23 
24 #define LOG_TAG "QCameraHWI"
25 #include <utils/Log.h>
26 #include <utils/threads.h>
27 #include <cutils/properties.h>
28 #include <fcntl.h>
29 #include <sys/mman.h>
30 
31 #include "QCameraHAL.h"
32 #include "QCameraHWI.h"
33 
34 /* QCameraHardwareInterface class implementation goes here*/
35 /* following code implement the contol logic of this class*/
36 
37 namespace android {
38 
39 extern void stream_cb_routine(mm_camera_super_buf_t *bufs,
40                        void *userdata);
41 
superbuf_cb_routine(mm_camera_super_buf_t * recvd_frame,void * userdata)42 void QCameraHardwareInterface::superbuf_cb_routine(mm_camera_super_buf_t *recvd_frame, void *userdata)
43 {
44     ALOGE("%s: E",__func__);
45     QCameraHardwareInterface *pme = (QCameraHardwareInterface *)userdata;
46     if(pme == NULL){
47        ALOGE("%s: pme is null", __func__);
48        return;
49     }
50 
51     mm_camera_super_buf_t* frame =
52            (mm_camera_super_buf_t *)malloc(sizeof(mm_camera_super_buf_t));
53     if (frame == NULL) {
54         ALOGE("%s: Error allocating memory to save received_frame structure.", __func__);
55         for (int i=0; i<recvd_frame->num_bufs; i++) {
56              if (recvd_frame->bufs[i] != NULL) {
57                  if (recvd_frame->bufs[i]->p_mobicat_info) {
58                     free(recvd_frame->bufs[i]->p_mobicat_info);
59                     recvd_frame->bufs[i]->p_mobicat_info = NULL;
60                  }
61                  pme->mCameraHandle->ops->qbuf(recvd_frame->camera_handle,
62                                                recvd_frame->ch_id,
63                                                recvd_frame->bufs[i]);
64                  pme->cache_ops((QCameraHalMemInfo_t *)(recvd_frame->bufs[i]->mem_info),
65                                 recvd_frame->bufs[i]->buffer,
66                                 ION_IOC_INV_CACHES);
67              }
68         }
69         return;
70     }
71     memcpy(frame, recvd_frame, sizeof(mm_camera_super_buf_t));
72     if(pme->mHdrInfo.hdr_on) {
73         pme->mHdrInfo.recvd_frame[pme->mHdrInfo.num_raw_received] = frame;
74 
75         ALOGE("hdl %d, ch_id %d, buf_num %d, bufidx0 %d, bufidx1 %d",
76               pme->mHdrInfo.recvd_frame[pme->mHdrInfo.num_raw_received]->
77               camera_handle, pme->mHdrInfo.recvd_frame[pme->mHdrInfo.
78               num_raw_received]->ch_id, pme->mHdrInfo.recvd_frame[pme->
79               mHdrInfo.num_raw_received]->num_bufs, pme->mHdrInfo.
80               recvd_frame[pme->mHdrInfo.num_raw_received]->bufs[0]->buf_idx,
81               pme->mHdrInfo.recvd_frame[pme->mHdrInfo.num_raw_received]->
82               bufs[1]->buf_idx);
83 
84         pme->mHdrInfo.num_raw_received++;
85 
86         ALOGE("%s Total %d Received %d frames, still need to receive %d frames",
87               __func__, pme->mHdrInfo.num_frame, pme->mHdrInfo.num_raw_received,
88               (pme->mHdrInfo.num_frame - pme->mHdrInfo.num_raw_received));
89 
90         if (pme->mHdrInfo.num_raw_received == pme->mHdrInfo.num_frame) {
91             ALOGE(" Received all %d YUV frames, Invoke HDR",
92                   pme->mHdrInfo.num_raw_received);
93             pme->doHdrProcessing();
94         }
95     } else {
96         /* enqueu to superbuf queue */
97         pme->mSuperBufQueue.enqueue(frame);
98 
99         /* notify dataNotify thread that new super buf is avail
100          * check if it's done with current JPEG notification and
101          * a new encoding job could be conducted*/
102         pme->mNotifyTh->sendCmd(CAMERA_CMD_TYPE_DO_NEXT_JOB, FALSE, FALSE);
103     }
104    ALOGE("%s: X", __func__);
105 
106 }
107 
snapshot_jpeg_cb(jpeg_job_status_t status,uint8_t thumbnailDroppedFlag,uint32_t client_hdl,uint32_t jobId,uint8_t * out_data,uint32_t data_size,void * userdata)108 void QCameraHardwareInterface::snapshot_jpeg_cb(jpeg_job_status_t status,
109                              uint8_t thumbnailDroppedFlag,
110                              uint32_t client_hdl,
111                              uint32_t jobId,
112                              uint8_t* out_data,
113                              uint32_t data_size,
114                              void *userdata)
115 {
116     ALOGE("%s: E", __func__);
117     camera_jpeg_encode_cookie_t *cookie =
118         (camera_jpeg_encode_cookie_t *)userdata;
119     if(cookie == NULL){
120        ALOGE("%s: userdata is null", __func__);
121        return;
122     }
123     QCameraHardwareInterface *pme = (QCameraHardwareInterface *)cookie->userdata;
124     if(pme == NULL){
125        ALOGE("%s: pme is null", __func__);
126        return;
127     }
128 
129     /* no use of src frames, return them to kernel */
130     for(int i = 0; i< cookie->src_frame->num_bufs; i++) {
131         if (cookie->src_frame->bufs[i]->p_mobicat_info) {
132             free(cookie->src_frame->bufs[i]->p_mobicat_info);
133             cookie->src_frame->bufs[i]->p_mobicat_info = NULL;
134         }
135         pme->mCameraHandle->ops->qbuf(cookie->src_frame->camera_handle,
136                                       cookie->src_frame->ch_id,
137                                       cookie->src_frame->bufs[i]);
138         pme->cache_ops((QCameraHalMemInfo_t *)(cookie->src_frame->bufs[i]->mem_info),
139                       cookie->src_frame->bufs[i]->buffer,
140                       ION_IOC_INV_CACHES);
141     }
142     free(cookie->src_frame);
143     cookie->src_frame = NULL;
144 
145     receiveCompleteJpegPicture(status,
146                                thumbnailDroppedFlag,
147                                client_hdl,
148                                jobId,
149                                out_data,
150                                data_size,
151                                pme);
152 
153     /* free sink frame */
154     free(out_data);
155     /* free cookie */
156     free(cookie);
157 
158     ALOGE("%s: X", __func__);
159 }
160 
releaseAppCBData(app_notify_cb_t * app_cb)161 void QCameraHardwareInterface::releaseAppCBData(app_notify_cb_t *app_cb)
162 {
163     if (app_cb->argm_data_cb.user_data != NULL) {
164         QCameraHalHeap_t *heap = (QCameraHalHeap_t *)app_cb->argm_data_cb.user_data;
165         releaseHeapMem(heap);
166     }
167 }
168 
releaseNofityData(void * data,void * user_data)169 void QCameraHardwareInterface::releaseNofityData(void *data, void *user_data)
170 {
171     QCameraHardwareInterface *pme = (QCameraHardwareInterface *)user_data;
172     if (NULL != pme) {
173         pme->releaseAppCBData((app_notify_cb_t *)data);
174     }
175 }
176 
releaseSuperBuf(mm_camera_super_buf_t * super_buf)177 void QCameraHardwareInterface::releaseSuperBuf(mm_camera_super_buf_t *super_buf)
178 {
179     if (NULL != super_buf) {
180         for(int i = 0; i< super_buf->num_bufs; i++) {
181             if (super_buf->bufs[i]->p_mobicat_info) {
182                 free(super_buf->bufs[i]->p_mobicat_info);
183                 super_buf->bufs[i]->p_mobicat_info = NULL;
184             }
185             mCameraHandle->ops->qbuf(super_buf->camera_handle,
186                                      super_buf->ch_id,
187                                      super_buf->bufs[i]);
188             cache_ops((QCameraHalMemInfo_t *)(super_buf->bufs[i]->mem_info),
189                       super_buf->bufs[i]->buffer,
190                       ION_IOC_INV_CACHES);
191         }
192     }
193 }
194 
releaseProcData(void * data,void * user_data)195 void QCameraHardwareInterface::releaseProcData(void *data, void *user_data)
196 {
197     QCameraHardwareInterface *pme = (QCameraHardwareInterface *)user_data;
198     if (NULL != pme) {
199         pme->releaseSuperBuf((mm_camera_super_buf_t *)data);
200     }
201 }
202 
dataNotifyRoutine(void * data)203 void *QCameraHardwareInterface::dataNotifyRoutine(void *data)
204 {
205     int running = 1;
206     int ret;
207     QCameraHardwareInterface *pme = (QCameraHardwareInterface *)data;
208     QCameraCmdThread *cmdThread = pme->mNotifyTh;
209     uint8_t isEncoding = FALSE;
210     uint8_t isActive = FALSE;
211     uint32_t numOfSnapshotExpected = 0;
212     uint32_t numOfSnapshotRcvd = 0;
213 
214     ALOGD("%s: E", __func__);
215     do {
216         do {
217             ret = sem_wait(&cmdThread->cmd_sem);
218             if (ret != 0 && errno != EINVAL) {
219                 ALOGE("%s: sem_wait error (%s)",
220                            __func__, strerror(errno));
221                 return NULL;
222             }
223         } while (ret != 0);
224 
225         /* we got notified about new cmd avail in cmd queue */
226         camera_cmd_type_t cmd = cmdThread->getCmd();
227         ALOGD("%s: get cmd %d", __func__, cmd);
228         switch (cmd) {
229         case CAMERA_CMD_TYPE_START_DATA_PROC:
230             isActive = TRUE;
231             /* init flag to FALSE */
232             isEncoding = FALSE;
233             numOfSnapshotExpected = pme->getNumOfSnapshots();
234             numOfSnapshotRcvd = 0;
235             break;
236         case CAMERA_CMD_TYPE_STOP_DATA_PROC:
237             /* flush jpeg data queue */
238             pme->mNotifyDataQueue.flush();
239 
240             isActive = FALSE;
241             /* set flag to FALSE */
242             isEncoding = FALSE;
243             numOfSnapshotExpected = 0;
244             numOfSnapshotRcvd = 0;
245             break;
246         case CAMERA_CMD_TYPE_DO_NEXT_JOB:
247             {
248                 if (TRUE == isActive) {
249                     /* first check if there is any pending jpeg notify */
250                     app_notify_cb_t *app_cb =
251                         (app_notify_cb_t *)pme->mNotifyDataQueue.dequeue();
252                     if (NULL != app_cb) {
253                         /* send notify to upper layer */
254                         if (app_cb->notifyCb) {
255                             ALOGE("%s: evt notify cb", __func__);
256                             app_cb->notifyCb(app_cb->argm_notify.msg_type,
257                                              app_cb->argm_notify.ext1,
258                                              app_cb->argm_notify.ext2,
259                                              app_cb->argm_notify.cookie);
260                         }
261                         if (app_cb->dataCb) {
262                             ALOGE("%s: data notify cb", __func__);
263                             app_cb->dataCb(app_cb->argm_data_cb.msg_type,
264                                            app_cb->argm_data_cb.data,
265                                            app_cb->argm_data_cb.index,
266                                            app_cb->argm_data_cb.metadata,
267                                            app_cb->argm_data_cb.cookie);
268                             if (CAMERA_MSG_COMPRESSED_IMAGE == app_cb->argm_data_cb.msg_type) {
269                                 numOfSnapshotRcvd++;
270                                 isEncoding = FALSE;
271                             }
272                         }
273 
274                         /* free app_cb */
275                         pme->releaseAppCBData(app_cb);
276                         free(app_cb);
277                     }
278 
279                     if ((FALSE == isEncoding) && !pme->mSuperBufQueue.is_empty()) {
280                         isEncoding = TRUE;
281                         /* notify processData thread to do next encoding job */
282                         pme->mDataProcTh->sendCmd(CAMERA_CMD_TYPE_DO_NEXT_JOB, FALSE, FALSE);
283                     }
284 
285                     if (numOfSnapshotExpected > 0 &&
286                         numOfSnapshotExpected == numOfSnapshotRcvd) {
287                         pme->cancelPictureInternal();
288                     }
289                 } else {
290                     /* do no op if not active */
291                     app_notify_cb_t *app_cb =
292                         (app_notify_cb_t *)pme->mNotifyDataQueue.dequeue();
293                     if (NULL != app_cb) {
294                         /* free app_cb */
295                         pme->releaseAppCBData(app_cb);
296                         free(app_cb);
297                     }
298                 }
299             }
300             break;
301         case CAMERA_CMD_TYPE_EXIT:
302             {
303                 /* flush jpeg data queue */
304                 pme->mNotifyDataQueue.flush();
305                 running = 0;
306             }
307             break;
308         default:
309             break;
310         }
311     } while (running);
312     ALOGD("%s: X", __func__);
313     return NULL;
314 }
315 
dataProcessRoutine(void * data)316 void *QCameraHardwareInterface::dataProcessRoutine(void *data)
317 {
318     int running = 1;
319     int ret;
320     uint8_t is_active = FALSE;
321     QCameraHardwareInterface *pme = (QCameraHardwareInterface *)data;
322     QCameraCmdThread *cmdThread = pme->mDataProcTh;
323     uint32_t current_jobId = 0;
324 
325     ALOGD("%s: E", __func__);
326     do {
327         do {
328             ret = sem_wait(&cmdThread->cmd_sem);
329             if (ret != 0 && errno != EINVAL) {
330                 ALOGE("%s: sem_wait error (%s)",
331                            __func__, strerror(errno));
332                 return NULL;
333             }
334         } while (ret != 0);
335 
336         /* we got notified about new cmd avail in cmd queue */
337         camera_cmd_type_t cmd = cmdThread->getCmd();
338         ALOGD("%s: get cmd %d", __func__, cmd);
339         switch (cmd) {
340         case CAMERA_CMD_TYPE_START_DATA_PROC:
341             is_active = TRUE;
342             break;
343         case CAMERA_CMD_TYPE_STOP_DATA_PROC:
344             {
345                 is_active = FALSE;
346                 /* abort current job if it's running */
347                 if (current_jobId > 0) {
348                     pme->mJpegHandle.abort_job(pme->mJpegClientHandle, current_jobId);
349                     current_jobId = 0;
350                 }
351                 /* flush superBufQueue */
352                 pme->mSuperBufQueue.flush();
353                 /* signal cmd is completed */
354                 sem_post(&cmdThread->sync_sem);
355             }
356             break;
357         case CAMERA_CMD_TYPE_DO_NEXT_JOB:
358             {
359                 ALOGD("%s: active is %d", __func__, is_active);
360                 if (is_active == TRUE) {
361                     /* first check if there is any pending jpeg notify */
362                     mm_camera_super_buf_t *super_buf =
363                         (mm_camera_super_buf_t *)pme->mSuperBufQueue.dequeue();
364                     if (NULL != super_buf) {
365                         //play shutter sound
366                         if(!pme->mShutterSoundPlayed){
367                             pme->notifyShutter(true);
368                         }
369                         pme->notifyShutter(false);
370                         pme->mShutterSoundPlayed = false;
371 
372                         if (pme->isRawSnapshot()) {
373                             receiveRawPicture(super_buf, pme);
374 
375                             /*free superbuf*/
376                             pme->releaseSuperBuf(super_buf);
377                             free(super_buf);
378                         } else{
379                             ret = pme->encodeData(super_buf, &current_jobId);
380 
381                              if (NO_ERROR != ret) {
382                                  pme->releaseSuperBuf(super_buf);
383                                  free(super_buf);
384                                  pme->sendDataNotify(CAMERA_MSG_COMPRESSED_IMAGE,
385                                                      NULL,
386                                                      0,
387                                                      NULL,
388                                                      NULL);
389                              }
390                         }
391                     }
392                 } else {
393                     /* not active, simply return buf and do no op */
394                     mm_camera_super_buf_t *super_buf =
395                         (mm_camera_super_buf_t *)pme->mSuperBufQueue.dequeue();
396                     if (NULL != super_buf) {
397                         pme->releaseSuperBuf(super_buf);
398                         free(super_buf);
399                     }
400                 }
401             }
402             break;
403         case CAMERA_CMD_TYPE_EXIT:
404             /* abort current job if it's running */
405             if (current_jobId > 0) {
406                 pme->mJpegHandle.abort_job(pme->mJpegClientHandle, current_jobId);
407                 current_jobId = 0;
408             }
409             /* flush super buf queue */
410             pme->mSuperBufQueue.flush();
411             running = 0;
412             break;
413         default:
414             break;
415         }
416     } while (running);
417     ALOGD("%s: X", __func__);
418     return NULL;
419 }
420 
notifyShutter(bool play_shutter_sound)421 void QCameraHardwareInterface::notifyShutter(bool play_shutter_sound){
422      ALOGV("%s : E", __func__);
423      if(mNotifyCb){
424          mNotifyCb(CAMERA_MSG_SHUTTER, 0, play_shutter_sound, mCallbackCookie);
425      }
426      ALOGV("%s : X", __func__);
427 }
428 
encodeData(mm_camera_super_buf_t * recvd_frame,uint32_t * jobId)429 status_t QCameraHardwareInterface::encodeData(mm_camera_super_buf_t* recvd_frame,
430                                               uint32_t *jobId)
431 {
432     ALOGV("%s : E", __func__);
433     int32_t ret = NO_ERROR;
434     mm_jpeg_job jpg_job;
435     mm_camera_buf_def_t *main_frame = NULL;
436     mm_camera_buf_def_t *thumb_frame = NULL;
437     src_image_buffer_info *main_buf_info = NULL;
438     src_image_buffer_info *thumb_buf_info = NULL;
439     QCameraHalMemInfo_t *main_mem_info = NULL;
440     QCameraHalMemInfo_t *thumb_mem_info = NULL;
441 
442     uint8_t src_img_num = recvd_frame->num_bufs;
443     int i;
444 
445     *jobId = 0;
446 
447     QCameraStream *main_stream = mStreams[MM_CAMERA_SNAPSHOT_MAIN];
448     for (i = 0; i < recvd_frame->num_bufs; i++) {
449         if (main_stream->mStreamId == recvd_frame->bufs[i]->stream_id) {
450             main_frame = recvd_frame->bufs[i];
451             break;
452         }
453     }
454     if(main_frame == NULL){
455        ALOGE("%s : Main frame is NULL", __func__);
456        return ret;
457     }
458     main_mem_info = &mSnapshotMemory.mem_info[main_frame->buf_idx];
459 
460     // send upperlayer callback for raw image (data or notify, not both)
461     app_notify_cb_t *app_cb = (app_notify_cb_t *)malloc(sizeof(app_notify_cb_t));
462     if (app_cb != NULL) {
463         memset(app_cb, 0, sizeof(app_notify_cb_t));
464 
465         if((mDataCb) && (mMsgEnabled & CAMERA_MSG_RAW_IMAGE)){
466             app_cb->dataCb = mDataCb;
467             app_cb->argm_data_cb.msg_type = CAMERA_MSG_RAW_IMAGE;
468             app_cb->argm_data_cb.cookie = mCallbackCookie;
469             app_cb->argm_data_cb.data = mSnapshotMemory.camera_memory[main_frame->buf_idx];
470             app_cb->argm_data_cb.index = 1;
471             app_cb->argm_data_cb.metadata = NULL;
472             app_cb->argm_data_cb.user_data = NULL;
473         }
474         if((mNotifyCb) && (mMsgEnabled & CAMERA_MSG_RAW_IMAGE_NOTIFY)){
475             app_cb->notifyCb = mNotifyCb;
476             app_cb->argm_notify.msg_type = CAMERA_MSG_RAW_IMAGE_NOTIFY;
477             app_cb->argm_notify.cookie = mCallbackCookie;
478             app_cb->argm_notify.ext1 = 0;
479             app_cb->argm_notify.ext2 = 0;
480         }
481 
482         /* enqueue jpeg_data into jpeg data queue */
483         if ((app_cb->dataCb || app_cb->notifyCb) && mNotifyDataQueue.enqueue((void *)app_cb)) {
484             mNotifyTh->sendCmd(CAMERA_CMD_TYPE_DO_NEXT_JOB, FALSE, FALSE);
485         } else {
486             free(app_cb);
487         }
488     } else {
489         ALOGE("%s: No mem for app_notify_cb_t", __func__);
490     }
491 
492     camera_jpeg_encode_cookie_t *cookie =
493         (camera_jpeg_encode_cookie_t *)malloc(sizeof(camera_jpeg_encode_cookie_t));
494     if (NULL == cookie) {
495         ALOGE("%s : no mem for cookie", __func__);
496         return -1;
497     }
498     cookie->src_frame = recvd_frame;
499     cookie->userdata = this;
500 
501     dumpFrameToFile(main_frame, HAL_DUMP_FRM_MAIN);
502 
503     QCameraStream *thumb_stream = NULL;
504     if (recvd_frame->num_bufs > 1) {
505         /* has thumbnail */
506         if(!isZSLMode()) {
507             thumb_stream = mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]; //mStreamSnapThumb;
508         } else {
509             thumb_stream = mStreams[MM_CAMERA_PREVIEW]; //mStreamDisplay;
510         }
511         for (i = 0; i < recvd_frame->num_bufs; i++) {
512             if (thumb_stream->mStreamId == recvd_frame->bufs[i]->stream_id) {
513                 thumb_frame = recvd_frame->bufs[i];
514                 break;
515             }
516         }
517         if (NULL != thumb_frame) {
518             if(thumb_stream == mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]) {
519                 thumb_mem_info = &mThumbnailMemory.mem_info[thumb_frame->buf_idx];
520             } else {
521                 if (isNoDisplayMode()) {
522                     thumb_mem_info = &mNoDispPreviewMemory.mem_info[thumb_frame->buf_idx];
523                 } else {
524                     thumb_mem_info = &mPreviewMemory.mem_info[thumb_frame->buf_idx];
525                 }
526             }
527         }
528     }  else if(mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]->mWidth &&
529                mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]->mHeight) {
530         /*thumbnail is required, not YUV thumbnail, borrow main image*/
531         thumb_stream = main_stream;
532         thumb_frame = main_frame;
533         src_img_num++;
534     }
535 
536     if (thumb_stream) {
537         dumpFrameToFile(thumb_frame, HAL_DUMP_FRM_THUMBNAIL);
538     }
539 
540     int jpeg_quality = getJpegQuality();
541     if (jpeg_quality <= 0) {
542         jpeg_quality = 85;
543     }
544 
545     memset(&jpg_job, 0, sizeof(mm_jpeg_job));
546     jpg_job.job_type = JPEG_JOB_TYPE_ENCODE;
547     jpg_job.encode_job.userdata = cookie;
548     jpg_job.encode_job.jpeg_cb = QCameraHardwareInterface::snapshot_jpeg_cb;
549     jpg_job.encode_job.encode_parm.exif_data = getExifData();
550     jpg_job.encode_job.encode_parm.exif_numEntries = getExifTableNumEntries();
551     jpg_job.encode_job.encode_parm.rotation = getJpegRotation();
552     ALOGV("%s: jpeg rotation is set to %d", __func__, jpg_job.encode_job.encode_parm.rotation);
553     jpg_job.encode_job.encode_parm.buf_info.src_imgs.src_img_num = src_img_num;
554     jpg_job.encode_job.encode_parm.buf_info.src_imgs.is_video_frame = FALSE;
555 
556     if (mMobiCatEnabled) {
557         main_frame->p_mobicat_info = (cam_exif_tags_t*)malloc(sizeof(cam_exif_tags_t));
558         if ((main_frame->p_mobicat_info != NULL) &&
559              mCameraHandle->ops->get_parm(mCameraHandle->camera_handle, MM_CAMERA_PARM_MOBICAT,
560                  main_frame->p_mobicat_info)
561                  == MM_CAMERA_OK) {
562                  ALOGV("%s:%d] Mobicat enabled %p %d", __func__, __LINE__,
563                        main_frame->p_mobicat_info->tags,
564                        main_frame->p_mobicat_info->data_len);
565         } else {
566               ALOGE("MM_CAMERA_PARM_MOBICAT get failed");
567         }
568     }
569     if (mMobiCatEnabled && main_frame->p_mobicat_info) {
570         jpg_job.encode_job.encode_parm.hasmobicat = 1;
571         jpg_job.encode_job.encode_parm.mobicat_data = (uint8_t *)main_frame->p_mobicat_info->tags;
572         jpg_job.encode_job.encode_parm.mobicat_data_length = main_frame->p_mobicat_info->data_len;
573      } else {
574         jpg_job.encode_job.encode_parm.hasmobicat = 0;
575      }
576 
577      // fill in the src_img info
578     //main img
579     main_buf_info = &jpg_job.encode_job.encode_parm.buf_info.src_imgs.src_img[JPEG_SRC_IMAGE_TYPE_MAIN];
580     main_buf_info->type = JPEG_SRC_IMAGE_TYPE_MAIN;
581     main_buf_info->color_format = getColorfmtFromImgFmt(main_stream->mFormat);
582     main_buf_info->quality = jpeg_quality;
583     main_buf_info->src_image[0].fd = main_frame->fd;
584     main_buf_info->src_image[0].buf_vaddr = (uint8_t*) main_frame->buffer;
585     main_buf_info->src_dim.width = main_stream->mWidth;
586     main_buf_info->src_dim.height = main_stream->mHeight;
587     main_buf_info->out_dim.width = mPictureWidth;
588     main_buf_info->out_dim.height = mPictureHeight;
589     memcpy(&main_buf_info->crop, &main_stream->mCrop, sizeof(image_crop_t));
590 
591     ALOGD("%s : Main Image :Input Dimension %d x %d output Dimension = %d X %d",
592           __func__, main_buf_info->src_dim.width, main_buf_info->src_dim.height,
593           main_buf_info->out_dim.width, main_buf_info->out_dim.height);
594     ALOGD("%s : Main Image :Crop %d x %d, offset = (%d, %d)",
595           __func__, main_buf_info->crop.width, main_buf_info->crop.height,
596           main_buf_info->crop.offset_x, main_buf_info->crop.offset_y);
597     main_buf_info->img_fmt = JPEG_SRC_IMAGE_FMT_YUV;
598     main_buf_info->num_bufs = 1;
599     main_buf_info->src_image[0].offset = main_stream->mFrameOffsetInfo;
600     ALOGD("%s : setting main image offset info, len = %d, offset = %d",
601           __func__, main_stream->mFrameOffsetInfo.mp[0].len,
602           main_stream->mFrameOffsetInfo.mp[0].offset);
603 
604     cache_ops(main_mem_info, main_frame->buffer, ION_IOC_CLEAN_INV_CACHES);
605 
606     if (thumb_frame && thumb_stream) {
607         /* fill in thumbnail src img encode param */
608         thumb_buf_info = &jpg_job.encode_job.encode_parm.buf_info.src_imgs.src_img[JPEG_SRC_IMAGE_TYPE_THUMB];
609         thumb_buf_info->type = JPEG_SRC_IMAGE_TYPE_THUMB;
610         thumb_buf_info->color_format = getColorfmtFromImgFmt(thumb_stream->mFormat);
611         //thumb_buf_info->quality = jpeg_quality;
612         thumb_buf_info->quality = 75; //hardcoded for now, will be calculated in encoder code later
613         thumb_buf_info->src_dim.width = thumb_stream->mWidth;
614         thumb_buf_info->src_dim.height = thumb_stream->mHeight;
615         thumb_buf_info->out_dim.width = thumbnailWidth;
616         thumb_buf_info->out_dim.height = thumbnailHeight;
617         memcpy(&thumb_buf_info->crop, &thumb_stream->mCrop, sizeof(image_crop_t));
618         ALOGD("%s : Thumanail :Input Dimension %d x %d output Dimension = %d X %d",
619           __func__, thumb_buf_info->src_dim.width, thumb_buf_info->src_dim.height,
620               thumb_buf_info->out_dim.width,thumb_buf_info->out_dim.height);
621         thumb_buf_info->img_fmt = JPEG_SRC_IMAGE_FMT_YUV;
622         thumb_buf_info->num_bufs = 1;
623         thumb_buf_info->src_image[0].fd = thumb_frame->fd;
624         thumb_buf_info->src_image[0].buf_vaddr = (uint8_t*) thumb_frame->buffer;
625         thumb_buf_info->src_image[0].offset = thumb_stream->mFrameOffsetInfo;
626         ALOGD("%s : setting thumb image offset info, len = %d, offset = %d",
627               __func__, thumb_stream->mFrameOffsetInfo.mp[0].len, thumb_stream->mFrameOffsetInfo.mp[0].offset);
628 
629         cache_ops(thumb_mem_info, thumb_frame->buffer, ION_IOC_CLEAN_INV_CACHES);
630     }
631 
632     uint32_t buf_len = main_stream->mFrameOffsetInfo.frame_len;
633     if (main_stream->m_flag_stream_on == FALSE) {
634         //if video-sized livesnapshot
635         jpg_job.encode_job.encode_parm.buf_info.src_imgs.is_video_frame = TRUE;
636 
637         //use the same output resolution as input
638         main_buf_info->out_dim.width = main_buf_info->src_dim.width;
639         main_buf_info->out_dim.height = main_buf_info->src_dim.height;
640 
641         if (thumb_buf_info->out_dim.width > thumb_buf_info->src_dim.width ||
642             thumb_buf_info->out_dim.height > thumb_buf_info->src_dim.height ) {
643             thumb_buf_info->out_dim.width = thumb_buf_info->src_dim.width;
644             thumb_buf_info->out_dim.height = thumb_buf_info->src_dim.height;
645         }
646 
647         uint32_t len = main_buf_info->out_dim.width * main_buf_info->out_dim.height * 1.5;
648         if (len > buf_len) {
649             buf_len = len;
650         }
651     }
652 
653     //fill in the sink img info
654     jpg_job.encode_job.encode_parm.buf_info.sink_img.buf_len = buf_len;
655     jpg_job.encode_job.encode_parm.buf_info.sink_img.buf_vaddr = (uint8_t *)malloc(buf_len);
656     if (NULL == jpg_job.encode_job.encode_parm.buf_info.sink_img.buf_vaddr) {
657         ALOGE("%s: ERROR: no memory for sink_img buf", __func__);
658         free(cookie);
659         cookie = NULL;
660         return -1;
661     }
662 
663     if (mJpegClientHandle > 0) {
664         ret = mJpegHandle.start_job(mJpegClientHandle, &jpg_job, jobId);
665     } else {
666         ALOGE("%s: Error: bug here, mJpegClientHandle is 0", __func__);
667         free(cookie);
668         cookie = NULL;
669         return -1;
670     }
671 
672     ALOGV("%s : X", __func__);
673     return ret;
674 
675 }
676 
sendDataNotify(int32_t msg_type,camera_memory_t * data,uint8_t index,camera_frame_metadata_t * metadata,QCameraHalHeap_t * heap)677 status_t QCameraHardwareInterface::sendDataNotify(int32_t msg_type,
678                                                  camera_memory_t *data,
679                                                  uint8_t index,
680                                                  camera_frame_metadata_t *metadata,
681                                                  QCameraHalHeap_t *heap)
682 {
683     app_notify_cb_t *app_cb = (app_notify_cb_t *)malloc(sizeof(app_notify_cb_t));
684     if (NULL == app_cb) {
685         ALOGE("%s: no mem for app_notify_cb_t", __func__);
686         return BAD_VALUE;
687     }
688     memset(app_cb, 0, sizeof(app_notify_cb_t));
689     app_cb->dataCb = mDataCb;
690     app_cb->argm_data_cb.msg_type = msg_type;
691     app_cb->argm_data_cb.cookie = mCallbackCookie;
692     app_cb->argm_data_cb.data = data;
693     app_cb->argm_data_cb.index = index;
694     app_cb->argm_data_cb.metadata = metadata;
695     app_cb->argm_data_cb.user_data = (void *)heap;
696 
697     /* enqueue jpeg_data into jpeg data queue */
698     if (mNotifyDataQueue.enqueue((void *)app_cb)) {
699         mNotifyTh->sendCmd(CAMERA_CMD_TYPE_DO_NEXT_JOB, FALSE, FALSE);
700     } else {
701         free(app_cb);
702         return BAD_VALUE;
703     }
704     return NO_ERROR;
705 }
706 
receiveRawPicture(mm_camera_super_buf_t * recvd_frame,QCameraHardwareInterface * pme)707 void QCameraHardwareInterface::receiveRawPicture(mm_camera_super_buf_t* recvd_frame,
708                                                  QCameraHardwareInterface *pme)
709 {
710      ALOGV("%s : E", __func__);
711      status_t rc = NO_ERROR;
712      int buf_index = 0;
713 
714      ALOGV("%s: is a raw snapshot", __func__);
715      /*RAW snapshot*/
716      if (recvd_frame->bufs[0] == NULL) {
717          ALOGE("%s: The main frame buffer is null", __func__);
718          return;
719      }
720 
721      if (pme->mDataCb && (pme->mMsgEnabled & CAMERA_MSG_COMPRESSED_IMAGE)) {
722          if (pme->initHeapMem(&pme->mRawMemory,
723                               1,
724                               recvd_frame->bufs[0]->frame_len,
725                               MSM_PMEM_RAW_MAINIMG,
726                               NULL,
727                               NULL) < 0) {
728              ALOGE("%s : initHeapMem for raw, ret = NO_MEMORY", __func__);
729              return;
730          }
731 
732          buf_index = recvd_frame->bufs[0]->buf_idx;
733          memcpy(pme->mRawMemory.camera_memory[0]->data,
734                 pme->mSnapshotMemory.camera_memory[buf_index]->data,
735                 recvd_frame->bufs[0]->frame_len);
736 
737          rc = pme->sendDataNotify(CAMERA_MSG_COMPRESSED_IMAGE,
738                                   pme->mRawMemory.camera_memory[0],
739                                   0,
740                                   NULL,
741                                   &pme->mRawMemory);
742          if (rc != NO_ERROR) {
743              pme->releaseHeapMem(&pme->mRawMemory);
744          }
745      }
746      ALOGV("%s : X", __func__);
747 }
748 
receiveCompleteJpegPicture(jpeg_job_status_t status,uint8_t thumbnailDroppedFlag,uint32_t client_hdl,uint32_t jobId,uint8_t * out_data,uint32_t data_size,QCameraHardwareInterface * pme)749 void QCameraHardwareInterface::receiveCompleteJpegPicture(jpeg_job_status_t status,
750                                                           uint8_t thumbnailDroppedFlag,
751                                                           uint32_t client_hdl,
752                                                           uint32_t jobId,
753                                                           uint8_t* out_data,
754                                                           uint32_t data_size,
755                                                           QCameraHardwareInterface *pme)
756 {
757     status_t rc = NO_ERROR;
758     ALOGE("%s: E", __func__);
759 
760     pme->deinitExifData();
761 
762     if(status == JPEG_JOB_STATUS_ERROR) {
763         ALOGE("Error event handled from jpeg");
764         if(pme->mDataCb && (pme->mMsgEnabled & CAMERA_MSG_COMPRESSED_IMAGE)){
765             pme->sendDataNotify(CAMERA_MSG_COMPRESSED_IMAGE,
766                                 NULL,
767                                 0,
768                                 NULL,
769                                 NULL);
770         }
771         return;
772     }
773 
774     if(thumbnailDroppedFlag) {
775         ALOGE("%s : Error in thumbnail encoding, no ops here", __func__);
776     }
777 
778     pme->dumpFrameToFile(out_data,
779                          data_size,
780                          (char *)"debug",
781                          (char *)"jpg",
782                          jobId);
783 
784     ALOGE("%s: jpeg_size=%d", __func__, data_size);
785 
786     if(pme->mDataCb && (pme->mMsgEnabled & CAMERA_MSG_COMPRESSED_IMAGE)){
787         if (pme->initHeapMem(&pme->mJpegMemory,
788                              1,
789                              data_size,
790                              MSM_PMEM_MAX,
791                              NULL,
792                              NULL) < 0) {
793             ALOGE("%s : initHeapMem for jpeg, ret = NO_MEMORY", __func__);
794             if(pme->mDataCb && (pme->mMsgEnabled & CAMERA_MSG_COMPRESSED_IMAGE)){
795                 pme->sendDataNotify(CAMERA_MSG_COMPRESSED_IMAGE,
796                                     NULL,
797                                     0,
798                                     NULL,
799                                     NULL);
800             }
801             return;
802         }
803 
804         memcpy(pme->mJpegMemory.camera_memory[0]->data, out_data, data_size);
805 
806         ALOGE("%s : Calling upperlayer callback to store JPEG image", __func__);
807         rc = pme->sendDataNotify(CAMERA_MSG_COMPRESSED_IMAGE,
808                                  pme->mJpegMemory.camera_memory[0],
809                                  0,
810                                  NULL,
811                                  &pme->mJpegMemory);
812         if (rc != NO_ERROR) {
813             pme->releaseHeapMem(&pme->mJpegMemory);
814         }
815     }
816 
817     ALOGE("%s: X", __func__);
818 }
819 
HAL_event_cb(uint32_t camera_handle,mm_camera_event_t * evt,void * user_data)820 static void HAL_event_cb(uint32_t camera_handle, mm_camera_event_t *evt, void *user_data)
821 {
822   QCameraHardwareInterface *obj = (QCameraHardwareInterface *)user_data;
823   if (obj) {
824     obj->processEvent(evt);
825   } else {
826     ALOGE("%s: NULL user_data", __func__);
827   }
828 }
829 
createRdi()830 int32_t QCameraHardwareInterface::createRdi()
831 {
832     int32_t ret = MM_CAMERA_OK;
833     ALOGV("%s : BEGIN",__func__);
834     mStreams[MM_CAMERA_RDI] = new QCameraStream_Rdi(mCameraHandle->camera_handle,
835                                                     mChannelId,
836                                                     640/*Width*/,
837                                                     480/*Height*/,
838                                                     CAMERA_BAYER_SBGGR10/*Format*/,
839                                                     PREVIEW_BUFFER_COUNT/*NumBuffers*/,
840                                                     mCameraHandle,
841                                                     MM_CAMERA_RDI,
842                                                     myMode,
843                                                     this);
844     if (!mStreams[MM_CAMERA_RDI]) {
845         ALOGE("%s: error - can't creat RDI stream!", __func__);
846         return BAD_VALUE;
847     }
848 
849     ALOGV("%s : END",__func__);
850     return ret;
851 }
852 
createRecord()853 int32_t QCameraHardwareInterface::createRecord()
854 {
855     int32_t ret = MM_CAMERA_OK;
856     ALOGV("%s : BEGIN",__func__);
857 
858     /*
859     * Creating Instance of record stream.
860     */
861     ALOGE("Mymode Record = %d",myMode);
862     mStreams[MM_CAMERA_VIDEO] = new QCameraStream_record(
863                                         mCameraHandle->camera_handle,
864                                         mChannelId,
865                                         640/*Width*/,
866                                         480/*Height*/,
867                                         0/*Format*/,
868                                         VIDEO_BUFFER_COUNT/*NumBuffers*/,
869                                         mCameraHandle,
870                                         MM_CAMERA_VIDEO,
871                                         myMode,
872                                         this);
873 
874     if (!mStreams[MM_CAMERA_VIDEO]) {
875         ALOGE("%s: error - can't creat record stream!", __func__);
876         return BAD_VALUE;
877     }
878 
879     /*Init Channel */
880     ALOGV("%s : END",__func__);
881     return ret;
882 }
createSnapshot()883 int32_t QCameraHardwareInterface::createSnapshot()
884 {
885     int32_t ret = MM_CAMERA_OK;
886     ALOGE("%s : BEGIN",__func__);
887     uint8_t NumBuffers = 1;
888 
889     if(mHdrMode) {
890         ALOGE("%s mHdrMode = %d, setting NumBuffers to 3", __func__, mHdrMode);
891         NumBuffers = 3;
892     }
893 
894     /*
895     * Creating Instance of Snapshot Main stream.
896     */
897     ALOGE("Mymode Snap = %d",myMode);
898     ALOGE("%s : before creating an instance of SnapshotMain, num buffers = %d", __func__, NumBuffers);
899     mStreams[MM_CAMERA_SNAPSHOT_MAIN] = new QCameraStream_SnapshotMain(
900                                                 mCameraHandle->camera_handle,
901                                                 mChannelId,
902                                                 640,
903                                                 480,
904                                                 CAMERA_YUV_420_NV21,
905                                                 NumBuffers,
906                                                 mCameraHandle,
907                                                 MM_CAMERA_SNAPSHOT_MAIN,
908                                                 myMode,
909                                                 this);
910     if (!mStreams[MM_CAMERA_SNAPSHOT_MAIN]) {
911         ALOGE("%s: error - can't creat snapshot stream!", __func__);
912         return BAD_VALUE;
913     }
914 
915     /*
916      * Creating Instance of Snapshot Thumb stream.
917     */
918     ALOGE("Mymode Snap = %d",myMode);
919     mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL] = new QCameraStream_SnapshotThumbnail(
920                                                     mCameraHandle->camera_handle,
921                                                     mChannelId,
922                                                     512,
923                                                     384,
924                                                     CAMERA_YUV_420_NV21,
925                                                     NumBuffers,
926                                                     mCameraHandle,
927                                                     MM_CAMERA_SNAPSHOT_THUMBNAIL,
928                                                     myMode,
929                                                     this);
930     if (!mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]) {
931         ALOGE("%s: error - can't creat snapshot stream!", __func__);
932         return BAD_VALUE;
933     }
934 
935     ALOGV("%s : END",__func__);
936     return ret;
937 }
createPreview()938 int32_t QCameraHardwareInterface::createPreview()
939 {
940     int32_t ret = MM_CAMERA_OK;
941     ALOGV("%s : BEGIN",__func__);
942 
943     ALOGE("Mymode Preview = %d",myMode);
944     mStreams[MM_CAMERA_PREVIEW] = new QCameraStream_preview(
945                                         mCameraHandle->camera_handle,
946                                         mChannelId,
947                                         640/*Width*/,
948                                         480/*Height*/,
949                                         0/*Format*/,
950                                         7/*NumBuffers*/,
951                                         mCameraHandle,
952                                         MM_CAMERA_PREVIEW,
953                                         myMode,
954                                         this);
955     if (!mStreams[MM_CAMERA_PREVIEW]) {
956         ALOGE("%s: error - can't creat preview stream!", __func__);
957         return BAD_VALUE;
958     }
959 
960     ALOGV("%s : END",__func__);
961     return ret;
962 }
963 
964 /*Mem Hooks*/
get_buffer_hook(uint32_t camera_handle,uint32_t ch_id,uint32_t stream_id,void * user_data,mm_camera_frame_len_offset * frame_offset_info,uint8_t num_bufs,uint8_t * initial_reg_flag,mm_camera_buf_def_t * bufs)965 int32_t get_buffer_hook(uint32_t camera_handle,
966                         uint32_t ch_id, uint32_t stream_id,
967                         void *user_data,
968                         mm_camera_frame_len_offset *frame_offset_info,
969                         uint8_t num_bufs,
970                         uint8_t *initial_reg_flag,
971                         mm_camera_buf_def_t  *bufs)
972 {
973     QCameraHardwareInterface *pme=(QCameraHardwareInterface *)user_data;
974     pme->getBuf(camera_handle, ch_id, stream_id,
975                 user_data, frame_offset_info,
976                 num_bufs,initial_reg_flag,
977                 bufs);
978 
979     return 0;
980 }
981 
put_buffer_hook(uint32_t camera_handle,uint32_t ch_id,uint32_t stream_id,void * user_data,uint8_t num_bufs,mm_camera_buf_def_t * bufs)982 int32_t put_buffer_hook(uint32_t camera_handle,
983                         uint32_t ch_id, uint32_t stream_id,
984                         void *user_data, uint8_t num_bufs,
985                         mm_camera_buf_def_t *bufs)
986 {
987     QCameraHardwareInterface *pme=(QCameraHardwareInterface *)user_data;
988     pme->putBuf(camera_handle, ch_id, stream_id,
989                 user_data, num_bufs, bufs);
990 
991     return 0;
992 }
993 
getBuf(uint32_t camera_handle,uint32_t ch_id,uint32_t stream_id,void * user_data,mm_camera_frame_len_offset * frame_offset_info,uint8_t num_bufs,uint8_t * initial_reg_flag,mm_camera_buf_def_t * bufs)994 int QCameraHardwareInterface::getBuf(uint32_t camera_handle,
995                         uint32_t ch_id, uint32_t stream_id,
996                         void *user_data,
997                         mm_camera_frame_len_offset *frame_offset_info,
998                         uint8_t num_bufs,
999                         uint8_t *initial_reg_flag,
1000                         mm_camera_buf_def_t *bufs)
1001 {
1002     int ret = BAD_VALUE;
1003     ALOGE("%s: len:%d, y_off:%d, cbcr:%d num buffers: %d planes:%d streamid:%d",
1004           __func__,
1005           frame_offset_info->frame_len,
1006           frame_offset_info->mp[0].len,
1007           frame_offset_info->mp[1].len,
1008           num_bufs,frame_offset_info->num_planes,
1009           stream_id);
1010 
1011     for (int i = 0; i < MM_CAMERA_IMG_MODE_MAX; i++) {
1012         if (mStreams[i] != NULL && mStreams[i]->mStreamId == stream_id) {
1013             ret = mStreams[i]->getBuf(frame_offset_info, num_bufs, initial_reg_flag, bufs);
1014             break;
1015         }
1016     }
1017 
1018     return ret;
1019 }
1020 
putBuf(uint32_t camera_handle,uint32_t ch_id,uint32_t stream_id,void * user_data,uint8_t num_bufs,mm_camera_buf_def_t * bufs)1021 int QCameraHardwareInterface::putBuf(uint32_t camera_handle,
1022                         uint32_t ch_id, uint32_t stream_id,
1023                         void *user_data, uint8_t num_bufs,
1024                         mm_camera_buf_def_t *bufs)
1025 {
1026     int ret = BAD_VALUE;
1027     ALOGE("%s:E",__func__);
1028     for (int i = 0; i < MM_CAMERA_IMG_MODE_MAX; i++) {
1029         if (mStreams[i] && (mStreams[i]->mStreamId == stream_id)) {
1030             ret = mStreams[i]->putBuf(num_bufs, bufs);
1031             break;
1032         }
1033     }
1034     return ret;
1035 }
1036 
1037 
1038 /* constructor */
1039 QCameraHardwareInterface::
QCameraHardwareInterface(int cameraId,int mode)1040 QCameraHardwareInterface(int cameraId, int mode)
1041                   : mCameraId(cameraId),
1042                     mParameters(),
1043                     mMsgEnabled(0),
1044                     mNotifyCb(0),
1045                     mDataCb(0),
1046                     mDataCbTimestamp(0),
1047                     mCallbackCookie(0),
1048                     mPreviewFormat(CAMERA_YUV_420_NV21),
1049                     mFps(0),
1050                     mDebugFps(0),
1051     mBrightness(0),
1052     mContrast(0),
1053     mBestShotMode(0),
1054     mEffects(0),
1055     mSkinToneEnhancement(0),
1056     mDenoiseValue(0),
1057     mHJR(0),
1058     mRotation(0),
1059     mMaxZoom(0),
1060     mCurrentZoom(0),
1061     mSupportedPictureSizesCount(15),
1062     mFaceDetectOn(0),
1063     mDumpFrmCnt(0), mDumpSkipCnt(0),
1064     mFocusMode(AF_MODE_MAX),
1065     mPictureSizeCount(15),
1066     mPreviewSizeCount(13),
1067     mVideoSizeCount(0),
1068     mAutoFocusRunning(false),
1069     mHasAutoFocusSupport(false),
1070     mInitialized(false),
1071     mDisEnabled(0),
1072     mIs3DModeOn(0),
1073     mSmoothZoomRunning(false),
1074     mParamStringInitialized(false),
1075     mZoomSupported(false),
1076     mFullLiveshotEnabled(true),
1077     mRecordingHint(0),
1078     mStartRecording(0),
1079     mReleasedRecordingFrame(false),
1080     mHdrMode(HDR_BRACKETING_OFF),
1081     mSnapshotFormat(0),
1082     mZslInterval(1),
1083     mRestartPreview(false),
1084     mStatsOn(0), mCurrentHisto(-1), mSendData(false), mStatHeap(NULL),
1085     mZslLookBackMode(0),
1086     mZslLookBackValue(0),
1087     mZslEmptyQueueFlag(FALSE),
1088     mPictureSizes(NULL),
1089     mVideoSizes(NULL),
1090     mCameraState(CAMERA_STATE_UNINITED),
1091     mExifTableNumEntries(0),
1092     mNoDisplayMode(0),
1093     rdiMode(STREAM_IMAGE),
1094     mSupportedFpsRanges(NULL),
1095     mSupportedFpsRangesCount(0),
1096     mPowerModule(0),
1097     mNeedToUnlockCaf(false),
1098     mSuperBufQueue(releaseProcData, this),
1099     mNotifyDataQueue(releaseNofityData, this)
1100 {
1101     ALOGI("QCameraHardwareInterface: E");
1102     int32_t result = MM_CAMERA_E_GENERAL;
1103     mMobiCatEnabled = false;
1104     char value[PROPERTY_VALUE_MAX];
1105 
1106     pthread_mutex_init(&mAsyncCmdMutex, NULL);
1107     pthread_cond_init(&mAsyncCmdWait, NULL);
1108 
1109     property_get("persist.debug.sf.showfps", value, "0");
1110     mDebugFps = atoi(value);
1111     mPreviewState = QCAMERA_HAL_PREVIEW_STOPPED;
1112     mPreviewWindow = NULL;
1113     property_get("camera.hal.fps", value, "0");
1114     mFps = atoi(value);
1115 
1116     ALOGI("Init mPreviewState = %d", mPreviewState);
1117 
1118     property_get("persist.camera.hal.multitouchaf", value, "0");
1119     mMultiTouch = atoi(value);
1120 
1121     property_get("persist.camera.full.liveshot", value, "1");
1122     mFullLiveshotEnabled = atoi(value);
1123 
1124     property_get("persist.camera.hal.dis", value, "0");
1125     mDisEnabled = atoi(value);
1126 
1127     memset(&mem_hooks,0,sizeof(mm_camear_mem_vtbl_t));
1128 
1129     mem_hooks.user_data=this;
1130     mem_hooks.get_buf=get_buffer_hook;
1131     mem_hooks.put_buf=put_buffer_hook;
1132 
1133     /* Open camera stack! */
1134     mCameraHandle=camera_open(mCameraId, &mem_hooks);
1135     ALOGV("Cam open returned %p",mCameraHandle);
1136     if(mCameraHandle == NULL) {
1137           ALOGE("startCamera: cam_ops_open failed: id = %d", mCameraId);
1138           return;
1139     }
1140     //sync API for mm-camera-interface
1141     mCameraHandle->ops->sync(mCameraHandle->camera_handle);
1142 
1143     mChannelId=mCameraHandle->ops->ch_acquire(mCameraHandle->camera_handle);
1144     if(mChannelId<=0)
1145     {
1146         mCameraHandle->ops->camera_close(mCameraHandle->camera_handle);
1147         return;
1148     }
1149     mm_camera_event_type_t evt;
1150     for (int i = 0; i < MM_CAMERA_EVT_TYPE_MAX; i++) {
1151         if(mCameraHandle->ops->is_event_supported(mCameraHandle->camera_handle,
1152                                  (mm_camera_event_type_t )i )){
1153             mCameraHandle->ops->register_event_notify(mCameraHandle->camera_handle,
1154 					   HAL_event_cb,
1155 					   (void *) this,
1156 					   (mm_camera_event_type_t) i);
1157         }
1158     }
1159 
1160     loadTables();
1161     /* Setup Picture Size and Preview size tables */
1162     setPictureSizeTable();
1163     ALOGD("%s: Picture table size: %d", __func__, mPictureSizeCount);
1164     ALOGD("%s: Picture table: ", __func__);
1165     for(unsigned int i=0; i < mPictureSizeCount;i++) {
1166       ALOGD(" %d  %d", mPictureSizes[i].width, mPictureSizes[i].height);
1167     }
1168 
1169     setPreviewSizeTable();
1170     ALOGD("%s: Preview table size: %d", __func__, mPreviewSizeCount);
1171     ALOGD("%s: Preview table: ", __func__);
1172     for(unsigned int i=0; i < mPreviewSizeCount;i++) {
1173       ALOGD(" %d  %d", mPreviewSizes[i].width, mPreviewSizes[i].height);
1174     }
1175 
1176     setVideoSizeTable();
1177     ALOGD("%s: Video table size: %d", __func__, mVideoSizeCount);
1178     ALOGD("%s: Video table: ", __func__);
1179     for(unsigned int i=0; i < mVideoSizeCount;i++) {
1180       ALOGD(" %d  %d", mVideoSizes[i].width, mVideoSizes[i].height);
1181     }
1182     memset(&mHistServer, 0, sizeof(mHistServer));
1183 
1184     /* set my mode - update myMode member variable due to difference in
1185      enum definition between upper and lower layer*/
1186     setMyMode(mode);
1187     initDefaultParameters();
1188 
1189     //Create Stream Objects
1190     memset(mStreams, 0, sizeof(mStreams));
1191 
1192     //Preview
1193     result = createPreview();
1194     if(result != MM_CAMERA_OK) {
1195         ALOGE("%s X: Failed to create Preview Object",__func__);
1196         return;
1197     }
1198 
1199     //Record
1200     result = createRecord();
1201     if(result != MM_CAMERA_OK) {
1202         ALOGE("%s X: Failed to create Record Object",__func__);
1203         return;
1204     }
1205     //Snapshot
1206     result = createSnapshot();
1207     if(result != MM_CAMERA_OK) {
1208         ALOGE("%s X: Failed to create Record Object",__func__);
1209         return;
1210     }
1211 
1212     memset(&mJpegHandle, 0, sizeof(mJpegHandle));
1213     mJpegClientHandle = jpeg_open(&mJpegHandle);
1214     if(!mJpegClientHandle) {
1215         ALOGE("%s : jpeg_open did not work", __func__);
1216         return;
1217     }
1218 
1219     /* launch jpeg notify thread and raw data proc thread */
1220     mNotifyTh = new QCameraCmdThread();
1221     if (mNotifyTh != NULL) {
1222         mNotifyTh->launch(dataNotifyRoutine, this);
1223     } else {
1224         ALOGE("%s : no mem for mNotifyTh", __func__);
1225         return;
1226     }
1227     mDataProcTh = new QCameraCmdThread();
1228     if (mDataProcTh != NULL) {
1229         mDataProcTh->launch(dataProcessRoutine, this);
1230     } else {
1231         ALOGE("%s : no mem for mDataProcTh", __func__);
1232         return;
1233     }
1234 
1235     memset(&mHdrInfo, 0, sizeof(snap_hdr_record_t));
1236     // initialize the mMetadata to set num_of_faces to 0
1237     memset(&mMetadata, 0, sizeof(mMetadata));
1238 
1239     if (hw_get_module(POWER_HARDWARE_MODULE_ID, (const hw_module_t **)&mPowerModule)) {
1240         ALOGE("%s module not found", POWER_HARDWARE_MODULE_ID);
1241     }
1242 
1243     mCameraState = CAMERA_STATE_READY;
1244     ALOGI("QCameraHardwareInterface: X");
1245 }
1246 
~QCameraHardwareInterface()1247 QCameraHardwareInterface::~QCameraHardwareInterface()
1248 {
1249     ALOGI("~QCameraHardwareInterface: E");
1250 
1251     if (CAMERA_STATE_READY == mCameraState) {
1252         stopPreview();
1253         mPreviewState = QCAMERA_HAL_PREVIEW_STOPPED;
1254     }
1255 
1256     if(mSupportedFpsRanges != NULL) {
1257         delete mSupportedFpsRanges;
1258         mSupportedFpsRanges = NULL;
1259     }
1260 
1261     freePictureTable();
1262     freeVideoSizeTable();
1263 
1264     deInitHistogramBuffers();
1265     if(mStatHeap != NULL) {
1266       mStatHeap.clear( );
1267       mStatHeap = NULL;
1268     }
1269 
1270     if(mMobiCatEnabled) {
1271       deInitMobicatBuffers();
1272     }
1273 
1274     for (int i = 0; i < MM_CAMERA_IMG_MODE_MAX; i++) {
1275         if (mStreams[i] != NULL) {
1276             delete mStreams[i];
1277             mStreams[i] = NULL;
1278         }
1279     }
1280 
1281     for (int i = 0; i < MAX_HDR_EXP_FRAME_NUM; i++) {
1282         if (mHdrInfo.recvd_frame[i] != NULL) {
1283             free(mHdrInfo.recvd_frame[i]);
1284             mHdrInfo.recvd_frame[i] = NULL;
1285         }
1286     }
1287 
1288     if (mNotifyTh != NULL) {
1289         mNotifyTh->exit();
1290         delete mNotifyTh;
1291         mNotifyTh = NULL;
1292     }
1293     if (mDataProcTh != NULL) {
1294         mDataProcTh->exit();
1295         delete mDataProcTh;
1296         mDataProcTh = NULL;
1297     }
1298     if(mJpegClientHandle > 0) {
1299         int rc = mJpegHandle.close(mJpegClientHandle);
1300         ALOGE("%s: Jpeg closed, rc = %d, mJpegClientHandle = %x",
1301               __func__, rc, mJpegClientHandle);
1302         mJpegClientHandle = 0;
1303         memset(&mJpegHandle, 0, sizeof(mJpegHandle));
1304     }
1305 
1306     if (NULL != mCameraHandle) {
1307         mCameraHandle->ops->ch_release(mCameraHandle->camera_handle,
1308                                        mChannelId);
1309 
1310         mCameraHandle->ops->camera_close(mCameraHandle->camera_handle);
1311     }
1312 
1313     pthread_mutex_destroy(&mAsyncCmdMutex);
1314     pthread_cond_destroy(&mAsyncCmdWait);
1315 
1316     ALOGE("~QCameraHardwareInterface: X");
1317 }
1318 
isCameraReady()1319 bool QCameraHardwareInterface::isCameraReady()
1320 {
1321     ALOGE("isCameraReady mCameraState %d", mCameraState);
1322     return (mCameraState == CAMERA_STATE_READY);
1323 }
1324 
release()1325 void QCameraHardwareInterface::release()
1326 {
1327     ALOGI("release: E");
1328     Mutex::Autolock l(&mLock);
1329 
1330     switch(mPreviewState) {
1331     case QCAMERA_HAL_PREVIEW_STOPPED:
1332         break;
1333     case QCAMERA_HAL_PREVIEW_START:
1334         break;
1335     case QCAMERA_HAL_PREVIEW_STARTED:
1336         stopPreviewInternal();
1337     break;
1338     case QCAMERA_HAL_RECORDING_STARTED:
1339         stopRecordingInternal();
1340         stopPreviewInternal();
1341         break;
1342     case QCAMERA_HAL_TAKE_PICTURE:
1343         cancelPictureInternal();
1344         break;
1345     default:
1346         break;
1347     }
1348     mPreviewState = QCAMERA_HAL_PREVIEW_STOPPED;
1349     ALOGI("release: X");
1350 }
1351 
setCallbacks(camera_notify_callback notify_cb,camera_data_callback data_cb,camera_data_timestamp_callback data_cb_timestamp,camera_request_memory get_memory,void * user)1352 void QCameraHardwareInterface::setCallbacks(
1353     camera_notify_callback notify_cb,
1354     camera_data_callback data_cb,
1355     camera_data_timestamp_callback data_cb_timestamp,
1356     camera_request_memory get_memory,
1357     void *user)
1358 {
1359     ALOGE("setCallbacks: E");
1360     Mutex::Autolock lock(mLock);
1361     mNotifyCb        = notify_cb;
1362     mDataCb          = data_cb;
1363     mDataCbTimestamp = data_cb_timestamp;
1364     mGetMemory       = get_memory;
1365     mCallbackCookie  = user;
1366     ALOGI("setCallbacks: X");
1367 }
1368 
enableMsgType(int32_t msgType)1369 void QCameraHardwareInterface::enableMsgType(int32_t msgType)
1370 {
1371     ALOGI("enableMsgType: E, msgType =0x%x", msgType);
1372     Mutex::Autolock lock(mLock);
1373     mMsgEnabled |= msgType;
1374     ALOGI("enableMsgType: X, msgType =0x%x, mMsgEnabled=0x%x", msgType, mMsgEnabled);
1375 }
1376 
disableMsgType(int32_t msgType)1377 void QCameraHardwareInterface::disableMsgType(int32_t msgType)
1378 {
1379     ALOGI("disableMsgType: E");
1380     Mutex::Autolock lock(mLock);
1381     mMsgEnabled &= ~msgType;
1382     ALOGI("disableMsgType: X, msgType =0x%x, mMsgEnabled=0x%x", msgType, mMsgEnabled);
1383 }
1384 
msgTypeEnabled(int32_t msgType)1385 int QCameraHardwareInterface::msgTypeEnabled(int32_t msgType)
1386 {
1387     ALOGI("msgTypeEnabled: E");
1388     Mutex::Autolock lock(mLock);
1389     return (mMsgEnabled & msgType);
1390     ALOGI("msgTypeEnabled: X");
1391 }
1392 
dump(int fd)1393 int QCameraHardwareInterface::dump(int fd)
1394 {
1395     ALOGE("%s: not supported yet", __func__);
1396     return -1;
1397 }
1398 
sendCommand(int32_t command,int32_t arg1,int32_t arg2)1399 status_t QCameraHardwareInterface::sendCommand(int32_t command, int32_t arg1,
1400                                          int32_t arg2)
1401 {
1402     ALOGI("sendCommand: E");
1403     status_t rc = NO_ERROR;
1404     Mutex::Autolock l(&mLock);
1405 
1406     switch (command) {
1407         case CAMERA_CMD_HISTOGRAM_ON:
1408             ALOGE("histogram set to on");
1409             rc = setHistogram(1);
1410             break;
1411         case CAMERA_CMD_HISTOGRAM_OFF:
1412             ALOGE("histogram set to off");
1413             rc = setHistogram(0);
1414             break;
1415         case CAMERA_CMD_HISTOGRAM_SEND_DATA:
1416             ALOGE("histogram send data");
1417             mSendData = true;
1418             rc = NO_ERROR;
1419             break;
1420         case CAMERA_CMD_START_FACE_DETECTION:
1421            if(supportsFaceDetection() == false){
1422                 ALOGE("Face detection support is not available");
1423                 return NO_ERROR;
1424            }
1425            setFaceDetection("on");
1426            return runFaceDetection();
1427         case CAMERA_CMD_STOP_FACE_DETECTION:
1428            if(supportsFaceDetection() == false){
1429                 ALOGE("Face detection support is not available");
1430                 return NO_ERROR;
1431            }
1432            setFaceDetection("off");
1433            return runFaceDetection();
1434         default:
1435             break;
1436     }
1437     ALOGI("sendCommand: X");
1438     return rc;
1439 }
1440 
setMyMode(int mode)1441 void QCameraHardwareInterface::setMyMode(int mode)
1442 {
1443     ALOGI("setMyMode: E");
1444     if (mode & CAMERA_SUPPORT_MODE_3D) {
1445         myMode = CAMERA_MODE_3D;
1446     }else {
1447         /* default mode is 2D */
1448         myMode = CAMERA_MODE_2D;
1449     }
1450 
1451     if (mode & CAMERA_SUPPORT_MODE_ZSL) {
1452         myMode = (camera_mode_t)(myMode |CAMERA_ZSL_MODE);
1453     }else {
1454        myMode = (camera_mode_t) (myMode | CAMERA_NONZSL_MODE);
1455     }
1456     ALOGI("setMyMode: Set mode to %d (passed mode: %d)", myMode, mode);
1457     ALOGI("setMyMode: X");
1458 }
1459 /* static factory function */
createInstance(int cameraId,int mode)1460 QCameraHardwareInterface *QCameraHardwareInterface::createInstance(int cameraId, int mode)
1461 {
1462     ALOGI("createInstance: E");
1463     QCameraHardwareInterface *cam = new QCameraHardwareInterface(cameraId, mode);
1464     if (cam ) {
1465       if (cam->mCameraState != CAMERA_STATE_READY) {
1466         ALOGE("createInstance: Failed");
1467         delete cam;
1468         cam = NULL;
1469       }
1470     }
1471 
1472     if (cam) {
1473       ALOGI("createInstance: X");
1474       return cam;
1475     } else {
1476       return NULL;
1477     }
1478 }
1479 /* external plug in function */
1480 extern "C" void *
QCameraHAL_openCameraHardware(int cameraId,int mode)1481 QCameraHAL_openCameraHardware(int  cameraId, int mode)
1482 {
1483     ALOGI("QCameraHAL_openCameraHardware: E");
1484     return (void *) QCameraHardwareInterface::createInstance(cameraId, mode);
1485 }
1486 
isPreviewRunning()1487 bool QCameraHardwareInterface::isPreviewRunning() {
1488     ALOGI("isPreviewRunning: E");
1489     bool ret = false;
1490 
1491     switch(mPreviewState) {
1492     case QCAMERA_HAL_PREVIEW_START:
1493     case QCAMERA_HAL_PREVIEW_STARTED:
1494     case QCAMERA_HAL_RECORDING_STARTED:
1495         ret = true;
1496         break;
1497     default:
1498         break;
1499     }
1500     ALOGI("isPreviewRunning: X");
1501     return ret;
1502 }
1503 
isRecordingRunning()1504 bool QCameraHardwareInterface::isRecordingRunning() {
1505     ALOGE("isRecordingRunning: E");
1506     bool ret = false;
1507     if(QCAMERA_HAL_RECORDING_STARTED == mPreviewState)
1508       ret = true;
1509     ALOGE("isRecordingRunning: X");
1510     return ret;
1511 }
1512 
isSnapshotRunning()1513 bool QCameraHardwareInterface::isSnapshotRunning() {
1514     ALOGE("isSnapshotRunning: E");
1515     bool ret = false;
1516     switch(mPreviewState) {
1517     case QCAMERA_HAL_PREVIEW_STOPPED:
1518     case QCAMERA_HAL_PREVIEW_START:
1519     case QCAMERA_HAL_PREVIEW_STARTED:
1520     case QCAMERA_HAL_RECORDING_STARTED:
1521     default:
1522         break;
1523     case QCAMERA_HAL_TAKE_PICTURE:
1524         ret = true;
1525         break;
1526     }
1527     ALOGI("isSnapshotRunning: X");
1528     return ret;
1529 }
1530 
isZSLMode()1531 bool QCameraHardwareInterface::isZSLMode() {
1532     return (myMode & CAMERA_ZSL_MODE);
1533 }
1534 
getHDRMode()1535 int QCameraHardwareInterface::getHDRMode() {
1536     ALOGE("%s, mHdrMode = %d", __func__, mHdrMode);
1537     return mHdrMode;
1538 }
1539 
debugShowPreviewFPS() const1540 void QCameraHardwareInterface::debugShowPreviewFPS() const
1541 {
1542     static int mFrameCount;
1543     static int mLastFrameCount = 0;
1544     static nsecs_t mLastFpsTime = 0;
1545     static float mFps = 0;
1546     mFrameCount++;
1547     nsecs_t now = systemTime();
1548     nsecs_t diff = now - mLastFpsTime;
1549     if (diff > ms2ns(250)) {
1550         mFps =  ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1551         ALOGE("Preview Frames Per Second: %.4f", mFps);
1552         mLastFpsTime = now;
1553         mLastFrameCount = mFrameCount;
1554     }
1555 }
1556 
1557 
1558 void QCameraHardwareInterface::
processPreviewChannelEvent(mm_camera_ch_event_type_t channelEvent,app_notify_cb_t * app_cb)1559 processPreviewChannelEvent(mm_camera_ch_event_type_t channelEvent, app_notify_cb_t *app_cb) {
1560     ALOGI("processPreviewChannelEvent: E");
1561     switch(channelEvent) {
1562         case MM_CAMERA_CH_EVT_STREAMING_ON:
1563             break;
1564         case MM_CAMERA_CH_EVT_STREAMING_OFF:
1565             break;
1566         case MM_CAMERA_CH_EVT_DATA_DELIVERY_DONE:
1567             break;
1568         default:
1569             break;
1570     }
1571     ALOGI("processPreviewChannelEvent: X");
1572     return;
1573 }
1574 
processRecordChannelEvent(mm_camera_ch_event_type_t channelEvent,app_notify_cb_t * app_cb)1575 void QCameraHardwareInterface::processRecordChannelEvent(
1576   mm_camera_ch_event_type_t channelEvent, app_notify_cb_t *app_cb) {
1577     ALOGI("processRecordChannelEvent: E");
1578     switch(channelEvent) {
1579         case MM_CAMERA_CH_EVT_STREAMING_ON:
1580             break;
1581         case MM_CAMERA_CH_EVT_STREAMING_OFF:
1582             break;
1583         case MM_CAMERA_CH_EVT_DATA_DELIVERY_DONE:
1584             break;
1585         default:
1586             break;
1587     }
1588     ALOGI("processRecordChannelEvent: X");
1589     return;
1590 }
1591 
1592 void QCameraHardwareInterface::
processSnapshotChannelEvent(mm_camera_ch_event_type_t channelEvent,app_notify_cb_t * app_cb)1593 processSnapshotChannelEvent(mm_camera_ch_event_type_t channelEvent, app_notify_cb_t *app_cb) {
1594     ALOGI("processSnapshotChannelEvent: E evt=%d state=%d", channelEvent,
1595       mCameraState);
1596     switch(channelEvent) {
1597         case MM_CAMERA_CH_EVT_STREAMING_ON:
1598             break;
1599         case MM_CAMERA_CH_EVT_STREAMING_OFF:
1600             break;
1601         case MM_CAMERA_CH_EVT_DATA_DELIVERY_DONE:
1602             break;
1603         case MM_CAMERA_CH_EVT_DATA_REQUEST_MORE:
1604             break;
1605         default:
1606             break;
1607     }
1608     ALOGI("processSnapshotChannelEvent: X");
1609     return;
1610 }
1611 
1612 void QCameraHardwareInterface::
processRdiChannelEvent(mm_camera_ch_event_type_t channelEvent,app_notify_cb_t * app_cb)1613 processRdiChannelEvent(mm_camera_ch_event_type_t channelEvent, app_notify_cb_t *app_cb) {
1614     ALOGI("processRdiChannelEvent: E evt=%d state=%d", channelEvent,
1615       mCameraState);
1616     switch(channelEvent) {
1617         case MM_CAMERA_CH_EVT_STREAMING_ON:
1618             break;
1619         case MM_CAMERA_CH_EVT_STREAMING_OFF:
1620             break;
1621         case MM_CAMERA_CH_EVT_DATA_DELIVERY_DONE:
1622             break;
1623         case MM_CAMERA_CH_EVT_DATA_REQUEST_MORE:
1624             break;
1625         default:
1626             break;
1627     }
1628     ALOGI("processRdiChannelEvent: X");
1629     return;
1630 }
1631 
processChannelEvent(mm_camera_ch_event_t * event,app_notify_cb_t * app_cb)1632 void QCameraHardwareInterface::processChannelEvent(
1633   mm_camera_ch_event_t *event, app_notify_cb_t *app_cb)
1634 {
1635     ALOGI("processChannelEvent: E");
1636     Mutex::Autolock lock(mLock);
1637     switch(event->ch) {
1638         case MM_CAMERA_PREVIEW:
1639             processPreviewChannelEvent(event->evt, app_cb);
1640             break;
1641         case MM_CAMERA_RDI:
1642             processRdiChannelEvent(event->evt, app_cb);
1643             break;
1644         case MM_CAMERA_VIDEO:
1645             processRecordChannelEvent(event->evt, app_cb);
1646             break;
1647         case MM_CAMERA_SNAPSHOT_MAIN:
1648         case MM_CAMERA_SNAPSHOT_THUMBNAIL:
1649             processSnapshotChannelEvent(event->evt, app_cb);
1650             break;
1651         default:
1652             break;
1653     }
1654     ALOGI("processChannelEvent: X");
1655     return;
1656 }
1657 
processCtrlEvent(mm_camera_ctrl_event_t * event,app_notify_cb_t * app_cb)1658 void QCameraHardwareInterface::processCtrlEvent(mm_camera_ctrl_event_t *event, app_notify_cb_t *app_cb)
1659 {
1660     ALOGI("processCtrlEvent: %d, E",event->evt);
1661     ALOGE("processCtrlEvent: MM_CAMERA_CTRL_EVT_HDR_DONE is %d", MM_CAMERA_CTRL_EVT_HDR_DONE);
1662     if(rdiMode == STREAM_RAW) {
1663         return;
1664     }
1665     Mutex::Autolock lock(mLock);
1666     switch(event->evt)
1667     {
1668         case MM_CAMERA_CTRL_EVT_ZOOM_DONE:
1669             ALOGI("processCtrlEvent: MM_CAMERA_CTRL_EVT_ZOOM_DONE");
1670             zoomEvent(&event->status, app_cb);
1671             break;
1672         case MM_CAMERA_CTRL_EVT_AUTO_FOCUS_DONE:
1673             ALOGI("processCtrlEvent: MM_CAMERA_CTRL_EVT_AUTO_FOCUS_DONE");
1674             autoFocusEvent(&event->status, app_cb);
1675             break;
1676         case MM_CAMERA_CTRL_EVT_PREP_SNAPSHOT:
1677             ALOGI("processCtrlEvent: MM_CAMERA_CTRL_EVT_ZOOM_DONE");
1678             break;
1679         case MM_CAMERA_CTRL_EVT_WDN_DONE:
1680             ALOGI("processCtrlEvent: MM_CAMERA_CTRL_EVT_WDN_DONE");
1681             wdenoiseEvent(event->status, (void *)(event->cookie));
1682             break;
1683         case MM_CAMERA_CTRL_EVT_HDR_DONE:
1684             ALOGI("processCtrlEvent:MM_CAMERA_CTRL_EVT_HDR_DONE");
1685             notifyHdrEvent(event->status, (void*)(event->cookie));
1686             break;
1687         case MM_CAMERA_CTRL_EVT_ERROR:
1688             ALOGI("processCtrlEvent: MM_CAMERA_CTRL_EVT_ERROR");
1689             app_cb->notifyCb  = mNotifyCb;
1690             app_cb->argm_notify.msg_type = CAMERA_MSG_ERROR;
1691             app_cb->argm_notify.ext1 = CAMERA_ERROR_UNKNOWN;
1692             app_cb->argm_notify.cookie =  mCallbackCookie;
1693             break;
1694         case MM_CAMERA_CTRL_EVT_SNAPSHOT_CONFIG_DONE:
1695             ALOGV("%s: MM_CAMERA_CTRL_EVT_SNAPSHOT_CONFIG_DONE", __func__);
1696             app_cb->notifyCb  = mNotifyCb;
1697             app_cb->argm_notify.msg_type = CAMERA_MSG_SHUTTER;
1698             app_cb->argm_notify.ext1 = 0;
1699             app_cb->argm_notify.ext2 = TRUE;
1700             app_cb->argm_notify.cookie =  mCallbackCookie;
1701             mShutterSoundPlayed = TRUE;
1702        default:
1703             break;
1704     }
1705     ALOGI("processCtrlEvent: X");
1706     return;
1707 }
1708 
processStatsEvent(mm_camera_stats_event_t * event,app_notify_cb_t * app_cb)1709 void  QCameraHardwareInterface::processStatsEvent(
1710   mm_camera_stats_event_t *event, app_notify_cb_t *app_cb)
1711 {
1712     ALOGI("processStatsEvent: E");
1713     if (!isPreviewRunning( )) {
1714         ALOGE("preview is not running");
1715         return;
1716     }
1717 
1718     switch (event->event_id) {
1719 
1720         case MM_CAMERA_STATS_EVT_HISTO:
1721         {
1722             ALOGE("HAL process Histo: mMsgEnabled=0x%x, mStatsOn=%d, mSendData=%d, mDataCb=%p ",
1723                   (mMsgEnabled & CAMERA_MSG_STATS_DATA), mStatsOn, mSendData, mDataCb);
1724             int msgEnabled = mMsgEnabled;
1725             /*get stats buffer based on index*/
1726             camera_preview_histogram_info* hist_info =
1727                 (camera_preview_histogram_info*) mHistServer.camera_memory[event->e.stats_histo.index]->data;
1728 
1729             if(mStatsOn == QCAMERA_PARM_ENABLE && mSendData &&
1730                             mDataCb && (msgEnabled & CAMERA_MSG_STATS_DATA) ) {
1731                 uint32_t *dest;
1732                 mSendData = false;
1733                 mCurrentHisto = (mCurrentHisto + 1) % 3;
1734                 // The first element of the array will contain the maximum hist value provided by driver.
1735                 *(uint32_t *)((unsigned int)(mStatsMapped[mCurrentHisto]->data)) = hist_info->max_value;
1736                 memcpy((uint32_t *)((unsigned int)mStatsMapped[mCurrentHisto]->data + sizeof(int32_t)),
1737                                                     (uint32_t *)hist_info->buffer,(sizeof(int32_t) * 256));
1738 
1739                 app_cb->dataCb  = mDataCb;
1740                 app_cb->argm_data_cb.msg_type = CAMERA_MSG_STATS_DATA;
1741                 app_cb->argm_data_cb.data = mStatsMapped[mCurrentHisto];
1742                 app_cb->argm_data_cb.index = 0;
1743                 app_cb->argm_data_cb.metadata = NULL;
1744                 app_cb->argm_data_cb.cookie =  mCallbackCookie;
1745             }
1746             break;
1747 
1748         }
1749         default:
1750         break;
1751     }
1752   ALOGV("receiveCameraStats X");
1753 }
1754 
processInfoEvent(mm_camera_info_event_t * event,app_notify_cb_t * app_cb)1755 void  QCameraHardwareInterface::processInfoEvent(
1756   mm_camera_info_event_t *event, app_notify_cb_t *app_cb) {
1757     ALOGI("processInfoEvent: %d, E",event->event_id);
1758     switch(event->event_id)
1759     {
1760         case MM_CAMERA_INFO_EVT_ROI:
1761             roiEvent(event->e.roi, app_cb);
1762             break;
1763         default:
1764             break;
1765     }
1766     ALOGI("processInfoEvent: X");
1767     return;
1768 }
1769 
processEvent(mm_camera_event_t * event)1770 void  QCameraHardwareInterface::processEvent(mm_camera_event_t *event)
1771 {
1772     app_notify_cb_t app_cb;
1773     ALOGE("processEvent: type :%d E",event->event_type);
1774     if(mPreviewState == QCAMERA_HAL_PREVIEW_STOPPED){
1775 	ALOGE("Stop recording issued. Return from process Event");
1776         return;
1777     }
1778     memset(&app_cb, 0, sizeof(app_notify_cb_t));
1779     switch(event->event_type)
1780     {
1781         case MM_CAMERA_EVT_TYPE_CH:
1782             processChannelEvent(&event->e.ch, &app_cb);
1783             break;
1784         case MM_CAMERA_EVT_TYPE_CTRL:
1785             processCtrlEvent(&event->e.ctrl, &app_cb);
1786             break;
1787         case MM_CAMERA_EVT_TYPE_STATS:
1788             processStatsEvent(&event->e.stats, &app_cb);
1789             break;
1790         case MM_CAMERA_EVT_TYPE_INFO:
1791             processInfoEvent(&event->e.info, &app_cb);
1792             break;
1793         default:
1794             break;
1795     }
1796     ALOGE(" App_cb Notify %p, datacb=%p", app_cb.notifyCb, app_cb.dataCb);
1797     if (app_cb.notifyCb) {
1798       app_cb.notifyCb(app_cb.argm_notify.msg_type,
1799         app_cb.argm_notify.ext1, app_cb.argm_notify.ext2,
1800         app_cb.argm_notify.cookie);
1801     }
1802     if (app_cb.dataCb) {
1803       app_cb.dataCb(app_cb.argm_data_cb.msg_type,
1804         app_cb.argm_data_cb.data, app_cb.argm_data_cb.index,
1805         app_cb.argm_data_cb.metadata, app_cb.argm_data_cb.cookie);
1806     }
1807     ALOGI("processEvent: X");
1808     return;
1809 }
1810 
startPreview()1811 status_t QCameraHardwareInterface::startPreview()
1812 {
1813     status_t retVal = NO_ERROR;
1814 
1815     ALOGE("%s: mPreviewState =%d", __func__, mPreviewState);
1816     Mutex::Autolock lock(mLock);
1817 
1818     switch(mPreviewState) {
1819     case QCAMERA_HAL_TAKE_PICTURE:
1820         /* cancel pic internally */
1821         cancelPictureInternal();
1822         mPreviewState = QCAMERA_HAL_PREVIEW_STOPPED;
1823         /* then continue with start preview */
1824     case QCAMERA_HAL_PREVIEW_STOPPED:
1825         mPreviewState = QCAMERA_HAL_PREVIEW_START;
1826         ALOGE("%s:  HAL::startPreview begin", __func__);
1827 
1828         if(QCAMERA_HAL_PREVIEW_START == mPreviewState &&
1829            (mPreviewWindow || isNoDisplayMode())) {
1830             ALOGE("%s:  start preview now", __func__);
1831             retVal = startPreview2();
1832             if(retVal == NO_ERROR)
1833                 mPreviewState = QCAMERA_HAL_PREVIEW_STARTED;
1834         } else {
1835             ALOGE("%s:  received startPreview, but preview window = null", __func__);
1836         }
1837         break;
1838     case QCAMERA_HAL_PREVIEW_START:
1839     case QCAMERA_HAL_PREVIEW_STARTED:
1840     break;
1841     case QCAMERA_HAL_RECORDING_STARTED:
1842         ALOGE("%s: cannot start preview in recording state", __func__);
1843         break;
1844     default:
1845         ALOGE("%s: unknow state %d received", __func__, mPreviewState);
1846         retVal = UNKNOWN_ERROR;
1847         break;
1848     }
1849     return retVal;
1850 }
1851 
startPreview2()1852 status_t QCameraHardwareInterface::startPreview2()
1853 {
1854     ALOGV("startPreview2: E");
1855     status_t ret = NO_ERROR;
1856 
1857     cam_ctrl_dimension_t dim;
1858     mm_camera_dimension_t maxDim;
1859     uint32_t stream[2];
1860     mm_camera_bundle_attr_t attr;
1861 
1862     if (mPreviewState == QCAMERA_HAL_PREVIEW_STARTED) { //isPreviewRunning()){
1863         ALOGE("%s:Preview already started  mPreviewState = %d!", __func__, mPreviewState);
1864         ALOGE("%s: X", __func__);
1865         return NO_ERROR;
1866     }
1867 
1868     /* config the parmeters and see if we need to re-init the stream*/
1869     ret = setDimension();
1870     if (MM_CAMERA_OK != ret) {
1871       ALOGE("%s: error - can't Set Dimensions!", __func__);
1872       return BAD_VALUE;
1873     }
1874 
1875     memset(&mHdrInfo, 0, sizeof(snap_hdr_record_t));
1876 
1877     if(isZSLMode()) {
1878         ALOGE("<DEBUGMODE>In ZSL mode");
1879         ALOGE("Setting OP MODE to MM_CAMERA_OP_MODE_VIDEO");
1880         mm_camera_op_mode_type_t op_mode=MM_CAMERA_OP_MODE_ZSL;
1881         ret = mCameraHandle->ops->set_parm(
1882                              mCameraHandle->camera_handle,
1883                              MM_CAMERA_PARM_OP_MODE,
1884                              &op_mode);
1885         ALOGE("OP Mode Set");
1886         /* Start preview streaming */
1887         /*now init all the buffers and send to steam object*/
1888         ret = mStreams[MM_CAMERA_PREVIEW]->initStream(FALSE, TRUE);
1889         if (MM_CAMERA_OK != ret){
1890             ALOGE("%s: error - can't init Preview channel!", __func__);
1891             return BAD_VALUE;
1892         }
1893 
1894         /* Start ZSL stream */
1895         ret = mStreams[MM_CAMERA_SNAPSHOT_MAIN]->initStream(TRUE, TRUE);
1896         if (MM_CAMERA_OK != ret){
1897             ALOGE("%s: error - can't init Snapshot stream!", __func__);
1898             mStreams[MM_CAMERA_PREVIEW]->deinitStream();
1899             return BAD_VALUE;
1900         }
1901 
1902         stream[0] = mStreams[MM_CAMERA_PREVIEW]->mStreamId;
1903         stream[1] = mStreams[MM_CAMERA_SNAPSHOT_MAIN]->mStreamId;
1904 
1905         attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_BURST;
1906         attr.burst_num = getNumOfSnapshots();
1907         attr.look_back = getZSLBackLookCount();
1908         attr.post_frame_skip = getZSLBurstInterval();
1909         attr.water_mark = getZSLQueueDepth();
1910         ALOGE("%s: burst_num=%d, look_back=%d, frame_skip=%d, water_mark=%d",
1911               __func__, attr.burst_num, attr.look_back,
1912               attr.post_frame_skip, attr.water_mark);
1913 
1914         ret = mCameraHandle->ops->init_stream_bundle(
1915                   mCameraHandle->camera_handle,
1916                   mChannelId,
1917                   superbuf_cb_routine,
1918                   this,
1919                   &attr,
1920                   2,
1921                   stream);
1922         if (MM_CAMERA_OK != ret){
1923             ALOGE("%s: error - can't init zsl preview streams!", __func__);
1924             mStreams[MM_CAMERA_PREVIEW]->deinitStream();
1925             mStreams[MM_CAMERA_SNAPSHOT_MAIN]->deinitStream();
1926             return BAD_VALUE;
1927         }
1928 
1929         ret = mStreams[MM_CAMERA_PREVIEW]->streamOn();
1930         if (MM_CAMERA_OK != ret){
1931             ALOGE("%s: error - can't start preview stream!", __func__);
1932             mStreams[MM_CAMERA_PREVIEW]->deinitStream();
1933             mStreams[MM_CAMERA_SNAPSHOT_MAIN]->deinitStream();
1934             return BAD_VALUE;
1935         }
1936 
1937         ret = mStreams[MM_CAMERA_SNAPSHOT_MAIN]->streamOn();
1938         if (MM_CAMERA_OK != ret){
1939             ALOGE("%s: error - can't start snapshot stream!", __func__);
1940             mStreams[MM_CAMERA_PREVIEW]->streamOff(0);
1941             mStreams[MM_CAMERA_PREVIEW]->deinitStream();
1942             mStreams[MM_CAMERA_SNAPSHOT_MAIN]->deinitStream();
1943             return BAD_VALUE;
1944         }
1945     }else{
1946         /*now init all the buffers and send to steam object*/
1947         ALOGE("Setting OP MODE to MM_CAMERA_OP_MODE_VIDEO");
1948         mm_camera_op_mode_type_t op_mode = MM_CAMERA_OP_MODE_VIDEO;
1949         ret = mCameraHandle->ops->set_parm(
1950                          mCameraHandle->camera_handle,
1951                          MM_CAMERA_PARM_OP_MODE,
1952                          &op_mode);
1953         ALOGE("OP Mode Set");
1954 
1955         if (MM_CAMERA_OK != ret){
1956             ALOGE("%s: X :set mode MM_CAMERA_OP_MODE_VIDEO err=%d\n", __func__, ret);
1957             return BAD_VALUE;
1958         }
1959         if(rdiMode == STREAM_RAW) {
1960             if(mStreams[MM_CAMERA_RDI] == NULL) {
1961                 createRdi();
1962             }
1963             mStreams[MM_CAMERA_RDI]->initStream(FALSE, TRUE);
1964             ret = mStreams[MM_CAMERA_RDI]->streamOn();
1965             return ret;
1966         }
1967         /*now init all the buffers and send to steam object*/
1968         ret = mStreams[MM_CAMERA_PREVIEW]->initStream(FALSE, TRUE);
1969         ALOGE("%s : called initStream from Preview and ret = %d", __func__, ret);
1970         if (MM_CAMERA_OK != ret){
1971             ALOGE("%s: error - can't init Preview channel!", __func__);
1972             return BAD_VALUE;
1973         }
1974         if(mRecordingHint == true) {
1975             ret = mStreams[MM_CAMERA_VIDEO]->initStream(FALSE, TRUE);
1976             if (MM_CAMERA_OK != ret){
1977                  ALOGE("%s: error - can't init Record channel!", __func__);
1978                  mStreams[MM_CAMERA_PREVIEW]->deinitStream();
1979                  return BAD_VALUE;
1980             }
1981             if (!canTakeFullSizeLiveshot()) {
1982                 // video-size live snapshot, config same as video
1983                 mStreams[MM_CAMERA_SNAPSHOT_MAIN]->mFormat = mStreams[MM_CAMERA_VIDEO]->mFormat;
1984                 mStreams[MM_CAMERA_SNAPSHOT_MAIN]->mWidth = mStreams[MM_CAMERA_VIDEO]->mWidth;
1985                 mStreams[MM_CAMERA_SNAPSHOT_MAIN]->mHeight = mStreams[MM_CAMERA_VIDEO]->mHeight;
1986                 ret = mStreams[MM_CAMERA_SNAPSHOT_MAIN]->initStream(FALSE, FALSE);
1987             } else {
1988                 ret = mStreams[MM_CAMERA_SNAPSHOT_MAIN]->initStream(FALSE, TRUE);
1989             }
1990             if (MM_CAMERA_OK != ret){
1991                  ALOGE("%s: error - can't init Snapshot Main!", __func__);
1992                  mStreams[MM_CAMERA_PREVIEW]->deinitStream();
1993                  mStreams[MM_CAMERA_VIDEO]->deinitStream();
1994                  return BAD_VALUE;
1995             }
1996 
1997         }
1998         ret = mStreams[MM_CAMERA_PREVIEW]->streamOn();
1999         if (MM_CAMERA_OK != ret){
2000             ALOGE("%s: error - can't start preview stream!", __func__);
2001             if (mRecordingHint == true) {
2002                 mStreams[MM_CAMERA_SNAPSHOT_MAIN]->deinitStream();
2003                 mStreams[MM_CAMERA_VIDEO]->deinitStream();
2004                 mStreams[MM_CAMERA_PREVIEW]->deinitStream();
2005             }
2006             return BAD_VALUE;
2007         }
2008     }
2009 
2010     ALOGV("startPreview: X");
2011     return ret;
2012 }
2013 
stopPreview()2014 void QCameraHardwareInterface::stopPreview()
2015 {
2016     ALOGI("%s: stopPreview: E", __func__);
2017     Mutex::Autolock lock(mLock);
2018     //mm_camera_util_profile("HAL: stopPreview(): E");
2019     mFaceDetectOn = false;
2020 
2021     // reset recording hint to the value passed from Apps
2022     const char * str = mParameters.get(QCameraParameters::KEY_RECORDING_HINT);
2023     if((str != NULL) && !strcmp(str, "true")){
2024         mRecordingHint = TRUE;
2025     } else {
2026         mRecordingHint = FALSE;
2027     }
2028 
2029     switch(mPreviewState) {
2030         case QCAMERA_HAL_PREVIEW_START:
2031             //mPreviewWindow = NULL;
2032             mPreviewState = QCAMERA_HAL_PREVIEW_STOPPED;
2033             break;
2034         case QCAMERA_HAL_PREVIEW_STARTED:
2035             cancelPictureInternal();
2036             stopPreviewInternal();
2037             mPreviewState = QCAMERA_HAL_PREVIEW_STOPPED;
2038             break;
2039         case QCAMERA_HAL_RECORDING_STARTED:
2040             cancelPictureInternal();
2041             stopRecordingInternal();
2042             stopPreviewInternal();
2043             mPreviewState = QCAMERA_HAL_PREVIEW_STOPPED;
2044             break;
2045         case QCAMERA_HAL_TAKE_PICTURE:
2046             cancelPictureInternal();
2047             mPreviewState = QCAMERA_HAL_PREVIEW_STOPPED;
2048             break;
2049         case QCAMERA_HAL_PREVIEW_STOPPED:
2050         default:
2051             break;
2052     }
2053     ALOGI("stopPreview: X, mPreviewState = %d", mPreviewState);
2054 }
2055 
stopPreviewInternal()2056 void QCameraHardwareInterface::stopPreviewInternal()
2057 {
2058     ALOGI("stopPreviewInternal: E");
2059     status_t ret = NO_ERROR;
2060 
2061     if(!mStreams[MM_CAMERA_PREVIEW]) {
2062         ALOGE("mStreamDisplay is null");
2063         return;
2064     }
2065 
2066     if(isZSLMode()) {
2067         mStreams[MM_CAMERA_PREVIEW]->streamOff(0);
2068         mStreams[MM_CAMERA_SNAPSHOT_MAIN]->streamOff(0);
2069         ret = mCameraHandle->ops->destroy_stream_bundle(mCameraHandle->camera_handle,mChannelId);
2070         if(ret != MM_CAMERA_OK) {
2071             ALOGE("%s : ZSL destroy_stream_bundle Error",__func__);
2072         }
2073     }else{
2074         if(rdiMode == STREAM_RAW) {
2075             mStreams[MM_CAMERA_RDI]->streamOff(0);
2076             mStreams[MM_CAMERA_RDI]->deinitStream();
2077             return;
2078         }
2079         mStreams[MM_CAMERA_PREVIEW]->streamOff(0);
2080     }
2081     if (mStreams[MM_CAMERA_VIDEO])
2082         mStreams[MM_CAMERA_VIDEO]->deinitStream();
2083     if (mStreams[MM_CAMERA_SNAPSHOT_MAIN])
2084         mStreams[MM_CAMERA_SNAPSHOT_MAIN]->deinitStream();
2085     mStreams[MM_CAMERA_PREVIEW]->deinitStream();
2086 
2087     ALOGI("stopPreviewInternal: X");
2088 }
2089 
previewEnabled()2090 int QCameraHardwareInterface::previewEnabled()
2091 {
2092     ALOGI("previewEnabled: E");
2093     Mutex::Autolock lock(mLock);
2094     ALOGE("%s: mPreviewState = %d", __func__, mPreviewState);
2095     switch(mPreviewState) {
2096     case QCAMERA_HAL_PREVIEW_START:
2097     case QCAMERA_HAL_PREVIEW_STARTED:
2098     case QCAMERA_HAL_RECORDING_STARTED:
2099         return true;
2100     default:
2101         return false;
2102     }
2103 }
2104 
startRecording()2105 status_t QCameraHardwareInterface::startRecording()
2106 {
2107     ALOGI("startRecording: E");
2108     status_t ret = NO_ERROR;
2109     Mutex::Autolock lock(mLock);
2110 
2111     switch(mPreviewState) {
2112     case QCAMERA_HAL_PREVIEW_STOPPED:
2113         ALOGE("%s: preview has not been started", __func__);
2114         ret = UNKNOWN_ERROR;
2115         break;
2116     case QCAMERA_HAL_PREVIEW_START:
2117         ALOGE("%s: no preview native window", __func__);
2118         ret = UNKNOWN_ERROR;
2119         break;
2120     case QCAMERA_HAL_PREVIEW_STARTED:
2121         if (mRecordingHint == FALSE) {
2122             ALOGE("%s: start recording when hint is false, stop preview first", __func__);
2123             stopPreviewInternal();
2124             mPreviewState = QCAMERA_HAL_PREVIEW_STOPPED;
2125 
2126             // Set recording hint to TRUE
2127             mRecordingHint = TRUE;
2128             setRecordingHintValue(mRecordingHint);
2129 
2130             // start preview again
2131             mPreviewState = QCAMERA_HAL_PREVIEW_START;
2132             if (startPreview2() == NO_ERROR)
2133                 mPreviewState = QCAMERA_HAL_PREVIEW_STARTED;
2134         }
2135         ret =  mStreams[MM_CAMERA_VIDEO]->streamOn();
2136         if (MM_CAMERA_OK != ret){
2137             ALOGE("%s: error - mStreamRecord->start!", __func__);
2138             ret = BAD_VALUE;
2139             break;
2140         }
2141         mPreviewState = QCAMERA_HAL_RECORDING_STARTED;
2142 
2143         if (mPowerModule) {
2144             if (mPowerModule->powerHint) {
2145                 mPowerModule->powerHint(mPowerModule, POWER_HINT_VIDEO_ENCODE, (void *)"state=1");
2146             }
2147         }
2148         break;
2149     case QCAMERA_HAL_RECORDING_STARTED:
2150         ALOGE("%s: ", __func__);
2151         break;
2152     case QCAMERA_HAL_TAKE_PICTURE:
2153     default:
2154        ret = BAD_VALUE;
2155        break;
2156     }
2157     ALOGI("startRecording: X");
2158     return ret;
2159 }
2160 
stopRecording()2161 void QCameraHardwareInterface::stopRecording()
2162 {
2163     ALOGI("stopRecording: E");
2164     Mutex::Autolock lock(mLock);
2165     switch(mPreviewState) {
2166     case QCAMERA_HAL_PREVIEW_STOPPED:
2167     case QCAMERA_HAL_PREVIEW_START:
2168     case QCAMERA_HAL_PREVIEW_STARTED:
2169         break;
2170     case QCAMERA_HAL_RECORDING_STARTED:
2171         cancelPictureInternal();
2172         stopRecordingInternal();
2173         mPreviewState = QCAMERA_HAL_PREVIEW_STARTED;
2174 
2175         if (mPowerModule) {
2176             if (mPowerModule->powerHint) {
2177 	            mPowerModule->powerHint(mPowerModule, POWER_HINT_VIDEO_ENCODE, (void *)"state=0");
2178             }
2179         }
2180         break;
2181     case QCAMERA_HAL_TAKE_PICTURE:
2182     default:
2183         break;
2184     }
2185     ALOGI("stopRecording: X");
2186 
2187 }
stopRecordingInternal()2188 void QCameraHardwareInterface::stopRecordingInternal()
2189 {
2190     ALOGI("stopRecordingInternal: E");
2191     status_t ret = NO_ERROR;
2192 
2193     if(!mStreams[MM_CAMERA_VIDEO]) {
2194         ALOGE("mStreamRecord is null");
2195         return;
2196     }
2197 
2198     /*
2199     * call QCameraStream_record::stop()
2200     * Unregister Callback, action stop
2201     */
2202     mStreams[MM_CAMERA_VIDEO]->streamOff(0);
2203     mPreviewState = QCAMERA_HAL_PREVIEW_STARTED;
2204     ALOGI("stopRecordingInternal: X");
2205     return;
2206 }
2207 
recordingEnabled()2208 int QCameraHardwareInterface::recordingEnabled()
2209 {
2210     int ret = 0;
2211     Mutex::Autolock lock(mLock);
2212     ALOGV("%s: E", __func__);
2213     switch(mPreviewState) {
2214     case QCAMERA_HAL_PREVIEW_STOPPED:
2215     case QCAMERA_HAL_PREVIEW_START:
2216     case QCAMERA_HAL_PREVIEW_STARTED:
2217         break;
2218     case QCAMERA_HAL_RECORDING_STARTED:
2219         ret = 1;
2220         break;
2221     case QCAMERA_HAL_TAKE_PICTURE:
2222     default:
2223         break;
2224     }
2225     ALOGV("%s: X, ret = %d", __func__, ret);
2226     return ret;   //isRecordingRunning();
2227 }
2228 
2229 /**
2230 * Release a record frame previously returned by CAMERA_MSG_VIDEO_FRAME.
2231 */
releaseRecordingFrame(const void * opaque)2232 void QCameraHardwareInterface::releaseRecordingFrame(const void *opaque)
2233 {
2234     ALOGV("%s : BEGIN",__func__);
2235     if(mStreams[MM_CAMERA_VIDEO] == NULL) {
2236         ALOGE("Record stream Not Initialized");
2237         return;
2238     }
2239     mStreams[MM_CAMERA_VIDEO]->releaseRecordingFrame(opaque);
2240     ALOGV("%s : END",__func__);
2241     return;
2242 }
2243 
autoFocusEvent(cam_ctrl_status_t * status,app_notify_cb_t * app_cb)2244 status_t QCameraHardwareInterface::autoFocusEvent(cam_ctrl_status_t *status, app_notify_cb_t *app_cb)
2245 {
2246     ALOGE("autoFocusEvent: E");
2247     int ret = NO_ERROR;
2248 /************************************************************
2249   BEGIN MUTEX CODE
2250 *************************************************************/
2251 
2252     ALOGE("%s:%d: Trying to acquire AF bit lock",__func__,__LINE__);
2253     mAutofocusLock.lock();
2254     ALOGE("%s:%d: Acquired AF bit lock",__func__,__LINE__);
2255 
2256     if(mAutoFocusRunning==false) {
2257       ALOGE("%s:AF not running, discarding stale event",__func__);
2258       mAutofocusLock.unlock();
2259       return ret;
2260     }
2261 
2262     /* If autofocus call has been made during CAF, CAF will be locked.
2263 	* We specifically need to call cancelAutoFocus to unlock CAF.
2264     * In that sense, AF is still running.*/
2265     isp3a_af_mode_t afMode = getAutoFocusMode(mParameters);
2266     if (afMode == AF_MODE_CAF) {
2267        mNeedToUnlockCaf = true;
2268     }
2269     mAutoFocusRunning = false;
2270     mAutofocusLock.unlock();
2271 
2272 /************************************************************
2273   END MUTEX CODE
2274 *************************************************************/
2275     if(status==NULL) {
2276       ALOGE("%s:NULL ptr received for status",__func__);
2277       return BAD_VALUE;
2278     }
2279 
2280     /* update focus distances after autofocus is done */
2281     if(updateFocusDistances() != NO_ERROR) {
2282        ALOGE("%s: updateFocusDistances failed for %d", __FUNCTION__, mFocusMode);
2283     }
2284 
2285     /*(Do?) we need to make sure that the call back is the
2286       last possible step in the execution flow since the same
2287       context might be used if a fail triggers another round
2288       of AF then the mAutoFocusRunning flag and other state
2289       variables' validity will be under question*/
2290 
2291     if (mNotifyCb && ( mMsgEnabled & CAMERA_MSG_FOCUS)){
2292       ALOGE("%s:Issuing callback to service",__func__);
2293 
2294       /* "Accepted" status is not appropriate it should be used for
2295         initial cmd, event reporting should only give use SUCCESS/FAIL
2296         */
2297 
2298       app_cb->notifyCb  = mNotifyCb;
2299       app_cb->argm_notify.msg_type = CAMERA_MSG_FOCUS;
2300       app_cb->argm_notify.ext2 = 0;
2301       app_cb->argm_notify.cookie =  mCallbackCookie;
2302 
2303       ALOGE("Auto foucs state =%d", *status);
2304       if(*status==CAM_CTRL_SUCCESS) {
2305         app_cb->argm_notify.ext1 = true;
2306       }
2307       else if(*status==CAM_CTRL_FAILED){
2308         app_cb->argm_notify.ext1 = false;
2309       }
2310       else{
2311         app_cb->notifyCb  = NULL;
2312         ALOGE("%s:Unknown AF status (%d) received",__func__,*status);
2313       }
2314 
2315     }/*(mNotifyCb && ( mMsgEnabled & CAMERA_MSG_FOCUS))*/
2316     else{
2317       ALOGE("%s:Call back not enabled",__func__);
2318     }
2319 
2320     ALOGE("autoFocusEvent: X");
2321     return ret;
2322 
2323 }
2324 
cancelPicture()2325 status_t QCameraHardwareInterface::cancelPicture()
2326 {
2327     ALOGI("cancelPicture: E, mPreviewState = %d", mPreviewState);
2328     status_t ret = MM_CAMERA_OK;
2329     Mutex::Autolock lock(mLock);
2330 
2331     switch(mPreviewState) {
2332         case QCAMERA_HAL_PREVIEW_STOPPED:
2333         case QCAMERA_HAL_PREVIEW_START:
2334         case QCAMERA_HAL_PREVIEW_STARTED:
2335         default:
2336             break;
2337         case QCAMERA_HAL_TAKE_PICTURE:
2338             ret = cancelPictureInternal();
2339             mPreviewState = QCAMERA_HAL_PREVIEW_STOPPED;
2340             break;
2341         case QCAMERA_HAL_RECORDING_STARTED:
2342             ret = cancelPictureInternal();
2343             break;
2344     }
2345     ALOGI("cancelPicture: X");
2346     return ret;
2347 }
2348 
cancelPictureInternal()2349 status_t QCameraHardwareInterface::cancelPictureInternal()
2350 {
2351     ALOGI("%s: E mPreviewState=%d", __func__ , mPreviewState);
2352     status_t ret = MM_CAMERA_OK;
2353 
2354     /* set rawdata proc thread and jpeg notify thread to inactive state */
2355     /* no need for notify thread as a sync call for stop cmd */
2356     mNotifyTh->sendCmd(CAMERA_CMD_TYPE_STOP_DATA_PROC, FALSE, TRUE);
2357     /* dataProc Thread need to process "stop" as sync call because abort jpeg job should be a sync call*/
2358     mDataProcTh->sendCmd(CAMERA_CMD_TYPE_STOP_DATA_PROC, TRUE, TRUE);
2359 
2360     if (isZSLMode()) {
2361         ret = mCameraHandle->ops->cancel_super_buf_request(mCameraHandle->camera_handle, mChannelId);
2362     } else {
2363         mStreams[MM_CAMERA_SNAPSHOT_MAIN]->streamOff(0);
2364         mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]->streamOff(0);
2365         ret = mCameraHandle->ops->destroy_stream_bundle(mCameraHandle->camera_handle, mChannelId);
2366         if(ret != MM_CAMERA_OK) {
2367             ALOGE("%s : destroy_stream_bundle Error",__func__);
2368         }
2369         if(mPreviewState != QCAMERA_HAL_RECORDING_STARTED) {
2370             mStreams[MM_CAMERA_SNAPSHOT_MAIN]->deinitStream();
2371             mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]->deinitStream();
2372         }
2373     }
2374     ALOGI("cancelPictureInternal: X");
2375     return ret;
2376 }
2377 
takePicture()2378 status_t  QCameraHardwareInterface::takePicture()
2379 {
2380     ALOGE("takePicture: E");
2381     status_t ret = MM_CAMERA_OK;
2382     uint32_t stream_info;
2383     uint32_t stream[2];
2384     mm_camera_bundle_attr_t attr;
2385     mm_camera_op_mode_type_t op_mode=MM_CAMERA_OP_MODE_CAPTURE;
2386     int num_streams = 0;
2387     Mutex::Autolock lock(mLock);
2388 
2389     /* set rawdata proc thread and jpeg notify thread to active state */
2390     mNotifyTh->sendCmd(CAMERA_CMD_TYPE_START_DATA_PROC, FALSE, FALSE);
2391     mDataProcTh->sendCmd(CAMERA_CMD_TYPE_START_DATA_PROC, FALSE, FALSE);
2392 
2393     switch(mPreviewState) {
2394     case QCAMERA_HAL_PREVIEW_STARTED:
2395         {
2396             if (isZSLMode()) {
2397                 ALOGE("ZSL: takePicture");
2398 
2399                 ret = mCameraHandle->ops->request_super_buf(
2400                           mCameraHandle->camera_handle,
2401                           mChannelId,
2402                           getNumOfSnapshots());
2403                 if (MM_CAMERA_OK != ret){
2404                     ALOGE("%s: error - can't start Snapshot streams!", __func__);
2405                     return BAD_VALUE;
2406                 }
2407                 return ret;
2408             }
2409 
2410             /*prepare snapshot, e.g LED*/
2411             takePicturePrepareHardware( );
2412 
2413             /* stop preview */
2414             stopPreviewInternal();
2415             /*Currently concurrent streaming is not enabled for snapshot
2416             So in snapshot mode, we turn of the RDI channel and configure backend
2417             for only pixel stream*/
2418 
2419             if (!isRawSnapshot()) {
2420                 op_mode=MM_CAMERA_OP_MODE_CAPTURE;
2421             } else {
2422                 ALOGV("%s: Raw snapshot so setting op mode to raw", __func__);
2423                 op_mode=MM_CAMERA_OP_MODE_RAW;
2424             }
2425             ret = mCameraHandle->ops->set_parm(mCameraHandle->camera_handle, MM_CAMERA_PARM_OP_MODE, &op_mode);
2426 
2427             if(MM_CAMERA_OK != ret) {
2428                 ALOGE("%s: X :set mode MM_CAMERA_OP_MODE_CAPTURE err=%d\n", __func__, ret);
2429                 return BAD_VALUE;
2430             }
2431 
2432             ret = setDimension();
2433             if (MM_CAMERA_OK != ret) {
2434                 ALOGE("%s: error - can't Set Dimensions!", __func__);
2435                 return BAD_VALUE;
2436             }
2437 
2438             //added to support hdr
2439             bool hdr;
2440             int frm_num = 1;
2441             int exp[MAX_HDR_EXP_FRAME_NUM];
2442             hdr = getHdrInfoAndSetExp(MAX_HDR_EXP_FRAME_NUM, &frm_num, exp);
2443             initHdrInfoForSnapshot(hdr, frm_num, exp); // - for hdr figure out equivalent of mStreamSnap
2444             memset(&attr, 0, sizeof(mm_camera_bundle_attr_t));
2445             attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_CONTINUOUS;
2446 
2447             num_streams = 0;
2448             mStreams[MM_CAMERA_SNAPSHOT_MAIN]->initStream(TRUE, TRUE);
2449             if (NO_ERROR!=ret) {
2450                 ALOGE("%s E: can't init native camera snapshot main ch\n",__func__);
2451                 return ret;
2452             }
2453             stream[num_streams++] = mStreams[MM_CAMERA_SNAPSHOT_MAIN]->mStreamId;
2454 
2455             if (!isRawSnapshot()) {
2456                 mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]->initStream(TRUE, TRUE);
2457                 if (NO_ERROR!=ret) {
2458                    ALOGE("%s E: can't init native camera snapshot thumb ch\n",__func__);
2459                    return ret;
2460                 }
2461                 stream[num_streams++] = mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]->mStreamId;
2462             }
2463             ret = mCameraHandle->ops->init_stream_bundle(
2464                       mCameraHandle->camera_handle,
2465                       mChannelId,
2466                       superbuf_cb_routine,
2467                       this,
2468                       &attr,
2469                       num_streams,
2470                       stream);
2471             if (MM_CAMERA_OK != ret){
2472                 ALOGE("%s: error - can't init Snapshot streams!", __func__);
2473                 return BAD_VALUE;
2474             }
2475             ret = mStreams[MM_CAMERA_SNAPSHOT_MAIN]->streamOn();
2476             if (MM_CAMERA_OK != ret){
2477                 ALOGE("%s: error - can't start Snapshot streams!", __func__);
2478                 mCameraHandle->ops->destroy_stream_bundle(
2479                    mCameraHandle->camera_handle,
2480                    mChannelId);
2481                 mStreams[MM_CAMERA_SNAPSHOT_MAIN]->deinitStream();
2482                 mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]->deinitStream();
2483                 return BAD_VALUE;
2484             }
2485             if (!isRawSnapshot()) {
2486                 ret = mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]->streamOn();
2487                 if (MM_CAMERA_OK != ret){
2488                     ALOGE("%s: error - can't start Thumbnail streams!", __func__);
2489                     mStreams[MM_CAMERA_SNAPSHOT_MAIN]->streamOff(0);
2490                     mCameraHandle->ops->destroy_stream_bundle(
2491                        mCameraHandle->camera_handle,
2492                        mChannelId);
2493                     mStreams[MM_CAMERA_SNAPSHOT_MAIN]->deinitStream();
2494                     mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]->deinitStream();
2495                     return BAD_VALUE;
2496                 }
2497             }
2498             mPreviewState = QCAMERA_HAL_TAKE_PICTURE;
2499         }
2500         break;
2501     case QCAMERA_HAL_TAKE_PICTURE:
2502           break;
2503     case QCAMERA_HAL_PREVIEW_STOPPED:
2504     case QCAMERA_HAL_PREVIEW_START:
2505         ret = UNKNOWN_ERROR;
2506         break;
2507     case QCAMERA_HAL_RECORDING_STARTED:
2508         stream[0] = mStreams[MM_CAMERA_SNAPSHOT_MAIN]->mStreamId;
2509         memset(&attr, 0, sizeof(mm_camera_bundle_attr_t));
2510         attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_CONTINUOUS;
2511         ret = mCameraHandle->ops->init_stream_bundle(
2512                   mCameraHandle->camera_handle,
2513                   mChannelId,
2514                   superbuf_cb_routine,
2515                   this,
2516                   &attr,
2517                   1,
2518                   stream);
2519         if (MM_CAMERA_OK != ret){
2520             ALOGE("%s: error - can't init Snapshot streams!", __func__);
2521             return BAD_VALUE;
2522         }
2523         ret = mStreams[MM_CAMERA_SNAPSHOT_MAIN]->streamOn();
2524         if (MM_CAMERA_OK != ret){
2525             ALOGE("%s: error - can't start Snapshot streams!", __func__);
2526             mCameraHandle->ops->destroy_stream_bundle(
2527                mCameraHandle->camera_handle,
2528                mChannelId);
2529             return BAD_VALUE;
2530         }
2531         break;
2532     default:
2533         ret = UNKNOWN_ERROR;
2534         break;
2535     }
2536     ALOGI("takePicture: X");
2537     return ret;
2538 }
2539 
autoFocus()2540 status_t QCameraHardwareInterface::autoFocus()
2541 {
2542     ALOGI("autoFocus: E");
2543     status_t ret = NO_ERROR;
2544 
2545     Mutex::Autolock lock(mLock);
2546     ALOGI("autoFocus: Got lock");
2547     bool status = true;
2548     isp3a_af_mode_t afMode = getAutoFocusMode(mParameters);
2549 
2550     if(mAutoFocusRunning==true){
2551       ALOGE("%s:AF already running should not have got this call",__func__);
2552       return NO_ERROR;
2553     }
2554 
2555     if (afMode == AF_MODE_MAX) {
2556       /* This should never happen. We cannot send a
2557        * callback notifying error from this place because
2558        * the CameraService has called this function after
2559        * acquiring the lock. So if we try to issue a callback
2560        * from this place, the callback will try to acquire
2561        * the same lock in CameraService and it will result
2562        * in deadlock. So, let the call go in to the lower
2563        * layer. The lower layer will anyway return error if
2564        * the autofocus is not supported or if the focus
2565        * value is invalid.
2566        * Just print out the error. */
2567       ALOGE("%s:Invalid AF mode (%d)", __func__, afMode);
2568     }
2569 
2570     ALOGI("%s:AF start (mode %d)", __func__, afMode);
2571     if(MM_CAMERA_OK != mCameraHandle->ops->start_focus(mCameraHandle->camera_handle,
2572                mChannelId,0,(uint32_t)&afMode)){
2573       ALOGE("%s: AF command failed err:%d error %s",
2574            __func__, errno, strerror(errno));
2575       return UNKNOWN_ERROR;
2576     }
2577 
2578     mAutoFocusRunning = true;
2579     ALOGE("autoFocus: X");
2580     return ret;
2581 }
2582 
cancelAutoFocus()2583 status_t QCameraHardwareInterface::cancelAutoFocus()
2584 {
2585     ALOGE("cancelAutoFocus: E");
2586     status_t ret = NO_ERROR;
2587     Mutex::Autolock lock(mLock);
2588 
2589 /**************************************************************
2590   BEGIN MUTEX CODE
2591 *************************************************************/
2592 
2593     mAutofocusLock.lock();
2594     if(mAutoFocusRunning || mNeedToUnlockCaf) {
2595 
2596       mAutoFocusRunning = false;
2597       mNeedToUnlockCaf = false;
2598       mAutofocusLock.unlock();
2599 
2600     }else/*(!mAutoFocusRunning)*/{
2601 
2602       mAutofocusLock.unlock();
2603       ALOGE("%s:Af not running",__func__);
2604       return NO_ERROR;
2605     }
2606 /**************************************************************
2607   END MUTEX CODE
2608 *************************************************************/
2609 
2610     if(MM_CAMERA_OK!= mCameraHandle->ops->abort_focus(mCameraHandle->camera_handle,
2611                mChannelId,0)){
2612         ALOGE("%s: AF command failed err:%d error %s",__func__, errno,strerror(errno));
2613     }
2614     ALOGE("cancelAutoFocus: X");
2615     return NO_ERROR;
2616 }
2617 
2618 /*==========================================================================
2619  * FUNCTION    - processprepareSnapshotEvent -
2620  *
2621  * DESCRIPTION:  Process the event of preparesnapshot done msg
2622                  unblock prepareSnapshotAndWait( )
2623  *=========================================================================*/
processprepareSnapshotEvent(cam_ctrl_status_t * status)2624 void QCameraHardwareInterface::processprepareSnapshotEvent(cam_ctrl_status_t *status)
2625 {
2626     ALOGI("processprepareSnapshotEvent: E");
2627     pthread_mutex_lock(&mAsyncCmdMutex);
2628     pthread_cond_signal(&mAsyncCmdWait);
2629     pthread_mutex_unlock(&mAsyncCmdMutex);
2630     ALOGI("processprepareSnapshotEvent: X");
2631 }
2632 
roiEvent(fd_roi_t roi,app_notify_cb_t * app_cb)2633 void QCameraHardwareInterface::roiEvent(fd_roi_t roi,app_notify_cb_t *app_cb)
2634 {
2635     ALOGE("roiEvent: E");
2636 
2637     if(mStreams[MM_CAMERA_PREVIEW]) {
2638         mStreams[MM_CAMERA_PREVIEW]->notifyROIEvent(roi);
2639     }
2640     ALOGE("roiEvent: X");
2641 }
2642 
2643 
handleZoomEventForSnapshot(void)2644 void QCameraHardwareInterface::handleZoomEventForSnapshot(void)
2645 {
2646     ALOGI("%s: E", __func__);
2647 
2648     if (mStreams[MM_CAMERA_SNAPSHOT_MAIN] != NULL) {
2649         mStreams[MM_CAMERA_SNAPSHOT_MAIN]->setCrop();
2650     }
2651     if (mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL] != NULL) {
2652         mStreams[MM_CAMERA_SNAPSHOT_THUMBNAIL]->setCrop();
2653     }
2654     ALOGI("%s: X", __func__);
2655 }
2656 
handleZoomEventForPreview(app_notify_cb_t * app_cb)2657 void QCameraHardwareInterface::handleZoomEventForPreview(app_notify_cb_t *app_cb)
2658 {
2659     ALOGI("%s: E", __func__);
2660 
2661     /*regular zooming or smooth zoom stopped*/
2662     if (mStreams[MM_CAMERA_PREVIEW] != NULL) {
2663         ALOGI("%s: Fetching crop info", __func__);
2664         mStreams[MM_CAMERA_PREVIEW]->setCrop();
2665         ALOGI("%s: Currrent zoom :%d",__func__, mCurrentZoom);
2666     }
2667 
2668     ALOGI("%s: X", __func__);
2669 }
2670 
zoomEvent(cam_ctrl_status_t * status,app_notify_cb_t * app_cb)2671 void QCameraHardwareInterface::zoomEvent(cam_ctrl_status_t *status, app_notify_cb_t *app_cb)
2672 {
2673     ALOGI("zoomEvent: state:%d E",mPreviewState);
2674     switch (mPreviewState) {
2675     case QCAMERA_HAL_PREVIEW_STOPPED:
2676         break;
2677     case QCAMERA_HAL_PREVIEW_START:
2678         break;
2679     case QCAMERA_HAL_PREVIEW_STARTED:
2680         handleZoomEventForPreview(app_cb);
2681         if (isZSLMode())
2682           handleZoomEventForSnapshot();
2683         break;
2684     case QCAMERA_HAL_RECORDING_STARTED:
2685         handleZoomEventForPreview(app_cb);
2686         if (mFullLiveshotEnabled)
2687             handleZoomEventForSnapshot();
2688         break;
2689     case QCAMERA_HAL_TAKE_PICTURE:
2690         if(isZSLMode())
2691             handleZoomEventForPreview(app_cb);
2692         handleZoomEventForSnapshot();
2693         break;
2694     default:
2695         break;
2696     }
2697     ALOGI("zoomEvent: X");
2698 }
2699 
dumpFrameToFile(const void * data,uint32_t size,char * name,char * ext,int index)2700 void QCameraHardwareInterface::dumpFrameToFile(const void * data, uint32_t size, char* name, char* ext, int index)
2701 {
2702     char buf[32];
2703     int file_fd;
2704     if ( data != NULL) {
2705         char * str;
2706         snprintf(buf, sizeof(buf), "/data/%s_%d.%s", name, index, ext);
2707         ALOGE("marvin, %s size =%d", buf, size);
2708         file_fd = open(buf, O_RDWR | O_CREAT, 0777);
2709         write(file_fd, data, size);
2710         close(file_fd);
2711     }
2712 }
2713 
dumpFrameToFile(mm_camera_buf_def_t * newFrame,HAL_cam_dump_frm_type_t frm_type)2714 void QCameraHardwareInterface::dumpFrameToFile(mm_camera_buf_def_t* newFrame,
2715   HAL_cam_dump_frm_type_t frm_type)
2716 {
2717   ALOGV("%s: E", __func__);
2718   int32_t enabled = 0;
2719   int frm_num;
2720   uint32_t  skip_mode;
2721   char value[PROPERTY_VALUE_MAX];
2722   char buf[32];
2723   int main_422 = 1;
2724   property_get("persist.camera.dumpimg", value, "0");
2725   enabled = atoi(value);
2726 
2727   ALOGV(" newFrame =%p, frm_type = %x, enabled=%x", newFrame, frm_type, enabled);
2728   if(enabled & HAL_DUMP_FRM_MASK_ALL) {
2729     if((enabled & frm_type) && newFrame) {
2730       frm_num = ((enabled & 0xffff0000) >> 16);
2731       if(frm_num == 0) frm_num = 10; /*default 10 frames*/
2732       if(frm_num > 256) frm_num = 256; /*256 buffers cycle around*/
2733       skip_mode = ((enabled & 0x0000ff00) >> 8);
2734       if(skip_mode == 0) skip_mode = 1; /*no -skip */
2735 
2736       if( mDumpSkipCnt % skip_mode == 0) {
2737         if (mDumpFrmCnt >= 0 && mDumpFrmCnt <= frm_num) {
2738           int w, h;
2739           int file_fd;
2740           switch (frm_type) {
2741           case  HAL_DUMP_FRM_PREVIEW:
2742             w = mDimension.display_width;
2743             h = mDimension.display_height;
2744             snprintf(buf, sizeof(buf), "/data/%dp_%dx%d_%d.yuv", mDumpFrmCnt, w, h, newFrame->frame_idx);
2745             file_fd = open(buf, O_RDWR | O_CREAT, 0777);
2746             break;
2747           case HAL_DUMP_FRM_VIDEO:
2748             w = mDimension.video_width;
2749             h = mDimension.video_height;
2750             snprintf(buf, sizeof(buf),"/data/%dv_%dx%d_%d.yuv", mDumpFrmCnt, w, h, newFrame->frame_idx);
2751             file_fd = open(buf, O_RDWR | O_CREAT, 0777);
2752             break;
2753           case HAL_DUMP_FRM_MAIN:
2754             w = mDimension.picture_width;
2755             h = mDimension.picture_height;
2756             snprintf(buf, sizeof(buf), "/data/%dm_%dx%d_%d.yuv", mDumpFrmCnt, w, h, newFrame->frame_idx);
2757             file_fd = open(buf, O_RDWR | O_CREAT, 0777);
2758             if (mDimension.main_img_format == CAMERA_YUV_422_NV16 ||
2759                 mDimension.main_img_format == CAMERA_YUV_422_NV61)
2760               main_422 = 2;
2761             break;
2762           case HAL_DUMP_FRM_THUMBNAIL:
2763             w = mDimension.ui_thumbnail_width;
2764             h = mDimension.ui_thumbnail_height;
2765             snprintf(buf, sizeof(buf),"/data/%dt_%dx%d_%d.yuv", mDumpFrmCnt, w, h, newFrame->frame_idx);
2766             file_fd = open(buf, O_RDWR | O_CREAT, 0777);
2767             break;
2768           case HAL_DUMP_FRM_RDI:
2769               w = mRdiWidth;
2770               h = mRdiHeight;
2771               snprintf(buf, sizeof(buf),"/data/%dr_%dx%d.raw", mDumpFrmCnt, w, h);
2772               file_fd = open(buf, O_RDWR | O_CREAT, 0777);
2773               break;
2774           default:
2775             w = h = 0;
2776             file_fd = -1;
2777             break;
2778           }
2779 
2780           if (file_fd < 0) {
2781             ALOGE("%s: cannot open file:type=%d\n", __func__, frm_type);
2782           } else {
2783             write(file_fd, (const void *)(newFrame->buffer), w * h);
2784             write(file_fd, (const void *)
2785               (newFrame->buffer), w * h / 2 * main_422);
2786             close(file_fd);
2787             ALOGE("dump %s", buf);
2788           }
2789         } else if(frm_num == 256){
2790           mDumpFrmCnt = 0;
2791         }
2792         mDumpFrmCnt++;
2793       }
2794       mDumpSkipCnt++;
2795     }
2796   }  else {
2797     mDumpFrmCnt = 0;
2798   }
2799   ALOGV("%s: X", __func__);
2800 }
2801 
setPreviewWindow(preview_stream_ops_t * window)2802 status_t QCameraHardwareInterface::setPreviewWindow(preview_stream_ops_t* window)
2803 {
2804     status_t retVal = NO_ERROR;
2805     ALOGE(" %s: E mPreviewState = %d, mStreamDisplay = %p",
2806           __func__, mPreviewState, mStreams[MM_CAMERA_PREVIEW]);
2807     if( window == NULL) {
2808         ALOGE("%s:Received Setting NULL preview window", __func__);
2809     }
2810     Mutex::Autolock lock(mLock);
2811     switch(mPreviewState) {
2812     case QCAMERA_HAL_PREVIEW_START:
2813         mPreviewWindow = window;
2814         if(mPreviewWindow) {
2815             /* we have valid surface now, start preview */
2816             ALOGE("%s:  calling startPreview2", __func__);
2817             retVal = startPreview2();
2818             if(retVal == NO_ERROR)
2819                 mPreviewState = QCAMERA_HAL_PREVIEW_STARTED;
2820             ALOGE("%s:  startPreview2 done, mPreviewState = %d", __func__, mPreviewState);
2821         } else
2822             ALOGE("%s: null window received, mPreviewState = %d", __func__, mPreviewState);
2823         break;
2824     case QCAMERA_HAL_PREVIEW_STARTED:
2825         /* new window comes */
2826         ALOGE("%s: bug, cannot handle new window in started state", __func__);
2827         //retVal = UNKNOWN_ERROR;
2828         break;
2829     case QCAMERA_HAL_PREVIEW_STOPPED:
2830     case QCAMERA_HAL_TAKE_PICTURE:
2831         mPreviewWindow = window;
2832         ALOGE("%s: mPreviewWindow = 0x%p, mStreamDisplay = 0x%p",
2833                                     __func__, mPreviewWindow, mStreams[MM_CAMERA_PREVIEW]);
2834         break;
2835     default:
2836         ALOGE("%s: bug, cannot handle new window in state %d", __func__, mPreviewState);
2837         retVal = UNKNOWN_ERROR;
2838         break;
2839     }
2840     ALOGE(" %s : X, mPreviewState = %d", __FUNCTION__, mPreviewState);
2841     return retVal;
2842 }
2843 
storeMetaDataInBuffers(int enable)2844 int QCameraHardwareInterface::storeMetaDataInBuffers(int enable)
2845 {
2846     /* this is a dummy func now. fix me later */
2847     mStoreMetaDataInFrame = enable;
2848     return 0;
2849 }
2850 
allocate_ion_memory(QCameraHalMemInfo_t * mem_info,int ion_type)2851 int QCameraHardwareInterface::allocate_ion_memory(QCameraHalMemInfo_t *mem_info, int ion_type)
2852 {
2853     int rc = 0;
2854     struct ion_handle_data handle_data;
2855     struct ion_allocation_data alloc;
2856     struct ion_fd_data ion_info_fd;
2857     int main_ion_fd = 0;
2858 
2859     main_ion_fd = open("/dev/ion", O_RDONLY);
2860     if (main_ion_fd <= 0) {
2861         ALOGE("Ion dev open failed %s\n", strerror(errno));
2862         goto ION_OPEN_FAILED;
2863     }
2864 
2865     memset(&alloc, 0, sizeof(alloc));
2866     alloc.len = mem_info->size;
2867     /* to make it page size aligned */
2868     alloc.len = (alloc.len + 4095) & (~4095);
2869     alloc.align = 4096;
2870     alloc.flags = ION_FLAG_CACHED;
2871     alloc.heap_mask = ion_type;
2872     rc = ioctl(main_ion_fd, ION_IOC_ALLOC, &alloc);
2873     if (rc < 0) {
2874         ALOGE("ION allocation failed\n");
2875         goto ION_ALLOC_FAILED;
2876     }
2877 
2878     memset(&ion_info_fd, 0, sizeof(ion_info_fd));
2879     ion_info_fd.handle = alloc.handle;
2880     rc = ioctl(main_ion_fd, ION_IOC_SHARE, &ion_info_fd);
2881     if (rc < 0) {
2882         ALOGE("ION map failed %s\n", strerror(errno));
2883         goto ION_MAP_FAILED;
2884     }
2885 
2886     mem_info->main_ion_fd = main_ion_fd;
2887     mem_info->fd = ion_info_fd.fd;
2888     mem_info->handle = ion_info_fd.handle;
2889     mem_info->size = alloc.len;
2890     return 0;
2891 
2892 ION_MAP_FAILED:
2893     memset(&handle_data, 0, sizeof(handle_data));
2894     handle_data.handle = ion_info_fd.handle;
2895     ioctl(main_ion_fd, ION_IOC_FREE, &handle_data);
2896 ION_ALLOC_FAILED:
2897     close(main_ion_fd);
2898 ION_OPEN_FAILED:
2899     return -1;
2900 }
2901 
deallocate_ion_memory(QCameraHalMemInfo_t * mem_info)2902 int QCameraHardwareInterface::deallocate_ion_memory(QCameraHalMemInfo_t *mem_info)
2903 {
2904   struct ion_handle_data handle_data;
2905   int rc = 0;
2906 
2907   if (mem_info->fd > 0) {
2908       close(mem_info->fd);
2909       mem_info->fd = 0;
2910   }
2911 
2912   if (mem_info->main_ion_fd > 0) {
2913       memset(&handle_data, 0, sizeof(handle_data));
2914       handle_data.handle = mem_info->handle;
2915       ioctl(mem_info->main_ion_fd, ION_IOC_FREE, &handle_data);
2916       close(mem_info->main_ion_fd);
2917       mem_info->main_ion_fd = 0;
2918   }
2919   return rc;
2920 }
2921 
initHeapMem(QCameraHalHeap_t * heap,int num_of_buf,uint32_t buf_len,int pmem_type,mm_camera_frame_len_offset * offset,mm_camera_buf_def_t * buf_def)2922 int QCameraHardwareInterface::initHeapMem( QCameraHalHeap_t *heap,
2923                                            int num_of_buf,
2924                                            uint32_t buf_len,
2925                                            int pmem_type,
2926                                            mm_camera_frame_len_offset* offset,
2927                                            mm_camera_buf_def_t *buf_def)
2928 {
2929     int rc = 0;
2930     int i;
2931     int path;
2932     ALOGE("Init Heap =%p. pmem_type =%d, num_of_buf=%d. buf_len=%d",
2933          heap,  pmem_type, num_of_buf, buf_len);
2934     if(num_of_buf > MM_CAMERA_MAX_NUM_FRAMES || heap == NULL ||
2935        mGetMemory == NULL ) {
2936         ALOGE("Init Heap error");
2937         rc = -1;
2938         return rc;
2939     }
2940 
2941     memset(heap, 0, sizeof(QCameraHalHeap_t));
2942     heap->buffer_count = num_of_buf;
2943     for(i = 0; i < num_of_buf; i++) {
2944         heap->mem_info[i].size = buf_len;
2945 #ifdef USE_ION
2946         if (isZSLMode()) {
2947             rc = allocate_ion_memory(&heap->mem_info[i],
2948                                      ((0x1 << CAMERA_ZSL_ION_HEAP_ID) | (0x1 << CAMERA_ZSL_ION_FALLBACK_HEAP_ID)));
2949         }
2950         else {
2951             rc = allocate_ion_memory(&heap->mem_info[i],
2952                                      ((0x1 << CAMERA_ION_HEAP_ID) | (0x1 << CAMERA_ION_FALLBACK_HEAP_ID)));
2953         }
2954 
2955         if (rc < 0) {
2956             ALOGE("%s: ION allocation failed\n", __func__);
2957             break;
2958         }
2959 #else
2960         if (pmem_type == MSM_PMEM_MAX){
2961             ALOGE("%s : USE_ION not defined, pmemtype == MSM_PMEM_MAX, so ret -1", __func__);
2962             rc = -1;
2963             break;
2964         }
2965         else {
2966             heap->mem_info[i].fd = open("/dev/pmem_adsp", O_RDWR|O_SYNC);
2967             if ( heap->mem_info[i].fd <= 0) {
2968                 ALOGE("Open fail: heap->fd[%d] =%d", i, heap->mem_info[i].fd);
2969                 rc = -1;
2970                 break;
2971             }
2972         }
2973 #endif
2974         heap->camera_memory[i] = mGetMemory(heap->mem_info[i].fd,
2975                                             heap->mem_info[i].size,
2976                                             1,
2977                                             (void *)this);
2978 
2979         if (heap->camera_memory[i] == NULL ) {
2980             ALOGE("Getmem fail %d: ", i);
2981             rc = -1;
2982             break;
2983         }
2984 
2985         if(buf_def != NULL && offset != NULL) {
2986             buf_def[i].fd = heap->mem_info[i].fd;
2987             buf_def[i].frame_len = heap->mem_info[i].size;
2988             buf_def[i].buffer = heap->camera_memory[i]->data;
2989             buf_def[i].mem_info = (void *)&heap->mem_info[i];
2990             buf_def[i].num_planes = offset->num_planes;
2991             /* Plane 0 needs to be set seperately. Set other planes
2992              * in a loop. */
2993             buf_def[i].planes[0].length = offset->mp[0].len;
2994             buf_def[i].planes[0].m.userptr = heap->mem_info[i].fd;
2995             buf_def[i].planes[0].data_offset = offset->mp[0].offset;
2996             buf_def[i].planes[0].reserved[0] = 0;
2997             for (int j = 1; j < buf_def[i].num_planes; j++) {
2998                  buf_def[i].planes[j].length = offset->mp[j].len;
2999                  buf_def[i].planes[j].m.userptr = heap->mem_info[i].fd;
3000                  buf_def[i].planes[j].data_offset = offset->mp[j].offset;
3001                  buf_def[i].planes[j].reserved[0] =
3002                      buf_def[i].planes[j-1].reserved[0] +
3003                      buf_def[i].planes[j-1].length;
3004             }
3005         }
3006 
3007         ALOGE("heap->fd[%d] =%d, camera_memory=%p", i,
3008               heap->mem_info[i].fd, heap->camera_memory[i]);
3009         heap->local_flag[i] = 1;
3010     }
3011     if( rc < 0) {
3012         releaseHeapMem(heap);
3013     }
3014     return rc;
3015 }
3016 
releaseHeapMem(QCameraHalHeap_t * heap)3017 int QCameraHardwareInterface::releaseHeapMem(QCameraHalHeap_t *heap)
3018 {
3019 	int rc = 0;
3020 	ALOGE("Release %p", heap);
3021 	if (heap != NULL) {
3022 		for (int i = 0; i < heap->buffer_count; i++) {
3023 			if(heap->camera_memory[i] != NULL) {
3024 				heap->camera_memory[i]->release( heap->camera_memory[i] );
3025 				heap->camera_memory[i] = NULL;
3026 			} else if (heap->mem_info[i].fd <= 0) {
3027 				ALOGE("impossible: camera_memory[%d] = %p, fd = %d",
3028 				i, heap->camera_memory[i], heap->mem_info[i].fd);
3029 			}
3030 
3031 #ifdef USE_ION
3032             deallocate_ion_memory(&heap->mem_info[i]);
3033 #endif
3034 		}
3035         memset(heap, 0, sizeof(QCameraHalHeap_t));
3036 	}
3037 	return rc;
3038 }
3039 
getPreviewFormatInfo()3040 preview_format_info_t  QCameraHardwareInterface::getPreviewFormatInfo( )
3041 {
3042   return mPreviewFormatInfo;
3043 }
3044 
wdenoiseEvent(cam_ctrl_status_t status,void * cookie)3045 void QCameraHardwareInterface::wdenoiseEvent(cam_ctrl_status_t status, void *cookie)
3046 {
3047 
3048 }
3049 
isWDenoiseEnabled()3050 bool QCameraHardwareInterface::isWDenoiseEnabled()
3051 {
3052     return mDenoiseValue;
3053 }
3054 
takePicturePrepareHardware()3055 void QCameraHardwareInterface::takePicturePrepareHardware()
3056 {
3057     ALOGV("%s: E", __func__);
3058 
3059     /* Prepare snapshot*/
3060     mCameraHandle->ops->prepare_snapshot(mCameraHandle->camera_handle,
3061                   mChannelId,
3062                   0);
3063     ALOGV("%s: X", __func__);
3064 }
3065 
isNoDisplayMode()3066 bool QCameraHardwareInterface::isNoDisplayMode()
3067 {
3068   return (mNoDisplayMode != 0);
3069 }
3070 
restartPreview()3071 void QCameraHardwareInterface::restartPreview()
3072 {
3073     if (QCAMERA_HAL_PREVIEW_STARTED == mPreviewState) {
3074         stopPreviewInternal();
3075         mPreviewState = QCAMERA_HAL_PREVIEW_STOPPED;
3076     }
3077     startPreview2();
3078     mPreviewState = QCAMERA_HAL_PREVIEW_STARTED;
3079 }
3080 
3081 // added to support hdr
getHdrInfoAndSetExp(int max_num_frm,int * num_frame,int * exp)3082 bool QCameraHardwareInterface::getHdrInfoAndSetExp(int max_num_frm, int *num_frame, int *exp)
3083 {
3084     bool rc = FALSE;
3085     ALOGE("%s, mHdrMode = %d, HDR_MODE = %d", __func__, mHdrMode, HDR_MODE);
3086     if (mHdrMode == HDR_MODE && num_frame != NULL && exp != NULL &&
3087         mRecordingHint != TRUE &&
3088         mPreviewState != QCAMERA_HAL_RECORDING_STARTED ) {
3089         ALOGE("%s : mHdrMode == HDR_MODE", __func__);
3090         int ret = 0;
3091         *num_frame = 1;
3092         exp_bracketing_t temp;
3093         memset(&temp, 0, sizeof(exp_bracketing_t));
3094         ret = mCameraHandle->ops->get_parm(mCameraHandle->camera_handle, MM_CAMERA_PARM_HDR, (void *)&temp );
3095         ALOGE("hdr - %s : ret = %d", __func__, ret);
3096         if (ret == NO_ERROR && max_num_frm > 0) {
3097             ALOGE("%s ret == NO_ERROR and max_num_frm = %d", __func__, max_num_frm);
3098             /*set as AE Bracketing mode*/
3099             temp.hdr_enable = FALSE;
3100             temp.mode = HDR_MODE;
3101             temp.total_hal_frames = temp.total_frames;
3102             ret = native_set_parms(MM_CAMERA_PARM_HDR,
3103                                    sizeof(exp_bracketing_t), (void *)&temp);
3104             ALOGE("%s, ret from set_parm = %d", __func__, ret);
3105             if (ret) {
3106                 char *val, *exp_value, *prev_value;
3107                 int i;
3108                 exp_value = (char *) temp.values;
3109                 i = 0;
3110                 val = strtok_r(exp_value,",", &prev_value);
3111                 while (val != NULL ){
3112                     exp[i++] = atoi(val);
3113                     if(i >= max_num_frm )
3114                         break;
3115                     val = strtok_r(NULL, ",", &prev_value);
3116                 }
3117                 *num_frame =temp.total_frames;
3118                 rc = TRUE;
3119             }
3120         } else {
3121             temp.total_frames = 1;
3122         }
3123         /* Application waits until this many snapshots before restarting preview */
3124         mParameters.set("num-snaps-per-shutter", 2);
3125     }
3126     ALOGE("%s, hdr - rc = %d, num_frame = %d", __func__, rc, *num_frame);
3127     return rc;
3128 }
3129 
initHistogramBuffers()3130 status_t QCameraHardwareInterface::initHistogramBuffers()
3131 {
3132     int page_size_minus_1 = getpagesize() - 1;
3133     int statSize = sizeof (camera_preview_histogram_info );
3134     int32_t mAlignedStatSize = ((statSize + page_size_minus_1)
3135                                 & (~page_size_minus_1));
3136     mm_camera_frame_map_type map_buf;
3137     ALOGI("%s E ", __func__);
3138 
3139     if (mHistServer.active) {
3140         ALOGI("%s Previous buffers not deallocated yet. ", __func__);
3141         return BAD_VALUE;
3142     }
3143 
3144     mStatSize = sizeof(uint32_t) * HISTOGRAM_STATS_SIZE;
3145     mCurrentHisto = -1;
3146 
3147     memset(&map_buf, 0, sizeof(map_buf));
3148     for(int cnt = 0; cnt < NUM_HISTOGRAM_BUFFERS; cnt++) {
3149         mStatsMapped[cnt] = mGetMemory(-1, mStatSize, 1, mCallbackCookie);
3150         if(mStatsMapped[cnt] == NULL) {
3151             ALOGE("Failed to get camera memory for stats heap index: %d", cnt);
3152             return NO_MEMORY;
3153         } else {
3154            ALOGI("Received following info for stats mapped data:%p,handle:%p,"
3155                  " size:%d,release:%p", mStatsMapped[cnt]->data,
3156                  mStatsMapped[cnt]->handle, mStatsMapped[cnt]->size,
3157                  mStatsMapped[cnt]->release);
3158         }
3159         mHistServer.mem_info[cnt].size = sizeof(camera_preview_histogram_info);
3160 #ifdef USE_ION
3161         int flag = (0x1 << ION_CP_MM_HEAP_ID | 0x1 << ION_IOMMU_HEAP_ID);
3162         if(allocate_ion_memory(&mHistServer.mem_info[cnt], flag) < 0) {
3163             ALOGE("%s ION alloc failed for %d\n", __func__, cnt);
3164             return NO_MEMORY;
3165         }
3166 #else
3167         mHistServer.mem_info[cnt].fd = open("/dev/pmem_adsp", O_RDWR|O_SYNC);
3168         if(mHistServer.mem_info[cnt].fd <= 0) {
3169             ALOGE("%s: no pmem for frame %d", __func__, cnt);
3170             return NO_INIT;
3171         }
3172 #endif
3173         mHistServer.camera_memory[cnt] = mGetMemory(mHistServer.mem_info[cnt].fd,
3174                                                     mHistServer.mem_info[cnt].size,
3175                                                     1,
3176                                                     mCallbackCookie);
3177         if(mHistServer.camera_memory[cnt] == NULL) {
3178             ALOGE("Failed to get camera memory for server side "
3179                   "histogram index: %d", cnt);
3180             return NO_MEMORY;
3181         } else {
3182             ALOGE("Received following info for server side histogram data:%p,"
3183                   " handle:%p, size:%d,release:%p",
3184                   mHistServer.camera_memory[cnt]->data,
3185                   mHistServer.camera_memory[cnt]->handle,
3186                   mHistServer.camera_memory[cnt]->size,
3187                   mHistServer.camera_memory[cnt]->release);
3188         }
3189         /*Register buffer at back-end*/
3190         map_buf.fd = mHistServer.mem_info[cnt].fd;
3191         map_buf.frame_idx = cnt;
3192         map_buf.size = mHistServer.mem_info[cnt].size;
3193         map_buf.ext_mode = 0;
3194         map_buf.is_hist = TRUE;
3195         mCameraHandle->ops->send_command(mCameraHandle->camera_handle,
3196                                          MM_CAMERA_CMD_TYPE_NATIVE,
3197                                          NATIVE_CMD_ID_SOCKET_MAP,
3198                                          sizeof(map_buf), &map_buf);
3199     }
3200     mHistServer.active = TRUE;
3201     ALOGI("%s X", __func__);
3202     return NO_ERROR;
3203 }
3204 
deInitHistogramBuffers()3205 status_t QCameraHardwareInterface::deInitHistogramBuffers()
3206 {
3207     mm_camera_frame_unmap_type unmap_buf;
3208     memset(&unmap_buf, 0, sizeof(unmap_buf));
3209 
3210     ALOGI("%s E", __func__);
3211 
3212     if (!mHistServer.active) {
3213         ALOGI("%s Histogram buffers not active. return. ", __func__);
3214         return NO_ERROR;
3215     }
3216 
3217     //release memory
3218     for(int i = 0; i < NUM_HISTOGRAM_BUFFERS; i++) {
3219         if(mStatsMapped[i] != NULL) {
3220             mStatsMapped[i]->release(mStatsMapped[i]);
3221         }
3222 
3223         unmap_buf.ext_mode = 0;
3224         unmap_buf.frame_idx = i;
3225         unmap_buf.is_hist = TRUE;
3226         mCameraHandle->ops->send_command(mCameraHandle->camera_handle,
3227                                          MM_CAMERA_CMD_TYPE_NATIVE,
3228                                          NATIVE_CMD_ID_SOCKET_UNMAP,
3229                                          sizeof(unmap_buf), &unmap_buf);
3230 
3231         if(mHistServer.camera_memory[i] != NULL) {
3232             mHistServer.camera_memory[i]->release(mHistServer.camera_memory[i]);
3233         }
3234 #ifdef USE_ION
3235         deallocate_ion_memory(&mHistServer.mem_info[i]);
3236 #endif
3237     }
3238     mHistServer.active = FALSE;
3239     ALOGI("%s X", __func__);
3240     return NO_ERROR;
3241 }
3242 
getColorfmtFromImgFmt(uint32_t img_fmt)3243 mm_jpeg_color_format QCameraHardwareInterface::getColorfmtFromImgFmt(uint32_t img_fmt)
3244 {
3245     switch (img_fmt) {
3246     case CAMERA_YUV_420_NV21:
3247         return MM_JPEG_COLOR_FORMAT_YCRCBLP_H2V2;
3248     case CAMERA_YUV_420_NV21_ADRENO:
3249         return MM_JPEG_COLOR_FORMAT_YCRCBLP_H2V2;
3250     case CAMERA_YUV_420_NV12:
3251         return MM_JPEG_COLOR_FORMAT_YCBCRLP_H2V2;
3252     case CAMERA_YUV_420_YV12:
3253         return MM_JPEG_COLOR_FORMAT_YCBCRLP_H2V2;
3254     case CAMERA_YUV_422_NV61:
3255         return MM_JPEG_COLOR_FORMAT_YCRCBLP_H2V1;
3256     case CAMERA_YUV_422_NV16:
3257         return MM_JPEG_COLOR_FORMAT_YCBCRLP_H2V1;
3258     default:
3259         return MM_JPEG_COLOR_FORMAT_YCRCBLP_H2V2;
3260     }
3261 }
3262 
doHdrProcessing()3263 void QCameraHardwareInterface::doHdrProcessing()
3264 {
3265     cam_sock_packet_t packet;
3266     int i;
3267     memset(&packet, 0, sizeof(cam_sock_packet_t));
3268     packet.msg_type = CAM_SOCK_MSG_TYPE_HDR_START;
3269 
3270     packet.payload.hdr_pkg.cookie = (long unsigned int) this;
3271     packet.payload.hdr_pkg.num_hdr_frames = mHdrInfo.num_frame;
3272     ALOGI("%s num frames = %d ", __func__, mHdrInfo.num_frame);
3273     for (i = 0; i < mHdrInfo.num_frame; i++) {
3274         packet.payload.hdr_pkg.hdr_main_idx[i] =
3275             mHdrInfo.recvd_frame[i]->bufs[0]->buf_idx;
3276         packet.payload.hdr_pkg.hdr_thm_idx[i] =
3277             mHdrInfo.recvd_frame[i]->bufs[1]->buf_idx;
3278         packet.payload.hdr_pkg.exp[i] = mHdrInfo.exp[i];
3279         ALOGI("%s Adding buffer M %d T %d Exp %d into hdr pkg ", __func__,
3280               packet.payload.hdr_pkg.hdr_main_idx[i],
3281               packet.payload.hdr_pkg.hdr_thm_idx[i],
3282               packet.payload.hdr_pkg.exp[i]);
3283     }
3284     mCameraHandle->ops->send_command(mCameraHandle->camera_handle,
3285                                   MM_CAMERA_CMD_TYPE_NATIVE,
3286                                   NATIVE_CMD_ID_IOCTL_CTRL,
3287                                   sizeof(cam_sock_packet_t), &packet);
3288 }
3289 
initHdrInfoForSnapshot(bool Hdr_on,int number_frames,int * exp)3290 void QCameraHardwareInterface::initHdrInfoForSnapshot(bool Hdr_on, int number_frames, int *exp )
3291 {
3292     ALOGE("%s E hdr_on = %d", __func__, Hdr_on);
3293     mHdrInfo.hdr_on = Hdr_on;
3294     mHdrInfo.num_frame = number_frames;
3295     mHdrInfo.num_raw_received = 0;
3296     if(number_frames) {
3297         memcpy(mHdrInfo.exp, exp, sizeof(int)*number_frames);
3298     }
3299     memset(mHdrInfo.recvd_frame, 0,
3300            sizeof(mm_camera_super_buf_t *)*MAX_HDR_EXP_FRAME_NUM);
3301     ALOGE("%s X", __func__);
3302 }
3303 
notifyHdrEvent(cam_ctrl_status_t status,void * cookie)3304 void QCameraHardwareInterface::notifyHdrEvent(cam_ctrl_status_t status, void * cookie)
3305 {
3306     ALOGE("%s E", __func__);
3307     mm_camera_super_buf_t *frame;
3308     int i;
3309     ALOGI("%s: HDR Done status (%d) received",__func__,status);
3310     for (i = 0; i < 2; i++) {
3311         frame = mHdrInfo.recvd_frame[i];
3312         mSuperBufQueue.enqueue(frame);
3313         /* notify dataNotify thread that new super buf is avail
3314         * check if it's done with current JPEG notification and
3315         * a new encoding job could be conducted */
3316         mNotifyTh->sendCmd(CAMERA_CMD_TYPE_DO_NEXT_JOB, FALSE, FALSE);
3317         mHdrInfo.recvd_frame[i] = NULL;
3318     }
3319     /* qbuf the third frame */
3320     frame = mHdrInfo.recvd_frame[2];
3321     for(i = 0; i < frame->num_bufs; i++) {
3322         mCameraHandle->ops->qbuf(frame->camera_handle,
3323                                  frame->ch_id,
3324                                  frame->bufs[i]);
3325         cache_ops((QCameraHalMemInfo_t *)(frame->bufs[i]->mem_info),
3326                   frame->bufs[i]->buffer,
3327                   ION_IOC_INV_CACHES);
3328     }
3329     free(frame);
3330     mHdrInfo.recvd_frame[2] = NULL;
3331 
3332     ALOGE("%s X", __func__);
3333 }
3334 
cache_ops(QCameraHalMemInfo_t * mem_info,void * buf_ptr,unsigned int cmd)3335 int QCameraHardwareInterface::cache_ops(QCameraHalMemInfo_t *mem_info,
3336                                         void *buf_ptr,
3337                                         unsigned int cmd)
3338 {
3339     struct ion_flush_data cache_inv_data;
3340     struct ion_custom_data custom_data;
3341     int ret = MM_CAMERA_OK;
3342 
3343 #ifdef USE_ION
3344     if (NULL == mem_info) {
3345         ALOGE("%s: mem_info is NULL, return here", __func__);
3346         return -1;
3347     }
3348 
3349     memset(&cache_inv_data, 0, sizeof(cache_inv_data));
3350     memset(&custom_data, 0, sizeof(custom_data));
3351     cache_inv_data.vaddr = buf_ptr;
3352     cache_inv_data.fd = mem_info->fd;
3353     cache_inv_data.handle = mem_info->handle;
3354     cache_inv_data.length = mem_info->size;
3355     custom_data.cmd = cmd;
3356     custom_data.arg = (unsigned long)&cache_inv_data;
3357 
3358     ALOGD("addr = %p, fd = %d, handle = %p length = %d, ION Fd = %d",
3359          cache_inv_data.vaddr, cache_inv_data.fd,
3360          cache_inv_data.handle, cache_inv_data.length,
3361          mem_info->main_ion_fd);
3362     if(mem_info->main_ion_fd > 0) {
3363         if(ioctl(mem_info->main_ion_fd, ION_IOC_CUSTOM, &custom_data) < 0) {
3364             ALOGE("%s: Cache Invalidate failed\n", __func__);
3365             ret = -1;
3366         }
3367     }
3368 #endif
3369 
3370     return ret;
3371 }
3372 
canTakeFullSizeLiveshot()3373 uint8_t QCameraHardwareInterface::canTakeFullSizeLiveshot() {
3374     if (mFullLiveshotEnabled && !isLowPowerCamcorder()) {
3375         /* Full size liveshot enabled. */
3376 
3377         /* If Picture size is same as video size, switch to Video size
3378          * live snapshot */
3379         if ((mDimension.picture_width == mDimension.video_width) &&
3380             (mDimension.picture_height == mDimension.video_height)) {
3381             return FALSE;
3382         }
3383 
3384         if (mDisEnabled) {
3385             /* If DIS is enabled and Picture size is
3386              * less than (video size + 10% DIS Margin)
3387              * then fall back to Video size liveshot. */
3388             if ((mDimension.picture_width <
3389                  (int)(mDimension.video_width * 1.1)) ||
3390                 (mDimension.picture_height <
3391                  (int)(mDimension.video_height * 1.1))) {
3392                 return FALSE;
3393             } else {
3394                 /* Go with Full size live snapshot. */
3395                 return TRUE;
3396             }
3397         } else {
3398             /* DIS Disabled. Go with Full size live snapshot */
3399             return TRUE;
3400         }
3401     } else {
3402         /* Full size liveshot disabled. Fallback to Video size liveshot. */
3403         return FALSE;
3404     }
3405 }
3406 
QCameraQueue()3407 QCameraQueue::QCameraQueue()
3408 {
3409     pthread_mutex_init(&mlock, NULL);
3410     cam_list_init(&mhead.list);
3411     msize = 0;
3412     mdata_rel_fn = NULL;
3413     muser_data = NULL;
3414 }
3415 
QCameraQueue(release_data_fn data_rel_fn,void * user_data)3416 QCameraQueue::QCameraQueue(release_data_fn data_rel_fn, void *user_data)
3417 {
3418     pthread_mutex_init(&mlock, NULL);
3419     cam_list_init(&mhead.list);
3420     msize = 0;
3421     mdata_rel_fn = data_rel_fn;
3422     muser_data = user_data;
3423 }
3424 
~QCameraQueue()3425 QCameraQueue::~QCameraQueue()
3426 {
3427     flush();
3428     pthread_mutex_destroy(&mlock);
3429 }
3430 
is_empty()3431 bool QCameraQueue::is_empty()
3432 {
3433     bool isEmpty = true;
3434     pthread_mutex_lock(&mlock);
3435     if (msize > 0) {
3436         isEmpty = false;
3437     }
3438     pthread_mutex_unlock(&mlock);
3439     return isEmpty;
3440 }
3441 
enqueue(void * data)3442 bool QCameraQueue::enqueue(void *data)
3443 {
3444     camera_q_node *node =
3445         (camera_q_node *)malloc(sizeof(camera_q_node));
3446     if (NULL == node) {
3447         ALOGE("%s: No memory for camera_q_node", __func__);
3448         return false;
3449     }
3450 
3451     memset(node, 0, sizeof(camera_q_node));
3452     node->data = data;
3453 
3454     pthread_mutex_lock(&mlock);
3455     cam_list_add_tail_node(&node->list, &mhead.list);
3456     msize++;
3457     pthread_mutex_unlock(&mlock);
3458     return true;
3459 }
3460 
3461 /* priority queue, will insert into the head of the queue */
pri_enqueue(void * data)3462 bool QCameraQueue::pri_enqueue(void *data)
3463 {
3464     camera_q_node *node =
3465         (camera_q_node *)malloc(sizeof(camera_q_node));
3466     if (NULL == node) {
3467         ALOGE("%s: No memory for camera_q_node", __func__);
3468         return false;
3469     }
3470 
3471     memset(node, 0, sizeof(camera_q_node));
3472     node->data = data;
3473 
3474     pthread_mutex_lock(&mlock);
3475     struct cam_list *p_next = mhead.list.next;
3476 
3477     mhead.list.next = &node->list;
3478     p_next->prev = &node->list;
3479     node->list.next = p_next;
3480     node->list.prev = &mhead.list;
3481 
3482     msize++;
3483     pthread_mutex_unlock(&mlock);
3484     return true;
3485 }
3486 
dequeue()3487 void* QCameraQueue::dequeue()
3488 {
3489     camera_q_node* node = NULL;
3490     void* data = NULL;
3491     struct cam_list *head = NULL;
3492     struct cam_list *pos = NULL;
3493 
3494     pthread_mutex_lock(&mlock);
3495     head = &mhead.list;
3496     pos = head->next;
3497     if (pos != head) {
3498         node = member_of(pos, camera_q_node, list);
3499         cam_list_del_node(&node->list);
3500         msize--;
3501     }
3502     pthread_mutex_unlock(&mlock);
3503 
3504     if (NULL != node) {
3505         data = node->data;
3506         free(node);
3507     }
3508 
3509     return data;
3510 }
3511 
flush()3512 void QCameraQueue::flush(){
3513     camera_q_node* node = NULL;
3514     void* data = NULL;
3515     struct cam_list *head = NULL;
3516     struct cam_list *pos = NULL;
3517 
3518     pthread_mutex_lock(&mlock);
3519     head = &mhead.list;
3520     pos = head->next;
3521 
3522     while(pos != head) {
3523         node = member_of(pos, camera_q_node, list);
3524         pos = pos->next;
3525         cam_list_del_node(&node->list);
3526         msize--;
3527 
3528         if (NULL != node->data) {
3529             if (mdata_rel_fn) {
3530                 mdata_rel_fn(node->data, muser_data);
3531             }
3532             free(node->data);
3533         }
3534         free(node);
3535 
3536     }
3537     msize = 0;
3538     pthread_mutex_unlock(&mlock);
3539 }
3540 
QCameraCmdThread()3541 QCameraCmdThread::QCameraCmdThread() :
3542     cmd_queue()
3543 {
3544     sem_init(&sync_sem, 0, 0);
3545     sem_init(&cmd_sem, 0, 0);
3546 }
3547 
~QCameraCmdThread()3548 QCameraCmdThread::~QCameraCmdThread()
3549 {
3550     sem_destroy(&sync_sem);
3551     sem_destroy(&cmd_sem);
3552 }
3553 
launch(void * (* start_routine)(void *),void * user_data)3554 int32_t QCameraCmdThread::launch(void *(*start_routine)(void *),
3555                                  void* user_data)
3556 {
3557     /* launch the thread */
3558     pthread_create(&cmd_pid,
3559                    NULL,
3560                    start_routine,
3561                    user_data);
3562     return 0;
3563 }
3564 
sendCmd(camera_cmd_type_t cmd,uint8_t sync_cmd,uint8_t priority)3565 int32_t QCameraCmdThread::sendCmd(camera_cmd_type_t cmd, uint8_t sync_cmd, uint8_t priority)
3566 {
3567     camera_cmd_t *node = (camera_cmd_t *)malloc(sizeof(camera_cmd_t));
3568     if (NULL == node) {
3569         ALOGE("%s: No memory for camera_cmd_t", __func__);
3570         return -1;
3571     }
3572     memset(node, 0, sizeof(camera_cmd_t));
3573     node->cmd = cmd;
3574 
3575     ALOGD("%s: enqueue cmd %d", __func__, cmd);
3576     if (TRUE == priority) {
3577         cmd_queue.pri_enqueue((void *)node);
3578     } else {
3579         cmd_queue.enqueue((void *)node);
3580     }
3581     sem_post(&cmd_sem);
3582 
3583     /* if is a sync call, need to wait until it returns */
3584     if (sync_cmd) {
3585         sem_wait(&sync_sem);
3586     }
3587     return 0;
3588 }
3589 
getCmd()3590 camera_cmd_type_t QCameraCmdThread::getCmd()
3591 {
3592     camera_cmd_type_t cmd = CAMERA_CMD_TYPE_NONE;
3593     camera_cmd_t *node = (camera_cmd_t *)cmd_queue.dequeue();
3594     if (NULL == node) {
3595         ALOGD("%s: No notify avail", __func__);
3596         return CAMERA_CMD_TYPE_NONE;
3597     } else {
3598         cmd = node->cmd;
3599         free(node);
3600     }
3601     return cmd;
3602 }
3603 
exit()3604 int32_t QCameraCmdThread::exit()
3605 {
3606     int32_t rc = 0;
3607 
3608     rc = sendCmd(CAMERA_CMD_TYPE_EXIT, FALSE, TRUE);
3609     if (0 != rc) {
3610         ALOGE("%s: Error during exit, rc = %d", __func__, rc);
3611         return rc;
3612     }
3613 
3614     /* wait until cmd thread exits */
3615     if (pthread_join(cmd_pid, NULL) != 0) {
3616         ALOGD("%s: pthread dead already\n", __func__);
3617     }
3618     cmd_pid = 0;
3619     return rc;
3620 }
3621 
3622 }; // namespace android
3623 
3624