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