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_device.h"
17
18 #include <cstdint>
19 #include <memory>
20 #include <mutex>
21 #include <nlohmann/json.hpp>
22 #include <vector>
23
24 #include "camera_common_event_manager.h"
25 #include "camera_device_ability_items.h"
26 #include "camera_log.h"
27 #include "camera_fwk_metadata_utils.h"
28 #include "camera_metadata_info.h"
29 #include "camera_metadata_operator.h"
30 #include "camera_service_ipc_interface_code.h"
31 #include "camera_util.h"
32 #include "device_protection_ability_connection.h"
33 #include "display_manager.h"
34 #include "extension_manager_client.h"
35 #include "hcamera_device_manager.h"
36 #include "ipc_skeleton.h"
37 #include "ipc_types.h"
38 #ifdef MEMMGR_OVERRID
39 #include "mem_mgr_client.h"
40 #include "mem_mgr_constant.h"
41 #endif
42 #include "metadata_utils.h"
43 #include "v1_0/types.h"
44 #include "os_account_manager.h"
45 #include "deferred_processing_service.h"
46 #include "camera_timer.h"
47 #include "camera_report_uitls.h"
48 #include "common_event_manager.h"
49 #include "common_event_data.h"
50 #include "want.h"
51 #include "parameters.h"
52 #include "res_type.h"
53 #include "res_sched_client.h"
54
55 namespace OHOS {
56 namespace CameraStandard {
57 using namespace OHOS::HDI::Camera::V1_0;
58 std::mutex HCameraDevice::g_deviceOpenCloseMutex_;
59 static const int32_t DEFAULT_SETTING_ITEM_COUNT = 100;
60 static const int32_t DEFAULT_SETTING_ITEM_LENGTH = 100;
61 static const int32_t CAMERA_QOS_LEVEL = 7;
62 static const float SMOOTH_ZOOM_DIVISOR = 100.0f;
63 static const std::vector<camera_device_metadata_tag> DEVICE_OPEN_LIFECYCLE_TAGS = { OHOS_CONTROL_MUTE_MODE };
64 constexpr int32_t DEFAULT_USER_ID = -1;
65 static const uint32_t DEVICE_EJECT_LIMIT = 5;
66 static const uint32_t DEVICE_EJECT_INTERVAL = 1000;
67 static const uint32_t SYSDIALOG_ZORDER_UPPER = 2;
68 static const uint32_t DEVICE_DROP_INTERVAL = 600000;
69 static std::mutex g_cameraHostManagerMutex;
70 static sptr<HCameraHostManager> g_cameraHostManager = nullptr;
71 static int64_t g_lastDeviceDropTime = 0;
72 sptr<OHOS::Rosen::DisplayManager::IFoldStatusListener> listener;
73 CallerInfo caller_;
74
75 const std::vector<std::tuple<uint32_t, std::string, DFX_UB_NAME>> HCameraDevice::reportTagInfos_ = {
76 {OHOS_CONTROL_FLASH_MODE, "OHOS_CONTROL_FLASH_MODE", DFX_UB_SET_FLASHMODE},
77 {OHOS_CONTROL_FOCUS_MODE, "OHOS_CONTROL_FOCUS_MODE", DFX_UB_SET_FOCUSMODE},
78 {OHOS_CONTROL_QUALITY_PRIORITIZATION, "OHOS_CONTROL_QUALITY_PRIORITIZATION", DFX_UB_SET_QUALITY_PRIORITIZATION},
79 {OHOS_CONTROL_EXPOSURE_MODE, "OHOS_CONTROL_EXPOSURE_MODE", DFX_UB_SET_EXPOSUREMODE},
80 {OHOS_CONTROL_VIDEO_STABILIZATION_MODE, "OHOS_CONTROL_VIDEO_STABILIZATION_MODE", DFX_UB_SET_VIDEOSTABILIZATIONMODE},
81 {OHOS_CONTROL_FILTER_TYPE, "OHOS_CONTROL_FILTER_TYPE", DFX_UB_SET_FILTER},
82 {OHOS_CONTROL_PORTRAIT_EFFECT_TYPE, "OHOS_CONTROL_PORTRAIT_EFFECT_TYPE", DFX_UB_SET_PORTRAITEFFECT},
83 {OHOS_CONTROL_BEAUTY_AUTO_VALUE, "OHOS_CONTROL_BEAUTY_AUTO_VALUE", DFX_UB_SET_BEAUTY_AUTOVALUE},
84 {OHOS_CONTROL_BEAUTY_SKIN_SMOOTH_VALUE, "OHOS_CONTROL_BEAUTY_SKIN_SMOOTH_VALUE", DFX_UB_SET_BEAUTY_SKINSMOOTH},
85 {OHOS_CONTROL_BEAUTY_FACE_SLENDER_VALUE, "OHOS_CONTROL_BEAUTY_FACE_SLENDER_VALUE", DFX_UB_SET_BEAUTY_FACESLENDER},
86 {OHOS_CONTROL_BEAUTY_SKIN_TONE_VALUE, "OHOS_CONTROL_BEAUTY_SKIN_TONE_VALUE", DFX_UB_SET_BEAUTY_SKINTONE},
87 {OHOS_CONTROL_AE_EXPOSURE_COMPENSATION, "OHOS_CONTROL_AE_EXPOSURE_COMPENSATION", DFX_UB_SET_EXPOSUREBIAS},
88 {OHOS_CONTROL_FPS_RANGES, "OHOS_CONTROL_FPS_RANGES", DFX_UB_SET_FRAMERATERANGE},
89 {OHOS_CONTROL_ZOOM_RATIO, "OHOS_CONTROL_ZOOM_RATIO", DFX_UB_SET_ZOOMRATIO},
90 {OHOS_CONTROL_BEAUTY_TYPE, "OHOS_CONTROL_BEAUTY_TYPE", DFX_UB_NOT_REPORT},
91 {OHOS_CONTROL_LIGHT_PAINTING_TYPE, "OHOS_CONTROL_LIGHT_PAINTING_TYPE", DFX_UB_NOT_REPORT},
92 {OHOS_CONTROL_LIGHT_PAINTING_FLASH, "OHOS_CONTROL_LIGHT_PAINTING_FLASH", DFX_UB_NOT_REPORT},
93 {OHOS_CONTROL_MANUAL_EXPOSURE_TIME, "OHOS_CONTROL_MANUAL_EXPOSURE_TIME", DFX_UB_NOT_REPORT},
94 {OHOS_CONTROL_CAMERA_USED_AS_POSITION, "OHOS_CONTROL_CAMERA_USED_AS_POSITION", DFX_UB_NOT_REPORT},
95 {OHOS_CONTROL_CHANGETO_OFFLINE_STREAM_OPEATOR, "OHOS_CONTROL_CHANGETO_OFFLINE_STREAM_OPEATOR", DFX_UB_NOT_REPORT},
96 {OHOS_CONTROL_ROTATE_ANGLE, "OHOS_CONTROL_ROTATE_ANGLE", DFX_UB_NOT_REPORT},
97 };
98
99 const std::unordered_map<DeviceProtectionStatus, CamServiceError> g_deviceProtectionToServiceError_ = {
100 {OHOS_DEVICE_SWITCH_FREQUENT, CAMERA_DEVICE_SWITCH_FREQUENT},
101 {OHOS_DEVICE_FALL_PROTECTION, CAMERA_DEVICE_LENS_RETRACTED}
102 };
103
104 const std::unordered_map<DeviceProtectionStatus, DeviceProtectionAbilityCallBack> g_deviceProtectionToCallBack_ = {
105 {OHOS_DEVICE_EXTERNAL_PRESS, HCameraDevice::DeviceFaultCallBack},
106 {OHOS_DEVICE_EJECT_BLOCK, HCameraDevice::DeviceEjectCallBack}
107 };
108
109 class HCameraDevice::FoldScreenListener : public OHOS::Rosen::DisplayManager::IFoldStatusListener {
110 public:
FoldScreenListener(sptr<HCameraHostManager> & cameraHostManager,const std::string cameraId)111 explicit FoldScreenListener(sptr<HCameraHostManager> &cameraHostManager, const std::string cameraId)
112 : cameraHostManager_(cameraHostManager), cameraId_(cameraId)
113 {
114 MEDIA_DEBUG_LOG("FoldScreenListener enter, cameraID: %{public}s", cameraId_.c_str());
115 }
116
117 virtual ~FoldScreenListener() = default;
OnFoldStatusChanged(OHOS::Rosen::FoldStatus foldStatus)118 void OnFoldStatusChanged(OHOS::Rosen::FoldStatus foldStatus) override
119 {
120 FoldStatus currentFoldStatus = static_cast<FoldStatus>(foldStatus);
121 if (currentFoldStatus == FoldStatus::HALF_FOLD) {
122 currentFoldStatus = FoldStatus::EXPAND;
123 }
124 if (cameraHostManager_ == nullptr || mLastFoldStatus == currentFoldStatus) {
125 MEDIA_DEBUG_LOG("no need set fold status");
126 return;
127 }
128 mLastFoldStatus = currentFoldStatus;
129 MEDIA_INFO_LOG("OnFoldStatusChanged, foldStatus: %{public}d", foldStatus);
130 cameraHostManager_->NotifyDeviceStateChangeInfo(DeviceType::FOLD_TYPE, (int)currentFoldStatus);
131 }
132 private:
133 sptr<HCameraHostManager> cameraHostManager_;
134 std::string cameraId_;
135 FoldStatus mLastFoldStatus = FoldStatus::UNKNOWN_FOLD;
136 };
137
HCameraDevice(sptr<HCameraHostManager> & cameraHostManager,std::string cameraID,const uint32_t callingTokenId)138 HCameraDevice::HCameraDevice(
139 sptr<HCameraHostManager>& cameraHostManager, std::string cameraID, const uint32_t callingTokenId)
140 : cachedSettings_(
141 std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_SETTING_ITEM_COUNT, DEFAULT_SETTING_ITEM_LENGTH)),
142 cameraHostManager_(cameraHostManager), cameraID_(cameraID), callerToken_(callingTokenId),
143 deviceOpenLifeCycleSettings_(std::make_shared<OHOS::Camera::CameraMetadata>(
144 DEVICE_OPEN_LIFECYCLE_TAGS.size(), DEFAULT_SETTING_ITEM_LENGTH)), clientUserId_(0), zoomTimerId_(0),
145 deviceMuteMode_(false), isHasOpenSecure(false)
146 {
147 MEDIA_INFO_LOG("HCameraDevice::HCameraDevice Contructor Camera: %{public}s", cameraID.c_str());
148 isOpenedCameraDevice_.store(false);
149 sptr<CameraPrivacy> cameraPrivacy = new CameraPrivacy(callingTokenId, IPCSkeleton::GetCallingPid());
150 SetCameraPrivacy(cameraPrivacy);
151 cameraPid_ = IPCSkeleton::GetCallingPid();
152
153 {
154 std::lock_guard<std::mutex> lock(g_cameraHostManagerMutex);
155 g_cameraHostManager = cameraHostManager;
156 }
157 }
158
~HCameraDevice()159 HCameraDevice::~HCameraDevice()
160 {
161 UnPrepareZoom();
162 CameraTimer::GetInstance().Unregister(zoomTimerId_);
163 SetCameraPrivacy(nullptr);
164 {
165 std::lock_guard<std::mutex> lock(movingPhotoStartTimeCallbackLock_);
166 movingPhotoStartTimeCallback_ = nullptr;
167 }
168 {
169 std::lock_guard<std::mutex> lock(movingPhotoEndTimeCallbackLock_);
170 movingPhotoEndTimeCallback_ = nullptr;
171 }
172 MEDIA_INFO_LOG("HCameraDevice::~HCameraDevice Destructor Camera: %{public}s", cameraID_.c_str());
173 }
174
GetCameraId()175 std::string HCameraDevice::GetCameraId()
176 {
177 return cameraID_;
178 }
179
GetCameraType()180 int32_t HCameraDevice::GetCameraType()
181 {
182 CHECK_ERROR_RETURN_RET(clientName_ == SYSTEM_CAMERA, SYSTEM);
183 return OTHER;
184 }
185
IsOpenedCameraDevice()186 bool HCameraDevice::IsOpenedCameraDevice()
187 {
188 return isOpenedCameraDevice_.load();
189 }
190
SetDeviceMuteMode(bool muteMode)191 void HCameraDevice::SetDeviceMuteMode(bool muteMode)
192 {
193 deviceMuteMode_ = muteMode;
194 }
195
GetDeviceMuteMode()196 bool HCameraDevice::GetDeviceMuteMode()
197 {
198 return deviceMuteMode_;
199 }
200
EnableMovingPhoto(bool isMovingPhotoEnabled)201 void HCameraDevice::EnableMovingPhoto(bool isMovingPhotoEnabled)
202 {
203 isMovingPhotoEnabled_ = isMovingPhotoEnabled;
204 }
205
CreateMuteSetting(std::shared_ptr<OHOS::Camera::CameraMetadata> & settings)206 void HCameraDevice::CreateMuteSetting(std::shared_ptr<OHOS::Camera::CameraMetadata>& settings)
207 {
208 constexpr int32_t DEFAULT_ITEMS = 1;
209 constexpr int32_t DEFAULT_DATA_LENGTH = 1;
210 int32_t count = 1;
211 uint8_t mode = OHOS_CAMERA_MUTE_MODE_SOLID_COLOR_BLACK;
212 settings = std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
213 settings->addEntry(OHOS_CONTROL_MUTE_MODE, &mode, count);
214 }
215
ResetDeviceSettings()216 int32_t HCameraDevice::ResetDeviceSettings()
217 {
218 CAMERA_SYNC_TRACE;
219 sptr<OHOS::HDI::Camera::V1_2::ICameraDevice> hdiCameraDeviceV1_2;
220 MEDIA_INFO_LOG("HCameraDevice::ResetDeviceSettings enter");
221 {
222 std::lock_guard<std::mutex> lock(opMutex_);
223 CHECK_ERROR_RETURN_RET(hdiCameraDevice_ == nullptr, CAMERA_OK);
224 hdiCameraDeviceV1_2 = HDI::Camera::V1_2::ICameraDevice::CastFrom(hdiCameraDevice_);
225 }
226 if (hdiCameraDeviceV1_2 != nullptr) {
227 int32_t errCode = hdiCameraDeviceV1_2->Reset();
228 CHECK_ERROR_RETURN_RET_LOG(errCode != HDI::Camera::V1_0::CamRetCode::NO_ERROR, CAMERA_UNKNOWN_ERROR,
229 "HCameraDevice::ResetDeviceSettings occur error");
230 ResetCachedSettings();
231 if (deviceMuteMode_) {
232 std::shared_ptr<OHOS::Camera::CameraMetadata> settings = nullptr;
233 CreateMuteSetting(settings);
234 UpdateSetting(settings);
235 }
236 }
237 MEDIA_INFO_LOG("HCameraDevice::ResetDeviceSettings end");
238 return CAMERA_OK;
239 }
240
DispatchDefaultSettingToHdi()241 int32_t HCameraDevice::DispatchDefaultSettingToHdi()
242 {
243 CAMERA_SYNC_TRACE;
244 MEDIA_INFO_LOG("HCameraDevice::DispatchDefaultSettingToHdi enter");
245
246 std::shared_ptr<OHOS::Camera::CameraMetadata> lifeCycleSettings;
247 {
248 std::lock_guard<std::mutex> lifeLock(deviceOpenLifeCycleMutex_);
249 if (deviceOpenLifeCycleSettings_->get()->item_count == 0) {
250 MEDIA_INFO_LOG("HCameraDevice::DispatchDefaultSettingToHdi skip, data is empty");
251 return CAMERA_OK;
252 }
253 lifeCycleSettings = CameraFwkMetadataUtils::CopyMetadata(deviceOpenLifeCycleSettings_);
254 }
255
256 if (IsCameraDebugOn()) {
257 auto metadataHeader = lifeCycleSettings->get();
258 for (uint32_t index = 0; index < metadataHeader->item_count; index++) {
259 camera_metadata_item_t item;
260 int32_t result = OHOS::Camera::GetCameraMetadataItem(metadataHeader, index, &item);
261 if (result == CAM_META_SUCCESS) {
262 MEDIA_INFO_LOG("HCameraDevice::DispatchDefaultSettingToHdi tag:%{public}d", item.item);
263 } else {
264 MEDIA_ERR_LOG(
265 "HCameraDevice::DispatchDefaultSettingToHdi tag:%{public}d error:%{public}d", item.item, result);
266 }
267 }
268 }
269
270 std::lock_guard<std::mutex> lock(opMutex_);
271 CHECK_ERROR_RETURN_RET(hdiCameraDevice_ == nullptr, CAMERA_INVALID_STATE);
272 std::vector<uint8_t> hdiMetadata;
273 bool isSuccess = OHOS::Camera::MetadataUtils::ConvertMetadataToVec(lifeCycleSettings, hdiMetadata);
274 CHECK_ERROR_RETURN_RET_LOG(!isSuccess, CAMERA_UNKNOWN_ERROR,
275 "HCameraDevice::DispatchDefaultSettingToHdi metadata ConvertMetadataToVec fail");
276 ReportMetadataDebugLog(lifeCycleSettings);
277 CamRetCode rc = (CamRetCode)hdiCameraDevice_->UpdateSettings(hdiMetadata);
278 if (rc != HDI::Camera::V1_0::NO_ERROR) {
279 MEDIA_ERR_LOG("HCameraDevice::DispatchDefaultSettingToHdi UpdateSettings error: %{public}d", rc);
280 CameraReportUtils::ReportCameraError(
281 "HCameraDevice::DispatchDefaultSettingToHdi", rc, true, CameraReportUtils::GetCallerInfo());
282 return HdiToServiceError(rc);
283 }
284 return CAMERA_OK;
285 }
286
ResetCachedSettings()287 void HCameraDevice::ResetCachedSettings()
288 {
289 std::lock_guard<std::mutex> cachedLock(cachedSettingsMutex_);
290 cachedSettings_ =
291 std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_SETTING_ITEM_COUNT, DEFAULT_SETTING_ITEM_LENGTH);
292 }
293
CloneCachedSettings()294 std::shared_ptr<OHOS::Camera::CameraMetadata> HCameraDevice::CloneCachedSettings()
295 {
296 std::lock_guard<std::mutex> cachedLock(cachedSettingsMutex_);
297 return CameraFwkMetadataUtils::CopyMetadata(cachedSettings_);
298 }
299
GetDeviceAbility()300 std::shared_ptr<OHOS::Camera::CameraMetadata> HCameraDevice::GetDeviceAbility()
301 {
302 CAMERA_SYNC_TRACE;
303 std::lock_guard<std::mutex> lock(deviceAbilityMutex_);
304 CHECK_ERROR_RETURN_RET(deviceAbility_ != nullptr, deviceAbility_);
305 int32_t errCode = cameraHostManager_->GetCameraAbility(cameraID_, deviceAbility_);
306 CHECK_ERROR_RETURN_RET_LOG(errCode != CAMERA_OK, nullptr,
307 "HCameraDevice::GetSettings Failed to get Camera Ability: %{public}d", errCode);
308 return deviceAbility_;
309 }
310
Open()311 int32_t HCameraDevice::Open()
312 {
313 CAMERA_SYNC_TRACE;
314 std::lock_guard<std::mutex> lock(g_deviceOpenCloseMutex_);
315 CHECK_ERROR_PRINT_LOG(isOpenedCameraDevice_.load(), "HCameraDevice::Open failed, camera is busy");
316 CHECK_ERROR_RETURN_RET_LOG(!IsInForeGround(callerToken_), CAMERA_ALLOC_ERROR,
317 "HCameraDevice::Open IsAllowedUsingPermission failed");
318 MEDIA_INFO_LOG("HCameraDevice::Open Camera:[%{public}s]", cameraID_.c_str());
319 int32_t result = OpenDevice();
320 return result;
321 }
322
OpenSecureCamera(uint64_t * secureSeqId)323 int32_t HCameraDevice::OpenSecureCamera(uint64_t* secureSeqId)
324 {
325 CAMERA_SYNC_TRACE;
326 CHECK_ERROR_PRINT_LOG(isOpenedCameraDevice_.load(), "HCameraDevice::Open failed, camera is busy");
327 CHECK_ERROR_RETURN_RET_LOG(!IsInForeGround(callerToken_), CAMERA_ALLOC_ERROR,
328 "HCameraDevice::Open IsAllowedUsingPermission failed");
329 MEDIA_INFO_LOG("HCameraDevice::OpenSecureCamera Camera:[%{public}s]", cameraID_.c_str());
330 int32_t errCode = OpenDevice(true);
331 CHECK_ERROR_RETURN_RET_LOG(hdiCameraDevice_ == nullptr, CAMERA_INVALID_ARG,
332 "HCameraDevice::OpenSecureCamera hdiCameraDevice_ is nullptr.");
333 auto hdiCameraDeviceV1_3 = HDI::Camera::V1_3::ICameraDevice::CastFrom(hdiCameraDevice_);
334 if (hdiCameraDeviceV1_3 != nullptr) {
335 errCode = hdiCameraDeviceV1_3->GetSecureCameraSeq(*secureSeqId);
336 CHECK_ERROR_RETURN_RET_LOG(errCode != HDI::Camera::V1_0::CamRetCode::NO_ERROR, CAMERA_UNKNOWN_ERROR,
337 "HCameraDevice::GetSecureCameraSeq occur error");
338 mSecureCameraSeqId = *secureSeqId;
339 isHasOpenSecure = true;
340 } else {
341 MEDIA_INFO_LOG("V1_3::ICameraDevice::CastFrom failed");
342 }
343 MEDIA_INFO_LOG("HCameraDevice::OpenSecureCamera secureSeqId = %{public}" PRIu64, *secureSeqId);
344 return errCode;
345 }
346
GetSecureCameraSeq(uint64_t * secureSeqId)347 int64_t HCameraDevice::GetSecureCameraSeq(uint64_t* secureSeqId)
348 {
349 if (!isHasOpenSecure) {
350 *secureSeqId = 0;
351 return CAMERA_OK;
352 }
353 auto hdiCameraDeviceV1_3 = HDI::Camera::V1_3::ICameraDevice::CastFrom(hdiCameraDevice_);
354 if (hdiCameraDeviceV1_3 != nullptr) {
355 *secureSeqId = mSecureCameraSeqId;
356 MEDIA_DEBUG_LOG("CaptureSession::GetSecureCameraSeq secureSeqId = %{public}" PRId64, *secureSeqId);
357 return CAMERA_UNKNOWN_ERROR;
358 } else {
359 MEDIA_INFO_LOG("V1_3::ICameraDevice::CastFrom failed");
360 }
361 return CAMERA_OK;
362 }
363
Close()364 int32_t HCameraDevice::Close()
365 {
366 CAMERA_SYNC_TRACE;
367 std::lock_guard<std::mutex> lock(g_deviceOpenCloseMutex_);
368 MEDIA_INFO_LOG("HCameraDevice::Close Closing camera device: %{public}s", cameraID_.c_str());
369 int32_t result = CloseDevice();
370 return result;
371 }
372
closeDelayed()373 int32_t HCameraDevice::closeDelayed()
374 {
375 CAMERA_SYNC_TRACE;
376 std::lock_guard<std::mutex> lock(g_deviceOpenCloseMutex_);
377 MEDIA_INFO_LOG("HCameraDevice::closeDelayed Closing camera device: %{public}s", cameraID_.c_str());
378 int32_t result = closeDelayedDevice();
379 return result;
380 }
381
ConfigQosParam(const char * bundleName,int32_t qosLevel,std::unordered_map<std::string,std::string> & qosParamMap)382 void HCameraDevice::ConfigQosParam(const char *bundleName, int32_t qosLevel,
383 std::unordered_map<std::string, std::string> &qosParamMap)
384 {
385 std::string strBundleName = bundleName;
386 std::string strPid = std::to_string(getpid());
387 std::string strTid = std::to_string(gettid());
388 std::string strQos = std::to_string(qosLevel);
389
390 qosParamMap["pid"] = strPid;
391 qosParamMap[strTid] = strQos;
392 qosParamMap["bundleName"] = strBundleName;
393 MEDIA_INFO_LOG("camera service qosParam: pid: %{public}s. tid: %{public}s, qos: %{public}s",
394 strPid.c_str(), strTid.c_str(), strQos.c_str());
395 }
396
OpenDevice(bool isEnableSecCam)397 int32_t HCameraDevice::OpenDevice(bool isEnableSecCam)
398 {
399 std::unordered_map<std::string, std::string> qosParamMap;
400 ConfigQosParam("camera_service", CAMERA_QOS_LEVEL, qosParamMap);
401 OHOS::ResourceSchedule::ResSchedClient::GetInstance().ReportData(
402 OHOS::ResourceSchedule::ResType::RES_TYPE_THREAD_QOS_CHANGE, 0, qosParamMap);
403
404 MEDIA_INFO_LOG("HCameraDevice::OpenDevice start cameraId: %{public}s", cameraID_.c_str());
405 CAMERA_SYNC_TRACE;
406 int32_t errorCode = CheckPermissionBeforeOpenDevice();
407 CHECK_ERROR_RETURN_RET(errorCode != CAMERA_OK, errorCode);
408 bool canOpenDevice = CanOpenCamera();
409 CHECK_ERROR_RETURN_RET_LOG(!canOpenDevice, CAMERA_DEVICE_CONFLICT, "HCameraDevice::Refuse to turn on the camera");
410 CHECK_ERROR_RETURN_RET_LOG(!HandlePrivacyBeforeOpenDevice(), CAMERA_OPERATION_NOT_ALLOWED, "privacy not allow!");
411 int pid = IPCSkeleton::GetCallingPid();
412 int uid = IPCSkeleton::GetCallingUid();
413 AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, clientUserId_);
414 int tokenId = IPCSkeleton::GetCallingTokenID();
415 clientName_ = GetClientNameByToken(tokenId);
416 #ifdef MEMMGR_OVERRID
417 RequireMemory(Memory::CAMERA_START);
418 #endif
419 CameraReportUtils::GetInstance().SetOpenCamPerfStartInfo(cameraID_.c_str(), CameraReportUtils::GetCallerInfo());
420 errorCode = cameraHostManager_->OpenCameraDevice(cameraID_, this, hdiCameraDevice_, isEnableSecCam);
421 if (errorCode != CAMERA_OK) {
422 MEDIA_ERR_LOG("HCameraDevice::OpenDevice Failed to open camera");
423 #ifdef MEMMGR_OVERRID
424 RequireMemory(Memory::CAMERA_END);
425 #endif
426 HandlePrivacyWhenOpenDeviceFail();
427 return CAMERA_UNKNOWN_ERROR;
428 } else {
429 isOpenedCameraDevice_.store(true);
430 HCameraDeviceManager::GetInstance()->AddDevice(IPCSkeleton::GetCallingPid(), this);
431 g_lastDeviceDropTime = 0;
432 RegisterSensorCallback();
433 }
434 CHECK_ERROR_RETURN_RET_LOG(errorCode != CAMERA_OK, errorCode,
435 "HCameraDevice::OpenDevice InitStreamOperator fail err code is:%{public}d", errorCode);
436 std::lock_guard<std::mutex> lockSetting(opMutex_);
437 if (hdiCameraDevice_ != nullptr) {
438 cameraHostManager_->AddCameraDevice(cameraID_, this);
439 if (updateSettings_ != nullptr || deviceMuteMode_) {
440 CHECK_EXECUTE(deviceMuteMode_, CreateMuteSetting(updateSettings_));
441 errorCode = UpdateDeviceSetting();
442 CHECK_ERROR_RETURN_RET(errorCode != CAMERA_OK, errorCode);
443 errorCode = HdiToServiceError((CamRetCode)(hdiCameraDevice_->SetResultMode(ON_CHANGED)));
444 }
445 }
446 HandleFoldableDevice();
447 POWERMGR_SYSEVENT_CAMERA_CONNECT(pid, uid, cameraID_.c_str(), clientName_);
448 NotifyCameraSessionStatus(true);
449 NotifyCameraStatus(CAMERA_OPEN);
450 MEDIA_INFO_LOG("HCameraDevice::OpenDevice end cameraId: %{public}s", cameraID_.c_str());
451 return errorCode;
452 }
453
454 #ifdef MEMMGR_OVERRID
RequireMemory(const std::string & reason)455 int32_t HCameraDevice::RequireMemory(const std::string& reason)
456 {
457 int32_t pid = getpid();
458 int32_t requiredMemSizeKB = 0;
459 int32_t ret = Memory::MemMgrClient::GetInstance().RequireBigMem(pid, reason,
460 requiredMemSizeKB, clientName_);
461 MEDIA_INFO_LOG("HCameraDevice::RequireMemory reason:%{public}s, clientName:%{public}s, ret:%{public}d",
462 reason.c_str(), clientName_.c_str(), ret);
463 return ret;
464 }
465 #endif
466
CheckPermissionBeforeOpenDevice()467 int32_t HCameraDevice::CheckPermissionBeforeOpenDevice()
468 {
469 MEDIA_DEBUG_LOG("enter checkPermissionBeforeOpenDevice");
470 if (IsHapTokenId(callerToken_)) {
471 auto cameraPrivacy = GetCameraPrivacy();
472 CHECK_ERROR_RETURN_RET_LOG(cameraPrivacy == nullptr, CAMERA_OPERATION_NOT_ALLOWED, "cameraPrivacy is null");
473 CHECK_ERROR_RETURN_RET_LOG(!cameraPrivacy->IsAllowUsingCamera(), CAMERA_OPERATION_NOT_ALLOWED,
474 "OpenDevice is not allowed!");
475 }
476 return CAMERA_OK;
477 }
478
HandlePrivacyBeforeOpenDevice()479 bool HCameraDevice::HandlePrivacyBeforeOpenDevice()
480 {
481 MEDIA_INFO_LOG("enter HandlePrivacyBeforeOpenDevice");
482 CHECK_ERROR_RETURN_RET_LOG(!IsHapTokenId(callerToken_), true, "system ability called not need privacy");
483 std::vector<sptr<HCameraDeviceHolder>> holders =
484 HCameraDeviceManager::GetInstance()->GetCameraHolderByPid(cameraPid_);
485 CHECK_ERROR_RETURN_RET_LOG(!holders.empty(), true, "current pid has active clients, no action is required");
486 auto cameraPrivacy = GetCameraPrivacy();
487 CHECK_ERROR_RETURN_RET_LOG(cameraPrivacy == nullptr, false, "cameraPrivacy is null");
488 if (HCameraDeviceManager::GetInstance()->IsMultiCameraActive(cameraPid_) == false) {
489 MEDIA_INFO_LOG("do StartUsingPermissionCallback");
490 CHECK_ERROR_RETURN_RET_LOG(!cameraPrivacy->StartUsingPermissionCallback(), false,
491 "start using permission failed");
492 }
493 CHECK_ERROR_RETURN_RET_LOG(!cameraPrivacy->RegisterPermissionCallback(), false, "register permission failed");
494 CHECK_ERROR_RETURN_RET_LOG(!cameraPrivacy->AddCameraPermissionUsedRecord(), false, "add permission record failed");
495 return true;
496 }
497
HandlePrivacyWhenOpenDeviceFail()498 void HCameraDevice::HandlePrivacyWhenOpenDeviceFail()
499 {
500 MEDIA_INFO_LOG("enter HandlePrivacyWhenOpenDeviceFail");
501 auto cameraPrivacy = GetCameraPrivacy();
502 if (cameraPrivacy != nullptr) {
503 if (HCameraDeviceManager::GetInstance()->IsMultiCameraActive(cameraPid_) == false) {
504 MEDIA_INFO_LOG("do StopUsingPermissionCallback");
505 cameraPrivacy->StopUsingPermissionCallback();
506 }
507 cameraPrivacy->UnregisterPermissionCallback();
508 }
509 }
510
HandlePrivacyAfterCloseDevice()511 void HCameraDevice::HandlePrivacyAfterCloseDevice()
512 {
513 MEDIA_INFO_LOG("enter HandlePrivacyAfterCloseDevice");
514 std::vector<sptr<HCameraDeviceHolder>> holders =
515 HCameraDeviceManager::GetInstance()->GetCameraHolderByPid(cameraPid_);
516 CHECK_ERROR_PRINT_LOG(!holders.empty(), "current pid has active clients, no action is required");
517 auto cameraPrivacy = GetCameraPrivacy();
518 if (cameraPrivacy != nullptr) {
519 if (HCameraDeviceManager::GetInstance()->IsMultiCameraActive(cameraPid_) == false) {
520 MEDIA_INFO_LOG("do StopUsingPermissionCallback");
521 cameraPrivacy->StopUsingPermissionCallback();
522 }
523 cameraPrivacy->UnregisterPermissionCallback();
524 }
525 }
526
UpdateDeviceSetting()527 int32_t HCameraDevice::UpdateDeviceSetting()
528 {
529 std::vector<uint8_t> setting;
530 OHOS::Camera::MetadataUtils::ConvertMetadataToVec(updateSettings_, setting);
531 ReportMetadataDebugLog(updateSettings_);
532 CamRetCode rc = (CamRetCode)(hdiCameraDevice_->UpdateSettings(setting));
533 CHECK_ERROR_RETURN_RET_LOG(rc != HDI::Camera::V1_0::NO_ERROR, HdiToServiceError(rc),
534 "HCameraDevice::OpenDevice Update setting failed with error Code: %{public}d", rc);
535 updateSettings_ = nullptr;
536 MEDIA_DEBUG_LOG("HCameraDevice::Open Updated device settings");
537 return CAMERA_OK;
538 }
539
ReportDeviceProtectionStatus(const std::shared_ptr<OHOS::Camera::CameraMetadata> & metadata)540 void HCameraDevice::ReportDeviceProtectionStatus(const std::shared_ptr<OHOS::Camera::CameraMetadata> &metadata)
541 {
542 CHECK_ERROR_RETURN_LOG(metadata == nullptr, "metadata is null");
543 camera_metadata_item_t item;
544 int ret = OHOS::Camera::FindCameraMetadataItem(metadata->get(), OHOS_DEVICE_PROTECTION_STATE, &item);
545 if (ret != CAM_META_SUCCESS || item.count == 0) {
546 return;
547 }
548 int32_t status = item.data.i32[0];
549 MEDIA_INFO_LOG("HCameraDevice::ReportDeviceProtectionStatus status: %{public}d", status);
550 if (!CanReportDeviceProtectionStatus(status)) {
551 return;
552 }
553 if (clientName_ == SYSTEM_CAMERA) {
554 auto callback = GetDeviceServiceCallback();
555 auto itr = g_deviceProtectionToServiceError_.find(static_cast<DeviceProtectionStatus>(status));
556 if (itr != g_deviceProtectionToServiceError_.end()) {
557 callback->OnError(itr->second, 0);
558 }
559 }
560 if (CameraCommonEventManager::GetInstance()->IsScreenLocked()) {
561 return;
562 }
563 ShowDeviceProtectionDialog(static_cast<DeviceProtectionStatus>(status));
564 }
565
CanReportDeviceProtectionStatus(int32_t status)566 bool HCameraDevice::CanReportDeviceProtectionStatus(int32_t status)
567 {
568 std::lock_guard<std::mutex> lock(deviceProtectionStatusMutex_);
569 bool ret = (status != lastDeviceProtectionStatus_);
570 lastDeviceProtectionStatus_ = status;
571 return ret;
572 }
573
DeviceEjectCallBack()574 void HCameraDevice::DeviceEjectCallBack()
575 {
576 MEDIA_INFO_LOG("HCameraDevice::DeviceEjectCallBack enter");
577 uint8_t value = 1;
578 uint32_t count = 1;
579 constexpr int32_t DEFAULT_ITEMS = 1;
580 constexpr int32_t DEFAULT_DATA_LENGTH = 1;
581 std::shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata =
582 std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
583 bool status = changedMetadata->addEntry(OHOS_CONTROL_EJECT_RETRY, &value, count);
584 CHECK_ERROR_RETURN_LOG(!status, "HCameraDevice::DropDetectionCallback Failed to set fall protection");
585
586 std::vector<sptr<HCameraDeviceHolder>> deviceHolderVector =
587 HCameraDeviceManager::GetInstance()->GetActiveCameraHolders();
588 for (sptr<HCameraDeviceHolder> activeDeviceHolder : deviceHolderVector) {
589 sptr<HCameraDevice> activeDevice = activeDeviceHolder->GetDevice();
590 if (activeDevice != nullptr && activeDevice->IsOpenedCameraDevice()) {
591 activeDevice->lastDeviceEjectTime_ = GetTimestamp();
592 activeDevice->UpdateSetting(changedMetadata);
593 MEDIA_INFO_LOG("HCameraService::DeviceEjectCallBack UpdateSetting");
594 }
595 }
596 }
597
DeviceFaultCallBack()598 void HCameraDevice::DeviceFaultCallBack()
599 {
600 MEDIA_INFO_LOG("HCameraDevice::DeviceFaultCallBack enter");
601 }
602
ShowDeviceProtectionDialog(DeviceProtectionStatus status)603 bool HCameraDevice::ShowDeviceProtectionDialog(DeviceProtectionStatus status)
604 {
605 if (status == OHOS_DEVICE_EJECT_BLOCK) {
606 int64_t timestamp = GetTimestamp();
607 if (timestamp - lastDeviceEjectTime_ < DEVICE_EJECT_INTERVAL) {
608 deviceEjectTimes_.operator++();
609 }
610 if (deviceEjectTimes_ > static_cast<int32_t>(DEVICE_EJECT_LIMIT)) {
611 status = OHOS_DEVICE_EXTERNAL_PRESS;
612 deviceEjectTimes_.store(0);
613 }
614 }
615
616 AAFwk::Want want;
617 std::string bundleName = "com.ohos.sceneboard";
618 std::string abilityName = "com.ohos.sceneboard.systemdialog";
619 want.SetElementName(bundleName, abilityName);
620
621 const int32_t code = 4;
622 std::string commandStr = BuildDeviceProtectionDialogCommand(status);
623 auto itr = g_deviceProtectionToCallBack_.find(static_cast<DeviceProtectionStatus>(status));
624 if (itr == g_deviceProtectionToCallBack_.end()) {
625 return false;
626 }
627 DeviceProtectionAbilityCallBack callback = itr->second;
628
629 sptr<DeviceProtectionAbilityConnection> connection = sptr<DeviceProtectionAbilityConnection> (new (std::nothrow)
630 DeviceProtectionAbilityConnection(commandStr, code, callback));
631 if (connection == nullptr) {
632 MEDIA_ERR_LOG("connection is nullptr");
633 return false;
634 }
635 std::string identity = IPCSkeleton::ResetCallingIdentity();
636 auto connectResult = AAFwk::ExtensionManagerClient::GetInstance().ConnectServiceExtensionAbility(want,
637 connection, nullptr, DEFAULT_USER_ID);
638 IPCSkeleton::SetCallingIdentity(identity);
639 if (connectResult != 0) {
640 MEDIA_ERR_LOG("ConnectServiceExtensionAbility Failed!");
641 return false;
642 }
643 return true;
644 }
645
BuildDeviceProtectionDialogCommand(DeviceProtectionStatus status)646 std::string HCameraDevice::BuildDeviceProtectionDialogCommand(DeviceProtectionStatus status)
647 {
648 nlohmann::json extraInfo;
649 switch (static_cast<int32_t>(status)) {
650 // 按压受阻
651 case OHOS_DEVICE_EJECT_BLOCK:
652 extraInfo["title"] = "camera_device_eject_lab";
653 extraInfo["content"] = "camera_device_eject_desc";
654 extraInfo["button"] = "camera_use_continue";
655 break;
656 // 故障上报弹窗
657 case OHOS_DEVICE_EXTERNAL_PRESS:
658 extraInfo["title"] = "camera_device_block_lab";
659 extraInfo["content"] = "camera_device_block_desc";
660 extraInfo["button"] = "camera_device_block_confirm";
661 break;
662 }
663 nlohmann::json dialogInfo;
664 dialogInfo["sysDialogZOrder"] = SYSDIALOG_ZORDER_UPPER;
665 dialogInfo["extraInfo"] = extraInfo;
666 std::string commandStr = dialogInfo.dump();
667 MEDIA_INFO_LOG("BuildDeviceProtectionDialogCommand, commandStr = %{public}s", commandStr.c_str());
668 return commandStr;
669 }
670
RegisterSensorCallback()671 void HCameraDevice::RegisterSensorCallback()
672 {
673 std::lock_guard<std::mutex> lock(sensorLock_);
674 MEDIA_INFO_LOG("HCameraDevice::RegisterDropDetectionListener start");
675 CHECK_ERROR_RETURN_LOG(!OHOS::Rosen::LoadMotionSensor(), "RegisterDropDetectionListener LoadMotionSensor fail");
676 CHECK_ERROR_RETURN_LOG(!OHOS::Rosen::SubscribeCallback(OHOS::Rosen::MOTION_TYPE_DROP_DETECTION,
677 DropDetectionDataCallbackImpl), "RegisterDropDetectionListener SubscribeCallback fail");
678 }
679
UnRegisterSensorCallback()680 void HCameraDevice::UnRegisterSensorCallback()
681 {
682 std::lock_guard<std::mutex> lock(sensorLock_);
683 CHECK_ERROR_RETURN_LOG(!UnsubscribeCallback(OHOS::Rosen::MOTION_TYPE_DROP_DETECTION, DropDetectionDataCallbackImpl),
684 "UnRegisterDropDetectionListener fail");
685 }
686
DropDetectionDataCallbackImpl(const OHOS::Rosen::MotionSensorEvent & motionData)687 void HCameraDevice::DropDetectionDataCallbackImpl(const OHOS::Rosen::MotionSensorEvent &motionData)
688 {
689 MEDIA_INFO_LOG("HCameraDevice::DropDetectionCallback type = %{public}d, status = %{public}d",
690 motionData.type, motionData.status);
691 {
692 if ((GetTimestamp() - g_lastDeviceDropTime < DEVICE_DROP_INTERVAL) ||
693 (g_cameraHostManager == nullptr)) {
694 return;
695 }
696 g_cameraHostManager->NotifyDeviceStateChangeInfo(
697 DeviceType::FALLING_TYPE, FallingState::FALLING_STATE);
698 }
699 }
700
HandleFoldableDevice()701 void HCameraDevice::HandleFoldableDevice()
702 {
703 bool isFoldable = OHOS::Rosen::DisplayManager::GetInstance().IsFoldable();
704 MEDIA_DEBUG_LOG("HCameraDevice::OpenDevice isFoldable is %d", isFoldable);
705 CHECK_EXECUTE(isFoldable, RegisterFoldStatusListener());
706 }
707
ReleaseSessionBeforeCloseDevice()708 void HCameraDevice::ReleaseSessionBeforeCloseDevice()
709 {
710 std::lock_guard<std::mutex> lock(cameraCloseListenerMutex_);
711 for (wptr<IHCameraCloseListener> cameraCloseListener : cameraCloseListenerVec_) {
712 auto cameraCloseListenerTemp = cameraCloseListener.promote();
713 if (cameraCloseListenerTemp == nullptr) {
714 continue;
715 }
716 cameraCloseListenerTemp->BeforeDeviceClose();
717 }
718 }
719
CloseDevice()720 int32_t HCameraDevice::CloseDevice()
721 {
722 MEDIA_INFO_LOG("HCameraDevice::CloseDevice start");
723 CAMERA_SYNC_TRACE;
724 ReleaseSessionBeforeCloseDevice();
725 {
726 std::lock_guard<std::mutex> lock(opMutex_);
727 CHECK_ERROR_RETURN_RET_LOG(!isOpenedCameraDevice_.load(), CAMERA_OK,
728 "HCameraDevice::CloseDevice device has benn closed");
729 bool isFoldable = OHOS::Rosen::DisplayManager::GetInstance().IsFoldable();
730 CHECK_EXECUTE(isFoldable, UnregisterFoldStatusListener());
731 if (hdiCameraDevice_ != nullptr) {
732 isOpenedCameraDevice_.store(false);
733 MEDIA_INFO_LOG("Closing camera device: %{public}s start", cameraID_.c_str());
734 hdiCameraDevice_->Close();
735 ResetCachedSettings();
736 ResetDeviceOpenLifeCycleSettings();
737 HCameraDeviceManager::GetInstance()->RemoveDevice(cameraID_);
738 MEDIA_INFO_LOG("Closing camera device: %{public}s end", cameraID_.c_str());
739 hdiCameraDevice_ = nullptr;
740 HandlePrivacyAfterCloseDevice();
741 } else {
742 MEDIA_INFO_LOG("hdiCameraDevice is null");
743 }
744 SetStreamOperatorCallback(nullptr);
745 EnableDeviceOpenedByConcurrent(false);
746 }
747 if (cameraHostManager_) {
748 cameraHostManager_->RemoveCameraDevice(cameraID_);
749 cameraHostManager_->UpdateRestoreParamCloseTime(clientName_, cameraID_);
750 }
751 {
752 std::lock_guard<std::mutex> lock(deviceSvcCbMutex_);
753 deviceSvcCallback_ = nullptr;
754 }
755 POWERMGR_SYSEVENT_CAMERA_DISCONNECT(cameraID_.c_str());
756 MEDIA_DEBUG_LOG("HCameraDevice::CloseDevice end");
757 NotifyCameraSessionStatus(false);
758 NotifyCameraStatus(CAMERA_CLOSE);
759 #ifdef MEMMGR_OVERRID
760 RequireMemory(Memory::CAMERA_END);
761 #endif
762 UnRegisterSensorCallback();
763 return CAMERA_OK;
764 }
765
closeDelayedDevice()766 int32_t HCameraDevice::closeDelayedDevice()
767 {
768 MEDIA_INFO_LOG("HCameraDevice::closeDelayedDevice start");
769 CAMERA_SYNC_TRACE;
770 sptr<OHOS::HDI::Camera::V1_2::ICameraDevice> hdiCameraDeviceV1_2;
771 {
772 std::lock_guard<std::mutex> lock(opMutex_);
773 CHECK_ERROR_RETURN_RET(hdiCameraDevice_ == nullptr, CAMERA_OK);
774 hdiCameraDeviceV1_2 = HDI::Camera::V1_2::ICameraDevice::CastFrom(hdiCameraDevice_);
775 }
776 if (hdiCameraDeviceV1_2 != nullptr) {
777 int32_t errCode = hdiCameraDeviceV1_2->Reset();
778 CHECK_ERROR_RETURN_RET_LOG(errCode != HDI::Camera::V1_0::CamRetCode::NO_ERROR, CAMERA_UNKNOWN_ERROR,
779 "HCameraDevice::closeDelayedDevice ResetDevice error");
780 ResetCachedSettings();
781 }
782 MEDIA_INFO_LOG("HCameraDevice::closeDelayedDevice end");
783 return CAMERA_OK;
784 }
785
Release()786 int32_t HCameraDevice::Release()
787 {
788 Close();
789 return CAMERA_OK;
790 }
791
GetEnabledResults(std::vector<int32_t> & results)792 int32_t HCameraDevice::GetEnabledResults(std::vector<int32_t> &results)
793 {
794 std::lock_guard<std::mutex> lock(opMutex_);
795 CHECK_ERROR_RETURN_RET_LOG(!hdiCameraDevice_, CAMERA_UNKNOWN_ERROR,
796 "HCameraDevice::GetEnabledResults GetEnabledResults hdiCameraDevice_ is nullptr");
797 CamRetCode rc = (CamRetCode)(hdiCameraDevice_->GetEnabledResults(results));
798 CHECK_ERROR_RETURN_RET_LOG(rc != HDI::Camera::V1_0::NO_ERROR, HdiToServiceError(rc),
799 "HCameraDevice::GetEnabledResults failed with error Code:%{public}d", rc);
800 return CAMERA_OK;
801 }
802
CheckZoomChange(const std::shared_ptr<OHOS::Camera::CameraMetadata> & settings)803 void HCameraDevice::CheckZoomChange(const std::shared_ptr<OHOS::Camera::CameraMetadata>& settings)
804 {
805 int32_t ret;
806 camera_metadata_item_t item;
807 ret = OHOS::Camera::FindCameraMetadataItem(settings->get(), OHOS_CONTROL_PREPARE_ZOOM, &item);
808 if (ret == CAM_META_SUCCESS) {
809 if (item.data.u8[0] == OHOS_CAMERA_ZOOMSMOOTH_PREPARE_ENABLE) {
810 MEDIA_ERR_LOG("OHOS_CAMERA_ZOOMSMOOTH_PREPARE_ENABLE");
811 inPrepareZoom_ = true;
812 ResetZoomTimer();
813 } else if (item.data.u8[0] == OHOS_CAMERA_ZOOMSMOOTH_PREPARE_DISABLE) {
814 MEDIA_ERR_LOG("OHOS_CAMERA_ZOOMSMOOTH_PREPARE_DISABLE");
815 inPrepareZoom_ = false;
816 ResetZoomTimer();
817 }
818 return;
819 }
820 ret = OHOS::Camera::FindCameraMetadataItem(settings->get(), OHOS_CONTROL_ZOOM_RATIO, &item);
821 if (ret != CAM_META_SUCCESS) {
822 ret = OHOS::Camera::FindCameraMetadataItem(settings->get(), OHOS_CONTROL_SMOOTH_ZOOM_RATIOS, &item);
823 }
824 CHECK_EXECUTE(ret == CAM_META_SUCCESS && inPrepareZoom_, ResetZoomTimer());
825 return;
826 }
827
CheckMovingPhotoSupported(int32_t mode)828 bool HCameraDevice::CheckMovingPhotoSupported(int32_t mode)
829 {
830 std::shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility;
831 int32_t ret = cameraHostManager_->GetCameraAbility(cameraID_, cameraAbility);
832 CHECK_ERROR_RETURN_RET(cameraAbility == nullptr, false);
833 camera_metadata_item_t metadataItem;
834 std::vector<int32_t> modes = {};
835 ret = OHOS::Camera::FindCameraMetadataItem(cameraAbility->get(), OHOS_ABILITY_MOVING_PHOTO,
836 &metadataItem);
837 if (ret == CAM_META_SUCCESS && metadataItem.count > 0) {
838 uint32_t step = 3;
839 for (uint32_t index = 0; index < metadataItem.count - 1;) {
840 CHECK_EXECUTE(metadataItem.data.i32[index + 1] == 1, modes.push_back(metadataItem.data.i32[index]));
841 MEDIA_DEBUG_LOG("IsMovingPhotoSupported mode:%{public}d", metadataItem.data.i32[index]);
842 index += step;
843 }
844 }
845 return std::find(modes.begin(), modes.end(), mode) != modes.end();
846 }
847
ResetZoomTimer()848 void HCameraDevice::ResetZoomTimer()
849 {
850 CameraTimer::GetInstance().Unregister(zoomTimerId_);
851 CHECK_ERROR_RETURN(!inPrepareZoom_);
852 MEDIA_INFO_LOG("register zoom timer callback");
853 uint32_t waitMs = 5 * 1000;
854 auto thisPtr = wptr<HCameraDevice>(this);
855 zoomTimerId_ = CameraTimer::GetInstance().Register([thisPtr]() {
856 auto devicePtr = thisPtr.promote();
857 CHECK_EXECUTE(devicePtr != nullptr, devicePtr->UnPrepareZoom());
858 }, waitMs, true);
859 }
860
UnPrepareZoom()861 void HCameraDevice::UnPrepareZoom()
862 {
863 MEDIA_INFO_LOG("entered.");
864 std::lock_guard<std::mutex> lock(unPrepareZoomMutex_);
865 if (inPrepareZoom_) {
866 inPrepareZoom_ = false;
867 uint32_t count = 1;
868 uint32_t prepareZoomType = OHOS_CAMERA_ZOOMSMOOTH_PREPARE_DISABLE;
869 std::shared_ptr<OHOS::Camera::CameraMetadata> metadata = std::make_shared<OHOS::Camera::CameraMetadata>(1, 1);
870 metadata->addEntry(OHOS_CONTROL_PREPARE_ZOOM, &prepareZoomType, count);
871 UpdateSetting(metadata);
872 }
873 }
874
UpdateSetting(const std::shared_ptr<OHOS::Camera::CameraMetadata> & settings)875 int32_t HCameraDevice::UpdateSetting(const std::shared_ptr<OHOS::Camera::CameraMetadata>& settings)
876 {
877 CAMERA_SYNC_TRACE;
878 CHECK_ERROR_RETURN_RET_LOG(settings == nullptr, CAMERA_INVALID_ARG,
879 "HCameraDevice::UpdateSetting settings is null");
880 CheckZoomChange(settings);
881
882 uint32_t count = OHOS::Camera::GetCameraMetadataItemCount(settings->get());
883 CHECK_ERROR_RETURN_RET_LOG(!count, CAMERA_OK, "HCameraDevice::UpdateSetting Nothing to update");
884 std::lock_guard<std::mutex> lock(opMutex_);
885 if (updateSettings_ == nullptr || !CameraFwkMetadataUtils::MergeMetadata(settings, updateSettings_)) {
886 updateSettings_ = settings;
887 }
888 MEDIA_INFO_LOG("HCameraDevice::UpdateSetting Updated device settings hdiCameraDevice_(%{public}d)",
889 hdiCameraDevice_ != nullptr);
890 if (hdiCameraDevice_ != nullptr) {
891 std::vector<uint8_t> hdiSettings;
892 OHOS::Camera::MetadataUtils::ConvertMetadataToVec(updateSettings_, hdiSettings);
893 ReportMetadataDebugLog(updateSettings_);
894 DumpMetadata(updateSettings_);
895 CamRetCode rc = (CamRetCode)(hdiCameraDevice_->UpdateSettings(hdiSettings));
896 CHECK_ERROR_RETURN_RET_LOG(rc != HDI::Camera::V1_0::NO_ERROR, HdiToServiceError(rc),
897 "HCameraDevice::UpdateSetting Failed with error Code: %{public}d", rc);
898 UpdateDeviceOpenLifeCycleSettings(updateSettings_);
899 {
900 std::lock_guard<std::mutex> cachedLock(cachedSettingsMutex_);
901 CameraFwkMetadataUtils::MergeMetadata(settings, cachedSettings_);
902 }
903 updateSettings_ = nullptr;
904 }
905 MEDIA_INFO_LOG("HCameraDevice::UpdateSetting execute success");
906 return CAMERA_OK;
907 }
908
SetUsedAsPosition(uint8_t value)909 int32_t HCameraDevice::SetUsedAsPosition(uint8_t value)
910 {
911 MEDIA_INFO_LOG("HCameraDevice::SetUsedAsPosition as %{public}d", value);
912 usedAsPosition_ = value;
913 // lockforcontrol
914 return CAMERA_OK;
915 }
916
GetUsedAsPosition()917 uint8_t HCameraDevice::GetUsedAsPosition()
918 {
919 MEDIA_INFO_LOG("HCameraDevice::GetUsedAsPosition success");
920 return usedAsPosition_;
921 }
922
UpdateSettingOnce(const std::shared_ptr<OHOS::Camera::CameraMetadata> & settings)923 int32_t HCameraDevice::UpdateSettingOnce(const std::shared_ptr<OHOS::Camera::CameraMetadata>& settings)
924 {
925 CAMERA_SYNC_TRACE;
926 MEDIA_INFO_LOG("HCameraDevice::UpdateSettingOnce prepare execute");
927 CHECK_ERROR_RETURN_RET_LOG(settings == nullptr, CAMERA_INVALID_ARG, "settings is null");
928 CheckZoomChange(settings);
929
930 uint32_t count = OHOS::Camera::GetCameraMetadataItemCount(settings->get());
931 CHECK_ERROR_RETURN_RET_LOG(!count, CAMERA_OK, "Nothing to update");
932 std::lock_guard<std::mutex> lock(opMutex_);
933 MEDIA_INFO_LOG("Updated device settings once hdiCameraDevice_(%{public}d)", hdiCameraDevice_ != nullptr);
934 if (hdiCameraDevice_ != nullptr) {
935 std::vector<uint8_t> hdiSettings;
936 OHOS::Camera::MetadataUtils::ConvertMetadataToVec(settings, hdiSettings);
937 ReportMetadataDebugLog(settings);
938 CamRetCode rc = (CamRetCode)(hdiCameraDevice_->UpdateSettings(hdiSettings));
939 CHECK_ERROR_RETURN_RET_LOG(rc != HDI::Camera::V1_0::NO_ERROR, HdiToServiceError(rc),
940 "Failed with error Code: %{public}d", rc);
941 }
942 MEDIA_INFO_LOG("HCameraDevice::UpdateSettingOnce execute success");
943 return CAMERA_OK;
944 }
945
GetStatus(std::shared_ptr<OHOS::Camera::CameraMetadata> & metaIn,std::shared_ptr<OHOS::Camera::CameraMetadata> & metaOut)946 int32_t HCameraDevice::GetStatus(std::shared_ptr<OHOS::Camera::CameraMetadata> &metaIn,
947 std::shared_ptr<OHOS::Camera::CameraMetadata> &metaOut)
948 {
949 CAMERA_SYNC_TRACE;
950 CHECK_ERROR_RETURN_RET_LOG(metaIn == nullptr, CAMERA_INVALID_ARG, "HCameraDevice::GetStatus metaIn is null");
951 uint32_t count = OHOS::Camera::GetCameraMetadataItemCount(metaIn->get());
952 CHECK_ERROR_RETURN_RET_LOG(!count, CAMERA_OK, "HCameraDevice::GetStatus Nothing to query");
953
954 sptr<OHOS::HDI::Camera::V1_2::ICameraDevice> hdiCameraDeviceV1_2;
955 if (cameraHostManager_->GetVersionByCamera(cameraID_) >= GetVersionId(HDI_VERSION_1, HDI_VERSION_2)) {
956 MEDIA_DEBUG_LOG("HCameraDevice::GetStatus ICameraDevice cast to V1_2");
957 hdiCameraDeviceV1_2 = OHOS::HDI::Camera::V1_2::ICameraDevice::CastFrom(hdiCameraDevice_);
958 if (hdiCameraDeviceV1_2 == nullptr) {
959 MEDIA_ERR_LOG("HCameraDevice::GetStatus ICameraDevice cast to V1_2 error");
960 hdiCameraDeviceV1_2 = static_cast<OHOS::HDI::Camera::V1_2::ICameraDevice *>(hdiCameraDevice_.GetRefPtr());
961 }
962 }
963
964 MEDIA_DEBUG_LOG("HCameraDevice::GetStatus hdiCameraDeviceV1_2(%{public}d)", hdiCameraDeviceV1_2 != nullptr);
965 if (hdiCameraDeviceV1_2 != nullptr) {
966 std::vector<uint8_t> hdiMetaIn;
967 std::vector<uint8_t> hdiMetaOut;
968 OHOS::Camera::MetadataUtils::ConvertMetadataToVec(metaIn, hdiMetaIn);
969 CamRetCode rc = (CamRetCode)(hdiCameraDeviceV1_2->GetStatus(hdiMetaIn, hdiMetaOut));
970 CHECK_ERROR_RETURN_RET_LOG(rc != HDI::Camera::V1_0::NO_ERROR, HdiToServiceError(rc),
971 "HCameraDevice::GetStatus Failed with error Code: %{public}d", rc);
972 CHECK_EXECUTE(hdiMetaOut.size() != 0, OHOS::Camera::MetadataUtils::ConvertVecToMetadata(hdiMetaOut, metaOut));
973 }
974 return CAMERA_OK;
975 }
976
ReportMetadataDebugLog(const std::shared_ptr<OHOS::Camera::CameraMetadata> & settings)977 void HCameraDevice::ReportMetadataDebugLog(const std::shared_ptr<OHOS::Camera::CameraMetadata> &settings)
978 {
979 caller_ = CameraReportUtils::GetCallerInfo();
980 for (const auto &tagInfo : reportTagInfos_) {
981 std::string tagName;
982 DFX_UB_NAME dfxUbStr;
983 uint32_t tag;
984 std::tie(tag, tagName, dfxUbStr) = tagInfo;
985 DebugLogTag(settings, tag, tagName, dfxUbStr);
986 }
987
988 DebugLogForSmoothZoom(settings, OHOS_CONTROL_SMOOTH_ZOOM_RATIOS);
989 DebugLogForAfRegions(settings, OHOS_CONTROL_AF_REGIONS);
990 DebugLogForAeRegions(settings, OHOS_CONTROL_AE_REGIONS);
991 }
992
DebugLogTag(const std::shared_ptr<OHOS::Camera::CameraMetadata> & settings,uint32_t tag,std::string tagName,DFX_UB_NAME dfxUbStr)993 void HCameraDevice::DebugLogTag(const std::shared_ptr<OHOS::Camera::CameraMetadata> &settings,
994 uint32_t tag, std::string tagName, DFX_UB_NAME dfxUbStr)
995 {
996 camera_metadata_item_t item;
997 int ret = OHOS::Camera::FindCameraMetadataItem(settings->get(), tag, &item);
998 if (ret != CAM_META_SUCCESS || item.count <= 0) {
999 MEDIA_DEBUG_LOG("Failed to find %{public}s tag", tagName.c_str());
1000 return;
1001 }
1002 uint32_t dataType = item.data_type;
1003 std::string valueStr;
1004 if (dataType == META_TYPE_BYTE) {
1005 valueStr = std::to_string(item.data.u8[0]);
1006 } else if (dataType == META_TYPE_INT32) {
1007 valueStr = std::to_string(item.data.i32[0]);
1008 } else if (dataType == META_TYPE_UINT32) {
1009 valueStr = std::to_string(item.data.ui32[0]);
1010 } else if (dataType == META_TYPE_FLOAT) {
1011 valueStr = std::to_string(item.data.f[0]);
1012 } else if (dataType == META_TYPE_INT64) {
1013 valueStr = std::to_string(item.data.i64[0]);
1014 } else if (dataType == META_TYPE_DOUBLE) {
1015 valueStr = std::to_string(item.data.d[0]);
1016 } else {
1017 MEDIA_ERR_LOG("unknown dataType");
1018 return;
1019 }
1020 MEDIA_DEBUG_LOG("Find %{public}s value = %{public}s", tagName.c_str(), valueStr.c_str());
1021
1022 CHECK_EXECUTE(dfxUbStr != DFX_UB_NOT_REPORT,
1023 CameraReportUtils::GetInstance().ReportUserBehavior(dfxUbStr, valueStr, caller_));
1024 }
1025
DebugLogForSmoothZoom(const std::shared_ptr<OHOS::Camera::CameraMetadata> & settings,uint32_t tag)1026 void HCameraDevice::DebugLogForSmoothZoom(const std::shared_ptr<OHOS::Camera::CameraMetadata> &settings, uint32_t tag)
1027 {
1028 // debug log for smooth zoom
1029 camera_metadata_item_t item;
1030 int ret = OHOS::Camera::FindCameraMetadataItem(settings->get(), tag, &item);
1031 if (ret != CAM_META_SUCCESS) {
1032 MEDIA_DEBUG_LOG("HCameraDevice::Failed to find OHOS_CONTROL_SMOOTH_ZOOM_RATIOS tag");
1033 } else {
1034 MEDIA_DEBUG_LOG("HCameraDevice::find OHOS_CONTROL_SMOOTH_ZOOM_RATIOS count = %{public}d", item.count);
1035 if (item.count > 1) {
1036 uint32_t targetZoom = item.data.ui32[item.count - 2];
1037 float zoomRatio = targetZoom / SMOOTH_ZOOM_DIVISOR;
1038 MEDIA_DEBUG_LOG("HCameraDevice::find OHOS_CONTROL_SMOOTH_ZOOM_RATIOS value = %{public}f", zoomRatio);
1039 CameraReportUtils::GetInstance().ReportUserBehavior(DFX_UB_SET_SMOOTHZOOM,
1040 std::to_string(zoomRatio), caller_);
1041 }
1042 }
1043 }
1044
DebugLogForAfRegions(const std::shared_ptr<OHOS::Camera::CameraMetadata> & settings,uint32_t tag)1045 void HCameraDevice::DebugLogForAfRegions(const std::shared_ptr<OHOS::Camera::CameraMetadata> &settings, uint32_t tag)
1046 {
1047 // debug log for af regions
1048 camera_metadata_item_t item;
1049 int ret = OHOS::Camera::FindCameraMetadataItem(settings->get(), tag, &item);
1050 if (ret != CAM_META_SUCCESS) {
1051 MEDIA_DEBUG_LOG("HCameraDevice::Failed to find OHOS_CONTROL_AF_REGIONS tag");
1052 } else {
1053 std::stringstream ss;
1054 ss << "x=" << item.data.f[0] << " y=" << item.data.f[1];
1055 std::string str = ss.str();
1056 MEDIA_DEBUG_LOG("HCameraDevice::find OHOS_CONTROL_AF_REGIONS %{public}s", str.c_str());
1057 CameraReportUtils::GetInstance().ReportUserBehavior(DFX_UB_SET_FOCUSPOINT, str, caller_);
1058 }
1059 }
1060
DebugLogForAeRegions(const std::shared_ptr<OHOS::Camera::CameraMetadata> & settings,uint32_t tag)1061 void HCameraDevice::DebugLogForAeRegions(const std::shared_ptr<OHOS::Camera::CameraMetadata> &settings, uint32_t tag)
1062 {
1063 // debug log for ae regions
1064 camera_metadata_item_t item;
1065 int ret = OHOS::Camera::FindCameraMetadataItem(settings->get(), tag, &item);
1066 if (ret != CAM_META_SUCCESS) {
1067 MEDIA_DEBUG_LOG("HCameraDevice::Failed to find OHOS_CONTROL_AE_REGIONS tag");
1068 } else {
1069 std::stringstream ss;
1070 ss << "x=" << item.data.f[0] << " y=" << item.data.f[1];
1071 std::string str = ss.str();
1072 MEDIA_DEBUG_LOG("HCameraDevice::find OHOS_CONTROL_AE_REGIONS %{public}s", str.c_str());
1073 CameraReportUtils::GetInstance().ReportUserBehavior(DFX_UB_SET_METERINGPOINT, str, caller_);
1074 }
1075 }
1076
RegisterFoldStatusListener()1077 void HCameraDevice::RegisterFoldStatusListener()
1078 {
1079 listener = new FoldScreenListener(cameraHostManager_, cameraID_);
1080 if (cameraHostManager_) {
1081 int foldStatus = static_cast<int>(OHOS::Rosen::DisplayManager::GetInstance().GetFoldStatus());
1082 if (foldStatus == FoldStatus::HALF_FOLD) {
1083 foldStatus = FoldStatus::EXPAND;
1084 }
1085 cameraHostManager_->NotifyDeviceStateChangeInfo(DeviceType::FOLD_TYPE, foldStatus);
1086 }
1087 auto ret = OHOS::Rosen::DisplayManager::GetInstance().RegisterFoldStatusListener(listener);
1088 if (ret != OHOS::Rosen::DMError::DM_OK) {
1089 MEDIA_DEBUG_LOG("HCameraDevice::RegisterFoldStatusListener failed");
1090 listener = nullptr;
1091 } else {
1092 MEDIA_DEBUG_LOG("HCameraDevice::RegisterFoldStatusListener success");
1093 }
1094 }
1095
UnregisterFoldStatusListener()1096 void HCameraDevice::UnregisterFoldStatusListener()
1097 {
1098 CHECK_ERROR_RETURN_LOG(listener == nullptr, "HCameraDevice::unRegisterFoldStatusListener listener is null");
1099 auto ret = OHOS::Rosen::DisplayManager::GetInstance().UnregisterFoldStatusListener(listener);
1100 if (ret != OHOS::Rosen::DMError::DM_OK) {
1101 MEDIA_DEBUG_LOG("HCameraDevice::UnregisterFoldStatusListener failed");
1102 }
1103 }
1104
EnableResult(std::vector<int32_t> & results)1105 int32_t HCameraDevice::EnableResult(std::vector<int32_t> &results)
1106 {
1107 CHECK_ERROR_RETURN_RET_LOG(results.empty(), CAMERA_INVALID_ARG, "HCameraDevice::EnableResult results is empty");
1108 std::lock_guard<std::mutex> lock(opMutex_);
1109 CHECK_ERROR_RETURN_RET_LOG(hdiCameraDevice_ == nullptr, CAMERA_UNKNOWN_ERROR,
1110 "HCameraDevice::hdiCameraDevice_ is null");
1111
1112 CamRetCode rc = (CamRetCode)(hdiCameraDevice_->EnableResult(results));
1113 CHECK_ERROR_RETURN_RET_LOG(rc != HDI::Camera::V1_0::NO_ERROR, HdiToServiceError(rc),
1114 "HCameraDevice::EnableResult failed with error Code:%{public}d", rc);
1115 return CAMERA_OK;
1116 }
1117
SetDeviceRetryTime()1118 int32_t HCameraDevice::SetDeviceRetryTime()
1119 {
1120 MEDIA_INFO_LOG("HCameraDevice::SetDeviceRetryTime");
1121 g_lastDeviceDropTime = GetTimestamp();
1122 return CAMERA_OK;
1123 }
1124
DisableResult(std::vector<int32_t> & results)1125 int32_t HCameraDevice::DisableResult(std::vector<int32_t> &results)
1126 {
1127 CHECK_ERROR_RETURN_RET_LOG(results.empty(), CAMERA_INVALID_ARG, "HCameraDevice::DisableResult results is empty");
1128 std::lock_guard<std::mutex> lock(opMutex_);
1129 CHECK_ERROR_RETURN_RET_LOG(hdiCameraDevice_ == nullptr, CAMERA_UNKNOWN_ERROR,
1130 "HCameraDevice::hdiCameraDevice_ is null");
1131
1132 CamRetCode rc = (CamRetCode)(hdiCameraDevice_->DisableResult(results));
1133 CHECK_ERROR_RETURN_RET_LOG(rc != HDI::Camera::V1_0::NO_ERROR, HdiToServiceError(rc),
1134 "HCameraDevice::DisableResult failed with error Code:%{public}d", rc);
1135 return CAMERA_OK;
1136 }
1137
SetCallback(sptr<ICameraDeviceServiceCallback> & callback)1138 int32_t HCameraDevice::SetCallback(sptr<ICameraDeviceServiceCallback>& callback)
1139 {
1140 if (callback == nullptr) {
1141 MEDIA_WARNING_LOG("HCameraDevice::SetCallback callback is null");
1142 }
1143 std::lock_guard<std::mutex> lock(deviceSvcCbMutex_);
1144 deviceSvcCallback_ = callback;
1145 return CAMERA_OK;
1146 }
1147
UnSetCallback()1148 int32_t HCameraDevice::UnSetCallback()
1149 {
1150 std::lock_guard<std::mutex> lock(deviceSvcCbMutex_);
1151 deviceSvcCallback_ = nullptr;
1152 return CAMERA_OK;
1153 }
1154
GetDeviceServiceCallback()1155 sptr<ICameraDeviceServiceCallback> HCameraDevice::GetDeviceServiceCallback()
1156 {
1157 std::lock_guard<std::mutex> lock(deviceSvcCbMutex_);
1158 return deviceSvcCallback_;
1159 }
1160
UpdateDeviceOpenLifeCycleSettings(std::shared_ptr<OHOS::Camera::CameraMetadata> changedSettings)1161 void HCameraDevice::UpdateDeviceOpenLifeCycleSettings(std::shared_ptr<OHOS::Camera::CameraMetadata> changedSettings)
1162 {
1163 CHECK_ERROR_RETURN(changedSettings == nullptr);
1164 std::lock_guard<std::mutex> lock(deviceOpenLifeCycleMutex_);
1165 for (auto itemTag : DEVICE_OPEN_LIFECYCLE_TAGS) {
1166 camera_metadata_item_t item;
1167 int32_t result = OHOS::Camera::FindCameraMetadataItem(changedSettings->get(), itemTag, &item);
1168 if (result != CAM_META_SUCCESS) {
1169 continue;
1170 }
1171 bool updateSuccess = CameraFwkMetadataUtils::UpdateMetadataTag(item, deviceOpenLifeCycleSettings_);
1172 if (!updateSuccess) {
1173 MEDIA_ERR_LOG("HCameraDevice::UpdateDeviceOpenLifeCycleSettings tag:%{public}d fail", itemTag);
1174 } else {
1175 MEDIA_INFO_LOG("HCameraDevice::UpdateDeviceOpenLifeCycleSettings tag:%{public}d success", itemTag);
1176 }
1177 }
1178 }
1179
ResetDeviceOpenLifeCycleSettings()1180 void HCameraDevice::ResetDeviceOpenLifeCycleSettings()
1181 {
1182 MEDIA_INFO_LOG("HCameraDevice::ResetDeviceOpenLifeCycleSettings");
1183 std::lock_guard<std::mutex> lock(deviceOpenLifeCycleMutex_);
1184 deviceOpenLifeCycleSettings_ =
1185 std::make_shared<OHOS::Camera::CameraMetadata>(DEVICE_OPEN_LIFECYCLE_TAGS.size(), DEFAULT_SETTING_ITEM_LENGTH);
1186 }
1187
GetStreamOperator(const sptr<IStreamOperatorCallback> & callbackObj,sptr<OHOS::HDI::Camera::V1_0::IStreamOperator> & streamOperator)1188 int32_t HCameraDevice::GetStreamOperator(const sptr<IStreamOperatorCallback> &callbackObj,
1189 sptr<OHOS::HDI::Camera::V1_0::IStreamOperator> &streamOperator)
1190 {
1191 std::lock_guard<std::mutex> lock(opMutex_);
1192 proxyStreamOperatorCallback_ = callbackObj;
1193 CHECK_ERROR_RETURN_RET_LOG(hdiCameraDevice_ == nullptr, CAMERA_UNKNOWN_ERROR,
1194 "HCameraDevice::GetStreamOperator hdiCameraDevice_ is null");
1195 CamRetCode rc;
1196 sptr<OHOS::HDI::Camera::V1_1::ICameraDevice> hdiCameraDeviceV1_1;
1197 sptr<OHOS::HDI::Camera::V1_2::ICameraDevice> hdiCameraDeviceV1_2;
1198 sptr<OHOS::HDI::Camera::V1_3::ICameraDevice> hdiCameraDeviceV1_3;
1199 int32_t versionRes = cameraHostManager_->GetVersionByCamera(cameraID_);
1200 if (versionRes >= GetVersionId(HDI_VERSION_1, HDI_VERSION_3)) {
1201 MEDIA_DEBUG_LOG("HCameraDevice::GetStreamOperator ICameraDevice cast to V1_3");
1202 hdiCameraDeviceV1_3 = OHOS::HDI::Camera::V1_3::ICameraDevice::CastFrom(hdiCameraDevice_);
1203 } else if (versionRes >= GetVersionId(HDI_VERSION_1, HDI_VERSION_2)) {
1204 MEDIA_DEBUG_LOG("HCameraDevice::GetStreamOperator ICameraDevice cast to V1_2");
1205 hdiCameraDeviceV1_2 = OHOS::HDI::Camera::V1_2::ICameraDevice::CastFrom(hdiCameraDevice_);
1206 } else if (versionRes == GetVersionId(HDI_VERSION_1, HDI_VERSION_1)) {
1207 MEDIA_DEBUG_LOG("HCameraDevice::GetStreamOperator ICameraDevice cast to V1_1");
1208 hdiCameraDeviceV1_1 = OHOS::HDI::Camera::V1_1::ICameraDevice::CastFrom(hdiCameraDevice_);
1209 if (hdiCameraDeviceV1_1 == nullptr) {
1210 MEDIA_ERR_LOG("HCameraDevice::GetStreamOperator ICameraDevice cast to V1_1 error");
1211 hdiCameraDeviceV1_1 = static_cast<OHOS::HDI::Camera::V1_1::ICameraDevice*>(hdiCameraDevice_.GetRefPtr());
1212 }
1213 }
1214
1215 if (hdiCameraDeviceV1_3 != nullptr && versionRes >= GetVersionId(HDI_VERSION_1, HDI_VERSION_3)) {
1216 sptr<OHOS::HDI::Camera::V1_3::IStreamOperator> streamOperator_v1_3;
1217 rc = (CamRetCode)(hdiCameraDeviceV1_3->GetStreamOperator_V1_3(callbackObj, streamOperator_v1_3));
1218 streamOperator = streamOperator_v1_3;
1219 } else if (hdiCameraDeviceV1_2 != nullptr && versionRes >= GetVersionId(HDI_VERSION_1, HDI_VERSION_2)) {
1220 MEDIA_DEBUG_LOG("HCameraDevice::GetStreamOperator ICameraDevice V1_2");
1221 sptr<OHOS::HDI::Camera::V1_2::IStreamOperator> streamOperator_v1_2;
1222 rc = (CamRetCode)(hdiCameraDeviceV1_2->GetStreamOperator_V1_2(callbackObj, streamOperator_v1_2));
1223 streamOperator = streamOperator_v1_2;
1224 } else if (hdiCameraDeviceV1_1 != nullptr && versionRes == GetVersionId(HDI_VERSION_1, HDI_VERSION_1)) {
1225 MEDIA_DEBUG_LOG("HCameraDevice::GetStreamOperator ICameraDevice V1_1");
1226 sptr<OHOS::HDI::Camera::V1_1::IStreamOperator> streamOperator_v1_1;
1227 rc = (CamRetCode)(hdiCameraDeviceV1_1->GetStreamOperator_V1_1(callbackObj, streamOperator_v1_1));
1228 streamOperator = streamOperator_v1_1;
1229 } else {
1230 MEDIA_DEBUG_LOG("HCameraDevice::GetStreamOperator ICameraDevice V1_0");
1231 rc = (CamRetCode)(hdiCameraDevice_->GetStreamOperator(callbackObj, streamOperator));
1232 }
1233 if (rc != HDI::Camera::V1_0::NO_ERROR) {
1234 MEDIA_ERR_LOG("HCameraDevice::GetStreamOperator failed with error Code:%{public}d", rc);
1235 CameraReportUtils::ReportCameraError(
1236 "HCameraDevice::GetStreamOperator", rc, true, CameraReportUtils::GetCallerInfo());
1237 return HdiToServiceError(rc);
1238 }
1239 return CAMERA_OK;
1240 }
1241
OnError(const OHOS::HDI::Camera::V1_0::ErrorType type,const int32_t errorMsg)1242 int32_t HCameraDevice::OnError(const OHOS::HDI::Camera::V1_0::ErrorType type, const int32_t errorMsg)
1243 {
1244 auto errType = static_cast<OHOS::HDI::Camera::V1_3::ErrorType>(type);
1245 MEDIA_ERR_LOG("CameraDeviceCallback::OnError() is called!, type: %{public}d,"
1246 "cameraID_: %{public}s, cameraPid: %{public}d.",
1247 type, cameraID_.c_str(), cameraPid_);
1248 if (errType == OHOS::HDI::Camera::V1_3::SENSOR_DATA_ERROR) {
1249 NotifyCameraStatus(HdiToCameraErrorType(errType), errorMsg);
1250 return CAMERA_OK;
1251 }
1252 NotifyCameraStatus(HdiToCameraErrorType(errType));
1253 auto callback = GetDeviceServiceCallback();
1254 if (callback != nullptr) {
1255 int32_t errorType;
1256 if (type == OHOS::HDI::Camera::V1_0::REQUEST_TIMEOUT) {
1257 errorType = CAMERA_DEVICE_REQUEST_TIMEOUT;
1258 } else if (type == OHOS::HDI::Camera::V1_0::DEVICE_PREEMPT) {
1259 errorType = CAMERA_DEVICE_PREEMPTED;
1260 } else if (type == DEVICE_DISCONNECT) {
1261 errorType = CAMERA_DEVICE_CLOSED;
1262 } else {
1263 errorType = CAMERA_UNKNOWN_ERROR;
1264 }
1265 callback->OnError(errorType, errorMsg);
1266 CAMERA_SYSEVENT_FAULT(CreateMsg("CameraDeviceServiceCallback::OnError() is called!, errorType: %d,"
1267 "errorMsg: %d",
1268 errorType, errorMsg));
1269 }
1270 return CAMERA_OK;
1271 }
1272
CheckOnResultData(std::shared_ptr<OHOS::Camera::CameraMetadata> cameraResult)1273 void HCameraDevice::CheckOnResultData(std::shared_ptr<OHOS::Camera::CameraMetadata> cameraResult)
1274 {
1275 CHECK_ERROR_RETURN_LOG(cameraResult == nullptr, "HCameraDevice::OnResult cameraResult is nullptr");
1276 camera_metadata_item_t item;
1277 common_metadata_header_t* metadata = cameraResult->get();
1278 int ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_CONTROL_FLASH_MODE, &item);
1279 if (ret == 0) {
1280 MEDIA_DEBUG_LOG("Flash mode: %{public}d", item.data.u8[0]);
1281 }
1282 ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_CONTROL_FLASH_STATE, &item);
1283 if (ret == 0) {
1284 MEDIA_DEBUG_LOG("Flash state: %{public}d", item.data.u8[0]);
1285 }
1286 ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_CONTROL_FOCUS_MODE, &item);
1287 if (ret == CAM_META_SUCCESS) {
1288 MEDIA_DEBUG_LOG("Focus mode: %{public}d", item.data.u8[0]);
1289 }
1290 ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_CONTROL_QUALITY_PRIORITIZATION, &item);
1291 if (ret == CAM_META_SUCCESS) {
1292 MEDIA_DEBUG_LOG("quality prioritization: %{public}d", item.data.u8[0]);
1293 }
1294 ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_CONTROL_FOCUS_STATE, &item);
1295 if (ret == CAM_META_SUCCESS) {
1296 MEDIA_DEBUG_LOG("Focus state: %{public}d", item.data.u8[0]);
1297 }
1298 ret = OHOS::Camera::FindCameraMetadataItem(metadata, OHOS_STATISTICS_FACE_RECTANGLES, &item);
1299 CHECK_ERROR_PRINT_LOG(ret != CAM_META_SUCCESS, "cannot find OHOS_STATISTICS_FACE_RECTANGLES: %{public}d", ret);
1300 MEDIA_DEBUG_LOG("ProcessFaceRectangles: %{public}d count: %{public}d", item.item, item.count);
1301 constexpr int32_t rectangleUnitLen = 4;
1302
1303 if (item.count % rectangleUnitLen) {
1304 MEDIA_DEBUG_LOG("Metadata item: %{public}d count: %{public}d is invalid", item.item, item.count);
1305 }
1306 const int32_t offsetX = 0;
1307 const int32_t offsetY = 1;
1308 const int32_t offsetW = 2;
1309 const int32_t offsetH = 3;
1310 float* start = item.data.f;
1311 float* end = item.data.f + item.count;
1312 for (; start < end; start += rectangleUnitLen) {
1313 MEDIA_DEBUG_LOG("Metadata item: %{public}f, %{public}f, %{public}f, %{public}f", start[offsetX], start[offsetY],
1314 start[offsetW], start[offsetH]);
1315 }
1316 }
1317
OnResult(const uint64_t timestamp,const std::vector<uint8_t> & result)1318 int32_t HCameraDevice::OnResult(const uint64_t timestamp, const std::vector<uint8_t>& result)
1319 {
1320 CHECK_ERROR_RETURN_RET_LOG(result.size() == 0, CAMERA_INVALID_ARG, "onResult get null meta from HAL");
1321 std::shared_ptr<OHOS::Camera::CameraMetadata> cameraResult = nullptr;
1322 OHOS::Camera::MetadataUtils::ConvertVecToMetadata(result, cameraResult);
1323 if (cameraResult == nullptr) {
1324 cameraResult = std::make_shared<OHOS::Camera::CameraMetadata>(0, 0);
1325 }
1326 CHECK_EXECUTE(IsCameraDebugOn(), CameraFwkMetadataUtils::DumpMetadataInfo(cameraResult));
1327 auto callback = GetDeviceServiceCallback();
1328 CHECK_EXECUTE(callback != nullptr, callback->OnResult(timestamp, cameraResult));
1329 ReportDeviceProtectionStatus(cameraResult);
1330 CHECK_EXECUTE(IsCameraDebugOn(), CheckOnResultData(cameraResult));
1331 CHECK_EXECUTE(isMovingPhotoEnabled_, GetMovingPhotoStartAndEndTime(cameraResult));
1332 return CAMERA_OK;
1333 }
1334
GetMovingPhotoStartAndEndTime(std::shared_ptr<OHOS::Camera::CameraMetadata> cameraResult)1335 void HCameraDevice::GetMovingPhotoStartAndEndTime(std::shared_ptr<OHOS::Camera::CameraMetadata> cameraResult)
1336 {
1337 MEDIA_DEBUG_LOG("HCameraDevice::GetMovingPhotoStartAndEndTime enter.");
1338 {
1339 std::lock_guard<std::mutex> lock(movingPhotoStartTimeCallbackLock_);
1340 if (movingPhotoStartTimeCallback_) {
1341 camera_metadata_item_t item;
1342 int ret = OHOS::Camera::FindCameraMetadataItem(cameraResult->get(), OHOS_MOVING_PHOTO_START, &item);
1343 if (ret == CAM_META_SUCCESS && item.count != 0) {
1344 int64_t captureId = item.data.i64[0];
1345 int64_t startTime = item.data.i64[1];
1346 movingPhotoStartTimeCallback_(static_cast<int32_t>(captureId), startTime);
1347 }
1348 }
1349 }
1350 std::lock_guard<std::mutex> lock(movingPhotoEndTimeCallbackLock_);
1351 if (movingPhotoEndTimeCallback_) {
1352 camera_metadata_item_t item;
1353 int ret = OHOS::Camera::FindCameraMetadataItem(cameraResult->get(), OHOS_MOVING_PHOTO_END, &item);
1354 if (ret == CAM_META_SUCCESS && item.count != 0) {
1355 int64_t captureId = item.data.i64[0];
1356 int64_t endTime = item.data.i64[1];
1357 movingPhotoEndTimeCallback_(static_cast<int32_t>(captureId), endTime);
1358 }
1359 }
1360 }
1361
SetMovingPhotoStartTimeCallback(std::function<void (int64_t,int64_t)> callback)1362 void HCameraDevice::SetMovingPhotoStartTimeCallback(std::function<void(int64_t, int64_t)> callback)
1363 {
1364 std::lock_guard<std::mutex> lock(movingPhotoStartTimeCallbackLock_);
1365 movingPhotoStartTimeCallback_ = callback;
1366 }
1367
SetMovingPhotoEndTimeCallback(std::function<void (int64_t,int64_t)> callback)1368 void HCameraDevice::SetMovingPhotoEndTimeCallback(std::function<void(int64_t, int64_t)> callback)
1369 {
1370 std::lock_guard<std::mutex> lock(movingPhotoEndTimeCallbackLock_);
1371 movingPhotoEndTimeCallback_ = callback;
1372 }
1373
GetCallerToken()1374 int32_t HCameraDevice::GetCallerToken()
1375 {
1376 return callerToken_;
1377 }
1378
CanOpenCamera()1379 bool HCameraDevice::CanOpenCamera()
1380 {
1381 int32_t cost;
1382 std::set<std::string> conflicting;
1383 if (GetCameraResourceCost(cost, conflicting)) {
1384 int32_t uidOfRequestProcess = IPCSkeleton::GetCallingUid();
1385 int32_t pidOfRequestProcess = IPCSkeleton::GetCallingPid();
1386 uint32_t accessTokenIdOfRequestProc = IPCSkeleton::GetCallingTokenID();
1387
1388 sptr<HCameraDeviceHolder> cameraRequestOpen = new HCameraDeviceHolder(
1389 pidOfRequestProcess, uidOfRequestProcess, 0, 0, this, accessTokenIdOfRequestProc, cost, conflicting);
1390
1391 std::vector<sptr<HCameraDeviceHolder>> evictedClients;
1392 bool ret = HCameraDeviceManager::GetInstance()->HandleCameraEvictions(evictedClients, cameraRequestOpen);
1393 // close evicted clients
1394 for (auto &camera : evictedClients) {
1395 MEDIA_DEBUG_LOG("HCameraDevice::CanOpenCamera open current device need to close");
1396 camera->GetDevice()->OnError(DEVICE_PREEMPT, 0);
1397 camera->GetDevice()->CloseDevice();
1398 }
1399 return ret;
1400 }
1401 std::vector<sptr<HCameraDevice>> cameraNeedEvict;
1402 bool ret = HCameraDeviceManager::GetInstance()->GetConflictDevices(cameraNeedEvict, this, cameraConcurrentType_);
1403 if (cameraNeedEvict.size() != 0) {
1404 MEDIA_DEBUG_LOG("HCameraDevice::CanOpenCamera open current device need to close other devices");
1405 for (auto deviceItem : cameraNeedEvict) {
1406 deviceItem->OnError(DEVICE_PREEMPT, 0);
1407 deviceItem->CloseDevice();
1408 }
1409 }
1410 return ret;
1411 }
1412
GetCameraResourceCost(int32_t & cost,std::set<std::string> & conflicting)1413 bool HCameraDevice::GetCameraResourceCost(int32_t &cost, std::set<std::string> &conflicting)
1414 {
1415 OHOS::HDI::Camera::V1_3::CameraDeviceResourceCost resourceCost;
1416 int32_t errorCode = cameraHostManager_->GetCameraResourceCost(cameraID_, resourceCost);
1417 CHECK_ERROR_RETURN_RET_LOG(errorCode != CAMERA_OK, false, "GetCameraResourceCost failed");
1418 cost = static_cast<int32_t>(resourceCost.resourceCost_);
1419 for (size_t i = 0; i < resourceCost.conflictingDevices_.size(); i++) {
1420 conflicting.emplace(resourceCost.conflictingDevices_[i]);
1421 }
1422 return true;
1423 }
1424
OperatePermissionCheck(uint32_t interfaceCode)1425 int32_t HCameraDevice::OperatePermissionCheck(uint32_t interfaceCode)
1426 {
1427 uint32_t callerToken = IPCSkeleton::GetCallingTokenID();
1428 int32_t errCode = CheckPermission(OHOS_PERMISSION_CAMERA, callerToken);
1429 CHECK_ERROR_RETURN_RET(errCode != CAMERA_OK, errCode);
1430 switch (static_cast<CameraDeviceInterfaceCode>(interfaceCode)) {
1431 case CameraDeviceInterfaceCode::CAMERA_DEVICE_OPEN:
1432 case CameraDeviceInterfaceCode::CAMERA_DEVICE_CLOSE:
1433 case CameraDeviceInterfaceCode::CAMERA_DEVICE_RELEASE:
1434 case CameraDeviceInterfaceCode::CAMERA_DEVICE_SET_CALLBACK:
1435 case CameraDeviceInterfaceCode::CAMERA_DEVICE_UNSET_CALLBACK:
1436 case CameraDeviceInterfaceCode::CAMERA_DEVICE_UPDATE_SETTNGS:
1437 case CameraDeviceInterfaceCode::CAMERA_DEVICE_SET_USED_POS:
1438 case CameraDeviceInterfaceCode::CAMERA_DEVICE_GET_ENABLED_RESULT:
1439 case CameraDeviceInterfaceCode::CAMERA_DEVICE_ENABLED_RESULT:
1440 case CameraDeviceInterfaceCode::CAMERA_DEVICE_DISABLED_RESULT: {
1441 CHECK_ERROR_RETURN_RET_LOG(callerToken_ != callerToken, CAMERA_OPERATION_NOT_ALLOWED,
1442 "HCameraDevice::OperatePermissionCheck fail, callerToken_ is : %{public}d, now token "
1443 "is %{public}d", callerToken_, callerToken);
1444 break;
1445 }
1446 default:
1447 break;
1448 }
1449 return CAMERA_OK;
1450 }
1451
NotifyCameraSessionStatus(bool running)1452 void HCameraDevice::NotifyCameraSessionStatus(bool running)
1453 {
1454 bool isSystemCamera = (clientName_ == SYSTEM_CAMERA);
1455 DeferredProcessing::DeferredProcessingService::GetInstance().NotifyCameraSessionStatus(clientUserId_, cameraID_,
1456 running, isSystemCamera);
1457 return;
1458 }
1459
RemoveResourceWhenHostDied()1460 void HCameraDevice::RemoveResourceWhenHostDied()
1461 {
1462 MEDIA_DEBUG_LOG("HCameraDevice::RemoveResourceWhenHostDied start");
1463 CAMERA_SYNC_TRACE;
1464 bool isFoldable = OHOS::Rosen::DisplayManager::GetInstance().IsFoldable();
1465 CHECK_EXECUTE(isFoldable, UnregisterFoldStatusListener());
1466 HCameraDeviceManager::GetInstance()->RemoveDevice(cameraID_);
1467 if (cameraHostManager_) {
1468 cameraHostManager_->RemoveCameraDevice(cameraID_);
1469 cameraHostManager_->UpdateRestoreParamCloseTime(clientName_, cameraID_);
1470 }
1471 POWERMGR_SYSEVENT_CAMERA_DISCONNECT(cameraID_.c_str());
1472 NotifyCameraSessionStatus(false);
1473 NotifyCameraStatus(CAMERA_CLOSE);
1474 #ifdef MEMMGR_OVERRID
1475 RequireMemory(Memory::CAMERA_END);
1476 #endif
1477 HandlePrivacyAfterCloseDevice();
1478 MEDIA_DEBUG_LOG("HCameraDevice::RemoveResourceWhenHostDied end");
1479 }
1480
NotifyCameraStatus(int32_t state,int32_t msg)1481 void HCameraDevice::NotifyCameraStatus(int32_t state, int32_t msg)
1482 {
1483 OHOS::AAFwk::Want want;
1484 MEDIA_DEBUG_LOG("HCameraDevice::NotifyCameraStatus strat");
1485 want.SetAction(COMMON_EVENT_CAMERA_STATUS);
1486 want.SetParam(CLIENT_USER_ID, clientUserId_);
1487 want.SetParam(CAMERA_ID, cameraID_);
1488 want.SetParam(CAMERA_STATE, state);
1489 int32_t type = GetCameraType();
1490 want.SetParam(IS_SYSTEM_CAMERA, type);
1491 want.SetParam(CAMERA_MSG, msg);
1492 want.SetParam(CLIENT_NAME, clientName_);
1493 MEDIA_DEBUG_LOG(
1494 "OnCameraStatusChanged userId: %{public}d, cameraId: %{public}s, state: %{public}d, "
1495 "cameraType: %{public}d, msg: %{public}d, clientName: %{public}s",
1496 clientUserId_, cameraID_.c_str(), state, type, msg, clientName_.c_str());
1497 EventFwk::CommonEventData CommonEventData { want };
1498 EventFwk::CommonEventPublishInfo publishInfo;
1499 std::vector<std::string> permissionVec { OHOS_PERMISSION_MANAGE_CAMERA_CONFIG };
1500 publishInfo.SetSubscriberPermissions(permissionVec);
1501 EventFwk::CommonEventManager::PublishCommonEvent(CommonEventData, publishInfo);
1502 MEDIA_DEBUG_LOG("HCameraDevice::NotifyCameraStatus end");
1503 }
1504
Open(int32_t concurrentType)1505 int32_t HCameraDevice::Open(int32_t concurrentType)
1506 {
1507 CAMERA_SYNC_TRACE;
1508 std::lock_guard<std::mutex> lock(g_deviceOpenCloseMutex_);
1509 CHECK_ERROR_PRINT_LOG(isOpenedCameraDevice_.load(), "HCameraDevice::Open failed, camera is busy");
1510 CHECK_ERROR_RETURN_RET_LOG(!IsInForeGround(callerToken_), CAMERA_ALLOC_ERROR,
1511 "HCameraDevice::Open IsAllowedUsingPermission failed");
1512 MEDIA_INFO_LOG(
1513 "HCameraDevice::Open Camera width concurrent:[%{public}s, %{public}d]", cameraID_.c_str(), concurrentType);
1514 SetCameraConcurrentType(concurrentType);
1515 EnableDeviceOpenedByConcurrent(true);
1516 int32_t result = OpenDevice();
1517 return result;
1518 }
1519
GetConcurrentDevicesTable()1520 std::vector<std::vector<std::int32_t>> HCameraDevice::GetConcurrentDevicesTable()
1521 {
1522 std::shared_ptr<OHOS::Camera::CameraMetadata> ability = GetDeviceAbility();
1523 std::vector<std::vector<std::int32_t>> resultTable;
1524 CHECK_ERROR_RETURN_RET(ability == nullptr, resultTable);
1525 std::vector<std::int32_t> concurrentList;
1526 int32_t ret;
1527 camera_metadata_item_t item;
1528 ret = OHOS::Camera::FindCameraMetadataItem(ability->get(), OHOS_ABILITY_CONCURRENT_SUPPORTED_CAMERAS, &item);
1529 if (ret == CAM_META_SUCCESS) {
1530 for (uint32_t index = 0; index < item.count; index++) {
1531 int32_t cameraId = item.data.i32[index];
1532 if (cameraId == -1) {
1533 resultTable.push_back(concurrentList);
1534 concurrentList.clear();
1535 } else {
1536 concurrentList.push_back(cameraId);
1537 }
1538 }
1539 }
1540 resultTable.push_back(concurrentList);
1541 concurrentList.clear();
1542 MEDIA_INFO_LOG("HCameraDevice::GetConcurrentDevicesTable device id : %{public}s"
1543 "find concurrent table size: %{public}zu", cameraID_.c_str(), resultTable.size());
1544 return resultTable;
1545 }
1546 } // namespace CameraStandard
1547 } // namespace OHOS
1548