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 <mutex>
26 #include <new>
27 #include <sched.h>
28 #include <string>
29 #include <sync_fence.h>
30 #include <utility>
31 #include <vector>
32 
33 #include "avcodec_task_manager.h"
34 #include "blocking_queue.h"
35 #include "bundle_mgr_interface.h"
36 #include "camera_dynamic_loader.h"
37 #include "camera_info_dumper.h"
38 #include "camera_log.h"
39 #include "camera_report_uitls.h"
40 #include "camera_server_photo_proxy.h"
41 #include "camera_service_ipc_interface_code.h"
42 #include "camera_util.h"
43 #include "datetime_ex.h"
44 #include "display/composer/v1_1/display_composer_type.h"
45 #include "display_manager.h"
46 #include "errors.h"
47 #include "hcamera_device_manager.h"
48 #include "hcamera_restore_param.h"
49 #include "hstream_capture.h"
50 #include "hstream_common.h"
51 #include "hstream_depth_data.h"
52 #include "hstream_metadata.h"
53 #include "hstream_repeat.h"
54 #include "icamera_util.h"
55 #include "icapture_session.h"
56 #include "iconsumer_surface.h"
57 #include "image_type.h"
58 #include "ipc_skeleton.h"
59 #include "iservice_registry.h"
60 #include "istream_common.h"
61 #include "media_library/photo_asset_interface.h"
62 #include "metadata_utils.h"
63 #include "moving_photo/moving_photo_surface_wrapper.h"
64 #include "moving_photo_video_cache.h"
65 #include "refbase.h"
66 #include "smooth_zoom.h"
67 #include "surface.h"
68 #include "surface_buffer.h"
69 #include "system_ability_definition.h"
70 #include "v1_0/types.h"
71 #include "deferred_processing_service.h"
72 #include "picture.h"
73 #include "camera_timer.h"
74 #include "fixed_size_list.h"
75 #include "camera_report_dfx_uitls.h"
76 
77 using namespace OHOS::AAFwk;
78 namespace OHOS {
79 namespace CameraStandard {
80 using namespace OHOS::HDI::Display::Composer::V1_1;
81 std::optional<uint32_t> HCaptureSession::closeTimerId_ = std::nullopt;
82 std::mutex HCaptureSession::g_mediaTaskLock_;
83 
84 namespace {
85 static std::map<pid_t, sptr<HCaptureSession>> g_totalSessions;
86 static std::mutex g_totalSessionLock;
87 #ifdef CAMERA_USE_SENSOR
88 constexpr int32_t POSTURE_INTERVAL = 100000000; //100ms
89 constexpr int VALID_INCLINATION_ANGLE_THRESHOLD_COEFFICIENT = 3;
90 #endif
91 static GravityData gravityData = {0.0, 0.0, 0.0};
92 static int32_t sensorRotation = 0;
93 const char *CAMERA_BUNDLE_NAME = "com.huawei.hmos.camera";
TotalSessionSize()94 static size_t TotalSessionSize()
95 {
96     std::lock_guard<std::mutex> lock(g_totalSessionLock);
97     return g_totalSessions.size();
98 }
99 
TotalSessionsCopy()100 static const std::map<pid_t, sptr<HCaptureSession>> TotalSessionsCopy()
101 {
102     std::lock_guard<std::mutex> lock(g_totalSessionLock);
103     return g_totalSessions;
104 }
105 
TotalSessionsInsert(pid_t pid,sptr<HCaptureSession> session)106 static void TotalSessionsInsert(pid_t pid, sptr<HCaptureSession> session)
107 {
108     std::lock_guard<std::mutex> lock(g_totalSessionLock);
109     auto it = g_totalSessions.find(pid);
110     if (it != g_totalSessions.end()) {
111         MEDIA_ERR_LOG("HCaptureSession TotalSessionsInsert insert session but pid already exist!, memory leak may "
112                       "occurred, pid is:%{public}d",
113             pid);
114         it->second = session;
115         return;
116     }
117     g_totalSessions.emplace(pid, session);
118 }
119 
TotalSessionsGet(pid_t pid)120 static sptr<HCaptureSession> TotalSessionsGet(pid_t pid)
121 {
122     std::lock_guard<std::mutex> lock(g_totalSessionLock);
123     auto it = g_totalSessions.find(pid);
124     CHECK_AND_RETURN_RET(it == g_totalSessions.end(), it->second);
125     return nullptr;
126 }
127 
TotalSessionErase(pid_t pid)128 static void TotalSessionErase(pid_t pid)
129 {
130     std::lock_guard<std::mutex> lock(g_totalSessionLock);
131     g_totalSessions.erase(pid);
132 }
133 
IsExistSessionsNeedMediaLib()134 static bool IsExistSessionsNeedMediaLib()
135 {
136     std::lock_guard<std::mutex> lock(g_totalSessionLock);
137     return std::any_of(g_totalSessions.begin(), g_totalSessions.end(), [](const auto& pair) {
138         return pair.second && pair.second->isNeedMediaLib;
139     });
140 }
141 } // namespace
142 
143 static const std::map<CaptureSessionState, std::string> SESSION_STATE_STRING_MAP = {
144     {CaptureSessionState::SESSION_INIT, "Init"},
145     {CaptureSessionState::SESSION_CONFIG_INPROGRESS, "Config_In-progress"},
146     {CaptureSessionState::SESSION_CONFIG_COMMITTED, "Committed"},
147     {CaptureSessionState::SESSION_RELEASED, "Released"},
148     {CaptureSessionState::SESSION_STARTED, "Started"}
149 };
150 
NewInstance(const uint32_t callerToken,int32_t opMode)151 sptr<HCaptureSession> HCaptureSession::NewInstance(const uint32_t callerToken, int32_t opMode)
152 {
153     sptr<HCaptureSession> session = new HCaptureSession();
154     CHECK_AND_RETURN_RET(session->Initialize(callerToken, opMode) != CAMERA_OK, session);
155     return nullptr;
156 }
157 
Initialize(const uint32_t callerToken,int32_t opMode)158 int32_t HCaptureSession::Initialize(const uint32_t callerToken, int32_t opMode)
159 {
160     pid_ = IPCSkeleton::GetCallingPid();
161     uid_ = static_cast<uint32_t>(IPCSkeleton::GetCallingUid());
162     MEDIA_DEBUG_LOG("HCaptureSession: camera stub services(%{public}zu) pid(%{public}d).", TotalSessionSize(), pid_);
163     auto pidSession = TotalSessionsGet(pid_);
164     if (pidSession != nullptr) {
165         auto disconnectDevice = pidSession->GetCameraDevice();
166         if (disconnectDevice != nullptr) {
167             disconnectDevice->OnError(HDI::Camera::V1_0::DEVICE_PREEMPT, 0);
168         }
169         MEDIA_ERR_LOG("HCaptureSession::HCaptureSession doesn't support multiple sessions per pid");
170         pidSession->Release();
171     }
172     TotalSessionsInsert(pid_, this);
173     callerToken_ = callerToken;
174     opMode_ = opMode;
175     featureMode_ = 0;
176     CameraReportUtils::GetInstance().updateModeChangePerfInfo(opMode, CameraReportUtils::GetCallerInfo());
177     MEDIA_INFO_LOG(
178         "HCaptureSession: camera stub services(%{public}zu). opMode_= %{public}d", TotalSessionSize(), opMode_);
179     return CAMERA_OK;
180 }
181 
HCaptureSession()182 HCaptureSession::HCaptureSession()
183 {
184     pid_ = 0;
185     uid_ = 0;
186     callerToken_ = 0;
187     opMode_ = 0;
188     featureMode_ = 0;
189 }
190 
HCaptureSession(const uint32_t callingTokenId,int32_t opMode)191 HCaptureSession::HCaptureSession(const uint32_t callingTokenId, int32_t opMode)
192 {
193     Initialize(callingTokenId, opMode);
194 }
195 
~HCaptureSession()196 HCaptureSession::~HCaptureSession()
197 {
198     CAMERA_SYNC_TRACE;
199     Release(CaptureSessionReleaseType::RELEASE_TYPE_OBJ_DIED);
200     if (displayListener_) {
201         OHOS::Rosen::DisplayManager::GetInstance().UnregisterDisplayListener(displayListener_);
202         displayListener_ = nullptr;
203     }
204 }
205 
GetPid()206 pid_t HCaptureSession::GetPid()
207 {
208     return pid_;
209 }
210 
GetopMode()211 int32_t HCaptureSession::GetopMode()
212 {
213     CHECK_AND_RETURN_RET(!featureMode_, featureMode_);
214     return opMode_;
215 }
216 
GetCurrentStreamInfos(std::vector<StreamInfo_V1_1> & streamInfos)217 int32_t HCaptureSession::GetCurrentStreamInfos(std::vector<StreamInfo_V1_1>& streamInfos)
218 {
219     auto streams = streamContainer_.GetAllStreams();
220     for (auto& stream : streams) {
221         if (stream) {
222             StreamInfo_V1_1 curStreamInfo;
223             stream->SetStreamInfo(curStreamInfo);
224             if (stream->GetStreamType() != StreamType::METADATA) {
225                 streamInfos.push_back(curStreamInfo);
226             }
227         }
228     }
229     return CAMERA_OK;
230 }
231 
DynamicConfigStream()232 void HCaptureSession::DynamicConfigStream()
233 {
234     isDynamicConfiged_ = false;
235     MEDIA_INFO_LOG("HCaptureSession::DynamicConfigStream enter. currentState = %{public}s",
236         GetSessionState().c_str());
237     auto currentState = stateMachine_.GetCurrentState();
238     if (currentState == CaptureSessionState::SESSION_STARTED) {
239         std::string bundleName = GetClientBundle(IPCSkeleton::GetCallingUid());
240         isDynamicConfiged_ = (bundleName == CAMERA_BUNDLE_NAME);
241         MEDIA_INFO_LOG("HCaptureSession::DynamicConfigStream support dynamic stream config");
242     }
243 }
244 
IsNeedDynamicConfig()245 bool HCaptureSession::IsNeedDynamicConfig()
246 {
247     return isDynamicConfiged_;
248 }
249 
BeginConfig()250 int32_t HCaptureSession::BeginConfig()
251 {
252     CAMERA_SYNC_TRACE;
253     int32_t errCode;
254     MEDIA_INFO_LOG("HCaptureSession::BeginConfig prepare execute");
255     stateMachine_.StateGuard([&errCode, this](const CaptureSessionState state) {
256         DynamicConfigStream();
257         bool isStateValid = stateMachine_.Transfer(CaptureSessionState::SESSION_CONFIG_INPROGRESS);
258         if (!isStateValid) {
259             MEDIA_ERR_LOG("HCaptureSession::BeginConfig in invalid state %{public}d", state);
260             errCode = CAMERA_INVALID_STATE;
261             isDynamicConfiged_ = false;
262             return;
263         }
264         if (!IsNeedDynamicConfig()) {
265             UnlinkInputAndOutputs();
266             ClearSketchRepeatStream();
267             ClearMovingPhotoRepeatStream();
268         }
269     });
270     if (errCode == CAMERA_OK) {
271         MEDIA_INFO_LOG("HCaptureSession::BeginConfig execute success");
272     } else {
273         CameraReportUtils::ReportCameraError(
274             "HCaptureSession::BeginConfig", errCode, false, CameraReportUtils::GetCallerInfo());
275     }
276     return errCode;
277 }
278 
CanAddInput(sptr<ICameraDeviceService> cameraDevice,bool & result)279 int32_t HCaptureSession::CanAddInput(sptr<ICameraDeviceService> cameraDevice, bool& result)
280 {
281     CAMERA_SYNC_TRACE;
282     int32_t errorCode = CAMERA_OK;
283     result = false;
284     stateMachine_.StateGuard([this, &errorCode](const CaptureSessionState currentState) {
285         if (currentState != CaptureSessionState::SESSION_CONFIG_INPROGRESS) {
286             MEDIA_ERR_LOG("HCaptureSession::CanAddInput Need to call BeginConfig before adding input");
287             errorCode = CAMERA_INVALID_STATE;
288             return;
289         }
290         if ((GetCameraDevice() != nullptr)) {
291             MEDIA_ERR_LOG("HCaptureSession::CanAddInput Only one input is supported");
292             errorCode = CAMERA_INVALID_SESSION_CFG;
293             return;
294         }
295     });
296     if (errorCode == CAMERA_OK) {
297         result = true;
298         CAMERA_SYSEVENT_STATISTIC(CreateMsg("CaptureSession::CanAddInput"));
299     }
300     return errorCode;
301 }
302 
AddInput(sptr<ICameraDeviceService> cameraDevice)303 int32_t HCaptureSession::AddInput(sptr<ICameraDeviceService> cameraDevice)
304 {
305     CAMERA_SYNC_TRACE;
306     int32_t errorCode = CAMERA_OK;
307     if (cameraDevice == nullptr) {
308         errorCode = CAMERA_INVALID_ARG;
309         MEDIA_ERR_LOG("HCaptureSession::AddInput cameraDevice is null");
310         CameraReportUtils::ReportCameraError(
311             "HCaptureSession::AddInput", errorCode, false, CameraReportUtils::GetCallerInfo());
312         return errorCode;
313     }
314     MEDIA_INFO_LOG("HCaptureSession::AddInput prepare execute");
315     stateMachine_.StateGuard([this, &errorCode, &cameraDevice](const CaptureSessionState currentState) {
316         if (currentState != CaptureSessionState::SESSION_CONFIG_INPROGRESS) {
317             MEDIA_ERR_LOG("HCaptureSession::AddInput Need to call BeginConfig before adding input");
318             errorCode = CAMERA_INVALID_STATE;
319             return;
320         }
321         if ((GetCameraDevice() != nullptr)) {
322             MEDIA_ERR_LOG("HCaptureSession::AddInput Only one input is supported");
323             errorCode = CAMERA_INVALID_SESSION_CFG;
324             return;
325         }
326         sptr<HCameraDevice> hCameraDevice = static_cast<HCameraDevice*>(cameraDevice.GetRefPtr());
327         MEDIA_INFO_LOG("HCaptureSession::AddInput device:%{public}s", hCameraDevice->GetCameraId().c_str());
328         hCameraDevice->SetStreamOperatorCallback(this);
329         SetCameraDevice(hCameraDevice);
330         hCameraDevice->DispatchDefaultSettingToHdi();
331     });
332     if (errorCode == CAMERA_OK) {
333         CAMERA_SYSEVENT_STATISTIC(CreateMsg("CaptureSession::AddInput"));
334     } else {
335         CameraReportUtils::ReportCameraError(
336             "HCaptureSession::AddInput", errorCode, false, CameraReportUtils::GetCallerInfo());
337     }
338     MEDIA_INFO_LOG("HCaptureSession::AddInput execute success");
339     return errorCode;
340 }
341 
AddOutputStream(sptr<HStreamCommon> stream)342 int32_t HCaptureSession::AddOutputStream(sptr<HStreamCommon> stream)
343 {
344     CAMERA_SYNC_TRACE;
345     CHECK_ERROR_RETURN_RET_LOG(stream == nullptr, CAMERA_INVALID_ARG,
346         "HCaptureSession::AddOutputStream stream is null");
347     MEDIA_INFO_LOG("HCaptureSession::AddOutputStream streamId:%{public}d streamType:%{public}d",
348         stream->GetFwkStreamId(), stream->GetStreamType());
349     CHECK_ERROR_RETURN_RET_LOG(
350         stream->GetFwkStreamId() == STREAM_ID_UNSET && stream->GetStreamType() != StreamType::METADATA,
351         CAMERA_INVALID_ARG, "HCaptureSession::AddOutputStream stream is released!");
352     bool isAddSuccess = streamContainer_.AddStream(stream);
353     CHECK_ERROR_RETURN_RET_LOG(!isAddSuccess, CAMERA_INVALID_SESSION_CFG,
354         "HCaptureSession::AddOutputStream add stream fail");
355     if (stream->GetStreamType() == StreamType::CAPTURE) {
356         auto captureStream = CastStream<HStreamCapture>(stream);
357         captureStream->SetMode(opMode_);
358         captureStream->SetColorSpace(currCaptureColorSpace_);
359         isNeedMediaLib = true;
360         HCaptureSession::OpenMediaLib();
361     } else {
362         stream->SetColorSpace(currColorSpace_);
363     }
364     return CAMERA_OK;
365 }
366 
OpenMediaLib()367 void HCaptureSession::OpenMediaLib()
368 {
369     std::lock_guard<std::mutex> lock(g_mediaTaskLock_);
370     if (closeTimerId_.has_value()) {
371         MEDIA_INFO_LOG("cancel closeDynamicHandle task id: %{public}d", closeTimerId_.value());
372         CameraTimer::GetInstance().Unregister(closeTimerId_.value());
373         closeTimerId_.reset();
374     }
375     CameraTimer::GetInstance().Register(
376         [&] { CameraDynamicLoader::GetInstance()->OpenDynamicHandle(MEDIA_LIB_SO); }, 0, true);
377 }
378 
StartMovingPhotoStream()379 void HCaptureSession::StartMovingPhotoStream()
380 {
381     int32_t errorCode = 0;
382     stateMachine_.StateGuard([&errorCode, this](CaptureSessionState currentState) {
383         if (currentState != CaptureSessionState::SESSION_STARTED) {
384             MEDIA_ERR_LOG("EnableMovingPhoto, invalid session state: %{public}d, start after preview", currentState);
385             errorCode = CAMERA_INVALID_STATE;
386             return;
387         }
388         auto repeatStreams = streamContainer_.GetStreams(StreamType::REPEAT);
389         bool isPreviewStarted = false;
390         for (auto& item : repeatStreams) {
391             auto curStreamRepeat = CastStream<HStreamRepeat>(item);
392             auto repeatType = curStreamRepeat->GetRepeatStreamType();
393             if (repeatType != RepeatStreamType::PREVIEW) {
394                 continue;
395             }
396             if (curStreamRepeat->GetPreparedCaptureId() != CAPTURE_ID_UNSET && curStreamRepeat->producer_ != nullptr) {
397                 isPreviewStarted = true;
398                 break;
399             }
400         }
401         CHECK_ERROR_RETURN_LOG(!isPreviewStarted, "EnableMovingPhoto, preview is not streaming");
402         std::shared_ptr<OHOS::Camera::CameraMetadata> settings = nullptr;
403         auto cameraDevice = GetCameraDevice();
404         if (cameraDevice != nullptr) {
405             settings = cameraDevice->CloneCachedSettings();
406             DumpMetadata(settings);
407         }
408         for (auto& item : repeatStreams) {
409             auto curStreamRepeat = CastStream<HStreamRepeat>(item);
410             auto repeatType = curStreamRepeat->GetRepeatStreamType();
411             if (repeatType != RepeatStreamType::LIVEPHOTO) {
412                 continue;
413             }
414             if (isSetMotionPhoto_) {
415                 errorCode = curStreamRepeat->Start(settings);
416                 #ifdef MOVING_PHOTO_ADD_AUDIO
417                 std::lock_guard<std::mutex> lock(movingPhotoStatusLock_);
418                 audioCapturerSession_ != nullptr && audioCapturerSession_->StartAudioCapture();
419                 #endif
420             } else {
421                 errorCode = curStreamRepeat->Stop();
422                 StopMovingPhoto();
423             }
424             break;
425         }
426     });
427     MEDIA_INFO_LOG("HCaptureSession::StartMovingPhotoStream result:%{public}d", errorCode);
428 }
429 
430 class DisplayRotationListener : public OHOS::Rosen::DisplayManager::IDisplayListener {
431 public:
DisplayRotationListener()432     explicit DisplayRotationListener() {};
433     virtual ~DisplayRotationListener() = default;
OnCreate(OHOS::Rosen::DisplayId)434     void OnCreate(OHOS::Rosen::DisplayId) override {}
OnDestroy(OHOS::Rosen::DisplayId)435     void OnDestroy(OHOS::Rosen::DisplayId) override {}
OnChange(OHOS::Rosen::DisplayId displayId)436     void OnChange(OHOS::Rosen::DisplayId displayId) override
437     {
438         sptr<Rosen::Display> display = Rosen::DisplayManager::GetInstance().GetDefaultDisplay();
439         if (display == nullptr) {
440             MEDIA_INFO_LOG("Get display info failed, display:%{public}" PRIu64"", displayId);
441             display = Rosen::DisplayManager::GetInstance().GetDisplayById(0);
442             CHECK_ERROR_RETURN_LOG(display == nullptr, "Get display info failed, display is nullptr");
443         }
444         {
445             Rosen::Rotation currentRotation = display->GetRotation();
446             std::lock_guard<std::mutex> lock(mStreamManagerLock_);
447             for (auto& repeatStream : repeatStreamList_) {
448                 if (repeatStream) {
449                     repeatStream->SetStreamTransform(static_cast<int>(currentRotation));
450                 }
451             }
452         }
453     }
454 
AddHstreamRepeatForListener(sptr<HStreamRepeat> repeatStream)455     void AddHstreamRepeatForListener(sptr<HStreamRepeat> repeatStream)
456     {
457         std::lock_guard<std::mutex> lock(mStreamManagerLock_);
458         if (repeatStream) {
459             repeatStreamList_.push_back(repeatStream);
460         }
461     }
462 
RemoveHstreamRepeatForListener(sptr<HStreamRepeat> repeatStream)463     void RemoveHstreamRepeatForListener(sptr<HStreamRepeat> repeatStream)
464     {
465         std::lock_guard<std::mutex> lock(mStreamManagerLock_);
466         if (repeatStream) {
467             repeatStreamList_.erase(std::remove(repeatStreamList_.begin(), repeatStreamList_.end(), repeatStream),
468                 repeatStreamList_.end());
469         }
470     }
471 
472 public:
473     std::list<sptr<HStreamRepeat>> repeatStreamList_;
474     std::mutex mStreamManagerLock_;
475 };
476 
RegisterDisplayListener(sptr<HStreamRepeat> repeat)477 void HCaptureSession::RegisterDisplayListener(sptr<HStreamRepeat> repeat)
478 {
479     if (displayListener_ == nullptr) {
480         displayListener_ = new DisplayRotationListener();
481         OHOS::Rosen::DisplayManager::GetInstance().RegisterDisplayListener(displayListener_);
482     }
483     displayListener_->AddHstreamRepeatForListener(repeat);
484 }
485 
UnRegisterDisplayListener(sptr<HStreamRepeat> repeatStream)486 void HCaptureSession::UnRegisterDisplayListener(sptr<HStreamRepeat> repeatStream)
487 {
488     if (displayListener_) {
489         displayListener_->RemoveHstreamRepeatForListener(repeatStream);
490     }
491 }
492 
SetPreviewRotation(std::string & deviceClass)493 int32_t HCaptureSession::SetPreviewRotation(std::string &deviceClass)
494 {
495     enableStreamRotate_ = true;
496     deviceClass_ = deviceClass;
497     return CAMERA_OK;
498 }
499 
AddOutput(StreamType streamType,sptr<IStreamCommon> stream)500 int32_t HCaptureSession::AddOutput(StreamType streamType, sptr<IStreamCommon> stream)
501 {
502     int32_t errorCode = CAMERA_INVALID_ARG;
503     if (stream == nullptr) {
504         MEDIA_ERR_LOG("HCaptureSession::AddOutput stream is null");
505         CameraReportUtils::ReportCameraError(
506             "HCaptureSession::AddOutput", errorCode, false, CameraReportUtils::GetCallerInfo());
507         return errorCode;
508     }
509     stateMachine_.StateGuard([this, &errorCode, streamType, &stream](const CaptureSessionState currentState) {
510         if (currentState != CaptureSessionState::SESSION_CONFIG_INPROGRESS) {
511             MEDIA_ERR_LOG("HCaptureSession::AddOutput Need to call BeginConfig before adding output");
512             errorCode = CAMERA_INVALID_STATE;
513             return;
514         }
515         // Temp hack to fix the library linking issue
516         sptr<IConsumerSurface> captureSurface = IConsumerSurface::Create();
517         if (streamType == StreamType::CAPTURE) {
518             errorCode = AddOutputStream(static_cast<HStreamCapture*>(stream.GetRefPtr()));
519         } else if (streamType == StreamType::REPEAT) {
520             HStreamRepeat* repeatSteam = static_cast<HStreamRepeat*>(stream.GetRefPtr());
521             if (enableStreamRotate_ && repeatSteam != nullptr &&
522                 repeatSteam->GetRepeatStreamType() == RepeatStreamType::PREVIEW) {
523                 RegisterDisplayListener(repeatSteam);
524                 repeatSteam->SetPreviewRotation(deviceClass_);
525             }
526             errorCode = AddOutputStream(repeatSteam);
527         } else if (streamType == StreamType::METADATA) {
528             errorCode = AddOutputStream(static_cast<HStreamMetadata*>(stream.GetRefPtr()));
529         } else if (streamType == StreamType::DEPTH) {
530             errorCode = AddOutputStream(static_cast<HStreamDepthData*>(stream.GetRefPtr()));
531         }
532     });
533     if (errorCode == CAMERA_OK) {
534         CAMERA_SYSEVENT_STATISTIC(CreateMsg("CaptureSession::AddOutput with %d", streamType));
535     } else {
536         CameraReportUtils::ReportCameraError(
537             "HCaptureSession::AddOutput", errorCode, false, CameraReportUtils::GetCallerInfo());
538     }
539     MEDIA_INFO_LOG("CaptureSession::AddOutput with with %{public}d, rc = %{public}d", streamType, errorCode);
540     return errorCode;
541 }
542 
RemoveInput(sptr<ICameraDeviceService> cameraDevice)543 int32_t HCaptureSession::RemoveInput(sptr<ICameraDeviceService> cameraDevice)
544 {
545     int32_t errorCode = CAMERA_OK;
546     if (cameraDevice == nullptr) {
547         errorCode = CAMERA_INVALID_ARG;
548         MEDIA_ERR_LOG("HCaptureSession::RemoveInput cameraDevice is null");
549         CameraReportUtils::ReportCameraError(
550             "HCaptureSession::RemoveInput", errorCode, false, CameraReportUtils::GetCallerInfo());
551         return errorCode;
552     }
553     MEDIA_INFO_LOG("HCaptureSession::RemoveInput prepare execute");
554     stateMachine_.StateGuard([this, &errorCode, &cameraDevice](const CaptureSessionState currentState) {
555         if (currentState != CaptureSessionState::SESSION_CONFIG_INPROGRESS) {
556             MEDIA_ERR_LOG("HCaptureSession::RemoveInput Need to call BeginConfig before removing input");
557             errorCode = CAMERA_INVALID_STATE;
558             return;
559         }
560         if (IsNeedDynamicConfig()) {
561             UnlinkInputAndOutputs();
562             ClearSketchRepeatStream();
563             ClearMovingPhotoRepeatStream();
564         }
565         auto currentDevice = GetCameraDevice();
566         if (currentDevice != nullptr && cameraDevice->AsObject() == currentDevice->AsObject()) {
567             // Do not close device while remove input!
568             MEDIA_INFO_LOG(
569                 "HCaptureSession::RemoveInput camera id is %{public}s", currentDevice->GetCameraId().c_str());
570             currentDevice->ResetDeviceSettings();
571             SetCameraDevice(nullptr);
572         } else {
573             MEDIA_ERR_LOG("HCaptureSession::RemoveInput Invalid camera device");
574             errorCode = CAMERA_INVALID_SESSION_CFG;
575         }
576     });
577     if (errorCode == CAMERA_OK) {
578         CAMERA_SYSEVENT_STATISTIC(CreateMsg("CaptureSession::RemoveInput"));
579     } else {
580         CameraReportUtils::ReportCameraError(
581             "HCaptureSession::RemoveInput", errorCode, false, CameraReportUtils::GetCallerInfo());
582     }
583     MEDIA_INFO_LOG("HCaptureSession::RemoveInput execute success");
584     return errorCode;
585 }
586 
RemoveOutputStream(sptr<HStreamCommon> stream)587 int32_t HCaptureSession::RemoveOutputStream(sptr<HStreamCommon> stream)
588 {
589     CAMERA_SYNC_TRACE;
590     CHECK_ERROR_RETURN_RET_LOG(stream == nullptr, CAMERA_INVALID_ARG,
591         "HCaptureSession::RemoveOutputStream stream is null");
592     MEDIA_INFO_LOG("HCaptureSession::RemoveOutputStream,streamType:%{public}d, streamId:%{public}d",
593         stream->GetStreamType(), stream->GetFwkStreamId());
594     bool isRemoveSuccess = streamContainer_.RemoveStream(stream);
595     CHECK_ERROR_RETURN_RET_LOG(!isRemoveSuccess, CAMERA_INVALID_SESSION_CFG,
596         "HCaptureSession::RemoveOutputStream Invalid output");
597     return CAMERA_OK;
598 }
599 
DelayCloseMediaLib()600 void HCaptureSession::DelayCloseMediaLib()
601 {
602     std::lock_guard<std::mutex> lock(g_mediaTaskLock_);
603     constexpr uint32_t waitMs = 60 * 1000;
604     if (closeTimerId_.has_value()) {
605         CameraTimer::GetInstance().Unregister(closeTimerId_.value());
606         MEDIA_INFO_LOG("delete closeDynamicHandle task id: %{public}d", closeTimerId_.value());
607     }
608     closeTimerId_ = CameraTimer::GetInstance().Register([]() {
609         CHECK_ERROR_RETURN_LOG(IsExistSessionsNeedMediaLib(), "exist session need media lib, directly return");
610         CameraDynamicLoader::GetInstance()->CloseDynamicHandle(MEDIA_LIB_SO);
611     }, waitMs, true);
612     MEDIA_INFO_LOG("create closeDynamicHandle task id: %{public}d", closeTimerId_.value());
613 }
614 
RemoveOutput(StreamType streamType,sptr<IStreamCommon> stream)615 int32_t HCaptureSession::RemoveOutput(StreamType streamType, sptr<IStreamCommon> stream)
616 {
617     int32_t errorCode = CAMERA_INVALID_ARG;
618     if (stream == nullptr) {
619         MEDIA_ERR_LOG("HCaptureSession::RemoveOutput stream is null");
620         CameraReportUtils::ReportCameraError(
621             "HCaptureSession::RemoveOutput", errorCode, false, CameraReportUtils::GetCallerInfo());
622         return errorCode;
623     }
624     MEDIA_INFO_LOG("HCaptureSession::RemoveOutput prepare execute");
625     stateMachine_.StateGuard([this, &errorCode, streamType, &stream](const CaptureSessionState currentState) {
626         if (currentState != CaptureSessionState::SESSION_CONFIG_INPROGRESS) {
627             MEDIA_ERR_LOG("HCaptureSession::RemoveOutput Need to call BeginConfig before removing output");
628             errorCode = CAMERA_INVALID_STATE;
629             return;
630         }
631         if (streamType == StreamType::CAPTURE) {
632             errorCode = RemoveOutputStream(static_cast<HStreamCapture*>(stream.GetRefPtr()));
633             isNeedMediaLib = false;
634             HCaptureSession::DelayCloseMediaLib();
635         } else if (streamType == StreamType::REPEAT) {
636             HStreamRepeat* repeatSteam = static_cast<HStreamRepeat*>(stream.GetRefPtr());
637             if (enableStreamRotate_ && repeatSteam != nullptr &&
638                 repeatSteam->GetRepeatStreamType() == RepeatStreamType::PREVIEW) {
639                 UnRegisterDisplayListener(repeatSteam);
640             }
641             errorCode = RemoveOutputStream(repeatSteam);
642         } else if (streamType == StreamType::METADATA) {
643             errorCode = RemoveOutputStream(static_cast<HStreamMetadata*>(stream.GetRefPtr()));
644         }
645     });
646     if (errorCode == CAMERA_OK) {
647         CAMERA_SYSEVENT_STATISTIC(CreateMsg("CaptureSession::RemoveOutput with %d", streamType));
648     } else {
649         CameraReportUtils::ReportCameraError(
650             "HCaptureSession::RemoveOutput", errorCode, false, CameraReportUtils::GetCallerInfo());
651     }
652     MEDIA_INFO_LOG("HCaptureSession::RemoveOutput execute success");
653     return errorCode;
654 }
655 
ValidateSessionInputs()656 int32_t HCaptureSession::ValidateSessionInputs()
657 {
658     CHECK_ERROR_RETURN_RET_LOG(GetCameraDevice() == nullptr, CAMERA_INVALID_SESSION_CFG,
659         "HCaptureSession::ValidateSessionInputs No inputs present");
660     return CAMERA_OK;
661 }
662 
ValidateSessionOutputs()663 int32_t HCaptureSession::ValidateSessionOutputs()
664 {
665     CHECK_ERROR_RETURN_RET_LOG(streamContainer_.Size() == 0, CAMERA_INVALID_SESSION_CFG,
666         "HCaptureSession::ValidateSessionOutputs No outputs present");
667     return CAMERA_OK;
668 }
669 
LinkInputAndOutputs()670 int32_t HCaptureSession::LinkInputAndOutputs()
671 {
672     int32_t rc;
673     std::vector<StreamInfo_V1_1> allStreamInfos;
674     sptr<OHOS::HDI::Camera::V1_0::IStreamOperator> streamOperator;
675     auto device = GetCameraDevice();
676     MEDIA_INFO_LOG("HCaptureSession::LinkInputAndOutputs prepare execute");
677     CHECK_ERROR_RETURN_RET_LOG(device == nullptr, CAMERA_INVALID_SESSION_CFG,
678         "HCaptureSession::LinkInputAndOutputs device is null");
679     auto settings = device->GetDeviceAbility();
680     CHECK_ERROR_RETURN_RET_LOG(settings == nullptr, CAMERA_UNKNOWN_ERROR,
681         "HCaptureSession::LinkInputAndOutputs deviceAbility is null");
682     streamOperator = device->GetStreamOperator();
683     auto allStream = streamContainer_.GetAllStreams();
684     MEDIA_INFO_LOG("HCaptureSession::LinkInputAndOutputs allStream size:%{public}zu", allStream.size());
685     CHECK_ERROR_RETURN_RET_LOG(!IsValidMode(opMode_, settings), CAMERA_INVALID_SESSION_CFG,
686         "HCaptureSession::LinkInputAndOutputs IsValidMode false");
687     for (auto& stream : allStream) {
688         rc = stream->LinkInput(streamOperator, settings);
689         if (rc == CAMERA_OK) {
690             if (stream->GetHdiStreamId() == STREAM_ID_UNSET) {
691                 stream->SetHdiStreamId(device->GenerateHdiStreamId());
692             }
693         }
694         MEDIA_INFO_LOG(
695             "HCaptureSession::LinkInputAndOutputs streamType:%{public}d, streamId:%{public}d ,hdiStreamId:%{public}d",
696             stream->GetStreamType(), stream->GetFwkStreamId(), stream->GetHdiStreamId());
697         CHECK_ERROR_RETURN_RET_LOG(rc != CAMERA_OK, rc, "HCaptureSession::LinkInputAndOutputs IsValidMode false");
698         StreamInfo_V1_1 curStreamInfo;
699         stream->SetStreamInfo(curStreamInfo);
700         if (stream->GetStreamType() != StreamType::METADATA) {
701             allStreamInfos.push_back(curStreamInfo);
702         }
703     }
704 
705     rc = device->CreateAndCommitStreams(allStreamInfos, settings, GetopMode());
706     MEDIA_INFO_LOG("HCaptureSession::LinkInputAndOutputs execute success");
707     return rc;
708 }
709 
UnlinkInputAndOutputs()710 int32_t HCaptureSession::UnlinkInputAndOutputs()
711 {
712     CAMERA_SYNC_TRACE;
713     int32_t rc = CAMERA_UNKNOWN_ERROR;
714     std::vector<int32_t> fwkStreamIds;
715     std::vector<int32_t> hdiStreamIds;
716     auto allStream = streamContainer_.GetAllStreams();
717     for (auto& stream : allStream) {
718         fwkStreamIds.emplace_back(stream->GetFwkStreamId());
719         hdiStreamIds.emplace_back(stream->GetHdiStreamId());
720         stream->UnlinkInput();
721     }
722     MEDIA_INFO_LOG("HCaptureSession::UnlinkInputAndOutputs() streamIds size() = %{public}zu, streamIds:%{public}s, "
723                    "hdiStreamIds:%{public}s",
724         fwkStreamIds.size(), Container2String(fwkStreamIds.begin(), fwkStreamIds.end()).c_str(),
725         Container2String(hdiStreamIds.begin(), hdiStreamIds.end()).c_str());
726 
727     // HDI release streams, do not clear streamContainer_
728     auto cameraDevice = GetCameraDevice();
729     if ((cameraDevice != nullptr)) {
730         cameraDevice->ReleaseStreams(hdiStreamIds);
731         std::vector<StreamInfo_V1_1> emptyStreams;
732         cameraDevice->UpdateStreams(emptyStreams);
733         cameraDevice->ResetHdiStreamId();
734     }
735     return rc;
736 }
737 
ExpandSketchRepeatStream()738 void HCaptureSession::ExpandSketchRepeatStream()
739 {
740     MEDIA_DEBUG_LOG("Enter HCaptureSession::ExpandSketchRepeatStream()");
741     std::set<sptr<HStreamCommon>> sketchStreams;
742     auto repeatStreams = streamContainer_.GetStreams(StreamType::REPEAT);
743     for (auto& stream : repeatStreams) {
744         if (stream == nullptr) {
745             continue;
746         }
747         auto streamRepeat = CastStream<HStreamRepeat>(stream);
748         if (streamRepeat->GetRepeatStreamType() == RepeatStreamType::SKETCH) {
749             continue;
750         }
751         sptr<HStreamRepeat> sketchStream = streamRepeat->GetSketchStream();
752         if (sketchStream == nullptr) {
753             continue;
754         }
755         sketchStreams.insert(sketchStream);
756     }
757     MEDIA_DEBUG_LOG("HCaptureSession::ExpandSketchRepeatStream() sketch size is:%{public}zu", sketchStreams.size());
758     for (auto& stream : sketchStreams) {
759         AddOutputStream(stream);
760     }
761     MEDIA_DEBUG_LOG("Exit HCaptureSession::ExpandSketchRepeatStream()");
762 }
763 
ExpandMovingPhotoRepeatStream()764 void HCaptureSession::ExpandMovingPhotoRepeatStream()
765 {
766     CAMERA_SYNC_TRACE;
767     MEDIA_ERR_LOG("ExpandMovingPhotoRepeatStream");
768     if (!GetCameraDevice()->CheckMovingPhotoSupported(GetopMode())) {
769         MEDIA_DEBUG_LOG("movingPhoto is not supported");
770         return;
771     }
772     auto captureStreams = streamContainer_.GetStreams(StreamType::CAPTURE);
773     MEDIA_INFO_LOG("HCameraService::ExpandMovingPhotoRepeatStream capture stream size = %{public}zu",
774         captureStreams.size());
775     VideoCodecType videoCodecType = VIDEO_ENCODE_TYPE_AVC;
776     for (auto &stream : captureStreams) {
777         int32_t type = static_cast<HStreamCapture*>(stream.GetRefPtr())->GetMovingPhotoVideoCodecType();
778         videoCodecType = static_cast<VideoCodecType>(type);
779         break;
780     }
781     MEDIA_INFO_LOG("HCameraService::ExpandMovingPhotoRepeatStream videoCodecType = %{public}d", videoCodecType);
782     auto repeatStreams = streamContainer_.GetStreams(StreamType::REPEAT);
783     for (auto& stream : repeatStreams) {
784         if (stream == nullptr) {
785             continue;
786         }
787         auto streamRepeat = CastStream<HStreamRepeat>(stream);
788         if (streamRepeat->GetRepeatStreamType() == RepeatStreamType::PREVIEW) {
789             std::lock_guard<std::mutex> lock(movingPhotoStatusLock_);
790             auto movingPhotoSurfaceWrapper =
791                 MovingPhotoSurfaceWrapper::CreateMovingPhotoSurfaceWrapper(streamRepeat->width_, streamRepeat->height_);
792             if (movingPhotoSurfaceWrapper == nullptr) {
793                 MEDIA_ERR_LOG("HCaptureSession::ExpandMovingPhotoRepeatStream CreateMovingPhotoSurfaceWrapper fail.");
794                 continue;
795             }
796             auto producer = movingPhotoSurfaceWrapper->GetProducer();
797             metaSurface_ = Surface::CreateSurfaceAsConsumer("movingPhotoMeta");
798             auto metaCache = make_shared<FixedSizeList<pair<int64_t, sptr<SurfaceBuffer>>>>(3);
799             CHECK_AND_CONTINUE_LOG(producer != nullptr, "get producer fail.");
800             livephotoListener_ = new (std::nothrow) MovingPhotoListener(movingPhotoSurfaceWrapper,
801                 metaSurface_, metaCache, preCacheFrameCount_, postCacheFrameCount_);
802             CHECK_AND_CONTINUE_LOG(livephotoListener_ != nullptr, "failed to new livephotoListener_!");
803             movingPhotoSurfaceWrapper->SetSurfaceBufferListener(livephotoListener_);
804             livephotoMetaListener_ = new(std::nothrow) MovingPhotoMetaListener(metaSurface_, metaCache);
805             CHECK_AND_CONTINUE_LOG(livephotoMetaListener_ != nullptr, "failed to new livephotoMetaListener_!");
806             metaSurface_->RegisterConsumerListener((sptr<IBufferConsumerListener> &)livephotoMetaListener_);
807             CreateMovingPhotoStreamRepeat(streamRepeat->format_, streamRepeat->width_, streamRepeat->height_, producer);
808             std::lock_guard<std::mutex> streamLock(livePhotoStreamLock_);
809             AddOutputStream(livePhotoStreamRepeat_);
810             if (!audioCapturerSession_) {
811                 audioCapturerSession_ = new AudioCapturerSession();
812             }
813             if (!taskManager_ && audioCapturerSession_) {
814                 taskManager_ = new AvcodecTaskManager(audioCapturerSession_, videoCodecType);
815                 taskManager_->SetVideoBufferDuration(preCacheFrameCount_, postCacheFrameCount_);
816             }
817             if (!videoCache_ && taskManager_) {
818                 videoCache_ = new MovingPhotoVideoCache(taskManager_);
819             }
820             break;
821         }
822     }
823     MEDIA_DEBUG_LOG("Exit HCaptureSession::ExpandMovingPhotoRepeatStream()");
824 }
825 
CreateMovingPhotoStreamRepeat(int32_t format,int32_t width,int32_t height,sptr<OHOS::IBufferProducer> producer)826 int32_t HCaptureSession::CreateMovingPhotoStreamRepeat(
827     int32_t format, int32_t width, int32_t height, sptr<OHOS::IBufferProducer> producer)
828 {
829     CAMERA_SYNC_TRACE;
830     std::lock_guard<std::mutex> lock(livePhotoStreamLock_);
831     CHECK_ERROR_RETURN_RET_LOG(width <= 0 || height <= 0, CAMERA_INVALID_ARG,
832         "HCameraService::CreateLivePhotoStreamRepeat args is illegal");
833     if (livePhotoStreamRepeat_ != nullptr) {
834         livePhotoStreamRepeat_->Release();
835     }
836     auto streamRepeat = new (std::nothrow) HStreamRepeat(producer, format, width, height, RepeatStreamType::LIVEPHOTO);
837     CHECK_AND_RETURN_RET_LOG(streamRepeat != nullptr, CAMERA_ALLOC_ERROR, "HStreamRepeat allocation failed");
838     MEDIA_DEBUG_LOG("para is:%{public}dx%{public}d,%{public}d", width, height, format);
839     livePhotoStreamRepeat_ = streamRepeat;
840     streamRepeat->SetMetaProducer(metaSurface_->GetProducer());
841     streamRepeat->SetMirror(isMovingPhotoMirror_);
842     MEDIA_INFO_LOG("HCameraService::CreateLivePhotoStreamRepeat end");
843     return CAMERA_OK;
844 }
845 
GetStreamByStreamID(int32_t streamId)846 const sptr<HStreamCommon> HCaptureSession::GetStreamByStreamID(int32_t streamId)
847 {
848     auto stream = streamContainer_.GetStream(streamId);
849     CHECK_ERROR_PRINT_LOG(stream == nullptr,
850         "HCaptureSession::GetStreamByStreamID get stream fail, streamId is:%{public}d", streamId);
851     return stream;
852 }
853 
GetHdiStreamByStreamID(int32_t streamId)854 const sptr<HStreamCommon> HCaptureSession::GetHdiStreamByStreamID(int32_t streamId)
855 {
856     auto stream = streamContainer_.GetHdiStream(streamId);
857     CHECK_ERROR_PRINT_LOG(stream == nullptr,
858         "HCaptureSession::GetHdiStreamByStreamID get stream fail, streamId is:%{public}d", streamId);
859     return stream;
860 }
861 
ClearSketchRepeatStream()862 void HCaptureSession::ClearSketchRepeatStream()
863 {
864     MEDIA_DEBUG_LOG("Enter HCaptureSession::ClearSketchRepeatStream()");
865 
866     // Already added session lock in BeginConfig()
867     auto repeatStreams = streamContainer_.GetStreams(StreamType::REPEAT);
868     for (auto& repeatStream : repeatStreams) {
869         if (repeatStream == nullptr) {
870             continue;
871         }
872         auto sketchStream = CastStream<HStreamRepeat>(repeatStream);
873         if (sketchStream->GetRepeatStreamType() != RepeatStreamType::SKETCH) {
874             continue;
875         }
876         MEDIA_DEBUG_LOG(
877             "HCaptureSession::ClearSketchRepeatStream() stream id is:%{public}d", sketchStream->GetFwkStreamId());
878         RemoveOutputStream(repeatStream);
879     }
880     MEDIA_DEBUG_LOG("Exit HCaptureSession::ClearSketchRepeatStream()");
881 }
882 
ClearMovingPhotoRepeatStream()883 void HCaptureSession::ClearMovingPhotoRepeatStream()
884 {
885     CAMERA_SYNC_TRACE;
886     MEDIA_DEBUG_LOG("Enter HCaptureSession::ClearMovingPhotoRepeatStream()");
887     // Already added session lock in BeginConfig()
888     auto repeatStreams = streamContainer_.GetStreams(StreamType::REPEAT);
889     for (auto& repeatStream : repeatStreams) {
890         if (repeatStream == nullptr) {
891             continue;
892         }
893         auto movingPhotoStream = CastStream<HStreamRepeat>(repeatStream);
894         if (movingPhotoStream->GetRepeatStreamType() != RepeatStreamType::LIVEPHOTO) {
895             continue;
896         }
897         StopMovingPhoto();
898         std::lock_guard<std::mutex> lock(movingPhotoStatusLock_);
899         livephotoListener_ = nullptr;
900         videoCache_ = nullptr;
901         MEDIA_DEBUG_LOG("HCaptureSession::ClearLivePhotoRepeatStream() stream id is:%{public}d",
902             movingPhotoStream->GetFwkStreamId());
903         RemoveOutputStream(repeatStream);
904     }
905     MEDIA_DEBUG_LOG("Exit HCaptureSession::ClearLivePhotoRepeatStream()");
906 }
907 
StopMovingPhoto()908 void HCaptureSession::StopMovingPhoto() __attribute__((no_sanitize("cfi")))
909 {
910     CAMERA_SYNC_TRACE;
911     MEDIA_DEBUG_LOG("Enter HCaptureSession::StopMovingPhoto");
912     std::lock_guard<std::mutex> lock(movingPhotoStatusLock_);
913     if (livephotoListener_) {
914         livephotoListener_->StopDrainOut();
915     }
916     if (videoCache_) {
917         videoCache_->ClearCache();
918     }
919     #ifdef MOVING_PHOTO_ADD_AUDIO
920     if (audioCapturerSession_) {
921         audioCapturerSession_->Stop();
922     }
923     #endif
924     if (taskManager_) {
925         taskManager_->Stop();
926     }
927 }
928 
ValidateSession()929 int32_t HCaptureSession::ValidateSession()
930 {
931     int32_t errorCode = CAMERA_OK;
932     errorCode = ValidateSessionInputs();
933     if (errorCode != CAMERA_OK) {
934         return errorCode;
935     }
936     errorCode = ValidateSessionOutputs();
937     return errorCode;
938 }
939 
CommitConfig()940 int32_t HCaptureSession::CommitConfig()
941 {
942     CAMERA_SYNC_TRACE;
943     MEDIA_INFO_LOG("HCaptureSession::CommitConfig begin");
944     int32_t errorCode = CAMERA_OK;
945     stateMachine_.StateGuard([&errorCode, this](CaptureSessionState currentState) {
946         bool isTransferSupport = stateMachine_.CheckTransfer(CaptureSessionState::SESSION_CONFIG_COMMITTED);
947         if (!isTransferSupport) {
948             MEDIA_ERR_LOG("HCaptureSession::CommitConfig() Need to call BeginConfig before committing configuration");
949             errorCode = CAMERA_INVALID_STATE;
950             return;
951         }
952         errorCode = ValidateSession();
953         if (errorCode != CAMERA_OK) {
954             return;
955         }
956         if (!IsNeedDynamicConfig()) {
957             // expand moving photo always
958             ExpandMovingPhotoRepeatStream();
959             ExpandSketchRepeatStream();
960         }
961         auto device = GetCameraDevice();
962         if (device == nullptr) {
963             MEDIA_ERR_LOG("HCaptureSession::CommitConfig() Failed to commit config. camera device is null");
964             errorCode = CAMERA_INVALID_STATE;
965             return;
966         }
967         const int32_t secureMode = 15;
968         uint64_t secureSeqId = 0L;
969         device ->GetSecureCameraSeq(&secureSeqId);
970         if (((GetopMode() == secureMode) ^ (secureSeqId != 0))) {
971             MEDIA_ERR_LOG("secureCamera is not allowed commit mode = %{public}d.", GetopMode());
972             errorCode = CAMERA_OPERATION_NOT_ALLOWED;
973             return;
974         }
975 
976         MEDIA_INFO_LOG("HCaptureSession::CommitConfig secureSeqId = %{public}" PRIu64 "", secureSeqId);
977         errorCode = LinkInputAndOutputs();
978         if (errorCode != CAMERA_OK) {
979             MEDIA_ERR_LOG("HCaptureSession::CommitConfig() Failed to commit config. rc: %{public}d", errorCode);
980             return;
981         }
982         stateMachine_.Transfer(CaptureSessionState::SESSION_CONFIG_COMMITTED);
983     });
984     if (errorCode != CAMERA_OK) {
985         CameraReportUtils::ReportCameraError(
986             "HCaptureSession::CommitConfig", errorCode, false, CameraReportUtils::GetCallerInfo());
987     }
988     MEDIA_INFO_LOG("HCaptureSession::CommitConfig end");
989     return errorCode;
990 }
991 
GetActiveColorSpace(ColorSpace & colorSpace)992 int32_t HCaptureSession::GetActiveColorSpace(ColorSpace& colorSpace)
993 {
994     colorSpace = currColorSpace_;
995     return CAMERA_OK;
996 }
997 
SetColorSpace(ColorSpace colorSpace,ColorSpace captureColorSpace,bool isNeedUpdate)998 int32_t HCaptureSession::SetColorSpace(ColorSpace colorSpace, ColorSpace captureColorSpace, bool isNeedUpdate)
999 {
1000     int32_t result = CAMERA_OK;
1001     CHECK_ERROR_RETURN_RET_LOG(colorSpace == currColorSpace_ && captureColorSpace == currCaptureColorSpace_, result,
1002         "HCaptureSession::SetColorSpace() colorSpace no need to update.");
1003     stateMachine_.StateGuard(
1004         [&result, this, &colorSpace, &captureColorSpace, &isNeedUpdate](CaptureSessionState currentState) {
1005             if (!(currentState == CaptureSessionState::SESSION_CONFIG_INPROGRESS ||
1006                     currentState == CaptureSessionState::SESSION_CONFIG_COMMITTED ||
1007                     currentState == CaptureSessionState::SESSION_STARTED)) {
1008                 MEDIA_ERR_LOG("HCaptureSession::SetColorSpace(), Invalid session state: %{public}d", currentState);
1009                 result = CAMERA_INVALID_STATE;
1010                 return;
1011             }
1012 
1013             currColorSpace_ = colorSpace;
1014             currCaptureColorSpace_ = captureColorSpace;
1015             result = CheckIfColorSpaceMatchesFormat(colorSpace);
1016             if (result != CAMERA_OK) {
1017                 if (isNeedUpdate) {
1018                     MEDIA_ERR_LOG("HCaptureSession::SetColorSpace() Failed, format and colorSpace not match.");
1019                     return;
1020                 } else {
1021                     MEDIA_ERR_LOG(
1022                         "HCaptureSession::SetColorSpace() %{public}d, format and colorSpace: %{public}d not match.",
1023                         result, colorSpace);
1024                     currColorSpace_ = ColorSpace::BT709;
1025                 }
1026             }
1027             MEDIA_INFO_LOG("HCaptureSession::SetColorSpace() colorSpace: %{public}d, captureColorSpace: %{public}d, "
1028                            "isNeedUpdate: %{public}d",
1029                 currColorSpace_, captureColorSpace, isNeedUpdate);
1030             SetColorSpaceForStreams();
1031 
1032             if (isNeedUpdate) {
1033                 result = UpdateStreamInfos();
1034             }
1035         });
1036     return result;
1037 }
1038 
SetColorSpaceForStreams()1039 void HCaptureSession::SetColorSpaceForStreams()
1040 {
1041     auto streams = streamContainer_.GetAllStreams();
1042     for (auto& stream : streams) {
1043         MEDIA_DEBUG_LOG("HCaptureSession::SetColorSpaceForStreams() streams type %{public}d", stream->GetStreamType());
1044         if (stream->GetStreamType() == StreamType::CAPTURE) {
1045             stream->SetColorSpace(currCaptureColorSpace_);
1046         } else {
1047             stream->SetColorSpace(currColorSpace_);
1048         }
1049     }
1050 }
1051 
CancelStreamsAndGetStreamInfos(std::vector<StreamInfo_V1_1> & streamInfos)1052 void HCaptureSession::CancelStreamsAndGetStreamInfos(std::vector<StreamInfo_V1_1>& streamInfos)
1053 {
1054     MEDIA_INFO_LOG("HCaptureSession::CancelStreamsAndGetStreamInfos enter.");
1055     StreamInfo_V1_1 curStreamInfo;
1056     auto streams = streamContainer_.GetAllStreams();
1057     for (auto& stream : streams) {
1058         if (stream && stream->GetStreamType() == StreamType::METADATA) {
1059             continue;
1060         }
1061         if (stream && stream->GetStreamType() == StreamType::CAPTURE && isSessionStarted_) {
1062             static_cast<HStreamCapture*>(stream.GetRefPtr())->CancelCapture();
1063         } else if (stream && stream->GetStreamType() == StreamType::REPEAT && isSessionStarted_) {
1064             static_cast<HStreamRepeat*>(stream.GetRefPtr())->Stop();
1065         }
1066         if (stream) {
1067             stream->SetStreamInfo(curStreamInfo);
1068             streamInfos.push_back(curStreamInfo);
1069         }
1070     }
1071 }
1072 
RestartStreams()1073 void HCaptureSession::RestartStreams()
1074 {
1075     MEDIA_INFO_LOG("HCaptureSession::RestartStreams() enter.");
1076     if (!isSessionStarted_) {
1077         MEDIA_DEBUG_LOG("HCaptureSession::RestartStreams() session is not started yet.");
1078         return;
1079     }
1080     auto cameraDevice = GetCameraDevice();
1081     if (cameraDevice == nullptr) {
1082         return;
1083     }
1084     auto streams = streamContainer_.GetAllStreams();
1085     for (auto& stream : streams) {
1086         if (stream && stream->GetStreamType() == StreamType::REPEAT &&
1087             CastStream<HStreamRepeat>(stream)->GetRepeatStreamType() == RepeatStreamType::PREVIEW) {
1088             std::shared_ptr<OHOS::Camera::CameraMetadata> settings = cameraDevice->CloneCachedSettings();
1089             MEDIA_INFO_LOG("HCaptureSession::RestartStreams() CloneCachedSettings");
1090             DumpMetadata(settings);
1091             CastStream<HStreamRepeat>(stream)->Start(settings);
1092         }
1093     }
1094 }
1095 
UpdateStreamInfos()1096 int32_t HCaptureSession::UpdateStreamInfos()
1097 {
1098     std::vector<StreamInfo_V1_1> streamInfos;
1099     CancelStreamsAndGetStreamInfos(streamInfos);
1100 
1101     auto cameraDevice = GetCameraDevice();
1102     CHECK_ERROR_RETURN_RET_LOG(cameraDevice == nullptr, CAMERA_UNKNOWN_ERROR,
1103         "HCaptureSession::UpdateStreamInfos() cameraDevice is null");
1104     int errorCode = cameraDevice->UpdateStreams(streamInfos);
1105     if (errorCode == CAMERA_OK) {
1106         RestartStreams();
1107     } else {
1108         MEDIA_DEBUG_LOG("HCaptureSession::UpdateStreamInfos err %{public}d", errorCode);
1109     }
1110     return errorCode;
1111 }
1112 
CheckIfColorSpaceMatchesFormat(ColorSpace colorSpace)1113 int32_t HCaptureSession::CheckIfColorSpaceMatchesFormat(ColorSpace colorSpace)
1114 {
1115     if (!(colorSpace == ColorSpace::BT2020_HLG || colorSpace == ColorSpace::BT2020_PQ ||
1116         colorSpace == ColorSpace::BT2020_HLG_LIMIT || colorSpace == ColorSpace::BT2020_PQ_LIMIT)) {
1117         return CAMERA_OK;
1118     }
1119 
1120     // 选择BT2020,需要匹配10bit的format;若不匹配,返回error
1121     auto streams = streamContainer_.GetAllStreams();
1122     for (auto& curStream : streams) {
1123         if (!curStream) {
1124             continue;
1125         }
1126         // 当前拍照流不支持BT2020,无需校验format
1127         if (curStream->GetStreamType() != StreamType::REPEAT) {
1128             continue;
1129         }
1130         StreamInfo_V1_1 curStreamInfo;
1131         curStream->SetStreamInfo(curStreamInfo);
1132         MEDIA_INFO_LOG("HCaptureSession::CheckFormat, stream repeatType: %{public}d, format: %{public}d",
1133             static_cast<HStreamRepeat*>(curStream.GetRefPtr())->GetRepeatStreamType(), curStreamInfo.v1_0.format_);
1134         if (!(curStreamInfo.v1_0.format_ == OHOS::HDI::Display::Composer::V1_1::PIXEL_FMT_YCBCR_P010 ||
1135             curStreamInfo.v1_0.format_ == OHOS::HDI::Display::Composer::V1_1::PIXEL_FMT_YCRCB_P010)) {
1136             MEDIA_ERR_LOG("HCaptureSession::CheckFormat, stream format not match");
1137             return CAMERA_OPERATION_NOT_ALLOWED;
1138         }
1139     }
1140     return CAMERA_OK;
1141 }
1142 
GetSessionState(CaptureSessionState & sessionState)1143 int32_t HCaptureSession::GetSessionState(CaptureSessionState& sessionState)
1144 {
1145     sessionState = stateMachine_.GetCurrentState();
1146     return CAMERA_OK;
1147 }
1148 
QueryFpsAndZoomRatio(float & currentFps,float & currentZoomRatio)1149 bool HCaptureSession::QueryFpsAndZoomRatio(float& currentFps, float& currentZoomRatio)
1150 {
1151     auto cameraDevice = GetCameraDevice();
1152     CHECK_ERROR_RETURN_RET_LOG(cameraDevice == nullptr, false,
1153         "HCaptureSession::QueryFpsAndZoomRatio() cameraDevice is null");
1154     int32_t DEFAULT_ITEMS = 2;
1155     int32_t DEFAULT_DATA_LENGTH = 100;
1156     std::shared_ptr<OHOS::Camera::CameraMetadata> metaIn =
1157         std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
1158     std::shared_ptr<OHOS::Camera::CameraMetadata> metaOut =
1159         std::make_shared<OHOS::Camera::CameraMetadata>(DEFAULT_ITEMS, DEFAULT_DATA_LENGTH);
1160     uint32_t count = 1;
1161     uint32_t fps = 30;
1162     uint32_t zoomRatio = 100;
1163     metaIn->addEntry(OHOS_STATUS_CAMERA_CURRENT_FPS, &fps, count);
1164     metaIn->addEntry(OHOS_STATUS_CAMERA_CURRENT_ZOOM_RATIO, &zoomRatio, count);
1165     cameraDevice->GetStatus(metaIn, metaOut);
1166 
1167     camera_metadata_item_t item;
1168     int retFindMeta = OHOS::Camera::FindCameraMetadataItem(metaOut->get(),
1169         OHOS_STATUS_CAMERA_CURRENT_ZOOM_RATIO, &item);
1170     if (retFindMeta == CAM_META_ITEM_NOT_FOUND) {
1171         MEDIA_ERR_LOG("HCaptureSession::QueryFpsAndZoomRatio() current zoom not found");
1172         return false;
1173     } else if (retFindMeta == CAM_META_SUCCESS) {
1174         currentZoomRatio = static_cast<float>(item.data.ui32[0]);
1175         MEDIA_INFO_LOG("HCaptureSession::QueryFpsAndZoomRatio() current zoom %{public}d.", item.data.ui32[0]);
1176     }
1177     retFindMeta = OHOS::Camera::FindCameraMetadataItem(metaOut->get(), OHOS_STATUS_CAMERA_CURRENT_FPS, &item);
1178     if (retFindMeta == CAM_META_ITEM_NOT_FOUND) {
1179         MEDIA_ERR_LOG("HCaptureSession::QueryFpsAndZoomRatio() current fps not found");
1180         return false;
1181     } else if (retFindMeta == CAM_META_SUCCESS) {
1182         currentFps = static_cast<float>(item.data.ui32[0]);
1183         MEDIA_INFO_LOG("HCaptureSession::QueryFpsAndZoomRatio() current fps %{public}d.", item.data.ui32[0]);
1184     }
1185     return true;
1186 }
1187 
QueryZoomPerformance(std::vector<float> & crossZoomAndTime,int32_t operationMode)1188 bool HCaptureSession::QueryZoomPerformance(std::vector<float>& crossZoomAndTime, int32_t operationMode)
1189 {
1190     auto cameraDevice = GetCameraDevice();
1191     CHECK_ERROR_RETURN_RET_LOG(cameraDevice == nullptr, false,
1192         "HCaptureSession::QueryZoomPerformance() cameraDevice is null");
1193     // query zoom performance. begin
1194     std::shared_ptr<OHOS::Camera::CameraMetadata> ability = cameraDevice->GetDeviceAbility();
1195     camera_metadata_item_t zoomItem;
1196     int retFindMeta =
1197         OHOS::Camera::FindCameraMetadataItem(ability->get(), OHOS_ABILITY_CAMERA_ZOOM_PERFORMANCE, &zoomItem);
1198     if (retFindMeta == CAM_META_ITEM_NOT_FOUND) {
1199         MEDIA_ERR_LOG("HCaptureSession::QueryZoomPerformance() current zoom not found");
1200         return false;
1201     } else if (retFindMeta == CAM_META_SUCCESS) {
1202         MEDIA_DEBUG_LOG("HCaptureSession::QueryZoomPerformance() zoom performance count %{public}d.", zoomItem.count);
1203         for (int i = 0; i < static_cast<int>(zoomItem.count); i++) {
1204             MEDIA_DEBUG_LOG(
1205                 "HCaptureSession::QueryZoomPerformance() zoom performance value %{public}d.", zoomItem.data.ui32[i]);
1206         }
1207     }
1208     int dataLenPerPoint = 3;
1209     int headLenPerMode = 2;
1210     MEDIA_DEBUG_LOG("HCaptureSession::QueryZoomPerformance() operationMode %{public}d.",
1211         static_cast<OHOS::HDI::Camera::V1_3::OperationMode>(operationMode));
1212     for (int i = 0; i < static_cast<int>(zoomItem.count);) {
1213         int sceneMode = static_cast<int>(zoomItem.data.ui32[i]);
1214         int zoomPointsNum = static_cast<int>(zoomItem.data.ui32[i + 1]);
1215         if (static_cast<OHOS::HDI::Camera::V1_3::OperationMode>(operationMode) == sceneMode) {
1216             for (int j = 0; j < dataLenPerPoint * zoomPointsNum; j++) {
1217                 crossZoomAndTime.push_back(zoomItem.data.ui32[i + headLenPerMode + j]);
1218                 MEDIA_DEBUG_LOG("HCaptureSession::QueryZoomPerformance()  crossZoomAndTime %{public}d.",
1219                     static_cast<int>(zoomItem.data.ui32[i + headLenPerMode + j]));
1220             }
1221             break;
1222         } else {
1223             i = i + 1 + zoomPointsNum * dataLenPerPoint + 1;
1224         }
1225     }
1226     return true;
1227 }
1228 
GetSensorOritation()1229 int32_t HCaptureSession::GetSensorOritation()
1230 {
1231     auto cameraDevice = GetCameraDevice();
1232     int32_t sensorOrientation = 0;
1233     CHECK_ERROR_RETURN_RET_LOG(cameraDevice == nullptr, sensorOrientation,
1234         "HCaptureSession::GetSensorOritation() cameraDevice is null");
1235     std::shared_ptr<OHOS::Camera::CameraMetadata> ability = cameraDevice->GetDeviceAbility();
1236     CHECK_ERROR_RETURN_RET(ability == nullptr, sensorOrientation);
1237     camera_metadata_item_t item;
1238     int ret = OHOS::Camera::FindCameraMetadataItem(ability->get(), OHOS_SENSOR_ORIENTATION, &item);
1239     CHECK_ERROR_RETURN_RET_LOG(ret != CAM_META_SUCCESS, sensorOrientation,
1240         "HCaptureSession::GetSensorOritation get sensor orientation failed");
1241     sensorOrientation = item.data.i32[0];
1242     MEDIA_INFO_LOG("HCaptureSession::GetSensorOritation sensor orientation %{public}d", sensorOrientation);
1243     return sensorOrientation;
1244 }
1245 
GetMovingPhotoBufferDuration()1246 int32_t HCaptureSession::GetMovingPhotoBufferDuration()
1247 {
1248     auto cameraDevice = GetCameraDevice();
1249     uint32_t preBufferDuration = 0;
1250     uint32_t postBufferDuration = 0;
1251     constexpr int32_t MILLSEC_MULTIPLE = 1000;
1252     CHECK_ERROR_RETURN_RET_LOG(cameraDevice == nullptr, 0,
1253         "HCaptureSession::GetMovingPhotoBufferDuration() cameraDevice is null");
1254     std::shared_ptr<OHOS::Camera::CameraMetadata> ability = cameraDevice->GetDeviceAbility();
1255     CHECK_ERROR_RETURN_RET(ability == nullptr, 0);
1256     camera_metadata_item_t item;
1257     int ret = OHOS::Camera::FindCameraMetadataItem(ability->get(), OHOS_MOVING_PHOTO_BUFFER_DURATION, &item);
1258     CHECK_ERROR_RETURN_RET_LOG(ret != CAM_META_SUCCESS, 0,
1259         "HCaptureSession::GetMovingPhotoBufferDuration get buffer duration failed");
1260     preBufferDuration = item.data.ui32[0];
1261     postBufferDuration = item.data.ui32[1];
1262     preCacheFrameCount_ = preBufferDuration == 0 ? preCacheFrameCount_ :
1263         static_cast<uint32_t>(float(preBufferDuration) / MILLSEC_MULTIPLE * VIDEO_FRAME_RATE);
1264     postCacheFrameCount_ = preBufferDuration == 0 ? postCacheFrameCount_ :
1265         static_cast<uint32_t>(float(postBufferDuration) / MILLSEC_MULTIPLE * VIDEO_FRAME_RATE);
1266     MEDIA_INFO_LOG("HCaptureSession::GetMovingPhotoBufferDuration preBufferDuration : %{public}u, "
1267         "postBufferDuration : %{public}u, preCacheFrameCount_ : %{public}u, postCacheFrameCount_ : %{public}u",
1268         preBufferDuration, postBufferDuration, preCacheFrameCount_, postCacheFrameCount_);
1269     return CAMERA_OK;
1270 }
1271 
SetSmoothZoom(int32_t smoothZoomType,int32_t operationMode,float targetZoomRatio,float & duration)1272 int32_t HCaptureSession::SetSmoothZoom(
1273     int32_t smoothZoomType, int32_t operationMode, float targetZoomRatio, float& duration)
1274 {
1275     constexpr int32_t ZOOM_RATIO_MULTIPLE = 100;
1276     auto cameraDevice = GetCameraDevice();
1277     CHECK_ERROR_RETURN_RET_LOG(cameraDevice == nullptr, CAMERA_UNKNOWN_ERROR,
1278         "HCaptureSession::SetSmoothZoom device is null");
1279     float currentFps = 30.0f;
1280     float currentZoomRatio = 1.0f;
1281     QueryFpsAndZoomRatio(currentFps, currentZoomRatio);
1282     std::vector<float> crossZoomAndTime {};
1283     QueryZoomPerformance(crossZoomAndTime, operationMode);
1284     float waitTime = 0.0;
1285     int dataLenPerPoint = 3;
1286     float frameIntervalMs = 1000.0 / currentFps;
1287     targetZoomRatio = targetZoomRatio * ZOOM_RATIO_MULTIPLE;
1288     int indexAdded = targetZoomRatio > currentZoomRatio ? 1 : 2;
1289     auto zoomAlgorithm = SmoothZoom::GetZoomAlgorithm(static_cast<SmoothZoomType>(smoothZoomType));
1290     auto array = zoomAlgorithm->GetZoomArray(currentZoomRatio, targetZoomRatio, frameIntervalMs);
1291     CHECK_ERROR_RETURN_RET_LOG(array.empty(), CAMERA_UNKNOWN_ERROR, "HCaptureSession::SetSmoothZoom array is empty");
1292     for (int i = 0; i < static_cast<int>(crossZoomAndTime.size()); i = i + dataLenPerPoint) {
1293         float crossZoom = crossZoomAndTime[i];
1294         if ((crossZoom - currentZoomRatio) * (crossZoom - targetZoomRatio) > 0) {
1295             continue;
1296         }
1297         float waitMs = crossZoomAndTime[i + indexAdded];
1298         if (std::fabs(currentZoomRatio - crossZoom) <= std::numeric_limits<float>::epsilon() &&
1299             currentZoomRatio > targetZoomRatio) {
1300             waitTime = crossZoomAndTime[i + indexAdded];
1301         }
1302         for (int j = 0; j < static_cast<int>(array.size()); j++) {
1303             if (static_cast<int>(array[j] - crossZoom) * static_cast<int>(array[0] - crossZoom) < 0) {
1304                 waitTime = fmax(waitMs - frameIntervalMs * j, waitTime);
1305                 break;
1306             }
1307         }
1308     }
1309     std::vector<uint32_t> zoomAndTimeArray {};
1310     for (int i = 0; i < static_cast<int>(array.size()); i++) {
1311         zoomAndTimeArray.push_back(static_cast<uint32_t>(array[i]));
1312         zoomAndTimeArray.push_back(static_cast<uint32_t>(i * frameIntervalMs + waitTime));
1313         MEDIA_DEBUG_LOG("HCaptureSession::SetSmoothZoom() zoom %{public}d, waitMs %{public}d.",
1314             static_cast<uint32_t>(array[i]), static_cast<uint32_t>(i * frameIntervalMs + waitTime));
1315     }
1316     duration = (static_cast<int>(array.size()) - 1) * frameIntervalMs + waitTime;
1317     MEDIA_DEBUG_LOG("HCaptureSession::SetSmoothZoom() duration %{public}f", duration);
1318     ProcessMetaZoomArray(zoomAndTimeArray, cameraDevice);
1319     return CAMERA_OK;
1320 }
1321 
ProcessMetaZoomArray(std::vector<uint32_t> & zoomAndTimeArray,sptr<HCameraDevice> & cameraDevice)1322 void HCaptureSession::ProcessMetaZoomArray(
1323     std::vector<uint32_t>& zoomAndTimeArray, sptr<HCameraDevice>& cameraDevice)
1324 {
1325     std::shared_ptr<OHOS::Camera::CameraMetadata> metaZoomArray = std::make_shared<OHOS::Camera::CameraMetadata>(1, 1);
1326     uint32_t zoomCount = static_cast<uint32_t>(zoomAndTimeArray.size());
1327     MEDIA_INFO_LOG("HCaptureSession::ProcessMetaZoomArray() zoomArray size: %{public}zu, zoomCount: %{public}u",
1328         zoomAndTimeArray.size(), zoomCount);
1329     metaZoomArray->addEntry(OHOS_CONTROL_SMOOTH_ZOOM_RATIOS, zoomAndTimeArray.data(), zoomCount);
1330     cameraDevice->UpdateSettingOnce(metaZoomArray);
1331 }
1332 
EnableMovingPhoto(bool isEnable)1333 int32_t HCaptureSession::EnableMovingPhoto(bool isEnable)
1334 {
1335     isSetMotionPhoto_ = isEnable;
1336     StartMovingPhotoStream();
1337     #ifdef CAMERA_USE_SENSOR
1338     if (isSetMotionPhoto_) {
1339         RegisterSensorCallback();
1340     } else {
1341         UnRegisterSensorCallback();
1342     }
1343     #endif
1344     auto device = GetCameraDevice();
1345     if (device != nullptr) {
1346         device->EnableMovingPhoto(isEnable);
1347     }
1348     GetMovingPhotoBufferDuration();
1349     GetMovingPhotoStartAndEndTime();
1350     return CAMERA_OK;
1351 }
1352 
Start()1353 int32_t HCaptureSession::Start()
1354 {
1355     CAMERA_SYNC_TRACE;
1356     int32_t errorCode = CAMERA_OK;
1357     MEDIA_INFO_LOG("HCaptureSession::Start prepare execute");
1358     stateMachine_.StateGuard([&errorCode, this](CaptureSessionState currentState) {
1359         bool isTransferSupport = stateMachine_.CheckTransfer(CaptureSessionState::SESSION_STARTED);
1360         if (!isTransferSupport) {
1361             MEDIA_ERR_LOG("HCaptureSession::Start() Need to call after committing configuration");
1362             errorCode = CAMERA_INVALID_STATE;
1363             return;
1364         }
1365 
1366         std::shared_ptr<OHOS::Camera::CameraMetadata> settings = nullptr;
1367         auto cameraDevice = GetCameraDevice();
1368         uint8_t usedAsPositionU8 = OHOS_CAMERA_POSITION_OTHER;
1369         MEDIA_INFO_LOG("HCaptureSession::Start usedAsPositionU8 default = %{public}d", usedAsPositionU8);
1370         if (cameraDevice != nullptr) {
1371             settings = cameraDevice->CloneCachedSettings();
1372             usedAsPositionU8 = cameraDevice->GetUsedAsPosition();
1373             MEDIA_INFO_LOG("HCaptureSession::Start usedAsPositionU8 set %{public}d", usedAsPositionU8);
1374             DumpMetadata(settings);
1375             UpdateMuteSetting(cameraDevice->GetDeviceMuteMode(), settings);
1376         }
1377         camera_position_enum_t cameraPosition = static_cast<camera_position_enum_t>(usedAsPositionU8);
1378         errorCode = StartPreviewStream(settings, cameraPosition);
1379         if (errorCode == CAMERA_OK) {
1380             isSessionStarted_ = true;
1381         }
1382         stateMachine_.Transfer(CaptureSessionState::SESSION_STARTED);
1383     });
1384     MEDIA_INFO_LOG("HCaptureSession::Start execute success");
1385     return errorCode;
1386 }
1387 
UpdateMuteSetting(bool muteMode,std::shared_ptr<OHOS::Camera::CameraMetadata> & settings)1388 void HCaptureSession::UpdateMuteSetting(bool muteMode, std::shared_ptr<OHOS::Camera::CameraMetadata> &settings)
1389 {
1390     int32_t count = 1;
1391     uint8_t mode = muteMode? OHOS_CAMERA_MUTE_MODE_SOLID_COLOR_BLACK:OHOS_CAMERA_MUTE_MODE_OFF;
1392     settings->addEntry(OHOS_CONTROL_MUTE_MODE, &mode, count);
1393 }
1394 
StartMovingPhoto(sptr<HStreamRepeat> & curStreamRepeat)1395 void HCaptureSession::StartMovingPhoto(sptr<HStreamRepeat>& curStreamRepeat)
1396 {
1397     auto thisPtr = wptr<HCaptureSession>(this);
1398     curStreamRepeat->SetMovingPhotoStartCallback([thisPtr]() {
1399         auto sessionPtr = thisPtr.promote();
1400         if (sessionPtr != nullptr) {
1401             MEDIA_INFO_LOG("StartMovingPhotoStream when addDeferedSurface");
1402             sessionPtr->StartMovingPhotoStream();
1403         }
1404     });
1405 }
1406 
GetMovingPhotoStartAndEndTime()1407 void HCaptureSession::GetMovingPhotoStartAndEndTime()
1408 {
1409     auto thisPtr = wptr<HCaptureSession>(this);
1410     auto cameraDevice = GetCameraDevice();
1411     CHECK_ERROR_RETURN_LOG(cameraDevice == nullptr, "HCaptureSession::GetMovingPhotoStartAndEndTime device is null");
1412     cameraDevice->SetMovingPhotoStartTimeCallback([thisPtr](int32_t captureId, int64_t startTimeStamp) {
1413         MEDIA_INFO_LOG("SetMovingPhotoStartTimeCallback function enter");
1414         auto sessionPtr = thisPtr.promote();
1415         CHECK_ERROR_RETURN_LOG(sessionPtr == nullptr, "Set start time callback sessionPtr is null");
1416         CHECK_ERROR_RETURN_LOG(sessionPtr->taskManager_ == nullptr, "Set start time callback taskManager_ is null");
1417         std::lock_guard<mutex> lock(sessionPtr->taskManager_->startTimeMutex_);
1418         if (sessionPtr->taskManager_->mPStartTimeMap_.count(captureId) == 0) {
1419             MEDIA_INFO_LOG("Save moving photo start info, captureId : %{public}d, start timestamp : %{public}" PRIu64,
1420                 captureId, startTimeStamp);
1421             sessionPtr->taskManager_->mPStartTimeMap_.insert(make_pair(captureId, startTimeStamp));
1422         }
1423     });
1424 
1425     cameraDevice->SetMovingPhotoEndTimeCallback([thisPtr](int32_t captureId, int64_t endTimeStamp) {
1426         auto sessionPtr = thisPtr.promote();
1427         CHECK_ERROR_RETURN_LOG(sessionPtr == nullptr, "Set end time callback sessionPtr is null");
1428         CHECK_ERROR_RETURN_LOG(sessionPtr->taskManager_ == nullptr, "Set end time callback taskManager_ is null");
1429         std::lock_guard<mutex> lock(sessionPtr->taskManager_->endTimeMutex_);
1430         if (sessionPtr->taskManager_->mPEndTimeMap_.count(captureId) == 0) {
1431             MEDIA_INFO_LOG("Save moving photo end info, captureId : %{public}d, end timestamp : %{public}" PRIu64,
1432                 captureId, endTimeStamp);
1433             sessionPtr->taskManager_->mPEndTimeMap_.insert(make_pair(captureId, endTimeStamp));
1434         }
1435     });
1436 }
1437 
StartPreviewStream(const std::shared_ptr<OHOS::Camera::CameraMetadata> & settings,camera_position_enum_t cameraPosition)1438 int32_t HCaptureSession::StartPreviewStream(const std::shared_ptr<OHOS::Camera::CameraMetadata>& settings,
1439     camera_position_enum_t cameraPosition)
1440 {
1441     int32_t errorCode = CAMERA_OK;
1442     auto repeatStreams = streamContainer_.GetStreams(StreamType::REPEAT);
1443     bool hasDerferedPreview = false;
1444     // start preview
1445     for (auto& item : repeatStreams) {
1446         auto curStreamRepeat = CastStream<HStreamRepeat>(item);
1447         auto repeatType = curStreamRepeat->GetRepeatStreamType();
1448         if (repeatType != RepeatStreamType::PREVIEW) {
1449             continue;
1450         }
1451         if (curStreamRepeat->GetPreparedCaptureId() != CAPTURE_ID_UNSET) {
1452             continue;
1453         }
1454         curStreamRepeat->SetUsedAsPosition(cameraPosition);
1455         errorCode = curStreamRepeat->Start(settings);
1456         hasDerferedPreview = curStreamRepeat->producer_ == nullptr;
1457         if (isSetMotionPhoto_ && hasDerferedPreview) {
1458             StartMovingPhoto(curStreamRepeat);
1459         }
1460         if (errorCode != CAMERA_OK) {
1461             MEDIA_ERR_LOG("HCaptureSession::Start(), Failed to start preview, rc: %{public}d", errorCode);
1462             break;
1463         }
1464     }
1465     // start movingPhoto
1466     for (auto& item : repeatStreams) {
1467         auto curStreamRepeat = CastStream<HStreamRepeat>(item);
1468         auto repeatType = curStreamRepeat->GetRepeatStreamType();
1469         if (repeatType != RepeatStreamType::LIVEPHOTO) {
1470             continue;
1471         }
1472         int32_t movingPhotoErrorCode = CAMERA_OK;
1473         if (isSetMotionPhoto_ && !hasDerferedPreview) {
1474             movingPhotoErrorCode = curStreamRepeat->Start(settings);
1475             #ifdef MOVING_PHOTO_ADD_AUDIO
1476             std::lock_guard<std::mutex> lock(movingPhotoStatusLock_);
1477             audioCapturerSession_ != nullptr && audioCapturerSession_->StartAudioCapture();
1478             #endif
1479         }
1480         if (movingPhotoErrorCode != CAMERA_OK) {
1481             MEDIA_ERR_LOG("Failed to start movingPhoto, rc: %{public}d", movingPhotoErrorCode);
1482             break;
1483         }
1484     }
1485     return errorCode;
1486 }
1487 
Stop()1488 int32_t HCaptureSession::Stop()
1489 {
1490     CAMERA_SYNC_TRACE;
1491     int32_t errorCode = CAMERA_OK;
1492     MEDIA_INFO_LOG("HCaptureSession::Stop prepare execute");
1493     stateMachine_.StateGuard([&errorCode, this](CaptureSessionState currentState) {
1494         bool isTransferSupport = stateMachine_.CheckTransfer(CaptureSessionState::SESSION_CONFIG_COMMITTED);
1495         if (!isTransferSupport) {
1496             MEDIA_ERR_LOG("HCaptureSession::Stop() Need to call after Start");
1497             errorCode = CAMERA_INVALID_STATE;
1498             return;
1499         }
1500         auto allStreams = streamContainer_.GetAllStreams();
1501         for (auto& item : allStreams) {
1502             if (item->GetStreamType() == StreamType::REPEAT) {
1503                 auto repeatStream = CastStream<HStreamRepeat>(item);
1504                 if (repeatStream->GetRepeatStreamType() == RepeatStreamType::PREVIEW) {
1505                     errorCode = repeatStream->Stop();
1506                 } else if (repeatStream->GetRepeatStreamType() == RepeatStreamType::LIVEPHOTO) {
1507                     repeatStream->Stop();
1508                     StopMovingPhoto();
1509                 } else {
1510                     repeatStream->Stop();
1511                 }
1512             } else if (item->GetStreamType() == StreamType::METADATA) {
1513                 CastStream<HStreamMetadata>(item)->Stop();
1514             } else if (item->GetStreamType() == StreamType::CAPTURE) {
1515                 CastStream<HStreamCapture>(item)->CancelCapture();
1516             } else if (item->GetStreamType() == StreamType::DEPTH) {
1517                 CastStream<HStreamDepthData>(item)->Stop();
1518             } else {
1519                 MEDIA_ERR_LOG("HCaptureSession::Stop(), get unknow stream, streamType: %{public}d, streamId:%{public}d",
1520                     item->GetStreamType(), item->GetFwkStreamId());
1521             }
1522             if (errorCode != CAMERA_OK) {
1523                 MEDIA_ERR_LOG("HCaptureSession::Stop(), Failed to stop stream, rc: %{public}d, streamId:%{public}d",
1524                     errorCode, item->GetFwkStreamId());
1525             }
1526         }
1527         if (errorCode == CAMERA_OK) {
1528             isSessionStarted_ = false;
1529         }
1530         stateMachine_.Transfer(CaptureSessionState::SESSION_CONFIG_COMMITTED);
1531     });
1532     MEDIA_INFO_LOG("HCaptureSession::Stop execute success");
1533     return errorCode;
1534 }
1535 
ReleaseStreams()1536 void HCaptureSession::ReleaseStreams()
1537 {
1538     CAMERA_SYNC_TRACE;
1539     std::vector<int32_t> fwkStreamIds;
1540     std::vector<int32_t> hdiStreamIds;
1541     auto allStream = streamContainer_.GetAllStreams();
1542     for (auto& stream : allStream) {
1543         auto fwkStreamId = stream->GetFwkStreamId();
1544         if (fwkStreamId != STREAM_ID_UNSET) {
1545             fwkStreamIds.emplace_back(fwkStreamId);
1546         }
1547         auto hdiStreamId = stream->GetHdiStreamId();
1548         if (hdiStreamId != STREAM_ID_UNSET) {
1549             hdiStreamIds.emplace_back(hdiStreamId);
1550         }
1551         stream->ReleaseStream(true);
1552     }
1553     streamContainer_.Clear();
1554     MEDIA_INFO_LOG("HCaptureSession::ReleaseStreams() streamIds size() = %{public}zu, fwkStreamIds:%{public}s, "
1555         "hdiStreamIds:%{public}s,",
1556         fwkStreamIds.size(), Container2String(fwkStreamIds.begin(), fwkStreamIds.end()).c_str(),
1557         Container2String(hdiStreamIds.begin(), hdiStreamIds.end()).c_str());
1558     auto cameraDevice = GetCameraDevice();
1559     if ((cameraDevice != nullptr) && !hdiStreamIds.empty()) {
1560         cameraDevice->ReleaseStreams(hdiStreamIds);
1561     }
1562     isNeedMediaLib = false;
1563     HCaptureSession::DelayCloseMediaLib();
1564 }
1565 
Release(CaptureSessionReleaseType type)1566 int32_t HCaptureSession::Release(CaptureSessionReleaseType type)
1567 {
1568     CAMERA_SYNC_TRACE;
1569     int32_t errorCode = CAMERA_OK;
1570     MEDIA_INFO_LOG("HCaptureSession::Release prepare execute, release type is:%{public}d pid(%{public}d)", type, pid_);
1571     //Check release without lock first
1572     if (stateMachine_.IsStateNoLock(CaptureSessionState::SESSION_RELEASED)) {
1573         MEDIA_ERR_LOG("HCaptureSession::Release error, session is already released!");
1574         return CAMERA_INVALID_STATE;
1575     }
1576 
1577     stateMachine_.StateGuard([&errorCode, this, type](CaptureSessionState currentState) {
1578         MEDIA_INFO_LOG("HCaptureSession::Release pid(%{public}d). release type is:%{public}d", pid_, type);
1579         bool isTransferSupport = stateMachine_.CheckTransfer(CaptureSessionState::SESSION_RELEASED);
1580         if (!isTransferSupport) {
1581             MEDIA_ERR_LOG("HCaptureSession::Release error, this session is already released!");
1582             errorCode = CAMERA_INVALID_STATE;
1583             return;
1584         }
1585         // stop movingPhoto
1586         StopMovingPhoto();
1587 
1588         // Clear outputs
1589         ReleaseStreams();
1590 
1591         // Clear inputs
1592         auto cameraDevice = GetCameraDevice();
1593         if (cameraDevice != nullptr) {
1594             cameraDevice->Release();
1595             SetCameraDevice(nullptr);
1596         }
1597 
1598         // Clear current session
1599         TotalSessionErase(pid_);
1600         MEDIA_DEBUG_LOG("HCaptureSession::Release clear pid left services(%{public}zu).", TotalSessionSize());
1601 
1602         sptr<ICaptureSessionCallback> emptyCallback = nullptr;
1603         SetCallback(emptyCallback);
1604         #ifdef CAMERA_USE_SENSOR
1605         if (isSetMotionPhoto_) {
1606             UnRegisterSensorCallback();
1607         }
1608         #endif
1609         stateMachine_.Transfer(CaptureSessionState::SESSION_RELEASED);
1610         isSessionStarted_ = false;
1611         if (displayListener_) {
1612             OHOS::Rosen::DisplayManager::GetInstance().UnregisterDisplayListener(displayListener_);
1613             displayListener_ = nullptr;
1614         }
1615         std::lock_guard<std::mutex> lock(movingPhotoStatusLock_);
1616         livephotoListener_ = nullptr;
1617         videoCache_ = nullptr;
1618         if (taskManager_) {
1619             taskManager_->ClearTaskResource();
1620             taskManager_ = nullptr;
1621         }
1622     });
1623     MEDIA_INFO_LOG("HCaptureSession::Release execute success");
1624     return errorCode;
1625 }
1626 
Release()1627 int32_t HCaptureSession::Release()
1628 {
1629     MEDIA_INFO_LOG("HCaptureSession::Release()");
1630     CameraReportUtils::GetInstance().SetModeChangePerfStartInfo(opMode_, CameraReportUtils::GetCallerInfo());
1631     return Release(CaptureSessionReleaseType::RELEASE_TYPE_CLIENT);
1632 }
1633 
OperatePermissionCheck(uint32_t interfaceCode)1634 int32_t HCaptureSession::OperatePermissionCheck(uint32_t interfaceCode)
1635 {
1636     if (stateMachine_.GetCurrentState() == CaptureSessionState::SESSION_RELEASED) {
1637         MEDIA_ERR_LOG("HCaptureSession::OperatePermissionCheck session is released");
1638         return CAMERA_INVALID_STATE;
1639     }
1640     switch (static_cast<CaptureSessionInterfaceCode>(interfaceCode)) {
1641         case CAMERA_CAPTURE_SESSION_START: {
1642             auto callerToken = IPCSkeleton::GetCallingTokenID();
1643             if (callerToken_ != callerToken) {
1644                 MEDIA_ERR_LOG("HCaptureSession::OperatePermissionCheck fail, callerToken not legal");
1645                 return CAMERA_OPERATION_NOT_ALLOWED;
1646             }
1647             break;
1648         }
1649         default:
1650             break;
1651     }
1652     return CAMERA_OK;
1653 }
1654 
DestroyStubObjectForPid(pid_t pid)1655 void HCaptureSession::DestroyStubObjectForPid(pid_t pid)
1656 {
1657     MEDIA_DEBUG_LOG("camera stub services(%{public}zu) pid(%{public}d).", TotalSessionSize(), pid);
1658     sptr<HCaptureSession> session = TotalSessionsGet(pid);
1659     if (session != nullptr) {
1660         session->Release(CaptureSessionReleaseType::RELEASE_TYPE_CLIENT_DIED);
1661     }
1662     MEDIA_DEBUG_LOG("camera stub services(%{public}zu).", TotalSessionSize());
1663 }
1664 
SetCallback(sptr<ICaptureSessionCallback> & callback)1665 int32_t HCaptureSession::SetCallback(sptr<ICaptureSessionCallback>& callback)
1666 {
1667     if (callback == nullptr) {
1668         MEDIA_WARNING_LOG("HCaptureSession::SetCallback callback is null, we should clear the callback");
1669     }
1670 
1671     // Not implement yet.
1672     return CAMERA_OK;
1673 }
1674 
GetSessionState()1675 std::string HCaptureSession::GetSessionState()
1676 {
1677     auto currentState = stateMachine_.GetCurrentState();
1678     std::map<CaptureSessionState, std::string>::const_iterator iter = SESSION_STATE_STRING_MAP.find(currentState);
1679     if (iter != SESSION_STATE_STRING_MAP.end()) {
1680         return iter->second;
1681     }
1682     return std::to_string(static_cast<uint32_t>(currentState));
1683 }
1684 
DumpCameraSessionSummary(CameraInfoDumper & infoDumper)1685 void HCaptureSession::DumpCameraSessionSummary(CameraInfoDumper& infoDumper)
1686 {
1687     infoDumper.Msg("Number of Camera clients:[" + std::to_string(TotalSessionSize()) + "]");
1688 }
1689 
DumpSessions(CameraInfoDumper & infoDumper)1690 void HCaptureSession::DumpSessions(CameraInfoDumper& infoDumper)
1691 {
1692     auto totalSession = TotalSessionsCopy();
1693     uint32_t index = 0;
1694     for (auto it = totalSession.begin(); it != totalSession.end(); it++) {
1695         if (it->second != nullptr) {
1696             sptr<HCaptureSession> session = it->second;
1697             infoDumper.Title("Camera Sessions[" + std::to_string(index++) + "] Info:");
1698             session->DumpSessionInfo(infoDumper);
1699         }
1700     }
1701 }
1702 
DumpSessionInfo(CameraInfoDumper & infoDumper)1703 void HCaptureSession::DumpSessionInfo(CameraInfoDumper& infoDumper)
1704 {
1705     infoDumper.Msg("Client pid:[" + std::to_string(pid_)+ "]    Client uid:[" + std::to_string(uid_) + "]");
1706     infoDumper.Msg("session state:[" + GetSessionState() + "]");
1707     for (auto& stream : streamContainer_.GetAllStreams()) {
1708         infoDumper.Push();
1709         stream->DumpStreamInfo(infoDumper);
1710         infoDumper.Pop();
1711     }
1712 }
1713 
EnableMovingPhotoMirror(bool isMirror,bool isConfig)1714 int32_t HCaptureSession::EnableMovingPhotoMirror(bool isMirror, bool isConfig)
1715 {
1716     if (!isConfig) {
1717         isMovingPhotoMirror_ = isMirror;
1718         return CAMERA_OK;
1719     }
1720     if (!isSetMotionPhoto_ || isMirror == isMovingPhotoMirror_) {
1721         return CAMERA_OK;
1722     }
1723     auto repeatStreams = streamContainer_.GetStreams(StreamType::REPEAT);
1724     for (auto& stream : repeatStreams) {
1725         if (stream == nullptr) {
1726             continue;
1727         }
1728         auto streamRepeat = CastStream<HStreamRepeat>(stream);
1729         if (streamRepeat->GetRepeatStreamType() == RepeatStreamType::LIVEPHOTO) {
1730             MEDIA_INFO_LOG("restart movingphoto stream.");
1731             if (streamRepeat->SetMirrorForLivePhoto(isMirror, opMode_)) {
1732                 isMovingPhotoMirror_ = isMirror;
1733                 // set clear cache flag
1734                 std::lock_guard<std::mutex> lock(movingPhotoStatusLock_);
1735                 livephotoListener_->SetClearFlag();
1736             }
1737             break;
1738         }
1739     }
1740     return CAMERA_OK;
1741 }
1742 
GetOutputStatus(int32_t & status)1743 void HCaptureSession::GetOutputStatus(int32_t &status)
1744 {
1745     auto repeatStreams = streamContainer_.GetStreams(StreamType::REPEAT);
1746     for (auto& stream : repeatStreams) {
1747         if (stream == nullptr) {
1748             continue;
1749         }
1750         auto streamRepeat = CastStream<HStreamRepeat>(stream);
1751         if (streamRepeat->GetRepeatStreamType() == RepeatStreamType::VIDEO) {
1752             if (streamRepeat->GetPreparedCaptureId() != CAPTURE_ID_UNSET) {
1753                 const int32_t videoStartStatus = 2;
1754                 status = videoStartStatus;
1755             }
1756         }
1757     }
1758 }
1759 
1760 #ifdef CAMERA_USE_SENSOR
RegisterSensorCallback()1761 void HCaptureSession::RegisterSensorCallback()
1762 {
1763     std::lock_guard<std::mutex> lock(sensorLock_);
1764     if (isRegisterSensorSuccess_) {
1765         MEDIA_INFO_LOG("HCaptureSession::RegisterSensorCallback isRegisterSensorSuccess return");
1766         return;
1767     }
1768     MEDIA_INFO_LOG("HCaptureSession::RegisterSensorCallback start");
1769     user.callback = GravityDataCallbackImpl;
1770     int32_t subscribeRet = SubscribeSensor(SENSOR_TYPE_ID_GRAVITY, &user);
1771     MEDIA_INFO_LOG("RegisterSensorCallback, subscribeRet: %{public}d", subscribeRet);
1772     int32_t setBatchRet = SetBatch(SENSOR_TYPE_ID_GRAVITY, &user, POSTURE_INTERVAL, 0);
1773     MEDIA_INFO_LOG("RegisterSensorCallback, setBatchRet: %{public}d", setBatchRet);
1774     int32_t activateRet = ActivateSensor(SENSOR_TYPE_ID_GRAVITY, &user);
1775     MEDIA_INFO_LOG("RegisterSensorCallback, activateRet: %{public}d", activateRet);
1776     if (subscribeRet != CAMERA_OK || setBatchRet != CAMERA_OK || activateRet != CAMERA_OK) {
1777         isRegisterSensorSuccess_ = false;
1778         MEDIA_INFO_LOG("RegisterSensorCallback failed.");
1779     } else {
1780         isRegisterSensorSuccess_ = true;
1781     }
1782 }
1783 
UnRegisterSensorCallback()1784 void HCaptureSession::UnRegisterSensorCallback()
1785 {
1786     std::lock_guard<std::mutex> lock(sensorLock_);
1787     int32_t deactivateRet = DeactivateSensor(SENSOR_TYPE_ID_GRAVITY, &user);
1788     int32_t unsubscribeRet = UnsubscribeSensor(SENSOR_TYPE_ID_GRAVITY, &user);
1789     if (deactivateRet == CAMERA_OK && unsubscribeRet == CAMERA_OK) {
1790         MEDIA_INFO_LOG("HCameraService.UnRegisterSensorCallback success.");
1791         isRegisterSensorSuccess_ = false;
1792     } else {
1793         MEDIA_INFO_LOG("HCameraService.UnRegisterSensorCallback failed.");
1794     }
1795 }
1796 
GravityDataCallbackImpl(SensorEvent * event)1797 void HCaptureSession::GravityDataCallbackImpl(SensorEvent* event)
1798 {
1799     MEDIA_DEBUG_LOG("GravityDataCallbackImpl prepare execute");
1800     CHECK_ERROR_RETURN_LOG(event == nullptr, "SensorEvent is nullptr.");
1801     CHECK_ERROR_RETURN_LOG(event[0].data == nullptr, "SensorEvent[0].data is nullptr.");
1802     CHECK_ERROR_RETURN_LOG(event->sensorTypeId != SENSOR_TYPE_ID_GRAVITY, "SensorCallback error type.");
1803     // this data will be delete when callback execute finish
1804     GravityData* nowGravityData = reinterpret_cast<GravityData*>(event->data);
1805     gravityData = { nowGravityData->x, nowGravityData->y, nowGravityData->z };
1806     sensorRotation = CalcSensorRotation(CalcRotationDegree(gravityData));
1807 }
1808 
CalcSensorRotation(int32_t sensorDegree)1809 int32_t HCaptureSession::CalcSensorRotation(int32_t sensorDegree)
1810 {
1811     // Use ROTATION_0 when degree range is [0, 30]∪[330, 359]
1812     if (sensorDegree >= 0 && (sensorDegree <= 30 || sensorDegree >= 330)) {
1813         return STREAM_ROTATE_0;
1814     } else if (sensorDegree >= 60 && sensorDegree <= 120) { // Use ROTATION_90 when degree range is [60, 120]
1815         return STREAM_ROTATE_90;
1816     } else if (sensorDegree >= 150 && sensorDegree <= 210) { // Use ROTATION_180 when degree range is [150, 210]
1817         return STREAM_ROTATE_180;
1818     } else if (sensorDegree >= 240 && sensorDegree <= 300) { // Use ROTATION_270 when degree range is [240, 300]
1819         return STREAM_ROTATE_270;
1820     } else {
1821         return sensorRotation;
1822     }
1823 }
1824 
CalcRotationDegree(GravityData data)1825 int32_t HCaptureSession::CalcRotationDegree(GravityData data)
1826 {
1827     float x = data.x;
1828     float y = data.y;
1829     float z = data.z;
1830     int degree = -1;
1831     if ((x * x + y * y) * VALID_INCLINATION_ANGLE_THRESHOLD_COEFFICIENT < z * z) {
1832         return degree;
1833     }
1834     // arccotx = pi / 2 - arctanx, 90 is used to calculate acot(in degree); degree = rad / pi * 180
1835     degree = 90 - static_cast<int>(round(atan2(y, -x) / M_PI * 180));
1836     // Normalize the degree to the range of 0~360
1837     return degree >= 0 ? degree % 360 : degree % 360 + 360;
1838 }
1839 #endif
1840 
StartMovingPhotoEncode(int32_t rotation,uint64_t timestamp,int32_t format,int32_t captureId)1841 void HCaptureSession::StartMovingPhotoEncode(int32_t rotation, uint64_t timestamp, int32_t format, int32_t captureId)
1842 {
1843     if (!isSetMotionPhoto_) {
1844         return;
1845     }
1846     int32_t addMirrorRotation = 0;
1847     MEDIA_INFO_LOG("sensorRotation is %{public}d", sensorRotation);
1848     if ((sensorRotation == STREAM_ROTATE_0 || sensorRotation == STREAM_ROTATE_180) && isMovingPhotoMirror_) {
1849         addMirrorRotation = STREAM_ROTATE_180;
1850     }
1851     int32_t realRotation = GetSensorOritation() + rotation + addMirrorRotation;
1852     realRotation = realRotation % ROTATION_360;
1853     StartRecord(timestamp, realRotation, captureId);
1854 }
1855 
CreateDisplayName(const std::string & suffix)1856 std::string HCaptureSession::CreateDisplayName(const std::string& suffix)
1857 {
1858     struct tm currentTime;
1859     std::string formattedTime = "";
1860     if (GetSystemCurrentTime(&currentTime)) {
1861         std::stringstream ss;
1862         ss << prefix << std::setw(yearWidth) << std::setfill(placeholder) << currentTime.tm_year + startYear
1863            << std::setw(otherWidth) << std::setfill(placeholder) << (currentTime.tm_mon + 1)
1864            << std::setw(otherWidth) << std::setfill(placeholder) << currentTime.tm_mday
1865            << connector << std::setw(otherWidth) << std::setfill(placeholder) << currentTime.tm_hour
1866            << std::setw(otherWidth) << std::setfill(placeholder) << currentTime.tm_min
1867            << std::setw(otherWidth) << std::setfill(placeholder) << currentTime.tm_sec;
1868         formattedTime = ss.str();
1869     } else {
1870         MEDIA_ERR_LOG("Failed to get current time.");
1871     }
1872     if (lastDisplayName_ == formattedTime) {
1873         saveIndex++;
1874         formattedTime = formattedTime + connector + std::to_string(saveIndex);
1875         MEDIA_INFO_LOG("CreateDisplayName is %{private}s", formattedTime.c_str());
1876         return formattedTime;
1877     }
1878     lastDisplayName_ = formattedTime;
1879     saveIndex = 0;
1880     MEDIA_INFO_LOG("CreateDisplayName is %{private}s", formattedTime.c_str());
1881     return formattedTime;
1882 }
1883 
CreateBurstDisplayName(int32_t imageSeqId,int32_t seqId)1884 std::string HCaptureSession::CreateBurstDisplayName(int32_t imageSeqId, int32_t seqId)
1885 {
1886     struct tm currentTime;
1887     std::string formattedTime = "";
1888     std::stringstream ss;
1889     // a group of burst capture use the same prefix
1890     if (imageSeqId == 1) {
1891         if (!GetSystemCurrentTime(&currentTime)) {
1892             MEDIA_ERR_LOG("Failed to get current time.");
1893             return formattedTime;
1894         }
1895         ss << prefix << std::setw(yearWidth) << std::setfill(placeholder) << currentTime.tm_year + startYear
1896            << std::setw(otherWidth) << std::setfill(placeholder) << (currentTime.tm_mon + 1) << std::setw(otherWidth)
1897            << std::setfill(placeholder) << currentTime.tm_mday << connector << std::setw(otherWidth)
1898            << std::setfill(placeholder) << currentTime.tm_hour << std::setw(otherWidth) << std::setfill(placeholder)
1899            << currentTime.tm_min << std::setw(otherWidth) << std::setfill(placeholder) << currentTime.tm_sec
1900            << connector << burstTag;
1901         lastBurstPrefix_ = ss.str();
1902         ss << std::setw(burstWidth) << std::setfill(placeholder) << seqId;
1903     } else {
1904         ss << lastBurstPrefix_ << std::setw(burstWidth) << std::setfill(placeholder) << seqId;
1905     }
1906     MEDIA_DEBUG_LOG("burst prefix is %{private}s", lastBurstPrefix_.c_str());
1907 
1908     if (seqId == 1) {
1909         ss << coverTag;
1910     }
1911     formattedTime = ss.str();
1912     MEDIA_INFO_LOG("CreateBurstDisplayName is %{private}s", formattedTime.c_str());
1913     return formattedTime;
1914 }
1915 
1916 typedef PhotoAssetIntf* (*GetPhotoAssetProxy)(int32_t, int32_t);
1917 
SetCameraPhotoProxyInfo(sptr<CameraServerPhotoProxy> cameraPhotoProxy,int32_t & cameraShotType,bool & isBursting,std::string & burstKey)1918 void HCaptureSession::SetCameraPhotoProxyInfo(sptr<CameraServerPhotoProxy> cameraPhotoProxy,
1919     int32_t &cameraShotType, bool &isBursting, std::string &burstKey)
1920 {
1921     cameraPhotoProxy->SetShootingMode(opMode_);
1922     int32_t captureId = cameraPhotoProxy->GetCaptureId();
1923     std::string imageId = cameraPhotoProxy->GetPhotoId();
1924     isBursting = false;
1925     bool isCoverPhoto = false;
1926     int32_t invalidBurstSeqId = -1;
1927     auto captureStreams = streamContainer_.GetStreams(StreamType::CAPTURE);
1928     for (auto& stream : captureStreams) {
1929         CHECK_AND_CONTINUE_LOG(stream != nullptr, "stream is null");
1930         MEDIA_INFO_LOG("CreateMediaLibrary get captureStream");
1931         auto streamCapture = CastStream<HStreamCapture>(stream);
1932         isBursting = streamCapture->IsBurstCapture(captureId);
1933         if (isBursting) {
1934             burstKey = streamCapture->GetBurstKey(captureId);
1935             streamCapture->SetBurstImages(captureId, imageId);
1936             isCoverPhoto = streamCapture->IsBurstCover(captureId);
1937             int32_t burstSeqId = cameraPhotoProxy->GetBurstSeqId();
1938             int32_t imageSeqId = streamCapture->GetCurBurstSeq(captureId);
1939             int32_t displaySeqId = (burstSeqId != invalidBurstSeqId) ? burstSeqId : imageSeqId;
1940             cameraPhotoProxy->SetDisplayName(CreateBurstDisplayName(imageSeqId, displaySeqId));
1941             streamCapture->CheckResetBurstKey(captureId);
1942             MEDIA_INFO_LOG("isBursting burstKey:%{public}s isCoverPhoto:%{public}d", burstKey.c_str(), isCoverPhoto);
1943             int32_t burstShotType = 3;
1944             cameraShotType = burstShotType;
1945             cameraPhotoProxy->SetBurstInfo(burstKey, isCoverPhoto);
1946             break;
1947         }
1948     }
1949     MEDIA_INFO_LOG("GetLocation latitude:%{private}f, quality:%{public}d, format:%{public}d,",
1950         cameraPhotoProxy->GetLatitude(), cameraPhotoProxy->GetPhotoQuality(), cameraPhotoProxy->GetFormat());
1951 }
1952 
CreateMediaLibrary(sptr<CameraPhotoProxy> & photoProxy,std::string & uri,int32_t & cameraShotType,std::string & burstKey,int64_t timestamp)1953 int32_t HCaptureSession::CreateMediaLibrary(sptr<CameraPhotoProxy> &photoProxy,
1954     std::string &uri, int32_t &cameraShotType, std::string &burstKey, int64_t timestamp)
1955 {
1956     CAMERA_SYNC_TRACE;
1957     constexpr int32_t movingPhotoShotType = 2;
1958     constexpr int32_t imageShotType = 0;
1959     cameraShotType = isSetMotionPhoto_ ? movingPhotoShotType : imageShotType;
1960     MessageParcel data;
1961     photoProxy->WriteToParcel(data);
1962     photoProxy->CameraFreeBufferHandle();
1963     sptr<CameraServerPhotoProxy> cameraPhotoProxy = new CameraServerPhotoProxy();
1964     cameraPhotoProxy->ReadFromParcel(data);
1965     cameraPhotoProxy->SetDisplayName(CreateDisplayName(suffixJpeg));
1966     int32_t captureId = cameraPhotoProxy->GetCaptureId();
1967     bool isBursting = false;
1968     CameraReportDfxUtils::GetInstance()->SetPrepareProxyEndInfo(captureId);
1969     CameraReportDfxUtils::GetInstance()->SetAddProxyStartInfo(captureId);
1970     SetCameraPhotoProxyInfo(cameraPhotoProxy, cameraShotType, isBursting, burstKey);
1971     GetPhotoAssetProxy getPhotoAssetProxy = (GetPhotoAssetProxy)(CameraDynamicLoader::GetInstance()->GetFunction(
1972         MEDIA_LIB_SO, "createPhotoAssetIntf"));
1973     PhotoAssetIntf* photoAssetProxy = getPhotoAssetProxy(cameraShotType, IPCSkeleton::GetCallingUid());
1974     photoAssetProxy->AddPhotoProxy((sptr<PhotoProxy>&)cameraPhotoProxy);
1975     uri = photoAssetProxy->GetPhotoAssetUri();
1976     if (!isBursting && isSetMotionPhoto_ && taskManager_) {
1977         MEDIA_INFO_LOG("taskManager setVideoFd start");
1978         taskManager_->SetVideoFd(timestamp, photoAssetProxy, captureId);
1979     } else {
1980         delete photoAssetProxy;
1981     }
1982     CameraReportDfxUtils::GetInstance()->SetAddProxyEndInfo(captureId);
1983     return CAMERA_OK;
1984 }
1985 
1986 std::unordered_map<std::string, float> exifOrientationDegree = {
1987     {"Top-left", 0},
1988     {"Top-right", 90},
1989     {"Bottom-right", 180},
1990     {"Right-top", 90},
1991     {"Left-bottom", 270},
1992 };
1993 
TransExifOrientationToDegree(const std::string & orientation)1994 inline float TransExifOrientationToDegree(const std::string& orientation)
1995 {
1996     float degree = .0;
1997     if (exifOrientationDegree.count(orientation)) {
1998         degree = exifOrientationDegree[orientation];
1999     }
2000     return degree;
2001 }
2002 
RotatePixelMap(std::shared_ptr<Media::PixelMap> pixelMap,const std::string & exifOrientation)2003 inline void RotatePixelMap(std::shared_ptr<Media::PixelMap> pixelMap, const std::string& exifOrientation)
2004 {
2005     float degree = TransExifOrientationToDegree(exifOrientation);
2006     if (pixelMap) {
2007         MEDIA_INFO_LOG("RotatePicture degree is %{public}f", degree);
2008         pixelMap->rotate(degree);
2009     } else {
2010         MEDIA_ERR_LOG("RotatePicture Failed pixelMap is nullptr");
2011     }
2012 }
2013 
GetAndSetExifOrientation(OHOS::Media::ImageMetadata * exifData)2014 std::string GetAndSetExifOrientation(OHOS::Media::ImageMetadata* exifData)
2015 {
2016     std::string orientation = "";
2017     if (exifData != nullptr) {
2018         exifData->GetValue("Orientation", orientation);
2019         std::string defalutExifOrientation = "1";
2020         exifData->SetValue("Orientation", defalutExifOrientation);
2021         MEDIA_INFO_LOG("GetExifOrientation orientation:%{public}s", orientation.c_str());
2022     } else {
2023         MEDIA_ERR_LOG("GetExifOrientation exifData is nullptr");
2024     }
2025     return orientation;
2026 }
2027 
RotatePicture(std::shared_ptr<Media::Picture> picture)2028 void RotatePicture(std::shared_ptr<Media::Picture> picture)
2029 {
2030     std::string orientation = GetAndSetExifOrientation(
2031         reinterpret_cast<OHOS::Media::ImageMetadata*>(picture->GetExifMetadata().get()));
2032     RotatePixelMap(picture->GetMainPixel(), orientation);
2033     auto gainMap = picture->GetAuxiliaryPicture(Media::AuxiliaryPictureType::GAINMAP);
2034     if (gainMap) {
2035         RotatePixelMap(gainMap->GetContentPixel(), orientation);
2036     }
2037     auto depthMap = picture->GetAuxiliaryPicture(Media::AuxiliaryPictureType::DEPTH_MAP);
2038     if (depthMap) {
2039         RotatePixelMap(depthMap->GetContentPixel(), orientation);
2040     }
2041 }
2042 
CreateMediaLibrary(std::unique_ptr<Media::Picture> picture,sptr<CameraPhotoProxy> & photoProxy,std::string & uri,int32_t & cameraShotType,std::string & burstKey,int64_t timestamp)2043 int32_t HCaptureSession::CreateMediaLibrary(std::unique_ptr<Media::Picture> picture, sptr<CameraPhotoProxy> &photoProxy,
2044     std::string &uri, int32_t &cameraShotType, std::string &burstKey, int64_t timestamp)
2045 {
2046     constexpr int32_t movingPhotoShotType = 2;
2047     constexpr int32_t imageShotType = 0;
2048     cameraShotType = isSetMotionPhoto_ ? movingPhotoShotType : imageShotType;
2049     MessageParcel data;
2050     photoProxy->WriteToParcel(data);
2051     photoProxy->CameraFreeBufferHandle();
2052     sptr<CameraServerPhotoProxy> cameraPhotoProxy = new CameraServerPhotoProxy();
2053     cameraPhotoProxy->ReadFromParcel(data);
2054     PhotoFormat photoFormat = cameraPhotoProxy->GetFormat();
2055     std::string formatSuffix = photoFormat == PhotoFormat::HEIF ? suffixHeif : suffixJpeg;
2056     cameraPhotoProxy->SetDisplayName(CreateDisplayName(formatSuffix));
2057     int32_t captureId = cameraPhotoProxy->GetCaptureId();
2058     bool isBursting = false;
2059     CameraReportDfxUtils::GetInstance()->SetPrepareProxyEndInfo(captureId);
2060     CameraReportDfxUtils::GetInstance()->SetAddProxyStartInfo(captureId);
2061     SetCameraPhotoProxyInfo(cameraPhotoProxy, cameraShotType, isBursting, burstKey);
2062     GetPhotoAssetProxy getPhotoAssetProxy = (GetPhotoAssetProxy)(CameraDynamicLoader::GetInstance()->GetFunction(
2063         MEDIA_LIB_SO, "createPhotoAssetIntf"));
2064     PhotoAssetIntf* photoAssetProxy = getPhotoAssetProxy(cameraShotType, IPCSkeleton::GetCallingUid());
2065     photoAssetProxy->AddPhotoProxy((sptr<PhotoProxy>&)cameraPhotoProxy);
2066     uri = photoAssetProxy->GetPhotoAssetUri();
2067     std::shared_ptr<Media::Picture> picturePtr(picture.release());
2068     if (!isBursting && picturePtr) {
2069         RotatePicture(picturePtr);
2070     }
2071     DeferredProcessing::DeferredProcessingService::GetInstance().
2072         NotifyLowQualityImage(photoAssetProxy->GetUserId(), uri, picturePtr);
2073     if (!isBursting && isSetMotionPhoto_) {
2074         int32_t videoFd = photoAssetProxy->GetVideoFd();
2075         MEDIA_DEBUG_LOG("videFd:%{public}d", videoFd);
2076         if (taskManager_) {
2077             taskManager_->SetVideoFd(timestamp, photoAssetProxy, captureId);
2078         }
2079     } else {
2080         delete photoAssetProxy;
2081     }
2082     CameraReportDfxUtils::GetInstance()->SetAddProxyEndInfo(captureId);
2083     return CAMERA_OK;
2084 }
2085 
SetFeatureMode(int32_t featureMode)2086 int32_t HCaptureSession::SetFeatureMode(int32_t featureMode)
2087 {
2088     MEDIA_INFO_LOG("SetFeatureMode is called!");
2089     featureMode_ = featureMode;
2090     return CAMERA_OK;
2091 }
2092 
OnCaptureStarted(int32_t captureId,const std::vector<int32_t> & streamIds)2093 int32_t StreamOperatorCallback::OnCaptureStarted(int32_t captureId, const std::vector<int32_t>& streamIds)
2094 {
2095     MEDIA_INFO_LOG("StreamOperatorCallback::OnCaptureStarted captureId:%{public}d, streamIds:%{public}s", captureId,
2096         Container2String(streamIds.begin(), streamIds.end()).c_str());
2097     std::lock_guard<std::mutex> lock(cbMutex_);
2098     for (auto& streamId : streamIds) {
2099         sptr<HStreamCommon> curStream = GetHdiStreamByStreamID(streamId);
2100         if (curStream == nullptr) {
2101             MEDIA_ERR_LOG("StreamOperatorCallback::OnCaptureStarted StreamId: %{public}d not found", streamId);
2102             return CAMERA_INVALID_ARG;
2103         } else if (curStream->GetStreamType() == StreamType::REPEAT) {
2104             CastStream<HStreamRepeat>(curStream)->OnFrameStarted();
2105             CameraReportUtils::GetInstance().SetOpenCamPerfEndInfo();
2106             CameraReportUtils::GetInstance().SetModeChangePerfEndInfo();
2107             CameraReportUtils::GetInstance().SetSwitchCamPerfEndInfo();
2108         } else if (curStream->GetStreamType() == StreamType::CAPTURE) {
2109             CastStream<HStreamCapture>(curStream)->OnCaptureStarted(captureId);
2110         }
2111     }
2112     return CAMERA_OK;
2113 }
2114 
StartRecord(uint64_t timestamp,int32_t rotation,int32_t captureId)2115 void HCaptureSession::StartRecord(uint64_t timestamp, int32_t rotation, int32_t captureId)
2116 {
2117     if (isSetMotionPhoto_) {
2118         taskManager_->SubmitTask([this, timestamp, rotation, captureId]() {
2119             this->StartOnceRecord(timestamp, rotation, captureId);
2120         });
2121     }
2122 }
2123 
SessionDrainImageCallback(std::vector<sptr<FrameRecord>> & frameCacheList,wptr<MovingPhotoListener> listener,wptr<MovingPhotoVideoCache> cache,uint64_t timestamp,int32_t rotation,int32_t captureId)2124 SessionDrainImageCallback::SessionDrainImageCallback(std::vector<sptr<FrameRecord>>& frameCacheList,
2125                                                      wptr<MovingPhotoListener> listener,
2126                                                      wptr<MovingPhotoVideoCache> cache,
2127                                                      uint64_t timestamp,
2128                                                      int32_t rotation,
2129                                                      int32_t captureId)
2130     : frameCacheList_(frameCacheList), listener_(listener), videoCache_(cache), timestamp_(timestamp),
2131       rotation_(rotation), captureId_(captureId)
2132 {
2133 }
2134 
~SessionDrainImageCallback()2135 SessionDrainImageCallback::~SessionDrainImageCallback()
2136 {
2137     MEDIA_INFO_LOG("~SessionDrainImageCallback enter");
2138 }
2139 
OnDrainImage(sptr<FrameRecord> frame)2140 void SessionDrainImageCallback::OnDrainImage(sptr<FrameRecord> frame)
2141 {
2142     MEDIA_INFO_LOG("OnDrainImage enter");
2143     {
2144         std::lock_guard<std::mutex> lock(mutex_);
2145         frameCacheList_.push_back(frame);
2146     }
2147     auto videoCache = videoCache_.promote();
2148     if (frame->IsIdle() && videoCache) {
2149         videoCache->CacheFrame(frame);
2150     } else if (frame->IsFinishCache() && videoCache) {
2151         videoCache->OnImageEncoded(frame, frame->IsEncoded());
2152     } else if (frame->IsReadyConvert()) {
2153         MEDIA_DEBUG_LOG("frame is ready convert");
2154     } else {
2155         MEDIA_INFO_LOG("videoCache and frame is not useful");
2156     }
2157 }
2158 
OnDrainImageFinish(bool isFinished)2159 void SessionDrainImageCallback::OnDrainImageFinish(bool isFinished)
2160 {
2161     MEDIA_INFO_LOG("OnDrainImageFinish enter");
2162     auto videoCache = videoCache_.promote();
2163     if (videoCache) {
2164         std::lock_guard<std::mutex> lock(mutex_);
2165         videoCache_->GetFrameCachedResult(
2166             frameCacheList_,
2167             [videoCache](const std::vector<sptr<FrameRecord>>& frameRecords,
2168                          uint64_t timestamp,
2169                          int32_t rotation,
2170                          int32_t captureId) { videoCache->DoMuxerVideo(frameRecords, timestamp, rotation, captureId); },
2171             timestamp_,
2172             rotation_,
2173             captureId_);
2174     }
2175     auto listener = listener_.promote();
2176     if (listener && isFinished) {
2177         listener->RemoveDrainImageManager(this);
2178     }
2179 }
2180 
StartOnceRecord(uint64_t timestamp,int32_t rotation,int32_t captureId)2181 void HCaptureSession::StartOnceRecord(uint64_t timestamp, int32_t rotation, int32_t captureId)
2182 {
2183     MEDIA_INFO_LOG("StartOnceRecord enter");
2184     // frameCacheList only used by now thread
2185     std::lock_guard<std::mutex> lock(movingPhotoStatusLock_);
2186     std::vector<sptr<FrameRecord>> frameCacheList;
2187     sptr<SessionDrainImageCallback> imageCallback = new SessionDrainImageCallback(frameCacheList,
2188         livephotoListener_, videoCache_, timestamp, rotation, captureId);
2189     livephotoListener_->ClearCache(timestamp);
2190     livephotoListener_->DrainOutImage(imageCallback);
2191     MEDIA_INFO_LOG("StartOnceRecord end");
2192 }
2193 
OnCaptureStarted_V1_2(int32_t captureId,const std::vector<OHOS::HDI::Camera::V1_2::CaptureStartedInfo> & infos)2194 int32_t StreamOperatorCallback::OnCaptureStarted_V1_2(
2195     int32_t captureId, const std::vector<OHOS::HDI::Camera::V1_2::CaptureStartedInfo>& infos)
2196 {
2197     MEDIA_INFO_LOG("StreamOperatorCallback::OnCaptureStarted_V1_2 captureId:%{public}d", captureId);
2198     std::lock_guard<std::mutex> lock(cbMutex_);
2199     for (auto& captureInfo : infos) {
2200         sptr<HStreamCommon> curStream = GetHdiStreamByStreamID(captureInfo.streamId_);
2201         if (curStream == nullptr) {
2202             MEDIA_ERR_LOG("StreamOperatorCallback::OnCaptureStarted_V1_2 StreamId: %{public}d not found."
2203                           " exposureTime: %{public}u",
2204                 captureInfo.streamId_, captureInfo.exposureTime_);
2205             return CAMERA_INVALID_ARG;
2206         } else if (curStream->GetStreamType() == StreamType::CAPTURE) {
2207             MEDIA_DEBUG_LOG("StreamOperatorCallback::OnCaptureStarted_V1_2 StreamId: %{public}d."
2208                             " exposureTime: %{public}u",
2209                 captureInfo.streamId_, captureInfo.exposureTime_);
2210             CastStream<HStreamCapture>(curStream)->OnCaptureStarted(captureId, captureInfo.exposureTime_);
2211         }
2212     }
2213     return CAMERA_OK;
2214 }
2215 
OnCaptureEnded(int32_t captureId,const std::vector<CaptureEndedInfo> & infos)2216 int32_t StreamOperatorCallback::OnCaptureEnded(int32_t captureId, const std::vector<CaptureEndedInfo>& infos)
2217 {
2218     MEDIA_INFO_LOG("StreamOperatorCallback::OnCaptureEnded");
2219     std::lock_guard<std::mutex> lock(cbMutex_);
2220     for (auto& captureInfo : infos) {
2221         sptr<HStreamCommon> curStream = GetHdiStreamByStreamID(captureInfo.streamId_);
2222         if (curStream == nullptr) {
2223             MEDIA_ERR_LOG("StreamOperatorCallback::OnCaptureEnded StreamId: %{public}d not found."
2224                           " Framecount: %{public}d",
2225                 captureInfo.streamId_, captureInfo.frameCount_);
2226             return CAMERA_INVALID_ARG;
2227         } else if (curStream->GetStreamType() == StreamType::REPEAT) {
2228             CastStream<HStreamRepeat>(curStream)->OnFrameEnded(captureInfo.frameCount_);
2229         } else if (curStream->GetStreamType() == StreamType::CAPTURE) {
2230             CastStream<HStreamCapture>(curStream)->OnCaptureEnded(captureId, captureInfo.frameCount_);
2231         }
2232     }
2233     return CAMERA_OK;
2234 }
2235 
OnCaptureEndedExt(int32_t captureId,const std::vector<OHOS::HDI::Camera::V1_3::CaptureEndedInfoExt> & infos)2236 int32_t StreamOperatorCallback::OnCaptureEndedExt(int32_t captureId,
2237     const std::vector<OHOS::HDI::Camera::V1_3::CaptureEndedInfoExt>& infos)
2238 {
2239     MEDIA_INFO_LOG("StreamOperatorCallback::OnCaptureEndedExt captureId:%{public}d", captureId);
2240     std::lock_guard<std::mutex> lock(cbMutex_);
2241     for (auto& captureInfo : infos) {
2242         sptr<HStreamCommon> curStream = GetHdiStreamByStreamID(captureInfo.streamId_);
2243         if (curStream == nullptr) {
2244             MEDIA_ERR_LOG("StreamOperatorCallback::OnCaptureEndedExt StreamId: %{public}d not found."
2245                           " Framecount: %{public}d",
2246                 captureInfo.streamId_, captureInfo.frameCount_);
2247             return CAMERA_INVALID_ARG;
2248         } else if (curStream->GetStreamType() == StreamType::REPEAT) {
2249             CastStream<HStreamRepeat>(curStream)->OnFrameEnded(captureInfo.frameCount_);
2250             CaptureEndedInfoExt extInfo;
2251             extInfo.streamId = captureInfo.streamId_;
2252             extInfo.frameCount = captureInfo.frameCount_;
2253             extInfo.isDeferredVideoEnhancementAvailable = captureInfo.isDeferredVideoEnhancementAvailable_;
2254             extInfo.videoId = captureInfo.videoId_;
2255             MEDIA_INFO_LOG("StreamOperatorCallback::OnCaptureEndedExt captureId:%{public}d videoId:%{public}s "
2256                            "isDeferredVideo:%{public}d",
2257                 captureId, extInfo.videoId.c_str(), extInfo.isDeferredVideoEnhancementAvailable);
2258             CastStream<HStreamRepeat>(curStream)->OnDeferredVideoEnhancementInfo(extInfo);
2259         }
2260     }
2261     return CAMERA_OK;
2262 }
2263 
OnCaptureError(int32_t captureId,const std::vector<CaptureErrorInfo> & infos)2264 int32_t StreamOperatorCallback::OnCaptureError(int32_t captureId, const std::vector<CaptureErrorInfo>& infos)
2265 {
2266     MEDIA_INFO_LOG("StreamOperatorCallback::OnCaptureError");
2267     std::lock_guard<std::mutex> lock(cbMutex_);
2268     for (auto& errInfo : infos) {
2269         sptr<HStreamCommon> curStream = GetHdiStreamByStreamID(errInfo.streamId_);
2270         if (curStream == nullptr) {
2271             MEDIA_ERR_LOG("StreamOperatorCallback::OnCaptureError StreamId: %{public}d not found."
2272                           " Error: %{public}d",
2273                 errInfo.streamId_, errInfo.error_);
2274             return CAMERA_INVALID_ARG;
2275         } else if (curStream->GetStreamType() == StreamType::REPEAT) {
2276             CastStream<HStreamRepeat>(curStream)->OnFrameError(errInfo.error_);
2277         } else if (curStream->GetStreamType() == StreamType::CAPTURE) {
2278             auto captureStream = CastStream<HStreamCapture>(curStream);
2279             captureStream->rotationMap_.Erase(captureId);
2280             captureStream->OnCaptureError(captureId, errInfo.error_);
2281         }
2282     }
2283     return CAMERA_OK;
2284 }
2285 
OnFrameShutter(int32_t captureId,const std::vector<int32_t> & streamIds,uint64_t timestamp)2286 int32_t StreamOperatorCallback::OnFrameShutter(
2287     int32_t captureId, const std::vector<int32_t>& streamIds, uint64_t timestamp)
2288 {
2289     MEDIA_INFO_LOG("StreamOperatorCallback::OnFrameShutter ts is:%{public}" PRIu64, timestamp);
2290     std::lock_guard<std::mutex> lock(cbMutex_);
2291     for (auto& streamId : streamIds) {
2292         sptr<HStreamCommon> curStream = GetHdiStreamByStreamID(streamId);
2293         if ((curStream != nullptr) && (curStream->GetStreamType() == StreamType::CAPTURE)) {
2294             auto captureStream = CastStream<HStreamCapture>(curStream);
2295             int32_t rotation = 0;
2296             captureStream->rotationMap_.Find(captureId, rotation);
2297             StartMovingPhotoEncode(rotation, timestamp, captureStream->format_, captureId);
2298             captureStream->OnFrameShutter(captureId, timestamp);
2299         } else {
2300             MEDIA_ERR_LOG("StreamOperatorCallback::OnFrameShutter StreamId: %{public}d not found", streamId);
2301             return CAMERA_INVALID_ARG;
2302         }
2303     }
2304     return CAMERA_OK;
2305 }
2306 
OnFrameShutterEnd(int32_t captureId,const std::vector<int32_t> & streamIds,uint64_t timestamp)2307 int32_t StreamOperatorCallback::OnFrameShutterEnd(
2308     int32_t captureId, const std::vector<int32_t>& streamIds, uint64_t timestamp)
2309 {
2310     MEDIA_INFO_LOG("StreamOperatorCallback::OnFrameShutterEnd ts is:%{public}" PRIu64, timestamp);
2311     std::lock_guard<std::mutex> lock(cbMutex_);
2312     for (auto& streamId : streamIds) {
2313         sptr<HStreamCommon> curStream = GetHdiStreamByStreamID(streamId);
2314         if ((curStream != nullptr) && (curStream->GetStreamType() == StreamType::CAPTURE)) {
2315             auto captureStream = CastStream<HStreamCapture>(curStream);
2316             captureStream->rotationMap_.Erase(captureId);
2317             captureStream->OnFrameShutterEnd(captureId, timestamp);
2318         } else {
2319             MEDIA_ERR_LOG("StreamOperatorCallback::OnFrameShutterEnd StreamId: %{public}d not found", streamId);
2320             return CAMERA_INVALID_ARG;
2321         }
2322     }
2323     return CAMERA_OK;
2324 }
2325 
OnCaptureReady(int32_t captureId,const std::vector<int32_t> & streamIds,uint64_t timestamp)2326 int32_t StreamOperatorCallback::OnCaptureReady(
2327     int32_t captureId, const std::vector<int32_t>& streamIds, uint64_t timestamp)
2328 {
2329     MEDIA_DEBUG_LOG("StreamOperatorCallback::OnCaptureReady");
2330     std::lock_guard<std::mutex> lock(cbMutex_);
2331     for (auto& streamId : streamIds) {
2332         sptr<HStreamCommon> curStream = GetHdiStreamByStreamID(streamId);
2333         if ((curStream != nullptr) && (curStream->GetStreamType() == StreamType::CAPTURE)) {
2334             CastStream<HStreamCapture>(curStream)->OnCaptureReady(captureId, timestamp);
2335         } else {
2336             MEDIA_ERR_LOG("StreamOperatorCallback::OnCaptureReady StreamId: %{public}d not found", streamId);
2337             return CAMERA_INVALID_ARG;
2338         }
2339     }
2340     return CAMERA_OK;
2341 }
2342 
OnResult(int32_t streamId,const std::vector<uint8_t> & result)2343 int32_t StreamOperatorCallback::OnResult(int32_t streamId, const std::vector<uint8_t>& result)
2344 {
2345     MEDIA_DEBUG_LOG("StreamOperatorCallback::OnResult");
2346     sptr<HStreamCommon> curStream;
2347     const int32_t metaStreamId = -1;
2348     if (streamId == metaStreamId) {
2349         curStream = GetStreamByStreamID(streamId);
2350     } else {
2351         curStream = GetHdiStreamByStreamID(streamId);
2352     }
2353     if ((curStream != nullptr) && (curStream->GetStreamType() == StreamType::METADATA)) {
2354         CastStream<HStreamMetadata>(curStream)->OnMetaResult(streamId, result);
2355     } else {
2356         MEDIA_ERR_LOG("StreamOperatorCallback::OnResult StreamId: %{public}d is null or not Not adapted", streamId);
2357         return CAMERA_INVALID_ARG;
2358     }
2359     return CAMERA_OK;
2360 }
2361 
StateMachine()2362 StateMachine::StateMachine()
2363 {
2364     stateTransferMap_[static_cast<uint32_t>(CaptureSessionState::SESSION_INIT)] = {
2365         CaptureSessionState::SESSION_CONFIG_INPROGRESS, CaptureSessionState::SESSION_RELEASED
2366     };
2367 
2368     stateTransferMap_[static_cast<uint32_t>(CaptureSessionState::SESSION_CONFIG_INPROGRESS)] = {
2369         CaptureSessionState::SESSION_CONFIG_COMMITTED, CaptureSessionState::SESSION_RELEASED
2370     };
2371 
2372     stateTransferMap_[static_cast<uint32_t>(CaptureSessionState::SESSION_CONFIG_COMMITTED)] = {
2373         CaptureSessionState::SESSION_CONFIG_INPROGRESS, CaptureSessionState::SESSION_STARTED,
2374         CaptureSessionState::SESSION_RELEASED
2375     };
2376 
2377     stateTransferMap_[static_cast<uint32_t>(CaptureSessionState::SESSION_STARTED)] = {
2378         CaptureSessionState::SESSION_CONFIG_INPROGRESS, CaptureSessionState::SESSION_CONFIG_COMMITTED,
2379         CaptureSessionState::SESSION_RELEASED
2380     };
2381 
2382     stateTransferMap_[static_cast<uint32_t>(CaptureSessionState::SESSION_RELEASED)] = {};
2383 }
2384 
CheckTransfer(CaptureSessionState targetState)2385 bool StateMachine::CheckTransfer(CaptureSessionState targetState)
2386 {
2387     std::lock_guard<std::recursive_mutex> lock(sessionStateLock_);
2388     return any_of(stateTransferMap_[static_cast<uint32_t>(currentState_)].begin(),
2389         stateTransferMap_[static_cast<uint32_t>(currentState_)].end(),
2390         [&targetState](const auto& state) {return state == targetState; });
2391 }
2392 
Transfer(CaptureSessionState targetState)2393 bool StateMachine::Transfer(CaptureSessionState targetState)
2394 {
2395     std::lock_guard<std::recursive_mutex> lock(sessionStateLock_);
2396     if (CheckTransfer(targetState)) {
2397         currentState_ = targetState;
2398         return true;
2399     }
2400     return false;
2401 }
2402 
AddStream(sptr<HStreamCommon> stream)2403 bool StreamContainer::AddStream(sptr<HStreamCommon> stream)
2404 {
2405     std::lock_guard<std::mutex> lock(streamsLock_);
2406     auto& list = streams_[stream->GetStreamType()];
2407     auto it = std::find_if(list.begin(), list.end(), [stream](auto item) { return item == stream; });
2408     if (it == list.end()) {
2409         list.emplace_back(stream);
2410         return true;
2411     }
2412     return false;
2413 }
2414 
RemoveStream(sptr<HStreamCommon> stream)2415 bool StreamContainer::RemoveStream(sptr<HStreamCommon> stream)
2416 {
2417     std::lock_guard<std::mutex> lock(streamsLock_);
2418     auto& list = streams_[stream->GetStreamType()];
2419     auto it = std::find_if(list.begin(), list.end(), [stream](auto item) { return item == stream; });
2420     if (it == list.end()) {
2421         return false;
2422     }
2423     list.erase(it);
2424     return true;
2425 }
2426 
GetStream(int32_t streamId)2427 sptr<HStreamCommon> StreamContainer::GetStream(int32_t streamId)
2428 {
2429     std::lock_guard<std::mutex> lock(streamsLock_);
2430     for (auto& pair : streams_) {
2431         for (auto& stream : pair.second) {
2432             if (stream->GetFwkStreamId() == streamId) {
2433                 return stream;
2434             }
2435         }
2436     }
2437     return nullptr;
2438 }
2439 
GetHdiStream(int32_t streamId)2440 sptr<HStreamCommon> StreamContainer::GetHdiStream(int32_t streamId)
2441 {
2442     std::lock_guard<std::mutex> lock(streamsLock_);
2443     for (auto& pair : streams_) {
2444         for (auto& stream : pair.second) {
2445             if (stream->GetHdiStreamId() == streamId) {
2446                 return stream;
2447             }
2448         }
2449     }
2450     return nullptr;
2451 }
2452 
Clear()2453 void StreamContainer::Clear()
2454 {
2455     std::lock_guard<std::mutex> lock(streamsLock_);
2456     streams_.clear();
2457 }
2458 
Size()2459 size_t StreamContainer::Size()
2460 {
2461     std::lock_guard<std::mutex> lock(streamsLock_);
2462     size_t totalSize = 0;
2463     for (auto& pair : streams_) {
2464         totalSize += pair.second.size();
2465     }
2466     return totalSize;
2467 }
2468 
GetStreams(const StreamType streamType)2469 std::list<sptr<HStreamCommon>> StreamContainer::GetStreams(const StreamType streamType)
2470 {
2471     std::lock_guard<std::mutex> lock(streamsLock_);
2472     std::list<sptr<HStreamCommon>> totalOrderedStreams;
2473     for (auto& stream : streams_[streamType]) {
2474         auto insertPos = std::find_if(totalOrderedStreams.begin(), totalOrderedStreams.end(),
2475             [&stream](auto& it) { return stream->GetFwkStreamId() <= it->GetFwkStreamId(); });
2476         totalOrderedStreams.emplace(insertPos, stream);
2477     }
2478     return totalOrderedStreams;
2479 }
2480 
GetAllStreams()2481 std::list<sptr<HStreamCommon>> StreamContainer::GetAllStreams()
2482 {
2483     std::lock_guard<std::mutex> lock(streamsLock_);
2484     std::list<sptr<HStreamCommon>> totalOrderedStreams;
2485     for (auto& pair : streams_) {
2486         for (auto& stream : pair.second) {
2487             auto insertPos = std::find_if(totalOrderedStreams.begin(), totalOrderedStreams.end(),
2488                 [&stream](auto& it) { return stream->GetFwkStreamId() <= it->GetFwkStreamId(); });
2489             totalOrderedStreams.emplace(insertPos, stream);
2490         }
2491     }
2492     return totalOrderedStreams;
2493 }
2494 
MovingPhotoListener(sptr<MovingPhotoSurfaceWrapper> surfaceWrapper,sptr<Surface> metaSurface,shared_ptr<FixedSizeList<MetaElementType>> metaCache,uint32_t preCacheFrameCount,uint32_t postCacheFrameCount)2495 MovingPhotoListener::MovingPhotoListener(sptr<MovingPhotoSurfaceWrapper> surfaceWrapper, sptr<Surface> metaSurface,
2496     shared_ptr<FixedSizeList<MetaElementType>> metaCache, uint32_t preCacheFrameCount, uint32_t postCacheFrameCount)
2497     : movingPhotoSurfaceWrapper_(surfaceWrapper),
2498       metaSurface_(metaSurface),
2499       metaCache_(metaCache),
2500       recorderBufferQueue_("videoBuffer", preCacheFrameCount),
2501       postCacheFrameCount_(postCacheFrameCount)
2502 {
2503     shutterTime_ = 0;
2504 }
2505 
~MovingPhotoListener()2506 MovingPhotoListener::~MovingPhotoListener()
2507 {
2508     recorderBufferQueue_.SetActive(false);
2509     metaCache_->clear();
2510     recorderBufferQueue_.Clear();
2511     MEDIA_ERR_LOG("HStreamRepeat::LivePhotoListener ~ end");
2512 }
2513 
RemoveDrainImageManager(sptr<SessionDrainImageCallback> callback)2514 void MovingPhotoListener::RemoveDrainImageManager(sptr<SessionDrainImageCallback> callback)
2515 {
2516     callbackMap_.Erase(callback);
2517     MEDIA_INFO_LOG("RemoveDrainImageManager drainImageManagerVec_ Start %d", callbackMap_.Size());
2518 }
2519 
ClearCache(uint64_t timestamp)2520 void MovingPhotoListener::ClearCache(uint64_t timestamp)
2521 {
2522     if (!isNeededClear_.load()) {
2523         return;
2524     }
2525     MEDIA_INFO_LOG("ClearCache enter");
2526     shutterTime_ = static_cast<int64_t>(timestamp);
2527     while (!recorderBufferQueue_.Empty()) {
2528         sptr<FrameRecord> popFrame = recorderBufferQueue_.Front();
2529         MEDIA_DEBUG_LOG("surface_ release surface buffer %{public}llu, timestamp %{public}llu",
2530             (long long unsigned)popFrame->GetTimeStamp(), (long long unsigned)timestamp);
2531         if (popFrame->GetTimeStamp() > shutterTime_) {
2532             isNeededClear_ = false;
2533             MEDIA_INFO_LOG("ClearCache end");
2534             return;
2535         }
2536         recorderBufferQueue_.Pop();
2537         popFrame->ReleaseSurfaceBuffer(movingPhotoSurfaceWrapper_);
2538     }
2539     isNeededPop_ = true;
2540 }
2541 
SetClearFlag()2542 void MovingPhotoListener::SetClearFlag()
2543 {
2544     MEDIA_INFO_LOG("need clear cache!");
2545     isNeededClear_ = true;
2546 }
2547 
StopDrainOut()2548 void MovingPhotoListener::StopDrainOut()
2549 {
2550     MEDIA_INFO_LOG("StopDrainOut drainImageManagerVec_ Start %d", callbackMap_.Size());
2551     callbackMap_.Iterate([](const sptr<SessionDrainImageCallback> callback, sptr<DrainImageManager> manager) {
2552         manager->DrainFinish(false);
2553     });
2554     callbackMap_.Clear();
2555 }
2556 
OnBufferArrival(sptr<SurfaceBuffer> buffer,int64_t timestamp,GraphicTransformType transform)2557 void MovingPhotoListener::OnBufferArrival(sptr<SurfaceBuffer> buffer, int64_t timestamp, GraphicTransformType transform)
2558 {
2559     MEDIA_DEBUG_LOG("OnBufferArrival timestamp %{public}llu", (long long unsigned)timestamp);
2560     if (recorderBufferQueue_.Full()) {
2561         MEDIA_DEBUG_LOG("surface_ release surface buffer");
2562         sptr<FrameRecord> popFrame = recorderBufferQueue_.Pop();
2563         popFrame->ReleaseSurfaceBuffer(movingPhotoSurfaceWrapper_);
2564         popFrame->ReleaseMetaBuffer(metaSurface_, true);
2565         MEDIA_DEBUG_LOG("surface_ release surface buffer: %{public}s, refCount: %{public}d",
2566             popFrame->GetFrameId().c_str(), popFrame->GetSptrRefCount());
2567     }
2568     MEDIA_DEBUG_LOG("surface_ push buffer %{public}d x %{public}d, stride is %{public}d",
2569         buffer->GetSurfaceBufferWidth(), buffer->GetSurfaceBufferHeight(), buffer->GetStride());
2570     sptr<FrameRecord> frameRecord = new (std::nothrow) FrameRecord(buffer, timestamp, transform);
2571     CHECK_AND_RETURN_LOG(frameRecord != nullptr, "MovingPhotoListener::OnBufferAvailable create FrameRecord fail!");
2572     if (isNeededClear_ && isNeededPop_) {
2573         if (timestamp < shutterTime_) {
2574             frameRecord->ReleaseSurfaceBuffer(movingPhotoSurfaceWrapper_);
2575             MEDIA_INFO_LOG("Drop this frame in cache");
2576             return;
2577         } else {
2578             isNeededClear_ = false;
2579             isNeededPop_ = false;
2580             MEDIA_INFO_LOG("ClearCache end");
2581         }
2582     }
2583     recorderBufferQueue_.Push(frameRecord);
2584     auto metaPair = metaCache_->find_if([timestamp](const MetaElementType& value) {
2585         return value.first == timestamp;
2586     });
2587     if (metaPair.has_value()) {
2588         MEDIA_DEBUG_LOG("frame has meta");
2589         frameRecord->SetMetaBuffer(metaPair.value().second);
2590     }
2591     vector<sptr<SessionDrainImageCallback>> callbacks;
2592     callbackMap_.Iterate([frameRecord, &callbacks](const sptr<SessionDrainImageCallback> callback,
2593         sptr<DrainImageManager> manager) {
2594         callbacks.push_back(callback);
2595     });
2596     for (sptr<SessionDrainImageCallback> drainImageCallback : callbacks) {
2597         sptr<DrainImageManager> drainImageManager;
2598         if (callbackMap_.Find(drainImageCallback, drainImageManager)) {
2599             std::lock_guard<std::mutex> lock(drainImageManager->drainImageLock_);
2600             drainImageManager->DrainImage(frameRecord);
2601         }
2602     }
2603 }
2604 
DrainOutImage(sptr<SessionDrainImageCallback> drainImageCallback)2605 void MovingPhotoListener::DrainOutImage(sptr<SessionDrainImageCallback> drainImageCallback)
2606 {
2607     sptr<DrainImageManager> drainImageManager =
2608         new DrainImageManager(drainImageCallback, recorderBufferQueue_.Size() + postCacheFrameCount_);
2609     {
2610         MEDIA_INFO_LOG("DrainOutImage enter %{public}zu", recorderBufferQueue_.Size());
2611         callbackMap_.Insert(drainImageCallback, drainImageManager);
2612     }
2613     // Convert recorderBufferQueue_ to a vector
2614     std::vector<sptr<FrameRecord>> frameList = recorderBufferQueue_.GetAllElements();
2615     if (!frameList.empty()) {
2616         frameList.back()->SetCoverFrame();
2617     }
2618     std::lock_guard<std::mutex> lock(drainImageManager->drainImageLock_);
2619     for (const auto& frame : frameList) {
2620         MEDIA_DEBUG_LOG("DrainOutImage enter DrainImage");
2621         drainImageManager->DrainImage(frame);
2622     }
2623 }
2624 
OnBufferAvailable()2625 void MovingPhotoMetaListener::OnBufferAvailable()
2626 {
2627     MEDIA_DEBUG_LOG("metaSurface_ OnBufferAvailable %{public}u", surface_->GetQueueSize());
2628     if (!surface_) {
2629         MEDIA_ERR_LOG("streamRepeat surface is null");
2630         return;
2631     }
2632     int64_t timestamp;
2633     OHOS::Rect damage;
2634     sptr<SurfaceBuffer> buffer;
2635     sptr<SyncFence> syncFence = SyncFence::INVALID_FENCE;
2636     SurfaceError surfaceRet = surface_->AcquireBuffer(buffer, syncFence, timestamp, damage);
2637     if (surfaceRet != SURFACE_ERROR_OK) {
2638         MEDIA_ERR_LOG("Failed to acquire meta surface buffer");
2639         return;
2640     }
2641     surfaceRet = surface_->DetachBufferFromQueue(buffer);
2642     if (surfaceRet != SURFACE_ERROR_OK) {
2643         MEDIA_ERR_LOG("Failed to detach meta buffer. %{public}d", surfaceRet);
2644         return;
2645     }
2646     metaCache_->add({timestamp, buffer});
2647 }
2648 
MovingPhotoMetaListener(sptr<Surface> surface,shared_ptr<FixedSizeList<MetaElementType>> metaCache)2649 MovingPhotoMetaListener::MovingPhotoMetaListener(sptr<Surface> surface,
2650     shared_ptr<FixedSizeList<MetaElementType>> metaCache)
2651     : surface_(surface), metaCache_(metaCache)
2652 {
2653 }
2654 
~MovingPhotoMetaListener()2655 MovingPhotoMetaListener::~MovingPhotoMetaListener()
2656 {
2657     MEDIA_ERR_LOG("HStreamRepeat::MovingPhotoMetaListener ~ end");
2658 }
2659 } // namespace CameraStandard
2660 } // namespace OHOS
2661