1 #ifndef DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H
2 #define DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H
5 * Copyright (c) 2023 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 <dali/devel-api/threading/conditional-wait.h>
23 #include <dali/devel-api/threading/semaphore.h>
24 #include <dali/integration-api/core.h>
26 #include <semaphore.h>
31 #include <dali/integration-api/adaptor-framework/thread-synchronization-interface.h>
32 #include <dali/internal/adaptor/common/thread-controller-interface.h>
33 #include <dali/internal/system/common/fps-tracker.h>
34 #include <dali/internal/system/common/performance-interface.h>
35 #include <dali/internal/system/common/update-status-logger.h>
36 #include <dali/internal/window-system/common/display-connection.h>
40 class RenderSurfaceInterface;
41 class TriggerEventInterface;
47 class AdaptorInternalServices;
48 class EnvironmentOptions;
51 * @brief Two threads where events/application interaction is handled on the main/event thread and the Update & Render
52 * happen on the other thread.
56 * a. Main/Event Thread.
57 * b. Update/Render Thread.
58 * 2. There is NO VSync thread:
59 * a. We retrieve the time before Update.
60 * b. Then retrieve the time after Render.
61 * c. We calculate the difference between these two times and if:
62 * i. The difference is less than the default frame time, we sleep.
63 * ii. If it’s more or the same, we continue.
64 * 3. On the update/render thread, if we discover that we do not need to do any more updates, we use a trigger-event
65 * to inform the main/event thread. This is then processed as soon as the event thread is able to do so where it
66 * is easier to make a decision about whether we should stop the update/render thread or not (depending on any
67 * update requests etc.).
68 * 4. The main thread is blocked while the surface is being replaced.
69 * 5. When we resume from paused, elapsed time is used for the animations, i.e. the could have finished while we were paused.
70 * However, FinishedSignal emission will only happen upon resumption.
71 * 6. Elapsed time is NOT used while if we are waking up from a sleep state or doing an UpdateOnce.
73 class CombinedUpdateRenderController : public ThreadControllerInterface,
74 public ThreadSynchronizationInterface
80 CombinedUpdateRenderController(AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions, ThreadMode threadMode);
83 * Non virtual destructor. Not intended as base class.
85 ~CombinedUpdateRenderController();
88 * @copydoc ThreadControllerInterface::Initialize()
90 void Initialize() override;
93 * @copydoc ThreadControllerInterface::Start()
95 void Start() override;
98 * @copydoc ThreadControllerInterface::Pause()
100 void Pause() override;
103 * @copydoc ThreadControllerInterface::Resume()
105 void Resume() override;
108 * @copydoc ThreadControllerInterface::Stop()
110 void Stop() override;
113 * @copydoc ThreadControllerInterface::RequestUpdate()
115 void RequestUpdate() override;
118 * @copydoc ThreadControllerInterface::RequestUpdateOnce()
120 void RequestUpdateOnce(UpdateMode updateMode) override;
123 * @copydoc ThreadControllerInterface::ReplaceSurface()
125 void ReplaceSurface(Dali::RenderSurfaceInterface* surface) override;
128 * @copydoc ThreadControllerInterface::DeleteSurface()
130 void DeleteSurface(Dali::RenderSurfaceInterface* surface) override;
133 * @copydoc ThreadControllerInterface::ResizeSurface()
135 void ResizeSurface() override;
138 * @copydoc ThreadControllerInterface::WaitForGraphicsInitialization()
140 void WaitForGraphicsInitialization() override;
143 * @copydoc ThreadControllerInterface::SetRenderRefreshRate()
145 void SetRenderRefreshRate(unsigned int numberOfFramesPerRender) override;
148 * @copydoc ThreadControllerInterface::SetPreRenderCallback
150 void SetPreRenderCallback(CallbackBase* callback) override;
153 * @copydoc ThreadControllerInterface::AddSurface()
155 void AddSurface(Dali::RenderSurfaceInterface* surface) override;
158 * @copydoc ThreadControllerInterface::GetThreadId()
160 int32_t GetThreadId() const override;
163 // Undefined copy constructor.
164 CombinedUpdateRenderController(const CombinedUpdateRenderController&);
166 // Undefined assignment operator.
167 CombinedUpdateRenderController& operator=(const CombinedUpdateRenderController&);
169 /////////////////////////////////////////////////////////////////////////////////////////////////
171 /////////////////////////////////////////////////////////////////////////////////////////////////
173 enum AnimationProgression
175 USE_ELAPSED_TIME, ///< Animation progression using elapsed time
176 NONE ///< No animation progression
180 * Runs the Update/Render Thread.
181 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
183 * @param[in] numberOfCycles The number of times the update/render cycle should run. If -1, then it will run continuously.
184 * @param[in] animationProgression Whether to progress animation using time elapsed since the last frame.
185 * @param[in] updateMode The update mode (i.e. either update & render or skip rendering)
187 inline void RunUpdateRenderThread(int numberOfCycles, AnimationProgression animationProgression, UpdateMode updateMode);
190 * Pauses the Update/Render Thread.
191 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
193 inline void PauseUpdateRenderThread();
196 * Stops the Update/Render Thread.
197 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
199 * @note Should only be called in Stop as calling this will kill the update-thread.
201 inline void StopUpdateRenderThread();
204 * Checks if the the Update/Render Thread is paused.
205 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
207 * @return true if paused, false otherwise
209 inline bool IsUpdateRenderThreadPaused();
212 * Used as the callback for the sleep-trigger.
214 * Will sleep when enough requests are made without any requests.
216 void ProcessSleepRequest();
218 /////////////////////////////////////////////////////////////////////////////////////////////////
219 // UpdateRenderThread
220 /////////////////////////////////////////////////////////////////////////////////////////////////
223 * The Update/Render thread loop. This thread will be destroyed on exit from this function.
225 void UpdateRenderThread();
228 * Called by the Update/Render Thread which ensures a wait if required.
230 * @param[out] useElapsedTime If true when returned, then the actual elapsed time will be used for animation.
231 * If false when returned, then there should NOT be any animation progression in the next Update.
232 * @param[in] updateRequired Whether another update is required.
233 * @param[out] timeToSleepUntil The time remaining in nanoseconds to keep the thread sleeping before resuming.
234 * @return false, if the thread should stop.
236 bool UpdateRenderReady(bool& useElapsedTime, bool updateRequired, uint64_t& timeToSleepUntil);
239 * Checks to see if the surface needs to be replaced.
240 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
242 * @return Pointer to the new surface, NULL otherwise
244 Dali::RenderSurfaceInterface* ShouldSurfaceBeReplaced();
247 * Called by the Update/Render thread after a surface has been replaced.
249 * This will lock the mutex in mEventThreadWaitCondition
251 void SurfaceReplaced();
254 * Checks to see if the surface needs to be deleted.
255 * This will lock the mutex in mUpdateRenderThreadWaitCondition.
257 * @return Pointer to the deleted surface, nullptr otherwise
259 Dali::RenderSurfaceInterface* ShouldSurfaceBeDeleted();
262 * Called by the Update/Render thread after a surface has been deleted.
264 * This will lock the mutex in mEventThreadWaitCondition
266 void SurfaceDeleted();
269 * Called by the Update/Render thread after a surface has been resized.
271 * This will lock the mutex in mEventThreadWaitCondition
273 void SurfaceResized();
276 * Helper for the thread calling the entry function
277 * @param[in] This A pointer to the current object
279 static void* InternalUpdateRenderThreadEntryFunc(void* This)
281 (static_cast<CombinedUpdateRenderController*>(This))->UpdateRenderThread();
285 /////////////////////////////////////////////////////////////////////////////////////////////////
287 /////////////////////////////////////////////////////////////////////////////////////////////////
290 * Called by the update-render & v-sync threads when they up and running.
292 * This will lock the mutex in mEventThreadWaitCondition.
294 void NotifyThreadInitialised();
297 * Called by the update-render thread when graphics has been initialised.
299 void NotifyGraphicsInitialised();
302 * Helper to add a performance marker to the performance server (if it's active)
303 * @param[in] type performance marker type
305 void AddPerformanceMarker(PerformanceInterface::MarkerType type);
307 /////////////////////////////////////////////////////////////////////////////////////////////////
308 // POST RENDERING - ThreadSynchronizationInterface overrides
309 /////////////////////////////////////////////////////////////////////////////////////////////////
311 /////////////////////////////////////////////////////////////////////////////////////////////////
312 //// Called by the Event Thread if post-rendering is required
313 /////////////////////////////////////////////////////////////////////////////////////////////////
316 * @copydoc ThreadSynchronizationInterface::PostRenderComplete()
318 void PostRenderComplete() override;
320 /////////////////////////////////////////////////////////////////////////////////////////////////
321 //// Called by the Render Thread if post-rendering is required
322 /////////////////////////////////////////////////////////////////////////////////////////////////
325 * @copydoc ThreadSynchronizationInterface::PostRenderStarted()
327 void PostRenderStarted() override;
330 * @copydoc ThreadSynchronizationInterface::PostRenderStarted()
332 void PostRenderWaitForCompletion() override;
335 FpsTracker mFpsTracker; ///< Object that tracks the FPS
336 UpdateStatusLogger mUpdateStatusLogger; ///< Object that logs the update-status as required.
338 Semaphore<> mEventThreadSemaphore; ///< Used by the event thread to ensure all threads have been initialised, and when replacing the surface.
339 ConditionalWait mGraphicsInitializeWait; ///< Used by the render thread to ensure the graphics has been initialised.
340 Semaphore<> mSurfaceSemaphore; ///< Used by the event thread to ensure the surface has been deleted or replaced.
342 ConditionalWait mUpdateRenderThreadWaitCondition; ///< The wait condition for the update-render-thread.
343 ConditionalWait mPostRenderWaitCondition; ///< The wait condition for the post render.
345 AdaptorInternalServices& mAdaptorInterfaces; ///< The adaptor internal interface
346 PerformanceInterface* mPerformanceInterface; ///< The performance logging interface
347 Integration::Core& mCore; ///< Dali core reference
348 const EnvironmentOptions& mEnvironmentOptions; ///< Environment options
349 TriggerEventInterface& mNotificationTrigger; ///< Reference to notification event trigger
350 TriggerEventInterface* mSleepTrigger; ///< Used by the update-render thread to trigger the event thread when it no longer needs to do any updates
351 CallbackBase* mPreRenderCallback; ///< Used by Update/Render thread when PreRender is about to be called on graphics.
353 pthread_t* mUpdateRenderThread; ///< The Update/Render thread.
355 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.
356 // TODO: mDefaultFrameDurationMilliseconds is defined as uint64_t, the only place where it is used, it is converted to an unsigned int!!!
357 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.
358 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.
359 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.
361 uint32_t mUpdateRequestCount; ///< Count of update-requests we have received to ensure we do not go to sleep too early.
362 uint32_t mRunning; ///< Read and set on the event-thread only to state whether we are running.
363 int32_t mThreadId; ///< UpdateRender thread id
365 ThreadMode mThreadMode; ///< Whether the thread runs continuously or runs when it is requested.
368 // NOTE: cannot use booleans as these are used from multiple threads, must use variable with machine word size for atomic read/write
371 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).
372 volatile unsigned int mDestroyUpdateRenderThread; ///< Whether the Update/Render thread be destroyed (set by the event-thread, read by the update-render-thread).
373 volatile unsigned int mUpdateRenderThreadCanSleep; ///< Whether the Update/Render thread can sleep (set by the event-thread, read by the update-render-thread).
374 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).
375 ///< Ensures we do not go to sleep if we have not processed the most recent update-request.
377 volatile unsigned int mUseElapsedTimeAfterWait; ///< Whether we should use the elapsed time after waiting (set by the event-thread, read by the update-render-thread).
379 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).
380 Dali::RenderSurfaceInterface* volatile mDeletedSurface; ///< Will be set to the deleted surface if requested (set by the event-thread, read & cleared by the update-render thread).
382 volatile unsigned int mPostRendering; ///< Whether post-rendering is taking place (set by the event & render threads, read by the render-thread).
383 volatile unsigned int mSurfaceResized; ///< Will be set to resize the surface (set by the event-thread, read & cleared by the update-render thread).
384 volatile unsigned int mForceClear; ///< Will be set to clear forcibly
386 volatile unsigned int mUploadWithoutRendering; ///< Will be set to upload the resource only (with no rendering)
388 volatile unsigned int mFirstFrameAfterResume; ///< Will be set to check the first frame after resume (for log)
390 std::vector<Rect<int>> mDamagedRects; ///< Keeps collected damaged render items rects for one render pass
393 } // namespace Adaptor
395 } // namespace Internal
399 #endif // DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H