• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "hcapture_session.h"
17 
18 #include <algorithm>
19 #include <atomic>
20 #include <cerrno>
21 #include <cinttypes>
22 #include <cstddef>
23 #include <cstdint>
24 #include <functional>
25 #include <memory>
26 #include <mutex>
27 #include <new>
28 #include <sched.h>
29 #include <string>
30 #include <sync_fence.h>
31 #include <utility>
32 #include <vector>
33 
34 #include "avcodec_task_manager.h"
35 #include "base_types.h"
36 #include "blocking_queue.h"
37 #include "camera_info_dumper.h"
38 #include "camera_log.h"
39 #include "camera_report_dfx_uitls.h"
40 #include "camera_report_uitls.h"
41 #include "camera_server_photo_proxy.h"
42 #include "camera_service_ipc_interface_code.h"
43 #include "camera_util.h"
44 #include "datetime_ex.h"
45 #include "deferred_processing_service.h"
46 #include "display/composer/v1_1/display_composer_type.h"
47 #include "display_manager.h"
48 #include "fixed_size_list.h"
49 #include "hcamera_restore_param.h"
50 #include "hcamera_service.h"
51 #include "hcamera_session_manager.h"
52 #include "hstream_capture.h"
53 #include "hstream_common.h"
54 #include "hstream_depth_data.h"
55 #include "hstream_metadata.h"
56 #include "hstream_repeat.h"
57 #include "icapture_session.h"
58 #include "iconsumer_surface.h"
59 #include "image_type.h"
60 #include "ipc_skeleton.h"
61 #include "istream_common.h"
62 #include "photo_asset_interface.h"
63 #include "photo_asset_proxy.h"
64 #include "picture_interface.h"
65 #include "moving_photo/moving_photo_surface_wrapper.h"
66 #include "moving_photo_video_cache.h"
67 #include "parameters.h"
68 #include "refbase.h"
69 #include "res_sched_client.h"
70 #include "res_type.h"
71 #include "smooth_zoom.h"
72 #include "surface.h"
73 #include "surface_buffer.h"
74 #include "v1_0/types.h"
75 #include "hstream_operator_manager.h"
76 
77 using namespace OHOS::AAFwk;
78 namespace OHOS {
79 namespace CameraStandard {
80 using namespace OHOS::HDI::Display::Composer::V1_1;
81 
82 namespace {
83 constexpr int32_t WIDE_CAMERA_ZOOM_RANGE = 0;
84 constexpr int32_t MAIN_CAMERA_ZOOM_RANGE = 1;
85 constexpr int32_t TWO_X_EXIT_TELE_ZOOM_RANGE = 2;
86 constexpr int32_t TELE_CAMERA_ZOOM_RANGE = 3;
87 constexpr int32_t WIDE_MAIN_ZOOM_PER = 0;
88 constexpr int32_t TELE_MAIN_ZOOM_PER = 1;
89 constexpr int32_t TELE_2X_ZOOM_PER = 2;
90 constexpr int32_t WIDE_TELE_ZOOM_PER = 3;
91 constexpr int32_t ZOOM_IN_PER = 0;
92 constexpr int32_t ZOOM_OUT_PERF = 1;
93 constexpr int32_t ZOOM_BEZIER_VALUE_COUNT = 5;
94 static const int32_t SESSIONID_BEGIN = 1;
95 static const int32_t SESSIONID_MAX = INT32_MAX - 1000;
96 static std::atomic<int32_t> g_currentSessionId = SESSIONID_BEGIN;
97 
GenerateSessionId()98 static int32_t GenerateSessionId()
99 {
100     int newId = g_currentSessionId++;
101     if (newId > SESSIONID_MAX) {
102         g_currentSessionId = SESSIONID_BEGIN;
103     }
104     return newId;
105 }
106 }  // namespace
107 
108 static const std::map<CaptureSessionState, std::string> SESSION_STATE_STRING_MAP = {
109     { CaptureSessionState::SESSION_INIT, "Init" },
110     { CaptureSessionState::SESSION_CONFIG_INPROGRESS, "Config_In-progress" },
111     { CaptureSessionState::SESSION_CONFIG_COMMITTED, "Committed" },
112     { CaptureSessionState::SESSION_RELEASED, "Released" }, { CaptureSessionState::SESSION_STARTED, "Started" }
113 };
114 
NewInstance(const uint32_t callerToken,int32_t opMode,sptr<HCaptureSession> & outSession)115 CamServiceError HCaptureSession::NewInstance(
116     const uint32_t callerToken, int32_t opMode, sptr<HCaptureSession>& outSession)
117 {
118     CamServiceError errCode = CAMERA_OK;
119     sptr<HCaptureSession> session = new (std::nothrow) HCaptureSession(callerToken, opMode);
120     if (session == nullptr) {
121         return CAMERA_ALLOC_ERROR;
122     }
123 
124     auto &sessionManager = HCameraSessionManager::GetInstance();
125     MEDIA_DEBUG_LOG("HCaptureSession::NewInstance start, total "
126                     "session:(%{public}zu), current pid(%{public}d).",
127         sessionManager.GetTotalSessionSize(),
128         session->pid_);
129     if (sessionManager.AddSession(session) == CAMERA_SESSION_MAX_INSTANCE_NUMBER_REACHED) {
130         MEDIA_WARNING_LOG("HCaptureSession::HCaptureSession maximum session limit reached. ");
131     }
132     // Avoid multithread leak session, PreemptOverflowSessions need to call after AddSession, ignore
133     // CAMERA_SESSION_MAX_INSTANCE_NUMBER_REACHED.
134     sessionManager.PreemptOverflowSessions(IPCSkeleton::GetCallingPid());
135     outSession = session;
136     MEDIA_INFO_LOG("HCaptureSession::NewInstance end, sessionId: %{public}d, "
137                    "total session:(%{public}zu). current opMode_= %{public}d "
138                    "errorCode:%{public}d",
139         outSession->sessionId_,
140         sessionManager.GetTotalSessionSize(),
141         opMode,
142         errCode);
143     return errCode;
144 }
145 
OnSessionPreempt()146 void HCaptureSession::OnSessionPreempt()
147 {
148     auto disconnectDevice = GetCameraDevice();
149     CHECK_EXECUTE(disconnectDevice != nullptr, disconnectDevice->OnError(HDI::Camera::V1_0::DEVICE_PREEMPT, 0));
150     MEDIA_ERR_LOG("HCaptureSession::HCaptureSession maximum session limit reached. "
151                   "Releasing the earliest session.");
152     Release();
153 }
154 
HCaptureSession(const uint32_t callingTokenId,int32_t opMode)155 HCaptureSession::HCaptureSession(const uint32_t callingTokenId, int32_t opMode)
156 {
157     pid_ = IPCSkeleton::GetCallingPid();
158     uid_ = static_cast<uint32_t>(IPCSkeleton::GetCallingUid());
159     sessionId_ = GenerateSessionId();
160     callerToken_ = callingTokenId;
161     opMode_ = opMode;
162     InitialHStreamOperator();
163 }
164 
~HCaptureSession()165 HCaptureSession::~HCaptureSession()
166 {
167     CAMERA_SYNC_TRACE;
168     Release(CaptureSessionReleaseType::RELEASE_TYPE_OBJ_DIED);
169 }
170 
GetPid()171 pid_t HCaptureSession::GetPid()
172 {
173     return pid_;
174 }
175 
GetSessionId()176 int32_t HCaptureSession::GetSessionId()
177 {
178     return sessionId_;
179 }
180 
GetopMode()181 int32_t HCaptureSession::GetopMode()
182 {
183     CHECK_ERROR_RETURN_RET(featureMode_, featureMode_);
184     return opMode_;
185 }
186 
GetCurrentStreamInfos(std::vector<StreamInfo_V1_1> & streamInfos)187 int32_t HCaptureSession::GetCurrentStreamInfos(std::vector<StreamInfo_V1_1>& streamInfos)
188 {
189     auto hStreamOperatorSptr = GetStreamOperator();
190     CHECK_ERROR_RETURN_RET_LOG(hStreamOperatorSptr == nullptr, CAMERA_INVALID_ARG,
191         "hStreamOperator_ is null");
192     return hStreamOperatorSptr->GetCurrentStreamInfos(streamInfos);
193 }
194 
195 
DynamicConfigStream()196 void HCaptureSession::DynamicConfigStream()
197 {
198     isDynamicConfiged_ = false;
199     MEDIA_INFO_LOG("HCaptureSession::DynamicConfigStream enter. currentState = "
200                    "%{public}s, sessionID: %{public}d",
201         GetSessionState().c_str(),
202         GetSessionId());
203     auto currentState = stateMachine_.GetCurrentState();
204     if (currentState == CaptureSessionState::SESSION_STARTED) {
205         isDynamicConfiged_ = CheckSystemApp();  // System applications support dynamic config stream.
206         MEDIA_INFO_LOG("HCaptureSession::DynamicConfigStream support dynamic "
207                        "stream config, sessionID: %{public}d",
208             GetSessionId());
209     }
210 }
211 
IsNeedDynamicConfig()212 bool HCaptureSession::IsNeedDynamicConfig()
213 {
214     return isDynamicConfiged_;
215 }
216 
BeginConfig()217 int32_t HCaptureSession::BeginConfig()
218 {
219     CAMERA_SYNC_TRACE;
220     int32_t errCode;
221     MEDIA_INFO_LOG("HCaptureSession::BeginConfig prepare execute, sessionID: %{public}d", GetSessionId());
222     InitialHStreamOperator();
223     stateMachine_.StateGuard([&errCode, this](const CaptureSessionState state) {
224         DynamicConfigStream();
225         bool isStateValid = stateMachine_.Transfer(CaptureSessionState::SESSION_CONFIG_INPROGRESS);
226         if (!isStateValid) {
227             MEDIA_ERR_LOG("HCaptureSession::BeginConfig in invalid state %{public}d, "
228                           ", sessionID: %{public}d",
229                 state,
230                 GetSessionId());
231             errCode = CAMERA_INVALID_STATE;
232             isDynamicConfiged_ = false;
233             return;
234         }
235         auto hStreamOperatorSptr = GetStreamOperator();
236         CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr, "hStreamOperator_ is null");
237         if (!IsNeedDynamicConfig() && (hStreamOperatorSptr->GetOfflineOutptSize() == 0)) {
238             UnlinkInputAndOutputs();
239             ClearSketchRepeatStream();
240             ClearMovingPhotoRepeatStream();
241         }
242     });
243     if (errCode == CAMERA_OK) {
244         MEDIA_INFO_LOG("HCaptureSession::BeginConfig execute success, sessionID: %{public}d", GetSessionId());
245     } else {
246         CameraReportUtils::ReportCameraError(
247             "HCaptureSession::BeginConfig, sessionID: " + std::to_string(GetSessionId()),
248             errCode, false, CameraReportUtils::GetCallerInfo());
249     }
250     return errCode;
251 }
252 
CanAddInput(sptr<ICameraDeviceService> cameraDevice,bool & result)253 int32_t HCaptureSession::CanAddInput(sptr<ICameraDeviceService> cameraDevice, bool& result)
254 {
255     CAMERA_SYNC_TRACE;
256     int32_t errorCode = CAMERA_OK;
257     result = false;
258     stateMachine_.StateGuard([this, &errorCode, &cameraDevice](const CaptureSessionState currentState) {
259         if (currentState != CaptureSessionState::SESSION_CONFIG_INPROGRESS) {
260             MEDIA_ERR_LOG("HCaptureSession::CanAddInput Need to call BeginConfig "
261                           "before adding input, sessionID: %{public}d",
262                 GetSessionId());
263             errorCode = CAMERA_INVALID_STATE;
264             return;
265         }
266         if ((GetCameraDevice() != nullptr)) {
267             MEDIA_ERR_LOG("HCaptureSession::CanAddInput Only one input is supported, "
268                           "sessionID: %{public}d",
269                 GetSessionId());
270             errorCode = CAMERA_INVALID_SESSION_CFG;
271             return;
272         }
273         sptr<HCameraDevice> hCameraDevice = static_cast<HCameraDevice*>(cameraDevice.GetRefPtr());
274         auto deviceSession = hCameraDevice->GetStreamOperatorCallback();
275         if (deviceSession != nullptr) {
276             errorCode = CAMERA_OPERATION_NOT_ALLOWED;
277             return;
278         }
279     });
280     if (errorCode == CAMERA_OK) {
281         result = true;
282         CAMERA_SYSEVENT_STATISTIC(CreateMsg("CaptureSession::CanAddInput, sessionID: %d", GetSessionId()));
283     }
284     return errorCode;
285 }
286 
AddInput(sptr<ICameraDeviceService> cameraDevice)287 int32_t HCaptureSession::AddInput(sptr<ICameraDeviceService> cameraDevice)
288 {
289     CAMERA_SYNC_TRACE;
290     int32_t errorCode = CAMERA_OK;
291     if (cameraDevice == nullptr) {
292         errorCode = CAMERA_INVALID_ARG;
293         MEDIA_ERR_LOG("HCaptureSession::AddInput cameraDevice is null, sessionID: %{public}d", GetSessionId());
294         CameraReportUtils::ReportCameraError(
295             "HCaptureSession::AddInput", errorCode, false, CameraReportUtils::GetCallerInfo());
296         return errorCode;
297     }
298     MEDIA_INFO_LOG("HCaptureSession::AddInput prepare execute, sessionID: %{public}d", GetSessionId());
299     stateMachine_.StateGuard([this, &errorCode, &cameraDevice](const CaptureSessionState currentState) {
300         if (currentState != CaptureSessionState::SESSION_CONFIG_INPROGRESS) {
301             MEDIA_ERR_LOG("HCaptureSession::AddInput Need to call BeginConfig before "
302                           "adding input, sessionID: %{public}d",
303                 GetSessionId());
304             errorCode = CAMERA_INVALID_STATE;
305             return;
306         }
307         if ((GetCameraDevice() != nullptr)) {
308             MEDIA_ERR_LOG("HCaptureSession::AddInput Only one input is supported, "
309                           "sessionID: %{public}d",
310                 GetSessionId());
311             errorCode = CAMERA_INVALID_SESSION_CFG;
312             return;
313         }
314         sptr<HCameraDevice> hCameraDevice = static_cast<HCameraDevice*>(cameraDevice.GetRefPtr());
315         MEDIA_INFO_LOG("HCaptureSession::AddInput device:%{public}s", hCameraDevice->GetCameraId().c_str());
316         SetCameraDevice(hCameraDevice);
317         hCameraDevice->DispatchDefaultSettingToHdi();
318     });
319     if (errorCode == CAMERA_OK) {
320         CAMERA_SYSEVENT_STATISTIC(CreateMsg("CaptureSession::AddInput, sessionID: %d", GetSessionId()));
321     } else {
322         CameraReportUtils::ReportCameraError(
323             "HCaptureSession::AddInput", errorCode, false, CameraReportUtils::GetCallerInfo());
324     }
325     MEDIA_INFO_LOG("HCaptureSession::AddInput execute success, sessionID: %{public}d", GetSessionId());
326     return errorCode;
327 }
328 
BeforeDeviceClose()329 void HCaptureSession::BeforeDeviceClose()
330 {
331     MEDIA_INFO_LOG("HCaptureSession::BeforeDeviceClose UnlinkInputAndOutputs");
332     UnlinkInputAndOutputs();
333     auto hStreamOperatorSptr = GetStreamOperator();
334     CHECK_ERROR_RETURN_LOG(
335         hStreamOperatorSptr == nullptr, "HCaptureSession::BeforeDeviceClose hStreamOperatorSptr is null");
336     if (!hStreamOperatorSptr->IsOfflineCapture()) {
337         hStreamOperatorSptr->Release();
338     }
339 }
340 
341 class DisplayRotationListener : public OHOS::Rosen::DisplayManager::IDisplayListener {
342 public:
DisplayRotationListener()343     explicit DisplayRotationListener() {};
344     virtual ~DisplayRotationListener() = default;
OnCreate(OHOS::Rosen::DisplayId)345     void OnCreate(OHOS::Rosen::DisplayId) override {}
OnDestroy(OHOS::Rosen::DisplayId)346     void OnDestroy(OHOS::Rosen::DisplayId) override {}
OnChange(OHOS::Rosen::DisplayId displayId)347     void OnChange(OHOS::Rosen::DisplayId displayId) override
348     {
349         sptr<Rosen::Display> display = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
350         if (display == nullptr) {
351             MEDIA_INFO_LOG("Get display info failed, display:%{public}" PRIu64 "", displayId);
352             display = Rosen::DisplayManager::GetInstance().GetDisplayById(0);
353             CHECK_ERROR_RETURN_LOG(display == nullptr, "Get display info failed, display is nullptr");
354         }
355         {
356             Rosen::Rotation currentRotation = display->GetRotation();
357             std::lock_guard<std::mutex> lock(mStreamManagerLock_);
358             for (auto& repeatStream : repeatStreamList_) {
359                 CHECK_EXECUTE(repeatStream, repeatStream->SetStreamTransform(static_cast<int>(currentRotation)));
360             }
361         }
362     }
363 
AddHstreamRepeatForListener(sptr<HStreamRepeat> repeatStream)364     void AddHstreamRepeatForListener(sptr<HStreamRepeat> repeatStream)
365     {
366         std::lock_guard<std::mutex> lock(mStreamManagerLock_);
367         CHECK_EXECUTE(repeatStream, repeatStreamList_.push_back(repeatStream));
368     }
369 
RemoveHstreamRepeatForListener(sptr<HStreamRepeat> repeatStream)370     void RemoveHstreamRepeatForListener(sptr<HStreamRepeat> repeatStream)
371     {
372         std::lock_guard<std::mutex> lock(mStreamManagerLock_);
373         if (repeatStream) {
374             repeatStreamList_.erase(
375                 std::remove(repeatStreamList_.begin(), repeatStreamList_.end(), repeatStream), repeatStreamList_.end());
376         }
377     }
378 
379 public:
380     std::list<sptr<HStreamRepeat>> repeatStreamList_;
381     std::mutex mStreamManagerLock_;
382 };
383 
SetPreviewRotation(std::string & deviceClass)384 int32_t HCaptureSession::SetPreviewRotation(std::string &deviceClass)
385 {
386     auto hStreamOperatorSptr = GetStreamOperator();
387     CHECK_ERROR_RETURN_RET_LOG(hStreamOperatorSptr == nullptr, CAMERA_INVALID_ARG,
388         "hStreamOperator_ is null");
389     hStreamOperatorSptr->SetPreviewRotation(deviceClass);
390     return CAMERA_OK;
391 }
392 
InitialHStreamOperator()393 void HCaptureSession::InitialHStreamOperator()
394 {
395     auto hStreamOperatorTemp = GetStreamOperator();
396     if (hStreamOperatorTemp == nullptr) {
397         sptr<HStreamOperator> hStreamOperator = HStreamOperator::NewInstance(callerToken_, opMode_);
398         SetStreamOperator(hStreamOperator);
399         HStreamOperatorManager::GetInstance()->AddStreamOperator(hStreamOperator); // 鍗曚緥绠$悊streamoperator 寰呮壘鍞竴key
400     }
401 }
402 
AddOutput(StreamType streamType,sptr<IStreamCommon> stream)403 int32_t HCaptureSession::AddOutput(StreamType streamType, sptr<IStreamCommon> stream)
404 {
405     int32_t errorCode = CAMERA_INVALID_ARG;
406     if (stream == nullptr) {
407         MEDIA_ERR_LOG("HCaptureSession::AddOutput stream is null, sessionID: %{public}d", GetSessionId());
408         CameraReportUtils::ReportCameraError(
409             "HCaptureSession::AddOutput", errorCode, false, CameraReportUtils::GetCallerInfo());
410         return errorCode;
411     }
412     stateMachine_.StateGuard([this, &errorCode, streamType, &stream](const CaptureSessionState currentState) {
413         InitialHStreamOperator();
414         auto hStreamOperatorSptr = GetStreamOperator();
415         CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr, "hStreamOperator_ is null");
416         if (currentState != CaptureSessionState::SESSION_CONFIG_INPROGRESS) {
417             MEDIA_ERR_LOG("HCaptureSession::AddOutput Need to call BeginConfig "
418                           "before adding output, sessionID: %{public}d",
419                 GetSessionId());
420             errorCode = CAMERA_INVALID_STATE;
421             return;
422         }
423         errorCode = hStreamOperatorSptr->AddOutput(streamType, stream);
424     });
425     if (errorCode == CAMERA_OK) {
426         CAMERA_SYSEVENT_STATISTIC(
427             CreateMsg("CaptureSession::AddOutput with %d, sessionID: %{public}d", streamType, GetSessionId()));
428     } else {
429         CameraReportUtils::ReportCameraError(
430             "HCaptureSession::AddOutput", errorCode, false, CameraReportUtils::GetCallerInfo());
431     }
432     MEDIA_INFO_LOG("CaptureSession::AddOutput with with %{public}d, rc = "
433                    "%{public}d, sessionID: %{public}d",
434         streamType,
435         errorCode,
436         GetSessionId());
437     return errorCode;
438 }
439 
RemoveInput(sptr<ICameraDeviceService> cameraDevice)440 int32_t HCaptureSession::RemoveInput(sptr<ICameraDeviceService> cameraDevice)
441 {
442     int32_t errorCode = CAMERA_OK;
443     if (cameraDevice == nullptr) {
444         errorCode = CAMERA_INVALID_ARG;
445         MEDIA_ERR_LOG("HCaptureSession::RemoveInput cameraDevice is null, "
446                       "sessionID: %{public}d",
447             GetSessionId());
448         CameraReportUtils::ReportCameraError(
449             "HCaptureSession::RemoveInput", errorCode, false, CameraReportUtils::GetCallerInfo());
450         return errorCode;
451     }
452     MEDIA_INFO_LOG("HCaptureSession::RemoveInput prepare execute, sessionID: %{public}d", GetSessionId());
453     stateMachine_.StateGuard([this, &errorCode, &cameraDevice](const CaptureSessionState currentState) {
454         if (currentState != CaptureSessionState::SESSION_CONFIG_INPROGRESS) {
455             MEDIA_ERR_LOG("HCaptureSession::RemoveInput Need to call BeginConfig "
456                           "before removing input, sessionID: %{public}d",
457                 GetSessionId());
458             errorCode = CAMERA_INVALID_STATE;
459             return;
460         }
461         if (IsNeedDynamicConfig()) {
462             UnlinkInputAndOutputs();
463             ClearSketchRepeatStream();
464             ClearMovingPhotoRepeatStream();
465         }
466         auto currentDevice = GetCameraDevice();
467         if (currentDevice != nullptr && cameraDevice->AsObject() == currentDevice->AsObject()) {
468             // Do not close device while remove input!
469             MEDIA_INFO_LOG(
470                 "HCaptureSession::RemoveInput camera id is %{public}s", currentDevice->GetCameraId().c_str());
471             currentDevice->ResetDeviceSettings();
472             SetCameraDevice(nullptr);
473             currentDevice->SetStreamOperatorCallback(nullptr);
474         } else {
475             MEDIA_ERR_LOG("HCaptureSession::RemoveInput Invalid camera device, "
476                           "sessionID: %{public}d",
477                 GetSessionId());
478             errorCode = CAMERA_INVALID_SESSION_CFG;
479         }
480     });
481     if (errorCode == CAMERA_OK) {
482         CAMERA_SYSEVENT_STATISTIC(CreateMsg("CaptureSession::RemoveInput, sessionID: %d", GetSessionId()));
483     } else {
484         CameraReportUtils::ReportCameraError(
485             "HCaptureSession::RemoveInput", errorCode, false, CameraReportUtils::GetCallerInfo());
486     }
487     MEDIA_INFO_LOG("HCaptureSession::RemoveInput execute success, sessionID: %{public}d", GetSessionId());
488     return errorCode;
489 }
490 
RemoveOutputStream(sptr<HStreamCommon> stream)491 int32_t HCaptureSession::RemoveOutputStream(sptr<HStreamCommon> stream)
492 {
493     CAMERA_SYNC_TRACE;
494     CHECK_ERROR_RETURN_RET_LOG(
495         stream == nullptr, CAMERA_INVALID_ARG, "HCaptureSession::RemoveOutputStream stream is null");
496     MEDIA_INFO_LOG("HCaptureSession::RemoveOutputStream,streamType:%{public}d, streamId:%{public}d",
497         stream->GetStreamType(), stream->GetFwkStreamId());
498     auto hStreamOperatorSptr = GetStreamOperator();
499     CHECK_ERROR_RETURN_RET_LOG(hStreamOperatorSptr == nullptr, CAMERA_INVALID_ARG,
500         "hStreamOperatorSptr is null");
501     int32_t errorCode = hStreamOperatorSptr->RemoveOutputStream(stream);
502     CHECK_ERROR_RETURN_RET_LOG(errorCode != CAMERA_OK, CAMERA_INVALID_SESSION_CFG,
503         "HCaptureSession::RemoveOutputStream Invalid output");
504     return CAMERA_OK;
505 }
506 
RemoveOutput(StreamType streamType,sptr<IStreamCommon> stream)507 int32_t HCaptureSession::RemoveOutput(StreamType streamType, sptr<IStreamCommon> stream)
508 {
509     int32_t errorCode = CAMERA_INVALID_ARG;
510     if (stream == nullptr) {
511         MEDIA_ERR_LOG("HCaptureSession::RemoveOutput stream is null, sessionID: %{public}d", GetSessionId());
512         CameraReportUtils::ReportCameraError(
513             "HCaptureSession::RemoveOutput", errorCode, false, CameraReportUtils::GetCallerInfo());
514         return errorCode;
515     }
516     MEDIA_INFO_LOG("HCaptureSession::RemoveOutput prepare execute, sessionID: %{public}d", GetSessionId());
517     stateMachine_.StateGuard([this, &errorCode, streamType, &stream](const CaptureSessionState currentState) {
518         if (currentState != CaptureSessionState::SESSION_CONFIG_INPROGRESS) {
519             MEDIA_ERR_LOG("HCaptureSession::RemoveOutput Need to call BeginConfig "
520                           "before removing output, sessionID: %{public}d",
521                 GetSessionId());
522             errorCode = CAMERA_INVALID_STATE;
523             return;
524         }
525         auto hStreamOperatorSptr = GetStreamOperator();
526         CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr, "hStreamOperatorSptr is null");
527         errorCode = hStreamOperatorSptr->RemoveOutput(streamType, stream);
528     });
529     if (errorCode == CAMERA_OK) {
530         CAMERA_SYSEVENT_STATISTIC(
531             CreateMsg("CaptureSession::RemoveOutput with %d, sessionID: %d", streamType, GetSessionId()));
532     } else {
533         CameraReportUtils::ReportCameraError(
534             "HCaptureSession::RemoveOutput", errorCode, false, CameraReportUtils::GetCallerInfo());
535     }
536     MEDIA_INFO_LOG("HCaptureSession::RemoveOutput execute success, sessionID: %{public}d", GetSessionId());
537     return errorCode;
538 }
539 
ValidateSessionInputs()540 int32_t HCaptureSession::ValidateSessionInputs()
541 {
542     CHECK_ERROR_RETURN_RET_LOG(GetCameraDevice() == nullptr,
543         CAMERA_INVALID_SESSION_CFG,
544         "HCaptureSession::ValidateSessionInputs No inputs "
545         "present, sessionID: %{public}d",
546         GetSessionId());
547     return CAMERA_OK;
548 }
549 
ValidateSessionOutputs()550 int32_t HCaptureSession::ValidateSessionOutputs()
551 {
552     auto hStreamOperatorSptr = GetStreamOperator();
553     CHECK_ERROR_RETURN_RET_LOG((hStreamOperatorSptr == nullptr || hStreamOperatorSptr->GetStreamsSize() == 0),
554         CAMERA_INVALID_SESSION_CFG, "HCaptureSession::ValidateSessionOutputs No outputs present");
555     return CAMERA_OK;
556 }
557 
LinkInputAndOutputs()558 int32_t HCaptureSession::LinkInputAndOutputs()
559 {
560     int32_t rc;
561     auto hStreamOperatorSptr = GetStreamOperator();
562     CHECK_ERROR_RETURN_RET_LOG(hStreamOperatorSptr == nullptr, CAMERA_INVALID_SESSION_CFG,
563         "HCaptureSession::ValidateSessionOutputs No outputs present");
564     auto device = GetCameraDevice();
565     CHECK_ERROR_RETURN_RET_LOG(device == nullptr, CAMERA_INVALID_SESSION_CFG,
566         "HCaptureSession::LinkInputAndOutputs device is null");
567     auto settings = device->GetDeviceAbility();
568     CHECK_ERROR_RETURN_RET_LOG(settings == nullptr, CAMERA_UNKNOWN_ERROR,
569         "HCaptureSession::LinkInputAndOutputs deviceAbility is null");
570     CHECK_ERROR_RETURN_RET_LOG(!IsValidMode(opMode_, settings), CAMERA_INVALID_SESSION_CFG,
571         "HCaptureSession::LinkInputAndOutputs IsValidMode false");
572     rc = hStreamOperatorSptr->LinkInputAndOutputs(settings, GetopMode());
573     MEDIA_INFO_LOG("HCaptureSession::LinkInputAndOutputs execute success");
574     return rc;
575 }
576 
UnlinkInputAndOutputs()577 int32_t HCaptureSession::UnlinkInputAndOutputs()
578 {
579     CAMERA_SYNC_TRACE;
580     int32_t rc = CAMERA_UNKNOWN_ERROR;
581     auto hStreamOperatorSptr = GetStreamOperator();
582     CHECK_ERROR_RETURN_RET_LOG(hStreamOperatorSptr == nullptr,  rc,
583         "HCaptureSession::ValidateSessionOutputs No outputs present");
584     rc = hStreamOperatorSptr->UnlinkInputAndOutputs();
585         // HDI release streams, do not clear streamContainer_
586     return rc;
587 }
588 
ExpandSketchRepeatStream()589 void HCaptureSession::ExpandSketchRepeatStream()
590 {
591     MEDIA_DEBUG_LOG("Enter HCaptureSession::ExpandSketchRepeatStream(), "
592         "sessionID: %{public}d", GetSessionId());
593     auto hStreamOperatorSptr = GetStreamOperator();
594     CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr,
595         "HCaptureSession::ValidateSessionOutputs No outputs present");
596     hStreamOperatorSptr->ExpandSketchRepeatStream();
597     MEDIA_DEBUG_LOG("Exit HCaptureSession::ExpandSketchRepeatStream()");
598 }
599 
ExpandMovingPhotoRepeatStream()600 void HCaptureSession::ExpandMovingPhotoRepeatStream()
601 {
602     CAMERA_SYNC_TRACE;
603     MEDIA_DEBUG_LOG("ExpandMovingPhotoRepeatStream enter, sessionID: %{public}d", GetSessionId());
604     if (!GetCameraDevice()->CheckMovingPhotoSupported(GetopMode())) {
605         MEDIA_DEBUG_LOG("movingPhoto is not supported, sessionID: %{public}d", GetSessionId());
606         return;
607     }
608     auto hStreamOperatorSptr = GetStreamOperator();
609     CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr,
610         "HCaptureSession::ValidateSessionOutputs No outputs present");
611     hStreamOperatorSptr->ExpandMovingPhotoRepeatStream();
612     MEDIA_DEBUG_LOG("ExpandMovingPhotoRepeatStream Exit");
613 }
614 
ClearSketchRepeatStream()615 void HCaptureSession::ClearSketchRepeatStream()
616 {
617     MEDIA_DEBUG_LOG("Enter HCaptureSession::ClearSketchRepeatStream(), sessionID: %{public}d", GetSessionId());
618 
619     auto hStreamOperatorSptr = GetStreamOperator();
620     CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr, "hStreamOperator is nullptr");
621     return hStreamOperatorSptr->ClearSketchRepeatStream();
622 }
623 
ClearMovingPhotoRepeatStream()624 void HCaptureSession::ClearMovingPhotoRepeatStream()
625 {
626     CAMERA_SYNC_TRACE;
627     MEDIA_DEBUG_LOG("Enter HCaptureSession::ClearMovingPhotoRepeatStream(), "
628                     "sessionID: %{public}d",
629         GetSessionId());
630     // Already added session lock in BeginConfig()
631     auto hStreamOperatorSptr = GetStreamOperator();
632     CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr, "hStreamOperator is nullptr");
633     return hStreamOperatorSptr->ClearMovingPhotoRepeatStream();
634 }
635 
ValidateSession()636 int32_t HCaptureSession::ValidateSession()
637 {
638     int32_t errorCode = CAMERA_OK;
639     errorCode = ValidateSessionInputs();
640     CHECK_ERROR_RETURN_RET(errorCode != CAMERA_OK, errorCode);
641     errorCode = ValidateSessionOutputs();
642     return errorCode;
643 }
644 
SetCommitConfigFlag(bool isNeedCommitting)645 int32_t HCaptureSession::SetCommitConfigFlag(bool isNeedCommitting)
646 {
647     isNeedCommitting_ = isNeedCommitting;
648     return CAMERA_OK;
649 }
650 
CommitConfig()651 int32_t HCaptureSession::CommitConfig()
652 {
653     CAMERA_SYNC_TRACE;
654     MEDIA_INFO_LOG("HCaptureSession::CommitConfig begin, sessionID: %{public}d", GetSessionId());
655     int32_t errorCode = CAMERA_OK;
656     stateMachine_.StateGuard([&errorCode, this](CaptureSessionState currentState) {
657         bool isTransferSupport = stateMachine_.CheckTransfer(CaptureSessionState::SESSION_CONFIG_COMMITTED);
658         CHECK_ERROR_RETURN_LOG(!isTransferSupport, "HCaptureSession::CommitConfig() Need to call BeginConfig "
659             "before committing configuration, sessionID: %{public}d", GetSessionId());
660         if (isNeedCommitting_) {
661             stateMachine_.Transfer(CaptureSessionState::SESSION_CONFIG_COMMITTED);
662             return;
663         }
664         auto hStreamOperatorSptr = GetStreamOperator();
665         CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr, "hStreamOperator is nullptr");
666         hStreamOperatorSptr->GetStreamOperator();
667         errorCode = ValidateSession();
668         CHECK_ERROR_RETURN(errorCode != CAMERA_OK);
669         if (!IsNeedDynamicConfig()) {
670             ExpandMovingPhotoRepeatStream(); // expand moving photo always
671             ExpandSketchRepeatStream();
672         }
673         auto device = GetCameraDevice();
674         if (device == nullptr) {
675             MEDIA_ERR_LOG("HCaptureSession::CommitConfig() Failed to commit config. "
676                           "camera device is null, sessionID: %{public}d", GetSessionId());
677             errorCode = CAMERA_INVALID_STATE;
678             return;
679         }
680         const int32_t secureMode = 15;
681         uint64_t secureSeqId = 0L;
682         device->GetSecureCameraSeq(&secureSeqId);
683         if (((GetopMode() == secureMode) ^ (secureSeqId != 0))) {
684             MEDIA_ERR_LOG("secureCamera is not allowed commit mode = %{public}d, "
685                           "sessionID: %{public}d.", GetopMode(), GetSessionId());
686             errorCode = CAMERA_OPERATION_NOT_ALLOWED;
687             return;
688         }
689         MEDIA_INFO_LOG("HCaptureSession::CommitConfig, sessionID: %{public}d, "
690                        "secureSeqId = %{public}" PRIu64 "", GetSessionId(), secureSeqId);
691         errorCode = LinkInputAndOutputs();
692         CHECK_ERROR_RETURN_LOG(errorCode != CAMERA_OK, "HCaptureSession::CommitConfig() Failed to commit "
693             "config. rc: %{public}d, sessionID: %{public}d", errorCode, GetSessionId());
694         stateMachine_.Transfer(CaptureSessionState::SESSION_CONFIG_COMMITTED);
695     });
696     CHECK_EXECUTE(errorCode != CAMERA_OK, CameraReportUtils::ReportCameraError(
697         "HCaptureSession::CommitConfig, sessionID: " + std::to_string(GetSessionId()),
698         errorCode, false, CameraReportUtils::GetCallerInfo()));
699     MEDIA_INFO_LOG("HCaptureSession::CommitConfig end, sessionID: %{public}d", GetSessionId());
700     return errorCode;
701 }
702 
GetActiveColorSpace(ColorSpace & colorSpace)703 int32_t HCaptureSession::GetActiveColorSpace(ColorSpace& colorSpace)
704 {
705     auto hStreamOperatorSptr = GetStreamOperator();
706     CHECK_ERROR_RETURN_RET_LOG(hStreamOperatorSptr == nullptr, CAMERA_OK, "hStreamOperator is nullptr");
707     hStreamOperatorSptr->GetActiveColorSpace(colorSpace);
708     return CAMERA_OK;
709 }
710 
SetColorSpace(ColorSpace colorSpace,bool isNeedUpdate)711 int32_t HCaptureSession::SetColorSpace(ColorSpace colorSpace, bool isNeedUpdate)
712 {
713     int32_t result = CAMERA_OK;
714     stateMachine_.StateGuard(
715         [&result, this, &colorSpace, &isNeedUpdate](CaptureSessionState currentState) {
716             MEDIA_INFO_LOG("HCaptureSession::SetColorSpace() ColorSpace : %{public}d", colorSpace);
717             if (!(currentState == CaptureSessionState::SESSION_CONFIG_INPROGRESS ||
718                     currentState == CaptureSessionState::SESSION_CONFIG_COMMITTED)) {
719                 MEDIA_ERR_LOG("HCaptureSession::SetColorSpace(), Invalid session state: "
720                               "%{public}d, sessionID: %{public}d",
721                     currentState,
722                     GetSessionId());
723                 result = CAMERA_INVALID_STATE;
724                 return;
725             }
726 
727             auto hStreamOperatorSptr = GetStreamOperator();
728             CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr, "hStreamOperator is nullptr");
729             result = hStreamOperatorSptr->SetColorSpace(colorSpace, isNeedUpdate);
730             if (isNeedUpdate &&  result != CAMERA_OK) {
731                 return;
732             }
733             if (isNeedUpdate) {
734                 auto device = GetCameraDevice();
735                 CHECK_ERROR_RETURN_LOG(device == nullptr, "HCaptureSession::SetColorSpace device is null");
736                 std::shared_ptr<OHOS::Camera::CameraMetadata> settings = device->CloneCachedSettings();
737                 MEDIA_INFO_LOG("HCaptureSession::SetColorSpace() CloneCachedSettings");
738                 DumpMetadata(settings);
739                 result = hStreamOperatorSptr->UpdateStreamInfos(settings);
740             }
741         });
742     return result;
743 }
744 
GetSessionState(CaptureSessionState & sessionState)745 int32_t HCaptureSession::GetSessionState(CaptureSessionState& sessionState)
746 {
747     sessionState = stateMachine_.GetCurrentState();
748     return CAMERA_OK;
749 }
750 
QueryFpsAndZoomRatio(float & currentFps,float & currentZoomRatio,std::vector<float> & crossZoomAndTime,int32_t operationMode)751 bool HCaptureSession::QueryFpsAndZoomRatio(
752     float &currentFps, float &currentZoomRatio, std::vector<float> &crossZoomAndTime, int32_t operationMode)
753 {
754     auto cameraDevice = GetCameraDevice();
755     CHECK_ERROR_RETURN_RET_LOG(
756         cameraDevice == nullptr, false, "HCaptureSession::QueryFpsAndZoomRatio() cameraDevice is null");
757     int32_t DEFAULT_ITEMS = 3;
758     int32_t DEFAULT_DATA_LENGTH = 200;
759     std::shared_ptr<OHOS::Camera::CameraMetadata> metaIn =
760         std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
761     std::shared_ptr<OHOS::Camera::CameraMetadata> metaOut =
762         std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
763     uint32_t count = 1;
764     uint32_t fps = 30;
765     uint32_t zoomRatio = 100;
766     uint32_t arrayCount = 154;
767     std::vector<uint32_t> vctZoomRatio;
768     vctZoomRatio.resize(arrayCount, 0);
769     metaIn->addEntry(OHOS_STATUS_CAMERA_CURRENT_FPS, &fps, count);
770     metaIn->addEntry(OHOS_STATUS_CAMERA_CURRENT_ZOOM_RATIO, &zoomRatio, count);
771     metaIn->addEntry(OHOS_STATUS_CAMERA_ZOOM_PERFORMANCE, vctZoomRatio.data(), arrayCount);
772     cameraDevice->GetStatus(metaIn, metaOut);
773     camera_metadata_item_t item;
774     int retFindMeta =
775         OHOS::Camera::FindCameraMetadataItem(metaOut->get(), OHOS_STATUS_CAMERA_CURRENT_ZOOM_RATIO, &item);
776     CHECK_ERROR_RETURN_RET_LOG(retFindMeta == CAM_META_ITEM_NOT_FOUND || item.count == 0, false,
777         "HCaptureSession::QueryFpsAndZoomRatio() current zoom not found, sessionID: %{public}d", GetSessionId());
778     if (retFindMeta == CAM_META_SUCCESS) {
779         currentZoomRatio = static_cast<float>(item.data.ui32[0]);
780         MEDIA_INFO_LOG("HCaptureSession::QueryFpsAndZoomRatio() current zoom "
781                        "%{public}d, sessionID: %{public}d.", item.data.ui32[0], GetSessionId());
782     }
783     retFindMeta = OHOS::Camera::FindCameraMetadataItem(metaOut->get(), OHOS_STATUS_CAMERA_CURRENT_FPS, &item);
784     CHECK_ERROR_RETURN_RET_LOG(retFindMeta == CAM_META_ITEM_NOT_FOUND || item.count == 0, false,
785         "HCaptureSession::QueryFpsAndZoomRatio() current fps not found, sessionID: %{public}d", GetSessionId());
786     if (retFindMeta == CAM_META_SUCCESS) {
787         currentFps = static_cast<float>(item.data.ui32[0]);
788         MEDIA_INFO_LOG("HCaptureSession::QueryFpsAndZoomRatio() current fps "
789             "%{public}d, sessionID: %{public}d.", item.data.ui32[0], GetSessionId());
790     }
791     retFindMeta = OHOS::Camera::FindCameraMetadataItem(metaOut->get(), OHOS_STATUS_CAMERA_ZOOM_PERFORMANCE, &item);
792     CHECK_ERROR_RETURN_RET_LOG(retFindMeta == CAM_META_ITEM_NOT_FOUND || item.count == 0, false,
793         "HCaptureSession::QueryFpsAndZoomRatio() current PERFORMANCE not found, sessionID: %{public}d",
794         GetSessionId());
795     if (retFindMeta == CAM_META_SUCCESS) {
796         MEDIA_INFO_LOG("HCaptureSession::QueryFpsAndZoomRatio() zoom performance count %{public}d,"
797             "sessionID: %{public}d.", item.count, GetSessionId());
798         QueryZoomPerformance(crossZoomAndTime, operationMode, item);
799     }
800     return true;
801 }
802 
QueryZoomPerformance(std::vector<float> & crossZoomAndTime,int32_t operationMode,const camera_metadata_item_t & zoomItem)803 bool HCaptureSession::QueryZoomPerformance(
804     std::vector<float> &crossZoomAndTime, int32_t operationMode, const camera_metadata_item_t &zoomItem)
805 {
806     auto cameraDevice = GetCameraDevice();
807     CHECK_ERROR_RETURN_RET_LOG(
808         cameraDevice == nullptr, false, "HCaptureSession::QueryZoomPerformance() cameraDevice is null");
809     // query zoom performance. begin
810     std::shared_ptr<OHOS::Camera::CameraMetadata> ability = cameraDevice->GetDeviceAbility();
811     MEDIA_DEBUG_LOG("HCaptureSession::QueryZoomPerformance() zoom performance count %{public}d.", zoomItem.count);
812     for (int i = 0; i < static_cast<int>(zoomItem.count); i++) {
813         MEDIA_DEBUG_LOG(
814             "HCaptureSession::QueryZoomPerformance() zoom performance value %{public}d.", zoomItem.data.ui32[i]);
815     }
816     int dataLenPerPoint = 3;
817     int headLenPerMode = 2;
818     MEDIA_DEBUG_LOG("HCaptureSession::QueryZoomPerformance() operationMode %{public}d, "
819                     "sessionID: %{public}d.",
820         static_cast<OHOS::HDI::Camera::V1_3::OperationMode>(operationMode),
821         GetSessionId());
822     for (int i = 0; i < static_cast<int>(zoomItem.count);) {
823         int sceneMode = static_cast<int>(zoomItem.data.ui32[i]);
824         int zoomPointsNum = static_cast<int>(zoomItem.data.ui32[i + 1]);
825         if (static_cast<OHOS::HDI::Camera::V1_3::OperationMode>(operationMode) == sceneMode) {
826             for (int j = 0; j < dataLenPerPoint * zoomPointsNum; j++) {
827                 crossZoomAndTime.push_back(zoomItem.data.ui32[i + headLenPerMode + j]);
828                 MEDIA_DEBUG_LOG("HCaptureSession::QueryZoomPerformance()    crossZoomAndTime "
829                                 "%{public}d, sessionID: %{public}d.",
830                     static_cast<int>(zoomItem.data.ui32[i + headLenPerMode + j]),
831                     GetSessionId());
832             }
833             break;
834         } else {
835             i = i + 1 + zoomPointsNum * dataLenPerPoint + 1;
836         }
837     }
838     return true;
839 }
840 
GetSensorOritation()841 int32_t HCaptureSession::GetSensorOritation()
842 {
843     auto cameraDevice = GetCameraDevice();
844     int32_t sensorOrientation = 0;
845     CHECK_ERROR_RETURN_RET_LOG(cameraDevice == nullptr,
846         sensorOrientation,
847         "HCaptureSession::GetSensorOritation() "
848         "cameraDevice is null, sessionID: %{public}d",
849         GetSessionId());
850     std::shared_ptr<OHOS::Camera::CameraMetadata> ability = cameraDevice->GetDeviceAbility();
851     CHECK_ERROR_RETURN_RET(ability == nullptr, sensorOrientation);
852     camera_metadata_item_t item;
853     int ret = OHOS::Camera::FindCameraMetadataItem(ability->get(), OHOS_SENSOR_ORIENTATION, &item);
854     CHECK_ERROR_RETURN_RET_LOG(ret != CAM_META_SUCCESS, sensorOrientation,
855         "HCaptureSession::GetSensorOritation get sensor orientation failed");
856     sensorOrientation = item.data.i32[0];
857     MEDIA_INFO_LOG("HCaptureSession::GetSensorOritation sensor orientation "
858                    "%{public}d, sessionID: %{public}d",
859         sensorOrientation,
860         GetSessionId());
861     return sensorOrientation;
862 }
863 
GetRangeId(float & zoomRatio,std::vector<float> & crossZoom)864 int32_t HCaptureSession::GetRangeId(float& zoomRatio, std::vector<float>& crossZoom)
865 {
866     int32_t rangId = 0;
867     for (; rangId < static_cast<int>(crossZoom.size()); rangId++) {
868         if (zoomRatio < crossZoom[rangId]) {
869             return rangId;
870         }
871     }
872     return rangId;
873 }
874 
isEqual(float zoomPointA,float zoomPointB)875 bool HCaptureSession::isEqual(float zoomPointA, float zoomPointB)
876 {
877     float epsilon = 0.00001f;
878     return fabs(zoomPointA - zoomPointB) < epsilon;
879 }
880 
GetCrossZoomAndTime(std::vector<float> & crossZoomAndTime,std::vector<float> & crossZoom,std::vector<std::vector<float>> & crossTime)881 void HCaptureSession::GetCrossZoomAndTime(
882     std::vector<float>& crossZoomAndTime, std::vector<float>& crossZoom, std::vector<std::vector<float>>& crossTime)
883 {
884     int dataLenPerPoint = 3;
885     for (int i = 0; i < static_cast<int>(crossZoomAndTime.size()); i = i + dataLenPerPoint) {
886         if (crossZoomAndTime[i] != 0) {
887             crossZoom.push_back(crossZoomAndTime[i]);
888         }
889         crossTime[i / dataLenPerPoint][ZOOM_IN_PER] = crossZoomAndTime[i + ZOOM_IN_PER + 1];
890         crossTime[i / dataLenPerPoint][ZOOM_OUT_PERF] = crossZoomAndTime[i + ZOOM_OUT_PERF + 1];
891     }
892 }
893 
GetCrossWaitTime(std::vector<std::vector<float>> & crossTime,int32_t targetRangeId,int32_t currentRangeId)894 float HCaptureSession::GetCrossWaitTime(
895     std::vector<std::vector<float>>& crossTime, int32_t targetRangeId, int32_t currentRangeId)
896 {
897     float waitTime = 0.0; // 100 199 370 获取maxWaitTime
898     switch (currentRangeId) {
899         case WIDE_CAMERA_ZOOM_RANGE:
900             if (targetRangeId == TELE_CAMERA_ZOOM_RANGE) {
901                 waitTime = crossTime[WIDE_TELE_ZOOM_PER][ZOOM_IN_PER];
902             } else {
903                 waitTime = crossTime[WIDE_MAIN_ZOOM_PER][ZOOM_IN_PER];
904             }
905             break;
906         case MAIN_CAMERA_ZOOM_RANGE:
907             if (targetRangeId == TELE_CAMERA_ZOOM_RANGE) {
908                 waitTime = crossTime[TELE_MAIN_ZOOM_PER][ZOOM_IN_PER];
909             } else if (targetRangeId == WIDE_CAMERA_ZOOM_RANGE) {
910                 waitTime = crossTime[WIDE_MAIN_ZOOM_PER][ZOOM_OUT_PERF];
911             }
912             break;
913         case TWO_X_EXIT_TELE_ZOOM_RANGE:
914             if (targetRangeId == TELE_CAMERA_ZOOM_RANGE) {
915                 waitTime = crossTime[TELE_2X_ZOOM_PER][ZOOM_IN_PER];
916             } else if (targetRangeId == WIDE_CAMERA_ZOOM_RANGE) {
917                 waitTime = crossTime[WIDE_MAIN_ZOOM_PER][ZOOM_OUT_PERF];
918             } else {
919                 MEDIA_DEBUG_LOG("HCaptureSession::GetCrossWaitTime pass");
920             }
921             break;
922         case TELE_CAMERA_ZOOM_RANGE:
923             if (targetRangeId == WIDE_CAMERA_ZOOM_RANGE) {
924                 waitTime = crossTime[WIDE_TELE_ZOOM_PER][ZOOM_OUT_PERF];
925             } else if (targetRangeId == TWO_X_EXIT_TELE_ZOOM_RANGE) {
926                 waitTime = crossTime[TELE_2X_ZOOM_PER][ZOOM_OUT_PERF];
927             } else {
928                 waitTime = crossTime[TELE_MAIN_ZOOM_PER][ZOOM_OUT_PERF];
929             }
930             break;
931     }
932     MEDIA_DEBUG_LOG("HCaptureSession::GetCrossWaitTime waitTime %{public}f, "
933                     "targetRangeId %{public}d,"
934                     " currentRangeId %{public}d, sessionID: %{public}d",
935         waitTime,
936         targetRangeId,
937         currentRangeId,
938         GetSessionId());
939     return waitTime;
940 }
941 
QueryZoomBezierValue(std::vector<float> & zoomBezierValue)942 bool HCaptureSession::QueryZoomBezierValue(std::vector<float> &zoomBezierValue)
943 {
944     auto cameraDevice = GetCameraDevice();
945     CHECK_ERROR_RETURN_RET_LOG(
946         cameraDevice == nullptr, false, "HCaptureSession::QueryZoomBezierValue() cameraDevice is null");
947     std::shared_ptr<OHOS::Camera::CameraMetadata> ability = cameraDevice->GetDeviceAbility();
948     camera_metadata_item_t bezierItem;
949     int retFindMeta =
950         OHOS::Camera::FindCameraMetadataItem(ability->get(), OHOS_ABILITY_CAMERA_ZOOM_BEZIER_CURVC_POINT, &bezierItem);
951     if (retFindMeta == CAM_META_ITEM_NOT_FOUND) {
952         MEDIA_ERR_LOG("HCaptureSession::QueryZoomBezierValue() current bezierValue not found");
953         return false;
954     }
955     for (int i = 0; i < static_cast<int>(bezierItem.count); i++) {
956         zoomBezierValue.push_back(bezierItem.data.f[i]);
957         MEDIA_DEBUG_LOG("HCaptureSession::QueryZoomBezierValue()  bezierValue %{public}f.",
958             static_cast<float>(bezierItem.data.f[i]));
959     }
960     return true;
961 }
962 
SetSmoothZoom(int32_t smoothZoomType,int32_t operationMode,float targetZoomRatio,float & duration)963 int32_t HCaptureSession::SetSmoothZoom(
964     int32_t smoothZoomType, int32_t operationMode, float targetZoomRatio, float& duration)
965 {
966     constexpr int32_t ZOOM_RATIO_MULTIPLE = 100;
967     const int32_t MAX_FPS = 60;
968     auto cameraDevice = GetCameraDevice();
969     CHECK_ERROR_RETURN_RET_LOG(cameraDevice == nullptr, CAMERA_UNKNOWN_ERROR,
970         "HCaptureSession::SetSmoothZoom device is null, sessionID: %{public}d", GetSessionId());
971     float currentFps = 30.0f;
972     float currentZoomRatio = 1.0f;
973     int32_t targetRangeId = 0;
974     int32_t currentRangeId = 0;
975     std::vector<float> crossZoomAndTime {};
976     std::vector<float> zoomBezierValue {};
977     QueryFpsAndZoomRatio(currentFps, currentZoomRatio, crossZoomAndTime, operationMode);
978     currentFps = currentFps > MAX_FPS ? MAX_FPS : currentFps;
979     std::vector<float> mCrossZoom {};
980     int32_t waitCount = 4;
981     int32_t zoomInOutCount = 2;
982     std::vector<std::vector<float>> crossTime(waitCount, std::vector<float>(zoomInOutCount, 0.0f)); // 生成4x2二维数组
983     GetCrossZoomAndTime(crossZoomAndTime, mCrossZoom, crossTime);
984     float waitTime = 0.0;
985     float frameIntervalMs = 1000.0 / currentFps;
986     targetZoomRatio = targetZoomRatio * ZOOM_RATIO_MULTIPLE;
987     targetRangeId = GetRangeId(targetZoomRatio, mCrossZoom);
988     currentRangeId = GetRangeId(currentZoomRatio, mCrossZoom);
989     float waitMs = GetCrossWaitTime(crossTime, targetRangeId, currentRangeId);
990     bool retHaveBezierValue = QueryZoomBezierValue(zoomBezierValue);
991     auto zoomAlgorithm = SmoothZoom::GetZoomAlgorithm(static_cast<SmoothZoomType>(smoothZoomType));
992     if (retHaveBezierValue && zoomBezierValue.size() == ZOOM_BEZIER_VALUE_COUNT) {
993         zoomAlgorithm->SetBezierValue(zoomBezierValue);
994     }
995     auto array = zoomAlgorithm->GetZoomArray(currentZoomRatio, targetZoomRatio, frameIntervalMs);
996     CHECK_ERROR_RETURN_RET_LOG(array.empty(), CAMERA_UNKNOWN_ERROR, "HCaptureSession::SetSmoothZoom array is empty");
997     if (currentZoomRatio < targetZoomRatio) {
998         std::sort(mCrossZoom.begin(), mCrossZoom.end());
999     } else {
1000         std::sort(mCrossZoom.begin(), mCrossZoom.end(), std::greater<float>());
1001     }
1002     for (int i = 0; i < static_cast<int>(mCrossZoom.size()); i++) {
1003         float crossZoom = mCrossZoom[i];
1004         MEDIA_DEBUG_LOG("HCaptureSession::SetSmoothZoom crossZoomIterator is:  %{public}f", crossZoom);
1005         if ((crossZoom - currentZoomRatio) * (crossZoom - targetZoomRatio) > 0 || isEqual(crossZoom, 199.0f)) {
1006             MEDIA_DEBUG_LOG("HCaptureSession::SetSmoothZoom skip zoomCross is:  %{public}f", crossZoom);
1007             continue;
1008         }
1009         if (std::fabs(currentZoomRatio - crossZoom) <= std::numeric_limits<float>::epsilon() &&
1010             currentZoomRatio > targetZoomRatio) {
1011             waitTime = waitMs;
1012         }
1013         for (int j = 0; j < static_cast<int>(array.size()); j++) {
1014             if (static_cast<int>(array[j] - crossZoom) * static_cast<int>(array[0] - crossZoom) <= 0) {
1015                 waitTime = waitMs - frameIntervalMs * j;
1016                 waitTime = waitTime >= 0 ? waitTime : 0;
1017                 MEDIA_DEBUG_LOG("HCaptureSession::SetSmoothZoom crossZoom is: %{public}f, waitTime is: %{public}f",
1018                     crossZoom, waitTime);
1019                 break;
1020             }
1021         }
1022     }
1023     std::vector<uint32_t> zoomAndTimeArray {};
1024     for (int i = 0; i < static_cast<int>(array.size()); i++) {
1025         zoomAndTimeArray.push_back(static_cast<uint32_t>(array[i]));
1026         zoomAndTimeArray.push_back(static_cast<uint32_t>(i * frameIntervalMs + waitTime));
1027         MEDIA_DEBUG_LOG("HCaptureSession::SetSmoothZoom() zoom %{public}d, waitMs %{public}d.",
1028             static_cast<uint32_t>(array[i]), static_cast<uint32_t>(i * frameIntervalMs + waitTime));
1029     }
1030     duration = (static_cast<int>(array.size()) - 1) * frameIntervalMs + waitTime;
1031     MEDIA_DEBUG_LOG("HCaptureSession::SetSmoothZoom() duration %{public}f, "
1032                     "sessionID: %{public}d", duration, GetSessionId());
1033     ProcessMetaZoomArray(zoomAndTimeArray, cameraDevice);
1034     return CAMERA_OK;
1035 }
1036 
ProcessMetaZoomArray(std::vector<uint32_t> & zoomAndTimeArray,sptr<HCameraDevice> & cameraDevice)1037 void HCaptureSession::ProcessMetaZoomArray(std::vector<uint32_t>& zoomAndTimeArray, sptr<HCameraDevice>& cameraDevice)
1038 {
1039     std::shared_ptr<OHOS::Camera::CameraMetadata> metaZoomArray = std::make_shared<OHOS::Camera::CameraMetadata>(1, 1);
1040     uint32_t zoomCount = static_cast<uint32_t>(zoomAndTimeArray.size());
1041     MEDIA_INFO_LOG("HCaptureSession::ProcessMetaZoomArray() zoomArray size: "
1042                    "%{public}zu, zoomCount: %{public}u, sessionID: %{public}d",
1043         zoomAndTimeArray.size(),
1044         zoomCount,
1045         GetSessionId());
1046     metaZoomArray->addEntry(OHOS_CONTROL_SMOOTH_ZOOM_RATIOS, zoomAndTimeArray.data(), zoomCount);
1047     cameraDevice->UpdateSettingOnce(metaZoomArray);
1048 }
1049 
EnableMovingPhoto(bool isEnable)1050 int32_t HCaptureSession::EnableMovingPhoto(bool isEnable)
1051 {
1052     auto hStreamOperatorSptr = GetStreamOperator();
1053     CHECK_ERROR_RETURN_RET_LOG(hStreamOperatorSptr == nullptr, CAMERA_OK, "hStreamOperatorSptr is null");
1054     std::shared_ptr<OHOS::Camera::CameraMetadata> settings = nullptr;
1055     auto cameraDevice = GetCameraDevice();
1056     if (cameraDevice != nullptr) {
1057         settings = cameraDevice->CloneCachedSettings();
1058     }
1059     hStreamOperatorSptr->EnableMovingPhoto(settings, isEnable, GetSensorOritation());
1060     return CAMERA_OK;
1061 }
1062 
Start()1063 int32_t HCaptureSession::Start()
1064 {
1065     CAMERA_SYNC_TRACE;
1066     int32_t errorCode = CAMERA_OK;
1067     MEDIA_INFO_LOG("HCaptureSession::Start prepare execute, sessionID: %{public}d", GetSessionId());
1068     stateMachine_.StateGuard([&errorCode, this](CaptureSessionState currentState) {
1069         bool isTransferSupport = stateMachine_.CheckTransfer(CaptureSessionState::SESSION_STARTED);
1070         if (!isTransferSupport) {
1071             MEDIA_ERR_LOG("HCaptureSession::Start() Need to call after "
1072                           "committing configuration, sessionID: %{public}d", GetSessionId());
1073             errorCode = CAMERA_INVALID_STATE;
1074             return;
1075         }
1076         std::shared_ptr<OHOS::Camera::CameraMetadata> settings = nullptr;
1077         auto cameraDevice = GetCameraDevice();
1078         uint8_t usedAsPositionU8 = OHOS_CAMERA_POSITION_OTHER;
1079         MEDIA_INFO_LOG("HCaptureSession::Start usedAsPositionU8 default = "
1080                        "%{public}d, sessionID: %{public}d", usedAsPositionU8, GetSessionId());
1081         if (cameraDevice != nullptr) {
1082             settings = cameraDevice->CloneCachedSettings();
1083             usedAsPositionU8 = cameraDevice->GetUsedAsPosition();
1084             MEDIA_INFO_LOG("HCaptureSession::Start usedAsPositionU8 set "
1085                            "%{public}d, sessionID: %{public}d", usedAsPositionU8, GetSessionId());
1086             DumpMetadata(settings);
1087             UpdateMuteSetting(cameraDevice->GetDeviceMuteMode(), settings);
1088         }
1089         camera_position_enum_t cameraPosition = static_cast<camera_position_enum_t>(usedAsPositionU8);
1090         auto hStreamOperatorSptr = GetStreamOperator();
1091         CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr, "hStreamOperatorSptr is null");
1092         if (OHOS::Rosen::DisplayManager::GetInstance().GetFoldStatus() == OHOS::Rosen::FoldStatus::FOLDED) {
1093             auto infos = GetCameraRotateStrategyInfos();
1094             auto frameRateRange = hStreamOperatorSptr->GetFrameRateRange();
1095             UpdateCameraRotateAngleAndZoom(infos, frameRateRange);
1096         }
1097         errorCode = hStreamOperatorSptr->StartPreviewStream(settings, cameraPosition);
1098         if (errorCode == CAMERA_OK) {
1099             isSessionStarted_ = true;
1100         }
1101         stateMachine_.Transfer(CaptureSessionState::SESSION_STARTED);
1102     });
1103     MEDIA_INFO_LOG("HCaptureSession::Start execute success, sessionID: %{public}d", GetSessionId());
1104     std::string concurrencyString = "Concurrency cameras:[";
1105     std::list<sptr<HCaptureSession>> sessionList = HCameraSessionManager::GetInstance().GetGroupSessions(pid_);
1106     for (auto entry : sessionList) {
1107         if (entry->isSessionStarted_) {
1108             concurrencyString.append(entry->GetCameraDevice()->GetCameraId() + "    ");
1109         }
1110     }
1111     concurrencyString.append("]");
1112     return errorCode;
1113 }
1114 
UpdateMuteSetting(bool muteMode,std::shared_ptr<OHOS::Camera::CameraMetadata> & settings)1115 void HCaptureSession::UpdateMuteSetting(bool muteMode, std::shared_ptr<OHOS::Camera::CameraMetadata>& settings)
1116 {
1117     int32_t count = 1;
1118     uint8_t mode = muteMode ? OHOS_CAMERA_MUTE_MODE_SOLID_COLOR_BLACK : OHOS_CAMERA_MUTE_MODE_OFF;
1119     settings->addEntry(OHOS_CONTROL_MUTE_MODE, &mode, count);
1120 }
1121 
Stop()1122 int32_t HCaptureSession::Stop()
1123 {
1124     CAMERA_SYNC_TRACE;
1125     int32_t errorCode = CAMERA_OK;
1126     MEDIA_INFO_LOG("HCaptureSession::Stop prepare execute, sessionID: %{public}d", GetSessionId());
1127     stateMachine_.StateGuard([&errorCode, this](CaptureSessionState currentState) {
1128         bool isTransferSupport = stateMachine_.CheckTransfer(CaptureSessionState::SESSION_CONFIG_COMMITTED);
1129         if (!isTransferSupport) {
1130             MEDIA_ERR_LOG("HCaptureSession::Stop() Need to call after Start, "
1131                           "sessionID: %{public}d", GetSessionId());
1132             errorCode = CAMERA_INVALID_STATE;
1133             return;
1134         }
1135         auto hStreamOperatorSptr = GetStreamOperator();
1136         if (hStreamOperatorSptr == nullptr) {
1137             MEDIA_ERR_LOG("hStreamOperatorSptr is null");
1138             errorCode = CAMERA_INVALID_STATE;
1139             return;
1140         }
1141         errorCode = hStreamOperatorSptr->Stop();
1142         if (errorCode == CAMERA_OK) {
1143             isSessionStarted_ = false;
1144         }
1145         stateMachine_.Transfer(CaptureSessionState::SESSION_CONFIG_COMMITTED);
1146     });
1147     MEDIA_INFO_LOG("HCaptureSession::Stop execute success, sessionID: %{public}d", GetSessionId());
1148     return errorCode;
1149 }
1150 
Release(CaptureSessionReleaseType type)1151 int32_t HCaptureSession::Release(CaptureSessionReleaseType type)
1152 {
1153     CAMERA_SYNC_TRACE;
1154     int32_t errorCode = CAMERA_OK;
1155     int32_t sid = GetSessionId();
1156     MEDIA_INFO_LOG("HCaptureSession::Release prepare execute, release type "
1157                    "is:%{public}d pid(%{public}d), sessionID: %{public}d", type, pid_, GetSessionId());
1158     // Check release without lock first
1159     CHECK_ERROR_RETURN_RET_LOG(stateMachine_.IsStateNoLock(CaptureSessionState::SESSION_RELEASED),
1160         CAMERA_INVALID_STATE,
1161         "HCaptureSession::Release error, session is already released!");
1162 
1163     stateMachine_.StateGuard([&errorCode, this, type](CaptureSessionState currentState) {
1164         MEDIA_INFO_LOG("HCaptureSession::Release pid(%{public}d). release type is:%{public}d", pid_, type);
1165         bool isTransferSupport = stateMachine_.CheckTransfer(CaptureSessionState::SESSION_RELEASED);
1166         if (!isTransferSupport) {
1167             MEDIA_ERR_LOG("HCaptureSession::Release error, this session is already released!");
1168             errorCode = CAMERA_INVALID_STATE;
1169             return;
1170         }
1171         // Clear current session
1172         if (type != CaptureSessionReleaseType::RELEASE_TYPE_OBJ_DIED) {
1173             HCameraSessionManager::GetInstance().RemoveSession(this);
1174             MEDIA_DEBUG_LOG("HCaptureSession::Release clear pid left sessions(%{public}zu).",
1175                 HCameraSessionManager::GetInstance().GetTotalSessionSize());
1176         }
1177         auto hStreamOperatorSptr = GetStreamOperator();
1178         CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr, "hStreamOperatorSptr is null");
1179         // stop movingPhoto
1180         hStreamOperatorSptr->StopMovingPhoto();
1181 
1182         // Clear outputs
1183         hStreamOperatorSptr->ReleaseStreams();
1184 
1185         // Clear inputs
1186         auto cameraDevice = GetCameraDevice();
1187         if (cameraDevice != nullptr) {
1188             cameraDevice->Release();
1189             SetCameraDevice(nullptr);
1190         }
1191 
1192         if ((hStreamOperatorSptr->GetAllOutptSize()) == 0) {
1193             hStreamOperatorSptr->Release();
1194         }
1195         sptr<ICaptureSessionCallback> emptyCallback = nullptr;
1196         SetCallback(emptyCallback);
1197         stateMachine_.Transfer(CaptureSessionState::SESSION_RELEASED);
1198         isSessionStarted_ = false;
1199     });
1200     MEDIA_INFO_LOG("HCaptureSession::Release execute success, sessionID: %{public}d", sid);
1201     return errorCode;
1202 }
1203 
Release()1204 int32_t HCaptureSession::Release()
1205 {
1206     MEDIA_INFO_LOG("HCaptureSession::Release(), sessionID: %{public}d", GetSessionId());
1207     CameraReportUtils::GetInstance().SetModeChangePerfStartInfo(opMode_, CameraReportUtils::GetCallerInfo());
1208     return Release(CaptureSessionReleaseType::RELEASE_TYPE_CLIENT);
1209 }
1210 
OperatePermissionCheck(uint32_t interfaceCode)1211 int32_t HCaptureSession::OperatePermissionCheck(uint32_t interfaceCode)
1212 {
1213     CHECK_ERROR_RETURN_RET_LOG(stateMachine_.GetCurrentState() == CaptureSessionState::SESSION_RELEASED,
1214         CAMERA_INVALID_STATE,
1215         "HCaptureSession::OperatePermissionCheck session is released");
1216     switch (static_cast<CaptureSessionInterfaceCode>(interfaceCode)) {
1217         case CAMERA_CAPTURE_SESSION_START: {
1218             auto callerToken = IPCSkeleton::GetCallingTokenID();
1219             CHECK_ERROR_RETURN_RET_LOG(callerToken_ != callerToken, CAMERA_OPERATION_NOT_ALLOWED,
1220                 "HCaptureSession::OperatePermissionCheck fail, callerToken_ is : %{public}d, now token "
1221                 "is %{public}d", callerToken_, callerToken);
1222             break;
1223         }
1224         default:
1225             break;
1226     }
1227     return CAMERA_OK;
1228 }
1229 
DestroyStubObjectForPid(pid_t pid)1230 void HCaptureSession::DestroyStubObjectForPid(pid_t pid)
1231 {
1232     auto& sessionManager = HCameraSessionManager::GetInstance();
1233     MEDIA_DEBUG_LOG("camera stub session groups(%{public}zu) pid(%{public}d).", sessionManager.GetGroupCount(), pid);
1234     auto sessions = sessionManager.GetGroupSessions(pid);
1235     for (auto& session : sessions) {
1236         session->Release(CaptureSessionReleaseType::RELEASE_TYPE_CLIENT_DIED);
1237     }
1238     sessionManager.RemoveGroup(pid);
1239     MEDIA_DEBUG_LOG("camera stub session groups(%{public}zu).", sessionManager.GetGroupCount());
1240 }
1241 
SetCallback(sptr<ICaptureSessionCallback> & callback)1242 int32_t HCaptureSession::SetCallback(sptr<ICaptureSessionCallback>& callback)
1243 {
1244     if (callback == nullptr) {
1245         MEDIA_WARNING_LOG("HCaptureSession::SetCallback callback is null, we "
1246                           "should clear the callback, sessionID: %{public}d",
1247             GetSessionId());
1248     }
1249     // Not implement yet.
1250     return CAMERA_OK;
1251 }
1252 
UnSetCallback()1253 int32_t HCaptureSession::UnSetCallback()
1254 {
1255     // Not implement yet.
1256     return CAMERA_OK;
1257 }
1258 
GetSessionState()1259 std::string HCaptureSession::GetSessionState()
1260 {
1261     auto currentState = stateMachine_.GetCurrentState();
1262     std::map<CaptureSessionState, std::string>::const_iterator iter = SESSION_STATE_STRING_MAP.find(currentState);
1263     CHECK_ERROR_RETURN_RET(iter != SESSION_STATE_STRING_MAP.end(), iter->second);
1264     return std::to_string(static_cast<uint32_t>(currentState));
1265 }
1266 
DumpCameraSessionSummary(CameraInfoDumper & infoDumper)1267 void HCaptureSession::DumpCameraSessionSummary(CameraInfoDumper& infoDumper)
1268 {
1269     infoDumper.Msg("Number of Camera sessions:[" +
1270                    std::to_string(HCameraSessionManager::GetInstance().GetTotalSessionSize()) + "]");
1271 }
1272 
DumpSessions(CameraInfoDumper & infoDumper)1273 void HCaptureSession::DumpSessions(CameraInfoDumper& infoDumper)
1274 {
1275     auto totalSession = HCameraSessionManager::GetInstance().GetTotalSession();
1276     uint32_t index = 0;
1277     for (auto& session : totalSession) {
1278         infoDumper.Title("Camera Sessions[" + std::to_string(index++) + "] Info:");
1279         session->DumpSessionInfo(infoDumper);
1280     }
1281 }
1282 
DumpSessionInfo(CameraInfoDumper & infoDumper)1283 void HCaptureSession::DumpSessionInfo(CameraInfoDumper& infoDumper)
1284 {
1285     infoDumper.Msg("Client pid:[" + std::to_string(pid_) + "]    Client uid:[" + std::to_string(uid_) + "]");
1286     infoDumper.Msg("session state:[" + GetSessionState() + "]");
1287     auto hStreamOperatorSptr = GetStreamOperator();
1288     CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr, "hStreamOperatorSptr is null");
1289     for (auto& stream : hStreamOperatorSptr->GetAllStreams()) {
1290         infoDumper.Push();
1291         stream->DumpStreamInfo(infoDumper);
1292         infoDumper.Pop();
1293     }
1294 }
1295 
EnableMovingPhotoMirror(bool isMirror,bool isConfig)1296 int32_t HCaptureSession::EnableMovingPhotoMirror(bool isMirror, bool isConfig)
1297 {
1298     auto hStreamOperatorSptr = GetStreamOperator();
1299     CHECK_ERROR_RETURN_RET_LOG(hStreamOperatorSptr == nullptr, CAMERA_OK, "hStreamOperatorSptr is null");
1300     hStreamOperatorSptr->EnableMovingPhotoMirror(isMirror, isConfig);
1301     return CAMERA_OK;
1302 }
1303 
GetOutputStatus(int32_t & status)1304 void HCaptureSession::GetOutputStatus(int32_t& status)
1305 {
1306     auto hStreamOperatorSptr = GetStreamOperator();
1307     CHECK_ERROR_RETURN_LOG(hStreamOperatorSptr == nullptr, "hStreamOperatorSptr is null");
1308     hStreamOperatorSptr->GetOutputStatus(status);
1309 }
1310 
SetCameraDevice(sptr<HCameraDevice> device)1311 void HCaptureSession::SetCameraDevice(sptr<HCameraDevice> device)
1312 {
1313     std::lock_guard<std::mutex> lock(cameraDeviceLock_);
1314     if (cameraDevice_ != nullptr) {
1315         cameraDevice_->SetCameraCloseListener(nullptr);
1316     }
1317     if (device != nullptr) {
1318         device->SetCameraCloseListener(this);
1319     }
1320     cameraDevice_ = device;
1321 
1322     auto hStreamOperatorSptr = GetStreamOperator();
1323     if (hStreamOperatorSptr != nullptr) {
1324         hStreamOperatorSptr->SetCameraDevice(device);
1325     }
1326 }
1327 
CreateDisplayName()1328 std::string HCaptureSession::CreateDisplayName()
1329 {
1330     struct tm currentTime;
1331     std::string formattedTime = "";
1332     if (GetSystemCurrentTime(&currentTime)) {
1333         std::stringstream ss;
1334         ss << prefix << std::setw(yearWidth) << std::setfill(placeholder) << currentTime.tm_year + startYear
1335            << std::setw(otherWidth) << std::setfill(placeholder) << (currentTime.tm_mon + 1) << std::setw(otherWidth)
1336            << std::setfill(placeholder) << currentTime.tm_mday << connector << std::setw(otherWidth)
1337            << std::setfill(placeholder) << currentTime.tm_hour << std::setw(otherWidth) << std::setfill(placeholder)
1338            << currentTime.tm_min << std::setw(otherWidth) << std::setfill(placeholder) << currentTime.tm_sec;
1339         formattedTime = ss.str();
1340     } else {
1341         MEDIA_ERR_LOG("Failed to get current time.sessionID: %{public}d", GetSessionId());
1342     }
1343     if (lastDisplayName_ == formattedTime) {
1344         saveIndex++;
1345         formattedTime = formattedTime + connector + std::to_string(saveIndex);
1346         MEDIA_INFO_LOG(
1347             "CreateDisplayName is %{private}s, sessionID: %{public}d", formattedTime.c_str(), GetSessionId());
1348         return formattedTime;
1349     }
1350     lastDisplayName_ = formattedTime;
1351     saveIndex = 0;
1352     MEDIA_INFO_LOG("CreateDisplayName is %{private}s", formattedTime.c_str());
1353     return formattedTime;
1354 }
1355 
CreateBurstDisplayName(int32_t imageSeqId,int32_t seqId)1356 std::string HCaptureSession::CreateBurstDisplayName(int32_t imageSeqId, int32_t seqId)
1357 {
1358     struct tm currentTime;
1359     std::string formattedTime = "";
1360     std::stringstream ss;
1361     // a group of burst capture use the same prefix
1362     if (imageSeqId == 1) {
1363         CHECK_ERROR_RETURN_RET_LOG(!GetSystemCurrentTime(&currentTime), formattedTime, "Failed to get current time.");
1364         ss << prefix << std::setw(yearWidth) << std::setfill(placeholder) << currentTime.tm_year + startYear
1365            << std::setw(otherWidth) << std::setfill(placeholder) << (currentTime.tm_mon + 1) << std::setw(otherWidth)
1366            << std::setfill(placeholder) << currentTime.tm_mday << connector << std::setw(otherWidth)
1367            << std::setfill(placeholder) << currentTime.tm_hour << std::setw(otherWidth) << std::setfill(placeholder)
1368            << currentTime.tm_min << std::setw(otherWidth) << std::setfill(placeholder) << currentTime.tm_sec
1369            << connector << burstTag;
1370         lastBurstPrefix_ = ss.str();
1371         ss << std::setw(burstWidth) << std::setfill(placeholder) << seqId;
1372     } else {
1373         ss << lastBurstPrefix_ << std::setw(burstWidth) << std::setfill(placeholder) << seqId;
1374     }
1375     MEDIA_DEBUG_LOG("burst prefix is %{private}s, sessionID: %{public}d", lastBurstPrefix_.c_str(), GetSessionId());
1376 
1377     if (seqId == 1) {
1378         ss << coverTag;
1379     }
1380     formattedTime = ss.str();
1381     MEDIA_INFO_LOG(
1382         "CreateBurstDisplayName is %{private}s, sessionID: %{public}d", formattedTime.c_str(), GetSessionId());
1383     return formattedTime;
1384 }
1385 
SetFeatureMode(int32_t featureMode)1386 int32_t HCaptureSession::SetFeatureMode(int32_t featureMode)
1387 {
1388     MEDIA_INFO_LOG("SetFeatureMode is called!sessionID: %{public}d", GetSessionId());
1389     featureMode_ = featureMode;
1390     return CAMERA_OK;
1391 }
1392 
StateMachine()1393 StateMachine::StateMachine()
1394 {
1395     stateTransferMap_[static_cast<uint32_t>(CaptureSessionState::SESSION_INIT)] = {
1396         CaptureSessionState::SESSION_CONFIG_INPROGRESS, CaptureSessionState::SESSION_RELEASED
1397     };
1398 
1399     stateTransferMap_[static_cast<uint32_t>(CaptureSessionState::SESSION_CONFIG_INPROGRESS)] = {
1400         CaptureSessionState::SESSION_CONFIG_COMMITTED, CaptureSessionState::SESSION_RELEASED
1401     };
1402 
1403     stateTransferMap_[static_cast<uint32_t>(CaptureSessionState::SESSION_CONFIG_COMMITTED)] = {
1404         CaptureSessionState::SESSION_CONFIG_INPROGRESS, CaptureSessionState::SESSION_STARTED,
1405         CaptureSessionState::SESSION_RELEASED
1406     };
1407 
1408     stateTransferMap_[static_cast<uint32_t>(CaptureSessionState::SESSION_STARTED)] = {
1409         CaptureSessionState::SESSION_CONFIG_INPROGRESS, CaptureSessionState::SESSION_CONFIG_COMMITTED,
1410         CaptureSessionState::SESSION_RELEASED
1411     };
1412 
1413     stateTransferMap_[static_cast<uint32_t>(CaptureSessionState::SESSION_RELEASED)] = {};
1414 }
1415 
CheckTransfer(CaptureSessionState targetState)1416 bool StateMachine::CheckTransfer(CaptureSessionState targetState)
1417 {
1418     std::lock_guard<std::recursive_mutex> lock(sessionStateLock_);
1419     return any_of(stateTransferMap_[static_cast<uint32_t>(currentState_)].begin(),
1420         stateTransferMap_[static_cast<uint32_t>(currentState_)].end(),
1421         [&targetState](const auto& state) { return state == targetState; });
1422 }
1423 
Transfer(CaptureSessionState targetState)1424 bool StateMachine::Transfer(CaptureSessionState targetState)
1425 {
1426     std::lock_guard<std::recursive_mutex> lock(sessionStateLock_);
1427     if (CheckTransfer(targetState)) {
1428         currentState_ = targetState;
1429         return true;
1430     }
1431     return false;
1432 }
1433 
UpdateCameraRotateAngleAndZoom(std::vector<CameraRotateStrategyInfo> & infos,std::vector<int32_t> & frameRateRange)1434 void HCaptureSession::UpdateCameraRotateAngleAndZoom(std::vector<CameraRotateStrategyInfo> &infos,
1435     std::vector<int32_t> &frameRateRange)
1436 {
1437     int index = -1;
1438     int uid = IPCSkeleton::GetCallingUid();
1439     std::string bundleName = GetClientBundle(uid);
1440     for (size_t i = 0; i < infos.size(); i++) {
1441         if (infos[i].bundleName == bundleName) {
1442             index = i;
1443             break;
1444         }
1445     }
1446     CHECK_ERROR_RETURN_LOG(index == -1, "Update roteta angle not supported");
1447     auto flag = false;
1448     CHECK_EXECUTE(infos[index].fps <= 0, flag = true);
1449     CHECK_EXECUTE(infos[index].fps > 0 && frameRateRange.size() > 1 &&
1450         infos[index].fps == frameRateRange[1], flag = true);
1451     CHECK_ERROR_RETURN(!flag);
1452     std::shared_ptr<OHOS::Camera::CameraMetadata> settings = std::make_shared<OHOS::Camera::CameraMetadata>(1, 1);
1453     int16_t rotateDegree = infos[index].rotateDegree;
1454     MEDIA_DEBUG_LOG("HCaptureSession::UpdateCameraRotateAngleAndZoom rotateDegree: %{public}d.", rotateDegree);
1455     CHECK_EXECUTE(rotateDegree >= 0, settings->addEntry(OHOS_CONTROL_ROTATE_ANGLE, &rotateDegree, 1));
1456     float zoom = infos[index].wideValue;
1457     MEDIA_DEBUG_LOG("HCaptureSession::UpdateCameraRotateAngleAndZoom zoom: %{public}f.", zoom);
1458     CHECK_EXECUTE(zoom >= 0, settings->addEntry(OHOS_CONTROL_ZOOM_RATIO, &zoom, 1));
1459     auto cameraDevive = GetCameraDevice();
1460     CHECK_ERROR_RETURN_LOG(cameraDevive == nullptr, "cameraDevive is null.");
1461     cameraDevive->UpdateSettingOnce(settings);
1462     MEDIA_INFO_LOG("UpdateCameraRotateAngleAndZoom success.");
1463 }
1464 
SetCameraRotateStrategyInfos(std::vector<CameraRotateStrategyInfo> infos)1465 void HCaptureSession::SetCameraRotateStrategyInfos(std::vector<CameraRotateStrategyInfo> infos)
1466 {
1467     std::lock_guard<std::mutex> lock(cameraRotateStrategyInfosLock_);
1468     cameraRotateStrategyInfos_ = infos;
1469 }
1470 
GetCameraRotateStrategyInfos()1471 std::vector<CameraRotateStrategyInfo> HCaptureSession::GetCameraRotateStrategyInfos()
1472 {
1473     std::lock_guard<std::mutex> lock(cameraRotateStrategyInfosLock_);
1474     return cameraRotateStrategyInfos_;
1475 }
1476 }  // namespace CameraStandard
1477 }  // namespace OHOS