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