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