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