2 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "combined-update-render-controller.h"
23 #include <dali/integration-api/platform-abstraction.h>
26 #include <trigger-event-factory.h>
27 #include <base/combined-update-render/combined-update-render-controller-debug.h>
28 #include <base/environment-options.h>
29 #include <base/time-service.h>
30 #include <base/interfaces/adaptor-internal-services.h>
43 const unsigned int CREATED_THREAD_COUNT = 1u;
45 const int CONTINUOUS = -1;
48 const unsigned int TRUE = 1u;
49 const unsigned int FALSE = 0u;
51 const unsigned int MILLISECONDS_PER_SECOND( 1e+3 );
52 const float NANOSECONDS_TO_SECOND( 1e-9f );
53 const unsigned int NANOSECONDS_PER_SECOND( 1e+9 );
54 const unsigned int NANOSECONDS_PER_MILLISECOND( 1e+6 );
56 // The following values will get calculated at compile time
57 const float DEFAULT_FRAME_DURATION_IN_SECONDS( 1.0f / 60.0f );
58 const unsigned int DEFAULT_FRAME_DURATION_IN_MILLISECONDS( DEFAULT_FRAME_DURATION_IN_SECONDS * MILLISECONDS_PER_SECOND );
59 const unsigned int DEFAULT_FRAME_DURATION_IN_NANOSECONDS( DEFAULT_FRAME_DURATION_IN_SECONDS * NANOSECONDS_PER_SECOND );
62 * Handles the use case when an update-request is received JUST before we process a sleep-request. If we did not have an update-request count then
63 * there is a danger that, on the event-thread we could have:
64 * 1) An update-request where we do nothing as Update/Render thread still running.
65 * 2) Quickly followed by a sleep-request being handled where we pause the Update/Render Thread (even though we have an update to process).
67 * Using a counter means we increment the counter on an update-request, and decrement it on a sleep-request. This handles the above scenario because:
68 * 1) MAIN THREAD: Update Request: COUNTER = 1
69 * 2) UPDATE/RENDER THREAD: Do Update/Render, then no Updates required -> Sleep Trigger
70 * 3) MAIN THREAD: Update Request: COUNTER = 2
71 * 4) MAIN THREAD: Sleep Request: COUNTER = 1 -> We do not sleep just yet
73 * Also ensures we preserve battery life by only doing ONE update when the above use case is not triggered.
74 * 1) MAIN THREAD: Update Request: COUNTER = 1
75 * 2) UPDATE/RENDER THREAD: Do Update/Render, then no Updates required -> Sleep Trigger
76 * 3) MAIN THREAD: Sleep Request: COUNTER = 0 -> Go to sleep
78 const unsigned int MAXIMUM_UPDATE_REQUESTS = 2;
79 } // unnamed namespace
81 ///////////////////////////////////////////////////////////////////////////////////////////////////
83 ///////////////////////////////////////////////////////////////////////////////////////////////////
85 CombinedUpdateRenderController::CombinedUpdateRenderController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions )
86 : mFpsTracker( environmentOptions ),
87 mUpdateStatusLogger( environmentOptions ),
88 mRenderHelper( adaptorInterfaces ),
89 mEventThreadSemaphore(),
90 mUpdateRenderThreadWaitCondition(),
91 mAdaptorInterfaces( adaptorInterfaces ),
92 mPerformanceInterface( adaptorInterfaces.GetPerformanceInterface() ),
93 mCore( adaptorInterfaces.GetCore() ),
94 mEnvironmentOptions( environmentOptions ),
95 mNotificationTrigger( adaptorInterfaces.GetProcessCoreEventsTrigger() ),
96 mSleepTrigger( NULL ),
97 mUpdateRenderThread( NULL ),
98 mDefaultFrameDelta( 0.0f ),
99 mDefaultFrameDurationMilliseconds( 0u ),
100 mDefaultFrameDurationNanoseconds( 0u ),
101 mDefaultHalfFrameNanoseconds( 0u ),
102 mUpdateRequestCount( 0u ),
104 mUpdateRenderRunCount( 0 ),
105 mDestroyUpdateRenderThread( FALSE ),
106 mUpdateRenderThreadCanSleep( FALSE ),
107 mPendingRequestUpdate( FALSE ),
109 mPostRendering( FALSE )
113 // Initialise frame delta/duration variables first
114 SetRenderRefreshRate( environmentOptions.GetRenderRefreshRate() );
116 // Set the thread-synchronization interface on the render-surface
117 RenderSurface* currentSurface = mAdaptorInterfaces.GetRenderSurfaceInterface();
120 currentSurface->SetThreadSynchronization( *this );
123 TriggerEventFactoryInterface& triggerFactory = mAdaptorInterfaces.GetTriggerEventFactoryInterface();
124 mSleepTrigger = triggerFactory.CreateTriggerEvent( MakeCallback( this, &CombinedUpdateRenderController::ProcessSleepRequest ), TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER );
126 sem_init( &mEventThreadSemaphore, 0, 0 ); // Initialize to 0 so that it just waits if sem_post has not been called
129 CombinedUpdateRenderController::~CombinedUpdateRenderController()
135 delete mSleepTrigger;
138 void CombinedUpdateRenderController::Initialize()
142 // Ensure Update/Render Thread not already created
143 DALI_ASSERT_ALWAYS( ! mUpdateRenderThread );
145 // Create Update/Render Thread
146 mUpdateRenderThread = new pthread_t();
147 int error = pthread_create( mUpdateRenderThread, NULL, InternalUpdateRenderThreadEntryFunc, this );
148 DALI_ASSERT_ALWAYS( !error && "Return code from pthread_create() when creating UpdateRenderThread" );
150 // The Update/Render thread will now run and initialise EGL etc. and will then wait for Start to be called
151 // When this function returns, the application initialisation on the event thread should occur
154 void CombinedUpdateRenderController::Start()
158 DALI_ASSERT_ALWAYS( !mRunning && mUpdateRenderThread );
160 // Wait until all threads created in Initialise are up and running
161 for( unsigned int i = 0; i < CREATED_THREAD_COUNT; ++i )
163 sem_wait( &mEventThreadSemaphore );
166 mRenderHelper.Start();
170 LOG_EVENT( "Startup Complete, starting Update/Render Thread" );
172 RunUpdateRenderThread( CONTINUOUS, false /* No animation progression */ );
175 void CombinedUpdateRenderController::Pause()
181 PauseUpdateRenderThread();
183 AddPerformanceMarker( PerformanceInterface::PAUSED );
186 void CombinedUpdateRenderController::Resume()
190 if( !mRunning && IsUpdateRenderThreadPaused() )
192 LOG_EVENT( "Resuming" );
194 RunUpdateRenderThread( CONTINUOUS, true /* Animation progression required while we were paused */ );
196 AddPerformanceMarker( PerformanceInterface::RESUME );
202 void CombinedUpdateRenderController::Stop()
206 // Stop Rendering and the Update/Render Thread
207 mRenderHelper.Stop();
209 StopUpdateRenderThread();
211 if( mUpdateRenderThread )
213 LOG_EVENT( "Destroying UpdateRenderThread" );
215 // wait for the thread to finish
216 pthread_join( *mUpdateRenderThread, NULL );
218 delete mUpdateRenderThread;
219 mUpdateRenderThread = NULL;
225 void CombinedUpdateRenderController::RequestUpdate()
229 // Increment the update-request count to the maximum
230 if( mUpdateRequestCount < MAXIMUM_UPDATE_REQUESTS )
232 ++mUpdateRequestCount;
235 if( mRunning && IsUpdateRenderThreadPaused() )
237 LOG_EVENT( "Processing" );
239 RunUpdateRenderThread( CONTINUOUS, false /* No animation progression */ );
242 ConditionalWait::ScopedLock updateLock( mUpdateRenderThreadWaitCondition );
243 mPendingRequestUpdate = TRUE;
246 void CombinedUpdateRenderController::RequestUpdateOnce()
248 if( IsUpdateRenderThreadPaused() )
252 // Run Update/Render once
253 RunUpdateRenderThread( ONCE, false /* No animation progression */ );
257 void CombinedUpdateRenderController::ReplaceSurface( RenderSurface* newSurface )
261 // Set the ThreadSyncronizationInterface on the new surface
262 newSurface->SetThreadSynchronization( *this );
264 LOG_EVENT( "Starting to replace the surface, event-thread blocked" );
266 // Start replacing the surface.
268 ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
269 mPostRendering = FALSE; // Clear the post-rendering flag as Update/Render thread will replace the surface now
270 mNewSurface = newSurface;
271 mUpdateRenderThreadWaitCondition.Notify( lock );
274 // Wait until the surface has been replaced
275 sem_wait( &mEventThreadSemaphore );
277 LOG_EVENT( "Surface replaced, event-thread continuing" );
280 void CombinedUpdateRenderController::SetRenderRefreshRate( unsigned int numberOfFramesPerRender )
282 // Not protected by lock, but written to rarely so not worth adding a lock when reading
283 mDefaultFrameDelta = numberOfFramesPerRender * DEFAULT_FRAME_DURATION_IN_SECONDS;
284 mDefaultFrameDurationMilliseconds = (uint64_t)numberOfFramesPerRender * DEFAULT_FRAME_DURATION_IN_MILLISECONDS;
285 mDefaultFrameDurationNanoseconds = (uint64_t)numberOfFramesPerRender * DEFAULT_FRAME_DURATION_IN_NANOSECONDS;
286 mDefaultHalfFrameNanoseconds = mDefaultFrameDurationNanoseconds / 2;
288 LOG_EVENT( "mDefaultFrameDelta(%.6f), mDefaultFrameDurationMilliseconds(%lld), mDefaultFrameDurationNanoseconds(%lld)", mDefaultFrameDelta, mDefaultFrameDurationMilliseconds, mDefaultFrameDurationNanoseconds );
291 ///////////////////////////////////////////////////////////////////////////////////////////////////
293 ///////////////////////////////////////////////////////////////////////////////////////////////////
295 void CombinedUpdateRenderController::RunUpdateRenderThread( int numberOfCycles, bool useElapsedTime )
297 ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
298 mUpdateRenderRunCount = numberOfCycles;
299 mUpdateRenderThreadCanSleep = FALSE;
300 mUseElapsedTimeAfterWait = useElapsedTime;
301 LOG_COUNTER_EVENT( "mUpdateRenderRunCount: %d, mUseElapsedTimeAfterWait: %d", mUpdateRenderRunCount, mUseElapsedTimeAfterWait );
302 mUpdateRenderThreadWaitCondition.Notify( lock );
305 void CombinedUpdateRenderController::PauseUpdateRenderThread()
307 ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
308 mUpdateRenderRunCount = 0;
311 void CombinedUpdateRenderController::StopUpdateRenderThread()
313 ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
314 mDestroyUpdateRenderThread = TRUE;
315 mUpdateRenderThreadWaitCondition.Notify( lock );
318 bool CombinedUpdateRenderController::IsUpdateRenderThreadPaused()
320 ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
321 return ( mUpdateRenderRunCount != CONTINUOUS ) || // Report paused if NOT continuously running
322 mUpdateRenderThreadCanSleep; // Report paused if sleeping
325 void CombinedUpdateRenderController::ProcessSleepRequest()
329 // Decrement Update request count
330 if( mUpdateRequestCount > 0 )
332 --mUpdateRequestCount;
335 // Can sleep if our update-request count is 0
336 // Update/Render thread can choose to carry on updating if it determines more update/renders are required
337 if( mUpdateRequestCount == 0 )
339 LOG_EVENT( "Going to sleep" );
341 ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
342 mUpdateRenderThreadCanSleep = TRUE;
346 ///////////////////////////////////////////////////////////////////////////////////////////////////
347 // UPDATE/RENDER THREAD
348 ///////////////////////////////////////////////////////////////////////////////////////////////////
350 void CombinedUpdateRenderController::UpdateRenderThread()
352 // Install a function for logging
353 mEnvironmentOptions.InstallLogFunction();
355 LOG_UPDATE_RENDER( "THREAD CREATED" );
357 mRenderHelper.InitializeEgl();
359 // tell core it has a context
360 mCore.ContextCreated();
362 NotifyThreadInitialised();
365 uint64_t lastFrameTime;
366 TimeService::GetNanoseconds( lastFrameTime );
368 LOG_UPDATE_RENDER( "THREAD INITIALISED" );
370 bool useElapsedTime = true;
371 bool updateRequired = true;
373 while( UpdateRenderReady( useElapsedTime, updateRequired ) )
375 LOG_UPDATE_RENDER_TRACE;
377 // Performance statistics are logged upon a VSYNC tick so use this point for a VSync marker
378 AddPerformanceMarker( PerformanceInterface::VSYNC );
380 uint64_t currentFrameStartTime = 0;
381 TimeService::GetNanoseconds( currentFrameStartTime );
383 const uint64_t timeSinceLastFrame = currentFrameStartTime - lastFrameTime;
385 // Optional FPS Tracking when continuously rendering
386 if( useElapsedTime && mFpsTracker.Enabled() )
388 float absoluteTimeSinceLastRender = timeSinceLastFrame * NANOSECONDS_TO_SECOND;
389 mFpsTracker.Track( absoluteTimeSinceLastRender );
392 lastFrameTime = currentFrameStartTime; // Store frame start time
394 //////////////////////////////
396 //////////////////////////////
398 RenderSurface* newSurface = ShouldSurfaceBeReplaced();
399 if( DALI_UNLIKELY( newSurface ) )
401 LOG_UPDATE_RENDER_TRACE_FMT( "Replacing Surface" );
402 mRenderHelper.ReplaceSurface( newSurface );
406 //////////////////////////////
408 //////////////////////////////
410 const unsigned int currentTime = currentFrameStartTime / NANOSECONDS_PER_MILLISECOND;
411 const unsigned int nextFrameTime = currentTime + mDefaultFrameDurationMilliseconds;
413 uint64_t noOfFramesSinceLastUpdate = 1;
414 float frameDelta = 0.0f;
417 // If using the elapsed time, then calculate frameDelta as a multiple of mDefaultFrameDelta
418 // Round up if remainder is more than half the default frame time
419 noOfFramesSinceLastUpdate = ( timeSinceLastFrame + mDefaultHalfFrameNanoseconds) / mDefaultFrameDurationNanoseconds;
420 frameDelta = mDefaultFrameDelta * noOfFramesSinceLastUpdate;
422 LOG_UPDATE_RENDER( "timeSinceLastFrame(%llu) noOfFramesSinceLastUpdate(%u) frameDelta(%.6f)", timeSinceLastFrame, noOfFramesSinceLastUpdate, frameDelta );
424 Integration::UpdateStatus updateStatus;
426 AddPerformanceMarker( PerformanceInterface::UPDATE_START );
427 mCore.Update( frameDelta, currentTime, nextFrameTime, updateStatus );
428 AddPerformanceMarker( PerformanceInterface::UPDATE_END );
430 unsigned int keepUpdatingStatus = updateStatus.KeepUpdating();
432 // Tell the event-thread to wake up (if asleep) and send a notification event to Core if required
433 if( updateStatus.NeedsNotification() )
435 mNotificationTrigger.Trigger();
436 LOG_UPDATE_RENDER( "Notification Triggered" );
439 // Optional logging of update/render status
440 mUpdateStatusLogger.Log( keepUpdatingStatus );
442 //////////////////////////////
444 //////////////////////////////
446 mRenderHelper.ConsumeEvents();
447 mRenderHelper.PreRender();
449 Integration::RenderStatus renderStatus;
451 AddPerformanceMarker( PerformanceInterface::RENDER_START );
452 mCore.Render( renderStatus );
453 AddPerformanceMarker( PerformanceInterface::RENDER_END );
455 if( renderStatus.HasRendered() )
457 mRenderHelper.PostRender();
460 // Trigger event thread to request Update/Render thread to sleep if update not required
461 if( ( Integration::KeepUpdating::NOT_REQUESTED == keepUpdatingStatus ) &&
462 ! renderStatus.NeedsUpdate() )
464 mSleepTrigger->Trigger();
465 updateRequired = false;
466 LOG_UPDATE_RENDER( "Sleep Triggered" );
470 updateRequired = true;
473 //////////////////////////////
475 //////////////////////////////
477 // Sleep until at least the the default frame duration has elapsed. This will return immediately if the specified end-time has already passed.
478 TimeService::SleepUntil( currentFrameStartTime + mDefaultFrameDurationNanoseconds );
481 // Inform core of context destruction & shutdown EGL
482 mCore.ContextDestroyed();
483 mRenderHelper.ShutdownEgl();
485 LOG_UPDATE_RENDER( "THREAD DESTROYED" );
487 // Uninstall the logging function
488 mEnvironmentOptions.UnInstallLogFunction();
491 bool CombinedUpdateRenderController::UpdateRenderReady( bool& useElapsedTime, bool updateRequired )
493 useElapsedTime = true;
495 ConditionalWait::ScopedLock updateLock( mUpdateRenderThreadWaitCondition );
496 while( ( ! mUpdateRenderRunCount || // Should try to wait if event-thread has paused the Update/Render thread
497 ( mUpdateRenderThreadCanSleep && ! updateRequired && ! mPendingRequestUpdate ) ) && // Ensure we wait if we're supposed to be sleeping AND do not require another update
498 ! mDestroyUpdateRenderThread && // Ensure we don't wait if the update-render-thread is supposed to be destroyed
499 ! mNewSurface ) // Ensure we don't wait if we need to replace the surface
501 LOG_UPDATE_RENDER( "WAIT: mUpdateRenderRunCount: %d", mUpdateRenderRunCount );
502 LOG_UPDATE_RENDER( " mUpdateRenderThreadCanSleep: %d, updateRequired: %d, mPendingRequestUpdate: %d", mUpdateRenderThreadCanSleep, updateRequired, mPendingRequestUpdate );
503 LOG_UPDATE_RENDER( " mDestroyUpdateRenderThread: %d", mDestroyUpdateRenderThread );
504 LOG_UPDATE_RENDER( " mNewSurface: %d", mNewSurface );
506 mUpdateRenderThreadWaitCondition.Wait( updateLock );
508 if( ! mUseElapsedTimeAfterWait )
510 useElapsedTime = false;
514 LOG_COUNTER_UPDATE_RENDER( "mUpdateRenderRunCount: %d", mUpdateRenderRunCount );
515 LOG_COUNTER_UPDATE_RENDER( "mUpdateRenderThreadCanSleep: %d, updateRequired: %d, mPendingRequestUpdate: %d", mUpdateRenderThreadCanSleep, updateRequired, mPendingRequestUpdate );
516 LOG_COUNTER_UPDATE_RENDER( "mDestroyUpdateRenderThread: %d", mDestroyUpdateRenderThread );
517 LOG_COUNTER_UPDATE_RENDER( "mNewSurface: %d", mNewSurface );
519 mUseElapsedTimeAfterWait = FALSE;
520 mUpdateRenderThreadCanSleep = FALSE;
521 mPendingRequestUpdate = FALSE;
523 // If we've been asked to run Update/Render cycles a finite number of times then decrement so we wait after the
524 // requested number of cycles
525 if( mUpdateRenderRunCount > 0 )
527 --mUpdateRenderRunCount;
530 // Keep the update-render thread alive if this thread is NOT to be destroyed
531 return ! mDestroyUpdateRenderThread;
534 RenderSurface* CombinedUpdateRenderController::ShouldSurfaceBeReplaced()
536 ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
538 RenderSurface* newSurface = mNewSurface;
544 void CombinedUpdateRenderController::SurfaceReplaced()
546 // Just increment the semaphore
547 sem_post( &mEventThreadSemaphore );
550 ///////////////////////////////////////////////////////////////////////////////////////////////////
552 ///////////////////////////////////////////////////////////////////////////////////////////////////
554 void CombinedUpdateRenderController::NotifyThreadInitialised()
556 // Just increment the semaphore
557 sem_post( &mEventThreadSemaphore );
560 void CombinedUpdateRenderController::AddPerformanceMarker( PerformanceInterface::MarkerType type )
562 if( mPerformanceInterface )
564 mPerformanceInterface->AddMarker( type );
568 /////////////////////////////////////////////////////////////////////////////////////////////////
569 // POST RENDERING: EVENT THREAD
570 /////////////////////////////////////////////////////////////////////////////////////////////////
572 void CombinedUpdateRenderController::PostRenderComplete()
574 ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
575 mPostRendering = FALSE;
576 mUpdateRenderThreadWaitCondition.Notify( lock );
579 ///////////////////////////////////////////////////////////////////////////////////////////////////
580 // POST RENDERING: RENDER THREAD
581 ///////////////////////////////////////////////////////////////////////////////////////////////////
583 void CombinedUpdateRenderController::PostRenderStarted()
585 ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
586 mPostRendering = TRUE;
589 void CombinedUpdateRenderController::PostRenderWaitForCompletion()
591 ConditionalWait::ScopedLock lock( mUpdateRenderThreadWaitCondition );
592 while( mPostRendering &&
593 ! mNewSurface ) // We should NOT wait if we're replacing the surface
595 mUpdateRenderThreadWaitCondition.Wait( lock );
599 } // namespace Adaptor
601 } // namespace Internal