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