QCamera3HWI.cpp revision 662d6f3c8101a94f45f3b0f892817e062a5c0faa
1/* Copyright (c) 2012-2013, The Linux Foundataion. All rights reserved.
2*
3* Redistribution and use in source and binary forms, with or without
4* modification, are permitted provided that the following conditions are
5* met:
6*     * Redistributions of source code must retain the above copyright
7*       notice, this list of conditions and the following disclaimer.
8*     * Redistributions in binary form must reproduce the above
9*       copyright notice, this list of conditions and the following
10*       disclaimer in the documentation and/or other materials provided
11*       with the distribution.
12*     * Neither the name of The Linux Foundation nor the names of its
13*       contributors may be used to endorse or promote products derived
14*       from this software without specific prior written permission.
15*
16* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
17* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
19* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
20* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
23* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
24* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
25* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
26* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27*
28*/
29
30#define LOG_TAG "QCamera3HWI"
31
32#include <cutils/properties.h>
33#include <hardware/camera3.h>
34#include <camera/CameraMetadata.h>
35#include <stdlib.h>
36#include <utils/Log.h>
37#include <utils/Errors.h>
38#include <ui/Fence.h>
39#include <gralloc_priv.h>
40#include "QCamera3HWI.h"
41#include "QCamera3Mem.h"
42#include "QCamera3Channel.h"
43
44using namespace android;
45
46//using namespace android;
47namespace qcamera {
48#define DATA_PTR(MEM_OBJ,INDEX) MEM_OBJ->getPtr( INDEX )
49cam_capability_t *gCamCapability[MM_CAMERA_MAX_NUM_SENSORS];
50parm_buffer_t *prevSettings;
51const camera_metadata_t *gStaticMetadata;
52
53const QCamera3HardwareInterface::QCameraMap QCamera3HardwareInterface::EFFECT_MODES_MAP[] = {
54    { ANDROID_CONTROL_EFFECT_MODE_OFF,       CAM_EFFECT_MODE_OFF },
55    { ANDROID_CONTROL_EFFECT_MODE_MONO,       CAM_EFFECT_MODE_MONO },
56    { ANDROID_CONTROL_EFFECT_MODE_NEGATIVE,   CAM_EFFECT_MODE_NEGATIVE },
57    { ANDROID_CONTROL_EFFECT_MODE_SOLARIZE,   CAM_EFFECT_MODE_SOLARIZE },
58    { ANDROID_CONTROL_EFFECT_MODE_SEPIA,      CAM_EFFECT_MODE_SEPIA },
59    { ANDROID_CONTROL_EFFECT_MODE_POSTERIZE,  CAM_EFFECT_MODE_POSTERIZE },
60    { ANDROID_CONTROL_EFFECT_MODE_WHITEBOARD, CAM_EFFECT_MODE_WHITEBOARD },
61    { ANDROID_CONTROL_EFFECT_MODE_BLACKBOARD, CAM_EFFECT_MODE_BLACKBOARD },
62    { ANDROID_CONTROL_EFFECT_MODE_AQUA,       CAM_EFFECT_MODE_AQUA }
63};
64
65const QCamera3HardwareInterface::QCameraMap QCamera3HardwareInterface::WHITE_BALANCE_MODES_MAP[] = {
66    { ANDROID_CONTROL_AWB_MODE_AUTO,            CAM_WB_MODE_AUTO },
67    { ANDROID_CONTROL_AWB_MODE_INCANDESCENT,    CAM_WB_MODE_INCANDESCENT },
68    { ANDROID_CONTROL_AWB_MODE_FLUORESCENT,     CAM_WB_MODE_FLUORESCENT },
69    { ANDROID_CONTROL_AWB_MODE_WARM_FLUORESCENT,CAM_WB_MODE_WARM_FLUORESCENT},
70    { ANDROID_CONTROL_AWB_MODE_DAYLIGHT,        CAM_WB_MODE_DAYLIGHT },
71    { ANDROID_CONTROL_AWB_MODE_CLOUDY_DAYLIGHT, CAM_WB_MODE_CLOUDY_DAYLIGHT },
72    { ANDROID_CONTROL_AWB_MODE_TWILIGHT,        CAM_WB_MODE_TWILIGHT },
73    { ANDROID_CONTROL_AWB_MODE_SHADE,           CAM_WB_MODE_SHADE }
74};
75
76const QCamera3HardwareInterface::QCameraMap QCamera3HardwareInterface::SCENE_MODES_MAP[] = {
77    { ANDROID_CONTROL_SCENE_MODE_UNSUPPORTED,    CAM_SCENE_MODE_OFF },
78    { ANDROID_CONTROL_SCENE_MODE_ACTION,         CAM_SCENE_MODE_ACTION },
79    { ANDROID_CONTROL_SCENE_MODE_PORTRAIT,       CAM_SCENE_MODE_PORTRAIT },
80    { ANDROID_CONTROL_SCENE_MODE_LANDSCAPE,      CAM_SCENE_MODE_LANDSCAPE },
81    { ANDROID_CONTROL_SCENE_MODE_NIGHT,          CAM_SCENE_MODE_NIGHT },
82    { ANDROID_CONTROL_SCENE_MODE_NIGHT_PORTRAIT, CAM_SCENE_MODE_NIGHT_PORTRAIT },
83    { ANDROID_CONTROL_SCENE_MODE_THEATRE,        CAM_SCENE_MODE_THEATRE },
84    { ANDROID_CONTROL_SCENE_MODE_BEACH,          CAM_SCENE_MODE_BEACH },
85    { ANDROID_CONTROL_SCENE_MODE_SNOW,           CAM_SCENE_MODE_SNOW },
86    { ANDROID_CONTROL_SCENE_MODE_SUNSET,         CAM_SCENE_MODE_SUNSET },
87    { ANDROID_CONTROL_SCENE_MODE_STEADYPHOTO,    CAM_SCENE_MODE_ANTISHAKE },
88    { ANDROID_CONTROL_SCENE_MODE_FIREWORKS ,     CAM_SCENE_MODE_FIREWORKS },
89    { ANDROID_CONTROL_SCENE_MODE_SPORTS ,        CAM_SCENE_MODE_SPORTS },
90    { ANDROID_CONTROL_SCENE_MODE_PARTY,          CAM_SCENE_MODE_PARTY },
91    { ANDROID_CONTROL_SCENE_MODE_CANDLELIGHT,    CAM_SCENE_MODE_CANDLELIGHT },
92    { ANDROID_CONTROL_SCENE_MODE_BARCODE,        CAM_SCENE_MODE_OFF}
93};
94
95const QCamera3HardwareInterface::QCameraMap QCamera3HardwareInterface::FOCUS_MODES_MAP[] = {
96    { ANDROID_CONTROL_AF_MODE_AUTO,               CAM_FOCUS_MODE_AUTO },
97    { ANDROID_CONTROL_AF_MODE_MACRO,              CAM_FOCUS_MODE_MACRO },
98    { ANDROID_CONTROL_AF_MODE_EDOF,               CAM_FOCUS_MODE_EDOF },
99    { ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE, CAM_FOCUS_MODE_CONTINOUS_PICTURE },
100    { ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO,   CAM_FOCUS_MODE_CONTINOUS_VIDEO }
101};
102
103const QCamera3HardwareInterface::QCameraMap QCamera3HardwareInterface::ANTIBANDING_MODES_MAP[] = {
104    { ANDROID_CONTROL_AE_ANTIBANDING_MODE_OFF,  CAM_ANTIBANDING_MODE_OFF },
105    { ANDROID_CONTROL_AE_ANTIBANDING_MODE_50HZ, CAM_ANTIBANDING_MODE_50HZ },
106    { ANDROID_CONTROL_AE_ANTIBANDING_MODE_60HZ, CAM_ANTIBANDING_MODE_60HZ },
107    { ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO, CAM_ANTIBANDING_MODE_AUTO }
108};
109
110const QCamera3HardwareInterface::QCameraMap QCamera3HardwareInterface::AUTO_EXPOSURE_MAP[] = {
111    { ANDROID_CONTROL_AE_MODE_OFF,    CAM_AEC_MODE_FRAME_AVERAGE },
112    { ANDROID_CONTROL_AE_MODE_ON,     CAM_AEC_MODE_FRAME_AVERAGE },
113};
114
115const QCamera3HardwareInterface::QCameraMap QCamera3HardwareInterface::FLASH_MODES_MAP[] = {
116    { ANDROID_FLASH_MODE_OFF,    CAM_FLASH_MODE_OFF  },
117    { ANDROID_FLASH_MODE_SINGLE, CAM_FLASH_MODE_ON   },
118    { ANDROID_FLASH_MODE_TORCH,  CAM_FLASH_MODE_TORCH}
119};
120
121
122camera3_device_ops_t QCamera3HardwareInterface::mCameraOps = {
123    initialize:                         QCamera3HardwareInterface::initialize,
124    configure_streams:                  QCamera3HardwareInterface::configure_streams,
125    register_stream_buffers:            QCamera3HardwareInterface::register_stream_buffers,
126    construct_default_request_settings: QCamera3HardwareInterface::construct_default_request_settings,
127    process_capture_request:            QCamera3HardwareInterface::process_capture_request,
128    get_metadata_vendor_tag_ops:        QCamera3HardwareInterface::get_metadata_vendor_tag_ops,
129    dump:                               QCamera3HardwareInterface::dump,
130};
131
132
133/*===========================================================================
134 * FUNCTION   : QCamera3HardwareInterface
135 *
136 * DESCRIPTION: constructor of QCamera3HardwareInterface
137 *
138 * PARAMETERS :
139 *   @cameraId  : camera ID
140 *
141 * RETURN     : none
142 *==========================================================================*/
143QCamera3HardwareInterface::QCamera3HardwareInterface(int cameraId)
144    : mCameraId(cameraId),
145      mCameraHandle(NULL),
146      mCameraOpened(false),
147      mCallbackOps(NULL)
148{
149    mCameraDevice.common.tag = HARDWARE_DEVICE_TAG;
150    mCameraDevice.common.version = CAMERA_DEVICE_API_VERSION_3_0;
151    mCameraDevice.common.close = close_camera_device;
152    mCameraDevice.ops = &mCameraOps;
153    mCameraDevice.priv = this;
154    gCamCapability[cameraId]->version = CAM_HAL_V3;
155
156    pthread_mutex_init(&mRequestLock, NULL);
157    pthread_cond_init(&mRequestCond, NULL);
158    mPendingRequest = 0;
159
160    pthread_mutex_init(&mMutex, NULL);
161}
162
163/*===========================================================================
164 * FUNCTION   : ~QCamera3HardwareInterface
165 *
166 * DESCRIPTION: destructor of QCamera2HardwareInterface
167 *
168 * PARAMETERS : none
169 *
170 * RETURN     : none
171 *==========================================================================*/
172QCamera3HardwareInterface::~QCamera3HardwareInterface()
173{
174    closeCamera();
175
176    pthread_mutex_destroy(&mRequestLock);
177    pthread_cond_destroy(&mRequestCond);
178
179    pthread_mutex_destroy(&mMutex);
180}
181
182/*===========================================================================
183 * FUNCTION   : openCamera
184 *
185 * DESCRIPTION: open camera
186 *
187 * PARAMETERS :
188 *   @hw_device  : double ptr for camera device struct
189 *
190 * RETURN     : int32_t type of status
191 *              NO_ERROR  -- success
192 *              none-zero failure code
193 *==========================================================================*/
194int QCamera3HardwareInterface::openCamera(struct hw_device_t **hw_device)
195{
196    //int rc = NO_ERROR;
197    int rc = 0;
198    if (mCameraOpened) {
199        *hw_device = NULL;
200        return PERMISSION_DENIED;
201    }
202
203    rc = openCamera();
204    if (rc == 0)
205        *hw_device = &mCameraDevice.common;
206    else
207        *hw_device = NULL;
208    return rc;
209}
210
211/*===========================================================================
212 * FUNCTION   : openCamera
213 *
214 * DESCRIPTION: open camera
215 *
216 * PARAMETERS : none
217 *
218 * RETURN     : int32_t type of status
219 *              NO_ERROR  -- success
220 *              none-zero failure code
221 *==========================================================================*/
222int QCamera3HardwareInterface::openCamera()
223{
224    if (mCameraHandle) {
225        ALOGE("Failure: Camera already opened");
226        return ALREADY_EXISTS;
227    }
228    mCameraHandle = camera_open(mCameraId);
229    if (!mCameraHandle) {
230        ALOGE("camera_open failed.");
231        return UNKNOWN_ERROR;
232    }
233
234    mCameraOpened = true;
235
236    return NO_ERROR;
237}
238
239/*===========================================================================
240 * FUNCTION   : closeCamera
241 *
242 * DESCRIPTION: close camera
243 *
244 * PARAMETERS : none
245 *
246 * RETURN     : int32_t type of status
247 *              NO_ERROR  -- success
248 *              none-zero failure code
249 *==========================================================================*/
250int QCamera3HardwareInterface::closeCamera()
251{
252    int rc = NO_ERROR;
253
254    rc = mCameraHandle->ops->close_camera(mCameraHandle->camera_handle);
255    mCameraHandle = NULL;
256    mCameraOpened = false;
257
258    return rc;
259}
260
261/*===========================================================================
262 * FUNCTION   : sendCaptureResult
263 *
264 * DESCRIPTION: send completed capture result metadata buffer along with possibly
265 *              completed output stream buffers to the framework
266 *
267 * PARAMETERS :
268 *
269 * RETURN     :
270 *==========================================================================*/
271void QCamera3HardwareInterface::sendCaptureResult(const struct camera3_callback_ops *,
272                                                 const camera3_capture_result_t *result)
273{
274    //TODO - Implement
275}
276
277/*===========================================================================
278 * FUNCTION   : notify
279 *
280 * DESCRIPTION: Asynchronous notification callback to framework
281 *
282 * PARAMETERS :
283 *
284 * RETURN     :
285 *
286 *
287 *==========================================================================*/
288
289void QCamera3HardwareInterface::notify(const struct camera3_callback_ops *,
290                                       const camera3_notify_msg_t *msg)
291{
292    //TODO - Implement
293}
294
295
296/*===========================================================================
297 * FUNCTION   : initialize
298 *
299 * DESCRIPTION: Initialize frameworks callback functions
300 *
301 * PARAMETERS :
302 *   @callback_ops : callback function to frameworks
303 *
304 * RETURN     :
305 *
306 *==========================================================================*/
307int QCamera3HardwareInterface::initialize(
308        const struct camera3_callback_ops *callback_ops)
309{
310    int rc;
311
312    pthread_mutex_lock(&mMutex);
313
314    //Create metadata channel and initialize it
315    mMetadataChannel = new QCamera3MetadataChannel(mCameraHandle->camera_handle,
316                    mCameraHandle->ops, captureResultCb,
317                    &gCamCapability[mCameraId]->padding_info, this);
318    if (mMetadataChannel == NULL) {
319        ALOGE("%s: failed to allocate metadata channel", __func__);
320        rc = -ENOMEM;
321        goto err1;
322    }
323    rc = mMetadataChannel->initialize();
324    if (rc < 0) {
325        ALOGE("%s: metadata channel initialization failed", __func__);
326        goto err2;
327    }
328
329    /* Initialize parameter heap and structure */
330    mParamHeap = new QCamera3HeapMemory();
331    if (mParamHeap == NULL) {
332        ALOGE("%s: creation of mParamHeap failed", __func__);
333        goto err2;
334    }
335    rc = mParamHeap->allocate(1, sizeof(parm_buffer_t), false);
336    if (rc < 0) {
337        ALOGE("%s: allocation of mParamHeap failed", __func__);
338        goto err3;
339    }
340    rc = mCameraHandle->ops->map_buf(mCameraHandle->camera_handle,
341                CAM_MAPPING_BUF_TYPE_PARM_BUF,
342                mParamHeap->getFd(0), sizeof(parm_buffer_t));
343    if (rc < 0) {
344        ALOGE("%s: map_buf failed for mParamHeap", __func__);
345        goto err4;
346    }
347    mParameters = (parm_buffer_t *)DATA_PTR(mParamHeap, 0);
348
349    mCallbackOps = callback_ops;
350
351    pthread_mutex_unlock(&mMutex);
352    return 0;
353
354err4:
355    mParamHeap->deallocate();
356err3:
357    delete mParamHeap;
358    mParamHeap = NULL;
359err2:
360    delete mMetadataChannel;
361    mMetadataChannel = NULL;
362err1:
363    pthread_mutex_unlock(&mMutex);
364    return rc;
365}
366
367/*===========================================================================
368 * FUNCTION   : configureStreams
369 *
370 * DESCRIPTION: Reset HAL camera device processing pipeline and set up new input
371 *              and output streams.
372 *
373 * PARAMETERS :
374 *   @stream_list : streams to be configured
375 *
376 * RETURN     :
377 *
378 *==========================================================================*/
379int QCamera3HardwareInterface::configureStreams(
380        camera3_stream_configuration_t *streamList)
381{
382    pthread_mutex_lock(&mMutex);
383
384    // Sanity check stream_list
385    if (streamList == NULL) {
386        ALOGE("%s: NULL stream configuration", __func__);
387        pthread_mutex_unlock(&mMutex);
388        return BAD_VALUE;
389    }
390
391    if (streamList->streams == NULL) {
392        ALOGE("%s: NULL stream list", __func__);
393        pthread_mutex_unlock(&mMutex);
394        return BAD_VALUE;
395    }
396
397    if (streamList->num_streams < 1) {
398        ALOGE("%s: Bad number of streams requested: %d", __func__,
399                streamList->num_streams);
400        pthread_mutex_unlock(&mMutex);
401        return BAD_VALUE;
402    }
403
404    camera3_stream_t *inputStream = NULL;
405    for (size_t i = 0; i < streamList->num_streams; i++) {
406        camera3_stream_t *newStream = streamList->streams[i];
407        if (newStream->stream_type == CAMERA3_STREAM_INPUT) {
408            if (inputStream != NULL) {
409                ALOGE("%s: Multiple input streams requested!", __func__);
410                pthread_mutex_unlock(&mMutex);
411                return BAD_VALUE;
412            }
413            inputStream = newStream;
414        }
415    }
416    mInputStream = inputStream;
417
418    /* TODO: Clean up no longer used streams, and maintain others if this
419     * is not the 1st time configureStreams is called */
420
421    mMetadataChannel->stop();
422
423    /* Allocate channel objects for the requested streams */
424    for (size_t i = 0; i < streamList->num_streams; i++) {
425        camera3_stream_t *newStream = streamList->streams[i];
426        if (newStream->priv == NULL) {
427            //New stream, construct channel
428
429            switch (newStream->stream_type) {
430            case CAMERA3_STREAM_INPUT:
431                newStream->usage = GRALLOC_USAGE_HW_CAMERA_READ;
432                newStream->max_buffers = QCamera3PicChannel::kMaxBuffers;
433                break;
434            case CAMERA3_STREAM_BIDIRECTIONAL:
435                newStream->usage = GRALLOC_USAGE_HW_CAMERA_READ |
436                    GRALLOC_USAGE_HW_CAMERA_WRITE;
437                newStream->max_buffers = QCamera3RegularChannel::kMaxBuffers;
438                break;
439            case CAMERA3_STREAM_OUTPUT:
440                newStream->usage = GRALLOC_USAGE_HW_CAMERA_WRITE;
441                newStream->max_buffers = QCamera3RegularChannel::kMaxBuffers;
442                break;
443            default:
444                ALOGE("%s: Invalid stream_type %d", __func__, newStream->stream_type);
445                break;
446            }
447
448            if (newStream->stream_type == CAMERA3_STREAM_OUTPUT ||
449                newStream->stream_type == CAMERA3_STREAM_BIDIRECTIONAL) {
450                QCamera3Channel *channel;
451                switch (newStream->format) {
452                case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
453                    channel = new QCamera3RegularChannel(mCameraHandle->camera_handle,
454                            mCameraHandle->ops, captureResultCb,
455                            &gCamCapability[mCameraId]->padding_info, this, newStream);
456                    if (channel == NULL) {
457                        ALOGE("%s: allocation of channel failed", __func__);
458                        pthread_mutex_unlock(&mMutex);
459                        return -ENOMEM;
460                    }
461
462                    newStream->priv = channel;
463                    break;
464                case HAL_PIXEL_FORMAT_BLOB:
465                    channel = new QCamera3PicChannel(mCameraHandle->camera_handle,
466                            mCameraHandle->ops, captureResultCb,
467                            &gCamCapability[mCameraId]->padding_info, this, newStream);
468                    if (channel == NULL) {
469                        ALOGE("%s: allocation of channel failed", __func__);
470                        pthread_mutex_unlock(&mMutex);
471                        return -ENOMEM;
472                    }
473
474                    newStream->priv = channel;
475                    break;
476
477                //TODO: Add support for app consumed format?
478                default:
479                    ALOGE("%s: not a supported format 0x%x", __func__, newStream->format);
480                    break;
481                }
482            }
483        } else {
484            // Channel already exists for this stream
485            // Do nothing for now
486        }
487    }
488
489    // Cannot reuse settings across configure call
490    memset(mParameters, 0, sizeof(parm_buffer_t));
491    pthread_mutex_unlock(&mMutex);
492    return 0;
493}
494
495/*===========================================================================
496 * FUNCTION   : validateCaptureRequest
497 *
498 * DESCRIPTION: validate a capture request from camera service
499 *
500 * PARAMETERS :
501 *   @request : request from framework to process
502 *
503 * RETURN     :
504 *
505 *==========================================================================*/
506int QCamera3HardwareInterface::validateCaptureRequest(
507                    camera3_capture_request_t *request)
508{
509    int rc = NO_ERROR;
510    ssize_t idx = 0;
511    const camera3_stream_buffer_t *b;
512    CameraMetadata meta;
513
514    /* Sanity check the request */
515    if (request == NULL) {
516        ALOGE("%s: NULL capture request", __func__);
517        return BAD_VALUE;
518    }
519
520    uint32_t frameNumber = request->frame_number;
521    if (request->input_buffer != NULL &&
522            request->input_buffer->stream != mInputStream) {
523        ALOGE("%s: Request %d: Input buffer not from input stream!",
524                __FUNCTION__, frameNumber);
525        return BAD_VALUE;
526    }
527    if (request->num_output_buffers < 1 || request->output_buffers == NULL) {
528        ALOGE("%s: Request %d: No output buffers provided!",
529                __FUNCTION__, frameNumber);
530        return BAD_VALUE;
531    }
532    if (request->input_buffer != NULL) {
533        //TODO
534        ALOGE("%s: Not supporting input buffer yet", __func__);
535        return BAD_VALUE;
536    }
537
538    // Validate all buffers
539    b = request->output_buffers;
540    do {
541        QCamera3Channel *channel =
542                static_cast<QCamera3Channel*>(b->stream->priv);
543        if (channel == NULL) {
544            ALOGE("%s: Request %d: Buffer %d: Unconfigured stream!",
545                    __func__, frameNumber, idx);
546            return BAD_VALUE;
547        }
548        if (b->status != CAMERA3_BUFFER_STATUS_OK) {
549            ALOGE("%s: Request %d: Buffer %d: Status not OK!",
550                    __func__, frameNumber, idx);
551            return BAD_VALUE;
552        }
553        if (b->release_fence != -1) {
554            ALOGE("%s: Request %d: Buffer %d: Has a release fence!",
555                    __func__, frameNumber, idx);
556            return BAD_VALUE;
557        }
558        if (b->buffer == NULL) {
559            ALOGE("%s: Request %d: Buffer %d: NULL buffer handle!",
560                    __func__, frameNumber, idx);
561            return BAD_VALUE;
562        }
563        idx++;
564        b = request->output_buffers + idx;
565    } while (idx < (ssize_t)request->num_output_buffers);
566
567    return NO_ERROR;
568}
569
570/*===========================================================================
571 * FUNCTION   : registerStreamBuffers
572 *
573 * DESCRIPTION: Register buffers for a given stream with the HAL device.
574 *
575 * PARAMETERS :
576 *   @stream_list : streams to be configured
577 *
578 * RETURN     :
579 *
580 *==========================================================================*/
581int QCamera3HardwareInterface::registerStreamBuffers(
582        const camera3_stream_buffer_set_t *buffer_set)
583{
584    int rc = 0;
585
586    pthread_mutex_lock(&mMutex);
587
588    if (buffer_set == NULL) {
589        ALOGE("%s: Invalid buffer_set parameter.", __func__);
590        pthread_mutex_unlock(&mMutex);
591        return -EINVAL;
592    }
593    if (buffer_set->stream == NULL) {
594        ALOGE("%s: Invalid stream parameter.", __func__);
595        pthread_mutex_unlock(&mMutex);
596        return -EINVAL;
597    }
598    if (buffer_set->num_buffers < 1) {
599        ALOGE("%s: Invalid num_buffers %d.", __func__, buffer_set->num_buffers);
600        pthread_mutex_unlock(&mMutex);
601        return -EINVAL;
602    }
603    if (buffer_set->buffers == NULL) {
604        ALOGE("%s: Invalid buffers parameter.", __func__);
605        pthread_mutex_unlock(&mMutex);
606        return -EINVAL;
607    }
608
609    camera3_stream_t *stream = buffer_set->stream;
610    QCamera3Channel *channel = (QCamera3Channel *)stream->priv;
611
612    if (stream->stream_type != CAMERA3_STREAM_OUTPUT) {
613        ALOGE("%s: not yet support non output type stream", __func__);
614        pthread_mutex_unlock(&mMutex);
615        return -EINVAL;
616    }
617    rc = channel->registerBuffers(buffer_set->num_buffers, buffer_set->buffers);
618    if (rc < 0) {
619        ALOGE("%s: registerBUffers for stream %p failed", __func__, stream);
620        pthread_mutex_unlock(&mMutex);
621        return -ENODEV;
622    }
623
624    pthread_mutex_unlock(&mMutex);
625    return NO_ERROR;
626}
627
628/*===========================================================================
629 * FUNCTION   : processCaptureRequest
630 *
631 * DESCRIPTION: process a capture request from camera service
632 *
633 * PARAMETERS :
634 *   @request : request from framework to process
635 *
636 * RETURN     :
637 *
638 *==========================================================================*/
639int QCamera3HardwareInterface::processCaptureRequest(
640                    camera3_capture_request_t *request)
641{
642    int rc = NO_ERROR;
643    ssize_t idx = 0;
644    const camera3_stream_buffer_t *b;
645    CameraMetadata meta;
646
647    pthread_mutex_lock(&mMutex);
648
649    rc = validateCaptureRequest(request);
650    if (rc != NO_ERROR) {
651        ALOGE("%s: incoming request is not valid", __func__);
652        pthread_mutex_unlock(&mMutex);
653        return rc;
654    }
655
656    uint32_t frameNumber = request->frame_number;
657
658    rc = setFrameParameters(request->frame_number, request->settings);
659
660    if (rc < 0) {
661        ALOGE("%s: fail to set frame parameters", __func__);
662        pthread_mutex_unlock(&mMutex);
663        return rc;
664    }
665
666    // Acquire all request buffers first
667    for (size_t i = 0; i < request->num_output_buffers; i++) {
668        const camera3_stream_buffer_t& output = request->output_buffers[i];
669        sp<Fence> acquireFence = new Fence(output.acquire_fence);
670        rc = acquireFence->wait(Fence::TIMEOUT_NEVER);
671        if (rc != OK) {
672            ALOGE("%s: fence wait failed %d", __func__, rc);
673            pthread_mutex_unlock(&mMutex);
674            return rc;
675        }
676    }
677
678    // Notify metadata channel we receive a request
679    mMetadataChannel->request(NULL, frameNumber);
680
681    // Call request on other streams
682    for (size_t i = 0; i < request->num_output_buffers; i++) {
683        const camera3_stream_buffer_t& output = request->output_buffers[i];
684        QCamera3Channel *channel = (QCamera3Channel *)output.stream->priv;
685        if (channel == NULL) {
686            ALOGE("%s: invalid channel pointer for stream", __func__);
687            continue;
688        }
689
690        rc = channel->request(output.buffer, frameNumber);
691        if (rc < 0)
692            ALOGE("%s: request failed", __func__);
693    }
694
695    //Block on conditional variable
696    pthread_mutex_lock(&mRequestLock);
697    mPendingRequest = 1;
698    while (mPendingRequest == 1) {
699        pthread_cond_wait(&mRequestCond, &mRequestLock);
700    }
701    pthread_mutex_unlock(&mRequestLock);
702
703    pthread_mutex_unlock(&mMutex);
704    return rc;
705}
706
707/*===========================================================================
708 * FUNCTION   : getMetadataVendorTagOps
709 *
710 * DESCRIPTION:
711 *
712 * PARAMETERS :
713 *
714 *
715 * RETURN     :
716 *==========================================================================*/
717void QCamera3HardwareInterface::getMetadataVendorTagOps(vendor_tag_query_ops_t* ops)
718{
719    /* Enable locks when we eventually add Vendor Tags */
720    /*
721    pthread_mutex_lock(&mMutex);
722
723    pthread_mutex_unlock(&mMutex);
724    */
725    return;
726}
727
728/*===========================================================================
729 * FUNCTION   : dump
730 *
731 * DESCRIPTION:
732 *
733 * PARAMETERS :
734 *
735 *
736 * RETURN     :
737 *==========================================================================*/
738void QCamera3HardwareInterface::dump(int fd)
739{
740    /*Enable lock when we implement this function*/
741    /*
742    pthread_mutex_lock(&mMutex);
743
744    pthread_mutex_unlock(&mMutex);
745    */
746    return;
747}
748
749/*===========================================================================
750 * FUNCTION   : captureResultCb
751 *
752 * DESCRIPTION: Callback handler for all capture result (streams, as well as metadata)
753 *
754 * PARAMETERS :
755 *   @metadata : metadata information
756 *   @buffer   : actual gralloc buffer to be returned to frameworks. NULL if metadata.
757 *
758 * RETURN     : NONE
759 *==========================================================================*/
760void QCamera3HardwareInterface::captureResultCb(metadata_buffer_t *metadata,
761                camera3_stream_buffer_t *buffer, uint32_t frame_number)
762{
763    pthread_mutex_lock(&mCaptureResultLock);
764    camera3_capture_result_t result;
765
766
767    if (metadata) {
768        // Signal to unblock processCaptureRequest
769        pthread_mutex_lock(&mRequestLock);
770        mPendingRequest = 0;
771        pthread_cond_signal(&mRequestCond);
772        pthread_mutex_unlock(&mRequestLock);
773
774        //TODO: Add translation from metadata_buffer_t to CameraMetadata
775        // for now, hardcode timestamp only.
776        CameraMetadata camMetadata;
777        uint32_t *frame_number = (uint32_t *)POINTER_OF(CAM_INTF_META_FRAME_NUMBER, metadata);
778        nsecs_t captureTime = 1000000 * (*frame_number) * 33;
779        camMetadata.update(ANDROID_SENSOR_TIMESTAMP, &captureTime, 1);
780
781        result.result = camMetadata.release();
782        if (!result.result) {
783            result.frame_number = *frame_number;
784            result.num_output_buffers = 0;
785            result.output_buffers = NULL;
786            mCallbackOps->process_capture_result(mCallbackOps, &result);
787
788            free_camera_metadata((camera_metadata_t*)result.result);
789        }
790    } else {
791        result.result = NULL;
792        result.frame_number = frame_number;
793        result.num_output_buffers = 1;
794        result.output_buffers = buffer;
795        mCallbackOps->process_capture_result(mCallbackOps, &result);
796    }
797
798    pthread_mutex_unlock(&mCaptureResultLock);
799    return;
800}
801
802#define DATA_PTR(MEM_OBJ,INDEX) MEM_OBJ->getPtr( INDEX )
803/*===========================================================================
804 * FUNCTION   : initCapabilities
805 *
806 * DESCRIPTION: initialize camera capabilities in static data struct
807 *
808 * PARAMETERS :
809 *   @cameraId  : camera Id
810 *
811 * RETURN     : int32_t type of status
812 *              NO_ERROR  -- success
813 *              none-zero failure code
814 *==========================================================================*/
815int QCamera3HardwareInterface::initCapabilities(int cameraId)
816{
817    int rc = 0;
818    mm_camera_vtbl_t *cameraHandle = NULL;
819    QCamera3HeapMemory *capabilityHeap = NULL;
820
821    cameraHandle = camera_open(cameraId);
822    if (!cameraHandle) {
823        ALOGE("%s: camera_open failed", __func__);
824        rc = -1;
825        goto open_failed;
826    }
827
828    capabilityHeap = new QCamera3HeapMemory();
829    if (capabilityHeap == NULL) {
830        ALOGE("%s: creation of capabilityHeap failed", __func__);
831        goto heap_creation_failed;
832    }
833    /* Allocate memory for capability buffer */
834    rc = capabilityHeap->allocate(1, sizeof(cam_capability_t), false);
835    if(rc != OK) {
836        ALOGE("%s: No memory for cappability", __func__);
837        goto allocate_failed;
838    }
839
840    /* Map memory for capability buffer */
841    memset(DATA_PTR(capabilityHeap,0), 0, sizeof(cam_capability_t));
842    rc = cameraHandle->ops->map_buf(cameraHandle->camera_handle,
843                                CAM_MAPPING_BUF_TYPE_CAPABILITY,
844                                capabilityHeap->getFd(0),
845                                sizeof(cam_capability_t));
846    if(rc < 0) {
847        ALOGE("%s: failed to map capability buffer", __func__);
848        goto map_failed;
849    }
850
851    /* Query Capability */
852    rc = cameraHandle->ops->query_capability(cameraHandle->camera_handle);
853    if(rc < 0) {
854        ALOGE("%s: failed to query capability",__func__);
855        goto query_failed;
856    }
857    gCamCapability[cameraId] = (cam_capability_t *)malloc(sizeof(cam_capability_t));
858    if (!gCamCapability[cameraId]) {
859        ALOGE("%s: out of memory", __func__);
860        goto query_failed;
861    }
862    memcpy(gCamCapability[cameraId], DATA_PTR(capabilityHeap,0),
863                                        sizeof(cam_capability_t));
864    rc = 0;
865
866query_failed:
867    cameraHandle->ops->unmap_buf(cameraHandle->camera_handle,
868                            CAM_MAPPING_BUF_TYPE_CAPABILITY);
869map_failed:
870    capabilityHeap->deallocate();
871allocate_failed:
872    delete capabilityHeap;
873heap_creation_failed:
874    cameraHandle->ops->close_camera(cameraHandle->camera_handle);
875    cameraHandle = NULL;
876open_failed:
877    return rc;
878}
879
880/*===========================================================================
881 * FUNCTION   : initParameters
882 *
883 * DESCRIPTION: initialize camera parameters
884 *
885 * PARAMETERS :
886 *
887 * RETURN     : int32_t type of status
888 *              NO_ERROR  -- success
889 *              none-zero failure code
890 *==========================================================================*/
891int QCamera3HardwareInterface::initParameters()
892{
893    int rc = 0;
894
895    //Allocate Set Param Buffer
896    mParamHeap = new QCamera3HeapMemory();
897    rc = mParamHeap->allocate(1, sizeof(parm_buffer_t), false);
898    if(rc != OK) {
899        rc = NO_MEMORY;
900        ALOGE("Failed to allocate SETPARM Heap memory");
901        delete mParamHeap;
902        mParamHeap = NULL;
903        return rc;
904    }
905
906    //Map memory for parameters buffer
907    rc = mCameraHandle->ops->map_buf(mCameraHandle->camera_handle,
908            CAM_MAPPING_BUF_TYPE_PARM_BUF,
909            mParamHeap->getFd(0),
910            sizeof(parm_buffer_t));
911    if(rc < 0) {
912        ALOGE("%s:failed to map SETPARM buffer",__func__);
913        rc = FAILED_TRANSACTION;
914        mParamHeap->deallocate();
915        delete mParamHeap;
916        mParamHeap = NULL;
917        return rc;
918    }
919
920    mParameters = (parm_buffer_t*) DATA_PTR(mParamHeap,0);
921    memset(mParameters, 0, sizeof(parm_buffer_t));
922    mParameters->first_flagged_entry = CAM_INTF_PARM_MAX;
923    return rc;
924}
925
926/*===========================================================================
927 * FUNCTION   : initStaticMetadata
928 *
929 * DESCRIPTION: initialize the static metadata
930 *
931 * PARAMETERS :
932 *   @cameraId  : camera Id
933 *
934 * RETURN     : int32_t type of status
935 *              0  -- success
936 *              non-zero failure code
937 *==========================================================================*/
938int QCamera3HardwareInterface::initStaticMetadata(int cameraId)
939{
940    int rc = 0;
941    android::CameraMetadata staticInfo;
942    int facingBack = gCamCapability[cameraId]->position == CAM_POSITION_BACK;
943    /*HAL 3 only*/
944    #ifdef HAL_3_CAPABILITIES
945    staticInfo.update(ANDROID_LENS_INFO_MINIMUM_FOCUS_DISTANCE,
946                    &gCamCapability[cameraId]->min_focus_distance, 1);
947
948    staticInfo.update(ANDROID_LENS_INFO_HYPERFOCAL_DISTANCE,
949                    &gCamCapability[cameraId]->hyper_focal_distance, 1);
950
951    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS,
952                      gCamCapability[cameraId]->focal_lengths,
953                      gCamCapability[cameraId]->focal_lengths_count);
954
955
956    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_APERTURES,
957                      gCamCapability[cameraId]->apertures,
958                      gCamCapability[cameraId]->apertures_count);
959
960    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_FILTER_DENSITIES,
961                gCamCapability[cameraId]->filter_densities,
962                gCamCapability[cameraId]->filter_densities_count);
963
964
965    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION,
966                      (int*)gCamCapability[cameraId]->optical_stab_modes,
967                      gCamCapability[cameraId]->optical_stab_modes_count);
968
969    staticInfo.update(ANDROID_LENS_POSITION,
970                      gCamCapability[cameraId]->lens_position,
971                      sizeof(gCamCapability[cameraId]->lens_position)/ sizeof(float));
972
973    static const int32_t lens_shading_map_size[] = {gCamCapability[cameraId]->lens_shading_map_size.width,
974                                                    gCamCapability[cameraId]->lens_shading_map_size.height};
975    staticInfo.update(ANDROID_LENS_INFO_SHADING_MAP_SIZE,
976                      lens_shading_map_size,
977                      sizeof(lens_shading_map_size)/sizeof(int32_t));
978
979    staticInfo.update(ANDROID_LENS_INFO_SHADING_MAP, gCamCapability[cameraId]->lens_shading_map,
980            sizeof(gCamCapability[cameraId]->lens_shading_map_size)/ sizeof(cam_dimension_t));
981
982    static const int32_t geo_correction_map_size[] = {gCamCapability[cameraId]->geo_correction_map_size.width,
983                                                            gCamCapability[cameraId]->geo_correction_map_size.height};
984    staticInfo.update(ANDROID_LENS_INFO_GEOMETRIC_CORRECTION_MAP_SIZE,
985            geo_correction_map_size,
986            sizeof(geo_correction_map_size)/sizeof(int32_t));
987
988    staticInfo.update(ANDROID_LENS_INFO_GEOMETRIC_CORRECTION_MAP,
989                       gCamCapability[cameraId]->geo_correction_map,
990            sizeof(gCamCapability[cameraId]->geo_correction_map_size)/ sizeof(cam_dimension_t));
991
992    staticInfo.update(ANDROID_SENSOR_INFO_PHYSICAL_SIZE,
993            gCamCapability[cameraId]->sensor_physical_size, 2);
994
995    staticInfo.update(ANDROID_SENSOR_INFO_EXPOSURE_TIME_RANGE,
996            gCamCapability[cameraId]->exposure_time_range, 2);
997
998    staticInfo.update(ANDROID_SENSOR_INFO_MAX_FRAME_DURATION,
999            &gCamCapability[cameraId]->max_frame_duration, 1);
1000
1001
1002    staticInfo.update(ANDROID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT,
1003                     (int*)&gCamCapability[cameraId]->color_arrangement, 1);
1004
1005    static const int32_t pixel_array_size[] = {gCamCapability[cameraId]->pixel_array_size.width,
1006                                               gCamCapability[cameraId]->pixel_array_size.height};
1007    staticInfo.update(ANDROID_SENSOR_INFO_PIXEL_ARRAY_SIZE,
1008                      pixel_array_size, 2);
1009
1010    static const int32_t active_array_size[] = {gCamCapability[cameraId]->active_array_size.width,
1011                                                gCamCapability[cameraId]->active_array_size.height};
1012    staticInfo.update(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE,
1013                      active_array_size, 2);
1014
1015    staticInfo.update(ANDROID_SENSOR_INFO_WHITE_LEVEL,
1016            &gCamCapability[cameraId]->white_level, 1);
1017
1018    staticInfo.update(ANDROID_SENSOR_BLACK_LEVEL_PATTERN,
1019            gCamCapability[cameraId]->black_level_pattern, 4);
1020
1021    staticInfo.update(ANDROID_FLASH_INFO_CHARGE_DURATION,
1022                      &gCamCapability[cameraId]->flash_charge_duration, 1);
1023
1024    staticInfo.update(ANDROID_TONEMAP_MAX_CURVE_POINTS,
1025                      &gCamCapability[cameraId]->max_tone_map_curve_points, 1);
1026
1027    staticInfo.update(ANDROID_STATISTICS_INFO_MAX_FACE_COUNT,
1028                      (int*)&gCamCapability[cameraId]->max_face_detection_count, 1);
1029
1030    staticInfo.update(ANDROID_STATISTICS_INFO_HISTOGRAM_BUCKET_COUNT,
1031                      &gCamCapability[cameraId]->histogram_size, 1);
1032
1033    staticInfo.update(ANDROID_STATISTICS_INFO_MAX_HISTOGRAM_COUNT,
1034            &gCamCapability[cameraId]->max_histogram_count, 1);
1035
1036    static const int32_t sharpness_map_size[] = {gCamCapability[cameraId]->sharpness_map_size.width,
1037                                                gCamCapability[cameraId]->sharpness_map_size.height};
1038
1039    staticInfo.update(ANDROID_STATISTICS_INFO_SHARPNESS_MAP_SIZE,
1040            sharpness_map_size, sizeof(sharpness_map_size)/sizeof(int32_t));
1041
1042    staticInfo.update(ANDROID_STATISTICS_INFO_MAX_SHARPNESS_MAP_VALUE,
1043            &gCamCapability[cameraId]->max_sharpness_map_value, 1);
1044
1045
1046    staticInfo.update(ANDROID_SCALER_AVAILABLE_RAW_MIN_DURATIONS,
1047                      &gCamCapability[cameraId]->raw_min_duration,
1048                       1);
1049
1050    static int32_t scalar_formats[CAM_FORMAT_MAX];
1051    for (int i = 0; i < gCamCapability[cameraId]->supported_scalar_format_cnt; i++) {
1052        scalar_formats[i] = getScalarFormat(gCamCapability[cameraId]->supported_scalar_fmts[i]);
1053    }
1054    staticInfo.update(ANDROID_SCALER_AVAILABLE_FORMATS,
1055                      scalar_formats,
1056                      sizeof(scalar_formats)/sizeof(int32_t));
1057
1058    static int32_t available_processed_sizes[CAM_FORMAT_MAX];
1059    makeTable(gCamCapability[cameraId]->supported_sizes_tbl,
1060              gCamCapability[cameraId]->supported_sizes_tbl_cnt,
1061              available_processed_sizes);
1062    staticInfo.update(ANDROID_SCALER_AVAILABLE_PROCESSED_SIZES,
1063                available_processed_sizes,
1064                sizeof(available_processed_sizes)/sizeof(int32_t));
1065    #else
1066    const float minFocusDistance = 0;
1067    staticInfo.update(ANDROID_LENS_INFO_MINIMUM_FOCUS_DISTANCE,
1068                    &minFocusDistance, 1);
1069
1070    const float hyperFocusDistance = 0;
1071    staticInfo.update(ANDROID_LENS_INFO_HYPERFOCAL_DISTANCE,
1072                     &hyperFocusDistance, 1);
1073
1074    static const float focalLength = 3.30f;
1075    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS,
1076                      &focalLength,
1077                      1);
1078
1079    static const float aperture = 2.8f;
1080    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_APERTURES,
1081                      &aperture,
1082                      1);
1083
1084    static const float filterDensity = 0;
1085    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_FILTER_DENSITIES,
1086                      &filterDensity, 1);
1087
1088    static const uint8_t availableOpticalStabilization =
1089            ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
1090    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION,
1091                      &availableOpticalStabilization, 1);
1092
1093    float lensPosition[3];
1094    if (facingBack) {
1095        // Back-facing camera is center-top on device
1096        lensPosition[0] = 0;
1097        lensPosition[1] = 20;
1098        lensPosition[2] = -5;
1099    } else {
1100        // Front-facing camera is center-right on device
1101        lensPosition[0] = 20;
1102        lensPosition[1] = 20;
1103        lensPosition[2] = 0;
1104    }
1105    staticInfo.update(ANDROID_LENS_POSITION,
1106                      lensPosition,
1107                      sizeof(lensPosition)/ sizeof(float));
1108
1109    static const int32_t lensShadingMapSize[] = {1, 1};
1110    staticInfo.update(ANDROID_LENS_INFO_SHADING_MAP_SIZE,
1111                      lensShadingMapSize,
1112                      sizeof(lensShadingMapSize)/sizeof(int32_t));
1113
1114    static const float lensShadingMap[3 * 1 * 1 ] =
1115            { 1.f, 1.f, 1.f };
1116    staticInfo.update(ANDROID_LENS_INFO_SHADING_MAP,
1117                      lensShadingMap,
1118                      sizeof(lensShadingMap)/ sizeof(float));
1119
1120    static const int32_t geometricCorrectionMapSize[] = {2, 2};
1121    staticInfo.update(ANDROID_LENS_INFO_GEOMETRIC_CORRECTION_MAP_SIZE,
1122                      geometricCorrectionMapSize,
1123                      sizeof(geometricCorrectionMapSize)/sizeof(int32_t));
1124
1125    static const float geometricCorrectionMap[2 * 3 * 2 * 2] = {
1126            0.f, 0.f,  0.f, 0.f,  0.f, 0.f,
1127            1.f, 0.f,  1.f, 0.f,  1.f, 0.f,
1128            0.f, 1.f,  0.f, 1.f,  0.f, 1.f,
1129            1.f, 1.f,  1.f, 1.f,  1.f, 1.f};
1130    staticInfo.update(ANDROID_LENS_INFO_GEOMETRIC_CORRECTION_MAP,
1131                      geometricCorrectionMap,
1132                      sizeof(geometricCorrectionMap)/ sizeof(float));
1133
1134    static const float sensorPhysicalSize[2] = {3.20f, 2.40f};
1135    staticInfo.update(ANDROID_SENSOR_INFO_PHYSICAL_SIZE,
1136                      sensorPhysicalSize, 2);
1137
1138    const int64_t exposureTimeRange[2] = {1000L, 30000000000L} ; // 1 us - 30 sec
1139    staticInfo.update(ANDROID_SENSOR_INFO_EXPOSURE_TIME_RANGE,
1140                      exposureTimeRange, 2);
1141
1142    const int64_t frameDurationRange[2] = {33331760L, 30000000000L};
1143    staticInfo.update(ANDROID_SENSOR_INFO_MAX_FRAME_DURATION,
1144                      frameDurationRange, 1);
1145
1146    const uint8_t colorFilterArrangement =
1147                         ANDROID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB;
1148    staticInfo.update(ANDROID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT,
1149                      &colorFilterArrangement, 1);
1150
1151    const int resolution[2]  = {640, 480};
1152    staticInfo.update(ANDROID_SENSOR_INFO_PIXEL_ARRAY_SIZE,
1153                      resolution, 2);
1154
1155    staticInfo.update(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE,
1156                      resolution, 2);
1157
1158    const uint32_t whiteLevel = 4000;
1159    staticInfo.update(ANDROID_SENSOR_INFO_WHITE_LEVEL,
1160                      (int32_t*)&whiteLevel, 1);
1161
1162    static const int32_t blackLevelPattern[4] = {
1163            1000, 1000,
1164            1000, 1000 };
1165    staticInfo.update(ANDROID_SENSOR_BLACK_LEVEL_PATTERN,
1166                      blackLevelPattern, 4);
1167
1168    static const int64_t flashChargeDuration = 0;
1169    staticInfo.update(ANDROID_FLASH_INFO_CHARGE_DURATION,
1170                      &flashChargeDuration, 1);
1171
1172    static const int32_t tonemapCurvePoints = 128;
1173    staticInfo.update(ANDROID_TONEMAP_MAX_CURVE_POINTS,
1174                      &tonemapCurvePoints, 1);
1175
1176    static const int32_t maxFaceCount = 8;
1177    staticInfo.update(ANDROID_STATISTICS_INFO_MAX_FACE_COUNT,
1178                      &maxFaceCount, 1);
1179
1180    static const int32_t histogramSize = 64;
1181    staticInfo.update(ANDROID_STATISTICS_INFO_HISTOGRAM_BUCKET_COUNT,
1182                      &histogramSize, 1);
1183
1184    static const int32_t maxHistogramCount = 1000;
1185    staticInfo.update(ANDROID_STATISTICS_INFO_MAX_HISTOGRAM_COUNT,
1186                      &maxHistogramCount, 1);
1187
1188    static const int32_t sharpnessMapSize[2] = {64, 64};
1189    staticInfo.update(ANDROID_STATISTICS_INFO_SHARPNESS_MAP_SIZE,
1190                      sharpnessMapSize, sizeof(sharpnessMapSize)/sizeof(int32_t));
1191
1192    static const int32_t maxSharpnessMapValue = 1000;
1193    staticInfo.update(ANDROID_STATISTICS_INFO_MAX_SHARPNESS_MAP_VALUE,
1194                      &maxSharpnessMapValue, 1);
1195
1196    static const uint8_t availableVstabModes[] = {ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF};
1197    staticInfo.update(ANDROID_CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES,
1198                      availableVstabModes, sizeof(availableVstabModes));
1199
1200    const uint64_t availableRawMinDurations[1] = {33331760L};
1201    staticInfo.update(ANDROID_SCALER_AVAILABLE_RAW_MIN_DURATIONS,
1202                      (int64_t*)&availableRawMinDurations,
1203                       1);
1204
1205    const uint32_t availableFormats[4] = {
1206        HAL_PIXEL_FORMAT_RAW_SENSOR,
1207        HAL_PIXEL_FORMAT_BLOB,
1208        HAL_PIXEL_FORMAT_RGBA_8888,
1209        HAL_PIXEL_FORMAT_YCrCb_420_SP
1210    };
1211    staticInfo.update(ANDROID_SCALER_AVAILABLE_FORMATS,
1212                      (int32_t*)availableFormats,
1213                      4);
1214
1215    const uint32_t availableProcessedSizes[4] = {640, 480, 320, 240};
1216    staticInfo.update(ANDROID_SCALER_AVAILABLE_PROCESSED_SIZES,
1217                      (int32_t*)availableProcessedSizes,
1218                      sizeof(availableProcessedSizes)/sizeof(int32_t));
1219
1220    staticInfo.update(ANDROID_SCALER_AVAILABLE_JPEG_SIZES,
1221                      resolution,
1222                     sizeof(resolution)/sizeof(int));
1223
1224    static const uint8_t availableFaceDetectModes[] = {
1225        ANDROID_STATISTICS_FACE_DETECT_MODE_OFF };
1226
1227    staticInfo.update(ANDROID_STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES,
1228                      availableFaceDetectModes,
1229                      sizeof(availableFaceDetectModes));
1230
1231    static const uint8_t availableSceneModes[] = {
1232            ANDROID_CONTROL_SCENE_MODE_UNSUPPORTED };
1233
1234    staticInfo.update(ANDROID_CONTROL_AVAILABLE_SCENE_MODES,
1235            availableSceneModes, sizeof(availableSceneModes));
1236
1237    static const int32_t availableFpsRanges[] = {15, 30};
1238    staticInfo.update(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES,
1239            availableFpsRanges, sizeof(availableFpsRanges)/sizeof(int32_t));
1240
1241    static const uint8_t availableEffectsModes[] = {
1242            ANDROID_CONTROL_EFFECT_MODE_OFF };
1243    staticInfo.update(ANDROID_CONTROL_AVAILABLE_EFFECTS,
1244            availableEffectsModes, sizeof(availableEffectsModes));
1245
1246    static const uint8_t availableAntibandingModes[] = {
1247            ANDROID_CONTROL_AE_ANTIBANDING_MODE_OFF };
1248    staticInfo.update(ANDROID_CONTROL_AE_AVAILABLE_ANTIBANDING_MODES,
1249            availableAntibandingModes, sizeof(availableAntibandingModes));
1250
1251    static const uint8_t flashAvailable = 0;
1252    staticInfo.update(ANDROID_FLASH_INFO_AVAILABLE,
1253            &flashAvailable, sizeof(flashAvailable));
1254
1255    static const int32_t max3aRegions = 0;
1256    staticInfo.update(ANDROID_CONTROL_MAX_REGIONS,
1257            &max3aRegions, 1);
1258
1259    static const camera_metadata_rational exposureCompensationStep = {
1260            1, 3
1261    };
1262    staticInfo.update(ANDROID_CONTROL_AE_COMPENSATION_STEP,
1263            &exposureCompensationStep, 1);
1264
1265    static const int32_t jpegThumbnailSizes[] = {
1266            0, 0,
1267            160, 120,
1268            320, 240
1269     };
1270    staticInfo.update(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES,
1271            jpegThumbnailSizes, sizeof(jpegThumbnailSizes)/sizeof(int32_t));
1272
1273    static const int32_t maxZoom = 10;
1274    staticInfo.update(ANDROID_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM,
1275            &maxZoom, 1);
1276
1277    static int64_t jpegMinDuration[] = {33331760L, 30000000000L};
1278    staticInfo.update(ANDROID_SCALER_AVAILABLE_JPEG_MIN_DURATIONS,
1279                      jpegMinDuration,
1280                      sizeof(jpegMinDuration)/sizeof(uint64_t));
1281    #endif
1282     /*HAL 1 and HAL 3 common*/
1283     static const int32_t raw_size[] = {gCamCapability[cameraId]->raw_dim.width,
1284                                       gCamCapability[cameraId]->raw_dim.height};
1285    staticInfo.update(ANDROID_SCALER_AVAILABLE_RAW_SIZES,
1286                      raw_size,
1287                      sizeof(raw_size)/sizeof(uint32_t));
1288
1289    static const int32_t exposureCompensationRange[] = {gCamCapability[cameraId]->exposure_compensation_min,
1290                                                        gCamCapability[cameraId]->exposure_compensation_max};
1291    staticInfo.update(ANDROID_CONTROL_AE_COMPENSATION_RANGE,
1292            exposureCompensationRange,
1293            sizeof(exposureCompensationRange)/sizeof(int32_t));
1294
1295    uint8_t lensFacing = (facingBack) ?
1296            ANDROID_LENS_FACING_BACK : ANDROID_LENS_FACING_FRONT;
1297    staticInfo.update(ANDROID_LENS_FACING, &lensFacing, 1);
1298
1299    static int32_t available_jpeg_sizes[MAX_SIZES_CNT];
1300    makeTable(gCamCapability[cameraId]->picture_sizes_tbl,
1301              gCamCapability[cameraId]->picture_sizes_tbl_cnt,
1302              available_jpeg_sizes);
1303    staticInfo.update(ANDROID_SCALER_AVAILABLE_JPEG_SIZES,
1304                available_jpeg_sizes,
1305                sizeof(available_jpeg_sizes)/sizeof(int32_t));
1306
1307    static int32_t avail_effects[CAM_EFFECT_MODE_MAX];
1308    for (int i = 0; i < gCamCapability[cameraId]->supported_effects_cnt; i++) {
1309        avail_effects[i] = lookupFwkName(EFFECT_MODES_MAP,
1310                                         sizeof(EFFECT_MODES_MAP)/sizeof(int),
1311                                         gCamCapability[cameraId]->supported_effects[i]);
1312    }
1313    staticInfo.update(ANDROID_CONTROL_AVAILABLE_EFFECTS,
1314                      avail_effects,
1315                      sizeof(avail_effects)/sizeof(int32_t));
1316
1317    static int32_t avail_scene_modes[CAM_SCENE_MODE_MAX];
1318    for (int i = 0; i < gCamCapability[cameraId]->supported_scene_modes_cnt; i++) {
1319        avail_scene_modes[i] = lookupFwkName(SCENE_MODES_MAP,
1320                                         sizeof(SCENE_MODES_MAP)/sizeof(int),
1321                                         gCamCapability[cameraId]->supported_scene_modes[i]);
1322    }
1323    staticInfo.update(ANDROID_CONTROL_AVAILABLE_SCENE_MODES,
1324                      avail_scene_modes,
1325                      sizeof(avail_scene_modes)/sizeof(int32_t));
1326
1327    static int32_t avail_antibanding_modes[CAM_ANTIBANDING_MODE_MAX];
1328    for (int i = 0; i < gCamCapability[cameraId]->supported_antibandings_cnt; i++) {
1329        avail_antibanding_modes[i] = lookupFwkName(ANTIBANDING_MODES_MAP,
1330                                         sizeof(ANTIBANDING_MODES_MAP)/sizeof(int),
1331                                         gCamCapability[cameraId]->supported_antibandings[i]);
1332    }
1333    staticInfo.update(ANDROID_CONTROL_AE_AVAILABLE_ANTIBANDING_MODES,
1334                      avail_antibanding_modes,
1335                      sizeof(avail_antibanding_modes)/sizeof(int32_t));
1336
1337    static uint8_t avail_af_modes[CAM_FOCUS_MODE_MAX];
1338    for (int i = 0; i < gCamCapability[cameraId]->supported_focus_modes_cnt; i++) {
1339        avail_af_modes[i] = lookupFwkName(FOCUS_MODES_MAP,
1340                                         sizeof(FOCUS_MODES_MAP)/sizeof(int),
1341                                         gCamCapability[cameraId]->supported_focus_modes[i]);
1342    }
1343    staticInfo.update(ANDROID_CONTROL_AF_AVAILABLE_MODES,
1344                      avail_af_modes,
1345                      sizeof(avail_af_modes));
1346
1347    static int32_t avail_awb_modes[CAM_WB_MODE_MAX];
1348    for (int i = 0; i < gCamCapability[cameraId]->supported_white_balances_cnt; i++) {
1349        avail_awb_modes[i] = lookupFwkName(WHITE_BALANCE_MODES_MAP,
1350                                         sizeof(WHITE_BALANCE_MODES_MAP)/sizeof(int),
1351                                         gCamCapability[cameraId]->supported_white_balances[i]);
1352    }
1353    staticInfo.update(ANDROID_CONTROL_AWB_AVAILABLE_MODES,
1354                      avail_awb_modes,
1355                      sizeof(avail_awb_modes)/sizeof(int32_t));
1356
1357    static int32_t avail_flash_modes[CAM_FLASH_MODE_MAX];
1358    for (int i = 0; i < gCamCapability[cameraId]->supported_flash_modes_cnt; i++) {
1359        avail_flash_modes[i] = lookupFwkName(FLASH_MODES_MAP,
1360                                         sizeof(FLASH_MODES_MAP)/sizeof(int),
1361                                         gCamCapability[cameraId]->supported_flash_modes[i]);
1362    }
1363    staticInfo.update(ANDROID_FLASH_MODE,
1364                      avail_flash_modes,
1365                      sizeof(avail_flash_modes)/sizeof(int32_t));
1366
1367    /*so far fwk seems to support only 2 aec modes on and off*/
1368    static const uint8_t avail_ae_modes[] = {
1369            ANDROID_CONTROL_AE_MODE_OFF,
1370            ANDROID_CONTROL_AE_MODE_ON
1371    };
1372    staticInfo.update(ANDROID_CONTROL_AE_AVAILABLE_MODES,
1373                      avail_ae_modes,
1374                      sizeof(avail_ae_modes));
1375
1376    gStaticMetadata = staticInfo.release();
1377    return rc;
1378}
1379
1380/*===========================================================================
1381 * FUNCTION   : makeTable
1382 *
1383 * DESCRIPTION: make a table of sizes
1384 *
1385 * PARAMETERS :
1386 *
1387 *
1388 *
1389 * RETURN     : int32_t type of status
1390 *              NO_ERROR  -- success
1391 *              none-zero failure code
1392 *==========================================================================*/
1393void QCamera3HardwareInterface::makeTable(cam_dimension_t* dimTable, uint8_t size,
1394                                          int32_t* sizeTable)
1395{
1396    int j = 0;
1397    for (int i = 0; i < size; i++) {
1398        sizeTable[j] = dimTable[i].width;
1399        sizeTable[j+1] = dimTable[i].height;
1400        j+=2;
1401    }
1402}
1403/*===========================================================================
1404 * FUNCTION   : getPreviewHalPixelFormat
1405 *
1406 * DESCRIPTION: convert the format to type recognized by framework
1407 *
1408 * PARAMETERS : format : the format from backend
1409 *
1410 ** RETURN    : format recognized by framework
1411 *
1412 *==========================================================================*/
1413int32_t QCamera3HardwareInterface::getScalarFormat(int32_t format)
1414{
1415    int32_t halPixelFormat;
1416
1417    switch (format) {
1418    case CAM_FORMAT_YUV_420_NV12:
1419        halPixelFormat = HAL_PIXEL_FORMAT_YCbCr_420_SP;
1420        break;
1421    case CAM_FORMAT_YUV_420_NV21:
1422        halPixelFormat = HAL_PIXEL_FORMAT_YCrCb_420_SP;
1423        break;
1424    case CAM_FORMAT_YUV_420_NV21_ADRENO:
1425        halPixelFormat = HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO;
1426        break;
1427    case CAM_FORMAT_YUV_420_YV12:
1428        halPixelFormat = HAL_PIXEL_FORMAT_YV12;
1429        break;
1430    case CAM_FORMAT_YUV_422_NV16:
1431    case CAM_FORMAT_YUV_422_NV61:
1432    default:
1433        halPixelFormat = HAL_PIXEL_FORMAT_YCrCb_420_SP;
1434        break;
1435    }
1436    return halPixelFormat;
1437}
1438
1439/*===========================================================================
1440 * FUNCTION   : AddSetParmEntryToBatch
1441 *
1442 * DESCRIPTION: add set parameter entry into batch
1443 *
1444 * PARAMETERS :
1445 *   @p_table     : ptr to parameter buffer
1446 *   @paramType   : parameter type
1447 *   @paramLength : length of parameter value
1448 *   @paramValue  : ptr to parameter value
1449 *
1450 * RETURN     : int32_t type of status
1451 *              NO_ERROR  -- success
1452 *              none-zero failure code
1453 *==========================================================================*/
1454int32_t QCamera3HardwareInterface::AddSetParmEntryToBatch(parm_buffer_t *p_table,
1455                                                          cam_intf_parm_type_t paramType,
1456                                                          uint32_t paramLength,
1457                                                          void *paramValue)
1458{
1459    int position = paramType;
1460    int current, next;
1461
1462    /*************************************************************************
1463    *                 Code to take care of linking next flags                *
1464    *************************************************************************/
1465    current = GET_FIRST_PARAM_ID(p_table);
1466    if (position == current){
1467        //DO NOTHING
1468    } else if (position < current){
1469        SET_NEXT_PARAM_ID(position, p_table, current);
1470        SET_FIRST_PARAM_ID(p_table, position);
1471    } else {
1472        /* Search for the position in the linked list where we need to slot in*/
1473        while (position > GET_NEXT_PARAM_ID(current, p_table))
1474            current = GET_NEXT_PARAM_ID(current, p_table);
1475
1476        /*If node already exists no need to alter linking*/
1477        if (position != GET_NEXT_PARAM_ID(current, p_table)) {
1478            next = GET_NEXT_PARAM_ID(current, p_table);
1479            SET_NEXT_PARAM_ID(current, p_table, position);
1480            SET_NEXT_PARAM_ID(position, p_table, next);
1481        }
1482    }
1483
1484    /*************************************************************************
1485    *                   Copy contents into entry                             *
1486    *************************************************************************/
1487
1488    if (paramLength > sizeof(parm_type_t)) {
1489        ALOGE("%s:Size of input larger than max entry size",__func__);
1490        return BAD_VALUE;
1491    }
1492    memcpy(POINTER_OF(paramType,p_table), paramValue, paramLength);
1493    return NO_ERROR;
1494}
1495
1496/*===========================================================================
1497 * FUNCTION   : lookupFwkName
1498 *
1499 * DESCRIPTION: In case the enum is not same in fwk and backend
1500 *              make sure the parameter is correctly propogated
1501 *
1502 * PARAMETERS  :
1503 *   @arr      : map between the two enums
1504 *   @len      : len of the map
1505 *   @hal_name : name of the hal_parm to map
1506 *
1507 * RETURN     : int type of status
1508 *              fwk_name  -- success
1509 *              none-zero failure code
1510 *==========================================================================*/
1511int QCamera3HardwareInterface::lookupFwkName(const QCameraMap arr[],
1512                                             int len, int hal_name)
1513{
1514
1515   for (int i = 0; i < len; i++) {
1516       if (arr[i].hal_name == hal_name)
1517           return arr[i].fwk_name;
1518    }
1519    return NAME_NOT_FOUND;
1520}
1521
1522/*===========================================================================
1523 * FUNCTION   : lookupHalName
1524 *
1525 * DESCRIPTION: In case the enum is not same in fwk and backend
1526 *              make sure the parameter is correctly propogated
1527 *
1528 * PARAMETERS  :
1529 *   @arr      : map between the two enums
1530 *   @len      : len of the map
1531 *   @fwk_name : name of the hal_parm to map
1532 *
1533 * RETURN     : int32_t type of status
1534 *              hal_name  -- success
1535 *              none-zero failure code
1536 *==========================================================================*/
1537int QCamera3HardwareInterface::lookupHalName(const QCameraMap arr[],
1538                                             int len, int fwk_name)
1539{
1540    for (int i = 0; i < len; i++) {
1541       if (arr[i].fwk_name == fwk_name)
1542           return arr[i].hal_name;
1543    }
1544    return NAME_NOT_FOUND;
1545}
1546
1547/*===========================================================================
1548 * FUNCTION   : getCapabilities
1549 *
1550 * DESCRIPTION: query camera capabilities
1551 *
1552 * PARAMETERS :
1553 *   @cameraId  : camera Id
1554 *   @info      : camera info struct to be filled in with camera capabilities
1555 *
1556 * RETURN     : int32_t type of status
1557 *              NO_ERROR  -- success
1558 *              none-zero failure code
1559 *==========================================================================*/
1560int QCamera3HardwareInterface::getCamInfo(int cameraId,
1561                                    struct camera_info *info)
1562{
1563    int rc = 0;
1564
1565    if (NULL == gCamCapability[cameraId]) {
1566        rc = initCapabilities(cameraId);
1567        if (rc < 0) {
1568            //pthread_mutex_unlock(&g_camlock);
1569            return rc;
1570        }
1571    }
1572
1573    if (NULL == gStaticMetadata) {
1574        rc = initStaticMetadata(cameraId);
1575        if (rc < 0) {
1576            return rc;
1577        }
1578    }
1579
1580    switch(gCamCapability[cameraId]->position) {
1581    case CAM_POSITION_BACK:
1582        info->facing = CAMERA_FACING_BACK;
1583        break;
1584
1585    case CAM_POSITION_FRONT:
1586        info->facing = CAMERA_FACING_FRONT;
1587        break;
1588
1589    default:
1590        ALOGE("%s:Unknown position type for camera id:%d", __func__, cameraId);
1591        rc = -1;
1592        break;
1593    }
1594
1595
1596    info->orientation = gCamCapability[cameraId]->sensor_mount_angle;
1597    info->device_version = HARDWARE_DEVICE_API_VERSION(3, 0);
1598    info->static_camera_characteristics = gStaticMetadata;
1599
1600    return rc;
1601}
1602
1603/*===========================================================================
1604 * FUNCTION   : translateMetadata
1605 *
1606 * DESCRIPTION: translate the metadata into camera_metadata_t
1607 *
1608 * PARAMETERS : type of the request
1609 *
1610 *
1611 * RETURN     : success: camera_metadata_t*
1612 *              failure: NULL
1613 *
1614 *==========================================================================*/
1615camera_metadata_t* QCamera3HardwareInterface::translateToMetadata(int type)
1616{
1617    pthread_mutex_lock(&mMutex);
1618
1619    if (mDefaultMetadata[type] != NULL) {
1620        pthread_mutex_unlock(&mMutex);
1621        return mDefaultMetadata[type];
1622    }
1623    //first time we are handling this request
1624    //fill up the metadata structure using the wrapper class
1625    android::CameraMetadata settings;
1626    //translate from cam_capability_t to camera_metadata_tag_t
1627    static const uint8_t requestType = ANDROID_REQUEST_TYPE_CAPTURE;
1628    settings.update(ANDROID_REQUEST_TYPE, &requestType, 1);
1629
1630    /*control*/
1631
1632    uint8_t controlIntent = 0;
1633    switch (type) {
1634      case CAMERA3_TEMPLATE_PREVIEW:
1635        controlIntent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
1636        break;
1637      case CAMERA3_TEMPLATE_STILL_CAPTURE:
1638        controlIntent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
1639        break;
1640      case CAMERA3_TEMPLATE_VIDEO_RECORD:
1641        controlIntent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
1642        break;
1643      case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
1644        controlIntent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
1645        break;
1646      case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
1647        controlIntent = ANDROID_CONTROL_CAPTURE_INTENT_ZERO_SHUTTER_LAG;
1648        break;
1649      default:
1650        controlIntent = ANDROID_CONTROL_CAPTURE_INTENT_CUSTOM;
1651        break;
1652    }
1653    settings.update(ANDROID_CONTROL_CAPTURE_INTENT, &controlIntent, 1);
1654
1655    settings.update(ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION,
1656            &gCamCapability[mCameraId]->exposure_compensation_default, 1);
1657
1658    static const uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_OFF;
1659    settings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1);
1660
1661    static const uint8_t awbLock = ANDROID_CONTROL_AWB_LOCK_OFF;
1662    settings.update(ANDROID_CONTROL_AWB_LOCK, &awbLock, 1);
1663
1664    static const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
1665    settings.update(ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
1666
1667    static const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
1668    settings.update(ANDROID_CONTROL_MODE, &controlMode, 1);
1669
1670    static const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
1671    settings.update(ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
1672
1673    static const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_FACE_PRIORITY; //similar to AUTO?
1674    settings.update(ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
1675
1676    /*flash*/
1677    static const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
1678    settings.update(ANDROID_FLASH_MODE, &flashMode, 1);
1679
1680
1681    /* lens */
1682    static const float default_aperture = gCamCapability[mCameraId]->apertures[0];
1683    settings.update(ANDROID_LENS_APERTURE, &default_aperture, 1);
1684
1685    static const float default_filter_density = gCamCapability[mCameraId]->filter_densities[0];
1686    settings.update(ANDROID_LENS_FILTER_DENSITY, &default_filter_density, 1);
1687
1688    static const float default_focal_length = gCamCapability[mCameraId]->focal_lengths[0];
1689    settings.update(ANDROID_LENS_FOCAL_LENGTH, &default_focal_length, 1);
1690
1691    mDefaultMetadata[type] = settings.release();
1692
1693    pthread_mutex_unlock(&mMutex);
1694    return mDefaultMetadata[type];
1695}
1696
1697/*===========================================================================
1698 * FUNCTION   : setFrameParameters
1699 *
1700 * DESCRIPTION: set parameters per frame as requested in the metadata from
1701 *              framework
1702 *
1703 * PARAMETERS :
1704 *   @settings  : frame settings information from framework
1705 *
1706 *
1707 * RETURN     : success: NO_ERROR
1708 *              failure:
1709 *==========================================================================*/
1710int QCamera3HardwareInterface::setFrameParameters(int frame_id,
1711                                                  const camera_metadata_t *settings)
1712{
1713    /*translate from camera_metadata_t type to parm_type_t*/
1714    int rc = 0;
1715    if (settings == NULL && mParameters == NULL) {
1716        /*settings cannot be null for the first request*/
1717        return BAD_VALUE;
1718    }
1719    /*we need to update the frame number in the parameters*/
1720    rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_FRAME_NUMBER,
1721                                sizeof(frame_id), &frame_id);
1722    if (rc < 0) {
1723        ALOGE("%s: Failed to set the frame number in the parameters", __func__);
1724        return BAD_VALUE;
1725    }
1726    if(settings != NULL){
1727        rc = translateMetadataToParameters(settings);
1728    }
1729    /*set the parameters to backend*/
1730    mCameraHandle->ops->set_parms(mCameraHandle->camera_handle, mParameters);
1731    return rc;
1732}
1733
1734/*===========================================================================
1735 * FUNCTION   : translateMetadataToParameters
1736 *
1737 * DESCRIPTION: read from the camera_metadata_t and change to parm_type_t
1738 *
1739 *
1740 * PARAMETERS :
1741 *   @settings  : frame settings information from framework
1742 *
1743 *
1744 * RETURN     : success: NO_ERROR
1745 *              failure:
1746 *==========================================================================*/
1747int QCamera3HardwareInterface::translateMetadataToParameters
1748                                  (const camera_metadata_t *settings)
1749{
1750    int rc = 0;
1751    android::CameraMetadata frame_settings;
1752    frame_settings = settings;
1753
1754    //white balance
1755    int32_t fwk_whiteLevel = frame_settings.find(ANDROID_CONTROL_AWB_MODE).data.i32[0];
1756    int whiteLevel = lookupHalName(WHITE_BALANCE_MODES_MAP,
1757                                   sizeof(WHITE_BALANCE_MODES_MAP)/ sizeof(int32_t),
1758                                   fwk_whiteLevel);
1759    rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_PARM_WHITE_BALANCE,
1760                                sizeof(whiteLevel), &whiteLevel);
1761    //effect
1762    int32_t fwk_effectMode = frame_settings.find(ANDROID_CONTROL_EFFECT_MODE).data.i32[0];
1763    int effectMode = lookupHalName(EFFECT_MODES_MAP,
1764                                   sizeof(EFFECT_MODES_MAP)/ sizeof(int32_t),
1765                                   fwk_effectMode);
1766    rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_PARM_EFFECT,
1767                                sizeof(effectMode), &effectMode);
1768    //ae mode
1769    int32_t fwk_aeMode = frame_settings.find(ANDROID_CONTROL_AE_MODE).data.i32[0];
1770    int aeMode = lookupHalName(AUTO_EXPOSURE_MAP,
1771                               sizeof(AUTO_EXPOSURE_MAP)/ sizeof(int32_t),
1772                               fwk_aeMode);
1773    rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_AEC_MODE,
1774                                sizeof(aeMode), &aeMode);
1775
1776    //scaler crop region
1777    int32_t scalerCropRegion = frame_settings.find(ANDROID_SCALER_CROP_REGION).data.i32[0];
1778    rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_SCALER_CROP_REGION,
1779                                sizeof(scalerCropRegion), &scalerCropRegion);
1780
1781    //capture_intent
1782    int32_t captureIntent = frame_settings.find(ANDROID_CONTROL_CAPTURE_INTENT).data.i32[0];
1783    rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_CAPTURE_INTENT,
1784                                sizeof(captureIntent), &captureIntent);
1785
1786    return rc;
1787}
1788
1789/*===========================================================================
1790 * FUNCTION   : translateMetadataToParameters
1791 *
1792 * DESCRIPTION: read from the camera_metadata_t and change to parm_type_t
1793 *
1794 *
1795 * PARAMETERS :
1796 *   @settings  : frame settings information from framework
1797 *
1798 *
1799 * RETURN     : success: NO_ERROR
1800 *              failure:
1801 *==========================================================================*/
1802int QCamera3HardwareInterface::getJpegSettings
1803                                  (const camera_metadata_t *settings)
1804{
1805    if (mJpegSettings) {
1806        free(mJpegSettings);
1807        mJpegSettings = NULL;
1808    }
1809    mJpegSettings = (jpeg_settings_t*) malloc(sizeof(jpeg_settings_t));
1810    android::CameraMetadata jpeg_settings;
1811    jpeg_settings = settings;
1812
1813    mJpegSettings->jpeg_orientation =
1814        jpeg_settings.find(ANDROID_JPEG_ORIENTATION).data.i32[0];
1815    mJpegSettings->jpeg_quality =
1816        jpeg_settings.find(ANDROID_JPEG_QUALITY).data.u8[0];
1817    mJpegSettings->thumbnail_size.height =
1818        jpeg_settings.find(ANDROID_JPEG_THUMBNAIL_SIZE).data.i32[0];
1819    mJpegSettings->thumbnail_size.height =
1820        jpeg_settings.find(ANDROID_JPEG_THUMBNAIL_SIZE).data.i32[1];
1821    for (int i = 0; i < 3; i++) {
1822        mJpegSettings->gps_coordinates[i] =
1823            jpeg_settings.find(ANDROID_JPEG_THUMBNAIL_SIZE).data.d[i];
1824    }
1825    mJpegSettings->gps_timestamp =
1826        jpeg_settings.find(ANDROID_JPEG_GPS_TIMESTAMP).data.i64[0];
1827    mJpegSettings->gps_processing_method =
1828        jpeg_settings.find(ANDROID_JPEG_GPS_PROCESSING_METHOD).data.u8[0];
1829    mJpegSettings->sensor_sensitivity =
1830        jpeg_settings.find(ANDROID_SENSOR_SENSITIVITY).data.i32[0];
1831    mJpegSettings->lens_focal_length =
1832        jpeg_settings.find(ANDROID_LENS_FOCAL_LENGTH).data.f[0];
1833    return 0;
1834}
1835
1836/*===========================================================================
1837 * FUNCTION   : captureResultCb
1838 *
1839 * DESCRIPTION: Callback handler for all channels (streams, as well as metadata)
1840 *
1841 * PARAMETERS :
1842 *   @frame  : frame information from mm-camera-interface
1843 *   @buffer : actual gralloc buffer to be returned to frameworks. NULL if metadata.
1844 *   @userdata: userdata
1845 *
1846 * RETURN     : NONE
1847 *==========================================================================*/
1848void QCamera3HardwareInterface::captureResultCb(metadata_buffer_t *metadata,
1849                camera3_stream_buffer_t *buffer,
1850                uint32_t frame_number, void *userdata)
1851{
1852    QCamera3HardwareInterface *hw = (QCamera3HardwareInterface *)userdata;
1853    if (hw == NULL) {
1854        ALOGE("%s: Invalid hw %p", __func__, hw);
1855        return;
1856    }
1857
1858    hw->captureResultCb(metadata, buffer, frame_number);
1859    return;
1860}
1861
1862/*===========================================================================
1863 * FUNCTION   : initialize
1864 *
1865 * DESCRIPTION: Pass framework callback pointers to HAL
1866 *
1867 * PARAMETERS :
1868 *
1869 *
1870 * RETURN     : Success : 0
1871 *              Failure: -ENODEV
1872 *==========================================================================*/
1873
1874int QCamera3HardwareInterface::initialize(const struct camera3_device *device,
1875                                  const camera3_callback_ops_t *callback_ops)
1876{
1877    QCamera3HardwareInterface *hw =
1878        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
1879    if (!hw) {
1880        ALOGE("%s: NULL camera device", __func__);
1881        return -ENODEV;
1882    }
1883
1884    return hw->initialize(callback_ops);
1885}
1886
1887/*===========================================================================
1888 * FUNCTION   : configure_streams
1889 *
1890 * DESCRIPTION:
1891 *
1892 * PARAMETERS :
1893 *
1894 *
1895 * RETURN     : Success: 0
1896 *              Failure: -EINVAL (if stream configuration is invalid)
1897 *                       -ENODEV (fatal error)
1898 *==========================================================================*/
1899
1900int QCamera3HardwareInterface::configure_streams(
1901        const struct camera3_device *device,
1902        camera3_stream_configuration_t *stream_list)
1903{
1904    QCamera3HardwareInterface *hw =
1905        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
1906    if (!hw) {
1907        ALOGE("%s: NULL camera device", __func__);
1908        return -ENODEV;
1909    }
1910    return hw->configureStreams(stream_list);
1911}
1912
1913/*===========================================================================
1914 * FUNCTION   : register_stream_buffers
1915 *
1916 * DESCRIPTION: Register stream buffers with the device
1917 *
1918 * PARAMETERS :
1919 *
1920 * RETURN     :
1921 *==========================================================================*/
1922int QCamera3HardwareInterface::register_stream_buffers(
1923        const struct camera3_device *device,
1924        const camera3_stream_buffer_set_t *buffer_set)
1925{
1926    QCamera3HardwareInterface *hw =
1927        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
1928    if (!hw) {
1929        ALOGE("%s: NULL camera device", __func__);
1930        return -ENODEV;
1931    }
1932    return hw->registerStreamBuffers(buffer_set);
1933}
1934
1935/*===========================================================================
1936 * FUNCTION   : construct_default_request_settings
1937 *
1938 * DESCRIPTION: Configure a settings buffer to meet the required use case
1939 *
1940 * PARAMETERS :
1941 *
1942 *
1943 * RETURN     : Success: Return valid metadata
1944 *              Failure: Return NULL
1945 *==========================================================================*/
1946const camera_metadata_t* QCamera3HardwareInterface::
1947    construct_default_request_settings(const struct camera3_device *device,
1948                                        int type)
1949{
1950
1951    camera_metadata_t* fwk_metadata = NULL;
1952    QCamera3HardwareInterface *hw =
1953        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
1954    if (!hw) {
1955        ALOGE("%s: NULL camera device", __func__);
1956        return NULL;
1957    }
1958
1959    fwk_metadata = hw->translateToMetadata(type);
1960
1961    return fwk_metadata;
1962}
1963
1964/*===========================================================================
1965 * FUNCTION   : process_capture_request
1966 *
1967 * DESCRIPTION:
1968 *
1969 * PARAMETERS :
1970 *
1971 *
1972 * RETURN     :
1973 *==========================================================================*/
1974int QCamera3HardwareInterface::process_capture_request(
1975                    const struct camera3_device *device,
1976                    camera3_capture_request_t *request)
1977{
1978    QCamera3HardwareInterface *hw =
1979        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
1980    if (!hw) {
1981        ALOGE("%s: NULL camera device", __func__);
1982        return -EINVAL;
1983    }
1984
1985    return hw->processCaptureRequest(request);
1986}
1987
1988/*===========================================================================
1989 * FUNCTION   : get_metadata_vendor_tag_ops
1990 *
1991 * DESCRIPTION:
1992 *
1993 * PARAMETERS :
1994 *
1995 *
1996 * RETURN     :
1997 *==========================================================================*/
1998
1999void QCamera3HardwareInterface::get_metadata_vendor_tag_ops(
2000                const struct camera3_device *device,
2001                vendor_tag_query_ops_t* ops)
2002{
2003    QCamera3HardwareInterface *hw =
2004        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
2005    if (!hw) {
2006        ALOGE("%s: NULL camera device", __func__);
2007        return;
2008    }
2009
2010    hw->getMetadataVendorTagOps(ops);
2011    return;
2012}
2013
2014/*===========================================================================
2015 * FUNCTION   : dump
2016 *
2017 * DESCRIPTION:
2018 *
2019 * PARAMETERS :
2020 *
2021 *
2022 * RETURN     :
2023 *==========================================================================*/
2024
2025void QCamera3HardwareInterface::dump(
2026                const struct camera3_device *device, int fd)
2027{
2028    QCamera3HardwareInterface *hw =
2029        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
2030    if (!hw) {
2031        ALOGE("%s: NULL camera device", __func__);
2032        return;
2033    }
2034
2035    hw->dump(fd);
2036    return;
2037}
2038
2039/*===========================================================================
2040 * FUNCTION   : close_camera_device
2041 *
2042 * DESCRIPTION:
2043 *
2044 * PARAMETERS :
2045 *
2046 *
2047 * RETURN     :
2048 *==========================================================================*/
2049int QCamera3HardwareInterface::close_camera_device(struct hw_device_t* device)
2050{
2051    int ret = NO_ERROR;
2052    QCamera3HardwareInterface *hw =
2053        reinterpret_cast<QCamera3HardwareInterface *>(
2054            reinterpret_cast<camera3_device_t *>(device)->priv);
2055    if (!hw) {
2056        ALOGE("NULL camera device");
2057        return BAD_VALUE;
2058    }
2059    delete hw;
2060    return ret;
2061}
2062
2063
2064}; //end namespace qcamera
2065