• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 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 "input/camera_manager.h"
17 
18 #include <climits>
19 #include <cstddef>
20 #include <cstdint>
21 #include <cstring>
22 #include <memory>
23 #include <mutex>
24 #include <nlohmann/json.hpp>
25 #include <ostream>
26 #include <parameters.h>
27 #include <regex>
28 #include <sstream>
29 #include <unordered_map>
30 
31 #include "ability/camera_ability_parse_util.h"
32 #include "bundle_mgr_interface.h"
33 #include "camera_counting_timer.h"
34 #include "camera_device.h"
35 #include "camera_device_ability_items.h"
36 #include "camera_error_code.h"
37 #include "camera_input.h"
38 #include "camera_log.h"
39 #include "camera_rotation_api_utils.h"
40 #include "camera_security_utils.h"
41 #include "camera_service_system_ability_listener.h"
42 #include "camera_util.h"
43 #include "capture_input.h"
44 #include "capture_scene_const.h"
45 #include "control_center_session.h"
46 #include "deferred_photo_proc_session.h"
47 #include "display_manager.h"
48 #include "icamera_service_callback.h"
49 #include "icamera_util.h"
50 #include "icapture_session.h"
51 #include "icontrol_center_status_callback.h"
52 #include "ipc_skeleton.h"
53 #include "iservice_registry.h"
54 #include "istream_capture.h"
55 #include "refbase.h"
56 #include "session/capture_session.h"
57 #include "session/photo_session.h"
58 #include "session/scan_session.h"
59 #include "session/secure_camera_session.h"
60 #include "session/video_session.h"
61 #include "system_ability_definition.h"
62 #include "anonymization.h"
63 
64 using namespace std;
65 namespace OHOS {
66 namespace CameraStandard {
67 using OHOS::HDI::Camera::V1_3::OperationMode;
68 sptr<CameraManager> CameraManager::g_cameraManager = nullptr;
69 std::mutex CameraManager::g_instanceMutex;
70 
71 constexpr int32_t CONTROL_CENTER_RESOLUTION_WIDTH_MAX = 1920;
72 constexpr int32_t CONTROL_CENTER_RESOLUTION_HEIGHT_MAX = 1080;
73 
74 const std::string CameraManager::surfaceFormat = "CAMERA_SURFACE_FORMAT";
75 
76 const std::unordered_map<camera_format_t, CameraFormat> CameraManager::metaToFwCameraFormat_ = {
77     {OHOS_CAMERA_FORMAT_YCRCB_420_SP, CAMERA_FORMAT_YUV_420_SP},
78     {OHOS_CAMERA_FORMAT_JPEG, CAMERA_FORMAT_JPEG},
79     {OHOS_CAMERA_FORMAT_RGBA_8888, CAMERA_FORMAT_RGBA_8888},
80     {OHOS_CAMERA_FORMAT_YCBCR_P010, CAMERA_FORMAT_YCBCR_P010},
81     {OHOS_CAMERA_FORMAT_YCRCB_P010, CAMERA_FORMAT_YCRCB_P010},
82     {OHOS_CAMERA_FORMAT_YCBCR_420_SP, CAMERA_FORMAT_NV12},
83     {OHOS_CAMERA_FORMAT_422_YUYV, CAMERA_FORMAT_YUV_422_YUYV},
84     {OHOS_CAMERA_FORMAT_422_UYVY, CAMERA_FORMAT_YUV_422_UYVY},
85     {OHOS_CAMERA_FORMAT_DNG, CAMERA_FORMAT_DNG},
86     {OHOS_CAMERA_FORMAT_DNG_XDRAW, CAMERA_FORMAT_DNG_XDRAW},
87     {OHOS_CAMERA_FORMAT_HEIC, CAMERA_FORMAT_HEIC},
88     {OHOS_CAMERA_FORMAT_DEPTH_16, CAMERA_FORMAT_DEPTH_16},
89     {OHOS_CAMERA_FORMAT_DEPTH_32, CAMERA_FORMAT_DEPTH_32},
90     {OHOS_CAMERA_FORMAT_MJPEG, CAMERA_FORMAT_MJPEG}
91 };
92 
93 const std::unordered_map<DepthDataAccuracyType, DepthDataAccuracy> CameraManager::metaToFwDepthDataAccuracy_ = {
94     {OHOS_DEPTH_DATA_ACCURACY_RELATIVE, DEPTH_DATA_ACCURACY_RELATIVE},
95     {OHOS_DEPTH_DATA_ACCURACY_ABSOLUTE, DEPTH_DATA_ACCURACY_ABSOLUTE},
96 };
97 
98 const std::unordered_map<CameraFormat, camera_format_t> CameraManager::fwToMetaCameraFormat_ = {
99     {CAMERA_FORMAT_YUV_420_SP, OHOS_CAMERA_FORMAT_YCRCB_420_SP},
100     {CAMERA_FORMAT_JPEG, OHOS_CAMERA_FORMAT_JPEG},
101     {CAMERA_FORMAT_RGBA_8888, OHOS_CAMERA_FORMAT_RGBA_8888},
102     {CAMERA_FORMAT_YCBCR_P010, OHOS_CAMERA_FORMAT_YCBCR_P010},
103     {CAMERA_FORMAT_YCRCB_P010, OHOS_CAMERA_FORMAT_YCRCB_P010},
104     {CAMERA_FORMAT_NV12, OHOS_CAMERA_FORMAT_YCBCR_420_SP},
105     {CAMERA_FORMAT_YUV_422_YUYV, OHOS_CAMERA_FORMAT_422_YUYV},
106     {CAMERA_FORMAT_YUV_422_UYVY, OHOS_CAMERA_FORMAT_422_UYVY},
107     {CAMERA_FORMAT_DNG, OHOS_CAMERA_FORMAT_DNG},
108     {CAMERA_FORMAT_DNG_XDRAW, OHOS_CAMERA_FORMAT_DNG_XDRAW},
109     {CAMERA_FORMAT_HEIC, OHOS_CAMERA_FORMAT_HEIC},
110     {CAMERA_FORMAT_DEPTH_16, OHOS_CAMERA_FORMAT_DEPTH_16},
111     {CAMERA_FORMAT_DEPTH_32, OHOS_CAMERA_FORMAT_DEPTH_32},
112     {CAMERA_FORMAT_MJPEG, OHOS_CAMERA_FORMAT_MJPEG}
113 };
114 
115 const std::unordered_map<CameraFoldStatus, FoldStatus> g_metaToFwCameraFoldStatus_ = {
116     {OHOS_CAMERA_FOLD_STATUS_NONFOLDABLE, FoldStatus::UNKNOWN_FOLD},
117     {OHOS_CAMERA_FOLD_STATUS_EXPANDED, FoldStatus::EXPAND},
118     {OHOS_CAMERA_FOLD_STATUS_FOLDED, FoldStatus::FOLDED}
119 };
120 
121 const std::set<int32_t> isTemplateMode_ = {
122     SceneMode::CAPTURE, SceneMode::VIDEO
123 };
124 
125 const std::set<int32_t> isPhotoMode_ = {
126     SceneMode::CAPTURE, SceneMode::PORTRAIT
127 };
128 
129 const std::unordered_map<CameraPosition, camera_position_enum_t> fwToMetaCameraPosition_ = {
130     {CAMERA_POSITION_FRONT, OHOS_CAMERA_POSITION_FRONT},
131     {CAMERA_POSITION_BACK, OHOS_CAMERA_POSITION_BACK},
132     {CAMERA_POSITION_UNSPECIFIED, OHOS_CAMERA_POSITION_OTHER}
133 };
134 
ConvertMetaToFwkMode(const OperationMode opMode,SceneMode & scMode)135 bool ConvertMetaToFwkMode(const OperationMode opMode, SceneMode &scMode)
136 {
137     // LCOV_EXCL_START
138     auto it = g_metaToFwSupportedMode_.find(opMode);
139     if (it != g_metaToFwSupportedMode_.end()) {
140         scMode = it->second;
141         MEDIA_DEBUG_LOG("ConvertMetaToFwkMode OperationMode = %{public}d to SceneMode %{public}d", opMode, scMode);
142         return true;
143     }
144     MEDIA_ERR_LOG("ConvertMetaToFwkMode OperationMode = %{public}d err", opMode);
145     return false;
146     // LCOV_EXCL_STOP
147 }
148 
ConvertFwkToMetaMode(const SceneMode scMode,OperationMode & opMode)149 bool ConvertFwkToMetaMode(const SceneMode scMode, OperationMode &opMode)
150 {
151     auto it = g_fwToMetaSupportedMode_.find(scMode);
152     if (it != g_fwToMetaSupportedMode_.end()) {
153         opMode = it->second;
154         MEDIA_DEBUG_LOG("ConvertFwkToMetaMode SceneMode %{public}d to OperationMode = %{public}d", scMode, opMode);
155         return true;
156     }
157     MEDIA_ERR_LOG("ConvertFwkToMetaMode SceneMode = %{public}d err", scMode);
158     return false;
159 }
160 
CameraManager()161 CameraManager::CameraManager()
162 {
163     MEDIA_INFO_LOG("CameraManager::CameraManager construct enter");
164     cameraStatusListenerManager_->SetCameraManager(this);
165     torchServiceListenerManager_->SetCameraManager(this);
166     cameraMuteListenerManager_->SetCameraManager(this);
167     foldStatusListenerManager_->SetCameraManager(this);
168     controlCenterStatusListenerManager_->SetCameraManager(this);
169 }
170 
~CameraManager()171 CameraManager::~CameraManager()
172 {
173     MEDIA_INFO_LOG("CameraManager::~CameraManager() called");
174     RemoveServiceProxyDeathRecipient();
175     UnSubscribeSystemAbility();
176 }
177 
CreateListenerObject()178 int32_t CameraManager::CreateListenerObject()
179 {
180     MEDIA_DEBUG_LOG("CameraManager::CreateListenerObject prepare execute");
181     sptr<CameraListenerStub> listenerStub = new (std::nothrow) CameraListenerStub();
182     CHECK_RETURN_RET_ELOG(listenerStub == nullptr, CAMERA_ALLOC_ERROR, "failed to new CameraListenerStub object");
183     sptr<IRemoteObject> object = listenerStub->AsObject();
184     CHECK_RETURN_RET_ELOG(object == nullptr, CAMERA_ALLOC_ERROR, "listener object is nullptr..");
185     auto serviceProxy = GetServiceProxy();
186     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CameraErrorCode::SERVICE_FATL_ERROR, "serviceProxy is null");
187     return serviceProxy->SetListenerObject(object);
188 }
189 
OnCameraStatusChanged(const std::string & cameraId,const int32_t status,const std::string & bundleName)190 int32_t CameraStatusListenerManager::OnCameraStatusChanged(
191     const std::string& cameraId, const int32_t status, const std::string& bundleName)
192 {
193     MEDIA_INFO_LOG("OnCameraStatusChanged cameraId: %{public}s, status: %{public}d", cameraId.c_str(), status);
194     auto cameraManager = GetCameraManager();
195     CHECK_RETURN_RET_ELOG(cameraManager == nullptr, CAMERA_OK, "OnCameraStatusChanged CameraManager is nullptr");
196 
197     CameraStatusInfo cameraStatusInfo;
198     // LCOV_EXCL_START
199     if (status == static_cast<int32_t>(CameraStatus::CAMERA_STATUS_APPEAR)) {
200         cameraManager->ClearCameraDeviceListCache();
201         cameraManager->ClearCameraDeviceAbilitySupportMap();
202     }
203     // LCOV_EXCL_STOP
204     sptr<CameraDevice> cameraInfo = cameraManager->GetCameraDeviceFromId(cameraId);
205     cameraStatusInfo.cameraDevice = cameraInfo;
206     CHECK_EXECUTE(status == static_cast<int32_t>(CameraStatus::CAMERA_STATUS_DISAPPEAR),
207         cameraManager->RemoveCameraDeviceFromCache(cameraId));
208     cameraStatusInfo.cameraStatus = static_cast<CameraStatus>(status);
209     cameraStatusInfo.bundleName = bundleName;
210 
211     CHECK_EXECUTE(!CheckCameraStatusValid(cameraInfo), return CAMERA_OK);
212     if (cameraStatusInfo.cameraDevice) {
213         auto listenerManager = cameraManager->GetCameraStatusListenerManager();
214         MEDIA_DEBUG_LOG("CameraStatusListenerManager listeners size: %{public}zu", listenerManager->GetListenerCount());
215         listenerManager->TriggerListener([&](auto listener) { listener->OnCameraStatusChanged(cameraStatusInfo); });
216         listenerManager->CacheCameraStatus(cameraId, std::make_shared<CameraStatusInfo>(cameraStatusInfo));
217     }
218     return CAMERA_OK;
219 }
220 
OnFlashlightStatusChanged(const std::string & cameraId,const int32_t status)221 int32_t CameraStatusListenerManager::OnFlashlightStatusChanged(const std::string& cameraId,
222     const int32_t status)
223 {
224     MEDIA_INFO_LOG("cameraId: %{public}s, status: %{public}d", cameraId.c_str(), status);
225     auto cameraManager = GetCameraManager();
226     CHECK_RETURN_RET_ELOG(
227         cameraManager == nullptr, CAMERA_OK, "OnFlashlightStatusChanged CameraManager is nullptr");
228     auto listenerManager = cameraManager->GetCameraStatusListenerManager();
229     MEDIA_DEBUG_LOG("CameraStatusListenerManager listeners size: %{public}zu", listenerManager->GetListenerCount());
230     listenerManager->TriggerListener([&](auto listener) {
231         listener->OnFlashlightStatusChanged(cameraId, static_cast<FlashStatus>(status));
232     });
233     listenerManager->CacheFlashStatus(cameraId, static_cast<FlashStatus>(status));
234     return CAMERA_OK;
235 }
236 
CheckCameraStatusValid(sptr<CameraDevice> cameraInfo)237 bool CameraStatusListenerManager::CheckCameraStatusValid(sptr<CameraDevice> cameraInfo)
238 {
239     // LCOV_EXCL_START
240     auto cameraManager = GetCameraManager();
241     CHECK_RETURN_RET_ELOG(cameraManager == nullptr || cameraInfo == nullptr,
242         false, "CheckCameraStatusValid CameraManager is nullptr");
243     std::string foldScreenType = cameraManager->GetFoldScreenType();
244     if (!foldScreenType.empty() && foldScreenType[0] == '4' &&
245         cameraInfo->GetPosition() == CAMERA_POSITION_BACK) {
246         std::string bundleName_ = system::GetParameter("const.camera.folded_lens_change", "default");
247         FoldStatus curFoldStatus = cameraManager->GetFoldStatus();
248         auto supportedFoldStatus = cameraInfo->GetSupportedFoldStatus();
249         auto it = g_metaToFwCameraFoldStatus_.find(static_cast<CameraFoldStatus>(supportedFoldStatus));
250         CHECK_RETURN_RET_DLOG(it == g_metaToFwCameraFoldStatus_.end(), false,
251             "No supported fold status is found");
252         CHECK_RETURN_RET_DLOG(it->second != curFoldStatus, false,
253             "current foldstatus is inconsistency");
254         bool isSpecialScene = it->second == curFoldStatus && curFoldStatus == FoldStatus::FOLDED &&
255             bundleName_ != "default" && cameraManager->GetBundleName() != bundleName_;
256         MEDIA_DEBUG_LOG("curFoldStatus %{public}d it->second= %{public}d cameraid = %{public}s",
257             static_cast<int32_t>(curFoldStatus), it->second, cameraInfo->GetID().c_str());
258         CHECK_RETURN_RET_ELOG(isSpecialScene, false, "CameraStatusListenerManager not notify");
259     }
260     return true;
261     // LCOV_EXCL_STOP
262 }
263 
CreateCaptureSession()264 sptr<CaptureSession> CameraManager::CreateCaptureSession()
265 {
266     CAMERA_SYNC_TRACE;
267     sptr<CaptureSession> captureSession = nullptr;
268     int ret = CreateCaptureSession(captureSession, SceneMode::NORMAL);
269     CHECK_RETURN_RET_ELOG(ret != CameraErrorCode::SUCCESS, nullptr,
270         "Failed to CreateCaptureSession with error code:%{public}d", ret);
271     return captureSession;
272 }
273 
CreateCaptureSessionImpl(SceneMode mode,sptr<ICaptureSession> session)274 sptr<CaptureSession> CameraManager::CreateCaptureSessionImpl(SceneMode mode, sptr<ICaptureSession> session)
275 {
276     // LCOV_EXCL_START
277     switch (mode) {
278         case SceneMode::VIDEO:
279             return new (std::nothrow) VideoSession(session);
280         case SceneMode::CAPTURE:
281             return new (std::nothrow) PhotoSession(session);
282         case SceneMode::SECURE:
283             return new (std::nothrow) SecureCameraSession(session);
284         case SceneMode::SCAN:
285             return new (std::nothrow) ScanSession(session);
286         default:
287             return new (std::nothrow) CaptureSession(session);
288     }
289     // LCOV_EXCL_STOP
290 }
291 
CreateCaptureSession(SceneMode mode)292 sptr<CaptureSession> CameraManager::CreateCaptureSession(SceneMode mode)
293 {
294     sptr<CaptureSession> session = nullptr;
295     CreateCaptureSession(session, mode);
296     return session;
297 }
298 
CreateCaptureSessionFromService(sptr<ICaptureSession> & session,SceneMode mode)299 int32_t CameraManager::CreateCaptureSessionFromService(sptr<ICaptureSession>& session, SceneMode mode)
300 {
301     // LCOV_EXCL_START
302     sptr<ICaptureSession> sessionTmp = nullptr;
303     auto serviceProxy = GetServiceProxy();
304     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CameraErrorCode::INVALID_ARGUMENT,
305         "CreateCaptureSessionFromService serviceProxy is nullptr");
306     OperationMode opMode = OperationMode::NORMAL;
307     CHECK_PRINT_ELOG(!ConvertFwkToMetaMode(mode, opMode),
308         "CameraManager::CreateCaptureSession ConvertFwkToMetaMode mode: %{public}d fail", mode);
309     int32_t retCode = serviceProxy->CreateCaptureSession(sessionTmp, opMode);
310     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
311         "CreateCaptureSessionFromService Failed to get captureSession object from hcamera service! "
312         "%{public}d", retCode);
313     CHECK_RETURN_RET_ELOG(sessionTmp == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
314         "CreateCaptureSessionFromService Failed to CreateCaptureSession with session is null");
315     session = sessionTmp;
316     return CameraErrorCode::SUCCESS;
317     // LCOV_EXCL_STOP
318 }
319 
CreateCaptureSession(sptr<CaptureSession> & pCaptureSession,SceneMode mode)320 int32_t CameraManager::CreateCaptureSession(sptr<CaptureSession>& pCaptureSession, SceneMode mode)
321 {
322     CAMERA_SYNC_TRACE;
323     sptr<ICaptureSession> session = nullptr;
324     sptr<CaptureSession> captureSession = nullptr;
325     auto serviceProxy = GetServiceProxy();
326     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CameraErrorCode::INVALID_ARGUMENT,
327         "CreateCaptureSession(pCaptureSession) serviceProxy is nullptr");
328     OperationMode opMode = OperationMode::NORMAL;
329     CHECK_PRINT_ELOG(!ConvertFwkToMetaMode(mode, opMode),
330         "CameraManager::CreateCaptureSession ConvertFwkToMetaMode mode: %{public}d fail", mode);
331     int32_t retCode = serviceProxy->CreateCaptureSession(session, opMode);
332     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
333         "CreateCaptureSession(pCaptureSession) Failed to get captureSession object from hcamera service! "
334         "%{public}d", retCode);
335     CHECK_RETURN_RET_ELOG(session == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
336         "CreateCaptureSession(pCaptureSession) Failed to CreateCaptureSession with session is null");
337     captureSession = CreateCaptureSessionImpl(mode, session);
338     CHECK_RETURN_RET_ELOG(captureSession == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
339         "CreateCaptureSession(pCaptureSession) failed to new captureSession!");
340     captureSession->SetMode(mode);
341     pCaptureSession = captureSession;
342     return CameraErrorCode::SUCCESS;
343 }
344 
CreateCaptureSession(sptr<CaptureSession> * pCaptureSession)345 int32_t CameraManager::CreateCaptureSession(sptr<CaptureSession>* pCaptureSession)
346 {
347     return CreateCaptureSession(*pCaptureSession, SceneMode::NORMAL);
348 }
349 
CreateDeferredPhotoProcessingSession(int userId,std::shared_ptr<IDeferredPhotoProcSessionCallback> callback)350 sptr<DeferredPhotoProcSession> CameraManager::CreateDeferredPhotoProcessingSession(int userId,
351     std::shared_ptr<IDeferredPhotoProcSessionCallback> callback)
352 {
353     CAMERA_SYNC_TRACE;
354     sptr<DeferredPhotoProcSession> deferredPhotoProcSession = nullptr;
355     int32_t retCode = CreateDeferredPhotoProcessingSession(userId, callback, &deferredPhotoProcSession);
356     CHECK_RETURN_RET_ELOG(retCode != CameraErrorCode::SUCCESS, nullptr,
357         "Failed to CreateDeferredPhotoProcessingSession with error code:%{public}d", retCode);
358     return deferredPhotoProcSession;
359 }
360 
CreateDeferredPhotoProcessingSession(int userId,std::shared_ptr<IDeferredPhotoProcSessionCallback> callback,sptr<DeferredPhotoProcSession> * pDeferredPhotoProcSession)361 int CameraManager::CreateDeferredPhotoProcessingSession(int userId,
362     std::shared_ptr<IDeferredPhotoProcSessionCallback> callback,
363     sptr<DeferredPhotoProcSession> *pDeferredPhotoProcSession)
364 {
365     CAMERA_SYNC_TRACE;
366     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
367     CHECK_RETURN_RET_ELOG(samgr == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
368         "CreateDeferredPhotoProcessingSession Failed to get System ability manager");
369     sptr<IRemoteObject> object = samgr->GetSystemAbility(CAMERA_SERVICE_ID);
370     CHECK_RETURN_RET_ELOG(object == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
371         "CreateDeferredPhotoProcessingSession object is null");
372     sptr<ICameraService> serviceProxy = iface_cast<ICameraService>(object);
373     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
374         "CreateDeferredPhotoProcessingSession serviceProxy is null");
375 
376     sptr<DeferredPhotoProcSession> deferredPhotoProcSession =
377         new(std::nothrow) DeferredPhotoProcSession(userId, callback);
378     CHECK_RETURN_RET_ELOG(deferredPhotoProcSession == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
379         "CreateDeferredPhotoProcessingSession failed to new deferredPhotoProcSession!");
380     sptr<DeferredProcessing::IDeferredPhotoProcessingSessionCallback> remoteCallback =
381         new(std::nothrow) DeferredPhotoProcessingSessionCallback(deferredPhotoProcSession);
382     CHECK_RETURN_RET_ELOG(remoteCallback == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
383         "CreateDeferredPhotoProcessingSession failed to new remoteCallback!");
384 
385     sptr<DeferredProcessing::IDeferredPhotoProcessingSession> session = nullptr;
386     int32_t retCode = serviceProxy->CreateDeferredPhotoProcessingSession(userId, remoteCallback, session);
387     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
388         "Failed to get photo session!, %{public}d", retCode);
389     CHECK_RETURN_RET_ELOG(session == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
390         "CreateDeferredPhotoProcessingSession Failed to CreateDeferredPhotoProcessingSession as session is null");
391 
392     deferredPhotoProcSession->SetDeferredPhotoSession(session);
393     *pDeferredPhotoProcSession = deferredPhotoProcSession;
394     return CameraErrorCode::SUCCESS;
395 }
396 
CreateDeferredVideoProcessingSession(int userId,std::shared_ptr<IDeferredVideoProcSessionCallback> callback)397 sptr<DeferredVideoProcSession> CameraManager::CreateDeferredVideoProcessingSession(int userId,
398     std::shared_ptr<IDeferredVideoProcSessionCallback> callback)
399 {
400     CAMERA_SYNC_TRACE;
401     sptr<DeferredVideoProcSession> deferredVideoProcSession = nullptr;
402     int ret = CreateDeferredVideoProcessingSession(userId, callback, &deferredVideoProcSession);
403     if (ret != CameraErrorCode::SUCCESS) {
404         MEDIA_ERR_LOG("Failed to CreateDeferredVideoProcessingSession with error code:%{public}d", ret);
405         return nullptr;
406     }
407     return deferredVideoProcSession;
408 }
409 
CreateDeferredVideoProcessingSession(int userId,std::shared_ptr<IDeferredVideoProcSessionCallback> callback,sptr<DeferredVideoProcSession> * pDeferredVideoProcSession)410 int CameraManager::CreateDeferredVideoProcessingSession(int userId,
411     std::shared_ptr<IDeferredVideoProcSessionCallback> callback,
412     sptr<DeferredVideoProcSession> *pDeferredVideoProcSession)
413 {
414     CAMERA_SYNC_TRACE;
415     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
416     CHECK_RETURN_RET_ELOG(samgr == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
417         "CreateDeferredVideoProcessingSession Failed to get System ability manager");
418     sptr<IRemoteObject> object = samgr->GetSystemAbility(CAMERA_SERVICE_ID);
419     CHECK_RETURN_RET_ELOG(object == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
420         "CreateDeferredVideoProcessingSession object is null");
421     sptr<ICameraService> serviceProxy = iface_cast<ICameraService>(object);
422     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
423         "CreateDeferredVideoProcessingSession serviceProxy is null");
424 
425     auto deferredVideoProcSession = new(std::nothrow) DeferredVideoProcSession(userId, callback);
426     CHECK_RETURN_RET_ELOG(deferredVideoProcSession == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
427         "CreateDeferredVideoProcessingSession failed to new deferredVideoProcSession!");
428     sptr<DeferredProcessing::IDeferredVideoProcessingSessionCallback> remoteCallback =
429         new(std::nothrow) DeferredVideoProcessingSessionCallback(deferredVideoProcSession);
430     CHECK_RETURN_RET_ELOG(remoteCallback == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
431         "CreateDeferredVideoProcessingSession failed to new remoteCallback!");
432 
433     sptr<DeferredProcessing::IDeferredVideoProcessingSession> session = nullptr;
434     int32_t retCode = serviceProxy->CreateDeferredVideoProcessingSession(userId, remoteCallback, session);
435     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
436         "Failed to get video session!, %{public}d", retCode);
437     CHECK_RETURN_RET_ELOG(session == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
438         "CreateDeferredVideoProcessingSession Failed to CreateDeferredVideoProcessingSession as session is null");
439 
440     deferredVideoProcSession->SetDeferredVideoSession(session);
441     *pDeferredVideoProcSession = deferredVideoProcSession;
442     return CameraErrorCode::SUCCESS;
443 }
444 
CreateMechSession(int userId)445 sptr<MechSession> CameraManager::CreateMechSession(int userId)
446 {
447     // LCOV_EXCL_START
448     CAMERA_SYNC_TRACE;
449     sptr<MechSession> mechSession = nullptr;
450     int32_t retCode = CreateMechSession(userId, &mechSession);
451     CHECK_RETURN_RET_ELOG(retCode != CameraErrorCode::SUCCESS, nullptr,
452         "Failed to CreateMechSession with error code:%{public}d", retCode);
453     return mechSession;
454     // LCOV_EXCL_STOP
455 }
456 
CreateMechSession(int userId,sptr<MechSession> * pMechSession)457 int CameraManager::CreateMechSession(int userId, sptr<MechSession>* pMechSession)
458 {
459     // LCOV_EXCL_START
460     CAMERA_SYNC_TRACE;
461     sptr<IMechSession> session = nullptr;
462     sptr<MechSession> mechSession = nullptr;
463 
464     auto serviceProxy = GetServiceProxy();
465     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CameraErrorCode::INVALID_ARGUMENT,
466         "CreateMechSession(pMechSession) serviceProxy is nullptr");
467     int32_t retCode = serviceProxy->CreateMechSession(userId, session);
468     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, retCode,
469         "Failed to get mech session!, %{public}d", retCode);
470     CHECK_RETURN_RET_ELOG(session == nullptr, retCode,
471         "CreateMechSession Failed to CreateMechSession as session is null");
472 
473     mechSession = new(std::nothrow) MechSession(session);
474     CHECK_RETURN_RET_ELOG(mechSession == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
475         "CreateMechSession failed to new MechSession!");
476 
477     *pMechSession = mechSession;
478     return CameraErrorCode::SUCCESS;
479     // LCOV_EXCL_STOP
480 }
481 
IsMechSupported()482 bool CameraManager::IsMechSupported()
483 {
484     // LCOV_EXCL_START
485     bool isMechSupported = false;
486     bool cacheResult = GetCameraDeviceAbilitySupportValue(CAMERA_ABILITY_SUPPORT_MECH, isMechSupported);
487     if (cacheResult) {
488         return isMechSupported;
489     }
490 
491     auto serviceProxy = GetServiceProxy();
492     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, false, "IsMechSupported serviceProxy is null");
493     int32_t retCode = serviceProxy->IsMechSupported(isMechSupported);
494     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, false, "IsMechSupported call failed, retCode: %{public}d",
495         retCode);
496     CacheCameraDeviceAbilitySupportValue(CAMERA_ABILITY_SUPPORT_MECH, isMechSupported);
497     return isMechSupported;
498     // LCOV_EXCL_STOP
499 }
500 
CreatePhotoOutput(sptr<IBufferProducer> & surface)501 sptr<PhotoOutput> CameraManager::CreatePhotoOutput(sptr<IBufferProducer> &surface)
502 {
503     CAMERA_SYNC_TRACE;
504     sptr<PhotoOutput> result = nullptr;
505     return result;
506 }
507 
CreatePhotoOutput(Profile & profile,sptr<IBufferProducer> & surfaceProducer)508 sptr<PhotoOutput> CameraManager::CreatePhotoOutput(Profile &profile, sptr<IBufferProducer> &surfaceProducer)
509 {
510     CAMERA_SYNC_TRACE;
511     sptr<PhotoOutput> photoOutput = nullptr;
512     int32_t retCode = CreatePhotoOutput(profile, surfaceProducer, &photoOutput);
513     CHECK_RETURN_RET_ELOG(retCode != CameraErrorCode::SUCCESS, nullptr,
514         "Failed to CreatePhotoOutput with error code:%{public}d", retCode);
515     return photoOutput;
516 }
517 
CreatePhotoOutputWithoutProfile(sptr<IBufferProducer> surfaceProducer,sptr<PhotoOutput> * pPhotoOutput)518 int CameraManager::CreatePhotoOutputWithoutProfile(sptr<IBufferProducer> surfaceProducer,
519                                                    sptr<PhotoOutput>* pPhotoOutput)
520 {
521     CAMERA_SYNC_TRACE;
522     auto serviceProxy = GetServiceProxy();
523     // LCOV_EXCL_START
524     CHECK_RETURN_RET_ELOG((serviceProxy == nullptr) || (surfaceProducer == nullptr), CameraErrorCode::INVALID_ARGUMENT,
525         "CreatePhotoOutputWithoutProfile serviceProxy is null or PhotoOutputSurface is null");
526     sptr<PhotoOutput> photoOutput = new (std::nothrow) PhotoOutput(surfaceProducer);
527     CHECK_RETURN_RET(photoOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
528     photoOutput->AddTag(CaptureOutput::DYNAMIC_PROFILE);
529     *pPhotoOutput = photoOutput;
530     return CameraErrorCode::SUCCESS;
531     // LCOV_EXCL_STOP
532 }
533 
CreatePhotoOutputWithoutProfile(sptr<IBufferProducer> surfaceProducer,sptr<PhotoOutput> * pPhotoOutput,sptr<Surface> photoSurface)534 int CameraManager::CreatePhotoOutputWithoutProfile(sptr<IBufferProducer> surfaceProducer,
535                                                    sptr<PhotoOutput>* pPhotoOutput, sptr<Surface> photoSurface)
536 {
537     // LCOV_EXCL_START
538     CAMERA_SYNC_TRACE;
539     auto serviceProxy = GetServiceProxy();
540     CHECK_RETURN_RET_ELOG((serviceProxy == nullptr) || (surfaceProducer == nullptr), CameraErrorCode::INVALID_ARGUMENT,
541         "CreatePhotoOutputWithoutProfile serviceProxy is null or PhotoOutputSurface is null");
542     sptr<PhotoOutput> photoOutput = new (std::nothrow) PhotoOutput(surfaceProducer, photoSurface);
543     CHECK_RETURN_RET(photoOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
544     photoOutput->AddTag(CaptureOutput::DYNAMIC_PROFILE);
545     *pPhotoOutput = photoOutput;
546     return CameraErrorCode::SUCCESS;
547     // LCOV_EXCL_STOP
548 }
549 
CreatePhotoOutputWithoutProfile(sptr<PhotoOutput> * pPhotoOutput)550 int CameraManager::CreatePhotoOutputWithoutProfile(sptr<PhotoOutput>* pPhotoOutput)
551 {
552     // LCOV_EXCL_START
553     CAMERA_SYNC_TRACE;
554     auto serviceProxy = GetServiceProxy();
555     CHECK_RETURN_RET_ELOG((serviceProxy == nullptr), CameraErrorCode::INVALID_ARGUMENT,
556         "CreatePhotoOutputWithoutProfile serviceProxy is null");
557     sptr<PhotoOutput> photoOutput = new (std::nothrow) PhotoOutput();
558     CHECK_RETURN_RET(photoOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
559     photoOutput->AddTag(CaptureOutput::DYNAMIC_PROFILE);
560     *pPhotoOutput = photoOutput;
561     return CameraErrorCode::SUCCESS;
562     // LCOV_EXCL_STOP
563 }
564 
CreatePhotoOutput(Profile & profile,sptr<IBufferProducer> & surfaceProducer,sptr<PhotoOutput> * pPhotoOutput)565 int CameraManager::CreatePhotoOutput(Profile &profile, sptr<IBufferProducer> &surfaceProducer,
566                                      sptr<PhotoOutput> *pPhotoOutput) __attribute__((no_sanitize("cfi")))
567 {
568     CAMERA_SYNC_TRACE;
569     auto serviceProxy = GetServiceProxy();
570     CHECK_RETURN_RET_ELOG((serviceProxy == nullptr) || (surfaceProducer == nullptr), CameraErrorCode::INVALID_ARGUMENT,
571         "CreatePhotoOutput serviceProxy is null or PhotoOutputSurface/profile is null");
572     CHECK_RETURN_RET_ELOG((profile.GetCameraFormat() == CAMERA_FORMAT_INVALID) || (profile.GetSize().width == 0)
573         || (profile.GetSize().height == 0), CameraErrorCode::INVALID_ARGUMENT,
574         "CreatePhotoOutput invalid fomrat or width or height is zero");
575     // to adapter yuv photo
576     CameraFormat yuvFormat = profile.GetCameraFormat();
577     camera_format_t metaFormat = GetCameraMetadataFormat(yuvFormat);
578     sptr<IStreamCapture> streamCapture = nullptr;
579     int32_t retCode = serviceProxy->CreatePhotoOutput(
580         surfaceProducer, metaFormat, profile.GetSize().width, profile.GetSize().height, streamCapture);
581     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
582         "Failed to get stream capture object from hcamera service!, %{public}d", retCode);
583     sptr<PhotoOutput> photoOutput = new(std::nothrow) PhotoOutput(surfaceProducer);
584     CHECK_RETURN_RET(photoOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
585     photoOutput->SetStream(streamCapture);
586     photoOutput->SetPhotoProfile(profile);
587     *pPhotoOutput = photoOutput;
588     return CameraErrorCode::SUCCESS;
589 }
590 
CreatePhotoOutput(Profile & profile,sptr<IBufferProducer> & surfaceProducer,sptr<PhotoOutput> * pPhotoOutput,sptr<Surface> photoSurface)591 int CameraManager::CreatePhotoOutput(Profile &profile, sptr<IBufferProducer> &surfaceProducer,
592                                      sptr<PhotoOutput> *pPhotoOutput, sptr<Surface> photoSurface)
593 {
594     // LCOV_EXCL_START
595     CAMERA_SYNC_TRACE;
596     auto serviceProxy = GetServiceProxy();
597     CHECK_RETURN_RET_ELOG((serviceProxy == nullptr) || (surfaceProducer == nullptr),
598         CameraErrorCode::INVALID_ARGUMENT,
599         "CreatePhotoOutput serviceProxy is null or PhotoOutputSurface/profile is null");
600     CHECK_RETURN_RET_ELOG((profile.GetCameraFormat() == CAMERA_FORMAT_INVALID) || (profile.GetSize().width == 0)
601         || (profile.GetSize().height == 0), CameraErrorCode::INVALID_ARGUMENT,
602         "CreatePhotoOutput invalid fomrat or width or height is zero");
603     // to adapter yuv photo
604     CameraFormat yuvFormat = profile.GetCameraFormat();
605     camera_format_t metaFormat = GetCameraMetadataFormat(yuvFormat);
606     sptr<IStreamCapture> streamCapture = nullptr;
607     int32_t retCode = serviceProxy->CreatePhotoOutput(
608         surfaceProducer, metaFormat, profile.GetSize().width, profile.GetSize().height, streamCapture);
609     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
610         "Failed to get stream capture object from hcamera service!, %{public}d", retCode);
611     sptr<PhotoOutput> photoOutput = new(std::nothrow) PhotoOutput(surfaceProducer, photoSurface);
612     CHECK_RETURN_RET(photoOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
613     photoOutput->SetStream(streamCapture);
614     photoOutput->SetPhotoProfile(profile);
615     *pPhotoOutput = photoOutput;
616     return CameraErrorCode::SUCCESS;
617     // LCOV_EXCL_STOP
618 }
619 
CreatePhotoOutput(Profile & profile,sptr<PhotoOutput> * pPhotoOutput)620 int CameraManager::CreatePhotoOutput(Profile& profile, sptr<PhotoOutput>* pPhotoOutput)
621 {
622     // LCOV_EXCL_START
623     CAMERA_SYNC_TRACE;
624     auto serviceProxy = GetServiceProxy();
625     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CameraErrorCode::INVALID_ARGUMENT,
626         "CreatePhotoOutput serviceProxy is null or PhotoOutputSurface/profile is null");
627     CHECK_RETURN_RET_ELOG((profile.GetCameraFormat() == CAMERA_FORMAT_INVALID) || (profile.GetSize().width == 0)
628         || (profile.GetSize().height == 0), CameraErrorCode::INVALID_ARGUMENT,
629         "CreatePhotoOutput invalid fomrat or width or height is zero");
630     // to adapter yuv photo
631     CameraFormat yuvFormat = profile.GetCameraFormat();
632     camera_format_t metaFormat = GetCameraMetadataFormat(yuvFormat);
633     sptr<IStreamCapture> streamCapture = nullptr;
634     int32_t retCode =
635         serviceProxy->CreatePhotoOutput(metaFormat, profile.GetSize().width, profile.GetSize().height, streamCapture);
636     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
637         "Failed to get stream capture object from hcamera service!, %{public}d", retCode);
638     sptr<PhotoOutput> photoOutput = new(std::nothrow) PhotoOutput();
639     CHECK_RETURN_RET(photoOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
640     photoOutput->SetStream(streamCapture);
641     photoOutput->SetPhotoProfile(profile);
642     *pPhotoOutput = photoOutput;
643     return CameraErrorCode::SUCCESS;
644     // LCOV_EXCL_STOP
645 }
646 
CreatePreviewOutput(Profile & profile,sptr<Surface> surface)647 sptr<PreviewOutput> CameraManager::CreatePreviewOutput(Profile &profile, sptr<Surface> surface)
648 {
649     CAMERA_SYNC_TRACE;
650     sptr<PreviewOutput> previewOutput = nullptr;
651     int32_t retCode = CreatePreviewOutput(profile, surface, &previewOutput);
652     CHECK_RETURN_RET_ELOG(retCode != CameraErrorCode::SUCCESS, nullptr,
653         "Failed to CreatePreviewOutput with error code:%{public}d", retCode);
654 
655     return previewOutput;
656 }
657 
CreatePreviewOutputWithoutProfile(sptr<Surface> surface,sptr<PreviewOutput> * pPreviewOutput)658 int CameraManager::CreatePreviewOutputWithoutProfile(sptr<Surface> surface, sptr<PreviewOutput>* pPreviewOutput)
659 {
660     CAMERA_SYNC_TRACE;
661     sptr<PreviewOutput> previewOutput = nullptr;
662     auto serviceProxy = GetServiceProxy();
663     // LCOV_EXCL_START
664     CHECK_RETURN_RET_ELOG((serviceProxy == nullptr) || (surface == nullptr), CameraErrorCode::INVALID_ARGUMENT,
665         "CreatePreviewOutputWithoutProfile serviceProxy is null or surface is null");
666     previewOutput = new (std::nothrow) PreviewOutput(surface->GetProducer());
667     CHECK_RETURN_RET(previewOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
668     previewOutput->AddTag(CaptureOutput::DYNAMIC_PROFILE);
669     *pPreviewOutput = previewOutput;
670     return CAMERA_OK;
671     // LCOV_EXCL_STOP
672 }
673 
CreatePreviewOutput(Profile & profile,sptr<Surface> surface,sptr<PreviewOutput> * pPreviewOutput)674 int CameraManager::CreatePreviewOutput(Profile &profile, sptr<Surface> surface, sptr<PreviewOutput> *pPreviewOutput)
675 {
676     CAMERA_SYNC_TRACE;
677     auto serviceProxy = GetServiceProxy();
678     CHECK_RETURN_RET_ELOG((serviceProxy == nullptr) || (surface == nullptr), CameraErrorCode::INVALID_ARGUMENT,
679         "CreatePreviewOutput serviceProxy is null or previewOutputSurface/profile is null");
680     CHECK_RETURN_RET_ELOG((profile.GetCameraFormat() == CAMERA_FORMAT_INVALID) || (profile.GetSize().width == 0)
681         || (profile.GetSize().height == 0), CameraErrorCode::INVALID_ARGUMENT,
682         "CreatePreviewOutput invalid fomrat or width or height is zero");
683 
684     camera_format_t metaFormat = GetCameraMetadataFormat(profile.GetCameraFormat());
685     sptr<IStreamRepeat> streamRepeat = nullptr;
686     int32_t retCode = serviceProxy->CreatePreviewOutput(
687         surface->GetProducer(), metaFormat, profile.GetSize().width, profile.GetSize().height, streamRepeat);
688     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
689         "Failed to get stream repeat object from hcamera service! %{public}d", retCode);
690     sptr<PreviewOutput> previewOutput = new (std::nothrow) PreviewOutput(surface->GetProducer());
691     CHECK_RETURN_RET(previewOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
692     previewOutput->SetStream(streamRepeat);
693     previewOutput->SetOutputFormat(profile.GetCameraFormat());
694     previewOutput->SetSize(profile.GetSize());
695     previewOutput->SetPreviewProfile(profile);
696     *pPreviewOutput = previewOutput;
697     bool resolutionCondition = profile.GetSize().height <= CONTROL_CENTER_RESOLUTION_HEIGHT_MAX
698         && profile.GetSize().width <= CONTROL_CENTER_RESOLUTION_WIDTH_MAX;
699     SetControlCenterResolutionCondition(resolutionCondition);
700     return CameraErrorCode::SUCCESS;
701 }
702 
CreatePreviewOutputStream(sptr<IStreamRepeat> & streamPtr,Profile & profile,const sptr<OHOS::IBufferProducer> & producer)703 int32_t CameraManager::CreatePreviewOutputStream(
704     sptr<IStreamRepeat>& streamPtr, Profile& profile, const sptr<OHOS::IBufferProducer>& producer)
705 {
706     auto validResult = ValidCreateOutputStream(profile, producer);
707     // LCOV_EXCL_START
708     CHECK_RETURN_RET_ELOG(validResult != SUCCESS, validResult,
709         "CameraManager::CreatePreviewOutputStream ValidCreateOutputStream fail:%{public}d", validResult);
710 
711     auto serviceProxy = GetServiceProxy();
712     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
713         "CameraManager::CreatePreviewOutputStream serviceProxy is null");
714     camera_format_t metaFormat = GetCameraMetadataFormat(profile.GetCameraFormat());
715     int32_t retCode = serviceProxy->CreatePreviewOutput(
716         producer, metaFormat, profile.GetSize().width, profile.GetSize().height, streamPtr);
717     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
718         "CreatePreviewOutputStream Failed to get stream repeat object from hcamera service! %{public}d", retCode);
719     return CameraErrorCode::SUCCESS;
720     // LCOV_EXCL_STOP
721 }
722 
CreatePhotoOutputStream(sptr<IStreamCapture> & streamPtr,Profile & profile,const sptr<OHOS::IBufferProducer> & producer)723 int32_t CameraManager::CreatePhotoOutputStream(
724     sptr<IStreamCapture>& streamPtr, Profile& profile, const sptr<OHOS::IBufferProducer>& producer)
725 {
726     // LCOV_EXCL_START
727     auto validResult = ValidCreateOutputStream(profile, producer);
728     CHECK_RETURN_RET_ELOG(validResult != SUCCESS, validResult,
729         "CameraManager::CreatePhotoOutputStream ValidCreateOutputStream fail:%{public}d", validResult);
730     auto serviceProxy = GetServiceProxy();
731     CHECK_RETURN_RET_ELOG((serviceProxy == nullptr) || (producer == nullptr), CameraErrorCode::INVALID_ARGUMENT,
732         "CameraManager::CreatePhotoOutputStream serviceProxy is null or producer is null");
733 
734     CameraFormat yuvFormat = profile.GetCameraFormat();
735     auto metaFormat = GetCameraMetadataFormat(yuvFormat);
736     auto retCode = serviceProxy->CreatePhotoOutput(
737         producer, metaFormat, profile.GetSize().width, profile.GetSize().height, streamPtr);
738     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
739         "CameraManager::CreatePhotoOutputStream Failed to get stream capture object from hcamera service! "
740         "%{public}d", retCode);
741     return CameraErrorCode::SUCCESS;
742     // LCOV_EXCL_STOP
743 }
744 
CreatePhotoOutputStream(sptr<IStreamCapture> & streamPtr,Profile & profile)745 int32_t CameraManager::CreatePhotoOutputStream(
746     sptr<IStreamCapture>& streamPtr, Profile& profile)
747 {
748     // LCOV_EXCL_START
749     auto serviceProxy = GetServiceProxy();
750     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CameraErrorCode::INVALID_ARGUMENT,
751         "CameraManager::CreatePhotoOutputStream serviceProxy is null or producer is null");
752     CameraFormat yuvFormat = profile.GetCameraFormat();
753     auto metaFormat = GetCameraMetadataFormat(yuvFormat);
754     auto retCode =
755         serviceProxy->CreatePhotoOutput(metaFormat, profile.GetSize().width, profile.GetSize().height, streamPtr);
756     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
757         "CameraManager::CreatePhotoOutputStream Failed to get stream capture object from hcamera service! "
758         "%{public}d", retCode);
759     return CameraErrorCode::SUCCESS;
760     // LCOV_EXCL_STOP
761 }
762 
ValidCreateOutputStream(Profile & profile,const sptr<OHOS::IBufferProducer> & producer)763 int32_t CameraManager::ValidCreateOutputStream(Profile& profile, const sptr<OHOS::IBufferProducer>& producer)
764 {
765     // LCOV_EXCL_START
766     CHECK_RETURN_RET_ELOG(producer == nullptr, CameraErrorCode::INVALID_ARGUMENT,
767         "CameraManager::ValidCreateOutputStream producer is null");
768     CHECK_RETURN_RET_ELOG((profile.GetCameraFormat() == CAMERA_FORMAT_INVALID) || (profile.GetSize().width == 0)
769         || (profile.GetSize().height == 0), CameraErrorCode::INVALID_ARGUMENT,
770         "CameraManager::ValidCreateOutputStream width or height is zero");
771     return CameraErrorCode::SUCCESS;
772     // LCOV_EXCL_STOP
773 }
774 
CreateDeferredPreviewOutput(Profile & profile)775 sptr<PreviewOutput> CameraManager::CreateDeferredPreviewOutput(Profile &profile)
776 {
777     // LCOV_EXCL_START
778     CAMERA_SYNC_TRACE;
779     MEDIA_INFO_LOG("CameraManager::CreateDeferredPreviewOutput called");
780     sptr<PreviewOutput> previewOutput = nullptr;
781     int32_t retCode = CreateDeferredPreviewOutput(profile, &previewOutput);
782     CHECK_RETURN_RET_ELOG(retCode != CameraErrorCode::SUCCESS, nullptr,
783         "CameraManager Failed to CreateDeferredPreviewOutput with error code:%{public}d", retCode);
784     return previewOutput;
785     // LCOV_EXCL_STOP
786 }
787 
CreateDeferredPreviewOutput(Profile & profile,sptr<PreviewOutput> * pPreviewOutput)788 int CameraManager::CreateDeferredPreviewOutput(Profile &profile, sptr<PreviewOutput> *pPreviewOutput)
789 {
790     // LCOV_EXCL_START
791     CAMERA_SYNC_TRACE;
792     auto serviceProxy = GetServiceProxy();
793     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CameraErrorCode::INVALID_ARGUMENT,
794         "CameraManager::CreateDeferredPreviewOutput serviceProxy is null");
795     CHECK_RETURN_RET_ELOG((profile.GetCameraFormat() == CAMERA_FORMAT_INVALID) || (profile.GetSize().width == 0)
796         || (profile.GetSize().height == 0), CameraErrorCode::INVALID_ARGUMENT,
797         "CreateDeferredPreviewOutput invalid fomrat or width or height is zero");
798 
799     camera_format_t metaFormat = GetCameraMetadataFormat(profile.GetCameraFormat());
800     sptr<IStreamRepeat> streamRepeat = nullptr;
801     int32_t retCode = serviceProxy->CreateDeferredPreviewOutput(
802         metaFormat, profile.GetSize().width, profile.GetSize().height, streamRepeat);
803     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
804         "CreateDeferredPreviewOutput Failed to get stream repeat object from hcamera service!, %{public}d", retCode);
805     sptr<PreviewOutput> previewOutput = new(std::nothrow) PreviewOutput();
806     CHECK_RETURN_RET(previewOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
807     previewOutput->SetStream(streamRepeat);
808     previewOutput->SetPreviewProfile(profile);
809     *pPreviewOutput = previewOutput;
810     bool resolutionCondition = profile.GetSize().height <= CONTROL_CENTER_RESOLUTION_HEIGHT_MAX
811         && profile.GetSize().width <= CONTROL_CENTER_RESOLUTION_WIDTH_MAX;
812     SetControlCenterResolutionCondition(resolutionCondition);
813     return CameraErrorCode::SUCCESS;
814     // LCOV_EXCL_STOP
815 }
816 
CreatePreviewOutput(const sptr<OHOS::IBufferProducer> & producer,int32_t format)817 sptr<PreviewOutput> CameraManager::CreatePreviewOutput(const sptr<OHOS::IBufferProducer> &producer, int32_t format)
818 {
819     CAMERA_SYNC_TRACE;
820     sptr<PreviewOutput> result = nullptr;
821     return result;
822 }
823 
CreateCustomPreviewOutput(sptr<Surface> surface,int32_t width,int32_t height)824 sptr<PreviewOutput> CameraManager::CreateCustomPreviewOutput(sptr<Surface> surface, int32_t width, int32_t height)
825 {
826     CAMERA_SYNC_TRACE;
827     sptr<PreviewOutput> result = nullptr;
828     return result;
829 }
830 
CreateMetadataOutput()831 sptr<MetadataOutput> CameraManager::CreateMetadataOutput()
832 {
833     CAMERA_SYNC_TRACE;
834     sptr<MetadataOutput> metadataOutput = nullptr;
835     int32_t retCode = CreateMetadataOutput(metadataOutput);
836     CHECK_RETURN_RET_ELOG(retCode != CameraErrorCode::SUCCESS, nullptr,
837         "CameraManager Failed to CreateMetadataOutput with error code:%{public}d", retCode);
838     return metadataOutput;
839 }
840 
CreateMetadataOutput(sptr<MetadataOutput> & pMetadataOutput)841 int CameraManager::CreateMetadataOutput(sptr<MetadataOutput>& pMetadataOutput)
842 {
843     return CreateMetadataOutputInternal(pMetadataOutput);
844 }
845 
CreateMetadataOutput(sptr<MetadataOutput> & pMetadataOutput,std::vector<MetadataObjectType> metadataObjectTypes)846 int CameraManager::CreateMetadataOutput(sptr<MetadataOutput>& pMetadataOutput,
847     std::vector<MetadataObjectType> metadataObjectTypes)
848 {
849     return CreateMetadataOutputInternal(pMetadataOutput, metadataObjectTypes);
850 }
851 
GetStreamDepthDataFromService(DepthProfile & depthProfile,sptr<IBufferProducer> & surface,sptr<IStreamDepthData> & streamDepthData)852 int CameraManager::GetStreamDepthDataFromService(DepthProfile& depthProfile, sptr<IBufferProducer> &surface,
853     sptr<IStreamDepthData>& streamDepthData)
854 {
855     sptr<IStreamDepthData> streamDepthDataTmp = nullptr;
856     int32_t retCode = CAMERA_OK;
857     camera_format_t metaFormat;
858 
859     auto serviceProxy = GetServiceProxy();
860     // LCOV_EXCL_START
861     CHECK_RETURN_RET_ELOG((serviceProxy == nullptr) || (surface == nullptr), CameraErrorCode::INVALID_ARGUMENT,
862         "serviceProxy is null or DepthDataOutputSurface/profile is null");
863 
864     if ((depthProfile.GetCameraFormat() == CAMERA_FORMAT_INVALID) ||
865         (depthProfile.GetSize().width == 0) ||
866         (depthProfile.GetSize().height == 0)) {
867         MEDIA_ERR_LOG("invalid fomrat or width or height is zero");
868         return CameraErrorCode::INVALID_ARGUMENT;
869     }
870 
871     metaFormat = GetCameraMetadataFormat(depthProfile.GetCameraFormat());
872     retCode = serviceProxy->CreateDepthDataOutput(
873         surface, metaFormat, depthProfile.GetSize().width, depthProfile.GetSize().height, streamDepthDataTmp);
874     if (retCode == CAMERA_OK) {
875         streamDepthData = streamDepthDataTmp;
876         return CameraErrorCode::SUCCESS;
877     } else {
878         MEDIA_ERR_LOG("Failed to get stream depth data object from hcamera service!, %{public}d", retCode);
879         return ServiceToCameraError(retCode);
880     }
881     // LCOV_EXCL_STOP
882 }
883 
CreateVideoOutput(sptr<Surface> & surface)884 sptr<VideoOutput> CameraManager::CreateVideoOutput(sptr<Surface> &surface)
885 {
886     CAMERA_SYNC_TRACE;
887     sptr<VideoOutput> result = nullptr;
888     return result;
889 }
890 
CreateVideoOutput(VideoProfile & profile,sptr<Surface> & surface)891 sptr<VideoOutput> CameraManager::CreateVideoOutput(VideoProfile &profile, sptr<Surface> &surface)
892 {
893     CAMERA_SYNC_TRACE;
894     sptr<VideoOutput> videoOutput = nullptr;
895     int32_t retCode = CreateVideoOutput(profile, surface, &videoOutput);
896     CHECK_RETURN_RET_ELOG(retCode != CameraErrorCode::SUCCESS, nullptr,
897         "CreateVideoOutput Failed to CreateVideoOutput with error code:%{public}d", retCode);
898     return videoOutput;
899 }
900 
CreateVideoOutputStream(sptr<IStreamRepeat> & streamPtr,Profile & profile,const sptr<OHOS::IBufferProducer> & producer)901 int32_t CameraManager::CreateVideoOutputStream(
902     sptr<IStreamRepeat>& streamPtr, Profile& profile, const sptr<OHOS::IBufferProducer>& producer)
903 {
904     auto validResult = ValidCreateOutputStream(profile, producer);
905     // LCOV_EXCL_START
906     CHECK_RETURN_RET_ELOG(validResult != SUCCESS, validResult,
907         "CameraManager::CreateVideoOutputStream ValidCreateOutputStream fail:%{public}d", validResult);
908 
909     auto serviceProxy = GetServiceProxy();
910     CHECK_RETURN_RET_ELOG((serviceProxy == nullptr) || (producer == nullptr), CameraErrorCode::INVALID_ARGUMENT,
911         "CameraManager::CreateVideoOutputStream serviceProxy is null or producer is null");
912 
913     auto metaFormat = GetCameraMetadataFormat(profile.GetCameraFormat());
914     MEDIA_DEBUG_LOG("metaFormat = %{public}d", static_cast<int32_t>(metaFormat));
915     int32_t retCode = serviceProxy->CreateVideoOutput(
916         producer, metaFormat, profile.GetSize().width, profile.GetSize().height, streamPtr);
917     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
918         "CameraManager::CreateVideoOutputStream Failed to get stream capture object from hcamera service! "
919         "%{public}d", retCode);
920     return CameraErrorCode::SUCCESS;
921     // LCOV_EXCL_STOP
922 }
923 
CreateVideoOutputWithoutProfile(sptr<Surface> surface,sptr<VideoOutput> * pVideoOutput)924 int CameraManager::CreateVideoOutputWithoutProfile(sptr<Surface> surface, sptr<VideoOutput>* pVideoOutput)
925 {
926     CAMERA_SYNC_TRACE;
927     auto serviceProxy = GetServiceProxy();
928     // LCOV_EXCL_START
929     CHECK_RETURN_RET_ELOG((serviceProxy == nullptr) || (surface == nullptr), CameraErrorCode::INVALID_ARGUMENT,
930         "CameraManager::CreateVideoOutput serviceProxy is null or VideoOutputSurface is null");
931 
932     sptr<VideoOutput> videoOutput = new (std::nothrow) VideoOutput(surface->GetProducer());
933     CHECK_RETURN_RET(videoOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
934     videoOutput->AddTag(CaptureOutput::DYNAMIC_PROFILE);
935     *pVideoOutput = videoOutput;
936     return CameraErrorCode::SUCCESS;
937     // LCOV_EXCL_STOP
938 }
939 
CreateVideoOutput(VideoProfile & profile,sptr<Surface> & surface,sptr<VideoOutput> * pVideoOutput)940 int CameraManager::CreateVideoOutput(VideoProfile &profile, sptr<Surface> &surface, sptr<VideoOutput> *pVideoOutput)
941 {
942     CAMERA_SYNC_TRACE;
943     auto serviceProxy = GetServiceProxy();
944     CHECK_RETURN_RET_ELOG((serviceProxy == nullptr) || (surface == nullptr), CameraErrorCode::INVALID_ARGUMENT,
945         "CameraManager::CreateVideoOutput serviceProxy is null or VideoOutputSurface/profile is null");
946     CHECK_RETURN_RET_ELOG((profile.GetCameraFormat() == CAMERA_FORMAT_INVALID) || (profile.GetSize().width == 0)
947         || (profile.GetSize().height == 0), CameraErrorCode::INVALID_ARGUMENT,
948         "CreateVideoOutput invalid format or width or height is zero");
949 
950     camera_format_t metaFormat = GetCameraMetadataFormat(profile.GetCameraFormat());
951     auto [width, height] = profile.GetSize();
952     auto frames = profile.GetFrameRates();
953     bool isExistFrames = frames.size() >= 2;
954     if (isExistFrames) {
955         MEDIA_INFO_LOG("CameraManager::CreateVideoOutput, format: %{public}d, width: %{public}d, height: %{public}d, "
956                        "frameRateMin: %{public}d, frameRateMax: %{public}d, surfaceId: %{public}" PRIu64,
957             static_cast<int32_t>(metaFormat), width, height, frames[0], frames[1], surface->GetUniqueId());
958     } else {
959         MEDIA_INFO_LOG("CameraManager::CreateVideoOutput, format: %{public}d, width: %{public}d, height: %{public}d, "
960                        "surfaceId: %{public}" PRIu64,
961             static_cast<int32_t>(metaFormat), width, height, surface->GetUniqueId());
962     }
963     sptr<IStreamRepeat> streamRepeat = nullptr;
964     int32_t retCode = serviceProxy->CreateVideoOutput(
965         surface->GetProducer(), metaFormat, profile.GetSize().width, profile.GetSize().height, streamRepeat);
966     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
967         "CameraManager::CreateVideoOutput Failed to get stream capture object from hcamera service! "
968         "%{public}d", retCode);
969     sptr<VideoOutput> videoOutput = new(std::nothrow) VideoOutput(surface->GetProducer());
970     CHECK_RETURN_RET(videoOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
971     videoOutput->SetStream(streamRepeat);
972     videoOutput->SetOutputFormat(profile.GetCameraFormat());
973     videoOutput->SetSize(profile.GetSize());
974     videoOutput->SetVideoProfile(profile);
975     *pVideoOutput = videoOutput;
976 
977     return CameraErrorCode::SUCCESS;
978 }
979 
InitCameraManager()980 void CameraManager::InitCameraManager()
981 {
982     CAMERA_SYNC_TRACE;
983     int32_t retCode = SubscribeSystemAbility();
984     CHECK_RETURN_ELOG(retCode != CameraErrorCode::SUCCESS, "failed to SubscribeSystemAbilityd");
985     retCode = RefreshServiceProxy();
986     CHECK_RETURN_ELOG(retCode != CameraErrorCode::SUCCESS, "RefreshServiceProxy fail , ret = %{public}d",
987         retCode);
988     retCode = AddServiceProxyDeathRecipient();
989     CHECK_RETURN_ELOG(retCode != CameraErrorCode::SUCCESS, "AddServiceProxyDeathRecipient fail ,"
990         "ret = %{public}d", retCode);
991     retCode = CreateListenerObject();
992     CHECK_RETURN_ELOG(retCode != CAMERA_OK, "failed to new CameraListenerStub, ret = %{public}d", retCode);
993     foldScreenType_ = system::GetParameter("const.window.foldscreen.type", "");
994     isSystemApp_ = CameraSecurity::CheckSystemApp();
995     CheckWhiteList();
996     bundleName_ = system::GetParameter("const.camera.folded_lens_change", "default");
997     curBundleName_ = GetBundleName();
998     MEDIA_DEBUG_LOG("IsSystemApp = %{public}d", isSystemApp_);
999 }
1000 
GetBundleName()1001 std::string CameraManager::GetBundleName()
1002 {
1003     auto bundleName = "";
1004     OHOS::sptr<OHOS::ISystemAbilityManager> samgr =
1005             OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1006     CHECK_RETURN_RET_ELOG(samgr == nullptr, bundleName, "GetClientBundle Get ability manager failed");
1007     OHOS::sptr<OHOS::IRemoteObject> remoteObject =
1008             samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
1009     CHECK_RETURN_RET_ELOG(remoteObject == nullptr, bundleName, "GetClientBundle object is NULL.");
1010     sptr<AppExecFwk::IBundleMgr> bms = OHOS::iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
1011     CHECK_RETURN_RET_ELOG(bms == nullptr, bundleName, "GetClientBundle bundle manager service is NULL.");
1012     AppExecFwk::BundleInfo bundleInfo;
1013     auto ret = bms->GetBundleInfoForSelf(0, bundleInfo);
1014     CHECK_RETURN_RET_ELOG(ret != ERR_OK, bundleName, "GetBundleInfoForSelf failed.");
1015     bundleName = bundleInfo.name.c_str();
1016     MEDIA_INFO_LOG("bundleName: [%{private}s]", bundleName);
1017     return bundleName;
1018 }
1019 
RefreshServiceProxy()1020 int32_t CameraManager::RefreshServiceProxy()
1021 {
1022     sptr<IRemoteObject> object = nullptr;
1023     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1024     CHECK_RETURN_RET_ELOG(samgr == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
1025         "CameraManager::RefreshServiceProxy Failed to get System ability manager");
1026     object = samgr->CheckSystemAbility(CAMERA_SERVICE_ID);
1027     CHECK_RETURN_RET_ELOG(object == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
1028         "CameraManager::RefreshServiceProxy Init CheckSystemAbility %{public}d is null", CAMERA_SERVICE_ID);
1029     auto serviceProxy = iface_cast<ICameraService>(object);
1030     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
1031         "CameraManager::RefreshServiceProxy serviceProxy is null");
1032     SetServiceProxy(serviceProxy);
1033     return CameraErrorCode::SUCCESS;
1034 }
1035 
SubscribeSystemAbility()1036 int32_t CameraManager::SubscribeSystemAbility()
1037 {
1038     MEDIA_INFO_LOG("Enter Into CameraManager::SubscribeSystemAbility");
1039     // LCOV_EXCL_START
1040     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1041     CHECK_RETURN_RET_ELOG(samgr == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
1042         "CameraManager::SubscribeSystemAbility Failed to get System ability manager");
1043     {
1044         std::lock_guard<std::mutex> lock(saListenerMuxtex_);
1045         if (saListener_ == nullptr) {
1046             auto listener = new(std::nothrow) CameraServiceSystemAbilityListener();
1047             saListener_ = listener;
1048             CHECK_RETURN_RET_ELOG(saListener_ == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
1049                 "CameraManager::SubscribeSystemAbility saListener_ is null");
1050             int32_t ret = samgr->SubscribeSystemAbility(CAMERA_SERVICE_ID, listener);
1051             MEDIA_INFO_LOG("SubscribeSystemAbility ret = %{public}d", ret);
1052             return ret == 0 ? CameraErrorCode::SUCCESS : CameraErrorCode::SERVICE_FATL_ERROR;
1053         }
1054     }
1055     return CameraErrorCode::SUCCESS;
1056     // LCOV_EXCL_STOP
1057 }
1058 
UnSubscribeSystemAbility()1059 int32_t CameraManager::UnSubscribeSystemAbility()
1060 {
1061     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1062     CHECK_RETURN_RET_ELOG(samgr == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
1063         "CameraManager::UnSubscribeSystemAbility Failed to get System ability manager");
1064     CHECK_RETURN_RET(saListener_ == nullptr, CameraErrorCode::SUCCESS);
1065     sptr<ISystemAbilityStatusChange> listener = static_cast<ISystemAbilityStatusChange*>(saListener_.GetRefPtr());
1066     int32_t ret = samgr->UnSubscribeSystemAbility(CAMERA_SERVICE_ID, listener);
1067     MEDIA_INFO_LOG("UnSubscribeSystemAbility ret = %{public}d", ret);
1068     saListener_ = nullptr;
1069     return ret == 0 ? CameraErrorCode::SUCCESS : CameraErrorCode::SERVICE_FATL_ERROR;
1070 }
1071 
OnCameraServerAlive()1072 void CameraManager::OnCameraServerAlive()
1073 {
1074     int32_t ret = RefreshServiceProxy();
1075     CHECK_RETURN_ELOG(ret != CameraErrorCode::SUCCESS, "RefreshServiceProxy fail , ret = %{public}d", ret);
1076     AddServiceProxyDeathRecipient();
1077     if (cameraStatusListenerManager_->GetListenerCount() > 0) {
1078         sptr<ICameraServiceCallback> callback = cameraStatusListenerManager_;
1079         SetCameraServiceCallback(callback);
1080     }
1081     if (cameraMuteListenerManager_->GetListenerCount() > 0) {
1082         sptr<ICameraMuteServiceCallback> callback = cameraMuteListenerManager_;
1083         SetCameraMuteServiceCallback(callback);
1084     }
1085     if (torchServiceListenerManager_->GetListenerCount() > 0) {
1086         sptr<ITorchServiceCallback> callback = torchServiceListenerManager_;
1087         SetTorchServiceCallback(callback);
1088     }
1089     if (foldStatusListenerManager_->GetListenerCount() > 0) {
1090         sptr<IFoldServiceCallback> callback = foldStatusListenerManager_;
1091         SetFoldServiceCallback(callback);
1092     }
1093 }
1094 
DestroyStubObj()1095 int32_t CameraManager::DestroyStubObj()
1096 {
1097     MEDIA_INFO_LOG("Enter Into CameraManager::DestroyStubObj");
1098     UnSubscribeSystemAbility();
1099     int32_t retCode = CAMERA_UNKNOWN_ERROR;
1100     auto serviceProxy = GetServiceProxy();
1101     // LCOV_EXCL_START
1102     if (serviceProxy == nullptr) {
1103         MEDIA_ERR_LOG("serviceProxy is null");
1104     } else {
1105         retCode = serviceProxy->DestroyStubObj();
1106         CHECK_PRINT_ELOG(retCode != CAMERA_OK, "Failed to DestroyStubObj, retCode: %{public}d", retCode);
1107     }
1108     // LCOV_EXCL_STOP
1109     return ServiceToCameraError(retCode);
1110 }
1111 
CameraServerDied(pid_t pid)1112 void CameraManager::CameraServerDied(pid_t pid)
1113 {
1114     MEDIA_ERR_LOG("camera server has died, pid:%{public}d!", pid);
1115     RemoveServiceProxyDeathRecipient();
1116     SetServiceProxy(nullptr);
1117     auto cameraDeviceList = GetCameraDeviceList();
1118     // LCOV_EXCL_START
1119     for (size_t i = 0; i < cameraDeviceList.size(); i++) {
1120         CameraStatusInfo cameraStatusInfo;
1121         cameraStatusInfo.cameraDevice = cameraDeviceList[i];
1122         cameraStatusInfo.cameraStatus = CAMERA_SERVER_UNAVAILABLE;
1123         cameraStatusListenerManager_->TriggerListener(
1124             [&](auto listener) { listener->OnCameraStatusChanged(cameraStatusInfo); });
1125     }
1126     // LCOV_EXCL_STOP
1127 }
1128 
AddServiceProxyDeathRecipient()1129 int32_t CameraManager::AddServiceProxyDeathRecipient()
1130 {
1131     std::lock_guard<std::mutex> lock(deathRecipientMutex_);
1132     auto serviceProxy = GetServiceProxy();
1133     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
1134         "CameraManager::AddServiceProxyDeathRecipient serviceProxy is null");
1135     auto remoteObj = serviceProxy->AsObject();
1136     if (deathRecipient_ != nullptr) {
1137         MEDIA_INFO_LOG("CameraManager::AddServiceProxyDeathRecipient remove last deathRecipient");
1138         remoteObj->RemoveDeathRecipient(deathRecipient_);
1139     }
1140     pid_t pid = 0;
1141     deathRecipient_ = new (std::nothrow) CameraDeathRecipient(pid);
1142     CHECK_RETURN_RET_ELOG(deathRecipient_ == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
1143         "CameraManager::AddServiceProxyDeathRecipient failed to new CameraDeathRecipient");
1144     auto thisPtr = wptr<CameraManager>(this);
1145     deathRecipient_->SetNotifyCb([thisPtr](pid_t pid) {
1146         auto cameraManagerPtr = thisPtr.promote();
1147         if (cameraManagerPtr != nullptr) {
1148             cameraManagerPtr->CameraServerDied(pid);
1149         }
1150     });
1151 
1152     bool result = remoteObj->AddDeathRecipient(deathRecipient_);
1153     CHECK_RETURN_RET_ELOG(!result, CameraErrorCode::SERVICE_FATL_ERROR,
1154         "CameraManager::AddServiceProxyDeathRecipient failed to add deathRecipient");
1155     return CameraErrorCode::SUCCESS;
1156 }
1157 
RemoveServiceProxyDeathRecipient()1158 void CameraManager::RemoveServiceProxyDeathRecipient()
1159 {
1160     std::lock_guard<std::mutex> lock(deathRecipientMutex_);
1161     auto serviceProxy = GetServiceProxy();
1162     CHECK_EXECUTE(serviceProxy != nullptr, (void)serviceProxy->AsObject()->RemoveDeathRecipient(deathRecipient_));
1163     deathRecipient_ = nullptr;
1164 }
1165 
CreateCameraDevice(std::string cameraId,sptr<ICameraDeviceService> * pICameraDeviceService)1166 int CameraManager::CreateCameraDevice(std::string cameraId, sptr<ICameraDeviceService> *pICameraDeviceService)
1167 {
1168     CAMERA_SYNC_TRACE;
1169     auto serviceProxy = GetServiceProxy();
1170     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr || cameraId.empty(), CameraErrorCode::INVALID_ARGUMENT,
1171         "CameraManager::CreateCameraDevice serviceProxy is null or CameraID is empty: %{public}s", cameraId.c_str());
1172     sptr<ICameraDeviceService> device = nullptr;
1173     int32_t retCode = serviceProxy->CreateCameraDevice(cameraId, device);
1174     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK,
1175         retCode == CAMERA_NO_PERMISSION ? CAMERA_NO_PERMISSION: ServiceToCameraError(retCode),
1176         "CameraManager::CreateCameraDevice Failed to create camera device from hcamera service! %{public}d", retCode);
1177     *pICameraDeviceService = device;
1178     return CameraErrorCode::SUCCESS;
1179 }
1180 
SetCallback(std::shared_ptr<CameraManagerCallback> listener)1181 void CameraManager::SetCallback(std::shared_ptr<CameraManagerCallback> listener)
1182 {
1183     RegisterCameraStatusCallback(listener);
1184 }
1185 
RegisterCameraStatusCallback(shared_ptr<CameraManagerCallback> listener)1186 void CameraManager::RegisterCameraStatusCallback(shared_ptr<CameraManagerCallback> listener)
1187 {
1188     CHECK_RETURN(listener == nullptr);
1189     bool isSuccess = cameraStatusListenerManager_->AddListener(listener);
1190     CHECK_RETURN(!isSuccess);
1191 
1192     // First register, set callback to service, service trigger callback.
1193     if (cameraStatusListenerManager_->GetListenerCount() == 1) {
1194         sptr<ICameraServiceCallback> callback = cameraStatusListenerManager_;
1195         SetCameraServiceCallback(callback);
1196         return;
1197     }
1198 
1199     // LCOV_EXCL_START
1200     // Non-First register, async callback by cache data.
1201     auto cachedStatus = cameraStatusListenerManager_->GetCachedCameraStatus();
1202     auto cachedFlashStatus = cameraStatusListenerManager_->GetCachedFlashStatus();
1203     cameraStatusListenerManager_->TriggerTargetListenerAsync(
1204         listener, [cachedStatus, cachedFlashStatus](auto listener) {
1205             MEDIA_INFO_LOG("CameraManager::RegisterCameraStatusCallback async trigger status");
1206             for (auto& status : cachedStatus) {
1207                 if (status == nullptr) {
1208                     continue;
1209                 }
1210                 listener->OnCameraStatusChanged(*status);
1211             }
1212             for (auto& status : cachedFlashStatus) {
1213                 listener->OnFlashlightStatusChanged(status.first, status.second);
1214             }
1215         });
1216     // LCOV_EXCL_STOP
1217 }
1218 
UnregisterCameraStatusCallback(std::shared_ptr<CameraManagerCallback> listener)1219 void CameraManager::UnregisterCameraStatusCallback(std::shared_ptr<CameraManagerCallback> listener)
1220 {
1221     // LCOV_EXCL_START
1222     CHECK_RETURN(listener == nullptr);
1223     cameraStatusListenerManager_->RemoveListener(listener);
1224     if (cameraStatusListenerManager_->GetListenerCount() == 0) {
1225         UnSetCameraServiceCallback();
1226     }
1227     // LCOV_EXCL_STOP
1228 }
1229 
GetCameraStatusListenerManager()1230 sptr<CameraStatusListenerManager> CameraManager::GetCameraStatusListenerManager()
1231 {
1232     return cameraStatusListenerManager_;
1233 }
1234 
RegisterCameraMuteListener(std::shared_ptr<CameraMuteListener> listener)1235 void CameraManager::RegisterCameraMuteListener(std::shared_ptr<CameraMuteListener> listener)
1236 {
1237     CHECK_RETURN(listener == nullptr);
1238     bool isSuccess = cameraMuteListenerManager_->AddListener(listener);
1239     CHECK_RETURN(!isSuccess);
1240     if (cameraMuteListenerManager_->GetListenerCount() == 1) {
1241         sptr<ICameraMuteServiceCallback> callback = cameraMuteListenerManager_;
1242         int32_t errCode = SetCameraMuteServiceCallback(callback);
1243         CHECK_RETURN(errCode != CAMERA_OK);
1244     }
1245 }
1246 
UnregisterCameraMuteListener(std::shared_ptr<CameraMuteListener> listener)1247 void CameraManager::UnregisterCameraMuteListener(std::shared_ptr<CameraMuteListener> listener)
1248 {
1249     CHECK_RETURN(listener == nullptr);
1250     cameraMuteListenerManager_->RemoveListener(listener);
1251     if (cameraMuteListenerManager_->GetListenerCount() == 0) {
1252         UnSetCameraMuteServiceCallback();
1253     }
1254 }
1255 
GetCameraMuteListenerManager()1256 sptr<CameraMuteListenerManager> CameraManager::GetCameraMuteListenerManager()
1257 {
1258     return cameraMuteListenerManager_;
1259 }
1260 
RegisterTorchListener(shared_ptr<TorchListener> listener)1261 void CameraManager::RegisterTorchListener(shared_ptr<TorchListener> listener)
1262 {
1263     CHECK_RETURN(listener == nullptr);
1264     bool isSuccess = torchServiceListenerManager_->AddListener(listener);
1265     CHECK_RETURN(!isSuccess);
1266 
1267     // First register, set callback to service, service trigger callback.
1268     if (torchServiceListenerManager_->GetListenerCount() == 1) {
1269         sptr<ITorchServiceCallback> callback = torchServiceListenerManager_;
1270         SetTorchServiceCallback(callback);
1271         return;
1272     }
1273 
1274     // LCOV_EXCL_START
1275     // Non-First register, async callback by cache data.
1276     auto torchStatus = torchServiceListenerManager_->GetCachedTorchStatus();
1277     torchServiceListenerManager_->TriggerTargetListenerAsync(listener, [torchStatus](auto listener) {
1278         MEDIA_INFO_LOG(
1279             "CameraManager::RegisterTorchListener async trigger status change %{public}d %{public}d %{public}f",
1280             torchStatus.isTorchActive, torchStatus.isTorchAvailable, torchStatus.torchLevel);
1281         listener->OnTorchStatusChange(torchStatus);
1282     });
1283     // LCOV_EXCL_STOP
1284 }
1285 
UnregisterTorchListener(std::shared_ptr<TorchListener> listener)1286 void CameraManager::UnregisterTorchListener(std::shared_ptr<TorchListener> listener)
1287 {
1288     // LCOV_EXCL_START
1289     CHECK_RETURN(listener == nullptr);
1290     torchServiceListenerManager_->RemoveListener(listener);
1291     if (torchServiceListenerManager_->GetListenerCount() == 0) {
1292         UnSetTorchServiceCallback();
1293     }
1294     // LCOV_EXCL_STOP
1295 }
1296 
GetTorchServiceListenerManager()1297 sptr<TorchServiceListenerManager> CameraManager::GetTorchServiceListenerManager()
1298 {
1299     return torchServiceListenerManager_;
1300 }
1301 
RegisterFoldListener(shared_ptr<FoldListener> listener)1302 void CameraManager::RegisterFoldListener(shared_ptr<FoldListener> listener)
1303 {
1304     CHECK_RETURN(listener == nullptr);
1305     bool isSuccess = foldStatusListenerManager_->AddListener(listener);
1306     CHECK_RETURN(!isSuccess);
1307     if (foldStatusListenerManager_->GetListenerCount() == 1) {
1308         sptr<IFoldServiceCallback> callback = foldStatusListenerManager_;
1309         int32_t errCode = SetFoldServiceCallback(callback);
1310         CHECK_RETURN(errCode != CAMERA_OK);
1311     }
1312 }
1313 
UnregisterFoldListener(shared_ptr<FoldListener> listener)1314 void CameraManager::UnregisterFoldListener(shared_ptr<FoldListener> listener)
1315 {
1316     // LCOV_EXCL_START
1317     CHECK_RETURN(listener == nullptr);
1318     foldStatusListenerManager_->RemoveListener(listener);
1319     if (foldStatusListenerManager_->GetListenerCount() == 0) {
1320         UnSetFoldServiceCallback();
1321     }
1322     // LCOV_EXCL_STOP
1323 }
1324 
GetFoldStatusListenerManager()1325 sptr<FoldStatusListenerManager> CameraManager::GetFoldStatusListenerManager()
1326 {
1327     return foldStatusListenerManager_;
1328 }
1329 
RegisterControlCenterStatusListener(std::shared_ptr<ControlCenterStatusListener> listener)1330 void CameraManager::RegisterControlCenterStatusListener(std::shared_ptr<ControlCenterStatusListener> listener)
1331 {
1332     // LCOV_EXCL_START
1333     CHECK_RETURN(listener == nullptr);
1334     bool isSuccess = controlCenterStatusListenerManager_->AddListener(listener);
1335     CHECK_RETURN(!isSuccess);
1336     if (controlCenterStatusListenerManager_->GetListenerCount() == 1) {
1337         sptr<IControlCenterStatusCallback> callback = controlCenterStatusListenerManager_;
1338         int32_t errCode = SetControlCenterStatusCallback(callback);
1339         CHECK_RETURN(errCode != CAMERA_OK);
1340     }
1341     // LCOV_EXCL_STOP
1342 }
1343 
UnregisterControlCenterStatusListener(std::shared_ptr<ControlCenterStatusListener> listener)1344 void CameraManager::UnregisterControlCenterStatusListener(std::shared_ptr<ControlCenterStatusListener> listener)
1345 {
1346     // LCOV_EXCL_START
1347     CHECK_RETURN(listener == nullptr);
1348     controlCenterStatusListenerManager_->RemoveListener(listener);
1349     if (controlCenterStatusListenerManager_->GetListenerCount() == 0) {
1350         UnSetControlCenterStatusCallback();
1351     }
1352     // LCOV_EXCL_STOP
1353 }
1354 
GetControlCenterStatusListenerManager()1355 sptr<ControlCenterStatusListenerManager> CameraManager::GetControlCenterStatusListenerManager()
1356 {
1357     return controlCenterStatusListenerManager_;
1358 }
1359 
GetCameraDeviceFromId(std::string cameraId)1360 sptr<CameraDevice> CameraManager::GetCameraDeviceFromId(std::string cameraId)
1361 {
1362     auto cameraDeviceList = GetCameraDeviceList();
1363     for (auto& deviceInfo : cameraDeviceList) {
1364         CHECK_RETURN_RET(deviceInfo->GetID() == cameraId, deviceInfo);
1365     }
1366     return nullptr;
1367 }
1368 
GetInstance()1369 sptr<CameraManager>& CameraManager::GetInstance()
1370 {
1371     std::lock_guard<std::mutex> lock(g_instanceMutex);
1372     if (CameraManager::g_cameraManager == nullptr) {
1373         MEDIA_INFO_LOG("Initializing camera manager for first time!");
1374         CameraManager::g_cameraManager = new CameraManager();
1375         CameraManager::g_cameraManager->InitCameraManager();
1376     } else if (CameraManager::g_cameraManager->GetServiceProxy() == nullptr) {
1377         CameraManager::g_cameraManager->InitCameraManager();
1378     }
1379     return CameraManager::g_cameraManager;
1380 }
1381 
GetCameras()1382 std::vector<sptr<CameraInfo>> CameraManager::GetCameras()
1383 {
1384     CAMERA_SYNC_TRACE;
1385     return {};
1386 }
1387 
GetDmDeviceInfo()1388 std::vector<dmDeviceInfo> CameraManager::GetDmDeviceInfo()
1389 {
1390     auto serviceProxy = GetServiceProxy();
1391     CHECK_RETURN_RET_ELOG(
1392         serviceProxy == nullptr, {}, "CameraManager::GetDmDeviceInfo serviceProxy is null, returning empty list!");
1393 
1394     std::vector<std::string> deviceInfos;
1395     int32_t retCode = serviceProxy->GetDmDeviceInfo(deviceInfos);
1396     CHECK_RETURN_RET_ELOG(
1397         retCode != CAMERA_OK, {}, "CameraManager::GetDmDeviceInfo failed!, retCode: %{public}d", retCode);
1398 
1399     int size = static_cast<int>(deviceInfos.size());
1400     MEDIA_INFO_LOG("CameraManager::GetDmDeviceInfo size=%{public}d", size);
1401     CHECK_RETURN_RET(size < 0, {});
1402 
1403     std::vector<dmDeviceInfo> distributedCamInfo(size);
1404     for (int i = 0; i < size; i++) {
1405         // LCOV_EXCL_START
1406         std::string deviceInfoStr = deviceInfos[i];
1407         MEDIA_INFO_LOG("CameraManager::GetDmDeviceInfo deviceInfo: %{public}s",
1408             OHOS::CameraStandard::Anonymization::AnonymizeString(deviceInfoStr).c_str());
1409         if (!nlohmann::json::accept(deviceInfoStr)) {
1410             MEDIA_ERR_LOG("Failed to verify the deviceInfo format, deviceInfo is: %{public}s",
1411                 OHOS::CameraStandard::Anonymization::AnonymizeString(deviceInfoStr).c_str());
1412         } else {
1413             nlohmann::json deviceInfoJson = nlohmann::json::parse(deviceInfoStr);
1414             if ((deviceInfoJson.contains("deviceName") && deviceInfoJson.contains("deviceTypeId") &&
1415                     deviceInfoJson.contains("networkId")) &&
1416                 (deviceInfoJson["deviceName"].is_string() && deviceInfoJson["networkId"].is_string())) {
1417                 distributedCamInfo[i].deviceName = deviceInfoJson["deviceName"];
1418                 distributedCamInfo[i].deviceTypeId = deviceInfoJson["deviceTypeId"];
1419                 distributedCamInfo[i].networkId = deviceInfoJson["networkId"];
1420             }
1421         }
1422         // LCOV_EXCL_STOP
1423     }
1424     return distributedCamInfo;
1425 }
1426 
GetCameraOutputStatus(int32_t pid,int32_t & status)1427 void CameraManager::GetCameraOutputStatus(int32_t pid, int32_t &status)
1428 {
1429     auto serviceProxy = GetServiceProxy();
1430     CHECK_RETURN_ELOG(
1431         serviceProxy == nullptr, "CameraManager::GetCameraOutputStatus serviceProxy is null");
1432 
1433     int32_t retCode = serviceProxy->GetCameraOutputStatus(pid, status);
1434     CHECK_RETURN_ELOG(
1435         retCode != CAMERA_OK, "CameraManager::GetCameraOutputStatus failed!, retCode: %{public}d", retCode);
1436 }
1437 
GetDmDeviceInfo(const std::string & cameraId,const std::vector<dmDeviceInfo> & dmDeviceInfoList)1438 dmDeviceInfo CameraManager::GetDmDeviceInfo(
1439     const std::string& cameraId, const std::vector<dmDeviceInfo>& dmDeviceInfoList)
1440 {
1441     dmDeviceInfo deviceInfo = { .deviceName = "", .deviceTypeId = 0, .networkId = "" };
1442     // LCOV_EXCL_START
1443     for (auto& info : dmDeviceInfoList) {
1444         if (cameraId.find(info.networkId) != std::string::npos) {
1445             deviceInfo = info;
1446             MEDIA_DEBUG_LOG("CameraManager::GetDmDeviceInfo %{public}s is remote camera", cameraId.c_str());
1447             break;
1448         }
1449     }
1450     // LCOV_EXCL_STOP
1451     return deviceInfo;
1452 }
1453 
GetCameraDeviceListFromServer()1454 std::vector<sptr<CameraDevice>> CameraManager::GetCameraDeviceListFromServer()
1455 {
1456     CAMERA_SYNC_TRACE;
1457     auto serviceProxy = GetServiceProxy();
1458     CHECK_RETURN_RET_ELOG(
1459         serviceProxy == nullptr, {}, "CameraManager::InitCameraList serviceProxy is null, returning empty list!");
1460     std::vector<std::string> cameraIds;
1461     std::vector<sptr<CameraDevice>> deviceInfoList = {};
1462     int32_t retCode = serviceProxy->GetCameraIds(cameraIds);
1463     if (retCode == CAMERA_OK) {
1464         auto dmDeviceInfoList = GetDmDeviceInfo();
1465         for (auto& cameraId : cameraIds) {
1466             MEDIA_DEBUG_LOG("InitCameraList cameraId= %{public}s", cameraId.c_str());
1467             std::shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility;
1468             retCode = serviceProxy->GetCameraAbility(cameraId, cameraAbility);
1469             if (retCode != CAMERA_OK) {
1470                 continue;
1471             }
1472 
1473             auto dmDeviceInfo = GetDmDeviceInfo(cameraId, dmDeviceInfoList);
1474             sptr<CameraDevice> cameraObj = new (std::nothrow) CameraDevice(cameraId, dmDeviceInfo, cameraAbility);
1475             if (cameraObj == nullptr) {
1476                 MEDIA_ERR_LOG("failed to new CameraDevice!");
1477                 continue;
1478             }
1479             SetProfile(cameraObj, cameraAbility);
1480             deviceInfoList.emplace_back(cameraObj);
1481         }
1482     } else {
1483         MEDIA_ERR_LOG("Get camera device failed!, retCode: %{public}d", retCode);
1484     }
1485     if (!foldScreenType_.empty() && foldScreenType_[0] == '4' && !GetIsInWhiteList()) {
1486         for (const auto& deviceInfo : deviceInfoList) {
1487             if (deviceInfo->GetPosition() == CAMERA_POSITION_FOLD_INNER) {
1488                 SetInnerCamera(deviceInfo);
1489                 break;
1490             }
1491         }
1492     }
1493     AlignVideoFpsProfile(deviceInfoList);
1494     std::sort(deviceInfoList.begin(), deviceInfoList.end(),
1495         [](const sptr<CameraDevice>& a, const sptr<CameraDevice>& b) {
1496             return static_cast<int>(a->GetConnectionType()) < static_cast<int>(b->GetConnectionType());
1497     });
1498     return deviceInfoList;
1499 }
1500 
ProcessModeAndOutputCapability(std::vector<std::vector<SceneMode>> & modes,std::vector<SceneMode> modeofThis,std::vector<std::vector<sptr<CameraOutputCapability>>> & outputCapabilities,std::vector<sptr<CameraOutputCapability>> outputCapabilitiesofThis)1501 void CameraManager::ProcessModeAndOutputCapability(std::vector<std::vector<SceneMode>> &modes,
1502     std::vector<SceneMode> modeofThis, std::vector<std::vector<sptr<CameraOutputCapability>>> &outputCapabilities,
1503     std::vector<sptr<CameraOutputCapability>> outputCapabilitiesofThis)
1504 {
1505     modes.push_back(modeofThis);
1506     outputCapabilities.push_back(outputCapabilitiesofThis);
1507 }
1508 
GetCameraConcurrentInfos(std::vector<sptr<CameraDevice>> cameraDeviceArrray,std::vector<bool> cameraConcurrentType,std::vector<std::vector<SceneMode>> & modes,std::vector<std::vector<sptr<CameraOutputCapability>>> & outputCapabilities)1509 void CameraManager::GetCameraConcurrentInfos(std::vector<sptr<CameraDevice>> cameraDeviceArrray,
1510     std::vector<bool> cameraConcurrentType, std::vector<std::vector<SceneMode>> &modes,
1511     std::vector<std::vector<sptr<CameraOutputCapability>>> &outputCapabilities)
1512 {
1513     // LCOV_EXCL_START
1514     MEDIA_INFO_LOG("CameraManager::GetCameraConcurrentInfos start");
1515     CAMERA_SYNC_TRACE;
1516     auto serviceProxy = GetServiceProxy();
1517     CHECK_RETURN_ELOG(
1518         serviceProxy == nullptr, "CameraManager::InitCameraList serviceProxy is null, returning empty list!");
1519     int32_t retCode;
1520     int index = 0;
1521     for (auto cameraDev : cameraDeviceArrray) {
1522         std::vector<SceneMode> modeofThis = {};
1523         std::vector<sptr<CameraOutputCapability>> outputCapabilitiesofThis = {};
1524         CameraPosition cameraPosition = cameraDev->GetPosition();
1525         auto iter = fwToMetaCameraPosition_.find(cameraPosition);
1526         if (iter == fwToMetaCameraPosition_.end()) {
1527             ProcessModeAndOutputCapability(modes, modeofThis, outputCapabilities, outputCapabilitiesofThis);
1528             continue;
1529         }
1530         string idOfThis = {};
1531         serviceProxy->GetIdforCameraConcurrentType(iter->second, idOfThis);
1532         sptr<ICameraDeviceService> cameradevicephysic = nullptr;
1533         CreateCameraDevice(idOfThis, &cameradevicephysic);
1534         std::shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility;
1535         retCode = serviceProxy->GetConcurrentCameraAbility(idOfThis, cameraAbility);
1536         if (retCode != CAMERA_OK) {
1537             ProcessModeAndOutputCapability(modes, modeofThis, outputCapabilities, outputCapabilitiesofThis);
1538             index++;
1539             continue;
1540         }
1541         sptr<CameraDevice> cameraObjnow = new (std::nothrow) CameraDevice(idOfThis, cameraAbility);
1542         camera_metadata_item_t item;
1543         if (!cameraConcurrentType[index]) {
1544             retCode = Camera::FindCameraMetadataItem(cameraAbility->get(),
1545                 OHOS_ABILITY_AVAILABLE_PROFILE_LEVEL, &item);
1546             if (retCode == CAM_META_SUCCESS) {
1547                 GetMetadataInfos(item, modeofThis, outputCapabilitiesofThis, cameraAbility);
1548             }
1549             ProcessModeAndOutputCapability(modes, modeofThis, outputCapabilities, outputCapabilitiesofThis);
1550         } else {
1551             retCode = Camera::FindCameraMetadataItem(cameraAbility->get(),
1552                 OHOS_ABILITY_CAMERA_LIMITED_CAPABILITIES, &item);
1553             if (retCode == CAM_META_SUCCESS) {
1554                 ParsingCameraConcurrentLimted(item, modeofThis, outputCapabilitiesofThis, cameraAbility, cameraObjnow);
1555             } else {
1556                 MEDIA_ERR_LOG("GetCameraConcurrentInfos error");
1557             }
1558             ProcessModeAndOutputCapability(modes, modeofThis, outputCapabilities, outputCapabilitiesofThis);
1559         }
1560         index++;
1561     }
1562     // LCOV_EXCL_STOP
1563 }
1564 
ParsingCameraConcurrentLimted(camera_metadata_item_t & item,std::vector<SceneMode> & mode,std::vector<sptr<CameraOutputCapability>> & outputCapabilitiesofThis,shared_ptr<OHOS::Camera::CameraMetadata> & cameraAbility,sptr<CameraDevice> cameraDevNow)1565 void CameraManager::ParsingCameraConcurrentLimted(camera_metadata_item_t &item,
1566     std::vector<SceneMode> &mode, std::vector<sptr<CameraOutputCapability>> &outputCapabilitiesofThis,
1567     shared_ptr<OHOS::Camera::CameraMetadata> &cameraAbility, sptr<CameraDevice>cameraDevNow)
1568 {
1569     // LCOV_EXCL_START
1570     MEDIA_INFO_LOG("CameraManager::ParsingCameraConcurrentLimted start");
1571     double* originInfo = item.data.d;
1572     uint32_t count = item.count;
1573     CHECK_RETURN_ELOG(
1574         cameraDevNow == nullptr, "CameraManager::ParsingCameraConcurrentLimted cameraDevNow is null");
1575     cameraDevNow->limtedCapabilitySave_.flashmodes.count = 0;
1576     cameraDevNow->limtedCapabilitySave_.flashmodes.mode.clear();
1577     cameraDevNow->limtedCapabilitySave_.exposuremodes.count = 0;
1578     cameraDevNow->limtedCapabilitySave_.exposuremodes.mode.clear();
1579     cameraDevNow->limtedCapabilitySave_.ratiorange.count = 0;
1580     cameraDevNow->limtedCapabilitySave_.ratiorange.mode.clear();
1581     cameraDevNow->limtedCapabilitySave_.ratiorange.range.clear();
1582     cameraDevNow->limtedCapabilitySave_.compensation.count = 0;
1583     cameraDevNow->limtedCapabilitySave_.compensation.range.clear();
1584     cameraDevNow->limtedCapabilitySave_.focusmodes.count = 0;
1585     cameraDevNow->limtedCapabilitySave_.focusmodes.mode.clear();
1586     cameraDevNow->limtedCapabilitySave_.stabilizationmodes.count = 0;
1587     cameraDevNow->limtedCapabilitySave_.stabilizationmodes.mode.clear();
1588     cameraDevNow->limtedCapabilitySave_.colorspaces.modeCount = 0;
1589     cameraDevNow->limtedCapabilitySave_.colorspaces.modeInfo.clear();
1590     for (int32_t i = 0; i < static_cast<int32_t>(count);) {
1591         if (static_cast<camera_device_metadata_tag>(originInfo[i]) == OHOS_ABILITY_FLASH_MODES) {
1592             std::vector<int32_t>vec;
1593             int length = static_cast<int32_t>(originInfo[i + STEP_ONE]);
1594             cameraDevNow->limtedCapabilitySave_.flashmodes.count = length;
1595             GetAbilityStructofConcurrentLimted(vec, originInfo + i + STEP_TWO, length);
1596             cameraDevNow->limtedCapabilitySave_.flashmodes.mode = vec;
1597             i = i + length + STEP_TWO + STEP_ONE;
1598         } else if (static_cast<camera_device_metadata_tag>(originInfo[i]) == OHOS_ABILITY_EXPOSURE_MODES) {
1599             std::vector<int32_t>vec;
1600             int length = static_cast<int32_t>(originInfo[i + STEP_ONE]);
1601             cameraDevNow->limtedCapabilitySave_.exposuremodes.count = length;
1602             GetAbilityStructofConcurrentLimted(vec, originInfo + i + STEP_TWO, length);
1603             cameraDevNow->limtedCapabilitySave_.exposuremodes.mode = vec;
1604             i = i + length + STEP_TWO + STEP_ONE;
1605         } else if (static_cast<camera_device_metadata_tag>(originInfo[i]) == OHOS_ABILITY_ZOOM_RATIO_RANGE) {
1606             std::vector<float>vec;
1607             int length = static_cast<int32_t>(originInfo[i + STEP_ONE]);
1608             cameraDevNow->limtedCapabilitySave_.ratiorange.count = length / STEP_THREE;
1609             for (int j = i + STEP_TWO; j < i + length + STEP_TWO + STEP_ONE; j += STEP_THREE) {
1610                 cameraDevNow->limtedCapabilitySave_.ratiorange.mode.push_back(static_cast<int32_t>(originInfo[j]));
1611                 cameraDevNow->limtedCapabilitySave_.ratiorange.range.insert({static_cast<int32_t>(originInfo[j]),
1612                     make_pair(static_cast<float>(originInfo[j + STEP_ONE]),
1613                         static_cast<float>(originInfo[j + STEP_TWO]))});
1614             }
1615             i = i + length + STEP_TWO + STEP_ONE;
1616         } else if (static_cast<camera_device_metadata_tag>(originInfo[i]) == OHOS_ABILITY_AE_COMPENSATION_RANGE) {
1617             std::vector<float>vec;
1618             int length = static_cast<int32_t>(originInfo[i + STEP_ONE]);
1619             cameraDevNow->limtedCapabilitySave_.compensation.count = length;
1620             GetAbilityStructofConcurrentLimtedfloat(vec, originInfo + i + STEP_TWO, length);
1621             cameraDevNow->limtedCapabilitySave_.compensation.range = vec;
1622             i = i + length + STEP_TWO + STEP_ONE;
1623         } else if (static_cast<camera_device_metadata_tag>(originInfo[i]) == OHOS_ABILITY_FOCUS_MODES) {
1624             std::vector<int32_t>vec;
1625             int length = static_cast<int32_t>(originInfo[i + STEP_ONE]);
1626             cameraDevNow->limtedCapabilitySave_.focusmodes.count = length;
1627             GetAbilityStructofConcurrentLimted(vec, originInfo + i + STEP_TWO, length);
1628             cameraDevNow->limtedCapabilitySave_.focusmodes.mode = vec;
1629             i = i + length + STEP_TWO + STEP_ONE;
1630         } else if (static_cast<camera_device_metadata_tag>(originInfo[i]) == OHOS_ABILITY_VIDEO_STABILIZATION_MODES) {
1631             std::vector<int32_t>vec;
1632             int length = static_cast<int32_t>(originInfo[i + STEP_ONE]);
1633             cameraDevNow->limtedCapabilitySave_.stabilizationmodes.count = length;
1634             GetAbilityStructofConcurrentLimted(vec, originInfo + i + STEP_TWO, length);
1635             cameraDevNow->limtedCapabilitySave_.stabilizationmodes.mode = vec;
1636             i = i + length + STEP_TWO + STEP_ONE;
1637         } else if (static_cast<camera_device_metadata_tag>(originInfo[i]) == OHOS_ABILITY_AVAILABLE_COLOR_SPACES) {
1638             std::shared_ptr<ColorSpaceInfoParse> colorSpaceParse = std::make_shared<ColorSpaceInfoParse>();
1639             int countl = 0;
1640             FindConcurrentLimtedEnd(originInfo, i, count, countl);
1641             colorSpaceParse->getColorSpaceInfoforConcurrent(originInfo + i + STEP_ONE,
1642                 countl - STEP_ONE, cameraDevNow->limtedCapabilitySave_.colorspaces);
1643                 i = i + countl + STEP_ONE;
1644         } else if (static_cast<camera_device_metadata_tag>(originInfo[i]) == OHOS_ABILITY_AVAILABLE_PROFILE_LEVEL) {
1645             GetMetadataInfosfordouble(item, originInfo, i + STEP_ONE, mode, outputCapabilitiesofThis, cameraAbility);
1646             break;
1647         } else {
1648             i++;
1649         }
1650     }
1651     cameraConLimCapMap_.insert({cameraDevNow->GetID(), cameraDevNow->limtedCapabilitySave_});
1652     // LCOV_EXCL_STOP
1653 }
1654 
FindConcurrentLimtedEnd(double * originInfo,int32_t i,int count,int & countl)1655 void CameraManager::FindConcurrentLimtedEnd(double* originInfo, int32_t i, int count, int &countl)
1656 {
1657     // LCOV_EXCL_START
1658     for (int32_t j = i + STEP_ONE; j < count; j++) {
1659         if (static_cast<camera_device_metadata_tag>(originInfo[j]) == OHOS_ABILITY_AVAILABLE_PROFILE_LEVEL) {
1660             break;
1661         }
1662         countl++;
1663     }
1664     // LCOV_EXCL_STOP
1665 }
1666 
GetAbilityStructofConcurrentLimted(std::vector<int32_t> & vec,double * originInfo,int length)1667 void CameraManager::GetAbilityStructofConcurrentLimted(std::vector<int32_t>&vec, double* originInfo, int length)
1668 {
1669     // LCOV_EXCL_START
1670     for (int i = 0; i < length; i++) {
1671         vec.push_back(static_cast<int32_t>(originInfo[i]));
1672     }
1673     // LCOV_EXCL_STOP
1674 }
1675 
GetAbilityStructofConcurrentLimtedfloat(std::vector<float> & vec,double * originInfo,int length)1676 void CameraManager::GetAbilityStructofConcurrentLimtedfloat(std::vector<float>&vec, double* originInfo, int length)
1677 {
1678     // LCOV_EXCL_START
1679     for (int i = 0; i < length; i++) {
1680         vec.push_back(static_cast<float>(originInfo[i]));
1681     }
1682     // LCOV_EXCL_STOP
1683 }
1684 
GetMetadataInfos(camera_metadata_item_t item,std::vector<SceneMode> & modeofThis,std::vector<sptr<CameraOutputCapability>> & outputCapabilitiesofThis,shared_ptr<OHOS::Camera::CameraMetadata> & cameraAbility)1685 void CameraManager::GetMetadataInfos(camera_metadata_item_t item,
1686     std::vector<SceneMode> &modeofThis, std::vector<sptr<CameraOutputCapability>> &outputCapabilitiesofThis,
1687     shared_ptr<OHOS::Camera::CameraMetadata> &cameraAbility)
1688 {
1689     // LCOV_EXCL_START
1690     ProfilesWrapper profilesWrapper = {};
1691     std::vector<ProfileLevelInfo> modeInfosum = {};
1692     int32_t* originInfo = item.data.i32;
1693     uint32_t count = item.count;
1694     CHECK_RETURN(count == 0 || originInfo == nullptr);
1695     uint32_t i = 0;
1696     uint32_t j = i + STEP_THREE;
1697     auto isModeEnd = [](int32_t *originInfo, uint32_t j) {
1698         return originInfo[j] == MODE_END && originInfo[j - 1] == SPEC_END &&
1699                 originInfo[j - 2] == STREAM_END && originInfo[j - 3] == DETAIL_END;
1700     };
1701     while (j < count) {
1702         if (originInfo[j] != MODE_END) {
1703             j = j + STEP_FOUR;
1704             continue;
1705         }
1706         if (isModeEnd(originInfo, j)) {
1707             ProfileLevelInfo modeInfo = {};
1708             modeofThis.push_back(static_cast<SceneMode>(originInfo[i]));
1709             CameraAbilityParseUtil::GetSpecInfo(originInfo, i + 1, j - 1, modeInfo);
1710             i = j + 1;
1711             j = i + 1;
1712             modeInfosum.push_back(modeInfo);
1713         } else {
1714             j++;
1715         }
1716     }
1717     int32_t mCount = 0;
1718     for (auto &modeInfo : modeInfosum) {
1719         std::vector<SpecInfo> specInfos;
1720         ProfilesWrapper profilesWrapper;
1721         specInfos.insert(specInfos.end(), modeInfo.specInfos.begin(), modeInfo.specInfos.end());
1722         sptr<CameraOutputCapability> cameraOutputCapability = new (std::nothrow) CameraOutputCapability();
1723         for (SpecInfo& specInfo : specInfos) {
1724             for (StreamInfo& streamInfo : specInfo.streamInfos) {
1725                 CreateProfileLevel4StreamType(profilesWrapper, specInfo.specId, streamInfo);
1726             }
1727         }
1728         int32_t modename = modeofThis[mCount];
1729         SetCameraOutputCapabilityofthis(cameraOutputCapability, profilesWrapper,
1730             modename, cameraAbility);
1731         outputCapabilitiesofThis.push_back(cameraOutputCapability);
1732         mCount++;
1733     }
1734     // LCOV_EXCL_STOP
1735 }
1736 
SetCameraOutputCapabilityofthis(sptr<CameraOutputCapability> & cameraOutputCapability,ProfilesWrapper & profilesWrapper,int32_t modeName,shared_ptr<OHOS::Camera::CameraMetadata> & cameraAbility)1737 void CameraManager::SetCameraOutputCapabilityofthis(sptr<CameraOutputCapability> &cameraOutputCapability,
1738     ProfilesWrapper &profilesWrapper, int32_t modeName,
1739     shared_ptr<OHOS::Camera::CameraMetadata> &cameraAbility)
1740 {
1741     // LCOV_EXCL_START
1742     if (IsSystemApp()) {
1743         FillSupportPhotoFormats(profilesWrapper.photoProfiles);
1744     }
1745     CHECK_RETURN_ELOG(
1746         cameraOutputCapability == nullptr, "cameraOutputCapability is null");
1747     cameraOutputCapability->SetPhotoProfiles(profilesWrapper.photoProfiles);
1748     MEDIA_INFO_LOG("SetPhotoProfiles size = %{public}zu", profilesWrapper.photoProfiles.size());
1749     cameraOutputCapability->SetPreviewProfiles(profilesWrapper.previewProfiles);
1750     MEDIA_INFO_LOG("SetPreviewProfiles size = %{public}zu", profilesWrapper.previewProfiles.size());
1751     if (!isPhotoMode_.count(modeName)) {
1752         cameraOutputCapability->SetVideoProfiles(profilesWrapper.vidProfiles);
1753     }
1754     MEDIA_INFO_LOG("SetVideoProfiles size = %{public}zu", profilesWrapper.vidProfiles.size());
1755     cameraOutputCapability->SetDepthProfiles(depthProfiles_);
1756     MEDIA_INFO_LOG("SetDepthProfiles size = %{public}zu", depthProfiles_.size());
1757 
1758     std::vector<MetadataObjectType> objectTypes = {};
1759     camera_metadata_item_t metadataItem;
1760     int32_t ret = Camera::FindCameraMetadataItem(cameraAbility->get(),
1761         OHOS_ABILITY_STATISTICS_DETECT_TYPE, &metadataItem);
1762     if (ret == CAM_META_SUCCESS) {
1763         for (uint32_t index = 0; index < metadataItem.count; index++) {
1764             auto iterator =
1765                 g_metaToFwCameraMetaDetect_.find(static_cast<StatisticsDetectType>(metadataItem.data.u8[index]));
1766             CHECK_PRINT_ELOG(iterator == g_metaToFwCameraMetaDetect_.end(),
1767                 "Not supported metadataItem %{public}d", metadataItem.data.u8[index]);
1768             if (iterator != g_metaToFwCameraMetaDetect_.end()) {
1769                 objectTypes.push_back(iterator->second);
1770             }
1771         }
1772     }
1773     if (!CameraSecurity::CheckSystemApp()) {
1774         MEDIA_DEBUG_LOG("public calling for GetSupportedOutputCapability");
1775         if (std::any_of(objectTypes.begin(), objectTypes.end(),
1776                         [](MetadataObjectType type) { return type == MetadataObjectType::FACE; })) {
1777             cameraOutputCapability->SetSupportedMetadataObjectType({MetadataObjectType::FACE});
1778         } else {
1779             cameraOutputCapability->SetSupportedMetadataObjectType({});
1780         }
1781     } else {
1782         cameraOutputCapability->SetSupportedMetadataObjectType(objectTypes);
1783     }
1784     MEDIA_INFO_LOG("SetMetadataTypes size = %{public}zu",
1785                    cameraOutputCapability->GetSupportedMetadataObjectType().size());
1786     // LCOV_EXCL_STOP
1787 }
1788 
GetConcurrentType(std::vector<sptr<CameraDevice>> cameraDeviceArrray,std::vector<bool> & cameraConcurrentType)1789 bool CameraManager::GetConcurrentType(std::vector<sptr<CameraDevice>> cameraDeviceArrray,
1790     std::vector<bool> &cameraConcurrentType)
1791 {
1792     // LCOV_EXCL_START
1793     CAMERA_SYNC_TRACE;
1794     auto serviceProxy = GetServiceProxy();
1795     CHECK_RETURN_RET_ELOG(
1796         serviceProxy == nullptr, false, "CameraManager::InitCameraList serviceProxy is null, returning empty list!");
1797     int32_t retCode;
1798     for (auto cameraDev : cameraDeviceArrray) {
1799         CameraPosition cameraPosition = cameraDev->GetPosition();
1800         CHECK_RETURN_RET_ELOG(cameraPosition == CameraPosition::CAMERA_POSITION_FOLD_INNER, false,
1801             "CameraManager::GetConcurrentType this device camera position is 3!");
1802         string idofthis;
1803         auto iter = fwToMetaCameraPosition_.find(cameraPosition);
1804         serviceProxy->GetIdforCameraConcurrentType(iter->second, idofthis);
1805 
1806         std::shared_ptr<OHOS::Camera::CameraMetadata> camAbility;
1807         retCode = serviceProxy->GetConcurrentCameraAbility(idofthis, camAbility);
1808         if (retCode != CAMERA_OK) {
1809             continue;
1810         }
1811         camera_metadata_item_t item;
1812         retCode = Camera::FindCameraMetadataItem(camAbility->get(), OHOS_ABILITY_CAMERA_CONCURRENT_TYPE, &item);
1813         if (retCode != CAMERA_OK) {
1814             cameraConcurrentType.clear();
1815             MEDIA_ERR_LOG("cameraAbility not support OHOS_ABILITY_CAMERA_CONCURRENT_TYPE");
1816             return false;
1817         }
1818         bool cameratype = 0;
1819         if (item.count > 0) {
1820             cameratype = static_cast<bool>(item.data.u8[0]);
1821         }
1822         MEDIA_INFO_LOG("cameraid is %{public}s, type is %{public}d", idofthis.c_str(), cameratype);
1823         cameraConcurrentType.push_back(cameratype);
1824     }
1825     return true;
1826     // LCOV_EXCL_STOP
1827 }
1828 
CheckCameraConcurrentId(std::unordered_map<std::string,int32_t> & idmap,std::vector<std::string> & cameraIdv)1829 bool CameraManager::CheckCameraConcurrentId(std::unordered_map<std::string, int32_t> &idmap,
1830     std::vector<std::string> &cameraIdv)
1831 {
1832     // LCOV_EXCL_START
1833     for (uint32_t i = 1; i < cameraIdv.size(); i++) {
1834         CHECK_PRINT_ELOG(cameraIdv[i].empty(), "CameraManager::CheckCameraConcurrentId get invalid cameraId");
1835         std::regex regex("\\d+$");
1836         std::smatch match;
1837         std::string cameraId;
1838         if (std::regex_search(cameraIdv[i], match, regex)) {
1839             cameraId = match[0];
1840         }
1841         MEDIA_DEBUG_LOG("CameraManager::CheckCameraConcurrentId check cameraId: %{public}s", cameraId.c_str());
1842         CHECK_RETURN_RET(!idmap.count(cameraId), false);
1843     }
1844     return true;
1845     // LCOV_EXCL_STOP
1846 }
1847 
CheckConcurrentExecution(std::vector<sptr<CameraDevice>> cameraDeviceArrray)1848 bool CameraManager::CheckConcurrentExecution(std::vector<sptr<CameraDevice>> cameraDeviceArrray)
1849 {
1850     // LCOV_EXCL_START
1851     std::vector<std::string>cameraIdv = {};
1852     CAMERA_SYNC_TRACE;
1853     auto serviceProxy = GetServiceProxy();
1854     CHECK_RETURN_RET_ELOG(
1855         serviceProxy == nullptr, false, "CameraManager::InitCameraList serviceProxy is null, returning empty list!");
1856     int32_t retCode;
1857 
1858     for (auto cameraDev : cameraDeviceArrray) {
1859         CameraPosition cameraPosition = cameraDev->GetPosition();
1860         string idofthis;
1861         auto iter = fwToMetaCameraPosition_.find(cameraPosition);
1862         serviceProxy->GetIdforCameraConcurrentType(iter->second, idofthis);
1863         cameraIdv.push_back(idofthis);
1864     }
1865     CHECK_RETURN_RET_ELOG(cameraIdv.size() == 0, false, "no find cameraid");
1866     std::shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility;
1867     retCode = serviceProxy->GetConcurrentCameraAbility(cameraIdv[0], cameraAbility);
1868     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, false, "GetCameraAbility fail");
1869     camera_metadata_item_t item;
1870     retCode = Camera::FindCameraMetadataItem(cameraAbility->get(), OHOS_ABILITY_CONCURRENT_SUPPORTED_CAMERAS, &item);
1871     if (retCode == CAMERA_OK) {
1872         MEDIA_DEBUG_LOG("success find OHOS_ABILITY_CONCURRENT_SUPPORTED_CAMERAS");
1873         for (uint32_t i = 0; i < item.count; i++) {
1874             MEDIA_DEBUG_LOG("concurrent cameras: %{public}d", item.data.i32[i]);
1875         }
1876     }
1877     int32_t* originInfo = item.data.i32;
1878     std::unordered_map<std::string, int32_t>idmap;
1879     idmap.clear();
1880     uint32_t count = item.count;
1881     for (uint32_t i = 0; i < count; i++) {
1882         if (originInfo[i] == -1) {
1883             CHECK_RETURN_RET(CheckCameraConcurrentId(idmap, cameraIdv), true);
1884             idmap.clear();
1885         } else {
1886             idmap[std::to_string(originInfo[i])]++;
1887         }
1888     }
1889     if (CheckCameraConcurrentId(idmap, cameraIdv)) {
1890         return true;
1891     }
1892     return false;
1893     // LCOV_EXCL_STOP
1894 }
1895 
GetMetadataInfosfordouble(camera_metadata_item_t & item,double * originInfo,uint32_t i,std::vector<SceneMode> & modeofThis,std::vector<sptr<CameraOutputCapability>> & outputCapabilitiesofThis,shared_ptr<OHOS::Camera::CameraMetadata> & cameraAbility)1896 void CameraManager::GetMetadataInfosfordouble(camera_metadata_item_t &item, double* originInfo, uint32_t i,
1897     std::vector<SceneMode> &modeofThis, std::vector<sptr<CameraOutputCapability>> &outputCapabilitiesofThis,
1898     shared_ptr<OHOS::Camera::CameraMetadata> &cameraAbility)
1899 {
1900     // LCOV_EXCL_START
1901     MEDIA_INFO_LOG("CameraManager::GetMetadataInfosfordouble start");
1902     ProfilesWrapper profilesWrapper = {};
1903     std::vector<ProfileLevelInfo> modeInfosum = {};
1904     uint32_t count = item.count;
1905     CHECK_RETURN(count == 0 || originInfo == nullptr);
1906     uint32_t j = i + STEP_THREE;
1907     auto isModeEnd = [](double *originInfo, uint32_t j) {
1908         return static_cast<int32_t>(originInfo[j]) == INT_MAX && static_cast<int32_t>(originInfo[j - 1]) == INT_MAX &&
1909                 static_cast<int32_t>(originInfo[j - 2]) == INT_MAX &&
1910                 static_cast<int32_t>(originInfo[j - 3]) == INT_MAX;
1911     };
1912     while (j < count) {
1913         if (static_cast<int32_t>(originInfo[j]) != INT_MAX) {
1914             j = j + STEP_FOUR;
1915             continue;
1916         }
1917         if (isModeEnd(originInfo, j)) {
1918             ProfileLevelInfo modeInfo = {};
1919             modeofThis.push_back(static_cast<SceneMode>(originInfo[i]));
1920             GetSpecInfofordouble(originInfo, i + 1, j - 1, modeInfo);
1921             modeInfosum.push_back(modeInfo);
1922             i = j + 1;
1923             j = i + 1;
1924         } else {
1925             j++;
1926         }
1927     }
1928     int32_t modecount = 0;
1929     for (auto &modeInfo : modeInfosum) {
1930         std::vector<SpecInfo> specInfos;
1931         ProfilesWrapper profilesWrapper;
1932         specInfos.insert(specInfos.end(), modeInfo.specInfos.begin(), modeInfo.specInfos.end());
1933         sptr<CameraOutputCapability> cameraOutputCapability = new (std::nothrow) CameraOutputCapability();
1934         for (SpecInfo& specInfo : specInfos) {
1935             for (StreamInfo& streamInfo : specInfo.streamInfos) {
1936                 CreateProfileLevel4StreamType(profilesWrapper, specInfo.specId, streamInfo);
1937             }
1938         }
1939         int32_t modename = modeofThis[modecount];
1940         SetCameraOutputCapabilityofthis(cameraOutputCapability, profilesWrapper,
1941             modename, cameraAbility);
1942 
1943         outputCapabilitiesofThis.push_back(cameraOutputCapability);
1944         modecount++;
1945     }
1946     // LCOV_EXCL_STOP
1947 }
1948 
GetSpecInfofordouble(double * originInfo,uint32_t start,uint32_t end,ProfileLevelInfo & modeInfo)1949 void CameraManager::GetSpecInfofordouble(double *originInfo, uint32_t start, uint32_t end, ProfileLevelInfo &modeInfo)
1950 {
1951     // LCOV_EXCL_START
1952     uint32_t i = start;
1953     uint32_t j = i + STEP_TWO;
1954     std::vector<std::pair<uint32_t, uint32_t>> specIndexRange;
1955     while (j <= end) {
1956         if (static_cast<int32_t>(originInfo[j]) != INT_MAX) {
1957             j = j + STEP_THREE;
1958             continue;
1959         }
1960         if (static_cast<int32_t>(originInfo[j - STEP_ONE]) == INT_MAX &&
1961             static_cast<int32_t>(originInfo[j - STEP_TWO]) == INT_MAX) {
1962             std::pair<uint32_t, uint32_t> indexPair(i, j);
1963             specIndexRange.push_back(indexPair);
1964             i = j + STEP_ONE;
1965             j = i + STEP_TWO;
1966         } else {
1967             j++;
1968         }
1969     }
1970     uint32_t specCount = specIndexRange.size();
1971     modeInfo.specInfos.resize(specCount);
1972 
1973     for (uint32_t k = 0; k < specCount; ++k) {
1974         SpecInfo& specInfo = modeInfo.specInfos[k];
1975         i = specIndexRange[k].first;
1976         j = specIndexRange[k].second;
1977         specInfo.specId = static_cast<int32_t>(originInfo[j]);
1978         GetStreamInfofordouble(originInfo, i + 1, j - 1, specInfo);
1979     }
1980     // LCOV_EXCL_STOP
1981 }
1982 
GetStreamInfofordouble(double * originInfo,uint32_t start,uint32_t end,SpecInfo & specInfo)1983 void CameraManager::GetStreamInfofordouble(double *originInfo, uint32_t start, uint32_t end, SpecInfo &specInfo)
1984 {
1985     // LCOV_EXCL_START
1986     uint32_t i = start;
1987     uint32_t j = i + STEP_ONE;
1988 
1989     std::vector<std::pair<uint32_t, uint32_t>> streamIndexRange;
1990     while (j <= end) {
1991         if (static_cast<int32_t>(originInfo[j]) == INT_MAX) {
1992             if (static_cast<int32_t>(originInfo[j - 1]) == INT_MAX) {
1993                 std::pair<uint32_t, uint32_t> indexPair(i, j);
1994                 streamIndexRange.push_back(indexPair);
1995                 i = j + STEP_ONE;
1996                 j = i + STEP_ONE;
1997             } else {
1998                 j++;
1999             }
2000         } else {
2001             j = j + STEP_TWO;
2002         }
2003     }
2004     uint32_t streamTypeCount = streamIndexRange.size();
2005     specInfo.streamInfos.resize(streamTypeCount);
2006 
2007     for (uint32_t k = 0; k < streamTypeCount; ++k) {
2008         StreamInfo& streamInfo = specInfo.streamInfos[k];
2009         i = streamIndexRange[k].first;
2010         j = streamIndexRange[k].second;
2011         streamInfo.streamType = static_cast<int32_t>(originInfo[i]);
2012         GetDetailInfofordouble(originInfo, i + 1, j - 1, streamInfo);
2013     }
2014     // LCOV_EXCL_STOP
2015 }
2016 
GetDetailInfofordouble(double * originInfo,uint32_t start,uint32_t end,StreamInfo & streamInfo)2017 void CameraManager::GetDetailInfofordouble(double *originInfo, uint32_t start, uint32_t end, StreamInfo &streamInfo)
2018 {
2019     // LCOV_EXCL_START
2020     uint32_t i = start;
2021     uint32_t j = i;
2022     std::vector<std::pair<uint32_t, uint32_t>> detailIndexRange;
2023     while (j <= end) {
2024         if (static_cast<int32_t>(originInfo[j]) == INT_MAX) {
2025             std::pair<uint32_t, uint32_t> indexPair(i, j);
2026             detailIndexRange.push_back(indexPair);
2027             i = j + STEP_ONE;
2028             j = i;
2029         } else {
2030             j++;
2031         }
2032     }
2033 
2034     uint32_t detailCount = detailIndexRange.size();
2035     streamInfo.detailInfos.resize(detailCount);
2036 
2037     for (uint32_t k = 0; k < detailCount; ++k) {
2038         auto &detailInfo = streamInfo.detailInfos[k];
2039         i = detailIndexRange[k].first;
2040         j = detailIndexRange[k].second;
2041         detailInfo.format = static_cast<uint32_t>(originInfo[i++]);
2042         detailInfo.width = static_cast<uint32_t>(originInfo[i++]);
2043         detailInfo.height = static_cast<uint32_t>(originInfo[i++]);
2044         detailInfo.fixedFps = static_cast<uint32_t>(originInfo[i++]);
2045         detailInfo.minFps = static_cast<uint32_t>(originInfo[i++]);
2046         detailInfo.maxFps = static_cast<uint32_t>(originInfo[i++]);
2047         detailInfo.abilityIds.resize(j - i);
2048         std::transform(originInfo + i, originInfo + j, detailInfo.abilityIds.begin(),
2049             [](auto val) { return static_cast<uint32_t>(val); });
2050     }
2051     // LCOV_EXCL_STOP
2052 }
2053 
SetProfile(sptr<CameraDevice> & cameraObj,std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)2054 void CameraManager::SetProfile(sptr<CameraDevice>& cameraObj, std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)
2055 {
2056     CHECK_RETURN_ELOG(
2057         cameraObj == nullptr, "CameraManager::SetProfile cameraObj is null");
2058     std::vector<SceneMode> supportedModes = GetSupportedModes(cameraObj);
2059     if (supportedModes.empty()) {
2060         // LCOV_EXCL_START
2061         auto capability = ParseSupportedOutputCapability(cameraObj, 0, metadata);
2062         cameraObj->SetProfile(capability);
2063         // LCOV_EXCL_STOP
2064     } else {
2065         supportedModes.emplace_back(NORMAL);
2066         for (const auto &modeName : supportedModes) {
2067             auto capability = ParseSupportedOutputCapability(cameraObj, modeName, metadata);
2068             cameraObj->SetProfile(capability, modeName);
2069         }
2070     }
2071 }
2072 
GetIsFoldable()2073 bool CameraManager::GetIsFoldable()
2074 {
2075     return !foldScreenType_.empty();
2076 }
2077 
GetFoldScreenType()2078 std::string CameraManager::GetFoldScreenType()
2079 {
2080     return foldScreenType_;
2081 }
2082 
GetFoldStatus()2083 FoldStatus CameraManager::GetFoldStatus()
2084 {
2085     auto curFoldStatus = (FoldStatus)OHOS::Rosen::DisplayManager::GetInstance().GetFoldStatus();
2086     if (curFoldStatus == FoldStatus::HALF_FOLD) {
2087         curFoldStatus = FoldStatus::EXPAND;
2088     }
2089     return curFoldStatus;
2090 }
2091 
CheckWhiteList()2092 void CameraManager::CheckWhiteList()
2093 {
2094     // LCOV_EXCL_START
2095     auto serviceProxy = GetServiceProxy();
2096     CHECK_RETURN_ELOG(
2097         serviceProxy == nullptr, "CameraManager::CheckWhitelist serviceProxy is null");
2098     serviceProxy->CheckWhiteList(isInWhiteList_);
2099     // LCOV_EXCL_STOP
2100 }
2101 
GetIsInWhiteList()2102 bool CameraManager::GetIsInWhiteList()
2103 {
2104     MEDIA_DEBUG_LOG("isInWhiteList: %{public}d", isInWhiteList_);
2105     return isInWhiteList_;
2106 }
2107 
GetSupportedCameras()2108 std::vector<sptr<CameraDevice>> CameraManager::GetSupportedCameras()
2109 {
2110     CAMERA_SYNC_TRACE;
2111     auto curFoldStatus = GetFoldStatus();
2112     std::vector<sptr<CameraDevice>> cameraDeviceList;
2113     // LCOV_EXCL_START
2114     if (curFoldStatus != preFoldStatus && !foldScreenType_.empty() && foldScreenType_[0] == '4') {
2115         std::lock_guard<std::mutex> lock(cameraDeviceListMutex_);
2116         cameraDeviceList = GetCameraDeviceListFromServer();
2117         cameraDeviceList_ = cameraDeviceList;
2118         preFoldStatus = curFoldStatus;
2119     } else {
2120         cameraDeviceList = GetCameraDeviceList();
2121     }
2122     // LCOV_EXCL_STOP
2123     bool isFoldable = GetIsFoldable();
2124     CHECK_RETURN_RET(!isFoldable, cameraDeviceList);
2125     MEDIA_INFO_LOG("fold status: %{public}d", curFoldStatus);
2126     CHECK_RETURN_RET(curFoldStatus == FoldStatus::UNKNOWN_FOLD &&
2127         !foldScreenType_.empty() && foldScreenType_[0] == '4', cameraDeviceList);
2128     std::vector<sptr<CameraDevice>> supportedCameraDeviceList;
2129     uint32_t apiCompatibleVersion = CameraApiVersion::GetApiVersion();
2130     // LCOV_EXCL_START
2131     for (const auto& deviceInfo : cameraDeviceList) {
2132         // The usb camera is added to the list and is not processed.
2133         if (deviceInfo->GetConnectionType() == CAMERA_CONNECTION_USB_PLUGIN ||
2134             (deviceInfo->GetConnectionType() == CAMERA_CONNECTION_REMOTE &&
2135             deviceInfo->GetSupportedFoldStatus() == OHOS_CAMERA_FOLD_STATUS_NONFOLDABLE)) {
2136             supportedCameraDeviceList.emplace_back(deviceInfo);
2137             continue;
2138         }
2139         if (!foldScreenType_.empty() && foldScreenType_[0] == '4' &&
2140             (deviceInfo->GetPosition() == CAMERA_POSITION_BACK ||
2141             deviceInfo->GetPosition() == CAMERA_POSITION_FOLD_INNER ||
2142             deviceInfo->GetPosition() == CAMERA_POSITION_FRONT) && !GetIsInWhiteList() &&
2143             curFoldStatus == FoldStatus::EXPAND) {
2144             auto it = std::find_if(supportedCameraDeviceList.begin(), supportedCameraDeviceList.end(),
2145                 [&deviceInfo](sptr<CameraDevice> cameraDevice) {
2146                 return cameraDevice->GetPosition() == deviceInfo->GetPosition();
2147             });
2148             if (it != supportedCameraDeviceList.end()) {
2149                 continue;
2150             }
2151             supportedCameraDeviceList.emplace_back(deviceInfo);
2152             continue;
2153         }
2154         // Check for API compatibility
2155         if (apiCompatibleVersion < CameraApiVersion::APIVersion::API_FOURTEEN) {
2156             bool isBackCamera = deviceInfo->GetPosition() == CAMERA_POSITION_BACK;
2157             bool isInnerOrFrontCamera = (deviceInfo->GetPosition() == CAMERA_POSITION_FOLD_INNER ||
2158                 deviceInfo->GetPosition() == CAMERA_POSITION_FRONT);
2159             bool isUnsupportedFoldScreenType = (!foldScreenType_.empty() &&
2160                 foldScreenType_[0] != '2' && foldScreenType_[0] != '4' && foldScreenType_[0] != '5');
2161             if ((isBackCamera || isInnerOrFrontCamera) && isUnsupportedFoldScreenType) {
2162                 supportedCameraDeviceList.emplace_back(deviceInfo);
2163                 continue;
2164             }
2165         }
2166 
2167         auto supportedFoldStatus = deviceInfo->GetSupportedFoldStatus();
2168 
2169         auto it = g_metaToFwCameraFoldStatus_.find(static_cast<CameraFoldStatus>(supportedFoldStatus));
2170         if (it == g_metaToFwCameraFoldStatus_.end()) {
2171             MEDIA_INFO_LOG("No supported fold status is found, fold status: %{public}d", curFoldStatus);
2172             supportedCameraDeviceList.emplace_back(deviceInfo);
2173             continue;
2174         }
2175         if (!foldScreenType_.empty() && foldScreenType_[0] == '4' && curFoldStatus == FoldStatus::FOLDED &&
2176             it->second == curFoldStatus && deviceInfo->GetPosition() == CAMERA_POSITION_BACK
2177             && bundleName_ != curBundleName_) {
2178             continue;
2179         }
2180         CHECK_EXECUTE(it->second == curFoldStatus, supportedCameraDeviceList.emplace_back(deviceInfo));
2181     }
2182     // LCOV_EXCL_STOP
2183     return supportedCameraDeviceList;
2184 }
2185 
GetSupportedModes(sptr<CameraDevice> & camera)2186 std::vector<SceneMode> CameraManager::GetSupportedModes(sptr<CameraDevice>& camera)
2187 {
2188     CHECK_RETURN_RET(camera == nullptr, {});
2189     std::vector<SceneMode> supportedSceneModes = camera->GetSupportedModes();
2190     MEDIA_DEBUG_LOG("CameraManager::GetSupportedModes supportedModes size: %{public}zu", supportedSceneModes.size());
2191     return supportedSceneModes;
2192 }
2193 
AlignVideoFpsProfile(std::vector<sptr<CameraDevice>> & cameraObjList)2194 void CameraManager::AlignVideoFpsProfile(std::vector<sptr<CameraDevice>>& cameraObjList)
2195 {
2196     MEDIA_ERR_LOG("CameraManager::AlignVideoFpsProfile enter");
2197     uint32_t normalMode = 0;
2198     int32_t alignFps = 60;
2199     std::vector<VideoProfile> frontVideoProfiles = {};
2200     std::vector<VideoProfile> backVideoProfiles = {};
2201     sptr<CameraDevice> frontCamera = nullptr;
2202     for (auto& camera : cameraObjList) {
2203         if (camera->GetPosition() == CAMERA_POSITION_FRONT) {
2204             frontVideoProfiles = camera->modeVideoProfiles_[normalMode];
2205             frontCamera = camera;
2206         } else if (camera->GetPosition() == CAMERA_POSITION_BACK) {
2207             backVideoProfiles = camera->modeVideoProfiles_[normalMode];
2208         }
2209     }
2210     const uint32_t minIndex = 0;
2211     const uint32_t maxIndex = 1;
2212     CHECK_RETURN_ELOG(!(frontVideoProfiles.size() && backVideoProfiles.size()),
2213         "CameraManager::AlignVideoFpsProfile failed! frontVideoSize = %{public}zu, "
2214         "frontVideoSize = %{public}zu", frontVideoProfiles.size(), backVideoProfiles.size());
2215     std::vector<VideoProfile> alignFrontVideoProfiles = frontVideoProfiles;
2216     for (auto &backProfile : backVideoProfiles) {
2217         for (auto &frontProfile : frontVideoProfiles) {
2218             if (backProfile.GetSize().width == frontProfile.GetSize().width &&
2219                 backProfile.GetSize().height == frontProfile.GetSize().height) {
2220                 if (backProfile.framerates_[minIndex] == alignFps && backProfile.framerates_[maxIndex] == alignFps) {
2221                     alignFrontVideoProfiles.push_back(backProfile);
2222                     MEDIA_INFO_LOG("CameraManager::AlignVideoFpsProfile backProfile w(%{public}d),h(%{public}d), "
2223                                    "frontProfile w(%{public}d),h(%{public}d)",
2224                                    backProfile.GetSize().width, backProfile.GetSize().height,
2225                                    frontProfile.GetSize().width, frontProfile.GetSize().height);
2226                 }
2227             }
2228         }
2229     }
2230     CHECK_RETURN(!frontCamera);
2231     frontCamera->modeVideoProfiles_[normalMode] = alignFrontVideoProfiles;
2232     for (auto& frontProfile : alignFrontVideoProfiles) {
2233         MEDIA_INFO_LOG("CameraManager::AlignVideoFpsProfile frontProfile "
2234                        "w(%{public}d),h(%{public}d) fps min(%{public}d),min(%{public}d)",
2235             frontProfile.GetSize().width, frontProfile.GetSize().height, frontProfile.framerates_[minIndex],
2236             frontProfile.framerates_[maxIndex]);
2237     }
2238 }
2239 
GetFallbackConfigMode(SceneMode profileMode,ProfilesWrapper & profilesWrapper)2240 SceneMode CameraManager::GetFallbackConfigMode(SceneMode profileMode, ProfilesWrapper& profilesWrapper)
2241 {
2242     MEDIA_DEBUG_LOG("CameraManager::GetFallbackConfigMode profileMode:%{public}d", profileMode);
2243     // LCOV_EXCL_START
2244     if (profilesWrapper.photoProfiles.empty() && profilesWrapper.previewProfiles.empty() &&
2245         profilesWrapper.vidProfiles.empty()) {
2246         switch (profileMode) {
2247             case CAPTURE_MACRO:
2248                 return CAPTURE;
2249             case VIDEO_MACRO:
2250                 return VIDEO;
2251             default:
2252                 return profileMode;
2253         }
2254     }
2255     // LCOV_EXCL_STOP
2256     return profileMode;
2257 }
2258 
CreateCameraInput(sptr<CameraInfo> & camera)2259 sptr<CameraInput> CameraManager::CreateCameraInput(sptr<CameraInfo> &camera)
2260 {
2261     CAMERA_SYNC_TRACE;
2262     sptr<CameraInput> cameraInput = nullptr;
2263     return cameraInput;
2264 }
2265 
CreateCameraInput(sptr<CameraDevice> & camera)2266 sptr<CameraInput> CameraManager::CreateCameraInput(sptr<CameraDevice> &camera)
2267 {
2268     CAMERA_SYNC_TRACE;
2269     sptr<CameraInput> cameraInput = nullptr;
2270     int32_t retCode = CreateCameraInput(camera, &cameraInput);
2271     CHECK_RETURN_RET_ELOG(retCode != CameraErrorCode::SUCCESS, nullptr,
2272         "CameraManager::CreateCameraInput Failed to create camera input with error code:%{public}d", retCode);
2273 
2274     return cameraInput;
2275 }
2276 
ReportEvent(const string & cameraId)2277 void CameraManager::ReportEvent(const string& cameraId)
2278 {
2279     int pid = IPCSkeleton::GetCallingPid();
2280     int uid = IPCSkeleton::GetCallingUid();
2281     auto clientName = "";
2282     POWERMGR_SYSEVENT_CAMERA_CONNECT(pid, uid, cameraId, clientName);
2283 
2284     stringstream ss;
2285     const std::string S_CUR_CAMERAID = "curCameraId:";
2286     const std::string S_CPID = ",cPid:";
2287     const std::string S_CUID = ",cUid:";
2288     const std::string S_CBUNDLENAME = ",cBundleName:";
2289     ss << S_CUR_CAMERAID << cameraId
2290     << S_CPID << pid
2291     << S_CUID << uid
2292     << S_CBUNDLENAME << clientName;
2293 
2294     HiSysEventWrite(
2295         HiviewDFX::HiSysEvent::Domain::CAMERA,
2296         "USER_BEHAVIOR",
2297         HiviewDFX::HiSysEvent::EventType::BEHAVIOR,
2298         "MSG", ss.str());
2299 }
2300 
CreateCameraInput(sptr<CameraDevice> & camera,sptr<CameraInput> * pCameraInput)2301 int CameraManager::CreateCameraInput(sptr<CameraDevice> &camera, sptr<CameraInput> *pCameraInput)
2302 {
2303     CAMERA_SYNC_TRACE;
2304     CHECK_RETURN_RET_ELOG(camera == nullptr, CameraErrorCode::INVALID_ARGUMENT,
2305         "CameraManager::CreateCameraInput Camera object is null");
2306     CHECK_EXECUTE(camera->GetPosition() == CameraPosition::CAMERA_POSITION_FOLD_INNER, ReportEvent(camera->GetID()));
2307 
2308     // Check for API compatibility
2309     FoldStatus curFoldStatus = GetFoldStatus();
2310     MEDIA_INFO_LOG("CreateCameraInput curFoldStatus:%{public}d, position:%{public}d", curFoldStatus,
2311         camera->GetPosition());
2312     uint32_t apiCompatibleVersion = CameraApiVersion::GetApiVersion();
2313     bool isFoldV4 = (!foldScreenType_.empty() && foldScreenType_[0] == '4');
2314     bool isApiCompatRequired = (apiCompatibleVersion < CameraApiVersion::APIVersion::API_FOURTEEN || isFoldV4);
2315     bool isFoldStatusValid = (curFoldStatus == FoldStatus::EXPAND) || (curFoldStatus == FoldStatus::HALF_FOLD) ||
2316         (isFoldV4 && curFoldStatus == FoldStatus::UNKNOWN_FOLD);
2317     bool isFrontCamera = (camera->GetPosition() == CameraPosition::CAMERA_POSITION_FRONT);
2318     // LCOV_EXCL_START
2319     if (isApiCompatRequired && isFoldStatusValid && isFrontCamera) {
2320         std::vector<sptr<CameraDevice>> cameraObjList = GetSupportedCameras();
2321         sptr<CameraDevice> cameraInfo;
2322         for (const auto& cameraDevice : cameraObjList) {
2323             if (cameraDevice != nullptr &&
2324                 cameraDevice->GetPosition() == CameraPosition::CAMERA_POSITION_FOLD_INNER) {
2325                 camera = cameraDevice;
2326                 break;
2327             }
2328         }
2329     }
2330     // LCOV_EXCL_STOP
2331     sptr<ICameraDeviceService> deviceObj = nullptr;
2332     int32_t retCode = CreateCameraDevice(camera->GetID(), &deviceObj);
2333     CHECK_RETURN_RET_ELOG(retCode != CameraErrorCode::SUCCESS, retCode,
2334         "CameraManager::CreateCameraInput Returning null in CreateCameraInput");
2335     sptr<CameraInput> cameraInput = new(std::nothrow) CameraInput(deviceObj, camera);
2336     CHECK_RETURN_RET_ELOG(cameraInput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
2337         "CameraManager::CreateCameraInput failed to new cameraInput!");
2338     *pCameraInput = cameraInput;
2339     return CameraErrorCode::SUCCESS;
2340 }
2341 
CreateCameraInput(CameraPosition position,CameraType cameraType)2342 sptr<CameraInput> CameraManager::CreateCameraInput(CameraPosition position, CameraType cameraType)
2343 {
2344     CAMERA_SYNC_TRACE;
2345     sptr<CameraInput> cameraInput = nullptr;
2346     int32_t retCode = CreateCameraInput(position, cameraType, &cameraInput);
2347     CHECK_RETURN_RET_ELOG(retCode != CameraErrorCode::SUCCESS, nullptr,
2348         "CameraManager::CreateCameraInput Failed to CreateCameraInput with error code:%{public}d", retCode);
2349     return cameraInput;
2350 }
2351 
CreateCameraInput(CameraPosition position,CameraType cameraType,sptr<CameraInput> * pCameraInput)2352 int CameraManager::CreateCameraInput(CameraPosition position, CameraType cameraType, sptr<CameraInput> *pCameraInput)
2353 {
2354     CAMERA_SYNC_TRACE;
2355     sptr<CameraInput> cameraInput = nullptr;
2356     std::vector<sptr<CameraDevice>> cameraDeviceList = GetSupportedCameras();
2357     for (size_t i = 0; i < cameraDeviceList.size(); i++) {
2358         MEDIA_DEBUG_LOG("CreateCameraInput position:%{public}d, Camera Type:%{public}d",
2359             cameraDeviceList[i]->GetPosition(), cameraDeviceList[i]->GetCameraType());
2360         // LCOV_EXCL_START
2361         if ((cameraDeviceList[i]->GetPosition() == position) && (cameraDeviceList[i]->GetCameraType() == cameraType)) {
2362             cameraInput = CreateCameraInput(cameraDeviceList[i]);
2363             break;
2364         }
2365         // LCOV_EXCL_STOP
2366     }
2367     CHECK_RETURN_RET_ELOG(!cameraInput, CameraErrorCode::SERVICE_FATL_ERROR,
2368         "No Camera Device for Camera position:%{public}d, Camera Type:%{public}d", position, cameraType);
2369     // LCOV_EXCL_START
2370     *pCameraInput = cameraInput;
2371     return CameraErrorCode::SUCCESS;
2372     // LCOV_EXCL_STOP
2373 }
2374 
g_isCapabilitySupported(std::shared_ptr<OHOS::Camera::CameraMetadata> metadata,camera_metadata_item_t & item,uint32_t metadataTag)2375 bool g_isCapabilitySupported(std::shared_ptr<OHOS::Camera::CameraMetadata> metadata,
2376     camera_metadata_item_t &item, uint32_t metadataTag)
2377 {
2378     CHECK_RETURN_RET(metadata == nullptr, false);
2379     bool isSupport = true;
2380     int32_t retCode = Camera::FindCameraMetadataItem(metadata->get(), metadataTag, &item);
2381     if (retCode != CAM_META_SUCCESS || item.count == 0) {
2382         MEDIA_DEBUG_LOG("Failed get metadata info tag = %{public}d, retCode = %{public}d, count = %{public}d",
2383             metadataTag, retCode, item.count);
2384         isSupport = false;
2385     }
2386     return isSupport;
2387 }
2388 
ParseBasicCapability(ProfilesWrapper & profilesWrapper,std::shared_ptr<OHOS::Camera::CameraMetadata> metadata,const camera_metadata_item_t & item)2389 void CameraManager::ParseBasicCapability(ProfilesWrapper& profilesWrapper,
2390     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata, const camera_metadata_item_t& item)
2391 {
2392     CHECK_RETURN(metadata == nullptr);
2393     uint32_t widthOffset = 1;
2394     uint32_t heightOffset = 2;
2395     const uint8_t UNIT_STEP = 3;
2396     const uint8_t FPS_STEP = 2;
2397 
2398     CameraFormat format = CAMERA_FORMAT_INVALID;
2399     Size size;
2400     // LCOV_EXCL_START
2401     for (uint32_t i = 0; i < item.count; i += UNIT_STEP) {
2402         auto itr = metaToFwCameraFormat_.find(static_cast<camera_format_t>(item.data.i32[i]));
2403         if (itr != metaToFwCameraFormat_.end()) {
2404             format = itr->second;
2405         } else {
2406             format = CAMERA_FORMAT_INVALID;
2407             MEDIA_ERR_LOG("format %{public}d is not supported now", item.data.i32[i]);
2408             continue;
2409         }
2410         size.width = static_cast<uint32_t>(item.data.i32[i + widthOffset]);
2411         size.height = static_cast<uint32_t>(item.data.i32[i + heightOffset]);
2412         Profile profile = Profile(format, size);
2413 #ifdef CAMERA_EMULATOR
2414         if (format != CAMERA_FORMAT_RGBA_8888) {
2415             continue;
2416         }
2417         profilesWrapper.photoProfiles.push_back(profile);
2418 #else
2419         if (format == CAMERA_FORMAT_JPEG) {
2420             profilesWrapper.photoProfiles.push_back(profile);
2421             continue;
2422         }
2423 #endif
2424         profilesWrapper.previewProfiles.push_back(profile);
2425         camera_metadata_item_t fpsItem;
2426         int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_FPS_RANGES, &fpsItem);
2427         if (ret != CAM_META_SUCCESS) {
2428             continue;
2429         }
2430         for (uint32_t j = 0; j < (fpsItem.count - 1); j += FPS_STEP) {
2431             std::vector<int32_t> fps = { fpsItem.data.i32[j], fpsItem.data.i32[j + 1] };
2432             VideoProfile vidProfile = VideoProfile(format, size, fps);
2433             profilesWrapper.vidProfiles.push_back(vidProfile);
2434         }
2435     }
2436     // LCOV_EXCL_STOP
2437 }
2438 
ParseExtendCapability(ProfilesWrapper & profilesWrapper,const int32_t modeName,const camera_metadata_item_t & item)2439 void CameraManager::ParseExtendCapability(ProfilesWrapper& profilesWrapper, const int32_t modeName,
2440     const camera_metadata_item_t& item) __attribute__((no_sanitize("cfi")))
2441 {
2442     ExtendInfo extendInfo = {};
2443     std::shared_ptr<CameraStreamInfoParse> modeStreamParse = std::make_shared<CameraStreamInfoParse>();
2444     modeStreamParse->getModeInfo(item.data.i32, item.count, extendInfo); // 解析tag中带的数据信息意义
2445     // LCOV_EXCL_START
2446     if (modeName == SceneMode::VIDEO) {
2447         for (uint32_t i = 0; i < extendInfo.modeCount; i++) {
2448             SceneMode scMode = SceneMode::NORMAL;
2449             CHECK_PRINT_ELOG(!ConvertMetaToFwkMode(static_cast<OperationMode>(extendInfo.modeInfo[i].modeName),
2450                 scMode), "ParseExtendCapability mode = %{public}d", extendInfo.modeInfo[i].modeName);
2451             if (SceneMode::HIGH_FRAME_RATE != scMode) {
2452                 continue;
2453             }
2454             for (uint32_t j = 0; j < extendInfo.modeInfo[i].streamTypeCount; j++) {
2455                 OutputCapStreamType streamType =
2456                     static_cast<OutputCapStreamType>(extendInfo.modeInfo[i].streamInfo[j].streamType);
2457                 CreateProfile4StreamType(profilesWrapper, streamType, i, j, extendInfo);
2458             }
2459         }
2460     }
2461     for (uint32_t i = 0; i < extendInfo.modeCount; i++) {
2462         SceneMode scMode = SceneMode::NORMAL;
2463         CHECK_PRINT_ELOG(!ConvertMetaToFwkMode(static_cast<OperationMode>(extendInfo.modeInfo[i].modeName),
2464             scMode), "ParseExtendCapability mode = %{public}d", extendInfo.modeInfo[i].modeName);
2465         if (modeName == scMode) {
2466             for (uint32_t j = 0; j < extendInfo.modeInfo[i].streamTypeCount; j++) {
2467                 OutputCapStreamType streamType =
2468                     static_cast<OutputCapStreamType>(extendInfo.modeInfo[i].streamInfo[j].streamType);
2469                 CreateProfile4StreamType(profilesWrapper, streamType, i, j, extendInfo);
2470             }
2471             break;
2472         }
2473     }
2474     // LCOV_EXCL_STOP
2475 }
2476 
ParseDepthCapability(const int32_t modeName,const camera_metadata_item_t & item)2477 void CameraManager::ParseDepthCapability(const int32_t modeName, const camera_metadata_item_t& item)
2478     __attribute__((no_sanitize("cfi")))
2479 {
2480     ExtendInfo extendInfo = {};
2481     std::shared_ptr<CameraDepthInfoParse> depthStreamParse = std::make_shared<CameraDepthInfoParse>();
2482     depthStreamParse->getModeInfo(item.data.i32, item.count, extendInfo); // 解析tag中带的数据信息意义
2483     for (uint32_t i = 0; i < extendInfo.modeCount; i++) {
2484         if (modeName == extendInfo.modeInfo[i].modeName) {
2485             for (uint32_t j = 0; j < extendInfo.modeInfo[i].streamTypeCount; j++) {
2486                 OutputCapStreamType streamType =
2487                     static_cast<OutputCapStreamType>(extendInfo.modeInfo[i].streamInfo[j].streamType);
2488                 CreateDepthProfile4StreamType(streamType, i, j, extendInfo);
2489             }
2490             break;
2491         }
2492     }
2493 }
2494 
CreateDepthProfile4StreamType(OutputCapStreamType streamType,uint32_t modeIndex,uint32_t streamIndex,ExtendInfo extendInfo)2495 void CameraManager::CreateDepthProfile4StreamType(OutputCapStreamType streamType, uint32_t modeIndex,
2496     uint32_t streamIndex, ExtendInfo extendInfo) __attribute__((no_sanitize("cfi")))
2497 {
2498     // LCOV_EXCL_START
2499     for (uint32_t k = 0; k < extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfoCount; k++) {
2500         const auto& detailInfo = extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfo[k];
2501         CameraFormat format = CAMERA_FORMAT_INVALID;
2502         auto itr = metaToFwCameraFormat_.find(static_cast<camera_format_t>(detailInfo.format));
2503         if (itr != metaToFwCameraFormat_.end()) {
2504             format = itr->second;
2505         } else {
2506             MEDIA_ERR_LOG("CreateDepthProfile4StreamType failed format = %{public}d",
2507                 extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfo[k].format);
2508             format = CAMERA_FORMAT_INVALID;
2509             continue;
2510         }
2511         Size size{static_cast<uint32_t>(detailInfo.width), static_cast<uint32_t>(detailInfo.height)};
2512         DepthDataAccuracy dataAccuracy = DEPTH_DATA_ACCURACY_INVALID;
2513         auto it = metaToFwDepthDataAccuracy_.find(static_cast<DepthDataAccuracyType>(detailInfo.dataAccuracy));
2514         if (it != metaToFwDepthDataAccuracy_.end()) {
2515             dataAccuracy = it->second;
2516         } else {
2517             MEDIA_ERR_LOG("CreateDepthProfile4StreamType failed dataAccuracy = %{public}d",
2518                 extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfo[k].dataAccuracy);
2519             dataAccuracy = DEPTH_DATA_ACCURACY_INVALID;
2520             continue;
2521         }
2522         MEDIA_DEBUG_LOG("streamType: %{public}d, OutputCapStreamType::DEPTH: %{public}d", streamType,
2523             OutputCapStreamType::DEPTH);
2524         DepthProfile depthProfile = DepthProfile(format, dataAccuracy, size);
2525         MEDIA_DEBUG_LOG("depthdata format : %{public}d, data accuracy: %{public}d, width: %{public}d,"
2526             "height: %{public}d", depthProfile.GetCameraFormat(), depthProfile.GetDataAccuracy(),
2527             depthProfile.GetSize().width, depthProfile.GetSize().height);
2528         depthProfiles_.push_back(depthProfile);
2529     }
2530     // LCOV_EXCL_STOP
2531 }
2532 
ParseProfileLevel(ProfilesWrapper & profilesWrapper,const int32_t modeName,const camera_metadata_item_t & item)2533 void CameraManager::ParseProfileLevel(ProfilesWrapper& profilesWrapper, const int32_t modeName,
2534     const camera_metadata_item_t& item) __attribute__((no_sanitize("cfi")))
2535 {
2536     std::vector<SpecInfo> specInfos;
2537     ProfileLevelInfo modeInfo = {};
2538     if (IsSystemApp() && modeName == SceneMode::VIDEO) {
2539         // LCOV_EXCL_START
2540         CameraAbilityParseUtil::GetModeInfo(SceneMode::HIGH_FRAME_RATE, item, modeInfo);
2541         specInfos.insert(specInfos.end(), modeInfo.specInfos.begin(), modeInfo.specInfos.end());
2542         // LCOV_EXCL_STOP
2543     }
2544     CameraAbilityParseUtil::GetModeInfo(modeName, item, modeInfo);
2545     specInfos.insert(specInfos.end(), modeInfo.specInfos.begin(), modeInfo.specInfos.end());
2546     for (SpecInfo& specInfo : specInfos) {
2547         MEDIA_DEBUG_LOG("modeName: %{public}d specId: %{public}d", modeName, specInfo.specId);
2548         for (StreamInfo& streamInfo : specInfo.streamInfos) {
2549             CreateProfileLevel4StreamType(profilesWrapper, specInfo.specId, streamInfo);
2550         }
2551     }
2552 }
2553 
CreateProfileLevel4StreamType(ProfilesWrapper & profilesWrapper,int32_t specId,StreamInfo & streamInfo)2554 void CameraManager::CreateProfileLevel4StreamType(
2555     ProfilesWrapper& profilesWrapper, int32_t specId, StreamInfo& streamInfo) __attribute__((no_sanitize("cfi")))
2556 {
2557     auto getCameraFormat = [&](camera_format_t format) -> CameraFormat {
2558         auto itr = metaToFwCameraFormat_.find(format);
2559         if (itr != metaToFwCameraFormat_.end()) {
2560             return itr->second;
2561         } else {
2562             // LCOV_EXCL_START
2563             MEDIA_ERR_LOG("CreateProfile4StreamType failed format = %{public}d", format);
2564             return CAMERA_FORMAT_INVALID;
2565             // LCOV_EXCL_STOP
2566         }
2567     };
2568 
2569     OutputCapStreamType streamType = static_cast<OutputCapStreamType>(streamInfo.streamType);
2570 
2571     for (const auto &detailInfo : streamInfo.detailInfos) {
2572         CameraFormat format = getCameraFormat(static_cast<camera_format_t>(detailInfo.format));
2573         if (format == CAMERA_FORMAT_INVALID) {
2574             continue;
2575         }
2576         Size size{detailInfo.width, detailInfo.height};
2577         Fps fps{detailInfo.fixedFps, detailInfo.minFps, detailInfo.maxFps};
2578         std::vector<uint32_t> abilityId = detailInfo.abilityIds;
2579         std::string abilityIds = Container2String(abilityId.begin(), abilityId.end());
2580         if (streamType == OutputCapStreamType::PREVIEW) {
2581             Profile previewProfile = Profile(format, size, fps, abilityId, specId);
2582             profilesWrapper.previewProfiles.push_back(previewProfile);
2583             previewProfile.DumpProfile("preview");
2584         } else if (streamType == OutputCapStreamType::STILL_CAPTURE) {
2585             Profile snapProfile = Profile(format, size, fps, abilityId, specId);
2586             profilesWrapper.photoProfiles.push_back(snapProfile);
2587             snapProfile.DumpProfile("photo");
2588         } else if (streamType == OutputCapStreamType::VIDEO_STREAM) {
2589             std::vector<int32_t> frameRates = {fps.minFps, fps.maxFps};
2590             VideoProfile vidProfile = VideoProfile(format, size, frameRates, specId);
2591             profilesWrapper.vidProfiles.push_back(vidProfile);
2592             vidProfile.DumpVideoProfile("video");
2593         }
2594     }
2595 }
2596 
ParseCapability(ProfilesWrapper & profilesWrapper,sptr<CameraDevice> & camera,const int32_t modeName,camera_metadata_item_t & item,std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)2597 void CameraManager::ParseCapability(ProfilesWrapper& profilesWrapper, sptr<CameraDevice>& camera,
2598     const int32_t modeName, camera_metadata_item_t& item, std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)
2599 {
2600     if (g_isCapabilitySupported(metadata, item, OHOS_ABILITY_AVAILABLE_PROFILE_LEVEL)) {
2601         std::vector<SceneMode> supportedModes = GetSupportedModes(camera);
2602         int32_t mode = (supportedModes.empty() && isTemplateMode_.count(modeName)) ? SceneMode::NORMAL : modeName;
2603         MEDIA_INFO_LOG("ParseProfileLevel by device = %{public}s, mode = %{public}d", camera->GetID().c_str(), mode);
2604         ParseProfileLevel(profilesWrapper, mode, item);
2605     } else if (g_isCapabilitySupported(metadata, item, OHOS_ABILITY_STREAM_AVAILABLE_EXTEND_CONFIGURATIONS)) {
2606         std::vector<SceneMode> supportedModes = GetSupportedModes(camera);
2607         int32_t mode = (supportedModes.empty() && isTemplateMode_.count(modeName)) ? SceneMode::NORMAL : modeName;
2608         MEDIA_INFO_LOG("ParseCapability by device = %{public}s, mode = %{public}d", camera->GetID().c_str(), mode);
2609         ParseExtendCapability(profilesWrapper, mode, item);
2610     } else if (g_isCapabilitySupported(metadata, item, OHOS_ABILITY_STREAM_AVAILABLE_BASIC_CONFIGURATIONS)) {
2611         ParseBasicCapability(profilesWrapper, metadata, item);
2612     } else {
2613         MEDIA_ERR_LOG("Failed get stream info");
2614     }
2615     // 解析深度流信息
2616     if (g_isCapabilitySupported(metadata, item, OHOS_ABILITY_DEPTH_DATA_PROFILES)) {
2617         std::vector<SceneMode> supportedModes = GetSupportedModes(camera);
2618         int32_t mode = (supportedModes.empty() && isTemplateMode_.count(modeName)) ? SceneMode::NORMAL : modeName;
2619         MEDIA_INFO_LOG("Depth g_isCapabilitySupported by device = %{public}s, mode = %{public}d, tag = %{public}d",
2620             camera->GetID().c_str(), mode, OHOS_ABILITY_DEPTH_DATA_PROFILES);
2621         ParseDepthCapability(mode, item);
2622     }
2623 }
2624 
GetSupportedOutputCapability(sptr<CameraDevice> & cameraDevice,int32_t modeName)2625 sptr<CameraOutputCapability> CameraManager::GetSupportedOutputCapability(sptr<CameraDevice>& cameraDevice,
2626     int32_t modeName) __attribute__((no_sanitize("cfi")))
2627 {
2628     MEDIA_DEBUG_LOG("GetSupportedOutputCapability mode = %{public}d", modeName);
2629     auto camera = cameraDevice;
2630     auto innerCamera = GetInnerCamera();
2631     if (!foldScreenType_.empty() && foldScreenType_[0] == '4' &&
2632         camera->GetPosition() == CAMERA_POSITION_FRONT && innerCamera && !GetIsInWhiteList() &&
2633         (GetFoldStatus() == FoldStatus::EXPAND || GetFoldStatus() == FoldStatus::UNKNOWN_FOLD)) {
2634         MEDIA_DEBUG_LOG("GetSupportedOutputCapability innerCamera Position = %{public}d", innerCamera->GetPosition());
2635         camera = innerCamera;
2636     }
2637     CHECK_RETURN_RET(camera == nullptr, nullptr);
2638     sptr<CameraOutputCapability> cameraOutputCapability = new (std::nothrow) CameraOutputCapability();
2639     CHECK_RETURN_RET(cameraOutputCapability == nullptr, nullptr);
2640     cameraOutputCapability->SetPhotoProfiles(camera->modePhotoProfiles_[modeName]);
2641     cameraOutputCapability->SetPreviewProfiles(camera->modePreviewProfiles_[modeName]);
2642     if (!isPhotoMode_.count(modeName)) {
2643         cameraOutputCapability->SetVideoProfiles(camera->modeVideoProfiles_[modeName]);
2644     }
2645     cameraOutputCapability->SetDepthProfiles(camera->modeDepthProfiles_[modeName]);
2646 
2647     std::vector<MetadataObjectType> objectTypes = camera->GetObjectTypes();
2648 
2649     if (!CameraSecurity::CheckSystemApp()) {
2650         MEDIA_DEBUG_LOG("public calling for GetsupportedOutputCapability");
2651         if (std::any_of(objectTypes.begin(), objectTypes.end(),
2652                         [](MetadataObjectType type) { return type == MetadataObjectType::FACE; })) {
2653             cameraOutputCapability->SetSupportedMetadataObjectType({MetadataObjectType::FACE});
2654         } else {
2655             cameraOutputCapability->SetSupportedMetadataObjectType({});
2656         }
2657     } else {
2658         cameraOutputCapability->SetSupportedMetadataObjectType(objectTypes);
2659     }
2660     return cameraOutputCapability;
2661 }
2662 
ParseSupportedOutputCapability(sptr<CameraDevice> & camera,int32_t modeName,std::shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility)2663 sptr<CameraOutputCapability> CameraManager::ParseSupportedOutputCapability(sptr<CameraDevice>& camera, int32_t modeName,
2664     std::shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility)
2665 {
2666     MEDIA_DEBUG_LOG("GetSupportedOutputCapability mode = %{public}d", modeName);
2667     CHECK_RETURN_RET(camera == nullptr || cameraAbility == nullptr, nullptr);
2668     sptr<CameraOutputCapability> cameraOutputCapability = new (std::nothrow) CameraOutputCapability();
2669     CHECK_RETURN_RET(cameraOutputCapability == nullptr, nullptr);
2670     camera_metadata_item_t item;
2671     ProfilesWrapper profilesWrapper = {};
2672     depthProfiles_.clear();
2673     photoFormats_.clear();
2674     photoFormats_ = GetSupportPhotoFormat(modeName, cameraAbility);
2675 
2676     ParseCapability(profilesWrapper, camera, modeName, item, cameraAbility);
2677     SceneMode profileMode = static_cast<SceneMode>(modeName);
2678     auto fallbackMode = GetFallbackConfigMode(profileMode, profilesWrapper);
2679     if (profileMode != fallbackMode) {
2680         ParseCapability(profilesWrapper, camera, fallbackMode, item, cameraAbility);
2681     }
2682     FillSupportPhotoFormats(profilesWrapper.photoProfiles);
2683     CHECK_EXECUTE(!IsSystemApp() && modeName == static_cast<int32_t>(SceneMode::CAPTURE),
2684         FillSupportPreviewFormats(profilesWrapper.previewProfiles));
2685     cameraOutputCapability->SetPhotoProfiles(profilesWrapper.photoProfiles);
2686     cameraOutputCapability->SetPreviewProfiles(profilesWrapper.previewProfiles);
2687     if (!isPhotoMode_.count(modeName)) {
2688         cameraOutputCapability->SetVideoProfiles(profilesWrapper.vidProfiles);
2689     }
2690     cameraOutputCapability->SetDepthProfiles(depthProfiles_);
2691     MEDIA_DEBUG_LOG("SetPhotoProfiles size = %{public}zu,SetPreviewProfiles size = %{public}zu"
2692         "SetVideoProfiles size = %{public}zu,SetDepthProfiles size = %{public}zu",
2693         profilesWrapper.photoProfiles.size(), profilesWrapper.previewProfiles.size(),
2694         profilesWrapper.vidProfiles.size(), depthProfiles_.size());
2695     return cameraOutputCapability;
2696 }
2697 
GetSupportPhotoFormat(const int32_t modeName,std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)2698 vector<CameraFormat> CameraManager::GetSupportPhotoFormat(const int32_t modeName,
2699     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)
2700 {
2701     // LCOV_EXCL_START
2702     CHECK_RETURN_RET(metadata == nullptr, {});
2703     vector<CameraFormat> photoFormats = {};
2704     camera_metadata_item_t item;
2705     int32_t metadataTag = OHOS_STREAM_AVAILABLE_FORMATS;
2706     int32_t retCode = OHOS::Camera::FindCameraMetadataItem(metadata->get(), metadataTag, &item);
2707     CHECK_RETURN_RET_ELOG(retCode != CAM_META_SUCCESS || item.count == 0, photoFormats,
2708         "Failed get metadata info tag = %{public}d, retCode = %{public}d, count = %{public}d",
2709         metadataTag, retCode, item.count);
2710     vector<int32_t> formats = {};
2711     std::map<int32_t, vector<int32_t> > modePhotoFormats = {};
2712     for (uint32_t i = 0; i < item.count; i++) {
2713         if (item.data.i32[i] != -1) {
2714             formats.push_back(item.data.i32[i]);
2715             continue;
2716         } else {
2717             modePhotoFormats.insert(std::make_pair(modeName, std::move(formats)));
2718             formats.clear();
2719         }
2720     }
2721     CHECK_RETURN_RET_ELOG(!modePhotoFormats.count(modeName), photoFormats,
2722         "GetSupportPhotoFormat not support mode = %{public}d", modeName);
2723     for (auto &val : modePhotoFormats[modeName]) {
2724         camera_format_t hdiFomart = static_cast<camera_format_t>(val);
2725         CHECK_EXECUTE(metaToFwCameraFormat_.count(hdiFomart),
2726             photoFormats.push_back(metaToFwCameraFormat_.at(hdiFomart)));
2727     }
2728     MEDIA_DEBUG_LOG("GetSupportPhotoFormat, mode = %{public}d, formats = %{public}s", modeName,
2729         Container2String(photoFormats.begin(), photoFormats.end()).c_str());
2730     return photoFormats;
2731     // LCOV_EXCL_STOP
2732 }
2733 
IsSystemApp()2734 bool CameraManager::IsSystemApp()
2735 {
2736     return isSystemApp_;
2737 }
2738 
CreateProfile4StreamType(ProfilesWrapper & profilesWrapper,OutputCapStreamType streamType,uint32_t modeIndex,uint32_t streamIndex,ExtendInfo extendInfo)2739 void CameraManager::CreateProfile4StreamType(ProfilesWrapper& profilesWrapper, OutputCapStreamType streamType,
2740     uint32_t modeIndex, uint32_t streamIndex, ExtendInfo extendInfo) __attribute__((no_sanitize("cfi")))
2741 {
2742     const int frameRate120 = 120;
2743     const int frameRate240 = 240;
2744     for (uint32_t k = 0; k < extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfoCount; k++) {
2745         const auto& detailInfo = extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfo[k];
2746         // Skip profiles with unsupported frame rates for non-system apps
2747         if ((detailInfo.minFps == frameRate120 || detailInfo.minFps == frameRate240) &&
2748             streamType == OutputCapStreamType::VIDEO_STREAM && !IsSystemApp()) {
2749             continue;
2750         }
2751         CameraFormat format = CAMERA_FORMAT_INVALID;
2752         auto itr = metaToFwCameraFormat_.find(static_cast<camera_format_t>(detailInfo.format));
2753         if (itr != metaToFwCameraFormat_.end()) {
2754             format = itr->second;
2755         } else {
2756             MEDIA_ERR_LOG("CreateProfile4StreamType failed format = %{public}d",
2757                 extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfo[k].format);
2758             format = CAMERA_FORMAT_INVALID;
2759             continue;
2760         }
2761         Size size { static_cast<uint32_t>(detailInfo.width), static_cast<uint32_t>(detailInfo.height) };
2762         Fps fps { static_cast<uint32_t>(detailInfo.fixedFps), static_cast<uint32_t>(detailInfo.minFps),
2763             static_cast<uint32_t>(detailInfo.maxFps) };
2764         std::vector<uint32_t> abilityId = detailInfo.abilityId;
2765         std::string abilityIds = Container2String(abilityId.begin(), abilityId.end());
2766         if (streamType == OutputCapStreamType::PREVIEW) {
2767             Profile previewProfile = Profile(format, size, fps, abilityId);
2768             profilesWrapper.previewProfiles.push_back(previewProfile);
2769             previewProfile.DumpProfile("preview");
2770         } else if (streamType == OutputCapStreamType::STILL_CAPTURE) {
2771             Profile snapProfile = Profile(format, size, fps, abilityId);
2772             profilesWrapper.photoProfiles.push_back(snapProfile);
2773             snapProfile.DumpProfile("photo");
2774         } else if (streamType == OutputCapStreamType::VIDEO_STREAM) {
2775             std::vector<int32_t> frameRates = { fps.minFps, fps.maxFps };
2776             VideoProfile vidProfile = VideoProfile(format, size, frameRates);
2777             profilesWrapper.vidProfiles.push_back(vidProfile);
2778             vidProfile.DumpVideoProfile("video");
2779         }
2780     }
2781 }
2782 
GetCameraMetadataFormat(CameraFormat format)2783 camera_format_t CameraManager::GetCameraMetadataFormat(CameraFormat format)
2784 {
2785     camera_format_t metaFormat = OHOS_CAMERA_FORMAT_YCRCB_420_SP;
2786     MEDIA_DEBUG_LOG("format = %{public}d", static_cast<int32_t>(format));
2787 
2788     auto itr = fwToMetaCameraFormat_.find(format);
2789     if (itr != fwToMetaCameraFormat_.end()) {
2790         metaFormat = itr->second;
2791     }
2792     MEDIA_DEBUG_LOG("metaFormat = %{public}d", static_cast<int32_t>(metaFormat));
2793     return metaFormat;
2794 }
2795 
SetCameraManager(wptr<CameraManager> cameraManager)2796 void CameraManagerGetter::SetCameraManager(wptr<CameraManager> cameraManager)
2797 {
2798     cameraManager_ = cameraManager;
2799 }
2800 
GetCameraManager()2801 sptr<CameraManager> CameraManagerGetter::GetCameraManager()
2802 {
2803     return cameraManager_.promote();
2804 }
2805 
OnTorchStatusChange(const TorchStatus status)2806 int32_t TorchServiceListenerManager::OnTorchStatusChange(const TorchStatus status)
2807 {
2808     MEDIA_DEBUG_LOG("TorchStatus is %{public}d", status);
2809     auto cameraManager = GetCameraManager();
2810     CHECK_RETURN_RET_ELOG(cameraManager == nullptr, CAMERA_OK, "OnTorchStatusChange CameraManager is nullptr");
2811 
2812     TorchStatusInfo torchStatusInfo;
2813     if (status == TorchStatus::TORCH_STATUS_UNAVAILABLE) {
2814         torchStatusInfo.isTorchAvailable = false;
2815         torchStatusInfo.isTorchActive = false;
2816         torchStatusInfo.torchLevel = 0;
2817         cameraManager->UpdateTorchMode(TORCH_MODE_OFF);
2818     } else if (status == TorchStatus::TORCH_STATUS_ON) {
2819         // LCOV_EXCL_START
2820         torchStatusInfo.isTorchAvailable = true;
2821         torchStatusInfo.isTorchActive = true;
2822         torchStatusInfo.torchLevel = 1;
2823         cameraManager->UpdateTorchMode(TORCH_MODE_ON);
2824         // LCOV_EXCL_STOP
2825     } else if (status == TorchStatus::TORCH_STATUS_OFF) {
2826         torchStatusInfo.isTorchAvailable = true;
2827         torchStatusInfo.isTorchActive = false;
2828         torchStatusInfo.torchLevel = 0;
2829         cameraManager->UpdateTorchMode(TORCH_MODE_OFF);
2830     }
2831     auto listener = cameraManager->GetTorchServiceListenerManager();
2832     listener->TriggerListener([&](auto listener) { listener->OnTorchStatusChange(torchStatusInfo); });
2833     listener->cachedTorchStatus_ = torchStatusInfo;
2834     return CAMERA_OK;
2835 }
2836 
OnFoldStatusChanged(const FoldStatus status)2837 int32_t FoldStatusListenerManager::OnFoldStatusChanged(const FoldStatus status)
2838 {
2839     // LCOV_EXCL_START
2840     MEDIA_DEBUG_LOG("FoldStatus is %{public}d", status);
2841     auto cameraManager = GetCameraManager();
2842     CHECK_RETURN_RET_ELOG(cameraManager == nullptr, CAMERA_OK, "OnFoldStatusChanged CameraManager is nullptr");
2843 
2844     FoldStatusInfo foldStatusInfo;
2845     foldStatusInfo.foldStatus = status;
2846     foldStatusInfo.supportedCameras = cameraManager->GetSupportedCameras();
2847     auto listenerManager = cameraManager->GetFoldStatusListenerManager();
2848     MEDIA_DEBUG_LOG("FoldListeners size %{public}zu", listenerManager->GetListenerCount());
2849     listenerManager->TriggerListener([&](auto listener) { listener->OnFoldStatusChanged(foldStatusInfo); });
2850     return CAMERA_OK;
2851     // LCOV_EXCL_STOP
2852 }
2853 
OnControlCenterStatusChanged(bool status)2854 int32_t ControlCenterStatusListenerManager::OnControlCenterStatusChanged(bool status)
2855 {
2856     // LCOV_EXCL_START
2857     MEDIA_INFO_LOG("OnControlCenterStatusChanged");
2858     auto cameraManager = GetCameraManager();
2859     CHECK_RETURN_RET_ELOG(cameraManager == nullptr, CAMERA_OK, "CameraManager is nullptr.");
2860     auto listenerManager = cameraManager->GetControlCenterStatusListenerManager();
2861     MEDIA_INFO_LOG("ControlCenterStatusListener size %{public}zu", listenerManager->GetListenerCount());
2862     listenerManager->TriggerListener([&](auto listener) { listener->OnControlCenterStatusChanged(status); });
2863     return CAMERA_OK;
2864     // LCOV_EXCL_STOP
2865 }
2866 
SetCameraServiceCallback(sptr<ICameraServiceCallback> & callback)2867 int32_t CameraManager::SetCameraServiceCallback(sptr<ICameraServiceCallback>& callback)
2868 {
2869     auto serviceProxy = GetServiceProxy();
2870     CHECK_RETURN_RET_ELOG(
2871         serviceProxy == nullptr, CAMERA_UNKNOWN_ERROR, "CameraManager::SetCameraServiceCallback serviceProxy is null");
2872     int32_t retCode = serviceProxy->SetCameraCallback(callback);
2873     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, retCode,
2874         "SetCameraServiceCallback Set service Callback failed, retCode: %{public}d", retCode);
2875     return CAMERA_OK;
2876 }
2877 
UnSetCameraServiceCallback()2878 int32_t CameraManager::UnSetCameraServiceCallback()
2879 {
2880     // LCOV_EXCL_START
2881     auto serviceProxy = GetServiceProxy();
2882     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CAMERA_UNKNOWN_ERROR,
2883         "CameraManager::UnSetCameraServiceCallback serviceProxy is null");
2884     int32_t retCode = serviceProxy->UnSetCameraCallback();
2885     CHECK_RETURN_RET_ELOG(
2886         retCode != CAMERA_OK, retCode, "UnSetCameraServiceCallback failed, retCode: %{public}d", retCode);
2887     return CAMERA_OK;
2888     // LCOV_EXCL_STOP
2889 }
2890 
SetCameraMuteServiceCallback(sptr<ICameraMuteServiceCallback> & callback)2891 int32_t CameraManager::SetCameraMuteServiceCallback(sptr<ICameraMuteServiceCallback>& callback)
2892 {
2893     auto serviceProxy = GetServiceProxy();
2894     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CAMERA_UNKNOWN_ERROR,
2895         "CameraManager::SetCameraMuteServiceCallback serviceProxy is null");
2896     int32_t retCode = serviceProxy->SetMuteCallback(callback);
2897     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, retCode,
2898         "SetCameraMuteServiceCallback Set Mute service Callback failed, retCode: %{public}d", retCode);
2899     return CAMERA_OK;
2900 }
2901 
UnSetCameraMuteServiceCallback()2902 int32_t CameraManager::UnSetCameraMuteServiceCallback()
2903 {
2904     // LCOV_EXCL_START
2905     auto serviceProxy = GetServiceProxy();
2906     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CAMERA_UNKNOWN_ERROR,
2907         "CameraManager::UnSetCameraMuteServiceCallback serviceProxy is null");
2908     int32_t retCode = serviceProxy->UnSetMuteCallback();
2909     CHECK_RETURN_RET_ELOG(
2910         retCode != CAMERA_OK, retCode, "UnSetCameraMuteServiceCallback failed, retCode: %{public}d", retCode);
2911     return CAMERA_OK;
2912     // LCOV_EXCL_STOP
2913 }
2914 
SetTorchServiceCallback(sptr<ITorchServiceCallback> & callback)2915 int32_t CameraManager::SetTorchServiceCallback(sptr<ITorchServiceCallback>& callback)
2916 {
2917     auto serviceProxy = GetServiceProxy();
2918     CHECK_RETURN_RET_ELOG(
2919         serviceProxy == nullptr, CAMERA_UNKNOWN_ERROR, "CameraManager::SetTorchServiceCallback serviceProxy is null");
2920     int32_t retCode = serviceProxy->SetTorchCallback(callback);
2921     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, retCode,
2922         "SetTorchServiceCallback Set service Callback failed, retCode: %{public}d", retCode);
2923     return CAMERA_OK;
2924 }
2925 
UnSetTorchServiceCallback()2926 int32_t CameraManager::UnSetTorchServiceCallback()
2927 {
2928     // LCOV_EXCL_START
2929     auto serviceProxy = GetServiceProxy();
2930     CHECK_RETURN_RET_ELOG(
2931         serviceProxy == nullptr, CAMERA_UNKNOWN_ERROR, "CameraManager::UnSetTorchServiceCallback serviceProxy is null");
2932     int32_t retCode = serviceProxy->UnSetTorchCallback();
2933     CHECK_RETURN_RET_ELOG(
2934         retCode != CAMERA_OK, retCode, "UnSetTorchServiceCallback failed, retCode: %{public}d", retCode);
2935     return CAMERA_OK;
2936     // LCOV_EXCL_STOP
2937 }
2938 
SetFoldServiceCallback(sptr<IFoldServiceCallback> & callback)2939 int32_t CameraManager::SetFoldServiceCallback(sptr<IFoldServiceCallback>& callback)
2940 {
2941     bool isInnerCallback = false;
2942     auto serviceProxy = GetServiceProxy();
2943     CHECK_RETURN_RET_ELOG(
2944         serviceProxy == nullptr, CAMERA_UNKNOWN_ERROR, "CameraManager::SetFoldServiceCallback serviceProxy is null");
2945     int32_t retCode = serviceProxy->SetFoldStatusCallback(callback, isInnerCallback);
2946     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, retCode,
2947         "SetFoldServiceCallback Set service Callback failed, retCode: %{public}d", retCode);
2948     return CAMERA_OK;
2949 }
2950 
UnSetFoldServiceCallback()2951 int32_t CameraManager::UnSetFoldServiceCallback()
2952 {
2953     // LCOV_EXCL_START
2954     auto serviceProxy = GetServiceProxy();
2955     CHECK_RETURN_RET_ELOG(
2956         serviceProxy == nullptr, CAMERA_UNKNOWN_ERROR, "CameraManager::UnSetFoldServiceCallback serviceProxy is null");
2957     int32_t retCode = serviceProxy->UnSetFoldStatusCallback();
2958     CHECK_RETURN_RET_ELOG(
2959         retCode != CAMERA_OK, retCode, "UnSetFoldServiceCallback failed, retCode: %{public}d", retCode);
2960     return CAMERA_OK;
2961     // LCOV_EXCL_STOP
2962 }
2963 
SetControlCenterStatusCallback(sptr<IControlCenterStatusCallback> & callback)2964 int32_t CameraManager::SetControlCenterStatusCallback(sptr<IControlCenterStatusCallback>& callback)
2965 {
2966     // LCOV_EXCL_START
2967     auto serviceProxy = GetServiceProxy();
2968     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CAMERA_UNKNOWN_ERROR,
2969         "CameraManager::SetControlCenterStatusCallback serviceProxy is null");
2970     int32_t retCode = serviceProxy->SetControlCenterCallback(callback);
2971     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, retCode,
2972         "SetControlCenterStatusCallback Set Callback failed, retCode: %{public}d", retCode);
2973     return CAMERA_OK;
2974     // LCOV_EXCL_STOP
2975 }
2976 
UnSetControlCenterStatusCallback()2977 int32_t CameraManager::UnSetControlCenterStatusCallback()
2978 {
2979     // LCOV_EXCL_START
2980     auto serviceProxy = GetServiceProxy();
2981     CHECK_RETURN_RET_ELOG(
2982         serviceProxy == nullptr, CAMERA_UNKNOWN_ERROR,
2983             "CameraManager::UnSetControlCenterStatusCallback serviceProxy is null");
2984     int32_t retCode = serviceProxy->UnSetControlCenterStatusCallback();
2985     CHECK_RETURN_RET_ELOG(
2986         retCode != CAMERA_OK, retCode, "UnSetControlCenterStatusCallback failed, retCode: %{public}d", retCode);
2987     return CAMERA_OK;
2988     // LCOV_EXCL_STOP
2989 }
2990 
IsControlCenterActive()2991 bool CameraManager::IsControlCenterActive()
2992 {
2993     // LCOV_EXCL_START
2994     bool status = false;
2995     auto serviceProxy = GetServiceProxy();
2996     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, CAMERA_UNKNOWN_ERROR,
2997         "CameraManager::IsControlCenterActive serviceProxy is null");
2998 
2999     int32_t retCode = serviceProxy->GetControlCenterStatus(status);
3000     CHECK_RETURN_RET_ELOG(retCode!=CAMERA_OK, false, "CameraManager::IsControlCenterActive failed");
3001     MEDIA_INFO_LOG("CameraManager::IsControlCenterActive status: %{public}d", status);
3002     return status;
3003     // LCOV_EXCL_STOP
3004 }
3005 
CreateControlCenterSession(sptr<ControlCenterSession> & pControlCenterSession)3006 int32_t CameraManager::CreateControlCenterSession(sptr<ControlCenterSession>& pControlCenterSession)
3007 {
3008     // LCOV_EXCL_START
3009     pControlCenterSession = new (std::nothrow) ControlCenterSession();
3010     MEDIA_INFO_LOG("CameraManager::CreateControlCenterSession");
3011     auto serviceProxy = GetServiceProxy();
3012     CHECK_RETURN_RET_ELOG(
3013         serviceProxy == nullptr, CAMERA_UNKNOWN_ERROR,
3014         "CameraManager::CreateControlCenterSession serviceProxy is null");
3015     int32_t retCode = serviceProxy->CheckControlCenterPermission();
3016     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, false, "CameraManager::CreateControlCenterSession failed");
3017     return CAMERA_OK;
3018     // LCOV_EXCL_STOP
3019 }
3020 
SetControlCenterFrameCondition(bool frameCondition)3021 void CameraManager::SetControlCenterFrameCondition(bool frameCondition)
3022 {
3023     MEDIA_INFO_LOG("SetControlCenterFrameCondition: %{public}d", frameCondition);
3024     controlCenterFrameCondition_ = frameCondition;
3025     UpdateControlCenterPrecondition();
3026 }
3027 
SetControlCenterResolutionCondition(bool resolutionCondition)3028 void CameraManager::SetControlCenterResolutionCondition(bool resolutionCondition)
3029 {
3030     MEDIA_INFO_LOG("SetControlCenterResolutionCondition: %{public}d", resolutionCondition);
3031     controlCenterResolutionCondition_ = resolutionCondition;
3032     UpdateControlCenterPrecondition();
3033 }
3034 
SetControlCenterPositionCondition(bool positionCondition)3035 void CameraManager::SetControlCenterPositionCondition(bool positionCondition)
3036 {
3037     MEDIA_INFO_LOG("SetControlCenterPositionCondition: %{public}d", positionCondition);
3038     controlCenterPositionCondition_ = positionCondition;
3039     UpdateControlCenterPrecondition();
3040 }
3041 
UpdateControlCenterPrecondition()3042 void CameraManager::UpdateControlCenterPrecondition()
3043 {
3044     MEDIA_INFO_LOG("UpdateControlCenterPrecondition:  %{public}d,%{public}d,%{public}d,%{public}d",
3045         controlCenterPrecondition_, controlCenterFrameCondition_,
3046         controlCenterResolutionCondition_, controlCenterPositionCondition_);
3047     auto serviceProxy = GetServiceProxy();
3048     CHECK_RETURN_ELOG(serviceProxy == nullptr, "UpdateControlCenterPrecondition serviceProxy is null");
3049     if (controlCenterPrecondition_
3050         && (!controlCenterFrameCondition_ || !controlCenterResolutionCondition_ || !controlCenterPositionCondition_)) {
3051         controlCenterPrecondition_ = false;
3052         serviceProxy->SetControlCenterPrecondition(false);
3053         return;
3054     }
3055     // LCOV_EXCL_START
3056     if (!controlCenterPrecondition_
3057         && (controlCenterFrameCondition_ && controlCenterResolutionCondition_ && controlCenterPositionCondition_)) {
3058         controlCenterPrecondition_ = true;
3059     }
3060     serviceProxy->SetControlCenterPrecondition(controlCenterPrecondition_);
3061     // LCOV_EXCL_STOP
3062     return;
3063 }
3064 
GetControlCenterPrecondition()3065 bool CameraManager::GetControlCenterPrecondition()
3066 {
3067     return controlCenterPrecondition_;
3068 }
3069 
SetIsControlCenterSupported(bool isSupported)3070 void CameraManager::SetIsControlCenterSupported(bool isSupported)
3071 {
3072     // LCOV_EXCL_START
3073     MEDIA_DEBUG_LOG("CameraManager::SetIsControlCenterSupported, isSupported: %{public}d", isSupported);
3074     isControlCenterSupported_ = isSupported;
3075 
3076     auto serviceProxy = GetServiceProxy();
3077     CHECK_RETURN_ELOG(serviceProxy == nullptr, "SetIsControlCenterSupported serviceProxy is null");
3078     int32_t retCode = serviceProxy->SetDeviceControlCenterAbility(isSupported);
3079     CHECK_RETURN_ELOG(retCode != CAMERA_OK, "IsControlCenterSupported call failed, retCode: %{public}d", retCode);
3080     // LCOV_EXCL_STOP
3081 }
3082 
GetIsControlCenterSupported()3083 bool CameraManager::GetIsControlCenterSupported()
3084 {
3085     return isControlCenterSupported_;
3086 }
3087 
OnCameraMute(bool muteMode)3088 int32_t CameraMuteListenerManager::OnCameraMute(bool muteMode)
3089 {
3090     MEDIA_DEBUG_LOG("muteMode is %{public}d", muteMode);
3091     auto cameraManager = GetCameraManager();
3092     CHECK_RETURN_RET_ELOG(cameraManager == nullptr, CAMERA_OK, "OnCameraMute CameraManager is nullptr");
3093     auto listenerManager = cameraManager->GetCameraMuteListenerManager();
3094     MEDIA_DEBUG_LOG("CameraMuteListeners size %{public}zu", listenerManager->GetListenerCount());
3095     listenerManager->TriggerListener([&](auto listener) { listener->OnCameraMute(muteMode); });
3096     return CAMERA_OK;
3097 }
3098 
IsCameraMuteSupported()3099 bool CameraManager::IsCameraMuteSupported()
3100 {
3101     bool isCameraMuteSupported = false;
3102     bool cacheResult = GetCameraDeviceAbilitySupportValue(CAMERA_ABILITY_SUPPORT_MUTE, isCameraMuteSupported);
3103     CHECK_RETURN_RET(cacheResult, isCameraMuteSupported);
3104 
3105     auto serviceProxy = GetServiceProxy();
3106     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, false, "IsCameraMuteSupported serviceProxy is null");
3107     int32_t retCode = serviceProxy->IsCameraMuteSupported(isCameraMuteSupported);
3108     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, false, "IsCameraMuteSupported call failed, retCode: %{public}d",
3109         retCode);
3110     CacheCameraDeviceAbilitySupportValue(CAMERA_ABILITY_SUPPORT_MUTE, isCameraMuteSupported);
3111     return isCameraMuteSupported;
3112 }
3113 
IsCameraMuted()3114 bool CameraManager::IsCameraMuted()
3115 {
3116     bool isMuted = false;
3117     auto serviceProxy = GetServiceProxy();
3118     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, isMuted, "CameraManager::IsCameraMuted serviceProxy is null");
3119     int32_t retCode = serviceProxy->IsCameraMuted(isMuted);
3120     CHECK_PRINT_ELOG(retCode != CAMERA_OK, "IsCameraMuted call failed, retCode: %{public}d", retCode);
3121     return isMuted;
3122 }
3123 
MuteCamera(bool muteMode)3124 void CameraManager::MuteCamera(bool muteMode)
3125 {
3126     // LCOV_EXCL_START
3127     auto serviceProxy = GetServiceProxy();
3128     CHECK_RETURN_ELOG(serviceProxy == nullptr, "CameraManager::MuteCamera serviceProxy is null");
3129     int32_t retCode = serviceProxy->MuteCamera(muteMode);
3130     CHECK_PRINT_ELOG(retCode != CAMERA_OK, "MuteCamera call failed, retCode: %{public}d", retCode);
3131     // LCOV_EXCL_STOP
3132 }
3133 
MuteCameraPersist(PolicyType policyType,bool muteMode)3134 int32_t CameraManager::MuteCameraPersist(PolicyType policyType, bool muteMode)
3135 {
3136     // LCOV_EXCL_START
3137     auto serviceProxy = GetServiceProxy();
3138     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, SERVICE_FATL_ERROR,
3139         "CameraManager::MuteCameraPersist serviceProxy is null");
3140     int32_t retCode = serviceProxy->MuteCameraPersist(policyType, muteMode);
3141     CHECK_PRINT_ELOG(retCode != CAMERA_OK, "MuteCameraPersist call failed, retCode: %{public}d", retCode);
3142     return ServiceToCameraError(retCode);
3143     // LCOV_EXCL_STOP
3144 }
3145 
PrelaunchCamera(int32_t flag)3146 int32_t CameraManager::PrelaunchCamera(int32_t flag)
3147 {
3148     auto serviceProxy = GetServiceProxy();
3149     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, SERVICE_FATL_ERROR, "PrelaunchCamera serviceProxy is null");
3150     int32_t retCode = serviceProxy->PrelaunchCamera(flag);
3151     CHECK_PRINT_ELOG(retCode != CAMERA_OK, "PrelaunchCamera call failed, retCode: %{public}d", retCode);
3152     return ServiceToCameraError(retCode);
3153 }
3154 
ResetRssPriority()3155 int32_t CameraManager::ResetRssPriority()
3156 {
3157     MEDIA_INFO_LOG("CameraManager::ResetRssPriority");
3158     auto serviceProxy = GetServiceProxy();
3159     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, SERVICE_FATL_ERROR, "ResetRssPriority serviceProxy is null");
3160     int32_t retCode = serviceProxy->ResetRssPriority();
3161     CHECK_PRINT_ELOG(retCode != CAMERA_OK, "ResetRssPriority call failed, retCode: %{public}d", retCode);
3162     return ServiceToCameraError(retCode);
3163 }
3164 
PreSwitchCamera(const std::string cameraId)3165 int32_t CameraManager::PreSwitchCamera(const std::string cameraId)
3166 {
3167     // LCOV_EXCL_START
3168     auto serviceProxy = GetServiceProxy();
3169     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, SERVICE_FATL_ERROR, "PreSwitchCamera serviceProxy is null");
3170     int32_t retCode = serviceProxy->PreSwitchCamera(cameraId);
3171     CHECK_PRINT_ELOG(retCode != CAMERA_OK, "PreSwitchCamera call failed, retCode: %{public}d", retCode);
3172     return ServiceToCameraError(retCode);
3173     // LCOV_EXCL_STOP
3174 }
3175 
IsPrelaunchSupported(sptr<CameraDevice> camera)3176 bool CameraManager::IsPrelaunchSupported(sptr<CameraDevice> camera)
3177 {
3178     // LCOV_EXCL_START
3179     CHECK_RETURN_RET(camera == nullptr, false);
3180     return camera->IsPrelaunch();
3181     // LCOV_EXCL_STOP
3182 }
3183 
IsTorchSupported()3184 bool CameraManager::IsTorchSupported()
3185 {
3186     bool isCameraTorchSupported = false;
3187     bool cacheResult = GetCameraDeviceAbilitySupportValue(CAMERA_ABILITY_SUPPORT_TORCH, isCameraTorchSupported);
3188     CHECK_RETURN_RET(cacheResult, isCameraTorchSupported);
3189 
3190     auto serviceProxy = GetServiceProxy();
3191     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, false, "IsTorchSupported serviceProxy is null");
3192     int32_t retCode = serviceProxy->IsTorchSupported(isCameraTorchSupported);
3193     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, false, "IsTorchSupported call failed, retCode: %{public}d",
3194         retCode);
3195     CacheCameraDeviceAbilitySupportValue(CAMERA_ABILITY_SUPPORT_TORCH, isCameraTorchSupported);
3196     return isCameraTorchSupported;
3197 }
3198 
IsTorchModeSupported(TorchMode mode)3199 bool CameraManager::IsTorchModeSupported(TorchMode mode)
3200 {
3201     return mode == TorchMode::TORCH_MODE_OFF || mode == TorchMode::TORCH_MODE_ON;
3202 }
3203 
GetTorchMode()3204 TorchMode CameraManager::GetTorchMode()
3205 {
3206     auto serviceProxy = GetServiceProxy();
3207     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, torchMode_, "GetTorchMode serviceProxy is null");
3208     int32_t status = 0;
3209     int32_t retCode = serviceProxy->GetTorchStatus(status);
3210     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, torchMode_, "GetTorchMode call failed, retCode: %{public}d",
3211         retCode);
3212     torchMode_ = (status == static_cast<int32_t>(TorchStatus::TORCH_STATUS_ON)) ? TORCH_MODE_ON : TORCH_MODE_OFF;
3213     return torchMode_;
3214 }
3215 
SetTorchMode(TorchMode mode)3216 int32_t CameraManager::SetTorchMode(TorchMode mode)
3217 {
3218     int32_t retCode = CAMERA_OPERATION_NOT_ALLOWED;
3219     int32_t pid = IPCSkeleton::GetCallingPid();
3220     int32_t uid = IPCSkeleton::GetCallingUid();
3221     POWERMGR_SYSEVENT_TORCH_STATE(pid, uid, mode);
3222     switch (mode) {
3223         case TorchMode::TORCH_MODE_OFF:
3224             retCode = SetTorchLevel(0);
3225             break;
3226         case TorchMode::TORCH_MODE_ON:
3227             retCode = SetTorchLevel(1);
3228             break;
3229         case TorchMode::TORCH_MODE_AUTO:
3230             MEDIA_ERR_LOG("Invalid or unsupported torchMode value received from application");
3231             break;
3232         default:
3233             MEDIA_ERR_LOG("Invalid or unsupported torchMode value received from application");
3234     }
3235     CHECK_EXECUTE(retCode == CAMERA_OK, UpdateTorchMode(mode));
3236     return ServiceToCameraError(retCode);
3237 }
3238 
UpdateTorchMode(TorchMode mode)3239 void CameraManager::UpdateTorchMode(TorchMode mode)
3240 {
3241     CHECK_RETURN(torchMode_ == mode);
3242     torchMode_ = mode;
3243     MEDIA_INFO_LOG("CameraManager::UpdateTorchMode() mode is %{public}d", mode);
3244 }
3245 
SetTorchLevel(float level)3246 int32_t CameraManager::SetTorchLevel(float level)
3247 {
3248     auto serviceProxy = GetServiceProxy();
3249     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, SERVICE_FATL_ERROR, "SetTorchLevel serviceProxy is null");
3250     int32_t retCode = serviceProxy->SetTorchLevel(level);
3251     CHECK_PRINT_ELOG(retCode != CAMERA_OK, "SetTorchLevel call failed, retCode: %{public}d", retCode);
3252     return retCode;
3253 }
3254 
SetPrelaunchConfig(std::string cameraId,RestoreParamTypeOhos restoreParamType,int activeTime,EffectParam effectParam)3255 int32_t CameraManager::SetPrelaunchConfig(
3256     std::string cameraId, RestoreParamTypeOhos restoreParamType, int activeTime, EffectParam effectParam)
3257 {
3258     // LCOV_EXCL_START
3259     auto serviceProxy = GetServiceProxy();
3260     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, SERVICE_FATL_ERROR, "SetPrelaunchConfig serviceProxy is null");
3261     int32_t retCode = serviceProxy->SetPrelaunchConfig(
3262         cameraId, static_cast<RestoreParamTypeOhos>(restoreParamType), activeTime, effectParam);
3263     CHECK_PRINT_ELOG(retCode != CAMERA_OK, "SetPrelaunchConfig call failed, retCode: %{public}d", retCode);
3264     return ServiceToCameraError(retCode);
3265     // LCOV_EXCL_STOP
3266 }
3267 
GetCameraStorageSize(int64_t & size)3268 int32_t CameraManager::GetCameraStorageSize(int64_t& size)
3269 {
3270     // LCOV_EXCL_START
3271     auto serviceProxy = GetServiceProxy();
3272     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, SERVICE_FATL_ERROR,
3273         "GetCameraStorageSize serviceProxy is null");
3274     int32_t retCode = serviceProxy->GetCameraStorageSize(size);
3275     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
3276         "GetStorageInfo call failed, retCode: %{public}d", retCode);
3277     return ServiceToCameraError(retCode);
3278     // LCOV_EXCL_STOP
3279 }
3280 
SetCameraManagerNull()3281 void CameraManager::SetCameraManagerNull()
3282 {
3283     MEDIA_INFO_LOG("CameraManager::SetCameraManagerNull() called");
3284     g_cameraManager = nullptr;
3285 }
3286 
FillSupportPreviewFormats(std::vector<Profile> & previewProfiles)3287 void CameraManager::FillSupportPreviewFormats(std::vector<Profile>& previewProfiles)
3288 {
3289     std::vector<Profile> extendProfiles = {};
3290     for (const auto& profile : previewProfiles) {
3291         if (profile.format_ == CAMERA_FORMAT_YCBCR_P010 || profile.format_ == CAMERA_FORMAT_YCRCB_P010) {
3292             continue;
3293         }
3294         extendProfiles.push_back(profile);
3295     }
3296     previewProfiles = extendProfiles;
3297 }
3298 
FillSupportPhotoFormats(std::vector<Profile> & photoProfiles)3299 void CameraManager::FillSupportPhotoFormats(std::vector<Profile>& photoProfiles)
3300 {
3301     // LCOV_EXCL_START
3302     CHECK_RETURN(photoFormats_.size() == 0 || photoProfiles.size() == 0);
3303     std::vector<Profile> extendProfiles = {};
3304     // if photo stream support jpeg, it must support yuv.
3305     for (const auto& profile : photoProfiles) {
3306         if (profile.format_ != CAMERA_FORMAT_JPEG) {
3307             extendProfiles.push_back(profile);
3308             continue;
3309         }
3310         for (const auto& format : photoFormats_) {
3311             Profile extendPhotoProfile = profile;
3312             extendPhotoProfile.format_ = format;
3313             extendProfiles.push_back(extendPhotoProfile);
3314         }
3315     }
3316     photoProfiles = extendProfiles;
3317     // LCOV_EXCL_STOP
3318 }
3319 
CreateMetadataOutputInternal(sptr<MetadataOutput> & pMetadataOutput,const std::vector<MetadataObjectType> & metadataObjectTypes)3320 int32_t CameraManager::CreateMetadataOutputInternal(sptr<MetadataOutput>& pMetadataOutput,
3321     const std::vector<MetadataObjectType>& metadataObjectTypes)
3322 {
3323     CAMERA_SYNC_TRACE;
3324     const size_t maxSize4NonSystemApp = 1;
3325     if (!CameraSecurity::CheckSystemApp()) {
3326         MEDIA_DEBUG_LOG("public calling for metadataOutput");
3327         // LCOV_EXCL_START
3328         if (metadataObjectTypes.size() > maxSize4NonSystemApp ||
3329             std::any_of(metadataObjectTypes.begin(), metadataObjectTypes.end(),
3330                 [](MetadataObjectType type) { return type != MetadataObjectType::FACE; })) {
3331             return CameraErrorCode::INVALID_ARGUMENT;
3332         }
3333         // LCOV_EXCL_STOP
3334     }
3335     auto serviceProxy = GetServiceProxy();
3336     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr,  CameraErrorCode::SERVICE_FATL_ERROR,
3337         "CameraManager::CreateMetadataOutput serviceProxy is null");
3338 
3339     sptr<IConsumerSurface> surface = IConsumerSurface::Create();
3340     CHECK_RETURN_RET_ELOG(surface == nullptr,  CameraErrorCode::SERVICE_FATL_ERROR,
3341         "CameraManager::CreateMetadataOutput Failed to create MetadataOutputSurface");
3342     // only for face recognize
3343     int32_t format = OHOS_CAMERA_FORMAT_YCRCB_420_SP;
3344     int32_t width = 1920;
3345     int32_t height = 1080;
3346     surface->SetDefaultWidthAndHeight(width, height);
3347     sptr<IStreamMetadata> streamMetadata = nullptr;
3348     std::vector<int32_t> result(metadataObjectTypes.size());
3349     std::transform(metadataObjectTypes.begin(), metadataObjectTypes.end(), result.begin(), [](MetadataObjectType obj) {
3350         return static_cast<int32_t>(obj);
3351     });
3352     int32_t retCode = serviceProxy->CreateMetadataOutput(surface->GetProducer(), format, result, streamMetadata);
3353     CHECK_RETURN_RET_ELOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
3354         "CreateMetadataOutput Failed to get stream metadata object from hcamera service! %{public}d", retCode);
3355     pMetadataOutput = new (std::nothrow) MetadataOutput(surface, streamMetadata);
3356     CHECK_RETURN_RET_ELOG(pMetadataOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
3357         "CreateMetadataOutput Failed to new pMetadataOutput!");
3358     pMetadataOutput->SetStream(streamMetadata);
3359     sptr<IBufferConsumerListener> bufferConsumerListener = new (std::nothrow) MetadataObjectListener(pMetadataOutput);
3360     CHECK_RETURN_RET_ELOG(bufferConsumerListener == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
3361         "CreateMetadataOutput Failed to new bufferConsumerListener!");
3362     SurfaceError ret = surface->RegisterConsumerListener(bufferConsumerListener);
3363     CHECK_PRINT_ELOG(ret != SURFACE_ERROR_OK,
3364         "MetadataOutputSurface consumer listener registration failed:%{public}d", ret);
3365     return CameraErrorCode::SUCCESS;
3366 }
3367 
RequireMemorySize(int32_t memSize)3368 int32_t CameraManager::RequireMemorySize(int32_t memSize)
3369 {
3370     // LCOV_EXCL_START
3371     auto serviceProxy = GetServiceProxy();
3372     CHECK_RETURN_RET_ELOG(serviceProxy == nullptr, SERVICE_FATL_ERROR, "RequireMemorySize serviceProxy is null");
3373     int32_t retCode = serviceProxy->RequireMemorySize(memSize);
3374     CHECK_PRINT_ELOG(retCode != CAMERA_OK, "RequireMemorySize call failed, retCode: %{public}d", retCode);
3375     return retCode;
3376     // LCOV_EXCL_STOP
3377 }
3378 
GetSupportedCamerasWithFoldStatus()3379 std::vector<sptr<CameraDevice>> CameraManager::GetSupportedCamerasWithFoldStatus()
3380 {
3381     // LCOV_EXCL_START
3382     auto cameraDeviceList = GetCameraDeviceList();
3383     bool isFoldable = GetIsFoldable();
3384     CHECK_RETURN_RET(!isFoldable, cameraDeviceList);
3385     auto curFoldStatus = GetFoldStatus();
3386     MEDIA_INFO_LOG("fold status: %{public}d", curFoldStatus);
3387     std::vector<sptr<CameraDevice>> supportedCameraDeviceList;
3388     for (const auto& deviceInfo : cameraDeviceList) {
3389         auto supportedFoldStatus = deviceInfo->GetSupportedFoldStatus();
3390         auto it = g_metaToFwCameraFoldStatus_.find(static_cast<CameraFoldStatus>(supportedFoldStatus));
3391         if (it == g_metaToFwCameraFoldStatus_.end()) {
3392             MEDIA_INFO_LOG("No supported fold status is found, fold status: %{public}d", curFoldStatus);
3393             supportedCameraDeviceList.emplace_back(deviceInfo);
3394             continue;
3395         }
3396         if (it->second == curFoldStatus) {
3397             supportedCameraDeviceList.emplace_back(deviceInfo);
3398         }
3399     }
3400     return supportedCameraDeviceList;
3401     // LCOV_EXCL_STOP
3402 }
3403 
SaveOldCameraId(std::string realCameraId,std::string oldCameraId)3404 void CameraManager::SaveOldCameraId(std::string realCameraId, std::string oldCameraId)
3405 {
3406     realtoVirtual_[realCameraId] = oldCameraId;
3407 }
3408 
GetOldCameraIdfromReal(std::string realCameraId)3409 std::string CameraManager::GetOldCameraIdfromReal(std::string realCameraId)
3410 {
3411     string resultstr = "";
3412     auto itr = realtoVirtual_.find(realCameraId);
3413     if (itr != realtoVirtual_.end()) {
3414         resultstr = itr->second;
3415     } else {
3416         MEDIA_ERR_LOG("Can not GetOldCameraIdfromReal");
3417     }
3418     return resultstr;
3419 }
3420 
SaveOldMeta(std::string cameraId,std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)3421 void CameraManager::SaveOldMeta(std::string cameraId, std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)
3422 {
3423     cameraOldCamera_[cameraId] = metadata;
3424 }
3425 
GetOldMeta(std::string cameraId)3426 std::shared_ptr<OHOS::Camera::CameraMetadata> CameraManager::GetOldMeta(std::string cameraId)
3427 {
3428     // LCOV_EXCL_START
3429     std::shared_ptr<OHOS::Camera::CameraMetadata> result_meta = nullptr;
3430     auto itr = cameraOldCamera_.find(cameraId);
3431     if (itr != cameraOldCamera_.end()) {
3432         result_meta = itr->second;
3433     } else {
3434         MEDIA_ERR_LOG("Can not GetOldMeta");
3435     }
3436     return result_meta;
3437     // LCOV_EXCL_STOP
3438 }
3439 
SetOldMetatoInput(sptr<CameraDevice> & cameraObj,std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)3440 void CameraManager::SetOldMetatoInput(sptr<CameraDevice>& cameraObj,
3441     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)
3442 {
3443     SetProfile(cameraObj, metadata);
3444 }
3445 } // namespace CameraStandard
3446 } // namespace OHOS
3447