• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "session/capture_session.h"
17 
18 #include <cstdint>
19 #include <iterator>
20 #include <memory>
21 #include <mutex>
22 #include <sys/types.h>
23 
24 #include "camera_device.h"
25 #include "camera_device_ability_items.h"
26 #include "camera_error_code.h"
27 #include "camera_log.h"
28 #include "camera_metadata_info.h"
29 #include "camera_metadata_operator.h"
30 #include "camera_output_capability.h"
31 #include "camera_util.h"
32 #include "capture_output.h"
33 #include "camera_security_utils.h"
34 #include "capture_scene_const.h"
35 #include "features/moon_capture_boost_feature.h"
36 #include "capture_session_callback_stub.h"
37 #include "icapture_session_callback.h"
38 #include "input/camera_input.h"
39 #include "input/camera_manager.h"
40 #include "ipc_skeleton.h"
41 #include "os_account_manager.h"
42 #include "output/metadata_output.h"
43 #include "output/photo_output.h"
44 #include "output/preview_output.h"
45 #include "output/video_output.h"
46 #include "ability/camera_ability_builder.h"
47 #include "display/graphic/common/v1_0/cm_color_space.h"
48 #include "camera_rotation_api_utils.h"
49 #include "picture_interface.h"
50 
51 namespace OHOS {
52 namespace CameraStandard {
53 using namespace OHOS::HDI::Display::Graphic::Common::V1_0;
54 
55 namespace {
56 constexpr int32_t DEFAULT_ITEMS = 10;
57 constexpr int32_t DEFAULT_DATA_LENGTH = 100;
58 constexpr int32_t DEFERRED_MODE_DATA_SIZE = 2;
59 constexpr int32_t FRAMERATE_120 = 120;
60 constexpr int32_t FRAMERATE_240 = 240;
61 constexpr int32_t CONTROL_CENTER_FPS_MAX = 30;
62 } // namespace
63 
64 static const std::map<ColorSpace, CM_ColorSpaceType> g_fwkColorSpaceMap_ = {
65     {COLOR_SPACE_UNKNOWN, CM_COLORSPACE_NONE},
66     {DISPLAY_P3, CM_P3_FULL},
67     {SRGB, CM_SRGB_FULL},
68     {BT709, CM_BT709_FULL},
69     {BT2020_HLG, CM_BT2020_HLG_FULL},
70     {BT2020_PQ, CM_BT2020_PQ_FULL},
71     {P3_HLG, CM_P3_HLG_FULL},
72     {P3_PQ, CM_P3_PQ_FULL},
73     {DISPLAY_P3_LIMIT, CM_P3_LIMIT},
74     {SRGB_LIMIT, CM_SRGB_LIMIT},
75     {BT709_LIMIT, CM_BT709_LIMIT},
76     {BT2020_HLG_LIMIT, CM_BT2020_HLG_LIMIT},
77     {BT2020_PQ_LIMIT, CM_BT2020_PQ_LIMIT},
78     {P3_HLG_LIMIT, CM_P3_HLG_LIMIT},
79     {P3_PQ_LIMIT, CM_P3_PQ_LIMIT}
80 };
81 
82 const std::unordered_map<camera_focus_state_t, FocusCallback::FocusState> CaptureSession::metaFocusStateMap_ = {
83     {OHOS_CAMERA_FOCUS_STATE_SCAN, FocusCallback::SCAN},
84     {OHOS_CAMERA_FOCUS_STATE_FOCUSED, FocusCallback::FOCUSED},
85     {OHOS_CAMERA_FOCUS_STATE_UNFOCUSED, FocusCallback::UNFOCUSED}
86 };
87 
88 const std::unordered_map<camera_exposure_state_t,
89         ExposureCallback::ExposureState> CaptureSession::metaExposureStateMap_ = {
90     {OHOS_CAMERA_EXPOSURE_STATE_SCAN, ExposureCallback::SCAN},
91     {OHOS_CAMERA_EXPOSURE_STATE_CONVERGED, ExposureCallback::CONVERGED}
92 };
93 
94 const std::unordered_map<camera_filter_type_t, FilterType> CaptureSession::metaFilterTypeMap_ = {
95     {OHOS_CAMERA_FILTER_TYPE_NONE, NONE},
96     {OHOS_CAMERA_FILTER_TYPE_CLASSIC, CLASSIC},
97     {OHOS_CAMERA_FILTER_TYPE_DAWN, DAWN},
98     {OHOS_CAMERA_FILTER_TYPE_PURE, PURE},
99     {OHOS_CAMERA_FILTER_TYPE_GREY, GREY},
100     {OHOS_CAMERA_FILTER_TYPE_NATURAL, NATURAL},
101     {OHOS_CAMERA_FILTER_TYPE_MORI, MORI},
102     {OHOS_CAMERA_FILTER_TYPE_FAIR, FAIR},
103     {OHOS_CAMERA_FILTER_TYPE_PINK, PINK}
104 };
105 
106 const std::unordered_map<FilterType, camera_filter_type_t> CaptureSession::fwkFilterTypeMap_ = {
107     {NONE, OHOS_CAMERA_FILTER_TYPE_NONE},
108     {CLASSIC, OHOS_CAMERA_FILTER_TYPE_CLASSIC},
109     {DAWN, OHOS_CAMERA_FILTER_TYPE_DAWN},
110     {PURE, OHOS_CAMERA_FILTER_TYPE_PURE},
111     {GREY, OHOS_CAMERA_FILTER_TYPE_GREY},
112     {NATURAL, OHOS_CAMERA_FILTER_TYPE_NATURAL},
113     {MORI, OHOS_CAMERA_FILTER_TYPE_MORI},
114     {FAIR, OHOS_CAMERA_FILTER_TYPE_FAIR},
115     {PINK, OHOS_CAMERA_FILTER_TYPE_PINK}
116 };
117 
118 const std::unordered_map<BeautyType, camera_device_metadata_tag_t> CaptureSession::fwkBeautyControlMap_ = {
119     {AUTO_TYPE, OHOS_CONTROL_BEAUTY_AUTO_VALUE},
120     {SKIN_SMOOTH, OHOS_CONTROL_BEAUTY_SKIN_SMOOTH_VALUE},
121     {FACE_SLENDER, OHOS_CONTROL_BEAUTY_FACE_SLENDER_VALUE},
122     {SKIN_TONE, OHOS_CONTROL_BEAUTY_SKIN_TONE_VALUE}
123 };
124 
125 const std::unordered_map<camera_device_metadata_tag_t, BeautyType> CaptureSession::metaBeautyControlMap_ = {
126     {OHOS_CONTROL_BEAUTY_SKIN_SMOOTH_VALUE, SKIN_SMOOTH},
127     {OHOS_CONTROL_BEAUTY_FACE_SLENDER_VALUE, FACE_SLENDER},
128     {OHOS_CONTROL_BEAUTY_SKIN_TONE_VALUE, SKIN_TONE}
129 };
130 
131 const std::unordered_map<CameraEffectSuggestionType, EffectSuggestionType>
132     CaptureSession::metaEffectSuggestionTypeMap_ = {
133     {OHOS_CAMERA_EFFECT_SUGGESTION_NONE, EFFECT_SUGGESTION_NONE},
134     {OHOS_CAMERA_EFFECT_SUGGESTION_PORTRAIT, EFFECT_SUGGESTION_PORTRAIT},
135     {OHOS_CAMERA_EFFECT_SUGGESTION_FOOD, EFFECT_SUGGESTION_FOOD},
136     {OHOS_CAMERA_EFFECT_SUGGESTION_SKY, EFFECT_SUGGESTION_SKY},
137     {OHOS_CAMERA_EFFECT_SUGGESTION_SUNRISE_SUNSET, EFFECT_SUGGESTION_SUNRISE_SUNSET},
138     {OHOS_CAMERA_EFFECT_SUGGESTION_STAGE, EFFECT_SUGGESTION_STAGE}
139 };
140 
141 // WhiteBalanceMode
142 const std::unordered_map<camera_awb_mode_t, WhiteBalanceMode> CaptureSession::metaWhiteBalanceModeMap_ = {
143     { OHOS_CAMERA_AWB_MODE_OFF, AWB_MODE_OFF },
144     { OHOS_CAMERA_AWB_MODE_AUTO, AWB_MODE_AUTO },
145     { OHOS_CAMERA_AWB_MODE_INCANDESCENT, AWB_MODE_INCANDESCENT },
146     { OHOS_CAMERA_AWB_MODE_FLUORESCENT, AWB_MODE_FLUORESCENT },
147     { OHOS_CAMERA_AWB_MODE_WARM_FLUORESCENT, AWB_MODE_WARM_FLUORESCENT },
148     { OHOS_CAMERA_AWB_MODE_DAYLIGHT, AWB_MODE_DAYLIGHT },
149     { OHOS_CAMERA_AWB_MODE_CLOUDY_DAYLIGHT, AWB_MODE_CLOUDY_DAYLIGHT },
150     { OHOS_CAMERA_AWB_MODE_TWILIGHT, AWB_MODE_TWILIGHT },
151     { OHOS_CAMERA_AWB_MODE_SHADE, AWB_MODE_SHADE },
152 };
153 
154 const std::unordered_map<WhiteBalanceMode, camera_awb_mode_t> CaptureSession::fwkWhiteBalanceModeMap_ = {
155     { AWB_MODE_OFF, OHOS_CAMERA_AWB_MODE_OFF },
156     { AWB_MODE_AUTO, OHOS_CAMERA_AWB_MODE_AUTO },
157     { AWB_MODE_INCANDESCENT, OHOS_CAMERA_AWB_MODE_INCANDESCENT },
158     { AWB_MODE_FLUORESCENT, OHOS_CAMERA_AWB_MODE_FLUORESCENT },
159     { AWB_MODE_WARM_FLUORESCENT, OHOS_CAMERA_AWB_MODE_WARM_FLUORESCENT },
160     { AWB_MODE_DAYLIGHT, OHOS_CAMERA_AWB_MODE_DAYLIGHT },
161     { AWB_MODE_CLOUDY_DAYLIGHT, OHOS_CAMERA_AWB_MODE_CLOUDY_DAYLIGHT },
162     { AWB_MODE_TWILIGHT, OHOS_CAMERA_AWB_MODE_TWILIGHT },
163     { AWB_MODE_SHADE, OHOS_CAMERA_AWB_MODE_SHADE },
164 };
165 
166 const std::unordered_map<LightPaintingType, CameraLightPaintingType>
167     CaptureSession::fwkLightPaintingTypeMap_ = {
168     {CAR, OHOS_CAMERA_LIGHT_PAINTING_CAR},
169     {STAR, OHOS_CAMERA_LIGHT_PAINTING_STAR},
170     {WATER, OHOS_CAMERA_LIGHT_PAINTING_WATER},
171     {LIGHT, OHOS_CAMERA_LIGHT_PAINTING_LIGHT}
172 };
173 
174 const std::unordered_map<CameraLightPaintingType, LightPaintingType>
175     CaptureSession::metaLightPaintingTypeMap_ = {
176     {OHOS_CAMERA_LIGHT_PAINTING_CAR, CAR},
177     {OHOS_CAMERA_LIGHT_PAINTING_STAR, STAR},
178     {OHOS_CAMERA_LIGHT_PAINTING_WATER, WATER},
179     {OHOS_CAMERA_LIGHT_PAINTING_LIGHT, LIGHT}
180 };
181 
182 const std::unordered_map<TripodStatus, FwkTripodStatus>
183     CaptureSession::metaTripodStatusMap_ = {
184     {TRIPOD_STATUS_INVALID, FwkTripodStatus::INVALID},
185     {TRIPOD_STATUS_ACTIVE, FwkTripodStatus::ACTIVE},
186     {TRIPOD_STATUS_ENTER, FwkTripodStatus::ENTER},
187     {TRIPOD_STATUS_EXITING, FwkTripodStatus::EXITING}
188 };
189 
OnError(int32_t errorCode)190 int32_t CaptureSessionCallback::OnError(int32_t errorCode)
191 {
192     MEDIA_INFO_LOG("CaptureSessionCallback::OnError() is called!, errorCode: %{public}d", errorCode);
193     if (captureSession_ != nullptr && captureSession_->GetApplicationCallback() != nullptr) {
194         captureSession_->GetApplicationCallback()->OnError(errorCode);
195     } else {
196         MEDIA_INFO_LOG("CaptureSessionCallback::ApplicationCallback not set!, Discarding callback");
197     }
198     return CameraErrorCode::SUCCESS;
199 }
200 
OnPressureStatusChanged(PressureStatus status)201 int32_t PressureStatusCallback::OnPressureStatusChanged(PressureStatus status)
202 {
203     MEDIA_INFO_LOG("PressureStatusCallback::OnPressureStatusChanged() is called, status: %{public}d", status);
204     if (captureSession_ != nullptr) {
205         auto callback = captureSession_->GetPressureCallback();
206         if (callback) {
207             callback->OnPressureStatusChanged(status);
208         } else {
209             MEDIA_INFO_LOG("PressureStatusCallback::GetPressureCallback not set!, Discarding callback");
210         }
211     } else {
212         MEDIA_INFO_LOG("PressureStatusCallback captureSession not set!, Discarding callback");
213     }
214     return CameraErrorCode::SUCCESS;
215 }
216 
OnControlCenterEffectStatusChanged(const ControlCenterStatusInfo & controlCenterStatusInfo)217 int32_t ControlCenterEffectStatusCallback::OnControlCenterEffectStatusChanged(
218     const ControlCenterStatusInfo& controlCenterStatusInfo)
219 {
220     MEDIA_INFO_LOG("OnControlCenterEffectStatusChanged is called, status: %{public}d",
221         controlCenterStatusInfo.isActive);
222     auto session = captureSession_.promote();
223     if (session != nullptr) {
224         auto callback = session->GetControlCenterEffectCallback();
225         if (callback) {
226             callback->OnControlCenterEffectStatusChanged(controlCenterStatusInfo);
227         } else {
228             MEDIA_INFO_LOG(
229                 "ControlCenterEffectStatusCallback::OnControlCenterEffectStatusChanged not set!, Discarding callback");
230         }
231     } else {
232         MEDIA_INFO_LOG(
233             "ControlCenterEffectStatusCallback::OnControlCenterEffectStatusChanged not set!, Discarding callback");
234     }
235     return CameraErrorCode::SUCCESS;
236 }
237 
OnFoldStatusChanged(const FoldStatus status)238 int32_t FoldCallback::OnFoldStatusChanged(const FoldStatus status)
239 {
240     MEDIA_INFO_LOG("FoldStatus is %{public}d", status);
241     auto captureSession = captureSession_.promote();
242     CHECK_RETURN_RET_ELOG(captureSession == nullptr, CAMERA_OPERATION_NOT_ALLOWED, "captureSession is nullptr.");
243     bool isEnableAutoSwitch = captureSession->GetIsAutoSwitchDeviceStatus();
244     CHECK_RETURN_RET_ELOG(!isEnableAutoSwitch, CAMERA_OPERATION_NOT_ALLOWED, "isEnableAutoSwitch is false.");
245     // LCOV_EXCL_START
246     bool isSuccess = captureSession->SwitchDevice();
247     MEDIA_INFO_LOG("SwitchDevice isSuccess: %{public}d", isSuccess);
248     auto autoDeviceSwitchCallback = captureSession->GetAutoDeviceSwitchCallback();
249     CHECK_RETURN_RET_ELOG(autoDeviceSwitchCallback == nullptr, CAMERA_OPERATION_NOT_ALLOWED,
250         "autoDeviceSwitchCallback is nullptr");
251     bool isDeviceCapabilityChanged = captureSession->GetDeviceCapabilityChangeStatus();
252     MEDIA_INFO_LOG("SwitchDevice isDeviceCapabilityChanged: %{public}d", isDeviceCapabilityChanged);
253     autoDeviceSwitchCallback->OnAutoDeviceSwitchStatusChange(isSuccess, isDeviceCapabilityChanged);
254     return CAMERA_OK;
255     // LCOV_EXCL_STOP
256 }
257 
CaptureSession(sptr<ICaptureSession> & captureSession)258 CaptureSession::CaptureSession(sptr<ICaptureSession>& captureSession) : innerCaptureSession_(captureSession)
259 {
260     metadataResultProcessor_ = std::make_shared<CaptureSessionMetadataResultProcessor>(this);
261     sptr<IRemoteObject> object = innerCaptureSession_->AsObject();
262     pid_t pid = 0;
263     deathRecipient_ = new (std::nothrow) CameraDeathRecipient(pid);
264     CHECK_RETURN_ELOG(deathRecipient_ == nullptr, "failed to new CameraDeathRecipient.");
265 
266     deathRecipient_->SetNotifyCb([this](pid_t pid) { CameraServerDied(pid); });
267     bool result = object->AddDeathRecipient(deathRecipient_);
268     CHECK_RETURN_ELOG(!result, "failed to add deathRecipient");
269 }
270 
CameraServerDied(pid_t pid)271 void CaptureSession::CameraServerDied(pid_t pid)
272 {
273     MEDIA_ERR_LOG("camera server has died, pid:%{public}d!", pid);
274     {
275         std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
276         if (appCallback_ != nullptr) {
277             MEDIA_DEBUG_LOG("appCallback not nullptr");
278             int32_t serviceErrorType = ServiceToCameraError(CAMERA_INVALID_STATE);
279             appCallback_->OnError(serviceErrorType);
280         }
281     }
282     SessionRemoveDeathRecipient();
283 }
284 
SessionRemoveDeathRecipient()285 void CaptureSession::SessionRemoveDeathRecipient()
286 {
287     auto captureSession = GetCaptureSession();
288     if (captureSession != nullptr) {
289         (void)captureSession->AsObject()->RemoveDeathRecipient(deathRecipient_);
290         SetCaptureSession(nullptr);
291     }
292     deathRecipient_ = nullptr;
293 }
294 
~CaptureSession()295 CaptureSession::~CaptureSession()
296 {
297     MEDIA_DEBUG_LOG("Enter Into CaptureSession::~CaptureSession()");
298     SessionRemoveDeathRecipient();
299 }
300 
BeginConfig()301 int32_t CaptureSession::BeginConfig()
302 {
303     CAMERA_SYNC_TRACE;
304     MEDIA_DEBUG_LOG("Enter Into CaptureSession::BeginConfig");
305     CHECK_RETURN_RET_ELOG(IsSessionConfiged(), CameraErrorCode::SESSION_CONFIG_LOCKED,
306         "CaptureSession::BeginConfig Session is locked");
307 
308     isColorSpaceSetted_ = false;
309     int32_t errCode = CAMERA_UNKNOWN_ERROR;
310     auto captureSession = GetCaptureSession();
311     if (captureSession) {
312         errCode = captureSession->BeginConfig();
313         CHECK_PRINT_ELOG(errCode != CAMERA_OK, "Failed to BeginConfig!, %{public}d", errCode);
314     } else {
315         MEDIA_ERR_LOG("CaptureSession::BeginConfig() captureSession is nullptr");
316     }
317     return ServiceToCameraError(errCode);
318 }
319 
EnableRawDelivery(bool enabled)320 int32_t CaptureSession::EnableRawDelivery(bool enabled)
321 {
322     CAMERA_SYNC_TRACE;
323     MEDIA_INFO_LOG("Enter EnableRawDelivery, isEnable:%{public}d", enabled);
324     isRawImageDelivery_ = enabled;
325     return CameraErrorCode::SUCCESS;
326 }
327 
CommitConfig()328 int32_t CaptureSession::CommitConfig()
329 {
330     CAMERA_SYNC_TRACE;
331     MEDIA_DEBUG_LOG("Enter Into CaptureSession::CommitConfig");
332     CHECK_RETURN_RET_ELOG(!IsSessionConfiged(), CameraErrorCode::OPERATION_NOT_ALLOWED,
333         "CaptureSession::CommitConfig operation Not allowed!");
334     if (!CheckLightStatus()) {
335         MEDIA_ERR_LOG("CaptureSession::CommitConfig the camera can't support light status!");
336     }
337 
338     MEDIA_INFO_LOG("CaptureSession::CommitConfig isColorSpaceSetted_ = %{public}d", isColorSpaceSetted_);
339     if (!isColorSpaceSetted_) {
340         auto preconfigProfiles = GetPreconfigProfiles();
341         if (preconfigProfiles != nullptr) {
342             SetColorSpace(preconfigProfiles->colorSpace);
343         }
344     }
345     // DELIVERY_PHOTO for default when commit
346     if (photoOutput_ && !isDeferTypeSetted_) {
347         sptr<PhotoOutput> photoOutput = (sptr<PhotoOutput>&)photoOutput_;
348         int32_t supportCode = photoOutput->IsDeferredImageDeliverySupported(DELIVERY_PHOTO);
349         MEDIA_INFO_LOG("CaptureSession::CommitConfig supportCode:%{public}d", supportCode);
350         if (supportCode == 0) {
351             EnableDeferredType(photoOutput->IsEnableDeferred() ? DELIVERY_PHOTO : DELIVERY_NONE, false);
352         } else {
353             EnableDeferredType(DELIVERY_NONE, false);
354         }
355         SetUserId();
356     }
357     int32_t errCode = CAMERA_UNKNOWN_ERROR;
358     auto captureSession = GetCaptureSession();
359     bool isHasSwitchedOffline = false;
360     if (photoOutput_ && ((sptr<PhotoOutput> &)photoOutput_)->IsHasSwitchOfflinePhoto()) {
361         isHasSwitchedOffline = true;
362         EnableOfflinePhoto();
363     }
364     if (captureSession) {
365         std::string foldScreenType = CameraManager::GetInstance()->GetFoldScreenType();
366         CHECK_EXECUTE(!foldScreenType.empty() && foldScreenType[0] == '6' && !CameraSecurity::CheckSystemApp(),
367             AdjustRenderFit());
368         errCode = captureSession->SetCommitConfigFlag(isHasSwitchedOffline);
369         errCode = captureSession->CommitConfig();
370         MEDIA_INFO_LOG("CaptureSession::CommitConfig commit mode = %{public}d", GetMode());
371         if (errCode != CAMERA_OK) {
372             MEDIA_ERR_LOG("Failed to CommitConfig!, %{public}d", errCode);
373         } else {
374             CreateCameraAbilityContainer();
375         }
376     }
377     return ServiceToCameraError(errCode);
378 }
379 
CheckSpecSearch()380 void CaptureSession::CheckSpecSearch()
381 {
382     auto inputDevice = GetInputDevice();
383     CHECK_RETURN_ELOG(!inputDevice || !(inputDevice->GetCameraDeviceInfo()), "camera device is null");
384     camera_metadata_item_t item;
385     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
386     CHECK_RETURN_ELOG(metadata == nullptr, "CheckSpecSearch camera metadata is null");
387     int32_t retCode = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_AVAILABLE_PROFILE_LEVEL, &item);
388     if (retCode != CAM_META_SUCCESS || item.count == 0) {
389         MEDIA_ERR_LOG("specSearch is not support");
390         supportSpecSearch_ = false;
391         return;
392     }
393     supportSpecSearch_ = true;
394 }
395 
CheckLightStatus()396 bool CaptureSession::CheckLightStatus()
397 {
398     camera_metadata_item_t item;
399     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
400     CHECK_RETURN_RET_ELOG(metadata == nullptr, false, "CheckLightStatus camera metadata is null");
401     int32_t retCode = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_LIGHT_STATUS, &item);
402     if (retCode != CAM_META_SUCCESS || item.count == 0 || item.data.u8[0] == 0) {
403         MEDIA_ERR_LOG("lightStatus is not support");
404         return false;
405     }
406     uint8_t lightStart = 1;
407     LockForControl();
408     changedMetadata_->addEntry(OHOS_CONTROL_LIGHT_STATUS, &lightStart, 1);
409     UnlockForControl();
410     return true;
411 }
412 
PopulateProfileLists(std::vector<Profile> & photoProfileList,std::vector<Profile> & previewProfileList,std::vector<VideoProfile> & videoProfileList)413 void CaptureSession::PopulateProfileLists(std::vector<Profile>& photoProfileList,
414                                           std::vector<Profile>& previewProfileList,
415                                           std::vector<VideoProfile>& videoProfileList)
416 {
417     for (auto output : captureOutputSets_) {
418         auto item = output.promote();
419         if (item == nullptr) {
420             continue;
421         }
422         if (item->GetOutputType() == CAPTURE_OUTPUT_TYPE_PREVIEW) {
423             previewProfileList.emplace_back(*(item->GetPreviewProfile()));
424         } else if (item->GetOutputType() == CAPTURE_OUTPUT_TYPE_PHOTO) {
425             photoProfileList.emplace_back(*(item->GetPhotoProfile()));
426         } else if (item->GetOutputType() == CAPTURE_OUTPUT_TYPE_VIDEO) {
427             videoProfileList.emplace_back(*(item->GetVideoProfile()));
428         }
429     }
430 }
431 
PopulateSpecIdMaps(sptr<CameraDevice> device,int32_t modeName,std::map<int32_t,std::vector<Profile>> & specIdPreviewMap,std::map<int32_t,std::vector<Profile>> & specIdPhotoMap,std::map<int32_t,std::vector<VideoProfile>> & specIdVideoMap)432 void CaptureSession::PopulateSpecIdMaps(sptr<CameraDevice> device, int32_t modeName,
433                                         std::map<int32_t, std::vector<Profile>>& specIdPreviewMap,
434                                         std::map<int32_t, std::vector<Profile>>& specIdPhotoMap,
435                                         std::map<int32_t, std::vector<VideoProfile>>& specIdVideoMap)
436 {
437     CHECK_RETURN_ELOG(!device, "camera device is null");
438     auto buildSpecProfileMap = [](auto& profiles, auto& map) {
439         for (auto& profile : profiles) {
440             map[profile.GetSpecId()].emplace_back(profile);
441         }
442     };
443 
444     buildSpecProfileMap(device->modePreviewProfiles_[modeName], specIdPreviewMap);
445     buildSpecProfileMap(device->modePhotoProfiles_[modeName], specIdPhotoMap);
446     buildSpecProfileMap(device->modeVideoProfiles_[modeName], specIdVideoMap);
447 }
448 
GetCameraOutputCapabilities(sptr<CameraDevice> & device)449 std::vector<sptr<CameraOutputCapability>> CaptureSession::GetCameraOutputCapabilities(sptr<CameraDevice> &device)
450 {
451     int32_t modeName = GetMode();
452     std::map<int32_t, std::vector<Profile>> specIdPreviewMap;
453     std::map<int32_t, std::vector<Profile>> specIdPhotoMap;
454     std::map<int32_t, std::vector<VideoProfile>> specIdVideoMap;
455     PopulateSpecIdMaps(device, modeName, specIdPreviewMap, specIdPhotoMap, specIdVideoMap);
456     std::vector<sptr<CameraOutputCapability>> list;
457     for (const auto& pair : specIdPreviewMap) {
458         int32_t specId = pair.first;
459         sptr<CameraOutputCapability> cameraOutputCapability = new CameraOutputCapability();
460         if (cameraOutputCapability == nullptr) {
461             continue;
462         }
463         cameraOutputCapability->SetPreviewProfiles(specIdPreviewMap[specId]);
464         cameraOutputCapability->SetPhotoProfiles(specIdPhotoMap[specId]);
465         cameraOutputCapability->SetVideoProfiles(specIdVideoMap[specId]);
466         cameraOutputCapability->specId_ = specId;
467         list.emplace_back(cameraOutputCapability);
468     }
469     return list;
470 }
471 
GetSessionFunctions(std::vector<Profile> & previewProfiles,std::vector<Profile> & photoProfiles,std::vector<VideoProfile> & videoProfiles,bool isForApp)472 std::vector<sptr<CameraAbility>> CaptureSession::GetSessionFunctions(std::vector<Profile>& previewProfiles,
473                                                                      std::vector<Profile>& photoProfiles,
474                                                                      std::vector<VideoProfile>& videoProfiles,
475                                                                      bool isForApp)
476 {
477     MEDIA_INFO_LOG("CaptureSession::GetSessionFunctions enter");
478     auto inputDevice = GetInputDevice();
479     CHECK_RETURN_RET_ELOG(inputDevice == nullptr, {}, "CaptureSession::GetSessionFunctions inputDevice is null");
480     auto device = inputDevice->GetCameraDeviceInfo();
481     std::vector<sptr<CameraOutputCapability>> outputCapabilityList = GetCameraOutputCapabilities(device);
482     std::set<int32_t> supportedSpecIds;
483 
484     for (const auto &profile : previewProfiles) {
485         profile.DumpProfile("preview");
486     }
487     for (const auto& profile : photoProfiles) {
488         profile.DumpProfile("photo");
489     }
490     for (const auto& profile : videoProfiles) {
491         profile.DumpVideoProfile("video");
492     }
493 
494     for (const auto& capability : outputCapabilityList) {
495         int32_t specId = capability->specId_;
496         MEDIA_DEBUG_LOG("CaptureSession::GetSessionFunctions specId: %{public}d", specId);
497         if (capability->IsMatchPreviewProfiles(previewProfiles) &&
498             capability->IsMatchPhotoProfiles(photoProfiles) &&
499             capability->IsMatchVideoProfiles(videoProfiles)) {
500             supportedSpecIds.insert(specId);
501             MEDIA_INFO_LOG("CaptureSession::GetSessionFunctions insert specId: %{public}d", specId);
502         }
503     }
504 
505     CameraAbilityBuilder builder;
506     std::vector<sptr<CameraAbility>> cameraAbilityArray;
507     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
508     CHECK_RETURN_RET_ELOG(metadata == nullptr, cameraAbilityArray,
509         "GetSessionFunctions camera metadata is null");
510     return builder.GetAbility(
511         GetFeaturesMode().GetFeaturedMode(), metadata->get(), supportedSpecIds, this, isForApp);
512 }
513 
GetSessionConflictFunctions()514 std::vector<sptr<CameraAbility>> CaptureSession::GetSessionConflictFunctions()
515 {
516     CameraAbilityBuilder builder;
517     std::vector<sptr<CameraAbility>> cameraAbilityArray;
518     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
519     CHECK_RETURN_RET_ELOG(metadata == nullptr, cameraAbilityArray,
520         "GetSessionConflictFunctions camera metadata is null");
521     return builder.GetConflictAbility(GetFeaturesMode().GetFeaturedMode(), metadata->get());
522 }
523 
CreateCameraAbilityContainer()524 void CaptureSession::CreateCameraAbilityContainer()
525 {
526     auto inputDevice = GetInputDevice();
527     CHECK_RETURN_ELOG(inputDevice == nullptr, "CreateCameraAbilityContainer inputDevice is null");
528     std::vector<Profile> photoProfileList;
529     std::vector<Profile> previewProfileList;
530     std::vector<VideoProfile> videoProfileList;
531     PopulateProfileLists(photoProfileList, previewProfileList, videoProfileList);
532     std::vector<sptr<CameraAbility>> abilities =
533         GetSessionFunctions(previewProfileList, photoProfileList, videoProfileList, false);
534     MEDIA_DEBUG_LOG("CreateCameraAbilityContainer abilities size %{public}zu", abilities.size());
535     if (abilities.size() == 0) {
536         MEDIA_INFO_LOG("CreateCameraAbilityContainer fail cant find suitable ability");
537     }
538     std::vector<sptr<CameraAbility>> conflictAbilities = GetSessionConflictFunctions();
539     MEDIA_DEBUG_LOG("CreateCameraAbilityContainer conflictAbilities size %{public}zu", conflictAbilities.size());
540     std::lock_guard<std::mutex> lock(abilityContainerMutex_);
541     cameraAbilityContainer_ = new CameraAbilityContainer(abilities, conflictAbilities, this);
542 }
543 
CanAddInput(sptr<CaptureInput> & input)544 bool CaptureSession::CanAddInput(sptr<CaptureInput>& input)
545 {
546     // can only add one cameraInput
547     CAMERA_SYNC_TRACE;
548     bool ret = false;
549     MEDIA_INFO_LOG("Enter Into CaptureSession::CanAddInput");
550     CHECK_RETURN_RET_ELOG(!IsSessionConfiged() || input == nullptr, ret,
551         "CaptureSession::AddInput operation Not allowed!");
552     auto captureSession = GetCaptureSession();
553     CHECK_RETURN_RET_ELOG(captureSession == nullptr, ret,
554         "CaptureSession::CanAddInput() captureSession is nullptr");
555     captureSession->CanAddInput(((sptr<CameraInput>&)input)->GetCameraDevice(), ret);
556     return ret;
557 }
558 
GetMetadataFromService(sptr<CameraDevice> device)559 void CaptureSession::GetMetadataFromService(sptr<CameraDevice> device)
560 {
561     CHECK_RETURN_ELOG(device == nullptr, "CaptureSession::GetMetadataFromService device is nullptr");
562     auto cameraId = device->GetID();
563     auto serviceProxy = CameraManager::GetInstance()->GetServiceProxy();
564     CHECK_RETURN_ELOG(serviceProxy == nullptr, "CaptureSession::GetMetadataFromService serviceProxy is null");
565     std::shared_ptr<OHOS::Camera::CameraMetadata> metaData;
566     serviceProxy->GetCameraAbility(cameraId, metaData);
567     CHECK_RETURN_ELOG(metaData == nullptr,
568         "CaptureSession::GetMetadataFromService GetDeviceMetadata failed");
569     device->AddMetadata(metaData);
570 }
571 
AddInput(sptr<CaptureInput> & input)572 int32_t CaptureSession::AddInput(sptr<CaptureInput>& input)
573 {
574     CAMERA_SYNC_TRACE;
575     MEDIA_DEBUG_LOG("Enter Into CaptureSession::AddInput");
576     CHECK_RETURN_RET_ELOG(!IsSessionConfiged(), CameraErrorCode::OPERATION_NOT_ALLOWED,
577         "CaptureSession::AddInput operation Not allowed!");
578     CHECK_RETURN_RET_ELOG(
579         input == nullptr, ServiceToCameraError(CAMERA_INVALID_ARG), "CaptureSession::AddInput input is null");
580     int32_t errCode = CAMERA_UNKNOWN_ERROR;
581     auto captureSession = GetCaptureSession();
582     CHECK_RETURN_RET_ELOG(captureSession == nullptr, ServiceToCameraError(errCode),
583         "CaptureSession::AddInput() captureSession is nullptr");
584     auto cameraInput = (sptr<CameraInput>&)input;
585     if (!cameraInput->timeQueue_.empty()) {
586         cameraInput->UnregisterTime();
587     }
588     CHECK_RETURN_RET_ELOG(!cameraInput->GetCameraDeviceInfo(), ServiceToCameraError(CAMERA_DEVICE_CLOSED),
589         "CaptureSession::AddInput GetCameraDeviceInfo is nullptr");
590     CameraPosition position = cameraInput->GetCameraDeviceInfo()->GetPosition();
591     bool positionCondition = position == CameraPosition::CAMERA_POSITION_FRONT
592         || position == CameraPosition::CAMERA_POSITION_FOLD_INNER;
593     CameraManager::GetInstance()->SetControlCenterPositionCondition(positionCondition);
594     errCode = captureSession->AddInput(((sptr<CameraInput>&)input)->GetCameraDevice());
595     CHECK_RETURN_RET_ELOG(
596         errCode != CAMERA_OK, ServiceToCameraError(errCode), "Failed to AddInput!, %{public}d", errCode);
597     SetInputDevice(input);
598     CheckSpecSearch();
599     input->SetMetadataResultProcessor(GetMetadataResultProcessor());
600     UpdateDeviceDeferredability();
601     FindTagId();
602     return ServiceToCameraError(errCode);
603 }
604 
UpdateDeviceDeferredability()605 void CaptureSession::UpdateDeviceDeferredability()
606 {
607     MEDIA_DEBUG_LOG("UpdateDeviceDeferredability begin.");
608     auto inputDevice = GetInputDevice();
609     CHECK_RETURN_ELOG(inputDevice == nullptr,
610         "CaptureSession::UpdateDeviceDeferredability inputDevice is nullptr");
611     auto deviceInfo = inputDevice->GetCameraDeviceInfo();
612     CHECK_RETURN_ELOG(deviceInfo == nullptr,
613         "CaptureSession::UpdateDeviceDeferredability deviceInfo is nullptr");
614     deviceInfo->modeDeferredType_ = {};
615     camera_metadata_item_t item;
616     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
617     CHECK_RETURN_ELOG(metadata == nullptr, "UpdateDeviceDeferredability camera metadata is null");
618     int32_t ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_DEFERRED_IMAGE_DELIVERY, &item);
619     MEDIA_INFO_LOG("UpdateDeviceDeferredability get ret: %{public}d", ret);
620     MEDIA_DEBUG_LOG("UpdateDeviceDeferredability item: %{public}d count: %{public}d", item.item, item.count);
621     for (uint32_t i = 0; i + 1 < item.count; i++) {
622         if (i % DEFERRED_MODE_DATA_SIZE == 0) {
623             MEDIA_DEBUG_LOG("UpdateDeviceDeferredability mode index:%{public}d, deferredType:%{public}d",
624                 item.data.u8[i], item.data.u8[i + 1]);
625             deviceInfo->modeDeferredType_[item.data.u8[i]] =
626                 static_cast<DeferredDeliveryImageType>(item.data.u8[i + 1]);
627         }
628     }
629 
630     deviceInfo->modeVideoDeferredType_ = {};
631     ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_AUTO_DEFERRED_VIDEO_ENHANCE, &item);
632     MEDIA_INFO_LOG("UpdateDeviceDeferredability get video ret: %{public}d", ret);
633     MEDIA_DEBUG_LOG("UpdateDeviceDeferredability video item: %{public}d count: %{public}d", item.item, item.count);
634     for (uint32_t i = 0; i + 1 < item.count; i++) {
635         if (i % DEFERRED_MODE_DATA_SIZE == 0) {
636             MEDIA_DEBUG_LOG("UpdateDeviceDeferredability mode index:%{public}d, video deferredType:%{public}d",
637                 item.data.u8[i], item.data.u8[i + 1]);
638             deviceInfo->modeVideoDeferredType_[item.data.u8[i]] = item.data.u8[i + 1];
639         }
640     }
641 }
642 
FindTagId()643 void CaptureSession::FindTagId()
644 {
645     MEDIA_INFO_LOG("Enter Into CaptureSession::FindTagId");
646     auto inputDevice = GetInputDevice();
647     CHECK_RETURN(inputDevice == nullptr);
648     MEDIA_DEBUG_LOG("CaptureSession::FindTagId inputDevice not nullptr");
649     std::vector<vendorTag_t> vendorTagInfos;
650     sptr<CameraInput> camInput = (sptr<CameraInput>&)inputDevice;
651     int32_t ret = camInput->GetCameraAllVendorTags(vendorTagInfos);
652     CHECK_RETURN_ELOG(ret != CAMERA_OK, "Failed to GetCameraAllVendorTags");
653     for (auto info : vendorTagInfos) {
654         if (info.tagName == nullptr) {
655             continue;
656         }
657         if (strcmp(info.tagName, "hwSensorName") == 0) {
658             HAL_CUSTOM_SENSOR_MODULE_TYPE = info.tagId;
659         } else if (strcmp(info.tagName, "lensFocusDistance") == 0) {
660             HAL_CUSTOM_LENS_FOCUS_DISTANCE = info.tagId;
661         } else if (strcmp(info.tagName, "sensorSensitivity") == 0) {
662             HAL_CUSTOM_SENSOR_SENSITIVITY = info.tagId;
663         } else if (strcmp(info.tagName, "cameraLaserData") == 0) {
664             HAL_CUSTOM_LASER_DATA = info.tagId;
665         } else if (strcmp(info.tagName, "cameraArMode") == 0) {
666             HAL_CUSTOM_AR_MODE = info.tagId;
667         }
668     }
669 }
670 
CheckFrameRateRangeWithCurrentFps(int32_t curMinFps,int32_t curMaxFps,int32_t minFps,int32_t maxFps)671 bool CaptureSession::CheckFrameRateRangeWithCurrentFps(int32_t curMinFps, int32_t curMaxFps,
672                                                        int32_t minFps, int32_t maxFps)
673 {
674     CHECK_RETURN_RET_ELOG(minFps == 0 || curMinFps == 0, false,
675         "CaptureSession::CheckFrameRateRangeWithCurrentFps can not set zero!");
676     if (curMinFps == curMaxFps && minFps == maxFps &&
677         (minFps % curMinFps == 0 || curMinFps % minFps == 0)) {
678         return true;
679     } else if (curMinFps != curMaxFps && curMinFps == minFps && curMaxFps == maxFps) {
680         return true;
681     }
682     MEDIA_WARNING_LOG("CaptureSession::CheckFrameRateRangeWithCurrentFps check is not pass!");
683     return false;
684 }
685 
GetMetaOutput()686 sptr<CaptureOutput> CaptureSession::GetMetaOutput()
687 {
688     MEDIA_DEBUG_LOG("CaptureSession::GetMetadataOutput metaOuput(%{public}d)", metaOutput_ != nullptr);
689     return metaOutput_;
690 }
691 
ConfigurePreviewOutput(sptr<CaptureOutput> & output)692 int32_t CaptureSession::ConfigurePreviewOutput(sptr<CaptureOutput>& output)
693 {
694     MEDIA_INFO_LOG("CaptureSession::ConfigurePreviewOutput enter");
695     auto previewProfile = output->GetPreviewProfile();
696     if (output->IsTagSetted(CaptureOutput::DYNAMIC_PROFILE)) {
697         CHECK_RETURN_RET_ELOG(previewProfile != nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
698             "CaptureSession::ConfigurePreviewOutput previewProfile is not null, is that output in use?");
699         // LCOV_EXCL_START
700         auto preconfigPreviewProfile = GetPreconfigPreviewProfile();
701         CHECK_RETURN_RET_ELOG(preconfigPreviewProfile == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
702             "CaptureSession::ConfigurePreviewOutput preconfigPreviewProfile is nullptr");
703         output->SetPreviewProfile(*preconfigPreviewProfile);
704         int32_t res = output->CreateStream();
705         CHECK_RETURN_RET_ELOG(res != CameraErrorCode::SUCCESS, res,
706             "CaptureSession::ConfigurePreviewOutput createStream from preconfig fail! %{public}d", res);
707         MEDIA_INFO_LOG("CaptureSession::ConfigurePreviewOutput createStream from preconfig success");
708         previewProfile_ = *preconfigPreviewProfile;
709         // LCOV_EXCL_STOP
710     } else {
711         previewProfile_ = *previewProfile;
712     }
713     SetGuessMode(SceneMode::CAPTURE);
714     return CameraErrorCode::SUCCESS;
715 }
716 
GetMaxSizePhotoProfile(ProfileSizeRatio sizeRatio)717 std::shared_ptr<Profile> CaptureSession::GetMaxSizePhotoProfile(ProfileSizeRatio sizeRatio)
718 {
719     auto inputDevice = GetInputDevice();
720     CHECK_RETURN_RET(inputDevice == nullptr, nullptr);
721     auto cameraInfo = inputDevice->GetCameraDeviceInfo();
722     CHECK_RETURN_RET(cameraInfo == nullptr, nullptr);
723     // Non-foldable devices filter out physical lenses.
724     CHECK_RETURN_RET(cameraInfo->GetCameraFoldScreenType() == CAMERA_FOLDSCREEN_UNSPECIFIED &&
725         cameraInfo->GetCameraType() != CAMERA_TYPE_DEFAULT, nullptr);
726     SceneMode sceneMode = GetMode();
727     if (sceneMode == SceneMode::CAPTURE) {
728         auto it = cameraInfo->modePhotoProfiles_.find(SceneMode::CAPTURE);
729         CHECK_RETURN_RET(it == cameraInfo->modePhotoProfiles_.end(), nullptr);
730         float photoRatioValue = GetTargetRatio(sizeRatio, RATIO_VALUE_4_3);
731         return cameraInfo->GetMaxSizeProfile<Profile>(it->second, photoRatioValue, CameraFormat::CAMERA_FORMAT_JPEG);
732     } else if (sceneMode == SceneMode::VIDEO) {
733         // LCOV_EXCL_START
734         auto it = cameraInfo->modePhotoProfiles_.find(SceneMode::VIDEO);
735         CHECK_RETURN_RET(it == cameraInfo->modePhotoProfiles_.end(), nullptr);
736         float photoRatioValue = GetTargetRatio(sizeRatio, RATIO_VALUE_16_9);
737         return cameraInfo->GetMaxSizeProfile<Profile>(it->second, photoRatioValue, CameraFormat::CAMERA_FORMAT_JPEG);
738         // LCOV_EXCL_STOP
739     } else {
740         return nullptr;
741     }
742     return nullptr;
743 }
744 
GetPreconfigPreviewProfile()745 std::shared_ptr<Profile> CaptureSession::GetPreconfigPreviewProfile()
746 {
747     auto preconfigProfiles = GetPreconfigProfiles();
748     CHECK_RETURN_RET_ELOG(preconfigProfiles == nullptr, nullptr,
749         "CaptureSession::GetPreconfigPreviewProfile preconfigProfiles is nullptr");
750     return std::make_shared<Profile>(preconfigProfiles->previewProfile);
751 }
752 
GetPreconfigPhotoProfile()753 std::shared_ptr<Profile> CaptureSession::GetPreconfigPhotoProfile()
754 {
755     auto preconfigProfiles = GetPreconfigProfiles();
756     CHECK_RETURN_RET_ELOG(preconfigProfiles == nullptr, nullptr,
757         "CaptureSession::GetPreconfigPhotoProfile preconfigProfiles is nullptr");
758     // LCOV_EXCL_START
759     if (preconfigProfiles->photoProfile.sizeFollowSensorMax_) {
760         auto maxSizePhotoProfile = GetMaxSizePhotoProfile(preconfigProfiles->photoProfile.sizeRatio_);
761         CHECK_RETURN_RET_ELOG(maxSizePhotoProfile == nullptr, nullptr,
762             "CaptureSession::GetPreconfigPhotoProfile maxSizePhotoProfile is null");
763         MEDIA_INFO_LOG("CaptureSession::GetPreconfigPhotoProfile preconfig maxSizePhotoProfile %{public}dx%{public}d "
764                        ",format:%{public}d",
765             maxSizePhotoProfile->size_.width, maxSizePhotoProfile->size_.height, maxSizePhotoProfile->format_);
766         return maxSizePhotoProfile;
767     }
768     return std::make_shared<Profile>(preconfigProfiles->photoProfile);
769     // LCOV_EXCL_STOP
770 }
771 
GetPreconfigVideoProfile()772 std::shared_ptr<VideoProfile> CaptureSession::GetPreconfigVideoProfile()
773 {
774     auto preconfigProfiles = GetPreconfigProfiles();
775     CHECK_RETURN_RET_ELOG(preconfigProfiles == nullptr, nullptr,
776         "CaptureSession::GetPreconfigVideoProfile preconfigProfiles is nullptr");
777     return std::make_shared<VideoProfile>(preconfigProfiles->videoProfile);
778 }
779 
ConfigurePhotoOutput(sptr<CaptureOutput> & output)780 int32_t CaptureSession::ConfigurePhotoOutput(sptr<CaptureOutput>& output)
781 {
782     MEDIA_INFO_LOG("CaptureSession::ConfigurePhotoOutput enter");
783     auto photoProfile = output->GetPhotoProfile();
784     if (output->IsTagSetted(CaptureOutput::DYNAMIC_PROFILE)) {
785         CHECK_RETURN_RET_ELOG(photoProfile != nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
786             "CaptureSession::ConfigurePhotoOutput photoProfile is not null, is that output in use?");
787         // LCOV_EXCL_START
788         auto preconfigPhotoProfile = GetPreconfigPhotoProfile();
789         CHECK_RETURN_RET_ELOG(preconfigPhotoProfile == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
790             "CaptureSession::ConfigurePhotoOutput preconfigPhotoProfile is null");
791         output->SetPhotoProfile(*preconfigPhotoProfile);
792         int32_t res = output->CreateStream();
793         CHECK_RETURN_RET_ELOG(res != CameraErrorCode::SUCCESS, res,
794             "CaptureSession::ConfigurePhotoOutput createStream from preconfig fail! %{public}d", res);
795         MEDIA_INFO_LOG("CaptureSession::ConfigurePhotoOutput createStream from preconfig success");
796         photoProfile_ = *preconfigPhotoProfile;
797         // LCOV_EXCL_STOP
798     } else {
799         photoProfile_ = *photoProfile;
800     }
801     SetGuessMode(SceneMode::CAPTURE);
802     return CameraErrorCode::SUCCESS;
803 }
804 
ConfigureVideoOutput(sptr<CaptureOutput> & output)805 int32_t CaptureSession::ConfigureVideoOutput(sptr<CaptureOutput>& output)
806 {
807     MEDIA_INFO_LOG("CaptureSession::ConfigureVideoOutput enter");
808     auto videoProfile = output->GetVideoProfile();
809     if (output->IsTagSetted(CaptureOutput::DYNAMIC_PROFILE)) {
810         CHECK_RETURN_RET_ELOG(videoProfile != nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
811             "CaptureSession::ConfigureVideoOutput videoProfile is not null, is that output in use?");
812         // LCOV_EXCL_START
813         auto preconfigVideoProfile = GetPreconfigVideoProfile();
814         CHECK_RETURN_RET_ELOG(preconfigVideoProfile == nullptr, CameraErrorCode::SERVICE_FATL_ERROR,
815             "CaptureSession::ConfigureVideoOutput preconfigVideoProfile is nullptr");
816         videoProfile = preconfigVideoProfile;
817         output->SetVideoProfile(*preconfigVideoProfile);
818         int32_t res = output->CreateStream();
819         CHECK_RETURN_RET_ELOG(res != CameraErrorCode::SUCCESS, res,
820             "CaptureSession::ConfigureVideoOutput createStream from preconfig fail! %{public}d", res);
821         MEDIA_INFO_LOG("CaptureSession::ConfigureVideoOutput createStream from preconfig success");
822         // LCOV_EXCL_STOP
823     }
824     std::vector<int32_t> frameRateRange = videoProfile->GetFrameRates();
825     const size_t minFpsRangeSize = 2;
826     CHECK_EXECUTE(frameRateRange.size() >= minFpsRangeSize, SetFrameRateRange(frameRateRange));
827     if (output != nullptr) {
828         sptr<VideoOutput> videoOutput = static_cast<VideoOutput*>(output.GetRefPtr());
829         CHECK_EXECUTE(videoOutput && (frameRateRange.size() >= minFpsRangeSize),
830             videoOutput->SetFrameRateRange(frameRateRange[0], frameRateRange[1]));
831     }
832     SetGuessMode(SceneMode::VIDEO);
833     return CameraErrorCode::SUCCESS;
834 }
835 
ConfigureOutput(sptr<CaptureOutput> & output)836 int32_t CaptureSession::ConfigureOutput(sptr<CaptureOutput>& output)
837 {
838     MEDIA_INFO_LOG("Enter Into CaptureSession::ConfigureOutput");
839     output->SetSession(this);
840     auto type = output->GetOutputType();
841     MEDIA_INFO_LOG("CaptureSession::ConfigureOutput outputType is:%{public}d", type);
842     switch (type) {
843         case CAPTURE_OUTPUT_TYPE_PREVIEW:
844             return ConfigurePreviewOutput(output);
845         case CAPTURE_OUTPUT_TYPE_PHOTO:
846             return ConfigurePhotoOutput(output);
847         case CAPTURE_OUTPUT_TYPE_VIDEO:
848             return ConfigureVideoOutput(output);
849         default:
850             // do nothing.
851             break;
852     }
853     return CameraErrorCode::SUCCESS;
854 }
855 
InsertOutputIntoSet(sptr<CaptureOutput> & output)856 void CaptureSession::InsertOutputIntoSet(sptr<CaptureOutput>& output)
857 {
858     std::lock_guard<std::mutex> lock(captureOutputSetsMutex_);
859     auto it = captureOutputSets_.begin();
860     while (it != captureOutputSets_.end()) {
861         if (*it == nullptr) {
862             it = captureOutputSets_.erase(it);
863         } else if (*it == output) {
864             break;
865         } else {
866             ++it;
867         }
868     }
869     CHECK_EXECUTE(it == captureOutputSets_.end(), captureOutputSets_.insert(output));
870 }
871 
AddOutput(sptr<CaptureOutput> & output)872 int32_t CaptureSession::AddOutput(sptr<CaptureOutput>& output)
873 {
874     CAMERA_SYNC_TRACE;
875     MEDIA_DEBUG_LOG("Enter Into CaptureSession::AddOutput");
876     CHECK_RETURN_RET_ELOG(!IsSessionConfiged(), CameraErrorCode::OPERATION_NOT_ALLOWED,
877         "CaptureSession::AddOutput operation Not allowed!");
878     CHECK_RETURN_RET_ELOG(output == nullptr, ServiceToCameraError(CAMERA_INVALID_ARG),
879         "CaptureSession::AddOutput output is null");
880 
881     CHECK_RETURN_RET_ELOG(ConfigureOutput(output) != CameraErrorCode::SUCCESS,
882         CameraErrorCode::SERVICE_FATL_ERROR,
883         "CaptureSession::AddOutput ConfigureOutput fail!");
884     if (output->GetOutputType() == CAPTURE_OUTPUT_TYPE_METADATA) {
885         MEDIA_INFO_LOG("CaptureSession::AddOutput MetadataOutput");
886         metaOutput_ = output;
887     }
888     CHECK_RETURN_RET_ELOG(!CanAddOutput(output), ServiceToCameraError(CAMERA_INVALID_ARG),
889         "CanAddOutput check failed!");
890     auto captureSession = GetCaptureSession();
891     CHECK_RETURN_RET_ELOG(captureSession == nullptr, ServiceToCameraError(CAMERA_UNKNOWN_ERROR),
892         "CaptureSession::AddOutput() captureSession is nullptr");
893     int32_t ret = AdaptOutputVideoHighFrameRate(output, captureSession);
894     CHECK_RETURN_RET_ELOG(ret != CameraErrorCode::SUCCESS, ServiceToCameraError(CAMERA_INVALID_ARG),
895         "CaptureSession::AddOutput An Error in the AdaptOutputVideoHighFrameRate");
896     int32_t errCode = CAMERA_UNKNOWN_ERROR;
897     CHECK_EXECUTE(output->GetStream() != nullptr,
898         errCode = captureSession->AddOutput(output->GetStreamType(), output->GetStream()->AsObject()));
899     if (output->GetOutputType() == CAPTURE_OUTPUT_TYPE_PHOTO) {
900         photoOutput_ = output;
901     }
902     MEDIA_INFO_LOG("CaptureSession::AddOutput StreamType = %{public}d", output->GetStreamType());
903     CHECK_RETURN_RET_ELOG(
904         errCode != CAMERA_OK, ServiceToCameraError(errCode), "Failed to AddOutput!, %{public}d", errCode);
905     InsertOutputIntoSet(output);
906     uint32_t apiCompatibleVersion = CameraApiVersion::GetApiVersion();
907     sptr<IStreamCommon> stream = output->GetStream();
908     IStreamRepeat* repeatStream = nullptr;
909     if (output->GetOutputType() == CAPTURE_OUTPUT_TYPE_PREVIEW) {
910         repeatStream = static_cast<IStreamRepeat*>(stream.GetRefPtr());
911     }
912     int32_t errItemCode = CAMERA_UNKNOWN_ERROR;
913     if (repeatStream) {
914         errItemCode = repeatStream->SetCameraApi(apiCompatibleVersion);
915         MEDIA_ERR_LOG("SetCameraApi!, errCode: %{public}d", errItemCode);
916     } else {
917         MEDIA_ERR_LOG("PreviewOutput::SetCameraApi() repeatStream is nullptr");
918     }
919     return ServiceToCameraError(errCode);
920 }
921 
AdaptOutputVideoHighFrameRate(sptr<CaptureOutput> & output,sptr<ICaptureSession> & captureSession)922 int32_t CaptureSession::AdaptOutputVideoHighFrameRate(sptr<CaptureOutput>& output,
923     sptr<ICaptureSession>& captureSession)
924 {
925     MEDIA_INFO_LOG("Enter Into CaptureSession::AdaptOutputVideoHighFrameRate");
926     CHECK_RETURN_RET_ELOG(output == nullptr, CameraErrorCode::INVALID_ARGUMENT,
927         "CaptureSession::AdaptOutputVideoHighFrameRate output is null");
928     CHECK_RETURN_RET_ELOG(captureSession == nullptr, CameraErrorCode::INVALID_ARGUMENT,
929         "CaptureSession::AdaptOutputVideoHighFrameRate() captureSession is nullptr");
930     if (GetMode() == SceneMode::VIDEO && output->GetOutputType() == CAPTURE_OUTPUT_TYPE_VIDEO) {
931         // LCOV_EXCL_START
932         std::vector<int32_t> videoFrameRates = output->GetVideoProfile()->GetFrameRates();
933         CHECK_RETURN_RET_ELOG(videoFrameRates.empty(), CameraErrorCode::INVALID_ARGUMENT,
934             "videoFrameRates is empty!");
935         if (videoFrameRates[0] == FRAMERATE_120 || videoFrameRates[0] == FRAMERATE_240) {
936             captureSession->SetFeatureMode(SceneMode::HIGH_FRAME_RATE);
937             SetMode(SceneMode::HIGH_FRAME_RATE);
938             return CameraErrorCode::SUCCESS;
939         }
940         // LCOV_EXCL_STOP
941     }
942     return CameraErrorCode::SUCCESS;
943 }
944 
AddSecureOutput(sptr<CaptureOutput> & output)945 int32_t CaptureSession::AddSecureOutput(sptr<CaptureOutput> &output)
946 {
947     CAMERA_SYNC_TRACE;
948     MEDIA_INFO_LOG("Enter Into SecureCameraSession::AddSecureOutput");
949     CHECK_RETURN_RET(currentMode_ != SceneMode::SECURE, CAMERA_OPERATION_NOT_ALLOWED);
950     // LCOV_EXCL_START
951     CHECK_RETURN_RET_ELOG(!IsSessionConfiged() || output == nullptr || isSetSecureOutput_,
952         CAMERA_OPERATION_NOT_ALLOWED, "SecureCameraSession::AddSecureOutput operation is Not allowed!");
953     sptr<IStreamCommon> stream = output->GetStream();
954     IStreamRepeat* repeatStream = static_cast<IStreamRepeat*>(stream.GetRefPtr());
955     repeatStream->EnableSecure(true);
956     isSetSecureOutput_ = true;
957     return CAMERA_OK;
958     // LCOV_EXCL_STOP
959 }
960 
CanAddOutput(sptr<CaptureOutput> & output)961 bool CaptureSession::CanAddOutput(sptr<CaptureOutput>& output)
962 {
963     CAMERA_SYNC_TRACE;
964     MEDIA_DEBUG_LOG("Enter Into CaptureSession::CanAddOutput");
965     CHECK_RETURN_RET_ELOG(!IsSessionConfiged() || output == nullptr, false,
966         "CaptureSession::CanAddOutput operation Not allowed!");
967     auto inputDevice = GetInputDevice();
968     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), false,
969         "CaptureSession::CanAddOutput Failed inputDevice is nullptr");
970     auto outputType = output->GetOutputType();
971     std::shared_ptr<Profile> profilePtr = nullptr;
972     switch (outputType) {
973         case CAPTURE_OUTPUT_TYPE_PREVIEW:
974             profilePtr = output->IsTagSetted(CaptureOutput::DYNAMIC_PROFILE) ? GetPreconfigPreviewProfile()
975                                                                              : output->GetPreviewProfile();
976             break;
977         case CAPTURE_OUTPUT_TYPE_PHOTO:
978             profilePtr = output->IsTagSetted(CaptureOutput::DYNAMIC_PROFILE) ? GetPreconfigPhotoProfile()
979                                                                              : output->GetPhotoProfile();
980             break;
981         case CAPTURE_OUTPUT_TYPE_VIDEO:
982             profilePtr = output->IsTagSetted(CaptureOutput::DYNAMIC_PROFILE) ? GetPreconfigVideoProfile()
983                                                                              : output->GetVideoProfile();
984             break;
985         case CAPTURE_OUTPUT_TYPE_DEPTH_DATA:
986             profilePtr = output->GetDepthProfile();
987             break;
988         case CAPTURE_OUTPUT_TYPE_METADATA:
989             return true;
990         default:
991             MEDIA_ERR_LOG("CaptureSession::CanAddOutput CaptureOutputType unknown");
992             return false;
993     }
994     CHECK_RETURN_RET(profilePtr == nullptr, false);
995     return ValidateOutputProfile(*profilePtr, outputType);
996 }
997 
RemoveInput(sptr<CaptureInput> & input)998 int32_t CaptureSession::RemoveInput(sptr<CaptureInput>& input)
999 {
1000     CAMERA_SYNC_TRACE;
1001     MEDIA_DEBUG_LOG("Enter Into CaptureSession::RemoveInput");
1002     CHECK_RETURN_RET_ELOG(!IsSessionConfiged(), CameraErrorCode::OPERATION_NOT_ALLOWED,
1003         "CaptureSession::RemoveInput operation Not allowed!");
1004 
1005     CHECK_RETURN_RET_ELOG(input == nullptr, ServiceToCameraError(CAMERA_INVALID_ARG),
1006         "CaptureSession::RemoveInput input is null");
1007     auto device = ((sptr<CameraInput>&)input)->GetCameraDevice();
1008     CHECK_RETURN_RET_ELOG(device == nullptr, ServiceToCameraError(CAMERA_INVALID_ARG),
1009         "CaptureSession::RemoveInput device is null");
1010     supportSpecSearch_ = false;
1011     {
1012         std::lock_guard<std::mutex> lock(abilityContainerMutex_);
1013         cameraAbilityContainer_ = nullptr;
1014     }
1015     SetInputDevice(nullptr);
1016     int32_t errCode = CAMERA_UNKNOWN_ERROR;
1017     auto captureSession = GetCaptureSession();
1018     if (captureSession) {
1019         errCode = captureSession->RemoveInput(device);
1020         auto deviceInfo = input->GetCameraDeviceInfo();
1021         if (deviceInfo != nullptr) {
1022             deviceInfo->ResetMetadata();
1023         }
1024         CHECK_PRINT_ELOG(errCode != CAMERA_OK, "Failed to RemoveInput!, %{public}d", errCode);
1025     } else {
1026         MEDIA_ERR_LOG("CaptureSession::RemoveInput() captureSession is nullptr");
1027     }
1028     return ServiceToCameraError(errCode);
1029 }
1030 
RemoveOutputFromSet(sptr<CaptureOutput> & output)1031 void CaptureSession::RemoveOutputFromSet(sptr<CaptureOutput>& output)
1032 {
1033     std::lock_guard<std::mutex> lock(captureOutputSetsMutex_);
1034     auto it = captureOutputSets_.begin();
1035     while (it != captureOutputSets_.end()) {
1036         if (*it == nullptr) {
1037             it = captureOutputSets_.erase(it);
1038         } else if (*it == output) {
1039             captureOutputSets_.erase(it);
1040             return;
1041         } else {
1042             ++it;
1043         }
1044     }
1045 }
1046 
RemoveOutput(sptr<CaptureOutput> & output)1047 int32_t CaptureSession::RemoveOutput(sptr<CaptureOutput>& output)
1048 {
1049     CAMERA_SYNC_TRACE;
1050     MEDIA_DEBUG_LOG("Enter Into CaptureSession::RemoveOutput");
1051     CHECK_RETURN_RET_ELOG(!IsSessionConfiged(), CameraErrorCode::OPERATION_NOT_ALLOWED,
1052         "CaptureSession::RemoveOutput session is not configed!");
1053     CHECK_RETURN_RET_ELOG(output == nullptr, ServiceToCameraError(CAMERA_INVALID_ARG),
1054         "CaptureSession::RemoveOutput output is null");
1055     // LCOV_EXCL_START
1056     output->SetSession(nullptr);
1057     if (output->GetOutputType() == CAPTURE_OUTPUT_TYPE_METADATA) {
1058         sptr<MetadataOutput> metaOutput = static_cast<MetadataOutput*>(output.GetRefPtr());
1059         CHECK_RETURN_RET_ELOG(!metaOutput, ServiceToCameraError(CAMERA_INVALID_ARG),
1060             "CaptureSession::metaOutput is null");
1061         std::vector<MetadataObjectType> metadataObjectTypes = {};
1062         MEDIA_DEBUG_LOG("CaptureSession::RemoveOutput SetCapturingMetadataObjectTypes off");
1063         metaOutput->Stop();
1064         MEDIA_DEBUG_LOG("CaptureSession::RemoveOutput remove metaOutput");
1065         return ServiceToCameraError(CAMERA_OK);
1066     }
1067     // LCOV_EXCL_STOP
1068     int32_t errCode = CAMERA_UNKNOWN_ERROR;
1069     auto captureSession = GetCaptureSession();
1070     if (captureSession) {
1071         if (output->GetOutputType() == CAPTURE_OUTPUT_TYPE_PHOTO && photoOutput_ &&
1072             ((sptr<PhotoOutput> &)photoOutput_)->IsHasEnableOfflinePhoto()) {
1073             ((sptr<PhotoOutput> &)photoOutput_)->SetSwitchOfflinePhotoOutput(true);
1074         }
1075         CHECK_EXECUTE(output->GetStream() != nullptr,
1076             errCode = captureSession->RemoveOutput(output->GetStreamType(), output->GetStream()->AsObject()));
1077         CHECK_PRINT_ELOG(errCode != CAMERA_OK, "Failed to RemoveOutput!, %{public}d", errCode);
1078     } else {
1079         MEDIA_ERR_LOG("CaptureSession::RemoveOutput() captureSession is nullptr");
1080     }
1081     RemoveOutputFromSet(output);
1082     CHECK_EXECUTE(output->IsTagSetted(CaptureOutput::DYNAMIC_PROFILE), output->ClearProfiles());
1083     return ServiceToCameraError(errCode);
1084 }
1085 
Start()1086 int32_t CaptureSession::Start()
1087 {
1088     CAMERA_SYNC_TRACE;
1089     MEDIA_DEBUG_LOG("Enter Into CaptureSession::Start");
1090     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
1091         "CaptureSession::Start Session not Commited");
1092     int32_t errCode = CAMERA_UNKNOWN_ERROR;
1093     auto captureSession = GetCaptureSession();
1094     if (captureSession) {
1095         errCode = captureSession->Start();
1096         CHECK_PRINT_ELOG(errCode != CAMERA_OK, "Failed to Start capture session!, %{public}d", errCode);
1097     } else {
1098         MEDIA_ERR_LOG("CaptureSession::Start() captureSession is nullptr");
1099     }
1100     if (GetMetaOutput()) {
1101         sptr<MetadataOutput> metaOutput = static_cast<MetadataOutput*>(GetMetaOutput().GetRefPtr());
1102         CHECK_RETURN_RET_ELOG(!metaOutput, ServiceToCameraError(errCode), "CaptureSession::metaOutput is null");
1103         metaOutput->Start();
1104     }
1105     return ServiceToCameraError(errCode);
1106 }
1107 
Stop()1108 int32_t CaptureSession::Stop()
1109 {
1110     CAMERA_SYNC_TRACE;
1111     MEDIA_DEBUG_LOG("Enter Into CaptureSession::Stop");
1112     int32_t errCode = CAMERA_UNKNOWN_ERROR;
1113     auto captureSession = GetCaptureSession();
1114     if (captureSession) {
1115         errCode = captureSession->Stop();
1116         CHECK_PRINT_ELOG(errCode != CAMERA_OK, "Failed to Stop capture session!, %{public}d", errCode);
1117     } else {
1118         MEDIA_ERR_LOG("CaptureSession::Stop() captureSession is nullptr");
1119     }
1120     return ServiceToCameraError(errCode);
1121 }
1122 
Release()1123 int32_t CaptureSession::Release()
1124 {
1125     CAMERA_SYNC_TRACE;
1126     MEDIA_DEBUG_LOG("Enter Into CaptureSession::Release");
1127     int32_t errCode = CAMERA_UNKNOWN_ERROR;
1128     auto captureSession = GetCaptureSession();
1129     if (captureSession) {
1130         errCode = captureSession->Release();
1131         MEDIA_DEBUG_LOG("Release capture session, %{public}d", errCode);
1132     } else {
1133         MEDIA_ERR_LOG("CaptureSession::Release() captureSession is nullptr");
1134     }
1135     SetInputDevice(nullptr);
1136     SessionRemoveDeathRecipient();
1137     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1138     captureSessionCallback_ = nullptr;
1139     pressureStatusCallback_ = nullptr;
1140     appCallback_ = nullptr;
1141     appPressureCallback_ = nullptr;
1142     exposureCallback_ = nullptr;
1143     focusCallback_ = nullptr;
1144     macroStatusCallback_ = nullptr;
1145     moonCaptureBoostStatusCallback_ = nullptr;
1146     smoothZoomCallback_ = nullptr;
1147     abilityCallback_ = nullptr;
1148     arCallback_ = nullptr;
1149     effectSuggestionCallback_ = nullptr;
1150     cameraAbilityContainer_ = nullptr;
1151     foldStatusCallback_ = nullptr;
1152     return ServiceToCameraError(errCode);
1153 }
1154 
SetCallback(std::shared_ptr<SessionCallback> callback)1155 void CaptureSession::SetCallback(std::shared_ptr<SessionCallback> callback)
1156 {
1157     CHECK_PRINT_ELOG(callback == nullptr, "CaptureSession::SetCallback Unregistering application callback!");
1158     int32_t errorCode = CAMERA_OK;
1159     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1160     appCallback_ = callback;
1161     auto captureSession = GetCaptureSession();
1162     if (appCallback_ != nullptr && captureSession != nullptr) {
1163         if (captureSessionCallback_ == nullptr) {
1164             captureSessionCallback_ = new (std::nothrow) CaptureSessionCallback(this);
1165             CHECK_RETURN_ELOG(captureSessionCallback_ == nullptr, "failed to new captureSessionCallback_!");
1166         }
1167         if (captureSession) {
1168             errorCode = captureSession->SetCallback(captureSessionCallback_);
1169             if (errorCode != CAMERA_OK) {
1170                 MEDIA_ERR_LOG(
1171                     "CaptureSession::SetCallback: Failed to register callback, errorCode: %{public}d", errorCode);
1172                 captureSessionCallback_ = nullptr;
1173                 appCallback_ = nullptr;
1174             }
1175         } else {
1176             MEDIA_ERR_LOG("CaptureSession::SetCallback captureSession is nullptr");
1177         }
1178     }
1179     return;
1180 }
1181 
SetPressureCallback(std::shared_ptr<PressureCallback> callback)1182 void CaptureSession::SetPressureCallback(std::shared_ptr<PressureCallback> callback)
1183 {
1184     CHECK_PRINT_ELOG(callback == nullptr,
1185         "CaptureSession::SetPressureCallback Unregistering application callback!");
1186     int32_t errorCode = CAMERA_OK;
1187     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1188     appPressureCallback_ = callback;
1189     auto captureSession = GetCaptureSession();
1190     if (appPressureCallback_ != nullptr && captureSession != nullptr) {
1191         if (pressureStatusCallback_ == nullptr) {
1192             pressureStatusCallback_ = new (std::nothrow) PressureStatusCallback(this);
1193             CHECK_RETURN_ELOG(pressureStatusCallback_ == nullptr, "failed to new pressureStatusCallback_!");
1194         }
1195         if (captureSession) {
1196             errorCode = captureSession->SetPressureCallback(pressureStatusCallback_);
1197             if (errorCode != CAMERA_OK) {
1198                 MEDIA_ERR_LOG("CaptureSession::SetPressureCallback: Failed to register callback, errorCode: %{public}d",
1199                     errorCode);
1200                 pressureStatusCallback_ = nullptr;
1201                 appPressureCallback_ = nullptr;
1202             }
1203         } else {
1204             MEDIA_ERR_LOG("CaptureSession::SetPressureCallback captureSession is nullptr");
1205         }
1206     }
1207     return;
1208 }
1209 
SetControlCenterEffectStatusCallback(std::shared_ptr<ControlCenterEffectCallback> callback)1210 void CaptureSession::SetControlCenterEffectStatusCallback(std::shared_ptr<ControlCenterEffectCallback> callback)
1211 {
1212     CHECK_PRINT_ELOG(callback == nullptr,
1213         "CaptureSession::SetControlCenterEffectStatusCallback callback is null.");
1214     int32_t errorCode = CAMERA_OK;
1215     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1216     appControlCenterEffectStatusCallback_ = callback;
1217     auto captureSession = GetCaptureSession();
1218     if (appControlCenterEffectStatusCallback_ != nullptr && captureSession != nullptr) {
1219         if (controlCenterEffectStatusCallback_ == nullptr) {
1220             controlCenterEffectStatusCallback_ = new (std::nothrow) ControlCenterEffectStatusCallback(this);
1221             CHECK_RETURN_ELOG(controlCenterEffectStatusCallback_ == nullptr,
1222                 "failed to new controlCenterEffectStatusCallback_!");
1223         }
1224         errorCode = captureSession->SetControlCenterEffectStatusCallback(controlCenterEffectStatusCallback_);
1225         if (errorCode != CAMERA_OK) {
1226             MEDIA_ERR_LOG(
1227                 "SetControlCenterEffectStatusCallback: Failed to register callback, errorCode: %{public}d",
1228                 errorCode);
1229             controlCenterEffectStatusCallback_ = nullptr;
1230             appControlCenterEffectStatusCallback_ = nullptr;
1231         }
1232     }
1233     return;
1234 }
1235 
UnSetControlCenterEffectStatusCallback()1236 void CaptureSession::UnSetControlCenterEffectStatusCallback()
1237 {
1238     MEDIA_INFO_LOG("CaptureSession::UnSetControlCenterEffectStatusCallback");
1239     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1240     appControlCenterEffectStatusCallback_ = nullptr;
1241     auto captureSession = GetCaptureSession();
1242     CHECK_PRINT_ELOG(captureSession == nullptr,
1243         "CaptureSession::UnSetControlCenterEffectStatusCallback captureSession is nullptr");
1244     captureSession->UnSetControlCenterEffectStatusCallback();
1245 }
1246 
SetPreviewRotation(std::string & deviceClass)1247 int32_t CaptureSession::SetPreviewRotation(std::string &deviceClass)
1248 {
1249     int32_t errorCode = CAMERA_OK;
1250     auto captureSession = GetCaptureSession();
1251     if (captureSession) {
1252         errorCode = captureSession->SetPreviewRotation(deviceClass);
1253         CHECK_PRINT_ELOG(errorCode != CAMERA_OK, "SetPreviewRotation is failed errorCode: %{public}d", errorCode);
1254     } else {
1255         MEDIA_ERR_LOG("CaptureSession::SetPreviewRotation captureSession is nullptr");
1256     }
1257     return errorCode;
1258 }
1259 
GetApplicationCallback()1260 std::shared_ptr<SessionCallback> CaptureSession::GetApplicationCallback()
1261 {
1262     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1263     return appCallback_;
1264 }
1265 
GetPressureCallback()1266 std::shared_ptr<PressureCallback> CaptureSession::GetPressureCallback()
1267 {
1268     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1269     return appPressureCallback_;
1270 }
1271 
GetControlCenterEffectCallback()1272 std::shared_ptr<ControlCenterEffectCallback> CaptureSession::GetControlCenterEffectCallback()
1273 {
1274     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1275     return appControlCenterEffectStatusCallback_;
1276 }
1277 
GetExposureCallback()1278 std::shared_ptr<ExposureCallback> CaptureSession::GetExposureCallback()
1279 {
1280     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1281     return exposureCallback_;
1282 }
1283 
GetFocusCallback()1284 std::shared_ptr<FocusCallback> CaptureSession::GetFocusCallback()
1285 {
1286     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1287     return focusCallback_;
1288 }
1289 
GetMacroStatusCallback()1290 std::shared_ptr<MacroStatusCallback> CaptureSession::GetMacroStatusCallback()
1291 {
1292     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1293     return macroStatusCallback_;
1294 }
1295 
GetMoonCaptureBoostStatusCallback()1296 std::shared_ptr<MoonCaptureBoostStatusCallback> CaptureSession::GetMoonCaptureBoostStatusCallback()
1297 {
1298     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1299     return moonCaptureBoostStatusCallback_;
1300 }
1301 
GetFeatureDetectionStatusCallback()1302 std::shared_ptr<FeatureDetectionStatusCallback> CaptureSession::GetFeatureDetectionStatusCallback()
1303 {
1304     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1305     return featureDetectionStatusCallback_;
1306 }
1307 
GetSmoothZoomCallback()1308 std::shared_ptr<SmoothZoomCallback> CaptureSession::GetSmoothZoomCallback()
1309 {
1310     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1311     return smoothZoomCallback_;
1312 }
1313 
GetARCallback()1314 std::shared_ptr<ARCallback> CaptureSession::GetARCallback()
1315 {
1316     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1317     return arCallback_;
1318 }
1319 
UpdateSetting(std::shared_ptr<Camera::CameraMetadata> changedMetadata)1320 int32_t CaptureSession::UpdateSetting(std::shared_ptr<Camera::CameraMetadata> changedMetadata)
1321 {
1322     CAMERA_SYNC_TRACE;
1323     CHECK_RETURN_RET_ELOG(!changedMetadata,
1324         CameraErrorCode::INVALID_ARGUMENT, "CaptureSession::UpdateSetting changedMetadata is nullptr");
1325     auto metadataHeader = changedMetadata->get();
1326     uint32_t count = Camera::GetCameraMetadataItemCount(metadataHeader);
1327     if (count == 0) {
1328         MEDIA_INFO_LOG("CaptureSession::UpdateSetting No configuration to update");
1329         return CameraErrorCode::SUCCESS;
1330     }
1331 
1332     auto inputDevice = GetInputDevice();
1333     CHECK_RETURN_RET_ELOG(!inputDevice, CameraErrorCode::SUCCESS,
1334         "CaptureSession::UpdateSetting Failed inputDevice is nullptr");
1335     auto cameraDeviceObj = ((sptr<CameraInput>&)inputDevice)->GetCameraDevice();
1336     CHECK_RETURN_RET_ELOG(!cameraDeviceObj,
1337         CameraErrorCode::SUCCESS, "CaptureSession::UpdateSetting Failed cameraDeviceObj is nullptr");
1338     int32_t ret = cameraDeviceObj->UpdateSetting(changedMetadata);
1339     CHECK_RETURN_RET_ELOG(ret != CAMERA_OK, ServiceToCameraError(ret),
1340         "CaptureSession::UpdateSetting Failed to update settings, errCode = %{public}d", ret);
1341 
1342     std::shared_ptr<Camera::CameraMetadata> baseMetadata = GetMetadata();
1343     CHECK_RETURN_RET_ELOG(baseMetadata == nullptr, CameraErrorCode::SUCCESS,
1344         "CaptureSession::UpdateSetting camera metadata is null");
1345     for (uint32_t index = 0; index < count; index++) {
1346         camera_metadata_item_t srcItem;
1347         int ret = OHOS::Camera::GetCameraMetadataItem(metadataHeader, index, &srcItem);
1348         CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CAMERA_INVALID_ARG,
1349             "CaptureSession::UpdateSetting Failed to get metadata item at index: %{public}d", index);
1350         bool status = false;
1351         uint32_t currentIndex;
1352         ret = OHOS::Camera::FindCameraMetadataItemIndex(baseMetadata->get(), srcItem.item, &currentIndex);
1353         if (ret == CAM_META_SUCCESS) {
1354             status = baseMetadata->updateEntry(srcItem.item, srcItem.data.u8, srcItem.count);
1355         } else if (ret == CAM_META_ITEM_NOT_FOUND) {
1356             status = baseMetadata->addEntry(srcItem.item, srcItem.data.u8, srcItem.count);
1357         }
1358         CHECK_PRINT_ELOG(!status,
1359             "CaptureSession::UpdateSetting Failed to add/update metadata item: %{public}d", srcItem.item);
1360     }
1361     OnSettingUpdated(changedMetadata);
1362     return CameraErrorCode::SUCCESS;
1363 }
1364 
OnSettingUpdated(std::shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata)1365 void CaptureSession::OnSettingUpdated(std::shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata)
1366 {
1367     std::lock_guard<std::mutex> lock(captureOutputSetsMutex_);
1368     auto it = captureOutputSets_.begin();
1369     while (it != captureOutputSets_.end()) {
1370         auto output = it->promote();
1371         if (output == nullptr) {
1372             it = captureOutputSets_.erase(it);
1373             continue;
1374         }
1375         ++it;
1376         auto filters = output->GetObserverControlTags();
1377         if (filters.empty()) {
1378             continue;
1379         }
1380         for (auto tag : filters) {
1381             camera_metadata_item_t item;
1382             int ret = Camera::FindCameraMetadataItem(changedMetadata->get(), tag, &item);
1383             if (ret != CAM_META_SUCCESS || item.count <= 0) {
1384                 continue;
1385             }
1386             output->OnControlMetadataChanged(tag, item);
1387         }
1388     }
1389 }
1390 
OnResultReceived(std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)1391 void CaptureSession::OnResultReceived(std::shared_ptr<OHOS::Camera::CameraMetadata> metadata)
1392 {
1393     std::lock_guard<std::mutex> lock(captureOutputSetsMutex_);
1394     auto it = captureOutputSets_.begin();
1395     while (it != captureOutputSets_.end()) {
1396         // LCOV_EXCL_START
1397         auto output = it->promote();
1398         if (output == nullptr) {
1399             it = captureOutputSets_.erase(it);
1400             continue;
1401         }
1402         ++it;
1403         auto filters = output->GetObserverResultTags();
1404         if (filters.empty()) {
1405             continue;
1406         }
1407         for (auto tag : filters) {
1408             camera_metadata_item_t item;
1409             int ret = Camera::FindCameraMetadataItem(metadata->get(), tag, &item);
1410             if (ret != CAM_META_SUCCESS || item.count <= 0) {
1411                 continue;
1412             }
1413             output->OnResultMetadataChanged(tag, item);
1414         }
1415         // LCOV_EXCL_STOP
1416     }
1417 }
1418 
LockForControl()1419 void CaptureSession::LockForControl()
1420 {
1421     changeMetaMutex_.lock();
1422     MEDIA_DEBUG_LOG("CaptureSession::LockForControl Called");
1423     changedMetadata_ = std::make_shared<Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
1424 }
1425 
UnlockForControl()1426 int32_t CaptureSession::UnlockForControl()
1427 {
1428     if (changedMetadata_ == nullptr) {
1429         MEDIA_ERR_LOG("CaptureSession::UnlockForControl Need to call LockForControl() before UnlockForControl()");
1430         changeMetaMutex_.unlock();
1431         return ServiceToCameraError(CAMERA_INVALID_ARG);
1432     }
1433     MEDIA_DEBUG_LOG("CaptureSession::UnlockForControl Called");
1434     UpdateSetting(changedMetadata_);
1435     changedMetadata_ = nullptr;
1436     changeMetaMutex_.unlock();
1437     return CameraErrorCode::SUCCESS;
1438 }
1439 
GetActiveVideoStabilizationMode()1440 VideoStabilizationMode CaptureSession::GetActiveVideoStabilizationMode()
1441 {
1442     sptr<CameraDevice> cameraObj_;
1443     auto inputDevice = GetInputDevice();
1444     CHECK_RETURN_RET_ELOG(!inputDevice, OFF,
1445         "CaptureSession::GetActiveVideoStabilizationMode camera device is null");
1446     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
1447     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, OFF,
1448         "CaptureSession::GetActiveVideoStabilizationMode camera deviceInfo is null");
1449     cameraObj_ = inputDeviceInfo;
1450     std::shared_ptr<Camera::CameraMetadata> metadata = cameraObj_->GetCachedMetadata();
1451     CHECK_RETURN_RET_ELOG(metadata == nullptr, OFF,
1452         "GetActiveVideoStabilizationMode camera metadata is null");
1453     camera_metadata_item_t item;
1454     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_VIDEO_STABILIZATION_MODE, &item);
1455     if (ret == CAM_META_SUCCESS) {
1456         auto itr = g_metaVideoStabModesMap_.find(static_cast<CameraVideoStabilizationMode>(item.data.u8[0]));
1457         CHECK_RETURN_RET(itr != g_metaVideoStabModesMap_.end(), itr->second);
1458     }
1459     return OFF;
1460 }
1461 
GetActiveVideoStabilizationMode(VideoStabilizationMode & mode)1462 int32_t CaptureSession::GetActiveVideoStabilizationMode(VideoStabilizationMode& mode)
1463 {
1464     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
1465         "CaptureSession::GetActiveVideoStabilizationMode Session is not Commited");
1466     auto inputDevice = GetInputDevice();
1467     CHECK_RETURN_RET_ELOG(!inputDevice, CameraErrorCode::SUCCESS,
1468         "CaptureSession::GetActiveVideoStabilizationMode camera device is null");
1469     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
1470     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, CameraErrorCode::SUCCESS,
1471         "CaptureSession::GetActiveVideoStabilizationMode camera deviceInfo is null");
1472     mode = OFF;
1473     bool isSupported = false;
1474     sptr<CameraDevice> cameraObj_;
1475     cameraObj_ = inputDeviceInfo;
1476     std::shared_ptr<Camera::CameraMetadata> metadata = cameraObj_->GetCachedMetadata();
1477     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
1478         "GetActiveVideoStabilizationMode camera metadata is null");
1479     camera_metadata_item_t item;
1480     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_VIDEO_STABILIZATION_MODE, &item);
1481     if (ret == CAM_META_SUCCESS) {
1482         auto itr = g_metaVideoStabModesMap_.find(static_cast<CameraVideoStabilizationMode>(item.data.u8[0]));
1483         if (itr != g_metaVideoStabModesMap_.end()) {
1484             mode = itr->second;
1485             isSupported = true;
1486         }
1487     }
1488     CHECK_PRINT_ELOG(!isSupported || ret != CAM_META_SUCCESS,
1489         "CaptureSession::GetActiveVideoStabilizationMode Failed with return code %{public}d", ret);
1490     return CameraErrorCode::SUCCESS;
1491 }
1492 
SetVideoStabilizationMode(VideoStabilizationMode stabilizationMode)1493 int32_t CaptureSession::SetVideoStabilizationMode(VideoStabilizationMode stabilizationMode)
1494 {
1495     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
1496         "CaptureSession::SetVideoStabilizationMode Session is not Commited");
1497     if ((!CameraSecurity::CheckSystemApp()) && (stabilizationMode == VideoStabilizationMode::HIGH)) {
1498         stabilizationMode = VideoStabilizationMode::AUTO;
1499     }
1500     CHECK_RETURN_RET(!IsVideoStabilizationModeSupported(stabilizationMode),
1501         CameraErrorCode::OPERATION_NOT_ALLOWED);
1502     auto itr = g_fwkVideoStabModesMap_.find(stabilizationMode);
1503     // LCOV_EXCL_START
1504     if ((itr == g_fwkVideoStabModesMap_.end())) {
1505         MEDIA_ERR_LOG("CaptureSession::SetVideoStabilizationMode Mode: %{public}d not supported", stabilizationMode);
1506         stabilizationMode = OFF;
1507     }
1508     // LCOV_EXCL_STOP
1509 
1510     uint32_t count = 1;
1511     uint8_t stabilizationMode_ = stabilizationMode;
1512 
1513     this->LockForControl();
1514     MEDIA_DEBUG_LOG("CaptureSession::SetVideoStabilizingMode StabilizationMode : %{public}d", stabilizationMode_);
1515     if (!(this->changedMetadata_->addEntry(OHOS_CONTROL_VIDEO_STABILIZATION_MODE, &stabilizationMode_, count))) {
1516         MEDIA_DEBUG_LOG("CaptureSession::SetVideoStabilizingMode Failed to set video stabilization mode");
1517     } else {
1518         wptr<CaptureSession> weakThis(this);
1519         AddFunctionToMap(std::to_string(OHOS_CONTROL_VIDEO_STABILIZATION_MODE), [weakThis, stabilizationMode]() {
1520             auto sharedThis = weakThis.promote();
1521             CHECK_RETURN_ELOG(!sharedThis, "SetVideoStabilizationMode session is nullptr");
1522             int32_t retCode = sharedThis->SetVideoStabilizationMode(stabilizationMode);
1523             CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS,
1524                           sharedThis->SetDeviceCapabilityChangeStatus(true));
1525         });
1526     }
1527     int32_t errCode = this->UnlockForControl();
1528     CHECK_PRINT_DLOG(errCode != CameraErrorCode::SUCCESS,
1529         "CaptureSession::SetVideoStabilizingMode Failed to set video stabilization mode");
1530     return CameraErrorCode::SUCCESS;
1531 }
1532 
IsVideoStabilizationModeSupported(VideoStabilizationMode stabilizationMode)1533 bool CaptureSession::IsVideoStabilizationModeSupported(VideoStabilizationMode stabilizationMode)
1534 {
1535     CHECK_RETURN_RET((!CameraSecurity::CheckSystemApp()) && (stabilizationMode == VideoStabilizationMode::HIGH),
1536         false);
1537     std::vector<VideoStabilizationMode> stabilizationModes = GetSupportedStabilizationMode();
1538     if (std::find(stabilizationModes.begin(), stabilizationModes.end(), stabilizationMode) !=
1539         stabilizationModes.end()) {
1540         return true;
1541     }
1542     return false;
1543 }
1544 
IsVideoStabilizationModeSupported(VideoStabilizationMode stabilizationMode,bool & isSupported)1545 int32_t CaptureSession::IsVideoStabilizationModeSupported(VideoStabilizationMode stabilizationMode, bool& isSupported)
1546 {
1547     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
1548         "CaptureSession::IsVideoStabilizationModeSupported Session is not Commited");
1549     isSupported = false;
1550     std::vector<VideoStabilizationMode> stabilizationModes = GetSupportedStabilizationMode();
1551     if (std::find(stabilizationModes.begin(), stabilizationModes.end(), stabilizationMode) !=
1552         stabilizationModes.end()) {
1553         isSupported = true;
1554         return CameraErrorCode::SUCCESS;
1555     }
1556     return CameraErrorCode::SUCCESS;
1557 }
1558 
GetSupportedStabilizationMode()1559 std::vector<VideoStabilizationMode> CaptureSession::GetSupportedStabilizationMode()
1560 {
1561     std::vector<VideoStabilizationMode> stabilizationModes;
1562     GetSupportedStabilizationMode(stabilizationModes);
1563     return stabilizationModes;
1564 }
1565 
GetSupportedStabilizationMode(std::vector<VideoStabilizationMode> & stabilizationModes)1566 int32_t CaptureSession::GetSupportedStabilizationMode(std::vector<VideoStabilizationMode>& stabilizationModes)
1567 {
1568     stabilizationModes.clear();
1569     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
1570         "CaptureSession::GetSupportedStabilizationMode Session is not Commited");
1571     auto inputDevice = GetInputDevice();
1572     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
1573         "CaptureSession::GetSupportedStabilizationMode camera device is null");
1574     sptr<CameraDevice> cameraDevNow = inputDevice->GetCameraDeviceInfo();
1575     if (cameraDevNow != nullptr && cameraDevNow->isConcurrentLimted_ == 1) {
1576         // LCOV_EXCL_START
1577         for (int i = 0; i < cameraDevNow->limtedCapabilitySave_.stabilizationmodes.count; i++) {
1578             auto num = static_cast<CameraVideoStabilizationMode>(cameraDevNow->limtedCapabilitySave_.
1579                 stabilizationmodes.mode[i]);
1580             auto itr = g_metaVideoStabModesMap_.find(num);
1581             if (itr != g_metaVideoStabModesMap_.end()) {
1582                 stabilizationModes.emplace_back(itr->second);
1583             }
1584         }
1585         return CameraErrorCode::SUCCESS;
1586         // LCOV_EXCL_STOP
1587     }
1588     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
1589     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
1590         "GetSupportedStabilizationMode camera metadata is null");
1591     camera_metadata_item_t item;
1592     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_VIDEO_STABILIZATION_MODES, &item);
1593     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
1594         "CaptureSession::GetSupporteStabilizationModes Failed with return code %{public}d", ret);
1595 
1596     for (uint32_t i = 0; i < item.count; i++) {
1597         auto itr = g_metaVideoStabModesMap_.find(static_cast<CameraVideoStabilizationMode>(item.data.u8[i]));
1598         CHECK_EXECUTE(itr != g_metaVideoStabModesMap_.end(), stabilizationModes.emplace_back(itr->second));
1599     }
1600     return CameraErrorCode::SUCCESS;
1601 }
1602 
IsExposureModeSupported(ExposureMode exposureMode)1603 bool CaptureSession::IsExposureModeSupported(ExposureMode exposureMode)
1604 {
1605     bool isSupported = false;
1606     IsExposureModeSupported(exposureMode, isSupported);
1607     return isSupported;
1608 }
1609 
IsExposureModeSupported(ExposureMode exposureMode,bool & isSupported)1610 int32_t CaptureSession::IsExposureModeSupported(ExposureMode exposureMode, bool& isSupported)
1611 {
1612     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
1613         "CaptureSession::IsExposureModeSupported Session is not Commited");
1614     std::vector<ExposureMode> vecSupportedExposureModeList;
1615     vecSupportedExposureModeList = this->GetSupportedExposureModes();
1616     if (find(vecSupportedExposureModeList.begin(), vecSupportedExposureModeList.end(), exposureMode) !=
1617         vecSupportedExposureModeList.end()) {
1618         isSupported = true;
1619         return CameraErrorCode::SUCCESS;
1620     }
1621     isSupported = false;
1622     return CameraErrorCode::SUCCESS;
1623 }
1624 
GetSupportedExposureModes()1625 std::vector<ExposureMode> CaptureSession::GetSupportedExposureModes()
1626 {
1627     std::vector<ExposureMode> supportedExposureModes;
1628     GetSupportedExposureModes(supportedExposureModes);
1629     return supportedExposureModes;
1630 }
1631 
GetSupportedExposureModes(std::vector<ExposureMode> & supportedExposureModes)1632 int32_t CaptureSession::GetSupportedExposureModes(std::vector<ExposureMode>& supportedExposureModes)
1633 {
1634     supportedExposureModes.clear();
1635     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
1636         "CaptureSession::GetSupportedExposureModes Session is not Commited");
1637     auto inputDevice = GetInputDevice();
1638     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
1639         "CaptureSession::GetSupportedExposureModes camera device is null");
1640     sptr<CameraDevice> cameraDevNow = inputDevice->GetCameraDeviceInfo();
1641     if (cameraDevNow != nullptr && cameraDevNow->isConcurrentLimted_ == 1) {
1642         // LCOV_EXCL_START
1643         for (int i = 0; i < cameraDevNow->limtedCapabilitySave_.exposuremodes.count; i++) {
1644             camera_exposure_mode_enum_t num =
1645                 static_cast<camera_exposure_mode_enum_t>(cameraDevNow->limtedCapabilitySave_.exposuremodes.mode[i]);
1646             auto itr = g_metaExposureModeMap_.find(num);
1647             if (itr != g_metaExposureModeMap_.end()) {
1648                 supportedExposureModes.emplace_back(itr->second);
1649             }
1650         }
1651         return CameraErrorCode::SUCCESS;
1652         // LCOV_EXCL_STOP
1653     }
1654     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
1655     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
1656         "GetSupportedExposureModes camera metadata is null");
1657     camera_metadata_item_t item;
1658     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_EXPOSURE_MODES, &item);
1659     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
1660         "CaptureSession::GetSupportedExposureModes Failed with return code %{public}d", ret);
1661 
1662     for (uint32_t i = 0; i < item.count; i++) {
1663         auto itr = g_metaExposureModeMap_.find(static_cast<camera_exposure_mode_enum_t>(item.data.u8[i]));
1664         CHECK_EXECUTE(itr != g_metaExposureModeMap_.end(), supportedExposureModes.emplace_back(itr->second));
1665     }
1666     return CameraErrorCode::SUCCESS;
1667 }
1668 
SetExposureMode(ExposureMode exposureMode)1669 int32_t CaptureSession::SetExposureMode(ExposureMode exposureMode)
1670 {
1671     CAMERA_SYNC_TRACE;
1672     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
1673         "CaptureSession::SetExposureMode Session is not Commited");
1674 
1675     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
1676         "CaptureSession::SetExposureMode Need to call LockForControl() before setting camera properties");
1677     CHECK_RETURN_RET(!IsExposureModeSupported(exposureMode), CameraErrorCode::OPERATION_NOT_ALLOWED);
1678     // LCOV_EXCL_START
1679     uint8_t exposure = g_fwkExposureModeMap_.at(EXPOSURE_MODE_LOCKED);
1680     auto itr = g_fwkExposureModeMap_.find(exposureMode);
1681     if (itr == g_fwkExposureModeMap_.end()) {
1682         MEDIA_ERR_LOG("CaptureSession::SetExposureMode Unknown exposure mode");
1683     } else {
1684         exposure = itr->second;
1685     }
1686     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_EXPOSURE_MODE, &exposure, 1);
1687     wptr<CaptureSession> weakThis(this);
1688     CHECK_EXECUTE(status, AddFunctionToMap(std::to_string(OHOS_CONTROL_EXPOSURE_MODE), [weakThis, exposureMode]() {
1689         auto sharedThis = weakThis.promote();
1690         CHECK_RETURN_ELOG(!sharedThis, "SetExposureMode session is nullptr");
1691         sharedThis->LockForControl();
1692         int32_t retCode = sharedThis->SetExposureMode(exposureMode);
1693         sharedThis->UnlockForControl();
1694         CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS, sharedThis->SetDeviceCapabilityChangeStatus(true));
1695     }));
1696     CHECK_PRINT_ELOG(!status, "CaptureSession::SetExposureMode Failed to set exposure mode");
1697 
1698     return CameraErrorCode::SUCCESS;
1699     // LCOV_EXCL_STOP
1700 }
1701 
GetExposureMode()1702 ExposureMode CaptureSession::GetExposureMode()
1703 {
1704     ExposureMode exposureMode;
1705     GetExposureMode(exposureMode);
1706     return exposureMode;
1707 }
1708 
GetExposureMode(ExposureMode & exposureMode)1709 int32_t CaptureSession::GetExposureMode(ExposureMode& exposureMode)
1710 {
1711     exposureMode = EXPOSURE_MODE_UNSUPPORTED;
1712     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
1713         "CaptureSession::GetExposureMode Session is not Commited");
1714     auto inputDevice = GetInputDevice();
1715     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
1716         "CaptureSession::GetExposureMode camera device is null");
1717     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
1718     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
1719         "GetExposureMode camera metadata is null");
1720     camera_metadata_item_t item;
1721     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_EXPOSURE_MODE, &item);
1722     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
1723         "CaptureSession::GetExposureMode Failed with return code %{public}d", ret);
1724     // LCOV_EXCL_START
1725     auto itr = g_metaExposureModeMap_.find(static_cast<camera_exposure_mode_enum_t>(item.data.u8[0]));
1726     if (itr != g_metaExposureModeMap_.end()) {
1727         exposureMode = itr->second;
1728         return CameraErrorCode::SUCCESS;
1729     }
1730     return CameraErrorCode::SUCCESS;
1731     // LCOV_EXCL_STOP
1732 }
1733 
SetMeteringPoint(Point exposurePoint)1734 int32_t CaptureSession::SetMeteringPoint(Point exposurePoint)
1735 {
1736     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
1737         "CaptureSession::SetMeteringPoint Session is not Commited");
1738     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
1739         "CaptureSession::SetExposurePoint Need to call LockForControl() before setting camera properties");
1740     Point exposureVerifyPoint = VerifyFocusCorrectness(exposurePoint);
1741     Point unifyExposurePoint = CoordinateTransform(exposureVerifyPoint);
1742     std::vector<float> exposureArea = { unifyExposurePoint.x, unifyExposurePoint.y };
1743     bool status = AddOrUpdateMetadata(
1744         changedMetadata_, OHOS_CONTROL_AE_REGIONS, exposureArea.data(), exposureArea.size());
1745     wptr<CaptureSession> weakThis(this);
1746     CHECK_EXECUTE(status, AddFunctionToMap(std::to_string(OHOS_CONTROL_AE_REGIONS), [weakThis, exposurePoint]() {
1747         auto sharedThis = weakThis.promote();
1748         CHECK_RETURN_ELOG(!sharedThis, "SetMeteringPoint session is nullptr");
1749         sharedThis->LockForControl();
1750         int32_t retCode = sharedThis->SetMeteringPoint(exposurePoint);
1751         sharedThis->UnlockForControl();
1752         CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS, sharedThis->SetDeviceCapabilityChangeStatus(true));
1753     }));
1754     CHECK_PRINT_ELOG(!status, "CaptureSession::SetExposurePoint Failed to set exposure Area");
1755     return CameraErrorCode::SUCCESS;
1756 }
1757 
GetMeteringPoint()1758 Point CaptureSession::GetMeteringPoint()
1759 {
1760     Point exposurePoint;
1761     GetMeteringPoint(exposurePoint);
1762     return exposurePoint;
1763 }
1764 
GetMeteringPoint(Point & exposurePoint)1765 int32_t CaptureSession::GetMeteringPoint(Point& exposurePoint)
1766 {
1767     exposurePoint.x = 0;
1768     exposurePoint.y = 0;
1769     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
1770         "CaptureSession::GetMeteringPoint Session is not Commited");
1771     auto inputDevice = GetInputDevice();
1772     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
1773         "CaptureSession::GetMeteringPoint camera device is null");
1774     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
1775     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
1776         "GetMeteringPoint camera metadata is null");
1777     camera_metadata_item_t item;
1778     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_AE_REGIONS, &item);
1779     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
1780         "CaptureSession::GetExposurePoint Failed with return code %{public}d", ret);
1781     // LCOV_EXCL_START
1782     exposurePoint.x = item.data.f[0];
1783     exposurePoint.y = item.data.f[1];
1784     exposurePoint = CoordinateTransform(exposurePoint);
1785     return CameraErrorCode::SUCCESS;
1786     // LCOV_EXCL_STOP
1787 }
1788 
GetExposureBiasRange()1789 std::vector<float> CaptureSession::GetExposureBiasRange()
1790 {
1791     std::vector<float> exposureBiasRange;
1792     GetExposureBiasRange(exposureBiasRange);
1793     return exposureBiasRange;
1794 }
1795 
GetExposureBiasRange(std::vector<float> & exposureBiasRange)1796 int32_t CaptureSession::GetExposureBiasRange(std::vector<float>& exposureBiasRange)
1797 {
1798     exposureBiasRange.clear();
1799     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
1800         "CaptureSession::GetExposureBiasRange Session is not Commited");
1801     auto inputDevice = GetInputDevice();
1802     CHECK_RETURN_RET_ELOG(!inputDevice, CameraErrorCode::SUCCESS,
1803         "CaptureSession::GetExposureBiasRange camera device is null");
1804     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
1805     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, CameraErrorCode::SUCCESS,
1806         "CaptureSession::GetExposureBiasRange camera deviceInfo is null");
1807     exposureBiasRange = inputDeviceInfo->GetExposureBiasRange();
1808     return CameraErrorCode::SUCCESS;
1809 }
1810 
SetExposureBias(float exposureValue)1811 int32_t CaptureSession::SetExposureBias(float exposureValue)
1812 {
1813     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
1814         "CaptureSession::SetExposureBias Session is not Commited");
1815     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
1816         "CaptureSession::SetExposureBias Need to call LockForControl() before setting camera properties");
1817     int32_t minIndex = 0;
1818     int32_t maxIndex = 1;
1819     MEDIA_DEBUG_LOG("CaptureSession::SetExposureValue exposure compensation: %{public}f", exposureValue);
1820     auto inputDevice = GetInputDevice();
1821     CHECK_RETURN_RET_ELOG(!inputDevice, CameraErrorCode::OPERATION_NOT_ALLOWED,
1822         "CaptureSession::SetExposureBias camera device is null");
1823     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
1824     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, CameraErrorCode::OPERATION_NOT_ALLOWED,
1825         "CaptureSession::SetExposureBias camera deviceInfo is null");
1826     std::vector<float> biasRange = inputDeviceInfo->GetExposureBiasRange();
1827     CHECK_RETURN_RET_ELOG(biasRange.empty(), CameraErrorCode::OPERATION_NOT_ALLOWED,
1828         "CaptureSession::SetExposureValue Bias range is empty");
1829     if (exposureValue < biasRange[minIndex]) {
1830         MEDIA_DEBUG_LOG("CaptureSession::SetExposureValue bias value:"
1831                         "%{public}f is lesser than minimum bias: %{public}f", exposureValue, biasRange[minIndex]);
1832         exposureValue = biasRange[minIndex];
1833     } else if (exposureValue > biasRange[maxIndex]) {
1834         MEDIA_DEBUG_LOG("CaptureSession::SetExposureValue bias value: "
1835                         "%{public}f is greater than maximum bias: %{public}f", exposureValue, biasRange[maxIndex]);
1836         exposureValue = biasRange[maxIndex];
1837     }
1838 
1839     int32_t exposureCompensation = CalculateExposureValue(exposureValue);
1840     bool status = AddOrUpdateMetadata(
1841         changedMetadata_, OHOS_CONTROL_AE_EXPOSURE_COMPENSATION, &exposureCompensation, 1);
1842     wptr<CaptureSession> weakThis(this);
1843     CHECK_EXECUTE(status, AddFunctionToMap(std::to_string(OHOS_CONTROL_AE_EXPOSURE_COMPENSATION),
1844         [weakThis, exposureValue]() {
1845             auto sharedThis = weakThis.promote();
1846             CHECK_RETURN_ELOG(!sharedThis, "SetExposureBias session is nullptr");
1847             sharedThis->LockForControl();
1848             int32_t retCode = sharedThis->SetExposureBias(exposureValue);
1849             sharedThis->UnlockForControl();
1850             CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS, sharedThis->SetDeviceCapabilityChangeStatus(true));
1851         }));
1852     CHECK_PRINT_ELOG(!status, "CaptureSession::SetExposureValue Failed to set exposure compensation");
1853     return CameraErrorCode::SUCCESS;
1854 }
1855 
GetExposureValue()1856 float CaptureSession::GetExposureValue()
1857 {
1858     float exposureValue;
1859     GetExposureValue(exposureValue);
1860     return exposureValue;
1861 }
1862 
GetExposureValue(float & exposureValue)1863 int32_t CaptureSession::GetExposureValue(float& exposureValue)
1864 {
1865     exposureValue = 0;
1866     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
1867         "CaptureSession::GetExposureValue Session is not Commited");
1868     auto inputDevice = GetInputDevice();
1869     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
1870         "CaptureSession::GetExposureValue camera device is null");
1871     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
1872     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
1873         "GetExposureValue camera metadata is null");
1874     camera_metadata_item_t item;
1875     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_AE_EXPOSURE_COMPENSATION, &item);
1876     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
1877         "CaptureSession::GetExposureValue Failed with return code %{public}d", ret);
1878     // LCOV_EXCL_START
1879     int32_t exposureCompensation = item.data.i32[0];
1880 
1881     ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_AE_COMPENSATION_STEP, &item);
1882     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, 0,
1883         "CaptureSession::GetExposureValue Failed with return code %{public}d", ret);
1884     int32_t stepNumerator = item.data.r->numerator;
1885     int32_t stepDenominator = item.data.r->denominator;
1886     if (stepDenominator == 0) {
1887         MEDIA_ERR_LOG("stepDenominator: %{public}d", stepDenominator);
1888     } else {
1889         float step = static_cast<float>(stepNumerator) / static_cast<float>(stepDenominator);
1890         exposureValue = step * exposureCompensation;
1891     }
1892     MEDIA_DEBUG_LOG("exposureValue: %{public}f", exposureValue);
1893     return CameraErrorCode::SUCCESS;
1894     // LCOV_EXCL_STOP
1895 }
1896 
SetExposureCallback(std::shared_ptr<ExposureCallback> exposureCallback)1897 void CaptureSession::SetExposureCallback(std::shared_ptr<ExposureCallback> exposureCallback)
1898 {
1899     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1900     exposureCallback_ = exposureCallback;
1901 }
1902 
ProcessAutoExposureUpdates(const std::shared_ptr<Camera::CameraMetadata> & result)1903 void CaptureSession::ProcessAutoExposureUpdates(const std::shared_ptr<Camera::CameraMetadata>& result)
1904 {
1905     camera_metadata_item_t item;
1906     common_metadata_header_t* metadata = result->get();
1907 
1908     int ret = Camera::FindCameraMetadataItem(metadata, OHOS_CONTROL_EXPOSURE_MODE, &item);
1909     CHECK_PRINT_DLOG(ret == CAM_META_SUCCESS, "exposure mode: %{public}d", item.data.u8[0]);
1910 
1911     ret = Camera::FindCameraMetadataItem(metadata, OHOS_CONTROL_EXPOSURE_STATE, &item);
1912     if (ret == CAM_META_SUCCESS) {
1913         // LCOV_EXCL_START
1914         MEDIA_INFO_LOG("Exposure state: %{public}d", item.data.u8[0]);
1915         std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1916         if (exposureCallback_ != nullptr) {
1917             auto itr = metaExposureStateMap_.find(static_cast<camera_exposure_state_t>(item.data.u8[0]));
1918             CHECK_EXECUTE(itr != metaExposureStateMap_.end(), exposureCallback_->OnExposureState(itr->second));
1919         }
1920         // LCOV_EXCL_STOP
1921     }
1922 }
1923 
GetSupportedFocusModes()1924 std::vector<FocusMode> CaptureSession::GetSupportedFocusModes()
1925 {
1926     std::vector<FocusMode> supportedFocusModes;
1927     GetSupportedFocusModes(supportedFocusModes);
1928     return supportedFocusModes;
1929 }
1930 
GetSupportedFocusModes(std::vector<FocusMode> & supportedFocusModes)1931 int32_t CaptureSession::GetSupportedFocusModes(std::vector<FocusMode>& supportedFocusModes)
1932 {
1933     supportedFocusModes.clear();
1934     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
1935         "CaptureSession::SetExposureBias Session is not Commited");
1936     auto inputDevice = GetInputDevice();
1937     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
1938         "CaptureSession::GetSupportedFocusModes camera device is null");
1939     sptr<CameraDevice> cameraDevNow = inputDevice->GetCameraDeviceInfo();
1940     if (cameraDevNow != nullptr && cameraDevNow->isConcurrentLimted_ == 1) {
1941         // LCOV_EXCL_START
1942         for (int i = 0; i < cameraDevNow->limtedCapabilitySave_.focusmodes.count; i++) {
1943             camera_focus_mode_enum_t num = static_cast<camera_focus_mode_enum_t>(cameraDevNow->
1944                 limtedCapabilitySave_.focusmodes.mode[i]);
1945             auto itr = g_metaFocusModeMap_.find(static_cast<camera_focus_mode_enum_t>(num));
1946             if (itr != g_metaFocusModeMap_.end()) {
1947                 supportedFocusModes.emplace_back(itr->second);
1948             }
1949         }
1950         return CameraErrorCode::SUCCESS;
1951         // LCOV_EXCL_STOP
1952     }
1953     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
1954     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
1955         "GetSupportedFocusModes camera metadata is null");
1956     camera_metadata_item_t item;
1957     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_FOCUS_MODES, &item);
1958     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
1959         "CaptureSession::GetSupportedFocusModes Failed with return code %{public}d", ret);
1960     for (uint32_t i = 0; i < item.count; i++) {
1961         auto itr = g_metaFocusModeMap_.find(static_cast<camera_focus_mode_enum_t>(item.data.u8[i]));
1962         CHECK_EXECUTE(itr != g_metaFocusModeMap_.end(), supportedFocusModes.emplace_back(itr->second));
1963     }
1964     return CameraErrorCode::SUCCESS;
1965 }
1966 
SetFocusCallback(std::shared_ptr<FocusCallback> focusCallback)1967 void CaptureSession::SetFocusCallback(std::shared_ptr<FocusCallback> focusCallback)
1968 {
1969     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
1970     focusCallback_ = focusCallback;
1971     return;
1972 }
1973 
IsFocusModeSupported(FocusMode focusMode)1974 bool CaptureSession::IsFocusModeSupported(FocusMode focusMode)
1975 {
1976     bool isSupported = false;
1977     IsFocusModeSupported(focusMode, isSupported);
1978     return isSupported;
1979 }
1980 
IsFocusModeSupported(FocusMode focusMode,bool & isSupported)1981 int32_t CaptureSession::IsFocusModeSupported(FocusMode focusMode, bool& isSupported)
1982 {
1983     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
1984         "CaptureSession::SetExposureBias Session is not Commited");
1985     std::vector<FocusMode> vecSupportedFocusModeList;
1986     vecSupportedFocusModeList = this->GetSupportedFocusModes();
1987     if (find(vecSupportedFocusModeList.begin(), vecSupportedFocusModeList.end(), focusMode) !=
1988         vecSupportedFocusModeList.end()) {
1989         isSupported = true;
1990         return CameraErrorCode::SUCCESS;
1991     }
1992     isSupported = false;
1993     return CameraErrorCode::SUCCESS;
1994 }
1995 
SetFocusMode(FocusMode focusMode)1996 int32_t CaptureSession::SetFocusMode(FocusMode focusMode)
1997 {
1998     CAMERA_SYNC_TRACE;
1999     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2000         "CaptureSession::SetFocusMode Session is not Commited");
2001     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
2002         "CaptureSession::SetFocusMode Need to call LockForControl() before setting camera properties");
2003     CHECK_RETURN_RET(!IsFocusModeSupported(focusMode), CameraErrorCode::OPERATION_NOT_ALLOWED);
2004     uint8_t focus = FOCUS_MODE_LOCKED;
2005     auto itr = g_fwkFocusModeMap_.find(focusMode);
2006     if (itr == g_fwkFocusModeMap_.end()) {
2007         MEDIA_ERR_LOG("CaptureSession::SetFocusMode Unknown exposure mode");
2008     } else {
2009         focus = itr->second;
2010     }
2011     MEDIA_DEBUG_LOG("CaptureSession::SetFocusMode Focus mode: %{public}d", focusMode);
2012     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_FOCUS_MODE, &focus, 1);
2013     wptr<CaptureSession> weakThis(this);
2014     CHECK_EXECUTE(status, AddFunctionToMap(std::to_string(OHOS_CONTROL_FOCUS_MODE), [weakThis, focusMode]() {
2015         auto sharedThis = weakThis.promote();
2016         CHECK_RETURN_ELOG(!sharedThis, "SetFocusMode session is nullptr");
2017         sharedThis->LockForControl();
2018         int32_t retCode = sharedThis->SetFocusMode(focusMode);
2019         sharedThis->UnlockForControl();
2020         CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS, sharedThis->SetDeviceCapabilityChangeStatus(true));
2021     }));
2022     CHECK_PRINT_ELOG(!status, "CaptureSession::SetFocusMode Failed to set focus mode");
2023     return CameraErrorCode::SUCCESS;
2024 }
2025 
GetFocusMode()2026 FocusMode CaptureSession::GetFocusMode()
2027 {
2028     FocusMode focusMode = FOCUS_MODE_MANUAL;
2029     GetFocusMode(focusMode);
2030     return focusMode;
2031 }
2032 
GetFocusMode(FocusMode & focusMode)2033 int32_t CaptureSession::GetFocusMode(FocusMode& focusMode)
2034 {
2035     focusMode = FOCUS_MODE_MANUAL;
2036     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2037         "CaptureSession::GetFocusMode Session is not Commited");
2038     auto inputDevice = GetInputDevice();
2039     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
2040         "CaptureSession::GetFocusMode camera device is null");
2041     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
2042     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
2043         "GetFocusMode camera metadata is null");
2044     camera_metadata_item_t item;
2045     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_FOCUS_MODE, &item);
2046     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
2047         "CaptureSession::GetFocusMode Failed with return code %{public}d", ret);
2048     auto itr = g_metaFocusModeMap_.find(static_cast<camera_focus_mode_enum_t>(item.data.u8[0]));
2049     if (itr != g_metaFocusModeMap_.end()) {
2050         focusMode = itr->second;
2051         return CameraErrorCode::SUCCESS;
2052     }
2053     return CameraErrorCode::SUCCESS;
2054 }
2055 
SetFocusPoint(Point focusPoint)2056 int32_t CaptureSession::SetFocusPoint(Point focusPoint)
2057 {
2058     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2059         "CaptureSession::SetFocusPoint Session is not Commited");
2060     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
2061         "CaptureSession::SetFocusPoint Need to call LockForControl() before setting camera properties");
2062     FocusMode focusMode;
2063     GetFocusMode(focusMode);
2064     CHECK_RETURN_RET_ELOG(focusMode == FOCUS_MODE_CONTINUOUS_AUTO, CameraErrorCode::SUCCESS,
2065         "The current mode does not support setting the focus point.");
2066     Point focusVerifyPoint = VerifyFocusCorrectness(focusPoint);
2067     Point unifyFocusPoint = CoordinateTransform(focusVerifyPoint);
2068     std::vector<float> focusArea = { unifyFocusPoint.x, unifyFocusPoint.y };
2069     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_AF_REGIONS, focusArea.data(), focusArea.size());
2070     wptr<CaptureSession> weakThis(this);
2071     CHECK_EXECUTE(status, AddFunctionToMap(std::to_string(OHOS_CONTROL_AF_REGIONS), [weakThis, focusPoint]() {
2072         auto sharedThis = weakThis.promote();
2073         CHECK_RETURN_ELOG(!sharedThis, "SetFocusPoint session is nullptr");
2074         sharedThis->LockForControl();
2075         int32_t retCode = sharedThis->SetFocusPoint(focusPoint);
2076         sharedThis->UnlockForControl();
2077         CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS, sharedThis->SetDeviceCapabilityChangeStatus(true));
2078     }));
2079     CHECK_PRINT_ELOG(!status, "CaptureSession::SetFocusPoint Failed to set Focus Area");
2080     return CameraErrorCode::SUCCESS;
2081 }
2082 
CoordinateTransform(Point point)2083 Point CaptureSession::CoordinateTransform(Point point)
2084 {
2085     MEDIA_DEBUG_LOG("CaptureSession::CoordinateTransform begin x: %{public}f, y: %{public}f", point.x, point.y);
2086     Point unifyPoint = point;
2087     auto inputDevice = GetInputDevice();
2088     CHECK_RETURN_RET_ELOG(!inputDevice, unifyPoint, "CaptureSession::CoordinateTransform cameraInput is nullptr");
2089     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
2090     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, unifyPoint,
2091         "CaptureSession::CoordinateTransform cameraInputInfo is nullptr");
2092     if (inputDeviceInfo->GetPosition() == CAMERA_POSITION_FRONT) {
2093         unifyPoint.x = 1 - unifyPoint.x; // flip horizontally
2094     }
2095     MEDIA_DEBUG_LOG("CaptureSession::CoordinateTransform end x: %{public}f, y: %{public}f", unifyPoint.x, unifyPoint.y);
2096     return unifyPoint;
2097 }
2098 
VerifyFocusCorrectness(Point point)2099 Point CaptureSession::VerifyFocusCorrectness(Point point)
2100 {
2101     MEDIA_DEBUG_LOG("CaptureSession::VerifyFocusCorrectness begin x: %{public}f, y: %{public}f", point.x, point.y);
2102     float minPoint = 0.0000001;
2103     float maxPoint = 1;
2104     Point VerifyPoint = point;
2105     if (VerifyPoint.x <= minPoint) {
2106         VerifyPoint.x = minPoint;
2107     } else if (VerifyPoint.x > maxPoint) {
2108         VerifyPoint.x = maxPoint;
2109     }
2110     if (VerifyPoint.y <= minPoint) {
2111         VerifyPoint.y = minPoint;
2112     } else if (VerifyPoint.y > maxPoint) {
2113         VerifyPoint.y = maxPoint;
2114     }
2115     MEDIA_DEBUG_LOG(
2116         "CaptureSession::VerifyFocusCorrectness end x: %{public}f, y: %{public}f", VerifyPoint.x, VerifyPoint.y);
2117     return VerifyPoint;
2118 }
2119 
GetFocusPoint()2120 Point CaptureSession::GetFocusPoint()
2121 {
2122     Point focusPoint = { 0, 0 };
2123     GetFocusPoint(focusPoint);
2124     return focusPoint;
2125 }
2126 
GetFocusPoint(Point & focusPoint)2127 int32_t CaptureSession::GetFocusPoint(Point& focusPoint)
2128 {
2129     focusPoint.x = 0;
2130     focusPoint.y = 0;
2131     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2132         "CaptureSession::GetFocusPoint Session is not Commited");
2133     auto inputDevice = GetInputDevice();
2134     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
2135         "CaptureSession::GetFocusPoint camera device is null");
2136     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
2137     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
2138         "GetFocusPoint camera metadata is null");
2139     camera_metadata_item_t item;
2140     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_AF_REGIONS, &item);
2141     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
2142         "CaptureSession::GetFocusPoint Failed with return code %{public}d", ret);
2143     // LCOV_EXCL_START
2144     focusPoint.x = item.data.f[0];
2145     focusPoint.y = item.data.f[1];
2146     focusPoint = CoordinateTransform(focusPoint);
2147     return CameraErrorCode::SUCCESS;
2148     // LCOV_EXCL_STOP
2149 }
2150 
GetFocalLength()2151 float CaptureSession::GetFocalLength()
2152 {
2153     float focalLength = 0;
2154     GetFocalLength(focalLength);
2155     return focalLength;
2156 }
2157 
GetFocalLength(float & focalLength)2158 int32_t CaptureSession::GetFocalLength(float& focalLength)
2159 {
2160     focalLength = 0;
2161     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2162         "CaptureSession::GetFocalLength Session is not Commited");
2163     auto inputDevice = GetInputDevice();
2164     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
2165         "CaptureSession::GetFocalLength camera device is null");
2166     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
2167     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
2168         "GetFocalLength camera metadata is null");
2169     camera_metadata_item_t item;
2170     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_FOCAL_LENGTH, &item);
2171     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
2172         "CaptureSession::GetFocalLength Failed with return code %{public}d", ret);
2173     focalLength = static_cast<float>(item.data.f[0]);
2174     return CameraErrorCode::SUCCESS;
2175 }
2176 
ProcessAutoFocusUpdates(const std::shared_ptr<Camera::CameraMetadata> & result)2177 void CaptureSession::ProcessAutoFocusUpdates(const std::shared_ptr<Camera::CameraMetadata>& result)
2178 {
2179     camera_metadata_item_t item;
2180     common_metadata_header_t* metadata = result->get();
2181     int ret = Camera::FindCameraMetadataItem(metadata, OHOS_CONTROL_FOCUS_MODE, &item);
2182     CHECK_RETURN_ELOG(ret != CAM_META_SUCCESS, "Camera not support Focus mode");
2183     MEDIA_DEBUG_LOG("Focus mode: %{public}d", item.data.u8[0]);
2184     auto it = g_metaFocusModeMap_.find(static_cast<camera_focus_mode_enum_t>(item.data.u8[0]));
2185     CHECK_RETURN_ELOG(it == g_metaFocusModeMap_.end(), "Focus mode not support");
2186     CHECK_EXECUTE(CameraSecurity::CheckSystemApp(), ProcessFocusDistanceUpdates(result));
2187     // continuous focus mode do not callback focusStateChange
2188     CHECK_RETURN((it->second != FOCUS_MODE_AUTO) && (it->second != FOCUS_MODE_CONTINUOUS_AUTO));
2189     // LCOV_EXCL_START
2190     ret = Camera::FindCameraMetadataItem(metadata, OHOS_CONTROL_FOCUS_STATE, &item);
2191     if (ret == CAM_META_SUCCESS) {
2192         MEDIA_DEBUG_LOG("Focus state: %{public}d", item.data.u8[0]);
2193         std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
2194         if (focusCallback_ != nullptr) {
2195             auto itr = metaFocusStateMap_.find(static_cast<camera_focus_state_t>(item.data.u8[0]));
2196             if (itr != metaFocusStateMap_.end() && itr->second != focusCallback_->currentState) {
2197                 focusCallback_->OnFocusState(itr->second);
2198                 focusCallback_->currentState = itr->second;
2199             }
2200         }
2201     }
2202     // LCOV_EXCL_STOP
2203 }
2204 
ProcessSnapshotDurationUpdates(const uint64_t timestamp,const std::shared_ptr<OHOS::Camera::CameraMetadata> & result)2205 void CaptureSession::ProcessSnapshotDurationUpdates(const uint64_t timestamp,
2206     const std::shared_ptr<OHOS::Camera::CameraMetadata> &result)
2207 {
2208     MEDIA_DEBUG_LOG("Entry ProcessSnapShotDurationUpdates");
2209     if (photoOutput_ != nullptr) {
2210         // LCOV_EXCL_START
2211         camera_metadata_item_t metadataItem;
2212         common_metadata_header_t* metadata = result->get();
2213         int ret = Camera::FindCameraMetadataItem(metadata, OHOS_CAMERA_CUSTOM_SNAPSHOT_DURATION, &metadataItem);
2214         CHECK_RETURN(ret != CAM_META_SUCCESS || metadataItem.count <= 0);
2215         const int32_t duration = static_cast<int32_t>(metadataItem.data.ui32[0]);
2216         CHECK_EXECUTE(duration != prevDuration_.load(),
2217             ((sptr<PhotoOutput> &)photoOutput_)->ProcessSnapshotDurationUpdates(duration));
2218         prevDuration_ = duration;
2219         // LCOV_EXCL_STOP
2220     }
2221 }
2222 
ProcessEffectSuggestionTypeUpdates(const std::shared_ptr<OHOS::Camera::CameraMetadata> & result)2223 void CaptureSession::ProcessEffectSuggestionTypeUpdates(const std::shared_ptr<OHOS::Camera::CameraMetadata> &result)
2224     __attribute__((no_sanitize("cfi")))
2225 {
2226     camera_metadata_item_t item;
2227     common_metadata_header_t* metadata = result->get();
2228     int ret = Camera::FindCameraMetadataItem(metadata, OHOS_CAMERA_EFFECT_SUGGESTION_TYPE, &item);
2229     CHECK_RETURN(ret != CAM_META_SUCCESS);
2230     MEDIA_DEBUG_LOG("ProcessEffectSuggestionTypeUpdates EffectSuggestionType: %{public}d", item.data.u8[0]);
2231     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
2232     if (effectSuggestionCallback_ != nullptr) {
2233         auto itr = metaEffectSuggestionTypeMap_.find(static_cast<CameraEffectSuggestionType>(item.data.u8[0]));
2234         if (itr != metaEffectSuggestionTypeMap_.end()) {
2235             EffectSuggestionType type = itr->second;
2236             if (!effectSuggestionCallback_->isFirstReport && type == effectSuggestionCallback_->currentType) {
2237                 MEDIA_DEBUG_LOG("EffectSuggestion type: no change");
2238                 return;
2239             }
2240             effectSuggestionCallback_->isFirstReport = false;
2241             effectSuggestionCallback_->currentType = type;
2242             effectSuggestionCallback_->OnEffectSuggestionChange(type);
2243         }
2244     }
2245 }
2246 
ProcessAREngineUpdates(const uint64_t timestamp,const std::shared_ptr<OHOS::Camera::CameraMetadata> & result)2247 void CaptureSession::ProcessAREngineUpdates(const uint64_t timestamp,
2248     const std::shared_ptr<OHOS::Camera::CameraMetadata> &result) __attribute__((no_sanitize("cfi")))
2249 {
2250     camera_metadata_item_t item;
2251     common_metadata_header_t* metadata = result->get();
2252     ARStatusInfo arStatusInfo;
2253 
2254     int ret = Camera::FindCameraMetadataItem(metadata, HAL_CUSTOM_LASER_DATA, &item);
2255     if (ret == CAM_META_SUCCESS) {
2256         // LCOV_EXCL_START
2257         std::vector<int32_t> laserData;
2258         for (uint32_t i = 0; i < item.count; i++) {
2259             laserData.emplace_back(item.data.i32[i]);
2260         }
2261         arStatusInfo.laserData = laserData;
2262         // LCOV_EXCL_STOP
2263     }
2264 
2265     ret = Camera::FindCameraMetadataItem(metadata, HAL_CUSTOM_LENS_FOCUS_DISTANCE, &item);
2266     CHECK_EXECUTE(ret == CAM_META_SUCCESS, arStatusInfo.lensFocusDistance = item.data.f[0]);
2267 
2268     ret = Camera::FindCameraMetadataItem(metadata, HAL_CUSTOM_SENSOR_SENSITIVITY, &item);
2269     CHECK_EXECUTE(ret == CAM_META_SUCCESS, arStatusInfo.sensorSensitivity = item.data.i32[0]);
2270 
2271     ret = Camera::FindCameraMetadataItem(metadata, OHOS_STATUS_SENSOR_EXPOSURE_TIME, &item);
2272     if (ret == CAM_META_SUCCESS) {
2273         int32_t numerator = item.data.r->numerator;
2274         int32_t denominator = item.data.r->denominator;
2275         MEDIA_DEBUG_LOG("SensorExposureTime: %{public}d/%{public}d", numerator, denominator);
2276         CHECK_RETURN_ELOG(denominator == 0, "ProcessSensorExposureTimeChange error! divide by zero");
2277         uint32_t value = static_cast<uint32_t>(numerator / (denominator/1000000));
2278         MEDIA_DEBUG_LOG("SensorExposureTime: %{public}u", value);
2279         arStatusInfo.exposureDurationValue = value;
2280     }
2281     // LCOV_EXCL_START
2282     ret = Camera::FindCameraMetadataItem(metadata, OHOS_SENSOR_INFO_TIMESTAMP, &item);
2283     if (ret == CAM_META_SUCCESS) {
2284         arStatusInfo.timestamp = item.data.i64[0];
2285     }
2286 
2287     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
2288     CHECK_EXECUTE(arCallback_ != nullptr, arCallback_->OnResult(arStatusInfo));
2289     // LCOV_EXCL_STOP
2290 }
2291 
ProcessCallbacks(const uint64_t timestamp,const std::shared_ptr<OHOS::Camera::CameraMetadata> & result)2292 void CaptureSession::CaptureSessionMetadataResultProcessor::ProcessCallbacks(
2293     const uint64_t timestamp, const std::shared_ptr<OHOS::Camera::CameraMetadata>& result)
2294 {
2295     MEDIA_DEBUG_LOG("CaptureSession::CaptureSessionMetadataResultProcessor ProcessCallbacks");
2296     auto session = session_.promote();
2297     CHECK_RETURN_ELOG(session == nullptr,
2298         "CaptureSession::CaptureSessionMetadataResultProcessor ProcessCallbacks but session is null");
2299 
2300     session->OnResultReceived(result);
2301     session->ProcessAutoFocusUpdates(result);
2302     session->ProcessMacroStatusChange(result);
2303     session->ProcessMoonCaptureBoostStatusChange(result);
2304     session->ProcessLowLightBoostStatusChange(result);
2305     session->ProcessSnapshotDurationUpdates(timestamp, result);
2306     session->ProcessAREngineUpdates(timestamp, result);
2307     session->ProcessEffectSuggestionTypeUpdates(result);
2308     session->ProcessLcdFlashStatusUpdates(result);
2309     session->ProcessTripodStatusChange(result);
2310 }
2311 
GetSupportedFlashModes()2312 std::vector<FlashMode> CaptureSession::GetSupportedFlashModes()
2313 {
2314     std::vector<FlashMode> supportedFlashModes;
2315     GetSupportedFlashModes(supportedFlashModes);
2316     return supportedFlashModes;
2317 }
2318 
GetSupportedFlashModes(std::vector<FlashMode> & supportedFlashModes)2319 int32_t CaptureSession::GetSupportedFlashModes(std::vector<FlashMode>& supportedFlashModes)
2320 {
2321     supportedFlashModes.clear();
2322     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
2323         "CaptureSession::GetSupportedFlashModes Session is not Commited");
2324     auto inputDevice = GetInputDevice();
2325     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
2326         "CaptureSession::GetSupportedFlashModes camera device is null");
2327     sptr<CameraDevice> cameraDevNow = inputDevice->GetCameraDeviceInfo();
2328     if (cameraDevNow != nullptr && cameraDevNow->isConcurrentLimted_ == 1) {
2329         // LCOV_EXCL_START
2330         for (int i = 0; i < cameraDevNow->limtedCapabilitySave_.flashmodes.count; i++) {
2331             camera_flash_mode_enum_t num = static_cast<camera_flash_mode_enum_t>
2332                 (cameraDevNow->limtedCapabilitySave_.flashmodes.mode[i]);
2333             auto it = g_metaFlashModeMap_.find(static_cast<camera_flash_mode_enum_t>(num));
2334             if (it != g_metaFlashModeMap_.end()) {
2335                 supportedFlashModes.emplace_back(it->second);
2336             }
2337         }
2338         return CameraErrorCode::SUCCESS;
2339         // LCOV_EXCL_STOP
2340     }
2341     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
2342     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
2343         "GetSupportedFlashModes camera metadata is null");
2344     camera_metadata_item_t item;
2345     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_FLASH_MODES, &item);
2346     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
2347         "CaptureSession::GetSupportedFlashModes Failed with return code %{public}d", ret);
2348     g_transformValidData(item, g_metaFlashModeMap_, supportedFlashModes);
2349     return CameraErrorCode::SUCCESS;
2350 }
2351 
GetFlashMode()2352 FlashMode CaptureSession::GetFlashMode()
2353 {
2354     FlashMode flashMode = FLASH_MODE_CLOSE;
2355     GetFlashMode(flashMode);
2356     return flashMode;
2357 }
2358 
GetFlashMode(FlashMode & flashMode)2359 int32_t CaptureSession::GetFlashMode(FlashMode& flashMode)
2360 {
2361     flashMode = FLASH_MODE_CLOSE;
2362     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2363         "CaptureSession::GetFlashMode Session is not Commited");
2364     auto inputDevice = GetInputDevice();
2365     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
2366         "CaptureSession::GetFlashMode camera device is null");
2367     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
2368     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
2369         "GetFlashMode camera metadata is null");
2370     camera_metadata_item_t item;
2371     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_FLASH_MODE, &item);
2372     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
2373         "CaptureSession::GetFlashMode Failed with return code %{public}d", ret);
2374     // LCOV_EXCL_START
2375     auto itr = g_metaFlashModeMap_.find(static_cast<camera_flash_mode_enum_t>(item.data.u8[0]));
2376     if (itr != g_metaFlashModeMap_.end()) {
2377         flashMode = itr->second;
2378         return CameraErrorCode::SUCCESS;
2379     }
2380 
2381     return CameraErrorCode::SUCCESS;
2382     // LCOV_EXCL_STOP
2383 }
2384 
SetFlashMode(FlashMode flashMode)2385 int32_t CaptureSession::SetFlashMode(FlashMode flashMode)
2386 {
2387     CAMERA_SYNC_TRACE;
2388     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2389         "CaptureSession::SetFlashMode Session is not Commited");
2390     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
2391         "CaptureSession::SetFlashMode Need to call LockForControl() before setting camera properties");
2392     // flash for lightPainting
2393     // LCOV_EXCL_START
2394     if (GetMode() == SceneMode::LIGHT_PAINTING && flashMode == FlashMode::FLASH_MODE_OPEN) {
2395         uint8_t enableTrigger = 1;
2396         MEDIA_DEBUG_LOG("CaptureSession::TriggerLighting once.");
2397         bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_LIGHT_PAINTING_FLASH, &enableTrigger, 1);
2398         CHECK_RETURN_RET_ELOG(!status, CameraErrorCode::SERVICE_FATL_ERROR,
2399             "CaptureSession::TriggerLighting Failed to trigger lighting");
2400         return CameraErrorCode::SUCCESS;
2401     }
2402     CHECK_RETURN_RET(!IsFlashModeSupported(flashMode), CameraErrorCode::OPERATION_NOT_ALLOWED);
2403     uint8_t flash = g_fwkFlashModeMap_.at(FLASH_MODE_CLOSE);
2404     auto itr = g_fwkFlashModeMap_.find(flashMode);
2405     if (itr == g_fwkFlashModeMap_.end()) {
2406         MEDIA_ERR_LOG("CaptureSession::SetFlashMode Unknown exposure mode");
2407     } else {
2408         flash = itr->second;
2409     }
2410     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_FLASH_MODE, &flash, 1);
2411     CHECK_PRINT_ELOG(!status, "CaptureSession::SetFlashMode Failed to set flash mode");
2412     wptr<CaptureSession> weakThis(this);
2413     AddFunctionToMap(std::to_string(OHOS_CONTROL_FLASH_MODE), [weakThis, flashMode]() {
2414         auto sharedThis = weakThis.promote();
2415         CHECK_RETURN_ELOG(!sharedThis, "SetFlashMode session is nullptr");
2416         sharedThis->LockForControl();
2417         int32_t retCode = sharedThis->SetFlashMode(flashMode);
2418         sharedThis->UnlockForControl();
2419         CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS,
2420                       sharedThis->SetDeviceCapabilityChangeStatus(true));
2421     });
2422     return CameraErrorCode::SUCCESS;
2423     // LCOV_EXCL_STOP
2424 }
2425 
IsFlashModeSupported(FlashMode flashMode)2426 bool CaptureSession::IsFlashModeSupported(FlashMode flashMode)
2427 {
2428     bool isSupported = false;
2429     IsFlashModeSupported(flashMode, isSupported);
2430     return isSupported;
2431 }
2432 
IsFlashModeSupported(FlashMode flashMode,bool & isSupported)2433 int32_t CaptureSession::IsFlashModeSupported(FlashMode flashMode, bool& isSupported)
2434 {
2435     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2436         "CaptureSession::IsFlashModeSupported Session is not Commited");
2437     std::vector<FlashMode> vecSupportedFlashModeList;
2438     vecSupportedFlashModeList = this->GetSupportedFlashModes();
2439     if (find(vecSupportedFlashModeList.begin(), vecSupportedFlashModeList.end(), flashMode) !=
2440         vecSupportedFlashModeList.end()) {
2441         isSupported = true;
2442         return CameraErrorCode::SUCCESS;
2443     }
2444     isSupported = false;
2445     return CameraErrorCode::SUCCESS;
2446 }
2447 
HasFlash()2448 bool CaptureSession::HasFlash()
2449 {
2450     bool hasFlash = false;
2451     HasFlash(hasFlash);
2452     return hasFlash;
2453 }
2454 
HasFlash(bool & hasFlash)2455 int32_t CaptureSession::HasFlash(bool& hasFlash)
2456 {
2457     hasFlash = false;
2458     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2459         "CaptureSession::HasFlash Session is not Commited");
2460     std::vector<FlashMode> supportedFlashModeList = GetSupportedFlashModes();
2461     bool onlyHasCloseMode = supportedFlashModeList.size() == 1 && supportedFlashModeList[0] == FLASH_MODE_CLOSE;
2462     if (!supportedFlashModeList.empty() && !onlyHasCloseMode) {
2463         hasFlash = true;
2464     }
2465     return CameraErrorCode::SUCCESS;
2466 }
2467 
GetZoomRatioRange()2468 std::vector<float> CaptureSession::GetZoomRatioRange()
2469 {
2470     std::vector<float> zoomRatioRange;
2471     GetZoomRatioRange(zoomRatioRange);
2472     return zoomRatioRange;
2473 }
2474 
DoSpecSearch(std::vector<float> & zoomRatioRange)2475 int32_t CaptureSession::DoSpecSearch(std::vector<float>& zoomRatioRange)
2476 {
2477     CHECK_PRINT_ELOG(zoomRatioRange.empty(), "zoomRatioRange is empty.");
2478     auto abilityContainer = GetCameraAbilityContainer();
2479     if (abilityContainer) {
2480         zoomRatioRange = abilityContainer->GetZoomRatioRange();
2481         std::string rangeStr = Container2String(zoomRatioRange.begin(), zoomRatioRange.end());
2482         MEDIA_INFO_LOG("spec search result: %{public}s", rangeStr.c_str());
2483     } else {
2484         MEDIA_ERR_LOG("spec search abilityContainer is null");
2485     }
2486     return CameraErrorCode::SUCCESS;
2487 }
2488 
GetZoomRatioRange(std::vector<float> & zoomRatioRange)2489 int32_t CaptureSession::GetZoomRatioRange(std::vector<float>& zoomRatioRange)
2490 {
2491     MEDIA_INFO_LOG("CaptureSession::GetZoomRatioRange is Called");
2492     zoomRatioRange.clear();
2493     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2494         "CaptureSession::GetZoomRatioRange Session is not Commited");
2495 
2496     auto inputDevice = GetInputDevice();
2497     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
2498         "CaptureSession::GetZoomRatioRange camera device is null");
2499 
2500     sptr<CameraDevice> cameraDevNow = inputDevice->GetCameraDeviceInfo();
2501 
2502     if (cameraDevNow != nullptr && cameraDevNow->isConcurrentLimted_ == 1) {
2503         // LCOV_EXCL_START
2504         auto itr = cameraDevNow->limtedCapabilitySave_.ratiorange.range.find(static_cast<int32_t>(GetMode()));
2505         if (itr != cameraDevNow->limtedCapabilitySave_.ratiorange.range.end()) {
2506             zoomRatioRange.push_back(itr->second.first);
2507             zoomRatioRange.push_back(itr->second.second);
2508             return CameraErrorCode::SUCCESS;
2509         }
2510         // LCOV_EXCL_STOP
2511     }
2512 
2513     if (supportSpecSearch_) {
2514         MEDIA_INFO_LOG("spec search enter");
2515         int32_t retCode = DoSpecSearch(zoomRatioRange);
2516         return retCode;
2517     }
2518     // LCOV_EXCL_START
2519     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
2520     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
2521         "GetZoomRatioRange camera metadata is null");
2522     camera_metadata_item_t item;
2523     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_SCENE_ZOOM_CAP, &item);
2524     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count == 0, 0,
2525         "CaptureSession::GetZoomRatio Failed with return code %{public}d,item.count = %{public}d", ret, item.count);
2526     constexpr float factor = 100.0;
2527     float minZoom = 0.0;
2528     float maxZoom = 0.0;
2529     const uint32_t step = 3;
2530     uint32_t minOffset = 1;
2531     uint32_t maxOffset = 2;
2532     for (uint32_t i = 0; i < item.count; i += step) {
2533         MEDIA_DEBUG_LOG("Scene zoom cap mode: %{public}d, min: %{public}d, max: %{public}d", item.data.i32[i],
2534             item.data.i32[i + minOffset], item.data.i32[i + maxOffset]);
2535         if (GetFeaturesMode().GetFeaturedMode() == item.data.i32[i]) {
2536             minZoom = item.data.i32[i + minOffset] / factor;
2537             maxZoom = item.data.i32[i + maxOffset] / factor;
2538             break;
2539         }
2540     }
2541     zoomRatioRange = {minZoom, maxZoom};
2542     return CameraErrorCode::SUCCESS;
2543     // LCOV_EXCL_STOP
2544 }
2545 
GetZoomRatio()2546 float CaptureSession::GetZoomRatio()
2547 {
2548     float zoomRatio = 0;
2549     GetZoomRatio(zoomRatio);
2550     return zoomRatio;
2551 }
2552 
GetZoomRatio(float & zoomRatio)2553 int32_t CaptureSession::GetZoomRatio(float& zoomRatio)
2554 {
2555     zoomRatio = 0;
2556     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2557         "CaptureSession::GetZoomRatio Session is not Commited");
2558     auto inputDevice = GetInputDevice();
2559     CHECK_RETURN_RET_ELOG(!inputDevice, CameraErrorCode::SUCCESS,
2560         "CaptureSession::GetZoomRatio camera device is null");
2561     int32_t DEFAULT_ITEMS = 1;
2562     int32_t DEFAULT_DATA_LENGTH = 100;
2563     std::shared_ptr<OHOS::Camera::CameraMetadata> metaIn =
2564         std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
2565     std::shared_ptr<OHOS::Camera::CameraMetadata> metaOut =
2566         std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
2567     uint32_t count = 1;
2568     uint32_t zoomRatioMultiple = 100;
2569     uint32_t metaInZoomRatio = 1 * zoomRatioMultiple;
2570     metaIn->addEntry(OHOS_STATUS_CAMERA_CURRENT_ZOOM_RATIO, &metaInZoomRatio, count);
2571     auto cameraDeviceObj = ((sptr<CameraInput>&)inputDevice)->GetCameraDevice();
2572     CHECK_RETURN_RET_ELOG(!cameraDeviceObj,
2573         CameraErrorCode::SUCCESS, "CaptureSession::GetZoomRatio cameraDeviceObj is nullptr");
2574     int32_t ret = cameraDeviceObj->GetStatus(metaIn, metaOut);
2575     CHECK_RETURN_RET_ELOG(ret != CAMERA_OK, ServiceToCameraError(ret),
2576         "CaptureSession::GetZoomRatio Failed to Get ZoomRatio, errCode = %{public}d", ret);
2577     // LCOV_EXCL_START
2578     camera_metadata_item_t item;
2579     ret = Camera::FindCameraMetadataItem(metaOut->get(), OHOS_STATUS_CAMERA_CURRENT_ZOOM_RATIO, &item);
2580     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
2581         "CaptureSession::GetZoomRatio Failed with return code %{public}d", ret);
2582     zoomRatio = static_cast<float>(item.data.ui32[0]) / static_cast<float>(zoomRatioMultiple);
2583     MEDIA_ERR_LOG("CaptureSession::GetZoomRatio %{public}f", zoomRatio);
2584     return CameraErrorCode::SUCCESS;
2585     // LCOV_EXCL_STOP
2586 }
2587 
SetZoomRatio(float zoomRatio)2588 int32_t CaptureSession::SetZoomRatio(float zoomRatio)
2589 {
2590     CAMERA_SYNC_TRACE;
2591     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2592         "CaptureSession::SetZoomRatio Session is not Commited");
2593     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
2594         "CaptureSession::SetZoomRatio Need to call LockForControl() before setting camera properties");
2595     int32_t minIndex = 0;
2596     int32_t maxIndex = 1;
2597     MEDIA_DEBUG_LOG("CaptureSession::SetZoomRatio Zoom ratio: %{public}f", zoomRatio);
2598     std::vector<float> zoomRange = GetZoomRatioRange();
2599     CHECK_RETURN_RET_ELOG(zoomRange.empty(), CameraErrorCode::SUCCESS,
2600         "CaptureSession::SetZoomRatio Zoom range is empty");
2601     if (zoomRatio < zoomRange[minIndex]) {
2602         MEDIA_DEBUG_LOG("CaptureSession::SetZoomRatio Zoom ratio: %{public}f is lesser than minimum zoom: %{public}f",
2603             zoomRatio, zoomRange[minIndex]);
2604         zoomRatio = zoomRange[minIndex];
2605     } else if (zoomRatio > zoomRange[maxIndex]) {
2606         MEDIA_DEBUG_LOG("CaptureSession::SetZoomRatio Zoom ratio: %{public}f is greater than maximum zoom: %{public}f",
2607             zoomRatio, zoomRange[maxIndex]);
2608         zoomRatio = zoomRange[maxIndex];
2609     }
2610     CHECK_RETURN_RET_ELOG(zoomRatio == 0, CameraErrorCode::SUCCESS,
2611         "CaptureSession::SetZoomRatio Invalid zoom ratio");
2612     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_ZOOM_RATIO, &zoomRatio, 1);
2613     if (!status) {
2614         MEDIA_ERR_LOG("CaptureSession::SetZoomRatio Failed to set zoom mode");
2615     } else {
2616         auto abilityContainer = GetCameraAbilityContainer();
2617         CHECK_EXECUTE(abilityContainer && supportSpecSearch_, abilityContainer->FilterByZoomRatio(zoomRatio));
2618         wptr<CaptureSession> weakThis(this);
2619         // LCOV_EXCL_START
2620         AddFunctionToMap(std::to_string(OHOS_CONTROL_ZOOM_RATIO), [weakThis, zoomRatio]() {
2621             auto sharedThis = weakThis.promote();
2622             CHECK_RETURN_ELOG(!sharedThis, "SetZoomRatio session is nullptr");
2623             sharedThis->LockForControl();
2624             int32_t retCode = sharedThis->SetZoomRatio(zoomRatio);
2625             sharedThis->UnlockForControl();
2626             CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS,
2627                           sharedThis->SetDeviceCapabilityChangeStatus(true));
2628         });
2629         // LCOV_EXCL_STOP
2630     }
2631     return CameraErrorCode::SUCCESS;
2632 }
2633 
PrepareZoom()2634 int32_t CaptureSession::PrepareZoom()
2635 {
2636     CAMERA_SYNC_TRACE;
2637     MEDIA_DEBUG_LOG("CaptureSession::PrepareZoom");
2638     isSmoothZooming_ = true;
2639     targetZoomRatio_ = -1.0;
2640     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
2641         "CaptureSession::PrepareZoom Session is not Commited");
2642     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
2643         "CaptureSession::PrepareZoom Need to call LockForControl() before setting camera properties");
2644     uint32_t prepareZoomType = OHOS_CAMERA_ZOOMSMOOTH_PREPARE_ENABLE;
2645     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_PREPARE_ZOOM, &prepareZoomType, 1);
2646     CHECK_PRINT_ELOG(!status, "CaptureSession::PrepareZoom Failed to prepare zoom");
2647     return CameraErrorCode::SUCCESS;
2648 }
2649 
UnPrepareZoom()2650 int32_t CaptureSession::UnPrepareZoom()
2651 {
2652     CAMERA_SYNC_TRACE;
2653     MEDIA_DEBUG_LOG("CaptureSession::UnPrepareZoom");
2654     isSmoothZooming_ = false;
2655     targetZoomRatio_ = -1.0;
2656     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
2657         "CaptureSession::UnPrepareZoom Session is not Commited");
2658     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
2659         "CaptureSession::UnPrepareZoom Need to call LockForControl() before setting camera properties");
2660     uint32_t prepareZoomType = OHOS_CAMERA_ZOOMSMOOTH_PREPARE_DISABLE;
2661     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_PREPARE_ZOOM, &prepareZoomType, 1);
2662     CHECK_PRINT_ELOG(!status, "CaptureSession::UnPrepareZoom Failed to unPrepare zoom");
2663     return CameraErrorCode::SUCCESS;
2664 }
2665 
SetSmoothZoom(float targetZoomRatio,uint32_t smoothZoomType)2666 int32_t CaptureSession::SetSmoothZoom(float targetZoomRatio, uint32_t smoothZoomType)
2667     __attribute__((no_sanitize("cfi")))
2668 {
2669     CAMERA_SYNC_TRACE;
2670     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
2671         "CaptureSession::SetSmoothZoom Session is not commited");
2672     int32_t minIndex = 0;
2673     int32_t maxIndex = 1;
2674     std::vector<float> zoomRange = GetZoomRatioRange();
2675     CHECK_RETURN_RET_ELOG(zoomRange.empty(), CameraErrorCode::SUCCESS,
2676         "CaptureSession::SetSmoothZoom Zoom range is empty");
2677     if (targetZoomRatio < zoomRange[minIndex]) {
2678         MEDIA_DEBUG_LOG("CaptureSession::SetSmoothZoom Zoom ratio: %{public}f is lesser than minimum zoom: %{public}f",
2679             targetZoomRatio, zoomRange[minIndex]);
2680         targetZoomRatio = zoomRange[minIndex];
2681     } else if (targetZoomRatio > zoomRange[maxIndex]) {
2682         MEDIA_DEBUG_LOG("CaptureSession::SetSmoothZoom Zoom ratio: %{public}f is greater than maximum zoom: %{public}f",
2683             targetZoomRatio, zoomRange[maxIndex]);
2684         targetZoomRatio = zoomRange[maxIndex];
2685     }
2686 
2687     int32_t errCode = CAMERA_UNKNOWN_ERROR;
2688     float duration;
2689     auto captureSession = GetCaptureSession();
2690     if (captureSession) {
2691         MEDIA_INFO_LOG("CaptureSession::SetSmoothZoom Zoom ratio: %{public}f", targetZoomRatio);
2692         errCode = captureSession->SetSmoothZoom(smoothZoomType, GetMode(), targetZoomRatio, duration);
2693         MEDIA_INFO_LOG("CaptureSession::SetSmoothZoom duration: %{public}f ", duration);
2694         if (errCode != CAMERA_OK) {
2695             MEDIA_ERR_LOG("Failed to SetSmoothZoom!, %{public}d", errCode);
2696         } else {
2697             std::shared_ptr<OHOS::Camera::CameraMetadata> changedMetadata =
2698                 std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
2699             changedMetadata->addEntry(OHOS_CONTROL_SMOOTH_ZOOM_RATIOS, &targetZoomRatio, 1);
2700             OnSettingUpdated(changedMetadata);
2701             auto abilityContainer = GetCameraAbilityContainer();
2702             if (abilityContainer && supportSpecSearch_) {
2703                 abilityContainer->FilterByZoomRatio(targetZoomRatio);
2704             }
2705             targetZoomRatio_ = targetZoomRatio;
2706         }
2707         std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
2708         CHECK_EXECUTE(smoothZoomCallback_ != nullptr, smoothZoomCallback_->OnSmoothZoom(duration));
2709     } else {
2710         MEDIA_ERR_LOG("CaptureSession::SetSmoothZoom() captureSession is nullptr");
2711     }
2712     return CameraErrorCode::SUCCESS;
2713 }
2714 
SetSmoothZoomCallback(std::shared_ptr<SmoothZoomCallback> smoothZoomCallback)2715 void CaptureSession::SetSmoothZoomCallback(std::shared_ptr<SmoothZoomCallback> smoothZoomCallback)
2716 {
2717     MEDIA_INFO_LOG("CaptureSession::SetSmoothZoomCallback() set smooth zoom callback");
2718     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
2719     smoothZoomCallback_ = smoothZoomCallback;
2720     return;
2721 }
2722 
SetCaptureMetadataObjectTypes(std::set<camera_face_detect_mode_t> metadataObjectTypes)2723 void CaptureSession::SetCaptureMetadataObjectTypes(std::set<camera_face_detect_mode_t> metadataObjectTypes)
2724 {
2725     MEDIA_INFO_LOG("CaptureSession SetCaptureMetadataObjectTypes Enter");
2726     CHECK_RETURN_ELOG(GetInputDevice() == nullptr, "SetCaptureMetadataObjectTypes: inputDevice is null");
2727     uint32_t count = 1;
2728     uint8_t objectType = OHOS_CAMERA_FACE_DETECT_MODE_SIMPLE;
2729     if (!metadataObjectTypes.count(OHOS_CAMERA_FACE_DETECT_MODE_SIMPLE)) {
2730         objectType = OHOS_CAMERA_FACE_DETECT_MODE_OFF;
2731         MEDIA_ERR_LOG("CaptureSession SetCaptureMetadataObjectTypes Can not set face detect mode!");
2732     }
2733     this->LockForControl();
2734     bool res = this->changedMetadata_->addEntry(OHOS_STATISTICS_FACE_DETECT_SWITCH, &objectType, count);
2735     CHECK_PRINT_ELOG(!res, "SetCaptureMetadataObjectTypes Failed to add detect object types to changed metadata");
2736     this->UnlockForControl();
2737 }
2738 
SetGuessMode(SceneMode mode)2739 void CaptureSession::SetGuessMode(SceneMode mode)
2740 {
2741     CHECK_RETURN(currentMode_ != SceneMode::NORMAL);
2742     switch (mode) {
2743         case CAPTURE:
2744             if (guessMode_ == SceneMode::NORMAL) {
2745                 guessMode_ = CAPTURE;
2746             }
2747             break;
2748         case VIDEO:
2749             if (guessMode_ != SceneMode::VIDEO) {
2750                 guessMode_ = VIDEO;
2751             }
2752             break;
2753         default:
2754             MEDIA_WARNING_LOG("CaptureSession::SetGuessMode not support this guest mode:%{public}d", mode);
2755             break;
2756     }
2757     MEDIA_INFO_LOG(
2758         "CaptureSession::SetGuessMode currentMode_:%{public}d guessMode_:%{public}d", currentMode_, guessMode_);
2759 }
2760 
SetMode(SceneMode modeName)2761 void CaptureSession::SetMode(SceneMode modeName)
2762 {
2763     CHECK_RETURN_ELOG(IsSessionCommited(), "CaptureSession::SetMode Session has been Commited");
2764     currentMode_ = modeName;
2765     // reset deferred enable status when reset mode
2766     EnableDeferredType(DELIVERY_NONE, false);
2767     auto captureSession = GetCaptureSession();
2768     if (captureSession) {
2769         captureSession->SetFeatureMode(modeName);
2770         MEDIA_INFO_LOG("CaptureSession::SetSceneMode  SceneMode = %{public}d", modeName);
2771     } else {
2772         MEDIA_ERR_LOG("CaptureSession::SetMode captureSession is nullptr");
2773         return;
2774     }
2775     MEDIA_INFO_LOG("CaptureSession SetMode modeName = %{public}d", modeName);
2776 }
2777 
GetMode()2778 SceneMode CaptureSession::GetMode()
2779 {
2780     MEDIA_INFO_LOG(
2781         "CaptureSession GetMode currentMode_ = %{public}d, guestMode_ = %{public}d", currentMode_, guessMode_);
2782     CHECK_RETURN_RET(currentMode_ == SceneMode::NORMAL, guessMode_);
2783     return currentMode_;
2784 }
2785 
IsImageDeferred()2786 bool CaptureSession::IsImageDeferred()
2787 {
2788     MEDIA_INFO_LOG("CaptureSession IsImageDeferred");
2789     return isImageDeferred_;
2790 }
2791 
IsVideoDeferred()2792 bool CaptureSession::IsVideoDeferred()
2793 {
2794     MEDIA_INFO_LOG("CaptureSession IsVideoDeferred:%{public}d", isVideoDeferred_);
2795     return isVideoDeferred_;
2796 }
2797 
GetFeaturesMode()2798 SceneFeaturesMode CaptureSession::GetFeaturesMode()
2799 {
2800     SceneFeaturesMode sceneFeaturesMode;
2801     sceneFeaturesMode.SetSceneMode(GetMode());
2802     sceneFeaturesMode.SwitchFeature(FEATURE_MACRO, isSetMacroEnable_);
2803     sceneFeaturesMode.SwitchFeature(FEATURE_MOON_CAPTURE_BOOST, isSetMoonCaptureBoostEnable_);
2804     sceneFeaturesMode.SwitchFeature(FEATURE_LOW_LIGHT_BOOST, isSetLowLightBoostEnable_);
2805     sceneFeaturesMode.SwitchFeature(FEATURE_TRIPOD_DETECTION, isSetTripodDetectionEnable_);
2806     return sceneFeaturesMode;
2807 }
2808 
GetSubFeatureMods()2809 vector<SceneFeaturesMode> CaptureSession::GetSubFeatureMods()
2810 {
2811     vector<SceneFeaturesMode> sceneFeaturesModes {};
2812     auto mode = GetMode();
2813     sceneFeaturesModes.emplace_back(SceneFeaturesMode(mode, {}));
2814     if (mode == SceneMode::CAPTURE) {
2815         sceneFeaturesModes.emplace_back(SceneFeaturesMode(SceneMode::CAPTURE, { SceneFeature::FEATURE_MACRO }));
2816         sceneFeaturesModes.emplace_back(
2817             SceneFeaturesMode(SceneMode::CAPTURE, { SceneFeature::FEATURE_MOON_CAPTURE_BOOST }));
2818     } else if (mode == SceneMode::VIDEO) {
2819         sceneFeaturesModes.emplace_back(
2820             SceneFeaturesMode(SceneMode::VIDEO, std::set<SceneFeature> { SceneFeature::FEATURE_MACRO }));
2821     }
2822     return sceneFeaturesModes;
2823 }
2824 
VerifyAbility(uint32_t ability)2825 int32_t CaptureSession::VerifyAbility(uint32_t ability)
2826 {
2827     SceneMode matchMode = SceneMode::NORMAL;
2828     std::vector<SceneMode> supportModes = {SceneMode::VIDEO, SceneMode::PORTRAIT, SceneMode::NIGHT};
2829     auto mode = std::find(supportModes.begin(), supportModes.end(), GetMode());
2830     if (mode != supportModes.end()) {
2831         matchMode = *mode;
2832     } else {
2833         MEDIA_ERR_LOG("CaptureSession::VerifyAbility need PortraitMode or Night or Video");
2834         return CAMERA_INVALID_ARG;
2835     }
2836     auto inputDevice = GetInputDevice();
2837     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CAMERA_INVALID_ARG,
2838         "CaptureSession::VerifyAbility camera device is null");
2839 
2840     ProcessProfilesAbilityId(matchMode);
2841 
2842     std::vector<uint32_t> photoAbilityId = previewProfile_.GetAbilityId();
2843     std::vector<uint32_t> previewAbilityId = previewProfile_.GetAbilityId();
2844 
2845     auto itrPhoto = std::find(photoAbilityId.begin(), photoAbilityId.end(), ability);
2846     auto itrPreview = std::find(previewAbilityId.begin(), previewAbilityId.end(), ability);
2847     CHECK_RETURN_RET_ELOG(itrPhoto == photoAbilityId.end() || itrPreview == previewAbilityId.end(),
2848         CAMERA_INVALID_ARG, "CaptureSession::VerifyAbility abilityId is NULL");
2849     return CAMERA_OK;
2850 }
2851 
ProcessProfilesAbilityId(const SceneMode supportModes)2852 void CaptureSession::ProcessProfilesAbilityId(const SceneMode supportModes)
2853 {
2854     auto inputDevice = GetInputDevice();
2855     CHECK_RETURN_ELOG(!inputDevice, "ProcessProfilesAbilityId inputDevice is null");
2856     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
2857     CHECK_RETURN_ELOG(!inputDeviceInfo, "ProcessProfilesAbilityId inputDeviceInfo is null");
2858     std::vector<Profile> photoProfiles = inputDeviceInfo->modePhotoProfiles_[supportModes];
2859     std::vector<Profile> previewProfiles = inputDeviceInfo->modePreviewProfiles_[supportModes];
2860     MEDIA_INFO_LOG("photoProfiles size = %{public}zu, photoProfiles size = %{public}zu", photoProfiles.size(),
2861         previewProfiles.size());
2862     for (auto i : photoProfiles) {
2863         std::vector<uint32_t> ids = i.GetAbilityId();
2864         std::string abilityIds = Container2String(ids.begin(), ids.end());
2865         MEDIA_INFO_LOG("photoProfiles f(%{public}d), w(%{public}d), h(%{public}d), ability:(%{public}s)",
2866             i.GetCameraFormat(), i.GetSize().width, i.GetSize().height, abilityIds.c_str());
2867         if (i.GetCameraFormat() == photoProfile_.GetCameraFormat() &&
2868             i.GetSize().width == photoProfile_.GetSize().width &&
2869             i.GetSize().height == photoProfile_.GetSize().height) {
2870             if (i.GetAbilityId().empty()) {
2871                 MEDIA_INFO_LOG("VerifyAbility::CreatePhotoOutput:: this size'abilityId is not exist");
2872                 continue;
2873             }
2874             photoProfile_.abilityId_ = i.GetAbilityId();
2875             break;
2876         }
2877     }
2878     for (auto i : previewProfiles) {
2879         std::vector<uint32_t> ids = i.GetAbilityId();
2880         std::string abilityIds = Container2String(ids.begin(), ids.end());
2881         MEDIA_INFO_LOG("previewProfiles f(%{public}d), w(%{public}d), h(%{public}d), ability:(%{public}s)",
2882             i.GetCameraFormat(), i.GetSize().width, i.GetSize().height, abilityIds.c_str());
2883         if (i.GetCameraFormat() == previewProfile_.GetCameraFormat() &&
2884             i.GetSize().width == previewProfile_.GetSize().width &&
2885             i.GetSize().height == previewProfile_.GetSize().height) {
2886             if (i.GetAbilityId().empty()) {
2887                 MEDIA_INFO_LOG("VerifyAbility::CreatePreviewOutput:: this size'abilityId is not exist");
2888                 continue;
2889             }
2890             previewProfile_.abilityId_ = i.GetAbilityId();
2891             break;
2892         }
2893     }
2894 }
2895 
GetSupportedFilters()2896 std::vector<FilterType> CaptureSession::GetSupportedFilters()
2897 {
2898     std::vector<FilterType> supportedFilters = {};
2899     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), supportedFilters,
2900         "CaptureSession::GetSupportedFilters Session is not Commited");
2901     auto inputDevice = GetInputDevice();
2902     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), supportedFilters,
2903         "CaptureSession::GetSupportedFilters camera device is null");
2904 
2905     int ret = VerifyAbility(static_cast<uint32_t>(OHOS_ABILITY_SCENE_FILTER_TYPES));
2906     CHECK_RETURN_RET_ELOG(ret != CAMERA_OK, supportedFilters,
2907         "CaptureSession::GetSupportedFilters abilityId is NULL");
2908     // LCOV_EXCL_START
2909     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
2910     CHECK_RETURN_RET_ELOG(metadata == nullptr, supportedFilters,
2911         "GetSupportedFilters camera metadata is null");
2912     camera_metadata_item_t item;
2913     ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_SCENE_FILTER_TYPES, &item);
2914     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count == 0, supportedFilters,
2915         "CaptureSession::GetSupportedFilters Failed with return code %{public}d", ret);
2916     for (uint32_t i = 0; i < item.count; i++) {
2917         auto itr = metaFilterTypeMap_.find(static_cast<camera_filter_type_t>(item.data.u8[i]));
2918         CHECK_EXECUTE(itr != metaFilterTypeMap_.end(), supportedFilters.emplace_back(itr->second));
2919     }
2920     return supportedFilters;
2921     // LCOV_EXCL_STOP
2922 }
2923 
GetFilter()2924 FilterType CaptureSession::GetFilter()
2925 {
2926     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), FilterType::NONE,
2927         "CaptureSession::GetFilter Session is not Commited");
2928     auto inputDevice = GetInputDevice();
2929     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), FilterType::NONE,
2930         "CaptureSession::GetFilter camera device is null");
2931     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
2932     CHECK_RETURN_RET_ELOG(metadata == nullptr, FilterType::NONE,
2933         "GetFilter camera metadata is null");
2934     camera_metadata_item_t item;
2935     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_FILTER_TYPE, &item);
2936     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count == 0, FilterType::NONE,
2937         "CaptureSession::GetFilter Failed with return code %{public}d", ret);
2938     // LCOV_EXCL_START
2939     auto itr = metaFilterTypeMap_.find(static_cast<camera_filter_type_t>(item.data.u8[0]));
2940     CHECK_RETURN_RET(itr != metaFilterTypeMap_.end(), itr->second);
2941     return FilterType::NONE;
2942     // LCOV_EXCL_STOP
2943 }
2944 
SetFilter(FilterType filterType)2945 void CaptureSession::SetFilter(FilterType filterType)
2946 {
2947     CAMERA_SYNC_TRACE;
2948     CHECK_RETURN_ELOG(!(IsSessionCommited() || IsSessionConfiged()),
2949         "CaptureSession::SetFilter Session is not Commited");
2950     CHECK_RETURN_ELOG(changedMetadata_ == nullptr,
2951         "CaptureSession::SetFilter Need to call LockForControl() before setting camera properties");
2952 
2953     std::vector<FilterType> supportedFilters = GetSupportedFilters();
2954     auto itr = std::find(supportedFilters.begin(), supportedFilters.end(), filterType);
2955     CHECK_RETURN_ELOG(itr == supportedFilters.end(), "CaptureSession::GetSupportedFilters abilityId is NULL");
2956     // LCOV_EXCL_START
2957     uint8_t filter = 0;
2958     for (auto itr2 = fwkFilterTypeMap_.cbegin(); itr2 != fwkFilterTypeMap_.cend(); itr2++) {
2959         if (filterType == itr2->first) {
2960             filter = static_cast<uint8_t>(itr2->second);
2961             break;
2962         }
2963     }
2964     MEDIA_DEBUG_LOG("CaptureSession::setFilter: %{public}d", filterType);
2965     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_FILTER_TYPE, &filter, 1);
2966     CHECK_PRINT_ELOG(!status, "CaptureSession::setFilter Failed to set filter");
2967     return;
2968     // LCOV_EXCL_STOP
2969 }
2970 
GetSupportedBeautyTypes()2971 std::vector<BeautyType> CaptureSession::GetSupportedBeautyTypes()
2972 {
2973     std::vector<BeautyType> supportedBeautyTypes = {};
2974     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), supportedBeautyTypes,
2975         "CaptureSession::GetSupportedBeautyTypes Session is not Commited");
2976     auto inputDevice = GetInputDevice();
2977     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), supportedBeautyTypes,
2978         "CaptureSession::GetSupportedBeautyTypes camera device is null");
2979 
2980     int ret = VerifyAbility(static_cast<uint32_t>(OHOS_ABILITY_SCENE_BEAUTY_TYPES));
2981     CHECK_RETURN_RET_ELOG(ret != CAMERA_OK, supportedBeautyTypes,
2982         "CaptureSession::GetSupportedBeautyTypes abilityId is NULL");
2983     // LCOV_EXCL_START
2984     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
2985     CHECK_RETURN_RET_ELOG(metadata == nullptr, supportedBeautyTypes,
2986         "GetSupportedBeautyTypes camera metadata is null");
2987     camera_metadata_item_t item;
2988     ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_SCENE_BEAUTY_TYPES, &item);
2989     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count == 0, supportedBeautyTypes,
2990         "CaptureSession::GetSupportedBeautyTypes Failed with return code %{public}d", ret);
2991     for (uint32_t i = 0; i < item.count; i++) {
2992         auto itr = g_metaBeautyTypeMap_.find(static_cast<camera_beauty_type_t>(item.data.u8[i]));
2993         CHECK_EXECUTE(itr != g_metaBeautyTypeMap_.end(), supportedBeautyTypes.emplace_back(itr->second));
2994     }
2995     return supportedBeautyTypes;
2996     // LCOV_EXCL_STOP
2997 }
2998 
GetSupportedBeautyRange(BeautyType beautyType)2999 std::vector<int32_t> CaptureSession::GetSupportedBeautyRange(BeautyType beautyType)
3000 {
3001     int ret = 0;
3002     std::vector<int32_t> supportedBeautyRange;
3003     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), supportedBeautyRange,
3004         "CaptureSession::GetSupportedBeautyRange Session is not Commited");
3005     auto inputDevice = GetInputDevice();
3006     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), supportedBeautyRange,
3007         "CaptureSession::GetSupportedBeautyRange camera device is null");
3008 
3009     std::vector<BeautyType> supportedBeautyTypes = GetSupportedBeautyTypes();
3010     CHECK_RETURN_RET_ELOG(std::find(supportedBeautyTypes.begin(), supportedBeautyTypes.end(), beautyType) ==
3011         supportedBeautyTypes.end(), supportedBeautyRange, "CaptureSession::GetSupportedBeautyRange beautyType is NULL");
3012     // LCOV_EXCL_START
3013     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
3014     CHECK_RETURN_RET_ELOG(metadata == nullptr, supportedBeautyRange,
3015         "GetSupportedBeautyRange camera metadata is null");
3016     camera_metadata_item_t item;
3017 
3018     MEDIA_ERR_LOG("CaptureSession::GetSupportedBeautyRange: %{public}d", beautyType);
3019 
3020     int32_t beautyTypeAbility;
3021     auto itr = g_fwkBeautyAbilityMap_.find(beautyType);
3022     CHECK_RETURN_RET_ELOG(itr == g_fwkBeautyAbilityMap_.end(), supportedBeautyRange,
3023         "CaptureSession::GetSupportedBeautyRange Unknown beauty Type");
3024         beautyTypeAbility = itr->second;
3025         Camera::FindCameraMetadataItem(metadata->get(), beautyTypeAbility, &item);
3026     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count == 0, supportedBeautyRange,
3027         "CaptureSession::GetSupportedBeautyRange Failed with return code %{public}d", ret);
3028     if (beautyType == SKIN_TONE) {
3029         int32_t skinToneOff = -1;
3030         supportedBeautyRange.push_back(skinToneOff);
3031     }
3032     for (uint32_t i = 0; i < item.count; i++) {
3033         if (beautyTypeAbility == OHOS_ABILITY_BEAUTY_SKIN_TONE_VALUES) {
3034             supportedBeautyRange.emplace_back(item.data.i32[i]);
3035         } else {
3036             supportedBeautyRange.emplace_back(item.data.u8[i]);
3037         }
3038     }
3039     beautyTypeAndRanges_[beautyType] = supportedBeautyRange;
3040     return supportedBeautyRange;
3041     // LCOV_EXCL_STOP
3042 }
3043 
SetBeautyValue(BeautyType beautyType,int32_t beautyLevel)3044 bool CaptureSession::SetBeautyValue(BeautyType beautyType, int32_t beautyLevel)
3045 {
3046     camera_device_metadata_tag_t metadata;
3047     auto metaItr = fwkBeautyControlMap_.find(beautyType);
3048     if (metaItr != fwkBeautyControlMap_.end()) {
3049         metadata = metaItr->second;
3050     }
3051 
3052     std::vector<int32_t> levelVec;
3053     if (beautyTypeAndRanges_.count(beautyType)) {
3054         levelVec = beautyTypeAndRanges_[beautyType];
3055     } else {
3056         levelVec = GetSupportedBeautyRange(beautyType);
3057     }
3058 
3059     bool status = false;
3060     CameraPosition usedAsCameraPosition = GetUsedAsPosition();
3061     MEDIA_INFO_LOG("CaptureSession::SetBeautyValue usedAsCameraPosition %{public}d", usedAsCameraPosition);
3062     if (CAMERA_POSITION_UNSPECIFIED == usedAsCameraPosition) {
3063         auto itrType = std::find(levelVec.cbegin(), levelVec.cend(), beautyLevel);
3064         CHECK_RETURN_RET_ELOG(itrType == levelVec.end(), status,
3065             "CaptureSession::SetBeautyValue: %{public}d not in beautyRanges", beautyLevel);
3066     }
3067     // LCOV_EXCL_START
3068     if (beautyType == BeautyType::SKIN_TONE) {
3069         int32_t skinToneVal = beautyLevel;
3070         status = AddOrUpdateMetadata(changedMetadata_, metadata, &skinToneVal, 1);
3071     } else {
3072         uint8_t beautyVal = static_cast<uint8_t>(beautyLevel);
3073         status = AddOrUpdateMetadata(changedMetadata_, metadata, &beautyVal, 1);
3074     }
3075     CHECK_RETURN_RET_ELOG(!status, status, "CaptureSession::SetBeautyValue Failed to set beauty");
3076     beautyTypeAndLevels_[beautyType] = beautyLevel;
3077     return status;
3078     // LCOV_EXCL_STOP
3079 }
3080 
GetUsedAsPosition()3081 CameraPosition CaptureSession::GetUsedAsPosition()
3082 {
3083     CameraPosition usedAsCameraPosition = CAMERA_POSITION_UNSPECIFIED;
3084     auto inputDevice = GetInputDevice();
3085     CHECK_RETURN_RET_ELOG(inputDevice == nullptr, usedAsCameraPosition,
3086         "CaptureSession::GetUsedAsPosition input device is null");
3087     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
3088     CHECK_RETURN_RET_ELOG(inputDevice == nullptr, usedAsCameraPosition,
3089         "CaptureSession::GetUsedAsPosition camera device info is null");
3090     usedAsCameraPosition = inputDeviceInfo->usedAsCameraPosition_;
3091     return usedAsCameraPosition;
3092 }
3093 
SetBeauty(BeautyType beautyType,int value)3094 void CaptureSession::SetBeauty(BeautyType beautyType, int value)
3095 {
3096     CHECK_RETURN_ELOG(!(IsSessionCommited() || IsSessionConfiged()),
3097         "CaptureSession::SetBeauty Session is not Commited");
3098     CHECK_RETURN_ELOG(changedMetadata_ == nullptr, "CaptureSession::SetBeauty changedMetadata_ is NULL");
3099 
3100     CameraPosition usedAsCameraPosition = GetUsedAsPosition();
3101     MEDIA_INFO_LOG("CaptureSession::SetBeauty usedAsCameraPosition %{public}d", usedAsCameraPosition);
3102     if (CAMERA_POSITION_UNSPECIFIED == usedAsCameraPosition) {
3103         std::vector<BeautyType> supportedBeautyTypes = GetSupportedBeautyTypes();
3104         auto itr = std::find(supportedBeautyTypes.begin(), supportedBeautyTypes.end(), beautyType);
3105         CHECK_RETURN_ELOG(itr == supportedBeautyTypes.end(),
3106             "CaptureSession::GetSupportedBeautyTypes abilityId is NULL");
3107     }
3108     // LCOV_EXCL_START
3109     MEDIA_ERR_LOG("SetBeauty beautyType %{public}d", beautyType);
3110     uint8_t beauty = OHOS_CAMERA_BEAUTY_TYPE_OFF;
3111     if ((beautyType == AUTO_TYPE) && (value == 0)) {
3112         bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_BEAUTY_TYPE, &beauty, 1);
3113         status = SetBeautyValue(beautyType, value);
3114         CHECK_PRINT_ELOG(!status, "CaptureSession::SetBeauty AUTO_TYPE Failed to set beauty value");
3115         return;
3116     }
3117 
3118     auto itrType = g_fwkBeautyTypeMap_.find(beautyType);
3119     if (itrType != g_fwkBeautyTypeMap_.end()) {
3120         beauty = static_cast<uint8_t>(itrType->second);
3121     }
3122 
3123     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_BEAUTY_TYPE, &beauty, 1);
3124     CHECK_PRINT_ELOG(!status, "CaptureSession::SetBeauty Failed to set beautyType control");
3125 
3126     status = SetBeautyValue(beautyType, value);
3127     CHECK_PRINT_ELOG(!status, "CaptureSession::SetBeauty Failed to set beauty value");
3128     return;
3129     // LCOV_EXCL_STOP
3130 }
3131 
GetSupportedPortraitThemeTypes(std::vector<PortraitThemeType> & supportedPortraitThemeTypes)3132 int32_t CaptureSession::GetSupportedPortraitThemeTypes(std::vector<PortraitThemeType>& supportedPortraitThemeTypes)
3133 {
3134     MEDIA_DEBUG_LOG("Enter CaptureSession::GetSupportedPortraitThemeTypes");
3135     supportedPortraitThemeTypes.clear();
3136     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
3137         "CaptureSession::GetSupportedPortraitThemeTypes Session is not Commited.");
3138     auto inputDevice = GetInputDevice();
3139     CHECK_RETURN_RET_ELOG(inputDevice == nullptr, CameraErrorCode::SUCCESS,
3140         "CaptureSession::GetSupportedPortraitThemeTypes camera device is null");
3141     auto deviceInfo = inputDevice->GetCameraDeviceInfo();
3142     CHECK_RETURN_RET_ELOG(deviceInfo == nullptr, CameraErrorCode::SUCCESS,
3143         "CaptureSession::GetSupportedPortraitThemeTypes camera deviceInfo is null");
3144     std::shared_ptr<Camera::CameraMetadata> metadata = deviceInfo->GetCachedMetadata();
3145     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
3146         "GetSupportedPortraitThemeTypes camera metadata is null");
3147     camera_metadata_item_t item;
3148     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_CAMERA_PORTRAIT_THEME_TYPES, &item);
3149     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count == 0, CameraErrorCode::SUCCESS,
3150         "CaptureSession::GetSupportedPortraitThemeTypes Failed with return code %{public}d", ret);
3151     g_transformValidData(item, g_metaPortraitThemeTypeMap_, supportedPortraitThemeTypes);
3152     return CameraErrorCode::SUCCESS;
3153 }
3154 
IsPortraitThemeSupported()3155 bool CaptureSession::IsPortraitThemeSupported()
3156 {
3157     bool isSupported;
3158     IsPortraitThemeSupported(isSupported);
3159     return isSupported;
3160 }
3161 
IsPortraitThemeSupported(bool & isSupported)3162 int32_t CaptureSession::IsPortraitThemeSupported(bool &isSupported)
3163 {
3164     MEDIA_DEBUG_LOG("Enter CaptureSession::IsPortraitThemeSupported");
3165     isSupported = false;
3166     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
3167         "CaptureSession::IsPortraitThemeSupported Session is not Commited.");
3168     auto inputDevice = GetInputDevice();
3169     CHECK_RETURN_RET_ELOG(inputDevice == nullptr, CameraErrorCode::SUCCESS,
3170         "CaptureSession::IsPortraitThemeSupported camera device is null");
3171     auto deviceInfo = inputDevice->GetCameraDeviceInfo();
3172     CHECK_RETURN_RET_ELOG(deviceInfo == nullptr, CameraErrorCode::SUCCESS,
3173         "CaptureSession::IsPortraitThemeSupported camera deviceInfo is null");
3174     std::shared_ptr<Camera::CameraMetadata> metadata = deviceInfo->GetCachedMetadata();
3175     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
3176         "IsPortraitThemeSupported camera metadata is null");
3177     camera_metadata_item_t item;
3178     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_CAMERA_PORTRAIT_THEME_SUPPORTED, &item);
3179     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count <= 0, CameraErrorCode::SUCCESS,
3180         "CaptureSession::IsPortraitThemeSupported Failed with return code %{public}d", ret);
3181     isSupported = static_cast<bool>(item.data.u8[0]);
3182     return CameraErrorCode::SUCCESS;
3183 }
3184 
GetSupportedVideoRotations(std::vector<int32_t> & supportedRotation)3185 int32_t CaptureSession::GetSupportedVideoRotations(std::vector<int32_t>& supportedRotation)
3186 {
3187     MEDIA_DEBUG_LOG("Enter CaptureSession::GetSupportedVideoRotations");
3188     supportedRotation.clear();
3189     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
3190         "CaptureSession::GetSupportedVideoRotations Session is not Commited.");
3191     auto inputDevice = GetInputDevice();
3192     CHECK_RETURN_RET_ELOG(inputDevice == nullptr, CameraErrorCode::SUCCESS,
3193         "CaptureSession::GetSupportedVideoRotations camera device is null");
3194     auto deviceInfo = inputDevice->GetCameraDeviceInfo();
3195     CHECK_RETURN_RET_ELOG(deviceInfo == nullptr, CameraErrorCode::SUCCESS,
3196         "CaptureSession::GetSupportedVideoRotations camera deviceInfo is null");
3197     std::shared_ptr<Camera::CameraMetadata> metadata = deviceInfo->GetCachedMetadata();
3198     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
3199         "GetSupportedVideoRotations camera metadata is null");
3200     camera_metadata_item_t item;
3201     int32_t ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_CAMERA_VIDEO_ROTATION, &item);
3202     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count == 0, CameraErrorCode::SUCCESS,
3203         "CaptureSession::GetSupportedVideoRotations Failed with return code %{public}d", ret);
3204     // LCOV_EXCL_START
3205     for (uint32_t i = 0; i < item.count; i++) {
3206         auto rotation = static_cast<VideoRotation>(item.data.i32[i]);
3207         auto it = std::find(g_fwkVideoRotationVector_.begin(), g_fwkVideoRotationVector_.end(), rotation);
3208         CHECK_EXECUTE(it != g_fwkVideoRotationVector_.end(), supportedRotation.emplace_back(static_cast<int32_t>(*it)));
3209     }
3210     return CameraErrorCode::SUCCESS;
3211     // LCOV_EXCL_STOP
3212 }
3213 
IsVideoRotationSupported()3214 bool CaptureSession::IsVideoRotationSupported()
3215 {
3216     bool isSupported;
3217     IsVideoRotationSupported(isSupported);
3218     return isSupported;
3219 }
3220 
IsVideoRotationSupported(bool & isSupported)3221 int32_t CaptureSession::IsVideoRotationSupported(bool &isSupported)
3222 {
3223     MEDIA_DEBUG_LOG("Enter CaptureSession::IsVideoRotationSupported");
3224     isSupported = false;
3225     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
3226         "CaptureSession::IsVideoRotationSupported Session is not Commited.");
3227     auto inputDevice = GetInputDevice();
3228     CHECK_RETURN_RET_ELOG(inputDevice == nullptr, CameraErrorCode::SUCCESS,
3229         "CaptureSession::IsVideoRotationSupported camera device is null");
3230     auto deviceInfo = inputDevice->GetCameraDeviceInfo();
3231     CHECK_RETURN_RET_ELOG(deviceInfo == nullptr, CameraErrorCode::SUCCESS,
3232         "CaptureSession::IsVideoRotationSupported camera deviceInfo is null");
3233     std::shared_ptr<Camera::CameraMetadata> metadata = deviceInfo->GetCachedMetadata();
3234     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
3235         "IsVideoRotationSupported camera metadata is null");
3236     camera_metadata_item_t item;
3237     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_CAMERA_VIDEO_ROTATION_SUPPORTED, &item);
3238     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count <= 0, CameraErrorCode::SUCCESS,
3239         "CaptureSession::IsVideoRotationSupported Failed with return code %{public}d", ret);
3240     isSupported = static_cast<bool>(item.data.u8[0]);
3241     return CameraErrorCode::SUCCESS;
3242 }
3243 
SetVideoRotation(int32_t rotation)3244 int32_t CaptureSession::SetVideoRotation(int32_t rotation)
3245 {
3246     MEDIA_DEBUG_LOG("Enter CaptureSession::SetVideoRotation");
3247     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
3248         "CaptureSession::SetVideoRotation Session is not Commited");
3249     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
3250         "CaptureSession::SetVideoRotation Need to call LockForControl() before setting camera properties");
3251     // LCOV_EXCL_START
3252     CHECK_RETURN_RET(!IsVideoRotationSupported(), CameraErrorCode::OPERATION_NOT_ALLOWED);
3253     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_CAMERA_VIDEO_ROTATION, &rotation, 1);
3254     CHECK_PRINT_ELOG(!status, "CaptureSession::SetVideoRotation Failed to set flash mode");
3255     return CameraErrorCode::SUCCESS;
3256     // LCOV_EXCL_STOP
3257 }
3258 
3259 // focus distance
GetMinimumFocusDistance()3260 float CaptureSession::GetMinimumFocusDistance() __attribute__((no_sanitize("cfi")))
3261 {
3262     float invalidDistance = 0.0;
3263     auto inputDevice = GetInputDevice();
3264     CHECK_RETURN_RET_ELOG(!inputDevice, invalidDistance,
3265         "CaptureSession::GetMinimumFocusDistance camera device is null");
3266     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
3267     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, invalidDistance,
3268         "CaptureSession::GetMinimumFocusDistance camera deviceInfo is null");
3269     std::shared_ptr<Camera::CameraMetadata> metadata = inputDeviceInfo->GetCachedMetadata();
3270     CHECK_RETURN_RET_ELOG(metadata == nullptr, invalidDistance,
3271         "GetMinimumFocusDistance camera metadata is null");
3272     camera_metadata_item_t item;
3273     int32_t ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_LENS_INFO_MINIMUM_FOCUS_DISTANCE, &item);
3274     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, invalidDistance,
3275         "CaptureSession::GetMinimumFocusDistance Failed with return code %{public}d", ret);
3276     float minimumFocusDistance = item.data.f[0];
3277     MEDIA_DEBUG_LOG("CaptureSession::GetMinimumFocusDistance minimumFocusDistance=%{public}f", minimumFocusDistance);
3278     return minimumFocusDistance;
3279 }
3280 
ProcessFocusDistanceUpdates(const std::shared_ptr<Camera::CameraMetadata> & result)3281 void CaptureSession::ProcessFocusDistanceUpdates(const std::shared_ptr<Camera::CameraMetadata>& result)
3282 {
3283     CHECK_RETURN_ELOG(!result, "CaptureSession::ProcessFocusDistanceUpdates camera metadata is null");
3284     camera_metadata_item_t item;
3285     int32_t ret = Camera::FindCameraMetadataItem(result->get(), OHOS_CONTROL_LENS_FOCUS_DISTANCE, &item);
3286     if (ret != CAM_META_SUCCESS) {
3287         MEDIA_DEBUG_LOG("CaptureSession::ProcessFocusDistanceUpdates Failed with return code %{public}d", ret);
3288         return;
3289     }
3290     // LCOV_EXCL_START
3291     MEDIA_DEBUG_LOG("CaptureSession::ProcessFocusDistanceUpdates meta=%{public}f", item.data.f[0]);
3292     CHECK_RETURN(FloatIsEqual(GetMinimumFocusDistance(), 0.0));
3293     focusDistance_ = 1.0 - (item.data.f[0] / GetMinimumFocusDistance());
3294     MEDIA_DEBUG_LOG("CaptureSession::ProcessFocusDistanceUpdates focusDistance = %{public}f", focusDistance_);
3295     return;
3296     // LCOV_EXCL_STOP
3297 }
3298 
SetFocusDistance(float focusDistance)3299 int32_t CaptureSession::SetFocusDistance(float focusDistance)
3300 {
3301     CAMERA_SYNC_TRACE;
3302     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
3303         "CaptureSession::SetFocusDistance Session is not Commited");
3304     // LCOV_EXCL_START
3305     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
3306         "CaptureSession::SetFocusDistance Need to call LockForControl before setting camera properties");
3307     MEDIA_DEBUG_LOG("CaptureSession::SetFocusDistance app set focusDistance = %{public}f", focusDistance);
3308     if (focusDistance < 0) {
3309         focusDistance = 0.0;
3310     } else if (focusDistance > 1) {
3311         focusDistance = 1.0;
3312     }
3313     float value = (1 - focusDistance) * GetMinimumFocusDistance();
3314     focusDistance_ = focusDistance;
3315     MEDIA_DEBUG_LOG("CaptureSession::SetFocusDistance meta set focusDistance = %{public}f", value);
3316     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_LENS_FOCUS_DISTANCE, &value, 1);
3317     wptr<CaptureSession> weakThis(this);
3318     CHECK_EXECUTE(status, AddFunctionToMap(std::to_string(OHOS_CONTROL_LENS_FOCUS_DISTANCE),
3319         [weakThis, focusDistance]() {
3320             auto sharedThis = weakThis.promote();
3321             CHECK_RETURN_ELOG(!sharedThis, "SetFocusDistance session is nullptr");
3322             sharedThis->LockForControl();
3323             int32_t retCode = sharedThis->SetFocusDistance(focusDistance);
3324             sharedThis->UnlockForControl();
3325             CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS, sharedThis->SetDeviceCapabilityChangeStatus(true));
3326         }));
3327     CHECK_PRINT_ELOG(!status, "CaptureSession::SetFocusDistance Failed to set");
3328     return CameraErrorCode::SUCCESS;
3329     // LCOV_EXCL_STOP
3330 }
3331 
SetFrameRateRange(const std::vector<int32_t> & frameRateRange)3332 int32_t CaptureSession::SetFrameRateRange(const std::vector<int32_t>& frameRateRange)
3333 {
3334     std::vector<int32_t> videoFrameRateRange = frameRateRange;
3335     this->LockForControl();
3336     bool isSuccess = this->changedMetadata_->addEntry(
3337         OHOS_CONTROL_FPS_RANGES, videoFrameRateRange.data(), videoFrameRateRange.size());
3338     wptr<CaptureSession> weakThis(this);
3339     CHECK_EXECUTE(isSuccess, AddFunctionToMap("video" + std::to_string(OHOS_CONTROL_FPS_RANGES),
3340         [weakThis, frameRateRange]() {
3341             auto sharedThis = weakThis.promote();
3342             CHECK_RETURN_ELOG(!sharedThis, "SetFrameRateRange session is nullptr");
3343             int32_t retCode = sharedThis->SetFrameRateRange(frameRateRange);
3344             CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS, sharedThis->SetDeviceCapabilityChangeStatus(true));
3345         }));
3346     bool frameCondition = true;
3347     for (size_t i = 0; i < frameRateRange.size(); i++) {
3348         MEDIA_DEBUG_LOG("CaptureSession::SetFrameRateRange:index:%{public}zu->%{public}d", i, frameRateRange[i]);
3349         if (frameRateRange[i] > CONTROL_CENTER_FPS_MAX) {
3350             frameCondition = false;
3351         }
3352     }
3353     CameraManager::GetInstance()->SetControlCenterFrameCondition(frameCondition);
3354     this->UnlockForControl();
3355     CHECK_RETURN_RET_ELOG(!isSuccess, CameraErrorCode::SERVICE_FATL_ERROR, "Failed to SetFrameRateRange ");
3356     return CameraErrorCode::SUCCESS;
3357 }
3358 
3359 
CanSetFrameRateRange(int32_t minFps,int32_t maxFps,CaptureOutput * curOutput)3360 bool CaptureSession::CanSetFrameRateRange(int32_t minFps, int32_t maxFps, CaptureOutput* curOutput)
3361 {
3362     // LCOV_EXCL_START
3363     MEDIA_WARNING_LOG("CaptureSession::CanSetFrameRateRange can not set frame rate range for %{public}d mode",
3364                       GetMode());
3365     return false;
3366     // LCOV_EXCL_STOP
3367 }
3368 
CanSetFrameRateRangeForOutput(int32_t minFps,int32_t maxFps,CaptureOutput * curOutput)3369 bool CaptureSession::CanSetFrameRateRangeForOutput(int32_t minFps, int32_t maxFps, CaptureOutput* curOutput)
3370 {
3371     std::lock_guard<std::mutex> lock(captureOutputSetsMutex_);
3372     int32_t defaultFpsNumber = 0;
3373     int32_t minFpsIndex = 0;
3374     int32_t maxFpsIndex = 1;
3375     for (auto output : captureOutputSets_) {
3376         auto item = output.promote();
3377         if (static_cast<CaptureOutput*>(item.GetRefPtr()) == curOutput) {
3378             continue;
3379         }
3380         std::vector<int32_t> currentFrameRange = {defaultFpsNumber, defaultFpsNumber};
3381         // LCOV_EXCL_START
3382         switch (output->GetOutputType()) {
3383             case CaptureOutputType::CAPTURE_OUTPUT_TYPE_VIDEO: {
3384                 sptr<VideoOutput> videoOutput = (sptr<VideoOutput>&)item;
3385                 currentFrameRange = videoOutput->GetFrameRateRange();
3386                 break;
3387             }
3388             case CaptureOutputType::CAPTURE_OUTPUT_TYPE_PREVIEW: {
3389                 sptr<PreviewOutput> previewOutput = (sptr<PreviewOutput>&)item;
3390                 currentFrameRange = previewOutput->GetFrameRateRange();
3391                 break;
3392             }
3393             default:
3394                 continue;
3395         }
3396         if (currentFrameRange[minFpsIndex] != defaultFpsNumber &&
3397             currentFrameRange[maxFpsIndex] != defaultFpsNumber) {
3398             MEDIA_DEBUG_LOG("The frame rate range conflict needs to be checked.");
3399             if (!CheckFrameRateRangeWithCurrentFps(currentFrameRange[minFpsIndex],
3400                                                    currentFrameRange[maxFpsIndex],
3401                                                    minFps, maxFps)) {
3402                 return false;
3403             };
3404         }
3405         // LCOV_EXCL_STOP
3406     }
3407     return true;
3408 }
3409 
IsSessionConfiged()3410 bool CaptureSession::IsSessionConfiged()
3411 {
3412     bool isSessionConfiged = false;
3413     auto captureSession = GetCaptureSession();
3414     if (captureSession) {
3415         CaptureSessionState currentState;
3416         captureSession->GetSessionState(currentState);
3417         isSessionConfiged = (currentState == CaptureSessionState::SESSION_CONFIG_INPROGRESS);
3418     } else {
3419         MEDIA_ERR_LOG("CaptureSession::IsSessionConfiged captureSession is nullptr");
3420     }
3421     return isSessionConfiged;
3422 }
3423 
IsSessionCommited()3424 bool CaptureSession::IsSessionCommited()
3425 {
3426     bool isCommitConfig = false;
3427     auto captureSession = GetCaptureSession();
3428     if (captureSession) {
3429         CaptureSessionState currentState;
3430         captureSession->GetSessionState(currentState);
3431         isCommitConfig = (currentState == CaptureSessionState::SESSION_CONFIG_COMMITTED)
3432             || (currentState == CaptureSessionState::SESSION_STARTED);
3433     } else {
3434         MEDIA_ERR_LOG("CaptureSession::IsSessionCommited captureSession is nullptr");
3435     }
3436     return isCommitConfig;
3437 }
3438 
IsSessionStarted()3439 bool CaptureSession::IsSessionStarted()
3440 {
3441     bool isStarted = false;
3442     auto captureSession = GetCaptureSession();
3443     if (captureSession) {
3444         CaptureSessionState currentState;
3445         captureSession->GetSessionState(currentState);
3446         isStarted = (currentState == CaptureSessionState::SESSION_STARTED);
3447     } else {
3448         MEDIA_ERR_LOG("CaptureSession::IsSessionStarted captureSession is nullptr");
3449     }
3450     return isStarted;
3451 }
3452 
CalculateExposureValue(float exposureValue)3453 int32_t CaptureSession::CalculateExposureValue(float exposureValue)
3454 {
3455     camera_metadata_item_t item;
3456     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
3457     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::OPERATION_NOT_ALLOWED,
3458         "CalculateExposureValue camera metadata is null");
3459     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_AE_COMPENSATION_STEP, &item);
3460     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::OPERATION_NOT_ALLOWED,
3461         "CaptureSession::Get Ae Compensation step Failed with return code %{public}d", ret);
3462 
3463     int32_t stepNumerator = item.data.r->numerator;
3464     int32_t stepDenominator = item.data.r->denominator;
3465     float stepsPerEv = static_cast<float>(stepDenominator) / static_cast<float>(stepNumerator);
3466     MEDIA_DEBUG_LOG("Exposure step numerator: %{public}d, denominatormax: %{public}d, stepsPerEv: %{public}f",
3467         stepNumerator, stepDenominator, stepsPerEv);
3468 
3469     int32_t exposureCompensation = static_cast<int32_t>(stepsPerEv * exposureValue);
3470     MEDIA_DEBUG_LOG("exposureCompensation: %{public}d", exposureCompensation);
3471     return exposureCompensation;
3472 }
3473 
GetSupportedColorSpaceInfo()3474 ColorSpaceInfo CaptureSession::GetSupportedColorSpaceInfo()
3475 {
3476     ColorSpaceInfo colorSpaceInfo = {};
3477     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), colorSpaceInfo,
3478         "CaptureSession::GetSupportedColorSpaceInfo Session is not Commited");
3479     auto inputDevice = GetInputDevice();
3480     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), colorSpaceInfo,
3481         "CaptureSession::GetSupportedColorSpaceInfo camera device is null");
3482     sptr<CameraDevice> cameraDevNow = inputDevice->GetCameraDeviceInfo();
3483     if (cameraDevNow != nullptr && cameraDevNow->isConcurrentLimted_ == 1) {
3484         return cameraDevNow->limtedCapabilitySave_.colorspaces;
3485     }
3486     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
3487     CHECK_RETURN_RET_ELOG(metadata == nullptr, colorSpaceInfo,
3488         "GetSupportedColorSpaceInfo camera metadata is null");
3489     camera_metadata_item_t item;
3490     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_AVAILABLE_COLOR_SPACES, &item);
3491     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, colorSpaceInfo,
3492         "CaptureSession::GetSupportedColorSpaceInfo Failed, return code %{public}d", ret);
3493 
3494     std::shared_ptr<ColorSpaceInfoParse> colorSpaceParse = std::make_shared<ColorSpaceInfoParse>();
3495     colorSpaceParse->getColorSpaceInfo(item.data.i32, item.count, colorSpaceInfo); // 解析tag中带的色彩空间信息
3496     return colorSpaceInfo;
3497 }
3498 
CheckColorSpaceForSystemApp(ColorSpace colorSpace,SceneMode sceneMode)3499 bool CheckColorSpaceForSystemApp(ColorSpace colorSpace, SceneMode sceneMode)
3500 {
3501     return CameraSecurity::CheckSystemApp() ||
3502         !(colorSpace == ColorSpace::BT2020_HLG && sceneMode == SceneMode::CAPTURE);
3503 }
3504 
GetSupportedColorSpaces()3505 std::vector<ColorSpace> CaptureSession::GetSupportedColorSpaces()
3506 {
3507     std::vector<ColorSpace> supportedColorSpaces = {};
3508     ColorSpaceInfo colorSpaceInfo = GetSupportedColorSpaceInfo();
3509     CHECK_RETURN_RET_ELOG(colorSpaceInfo.modeCount == 0, supportedColorSpaces,
3510         "CaptureSession::GetSupportedColorSpaces Failed, colorSpaceInfo is null");
3511 
3512     for (uint32_t i = 0; i < colorSpaceInfo.modeCount; i++) {
3513         if (GetMode() != colorSpaceInfo.modeInfo[i].modeType) {
3514             continue;
3515         }
3516         MEDIA_DEBUG_LOG("CaptureSession::GetSupportedColorSpaces modeType %{public}d found.", GetMode());
3517         std::vector<int32_t> colorSpaces = colorSpaceInfo.modeInfo[i].streamInfo[0].colorSpaces;
3518         supportedColorSpaces.reserve(colorSpaces.size());
3519         for (uint32_t j = 0; j < colorSpaces.size(); j++) {
3520             auto itr = g_metaColorSpaceMap_.find(static_cast<CM_ColorSpaceType>(colorSpaces[j]));
3521             CHECK_EXECUTE(itr != g_metaColorSpaceMap_.end() && CheckColorSpaceForSystemApp(itr->second, GetMode()),
3522                 supportedColorSpaces.emplace_back(itr->second));
3523         }
3524         return supportedColorSpaces;
3525     }
3526     MEDIA_ERR_LOG("CaptureSession::GetSupportedColorSpaces no colorSpaces info for mode %{public}d", GetMode());
3527     return supportedColorSpaces;
3528 }
3529 
GetActiveColorSpace(ColorSpace & colorSpace)3530 int32_t CaptureSession::GetActiveColorSpace(ColorSpace& colorSpace)
3531 {
3532     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
3533         "CaptureSession::GetActiveColorSpace Session is not Commited");
3534 
3535     int32_t errCode = CAMERA_UNKNOWN_ERROR;
3536     auto captureSession = GetCaptureSession();
3537     CHECK_RETURN_RET_ELOG(captureSession == nullptr, ServiceToCameraError(errCode),
3538         "CaptureSession::GetActiveColorSpace() captureSession is nullptr");
3539     int32_t curColorSpace = 0;
3540     errCode = captureSession->GetActiveColorSpace(curColorSpace);
3541     if (errCode != CAMERA_OK) {
3542         MEDIA_ERR_LOG("Failed to GetActiveColorSpace! %{public}d", errCode);
3543     } else {
3544         colorSpace = static_cast<ColorSpace>(curColorSpace);
3545         MEDIA_INFO_LOG("CaptureSession::GetActiveColorSpace %{public}d", colorSpace);
3546     }
3547     return ServiceToCameraError(errCode);
3548 }
3549 
IsControlCenterSupported()3550 bool CaptureSession::IsControlCenterSupported()
3551 {
3552     bool isSupported = false;
3553     MEDIA_INFO_LOG("CaptureSession::IsControlCenterSupported");
3554 
3555     bool controlCenterPrecondition = CameraManager::GetInstance()->GetControlCenterPrecondition();
3556     CHECK_RETURN_RET_ELOG(!controlCenterPrecondition, false,
3557         "CaptureSession::IsControlCenterSupported controlCenterPrecondition false");
3558 
3559     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata = GetMetadata();
3560     CHECK_RETURN_RET_ELOG(metadata == nullptr, isSupported, "metadata is null");
3561     camera_metadata_item_t item;
3562     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_CONTROL_CENTER_SUPPORTED, &item);
3563     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count <= 0, isSupported,
3564         "CaptureSession::IsControlCenterSupported Failed with return code %{public}d", ret);
3565     isSupported = static_cast<bool>(item.data.u8[0]);
3566     CameraManager::GetInstance()->SetIsControlCenterSupported(isSupported);
3567     return isSupported;
3568 }
3569 
GetSupportedEffectTypes()3570 std::vector<ControlCenterEffectType> CaptureSession::GetSupportedEffectTypes()
3571 {
3572     std::vector<ControlCenterEffectType> supportedEffectType = {};
3573     bool isSupported = CameraManager::GetInstance()->GetIsControlCenterSupported();
3574     CHECK_RETURN_RET_ELOG(!isSupported, {}, "Current status does not support control center.");
3575     MEDIA_INFO_LOG("CaptureSession::GetSupportedEffectTypes");
3576     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata = GetMetadata();
3577     CHECK_RETURN_RET_ELOG(metadata == nullptr, supportedEffectType, "metadata is null");
3578     camera_metadata_item_t item;
3579     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_CONTROL_CENTER_EFFECT_TYPE, &item);
3580     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count <= 0, supportedEffectType,
3581         "CaptureSession::GetSupportedEffectTypes Failed with return code %{public}d", ret);
3582     for (uint32_t i = 0; i < item.count; i++) {
3583         supportedEffectType.emplace_back(static_cast<ControlCenterEffectType>(item.data.u8[i]));
3584     }
3585     return supportedEffectType;
3586 }
3587 
EnableControlCenter(bool isEnable)3588 void CaptureSession::EnableControlCenter(bool isEnable)
3589 {
3590     MEDIA_INFO_LOG("CaptureSession::EnableControlCenter: %{public}d", isEnable);
3591     bool isSupported = CameraManager::GetInstance()->GetIsControlCenterSupported();
3592     CHECK_RETURN_ELOG(!isSupported, "Current status does not support control center.");
3593     auto serviceProxy = CameraManager::GetInstance()->GetServiceProxy();
3594     CHECK_RETURN_ELOG(serviceProxy == nullptr,
3595         "CaptureSession::EnableControlCenter serviceProxy is null");
3596     auto ret = serviceProxy->EnableControlCenter(isEnable, true);
3597     CHECK_RETURN_ELOG(ret != CAMERA_OK,
3598         "CaptureSession::EnableControlCenter failed.");
3599     isControlCenterEnabled_ = isEnable;
3600 }
3601 
SetColorSpace(ColorSpace colorSpace)3602 int32_t CaptureSession::SetColorSpace(ColorSpace colorSpace)
3603 {
3604     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
3605         "CaptureSession::SetColorSpace Session is not Commited");
3606 
3607     auto captureSession = GetCaptureSession();
3608     CHECK_RETURN_RET_ELOG(!captureSession, CameraErrorCode::SERVICE_FATL_ERROR,
3609         "CaptureSession::SetColorSpace() captureSession is nullptr");
3610     auto itr = g_fwkColorSpaceMap_.find(colorSpace);
3611     CHECK_RETURN_RET_ELOG(itr == g_fwkColorSpaceMap_.end(), CameraErrorCode::INVALID_ARGUMENT,
3612         "CaptureSession::SetColorSpace() map failed, %{public}d", static_cast<int32_t>(colorSpace));
3613     std::vector<ColorSpace> supportedColorSpaces = GetSupportedColorSpaces();
3614     auto curColorSpace = std::find(supportedColorSpaces.begin(), supportedColorSpaces.end(),
3615         colorSpace);
3616     CHECK_RETURN_RET_ELOG(curColorSpace == supportedColorSpaces.end(), CameraErrorCode::INVALID_ARGUMENT,
3617         "CaptureSession::SetColorSpace input colorSpace not found in supportedList.");
3618     if (IsSessionConfiged()) {
3619         isColorSpaceSetted_ = true;
3620     }
3621     // 若session还未commit,则后续createStreams会把色域带下去;否则,SetColorSpace要走updateStreams
3622     MEDIA_DEBUG_LOG("CaptureSession::SetColorSpace, IsSessionCommited %{public}d", IsSessionCommited());
3623     int32_t errCode = captureSession->SetColorSpace(static_cast<int32_t>(colorSpace), IsSessionCommited());
3624     CHECK_PRINT_ELOG(errCode != CAMERA_OK, "Failed to SetColorSpace!, %{public}d", errCode);
3625     return ServiceToCameraError(errCode);
3626 }
3627 
GetSupportedColorEffects()3628 std::vector<ColorEffect> CaptureSession::GetSupportedColorEffects()
3629 {
3630     std::vector<ColorEffect> supportedColorEffects = {};
3631     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), supportedColorEffects,
3632         "CaptureSession::GetSupportedColorEffects Session is not Commited");
3633     auto inputDevice = GetInputDevice();
3634     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), supportedColorEffects,
3635         "CaptureSession::GetSupportedColorEffects camera device is null");
3636     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
3637     CHECK_RETURN_RET_ELOG(metadata == nullptr, supportedColorEffects,
3638         "GetSupportedColorEffects camera metadata is null");
3639     camera_metadata_item_t item;
3640     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_SUPPORTED_COLOR_MODES, &item);
3641     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, supportedColorEffects,
3642         "CaptureSession::GetSupportedColorEffects Failed with return code %{public}d", ret);
3643     for (uint32_t i = 0; i < item.count; i++) {
3644         auto itr = g_metaColorEffectMap_.find(static_cast<camera_xmage_color_type_t>(item.data.u8[i]));
3645         CHECK_EXECUTE(itr != g_metaColorEffectMap_.end(), supportedColorEffects.emplace_back(itr->second));
3646     }
3647     return supportedColorEffects;
3648 }
3649 
GetSensorExposureTimeRange(std::vector<uint32_t> & sensorExposureTimeRange)3650 int32_t CaptureSession::GetSensorExposureTimeRange(std::vector<uint32_t> &sensorExposureTimeRange)
3651 {
3652     sensorExposureTimeRange.clear();
3653     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
3654         "CaptureSession::GetSensorExposureTimeRange Session is not Commited");
3655     auto inputDevice = GetInputDevice();
3656     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::INVALID_ARGUMENT,
3657         "CaptureSession::GetSensorExposureTimeRange camera device is null");
3658     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata = GetMetadata();
3659     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::INVALID_ARGUMENT,
3660         "GetSensorExposureTimeRange camera metadata is null");
3661     camera_metadata_item_t item;
3662     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_SENSOR_EXPOSURE_TIME_RANGE, &item);
3663     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count == 0, CameraErrorCode::INVALID_ARGUMENT,
3664         "CaptureSession::GetSensorExposureTimeRange Failed with return code %{public}d", ret);
3665 
3666     int32_t numerator = 0;
3667     int32_t denominator = 0;
3668     uint32_t value = 0;
3669     constexpr int32_t timeUnit = 1000000;
3670     for (uint32_t i = 0; i < item.count; i++) {
3671         numerator = item.data.r[i].numerator;
3672         denominator = item.data.r[i].denominator;
3673         CHECK_RETURN_RET_ELOG(denominator == 0, CameraErrorCode::INVALID_ARGUMENT,
3674             "CaptureSession::GetSensorExposureTimeRange divide by 0! numerator=%{public}d", numerator);
3675         value = static_cast<uint32_t>(numerator / (denominator / timeUnit));
3676         MEDIA_DEBUG_LOG("CaptureSession::GetSensorExposureTimeRange numerator=%{public}d, denominator=%{public}d,"
3677                         " value=%{public}d", numerator, denominator, value);
3678         sensorExposureTimeRange.emplace_back(value);
3679     }
3680     MEDIA_INFO_LOG("CaptureSession::GetSensorExposureTimeRange range=%{public}s, len = %{public}zu",
3681                    Container2String(sensorExposureTimeRange.begin(), sensorExposureTimeRange.end()).c_str(),
3682                    sensorExposureTimeRange.size());
3683     return CameraErrorCode::SUCCESS;
3684 }
3685 
SetSensorExposureTime(uint32_t exposureTime)3686 int32_t CaptureSession::SetSensorExposureTime(uint32_t exposureTime)
3687 {
3688     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
3689         "CaptureSession::SetSensorExposureTime Session is not Commited");
3690     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
3691         "CaptureSession::SetSensorExposureTime Need to call LockForControl() before setting camera properties");
3692     MEDIA_DEBUG_LOG("CaptureSession::SetSensorExposureTime exposure: %{public}d", exposureTime);
3693     auto inputDevice = GetInputDevice();
3694     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(),
3695         CameraErrorCode::OPERATION_NOT_ALLOWED, "CaptureSession::SetSensorExposureTime camera device is null");
3696     std::vector<uint32_t> sensorExposureTimeRange;
3697     CHECK_RETURN_RET_ELOG((GetSensorExposureTimeRange(sensorExposureTimeRange) != CameraErrorCode::SUCCESS) &&
3698         sensorExposureTimeRange.empty(), CameraErrorCode::OPERATION_NOT_ALLOWED,
3699         "CaptureSession::SetSensorExposureTime range is empty");
3700     const uint32_t autoLongExposure = 0;
3701     int32_t minIndex = 0;
3702     int32_t maxIndex = 1;
3703     if (exposureTime != autoLongExposure && exposureTime < sensorExposureTimeRange[minIndex]) {
3704         MEDIA_DEBUG_LOG("CaptureSession::SetSensorExposureTime exposureTime:"
3705                         "%{public}d is lesser than minimum exposureTime: %{public}d",
3706                         exposureTime, sensorExposureTimeRange[minIndex]);
3707         exposureTime = sensorExposureTimeRange[minIndex];
3708     } else if (exposureTime > sensorExposureTimeRange[maxIndex]) {
3709         MEDIA_DEBUG_LOG("CaptureSession::SetSensorExposureTime exposureTime: "
3710                         "%{public}d is greater than maximum exposureTime: %{public}d",
3711                         exposureTime, sensorExposureTimeRange[maxIndex]);
3712         exposureTime = sensorExposureTimeRange[maxIndex];
3713     }
3714     constexpr int32_t timeUnit = 1000000;
3715     camera_rational_t value = {.numerator = exposureTime, .denominator = timeUnit};
3716     bool res = AddOrUpdateMetadata(changedMetadata_->get(), OHOS_CONTROL_SENSOR_EXPOSURE_TIME, &value, 1);
3717     wptr<CaptureSession> weakThis(this);
3718     CHECK_EXECUTE(res, AddFunctionToMap(std::to_string(OHOS_CONTROL_SENSOR_EXPOSURE_TIME), [weakThis, exposureTime]() {
3719         auto sharedThis = weakThis.promote();
3720         CHECK_RETURN_ELOG(!sharedThis, "SetSensorExposureTime session is nullptr");
3721         sharedThis->LockForControl();
3722         int32_t retCode = sharedThis->SetSensorExposureTime(exposureTime);
3723         sharedThis->UnlockForControl();
3724         CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS, sharedThis->SetDeviceCapabilityChangeStatus(true));
3725     }));
3726     CHECK_PRINT_ELOG(!res, "CaptureSession::SetSensorExposureTime Failed to set exposure compensation");
3727     exposureDurationValue_ = exposureTime;
3728     return CameraErrorCode::SUCCESS;
3729 }
3730 
GetSensorExposureTime(uint32_t & exposureTime)3731 int32_t CaptureSession::GetSensorExposureTime(uint32_t &exposureTime)
3732 {
3733     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
3734         "CaptureSession::GetSensorExposureTime Session is not Commited");
3735     auto inputDevice = GetInputDevice();
3736     CHECK_RETURN_RET_ELOG(!inputDevice, CameraErrorCode::INVALID_ARGUMENT,
3737         "CaptureSession::GetSensorExposureTime camera device is null");
3738     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
3739     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, CameraErrorCode::INVALID_ARGUMENT,
3740         "CaptureSession::GetSensorExposureTime camera deviceInfo is null");
3741     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata = inputDeviceInfo->GetCachedMetadata();
3742     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::INVALID_ARGUMENT,
3743         "GetSensorExposureTime camera metadata is null");
3744     camera_metadata_item_t item;
3745     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_SENSOR_EXPOSURE_TIME, &item);
3746     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::INVALID_ARGUMENT,
3747         "CaptureSession::GetSensorExposureTime Failed with return code %{public}d", ret);
3748     // LCOV_EXCL_START
3749     exposureTime = item.data.ui32[0];
3750     MEDIA_DEBUG_LOG("CaptureSession::GetSensorExposureTime exposureTime: %{public}d", exposureTime);
3751     return CameraErrorCode::SUCCESS;
3752     // LCOV_EXCL_STOP
3753 }
3754 
IsMacroSupported()3755 bool CaptureSession::IsMacroSupported()
3756 {
3757     CAMERA_SYNC_TRACE;
3758     MEDIA_DEBUG_LOG("Enter IsMacroSupported");
3759 
3760     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), false,
3761         "CaptureSession::IsMacroSupported Session is not Commited");
3762     auto inputDevice = GetInputDevice();
3763     CHECK_RETURN_RET_ELOG(inputDevice == nullptr, false, "CaptureSession::IsMacroSupported camera device is null");
3764     auto deviceInfo = inputDevice->GetCameraDeviceInfo();
3765     CHECK_RETURN_RET_ELOG(deviceInfo == nullptr, false,
3766         "CaptureSession::IsMacroSupported camera deviceInfo is null");
3767 
3768     if (supportSpecSearch_) {
3769         MEDIA_DEBUG_LOG("spec search enter");
3770         auto abilityContainer = GetCameraAbilityContainer();
3771         if (abilityContainer) {
3772             bool isSupport = abilityContainer->IsMacroSupported();
3773             MEDIA_INFO_LOG("spec search result: %{public}d", static_cast<int32_t>(isSupport));
3774             return isSupport;
3775         } else {
3776             MEDIA_ERR_LOG("spec search abilityContainer is null");
3777             return false;
3778         }
3779     }
3780     // LCOV_EXCL_START
3781     std::shared_ptr<Camera::CameraMetadata> metadata = deviceInfo->GetCachedMetadata();
3782     CHECK_RETURN_RET_ELOG(metadata == nullptr, false,
3783         "IsMacroSupported camera metadata is null");
3784     camera_metadata_item_t item;
3785     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_CAMERA_MACRO_SUPPORTED, &item);
3786     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count <= 0, false,
3787         "CaptureSession::IsMacroSupported Failed with return code %{public}d", ret);
3788     auto supportResult = static_cast<camera_macro_supported_type_t>(*item.data.i32);
3789     return supportResult == OHOS_CAMERA_MACRO_SUPPORTED;
3790     // LCOV_EXCL_STOP
3791 }
3792 
EnableMacro(bool isEnable)3793 int32_t CaptureSession::EnableMacro(bool isEnable)
3794 {
3795     CAMERA_SYNC_TRACE;
3796     MEDIA_DEBUG_LOG("Enter EnableMacro, isEnable:%{public}d", isEnable);
3797     CHECK_RETURN_RET_ELOG(!IsMacroSupported(), CameraErrorCode::OPERATION_NOT_ALLOWED,
3798         "EnableMacro IsMacroSupported is false");
3799     // LCOV_EXCL_START
3800     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
3801         "CaptureSession Failed EnableMacro!, session not commited");
3802     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
3803         "CaptureSession::EnableMacro Need to call LockForControl() before setting camera properties");
3804     uint8_t enableValue = static_cast<uint8_t>(isEnable ? OHOS_CAMERA_MACRO_ENABLE : OHOS_CAMERA_MACRO_DISABLE);
3805     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_CAMERA_MACRO, &enableValue, 1);
3806     if (!status) {
3807         MEDIA_ERR_LOG("CaptureSession::EnableMacro Failed to enable macro");
3808     } else {
3809         auto abilityContainer = GetCameraAbilityContainer();
3810         CHECK_EXECUTE(abilityContainer && supportSpecSearch_, abilityContainer->FilterByMacro(isEnable));
3811     }
3812     isSetMacroEnable_ = isEnable;
3813     return CameraErrorCode::SUCCESS;
3814     // LCOV_EXCL_STOP
3815 }
3816 
GetMoonCaptureBoostFeature()3817 std::shared_ptr<MoonCaptureBoostFeature> CaptureSession::GetMoonCaptureBoostFeature()
3818 {
3819     auto inputDevice = GetInputDevice();
3820     CHECK_RETURN_RET(inputDevice == nullptr, nullptr);
3821     auto deviceInfo = inputDevice->GetCameraDeviceInfo();
3822     CHECK_RETURN_RET(deviceInfo == nullptr, nullptr);
3823     auto deviceAbility = deviceInfo->GetCachedMetadata();
3824     CHECK_RETURN_RET(deviceAbility == nullptr, nullptr);
3825 
3826     auto currentMode = GetMode();
3827     {
3828         std::lock_guard<std::mutex> lock(moonCaptureBoostFeatureMutex_);
3829         if (moonCaptureBoostFeature_ == nullptr || moonCaptureBoostFeature_->GetRelatedMode() != currentMode) {
3830             moonCaptureBoostFeature_ = std::make_shared<MoonCaptureBoostFeature>(currentMode, deviceAbility);
3831         }
3832         return moonCaptureBoostFeature_;
3833     }
3834 }
3835 
IsMoonCaptureBoostSupported()3836 bool CaptureSession::IsMoonCaptureBoostSupported()
3837 {
3838     CAMERA_SYNC_TRACE;
3839     MEDIA_DEBUG_LOG("Enter IsMoonCaptureBoostSupported");
3840     auto feature = GetMoonCaptureBoostFeature();
3841     CHECK_RETURN_RET(feature == nullptr, false);
3842     return feature->IsSupportedMoonCaptureBoostFeature();
3843 }
3844 
EnableMoonCaptureBoost(bool isEnable)3845 int32_t CaptureSession::EnableMoonCaptureBoost(bool isEnable)
3846 {
3847     CAMERA_SYNC_TRACE;
3848     MEDIA_DEBUG_LOG("Enter EnableMoonCaptureBoost, isEnable:%{public}d", isEnable);
3849     CHECK_RETURN_RET_ELOG(!IsMoonCaptureBoostSupported(), CameraErrorCode::OPERATION_NOT_ALLOWED,
3850         "EnableMoonCaptureBoost IsMoonCaptureBoostSupported is false");
3851     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
3852         "CaptureSession Failed EnableMoonCaptureBoost!, session not commited");
3853     // LCOV_EXCL_START
3854     uint8_t enableValue = static_cast<uint8_t>(isEnable ? 1 : 0);
3855     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_MOON_CAPTURE_BOOST, &enableValue, 1);
3856     CHECK_PRINT_ELOG(!status, "CaptureSession::EnableMoonCaptureBoost failed to enable moon capture boost");
3857     isSetMoonCaptureBoostEnable_ = isEnable;
3858     return CameraErrorCode::SUCCESS;
3859     // LCOV_EXCL_STOP
3860 }
3861 
IsLowLightBoostSupported()3862 bool CaptureSession::IsLowLightBoostSupported()
3863 {
3864     CAMERA_SYNC_TRACE;
3865     MEDIA_DEBUG_LOG("Enter IsLowLightBoostSupported");
3866     CHECK_RETURN_RET_ELOG(!(IsSessionConfiged() || IsSessionCommited()), false,
3867         "CaptureSession::IsLowLightBoostSupported Session is not Commited!");
3868     auto inputDevice = GetInputDevice();
3869     CHECK_RETURN_RET_ELOG(
3870         inputDevice == nullptr, false, "CaptureSession::IsLowLightBoostSupported camera device is null");
3871     auto deviceInfo = inputDevice->GetCameraDeviceInfo();
3872     CHECK_RETURN_RET_ELOG(
3873         deviceInfo == nullptr, false, "CaptureSession::IsLowLightBoostSupported camera deviceInfo is null");
3874     std::shared_ptr<Camera::CameraMetadata> metadata = deviceInfo->GetCachedMetadata();
3875     CHECK_RETURN_RET_ELOG(metadata == nullptr, false,
3876         "IsLowLightBoostSupported camera metadata is null");
3877     camera_metadata_item_t item;
3878     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_LOW_LIGHT_BOOST, &item);
3879     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count <= 0, false,
3880         "CaptureSession::IsLowLightBoostSupported Failed with return code %{public}d", ret);
3881     const uint32_t step = 3;
3882     for (uint32_t i = 0; i < item.count - 1; i += step) {
3883         CHECK_RETURN_RET(GetMode() == item.data.i32[i] && item.data.i32[i + 1] == 1, true);
3884     }
3885     return false;
3886 }
3887 
3888 
EnableLowLightBoost(bool isEnable)3889 int32_t CaptureSession::EnableLowLightBoost(bool isEnable)
3890 {
3891     CAMERA_SYNC_TRACE;
3892     MEDIA_DEBUG_LOG("Enter EnableLowLightBoost, isEnable:%{public}d", isEnable);
3893     CHECK_RETURN_RET_ELOG(
3894         !IsLowLightBoostSupported(), CameraErrorCode::OPERATION_NOT_ALLOWED, "Not support LowLightBoost");
3895     // LCOV_EXCL_START
3896     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG, "Session is not Commited!");
3897     uint8_t enableValue = static_cast<uint8_t>(isEnable ? 1 : 0);
3898     if (!AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_LOW_LIGHT_BOOST, &enableValue, 1)) {
3899         MEDIA_ERR_LOG("CaptureSession::EnableLowLightBoost failed to enable low light boost");
3900     } else {
3901         isSetLowLightBoostEnable_ = isEnable;
3902     }
3903     return CameraErrorCode::SUCCESS;
3904     // LCOV_EXCL_STOP
3905 }
3906 
EnableLowLightDetection(bool isEnable)3907 int32_t CaptureSession::EnableLowLightDetection(bool isEnable)
3908 {
3909     CAMERA_SYNC_TRACE;
3910     MEDIA_DEBUG_LOG("Enter EnableLowLightDetection, isEnable:%{public}d", isEnable);
3911     CHECK_RETURN_RET_ELOG(
3912         !IsLowLightBoostSupported(), CameraErrorCode::OPERATION_NOT_ALLOWED, "Not support LowLightBoost");
3913     // LCOV_EXCL_START
3914     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG, "Session is not Commited!");
3915     uint8_t enableValue = static_cast<uint8_t>(isEnable ? 1 : 0);
3916     CHECK_PRINT_ELOG(!AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_LOW_LIGHT_DETECT, &enableValue, 1),
3917         "CaptureSession::EnableLowLightDetection failed to enable low light detect");
3918     return CameraErrorCode::SUCCESS;
3919     // LCOV_EXCL_STOP
3920 }
3921 
IsFeatureSupported(SceneFeature feature)3922 bool CaptureSession::IsFeatureSupported(SceneFeature feature)
3923 {
3924     switch (static_cast<SceneFeature>(feature)) {
3925         case FEATURE_MACRO:
3926             return IsMacroSupported();
3927             break;
3928         case FEATURE_MOON_CAPTURE_BOOST:
3929             return IsMoonCaptureBoostSupported();
3930             break;
3931         case FEATURE_TRIPOD_DETECTION:
3932             return IsTripodDetectionSupported();
3933             break;
3934         case FEATURE_LOW_LIGHT_BOOST:
3935             return IsLowLightBoostSupported();
3936             break;
3937         default:
3938             MEDIA_ERR_LOG("CaptureSession::IsFeatureSupported sceneFeature is unhandled %{public}d", feature);
3939             break;
3940     }
3941     return false;
3942 }
3943 
EnableFeature(SceneFeature feature,bool isEnable)3944 int32_t CaptureSession::EnableFeature(SceneFeature feature, bool isEnable)
3945 {
3946     LockForControl();
3947     int32_t retCode;
3948     switch (static_cast<SceneFeature>(feature)) {
3949         case FEATURE_MACRO:
3950             retCode = EnableMacro(isEnable);
3951             break;
3952         case FEATURE_MOON_CAPTURE_BOOST:
3953             retCode = EnableMoonCaptureBoost(isEnable);
3954             break;
3955         case FEATURE_TRIPOD_DETECTION:
3956             retCode = EnableTripodStabilization(isEnable);
3957             break;
3958         case FEATURE_LOW_LIGHT_BOOST:
3959             retCode = EnableLowLightBoost(isEnable);
3960             break;
3961         default:
3962             retCode = INVALID_ARGUMENT;
3963     }
3964     UnlockForControl();
3965     return retCode;
3966 }
3967 
IsMovingPhotoSupported()3968 bool CaptureSession::IsMovingPhotoSupported()
3969 {
3970     CAMERA_SYNC_TRACE;
3971     MEDIA_DEBUG_LOG("Enter IsMovingPhotoSupported");
3972     auto inputDevice = GetInputDevice();
3973     CHECK_RETURN_RET_ELOG(inputDevice == nullptr, false,
3974         "CaptureSession::IsMovingPhotoSupported camera device is null");
3975     auto deviceInfo = inputDevice->GetCameraDeviceInfo();
3976     CHECK_RETURN_RET_ELOG(deviceInfo == nullptr, false,
3977         "CaptureSession::IsMovingPhotoSupported camera deviceInfo is null");
3978     std::shared_ptr<Camera::CameraMetadata> metadata = deviceInfo->GetCachedMetadata();
3979     CHECK_RETURN_RET_ELOG(metadata == nullptr, false,
3980         "IsMovingPhotoSupported camera metadata is null");
3981     camera_metadata_item_t metadataItem;
3982     vector<int32_t> modes = {};
3983     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_MOVING_PHOTO, &metadataItem);
3984     if (ret == CAM_META_SUCCESS && metadataItem.count > 0) {
3985         uint32_t step = 3;
3986         for (uint32_t index = 0; index < metadataItem.count - 1;) {
3987             CHECK_EXECUTE(metadataItem.data.i32[index + 1] == 1, modes.push_back(metadataItem.data.i32[index]));
3988             MEDIA_DEBUG_LOG("IsMovingPhotoSupported mode:%{public}d", metadataItem.data.i32[index]);
3989             index += step;
3990         }
3991     }
3992     return std::find(modes.begin(), modes.end(), GetMode()) != modes.end();
3993 }
3994 
EnableMovingPhoto(bool isEnable)3995 int32_t CaptureSession::EnableMovingPhoto(bool isEnable)
3996 {
3997     CAMERA_SYNC_TRACE;
3998     MEDIA_INFO_LOG("Enter EnableMovingPhoto, isEnable:%{public}d", isEnable);
3999     CHECK_RETURN_RET_ELOG(!IsMovingPhotoSupported(), CameraErrorCode::SERVICE_FATL_ERROR,
4000         "IsMovingPhotoSupported is false");
4001     CHECK_RETURN_RET_ELOG(!(IsSessionConfiged() || IsSessionCommited()), CameraErrorCode::SERVICE_FATL_ERROR,
4002         "CaptureSession Failed EnableMovingPhoto!, session not configed");
4003     // LCOV_EXCL_START
4004     uint8_t enableValue = static_cast<uint8_t>(isEnable ? OHOS_CAMERA_MOVING_PHOTO_ON : OHOS_CAMERA_MOVING_PHOTO_OFF);
4005     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_MOVING_PHOTO, &enableValue, 1);
4006     wptr<CaptureSession> weakThis(this);
4007     CHECK_EXECUTE(status, AddFunctionToMap(std::to_string(OHOS_CONTROL_MOVING_PHOTO), [weakThis, isEnable]() {
4008         auto sharedThis = weakThis.promote();
4009         CHECK_RETURN_ELOG(!sharedThis, "EnableMovingPhoto session is nullptr");
4010         sharedThis->LockForControl();
4011         int32_t retCode = sharedThis->EnableMovingPhoto(isEnable);
4012         sharedThis->UnlockForControl();
4013         CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS, sharedThis->SetDeviceCapabilityChangeStatus(true));
4014     }));
4015     CHECK_PRINT_ELOG(!status, "CaptureSession::EnableMovingPhoto Failed to enable");
4016     auto captureSession = GetCaptureSession();
4017     CHECK_RETURN_RET_ELOG(captureSession == nullptr, CameraErrorCode::INVALID_ARGUMENT,
4018         "CaptureSession::EnableMovingPhoto() captureSession is nullptr");
4019     int32_t errCode = captureSession->EnableMovingPhoto(isEnable);
4020     CHECK_RETURN_RET_ELOG(errCode != CAMERA_OK, errCode, "Failed to EnableMovingPhoto!, %{public}d", errCode);
4021     isMovingPhotoEnabled_ = isEnable;
4022     return CameraErrorCode::SUCCESS;
4023     // LCOV_EXCL_STOP
4024 }
4025 
IsMovingPhotoEnabled()4026 bool CaptureSession::IsMovingPhotoEnabled()
4027 {
4028     return isMovingPhotoEnabled_;
4029 }
4030 
EnableMovingPhotoMirror(bool isMirror,bool isConfig)4031 int32_t CaptureSession::EnableMovingPhotoMirror(bool isMirror, bool isConfig)
4032 {
4033     CAMERA_SYNC_TRACE;
4034     MEDIA_INFO_LOG("EnableMovingPhotoMirror enter, isMirror: %{public}d", isMirror);
4035     CHECK_RETURN_RET_ELOG(
4036         !IsMovingPhotoSupported(), CameraErrorCode::SERVICE_FATL_ERROR, "IsMovingPhotoSupported is false");
4037     auto captureSession = GetCaptureSession();
4038     CHECK_RETURN_RET_ELOG(!captureSession, CameraErrorCode::SERVICE_FATL_ERROR,
4039         "CaptureSession::StartMovingPhotoCapture captureSession is nullptr");
4040     // LCOV_EXCL_START
4041     int32_t errCode = captureSession->EnableMovingPhotoMirror(isMirror, isConfig);
4042     CHECK_PRINT_ELOG(errCode != CAMERA_OK, "Failed to StartMovingPhotoCapture!, %{public}d", errCode);
4043     return CameraErrorCode::SUCCESS;
4044     // LCOV_EXCL_STOP
4045 }
4046 
SetMoonCaptureBoostStatusCallback(std::shared_ptr<MoonCaptureBoostStatusCallback> callback)4047 void CaptureSession::SetMoonCaptureBoostStatusCallback(std::shared_ptr<MoonCaptureBoostStatusCallback> callback)
4048 {
4049     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
4050     moonCaptureBoostStatusCallback_ = callback;
4051     return;
4052 }
4053 
ProcessMacroStatusChange(const std::shared_ptr<OHOS::Camera::CameraMetadata> & result)4054 void CaptureSession::ProcessMacroStatusChange(const std::shared_ptr<OHOS::Camera::CameraMetadata>& result)
4055     __attribute__((no_sanitize("cfi")))
4056 {
4057     CAMERA_SYNC_TRACE;
4058     MEDIA_DEBUG_LOG("Entry ProcessMacroStatusChange");
4059 
4060     // To avoid macroStatusCallback_ change pointed value occur multithread problem, copy pointer first.
4061     auto statusCallback = GetMacroStatusCallback();
4062     if (statusCallback == nullptr) {
4063         MEDIA_DEBUG_LOG("CaptureSession::ProcessMacroStatusChange statusCallback is null");
4064         return;
4065     }
4066     camera_metadata_item_t item;
4067     common_metadata_header_t* metadata = result->get();
4068     int ret = Camera::FindCameraMetadataItem(metadata, OHOS_CAMERA_MACRO_STATUS, &item);
4069     if (ret != CAM_META_SUCCESS || item.count <= 0) {
4070         MEDIA_DEBUG_LOG("Camera not support macro mode");
4071         return;
4072     }
4073     auto isMacroActive = static_cast<bool>(item.data.u8[0]);
4074     MEDIA_DEBUG_LOG("Macro active: %{public}d", isMacroActive);
4075     auto macroStatus =
4076         isMacroActive ? MacroStatusCallback::MacroStatus::ACTIVE : MacroStatusCallback::MacroStatus::IDLE;
4077     if (macroStatus == statusCallback->currentStatus) {
4078         MEDIA_DEBUG_LOG("Macro mode: no change");
4079         return;
4080     }
4081     statusCallback->currentStatus = macroStatus;
4082     statusCallback->OnMacroStatusChanged(macroStatus);
4083 }
4084 
ProcessMoonCaptureBoostStatusChange(const std::shared_ptr<OHOS::Camera::CameraMetadata> & result)4085 void CaptureSession::ProcessMoonCaptureBoostStatusChange(const std::shared_ptr<OHOS::Camera::CameraMetadata>& result)
4086     __attribute__((no_sanitize("cfi")))
4087 {
4088     CAMERA_SYNC_TRACE;
4089     MEDIA_DEBUG_LOG("Entry ProcessMoonCaptureBoostStatusChange");
4090 
4091     auto statusCallback = GetMoonCaptureBoostStatusCallback();
4092     auto featureStatusCallback = GetFeatureDetectionStatusCallback();
4093     if (statusCallback == nullptr &&
4094         (featureStatusCallback == nullptr ||
4095             !featureStatusCallback->IsFeatureSubscribed(SceneFeature::FEATURE_MOON_CAPTURE_BOOST))) {
4096         MEDIA_DEBUG_LOG("CaptureSession::ProcessMoonCaptureBoostStatusChange statusCallback and "
4097                         "featureDetectionStatusChangedCallback are null");
4098         return;
4099     }
4100 
4101     camera_metadata_item_t item;
4102     common_metadata_header_t* metadata = result->get();
4103     int ret = Camera::FindCameraMetadataItem(metadata, OHOS_STATUS_MOON_CAPTURE_DETECTION, &item);
4104     if (ret != CAM_META_SUCCESS || item.count <= 0) {
4105         MEDIA_DEBUG_LOG("Camera not support moon capture detection");
4106         return;
4107     }
4108     auto isMoonActive = static_cast<bool>(item.data.u8[0]);
4109     MEDIA_DEBUG_LOG("Moon active: %{public}d", isMoonActive);
4110 
4111     if (statusCallback != nullptr) {
4112         auto moonCaptureBoostStatus = isMoonActive ? MoonCaptureBoostStatusCallback::MoonCaptureBoostStatus::ACTIVE
4113                                                    : MoonCaptureBoostStatusCallback::MoonCaptureBoostStatus::IDLE;
4114         if (moonCaptureBoostStatus == statusCallback->currentStatus) {
4115             MEDIA_DEBUG_LOG("Moon mode: no change");
4116             return;
4117         }
4118         statusCallback->currentStatus = moonCaptureBoostStatus;
4119         statusCallback->OnMoonCaptureBoostStatusChanged(moonCaptureBoostStatus);
4120     }
4121     if (featureStatusCallback != nullptr &&
4122         featureStatusCallback->IsFeatureSubscribed(SceneFeature::FEATURE_MOON_CAPTURE_BOOST)) {
4123         // LCOV_EXCL_START
4124         auto detectStatus = isMoonActive ? FeatureDetectionStatusCallback::FeatureDetectionStatus::ACTIVE
4125                                          : FeatureDetectionStatusCallback::FeatureDetectionStatus::IDLE;
4126         if (!featureStatusCallback->UpdateStatus(SceneFeature::FEATURE_MOON_CAPTURE_BOOST, detectStatus)) {
4127             MEDIA_DEBUG_LOG("Feature detect Moon mode: no change");
4128             return;
4129         }
4130         featureStatusCallback->OnFeatureDetectionStatusChanged(SceneFeature::FEATURE_MOON_CAPTURE_BOOST, detectStatus);
4131         // LCOV_EXCL_STOP
4132     }
4133 }
4134 
ProcessLowLightBoostStatusChange(const std::shared_ptr<OHOS::Camera::CameraMetadata> & result)4135 void CaptureSession::ProcessLowLightBoostStatusChange(const std::shared_ptr<OHOS::Camera::CameraMetadata>& result)
4136 {
4137     CAMERA_SYNC_TRACE;
4138     MEDIA_DEBUG_LOG("Entry ProcessLowLightBoostStatusChange");
4139 
4140     auto featureStatusCallback = GetFeatureDetectionStatusCallback();
4141     if (featureStatusCallback == nullptr ||
4142         !featureStatusCallback->IsFeatureSubscribed(SceneFeature::FEATURE_LOW_LIGHT_BOOST)) {
4143         MEDIA_DEBUG_LOG("CaptureSession::ProcessLowLightBoostStatusChange featureStatusCallback is null");
4144         return;
4145     }
4146     // LCOV_EXCL_START
4147     camera_metadata_item_t item;
4148     common_metadata_header_t* metadata = result->get();
4149     int ret = Camera::FindCameraMetadataItem(metadata, OHOS_STATUS_LOW_LIGHT_DETECTION, &item);
4150     if (ret != CAM_META_SUCCESS || item.count <= 0) {
4151         MEDIA_DEBUG_LOG("Camera not support low light detection");
4152         return;
4153     }
4154     auto isLowLightActive = static_cast<bool>(item.data.u8[0]);
4155     MEDIA_DEBUG_LOG("LowLight active: %{public}d", isLowLightActive);
4156 
4157     auto detectStatus = isLowLightActive ? FeatureDetectionStatusCallback::FeatureDetectionStatus::ACTIVE
4158                                          : FeatureDetectionStatusCallback::FeatureDetectionStatus::IDLE;
4159     if (!featureStatusCallback->UpdateStatus(SceneFeature::FEATURE_LOW_LIGHT_BOOST, detectStatus)) {
4160         MEDIA_DEBUG_LOG("Feature detect LowLight mode: no change");
4161         return;
4162     }
4163     featureStatusCallback->OnFeatureDetectionStatusChanged(SceneFeature::FEATURE_LOW_LIGHT_BOOST, detectStatus);
4164     // LCOV_EXCL_STOP
4165 }
4166 
IsSetEnableMacro()4167 bool CaptureSession::IsSetEnableMacro()
4168 {
4169     return isSetMacroEnable_;
4170 }
4171 
ValidateOutputProfile(Profile & outputProfile,CaptureOutputType outputType)4172 bool CaptureSession::ValidateOutputProfile(Profile& outputProfile, CaptureOutputType outputType)
4173 {
4174     MEDIA_INFO_LOG(
4175         "CaptureSession::ValidateOutputProfile profile:w(%{public}d),h(%{public}d),f(%{public}d) outputType:%{public}d",
4176         outputProfile.size_.width, outputProfile.size_.height, outputProfile.format_, outputType);
4177     auto inputDevice = GetInputDevice();
4178     CHECK_RETURN_RET_ELOG(!inputDevice, false,
4179         "CaptureSession::ValidateOutputProfile Failed inputDevice is nullptr");
4180     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
4181     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, false,
4182         "CaptureSession::ValidateOutputProfile Failed inputDevice is nullptr");
4183     if (outputType == CAPTURE_OUTPUT_TYPE_METADATA) {
4184         MEDIA_INFO_LOG("CaptureSession::ValidateOutputProfile MetadataOutput");
4185         return true;
4186     }
4187     if (outputType == CAPTURE_OUTPUT_TYPE_DEPTH_DATA) {
4188         MEDIA_INFO_LOG("CaptureSession::ValidateOutputProfile DepthDataOutput");
4189         return true;
4190     }
4191     auto modeName = GetMode();
4192     auto validateOutputProfileFunc = [modeName](auto validateProfile, auto& profiles) -> bool {
4193         MEDIA_INFO_LOG("CaptureSession::ValidateOutputProfile in mode(%{public}d): "
4194                        "w(%{public}d),h(%{public}d),f(%{public}d), profiles size is:%{public}zu",
4195             static_cast<int32_t>(modeName), validateProfile.size_.width, validateProfile.size_.height,
4196             validateProfile.format_, profiles.size());
4197         bool result = std::any_of(profiles.begin(), profiles.end(), [&validateProfile](const auto& profile) {
4198             return validateProfile == profile;
4199         });
4200         CHECK_EXECUTE(result, MEDIA_INFO_LOG("CaptureSession::ValidateOutputProfile fail!"));
4201         CHECK_PRINT_ELOG(!result, "CaptureSession::ValidateOutputProfile fail! Not in the profiles set.");
4202         return result;
4203     };
4204     switch (outputType) {
4205         case CAPTURE_OUTPUT_TYPE_PREVIEW: {
4206             auto profiles = inputDeviceInfo->modePreviewProfiles_[modeName];
4207             return validateOutputProfileFunc(outputProfile, profiles);
4208         }
4209         case CAPTURE_OUTPUT_TYPE_PHOTO: {
4210             auto profiles = inputDeviceInfo->modePhotoProfiles_[modeName];
4211             return validateOutputProfileFunc(outputProfile, profiles);
4212         }
4213         case CAPTURE_OUTPUT_TYPE_VIDEO: {
4214             auto profiles = inputDeviceInfo->modeVideoProfiles_[modeName];
4215             return validateOutputProfileFunc(outputProfile, profiles);
4216         }
4217         default:
4218             MEDIA_ERR_LOG("CaptureSession::ValidateOutputProfile CaptureOutputType unknown");
4219             return false;
4220     }
4221 }
4222 
CanPreconfig(PreconfigType preconfigType,ProfileSizeRatio preconfigRatio)4223 bool CaptureSession::CanPreconfig(PreconfigType preconfigType, ProfileSizeRatio preconfigRatio)
4224 {
4225     // Default implementation return false. Only photo session and video session override this method.
4226     MEDIA_ERR_LOG("CaptureSession::CanPreconfig is not valid! Did you set the correct mode?");
4227     return false;
4228 }
4229 
Preconfig(PreconfigType preconfigType,ProfileSizeRatio preconfigRatio)4230 int32_t CaptureSession::Preconfig(PreconfigType preconfigType, ProfileSizeRatio preconfigRatio)
4231 {
4232     // Default implementation throw error. Only photo session and video session override this method.
4233     MEDIA_ERR_LOG("CaptureSession::Preconfig is not valid! Did you set the correct mode?");
4234     return CAMERA_UNSUPPORTED;
4235 }
4236 
4237 // LCOV_EXCL_START
GeneratePreconfigProfiles(PreconfigType preconfigType,ProfileSizeRatio preconfigRatio)4238 std::shared_ptr<PreconfigProfiles> CaptureSession::GeneratePreconfigProfiles(
4239     PreconfigType preconfigType, ProfileSizeRatio preconfigRatio)
4240 {
4241     // Default implementation return nullptr. Only photo session and video session override this method.
4242     MEDIA_ERR_LOG("CaptureSession::GeneratePreconfigProfiles is not valid! Did you set the correct mode?");
4243     return nullptr;
4244 }
4245 // LCOV_EXCL_STOP
4246 
EnableDeferredType(DeferredDeliveryImageType type,bool isEnableByUser)4247 void CaptureSession::EnableDeferredType(DeferredDeliveryImageType type, bool isEnableByUser)
4248 {
4249     MEDIA_INFO_LOG("CaptureSession::EnableDeferredType type:%{public}d", type);
4250     CHECK_RETURN_ELOG(IsSessionCommited(), "CaptureSession::EnableDeferredType session has committed!");
4251     this->LockForControl();
4252     CHECK_RETURN_ELOG(changedMetadata_ == nullptr, "CaptureSession::EnableDeferredType changedMetadata_ is NULL");
4253     isImageDeferred_ = false;
4254     uint8_t deferredType;
4255     switch (type) {
4256         case DELIVERY_NONE:
4257             deferredType = HDI::Camera::V1_2::NONE;
4258             break;
4259         // LCOV_EXCL_START
4260         case DELIVERY_PHOTO:
4261             deferredType = HDI::Camera::V1_2::STILL_IMAGE;
4262             isImageDeferred_ = true;
4263             break;
4264         case DELIVERY_VIDEO:
4265             deferredType = HDI::Camera::V1_2::MOVING_IMAGE;
4266             break;
4267         default:
4268             deferredType = HDI::Camera::V1_2::NONE;
4269             MEDIA_ERR_LOG("CaptureSession::EnableDeferredType not support yet.");
4270             break;
4271         // LCOV_EXCL_STOP
4272     }
4273     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_DEFERRED_IMAGE_DELIVERY, &deferredType, 1);
4274     CHECK_PRINT_ELOG(!status, "CaptureSession::enableDeferredType Failed to set type!");
4275     int32_t errCode = this->UnlockForControl();
4276     CHECK_RETURN_DLOG(errCode != CameraErrorCode::SUCCESS, "CaptureSession::EnableDeferredType Failed");
4277     isDeferTypeSetted_ = isEnableByUser;
4278 }
4279 
EnableAutoDeferredVideoEnhancement(bool isEnableByUser)4280 void CaptureSession::EnableAutoDeferredVideoEnhancement(bool isEnableByUser)
4281 {
4282     MEDIA_INFO_LOG("EnableAutoDeferredVideoEnhancement isEnableByUser:%{public}d", isEnableByUser);
4283     CHECK_RETURN_ELOG(IsSessionCommited(), "EnableAutoDeferredVideoEnhancement session has committed!");
4284     this->LockForControl();
4285     CHECK_RETURN_ELOG(changedMetadata_ == nullptr, "EnableAutoDeferredVideoEnhancement changedMetadata_ is NULL");
4286     isVideoDeferred_ = isEnableByUser;
4287     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_AUTO_DEFERRED_VIDEO_ENHANCE, &isEnableByUser, 1);
4288     CHECK_PRINT_ELOG(!status, "EnableAutoDeferredVideoEnhancement Failed to set type!");
4289     int32_t errCode = this->UnlockForControl();
4290     CHECK_PRINT_DLOG(errCode != CameraErrorCode::SUCCESS, "EnableAutoDeferredVideoEnhancement Failed");
4291 }
4292 
SetUserId()4293 void CaptureSession::SetUserId()
4294 {
4295     MEDIA_INFO_LOG("CaptureSession::SetUserId");
4296     CHECK_RETURN_ELOG(IsSessionCommited(), "CaptureSession::SetUserId session has committed!");
4297     this->LockForControl();
4298     CHECK_RETURN_ELOG(changedMetadata_ == nullptr, "CaptureSession::SetUserId changedMetadata_ is NULL");
4299     int32_t userId;
4300     int32_t uid = IPCSkeleton::GetCallingUid();
4301     AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
4302     MEDIA_INFO_LOG("CaptureSession get uid:%{public}d userId:%{public}d", uid, userId);
4303     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CAMERA_USER_ID, &userId, 1);
4304     CHECK_PRINT_ELOG(!status, "CaptureSession::SetUserId Failed!");
4305     int32_t errCode = this->UnlockForControl();
4306     CHECK_PRINT_ELOG(errCode != CameraErrorCode::SUCCESS, "CaptureSession::SetUserId Failed");
4307 }
4308 
4309 
EnableOfflinePhoto()4310 void CaptureSession::EnableOfflinePhoto()
4311 {
4312     MEDIA_INFO_LOG("CaptureSession::EnableOfflinePhoto");
4313     CHECK_RETURN_ELOG(IsSessionCommited(), "CaptureSession::EnableOfflinePhoto session has committed!");
4314     // LCOV_EXCL_START
4315     if (photoOutput_ && ((sptr<PhotoOutput> &)photoOutput_)->IsHasSwitchOfflinePhoto()) {
4316         this->LockForControl();
4317         uint8_t enableOffline = 1;
4318         bool status = AddOrUpdateMetadata(
4319             changedMetadata_, OHOS_CONTROL_CHANGETO_OFFLINE_STREAM_OPEATOR, &enableOffline, 1);
4320         MEDIA_INFO_LOG("CaptureSession::Start() enableOffline is %{public}d", enableOffline);
4321         CHECK_PRINT_ELOG(!status,
4322             "CaptureSession::CommitConfig Failed to add/update offline stream operator");
4323         this->UnlockForControl();
4324     }
4325     // LCOV_EXCL_STOP
4326 }
4327 
EnableAutoHighQualityPhoto(bool enabled)4328 int32_t CaptureSession::EnableAutoHighQualityPhoto(bool enabled)
4329 {
4330     MEDIA_INFO_LOG("CaptureSession::EnableAutoHighQualityPhoto enabled:%{public}d", enabled);
4331 
4332     this->LockForControl();
4333     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, INVALID_ARGUMENT,
4334         "CaptureSession::EnableAutoHighQualityPhoto changedMetadata_ is NULL");
4335 
4336     int32_t res = CameraErrorCode::SUCCESS;
4337     uint8_t hightQualityEnable = static_cast<uint8_t>(enabled);
4338     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_HIGH_QUALITY_MODE, &hightQualityEnable, 1);
4339     if (!status) {
4340         MEDIA_ERR_LOG("CaptureSession::EnableAutoHighQualityPhoto Failed to set type!");
4341         res = INVALID_ARGUMENT;
4342     }
4343     wptr<CaptureSession> weakThis(this);
4344     CHECK_EXECUTE(status, AddFunctionToMap(std::to_string(OHOS_CONTROL_HIGH_QUALITY_MODE), [weakThis, enabled]() {
4345         auto sharedThis = weakThis.promote();
4346         CHECK_RETURN_ELOG(!sharedThis, "EnableAutoHighQualityPhoto session is nullptr");
4347         int32_t retCode = sharedThis->EnableAutoHighQualityPhoto(enabled);
4348         CHECK_EXECUTE(retCode != CameraErrorCode::SUCCESS, sharedThis->SetDeviceCapabilityChangeStatus(true));
4349     }));
4350     res = this->UnlockForControl();
4351     CHECK_PRINT_ELOG(res != CameraErrorCode::SUCCESS, "CaptureSession::EnableAutoHighQualityPhoto Failed");
4352     return res;
4353 }
4354 
EnableAutoCloudImageEnhancement(bool enabled)4355 int32_t CaptureSession::EnableAutoCloudImageEnhancement(bool enabled)
4356 {
4357     MEDIA_INFO_LOG("CaptureSession::EnableAutoCloudImageEnhancement enabled:%{public}d", enabled);
4358 
4359     LockForControl();
4360     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, INVALID_ARGUMENT,
4361         "CaptureSession::EnableAutoCloudImageEnhancement changedMetadata_ is NULL");
4362 
4363     int32_t res = CameraErrorCode::SUCCESS;
4364     uint8_t enableAutoCloudImageEnhance = static_cast<uint8_t>(enabled); // 三目表达式处理,不使用强转
4365     bool status = AddOrUpdateMetadata(
4366         changedMetadata_, OHOS_CONTROL_AUTO_CLOUD_IMAGE_ENHANCE, &enableAutoCloudImageEnhance, 1);
4367     if (!status) {
4368         MEDIA_ERR_LOG("CaptureSession::EnableAutoCloudImageEnhancement Failed to set type!");
4369         res = INVALID_ARGUMENT;
4370     }
4371     UnlockForControl();
4372     CHECK_PRINT_ELOG(res != CameraErrorCode::SUCCESS, "CaptureSession::EnableAutoCloudImageEnhancement Failed");
4373     return res;
4374 }
4375 
ExecuteAbilityChangeCallback()4376 void CaptureSession::ExecuteAbilityChangeCallback() __attribute__((no_sanitize("cfi")))
4377 {
4378     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
4379     CHECK_EXECUTE(abilityCallback_ != nullptr, abilityCallback_->OnAbilityChange());
4380 }
4381 
SetAbilityCallback(std::shared_ptr<AbilityCallback> abilityCallback)4382 void CaptureSession::SetAbilityCallback(std::shared_ptr<AbilityCallback> abilityCallback)
4383 {
4384     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
4385     abilityCallback_ = abilityCallback;
4386 }
4387 
GetMetadata()4388 std::shared_ptr<OHOS::Camera::CameraMetadata> CaptureSession::GetMetadata()
4389 {
4390     auto inputDevice = GetInputDevice();
4391     if (inputDevice == nullptr) {
4392         MEDIA_INFO_LOG("CaptureSession::GetMetadata inputDevice is null, create default metadata");
4393         return std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
4394     }
4395     auto deviceInfo = inputDevice->GetCameraDeviceInfo();
4396     if (deviceInfo == nullptr) {
4397         MEDIA_INFO_LOG("CaptureSession::GetMetadata deviceInfo is null, create default metadata");
4398         return std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
4399     }
4400     return deviceInfo->GetCachedMetadata();
4401 }
4402 
SetARMode(bool isEnable)4403 int32_t CaptureSession::SetARMode(bool isEnable)
4404 {
4405     MEDIA_INFO_LOG("CaptureSession::SetARMode");
4406     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
4407         "CaptureSession::SetARMode Session is not Commited");
4408     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
4409         "CaptureSession::SetARMode Need to call LockForControl() before setting camera properties");
4410     uint8_t value = isEnable ? 1 : 0;
4411     bool status = AddOrUpdateMetadata(changedMetadata_, HAL_CUSTOM_AR_MODE, &value, 1);
4412     CHECK_RETURN_RET_ELOG(!status, CameraErrorCode::SUCCESS, "CaptureSession::SetARMode Failed to set ar mode");
4413     return CameraErrorCode::SUCCESS;
4414 }
4415 
GetSensorSensitivityRange(std::vector<int32_t> & sensitivityRange)4416 int32_t CaptureSession::GetSensorSensitivityRange(std::vector<int32_t> &sensitivityRange)
4417 {
4418     MEDIA_INFO_LOG("CaptureSession::GetSensorSensitivityRange");
4419     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
4420         "CaptureSession::GetSensorSensitivity fail due to Session is not Commited");
4421     auto inputDevice = GetInputDevice();
4422     CHECK_RETURN_RET_ELOG(!inputDevice, CameraErrorCode::INVALID_ARGUMENT,
4423         "CaptureSession::GetSensorSensitivity fail due to camera device is null");
4424     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
4425     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, CameraErrorCode::INVALID_ARGUMENT,
4426         "CaptureSession::GetSensorSensitivity fail due to camera deviceInfo is null");
4427     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata = inputDeviceInfo->GetCachedMetadata();
4428     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::INVALID_ARGUMENT,
4429         "GetSensorSensitivity camera metadata is null");
4430     camera_metadata_item_t item;
4431     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_SENSOR_INFO_SENSITIVITY_RANGE, &item);
4432     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::INVALID_ARGUMENT,
4433         "CaptureSession::GetSensorSensitivity Failed with return code %{public}d", ret);
4434 
4435     for (uint32_t i = 0; i < item.count; i++) {
4436         sensitivityRange.emplace_back(item.data.i32[i]);
4437     }
4438 
4439     return CameraErrorCode::SUCCESS;
4440 }
4441 
SetSensorSensitivity(uint32_t sensitivity)4442 int32_t CaptureSession::SetSensorSensitivity(uint32_t sensitivity)
4443 {
4444     MEDIA_INFO_LOG("CaptureSession::SetSensorSensitivity");
4445     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
4446         "CaptureSession::SetSensorSensitivity Session is not Commited");
4447     // LCOV_EXCL_START
4448     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
4449         "CaptureSession::SetSensorSensitivity Need to call LockForControl() before setting camera properties");
4450     MEDIA_DEBUG_LOG("CaptureSession::SetSensorSensitivity sensitivity: %{public}d", sensitivity);
4451     auto inputDevice = GetInputDevice();
4452     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(),
4453         CameraErrorCode::OPERATION_NOT_ALLOWED, "CaptureSession::SetSensorSensitivity camera device is null");
4454     bool status = AddOrUpdateMetadata(changedMetadata_, HAL_CUSTOM_SENSOR_SENSITIVITY, &sensitivity, 1);
4455     CHECK_PRINT_ELOG(!status, "CaptureSession::SetSensorSensitivity Failed to set sensitivity");
4456     return CameraErrorCode::SUCCESS;
4457     // LCOV_EXCL_STOP
4458 }
4459 
GetModuleType(uint32_t & moduleType)4460 int32_t CaptureSession::GetModuleType(uint32_t &moduleType)
4461 {
4462     MEDIA_INFO_LOG("CaptureSession::GetModuleType");
4463     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
4464         "CaptureSession::GetModuleType fail due to Session is not Commited");
4465     auto inputDevice = GetInputDevice();
4466     CHECK_RETURN_RET_ELOG(!inputDevice, CameraErrorCode::INVALID_ARGUMENT,
4467         "CaptureSession::GetModuleType fail due to camera device is null");
4468     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
4469     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, CameraErrorCode::INVALID_ARGUMENT,
4470         "CaptureSession::GetModuleType fail due to camera deviceInfo is null");
4471     std::shared_ptr<OHOS::Camera::CameraMetadata> metadata = inputDeviceInfo->GetCachedMetadata();
4472     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::INVALID_ARGUMENT,
4473         "GetModuleType camera metadata is null");
4474     camera_metadata_item_t item;
4475     int ret = Camera::FindCameraMetadataItem(metadata->get(), HAL_CUSTOM_SENSOR_MODULE_TYPE, &item);
4476     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::INVALID_ARGUMENT,
4477         "CaptureSession::GetModuleType Failed with return code %{public}d", ret);
4478     moduleType = item.data.ui32[0];
4479     MEDIA_DEBUG_LOG("moduleType: %{public}d", moduleType);
4480     return CameraErrorCode::SUCCESS;
4481 }
4482 
SetARCallback(std::shared_ptr<ARCallback> arCallback)4483 void CaptureSession::SetARCallback(std::shared_ptr<ARCallback> arCallback)
4484 {
4485     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
4486     arCallback_ = arCallback;
4487 }
4488 
4489 // white balance mode
GetSupportedWhiteBalanceModes(std::vector<WhiteBalanceMode> & supportedWhiteBalanceModes)4490 int32_t CaptureSession::GetSupportedWhiteBalanceModes(std::vector<WhiteBalanceMode> &supportedWhiteBalanceModes)
4491 {
4492     supportedWhiteBalanceModes.clear();
4493     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
4494         "CaptureSession::GetSupportedWhiteBalanceModes Session is not Commited");
4495     auto inputDevice = GetInputDevice();
4496     CHECK_RETURN_RET_ELOG(!inputDevice, CameraErrorCode::SUCCESS,
4497         "CaptureSession::GetSupportedWhiteBalanceModes camera device is null");
4498     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
4499     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, CameraErrorCode::SUCCESS,
4500         "CaptureSession::GetSupportedWhiteBalanceModes camera deviceInfo is null");
4501     std::shared_ptr<Camera::CameraMetadata> metadata = inputDeviceInfo->GetCachedMetadata();
4502     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
4503         "GetSupportedWhiteBalanceModes camera metadata is null");
4504     camera_metadata_item_t item;
4505     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_AWB_AVAILABLE_MODES, &item);
4506     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
4507         "CaptureSession::GetSupportedWhiteBalanceModes Failed with return code %{public}d", ret);
4508     // LCOV_EXCL_START
4509     for (uint32_t i = 0; i < item.count; i++) {
4510         auto itr = metaWhiteBalanceModeMap_.find(static_cast<camera_awb_mode_t>(item.data.u8[i]));
4511         CHECK_EXECUTE(itr != metaWhiteBalanceModeMap_.end(), supportedWhiteBalanceModes.emplace_back(itr->second));
4512     }
4513     return CameraErrorCode::SUCCESS;
4514     // LCOV_EXCL_STOP
4515 }
4516 
IsWhiteBalanceModeSupported(WhiteBalanceMode mode,bool & isSupported)4517 int32_t CaptureSession::IsWhiteBalanceModeSupported(WhiteBalanceMode mode, bool &isSupported)
4518 {
4519     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
4520         "CaptureSession::IsFocusModeSupported Session is not Commited");
4521     if (mode == AWB_MODE_LOCKED) {
4522         isSupported = true;
4523         return CameraErrorCode::SUCCESS;
4524     }
4525     // LCOV_EXCL_START
4526     std::vector<WhiteBalanceMode> vecSupportedWhiteBalanceModeList;
4527     (void)this->GetSupportedWhiteBalanceModes(vecSupportedWhiteBalanceModeList);
4528     if (find(vecSupportedWhiteBalanceModeList.begin(), vecSupportedWhiteBalanceModeList.end(),
4529         mode) != vecSupportedWhiteBalanceModeList.end()) {
4530         isSupported = true;
4531         return CameraErrorCode::SUCCESS;
4532     }
4533     isSupported = false;
4534     return CameraErrorCode::SUCCESS;
4535     // LCOV_EXCL_STOP
4536 }
4537 
SetWhiteBalanceMode(WhiteBalanceMode mode)4538 int32_t CaptureSession::SetWhiteBalanceMode(WhiteBalanceMode mode)
4539 {
4540     CAMERA_SYNC_TRACE;
4541     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
4542         "CaptureSession::SetWhiteBalanceMode Session is not Commited");
4543     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
4544         "CaptureSession::SetWhiteBalanceMode Need to call LockForControl() before setting camera properties");
4545     uint8_t awbLock = OHOS_CAMERA_AWB_LOCK_OFF;
4546     bool res = false;
4547     if (mode == AWB_MODE_LOCKED) {
4548         awbLock = OHOS_CAMERA_AWB_LOCK_ON;
4549         res = AddOrUpdateMetadata(changedMetadata_->get(), OHOS_CONTROL_AWB_LOCK, &awbLock, 1);
4550         CHECK_PRINT_ELOG(!res, "CaptureSession::SetWhiteBalanceMode Failed to lock whiteBalance");
4551         return CameraErrorCode::SUCCESS;
4552     }
4553     res = AddOrUpdateMetadata(changedMetadata_->get(), OHOS_CONTROL_AWB_LOCK, &awbLock, 1);
4554     CHECK_PRINT_ELOG(!res, "CaptureSession::SetWhiteBalanceMode Failed to unlock whiteBalance");
4555     uint8_t whiteBalanceMode = OHOS_CAMERA_AWB_MODE_OFF;
4556     auto itr = fwkWhiteBalanceModeMap_.find(mode);
4557     if (itr == fwkWhiteBalanceModeMap_.end()) {
4558         MEDIA_ERR_LOG("CaptureSession::SetWhiteBalanceMode Unknown exposure mode");
4559     } else {
4560         whiteBalanceMode = itr->second;
4561     }
4562     MEDIA_DEBUG_LOG("CaptureSession::SetWhiteBalanceMode WhiteBalance mode: %{public}d", whiteBalanceMode);
4563     // no manual wb mode need set maunual value to 0
4564     if (mode != AWB_MODE_OFF) {
4565         int32_t wbValue = 0;
4566         CHECK_PRINT_ELOG(!AddOrUpdateMetadata(changedMetadata_->get(), OHOS_CONTROL_SENSOR_WB_VALUE, &wbValue, 1),
4567             "SetManualWhiteBalance Failed to SetManualWhiteBalance.");
4568     }
4569     res = AddOrUpdateMetadata(changedMetadata_->get(), OHOS_CONTROL_AWB_MODE, &whiteBalanceMode, 1);
4570     CHECK_PRINT_ELOG(!res, "CaptureSession::SetWhiteBalanceMode Failed to set WhiteBalance mode");
4571     return CameraErrorCode::SUCCESS;
4572 }
4573 
GetWhiteBalanceMode(WhiteBalanceMode & mode)4574 int32_t CaptureSession::GetWhiteBalanceMode(WhiteBalanceMode &mode)
4575 {
4576     mode = AWB_MODE_OFF;
4577     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
4578         "CaptureSession::GetWhiteBalanceMode Session is not Commited");
4579     auto inputDevice = GetInputDevice();
4580     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
4581         "CaptureSession::GetWhiteBalanceMode camera device is null");
4582     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
4583     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::INVALID_ARGUMENT,
4584         "GetWhiteBalanceMode metadata is null");
4585     camera_metadata_item_t item;
4586     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_AWB_LOCK, &item);
4587     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
4588         "CaptureSession::GetWhiteBalanceMode Failed with return code %{public}d", ret);
4589     // LCOV_EXCL_START
4590     if (item.data.u8[0] == OHOS_CAMERA_AWB_LOCK_ON) {
4591         mode = AWB_MODE_LOCKED;
4592         return CameraErrorCode::SUCCESS;
4593     }
4594     ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_AWB_MODE, &item);
4595     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
4596         "CaptureSession::GetWhiteBalanceMode Failed with return code %{public}d", ret);
4597     auto itr = metaWhiteBalanceModeMap_.find(static_cast<camera_awb_mode_t>(item.data.u8[0]));
4598     if (itr != metaWhiteBalanceModeMap_.end()) {
4599         mode = itr->second;
4600         return CameraErrorCode::SUCCESS;
4601     }
4602     return CameraErrorCode::SUCCESS;
4603     // LCOV_EXCL_STOP
4604 }
4605 
4606 // manual white balance
GetManualWhiteBalanceRange(std::vector<int32_t> & whiteBalanceRange)4607 int32_t CaptureSession::GetManualWhiteBalanceRange(std::vector<int32_t> &whiteBalanceRange)
4608 {
4609     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
4610         "CaptureSession::GetManualWhiteBalanceRange Session is not Commited");
4611     auto inputDevice = GetInputDevice();
4612     CHECK_RETURN_RET_ELOG(!inputDevice, CameraErrorCode::SUCCESS,
4613         "CaptureSession::GetManualWhiteBalanceRange camera device is null");
4614     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
4615     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, CameraErrorCode::SUCCESS,
4616         "CaptureSession::GetManualWhiteBalanceRange camera deviceInfo is null");
4617     std::shared_ptr<Camera::CameraMetadata> metadata = inputDeviceInfo->GetCachedMetadata();
4618     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
4619         "GetManualWhiteBalanceRange camera metadata is null");
4620     camera_metadata_item_t item;
4621     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_SENSOR_WB_VALUES, &item);
4622     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
4623         "CaptureSession::GetManualWhiteBalanceRange Failed with return code %{public}d", ret);
4624 
4625     for (uint32_t i = 0; i < item.count; i++) {
4626         whiteBalanceRange.emplace_back(item.data.i32[i]);
4627     }
4628     return CameraErrorCode::SUCCESS;
4629 }
4630 
IsManualWhiteBalanceSupported(bool & isSupported)4631 int32_t CaptureSession::IsManualWhiteBalanceSupported(bool &isSupported)
4632 {
4633     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
4634         "CaptureSession::IsManualWhiteBalanceSupported Session is not Commited");
4635     std::vector<int32_t> whiteBalanceRange;
4636     this->GetManualWhiteBalanceRange(whiteBalanceRange);
4637     constexpr int32_t rangeSize = 2;
4638     isSupported = (whiteBalanceRange.size() == rangeSize);
4639     return CameraErrorCode::SUCCESS;
4640 }
4641 
SetManualWhiteBalance(int32_t wbValue)4642 int32_t CaptureSession::SetManualWhiteBalance(int32_t wbValue)
4643 {
4644     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
4645         "CaptureSession::SetManualWhiteBalance Session is not Commited");
4646     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
4647         "CaptureSession::SetManualWhiteBalance Need to call LockForControl() before setting camera properties");
4648     WhiteBalanceMode mode;
4649     GetWhiteBalanceMode(mode);
4650     // WhiteBalanceMode::OFF
4651     CHECK_RETURN_RET_ELOG(mode != WhiteBalanceMode::AWB_MODE_OFF, CameraErrorCode::OPERATION_NOT_ALLOWED,
4652         "CaptureSession::SetManualWhiteBalance Need to set WhiteBalanceMode off");
4653     int32_t minIndex = 0;
4654     int32_t maxIndex = 1;
4655     MEDIA_DEBUG_LOG("CaptureSession::SetManualWhiteBalance white balance: %{public}d", wbValue);
4656     auto inputDevice = GetInputDevice();
4657     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(),
4658         CameraErrorCode::OPERATION_NOT_ALLOWED, "CaptureSession::SetManualWhiteBalance camera device is null");
4659     std::vector<int32_t> whiteBalanceRange;
4660     this->GetManualWhiteBalanceRange(whiteBalanceRange);
4661     CHECK_RETURN_RET_ELOG(whiteBalanceRange.empty(), CameraErrorCode::OPERATION_NOT_ALLOWED,
4662         "CaptureSession::SetManualWhiteBalance Bias range is empty");
4663 
4664     if (wbValue != 0 && wbValue < whiteBalanceRange[minIndex]) {
4665         MEDIA_DEBUG_LOG("CaptureSession::SetManualWhiteBalance wbValue:"
4666                         "%{public}d is lesser than minimum wbValue: %{public}d",
4667             wbValue, whiteBalanceRange[minIndex]);
4668         wbValue = whiteBalanceRange[minIndex];
4669     } else if (wbValue > whiteBalanceRange[maxIndex]) {
4670         MEDIA_DEBUG_LOG("CaptureSession::SetManualWhiteBalance wbValue: "
4671                         "%{public}d is greater than maximum wbValue: %{public}d",
4672             wbValue, whiteBalanceRange[maxIndex]);
4673         wbValue = whiteBalanceRange[maxIndex];
4674     }
4675     CHECK_PRINT_ELOG(!AddOrUpdateMetadata(changedMetadata_->get(), OHOS_CONTROL_SENSOR_WB_VALUE, &wbValue, 1),
4676         "SetManualWhiteBalance Failed to SetManualWhiteBalance");
4677     return CameraErrorCode::SUCCESS;
4678 }
4679 
GetManualWhiteBalance(int32_t & wbValue)4680 int32_t CaptureSession::GetManualWhiteBalance(int32_t &wbValue)
4681 {
4682     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
4683         "CaptureSession::GetManualWhiteBalance Session is not Commited");
4684     // LCOV_EXCL_START
4685     auto inputDevice = GetInputDevice();
4686     CHECK_RETURN_RET_ELOG(!inputDevice, CameraErrorCode::SUCCESS,
4687         "CaptureSession::GetManualWhiteBalance camera device is null");
4688     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
4689     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, CameraErrorCode::SUCCESS,
4690         "CaptureSession::GetManualWhiteBalance camera deviceInfo is null");
4691     std::shared_ptr<Camera::CameraMetadata> metadata = inputDeviceInfo->GetCachedMetadata();
4692     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
4693         "GetManualWhiteBalance camera metadata is null");
4694     camera_metadata_item_t item;
4695     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_CONTROL_SENSOR_WB_VALUE, &item);
4696     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
4697         "CaptureSession::GetManualWhiteBalance Failed with return code %{public}d", ret);
4698     if (item.count != 0) {
4699         wbValue = item.data.i32[0];
4700     }
4701     return CameraErrorCode::SUCCESS;
4702     // LCOV_EXCL_STOP
4703 }
4704 
GetSupportedPhysicalApertures(std::vector<std::vector<float>> & supportedPhysicalApertures)4705 int32_t CaptureSession::GetSupportedPhysicalApertures(std::vector<std::vector<float>>& supportedPhysicalApertures)
4706 {
4707     // The data structure of the supportedPhysicalApertures object is { {zoomMin, zoomMax,
4708     // physicalAperture1, physicalAperture2···}, }.
4709     supportedPhysicalApertures.clear();
4710     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
4711         "GetSupportedPhysicalApertures Session is not Commited");
4712     auto inputDevice = GetInputDevice();
4713     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
4714         "GetSupportedPhysicalApertures camera device is null");
4715 
4716     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
4717     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
4718         "GetSupportedPhysicalApertures camera metadata is null");
4719     camera_metadata_item_t item;
4720     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_CAMERA_PHYSICAL_APERTURE_RANGE, &item);
4721     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count == 0, CameraErrorCode::SUCCESS,
4722         "GetSupportedPhysicalApertures Failed with return code %{public}d", ret);
4723     std::vector<float> chooseModeRange = ParsePhysicalApertureRangeByMode(item, GetMode());
4724     constexpr int32_t minPhysicalApertureMetaSize = 3;
4725     CHECK_RETURN_RET_ELOG(chooseModeRange.size() < minPhysicalApertureMetaSize, CameraErrorCode::SUCCESS,
4726         "GetSupportedPhysicalApertures Failed meta format error");
4727     // LCOV_EXCL_START
4728     int32_t deviceCntPos = 1;
4729     int32_t supportedDeviceCount = static_cast<int32_t>(chooseModeRange[deviceCntPos]);
4730     CHECK_RETURN_RET_ELOG(supportedDeviceCount == 0, CameraErrorCode::SUCCESS,
4731         "GetSupportedPhysicalApertures Failed meta device count is 0");
4732     std::vector<float> tempPhysicalApertures = {};
4733     for (uint32_t i = 2; i < chooseModeRange.size(); i++) {
4734         if (chooseModeRange[i] == -1) {
4735             supportedPhysicalApertures.emplace_back(tempPhysicalApertures);
4736             vector<float>().swap(tempPhysicalApertures);
4737             continue;
4738         }
4739         tempPhysicalApertures.emplace_back(chooseModeRange[i]);
4740     }
4741     return CameraErrorCode::SUCCESS;
4742     // LCOV_EXCL_STOP
4743 }
4744 
GetSupportedVirtualApertures(std::vector<float> & apertures)4745 int32_t CaptureSession::GetSupportedVirtualApertures(std::vector<float>& apertures)
4746 {
4747     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
4748         "GetSupportedVirtualApertures Session is not Commited");
4749     auto inputDevice = GetInputDevice();
4750     CHECK_RETURN_RET_ELOG(!inputDevice, CameraErrorCode::SUCCESS,
4751         "GetSupportedVirtualApertures camera device is null");
4752     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
4753     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, CameraErrorCode::SUCCESS,
4754         "CaptureSession::GetManualWhiteBalance camera deviceInfo is null");
4755     std::shared_ptr<Camera::CameraMetadata> metadata = inputDeviceInfo->GetCachedMetadata();
4756     CHECK_RETURN_RET(metadata == nullptr, CameraErrorCode::SUCCESS);
4757     camera_metadata_item_t item;
4758     int32_t ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_CAMERA_VIRTUAL_APERTURE_RANGE, &item);
4759     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count == 0, CameraErrorCode::SUCCESS,
4760         "GetSupportedVirtualApertures Failed with return code %{public}d", ret);
4761     for (uint32_t i = 0; i < item.count; i++) {
4762         apertures.emplace_back(item.data.f[i]);
4763     }
4764     return CameraErrorCode::SUCCESS;
4765 }
4766 
GetSupportedPortraitEffects()4767 std::vector<PortraitEffect> CaptureSession::GetSupportedPortraitEffects()
4768 {
4769     std::vector<PortraitEffect> supportedPortraitEffects = {};
4770     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), supportedPortraitEffects,
4771         "CaptureSession::GetSupportedPortraitEffects Session is not Commited");
4772     auto inputDevice = GetInputDevice();
4773     CHECK_RETURN_RET_ELOG(!inputDevice, supportedPortraitEffects,
4774         "CaptureSession::GetSupportedPortraitEffects camera device is null");
4775     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
4776     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, supportedPortraitEffects,
4777         "CaptureSession::GetSupportedPortraitEffects camera deviceInfo is null");
4778     int ret = VerifyAbility(static_cast<uint32_t>(OHOS_ABILITY_SCENE_PORTRAIT_EFFECT_TYPES));
4779     CHECK_RETURN_RET_ELOG(ret != CAMERA_OK, supportedPortraitEffects,
4780         "CaptureSession::GetSupportedPortraitEffects abilityId is NULL");
4781     // LCOV_EXCL_START
4782     std::shared_ptr<Camera::CameraMetadata> metadata = inputDeviceInfo->GetCachedMetadata();
4783     CHECK_RETURN_RET(metadata == nullptr, supportedPortraitEffects);
4784     camera_metadata_item_t item;
4785     ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_SCENE_PORTRAIT_EFFECT_TYPES, &item);
4786     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count == 0, supportedPortraitEffects,
4787         "CaptureSession::GetSupportedPortraitEffects Failed with return code %{public}d", ret);
4788     for (uint32_t i = 0; i < item.count; i++) {
4789         auto itr = g_metaToFwPortraitEffect_.find(static_cast<camera_portrait_effect_type_t>(item.data.u8[i]));
4790         CHECK_EXECUTE(itr != g_metaToFwPortraitEffect_.end(), supportedPortraitEffects.emplace_back(itr->second));
4791     }
4792     return supportedPortraitEffects;
4793     // LCOV_EXCL_STOP
4794 }
4795 
IsLcdFlashSupported()4796 bool CaptureSession::IsLcdFlashSupported()
4797 {
4798     CAMERA_SYNC_TRACE;
4799     MEDIA_DEBUG_LOG("IsLcdFlashSupported is called");
4800     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), false,
4801         "IsLcdFlashSupported Session is not Commited");
4802     auto inputDevice = GetInputDevice();
4803     CHECK_RETURN_RET_ELOG(!inputDevice, false,
4804         "IsLcdFlashSupported camera device is null");
4805     auto inputDeviceInfo = inputDevice->GetCameraDeviceInfo();
4806     CHECK_RETURN_RET_ELOG(!inputDeviceInfo, false, "IsLcdFlashSupported camera device is null");
4807     std::shared_ptr<Camera::CameraMetadata> metadata = inputDeviceInfo->GetCachedMetadata();
4808     CHECK_RETURN_RET_ELOG(metadata == nullptr, false, "IsLcdFlashSupported camera metadata is null");
4809     camera_metadata_item_t item;
4810     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_LCD_FLASH, &item);
4811     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, false,
4812         "IsLcdFlashSupported Failed with return code %{public}d", ret);
4813     MEDIA_INFO_LOG("IsLcdFlashSupported value: %{public}u", item.data.i32[0]);
4814     return item.data.i32[0] == 1;
4815 }
4816 
ProcessLcdFlashStatusUpdates(const std::shared_ptr<OHOS::Camera::CameraMetadata> & result)4817 void CaptureSession::ProcessLcdFlashStatusUpdates(const std::shared_ptr<OHOS::Camera::CameraMetadata>& result)
4818     __attribute__((no_sanitize("cfi")))
4819 {
4820     CAMERA_SYNC_TRACE;
4821     MEDIA_DEBUG_LOG("Entry ProcessLcdFlashStatusUpdates");
4822 
4823     auto statusCallback = GetLcdFlashStatusCallback();
4824     if (statusCallback == nullptr) {
4825         MEDIA_DEBUG_LOG("CaptureSession::ProcessLcdFlashStatusUpdates statusCallback is null");
4826         return;
4827     }
4828     // LCOV_EXCL_START
4829     camera_metadata_item_t item;
4830     common_metadata_header_t* metadata = result->get();
4831     int ret = Camera::FindCameraMetadataItem(metadata, OHOS_STATUS_LCD_FLASH_STATUS, &item);
4832     if (ret != CAM_META_SUCCESS || item.count <= 0) {
4833         MEDIA_DEBUG_LOG("Camera not support lcd flash");
4834         return;
4835     }
4836     constexpr uint32_t validCount = 2;
4837     CHECK_RETURN_ELOG(item.count != validCount, "OHOS_STATUS_LCD_FLASH_STATUS invalid data size");
4838     auto isLcdFlashNeeded = static_cast<bool>(item.data.i32[0]);
4839     auto lcdCompensation = item.data.i32[1];
4840     LcdFlashStatusInfo preLcdFlashStatusInfo = statusCallback->GetLcdFlashStatusInfo();
4841     if (preLcdFlashStatusInfo.isLcdFlashNeeded != isLcdFlashNeeded ||
4842         preLcdFlashStatusInfo.lcdCompensation != lcdCompensation) {
4843         LcdFlashStatusInfo lcdFlashStatusInfo;
4844         lcdFlashStatusInfo.isLcdFlashNeeded = isLcdFlashNeeded;
4845         lcdFlashStatusInfo.lcdCompensation = lcdCompensation;
4846         statusCallback->SetLcdFlashStatusInfo(lcdFlashStatusInfo);
4847         statusCallback->OnLcdFlashStatusChanged(lcdFlashStatusInfo);
4848     }
4849     // LCOV_EXCL_STOP
4850 }
4851 
GetLcdFlashStatusCallback()4852 std::shared_ptr<LcdFlashStatusCallback> CaptureSession::GetLcdFlashStatusCallback()
4853 {
4854     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
4855     return lcdFlashStatusCallback_;
4856 }
4857 
EnableFaceDetection(bool enable)4858 void CaptureSession::EnableFaceDetection(bool enable)
4859 {
4860     MEDIA_INFO_LOG("EnableFaceDetection enable: %{public}d", enable);
4861     CHECK_RETURN_ELOG(GetMetaOutput() == nullptr, "MetaOutput is null");
4862     if (!enable) {
4863         std::set<camera_face_detect_mode_t> objectTypes;
4864         SetCaptureMetadataObjectTypes(objectTypes);
4865         return;
4866     }
4867     sptr<MetadataOutput> metaOutput = static_cast<MetadataOutput*>(GetMetaOutput().GetRefPtr());
4868     CHECK_RETURN_ELOG(!metaOutput, "MetaOutput is null");
4869     std::vector<MetadataObjectType> metadataObjectTypes = metaOutput->GetSupportedMetadataObjectTypes();
4870     MEDIA_INFO_LOG("EnableFaceDetection SetCapturingMetadataObjectTypes objectTypes size = %{public}zu",
4871         metadataObjectTypes.size());
4872     metaOutput->SetCapturingMetadataObjectTypes(metadataObjectTypes);
4873 }
4874 
IsTripodDetectionSupported()4875 bool CaptureSession::IsTripodDetectionSupported()
4876 {
4877     CAMERA_SYNC_TRACE;
4878     MEDIA_INFO_LOG("Enter IsTripodDetectionSupported");
4879     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), false,
4880         "CaptureSession::IsTripodDetectionSupported Session is not Commited");
4881     auto inputDevice = GetInputDevice();
4882     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), false,
4883         "CaptureSession::IsTripodDetectionSupported camera device is null");
4884     auto deviceInfo = inputDevice->GetCameraDeviceInfo();
4885     CHECK_RETURN_RET_ELOG(deviceInfo == nullptr, false,
4886         "CaptureSession::IsTripodDetectionSupported camera device is null");
4887     std::shared_ptr<Camera::CameraMetadata> metadata = deviceInfo->GetCachedMetadata();
4888     CHECK_RETURN_RET_ELOG(metadata == nullptr, false,
4889         "IsTripodDetectionSupported camera metadata is null");
4890     camera_metadata_item_t item;
4891     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_TRIPOD_DETECTION, &item);
4892     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS || item.count <= 0, false,
4893         "CaptureSession::IsTripodDetectionSupported Failed with return code %{public}d", ret);
4894     auto supportResult = static_cast<bool>(item.data.i32[0]);
4895     return supportResult;
4896 }
4897 
EnableTripodStabilization(bool isEnable)4898 int32_t CaptureSession::EnableTripodStabilization(bool isEnable)
4899 {
4900     CAMERA_SYNC_TRACE;
4901     MEDIA_INFO_LOG("Enter EnableTripodStabilization, isEnable:%{public}d", isEnable);
4902     CHECK_RETURN_RET_ELOG(!IsTripodDetectionSupported(), CameraErrorCode::OPERATION_NOT_ALLOWED,
4903         "EnableTripodStabilization IsTripodDetectionSupported is false");
4904     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG, "Session is not Commited");
4905     // LCOV_EXCL_START
4906     uint8_t enableValue = static_cast<uint8_t>(isEnable ? 1 : 0);
4907     if (!AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_TRIPOD_STABLITATION, &enableValue, 1)) {
4908         MEDIA_ERR_LOG("EnableTripodStabilization failed to enable tripod detection");
4909     } else {
4910         isSetTripodDetectionEnable_ = isEnable;
4911     }
4912     return CameraErrorCode::SUCCESS;
4913     // LCOV_EXCL_STOP
4914 }
4915 
ProcessTripodStatusChange(const std::shared_ptr<OHOS::Camera::CameraMetadata> & result)4916 void CaptureSession::ProcessTripodStatusChange(const std::shared_ptr<OHOS::Camera::CameraMetadata>& result)
4917     __attribute__((no_sanitize("cfi")))
4918 {
4919     CAMERA_SYNC_TRACE;
4920     MEDIA_DEBUG_LOG("Entry ProcessTripodStatusChange");
4921     auto featureStatusCallback = GetFeatureDetectionStatusCallback();
4922     if (featureStatusCallback == nullptr ||
4923             !featureStatusCallback->IsFeatureSubscribed(SceneFeature::FEATURE_TRIPOD_DETECTION)) {
4924         MEDIA_DEBUG_LOG("CaptureSession::ProcessTripodStatusChange"
4925                         "featureDetectionStatusChangedCallback are null");
4926         return;
4927     }
4928     // LCOV_EXCL_START
4929     camera_metadata_item_t item;
4930     common_metadata_header_t* metadata = result->get();
4931     int ret = Camera::FindCameraMetadataItem(metadata, OHOS_STATUS_TRIPOD_DETECTION_STATUS, &item);
4932     if (ret != CAM_META_SUCCESS || item.count <= 0) {
4933         MEDIA_DEBUG_LOG("Camera not support tripod detection");
4934         return;
4935     }
4936     FwkTripodStatus tripodStatus = FwkTripodStatus::INVALID;
4937     auto itr = metaTripodStatusMap_.find(static_cast<TripodStatus>(item.data.u8[0]));
4938     if (itr == metaTripodStatusMap_.end()) {
4939         MEDIA_DEBUG_LOG("Tripod status not found");
4940         return;
4941     }
4942     tripodStatus = itr->second;
4943     MEDIA_DEBUG_LOG("Tripod status: %{public}d", tripodStatus);
4944     if (featureStatusCallback != nullptr &&
4945         featureStatusCallback->IsFeatureSubscribed(SceneFeature::FEATURE_TRIPOD_DETECTION) &&
4946         (static_cast<int>(featureStatusCallback->GetFeatureStatus()) != static_cast<int>(tripodStatus))) {
4947         auto detectStatus = FeatureDetectionStatusCallback::FeatureDetectionStatus::ACTIVE;
4948         featureStatusCallback->SetFeatureStatus(static_cast<int8_t>(tripodStatus));
4949         featureStatusCallback->OnFeatureDetectionStatusChanged(SceneFeature::FEATURE_TRIPOD_DETECTION, detectStatus);
4950     }
4951     // LCOV_EXCL_STOP
4952 }
4953 
IsAutoDeviceSwitchSupported()4954 bool CaptureSession::IsAutoDeviceSwitchSupported()
4955 {
4956     bool isFoldable = CameraManager::GetInstance()->GetIsFoldable();
4957     MEDIA_INFO_LOG("IsAutoDeviceSwitchSupported %{public}d.", isFoldable);
4958     return isFoldable;
4959 }
4960 
EnableAutoDeviceSwitch(bool isEnable)4961 int32_t CaptureSession::EnableAutoDeviceSwitch(bool isEnable)
4962 {
4963     MEDIA_INFO_LOG("EnableAutoDeviceSwitch, isEnable:%{public}d", isEnable);
4964     CHECK_RETURN_RET_ELOG(!IsAutoDeviceSwitchSupported(), CameraErrorCode::OPERATION_NOT_ALLOWED,
4965         "The automatic switchover mode is not supported.");
4966     // LCOV_EXCL_START
4967     CHECK_RETURN_RET_ELOG(GetIsAutoSwitchDeviceStatus() == isEnable, CameraErrorCode::SUCCESS,
4968         "Repeat Settings.");
4969     SetIsAutoSwitchDeviceStatus(isEnable);
4970     if (GetIsAutoSwitchDeviceStatus()) {
4971         MEDIA_INFO_LOG("RegisterFoldStatusListener is called");
4972         CreateAndSetFoldServiceCallback();
4973     }
4974     return CameraErrorCode::SUCCESS;
4975     // LCOV_EXCL_STOP
4976 }
4977 
SetIsAutoSwitchDeviceStatus(bool isEnable)4978 void CaptureSession::SetIsAutoSwitchDeviceStatus(bool isEnable)
4979 {
4980     isAutoSwitchDevice_ = isEnable;
4981 }
4982 
GetIsAutoSwitchDeviceStatus()4983 bool CaptureSession::GetIsAutoSwitchDeviceStatus()
4984 {
4985     return isAutoSwitchDevice_;
4986 }
4987 
SwitchDevice()4988 bool CaptureSession::SwitchDevice()
4989 {
4990     std::lock_guard<std::mutex> lock(switchDeviceMutex_);
4991     CHECK_RETURN_RET_ELOG(!IsSessionStarted(), false,
4992         "The switch device has failed because the session has not started.");
4993     // LCOV_EXCL_START
4994     auto captureInput = GetInputDevice();
4995     auto cameraInput = (sptr<CameraInput>&)captureInput;
4996     CHECK_RETURN_RET_ELOG(cameraInput == nullptr, false, "cameraInput is nullptr.");
4997     auto deviceiInfo = cameraInput->GetCameraDeviceInfo();
4998     CHECK_RETURN_RET_ELOG(!deviceiInfo ||
4999         (deviceiInfo->GetPosition() != CAMERA_POSITION_FRONT &&
5000         deviceiInfo->GetPosition() != CAMERA_POSITION_FOLD_INNER), false, "No need switch camera.");
5001     bool hasVideoOutput = StopVideoOutput();
5002     int32_t retCode = CameraErrorCode::SUCCESS;
5003     Stop();
5004     BeginConfig();
5005     RemoveInput(captureInput);
5006     cameraInput->Close();
5007     sptr<CameraDevice> cameraDeviceTemp = FindFrontCamera();
5008     CHECK_RETURN_RET_ELOG(cameraDeviceTemp == nullptr, false, "No front camera found.");
5009     sptr<ICameraDeviceService> deviceObj = nullptr;
5010     retCode = CameraManager::GetInstance()->CreateCameraDevice(cameraDeviceTemp->GetID(), &deviceObj);
5011     CHECK_RETURN_RET_ELOG(retCode != CameraErrorCode::SUCCESS, false,
5012         "SwitchDevice::CreateCameraDevice Create camera device failed.");
5013     cameraInput->SwitchCameraDevice(deviceObj, cameraDeviceTemp);
5014     retCode = cameraInput->Open();
5015     CHECK_PRINT_ELOG(retCode != CameraErrorCode::SUCCESS, "SwitchDevice::Open failed.");
5016     retCode = AddInput(captureInput);
5017     CHECK_PRINT_ELOG(retCode != CameraErrorCode::SUCCESS, "SwitchDevice::AddInput failed.");
5018     retCode = CommitConfig();
5019     CHECK_PRINT_ELOG(retCode != CameraErrorCode::SUCCESS, "SwitchDevice::CommitConfig failed.");
5020     ExecuteAllFunctionsInMap();
5021     retCode = Start();
5022     CHECK_PRINT_ELOG(retCode != CameraErrorCode::SUCCESS, "SwitchDevice::Start failed.");
5023     CHECK_EXECUTE(hasVideoOutput, StartVideoOutput());
5024     return true;
5025     // LCOV_EXCL_STOP
5026 }
5027 
FindFrontCamera()5028 sptr<CameraDevice> CaptureSession::FindFrontCamera()
5029 {
5030     auto cameraDeviceList = CameraManager::GetInstance()->GetSupportedCamerasWithFoldStatus();
5031     for (const auto& cameraDevice : cameraDeviceList) {
5032         if (cameraDevice->GetPosition() == CAMERA_POSITION_FRONT ||
5033             cameraDevice->GetPosition() == CAMERA_POSITION_FOLD_INNER) {
5034             return cameraDevice;
5035         }
5036     }
5037     return nullptr;
5038 }
5039 
StartVideoOutput()5040 void CaptureSession::StartVideoOutput()
5041 {
5042     sptr<VideoOutput> videoOutput = nullptr;
5043     {
5044         std::lock_guard<std::mutex> lock(captureOutputSetsMutex_);
5045         for (const auto& output : captureOutputSets_) {
5046             auto item = output.promote();
5047             if (item && item->GetOutputType() == CAPTURE_OUTPUT_TYPE_VIDEO) {
5048                 videoOutput = (sptr<VideoOutput>&)item;
5049                 break;
5050             }
5051         }
5052     }
5053     CHECK_EXECUTE(videoOutput, videoOutput->Start());
5054 }
5055 
StopVideoOutput()5056 bool CaptureSession::StopVideoOutput()
5057 {
5058     sptr<VideoOutput> videoOutput = nullptr;
5059     bool hasVideoOutput = false;
5060     {
5061         std::lock_guard<std::mutex> lock(captureOutputSetsMutex_);
5062         for (const auto& output : captureOutputSets_) {
5063             auto item = output.promote();
5064             if (item && item->GetOutputType() == CAPTURE_OUTPUT_TYPE_VIDEO) {
5065                 videoOutput = (sptr<VideoOutput>&)item;
5066                 break;
5067             }
5068         }
5069     }
5070     if (videoOutput && videoOutput->IsVideoStarted()) {
5071         videoOutput->Stop();
5072         hasVideoOutput = true;
5073     }
5074     return hasVideoOutput;
5075 }
5076 
SetAutoDeviceSwitchCallback(shared_ptr<AutoDeviceSwitchCallback> autoDeviceSwitchCallback)5077 void CaptureSession::SetAutoDeviceSwitchCallback(shared_ptr<AutoDeviceSwitchCallback> autoDeviceSwitchCallback)
5078 {
5079     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
5080     autoDeviceSwitchCallback_ = autoDeviceSwitchCallback;
5081 }
5082 
GetAutoDeviceSwitchCallback()5083 shared_ptr<AutoDeviceSwitchCallback> CaptureSession::GetAutoDeviceSwitchCallback()
5084 {
5085     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
5086     return autoDeviceSwitchCallback_;
5087 }
5088 
AddFunctionToMap(std::string ctrlTarget,std::function<void ()> func)5089 void CaptureSession::AddFunctionToMap(std::string ctrlTarget, std::function<void()> func)
5090 {
5091     if (!GetIsAutoSwitchDeviceStatus() || !canAddFuncToMap_) {
5092         MEDIA_INFO_LOG("The automatic switching device is not enabled.");
5093         return;
5094     }
5095     std::lock_guard<std::mutex> lock(functionMapMutex_);
5096     functionMap[ctrlTarget] = func;
5097 }
5098 
ExecuteAllFunctionsInMap()5099 void CaptureSession::ExecuteAllFunctionsInMap()
5100 {
5101     MEDIA_INFO_LOG("ExecuteAllFunctionsInMap is called.");
5102     canAddFuncToMap_ = false;
5103     std::lock_guard<std::mutex> lock(functionMapMutex_);
5104     for (const auto& pair : functionMap) {
5105         pair.second();
5106     }
5107     canAddFuncToMap_ = true;
5108 }
5109 
CreateAndSetFoldServiceCallback()5110 void CaptureSession::CreateAndSetFoldServiceCallback()
5111 {
5112     auto serviceProxy = CameraManager::GetInstance()->GetServiceProxy();
5113     CHECK_RETURN_ELOG(serviceProxy == nullptr,
5114         "CaptureSession::CreateAndSetFoldServiceCallback serviceProxy is null");
5115     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
5116     foldStatusCallback_ = new(std::nothrow) FoldCallback(this);
5117     CHECK_RETURN_ELOG(foldStatusCallback_ == nullptr,
5118         "CaptureSession::CreateAndSetFoldServiceCallback failed to new foldSvcCallback_!");
5119     int32_t retCode = serviceProxy->SetFoldStatusCallback(foldStatusCallback_, true);
5120     CHECK_PRINT_ELOG(retCode != CAMERA_OK,
5121         "CreateAndSetFoldServiceCallback Set service Callback failed, retCode: %{public}d", retCode);
5122 }
5123 
SetQualityPrioritization(QualityPrioritization qualityPrioritization)5124 int32_t CaptureSession::SetQualityPrioritization(QualityPrioritization qualityPrioritization)
5125 {
5126     CAMERA_SYNC_TRACE;
5127     CHECK_RETURN_RET_ELOG(!(IsSessionCommited() || IsSessionConfiged()), CameraErrorCode::SESSION_NOT_CONFIG,
5128         "CaptureSession::SetQualityPrioritization Session is not Commited");
5129     CHECK_RETURN_RET_ELOG(changedMetadata_ == nullptr, CameraErrorCode::SUCCESS,
5130         "CaptureSession::SetQualityPrioritization Need to call LockForControl() before setting camera properties");
5131     // LCOV_EXCL_START
5132     uint8_t quality = HIGH_QUALITY;
5133     auto itr = g_fwkQualityPrioritizationMap_.find(qualityPrioritization);
5134     CHECK_RETURN_RET_ELOG(itr == g_fwkQualityPrioritizationMap_.end(), CameraErrorCode::PARAMETER_ERROR,
5135         "CaptureSession::SetColorSpace() map failed, %{public}d", static_cast<int32_t>(qualityPrioritization));
5136     quality = itr->second;
5137     MEDIA_DEBUG_LOG(
5138         "CaptureSession::SetQualityPrioritization quality prioritization: %{public}d", qualityPrioritization);
5139     bool status = AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_QUALITY_PRIORITIZATION, &quality, 1);
5140     CHECK_PRINT_ELOG(!status, "CaptureSession::SetQualityPrioritization Failed to set quality prioritization");
5141     return CameraErrorCode::SUCCESS;
5142     // LCOV_EXCL_STOP
5143 }
5144 
EnableAutoAigcPhoto(bool enabled)5145 int32_t CaptureSession::EnableAutoAigcPhoto(bool enabled)
5146 {
5147     MEDIA_INFO_LOG("CaptureSession::EnableAutoAigcPhoto enabled:%{public}d", enabled);
5148 
5149     LockForControl();
5150     CHECK_RETURN_RET_ELOG(
5151         changedMetadata_ == nullptr, PARAMETER_ERROR, "CaptureSession::EnableAutoAigcPhoto changedMetadata_ is NULL");
5152     int32_t res = CameraErrorCode::SUCCESS;
5153     bool status = false;
5154     camera_metadata_item_t item;
5155     uint8_t autoAigcPhoto = static_cast<uint8_t>(enabled); // 三目表达式处理,不使用强转
5156     int ret = Camera::FindCameraMetadataItem(changedMetadata_->get(), OHOS_CONTROL_AUTO_AIGC_PHOTO, &item);
5157     if (ret == CAM_META_ITEM_NOT_FOUND) {
5158         status = changedMetadata_->addEntry(OHOS_CONTROL_AUTO_AIGC_PHOTO, &autoAigcPhoto, 1);
5159     } else if (ret == CAM_META_SUCCESS) {
5160         status = changedMetadata_->updateEntry(OHOS_CONTROL_AUTO_AIGC_PHOTO, &autoAigcPhoto, 1);
5161     }
5162     CHECK_RETURN_RET_ELOG(
5163         !status, PARAMETER_ERROR, "CaptureSession::EnableAutoAigcPhoto failed to set type!");
5164     UnlockForControl();
5165 
5166     CHECK_PRINT_ELOG(res != CameraErrorCode::SUCCESS, "CaptureSession::EnableAutoAigcPhoto failed");
5167     return res;
5168 }
5169 
GetSupportedFocusRangeTypes(std::vector<FocusRangeType> & types)5170 int32_t CaptureSession::GetSupportedFocusRangeTypes(std::vector<FocusRangeType>& types)
5171 {
5172     types.clear();
5173     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
5174         "CaptureSession::GetSupportedFocusRangeTypes Session is not Commited");
5175     auto inputDevice = GetInputDevice();
5176     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
5177         "CaptureSession::GetSupportedFocusRangeTypes camera device is null");
5178     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
5179     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
5180         "GetSupportedFocusRangeTypes camera metadata is null");
5181     camera_metadata_item_t item;
5182     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_FOCUS_RANGE_TYPES, &item);
5183     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
5184         "CaptureSession::GetSupportedFocusRangeTypes Failed with return code %{public}d", ret);
5185     // LCOV_EXCL_START
5186     for (uint32_t i = 0; i < item.count; i++) {
5187         auto itr = g_metaFocusRangeTypeMap_.find(static_cast<camera_focus_range_type_t>(item.data.u8[i]));
5188         if (itr != g_metaFocusRangeTypeMap_.end()) {
5189             types.emplace_back(itr->second);
5190         }
5191     }
5192     return CameraErrorCode::SUCCESS;
5193     // LCOV_EXCL_STOP
5194 }
5195 
GetSupportedFocusDrivenTypes(std::vector<FocusDrivenType> & types)5196 int32_t CaptureSession::GetSupportedFocusDrivenTypes(std::vector<FocusDrivenType>& types)
5197 {
5198     types.clear();
5199     CHECK_RETURN_RET_ELOG(!IsSessionCommited(), CameraErrorCode::SESSION_NOT_CONFIG,
5200         "CaptureSession::GetSupportedFocusDrivenTypes Session is not Commited");
5201     auto inputDevice = GetInputDevice();
5202     CHECK_RETURN_RET_ELOG(!inputDevice || !inputDevice->GetCameraDeviceInfo(), CameraErrorCode::SUCCESS,
5203         "CaptureSession::GetSupportedFocusDrivenTypes camera device is null");
5204     std::shared_ptr<Camera::CameraMetadata> metadata = GetMetadata();
5205     CHECK_RETURN_RET_ELOG(metadata == nullptr, CameraErrorCode::SUCCESS,
5206         "GetSupportedFocusDrivenTypes camera metadata is null");
5207     camera_metadata_item_t item;
5208     int ret = Camera::FindCameraMetadataItem(metadata->get(), OHOS_ABILITY_FOCUS_DRIVEN_TYPES, &item);
5209     CHECK_RETURN_RET_ELOG(ret != CAM_META_SUCCESS, CameraErrorCode::SUCCESS,
5210         "CaptureSession::GetSupportedFocusDrivenTypes Failed with return code %{public}d", ret);
5211     // LCOV_EXCL_START
5212     for (uint32_t i = 0; i < item.count; i++) {
5213         auto itr = g_metaFocusDrivenTypeMap_.find(static_cast<camera_focus_driven_type_t>(item.data.u8[i]));
5214         if (itr != g_metaFocusDrivenTypeMap_.end()) {
5215             types.emplace_back(itr->second);
5216         }
5217     }
5218     return CameraErrorCode::SUCCESS;
5219     // LCOV_EXCL_STOP
5220 }
5221 
SetHasFitedRotation(bool isHasFitedRotation)5222 int32_t CaptureSession::SetHasFitedRotation(bool isHasFitedRotation)
5223 {
5224     CAMERA_SYNC_TRACE;
5225     auto captureSession = GetCaptureSession();
5226     CHECK_RETURN_RET_ELOG(!captureSession, CameraErrorCode::SERVICE_FATL_ERROR,
5227         "CaptureSession::SetHasFitedRotation captureSession is nullptr");
5228     int32_t errCode = captureSession->SetHasFitedRotation(isHasFitedRotation);
5229     CHECK_PRINT_ELOG(errCode != CAMERA_OK, "Failed to SetHasFitedRotation!, %{public}d", errCode);
5230     return errCode;
5231 }
5232 
EnableAutoFrameRate(bool isEnable)5233 void CaptureSession::EnableAutoFrameRate(bool isEnable)
5234 {
5235     CAMERA_SYNC_TRACE;
5236     MEDIA_INFO_LOG("Enter EnableAutoFrameRate, isEnable:%{public}d", isEnable);
5237     uint8_t enableValue = static_cast<uint8_t>(isEnable);
5238     CHECK_PRINT_ELOG(!AddOrUpdateMetadata(changedMetadata_, OHOS_CONTROL_AUTO_VIDEO_FRAME_RATE, &enableValue, 1),
5239         "EnableAutoFrameRate Failed to enable OHOS_CONTROL_AUTO_VIDEO_FRAME_RATE");
5240     // LCOV_EXCL_STOP
5241 }
5242 
AdjustRenderFit()5243 void CaptureSession::AdjustRenderFit()
5244 {
5245     std::lock_guard<std::mutex> lock(captureOutputSetsMutex_);
5246     for (const auto& output : captureOutputSets_) {
5247         auto item = output.promote();
5248         CHECK_CONTINUE(item && item->GetOutputType() != CAPTURE_OUTPUT_TYPE_PREVIEW);
5249         sptr<PreviewOutput> previewOutput = (sptr<PreviewOutput>&)item;
5250         previewOutput->AdjustRenderFit();
5251     }
5252 }
5253 
SetMacroStatusCallback(std::shared_ptr<MacroStatusCallback> callback)5254 void CaptureSession::SetMacroStatusCallback(std::shared_ptr<MacroStatusCallback> callback)
5255 {
5256     MEDIA_DEBUG_LOG("CaptureSession::SetMacroStatusCallback ENTER");
5257     std::lock_guard<std::mutex> lock(sessionCallbackMutex_);
5258     macroStatusCallback_ = callback;
5259     return;
5260 }
5261 
5262 } // namespace CameraStandard
5263 } // namespace OHOS
5264