• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "Enumerator.h"
18 
19 #include "AidlEnumerator.h"
20 #include "HalDisplay.h"
21 #include "utils/include/Utils.h"
22 
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/stringprintf.h>
26 #include <android-base/strings.h>
27 #include <android/binder_manager.h>
28 #include <android/hardware/automotive/evs/1.1/IEvsEnumerator.h>
29 #include <cutils/android_filesystem_config.h>
30 
31 namespace {
32 
33 namespace hidlevs = ::android::hardware::automotive::evs;
34 
35 using ::aidl::android::hardware::automotive::evs::CameraDesc;
36 using ::aidl::android::hardware::automotive::evs::DisplayState;
37 using ::aidl::android::hardware::automotive::evs::EvsResult;
38 using ::aidl::android::hardware::automotive::evs::IEvsCamera;
39 using ::aidl::android::hardware::automotive::evs::IEvsDisplay;
40 using ::aidl::android::hardware::automotive::evs::IEvsEnumerator;
41 using ::aidl::android::hardware::automotive::evs::IEvsEnumeratorStatusCallback;
42 using ::aidl::android::hardware::automotive::evs::IEvsUltrasonicsArray;
43 using ::aidl::android::hardware::automotive::evs::Stream;
44 using ::aidl::android::hardware::automotive::evs::UltrasonicsArrayDesc;
45 using ::android::base::EqualsIgnoreCase;
46 using ::android::base::StringAppendF;
47 using ::android::base::StringPrintf;
48 using ::android::base::WriteStringToFd;
49 using ::ndk::ScopedAStatus;
50 
51 // For status dump function
52 constexpr const char kSingleIndent[] = "\t";
53 constexpr const char kDumpOptionAll[] = "all";
54 constexpr const char kDumpDeviceCamera[] = "camera";
55 constexpr const char kDumpDeviceDisplay[] = "display";
56 constexpr const char kDumpCameraCommandCurrent[] = "--current";
57 constexpr const char kDumpCameraCommandCollected[] = "--collected";
58 constexpr const char kDumpCameraCommandCustom[] = "--custom";
59 constexpr const char kDumpCameraCommandCustomStart[] = "start";
60 constexpr const char kDumpCameraCommandCustomStop[] = "stop";
61 constexpr int kDumpCameraMinNumArgs = 4;
62 constexpr int kOptionDumpDeviceTypeIndex = 1;
63 constexpr int kOptionDumpCameraTypeIndex = 2;
64 constexpr int kOptionDumpCameraCommandIndex = 3;
65 constexpr int kOptionDumpCameraArgsStartIndex = 4;
66 
67 // Parameters for HAL connection
68 constexpr int64_t kSleepTimeMilliseconds = 1000;
69 constexpr int64_t kTimeoutMilliseconds = 30000;
70 
71 // UIDs allowed to use this service
72 const std::set<uid_t> kAllowedUids = {AID_AUTOMOTIVE_EVS, AID_SYSTEM, AID_ROOT};
73 
74 }  // namespace
75 
76 namespace aidl::android::automotive::evs::implementation {
77 
~Enumerator()78 Enumerator::~Enumerator() {
79     if (mClientsMonitor) {
80         mClientsMonitor->stopCollection();
81     }
82 }
83 
connectToAidlHal(const std::string_view & hardwareServiceName,bool blocking)84 std::shared_ptr<IEvsEnumerator> Enumerator::connectToAidlHal(
85         const std::string_view& hardwareServiceName, bool blocking) {
86     // Connect with the underlying hardware enumerator
87     const std::string separator("/");
88     const std::string instanceName =
89             std::string(Enumerator::descriptor) + separator + std::string(hardwareServiceName);
90     if (!AServiceManager_isDeclared(instanceName.data())) {
91         return nullptr;
92     }
93 
94     std::add_pointer_t<AIBinder*(const char*)> getService;
95     if (blocking) {
96         getService = AServiceManager_waitForService;
97     } else {
98         getService = AServiceManager_checkService;
99     }
100 
101     auto service = IEvsEnumerator::fromBinder(::ndk::SpAIBinder(getService(instanceName.data())));
102     if (!service) {
103         return nullptr;
104     }
105 
106     // Register a device status callback
107     mDeviceStatusCallback =
108             ::ndk::SharedRefBase::make<EvsDeviceStatusCallbackImpl>(ref<Enumerator>());
109     if (!service->registerStatusCallback(mDeviceStatusCallback).isOk()) {
110         LOG(WARNING) << "Failed to register a device status callback";
111     }
112 
113     return std::move(service);
114 }
115 
connectToHidlHal(const std::string_view & hardwareServiceName)116 std::shared_ptr<IEvsEnumerator> Enumerator::connectToHidlHal(
117         const std::string_view& hardwareServiceName) {
118     // Connect with the underlying hardware enumerator
119     ::android::sp<hidlevs::V1_1::IEvsEnumerator> service =
120             hidlevs::V1_1::IEvsEnumerator::tryGetService(hardwareServiceName.data());
121     if (!service) {
122         return nullptr;
123     }
124 
125     return std::move(::ndk::SharedRefBase::make<AidlEnumerator>(service));
126 }
127 
init(const std::string_view & hardwareServiceName)128 bool Enumerator::init(const std::string_view& hardwareServiceName) {
129     LOG(DEBUG) << __FUNCTION__;
130 
131     if (mHwEnumerator) {
132         LOG(INFO) << "Enumerator is initialized already.";
133         return true;
134     }
135 
136     // Connect to EVS HAL implementation
137     auto retryCount = 0;
138     while (!mHwEnumerator && retryCount < (kTimeoutMilliseconds / kSleepTimeMilliseconds)) {
139         mHwEnumerator = connectToAidlHal(hardwareServiceName, /* blocking= */ false);
140         if (!mHwEnumerator) {
141             LOG(INFO) << "Failed to connect to AIDL EVS HAL implementation.  "
142                       << "Trying to connect to HIDL EVS HAL implementation instead.";
143             mHwEnumerator = connectToHidlHal(hardwareServiceName);
144             if (!mHwEnumerator) {
145                 LOG(INFO) << "No EVS HAL implementation is available.  Retrying after "
146                           << kSleepTimeMilliseconds << " ms";
147                 std::this_thread::sleep_for(std::chrono::milliseconds(kSleepTimeMilliseconds));
148                 ++retryCount;
149             }
150         }
151     }
152 
153     if (!mHwEnumerator) {
154         LOG(ERROR) << "Failed to connect EVS HAL.";
155         return false;
156     }
157 
158     // Get a list of available displays and identify the internal display
159     if (!mHwEnumerator->getDisplayIdList(&mDisplayPorts).isOk()) {
160         LOG(WARNING)
161                 << "Failed to get a list of available displays. EVS Display may not work properly "
162                    "if an active EVS HAL service implements HIDL v1.1 or AIDL EVS interface.";
163     }
164 
165     const size_t numDisplays = mDisplayPorts.size();
166     mDisplayPorts.erase(std::remove_if(mDisplayPorts.begin(), mDisplayPorts.end(),
167                                        [](const auto id) { return id == kExclusiveDisplayId; }),
168                         mDisplayPorts.end());
169     if (numDisplays != mDisplayPorts.size()) {
170         LOG(WARNING)
171                 << kExclusiveDisplayId
172                 << " is reserved for the special purpose so will not be available for EVS service.";
173     }
174 
175     // The first element is the internal display if a returned list is not
176     // empty.
177     mInternalDisplayPort = mDisplayPorts.empty() ? kDisplayIdUnavailable : mDisplayPorts.front();
178     mDisplayOwnedExclusively = false;
179 
180     // Starts the statistics collection
181     mMonitorEnabled = false;
182     mClientsMonitor = new (std::nothrow) StatsCollector();
183     if (mClientsMonitor) {
184         if (auto result = mClientsMonitor->startCollection(); !result.ok()) {
185             LOG(ERROR) << "Failed to start the usage monitor: " << result.error();
186         } else {
187             mMonitorEnabled = true;
188         }
189     }
190 
191     return true;
192 }
193 
checkPermission() const194 bool Enumerator::checkPermission() const {
195     const auto uid = AIBinder_getCallingUid();
196     if (!mDisablePermissionCheck && kAllowedUids.find(uid) == kAllowedUids.end()) {
197         LOG(ERROR) << "EVS access denied: "
198                    << "pid = " << AIBinder_getCallingPid() << ", uid = " << uid;
199         return false;
200     }
201 
202     return true;
203 }
204 
isLogicalCamera(const camera_metadata_t * metadata) const205 bool Enumerator::isLogicalCamera(const camera_metadata_t* metadata) const {
206     if (metadata == nullptr) {
207         LOG(INFO) << "Camera metadata is invalid";
208         return false;
209     }
210 
211     camera_metadata_ro_entry_t entry;
212     int rc =
213             find_camera_metadata_ro_entry(metadata, ANDROID_REQUEST_AVAILABLE_CAPABILITIES, &entry);
214     if (rc != ::android::OK) {
215         // No capabilities are found in metadata.
216         LOG(DEBUG) << "No capability is found";
217         return false;
218     }
219 
220     for (size_t i = 0; i < entry.count; ++i) {
221         uint8_t capability = entry.data.u8[i];
222         if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA) {
223             return true;
224         }
225     }
226 
227     return false;
228 }
229 
getPhysicalCameraIds(const std::string & id)230 std::unordered_set<std::string> Enumerator::getPhysicalCameraIds(const std::string& id) {
231     std::unordered_set<std::string> physicalCameras;
232     if (mCameraDevices.find(id) == mCameraDevices.end()) {
233         LOG(ERROR) << "Queried device " << id << " is unknown";
234         return physicalCameras;
235     }
236 
237     const camera_metadata_t* metadata =
238             reinterpret_cast<camera_metadata_t*>(&mCameraDevices[id].metadata[0]);
239     if (!isLogicalCamera(metadata)) {
240         // EVS assumes that the device w/o a valid metadata is a physical device.
241         LOG(INFO) << id << " is not a logical camera device.";
242         physicalCameras.insert(id);
243         return physicalCameras;
244     }
245 
246     camera_metadata_ro_entry entry;
247     int rc = find_camera_metadata_ro_entry(metadata, ANDROID_LOGICAL_MULTI_CAMERA_PHYSICAL_IDS,
248                                            &entry);
249     if (rc != ::android::OK) {
250         LOG(ERROR) << "No physical camera ID is found for a logical camera device " << id;
251         return physicalCameras;
252     }
253 
254     const uint8_t* ids = entry.data.u8;
255     size_t start = 0;
256     for (size_t i = 0; i < entry.count; ++i) {
257         if (ids[i] == '\0') {
258             if (start != i) {
259                 std::string id(reinterpret_cast<const char*>(ids + start));
260                 physicalCameras.insert(id);
261             }
262             start = i + 1;
263         }
264     }
265 
266     LOG(INFO) << id << " consists of " << physicalCameras.size() << " physical camera devices.";
267     return physicalCameras;
268 }
269 
270 // Methods from ::aidl::android::hardware::automotive::evs::IEvsEnumerator
isHardware(bool * flag)271 ScopedAStatus Enumerator::isHardware(bool* flag) {
272     *flag = false;
273     return ScopedAStatus::ok();
274 }
275 
getCameraList(std::vector<CameraDesc> * _aidl_return)276 ScopedAStatus Enumerator::getCameraList(std::vector<CameraDesc>* _aidl_return) {
277     LOG(DEBUG) << __FUNCTION__;
278     if (!checkPermission()) {
279         return Utils::buildScopedAStatusFromEvsResult(EvsResult::PERMISSION_DENIED);
280     }
281 
282     {
283         std::lock_guard lock(mLock);
284         auto status = mHwEnumerator->getCameraList(_aidl_return);
285         if (!status.isOk()) {
286             return status;
287         }
288 
289         for (auto&& desc : *_aidl_return) {
290             mCameraDevices.insert_or_assign(desc.id, desc);
291         }
292 
293         return status;
294     }
295 }
296 
getStreamList(const CameraDesc & desc,std::vector<Stream> * _aidl_return)297 ScopedAStatus Enumerator::getStreamList(const CameraDesc& desc, std::vector<Stream>* _aidl_return) {
298     std::shared_lock lock(mLock);
299     return mHwEnumerator->getStreamList(desc, _aidl_return);
300 }
301 
closeCamera(const std::shared_ptr<IEvsCamera> & cameraObj)302 ScopedAStatus Enumerator::closeCamera(const std::shared_ptr<IEvsCamera>& cameraObj) {
303     LOG(DEBUG) << __FUNCTION__;
304     if (!checkPermission()) {
305         return Utils::buildScopedAStatusFromEvsResult(EvsResult::PERMISSION_DENIED);
306     }
307 
308     if (!cameraObj) {
309         LOG(WARNING) << "Ignoring a call with an invalid camera object";
310         return Utils::buildScopedAStatusFromEvsResult(EvsResult::INVALID_ARG);
311     }
312 
313     {
314         std::lock_guard lock(mLock);
315         // All our client cameras are actually VirtualCamera objects
316         VirtualCamera* virtualCamera = reinterpret_cast<VirtualCamera*>(cameraObj.get());
317 
318         // Find the parent camera that backs this virtual camera
319         for (auto&& halCamera : virtualCamera->getHalCameras()) {
320             // Tell the virtual camera's parent to clean it up and drop it
321             // NOTE:  The camera objects will only actually destruct when the sp<> ref counts get to
322             //        zero, so it is important to break all cyclic references.
323             halCamera->disownVirtualCamera(virtualCamera);
324 
325             // Did we just remove the last client of this camera?
326             if (halCamera->getClientCount() == 0) {
327                 // Take this now unused camera out of our list
328                 // NOTE:  This should drop our last reference to the camera, resulting in its
329                 //        destruction.
330                 mActiveCameras.erase(halCamera->getId());
331                 auto status = mHwEnumerator->closeCamera(halCamera->getHwCamera());
332                 if (!status.isOk()) {
333                     LOG(WARNING) << "Failed to close a camera with id = " << halCamera->getId()
334                                  << ", error = " << status.getServiceSpecificError();
335                 }
336                 if (mMonitorEnabled) {
337                     mClientsMonitor->unregisterClientToMonitor(halCamera->getId());
338                 }
339             }
340         }
341 
342         // Make sure the virtual camera's stream is stopped
343         virtualCamera->stopVideoStream();
344 
345         return ScopedAStatus::ok();
346     }
347 }
348 
openCamera(const std::string & id,const Stream & cfg,std::shared_ptr<IEvsCamera> * cameraObj)349 ScopedAStatus Enumerator::openCamera(const std::string& id, const Stream& cfg,
350                                      std::shared_ptr<IEvsCamera>* cameraObj) {
351     LOG(DEBUG) << __FUNCTION__;
352     if (!checkPermission()) {
353         return Utils::buildScopedAStatusFromEvsResult(EvsResult::PERMISSION_DENIED);
354     }
355 
356     // If hwCamera is null, a requested camera device is either a logical camera
357     // device or a hardware camera, which is not being used now.
358     std::unordered_set<std::string> physicalCameras = getPhysicalCameraIds(id);
359     std::vector<std::shared_ptr<HalCamera>> sourceCameras;
360     bool success = true;
361 
362     {
363         std::lock_guard lock(mLock);
364         // 1. Try to open inactive camera devices.
365         for (auto&& id : physicalCameras) {
366             auto it = mActiveCameras.find(id);
367             if (it == mActiveCameras.end()) {
368                 std::shared_ptr<IEvsCamera> device;
369                 auto status = mHwEnumerator->openCamera(id, cfg, &device);
370                 if (!status.isOk()) {
371                     LOG(ERROR) << "Failed to open hardware camera " << id
372                                << ", error = " << status.getServiceSpecificError();
373                     success = false;
374                     break;
375                 }
376 
377                 // Calculates the usage statistics record identifier
378                 auto fn = mCameraDevices.hash_function();
379                 auto recordId = fn(id) & 0xFF;
380                 std::shared_ptr<HalCamera> hwCamera =
381                         ::ndk::SharedRefBase::make<HalCamera>(device, id, recordId, cfg);
382                 if (!hwCamera) {
383                     LOG(ERROR) << "Failed to allocate camera wrapper object";
384                     mHwEnumerator->closeCamera(device);
385                     success = false;
386                     break;
387                 }
388 
389                 // Add the hardware camera to our list, which will keep it alive via ref count
390                 mActiveCameras.insert_or_assign(id, hwCamera);
391                 if (mMonitorEnabled) {
392                     mClientsMonitor->registerClientToMonitor(hwCamera);
393                 }
394                 sourceCameras.push_back(std::move(hwCamera));
395             } else {
396                 if (it->second->getStreamConfig().id != cfg.id) {
397                     LOG(WARNING)
398                             << "Requested camera is already active in different configuration.";
399                 } else {
400                     sourceCameras.push_back(it->second);
401                 }
402             }
403         }
404 
405         if (!success || sourceCameras.size() < 1) {
406             LOG(ERROR) << "Failed to open any physical camera device";
407             return Utils::buildScopedAStatusFromEvsResult(EvsResult::UNDERLYING_SERVICE_ERROR);
408         }
409 
410         // TODO(b/147170360): Implement a logic to handle a failure.
411         // 3. Create a proxy camera object
412         std::shared_ptr<VirtualCamera> clientCamera =
413                 ::ndk::SharedRefBase::make<VirtualCamera>(sourceCameras);
414         if (!clientCamera) {
415             // TODO(b/213108625): Any resource needs to be cleaned up explicitly?
416             LOG(ERROR) << "Failed to create a client camera object";
417             return Utils::buildScopedAStatusFromEvsResult(EvsResult::UNDERLYING_SERVICE_ERROR);
418         }
419 
420         if (physicalCameras.size() > 1) {
421             // VirtualCamera, which represents a logical device, caches its
422             // descriptor.
423             clientCamera->setDescriptor(&mCameraDevices[id]);
424         }
425 
426         // 4. Owns created proxy camera object
427         for (auto&& hwCamera : sourceCameras) {
428             if (!hwCamera->ownVirtualCamera(clientCamera)) {
429                 // TODO(b/213108625): Remove a reference to this camera from a virtual camera
430                 // object.
431                 LOG(ERROR) << hwCamera->getId() << " failed to own a created proxy camera object.";
432             }
433         }
434 
435         // Send the virtual camera object back to the client by strong pointer which will keep it
436         // alive
437         *cameraObj = std::move(clientCamera);
438         return ScopedAStatus::ok();
439     }
440 }
441 
openDisplay(int32_t id,std::shared_ptr<IEvsDisplay> * displayObj)442 ScopedAStatus Enumerator::openDisplay(int32_t id, std::shared_ptr<IEvsDisplay>* displayObj) {
443     LOG(DEBUG) << __FUNCTION__;
444     if (!checkPermission()) {
445         return Utils::buildScopedAStatusFromEvsResult(EvsResult::PERMISSION_DENIED);
446     }
447 
448     {
449         std::lock_guard lock(mLock);
450         if (mDisplayOwnedExclusively) {
451             if (!mActiveDisplay.expired()) {
452                 LOG(ERROR) << "Display is owned exclusively by another client.";
453                 return Utils::buildScopedAStatusFromEvsResult(EvsResult::RESOURCE_BUSY);
454             }
455 
456             mDisplayOwnedExclusively = false;
457         }
458 
459         bool flagExclusive = false;
460         if (id == kExclusiveDisplayId) {
461             // The client requests to open the primary display exclusively.
462             id = mInternalDisplayPort;
463             flagExclusive = true;
464             LOG(DEBUG) << "EvsDisplay is now owned exclusively by process "
465                        << AIBinder_getCallingPid();
466         } else if (id == kDisplayIdUnavailable || mDisplayPorts.empty()) {
467             // If any display port is not available, it's possible that a
468             // running EVS HAL service implements HIDL EVS v1.0 interfaces.
469             id = mInternalDisplayPort;
470             LOG(WARNING) << "No display port is listed; Does a running EVS HAL service implement "
471                             "HIDL EVS v1.0 interfaces?";
472         } else if (std::find(mDisplayPorts.begin(), mDisplayPorts.end(), id) ==
473                    mDisplayPorts.end()) {
474             // If we know any available display port, a given display ID must be
475             // one of them.
476             LOG(ERROR) << "No display is available on the port " << id;
477             return Utils::buildScopedAStatusFromEvsResult(EvsResult::INVALID_ARG);
478         }
479 
480         // We simply keep track of the most recently opened display instance.
481         // In the underlying layers we expect that a new open will cause the previous
482         // object to be destroyed.  This avoids any race conditions associated with
483         // create/destroy order and provides a cleaner restart sequence if the previous owner
484         // is non-responsive for some reason.
485         // Request exclusive access to the EVS display
486         std::shared_ptr<IEvsDisplay> displayHandle;
487         if (auto status = mHwEnumerator->openDisplay(id, &displayHandle);
488             !status.isOk() || !displayHandle) {
489             // We may fail to open the display in following cases:
490             // 1) If a running EVS HAL service implements HIDL EVS interfaces,
491             // AidlEnumerator validates a given display ID and return a null if
492             // it's out of [0, 255].
493             // 2) If a running EVS HAL service implements AIDL EVS interfaces,
494             // EVS HAL service will return a null if no display is associated
495             // with a given display ID.
496             LOG(ERROR) << "EVS Display unavailable";
497             return status;
498         }
499 
500         // Remember (via weak pointer) who we think the most recently opened display is so that
501         // we can proxy state requests from other callers to it.
502         std::shared_ptr<IEvsDisplay> pHalDisplay =
503                 ::ndk::SharedRefBase::make<HalDisplay>(displayHandle, id);
504         *displayObj = pHalDisplay;
505         mActiveDisplay = pHalDisplay;
506         mDisplayOwnedExclusively = flagExclusive;
507 
508         return ScopedAStatus::ok();
509     }
510 }
511 
closeDisplay(const std::shared_ptr<IEvsDisplay> & displayObj)512 ScopedAStatus Enumerator::closeDisplay(const std::shared_ptr<IEvsDisplay>& displayObj) {
513     LOG(DEBUG) << __FUNCTION__;
514 
515     if (!displayObj) {
516         LOG(WARNING) << "Ignoring a call with an invalid display object";
517         return Utils::buildScopedAStatusFromEvsResult(EvsResult::INVALID_ARG);
518     }
519 
520     {
521         std::lock_guard lock(mLock);
522         // Drop the active display
523         std::shared_ptr<IEvsDisplay> pActiveDisplay = mActiveDisplay.lock();
524         if (pActiveDisplay != displayObj) {
525             LOG(WARNING) << "Ignoring call to closeDisplay with unrecognized display object.";
526             return ScopedAStatus::ok();
527         }
528 
529         // Pass this request through to the hardware layer
530         HalDisplay* halDisplay = reinterpret_cast<HalDisplay*>(pActiveDisplay.get());
531         mHwEnumerator->closeDisplay(halDisplay->getHwDisplay());
532         mActiveDisplay.reset();
533         mDisplayOwnedExclusively = false;
534 
535         return ScopedAStatus::ok();
536     }
537 }
538 
getDisplayState(DisplayState * _aidl_return)539 ScopedAStatus Enumerator::getDisplayState(DisplayState* _aidl_return) {
540     LOG(DEBUG) << __FUNCTION__;
541     if (!checkPermission()) {
542         return Utils::buildScopedAStatusFromEvsResult(EvsResult::PERMISSION_DENIED);
543     }
544 
545     {
546         std::lock_guard lock(mLock);
547         // Do we have a display object we think should be active?
548         std::shared_ptr<IEvsDisplay> pActiveDisplay = mActiveDisplay.lock();
549         if (pActiveDisplay) {
550             // Pass this request through to the hardware layer
551             return pActiveDisplay->getDisplayState(_aidl_return);
552         } else {
553             // We don't have a live display right now
554             mActiveDisplay.reset();
555             return Utils::buildScopedAStatusFromEvsResult(EvsResult::RESOURCE_NOT_AVAILABLE);
556         }
557     }
558 }
559 
getDisplayStateById(int32_t displayId,DisplayState * _aidl_return)560 ScopedAStatus Enumerator::getDisplayStateById(int32_t displayId, DisplayState* _aidl_return) {
561     LOG(DEBUG) << __FUNCTION__;
562     if (!checkPermission()) {
563         return Utils::buildScopedAStatusFromEvsResult(EvsResult::PERMISSION_DENIED);
564     }
565 
566     return mHwEnumerator->getDisplayStateById(displayId, _aidl_return);
567 }
568 
getDisplayIdList(std::vector<uint8_t> * _aidl_return)569 ScopedAStatus Enumerator::getDisplayIdList(std::vector<uint8_t>* _aidl_return) {
570     std::shared_lock lock(mLock);
571     return mHwEnumerator->getDisplayIdList(_aidl_return);
572 }
573 
registerStatusCallback(const std::shared_ptr<IEvsEnumeratorStatusCallback> & callback)574 ScopedAStatus Enumerator::registerStatusCallback(
575         const std::shared_ptr<IEvsEnumeratorStatusCallback>& callback) {
576     std::lock_guard lock(mLock);
577     mDeviceStatusCallbacks.insert(callback);
578     return ScopedAStatus::ok();
579 }
580 
getUltrasonicsArrayList(std::vector<UltrasonicsArrayDesc> * list)581 ScopedAStatus Enumerator::getUltrasonicsArrayList(
582         [[maybe_unused]] std::vector<UltrasonicsArrayDesc>* list) {
583     // TODO(b/149874793): Add implementation for EVS Manager and Sample driver
584     return Utils::buildScopedAStatusFromEvsResult(EvsResult::NOT_IMPLEMENTED);
585 }
586 
openUltrasonicsArray(const std::string & id,std::shared_ptr<IEvsUltrasonicsArray> * obj)587 ScopedAStatus Enumerator::openUltrasonicsArray(
588         [[maybe_unused]] const std::string& id,
589         [[maybe_unused]] std::shared_ptr<IEvsUltrasonicsArray>* obj) {
590     // TODO(b/149874793): Add implementation for EVS Manager and Sample driver
591     return Utils::buildScopedAStatusFromEvsResult(EvsResult::NOT_IMPLEMENTED);
592 }
593 
closeUltrasonicsArray(const std::shared_ptr<IEvsUltrasonicsArray> & obj)594 ScopedAStatus Enumerator::closeUltrasonicsArray(
595         [[maybe_unused]] const std::shared_ptr<IEvsUltrasonicsArray>& obj) {
596     // TODO(b/149874793): Add implementation for EVS Manager and Sample driver
597     return Utils::buildScopedAStatusFromEvsResult(EvsResult::NOT_IMPLEMENTED);
598 }
599 
dump(int fd,const char ** args,uint32_t numArgs)600 binder_status_t Enumerator::dump(int fd, const char** args, uint32_t numArgs) {
601     if (fd < 0) {
602         LOG(ERROR) << "Given file descriptor is not valid.";
603         return STATUS_BAD_VALUE;
604     }
605 
606     cmdDump(fd, args, numArgs);
607     return STATUS_OK;
608 }
609 
cmdDump(int fd,const char ** args,uint32_t numArgs)610 void Enumerator::cmdDump(int fd, const char** args, uint32_t numArgs) {
611     if (numArgs < 1) {
612         WriteStringToFd("No option is given.\n", fd);
613         cmdHelp(fd);
614         return;
615     }
616 
617     const std::string option = args[0];
618     if (EqualsIgnoreCase(option, "--help")) {
619         cmdHelp(fd);
620     } else if (EqualsIgnoreCase(option, "--list")) {
621         cmdList(fd, args, numArgs);
622     } else if (EqualsIgnoreCase(option, "--dump")) {
623         cmdDumpDevice(fd, args, numArgs);
624     } else {
625         WriteStringToFd(StringPrintf("Invalid option: %s\n", option.data()), fd);
626     }
627 }
628 
cmdHelp(int fd)629 void Enumerator::cmdHelp(int fd) {
630     WriteStringToFd("--help: shows this help.\n"
631                     "--list [all|camera|display]: lists camera or display devices or both "
632                     "available to EVS manager.\n"
633                     "--dump camera [all|device_id] --[current|collected|custom] [args]\n"
634                     "\tcurrent: shows the current status\n"
635                     "\tcollected: shows 10 most recent periodically collected camera usage "
636                     "statistics\n"
637                     "\tcustom: starts/stops collecting the camera usage statistics\n"
638                     "\t\tstart [interval] [duration]: starts collecting usage statistics "
639                     "at every [interval] during [duration].  Interval and duration are in "
640                     "milliseconds.\n"
641                     "\t\tstop: stops collecting usage statistics and shows collected records.\n"
642                     "--dump display: shows current status of the display\n",
643                     fd);
644 }
645 
cmdList(int fd,const char ** args,uint32_t numArgs)646 void Enumerator::cmdList(int fd, const char** args, uint32_t numArgs) {
647     bool listCameras = false;
648     bool listDisplays = false;
649     if (numArgs > 1) {
650         const std::string option = args[1];
651         const bool listAll = EqualsIgnoreCase(option, kDumpOptionAll);
652         listCameras = listAll || EqualsIgnoreCase(option, kDumpDeviceCamera);
653         listDisplays = listAll || EqualsIgnoreCase(option, kDumpDeviceDisplay);
654         if (!listCameras && !listDisplays) {
655             WriteStringToFd(StringPrintf("Unrecognized option, %s, is ignored.\n", option.data()),
656                             fd);
657 
658             // Nothing to show, return
659             return;
660         }
661     }
662 
663     std::string buffer;
664     if (listCameras) {
665         StringAppendF(&buffer, "Camera devices available to EVS service:\n");
666         if (mCameraDevices.size() < 1) {
667             // Camera devices may not be enumerated yet.  This may fail if the
668             // user is not permitted to use EVS service.
669             std::vector<CameraDesc> temp;
670             (void)getCameraList(&temp);
671         }
672 
673         for (auto& [id, desc] : mCameraDevices) {
674             StringAppendF(&buffer, "%s%s\n", kSingleIndent, id.data());
675         }
676 
677         StringAppendF(&buffer, "%sCamera devices currently in use:\n", kSingleIndent);
678         for (auto& [id, ptr] : mActiveCameras) {
679             StringAppendF(&buffer, "%s%s\n", kSingleIndent, id.data());
680         }
681         StringAppendF(&buffer, "\n");
682     }
683 
684     if (listDisplays) {
685         if (mHwEnumerator != nullptr) {
686             StringAppendF(&buffer, "Display devices available to EVS service:\n");
687             // Get an internal display identifier.
688             if (mDisplayPorts.size() < 1) {
689                 (void)mHwEnumerator->getDisplayIdList(&mDisplayPorts);
690             }
691 
692             for (auto&& port : mDisplayPorts) {
693                 StringAppendF(&buffer, "%sdisplay port %u\n", kSingleIndent,
694                               static_cast<unsigned>(port));
695             }
696         } else {
697             LOG(WARNING) << "EVS HAL implementation is not available.";
698         }
699     }
700 
701     WriteStringToFd(buffer, fd);
702 }
703 
cmdDumpDevice(int fd,const char ** args,uint32_t numArgs)704 void Enumerator::cmdDumpDevice(int fd, const char** args, uint32_t numArgs) {
705     // Dumps both cameras and displays if the target device type is not given
706     bool dumpCameras = false;
707     bool dumpDisplays = false;
708     if (numArgs > kOptionDumpDeviceTypeIndex) {
709         const std::string target = args[kOptionDumpDeviceTypeIndex];
710         dumpCameras = EqualsIgnoreCase(target, kDumpDeviceCamera);
711         dumpDisplays = EqualsIgnoreCase(target, kDumpDeviceDisplay);
712         if (!dumpCameras && !dumpDisplays) {
713             WriteStringToFd(StringPrintf("Unrecognized option, %s, is ignored.\n", target.data()),
714                             fd);
715             cmdHelp(fd);
716             return;
717         }
718     } else {
719         WriteStringToFd(StringPrintf("Necessary arguments are missing.  "
720                                      "Please check the usages:\n"),
721                         fd);
722         cmdHelp(fd);
723         return;
724     }
725 
726     if (dumpCameras) {
727         // --dump camera [all|device_id] --[current|collected|custom] [args]
728         if (numArgs < kDumpCameraMinNumArgs) {
729             WriteStringToFd(StringPrintf("Necessary arguments are missing.  "
730                                          "Please check the usages:\n"),
731                             fd);
732             cmdHelp(fd);
733             return;
734         }
735 
736         const std::string deviceId = args[kOptionDumpCameraTypeIndex];
737         auto target = mActiveCameras.find(deviceId);
738         const bool dumpAllCameras = EqualsIgnoreCase(deviceId, kDumpOptionAll);
739         if (!dumpAllCameras && target == mActiveCameras.end()) {
740             // Unknown camera identifier
741             WriteStringToFd(StringPrintf("Given camera ID %s is unknown or not active.\n",
742                                          deviceId.data()),
743                             fd);
744             return;
745         }
746 
747         const std::string command = args[kOptionDumpCameraCommandIndex];
748         std::string cameraInfo;
749         if (EqualsIgnoreCase(command, kDumpCameraCommandCurrent)) {
750             // Active stream configuration from each active HalCamera objects
751             if (!dumpAllCameras) {
752                 StringAppendF(&cameraInfo, "HalCamera: %s\n%s", deviceId.data(),
753                               target->second->toString(kSingleIndent).data());
754             } else {
755                 for (auto&& [_, handle] : mActiveCameras) {
756                     // Appends the current status
757                     cameraInfo += handle->toString(kSingleIndent);
758                 }
759             }
760         } else if (EqualsIgnoreCase(command, kDumpCameraCommandCollected)) {
761             // Reads the usage statistics from active HalCamera objects
762             std::unordered_map<std::string, std::string> usageStrings;
763             if (mMonitorEnabled) {
764                 auto result = mClientsMonitor->toString(&usageStrings, kSingleIndent);
765                 if (!result.ok()) {
766                     LOG(ERROR) << "Failed to get the monitoring result";
767                     return;
768                 }
769 
770                 if (!dumpAllCameras) {
771                     cameraInfo += usageStrings[deviceId];
772                 } else {
773                     for (auto&& [_, stats] : usageStrings) {
774                         cameraInfo += stats;
775                     }
776                 }
777             } else {
778                 WriteStringToFd(StringPrintf("Client monitor is not available.\n"), fd);
779                 return;
780             }
781         } else if (EqualsIgnoreCase(command, kDumpCameraCommandCustom)) {
782             // Additional arguments are expected for this command:
783             // --dump camera device_id --custom start [interval] [duration]
784             // or, --dump camera device_id --custom stop
785             if (numArgs < kDumpCameraMinNumArgs + 1) {
786                 WriteStringToFd(StringPrintf("Necessary arguments are missing. "
787                                              "Please check the usages:\n"),
788                                 fd);
789                 cmdHelp(fd);
790                 return;
791             }
792 
793             if (!mMonitorEnabled) {
794                 WriteStringToFd(StringPrintf("Client monitor is not available."), fd);
795                 return;
796             }
797 
798             const std::string subcommand = args[kOptionDumpCameraArgsStartIndex];
799             if (EqualsIgnoreCase(subcommand, kDumpCameraCommandCustomStart)) {
800                 using ::std::chrono::duration_cast;
801                 using ::std::chrono::milliseconds;
802                 using ::std::chrono::nanoseconds;
803                 nanoseconds interval = 0ns;
804                 nanoseconds duration = 0ns;
805                 if (numArgs > kOptionDumpCameraArgsStartIndex + 2) {
806                     duration = duration_cast<nanoseconds>(
807                             milliseconds(std::stoi(args[kOptionDumpCameraArgsStartIndex + 2])));
808                 }
809 
810                 if (numArgs > kOptionDumpCameraArgsStartIndex + 1) {
811                     interval = duration_cast<nanoseconds>(
812                             milliseconds(std::stoi(args[kOptionDumpCameraArgsStartIndex + 1])));
813                 }
814 
815                 // Starts a custom collection
816                 auto result = mClientsMonitor->startCustomCollection(interval, duration);
817                 if (!result.ok()) {
818                     LOG(ERROR) << "Failed to start a custom collection.  " << result.error();
819                     StringAppendF(&cameraInfo, "Failed to start a custom collection. %s\n",
820                                   result.error().message().data());
821                 }
822             } else if (EqualsIgnoreCase(subcommand, kDumpCameraCommandCustomStop)) {
823                 if (!mMonitorEnabled) {
824                     WriteStringToFd(StringPrintf("Client monitor is not available."), fd);
825                     return;
826                 }
827 
828                 auto result = mClientsMonitor->stopCustomCollection(deviceId);
829                 if (!result.ok()) {
830                     LOG(ERROR) << "Failed to stop a custom collection.  " << result.error();
831                     StringAppendF(&cameraInfo, "Failed to stop a custom collection. %s\n",
832                                   result.error().message().data());
833                 } else {
834                     // Pull the custom collection
835                     cameraInfo += *result;
836                 }
837             } else {
838                 WriteStringToFd(StringPrintf("Unknown argument: %s\n", subcommand.data()), fd);
839                 cmdHelp(fd);
840                 return;
841             }
842         } else {
843             WriteStringToFd(StringPrintf("Unknown command: %s\n"
844                                          "Please check the usages:\n",
845                                          command.data()),
846                             fd);
847             cmdHelp(fd);
848             return;
849         }
850 
851         // Outputs the report
852         WriteStringToFd(cameraInfo, fd);
853     }
854 
855     if (dumpDisplays) {
856         HalDisplay* pDisplay = reinterpret_cast<HalDisplay*>(mActiveDisplay.lock().get());
857         if (pDisplay == nullptr) {
858             WriteStringToFd("No active display is found.\n", fd);
859         } else {
860             WriteStringToFd(pDisplay->toString(kSingleIndent), fd);
861         }
862     }
863 }
864 
broadcastDeviceStatusChange(const std::vector<aidlevs::DeviceStatus> & list)865 void Enumerator::broadcastDeviceStatusChange(const std::vector<aidlevs::DeviceStatus>& list) {
866     std::lock_guard lock(mLock);
867     auto it = mDeviceStatusCallbacks.begin();
868     while (it != mDeviceStatusCallbacks.end()) {
869         if (!(*it)->deviceStatusChanged(list).isOk()) {
870             mDeviceStatusCallbacks.erase(it);
871         } else {
872             ++it;
873         }
874     }
875 }
876 
deviceStatusChanged(const std::vector<aidlevs::DeviceStatus> & list)877 ScopedAStatus Enumerator::EvsDeviceStatusCallbackImpl::deviceStatusChanged(
878         const std::vector<aidlevs::DeviceStatus>& list) {
879     mEnumerator->broadcastDeviceStatusChange(list);
880     return ScopedAStatus::ok();
881 }
882 
init(std::shared_ptr<IEvsEnumerator> & hwEnumerator,bool enableMonitor)883 bool Enumerator::init(std::shared_ptr<IEvsEnumerator>& hwEnumerator, bool enableMonitor) {
884     LOG(DEBUG) << __FUNCTION__;
885 
886     // Register a device status callback
887     mDeviceStatusCallback =
888             ::ndk::SharedRefBase::make<EvsDeviceStatusCallbackImpl>(ref<Enumerator>());
889     if (!hwEnumerator->registerStatusCallback(mDeviceStatusCallback).isOk()) {
890         LOG(WARNING) << "Failed to register a device status callback";
891     }
892 
893     // Get a list of available displays and identify the internal display
894     if (!hwEnumerator->getDisplayIdList(&mDisplayPorts).isOk()) {
895         LOG(WARNING)
896                 << "Failed to get a list of available displays. EVS Display may not work properly "
897                    "if an active EVS HAL service implements HIDL v1.1 or AIDL EVS interface.";
898     }
899 
900     const size_t numDisplays = mDisplayPorts.size();
901     mDisplayPorts.erase(std::remove_if(mDisplayPorts.begin(), mDisplayPorts.end(),
902                                        [](const auto id) { return id == kExclusiveDisplayId; }),
903                         mDisplayPorts.end());
904     if (numDisplays != mDisplayPorts.size()) {
905         LOG(WARNING)
906                 << kExclusiveDisplayId
907                 << " is reserved for the special purpose so will not be available for EVS service.";
908     }
909 
910     // The first element is the internal display if a returned list is not
911     // empty.
912     mInternalDisplayPort = mDisplayPorts.empty() ? kDisplayIdUnavailable : mDisplayPorts.front();
913     mDisplayOwnedExclusively = false;
914     mHwEnumerator = hwEnumerator;
915 
916     // Starts the statistics collection
917     mMonitorEnabled = false;
918     if (!enableMonitor) {
919         return true;
920     }
921 
922     mClientsMonitor = new (std::nothrow) StatsCollector();
923     if (mClientsMonitor) {
924         if (auto result = mClientsMonitor->startCollection(); !result.ok()) {
925             LOG(ERROR) << "Failed to start the usage monitor: " << result.error();
926         } else {
927             mMonitorEnabled = true;
928         }
929     }
930 
931     return true;
932 }
933 
enablePermissionCheck(bool enable)934 void Enumerator::enablePermissionCheck(bool enable) {
935     mDisablePermissionCheck = !enable;
936 }
937 
938 }  // namespace aidl::android::automotive::evs::implementation
939