QCamera3HWI.cpp revision d5d5a90863708ac1cdbef25c41853b6f6f05d4e2
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#include "QCamera3PostProc.h"
44
45using namespace android;
46
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_OFF,             CAM_WB_MODE_OFF },
67    { ANDROID_CONTROL_AWB_MODE_AUTO,            CAM_WB_MODE_AUTO },
68    { ANDROID_CONTROL_AWB_MODE_INCANDESCENT,    CAM_WB_MODE_INCANDESCENT },
69    { ANDROID_CONTROL_AWB_MODE_FLUORESCENT,     CAM_WB_MODE_FLUORESCENT },
70    { ANDROID_CONTROL_AWB_MODE_WARM_FLUORESCENT,CAM_WB_MODE_WARM_FLUORESCENT},
71    { ANDROID_CONTROL_AWB_MODE_DAYLIGHT,        CAM_WB_MODE_DAYLIGHT },
72    { ANDROID_CONTROL_AWB_MODE_CLOUDY_DAYLIGHT, CAM_WB_MODE_CLOUDY_DAYLIGHT },
73    { ANDROID_CONTROL_AWB_MODE_TWILIGHT,        CAM_WB_MODE_TWILIGHT },
74    { ANDROID_CONTROL_AWB_MODE_SHADE,           CAM_WB_MODE_SHADE }
75};
76
77const QCamera3HardwareInterface::QCameraMap QCamera3HardwareInterface::SCENE_MODES_MAP[] = {
78    { ANDROID_CONTROL_SCENE_MODE_UNSUPPORTED,    CAM_SCENE_MODE_OFF },
79    { ANDROID_CONTROL_SCENE_MODE_ACTION,         CAM_SCENE_MODE_ACTION },
80    { ANDROID_CONTROL_SCENE_MODE_PORTRAIT,       CAM_SCENE_MODE_PORTRAIT },
81    { ANDROID_CONTROL_SCENE_MODE_LANDSCAPE,      CAM_SCENE_MODE_LANDSCAPE },
82    { ANDROID_CONTROL_SCENE_MODE_NIGHT,          CAM_SCENE_MODE_NIGHT },
83    { ANDROID_CONTROL_SCENE_MODE_NIGHT_PORTRAIT, CAM_SCENE_MODE_NIGHT_PORTRAIT },
84    { ANDROID_CONTROL_SCENE_MODE_THEATRE,        CAM_SCENE_MODE_THEATRE },
85    { ANDROID_CONTROL_SCENE_MODE_BEACH,          CAM_SCENE_MODE_BEACH },
86    { ANDROID_CONTROL_SCENE_MODE_SNOW,           CAM_SCENE_MODE_SNOW },
87    { ANDROID_CONTROL_SCENE_MODE_SUNSET,         CAM_SCENE_MODE_SUNSET },
88    { ANDROID_CONTROL_SCENE_MODE_STEADYPHOTO,    CAM_SCENE_MODE_ANTISHAKE },
89    { ANDROID_CONTROL_SCENE_MODE_FIREWORKS ,     CAM_SCENE_MODE_FIREWORKS },
90    { ANDROID_CONTROL_SCENE_MODE_SPORTS ,        CAM_SCENE_MODE_SPORTS },
91    { ANDROID_CONTROL_SCENE_MODE_PARTY,          CAM_SCENE_MODE_PARTY },
92    { ANDROID_CONTROL_SCENE_MODE_CANDLELIGHT,    CAM_SCENE_MODE_CANDLELIGHT },
93    { ANDROID_CONTROL_SCENE_MODE_BARCODE,        CAM_SCENE_MODE_BARCODE}
94};
95
96const QCamera3HardwareInterface::QCameraMap QCamera3HardwareInterface::FOCUS_MODES_MAP[] = {
97    { ANDROID_CONTROL_AF_MODE_OFF,                CAM_FOCUS_MODE_OFF },
98    { ANDROID_CONTROL_AF_MODE_OFF,                CAM_FOCUS_MODE_FIXED },
99    { ANDROID_CONTROL_AF_MODE_AUTO,               CAM_FOCUS_MODE_AUTO },
100    { ANDROID_CONTROL_AF_MODE_MACRO,              CAM_FOCUS_MODE_MACRO },
101    { ANDROID_CONTROL_AF_MODE_EDOF,               CAM_FOCUS_MODE_EDOF },
102    { ANDROID_CONTROL_AF_MODE_CONTINUOUS_PICTURE, CAM_FOCUS_MODE_CONTINOUS_PICTURE },
103    { ANDROID_CONTROL_AF_MODE_CONTINUOUS_VIDEO,   CAM_FOCUS_MODE_CONTINOUS_VIDEO }
104};
105
106const QCamera3HardwareInterface::QCameraMap QCamera3HardwareInterface::ANTIBANDING_MODES_MAP[] = {
107    { ANDROID_CONTROL_AE_ANTIBANDING_MODE_OFF,  CAM_ANTIBANDING_MODE_OFF },
108    { ANDROID_CONTROL_AE_ANTIBANDING_MODE_50HZ, CAM_ANTIBANDING_MODE_50HZ },
109    { ANDROID_CONTROL_AE_ANTIBANDING_MODE_60HZ, CAM_ANTIBANDING_MODE_60HZ },
110    { ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO, CAM_ANTIBANDING_MODE_AUTO }
111};
112
113const QCamera3HardwareInterface::QCameraMap QCamera3HardwareInterface::AUTO_EXPOSURE_MAP[] = {
114    { ANDROID_CONTROL_AE_MODE_OFF,    CAM_AEC_MODE_OFF           },
115    { ANDROID_CONTROL_AE_MODE_ON,     CAM_AEC_MODE_FRAME_AVERAGE },
116};
117
118const QCamera3HardwareInterface::QCameraMap QCamera3HardwareInterface::FLASH_MODES_MAP[] = {
119    { ANDROID_FLASH_MODE_OFF,    CAM_FLASH_MODE_OFF  },
120    { ANDROID_FLASH_MODE_SINGLE, CAM_FLASH_MODE_ON   },
121    { ANDROID_FLASH_MODE_TORCH,  CAM_FLASH_MODE_TORCH}
122};
123
124
125camera3_device_ops_t QCamera3HardwareInterface::mCameraOps = {
126    initialize:                         QCamera3HardwareInterface::initialize,
127    configure_streams:                  QCamera3HardwareInterface::configure_streams,
128    register_stream_buffers:            QCamera3HardwareInterface::register_stream_buffers,
129    construct_default_request_settings: QCamera3HardwareInterface::construct_default_request_settings,
130    process_capture_request:            QCamera3HardwareInterface::process_capture_request,
131    get_metadata_vendor_tag_ops:        QCamera3HardwareInterface::get_metadata_vendor_tag_ops,
132    dump:                               QCamera3HardwareInterface::dump,
133};
134
135
136/*===========================================================================
137 * FUNCTION   : QCamera3HardwareInterface
138 *
139 * DESCRIPTION: constructor of QCamera3HardwareInterface
140 *
141 * PARAMETERS :
142 *   @cameraId  : camera ID
143 *
144 * RETURN     : none
145 *==========================================================================*/
146QCamera3HardwareInterface::QCamera3HardwareInterface(int cameraId)
147    : mCameraId(cameraId),
148      mCameraHandle(NULL),
149      mCameraOpened(false),
150      mCallbackOps(NULL),
151      mInputStream(NULL),
152      mMetadataChannel(NULL),
153      mFirstRequest(false),
154      mParamHeap(NULL),
155      mParameters(NULL),
156      mJpegSettings(NULL)
157{
158    mCameraDevice.common.tag = HARDWARE_DEVICE_TAG;
159    mCameraDevice.common.version = CAMERA_DEVICE_API_VERSION_3_0;
160    mCameraDevice.common.close = close_camera_device;
161    mCameraDevice.ops = &mCameraOps;
162    mCameraDevice.priv = this;
163    gCamCapability[cameraId]->version = CAM_HAL_V3;
164
165    pthread_mutex_init(&mRequestLock, NULL);
166    pthread_cond_init(&mRequestCond, NULL);
167    mPendingRequest = 0;
168
169    pthread_mutex_init(&mMutex, NULL);
170    pthread_mutex_init(&mCaptureResultLock, NULL);
171
172    for (size_t i = 0; i < CAMERA3_TEMPLATE_COUNT; i++)
173        mDefaultMetadata[i] = NULL;
174}
175
176/*===========================================================================
177 * FUNCTION   : ~QCamera3HardwareInterface
178 *
179 * DESCRIPTION: destructor of QCamera3HardwareInterface
180 *
181 * PARAMETERS : none
182 *
183 * RETURN     : none
184 *==========================================================================*/
185QCamera3HardwareInterface::~QCamera3HardwareInterface()
186{
187    ALOGV("%s: E", __func__);
188    /* Clean up all channels */
189    mMetadataChannel->stop();
190    delete mMetadataChannel;
191    mMetadataChannel = NULL;
192    /* We need to stop all streams before deleting any stream */
193    for (List<stream_info_t *>::iterator it = mStreamInfo.begin();
194        it != mStreamInfo.end(); it++) {
195        QCamera3Channel *channel = (QCamera3Channel *)(*it)->stream->priv;
196        channel->stop();
197    }
198    for (List<stream_info_t *>::iterator it = mStreamInfo.begin();
199        it != mStreamInfo.end(); it++) {
200        QCamera3Channel *channel = (QCamera3Channel *)(*it)->stream->priv;
201        delete channel;
202        free (*it);
203    }
204
205    if (mJpegSettings != NULL) {
206        free(mJpegSettings);
207        mJpegSettings = NULL;
208    }
209    deinitParameters();
210    closeCamera();
211
212    for (size_t i = 0; i < CAMERA3_TEMPLATE_COUNT; i++)
213        if (mDefaultMetadata[i])
214            free_camera_metadata(mDefaultMetadata[i]);
215
216    pthread_mutex_destroy(&mRequestLock);
217    pthread_cond_destroy(&mRequestCond);
218
219    pthread_mutex_destroy(&mMutex);
220    pthread_mutex_destroy(&mCaptureResultLock);
221    ALOGV("%s: X", __func__);
222}
223
224/*===========================================================================
225 * FUNCTION   : openCamera
226 *
227 * DESCRIPTION: open camera
228 *
229 * PARAMETERS :
230 *   @hw_device  : double ptr for camera device struct
231 *
232 * RETURN     : int32_t type of status
233 *              NO_ERROR  -- success
234 *              none-zero failure code
235 *==========================================================================*/
236int QCamera3HardwareInterface::openCamera(struct hw_device_t **hw_device)
237{
238    //int rc = NO_ERROR;
239    int rc = 0;
240    if (mCameraOpened) {
241        *hw_device = NULL;
242        return PERMISSION_DENIED;
243    }
244
245    rc = openCamera();
246    if (rc == 0)
247        *hw_device = &mCameraDevice.common;
248    else
249        *hw_device = NULL;
250    return rc;
251}
252
253/*===========================================================================
254 * FUNCTION   : openCamera
255 *
256 * DESCRIPTION: open camera
257 *
258 * PARAMETERS : none
259 *
260 * RETURN     : int32_t type of status
261 *              NO_ERROR  -- success
262 *              none-zero failure code
263 *==========================================================================*/
264int QCamera3HardwareInterface::openCamera()
265{
266    if (mCameraHandle) {
267        ALOGE("Failure: Camera already opened");
268        return ALREADY_EXISTS;
269    }
270    mCameraHandle = camera_open(mCameraId);
271    if (!mCameraHandle) {
272        ALOGE("camera_open failed.");
273        return UNKNOWN_ERROR;
274    }
275
276    mCameraOpened = true;
277
278    return NO_ERROR;
279}
280
281/*===========================================================================
282 * FUNCTION   : closeCamera
283 *
284 * DESCRIPTION: close camera
285 *
286 * PARAMETERS : none
287 *
288 * RETURN     : int32_t type of status
289 *              NO_ERROR  -- success
290 *              none-zero failure code
291 *==========================================================================*/
292int QCamera3HardwareInterface::closeCamera()
293{
294    int rc = NO_ERROR;
295
296    rc = mCameraHandle->ops->close_camera(mCameraHandle->camera_handle);
297    mCameraHandle = NULL;
298    mCameraOpened = false;
299
300    return rc;
301}
302
303/*===========================================================================
304 * FUNCTION   : initialize
305 *
306 * DESCRIPTION: Initialize frameworks callback functions
307 *
308 * PARAMETERS :
309 *   @callback_ops : callback function to frameworks
310 *
311 * RETURN     :
312 *
313 *==========================================================================*/
314int QCamera3HardwareInterface::initialize(
315        const struct camera3_callback_ops *callback_ops)
316{
317    int rc;
318
319    pthread_mutex_lock(&mMutex);
320
321    rc = initParameters();
322    if (rc < 0) {
323        ALOGE("%s: initParamters failed %d", __func__, rc);
324       goto err1;
325    }
326    //Create metadata channel and initialize it
327    mMetadataChannel = new QCamera3MetadataChannel(mCameraHandle->camera_handle,
328                    mCameraHandle->ops, captureResultCb,
329                    &gCamCapability[mCameraId]->padding_info, this);
330    if (mMetadataChannel == NULL) {
331        ALOGE("%s: failed to allocate metadata channel", __func__);
332        rc = -ENOMEM;
333        goto err2;
334    }
335    rc = mMetadataChannel->initialize();
336    if (rc < 0) {
337        ALOGE("%s: metadata channel initialization failed", __func__);
338        goto err3;
339    }
340
341    mCallbackOps = callback_ops;
342
343    pthread_mutex_unlock(&mMutex);
344    return 0;
345
346err3:
347    delete mMetadataChannel;
348    mMetadataChannel = NULL;
349err2:
350    deinitParameters();
351err1:
352    pthread_mutex_unlock(&mMutex);
353    return rc;
354}
355
356/*===========================================================================
357 * FUNCTION   : configureStreams
358 *
359 * DESCRIPTION: Reset HAL camera device processing pipeline and set up new input
360 *              and output streams.
361 *
362 * PARAMETERS :
363 *   @stream_list : streams to be configured
364 *
365 * RETURN     :
366 *
367 *==========================================================================*/
368int QCamera3HardwareInterface::configureStreams(
369        camera3_stream_configuration_t *streamList)
370{
371    int rc = 0;
372    pthread_mutex_lock(&mMutex);
373
374    // Sanity check stream_list
375    if (streamList == NULL) {
376        ALOGE("%s: NULL stream configuration", __func__);
377        pthread_mutex_unlock(&mMutex);
378        return BAD_VALUE;
379    }
380
381    if (streamList->streams == NULL) {
382        ALOGE("%s: NULL stream list", __func__);
383        pthread_mutex_unlock(&mMutex);
384        return BAD_VALUE;
385    }
386
387    if (streamList->num_streams < 1) {
388        ALOGE("%s: Bad number of streams requested: %d", __func__,
389                streamList->num_streams);
390        pthread_mutex_unlock(&mMutex);
391        return BAD_VALUE;
392    }
393
394    camera3_stream_t *inputStream = NULL;
395    /* first invalidate all the steams in the mStreamList
396     * if they appear again, they will be validated */
397    for (List<stream_info_t*>::iterator it=mStreamInfo.begin();
398            it != mStreamInfo.end(); it++) {
399        QCamera3Channel *channel = (QCamera3Channel*)(*it)->stream->priv;
400        channel->stop();
401        (*it)->status = INVALID;
402    }
403
404    for (size_t i = 0; i < streamList->num_streams; i++) {
405        camera3_stream_t *newStream = streamList->streams[i];
406        ALOGV("%s: newStream type = %d, stream format = %d",
407                __func__, newStream->stream_type, newStream->format);
408        //if the stream is in the mStreamList validate it
409        bool stream_exists = false;
410        for (List<stream_info_t*>::iterator it=mStreamInfo.begin();
411                it != mStreamInfo.end(); it++) {
412            if ((*it)->stream == newStream) {
413                QCamera3Channel *channel =
414                    (QCamera3Channel*)(*it)->stream->priv;
415                stream_exists = true;
416                (*it)->status = RECONFIGURE;
417                /*delete the channel object associated with the stream because
418                  we need to reconfigure*/
419                delete channel;
420                (*it)->stream->priv = NULL;
421            }
422        }
423        if (!stream_exists) {
424            //new stream
425            stream_info_t* stream_info;
426            stream_info = (stream_info_t* )malloc(sizeof(stream_info_t));
427            stream_info->stream = newStream;
428            stream_info->status = VALID;
429            stream_info->registered = 0;
430            mStreamInfo.push_back(stream_info);
431        }
432        if (newStream->stream_type == CAMERA3_STREAM_INPUT) {
433            if (inputStream != NULL) {
434                ALOGE("%s: Multiple input streams requested!", __func__);
435                pthread_mutex_unlock(&mMutex);
436                return BAD_VALUE;
437            }
438            inputStream = newStream;
439        }
440    }
441    mInputStream = inputStream;
442
443    /*clean up invalid streams*/
444    for (List<stream_info_t*>::iterator it=mStreamInfo.begin();
445            it != mStreamInfo.end();) {
446        if(((*it)->status) == INVALID){
447            QCamera3Channel *channel = (QCamera3Channel*)(*it)->stream->priv;
448            delete channel;
449            delete[] (buffer_handle_t*)(*it)->buffer_set.buffers;
450            free(*it);
451            it = mStreamInfo.erase(it);
452        } else {
453            it++;
454        }
455    }
456
457    //mMetadataChannel->stop();
458
459    /* Allocate channel objects for the requested streams */
460    for (size_t i = 0; i < streamList->num_streams; i++) {
461        camera3_stream_t *newStream = streamList->streams[i];
462        if (newStream->priv == NULL) {
463            //New stream, construct channel
464            switch (newStream->stream_type) {
465            case CAMERA3_STREAM_INPUT:
466                newStream->usage = GRALLOC_USAGE_HW_CAMERA_READ;
467                break;
468            case CAMERA3_STREAM_BIDIRECTIONAL:
469                newStream->usage = GRALLOC_USAGE_HW_CAMERA_READ |
470                    GRALLOC_USAGE_HW_CAMERA_WRITE;
471                break;
472            case CAMERA3_STREAM_OUTPUT:
473                newStream->usage = GRALLOC_USAGE_HW_CAMERA_WRITE;
474                break;
475            default:
476                ALOGE("%s: Invalid stream_type %d", __func__, newStream->stream_type);
477                break;
478            }
479
480            if (newStream->stream_type == CAMERA3_STREAM_OUTPUT ||
481                    newStream->stream_type == CAMERA3_STREAM_BIDIRECTIONAL) {
482                QCamera3Channel *channel;
483                switch (newStream->format) {
484                case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
485                    newStream->max_buffers = QCamera3RegularChannel::kMaxBuffers;
486                    channel = new QCamera3RegularChannel(mCameraHandle->camera_handle,
487                            mCameraHandle->ops, captureResultCb,
488                            &gCamCapability[mCameraId]->padding_info, this, newStream);
489                    if (channel == NULL) {
490                        ALOGE("%s: allocation of channel failed", __func__);
491                        pthread_mutex_unlock(&mMutex);
492                        return -ENOMEM;
493                    }
494
495                    newStream->priv = channel;
496                    break;
497                case HAL_PIXEL_FORMAT_BLOB:
498                    newStream->max_buffers = QCamera3PicChannel::kMaxBuffers;
499                    channel = new QCamera3PicChannel(mCameraHandle->camera_handle,
500                            mCameraHandle->ops, captureResultCb,
501                            &gCamCapability[mCameraId]->padding_info, this, newStream);
502                    if (channel == NULL) {
503                        ALOGE("%s: allocation of channel failed", __func__);
504                        pthread_mutex_unlock(&mMutex);
505                        return -ENOMEM;
506                    }
507                    newStream->priv = channel;
508                    break;
509
510                //TODO: Add support for app consumed format?
511                default:
512                    ALOGE("%s: not a supported format 0x%x", __func__, newStream->format);
513                    break;
514                }
515            }
516        } else {
517            // Channel already exists for this stream
518            // Do nothing for now
519        }
520    }
521    /*For the streams to be reconfigured we need to register the buffers
522      since the framework wont*/
523    for (List<stream_info_t *>::iterator it = mStreamInfo.begin();
524            it != mStreamInfo.end(); it++) {
525        if ((*it)->status == RECONFIGURE) {
526            QCamera3Channel *channel = (QCamera3Channel *)(*it)->stream->priv;
527            /*only register buffers for streams that have already been
528              registered*/
529            if ((*it)->registered) {
530                rc = channel->registerBuffers((*it)->buffer_set.num_buffers,
531                        (*it)->buffer_set.buffers);
532                if (rc != NO_ERROR) {
533                    ALOGE("%s: Failed to register the buffers of old stream,\
534                            rc = %d", __func__, rc);
535                }
536                ALOGD("%s: channel %p has %d buffers",
537                        __func__, channel, (*it)->buffer_set.num_buffers);
538            }
539        }
540
541        ssize_t index = mPendingBuffersMap.indexOfKey((*it)->stream);
542        if (index == NAME_NOT_FOUND) {
543            mPendingBuffersMap.add((*it)->stream, 0);
544        } else {
545            mPendingBuffersMap.editValueAt(index) = 0;
546        }
547    }
548
549    /* Initialize mPendingRequestInfo and mPendnigBuffersMap */
550    mPendingRequestsList.clear();
551
552    //settings/parameters don't carry over for new configureStreams
553    memset(mParameters, 0, sizeof(parm_buffer_t));
554    mFirstRequest = true;
555
556    pthread_mutex_unlock(&mMutex);
557    return rc;
558}
559
560/*===========================================================================
561 * FUNCTION   : validateCaptureRequest
562 *
563 * DESCRIPTION: validate a capture request from camera service
564 *
565 * PARAMETERS :
566 *   @request : request from framework to process
567 *
568 * RETURN     :
569 *
570 *==========================================================================*/
571int QCamera3HardwareInterface::validateCaptureRequest(
572                    camera3_capture_request_t *request)
573{
574    ssize_t idx = 0;
575    const camera3_stream_buffer_t *b;
576    CameraMetadata meta;
577
578    /* Sanity check the request */
579    if (request == NULL) {
580        ALOGE("%s: NULL capture request", __func__);
581        return BAD_VALUE;
582    }
583
584    uint32_t frameNumber = request->frame_number;
585    if (request->input_buffer != NULL &&
586            request->input_buffer->stream != mInputStream) {
587        ALOGE("%s: Request %d: Input buffer not from input stream!",
588                __FUNCTION__, frameNumber);
589        return BAD_VALUE;
590    }
591    if (request->num_output_buffers < 1 || request->output_buffers == NULL) {
592        ALOGE("%s: Request %d: No output buffers provided!",
593                __FUNCTION__, frameNumber);
594        return BAD_VALUE;
595    }
596    if (request->input_buffer != NULL) {
597        //TODO
598        ALOGE("%s: Not supporting input buffer yet", __func__);
599        return BAD_VALUE;
600    }
601
602    // Validate all buffers
603    b = request->output_buffers;
604    do {
605        QCamera3Channel *channel =
606                static_cast<QCamera3Channel*>(b->stream->priv);
607        if (channel == NULL) {
608            ALOGE("%s: Request %d: Buffer %d: Unconfigured stream!",
609                    __func__, frameNumber, idx);
610            return BAD_VALUE;
611        }
612        if (b->status != CAMERA3_BUFFER_STATUS_OK) {
613            ALOGE("%s: Request %d: Buffer %d: Status not OK!",
614                    __func__, frameNumber, idx);
615            return BAD_VALUE;
616        }
617        if (b->release_fence != -1) {
618            ALOGE("%s: Request %d: Buffer %d: Has a release fence!",
619                    __func__, frameNumber, idx);
620            return BAD_VALUE;
621        }
622        if (b->buffer == NULL) {
623            ALOGE("%s: Request %d: Buffer %d: NULL buffer handle!",
624                    __func__, frameNumber, idx);
625            return BAD_VALUE;
626        }
627        idx++;
628        b = request->output_buffers + idx;
629    } while (idx < (ssize_t)request->num_output_buffers);
630
631    return NO_ERROR;
632}
633
634/*===========================================================================
635 * FUNCTION   : registerStreamBuffers
636 *
637 * DESCRIPTION: Register buffers for a given stream with the HAL device.
638 *
639 * PARAMETERS :
640 *   @stream_list : streams to be configured
641 *
642 * RETURN     :
643 *
644 *==========================================================================*/
645int QCamera3HardwareInterface::registerStreamBuffers(
646        const camera3_stream_buffer_set_t *buffer_set)
647{
648    int rc = 0;
649
650    pthread_mutex_lock(&mMutex);
651
652    if (buffer_set == NULL) {
653        ALOGE("%s: Invalid buffer_set parameter.", __func__);
654        pthread_mutex_unlock(&mMutex);
655        return -EINVAL;
656    }
657    if (buffer_set->stream == NULL) {
658        ALOGE("%s: Invalid stream parameter.", __func__);
659        pthread_mutex_unlock(&mMutex);
660        return -EINVAL;
661    }
662    if (buffer_set->num_buffers < 1) {
663        ALOGE("%s: Invalid num_buffers %d.", __func__, buffer_set->num_buffers);
664        pthread_mutex_unlock(&mMutex);
665        return -EINVAL;
666    }
667    if (buffer_set->buffers == NULL) {
668        ALOGE("%s: Invalid buffers parameter.", __func__);
669        pthread_mutex_unlock(&mMutex);
670        return -EINVAL;
671    }
672
673    camera3_stream_t *stream = buffer_set->stream;
674    QCamera3Channel *channel = (QCamera3Channel *)stream->priv;
675
676    //set the buffer_set in the mStreamInfo array
677    for (List<stream_info_t *>::iterator it = mStreamInfo.begin();
678            it != mStreamInfo.end(); it++) {
679        if ((*it)->stream == stream) {
680            uint32_t numBuffers = buffer_set->num_buffers;
681            (*it)->buffer_set.stream = buffer_set->stream;
682            (*it)->buffer_set.num_buffers = numBuffers;
683            (*it)->buffer_set.buffers = new buffer_handle_t*[numBuffers];
684            if ((*it)->buffer_set.buffers == NULL) {
685                ALOGE("%s: Failed to allocate buffer_handle_t*", __func__);
686                pthread_mutex_unlock(&mMutex);
687                return -ENOMEM;
688            }
689            for (size_t j = 0; j < numBuffers; j++){
690                (*it)->buffer_set.buffers[j] = buffer_set->buffers[j];
691            }
692            (*it)->registered = 1;
693        }
694    }
695
696    if (stream->stream_type != CAMERA3_STREAM_OUTPUT) {
697        ALOGE("%s: not yet support non output type stream", __func__);
698        pthread_mutex_unlock(&mMutex);
699        return -EINVAL;
700    }
701    rc = channel->registerBuffers(buffer_set->num_buffers, buffer_set->buffers);
702    if (rc < 0) {
703        ALOGE("%s: registerBUffers for stream %p failed", __func__, stream);
704        pthread_mutex_unlock(&mMutex);
705        return -ENODEV;
706    }
707
708    pthread_mutex_unlock(&mMutex);
709    return NO_ERROR;
710}
711
712/*===========================================================================
713 * FUNCTION   : processCaptureRequest
714 *
715 * DESCRIPTION: process a capture request from camera service
716 *
717 * PARAMETERS :
718 *   @request : request from framework to process
719 *
720 * RETURN     :
721 *
722 *==========================================================================*/
723int QCamera3HardwareInterface::processCaptureRequest(
724                    camera3_capture_request_t *request)
725{
726    int rc = NO_ERROR;
727    CameraMetadata meta;
728
729    pthread_mutex_lock(&mMutex);
730
731    rc = validateCaptureRequest(request);
732    if (rc != NO_ERROR) {
733        ALOGE("%s: incoming request is not valid", __func__);
734        pthread_mutex_unlock(&mMutex);
735        return rc;
736    }
737
738    uint32_t frameNumber = request->frame_number;
739
740    rc = setFrameParameters(request->frame_number, request->settings);
741    if (rc < 0) {
742        ALOGE("%s: fail to set frame parameters", __func__);
743        pthread_mutex_unlock(&mMutex);
744        return rc;
745    }
746
747    ALOGV("%s: %d, num_output_buffers = %d", __func__, __LINE__,
748                                    request->num_output_buffers);
749    // Acquire all request buffers first
750    for (size_t i = 0; i < request->num_output_buffers; i++) {
751        const camera3_stream_buffer_t& output = request->output_buffers[i];
752        sp<Fence> acquireFence = new Fence(output.acquire_fence);
753
754        if (output.stream->format == HAL_PIXEL_FORMAT_BLOB) {
755        //Call function to store local copy of jpeg data for encode params.
756            rc = getJpegSettings(request->settings);
757            if (rc < 0) {
758                ALOGE("%s: failed to get jpeg parameters", __func__);
759                pthread_mutex_unlock(&mMutex);
760                return rc;
761            }
762        }
763
764        rc = acquireFence->wait(Fence::TIMEOUT_NEVER);
765        if (rc != OK) {
766            ALOGE("%s: fence wait failed %d", __func__, rc);
767            pthread_mutex_unlock(&mMutex);
768            return rc;
769        }
770    }
771
772    /* Update pending request list and pending buffers map */
773    pthread_mutex_lock(&mRequestLock);
774    PendingRequestInfo pendingRequest;
775    pendingRequest.frame_number = frameNumber;
776    pendingRequest.num_buffers = request->num_output_buffers;
777    for (size_t i = 0; i < request->num_output_buffers; i++) {
778        RequestedBufferInfo requestedBuf;
779        requestedBuf.stream = request->output_buffers[i].stream;
780        requestedBuf.buffer = NULL;
781        pendingRequest.buffers.push_back(requestedBuf);
782
783        mPendingBuffersMap.editValueFor(requestedBuf.stream)++;
784    }
785    mPendingRequestsList.push_back(pendingRequest);
786    pthread_mutex_unlock(&mRequestLock);
787
788    // Notify metadata channel we receive a request
789    mMetadataChannel->request(NULL, frameNumber);
790
791    // Call request on other streams
792    for (size_t i = 0; i < request->num_output_buffers; i++) {
793        const camera3_stream_buffer_t& output = request->output_buffers[i];
794        QCamera3Channel *channel = (QCamera3Channel *)output.stream->priv;
795
796        if (channel == NULL) {
797            ALOGE("%s: invalid channel pointer for stream", __func__);
798            continue;
799        }
800
801        if (output.stream->format == HAL_PIXEL_FORMAT_BLOB) {
802            rc = channel->request(output.buffer, frameNumber, mJpegSettings);
803        } else {
804            ALOGI("%s: %d, request with buffer %p, frame_number %d", __func__, __LINE__, output.buffer, frameNumber);
805            rc = channel->request(output.buffer, frameNumber);
806        }
807        if (rc < 0)
808            ALOGE("%s: request failed", __func__);
809    }
810
811    mFirstRequest = false;
812
813    //Block on conditional variable
814    pthread_mutex_lock(&mRequestLock);
815    mPendingRequest = 1;
816    while (mPendingRequest == 1) {
817        pthread_cond_wait(&mRequestCond, &mRequestLock);
818    }
819    pthread_mutex_unlock(&mRequestLock);
820
821    pthread_mutex_unlock(&mMutex);
822    return rc;
823}
824
825/*===========================================================================
826 * FUNCTION   : getMetadataVendorTagOps
827 *
828 * DESCRIPTION:
829 *
830 * PARAMETERS :
831 *
832 *
833 * RETURN     :
834 *==========================================================================*/
835void QCamera3HardwareInterface::getMetadataVendorTagOps(
836                    vendor_tag_query_ops_t* /*ops*/)
837{
838    /* Enable locks when we eventually add Vendor Tags */
839    /*
840    pthread_mutex_lock(&mMutex);
841
842    pthread_mutex_unlock(&mMutex);
843    */
844    return;
845}
846
847/*===========================================================================
848 * FUNCTION   : dump
849 *
850 * DESCRIPTION:
851 *
852 * PARAMETERS :
853 *
854 *
855 * RETURN     :
856 *==========================================================================*/
857void QCamera3HardwareInterface::dump(int /*fd*/)
858{
859    /*Enable lock when we implement this function*/
860    /*
861    pthread_mutex_lock(&mMutex);
862
863    pthread_mutex_unlock(&mMutex);
864    */
865    return;
866}
867
868/*===========================================================================
869 * FUNCTION   : captureResultCb
870 *
871 * DESCRIPTION: Callback handler for all capture result
872 *              (streams, as well as metadata)
873 *
874 * PARAMETERS :
875 *   @metadata : metadata information
876 *   @buffer   : actual gralloc buffer to be returned to frameworks.
877 *               NULL if metadata.
878 *
879 * RETURN     : NONE
880 *==========================================================================*/
881void QCamera3HardwareInterface::captureResultCb(mm_camera_super_buf_t *metadata_buf,
882                camera3_stream_buffer_t *buffer, uint32_t frame_number)
883{
884    pthread_mutex_lock(&mRequestLock);
885
886    if (metadata_buf) {
887        metadata_buffer_t *metadata = (metadata_buffer_t *)metadata_buf->bufs[0]->buffer;
888        int32_t frame_number_valid = *(int32_t *)
889            POINTER_OF(CAM_INTF_META_FRAME_NUMBER_VALID, metadata);
890        uint32_t frame_number = *(uint32_t *)
891            POINTER_OF(CAM_INTF_META_FRAME_NUMBER, metadata);
892        const struct timeval *tv = (const struct timeval *)
893            POINTER_OF(CAM_INTF_META_SENSOR_TIMESTAMP, metadata);
894        nsecs_t capture_time = (nsecs_t)tv->tv_sec * NSEC_PER_SEC +
895            tv->tv_usec * NSEC_PER_USEC;
896
897        if (!frame_number_valid) {
898            ALOGD("%s: Not a valid frame number, used as SOF only", __func__);
899            mMetadataChannel->bufDone(metadata_buf);
900            goto done_metadata;
901        }
902        ALOGD("%s: valid frame_number = %d, capture_time = %lld", __func__,
903                frame_number, capture_time);
904
905        // Go through the pending requests info and send shutter/results to frameworks
906        for (List<PendingRequestInfo>::iterator i = mPendingRequestsList.begin();
907                i != mPendingRequestsList.end() && i->frame_number <= frame_number;) {
908            camera3_capture_result_t result;
909            camera3_notify_msg_t notify_msg;
910            ALOGD("%s: frame_number in the list is %d", __func__, i->frame_number);
911
912            // Flush out all entries with less or equal frame numbers.
913
914            //TODO: Make sure shutter timestamp really reflects shutter timestamp.
915            //Right now it's the same as metadata timestamp
916
917            //TODO: When there is metadata drop, how do we derive the timestamp of
918            //dropped frames? For now, we fake the dropped timestamp by substracting
919            //from the reported timestamp
920            nsecs_t current_capture_time = capture_time -
921                (frame_number - i->frame_number) * NSEC_PER_33MSEC;
922
923            // Send shutter notify to frameworks
924            notify_msg.type = CAMERA3_MSG_SHUTTER;
925            notify_msg.message.shutter.frame_number = i->frame_number;
926            notify_msg.message.shutter.timestamp = current_capture_time;
927            mCallbackOps->notify(mCallbackOps, &notify_msg);
928            ALOGD("%s: notify frame_number = %d, capture_time = %lld", __func__,
929                    i->frame_number, capture_time);
930
931            // Send empty metadata with already filled buffers for dropped metadata
932            // and send valid metadata with already filled buffers for current metadata
933            if (i->frame_number < frame_number) {
934                CameraMetadata emptyMetadata(1, 0);
935                emptyMetadata.update(ANDROID_SENSOR_TIMESTAMP,
936                        &current_capture_time, 1);
937                result.result = emptyMetadata.release();
938            } else {
939                result.result = translateCbMetadataToResultMetadata(metadata,
940                        current_capture_time);
941                // Return metadata buffer
942                mMetadataChannel->bufDone(metadata_buf);
943            }
944            if (!result.result) {
945                ALOGE("%s: metadata is NULL", __func__);
946            }
947            result.frame_number = i->frame_number;
948            result.num_output_buffers = 0;
949            result.output_buffers = NULL;
950            for (List<RequestedBufferInfo>::iterator j = i->buffers.begin();
951                    j != i->buffers.end(); j++) {
952                if (j->buffer) {
953                    result.num_output_buffers++;
954                }
955            }
956
957            if (result.num_output_buffers > 0) {
958                camera3_stream_buffer_t *result_buffers =
959                    new camera3_stream_buffer_t[result.num_output_buffers];
960                if (!result_buffers) {
961                    ALOGE("%s: Fatal error: out of memory", __func__);
962                }
963                size_t result_buffers_idx = 0;
964                for (List<RequestedBufferInfo>::iterator j = i->buffers.begin();
965                        j != i->buffers.end(); j++) {
966                    if (j->buffer) {
967                        result_buffers[result_buffers_idx++] = *(j->buffer);
968                        free(j->buffer);
969                        mPendingBuffersMap.editValueFor(j->stream)--;
970                    }
971                }
972                result.output_buffers = result_buffers;
973
974                mCallbackOps->process_capture_result(mCallbackOps, &result);
975                ALOGD("%s: meta frame_number = %d, capture_time = %lld",
976                        __func__, result.frame_number, current_capture_time);
977                free_camera_metadata((camera_metadata_t *)result.result);
978                delete[] result_buffers;
979            } else {
980                mCallbackOps->process_capture_result(mCallbackOps, &result);
981                ALOGD("%s: meta frame_number = %d, capture_time = %lld",
982                        __func__, result.frame_number, current_capture_time);
983                free_camera_metadata((camera_metadata_t *)result.result);
984            }
985            // erase the element from the list
986            i = mPendingRequestsList.erase(i);
987        }
988
989
990done_metadata:
991        bool max_buffers_dequeued = false;
992        for (size_t i = 0; i < mPendingBuffersMap.size(); i++) {
993            const camera3_stream_t *stream = mPendingBuffersMap.keyAt(i);
994            uint32_t queued_buffers = mPendingBuffersMap.valueAt(i);
995            if (queued_buffers == stream->max_buffers) {
996                max_buffers_dequeued = true;
997                break;
998            }
999        }
1000        if (!max_buffers_dequeued) {
1001            // Unblock process_capture_request
1002            mPendingRequest = 0;
1003            pthread_cond_signal(&mRequestCond);
1004        }
1005    } else {
1006        // If the frame number doesn't exist in the pending request list,
1007        // directly send the buffer to the frameworks, and update pending buffers map
1008        // Otherwise, book-keep the buffer.
1009        List<PendingRequestInfo>::iterator i = mPendingRequestsList.begin();
1010        while (i != mPendingRequestsList.end() && i->frame_number != frame_number)
1011            i++;
1012        if (i == mPendingRequestsList.end()) {
1013            // Verify all pending requests frame_numbers are greater
1014            for (List<PendingRequestInfo>::iterator j = mPendingRequestsList.begin();
1015                    j != mPendingRequestsList.end(); j++) {
1016                if (j->frame_number < frame_number) {
1017                    ALOGE("%s: Error: pending frame number %d is smaller than %d",
1018                            __func__, j->frame_number, frame_number);
1019                }
1020            }
1021            camera3_capture_result_t result;
1022            result.result = NULL;
1023            result.frame_number = frame_number;
1024            result.num_output_buffers = 1;
1025            result.output_buffers = buffer;
1026            ALOGD("%s: result frame_number = %d, buffer = %p",
1027                    __func__, frame_number, buffer);
1028            mPendingBuffersMap.editValueFor(buffer->stream)--;
1029            mCallbackOps->process_capture_result(mCallbackOps, &result);
1030        } else {
1031            for (List<RequestedBufferInfo>::iterator j = i->buffers.begin();
1032                    j != i->buffers.end(); j++) {
1033                if (j->stream == buffer->stream) {
1034                    if (j->buffer != NULL) {
1035                        ALOGE("%s: Error: buffer is already set", __func__);
1036                    } else {
1037                        j->buffer = (camera3_stream_buffer_t *)malloc(
1038                                sizeof(camera3_stream_buffer_t));
1039                        *(j->buffer) = *buffer;
1040                        ALOGD("%s: cache buffer %p at result frame_number %d",
1041                                __func__, buffer, frame_number);
1042                    }
1043                }
1044            }
1045        }
1046    }
1047
1048    pthread_mutex_unlock(&mRequestLock);
1049    return;
1050}
1051
1052/*===========================================================================
1053 * FUNCTION   : translateCbMetadataToResultMetadata
1054 *
1055 * DESCRIPTION:
1056 *
1057 * PARAMETERS :
1058 *   @metadata : metadata information from callback
1059 *
1060 * RETURN     : camera_metadata_t*
1061 *              metadata in a format specified by fwk
1062 *==========================================================================*/
1063camera_metadata_t*
1064QCamera3HardwareInterface::translateCbMetadataToResultMetadata
1065                                (metadata_buffer_t *metadata, nsecs_t timestamp)
1066{
1067    CameraMetadata camMetadata;
1068    camera_metadata_t* resultMetadata;
1069
1070
1071    camMetadata.update(ANDROID_SENSOR_TIMESTAMP, &timestamp, 1);
1072
1073    /*CAM_INTF_META_HISTOGRAM - TODO*/
1074    /*cam_hist_stats_t  *histogram =
1075      (cam_hist_stats_t *)POINTER_OF(CAM_INTF_META_HISTOGRAM,
1076      metadata);*/
1077
1078    /*face detection*/
1079    cam_face_detection_data_t *faceDetectionInfo =(cam_face_detection_data_t *)
1080        POINTER_OF(CAM_INTF_META_FACE_DETECTION, metadata);
1081    uint8_t numFaces = faceDetectionInfo->num_faces_detected;
1082    int32_t faceIds[numFaces];
1083    uint8_t faceScores[numFaces];
1084    int32_t faceRectangles[numFaces * 4];
1085    int32_t faceLandmarks[numFaces * 6];
1086    int j = 0, k = 0;
1087    for (int i = 0; i < numFaces; i++) {
1088        faceIds[i] = faceDetectionInfo->faces[i].face_id;
1089        faceScores[i] = faceDetectionInfo->faces[i].score;
1090        convertRegions(faceDetectionInfo->faces[i].face_boundary,
1091                faceRectangles+j, -1);
1092        convertLandmarks(faceDetectionInfo->faces[i], faceLandmarks+k);
1093        j+= 4;
1094        k+= 6;
1095    }
1096    camMetadata.update(ANDROID_STATISTICS_FACE_IDS, faceIds, numFaces);
1097    camMetadata.update(ANDROID_STATISTICS_FACE_SCORES, faceScores, numFaces);
1098    camMetadata.update(ANDROID_STATISTICS_FACE_RECTANGLES,
1099            faceRectangles, numFaces*4);
1100    camMetadata.update(ANDROID_STATISTICS_FACE_LANDMARKS,
1101            faceLandmarks, numFaces*6);
1102
1103
1104    /*autofocus - TODO*/
1105    /*cam_auto_focus_data_t  *afData =(cam_auto_focus_data_t *)
1106      POINTER_OF(CAM_INTF_META_AUTOFOCUS_DATA,metadata);*/
1107
1108    uint8_t  *color_correct_mode =
1109        (uint8_t *)POINTER_OF(CAM_INTF_META_COLOR_CORRECT_MODE, metadata);
1110    camMetadata.update(ANDROID_COLOR_CORRECTION_MODE, color_correct_mode, 1);
1111
1112    int32_t  *ae_precapture_id =
1113        (int32_t *)POINTER_OF(CAM_INTF_META_AEC_PRECAPTURE_ID, metadata);
1114    camMetadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID, ae_precapture_id, 1);
1115
1116    /*aec regions*/
1117    cam_area_t  *hAeRegions =
1118        (cam_area_t *)POINTER_OF(CAM_INTF_META_AEC_ROI, metadata);
1119    int32_t aeRegions[5];
1120    convertRegions(hAeRegions->rect, aeRegions, hAeRegions->weight);
1121    camMetadata.update(ANDROID_CONTROL_AE_REGIONS, aeRegions, 5);
1122
1123    uint8_t  *ae_state =
1124        (uint8_t *)POINTER_OF(CAM_INTF_META_AEC_STATE, metadata);
1125    camMetadata.update(ANDROID_CONTROL_AE_STATE, ae_state, 1);
1126
1127    uint8_t  *focusMode =
1128        (uint8_t *)POINTER_OF(CAM_INTF_PARM_FOCUS_MODE, metadata);
1129    camMetadata.update(ANDROID_CONTROL_AF_MODE, focusMode, 1);
1130
1131    /*af regions*/
1132    cam_area_t  *hAfRegions =
1133        (cam_area_t *)POINTER_OF(CAM_INTF_META_AF_ROI, metadata);
1134    int32_t afRegions[5];
1135    convertRegions(hAfRegions->rect, afRegions, hAfRegions->weight);
1136    camMetadata.update(ANDROID_CONTROL_AF_REGIONS, afRegions, 5);
1137
1138    uint8_t  *afState = (uint8_t *)POINTER_OF(CAM_INTF_META_AF_STATE, metadata);
1139    camMetadata.update(ANDROID_CONTROL_AF_STATE, afState, 1);
1140
1141    int32_t  *afTriggerId =
1142        (int32_t *)POINTER_OF(CAM_INTF_META_AF_TRIGGER_ID, metadata);
1143    camMetadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, afTriggerId, 1);
1144
1145    uint8_t  *whiteBalance =
1146        (uint8_t *)POINTER_OF(CAM_INTF_PARM_WHITE_BALANCE, metadata);
1147    camMetadata.update(ANDROID_CONTROL_AWB_MODE, whiteBalance, 1);
1148
1149    /*awb regions*/
1150    cam_area_t  *hAwbRegions =
1151        (cam_area_t *)POINTER_OF(CAM_INTF_META_AWB_REGIONS, metadata);
1152    int32_t awbRegions[5];
1153    convertRegions(hAwbRegions->rect, awbRegions, hAwbRegions->weight);
1154    camMetadata.update(ANDROID_CONTROL_AWB_REGIONS, awbRegions, 5);
1155
1156    uint8_t  *whiteBalanceState =
1157        (uint8_t *)POINTER_OF(CAM_INTF_META_AWB_STATE, metadata);
1158    camMetadata.update(ANDROID_CONTROL_AWB_STATE, whiteBalanceState, 1);
1159
1160    uint8_t  *mode = (uint8_t *)POINTER_OF(CAM_INTF_META_MODE, metadata);
1161    camMetadata.update(ANDROID_CONTROL_MODE, mode, 1);
1162
1163    uint8_t  *edgeMode = (uint8_t *)POINTER_OF(CAM_INTF_META_EDGE, metadata);
1164    camMetadata.update(ANDROID_EDGE_MODE, edgeMode, 1);
1165
1166    uint8_t  *flashPower =
1167        (uint8_t *)POINTER_OF(CAM_INTF_META_FLASH_POWER, metadata);
1168    camMetadata.update(ANDROID_FLASH_FIRING_POWER, flashPower, 1);
1169
1170    int64_t  *flashFiringTime =
1171        (int64_t *)POINTER_OF(CAM_INTF_META_FLASH_FIRING_TIME, metadata);
1172    camMetadata.update(ANDROID_FLASH_FIRING_TIME, flashFiringTime, 1);
1173
1174    /*int32_t  *ledMode =
1175      (int32_t *)POINTER_OF(CAM_INTF_PARM_LED_MODE, metadata);
1176      camMetadata.update(ANDROID_FLASH_FIRING_TIME, ledMode, 1);*/
1177
1178    uint8_t  *flashState =
1179        (uint8_t *)POINTER_OF(CAM_INTF_META_FLASH_STATE, metadata);
1180    camMetadata.update(ANDROID_FLASH_STATE, flashState, 1);
1181
1182    uint8_t  *hotPixelMode =
1183        (uint8_t *)POINTER_OF(CAM_INTF_META_HOTPIXEL_MODE, metadata);
1184    camMetadata.update(ANDROID_HOT_PIXEL_MODE, hotPixelMode, 1);
1185
1186    float  *lensAperture =
1187        (float *)POINTER_OF(CAM_INTF_META_LENS_APERTURE, metadata);
1188    camMetadata.update(ANDROID_LENS_APERTURE , lensAperture, 1);
1189
1190    float  *filterDensity =
1191        (float *)POINTER_OF(CAM_INTF_META_LENS_FILTERDENSITY, metadata);
1192    camMetadata.update(ANDROID_LENS_FILTER_DENSITY , filterDensity, 1);
1193
1194    float  *focalLength =
1195        (float *)POINTER_OF(CAM_INTF_META_LENS_FOCAL_LENGTH, metadata);
1196    camMetadata.update(ANDROID_LENS_FOCAL_LENGTH, focalLength, 1);
1197
1198    float  *focusDistance =
1199        (float *)POINTER_OF(CAM_INTF_META_LENS_FOCUS_DISTANCE, metadata);
1200    camMetadata.update(ANDROID_LENS_FOCUS_DISTANCE , focusDistance, 1);
1201
1202    float  *focusRange =
1203        (float *)POINTER_OF(CAM_INTF_META_LENS_FOCUS_RANGE, metadata);
1204    camMetadata.update(ANDROID_LENS_FOCUS_RANGE , focusRange, 1);
1205
1206    uint8_t  *opticalStab =
1207        (uint8_t *)POINTER_OF(CAM_INTF_META_LENS_OPT_STAB_MODE, metadata);
1208    camMetadata.update(ANDROID_LENS_OPTICAL_STABILIZATION_MODE ,opticalStab, 1);
1209
1210    /*int32_t  *focusState =
1211      (int32_t *)POINTER_OF(CAM_INTF_META_LENS_FOCUS_STATE, metadata);
1212      camMetadata.update(ANDROID_LENS_STATE , focusState, 1); //check */
1213
1214    uint8_t  *noiseRedMode =
1215        (uint8_t *)POINTER_OF(CAM_INTF_META_NOISE_REDUCTION_MODE, metadata);
1216    camMetadata.update(ANDROID_NOISE_REDUCTION_MODE , noiseRedMode, 1);
1217
1218    /*CAM_INTF_META_SCALER_CROP_REGION - check size*/
1219
1220    cam_crop_region_t  *hScalerCropRegion =(cam_crop_region_t *)
1221        POINTER_OF(CAM_INTF_META_SCALER_CROP_REGION, metadata);
1222    int32_t scalerCropRegion[3];
1223    scalerCropRegion[0] = hScalerCropRegion->left;
1224    scalerCropRegion[1] = hScalerCropRegion->top;
1225    scalerCropRegion[2] = hScalerCropRegion->width;
1226    camMetadata.update(ANDROID_SCALER_CROP_REGION, scalerCropRegion, 3);
1227
1228    int64_t  *sensorExpTime =
1229        (int64_t *)POINTER_OF(CAM_INTF_META_SENSOR_EXPOSURE_TIME, metadata);
1230    camMetadata.update(ANDROID_SENSOR_EXPOSURE_TIME , sensorExpTime, 1);
1231
1232    int64_t  *sensorFameDuration =
1233        (int64_t *)POINTER_OF(CAM_INTF_META_SENSOR_FRAME_DURATION, metadata);
1234    camMetadata.update(ANDROID_SENSOR_FRAME_DURATION, sensorFameDuration, 1);
1235
1236    int32_t  *sensorSensitivity =
1237        (int32_t *)POINTER_OF(CAM_INTF_META_SENSOR_SENSITIVITY, metadata);
1238    camMetadata.update(ANDROID_SENSOR_SENSITIVITY, sensorSensitivity, 1);
1239
1240    uint8_t  *shadingMode =
1241        (uint8_t *)POINTER_OF(CAM_INTF_META_SHADING_MODE, metadata);
1242    camMetadata.update(ANDROID_SHADING_MODE, shadingMode, 1);
1243
1244    uint8_t  *faceDetectMode =
1245        (uint8_t *)POINTER_OF(CAM_INTF_META_STATS_FACEDETECT_MODE, metadata);
1246    camMetadata.update(ANDROID_STATISTICS_FACE_DETECT_MODE, faceDetectMode, 1);
1247
1248    uint8_t  *histogramMode =
1249        (uint8_t *)POINTER_OF(CAM_INTF_META_STATS_HISTOGRAM_MODE, metadata);
1250    camMetadata.update(ANDROID_STATISTICS_HISTOGRAM_MODE, histogramMode, 1);
1251
1252    uint8_t  *sharpnessMapMode =
1253        (uint8_t *)POINTER_OF(CAM_INTF_META_STATS_SHARPNESS_MAP_MODE, metadata);
1254    camMetadata.update(ANDROID_STATISTICS_SHARPNESS_MAP_MODE,
1255            sharpnessMapMode, 1);
1256
1257    /*CAM_INTF_META_STATS_SHARPNESS_MAP - check size*/
1258    cam_sharpness_map_t  *sharpnessMap = (cam_sharpness_map_t *)
1259        POINTER_OF(CAM_INTF_META_STATS_SHARPNESS_MAP, metadata);
1260    camMetadata.update(ANDROID_STATISTICS_SHARPNESS_MAP,
1261            (int32_t*)sharpnessMap->sharpness,
1262            CAM_MAX_MAP_WIDTH*CAM_MAX_MAP_HEIGHT);
1263
1264    resultMetadata = camMetadata.release();
1265    return resultMetadata;
1266}
1267
1268/*===========================================================================
1269 * FUNCTION   : convertRegions
1270 *
1271 * DESCRIPTION: helper method to convert from cam_rect_t into int32_t array
1272 *
1273 * PARAMETERS :
1274 *   @rect   : cam_rect_t struct to convert
1275 *   @region : int32_t destination array
1276 *   @weight : if we are converting from cam_area_t, weight is valid
1277 *             else weight = -1
1278 *
1279 *==========================================================================*/
1280void QCamera3HardwareInterface::convertRegions(cam_rect_t rect, int32_t* region, int weight){
1281    region[0] = rect.left;
1282    region[1] = rect.top;
1283    region[2] = rect.width;
1284    region[3] = rect.height;
1285    if (weight > -1) {
1286        region[4] = weight;
1287    }
1288}
1289/*===========================================================================
1290 * FUNCTION   : convertLandmarks
1291 *
1292 * DESCRIPTION: helper method to extract the landmarks from face detection info
1293 *
1294 * PARAMETERS :
1295 *   @face   : cam_rect_t struct to convert
1296 *   @landmarks : int32_t destination array
1297 *
1298 *
1299 *==========================================================================*/
1300void QCamera3HardwareInterface::convertLandmarks(cam_face_detection_info_t face, int32_t* landmarks)
1301{
1302    landmarks[0] = face.left_eye_center.x;
1303    landmarks[1] = face.left_eye_center.y;
1304    landmarks[2] = face.right_eye_center.y;
1305    landmarks[3] = face.right_eye_center.y;
1306    landmarks[4] = face.mouth_center.x;
1307    landmarks[5] = face.mouth_center.y;
1308}
1309
1310#define DATA_PTR(MEM_OBJ,INDEX) MEM_OBJ->getPtr( INDEX )
1311/*===========================================================================
1312 * FUNCTION   : initCapabilities
1313 *
1314 * DESCRIPTION: initialize camera capabilities in static data struct
1315 *
1316 * PARAMETERS :
1317 *   @cameraId  : camera Id
1318 *
1319 * RETURN     : int32_t type of status
1320 *              NO_ERROR  -- success
1321 *              none-zero failure code
1322 *==========================================================================*/
1323int QCamera3HardwareInterface::initCapabilities(int cameraId)
1324{
1325    int rc = 0;
1326    mm_camera_vtbl_t *cameraHandle = NULL;
1327    QCamera3HeapMemory *capabilityHeap = NULL;
1328
1329    cameraHandle = camera_open(cameraId);
1330    if (!cameraHandle) {
1331        ALOGE("%s: camera_open failed", __func__);
1332        rc = -1;
1333        goto open_failed;
1334    }
1335
1336    capabilityHeap = new QCamera3HeapMemory();
1337    if (capabilityHeap == NULL) {
1338        ALOGE("%s: creation of capabilityHeap failed", __func__);
1339        goto heap_creation_failed;
1340    }
1341    /* Allocate memory for capability buffer */
1342    rc = capabilityHeap->allocate(1, sizeof(cam_capability_t), false);
1343    if(rc != OK) {
1344        ALOGE("%s: No memory for cappability", __func__);
1345        goto allocate_failed;
1346    }
1347
1348    /* Map memory for capability buffer */
1349    memset(DATA_PTR(capabilityHeap,0), 0, sizeof(cam_capability_t));
1350    rc = cameraHandle->ops->map_buf(cameraHandle->camera_handle,
1351                                CAM_MAPPING_BUF_TYPE_CAPABILITY,
1352                                capabilityHeap->getFd(0),
1353                                sizeof(cam_capability_t));
1354    if(rc < 0) {
1355        ALOGE("%s: failed to map capability buffer", __func__);
1356        goto map_failed;
1357    }
1358
1359    /* Query Capability */
1360    rc = cameraHandle->ops->query_capability(cameraHandle->camera_handle);
1361    if(rc < 0) {
1362        ALOGE("%s: failed to query capability",__func__);
1363        goto query_failed;
1364    }
1365    gCamCapability[cameraId] = (cam_capability_t *)malloc(sizeof(cam_capability_t));
1366    if (!gCamCapability[cameraId]) {
1367        ALOGE("%s: out of memory", __func__);
1368        goto query_failed;
1369    }
1370    memcpy(gCamCapability[cameraId], DATA_PTR(capabilityHeap,0),
1371                                        sizeof(cam_capability_t));
1372    rc = 0;
1373
1374query_failed:
1375    cameraHandle->ops->unmap_buf(cameraHandle->camera_handle,
1376                            CAM_MAPPING_BUF_TYPE_CAPABILITY);
1377map_failed:
1378    capabilityHeap->deallocate();
1379allocate_failed:
1380    delete capabilityHeap;
1381heap_creation_failed:
1382    cameraHandle->ops->close_camera(cameraHandle->camera_handle);
1383    cameraHandle = NULL;
1384open_failed:
1385    return rc;
1386}
1387
1388/*===========================================================================
1389 * FUNCTION   : initParameters
1390 *
1391 * DESCRIPTION: initialize camera parameters
1392 *
1393 * PARAMETERS :
1394 *
1395 * RETURN     : int32_t type of status
1396 *              NO_ERROR  -- success
1397 *              none-zero failure code
1398 *==========================================================================*/
1399int QCamera3HardwareInterface::initParameters()
1400{
1401    int rc = 0;
1402
1403    //Allocate Set Param Buffer
1404    mParamHeap = new QCamera3HeapMemory();
1405    rc = mParamHeap->allocate(1, sizeof(parm_buffer_t), false);
1406    if(rc != OK) {
1407        rc = NO_MEMORY;
1408        ALOGE("Failed to allocate SETPARM Heap memory");
1409        delete mParamHeap;
1410        mParamHeap = NULL;
1411        return rc;
1412    }
1413
1414    //Map memory for parameters buffer
1415    rc = mCameraHandle->ops->map_buf(mCameraHandle->camera_handle,
1416            CAM_MAPPING_BUF_TYPE_PARM_BUF,
1417            mParamHeap->getFd(0),
1418            sizeof(parm_buffer_t));
1419    if(rc < 0) {
1420        ALOGE("%s:failed to map SETPARM buffer",__func__);
1421        rc = FAILED_TRANSACTION;
1422        mParamHeap->deallocate();
1423        delete mParamHeap;
1424        mParamHeap = NULL;
1425        return rc;
1426    }
1427
1428    mParameters = (parm_buffer_t*) DATA_PTR(mParamHeap,0);
1429    return rc;
1430}
1431
1432/*===========================================================================
1433 * FUNCTION   : deinitParameters
1434 *
1435 * DESCRIPTION: de-initialize camera parameters
1436 *
1437 * PARAMETERS :
1438 *
1439 * RETURN     : NONE
1440 *==========================================================================*/
1441void QCamera3HardwareInterface::deinitParameters()
1442{
1443    mCameraHandle->ops->unmap_buf(mCameraHandle->camera_handle,
1444            CAM_MAPPING_BUF_TYPE_PARM_BUF);
1445
1446    mParamHeap->deallocate();
1447    delete mParamHeap;
1448    mParamHeap = NULL;
1449
1450    mParameters = NULL;
1451}
1452
1453/*===========================================================================
1454 * FUNCTION   : initStaticMetadata
1455 *
1456 * DESCRIPTION: initialize the static metadata
1457 *
1458 * PARAMETERS :
1459 *   @cameraId  : camera Id
1460 *
1461 * RETURN     : int32_t type of status
1462 *              0  -- success
1463 *              non-zero failure code
1464 *==========================================================================*/
1465int QCamera3HardwareInterface::initStaticMetadata(int cameraId)
1466{
1467    int rc = 0;
1468    CameraMetadata staticInfo;
1469    int facingBack = gCamCapability[cameraId]->position == CAM_POSITION_BACK;
1470    /*HAL 3 only*/
1471    #ifdef HAL_3_CAPABILITIES
1472    staticInfo.update(ANDROID_LENS_INFO_MINIMUM_FOCUS_DISTANCE,
1473                    &gCamCapability[cameraId]->min_focus_distance, 1);
1474
1475    staticInfo.update(ANDROID_LENS_INFO_HYPERFOCAL_DISTANCE,
1476                    &gCamCapability[cameraId]->hyper_focal_distance, 1);
1477
1478    /*should be using focal lengths but sensor doesn't provide that info now*/
1479    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS,
1480                      &gCamCapability[cameraId]->focal_length,
1481                      1);
1482
1483    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_APERTURES,
1484                      gCamCapability[cameraId]->apertures,
1485                      gCamCapability[cameraId]->apertures_count);
1486
1487    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_FILTER_DENSITIES,
1488                gCamCapability[cameraId]->filter_densities,
1489                gCamCapability[cameraId]->filter_densities_count);
1490
1491
1492    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION,
1493                      (uint8_t*)gCamCapability[cameraId]->optical_stab_modes,
1494                      gCamCapability[cameraId]->optical_stab_modes_count);
1495
1496    staticInfo.update(ANDROID_LENS_POSITION,
1497                      gCamCapability[cameraId]->lens_position,
1498                      sizeof(gCamCapability[cameraId]->lens_position)/ sizeof(float));
1499
1500    static const int32_t lens_shading_map_size[] = {gCamCapability[cameraId]->lens_shading_map_size.width,
1501                                                    gCamCapability[cameraId]->lens_shading_map_size.height};
1502    staticInfo.update(ANDROID_LENS_INFO_SHADING_MAP_SIZE,
1503                      lens_shading_map_size,
1504                      sizeof(lens_shading_map_size)/sizeof(int32_t));
1505
1506    staticInfo.update(ANDROID_LENS_INFO_SHADING_MAP, gCamCapability[cameraId]->lens_shading_map,
1507            sizeof(gCamCapability[cameraId]->lens_shading_map)/ sizeof(float));
1508
1509    static const int32_t geo_correction_map_size[] = {gCamCapability[cameraId]->geo_correction_map_size.width,
1510                                                      gCamCapability[cameraId]->geo_correction_map_size.height};
1511    staticInfo.update(ANDROID_LENS_INFO_GEOMETRIC_CORRECTION_MAP_SIZE,
1512            geo_correction_map_size,
1513            sizeof(geo_correction_map_size)/sizeof(int32_t));
1514
1515    staticInfo.update(ANDROID_LENS_INFO_GEOMETRIC_CORRECTION_MAP,
1516                       gCamCapability[cameraId]->geo_correction_map,
1517                       sizeof(gCamCapability[cameraId]->geo_correction_map)/sizeof(float));
1518
1519    staticInfo.update(ANDROID_SENSOR_INFO_PHYSICAL_SIZE,
1520            gCamCapability[cameraId]->sensor_physical_size, 2);
1521
1522    staticInfo.update(ANDROID_SENSOR_INFO_EXPOSURE_TIME_RANGE,
1523            gCamCapability[cameraId]->exposure_time_range, 2);
1524
1525    staticInfo.update(ANDROID_SENSOR_INFO_MAX_FRAME_DURATION,
1526            &gCamCapability[cameraId]->max_frame_duration, 1);
1527
1528
1529    staticInfo.update(ANDROID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT,
1530                     (uint8_t*)&gCamCapability[cameraId]->color_arrangement, 1);
1531
1532    static const int32_t pixel_array_size[] = {gCamCapability[cameraId]->pixel_array_size.width,
1533                                               gCamCapability[cameraId]->pixel_array_size.height};
1534    staticInfo.update(ANDROID_SENSOR_INFO_PIXEL_ARRAY_SIZE,
1535                      pixel_array_size, 2);
1536
1537    static const int32_t active_array_size[] = {gCamCapability[cameraId]->active_array_size.width,
1538                                                gCamCapability[cameraId]->active_array_size.height};
1539    staticInfo.update(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE,
1540                      active_array_size, 2);
1541
1542    staticInfo.update(ANDROID_SENSOR_INFO_WHITE_LEVEL,
1543            &gCamCapability[cameraId]->white_level, 1);
1544
1545    staticInfo.update(ANDROID_SENSOR_BLACK_LEVEL_PATTERN,
1546            gCamCapability[cameraId]->black_level_pattern, 4);
1547
1548    staticInfo.update(ANDROID_FLASH_INFO_CHARGE_DURATION,
1549                      &gCamCapability[cameraId]->flash_charge_duration, 1);
1550
1551    staticInfo.update(ANDROID_TONEMAP_MAX_CURVE_POINTS,
1552                      &gCamCapability[cameraId]->max_tone_map_curve_points, 1);
1553
1554    /*staticInfo.update(ANDROID_STATISTICS_INFO_MAX_FACE_COUNT,
1555                      (int*)&gCamCapability[cameraId]->max_face_detection_count, 1);*/
1556    /*hardcode 0 for now*/
1557    int32_t max_face_count = 0;
1558    staticInfo.update(ANDROID_STATISTICS_INFO_MAX_FACE_COUNT,
1559                      &max_face_count, 1);
1560
1561    staticInfo.update(ANDROID_STATISTICS_INFO_HISTOGRAM_BUCKET_COUNT,
1562                      &gCamCapability[cameraId]->histogram_size, 1);
1563
1564    staticInfo.update(ANDROID_STATISTICS_INFO_MAX_HISTOGRAM_COUNT,
1565            &gCamCapability[cameraId]->max_histogram_count, 1);
1566
1567    static const int32_t sharpness_map_size[] = {gCamCapability[cameraId]->sharpness_map_size.width,
1568                                                gCamCapability[cameraId]->sharpness_map_size.height};
1569
1570    staticInfo.update(ANDROID_STATISTICS_INFO_SHARPNESS_MAP_SIZE,
1571            sharpness_map_size, sizeof(sharpness_map_size)/sizeof(int32_t));
1572
1573    staticInfo.update(ANDROID_STATISTICS_INFO_MAX_SHARPNESS_MAP_VALUE,
1574            &gCamCapability[cameraId]->max_sharpness_map_value, 1);
1575
1576
1577    staticInfo.update(ANDROID_SCALER_AVAILABLE_RAW_MIN_DURATIONS,
1578                      &gCamCapability[cameraId]->raw_min_duration,
1579                       1);
1580
1581    static int32_t scalar_formats[CAM_FORMAT_MAX];
1582    for (int i = 0; i < gCamCapability[cameraId]->supported_scalar_format_cnt; i++) {
1583        scalar_formats[i] = getScalarFormat(gCamCapability[cameraId]->supported_scalar_fmts[i]);
1584    }
1585    staticInfo.update(ANDROID_SCALER_AVAILABLE_FORMATS,
1586                      scalar_formats,
1587                      gCamCapability[cameraId]->supported_scalar_format_cnt);
1588
1589    static int32_t available_processed_sizes[CAM_FORMAT_MAX];
1590    makeTable(gCamCapability[cameraId]->supported_sizes_tbl,
1591              gCamCapability[cameraId]->supported_sizes_tbl_cnt,
1592              available_processed_sizes);
1593    staticInfo.update(ANDROID_SCALER_AVAILABLE_PROCESSED_SIZES,
1594                available_processed_sizes,
1595                (gCamCapability[cameraId]->supported_sizes_tbl_cnt) * 2);
1596
1597    static int32_t available_fps_ranges[MAX_SIZES_CNT];
1598    makeFPSTable(gCamCapability[cameraId]->fps_ranges_tbl,
1599                 gCamCapability[cameraId]->fps_ranges_tbl_cnt,
1600                 available_fps_ranges);
1601    staticInfo.update(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES,
1602            available_fps_ranges, (gCamCapability[cameraId]->fps_ranges_tbl_cnt*2) );
1603
1604    static const camera_metadata_rational exposureCompensationStep = {
1605            gCamCapability[cameraId]->exp_compensation_step.numerator,
1606            gCamCapability[cameraId]->exp_compensation_step.denominator};
1607    staticInfo.update(ANDROID_CONTROL_AE_COMPENSATION_STEP,
1608                      &exposureCompensationStep, 1);
1609
1610    /*TO DO*/
1611    static const uint8_t availableVstabModes[] = {ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF};
1612    staticInfo.update(ANDROID_CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES,
1613                      availableVstabModes, sizeof(availableVstabModes));
1614
1615    #else
1616    const float minFocusDistance = 0;
1617    staticInfo.update(ANDROID_LENS_INFO_MINIMUM_FOCUS_DISTANCE,
1618                    &minFocusDistance, 1);
1619
1620    const float hyperFocusDistance = 0;
1621    staticInfo.update(ANDROID_LENS_INFO_HYPERFOCAL_DISTANCE,
1622                     &hyperFocusDistance, 1);
1623
1624    static const float focalLength = 3.30f;
1625    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_FOCAL_LENGTHS,
1626                      &focalLength,
1627                      1);
1628
1629    static const float aperture = 2.8f;
1630    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_APERTURES,
1631                      &aperture,
1632                      1);
1633
1634    static const float filterDensity = 0;
1635    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_FILTER_DENSITIES,
1636                      &filterDensity, 1);
1637
1638    static const uint8_t availableOpticalStabilization =
1639            ANDROID_LENS_OPTICAL_STABILIZATION_MODE_OFF;
1640    staticInfo.update(ANDROID_LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION,
1641                      &availableOpticalStabilization, 1);
1642
1643    float lensPosition[3];
1644    if (facingBack) {
1645        // Back-facing camera is center-top on device
1646        lensPosition[0] = 0;
1647        lensPosition[1] = 20;
1648        lensPosition[2] = -5;
1649    } else {
1650        // Front-facing camera is center-right on device
1651        lensPosition[0] = 20;
1652        lensPosition[1] = 20;
1653        lensPosition[2] = 0;
1654    }
1655    staticInfo.update(ANDROID_LENS_POSITION,
1656                      lensPosition,
1657                      sizeof(lensPosition)/ sizeof(float));
1658
1659    static const int32_t lensShadingMapSize[] = {1, 1};
1660    staticInfo.update(ANDROID_LENS_INFO_SHADING_MAP_SIZE,
1661                      lensShadingMapSize,
1662                      sizeof(lensShadingMapSize)/sizeof(int32_t));
1663
1664    static const float lensShadingMap[3 * 1 * 1 ] =
1665            { 1.f, 1.f, 1.f };
1666    staticInfo.update(ANDROID_LENS_INFO_SHADING_MAP,
1667                      lensShadingMap,
1668                      sizeof(lensShadingMap)/ sizeof(float));
1669
1670    static const int32_t geometricCorrectionMapSize[] = {2, 2};
1671    staticInfo.update(ANDROID_LENS_INFO_GEOMETRIC_CORRECTION_MAP_SIZE,
1672                      geometricCorrectionMapSize,
1673                      sizeof(geometricCorrectionMapSize)/sizeof(int32_t));
1674
1675    static const float geometricCorrectionMap[2 * 3 * 2 * 2] = {
1676            0.f, 0.f,  0.f, 0.f,  0.f, 0.f,
1677            1.f, 0.f,  1.f, 0.f,  1.f, 0.f,
1678            0.f, 1.f,  0.f, 1.f,  0.f, 1.f,
1679            1.f, 1.f,  1.f, 1.f,  1.f, 1.f};
1680    staticInfo.update(ANDROID_LENS_INFO_GEOMETRIC_CORRECTION_MAP,
1681                      geometricCorrectionMap,
1682                      sizeof(geometricCorrectionMap)/ sizeof(float));
1683
1684    static const float sensorPhysicalSize[2] = {3.20f, 2.40f};
1685    staticInfo.update(ANDROID_SENSOR_INFO_PHYSICAL_SIZE,
1686                      sensorPhysicalSize, 2);
1687
1688    const int64_t exposureTimeRange[2] = {1000L, 30000000000L} ; // 1 us - 30 sec
1689    staticInfo.update(ANDROID_SENSOR_INFO_EXPOSURE_TIME_RANGE,
1690                      exposureTimeRange, 2);
1691
1692    const int64_t frameDurationRange[2] = {33331760L, 30000000000L};
1693    staticInfo.update(ANDROID_SENSOR_INFO_MAX_FRAME_DURATION,
1694                      frameDurationRange, 1);
1695
1696    const uint8_t colorFilterArrangement =
1697                         ANDROID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_RGGB;
1698    staticInfo.update(ANDROID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT,
1699                      &colorFilterArrangement, 1);
1700
1701    const int resolution[2]  = {640, 480};
1702    staticInfo.update(ANDROID_SENSOR_INFO_PIXEL_ARRAY_SIZE,
1703                      resolution, 2);
1704
1705    staticInfo.update(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE,
1706                      resolution, 2);
1707
1708    const uint32_t whiteLevel = 4000;
1709    staticInfo.update(ANDROID_SENSOR_INFO_WHITE_LEVEL,
1710                      (int32_t*)&whiteLevel, 1);
1711
1712    static const int32_t blackLevelPattern[4] = {
1713            1000, 1000,
1714            1000, 1000 };
1715    staticInfo.update(ANDROID_SENSOR_BLACK_LEVEL_PATTERN,
1716                      blackLevelPattern, 4);
1717
1718    static const int64_t flashChargeDuration = 0;
1719    staticInfo.update(ANDROID_FLASH_INFO_CHARGE_DURATION,
1720                      &flashChargeDuration, 1);
1721
1722    static const int32_t tonemapCurvePoints = 128;
1723    staticInfo.update(ANDROID_TONEMAP_MAX_CURVE_POINTS,
1724                      &tonemapCurvePoints, 1);
1725
1726    static const int32_t maxFaceCount = 0;
1727    staticInfo.update(ANDROID_STATISTICS_INFO_MAX_FACE_COUNT,
1728                      &maxFaceCount, 1);
1729
1730    static const int32_t histogramSize = 64;
1731    staticInfo.update(ANDROID_STATISTICS_INFO_HISTOGRAM_BUCKET_COUNT,
1732                      &histogramSize, 1);
1733
1734    static const int32_t maxHistogramCount = 1000;
1735    staticInfo.update(ANDROID_STATISTICS_INFO_MAX_HISTOGRAM_COUNT,
1736                      &maxHistogramCount, 1);
1737
1738    static const int32_t sharpnessMapSize[2] = {64, 64};
1739    staticInfo.update(ANDROID_STATISTICS_INFO_SHARPNESS_MAP_SIZE,
1740                      sharpnessMapSize, sizeof(sharpnessMapSize)/sizeof(int32_t));
1741
1742    static const int32_t maxSharpnessMapValue = 1000;
1743    staticInfo.update(ANDROID_STATISTICS_INFO_MAX_SHARPNESS_MAP_VALUE,
1744                      &maxSharpnessMapValue, 1);
1745
1746    static const uint8_t availableVstabModes[] = {ANDROID_CONTROL_VIDEO_STABILIZATION_MODE_OFF};
1747    staticInfo.update(ANDROID_CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES,
1748                      availableVstabModes, sizeof(availableVstabModes));
1749
1750    const uint64_t availableRawMinDurations[1] = {33331760L};
1751    staticInfo.update(ANDROID_SCALER_AVAILABLE_RAW_MIN_DURATIONS,
1752                      (int64_t*)&availableRawMinDurations,
1753                       1);
1754
1755    const uint32_t availableFormats[4] = {
1756        HAL_PIXEL_FORMAT_RAW_SENSOR,
1757        HAL_PIXEL_FORMAT_BLOB,
1758        HAL_PIXEL_FORMAT_RGBA_8888,
1759        HAL_PIXEL_FORMAT_YCrCb_420_SP
1760    };
1761    staticInfo.update(ANDROID_SCALER_AVAILABLE_FORMATS,
1762                      (int32_t*)availableFormats,
1763                      4);
1764
1765    const uint32_t availableProcessedSizes[4] = {1280, 720, 640, 480};
1766    staticInfo.update(ANDROID_SCALER_AVAILABLE_PROCESSED_SIZES,
1767                      (int32_t*)availableProcessedSizes,
1768                      sizeof(availableProcessedSizes)/sizeof(int32_t));
1769
1770    staticInfo.update(ANDROID_SCALER_AVAILABLE_JPEG_SIZES,
1771                      resolution,
1772                     sizeof(resolution)/sizeof(int));
1773
1774    static const uint8_t availableSceneModes[] = {
1775            ANDROID_CONTROL_SCENE_MODE_UNSUPPORTED };
1776
1777    staticInfo.update(ANDROID_CONTROL_AVAILABLE_SCENE_MODES,
1778            availableSceneModes, sizeof(availableSceneModes));
1779
1780    static const int32_t availableFpsRanges[] = {15, 30};
1781    staticInfo.update(ANDROID_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES,
1782            availableFpsRanges, sizeof(availableFpsRanges)/sizeof(int32_t));
1783
1784    static const uint8_t availableEffectsModes[] = {
1785            ANDROID_CONTROL_EFFECT_MODE_OFF };
1786    staticInfo.update(ANDROID_CONTROL_AVAILABLE_EFFECTS,
1787            availableEffectsModes, sizeof(availableEffectsModes));
1788
1789    static const uint8_t availableAntibandingModes[] = {
1790            ANDROID_CONTROL_AE_ANTIBANDING_MODE_OFF };
1791    staticInfo.update(ANDROID_CONTROL_AE_AVAILABLE_ANTIBANDING_MODES,
1792            availableAntibandingModes, sizeof(availableAntibandingModes));
1793
1794    static const camera_metadata_rational exposureCompensationStep = {
1795            1, 3
1796    };
1797    staticInfo.update(ANDROID_CONTROL_AE_COMPENSATION_STEP,
1798            &exposureCompensationStep, 1);
1799
1800    static const int32_t jpegThumbnailSizes[] = {
1801            0, 0,
1802            160, 120,
1803            320, 240
1804     };
1805    staticInfo.update(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES,
1806            jpegThumbnailSizes, sizeof(jpegThumbnailSizes)/sizeof(int32_t));
1807
1808    static int64_t jpegMinDuration[] = {33331760L, 30000000000L};
1809    staticInfo.update(ANDROID_SCALER_AVAILABLE_JPEG_MIN_DURATIONS,
1810                      jpegMinDuration,
1811                      sizeof(jpegMinDuration)/sizeof(uint64_t));
1812    #endif
1813     /*HAL 1 and HAL 3 common*/
1814    static const int32_t maxZoom = 10;
1815    staticInfo.update(ANDROID_SCALER_AVAILABLE_MAX_DIGITAL_ZOOM,
1816            &maxZoom, 1);
1817
1818    static const int32_t max3aRegions = 0;
1819    staticInfo.update(ANDROID_CONTROL_MAX_REGIONS,
1820            &max3aRegions, 1);
1821
1822    static const uint8_t flashAvailable = 0;
1823    staticInfo.update(ANDROID_FLASH_INFO_AVAILABLE,
1824            &flashAvailable, sizeof(flashAvailable));
1825
1826    static const uint8_t availableFaceDetectModes[] = {
1827    ANDROID_STATISTICS_FACE_DETECT_MODE_OFF };
1828
1829    staticInfo.update(ANDROID_STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES,
1830                      availableFaceDetectModes,
1831                      sizeof(availableFaceDetectModes));
1832
1833    static const int32_t raw_size[] = {gCamCapability[cameraId]->raw_dim.width,
1834                                       gCamCapability[cameraId]->raw_dim.height};
1835    staticInfo.update(ANDROID_SCALER_AVAILABLE_RAW_SIZES,
1836                      raw_size,
1837                      sizeof(raw_size)/sizeof(uint32_t));
1838
1839    static const int32_t exposureCompensationRange[] = {gCamCapability[cameraId]->exposure_compensation_min,
1840                                                        gCamCapability[cameraId]->exposure_compensation_max};
1841    staticInfo.update(ANDROID_CONTROL_AE_COMPENSATION_RANGE,
1842            exposureCompensationRange,
1843            sizeof(exposureCompensationRange)/sizeof(int32_t));
1844
1845    uint8_t lensFacing = (facingBack) ?
1846            ANDROID_LENS_FACING_BACK : ANDROID_LENS_FACING_FRONT;
1847    staticInfo.update(ANDROID_LENS_FACING, &lensFacing, 1);
1848
1849    static int32_t available_jpeg_sizes[MAX_SIZES_CNT];
1850    makeTable(gCamCapability[cameraId]->picture_sizes_tbl,
1851              gCamCapability[cameraId]->picture_sizes_tbl_cnt,
1852              available_jpeg_sizes);
1853    staticInfo.update(ANDROID_SCALER_AVAILABLE_JPEG_SIZES,
1854                available_jpeg_sizes,
1855                (gCamCapability[cameraId]->picture_sizes_tbl_cnt * 2));
1856
1857    staticInfo.update(ANDROID_JPEG_AVAILABLE_THUMBNAIL_SIZES,
1858                      available_jpeg_sizes,
1859                      (gCamCapability[cameraId]->picture_sizes_tbl_cnt * 2));
1860
1861    static int32_t max_jpeg_size = 0;
1862    int temp_width, temp_height;
1863    for (int i = 0; i < gCamCapability[cameraId]->picture_sizes_tbl_cnt; i++) {
1864        temp_width = gCamCapability[cameraId]->picture_sizes_tbl[i].width;
1865        temp_height = gCamCapability[cameraId]->picture_sizes_tbl[i].height;
1866        if (temp_width * temp_height > max_jpeg_size ) {
1867            max_jpeg_size = temp_width * temp_height;
1868        }
1869    }
1870    max_jpeg_size = max_jpeg_size * 3/2 + sizeof(camera3_jpeg_blob_t);
1871    staticInfo.update(ANDROID_JPEG_MAX_SIZE,
1872                      &max_jpeg_size, 1);
1873
1874    static uint8_t avail_effects[CAM_EFFECT_MODE_MAX];
1875    int32_t size = 0;
1876    for (int i = 0; i < gCamCapability[cameraId]->supported_effects_cnt; i++) {
1877        int val = lookupFwkName(EFFECT_MODES_MAP,
1878                                   sizeof(EFFECT_MODES_MAP)/sizeof(EFFECT_MODES_MAP[0]),
1879                                   gCamCapability[cameraId]->supported_effects[i]);
1880        if (val != NAME_NOT_FOUND) {
1881            avail_effects[size] = (uint8_t)val;
1882            size++;
1883        }
1884    }
1885    staticInfo.update(ANDROID_CONTROL_AVAILABLE_EFFECTS,
1886                      avail_effects,
1887                      size);
1888
1889    static uint8_t avail_scene_modes[CAM_SCENE_MODE_MAX];
1890    size = 0;
1891    for (int i = 0; i < gCamCapability[cameraId]->supported_scene_modes_cnt; i++) {
1892        int val = lookupFwkName(SCENE_MODES_MAP,
1893                                sizeof(SCENE_MODES_MAP)/sizeof(SCENE_MODES_MAP[0]),
1894                                gCamCapability[cameraId]->supported_scene_modes[i]);
1895        if (val != NAME_NOT_FOUND) {
1896            avail_scene_modes[size] = (uint8_t)val;
1897            size++;
1898        }
1899    }
1900    staticInfo.update(ANDROID_CONTROL_AVAILABLE_SCENE_MODES,
1901                      avail_scene_modes,
1902                      size);
1903
1904    static uint8_t avail_antibanding_modes[CAM_ANTIBANDING_MODE_MAX];
1905    size = 0;
1906    for (int i = 0; i < gCamCapability[cameraId]->supported_antibandings_cnt; i++) {
1907        int val = lookupFwkName(ANTIBANDING_MODES_MAP,
1908                                 sizeof(ANTIBANDING_MODES_MAP)/sizeof(ANTIBANDING_MODES_MAP[0]),
1909                                 gCamCapability[cameraId]->supported_antibandings[i]);
1910        if (val != NAME_NOT_FOUND) {
1911            avail_antibanding_modes[size] = (uint8_t)val;
1912            size++;
1913        }
1914
1915    }
1916    staticInfo.update(ANDROID_CONTROL_AE_AVAILABLE_ANTIBANDING_MODES,
1917                      avail_antibanding_modes,
1918                      size);
1919
1920    static uint8_t avail_af_modes[CAM_FOCUS_MODE_MAX];
1921    size = 0;
1922    for (int i = 0; i < gCamCapability[cameraId]->supported_focus_modes_cnt; i++) {
1923        int val = lookupFwkName(FOCUS_MODES_MAP,
1924                                sizeof(FOCUS_MODES_MAP)/sizeof(FOCUS_MODES_MAP[0]),
1925                                gCamCapability[cameraId]->supported_focus_modes[i]);
1926        if (val != NAME_NOT_FOUND) {
1927            avail_af_modes[size] = (uint8_t)val;
1928            size++;
1929        }
1930    }
1931    staticInfo.update(ANDROID_CONTROL_AF_AVAILABLE_MODES,
1932                      avail_af_modes,
1933                      size);
1934
1935    static uint8_t avail_awb_modes[CAM_WB_MODE_MAX];
1936    size = 0;
1937    for (int i = 0; i < gCamCapability[cameraId]->supported_white_balances_cnt; i++) {
1938        int8_t val = lookupFwkName(WHITE_BALANCE_MODES_MAP,
1939                                    sizeof(WHITE_BALANCE_MODES_MAP)/sizeof(WHITE_BALANCE_MODES_MAP[0]),
1940                                    gCamCapability[cameraId]->supported_white_balances[i]);
1941        if (val != NAME_NOT_FOUND) {
1942            avail_awb_modes[size] = (uint8_t)val;
1943            size++;
1944        }
1945    }
1946    staticInfo.update(ANDROID_CONTROL_AWB_AVAILABLE_MODES,
1947                      avail_awb_modes,
1948                      size);
1949
1950    static uint8_t avail_flash_modes[CAM_FLASH_MODE_MAX];
1951    size = 0;
1952    for (int i = 0; i < gCamCapability[cameraId]->supported_flash_modes_cnt; i++) {
1953        int val = lookupFwkName(FLASH_MODES_MAP,
1954                                sizeof(FLASH_MODES_MAP)/sizeof(FLASH_MODES_MAP[0]),
1955                                gCamCapability[cameraId]->supported_flash_modes[i]);
1956        if (val != NAME_NOT_FOUND) {
1957            avail_flash_modes[size] = (uint8_t)val;
1958            size++;
1959        }
1960    }
1961    staticInfo.update(ANDROID_FLASH_MODE,
1962                      avail_flash_modes,
1963                      size);
1964
1965    /*so far fwk seems to support only 2 aec modes on and off*/
1966    static const uint8_t avail_ae_modes[] = {
1967            ANDROID_CONTROL_AE_MODE_OFF,
1968            ANDROID_CONTROL_AE_MODE_ON
1969    };
1970    staticInfo.update(ANDROID_CONTROL_AE_AVAILABLE_MODES,
1971                      avail_ae_modes,
1972                      sizeof(avail_ae_modes));
1973
1974    gStaticMetadata = staticInfo.release();
1975    return rc;
1976}
1977
1978/*===========================================================================
1979 * FUNCTION   : makeTable
1980 *
1981 * DESCRIPTION: make a table of sizes
1982 *
1983 * PARAMETERS :
1984 *
1985 *
1986 *
1987 * RETURN     : int32_t type of status
1988 *              NO_ERROR  -- success
1989 *              none-zero failure code
1990 *==========================================================================*/
1991void QCamera3HardwareInterface::makeTable(cam_dimension_t* dimTable, uint8_t size,
1992                                          int32_t* sizeTable)
1993{
1994    int j = 0;
1995    for (int i = 0; i < size; i++) {
1996        sizeTable[j] = dimTable[i].width;
1997        sizeTable[j+1] = dimTable[i].height;
1998        j+=2;
1999    }
2000}
2001
2002/*===========================================================================
2003 * FUNCTION   : makeFPSTable
2004 *
2005 * DESCRIPTION: make a table of fps ranges
2006 *
2007 * PARAMETERS :
2008 *
2009 *
2010 *
2011 * RETURN     : int32_t type of status
2012 *              NO_ERROR  -- success
2013 *              none-zero failure code
2014 *==========================================================================*/
2015void QCamera3HardwareInterface::makeFPSTable(cam_fps_range_t* fpsTable, uint8_t size,
2016                                          int32_t* fpsRangesTable)
2017{
2018    int j = 0;
2019    for (int i = 0; i < size; i++) {
2020        fpsRangesTable[j] = (int32_t)fpsTable[i].min_fps;
2021        fpsRangesTable[j+1] = (int32_t)fpsTable[i].max_fps;
2022        j+=2;
2023    }
2024}
2025/*===========================================================================
2026 * FUNCTION   : getPreviewHalPixelFormat
2027 *
2028 * DESCRIPTION: convert the format to type recognized by framework
2029 *
2030 * PARAMETERS : format : the format from backend
2031 *
2032 ** RETURN    : format recognized by framework
2033 *
2034 *==========================================================================*/
2035int32_t QCamera3HardwareInterface::getScalarFormat(int32_t format)
2036{
2037    int32_t halPixelFormat;
2038
2039    switch (format) {
2040    case CAM_FORMAT_YUV_420_NV12:
2041        halPixelFormat = HAL_PIXEL_FORMAT_YCbCr_420_SP;
2042        break;
2043    case CAM_FORMAT_YUV_420_NV21:
2044        halPixelFormat = HAL_PIXEL_FORMAT_YCrCb_420_SP;
2045        break;
2046    case CAM_FORMAT_YUV_420_NV21_ADRENO:
2047        halPixelFormat = HAL_PIXEL_FORMAT_YCrCb_420_SP_ADRENO;
2048        break;
2049    case CAM_FORMAT_YUV_420_YV12:
2050        halPixelFormat = HAL_PIXEL_FORMAT_YV12;
2051        break;
2052    case CAM_FORMAT_YUV_422_NV16:
2053    case CAM_FORMAT_YUV_422_NV61:
2054    default:
2055        halPixelFormat = HAL_PIXEL_FORMAT_YCrCb_420_SP;
2056        break;
2057    }
2058    return halPixelFormat;
2059}
2060
2061/*===========================================================================
2062 * FUNCTION   : AddSetParmEntryToBatch
2063 *
2064 * DESCRIPTION: add set parameter entry into batch
2065 *
2066 * PARAMETERS :
2067 *   @p_table     : ptr to parameter buffer
2068 *   @paramType   : parameter type
2069 *   @paramLength : length of parameter value
2070 *   @paramValue  : ptr to parameter value
2071 *
2072 * RETURN     : int32_t type of status
2073 *              NO_ERROR  -- success
2074 *              none-zero failure code
2075 *==========================================================================*/
2076int32_t QCamera3HardwareInterface::AddSetParmEntryToBatch(parm_buffer_t *p_table,
2077                                                          cam_intf_parm_type_t paramType,
2078                                                          uint32_t paramLength,
2079                                                          void *paramValue)
2080{
2081    int position = paramType;
2082    int current, next;
2083
2084    /*************************************************************************
2085    *                 Code to take care of linking next flags                *
2086    *************************************************************************/
2087    current = GET_FIRST_PARAM_ID(p_table);
2088    if (position == current){
2089        //DO NOTHING
2090    } else if (position < current){
2091        SET_NEXT_PARAM_ID(position, p_table, current);
2092        SET_FIRST_PARAM_ID(p_table, position);
2093    } else {
2094        /* Search for the position in the linked list where we need to slot in*/
2095        while (position > GET_NEXT_PARAM_ID(current, p_table))
2096            current = GET_NEXT_PARAM_ID(current, p_table);
2097
2098        /*If node already exists no need to alter linking*/
2099        if (position != GET_NEXT_PARAM_ID(current, p_table)) {
2100            next = GET_NEXT_PARAM_ID(current, p_table);
2101            SET_NEXT_PARAM_ID(current, p_table, position);
2102            SET_NEXT_PARAM_ID(position, p_table, next);
2103        }
2104    }
2105
2106    /*************************************************************************
2107    *                   Copy contents into entry                             *
2108    *************************************************************************/
2109
2110    if (paramLength > sizeof(parm_type_t)) {
2111        ALOGE("%s:Size of input larger than max entry size",__func__);
2112        return BAD_VALUE;
2113    }
2114    memcpy(POINTER_OF(paramType,p_table), paramValue, paramLength);
2115    return NO_ERROR;
2116}
2117
2118/*===========================================================================
2119 * FUNCTION   : lookupFwkName
2120 *
2121 * DESCRIPTION: In case the enum is not same in fwk and backend
2122 *              make sure the parameter is correctly propogated
2123 *
2124 * PARAMETERS  :
2125 *   @arr      : map between the two enums
2126 *   @len      : len of the map
2127 *   @hal_name : name of the hal_parm to map
2128 *
2129 * RETURN     : int type of status
2130 *              fwk_name  -- success
2131 *              none-zero failure code
2132 *==========================================================================*/
2133int8_t QCamera3HardwareInterface::lookupFwkName(const QCameraMap arr[],
2134                                             int len, int hal_name)
2135{
2136
2137    for (int i = 0; i < len; i++) {
2138        if (arr[i].hal_name == hal_name)
2139            return arr[i].fwk_name;
2140    }
2141
2142    /* Not able to find matching framework type is not necessarily
2143     * an error case. This happens when mm-camera supports more attributes
2144     * than the frameworks do */
2145    ALOGD("%s: Cannot find matching framework type", __func__);
2146    return NAME_NOT_FOUND;
2147}
2148
2149/*===========================================================================
2150 * FUNCTION   : lookupHalName
2151 *
2152 * DESCRIPTION: In case the enum is not same in fwk and backend
2153 *              make sure the parameter is correctly propogated
2154 *
2155 * PARAMETERS  :
2156 *   @arr      : map between the two enums
2157 *   @len      : len of the map
2158 *   @fwk_name : name of the hal_parm to map
2159 *
2160 * RETURN     : int32_t type of status
2161 *              hal_name  -- success
2162 *              none-zero failure code
2163 *==========================================================================*/
2164int8_t QCamera3HardwareInterface::lookupHalName(const QCameraMap arr[],
2165                                             int len, int fwk_name)
2166{
2167    for (int i = 0; i < len; i++) {
2168       if (arr[i].fwk_name == fwk_name)
2169           return arr[i].hal_name;
2170    }
2171    ALOGE("%s: Cannot find matching hal type", __func__);
2172    return NAME_NOT_FOUND;
2173}
2174
2175/*===========================================================================
2176 * FUNCTION   : getCapabilities
2177 *
2178 * DESCRIPTION: query camera capabilities
2179 *
2180 * PARAMETERS :
2181 *   @cameraId  : camera Id
2182 *   @info      : camera info struct to be filled in with camera capabilities
2183 *
2184 * RETURN     : int32_t type of status
2185 *              NO_ERROR  -- success
2186 *              none-zero failure code
2187 *==========================================================================*/
2188int QCamera3HardwareInterface::getCamInfo(int cameraId,
2189                                    struct camera_info *info)
2190{
2191    int rc = 0;
2192
2193    if (NULL == gCamCapability[cameraId]) {
2194        rc = initCapabilities(cameraId);
2195        if (rc < 0) {
2196            //pthread_mutex_unlock(&g_camlock);
2197            return rc;
2198        }
2199    }
2200
2201    if (NULL == gStaticMetadata) {
2202        rc = initStaticMetadata(cameraId);
2203        if (rc < 0) {
2204            return rc;
2205        }
2206    }
2207
2208    switch(gCamCapability[cameraId]->position) {
2209    case CAM_POSITION_BACK:
2210        info->facing = CAMERA_FACING_BACK;
2211        break;
2212
2213    case CAM_POSITION_FRONT:
2214        info->facing = CAMERA_FACING_FRONT;
2215        break;
2216
2217    default:
2218        ALOGE("%s:Unknown position type for camera id:%d", __func__, cameraId);
2219        rc = -1;
2220        break;
2221    }
2222
2223
2224    info->orientation = gCamCapability[cameraId]->sensor_mount_angle;
2225    info->device_version = HARDWARE_DEVICE_API_VERSION(3, 0);
2226    info->static_camera_characteristics = gStaticMetadata;
2227
2228    return rc;
2229}
2230
2231/*===========================================================================
2232 * FUNCTION   : translateMetadata
2233 *
2234 * DESCRIPTION: translate the metadata into camera_metadata_t
2235 *
2236 * PARAMETERS : type of the request
2237 *
2238 *
2239 * RETURN     : success: camera_metadata_t*
2240 *              failure: NULL
2241 *
2242 *==========================================================================*/
2243camera_metadata_t* QCamera3HardwareInterface::translateCapabilityToMetadata(int type)
2244{
2245    pthread_mutex_lock(&mMutex);
2246
2247    if (mDefaultMetadata[type] != NULL) {
2248        pthread_mutex_unlock(&mMutex);
2249        return mDefaultMetadata[type];
2250    }
2251    //first time we are handling this request
2252    //fill up the metadata structure using the wrapper class
2253    CameraMetadata settings;
2254    //translate from cam_capability_t to camera_metadata_tag_t
2255    static const uint8_t requestType = ANDROID_REQUEST_TYPE_CAPTURE;
2256    settings.update(ANDROID_REQUEST_TYPE, &requestType, 1);
2257
2258    /*control*/
2259
2260    uint8_t controlIntent = 0;
2261    switch (type) {
2262      case CAMERA3_TEMPLATE_PREVIEW:
2263        controlIntent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW;
2264        break;
2265      case CAMERA3_TEMPLATE_STILL_CAPTURE:
2266        controlIntent = ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE;
2267        break;
2268      case CAMERA3_TEMPLATE_VIDEO_RECORD:
2269        controlIntent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_RECORD;
2270        break;
2271      case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
2272        controlIntent = ANDROID_CONTROL_CAPTURE_INTENT_VIDEO_SNAPSHOT;
2273        break;
2274      case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
2275        controlIntent = ANDROID_CONTROL_CAPTURE_INTENT_ZERO_SHUTTER_LAG;
2276        break;
2277      default:
2278        controlIntent = ANDROID_CONTROL_CAPTURE_INTENT_CUSTOM;
2279        break;
2280    }
2281    settings.update(ANDROID_CONTROL_CAPTURE_INTENT, &controlIntent, 1);
2282
2283    settings.update(ANDROID_CONTROL_AE_EXPOSURE_COMPENSATION,
2284            &gCamCapability[mCameraId]->exposure_compensation_default, 1);
2285
2286    static const uint8_t aeLock = ANDROID_CONTROL_AE_LOCK_OFF;
2287    settings.update(ANDROID_CONTROL_AE_LOCK, &aeLock, 1);
2288
2289    static const uint8_t awbLock = ANDROID_CONTROL_AWB_LOCK_OFF;
2290    settings.update(ANDROID_CONTROL_AWB_LOCK, &awbLock, 1);
2291
2292    static const uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO;
2293    settings.update(ANDROID_CONTROL_AWB_MODE, &awbMode, 1);
2294
2295    static const uint8_t controlMode = ANDROID_CONTROL_MODE_AUTO;
2296    settings.update(ANDROID_CONTROL_MODE, &controlMode, 1);
2297
2298    static const uint8_t effectMode = ANDROID_CONTROL_EFFECT_MODE_OFF;
2299    settings.update(ANDROID_CONTROL_EFFECT_MODE, &effectMode, 1);
2300
2301    static const uint8_t sceneMode = ANDROID_CONTROL_SCENE_MODE_FACE_PRIORITY; //similar to AUTO?
2302    settings.update(ANDROID_CONTROL_SCENE_MODE, &sceneMode, 1);
2303
2304    /*flash*/
2305    static const uint8_t flashMode = ANDROID_FLASH_MODE_OFF;
2306    settings.update(ANDROID_FLASH_MODE, &flashMode, 1);
2307
2308
2309    /* lens */
2310    static const float default_aperture = gCamCapability[mCameraId]->apertures[0];
2311    settings.update(ANDROID_LENS_APERTURE, &default_aperture, 1);
2312
2313    if (gCamCapability[mCameraId]->filter_densities_count) {
2314        static const float default_filter_density = gCamCapability[mCameraId]->filter_densities[0];
2315        settings.update(ANDROID_LENS_FILTER_DENSITY, &default_filter_density,
2316                        gCamCapability[mCameraId]->filter_densities_count);
2317    }
2318
2319    /* TODO: Enable focus lengths once supported*/
2320    /*if (gCamCapability[mCameraId]->focal_lengths_count) {
2321        static const float default_focal_length = gCamCapability[mCameraId]->focal_lengths[0];
2322        settings.update(ANDROID_LENS_FOCAL_LENGTH, &default_focal_length, 1);
2323    }*/
2324
2325    mDefaultMetadata[type] = settings.release();
2326
2327    pthread_mutex_unlock(&mMutex);
2328    return mDefaultMetadata[type];
2329}
2330
2331/*===========================================================================
2332 * FUNCTION   : setFrameParameters
2333 *
2334 * DESCRIPTION: set parameters per frame as requested in the metadata from
2335 *              framework
2336 *
2337 * PARAMETERS :
2338 *   @settings  : frame settings information from framework
2339 *
2340 *
2341 * RETURN     : success: NO_ERROR
2342 *              failure:
2343 *==========================================================================*/
2344int QCamera3HardwareInterface::setFrameParameters(int frame_id,
2345                                                  const camera_metadata_t *settings)
2346{
2347    /*translate from camera_metadata_t type to parm_type_t*/
2348    int rc = 0;
2349    if (settings == NULL && mFirstRequest) {
2350        /*settings cannot be null for the first request*/
2351        return BAD_VALUE;
2352    }
2353
2354    int32_t hal_version = CAM_HAL_V3;
2355
2356    memset(mParameters, 0, sizeof(parm_buffer_t));
2357    mParameters->first_flagged_entry = CAM_INTF_PARM_MAX;
2358    AddSetParmEntryToBatch(mParameters, CAM_INTF_PARM_HAL_VERSION,
2359                sizeof(hal_version), &hal_version);
2360
2361    /*we need to update the frame number in the parameters*/
2362    rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_FRAME_NUMBER,
2363                                sizeof(frame_id), &frame_id);
2364    if (rc < 0) {
2365        ALOGE("%s: Failed to set the frame number in the parameters", __func__);
2366        return BAD_VALUE;
2367    }
2368
2369    if(settings != NULL){
2370        rc = translateMetadataToParameters(settings);
2371    }
2372    /*set the parameters to backend*/
2373    mCameraHandle->ops->set_parms(mCameraHandle->camera_handle, mParameters);
2374    return rc;
2375}
2376
2377/*===========================================================================
2378 * FUNCTION   : translateMetadataToParameters
2379 *
2380 * DESCRIPTION: read from the camera_metadata_t and change to parm_type_t
2381 *
2382 *
2383 * PARAMETERS :
2384 *   @settings  : frame settings information from framework
2385 *
2386 *
2387 * RETURN     : success: NO_ERROR
2388 *              failure:
2389 *==========================================================================*/
2390int QCamera3HardwareInterface::translateMetadataToParameters
2391                                  (const camera_metadata_t *settings)
2392{
2393    int rc = 0;
2394    CameraMetadata frame_settings;
2395    frame_settings = settings;
2396
2397
2398    if (frame_settings.exists(ANDROID_CONTROL_AE_ANTIBANDING_MODE)) {
2399        int32_t antibandingMode =
2400            frame_settings.find(ANDROID_CONTROL_AE_ANTIBANDING_MODE).data.i32[0];
2401        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_PARM_ANTIBANDING,
2402                sizeof(antibandingMode), &antibandingMode);
2403    }
2404
2405    /*int32_t expCompensation = frame_settings.find().data.i32[0];
2406      rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_PARM_EXPOSURE_COMPENSATION,
2407      sizeof(expCompensation), &expCompensation);*/
2408    if (frame_settings.exists(ANDROID_CONTROL_AE_LOCK)) {
2409        uint8_t aeLock = frame_settings.find(ANDROID_CONTROL_AE_LOCK).data.u8[0];
2410        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_PARM_AEC_LOCK,
2411                sizeof(aeLock), &aeLock);
2412    }
2413
2414    if (frame_settings.exists(ANDROID_CONTROL_AE_TARGET_FPS_RANGE)) {
2415        cam_fps_range_t fps_range;
2416        fps_range.min_fps =
2417            frame_settings.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE).data.i32[0];
2418        fps_range.max_fps =
2419            frame_settings.find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE).data.i32[0];
2420        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_PARM_FPS_RANGE,
2421                sizeof(fps_range), &fps_range);
2422    }
2423
2424    if (frame_settings.exists(ANDROID_CONTROL_AF_MODE)) {
2425        uint8_t focusMode =
2426            frame_settings.find(ANDROID_CONTROL_AF_MODE).data.u8[0];
2427        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_PARM_FOCUS_MODE,
2428                sizeof(focusMode), &focusMode);
2429    }
2430
2431    if (frame_settings.exists(ANDROID_CONTROL_AWB_LOCK)) {
2432        uint8_t awbLock =
2433            frame_settings.find(ANDROID_CONTROL_AWB_LOCK).data.u8[0];
2434        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_PARM_AWB_LOCK,
2435                sizeof(awbLock), &awbLock);
2436    }
2437
2438    if (frame_settings.exists(ANDROID_CONTROL_AWB_MODE)) {
2439        uint8_t fwk_whiteLevel =
2440            frame_settings.find(ANDROID_CONTROL_AWB_MODE).data.u8[0];
2441        uint8_t whiteLevel = lookupHalName(WHITE_BALANCE_MODES_MAP,
2442                sizeof(WHITE_BALANCE_MODES_MAP),
2443                fwk_whiteLevel);
2444        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_PARM_WHITE_BALANCE,
2445                sizeof(whiteLevel), &whiteLevel);
2446    }
2447
2448    if (frame_settings.exists(ANDROID_CONTROL_EFFECT_MODE)) {
2449        uint8_t fwk_effectMode =
2450            frame_settings.find(ANDROID_CONTROL_EFFECT_MODE).data.u8[0];
2451        uint8_t effectMode = lookupHalName(EFFECT_MODES_MAP,
2452                sizeof(EFFECT_MODES_MAP),
2453                fwk_effectMode);
2454        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_PARM_EFFECT,
2455                sizeof(effectMode), &effectMode);
2456    }
2457
2458    if (frame_settings.exists(ANDROID_CONTROL_AE_MODE)) {
2459        uint8_t fwk_aeMode =
2460            frame_settings.find(ANDROID_CONTROL_AE_MODE).data.u8[0];
2461        uint8_t aeMode = lookupHalName(AUTO_EXPOSURE_MAP,
2462                sizeof(AUTO_EXPOSURE_MAP),
2463                fwk_aeMode);
2464        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_AEC_MODE,
2465                sizeof(aeMode), &aeMode);
2466    }
2467
2468    if (frame_settings.exists(ANDROID_REQUEST_FRAME_COUNT)) {
2469        int32_t metaFrameNumber =
2470            frame_settings.find(ANDROID_REQUEST_FRAME_COUNT).data.i32[0];
2471        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_FRAME_NUMBER,
2472                sizeof(metaFrameNumber), &metaFrameNumber);
2473    }
2474
2475    if (frame_settings.exists(ANDROID_COLOR_CORRECTION_MODE)) {
2476        uint8_t colorCorrectMode =
2477            frame_settings.find(ANDROID_COLOR_CORRECTION_MODE).data.u8[0];
2478        rc =
2479            AddSetParmEntryToBatch(mParameters, CAM_INTF_META_COLOR_CORRECT_MODE,
2480                    sizeof(colorCorrectMode), &colorCorrectMode);
2481    }
2482
2483    uint8_t aecTrigger = CAM_AEC_TRIGGER_IDLE;
2484    if (frame_settings.exists(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER)) {
2485        aecTrigger =
2486            frame_settings.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER).data.u8[0];
2487    }
2488    rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_AEC_PRECAPTURE_TRIGGER,
2489                                sizeof(aecTrigger), &aecTrigger);
2490
2491    if (frame_settings.exists(ANDROID_CONTROL_AF_TRIGGER)) {
2492        uint8_t afTrigger =
2493            frame_settings.find(ANDROID_CONTROL_AF_TRIGGER).data.u8[0];
2494        rc = AddSetParmEntryToBatch(mParameters,
2495                CAM_INTF_META_AF_TRIGGER, sizeof(afTrigger), &afTrigger);
2496    }
2497
2498    if (frame_settings.exists(ANDROID_CONTROL_MODE)) {
2499        uint8_t metaMode = frame_settings.find(ANDROID_CONTROL_MODE).data.u8[0];
2500        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_MODE,
2501                sizeof(metaMode), &metaMode);
2502    }
2503
2504    if (frame_settings.exists(ANDROID_DEMOSAIC_MODE)) {
2505        int32_t demosaic =
2506            frame_settings.find(ANDROID_DEMOSAIC_MODE).data.u8[0];
2507        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_DEMOSAIC,
2508                sizeof(demosaic), &demosaic);
2509    }
2510
2511    if (frame_settings.exists(ANDROID_EDGE_MODE)) {
2512        uint8_t edgeMode = frame_settings.find(ANDROID_EDGE_MODE).data.u8[0];
2513        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_EDGE,
2514                sizeof(edgeMode), &edgeMode);
2515    }
2516
2517    if (frame_settings.exists(ANDROID_EDGE_STRENGTH)) {
2518        int32_t edgeStrength =
2519            frame_settings.find(ANDROID_EDGE_STRENGTH).data.i32[0];
2520        rc = AddSetParmEntryToBatch(mParameters,
2521                CAM_INTF_META_SHARPNESS_STRENGTH, sizeof(edgeStrength), &edgeStrength);
2522    }
2523
2524    if (frame_settings.exists(ANDROID_FLASH_FIRING_POWER)) {
2525        uint8_t flashPower =
2526            frame_settings.find(ANDROID_FLASH_FIRING_POWER).data.u8[0];
2527        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_FLASH_POWER,
2528                sizeof(flashPower), &flashPower);
2529    }
2530
2531    if (frame_settings.exists(ANDROID_FLASH_FIRING_TIME)) {
2532        int64_t flashFiringTime =
2533            frame_settings.find(ANDROID_FLASH_FIRING_TIME).data.i64[0];
2534        rc = AddSetParmEntryToBatch(mParameters,
2535                CAM_INTF_META_FLASH_FIRING_TIME, sizeof(flashFiringTime), &flashFiringTime);
2536    }
2537
2538    if (frame_settings.exists(ANDROID_GEOMETRIC_MODE)) {
2539        uint8_t geometricMode =
2540            frame_settings.find(ANDROID_GEOMETRIC_MODE).data.u8[0];
2541        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_GEOMETRIC_MODE,
2542                sizeof(geometricMode), &geometricMode);
2543    }
2544
2545    if (frame_settings.exists(ANDROID_GEOMETRIC_STRENGTH)) {
2546        uint8_t geometricStrength =
2547            frame_settings.find(ANDROID_GEOMETRIC_STRENGTH).data.u8[0];
2548        rc = AddSetParmEntryToBatch(mParameters,
2549                CAM_INTF_META_GEOMETRIC_STRENGTH,
2550                sizeof(geometricStrength), &geometricStrength);
2551    }
2552
2553    if (frame_settings.exists(ANDROID_HOT_PIXEL_MODE)) {
2554        uint8_t hotPixelMode =
2555            frame_settings.find(ANDROID_HOT_PIXEL_MODE).data.u8[0];
2556        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_HOTPIXEL_MODE,
2557                sizeof(hotPixelMode), &hotPixelMode);
2558    }
2559
2560    if (frame_settings.exists(ANDROID_LENS_APERTURE)) {
2561        float lensAperture =
2562            frame_settings.find( ANDROID_LENS_APERTURE).data.f[0];
2563        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_LENS_APERTURE,
2564                sizeof(lensAperture), &lensAperture);
2565    }
2566
2567    if (frame_settings.exists(ANDROID_LENS_FILTER_DENSITY)) {
2568        float filterDensity =
2569            frame_settings.find(ANDROID_LENS_FILTER_DENSITY).data.f[0];
2570        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_LENS_FILTERDENSITY,
2571                sizeof(filterDensity), &filterDensity);
2572    }
2573
2574    if (frame_settings.exists(ANDROID_LENS_FOCAL_LENGTH)) {
2575        float focalLength =
2576            frame_settings.find(ANDROID_LENS_FOCAL_LENGTH).data.f[0];
2577        rc = AddSetParmEntryToBatch(mParameters,
2578                CAM_INTF_META_LENS_FOCAL_LENGTH,
2579                sizeof(focalLength), &focalLength);
2580    }
2581
2582    if (frame_settings.exists(ANDROID_LENS_FOCUS_DISTANCE)) {
2583        float focalDistance =
2584            frame_settings.find(ANDROID_LENS_FOCUS_DISTANCE).data.f[0];
2585        rc = AddSetParmEntryToBatch(mParameters,
2586                CAM_INTF_META_LENS_FOCUS_DISTANCE,
2587                sizeof(focalDistance), &focalDistance);
2588    }
2589
2590    if (frame_settings.exists(ANDROID_LENS_OPTICAL_STABILIZATION_MODE)) {
2591        uint8_t optStabMode =
2592            frame_settings.find(ANDROID_LENS_OPTICAL_STABILIZATION_MODE).data.u8[0];
2593        rc = AddSetParmEntryToBatch(mParameters,
2594                CAM_INTF_META_LENS_OPT_STAB_MODE,
2595                sizeof(optStabMode), &optStabMode);
2596    }
2597
2598    if (frame_settings.exists(ANDROID_NOISE_REDUCTION_MODE)) {
2599        uint8_t noiseRedMode =
2600            frame_settings.find(ANDROID_NOISE_REDUCTION_MODE).data.u8[0];
2601        rc = AddSetParmEntryToBatch(mParameters,
2602                CAM_INTF_META_NOISE_REDUCTION_MODE,
2603                sizeof(noiseRedMode), &noiseRedMode);
2604    }
2605
2606    if (frame_settings.exists(ANDROID_NOISE_REDUCTION_STRENGTH)) {
2607        uint8_t noiseRedStrength =
2608            frame_settings.find(ANDROID_NOISE_REDUCTION_STRENGTH).data.u8[0];
2609        rc = AddSetParmEntryToBatch(mParameters,
2610                CAM_INTF_META_NOISE_REDUCTION_STRENGTH,
2611                sizeof(noiseRedStrength), &noiseRedStrength);
2612    }
2613
2614    if (frame_settings.exists(ANDROID_SCALER_CROP_REGION)) {
2615        cam_crop_region_t scalerCropRegion;
2616        scalerCropRegion.left =
2617            frame_settings.find(ANDROID_SCALER_CROP_REGION).data.i32[0];
2618        scalerCropRegion.top =
2619            frame_settings.find(ANDROID_SCALER_CROP_REGION).data.i32[1];
2620        scalerCropRegion.width =
2621            frame_settings.find(ANDROID_SCALER_CROP_REGION).data.i32[2];
2622        rc = AddSetParmEntryToBatch(mParameters,
2623                CAM_INTF_META_SCALER_CROP_REGION,
2624                sizeof(scalerCropRegion), &scalerCropRegion);
2625    }
2626
2627    if (frame_settings.exists(ANDROID_SENSOR_EXPOSURE_TIME)) {
2628        int64_t sensorExpTime =
2629            frame_settings.find(ANDROID_SENSOR_EXPOSURE_TIME).data.i64[0];
2630        rc = AddSetParmEntryToBatch(mParameters,
2631                CAM_INTF_META_SENSOR_EXPOSURE_TIME,
2632                sizeof(sensorExpTime), &sensorExpTime);
2633    }
2634
2635    if (frame_settings.exists(ANDROID_SENSOR_FRAME_DURATION)) {
2636        int64_t sensorFrameDuration =
2637            frame_settings.find(ANDROID_SENSOR_FRAME_DURATION).data.i64[0];
2638        rc = AddSetParmEntryToBatch(mParameters,
2639                CAM_INTF_META_SENSOR_FRAME_DURATION,
2640                sizeof(sensorFrameDuration), &sensorFrameDuration);
2641    }
2642
2643    if (frame_settings.exists(ANDROID_SENSOR_SENSITIVITY)) {
2644        int32_t sensorSensitivity =
2645            frame_settings.find(ANDROID_SENSOR_SENSITIVITY).data.i32[0];
2646        rc = AddSetParmEntryToBatch(mParameters,
2647                CAM_INTF_META_SENSOR_SENSITIVITY,
2648                sizeof(sensorSensitivity), &sensorSensitivity);
2649    }
2650
2651    if (frame_settings.exists(ANDROID_SHADING_MODE)) {
2652        int32_t shadingMode =
2653            frame_settings.find(ANDROID_SHADING_MODE).data.u8[0];
2654        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_SHADING_MODE,
2655                sizeof(shadingMode), &shadingMode);
2656    }
2657
2658    if (frame_settings.exists(ANDROID_SHADING_STRENGTH)) {
2659        uint8_t shadingStrength =
2660            frame_settings.find(ANDROID_SHADING_STRENGTH).data.u8[0];
2661        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_SHADING_STRENGTH,
2662                sizeof(shadingStrength), &shadingStrength);
2663    }
2664
2665    if (frame_settings.exists(ANDROID_STATISTICS_FACE_DETECT_MODE)) {
2666        uint8_t facedetectMode =
2667            frame_settings.find(ANDROID_STATISTICS_FACE_DETECT_MODE).data.u8[0];
2668        rc = AddSetParmEntryToBatch(mParameters,
2669                CAM_INTF_META_STATS_FACEDETECT_MODE,
2670                sizeof(facedetectMode), &facedetectMode);
2671    }
2672
2673    if (frame_settings.exists(ANDROID_STATISTICS_HISTOGRAM_MODE)) {
2674        uint8_t histogramMode =
2675            frame_settings.find(ANDROID_STATISTICS_HISTOGRAM_MODE).data.u8[0];
2676        rc = AddSetParmEntryToBatch(mParameters,
2677                CAM_INTF_META_STATS_HISTOGRAM_MODE,
2678                sizeof(histogramMode), &histogramMode);
2679    }
2680
2681    if (frame_settings.exists(ANDROID_STATISTICS_SHARPNESS_MAP_MODE)) {
2682        uint8_t sharpnessMapMode =
2683            frame_settings.find(ANDROID_STATISTICS_SHARPNESS_MAP_MODE).data.u8[0];
2684        rc = AddSetParmEntryToBatch(mParameters,
2685                CAM_INTF_META_STATS_SHARPNESS_MAP_MODE,
2686                sizeof(sharpnessMapMode), &sharpnessMapMode);
2687    }
2688
2689    if (frame_settings.exists(ANDROID_TONEMAP_MODE)) {
2690        uint8_t tonemapMode =
2691            frame_settings.find(ANDROID_TONEMAP_MODE).data.u8[0];
2692        rc = AddSetParmEntryToBatch(mParameters,
2693                CAM_INTF_META_TONEMAP_MODE,
2694                sizeof(tonemapMode), &tonemapMode);
2695    }
2696
2697    if (frame_settings.exists(ANDROID_CONTROL_CAPTURE_INTENT)) {
2698        uint8_t captureIntent =
2699            frame_settings.find(ANDROID_CONTROL_CAPTURE_INTENT).data.u8[0];
2700        rc = AddSetParmEntryToBatch(mParameters, CAM_INTF_META_CAPTURE_INTENT,
2701                sizeof(captureIntent), &captureIntent);
2702    }
2703
2704    return rc;
2705}
2706
2707/*===========================================================================
2708 * FUNCTION   : getJpegSettings
2709 *
2710 * DESCRIPTION: save the jpeg settings in the HAL
2711 *
2712 *
2713 * PARAMETERS :
2714 *   @settings  : frame settings information from framework
2715 *
2716 *
2717 * RETURN     : success: NO_ERROR
2718 *              failure:
2719 *==========================================================================*/
2720int QCamera3HardwareInterface::getJpegSettings
2721                                  (const camera_metadata_t *settings)
2722{
2723    if (mJpegSettings) {
2724        free(mJpegSettings);
2725        mJpegSettings = NULL;
2726    }
2727    mJpegSettings = (jpeg_settings_t*) malloc(sizeof(jpeg_settings_t));
2728    CameraMetadata jpeg_settings;
2729    jpeg_settings = settings;
2730
2731    if (jpeg_settings.exists(ANDROID_JPEG_ORIENTATION)) {
2732        mJpegSettings->jpeg_orientation =
2733            jpeg_settings.find(ANDROID_JPEG_ORIENTATION).data.i32[0];
2734    } else {
2735        mJpegSettings->jpeg_orientation = 0;
2736    }
2737    if (jpeg_settings.exists(ANDROID_JPEG_QUALITY)) {
2738        mJpegSettings->jpeg_quality =
2739            jpeg_settings.find(ANDROID_JPEG_QUALITY).data.u8[0];
2740    } else {
2741        mJpegSettings->jpeg_quality = 85;
2742    }
2743    if (jpeg_settings.exists(ANDROID_JPEG_THUMBNAIL_SIZE)) {
2744        mJpegSettings->thumbnail_size.width =
2745            jpeg_settings.find(ANDROID_JPEG_THUMBNAIL_SIZE).data.i32[0];
2746        mJpegSettings->thumbnail_size.height =
2747            jpeg_settings.find(ANDROID_JPEG_THUMBNAIL_SIZE).data.i32[1];
2748        mJpegSettings->thumbnail_size.width = 320;
2749        mJpegSettings->thumbnail_size.height = 240;
2750    } else {
2751        mJpegSettings->thumbnail_size.width = 640;
2752        mJpegSettings->thumbnail_size.height = 480;
2753    }
2754    if (jpeg_settings.exists(ANDROID_JPEG_GPS_COORDINATES)) {
2755        for (int i = 0; i < 3; i++) {
2756            mJpegSettings->gps_coordinates[i] =
2757                jpeg_settings.find(ANDROID_JPEG_GPS_COORDINATES).data.d[i];
2758        }
2759    }
2760    if (jpeg_settings.exists(ANDROID_JPEG_GPS_TIMESTAMP)) {
2761        mJpegSettings->gps_timestamp =
2762            jpeg_settings.find(ANDROID_JPEG_GPS_TIMESTAMP).data.i64[0];
2763    }
2764
2765    if (jpeg_settings.exists(ANDROID_JPEG_GPS_PROCESSING_METHOD)) {
2766        mJpegSettings->gps_processing_method =
2767            jpeg_settings.find(ANDROID_JPEG_GPS_PROCESSING_METHOD).data.u8[0];
2768    }
2769    if (jpeg_settings.exists(ANDROID_SENSOR_SENSITIVITY)) {
2770        mJpegSettings->sensor_sensitivity =
2771            jpeg_settings.find(ANDROID_SENSOR_SENSITIVITY).data.i32[0];
2772    }
2773    if (jpeg_settings.exists(ANDROID_LENS_FOCAL_LENGTH)) {
2774        mJpegSettings->lens_focal_length =
2775            jpeg_settings.find(ANDROID_LENS_FOCAL_LENGTH).data.f[0];
2776    }
2777    return 0;
2778}
2779
2780/*===========================================================================
2781 * FUNCTION   : captureResultCb
2782 *
2783 * DESCRIPTION: Callback handler for all channels (streams, as well as metadata)
2784 *
2785 * PARAMETERS :
2786 *   @frame  : frame information from mm-camera-interface
2787 *   @buffer : actual gralloc buffer to be returned to frameworks. NULL if metadata.
2788 *   @userdata: userdata
2789 *
2790 * RETURN     : NONE
2791 *==========================================================================*/
2792void QCamera3HardwareInterface::captureResultCb(mm_camera_super_buf_t *metadata,
2793                camera3_stream_buffer_t *buffer,
2794                uint32_t frame_number, void *userdata)
2795{
2796    QCamera3HardwareInterface *hw = (QCamera3HardwareInterface *)userdata;
2797    if (hw == NULL) {
2798        ALOGE("%s: Invalid hw %p", __func__, hw);
2799        return;
2800    }
2801
2802    hw->captureResultCb(metadata, buffer, frame_number);
2803    return;
2804}
2805
2806/*===========================================================================
2807 * FUNCTION   : initialize
2808 *
2809 * DESCRIPTION: Pass framework callback pointers to HAL
2810 *
2811 * PARAMETERS :
2812 *
2813 *
2814 * RETURN     : Success : 0
2815 *              Failure: -ENODEV
2816 *==========================================================================*/
2817
2818int QCamera3HardwareInterface::initialize(const struct camera3_device *device,
2819                                  const camera3_callback_ops_t *callback_ops)
2820{
2821    ALOGV("%s: E", __func__);
2822    QCamera3HardwareInterface *hw =
2823        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
2824    if (!hw) {
2825        ALOGE("%s: NULL camera device", __func__);
2826        return -ENODEV;
2827    }
2828
2829    int rc = hw->initialize(callback_ops);
2830    ALOGV("%s: X", __func__);
2831    return rc;
2832}
2833
2834/*===========================================================================
2835 * FUNCTION   : configure_streams
2836 *
2837 * DESCRIPTION:
2838 *
2839 * PARAMETERS :
2840 *
2841 *
2842 * RETURN     : Success: 0
2843 *              Failure: -EINVAL (if stream configuration is invalid)
2844 *                       -ENODEV (fatal error)
2845 *==========================================================================*/
2846
2847int QCamera3HardwareInterface::configure_streams(
2848        const struct camera3_device *device,
2849        camera3_stream_configuration_t *stream_list)
2850{
2851    ALOGV("%s: E", __func__);
2852    QCamera3HardwareInterface *hw =
2853        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
2854    if (!hw) {
2855        ALOGE("%s: NULL camera device", __func__);
2856        return -ENODEV;
2857    }
2858    int rc = hw->configureStreams(stream_list);
2859    ALOGV("%s: X", __func__);
2860    return rc;
2861}
2862
2863/*===========================================================================
2864 * FUNCTION   : register_stream_buffers
2865 *
2866 * DESCRIPTION: Register stream buffers with the device
2867 *
2868 * PARAMETERS :
2869 *
2870 * RETURN     :
2871 *==========================================================================*/
2872int QCamera3HardwareInterface::register_stream_buffers(
2873        const struct camera3_device *device,
2874        const camera3_stream_buffer_set_t *buffer_set)
2875{
2876    ALOGV("%s: E", __func__);
2877    QCamera3HardwareInterface *hw =
2878        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
2879    if (!hw) {
2880        ALOGE("%s: NULL camera device", __func__);
2881        return -ENODEV;
2882    }
2883    int rc = hw->registerStreamBuffers(buffer_set);
2884    ALOGV("%s: X", __func__);
2885    return rc;
2886}
2887
2888/*===========================================================================
2889 * FUNCTION   : construct_default_request_settings
2890 *
2891 * DESCRIPTION: Configure a settings buffer to meet the required use case
2892 *
2893 * PARAMETERS :
2894 *
2895 *
2896 * RETURN     : Success: Return valid metadata
2897 *              Failure: Return NULL
2898 *==========================================================================*/
2899const camera_metadata_t* QCamera3HardwareInterface::
2900    construct_default_request_settings(const struct camera3_device *device,
2901                                        int type)
2902{
2903
2904    ALOGV("%s: E", __func__);
2905    camera_metadata_t* fwk_metadata = NULL;
2906    QCamera3HardwareInterface *hw =
2907        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
2908    if (!hw) {
2909        ALOGE("%s: NULL camera device", __func__);
2910        return NULL;
2911    }
2912
2913    fwk_metadata = hw->translateCapabilityToMetadata(type);
2914
2915    ALOGV("%s: X", __func__);
2916    return fwk_metadata;
2917}
2918
2919/*===========================================================================
2920 * FUNCTION   : process_capture_request
2921 *
2922 * DESCRIPTION:
2923 *
2924 * PARAMETERS :
2925 *
2926 *
2927 * RETURN     :
2928 *==========================================================================*/
2929int QCamera3HardwareInterface::process_capture_request(
2930                    const struct camera3_device *device,
2931                    camera3_capture_request_t *request)
2932{
2933    ALOGV("%s: E", __func__);
2934    QCamera3HardwareInterface *hw =
2935        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
2936    if (!hw) {
2937        ALOGE("%s: NULL camera device", __func__);
2938        return -EINVAL;
2939    }
2940
2941    int rc = hw->processCaptureRequest(request);
2942    ALOGV("%s: X", __func__);
2943    return rc;
2944}
2945
2946/*===========================================================================
2947 * FUNCTION   : get_metadata_vendor_tag_ops
2948 *
2949 * DESCRIPTION:
2950 *
2951 * PARAMETERS :
2952 *
2953 *
2954 * RETURN     :
2955 *==========================================================================*/
2956
2957void QCamera3HardwareInterface::get_metadata_vendor_tag_ops(
2958                const struct camera3_device *device,
2959                vendor_tag_query_ops_t* ops)
2960{
2961    ALOGV("%s: E", __func__);
2962    QCamera3HardwareInterface *hw =
2963        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
2964    if (!hw) {
2965        ALOGE("%s: NULL camera device", __func__);
2966        return;
2967    }
2968
2969    hw->getMetadataVendorTagOps(ops);
2970    ALOGV("%s: X", __func__);
2971    return;
2972}
2973
2974/*===========================================================================
2975 * FUNCTION   : dump
2976 *
2977 * DESCRIPTION:
2978 *
2979 * PARAMETERS :
2980 *
2981 *
2982 * RETURN     :
2983 *==========================================================================*/
2984
2985void QCamera3HardwareInterface::dump(
2986                const struct camera3_device *device, int fd)
2987{
2988    ALOGV("%s: E", __func__);
2989    QCamera3HardwareInterface *hw =
2990        reinterpret_cast<QCamera3HardwareInterface *>(device->priv);
2991    if (!hw) {
2992        ALOGE("%s: NULL camera device", __func__);
2993        return;
2994    }
2995
2996    hw->dump(fd);
2997    ALOGV("%s: X", __func__);
2998    return;
2999}
3000
3001/*===========================================================================
3002 * FUNCTION   : close_camera_device
3003 *
3004 * DESCRIPTION:
3005 *
3006 * PARAMETERS :
3007 *
3008 *
3009 * RETURN     :
3010 *==========================================================================*/
3011int QCamera3HardwareInterface::close_camera_device(struct hw_device_t* device)
3012{
3013    ALOGV("%s: E", __func__);
3014    int ret = NO_ERROR;
3015    QCamera3HardwareInterface *hw =
3016        reinterpret_cast<QCamera3HardwareInterface *>(
3017            reinterpret_cast<camera3_device_t *>(device)->priv);
3018    if (!hw) {
3019        ALOGE("NULL camera device");
3020        return BAD_VALUE;
3021    }
3022    delete hw;
3023    ALOGV("%s: X", __func__);
3024    return ret;
3025}
3026
3027}; //end namespace qcamera
3028