1 /*
2 * Copyright (C) 2018 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_NDEBUG 0
18 #define LOG_TAG "ACameraManagerVendor"
19
20 #include <memory>
21 #include "ndk_vendor/impl/ACameraManager.h"
22 #include "ACameraMetadata.h"
23 #include "ndk_vendor/impl/ACameraDevice.h"
24 #include "utils.h"
25 #include <CameraMetadata.h>
26 #include <camera_metadata_hidden.h>
27
28 #include <utils/Vector.h>
29 #include <cutils/properties.h>
30 #include <stdlib.h>
31
32 #include <VendorTagDescriptor.h>
33
34 using namespace android::acam;
35
36 namespace android {
37 namespace acam {
38
39 using frameworks::cameraservice::common::V2_0::ProviderIdAndVendorTagSections;
40 using android::hardware::camera::common::V1_0::helper::VendorTagDescriptor;
41 using android::hardware::camera::common::V1_0::helper::VendorTagDescriptorCache;
42
43 // Static member definitions
44 const char* CameraManagerGlobal::kCameraIdKey = "CameraId";
45 const char* CameraManagerGlobal::kPhysicalCameraIdKey = "PhysicalCameraId";
46 const char* CameraManagerGlobal::kCallbackFpKey = "CallbackFp";
47 const char* CameraManagerGlobal::kContextKey = "CallbackContext";
48 const nsecs_t CameraManagerGlobal::kCallbackDrainTimeout = 5000000; // 5 ms
49 Mutex CameraManagerGlobal::sLock;
50 CameraManagerGlobal* CameraManagerGlobal::sInstance = nullptr;
51
52 /**
53 * The vendor tag descriptor class that takes HIDL vendor tag information as
54 * input. Not part of vendor available VendorTagDescriptor class because that class is used by
55 * default HAL implementation code as well.
56 */
57 class HidlVendorTagDescriptor : public VendorTagDescriptor {
58 public:
59 /**
60 * Create a VendorTagDescriptor object from the HIDL VendorTagSection
61 * vector.
62 *
63 * Returns OK on success, or a negative error code.
64 */
65 static status_t createDescriptorFromHidl(const hidl_vec<VendorTagSection>& vts,
66 /*out*/ sp<VendorTagDescriptor> *descriptor);
67 };
68
createDescriptorFromHidl(const hidl_vec<VendorTagSection> & vts,sp<VendorTagDescriptor> * descriptor)69 status_t HidlVendorTagDescriptor::createDescriptorFromHidl(const hidl_vec<VendorTagSection> &vts,
70 sp<VendorTagDescriptor> *descriptor) {
71 int tagCount = 0;
72
73 for (size_t s = 0; s < vts.size(); s++) {
74 tagCount += vts[s].tags.size();
75 }
76
77 if (tagCount < 0 || tagCount > INT32_MAX) {
78 ALOGE("%s: tag count %d from vendor tag sections is invalid.", __FUNCTION__, tagCount);
79 return BAD_VALUE;
80 }
81
82 Vector<uint32_t> tagArray;
83 LOG_ALWAYS_FATAL_IF(tagArray.resize(tagCount) != tagCount,
84 "%s: too many (%u) vendor tags defined.", __FUNCTION__, tagCount);
85
86 sp<HidlVendorTagDescriptor> desc = new HidlVendorTagDescriptor();
87 desc->mTagCount = tagCount;
88
89 KeyedVector<uint32_t, String8> tagToSectionMap;
90
91 int idx = 0;
92 for (size_t s = 0; s < vts.size(); s++) {
93 const VendorTagSection& section = vts[s];
94 const char *sectionName = section.sectionName.c_str();
95 if (sectionName == NULL) {
96 ALOGE("%s: no section name defined for vendor tag section %zu.", __FUNCTION__, s);
97 return BAD_VALUE;
98 }
99 String8 sectionString(sectionName);
100 desc->mSections.add(sectionString);
101
102 for (size_t j = 0; j < section.tags.size(); j++) {
103 uint32_t tag = section.tags[j].tagId;
104 if (tag < CAMERA_METADATA_VENDOR_TAG_BOUNDARY) {
105 ALOGE("%s: vendor tag %d not in vendor tag section.", __FUNCTION__, tag);
106 return BAD_VALUE;
107 }
108
109 tagArray.editItemAt(idx++) = section.tags[j].tagId;
110
111 const char *tagName = section.tags[j].tagName.c_str();
112 if (tagName == NULL) {
113 ALOGE("%s: no tag name defined for vendor tag %d.", __FUNCTION__, tag);
114 return BAD_VALUE;
115 }
116 desc->mTagToNameMap.add(tag, String8(tagName));
117 tagToSectionMap.add(tag, sectionString);
118
119 int tagType = (int) section.tags[j].tagType;
120 if (tagType < 0 || tagType >= NUM_TYPES) {
121 ALOGE("%s: tag type %d from vendor ops does not exist.", __FUNCTION__, tagType);
122 return BAD_VALUE;
123 }
124 desc->mTagToTypeMap.emplace(tag, tagType);
125 }
126 }
127
128 for (size_t i = 0; i < tagArray.size(); ++i) {
129 uint32_t tag = tagArray[i];
130 String8 sectionString = tagToSectionMap.valueFor(tag);
131
132 // Set up tag to section index map
133 ssize_t index = desc->mSections.indexOf(sectionString);
134 LOG_ALWAYS_FATAL_IF(index < 0, "index %zd must be non-negative", index);
135 desc->mTagToSectionMap.add(tag, static_cast<uint32_t>(index));
136
137 // Set up reverse mapping
138 ssize_t reverseIndex = -1;
139 if ((reverseIndex = desc->mReverseMapping.indexOfKey(sectionString)) < 0) {
140 KeyedVector<String8, uint32_t>* nameMapper = new KeyedVector<String8, uint32_t>();
141 reverseIndex = desc->mReverseMapping.add(sectionString, nameMapper);
142 }
143 desc->mReverseMapping[reverseIndex]->add(desc->mTagToNameMap.valueFor(tag), tag);
144 }
145
146 *descriptor = std::move(desc);
147 return OK;
148 }
149
150 CameraManagerGlobal&
getInstance()151 CameraManagerGlobal::getInstance() {
152 Mutex::Autolock _l(sLock);
153 CameraManagerGlobal* instance = sInstance;
154 if (instance == nullptr) {
155 instance = new CameraManagerGlobal();
156 sInstance = instance;
157 }
158 return *instance;
159 }
160
~CameraManagerGlobal()161 CameraManagerGlobal::~CameraManagerGlobal() {
162 // clear sInstance so next getInstance call knows to create a new one
163 Mutex::Autolock _sl(sLock);
164 sInstance = nullptr;
165 Mutex::Autolock _l(mLock);
166 if (mCameraService != nullptr) {
167 mCameraService->unlinkToDeath(mDeathNotifier);
168 mCameraService->removeListener(mCameraServiceListener);
169 }
170 mDeathNotifier.clear();
171 if (mCbLooper != nullptr) {
172 mCbLooper->unregisterHandler(mHandler->id());
173 mCbLooper->stop();
174 }
175 mCbLooper.clear();
176 mHandler.clear();
177 mCameraServiceListener.clear();
178 mCameraService.clear();
179 }
180
isCameraServiceDisabled()181 static bool isCameraServiceDisabled() {
182 char value[PROPERTY_VALUE_MAX];
183 property_get("config.disable_cameraservice", value, "0");
184 return (strncmp(value, "0", 2) != 0 && strncasecmp(value, "false", 6) != 0);
185 }
186
setupVendorTags()187 bool CameraManagerGlobal::setupVendorTags() {
188 sp<VendorTagDescriptorCache> tagCache = new VendorTagDescriptorCache();
189 Status status = Status::NO_ERROR;
190 std::vector<ProviderIdAndVendorTagSections> providerIdsAndVts;
191 auto remoteRet = mCameraService->getCameraVendorTagSections([&status, &providerIdsAndVts]
192 (Status s,
193 auto &IdsAndVts) {
194 status = s;
195 providerIdsAndVts = IdsAndVts; });
196
197 if (!remoteRet.isOk() || status != Status::NO_ERROR) {
198 ALOGE("Failed to retrieve VendorTagSections %s", remoteRet.description().c_str());
199 return false;
200 }
201 // Convert each providers VendorTagSections into a VendorTagDescriptor and
202 // add it to the cache
203 for (auto &providerIdAndVts : providerIdsAndVts) {
204 sp<VendorTagDescriptor> vendorTagDescriptor;
205 if (HidlVendorTagDescriptor::createDescriptorFromHidl(providerIdAndVts.vendorTagSections,
206 &vendorTagDescriptor) != OK) {
207 ALOGE("Failed to convert from Hidl: VendorTagDescriptor");
208 return false;
209 }
210 tagCache->addVendorDescriptor(providerIdAndVts.providerId, vendorTagDescriptor);
211 }
212 VendorTagDescriptorCache::setAsGlobalVendorTagCache(tagCache);
213 return true;
214 }
215
getCameraService()216 sp<ICameraService> CameraManagerGlobal::getCameraService() {
217 Mutex::Autolock _l(mLock);
218 if (mCameraService.get() == nullptr) {
219 if (isCameraServiceDisabled()) {
220 return mCameraService;
221 }
222
223 sp<ICameraService> cameraServiceBinder;
224 do {
225 cameraServiceBinder = ICameraService::getService();
226 if (cameraServiceBinder != nullptr) {
227 break;
228 }
229 ALOGW("CameraService not published, waiting...");
230 usleep(kCameraServicePollDelay);
231 } while(true);
232 if (mDeathNotifier == nullptr) {
233 mDeathNotifier = new DeathNotifier(this);
234 }
235 cameraServiceBinder->linkToDeath(mDeathNotifier, 0);
236 mCameraService = cameraServiceBinder;
237
238 // Setup looper thread to perfrom availiability callbacks
239 if (mCbLooper == nullptr) {
240 mCbLooper = new ALooper;
241 mCbLooper->setName("C2N-mgr-looper");
242 status_t err = mCbLooper->start(
243 /*runOnCallingThread*/false,
244 /*canCallJava*/ true,
245 PRIORITY_DEFAULT);
246 if (err != OK) {
247 ALOGE("%s: Unable to start camera service listener looper: %s (%d)",
248 __FUNCTION__, strerror(-err), err);
249 mCbLooper.clear();
250 return nullptr;
251 }
252 if (mHandler == nullptr) {
253 mHandler = new CallbackHandler(this);
254 }
255 mCbLooper->registerHandler(mHandler);
256 }
257
258 // register ICameraServiceListener
259 if (mCameraServiceListener == nullptr) {
260 mCameraServiceListener = new CameraServiceListener(this);
261 }
262 hidl_vec<frameworks::cameraservice::service::V2_1::CameraStatusAndId> cameraStatuses{};
263 Status status = Status::NO_ERROR;
264 auto remoteRet = mCameraService->addListener_2_1(mCameraServiceListener,
265 [&status, &cameraStatuses](Status s,
266 auto &retStatuses) {
267 status = s;
268 cameraStatuses = retStatuses;
269 });
270 if (!remoteRet.isOk() || status != Status::NO_ERROR) {
271 ALOGE("Failed to add listener to camera service %s", remoteRet.description().c_str());
272 }
273
274 // Setup vendor tags
275 if (!setupVendorTags()) {
276 ALOGE("Unable to set up vendor tags");
277 return nullptr;
278 }
279
280 for (auto& c : cameraStatuses) {
281 onStatusChangedLocked(c.v2_0);
282
283 for (auto& unavailablePhysicalId : c.unavailPhysicalCameraIds) {
284 PhysicalCameraStatusAndId statusAndId;
285 statusAndId.deviceStatus = CameraDeviceStatus::STATUS_NOT_PRESENT;
286 statusAndId.cameraId = c.v2_0.cameraId;
287 statusAndId.physicalCameraId = unavailablePhysicalId;
288 onStatusChangedLocked(statusAndId);
289 }
290 }
291 }
292 return mCameraService;
293 }
294
serviceDied(uint64_t cookie,const wp<IBase> & who)295 void CameraManagerGlobal::DeathNotifier::serviceDied(uint64_t cookie, const wp<IBase> &who) {
296 (void) cookie;
297 (void) who;
298 ALOGE("Camera service binderDied!");
299 sp<CameraManagerGlobal> cm = mCameraManager.promote();
300 if (cm != nullptr) {
301 AutoMutex lock(cm->mLock);
302 for (auto& pair : cm->mDeviceStatusMap) {
303 CameraStatusAndId cameraStatusAndId;
304 cameraStatusAndId.cameraId = pair.first;
305 cameraStatusAndId.deviceStatus = pair.second.getStatus();
306 cm->onStatusChangedLocked(cameraStatusAndId);
307 }
308 cm->mCameraService.clear();
309 // TODO: consider adding re-connect call here?
310 }
311 }
312
registerAvailabilityCallback(const ACameraManager_AvailabilityCallbacks * callback)313 void CameraManagerGlobal::registerAvailabilityCallback(
314 const ACameraManager_AvailabilityCallbacks *callback) {
315 return registerAvailCallback<ACameraManager_AvailabilityCallbacks>(callback);
316 }
317
unregisterAvailabilityCallback(const ACameraManager_AvailabilityCallbacks * callback)318 void CameraManagerGlobal::unregisterAvailabilityCallback(
319 const ACameraManager_AvailabilityCallbacks *callback) {
320 Mutex::Autolock _l(mLock);
321 drainPendingCallbacksLocked();
322 Callback cb(callback);
323 mCallbacks.erase(cb);
324 }
325
registerExtendedAvailabilityCallback(const ACameraManager_ExtendedAvailabilityCallbacks * callback)326 void CameraManagerGlobal::registerExtendedAvailabilityCallback(
327 const ACameraManager_ExtendedAvailabilityCallbacks *callback) {
328 return registerAvailCallback<ACameraManager_ExtendedAvailabilityCallbacks>(callback);
329 }
330
unregisterExtendedAvailabilityCallback(const ACameraManager_ExtendedAvailabilityCallbacks * callback)331 void CameraManagerGlobal::unregisterExtendedAvailabilityCallback(
332 const ACameraManager_ExtendedAvailabilityCallbacks *callback) {
333 Mutex::Autolock _l(mLock);
334 drainPendingCallbacksLocked();
335 Callback cb(callback);
336 mCallbacks.erase(cb);
337 }
338
onCallbackCalled()339 void CameraManagerGlobal::onCallbackCalled() {
340 Mutex::Autolock _l(mLock);
341 if (mPendingCallbackCnt > 0) {
342 mPendingCallbackCnt--;
343 }
344 mCallbacksCond.signal();
345 }
346
drainPendingCallbacksLocked()347 void CameraManagerGlobal::drainPendingCallbacksLocked() {
348 while (mPendingCallbackCnt > 0) {
349 auto res = mCallbacksCond.waitRelative(mLock, kCallbackDrainTimeout);
350 if (res != NO_ERROR) {
351 ALOGE("%s: Error waiting to drain callbacks: %s(%d)",
352 __FUNCTION__, strerror(-res), res);
353 break;
354 }
355 }
356 }
357
358 template <class T>
registerAvailCallback(const T * callback)359 void CameraManagerGlobal::registerAvailCallback(const T *callback) {
360 Mutex::Autolock _l(mLock);
361 Callback cb(callback);
362 auto pair = mCallbacks.insert(cb);
363 // Send initial callbacks if callback is newly registered
364 if (pair.second) {
365 for (auto& pair : mDeviceStatusMap) {
366 const hidl_string& cameraId = pair.first;
367 CameraDeviceStatus status = pair.second.getStatus();
368
369 // Camera available/unavailable callback
370 sp<AMessage> msg = new AMessage(kWhatSendSingleCallback, mHandler);
371 ACameraManager_AvailabilityCallback cbFunc = isStatusAvailable(status) ?
372 cb.mAvailable : cb.mUnavailable;
373 msg->setPointer(kCallbackFpKey, (void *) cbFunc);
374 msg->setPointer(kContextKey, cb.mContext);
375 msg->setString(kCameraIdKey, AString(cameraId.c_str()));
376 mPendingCallbackCnt++;
377 msg->post();
378
379 // Physical camera unavailable callback
380 std::set<hidl_string> unavailPhysicalIds = pair.second.getUnavailablePhysicalIds();
381 for (const auto& physicalCameraId : unavailPhysicalIds) {
382 sp<AMessage> msg = new AMessage(kWhatSendSinglePhysicalCameraCallback, mHandler);
383 ACameraManager_PhysicalCameraAvailabilityCallback cbFunc =
384 cb.mPhysicalCamUnavailable;
385 msg->setPointer(kCallbackFpKey, (void *) cbFunc);
386 msg->setPointer(kContextKey, cb.mContext);
387 msg->setString(kCameraIdKey, AString(cameraId.c_str()));
388 msg->setString(kPhysicalCameraIdKey, AString(physicalCameraId.c_str()));
389 mPendingCallbackCnt++;
390 msg->post();
391 }
392 }
393 }
394 }
395
getCameraIdList(std::vector<hidl_string> * cameraIds)396 void CameraManagerGlobal::getCameraIdList(std::vector<hidl_string>* cameraIds) {
397 // Ensure that we have initialized/refreshed the list of available devices
398 auto cs = getCameraService();
399 Mutex::Autolock _l(mLock);
400
401 for(auto& deviceStatus : mDeviceStatusMap) {
402 CameraDeviceStatus status = deviceStatus.second.getStatus();
403 if (status == CameraDeviceStatus::STATUS_NOT_PRESENT ||
404 status == CameraDeviceStatus::STATUS_ENUMERATING) {
405 continue;
406 }
407 cameraIds->push_back(deviceStatus.first);
408 }
409 }
410
validStatus(CameraDeviceStatus status)411 bool CameraManagerGlobal::validStatus(CameraDeviceStatus status) {
412 switch (status) {
413 case CameraDeviceStatus::STATUS_NOT_PRESENT:
414 case CameraDeviceStatus::STATUS_PRESENT:
415 case CameraDeviceStatus::STATUS_ENUMERATING:
416 case CameraDeviceStatus::STATUS_NOT_AVAILABLE:
417 return true;
418 default:
419 return false;
420 }
421 }
422
isStatusAvailable(CameraDeviceStatus status)423 bool CameraManagerGlobal::isStatusAvailable(CameraDeviceStatus status) {
424 switch (status) {
425 case CameraDeviceStatus::STATUS_PRESENT:
426 return true;
427 default:
428 return false;
429 }
430 }
431
onMessageReceived(const sp<AMessage> & msg)432 void CameraManagerGlobal::CallbackHandler::onMessageReceived(
433 const sp<AMessage> &msg) {
434 onMessageReceivedInternal(msg);
435 if (msg->what() == kWhatSendSingleCallback ||
436 msg->what() == kWhatSendSinglePhysicalCameraCallback) {
437 notifyParent();
438 }
439 }
440
onMessageReceivedInternal(const sp<AMessage> & msg)441 void CameraManagerGlobal::CallbackHandler::onMessageReceivedInternal(
442 const sp<AMessage> &msg) {
443 switch (msg->what()) {
444 case kWhatSendSingleCallback:
445 {
446 ACameraManager_AvailabilityCallback cb;
447 void* context;
448 AString cameraId;
449 bool found = msg->findPointer(kCallbackFpKey, (void**) &cb);
450 if (!found) {
451 ALOGE("%s: Cannot find camera callback fp!", __FUNCTION__);
452 return;
453 }
454 found = msg->findPointer(kContextKey, &context);
455 if (!found) {
456 ALOGE("%s: Cannot find callback context!", __FUNCTION__);
457 return;
458 }
459 found = msg->findString(kCameraIdKey, &cameraId);
460 if (!found) {
461 ALOGE("%s: Cannot find camera ID!", __FUNCTION__);
462 return;
463 }
464 (*cb)(context, cameraId.c_str());
465 break;
466 }
467 case kWhatSendSinglePhysicalCameraCallback:
468 {
469 ACameraManager_PhysicalCameraAvailabilityCallback cb;
470 void* context;
471 AString cameraId;
472 AString physicalCameraId;
473 bool found = msg->findPointer(kCallbackFpKey, (void**) &cb);
474 if (!found) {
475 ALOGE("%s: Cannot find camera callback fp!", __FUNCTION__);
476 return;
477 }
478 found = msg->findPointer(kContextKey, &context);
479 if (!found) {
480 ALOGE("%s: Cannot find callback context!", __FUNCTION__);
481 return;
482 }
483 found = msg->findString(kCameraIdKey, &cameraId);
484 if (!found) {
485 ALOGE("%s: Cannot find camera ID!", __FUNCTION__);
486 return;
487 }
488 found = msg->findString(kPhysicalCameraIdKey, &physicalCameraId);
489 if (!found) {
490 ALOGE("%s: Cannot find physical camera ID!", __FUNCTION__);
491 return;
492 }
493 (*cb)(context, cameraId.c_str(), physicalCameraId.c_str());
494 break;
495 }
496 default:
497 ALOGE("%s: unknown message type %d", __FUNCTION__, msg->what());
498 break;
499 }
500 }
501
notifyParent()502 void CameraManagerGlobal::CallbackHandler::notifyParent() {
503 sp<CameraManagerGlobal> parent = mParent.promote();
504 if (parent != nullptr) {
505 parent->onCallbackCalled();
506 }
507 }
508
onStatusChanged(const CameraStatusAndId & statusAndId)509 hardware::Return<void> CameraManagerGlobal::CameraServiceListener::onStatusChanged(
510 const CameraStatusAndId &statusAndId) {
511 sp<CameraManagerGlobal> cm = mCameraManager.promote();
512 if (cm != nullptr) {
513 cm->onStatusChanged(statusAndId);
514 } else {
515 ALOGE("Cannot deliver status change. Global camera manager died");
516 }
517 return Void();
518 }
519
onStatusChanged(const CameraStatusAndId & statusAndId)520 void CameraManagerGlobal::onStatusChanged(
521 const CameraStatusAndId &statusAndId) {
522 Mutex::Autolock _l(mLock);
523 onStatusChangedLocked(statusAndId);
524 }
525
onStatusChangedLocked(const CameraStatusAndId & statusAndId)526 void CameraManagerGlobal::onStatusChangedLocked(
527 const CameraStatusAndId &statusAndId) {
528 hidl_string cameraId = statusAndId.cameraId;
529 CameraDeviceStatus status = statusAndId.deviceStatus;
530 if (!validStatus(status)) {
531 ALOGE("%s: Invalid status %d", __FUNCTION__, status);
532 return;
533 }
534
535 bool firstStatus = (mDeviceStatusMap.count(cameraId) == 0);
536 CameraDeviceStatus oldStatus = firstStatus ?
537 status : // first status
538 mDeviceStatusMap[cameraId].getStatus();
539
540 if (!firstStatus &&
541 isStatusAvailable(status) == isStatusAvailable(oldStatus)) {
542 // No status update. No need to send callback
543 return;
544 }
545
546 // Iterate through all registered callbacks
547 mDeviceStatusMap[cameraId].updateStatus(status);
548 for (auto cb : mCallbacks) {
549 sp<AMessage> msg = new AMessage(kWhatSendSingleCallback, mHandler);
550 ACameraManager_AvailabilityCallback cbFp = isStatusAvailable(status) ?
551 cb.mAvailable : cb.mUnavailable;
552 msg->setPointer(kCallbackFpKey, (void *) cbFp);
553 msg->setPointer(kContextKey, cb.mContext);
554 msg->setString(kCameraIdKey, AString(cameraId.c_str()));
555 mPendingCallbackCnt++;
556 msg->post();
557 }
558 if (status == CameraDeviceStatus::STATUS_NOT_PRESENT) {
559 mDeviceStatusMap.erase(cameraId);
560 }
561 }
562
onPhysicalCameraStatusChanged(const PhysicalCameraStatusAndId & statusAndId)563 hardware::Return<void> CameraManagerGlobal::CameraServiceListener::onPhysicalCameraStatusChanged(
564 const PhysicalCameraStatusAndId &statusAndId) {
565 sp<CameraManagerGlobal> cm = mCameraManager.promote();
566 if (cm != nullptr) {
567 cm->onStatusChanged(statusAndId);
568 } else {
569 ALOGE("Cannot deliver status change. Global camera manager died");
570 }
571 return Void();
572 }
573
onStatusChanged(const PhysicalCameraStatusAndId & statusAndId)574 void CameraManagerGlobal::onStatusChanged(
575 const PhysicalCameraStatusAndId &statusAndId) {
576 Mutex::Autolock _l(mLock);
577 onStatusChangedLocked(statusAndId);
578 }
579
onStatusChangedLocked(const PhysicalCameraStatusAndId & statusAndId)580 void CameraManagerGlobal::onStatusChangedLocked(
581 const PhysicalCameraStatusAndId &statusAndId) {
582 hidl_string cameraId = statusAndId.cameraId;
583 hidl_string physicalCameraId = statusAndId.physicalCameraId;
584 CameraDeviceStatus status = statusAndId.deviceStatus;
585 if (!validStatus(status)) {
586 ALOGE("%s: Invalid status %d", __FUNCTION__, status);
587 return;
588 }
589
590 auto logicalStatus = mDeviceStatusMap.find(cameraId);
591 if (logicalStatus == mDeviceStatusMap.end()) {
592 ALOGE("%s: Physical camera id %s status change on a non-present id %s",
593 __FUNCTION__, physicalCameraId.c_str(), cameraId.c_str());
594 return;
595 }
596 CameraDeviceStatus logicalCamStatus = mDeviceStatusMap[cameraId].getStatus();
597 if (logicalCamStatus != CameraDeviceStatus::STATUS_PRESENT &&
598 logicalCamStatus != CameraDeviceStatus::STATUS_NOT_AVAILABLE) {
599 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
600 __FUNCTION__, physicalCameraId.c_str(), status, logicalCamStatus);
601 return;
602 }
603
604 bool updated = false;
605 if (status == CameraDeviceStatus::STATUS_PRESENT) {
606 updated = mDeviceStatusMap[cameraId].removeUnavailablePhysicalId(physicalCameraId);
607 } else {
608 updated = mDeviceStatusMap[cameraId].addUnavailablePhysicalId(physicalCameraId);
609 }
610
611 // Iterate through all registered callbacks
612 if (updated) {
613 for (auto cb : mCallbacks) {
614 sp<AMessage> msg = new AMessage(kWhatSendSinglePhysicalCameraCallback, mHandler);
615 ACameraManager_PhysicalCameraAvailabilityCallback cbFp = isStatusAvailable(status) ?
616 cb.mPhysicalCamAvailable : cb.mPhysicalCamUnavailable;
617 msg->setPointer(kCallbackFpKey, (void *) cbFp);
618 msg->setPointer(kContextKey, cb.mContext);
619 msg->setString(kCameraIdKey, AString(cameraId.c_str()));
620 msg->setString(kPhysicalCameraIdKey, AString(physicalCameraId.c_str()));
621 mPendingCallbackCnt++;
622 msg->post();
623 }
624 }
625 }
626
getStatus()627 CameraDeviceStatus CameraManagerGlobal::CameraStatus::getStatus() {
628 std::lock_guard<std::mutex> lock(mLock);
629 return status;
630 }
631
updateStatus(CameraDeviceStatus newStatus)632 void CameraManagerGlobal::CameraStatus::updateStatus(CameraDeviceStatus newStatus) {
633 std::lock_guard<std::mutex> lock(mLock);
634 status = newStatus;
635 }
636
addUnavailablePhysicalId(const hidl_string & physicalCameraId)637 bool CameraManagerGlobal::CameraStatus::addUnavailablePhysicalId(
638 const hidl_string& physicalCameraId) {
639 std::lock_guard<std::mutex> lock(mLock);
640 auto result = unavailablePhysicalIds.insert(physicalCameraId);
641 return result.second;
642 }
643
removeUnavailablePhysicalId(const hidl_string & physicalCameraId)644 bool CameraManagerGlobal::CameraStatus::removeUnavailablePhysicalId(
645 const hidl_string& physicalCameraId) {
646 std::lock_guard<std::mutex> lock(mLock);
647 auto count = unavailablePhysicalIds.erase(physicalCameraId);
648 return count > 0;
649 }
650
getUnavailablePhysicalIds()651 std::set<hidl_string> CameraManagerGlobal::CameraStatus::getUnavailablePhysicalIds() {
652 std::lock_guard<std::mutex> lock(mLock);
653 return unavailablePhysicalIds;
654 }
655
656 } // namespace acam
657 } // namespace android
658
659 /**
660 * ACameraManger Implementation
661 */
662 camera_status_t
getCameraIdList(ACameraIdList ** cameraIdList)663 ACameraManager::getCameraIdList(ACameraIdList** cameraIdList) {
664 Mutex::Autolock _l(mLock);
665
666 std::vector<hidl_string> idList;
667 CameraManagerGlobal::getInstance().getCameraIdList(&idList);
668
669 int numCameras = idList.size();
670 ACameraIdList *out = new ACameraIdList;
671 if (!out) {
672 ALOGE("Allocate memory for ACameraIdList failed!");
673 return ACAMERA_ERROR_NOT_ENOUGH_MEMORY;
674 }
675 out->numCameras = numCameras;
676 out->cameraIds = new const char*[numCameras];
677 if (!out->cameraIds) {
678 ALOGE("Allocate memory for ACameraIdList failed!");
679 deleteCameraIdList(out);
680 return ACAMERA_ERROR_NOT_ENOUGH_MEMORY;
681 }
682 for (int i = 0; i < numCameras; i++) {
683 const char* src = idList[i].c_str();
684 size_t dstSize = strlen(src) + 1;
685 char* dst = new char[dstSize];
686 if (!dst) {
687 ALOGE("Allocate memory for ACameraIdList failed!");
688 deleteCameraIdList(out);
689 return ACAMERA_ERROR_NOT_ENOUGH_MEMORY;
690 }
691 strlcpy(dst, src, dstSize);
692 out->cameraIds[i] = dst;
693 }
694 *cameraIdList = out;
695 return ACAMERA_OK;
696 }
697
698 void
deleteCameraIdList(ACameraIdList * cameraIdList)699 ACameraManager::deleteCameraIdList(ACameraIdList* cameraIdList) {
700 if (cameraIdList != nullptr) {
701 if (cameraIdList->cameraIds != nullptr) {
702 for (int i = 0; i < cameraIdList->numCameras; i ++) {
703 if (cameraIdList->cameraIds[i] != nullptr) {
704 delete[] cameraIdList->cameraIds[i];
705 }
706 }
707 delete[] cameraIdList->cameraIds;
708 }
709 delete cameraIdList;
710 }
711 }
712
getCameraCharacteristics(const char * cameraIdStr,sp<ACameraMetadata> * characteristics)713 camera_status_t ACameraManager::getCameraCharacteristics(
714 const char *cameraIdStr, sp<ACameraMetadata> *characteristics) {
715 Mutex::Autolock _l(mLock);
716
717 sp<ICameraService> cs = CameraManagerGlobal::getInstance().getCameraService();
718 if (cs == nullptr) {
719 ALOGE("%s: Cannot reach camera service!", __FUNCTION__);
720 return ACAMERA_ERROR_CAMERA_DISCONNECTED;
721 }
722 CameraMetadata rawMetadata;
723 Status status = Status::NO_ERROR;
724 auto serviceRet =
725 cs->getCameraCharacteristics(cameraIdStr,
726 [&status, &rawMetadata] (auto s ,
727 const hidl_vec<uint8_t> &metadata) {
728 status = s;
729 if (status == Status::NO_ERROR) {
730 utils::convertFromHidlCloned(metadata, &rawMetadata);
731 }
732 });
733 if (!serviceRet.isOk() || status != Status::NO_ERROR) {
734 ALOGE("Get camera characteristics from camera service failed");
735 return ACAMERA_ERROR_UNKNOWN; // should not reach here
736 }
737
738 *characteristics = new ACameraMetadata(
739 rawMetadata.release(), ACameraMetadata::ACM_CHARACTERISTICS);
740 return ACAMERA_OK;
741 }
742
743 camera_status_t
openCamera(const char * cameraId,ACameraDevice_StateCallbacks * callback,ACameraDevice ** outDevice)744 ACameraManager::openCamera(
745 const char* cameraId,
746 ACameraDevice_StateCallbacks* callback,
747 /*out*/ACameraDevice** outDevice) {
748 sp<ACameraMetadata> rawChars;
749 camera_status_t ret = getCameraCharacteristics(cameraId, &rawChars);
750 Mutex::Autolock _l(mLock);
751 if (ret != ACAMERA_OK) {
752 ALOGE("%s: cannot get camera characteristics for camera %s. err %d",
753 __FUNCTION__, cameraId, ret);
754 return ACAMERA_ERROR_INVALID_PARAMETER;
755 }
756
757 ACameraDevice* device = new ACameraDevice(cameraId, callback, std::move(rawChars));
758
759 sp<ICameraService> cs = CameraManagerGlobal::getInstance().getCameraService();
760 if (cs == nullptr) {
761 ALOGE("%s: Cannot reach camera service!", __FUNCTION__);
762 delete device;
763 return ACAMERA_ERROR_CAMERA_DISCONNECTED;
764 }
765
766 sp<ICameraDeviceCallback> callbacks = device->getServiceCallback();
767 sp<ICameraDeviceUser> deviceRemote;
768
769 // No way to get package name from native.
770 // Send a zero length package name and let camera service figure it out from UID
771 Status status = Status::NO_ERROR;
772 auto serviceRet = cs->connectDevice(
773 callbacks, cameraId, [&status, &deviceRemote](auto s, auto &device) {
774 status = s;
775 deviceRemote = device;
776 });
777
778 if (!serviceRet.isOk() || status != Status::NO_ERROR) {
779 ALOGE("%s: connect camera device failed", __FUNCTION__);
780 delete device;
781 return utils::convertFromHidl(status);
782 }
783 if (deviceRemote == nullptr) {
784 ALOGE("%s: connect camera device failed! remote device is null", __FUNCTION__);
785 delete device;
786 return ACAMERA_ERROR_CAMERA_DISCONNECTED;
787 }
788 device->setRemoteDevice(deviceRemote);
789 device->setDeviceMetadataQueues();
790 *outDevice = device;
791 return ACAMERA_OK;
792 }
793
794 camera_status_t
getTagFromName(const char * cameraId,const char * name,uint32_t * tag)795 ACameraManager::getTagFromName(const char *cameraId, const char *name, uint32_t *tag) {
796 sp<ACameraMetadata> rawChars;
797 camera_status_t ret = getCameraCharacteristics(cameraId, &rawChars);
798 if (ret != ACAMERA_OK) {
799 ALOGE("%s, Cannot retrieve camera characteristics for camera id %s", __FUNCTION__,
800 cameraId);
801 return ACAMERA_ERROR_METADATA_NOT_FOUND;
802 }
803 const CameraMetadata& metadata = rawChars->getInternalData();
804 const camera_metadata_t *rawMetadata = metadata.getAndLock();
805 metadata_vendor_id_t vendorTagId = get_camera_metadata_vendor_id(rawMetadata);
806 metadata.unlock(rawMetadata);
807 sp<VendorTagDescriptorCache> vtCache = VendorTagDescriptorCache::getGlobalVendorTagCache();
808 sp<VendorTagDescriptor> vTags = nullptr;
809 vtCache->getVendorTagDescriptor(vendorTagId, &vTags);
810 status_t status= metadata.getTagFromName(name, vTags.get(), tag);
811 return status == OK ? ACAMERA_OK : ACAMERA_ERROR_METADATA_NOT_FOUND;
812 }
813
~ACameraManager()814 ACameraManager::~ACameraManager() {
815
816 }
817