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@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 
getHidlStatus(const int & status)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 
getStatusT(const Status & s)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 
initStatus() const76 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 
CameraDevice(sp<CameraModule> module,const std::string & cameraId,const SortedVector<std::pair<std::string,std::string>> & cameraDeviceNames)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 
~CameraDevice()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 
setConnectionStatus(bool connected)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 
cleanUpCirculatingBuffers()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 
sDequeueBuffer(struct preview_stream_ops * w,buffer_handle_t ** buffer,int * stride)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 
sLockBuffer(struct preview_stream_ops *,buffer_handle_t *)185 int CameraDevice::sLockBuffer(struct preview_stream_ops*, buffer_handle_t*) {
186     return 0;
187 }
188 
sEnqueueBuffer(struct preview_stream_ops * w,buffer_handle_t * buffer)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 
sCancelBuffer(struct preview_stream_ops * w,buffer_handle_t * buffer)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 
sSetBufferCount(struct preview_stream_ops * w,int count)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 
sSetBuffersGeometry(struct preview_stream_ops * w,int width,int height,int format)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 
sSetCrop(struct preview_stream_ops * w,int left,int top,int right,int bottom)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 
sSetTimestamp(struct preview_stream_ops * w,int64_t timestamp)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 
sSetUsage(struct preview_stream_ops * w,int usage)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 
sSetSwapInterval(struct preview_stream_ops * w,int interval)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 
sGetMinUndequeuedBufferCount(const struct preview_stream_ops * w,int * count)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 
CameraHeapMemory(int fd,size_t buf_size,uint_t num_buffers)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 
CameraHeapMemory(sp<IAllocator> ashmemAllocator,size_t buf_size,uint_t num_buffers)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 
commonInitialization()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 
~CameraHeapMemory()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
sGetMemory(int fd,size_t buf_size,uint_t num_bufs,void * user)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     if (object->mMemoryMap.count(id) != 0) {
381         ALOGE("%s: duplicate MemoryId %d returned by client!", __FUNCTION__, id);
382     }
383     object->mMemoryMap[id] = mem;
384     mem->handle.mDevice = object;
385     return &mem->handle;
386 }
387 
sPutMemory(camera_memory_t * data)388 void CameraDevice::sPutMemory(camera_memory_t *data) {
389     if (!data)
390         return;
391 
392     CameraHeapMemory* mem = static_cast<CameraHeapMemory *>(data->handle);
393     CameraDevice* device = mem->handle.mDevice;
394     if (device == nullptr) {
395         ALOGE("%s: camera HAL return memory for a null device!", __FUNCTION__);
396     }
397     if (device->mDeviceCallback == nullptr) {
398         ALOGE("%s: camera HAL return memory while camera is not opened!", __FUNCTION__);
399     }
400     device->mDeviceCallback->unregisterMemory(mem->handle.mId);
401     device->mMemoryMap.erase(mem->handle.mId);
402     mem->decStrong(mem);
403 }
404 
405 // Callback forwarding methods
sNotifyCb(int32_t msg_type,int32_t ext1,int32_t ext2,void * user)406 void CameraDevice::sNotifyCb(int32_t msg_type, int32_t ext1, int32_t ext2, void *user) {
407     ALOGV("%s", __FUNCTION__);
408     CameraDevice* object = static_cast<CameraDevice*>(user);
409     if (object->mDeviceCallback != nullptr) {
410         object->mDeviceCallback->notifyCallback((NotifyCallbackMsg) msg_type, ext1, ext2);
411     }
412 }
413 
sDataCb(int32_t msg_type,const camera_memory_t * data,unsigned int index,camera_frame_metadata_t * metadata,void * user)414 void CameraDevice::sDataCb(int32_t msg_type, const camera_memory_t *data, unsigned int index,
415         camera_frame_metadata_t *metadata, void *user) {
416     ALOGV("%s", __FUNCTION__);
417     CameraDevice* object = static_cast<CameraDevice*>(user);
418     sp<CameraHeapMemory> mem(static_cast<CameraHeapMemory*>(data->handle));
419     if (index >= mem->mNumBufs) {
420         ALOGE("%s: invalid buffer index %d, max allowed is %d", __FUNCTION__,
421              index, mem->mNumBufs);
422         return;
423     }
424     if (object->mDeviceCallback != nullptr) {
425         CameraFrameMetadata hidlMetadata;
426         if (metadata) {
427             hidlMetadata.faces.resize(metadata->number_of_faces);
428             for (size_t i = 0; i < hidlMetadata.faces.size(); i++) {
429                 hidlMetadata.faces[i].score = metadata->faces[i].score;
430                 hidlMetadata.faces[i].id = metadata->faces[i].id;
431                 for (int k = 0; k < 4; k++) {
432                     hidlMetadata.faces[i].rect[k] = metadata->faces[i].rect[k];
433                 }
434                 for (int k = 0; k < 2; k++) {
435                     hidlMetadata.faces[i].leftEye[k] = metadata->faces[i].left_eye[k];
436                 }
437                 for (int k = 0; k < 2; k++) {
438                     hidlMetadata.faces[i].rightEye[k] = metadata->faces[i].right_eye[k];
439                 }
440                 for (int k = 0; k < 2; k++) {
441                     hidlMetadata.faces[i].mouth[k] = metadata->faces[i].mouth[k];
442                 }
443             }
444         }
445         CameraHeapMemory* mem = static_cast<CameraHeapMemory *>(data->handle);
446         object->mDeviceCallback->dataCallback(
447                 (DataCallbackMsg) msg_type, mem->handle.mId, index, hidlMetadata);
448     }
449 }
450 
handleCallbackTimestamp(nsecs_t timestamp,int32_t msg_type,MemoryId memId,unsigned index,native_handle_t * handle)451 void CameraDevice::handleCallbackTimestamp(
452         nsecs_t timestamp, int32_t msg_type,
453         MemoryId memId , unsigned index, native_handle_t* handle) {
454     uint32_t batchSize = 0;
455     {
456         Mutex::Autolock _l(mBatchLock);
457         batchSize = mBatchSize;
458     }
459 
460     if (batchSize == 0) { // non-batch mode
461         mDeviceCallback->handleCallbackTimestamp(
462                 (DataCallbackMsg) msg_type, handle, memId, index, timestamp);
463     } else { // batch mode
464         Mutex::Autolock _l(mBatchLock);
465         size_t inflightSize = mInflightBatch.size();
466         if (inflightSize == 0) {
467             mBatchMsgType = msg_type;
468         } else if (mBatchMsgType != msg_type) {
469             ALOGE("%s: msg_type change (from %d to %d) is not supported!",
470                     __FUNCTION__, mBatchMsgType, msg_type);
471             return;
472         }
473         mInflightBatch.push_back({handle, memId, index, timestamp});
474 
475         // Send batched frames to camera framework
476         if (mInflightBatch.size() >= batchSize) {
477             mDeviceCallback->handleCallbackTimestampBatch(
478                     (DataCallbackMsg) mBatchMsgType, mInflightBatch);
479             mInflightBatch.clear();
480         }
481     }
482 }
483 
sDataCbTimestamp(nsecs_t timestamp,int32_t msg_type,const camera_memory_t * data,unsigned index,void * user)484 void CameraDevice::sDataCbTimestamp(nsecs_t timestamp, int32_t msg_type,
485         const camera_memory_t *data, unsigned index, void *user) {
486     ALOGV("%s", __FUNCTION__);
487     CameraDevice* object = static_cast<CameraDevice*>(user);
488     // Start refcounting the heap object from here on.  When the clients
489     // drop all references, it will be destroyed (as well as the enclosed
490     // MemoryHeapBase.
491     sp<CameraHeapMemory> mem(static_cast<CameraHeapMemory*>(data->handle));
492     if (index >= mem->mNumBufs) {
493         ALOGE("%s: invalid buffer index %d, max allowed is %d", __FUNCTION__,
494              index, mem->mNumBufs);
495         return;
496     }
497 
498     native_handle_t* handle = nullptr;
499     if (object->mMetadataMode) {
500         if (mem->mBufSize == sizeof(VideoNativeHandleMetadata)) {
501             VideoNativeHandleMetadata* md = (VideoNativeHandleMetadata*)
502                     ((uint8_t*) mem->mHidlHeapMemData + index * mem->mBufSize);
503             if (md->eType == kMetadataBufferTypeNativeHandleSource) {
504                 handle = md->pHandle;
505             }
506         }
507     }
508 
509     if (object->mDeviceCallback != nullptr) {
510         if (handle == nullptr) {
511             object->mDeviceCallback->dataCallbackTimestamp(
512                     (DataCallbackMsg) msg_type, mem->handle.mId, index, timestamp);
513         } else {
514             object->handleCallbackTimestamp(timestamp, msg_type, mem->handle.mId, index, handle);
515         }
516     }
517 }
518 
initHalPreviewWindow()519 void CameraDevice::initHalPreviewWindow()
520 {
521     mHalPreviewWindow.cancel_buffer = sCancelBuffer;
522     mHalPreviewWindow.lock_buffer = sLockBuffer;
523     mHalPreviewWindow.dequeue_buffer = sDequeueBuffer;
524     mHalPreviewWindow.enqueue_buffer = sEnqueueBuffer;
525     mHalPreviewWindow.set_buffer_count = sSetBufferCount;
526     mHalPreviewWindow.set_buffers_geometry = sSetBuffersGeometry;
527     mHalPreviewWindow.set_crop = sSetCrop;
528     mHalPreviewWindow.set_timestamp = sSetTimestamp;
529     mHalPreviewWindow.set_usage = sSetUsage;
530     mHalPreviewWindow.set_swap_interval = sSetSwapInterval;
531 
532     mHalPreviewWindow.get_min_undequeued_buffer_count =
533             sGetMinUndequeuedBufferCount;
534 }
535 
536 // Methods from ::android::hardware::camera::device::V1_0::ICameraDevice follow.
getResourceCost(getResourceCost_cb _hidl_cb)537 Return<void> CameraDevice::getResourceCost(getResourceCost_cb _hidl_cb) {
538     Status status = initStatus();
539     CameraResourceCost resCost;
540     if (status == Status::OK) {
541         int cost = 100;
542         std::vector<std::string> conflicting_devices;
543         struct camera_info info;
544 
545         // If using post-2.4 module version, query the cost + conflicting devices from the HAL
546         if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4) {
547             int ret = mModule->getCameraInfo(mCameraIdInt, &info);
548             if (ret == OK) {
549                 cost = info.resource_cost;
550                 for (size_t i = 0; i < info.conflicting_devices_length; i++) {
551                     std::string cameraId(info.conflicting_devices[i]);
552                     for (const auto& pair : mCameraDeviceNames) {
553                         if (cameraId == pair.first) {
554                             conflicting_devices.push_back(pair.second);
555                         }
556                     }
557                 }
558             } else {
559                 status = Status::INTERNAL_ERROR;
560             }
561         }
562 
563         if (status == Status::OK) {
564             resCost.resourceCost = cost;
565             resCost.conflictingDevices.resize(conflicting_devices.size());
566             for (size_t i = 0; i < conflicting_devices.size(); i++) {
567                 resCost.conflictingDevices[i] = conflicting_devices[i];
568                 ALOGV("CamDevice %s is conflicting with camDevice %s",
569                         mCameraId.c_str(), resCost.conflictingDevices[i].c_str());
570             }
571         }
572     }
573     _hidl_cb(status, resCost);
574     return Void();
575 }
576 
getCameraInfo(getCameraInfo_cb _hidl_cb)577 Return<void> CameraDevice::getCameraInfo(getCameraInfo_cb _hidl_cb) {
578     Status status = initStatus();
579     CameraInfo cameraInfo;
580     if (status == Status::OK) {
581         struct camera_info info;
582         int ret = mModule->getCameraInfo(mCameraIdInt, &info);
583         if (ret == OK) {
584             cameraInfo.facing = (CameraFacing) info.facing;
585             // Device 1.0 does not support external camera facing.
586             // The closest approximation would be front camera.
587             if (cameraInfo.facing == CameraFacing::EXTERNAL) {
588                 cameraInfo.facing = CameraFacing::FRONT;
589             }
590             cameraInfo.orientation = info.orientation;
591         } else {
592             ALOGE("%s: get camera info failed!", __FUNCTION__);
593             status = Status::INTERNAL_ERROR;
594         }
595     }
596     _hidl_cb(status, cameraInfo);
597     return Void();
598 }
599 
setTorchMode(TorchMode mode)600 Return<Status> CameraDevice::setTorchMode(TorchMode mode) {
601     if (!mModule->isSetTorchModeSupported()) {
602         return Status::METHOD_NOT_SUPPORTED;
603     }
604 
605     Status status = initStatus();
606     if (status == Status::OK) {
607         bool enable = (mode == TorchMode::ON) ? true : false;
608         status = getHidlStatus(mModule->setTorchMode(mCameraId.c_str(), enable));
609     }
610     return status;
611 }
612 
dumpState(const hidl_handle & handle)613 Return<Status> CameraDevice::dumpState(const hidl_handle& handle) {
614     Mutex::Autolock _l(mLock);
615     if (handle.getNativeHandle() == nullptr) {
616         ALOGE("%s: handle must not be null", __FUNCTION__);
617         return Status::ILLEGAL_ARGUMENT;
618     }
619     if (handle->numFds != 1 || handle->numInts != 0) {
620         ALOGE("%s: handle must contain 1 FD and 0 integers! Got %d FDs and %d ints",
621                 __FUNCTION__, handle->numFds, handle->numInts);
622         return Status::ILLEGAL_ARGUMENT;
623     }
624     int fd = handle->data[0];
625 
626     if (mDevice != nullptr) {
627         if (mDevice->ops->dump) { // It's fine if the HAL doesn't implement dump()
628             return getHidlStatus(mDevice->ops->dump(mDevice, fd));
629         }
630     }
631     return Status::OK;
632 }
633 
open(const sp<ICameraDeviceCallback> & callback)634 Return<Status> CameraDevice::open(const sp<ICameraDeviceCallback>& callback) {
635     ALOGI("Opening camera %s", mCameraId.c_str());
636     Mutex::Autolock _l(mLock);
637 
638     camera_info info;
639     status_t res = mModule->getCameraInfo(mCameraIdInt, &info);
640     if (res != OK) {
641         ALOGE("Could not get camera info: %s: %d", mCameraId.c_str(), res);
642         return getHidlStatus(res);
643     }
644 
645     int rc = OK;
646     if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_3 &&
647         info.device_version > CAMERA_DEVICE_API_VERSION_1_0) {
648         // Open higher version camera device as HAL1.0 device.
649         rc = mModule->openLegacy(mCameraId.c_str(),
650                                  CAMERA_DEVICE_API_VERSION_1_0,
651                                  (hw_device_t **)&mDevice);
652     } else {
653         rc = mModule->open(mCameraId.c_str(), (hw_device_t **)&mDevice);
654     }
655     if (rc != OK) {
656         mDevice = nullptr;
657         ALOGE("Could not open camera %s: %d", mCameraId.c_str(), rc);
658         return getHidlStatus(rc);
659     }
660 
661     initHalPreviewWindow();
662     mDeviceCallback = callback;
663 
664     if (mDevice->ops->set_callbacks) {
665         mDevice->ops->set_callbacks(mDevice,
666                 sNotifyCb, sDataCb, sDataCbTimestamp, sGetMemory, this);
667     }
668 
669     return getHidlStatus(rc);
670 }
671 
setPreviewWindow(const sp<ICameraDevicePreviewCallback> & window)672 Return<Status> CameraDevice::setPreviewWindow(const sp<ICameraDevicePreviewCallback>& window) {
673     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
674     Mutex::Autolock _l(mLock);
675     if (!mDevice) {
676         ALOGE("%s called while camera is not opened", __FUNCTION__);
677         return Status::OPERATION_NOT_SUPPORTED;
678     }
679 
680     mHalPreviewWindow.mPreviewCallback = window;
681     if (mDevice->ops->set_preview_window) {
682         return getHidlStatus(mDevice->ops->set_preview_window(mDevice,
683                 (window == nullptr) ? nullptr : &mHalPreviewWindow));
684     }
685     return Status::INTERNAL_ERROR; // HAL should provide set_preview_window
686 }
687 
enableMsgType(uint32_t msgType)688 Return<void> CameraDevice::enableMsgType(uint32_t msgType) {
689     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
690     Mutex::Autolock _l(mLock);
691     if (!mDevice) {
692         ALOGE("%s called while camera is not opened", __FUNCTION__);
693         return Void();
694     }
695     if (mDevice->ops->enable_msg_type) {
696         mDevice->ops->enable_msg_type(mDevice, msgType);
697     }
698     return Void();
699 }
700 
disableMsgType(uint32_t msgType)701 Return<void> CameraDevice::disableMsgType(uint32_t msgType) {
702     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
703     Mutex::Autolock _l(mLock);
704     if (!mDevice) {
705         ALOGE("%s called while camera is not opened", __FUNCTION__);
706         return Void();
707     }
708     if (mDevice->ops->disable_msg_type) {
709         mDevice->ops->disable_msg_type(mDevice, msgType);
710     }
711     return Void();
712 }
713 
msgTypeEnabled(uint32_t msgType)714 Return<bool> CameraDevice::msgTypeEnabled(uint32_t msgType) {
715     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
716     Mutex::Autolock _l(mLock);
717     if (!mDevice) {
718         ALOGE("%s called while camera is not opened", __FUNCTION__);
719         return false;
720     }
721     if (mDevice->ops->msg_type_enabled) {
722         return mDevice->ops->msg_type_enabled(mDevice, msgType);
723     }
724     return false;
725 }
726 
startPreview()727 Return<Status> CameraDevice::startPreview() {
728     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
729     Mutex::Autolock _l(mLock);
730     if (!mDevice) {
731         ALOGE("%s called while camera is not opened", __FUNCTION__);
732         return Status::OPERATION_NOT_SUPPORTED;
733     }
734     if (mDevice->ops->start_preview) {
735         return getHidlStatus(mDevice->ops->start_preview(mDevice));
736     }
737     return Status::INTERNAL_ERROR; // HAL should provide start_preview
738 }
739 
stopPreview()740 Return<void> CameraDevice::stopPreview() {
741     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
742     Mutex::Autolock _l(mLock);
743     if (!mDevice) {
744         ALOGE("%s called while camera is not opened", __FUNCTION__);
745         return Void();
746     }
747     if (mDevice->ops->stop_preview) {
748         mDevice->ops->stop_preview(mDevice);
749     }
750     return Void();
751 }
752 
previewEnabled()753 Return<bool> CameraDevice::previewEnabled() {
754     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
755     Mutex::Autolock _l(mLock);
756     if (!mDevice) {
757         ALOGE("%s called while camera is not opened", __FUNCTION__);
758         return false;
759     }
760     if (mDevice->ops->preview_enabled) {
761         return mDevice->ops->preview_enabled(mDevice);
762     }
763     return false;
764 }
765 
storeMetaDataInBuffers(bool enable)766 Return<Status> CameraDevice::storeMetaDataInBuffers(bool enable) {
767     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
768     Mutex::Autolock _l(mLock);
769     if (!mDevice) {
770         ALOGE("%s called while camera is not opened", __FUNCTION__);
771         return Status::OPERATION_NOT_SUPPORTED;
772     }
773     if (mDevice->ops->store_meta_data_in_buffers) {
774         status_t s = mDevice->ops->store_meta_data_in_buffers(mDevice, enable);
775         if (s == OK && enable) {
776             mMetadataMode = true;
777         }
778         return getHidlStatus(s);
779     }
780     return enable ? Status::ILLEGAL_ARGUMENT : Status::OK;
781 }
782 
startRecording()783 Return<Status> CameraDevice::startRecording() {
784     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
785     Mutex::Autolock _l(mLock);
786     if (!mDevice) {
787         ALOGE("%s called while camera is not opened", __FUNCTION__);
788         return Status::OPERATION_NOT_SUPPORTED;
789     }
790     if (mDevice->ops->start_recording) {
791         return getHidlStatus(mDevice->ops->start_recording(mDevice));
792     }
793     return Status::ILLEGAL_ARGUMENT;
794 }
795 
stopRecording()796 Return<void> CameraDevice::stopRecording() {
797     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
798     Mutex::Autolock _l(mLock);
799     if (!mDevice) {
800         ALOGE("%s called while camera is not opened", __FUNCTION__);
801         return Void();
802     }
803     if (mDevice->ops->stop_recording) {
804         mDevice->ops->stop_recording(mDevice);
805     }
806     return Void();
807 }
808 
recordingEnabled()809 Return<bool> CameraDevice::recordingEnabled() {
810     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
811     Mutex::Autolock _l(mLock);
812     if (!mDevice) {
813         ALOGE("%s called while camera is not opened", __FUNCTION__);
814         return false;
815     }
816     if (mDevice->ops->recording_enabled) {
817         return mDevice->ops->recording_enabled(mDevice);
818     }
819     return false;
820 }
821 
releaseRecordingFrameLocked(uint32_t memId,uint32_t bufferIndex,const native_handle_t * handle)822 void CameraDevice::releaseRecordingFrameLocked(
823         uint32_t memId, uint32_t bufferIndex, const native_handle_t* handle) {
824     if (!mDevice) {
825         ALOGE("%s called while camera is not opened", __FUNCTION__);
826         return;
827     }
828     if (mDevice->ops->release_recording_frame) {
829         CameraHeapMemory* camMemory = mMemoryMap.at(memId);
830         if (bufferIndex >= camMemory->mNumBufs) {
831             ALOGE("%s: bufferIndex %d exceeds number of buffers %d",
832                     __FUNCTION__, bufferIndex, camMemory->mNumBufs);
833             return;
834         }
835         void *data = ((uint8_t *) camMemory->mHidlHeapMemData) + bufferIndex * camMemory->mBufSize;
836         if (handle) {
837             VideoNativeHandleMetadata* md = (VideoNativeHandleMetadata*) data;
838             if (md->eType == kMetadataBufferTypeNativeHandleSource) {
839                 // Input handle will be closed by HIDL transport later, so clone it
840                 // HAL implementation is responsible to close/delete the clone
841                 native_handle_t* clone = native_handle_clone(handle);
842                 if (!clone) {
843                     ALOGE("%s: failed to clone buffer %p", __FUNCTION__, handle);
844                     return;
845                 }
846                 md->pHandle = clone;
847             } else {
848                 ALOGE("%s:Malform VideoNativeHandleMetadata at memId %d, bufferId %d",
849                         __FUNCTION__, memId, bufferIndex);
850                 return;
851             }
852         }
853         mDevice->ops->release_recording_frame(mDevice, data);
854     }
855 }
856 
releaseRecordingFrame(uint32_t memId,uint32_t bufferIndex)857 Return<void> CameraDevice::releaseRecordingFrame(uint32_t memId, uint32_t bufferIndex) {
858     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
859     Mutex::Autolock _l(mLock);
860     releaseRecordingFrameLocked(memId, bufferIndex, nullptr);
861     return Void();
862 }
863 
releaseRecordingFrameHandle(uint32_t memId,uint32_t bufferIndex,const hidl_handle & frame)864 Return<void> CameraDevice::releaseRecordingFrameHandle(
865         uint32_t memId, uint32_t bufferIndex, const hidl_handle& frame) {
866     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
867     Mutex::Autolock _l(mLock);
868     releaseRecordingFrameLocked(
869             memId, bufferIndex, frame.getNativeHandle());
870     return Void();
871 }
872 
releaseRecordingFrameHandleBatch(const hidl_vec<VideoFrameMessage> & msgs)873 Return<void> CameraDevice::releaseRecordingFrameHandleBatch(
874         const hidl_vec<VideoFrameMessage>& msgs) {
875     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
876     Mutex::Autolock _l(mLock);
877     for (auto& msg : msgs) {
878         releaseRecordingFrameLocked(
879                 msg.data, msg.bufferIndex, msg.frameData.getNativeHandle());
880     }
881     return Void();
882 }
883 
autoFocus()884 Return<Status> CameraDevice::autoFocus() {
885     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
886     Mutex::Autolock _l(mLock);
887     if (!mDevice) {
888         ALOGE("%s called while camera is not opened", __FUNCTION__);
889         return Status::OPERATION_NOT_SUPPORTED;
890     }
891     if (mDevice->ops->auto_focus) {
892         return getHidlStatus(mDevice->ops->auto_focus(mDevice));
893     }
894     return Status::ILLEGAL_ARGUMENT;
895 }
896 
cancelAutoFocus()897 Return<Status> CameraDevice::cancelAutoFocus() {
898     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
899     Mutex::Autolock _l(mLock);
900     if (!mDevice) {
901         ALOGE("%s called while camera is not opened", __FUNCTION__);
902         return Status::OPERATION_NOT_SUPPORTED;
903     }
904     if (mDevice->ops->cancel_auto_focus) {
905         return getHidlStatus(mDevice->ops->cancel_auto_focus(mDevice));
906     }
907     return Status::ILLEGAL_ARGUMENT;
908 }
909 
takePicture()910 Return<Status> CameraDevice::takePicture() {
911     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
912     Mutex::Autolock _l(mLock);
913     if (!mDevice) {
914         ALOGE("%s called while camera is not opened", __FUNCTION__);
915         return Status::OPERATION_NOT_SUPPORTED;
916     }
917     if (mDevice->ops->take_picture) {
918         return getHidlStatus(mDevice->ops->take_picture(mDevice));
919     }
920     return Status::ILLEGAL_ARGUMENT;
921 }
922 
cancelPicture()923 Return<Status> CameraDevice::cancelPicture() {
924     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
925     Mutex::Autolock _l(mLock);
926     if (!mDevice) {
927         ALOGE("%s called while camera is not opened", __FUNCTION__);
928         return Status::OPERATION_NOT_SUPPORTED;
929     }
930     if (mDevice->ops->cancel_picture) {
931         return getHidlStatus(mDevice->ops->cancel_picture(mDevice));
932     }
933     return Status::ILLEGAL_ARGUMENT;
934 }
935 
setParameters(const hidl_string & params)936 Return<Status> CameraDevice::setParameters(const hidl_string& params) {
937     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
938     Mutex::Autolock _l(mLock);
939     if (!mDevice) {
940         ALOGE("%s called while camera is not opened", __FUNCTION__);
941         return Status::OPERATION_NOT_SUPPORTED;
942     }
943     if (mDevice->ops->set_parameters) {
944         return getHidlStatus(mDevice->ops->set_parameters(mDevice, params.c_str()));
945     }
946     return Status::ILLEGAL_ARGUMENT;
947 }
948 
getParameters(getParameters_cb _hidl_cb)949 Return<void> CameraDevice::getParameters(getParameters_cb _hidl_cb) {
950     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
951     Mutex::Autolock _l(mLock);
952     hidl_string outStr;
953     if (!mDevice) {
954         ALOGE("%s called while camera is not opened", __FUNCTION__);
955         _hidl_cb(outStr);
956         return Void();
957     }
958     if (mDevice->ops->get_parameters) {
959         char *temp = mDevice->ops->get_parameters(mDevice);
960         outStr = temp;
961         if (mDevice->ops->put_parameters) {
962             mDevice->ops->put_parameters(mDevice, temp);
963         } else {
964             free(temp);
965         }
966     }
967     _hidl_cb(outStr);
968     return Void();
969 }
970 
sendCommand(CommandType cmd,int32_t arg1,int32_t arg2)971 Return<Status> CameraDevice::sendCommand(CommandType cmd, int32_t arg1, int32_t arg2) {
972     ALOGV("%s(%s)", __FUNCTION__, mCameraId.c_str());
973     Mutex::Autolock _l(mLock);
974     if (!mDevice) {
975         ALOGE("%s called while camera is not opened", __FUNCTION__);
976         return Status::OPERATION_NOT_SUPPORTED;
977     }
978     if (mDevice->ops->send_command) {
979         return getHidlStatus(mDevice->ops->send_command(mDevice, (int32_t) cmd, arg1, arg2));
980     }
981     return Status::ILLEGAL_ARGUMENT;
982 }
983 
close()984 Return<void> CameraDevice::close() {
985     Mutex::Autolock _l(mLock);
986     closeLocked();
987     return Void();
988 }
989 
closeLocked()990 void CameraDevice::closeLocked() {
991     ALOGI("Closing camera %s", mCameraId.c_str());
992     if(mDevice) {
993         int rc = mDevice->common.close(&mDevice->common);
994         if (rc != OK) {
995             ALOGE("Could not close camera %s: %d", mCameraId.c_str(), rc);
996         }
997         mDevice = nullptr;
998     }
999 }
1000 
1001 }  // namespace implementation
1002 }  // namespace V1_0
1003 }  // namespace device
1004 }  // namespace camera
1005 }  // namespace hardware
1006 }  // namespace android
1007