cb67bc78f6f9cf5752cd66230cea2f6f5e664081
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / animated-vector-image / vector-animation-task.cpp
1 /*
2  * Copyright (c) 2024 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-task.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/adaptor-framework/file-loader.h>
23 #include <dali/integration-api/debug.h>
24 #include <dali/integration-api/trace.h>
25 #include <dali/public-api/math/math-utils.h>
26 #include <dali/public-api/object/property-array.h>
27
28 // INTERNAL INCLUDES
29 #include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.h>
30 #include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.h>
31 #include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
32
33 #ifdef TRACE_ENABLED
34 #include <chrono>
35 #include <iomanip>
36 #include <sstream>
37 #include <thread>
38 #endif
39
40 namespace Dali
41 {
42 namespace Toolkit
43 {
44 namespace Internal
45 {
46 namespace
47 {
48 constexpr auto LOOP_FOREVER = -1;
49 constexpr auto MICROSECONDS_PER_SECOND(1e+6);
50
51 #if defined(DEBUG_ENABLED)
52 Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION");
53 #endif
54
55 DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_IMAGE_PERFORMANCE_MARKER, false);
56
57 #ifdef TRACE_ENABLED
58 uint64_t GetNanoseconds()
59 {
60   // Get the time of a monotonic clock since its epoch.
61   auto epoch    = std::chrono::steady_clock::now().time_since_epoch();
62   auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(epoch);
63   return static_cast<uint64_t>(duration.count());
64 }
65 #endif
66
67 } // unnamed namespace
68
69 VectorAnimationTask::VectorAnimationTask(VisualFactoryCache& factoryCache)
70 : AsyncTask(MakeCallback(this, &VectorAnimationTask::TaskCompleted), AsyncTask::PriorityType::HIGH, AsyncTask::ThreadType::WORKER_THREAD),
71   mImageUrl(),
72   mEncodedImageBuffer(),
73   mVectorRenderer(VectorAnimationRenderer::New()),
74   mAnimationData(),
75   mVectorAnimationThread(factoryCache.GetVectorAnimationManager().GetVectorAnimationThread()),
76   mMutex(),
77   mResourceReadySignal(),
78   mLoadCompletedCallback(MakeCallback(this, &VectorAnimationTask::OnLoadCompleted)),
79   mCachedLayerInfo(),
80   mCachedMarkerInfo(),
81   mPlayState(PlayState::STOPPED),
82   mStopBehavior(DevelImageVisual::StopBehavior::CURRENT_FRAME),
83   mLoopingMode(DevelImageVisual::LoopingMode::RESTART),
84   mNextFrameStartTime(),
85   mFrameDurationMicroSeconds(MICROSECONDS_PER_SECOND / 60.0f),
86   mFrameRate(60.0f),
87   mCurrentFrame(0),
88   mTotalFrame(0),
89   mStartFrame(0),
90   mEndFrame(0),
91   mDroppedFrames(0),
92   mWidth(0),
93   mHeight(0),
94   mAnimationDataIndex(0),
95   mLoopCount(LOOP_FOREVER),
96   mCurrentLoop(0),
97   mForward(true),
98   mUpdateFrameNumber(false),
99   mNeedAnimationFinishedTrigger(true),
100   mAnimationDataUpdated(false),
101   mDestroyTask(false),
102   mLoadRequest(false),
103   mLoadFailed(false),
104   mRasterized(false),
105   mKeepAnimation(false),
106   mLayerInfoCached(false),
107   mMarkerInfoCached(false),
108   mEnableFrameCache(false),
109   mSizeUpdated(false)
110 {
111   mVectorRenderer.UploadCompletedSignal().Connect(this, &VectorAnimationTask::OnUploadCompleted);
112 }
113
114 VectorAnimationTask::~VectorAnimationTask()
115 {
116   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::~VectorAnimationTask: destructor [%p]\n", this);
117 }
118
119 void VectorAnimationTask::Process()
120 {
121   mRasterized = Rasterize();
122 }
123
124 bool VectorAnimationTask::IsReady()
125 {
126   return true;
127 }
128
129 void VectorAnimationTask::Finalize()
130 {
131   {
132     Mutex::ScopedLock lock(mMutex);
133
134     // Release some objects in the main thread
135     if(mAnimationFinishedCallback)
136     {
137       mVectorAnimationThread.RemoveEventTriggerCallbacks(mAnimationFinishedCallback.get());
138       mAnimationFinishedCallback.reset();
139     }
140     if(mLoadCompletedCallback)
141     {
142       mVectorAnimationThread.RemoveEventTriggerCallbacks(mLoadCompletedCallback.get());
143       mLoadCompletedCallback.reset();
144     }
145
146     mDestroyTask = true;
147   }
148
149   mVectorRenderer.Finalize();
150 }
151
152 void VectorAnimationTask::TaskCompleted(VectorAnimationTaskPtr task)
153 {
154   mVectorAnimationThread.OnTaskCompleted(task, task->IsRasterized(), task->IsAnimating());
155 }
156
157 bool VectorAnimationTask::IsRasterized()
158 {
159   return mRasterized;
160 }
161
162 bool VectorAnimationTask::IsAnimating()
163 {
164   return mKeepAnimation;
165 }
166
167 bool VectorAnimationTask::Load(bool synchronousLoading)
168 {
169 #ifdef TRACE_ENABLED
170   uint64_t mStartTimeNanoSceonds = 0;
171   uint64_t mEndTimeNanoSceonds   = 0;
172   if(gTraceFilter && gTraceFilter->IsTraceEnabled())
173   {
174     mStartTimeNanoSceonds = GetNanoseconds();
175     std::ostringstream oss;
176     oss << "[u:" << mImageUrl.GetEllipsedUrl() << "]";
177     // DALI_TRACE_BEGIN(gTraceFilter, "DALI_LOTTIE_LOADING_TASK"); ///< TODO : Open it if we can control trace log level
178     DALI_LOG_RELEASE_INFO("BEGIN: DALI_LOTTIE_LOADING_TASK %s", oss.str().c_str());
179   }
180 #endif
181
182   if(mEncodedImageBuffer)
183   {
184     if(!mVectorRenderer.Load(mEncodedImageBuffer.GetRawBuffer()))
185     {
186       mLoadFailed = true;
187     }
188
189     // We don't need to hold image buffer anymore.
190     mEncodedImageBuffer.Reset();
191   }
192   else if(mImageUrl.IsLocalResource())
193   {
194     if(!mVectorRenderer.Load(mImageUrl.GetUrl()))
195     {
196       mLoadFailed = true;
197     }
198   }
199   else
200   {
201     Dali::Vector<uint8_t> remoteData;
202     if(!Dali::FileLoader::DownloadFileSynchronously(mImageUrl.GetUrl(), remoteData) || // Failed if we fail to download json file,
203        !mVectorRenderer.Load(remoteData))                                              // or download data is not valid vector animation file.
204     {
205       mLoadFailed = true;
206     }
207   }
208
209   if(mLoadFailed)
210   {
211     DALI_LOG_ERROR("VectorAnimationTask::Load: Load failed [%s]\n", mImageUrl.GetUrl().c_str());
212     mLoadRequest = false;
213     {
214       Mutex::ScopedLock lock(mMutex);
215       if(!synchronousLoading && mLoadCompletedCallback)
216       {
217         mVectorAnimationThread.AddEventTriggerCallback(mLoadCompletedCallback.get());
218       }
219     }
220 #ifdef TRACE_ENABLED
221     if(gTraceFilter && gTraceFilter->IsTraceEnabled())
222     {
223       mEndTimeNanoSceonds = GetNanoseconds();
224       std::ostringstream oss;
225       oss << std::fixed << std::setprecision(3);
226       oss << "[";
227       oss << "d:" << static_cast<float>(mEndTimeNanoSceonds - mStartTimeNanoSceonds) / 1000000.0f << "ms ";
228       oss << "u:" << mImageUrl.GetEllipsedUrl() << "]";
229       // DALI_TRACE_END(gTraceFilter, "DALI_LOTTIE_LOADING_TASK"); ///< TODO : Open it if we can control trace log level
230       DALI_LOG_RELEASE_INFO("END: DALI_LOTTIE_LOADING_TASK %s", oss.str().c_str());
231     }
232 #endif
233     return false;
234   }
235
236   mTotalFrame = mVectorRenderer.GetTotalFrameNumber();
237
238   mEndFrame = mTotalFrame - 1;
239
240   mFrameRate                 = mVectorRenderer.GetFrameRate();
241   mFrameDurationMicroSeconds = MICROSECONDS_PER_SECOND / mFrameRate;
242
243   mLoadRequest = false;
244   {
245     Mutex::ScopedLock lock(mMutex);
246     if(!synchronousLoading && mLoadCompletedCallback)
247     {
248       mVectorAnimationThread.AddEventTriggerCallback(mLoadCompletedCallback.get());
249     }
250   }
251
252   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Load: file = %s [%d frames, %f fps] [%p]\n", mImageUrl.GetUrl().c_str(), mTotalFrame, mFrameRate, this);
253
254 #ifdef TRACE_ENABLED
255   if(gTraceFilter && gTraceFilter->IsTraceEnabled())
256   {
257     mEndTimeNanoSceonds = GetNanoseconds();
258     std::ostringstream oss;
259     oss << std::fixed << std::setprecision(3);
260     oss << "[";
261     oss << "d:" << static_cast<float>(mEndTimeNanoSceonds - mStartTimeNanoSceonds) / 1000000.0f << "ms ";
262     oss << "u:" << mImageUrl.GetEllipsedUrl() << "]";
263     // DALI_TRACE_END(gTraceFilter, "DALI_LOTTIE_LOADING_TASK"); ///< TODO : Open it if we can control trace log level
264     DALI_LOG_RELEASE_INFO("END: DALI_LOTTIE_LOADING_TASK %s", oss.str().c_str());
265   }
266 #endif
267
268   return true;
269 }
270
271 void VectorAnimationTask::SetRenderer(Renderer renderer)
272 {
273   mVectorRenderer.SetRenderer(renderer);
274
275   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetRenderer [%p]\n", this);
276 }
277
278 void VectorAnimationTask::RequestLoad(const VisualUrl& url, EncodedImageBuffer encodedImageBuffer, bool synchronousLoading)
279 {
280   mImageUrl           = url;
281   mEncodedImageBuffer = encodedImageBuffer;
282
283   if(!synchronousLoading)
284   {
285     mLoadRequest = true;
286
287     mVectorAnimationThread.AddTask(this);
288   }
289   else
290   {
291     Load(true);
292
293     OnLoadCompleted();
294   }
295 }
296
297 bool VectorAnimationTask::IsLoadRequested() const
298 {
299   return mLoadRequest;
300 }
301
302 void VectorAnimationTask::SetAnimationData(const AnimationData& data)
303 {
304   Mutex::ScopedLock lock(mMutex);
305
306   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetAnimationData [%p]\n", this);
307
308   uint32_t index = mAnimationDataIndex == 0 ? 1 : 0; // Use the other buffer
309
310   mAnimationData[index].push_back(data);
311   mAnimationDataUpdated = true;
312
313   if(data.resendFlag & VectorAnimationTask::RESEND_SIZE)
314   {
315     // The size should be changed in the main thread.
316     SetSize(data.width, data.height);
317   }
318
319   mVectorAnimationThread.AddTask(this);
320 }
321
322 void VectorAnimationTask::SetSize(uint32_t width, uint32_t height)
323 {
324   if(mWidth != width || mHeight != height)
325   {
326     mVectorRenderer.SetSize(width, height);
327
328     mWidth  = width;
329     mHeight = height;
330
331     // If fixedCache is enabled, Call KeepRasterizedBuffer()
332     if(mEnableFrameCache)
333     {
334       if(mTotalFrame > 0 && !mLoadFailed)
335       {
336         mVectorRenderer.KeepRasterizedBuffer();
337       }
338       else
339       {
340         // If Load is not yet, update the size later.
341         mSizeUpdated = true;
342       }
343     }
344
345     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetSize: width = %d, height = %d [%p]\n", width, height, this);
346   }
347 }
348
349 void VectorAnimationTask::PlayAnimation()
350 {
351   if(mPlayState != PlayState::PLAYING)
352   {
353     mNeedAnimationFinishedTrigger = true;
354     mUpdateFrameNumber            = false;
355     mPlayState                    = PlayState::PLAYING;
356
357     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::PlayAnimation: Play [%p]\n", this);
358   }
359 }
360
361 void VectorAnimationTask::StopAnimation()
362 {
363   if(mPlayState != PlayState::STOPPING)
364   {
365     mNeedAnimationFinishedTrigger = false;
366     mPlayState                    = PlayState::STOPPING;
367
368     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::StopAnimation: Stop [%p]\n", this);
369   }
370 }
371
372 void VectorAnimationTask::PauseAnimation()
373 {
374   if(mPlayState == PlayState::PLAYING)
375   {
376     mPlayState = PlayState::PAUSED;
377
378     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::PauseAnimation: Pause [%p]\n", this);
379   }
380 }
381
382 void VectorAnimationTask::SetAnimationFinishedCallback(CallbackBase* callback)
383 {
384   Mutex::ScopedLock lock(mMutex);
385   mAnimationFinishedCallback = std::unique_ptr<CallbackBase>(callback);
386 }
387
388 void VectorAnimationTask::SetLoopCount(int32_t count)
389 {
390   if(mLoopCount != count)
391   {
392     mLoopCount   = count;
393     mCurrentLoop = 0;
394
395     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetLoopCount: [%d] [%p]\n", count, this);
396   }
397 }
398
399 void VectorAnimationTask::SetPlayRange(const Property::Array& playRange)
400 {
401   bool     valid      = false;
402   uint32_t startFrame = 0, endFrame = 0;
403   size_t   count = playRange.Count();
404
405   if(count >= 2)
406   {
407     int32_t start = 0, end = 0;
408     if(playRange.GetElementAt(0).Get(start) && playRange.GetElementAt(1).Get(end))
409     {
410       startFrame = static_cast<uint32_t>(start);
411       endFrame   = static_cast<uint32_t>(end);
412       valid      = true;
413     }
414     else
415     {
416       std::string startMarker, endMarker;
417       if(playRange.GetElementAt(0).Get(startMarker) && playRange.GetElementAt(1).Get(endMarker))
418       {
419         if(mVectorRenderer)
420         {
421           uint32_t frame; // We don't use this later
422           if(mVectorRenderer.GetMarkerInfo(startMarker, startFrame, frame) && mVectorRenderer.GetMarkerInfo(endMarker, frame, endFrame))
423           {
424             valid = true;
425           }
426         }
427       }
428     }
429   }
430   else if(count == 1)
431   {
432     std::string marker;
433     if(playRange.GetElementAt(0).Get(marker))
434     {
435       if(mVectorRenderer && mVectorRenderer.GetMarkerInfo(marker, startFrame, endFrame))
436       {
437         valid = true;
438       }
439     }
440   }
441
442   if(!valid)
443   {
444     DALI_LOG_ERROR("VectorAnimationTask::SetPlayRange: Invalid range [%p]\n", this);
445     return;
446   }
447
448   // Make sure the range specified is between 0 and the total frame number
449   startFrame = std::min(startFrame, mTotalFrame - 1);
450   endFrame   = std::min(endFrame, mTotalFrame - 1);
451
452   // If the range is not in order swap values
453   if(startFrame > endFrame)
454   {
455     uint32_t temp = startFrame;
456     startFrame    = endFrame;
457     endFrame      = temp;
458   }
459
460   if(startFrame != mStartFrame || endFrame != mEndFrame)
461   {
462     mStartFrame = startFrame;
463     mEndFrame   = endFrame;
464
465     // If the current frame is out of the range, change the current frame also.
466     if(mStartFrame > mCurrentFrame)
467     {
468       mCurrentFrame = mStartFrame;
469     }
470     else if(mEndFrame < mCurrentFrame)
471     {
472       mCurrentFrame = mEndFrame;
473     }
474
475     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetPlayRange: [%d, %d] [%s] [%p]\n", mStartFrame, mEndFrame, mImageUrl.GetUrl().c_str(), this);
476   }
477 }
478
479 void VectorAnimationTask::GetPlayRange(uint32_t& startFrame, uint32_t& endFrame)
480 {
481   startFrame = mStartFrame;
482   endFrame   = mEndFrame;
483 }
484
485 void VectorAnimationTask::SetCurrentFrameNumber(uint32_t frameNumber)
486 {
487   if(mCurrentFrame == frameNumber)
488   {
489     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetCurrentFrameNumber: Set same frame [%d] [%p]\n", frameNumber, this);
490     return;
491   }
492
493   if(frameNumber >= mStartFrame && frameNumber <= mEndFrame)
494   {
495     mCurrentFrame      = frameNumber;
496     mUpdateFrameNumber = false;
497
498     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetCurrentFrameNumber: frame number = %d [%p]\n", mCurrentFrame, this);
499   }
500   else
501   {
502     DALI_LOG_ERROR("Invalid frame number [%d (%d, %d)] [%p]\n", frameNumber, mStartFrame, mEndFrame, this);
503   }
504 }
505
506 uint32_t VectorAnimationTask::GetCurrentFrameNumber() const
507 {
508   return mCurrentFrame;
509 }
510
511 uint32_t VectorAnimationTask::GetTotalFrameNumber() const
512 {
513   return mTotalFrame;
514 }
515
516 void VectorAnimationTask::GetDefaultSize(uint32_t& width, uint32_t& height) const
517 {
518   mVectorRenderer.GetDefaultSize(width, height);
519 }
520
521 void VectorAnimationTask::SetStopBehavior(DevelImageVisual::StopBehavior::Type stopBehavior)
522 {
523   mStopBehavior = stopBehavior;
524
525   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetStopBehavior: stop behavor = %d [%p]\n", mStopBehavior, this);
526 }
527
528 void VectorAnimationTask::SetLoopingMode(DevelImageVisual::LoopingMode::Type loopingMode)
529 {
530   mLoopingMode = loopingMode;
531
532   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetLoopingMode: looping mode = %d [%p]\n", mLoopingMode, this);
533 }
534
535 void VectorAnimationTask::GetLayerInfo(Property::Map& map) const
536 {
537   // Fast-out if file is loading, or load failed.
538   if(mLoadFailed || IsLoadRequested())
539   {
540     return;
541   }
542
543   if(DALI_UNLIKELY(!mLayerInfoCached))
544   {
545     // Update only 1 time.
546     mLayerInfoCached = true;
547     mVectorRenderer.GetLayerInfo(mCachedLayerInfo);
548   }
549
550   map = mCachedLayerInfo;
551 }
552
553 void VectorAnimationTask::GetMarkerInfo(Property::Map& map) const
554 {
555   // Fast-out if file is loading, or load failed.
556   if(mLoadFailed || IsLoadRequested())
557   {
558     return;
559   }
560
561   if(DALI_UNLIKELY(!mMarkerInfoCached))
562   {
563     // Update only 1 time.
564     mMarkerInfoCached = true;
565     mVectorRenderer.GetMarkerInfo(mCachedMarkerInfo);
566   }
567
568   map = mCachedMarkerInfo;
569 }
570
571 VectorAnimationTask::ResourceReadySignalType& VectorAnimationTask::ResourceReadySignal()
572 {
573   return mResourceReadySignal;
574 }
575
576 bool VectorAnimationTask::Rasterize()
577 {
578   bool     stopped = false;
579   uint32_t currentFrame;
580   mKeepAnimation = false;
581
582   {
583     Mutex::ScopedLock lock(mMutex);
584     if(mDestroyTask)
585     {
586       // The task will be destroyed. We don't need rasterization.
587       return false;
588     }
589   }
590
591   if(mLoadRequest)
592   {
593     return Load(false);
594   }
595
596   if(mLoadFailed)
597   {
598     return false;
599   }
600
601 #ifdef TRACE_ENABLED
602   uint64_t mStartTimeNanoSceonds = 0;
603   uint64_t mEndTimeNanoSceonds   = 0;
604 #endif
605   DALI_TRACE_BEGIN_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_LOTTIE_RASTERIZE_TASK", [&](std::ostringstream& oss) {
606     mStartTimeNanoSceonds = GetNanoseconds();
607     oss << "[s:" << mWidth << "x" << mHeight << " ";
608     oss << "u:" << mImageUrl.GetEllipsedUrl() << "]";
609   });
610
611   ApplyAnimationData();
612
613   if(mPlayState == PlayState::PLAYING && mUpdateFrameNumber)
614   {
615     mCurrentFrame = mForward ? mCurrentFrame + mDroppedFrames + 1 : (mCurrentFrame > mDroppedFrames ? mCurrentFrame - mDroppedFrames - 1 : 0);
616     Dali::ClampInPlace(mCurrentFrame, mStartFrame, mEndFrame);
617   }
618
619   currentFrame = mCurrentFrame;
620
621   mUpdateFrameNumber = true;
622
623   if(mPlayState == PlayState::STOPPING)
624   {
625     mCurrentFrame = GetStoppedFrame(mStartFrame, mEndFrame, mCurrentFrame);
626     currentFrame  = mCurrentFrame;
627     stopped       = true;
628   }
629   else if(mPlayState == PlayState::PLAYING)
630   {
631     bool animationFinished = false;
632
633     if(currentFrame >= mEndFrame) // last frame
634     {
635       if(mLoopingMode == DevelImageVisual::LoopingMode::AUTO_REVERSE)
636       {
637         mForward = false;
638       }
639       else
640       {
641         if(mLoopCount < 0 || ++mCurrentLoop < mLoopCount) // repeat forever or before the last loop
642         {
643           mCurrentFrame      = mStartFrame;
644           mUpdateFrameNumber = false;
645         }
646         else
647         {
648           animationFinished = true; // end of animation
649         }
650       }
651     }
652     else if(currentFrame == mStartFrame && !mForward) // first frame
653     {
654       if(mLoopCount < 0 || ++mCurrentLoop < mLoopCount) // repeat forever or before the last loop
655       {
656         mForward = true;
657       }
658       else
659       {
660         animationFinished = true; // end of animation
661       }
662     }
663
664     if(animationFinished)
665     {
666       if(mStopBehavior == DevelImageVisual::StopBehavior::CURRENT_FRAME)
667       {
668         stopped = true;
669       }
670       else
671       {
672         mPlayState = PlayState::STOPPING;
673       }
674     }
675   }
676
677   // Rasterize
678   bool renderSuccess = false;
679   if(mVectorRenderer)
680   {
681     renderSuccess = mVectorRenderer.Render(currentFrame);
682     if(!renderSuccess)
683     {
684       DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Rasterize: Rendering failed. Try again later.[%d] [%p]\n", currentFrame, this);
685       mUpdateFrameNumber = false;
686     }
687   }
688
689   if(stopped && renderSuccess)
690   {
691     mPlayState   = PlayState::STOPPED;
692     mForward     = true;
693     mCurrentLoop = 0;
694
695     if(mVectorRenderer)
696     {
697       // Notify the Renderer that rendering is stopped.
698       mVectorRenderer.RenderStopped();
699     }
700
701     // Animation is finished
702     {
703       Mutex::ScopedLock lock(mMutex);
704       if(mNeedAnimationFinishedTrigger && mAnimationFinishedCallback)
705       {
706         mVectorAnimationThread.AddEventTriggerCallback(mAnimationFinishedCallback.get());
707       }
708     }
709
710     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Rasterize: Animation is finished [current = %d] [%p]\n", currentFrame, this);
711   }
712
713   if(mPlayState != PlayState::PAUSED && mPlayState != PlayState::STOPPED)
714   {
715     mKeepAnimation = true;
716   }
717
718   DALI_TRACE_END_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_LOTTIE_RASTERIZE_TASK", [&](std::ostringstream& oss) {
719     mEndTimeNanoSceonds = GetNanoseconds();
720     oss << std::fixed << std::setprecision(3);
721     oss << "[";
722     oss << "d:" << static_cast<float>(mEndTimeNanoSceonds - mStartTimeNanoSceonds) / 1000000.0f << "ms ";
723     oss << "s:" << mWidth << "x" << mHeight << " ";
724     oss << "f:" << mCurrentFrame << " ";
725     oss << "l:" << mCurrentLoop << " ";
726     oss << "p:" << mPlayState << " ";
727     oss << "u:" << mImageUrl.GetEllipsedUrl() << "]";
728   });
729
730   return true;
731 }
732
733 uint32_t VectorAnimationTask::GetStoppedFrame(uint32_t startFrame, uint32_t endFrame, uint32_t currentFrame)
734 {
735   uint32_t frame = currentFrame;
736
737   switch(mStopBehavior)
738   {
739     case DevelImageVisual::StopBehavior::FIRST_FRAME:
740     {
741       frame = startFrame;
742       break;
743     }
744     case DevelImageVisual::StopBehavior::LAST_FRAME:
745     {
746       if(mLoopingMode == DevelImageVisual::LoopingMode::AUTO_REVERSE)
747       {
748         frame = startFrame;
749       }
750       else
751       {
752         frame = endFrame;
753       }
754       break;
755     }
756     case DevelImageVisual::StopBehavior::CURRENT_FRAME:
757     {
758       frame = currentFrame;
759       break;
760     }
761   }
762
763   return frame;
764 }
765
766 VectorAnimationTask::TimePoint VectorAnimationTask::CalculateNextFrameTime(bool renderNow)
767 {
768   // std::chrono::time_point template has second parameter duration which defaults to the std::chrono::steady_clock supported
769   // duration. In some C++11 implementations it is a milliseconds duration, so it fails to compile unless mNextFrameStartTime
770   // is casted to use the default duration.
771   mNextFrameStartTime = std::chrono::time_point_cast<TimePoint::duration>(mNextFrameStartTime + std::chrono::microseconds(mFrameDurationMicroSeconds));
772   auto current        = std::chrono::steady_clock::now();
773   mDroppedFrames      = 0;
774
775   if(renderNow)
776   {
777     mNextFrameStartTime = current;
778   }
779   else if(mNextFrameStartTime < current)
780   {
781     uint32_t droppedFrames = 0;
782
783     while(current > std::chrono::time_point_cast<TimePoint::duration>(mNextFrameStartTime + std::chrono::microseconds(mFrameDurationMicroSeconds)) && droppedFrames < mTotalFrame)
784     {
785       droppedFrames++;
786       mNextFrameStartTime = std::chrono::time_point_cast<TimePoint::duration>(mNextFrameStartTime + std::chrono::microseconds(mFrameDurationMicroSeconds));
787     }
788
789     mNextFrameStartTime = current;
790     mDroppedFrames      = droppedFrames;
791   }
792
793   return mNextFrameStartTime;
794 }
795
796 VectorAnimationTask::TimePoint VectorAnimationTask::GetNextFrameTime()
797 {
798   return mNextFrameStartTime;
799 }
800
801 void VectorAnimationTask::ApplyAnimationData()
802 {
803   uint32_t index;
804
805   {
806     Mutex::ScopedLock lock(mMutex);
807
808     if(!mAnimationDataUpdated || mAnimationData[mAnimationDataIndex].size() != 0)
809     {
810       // Data is not updated or the previous data is not applied yet.
811       return;
812     }
813
814     mAnimationDataIndex   = mAnimationDataIndex == 0 ? 1 : 0; // Swap index
815     mAnimationDataUpdated = false;
816
817     index = mAnimationDataIndex;
818   }
819
820   for(const auto& animationData : mAnimationData[index])
821   {
822     if(animationData.resendFlag & VectorAnimationTask::RESEND_LOOP_COUNT)
823     {
824       SetLoopCount(animationData.loopCount);
825     }
826
827     if(animationData.resendFlag & VectorAnimationTask::RESEND_PLAY_RANGE)
828     {
829       SetPlayRange(animationData.playRange);
830     }
831
832     if(animationData.resendFlag & VectorAnimationTask::RESEND_STOP_BEHAVIOR)
833     {
834       SetStopBehavior(animationData.stopBehavior);
835     }
836
837     if(animationData.resendFlag & VectorAnimationTask::RESEND_LOOPING_MODE)
838     {
839       SetLoopingMode(animationData.loopingMode);
840     }
841
842     if(animationData.resendFlag & VectorAnimationTask::RESEND_CURRENT_FRAME)
843     {
844       SetCurrentFrameNumber(animationData.currentFrame);
845     }
846
847     if(animationData.resendFlag & VectorAnimationTask::RESEND_NEED_RESOURCE_READY)
848     {
849       mVectorRenderer.InvalidateBuffer();
850     }
851
852     if(animationData.resendFlag & VectorAnimationTask::RESEND_DYNAMIC_PROPERTY)
853     {
854       for(auto&& iter : animationData.dynamicProperties)
855       {
856         mVectorRenderer.AddPropertyValueCallback(iter.keyPath, static_cast<VectorAnimationRenderer::VectorProperty>(iter.property), iter.callback, iter.id);
857       }
858     }
859
860     if(animationData.resendFlag & VectorAnimationTask::RESEND_PLAY_STATE)
861     {
862       if(animationData.playState == DevelImageVisual::PlayState::PLAYING)
863       {
864         PlayAnimation();
865       }
866       else if(animationData.playState == DevelImageVisual::PlayState::PAUSED)
867       {
868         PauseAnimation();
869       }
870       else if(animationData.playState == DevelImageVisual::PlayState::STOPPED)
871       {
872         StopAnimation();
873       }
874     }
875   }
876
877   // reset data list
878   mAnimationData[index].clear();
879 }
880
881 void VectorAnimationTask::OnUploadCompleted()
882 {
883   mResourceReadySignal.Emit(ResourceStatus::READY);
884 }
885
886 void VectorAnimationTask::OnLoadCompleted()
887 {
888   if(!mLoadFailed)
889   {
890     if(mEnableFrameCache && mSizeUpdated)
891     {
892       mVectorRenderer.KeepRasterizedBuffer();
893       mSizeUpdated = false;
894     }
895     mResourceReadySignal.Emit(ResourceStatus::LOADED);
896   }
897   else
898   {
899     mResourceReadySignal.Emit(ResourceStatus::FAILED);
900   }
901 }
902 } // namespace Internal
903
904 } // namespace Toolkit
905
906 } // namespace Dali