xref: /aosp_15_r20/frameworks/av/services/camera/libcameraservice/aidl/AidlCameraService.cpp (revision ec779b8e0859a360c3d303172224686826e6e0e1)
1 /*
2  * Copyright (C) 2022 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 "AidlCameraService"
18 
19 #include "AidlCameraService.h"
20 #include <aidl/AidlCameraDeviceCallbacks.h>
21 #include <aidl/AidlCameraDeviceUser.h>
22 #include <aidl/AidlCameraServiceListener.h>
23 #include <aidl/AidlUtils.h>
24 #include <aidl/android/frameworks/cameraservice/common/CameraMetadataType.h>
25 #include <android-base/properties.h>
26 #include <android/binder_ibinder.h>
27 #include <android/binder_manager.h>
28 #include <binder/Status.h>
29 #include <camera/CameraUtils.h>
30 #include <hidl/HidlTransportSupport.h>
31 #include <utils/AttributionAndPermissionUtils.h>
32 #include <utils/Utils.h>
33 #include <com_android_internal_camera_flags.h>
34 
35 namespace flags = com::android::internal::camera::flags;
36 
37 namespace android::frameworks::cameraservice::service::implementation {
38 
39 using ::android::frameworks::cameraservice::device::implementation::AidlCameraDeviceCallbacks;
40 using ::android::frameworks::cameraservice::device::implementation::AidlCameraDeviceUser;
41 using ::android::hardware::cameraservice::utils::conversion::aidl::areBindersEqual;
42 using ::android::hardware::cameraservice::utils::conversion::aidl::cloneToAidl;
43 using ::android::hardware::cameraservice::utils::conversion::aidl::convertToAidl;
44 using ::android::hardware::cameraservice::utils::conversion::aidl::filterVndkKeys;
45 using hardware::BnCameraService::ROTATION_OVERRIDE_NONE;
46 using ::ndk::ScopedAStatus;
47 
48 // VNDK classes
49 using SCameraMetadataType = ::aidl::android::frameworks::cameraservice::common::CameraMetadataType;
50 using SVendorTag = ::aidl::android::frameworks::cameraservice::common::VendorTag;
51 using SVendorTagSection = ::aidl::android::frameworks::cameraservice::common::VendorTagSection;
52 // NDK classes
53 using UICameraService = ::android::hardware::ICameraService;
54 using UStatus = ::android::binder::Status;
55 
56 namespace {
fromSStatus(const SStatus & s)57 inline ScopedAStatus fromSStatus(const SStatus& s) {
58     return s == SStatus::NO_ERROR ? ScopedAStatus::ok()
59                                   : ScopedAStatus::fromServiceSpecificError(
60                                             static_cast<int32_t>(s));
61 }
fromUStatus(const UStatus & s)62 inline ScopedAStatus fromUStatus(const UStatus& s) {
63     return s.isOk() ? ScopedAStatus::ok() : fromSStatus(convertToAidl(s));
64 }
65 } // anonymous namespace
66 
67 std::shared_ptr<AidlCameraService> kCameraService;
68 
registerService(::android::CameraService * cameraService)69 bool AidlCameraService::registerService(::android::CameraService* cameraService) {
70     kCameraService = SharedRefBase::make<AidlCameraService>(cameraService);
71     std::string serviceName = SBnCameraService::descriptor;
72     serviceName += "/default";
73     bool isDeclared = AServiceManager_isDeclared(serviceName.c_str());
74     if (!isDeclared) {
75         ALOGI("%s: AIDL vndk not declared.", __FUNCTION__);
76         return false;
77     }
78 
79     binder_exception_t registered = AServiceManager_addService(
80             kCameraService->asBinder().get(), serviceName.c_str());
81     ALOGE_IF(registered != EX_NONE,
82              "%s: AIDL VNDK declared, but failed to register service: %d",
83              __FUNCTION__, registered);
84     return registered == EX_NONE;
85 }
86 
AidlCameraService(::android::CameraService * cameraService)87 AidlCameraService::AidlCameraService(::android::CameraService* cameraService):
88       mCameraService(cameraService) {
89     mVndkVersion = getVNDKVersionFromProp(__ANDROID_API_FUTURE__);
90 }
getCameraCharacteristics(const std::string & in_cameraId,SCameraMetadata * _aidl_return)91 ScopedAStatus AidlCameraService::getCameraCharacteristics(const std::string& in_cameraId,
92                                                           SCameraMetadata* _aidl_return) {
93     if (_aidl_return == nullptr) { return fromSStatus(SStatus::ILLEGAL_ARGUMENT); }
94 
95     ::android::CameraMetadata cameraMetadata;
96     AttributionSourceState clientAttribution =
97             AttributionAndPermissionUtils::buildAttributionSource(
98                     hardware::ICameraService::USE_CALLING_PID,
99                     hardware::ICameraService::USE_CALLING_UID,
100                     kDefaultDeviceId);
101     UStatus ret = mCameraService->getCameraCharacteristics(in_cameraId,
102                                                            mVndkVersion,
103                                                            ROTATION_OVERRIDE_NONE,
104                                                            clientAttribution,
105                                                            /* devicePolicy= */ 0,
106                                                            &cameraMetadata);
107     if (!ret.isOk()) {
108         if (ret.exceptionCode() != EX_SERVICE_SPECIFIC) {
109             ALOGE("%s: Transaction error when getting camera characteristics"
110                   " from camera service: %d.",
111                   __FUNCTION__ , ret.exceptionCode());
112             return fromUStatus(ret);
113         }
114         switch (ret.serviceSpecificErrorCode()) {
115             case UICameraService::ERROR_ILLEGAL_ARGUMENT:
116                 ALOGE("%s: Camera ID %s does not exist!", __FUNCTION__, in_cameraId.c_str());
117                 return fromSStatus(SStatus::ILLEGAL_ARGUMENT);
118             default:
119                 ALOGE("Get camera characteristics from camera service failed: %s",
120                       ret.toString8().c_str());
121                 return fromUStatus(ret);
122         }
123     }
124 
125     if (filterVndkKeys(mVndkVersion, cameraMetadata) != OK) {
126          ALOGE("%s: Unable to filter vndk metadata keys for version %d",
127               __FUNCTION__, mVndkVersion);
128          return fromSStatus(SStatus::UNKNOWN_ERROR);
129     }
130 
131     const camera_metadata_t* rawMetadata = cameraMetadata.getAndLock();
132     cloneToAidl(rawMetadata, _aidl_return);
133     cameraMetadata.unlock(rawMetadata);
134 
135     return ScopedAStatus::ok();
136 }
137 
connectDevice(const std::shared_ptr<SICameraDeviceCallback> & in_callback,const std::string & in_cameraId,std::shared_ptr<SICameraDeviceUser> * _aidl_return)138 ndk::ScopedAStatus AidlCameraService::connectDevice(
139         const std::shared_ptr<SICameraDeviceCallback>& in_callback,
140         const std::string& in_cameraId,
141         std::shared_ptr<SICameraDeviceUser>* _aidl_return) {
142     return connectDeviceImpl(in_callback, in_cameraId, /*sharedMode*/false, _aidl_return);
143 }
144 
connectDeviceV2(const std::shared_ptr<SICameraDeviceCallback> & in_callback,const std::string & in_cameraId,bool sharedMode,std::shared_ptr<SICameraDeviceUser> * _aidl_return)145 ndk::ScopedAStatus AidlCameraService::connectDeviceV2(
146         const std::shared_ptr<SICameraDeviceCallback>& in_callback,
147         const std::string& in_cameraId, bool sharedMode,
148         std::shared_ptr<SICameraDeviceUser>* _aidl_return) {
149       if (!flags::camera_multi_client()) {
150           return fromSStatus(SStatus::INVALID_OPERATION);
151       }
152       return connectDeviceImpl(in_callback, in_cameraId, sharedMode, _aidl_return);
153 }
154 
connectDeviceImpl(const std::shared_ptr<SICameraDeviceCallback> & in_callback,const std::string & in_cameraId,bool sharedMode,std::shared_ptr<SICameraDeviceUser> * _aidl_return)155 ndk::ScopedAStatus AidlCameraService::connectDeviceImpl(
156         const std::shared_ptr<SICameraDeviceCallback>& in_callback,
157         const std::string& in_cameraId, bool sharedMode,
158         std::shared_ptr<SICameraDeviceUser>* _aidl_return) {
159     // Here, we first get NDK ICameraDeviceUser from mCameraService, then save
160     // that interface in the newly created AidlCameraDeviceUser impl class.
161     if (mCameraService == nullptr) {
162         return fromSStatus(SStatus::UNKNOWN_ERROR);
163     }
164     sp<hardware::camera2::ICameraDeviceUser> unstableDevice = nullptr;
165     // Create a hardware::camera2::ICameraDeviceCallback object which internally
166     // calls callback functions passed through hCallback.
167     sp<AidlCameraDeviceCallbacks> hybridCallbacks = new AidlCameraDeviceCallbacks(in_callback);
168     if (!hybridCallbacks->initializeLooper(mVndkVersion)) {
169         ALOGE("Unable to handle callbacks on device, cannot connect");
170         return fromSStatus(SStatus::UNKNOWN_ERROR);
171     }
172     sp<hardware::camera2::ICameraDeviceCallbacks> callbacks = hybridCallbacks;
173     AttributionSourceState clientAttribution =
174             AttributionAndPermissionUtils::buildAttributionSource(
175                     hardware::ICameraService::USE_CALLING_PID,
176                     hardware::ICameraService::USE_CALLING_UID,
177                     kDefaultDeviceId);
178     clientAttribution.packageName = "";
179     clientAttribution.attributionTag = std::nullopt;
180     binder::Status serviceRet = mCameraService->connectDeviceVendor(
181             callbacks,
182             in_cameraId,
183             /* scoreOffset= */ 0,
184             /* targetSdkVersion= */ __ANDROID_API_FUTURE__,
185             ROTATION_OVERRIDE_NONE,
186             clientAttribution,
187             /* devicePolicy= */ 0,
188             sharedMode,
189             &unstableDevice);
190     if (!serviceRet.isOk()) {
191         ALOGE("%s: Unable to connect to camera device: %s", __FUNCTION__,
192               serviceRet.toString8().c_str());
193         return fromUStatus(serviceRet);
194     }
195 
196     // Now we create a AidlCameraDeviceUser class, store the unstableDevice in it,
197     // and return that back. All calls on that interface will be forwarded to
198     // the NDK AIDL interface.
199     std::shared_ptr<AidlCameraDeviceUser> stableDevice =
200             ndk::SharedRefBase::make<AidlCameraDeviceUser>(unstableDevice);
201     if (!stableDevice->initStatus()) {
202         ALOGE("%s: Unable to initialize camera device AIDL wrapper", __FUNCTION__);
203         return fromSStatus(SStatus::UNKNOWN_ERROR);
204     }
205     hybridCallbacks->setCaptureResultMetadataQueue(
206             stableDevice->getCaptureResultMetadataQueue());
207     *_aidl_return = stableDevice;
208     return ScopedAStatus::ok();
209 }
addToListenerCacheLocked(std::shared_ptr<SICameraServiceListener> stableCsListener,sp<UICameraServiceListener> csListener)210 void AidlCameraService::addToListenerCacheLocked(
211         std::shared_ptr<SICameraServiceListener> stableCsListener,
212         sp<UICameraServiceListener> csListener) {
213     mListeners.emplace_back(std::make_pair(stableCsListener, csListener));
214 }
searchListenerCacheLocked(const std::shared_ptr<SICameraServiceListener> & listener,bool removeIfFound)215 sp<UICameraServiceListener> AidlCameraService::searchListenerCacheLocked(
216         const std::shared_ptr<SICameraServiceListener>& listener, bool removeIfFound) {
217     // Go through the mListeners list and compare the listener with the VNDK AIDL
218     // listener registered.
219     if (listener == nullptr) {
220         return nullptr;
221     }
222 
223     auto it = mListeners.begin();
224     sp<UICameraServiceListener> csListener = nullptr;
225     for (;it != mListeners.end(); it++) {
226         if (areBindersEqual(listener->asBinder(), it->first->asBinder())) {
227             break;
228         }
229     }
230     if (it != mListeners.end()) {
231         csListener = it->second;
232         if (removeIfFound) {
233             mListeners.erase(it);
234         }
235     }
236     return csListener;
237 }
addListener(const std::shared_ptr<SICameraServiceListener> & in_listener,std::vector<SCameraStatusAndId> * _aidl_return)238 ndk::ScopedAStatus AidlCameraService::addListener(
239         const std::shared_ptr<SICameraServiceListener>& in_listener,
240         std::vector<SCameraStatusAndId>* _aidl_return) {
241     std::vector<hardware::CameraStatus> cameraStatusAndIds{};
242     SStatus status = addListenerInternal(
243             in_listener, &cameraStatusAndIds);
244     if (status != SStatus::NO_ERROR) {
245         return fromSStatus(status);
246     }
247 
248     // Convert cameraStatusAndIds to VNDK AIDL
249     convertToAidl(cameraStatusAndIds, _aidl_return);
250     return ScopedAStatus::ok();
251 }
addListenerInternal(const std::shared_ptr<SICameraServiceListener> & listener,std::vector<hardware::CameraStatus> * cameraStatusAndIds)252 SStatus AidlCameraService::addListenerInternal(
253         const std::shared_ptr<SICameraServiceListener>& listener,
254         std::vector<hardware::CameraStatus>* cameraStatusAndIds) {
255     if (mCameraService == nullptr) {
256         return SStatus::UNKNOWN_ERROR;
257     }
258     if (listener == nullptr || cameraStatusAndIds == nullptr) {
259         ALOGE("%s listener and cameraStatusAndIds must not be NULL", __FUNCTION__);
260         return SStatus::ILLEGAL_ARGUMENT;
261     }
262     sp<UICameraServiceListener> csListener = nullptr;
263     // Check the cache for previously registered callbacks
264     {
265         Mutex::Autolock l(mListenerListLock);
266         csListener = searchListenerCacheLocked(listener);
267         if (csListener == nullptr) {
268             // Wrap a listener with AidlCameraServiceListener and pass it to
269             // CameraService.
270             csListener = sp<AidlCameraServiceListener>::make(listener);
271             // Add to cache
272             addToListenerCacheLocked(listener, csListener);
273         } else {
274             ALOGE("%s: Trying to add a listener %p already registered",
275                   __FUNCTION__, listener.get());
276             return SStatus::ILLEGAL_ARGUMENT;
277         }
278     }
279     binder::Status serviceRet =
280             mCameraService->addListenerHelper(csListener, cameraStatusAndIds, true);
281     if (!serviceRet.isOk()) {
282         ALOGE("%s: Unable to add camera device status listener", __FUNCTION__);
283         return convertToAidl(serviceRet);
284     }
285 
286     cameraStatusAndIds->erase(std::remove_if(cameraStatusAndIds->begin(),
287                                              cameraStatusAndIds->end(),
288             [this](const hardware::CameraStatus& s) {
289                 bool supportsHAL3 = false;
290                 binder::Status sRet =
291                             mCameraService->supportsCameraApi(s.cameraId,
292                                     UICameraService::API_VERSION_2, &supportsHAL3);
293                 return !sRet.isOk() || !supportsHAL3;
294             }), cameraStatusAndIds->end());
295 
296     return SStatus::NO_ERROR;
297 }
removeListener(const std::shared_ptr<SICameraServiceListener> & in_listener)298 ndk::ScopedAStatus AidlCameraService::removeListener(
299         const std::shared_ptr<SICameraServiceListener>& in_listener) {
300     if (in_listener == nullptr) {
301         ALOGE("%s listener must not be NULL", __FUNCTION__);
302         return fromSStatus(SStatus::ILLEGAL_ARGUMENT);
303     }
304     sp<UICameraServiceListener> csListener = nullptr;
305     {
306         Mutex::Autolock l(mListenerListLock);
307         csListener = searchListenerCacheLocked(in_listener, /*removeIfFound*/true);
308     }
309     if (csListener != nullptr) {
310           mCameraService->removeListener(csListener);
311     } else {
312         ALOGE("%s Removing unregistered listener %p", __FUNCTION__, in_listener.get());
313         return fromSStatus(SStatus::ILLEGAL_ARGUMENT);
314     }
315     return ScopedAStatus::ok();
316 }
getCameraVendorTagSections(std::vector<SProviderIdAndVendorTagSections> * _aidl_return)317 ndk::ScopedAStatus AidlCameraService::getCameraVendorTagSections(
318         std::vector<SProviderIdAndVendorTagSections>* _aidl_return) {
319     sp<VendorTagDescriptorCache> gCache = VendorTagDescriptorCache::getGlobalVendorTagCache();
320     if (gCache == nullptr) {
321         return fromSStatus(SStatus::UNKNOWN_ERROR);
322     }
323 
324     const std::unordered_map<metadata_vendor_id_t, sp<android::VendorTagDescriptor>>
325             &vendorIdsAndTagDescs = gCache->getVendorIdsAndTagDescriptors();
326     if (vendorIdsAndTagDescs.empty()) {
327         return fromSStatus(SStatus::UNKNOWN_ERROR);
328     }
329 
330     std::vector<SProviderIdAndVendorTagSections>& tagIdAndVendorTagSections = *_aidl_return;
331     tagIdAndVendorTagSections.resize(vendorIdsAndTagDescs.size());
332     size_t j = 0;
333     for (auto &vendorIdAndTagDescs : vendorIdsAndTagDescs) {
334         std::vector<SVendorTagSection> vendorTagSections;
335         sp<VendorTagDescriptor> desc = vendorIdAndTagDescs.second;
336         const SortedVector<String8>* sectionNames = desc->getAllSectionNames();
337         size_t numSections = sectionNames->size();
338         std::vector<std::vector<SVendorTag>> tagsBySection(numSections);
339         int tagCount = desc->getTagCount();
340         if (tagCount <= 0) {
341             continue;
342         }
343         std::vector<uint32_t> tags(tagCount);
344         desc->getTagArray(tags.data());
345         for (int i = 0; i < tagCount; i++) {
346             SVendorTag vt;
347             vt.tagId = tags[i];
348             vt.tagName = desc->getTagName(tags[i]);
349             vt.tagType = (SCameraMetadataType) desc->getTagType(tags[i]);
350             ssize_t sectionIdx = desc->getSectionIndex(tags[i]);
351             tagsBySection[sectionIdx].push_back(vt);
352         }
353         vendorTagSections.resize(numSections);
354         for (size_t s = 0; s < numSections; s++) {
355             vendorTagSections[s].sectionName = (*sectionNames)[s].c_str();
356             vendorTagSections[s].tags = tagsBySection[s];
357         }
358         SProviderIdAndVendorTagSections & prvdrIdAndVendorTagSection =
359                 tagIdAndVendorTagSections[j];
360         prvdrIdAndVendorTagSection.providerId = vendorIdAndTagDescs.first;
361         prvdrIdAndVendorTagSection.vendorTagSections = std::move(vendorTagSections);
362         j++;
363     }
364     return ScopedAStatus::ok();
365 }
366 
367 } // namespace android::frameworks::cameraservice::service::implementation
368