1 #ifndef DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H
2 #define DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H
5 * Copyright (c) 2018 Samsung Electronics Co., Ltd.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
22 #include <semaphore.h>
24 #include <dali/integration-api/core.h>
25 #include <dali/devel-api/threading/conditional-wait.h>
28 #include <dali/integration-api/thread-synchronization-interface.h>
29 #include <dali/internal/system/common/performance-interface.h>
30 #include <dali/internal/system/common/fps-tracker.h>
31 #include <dali/internal/adaptor/common/thread-controller-interface.h>
32 #include <dali/internal/system/common/update-status-logger.h>
33 #include <dali/internal/window-system/common/display-connection.h>
39 class RenderSurfaceInterface;
40 class TriggerEventInterface;
48 class AdaptorInternalServices;
49 class EnvironmentOptions;
52 * @brief Two threads where events/application interaction is handled on the main/event thread and the Update & Render
53 * happen on the other thread.
57 * a. Main/Event Thread.
58 * b. Update/Render Thread.
59 * 2. There is NO VSync thread:
60 * a. We retrieve the time before Update.
61 * b. Then retrieve the time after Render.
62 * c. We calculate the difference between these two times and if:
63 * i. The difference is less than the default frame time, we sleep.
64 * ii. If it’s more or the same, we continue.
65 * 3. On the update/render thread, if we discover that we do not need to do any more updates, we use a trigger-event
66 * to inform the main/event thread. This is then processed as soon as the event thread is able to do so where it
67 * is easier to make a decision about whether we should stop the update/render thread or not (depending on any
68 * update requests etc.).
69 * 4. The main thread is blocked while the surface is being replaced.
70 * 5. When we resume from paused, elapsed time is used for the animations, i.e. the could have finished while we were paused.
71 * However, FinishedSignal emission will only happen upon resumption.
72 * 6. Elapsed time is NOT used while if we are waking up from a sleep state or doing an UpdateOnce.
74 class CombinedUpdateRenderController : public ThreadControllerInterface,
75 public ThreadSynchronizationInterface
82 CombinedUpdateRenderController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions );
85 * Non virtual destructor. Not intended as base class.
87 ~CombinedUpdateRenderController();
90 * @copydoc ThreadControllerInterface::Initialize()
92 virtual void Initialize();
95 * @copydoc ThreadControllerInterface::Start()
100 * @copydoc ThreadControllerInterface::Pause()
102 virtual void Pause();
105 * @copydoc ThreadControllerInterface::Resume()
107 virtual void Resume();
110 * @copydoc ThreadControllerInterface::Stop()
115 * @copydoc ThreadControllerInterface::RequestUpdate()
117 virtual void RequestUpdate();
120 * @copydoc ThreadControllerInterface::RequestUpdateOnce()
122 virtual void RequestUpdateOnce();
125 * @copydoc ThreadControllerInterface::ReplaceSurface()
127 virtual void ReplaceSurface( Dali::RenderSurfaceInterface* surface );
130 * @copydoc ThreadControllerInterface::DeleteSurface()
132 virtual void DeleteSurface( Dali::RenderSurfaceInterface* surface );
135 * @copydoc ThreadControllerInterface::ResizeSurface()
137 virtual void ResizeSurface();
140 * @copydoc ThreadControllerInterface::SetRenderRefreshRate()
142 virtual void SetRenderRefreshRate( unsigned int numberOfFramesPerRender );
145 * @copydoc ThreadControllerInterface::SetPreRenderCallback
147 void SetPreRenderCallback( CallbackBase* callback ) override;
151 // Undefined copy constructor.
152 CombinedUpdateRenderController( const CombinedUpdateRenderController& );
154 // Undefined assignment operator.
155 CombinedUpdateRenderController& operator=( const CombinedUpdateRenderController& );
157 /////////////////////////////////////////////////////////////////////////////////////////////////
159 /////////////////////////////////////////////////////////////////////////////////////////////////
162 * Runs the Update/Render Thread.
163 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
165 * @param[in] numberOfCycles The number of times the update/render cycle should run. If -1, then it will run continuously.
166 * @param[in] useElapsedTimeAfterWait If true, then the elapsed time during wait is used for animations, otherwise no animation progression is made.
168 inline void RunUpdateRenderThread( int numberOfCycles, bool useElapsedTimeAfterWait );
171 * Pauses the Update/Render Thread.
172 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
174 inline void PauseUpdateRenderThread();
177 * Stops the Update/Render Thread.
178 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
180 * @note Should only be called in Stop as calling this will kill the update-thread.
182 inline void StopUpdateRenderThread();
185 * Checks if the the Update/Render Thread is paused.
186 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
188 * @return true if paused, false otherwise
190 inline bool IsUpdateRenderThreadPaused();
193 * Used as the callback for the sleep-trigger.
195 * Will sleep when enough requests are made without any requests.
197 void ProcessSleepRequest();
199 /////////////////////////////////////////////////////////////////////////////////////////////////
200 // UpdateRenderThread
201 /////////////////////////////////////////////////////////////////////////////////////////////////
204 * The Update/Render thread loop. This thread will be destroyed on exit from this function.
206 void UpdateRenderThread();
209 * Called by the Update/Render Thread which ensures a wait if required.
211 * @param[out] useElapsedTime If true when returned, then the actual elapsed time will be used for animation.
212 * If false when returned, then there should NOT be any animation progression in the next Update.
213 * @param[in] updateRequired Whether another update is required.
214 * @param[out] timeToSleepUntil The time remaining in nanoseconds to keep the thread sleeping before resuming.
215 * @return false, if the thread should stop.
217 bool UpdateRenderReady( bool& useElapsedTime, bool updateRequired, uint64_t& timeToSleepUntil );
220 * Checks to see if the surface needs to be replaced.
221 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
223 * @return Pointer to the new surface, NULL otherwise
225 Integration::RenderSurface* ShouldSurfaceBeReplaced();
228 * Called by the Update/Render thread after a surface has been replaced.
230 * This will lock the mutex in mEventThreadWaitCondition
232 void SurfaceReplaced();
235 * Checks to see if the surface needs to be deleted.
236 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
238 * @return Pointer to the deleted surface, nullptr otherwise
240 Integration::RenderSurface* ShouldSurfaceBeDeleted();
243 * Called by the Update/Render thread after a surface has been deleted.
245 * This will lock the mutex in mEventThreadWaitCondition
247 void SurfaceDeleted();
250 * Checks to see if the surface needs to be resized.
251 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
253 * @return true if the surface should be resized, false otherwise
255 bool ShouldSurfaceBeResized();
258 * Called by the Update/Render thread after a surface has been resized.
260 * This will lock the mutex in mEventThreadWaitCondition
262 void SurfaceResized();
265 * Helper for the thread calling the entry function
266 * @param[in] This A pointer to the current object
268 static void* InternalUpdateRenderThreadEntryFunc( void* This )
270 ( static_cast<CombinedUpdateRenderController*>( This ) )->UpdateRenderThread();
274 /////////////////////////////////////////////////////////////////////////////////////////////////
276 /////////////////////////////////////////////////////////////////////////////////////////////////
279 * Called by the update-render & v-sync threads when they up and running.
281 * This will lock the mutex in mEventThreadWaitCondition.
283 void NotifyThreadInitialised();
286 * Helper to add a performance marker to the performance server (if it's active)
287 * @param[in] type performance marker type
289 void AddPerformanceMarker( PerformanceInterface::MarkerType type );
291 /////////////////////////////////////////////////////////////////////////////////////////////////
292 // POST RENDERING - ThreadSynchronizationInterface overrides
293 /////////////////////////////////////////////////////////////////////////////////////////////////
295 /////////////////////////////////////////////////////////////////////////////////////////////////
296 //// Called by the Event Thread if post-rendering is required
297 /////////////////////////////////////////////////////////////////////////////////////////////////
300 * @copydoc ThreadSynchronizationInterface::PostRenderComplete()
302 virtual void PostRenderComplete();
304 /////////////////////////////////////////////////////////////////////////////////////////////////
305 //// Called by the Render Thread if post-rendering is required
306 /////////////////////////////////////////////////////////////////////////////////////////////////
309 * @copydoc ThreadSynchronizationInterface::PostRenderStarted()
311 virtual void PostRenderStarted();
314 * @copydoc ThreadSynchronizationInterface::PostRenderStarted()
316 virtual void PostRenderWaitForCompletion();
320 FpsTracker mFpsTracker; ///< Object that tracks the FPS
321 UpdateStatusLogger mUpdateStatusLogger; ///< Object that logs the update-status as required.
323 sem_t mEventThreadSemaphore; ///< Used by the event thread to ensure all threads have been initialised, and when replacing the surface.
325 ConditionalWait mUpdateRenderThreadWaitCondition; ///< The wait condition for the update-render-thread.
327 AdaptorInternalServices& mAdaptorInterfaces; ///< The adaptor internal interface
328 PerformanceInterface* mPerformanceInterface; ///< The performance logging interface
329 Integration::Core& mCore; ///< Dali core reference
330 const EnvironmentOptions& mEnvironmentOptions; ///< Environment options
331 TriggerEventInterface& mNotificationTrigger; ///< Reference to notification event trigger
332 TriggerEventInterface* mSleepTrigger; ///< Used by the update-render thread to trigger the event thread when it no longer needs to do any updates
333 CallbackBase* mPreRenderCallback; ///< Used by Update/Render thread when PreRender is about to be called on graphics.
335 pthread_t* mUpdateRenderThread; ///< The Update/Render thread.
337 float mDefaultFrameDelta; ///< Default time delta between each frame (used for animations). Not protected by lock, but written to rarely so not worth adding a lock when reading.
338 // TODO: mDefaultFrameDurationMilliseconds is defined as uint64_t, the only place where it is used, it is converted to an unsigned int!!!
339 uint64_t mDefaultFrameDurationMilliseconds; ///< Default duration of a frame (used for predicting the time of the next frame). Not protected by lock, but written to rarely so not worth adding a lock when reading.
340 uint64_t mDefaultFrameDurationNanoseconds; ///< Default duration of a frame (used for sleeping if not enough time elapsed). Not protected by lock, but written to rarely so not worth adding a lock when reading.
341 uint64_t mDefaultHalfFrameNanoseconds; ///< Is half of mDefaultFrameDurationNanoseconds. Using a member variable avoids having to do the calculation every frame. Not protected by lock, but written to rarely so not worth adding a lock when reading.
343 unsigned int mUpdateRequestCount; ///< Count of update-requests we have received to ensure we do not go to sleep too early.
344 unsigned int mRunning; ///< Read and set on the event-thread only to state whether we are running.
347 // NOTE: cannot use booleans as these are used from multiple threads, must use variable with machine word size for atomic read/write
350 volatile int mUpdateRenderRunCount; ///< The number of times Update/Render cycle should run. If -1, then will run continuously (set by the event-thread, read by v-sync-thread).
351 volatile unsigned int mDestroyUpdateRenderThread; ///< Whether the Update/Render thread be destroyed (set by the event-thread, read by the update-render-thread).
352 volatile unsigned int mUpdateRenderThreadCanSleep; ///< Whether the Update/Render thread can sleep (set by the event-thread, read by the update-render-thread).
353 volatile unsigned int mPendingRequestUpdate; ///< Is set as soon as an RequestUpdate is made and unset when the next update happens (set by the event-thread and update-render thread, read by the update-render-thread).
354 ///< Ensures we do not go to sleep if we have not processed the most recent update-request.
356 volatile unsigned int mUseElapsedTimeAfterWait; ///< Whether we should use the elapsed time after waiting (set by the event-thread, read by the update-render-thread).
358 Integration::RenderSurface* volatile mNewSurface; ///< Will be set to the new-surface if requested (set by the event-thread, read & cleared by the update-render thread).
359 Integration::RenderSurface* volatile mDeletedSurface; ///< Will be set to the deleted surface if requested (set by the event-thread, read & cleared by the update-render thread).
361 volatile unsigned int mPostRendering; ///< Whether post-rendering is taking place (set by the event & render threads, read by the render-thread).
362 volatile unsigned int mSurfaceResized; ///< Will be set to resize the surface (set by the event-thread, read & cleared by the update-render thread).
363 volatile unsigned int mForceClear; ///< Will be set to clear forcibly
366 } // namespace Adaptor
368 } // namespace Internal
372 #endif // DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H