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