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