• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef OHOS_CAMERA_H_CAPTURE_SESSION_H
17 #define OHOS_CAMERA_H_CAPTURE_SESSION_H
18 #define EXPORT_API __attribute__((visibility("default")))
19 
20 #include <atomic>
21 #include <cstdint>
22 #include <functional>
23 #include <iostream>
24 #include <list>
25 #include <memory>
26 #include <mutex>
27 #include <refbase.h>
28 #include <unordered_map>
29 #include <unordered_set>
30 #include "camera_util.h"
31 #include "camera_dynamic_loader.h"
32 #include "fixed_size_list.h"
33 #include "camera_dynamic_loader.h"
34 #include "hcamera_device.h"
35 #include "hcapture_session_stub.h"
36 #include "hstream_capture.h"
37 #include "hstream_metadata.h"
38 #include "hstream_repeat.h"
39 #include "icapture_session.h"
40 #include "istream_common.h"
41 #include "camera_photo_proxy.h"
42 #include "moving_photo/moving_photo_surface_wrapper.h"
43 #include "surface.h"
44 #include "v1_0/istream_operator.h"
45 #include "v1_1/istream_operator.h"
46 #include "v1_2/istream_operator.h"
47 #include "v1_3/istream_operator_callback.h"
48 #include "hcamera_restore_param.h"
49 #include "iconsumer_surface.h"
50 #include "blocking_queue.h"
51 #include "audio_capturer.h"
52 #include "audio_info.h"
53 #include "avcodec_task_manager.h"
54 #include "moving_photo_video_cache.h"
55 #include "drain_manager.h"
56 #include "audio_capturer_session.h"
57 #include "safe_map.h"
58 #ifdef CAMERA_USE_SENSOR
59 #include "sensor_agent.h"
60 #include "sensor_agent_type.h"
61 #endif
62 namespace OHOS::Media {
63     class Picture;
64 }
65 namespace OHOS {
66 namespace CameraStandard {
67 using OHOS::HDI::Camera::V1_0::CaptureEndedInfo;
68 using OHOS::HDI::Camera::V1_0::CaptureErrorInfo;
69 using namespace AudioStandard;
70 using namespace std::chrono;
71 using namespace DeferredProcessing;
72 using namespace Media;
73 class PermissionStatusChangeCb;
74 class CameraUseStateChangeCb;
75 class DisplayRotationListener;
76 class CameraServerPhotoProxy;
77 
78 static const int32_t STREAM_NOT_FOUNT = -1;
79 
80 enum class CaptureSessionReleaseType : int32_t {
81     RELEASE_TYPE_CLIENT = 0,
82     RELEASE_TYPE_CLIENT_DIED,
83     RELEASE_TYPE_SECURE,
84     RELEASE_TYPE_OBJ_DIED,
85 };
86 
87 class StateMachine {
88 public:
89     explicit StateMachine();
90     virtual ~StateMachine() = default;
91     bool CheckTransfer(CaptureSessionState targetState);
92     bool Transfer(CaptureSessionState targetState);
93 
GetCurrentState()94     inline CaptureSessionState GetCurrentState()
95     {
96         std::lock_guard<std::recursive_mutex> lock(sessionStateLock_);
97         return currentState_;
98     }
99 
StateGuard(const std::function<void (const CaptureSessionState)> & fun)100     inline void StateGuard(const std::function<void(const CaptureSessionState)>& fun)
101     {
102         std::lock_guard<std::recursive_mutex> lock(sessionStateLock_);
103         fun(currentState_);
104     }
105 
IsStateNoLock(CaptureSessionState targetState)106     inline bool IsStateNoLock(CaptureSessionState targetState)
107     {
108         return currentState_ == targetState;
109     }
110 
111 private:
112     std::vector<CaptureSessionState> stateTransferMap_[static_cast<uint32_t>(CaptureSessionState::SESSION_STATE_MAX)];
113     std::recursive_mutex sessionStateLock_;
114     CaptureSessionState currentState_ = CaptureSessionState::SESSION_INIT;
115 };
116 
117 class StreamContainer {
118 public:
StreamContainer()119     StreamContainer() {};
120     virtual ~StreamContainer() = default;
121 
122     bool AddStream(sptr<HStreamCommon> stream);
123     bool RemoveStream(sptr<HStreamCommon> stream);
124     sptr<HStreamCommon> GetStream(int32_t streamId);
125     sptr<HStreamCommon> GetHdiStream(int32_t streamId);
126     void Clear();
127     size_t Size();
128 
129     std::list<sptr<HStreamCommon>> GetStreams(const StreamType streamType);
130     std::list<sptr<HStreamCommon>> GetAllStreams();
131 
132 private:
133     std::mutex streamsLock_;
134     std::map<const StreamType, std::list<sptr<HStreamCommon>>> streams_;
135 };
136 
137 class StreamOperatorCallback : public OHOS::HDI::Camera::V1_3::IStreamOperatorCallback {
138 public:
139     StreamOperatorCallback() = default;
140     virtual ~StreamOperatorCallback() = default;
141 
142     int32_t OnCaptureStarted(int32_t captureId, const std::vector<int32_t>& streamIds) override;
143     int32_t OnCaptureStarted_V1_2(
144         int32_t captureId, const std::vector<OHOS::HDI::Camera::V1_2::CaptureStartedInfo>& infos) override;
145     int32_t OnCaptureEnded(int32_t captureId, const std::vector<CaptureEndedInfo>& infos) override;
146     int32_t OnCaptureEndedExt(
147         int32_t captureId, const std::vector<OHOS::HDI::Camera::V1_3::CaptureEndedInfoExt>& infos) override;
148     int32_t OnCaptureError(int32_t captureId, const std::vector<CaptureErrorInfo>& infos) override;
149     int32_t OnFrameShutter(int32_t captureId, const std::vector<int32_t>& streamIds, uint64_t timestamp) override;
150     int32_t OnFrameShutterEnd(int32_t captureId, const std::vector<int32_t>& streamIds, uint64_t timestamp) override;
151     int32_t OnCaptureReady(int32_t captureId, const std::vector<int32_t>& streamIds, uint64_t timestamp) override;
152     int32_t OnResult(int32_t streamId, const std::vector<uint8_t>& result) override;
153 
154     virtual const sptr<HStreamCommon> GetStreamByStreamID(int32_t streamId) = 0;
155     virtual const sptr<HStreamCommon> GetHdiStreamByStreamID(int32_t streamId) = 0;
156     virtual void StartMovingPhotoEncode(int32_t rotation, uint64_t timestamp, int32_t format, int32_t captureId) = 0;
157 
158 private:
159     std::mutex cbMutex_;
160 };
161 
162 class SessionDrainImageCallback;
163 using MetaElementType = std::pair<int64_t, sptr<SurfaceBuffer>>;
164 class MovingPhotoListener : public MovingPhotoSurfaceWrapper::SurfaceBufferListener {
165 public:
166     explicit MovingPhotoListener(sptr<MovingPhotoSurfaceWrapper> surfaceWrapper, sptr<Surface> metaSurface,
167         shared_ptr<FixedSizeList<MetaElementType>> metaCache, uint32_t preCacheFrameCount,
168         uint32_t postCacheFrameCount);
169     ~MovingPhotoListener() override;
170     void OnBufferArrival(sptr<SurfaceBuffer> buffer, int64_t timestamp, GraphicTransformType transform) override;
171     void DrainOutImage(sptr<SessionDrainImageCallback> drainImageCallback);
172     void RemoveDrainImageManager(sptr<SessionDrainImageCallback> drainImageCallback);
173     void StopDrainOut();
174     void ClearCache(uint64_t timestamp);
175     void SetClearFlag();
176 
177 private:
178     sptr<MovingPhotoSurfaceWrapper> movingPhotoSurfaceWrapper_;
179     sptr<Surface> metaSurface_;
180     shared_ptr<FixedSizeList<MetaElementType>> metaCache_;
181     BlockingQueue<sptr<FrameRecord>> recorderBufferQueue_;
182     SafeMap<sptr<SessionDrainImageCallback>, sptr<DrainImageManager>> callbackMap_;
183     std::atomic<bool> isNeededClear_ { false };
184     std::atomic<bool> isNeededPop_ { false };
185     int64_t shutterTime_;
186     uint64_t postCacheFrameCount_;
187 };
188 
189 class MovingPhotoMetaListener : public IBufferConsumerListener {
190 public:
191     explicit MovingPhotoMetaListener(sptr<Surface> surface, shared_ptr<FixedSizeList<MetaElementType>> metaCache);
192     ~MovingPhotoMetaListener();
193     void OnBufferAvailable() override;
194 private:
195     sptr<Surface> surface_;
196     shared_ptr<FixedSizeList<MetaElementType>> metaCache_;
197 };
198 
199 class SessionDrainImageCallback : public DrainImageCallback {
200 public:
201     explicit SessionDrainImageCallback(std::vector<sptr<FrameRecord>>& frameCacheList,
202                                        wptr<MovingPhotoListener> listener,
203                                        wptr<MovingPhotoVideoCache> cache,
204                                        uint64_t timestamp,
205                                        int32_t rotation,
206                                        int32_t captureId);
207     ~SessionDrainImageCallback();
208     void OnDrainImage(sptr<FrameRecord> frame) override;
209     void OnDrainImageFinish(bool isFinished) override;
210 
211 private:
212     std::mutex mutex_;
213     std::vector<sptr<FrameRecord>> frameCacheList_;
214     wptr<MovingPhotoListener> listener_;
215     wptr<MovingPhotoVideoCache> videoCache_;
216     uint64_t timestamp_;
217     int32_t rotation_;
218     int32_t captureId_;
219 };
220 
221 class CameraInfoDumper;
222 
223 class EXPORT_API HCaptureSession : public HCaptureSessionStub, public StreamOperatorCallback {
224 public:
225     static sptr<HCaptureSession> NewInstance(const uint32_t callerToken, int32_t opMode);
226     HCaptureSession();
227     explicit HCaptureSession(const uint32_t callingTokenId, int32_t opMode);
228     virtual ~HCaptureSession();
229 
230     int32_t BeginConfig() override;
231     int32_t CommitConfig() override;
232 
233     int32_t CanAddInput(sptr<ICameraDeviceService> cameraDevice, bool& result) override;
234     int32_t AddInput(sptr<ICameraDeviceService> cameraDevice) override;
235     int32_t AddOutput(StreamType streamType, sptr<IStreamCommon> stream) override;
236 
237     int32_t RemoveInput(sptr<ICameraDeviceService> cameraDevice) override;
238     int32_t RemoveOutput(StreamType streamType, sptr<IStreamCommon> stream) override;
239 
240     int32_t Start() override;
241     int32_t Stop() override;
242     int32_t Release() override;
243     int32_t Release(CaptureSessionReleaseType type);
244 
245     static void DestroyStubObjectForPid(pid_t pid);
246     int32_t SetCallback(sptr<ICaptureSessionCallback>& callback) override;
247 
248     int32_t GetSessionState(CaptureSessionState& sessionState) override;
249     int32_t GetActiveColorSpace(ColorSpace& colorSpace) override;
250     int32_t SetColorSpace(ColorSpace colorSpace, ColorSpace captureColorSpace, bool isNeedUpdate) override;
251     bool QueryFpsAndZoomRatio(float& currentFps, float& currentZoomRatio);
252     bool QueryZoomPerformance(std::vector<float>& crossZoomAndTime, int32_t operationMode);
253     int32_t SetSmoothZoom(
254         int32_t smoothZoomType, int32_t operationMode, float targetZoomRatio, float& duration) override;
255     int32_t EnableMovingPhoto(bool isEnable) override;
256     pid_t GetPid();
257     int32_t GetCurrentStreamInfos(std::vector<StreamInfo_V1_1>& streamInfos);
258     int32_t GetopMode();
259 
260     int32_t OperatePermissionCheck(uint32_t interfaceCode) override;
261     int32_t EnableMovingPhotoMirror(bool isMirror) override;
262     int32_t CreateMediaLibrary(sptr<CameraPhotoProxy>& photoProxy,
263         std::string& uri, int32_t& cameraShotType, std::string& burstKey, int64_t timestamp) override;
264     int32_t CreateMediaLibrary(std::unique_ptr<Media::Picture> picture, sptr<CameraPhotoProxy> &photoProxy,
265         std::string &uri, int32_t &cameraShotType, std::string& burstKey, int64_t timestamp) override;
266     void SetCameraPhotoProxyInfo(sptr<CameraServerPhotoProxy> cameraPhotoProxy, int32_t &cameraShotType,
267         bool &isBursting, std::string &burstKey);
268     const sptr<HStreamCommon> GetStreamByStreamID(int32_t streamId) override;
269     int32_t SetFeatureMode(int32_t featureMode) override;
270     const sptr<HStreamCommon> GetHdiStreamByStreamID(int32_t streamId) override;
271     void StartMovingPhotoEncode(int32_t rotation, uint64_t timestamp, int32_t format, int32_t captureId) override;
272     void StartRecord(uint64_t timestamp, int32_t rotation, int32_t captureId);
273     void GetOutputStatus(int32_t &status);
274     int32_t SetPreviewRotation(std::string &deviceClass) override;
275 
276     void DumpSessionInfo(CameraInfoDumper& infoDumper);
277     static void DumpSessions(CameraInfoDumper& infoDumper);
278     static void DumpCameraSessionSummary(CameraInfoDumper& infoDumper);
279     void ReleaseStreams();
280     void StopMovingPhoto();
281 
282     static void OpenMediaLib();
283     static void DelayCloseMediaLib();
284     static shared_ptr<CameraDynamicLoader> dynamicLoader_;
285     static std::optional<uint32_t> closeTimerId_;
286     static std::mutex g_mediaTaskLock_;
287     uint32_t preCacheFrameCount_ = CACHE_FRAME_COUNT;
288     uint32_t postCacheFrameCount_ = CACHE_FRAME_COUNT;
289 
290 private:
291     int32_t Initialize(const uint32_t callerToken, int32_t opMode);
292     string lastDisplayName_ = "";
293     string lastBurstPrefix_ = "";
294     int32_t saveIndex = 0;
295     volatile bool isMovingPhotoMirror_ = false;
296     volatile bool isSetMotionPhoto_ = false;
297     std::mutex livePhotoStreamLock_; // Guard livePhotoStreamRepeat_
298     sptr<HStreamRepeat> livePhotoStreamRepeat_;
SetCameraDevice(sptr<HCameraDevice> device)299     inline void SetCameraDevice(sptr<HCameraDevice> device)
300     {
301         std::lock_guard<std::mutex> lock(cameraDeviceLock_);
302         cameraDevice_ = device;
303     }
304 
GetCameraDevice()305     inline const sptr<HCameraDevice> GetCameraDevice()
306     {
307         std::lock_guard<std::mutex> lock(cameraDeviceLock_);
308         return cameraDevice_;
309     }
310     string CreateDisplayName(const std::string& suffix);
311     string CreateBurstDisplayName(int32_t seqId);
312     int32_t ValidateSessionInputs();
313     int32_t ValidateSessionOutputs();
314     int32_t ValidateSession();
315     int32_t AddOutputStream(sptr<HStreamCommon> stream);
316     int32_t RemoveOutputStream(sptr<HStreamCommon> stream);
317     int32_t LinkInputAndOutputs();
318     int32_t UnlinkInputAndOutputs();
319 
320     void ClearSketchRepeatStream();
321     void ExpandSketchRepeatStream();
322     void ExpandMovingPhotoRepeatStream();
323     void ClearMovingPhotoRepeatStream();
324     int32_t CreateMovingPhotoStreamRepeat(int32_t format, int32_t width, int32_t height,
325         sptr<OHOS::IBufferProducer> producer);
326     int32_t CheckIfColorSpaceMatchesFormat(ColorSpace colorSpace);
327     void CancelStreamsAndGetStreamInfos(std::vector<StreamInfo_V1_1>& streamInfos);
328     void RestartStreams();
329     int32_t UpdateStreamInfos();
330     void SetColorSpaceForStreams();
331 
332     void ProcessMetaZoomArray(std::vector<uint32_t>& zoomAndTimeArray, sptr<HCameraDevice>& cameraDevice);
333     void StartMovingPhotoStream();
334     bool InitAudioCapture();
335     bool StartAudioCapture();
336     void ProcessAudioBuffer();
337     void StartOnceRecord(uint64_t timestamp, int32_t rotation, int32_t captureId);
338     int32_t StartPreviewStream(const std::shared_ptr<OHOS::Camera::CameraMetadata>& settings,
339         camera_position_enum_t cameraPosition);
340     void UpdateMuteSetting(bool muteMode, std::shared_ptr<OHOS::Camera::CameraMetadata> &settings);
341     int32_t GetSensorOritation();
342     int32_t GetMovingPhotoBufferDuration();
343     void GetMovingPhotoStartAndEndTime();
344     void StartMovingPhoto(sptr<HStreamRepeat>& curStreamRepeat);
345 
346     std::string GetSessionState();
347     void DynamicConfigStream();
348     bool IsNeedDynamicConfig();
349     void RegisterDisplayListener(sptr<HStreamRepeat> repeat);
350     void UnRegisterDisplayListener(sptr<HStreamRepeat> repeat);
351     StateMachine stateMachine_;
352 
353     #ifdef CAMERA_USE_SENSOR
354         std::mutex sensorLock_;
355         bool isRegisterSensorSuccess_ = false;
356         void RegisterSensorCallback();
357         void UnRegisterSensorCallback();
358         static void GravityDataCallbackImpl(SensorEvent *event);
359         static int32_t CalcSensorRotation(int32_t sensorDegree);
360         static int32_t CalcRotationDegree(GravityData data);
361     #endif
362     // Make sure device thread safe,set device by {SetCameraDevice}, get device by {GetCameraDevice}
363     std::mutex cameraDeviceLock_;
364     sptr<HCameraDevice> cameraDevice_;
365     StreamContainer streamContainer_;
366     #ifdef CAMERA_USE_SENSOR
367         SensorUser user = {"", nullptr, nullptr};
368     #endif
369     pid_t pid_;
370     uid_t uid_;
371     uint32_t callerToken_;
372     int32_t opMode_;
373     int32_t featureMode_;
374     ColorSpace currColorSpace_ = ColorSpace::COLOR_SPACE_UNKNOWN;
375     ColorSpace currCaptureColorSpace_ = ColorSpace::COLOR_SPACE_UNKNOWN;
376     bool isSessionStarted_ = false;
377     bool enableStreamRotate_ = false;
378     bool isDynamicConfiged_ = false;
379     std::string deviceClass_ = "phone";
380     std::mutex movingPhotoStatusLock_; // Guard movingPhotoStatus
381     sptr<MovingPhotoListener> livephotoListener_;
382     sptr<MovingPhotoMetaListener> livephotoMetaListener_;
383     sptr<AudioCapturerSession> audioCapturerSession_;
384     sptr<Surface> metaSurface_ = nullptr;
385     sptr<MovingPhotoVideoCache> videoCache_;
386     sptr<AvcodecTaskManager> taskManager_;
387     std::mutex displayListenerLock_;
388     sptr<DisplayRotationListener> displayListener_;
389 };
390 } // namespace CameraStandard
391 } // namespace OHOS
392 #endif // OHOS_CAMERA_H_CAPTURE_SESSION_H
393