1 /*
2  * Copyright (C) 2016 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 "CameraProviderManager"
18 #define ATRACE_TAG ATRACE_TAG_CAMERA
19 //#define LOG_NDEBUG 0
20 
21 #include "CameraProviderManager.h"
22 
23 #include <android/hardware/camera/device/3.5/ICameraDevice.h>
24 
25 #include <algorithm>
26 #include <chrono>
27 #include "common/DepthPhotoProcessor.h"
28 #include <dlfcn.h>
29 #include <future>
30 #include <inttypes.h>
31 #include <hardware/camera_common.h>
32 #include <android/hidl/manager/1.2/IServiceManager.h>
33 #include <hidl/ServiceManagement.h>
34 #include <functional>
35 #include <camera_metadata_hidden.h>
36 #include <android-base/parseint.h>
37 #include <android-base/logging.h>
38 #include <cutils/properties.h>
39 #include <hwbinder/IPCThreadState.h>
40 #include <utils/SessionConfigurationUtils.h>
41 #include <utils/Trace.h>
42 
43 #include "api2/HeicCompositeStream.h"
44 #include "device3/ZoomRatioMapper.h"
45 
46 namespace android {
47 
48 using namespace ::android::hardware::camera;
49 using namespace ::android::hardware::camera::common::V1_0;
50 using std::literals::chrono_literals::operator""s;
51 using hardware::camera2::utils::CameraIdAndSessionConfiguration;
52 using hardware::camera::provider::V2_6::CameraIdAndStreamCombination;
53 
54 namespace {
55 const bool kEnableLazyHal(property_get_bool("ro.camera.enableLazyHal", false));
56 } // anonymous namespace
57 
58 const float CameraProviderManager::kDepthARTolerance = .1f;
59 
60 CameraProviderManager::HardwareServiceInteractionProxy
61 CameraProviderManager::sHardwareServiceInteractionProxy{};
62 
~CameraProviderManager()63 CameraProviderManager::~CameraProviderManager() {
64 }
65 
66 hardware::hidl_vec<hardware::hidl_string>
listServices()67 CameraProviderManager::HardwareServiceInteractionProxy::listServices() {
68     hardware::hidl_vec<hardware::hidl_string> ret;
69     auto manager = hardware::defaultServiceManager1_2();
70     if (manager != nullptr) {
71         manager->listManifestByInterface(provider::V2_4::ICameraProvider::descriptor,
72                 [&ret](const hardware::hidl_vec<hardware::hidl_string> &registered) {
73                     ret = registered;
74                 });
75     }
76     return ret;
77 }
78 
initialize(wp<CameraProviderManager::StatusListener> listener,ServiceInteractionProxy * proxy)79 status_t CameraProviderManager::initialize(wp<CameraProviderManager::StatusListener> listener,
80         ServiceInteractionProxy* proxy) {
81     std::lock_guard<std::mutex> lock(mInterfaceMutex);
82     if (proxy == nullptr) {
83         ALOGE("%s: No valid service interaction proxy provided", __FUNCTION__);
84         return BAD_VALUE;
85     }
86     mListener = listener;
87     mServiceProxy = proxy;
88     mDeviceState = static_cast<hardware::hidl_bitfield<provider::V2_5::DeviceState>>(
89         provider::V2_5::DeviceState::NORMAL);
90 
91     // Registering will trigger notifications for all already-known providers
92     bool success = mServiceProxy->registerForNotifications(
93         /* instance name, empty means no filter */ "",
94         this);
95     if (!success) {
96         ALOGE("%s: Unable to register with hardware service manager for notifications "
97                 "about camera providers", __FUNCTION__);
98         return INVALID_OPERATION;
99     }
100 
101 
102     for (const auto& instance : mServiceProxy->listServices()) {
103         this->addProviderLocked(instance);
104     }
105 
106     IPCThreadState::self()->flushCommands();
107 
108     return OK;
109 }
110 
getCameraCount() const111 std::pair<int, int> CameraProviderManager::getCameraCount() const {
112     std::lock_guard<std::mutex> lock(mInterfaceMutex);
113     int systemCameraCount = 0;
114     int publicCameraCount = 0;
115     for (auto& provider : mProviders) {
116         for (auto &id : provider->mUniqueCameraIds) {
117             SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
118             if (getSystemCameraKindLocked(id, &deviceKind) != OK) {
119                 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
120                 continue;
121             }
122             switch(deviceKind) {
123                 case SystemCameraKind::PUBLIC:
124                     publicCameraCount++;
125                     break;
126                 case SystemCameraKind::SYSTEM_ONLY_CAMERA:
127                     systemCameraCount++;
128                     break;
129                 default:
130                     break;
131             }
132         }
133     }
134     return std::make_pair(systemCameraCount, publicCameraCount);
135 }
136 
getCameraDeviceIds() const137 std::vector<std::string> CameraProviderManager::getCameraDeviceIds() const {
138     std::lock_guard<std::mutex> lock(mInterfaceMutex);
139     std::vector<std::string> deviceIds;
140     for (auto& provider : mProviders) {
141         for (auto& id : provider->mUniqueCameraIds) {
142             deviceIds.push_back(id);
143         }
144     }
145     return deviceIds;
146 }
147 
collectDeviceIdsLocked(const std::vector<std::string> deviceIds,std::vector<std::string> & publicDeviceIds,std::vector<std::string> & systemDeviceIds) const148 void CameraProviderManager::collectDeviceIdsLocked(const std::vector<std::string> deviceIds,
149         std::vector<std::string>& publicDeviceIds,
150         std::vector<std::string>& systemDeviceIds) const {
151     for (auto &deviceId : deviceIds) {
152         SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
153         if (getSystemCameraKindLocked(deviceId, &deviceKind) != OK) {
154             ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
155             continue;
156         }
157         if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
158             systemDeviceIds.push_back(deviceId);
159         } else {
160             publicDeviceIds.push_back(deviceId);
161         }
162     }
163 }
164 
getAPI1CompatibleCameraDeviceIds() const165 std::vector<std::string> CameraProviderManager::getAPI1CompatibleCameraDeviceIds() const {
166     std::lock_guard<std::mutex> lock(mInterfaceMutex);
167     std::vector<std::string> publicDeviceIds;
168     std::vector<std::string> systemDeviceIds;
169     std::vector<std::string> deviceIds;
170     for (auto& provider : mProviders) {
171         std::vector<std::string> providerDeviceIds = provider->mUniqueAPI1CompatibleCameraIds;
172         // Secure cameras should not be exposed through camera 1 api
173         providerDeviceIds.erase(std::remove_if(providerDeviceIds.begin(), providerDeviceIds.end(),
174                 [this](const std::string& s) {
175                 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
176                 if (getSystemCameraKindLocked(s, &deviceKind) != OK) {
177                     ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, s.c_str());
178                     return true;
179                 }
180                 return deviceKind == SystemCameraKind::HIDDEN_SECURE_CAMERA;}),
181                 providerDeviceIds.end());
182         // API1 app doesn't handle logical and physical camera devices well. So
183         // for each camera facing, only take the first id advertised by HAL in
184         // all [logical, physical1, physical2, ...] id combos, and filter out the rest.
185         filterLogicalCameraIdsLocked(providerDeviceIds);
186         collectDeviceIdsLocked(providerDeviceIds, publicDeviceIds, systemDeviceIds);
187     }
188     auto sortFunc =
189             [](const std::string& a, const std::string& b) -> bool {
190                 uint32_t aUint = 0, bUint = 0;
191                 bool aIsUint = base::ParseUint(a, &aUint);
192                 bool bIsUint = base::ParseUint(b, &bUint);
193 
194                 // Uint device IDs first
195                 if (aIsUint && bIsUint) {
196                     return aUint < bUint;
197                 } else if (aIsUint) {
198                     return true;
199                 } else if (bIsUint) {
200                     return false;
201                 }
202                 // Simple string compare if both id are not uint
203                 return a < b;
204             };
205     // We put device ids for system cameras at the end since they will be pared
206     // off for processes not having system camera permissions.
207     std::sort(publicDeviceIds.begin(), publicDeviceIds.end(), sortFunc);
208     std::sort(systemDeviceIds.begin(), systemDeviceIds.end(), sortFunc);
209     deviceIds.insert(deviceIds.end(), publicDeviceIds.begin(), publicDeviceIds.end());
210     deviceIds.insert(deviceIds.end(), systemDeviceIds.begin(), systemDeviceIds.end());
211     return deviceIds;
212 }
213 
isValidDevice(const std::string & id,uint16_t majorVersion) const214 bool CameraProviderManager::isValidDevice(const std::string &id, uint16_t majorVersion) const {
215     std::lock_guard<std::mutex> lock(mInterfaceMutex);
216     return isValidDeviceLocked(id, majorVersion);
217 }
218 
isValidDeviceLocked(const std::string & id,uint16_t majorVersion) const219 bool CameraProviderManager::isValidDeviceLocked(const std::string &id, uint16_t majorVersion) const {
220     for (auto& provider : mProviders) {
221         for (auto& deviceInfo : provider->mDevices) {
222             if (deviceInfo->mId == id && deviceInfo->mVersion.get_major() == majorVersion) {
223                 return true;
224             }
225         }
226     }
227     return false;
228 }
229 
hasFlashUnit(const std::string & id) const230 bool CameraProviderManager::hasFlashUnit(const std::string &id) const {
231     std::lock_guard<std::mutex> lock(mInterfaceMutex);
232 
233     auto deviceInfo = findDeviceInfoLocked(id);
234     if (deviceInfo == nullptr) return false;
235 
236     return deviceInfo->hasFlashUnit();
237 }
238 
supportNativeZoomRatio(const std::string & id) const239 bool CameraProviderManager::supportNativeZoomRatio(const std::string &id) const {
240     std::lock_guard<std::mutex> lock(mInterfaceMutex);
241 
242     auto deviceInfo = findDeviceInfoLocked(id);
243     if (deviceInfo == nullptr) return false;
244 
245     return deviceInfo->supportNativeZoomRatio();
246 }
247 
getResourceCost(const std::string & id,CameraResourceCost * cost) const248 status_t CameraProviderManager::getResourceCost(const std::string &id,
249         CameraResourceCost* cost) const {
250     std::lock_guard<std::mutex> lock(mInterfaceMutex);
251 
252     auto deviceInfo = findDeviceInfoLocked(id);
253     if (deviceInfo == nullptr) return NAME_NOT_FOUND;
254 
255     *cost = deviceInfo->mResourceCost;
256     return OK;
257 }
258 
getCameraInfo(const std::string & id,hardware::CameraInfo * info) const259 status_t CameraProviderManager::getCameraInfo(const std::string &id,
260         hardware::CameraInfo* info) const {
261     std::lock_guard<std::mutex> lock(mInterfaceMutex);
262 
263     auto deviceInfo = findDeviceInfoLocked(id);
264     if (deviceInfo == nullptr) return NAME_NOT_FOUND;
265 
266     return deviceInfo->getCameraInfo(info);
267 }
268 
isSessionConfigurationSupported(const std::string & id,const hardware::camera::device::V3_4::StreamConfiguration & configuration,bool * status) const269 status_t CameraProviderManager::isSessionConfigurationSupported(const std::string& id,
270         const hardware::camera::device::V3_4::StreamConfiguration &configuration,
271         bool *status /*out*/) const {
272     std::lock_guard<std::mutex> lock(mInterfaceMutex);
273     auto deviceInfo = findDeviceInfoLocked(id);
274     if (deviceInfo == nullptr) {
275         return NAME_NOT_FOUND;
276     }
277 
278     return deviceInfo->isSessionConfigurationSupported(configuration, status);
279 }
280 
getCameraCharacteristics(const std::string & id,CameraMetadata * characteristics) const281 status_t CameraProviderManager::getCameraCharacteristics(const std::string &id,
282         CameraMetadata* characteristics) const {
283     std::lock_guard<std::mutex> lock(mInterfaceMutex);
284     return getCameraCharacteristicsLocked(id, characteristics);
285 }
286 
getHighestSupportedVersion(const std::string & id,hardware::hidl_version * v)287 status_t CameraProviderManager::getHighestSupportedVersion(const std::string &id,
288         hardware::hidl_version *v) {
289     std::lock_guard<std::mutex> lock(mInterfaceMutex);
290 
291     hardware::hidl_version maxVersion{0,0};
292     bool found = false;
293     for (auto& provider : mProviders) {
294         for (auto& deviceInfo : provider->mDevices) {
295             if (deviceInfo->mId == id) {
296                 if (deviceInfo->mVersion > maxVersion) {
297                     maxVersion = deviceInfo->mVersion;
298                     found = true;
299                 }
300             }
301         }
302     }
303     if (!found) {
304         return NAME_NOT_FOUND;
305     }
306     *v = maxVersion;
307     return OK;
308 }
309 
supportSetTorchMode(const std::string & id) const310 bool CameraProviderManager::supportSetTorchMode(const std::string &id) const {
311     std::lock_guard<std::mutex> lock(mInterfaceMutex);
312     for (auto& provider : mProviders) {
313         auto deviceInfo = findDeviceInfoLocked(id);
314         if (deviceInfo != nullptr) {
315             return provider->mSetTorchModeSupported;
316         }
317     }
318     return false;
319 }
320 
setTorchMode(const std::string & id,bool enabled)321 status_t CameraProviderManager::setTorchMode(const std::string &id, bool enabled) {
322     std::lock_guard<std::mutex> lock(mInterfaceMutex);
323 
324     auto deviceInfo = findDeviceInfoLocked(id);
325     if (deviceInfo == nullptr) return NAME_NOT_FOUND;
326 
327     // Pass the camera ID to start interface so that it will save it to the map of ICameraProviders
328     // that are currently in use.
329     sp<ProviderInfo> parentProvider = deviceInfo->mParentProvider.promote();
330     if (parentProvider == nullptr) {
331         return DEAD_OBJECT;
332     }
333     const sp<provider::V2_4::ICameraProvider> interface = parentProvider->startProviderInterface();
334     if (interface == nullptr) {
335         return DEAD_OBJECT;
336     }
337     saveRef(DeviceMode::TORCH, deviceInfo->mId, interface);
338 
339     return deviceInfo->setTorchMode(enabled);
340 }
341 
setUpVendorTags()342 status_t CameraProviderManager::setUpVendorTags() {
343     sp<VendorTagDescriptorCache> tagCache = new VendorTagDescriptorCache();
344 
345     for (auto& provider : mProviders) {
346         tagCache->addVendorDescriptor(provider->mProviderTagid, provider->mVendorTagDescriptor);
347     }
348 
349     VendorTagDescriptorCache::setAsGlobalVendorTagCache(tagCache);
350 
351     return OK;
352 }
353 
notifyDeviceStateChange(hardware::hidl_bitfield<provider::V2_5::DeviceState> newState)354 status_t CameraProviderManager::notifyDeviceStateChange(
355         hardware::hidl_bitfield<provider::V2_5::DeviceState> newState) {
356     std::lock_guard<std::mutex> lock(mInterfaceMutex);
357     mDeviceState = newState;
358     status_t res = OK;
359     for (auto& provider : mProviders) {
360         ALOGV("%s: Notifying %s for new state 0x%" PRIx64,
361                 __FUNCTION__, provider->mProviderName.c_str(), newState);
362         status_t singleRes = provider->notifyDeviceStateChange(mDeviceState);
363         if (singleRes != OK) {
364             ALOGE("%s: Unable to notify provider %s about device state change",
365                     __FUNCTION__,
366                     provider->mProviderName.c_str());
367             res = singleRes;
368             // continue to do the rest of the providers instead of returning now
369         }
370     }
371     return res;
372 }
373 
openSession(const std::string & id,const sp<device::V3_2::ICameraDeviceCallback> & callback,sp<device::V3_2::ICameraDeviceSession> * session)374 status_t CameraProviderManager::openSession(const std::string &id,
375         const sp<device::V3_2::ICameraDeviceCallback>& callback,
376         /*out*/
377         sp<device::V3_2::ICameraDeviceSession> *session) {
378 
379     std::lock_guard<std::mutex> lock(mInterfaceMutex);
380 
381     auto deviceInfo = findDeviceInfoLocked(id,
382             /*minVersion*/ {3,0}, /*maxVersion*/ {4,0});
383     if (deviceInfo == nullptr) return NAME_NOT_FOUND;
384 
385     auto *deviceInfo3 = static_cast<ProviderInfo::DeviceInfo3*>(deviceInfo);
386     sp<ProviderInfo> parentProvider = deviceInfo->mParentProvider.promote();
387     if (parentProvider == nullptr) {
388         return DEAD_OBJECT;
389     }
390     const sp<provider::V2_4::ICameraProvider> provider = parentProvider->startProviderInterface();
391     if (provider == nullptr) {
392         return DEAD_OBJECT;
393     }
394     saveRef(DeviceMode::CAMERA, id, provider);
395 
396     Status status;
397     hardware::Return<void> ret;
398     auto interface = deviceInfo3->startDeviceInterface<
399             CameraProviderManager::ProviderInfo::DeviceInfo3::InterfaceT>();
400     if (interface == nullptr) {
401         return DEAD_OBJECT;
402     }
403 
404     ret = interface->open(callback, [&status, &session]
405             (Status s, const sp<device::V3_2::ICameraDeviceSession>& cameraSession) {
406                 status = s;
407                 if (status == Status::OK) {
408                     *session = cameraSession;
409                 }
410             });
411     if (!ret.isOk()) {
412         removeRef(DeviceMode::CAMERA, id);
413         ALOGE("%s: Transaction error opening a session for camera device %s: %s",
414                 __FUNCTION__, id.c_str(), ret.description().c_str());
415         return DEAD_OBJECT;
416     }
417     return mapToStatusT(status);
418 }
419 
openSession(const std::string & id,const sp<device::V1_0::ICameraDeviceCallback> & callback,sp<device::V1_0::ICameraDevice> * session)420 status_t CameraProviderManager::openSession(const std::string &id,
421         const sp<device::V1_0::ICameraDeviceCallback>& callback,
422         /*out*/
423         sp<device::V1_0::ICameraDevice> *session) {
424 
425     std::lock_guard<std::mutex> lock(mInterfaceMutex);
426 
427     auto deviceInfo = findDeviceInfoLocked(id,
428             /*minVersion*/ {1,0}, /*maxVersion*/ {2,0});
429     if (deviceInfo == nullptr) return NAME_NOT_FOUND;
430 
431     auto *deviceInfo1 = static_cast<ProviderInfo::DeviceInfo1*>(deviceInfo);
432     sp<ProviderInfo> parentProvider = deviceInfo->mParentProvider.promote();
433     if (parentProvider == nullptr) {
434         return DEAD_OBJECT;
435     }
436     const sp<provider::V2_4::ICameraProvider> provider = parentProvider->startProviderInterface();
437     if (provider == nullptr) {
438         return DEAD_OBJECT;
439     }
440     saveRef(DeviceMode::CAMERA, id, provider);
441 
442     auto interface = deviceInfo1->startDeviceInterface<
443             CameraProviderManager::ProviderInfo::DeviceInfo1::InterfaceT>();
444     if (interface == nullptr) {
445         return DEAD_OBJECT;
446     }
447     hardware::Return<Status> status = interface->open(callback);
448     if (!status.isOk()) {
449         removeRef(DeviceMode::CAMERA, id);
450         ALOGE("%s: Transaction error opening a session for camera device %s: %s",
451                 __FUNCTION__, id.c_str(), status.description().c_str());
452         return DEAD_OBJECT;
453     }
454     if (status == Status::OK) {
455         *session = interface;
456     }
457     return mapToStatusT(status);
458 }
459 
saveRef(DeviceMode usageType,const std::string & cameraId,sp<provider::V2_4::ICameraProvider> provider)460 void CameraProviderManager::saveRef(DeviceMode usageType, const std::string &cameraId,
461         sp<provider::V2_4::ICameraProvider> provider) {
462     if (!kEnableLazyHal) {
463         return;
464     }
465     ALOGV("Saving camera provider %s for camera device %s", provider->descriptor, cameraId.c_str());
466     std::lock_guard<std::mutex> lock(mProviderInterfaceMapLock);
467     std::unordered_map<std::string, sp<provider::V2_4::ICameraProvider>> *primaryMap, *alternateMap;
468     if (usageType == DeviceMode::TORCH) {
469         primaryMap = &mTorchProviderByCameraId;
470         alternateMap = &mCameraProviderByCameraId;
471     } else {
472         primaryMap = &mCameraProviderByCameraId;
473         alternateMap = &mTorchProviderByCameraId;
474     }
475     auto id = cameraId.c_str();
476     (*primaryMap)[id] = provider;
477     auto search = alternateMap->find(id);
478     if (search != alternateMap->end()) {
479         ALOGW("%s: Camera device %s is using both torch mode and camera mode simultaneously. "
480                 "That should not be possible", __FUNCTION__, id);
481     }
482     ALOGV("%s: Camera device %s connected", __FUNCTION__, id);
483 }
484 
removeRef(DeviceMode usageType,const std::string & cameraId)485 void CameraProviderManager::removeRef(DeviceMode usageType, const std::string &cameraId) {
486     if (!kEnableLazyHal) {
487         return;
488     }
489     ALOGV("Removing camera device %s", cameraId.c_str());
490     std::unordered_map<std::string, sp<provider::V2_4::ICameraProvider>> *providerMap;
491     if (usageType == DeviceMode::TORCH) {
492         providerMap = &mTorchProviderByCameraId;
493     } else {
494         providerMap = &mCameraProviderByCameraId;
495     }
496     std::lock_guard<std::mutex> lock(mProviderInterfaceMapLock);
497     auto search = providerMap->find(cameraId.c_str());
498     if (search != providerMap->end()) {
499         // Drop the reference to this ICameraProvider. This is safe to do immediately (without an
500         // added delay) because hwservicemanager guarantees to hold the reference for at least five
501         // more seconds.  We depend on this behavior so that if the provider is unreferenced and
502         // then referenced again quickly, we do not let the HAL exit and then need to immediately
503         // restart it. An example when this could happen is switching from a front-facing to a
504         // rear-facing camera. If the HAL were to exit during the camera switch, the camera could
505         // appear janky to the user.
506         providerMap->erase(cameraId.c_str());
507         IPCThreadState::self()->flushCommands();
508     } else {
509         ALOGE("%s: Asked to remove reference for camera %s, but no reference to it was found. This "
510                 "could mean removeRef was called twice for the same camera ID.", __FUNCTION__,
511                 cameraId.c_str());
512     }
513 }
514 
onRegistration(const hardware::hidl_string &,const hardware::hidl_string & name,bool)515 hardware::Return<void> CameraProviderManager::onRegistration(
516         const hardware::hidl_string& /*fqName*/,
517         const hardware::hidl_string& name,
518         bool /*preexisting*/) {
519     std::lock_guard<std::mutex> providerLock(mProviderLifecycleLock);
520     {
521         std::lock_guard<std::mutex> lock(mInterfaceMutex);
522 
523         addProviderLocked(name);
524     }
525 
526     sp<StatusListener> listener = getStatusListener();
527     if (nullptr != listener.get()) {
528         listener->onNewProviderRegistered();
529     }
530 
531     IPCThreadState::self()->flushCommands();
532 
533     return hardware::Return<void>();
534 }
535 
dump(int fd,const Vector<String16> & args)536 status_t CameraProviderManager::dump(int fd, const Vector<String16>& args) {
537     std::lock_guard<std::mutex> lock(mInterfaceMutex);
538 
539     for (auto& provider : mProviders) {
540         provider->dump(fd, args);
541     }
542     return OK;
543 }
544 
findDeviceInfoLocked(const std::string & id,hardware::hidl_version minVersion,hardware::hidl_version maxVersion) const545 CameraProviderManager::ProviderInfo::DeviceInfo* CameraProviderManager::findDeviceInfoLocked(
546         const std::string& id,
547         hardware::hidl_version minVersion, hardware::hidl_version maxVersion) const {
548     for (auto& provider : mProviders) {
549         for (auto& deviceInfo : provider->mDevices) {
550             if (deviceInfo->mId == id &&
551                     minVersion <= deviceInfo->mVersion && maxVersion >= deviceInfo->mVersion) {
552                 return deviceInfo.get();
553             }
554         }
555     }
556     return nullptr;
557 }
558 
getProviderTagIdLocked(const std::string & id,hardware::hidl_version minVersion,hardware::hidl_version maxVersion) const559 metadata_vendor_id_t CameraProviderManager::getProviderTagIdLocked(
560         const std::string& id, hardware::hidl_version minVersion,
561         hardware::hidl_version maxVersion) const {
562     metadata_vendor_id_t ret = CAMERA_METADATA_INVALID_VENDOR_ID;
563 
564     std::lock_guard<std::mutex> lock(mInterfaceMutex);
565     for (auto& provider : mProviders) {
566         for (auto& deviceInfo : provider->mDevices) {
567             if (deviceInfo->mId == id &&
568                     minVersion <= deviceInfo->mVersion &&
569                     maxVersion >= deviceInfo->mVersion) {
570                 return provider->mProviderTagid;
571             }
572         }
573     }
574 
575     return ret;
576 }
577 
queryPhysicalCameraIds()578 void CameraProviderManager::ProviderInfo::DeviceInfo3::queryPhysicalCameraIds() {
579     camera_metadata_entry_t entryCap;
580 
581     entryCap = mCameraCharacteristics.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
582     for (size_t i = 0; i < entryCap.count; ++i) {
583         uint8_t capability = entryCap.data.u8[i];
584         if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA) {
585             mIsLogicalCamera = true;
586             break;
587         }
588     }
589     if (!mIsLogicalCamera) {
590         return;
591     }
592 
593     camera_metadata_entry_t entryIds = mCameraCharacteristics.find(
594             ANDROID_LOGICAL_MULTI_CAMERA_PHYSICAL_IDS);
595     const uint8_t* ids = entryIds.data.u8;
596     size_t start = 0;
597     for (size_t i = 0; i < entryIds.count; ++i) {
598         if (ids[i] == '\0') {
599             if (start != i) {
600                 mPhysicalIds.push_back((const char*)ids+start);
601             }
602             start = i+1;
603         }
604     }
605 }
606 
getSystemCameraKind()607 SystemCameraKind CameraProviderManager::ProviderInfo::DeviceInfo3::getSystemCameraKind() {
608     camera_metadata_entry_t entryCap;
609     entryCap = mCameraCharacteristics.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
610     if (entryCap.count == 1 &&
611             entryCap.data.u8[0] == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_SECURE_IMAGE_DATA) {
612         return SystemCameraKind::HIDDEN_SECURE_CAMERA;
613     }
614 
615     // Go through the capabilities and check if it has
616     // ANDROID_REQUEST_AVAILABLE_CAPABILITIES_SYSTEM_CAMERA
617     for (size_t i = 0; i < entryCap.count; ++i) {
618         uint8_t capability = entryCap.data.u8[i];
619         if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_SYSTEM_CAMERA) {
620             return SystemCameraKind::SYSTEM_ONLY_CAMERA;
621         }
622     }
623     return SystemCameraKind::PUBLIC;
624 }
625 
getSupportedSizes(const CameraMetadata & ch,uint32_t tag,android_pixel_format_t format,std::vector<std::tuple<size_t,size_t>> * sizes)626 void CameraProviderManager::ProviderInfo::DeviceInfo3::getSupportedSizes(
627         const CameraMetadata& ch, uint32_t tag, android_pixel_format_t format,
628         std::vector<std::tuple<size_t, size_t>> *sizes/*out*/) {
629     if (sizes == nullptr) {
630         return;
631     }
632 
633     auto scalerDims = ch.find(tag);
634     if (scalerDims.count > 0) {
635         // Scaler entry contains 4 elements (format, width, height, type)
636         for (size_t i = 0; i < scalerDims.count; i += 4) {
637             if ((scalerDims.data.i32[i] == format) &&
638                     (scalerDims.data.i32[i+3] ==
639                      ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT)) {
640                 sizes->push_back(std::make_tuple(scalerDims.data.i32[i+1],
641                             scalerDims.data.i32[i+2]));
642             }
643         }
644     }
645 }
646 
getSupportedDurations(const CameraMetadata & ch,uint32_t tag,android_pixel_format_t format,const std::vector<std::tuple<size_t,size_t>> & sizes,std::vector<int64_t> * durations)647 void CameraProviderManager::ProviderInfo::DeviceInfo3::getSupportedDurations(
648         const CameraMetadata& ch, uint32_t tag, android_pixel_format_t format,
649         const std::vector<std::tuple<size_t, size_t>>& sizes,
650         std::vector<int64_t> *durations/*out*/) {
651     if (durations == nullptr) {
652         return;
653     }
654 
655     auto availableDurations = ch.find(tag);
656     if (availableDurations.count > 0) {
657         // Duration entry contains 4 elements (format, width, height, duration)
658         for (size_t i = 0; i < availableDurations.count; i += 4) {
659             for (const auto& size : sizes) {
660                 int64_t width = std::get<0>(size);
661                 int64_t height = std::get<1>(size);
662                 if ((availableDurations.data.i64[i] == format) &&
663                         (availableDurations.data.i64[i+1] == width) &&
664                         (availableDurations.data.i64[i+2] == height)) {
665                     durations->push_back(availableDurations.data.i64[i+3]);
666                 }
667             }
668         }
669     }
670 }
getSupportedDynamicDepthDurations(const std::vector<int64_t> & depthDurations,const std::vector<int64_t> & blobDurations,std::vector<int64_t> * dynamicDepthDurations)671 void CameraProviderManager::ProviderInfo::DeviceInfo3::getSupportedDynamicDepthDurations(
672         const std::vector<int64_t>& depthDurations, const std::vector<int64_t>& blobDurations,
673         std::vector<int64_t> *dynamicDepthDurations /*out*/) {
674     if ((dynamicDepthDurations == nullptr) || (depthDurations.size() != blobDurations.size())) {
675         return;
676     }
677 
678     // Unfortunately there is no direct way to calculate the dynamic depth stream duration.
679     // Processing time on camera service side can vary greatly depending on multiple
680     // variables which are not under our control. Make a guesstimate by taking the maximum
681     // corresponding duration value from depth and blob.
682     auto depthDuration = depthDurations.begin();
683     auto blobDuration = blobDurations.begin();
684     dynamicDepthDurations->reserve(depthDurations.size());
685     while ((depthDuration != depthDurations.end()) && (blobDuration != blobDurations.end())) {
686         dynamicDepthDurations->push_back(std::max(*depthDuration, *blobDuration));
687         depthDuration++; blobDuration++;
688     }
689 }
690 
getSupportedDynamicDepthSizes(const std::vector<std::tuple<size_t,size_t>> & blobSizes,const std::vector<std::tuple<size_t,size_t>> & depthSizes,std::vector<std::tuple<size_t,size_t>> * dynamicDepthSizes,std::vector<std::tuple<size_t,size_t>> * internalDepthSizes)691 void CameraProviderManager::ProviderInfo::DeviceInfo3::getSupportedDynamicDepthSizes(
692         const std::vector<std::tuple<size_t, size_t>>& blobSizes,
693         const std::vector<std::tuple<size_t, size_t>>& depthSizes,
694         std::vector<std::tuple<size_t, size_t>> *dynamicDepthSizes /*out*/,
695         std::vector<std::tuple<size_t, size_t>> *internalDepthSizes /*out*/) {
696     if (dynamicDepthSizes == nullptr || internalDepthSizes == nullptr) {
697         return;
698     }
699 
700     // The dynamic depth spec. does not mention how close the AR ratio should be.
701     // Try using something appropriate.
702     float ARTolerance = kDepthARTolerance;
703 
704     for (const auto& blobSize : blobSizes) {
705         float jpegAR = static_cast<float> (std::get<0>(blobSize)) /
706                 static_cast<float>(std::get<1>(blobSize));
707         bool found = false;
708         for (const auto& depthSize : depthSizes) {
709             if (depthSize == blobSize) {
710                 internalDepthSizes->push_back(depthSize);
711                 found = true;
712                 break;
713             } else {
714                 float depthAR = static_cast<float> (std::get<0>(depthSize)) /
715                     static_cast<float>(std::get<1>(depthSize));
716                 if (std::fabs(jpegAR - depthAR) <= ARTolerance) {
717                     internalDepthSizes->push_back(depthSize);
718                     found = true;
719                     break;
720                 }
721             }
722         }
723 
724         if (found) {
725             dynamicDepthSizes->push_back(blobSize);
726         }
727     }
728 }
729 
addDynamicDepthTags()730 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::addDynamicDepthTags() {
731     uint32_t depthExclTag = ANDROID_DEPTH_DEPTH_IS_EXCLUSIVE;
732     uint32_t depthSizesTag = ANDROID_DEPTH_AVAILABLE_DEPTH_STREAM_CONFIGURATIONS;
733     auto& c = mCameraCharacteristics;
734     std::vector<std::tuple<size_t, size_t>> supportedBlobSizes, supportedDepthSizes,
735             supportedDynamicDepthSizes, internalDepthSizes;
736     auto chTags = c.find(ANDROID_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS);
737     if (chTags.count == 0) {
738         ALOGE("%s: Supported camera characteristics is empty!", __FUNCTION__);
739         return BAD_VALUE;
740     }
741 
742     bool isDepthExclusivePresent = std::find(chTags.data.i32, chTags.data.i32 + chTags.count,
743             depthExclTag) != (chTags.data.i32 + chTags.count);
744     bool isDepthSizePresent = std::find(chTags.data.i32, chTags.data.i32 + chTags.count,
745             depthSizesTag) != (chTags.data.i32 + chTags.count);
746     if (!(isDepthExclusivePresent && isDepthSizePresent)) {
747         // No depth support, nothing more to do.
748         return OK;
749     }
750 
751     auto depthExclusiveEntry = c.find(depthExclTag);
752     if (depthExclusiveEntry.count > 0) {
753         if (depthExclusiveEntry.data.u8[0] != ANDROID_DEPTH_DEPTH_IS_EXCLUSIVE_FALSE) {
754             // Depth support is exclusive, nothing more to do.
755             return OK;
756         }
757     } else {
758         ALOGE("%s: Advertised depth exclusive tag but value is not present!", __FUNCTION__);
759         return BAD_VALUE;
760     }
761 
762     getSupportedSizes(c, ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS, HAL_PIXEL_FORMAT_BLOB,
763             &supportedBlobSizes);
764     getSupportedSizes(c, depthSizesTag, HAL_PIXEL_FORMAT_Y16, &supportedDepthSizes);
765     if (supportedBlobSizes.empty() || supportedDepthSizes.empty()) {
766         // Nothing to do in this case.
767         return OK;
768     }
769 
770     getSupportedDynamicDepthSizes(supportedBlobSizes, supportedDepthSizes,
771             &supportedDynamicDepthSizes, &internalDepthSizes);
772     if (supportedDynamicDepthSizes.empty()) {
773         // Nothing more to do.
774         return OK;
775     }
776 
777     std::vector<int32_t> dynamicDepthEntries;
778     for (const auto& it : supportedDynamicDepthSizes) {
779         int32_t entry[4] = {HAL_PIXEL_FORMAT_BLOB, static_cast<int32_t> (std::get<0>(it)),
780                 static_cast<int32_t> (std::get<1>(it)),
781                 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT };
782         dynamicDepthEntries.insert(dynamicDepthEntries.end(), entry, entry + 4);
783     }
784 
785     std::vector<int64_t> depthMinDurations, depthStallDurations;
786     std::vector<int64_t> blobMinDurations, blobStallDurations;
787     std::vector<int64_t> dynamicDepthMinDurations, dynamicDepthStallDurations;
788 
789     getSupportedDurations(c, ANDROID_DEPTH_AVAILABLE_DEPTH_MIN_FRAME_DURATIONS,
790             HAL_PIXEL_FORMAT_Y16, internalDepthSizes, &depthMinDurations);
791     getSupportedDurations(c, ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS,
792             HAL_PIXEL_FORMAT_BLOB, supportedDynamicDepthSizes, &blobMinDurations);
793     if (blobMinDurations.empty() || depthMinDurations.empty() ||
794             (depthMinDurations.size() != blobMinDurations.size())) {
795         ALOGE("%s: Unexpected number of available depth min durations! %zu vs. %zu",
796                 __FUNCTION__, depthMinDurations.size(), blobMinDurations.size());
797         return BAD_VALUE;
798     }
799 
800     getSupportedDurations(c, ANDROID_DEPTH_AVAILABLE_DEPTH_STALL_DURATIONS,
801             HAL_PIXEL_FORMAT_Y16, internalDepthSizes, &depthStallDurations);
802     getSupportedDurations(c, ANDROID_SCALER_AVAILABLE_STALL_DURATIONS,
803             HAL_PIXEL_FORMAT_BLOB, supportedDynamicDepthSizes, &blobStallDurations);
804     if (blobStallDurations.empty() || depthStallDurations.empty() ||
805             (depthStallDurations.size() != blobStallDurations.size())) {
806         ALOGE("%s: Unexpected number of available depth stall durations! %zu vs. %zu",
807                 __FUNCTION__, depthStallDurations.size(), blobStallDurations.size());
808         return BAD_VALUE;
809     }
810 
811     getSupportedDynamicDepthDurations(depthMinDurations, blobMinDurations,
812             &dynamicDepthMinDurations);
813     getSupportedDynamicDepthDurations(depthStallDurations, blobStallDurations,
814             &dynamicDepthStallDurations);
815     if (dynamicDepthMinDurations.empty() || dynamicDepthStallDurations.empty() ||
816             (dynamicDepthMinDurations.size() != dynamicDepthStallDurations.size())) {
817         ALOGE("%s: Unexpected number of dynamic depth stall/min durations! %zu vs. %zu",
818                 __FUNCTION__, dynamicDepthMinDurations.size(), dynamicDepthStallDurations.size());
819         return BAD_VALUE;
820     }
821 
822     std::vector<int64_t> dynamicDepthMinDurationEntries;
823     auto itDuration = dynamicDepthMinDurations.begin();
824     auto itSize = supportedDynamicDepthSizes.begin();
825     while (itDuration != dynamicDepthMinDurations.end()) {
826         int64_t entry[4] = {HAL_PIXEL_FORMAT_BLOB, static_cast<int32_t> (std::get<0>(*itSize)),
827                 static_cast<int32_t> (std::get<1>(*itSize)), *itDuration};
828         dynamicDepthMinDurationEntries.insert(dynamicDepthMinDurationEntries.end(), entry,
829                 entry + 4);
830         itDuration++; itSize++;
831     }
832 
833     std::vector<int64_t> dynamicDepthStallDurationEntries;
834     itDuration = dynamicDepthStallDurations.begin();
835     itSize = supportedDynamicDepthSizes.begin();
836     while (itDuration != dynamicDepthStallDurations.end()) {
837         int64_t entry[4] = {HAL_PIXEL_FORMAT_BLOB, static_cast<int32_t> (std::get<0>(*itSize)),
838                 static_cast<int32_t> (std::get<1>(*itSize)), *itDuration};
839         dynamicDepthStallDurationEntries.insert(dynamicDepthStallDurationEntries.end(), entry,
840                 entry + 4);
841         itDuration++; itSize++;
842     }
843 
844     std::vector<int32_t> supportedChTags;
845     supportedChTags.reserve(chTags.count + 3);
846     supportedChTags.insert(supportedChTags.end(), chTags.data.i32,
847             chTags.data.i32 + chTags.count);
848     supportedChTags.push_back(ANDROID_DEPTH_AVAILABLE_DYNAMIC_DEPTH_STREAM_CONFIGURATIONS);
849     supportedChTags.push_back(ANDROID_DEPTH_AVAILABLE_DYNAMIC_DEPTH_MIN_FRAME_DURATIONS);
850     supportedChTags.push_back(ANDROID_DEPTH_AVAILABLE_DYNAMIC_DEPTH_STALL_DURATIONS);
851     c.update(ANDROID_DEPTH_AVAILABLE_DYNAMIC_DEPTH_STREAM_CONFIGURATIONS,
852             dynamicDepthEntries.data(), dynamicDepthEntries.size());
853     c.update(ANDROID_DEPTH_AVAILABLE_DYNAMIC_DEPTH_MIN_FRAME_DURATIONS,
854             dynamicDepthMinDurationEntries.data(), dynamicDepthMinDurationEntries.size());
855     c.update(ANDROID_DEPTH_AVAILABLE_DYNAMIC_DEPTH_STALL_DURATIONS,
856             dynamicDepthStallDurationEntries.data(), dynamicDepthStallDurationEntries.size());
857     c.update(ANDROID_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS, supportedChTags.data(),
858             supportedChTags.size());
859 
860     return OK;
861 }
862 
fixupMonochromeTags()863 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::fixupMonochromeTags() {
864     status_t res = OK;
865     auto& c = mCameraCharacteristics;
866 
867     // Override static metadata for MONOCHROME camera with older device version
868     if (mVersion.get_major() == 3 && mVersion.get_minor() < 5) {
869         camera_metadata_entry cap = c.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
870         for (size_t i = 0; i < cap.count; i++) {
871             if (cap.data.u8[i] == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
872                 // ANDROID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT
873                 uint8_t cfa = ANDROID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_MONO;
874                 res = c.update(ANDROID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT, &cfa, 1);
875                 if (res != OK) {
876                     ALOGE("%s: Failed to update COLOR_FILTER_ARRANGEMENT: %s (%d)",
877                           __FUNCTION__, strerror(-res), res);
878                     return res;
879                 }
880 
881                 // ANDROID_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS
882                 const std::vector<uint32_t> sKeys = {
883                         ANDROID_SENSOR_REFERENCE_ILLUMINANT1,
884                         ANDROID_SENSOR_REFERENCE_ILLUMINANT2,
885                         ANDROID_SENSOR_CALIBRATION_TRANSFORM1,
886                         ANDROID_SENSOR_CALIBRATION_TRANSFORM2,
887                         ANDROID_SENSOR_COLOR_TRANSFORM1,
888                         ANDROID_SENSOR_COLOR_TRANSFORM2,
889                         ANDROID_SENSOR_FORWARD_MATRIX1,
890                         ANDROID_SENSOR_FORWARD_MATRIX2,
891                 };
892                 res = removeAvailableKeys(c, sKeys,
893                         ANDROID_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS);
894                 if (res != OK) {
895                     ALOGE("%s: Failed to update REQUEST_AVAILABLE_CHARACTERISTICS_KEYS: %s (%d)",
896                             __FUNCTION__, strerror(-res), res);
897                     return res;
898                 }
899 
900                 // ANDROID_REQUEST_AVAILABLE_REQUEST_KEYS
901                 const std::vector<uint32_t> reqKeys = {
902                         ANDROID_COLOR_CORRECTION_MODE,
903                         ANDROID_COLOR_CORRECTION_TRANSFORM,
904                         ANDROID_COLOR_CORRECTION_GAINS,
905                 };
906                 res = removeAvailableKeys(c, reqKeys, ANDROID_REQUEST_AVAILABLE_REQUEST_KEYS);
907                 if (res != OK) {
908                     ALOGE("%s: Failed to update REQUEST_AVAILABLE_REQUEST_KEYS: %s (%d)",
909                             __FUNCTION__, strerror(-res), res);
910                     return res;
911                 }
912 
913                 // ANDROID_REQUEST_AVAILABLE_RESULT_KEYS
914                 const std::vector<uint32_t> resKeys = {
915                         ANDROID_SENSOR_GREEN_SPLIT,
916                         ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
917                         ANDROID_COLOR_CORRECTION_MODE,
918                         ANDROID_COLOR_CORRECTION_TRANSFORM,
919                         ANDROID_COLOR_CORRECTION_GAINS,
920                 };
921                 res = removeAvailableKeys(c, resKeys, ANDROID_REQUEST_AVAILABLE_RESULT_KEYS);
922                 if (res != OK) {
923                     ALOGE("%s: Failed to update REQUEST_AVAILABLE_RESULT_KEYS: %s (%d)",
924                             __FUNCTION__, strerror(-res), res);
925                     return res;
926                 }
927 
928                 // ANDROID_SENSOR_BLACK_LEVEL_PATTERN
929                 camera_metadata_entry blEntry = c.find(ANDROID_SENSOR_BLACK_LEVEL_PATTERN);
930                 for (size_t j = 1; j < blEntry.count; j++) {
931                     blEntry.data.i32[j] = blEntry.data.i32[0];
932                 }
933             }
934         }
935     }
936     return res;
937 }
938 
addRotateCropTags()939 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::addRotateCropTags() {
940     status_t res = OK;
941     auto& c = mCameraCharacteristics;
942 
943     auto availableRotateCropEntry = c.find(ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
944     if (availableRotateCropEntry.count == 0) {
945         uint8_t defaultAvailableRotateCropEntry = ANDROID_SCALER_ROTATE_AND_CROP_NONE;
946         res = c.update(ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES,
947                 &defaultAvailableRotateCropEntry, 1);
948     }
949     return res;
950 }
951 
addPreCorrectionActiveArraySize()952 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::addPreCorrectionActiveArraySize() {
953     status_t res = OK;
954     auto& c = mCameraCharacteristics;
955 
956     auto activeArraySize = c.find(ANDROID_SENSOR_INFO_ACTIVE_ARRAY_SIZE);
957     auto preCorrectionActiveArraySize = c.find(
958             ANDROID_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE);
959     if (activeArraySize.count == 4 && preCorrectionActiveArraySize.count == 0) {
960         std::vector<int32_t> preCorrectionArray(
961                 activeArraySize.data.i32, activeArraySize.data.i32+4);
962         res = c.update(ANDROID_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE,
963                 preCorrectionArray.data(), 4);
964         if (res != OK) {
965             ALOGE("%s: Failed to add ANDROID_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE: %s(%d)",
966                     __FUNCTION__, strerror(-res), res);
967             return res;
968         }
969     } else {
970         return res;
971     }
972 
973     auto charTags = c.find(ANDROID_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS);
974     bool hasPreCorrectionActiveArraySize = std::find(charTags.data.i32,
975             charTags.data.i32 + charTags.count,
976             ANDROID_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE) !=
977             (charTags.data.i32 + charTags.count);
978     if (!hasPreCorrectionActiveArraySize) {
979         std::vector<int32_t> supportedCharTags;
980         supportedCharTags.reserve(charTags.count + 1);
981         supportedCharTags.insert(supportedCharTags.end(), charTags.data.i32,
982                 charTags.data.i32 + charTags.count);
983         supportedCharTags.push_back(ANDROID_SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE);
984 
985         res = c.update(ANDROID_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS, supportedCharTags.data(),
986                 supportedCharTags.size());
987         if (res != OK) {
988             ALOGE("%s: Failed to update ANDROID_REQUEST_AVAILABLE_CHARACTERISTICS_KEYS: %s(%d)",
989                     __FUNCTION__, strerror(-res), res);
990             return res;
991         }
992     }
993 
994     return res;
995 }
996 
removeAvailableKeys(CameraMetadata & c,const std::vector<uint32_t> & keys,uint32_t keyTag)997 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::removeAvailableKeys(
998         CameraMetadata& c, const std::vector<uint32_t>& keys, uint32_t keyTag) {
999     status_t res = OK;
1000 
1001     camera_metadata_entry keysEntry = c.find(keyTag);
1002     if (keysEntry.count == 0) {
1003         ALOGE("%s: Failed to find tag %u: %s (%d)", __FUNCTION__, keyTag, strerror(-res), res);
1004         return res;
1005     }
1006     std::vector<int32_t> vKeys;
1007     vKeys.reserve(keysEntry.count);
1008     for (size_t i = 0; i < keysEntry.count; i++) {
1009         if (std::find(keys.begin(), keys.end(), keysEntry.data.i32[i]) == keys.end()) {
1010             vKeys.push_back(keysEntry.data.i32[i]);
1011         }
1012     }
1013     res = c.update(keyTag, vKeys.data(), vKeys.size());
1014     return res;
1015 }
1016 
fillHeicStreamCombinations(std::vector<int32_t> * outputs,std::vector<int64_t> * durations,std::vector<int64_t> * stallDurations,const camera_metadata_entry & halStreamConfigs,const camera_metadata_entry & halStreamDurations)1017 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::fillHeicStreamCombinations(
1018         std::vector<int32_t>* outputs,
1019         std::vector<int64_t>* durations,
1020         std::vector<int64_t>* stallDurations,
1021         const camera_metadata_entry& halStreamConfigs,
1022         const camera_metadata_entry& halStreamDurations) {
1023     if (outputs == nullptr || durations == nullptr || stallDurations == nullptr) {
1024         return BAD_VALUE;
1025     }
1026 
1027     static bool supportInMemoryTempFile =
1028             camera3::HeicCompositeStream::isInMemoryTempFileSupported();
1029     if (!supportInMemoryTempFile) {
1030         ALOGI("%s: No HEIC support due to absence of in memory temp file support",
1031                 __FUNCTION__);
1032         return OK;
1033     }
1034 
1035     for (size_t i = 0; i < halStreamConfigs.count; i += 4) {
1036         int32_t format = halStreamConfigs.data.i32[i];
1037         // Only IMPLEMENTATION_DEFINED and YUV_888 can be used to generate HEIC
1038         // image.
1039         if (format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
1040                 format != HAL_PIXEL_FORMAT_YCBCR_420_888) {
1041             continue;
1042         }
1043 
1044         bool sizeAvail = false;
1045         for (size_t j = 0; j < outputs->size(); j+= 4) {
1046             if ((*outputs)[j+1] == halStreamConfigs.data.i32[i+1] &&
1047                     (*outputs)[j+2] == halStreamConfigs.data.i32[i+2]) {
1048                 sizeAvail = true;
1049                 break;
1050             }
1051         }
1052         if (sizeAvail) continue;
1053 
1054         int64_t stall = 0;
1055         bool useHeic = false;
1056         bool useGrid = false;
1057         if (camera3::HeicCompositeStream::isSizeSupportedByHeifEncoder(
1058                 halStreamConfigs.data.i32[i+1], halStreamConfigs.data.i32[i+2],
1059                 &useHeic, &useGrid, &stall)) {
1060             if (useGrid != (format == HAL_PIXEL_FORMAT_YCBCR_420_888)) {
1061                 continue;
1062             }
1063 
1064             // HEIC configuration
1065             int32_t config[] = {HAL_PIXEL_FORMAT_BLOB, halStreamConfigs.data.i32[i+1],
1066                     halStreamConfigs.data.i32[i+2], 0 /*isInput*/};
1067             outputs->insert(outputs->end(), config, config + 4);
1068 
1069             // HEIC minFrameDuration
1070             for (size_t j = 0; j < halStreamDurations.count; j += 4) {
1071                 if (halStreamDurations.data.i64[j] == format &&
1072                         halStreamDurations.data.i64[j+1] == halStreamConfigs.data.i32[i+1] &&
1073                         halStreamDurations.data.i64[j+2] == halStreamConfigs.data.i32[i+2]) {
1074                     int64_t duration[] = {HAL_PIXEL_FORMAT_BLOB, halStreamConfigs.data.i32[i+1],
1075                             halStreamConfigs.data.i32[i+2], halStreamDurations.data.i64[j+3]};
1076                     durations->insert(durations->end(), duration, duration+4);
1077                     break;
1078                 }
1079             }
1080 
1081             // HEIC stallDuration
1082             int64_t stallDuration[] = {HAL_PIXEL_FORMAT_BLOB, halStreamConfigs.data.i32[i+1],
1083                     halStreamConfigs.data.i32[i+2], stall};
1084             stallDurations->insert(stallDurations->end(), stallDuration, stallDuration+4);
1085         }
1086     }
1087     return OK;
1088 }
1089 
deriveHeicTags()1090 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::deriveHeicTags() {
1091     auto& c = mCameraCharacteristics;
1092 
1093     camera_metadata_entry halHeicSupport = c.find(ANDROID_HEIC_INFO_SUPPORTED);
1094     if (halHeicSupport.count > 1) {
1095         ALOGE("%s: Invalid entry count %zu for ANDROID_HEIC_INFO_SUPPORTED",
1096                 __FUNCTION__, halHeicSupport.count);
1097         return BAD_VALUE;
1098     } else if (halHeicSupport.count == 0 ||
1099             halHeicSupport.data.u8[0] == ANDROID_HEIC_INFO_SUPPORTED_FALSE) {
1100         // Camera HAL doesn't support mandatory stream combinations for HEIC.
1101         return OK;
1102     }
1103 
1104     camera_metadata_entry maxJpegAppsSegments =
1105             c.find(ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT);
1106     if (maxJpegAppsSegments.count != 1 || maxJpegAppsSegments.data.u8[0] == 0 ||
1107             maxJpegAppsSegments.data.u8[0] > 16) {
1108         ALOGE("%s: ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT must be within [1, 16]",
1109                 __FUNCTION__);
1110         return BAD_VALUE;
1111     }
1112 
1113     // Populate HEIC output configurations and its related min frame duration
1114     // and stall duration.
1115     std::vector<int32_t> heicOutputs;
1116     std::vector<int64_t> heicDurations;
1117     std::vector<int64_t> heicStallDurations;
1118 
1119     camera_metadata_entry halStreamConfigs =
1120             c.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
1121     camera_metadata_entry minFrameDurations =
1122             c.find(ANDROID_SCALER_AVAILABLE_MIN_FRAME_DURATIONS);
1123 
1124     status_t res = fillHeicStreamCombinations(&heicOutputs, &heicDurations, &heicStallDurations,
1125             halStreamConfigs, minFrameDurations);
1126     if (res != OK) {
1127         ALOGE("%s: Failed to fill HEIC stream combinations: %s (%d)", __FUNCTION__,
1128                 strerror(-res), res);
1129         return res;
1130     }
1131 
1132     c.update(ANDROID_HEIC_AVAILABLE_HEIC_STREAM_CONFIGURATIONS,
1133            heicOutputs.data(), heicOutputs.size());
1134     c.update(ANDROID_HEIC_AVAILABLE_HEIC_MIN_FRAME_DURATIONS,
1135             heicDurations.data(), heicDurations.size());
1136     c.update(ANDROID_HEIC_AVAILABLE_HEIC_STALL_DURATIONS,
1137             heicStallDurations.data(), heicStallDurations.size());
1138 
1139     return OK;
1140 }
1141 
isLogicalCameraLocked(const std::string & id,std::vector<std::string> * physicalCameraIds)1142 bool CameraProviderManager::isLogicalCameraLocked(const std::string& id,
1143         std::vector<std::string>* physicalCameraIds) {
1144     auto deviceInfo = findDeviceInfoLocked(id);
1145     if (deviceInfo == nullptr) return false;
1146 
1147     if (deviceInfo->mIsLogicalCamera && physicalCameraIds != nullptr) {
1148         *physicalCameraIds = deviceInfo->mPhysicalIds;
1149     }
1150     return deviceInfo->mIsLogicalCamera;
1151 }
1152 
isLogicalCamera(const std::string & id,std::vector<std::string> * physicalCameraIds)1153 bool CameraProviderManager::isLogicalCamera(const std::string& id,
1154         std::vector<std::string>* physicalCameraIds) {
1155     std::lock_guard<std::mutex> lock(mInterfaceMutex);
1156     return isLogicalCameraLocked(id, physicalCameraIds);
1157 }
1158 
getSystemCameraKind(const std::string & id,SystemCameraKind * kind) const1159 status_t CameraProviderManager::getSystemCameraKind(const std::string& id,
1160         SystemCameraKind *kind) const {
1161     std::lock_guard<std::mutex> lock(mInterfaceMutex);
1162     return getSystemCameraKindLocked(id, kind);
1163 }
1164 
getSystemCameraKindLocked(const std::string & id,SystemCameraKind * kind) const1165 status_t CameraProviderManager::getSystemCameraKindLocked(const std::string& id,
1166         SystemCameraKind *kind) const {
1167     auto deviceInfo = findDeviceInfoLocked(id);
1168     if (deviceInfo != nullptr) {
1169         *kind = deviceInfo->mSystemCameraKind;
1170         return OK;
1171     }
1172     // If this is a hidden physical camera, we should return what kind of
1173     // camera the enclosing logical camera is.
1174     auto isHiddenAndParent = isHiddenPhysicalCameraInternal(id);
1175     if (isHiddenAndParent.first) {
1176         LOG_ALWAYS_FATAL_IF(id == isHiddenAndParent.second->mId,
1177                 "%s: hidden physical camera id %s and enclosing logical camera id %s are the same",
1178                 __FUNCTION__, id.c_str(), isHiddenAndParent.second->mId.c_str());
1179         return getSystemCameraKindLocked(isHiddenAndParent.second->mId, kind);
1180     }
1181     // Neither a hidden physical camera nor a logical camera
1182     return NAME_NOT_FOUND;
1183 }
1184 
isHiddenPhysicalCamera(const std::string & cameraId) const1185 bool CameraProviderManager::isHiddenPhysicalCamera(const std::string& cameraId) const {
1186     return isHiddenPhysicalCameraInternal(cameraId).first;
1187 }
1188 
1189 std::pair<bool, CameraProviderManager::ProviderInfo::DeviceInfo *>
isHiddenPhysicalCameraInternal(const std::string & cameraId) const1190 CameraProviderManager::isHiddenPhysicalCameraInternal(const std::string& cameraId) const {
1191     auto falseRet = std::make_pair(false, nullptr);
1192     for (auto& provider : mProviders) {
1193         for (auto& deviceInfo : provider->mDevices) {
1194             if (deviceInfo->mId == cameraId) {
1195                 // cameraId is found in public camera IDs advertised by the
1196                 // provider.
1197                 return falseRet;
1198             }
1199         }
1200     }
1201 
1202     for (auto& provider : mProviders) {
1203         for (auto& deviceInfo : provider->mDevices) {
1204             CameraMetadata info;
1205             status_t res = deviceInfo->getCameraCharacteristics(&info);
1206             if (res != OK) {
1207                 ALOGE("%s: Failed to getCameraCharacteristics for id %s", __FUNCTION__,
1208                         deviceInfo->mId.c_str());
1209                 return falseRet;
1210             }
1211 
1212             std::vector<std::string> physicalIds;
1213             if (deviceInfo->mIsLogicalCamera) {
1214                 if (std::find(deviceInfo->mPhysicalIds.begin(), deviceInfo->mPhysicalIds.end(),
1215                         cameraId) != deviceInfo->mPhysicalIds.end()) {
1216                     int deviceVersion = HARDWARE_DEVICE_API_VERSION(
1217                             deviceInfo->mVersion.get_major(), deviceInfo->mVersion.get_minor());
1218                     if (deviceVersion < CAMERA_DEVICE_API_VERSION_3_5) {
1219                         ALOGE("%s: Wrong deviceVersion %x for hiddenPhysicalCameraId %s",
1220                                 __FUNCTION__, deviceVersion, cameraId.c_str());
1221                         return falseRet;
1222                     } else {
1223                         return std::make_pair(true, deviceInfo.get());
1224                     }
1225                 }
1226             }
1227         }
1228     }
1229 
1230     return falseRet;
1231 }
1232 
addProviderLocked(const std::string & newProvider)1233 status_t CameraProviderManager::addProviderLocked(const std::string& newProvider) {
1234     for (const auto& providerInfo : mProviders) {
1235         if (providerInfo->mProviderName == newProvider) {
1236             ALOGW("%s: Camera provider HAL with name '%s' already registered", __FUNCTION__,
1237                     newProvider.c_str());
1238             return ALREADY_EXISTS;
1239         }
1240     }
1241 
1242     sp<provider::V2_4::ICameraProvider> interface;
1243     interface = mServiceProxy->tryGetService(newProvider);
1244 
1245     if (interface == nullptr) {
1246         ALOGE("%s: Camera provider HAL '%s' is not actually available", __FUNCTION__,
1247                 newProvider.c_str());
1248         return BAD_VALUE;
1249     }
1250 
1251     sp<ProviderInfo> providerInfo = new ProviderInfo(newProvider, this);
1252     status_t res = providerInfo->initialize(interface, mDeviceState);
1253     if (res != OK) {
1254         return res;
1255     }
1256 
1257     mProviders.push_back(providerInfo);
1258 
1259     return OK;
1260 }
1261 
removeProvider(const std::string & provider)1262 status_t CameraProviderManager::removeProvider(const std::string& provider) {
1263     std::lock_guard<std::mutex> providerLock(mProviderLifecycleLock);
1264     std::unique_lock<std::mutex> lock(mInterfaceMutex);
1265     std::vector<String8> removedDeviceIds;
1266     status_t res = NAME_NOT_FOUND;
1267     for (auto it = mProviders.begin(); it != mProviders.end(); it++) {
1268         if ((*it)->mProviderName == provider) {
1269             removedDeviceIds.reserve((*it)->mDevices.size());
1270             for (auto& deviceInfo : (*it)->mDevices) {
1271                 removedDeviceIds.push_back(String8(deviceInfo->mId.c_str()));
1272             }
1273             mProviders.erase(it);
1274             res = OK;
1275             break;
1276         }
1277     }
1278     if (res != OK) {
1279         ALOGW("%s: Camera provider HAL with name '%s' is not registered", __FUNCTION__,
1280                 provider.c_str());
1281     } else {
1282         // Inform camera service of loss of presence for all the devices from this provider,
1283         // without lock held for reentrancy
1284         sp<StatusListener> listener = getStatusListener();
1285         if (listener != nullptr) {
1286             lock.unlock();
1287             for (auto& id : removedDeviceIds) {
1288                 listener->onDeviceStatusChanged(id, CameraDeviceStatus::NOT_PRESENT);
1289             }
1290         }
1291     }
1292     return res;
1293 }
1294 
getStatusListener() const1295 sp<CameraProviderManager::StatusListener> CameraProviderManager::getStatusListener() const {
1296     return mListener.promote();
1297 }
1298 
1299 /**** Methods for ProviderInfo ****/
1300 
1301 
ProviderInfo(const std::string & providerName,CameraProviderManager * manager)1302 CameraProviderManager::ProviderInfo::ProviderInfo(
1303         const std::string &providerName,
1304         CameraProviderManager *manager) :
1305         mProviderName(providerName),
1306         mProviderTagid(generateVendorTagId(providerName)),
1307         mUniqueDeviceCount(0),
1308         mManager(manager) {
1309     (void) mManager;
1310 }
1311 
initialize(sp<provider::V2_4::ICameraProvider> & interface,hardware::hidl_bitfield<provider::V2_5::DeviceState> currentDeviceState)1312 status_t CameraProviderManager::ProviderInfo::initialize(
1313         sp<provider::V2_4::ICameraProvider>& interface,
1314         hardware::hidl_bitfield<provider::V2_5::DeviceState> currentDeviceState) {
1315     status_t res = parseProviderName(mProviderName, &mType, &mId);
1316     if (res != OK) {
1317         ALOGE("%s: Invalid provider name, ignoring", __FUNCTION__);
1318         return BAD_VALUE;
1319     }
1320     ALOGI("Connecting to new camera provider: %s, isRemote? %d",
1321             mProviderName.c_str(), interface->isRemote());
1322 
1323     // Determine minor version
1324     mMinorVersion = 4;
1325     auto cast2_6 = provider::V2_6::ICameraProvider::castFrom(interface);
1326     sp<provider::V2_6::ICameraProvider> interface2_6 = nullptr;
1327     if (cast2_6.isOk()) {
1328         interface2_6 = cast2_6;
1329         if (interface2_6 != nullptr) {
1330             mMinorVersion = 6;
1331         }
1332     }
1333     // We need to check again since cast2_6.isOk() succeeds even if the provider
1334     // version isn't actually 2.6.
1335     if (interface2_6 == nullptr){
1336         auto cast2_5 =
1337                 provider::V2_5::ICameraProvider::castFrom(interface);
1338         sp<provider::V2_5::ICameraProvider> interface2_5 = nullptr;
1339         if (cast2_5.isOk()) {
1340             interface2_5 = cast2_5;
1341             if (interface != nullptr) {
1342                 mMinorVersion = 5;
1343             }
1344         }
1345     }
1346 
1347     hardware::Return<bool> linked = interface->linkToDeath(this, /*cookie*/ mId);
1348     if (!linked.isOk()) {
1349         ALOGE("%s: Transaction error in linking to camera provider '%s' death: %s",
1350                 __FUNCTION__, mProviderName.c_str(), linked.description().c_str());
1351         return DEAD_OBJECT;
1352     } else if (!linked) {
1353         ALOGW("%s: Unable to link to provider '%s' death notifications",
1354                 __FUNCTION__, mProviderName.c_str());
1355     }
1356 
1357     if (!kEnableLazyHal) {
1358         // Save HAL reference indefinitely
1359         mSavedInterface = interface;
1360     } else {
1361         mActiveInterface = interface;
1362     }
1363 
1364     ALOGV("%s: Setting device state for %s: 0x%" PRIx64,
1365             __FUNCTION__, mProviderName.c_str(), mDeviceState);
1366     notifyDeviceStateChange(currentDeviceState);
1367 
1368     res = setUpVendorTags();
1369     if (res != OK) {
1370         ALOGE("%s: Unable to set up vendor tags from provider '%s'",
1371                 __FUNCTION__, mProviderName.c_str());
1372         return res;
1373     }
1374 
1375     Status status;
1376     // Get initial list of camera devices, if any
1377     std::vector<std::string> devices;
1378     hardware::Return<void> ret = interface->getCameraIdList([&status, this, &devices](
1379             Status idStatus,
1380             const hardware::hidl_vec<hardware::hidl_string>& cameraDeviceNames) {
1381         status = idStatus;
1382         if (status == Status::OK) {
1383             for (auto& name : cameraDeviceNames) {
1384                 uint16_t major, minor;
1385                 std::string type, id;
1386                 status_t res = parseDeviceName(name, &major, &minor, &type, &id);
1387                 if (res != OK) {
1388                     ALOGE("%s: Error parsing deviceName: %s: %d", __FUNCTION__, name.c_str(), res);
1389                     status = Status::INTERNAL_ERROR;
1390                 } else {
1391                     devices.push_back(name);
1392                     mProviderPublicCameraIds.push_back(id);
1393                 }
1394             }
1395         } });
1396     if (!ret.isOk()) {
1397         ALOGE("%s: Transaction error in getting camera ID list from provider '%s': %s",
1398                 __FUNCTION__, mProviderName.c_str(), linked.description().c_str());
1399         return DEAD_OBJECT;
1400     }
1401     if (status != Status::OK) {
1402         ALOGE("%s: Unable to query for camera devices from provider '%s'",
1403                 __FUNCTION__, mProviderName.c_str());
1404         return mapToStatusT(status);
1405     }
1406 
1407     // Get list of concurrent streaming camera device combinations
1408     if (mMinorVersion >= 6) {
1409         res = getConcurrentCameraIdsInternalLocked(interface2_6);
1410         if (res != OK) {
1411             return res;
1412         }
1413     }
1414 
1415     ret = interface->isSetTorchModeSupported(
1416         [this](auto status, bool supported) {
1417             if (status == Status::OK) {
1418                 mSetTorchModeSupported = supported;
1419             }
1420         });
1421     if (!ret.isOk()) {
1422         ALOGE("%s: Transaction error checking torch mode support '%s': %s",
1423                 __FUNCTION__, mProviderName.c_str(), ret.description().c_str());
1424         return DEAD_OBJECT;
1425     }
1426 
1427     mIsRemote = interface->isRemote();
1428 
1429     sp<StatusListener> listener = mManager->getStatusListener();
1430     for (auto& device : devices) {
1431         std::string id;
1432         status_t res = addDevice(device, common::V1_0::CameraDeviceStatus::PRESENT, &id);
1433         if (res != OK) {
1434             ALOGE("%s: Unable to enumerate camera device '%s': %s (%d)",
1435                     __FUNCTION__, device.c_str(), strerror(-res), res);
1436             continue;
1437         }
1438     }
1439 
1440     // cameraDeviceStatusChange callbacks may be called (and causing new devices added)
1441     // before setCallback returns. setCallback must be called after addDevice so that
1442     // the physical camera status callback can look up available regular
1443     // cameras.
1444     hardware::Return<Status> st = interface->setCallback(this);
1445     if (!st.isOk()) {
1446         ALOGE("%s: Transaction error setting up callbacks with camera provider '%s': %s",
1447                 __FUNCTION__, mProviderName.c_str(), st.description().c_str());
1448         return DEAD_OBJECT;
1449     }
1450     if (st != Status::OK) {
1451         ALOGE("%s: Unable to register callbacks with camera provider '%s'",
1452                 __FUNCTION__, mProviderName.c_str());
1453         return mapToStatusT(st);
1454     }
1455 
1456     ALOGI("Camera provider %s ready with %zu camera devices",
1457             mProviderName.c_str(), mDevices.size());
1458 
1459     mInitialized = true;
1460     return OK;
1461 }
1462 
1463 const sp<provider::V2_4::ICameraProvider>
startProviderInterface()1464 CameraProviderManager::ProviderInfo::startProviderInterface() {
1465     ATRACE_CALL();
1466     ALOGV("Request to start camera provider: %s", mProviderName.c_str());
1467     if (mSavedInterface != nullptr) {
1468         return mSavedInterface;
1469     }
1470     if (!kEnableLazyHal) {
1471         ALOGE("Bad provider state! Should not be here on a non-lazy HAL!");
1472         return nullptr;
1473     }
1474 
1475     auto interface = mActiveInterface.promote();
1476     if (interface == nullptr) {
1477         ALOGI("Camera HAL provider needs restart, calling getService(%s)", mProviderName.c_str());
1478         interface = mManager->mServiceProxy->getService(mProviderName);
1479         interface->setCallback(this);
1480         hardware::Return<bool> linked = interface->linkToDeath(this, /*cookie*/ mId);
1481         if (!linked.isOk()) {
1482             ALOGE("%s: Transaction error in linking to camera provider '%s' death: %s",
1483                     __FUNCTION__, mProviderName.c_str(), linked.description().c_str());
1484             mManager->removeProvider(mProviderName);
1485             return nullptr;
1486         } else if (!linked) {
1487             ALOGW("%s: Unable to link to provider '%s' death notifications",
1488                     __FUNCTION__, mProviderName.c_str());
1489         }
1490         // Send current device state
1491         if (mMinorVersion >= 5) {
1492             auto castResult = provider::V2_5::ICameraProvider::castFrom(interface);
1493             if (castResult.isOk()) {
1494                 sp<provider::V2_5::ICameraProvider> interface_2_5 = castResult;
1495                 if (interface_2_5 != nullptr) {
1496                     ALOGV("%s: Initial device state for %s: 0x %" PRIx64,
1497                             __FUNCTION__, mProviderName.c_str(), mDeviceState);
1498                     interface_2_5->notifyDeviceStateChange(mDeviceState);
1499                 }
1500             }
1501         }
1502 
1503         mActiveInterface = interface;
1504     } else {
1505         ALOGV("Camera provider (%s) already in use. Re-using instance.", mProviderName.c_str());
1506     }
1507     return interface;
1508 }
1509 
getType() const1510 const std::string& CameraProviderManager::ProviderInfo::getType() const {
1511     return mType;
1512 }
1513 
addDevice(const std::string & name,CameraDeviceStatus initialStatus,std::string * parsedId)1514 status_t CameraProviderManager::ProviderInfo::addDevice(const std::string& name,
1515         CameraDeviceStatus initialStatus, /*out*/ std::string* parsedId) {
1516 
1517     ALOGI("Enumerating new camera device: %s", name.c_str());
1518 
1519     uint16_t major, minor;
1520     std::string type, id;
1521 
1522     status_t res = parseDeviceName(name, &major, &minor, &type, &id);
1523     if (res != OK) {
1524         return res;
1525     }
1526     if (type != mType) {
1527         ALOGE("%s: Device type %s does not match provider type %s", __FUNCTION__,
1528                 type.c_str(), mType.c_str());
1529         return BAD_VALUE;
1530     }
1531     if (mManager->isValidDeviceLocked(id, major)) {
1532         ALOGE("%s: Device %s: ID %s is already in use for device major version %d", __FUNCTION__,
1533                 name.c_str(), id.c_str(), major);
1534         return BAD_VALUE;
1535     }
1536 
1537     std::unique_ptr<DeviceInfo> deviceInfo;
1538     switch (major) {
1539         case 1:
1540             deviceInfo = initializeDeviceInfo<DeviceInfo1>(name, mProviderTagid,
1541                     id, minor);
1542             break;
1543         case 3:
1544             deviceInfo = initializeDeviceInfo<DeviceInfo3>(name, mProviderTagid,
1545                     id, minor);
1546             break;
1547         default:
1548             ALOGE("%s: Device %s: Unknown HIDL device HAL major version %d:", __FUNCTION__,
1549                     name.c_str(), major);
1550             return BAD_VALUE;
1551     }
1552     if (deviceInfo == nullptr) return BAD_VALUE;
1553     deviceInfo->mStatus = initialStatus;
1554     bool isAPI1Compatible = deviceInfo->isAPI1Compatible();
1555 
1556     mDevices.push_back(std::move(deviceInfo));
1557 
1558     mUniqueCameraIds.insert(id);
1559     if (isAPI1Compatible) {
1560         // addDevice can be called more than once for the same camera id if HAL
1561         // supports openLegacy.
1562         if (std::find(mUniqueAPI1CompatibleCameraIds.begin(), mUniqueAPI1CompatibleCameraIds.end(),
1563                 id) == mUniqueAPI1CompatibleCameraIds.end()) {
1564             mUniqueAPI1CompatibleCameraIds.push_back(id);
1565         }
1566     }
1567 
1568     if (parsedId != nullptr) {
1569         *parsedId = id;
1570     }
1571     return OK;
1572 }
1573 
removeDevice(std::string id)1574 void CameraProviderManager::ProviderInfo::removeDevice(std::string id) {
1575     for (auto it = mDevices.begin(); it != mDevices.end(); it++) {
1576         if ((*it)->mId == id) {
1577             mUniqueCameraIds.erase(id);
1578             if ((*it)->isAPI1Compatible()) {
1579                 mUniqueAPI1CompatibleCameraIds.erase(std::remove(
1580                         mUniqueAPI1CompatibleCameraIds.begin(),
1581                         mUniqueAPI1CompatibleCameraIds.end(), id));
1582             }
1583             mDevices.erase(it);
1584             break;
1585         }
1586     }
1587 }
1588 
dump(int fd,const Vector<String16> &) const1589 status_t CameraProviderManager::ProviderInfo::dump(int fd, const Vector<String16>&) const {
1590     dprintf(fd, "== Camera Provider HAL %s (v2.%d, %s) static info: %zu devices: ==\n",
1591             mProviderName.c_str(),
1592             mMinorVersion,
1593             mIsRemote ? "remote" : "passthrough",
1594             mDevices.size());
1595 
1596     for (auto& device : mDevices) {
1597         dprintf(fd, "== Camera HAL device %s (v%d.%d) static information: ==\n", device->mName.c_str(),
1598                 device->mVersion.get_major(), device->mVersion.get_minor());
1599         dprintf(fd, "  Resource cost: %d\n", device->mResourceCost.resourceCost);
1600         if (device->mResourceCost.conflictingDevices.size() == 0) {
1601             dprintf(fd, "  Conflicting devices: None\n");
1602         } else {
1603             dprintf(fd, "  Conflicting devices:\n");
1604             for (size_t i = 0; i < device->mResourceCost.conflictingDevices.size(); i++) {
1605                 dprintf(fd, "    %s\n",
1606                         device->mResourceCost.conflictingDevices[i].c_str());
1607             }
1608         }
1609         dprintf(fd, "  API1 info:\n");
1610         dprintf(fd, "    Has a flash unit: %s\n",
1611                 device->hasFlashUnit() ? "true" : "false");
1612         hardware::CameraInfo info;
1613         status_t res = device->getCameraInfo(&info);
1614         if (res != OK) {
1615             dprintf(fd, "   <Error reading camera info: %s (%d)>\n",
1616                     strerror(-res), res);
1617         } else {
1618             dprintf(fd, "    Facing: %s\n",
1619                     info.facing == hardware::CAMERA_FACING_BACK ? "Back" : "Front");
1620             dprintf(fd, "    Orientation: %d\n", info.orientation);
1621         }
1622         CameraMetadata info2;
1623         res = device->getCameraCharacteristics(&info2);
1624         if (res == INVALID_OPERATION) {
1625             dprintf(fd, "  API2 not directly supported\n");
1626         } else if (res != OK) {
1627             dprintf(fd, "  <Error reading camera characteristics: %s (%d)>\n",
1628                     strerror(-res), res);
1629         } else {
1630             dprintf(fd, "  API2 camera characteristics:\n");
1631             info2.dump(fd, /*verbosity*/ 2, /*indentation*/ 4);
1632         }
1633 
1634         // Dump characteristics of non-standalone physical camera
1635         if (device->mIsLogicalCamera) {
1636             for (auto& id : device->mPhysicalIds) {
1637                 // Skip if physical id is an independent camera
1638                 if (std::find(mProviderPublicCameraIds.begin(), mProviderPublicCameraIds.end(), id)
1639                         != mProviderPublicCameraIds.end()) {
1640                     continue;
1641                 }
1642 
1643                 CameraMetadata physicalInfo;
1644                 status_t status = device->getPhysicalCameraCharacteristics(id, &physicalInfo);
1645                 if (status == OK) {
1646                     dprintf(fd, "  Physical camera %s characteristics:\n", id.c_str());
1647                     physicalInfo.dump(fd, /*verbosity*/ 2, /*indentation*/ 4);
1648                 }
1649             }
1650         }
1651 
1652         dprintf(fd, "== Camera HAL device %s (v%d.%d) dumpState: ==\n", device->mName.c_str(),
1653                 device->mVersion.get_major(), device->mVersion.get_minor());
1654         res = device->dumpState(fd);
1655         if (res != OK) {
1656             dprintf(fd, "   <Error dumping device %s state: %s (%d)>\n",
1657                     device->mName.c_str(), strerror(-res), res);
1658         }
1659     }
1660     return OK;
1661 }
1662 
getConcurrentCameraIdsInternalLocked(sp<provider::V2_6::ICameraProvider> & interface2_6)1663 status_t CameraProviderManager::ProviderInfo::getConcurrentCameraIdsInternalLocked(
1664         sp<provider::V2_6::ICameraProvider> &interface2_6) {
1665     if (interface2_6 == nullptr) {
1666         ALOGE("%s: null interface provided", __FUNCTION__);
1667         return BAD_VALUE;
1668     }
1669     Status status = Status::OK;
1670     hardware::Return<void> ret =
1671             interface2_6->getConcurrentStreamingCameraIds([&status, this](
1672             Status concurrentIdStatus, // TODO: Move all instances of hidl_string to 'using'
1673             const hardware::hidl_vec<hardware::hidl_vec<hardware::hidl_string>>&
1674                         cameraDeviceIdCombinations) {
1675             status = concurrentIdStatus;
1676             if (status == Status::OK) {
1677                 mConcurrentCameraIdCombinations.clear();
1678                 for (auto& combination : cameraDeviceIdCombinations) {
1679                     std::unordered_set<std::string> deviceIds;
1680                     for (auto &cameraDeviceId : combination) {
1681                         deviceIds.insert(cameraDeviceId.c_str());
1682                     }
1683                     mConcurrentCameraIdCombinations.push_back(std::move(deviceIds));
1684                 }
1685             } });
1686     if (!ret.isOk()) {
1687         ALOGE("%s: Transaction error in getting concurrent camera ID list from provider '%s'",
1688                 __FUNCTION__, mProviderName.c_str());
1689             return DEAD_OBJECT;
1690     }
1691     if (status != Status::OK) {
1692         ALOGE("%s: Unable to query for camera devices from provider '%s'",
1693                     __FUNCTION__, mProviderName.c_str());
1694         return mapToStatusT(status);
1695     }
1696     return OK;
1697 }
1698 
reCacheConcurrentStreamingCameraIdsLocked()1699 status_t CameraProviderManager::ProviderInfo::reCacheConcurrentStreamingCameraIdsLocked() {
1700     if (mMinorVersion < 6) {
1701       // Unsupported operation, nothing to do here
1702       return OK;
1703     }
1704     // Check if the provider is currently active - not going to start it up for this notification
1705     auto interface = mSavedInterface != nullptr ? mSavedInterface : mActiveInterface.promote();
1706     if (interface == nullptr) {
1707         ALOGE("%s: camera provider interface for %s is not valid", __FUNCTION__,
1708                 mProviderName.c_str());
1709         return INVALID_OPERATION;
1710     }
1711     auto castResult = provider::V2_6::ICameraProvider::castFrom(interface);
1712 
1713     if (castResult.isOk()) {
1714         sp<provider::V2_6::ICameraProvider> interface2_6 = castResult;
1715         if (interface2_6 != nullptr) {
1716             return getConcurrentCameraIdsInternalLocked(interface2_6);
1717         } else {
1718             // This should not happen since mMinorVersion >= 6
1719             ALOGE("%s: mMinorVersion was >= 6, but interface2_6 was nullptr", __FUNCTION__);
1720             return UNKNOWN_ERROR;
1721         }
1722     }
1723     return OK;
1724 }
1725 
1726 std::vector<std::unordered_set<std::string>>
getConcurrentCameraIdCombinations()1727 CameraProviderManager::ProviderInfo::getConcurrentCameraIdCombinations() {
1728     std::lock_guard<std::mutex> lock(mLock);
1729     return mConcurrentCameraIdCombinations;
1730 }
1731 
cameraDeviceStatusChange(const hardware::hidl_string & cameraDeviceName,CameraDeviceStatus newStatus)1732 hardware::Return<void> CameraProviderManager::ProviderInfo::cameraDeviceStatusChange(
1733         const hardware::hidl_string& cameraDeviceName,
1734         CameraDeviceStatus newStatus) {
1735     sp<StatusListener> listener;
1736     std::string id;
1737     bool initialized = false;
1738     {
1739         std::lock_guard<std::mutex> lock(mLock);
1740         bool known = false;
1741         for (auto& deviceInfo : mDevices) {
1742             if (deviceInfo->mName == cameraDeviceName) {
1743                 ALOGI("Camera device %s status is now %s, was %s", cameraDeviceName.c_str(),
1744                         deviceStatusToString(newStatus), deviceStatusToString(deviceInfo->mStatus));
1745                 deviceInfo->mStatus = newStatus;
1746                 // TODO: Handle device removal (NOT_PRESENT)
1747                 id = deviceInfo->mId;
1748                 known = true;
1749                 break;
1750             }
1751         }
1752         // Previously unseen device; status must not be NOT_PRESENT
1753         if (!known) {
1754             if (newStatus == CameraDeviceStatus::NOT_PRESENT) {
1755                 ALOGW("Camera provider %s says an unknown camera device %s is not present. Curious.",
1756                     mProviderName.c_str(), cameraDeviceName.c_str());
1757                 return hardware::Void();
1758             }
1759             addDevice(cameraDeviceName, newStatus, &id);
1760         } else if (newStatus == CameraDeviceStatus::NOT_PRESENT) {
1761             removeDevice(id);
1762         }
1763         listener = mManager->getStatusListener();
1764         initialized = mInitialized;
1765         if (reCacheConcurrentStreamingCameraIdsLocked() != OK) {
1766             ALOGE("%s: CameraProvider %s could not re-cache concurrent streaming camera id list ",
1767                       __FUNCTION__, mProviderName.c_str());
1768         }
1769     }
1770     // Call without lock held to allow reentrancy into provider manager
1771     // Don't send the callback if providerInfo hasn't been initialized.
1772     // CameraService will initialize device status after provider is
1773     // initialized
1774     if (listener != nullptr && initialized) {
1775         listener->onDeviceStatusChanged(String8(id.c_str()), newStatus);
1776     }
1777     return hardware::Void();
1778 }
1779 
physicalCameraDeviceStatusChange(const hardware::hidl_string & cameraDeviceName,const hardware::hidl_string & physicalCameraDeviceName,CameraDeviceStatus newStatus)1780 hardware::Return<void> CameraProviderManager::ProviderInfo::physicalCameraDeviceStatusChange(
1781         const hardware::hidl_string& cameraDeviceName,
1782         const hardware::hidl_string& physicalCameraDeviceName,
1783         CameraDeviceStatus newStatus) {
1784     sp<StatusListener> listener;
1785     std::string id;
1786     bool initialized = false;
1787     {
1788         std::lock_guard<std::mutex> lock(mLock);
1789         bool known = false;
1790         for (auto& deviceInfo : mDevices) {
1791             if (deviceInfo->mName == cameraDeviceName) {
1792                 id = deviceInfo->mId;
1793 
1794                 if (!deviceInfo->mIsLogicalCamera) {
1795                     ALOGE("%s: Invalid combination of camera id %s, physical id %s",
1796                             __FUNCTION__, id.c_str(), physicalCameraDeviceName.c_str());
1797                     return hardware::Void();
1798                 }
1799                 if (std::find(deviceInfo->mPhysicalIds.begin(), deviceInfo->mPhysicalIds.end(),
1800                         physicalCameraDeviceName) == deviceInfo->mPhysicalIds.end()) {
1801                     ALOGE("%s: Invalid combination of camera id %s, physical id %s",
1802                             __FUNCTION__, id.c_str(), physicalCameraDeviceName.c_str());
1803                     return hardware::Void();
1804                 }
1805                 ALOGI("Camera device %s physical device %s status is now %s, was %s",
1806                         cameraDeviceName.c_str(), physicalCameraDeviceName.c_str(),
1807                         deviceStatusToString(newStatus), deviceStatusToString(
1808                         deviceInfo->mPhysicalStatus[physicalCameraDeviceName]));
1809                 known = true;
1810                 break;
1811             }
1812         }
1813         // Previously unseen device; status must not be NOT_PRESENT
1814         if (!known) {
1815             ALOGW("Camera provider %s says an unknown camera device %s-%s is not present. Curious.",
1816                     mProviderName.c_str(), cameraDeviceName.c_str(),
1817                     physicalCameraDeviceName.c_str());
1818             return hardware::Void();
1819         }
1820         listener = mManager->getStatusListener();
1821         initialized = mInitialized;
1822     }
1823     // Call without lock held to allow reentrancy into provider manager
1824     // Don't send the callback if providerInfo hasn't been initialized.
1825     // CameraService will initialize device status after provider is
1826     // initialized
1827     if (listener != nullptr && initialized) {
1828         String8 physicalId(physicalCameraDeviceName.c_str());
1829         listener->onDeviceStatusChanged(String8(id.c_str()),
1830                 physicalId, newStatus);
1831     }
1832     return hardware::Void();
1833 }
1834 
torchModeStatusChange(const hardware::hidl_string & cameraDeviceName,TorchModeStatus newStatus)1835 hardware::Return<void> CameraProviderManager::ProviderInfo::torchModeStatusChange(
1836         const hardware::hidl_string& cameraDeviceName,
1837         TorchModeStatus newStatus) {
1838     sp<StatusListener> listener;
1839     std::string id;
1840     {
1841         std::lock_guard<std::mutex> lock(mManager->mStatusListenerMutex);
1842         bool known = false;
1843         for (auto& deviceInfo : mDevices) {
1844             if (deviceInfo->mName == cameraDeviceName) {
1845                 ALOGI("Camera device %s torch status is now %s", cameraDeviceName.c_str(),
1846                         torchStatusToString(newStatus));
1847                 id = deviceInfo->mId;
1848                 known = true;
1849                 if (TorchModeStatus::AVAILABLE_ON != newStatus) {
1850                     mManager->removeRef(DeviceMode::TORCH, id);
1851                 }
1852                 break;
1853             }
1854         }
1855         if (!known) {
1856             ALOGW("Camera provider %s says an unknown camera %s now has torch status %d. Curious.",
1857                     mProviderName.c_str(), cameraDeviceName.c_str(), newStatus);
1858             return hardware::Void();
1859         }
1860         listener = mManager->getStatusListener();
1861     }
1862     // Call without lock held to allow reentrancy into provider manager
1863     if (listener != nullptr) {
1864         listener->onTorchStatusChanged(String8(id.c_str()), newStatus);
1865     }
1866     return hardware::Void();
1867 }
1868 
serviceDied(uint64_t cookie,const wp<hidl::base::V1_0::IBase> & who)1869 void CameraProviderManager::ProviderInfo::serviceDied(uint64_t cookie,
1870         const wp<hidl::base::V1_0::IBase>& who) {
1871     (void) who;
1872     ALOGI("Camera provider '%s' has died; removing it", mProviderName.c_str());
1873     if (cookie != mId) {
1874         ALOGW("%s: Unexpected serviceDied cookie %" PRIu64 ", expected %" PRIu32,
1875                 __FUNCTION__, cookie, mId);
1876     }
1877     mManager->removeProvider(mProviderName);
1878 }
1879 
setUpVendorTags()1880 status_t CameraProviderManager::ProviderInfo::setUpVendorTags() {
1881     if (mVendorTagDescriptor != nullptr)
1882         return OK;
1883 
1884     hardware::hidl_vec<VendorTagSection> vts;
1885     Status status;
1886     hardware::Return<void> ret;
1887     const sp<provider::V2_4::ICameraProvider> interface = startProviderInterface();
1888     if (interface == nullptr) {
1889         return DEAD_OBJECT;
1890     }
1891     ret = interface->getVendorTags(
1892         [&](auto s, const auto& vendorTagSecs) {
1893             status = s;
1894             if (s == Status::OK) {
1895                 vts = vendorTagSecs;
1896             }
1897     });
1898     if (!ret.isOk()) {
1899         ALOGE("%s: Transaction error getting vendor tags from provider '%s': %s",
1900                 __FUNCTION__, mProviderName.c_str(), ret.description().c_str());
1901         return DEAD_OBJECT;
1902     }
1903     if (status != Status::OK) {
1904         return mapToStatusT(status);
1905     }
1906 
1907     // Read all vendor tag definitions into a descriptor
1908     status_t res;
1909     if ((res = HidlVendorTagDescriptor::createDescriptorFromHidl(vts, /*out*/mVendorTagDescriptor))
1910             != OK) {
1911         ALOGE("%s: Could not generate descriptor from vendor tag operations,"
1912                 "received error %s (%d). Camera clients will not be able to use"
1913                 "vendor tags", __FUNCTION__, strerror(res), res);
1914         return res;
1915     }
1916 
1917     return OK;
1918 }
1919 
notifyDeviceStateChange(hardware::hidl_bitfield<provider::V2_5::DeviceState> newDeviceState)1920 status_t CameraProviderManager::ProviderInfo::notifyDeviceStateChange(
1921         hardware::hidl_bitfield<provider::V2_5::DeviceState> newDeviceState) {
1922     mDeviceState = newDeviceState;
1923     if (mMinorVersion >= 5) {
1924         // Check if the provider is currently active - not going to start it up for this notification
1925         auto interface = mSavedInterface != nullptr ? mSavedInterface : mActiveInterface.promote();
1926         if (interface != nullptr) {
1927             // Send current device state
1928             auto castResult = provider::V2_5::ICameraProvider::castFrom(interface);
1929             if (castResult.isOk()) {
1930                 sp<provider::V2_5::ICameraProvider> interface_2_5 = castResult;
1931                 if (interface_2_5 != nullptr) {
1932                     interface_2_5->notifyDeviceStateChange(mDeviceState);
1933                 }
1934             }
1935         }
1936     }
1937     return OK;
1938 }
1939 
isConcurrentSessionConfigurationSupported(const hardware::hidl_vec<CameraIdAndStreamCombination> & halCameraIdsAndStreamCombinations,bool * isSupported)1940 status_t CameraProviderManager::ProviderInfo::isConcurrentSessionConfigurationSupported(
1941         const hardware::hidl_vec<CameraIdAndStreamCombination> &halCameraIdsAndStreamCombinations,
1942         bool *isSupported) {
1943     status_t res = OK;
1944     if (mMinorVersion >= 6) {
1945         // Check if the provider is currently active - not going to start it up for this notification
1946         auto interface = mSavedInterface != nullptr ? mSavedInterface : mActiveInterface.promote();
1947         if (interface == nullptr) {
1948             // TODO: This might be some other problem
1949             return INVALID_OPERATION;
1950         }
1951         auto castResult = provider::V2_6::ICameraProvider::castFrom(interface);
1952         if (castResult.isOk()) {
1953             sp<provider::V2_6::ICameraProvider> interface_2_6 = castResult;
1954             if (interface_2_6 != nullptr) {
1955                 Status callStatus;
1956                 auto cb =
1957                         [&isSupported, &callStatus](Status s, bool supported) {
1958                               callStatus = s;
1959                               *isSupported = supported; };
1960 
1961                 auto ret =  interface_2_6->isConcurrentStreamCombinationSupported(
1962                             halCameraIdsAndStreamCombinations, cb);
1963                 if (ret.isOk()) {
1964                     switch (callStatus) {
1965                         case Status::OK:
1966                             // Expected case, do nothing.
1967                             res = OK;
1968                             break;
1969                         case Status::METHOD_NOT_SUPPORTED:
1970                             res = INVALID_OPERATION;
1971                             break;
1972                         default:
1973                             ALOGE("%s: Session configuration query failed: %d", __FUNCTION__,
1974                                       callStatus);
1975                             res = UNKNOWN_ERROR;
1976                     }
1977                 } else {
1978                     ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, ret.description().c_str());
1979                     res = UNKNOWN_ERROR;
1980                 }
1981                 return res;
1982             }
1983         }
1984     }
1985     // unsupported operation
1986     return INVALID_OPERATION;
1987 }
1988 
1989 template<class DeviceInfoT>
1990 std::unique_ptr<CameraProviderManager::ProviderInfo::DeviceInfo>
initializeDeviceInfo(const std::string & name,const metadata_vendor_id_t tagId,const std::string & id,uint16_t minorVersion)1991     CameraProviderManager::ProviderInfo::initializeDeviceInfo(
1992         const std::string &name, const metadata_vendor_id_t tagId,
1993         const std::string &id, uint16_t minorVersion) {
1994     Status status;
1995 
1996     auto cameraInterface =
1997             startDeviceInterface<typename DeviceInfoT::InterfaceT>(name);
1998     if (cameraInterface == nullptr) return nullptr;
1999 
2000     CameraResourceCost resourceCost;
2001     cameraInterface->getResourceCost([&status, &resourceCost](
2002         Status s, CameraResourceCost cost) {
2003                 status = s;
2004                 resourceCost = cost;
2005             });
2006     if (status != Status::OK) {
2007         ALOGE("%s: Unable to obtain resource costs for camera device %s: %s", __FUNCTION__,
2008                 name.c_str(), statusToString(status));
2009         return nullptr;
2010     }
2011 
2012     for (auto& conflictName : resourceCost.conflictingDevices) {
2013         uint16_t major, minor;
2014         std::string type, id;
2015         status_t res = parseDeviceName(conflictName, &major, &minor, &type, &id);
2016         if (res != OK) {
2017             ALOGE("%s: Failed to parse conflicting device %s", __FUNCTION__, conflictName.c_str());
2018             return nullptr;
2019         }
2020         conflictName = id;
2021     }
2022 
2023     return std::unique_ptr<DeviceInfo>(
2024         new DeviceInfoT(name, tagId, id, minorVersion, resourceCost, this,
2025                 mProviderPublicCameraIds, cameraInterface));
2026 }
2027 
2028 template<class InterfaceT>
2029 sp<InterfaceT>
startDeviceInterface(const std::string & name)2030 CameraProviderManager::ProviderInfo::startDeviceInterface(const std::string &name) {
2031     ALOGE("%s: Device %s: Unknown HIDL device HAL major version %d:", __FUNCTION__,
2032             name.c_str(), InterfaceT::version.get_major());
2033     return nullptr;
2034 }
2035 
2036 template<>
2037 sp<device::V1_0::ICameraDevice>
startDeviceInterface(const std::string & name)2038 CameraProviderManager::ProviderInfo::startDeviceInterface
2039         <device::V1_0::ICameraDevice>(const std::string &name) {
2040     Status status;
2041     sp<device::V1_0::ICameraDevice> cameraInterface;
2042     hardware::Return<void> ret;
2043     const sp<provider::V2_4::ICameraProvider> interface = startProviderInterface();
2044     if (interface == nullptr) {
2045         return nullptr;
2046     }
2047     ret = interface->getCameraDeviceInterface_V1_x(name, [&status, &cameraInterface](
2048         Status s, sp<device::V1_0::ICameraDevice> interface) {
2049                 status = s;
2050                 cameraInterface = interface;
2051             });
2052     if (!ret.isOk()) {
2053         ALOGE("%s: Transaction error trying to obtain interface for camera device %s: %s",
2054                 __FUNCTION__, name.c_str(), ret.description().c_str());
2055         return nullptr;
2056     }
2057     if (status != Status::OK) {
2058         ALOGE("%s: Unable to obtain interface for camera device %s: %s", __FUNCTION__,
2059                 name.c_str(), statusToString(status));
2060         return nullptr;
2061     }
2062     return cameraInterface;
2063 }
2064 
2065 template<>
2066 sp<device::V3_2::ICameraDevice>
startDeviceInterface(const std::string & name)2067 CameraProviderManager::ProviderInfo::startDeviceInterface
2068         <device::V3_2::ICameraDevice>(const std::string &name) {
2069     Status status;
2070     sp<device::V3_2::ICameraDevice> cameraInterface;
2071     hardware::Return<void> ret;
2072     const sp<provider::V2_4::ICameraProvider> interface = startProviderInterface();
2073     if (interface == nullptr) {
2074         return nullptr;
2075     }
2076     ret = interface->getCameraDeviceInterface_V3_x(name, [&status, &cameraInterface](
2077         Status s, sp<device::V3_2::ICameraDevice> interface) {
2078                 status = s;
2079                 cameraInterface = interface;
2080             });
2081     if (!ret.isOk()) {
2082         ALOGE("%s: Transaction error trying to obtain interface for camera device %s: %s",
2083                 __FUNCTION__, name.c_str(), ret.description().c_str());
2084         return nullptr;
2085     }
2086     if (status != Status::OK) {
2087         ALOGE("%s: Unable to obtain interface for camera device %s: %s", __FUNCTION__,
2088                 name.c_str(), statusToString(status));
2089         return nullptr;
2090     }
2091     return cameraInterface;
2092 }
2093 
~DeviceInfo()2094 CameraProviderManager::ProviderInfo::DeviceInfo::~DeviceInfo() {}
2095 
2096 template<class InterfaceT>
startDeviceInterface()2097 sp<InterfaceT> CameraProviderManager::ProviderInfo::DeviceInfo::startDeviceInterface() {
2098     sp<InterfaceT> device;
2099     ATRACE_CALL();
2100     if (mSavedInterface == nullptr) {
2101         sp<ProviderInfo> parentProvider = mParentProvider.promote();
2102         if (parentProvider != nullptr) {
2103             device = parentProvider->startDeviceInterface<InterfaceT>(mName);
2104         }
2105     } else {
2106         device = (InterfaceT *) mSavedInterface.get();
2107     }
2108     return device;
2109 }
2110 
2111 template<class InterfaceT>
setTorchMode(InterfaceT & interface,bool enabled)2112 status_t CameraProviderManager::ProviderInfo::DeviceInfo::setTorchMode(InterfaceT& interface,
2113         bool enabled) {
2114     Status s = interface->setTorchMode(enabled ? TorchMode::ON : TorchMode::OFF);
2115     return mapToStatusT(s);
2116 }
2117 
DeviceInfo1(const std::string & name,const metadata_vendor_id_t tagId,const std::string & id,uint16_t minorVersion,const CameraResourceCost & resourceCost,sp<ProviderInfo> parentProvider,const std::vector<std::string> & publicCameraIds,sp<InterfaceT> interface)2118 CameraProviderManager::ProviderInfo::DeviceInfo1::DeviceInfo1(const std::string& name,
2119         const metadata_vendor_id_t tagId, const std::string &id,
2120         uint16_t minorVersion,
2121         const CameraResourceCost& resourceCost,
2122         sp<ProviderInfo> parentProvider,
2123         const std::vector<std::string>& publicCameraIds,
2124         sp<InterfaceT> interface) :
2125         DeviceInfo(name, tagId, id, hardware::hidl_version{1, minorVersion},
2126                    publicCameraIds, resourceCost, parentProvider) {
2127     // Get default parameters and initialize flash unit availability
2128     // Requires powering on the camera device
2129     hardware::Return<Status> status = interface->open(nullptr);
2130     if (!status.isOk()) {
2131         ALOGE("%s: Transaction error opening camera device %s to check for a flash unit: %s",
2132                 __FUNCTION__, id.c_str(), status.description().c_str());
2133         return;
2134     }
2135     if (status != Status::OK) {
2136         ALOGE("%s: Unable to open camera device %s to check for a flash unit: %s", __FUNCTION__,
2137                 id.c_str(), CameraProviderManager::statusToString(status));
2138         return;
2139     }
2140     hardware::Return<void> ret;
__anon330ebd180e02(const hardware::hidl_string& parms) 2141     ret = interface->getParameters([this](const hardware::hidl_string& parms) {
2142                 mDefaultParameters.unflatten(String8(parms.c_str()));
2143             });
2144     if (!ret.isOk()) {
2145         ALOGE("%s: Transaction error reading camera device %s params to check for a flash unit: %s",
2146                 __FUNCTION__, id.c_str(), status.description().c_str());
2147         return;
2148     }
2149     const char *flashMode =
2150             mDefaultParameters.get(CameraParameters::KEY_SUPPORTED_FLASH_MODES);
2151     if (flashMode && strstr(flashMode, CameraParameters::FLASH_MODE_TORCH)) {
2152         mHasFlashUnit = true;
2153     }
2154 
2155     status_t res = cacheCameraInfo(interface);
2156     if (res != OK) {
2157         ALOGE("%s: Could not cache CameraInfo", __FUNCTION__);
2158         return;
2159     }
2160 
2161     ret = interface->close();
2162     if (!ret.isOk()) {
2163         ALOGE("%s: Transaction error closing camera device %s after check for a flash unit: %s",
2164                 __FUNCTION__, id.c_str(), status.description().c_str());
2165     }
2166 
2167     if (!kEnableLazyHal) {
2168         // Save HAL reference indefinitely
2169         mSavedInterface = interface;
2170     }
2171 }
2172 
~DeviceInfo1()2173 CameraProviderManager::ProviderInfo::DeviceInfo1::~DeviceInfo1() {}
2174 
setTorchMode(bool enabled)2175 status_t CameraProviderManager::ProviderInfo::DeviceInfo1::setTorchMode(bool enabled) {
2176     return setTorchModeForDevice<InterfaceT>(enabled);
2177 }
2178 
getCameraInfo(hardware::CameraInfo * info) const2179 status_t CameraProviderManager::ProviderInfo::DeviceInfo1::getCameraInfo(
2180         hardware::CameraInfo *info) const {
2181     if (info == nullptr) return BAD_VALUE;
2182     *info = mInfo;
2183     return OK;
2184 }
2185 
cacheCameraInfo(sp<CameraProviderManager::ProviderInfo::DeviceInfo1::InterfaceT> interface)2186 status_t CameraProviderManager::ProviderInfo::DeviceInfo1::cacheCameraInfo(
2187         sp<CameraProviderManager::ProviderInfo::DeviceInfo1::InterfaceT> interface) {
2188     Status status;
2189     device::V1_0::CameraInfo cInfo;
2190     hardware::Return<void> ret;
2191     ret = interface->getCameraInfo([&status, &cInfo](Status s, device::V1_0::CameraInfo camInfo) {
2192                 status = s;
2193                 cInfo = camInfo;
2194             });
2195     if (!ret.isOk()) {
2196         ALOGE("%s: Transaction error reading camera info from device %s: %s",
2197                 __FUNCTION__, mId.c_str(), ret.description().c_str());
2198         return DEAD_OBJECT;
2199     }
2200     if (status != Status::OK) {
2201         return mapToStatusT(status);
2202     }
2203 
2204     switch(cInfo.facing) {
2205         case device::V1_0::CameraFacing::BACK:
2206             mInfo.facing = hardware::CAMERA_FACING_BACK;
2207             break;
2208         case device::V1_0::CameraFacing::EXTERNAL:
2209             // Map external to front for legacy API
2210         case device::V1_0::CameraFacing::FRONT:
2211             mInfo.facing = hardware::CAMERA_FACING_FRONT;
2212             break;
2213         default:
2214             ALOGW("%s: Device %s: Unknown camera facing: %d",
2215                     __FUNCTION__, mId.c_str(), cInfo.facing);
2216             mInfo.facing = hardware::CAMERA_FACING_BACK;
2217     }
2218     mInfo.orientation = cInfo.orientation;
2219 
2220     return OK;
2221 }
2222 
dumpState(int fd)2223 status_t CameraProviderManager::ProviderInfo::DeviceInfo1::dumpState(int fd) {
2224     native_handle_t* handle = native_handle_create(1,0);
2225     handle->data[0] = fd;
2226     const sp<InterfaceT> interface = startDeviceInterface<InterfaceT>();
2227     if (interface == nullptr) {
2228         return DEAD_OBJECT;
2229     }
2230     hardware::Return<Status> s = interface->dumpState(handle);
2231     native_handle_delete(handle);
2232     if (!s.isOk()) {
2233         return INVALID_OPERATION;
2234     }
2235     return mapToStatusT(s);
2236 }
2237 
DeviceInfo3(const std::string & name,const metadata_vendor_id_t tagId,const std::string & id,uint16_t minorVersion,const CameraResourceCost & resourceCost,sp<ProviderInfo> parentProvider,const std::vector<std::string> & publicCameraIds,sp<InterfaceT> interface)2238 CameraProviderManager::ProviderInfo::DeviceInfo3::DeviceInfo3(const std::string& name,
2239         const metadata_vendor_id_t tagId, const std::string &id,
2240         uint16_t minorVersion,
2241         const CameraResourceCost& resourceCost,
2242         sp<ProviderInfo> parentProvider,
2243         const std::vector<std::string>& publicCameraIds,
2244         sp<InterfaceT> interface) :
2245         DeviceInfo(name, tagId, id, hardware::hidl_version{3, minorVersion},
2246                    publicCameraIds, resourceCost, parentProvider) {
2247     // Get camera characteristics and initialize flash unit availability
2248     Status status;
2249     hardware::Return<void> ret;
2250     ret = interface->getCameraCharacteristics([&status, this](Status s,
__anon330ebd181002(Status s, device::V3_2::CameraMetadata metadata) 2251                     device::V3_2::CameraMetadata metadata) {
2252                 status = s;
2253                 if (s == Status::OK) {
2254                     camera_metadata_t *buffer =
2255                             reinterpret_cast<camera_metadata_t*>(metadata.data());
2256                     size_t expectedSize = metadata.size();
2257                     int res = validate_camera_metadata_structure(buffer, &expectedSize);
2258                     if (res == OK || res == CAMERA_METADATA_VALIDATION_SHIFTED) {
2259                         set_camera_metadata_vendor_id(buffer, mProviderTagid);
2260                         mCameraCharacteristics = buffer;
2261                     } else {
2262                         ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2263                         status = Status::INTERNAL_ERROR;
2264                     }
2265                 }
2266             });
2267     if (!ret.isOk()) {
2268         ALOGE("%s: Transaction error getting camera characteristics for device %s"
2269                 " to check for a flash unit: %s", __FUNCTION__, id.c_str(),
2270                 ret.description().c_str());
2271         return;
2272     }
2273     if (status != Status::OK) {
2274         ALOGE("%s: Unable to get camera characteristics for device %s: %s (%d)",
2275                 __FUNCTION__, id.c_str(), CameraProviderManager::statusToString(status), status);
2276         return;
2277     }
2278 
2279     mSystemCameraKind = getSystemCameraKind();
2280 
2281     status_t res = fixupMonochromeTags();
2282     if (OK != res) {
2283         ALOGE("%s: Unable to fix up monochrome tags based for older HAL version: %s (%d)",
2284                 __FUNCTION__, strerror(-res), res);
2285         return;
2286     }
2287     auto stat = addDynamicDepthTags();
2288     if (OK != stat) {
2289         ALOGE("%s: Failed appending dynamic depth tags: %s (%d)", __FUNCTION__, strerror(-stat),
2290                 stat);
2291     }
2292     res = deriveHeicTags();
2293     if (OK != res) {
2294         ALOGE("%s: Unable to derive HEIC tags based on camera and media capabilities: %s (%d)",
2295                 __FUNCTION__, strerror(-res), res);
2296     }
2297     res = addRotateCropTags();
2298     if (OK != res) {
2299         ALOGE("%s: Unable to add default SCALER_ROTATE_AND_CROP tags: %s (%d)", __FUNCTION__,
2300                 strerror(-res), res);
2301     }
2302     res = addPreCorrectionActiveArraySize();
2303     if (OK != res) {
2304         ALOGE("%s: Unable to add PRE_CORRECTION_ACTIVE_ARRAY_SIZE: %s (%d)", __FUNCTION__,
2305                 strerror(-res), res);
2306     }
2307     res = camera3::ZoomRatioMapper::overrideZoomRatioTags(
2308             &mCameraCharacteristics, &mSupportNativeZoomRatio);
2309     if (OK != res) {
2310         ALOGE("%s: Unable to override zoomRatio related tags: %s (%d)",
2311                 __FUNCTION__, strerror(-res), res);
2312     }
2313 
2314     camera_metadata_entry flashAvailable =
2315             mCameraCharacteristics.find(ANDROID_FLASH_INFO_AVAILABLE);
2316     if (flashAvailable.count == 1 &&
2317             flashAvailable.data.u8[0] == ANDROID_FLASH_INFO_AVAILABLE_TRUE) {
2318         mHasFlashUnit = true;
2319     } else {
2320         mHasFlashUnit = false;
2321     }
2322 
2323     queryPhysicalCameraIds();
2324 
2325     // Get physical camera characteristics if applicable
2326     auto castResult = device::V3_5::ICameraDevice::castFrom(interface);
2327     if (!castResult.isOk()) {
2328         ALOGV("%s: Unable to convert ICameraDevice instance to version 3.5", __FUNCTION__);
2329         return;
2330     }
2331     sp<device::V3_5::ICameraDevice> interface_3_5 = castResult;
2332     if (interface_3_5 == nullptr) {
2333         ALOGE("%s: Converted ICameraDevice instance to nullptr", __FUNCTION__);
2334         return;
2335     }
2336 
2337     if (mIsLogicalCamera) {
2338         for (auto& id : mPhysicalIds) {
2339             if (std::find(mPublicCameraIds.begin(), mPublicCameraIds.end(), id) !=
2340                     mPublicCameraIds.end()) {
2341                 continue;
2342             }
2343 
2344             hardware::hidl_string hidlId(id);
2345             ret = interface_3_5->getPhysicalCameraCharacteristics(hidlId,
__anon330ebd181102(Status s, device::V3_2::CameraMetadata metadata) 2346                     [&status, &id, this](Status s, device::V3_2::CameraMetadata metadata) {
2347                 status = s;
2348                 if (s == Status::OK) {
2349                     camera_metadata_t *buffer =
2350                             reinterpret_cast<camera_metadata_t*>(metadata.data());
2351                     size_t expectedSize = metadata.size();
2352                     int res = validate_camera_metadata_structure(buffer, &expectedSize);
2353                     if (res == OK || res == CAMERA_METADATA_VALIDATION_SHIFTED) {
2354                         set_camera_metadata_vendor_id(buffer, mProviderTagid);
2355                         mPhysicalCameraCharacteristics[id] = buffer;
2356                     } else {
2357                         ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2358                         status = Status::INTERNAL_ERROR;
2359                     }
2360                 }
2361             });
2362 
2363             if (!ret.isOk()) {
2364                 ALOGE("%s: Transaction error getting physical camera %s characteristics for %s: %s",
2365                         __FUNCTION__, id.c_str(), id.c_str(), ret.description().c_str());
2366                 return;
2367             }
2368             if (status != Status::OK) {
2369                 ALOGE("%s: Unable to get physical camera %s characteristics for device %s: %s (%d)",
2370                         __FUNCTION__, id.c_str(), mId.c_str(),
2371                         CameraProviderManager::statusToString(status), status);
2372                 return;
2373             }
2374 
2375             res = camera3::ZoomRatioMapper::overrideZoomRatioTags(
2376                     &mPhysicalCameraCharacteristics[id], &mSupportNativeZoomRatio);
2377             if (OK != res) {
2378                 ALOGE("%s: Unable to override zoomRatio related tags: %s (%d)",
2379                         __FUNCTION__, strerror(-res), res);
2380             }
2381         }
2382     }
2383 
2384     if (!kEnableLazyHal) {
2385         // Save HAL reference indefinitely
2386         mSavedInterface = interface;
2387     }
2388 }
2389 
~DeviceInfo3()2390 CameraProviderManager::ProviderInfo::DeviceInfo3::~DeviceInfo3() {}
2391 
setTorchMode(bool enabled)2392 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::setTorchMode(bool enabled) {
2393     return setTorchModeForDevice<InterfaceT>(enabled);
2394 }
2395 
getCameraInfo(hardware::CameraInfo * info) const2396 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::getCameraInfo(
2397         hardware::CameraInfo *info) const {
2398     if (info == nullptr) return BAD_VALUE;
2399 
2400     camera_metadata_ro_entry facing =
2401             mCameraCharacteristics.find(ANDROID_LENS_FACING);
2402     if (facing.count == 1) {
2403         switch (facing.data.u8[0]) {
2404             case ANDROID_LENS_FACING_BACK:
2405                 info->facing = hardware::CAMERA_FACING_BACK;
2406                 break;
2407             case ANDROID_LENS_FACING_EXTERNAL:
2408                 // Map external to front for legacy API
2409             case ANDROID_LENS_FACING_FRONT:
2410                 info->facing = hardware::CAMERA_FACING_FRONT;
2411                 break;
2412         }
2413     } else {
2414         ALOGE("%s: Unable to find android.lens.facing static metadata", __FUNCTION__);
2415         return NAME_NOT_FOUND;
2416     }
2417 
2418     camera_metadata_ro_entry orientation =
2419             mCameraCharacteristics.find(ANDROID_SENSOR_ORIENTATION);
2420     if (orientation.count == 1) {
2421         info->orientation = orientation.data.i32[0];
2422     } else {
2423         ALOGE("%s: Unable to find android.sensor.orientation static metadata", __FUNCTION__);
2424         return NAME_NOT_FOUND;
2425     }
2426 
2427     return OK;
2428 }
isAPI1Compatible() const2429 bool CameraProviderManager::ProviderInfo::DeviceInfo3::isAPI1Compatible() const {
2430     // Do not advertise NIR cameras to API1 camera app.
2431     camera_metadata_ro_entry cfa = mCameraCharacteristics.find(
2432             ANDROID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT);
2433     if (cfa.count == 1 && cfa.data.u8[0] == ANDROID_SENSOR_INFO_COLOR_FILTER_ARRANGEMENT_NIR) {
2434         return false;
2435     }
2436 
2437     bool isBackwardCompatible = false;
2438     camera_metadata_ro_entry_t caps = mCameraCharacteristics.find(
2439             ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
2440     for (size_t i = 0; i < caps.count; i++) {
2441         if (caps.data.u8[i] ==
2442                 ANDROID_REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE) {
2443             isBackwardCompatible = true;
2444             break;
2445         }
2446     }
2447 
2448     return isBackwardCompatible;
2449 }
2450 
dumpState(int fd)2451 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::dumpState(int fd) {
2452     native_handle_t* handle = native_handle_create(1,0);
2453     handle->data[0] = fd;
2454     const sp<InterfaceT> interface = startDeviceInterface<InterfaceT>();
2455     if (interface == nullptr) {
2456         return DEAD_OBJECT;
2457     }
2458     auto ret = interface->dumpState(handle);
2459     native_handle_delete(handle);
2460     if (!ret.isOk()) {
2461         return INVALID_OPERATION;
2462     }
2463     return OK;
2464 }
2465 
getCameraCharacteristics(CameraMetadata * characteristics) const2466 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::getCameraCharacteristics(
2467         CameraMetadata *characteristics) const {
2468     if (characteristics == nullptr) return BAD_VALUE;
2469 
2470     *characteristics = mCameraCharacteristics;
2471     return OK;
2472 }
2473 
getPhysicalCameraCharacteristics(const std::string & physicalCameraId,CameraMetadata * characteristics) const2474 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::getPhysicalCameraCharacteristics(
2475         const std::string& physicalCameraId, CameraMetadata *characteristics) const {
2476     if (characteristics == nullptr) return BAD_VALUE;
2477     if (mPhysicalCameraCharacteristics.find(physicalCameraId) ==
2478             mPhysicalCameraCharacteristics.end()) {
2479         return NAME_NOT_FOUND;
2480     }
2481 
2482     *characteristics = mPhysicalCameraCharacteristics.at(physicalCameraId);
2483     return OK;
2484 }
2485 
isSessionConfigurationSupported(const hardware::camera::device::V3_4::StreamConfiguration & configuration,bool * status)2486 status_t CameraProviderManager::ProviderInfo::DeviceInfo3::isSessionConfigurationSupported(
2487         const hardware::camera::device::V3_4::StreamConfiguration &configuration,
2488         bool *status /*out*/) {
2489 
2490     const sp<CameraProviderManager::ProviderInfo::DeviceInfo3::InterfaceT> interface =
2491             this->startDeviceInterface<CameraProviderManager::ProviderInfo::DeviceInfo3::InterfaceT>();
2492     if (interface == nullptr) {
2493         return DEAD_OBJECT;
2494     }
2495     auto castResult = device::V3_5::ICameraDevice::castFrom(interface);
2496     sp<hardware::camera::device::V3_5::ICameraDevice> interface_3_5 = castResult;
2497     if (interface_3_5 == nullptr) {
2498         return INVALID_OPERATION;
2499     }
2500 
2501     status_t res;
2502     Status callStatus;
2503     auto ret =  interface_3_5->isStreamCombinationSupported(configuration,
2504             [&callStatus, &status] (Status s, bool combStatus) {
2505                 callStatus = s;
2506                 *status = combStatus;
2507             });
2508     if (ret.isOk()) {
2509         switch (callStatus) {
2510             case Status::OK:
2511                 // Expected case, do nothing.
2512                 res = OK;
2513                 break;
2514             case Status::METHOD_NOT_SUPPORTED:
2515                 res = INVALID_OPERATION;
2516                 break;
2517             default:
2518                 ALOGE("%s: Session configuration query failed: %d", __FUNCTION__, callStatus);
2519                 res = UNKNOWN_ERROR;
2520         }
2521     } else {
2522         ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, ret.description().c_str());
2523         res = UNKNOWN_ERROR;
2524     }
2525 
2526     return res;
2527 }
2528 
parseProviderName(const std::string & name,std::string * type,uint32_t * id)2529 status_t CameraProviderManager::ProviderInfo::parseProviderName(const std::string& name,
2530         std::string *type, uint32_t *id) {
2531     // Format must be "<type>/<id>"
2532 #define ERROR_MSG_PREFIX "%s: Invalid provider name '%s'. "       \
2533     "Should match '<type>/<id>' - "
2534 
2535     if (!type || !id) return INVALID_OPERATION;
2536 
2537     std::string::size_type slashIdx = name.find('/');
2538     if (slashIdx == std::string::npos || slashIdx == name.size() - 1) {
2539         ALOGE(ERROR_MSG_PREFIX
2540                 "does not have / separator between type and id",
2541                 __FUNCTION__, name.c_str());
2542         return BAD_VALUE;
2543     }
2544 
2545     std::string typeVal = name.substr(0, slashIdx);
2546 
2547     char *endPtr;
2548     errno = 0;
2549     long idVal = strtol(name.c_str() + slashIdx + 1, &endPtr, 10);
2550     if (errno != 0) {
2551         ALOGE(ERROR_MSG_PREFIX
2552                 "cannot parse provider id as an integer: %s (%d)",
2553                 __FUNCTION__, name.c_str(), strerror(errno), errno);
2554         return BAD_VALUE;
2555     }
2556     if (endPtr != name.c_str() + name.size()) {
2557         ALOGE(ERROR_MSG_PREFIX
2558                 "provider id has unexpected length",
2559                 __FUNCTION__, name.c_str());
2560         return BAD_VALUE;
2561     }
2562     if (idVal < 0) {
2563         ALOGE(ERROR_MSG_PREFIX
2564                 "id is negative: %ld",
2565                 __FUNCTION__, name.c_str(), idVal);
2566         return BAD_VALUE;
2567     }
2568 
2569 #undef ERROR_MSG_PREFIX
2570 
2571     *type = typeVal;
2572     *id = static_cast<uint32_t>(idVal);
2573 
2574     return OK;
2575 }
2576 
generateVendorTagId(const std::string & name)2577 metadata_vendor_id_t CameraProviderManager::ProviderInfo::generateVendorTagId(
2578         const std::string &name) {
2579     metadata_vendor_id_t ret = std::hash<std::string> {} (name);
2580     // CAMERA_METADATA_INVALID_VENDOR_ID is not a valid hash value
2581     if (CAMERA_METADATA_INVALID_VENDOR_ID == ret) {
2582         ret = 0;
2583     }
2584 
2585     return ret;
2586 }
2587 
parseDeviceName(const std::string & name,uint16_t * major,uint16_t * minor,std::string * type,std::string * id)2588 status_t CameraProviderManager::ProviderInfo::parseDeviceName(const std::string& name,
2589         uint16_t *major, uint16_t *minor, std::string *type, std::string *id) {
2590 
2591     // Format must be "device@<major>.<minor>/<type>/<id>"
2592 
2593 #define ERROR_MSG_PREFIX "%s: Invalid device name '%s'. " \
2594     "Should match 'device@<major>.<minor>/<type>/<id>' - "
2595 
2596     if (!major || !minor || !type || !id) return INVALID_OPERATION;
2597 
2598     // Verify starting prefix
2599     const char expectedPrefix[] = "device@";
2600 
2601     if (name.find(expectedPrefix) != 0) {
2602         ALOGE(ERROR_MSG_PREFIX
2603                 "does not start with '%s'",
2604                 __FUNCTION__, name.c_str(), expectedPrefix);
2605         return BAD_VALUE;
2606     }
2607 
2608     // Extract major/minor versions
2609     constexpr std::string::size_type atIdx = sizeof(expectedPrefix) - 2;
2610     std::string::size_type dotIdx = name.find('.', atIdx);
2611     if (dotIdx == std::string::npos) {
2612         ALOGE(ERROR_MSG_PREFIX
2613                 "does not have @<major>. version section",
2614                 __FUNCTION__, name.c_str());
2615         return BAD_VALUE;
2616     }
2617     std::string::size_type typeSlashIdx = name.find('/', dotIdx);
2618     if (typeSlashIdx == std::string::npos) {
2619         ALOGE(ERROR_MSG_PREFIX
2620                 "does not have .<minor>/ version section",
2621                 __FUNCTION__, name.c_str());
2622         return BAD_VALUE;
2623     }
2624 
2625     char *endPtr;
2626     errno = 0;
2627     long majorVal = strtol(name.c_str() + atIdx + 1, &endPtr, 10);
2628     if (errno != 0) {
2629         ALOGE(ERROR_MSG_PREFIX
2630                 "cannot parse major version: %s (%d)",
2631                 __FUNCTION__, name.c_str(), strerror(errno), errno);
2632         return BAD_VALUE;
2633     }
2634     if (endPtr != name.c_str() + dotIdx) {
2635         ALOGE(ERROR_MSG_PREFIX
2636                 "major version has unexpected length",
2637                 __FUNCTION__, name.c_str());
2638         return BAD_VALUE;
2639     }
2640     long minorVal = strtol(name.c_str() + dotIdx + 1, &endPtr, 10);
2641     if (errno != 0) {
2642         ALOGE(ERROR_MSG_PREFIX
2643                 "cannot parse minor version: %s (%d)",
2644                 __FUNCTION__, name.c_str(), strerror(errno), errno);
2645         return BAD_VALUE;
2646     }
2647     if (endPtr != name.c_str() + typeSlashIdx) {
2648         ALOGE(ERROR_MSG_PREFIX
2649                 "minor version has unexpected length",
2650                 __FUNCTION__, name.c_str());
2651         return BAD_VALUE;
2652     }
2653     if (majorVal < 0 || majorVal > UINT16_MAX || minorVal < 0 || minorVal > UINT16_MAX) {
2654         ALOGE(ERROR_MSG_PREFIX
2655                 "major/minor version is out of range of uint16_t: %ld.%ld",
2656                 __FUNCTION__, name.c_str(), majorVal, minorVal);
2657         return BAD_VALUE;
2658     }
2659 
2660     // Extract type and id
2661 
2662     std::string::size_type instanceSlashIdx = name.find('/', typeSlashIdx + 1);
2663     if (instanceSlashIdx == std::string::npos) {
2664         ALOGE(ERROR_MSG_PREFIX
2665                 "does not have /<type>/ component",
2666                 __FUNCTION__, name.c_str());
2667         return BAD_VALUE;
2668     }
2669     std::string typeVal = name.substr(typeSlashIdx + 1, instanceSlashIdx - typeSlashIdx - 1);
2670 
2671     if (instanceSlashIdx == name.size() - 1) {
2672         ALOGE(ERROR_MSG_PREFIX
2673                 "does not have an /<id> component",
2674                 __FUNCTION__, name.c_str());
2675         return BAD_VALUE;
2676     }
2677     std::string idVal = name.substr(instanceSlashIdx + 1);
2678 
2679 #undef ERROR_MSG_PREFIX
2680 
2681     *major = static_cast<uint16_t>(majorVal);
2682     *minor = static_cast<uint16_t>(minorVal);
2683     *type = typeVal;
2684     *id = idVal;
2685 
2686     return OK;
2687 }
2688 
2689 
2690 
~ProviderInfo()2691 CameraProviderManager::ProviderInfo::~ProviderInfo() {
2692     // Destruction of ProviderInfo is only supposed to happen when the respective
2693     // CameraProvider interface dies, so do not unregister callbacks.
2694 
2695 }
2696 
mapToStatusT(const Status & s)2697 status_t CameraProviderManager::mapToStatusT(const Status& s)  {
2698     switch(s) {
2699         case Status::OK:
2700             return OK;
2701         case Status::ILLEGAL_ARGUMENT:
2702             return BAD_VALUE;
2703         case Status::CAMERA_IN_USE:
2704             return -EBUSY;
2705         case Status::MAX_CAMERAS_IN_USE:
2706             return -EUSERS;
2707         case Status::METHOD_NOT_SUPPORTED:
2708             return UNKNOWN_TRANSACTION;
2709         case Status::OPERATION_NOT_SUPPORTED:
2710             return INVALID_OPERATION;
2711         case Status::CAMERA_DISCONNECTED:
2712             return DEAD_OBJECT;
2713         case Status::INTERNAL_ERROR:
2714             return INVALID_OPERATION;
2715     }
2716     ALOGW("Unexpected HAL status code %d", s);
2717     return INVALID_OPERATION;
2718 }
2719 
statusToString(const Status & s)2720 const char* CameraProviderManager::statusToString(const Status& s) {
2721     switch(s) {
2722         case Status::OK:
2723             return "OK";
2724         case Status::ILLEGAL_ARGUMENT:
2725             return "ILLEGAL_ARGUMENT";
2726         case Status::CAMERA_IN_USE:
2727             return "CAMERA_IN_USE";
2728         case Status::MAX_CAMERAS_IN_USE:
2729             return "MAX_CAMERAS_IN_USE";
2730         case Status::METHOD_NOT_SUPPORTED:
2731             return "METHOD_NOT_SUPPORTED";
2732         case Status::OPERATION_NOT_SUPPORTED:
2733             return "OPERATION_NOT_SUPPORTED";
2734         case Status::CAMERA_DISCONNECTED:
2735             return "CAMERA_DISCONNECTED";
2736         case Status::INTERNAL_ERROR:
2737             return "INTERNAL_ERROR";
2738     }
2739     ALOGW("Unexpected HAL status code %d", s);
2740     return "UNKNOWN_ERROR";
2741 }
2742 
deviceStatusToString(const CameraDeviceStatus & s)2743 const char* CameraProviderManager::deviceStatusToString(const CameraDeviceStatus& s) {
2744     switch(s) {
2745         case CameraDeviceStatus::NOT_PRESENT:
2746             return "NOT_PRESENT";
2747         case CameraDeviceStatus::PRESENT:
2748             return "PRESENT";
2749         case CameraDeviceStatus::ENUMERATING:
2750             return "ENUMERATING";
2751     }
2752     ALOGW("Unexpected HAL device status code %d", s);
2753     return "UNKNOWN_STATUS";
2754 }
2755 
torchStatusToString(const TorchModeStatus & s)2756 const char* CameraProviderManager::torchStatusToString(const TorchModeStatus& s) {
2757     switch(s) {
2758         case TorchModeStatus::NOT_AVAILABLE:
2759             return "NOT_AVAILABLE";
2760         case TorchModeStatus::AVAILABLE_OFF:
2761             return "AVAILABLE_OFF";
2762         case TorchModeStatus::AVAILABLE_ON:
2763             return "AVAILABLE_ON";
2764     }
2765     ALOGW("Unexpected HAL torch mode status code %d", s);
2766     return "UNKNOWN_STATUS";
2767 }
2768 
2769 
createDescriptorFromHidl(const hardware::hidl_vec<common::V1_0::VendorTagSection> & vts,sp<VendorTagDescriptor> & descriptor)2770 status_t HidlVendorTagDescriptor::createDescriptorFromHidl(
2771         const hardware::hidl_vec<common::V1_0::VendorTagSection>& vts,
2772         /*out*/
2773         sp<VendorTagDescriptor>& descriptor) {
2774 
2775     int tagCount = 0;
2776 
2777     for (size_t s = 0; s < vts.size(); s++) {
2778         tagCount += vts[s].tags.size();
2779     }
2780 
2781     if (tagCount < 0 || tagCount > INT32_MAX) {
2782         ALOGE("%s: tag count %d from vendor tag sections is invalid.", __FUNCTION__, tagCount);
2783         return BAD_VALUE;
2784     }
2785 
2786     Vector<uint32_t> tagArray;
2787     LOG_ALWAYS_FATAL_IF(tagArray.resize(tagCount) != tagCount,
2788             "%s: too many (%u) vendor tags defined.", __FUNCTION__, tagCount);
2789 
2790 
2791     sp<HidlVendorTagDescriptor> desc = new HidlVendorTagDescriptor();
2792     desc->mTagCount = tagCount;
2793 
2794     SortedVector<String8> sections;
2795     KeyedVector<uint32_t, String8> tagToSectionMap;
2796 
2797     int idx = 0;
2798     for (size_t s = 0; s < vts.size(); s++) {
2799         const common::V1_0::VendorTagSection& section = vts[s];
2800         const char *sectionName = section.sectionName.c_str();
2801         if (sectionName == NULL) {
2802             ALOGE("%s: no section name defined for vendor tag section %zu.", __FUNCTION__, s);
2803             return BAD_VALUE;
2804         }
2805         String8 sectionString(sectionName);
2806         sections.add(sectionString);
2807 
2808         for (size_t j = 0; j < section.tags.size(); j++) {
2809             uint32_t tag = section.tags[j].tagId;
2810             if (tag < CAMERA_METADATA_VENDOR_TAG_BOUNDARY) {
2811                 ALOGE("%s: vendor tag %d not in vendor tag section.", __FUNCTION__, tag);
2812                 return BAD_VALUE;
2813             }
2814 
2815             tagArray.editItemAt(idx++) = section.tags[j].tagId;
2816 
2817             const char *tagName = section.tags[j].tagName.c_str();
2818             if (tagName == NULL) {
2819                 ALOGE("%s: no tag name defined for vendor tag %d.", __FUNCTION__, tag);
2820                 return BAD_VALUE;
2821             }
2822             desc->mTagToNameMap.add(tag, String8(tagName));
2823             tagToSectionMap.add(tag, sectionString);
2824 
2825             int tagType = (int) section.tags[j].tagType;
2826             if (tagType < 0 || tagType >= NUM_TYPES) {
2827                 ALOGE("%s: tag type %d from vendor ops does not exist.", __FUNCTION__, tagType);
2828                 return BAD_VALUE;
2829             }
2830             desc->mTagToTypeMap.add(tag, tagType);
2831         }
2832     }
2833 
2834     desc->mSections = sections;
2835 
2836     for (size_t i = 0; i < tagArray.size(); ++i) {
2837         uint32_t tag = tagArray[i];
2838         String8 sectionString = tagToSectionMap.valueFor(tag);
2839 
2840         // Set up tag to section index map
2841         ssize_t index = sections.indexOf(sectionString);
2842         LOG_ALWAYS_FATAL_IF(index < 0, "index %zd must be non-negative", index);
2843         desc->mTagToSectionMap.add(tag, static_cast<uint32_t>(index));
2844 
2845         // Set up reverse mapping
2846         ssize_t reverseIndex = -1;
2847         if ((reverseIndex = desc->mReverseMapping.indexOfKey(sectionString)) < 0) {
2848             KeyedVector<String8, uint32_t>* nameMapper = new KeyedVector<String8, uint32_t>();
2849             reverseIndex = desc->mReverseMapping.add(sectionString, nameMapper);
2850         }
2851         desc->mReverseMapping[reverseIndex]->add(desc->mTagToNameMap.valueFor(tag), tag);
2852     }
2853 
2854     descriptor = std::move(desc);
2855     return OK;
2856 }
2857 
2858 // Expects to have mInterfaceMutex locked
2859 std::vector<std::unordered_set<std::string>>
getConcurrentCameraIds() const2860 CameraProviderManager::getConcurrentCameraIds() const {
2861     std::vector<std::unordered_set<std::string>> deviceIdCombinations;
2862     std::lock_guard<std::mutex> lock(mInterfaceMutex);
2863     for (auto &provider : mProviders) {
2864         for (auto &combinations : provider->getConcurrentCameraIdCombinations()) {
2865             deviceIdCombinations.push_back(combinations);
2866         }
2867     }
2868     return deviceIdCombinations;
2869 }
2870 
convertToHALStreamCombinationAndCameraIdsLocked(const std::vector<CameraIdAndSessionConfiguration> & cameraIdsAndSessionConfigs,hardware::hidl_vec<CameraIdAndStreamCombination> * halCameraIdsAndStreamCombinations,bool * earlyExit)2871 status_t CameraProviderManager::convertToHALStreamCombinationAndCameraIdsLocked(
2872         const std::vector<CameraIdAndSessionConfiguration> &cameraIdsAndSessionConfigs,
2873         hardware::hidl_vec<CameraIdAndStreamCombination> *halCameraIdsAndStreamCombinations,
2874         bool *earlyExit) {
2875     binder::Status bStatus = binder::Status::ok();
2876     std::vector<CameraIdAndStreamCombination> halCameraIdsAndStreamsV;
2877     bool shouldExit = false;
2878     status_t res = OK;
2879     for (auto &cameraIdAndSessionConfig : cameraIdsAndSessionConfigs) {
2880         hardware::camera::device::V3_4::StreamConfiguration streamConfiguration;
2881         CameraMetadata deviceInfo;
2882         res = getCameraCharacteristicsLocked(cameraIdAndSessionConfig.mCameraId, &deviceInfo);
2883         if (res != OK) {
2884             return res;
2885         }
2886         metadataGetter getMetadata =
2887                 [this](const String8 &id) {
2888                     CameraMetadata physicalDeviceInfo;
2889                     getCameraCharacteristicsLocked(id.string(), &physicalDeviceInfo);
2890                     return physicalDeviceInfo;
2891                 };
2892         std::vector<std::string> physicalCameraIds;
2893         isLogicalCameraLocked(cameraIdAndSessionConfig.mCameraId, &physicalCameraIds);
2894         bStatus =
2895             SessionConfigurationUtils::convertToHALStreamCombination(
2896                     cameraIdAndSessionConfig.mSessionConfiguration,
2897                     String8(cameraIdAndSessionConfig.mCameraId.c_str()), deviceInfo, getMetadata,
2898                     physicalCameraIds, streamConfiguration, &shouldExit);
2899         if (!bStatus.isOk()) {
2900             ALOGE("%s: convertToHALStreamCombination failed", __FUNCTION__);
2901             return INVALID_OPERATION;
2902         }
2903         if (shouldExit) {
2904             *earlyExit = true;
2905             return OK;
2906         }
2907         CameraIdAndStreamCombination halCameraIdAndStream;
2908         halCameraIdAndStream.cameraId = cameraIdAndSessionConfig.mCameraId;
2909         halCameraIdAndStream.streamConfiguration = streamConfiguration;
2910         halCameraIdsAndStreamsV.push_back(halCameraIdAndStream);
2911     }
2912     *halCameraIdsAndStreamCombinations = halCameraIdsAndStreamsV;
2913     return OK;
2914 }
2915 
2916 // Checks if the containing vector of sets has any set that contains all of the
2917 // camera ids in cameraIdsAndSessionConfigs.
checkIfSetContainsAll(const std::vector<CameraIdAndSessionConfiguration> & cameraIdsAndSessionConfigs,const std::vector<std::unordered_set<std::string>> & containingSets)2918 static bool checkIfSetContainsAll(
2919         const std::vector<CameraIdAndSessionConfiguration> &cameraIdsAndSessionConfigs,
2920         const std::vector<std::unordered_set<std::string>> &containingSets) {
2921     for (auto &containingSet : containingSets) {
2922         bool didHaveAll = true;
2923         for (auto &cameraIdAndSessionConfig : cameraIdsAndSessionConfigs) {
2924             if (containingSet.find(cameraIdAndSessionConfig.mCameraId) == containingSet.end()) {
2925                 // a camera id doesn't belong to this set, keep looking in other
2926                 // sets
2927                 didHaveAll = false;
2928                 break;
2929             }
2930         }
2931         if (didHaveAll) {
2932             // found a set that has all camera ids, lets return;
2933             return true;
2934         }
2935     }
2936     return false;
2937 }
2938 
isConcurrentSessionConfigurationSupported(const std::vector<CameraIdAndSessionConfiguration> & cameraIdsAndSessionConfigs,bool * isSupported)2939 status_t CameraProviderManager::isConcurrentSessionConfigurationSupported(
2940         const std::vector<CameraIdAndSessionConfiguration> &cameraIdsAndSessionConfigs,
2941         bool *isSupported) {
2942     std::lock_guard<std::mutex> lock(mInterfaceMutex);
2943     // Check if all the devices are a subset of devices advertised by the
2944     // same provider through getConcurrentStreamingCameraIds()
2945     // TODO: we should also do a findDeviceInfoLocked here ?
2946     for (auto &provider : mProviders) {
2947         if (checkIfSetContainsAll(cameraIdsAndSessionConfigs,
2948                 provider->getConcurrentCameraIdCombinations())) {
2949             // For each camera device in cameraIdsAndSessionConfigs collect
2950             // the streamConfigs and create the HAL
2951             // CameraIdAndStreamCombination, exit early if needed
2952             hardware::hidl_vec<CameraIdAndStreamCombination> halCameraIdsAndStreamCombinations;
2953             bool knowUnsupported = false;
2954             status_t res = convertToHALStreamCombinationAndCameraIdsLocked(
2955                     cameraIdsAndSessionConfigs, &halCameraIdsAndStreamCombinations,
2956                     &knowUnsupported);
2957             if (res != OK) {
2958                 ALOGE("%s unable to convert session configurations provided to HAL stream"
2959                       "combinations", __FUNCTION__);
2960                 return res;
2961             }
2962             if (knowUnsupported) {
2963                 // We got to know the streams aren't valid before doing the HAL
2964                 // call itself.
2965                 *isSupported = false;
2966                 return OK;
2967             }
2968             return provider->isConcurrentSessionConfigurationSupported(
2969                     halCameraIdsAndStreamCombinations, isSupported);
2970         }
2971     }
2972     *isSupported = false;
2973     //The set of camera devices were not found
2974     return INVALID_OPERATION;
2975 }
2976 
getCameraCharacteristicsLocked(const std::string & id,CameraMetadata * characteristics) const2977 status_t CameraProviderManager::getCameraCharacteristicsLocked(const std::string &id,
2978         CameraMetadata* characteristics) const {
2979     auto deviceInfo = findDeviceInfoLocked(id, /*minVersion*/ {3,0}, /*maxVersion*/ {5,0});
2980     if (deviceInfo != nullptr) {
2981         return deviceInfo->getCameraCharacteristics(characteristics);
2982     }
2983 
2984     // Find hidden physical camera characteristics
2985     for (auto& provider : mProviders) {
2986         for (auto& deviceInfo : provider->mDevices) {
2987             status_t res = deviceInfo->getPhysicalCameraCharacteristics(id, characteristics);
2988             if (res != NAME_NOT_FOUND) return res;
2989         }
2990     }
2991 
2992     return NAME_NOT_FOUND;
2993 }
2994 
filterLogicalCameraIdsLocked(std::vector<std::string> & deviceIds) const2995 void CameraProviderManager::filterLogicalCameraIdsLocked(
2996         std::vector<std::string>& deviceIds) const
2997 {
2998     // Map between camera facing and camera IDs related to logical camera.
2999     std::map<int, std::unordered_set<std::string>> idCombos;
3000 
3001     // Collect all logical and its underlying physical camera IDs for each
3002     // facing.
3003     for (auto& deviceId : deviceIds) {
3004         auto deviceInfo = findDeviceInfoLocked(deviceId);
3005         if (deviceInfo == nullptr) continue;
3006 
3007         if (!deviceInfo->mIsLogicalCamera) {
3008             continue;
3009         }
3010 
3011         // combo contains the ids of a logical camera and its physical cameras
3012         std::vector<std::string> combo = deviceInfo->mPhysicalIds;
3013         combo.push_back(deviceId);
3014 
3015         hardware::CameraInfo info;
3016         status_t res = deviceInfo->getCameraInfo(&info);
3017         if (res != OK) {
3018             ALOGE("%s: Error reading camera info: %s (%d)", __FUNCTION__, strerror(-res), res);
3019             continue;
3020         }
3021         idCombos[info.facing].insert(combo.begin(), combo.end());
3022     }
3023 
3024     // Only expose one camera ID per facing for all logical and underlying
3025     // physical camera IDs.
3026     for (auto& r : idCombos) {
3027         auto& removedIds = r.second;
3028         for (auto& id : deviceIds) {
3029             auto foundId = std::find(removedIds.begin(), removedIds.end(), id);
3030             if (foundId == removedIds.end()) {
3031                 continue;
3032             }
3033 
3034             removedIds.erase(foundId);
3035             break;
3036         }
3037         deviceIds.erase(std::remove_if(deviceIds.begin(), deviceIds.end(),
3038                 [&removedIds](const std::string& s) {
3039                 return removedIds.find(s) != removedIds.end();}),
3040                 deviceIds.end());
3041     }
3042 }
3043 
3044 } // namespace android
3045