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