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