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