Merge "Remove Atlas parameter for TextureManager cache system" into 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/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   };
80
81   /**
82    * @brief Structure used to pass parameters to the vector animation task
83    */
84   struct AnimationData
85   {
86     AnimationData()
87     : resendFlag(0),
88       playRange(),
89       dynamicProperties(),
90       playState(),
91       stopBehavior(DevelImageVisual::StopBehavior::CURRENT_FRAME),
92       loopingMode(DevelImageVisual::LoopingMode::RESTART),
93       currentFrame(0),
94       width(0),
95       height(0),
96       loopCount(-1)
97     {
98     }
99
100     AnimationData& operator=(const AnimationData& rhs)
101     {
102       resendFlag |= rhs.resendFlag; // OR resend flag
103       playRange    = rhs.playRange;
104       playState    = rhs.playState;
105       stopBehavior = rhs.stopBehavior;
106       loopingMode  = rhs.loopingMode;
107       currentFrame = rhs.currentFrame;
108       width        = rhs.width;
109       height       = rhs.height;
110       loopCount    = rhs.loopCount;
111       dynamicProperties.insert(dynamicProperties.end(), rhs.dynamicProperties.begin(), rhs.dynamicProperties.end());
112       return *this;
113     }
114
115     uint32_t                             resendFlag;
116     Property::Array                      playRange;
117     DynamicPropertyType                  dynamicProperties;
118     DevelImageVisual::PlayState::Type    playState;
119     DevelImageVisual::StopBehavior::Type stopBehavior;
120     DevelImageVisual::LoopingMode::Type  loopingMode;
121     uint32_t                             currentFrame;
122     uint32_t                             width;
123     uint32_t                             height;
124     int32_t                              loopCount;
125   };
126
127   /**
128    * @brief Constructor.
129    *
130    * @param[in] factoryCache A pointer pointing to the VisualFactoryCache object
131    */
132   VectorAnimationTask(VisualFactoryCache& factoryCache);
133
134   /**
135    * @brief Destructor.
136    */
137   ~VectorAnimationTask() override;
138
139   /**
140    * Process the task accodring to the type
141    */
142   void Process() override;
143
144   /**
145    * Whether the task is ready to process.
146    * @return True if the task is ready to process.
147    */
148   bool IsReady() override;
149
150   /**
151    * @brief Finalizes the task.
152    */
153   void Finalize();
154
155   /**
156    * @brief Sets the renderer used to display the result image.
157    *
158    * @param[in] renderer The renderer used to display the result image
159    */
160   void SetRenderer(Renderer renderer);
161
162   /**
163    * @brief Requests to load the animation file.
164    *
165    * @param[in] url The url of the vector animation file
166    * @param[in] encodedImageBuffer The resource buffer if required.
167    * @param[in] synchronousLoading True if the url should be loaded synchronously
168    */
169   void RequestLoad(const VisualUrl& url, EncodedImageBuffer encodedImageBuffer, bool synchronousLoading);
170
171   /**
172    * @brief Queries whether loading is requested.
173    * @return True if loading is requested.
174    */
175   bool IsLoadRequested() const;
176
177   /**
178    * @brief Sets data to specify animation playback.
179    * @param[in] data The animation data
180    */
181   void SetAnimationData(const AnimationData& data);
182
183   /**
184    * @brief This callback is called after the animation is finished.
185    * @param[in] callback The animation finished callback
186    */
187   void SetAnimationFinishedCallback(CallbackBase* callback);
188
189   /**
190    * @brief Gets the playing range in frame number.
191    * @param[out] startFrame The frame number to specify minimum progress.
192    * @param[out] endFrame The frame number to specify maximum progress.
193    */
194   void GetPlayRange(uint32_t& startFrame, uint32_t& endFrame);
195
196   /**
197    * @brief Retrieves the current frame number of the animation.
198    * @return The current frame number
199    */
200   uint32_t GetCurrentFrameNumber() const;
201
202   /**
203    * @brief Retrieves the total frame number of the animation.
204    * @return The total frame number
205    */
206   uint32_t GetTotalFrameNumber() const;
207
208   /**
209    * @brief Gets the default size of the file,.
210    * @return The default size of the file
211    */
212   void GetDefaultSize(uint32_t& width, uint32_t& height) const;
213
214   /**
215    * @brief Gets the layer information of all the child layers.
216    * @param[out] map The layer information
217    */
218   void GetLayerInfo(Property::Map& map) const;
219
220   /**
221    * @brief Gets the all marker information.
222    * @param[out] map The marker information
223    */
224   void GetMarkerInfo(Property::Map& map) const;
225
226   /**
227    * @brief Connect to this signal to be notified when the resource is ready.
228    * @return The signal to connect to.
229    */
230   ResourceReadySignalType& ResourceReadySignal();
231
232   /**
233    * @brief Rasterizes the current frame.
234    * @return true if the rasterization succeeded, false otherwise.
235    */
236   bool Rasterize();
237
238   /**
239    * @brief Calculates the time for the next frame rasterization.
240    * @return The time for the next frame rasterization.
241    */
242   TimePoint CalculateNextFrameTime(bool renderNow);
243
244   /**
245    * @brief Gets the time for the next frame rasterization.
246    * @return The time for the next frame rasterization.
247    */
248   TimePoint GetNextFrameTime();
249
250   /**
251    * @brief Called when the rasterization is completed from the asyncTaskManager
252    * @param[in] task The completed task
253    */
254   void TaskCompleted(VectorAnimationTaskPtr task);
255
256   /**
257    * @brief Check the rasterization succeeded
258    * @return true if the rasterization succeeded, false otherwise.
259    */
260   bool IsRasterized();
261
262   /**
263    * @brief Check the animation is running
264    * @return true if the animation is running, false otherwise.
265    */
266   bool IsAnimating();
267
268 private:
269   /**
270    * @brief Loads the animation file.
271    *
272    * @param[in] synchronousLoading True if loading is requested synchronously
273    * @return True if loading succeeded, false otherwise.
274    */
275   bool Load(bool synchronousLoading);
276
277   /**
278    * @brief Play the vector animation.
279    */
280   void PlayAnimation();
281
282   /**
283    * @brief Stop the vector animation.
284    */
285   void StopAnimation();
286
287   /**
288    * @brief Pause the vector animation.
289    */
290   void PauseAnimation();
291
292   /**
293    * @brief Sets the target image size.
294    *
295    * @param[in] width The target image width
296    * @param[in] height The target image height
297    */
298   void SetSize(uint32_t width, uint32_t height);
299
300   /**
301    * @brief Enable looping for 'count' repeats. -1 means to repeat forever.
302    * @param[in] count The number of times to loop
303    */
304   void SetLoopCount(int32_t count);
305
306   /**
307    * @brief Set the playing range in frame number.
308    * @param[in] playRange The array to specify minimum and maximum progress.
309    * The animation will play between those values.
310    */
311   void SetPlayRange(const Property::Array& playRange);
312
313   /**
314    * @brief Sets the current frame number of the animation.
315    * @param[in] frameNumber The new frame number between [0, the maximum frame number] or between the play range if specified.
316    */
317   void SetCurrentFrameNumber(uint32_t frameNumber);
318
319   /**
320    * @brief Sets the stop behavior of the animation. This is performed when the animation is stopped.
321    * @param[in] stopBehavior The stop behavior
322    */
323   void SetStopBehavior(DevelImageVisual::StopBehavior::Type stopBehavior);
324
325   /**
326    * @brief Sets the looping mode.
327    * Animation plays forwards and then restarts from the beginning or runs backwards again.
328    * @param[in] loopingMode The looping mode
329    */
330   void SetLoopingMode(DevelImageVisual::LoopingMode::Type loopingMode);
331
332   /**
333    * @brief Gets the frame number when the animation is stopped according to the stop behavior.
334    */
335   uint32_t GetStoppedFrame(uint32_t startFrame, uint32_t endFrame, uint32_t currentFrame);
336
337   /**
338    * @brief Applies the animation data set by the main thread.
339    */
340   void ApplyAnimationData();
341
342   /**
343    * @brief Called when the texture upload is completed.
344    */
345   void OnUploadCompleted();
346
347   /**
348    * @brief Event callback from rasterize thread. This is called when the file loading is completed.
349    */
350   void OnLoadCompleted();
351
352   // Undefined
353   VectorAnimationTask(const VectorAnimationTask& task) = delete;
354
355   // Undefined
356   VectorAnimationTask& operator=(const VectorAnimationTask& task) = delete;
357
358 private:
359   enum class PlayState
360   {
361     STOPPING, ///< The animation is stopping
362     STOPPED,  ///< The animation has stopped
363     PLAYING,  ///< The animation is playing
364     PAUSED    ///< The animation is paused
365   };
366
367   VisualUrl                            mImageUrl;
368   EncodedImageBuffer                   mEncodedImageBuffer;
369   VectorAnimationRenderer              mVectorRenderer;
370   std::vector<AnimationData>           mAnimationData[2];
371   VectorAnimationThread&               mVectorAnimationThread;
372   ConditionalWait                      mConditionalWait;
373   ResourceReadySignalType              mResourceReadySignal;
374   std::unique_ptr<CallbackBase>        mAnimationFinishedCallback{};
375   std::unique_ptr<CallbackBase>        mLoadCompletedCallback{};
376   mutable Property::Map                mCachedLayerInfo;
377   mutable Property::Map                mCachedMarkerInfo;
378   PlayState                            mPlayState;
379   DevelImageVisual::StopBehavior::Type mStopBehavior;
380   DevelImageVisual::LoopingMode::Type  mLoopingMode;
381   TimePoint                            mNextFrameStartTime;
382   int64_t                              mFrameDurationMicroSeconds;
383   float                                mFrameRate;
384   uint32_t                             mCurrentFrame;
385   uint32_t                             mTotalFrame;
386   uint32_t                             mStartFrame;
387   uint32_t                             mEndFrame;
388   uint32_t                             mDroppedFrames;
389   uint32_t                             mWidth;
390   uint32_t                             mHeight;
391   uint32_t                             mAnimationDataIndex;
392   int32_t                              mLoopCount;
393   int32_t                              mCurrentLoop;
394   bool                                 mForward : 1;
395   bool                                 mUpdateFrameNumber : 1;
396   bool                                 mNeedAnimationFinishedTrigger : 1;
397   bool                                 mAnimationDataUpdated : 1;
398   bool                                 mDestroyTask : 1;
399   bool                                 mLoadRequest : 1;
400   bool                                 mLoadFailed : 1;
401   bool                                 mRasterized : 1;
402   bool                                 mKeepAnimation : 1;
403   mutable bool                         mLayerInfoCached : 1;
404   mutable bool                         mMarkerInfoCached : 1;
405 };
406
407 } // namespace Internal
408
409 } // namespace Toolkit
410
411 } // namespace Dali
412
413 #endif // DALI_TOOLKIT_VECTOR_ANIMATION_TASK_H