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