• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 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 <cstddef>
19 #include <cstdint>
20 #include <cstring>
21 #include <mutex>
22 #include <nlohmann/json.hpp>
23 #include <ostream>
24 #include <sstream>
25 #include <parameters.h>
26 
27 #include "aperture_video_session.h"
28 #include "camera_device_ability_items.h"
29 #include "camera_error_code.h"
30 #include "camera_log.h"
31 #include "camera_security_utils.h"
32 #include "camera_util.h"
33 #include "capture_scene_const.h"
34 #include "deferred_photo_proc_session.h"
35 #include "display_manager.h"
36 #include "dps_metadata_info.h"
37 #include "icamera_util.h"
38 #include "ipc_skeleton.h"
39 #include "iservice_registry.h"
40 #include "istream_capture.h"
41 #include "istream_common.h"
42 #include "light_painting_session.h"
43 #include "quick_shot_photo_session.h"
44 #include "session/capture_session.h"
45 #include "session/fluorescence_photo_session.h"
46 #include "session/high_res_photo_session.h"
47 #include "session/macro_photo_session.h"
48 #include "session/macro_video_session.h"
49 #include "session/night_session.h"
50 #include "session/panorama_session.h"
51 #include "session/photo_session.h"
52 #include "session/portrait_session.h"
53 #include "session/profession_session.h"
54 #include "session/scan_session.h"
55 #include "session/slow_motion_session.h"
56 #include "session/video_session.h"
57 #include "session/secure_camera_session.h"
58 #include "session/time_lapse_photo_session.h"
59 #include "system_ability_definition.h"
60 #include "ability/camera_ability_parse_util.h"
61 
62 using namespace std;
63 namespace OHOS {
64 namespace CameraStandard {
65 using OHOS::HDI::Camera::V1_3::OperationMode;
66 sptr<CameraManager> CameraManager::g_cameraManager = nullptr;
67 std::mutex CameraManager::g_instanceMutex;
68 
69 const std::string CameraManager::surfaceFormat = "CAMERA_SURFACE_FORMAT";
70 
71 const std::unordered_map<camera_format_t, CameraFormat> CameraManager::metaToFwCameraFormat_ = {
72     {OHOS_CAMERA_FORMAT_YCRCB_420_SP, CAMERA_FORMAT_YUV_420_SP},
73     {OHOS_CAMERA_FORMAT_JPEG, CAMERA_FORMAT_JPEG},
74     {OHOS_CAMERA_FORMAT_RGBA_8888, CAMERA_FORMAT_RGBA_8888},
75     {OHOS_CAMERA_FORMAT_YCBCR_P010, CAMERA_FORMAT_YCBCR_P010},
76     {OHOS_CAMERA_FORMAT_YCRCB_P010, CAMERA_FORMAT_YCRCB_P010},
77     {OHOS_CAMERA_FORMAT_YCBCR_420_SP, CAMERA_FORMAT_NV12},
78     {OHOS_CAMERA_FORMAT_422_YUYV, CAMERA_FORMAT_YUV_422_YUYV},
79     {OHOS_CAMERA_FORMAT_DNG, CAMERA_FORMAT_DNG},
80     {OHOS_CAMERA_FORMAT_HEIC, CAMERA_FORMAT_HEIC},
81     {OHOS_CAMERA_FORMAT_DEPTH_16, CAMERA_FORMAT_DEPTH_16},
82     {OHOS_CAMERA_FORMAT_DEPTH_32, CAMERA_FORMAT_DEPTH_32}
83 };
84 
85 const std::unordered_map<DepthDataAccuracyType, DepthDataAccuracy> CameraManager::metaToFwDepthDataAccuracy_ = {
86     {OHOS_DEPTH_DATA_ACCURACY_RELATIVE, DEPTH_DATA_ACCURACY_RELATIVE},
87     {OHOS_DEPTH_DATA_ACCURACY_ABSOLUTE, DEPTH_DATA_ACCURACY_ABSOLUTE},
88 };
89 
90 const std::unordered_map<CameraFormat, camera_format_t> CameraManager::fwToMetaCameraFormat_ = {
91     {CAMERA_FORMAT_YUV_420_SP, OHOS_CAMERA_FORMAT_YCRCB_420_SP},
92     {CAMERA_FORMAT_JPEG, OHOS_CAMERA_FORMAT_JPEG},
93     {CAMERA_FORMAT_RGBA_8888, OHOS_CAMERA_FORMAT_RGBA_8888},
94     {CAMERA_FORMAT_YCBCR_P010, OHOS_CAMERA_FORMAT_YCBCR_P010},
95     {CAMERA_FORMAT_YCRCB_P010, OHOS_CAMERA_FORMAT_YCRCB_P010},
96     {CAMERA_FORMAT_NV12, OHOS_CAMERA_FORMAT_YCBCR_420_SP},
97     {CAMERA_FORMAT_YUV_422_YUYV, OHOS_CAMERA_FORMAT_422_YUYV},
98     {CAMERA_FORMAT_DNG, OHOS_CAMERA_FORMAT_DNG},
99     {CAMERA_FORMAT_HEIC, OHOS_CAMERA_FORMAT_HEIC},
100     {CAMERA_FORMAT_DEPTH_16, OHOS_CAMERA_FORMAT_DEPTH_16},
101     {CAMERA_FORMAT_DEPTH_32, OHOS_CAMERA_FORMAT_DEPTH_32}
102 };
103 
104 const std::unordered_map<OperationMode, SceneMode> g_metaToFwSupportedMode_ = {
105     {OperationMode::NORMAL, NORMAL},
106     {OperationMode::CAPTURE, CAPTURE},
107     {OperationMode::VIDEO, VIDEO},
108     {OperationMode::PORTRAIT, PORTRAIT},
109     {OperationMode::NIGHT, NIGHT},
110     {OperationMode::PROFESSIONAL_PHOTO, PROFESSIONAL_PHOTO},
111     {OperationMode::PROFESSIONAL_VIDEO, PROFESSIONAL_VIDEO},
112     {OperationMode::SLOW_MOTION, SLOW_MOTION},
113     {OperationMode::SCAN_CODE, SCAN},
114     {OperationMode::CAPTURE_MACRO, CAPTURE_MACRO},
115     {OperationMode::VIDEO_MACRO, VIDEO_MACRO},
116     {OperationMode::HIGH_FRAME_RATE, HIGH_FRAME_RATE},
117     {OperationMode::HIGH_RESOLUTION_PHOTO, HIGH_RES_PHOTO},
118     {OperationMode::SECURE, SECURE},
119     {OperationMode::QUICK_SHOT_PHOTO, QUICK_SHOT_PHOTO},
120     {OperationMode::APERTURE_VIDEO, APERTURE_VIDEO},
121     {OperationMode::PANORAMA_PHOTO, PANORAMA_PHOTO},
122     {OperationMode::LIGHT_PAINTING, LIGHT_PAINTING},
123     {OperationMode::TIMELAPSE_PHOTO, TIMELAPSE_PHOTO},
124     {OperationMode::FLUORESCENCE_PHOTO, FLUORESCENCE_PHOTO},
125 };
126 
127 const std::unordered_map<SceneMode, OperationMode> g_fwToMetaSupportedMode_ = {
128     {NORMAL, OperationMode::NORMAL},
129     {CAPTURE,  OperationMode::CAPTURE},
130     {VIDEO,  OperationMode::VIDEO},
131     {PORTRAIT,  OperationMode::PORTRAIT},
132     {NIGHT,  OperationMode::NIGHT},
133     {PROFESSIONAL_PHOTO,  OperationMode::PROFESSIONAL_PHOTO},
134     {PROFESSIONAL_VIDEO,  OperationMode::PROFESSIONAL_VIDEO},
135     {SLOW_MOTION,  OperationMode::SLOW_MOTION},
136     {SCAN, OperationMode::SCAN_CODE},
137     {CAPTURE_MACRO, OperationMode::CAPTURE_MACRO},
138     {VIDEO_MACRO, OperationMode::VIDEO_MACRO},
139     {HIGH_FRAME_RATE, OperationMode::HIGH_FRAME_RATE},
140     {HIGH_RES_PHOTO, OperationMode::HIGH_RESOLUTION_PHOTO},
141     {SECURE, OperationMode::SECURE},
142     {QUICK_SHOT_PHOTO, OperationMode::QUICK_SHOT_PHOTO},
143     {APERTURE_VIDEO, OperationMode::APERTURE_VIDEO},
144     {PANORAMA_PHOTO, OperationMode::PANORAMA_PHOTO},
145     {LIGHT_PAINTING, OperationMode::LIGHT_PAINTING},
146     {TIMELAPSE_PHOTO, OperationMode::TIMELAPSE_PHOTO},
147     {FLUORESCENCE_PHOTO, OperationMode::FLUORESCENCE_PHOTO},
148 };
149 
150 const std::unordered_map<CameraFoldStatus, FoldStatus> g_metaToFwCameraFoldStatus_ = {
151     {OHOS_CAMERA_FOLD_STATUS_NONFOLDABLE, UNKNOWN_FOLD},
152     {OHOS_CAMERA_FOLD_STATUS_EXPANDED, EXPAND},
153     {OHOS_CAMERA_FOLD_STATUS_FOLDED, FOLDED}
154 };
155 
156 const std::unordered_map<StatisticsDetectType, MetadataObjectType> g_metaToFwCameraMetaDetect_ = {
157     {StatisticsDetectType::OHOS_CAMERA_HUMAN_FACE_DETECT, MetadataObjectType::FACE},
158     {StatisticsDetectType::OHOS_CAMERA_HUMAN_BODY_DETECT, MetadataObjectType::HUMAN_BODY},
159     {StatisticsDetectType::OHOS_CAMERA_CAT_FACE_DETECT, MetadataObjectType::CAT_FACE},
160     {StatisticsDetectType::OHOS_CAMERA_CAT_BODY_DETECT, MetadataObjectType::CAT_BODY},
161     {StatisticsDetectType::OHOS_CAMERA_DOG_FACE_DETECT, MetadataObjectType::DOG_FACE},
162     {StatisticsDetectType::OHOS_CAMERA_DOG_BODY_DETECT, MetadataObjectType::DOG_BODY},
163     {StatisticsDetectType::OHOS_CAMERA_SALIENT_DETECT, MetadataObjectType::SALIENT_DETECTION},
164     {StatisticsDetectType::OHOS_CAMERA_BAR_CODE_DETECT, MetadataObjectType::BAR_CODE_DETECTION},
165     {StatisticsDetectType::OHOS_CAMERA_BASE_FACE_DETECT, MetadataObjectType::BASE_FACE_DETECTION}
166 };
167 
168 const std::set<int32_t> isTemplateMode_ = {
169     SceneMode::CAPTURE, SceneMode::VIDEO
170 };
171 
172 const std::set<int32_t> isPhotoMode_ = {
173     SceneMode::CAPTURE, SceneMode::PORTRAIT
174 };
175 
ConvertMetaToFwkMode(const OperationMode opMode,SceneMode & scMode)176 bool ConvertMetaToFwkMode(const OperationMode opMode, SceneMode &scMode)
177 {
178     auto it = g_metaToFwSupportedMode_.find(opMode);
179     if (it != g_metaToFwSupportedMode_.end()) {
180         scMode = it->second;
181         MEDIA_DEBUG_LOG("ConvertMetaToFwkMode OperationMode = %{public}d to SceneMode %{public}d", opMode, scMode);
182         return true;
183     }
184     MEDIA_ERR_LOG("ConvertMetaToFwkMode OperationMode = %{public}d err", opMode);
185     return false;
186 }
187 
ConvertFwkToMetaMode(const SceneMode scMode,OperationMode & opMode)188 bool ConvertFwkToMetaMode(const SceneMode scMode, OperationMode &opMode)
189 {
190     auto it = g_fwToMetaSupportedMode_.find(scMode);
191     if (it != g_fwToMetaSupportedMode_.end()) {
192         opMode = it->second;
193         MEDIA_DEBUG_LOG("ConvertFwkToMetaMode SceneMode %{public}d to OperationMode = %{public}d", scMode, opMode);
194         return true;
195     }
196     MEDIA_ERR_LOG("ConvertFwkToMetaMode SceneMode = %{public}d err", scMode);
197     return false;
198 }
199 
CameraManager()200 CameraManager::CameraManager()
201 {
202     MEDIA_INFO_LOG("CameraManager::CameraManager construct enter");
203 }
204 
~CameraManager()205 CameraManager::~CameraManager()
206 {
207     MEDIA_INFO_LOG("CameraManager::~CameraManager() called");
208     RemoveServiceProxyDeathRecipient();
209     UnSubscribeSystemAbility();
210 }
211 
CreateListenerObject()212 int32_t CameraManager::CreateListenerObject()
213 {
214     MEDIA_DEBUG_LOG("CameraManager::CreateListenerObject prepare execute");
215     sptr<CameraListenerStub> listenerStub = new (std::nothrow) CameraListenerStub();
216     CHECK_ERROR_RETURN_RET_LOG(listenerStub == nullptr, CAMERA_ALLOC_ERROR, "failed to new CameraListenerStub object");
217     sptr<IRemoteObject> object = listenerStub->AsObject();
218     CHECK_ERROR_RETURN_RET_LOG(object == nullptr, CAMERA_ALLOC_ERROR, "listener object is nullptr..");
219     auto serviceProxy = GetServiceProxy();
220     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, CameraErrorCode::SERVICE_FATL_ERROR, "serviceProxy is null");
221     return serviceProxy->SetListenerObject(object);
222 }
223 
OnCameraStatusChanged(const std::string & cameraId,const CameraStatus status,const std::string & bundleName)224 int32_t CameraStatusServiceCallback::OnCameraStatusChanged(const std::string& cameraId, const CameraStatus status,
225     const std::string& bundleName) __attribute__((no_sanitize("cfi")))
226 {
227     MEDIA_INFO_LOG("OnCameraStatusChanged cameraId: %{public}s, status: %{public}d", cameraId.c_str(), status);
228     auto cameraManager = cameraManager_.promote();
229     CHECK_ERROR_RETURN_RET_LOG(cameraManager == nullptr, CAMERA_OK, "OnCameraStatusChanged CameraManager is nullptr");
230     auto listenerMap = cameraManager->GetCameraMngrCallbackMap();
231     MEDIA_DEBUG_LOG("CameraMngrCallbackMap size %{public}d", listenerMap.Size());
232     if (listenerMap.IsEmpty()) {
233         return CAMERA_OK;
234     }
235 
236     CameraStatusInfo cameraStatusInfo;
237     if (status == CAMERA_STATUS_APPEAR) {
238         cameraManager->ClearCameraDeviceListCache();
239         cameraManager->ClearCameraDeviceAbilitySupportMap();
240     }
241     cameraStatusInfo.cameraDevice = cameraManager->GetCameraDeviceFromId(cameraId);
242     if (status == CAMERA_STATUS_DISAPPEAR) {
243         cameraManager->ClearCameraDeviceListCache();
244         cameraManager->ClearCameraDeviceAbilitySupportMap();
245     }
246     cameraStatusInfo.cameraStatus = status;
247     cameraStatusInfo.bundleName = bundleName;
248 
249     if (cameraStatusInfo.cameraDevice) {
250         listenerMap.Iterate([&](std::thread::id threadId,
251                                 std::shared_ptr<CameraManagerCallback> cameraManagerCallback) {
252             if (cameraManagerCallback != nullptr) {
253                 MEDIA_INFO_LOG("Callback cameraStatus");
254                 cameraManagerCallback->OnCameraStatusChanged(cameraStatusInfo);
255             } else {
256                 std::ostringstream oss;
257                 oss << threadId;
258                 MEDIA_INFO_LOG("Callback not registered!, Ignore the callback: thread:%{public}s", oss.str().c_str());
259             }
260         });
261     }
262     return CAMERA_OK;
263 }
264 
OnFlashlightStatusChanged(const std::string & cameraId,const FlashStatus status)265 int32_t CameraStatusServiceCallback::OnFlashlightStatusChanged(const std::string& cameraId, const FlashStatus status)
266     __attribute__((no_sanitize("cfi")))
267 {
268     MEDIA_INFO_LOG("cameraId: %{public}s, status: %{public}d", cameraId.c_str(), status);
269     auto cameraManager = cameraManager_.promote();
270     CHECK_ERROR_RETURN_RET_LOG(cameraManager == nullptr, CAMERA_OK,
271         "OnFlashlightStatusChanged CameraManager is nullptr");
272     auto listenerMap = cameraManager->GetCameraMngrCallbackMap();
273     MEDIA_DEBUG_LOG("CameraMngrCallbackMap size %{public}d", listenerMap.Size());
274     if (listenerMap.IsEmpty()) {
275         return CAMERA_OK;
276     }
277 
278     listenerMap.Iterate([&](std::thread::id threadId, std::shared_ptr<CameraManagerCallback> cameraManagerCallback) {
279         if (cameraManagerCallback != nullptr) {
280             MEDIA_INFO_LOG("Callback cameraStatus");
281             cameraManagerCallback->OnFlashlightStatusChanged(cameraId, status);
282         } else {
283             std::ostringstream oss;
284             oss << threadId;
285             MEDIA_INFO_LOG("Callback not registered!, Ignore the callback: thread:%{public}s", oss.str().c_str());
286         }
287     });
288     return CAMERA_OK;
289 }
290 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)291 void CameraServiceSystemAbilityListener::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
292 {
293     MEDIA_INFO_LOG("OnAddSystemAbility,id: %{public}d", systemAbilityId);
294     CameraManager::GetInstance()->OnCameraServerAlive();
295 }
296 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)297 void CameraServiceSystemAbilityListener::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
298 {
299     MEDIA_INFO_LOG("OnRemoveSystemAbility,id: %{public}d", systemAbilityId);
300 }
301 
CreateCaptureSession()302 sptr<CaptureSession> CameraManager::CreateCaptureSession()
303 {
304     CAMERA_SYNC_TRACE;
305     sptr<CaptureSession> captureSession = nullptr;
306     int ret = CreateCaptureSession(&captureSession);
307     CHECK_ERROR_RETURN_RET_LOG(ret != CameraErrorCode::SUCCESS, nullptr,
308         "Failed to CreateCaptureSession with error code:%{public}d", ret);
309     return captureSession;
310 }
311 
CreateCaptureSessionImpl(SceneMode mode,sptr<ICaptureSession> session)312 sptr<CaptureSession> CameraManager::CreateCaptureSessionImpl(SceneMode mode, sptr<ICaptureSession> session)
313 {
314     switch (mode) {
315         case SceneMode::VIDEO:
316             return new (std::nothrow) VideoSession(session);
317         case SceneMode::CAPTURE:
318             return new (std::nothrow) PhotoSession(session);
319         case SceneMode::PORTRAIT:
320             return new (std::nothrow) PortraitSession(session);
321         case SceneMode::PROFESSIONAL_VIDEO:
322         case SceneMode::PROFESSIONAL_PHOTO:
323             return new (std::nothrow) ProfessionSession(session, GetCameraDeviceList());
324         case SceneMode::SCAN:
325             return new (std::nothrow) ScanSession(session);
326         case SceneMode::NIGHT:
327             return new (std::nothrow) NightSession(session);
328         case SceneMode::CAPTURE_MACRO:
329             return new (std::nothrow) MacroPhotoSession(session);
330         case SceneMode::VIDEO_MACRO:
331             return new (std::nothrow) MacroVideoSession(session);
332         case SceneMode::SLOW_MOTION:
333             return new (std::nothrow) SlowMotionSession(session);
334         case SceneMode::HIGH_RES_PHOTO:
335             return new (std::nothrow) HighResPhotoSession(session);
336         case SceneMode::SECURE:
337             return new (std::nothrow) SecureCameraSession(session);
338         case SceneMode::QUICK_SHOT_PHOTO:
339             return new (std::nothrow) QuickShotPhotoSession(session);
340         case SceneMode::APERTURE_VIDEO:
341             return new (std::nothrow) ApertureVideoSession(session);
342         case SceneMode::PANORAMA_PHOTO:
343             return new (std::nothrow) PanoramaSession(session);
344         case SceneMode::TIMELAPSE_PHOTO:
345             return new(std::nothrow) TimeLapsePhotoSession(session, GetCameraDeviceList());
346         case SceneMode::FLUORESCENCE_PHOTO:
347             return new(std::nothrow) FluorescencePhotoSession(session);
348         case SceneMode::LIGHT_PAINTING:
349             return new (std::nothrow) LightPaintingSession(session);
350         default:
351             return new (std::nothrow) CaptureSession(session);
352     }
353 }
354 
CreateCaptureSession(SceneMode mode)355 sptr<CaptureSession> CameraManager::CreateCaptureSession(SceneMode mode)
356 {
357     CAMERA_SYNC_TRACE;
358     sptr<ICaptureSession> session = nullptr;
359 
360     int32_t retCode = CAMERA_OK;
361     auto serviceProxy = GetServiceProxy();
362     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, nullptr, "CreateCaptureSession(mode) serviceProxy is nullptr");
363     OperationMode opMode = OperationMode::NORMAL;
364     if (!ConvertFwkToMetaMode(mode, opMode)) {
365         MEDIA_ERR_LOG("CameraManager::CreateCaptureSession ConvertFwkToMetaMode mode: %{public}d fail", mode);
366     }
367     MEDIA_INFO_LOG("CameraManager::CreateCaptureSession prepare proxy execute");
368     retCode = serviceProxy->CreateCaptureSession(session, opMode);
369     MEDIA_INFO_LOG("CameraManager::CreateCaptureSession proxy execute end, mode %{public}d ret %{public}d",
370         mode, retCode);
371     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK || session == nullptr, nullptr,
372         "Failed to get capture session object from hcamera service!, %{public}d", retCode);
373     sptr<CaptureSession> captureSession = CreateCaptureSessionImpl(mode, session);
374     CHECK_ERROR_RETURN_RET_LOG(captureSession == nullptr, nullptr, "failed to new captureSession!");
375     captureSession->SetMode(mode);
376     return captureSession;
377 }
378 
CreateCaptureSession(sptr<CaptureSession> * pCaptureSession)379 int CameraManager::CreateCaptureSession(sptr<CaptureSession> *pCaptureSession)
380 {
381     CAMERA_SYNC_TRACE;
382     sptr<ICaptureSession> session = nullptr;
383     sptr<CaptureSession> captureSession = nullptr;
384     auto serviceProxy = GetServiceProxy();
385     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, CameraErrorCode::INVALID_ARGUMENT,
386         "CreateCaptureSession(pCaptureSession) serviceProxy is nullptr");
387     int32_t retCode = serviceProxy->CreateCaptureSession(session);
388     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
389         "CreateCaptureSession(pCaptureSession) Failed to get captureSession object from hcamera service! "
390         "%{public}d", retCode);
391     CHECK_ERROR_RETURN_RET_LOG(session == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
392         "CreateCaptureSession(pCaptureSession) Failed to CreateCaptureSession with session is null");
393     captureSession = new(std::nothrow) CaptureSession(session);
394     CHECK_ERROR_RETURN_RET_LOG(captureSession == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
395         "CreateCaptureSession(pCaptureSession) failed to new captureSession!");
396     *pCaptureSession = captureSession;
397     return CameraErrorCode::SUCCESS;
398 }
399 
CreateDeferredPhotoProcessingSession(int userId,std::shared_ptr<IDeferredPhotoProcSessionCallback> callback)400 sptr<DeferredPhotoProcSession> CameraManager::CreateDeferredPhotoProcessingSession(int userId,
401     std::shared_ptr<IDeferredPhotoProcSessionCallback> callback)
402 {
403     CAMERA_SYNC_TRACE;
404     sptr<DeferredPhotoProcSession> deferredPhotoProcSession = nullptr;
405     int32_t retCode = CreateDeferredPhotoProcessingSession(userId, callback, &deferredPhotoProcSession);
406     CHECK_ERROR_RETURN_RET_LOG(retCode != CameraErrorCode::SUCCESS, nullptr,
407         "Failed to CreateDeferredPhotoProcessingSession with error code:%{public}d", retCode);
408     return deferredPhotoProcSession;
409 }
410 
CreateDeferredPhotoProcessingSession(int userId,std::shared_ptr<IDeferredPhotoProcSessionCallback> callback,sptr<DeferredPhotoProcSession> * pDeferredPhotoProcSession)411 int CameraManager::CreateDeferredPhotoProcessingSession(int userId,
412     std::shared_ptr<IDeferredPhotoProcSessionCallback> callback,
413     sptr<DeferredPhotoProcSession> *pDeferredPhotoProcSession)
414 {
415     CAMERA_SYNC_TRACE;
416     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
417     CHECK_ERROR_RETURN_RET_LOG(samgr == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
418         "CreateDeferredPhotoProcessingSession Failed to get System ability manager");
419     sptr<IRemoteObject> object = samgr->GetSystemAbility(CAMERA_SERVICE_ID);
420     CHECK_ERROR_RETURN_RET_LOG(object == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
421         "CreateDeferredPhotoProcessingSession object is null");
422     sptr<ICameraService> serviceProxy = iface_cast<ICameraService>(object);
423     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
424         "CreateDeferredPhotoProcessingSession serviceProxy is null");
425 
426     sptr<DeferredPhotoProcSession> deferredPhotoProcSession =
427         new(std::nothrow) DeferredPhotoProcSession(userId, callback);
428     CHECK_ERROR_RETURN_RET_LOG(deferredPhotoProcSession == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
429         "CreateDeferredPhotoProcessingSession failed to new deferredPhotoProcSession!");
430     sptr<DeferredProcessing::IDeferredPhotoProcessingSessionCallback> remoteCallback =
431         new(std::nothrow) DeferredPhotoProcessingSessionCallback(deferredPhotoProcSession);
432     CHECK_ERROR_RETURN_RET_LOG(remoteCallback == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
433         "CreateDeferredPhotoProcessingSession failed to new remoteCallback!");
434 
435     sptr<DeferredProcessing::IDeferredPhotoProcessingSession> session = nullptr;
436     int32_t retCode = serviceProxy->CreateDeferredPhotoProcessingSession(userId, remoteCallback, session);
437     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
438         "Failed to get photo session!, %{public}d", retCode);
439     CHECK_ERROR_RETURN_RET_LOG(session == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
440         "CreateDeferredPhotoProcessingSession Failed to CreateDeferredPhotoProcessingSession as session is null");
441 
442     deferredPhotoProcSession->SetDeferredPhotoSession(session);
443     *pDeferredPhotoProcSession = deferredPhotoProcSession;
444     return CameraErrorCode::SUCCESS;
445 }
446 
CreateDeferredVideoProcessingSession(int userId,std::shared_ptr<IDeferredVideoProcSessionCallback> callback)447 sptr<DeferredVideoProcSession> CameraManager::CreateDeferredVideoProcessingSession(int userId,
448     std::shared_ptr<IDeferredVideoProcSessionCallback> callback)
449 {
450     CAMERA_SYNC_TRACE;
451     sptr<DeferredVideoProcSession> deferredVideoProcSession = nullptr;
452     int32_t retCode = CreateDeferredVideoProcessingSession(userId, callback, &deferredVideoProcSession);
453     CHECK_ERROR_RETURN_RET_LOG(retCode != CameraErrorCode::SUCCESS, nullptr,
454         "Failed to CreateDeferredVideoProcessingSession with error code:%{public}d", retCode);
455     return deferredVideoProcSession;
456 }
457 
CreateDeferredVideoProcessingSession(int userId,std::shared_ptr<IDeferredVideoProcSessionCallback> callback,sptr<DeferredVideoProcSession> * pDeferredVideoProcSession)458 int CameraManager::CreateDeferredVideoProcessingSession(int userId,
459     std::shared_ptr<IDeferredVideoProcSessionCallback> callback,
460     sptr<DeferredVideoProcSession> *pDeferredVideoProcSession)
461 {
462     CAMERA_SYNC_TRACE;
463     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
464     CHECK_ERROR_RETURN_RET_LOG(samgr == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
465         "CreateDeferredVideoProcessingSession Failed to get System ability manager");
466     sptr<IRemoteObject> object = samgr->GetSystemAbility(CAMERA_SERVICE_ID);
467     CHECK_ERROR_RETURN_RET_LOG(object == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
468         "CreateDeferredVideoProcessingSession object is null");
469     sptr<ICameraService> serviceProxy = iface_cast<ICameraService>(object);
470     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
471         "CreateDeferredVideoProcessingSession serviceProxy is null");
472 
473     auto deferredVideoProcSession = new(std::nothrow) DeferredVideoProcSession(userId, callback);
474     CHECK_ERROR_RETURN_RET_LOG(deferredVideoProcSession == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
475         "CreateDeferredVideoProcessingSession failed to new deferredVideoProcSession!");
476     sptr<DeferredProcessing::IDeferredVideoProcessingSessionCallback> remoteCallback =
477         new(std::nothrow) DeferredVideoProcessingSessionCallback(deferredVideoProcSession);
478     CHECK_ERROR_RETURN_RET_LOG(remoteCallback == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
479         "CreateDeferredVideoProcessingSession failed to new remoteCallback!");
480 
481     sptr<DeferredProcessing::IDeferredVideoProcessingSession> session = nullptr;
482     int32_t retCode = serviceProxy->CreateDeferredVideoProcessingSession(userId, remoteCallback, session);
483     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
484         "Failed to get video session!, %{public}d", retCode);
485     CHECK_ERROR_RETURN_RET_LOG(session == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
486         "CreateDeferredVideoProcessingSession Failed to CreateDeferredVideoProcessingSession as session is null");
487 
488     deferredVideoProcSession->SetDeferredVideoSession(session);
489     *pDeferredVideoProcSession = deferredVideoProcSession;
490     return CameraErrorCode::SUCCESS;
491 }
492 
CreatePhotoOutput(sptr<IBufferProducer> & surface)493 sptr<PhotoOutput> CameraManager::CreatePhotoOutput(sptr<IBufferProducer> &surface)
494 {
495     CAMERA_SYNC_TRACE;
496     sptr<PhotoOutput> result = nullptr;
497     return result;
498 }
499 
CreatePhotoOutput(Profile & profile,sptr<IBufferProducer> & surface)500 sptr<PhotoOutput> CameraManager::CreatePhotoOutput(Profile &profile, sptr<IBufferProducer> &surface)
501 {
502     CAMERA_SYNC_TRACE;
503     sptr<PhotoOutput> photoOutput = nullptr;
504     int32_t retCode = CreatePhotoOutput(profile, surface, &photoOutput);
505     CHECK_ERROR_RETURN_RET_LOG(retCode != CameraErrorCode::SUCCESS, nullptr,
506         "Failed to CreatePhotoOutput with error code:%{public}d", retCode);
507     return photoOutput;
508 }
509 
CreatePhotoOutputWithoutProfile(sptr<IBufferProducer> surface,sptr<PhotoOutput> * pPhotoOutput)510 int CameraManager::CreatePhotoOutputWithoutProfile(sptr<IBufferProducer> surface, sptr<PhotoOutput>* pPhotoOutput)
511 {
512     CAMERA_SYNC_TRACE;
513     auto serviceProxy = GetServiceProxy();
514     CHECK_ERROR_RETURN_RET_LOG((serviceProxy == nullptr) || (surface == nullptr), CameraErrorCode::INVALID_ARGUMENT,
515         "CreatePhotoOutputWithoutProfile serviceProxy is null or PhotoOutputSurface is null");
516     sptr<PhotoOutput> photoOutput = new (std::nothrow) PhotoOutput(surface);
517     CHECK_ERROR_RETURN_RET(photoOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
518     photoOutput->AddTag(CaptureOutput::DYNAMIC_PROFILE);
519     *pPhotoOutput = photoOutput;
520     return CameraErrorCode::SUCCESS;
521 }
522 
CreatePhotoOutput(Profile & profile,sptr<IBufferProducer> & surface,sptr<PhotoOutput> * pPhotoOutput)523 int CameraManager::CreatePhotoOutput(Profile &profile, sptr<IBufferProducer> &surface, sptr<PhotoOutput> *pPhotoOutput)
524     __attribute__((no_sanitize("cfi")))
525 {
526     CAMERA_SYNC_TRACE;
527     auto serviceProxy = GetServiceProxy();
528     CHECK_ERROR_RETURN_RET_LOG((serviceProxy == nullptr) || (surface == nullptr), CameraErrorCode::INVALID_ARGUMENT,
529         "CreatePhotoOutput serviceProxy is null or PhotoOutputSurface/profile is null");
530     CHECK_ERROR_RETURN_RET_LOG((profile.GetCameraFormat() == CAMERA_FORMAT_INVALID) || (profile.GetSize().width == 0)
531         || (profile.GetSize().height == 0), CameraErrorCode::INVALID_ARGUMENT,
532         "CreatePhotoOutput invalid fomrat or width or height is zero");
533     // to adapter yuv photo
534     CameraFormat yuvFormat = profile.GetCameraFormat();
535     camera_format_t metaFormat = GetCameraMetadataFormat(yuvFormat);
536     sptr<IStreamCapture> streamCapture = nullptr;
537     int32_t retCode = serviceProxy->CreatePhotoOutput(
538         surface, metaFormat, profile.GetSize().width, profile.GetSize().height, streamCapture);
539     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
540         "Failed to get stream capture object from hcamera service!, %{public}d", retCode);
541     sptr<PhotoOutput> photoOutput = new(std::nothrow) PhotoOutput(surface);
542     CHECK_ERROR_RETURN_RET(photoOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
543     photoOutput->SetStream(streamCapture);
544     photoOutput->SetPhotoProfile(profile);
545     *pPhotoOutput = photoOutput;
546     return CameraErrorCode::SUCCESS;
547 }
548 
CreatePreviewOutput(Profile & profile,sptr<Surface> surface)549 sptr<PreviewOutput> CameraManager::CreatePreviewOutput(Profile &profile, sptr<Surface> surface)
550 {
551     CAMERA_SYNC_TRACE;
552     sptr<PreviewOutput> previewOutput = nullptr;
553     int32_t retCode = CreatePreviewOutput(profile, surface, &previewOutput);
554     CHECK_ERROR_RETURN_RET_LOG(retCode != CameraErrorCode::SUCCESS, nullptr,
555         "Failed to CreatePreviewOutput with error code:%{public}d", retCode);
556 
557     return previewOutput;
558 }
559 
CreatePreviewOutputWithoutProfile(sptr<Surface> surface,sptr<PreviewOutput> * pPreviewOutput)560 int CameraManager::CreatePreviewOutputWithoutProfile(sptr<Surface> surface, sptr<PreviewOutput>* pPreviewOutput)
561 {
562     CAMERA_SYNC_TRACE;
563     sptr<PreviewOutput> previewOutput = nullptr;
564     auto serviceProxy = GetServiceProxy();
565     CHECK_ERROR_RETURN_RET_LOG((serviceProxy == nullptr) || (surface == nullptr), CameraErrorCode::INVALID_ARGUMENT,
566         "CreatePreviewOutputWithoutProfile serviceProxy is null or surface is null");
567     previewOutput = new (std::nothrow) PreviewOutput(surface->GetProducer());
568     CHECK_ERROR_RETURN_RET(previewOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
569     previewOutput->AddTag(CaptureOutput::DYNAMIC_PROFILE);
570     *pPreviewOutput = previewOutput;
571     return CAMERA_OK;
572 }
573 
CreatePreviewOutput(Profile & profile,sptr<Surface> surface,sptr<PreviewOutput> * pPreviewOutput)574 int CameraManager::CreatePreviewOutput(Profile &profile, sptr<Surface> surface, sptr<PreviewOutput> *pPreviewOutput)
575 {
576     CAMERA_SYNC_TRACE;
577     auto serviceProxy = GetServiceProxy();
578     CHECK_ERROR_RETURN_RET_LOG((serviceProxy == nullptr) || (surface == nullptr), CameraErrorCode::INVALID_ARGUMENT,
579         "CreatePreviewOutput serviceProxy is null or previewOutputSurface/profile is null");
580     CHECK_ERROR_RETURN_RET_LOG((profile.GetCameraFormat() == CAMERA_FORMAT_INVALID) || (profile.GetSize().width == 0)
581         || (profile.GetSize().height == 0), CameraErrorCode::INVALID_ARGUMENT,
582         "CreatePreviewOutput invalid fomrat or width or height is zero");
583 
584     camera_format_t metaFormat = GetCameraMetadataFormat(profile.GetCameraFormat());
585     sptr<IStreamRepeat> streamRepeat = nullptr;
586     int32_t retCode = serviceProxy->CreatePreviewOutput(
587         surface->GetProducer(), metaFormat, profile.GetSize().width, profile.GetSize().height, streamRepeat);
588     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
589         "Failed to get stream repeat object from hcamera service! %{public}d", retCode);
590     sptr<PreviewOutput> previewOutput = new (std::nothrow) PreviewOutput(surface->GetProducer());
591     CHECK_ERROR_RETURN_RET(previewOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
592     previewOutput->SetStream(streamRepeat);
593     previewOutput->SetOutputFormat(profile.GetCameraFormat());
594     previewOutput->SetSize(profile.GetSize());
595     previewOutput->SetPreviewProfile(profile);
596     *pPreviewOutput = previewOutput;
597     return CameraErrorCode::SUCCESS;
598 }
599 
CreatePreviewOutputStream(sptr<IStreamRepeat> & streamPtr,Profile & profile,const sptr<OHOS::IBufferProducer> & producer)600 int32_t CameraManager::CreatePreviewOutputStream(
601     sptr<IStreamRepeat>& streamPtr, Profile& profile, const sptr<OHOS::IBufferProducer>& producer)
602 {
603     auto validResult = ValidCreateOutputStream(profile, producer);
604     CHECK_ERROR_RETURN_RET_LOG(validResult != SUCCESS, validResult,
605         "CameraManager::CreatePreviewOutputStream ValidCreateOutputStream fail:%{public}d", validResult);
606 
607     auto serviceProxy = GetServiceProxy();
608     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
609         "CameraManager::CreatePreviewOutputStream serviceProxy is null");
610     camera_format_t metaFormat = GetCameraMetadataFormat(profile.GetCameraFormat());
611     int32_t retCode = serviceProxy->CreatePreviewOutput(
612         producer, metaFormat, profile.GetSize().width, profile.GetSize().height, streamPtr);
613     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
614         "CreatePreviewOutputStream Failed to get stream repeat object from hcamera service! %{public}d", retCode);
615     return CameraErrorCode::SUCCESS;
616 }
617 
CreatePhotoOutputStream(sptr<IStreamCapture> & streamPtr,Profile & profile,const sptr<OHOS::IBufferProducer> & producer)618 int32_t CameraManager::CreatePhotoOutputStream(
619     sptr<IStreamCapture>& streamPtr, Profile& profile, const sptr<OHOS::IBufferProducer>& producer)
620 {
621     auto validResult = ValidCreateOutputStream(profile, producer);
622     CHECK_ERROR_RETURN_RET_LOG(validResult != SUCCESS, validResult,
623         "CameraManager::CreatePhotoOutputStream ValidCreateOutputStream fail:%{public}d", validResult);
624     auto serviceProxy = GetServiceProxy();
625     CHECK_ERROR_RETURN_RET_LOG((serviceProxy == nullptr) || (producer == nullptr), CameraErrorCode::INVALID_ARGUMENT,
626         "CameraManager::CreatePhotoOutputStream serviceProxy is null or producer is null");
627 
628     CameraFormat yuvFormat = profile.GetCameraFormat();
629     auto metaFormat = GetCameraMetadataFormat(yuvFormat);
630     auto retCode = serviceProxy->CreatePhotoOutput(
631         producer, metaFormat, profile.GetSize().width, profile.GetSize().height, streamPtr);
632     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
633         "CameraManager::CreatePhotoOutputStream Failed to get stream capture object from hcamera service! "
634         "%{public}d", retCode);
635     return CameraErrorCode::SUCCESS;
636 }
637 
ValidCreateOutputStream(Profile & profile,const sptr<OHOS::IBufferProducer> & producer)638 int32_t CameraManager::ValidCreateOutputStream(Profile& profile, const sptr<OHOS::IBufferProducer>& producer)
639 {
640     CHECK_ERROR_RETURN_RET_LOG(producer == nullptr, CameraErrorCode::INVALID_ARGUMENT,
641         "CameraManager::ValidCreateOutputStream producer is null");
642     CHECK_ERROR_RETURN_RET_LOG((profile.GetCameraFormat() == CAMERA_FORMAT_INVALID) || (profile.GetSize().width == 0)
643         || (profile.GetSize().height == 0), CameraErrorCode::INVALID_ARGUMENT,
644         "CameraManager::ValidCreateOutputStream width or height is zero");
645     return CameraErrorCode::SUCCESS;
646 }
647 
CreateDeferredPreviewOutput(Profile & profile)648 sptr<PreviewOutput> CameraManager::CreateDeferredPreviewOutput(Profile &profile)
649 {
650     CAMERA_SYNC_TRACE;
651     MEDIA_INFO_LOG("CameraManager::CreateDeferredPreviewOutput called");
652     sptr<PreviewOutput> previewOutput = nullptr;
653     int32_t retCode = CreateDeferredPreviewOutput(profile, &previewOutput);
654     CHECK_ERROR_RETURN_RET_LOG(retCode != CameraErrorCode::SUCCESS, nullptr,
655         "CameraManager Failed to CreateDeferredPreviewOutput with error code:%{public}d", retCode);
656     return previewOutput;
657 }
658 
CreateDeferredPreviewOutput(Profile & profile,sptr<PreviewOutput> * pPreviewOutput)659 int CameraManager::CreateDeferredPreviewOutput(Profile &profile, sptr<PreviewOutput> *pPreviewOutput)
660 {
661     CAMERA_SYNC_TRACE;
662     auto serviceProxy = GetServiceProxy();
663     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, CameraErrorCode::INVALID_ARGUMENT,
664         "CameraManager::CreateDeferredPreviewOutput serviceProxy is null");
665     CHECK_ERROR_RETURN_RET_LOG((profile.GetCameraFormat() == CAMERA_FORMAT_INVALID) || (profile.GetSize().width == 0)
666         || (profile.GetSize().height == 0), CameraErrorCode::INVALID_ARGUMENT,
667         "CreateDeferredPreviewOutput invalid fomrat or width or height is zero");
668 
669     camera_format_t metaFormat = GetCameraMetadataFormat(profile.GetCameraFormat());
670     sptr<IStreamRepeat> streamRepeat = nullptr;
671     int32_t retCode = serviceProxy->CreateDeferredPreviewOutput(
672         metaFormat, profile.GetSize().width, profile.GetSize().height, streamRepeat);
673     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
674         "CreateDeferredPreviewOutput Failed to get stream repeat object from hcamera service!, %{public}d", retCode);
675     sptr<PreviewOutput> previewOutput = new(std::nothrow) PreviewOutput();
676     CHECK_ERROR_RETURN_RET(previewOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
677     previewOutput->SetStream(streamRepeat);
678     previewOutput->SetPreviewProfile(profile);
679     *pPreviewOutput = previewOutput;
680     return CameraErrorCode::SUCCESS;
681 }
682 
CreatePreviewOutput(const sptr<OHOS::IBufferProducer> & producer,int32_t format)683 sptr<PreviewOutput> CameraManager::CreatePreviewOutput(const sptr<OHOS::IBufferProducer> &producer, int32_t format)
684 {
685     CAMERA_SYNC_TRACE;
686     sptr<PreviewOutput> result = nullptr;
687     return result;
688 }
689 
CreateCustomPreviewOutput(sptr<Surface> surface,int32_t width,int32_t height)690 sptr<PreviewOutput> CameraManager::CreateCustomPreviewOutput(sptr<Surface> surface, int32_t width, int32_t height)
691 {
692     CAMERA_SYNC_TRACE;
693     sptr<PreviewOutput> result = nullptr;
694     return result;
695 }
696 
CreateMetadataOutput()697 sptr<MetadataOutput> CameraManager::CreateMetadataOutput()
698 {
699     CAMERA_SYNC_TRACE;
700     sptr<MetadataOutput> metadataOutput = nullptr;
701     int32_t retCode = CreateMetadataOutput(metadataOutput);
702     CHECK_ERROR_RETURN_RET_LOG(retCode != CameraErrorCode::SUCCESS, nullptr,
703         "CameraManager Failed to CreateMetadataOutput with error code:%{public}d", retCode);
704     return metadataOutput;
705 }
706 
CreateMetadataOutput(sptr<MetadataOutput> & pMetadataOutput)707 int CameraManager::CreateMetadataOutput(sptr<MetadataOutput>& pMetadataOutput)
708 {
709     return CreateMetadataOutputInternal(pMetadataOutput);
710 }
711 
CreateMetadataOutput(sptr<MetadataOutput> & pMetadataOutput,std::vector<MetadataObjectType> metadataObjectTypes)712 int CameraManager::CreateMetadataOutput(sptr<MetadataOutput>& pMetadataOutput,
713     std::vector<MetadataObjectType> metadataObjectTypes)
714 {
715     return CreateMetadataOutputInternal(pMetadataOutput, metadataObjectTypes);
716 }
717 
CreateDepthDataOutput(DepthProfile & depthProfile,sptr<IBufferProducer> & surface)718 sptr<DepthDataOutput> CameraManager::CreateDepthDataOutput(DepthProfile& depthProfile, sptr<IBufferProducer> &surface)
719 {
720     CAMERA_SYNC_TRACE;
721     sptr<DepthDataOutput> depthDataOutput = nullptr;
722     int ret = CreateDepthDataOutput(depthProfile, surface, &depthDataOutput);
723     if (ret != CameraErrorCode::SUCCESS) {
724         MEDIA_ERR_LOG("Failed to CreateDepthDataOutput with error code:%{public}d", ret);
725         return nullptr;
726     }
727     return depthDataOutput;
728 }
729 
CreateDepthDataOutput(DepthProfile & depthProfile,sptr<IBufferProducer> & surface,sptr<DepthDataOutput> * pDepthDataOutput)730 int CameraManager::CreateDepthDataOutput(DepthProfile& depthProfile, sptr<IBufferProducer> &surface,
731     sptr<DepthDataOutput>* pDepthDataOutput)
732 {
733     CAMERA_SYNC_TRACE;
734     sptr<IStreamDepthData> streamDepthData = nullptr;
735     sptr<DepthDataOutput> depthDataOutput = nullptr;
736     int32_t retCode = CAMERA_OK;
737     camera_format_t metaFormat;
738 
739     auto serviceProxy = GetServiceProxy();
740     if ((serviceProxy == nullptr) || (surface == nullptr)) {
741         MEDIA_ERR_LOG("serviceProxy is null or DepthDataOutputSurface/profile is null");
742         return CameraErrorCode::INVALID_ARGUMENT;
743     }
744 
745     if ((depthProfile.GetCameraFormat() == CAMERA_FORMAT_INVALID) ||
746         (depthProfile.GetSize().width == 0) ||
747         (depthProfile.GetSize().height == 0)) {
748         MEDIA_ERR_LOG("invalid fomrat or width or height is zero");
749         return CameraErrorCode::INVALID_ARGUMENT;
750     }
751 
752     metaFormat = GetCameraMetadataFormat(depthProfile.GetCameraFormat());
753     retCode = serviceProxy->CreateDepthDataOutput(
754         surface, metaFormat, depthProfile.GetSize().width, depthProfile.GetSize().height, streamDepthData);
755     if (retCode == CAMERA_OK) {
756         depthDataOutput = new(std::nothrow) DepthDataOutput(surface);
757         if (depthDataOutput == nullptr) {
758             return CameraErrorCode::SERVICE_FATL_ERROR;
759         }
760         depthDataOutput->SetStream(streamDepthData);
761     } else {
762         MEDIA_ERR_LOG("Failed to get stream depth data object from hcamera service!, %{public}d", retCode);
763         return ServiceToCameraError(retCode);
764     }
765     depthDataOutput->SetDepthProfile(depthProfile);
766     *pDepthDataOutput = depthDataOutput;
767     return CameraErrorCode::SUCCESS;
768 }
769 
CreateVideoOutput(sptr<Surface> & surface)770 sptr<VideoOutput> CameraManager::CreateVideoOutput(sptr<Surface> &surface)
771 {
772     CAMERA_SYNC_TRACE;
773     sptr<VideoOutput> result = nullptr;
774     return result;
775 }
776 
CreateVideoOutput(VideoProfile & profile,sptr<Surface> & surface)777 sptr<VideoOutput> CameraManager::CreateVideoOutput(VideoProfile &profile, sptr<Surface> &surface)
778 {
779     CAMERA_SYNC_TRACE;
780     sptr<VideoOutput> videoOutput = nullptr;
781     int32_t retCode = CreateVideoOutput(profile, surface, &videoOutput);
782     CHECK_ERROR_RETURN_RET_LOG(retCode != CameraErrorCode::SUCCESS, nullptr,
783         "CreateVideoOutput Failed to CreateVideoOutput with error code:%{public}d", retCode);
784     return videoOutput;
785 }
786 
CreateVideoOutputStream(sptr<IStreamRepeat> & streamPtr,Profile & profile,const sptr<OHOS::IBufferProducer> & producer)787 int32_t CameraManager::CreateVideoOutputStream(
788     sptr<IStreamRepeat>& streamPtr, Profile& profile, const sptr<OHOS::IBufferProducer>& producer)
789 {
790     auto validResult = ValidCreateOutputStream(profile, producer);
791     CHECK_ERROR_RETURN_RET_LOG(validResult != SUCCESS, validResult,
792         "CameraManager::CreateVideoOutputStream ValidCreateOutputStream fail:%{public}d", validResult);
793 
794     auto serviceProxy = GetServiceProxy();
795     CHECK_ERROR_RETURN_RET_LOG((serviceProxy == nullptr) || (producer == nullptr), CameraErrorCode::INVALID_ARGUMENT,
796         "CameraManager::CreateVideoOutputStream serviceProxy is null or producer is null");
797 
798     auto metaFormat = GetCameraMetadataFormat(profile.GetCameraFormat());
799     MEDIA_DEBUG_LOG("metaFormat = %{public}d", static_cast<int32_t>(metaFormat));
800     int32_t retCode = serviceProxy->CreateVideoOutput(
801         producer, metaFormat, profile.GetSize().width, profile.GetSize().height, streamPtr);
802     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
803         "CameraManager::CreateVideoOutputStream Failed to get stream capture object from hcamera service! "
804         "%{public}d", retCode);
805     return CameraErrorCode::SUCCESS;
806 }
807 
CreateVideoOutputWithoutProfile(sptr<Surface> surface,sptr<VideoOutput> * pVideoOutput)808 int CameraManager::CreateVideoOutputWithoutProfile(sptr<Surface> surface, sptr<VideoOutput>* pVideoOutput)
809 {
810     CAMERA_SYNC_TRACE;
811     auto serviceProxy = GetServiceProxy();
812     CHECK_ERROR_RETURN_RET_LOG((serviceProxy == nullptr) || (surface == nullptr), CameraErrorCode::INVALID_ARGUMENT,
813         "CameraManager::CreateVideoOutput serviceProxy is null or VideoOutputSurface is null");
814 
815     sptr<VideoOutput> videoOutput = new (std::nothrow) VideoOutput(surface->GetProducer());
816     CHECK_ERROR_RETURN_RET(videoOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
817     videoOutput->AddTag(CaptureOutput::DYNAMIC_PROFILE);
818     *pVideoOutput = videoOutput;
819     return CameraErrorCode::SUCCESS;
820 }
821 
CreateVideoOutput(VideoProfile & profile,sptr<Surface> & surface,sptr<VideoOutput> * pVideoOutput)822 int CameraManager::CreateVideoOutput(VideoProfile &profile, sptr<Surface> &surface, sptr<VideoOutput> *pVideoOutput)
823 {
824     CAMERA_SYNC_TRACE;
825     auto serviceProxy = GetServiceProxy();
826     CHECK_ERROR_RETURN_RET_LOG((serviceProxy == nullptr) || (surface == nullptr), CameraErrorCode::INVALID_ARGUMENT,
827         "CameraManager::CreateVideoOutput serviceProxy is null or VideoOutputSurface/profile is null");
828     CHECK_ERROR_RETURN_RET_LOG((profile.GetCameraFormat() == CAMERA_FORMAT_INVALID) || (profile.GetSize().width == 0)
829         || (profile.GetSize().height == 0), CameraErrorCode::INVALID_ARGUMENT,
830         "CreateVideoOutput invalid fomrat or width or height is zero");
831 
832     camera_format_t metaFormat = GetCameraMetadataFormat(profile.GetCameraFormat());
833     MEDIA_DEBUG_LOG("metaFormat = %{public}d", static_cast<int32_t>(metaFormat));
834     sptr<IStreamRepeat> streamRepeat = nullptr;
835     int32_t retCode = serviceProxy->CreateVideoOutput(
836         surface->GetProducer(), metaFormat, profile.GetSize().width, profile.GetSize().height, streamRepeat);
837     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
838         "CameraManager::CreateVideoOutput Failed to get stream capture object from hcamera service! "
839         "%{public}d", retCode);
840     sptr<VideoOutput> videoOutput = new(std::nothrow) VideoOutput(surface->GetProducer());
841     CHECK_ERROR_RETURN_RET(videoOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR);
842     videoOutput->SetStream(streamRepeat);
843     videoOutput->SetOutputFormat(profile.GetCameraFormat());
844     videoOutput->SetSize(profile.GetSize());
845     videoOutput->SetVideoProfile(profile);
846     *pVideoOutput = videoOutput;
847 
848     return CameraErrorCode::SUCCESS;
849 }
850 
InitCameraManager()851 void CameraManager::InitCameraManager()
852 {
853     CAMERA_SYNC_TRACE;
854     int32_t retCode = SubscribeSystemAbility();
855     CHECK_ERROR_RETURN_LOG(retCode != CameraErrorCode::SUCCESS, "failed to SubscribeSystemAbilityd");
856     retCode = RefreshServiceProxy();
857     CHECK_ERROR_RETURN_LOG(retCode != CameraErrorCode::SUCCESS, "RefreshServiceProxy fail , ret = %{public}d",
858         retCode);
859     retCode = AddServiceProxyDeathRecipient();
860     CHECK_ERROR_RETURN_LOG(retCode != CameraErrorCode::SUCCESS, "AddServiceProxyDeathRecipient fail ,"
861         "ret = %{public}d", retCode);
862     retCode = CreateListenerObject();
863     CHECK_ERROR_RETURN_LOG(retCode != CAMERA_OK, "failed to new CameraListenerStub, ret = %{public}d", retCode);
864     foldScreenType_ = system::GetParameter("const.window.foldscreen.type", "");
865     isSystemApp_ = CameraSecurity::CheckSystemApp();
866     MEDIA_DEBUG_LOG("IsSystemApp = %{public}d", isSystemApp_);
867 }
868 
RefreshServiceProxy()869 int32_t CameraManager::RefreshServiceProxy()
870 {
871     sptr<IRemoteObject> object = nullptr;
872     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
873     CHECK_ERROR_RETURN_RET_LOG(samgr == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
874         "CameraManager::RefreshServiceProxy Failed to get System ability manager");
875     object = samgr->GetSystemAbility(CAMERA_SERVICE_ID);
876     CHECK_ERROR_RETURN_RET_LOG(object == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
877         "CameraManager::RefreshServiceProxy Init GetSystemAbility %{public}d is null", CAMERA_SERVICE_ID);
878     auto serviceProxy = iface_cast<ICameraService>(object);
879     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
880         "CameraManager::RefreshServiceProxy serviceProxy is null");
881     SetServiceProxy(serviceProxy);
882     return CameraErrorCode::SUCCESS;
883 }
884 
SubscribeSystemAbility()885 int32_t CameraManager::SubscribeSystemAbility()
886 {
887     MEDIA_INFO_LOG("Enter Into CameraManager::SubscribeSystemAbility");
888     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
889     CHECK_ERROR_RETURN_RET_LOG(samgr == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
890         "CameraManager::SubscribeSystemAbility Failed to get System ability manager");
891     saListener_ = new CameraServiceSystemAbilityListener();
892     CHECK_ERROR_RETURN_RET_LOG(saListener_ == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
893         "CameraManager::SubscribeSystemAbility saListener_ is null");
894     int32_t ret = samgr->SubscribeSystemAbility(CAMERA_SERVICE_ID, saListener_);
895     MEDIA_INFO_LOG("SubscribeSystemAbility ret = %{public}d", ret);
896     return ret == 0 ? CameraErrorCode::SUCCESS : CameraErrorCode::SERVICE_FATL_ERROR;
897 }
898 
UnSubscribeSystemAbility()899 int32_t CameraManager::UnSubscribeSystemAbility()
900 {
901     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
902     CHECK_ERROR_RETURN_RET_LOG(samgr == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
903         "CameraManager::UnSubscribeSystemAbility Failed to get System ability manager");
904     CHECK_ERROR_RETURN_RET(saListener_ == nullptr, CameraErrorCode::SUCCESS);
905     int32_t ret = samgr->UnSubscribeSystemAbility(CAMERA_SERVICE_ID, saListener_);
906     MEDIA_INFO_LOG("UnSubscribeSystemAbility ret = %{public}d", ret);
907     saListener_ = nullptr;
908     return ret == 0 ? CameraErrorCode::SUCCESS : CameraErrorCode::SERVICE_FATL_ERROR;
909 }
910 
OnCameraServerAlive()911 void CameraManager::OnCameraServerAlive()
912 {
913     int32_t ret = RefreshServiceProxy();
914     CHECK_ERROR_RETURN_LOG(ret != CameraErrorCode::SUCCESS, "RefreshServiceProxy fail , ret = %{public}d", ret);
915     AddServiceProxyDeathRecipient();
916     CHECK_EXECUTE(cameraSvcCallback_ != nullptr, SetCameraServiceCallback(cameraSvcCallback_));
917     CHECK_EXECUTE(cameraMuteSvcCallback_ != nullptr, SetCameraMuteServiceCallback(cameraMuteSvcCallback_));
918     CHECK_EXECUTE(torchSvcCallback_ != nullptr, SetTorchServiceCallback(torchSvcCallback_));
919     CHECK_EXECUTE(foldSvcCallback_ != nullptr, SetFoldServiceCallback(foldSvcCallback_));
920 }
921 
DestroyStubObj()922 int32_t CameraManager::DestroyStubObj()
923 {
924     MEDIA_INFO_LOG("Enter Into CameraManager::DestroyStubObj");
925     UnSubscribeSystemAbility();
926     int32_t retCode = CAMERA_UNKNOWN_ERROR;
927     auto serviceProxy = GetServiceProxy();
928     if (serviceProxy == nullptr) {
929         MEDIA_ERR_LOG("serviceProxy is null");
930     } else {
931         retCode = serviceProxy->DestroyStubObj();
932         CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK, "Failed to DestroyStubObj, retCode: %{public}d", retCode);
933     }
934     return ServiceToCameraError(retCode);
935 }
936 
CameraServerDied(pid_t pid)937 void CameraManager::CameraServerDied(pid_t pid)
938 {
939     MEDIA_ERR_LOG("camera server has died, pid:%{public}d!", pid);
940     RemoveServiceProxyDeathRecipient();
941     SetServiceProxy(nullptr);
942     CHECK_ERROR_RETURN_LOG(cameraSvcCallback_ == nullptr, "CameraServerDied cameraSvcCallback_ is nullptr");
943     auto cameraDeviceList = GetCameraDeviceList();
944     for (size_t i = 0; i < cameraDeviceList.size(); i++) {
945         CameraStatusInfo cameraStatusInfo;
946         cameraStatusInfo.cameraDevice = cameraDeviceList[i];
947         cameraStatusInfo.cameraStatus = CAMERA_SERVER_UNAVAILABLE;
948         auto listenerMap = GetCameraMngrCallbackMap();
949         listenerMap.Iterate([&](std::thread::id threadId,
950             std::shared_ptr<CameraManagerCallback> cameraManagerCallback) {
951             MEDIA_INFO_LOG("Callback cameraStatus");
952             if (cameraManagerCallback != nullptr) {
953                 cameraManagerCallback->OnCameraStatusChanged(cameraStatusInfo);
954             }
955         });
956     }
957 }
958 
AddServiceProxyDeathRecipient()959 int32_t CameraManager::AddServiceProxyDeathRecipient()
960 {
961     std::lock_guard<std::mutex> lock(deathRecipientMutex_);
962     pid_t pid = 0;
963     deathRecipient_ = new (std::nothrow) CameraDeathRecipient(pid);
964     CHECK_ERROR_RETURN_RET_LOG(deathRecipient_ == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
965         "CameraManager::AddServiceProxyDeathRecipient failed to new CameraDeathRecipient");
966     auto thisPtr = wptr<CameraManager>(this);
967     deathRecipient_->SetNotifyCb([thisPtr](pid_t pid) {
968         auto cameraManagerPtr = thisPtr.promote();
969         if (cameraManagerPtr != nullptr) {
970             cameraManagerPtr->CameraServerDied(pid);
971         }
972     });
973     auto serviceProxy = GetServiceProxy();
974     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
975         "CameraManager::AddServiceProxyDeathRecipient serviceProxy is null");
976     bool result = serviceProxy->AsObject()->AddDeathRecipient(deathRecipient_);
977     CHECK_ERROR_RETURN_RET_LOG(!result, CameraErrorCode::SERVICE_FATL_ERROR,
978         "CameraManager::AddServiceProxyDeathRecipient failed to add deathRecipient");
979     return CameraErrorCode::SUCCESS;
980 }
981 
RemoveServiceProxyDeathRecipient()982 void CameraManager::RemoveServiceProxyDeathRecipient()
983 {
984     std::lock_guard<std::mutex> lock(deathRecipientMutex_);
985     auto serviceProxy = GetServiceProxy();
986     if (serviceProxy != nullptr) {
987         (void)serviceProxy->AsObject()->RemoveDeathRecipient(deathRecipient_);
988     }
989     deathRecipient_ = nullptr;
990 }
991 
CreateCameraDevice(std::string cameraId,sptr<ICameraDeviceService> * pICameraDeviceService)992 int CameraManager::CreateCameraDevice(std::string cameraId, sptr<ICameraDeviceService> *pICameraDeviceService)
993 {
994     CAMERA_SYNC_TRACE;
995     auto serviceProxy = GetServiceProxy();
996     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr || cameraId.empty(), CameraErrorCode::INVALID_ARGUMENT,
997         "CameraManager::CreateCameraDevice serviceProxy is null or CameraID is empty: %{public}s", cameraId.c_str());
998     sptr<ICameraDeviceService> device = nullptr;
999     int32_t retCode = serviceProxy->CreateCameraDevice(cameraId, device);
1000     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
1001         "CameraManager::CreateCameraDeviceFailed to create camera device from hcamera service! %{public}d", retCode);
1002     *pICameraDeviceService = device;
1003     return CameraErrorCode::SUCCESS;
1004 }
1005 
SetCallback(std::shared_ptr<CameraManagerCallback> callback)1006 void CameraManager::SetCallback(std::shared_ptr<CameraManagerCallback> callback)
1007 {
1008     std::thread::id threadId = std::this_thread::get_id();
1009     cameraMngrCallbackMap_.EnsureInsert(threadId, callback);
1010     CHECK_EXECUTE(cameraSvcCallback_ == nullptr, CreateAndSetCameraServiceCallback());
1011 }
1012 
GetApplicationCallback()1013 std::shared_ptr<CameraManagerCallback> CameraManager::GetApplicationCallback()
1014 {
1015     std::thread::id threadId = std::this_thread::get_id();
1016     std::shared_ptr<CameraManagerCallback> callback = nullptr;
1017     cameraMngrCallbackMap_.Find(threadId, callback);
1018     return callback;
1019 }
1020 
RegisterCameraMuteListener(std::shared_ptr<CameraMuteListener> listener)1021 void CameraManager::RegisterCameraMuteListener(std::shared_ptr<CameraMuteListener> listener)
1022 {
1023     std::thread::id threadId = std::this_thread::get_id();
1024     cameraMuteListenerMap_.EnsureInsert(threadId, listener);
1025     CHECK_EXECUTE(cameraMuteSvcCallback_ == nullptr, CreateAndSetCameraMuteServiceCallback());
1026 }
1027 
GetCameraMuteListener()1028 shared_ptr<CameraMuteListener> CameraManager::GetCameraMuteListener()
1029 {
1030     std::thread::id threadId = std::this_thread::get_id();
1031     std::shared_ptr<CameraMuteListener> listener = nullptr;
1032     cameraMuteListenerMap_.Find(threadId, listener);
1033     return listener;
1034 }
1035 
RegisterTorchListener(shared_ptr<TorchListener> listener)1036 void CameraManager::RegisterTorchListener(shared_ptr<TorchListener> listener)
1037 {
1038     std::thread::id threadId = std::this_thread::get_id();
1039     torchListenerMap_.EnsureInsert(threadId, listener);
1040     CHECK_EXECUTE(torchSvcCallback_ == nullptr, CreateAndSetTorchServiceCallback());
1041 }
1042 
GetTorchListener()1043 shared_ptr<TorchListener> CameraManager::GetTorchListener()
1044 {
1045     std::thread::id threadId = std::this_thread::get_id();
1046     std::shared_ptr<TorchListener> listener = nullptr;
1047     torchListenerMap_.Find(threadId, listener);
1048     return listener;
1049 }
1050 
RegisterFoldListener(shared_ptr<FoldListener> listener)1051 void CameraManager::RegisterFoldListener(shared_ptr<FoldListener> listener)
1052 {
1053     std::thread::id threadId = std::this_thread::get_id();
1054     foldListenerMap_.EnsureInsert(threadId, listener);
1055     CHECK_EXECUTE(foldSvcCallback_ == nullptr, CreateAndSetFoldServiceCallback());
1056 }
1057 
GetFoldListener()1058 shared_ptr<FoldListener> CameraManager::GetFoldListener()
1059 {
1060     std::thread::id threadId = std::this_thread::get_id();
1061     std::shared_ptr<FoldListener> listener = nullptr;
1062     foldListenerMap_.Find(threadId, listener);
1063     return listener;
1064 }
1065 
GetCameraMngrCallbackMap()1066 SafeMap<std::thread::id, std::shared_ptr<CameraManagerCallback>> CameraManager::GetCameraMngrCallbackMap()
1067 {
1068     return cameraMngrCallbackMap_;
1069 }
GetCameraMuteListenerMap()1070 SafeMap<std::thread::id, std::shared_ptr<CameraMuteListener>> CameraManager::GetCameraMuteListenerMap()
1071 {
1072     return cameraMuteListenerMap_;
1073 }
GetTorchListenerMap()1074 SafeMap<std::thread::id, std::shared_ptr<TorchListener>> CameraManager::GetTorchListenerMap()
1075 {
1076     return torchListenerMap_;
1077 }
1078 
GetFoldListenerMap()1079 SafeMap<std::thread::id, std::shared_ptr<FoldListener>> CameraManager::GetFoldListenerMap()
1080 {
1081     return foldListenerMap_;
1082 }
1083 
GetCameraDeviceFromId(std::string cameraId)1084 sptr<CameraDevice> CameraManager::GetCameraDeviceFromId(std::string cameraId)
1085 {
1086     auto cameraDeviceList = GetCameraDeviceList();
1087     for (auto& deviceInfo : cameraDeviceList) {
1088         if (deviceInfo->GetID() == cameraId) {
1089             return deviceInfo;
1090         }
1091     }
1092     return nullptr;
1093 }
1094 
GetInstance()1095 sptr<CameraManager>& CameraManager::GetInstance()
1096 {
1097     std::lock_guard<std::mutex> lock(g_instanceMutex);
1098     if (CameraManager::g_cameraManager == nullptr) {
1099         MEDIA_INFO_LOG("Initializing camera manager for first time!");
1100         CameraManager::g_cameraManager = new CameraManager();
1101         CameraManager::g_cameraManager->InitCameraManager();
1102     } else if (CameraManager::g_cameraManager->GetServiceProxy() == nullptr) {
1103         CameraManager::g_cameraManager->InitCameraManager();
1104     }
1105     return CameraManager::g_cameraManager;
1106 }
1107 
GetCameras()1108 std::vector<sptr<CameraInfo>> CameraManager::GetCameras()
1109 {
1110     CAMERA_SYNC_TRACE;
1111     return {};
1112 }
1113 
GetDmDeviceInfo()1114 std::vector<dmDeviceInfo> CameraManager::GetDmDeviceInfo()
1115 {
1116     auto serviceProxy = GetServiceProxy();
1117     CHECK_ERROR_RETURN_RET_LOG(
1118         serviceProxy == nullptr, {}, "CameraManager::GetDmDeviceInfo serviceProxy is null, returning empty list!");
1119 
1120     std::vector<std::string> deviceInfos;
1121     int32_t retCode = serviceProxy->GetDmDeviceInfo(deviceInfos);
1122     CHECK_ERROR_RETURN_RET_LOG(
1123         retCode != CAMERA_OK, {}, "CameraManager::GetDmDeviceInfo failed!, retCode: %{public}d", retCode);
1124 
1125     int size = static_cast<int>(deviceInfos.size());
1126     MEDIA_INFO_LOG("CameraManager::GetDmDeviceInfo size=%{public}d", size);
1127     if (size < 0) {
1128         return {};
1129     }
1130 
1131     std::vector<dmDeviceInfo> distributedCamInfo(size);
1132     for (int i = 0; i < size; i++) {
1133         std::string deviceInfoStr = deviceInfos[i];
1134         MEDIA_INFO_LOG("CameraManager::GetDmDeviceInfo deviceInfo: %{public}s", deviceInfoStr.c_str());
1135         if (!nlohmann::json::accept(deviceInfoStr)) {
1136             MEDIA_ERR_LOG("Failed to verify the deviceInfo format, deviceInfo is: %{public}s", deviceInfoStr.c_str());
1137         } else {
1138             nlohmann::json deviceInfoJson = nlohmann::json::parse(deviceInfoStr);
1139             if ((deviceInfoJson.contains("deviceName") && deviceInfoJson.contains("deviceTypeId") &&
1140                     deviceInfoJson.contains("networkId")) &&
1141                 (deviceInfoJson["deviceName"].is_string() && deviceInfoJson["networkId"].is_string())) {
1142                 distributedCamInfo[i].deviceName = deviceInfoJson["deviceName"];
1143                 distributedCamInfo[i].deviceTypeId = deviceInfoJson["deviceTypeId"];
1144                 distributedCamInfo[i].networkId = deviceInfoJson["networkId"];
1145             }
1146         }
1147     }
1148     return distributedCamInfo;
1149 }
1150 
GetCameraOutputStatus(int32_t pid,int32_t & status)1151 void CameraManager::GetCameraOutputStatus(int32_t pid, int32_t &status)
1152 {
1153     auto serviceProxy = GetServiceProxy();
1154     CHECK_ERROR_RETURN_LOG(
1155         serviceProxy == nullptr, "CameraManager::GetCameraOutputStatus serviceProxy is null");
1156 
1157     int32_t retCode = serviceProxy->GetCameraOutputStatus(pid, status);
1158     CHECK_ERROR_RETURN_LOG(
1159         retCode != CAMERA_OK, "CameraManager::GetCameraOutputStatus failed!, retCode: %{public}d", retCode);
1160 }
1161 
GetDmDeviceInfo(const std::string & cameraId,const std::vector<dmDeviceInfo> & dmDeviceInfoList)1162 dmDeviceInfo CameraManager::GetDmDeviceInfo(
1163     const std::string& cameraId, const std::vector<dmDeviceInfo>& dmDeviceInfoList)
1164 {
1165     dmDeviceInfo deviceInfo = { .deviceName = "", .deviceTypeId = 0, .networkId = "" };
1166     for (auto& info : dmDeviceInfoList) {
1167         if (cameraId.find(info.networkId) != std::string::npos) {
1168             deviceInfo = info;
1169             MEDIA_DEBUG_LOG("CameraManager::GetDmDeviceInfo %{public}s is remote camera", cameraId.c_str());
1170             break;
1171         }
1172     }
1173     return deviceInfo;
1174 }
1175 
GetCameraDeviceListFromServer()1176 std::vector<sptr<CameraDevice>> CameraManager::GetCameraDeviceListFromServer()
1177 {
1178     CAMERA_SYNC_TRACE;
1179     auto serviceProxy = GetServiceProxy();
1180     CHECK_ERROR_RETURN_RET_LOG(
1181         serviceProxy == nullptr, {}, "CameraManager::InitCameraList serviceProxy is null, returning empty list!");
1182     std::vector<std::string> cameraIds;
1183     std::vector<sptr<CameraDevice>> deviceInfoList = {};
1184     int32_t retCode = serviceProxy->GetCameraIds(cameraIds);
1185     if (retCode == CAMERA_OK) {
1186         auto dmDeviceInfoList = GetDmDeviceInfo();
1187         for (auto& cameraId : cameraIds) {
1188             MEDIA_DEBUG_LOG("InitCameraList cameraId= %{public}s", cameraId.c_str());
1189             std::shared_ptr<OHOS::Camera::CameraMetadata> cameraAbility;
1190             retCode = serviceProxy->GetCameraAbility(cameraId, cameraAbility);
1191             if (retCode != CAMERA_OK) {
1192                 continue;
1193             }
1194 
1195             auto dmDeviceInfo = GetDmDeviceInfo(cameraId, dmDeviceInfoList);
1196             sptr<CameraDevice> cameraObj = new (std::nothrow) CameraDevice(cameraId, cameraAbility, dmDeviceInfo);
1197             if (cameraObj == nullptr) {
1198                 MEDIA_ERR_LOG("failed to new CameraDevice!");
1199                 continue;
1200             }
1201             deviceInfoList.emplace_back(cameraObj);
1202         }
1203     } else {
1204         MEDIA_ERR_LOG("Get camera device failed!, retCode: %{public}d", retCode);
1205     }
1206     SetProfile(deviceInfoList);
1207     AlignVideoFpsProfile(deviceInfoList);
1208     return deviceInfoList;
1209 }
1210 
GetIsFoldable()1211 bool CameraManager::GetIsFoldable()
1212 {
1213     return !foldScreenType_.empty();
1214 }
1215 
GetFoldStatus()1216 FoldStatus CameraManager::GetFoldStatus()
1217 {
1218     return (FoldStatus)OHOS::Rosen::DisplayManager::GetInstance().GetFoldStatus();
1219 }
1220 
SetProfile(std::vector<sptr<CameraDevice>> & cameraObjList)1221 void CameraManager::SetProfile(std::vector<sptr<CameraDevice>>& cameraObjList)
1222 {
1223     for (auto& cameraObj : cameraObjList) {
1224         if (cameraObj == nullptr) {
1225             continue;
1226         }
1227         std::vector<SceneMode> supportedModes = GetSupportedModes(cameraObj);
1228         if (supportedModes.empty()) {
1229             auto capability = GetSupportedOutputCapability(cameraObj);
1230             cameraObj->SetProfile(capability);
1231         } else {
1232             supportedModes.emplace_back(NORMAL);
1233             for (const auto &modeName : supportedModes) {
1234                 auto capability = GetSupportedOutputCapability(cameraObj, modeName);
1235                 cameraObj->SetProfile(capability, modeName);
1236             }
1237         }
1238     }
1239 }
1240 
GetSupportedCameras()1241 std::vector<sptr<CameraDevice>> CameraManager::GetSupportedCameras()
1242 {
1243     CAMERA_SYNC_TRACE;
1244     auto cameraDeviceList = GetCameraDeviceList();
1245     bool isFoldable = GetIsFoldable();
1246     CHECK_ERROR_RETURN_RET(!isFoldable, cameraDeviceList);
1247     auto curFoldStatus = GetFoldStatus();
1248     if (curFoldStatus == FoldStatus::HALF_FOLD) {
1249         curFoldStatus = FoldStatus::EXPAND;
1250     }
1251     MEDIA_INFO_LOG("fold status: %{public}d", curFoldStatus);
1252     std::vector<sptr<CameraDevice>> supportedCameraDeviceList;
1253     for (auto& deviceInfo : cameraDeviceList) {
1254         // Compatible with adaptive applications
1255         if (deviceInfo->GetPosition() == CAMERA_POSITION_BACK &&
1256             (foldScreenType_[0] != '2' && foldScreenType_[0] != '4')) {
1257             supportedCameraDeviceList.emplace_back(deviceInfo);
1258             continue;
1259         }
1260         if ((deviceInfo->GetPosition() == CAMERA_POSITION_FOLD_INNER ||
1261             deviceInfo->GetPosition() == CAMERA_POSITION_FRONT) &&
1262             (foldScreenType_[0] != '2' && foldScreenType_[0] != '4')) {
1263             supportedCameraDeviceList.emplace_back(deviceInfo);
1264             continue;
1265         }
1266 
1267         auto supportedFoldStatus = deviceInfo->GetSupportedFoldStatus();
1268         auto it = g_metaToFwCameraFoldStatus_.find(static_cast<CameraFoldStatus>(supportedFoldStatus));
1269         if (it == g_metaToFwCameraFoldStatus_.end()) {
1270             MEDIA_INFO_LOG("No supported fold status is found, fold status: %{public}d", curFoldStatus);
1271             supportedCameraDeviceList.emplace_back(deviceInfo);
1272             continue;
1273         }
1274         if (it->second == curFoldStatus) {
1275             supportedCameraDeviceList.emplace_back(deviceInfo);
1276         }
1277     }
1278     return supportedCameraDeviceList;
1279 }
1280 
GetSupportedModes(sptr<CameraDevice> & camera)1281 std::vector<SceneMode> CameraManager::GetSupportedModes(sptr<CameraDevice>& camera)
1282 {
1283     std::vector<SceneMode> supportedModes = {};
1284 
1285     std::shared_ptr<Camera::CameraMetadata> metadata = camera->GetMetadata();
1286     CHECK_ERROR_RETURN_RET(metadata == nullptr, supportedModes);
1287     camera_metadata_item_t item;
1288     int32_t retCode = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_CAMERA_MODES, &item);
1289     CHECK_ERROR_RETURN_RET_LOG(retCode != CAM_META_SUCCESS || item.count == 0, supportedModes,
1290         "CameraManager::GetSupportedModes Failed with return code %{public}d", retCode);
1291     for (uint32_t i = 0; i < item.count; i++) {
1292         SceneMode scMode = SceneMode::NORMAL;
1293         if (ConvertMetaToFwkMode(static_cast<OperationMode>(item.data.u8[i]), scMode)) {
1294             supportedModes.emplace_back(scMode);
1295         }
1296     }
1297     MEDIA_INFO_LOG("CameraManager::GetSupportedModes supportedModes size: %{public}zu", supportedModes.size());
1298     return supportedModes;
1299 }
1300 
AlignVideoFpsProfile(std::vector<sptr<CameraDevice>> & cameraObjList)1301 void CameraManager::AlignVideoFpsProfile(std::vector<sptr<CameraDevice>>& cameraObjList)
1302 {
1303     MEDIA_ERR_LOG("CameraManager::AlignVideoFpsProfile enter");
1304     uint32_t normalMode = 0;
1305     int32_t alignFps = 60;
1306     std::vector<VideoProfile> frontVideoProfiles = {};
1307     std::vector<VideoProfile> backVideoProfiles = {};
1308     sptr<CameraDevice> frontCamera = nullptr;
1309     for (auto& camera : cameraObjList) {
1310         if (camera->GetPosition() == CAMERA_POSITION_FRONT) {
1311             frontVideoProfiles = camera->modeVideoProfiles_[normalMode];
1312             frontCamera = camera;
1313         } else if (camera->GetPosition() == CAMERA_POSITION_BACK) {
1314             backVideoProfiles = camera->modeVideoProfiles_[normalMode];
1315         }
1316     }
1317     const uint32_t minIndex = 0;
1318     const uint32_t maxIndex = 1;
1319     if (!(frontVideoProfiles.size() && backVideoProfiles.size())) {
1320         MEDIA_ERR_LOG("CameraManager::AlignVideoFpsProfile failed! frontVideoSize = %{public}zu, "
1321                       "frontVideoSize = %{public}zu", frontVideoProfiles.size(), backVideoProfiles.size());
1322         return;
1323     }
1324     std::vector<VideoProfile> alignFrontVideoProfiles = frontVideoProfiles;
1325     for (auto &backProfile : backVideoProfiles) {
1326         for (auto &frontProfile : frontVideoProfiles) {
1327             if (backProfile.GetSize().width == frontProfile.GetSize().width &&
1328                 backProfile.GetSize().height == frontProfile.GetSize().height) {
1329                 if (backProfile.framerates_[minIndex] == alignFps && backProfile.framerates_[maxIndex] == alignFps) {
1330                     alignFrontVideoProfiles.push_back(backProfile);
1331                     MEDIA_INFO_LOG("CameraManager::AlignVideoFpsProfile backProfile w(%{public}d),h(%{public}d), "
1332                                    "frontProfile w(%{public}d),h(%{public}d)",
1333                                    backProfile.GetSize().width, backProfile.GetSize().height,
1334                                    frontProfile.GetSize().width, frontProfile.GetSize().height);
1335                 }
1336             }
1337         }
1338     }
1339     if (frontCamera) {
1340         frontCamera->modeVideoProfiles_[normalMode] = alignFrontVideoProfiles;
1341         for (auto &frontProfile : alignFrontVideoProfiles) {
1342             MEDIA_INFO_LOG("CameraManager::AlignVideoFpsProfile frontProfile "
1343                            "w(%{public}d),h(%{public}d) fps min(%{public}d),min(%{public}d)",
1344                            frontProfile.GetSize().width, frontProfile.GetSize().height,
1345                            frontProfile.framerates_[minIndex], frontProfile.framerates_[maxIndex]);
1346         }
1347     }
1348 }
1349 
GetFallbackConfigMode(SceneMode profileMode,ProfilesWrapper & profilesWrapper)1350 SceneMode CameraManager::GetFallbackConfigMode(SceneMode profileMode, ProfilesWrapper& profilesWrapper)
1351 {
1352     MEDIA_INFO_LOG("CameraManager::GetFallbackConfigMode profileMode:%{public}d", profileMode);
1353     if (profilesWrapper.photoProfiles.empty() && profilesWrapper.previewProfiles.empty() &&
1354         profilesWrapper.vidProfiles.empty()) {
1355         switch (profileMode) {
1356             case CAPTURE_MACRO:
1357                 return CAPTURE;
1358             case VIDEO_MACRO:
1359                 return VIDEO;
1360             default:
1361                 return profileMode;
1362         }
1363     }
1364     return profileMode;
1365 }
1366 
CreateCameraInput(sptr<CameraInfo> & camera)1367 sptr<CameraInput> CameraManager::CreateCameraInput(sptr<CameraInfo> &camera)
1368 {
1369     CAMERA_SYNC_TRACE;
1370     sptr<CameraInput> cameraInput = nullptr;
1371     return cameraInput;
1372 }
1373 
CreateCameraInput(sptr<CameraDevice> & camera)1374 sptr<CameraInput> CameraManager::CreateCameraInput(sptr<CameraDevice> &camera)
1375 {
1376     CAMERA_SYNC_TRACE;
1377     sptr<CameraInput> cameraInput = nullptr;
1378     int32_t retCode = CreateCameraInput(camera, &cameraInput);
1379     CHECK_ERROR_RETURN_RET_LOG(retCode != CameraErrorCode::SUCCESS, nullptr,
1380         "CameraManager::CreateCameraInput Failed to create camera input with error code:%{public}d", retCode);
1381 
1382     return cameraInput;
1383 }
1384 
CreateCameraInput(sptr<CameraDevice> & camera,sptr<CameraInput> * pCameraInput)1385 int CameraManager::CreateCameraInput(sptr<CameraDevice> &camera, sptr<CameraInput> *pCameraInput)
1386 {
1387     CAMERA_SYNC_TRACE;
1388     CHECK_ERROR_RETURN_RET_LOG(camera == nullptr, CameraErrorCode::INVALID_ARGUMENT,
1389         "CameraManager::CreateCameraInput Camera object is null");
1390         // Compatible with adaptive applications
1391     FoldStatus curFoldStatus = GetFoldStatus();
1392     MEDIA_INFO_LOG("CreateCameraInput curFoldStatus:%{public}d, position:%{public}d", curFoldStatus,
1393         camera->GetPosition());
1394     if ((curFoldStatus == FoldStatus::EXPAND || curFoldStatus == FoldStatus::HALF_FOLD) &&
1395         camera->GetPosition() == CameraPosition::CAMERA_POSITION_FRONT && foldScreenType_[0] != '4') {
1396         std::vector<sptr<CameraDevice>> cameraObjList = GetSupportedCameras();
1397         sptr<CameraDevice> cameraInfo;
1398         for (size_t i = 0; i < cameraObjList.size(); i++) {
1399             sptr<CameraDevice> cameraDevice = cameraObjList[i];
1400             if (cameraDevice == nullptr) {
1401                 continue;
1402             }
1403             if (cameraDevice->GetPosition() == CameraPosition::CAMERA_POSITION_FOLD_INNER) {
1404                 camera = cameraDevice;
1405                 break;
1406             }
1407         }
1408     }
1409 
1410     sptr<ICameraDeviceService> deviceObj = nullptr;
1411     int32_t retCode = CreateCameraDevice(camera->GetID(), &deviceObj);
1412     CHECK_ERROR_RETURN_RET_LOG(retCode != CameraErrorCode::SUCCESS, retCode,
1413         "CameraManager::CreateCameraInput Returning null in CreateCameraInput");
1414     sptr<CameraInput> cameraInput = new(std::nothrow) CameraInput(deviceObj, camera);
1415     CHECK_ERROR_RETURN_RET_LOG(cameraInput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
1416         "CameraManager::CreateCameraInput failed to new cameraInput!");
1417     *pCameraInput = cameraInput;
1418     return CameraErrorCode::SUCCESS;
1419 }
1420 
CreateCameraInput(CameraPosition position,CameraType cameraType)1421 sptr<CameraInput> CameraManager::CreateCameraInput(CameraPosition position, CameraType cameraType)
1422 {
1423     CAMERA_SYNC_TRACE;
1424     sptr<CameraInput> cameraInput = nullptr;
1425     int32_t retCode = CreateCameraInput(position, cameraType, &cameraInput);
1426     CHECK_ERROR_RETURN_RET_LOG(retCode != CameraErrorCode::SUCCESS, nullptr,
1427         "CameraManager::CreateCameraInput Failed to CreateCameraInput with error code:%{public}d", retCode);
1428     return cameraInput;
1429 }
1430 
CreateCameraInput(CameraPosition position,CameraType cameraType,sptr<CameraInput> * pCameraInput)1431 int CameraManager::CreateCameraInput(CameraPosition position, CameraType cameraType, sptr<CameraInput> *pCameraInput)
1432 {
1433     CAMERA_SYNC_TRACE;
1434     sptr<CameraInput> cameraInput = nullptr;
1435     std::vector<sptr<CameraDevice>> cameraDeviceList = GetSupportedCameras();
1436     for (size_t i = 0; i < cameraDeviceList.size(); i++) {
1437         MEDIA_DEBUG_LOG("CreateCameraInput position:%{public}d, Camera Type:%{public}d",
1438             cameraDeviceList[i]->GetPosition(), cameraDeviceList[i]->GetCameraType());
1439         if ((cameraDeviceList[i]->GetPosition() == position) && (cameraDeviceList[i]->GetCameraType() == cameraType)) {
1440             cameraInput = CreateCameraInput(cameraDeviceList[i]);
1441             break;
1442         }
1443     }
1444     CHECK_ERROR_RETURN_RET_LOG(!cameraInput, CameraErrorCode::SERVICE_FATL_ERROR,
1445         "No Camera Device for Camera position:%{public}d, Camera Type:%{public}d", position, cameraType);
1446     *pCameraInput = cameraInput;
1447     return CameraErrorCode::SUCCESS;
1448 }
1449 
g_isCapabilitySupported(std::shared_ptr<OHOS::Camera::CameraMetadata> metadata,camera_metadata_item_t & item,uint32_t metadataTag)1450 bool g_isCapabilitySupported(std::shared_ptr<OHOS::Camera::CameraMetadata> metadata,
1451     camera_metadata_item_t &item, uint32_t metadataTag)
1452 {
1453     CHECK_ERROR_RETURN_RET(metadata == nullptr, false);
1454     bool isSupport = true;
1455     int32_t retCode = Camera::FindCameraMetadataItem(metadata->get(), metadataTag, &item);
1456     if (retCode != CAM_META_SUCCESS || item.count == 0) {
1457         MEDIA_ERR_LOG("Failed get metadata info tag = %{public}d, retCode = %{public}d, count = %{public}d",
1458             metadataTag, retCode, item.count);
1459         isSupport = false;
1460     }
1461     return isSupport;
1462 }
1463 
ParseBasicCapability(ProfilesWrapper & profilesWrapper,std::shared_ptr<OHOS::Camera::CameraMetadata> metadata,const camera_metadata_item_t & item)1464 void CameraManager::ParseBasicCapability(ProfilesWrapper& profilesWrapper,
1465     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata, const camera_metadata_item_t& item)
1466 {
1467     CHECK_ERROR_RETURN(metadata == nullptr);
1468     uint32_t widthOffset = 1;
1469     uint32_t heightOffset = 2;
1470     const uint8_t UNIT_STEP = 3;
1471     const uint8_t FPS_STEP = 2;
1472 
1473     CameraFormat format = CAMERA_FORMAT_INVALID;
1474     Size size;
1475     for (uint32_t i = 0; i < item.count; i += UNIT_STEP) {
1476         auto itr = metaToFwCameraFormat_.find(static_cast<camera_format_t>(item.data.i32[i]));
1477         if (itr != metaToFwCameraFormat_.end()) {
1478             format = itr->second;
1479         } else {
1480             format = CAMERA_FORMAT_INVALID;
1481             MEDIA_ERR_LOG("format %{public}d is not supported now", item.data.i32[i]);
1482             continue;
1483         }
1484         size.width = static_cast<uint32_t>(item.data.i32[i + widthOffset]);
1485         size.height = static_cast<uint32_t>(item.data.i32[i + heightOffset]);
1486         Profile profile = Profile(format, size);
1487         if (format == CAMERA_FORMAT_JPEG) {
1488             profilesWrapper.photoProfiles.push_back(profile);
1489         } else {
1490             profilesWrapper.previewProfiles.push_back(profile);
1491             camera_metadata_item_t fpsItem;
1492             int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_FPS_RANGES, &fpsItem);
1493             if (ret != CAM_META_SUCCESS) {
1494                 continue;
1495             }
1496             for (uint32_t j = 0; j < (fpsItem.count - 1); j += FPS_STEP) {
1497                 std::vector<int32_t> fps = { fpsItem.data.i32[j], fpsItem.data.i32[j + 1] };
1498                 VideoProfile vidProfile = VideoProfile(format, size, fps);
1499                 profilesWrapper.vidProfiles.push_back(vidProfile);
1500             }
1501         }
1502     }
1503 }
1504 
ParseExtendCapability(ProfilesWrapper & profilesWrapper,const int32_t modeName,const camera_metadata_item_t & item)1505 void CameraManager::ParseExtendCapability(ProfilesWrapper& profilesWrapper, const int32_t modeName,
1506     const camera_metadata_item_t& item) __attribute__((no_sanitize("cfi")))
1507 {
1508     ExtendInfo extendInfo = {};
1509     std::shared_ptr<CameraStreamInfoParse> modeStreamParse = std::make_shared<CameraStreamInfoParse>();
1510     modeStreamParse->getModeInfo(item.data.i32, item.count, extendInfo); // 解析tag中带的数据信息意义
1511     if (modeName == SceneMode::VIDEO) {
1512         for (uint32_t i = 0; i < extendInfo.modeCount; i++) {
1513             SceneMode scMode = SceneMode::NORMAL;
1514             if (!ConvertMetaToFwkMode(static_cast<OperationMode>(extendInfo.modeInfo[i].modeName), scMode)) {
1515                 MEDIA_ERR_LOG("ParseExtendCapability mode = %{public}d", extendInfo.modeInfo[i].modeName);
1516             }
1517             if (SceneMode::HIGH_FRAME_RATE != scMode) {
1518                 continue;
1519             }
1520             for (uint32_t j = 0; j < extendInfo.modeInfo[i].streamTypeCount; j++) {
1521                 OutputCapStreamType streamType =
1522                     static_cast<OutputCapStreamType>(extendInfo.modeInfo[i].streamInfo[j].streamType);
1523                 CreateProfile4StreamType(profilesWrapper, streamType, i, j, extendInfo);
1524             }
1525         }
1526     }
1527     for (uint32_t i = 0; i < extendInfo.modeCount; i++) {
1528         SceneMode scMode = SceneMode::NORMAL;
1529         if (!ConvertMetaToFwkMode(static_cast<OperationMode>(extendInfo.modeInfo[i].modeName), scMode)) {
1530             MEDIA_ERR_LOG("ParseExtendCapability mode = %{public}d", extendInfo.modeInfo[i].modeName);
1531         }
1532         if (modeName == scMode) {
1533             for (uint32_t j = 0; j < extendInfo.modeInfo[i].streamTypeCount; j++) {
1534                 OutputCapStreamType streamType =
1535                     static_cast<OutputCapStreamType>(extendInfo.modeInfo[i].streamInfo[j].streamType);
1536                 CreateProfile4StreamType(profilesWrapper, streamType, i, j, extendInfo);
1537             }
1538             break;
1539         }
1540     }
1541 }
1542 
ParseDepthCapability(const int32_t modeName,const camera_metadata_item_t & item)1543 void CameraManager::ParseDepthCapability(const int32_t modeName, const camera_metadata_item_t& item)
1544     __attribute__((no_sanitize("cfi")))
1545 {
1546     ExtendInfo extendInfo = {};
1547     std::shared_ptr<CameraDepthInfoParse> depthStreamParse = std::make_shared<CameraDepthInfoParse>();
1548     depthStreamParse->getModeInfo(item.data.i32, item.count, extendInfo); // 解析tag中带的数据信息意义
1549     for (uint32_t i = 0; i < extendInfo.modeCount; i++) {
1550         if (modeName == extendInfo.modeInfo[i].modeName) {
1551             for (uint32_t j = 0; j < extendInfo.modeInfo[i].streamTypeCount; j++) {
1552                 OutputCapStreamType streamType =
1553                     static_cast<OutputCapStreamType>(extendInfo.modeInfo[i].streamInfo[j].streamType);
1554                 CreateDepthProfile4StreamType(streamType, i, j, extendInfo);
1555             }
1556             break;
1557         }
1558     }
1559 }
1560 
CreateDepthProfile4StreamType(OutputCapStreamType streamType,uint32_t modeIndex,uint32_t streamIndex,ExtendInfo extendInfo)1561 void CameraManager::CreateDepthProfile4StreamType(OutputCapStreamType streamType, uint32_t modeIndex,
1562     uint32_t streamIndex, ExtendInfo extendInfo) __attribute__((no_sanitize("cfi")))
1563 {
1564     for (uint32_t k = 0; k < extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfoCount; k++) {
1565         const auto& detailInfo = extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfo[k];
1566         CameraFormat format = CAMERA_FORMAT_INVALID;
1567         auto itr = metaToFwCameraFormat_.find(static_cast<camera_format_t>(detailInfo.format));
1568         if (itr != metaToFwCameraFormat_.end()) {
1569             format = itr->second;
1570         } else {
1571             MEDIA_ERR_LOG("CreateDepthProfile4StreamType failed format = %{public}d",
1572                 extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfo[k].format);
1573             format = CAMERA_FORMAT_INVALID;
1574             continue;
1575         }
1576         Size size{static_cast<uint32_t>(detailInfo.width), static_cast<uint32_t>(detailInfo.height)};
1577         DepthDataAccuracy dataAccuracy = DEPTH_DATA_ACCURACY_INVALID;
1578         auto it = metaToFwDepthDataAccuracy_.find(static_cast<DepthDataAccuracyType>(detailInfo.dataAccuracy));
1579         if (it != metaToFwDepthDataAccuracy_.end()) {
1580             dataAccuracy = it->second;
1581         } else {
1582             MEDIA_ERR_LOG("CreateDepthProfile4StreamType failed dataAccuracy = %{public}d",
1583                 extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfo[k].dataAccuracy);
1584             dataAccuracy = DEPTH_DATA_ACCURACY_INVALID;
1585             continue;
1586         }
1587         MEDIA_DEBUG_LOG("streamType: %{public}d, OutputCapStreamType::DEPTH: %{public}d", streamType,
1588             OutputCapStreamType::DEPTH);
1589         DepthProfile depthProfile = DepthProfile(format, dataAccuracy, size);
1590         MEDIA_DEBUG_LOG("depthdata format : %{public}d, data accuracy: %{public}d, width: %{public}d,"
1591             "height: %{public}d", depthProfile.GetCameraFormat(), depthProfile.GetDataAccuracy(),
1592             depthProfile.GetSize().width, depthProfile.GetSize().height);
1593         depthProfiles_.push_back(depthProfile);
1594     }
1595 }
1596 
ParseProfileLevel(ProfilesWrapper & profilesWrapper,const int32_t modeName,const camera_metadata_item_t & item)1597 void CameraManager::ParseProfileLevel(ProfilesWrapper& profilesWrapper, const int32_t modeName,
1598     const camera_metadata_item_t& item) __attribute__((no_sanitize("cfi")))
1599 {
1600     std::vector<SpecInfo> specInfos;
1601     ProfileLevelInfo modeInfo = {};
1602     if (IsSystemApp() && modeName == SceneMode::VIDEO) {
1603         CameraAbilityParseUtil::GetModeInfo(SceneMode::HIGH_FRAME_RATE, item, modeInfo);
1604         specInfos.insert(specInfos.end(), modeInfo.specInfos.begin(), modeInfo.specInfos.end());
1605     }
1606     CameraAbilityParseUtil::GetModeInfo(modeName, item, modeInfo);
1607     specInfos.insert(specInfos.end(), modeInfo.specInfos.begin(), modeInfo.specInfos.end());
1608     for (SpecInfo& specInfo : specInfos) {
1609         MEDIA_INFO_LOG("modeName: %{public}d specId: %{public}d", modeName, specInfo.specId);
1610         for (StreamInfo& streamInfo : specInfo.streamInfos) {
1611             CreateProfileLevel4StreamType(profilesWrapper, specInfo.specId, streamInfo);
1612         }
1613     }
1614 }
1615 
CreateProfileLevel4StreamType(ProfilesWrapper & profilesWrapper,int32_t specId,StreamInfo & streamInfo)1616 void CameraManager::CreateProfileLevel4StreamType(
1617     ProfilesWrapper& profilesWrapper, int32_t specId, StreamInfo& streamInfo) __attribute__((no_sanitize("cfi")))
1618 {
1619     auto getCameraFormat = [&](camera_format_t format) -> CameraFormat {
1620         auto itr = metaToFwCameraFormat_.find(format);
1621         if (itr != metaToFwCameraFormat_.end()) {
1622             return itr->second;
1623         } else {
1624             MEDIA_ERR_LOG("CreateProfile4StreamType failed format = %{public}d", format);
1625             return CAMERA_FORMAT_INVALID;
1626         }
1627     };
1628 
1629     OutputCapStreamType streamType = static_cast<OutputCapStreamType>(streamInfo.streamType);
1630 
1631     for (const auto &detailInfo : streamInfo.detailInfos) {
1632         CameraFormat format = getCameraFormat(static_cast<camera_format_t>(detailInfo.format));
1633         if (format == CAMERA_FORMAT_INVALID) {
1634             continue;
1635         }
1636         Size size{detailInfo.width, detailInfo.height};
1637         Fps fps{detailInfo.fixedFps, detailInfo.minFps, detailInfo.maxFps};
1638         std::vector<uint32_t> abilityId = detailInfo.abilityIds;
1639         std::string abilityIds = Container2String(abilityId.begin(), abilityId.end());
1640         if (streamType == OutputCapStreamType::PREVIEW) {
1641             Profile previewProfile = Profile(format, size, fps, abilityId, specId);
1642             profilesWrapper.previewProfiles.push_back(previewProfile);
1643             previewProfile.DumpProfile("preview");
1644         } else if (streamType == OutputCapStreamType::STILL_CAPTURE) {
1645             Profile snapProfile = Profile(format, size, fps, abilityId, specId);
1646             profilesWrapper.photoProfiles.push_back(snapProfile);
1647             snapProfile.DumpProfile("photo");
1648         } else if (streamType == OutputCapStreamType::VIDEO_STREAM) {
1649             std::vector<int32_t> frameRates = {fps.minFps, fps.maxFps};
1650             VideoProfile vidProfile = VideoProfile(format, size, frameRates, specId);
1651             profilesWrapper.vidProfiles.push_back(vidProfile);
1652             vidProfile.DumpVideoProfile("video");
1653         }
1654     }
1655 }
1656 
ParseCapability(ProfilesWrapper & profilesWrapper,sptr<CameraDevice> & camera,const int32_t modeName,camera_metadata_item_t & item,std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)1657 void CameraManager::ParseCapability(ProfilesWrapper& profilesWrapper, sptr<CameraDevice>& camera,
1658     const int32_t modeName, camera_metadata_item_t& item, std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)
1659 {
1660     if (g_isCapabilitySupported(metadata, item, OHOS_ABILITY_AVAILABLE_PROFILE_LEVEL)) {
1661         std::vector<SceneMode> supportedModes = GetSupportedModes(camera);
1662         int32_t mode = (supportedModes.empty() && isTemplateMode_.count(modeName)) ? SceneMode::NORMAL : modeName;
1663         MEDIA_INFO_LOG("ParseProfileLevel by device = %{public}s, mode = %{public}d", camera->GetID().c_str(), mode);
1664         ParseProfileLevel(profilesWrapper, mode, item);
1665     } else if (g_isCapabilitySupported(metadata, item, OHOS_ABILITY_STREAM_AVAILABLE_EXTEND_CONFIGURATIONS)) {
1666         std::vector<SceneMode> supportedModes = GetSupportedModes(camera);
1667         int32_t mode = (supportedModes.empty() && isTemplateMode_.count(modeName)) ? SceneMode::NORMAL : modeName;
1668         MEDIA_INFO_LOG("ParseCapability by device = %{public}s, mode = %{public}d", camera->GetID().c_str(), mode);
1669         ParseExtendCapability(profilesWrapper, mode, item);
1670     } else if (g_isCapabilitySupported(metadata, item, OHOS_ABILITY_STREAM_AVAILABLE_BASIC_CONFIGURATIONS)) {
1671         ParseBasicCapability(profilesWrapper, metadata, item);
1672     } else {
1673         MEDIA_ERR_LOG("Failed get stream info");
1674     }
1675     // 解析深度流信息
1676     if (g_isCapabilitySupported(metadata, item, OHOS_ABILITY_DEPTH_DATA_PROFILES)) {
1677         std::vector<SceneMode> supportedModes = GetSupportedModes(camera);
1678         int32_t mode = (supportedModes.empty() && isTemplateMode_.count(modeName)) ? SceneMode::NORMAL : modeName;
1679         MEDIA_INFO_LOG("Depth g_isCapabilitySupported by device = %{public}s, mode = %{public}d, tag = %{public}d",
1680             camera->GetID().c_str(), mode, OHOS_ABILITY_DEPTH_DATA_PROFILES);
1681         ParseDepthCapability(mode, item);
1682     } else {
1683         MEDIA_INFO_LOG("Depth GetSupportedOutputCapability is not supported by device = %{public}s,"
1684             "tag = %{public}d", camera->GetID().c_str(), OHOS_ABILITY_DEPTH_DATA_PROFILES);
1685     }
1686 }
1687 
GetSupportedOutputCapability(sptr<CameraDevice> & camera,int32_t modeName)1688 sptr<CameraOutputCapability> CameraManager::GetSupportedOutputCapability(sptr<CameraDevice>& camera, int32_t modeName)
1689     __attribute__((no_sanitize("cfi")))
1690 {
1691     MEDIA_DEBUG_LOG("GetSupportedOutputCapability mode = %{public}d", modeName);
1692     CHECK_ERROR_RETURN_RET(camera == nullptr, nullptr);
1693     sptr<CameraOutputCapability> cameraOutputCapability = new (std::nothrow) CameraOutputCapability();
1694     CHECK_ERROR_RETURN_RET(cameraOutputCapability == nullptr, nullptr);
1695     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata = camera->GetMetadata();
1696     CHECK_ERROR_RETURN_RET(metadata == nullptr, nullptr);
1697     camera_metadata_item_t item;
1698     ProfilesWrapper profilesWrapper = {};
1699     depthProfiles_.clear();
1700     photoFormats_.clear();
1701     photoFormats_ = GetSupportPhotoFormat(modeName, metadata);
1702 
1703     ParseCapability(profilesWrapper, camera, modeName, item, metadata);
1704     SceneMode profileMode = static_cast<SceneMode>(modeName);
1705     auto fallbackMode = GetFallbackConfigMode(profileMode, profilesWrapper);
1706     if (profileMode != fallbackMode) {
1707         ParseCapability(profilesWrapper, camera, fallbackMode, item, metadata);
1708     }
1709     if (IsSystemApp()) {
1710         FillSupportPhotoFormats(profilesWrapper.photoProfiles);
1711     }
1712     cameraOutputCapability->SetPhotoProfiles(profilesWrapper.photoProfiles);
1713     MEDIA_INFO_LOG("SetPhotoProfiles size = %{public}zu", profilesWrapper.photoProfiles.size());
1714     cameraOutputCapability->SetPreviewProfiles(profilesWrapper.previewProfiles);
1715     MEDIA_INFO_LOG("SetPreviewProfiles size = %{public}zu", profilesWrapper.previewProfiles.size());
1716     if (!isPhotoMode_.count(modeName)) {
1717         cameraOutputCapability->SetVideoProfiles(profilesWrapper.vidProfiles);
1718     }
1719     MEDIA_INFO_LOG("SetVideoProfiles size = %{public}zu", profilesWrapper.vidProfiles.size());
1720     cameraOutputCapability->SetDepthProfiles(depthProfiles_);
1721     MEDIA_INFO_LOG("SetDepthProfiles size = %{public}zu", depthProfiles_.size());
1722 
1723     std::vector<MetadataObjectType> objectTypes = {};
1724     GetSupportedMetadataObjectType(metadata->get(), objectTypes);
1725     if (!CameraSecurity::CheckSystemApp()) {
1726         MEDIA_DEBUG_LOG("public calling for GetSupportedOutputCapability");
1727         if (std::any_of(objectTypes.begin(), objectTypes.end(),
1728                         [](MetadataObjectType type) { return type == MetadataObjectType::FACE; })) {
1729             cameraOutputCapability->SetSupportedMetadataObjectType({ MetadataObjectType::FACE });
1730         } else {
1731             cameraOutputCapability->SetSupportedMetadataObjectType({});
1732         }
1733     } else {
1734         cameraOutputCapability->SetSupportedMetadataObjectType(objectTypes);
1735     }
1736     MEDIA_INFO_LOG("SetMetadataTypes size = %{public}zu",
1737                    cameraOutputCapability->GetSupportedMetadataObjectType().size());
1738     return cameraOutputCapability;
1739 }
1740 
GetSupportedMetadataObjectType(common_metadata_header_t * metadata,std::vector<MetadataObjectType> & objectTypes)1741 void CameraManager::GetSupportedMetadataObjectType(common_metadata_header_t* metadata,
1742                                                    std::vector<MetadataObjectType>& objectTypes)
1743 {
1744     camera_metadata_item_t metadataItem;
1745     int32_t ret = Camera::FindCameraMetadataItem(metadata, OHOS_ABILITY_STATISTICS_DETECT_TYPE, &metadataItem);
1746     if (ret == CAM_META_SUCCESS) {
1747         for (uint32_t index = 0; index < metadataItem.count; index++) {
1748             auto iterator =
1749                 g_metaToFwCameraMetaDetect_.find(static_cast<StatisticsDetectType>(metadataItem.data.u8[index]));
1750             CHECK_ERROR_PRINT_LOG(iterator == g_metaToFwCameraMetaDetect_.end(),
1751                 "Not supported metadataItem %{public}d", metadataItem.data.u8[index]);
1752             if (iterator != g_metaToFwCameraMetaDetect_.end()) {
1753                 objectTypes.push_back(iterator->second);
1754             }
1755         }
1756     }
1757 }
1758 
GetSupportPhotoFormat(const int32_t modeName,std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)1759 vector<CameraFormat> CameraManager::GetSupportPhotoFormat(const int32_t modeName,
1760     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)
1761 {
1762     if (metadata == nullptr) {
1763         return {};
1764     }
1765     vector<CameraFormat> photoFormats = {};
1766     camera_metadata_item_t item;
1767     int32_t metadataTag = OHOS_STREAM_AVAILABLE_FORMATS;
1768     int32_t retCode = OHOS::Camera::FindCameraMetadataItem(metadata->get(), metadataTag, &item);
1769     if (retCode != CAM_META_SUCCESS || item.count == 0) {
1770         MEDIA_ERR_LOG("Failed get metadata info tag = %{public}d, retCode = %{public}d, count = %{public}d",
1771             metadataTag, retCode, item.count);
1772         return photoFormats;
1773     }
1774     vector<int32_t> formats = {};
1775     std::map<int32_t, vector<int32_t> > modePhotoFormats = {};
1776     for (uint32_t i = 0; i < item.count; i++) {
1777         if (item.data.i32[i] != -1) {
1778             formats.push_back(item.data.i32[i]);
1779             continue;
1780         } else {
1781             modePhotoFormats.insert(std::make_pair(modeName, std::move(formats)));
1782             formats.clear();
1783         }
1784     }
1785     if (!modePhotoFormats.count(modeName)) {
1786         MEDIA_ERR_LOG("GetSupportPhotoFormat not support mode = %{public}d", modeName);
1787         return photoFormats;
1788     }
1789     for (auto &val : modePhotoFormats[modeName]) {
1790         camera_format_t hdiFomart = static_cast<camera_format_t>(val);
1791         if (metaToFwCameraFormat_.count(hdiFomart)) {
1792             photoFormats.push_back(metaToFwCameraFormat_.at(hdiFomart));
1793         }
1794     }
1795     MEDIA_DEBUG_LOG("GetSupportPhotoFormat, mode = %{public}d, formats = %{public}s", modeName,
1796         Container2String(photoFormats.begin(), photoFormats.end()).c_str());
1797     return photoFormats;
1798 }
1799 
IsSystemApp()1800 bool CameraManager::IsSystemApp()
1801 {
1802     return isSystemApp_;
1803 }
1804 
CreateProfile4StreamType(ProfilesWrapper & profilesWrapper,OutputCapStreamType streamType,uint32_t modeIndex,uint32_t streamIndex,ExtendInfo extendInfo)1805 void CameraManager::CreateProfile4StreamType(ProfilesWrapper& profilesWrapper, OutputCapStreamType streamType,
1806     uint32_t modeIndex, uint32_t streamIndex, ExtendInfo extendInfo) __attribute__((no_sanitize("cfi")))
1807 {
1808     const int frameRate120 = 120;
1809     const int frameRate240 = 240;
1810     for (uint32_t k = 0; k < extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfoCount; k++) {
1811         const auto& detailInfo = extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfo[k];
1812         // Skip profiles with unsupported frame rates for non-system apps
1813         if ((detailInfo.minFps == frameRate120 || detailInfo.minFps == frameRate240) &&
1814             streamType == OutputCapStreamType::VIDEO_STREAM && !IsSystemApp()) {
1815             continue;
1816         }
1817         CameraFormat format = CAMERA_FORMAT_INVALID;
1818         auto itr = metaToFwCameraFormat_.find(static_cast<camera_format_t>(detailInfo.format));
1819         if (itr != metaToFwCameraFormat_.end()) {
1820             format = itr->second;
1821         } else {
1822             MEDIA_ERR_LOG("CreateProfile4StreamType failed format = %{public}d",
1823                 extendInfo.modeInfo[modeIndex].streamInfo[streamIndex].detailInfo[k].format);
1824             format = CAMERA_FORMAT_INVALID;
1825             continue;
1826         }
1827         Size size { static_cast<uint32_t>(detailInfo.width), static_cast<uint32_t>(detailInfo.height) };
1828         Fps fps { static_cast<uint32_t>(detailInfo.fixedFps), static_cast<uint32_t>(detailInfo.minFps),
1829                 static_cast<uint32_t>(detailInfo.maxFps) };
1830         std::vector<uint32_t> abilityId = detailInfo.abilityId;
1831         std::string abilityIds = Container2String(abilityId.begin(), abilityId.end());
1832         if (streamType == OutputCapStreamType::PREVIEW) {
1833             Profile previewProfile = Profile(format, size, fps, abilityId);
1834             profilesWrapper.previewProfiles.push_back(previewProfile);
1835             previewProfile.DumpProfile("preview");
1836         } else if (streamType == OutputCapStreamType::STILL_CAPTURE) {
1837             Profile snapProfile = Profile(format, size, fps, abilityId);
1838             profilesWrapper.photoProfiles.push_back(snapProfile);
1839             snapProfile.DumpProfile("photo");
1840         } else if (streamType == OutputCapStreamType::VIDEO_STREAM) {
1841             std::vector<int32_t> frameRates = { fps.minFps, fps.maxFps };
1842             VideoProfile vidProfile = VideoProfile(format, size, frameRates);
1843             profilesWrapper.vidProfiles.push_back(vidProfile);
1844             vidProfile.DumpVideoProfile("video");
1845         }
1846     }
1847 }
1848 
CreateAndSetCameraServiceCallback()1849 void CameraManager::CreateAndSetCameraServiceCallback()
1850 {
1851     CHECK_ERROR_RETURN_LOG(cameraSvcCallback_ != nullptr,
1852         "CameraManager::CreateAndSetCameraServiceCallback cameraSvcCallback_ is not nullptr");
1853     auto serviceProxy = GetServiceProxy();
1854     CHECK_ERROR_RETURN_LOG(serviceProxy == nullptr,
1855         "CameraManager::CreateAndSetCameraServiceCallback serviceProxy is null");
1856     cameraSvcCallback_ = new(std::nothrow) CameraStatusServiceCallback(this);
1857     CHECK_ERROR_RETURN_LOG(cameraSvcCallback_ == nullptr,
1858         "CameraManager::CreateAndSetCameraServiceCallback failed to new cameraSvcCallback_!");
1859     int32_t retCode = serviceProxy->SetCameraCallback(cameraSvcCallback_);
1860     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK,
1861         "CreateAndSetCameraServiceCallback Set CameraStatus service Callback failed, retCode: %{public}d", retCode);
1862 }
1863 
SetCameraServiceCallback(sptr<ICameraServiceCallback> & callback)1864 void CameraManager::SetCameraServiceCallback(sptr<ICameraServiceCallback>& callback)
1865 {
1866     auto serviceProxy = GetServiceProxy();
1867     CHECK_ERROR_RETURN_LOG(serviceProxy == nullptr,
1868         "CameraManager::SetCameraServiceCallback serviceProxy is null");
1869     int32_t retCode = serviceProxy->SetCameraCallback(callback);
1870     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK,
1871         "SetCameraServiceCallback Set service Callback failed, retCode: %{public}d", retCode);
1872     return;
1873 }
1874 
GetCameraMetadataFormat(CameraFormat format)1875 camera_format_t CameraManager::GetCameraMetadataFormat(CameraFormat format)
1876 {
1877     camera_format_t metaFormat = OHOS_CAMERA_FORMAT_YCRCB_420_SP;
1878     MEDIA_DEBUG_LOG("format = %{public}d", static_cast<int32_t>(format));
1879 
1880     auto itr = fwToMetaCameraFormat_.find(format);
1881     if (itr != fwToMetaCameraFormat_.end()) {
1882         metaFormat = itr->second;
1883     }
1884     MEDIA_DEBUG_LOG("metaFormat = %{public}d", static_cast<int32_t>(metaFormat));
1885     return metaFormat;
1886 }
1887 
OnTorchStatusChange(const TorchStatus status)1888 int32_t TorchServiceCallback::OnTorchStatusChange(const TorchStatus status)
1889 {
1890     MEDIA_DEBUG_LOG("TorchStatus is %{public}d", status);
1891     auto cameraManager = cameraManager_.promote();
1892     CHECK_ERROR_RETURN_RET_LOG(cameraManager == nullptr, CAMERA_OK, "OnTorchStatusChange CameraManager is nullptr");
1893 
1894     TorchStatusInfo torchStatusInfo;
1895     if (status == TorchStatus::TORCH_STATUS_UNAVAILABLE) {
1896         torchStatusInfo.isTorchAvailable = false;
1897         torchStatusInfo.isTorchActive = false;
1898         torchStatusInfo.torchLevel = 0;
1899         cameraManager->UpdateTorchMode(TORCH_MODE_OFF);
1900     } else if (status == TorchStatus::TORCH_STATUS_ON) {
1901         torchStatusInfo.isTorchAvailable = true;
1902         torchStatusInfo.isTorchActive = true;
1903         torchStatusInfo.torchLevel = 1;
1904         cameraManager->UpdateTorchMode(TORCH_MODE_ON);
1905     } else if (status == TorchStatus::TORCH_STATUS_OFF) {
1906         torchStatusInfo.isTorchAvailable = true;
1907         torchStatusInfo.isTorchActive = false;
1908         torchStatusInfo.torchLevel = 0;
1909         cameraManager->UpdateTorchMode(TORCH_MODE_OFF);
1910     }
1911 
1912     auto listenerMap = cameraManager->GetTorchListenerMap();
1913     MEDIA_DEBUG_LOG("TorchListenerMap size %{public}d", listenerMap.Size());
1914     if (listenerMap.IsEmpty()) {
1915         return CAMERA_OK;
1916     }
1917 
1918     listenerMap.Iterate([&](std::thread::id threadId, std::shared_ptr<TorchListener> torchListener) {
1919         if (torchListener != nullptr) {
1920             torchListener->OnTorchStatusChange(torchStatusInfo);
1921         } else {
1922             std::ostringstream oss;
1923             oss << threadId;
1924             MEDIA_INFO_LOG(
1925                 "OnTorchStatusChange not registered!, Ignore the callback: thread:%{public}s", oss.str().c_str());
1926         }
1927     });
1928     return CAMERA_OK;
1929 }
1930 
OnFoldStatusChanged(const FoldStatus status)1931 int32_t FoldServiceCallback::OnFoldStatusChanged(const FoldStatus status)
1932 {
1933     MEDIA_DEBUG_LOG("FoldStatus is %{public}d", status);
1934     auto cameraManager = cameraManager_.promote();
1935     CHECK_ERROR_RETURN_RET_LOG(cameraManager == nullptr, CAMERA_OK, "OnFoldStatusChanged CameraManager is nullptr");
1936 
1937     FoldStatusInfo foldStatusInfo;
1938     foldStatusInfo.foldStatus = status;
1939     foldStatusInfo.supportedCameras = cameraManager->GetSupportedCameras();
1940     auto listenerMap = cameraManager->GetFoldListenerMap();
1941     MEDIA_DEBUG_LOG("FoldListenerMap size %{public}d", listenerMap.Size());
1942     CHECK_ERROR_RETURN_RET(listenerMap.IsEmpty(), CAMERA_OK);
1943     listenerMap.Iterate([&](std::thread::id threadId, std::shared_ptr<FoldListener> foldListener) {
1944         if (foldListener != nullptr) {
1945             foldListener->OnFoldStatusChanged(foldStatusInfo);
1946         } else {
1947             std::ostringstream oss;
1948             oss << threadId;
1949             MEDIA_INFO_LOG(
1950                 "OnFoldStatusChanged not registered!, Ignore the callback: thread:%{public}s", oss.str().c_str());
1951         }
1952     });
1953     return CAMERA_OK;
1954 }
1955 
SetTorchServiceCallback(sptr<ITorchServiceCallback> & callback)1956 void CameraManager::SetTorchServiceCallback(sptr<ITorchServiceCallback>& callback)
1957 {
1958     auto serviceProxy = GetServiceProxy();
1959     CHECK_ERROR_RETURN_LOG(serviceProxy == nullptr,
1960         "CameraManager::SetTorchServiceCallback serviceProxy is null");
1961     int32_t retCode = serviceProxy->SetTorchCallback(callback);
1962     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK,
1963         "SetTorchServiceCallback Set service Callback failed, retCode: %{public}d", retCode);
1964     return;
1965 }
1966 
CreateAndSetTorchServiceCallback()1967 void CameraManager::CreateAndSetTorchServiceCallback()
1968 {
1969     CHECK_ERROR_RETURN_LOG(torchSvcCallback_ != nullptr,
1970         "CameraManager::CreateAndSetTorchServiceCallback torchSvcCallback_ is not nullptr");
1971     auto serviceProxy = GetServiceProxy();
1972     CHECK_ERROR_RETURN_LOG(serviceProxy == nullptr,
1973         "CameraManager::CreateAndSetTorchServiceCallback serviceProxy is null");
1974     torchSvcCallback_ = new(std::nothrow) TorchServiceCallback(this);
1975     CHECK_ERROR_RETURN_LOG(torchSvcCallback_ == nullptr,
1976         "CameraManager::CreateAndSetTorchServiceCallback failed to new torchSvcCallback_!");
1977     int32_t retCode = serviceProxy->SetTorchCallback(torchSvcCallback_);
1978     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK,
1979         "CreateAndSetTorchServiceCallback Set service Callback failed, retCode: %{public}d", retCode);
1980 }
1981 
SetFoldServiceCallback(sptr<IFoldServiceCallback> & callback)1982 void CameraManager::SetFoldServiceCallback(sptr<IFoldServiceCallback>& callback)
1983 {
1984     auto serviceProxy = GetServiceProxy();
1985     CHECK_ERROR_RETURN_LOG(serviceProxy == nullptr,
1986         "CameraManager::SetFoldServiceCallback serviceProxy is null");
1987     int32_t retCode = serviceProxy->SetFoldStatusCallback(callback);
1988     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK,
1989         "SetFoldServiceCallback Set service Callback failed, retCode: %{public}d", retCode);
1990     return;
1991 }
1992 
CreateAndSetFoldServiceCallback()1993 void CameraManager::CreateAndSetFoldServiceCallback()
1994 {
1995     CHECK_ERROR_RETURN_LOG(foldSvcCallback_ != nullptr,
1996         "CameraManager::CreateAndSetFoldServiceCallback foldSvcCallback_ is not nullptr");
1997     auto serviceProxy = GetServiceProxy();
1998     CHECK_ERROR_RETURN_LOG(serviceProxy == nullptr,
1999         "CameraManager::CreateAndSetFoldServiceCallback serviceProxy is null");
2000     foldSvcCallback_ = new(std::nothrow) FoldServiceCallback(this);
2001     CHECK_ERROR_RETURN_LOG(foldSvcCallback_ == nullptr,
2002         "CameraManager::CreateAndSetFoldServiceCallback failed to new foldSvcCallback_!");
2003     int32_t retCode = serviceProxy->SetFoldStatusCallback(foldSvcCallback_);
2004     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK,
2005         "CreateAndSetFoldServiceCallback Set service Callback failed, retCode: %{public}d", retCode);
2006 }
2007 
OnCameraMute(bool muteMode)2008 int32_t CameraMuteServiceCallback::OnCameraMute(bool muteMode)
2009 {
2010     MEDIA_DEBUG_LOG("muteMode is %{public}d", muteMode);
2011     auto cameraManager = cameraManager_.promote();
2012     CHECK_ERROR_RETURN_RET_LOG(cameraManager == nullptr, CAMERA_OK, "OnCameraMute CameraManager is nullptr");
2013     auto listenerMap = cameraManager->GetCameraMuteListenerMap();
2014     MEDIA_DEBUG_LOG("CameraMuteListenerMap size %{public}d", listenerMap.Size());
2015     if (listenerMap.IsEmpty()) {
2016         return CAMERA_OK;
2017     }
2018     listenerMap.Iterate([&](std::thread::id threadId, std::shared_ptr<CameraMuteListener> cameraMuteListener) {
2019         if (cameraMuteListener != nullptr) {
2020             cameraMuteListener->OnCameraMute(muteMode);
2021         } else {
2022             std::ostringstream oss;
2023             oss << threadId;
2024             MEDIA_INFO_LOG("OnCameraMute not registered!, Ignore the callback: thread:%{public}s", oss.str().c_str());
2025         }
2026     });
2027     return CAMERA_OK;
2028 }
2029 
CreateAndSetCameraMuteServiceCallback()2030 void CameraManager::CreateAndSetCameraMuteServiceCallback()
2031 {
2032     CHECK_ERROR_RETURN_LOG(cameraMuteSvcCallback_ != nullptr,
2033         "CameraManager::CreateAndSetCameraMuteServiceCallback cameraMuteSvcCallback_ is not nullptr");
2034     auto serviceProxy = GetServiceProxy();
2035     CHECK_ERROR_RETURN_LOG(serviceProxy == nullptr,
2036         "CameraManager::CreateAndSetCameraMuteServiceCallback serviceProxy is null");
2037     cameraMuteSvcCallback_ = new(std::nothrow) CameraMuteServiceCallback(this);
2038     CHECK_ERROR_RETURN_LOG(cameraMuteSvcCallback_ == nullptr,
2039         "CameraManager::CreateAndSetCameraMuteServiceCallback failed to new cameraMuteSvcCallback_!");
2040     int32_t retCode = serviceProxy->SetMuteCallback(cameraMuteSvcCallback_);
2041     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK,
2042         "CreateAndSetCameraMuteServiceCallback Set Mute service Callback failed, retCode: %{public}d", retCode);
2043 }
2044 
SetCameraMuteServiceCallback(sptr<ICameraMuteServiceCallback> & callback)2045 void CameraManager::SetCameraMuteServiceCallback(sptr<ICameraMuteServiceCallback>& callback)
2046 {
2047     auto serviceProxy = GetServiceProxy();
2048     CHECK_ERROR_RETURN_LOG(serviceProxy == nullptr,
2049         "CameraManager::SetCameraMuteServiceCallback serviceProxy is null");
2050     int32_t retCode = serviceProxy->SetMuteCallback(callback);
2051     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK,
2052         "SetCameraMuteServiceCallback Set Mute service Callback failed, retCode: %{public}d", retCode);
2053     return;
2054 }
2055 
IsCameraMuteSupported()2056 bool CameraManager::IsCameraMuteSupported()
2057 {
2058     bool isCameraMuteSupported = false;
2059     bool cacheResult = GetCameraDeviceAbilitySupportValue(CAMERA_ABILITY_SUPPORT_MUTE, isCameraMuteSupported);
2060     if (cacheResult) {
2061         return isCameraMuteSupported;
2062     }
2063 
2064     std::vector<sptr<CameraDevice>> cameraDeviceList;
2065     if (IsCameraDeviceListCached()) {
2066         cameraDeviceList = GetCameraDeviceList();
2067     } else {
2068         cameraDeviceList = GetCameraDeviceListFromServer();
2069     }
2070 
2071     for (auto& cameraDeviceInfo : cameraDeviceList) {
2072         std::shared_ptr<OHOS::Camera::CameraMetadata> metadata = cameraDeviceInfo->GetMetadata();
2073         CHECK_ERROR_RETURN_RET(metadata == nullptr, false);
2074         camera_metadata_item_t item;
2075         int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_MUTE_MODES, &item);
2076         CHECK_ERROR_RETURN_RET_LOG(ret != 0, isCameraMuteSupported,
2077             "Failed to get stream configuration or Invalid stream configuation "
2078             "OHOS_ABILITY_MUTE_MODES ret = %{public}d",
2079             ret);
2080         for (uint32_t i = 0; i < item.count; i++) {
2081             MEDIA_INFO_LOG("OHOS_ABILITY_MUTE_MODES %{public}d th is %{public}d", i, item.data.u8[i]);
2082             if (item.data.u8[i] == OHOS_CAMERA_MUTE_MODE_SOLID_COLOR_BLACK) {
2083                 isCameraMuteSupported = true;
2084                 break;
2085             }
2086         }
2087         if (isCameraMuteSupported) {
2088             break;
2089         }
2090     }
2091     if (!cameraDeviceList.empty()) {
2092         CacheCameraDeviceAbilitySupportValue(CAMERA_ABILITY_SUPPORT_MUTE, isCameraMuteSupported);
2093     }
2094     return isCameraMuteSupported;
2095 }
2096 
IsCameraMuted()2097 bool CameraManager::IsCameraMuted()
2098 {
2099     bool isMuted = false;
2100     auto serviceProxy = GetServiceProxy();
2101     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, isMuted, "CameraManager::IsCameraMuted serviceProxy is null");
2102     int32_t retCode = serviceProxy->IsCameraMuted(isMuted);
2103     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK, "IsCameraMuted call failed, retCode: %{public}d", retCode);
2104     return isMuted;
2105 }
2106 
MuteCamera(bool muteMode)2107 void CameraManager::MuteCamera(bool muteMode)
2108 {
2109     auto serviceProxy = GetServiceProxy();
2110     CHECK_ERROR_RETURN_LOG(serviceProxy == nullptr, "CameraManager::MuteCamera serviceProxy is null");
2111     int32_t retCode = serviceProxy->MuteCamera(muteMode);
2112     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK, "MuteCamera call failed, retCode: %{public}d", retCode);
2113 }
2114 
MuteCameraPersist(PolicyType policyType,bool muteMode)2115 int32_t CameraManager::MuteCameraPersist(PolicyType policyType, bool muteMode)
2116 {
2117     auto serviceProxy = GetServiceProxy();
2118     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, SERVICE_FATL_ERROR,
2119         "CameraManager::MuteCameraPersist serviceProxy is null");
2120     int32_t retCode = serviceProxy->MuteCameraPersist(policyType, muteMode);
2121     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK, "MuteCameraPersist call failed, retCode: %{public}d", retCode);
2122     return ServiceToCameraError(retCode);
2123 }
2124 
PrelaunchCamera()2125 int32_t CameraManager::PrelaunchCamera()
2126 {
2127     auto serviceProxy = GetServiceProxy();
2128     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, SERVICE_FATL_ERROR, "PrelaunchCamera serviceProxy is null");
2129     int32_t retCode = serviceProxy->PrelaunchCamera();
2130     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK, "PrelaunchCamera call failed, retCode: %{public}d", retCode);
2131     return ServiceToCameraError(retCode);
2132 }
2133 
PreSwitchCamera(const std::string cameraId)2134 int32_t CameraManager::PreSwitchCamera(const std::string cameraId)
2135 {
2136     auto serviceProxy = GetServiceProxy();
2137     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, SERVICE_FATL_ERROR, "PreSwitchCamera serviceProxy is null");
2138     int32_t retCode = serviceProxy->PreSwitchCamera(cameraId);
2139     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK, "PreSwitchCamera call failed, retCode: %{public}d", retCode);
2140     return ServiceToCameraError(retCode);
2141 }
2142 
IsPrelaunchSupported(sptr<CameraDevice> camera)2143 bool CameraManager::IsPrelaunchSupported(sptr<CameraDevice> camera)
2144 {
2145     CHECK_ERROR_RETURN_RET(camera == nullptr, false);
2146     bool isPrelaunch = false;
2147     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata = camera->GetMetadata();
2148     CHECK_ERROR_RETURN_RET(metadata == nullptr, false);
2149     camera_metadata_item_t item;
2150     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_PRELAUNCH_AVAILABLE, &item);
2151     if (ret == 0) {
2152         MEDIA_INFO_LOG("CameraManager::IsPrelaunchSupported() OHOS_ABILITY_PRELAUNCH_AVAILABLE is %{public}d",
2153                        item.data.u8[0]);
2154         isPrelaunch = (item.data.u8[0] == 1);
2155     } else {
2156         MEDIA_ERR_LOG("Failed to get OHOS_ABILITY_PRELAUNCH_AVAILABLE ret = %{public}d", ret);
2157     }
2158     return isPrelaunch;
2159 }
2160 
IsTorchSupported()2161 bool CameraManager::IsTorchSupported()
2162 {
2163     bool isCameraTorchSupported = false;
2164     bool cacheResult = GetCameraDeviceAbilitySupportValue(CAMERA_ABILITY_SUPPORT_TORCH, isCameraTorchSupported);
2165     if (cacheResult) {
2166         return isCameraTorchSupported;
2167     }
2168 
2169     std::vector<sptr<CameraDevice>> cameraDeviceList;
2170     if (IsCameraDeviceListCached()) {
2171         cameraDeviceList = GetCameraDeviceList();
2172     } else {
2173         cameraDeviceList = GetCameraDeviceListFromServer();
2174     }
2175 
2176     for (auto& cameraDeviceInfo : cameraDeviceList) {
2177         std::shared_ptr<Camera::CameraMetadata> metadata = cameraDeviceInfo->GetMetadata();
2178         CHECK_ERROR_RETURN_RET(metadata == nullptr, false);
2179         camera_metadata_item_t item;
2180         int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_FLASH_AVAILABLE, &item);
2181         if (ret == CAM_META_SUCCESS && item.count > 0) {
2182             MEDIA_INFO_LOG("OHOS_ABILITY_FLASH_AVAILABLE is %{public}d", item.data.u8[0]);
2183             if (item.data.u8[0] == 1) {
2184                 isCameraTorchSupported = true;
2185                 break;
2186             }
2187         }
2188     }
2189 
2190     if (!cameraDeviceList.empty()) {
2191         CacheCameraDeviceAbilitySupportValue(CAMERA_ABILITY_SUPPORT_TORCH, isCameraTorchSupported);
2192     }
2193     return isCameraTorchSupported;
2194 }
2195 
IsTorchModeSupported(TorchMode mode)2196 bool CameraManager::IsTorchModeSupported(TorchMode mode)
2197 {
2198     return mode == TorchMode::TORCH_MODE_OFF || mode == TorchMode::TORCH_MODE_ON;
2199 }
2200 
GetTorchMode()2201 TorchMode CameraManager::GetTorchMode()
2202 {
2203     return torchMode_;
2204 }
2205 
SetTorchMode(TorchMode mode)2206 int32_t CameraManager::SetTorchMode(TorchMode mode)
2207 {
2208     int32_t retCode = CAMERA_OPERATION_NOT_ALLOWED;
2209     int32_t pid = IPCSkeleton::GetCallingPid();
2210     int32_t uid = IPCSkeleton::GetCallingUid();
2211     POWERMGR_SYSEVENT_TORCH_STATE(pid, uid, mode);
2212     switch (mode) {
2213         case TorchMode::TORCH_MODE_OFF:
2214             retCode = SetTorchLevel(0);
2215             break;
2216         case TorchMode::TORCH_MODE_ON:
2217             retCode = SetTorchLevel(1);
2218             break;
2219         case TorchMode::TORCH_MODE_AUTO:
2220             MEDIA_ERR_LOG("Invalid or unsupported torchMode value received from application");
2221             break;
2222         default:
2223             MEDIA_ERR_LOG("Invalid or unsupported torchMode value received from application");
2224     }
2225     if (retCode == CAMERA_OK) {
2226         UpdateTorchMode(mode);
2227     }
2228     return ServiceToCameraError(retCode);
2229 }
2230 
UpdateTorchMode(TorchMode mode)2231 void CameraManager::UpdateTorchMode(TorchMode mode)
2232 {
2233     if (torchMode_ == mode) {
2234         return;
2235     }
2236     torchMode_ = mode;
2237     MEDIA_INFO_LOG("CameraManager::UpdateTorchMode() mode is %{public}d", mode);
2238 }
2239 
SetTorchLevel(float level)2240 int32_t CameraManager::SetTorchLevel(float level)
2241 {
2242     auto serviceProxy = GetServiceProxy();
2243     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, SERVICE_FATL_ERROR, "SetTorchLevel serviceProxy is null");
2244     int32_t retCode = serviceProxy->SetTorchLevel(level);
2245     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK, "SetTorchLevel call failed, retCode: %{public}d", retCode);
2246     return retCode;
2247 }
2248 
SetPrelaunchConfig(std::string cameraId,RestoreParamTypeOhos restoreParamType,int activeTime,EffectParam effectParam)2249 int32_t CameraManager::SetPrelaunchConfig(
2250     std::string cameraId, RestoreParamTypeOhos restoreParamType, int activeTime, EffectParam effectParam)
2251 {
2252     auto serviceProxy = GetServiceProxy();
2253     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr, SERVICE_FATL_ERROR, "SetPrelaunchConfig serviceProxy is null");
2254     int32_t retCode = serviceProxy->SetPrelaunchConfig(
2255         cameraId, static_cast<RestoreParamTypeOhos>(restoreParamType), activeTime, effectParam);
2256     CHECK_ERROR_PRINT_LOG(retCode != CAMERA_OK, "SetPrelaunchConfig call failed, retCode: %{public}d", retCode);
2257     return ServiceToCameraError(retCode);
2258 }
2259 
SetCameraManagerNull()2260 void CameraManager::SetCameraManagerNull()
2261 {
2262     MEDIA_INFO_LOG("CameraManager::SetCameraManagerNull() called");
2263     g_cameraManager = nullptr;
2264 }
2265 
FillSupportPhotoFormats(std::vector<Profile> & photoProfiles)2266 void CameraManager::FillSupportPhotoFormats(std::vector<Profile>& photoProfiles)
2267 {
2268     if (photoFormats_.size() == 0 || photoProfiles.size() == 0) {
2269         return;
2270     }
2271     std::vector<Profile> extendProfiles = {};
2272     // if photo stream support jpeg, it must support yuv.
2273     for (const auto& profile : photoProfiles) {
2274         if (profile.format_ != CAMERA_FORMAT_JPEG) {
2275             extendProfiles.push_back(profile);
2276             continue;
2277         }
2278         for (const auto& format : photoFormats_) {
2279             Profile extendPhotoProfile = profile;
2280             extendPhotoProfile.format_ = format;
2281             extendProfiles.push_back(extendPhotoProfile);
2282         }
2283     }
2284     photoProfiles = extendProfiles;
2285 }
2286 
CreateMetadataOutputInternal(sptr<MetadataOutput> & pMetadataOutput,const std::vector<MetadataObjectType> & metadataObjectTypes)2287 int32_t CameraManager::CreateMetadataOutputInternal(sptr<MetadataOutput>& pMetadataOutput,
2288     const std::vector<MetadataObjectType>& metadataObjectTypes)
2289 {
2290     CAMERA_SYNC_TRACE;
2291     const size_t maxSize4NonSystemApp = 1;
2292     if (!CameraSecurity::CheckSystemApp()) {
2293         MEDIA_DEBUG_LOG("public calling for metadataOutput");
2294         if (metadataObjectTypes.size() > maxSize4NonSystemApp ||
2295             std::any_of(metadataObjectTypes.begin(), metadataObjectTypes.end(),
2296                 [](MetadataObjectType type) { return type != MetadataObjectType::FACE; })) {
2297             return CameraErrorCode::INVALID_ARGUMENT;
2298         }
2299     }
2300     auto serviceProxy = GetServiceProxy();
2301     CHECK_ERROR_RETURN_RET_LOG(serviceProxy == nullptr,  CameraErrorCode::SERVICE_FATL_ERROR,
2302         "CameraManager::CreateMetadataOutput serviceProxy is null");
2303 
2304     sptr<IConsumerSurface> surface = IConsumerSurface::Create();
2305     CHECK_ERROR_RETURN_RET_LOG(surface == nullptr,  CameraErrorCode::SERVICE_FATL_ERROR,
2306         "CameraManager::CreateMetadataOutput Failed to create MetadataOutputSurface");
2307     // only for face recognize
2308     int32_t format = OHOS_CAMERA_FORMAT_YCRCB_420_SP;
2309     int32_t width = 1920;
2310     int32_t height = 1080;
2311     surface->SetDefaultWidthAndHeight(width, height);
2312     sptr<IStreamMetadata> streamMetadata = nullptr;
2313     std::vector<int32_t> result(metadataObjectTypes.size());
2314     std::transform(metadataObjectTypes.begin(), metadataObjectTypes.end(), result.begin(), [](MetadataObjectType obj) {
2315         return static_cast<int32_t>(obj);
2316     });
2317     int32_t retCode = serviceProxy->CreateMetadataOutput(surface->GetProducer(), format, result, streamMetadata);
2318     CHECK_ERROR_RETURN_RET_LOG(retCode != CAMERA_OK, ServiceToCameraError(retCode),
2319         "CreateMetadataOutput Failed to get stream metadata object from hcamera service! %{public}d", retCode);
2320     pMetadataOutput = new (std::nothrow) MetadataOutput(surface, streamMetadata);
2321     CHECK_ERROR_RETURN_RET_LOG(pMetadataOutput == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
2322         "CreateMetadataOutput Failed to new pMetadataOutput!");
2323     pMetadataOutput->SetStream(streamMetadata);
2324     sptr<IBufferConsumerListener> bufferConsumerListener = new (std::nothrow) MetadataObjectListener(pMetadataOutput);
2325     CHECK_ERROR_RETURN_RET_LOG(bufferConsumerListener == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
2326         "CreateMetadataOutput Failed to new bufferConsumerListener!");
2327     SurfaceError ret = surface->RegisterConsumerListener(bufferConsumerListener);
2328     CHECK_ERROR_PRINT_LOG(ret != SURFACE_ERROR_OK,
2329         "MetadataOutputSurface consumer listener registration failed:%{public}d", ret);
2330     return CameraErrorCode::SUCCESS;
2331 }
2332 } // namespace CameraStandard
2333 } // namespace OHOS
2334