• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "hcamera_service.h"
17 
18 #include <securec.h>
19 #include <unordered_set>
20 
21 #include "access_token.h"
22 #include "accesstoken_kit.h"
23 #include "camera_util.h"
24 #include "iservice_registry.h"
25 #include "camera_log.h"
26 #include "system_ability_definition.h"
27 #include "ipc_skeleton.h"
28 
29 namespace OHOS {
30 namespace CameraStandard {
REGISTER_SYSTEM_ABILITY_BY_ID(HCameraService,CAMERA_SERVICE_ID,true)31 REGISTER_SYSTEM_ABILITY_BY_ID(HCameraService, CAMERA_SERVICE_ID, true)
32 HCameraService::HCameraService(int32_t systemAbilityId, bool runOnCreate)
33     : SystemAbility(systemAbilityId, runOnCreate),
34       cameraHostManager_(nullptr),
35       streamOperatorCallback_(nullptr),
36       muteMode_(false)
37 {
38 }
39 
~HCameraService()40 HCameraService::~HCameraService()
41 {
42 }
43 
OnStart()44 void HCameraService::OnStart()
45 {
46     if (cameraHostManager_ == nullptr) {
47         cameraHostManager_ = new(std::nothrow) HCameraHostManager(this);
48         if (cameraHostManager_ == nullptr) {
49             MEDIA_ERR_LOG("HCameraService OnStart failed to create HCameraHostManager obj");
50             return;
51         }
52     }
53     if (cameraHostManager_->Init() != CAMERA_OK) {
54         MEDIA_ERR_LOG("HCameraService OnStart failed to init camera host manager.");
55     }
56     bool res = Publish(this);
57     if (res) {
58         MEDIA_INFO_LOG("HCameraService OnStart res=%{public}d", res);
59     }
60 }
61 
OnDump()62 void HCameraService::OnDump()
63 {
64     MEDIA_INFO_LOG("HCameraService::OnDump called");
65 }
66 
OnStop()67 void HCameraService::OnStop()
68 {
69     MEDIA_INFO_LOG("HCameraService::OnStop called");
70 
71     if (cameraHostManager_) {
72         cameraHostManager_->DeInit();
73         delete cameraHostManager_;
74         cameraHostManager_ = nullptr;
75     }
76     if (streamOperatorCallback_) {
77         streamOperatorCallback_ = nullptr;
78     }
79 }
80 
GetCameras(std::vector<std::string> & cameraIds,std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> & cameraAbilityList)81 int32_t HCameraService::GetCameras(std::vector<std::string> &cameraIds,
82     std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> &cameraAbilityList)
83 {
84     CAMERA_SYNC_TRACE;
85     int32_t ret = cameraHostManager_->GetCameras(cameraIds);
86     if (ret != CAMERA_OK) {
87         MEDIA_ERR_LOG("HCameraService::GetCameras failed");
88         return ret;
89     }
90 
91     std::shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility;
92     for (auto id : cameraIds) {
93         ret = cameraHostManager_->GetCameraAbility(id, cameraAbility);
94         if (ret != CAMERA_OK) {
95             MEDIA_ERR_LOG("HCameraService::GetCameraAbility failed");
96             return ret;
97         }
98 
99         if (cameraAbility == nullptr) {
100             MEDIA_ERR_LOG("HCameraService::GetCameraAbility return null");
101             return CAMERA_INVALID_ARG;
102         }
103 
104         camera_metadata_item_t item;
105         common_metadata_header_t* metadata = cameraAbility->get();
106         camera_position_enum_t cameraPosition = OHOS_CAMERA_POSITION_OTHER;
107         int ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_CAMERA_POSITION, &item);
108         if (ret == CAM_META_SUCCESS) {
109             cameraPosition = static_cast<camera_position_enum_t>(item.data.u8[0]);
110         }
111 
112         camera_type_enum_t cameraType = OHOS_CAMERA_TYPE_UNSPECIFIED;
113         ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_CAMERA_TYPE, &item);
114         if (ret == CAM_META_SUCCESS) {
115             cameraType = static_cast<camera_type_enum_t>(item.data.u8[0]);
116         }
117 
118         camera_connection_type_t connectionType = OHOS_CAMERA_CONNECTION_TYPE_BUILTIN;
119         ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_CAMERA_CONNECTION_TYPE, &item);
120         if (ret == CAM_META_SUCCESS) {
121             connectionType = static_cast<camera_connection_type_t>(item.data.u8[0]);
122         }
123 
124         bool isMirrorSupported = false;
125         ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_CONTROL_CAPTURE_MIRROR_SUPPORTED, &item);
126         if (ret == CAM_META_SUCCESS) {
127             isMirrorSupported = ((item.data.u8[0] == 1) || (item.data.u8[0] == 0));
128         }
129 
130         CAMERA_SYSEVENT_STATISTIC(CreateMsg("CameraManager GetCameras camera ID:%s, Camera position:%d,"
131                                             " Camera Type:%d, Connection Type:%d, Mirror support:%d", id.c_str(),
132                                             cameraPosition, cameraType, connectionType, isMirrorSupported));
133         cameraAbilityList.emplace_back(cameraAbility);
134     }
135 
136     return ret;
137 }
138 
CreateCameraDevice(std::string cameraId,sptr<ICameraDeviceService> & device)139 int32_t HCameraService::CreateCameraDevice(std::string cameraId, sptr<ICameraDeviceService> &device)
140 {
141     CAMERA_SYNC_TRACE;
142     OHOS::Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
143 
144     std::string permissionName = OHOS_PERMISSION_CAMERA;
145     int32_t ret = CheckPermission(permissionName, callerToken);
146     if (ret != CAMERA_OK) {
147         return ret;
148     }
149     // if callerToken is invalid, will not call IsAllowedUsingPermission
150     if (IsValidTokenId(callerToken) &&
151         !Security::AccessToken::PrivacyKit::IsAllowedUsingPermission(callerToken, permissionName)) {
152         MEDIA_ERR_LOG("HCameraService::CreateCameraDevice is not allowed!");
153         return CAMERA_ALLOC_ERROR;
154     }
155 
156     bool isPermisson = true;
157     auto conflictDevices = CameraConflictDetection(cameraId, isPermisson);
158     if (!isPermisson) {
159         MEDIA_ERR_LOG("HCameraDevice::CreateCameraDevice device busy!");
160         return CAMERA_DEVICE_BUSY;
161     }
162     // Destory conflict devices
163     for (auto &i : conflictDevices) {
164         if (i != nullptr) {
165             i->OnError(DEVICE_PREEMPT, 0);
166             DeviceClose(i->GetCameraId());
167         }
168     }
169     std::lock_guard<std::mutex> lock(mapOperatorsLock_);
170     sptr<HCameraDevice> cameraDevice = new(std::nothrow) HCameraDevice(cameraHostManager_, cameraId, callerToken);
171     if (cameraDevice == nullptr) {
172         MEDIA_ERR_LOG("HCameraService::CreateCameraDevice HCameraDevice allocation failed");
173         return CAMERA_ALLOC_ERROR;
174     }
175 
176     // when create camera device, update mute setting truely.
177     if (IsCameraMuteSupported(cameraId)) {
178         if (UpdateMuteSetting(cameraDevice, muteMode_) != CAMERA_OK) {
179             MEDIA_ERR_LOG("UpdateMuteSetting Failed, cameraId: %{public}s", cameraId.c_str());
180         }
181     } else {
182         MEDIA_ERR_LOG("HCameraService::CreateCameraDevice MuteCamera not Supported");
183     }
184     cameraDevice->SetDeviceOperatorsCallback(this);
185     pid_t pid = IPCSkeleton::GetCallingPid();
186     MEDIA_INFO_LOG("HCameraService::CreateCameraDevice before insert! cameraId: %{public}s, pid = %{public}d, "
187                    "devices size = %{public}d, cameraIds size = %{public}zu",
188                    cameraId.c_str(), pid, devicesManager_.Size(), camerasForPid_[pid].size());
189     devicesManager_.EnsureInsert(cameraId, cameraDevice);
190     camerasForPid_[pid].insert(cameraId);
191     MEDIA_INFO_LOG("HCameraService::CreateCameraDevice after insert! cameraId: %{public}s, pid = %{public}d, "
192                    "devices size = %{public}d, cameraIds size = %{public}zu",
193                    cameraId.c_str(), pid, devicesManager_.Size(), camerasForPid_[pid].size());
194     device = cameraDevice;
195     CAMERA_SYSEVENT_STATISTIC(CreateMsg("CameraManager_CreateCameraInput CameraId:%s", cameraId.c_str()));
196     return CAMERA_OK;
197 }
198 
CreateCaptureSession(sptr<ICaptureSession> & session)199 int32_t HCameraService::CreateCaptureSession(sptr<ICaptureSession> &session)
200 {
201     CAMERA_SYNC_TRACE;
202     std::lock_guard<std::mutex> lock(mutex_);
203     sptr<HCaptureSession> captureSession;
204     if (streamOperatorCallback_ == nullptr) {
205         streamOperatorCallback_ = new(std::nothrow) StreamOperatorCallback();
206         if (streamOperatorCallback_ == nullptr) {
207             MEDIA_ERR_LOG("HCameraService::CreateCaptureSession streamOperatorCallback_ allocation failed");
208             return CAMERA_ALLOC_ERROR;
209         }
210     }
211 
212     OHOS::Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
213     captureSession = new(std::nothrow) HCaptureSession(cameraHostManager_, streamOperatorCallback_, callerToken);
214     if (captureSession == nullptr) {
215         MEDIA_ERR_LOG("HCameraService::CreateCaptureSession HCaptureSession allocation failed");
216         return CAMERA_ALLOC_ERROR;
217     }
218     captureSession->SetDeviceOperatorsCallback(this);
219     session = captureSession;
220     return CAMERA_OK;
221 }
222 
CreatePhotoOutput(const sptr<OHOS::IBufferProducer> & producer,int32_t format,int32_t width,int32_t height,sptr<IStreamCapture> & photoOutput)223 int32_t HCameraService::CreatePhotoOutput(const sptr<OHOS::IBufferProducer> &producer, int32_t format,
224                                           int32_t width, int32_t height,
225                                           sptr<IStreamCapture> &photoOutput)
226 {
227     CAMERA_SYNC_TRACE;
228     if ((producer == nullptr) || (width == 0) || (height == 0)) {
229         MEDIA_ERR_LOG("HCameraService::CreatePhotoOutput producer is null");
230         return CAMERA_INVALID_ARG;
231     }
232     sptr<HStreamCapture> streamCapture = new(std::nothrow) HStreamCapture(producer, format, width, height);
233     if (streamCapture == nullptr) {
234         MEDIA_ERR_LOG("HCameraService::CreatePhotoOutput HStreamCapture allocation failed");
235         return CAMERA_ALLOC_ERROR;
236     }
237     POWERMGR_SYSEVENT_CAMERA_CONFIG(PHOTO, producer->GetDefaultWidth(),
238                                     producer->GetDefaultHeight());
239     photoOutput = streamCapture;
240     return CAMERA_OK;
241 }
242 
CreateDeferredPreviewOutput(int32_t format,int32_t width,int32_t height,sptr<IStreamRepeat> & previewOutput)243 int32_t HCameraService::CreateDeferredPreviewOutput(int32_t format,
244                                                     int32_t width, int32_t height,
245                                                     sptr<IStreamRepeat> &previewOutput)
246 {
247     CAMERA_SYNC_TRACE;
248     sptr<HStreamRepeat> streamDeferredPreview;
249 
250     if ((width == 0) || (height == 0)) {
251         MEDIA_ERR_LOG("HCameraService::CreateDeferredPreviewOutput producer is null");
252         return CAMERA_INVALID_ARG;
253     }
254     streamDeferredPreview = new(std::nothrow) HStreamRepeat(nullptr, format, width, height, false);
255     if (streamDeferredPreview == nullptr) {
256         MEDIA_ERR_LOG("HCameraService::CreateDeferredPreviewOutput HStreamRepeat allocation failed");
257         return CAMERA_ALLOC_ERROR;
258     }
259     previewOutput = streamDeferredPreview;
260     return CAMERA_OK;
261 }
262 
CreatePreviewOutput(const sptr<OHOS::IBufferProducer> & producer,int32_t format,int32_t width,int32_t height,sptr<IStreamRepeat> & previewOutput)263 int32_t HCameraService::CreatePreviewOutput(const sptr<OHOS::IBufferProducer> &producer, int32_t format,
264                                             int32_t width, int32_t height,
265                                             sptr<IStreamRepeat> &previewOutput)
266 {
267     CAMERA_SYNC_TRACE;
268     sptr<HStreamRepeat> streamRepeatPreview;
269 
270     if ((producer == nullptr) || (width == 0) || (height == 0)) {
271         MEDIA_ERR_LOG("HCameraService::CreatePreviewOutput producer is null");
272         return CAMERA_INVALID_ARG;
273     }
274     streamRepeatPreview = new(std::nothrow) HStreamRepeat(producer, format, width, height, false);
275     if (streamRepeatPreview == nullptr) {
276         MEDIA_ERR_LOG("HCameraService::CreatePreviewOutput HStreamRepeat allocation failed");
277         return CAMERA_ALLOC_ERROR;
278     }
279     POWERMGR_SYSEVENT_CAMERA_CONFIG(PREVIEW, width, height);
280     previewOutput = streamRepeatPreview;
281     return CAMERA_OK;
282 }
283 
CreateMetadataOutput(const sptr<OHOS::IBufferProducer> & producer,int32_t format,sptr<IStreamMetadata> & metadataOutput)284 int32_t HCameraService::CreateMetadataOutput(const sptr<OHOS::IBufferProducer> &producer, int32_t format,
285                                              sptr<IStreamMetadata> &metadataOutput)
286 {
287     CAMERA_SYNC_TRACE;
288     sptr<HStreamMetadata> streamMetadata;
289 
290     if (producer == nullptr) {
291         MEDIA_ERR_LOG("HCameraService::CreateMetadataOutput producer is null");
292         return CAMERA_INVALID_ARG;
293     }
294     streamMetadata = new(std::nothrow) HStreamMetadata(producer, format);
295     if (streamMetadata == nullptr) {
296         MEDIA_ERR_LOG("HCameraService::CreateMetadataOutput HStreamMetadata allocation failed");
297         return CAMERA_ALLOC_ERROR;
298     }
299     POWERMGR_SYSEVENT_CAMERA_CONFIG(METADATA, producer->GetDefaultWidth(),
300                                     producer->GetDefaultHeight());
301     metadataOutput = streamMetadata;
302     return CAMERA_OK;
303 }
304 
CreateVideoOutput(const sptr<OHOS::IBufferProducer> & producer,int32_t format,int32_t width,int32_t height,sptr<IStreamRepeat> & videoOutput)305 int32_t HCameraService::CreateVideoOutput(const sptr<OHOS::IBufferProducer> &producer, int32_t format,
306                                           int32_t width, int32_t height,
307                                           sptr<IStreamRepeat> &videoOutput)
308 {
309     CAMERA_SYNC_TRACE;
310     sptr<HStreamRepeat> streamRepeatVideo;
311 
312     if ((producer == nullptr) || (width == 0) || (height == 0)) {
313         MEDIA_ERR_LOG("HCameraService::CreateVideoOutput producer is null");
314         return CAMERA_INVALID_ARG;
315     }
316     streamRepeatVideo = new(std::nothrow) HStreamRepeat(producer, format, width, height, true);
317     if (streamRepeatVideo == nullptr) {
318         MEDIA_ERR_LOG("HCameraService::CreateVideoOutput HStreamRepeat allocation failed");
319         return CAMERA_ALLOC_ERROR;
320     }
321     POWERMGR_SYSEVENT_CAMERA_CONFIG(VIDEO, producer->GetDefaultWidth(),
322                                     producer->GetDefaultHeight());
323     videoOutput = streamRepeatVideo;
324     return CAMERA_OK;
325 }
326 
OnCameraStatus(const std::string & cameraId,CameraStatus status)327 void HCameraService::OnCameraStatus(const std::string& cameraId, CameraStatus status)
328 {
329     std::lock_guard<std::mutex> lock(cbMutex_);
330     MEDIA_INFO_LOG("HCameraService::OnCameraStatus "
331                    "callbacks.size = %{public}zu, cameraId = %{public}s, status = %{public}d, pid = %{public}d",
332                    cameraServiceCallbacks_.size(), cameraId.c_str(), status, IPCSkeleton::GetCallingPid());
333     for (auto it : cameraServiceCallbacks_) {
334         if (it.second == nullptr) {
335             MEDIA_ERR_LOG("HCameraService::OnCameraStatus cameraServiceCallback is null, pid = %{public}d",
336                           IPCSkeleton::GetCallingPid());
337             continue;
338         }
339         if (it.second != nullptr) {
340             it.second->OnCameraStatusChanged(cameraId, status);
341         }
342         CAMERA_SYSEVENT_BEHAVIOR(CreateMsg("OnCameraStatusChanged! for cameraId:%s, current Camera Status:%d",
343                                            cameraId.c_str(), status));
344     }
345 }
346 
OnFlashlightStatus(const std::string & cameraId,FlashStatus status)347 void HCameraService::OnFlashlightStatus(const std::string& cameraId, FlashStatus status)
348 {
349     std::lock_guard<std::mutex> lock(cbMutex_);
350     MEDIA_INFO_LOG("HCameraService::OnFlashlightStatus "
351                    "callbacks.size = %{public}zu, cameraId = %{public}s, status = %{public}d, pid = %{public}d",
352                    cameraServiceCallbacks_.size(), cameraId.c_str(), status, IPCSkeleton::GetCallingPid());
353     for (auto it : cameraServiceCallbacks_) {
354         if (it.second == nullptr) {
355             MEDIA_ERR_LOG("HCameraService::OnCameraStatus cameraServiceCallback is null, pid = %{public}d",
356                           IPCSkeleton::GetCallingPid());
357             continue;
358         }
359         if (it.second != nullptr) {
360             it.second->OnFlashlightStatusChanged(cameraId, status);
361         }
362     }
363 }
364 
SetCallback(sptr<ICameraServiceCallback> & callback)365 int32_t HCameraService::SetCallback(sptr<ICameraServiceCallback> &callback)
366 {
367     std::lock_guard<std::mutex> lock(cbMutex_);
368     pid_t pid = IPCSkeleton::GetCallingPid();
369     MEDIA_INFO_LOG("HCameraService::SetCallback pid = %{public}d", pid);
370     if (callback == nullptr) {
371         MEDIA_ERR_LOG("HCameraService::SetCallback callback is null");
372         return CAMERA_INVALID_ARG;
373     }
374     auto callbackItem = cameraServiceCallbacks_.find(pid);
375     if (callbackItem != cameraServiceCallbacks_.end()) {
376         callbackItem->second = nullptr;
377         (void)cameraServiceCallbacks_.erase(callbackItem);
378     }
379     cameraServiceCallbacks_.insert(std::make_pair(pid, callback));
380     return CAMERA_OK;
381 }
382 
CloseCameraForDestory(pid_t pid)383 int32_t HCameraService::CloseCameraForDestory(pid_t pid)
384 {
385     std::lock_guard<std::mutex> lock(mapOperatorsLock_);
386     MEDIA_INFO_LOG("HCameraService::CloseCameraForDestory pid = %{public}d, Camera created size = %{public}zu",
387                    pid, camerasForPid_[pid].size());
388     auto cameraIds = camerasForPid_[pid];
389     for (std::set<std::string>::iterator itIds = cameraIds.begin(); itIds != cameraIds.end(); itIds++) {
390         MEDIA_INFO_LOG("HCameraService::CloseCameraForDestory cameraId %{public}s in camerasForPid_[%{public}d]",
391                        (*itIds).c_str(), pid);
392         devicesManager_.Iterate([&](std::string cameraId, sptr<HCameraDevice> cameraDevice) {
393             MEDIA_INFO_LOG("HCameraService::CloseCameraForDestory cameraId %{public}s in devicesManager_",
394                            cameraId.c_str());
395             if (cameraId != *itIds || cameraDevice == nullptr) {
396                 MEDIA_INFO_LOG("HCameraService::CloseCameraForDestory item is null: %{public}d or"
397                                "cameraId not equal: %{public}d {%{public}s, %{public}s}",
398                                cameraDevice == nullptr, cameraId != *itIds, cameraId.c_str(), (*itIds).c_str());
399                 return;
400             } else {
401                 MEDIA_INFO_LOG("HCameraService::CloseCameraForDestory pid = %{public}d,Camera:[%{public}s] need close",
402                                pid, cameraId.c_str());
403                 DeviceClose(cameraDevice);
404                 cameraDevice = nullptr;
405             }
406         });
407     }
408     cameraIds.clear();
409     size_t eraseSize = camerasForPid_.erase(pid);
410     MEDIA_INFO_LOG("HCameraService::CloseCameraForDestory pid: %{public}d cameraIds have removed: %{public}zu",
411                    pid, eraseSize);
412     return CAMERA_OK;
413 }
414 
UnSetMuteCallback(pid_t pid)415 int32_t HCameraService::UnSetMuteCallback(pid_t pid)
416 {
417     std::lock_guard<std::mutex> lock(muteCbMutex_);
418     MEDIA_INFO_LOG("HCameraService::UnSetMuteCallback pid = %{public}d, size = %{public}zu",
419                    pid, cameraMuteServiceCallbacks_.size());
420     if (!cameraMuteServiceCallbacks_.empty()) {
421         MEDIA_INFO_LOG("HCameraDevice::UnSetMuteCallback cameraMuteServiceCallbacks_ is not empty, reset it");
422         auto it = cameraMuteServiceCallbacks_.find(pid);
423         if ((it != cameraMuteServiceCallbacks_.end()) && (it->second)) {
424             it->second = nullptr;
425             cameraMuteServiceCallbacks_.erase(it);
426         }
427     }
428 
429     MEDIA_INFO_LOG("HCameraService::UnSetMuteCallback after erase pid = %{public}d, size = %{public}zu",
430                    pid, cameraMuteServiceCallbacks_.size());
431     return CAMERA_OK;
432 }
433 
UnSetCallback(pid_t pid)434 int32_t HCameraService::UnSetCallback(pid_t pid)
435 {
436     std::lock_guard<std::mutex> lock(cbMutex_);
437     MEDIA_INFO_LOG("HCameraService::UnSetCallback pid = %{public}d, size = %{public}zu",
438                    pid, cameraServiceCallbacks_.size());
439     if (!cameraServiceCallbacks_.empty()) {
440         MEDIA_INFO_LOG("HCameraDevice::SetStatusCallback statusSvcCallbacks_ is not empty, reset it");
441         auto it = cameraServiceCallbacks_.find(pid);
442         if ((it != cameraServiceCallbacks_.end()) && (it->second != nullptr)) {
443             it->second = nullptr;
444             cameraServiceCallbacks_.erase(it);
445         }
446     }
447     MEDIA_INFO_LOG("HCameraService::UnSetCallback after erase pid = %{public}d, size = %{public}zu",
448                    pid, cameraServiceCallbacks_.size());
449     int32_t ret = CAMERA_OK;
450     ret = UnSetMuteCallback(pid);
451     return ret;
452 }
453 
SetMuteCallback(sptr<ICameraMuteServiceCallback> & callback)454 int32_t HCameraService::SetMuteCallback(sptr<ICameraMuteServiceCallback> &callback)
455 {
456     std::lock_guard<std::mutex> lock(muteCbMutex_);
457     pid_t pid = IPCSkeleton::GetCallingPid();
458     if (callback == nullptr) {
459         MEDIA_ERR_LOG("HCameraService::SetMuteCallback callback is null");
460         return CAMERA_INVALID_ARG;
461     }
462     cameraMuteServiceCallbacks_.insert(std::make_pair(pid, callback));
463     return CAMERA_OK;
464 }
465 
IsCameraMuteSupported(std::string cameraId)466 bool HCameraService::IsCameraMuteSupported(std::string cameraId)
467 {
468     bool isMuteSupported = false;
469     std::shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility;
470     int32_t ret = cameraHostManager_->GetCameraAbility(cameraId, cameraAbility);
471     if (ret != CAMERA_OK) {
472         MEDIA_ERR_LOG("HCameraService::IsCameraMuted GetCameraAbility failed");
473         return false;
474     }
475     camera_metadata_item_t item;
476     common_metadata_header_t* metadata = cameraAbility->get();
477     ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_MUTE_MODES, &item);
478     if (ret == CAM_META_SUCCESS) {
479         isMuteSupported = true;
480     } else {
481         isMuteSupported = false;
482         MEDIA_ERR_LOG("HCameraService::IsCameraMuted not find MUTE ability");
483     }
484     MEDIA_DEBUG_LOG("HCameraService::IsCameraMuted supported: %{public}d", isMuteSupported);
485     return isMuteSupported;
486 }
487 
UpdateMuteSetting(sptr<HCameraDevice> cameraDevice,bool muteMode)488 int32_t HCameraService::UpdateMuteSetting(sptr<HCameraDevice> cameraDevice, bool muteMode)
489 {
490     constexpr uint8_t MUTE_ON = 1;
491     constexpr uint8_t MUTE_OFF = 0;
492     constexpr int32_t DEFAULT_ITEMS = 1;
493     constexpr int32_t DEFAULT_DATA_LENGTH = 1;
494     std::shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata =
495         std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
496     bool status = false;
497     int32_t ret;
498     int32_t count = 1;
499     uint8_t mode = muteMode ? MUTE_ON : MUTE_OFF;
500     camera_metadata_item_t item;
501 
502     MEDIA_DEBUG_LOG("UpdateMuteSetting muteMode: %{public}d", muteMode);
503 
504     ret = OHOS::Camera::FindCameraMetadataItem(changedMetadata->get(), OHOS_CONTROL_MUTE_MODE, &item);
505     if (ret == CAM_META_ITEM_NOT_FOUND) {
506         status = changedMetadata->addEntry(OHOS_CONTROL_MUTE_MODE, &mode, count);
507     } else if (ret == CAM_META_SUCCESS) {
508         status = changedMetadata->updateEntry(OHOS_CONTROL_MUTE_MODE, &mode, count);
509     }
510     ret = cameraDevice->UpdateSetting(changedMetadata);
511     if (!status || ret != CAMERA_OK) {
512         MEDIA_ERR_LOG("UpdateMuteSetting muteMode Failed");
513         return CAMERA_UNKNOWN_ERROR;
514     }
515     return CAMERA_OK;
516 }
517 
MuteCamera(bool muteMode)518 int32_t HCameraService::MuteCamera(bool muteMode)
519 {
520     OHOS::Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
521     int32_t ret = CheckPermission(OHOS_PERMISSION_MANAGE_CAMERA_CONFIG, callerToken);
522     if (ret != CAMERA_OK) {
523         MEDIA_ERR_LOG("CheckPermission is failed!");
524         return ret;
525     }
526 
527     bool oldMuteMode = muteMode_;
528     if (muteMode == oldMuteMode) {
529         return CAMERA_OK;
530     } else {
531         muteMode_ = muteMode;
532     }
533     if (devicesManager_.IsEmpty()) {
534         if (!cameraMuteServiceCallbacks_.empty()) {
535             for (auto cb : cameraMuteServiceCallbacks_) {
536                 cb.second->OnCameraMute(muteMode);
537                 CAMERA_SYSEVENT_BEHAVIOR(CreateMsg("OnCameraMute! current Camera muteMode:%d", muteMode));
538             }
539         }
540         return CAMERA_OK;
541     }
542     bool isCameraMuteSuccess = true;
543     devicesManager_.Iterate([&](std::string cameraId, sptr<HCameraDevice> cameraDevice) {
544         if (!isCameraMuteSuccess) {
545             return;
546         }
547         if (!IsCameraMuteSupported(cameraId)) {
548             isCameraMuteSuccess = false;
549             MEDIA_ERR_LOG("Not Supported Mute,cameraId: %{public}s", cameraId.c_str());
550             return;
551         }
552         if (cameraDevice != nullptr) {
553             ret = UpdateMuteSetting(cameraDevice, muteMode);
554         }
555         if (ret != CAMERA_OK) {
556             MEDIA_ERR_LOG("UpdateMuteSetting Failed, cameraId: %{public}s", cameraId.c_str());
557             muteMode_ = oldMuteMode;
558             isCameraMuteSuccess = false;
559         }
560     });
561     if (!cameraMuteServiceCallbacks_.empty() && ret == CAMERA_OK) {
562         for (auto cb : cameraMuteServiceCallbacks_) {
563             if (cb.second) {
564                 cb.second->OnCameraMute(muteMode);
565             }
566             CAMERA_SYSEVENT_BEHAVIOR(CreateMsg("OnCameraMute! current Camera muteMode:%d", muteMode));
567         }
568     }
569     return ret;
570 }
571 
PrelaunchCamera()572 int32_t HCameraService::PrelaunchCamera()
573 {
574     CAMERA_SYNC_TRACE;
575     MEDIA_INFO_LOG("HCameraService::PrelaunchCamera");
576     if (preCameraId_.empty()) {
577         std::vector<std::string> cameraIds_;
578         cameraHostManager_->GetCameras(cameraIds_);
579         if (cameraIds_.empty()) {
580             return CAMERA_OK;
581         }
582         preCameraId_= cameraIds_.front();
583     }
584     MEDIA_INFO_LOG("HCameraService::PrelaunchCamera preCameraId_ is: %{public}s", preCameraId_.c_str());
585     CAMERA_SYSEVENT_STATISTIC(CreateMsg("Camera Prelaunch CameraId:%s", preCameraId_.c_str()));
586     int32_t ret = cameraHostManager_->Prelaunch(preCameraId_);
587     if (ret != CAMERA_OK) {
588         MEDIA_ERR_LOG("HCameraService::Prelaunch failed");
589     }
590     return ret;
591 }
592 
593 
SetPrelaunchConfig(std::string cameraId)594 int32_t HCameraService::SetPrelaunchConfig(std::string cameraId)
595 {
596     CAMERA_SYNC_TRACE;
597     OHOS::Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
598     std::string permissionName = OHOS_PERMISSION_CAMERA;
599     int32_t ret = CheckPermission(permissionName, callerToken);
600     if (ret != CAMERA_OK) {
601         MEDIA_ERR_LOG("HCameraService::SetPrelaunchConfig failed permission is: %{public}s", permissionName.c_str());
602         return ret;
603     }
604 
605     MEDIA_INFO_LOG("HCameraService::SetPrelaunchConfig");
606     std::vector<std::string> cameraIds_;
607     cameraHostManager_->GetCameras(cameraIds_);
608     if ((find(cameraIds_.begin(), cameraIds_.end(), cameraId) != cameraIds_.end()) && IsPrelaunchSupported(cameraId)) {
609         preCameraId_ = cameraId;
610     } else {
611         MEDIA_ERR_LOG("HCameraService::SetPrelaunchConfig illegal");
612         ret = CAMERA_INVALID_ARG;
613     }
614     return ret;
615 }
616 
IsPrelaunchSupported(std::string cameraId)617 bool HCameraService::IsPrelaunchSupported(std::string cameraId)
618 {
619     bool isPrelaunchSupported = false;
620     std::shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility;
621     int32_t ret = cameraHostManager_->GetCameraAbility(cameraId, cameraAbility);
622     if (ret != CAMERA_OK) {
623         MEDIA_ERR_LOG("HCameraService::IsCameraMuted GetCameraAbility failed");
624         return isPrelaunchSupported;
625     }
626     camera_metadata_item_t item;
627     common_metadata_header_t* metadata = cameraAbility->get();
628     ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_PRELAUNCH_AVAILABLE, &item);
629     if (ret == 0) {
630         MEDIA_INFO_LOG("CameraManager::IsPrelaunchSupported() OHOS_ABILITY_PRELAUNCH_AVAILABLE is %{public}d",
631                        item.data.u8[0]);
632         isPrelaunchSupported = (item.data.u8[0] == 1);
633     } else {
634         MEDIA_ERR_LOG("Failed to get OHOS_ABILITY_PRELAUNCH_AVAILABLE ret = %{public}d", ret);
635     }
636     return isPrelaunchSupported;
637 }
638 
IsCameraMuted(bool & muteMode)639 int32_t HCameraService::IsCameraMuted(bool &muteMode)
640 {
641     muteMode = muteMode_;
642     MEDIA_DEBUG_LOG("HCameraService::IsCameraMuted success. isMuted: %{public}d", muteMode);
643     return CAMERA_OK;
644 }
645 
CameraSummary(std::vector<std::string> cameraIds,std::string & dumpString)646 void HCameraService::CameraSummary(std::vector<std::string> cameraIds,
647     std::string& dumpString)
648 {
649     dumpString += "# Number of Cameras:[" + std::to_string(cameraIds.size()) + "]:\n";
650     dumpString += "# Number of Active Cameras:[" + std::to_string(devicesManager_.Size()) + "]:\n";
651     HCaptureSession::CameraSessionSummary(dumpString);
652 }
653 
CameraDumpAbility(common_metadata_header_t * metadataEntry,std::string & dumpString)654 void HCameraService::CameraDumpAbility(common_metadata_header_t* metadataEntry, std::string& dumpString)
655 {
656     camera_metadata_item_t item;
657     int ret;
658     dumpString += "    ## Camera Ability List: \n";
659 
660     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_CAMERA_POSITION, &item);
661     if (ret == CAM_META_SUCCESS) {
662         std::map<int, std::string>::const_iterator iter =
663             g_cameraPos.find(item.data.u8[0]);
664         if (iter != g_cameraPos.end()) {
665             dumpString += "        Camera Position:["
666                 + iter->second
667                 + "]:    ";
668         }
669     }
670 
671     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_CAMERA_TYPE, &item);
672     if (ret == CAM_META_SUCCESS) {
673         std::map<int, std::string>::const_iterator iter =
674             g_cameraType.find(item.data.u8[0]);
675         if (iter != g_cameraType.end()) {
676             dumpString += "Camera Type:["
677                 + iter->second
678                 + "]:    ";
679         }
680     }
681 
682     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_CAMERA_CONNECTION_TYPE, &item);
683     if (ret == CAM_META_SUCCESS) {
684         std::map<int, std::string>::const_iterator iter =
685             g_cameraConType.find(item.data.u8[0]);
686         if (iter != g_cameraConType.end()) {
687             dumpString += "Camera Connection Type:["
688                 + iter->second
689                 + "]:\n";
690         }
691     }
692 }
693 
CameraDumpStreaminfo(common_metadata_header_t * metadataEntry,std::string & dumpString)694 void HCameraService::CameraDumpStreaminfo(common_metadata_header_t* metadataEntry, std::string& dumpString)
695 {
696     camera_metadata_item_t item;
697     int ret;
698     constexpr uint32_t unitLen = 3;
699     uint32_t widthOffset = 1;
700     uint32_t heightOffset = 2;
701     dumpString += "        ### Camera Available stream configuration List: \n";
702     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry,
703                                                OHOS_ABILITY_STREAM_AVAILABLE_BASIC_CONFIGURATIONS, &item);
704     if (ret == CAM_META_SUCCESS) {
705         dumpString += "            Number Stream Info: "
706             + std::to_string(item.count/unitLen) + "\n";
707         for (uint32_t index = 0; index < item.count; index += unitLen) {
708             std::map<int, std::string>::const_iterator iter =
709                 g_cameraFormat.find(item.data.i32[index]);
710             if (iter != g_cameraFormat.end()) {
711                 dumpString += "            Format:["
712                         + iter->second
713                         + "]:    ";
714                 dumpString += "Size:[Width:"
715                         + std::to_string(item.data.i32[index + widthOffset])
716                         + " Height:"
717                         + std::to_string(item.data.i32[index + heightOffset])
718                         + "]:\n";
719             }
720         }
721     }
722 }
723 
CameraDumpZoom(common_metadata_header_t * metadataEntry,std::string & dumpString)724 void HCameraService::CameraDumpZoom(common_metadata_header_t* metadataEntry, std::string& dumpString)
725 {
726     dumpString += "    ## Zoom Related Info: \n";
727     camera_metadata_item_t item;
728     int ret;
729     int32_t minIndex = 0;
730     int32_t maxIndex = 1;
731     uint32_t zoomRangeCount = 2;
732     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_ZOOM_CAP, &item);
733     if ((ret == CAM_META_SUCCESS) && (item.count == zoomRangeCount)) {
734         dumpString += "        Available Zoom Capability:["
735             + std::to_string(item.data.i32[minIndex]) + "  "
736             + std::to_string(item.data.i32[maxIndex])
737             + "]:\n";
738     }
739 
740     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_SCENE_ZOOM_CAP, &item);
741     if ((ret == CAM_META_SUCCESS) && (item.count == zoomRangeCount)) {
742         dumpString += "        Available scene Zoom Capability:["
743             + std::to_string(item.data.i32[minIndex]) + "  "
744             + std::to_string(item.data.i32[maxIndex])
745             + "]:\n";
746     }
747 
748     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_ZOOM_RATIO_RANGE, &item);
749     if ((ret == CAM_META_SUCCESS) && (item.count == zoomRangeCount)) {
750         dumpString += "        Available Zoom Ratio Range:["
751             + std::to_string(item.data.f[minIndex])
752             + std::to_string(item.data.f[maxIndex])
753             + "]:\n";
754     }
755 
756     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_CONTROL_ZOOM_RATIO, &item);
757     if (ret == CAM_META_SUCCESS) {
758         dumpString += "        Set Zoom Ratio:["
759             + std::to_string(item.data.f[0])
760             + "]:\n";
761     }
762 }
763 
CameraDumpFlash(common_metadata_header_t * metadataEntry,std::string & dumpString)764 void HCameraService::CameraDumpFlash(common_metadata_header_t* metadataEntry, std::string& dumpString)
765 {
766     camera_metadata_item_t item;
767     int ret;
768     dumpString += "    ## Flash Related Info: \n";
769     dumpString += "        Available Flash Modes:[";
770     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_FLASH_MODES, &item);
771     if (ret == CAM_META_SUCCESS) {
772         for (uint32_t i = 0; i < item.count; i++) {
773             std::map<int, std::string>::const_iterator iter =
774                 g_cameraFlashMode.find(item.data.u8[i]);
775             if (iter != g_cameraFlashMode.end()) {
776                 dumpString += " " + iter->second;
777             }
778         }
779         dumpString += "]:\n";
780     }
781 
782     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_CONTROL_FLASH_MODE, &item);
783     if (ret == CAM_META_SUCCESS) {
784         std::map<int, std::string>::const_iterator iter =
785             g_cameraFlashMode.find(item.data.u8[0]);
786         if (iter != g_cameraFlashMode.end()) {
787             dumpString += "        Set Flash Mode:["
788                 + iter->second
789                 + "]:\n";
790         }
791     }
792 }
793 
CameraDumpAF(common_metadata_header_t * metadataEntry,std::string & dumpString)794 void HCameraService::CameraDumpAF(common_metadata_header_t* metadataEntry, std::string& dumpString)
795 {
796     camera_metadata_item_t item;
797     int ret;
798     dumpString += "    ## AF Related Info: \n";
799     dumpString += "        Available Focus Modes:[";
800 
801     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_FOCUS_MODES, &item);
802     if (ret == CAM_META_SUCCESS) {
803         for (uint32_t i = 0; i < item.count; i++) {
804             std::map<int, std::string>::const_iterator iter =
805                 g_cameraFocusMode.find(item.data.u8[i]);
806             if (iter != g_cameraFocusMode.end()) {
807                 dumpString += " " + iter->second;
808             }
809         }
810         dumpString += "]:\n";
811     }
812 
813     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_CONTROL_FOCUS_MODE, &item);
814     if (ret == CAM_META_SUCCESS) {
815         std::map<int, std::string>::const_iterator iter =
816             g_cameraFocusMode.find(item.data.u8[0]);
817         if (iter != g_cameraFocusMode.end()) {
818             dumpString += "        Set Focus Mode:["
819                 + iter->second
820                 + "]:\n";
821         }
822     }
823 }
824 
CameraDumpAE(common_metadata_header_t * metadataEntry,std::string & dumpString)825 void HCameraService::CameraDumpAE(common_metadata_header_t* metadataEntry, std::string& dumpString)
826 {
827     camera_metadata_item_t item;
828     int ret;
829     dumpString += "    ## AE Related Info: \n";
830     dumpString += "        Available Exposure Modes:[";
831 
832     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_EXPOSURE_MODES, &item);
833     if (ret == CAM_META_SUCCESS) {
834         for (uint32_t i = 0; i < item.count; i++) {
835             std::map<int, std::string>::const_iterator iter =
836                 g_cameraExposureMode.find(item.data.u8[i]);
837             if (iter != g_cameraExposureMode.end()) {
838                 dumpString += " " + iter->second;
839             }
840         }
841         dumpString += "]:\n";
842     }
843 
844     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_CONTROL_EXPOSURE_MODE, &item);
845     if (ret == CAM_META_SUCCESS) {
846         std::map<int, std::string>::const_iterator iter =
847             g_cameraExposureMode.find(item.data.u8[0]);
848         if (iter != g_cameraExposureMode.end()) {
849             dumpString += "        Set exposure Mode:["
850                 + iter->second
851                 + "]:\n";
852         }
853     }
854 }
855 
CameraDumpSensorInfo(common_metadata_header_t * metadataEntry,std::string & dumpString)856 void HCameraService::CameraDumpSensorInfo(common_metadata_header_t* metadataEntry, std::string& dumpString)
857 {
858     camera_metadata_item_t item;
859     int ret;
860     dumpString += "    ## Sensor Info Info: \n";
861     int32_t leftIndex = 0;
862     int32_t topIndex = 1;
863     int32_t rightIndex = 2;
864     int32_t bottomIndex = 3;
865     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_SENSOR_INFO_ACTIVE_ARRAY_SIZE, &item);
866     if (ret == CAM_META_SUCCESS) {
867         dumpString += "        Array:["
868             + std::to_string(item.data.i32[leftIndex]) + " "
869             + std::to_string(item.data.i32[topIndex]) + " "
870             + std::to_string(item.data.i32[rightIndex]) + " "
871             + std::to_string(item.data.i32[bottomIndex])
872             + "]:\n";
873     }
874 }
875 
CameraDumpVideoStabilization(common_metadata_header_t * metadataEntry,std::string & dumpString)876 void HCameraService::CameraDumpVideoStabilization(common_metadata_header_t* metadataEntry, std::string& dumpString)
877 {
878     camera_metadata_item_t item;
879     int ret;
880     dumpString += "    ## Video Stabilization Related Info: \n";
881     dumpString += "        Available Video Stabilization Modes:[";
882 
883     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_VIDEO_STABILIZATION_MODES, &item);
884     if (ret == CAM_META_SUCCESS) {
885         for (uint32_t i = 0; i < item.count; i++) {
886             std::map<int, std::string>::const_iterator iter =
887                 g_cameraVideoStabilizationMode.find(item.data.u8[i]);
888             if (iter != g_cameraVideoStabilizationMode.end()) {
889                 dumpString += " " + iter->second;
890             }
891         }
892         dumpString += "]:\n";
893     }
894 
895     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_CONTROL_VIDEO_STABILIZATION_MODE, &item);
896     if (ret == CAM_META_SUCCESS) {
897         std::map<int, std::string>::const_iterator iter =
898             g_cameraVideoStabilizationMode.find(item.data.u8[0]);
899         if (iter != g_cameraVideoStabilizationMode.end()) {
900             dumpString += "        Set Stabilization Mode:["
901                 + iter->second
902                 + "]:\n";
903         }
904     }
905 }
906 
CameraDumpVideoFrameRateRange(common_metadata_header_t * metadataEntry,std::string & dumpString)907 void HCameraService::CameraDumpVideoFrameRateRange(common_metadata_header_t* metadataEntry, std::string& dumpString)
908 {
909     camera_metadata_item_t item;
910     const int32_t FRAME_RATE_RANGE_STEP = 2;
911     int ret;
912     dumpString += "    ## Video FrameRateRange Related Info: \n";
913     dumpString += "        Available FrameRateRange :\n";
914 
915     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_FPS_RANGES, &item);
916     if (ret == CAM_META_SUCCESS) {
917         for (uint32_t i = 0; i < (item.count - 1); i += FRAME_RATE_RANGE_STEP) {
918             dumpString += "            [ " + std::to_string(item.data.i32[i]) + ", " +
919                           std::to_string(item.data.i32[i+1]) + " ]\n";
920         }
921         dumpString += "\n";
922     }
923 }
924 
CameraDumpPrelaunch(common_metadata_header_t * metadataEntry,std::string & dumpString)925 void HCameraService::CameraDumpPrelaunch(common_metadata_header_t* metadataEntry, std::string& dumpString)
926 {
927     camera_metadata_item_t item;
928     int ret;
929     dumpString += "    ## Camera Prelaunch Related Info: \n";
930     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_PRELAUNCH_AVAILABLE, &item);
931     if (ret == CAM_META_SUCCESS) {
932         std::map<int, std::string>::const_iterator iter =
933             g_cameraPrelaunchAvailable.find(item.data.u8[0]);
934         if (iter != g_cameraPrelaunchAvailable.end()) {
935             dumpString += "        Available Prelaunch Info:["
936                 + iter->second
937                 + "]:\n";
938         }
939     }
940 }
941 
CameraDumpThumbnail(common_metadata_header_t * metadataEntry,std::string & dumpString)942 void HCameraService::CameraDumpThumbnail(common_metadata_header_t* metadataEntry, std::string& dumpString)
943 {
944     camera_metadata_item_t item;
945     int ret;
946     dumpString += "    ## Camera Thumbnail Related Info: \n";
947     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_STREAM_QUICK_THUMBNAIL_AVAILABLE, &item);
948     if (ret == CAM_META_SUCCESS) {
949         std::map<int, std::string>::const_iterator iter =
950             g_cameraQuickThumbnailAvailable.find(item.data.u8[0]);
951         if (iter != g_cameraQuickThumbnailAvailable.end()) {
952             dumpString += "        Available Thumbnail Info:["
953                 + iter->second
954                 + "]:\n";
955         }
956     }
957 }
958 
Dump(int fd,const std::vector<std::u16string> & args)959 int32_t HCameraService::Dump(int fd, const std::vector<std::u16string>& args)
960 {
961     std::unordered_set<std::u16string> argSets;
962     std::u16string arg1(u"summary");
963     std::u16string arg2(u"ability");
964     std::u16string arg3(u"clientwiseinfo");
965     for (decltype(args.size()) index = 0; index < args.size(); ++index) {
966         argSets.insert(args[index]);
967     }
968     std::string dumpString;
969     std::vector<std::string> cameraIds;
970     std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> cameraAbilityList;
971     int32_t capIdx = 0;
972     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata;
973     int ret;
974 
975     ret = GetCameras(cameraIds, cameraAbilityList);
976     if ((ret != CAMERA_OK) || cameraIds.empty() || (cameraAbilityList.empty())) {
977         return CAMERA_INVALID_STATE;
978     }
979     if (args.size() == 0 || argSets.count(arg1) != 0) {
980         dumpString += "-------- Summary -------\n";
981         CameraSummary(cameraIds, dumpString);
982     }
983     if (args.size() == 0 || argSets.count(arg2) != 0) {
984         dumpString += "-------- CameraDevice -------\n";
985         for (auto& it : cameraIds) {
986             metadata = cameraAbilityList[capIdx++];
987             common_metadata_header_t* metadataEntry = metadata->get();
988             dumpString += "# Camera ID:[" + it + "]: \n";
989             CameraDumpAbility(metadataEntry, dumpString);
990             CameraDumpStreaminfo(metadataEntry, dumpString);
991             CameraDumpZoom(metadataEntry, dumpString);
992             CameraDumpFlash(metadataEntry, dumpString);
993             CameraDumpAF(metadataEntry, dumpString);
994             CameraDumpAE(metadataEntry, dumpString);
995             CameraDumpSensorInfo(metadataEntry, dumpString);
996             CameraDumpVideoStabilization(metadataEntry, dumpString);
997             CameraDumpVideoFrameRateRange(metadataEntry, dumpString);
998             CameraDumpPrelaunch(metadataEntry, dumpString);
999             CameraDumpThumbnail(metadataEntry, dumpString);
1000         }
1001     }
1002     if (args.size() == 0 || argSets.count(arg3) != 0) {
1003         dumpString += "-------- Clientwise Info -------\n";
1004         HCaptureSession::dumpSessions(dumpString);
1005     }
1006 
1007     if (dumpString.size() == 0) {
1008         MEDIA_ERR_LOG("Dump string empty!");
1009         return CAMERA_INVALID_STATE;
1010     }
1011 
1012     (void)write(fd, dumpString.c_str(), dumpString.size());
1013     return CAMERA_OK;
1014 }
1015 
DeviceOpen(const std::string & cameraId)1016 int32_t HCameraService::DeviceOpen(const std::string& cameraId)
1017 {
1018     MEDIA_INFO_LOG("HCameraService::DeviceOpen Enter");
1019     int32_t ret = CAMERA_OK;
1020     sptr<HCameraDevice> cameraDevice = nullptr;
1021     if (devicesManager_.Find(cameraId, cameraDevice)) {
1022         MEDIA_INFO_LOG("HCameraService::DeviceOpen Camera:[%{public}s] need open", cameraId.c_str());
1023         if (cameraDevice != nullptr && !cameraDevice->IsOpenedCameraDevice()) {
1024             ret = cameraDevice->OpenDevice();
1025         } else {
1026             MEDIA_ERR_LOG("HCameraService::DeviceOpen device is null");
1027         }
1028     }
1029     MEDIA_INFO_LOG("HCameraService::DeviceOpen Exit");
1030     return ret;
1031 }
1032 
DeviceClose(sptr<HCameraDevice> cameraDevice)1033 int32_t HCameraService::DeviceClose(sptr<HCameraDevice> cameraDevice)
1034 {
1035     MEDIA_INFO_LOG("HCameraService::DeviceClose Enter");
1036     int32_t ret = CAMERA_OK;
1037     std::string cameraId;
1038     pid_t pid = IPCSkeleton::GetCallingPid();
1039     if (cameraDevice != nullptr && cameraDevice->IsOpenedCameraDevice()) {
1040         cameraId = cameraDevice->GetCameraId();
1041         MEDIA_INFO_LOG("HCameraService::DeviceClose pid = %{public}d Camera:[%{public}s] need close",
1042             pid, cameraId.c_str());
1043         ret = cameraDevice->CloseDevice();
1044         cameraDevice = nullptr;
1045     }
1046 
1047     for (auto& it : camerasForPid_) {
1048         std::set<std::string>& cameraIds = it.second;
1049         MEDIA_INFO_LOG("HCameraService::DeviceClose pid = %{public}d size %{public}zu E", it.first, cameraIds.size());
1050         if (!cameraIds.empty()) {
1051             for (std::set<std::string>::iterator itIds = cameraIds.begin(); itIds != cameraIds.end(); itIds++) {
1052                 if (*itIds == cameraId && !IsInForeGround(it.first)) {
1053                     cameraIds.erase(itIds);
1054                     break;
1055                 }
1056             }
1057         }
1058         MEDIA_INFO_LOG("HCameraService::DeviceClose pid = %{public}d size %{public}zu X", it.first, cameraIds.size());
1059     }
1060     MEDIA_INFO_LOG("HCameraService::DeviceClose Exit");
1061     return  ret;
1062 }
1063 
DeviceClose(const std::string & cameraId,pid_t pidFromSession)1064 int32_t HCameraService::DeviceClose(const std::string& cameraId, pid_t pidFromSession)
1065 {
1066     std::lock_guard<std::mutex> lock(mapOperatorsLock_);
1067     MEDIA_INFO_LOG("HCameraService::DeviceClose Enter");
1068     int32_t ret = CAMERA_OK;
1069 
1070     pid_t pid = pidFromSession != 0 ? pidFromSession : IPCSkeleton::GetCallingPid();
1071     sptr<HCameraDevice> cameraDevice = nullptr;
1072     if (devicesManager_.Find(cameraId, cameraDevice)) {
1073         MEDIA_INFO_LOG("HCameraService::DeviceClose pid = %{public}d Camera:[%{public}s] need close",
1074             pid, cameraId.c_str());
1075         if (cameraDevice != nullptr && cameraDevice->IsOpenedCameraDevice()) {
1076             ret = cameraDevice->CloseDevice();
1077             cameraDevice = nullptr;
1078         }
1079     }
1080 
1081     for (auto& it : camerasForPid_) {
1082         std::set<std::string>& cameraIds = it.second;
1083         MEDIA_INFO_LOG("HCameraService::DeviceClose pid = %{public}d size %{public}zu E", it.first, cameraIds.size());
1084         if (!cameraIds.empty()) {
1085             for (std::set<std::string>::iterator itIds = cameraIds.begin(); itIds != cameraIds.end(); itIds++) {
1086                 if (*itIds == cameraId && !IsInForeGround(it.first)) {
1087                     cameraIds.erase(itIds);
1088                     break;
1089                 }
1090             }
1091         }
1092         MEDIA_INFO_LOG("HCameraService::DeviceClose pid = %{public}d size %{public}zu X", it.first, cameraIds.size());
1093     }
1094     MEDIA_INFO_LOG("HCameraService::DeviceClose Exit");
1095     return  ret;
1096 }
1097 
IsDeviceAlreadyOpen(pid_t & tempPid,std::string & tempCameraId,sptr<HCameraDevice> & tempDevice)1098 bool HCameraService::IsDeviceAlreadyOpen(pid_t& tempPid, std::string& tempCameraId, sptr<HCameraDevice> &tempDevice)
1099 {
1100     bool isOpened = false;
1101     devicesManager_.Iterate([&](std::string cameraId, sptr<HCameraDevice> cameraDevice) {
1102         if (isOpened) {
1103             return;
1104         }
1105         if (cameraDevice != nullptr) {
1106             isOpened = cameraDevice->IsOpenedCameraDevice();
1107             MEDIA_INFO_LOG("HCameraService::IsDeviceAlreadyOpen cameraId: %{public}s opened %{public}d",
1108                 cameraId.c_str(), isOpened);
1109             tempCameraId = cameraId;
1110             tempDevice = cameraDevice;
1111         }
1112     });
1113 
1114     if (isOpened) {
1115         for (auto it : camerasForPid_) {
1116             std::set<std::string> cameraIds = it.second;
1117             if (cameraIds.size() > 0 && cameraIds.find(tempCameraId) != cameraIds.end()) {
1118                 tempPid = it.first;
1119                 break;
1120             }
1121         }
1122         MEDIA_INFO_LOG("HCameraService::IsDeviceAlreadyOpen pid: %{public}d cameraId: %{public}s opened %{public}d",
1123             tempPid, tempCameraId.c_str(), isOpened);
1124     }
1125     return isOpened;
1126 }
1127 
CameraConflictDetection(const std::string & cameraId,bool & isPermisson)1128 std::vector<sptr<HCameraDevice>> HCameraService::CameraConflictDetection(const std::string& cameraId, bool& isPermisson)
1129 {
1130     std::vector<sptr<HCameraDevice>> devicesNeedClose;
1131     pid_t tempPid;
1132     std::string tempCameraId;
1133     sptr<HCameraDevice> tempDevice = nullptr;
1134     std::lock_guard<std::mutex> lock(mapOperatorsLock_);
1135     pid_t pid = IPCSkeleton::GetCallingPid();
1136     /*  whether there is a device being used, if not, the current operation is allowed */
1137     if (!IsDeviceAlreadyOpen(tempPid, tempCameraId, tempDevice)) {
1138         MEDIA_INFO_LOG("There is no clients use device, allowed!");
1139         isPermisson = true;
1140         return devicesNeedClose;
1141     }
1142 
1143     MEDIA_INFO_LOG("HCameraService::CameraConflictDetection pid: %{public}d cameraId: %{public}s already opened",
1144                    tempPid, tempCameraId.c_str());
1145     /*
1146      *  whether the application that is using the device is the same application
1147      *  as the application currently operating, if they are the same, the operation will be rejected
1148      */
1149     if (IsSameClient(tempPid, pid)) {
1150         MEDIA_INFO_LOG("Same client, reject!");
1151         isPermisson = false;
1152         return devicesNeedClose;
1153     }
1154 
1155     /*
1156      *  1. if it is judged that the application that is using the device is in the background,
1157      *     it is necessary to close the used device and allow this operation to seize the device.
1158      *  2. The application that is using the device is in the foreground, and the priority is judged;
1159      *     If there is a conflict, the operation is rejected; otherwise,
1160      *     the operation is allowed to preempt the device, and the device in use needs to be close.
1161      */
1162     if (tempDevice != nullptr) {
1163         if (IsCameraNeedClose(tempDevice->GetCallerToken(), tempPid, pid)) {
1164             isPermisson = true;
1165             devicesNeedClose.push_back(tempDevice);
1166             MEDIA_INFO_LOG("HCameraService::CameraConflictDetection device can be preempted, allowed!");
1167         } else {
1168             isPermisson = false;
1169         }
1170     }
1171     return devicesNeedClose;
1172 }
1173 } // namespace CameraStandard
1174 } // namespace OHOS
1175