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