[dali_2.2.51] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / animated-vector-image / vector-animation-task.h
1 #ifndef DALI_TOOLKIT_VECTOR_ANIMATION_TASK_H
2 #define DALI_TOOLKIT_VECTOR_ANIMATION_TASK_H
3
4 /*
5  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 // EXTERNAL INCLUDES
21 #include <dali/devel-api/adaptor-framework/event-thread-callback.h>
22 #include <dali/devel-api/adaptor-framework/vector-animation-renderer.h>
23 #include <dali/devel-api/threading/conditional-wait.h>
24 #include <dali/public-api/adaptor-framework/async-task-manager.h>
25 #include <dali/public-api/common/vector-wrapper.h>
26 #include <dali/public-api/object/property-array.h>
27 #include <chrono>
28 #include <memory>
29
30 // INTERNAL INCLUDES
31 #include <dali-toolkit/devel-api/visuals/animated-vector-image-visual-actions-devel.h>
32 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
33 #include <dali-toolkit/internal/visuals/visual-url.h>
34
35 namespace Dali
36 {
37 namespace Toolkit
38 {
39 namespace Internal
40 {
41 class VisualFactoryCache;
42 class VectorAnimationThread;
43 class VectorAnimationTask;
44 typedef IntrusivePtr<VectorAnimationTask> VectorAnimationTaskPtr;
45
46 /**
47  * The task of the vector animation.
48  */
49 class VectorAnimationTask : public AsyncTask, public ConnectionTracker
50 {
51 public:
52   enum class ResourceStatus
53   {
54     LOADED, /// Resource is loaded
55     READY,  /// Resource is ready
56     FAILED  /// Resource is fail to load
57   };
58
59   using ResourceReadySignalType = Signal<void(ResourceStatus)>;
60
61   using TimePoint           = std::chrono::time_point<std::chrono::steady_clock>;
62   using DynamicPropertyType = std::vector<DevelAnimatedVectorImageVisual::DynamicPropertyInfo>;
63
64   /**
65    * Flags for re-sending data to the vector animation thread
66    */
67   enum ResendFlags
68   {
69     RESEND_PLAY_RANGE          = 1 << 0,
70     RESEND_LOOP_COUNT          = 1 << 1,
71     RESEND_STOP_BEHAVIOR       = 1 << 2,
72     RESEND_LOOPING_MODE        = 1 << 3,
73     RESEND_CURRENT_FRAME       = 1 << 4,
74     RESEND_SIZE                = 1 << 5,
75     RESEND_PLAY_STATE          = 1 << 6,
76     RESEND_NEED_RESOURCE_READY = 1 << 7,
77     RESEND_DYNAMIC_PROPERTY    = 1 << 8
78   };
79
80   /**
81    * @brief Structure used to pass parameters to the vector animation task
82    */
83   struct AnimationData
84   {
85     AnimationData()
86     : resendFlag(0),
87       playRange(),
88       dynamicProperties(),
89       playState(),
90       stopBehavior(DevelImageVisual::StopBehavior::CURRENT_FRAME),
91       loopingMode(DevelImageVisual::LoopingMode::RESTART),
92       currentFrame(0),
93       width(0),
94       height(0),
95       loopCount(-1)
96     {
97     }
98
99     AnimationData& operator=(const AnimationData& rhs)
100     {
101       resendFlag |= rhs.resendFlag; // OR resend flag
102       playRange    = rhs.playRange;
103       playState    = rhs.playState;
104       stopBehavior = rhs.stopBehavior;
105       loopingMode  = rhs.loopingMode;
106       currentFrame = rhs.currentFrame;
107       width        = rhs.width;
108       height       = rhs.height;
109       loopCount    = rhs.loopCount;
110       dynamicProperties.insert(dynamicProperties.end(), rhs.dynamicProperties.begin(), rhs.dynamicProperties.end());
111       return *this;
112     }
113
114     uint32_t                             resendFlag;
115     Property::Array                      playRange;
116     DynamicPropertyType                  dynamicProperties;
117     DevelImageVisual::PlayState::Type    playState;
118     DevelImageVisual::StopBehavior::Type stopBehavior;
119     DevelImageVisual::LoopingMode::Type  loopingMode;
120     uint32_t                             currentFrame;
121     uint32_t                             width;
122     uint32_t                             height;
123     int32_t                              loopCount;
124   };
125
126   /**
127    * @brief Constructor.
128    *
129    * @param[in] factoryCache A pointer pointing to the VisualFactoryCache object
130    */
131   VectorAnimationTask(VisualFactoryCache& factoryCache);
132
133   /**
134    * @brief Destructor.
135    */
136   ~VectorAnimationTask() override;
137
138   /**
139    * Process the task accodring to the type
140    */
141   void Process() override;
142
143   /**
144    * Whether the task is ready to process.
145    * @return True if the task is ready to process.
146    */
147   bool IsReady() override;
148
149   /**
150    * @brief Finalizes the task.
151    */
152   void Finalize();
153
154   /**
155    * @brief Sets the renderer used to display the result image.
156    *
157    * @param[in] renderer The renderer used to display the result image
158    */
159   void SetRenderer(Renderer renderer);
160
161   /**
162    * @brief Requests to load the animation file.
163    *
164    * @param[in] url The url of the vector animation file
165    * @param[in] synchronousLoading True if the url should be loaded synchronously
166    */
167   void RequestLoad(const VisualUrl& url, bool synchronousLoading);
168
169   /**
170    * @brief Queries whether loading is requested.
171    * @return True if loading is requested.
172    */
173   bool IsLoadRequested() const;
174
175   /**
176    * @brief Sets data to specify animation playback.
177    * @param[in] data The animation data
178    */
179   void SetAnimationData(const AnimationData& data);
180
181   /**
182    * @brief This callback is called after the animation is finished.
183    * @param[in] callback The animation finished callback
184    */
185   void SetAnimationFinishedCallback(CallbackBase* callback);
186
187   /**
188    * @brief Gets the playing range in frame number.
189    * @param[out] startFrame The frame number to specify minimum progress.
190    * @param[out] endFrame The frame number to specify maximum progress.
191    */
192   void GetPlayRange(uint32_t& startFrame, uint32_t& endFrame);
193
194   /**
195    * @brief Retrieves the current frame number of the animation.
196    * @return The current frame number
197    */
198   uint32_t GetCurrentFrameNumber() const;
199
200   /**
201    * @brief Retrieves the total frame number of the animation.
202    * @return The total frame number
203    */
204   uint32_t GetTotalFrameNumber() const;
205
206   /**
207    * @brief Gets the default size of the file,.
208    * @return The default size of the file
209    */
210   void GetDefaultSize(uint32_t& width, uint32_t& height) const;
211
212   /**
213    * @brief Gets the layer information of all the child layers.
214    * @param[out] map The layer information
215    */
216   void GetLayerInfo(Property::Map& map) const;
217
218   /**
219    * @brief Connect to this signal to be notified when the resource is ready.
220    * @return The signal to connect to.
221    */
222   ResourceReadySignalType& ResourceReadySignal();
223
224   /**
225    * @brief Rasterizes the current frame.
226    * @return true if the rasterization succeeded, false otherwise.
227    */
228   bool Rasterize();
229
230   /**
231    * @brief Calculates the time for the next frame rasterization.
232    * @return The time for the next frame rasterization.
233    */
234   TimePoint CalculateNextFrameTime(bool renderNow);
235
236   /**
237    * @brief Gets the time for the next frame rasterization.
238    * @return The time for the next frame rasterization.
239    */
240   TimePoint GetNextFrameTime();
241
242   /**
243    * @brief Called when the rasterization is completed from the asyncTaskManager
244    * @param[in] task The completed task
245    */
246   void TaskCompleted(VectorAnimationTaskPtr task);
247
248   /**
249    * @brief Check the rasterization succeeded
250    * @return true if the rasterization succeeded, false otherwise.
251    */
252   bool IsRasterized();
253
254   /**
255    * @brief Check the animation is running
256    * @return true if the animation is running, false otherwise.
257    */
258   bool IsAnimating();
259
260 private:
261   /**
262    * @brief Loads the animation file.
263    *
264    * @param[in] synchronousLoading True if loading is requested synchronously
265    * @return True if loading succeeded, false otherwise.
266    */
267   bool Load(bool synchronousLoading);
268
269   /**
270    * @brief Play the vector animation.
271    */
272   void PlayAnimation();
273
274   /**
275    * @brief Stop the vector animation.
276    */
277   void StopAnimation();
278
279   /**
280    * @brief Pause the vector animation.
281    */
282   void PauseAnimation();
283
284   /**
285    * @brief Sets the target image size.
286    *
287    * @param[in] width The target image width
288    * @param[in] height The target image height
289    */
290   void SetSize(uint32_t width, uint32_t height);
291
292   /**
293    * @brief Enable looping for 'count' repeats. -1 means to repeat forever.
294    * @param[in] count The number of times to loop
295    */
296   void SetLoopCount(int32_t count);
297
298   /**
299    * @brief Set the playing range in frame number.
300    * @param[in] playRange The array to specify minimum and maximum progress.
301    * The animation will play between those values.
302    */
303   void SetPlayRange(const Property::Array& playRange);
304
305   /**
306    * @brief Sets the current frame number of the animation.
307    * @param[in] frameNumber The new frame number between [0, the maximum frame number] or between the play range if specified.
308    */
309   void SetCurrentFrameNumber(uint32_t frameNumber);
310
311   /**
312    * @brief Sets the stop behavior of the animation. This is performed when the animation is stopped.
313    * @param[in] stopBehavior The stop behavior
314    */
315   void SetStopBehavior(DevelImageVisual::StopBehavior::Type stopBehavior);
316
317   /**
318    * @brief Sets the looping mode.
319    * Animation plays forwards and then restarts from the beginning or runs backwards again.
320    * @param[in] loopingMode The looping mode
321    */
322   void SetLoopingMode(DevelImageVisual::LoopingMode::Type loopingMode);
323
324   /**
325    * @brief Gets the frame number when the animation is stopped according to the stop behavior.
326    */
327   uint32_t GetStoppedFrame(uint32_t startFrame, uint32_t endFrame, uint32_t currentFrame);
328
329   /**
330    * @brief Applies the animation data set by the main thread.
331    */
332   void ApplyAnimationData();
333
334   /**
335    * @brief Called when the texture upload is completed.
336    */
337   void OnUploadCompleted();
338
339   /**
340    * @brief Event callback from rasterize thread. This is called when the file loading is completed.
341    */
342   void OnLoadCompleted();
343
344   // Undefined
345   VectorAnimationTask(const VectorAnimationTask& task) = delete;
346
347   // Undefined
348   VectorAnimationTask& operator=(const VectorAnimationTask& task) = delete;
349
350 private:
351   enum class PlayState
352   {
353     STOPPING, ///< The animation is stopping
354     STOPPED,  ///< The animation has stopped
355     PLAYING,  ///< The animation is playing
356     PAUSED    ///< The animation is paused
357   };
358
359   VisualUrl                            mImageUrl;
360   VectorAnimationRenderer              mVectorRenderer;
361   std::vector<AnimationData>           mAnimationData[2];
362   VectorAnimationThread&               mVectorAnimationThread;
363   ConditionalWait                      mConditionalWait;
364   ResourceReadySignalType              mResourceReadySignal;
365   std::unique_ptr<CallbackBase>        mAnimationFinishedCallback{};
366   std::unique_ptr<CallbackBase>        mLoadCompletedCallback{};
367   PlayState                            mPlayState;
368   DevelImageVisual::StopBehavior::Type mStopBehavior;
369   DevelImageVisual::LoopingMode::Type  mLoopingMode;
370   TimePoint                            mNextFrameStartTime;
371   int64_t                              mFrameDurationMicroSeconds;
372   float                                mFrameRate;
373   uint32_t                             mCurrentFrame;
374   uint32_t                             mTotalFrame;
375   uint32_t                             mStartFrame;
376   uint32_t                             mEndFrame;
377   uint32_t                             mDroppedFrames;
378   uint32_t                             mWidth;
379   uint32_t                             mHeight;
380   uint32_t                             mAnimationDataIndex;
381   int32_t                              mLoopCount;
382   int32_t                              mCurrentLoop;
383   bool                                 mForward;
384   bool                                 mUpdateFrameNumber;
385   bool                                 mNeedAnimationFinishedTrigger;
386   bool                                 mAnimationDataUpdated;
387   bool                                 mDestroyTask;
388   bool                                 mLoadRequest;
389   bool                                 mLoadFailed;
390   bool                                 mRasterized;
391   bool                                 mKeepAnimation;
392 };
393
394 } // namespace Internal
395
396 } // namespace Toolkit
397
398 } // namespace Dali
399
400 #endif // DALI_TOOLKIT_VECTOR_ANIMATION_TASK_H