Home | History | Annotate | Download | only in default
      1 /*
      2  * Copyright (C) 2017 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #define LOG_TAG "CamDev (at) 1.0-impl"
     18 #include <hardware/camera.h>
     19 #include <hardware/gralloc1.h>
     20 #include <hidlmemory/mapping.h>
     21 #include <log/log.h>
     22 #include <utils/Trace.h>
     23 
     24 #include <media/hardware/HardwareAPI.h> // For VideoNativeHandleMetadata
     25 #include "CameraDevice_1_0.h"
     26 
     27 namespace android {
     28 namespace hardware {
     29 namespace camera {
     30 namespace device {
     31 namespace V1_0 {
     32 namespace implementation {
     33 
     34 using ::android::hardware::graphics::common::V1_0::BufferUsage;
     35 using ::android::hardware::graphics::common::V1_0::PixelFormat;
     36 
     37 HandleImporter CameraDevice::sHandleImporter;
     38 
     39 Status CameraDevice::getHidlStatus(const int& status) {
     40     switch (status) {
     41         case 0: return Status::OK;
     42         case -ENOSYS: return Status::OPERATION_NOT_SUPPORTED;
     43         case -EBUSY : return Status::CAMERA_IN_USE;
     44         case -EUSERS: return Status::MAX_CAMERAS_IN_USE;
     45         case -ENODEV: return Status::INTERNAL_ERROR;
     46         case -EINVAL: return Status::ILLEGAL_ARGUMENT;
     47         default:
     48             ALOGE("%s: unknown HAL status code %d", __FUNCTION__, status);
     49             return Status::INTERNAL_ERROR;
     50     }
     51 }
     52 
     53 status_t CameraDevice::getStatusT(const Status& s)  {
     54     switch(s) {
     55         case Status::OK:
     56             return OK;
     57         case Status::ILLEGAL_ARGUMENT:
     58             return BAD_VALUE;
     59         case Status::CAMERA_IN_USE:
     60             return -EBUSY;
     61         case Status::MAX_CAMERAS_IN_USE:
     62             return -EUSERS;
     63         case Status::METHOD_NOT_SUPPORTED:
     64             return UNKNOWN_TRANSACTION;
     65         case Status::OPERATION_NOT_SUPPORTED:
     66             return INVALID_OPERATION;
     67         case Status::CAMERA_DISCONNECTED:
     68             return DEAD_OBJECT;
     69         case Status::INTERNAL_ERROR:
     70             return INVALID_OPERATION;
     71     }
     72     ALOGW("Unexpected HAL status code %d", s);
     73     return INVALID_OPERATION;
     74 }
     75 
     76 Status CameraDevice::initStatus() const {
     77     Mutex::Autolock _l(mLock);
     78     Status status = Status::OK;
     79     if (mInitFail) {
     80         status = Status::INTERNAL_ERROR;
     81     } else if (mDisconnected) {
     82         status = Status::CAMERA_DISCONNECTED;
     83     }
     84     return status;
     85 }
     86 
     87 CameraDevice::CameraDevice(
     88     sp<CameraModule> module, const std::string& cameraId,
     89     const SortedVector<std::pair<std::string, std::string>>& cameraDeviceNames) :
     90         mModule(module),
     91         mCameraId(cameraId),
     92         mDisconnected(false),
     93         mCameraDeviceNames(cameraDeviceNames) {
     94     mCameraIdInt = atoi(mCameraId.c_str());
     95     // Should not reach here as provider also validate ID
     96     if (mCameraIdInt < 0 || mCameraIdInt >= module->getNumberOfCameras()) {
     97         ALOGE("%s: Invalid camera id: %s", __FUNCTION__, mCameraId.c_str());
     98         mInitFail = true;
     99     }
    100 
    101     mDeviceVersion = mModule->getDeviceVersion(mCameraIdInt);
    102     if (mDeviceVersion != CAMERA_DEVICE_API_VERSION_1_0 && !mModule->isOpenLegacyDefined()) {
    103         ALOGI("%s: Camera id %s does not support HAL1.0",
    104                 __FUNCTION__, mCameraId.c_str());
    105         mInitFail = true;
    106     }
    107 
    108     mAshmemAllocator = IAllocator::getService("ashmem");
    109     if (mAshmemAllocator == nullptr) {
    110         ALOGI("%s: cannot get ashmemAllocator", __FUNCTION__);
    111         mInitFail = true;
    112     }
    113 }
    114 
    115 CameraDevice::~CameraDevice() {
    116     Mutex::Autolock _l(mLock);
    117     if (mDevice != nullptr) {
    118         ALOGW("%s: camera %s is deleted while open", __FUNCTION__, mCameraId.c_str());
    119         closeLocked();
    120     }
    121     mHalPreviewWindow.cleanUpCirculatingBuffers();
    122 }
    123 
    124 
    125 void CameraDevice::setConnectionStatus(bool connected) {
    126     Mutex::Autolock _l(mLock);
    127     mDisconnected = !connected;
    128     if (mDevice == nullptr) {
    129         return;
    130     }
    131     if (!connected) {
    132         ALOGW("%s: camera %s is disconneted. Closing", __FUNCTION__, mCameraId.c_str());
    133         closeLocked();
    134     }
    135     return;
    136 }
    137 
    138 void CameraDevice::CameraPreviewWindow::cleanUpCirculatingBuffers() {
    139     Mutex::Autolock _l(mLock);
    140     for (auto pair : mCirculatingBuffers) {
    141         sHandleImporter.freeBuffer(pair.second);
    142     }
    143     mCirculatingBuffers.clear();
    144     mBufferIdMap.clear();
    145 }
    146 
    147 int CameraDevice::sDequeueBuffer(struct preview_stream_ops* w,
    148                                    buffer_handle_t** buffer, int *stride) {
    149     CameraPreviewWindow* object = static_cast<CameraPreviewWindow*>(w);
    150     if (object->mPreviewCallback == nullptr) {
    151         ALOGE("%s: camera HAL calling preview ops while there is no preview window!", __FUNCTION__);
    152         return INVALID_OPERATION;
    153     }
    154 
    155     if (buffer == nullptr || stride == nullptr) {
    156         ALOGE("%s: buffer (%p) and stride (%p) must not be null!", __FUNCTION__, buffer, stride);
    157         return BAD_VALUE;
    158     }
    159 
    160     Status s;
    161     object->mPreviewCallback->dequeueBuffer(
    162         [&](auto status, uint64_t bufferId, const auto& buf, uint32_t strd) {
    163             s = status;
    164             if (s == Status::OK) {
    165                 Mutex::Autolock _l(object->mLock);
    166                 if (object->mCirculatingBuffers.count(bufferId) == 0) {
    167                     buffer_handle_t importedBuf = buf.getNativeHandle();
    168                     sHandleImporter.importBuffer(importedBuf);
    169                     if (importedBuf == nullptr) {
    170                         ALOGE("%s: preview buffer import failed!", __FUNCTION__);
    171                         s = Status::INTERNAL_ERROR;
    172                         return;
    173                     } else {
    174                         object->mCirculatingBuffers[bufferId] = importedBuf;
    175                         object->mBufferIdMap[&(object->mCirculatingBuffers[bufferId])] = bufferId;
    176                     }
    177                 }
    178                 *buffer = &(object->mCirculatingBuffers[bufferId]);
    179                 *stride = strd;
    180             }
    181         });
    182     return getStatusT(s);
    183 }
    184 
    185 int CameraDevice::sLockBuffer(struct preview_stream_ops*, buffer_handle_t*) {
    186     return 0;
    187 }
    188 
    189 int CameraDevice::sEnqueueBuffer(struct preview_stream_ops* w, buffer_handle_t* buffer) {
    190     CameraPreviewWindow* object = static_cast<CameraPreviewWindow*>(w);
    191     if (object->mPreviewCallback == nullptr) {
    192         ALOGE("%s: camera HAL calling preview ops while there is no preview window!", __FUNCTION__);
    193         return INVALID_OPERATION;
    194     }
    195     uint64_t bufferId = object->mBufferIdMap.at(buffer);
    196     return getStatusT(object->mPreviewCallback->enqueueBuffer(bufferId));
    197 }
    198 
    199 int CameraDevice::sCancelBuffer(struct preview_stream_ops* w, buffer_handle_t* buffer) {
    200     CameraPreviewWindow* object = static_cast<CameraPreviewWindow*>(w);
    201     if (object->mPreviewCallback == nullptr) {
    202         ALOGE("%s: camera HAL calling preview ops while there is no preview window!", __FUNCTION__);
    203         return INVALID_OPERATION;
    204     }
    205     uint64_t bufferId = object->mBufferIdMap.at(buffer);
    206     return getStatusT(object->mPreviewCallback->cancelBuffer(bufferId));
    207 }
    208 
    209 int CameraDevice::sSetBufferCount(struct preview_stream_ops* w, int count) {
    210     CameraPreviewWindow* object = static_cast<CameraPreviewWindow*>(w);
    211     if (object->mPreviewCallback == nullptr) {
    212         ALOGE("%s: camera HAL calling preview ops while there is no preview window!", __FUNCTION__);
    213         return INVALID_OPERATION;
    214     }
    215 
    216     object->cleanUpCirculatingBuffers();
    217     return getStatusT(object->mPreviewCallback->setBufferCount(count));
    218 }
    219 
    220 int CameraDevice::sSetBuffersGeometry(struct preview_stream_ops* w,
    221                                          int width, int height, int format) {
    222     CameraPreviewWindow* object = static_cast<CameraPreviewWindow*>(w);
    223     if (object->mPreviewCallback == nullptr) {
    224         ALOGE("%s: camera HAL calling preview ops while there is no preview window!", __FUNCTION__);
    225         return INVALID_OPERATION;
    226     }
    227 
    228     object->cleanUpCirculatingBuffers();
    229     return getStatusT(
    230             object->mPreviewCallback->setBuffersGeometry(width, height, (PixelFormat) format));
    231 }
    232 
    233 int CameraDevice::sSetCrop(struct preview_stream_ops *w,
    234                              int left, int top, int right, int bottom) {
    235     CameraPreviewWindow* object = static_cast<CameraPreviewWindow*>(w);
    236     if (object->mPreviewCallback == nullptr) {
    237         ALOGE("%s: camera HAL calling preview ops while there is no preview window!", __FUNCTION__);
    238         return INVALID_OPERATION;
    239     }
    240 
    241     return getStatusT(object->mPreviewCallback->setCrop(left, top, right, bottom));
    242 }
    243 
    244 int CameraDevice::sSetTimestamp(struct preview_stream_ops *w, int64_t timestamp) {
    245     CameraPreviewWindow* object = static_cast<CameraPreviewWindow*>(w);
    246     if (object->mPreviewCallback == nullptr) {
    247         ALOGE("%s: camera HAL calling preview ops while there is no preview window!", __FUNCTION__);
    248         return INVALID_OPERATION;
    249     }
    250 
    251     return getStatusT(object->mPreviewCallback->setTimestamp(timestamp));
    252 }
    253 
    254 int CameraDevice::sSetUsage(struct preview_stream_ops* w, int usage) {
    255     CameraPreviewWindow* object = static_cast<CameraPreviewWindow*>(w);
    256     if (object->mPreviewCallback == nullptr) {
    257         ALOGE("%s: camera HAL calling preview ops while there is no preview window!", __FUNCTION__);
    258         return INVALID_OPERATION;
    259     }
    260 
    261     object->cleanUpCirculatingBuffers();
    262     return getStatusT(object->mPreviewCallback->setUsage((BufferUsage)usage));
    263 }
    264 
    265 int CameraDevice::sSetSwapInterval(struct preview_stream_ops *w, int interval) {
    266     CameraPreviewWindow* object = static_cast<CameraPreviewWindow*>(w);
    267     if (object->mPreviewCallback == nullptr) {
    268         ALOGE("%s: camera HAL calling preview ops while there is no preview window!", __FUNCTION__);
    269         return INVALID_OPERATION;
    270     }
    271 
    272     return getStatusT(object->mPreviewCallback->setSwapInterval(interval));
    273 }
    274 
    275 int CameraDevice::sGetMinUndequeuedBufferCount(
    276                   const struct preview_stream_ops *w,
    277                   int *count) {
    278     const CameraPreviewWindow* object =  static_cast<const CameraPreviewWindow*>(w);
    279     if (object->mPreviewCallback == nullptr) {
    280         ALOGE("%s: camera HAL calling preview ops while there is no preview window!", __FUNCTION__);
    281         return INVALID_OPERATION;
    282     }
    283     if (count == nullptr) {
    284         ALOGE("%s: count is null!", __FUNCTION__);
    285         return BAD_VALUE;
    286     }
    287 
    288     Status s;
    289     object->mPreviewCallback->getMinUndequeuedBufferCount(
    290         [&](auto status, uint32_t cnt) {
    291             s = status;
    292             if (s == Status::OK) {
    293                 *count = cnt;
    294             }
    295         });
    296     return getStatusT(s);
    297 }
    298 
    299 CameraDevice::CameraHeapMemory::CameraHeapMemory(
    300     int fd, size_t buf_size, uint_t num_buffers) :
    301         mBufSize(buf_size),
    302         mNumBufs(num_buffers) {
    303     mHidlHandle = native_handle_create(1,0);
    304     mHidlHandle->data[0] = fcntl(fd, F_DUPFD_CLOEXEC, 0);
    305     const size_t pagesize = getpagesize();
    306     size_t size = ((buf_size * num_buffers + pagesize-1) & ~(pagesize-1));
    307     mHidlHeap = hidl_memory("ashmem", mHidlHandle, size);
    308     commonInitialization();
    309 }
    310 
    311 CameraDevice::CameraHeapMemory::CameraHeapMemory(
    312     sp<IAllocator> ashmemAllocator,
    313     size_t buf_size, uint_t num_buffers) :
    314         mBufSize(buf_size),
    315         mNumBufs(num_buffers) {
    316     const size_t pagesize = getpagesize();
    317     size_t size = ((buf_size * num_buffers + pagesize-1) & ~(pagesize-1));
    318     ashmemAllocator->allocate(size,
    319         [&](bool success, const hidl_memory& mem) {
    320             if (!success) {
    321                 ALOGE("%s: allocating ashmem of %zu bytes failed!",
    322                         __FUNCTION__, buf_size * num_buffers);
    323                 return;
    324             }
    325             mHidlHandle = native_handle_clone(mem.handle());
    326             mHidlHeap = hidl_memory("ashmem", mHidlHandle, size);
    327         });
    328 
    329     commonInitialization();
    330 }
    331 
    332 void CameraDevice::CameraHeapMemory::commonInitialization() {
    333     mHidlHeapMemory = mapMemory(mHidlHeap);
    334     if (mHidlHeapMemory == nullptr) {
    335         ALOGE("%s: memory map failed!", __FUNCTION__);
    336         native_handle_close(mHidlHandle); // close FD for the shared memory
    337         native_handle_delete(mHidlHandle);
    338         mHidlHeap = hidl_memory();
    339         mHidlHandle = nullptr;
    340         return;
    341     }
    342     mHidlHeapMemData = mHidlHeapMemory->getPointer();
    343     handle.data = mHidlHeapMemData;
    344     handle.size = mBufSize * mNumBufs;
    345     handle.handle = this;
    346     handle.release = sPutMemory;
    347 }
    348 
    349 CameraDevice::CameraHeapMemory::~CameraHeapMemory() {
    350     if (mHidlHeapMemory != nullptr) {
    351         mHidlHeapMemData = nullptr;
    352         mHidlHeapMemory.clear(); // The destructor will trigger munmap
    353     }
    354 
    355     if (mHidlHandle) {
    356         native_handle_close(mHidlHandle); // close FD for the shared memory
    357         native_handle_delete(mHidlHandle);
    358     }
    359 }
    360 
    361 // shared memory methods
    362 camera_memory_t* CameraDevice::sGetMemory(int fd, size_t buf_size, uint_t num_bufs, void *user) {
    363     ALOGV("%s", __FUNCTION__);
    364     CameraDevice* object = static_cast<CameraDevice*>(user);
    365     if (object->mDeviceCallback == nullptr) {
    366         ALOGE("%s: camera HAL request memory while camera is not opened!", __FUNCTION__);
    367         return nullptr;
    368     }
    369 
    370     CameraHeapMemory* mem;
    371     if (fd < 0) {
    372         mem = new CameraHeapMemory(object->mAshmemAllocator, buf_size, num_bufs);
    373     } else {
    374         mem = new CameraHeapMemory(fd, buf_size, num_bufs);
    375     }
    376     mem->incStrong(mem);
    377     hidl_handle hidlHandle = mem->mHidlHandle;
    378     MemoryId id = object->mDeviceCallback->registerMemory(hidlHandle, buf_size, num_bufs);
    379     mem->handle.mId = id;
    380 
    381     {
    382         Mutex::Autolock _l(object->mMemoryMapLock);
    383         if (object->mMemoryMap.count(id) != 0) {
    384             ALOGE("%s: duplicate MemoryId %d returned by client!", __FUNCTION__, id);
    385         }
    386         object->mMemoryMap[id] = mem;
    387     }
    388     mem->handle.mDevice = object;
    389     return &mem->handle;
    390 }
    391 
    392 void CameraDevice::sPutMemory(camera_memory_t *data) {
    393     if (!data)
    394         return;
    395 
    396     CameraHeapMemory* mem = static_cast<CameraHeapMemory *>(data->handle);
    397     CameraDevice* device = mem->handle.mDevice;
    398     if (device == nullptr) {
    399         ALOGE("%s: camera HAL return memory for a null device!", __FUNCTION__);
    400     }
    401     if (device->mDeviceCallback == nullptr) {
    402         ALOGE("%s: camera HAL return memory while camera is not opened!", __FUNCTION__);
    403     }
    404     device->mDeviceCallback->unregisterMemory(mem->handle.mId);
    405     {
    406         Mutex::Autolock _l(device->mMemoryMapLock);
    407         device->mMemoryMap.erase(mem->handle.mId);
    408     }
    409     mem->decStrong(mem);
    410 }
    411 
    412 // Callback forwarding methods
    413 void CameraDevice::sNotifyCb(int32_t msg_type, int32_t ext1, int32_t ext2, void *user) {
    414     ALOGV("%s", __FUNCTION__);
    415     CameraDevice* object = static_cast<CameraDevice*>(user);
    416     if (object->mDeviceCallback != nullptr) {
    417         object->mDeviceCallback->notifyCallback((NotifyCallbackMsg) msg_type, ext1, ext2);
    418     }
    419 }
    420 
    421 void CameraDevice::sDataCb(int32_t msg_type, const camera_memory_t *data, unsigned int index,
    422         camera_frame_metadata_t *metadata, void *user) {
    423     ALOGV("%s", __FUNCTION__);
    424     CameraDevice* object = static_cast<CameraDevice*>(user);
    425     sp<CameraHeapMemory> mem(static_cast<CameraHeapMemory*>(data->handle));
    426     if (index >= mem->mNumBufs) {
    427         ALOGE("%s: invalid buffer index %d, max allowed is %d", __FUNCTION__,
    428              index, mem->mNumBufs);
    429         return;
    430     }
    431     if (object->mDeviceCallback != nullptr) {
    432         CameraFrameMetadata hidlMetadata;
    433         if (metadata) {
    434             hidlMetadata.faces.resize(metadata->number_of_faces);
    435             for (size_t i = 0; i < hidlMetadata.faces.size(); i++) {
    436                 hidlMetadata.faces[i].score = metadata->faces[i].score;
    437                 hidlMetadata.faces[i].id = metadata->faces[i].id;
    438                 for (int k = 0; k < 4; k++) {
    439                     hidlMetadata.faces[i].rect[k] = metadata->faces[i].rect[k];
    440                 }
    441                 for (int k = 0; k < 2; k++) {
    442                     hidlMetadata.faces[i].leftEye[k] = metadata->faces[i].left_eye[k];
    443                 }
    444                 for (int k = 0; k < 2; k++) {
    445                     hidlMetadata.faces[i].rightEye[k] = metadata->faces[i].right_eye[k];
    446                 }
    447                 for (int k = 0; k < 2; k++) {
    448                     hidlMetadata.faces[i].mouth[k] = metadata->faces[i].mouth[k];
    449                 }
    450             }
    451         }
    452         CameraHeapMemory* mem = static_cast<CameraHeapMemory *>(data->handle);
    453         object->mDeviceCallback->dataCallback(
    454                 (DataCallbackMsg) msg_type, mem->handle.mId, index, hidlMetadata);
    455     }
    456 }
    457 
    458 void CameraDevice::handleCallbackTimestamp(
    459         nsecs_t timestamp, int32_t msg_type,
    460         MemoryId memId , unsigned index, native_handle_t* handle) {
    461     uint32_t batchSize = 0;
    462     {
    463         Mutex::Autolock _l(mBatchLock);
    464         batchSize = mBatchSize;
    465     }
    466 
    467     if (batchSize == 0) { // non-batch mode
    468         mDeviceCallback->handleCallbackTimestamp(
    469                 (DataCallbackMsg) msg_type, handle, memId, index, timestamp);
    470     } else { // batch mode
    471         Mutex::Autolock _l(mBatchLock);
    472         size_t inflightSize = mInflightBatch.size();
    473         if (inflightSize == 0) {
    474             mBatchMsgType = msg_type;
    475         } else if (mBatchMsgType != msg_type) {
    476             ALOGE("%s: msg_type change (from %d to %d) is not supported!",
    477                     __FUNCTION__, mBatchMsgType, msg_type);
    478             return;
    479         }
    480         mInflightBatch.push_back({handle, memId, index, timestamp});
    481 
    482         // Send batched frames to camera framework
    483         if (mInflightBatch.size() >= batchSize) {
    484             mDeviceCallback->handleCallbackTimestampBatch(
    485                     (DataCallbackMsg) mBatchMsgType, mInflightBatch);
    486             mInflightBatch.clear();
    487         }
    488     }
    489 }
    490 
    491 void CameraDevice::sDataCbTimestamp(nsecs_t timestamp, int32_t msg_type,
    492         const camera_memory_t *data, unsigned index, void *user) {
    493     ALOGV("%s", __FUNCTION__);
    494     CameraDevice* object = static_cast<CameraDevice*>(user);
    495     // Start refcounting the heap object from here on.  When the clients
    496     // drop all references, it will be destroyed (as well as the enclosed
    497     // MemoryHeapBase.
    498     sp<CameraHeapMemory> mem(static_cast<CameraHeapMemory*>(data->handle));
    499     if (index >= mem->mNumBufs) {
    500         ALOGE("%s: invalid buffer index %d, max allowed is %d", __FUNCTION__,
    501              index, mem->mNumBufs);
    502         return;
    503     }
    504 
    505     native_handle_t* handle = nullptr;
    506     if (object->mMetadataMode) {
    507         if (mem->mBufSize == sizeof(VideoNativeHandleMetadata)) {
    508             VideoNativeHandleMetadata* md = (VideoNativeHandleMetadata*)
    509                     ((uint8_t*) mem->mHidlHeapMemData + index * mem->mBufSize);
    510             if (md->eType == kMetadataBufferTypeNativeHandleSource) {
    511                 handle = md->pHandle;
    512             }
    513         }
    514     }
    515 
    516     if (object->mDeviceCallback != nullptr) {
    517         if (handle == nullptr) {
    518             object->mDeviceCallback->dataCallbackTimestamp(
    519                     (DataCallbackMsg) msg_type, mem->handle.mId, index, timestamp);
    520         } else {
    521             object->handleCallbackTimestamp(timestamp, msg_type, mem->handle.mId, index, handle);
    522         }
    523     }
    524 }
    525 
    526 void CameraDevice::initHalPreviewWindow()
    527 {
    528     mHalPreviewWindow.cancel_buffer = sCancelBuffer;
    529     mHalPreviewWindow.lock_buffer = sLockBuffer;
    530     mHalPreviewWindow.dequeue_buffer = sDequeueBuffer;
    531     mHalPreviewWindow.enqueue_buffer = sEnqueueBuffer;
    532     mHalPreviewWindow.set_buffer_count = sSetBufferCount;
    533     mHalPreviewWindow.set_buffers_geometry = sSetBuffersGeometry;
    534     mHalPreviewWindow.set_crop = sSetCrop;
    535     mHalPreviewWindow.set_timestamp = sSetTimestamp;
    536     mHalPreviewWindow.set_usage = sSetUsage;
    537     mHalPreviewWindow.set_swap_interval = sSetSwapInterval;
    538 
    539     mHalPreviewWindow.get_min_undequeued_buffer_count =
    540             sGetMinUndequeuedBufferCount;
    541 }
    542 
    543 // Methods from ::android::hardware::camera::device::V1_0::ICameraDevice follow.
    544 Return<void> CameraDevice::getResourceCost(getResourceCost_cb _hidl_cb) {
    545     Status status = initStatus();
    546     CameraResourceCost resCost;
    547     if (status == Status::OK) {
    548         int cost = 100;
    549         std::vector<std::string> conflicting_devices;
    550         struct camera_info info;
    551 
    552         // If using post-2.4 module version, query the cost + conflicting devices from the HAL
    553         if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4) {
    554             int ret = mModule->getCameraInfo(mCameraIdInt, &info);
    555             if (ret == OK) {
    556                 cost = info.resource_cost;
    557                 for (size_t i = 0; i < info.conflicting_devices_length; i++) {
    558                     std::string cameraId(info.conflicting_devices[i]);
    559                     for (const auto& pair : mCameraDeviceNames) {
    560                         if (cameraId == pair.first) {
    561                             conflicting_devices.push_back(pair.second);
    562                         }
    563                     }
    564                 }
    565             } else {
    566                 status = Status::INTERNAL_ERROR;
    567             }
    568         }
    569 
    570         if (status == Status::OK) {
    571             resCost.resourceCost = cost;
    572             resCost.conflictingDevices.resize(conflicting_devices.size());
    573             for (size_t i = 0; i < conflicting_devices.size(); i++) {
    574                 resCost.conflictingDevices[i] = conflicting_devices[i];
    575                 ALOGV("CamDevice %s is conflicting with camDevice %s",
    576                         mCameraId.c_str(), resCost.conflictingDevices[i].c_str());
    577             }
    578         }
    579     }
    580     _hidl_cb(status, resCost);
    581     return Void();
    582 }
    583 
    584 Return<void> CameraDevice::getCameraInfo(getCameraInfo_cb _hidl_cb) {
    585     Status status = initStatus();
    586     CameraInfo cameraInfo;
    587     if (status == Status::OK) {
    588         struct camera_info info;
    589         int ret = mModule->getCameraInfo(mCameraIdInt, &info);
    590         if (ret == OK) {
    591             cameraInfo.facing = (CameraFacing) info.facing;
    592             // Device 1.0 does not support external camera facing.
    593             // The closest approximation would be front camera.
    594             if (cameraInfo.facing == CameraFacing::EXTERNAL) {
    595                 cameraInfo.facing = CameraFacing::FRONT;
    596             }
    597             cameraInfo.orientation = info.orientation;
    598         } else {
    599             ALOGE("%s: get camera info failed!", __FUNCTION__);
    600             status = Status::INTERNAL_ERROR;
    601         }
    602     }
    603     _hidl_cb(status, cameraInfo);
    604     return Void();
    605 }
    606 
    607 Return<Status> CameraDevice::setTorchMode(TorchMode mode) {
    608     if (!mModule->isSetTorchModeSupported()) {
    609         return Status::METHOD_NOT_SUPPORTED;
    610     }
    611 
    612     Status status = initStatus();
    613     if (status == Status::OK) {
    614         bool enable = (mode == TorchMode::ON) ? true : false;
    615         status = getHidlStatus(mModule->setTorchMode(mCameraId.c_str(), enable));
    616     }
    617     return status;
    618 }
    619 
    620 Return<Status> CameraDevice::dumpState(const hidl_handle& handle) {
    621     Mutex::Autolock _l(mLock);
    622     if (handle.getNativeHandle() == nullptr) {
    623         ALOGE("%s: handle must not be null", __FUNCTION__);
    624         return Status::ILLEGAL_ARGUMENT;
    625     }
    626     if (handle->numFds != 1 || handle->numInts != 0) {
    627         ALOGE("%s: handle must contain 1 FD and 0 integers! Got %d FDs and %d ints",
    628                 __FUNCTION__, handle->numFds, handle->numInts);
    629         return Status::ILLEGAL_ARGUMENT;
    630     }
    631     int fd = handle->data[0];
    632 
    633     if (mDevice != nullptr) {
    634         if (mDevice->ops->dump) { // It's fine if the HAL doesn't implement dump()
    635             return getHidlStatus(mDevice->ops->dump(mDevice, fd));
    636         }
    637     }
    638     return Status::OK;
    639 }
    640 
    641 Return<Status> CameraDevice::open(const sp<ICameraDeviceCallback>& callback) {
    642     ALOGI("Opening camera %s", mCameraId.c_str());
    643     Mutex::Autolock _l(mLock);
    644 
    645     camera_info info;
    646     status_t res = mModule->getCameraInfo(mCameraIdInt, &info);
    647     if (res != OK) {
    648         ALOGE("Could not get camera info: %s: %d", mCameraId.c_str(), res);
    649         return getHidlStatus(res);
    650     }
    651 
    652     int rc = OK;
    653     if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_3 &&
    654         info.device_version > CAMERA_DEVICE_API_VERSION_1_0) {
    655         // Open higher version camera device as HAL1.0 device.
    656         rc = mModule->openLegacy(mCameraId.c_str(),
    657                                  CAMERA_DEVICE_API_VERSION_1_0,
    658                                  (hw_device_t **)&mDevice);
    659     } else {
    660         rc = mModule->open(mCameraId.c_str(), (hw_device_t **)&mDevice);
    661     }
    662     if (rc != OK) {
    663         mDevice = nullptr;
    664         ALOGE("Could not open camera %s: %d", mCameraId.c_str(), rc);
    665         return getHidlStatus(rc);
    666     }
    667 
    668     initHalPreviewWindow();
    669     mDeviceCallback = callback;
    670 
    671     if (mDevice->ops->set_callbacks) {
    672         mDevice->ops->set_callbacks(mDevice,
    673                 sNotifyCb, sDataCb, sDataCbTimestamp, sGetMemory, this);
    674     }
    675 
    676     return getHidlStatus(rc);
    677 }
    678 
    679 Return<Status> CameraDevice::setPreviewWindow(const sp<ICameraDevicePreviewCallback>& window) {
    680     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    681     Mutex::Autolock _l(mLock);
    682     if (!mDevice) {
    683         ALOGE("%s called while camera is not opened", __FUNCTION__);
    684         return Status::OPERATION_NOT_SUPPORTED;
    685     }
    686 
    687     mHalPreviewWindow.mPreviewCallback = window;
    688     if (mDevice->ops->set_preview_window) {
    689         return getHidlStatus(mDevice->ops->set_preview_window(mDevice,
    690                 (window == nullptr) ? nullptr : &mHalPreviewWindow));
    691     }
    692     return Status::INTERNAL_ERROR; // HAL should provide set_preview_window
    693 }
    694 
    695 Return<void> CameraDevice::enableMsgType(uint32_t msgType) {
    696     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    697     Mutex::Autolock _l(mLock);
    698     if (!mDevice) {
    699         ALOGE("%s called while camera is not opened", __FUNCTION__);
    700         return Void();
    701     }
    702     if (mDevice->ops->enable_msg_type) {
    703         mDevice->ops->enable_msg_type(mDevice, msgType);
    704     }
    705     return Void();
    706 }
    707 
    708 Return<void> CameraDevice::disableMsgType(uint32_t msgType) {
    709     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    710     Mutex::Autolock _l(mLock);
    711     if (!mDevice) {
    712         ALOGE("%s called while camera is not opened", __FUNCTION__);
    713         return Void();
    714     }
    715     if (mDevice->ops->disable_msg_type) {
    716         mDevice->ops->disable_msg_type(mDevice, msgType);
    717     }
    718     return Void();
    719 }
    720 
    721 Return<bool> CameraDevice::msgTypeEnabled(uint32_t msgType) {
    722     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    723     Mutex::Autolock _l(mLock);
    724     if (!mDevice) {
    725         ALOGE("%s called while camera is not opened", __FUNCTION__);
    726         return false;
    727     }
    728     if (mDevice->ops->msg_type_enabled) {
    729         return mDevice->ops->msg_type_enabled(mDevice, msgType);
    730     }
    731     return false;
    732 }
    733 
    734 Return<Status> CameraDevice::startPreview() {
    735     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    736     Mutex::Autolock _l(mLock);
    737     if (!mDevice) {
    738         ALOGE("%s called while camera is not opened", __FUNCTION__);
    739         return Status::OPERATION_NOT_SUPPORTED;
    740     }
    741     if (mDevice->ops->start_preview) {
    742         return getHidlStatus(mDevice->ops->start_preview(mDevice));
    743     }
    744     return Status::INTERNAL_ERROR; // HAL should provide start_preview
    745 }
    746 
    747 Return<void> CameraDevice::stopPreview() {
    748     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    749     Mutex::Autolock _l(mLock);
    750     if (!mDevice) {
    751         ALOGE("%s called while camera is not opened", __FUNCTION__);
    752         return Void();
    753     }
    754     if (mDevice->ops->stop_preview) {
    755         mDevice->ops->stop_preview(mDevice);
    756     }
    757     return Void();
    758 }
    759 
    760 Return<bool> CameraDevice::previewEnabled() {
    761     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    762     Mutex::Autolock _l(mLock);
    763     if (!mDevice) {
    764         ALOGE("%s called while camera is not opened", __FUNCTION__);
    765         return false;
    766     }
    767     if (mDevice->ops->preview_enabled) {
    768         return mDevice->ops->preview_enabled(mDevice);
    769     }
    770     return false;
    771 }
    772 
    773 Return<Status> CameraDevice::storeMetaDataInBuffers(bool enable) {
    774     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    775     Mutex::Autolock _l(mLock);
    776     if (!mDevice) {
    777         ALOGE("%s called while camera is not opened", __FUNCTION__);
    778         return Status::OPERATION_NOT_SUPPORTED;
    779     }
    780     if (mDevice->ops->store_meta_data_in_buffers) {
    781         status_t s = mDevice->ops->store_meta_data_in_buffers(mDevice, enable);
    782         if (s == OK && enable) {
    783             mMetadataMode = true;
    784         }
    785         return getHidlStatus(s);
    786     }
    787     return enable ? Status::ILLEGAL_ARGUMENT : Status::OK;
    788 }
    789 
    790 Return<Status> CameraDevice::startRecording() {
    791     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    792     Mutex::Autolock _l(mLock);
    793     if (!mDevice) {
    794         ALOGE("%s called while camera is not opened", __FUNCTION__);
    795         return Status::OPERATION_NOT_SUPPORTED;
    796     }
    797     if (mDevice->ops->start_recording) {
    798         return getHidlStatus(mDevice->ops->start_recording(mDevice));
    799     }
    800     return Status::ILLEGAL_ARGUMENT;
    801 }
    802 
    803 Return<void> CameraDevice::stopRecording() {
    804     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    805     Mutex::Autolock _l(mLock);
    806     if (!mDevice) {
    807         ALOGE("%s called while camera is not opened", __FUNCTION__);
    808         return Void();
    809     }
    810     if (mDevice->ops->stop_recording) {
    811         mDevice->ops->stop_recording(mDevice);
    812     }
    813     return Void();
    814 }
    815 
    816 Return<bool> CameraDevice::recordingEnabled() {
    817     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    818     Mutex::Autolock _l(mLock);
    819     if (!mDevice) {
    820         ALOGE("%s called while camera is not opened", __FUNCTION__);
    821         return false;
    822     }
    823     if (mDevice->ops->recording_enabled) {
    824         return mDevice->ops->recording_enabled(mDevice);
    825     }
    826     return false;
    827 }
    828 
    829 void CameraDevice::releaseRecordingFrameLocked(
    830         uint32_t memId, uint32_t bufferIndex, const native_handle_t* handle) {
    831     if (!mDevice) {
    832         ALOGE("%s called while camera is not opened", __FUNCTION__);
    833         return;
    834     }
    835     if (mDevice->ops->release_recording_frame) {
    836         CameraHeapMemory* camMemory;
    837         {
    838             Mutex::Autolock _l(mMemoryMapLock);
    839             auto it = mMemoryMap.find(memId);
    840             if (it == mMemoryMap.end() || it->second == nullptr) {
    841                 ALOGE("%s unknown memoryId %d", __FUNCTION__, memId);
    842                 return;
    843             }
    844             camMemory = it->second;
    845         }
    846         if (bufferIndex >= camMemory->mNumBufs) {
    847             ALOGE("%s: bufferIndex %d exceeds number of buffers %d",
    848                     __FUNCTION__, bufferIndex, camMemory->mNumBufs);
    849             return;
    850         }
    851         void *data = ((uint8_t *) camMemory->mHidlHeapMemData) + bufferIndex * camMemory->mBufSize;
    852         if (handle) {
    853             VideoNativeHandleMetadata* md = (VideoNativeHandleMetadata*) data;
    854             if (md->eType == kMetadataBufferTypeNativeHandleSource) {
    855                 // Input handle will be closed by HIDL transport later, so clone it
    856                 // HAL implementation is responsible to close/delete the clone
    857                 native_handle_t* clone = native_handle_clone(handle);
    858                 if (!clone) {
    859                     ALOGE("%s: failed to clone buffer %p", __FUNCTION__, handle);
    860                     return;
    861                 }
    862                 md->pHandle = clone;
    863             } else {
    864                 ALOGE("%s:Malform VideoNativeHandleMetadata at memId %d, bufferId %d",
    865                         __FUNCTION__, memId, bufferIndex);
    866                 return;
    867             }
    868         }
    869         mDevice->ops->release_recording_frame(mDevice, data);
    870     }
    871 }
    872 
    873 Return<void> CameraDevice::releaseRecordingFrame(uint32_t memId, uint32_t bufferIndex) {
    874     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    875     Mutex::Autolock _l(mLock);
    876     releaseRecordingFrameLocked(memId, bufferIndex, nullptr);
    877     return Void();
    878 }
    879 
    880 Return<void> CameraDevice::releaseRecordingFrameHandle(
    881         uint32_t memId, uint32_t bufferIndex, const hidl_handle& frame) {
    882     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    883     Mutex::Autolock _l(mLock);
    884     releaseRecordingFrameLocked(
    885             memId, bufferIndex, frame.getNativeHandle());
    886     return Void();
    887 }
    888 
    889 Return<void> CameraDevice::releaseRecordingFrameHandleBatch(
    890         const hidl_vec<VideoFrameMessage>& msgs) {
    891     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    892     Mutex::Autolock _l(mLock);
    893     for (auto& msg : msgs) {
    894         releaseRecordingFrameLocked(
    895                 msg.data, msg.bufferIndex, msg.frameData.getNativeHandle());
    896     }
    897     return Void();
    898 }
    899 
    900 Return<Status> CameraDevice::autoFocus() {
    901     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    902     Mutex::Autolock _l(mLock);
    903     if (!mDevice) {
    904         ALOGE("%s called while camera is not opened", __FUNCTION__);
    905         return Status::OPERATION_NOT_SUPPORTED;
    906     }
    907     if (mDevice->ops->auto_focus) {
    908         return getHidlStatus(mDevice->ops->auto_focus(mDevice));
    909     }
    910     return Status::ILLEGAL_ARGUMENT;
    911 }
    912 
    913 Return<Status> CameraDevice::cancelAutoFocus() {
    914     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    915     Mutex::Autolock _l(mLock);
    916     if (!mDevice) {
    917         ALOGE("%s called while camera is not opened", __FUNCTION__);
    918         return Status::OPERATION_NOT_SUPPORTED;
    919     }
    920     if (mDevice->ops->cancel_auto_focus) {
    921         return getHidlStatus(mDevice->ops->cancel_auto_focus(mDevice));
    922     }
    923     return Status::ILLEGAL_ARGUMENT;
    924 }
    925 
    926 Return<Status> CameraDevice::takePicture() {
    927     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    928     Mutex::Autolock _l(mLock);
    929     if (!mDevice) {
    930         ALOGE("%s called while camera is not opened", __FUNCTION__);
    931         return Status::OPERATION_NOT_SUPPORTED;
    932     }
    933     if (mDevice->ops->take_picture) {
    934         return getHidlStatus(mDevice->ops->take_picture(mDevice));
    935     }
    936     return Status::ILLEGAL_ARGUMENT;
    937 }
    938 
    939 Return<Status> CameraDevice::cancelPicture() {
    940     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    941     Mutex::Autolock _l(mLock);
    942     if (!mDevice) {
    943         ALOGE("%s called while camera is not opened", __FUNCTION__);
    944         return Status::OPERATION_NOT_SUPPORTED;
    945     }
    946     if (mDevice->ops->cancel_picture) {
    947         return getHidlStatus(mDevice->ops->cancel_picture(mDevice));
    948     }
    949     return Status::ILLEGAL_ARGUMENT;
    950 }
    951 
    952 Return<Status> CameraDevice::setParameters(const hidl_string& params) {
    953     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    954     Mutex::Autolock _l(mLock);
    955     if (!mDevice) {
    956         ALOGE("%s called while camera is not opened", __FUNCTION__);
    957         return Status::OPERATION_NOT_SUPPORTED;
    958     }
    959     if (mDevice->ops->set_parameters) {
    960         return getHidlStatus(mDevice->ops->set_parameters(mDevice, params.c_str()));
    961     }
    962     return Status::ILLEGAL_ARGUMENT;
    963 }
    964 
    965 Return<void> CameraDevice::getParameters(getParameters_cb _hidl_cb) {
    966     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    967     Mutex::Autolock _l(mLock);
    968     hidl_string outStr;
    969     if (!mDevice) {
    970         ALOGE("%s called while camera is not opened", __FUNCTION__);
    971         _hidl_cb(outStr);
    972         return Void();
    973     }
    974     if (mDevice->ops->get_parameters) {
    975         char *temp = mDevice->ops->get_parameters(mDevice);
    976         outStr = temp;
    977         if (mDevice->ops->put_parameters) {
    978             mDevice->ops->put_parameters(mDevice, temp);
    979         } else {
    980             free(temp);
    981         }
    982     }
    983     _hidl_cb(outStr);
    984     return Void();
    985 }
    986 
    987 Return<Status> CameraDevice::sendCommand(CommandType cmd, int32_t arg1, int32_t arg2) {
    988     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
    989     Mutex::Autolock _l(mLock);
    990     if (!mDevice) {
    991         ALOGE("%s called while camera is not opened", __FUNCTION__);
    992         return Status::OPERATION_NOT_SUPPORTED;
    993     }
    994     if (mDevice->ops->send_command) {
    995         return getHidlStatus(mDevice->ops->send_command(mDevice, (int32_t) cmd, arg1, arg2));
    996     }
    997     return Status::ILLEGAL_ARGUMENT;
    998 }
    999 
   1000 Return<void> CameraDevice::close() {
   1001     Mutex::Autolock _l(mLock);
   1002     closeLocked();
   1003     return Void();
   1004 }
   1005 
   1006 void CameraDevice::closeLocked() {
   1007     ALOGI("Closing camera %s", mCameraId.c_str());
   1008     if(mDevice) {
   1009         int rc = mDevice->common.close(&mDevice->common);
   1010         if (rc != OK) {
   1011             ALOGE("Could not close camera %s: %d", mCameraId.c_str(), rc);
   1012         }
   1013         mDevice = nullptr;
   1014     }
   1015 }
   1016 
   1017 }  // namespace implementation
   1018 }  // namespace V1_0
   1019 }  // namespace device
   1020 }  // namespace camera
   1021 }  // namespace hardware
   1022 }  // namespace android
   1023