Merge "(Vector) Change SetPlayRange and fix a crash" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / animated-vector-image / vector-animation-task.cpp
1 /*
2  * Copyright (c) 2022 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/integration-api/debug.h>
23 #include <dali/public-api/math/math-utils.h>
24 #include <dali/public-api/object/property-array.h>
25
26 // INTERNAL INCLUDES
27 #include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-manager.h>
28 #include <dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.h>
29 #include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
30
31 namespace Dali
32 {
33 namespace Toolkit
34 {
35 namespace Internal
36 {
37 namespace
38 {
39 constexpr auto LOOP_FOREVER = -1;
40 constexpr auto MICROSECONDS_PER_SECOND(1e+6);
41
42 #if defined(DEBUG_ENABLED)
43 Debug::Filter* gVectorAnimationLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_VECTOR_ANIMATION");
44 #endif
45
46 } // unnamed namespace
47
48 VectorAnimationTask::VectorAnimationTask(VisualFactoryCache& factoryCache)
49 : mUrl(),
50   mVectorRenderer(VectorAnimationRenderer::New()),
51   mAnimationData(),
52   mVectorAnimationThread(factoryCache.GetVectorAnimationManager().GetVectorAnimationThread()),
53   mConditionalWait(),
54   mResourceReadySignal(),
55   mAnimationFinishedTrigger(),
56   mLoadCompletedTrigger(new EventThreadCallback(MakeCallback(this, &VectorAnimationTask::OnLoadCompleted))),
57   mPlayState(PlayState::STOPPED),
58   mStopBehavior(DevelImageVisual::StopBehavior::CURRENT_FRAME),
59   mLoopingMode(DevelImageVisual::LoopingMode::RESTART),
60   mNextFrameStartTime(),
61   mFrameDurationMicroSeconds(MICROSECONDS_PER_SECOND / 60.0f),
62   mFrameRate(60.0f),
63   mCurrentFrame(0),
64   mTotalFrame(0),
65   mStartFrame(0),
66   mEndFrame(0),
67   mDroppedFrames(0),
68   mWidth(0),
69   mHeight(0),
70   mAnimationDataIndex(0),
71   mLoopCount(LOOP_FOREVER),
72   mCurrentLoop(0),
73   mForward(true),
74   mUpdateFrameNumber(false),
75   mNeedAnimationFinishedTrigger(true),
76   mAnimationDataUpdated(false),
77   mDestroyTask(false),
78   mLoadRequest(false),
79   mLoadFailed(false)
80 {
81   mVectorRenderer.UploadCompletedSignal().Connect(this, &VectorAnimationTask::OnUploadCompleted);
82 }
83
84 VectorAnimationTask::~VectorAnimationTask()
85 {
86   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::~VectorAnimationTask: destructor [%p]\n", this);
87 }
88
89 void VectorAnimationTask::Finalize()
90 {
91   ConditionalWait::ScopedLock lock(mConditionalWait);
92
93   // Release some objects in the main thread
94   if(mAnimationFinishedTrigger)
95   {
96     mAnimationFinishedTrigger.reset();
97   }
98   if(mLoadCompletedTrigger)
99   {
100     mLoadCompletedTrigger.reset();
101   }
102
103   mVectorRenderer.Finalize();
104
105   mDestroyTask = true;
106 }
107
108 bool VectorAnimationTask::Load()
109 {
110   if(!mVectorRenderer.Load(mUrl))
111   {
112     DALI_LOG_ERROR("VectorAnimationTask::Load: Load failed [%s]\n", mUrl.c_str());
113     mLoadRequest = false;
114     mLoadFailed  = true;
115     mLoadCompletedTrigger->Trigger();
116     return false;
117   }
118
119   mTotalFrame = mVectorRenderer.GetTotalFrameNumber();
120
121   mEndFrame = mTotalFrame - 1;
122
123   mFrameRate                 = mVectorRenderer.GetFrameRate();
124   mFrameDurationMicroSeconds = MICROSECONDS_PER_SECOND / mFrameRate;
125
126   mLoadRequest = false;
127   mLoadCompletedTrigger->Trigger();
128
129   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Load: file = %s [%d frames, %f fps] [%p]\n", mUrl.c_str(), mTotalFrame, mFrameRate, this);
130
131   return true;
132 }
133
134 void VectorAnimationTask::SetRenderer(Renderer renderer)
135 {
136   ConditionalWait::ScopedLock lock(mConditionalWait);
137
138   mVectorRenderer.SetRenderer(renderer);
139
140   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetRenderer [%p]\n", this);
141 }
142
143 void VectorAnimationTask::RequestLoad(const std::string& url)
144 {
145   mUrl         = url;
146   mLoadRequest = true;
147
148   mVectorAnimationThread.AddTask(this);
149 }
150
151 bool VectorAnimationTask::IsLoadRequested() const
152 {
153   return mLoadRequest;
154 }
155
156 void VectorAnimationTask::SetAnimationData(const AnimationData& data)
157 {
158   ConditionalWait::ScopedLock lock(mConditionalWait);
159
160   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetAnimationData [%p]\n", this);
161
162   uint32_t index = mAnimationDataIndex == 0 ? 1 : 0; // Use the other buffer
163
164   mAnimationData[index] = data;
165   mAnimationDataUpdated = true;
166
167   if(data.resendFlag & VectorAnimationTask::RESEND_SIZE)
168   {
169     // The size should be changed in the main thread.
170     SetSize(data.width, data.height);
171   }
172
173   mVectorAnimationThread.AddTask(this);
174 }
175
176 void VectorAnimationTask::SetSize(uint32_t width, uint32_t height)
177 {
178   if(mWidth != width || mHeight != height)
179   {
180     mVectorRenderer.SetSize(width, height);
181
182     mWidth  = width;
183     mHeight = height;
184
185     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetSize: width = %d, height = %d [%p]\n", width, height, this);
186   }
187 }
188
189 void VectorAnimationTask::PlayAnimation()
190 {
191   if(mPlayState != PlayState::PLAYING)
192   {
193     mNeedAnimationFinishedTrigger = true;
194     mUpdateFrameNumber            = false;
195     mPlayState                    = PlayState::PLAYING;
196
197     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::PlayAnimation: Play [%p]\n", this);
198   }
199 }
200
201 void VectorAnimationTask::StopAnimation()
202 {
203   if(mPlayState != PlayState::STOPPING)
204   {
205     mNeedAnimationFinishedTrigger = false;
206     mPlayState                    = PlayState::STOPPING;
207
208     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::StopAnimation: Stop [%p]\n", this);
209   }
210 }
211
212 void VectorAnimationTask::PauseAnimation()
213 {
214   if(mPlayState == PlayState::PLAYING)
215   {
216     mPlayState = PlayState::PAUSED;
217
218     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::PauseAnimation: Pause [%p]\n", this);
219   }
220 }
221
222 void VectorAnimationTask::SetAnimationFinishedCallback(EventThreadCallback* callback)
223 {
224   ConditionalWait::ScopedLock lock(mConditionalWait);
225   if(callback)
226   {
227     mAnimationFinishedTrigger = std::unique_ptr<EventThreadCallback>(callback);
228   }
229 }
230
231 void VectorAnimationTask::SetLoopCount(int32_t count)
232 {
233   if(mLoopCount != count)
234   {
235     mLoopCount   = count;
236     mCurrentLoop = 0;
237
238     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetLoopCount: [%d] [%p]\n", count, this);
239   }
240 }
241
242 void VectorAnimationTask::SetPlayRange(const Property::Array& playRange)
243 {
244   bool     valid      = false;
245   uint32_t startFrame = 0, endFrame = 0;
246   size_t   count = playRange.Count();
247
248   if(count >= 2)
249   {
250     int32_t start = 0, end = 0;
251     if(playRange.GetElementAt(0).Get(start) && playRange.GetElementAt(1).Get(end))
252     {
253       startFrame = static_cast<uint32_t>(start);
254       endFrame   = static_cast<uint32_t>(end);
255       valid      = true;
256     }
257     else
258     {
259       std::string startMarker, endMarker;
260       if(playRange.GetElementAt(0).Get(startMarker) && playRange.GetElementAt(1).Get(endMarker))
261       {
262         if(mVectorRenderer)
263         {
264           uint32_t frame; // We don't use this later
265           if(mVectorRenderer.GetMarkerInfo(startMarker, startFrame, frame) && mVectorRenderer.GetMarkerInfo(endMarker, frame, endFrame))
266           {
267             valid = true;
268           }
269         }
270       }
271     }
272   }
273   else if(count == 1)
274   {
275     std::string marker;
276     if(playRange.GetElementAt(0).Get(marker))
277     {
278       if(mVectorRenderer && mVectorRenderer.GetMarkerInfo(marker, startFrame, endFrame))
279       {
280         valid = true;
281       }
282     }
283   }
284
285   if(!valid)
286   {
287     DALI_LOG_ERROR("VectorAnimationTask::SetPlayRange: Invalid range [%p]\n", this);
288     return;
289   }
290
291   // Make sure the range specified is between 0 and the total frame number
292   startFrame = std::min(startFrame, mTotalFrame - 1);
293   endFrame   = std::min(endFrame, mTotalFrame - 1);
294
295   // If the range is not in order swap values
296   if(startFrame > endFrame)
297   {
298     uint32_t temp = startFrame;
299     startFrame    = endFrame;
300     endFrame      = temp;
301   }
302
303   if(startFrame != mStartFrame || endFrame != mEndFrame)
304   {
305     mStartFrame = startFrame;
306     mEndFrame   = endFrame;
307
308     // If the current frame is out of the range, change the current frame also.
309     if(mStartFrame > mCurrentFrame)
310     {
311       mCurrentFrame = mStartFrame;
312     }
313     else if(mEndFrame < mCurrentFrame)
314     {
315       mCurrentFrame = mEndFrame;
316     }
317
318     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetPlayRange: [%d, %d] [%s] [%p]\n", mStartFrame, mEndFrame, mUrl.c_str(), this);
319   }
320 }
321
322 void VectorAnimationTask::GetPlayRange(uint32_t& startFrame, uint32_t& endFrame)
323 {
324   startFrame = mStartFrame;
325   endFrame   = mEndFrame;
326 }
327
328 void VectorAnimationTask::SetCurrentFrameNumber(uint32_t frameNumber)
329 {
330   if(mCurrentFrame == frameNumber)
331   {
332     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetCurrentFrameNumber: Set same frame [%d] [%p]\n", frameNumber, this);
333     return;
334   }
335
336   if(frameNumber >= mStartFrame && frameNumber <= mEndFrame)
337   {
338     mCurrentFrame      = frameNumber;
339     mUpdateFrameNumber = false;
340
341     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetCurrentFrameNumber: frame number = %d [%p]\n", mCurrentFrame, this);
342   }
343   else
344   {
345     DALI_LOG_ERROR("Invalid frame number [%d (%d, %d)] [%p]\n", frameNumber, mStartFrame, mEndFrame, this);
346   }
347 }
348
349 uint32_t VectorAnimationTask::GetCurrentFrameNumber() const
350 {
351   return mCurrentFrame;
352 }
353
354 uint32_t VectorAnimationTask::GetTotalFrameNumber() const
355 {
356   return mTotalFrame;
357 }
358
359 void VectorAnimationTask::GetDefaultSize(uint32_t& width, uint32_t& height) const
360 {
361   mVectorRenderer.GetDefaultSize(width, height);
362 }
363
364 void VectorAnimationTask::SetStopBehavior(DevelImageVisual::StopBehavior::Type stopBehavior)
365 {
366   mStopBehavior = stopBehavior;
367
368   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetStopBehavior: stop behavor = %d [%p]\n", mStopBehavior, this);
369 }
370
371 void VectorAnimationTask::SetLoopingMode(DevelImageVisual::LoopingMode::Type loopingMode)
372 {
373   mLoopingMode = loopingMode;
374
375   DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::SetLoopingMode: looping mode = %d [%p]\n", mLoopingMode, this);
376 }
377
378 void VectorAnimationTask::GetLayerInfo(Property::Map& map) const
379 {
380   mVectorRenderer.GetLayerInfo(map);
381 }
382
383 VectorAnimationTask::ResourceReadySignalType& VectorAnimationTask::ResourceReadySignal()
384 {
385   return mResourceReadySignal;
386 }
387
388 bool VectorAnimationTask::Rasterize(bool& keepAnimation)
389 {
390   bool     stopped = false;
391   uint32_t currentFrame;
392   keepAnimation = false;
393
394   {
395     ConditionalWait::ScopedLock lock(mConditionalWait);
396     if(mDestroyTask)
397     {
398       // The task will be destroyed. We don't need rasterization.
399       return false;
400     }
401
402     if(mLoadRequest)
403     {
404       return Load();
405     }
406   }
407
408   if(mLoadFailed)
409   {
410     return false;
411   }
412
413   ApplyAnimationData();
414
415   if(mPlayState == PlayState::PLAYING && mUpdateFrameNumber)
416   {
417     mCurrentFrame = mForward ? mCurrentFrame + mDroppedFrames + 1 : (mCurrentFrame > mDroppedFrames ? mCurrentFrame - mDroppedFrames - 1 : 0);
418     Dali::ClampInPlace(mCurrentFrame, mStartFrame, mEndFrame);
419   }
420
421   currentFrame = mCurrentFrame;
422
423   mUpdateFrameNumber = true;
424
425   if(mPlayState == PlayState::STOPPING)
426   {
427     mCurrentFrame = GetStoppedFrame(mStartFrame, mEndFrame, mCurrentFrame);
428     currentFrame  = mCurrentFrame;
429     stopped       = true;
430   }
431   else if(mPlayState == PlayState::PLAYING)
432   {
433     bool animationFinished = false;
434
435     if(currentFrame >= mEndFrame) // last frame
436     {
437       if(mLoopingMode == DevelImageVisual::LoopingMode::AUTO_REVERSE)
438       {
439         mForward = false;
440       }
441       else
442       {
443         if(mLoopCount < 0 || ++mCurrentLoop < mLoopCount) // repeat forever or before the last loop
444         {
445           mCurrentFrame      = mStartFrame;
446           mUpdateFrameNumber = false;
447         }
448         else
449         {
450           animationFinished = true; // end of animation
451         }
452       }
453     }
454     else if(currentFrame == mStartFrame && !mForward) // first frame
455     {
456       if(mLoopCount < 0 || ++mCurrentLoop < mLoopCount) // repeat forever or before the last loop
457       {
458         mForward = true;
459       }
460       else
461       {
462         animationFinished = true; // end of animation
463       }
464     }
465
466     if(animationFinished)
467     {
468       if(mStopBehavior == DevelImageVisual::StopBehavior::CURRENT_FRAME)
469       {
470         stopped = true;
471       }
472       else
473       {
474         mPlayState = PlayState::STOPPING;
475       }
476     }
477   }
478
479   // Rasterize
480   bool renderSuccess = false;
481   if(mVectorRenderer)
482   {
483     renderSuccess = mVectorRenderer.Render(currentFrame);
484     if(!renderSuccess)
485     {
486       DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Rasterize: Rendering failed. Try again later.[%d] [%p]\n", currentFrame, this);
487       mUpdateFrameNumber = false;
488     }
489   }
490
491   if(stopped && renderSuccess)
492   {
493     mPlayState   = PlayState::STOPPED;
494     mForward     = true;
495     mCurrentLoop = 0;
496
497     // Animation is finished
498     {
499       ConditionalWait::ScopedLock lock(mConditionalWait);
500       if(mNeedAnimationFinishedTrigger && mAnimationFinishedTrigger)
501       {
502         mAnimationFinishedTrigger->Trigger();
503       }
504     }
505
506     DALI_LOG_INFO(gVectorAnimationLogFilter, Debug::Verbose, "VectorAnimationTask::Rasterize: Animation is finished [current = %d] [%p]\n", currentFrame, this);
507   }
508
509   if(mPlayState != PlayState::PAUSED && mPlayState != PlayState::STOPPED)
510   {
511     keepAnimation = true;
512   }
513
514   return true;
515 }
516
517 uint32_t VectorAnimationTask::GetStoppedFrame(uint32_t startFrame, uint32_t endFrame, uint32_t currentFrame)
518 {
519   uint32_t frame = currentFrame;
520
521   switch(mStopBehavior)
522   {
523     case DevelImageVisual::StopBehavior::FIRST_FRAME:
524     {
525       frame = startFrame;
526       break;
527     }
528     case DevelImageVisual::StopBehavior::LAST_FRAME:
529     {
530       if(mLoopingMode == DevelImageVisual::LoopingMode::AUTO_REVERSE)
531       {
532         frame = startFrame;
533       }
534       else
535       {
536         frame = endFrame;
537       }
538       break;
539     }
540     case DevelImageVisual::StopBehavior::CURRENT_FRAME:
541     {
542       frame = currentFrame;
543       break;
544     }
545   }
546
547   return frame;
548 }
549
550 VectorAnimationTask::TimePoint VectorAnimationTask::CalculateNextFrameTime(bool renderNow)
551 {
552   // std::chrono::time_point template has second parameter duration which defaults to the std::chrono::steady_clock supported
553   // duration. In some C++11 implementations it is a milliseconds duration, so it fails to compile unless mNextFrameStartTime
554   // is casted to use the default duration.
555   mNextFrameStartTime = std::chrono::time_point_cast<TimePoint::duration>(mNextFrameStartTime + std::chrono::microseconds(mFrameDurationMicroSeconds));
556   auto current        = std::chrono::steady_clock::now();
557   mDroppedFrames      = 0;
558
559   if(renderNow)
560   {
561     mNextFrameStartTime = current;
562   }
563   else if(mNextFrameStartTime < current)
564   {
565     uint32_t droppedFrames = 0;
566
567     while(current > std::chrono::time_point_cast<TimePoint::duration>(mNextFrameStartTime + std::chrono::microseconds(mFrameDurationMicroSeconds)) && droppedFrames < mTotalFrame)
568     {
569       droppedFrames++;
570       mNextFrameStartTime = std::chrono::time_point_cast<TimePoint::duration>(mNextFrameStartTime + std::chrono::microseconds(mFrameDurationMicroSeconds));
571     }
572
573     mNextFrameStartTime = current;
574     mDroppedFrames      = droppedFrames;
575   }
576
577   return mNextFrameStartTime;
578 }
579
580 VectorAnimationTask::TimePoint VectorAnimationTask::GetNextFrameTime()
581 {
582   return mNextFrameStartTime;
583 }
584
585 void VectorAnimationTask::ApplyAnimationData()
586 {
587   uint32_t index;
588
589   {
590     ConditionalWait::ScopedLock lock(mConditionalWait);
591
592     if(!mAnimationDataUpdated || mAnimationData[mAnimationDataIndex].resendFlag != 0)
593     {
594       // Data is not updated or the previous data is not applied yet.
595       return;
596     }
597
598     mAnimationDataIndex   = mAnimationDataIndex == 0 ? 1 : 0; // Swap index
599     mAnimationDataUpdated = false;
600
601     index = mAnimationDataIndex;
602   }
603
604   if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_LOOP_COUNT)
605   {
606     SetLoopCount(mAnimationData[index].loopCount);
607   }
608
609   if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_PLAY_RANGE)
610   {
611     SetPlayRange(mAnimationData[index].playRange);
612   }
613
614   if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_STOP_BEHAVIOR)
615   {
616     SetStopBehavior(mAnimationData[index].stopBehavior);
617   }
618
619   if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_LOOPING_MODE)
620   {
621     SetLoopingMode(mAnimationData[index].loopingMode);
622   }
623
624   if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_CURRENT_FRAME)
625   {
626     SetCurrentFrameNumber(mAnimationData[index].currentFrame);
627   }
628
629   if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_NEED_RESOURCE_READY)
630   {
631     mVectorRenderer.InvalidateBuffer();
632   }
633
634   if(mAnimationData[index].resendFlag & VectorAnimationTask::RESEND_PLAY_STATE)
635   {
636     if(mAnimationData[index].playState == DevelImageVisual::PlayState::PLAYING)
637     {
638       PlayAnimation();
639     }
640     else if(mAnimationData[index].playState == DevelImageVisual::PlayState::PAUSED)
641     {
642       PauseAnimation();
643     }
644     else if(mAnimationData[index].playState == DevelImageVisual::PlayState::STOPPED)
645     {
646       StopAnimation();
647     }
648   }
649
650   mAnimationData[index].resendFlag = 0;
651 }
652
653 void VectorAnimationTask::OnUploadCompleted()
654 {
655   mResourceReadySignal.Emit(ResourceStatus::READY);
656 }
657
658 void VectorAnimationTask::OnLoadCompleted()
659 {
660   if(!mLoadFailed)
661   {
662     mResourceReadySignal.Emit(ResourceStatus::LOADED);
663   }
664   else
665   {
666     mResourceReadySignal.Emit(ResourceStatus::FAILED);
667   }
668 }
669 } // namespace Internal
670
671 } // namespace Toolkit
672
673 } // namespace Dali