• 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 <algorithm>
19 #include <memory>
20 #include <mutex>
21 #include <parameter.h>
22 #include <parameters.h>
23 #include <securec.h>
24 #include <string>
25 #include <unordered_set>
26 #include <vector>
27 
28 #include "access_token.h"
29 #ifdef NOTIFICATION_ENABLE
30 #include "camera_beauty_notification.h"
31 #endif
32 #include "camera_info_dumper.h"
33 #include "camera_log.h"
34 #include "camera_report_uitls.h"
35 #include "camera_util.h"
36 #include "camera_common_event_manager.h"
37 #include "datashare_predicates.h"
38 #include "deferred_processing_service.h"
39 #include "hcamera_preconfig.h"
40 #include "hcamera_session_manager.h"
41 #include "icamera_service_callback.h"
42 #ifdef DEVICE_MANAGER
43 #include "device_manager.h"
44 #endif
45 #include "hcamera_device_manager.h"
46 #include "hstream_operator_manager.h"
47 #include "ipc_skeleton.h"
48 #include "iservice_registry.h"
49 #include "os_account_manager.h"
50 #include "system_ability_definition.h"
51 #include "tokenid_kit.h"
52 #include "uri.h"
53 
54 namespace OHOS {
55 namespace CameraStandard {
56 REGISTER_SYSTEM_ABILITY_BY_ID(HCameraService, CAMERA_SERVICE_ID, true)
57 constexpr uint8_t POSITION_FOLD_INNER = 3;
58 constexpr uint32_t ROOT_UID = 0;
59 constexpr uint32_t FACE_CLIENT_UID = 1088;
60 constexpr uint32_t RSS_UID = 1096;
61 static sptr<HCameraService> g_cameraServiceHolder = nullptr;
62 static bool g_isFoldScreen = system::GetParameter("const.window.foldscreen.type", "") != "";
63 
64 std::vector<uint32_t> restoreMetadataTag { // item.type is uint8
65     OHOS_CONTROL_VIDEO_STABILIZATION_MODE,
66     OHOS_CONTROL_DEFERRED_IMAGE_DELIVERY,
67     OHOS_CONTROL_SUPPORTED_COLOR_MODES,
68     OHOS_CONTROL_PORTRAIT_EFFECT_TYPE,
69     OHOS_CONTROL_FILTER_TYPE,
70     OHOS_CONTROL_EFFECT_SUGGESTION,
71     OHOS_CONTROL_MOTION_DETECTION,
72     OHOS_CONTROL_HIGH_QUALITY_MODE,
73     OHOS_CONTROL_CAMERA_USED_AS_POSITION,
74     OHOS_CONTROL_MOVING_PHOTO,
75     OHOS_CONTROL_AUTO_CLOUD_IMAGE_ENHANCE,
76     OHOS_CONTROL_BEAUTY_TYPE,
77     OHOS_CONTROL_BEAUTY_AUTO_VALUE,
78     OHOS_CONTROL_FOCUS_DRIVEN_TYPE,
79     OHOS_CONTROL_COLOR_RESERVATION_TYPE,
80     OHOS_CONTROL_FOCUS_RANGE_TYPE,
81     OHOS_CONTROL_CAMERA_VIRTUAL_APERTURE_VALUE,
82 };
83 mutex g_dataShareHelperMutex;
84 mutex g_dmDeviceInfoMutex;
85 thread_local uint32_t g_dumpDepth = 0;
86 
HCameraService(int32_t systemAbilityId,bool runOnCreate)87 HCameraService::HCameraService(int32_t systemAbilityId, bool runOnCreate)
88     : SystemAbility(systemAbilityId, runOnCreate), muteModeStored_(false)
89 {
90     MEDIA_INFO_LOG("HCameraService Construct begin");
91     g_cameraServiceHolder = this;
92     unique_ptr<CameraRotateStrategyParser> cameraRotateStrategyParser = make_unique<CameraRotateStrategyParser>();
93     cameraRotateStrategyParser->LoadConfiguration();
94     cameraRotateStrategyInfos_ = cameraRotateStrategyParser->GetCameraRotateStrategyInfos();
95     cameraRotateStrategyParser->Destroy();
96     statusCallback_ = std::make_shared<ServiceHostStatus>(this);
97     cameraHostManager_ = new (std::nothrow) HCameraHostManager(statusCallback_);
98     CHECK_ERROR_RETURN_LOG(
99         cameraHostManager_ == nullptr, "HCameraService OnStart failed to create HCameraHostManager obj");
100     MEDIA_INFO_LOG("HCameraService Construct end");
101     serviceStatus_ = CameraServiceStatus::SERVICE_NOT_READY;
102 }
103 
HCameraService(sptr<HCameraHostManager> cameraHostManager)104 HCameraService::HCameraService(sptr<HCameraHostManager> cameraHostManager)
105     : cameraHostManager_(cameraHostManager), muteModeStored_(false)
106 {}
107 
~HCameraService()108 HCameraService::~HCameraService() {}
109 
110 #ifdef DEVICE_MANAGER
111 class HCameraService::DeviceInitCallBack : public DistributedHardware::DmInitCallback {
112     void OnRemoteDied() override;
113 };
114 
OnRemoteDied()115 void HCameraService::DeviceInitCallBack::OnRemoteDied()
116 {
117     MEDIA_INFO_LOG("CameraManager::DeviceInitCallBack OnRemoteDied");
118 }
119 #endif
120 
OnStart()121 void HCameraService::OnStart()
122 {
123     MEDIA_INFO_LOG("HCameraService OnStart begin");
124     CHECK_ERROR_PRINT_LOG(cameraHostManager_->Init() != CAMERA_OK,
125         "HCameraService OnStart failed to init camera host manager.");
126     // initialize deferred processing service.
127     DeferredProcessing::DeferredProcessingService::GetInstance().Initialize();
128     DeferredProcessing::DeferredProcessingService::GetInstance().Start();
129 
130     cameraDataShareHelper_ = std::make_shared<CameraDataShareHelper>();
131     AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
132 #ifdef NOTIFICATION_ENABLE
133     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
134 #endif
135     if (Publish(this)) {
136         MEDIA_INFO_LOG("HCameraService publish OnStart sucess");
137     } else {
138         MEDIA_INFO_LOG("HCameraService publish OnStart failed");
139     }
140     MEDIA_INFO_LOG("HCameraService OnStart end");
141 }
142 
OnDump()143 void HCameraService::OnDump()
144 {
145     MEDIA_INFO_LOG("HCameraService::OnDump called");
146 }
147 
OnStop()148 void HCameraService::OnStop()
149 {
150     MEDIA_INFO_LOG("HCameraService::OnStop called");
151     cameraHostManager_->DeInit();
152     UnregisterFoldStatusListener();
153     DeferredProcessing::DeferredProcessingService::GetInstance().Stop();
154 }
155 
GetMuteModeFromDataShareHelper(bool & muteMode)156 int32_t HCameraService::GetMuteModeFromDataShareHelper(bool &muteMode)
157 {
158     lock_guard<mutex> lock(g_dataShareHelperMutex);
159     CHECK_ERROR_RETURN_RET_LOG(cameraDataShareHelper_ == nullptr, CAMERA_INVALID_ARG,
160         "GetMuteModeFromDataShareHelper NULL");
161     std::string value = "";
162     auto ret = cameraDataShareHelper_->QueryOnce(PREDICATES_STRING, value);
163     MEDIA_INFO_LOG("GetMuteModeFromDataShareHelper Query ret = %{public}d, value = %{public}s", ret, value.c_str());
164     CHECK_ERROR_RETURN_RET_LOG(ret != CAMERA_OK, CAMERA_INVALID_ARG, "GetMuteModeFromDataShareHelper QueryOnce fail.");
165     value = (value == "0" || value == "1") ? value : "0";
166     int32_t muteModeVal = std::stoi(value);
167     CHECK_ERROR_RETURN_RET_LOG(muteModeVal != 0 && muteModeVal != 1, CAMERA_INVALID_ARG,
168         "GetMuteModeFromDataShareHelper Query MuteMode invald, value = %{public}d", muteModeVal);
169         muteMode = (muteModeVal == 1) ? true: false;
170     this->muteModeStored_ = muteMode;
171     return CAMERA_OK;
172 }
173 
SetMuteModeFromDataShareHelper()174 bool HCameraService::SetMuteModeFromDataShareHelper()
175 {
176     CHECK_ERROR_RETURN_RET(GetServiceStatus() == CameraServiceStatus::SERVICE_READY, true);
177     this->SetServiceStatus(CameraServiceStatus::SERVICE_READY);
178     bool muteMode = false;
179     int32_t ret = GetMuteModeFromDataShareHelper(muteMode);
180     CHECK_ERROR_RETURN_RET_LOG((ret != CAMERA_OK), false, "GetMuteModeFromDataShareHelper failed");
181     MuteCameraFunc(muteMode);
182     muteModeStored_ = muteMode;
183     MEDIA_INFO_LOG("SetMuteModeFromDataShareHelper Success, muteMode = %{public}d", muteMode);
184     return true;
185 }
186 
OnReceiveEvent(const EventFwk::CommonEventData & data)187 void HCameraService::OnReceiveEvent(const EventFwk::CommonEventData &data)
188 {
189     auto const &want = data.GetWant();
190     std::string action = want.GetAction();
191     if (action == COMMON_EVENT_DATA_SHARE_READY) {
192         MEDIA_INFO_LOG("on receive datashare ready.");
193         SetMuteModeFromDataShareHelper();
194     }
195 #ifdef NOTIFICATION_ENABLE
196     if (action == EVENT_CAMERA_BEAUTY_NOTIFICATION) {
197         MEDIA_INFO_LOG("on receive camera beauty.");
198         OHOS::AAFwk::WantParams wantParams = data.GetWant().GetParams();
199         int32_t currentFlag = wantParams.GetIntParam(BEAUTY_NOTIFICATION_ACTION_PARAM, -1);
200         MEDIA_INFO_LOG("currentFlag: %{public}d", currentFlag);
201         int32_t beautyStatus = currentFlag == BEAUTY_STATUS_OFF ? BEAUTY_STATUS_ON : BEAUTY_STATUS_OFF;
202         CameraBeautyNotification::GetInstance()->SetBeautyStatusFromDataShareHelper(beautyStatus);
203         SetBeauty(beautyStatus);
204         CameraBeautyNotification::GetInstance()->SetBeautyStatus(beautyStatus);
205         CameraBeautyNotification::GetInstance()->PublishNotification(false);
206     }
207 #endif
208     if (action == COMMON_EVENT_SCREEN_LOCKED) {
209         MEDIA_DEBUG_LOG("on receive usual.event.SCREEN_LOCKED.");
210         CameraCommonEventManager::GetInstance()->SetScreenLocked(true);
211     }
212     if (action == COMMON_EVENT_SCREEN_UNLOCKED) {
213         MEDIA_DEBUG_LOG("on receive usual.event.SCREEN_UNLOCKED.");
214         CameraCommonEventManager::GetInstance()->SetScreenLocked(false);
215     }
216 }
217 
218 #ifdef NOTIFICATION_ENABLE
SetBeauty(int32_t beautyStatus)219 int32_t HCameraService::SetBeauty(int32_t beautyStatus)
220 {
221     constexpr int32_t DEFAULT_ITEMS = 1;
222     constexpr int32_t DEFAULT_DATA_LENGTH = 1;
223     shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata =
224         make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
225     int32_t ret;
226     int32_t count = 1;
227     uint8_t beautyLevel = 0;
228     uint8_t beautyType = OHOS_CAMERA_BEAUTY_TYPE_OFF;
229     if (beautyStatus == BEAUTY_STATUS_ON) {
230         beautyLevel = BEAUTY_LEVEL;
231         beautyType = OHOS_CAMERA_BEAUTY_TYPE_AUTO;
232     }
233     MEDIA_INFO_LOG("HCameraService::SetBeauty beautyType: %{public}d, beautyLevel: %{public}d",
234         beautyType, beautyLevel);
235     camera_metadata_item_t item;
236     ret = OHOS::Camera::FindCameraMetadataItem(changedMetadata->get(), OHOS_CONTROL_BEAUTY_TYPE, &item);
237     if (ret == CAM_META_ITEM_NOT_FOUND) {
238         changedMetadata->addEntry(OHOS_CONTROL_BEAUTY_TYPE, &beautyType, count);
239     } else if (ret == CAM_META_SUCCESS) {
240         changedMetadata->updateEntry(OHOS_CONTROL_BEAUTY_TYPE, &beautyType, count);
241     }
242 
243     ret = OHOS::Camera::FindCameraMetadataItem(changedMetadata->get(), OHOS_CONTROL_BEAUTY_AUTO_VALUE, &item);
244     if (ret == CAM_META_ITEM_NOT_FOUND) {
245         changedMetadata->addEntry(OHOS_CONTROL_BEAUTY_AUTO_VALUE, &beautyLevel, count);
246     } else if (ret == CAM_META_SUCCESS) {
247         changedMetadata->updateEntry(OHOS_CONTROL_BEAUTY_AUTO_VALUE, &beautyLevel, count);
248     }
249 
250     sptr<HCameraDeviceManager> deviceManager = HCameraDeviceManager::GetInstance();
251     std::vector<sptr<HCameraDeviceHolder>> deviceHolderVector = deviceManager->GetActiveCameraHolders();
252     for (sptr<HCameraDeviceHolder> activeDeviceHolder : deviceHolderVector) {
253         sptr<HCameraDevice> activeDevice = activeDeviceHolder->GetDevice();
254         if (activeDevice != nullptr && activeDevice->IsOpenedCameraDevice()) {
255             activeDevice->UpdateSetting(changedMetadata);
256             MEDIA_INFO_LOG("HCameraService::SetBeauty UpdateSetting");
257         }
258     }
259     return CAMERA_OK;
260 }
261 #endif
262 
SetMuteModeByDataShareHelper(bool muteMode)263 int32_t HCameraService::SetMuteModeByDataShareHelper(bool muteMode)
264 {
265     MEDIA_INFO_LOG("SetMuteModeByDataShareHelper enter.");
266     lock_guard<mutex> lock(g_dataShareHelperMutex);
267     CHECK_ERROR_RETURN_RET_LOG(cameraDataShareHelper_ == nullptr, CAMERA_ALLOC_ERROR,
268         "GetMuteModeFromDataShareHelper NULL");
269     std::string unMuteModeStr = "0";
270     std::string muteModeStr = "1";
271     std::string value = muteMode? muteModeStr : unMuteModeStr;
272     auto ret = cameraDataShareHelper_->UpdateOnce(PREDICATES_STRING, value);
273     CHECK_ERROR_RETURN_RET_LOG(ret != CAMERA_OK, CAMERA_ALLOC_ERROR, "SetMuteModeByDataShareHelper UpdateOnce fail.");
274     return CAMERA_OK;
275 }
276 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)277 void HCameraService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
278 {
279     MEDIA_INFO_LOG("OnAddSystemAbility systemAbilityId:%{public}d", systemAbilityId);
280     switch (systemAbilityId) {
281         case DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID:
282             MEDIA_INFO_LOG("OnAddSystemAbility RegisterObserver start");
283             CameraCommonEventManager::GetInstance()->SubscribeCommonEvent(COMMON_EVENT_DATA_SHARE_READY,
284                 std::bind(&HCameraService::OnReceiveEvent, this, std::placeholders::_1));
285             CHECK_EXECUTE(cameraDataShareHelper_->IsDataShareReady(), SetMuteModeFromDataShareHelper());
286             break;
287         case COMMON_EVENT_SERVICE_ID:
288             MEDIA_INFO_LOG("OnAddSystemAbility COMMON_EVENT_SERVICE");
289 #ifdef NOTIFICATION_ENABLE
290             CameraCommonEventManager::GetInstance()->SubscribeCommonEvent(EVENT_CAMERA_BEAUTY_NOTIFICATION,
291                 std::bind(&HCameraService::OnReceiveEvent, this, std::placeholders::_1));
292 #endif
293             CameraCommonEventManager::GetInstance()->SubscribeCommonEvent(COMMON_EVENT_SCREEN_LOCKED,
294                 std::bind(&HCameraService::OnReceiveEvent, this, std::placeholders::_1));
295             CameraCommonEventManager::GetInstance()->SubscribeCommonEvent(COMMON_EVENT_SCREEN_UNLOCKED,
296                 std::bind(&HCameraService::OnReceiveEvent, this, std::placeholders::_1));
297             break;
298         default:
299             MEDIA_INFO_LOG("OnAddSystemAbility unhandled sysabilityId:%{public}d", systemAbilityId);
300             break;
301     }
302     MEDIA_INFO_LOG("OnAddSystemAbility done");
303 }
304 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)305 void HCameraService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
306 {
307     MEDIA_DEBUG_LOG("HCameraService::OnRemoveSystemAbility systemAbilityId:%{public}d removed", systemAbilityId);
308     switch (systemAbilityId) {
309         case DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID:
310             CameraCommonEventManager::GetInstance()->UnSubscribeCommonEvent(COMMON_EVENT_DATA_SHARE_READY);
311             break;
312         default:
313             break;
314     }
315     MEDIA_DEBUG_LOG("HCameraService::OnRemoveSystemAbility done");
316 }
317 
GetCameras(vector<string> & cameraIds,vector<shared_ptr<OHOS::Camera::CameraMetadata>> & cameraAbilityList)318 int32_t HCameraService::GetCameras(
319     vector<string>& cameraIds, vector<shared_ptr<OHOS::Camera::CameraMetadata>>& cameraAbilityList)
320 {
321     CAMERA_SYNC_TRACE;
322     isFoldable = isFoldableInit ? isFoldable : g_isFoldScreen;
323     isFoldableInit = true;
324     int32_t ret = cameraHostManager_->GetCameras(cameraIds);
325     CHECK_ERROR_RETURN_RET_LOG(ret != CAMERA_OK, ret, "HCameraService::GetCameras failed");
326     shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility;
327     vector<shared_ptr<CameraMetaInfo>> cameraInfos;
328     for (auto id : cameraIds) {
329         ret = cameraHostManager_->GetCameraAbility(id, cameraAbility);
330         CHECK_ERROR_RETURN_RET_LOG(ret != CAMERA_OK || cameraAbility == nullptr, ret,
331             "HCameraService::GetCameraAbility failed");
332         auto cameraMetaInfo = GetCameraMetaInfo(id, cameraAbility);
333         if (cameraMetaInfo == nullptr) {
334             continue;
335         }
336         cameraInfos.emplace_back(cameraMetaInfo);
337     }
338     FillCameras(cameraInfos, cameraIds, cameraAbilityList);
339     return ret;
340 }
341 
GetCameraMetaInfo(std::string & cameraId,shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility)342 shared_ptr<CameraMetaInfo>HCameraService::GetCameraMetaInfo(std::string &cameraId,
343     shared_ptr<OHOS::Camera::CameraMetadata>cameraAbility)
344 {
345     camera_metadata_item_t item;
346     common_metadata_header_t* metadata = cameraAbility->get();
347     int32_t res = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_CAMERA_POSITION, &item);
348     uint8_t cameraPosition = (res == CAM_META_SUCCESS) ? item.data.u8[0] : OHOS_CAMERA_POSITION_OTHER;
349     res = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_CAMERA_FOLDSCREEN_TYPE, &item);
350     uint8_t foldType = (res == CAM_META_SUCCESS) ? item.data.u8[0] : OHOS_CAMERA_FOLDSCREEN_OTHER;
351     if (isFoldable && cameraPosition == OHOS_CAMERA_POSITION_FRONT && foldType == OHOS_CAMERA_FOLDSCREEN_OTHER &&
352         system::GetParameter("const.window.foldscreen.type", "")[0] == '1') {
353         return nullptr;
354     }
355     if (isFoldable && cameraPosition == OHOS_CAMERA_POSITION_FRONT && foldType == OHOS_CAMERA_FOLDSCREEN_INNER) {
356         cameraPosition = POSITION_FOLD_INNER;
357     }
358     res = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_CAMERA_TYPE, &item);
359     uint8_t cameraType = (res == CAM_META_SUCCESS) ? item.data.u8[0] : OHOS_CAMERA_TYPE_UNSPECIFIED;
360     res = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_CAMERA_CONNECTION_TYPE, &item);
361     uint8_t connectionType = (res == CAM_META_SUCCESS) ? item.data.u8[0] : OHOS_CAMERA_CONNECTION_TYPE_BUILTIN;
362     res = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_CONTROL_CAPTURE_MIRROR_SUPPORTED, &item);
363     bool isMirrorSupported = (res == CAM_META_SUCCESS) ? (item.count != 0) : false;
364     res = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_CAMERA_FOLD_STATUS, &item);
365     uint8_t foldStatus = (res == CAM_META_SUCCESS) ? item.data.u8[0] : OHOS_CAMERA_FOLD_STATUS_NONFOLDABLE;
366     res = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_CAMERA_MODES, &item);
367     std::vector<uint8_t> supportModes = {};
368     for (uint32_t i = 0; i < item.count; i++) {
369         supportModes.push_back(item.data.u8[i]);
370     }
371     CAMERA_SYSEVENT_STATISTIC(CreateMsg("CameraManager GetCameras camera ID:%s, Camera position:%d, "
372                                         "Camera Type:%d, Connection Type:%d, Mirror support:%d, Fold status %d",
373         cameraId.c_str(), cameraPosition, cameraType, connectionType, isMirrorSupported, foldStatus));
374     return make_shared<CameraMetaInfo>(cameraId, cameraType, cameraPosition, connectionType,
375         foldStatus, supportModes, cameraAbility);
376 }
377 
FillCameras(vector<shared_ptr<CameraMetaInfo>> & cameraInfos,vector<string> & cameraIds,vector<shared_ptr<OHOS::Camera::CameraMetadata>> & cameraAbilityList)378 void HCameraService::FillCameras(vector<shared_ptr<CameraMetaInfo>>& cameraInfos,
379     vector<string>& cameraIds, vector<shared_ptr<OHOS::Camera::CameraMetadata>>& cameraAbilityList)
380 {
381     vector<shared_ptr<CameraMetaInfo>> choosedCameras = ChooseDeFaultCameras(cameraInfos);
382     cameraIds.clear();
383     cameraAbilityList.clear();
384     for (const auto& camera: choosedCameras) {
385         cameraIds.emplace_back(camera->cameraId);
386         cameraAbilityList.emplace_back(camera->cameraAbility);
387     }
388     int32_t uid = IPCSkeleton::GetCallingUid();
389     if (uid == ROOT_UID || uid == FACE_CLIENT_UID || uid == RSS_UID ||
390         OHOS::Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
391         vector<shared_ptr<CameraMetaInfo>> physicalCameras = ChoosePhysicalCameras(cameraInfos, choosedCameras);
392         for (const auto& camera: physicalCameras) {
393             cameraIds.emplace_back(camera->cameraId);
394             cameraAbilityList.emplace_back(camera->cameraAbility);
395         }
396     } else {
397         MEDIA_INFO_LOG("current token id not support physical camera");
398     }
399 }
400 
ChoosePhysicalCameras(const vector<shared_ptr<CameraMetaInfo>> & cameraInfos,const vector<shared_ptr<CameraMetaInfo>> & choosedCameras)401 vector<shared_ptr<CameraMetaInfo>> HCameraService::ChoosePhysicalCameras(
402     const vector<shared_ptr<CameraMetaInfo>>& cameraInfos, const vector<shared_ptr<CameraMetaInfo>>& choosedCameras)
403 {
404     std::vector<OHOS::HDI::Camera::V1_3::OperationMode> supportedPhysicalCamerasModes = {
405         OHOS::HDI::Camera::V1_3::OperationMode::PROFESSIONAL_PHOTO,
406         OHOS::HDI::Camera::V1_3::OperationMode::PROFESSIONAL_VIDEO,
407         OHOS::HDI::Camera::V1_3::OperationMode::HIGH_RESOLUTION_PHOTO,
408     };
409     vector<shared_ptr<CameraMetaInfo>> physicalCameraInfos = {};
410     for (auto& camera : cameraInfos) {
411         if (std::any_of(choosedCameras.begin(), choosedCameras.end(), [camera](const auto& defaultCamera) {
412                 return camera->cameraId == defaultCamera->cameraId;
413             })
414         ) {
415             MEDIA_INFO_LOG("ChoosePhysicalCameras alreadly has default camera: %{public}s", camera->cameraId.c_str());
416         } else {
417             physicalCameraInfos.push_back(camera);
418         }
419     }
420     vector<shared_ptr<CameraMetaInfo>> physicalCameras = {};
421     for (auto& camera : physicalCameraInfos) {
422         MEDIA_INFO_LOG("ChoosePhysicalCameras camera ID:%s, CameraType: %{public}d, Camera position:%{public}d, "
423                        "Connection Type:%{public}d",
424                        camera->cameraId.c_str(), camera->cameraType, camera->position, camera->connectionType);
425         bool isSupportPhysicalCamera = std::any_of(camera->supportModes.begin(), camera->supportModes.end(),
426             [&supportedPhysicalCamerasModes](auto mode) -> bool {
427                 return any_of(supportedPhysicalCamerasModes.begin(), supportedPhysicalCamerasModes.end(),
428                     [mode](auto it)-> bool { return it == mode; });
429             });
430         if (camera->cameraType != camera_type_enum_t::OHOS_CAMERA_TYPE_UNSPECIFIED && isSupportPhysicalCamera) {
431             physicalCameras.emplace_back(camera);
432             MEDIA_INFO_LOG("ChoosePhysicalCameras add camera ID:%{public}s", camera->cameraId.c_str());
433         }
434     }
435     return physicalCameras;
436 }
437 
438 
GetCameraIds(std::vector<std::string> & cameraIds)439 int32_t HCameraService::GetCameraIds(std::vector<std::string>& cameraIds)
440 {
441     CAMERA_SYNC_TRACE;
442     int32_t ret = CAMERA_OK;
443     MEDIA_DEBUG_LOG("HCameraService::GetCameraIds");
444     std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> cameraAbilityList;
445     ret = GetCameras(cameraIds, cameraAbilityList);
446     CHECK_ERROR_PRINT_LOG(ret != CAMERA_OK, "HCameraService::GetCameraIds failed");
447     return ret;
448 }
449 
GetCameraAbility(std::string & cameraId,std::shared_ptr<OHOS::Camera::CameraMetadata> & cameraAbility)450 int32_t HCameraService::GetCameraAbility(std::string& cameraId,
451     std::shared_ptr<OHOS::Camera::CameraMetadata>& cameraAbility)
452 {
453     CAMERA_SYNC_TRACE;
454     MEDIA_DEBUG_LOG("HCameraService::GetCameraAbility");
455     int32_t ret = cameraHostManager_->GetCameraAbility(cameraId, cameraAbility);
456     CHECK_ERROR_RETURN_RET_LOG(ret != CAMERA_OK, ret, "HCameraService::GetCameraAbility failed");
457     return ret;
458 }
459 
ChooseDeFaultCameras(vector<shared_ptr<CameraMetaInfo>> cameraInfos)460 vector<shared_ptr<CameraMetaInfo>> HCameraService::ChooseDeFaultCameras(vector<shared_ptr<CameraMetaInfo>> cameraInfos)
461 {
462     vector<shared_ptr<CameraMetaInfo>> choosedCameras;
463     for (auto& camera : cameraInfos) {
464         MEDIA_DEBUG_LOG("ChooseDeFaultCameras camera ID:%s, Camera position:%{public}d, Connection Type:%{public}d",
465             camera->cameraId.c_str(), camera->position, camera->connectionType);
466         if (any_of(choosedCameras.begin(), choosedCameras.end(),
467             [camera](const auto& defaultCamera) {
468                 return (camera->connectionType != OHOS_CAMERA_CONNECTION_TYPE_USB_PLUGIN &&
469                     defaultCamera->position == camera->position &&
470                     defaultCamera->connectionType == camera->connectionType &&
471                     defaultCamera->foldStatus == camera->foldStatus);
472             })
473         ) {
474             MEDIA_DEBUG_LOG("ChooseDeFaultCameras alreadly has default camera");
475         } else {
476             choosedCameras.emplace_back(camera);
477             MEDIA_INFO_LOG("add camera ID:%{public}s", camera->cameraId.c_str());
478         }
479     }
480     return choosedCameras;
481 }
482 
CreateCameraDevice(string cameraId,sptr<ICameraDeviceService> & device)483 int32_t HCameraService::CreateCameraDevice(string cameraId, sptr<ICameraDeviceService>& device)
484 {
485     CAMERA_SYNC_TRACE;
486     OHOS::Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
487     MEDIA_INFO_LOG("HCameraService::CreateCameraDevice prepare execute, cameraId:%{public}s", cameraId.c_str());
488 
489     string permissionName = OHOS_PERMISSION_CAMERA;
490     int32_t ret = CheckPermission(permissionName, callerToken);
491     CHECK_ERROR_RETURN_RET_LOG(ret != CAMERA_OK, ret,
492         "HCameraService::CreateCameraDevice Check OHOS_PERMISSION_CAMERA fail %{public}d", ret);
493     // if callerToken is invalid, will not call IsAllowedUsingPermission
494     CHECK_ERROR_RETURN_RET_LOG(!IsInForeGround(callerToken), CAMERA_ALLOC_ERROR,
495         "HCameraService::CreateCameraDevice is not allowed!");
496     sptr<HCameraDevice> cameraDevice = new (nothrow) HCameraDevice(cameraHostManager_, cameraId, callerToken);
497     CHECK_ERROR_RETURN_RET_LOG(cameraDevice == nullptr, CAMERA_ALLOC_ERROR,
498         "HCameraService::CreateCameraDevice HCameraDevice allocation failed");
499     CHECK_ERROR_RETURN_RET_LOG(GetServiceStatus() != CameraServiceStatus::SERVICE_READY, CAMERA_INVALID_STATE,
500         "HCameraService::CreateCameraDevice CameraService not ready!");
501     {
502         lock_guard<mutex> lock(g_dataShareHelperMutex);
503         // when create camera device, update mute setting truely.
504         if (IsCameraMuteSupported(cameraId)) {
505             CHECK_ERROR_PRINT_LOG(UpdateMuteSetting(cameraDevice, muteModeStored_) != CAMERA_OK,
506                 "UpdateMuteSetting Failed, cameraId: %{public}s", cameraId.c_str());
507         } else {
508             MEDIA_ERR_LOG("HCameraService::CreateCameraDevice MuteCamera not Supported");
509         }
510         device = cameraDevice;
511         cameraDevice->SetDeviceMuteMode(muteModeStored_);
512     }
513     CAMERA_SYSEVENT_STATISTIC(CreateMsg("CameraManager_CreateCameraInput CameraId:%s", cameraId.c_str()));
514     MEDIA_INFO_LOG("HCameraService::CreateCameraDevice execute success");
515     return CAMERA_OK;
516 }
517 
CreateCaptureSession(sptr<ICaptureSession> & session,int32_t opMode)518 int32_t HCameraService::CreateCaptureSession(sptr<ICaptureSession>& session, int32_t opMode)
519 {
520     CAMERA_SYNC_TRACE;
521     std::lock_guard<std::mutex> lock(mutex_);
522     int32_t rc = CAMERA_OK;
523     MEDIA_INFO_LOG("HCameraService::CreateCaptureSession opMode_= %{public}d", opMode);
524 
525     OHOS::Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
526     sptr<HCaptureSession> captureSession = nullptr;
527     rc = HCaptureSession::NewInstance(callerToken, opMode, captureSession);
528     if (rc != CAMERA_OK) {
529         MEDIA_ERR_LOG("HCameraService::CreateCaptureSession allocation failed");
530         CameraReportUtils::ReportCameraError(
531             "HCameraService::CreateCaptureSession", rc, false, CameraReportUtils::GetCallerInfo());
532         return rc;
533     }
534     captureSession->SetCameraRotateStrategyInfos(cameraRotateStrategyInfos_);
535     session = captureSession;
536     pid_t pid = IPCSkeleton::GetCallingPid();
537     captureSessionsManager_.EnsureInsert(pid, captureSession);
538     return rc;
539 }
540 
CreateDeferredPhotoProcessingSession(int32_t userId,sptr<DeferredProcessing::IDeferredPhotoProcessingSessionCallback> & callback,sptr<DeferredProcessing::IDeferredPhotoProcessingSession> & session)541 int32_t HCameraService::CreateDeferredPhotoProcessingSession(int32_t userId,
542     sptr<DeferredProcessing::IDeferredPhotoProcessingSessionCallback>& callback,
543     sptr<DeferredProcessing::IDeferredPhotoProcessingSession>& session)
544 {
545     CAMERA_SYNC_TRACE;
546     MEDIA_INFO_LOG("HCameraService::CreateDeferredPhotoProcessingSession enter.");
547     sptr<DeferredProcessing::IDeferredPhotoProcessingSession> photoSession;
548     int32_t uid = IPCSkeleton::GetCallingUid();
549     AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
550     MEDIA_INFO_LOG("CreateDeferredPhotoProcessingSession get uid:%{public}d userId:%{public}d", uid, userId);
551     photoSession =
552         DeferredProcessing::DeferredProcessingService::GetInstance().CreateDeferredPhotoProcessingSession(userId,
553         callback);
554     session = photoSession;
555     return CAMERA_OK;
556 }
557 
CreateDeferredVideoProcessingSession(int32_t userId,sptr<DeferredProcessing::IDeferredVideoProcessingSessionCallback> & callback,sptr<DeferredProcessing::IDeferredVideoProcessingSession> & session)558 int32_t HCameraService::CreateDeferredVideoProcessingSession(int32_t userId,
559     sptr<DeferredProcessing::IDeferredVideoProcessingSessionCallback>& callback,
560     sptr<DeferredProcessing::IDeferredVideoProcessingSession>& session)
561 {
562     CAMERA_SYNC_TRACE;
563     MEDIA_INFO_LOG("HCameraService::CreateDeferredVideoProcessingSession enter.");
564     sptr<DeferredProcessing::IDeferredVideoProcessingSession> videoSession;
565     int32_t uid = IPCSkeleton::GetCallingUid();
566     AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
567     MEDIA_INFO_LOG("CreateDeferredVideoProcessingSession get uid:%{public}d userId:%{public}d", uid, userId);
568     videoSession =
569         DeferredProcessing::DeferredProcessingService::GetInstance().CreateDeferredVideoProcessingSession(userId,
570         callback);
571     session = videoSession;
572     return CAMERA_OK;
573 }
574 
CreatePhotoOutput(const sptr<OHOS::IBufferProducer> & producer,int32_t format,int32_t width,int32_t height,sptr<IStreamCapture> & photoOutput)575 int32_t HCameraService::CreatePhotoOutput(const sptr<OHOS::IBufferProducer>& producer, int32_t format, int32_t width,
576     int32_t height, sptr<IStreamCapture>& photoOutput)
577 {
578     CAMERA_SYNC_TRACE;
579     int32_t rc = CAMERA_OK;
580     MEDIA_INFO_LOG("HCameraService::CreatePhotoOutput prepare execute");
581     if ((producer == nullptr) || (width == 0) || (height == 0)) {
582         rc = CAMERA_INVALID_ARG;
583         MEDIA_ERR_LOG("HCameraService::CreatePhotoOutput producer is null");
584         CameraReportUtils::ReportCameraError(
585             "HCameraService::CreatePhotoOutput", rc, false, CameraReportUtils::GetCallerInfo());
586         return rc;
587     }
588     sptr<HStreamCapture> streamCapture = new (nothrow) HStreamCapture(producer, format, width, height);
589     if (streamCapture == nullptr) {
590         rc = CAMERA_ALLOC_ERROR;
591         MEDIA_ERR_LOG("HCameraService::CreatePhotoOutput streamCapture is null");
592         CameraReportUtils::ReportCameraError(
593             "HCameraService::CreatePhotoOutput", rc, false, CameraReportUtils::GetCallerInfo());
594         return rc;
595     }
596 
597     stringstream ss;
598     ss << "format=" << format << " width=" << width << " height=" << height;
599     CameraReportUtils::GetInstance().UpdateProfileInfo(ss.str());
600     photoOutput = streamCapture;
601     MEDIA_INFO_LOG("HCameraService::CreatePhotoOutput execute success");
602     return rc;
603 }
604 
CreateDeferredPreviewOutput(int32_t format,int32_t width,int32_t height,sptr<IStreamRepeat> & previewOutput)605 int32_t HCameraService::CreateDeferredPreviewOutput(
606     int32_t format, int32_t width, int32_t height, sptr<IStreamRepeat>& previewOutput)
607 {
608     CAMERA_SYNC_TRACE;
609     sptr<HStreamRepeat> streamDeferredPreview;
610     MEDIA_INFO_LOG("HCameraService::CreateDeferredPreviewOutput prepare execute");
611     CHECK_ERROR_RETURN_RET_LOG((width == 0) || (height == 0), CAMERA_INVALID_ARG,
612         "HCameraService::CreateDeferredPreviewOutput producer is null!");
613     streamDeferredPreview = new (nothrow) HStreamRepeat(nullptr, format, width, height, RepeatStreamType::PREVIEW);
614     CHECK_ERROR_RETURN_RET_LOG(streamDeferredPreview == nullptr, CAMERA_ALLOC_ERROR,
615         "HCameraService::CreateDeferredPreviewOutput HStreamRepeat allocation failed");
616     previewOutput = streamDeferredPreview;
617     MEDIA_INFO_LOG("HCameraService::CreateDeferredPreviewOutput execute success");
618     return CAMERA_OK;
619 }
620 
CreatePreviewOutput(const sptr<OHOS::IBufferProducer> & producer,int32_t format,int32_t width,int32_t height,sptr<IStreamRepeat> & previewOutput)621 int32_t HCameraService::CreatePreviewOutput(const sptr<OHOS::IBufferProducer>& producer, int32_t format, int32_t width,
622     int32_t height, sptr<IStreamRepeat>& previewOutput)
623 {
624     CAMERA_SYNC_TRACE;
625     sptr<HStreamRepeat> streamRepeatPreview;
626     int32_t rc = CAMERA_OK;
627     MEDIA_INFO_LOG("HCameraService::CreatePreviewOutput prepare execute");
628 
629     if ((producer == nullptr) || (width == 0) || (height == 0)) {
630         rc = CAMERA_INVALID_ARG;
631         MEDIA_ERR_LOG("HCameraService::CreatePreviewOutput producer is null");
632         CameraReportUtils::ReportCameraError(
633             "HCameraService::CreatePreviewOutput", rc, false, CameraReportUtils::GetCallerInfo());
634         return rc;
635     }
636     streamRepeatPreview = new (nothrow) HStreamRepeat(producer, format, width, height, RepeatStreamType::PREVIEW);
637     if (streamRepeatPreview == nullptr) {
638         rc = CAMERA_ALLOC_ERROR;
639         MEDIA_ERR_LOG("HCameraService::CreatePreviewOutput HStreamRepeat allocation failed");
640         CameraReportUtils::ReportCameraError(
641             "HCameraService::CreatePreviewOutput", rc, false, CameraReportUtils::GetCallerInfo());
642         return rc;
643     }
644     previewOutput = streamRepeatPreview;
645     MEDIA_INFO_LOG("HCameraService::CreatePreviewOutput execute success");
646     return rc;
647 }
648 
CreateDepthDataOutput(const sptr<OHOS::IBufferProducer> & producer,int32_t format,int32_t width,int32_t height,sptr<IStreamDepthData> & depthDataOutput)649 int32_t HCameraService::CreateDepthDataOutput(const sptr<OHOS::IBufferProducer>& producer, int32_t format,
650     int32_t width, int32_t height, sptr<IStreamDepthData>& depthDataOutput)
651 {
652     CAMERA_SYNC_TRACE;
653     sptr<HStreamDepthData> streamDepthData;
654     int32_t rc = CAMERA_OK;
655     MEDIA_INFO_LOG("HCameraService::CreateDepthDataOutput prepare execute");
656 
657     if ((producer == nullptr) || (width == 0) || (height == 0)) {
658         rc = CAMERA_INVALID_ARG;
659         MEDIA_ERR_LOG("HCameraService::CreateDepthDataOutput producer is null");
660         CameraReportUtils::ReportCameraError(
661             "HCameraService::CreateDepthDataOutput", rc, false, CameraReportUtils::GetCallerInfo());
662         return rc;
663     }
664     streamDepthData = new (nothrow) HStreamDepthData(producer, format, width, height);
665     if (streamDepthData == nullptr) {
666         rc = CAMERA_ALLOC_ERROR;
667         MEDIA_ERR_LOG("HCameraService::CreateDepthDataOutput HStreamRepeat allocation failed");
668         CameraReportUtils::ReportCameraError(
669             "HCameraService::CreateDepthDataOutput", rc, false, CameraReportUtils::GetCallerInfo());
670         return rc;
671     }
672     depthDataOutput = streamDepthData;
673     MEDIA_INFO_LOG("HCameraService::CreateDepthDataOutput execute success");
674     return rc;
675 }
676 
CreateMetadataOutput(const sptr<OHOS::IBufferProducer> & producer,int32_t format,std::vector<int32_t> metadataTypes,sptr<IStreamMetadata> & metadataOutput)677 int32_t HCameraService::CreateMetadataOutput(const sptr<OHOS::IBufferProducer>& producer, int32_t format,
678     std::vector<int32_t> metadataTypes, sptr<IStreamMetadata>& metadataOutput)
679 {
680     CAMERA_SYNC_TRACE;
681     sptr<HStreamMetadata> streamMetadata;
682     MEDIA_INFO_LOG("HCameraService::CreateMetadataOutput prepare execute");
683 
684     CHECK_ERROR_RETURN_RET_LOG(producer == nullptr, CAMERA_INVALID_ARG,
685         "HCameraService::CreateMetadataOutput producer is null");
686     streamMetadata = new (nothrow) HStreamMetadata(producer, format, metadataTypes);
687     CHECK_ERROR_RETURN_RET_LOG(streamMetadata == nullptr, CAMERA_ALLOC_ERROR,
688         "HCameraService::CreateMetadataOutput HStreamMetadata allocation failed");
689 
690     metadataOutput = streamMetadata;
691     MEDIA_INFO_LOG("HCameraService::CreateMetadataOutput execute success");
692     return CAMERA_OK;
693 }
694 
CreateVideoOutput(const sptr<OHOS::IBufferProducer> & producer,int32_t format,int32_t width,int32_t height,sptr<IStreamRepeat> & videoOutput)695 int32_t HCameraService::CreateVideoOutput(const sptr<OHOS::IBufferProducer>& producer, int32_t format, int32_t width,
696     int32_t height, sptr<IStreamRepeat>& videoOutput)
697 {
698     CAMERA_SYNC_TRACE;
699     sptr<HStreamRepeat> streamRepeatVideo;
700     int32_t rc = CAMERA_OK;
701     MEDIA_INFO_LOG("HCameraService::CreateVideoOutput prepare execute");
702 
703     if ((producer == nullptr) || (width == 0) || (height == 0)) {
704         rc = CAMERA_INVALID_ARG;
705         MEDIA_ERR_LOG("HCameraService::CreateVideoOutput producer is null");
706         CameraReportUtils::ReportCameraError(
707             "HCameraService::CreateVideoOutput", rc, false, CameraReportUtils::GetCallerInfo());
708         return rc;
709     }
710     streamRepeatVideo = new (nothrow) HStreamRepeat(producer, format, width, height, RepeatStreamType::VIDEO);
711     if (streamRepeatVideo == nullptr) {
712         rc = CAMERA_ALLOC_ERROR;
713         MEDIA_ERR_LOG("HCameraService::CreateVideoOutput HStreamRepeat allocation failed");
714         CameraReportUtils::ReportCameraError(
715             "HCameraService::CreateVideoOutput", rc, false, CameraReportUtils::GetCallerInfo());
716         return rc;
717     }
718     stringstream ss;
719     ss << "format=" << format << " width=" << width << " height=" << height;
720     CameraReportUtils::GetInstance().UpdateProfileInfo(ss.str());
721     videoOutput = streamRepeatVideo;
722     MEDIA_INFO_LOG("HCameraService::CreateVideoOutput execute success");
723     return rc;
724 }
725 
ShouldSkipStatusUpdates(pid_t pid)726 bool HCameraService::ShouldSkipStatusUpdates(pid_t pid)
727 {
728     std::lock_guard<std::mutex> lock(freezedPidListMutex_);
729     CHECK_ERROR_RETURN_RET(freezedPidList_.count(pid) == 0, false);
730     MEDIA_INFO_LOG("ShouldSkipStatusUpdates pid = %{public}d", pid);
731     return true;
732 }
733 
OnCameraStatus(const string & cameraId,CameraStatus status,CallbackInvoker invoker)734 void HCameraService::OnCameraStatus(const string& cameraId, CameraStatus status, CallbackInvoker invoker)
735 {
736     lock_guard<mutex> lock(cameraCbMutex_);
737     std::string bundleName = "";
738     if (invoker == CallbackInvoker::APPLICATION) {
739         bundleName = GetClientBundle(IPCSkeleton::GetCallingUid());
740     }
741     MEDIA_INFO_LOG("HCameraService::OnCameraStatus callbacks.size = %{public}zu, cameraId = %{public}s, "
742                    "status = %{public}d, pid = %{public}d, bundleName = %{public}s",
743         cameraServiceCallbacks_.size(), cameraId.c_str(), status, IPCSkeleton::GetCallingPid(), bundleName.c_str());
744     for (auto it : cameraServiceCallbacks_) {
745         if (it.second == nullptr) {
746             MEDIA_ERR_LOG("HCameraService::OnCameraStatus pid:%{public}d cameraServiceCallback is null", it.first);
747             continue;
748         }
749         uint32_t pid = it.first;
750         if (ShouldSkipStatusUpdates(pid)) {
751             continue;
752         }
753         it.second->OnCameraStatusChanged(cameraId, status, bundleName);
754         CacheCameraStatus(
755             cameraId, std::make_shared<CameraStatusCallbacksInfo>(CameraStatusCallbacksInfo { status, bundleName }));
756         CAMERA_SYSEVENT_BEHAVIOR(
757             CreateMsg("OnCameraStatusChanged! for cameraId:%s, current Camera Status:%d", cameraId.c_str(), status));
758     }
759 }
760 
OnFlashlightStatus(const string & cameraId,FlashStatus status)761 void HCameraService::OnFlashlightStatus(const string& cameraId, FlashStatus status)
762 {
763     lock_guard<mutex> lock(cameraCbMutex_);
764     MEDIA_INFO_LOG("HCameraService::OnFlashlightStatus callbacks.size = %{public}zu, cameraId = %{public}s, "
765                    "status = %{public}d, pid = %{public}d",
766         cameraServiceCallbacks_.size(), cameraId.c_str(), status, IPCSkeleton::GetCallingPid());
767     for (auto it : cameraServiceCallbacks_) {
768         if (it.second == nullptr) {
769             MEDIA_ERR_LOG("HCameraService::OnCameraStatus pid:%{public}d cameraServiceCallback is null", it.first);
770             continue;
771         }
772         uint32_t pid = it.first;
773         if (ShouldSkipStatusUpdates(pid)) {
774             continue;
775         }
776         it.second->OnFlashlightStatusChanged(cameraId, status);
777         CacheFlashStatus(cameraId, status);
778     }
779 }
780 
OnMute(bool muteMode)781 void HCameraService::OnMute(bool muteMode)
782 {
783     lock_guard<mutex> lock(muteCbMutex_);
784     if (!cameraMuteServiceCallbacks_.empty()) {
785         for (auto it : cameraMuteServiceCallbacks_) {
786             if (it.second == nullptr) {
787                 MEDIA_ERR_LOG("HCameraService::OnMute pid:%{public}d cameraMuteServiceCallback is null", it.first);
788                 continue;
789             }
790             uint32_t pid = it.first;
791             if (ShouldSkipStatusUpdates(pid)) {
792                 continue;
793             }
794             it.second->OnCameraMute(muteMode);
795             CAMERA_SYSEVENT_BEHAVIOR(CreateMsg("OnCameraMute! current Camera muteMode:%d", muteMode));
796         }
797     }
798     {
799         std::lock_guard<std::mutex> peerLock(peerCallbackMutex_);
800         if (peerCallback_ != nullptr) {
801             MEDIA_INFO_LOG(
802                 "HCameraService::NotifyMuteCamera peerCallback current camera muteMode:%{public}d", muteMode);
803             peerCallback_->NotifyMuteCamera(muteMode);
804         }
805     }
806 }
807 
GetTorchStatus(int32_t & status)808 int32_t HCameraService::GetTorchStatus(int32_t &status)
809 {
810     status = static_cast<int32_t>(torchStatus_);
811     return CAMERA_OK;
812 }
813 
OnTorchStatus(TorchStatus status)814 void HCameraService::OnTorchStatus(TorchStatus status)
815 {
816     lock_guard<recursive_mutex> lock(torchCbMutex_);
817     torchStatus_ = status;
818     MEDIA_INFO_LOG("HCameraService::OnTorchtStatus callbacks.size = %{public}zu, status = %{public}d, pid = %{public}d",
819         torchServiceCallbacks_.size(), status, IPCSkeleton::GetCallingPid());
820     for (auto it : torchServiceCallbacks_) {
821         if (it.second == nullptr) {
822             MEDIA_ERR_LOG("HCameraService::OnTorchtStatus pid:%{public}d torchServiceCallback is null", it.first);
823             continue;
824         }
825         uint32_t pid = it.first;
826         if (ShouldSkipStatusUpdates(pid)) {
827             continue;
828         }
829         it.second->OnTorchStatusChange(status);
830     }
831 }
832 
OnFoldStatusChanged(OHOS::Rosen::FoldStatus foldStatus)833 void HCameraService::OnFoldStatusChanged(OHOS::Rosen::FoldStatus foldStatus)
834 {
835     MEDIA_INFO_LOG("OnFoldStatusChanged preFoldStatus = %{public}d, foldStatus = %{public}d, pid = %{public}d",
836         preFoldStatus_, foldStatus, IPCSkeleton::GetCallingPid());
837     auto curFoldStatus = (FoldStatus)foldStatus;
838     if ((curFoldStatus == FoldStatus::HALF_FOLD && preFoldStatus_ == FoldStatus::EXPAND) ||
839         (curFoldStatus == FoldStatus::EXPAND && preFoldStatus_ == FoldStatus::HALF_FOLD)) {
840         preFoldStatus_ = curFoldStatus;
841         return;
842     }
843     preFoldStatus_ = curFoldStatus;
844     if (curFoldStatus == FoldStatus::HALF_FOLD) {
845         curFoldStatus = FoldStatus::EXPAND;
846     }
847     lock_guard<recursive_mutex> lock(foldCbMutex_);
848     CHECK_EXECUTE(innerFoldCallback_, innerFoldCallback_->OnFoldStatusChanged(curFoldStatus));
849     CHECK_ERROR_RETURN_LOG(foldServiceCallbacks_.empty(), "OnFoldStatusChanged foldServiceCallbacks is empty");
850     MEDIA_INFO_LOG("OnFoldStatusChanged foldStatusCallback size = %{public}zu", foldServiceCallbacks_.size());
851     for (auto it : foldServiceCallbacks_) {
852         if (it.second == nullptr) {
853             MEDIA_ERR_LOG("OnFoldStatusChanged pid:%{public}d foldStatusCallbacks is null", it.first);
854             continue;
855         }
856         uint32_t pid = it.first;
857         if (ShouldSkipStatusUpdates(pid)) {
858             continue;
859         }
860         it.second->OnFoldStatusChanged(curFoldStatus);
861     }
862 }
863 
CloseCameraForDestory(pid_t pid)864 int32_t HCameraService::CloseCameraForDestory(pid_t pid)
865 {
866     MEDIA_INFO_LOG("HCameraService::CloseCameraForDestory enter");
867     sptr<HCameraDeviceManager> deviceManager = HCameraDeviceManager::GetInstance();
868     std::vector<sptr<HCameraDevice>> devicesNeedClose = deviceManager->GetCamerasByPid(pid);
869     for (auto device : devicesNeedClose) {
870         device->Close();
871     }
872 
873     std::vector<sptr<HStreamOperator>> streamOperatorToRelease =
874         HStreamOperatorManager::GetInstance()->GetStreamOperatorByPid(pid);
875     for (auto streamoperator : streamOperatorToRelease) {
876         streamoperator->Release();
877     }
878     return CAMERA_OK;
879 }
880 
ExecutePidSetCallback(sptr<ICameraServiceCallback> & callback,std::vector<std::string> & cameraIds)881 void HCameraService::ExecutePidSetCallback(sptr<ICameraServiceCallback>& callback, std::vector<std::string>& cameraIds)
882 {
883     for (const auto& cameraId : cameraIds) {
884         auto info = GetCachedCameraStatus(cameraId);
885         auto flashStatus = GetCachedFlashStatus(cameraId);
886         if (info != nullptr) {
887             MEDIA_INFO_LOG("ExecutePidSetCallback cameraId = %{public}s, status = %{public}d, bundleName = %{public}s, "
888                            "flash status = %{public}d",
889                 cameraId.c_str(), info->status, info->bundleName.c_str(), flashStatus);
890             callback->OnCameraStatusChanged(cameraId, info->status, info->bundleName);
891             callback->OnFlashlightStatusChanged(cameraId, flashStatus);
892         } else {
893             MEDIA_INFO_LOG("ExecutePidSetCallback cameraId = %{public}s, status = 2", cameraId.c_str());
894             callback->OnCameraStatusChanged(cameraId, CameraStatus::CAMERA_STATUS_AVAILABLE);
895             callback->OnFlashlightStatusChanged(cameraId, FlashStatus::FLASH_STATUS_UNAVAILABLE);
896         }
897     }
898 }
899 
SetCameraCallback(sptr<ICameraServiceCallback> & callback)900 int32_t HCameraService::SetCameraCallback(sptr<ICameraServiceCallback>& callback)
901 {
902     std::vector<std::string> cameraIds;
903     GetCameraIds(cameraIds);
904     lock_guard<mutex> lock(cameraCbMutex_);
905     pid_t pid = IPCSkeleton::GetCallingPid();
906     MEDIA_INFO_LOG("HCameraService::SetCameraCallback pid = %{public}d", pid);
907     CHECK_ERROR_RETURN_RET_LOG(callback == nullptr, CAMERA_INVALID_ARG,
908         "HCameraService::SetCameraCallback callback is null");
909     auto callbackItem = cameraServiceCallbacks_.find(pid);
910     if (callbackItem != cameraServiceCallbacks_.end()) {
911         callbackItem->second = nullptr;
912         (void)cameraServiceCallbacks_.erase(callbackItem);
913     }
914     cameraServiceCallbacks_.insert(make_pair(pid, callback));
915     ExecutePidSetCallback(callback, cameraIds);
916     return CAMERA_OK;
917 }
918 
UnSetCameraCallback()919 int32_t HCameraService::UnSetCameraCallback()
920 {
921     pid_t pid = IPCSkeleton::GetCallingPid();
922     return UnSetCameraCallback(pid);
923 }
924 
SetMuteCallback(sptr<ICameraMuteServiceCallback> & callback)925 int32_t HCameraService::SetMuteCallback(sptr<ICameraMuteServiceCallback>& callback)
926 {
927     lock_guard<mutex> lock(muteCbMutex_);
928     pid_t pid = IPCSkeleton::GetCallingPid();
929     MEDIA_INFO_LOG("HCameraService::SetMuteCallback pid = %{public}d, muteMode:%{public}d", pid, muteModeStored_);
930     CHECK_ERROR_RETURN_RET_LOG(callback == nullptr, CAMERA_INVALID_ARG,
931         "HCameraService::SetMuteCallback callback is null");
932     // If the callback set by the SA caller is later than the camera service is started,
933     // the callback cannot be triggered to obtain the mute state. Therefore,
934     // when the SA sets the callback, the callback is triggered immediately to return the mute state.
935     callback->OnCameraMute(muteModeStored_);
936     cameraMuteServiceCallbacks_.insert(make_pair(pid, callback));
937     return CAMERA_OK;
938 }
939 
UnSetMuteCallback()940 int32_t HCameraService::UnSetMuteCallback()
941 {
942     pid_t pid = IPCSkeleton::GetCallingPid();
943     return UnSetMuteCallback(pid);
944 }
945 
SetTorchCallback(sptr<ITorchServiceCallback> & callback)946 int32_t HCameraService::SetTorchCallback(sptr<ITorchServiceCallback>& callback)
947 {
948     lock_guard<recursive_mutex> lock(torchCbMutex_);
949     pid_t pid = IPCSkeleton::GetCallingPid();
950     MEDIA_INFO_LOG("HCameraService::SetTorchCallback pid = %{public}d", pid);
951     CHECK_ERROR_RETURN_RET_LOG(callback == nullptr, CAMERA_INVALID_ARG,
952         "HCameraService::SetTorchCallback callback is null");
953     torchServiceCallbacks_.insert(make_pair(pid, callback));
954 
955     MEDIA_INFO_LOG("HCameraService::SetTorchCallback notify pid = %{public}d", pid);
956     callback->OnTorchStatusChange(torchStatus_);
957     return CAMERA_OK;
958 }
959 
UnSetTorchCallback()960 int32_t HCameraService::UnSetTorchCallback()
961 {
962     pid_t pid = IPCSkeleton::GetCallingPid();
963     return UnSetTorchCallback(pid);
964 }
965 
SetFoldStatusCallback(sptr<IFoldServiceCallback> & callback,bool isInnerCallback)966 int32_t HCameraService::SetFoldStatusCallback(sptr<IFoldServiceCallback>& callback, bool isInnerCallback)
967 {
968     lock_guard<recursive_mutex> lock(foldCbMutex_);
969     isFoldable = isFoldableInit ? isFoldable : g_isFoldScreen;
970     CHECK_EXECUTE((isFoldable && !isFoldRegister), RegisterFoldStatusListener());
971     if (isInnerCallback) {
972         innerFoldCallback_ = callback;
973     } else {
974         pid_t pid = IPCSkeleton::GetCallingPid();
975         MEDIA_INFO_LOG("HCameraService::SetFoldStatusCallback pid = %{public}d", pid);
976         CHECK_ERROR_RETURN_RET_LOG(
977             callback == nullptr, CAMERA_INVALID_ARG, "HCameraService::SetFoldStatusCallback callback is null");
978         foldServiceCallbacks_.insert(make_pair(pid, callback));
979     }
980     return CAMERA_OK;
981 }
982 
UnSetFoldStatusCallback()983 int32_t HCameraService::UnSetFoldStatusCallback()
984 {
985     pid_t pid = IPCSkeleton::GetCallingPid();
986     return UnSetFoldStatusCallback(pid);
987 }
988 
UnSetCameraCallback(pid_t pid)989 int32_t HCameraService::UnSetCameraCallback(pid_t pid)
990 {
991     lock_guard<mutex> lock(cameraCbMutex_);
992     MEDIA_INFO_LOG("HCameraService::UnSetCameraCallback pid = %{public}d, size = %{public}zu",
993         pid, cameraServiceCallbacks_.size());
994     if (!cameraServiceCallbacks_.empty()) {
995         MEDIA_INFO_LOG("HCameraService::UnSetCameraCallback cameraServiceCallbacks_ is not empty, reset it");
996         auto it = cameraServiceCallbacks_.find(pid);
997         if ((it != cameraServiceCallbacks_.end()) && (it->second != nullptr)) {
998             it->second = nullptr;
999             cameraServiceCallbacks_.erase(it);
1000         }
1001     }
1002     MEDIA_INFO_LOG("HCameraService::UnSetCameraCallback after erase pid = %{public}d, size = %{public}zu",
1003         pid, cameraServiceCallbacks_.size());
1004     return CAMERA_OK;
1005 }
1006 
UnSetMuteCallback(pid_t pid)1007 int32_t HCameraService::UnSetMuteCallback(pid_t pid)
1008 {
1009     lock_guard<mutex> lock(muteCbMutex_);
1010     MEDIA_INFO_LOG("HCameraService::UnSetMuteCallback pid = %{public}d, size = %{public}zu",
1011         pid, cameraMuteServiceCallbacks_.size());
1012     if (!cameraMuteServiceCallbacks_.empty()) {
1013         MEDIA_INFO_LOG("HCameraService::UnSetMuteCallback cameraMuteServiceCallbacks_ is not empty, reset it");
1014         auto it = cameraMuteServiceCallbacks_.find(pid);
1015         if ((it != cameraMuteServiceCallbacks_.end()) && (it->second)) {
1016             it->second = nullptr;
1017             cameraMuteServiceCallbacks_.erase(it);
1018         }
1019     }
1020 
1021     MEDIA_INFO_LOG("HCameraService::UnSetMuteCallback after erase pid = %{public}d, size = %{public}zu",
1022         pid, cameraMuteServiceCallbacks_.size());
1023     return CAMERA_OK;
1024 }
1025 
UnSetTorchCallback(pid_t pid)1026 int32_t HCameraService::UnSetTorchCallback(pid_t pid)
1027 {
1028     lock_guard<recursive_mutex> lock(torchCbMutex_);
1029     MEDIA_INFO_LOG("HCameraService::UnSetTorchCallback pid = %{public}d, size = %{public}zu",
1030         pid, torchServiceCallbacks_.size());
1031     if (!torchServiceCallbacks_.empty()) {
1032         MEDIA_INFO_LOG("HCameraService::UnSetTorchCallback torchServiceCallbacks_ is not empty, reset it");
1033         auto it = torchServiceCallbacks_.find(pid);
1034         if ((it != torchServiceCallbacks_.end()) && (it->second)) {
1035             it->second = nullptr;
1036             torchServiceCallbacks_.erase(it);
1037         }
1038     }
1039 
1040     MEDIA_INFO_LOG("HCameraService::UnSetTorchCallback after erase pid = %{public}d, size = %{public}zu",
1041         pid, torchServiceCallbacks_.size());
1042     return CAMERA_OK;
1043 }
1044 
UnSetFoldStatusCallback(pid_t pid)1045 int32_t HCameraService::UnSetFoldStatusCallback(pid_t pid)
1046 {
1047     lock_guard<recursive_mutex> lock(foldCbMutex_);
1048     MEDIA_INFO_LOG("HCameraService::UnSetFoldStatusCallback pid = %{public}d, size = %{public}zu",
1049         pid, foldServiceCallbacks_.size());
1050     if (!foldServiceCallbacks_.empty()) {
1051         MEDIA_INFO_LOG("HCameraService::UnSetFoldStatusCallback foldServiceCallbacks_ is not empty, reset it");
1052         auto it = foldServiceCallbacks_.find(pid);
1053         if ((it != foldServiceCallbacks_.end()) && (it->second)) {
1054             it->second = nullptr;
1055             foldServiceCallbacks_.erase(it);
1056         }
1057     }
1058     MEDIA_INFO_LOG("HCameraService::UnSetFoldStatusCallback after erase pid = %{public}d, size = %{public}zu",
1059         pid, foldServiceCallbacks_.size());
1060     innerFoldCallback_ = nullptr;
1061     return CAMERA_OK;
1062 }
1063 
RegisterFoldStatusListener()1064 void HCameraService::RegisterFoldStatusListener()
1065 {
1066     MEDIA_INFO_LOG("RegisterFoldStatusListener is called");
1067     preFoldStatus_ = (FoldStatus)OHOS::Rosen::DisplayManager::GetInstance().GetFoldStatus();
1068     auto ret = OHOS::Rosen::DisplayManager::GetInstance().RegisterFoldStatusListener(this);
1069     CHECK_ERROR_RETURN_LOG(ret != OHOS::Rosen::DMError::DM_OK, "RegisterFoldStatusListener failed");
1070     isFoldRegister = true;
1071 }
1072 
UnregisterFoldStatusListener()1073 void HCameraService::UnregisterFoldStatusListener()
1074 {
1075     MEDIA_INFO_LOG("UnregisterFoldStatusListener is called");
1076     auto ret = OHOS::Rosen::DisplayManager::GetInstance().UnregisterFoldStatusListener(this);
1077     preFoldStatus_ = FoldStatus::UNKNOWN_FOLD;
1078     CHECK_ERROR_PRINT_LOG(ret != OHOS::Rosen::DMError::DM_OK, "UnregisterFoldStatusListener failed");
1079     isFoldRegister = false;
1080 }
1081 
UnSetAllCallback(pid_t pid)1082 int32_t HCameraService::UnSetAllCallback(pid_t pid)
1083 {
1084     MEDIA_INFO_LOG("HCameraService::UnSetAllCallback enter");
1085     UnSetCameraCallback(pid);
1086     UnSetMuteCallback(pid);
1087     UnSetTorchCallback(pid);
1088     UnSetFoldStatusCallback(pid);
1089     return CAMERA_OK;
1090 }
1091 
IsCameraMuteSupported(string cameraId)1092 bool HCameraService::IsCameraMuteSupported(string cameraId)
1093 {
1094     bool isMuteSupported = false;
1095     shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility;
1096     int32_t ret = cameraHostManager_->GetCameraAbility(cameraId, cameraAbility);
1097     CHECK_ERROR_RETURN_RET_LOG(ret != CAMERA_OK, false, "HCameraService::IsCameraMuted GetCameraAbility failed");
1098     camera_metadata_item_t item;
1099     common_metadata_header_t* metadata = cameraAbility->get();
1100     ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_MUTE_MODES, &item);
1101     if (ret == CAM_META_SUCCESS) {
1102         for (uint32_t i = 0; i < item.count; i++) {
1103             MEDIA_INFO_LOG("OHOS_ABILITY_MUTE_MODES %{public}d th is %{public}d", i, item.data.u8[i]);
1104             if (item.data.u8[i] == OHOS_CAMERA_MUTE_MODE_SOLID_COLOR_BLACK) {
1105                 isMuteSupported = true;
1106                 break;
1107             }
1108         }
1109     } else {
1110         isMuteSupported = false;
1111         MEDIA_ERR_LOG("HCameraService::IsCameraMuted not find MUTE ability");
1112     }
1113     MEDIA_DEBUG_LOG("HCameraService::IsCameraMuted supported: %{public}d", isMuteSupported);
1114     return isMuteSupported;
1115 }
1116 
UpdateMuteSetting(sptr<HCameraDevice> cameraDevice,bool muteMode)1117 int32_t HCameraService::UpdateMuteSetting(sptr<HCameraDevice> cameraDevice, bool muteMode)
1118 {
1119     constexpr int32_t DEFAULT_ITEMS = 1;
1120     constexpr int32_t DEFAULT_DATA_LENGTH = 1;
1121     shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata =
1122         make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
1123     bool status = false;
1124     int32_t ret;
1125     int32_t count = 1;
1126     uint8_t mode = muteMode ? OHOS_CAMERA_MUTE_MODE_SOLID_COLOR_BLACK : OHOS_CAMERA_MUTE_MODE_OFF;
1127     camera_metadata_item_t item;
1128 
1129     MEDIA_DEBUG_LOG("UpdateMuteSetting muteMode: %{public}d", muteMode);
1130 
1131     ret = OHOS::Camera::FindCameraMetadataItem(changedMetadata->get(), OHOS_CONTROL_MUTE_MODE, &item);
1132     if (ret == CAM_META_ITEM_NOT_FOUND) {
1133         status = changedMetadata->addEntry(OHOS_CONTROL_MUTE_MODE, &mode, count);
1134     } else if (ret == CAM_META_SUCCESS) {
1135         status = changedMetadata->updateEntry(OHOS_CONTROL_MUTE_MODE, &mode, count);
1136     }
1137     ret = cameraDevice->UpdateSetting(changedMetadata);
1138     CHECK_ERROR_RETURN_RET_LOG(!status || ret != CAMERA_OK, CAMERA_UNKNOWN_ERROR, "UpdateMuteSetting muteMode Failed");
1139     return CAMERA_OK;
1140 }
1141 
MuteCameraFunc(bool muteMode)1142 int32_t HCameraService::MuteCameraFunc(bool muteMode)
1143 {
1144     {
1145         lock_guard<mutex> lock(g_dataShareHelperMutex);
1146         cameraHostManager_->SetMuteMode(muteMode);
1147     }
1148     int32_t ret = CAMERA_OK;
1149     bool currentMuteMode = muteModeStored_;
1150     sptr<HCameraDeviceManager> deviceManager = HCameraDeviceManager::GetInstance();
1151     std::vector<sptr<HCameraDeviceHolder>> deviceHolderVector = deviceManager->GetActiveCameraHolders();
1152     if (deviceHolderVector.size() == 0) {
1153         OnMute(muteMode);
1154         int32_t retCode = SetMuteModeByDataShareHelper(muteMode);
1155         muteModeStored_ = muteMode;
1156         if (retCode != CAMERA_OK) {
1157             MEDIA_ERR_LOG("no activeClient, SetMuteModeByDataShareHelper: ret=%{public}d", retCode);
1158             muteModeStored_ = currentMuteMode;
1159         }
1160         return retCode;
1161     }
1162     for (sptr<HCameraDeviceHolder> activeDeviceHolder : deviceHolderVector) {
1163         sptr<HCameraDevice> activeDevice = activeDeviceHolder->GetDevice();
1164         if (activeDevice != nullptr) {
1165             string cameraId = activeDevice->GetCameraId();
1166             CHECK_ERROR_RETURN_RET_LOG(!IsCameraMuteSupported(cameraId), CAMERA_UNSUPPORTED,
1167                 "Not Supported Mute,cameraId: %{public}s", cameraId.c_str());
1168             if (activeDevice != nullptr) {
1169                 ret = UpdateMuteSetting(activeDevice, muteMode);
1170             }
1171             if (ret != CAMERA_OK) {
1172                 MEDIA_ERR_LOG("UpdateMuteSetting Failed, cameraId: %{public}s", cameraId.c_str());
1173                 muteModeStored_ = currentMuteMode;
1174             }
1175         }
1176         CHECK_EXECUTE(activeDevice != nullptr, activeDevice->SetDeviceMuteMode(muteMode));
1177     }
1178 
1179     CHECK_EXECUTE(ret == CAMERA_OK, OnMute(muteMode));
1180     ret = SetMuteModeByDataShareHelper(muteMode);
1181     if (ret == CAMERA_OK) {
1182         muteModeStored_ = muteMode;
1183     }
1184     return ret;
1185 }
1186 
CacheCameraStatus(const string & cameraId,std::shared_ptr<CameraStatusCallbacksInfo> info)1187 void HCameraService::CacheCameraStatus(const string& cameraId, std::shared_ptr<CameraStatusCallbacksInfo> info)
1188 {
1189     std::lock_guard<std::mutex> lock(cameraStatusCallbacksMutex_);
1190     cameraStatusCallbacks_[cameraId] = info;
1191 }
1192 
GetCachedCameraStatus(const string & cameraId)1193 std::shared_ptr<CameraStatusCallbacksInfo> HCameraService::GetCachedCameraStatus(const string& cameraId)
1194 {
1195     std::lock_guard<std::mutex> lock(cameraStatusCallbacksMutex_);
1196     auto it = cameraStatusCallbacks_.find(cameraId);
1197     if (it == cameraStatusCallbacks_.end()) {
1198         return nullptr;
1199     }
1200     return it->second;
1201 }
1202 
CacheFlashStatus(const string & cameraId,FlashStatus flashStatus)1203 void HCameraService::CacheFlashStatus(const string& cameraId, FlashStatus flashStatus)
1204 {
1205     std::lock_guard<std::mutex> lock(flashStatusCallbacksMutex_);
1206     flashStatusCallbacks_[cameraId] = flashStatus;
1207 }
1208 
GetCachedFlashStatus(const string & cameraId)1209 FlashStatus HCameraService::GetCachedFlashStatus(const string& cameraId)
1210 {
1211     std::lock_guard<std::mutex> lock(flashStatusCallbacksMutex_);
1212     auto it = flashStatusCallbacks_.find(cameraId);
1213     if (it == flashStatusCallbacks_.end()) {
1214         return FlashStatus::FLASH_STATUS_UNAVAILABLE;
1215     }
1216     return it->second;
1217 }
1218 
1219 static std::map<PolicyType, Security::AccessToken::PolicyType> g_policyTypeMap_ = {
1220     {PolicyType::EDM, Security::AccessToken::PolicyType::EDM},
1221     {PolicyType::PRIVACY, Security::AccessToken::PolicyType::PRIVACY},
1222 };
1223 
MuteCamera(bool muteMode)1224 int32_t HCameraService::MuteCamera(bool muteMode)
1225 {
1226     int32_t ret = CheckPermission(OHOS_PERMISSION_MANAGE_CAMERA_CONFIG, IPCSkeleton::GetCallingTokenID());
1227     CHECK_ERROR_RETURN_RET_LOG(ret != CAMERA_OK, ret, "CheckPermission argumentis failed!");
1228     CameraReportUtils::GetInstance().ReportUserBehavior(DFX_UB_MUTE_CAMERA,
1229         to_string(muteMode), CameraReportUtils::GetCallerInfo());
1230     return MuteCameraFunc(muteMode);
1231 }
1232 
MuteCameraPersist(PolicyType policyType,bool isMute)1233 int32_t HCameraService::MuteCameraPersist(PolicyType policyType, bool isMute)
1234 {
1235     OHOS::Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
1236     int32_t ret = CheckPermission(OHOS_PERMISSION_CAMERA_CONTROL, callerToken);
1237     CHECK_ERROR_RETURN_RET_LOG(ret != CAMERA_OK, ret, "CheckPermission arguments failed!");
1238     CameraReportUtils::GetInstance().ReportUserBehavior(DFX_UB_MUTE_CAMERA,
1239         to_string(isMute), CameraReportUtils::GetCallerInfo());
1240     CHECK_ERROR_RETURN_RET_LOG(g_policyTypeMap_.count(policyType) == 0, CAMERA_INVALID_ARG,
1241         "MuteCameraPersist Failed, invalid param policyType = %{public}d", static_cast<int32_t>(policyType));
1242     bool targetMuteMode = isMute;
1243     const Security::AccessToken::PolicyType secPolicyType = g_policyTypeMap_[policyType];
1244     const Security::AccessToken::CallerType secCaller = Security::AccessToken::CallerType::CAMERA;
1245     ret = Security::AccessToken::PrivacyKit::SetMutePolicy(secPolicyType, secCaller, isMute, callerToken);
1246     if (ret != Security::AccessToken::RET_SUCCESS) {
1247         MEDIA_ERR_LOG("MuteCameraPersist SetMutePolicy return false, policyType = %{public}d, retCode = %{public}d",
1248             static_cast<int32_t>(policyType), static_cast<int32_t>(ret));
1249         targetMuteMode = muteModeStored_;
1250     }
1251     return MuteCameraFunc(targetMuteMode);
1252 }
1253 
PrelaunchCamera()1254 int32_t HCameraService::PrelaunchCamera()
1255 {
1256     CAMERA_SYNC_TRACE;
1257     MEDIA_INFO_LOG("HCameraService::PrelaunchCamera");
1258     CHECK_ERROR_RETURN_RET_LOG(HCameraDeviceManager::GetInstance()->GetCameraStateOfASide().Size() != 0,
1259         CAMERA_DEVICE_CONFLICT, "HCameraService::PrelaunchCamera there is a device active in A side, abort!");
1260     if (preCameraId_.empty()) {
1261         MEDIA_DEBUG_LOG("HCameraService::PrelaunchCamera firstBoot in");
1262         if (OHOS::Rosen::DisplayManager::GetInstance().IsFoldable()) {
1263             // foldable devices
1264             MEDIA_DEBUG_LOG("HCameraService::PrelaunchCamera firstBoot foldable");
1265             FoldStatus curFoldStatus = (FoldStatus)OHOS::Rosen::DisplayManager::GetInstance().GetFoldStatus();
1266             MEDIA_DEBUG_LOG("HCameraService::PrelaunchCamera curFoldStatus:%d", curFoldStatus);
1267             std::vector<std::string> cameraIds;
1268             std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> cameraAbilityList;
1269             int32_t retCode = GetCameras(cameraIds, cameraAbilityList);
1270             CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, CAMERA_OK, "HCameraService::PrelaunchCamera exit");
1271             int8_t camIdx = ChooseFisrtBootFoldCamIdx(curFoldStatus, cameraAbilityList);
1272             CHECK_ERROR_RETURN_RET_LOG(camIdx == -1, CAMERA_OK, "HCameraService::PrelaunchCamera exit");
1273             preCameraId_ = cameraIds[camIdx];
1274         } else {
1275             // unfoldable devices
1276             MEDIA_DEBUG_LOG("HCameraService::PrelaunchCamera firstBoot unfoldable");
1277             vector<string> cameraIds_;
1278             cameraHostManager_->GetCameras(cameraIds_);
1279             CHECK_ERROR_RETURN_RET_LOG(cameraIds_.empty(), CAMERA_OK, "HCameraService::PrelaunchCamera exit");
1280             preCameraId_ = cameraIds_.front();
1281         }
1282     }
1283     MEDIA_INFO_LOG("HCameraService::PrelaunchCamera preCameraId_ is: %{public}s", preCameraId_.c_str());
1284     CAMERA_SYSEVENT_STATISTIC(CreateMsg("Camera Prelaunch CameraId:%s", preCameraId_.c_str()));
1285     CameraReportUtils::GetInstance().SetOpenCamPerfPreInfo(preCameraId_.c_str(), CameraReportUtils::GetCallerInfo());
1286     int32_t ret = cameraHostManager_->Prelaunch(preCameraId_, preCameraClient_);
1287     CHECK_ERROR_PRINT_LOG(ret != CAMERA_OK, "HCameraService::Prelaunch failed");
1288     return ret;
1289 }
1290 
1291 /**
1292     camIdx select strategy:
1293     1. make sure curFoldStatus match foldStatusValue
1294     2. priority: BACK > FRONT > OTHER
1295     curFoldStatus 0: UNKNOWN_FOLD
1296     curFoldStatus 1: EXPAND
1297     curFoldStatus 2: FOLDED
1298     curFoldStatus 3: HALF_FOLD
1299     foldStatusValue 0: OHOS_CAMERA_FOLD_STATUS_NONFOLDABLE
1300     foldStatusValue 1: OHOS_CAMERA_FOLD_STATUS_EXPANDED
1301     foldStatusValue 2: OHOS_CAMERA_FOLD_STATUS_FOLDED
1302     foldStatusValue 3: OHOS_CAMERA_FOLD_STATUS_EXPANDED + OHOS_CAMERA_FOLD_STATUS_FOLDED
1303     positionValue 0: OHOS_CAMERA_POSITION_FRONT
1304     positionValue 1: OHOS_CAMERA_POSITION_BACK
1305     positionValue 2: OHOS_CAMERA_POSITION_OTHER
1306 */
ChooseFisrtBootFoldCamIdx(FoldStatus curFoldStatus,std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> cameraAbilityList)1307 int8_t HCameraService::ChooseFisrtBootFoldCamIdx(
1308     FoldStatus curFoldStatus, std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> cameraAbilityList)
1309 {
1310     int8_t camIdx = -1;
1311     uint8_t foldStatusValue = 0;
1312     uint8_t positionValue = 0;
1313     uint8_t EXPAND_SUPPORT = 1;
1314     uint8_t FOLD_SUPPORT = 2;
1315     uint8_t ALL_SUPPORT = 3;
1316     for (size_t i = 0; i < cameraAbilityList.size(); i++) {
1317         camera_metadata_item_t item;
1318         int ret =
1319             OHOS::Camera::FindCameraMetadataItem(cameraAbilityList[i]->get(), OHOS_ABILITY_CAMERA_FOLD_STATUS, &item);
1320         if (ret == CAM_META_SUCCESS && item.count > 0) {
1321             MEDIA_DEBUG_LOG("HCameraService::PrelaunchCamera device fold ablity is %{public}d", item.data.u8[0]);
1322             foldStatusValue = item.data.u8[0];
1323         } else {
1324             MEDIA_DEBUG_LOG("HCameraService::PrelaunchCamera device ablity not found");
1325         }
1326         ret = OHOS::Camera::FindCameraMetadataItem(cameraAbilityList[i]->get(), OHOS_ABILITY_CAMERA_POSITION, &item);
1327         if (ret == CAM_META_SUCCESS && item.count > 0) {
1328             MEDIA_DEBUG_LOG("HCameraService::PrelaunchCamera device position is %{public}d", item.data.u8[0]);
1329             positionValue = item.data.u8[0];
1330         } else {
1331             MEDIA_DEBUG_LOG("HCameraService::PrelaunchCamera device position not found");
1332         }
1333         // check is fold supported
1334         bool isFoldSupported = false;
1335         if (curFoldStatus == FOLDED) {
1336             isFoldSupported = (foldStatusValue == FOLD_SUPPORT || foldStatusValue == ALL_SUPPORT);
1337         } else if (curFoldStatus == EXPAND || curFoldStatus == HALF_FOLD) {
1338             isFoldSupported = (foldStatusValue == EXPAND_SUPPORT || foldStatusValue == ALL_SUPPORT);
1339         }
1340         // choose camIdx by priority
1341         if (isFoldSupported) {
1342             if (positionValue == OHOS_CAMERA_POSITION_BACK) {
1343                 camIdx = i;
1344                 break; // use BACK
1345             } else if (positionValue == OHOS_CAMERA_POSITION_FRONT && camIdx == -1) {
1346                 camIdx = i; // record FRONT find BACK continue
1347             } else if (positionValue == OHOS_CAMERA_POSITION_OTHER && camIdx == -1) {
1348                 camIdx = i; // record OTHER find BACK&FRONT continue
1349             }
1350         }
1351     }
1352     return camIdx;
1353 }
1354 
PreSwitchCamera(const std::string cameraId)1355 int32_t HCameraService::PreSwitchCamera(const std::string cameraId)
1356 {
1357     CAMERA_SYNC_TRACE;
1358     MEDIA_INFO_LOG("HCameraService::PreSwitchCamera");
1359     CHECK_ERROR_RETURN_RET(cameraId.empty(), CAMERA_INVALID_ARG);
1360     std::vector<std::string> cameraIds_;
1361     cameraHostManager_->GetCameras(cameraIds_);
1362     CHECK_ERROR_RETURN_RET(cameraIds_.empty(), CAMERA_INVALID_STATE);
1363     auto it = std::find(cameraIds_.begin(), cameraIds_.end(), cameraId);
1364     CHECK_ERROR_RETURN_RET(it == cameraIds_.end(), CAMERA_INVALID_ARG);
1365     MEDIA_INFO_LOG("HCameraService::PreSwitchCamera cameraId is: %{public}s", cameraId.c_str());
1366     CameraReportUtils::GetInstance().SetSwitchCamPerfStartInfo(CameraReportUtils::GetCallerInfo());
1367     int32_t ret = cameraHostManager_->PreSwitchCamera(cameraId);
1368     CHECK_ERROR_PRINT_LOG(ret != CAMERA_OK, "HCameraService::Prelaunch failed");
1369     return ret;
1370 }
1371 
SetPrelaunchConfig(string cameraId,RestoreParamTypeOhos restoreParamType,int activeTime,EffectParam effectParam)1372 int32_t HCameraService::SetPrelaunchConfig(string cameraId, RestoreParamTypeOhos restoreParamType, int activeTime,
1373     EffectParam effectParam)
1374 {
1375     CAMERA_SYNC_TRACE;
1376     OHOS::Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
1377     string permissionName = OHOS_PERMISSION_CAMERA;
1378     int32_t ret = CheckPermission(permissionName, callerToken);
1379     CHECK_ERROR_RETURN_RET_LOG(ret != CAMERA_OK, ret,
1380         "HCameraService::SetPrelaunchConfig failed permission is: %{public}s", permissionName.c_str());
1381 
1382     MEDIA_INFO_LOG("HCameraService::SetPrelaunchConfig cameraId %{public}s", (cameraId).c_str());
1383     vector<string> cameraIds_;
1384     cameraHostManager_->GetCameras(cameraIds_);
1385     if ((find(cameraIds_.begin(), cameraIds_.end(), cameraId) != cameraIds_.end()) && IsPrelaunchSupported(cameraId)) {
1386         preCameraId_ = cameraId;
1387         MEDIA_INFO_LOG("CameraHostInfo::SetPrelaunchConfig for cameraId %{public}s", (cameraId).c_str());
1388         sptr<HCaptureSession> captureSession_ = nullptr;
1389         pid_t pid = IPCSkeleton::GetCallingPid();
1390         captureSessionsManager_.Find(pid, captureSession_);
1391         SaveCurrentParamForRestore(cameraId, static_cast<RestoreParamTypeOhos>(restoreParamType), activeTime,
1392             effectParam, captureSession_);
1393         captureSessionsManager_.Clear();
1394         captureSessionsManager_.EnsureInsert(pid, captureSession_);
1395     } else {
1396         MEDIA_ERR_LOG("HCameraService::SetPrelaunchConfig illegal");
1397         ret = CAMERA_INVALID_ARG;
1398     }
1399     return ret;
1400 }
1401 
SetTorchLevel(float level)1402 int32_t HCameraService::SetTorchLevel(float level)
1403 {
1404     int32_t ret = cameraHostManager_->SetTorchLevel(level);
1405     CHECK_ERROR_PRINT_LOG(ret != CAMERA_OK, "Failed to SetTorchLevel");
1406     return ret;
1407 }
1408 
AllowOpenByOHSide(std::string cameraId,int32_t state,bool & canOpenCamera)1409 int32_t HCameraService::AllowOpenByOHSide(std::string cameraId, int32_t state, bool& canOpenCamera)
1410 {
1411     MEDIA_INFO_LOG("HCameraService::AllowOpenByOHSide start");
1412     std::vector<pid_t> activePids = HCameraDeviceManager::GetInstance()->GetActiveClient();
1413     if (activePids.size() == 0) {
1414         MEDIA_INFO_LOG("AllowOpenByOHSide::Open allow open camera");
1415         NotifyCameraState(cameraId, 0);
1416         canOpenCamera = true;
1417         return CAMERA_OK;
1418     }
1419     for (auto eachPid : activePids) {
1420         std::vector<sptr<HCameraDevice>> camerasNeedEvict =
1421             HCameraDeviceManager::GetInstance()->GetCamerasByPid(eachPid);
1422         for (auto device : camerasNeedEvict) {
1423             device->OnError(DEVICE_PREEMPT, 0);
1424             device->Close();
1425             NotifyCameraState(cameraId, 0);
1426         }
1427     }
1428     canOpenCamera = true;
1429     MEDIA_INFO_LOG("HCameraService::AllowOpenByOHSide end");
1430     return CAMERA_OK;
1431 }
1432 
NotifyCameraState(std::string cameraId,int32_t state)1433 int32_t HCameraService::NotifyCameraState(std::string cameraId, int32_t state)
1434 {
1435     // 把cameraId和前后台状态刷新给device manager
1436     MEDIA_INFO_LOG(
1437         "HCameraService::NotifyCameraState SetStateOfACamera %{public}s:%{public}d", cameraId.c_str(), state);
1438     HCameraDeviceManager::GetInstance()->SetStateOfACamera(cameraId, state);
1439     return CAMERA_OK;
1440 }
1441 
SetPeerCallback(sptr<ICameraBroker> & callback)1442 int32_t HCameraService::SetPeerCallback(sptr<ICameraBroker>& callback)
1443 {
1444     MEDIA_INFO_LOG("SetPeerCallback get callback");
1445     CHECK_ERROR_RETURN_RET(callback == nullptr, CAMERA_INVALID_ARG);
1446     {
1447         std::lock_guard<std::mutex> lock(peerCallbackMutex_);
1448         peerCallback_ = callback;
1449     }
1450     MEDIA_INFO_LOG("HCameraService::SetPeerCallback current muteMode:%{public}d", muteModeStored_);
1451     callback->NotifyMuteCamera(muteModeStored_);
1452     HCameraDeviceManager::GetInstance()->SetPeerCallback(callback);
1453     return CAMERA_OK;
1454 }
1455 
UnsetPeerCallback()1456 int32_t HCameraService::UnsetPeerCallback()
1457 {
1458     MEDIA_INFO_LOG("UnsetPeerCallback callback");
1459     {
1460         std::lock_guard<std::mutex> lock(peerCallbackMutex_);
1461         peerCallback_ = nullptr;
1462     }
1463     HCameraDeviceManager::GetInstance()->UnsetPeerCallback();
1464     return CAMERA_OK;
1465 }
1466 
IsPrelaunchSupported(string cameraId)1467 bool HCameraService::IsPrelaunchSupported(string cameraId)
1468 {
1469     bool isPrelaunchSupported = false;
1470     shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility;
1471     int32_t ret = cameraHostManager_->GetCameraAbility(cameraId, cameraAbility);
1472     CHECK_ERROR_RETURN_RET_LOG(ret != CAMERA_OK, isPrelaunchSupported,
1473         "HCameraService::IsCameraMuted GetCameraAbility failed");
1474     camera_metadata_item_t item;
1475     common_metadata_header_t* metadata = cameraAbility->get();
1476     ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_PRELAUNCH_AVAILABLE, &item);
1477     if (ret == 0) {
1478         MEDIA_INFO_LOG(
1479             "CameraManager::IsPrelaunchSupported() OHOS_ABILITY_PRELAUNCH_AVAILABLE is %{public}d", item.data.u8[0]);
1480         isPrelaunchSupported = (item.data.u8[0] == 1);
1481     } else {
1482         MEDIA_ERR_LOG("Failed to get OHOS_ABILITY_PRELAUNCH_AVAILABLE ret = %{public}d", ret);
1483     }
1484     return isPrelaunchSupported;
1485 }
1486 
GetServiceStatus()1487 CameraServiceStatus HCameraService::GetServiceStatus()
1488 {
1489     lock_guard<mutex> lock(serviceStatusMutex_);
1490     return serviceStatus_;
1491 }
1492 
SetServiceStatus(CameraServiceStatus serviceStatus)1493 void HCameraService::SetServiceStatus(CameraServiceStatus serviceStatus)
1494 {
1495     lock_guard<mutex> lock(serviceStatusMutex_);
1496     serviceStatus_ = serviceStatus;
1497     MEDIA_DEBUG_LOG("HCameraService::SetServiceStatus success. serviceStatus: %{public}d", serviceStatus);
1498 }
1499 
IsTorchSupported(bool & isTorchSupported)1500 int32_t HCameraService::IsTorchSupported(bool &isTorchSupported)
1501 {
1502     isTorchSupported = false;
1503     std::vector<std::string> cameraIds;
1504     std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> cameraAbilityList;
1505     int32_t retCode = GetCameras(cameraIds, cameraAbilityList);
1506     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, retCode, "HCameraService::IsTorchSupported failed");
1507     for (auto& cameraAbility : cameraAbilityList) {
1508         camera_metadata_item_t item;
1509         int ret = OHOS::Camera::FindCameraMetadataItem(cameraAbility->get(), OHOS_ABILITY_FLASH_AVAILABLE, &item);
1510         if (ret == CAM_META_SUCCESS && item.count > 0) {
1511             MEDIA_DEBUG_LOG("OHOS_ABILITY_FLASH_AVAILABLE is %{public}d", item.data.u8[0]);
1512             if (item.data.u8[0] == 1) {
1513                 isTorchSupported = true;
1514                 break;
1515             }
1516         }
1517     }
1518     MEDIA_DEBUG_LOG("HCameraService::isTorchSupported success. isTorchSupported: %{public}d", isTorchSupported);
1519     return retCode;
1520 }
1521 
IsCameraMuteSupported(bool & isCameraMuteSupported)1522 int32_t HCameraService::IsCameraMuteSupported(bool &isCameraMuteSupported)
1523 {
1524     isCameraMuteSupported = false;
1525     std::vector<std::string> cameraIds;
1526     std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> cameraAbilityList;
1527     int32_t retCode = GetCameras(cameraIds, cameraAbilityList);
1528     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, retCode, "HCameraService::IsCameraMuteSupported failed");
1529     for (auto& cameraId : cameraIds) {
1530         isCameraMuteSupported = IsCameraMuteSupported(cameraId);
1531         if (isCameraMuteSupported) {
1532             break;
1533         }
1534     }
1535     return retCode;
1536 }
1537 
IsCameraMuted(bool & muteMode)1538 int32_t HCameraService::IsCameraMuted(bool& muteMode)
1539 {
1540     lock_guard<mutex> lock(g_dataShareHelperMutex);
1541     CHECK_ERROR_RETURN_RET(GetServiceStatus() != CameraServiceStatus::SERVICE_READY, CAMERA_INVALID_STATE);
1542     muteMode = muteModeStored_;
1543 
1544     MEDIA_DEBUG_LOG("HCameraService::IsCameraMuted success. isMuted: %{public}d", muteMode);
1545     return CAMERA_OK;
1546 }
1547 
DumpCameraSummary(vector<string> cameraIds,CameraInfoDumper & infoDumper)1548 void HCameraService::DumpCameraSummary(vector<string> cameraIds, CameraInfoDumper& infoDumper)
1549 {
1550     infoDumper.Tip("--------Dump Summary Begin-------");
1551     infoDumper.Title("Number of Cameras:[" + to_string(cameraIds.size()) + "]");
1552     infoDumper.Title(
1553         "Number of Active Cameras:[" + to_string(HCameraDeviceManager::GetInstance()->GetActiveCamerasCount()) + "]");
1554     infoDumper.Title("Current session summary:");
1555     HCaptureSession::DumpCameraSessionSummary(infoDumper);
1556 }
1557 
DumpCameraInfo(CameraInfoDumper & infoDumper,std::vector<std::string> & cameraIds,std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> & cameraAbilityList)1558 void HCameraService::DumpCameraInfo(CameraInfoDumper& infoDumper, std::vector<std::string>& cameraIds,
1559     std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>>& cameraAbilityList)
1560 {
1561     infoDumper.Tip("--------Dump CameraDevice Begin-------");
1562     int32_t capIdx = 0;
1563     for (auto& it : cameraIds) {
1564         auto metadata = cameraAbilityList[capIdx++];
1565         common_metadata_header_t* metadataEntry = metadata->get();
1566         infoDumper.Title("Camera ID:[" + it + "]:");
1567         infoDumper.Push();
1568         DumpCameraAbility(metadataEntry, infoDumper);
1569         DumpCameraStreamInfo(metadataEntry, infoDumper);
1570         DumpCameraZoom(metadataEntry, infoDumper);
1571         DumpCameraFlash(metadataEntry, infoDumper);
1572         DumpCameraCompensation(metadataEntry, infoDumper);
1573         DumpCameraColorSpace(metadataEntry, infoDumper);
1574         DumpCameraAF(metadataEntry, infoDumper);
1575         DumpCameraAE(metadataEntry, infoDumper);
1576         DumpCameraSensorInfo(metadataEntry, infoDumper);
1577         DumpCameraVideoStabilization(metadataEntry, infoDumper);
1578         DumpCameraVideoFrameRateRange(metadataEntry, infoDumper);
1579         DumpCameraPrelaunch(metadataEntry, infoDumper);
1580         DumpCameraThumbnail(metadataEntry, infoDumper);
1581         infoDumper.Pop();
1582     }
1583 }
1584 
DumpCameraAbility(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1585 void HCameraService::DumpCameraAbility(common_metadata_header_t* metadataEntry, CameraInfoDumper& infoDumper)
1586 {
1587     camera_metadata_item_t item;
1588     int ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_CAMERA_POSITION, &item);
1589     if (ret == CAM_META_SUCCESS) {
1590         map<int, string>::const_iterator iter = g_cameraPos.find(item.data.u8[0]);
1591         CHECK_EXECUTE(iter != g_cameraPos.end(), infoDumper.Title("Camera Position:[" + iter->second + "]"));
1592     }
1593 
1594     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_CAMERA_TYPE, &item);
1595     if (ret == CAM_META_SUCCESS) {
1596         map<int, string>::const_iterator iter = g_cameraType.find(item.data.u8[0]);
1597         CHECK_EXECUTE(iter != g_cameraType.end(), infoDumper.Title("Camera Type:[" + iter->second + "]"));
1598     }
1599 
1600     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_CAMERA_CONNECTION_TYPE, &item);
1601     if (ret == CAM_META_SUCCESS) {
1602         map<int, string>::const_iterator iter = g_cameraConType.find(item.data.u8[0]);
1603         CHECK_EXECUTE(iter != g_cameraConType.end(),
1604             infoDumper.Title("Camera Connection Type:[" + iter->second + "]"));
1605     }
1606 }
1607 
DumpCameraStreamInfo(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1608 void HCameraService::DumpCameraStreamInfo(common_metadata_header_t* metadataEntry, CameraInfoDumper& infoDumper)
1609 {
1610     camera_metadata_item_t item;
1611     int ret;
1612     constexpr uint32_t unitLen = 3;
1613     uint32_t widthOffset = 1;
1614     uint32_t heightOffset = 2;
1615     infoDumper.Title("Camera Available stream configuration List:");
1616     infoDumper.Push();
1617     ret =
1618         OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_STREAM_AVAILABLE_BASIC_CONFIGURATIONS, &item);
1619     if (ret == CAM_META_SUCCESS) {
1620         infoDumper.Title("Basic Stream Info Size: " + to_string(item.count / unitLen));
1621         for (uint32_t index = 0; index < item.count; index += unitLen) {
1622             map<int, string>::const_iterator iter = g_cameraFormat.find(item.data.i32[index]);
1623             if (iter != g_cameraFormat.end()) {
1624                 infoDumper.Msg("Format:[" + iter->second + "]    " +
1625                                "Size:[Width:" + to_string(item.data.i32[index + widthOffset]) +
1626                                " Height:" + to_string(item.data.i32[index + heightOffset]) + "]");
1627             } else {
1628                 infoDumper.Msg("Format:[" + to_string(item.data.i32[index]) + "]    " +
1629                                "Size:[Width:" + to_string(item.data.i32[index + widthOffset]) +
1630                                " Height:" + to_string(item.data.i32[index + heightOffset]) + "]");
1631             }
1632         }
1633     }
1634 
1635     infoDumper.Pop();
1636 }
1637 
DumpCameraZoom(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1638 void HCameraService::DumpCameraZoom(common_metadata_header_t* metadataEntry, CameraInfoDumper& infoDumper)
1639 {
1640     camera_metadata_item_t item;
1641     int ret;
1642     int32_t minIndex = 0;
1643     int32_t maxIndex = 1;
1644     uint32_t zoomRangeCount = 2;
1645     infoDumper.Title("Zoom Related Info:");
1646 
1647     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_ZOOM_CAP, &item);
1648     if (ret == CAM_META_SUCCESS) {
1649         infoDumper.Msg("OHOS_ABILITY_ZOOM_CAP data size:" + to_string(item.count));
1650         if (item.count == zoomRangeCount) {
1651             infoDumper.Msg("Available Zoom Capability:[" + to_string(item.data.i32[minIndex]) + "  " +
1652                            to_string(item.data.i32[maxIndex]) + "]");
1653         }
1654     }
1655 
1656     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_SCENE_ZOOM_CAP, &item);
1657     if (ret == CAM_META_SUCCESS) {
1658         infoDumper.Msg("OHOS_ABILITY_ZOOM_RATIO_RANGE data size:" + to_string(item.count));
1659         string zoomAbilityString = "Available Zoom Modes:[ ";
1660         int reduce = 100;
1661         int size = 3;
1662         float range;
1663         int32_t val;
1664         for (uint32_t i = 0; i < item.count; i++) {
1665             val = item.data.i32[i];
1666             if (i % size != 0) {
1667                 range = (float)val / reduce;
1668                 zoomAbilityString.append(to_string(range) + " ");
1669             } else {
1670                 zoomAbilityString.append(" mode: " + to_string(val) + " ");
1671             }
1672         }
1673         zoomAbilityString.append("]");
1674         infoDumper.Msg(zoomAbilityString);
1675     }
1676 
1677     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_ZOOM_RATIO_RANGE, &item);
1678     if (ret == CAM_META_SUCCESS) {
1679         infoDumper.Msg("OHOS_ABILITY_ZOOM_RATIO_RANGE data size:" + to_string(item.count));
1680         if (item.count == zoomRangeCount) {
1681             infoDumper.Msg("Available Zoom Ratio Range:[" + to_string(item.data.f[minIndex]) +
1682                            to_string(item.data.f[maxIndex]) + "]");
1683         }
1684     }
1685 }
1686 
DumpCameraFlash(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1687 void HCameraService::DumpCameraFlash(common_metadata_header_t* metadataEntry, CameraInfoDumper& infoDumper)
1688 {
1689     camera_metadata_item_t item;
1690     int ret;
1691     infoDumper.Title("Flash Related Info:");
1692     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_FLASH_MODES, &item);
1693     if (ret == CAM_META_SUCCESS) {
1694         string flashAbilityString = "Available Flash Modes:[ ";
1695         for (uint32_t i = 0; i < item.count; i++) {
1696             map<int, string>::const_iterator iter = g_cameraFlashMode.find(item.data.u8[i]);
1697             CHECK_EXECUTE(iter != g_cameraFlashMode.end(), flashAbilityString.append(iter->second + " "));
1698         }
1699         flashAbilityString.append("]");
1700         infoDumper.Msg(flashAbilityString);
1701     }
1702 }
1703 
DumpCameraCompensation(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1704 void HCameraService::DumpCameraCompensation(common_metadata_header_t *metadataEntry, CameraInfoDumper &infoDumper)
1705 {
1706     camera_metadata_item_t item;
1707     int ret;
1708     infoDumper.Title("Compensation Related Info:");
1709     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_AE_COMPENSATION_RANGE, &item);
1710     if (ret == CAM_META_SUCCESS) {
1711         string compensationAbilityString = "Available Compensation Modes:[ ";
1712         for (uint32_t i = 0; i < item.count; i++) {
1713             int32_t val = item.data.i32[i];
1714             compensationAbilityString.append(to_string(val));
1715         }
1716         compensationAbilityString.append("]");
1717         infoDumper.Msg(compensationAbilityString);
1718     }
1719 }
1720 
DumpCameraColorSpace(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1721 void HCameraService::DumpCameraColorSpace(common_metadata_header_t *metadataEntry, CameraInfoDumper &infoDumper)
1722 {
1723     camera_metadata_item_t item;
1724     int ret;
1725     infoDumper.Title("Color Space Related Info:");
1726     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_AVAILABLE_COLOR_SPACES, &item);
1727     if (ret == CAM_META_SUCCESS) {
1728         string colorSpaceAbilityString = "Available Color Space Modes:[ ";
1729         for (uint32_t i = 0; i < item.count; i++) {
1730             int32_t val = item.data.i32[i];
1731             colorSpaceAbilityString.append(to_string(val));
1732         }
1733         colorSpaceAbilityString.append("]");
1734         infoDumper.Msg(colorSpaceAbilityString);
1735     }
1736 }
1737 
DumpCameraAF(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1738 void HCameraService::DumpCameraAF(common_metadata_header_t *metadataEntry, CameraInfoDumper &infoDumper)
1739 {
1740     camera_metadata_item_t item;
1741     int ret;
1742     infoDumper.Title("AF Related Info:");
1743     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_FOCUS_MODES, &item);
1744     if (ret == CAM_META_SUCCESS) {
1745         string afAbilityString = "Available Focus Modes:[ ";
1746         for (uint32_t i = 0; i < item.count; i++) {
1747             map<int, string>::const_iterator iter = g_cameraFocusMode.find(item.data.u8[i]);
1748             CHECK_EXECUTE(iter != g_cameraFocusMode.end(), afAbilityString.append(iter->second + " "));
1749         }
1750         afAbilityString.append("]");
1751         infoDumper.Msg(afAbilityString);
1752     }
1753 }
1754 
DumpCameraAE(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1755 void HCameraService::DumpCameraAE(common_metadata_header_t* metadataEntry, CameraInfoDumper& infoDumper)
1756 {
1757     camera_metadata_item_t item;
1758     int ret;
1759     infoDumper.Title("AE Related Info:");
1760     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_EXPOSURE_MODES, &item);
1761     if (ret == CAM_META_SUCCESS) {
1762         string aeAbilityString = "Available Exposure Modes:[ ";
1763         for (uint32_t i = 0; i < item.count; i++) {
1764             map<int, string>::const_iterator iter = g_cameraExposureMode.find(item.data.u8[i]);
1765             CHECK_EXECUTE(iter != g_cameraExposureMode.end(), aeAbilityString.append(iter->second + " "));
1766         }
1767         aeAbilityString.append("]");
1768         infoDumper.Msg(aeAbilityString);
1769     }
1770 }
1771 
DumpCameraSensorInfo(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1772 void HCameraService::DumpCameraSensorInfo(common_metadata_header_t* metadataEntry, CameraInfoDumper& infoDumper)
1773 {
1774     camera_metadata_item_t item;
1775     int ret;
1776     int32_t leftIndex = 0;
1777     int32_t topIndex = 1;
1778     int32_t rightIndex = 2;
1779     int32_t bottomIndex = 3;
1780     infoDumper.Title("Sensor Related Info:");
1781     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_SENSOR_INFO_ACTIVE_ARRAY_SIZE, &item);
1782     if (ret == CAM_META_SUCCESS) {
1783         infoDumper.Msg("Array:[" +
1784             to_string(item.data.i32[leftIndex]) + " " +
1785             to_string(item.data.i32[topIndex]) + " " +
1786             to_string(item.data.i32[rightIndex]) + " " +
1787             to_string(item.data.i32[bottomIndex]) + "]:\n");
1788     }
1789 }
1790 
DumpCameraVideoStabilization(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1791 void HCameraService::DumpCameraVideoStabilization(common_metadata_header_t* metadataEntry, CameraInfoDumper& infoDumper)
1792 {
1793     camera_metadata_item_t item;
1794     int ret;
1795     infoDumper.Title("Video Stabilization Related Info:");
1796     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_VIDEO_STABILIZATION_MODES, &item);
1797     if (ret == CAM_META_SUCCESS) {
1798         std::string infoString = "Available Video Stabilization Modes:[ ";
1799         for (uint32_t i = 0; i < item.count; i++) {
1800             map<int, string>::const_iterator iter = g_cameraVideoStabilizationMode.find(item.data.u8[i]);
1801             CHECK_EXECUTE(iter != g_cameraVideoStabilizationMode.end(), infoString.append(iter->second + " "));
1802         }
1803         infoString.append("]:");
1804         infoDumper.Msg(infoString);
1805     }
1806 }
1807 
DumpCameraVideoFrameRateRange(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1808 void HCameraService::DumpCameraVideoFrameRateRange(
1809     common_metadata_header_t* metadataEntry, CameraInfoDumper& infoDumper)
1810 {
1811     camera_metadata_item_t item;
1812     const int32_t FRAME_RATE_RANGE_STEP = 2;
1813     int ret;
1814     infoDumper.Title("Video FrameRateRange Related Info:");
1815     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_FPS_RANGES, &item);
1816     if (ret == CAM_META_SUCCESS && item.count > 0) {
1817         infoDumper.Msg("Available FrameRateRange:");
1818         for (uint32_t i = 0; i < (item.count - 1); i += FRAME_RATE_RANGE_STEP) {
1819             infoDumper.Msg("[ " + to_string(item.data.i32[i]) + ", " + to_string(item.data.i32[i + 1]) + " ]");
1820         }
1821     }
1822 }
1823 
DumpCameraPrelaunch(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1824 void HCameraService::DumpCameraPrelaunch(common_metadata_header_t* metadataEntry, CameraInfoDumper& infoDumper)
1825 {
1826     camera_metadata_item_t item;
1827     int ret;
1828     infoDumper.Title("Camera Prelaunch Related Info:");
1829     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_PRELAUNCH_AVAILABLE, &item);
1830     if (ret == CAM_META_SUCCESS) {
1831         map<int, string>::const_iterator iter = g_cameraPrelaunchAvailable.find(item.data.u8[0]);
1832         bool isSupport = false;
1833         if (iter != g_cameraPrelaunchAvailable.end()) {
1834             isSupport = true;
1835         }
1836         std::string infoString = "Available Prelaunch Info:[";
1837         infoString.append(isSupport ? "True" : "False");
1838         infoString.append("]");
1839         infoDumper.Msg(infoString);
1840     }
1841 }
1842 
DumpCameraThumbnail(common_metadata_header_t * metadataEntry,CameraInfoDumper & infoDumper)1843 void HCameraService::DumpCameraThumbnail(common_metadata_header_t* metadataEntry, CameraInfoDumper& infoDumper)
1844 {
1845     camera_metadata_item_t item;
1846     int ret;
1847     infoDumper.Title("Camera Thumbnail Related Info:");
1848     ret = OHOS::Camera::FindCameraMetadataItem(metadataEntry, OHOS_ABILITY_STREAM_QUICK_THUMBNAIL_AVAILABLE, &item);
1849     if (ret == CAM_META_SUCCESS) {
1850         map<int, string>::const_iterator iter = g_cameraQuickThumbnailAvailable.find(item.data.u8[0]);
1851         bool isSupport = false;
1852         if (iter != g_cameraQuickThumbnailAvailable.end()) {
1853             isSupport = true;
1854         }
1855         std::string infoString = "Available Thumbnail Info:[";
1856         infoString.append(isSupport ? "True" : "False");
1857         infoString.append("]");
1858         infoDumper.Msg(infoString);
1859     }
1860 }
1861 
DumpCameraConcurrency(CameraInfoDumper & infoDumper,std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> & cameraAbilityList)1862 void HCameraService::DumpCameraConcurrency(
1863     CameraInfoDumper &infoDumper, std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> &cameraAbilityList)
1864 {
1865     infoDumper.Title("Concurrency Camera Info");
1866     HCameraDeviceManager *deviceManager = HCameraDeviceManager::GetInstance();
1867     std::vector<sptr<HCameraDeviceHolder>> cameraHolder = deviceManager->GetActiveCameraHolders();
1868     std::vector<std::string> cameraIds;
1869     std::vector<sptr<HCameraDevice>> cameraDevices;
1870     for (auto entry : cameraHolder) {
1871         cameraIds.push_back(entry->GetDevice()->GetCameraId());
1872         cameraDevices.push_back(entry->GetDevice());
1873     }
1874     size_t activeCamerasCount = deviceManager->GetActiveCamerasCount();
1875     infoDumper.Title("Number of Active Cameras:[" + to_string(activeCamerasCount) + "]");
1876     DumpCameraInfo(infoDumper, cameraIds, cameraAbilityList);
1877     HCaptureSession::DumpSessions(infoDumper);
1878 }
1879 
Dump(int fd,const vector<u16string> & args)1880 int32_t HCameraService::Dump(int fd, const vector<u16string> &args)
1881 {
1882     unordered_set<u16string> argSets;
1883     for (decltype(args.size()) index = 0; index < args.size(); ++index) {
1884         argSets.insert(args[index]);
1885     }
1886     std::string dumpString;
1887     std::vector<std::string> cameraIds;
1888     std::vector<std::shared_ptr<OHOS::Camera::CameraMetadata>> cameraAbilityList;
1889     int ret = GetCameras(cameraIds, cameraAbilityList);
1890     CHECK_ERROR_RETURN_RET((ret != CAMERA_OK) || cameraIds.empty() || cameraAbilityList.empty(), OHOS::UNKNOWN_ERROR);
1891     CameraInfoDumper infoDumper(fd);
1892     CHECK_EXECUTE(args.empty() || argSets.count(u16string(u"summary")), DumpCameraSummary(cameraIds, infoDumper));
1893     CHECK_EXECUTE(args.empty() || argSets.count(u16string(u"ability")),
1894         DumpCameraInfo(infoDumper, cameraIds, cameraAbilityList));
1895     if (args.empty() || argSets.count(u16string(u"preconfig"))) {
1896         infoDumper.Tip("--------Dump PreconfigInfo Begin-------");
1897         DumpPreconfigInfo(infoDumper, cameraHostManager_);
1898     }
1899     if (args.empty() || argSets.count(u16string(u"clientwiseinfo"))) {
1900         infoDumper.Tip("--------Dump Clientwise Info Begin-------");
1901         HCaptureSession::DumpSessions(infoDumper);
1902     }
1903     CHECK_EXECUTE(argSets.count(std::u16string(u"debugOn")), SetCameraDebugValue(true));
1904 
1905     if (argSets.count(std::u16string(u"concurrency"))) {
1906         DumpCameraConcurrency(infoDumper, cameraAbilityList);
1907     }
1908     infoDumper.Print();
1909     return OHOS::NO_ERROR;
1910 }
1911 
SaveCurrentParamForRestore(std::string cameraId,RestoreParamTypeOhos restoreParamType,int activeTime,EffectParam effectParam,sptr<HCaptureSession> captureSession)1912 int32_t HCameraService::SaveCurrentParamForRestore(std::string cameraId, RestoreParamTypeOhos restoreParamType,
1913     int activeTime, EffectParam effectParam, sptr<HCaptureSession> captureSession)
1914 {
1915     MEDIA_INFO_LOG("HCameraService::SaveCurrentParamForRestore enter");
1916     int32_t rc = CAMERA_OK;
1917     preCameraClient_ = GetClientBundle(IPCSkeleton::GetCallingUid());
1918     sptr<HCameraRestoreParam> cameraRestoreParam = new HCameraRestoreParam(
1919         preCameraClient_, cameraId);
1920     cameraRestoreParam->SetRestoreParamType(restoreParamType);
1921     cameraRestoreParam->SetStartActiveTime(activeTime);
1922     int foldStatus = static_cast<int>(OHOS::Rosen::DisplayManager::GetInstance().GetFoldStatus());
1923     cameraRestoreParam->SetFoldStatus(foldStatus);
1924     if (captureSession == nullptr || restoreParamType == NO_NEED_RESTORE_PARAM_OHOS) {
1925         cameraHostManager_->SaveRestoreParam(cameraRestoreParam);
1926         return rc;
1927     }
1928 
1929     sptr<HCameraDeviceManager> deviceManager = HCameraDeviceManager::GetInstance();
1930     std::vector<pid_t> pidOfActiveClients = deviceManager->GetActiveClient();
1931     CHECK_ERROR_RETURN_RET_LOG(pidOfActiveClients.size() == 0, CAMERA_OPERATION_NOT_ALLOWED,
1932         "HCaptureSession::SaveCurrentParamForRestore() Failed to save param cause no device is opening");
1933     CHECK_ERROR_RETURN_RET_LOG(pidOfActiveClients.size() > 1, CAMERA_OPERATION_NOT_ALLOWED,
1934         "HCaptureSession::SaveCurrentParamForRestore() not supported for Multi-Device is opening");
1935     std::vector<sptr<HCameraDevice>> activeDevices = deviceManager->GetCamerasByPid(pidOfActiveClients[0]);
1936     CHECK_ERROR_RETURN_RET(activeDevices.empty(), CAMERA_OK);
1937     std::vector<StreamInfo_V1_1> allStreamInfos;
1938 
1939     if (activeDevices.size() == 1) {
1940         std::shared_ptr<OHOS::Camera::CameraMetadata> defaultSettings
1941             = CreateDefaultSettingForRestore(activeDevices[0]);
1942         UpdateSkinSmoothSetting(defaultSettings, effectParam.skinSmoothLevel);
1943         UpdateFaceSlenderSetting(defaultSettings, effectParam.faceSlender);
1944         UpdateSkinToneSetting(defaultSettings, effectParam.skinTone);
1945         cameraRestoreParam->SetSetting(defaultSettings);
1946     }
1947     rc = captureSession->GetCurrentStreamInfos(allStreamInfos);
1948     CHECK_ERROR_RETURN_RET_LOG(rc != CAMERA_OK, rc,
1949         "HCaptureSession::SaveCurrentParamForRestore() Failed to get streams info, %{public}d", rc);
1950     int count = 0;
1951     for (auto& info : allStreamInfos) {
1952         MEDIA_INFO_LOG("HCameraService::SaveCurrentParamForRestore: streamId is:%{public}d", info.v1_0.streamId_);
1953         count += (info.v1_0.streamId_ == 0) ? 1: 0;
1954     }
1955     CaptureSessionState currentState;
1956     captureSession->GetSessionState(currentState);
1957     bool isCommitConfig = (currentState == CaptureSessionState::SESSION_CONFIG_COMMITTED)
1958             || (currentState == CaptureSessionState::SESSION_STARTED);
1959     CHECK_ERROR_RETURN_RET_LOG((!isCommitConfig || count > 1), CAMERA_INVALID_ARG,
1960         "HCameraService::SaveCurrentParamForRestore stream is not commit or streamId is all 0");
1961     cameraRestoreParam->SetStreamInfo(allStreamInfos);
1962     cameraRestoreParam->SetCameraOpMode(captureSession->GetopMode());
1963     cameraHostManager_->SaveRestoreParam(cameraRestoreParam);
1964     return rc;
1965 }
1966 
CreateDefaultSettingForRestore(sptr<HCameraDevice> activeDevice)1967 std::shared_ptr<OHOS::Camera::CameraMetadata> HCameraService::CreateDefaultSettingForRestore(
1968     sptr<HCameraDevice> activeDevice)
1969 {
1970     constexpr int32_t DEFAULT_ITEMS = 1;
1971     constexpr int32_t DEFAULT_DATA_LENGTH = 1;
1972     auto defaultSettings = std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
1973     float zoomRatio = 1.0f;
1974     int32_t count = 1;
1975     int32_t ret = 0;
1976     camera_metadata_item_t item;
1977     defaultSettings->addEntry(OHOS_CONTROL_ZOOM_RATIO, &zoomRatio, count);
1978     defaultSettings->addEntry(OHOS_CONTROL_TIME_LAPSE_RECORD_STATE, &ret, count);
1979     std::shared_ptr<OHOS::Camera::CameraMetadata> currentSetting = activeDevice->CloneCachedSettings();
1980     CHECK_ERROR_RETURN_RET_LOG(currentSetting == nullptr, defaultSettings,
1981         "HCameraService::CreateDefaultSettingForRestore:currentSetting is null");
1982     ret = OHOS::Camera::FindCameraMetadataItem(currentSetting->get(), OHOS_CONTROL_FPS_RANGES, &item);
1983     if (ret == CAM_META_SUCCESS) {
1984         uint32_t fpscount = item.count;
1985         std::vector<int32_t> fpsRange;
1986         for (uint32_t i = 0; i < fpscount; i++) {
1987             fpsRange.push_back(*(item.data.i32 + i));
1988         }
1989         defaultSettings->addEntry(OHOS_CONTROL_FPS_RANGES, fpsRange.data(), fpscount);
1990     }
1991 
1992     ret = OHOS::Camera::FindCameraMetadataItem(currentSetting->get(), OHOS_CAMERA_USER_ID, &item);
1993     if (ret == CAM_META_SUCCESS) {
1994         int32_t userId = item.data.i32[0];
1995         defaultSettings->addEntry(OHOS_CAMERA_USER_ID, &userId, count);
1996     }
1997 
1998     ret = OHOS::Camera::FindCameraMetadataItem(currentSetting->get(), OHOS_CONTROL_AE_EXPOSURE_COMPENSATION, &item);
1999     if (ret == CAM_META_SUCCESS) {
2000         int32_t exporseValue = item.data.i32[0];
2001         defaultSettings->addEntry(OHOS_CONTROL_AE_EXPOSURE_COMPENSATION, &exporseValue, count);
2002     }
2003 
2004     uint8_t enableValue = true;
2005     defaultSettings->addEntry(OHOS_CONTROL_VIDEO_DEBUG_SWITCH, &enableValue, 1);
2006 
2007     for (uint32_t metadataTag : restoreMetadataTag) { // item.type is uint8
2008         ret = OHOS::Camera::FindCameraMetadataItem(currentSetting->get(), metadataTag, &item);
2009         CHECK_EXECUTE(ret == 0 && item.count != 0,
2010             defaultSettings->addEntry(item.item, item.data.u8, item.count));
2011     }
2012     return defaultSettings;
2013 }
2014 
UpdateSkinSmoothSetting(std::shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata,int skinSmoothValue)2015 int32_t HCameraService::UpdateSkinSmoothSetting(std::shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata,
2016                                                 int skinSmoothValue)
2017 {
2018     CHECK_ERROR_RETURN_RET(skinSmoothValue <= 0 || changedMetadata == nullptr, CAMERA_OK);
2019     bool status = false;
2020     int32_t count = 1;
2021     int ret;
2022     camera_metadata_item_t item;
2023 
2024     MEDIA_DEBUG_LOG("UpdateBeautySetting skinsmooth: %{public}d", skinSmoothValue);
2025     uint8_t beauty = OHOS_CAMERA_BEAUTY_TYPE_SKIN_SMOOTH;
2026     ret = OHOS::Camera::FindCameraMetadataItem(changedMetadata->get(), OHOS_CONTROL_BEAUTY_TYPE, &item);
2027     if (ret == CAM_META_ITEM_NOT_FOUND) {
2028         status = changedMetadata->addEntry(OHOS_CONTROL_BEAUTY_TYPE, &beauty, count);
2029     } else if (ret == CAM_META_SUCCESS) {
2030         status = changedMetadata->updateEntry(OHOS_CONTROL_BEAUTY_TYPE, &beauty, count);
2031     }
2032 
2033     ret = OHOS::Camera::FindCameraMetadataItem(changedMetadata->get(), OHOS_CONTROL_BEAUTY_SKIN_SMOOTH_VALUE, &item);
2034     if (ret == CAM_META_ITEM_NOT_FOUND) {
2035         status = changedMetadata->addEntry(OHOS_CONTROL_BEAUTY_SKIN_SMOOTH_VALUE, &skinSmoothValue, count);
2036     } else if (ret == CAM_META_SUCCESS) {
2037         status = changedMetadata->updateEntry(OHOS_CONTROL_BEAUTY_SKIN_SMOOTH_VALUE, &skinSmoothValue, count);
2038     }
2039     if (status) {
2040         MEDIA_INFO_LOG("UpdateBeautySetting status: %{public}d", status);
2041     }
2042 
2043     return CAMERA_OK;
2044 }
2045 
UpdateFaceSlenderSetting(std::shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata,int faceSlenderValue)2046 int32_t HCameraService::UpdateFaceSlenderSetting(std::shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata,
2047                                                  int faceSlenderValue)
2048 {
2049     CHECK_ERROR_RETURN_RET(faceSlenderValue <= 0 || changedMetadata == nullptr, CAMERA_OK);
2050     bool status = false;
2051     int32_t count = 1;
2052     int ret;
2053     camera_metadata_item_t item;
2054 
2055     MEDIA_DEBUG_LOG("UpdateBeautySetting faceSlender: %{public}d", faceSlenderValue);
2056     uint8_t beauty = OHOS_CAMERA_BEAUTY_TYPE_FACE_SLENDER;
2057     ret = OHOS::Camera::FindCameraMetadataItem(changedMetadata->get(), OHOS_CONTROL_BEAUTY_TYPE, &item);
2058     if (ret == CAM_META_ITEM_NOT_FOUND) {
2059         status = changedMetadata->addEntry(OHOS_CONTROL_BEAUTY_TYPE, &beauty, count);
2060     } else if (ret == CAM_META_SUCCESS) {
2061         status = changedMetadata->updateEntry(OHOS_CONTROL_BEAUTY_TYPE, &beauty, count);
2062     }
2063 
2064     ret = OHOS::Camera::FindCameraMetadataItem(changedMetadata->get(), OHOS_CONTROL_BEAUTY_FACE_SLENDER_VALUE, &item);
2065     if (ret == CAM_META_ITEM_NOT_FOUND) {
2066         status = changedMetadata->addEntry(OHOS_CONTROL_BEAUTY_FACE_SLENDER_VALUE, &faceSlenderValue, count);
2067     } else if (ret == CAM_META_SUCCESS) {
2068         status = changedMetadata->updateEntry(OHOS_CONTROL_BEAUTY_FACE_SLENDER_VALUE, &faceSlenderValue, count);
2069     }
2070     if (status) {
2071         MEDIA_INFO_LOG("UpdateBeautySetting status: %{public}d", status);
2072     }
2073 
2074     return CAMERA_OK;
2075 }
2076 
UpdateSkinToneSetting(std::shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata,int skinToneValue)2077 int32_t HCameraService::UpdateSkinToneSetting(std::shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata,
2078     int skinToneValue)
2079 {
2080     CHECK_ERROR_RETURN_RET(skinToneValue <= 0 || changedMetadata == nullptr, CAMERA_OK);
2081     bool status = false;
2082     int32_t count = 1;
2083     int ret;
2084     camera_metadata_item_t item;
2085 
2086     MEDIA_DEBUG_LOG("UpdateBeautySetting skinTone: %{public}d", skinToneValue);
2087     uint8_t beauty = OHOS_CAMERA_BEAUTY_TYPE_SKIN_TONE;
2088     ret = OHOS::Camera::FindCameraMetadataItem(changedMetadata->get(), OHOS_CONTROL_BEAUTY_TYPE, &item);
2089     if (ret == CAM_META_ITEM_NOT_FOUND) {
2090         status = changedMetadata->addEntry(OHOS_CONTROL_BEAUTY_TYPE, &beauty, count);
2091     } else if (ret == CAM_META_SUCCESS) {
2092         status = changedMetadata->updateEntry(OHOS_CONTROL_BEAUTY_TYPE, &beauty, count);
2093     }
2094 
2095     ret = OHOS::Camera::FindCameraMetadataItem(changedMetadata->get(), OHOS_CONTROL_BEAUTY_SKIN_TONE_VALUE, &item);
2096     if (ret == CAM_META_ITEM_NOT_FOUND) {
2097         status = changedMetadata->addEntry(OHOS_CONTROL_BEAUTY_SKIN_TONE_VALUE, &skinToneValue, count);
2098     } else if (ret == CAM_META_SUCCESS) {
2099         status = changedMetadata->updateEntry(OHOS_CONTROL_BEAUTY_SKIN_TONE_VALUE, &skinToneValue, count);
2100     }
2101     if (status) {
2102         MEDIA_INFO_LOG("UpdateBeautySetting status: %{public}d", status);
2103     }
2104 
2105     return CAMERA_OK;
2106 }
2107 
g_toString(std::set<int32_t> & pidList)2108 std::string g_toString(std::set<int32_t>& pidList)
2109 {
2110     std::string ret = "[";
2111     for (const auto& pid : pidList) {
2112         ret += std::to_string(pid) + ",";
2113     }
2114     ret += "]";
2115     return ret;
2116 }
2117 
ProxyForFreeze(const std::set<int32_t> & pidList,bool isProxy)2118 int32_t HCameraService::ProxyForFreeze(const std::set<int32_t>& pidList, bool isProxy)
2119 {
2120     constexpr int32_t maxSaUid = 10000;
2121     CHECK_ERROR_RETURN_RET_LOG(IPCSkeleton::GetCallingUid() >= maxSaUid, CAMERA_OPERATION_NOT_ALLOWED, "not allow");
2122     {
2123         std::lock_guard<std::mutex> lock(freezedPidListMutex_);
2124         if (isProxy) {
2125             freezedPidList_.insert(pidList.begin(), pidList.end());
2126             MEDIA_DEBUG_LOG("after freeze freezedPidList_:%{public}s", g_toString(freezedPidList_).c_str());
2127             return CAMERA_OK;
2128         } else {
2129             for (auto pid : pidList) {
2130                 freezedPidList_.erase(pid);
2131             }
2132             MEDIA_DEBUG_LOG("after unfreeze freezedPidList_:%{public}s", g_toString(freezedPidList_).c_str());
2133         }
2134     }
2135 
2136     {
2137         std::lock_guard<std::mutex> lock(cameraCbMutex_);
2138         for (auto pid : pidList) {
2139             auto it = delayCbtaskMap.find(pid);
2140             if (it != delayCbtaskMap.end()) {
2141                 it->second();
2142                 delayCbtaskMap.erase(it);
2143             }
2144         }
2145     }
2146     return CAMERA_OK;
2147 }
2148 
ResetAllFreezeStatus()2149 int32_t HCameraService::ResetAllFreezeStatus()
2150 {
2151     constexpr int32_t maxSaUid = 10000;
2152     CHECK_ERROR_RETURN_RET_LOG(IPCSkeleton::GetCallingUid() >= maxSaUid, CAMERA_OPERATION_NOT_ALLOWED, "not allow");
2153     std::lock_guard<std::mutex> lock(freezedPidListMutex_);
2154     freezedPidList_.clear();
2155     MEDIA_INFO_LOG("freezedPidList_ has been clear");
2156     return CAMERA_OK;
2157 }
2158 
GetDmDeviceInfo(std::vector<std::string> & deviceInfos)2159 int32_t HCameraService::GetDmDeviceInfo(std::vector<std::string> &deviceInfos)
2160 {
2161 #ifdef DEVICE_MANAGER
2162     lock_guard<mutex> lock(g_dmDeviceInfoMutex);
2163     std::vector <DistributedHardware::DmDeviceInfo> deviceInfoList;
2164     auto &deviceManager = DistributedHardware::DeviceManager::GetInstance();
2165     std::shared_ptr<DistributedHardware::DmInitCallback> initCallback = std::make_shared<DeviceInitCallBack>();
2166     std::string pkgName = std::to_string(IPCSkeleton::GetCallingTokenID());
2167     const string extraInfo = "";
2168     deviceManager.InitDeviceManager(pkgName, initCallback);
2169     deviceManager.RegisterDevStateCallback(pkgName, extraInfo, NULL);
2170     deviceManager.GetTrustedDeviceList(pkgName, extraInfo, deviceInfoList);
2171     deviceManager.UnInitDeviceManager(pkgName);
2172     int size = static_cast<int>(deviceInfoList.size());
2173     MEDIA_INFO_LOG("HCameraService::GetDmDeviceInfo size=%{public}d", size);
2174     if (size > 0) {
2175         for (int i = 0; i < size; i++) {
2176             nlohmann::json deviceInfo;
2177             deviceInfo["deviceName"] = deviceInfoList[i].deviceName;
2178             deviceInfo["deviceTypeId"] = deviceInfoList[i].deviceTypeId;
2179             deviceInfo["networkId"] = deviceInfoList[i].networkId;
2180             std::string deviceInfoStr = deviceInfo.dump();
2181             MEDIA_INFO_LOG("HCameraService::GetDmDeviceInfo deviceInfo:%{public}s", deviceInfoStr.c_str());
2182             deviceInfos.emplace_back(deviceInfoStr);
2183         }
2184     }
2185 #endif
2186     return CAMERA_OK;
2187 }
2188 
GetCameraOutputStatus(int32_t pid,int32_t & status)2189 int32_t HCameraService::GetCameraOutputStatus(int32_t pid, int32_t &status)
2190 {
2191     sptr<HCaptureSession> captureSession = nullptr;
2192     captureSessionsManager_.Find(pid,  captureSession);
2193     if (captureSession) {
2194         captureSession->GetOutputStatus(status);
2195     } else {
2196         status = 0;
2197     }
2198     return CAMERA_OK;
2199 }
2200 
RequireMemorySize(int32_t requiredMemSizeKB)2201 int32_t HCameraService::RequireMemorySize(int32_t requiredMemSizeKB)
2202 {
2203     #ifdef MEMMGR_OVERRID
2204     int32_t pid = getpid();
2205     const std::string reason = "HW_CAMERA_TO_PHOTO";
2206     std::string clientName = SYSTEM_CAMERA;
2207     int32_t ret = Memory::MemMgrClient::GetInstance().RequireBigMem(pid, reason, requiredMemSizeKB, clientName);
2208     MEDIA_INFO_LOG("HCameraDevice::RequireMemory reason:%{public}s, clientName:%{public}s, ret:%{public}d",
2209         reason.c_str(), clientName.c_str(), ret);
2210     CHECK_ERROR_RETURN_RET(ret == 0, CAMERA_OK);
2211     #endif
2212     return CAMERA_UNKNOWN_ERROR;
2213 }
2214 
GetIdforCameraConcurrentType(int32_t cameraPosition,std::string & cameraId)2215 int32_t HCameraService::GetIdforCameraConcurrentType(int32_t cameraPosition, std::string &cameraId)
2216 {
2217     std::string cameraIdnow;
2218     cameraHostManager_->GetPhysicCameraId(cameraPosition, cameraIdnow);
2219     cameraId = cameraIdnow;
2220     return CAMERA_OK;
2221 }
2222 
GetConcurrentCameraAbility(std::string & cameraId,std::shared_ptr<OHOS::Camera::CameraMetadata> & cameraAbility)2223 int32_t HCameraService::GetConcurrentCameraAbility(std::string& cameraId,
2224     std::shared_ptr<OHOS::Camera::CameraMetadata>& cameraAbility)
2225 {
2226     MEDIA_DEBUG_LOG("HCameraService::GetConcurrentCameraAbility cameraId: %{public}s", cameraId.c_str());
2227     return cameraHostManager_->GetCameraAbility(cameraId, cameraAbility);
2228 }
2229 
CheckWhiteList(bool & isInWhiteList)2230 int32_t HCameraService::CheckWhiteList(bool &isInWhiteList)
2231 {
2232     int32_t uid = IPCSkeleton::GetCallingUid();
2233     MEDIA_INFO_LOG("CheckWhitelist uid: %{public}d", uid);
2234     isInWhiteList = (uid == ROOT_UID || uid == FACE_CLIENT_UID || uid == RSS_UID ||
2235         OHOS::Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID()));
2236     return CAMERA_OK;
2237 }
2238 } // namespace CameraStandard
2239 } // namespace OHOS
2240