Merge "Remove DALI_ADAPTOR_COMPILATION define" into devel/master
[platform/core/uifw/dali-adaptor.git] / dali / internal / adaptor / common / combined-update-render-controller.h
1 #ifndef DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H
2 #define DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H
3
4 /*
5  * Copyright (c) 2019 Samsung Electronics Co., Ltd.
6  *
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
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
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.
18  *
19  */
20
21 // EXTERNAL INCLUDES
22 #include <semaphore.h>
23 #include <stdint.h>
24 #include <dali/devel-api/threading/conditional-wait.h>
25 #include <dali/integration-api/core.h>
26
27 // INTERNAL INCLUDES
28 #include <dali/integration-api/adaptors/thread-synchronization-interface.h>
29 #include <dali/internal/adaptor/common/thread-controller-interface.h>
30 #include <dali/internal/system/common/fps-tracker.h>
31 #include <dali/internal/system/common/performance-interface.h>
32 #include <dali/internal/system/common/update-status-logger.h>
33 #include <dali/internal/window-system/common/display-connection.h>
34
35 namespace Dali
36 {
37
38 class RenderSurfaceInterface;
39 class TriggerEventInterface;
40
41 namespace Internal
42 {
43
44 namespace Adaptor
45 {
46
47 class AdaptorInternalServices;
48 class EnvironmentOptions;
49
50 /**
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.
53  *
54  * Key Points:
55  *  1. Two Threads:
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.
72  */
73 class CombinedUpdateRenderController : public ThreadControllerInterface,
74                                        public ThreadSynchronizationInterface
75 {
76 public:
77
78   /**
79    * Constructor
80    */
81   CombinedUpdateRenderController( AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions );
82
83   /**
84    * Non virtual destructor. Not intended as base class.
85    */
86   ~CombinedUpdateRenderController();
87
88   /**
89    * @copydoc ThreadControllerInterface::Initialize()
90    */
91   virtual void Initialize();
92
93   /**
94    * @copydoc ThreadControllerInterface::Start()
95    */
96   virtual void Start();
97
98   /**
99    * @copydoc ThreadControllerInterface::Pause()
100    */
101   virtual void Pause();
102
103   /**
104    * @copydoc ThreadControllerInterface::Resume()
105    */
106   virtual void Resume();
107
108   /**
109    * @copydoc ThreadControllerInterface::Stop()
110    */
111   virtual void Stop();
112
113   /**
114    * @copydoc ThreadControllerInterface::RequestUpdate()
115    */
116   virtual void RequestUpdate();
117
118   /**
119    * @copydoc ThreadControllerInterface::RequestUpdateOnce()
120    */
121   virtual void RequestUpdateOnce( UpdateMode updateMode );
122
123   /**
124    * @copydoc ThreadControllerInterface::ReplaceSurface()
125    */
126   virtual void ReplaceSurface( Dali::RenderSurfaceInterface* surface );
127
128   /**
129    * @copydoc ThreadControllerInterface::DeleteSurface()
130    */
131   virtual void DeleteSurface( Dali::RenderSurfaceInterface* surface );
132
133   /**
134    * @copydoc ThreadControllerInterface::ResizeSurface()
135    */
136   virtual void ResizeSurface();
137
138   /**
139    * @copydoc ThreadControllerInterface::SetRenderRefreshRate()
140    */
141   virtual void SetRenderRefreshRate( unsigned int numberOfFramesPerRender );
142
143   /**
144    * @copydoc ThreadControllerInterface::SetPreRenderCallback
145    */
146   void SetPreRenderCallback( CallbackBase* callback ) override;
147
148 private:
149
150   // Undefined copy constructor.
151   CombinedUpdateRenderController( const CombinedUpdateRenderController& );
152
153   // Undefined assignment operator.
154   CombinedUpdateRenderController& operator=( const CombinedUpdateRenderController& );
155
156   /////////////////////////////////////////////////////////////////////////////////////////////////
157   // EventThread
158   /////////////////////////////////////////////////////////////////////////////////////////////////
159
160   enum AnimationProgression
161   {
162     USE_ELAPSED_TIME,          ///< Animation progression using elapsed time
163     NONE                       ///< No animation progression
164   };
165
166   /**
167    * Runs the Update/Render Thread.
168    * This will lock the mutex in mUpdateRenderThreadWaitCondition.
169    *
170    * @param[in]  numberOfCycles           The number of times the update/render cycle should run. If -1, then it will run continuously.
171    * @param[in]  animationProgression     Whether to progress animation using time elapsed since the last frame.
172    * @param[in]  updateMode               The update mode (i.e. either update & render or skip rendering)
173    */
174   inline void RunUpdateRenderThread( int numberOfCycles, AnimationProgression animationProgression, UpdateMode updateMode );
175
176   /**
177    * Pauses the Update/Render Thread.
178    * This will lock the mutex in mUpdateRenderThreadWaitCondition.
179    */
180   inline void PauseUpdateRenderThread();
181
182   /**
183    * Stops the Update/Render Thread.
184    * This will lock the mutex in mUpdateRenderThreadWaitCondition.
185    *
186    * @note Should only be called in Stop as calling this will kill the update-thread.
187    */
188   inline void StopUpdateRenderThread();
189
190   /**
191    * Checks if the the Update/Render Thread is paused.
192    * This will lock the mutex in mUpdateRenderThreadWaitCondition.
193    *
194    * @return true if paused, false otherwise
195    */
196   inline bool IsUpdateRenderThreadPaused();
197
198   /**
199    * Used as the callback for the sleep-trigger.
200    *
201    * Will sleep when enough requests are made without any requests.
202    */
203   void ProcessSleepRequest();
204
205   /////////////////////////////////////////////////////////////////////////////////////////////////
206   // UpdateRenderThread
207   /////////////////////////////////////////////////////////////////////////////////////////////////
208
209   /**
210    * The Update/Render thread loop. This thread will be destroyed on exit from this function.
211    */
212   void UpdateRenderThread();
213
214   /**
215    * Called by the Update/Render Thread which ensures a wait if required.
216    *
217    * @param[out] useElapsedTime    If true when returned, then the actual elapsed time will be used for animation.
218    *                               If false when returned, then there should NOT be any animation progression in the next Update.
219    * @param[in]  updateRequired    Whether another update is required.
220    * @param[out] timeToSleepUntil  The time remaining in nanoseconds to keep the thread sleeping before resuming.
221    * @return false, if the thread should stop.
222    */
223   bool UpdateRenderReady( bool& useElapsedTime, bool updateRequired, uint64_t& timeToSleepUntil );
224
225   /**
226    * Checks to see if the surface needs to be replaced.
227    * This will lock the mutex in mUpdateRenderThreadWaitCondition.
228    *
229    * @return Pointer to the new surface, NULL otherwise
230    */
231   Integration::RenderSurface* ShouldSurfaceBeReplaced();
232
233   /**
234    * Called by the Update/Render thread after a surface has been replaced.
235    *
236    * This will lock the mutex in mEventThreadWaitCondition
237    */
238   void SurfaceReplaced();
239
240   /**
241    * Checks to see if the surface needs to be deleted.
242    * This will lock the mutex in mUpdateRenderThreadWaitCondition.
243    *
244    * @return Pointer to the deleted surface, nullptr otherwise
245    */
246   Integration::RenderSurface* ShouldSurfaceBeDeleted();
247
248   /**
249    * Called by the Update/Render thread after a surface has been deleted.
250    *
251    * This will lock the mutex in mEventThreadWaitCondition
252    */
253   void SurfaceDeleted();
254
255   /**
256    * Checks to see if the surface needs to be resized.
257    * This will lock the mutex in mUpdateRenderThreadWaitCondition.
258    *
259    * @return true if the surface should be resized, false otherwise
260    */
261   bool ShouldSurfaceBeResized();
262
263   /**
264    * Called by the Update/Render thread after a surface has been resized.
265    *
266    * This will lock the mutex in mEventThreadWaitCondition
267    */
268   void SurfaceResized();
269
270   /**
271    * Helper for the thread calling the entry function
272    * @param[in] This A pointer to the current object
273    */
274   static void* InternalUpdateRenderThreadEntryFunc( void* This )
275   {
276     ( static_cast<CombinedUpdateRenderController*>( This ) )->UpdateRenderThread();
277     return NULL;
278   }
279
280   /////////////////////////////////////////////////////////////////////////////////////////////////
281   // ALL Threads
282   /////////////////////////////////////////////////////////////////////////////////////////////////
283
284   /**
285    * Called by the update-render & v-sync threads when they up and running.
286    *
287    * This will lock the mutex in mEventThreadWaitCondition.
288    */
289   void NotifyThreadInitialised();
290
291   /**
292    * Helper to add a performance marker to the performance server (if it's active)
293    * @param[in]  type  performance marker type
294    */
295   void AddPerformanceMarker( PerformanceInterface::MarkerType type );
296
297   /////////////////////////////////////////////////////////////////////////////////////////////////
298   // POST RENDERING - ThreadSynchronizationInterface overrides
299   /////////////////////////////////////////////////////////////////////////////////////////////////
300
301   /////////////////////////////////////////////////////////////////////////////////////////////////
302   //// Called by the Event Thread if post-rendering is required
303   /////////////////////////////////////////////////////////////////////////////////////////////////
304
305   /**
306    * @copydoc ThreadSynchronizationInterface::PostRenderComplete()
307    */
308   virtual void PostRenderComplete();
309
310   /////////////////////////////////////////////////////////////////////////////////////////////////
311   //// Called by the Render Thread if post-rendering is required
312   /////////////////////////////////////////////////////////////////////////////////////////////////
313
314   /**
315    * @copydoc ThreadSynchronizationInterface::PostRenderStarted()
316    */
317   virtual void PostRenderStarted();
318
319   /**
320    * @copydoc ThreadSynchronizationInterface::PostRenderStarted()
321    */
322   virtual void PostRenderWaitForCompletion();
323
324 private:
325
326   FpsTracker                        mFpsTracker;                       ///< Object that tracks the FPS
327   UpdateStatusLogger                mUpdateStatusLogger;               ///< Object that logs the update-status as required.
328
329   sem_t                             mEventThreadSemaphore;             ///< Used by the event thread to ensure all threads have been initialised, and when replacing the surface.
330
331   ConditionalWait                   mUpdateRenderThreadWaitCondition;  ///< The wait condition for the update-render-thread.
332
333   AdaptorInternalServices&          mAdaptorInterfaces;                ///< The adaptor internal interface
334   PerformanceInterface*             mPerformanceInterface;             ///< The performance logging interface
335   Integration::Core&                mCore;                             ///< Dali core reference
336   const EnvironmentOptions&         mEnvironmentOptions;               ///< Environment options
337   TriggerEventInterface&            mNotificationTrigger;              ///< Reference to notification event trigger
338   TriggerEventInterface*            mSleepTrigger;                     ///< Used by the update-render thread to trigger the event thread when it no longer needs to do any updates
339   CallbackBase*                     mPreRenderCallback;                ///< Used by Update/Render thread when PreRender is about to be called on graphics.
340
341   pthread_t*                        mUpdateRenderThread;               ///< The Update/Render thread.
342
343   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.
344   // TODO: mDefaultFrameDurationMilliseconds is defined as uint64_t, the only place where it is used, it is converted to an unsigned int!!!
345   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.
346   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.
347   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.
348
349   unsigned int                      mUpdateRequestCount;               ///< Count of update-requests we have received to ensure we do not go to sleep too early.
350   unsigned int                      mRunning;                          ///< Read and set on the event-thread only to state whether we are running.
351
352   //
353   // NOTE: cannot use booleans as these are used from multiple threads, must use variable with machine word size for atomic read/write
354   //
355
356   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).
357   volatile unsigned int             mDestroyUpdateRenderThread;        ///< Whether the Update/Render thread be destroyed (set by the event-thread, read by the update-render-thread).
358   volatile unsigned int             mUpdateRenderThreadCanSleep;       ///< Whether the Update/Render thread can sleep (set by the event-thread, read by the update-render-thread).
359   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).
360                                                                        ///< Ensures we do not go to sleep if we have not processed the most recent update-request.
361
362   volatile unsigned int             mUseElapsedTimeAfterWait;          ///< Whether we should use the elapsed time after waiting (set by the event-thread, read by the update-render-thread).
363
364   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).
365   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).
366
367   volatile unsigned int             mPostRendering;                    ///< Whether post-rendering is taking place (set by the event & render threads, read by the render-thread).
368   volatile unsigned int             mSurfaceResized;                   ///< Will be set to resize the surface (set by the event-thread, read & cleared by the update-render thread).
369   volatile unsigned int             mForceClear;                       ///< Will be set to clear forcibly
370
371   volatile unsigned int             mUploadWithoutRendering;           ///< Will be set to upload the resource only (with no rendering)
372
373   volatile unsigned int             mFirstFrameAfterResume;            ///< Will be set to check the first frame after resume (for log)
374 };
375
376 } // namespace Adaptor
377
378 } // namespace Internal
379
380 } // namespace Dali
381
382 #endif // DALI_INTERNAL_COMBINED_UPDATE_RENDER_CONTROLLER_H