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