1 #ifndef DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H
2 #define DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H
5 * Copyright (c) 2020 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.
23 #include <semaphore.h>
26 #include <dali/devel-api/threading/conditional-wait.h>
27 #include <dali/integration-api/core.h>
30 #include <dali/integration-api/adaptor-framework/thread-synchronization-interface.h>
31 #include <dali/internal/adaptor/common/thread-controller-interface.h>
32 #include <dali/internal/system/common/fps-tracker.h>
33 #include <dali/internal/system/common/performance-interface.h>
34 #include <dali/internal/system/common/update-status-logger.h>
35 #include <dali/internal/window-system/common/display-connection.h>
40 class RenderSurfaceInterface;
41 class TriggerEventInterface;
49 class AdaptorInternalServices;
50 class EnvironmentOptions;
53 * @brief Two threads where events/application interaction is handled on the main/event thread and the Update & Render
54 * happen on the other thread.
58 * a. Main/Event Thread.
59 * b. Update/Render Thread.
60 * 2. There is NO VSync thread:
61 * a. We retrieve the time before Update.
62 * b. Then retrieve the time after Render.
63 * c. We calculate the difference between these two times and if:
64 * i. The difference is less than the default frame time, we sleep.
65 * ii. If it’s more or the same, we continue.
66 * 3. On the update/render thread, if we discover that we do not need to do any more updates, we use a trigger-event
67 * to inform the main/event thread. This is then processed as soon as the event thread is able to do so where it
68 * is easier to make a decision about whether we should stop the update/render thread or not (depending on any
69 * update requests etc.).
70 * 4. The main thread is blocked while the surface is being replaced.
71 * 5. When we resume from paused, elapsed time is used for the animations, i.e. the could have finished while we were paused.
72 * However, FinishedSignal emission will only happen upon resumption.
73 * 6. Elapsed time is NOT used while if we are waking up from a sleep state or doing an UpdateOnce.
75 class CombinedUpdateRenderController : public ThreadControllerInterface,
76 public ThreadSynchronizationInterface
83 CombinedUpdateRenderController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions );
86 * Non virtual destructor. Not intended as base class.
88 ~CombinedUpdateRenderController();
91 * @copydoc ThreadControllerInterface::Initialize()
93 virtual void Initialize();
96 * @copydoc ThreadControllerInterface::Start()
101 * @copydoc ThreadControllerInterface::Pause()
103 virtual void Pause();
106 * @copydoc ThreadControllerInterface::Resume()
108 virtual void Resume();
111 * @copydoc ThreadControllerInterface::Stop()
116 * @copydoc ThreadControllerInterface::RequestUpdate()
118 virtual void RequestUpdate();
121 * @copydoc ThreadControllerInterface::RequestUpdateOnce()
123 virtual void RequestUpdateOnce( UpdateMode updateMode );
126 * @copydoc ThreadControllerInterface::ReplaceSurface()
128 virtual void ReplaceSurface( Dali::RenderSurfaceInterface* surface );
131 * @copydoc ThreadControllerInterface::ResizeSurface()
133 virtual void ResizeSurface();
136 * @copydoc ThreadControllerInterface::WaitForGraphicsInitialization()
138 virtual void WaitForGraphicsInitialization();
141 * @copydoc ThreadControllerInterface::SetRenderRefreshRate()
143 virtual void SetRenderRefreshRate( unsigned int numberOfFramesPerRender );
146 * @copydoc ThreadControllerInterface::SetPreRenderCallback
148 void SetPreRenderCallback( CallbackBase* callback ) override;
151 * @copydoc ThreadControllerInterface::AddSurface()
153 virtual void AddSurface( Dali::RenderSurfaceInterface* surface );
156 * @copydoc ThreadControllerInterface::IsRenderingWindows()
158 bool IsRenderingWindows() const override { return mIsRenderingWindows; }
162 // Undefined copy constructor.
163 CombinedUpdateRenderController( const CombinedUpdateRenderController& );
165 // Undefined assignment operator.
166 CombinedUpdateRenderController& operator=( const CombinedUpdateRenderController& );
168 /////////////////////////////////////////////////////////////////////////////////////////////////
170 /////////////////////////////////////////////////////////////////////////////////////////////////
172 enum AnimationProgression
174 USE_ELAPSED_TIME, ///< Animation progression using elapsed time
175 NONE ///< No animation progression
179 * Runs the Update/Render Thread.
180 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
182 * @param[in] numberOfCycles The number of times the update/render cycle should run. If -1, then it will run continuously.
183 * @param[in] animationProgression Whether to progress animation using time elapsed since the last frame.
184 * @param[in] updateMode The update mode (i.e. either update & render or skip rendering)
186 inline void RunUpdateRenderThread( int numberOfCycles, AnimationProgression animationProgression, UpdateMode updateMode );
189 * Pauses the Update/Render Thread.
190 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
192 inline void PauseUpdateRenderThread();
195 * Stops the Update/Render Thread.
196 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
198 * @note Should only be called in Stop as calling this will kill the update-thread.
200 inline void StopUpdateRenderThread();
203 * Checks if the the Update/Render Thread is paused.
204 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
206 * @return true if paused, false otherwise
208 inline bool IsUpdateRenderThreadPaused();
211 * Used as the callback for the sleep-trigger.
213 * Will sleep when enough requests are made without any requests.
215 void ProcessSleepRequest();
217 /////////////////////////////////////////////////////////////////////////////////////////////////
218 // UpdateRenderThread
219 /////////////////////////////////////////////////////////////////////////////////////////////////
222 * The Update/Render thread loop. This thread will be destroyed on exit from this function.
224 void UpdateRenderThread();
227 * Called by the Update/Render Thread which ensures a wait if required.
229 * @param[out] useElapsedTime If true when returned, then the actual elapsed time will be used for animation.
230 * If false when returned, then there should NOT be any animation progression in the next Update.
231 * @param[in] updateRequired Whether another update is required.
232 * @param[out] timeToSleepUntil The time remaining in nanoseconds to keep the thread sleeping before resuming.
233 * @return false, if the thread should stop.
235 bool UpdateRenderReady( bool& useElapsedTime, bool updateRequired, uint64_t& timeToSleepUntil );
238 * Checks to see if the surface needs to be replaced.
239 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
241 * @return Pointer to the new surface, NULL otherwise
243 Dali::RenderSurfaceInterface* ShouldSurfaceBeReplaced();
246 * Called by the Update/Render thread after a surface has been replaced.
248 * This will lock the mutex in mEventThreadWaitCondition
250 void SurfaceReplaced();
253 * Checks to see if the surface needs to be resized.
254 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
256 * @return true if the surface should be resized, false otherwise
258 bool ShouldSurfaceBeResized();
261 * Called by the Update/Render thread after a surface has been resized.
263 * This will lock the mutex in mEventThreadWaitCondition
265 void SurfaceResized();
268 * Helper for the thread calling the entry function
269 * @param[in] This A pointer to the current object
271 static void* InternalUpdateRenderThreadEntryFunc( void* This )
273 ( static_cast<CombinedUpdateRenderController*>( This ) )->UpdateRenderThread();
277 /////////////////////////////////////////////////////////////////////////////////////////////////
279 /////////////////////////////////////////////////////////////////////////////////////////////////
282 * Called by the update-render & v-sync threads when they up and running.
284 * This will lock the mutex in mEventThreadWaitCondition.
286 void NotifyThreadInitialised();
289 * Called by the update-render thread when graphics has been initialised.
291 void NotifyGraphicsInitialised();
294 * Helper to add a performance marker to the performance server (if it's active)
295 * @param[in] type performance marker type
297 void AddPerformanceMarker( PerformanceInterface::MarkerType type );
299 /////////////////////////////////////////////////////////////////////////////////////////////////
300 // POST RENDERING - ThreadSynchronizationInterface overrides
301 /////////////////////////////////////////////////////////////////////////////////////////////////
303 /////////////////////////////////////////////////////////////////////////////////////////////////
304 //// Called by the Event Thread if post-rendering is required
305 /////////////////////////////////////////////////////////////////////////////////////////////////
308 * @copydoc ThreadSynchronizationInterface::PostRenderComplete()
310 virtual void PostRenderComplete();
312 /////////////////////////////////////////////////////////////////////////////////////////////////
313 //// Called by the Render Thread if post-rendering is required
314 /////////////////////////////////////////////////////////////////////////////////////////////////
317 * @copydoc ThreadSynchronizationInterface::PostRenderStarted()
319 virtual void PostRenderStarted();
322 * @copydoc ThreadSynchronizationInterface::PostRenderStarted()
324 virtual void PostRenderWaitForCompletion();
328 FpsTracker mFpsTracker; ///< Object that tracks the FPS
329 UpdateStatusLogger mUpdateStatusLogger; ///< Object that logs the update-status as required.
331 sem_t mEventThreadSemaphore; ///< Used by the event thread to ensure all threads have been initialised, and when replacing the surface.
332 sem_t mGraphicsInitializeSemaphore; ///< Used by the render thread to ensure the graphics has been initialised.
334 ConditionalWait mUpdateRenderThreadWaitCondition; ///< The wait condition for the update-render-thread.
336 AdaptorInternalServices& mAdaptorInterfaces; ///< The adaptor internal interface
337 PerformanceInterface* mPerformanceInterface; ///< The performance logging interface
338 Integration::Core& mCore; ///< Dali core reference
339 const EnvironmentOptions& mEnvironmentOptions; ///< Environment options
340 TriggerEventInterface& mNotificationTrigger; ///< Reference to notification event trigger
341 TriggerEventInterface* mSleepTrigger; ///< Used by the update-render thread to trigger the event thread when it no longer needs to do any updates
342 CallbackBase* mPreRenderCallback; ///< Used by Update/Render thread when PreRender is about to be called on graphics.
344 pthread_t* mUpdateRenderThread; ///< The Update/Render thread.
346 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.
347 // TODO: mDefaultFrameDurationMilliseconds is defined as uint64_t, the only place where it is used, it is converted to an unsigned int!!!
348 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.
349 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.
350 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.
352 unsigned int mUpdateRequestCount; ///< Count of update-requests we have received to ensure we do not go to sleep too early.
353 unsigned int mRunning; ///< Read and set on the event-thread only to state whether we are running.
356 // NOTE: cannot use booleans as these are used from multiple threads, must use variable with machine word size for atomic read/write
359 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).
360 volatile unsigned int mDestroyUpdateRenderThread; ///< Whether the Update/Render thread be destroyed (set by the event-thread, read by the update-render-thread).
361 volatile unsigned int mUpdateRenderThreadCanSleep; ///< Whether the Update/Render thread can sleep (set by the event-thread, read by the update-render-thread).
362 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).
363 ///< Ensures we do not go to sleep if we have not processed the most recent update-request.
365 volatile unsigned int mUseElapsedTimeAfterWait; ///< Whether we should use the elapsed time after waiting (set by the event-thread, read by the update-render-thread).
367 Dali::RenderSurfaceInterface* volatile mNewSurface; ///< Will be set to the new-surface if requested (set by the event-thread, read & cleared by the update-render thread).
369 volatile unsigned int mPostRendering; ///< Whether post-rendering is taking place (set by the event & render threads, read by the render-thread).
370 volatile unsigned int mSurfaceResized; ///< Will be set to resize the surface (set by the event-thread, read & cleared by the update-render thread).
371 volatile unsigned int mForceClear; ///< Will be set to clear forcibly
373 volatile unsigned int mUploadWithoutRendering; ///< Will be set to upload the resource only (with no rendering)
375 volatile unsigned int mFirstFrameAfterResume; ///< Will be set to check the first frame after resume (for log)
377 std::atomic<bool> mIsRenderingWindows; ///< This is set only from the render thread and read only from the event thread
380 } // namespace Adaptor
382 } // namespace Internal
386 #endif // DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H