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