Merge "Enable atspi" into devel/master
[platform/core/uifw/dali-adaptor.git] / dali / internal / adaptor / common / combined-update-render-controller.cpp
1 /*
2  * Copyright (c) 2021 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/adaptor/common/combined-update-render-controller.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/platform-abstraction.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include "dali/public-api/common/dali-common.h"
26
27 // INTERNAL INCLUDES
28 #include <dali/devel-api/adaptor-framework/thread-settings.h>
29 #include <dali/integration-api/adaptor-framework/trigger-event-factory.h>
30 #include <dali/internal/adaptor/common/adaptor-internal-services.h>
31 #include <dali/internal/adaptor/common/combined-update-render-controller-debug.h>
32 #include <dali/internal/graphics/common/graphics-interface.h>
33 #include <dali/internal/graphics/gles/egl-graphics.h>
34 #include <dali/internal/graphics/gles/egl-implementation.h>
35 #include <dali/internal/system/common/environment-options.h>
36 #include <dali/internal/system/common/time-service.h>
37 #include <dali/internal/window-system/common/window-impl.h>
38
39 namespace Dali
40 {
41 namespace Internal
42 {
43 namespace Adaptor
44 {
45 namespace
46 {
47 const unsigned int CREATED_THREAD_COUNT = 1u;
48
49 const int CONTINUOUS = -1;
50 const int ONCE       = 1;
51
52 const unsigned int TRUE  = 1u;
53 const unsigned int FALSE = 0u;
54
55 const unsigned int MILLISECONDS_PER_SECOND(1e+3);
56 const float        NANOSECONDS_TO_SECOND(1e-9f);
57 const unsigned int NANOSECONDS_PER_SECOND(1e+9);
58 const unsigned int NANOSECONDS_PER_MILLISECOND(1e+6);
59
60 // The following values will get calculated at compile time
61 const float    DEFAULT_FRAME_DURATION_IN_SECONDS(1.0f / 60.0f);
62 const uint64_t DEFAULT_FRAME_DURATION_IN_MILLISECONDS(DEFAULT_FRAME_DURATION_IN_SECONDS* MILLISECONDS_PER_SECOND);
63 const uint64_t DEFAULT_FRAME_DURATION_IN_NANOSECONDS(DEFAULT_FRAME_DURATION_IN_SECONDS* NANOSECONDS_PER_SECOND);
64
65 /**
66  * 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
67  * there is a danger that, on the event-thread we could have:
68  *  1) An update-request where we do nothing as Update/Render thread still running.
69  *  2) Quickly followed by a sleep-request being handled where we pause the Update/Render Thread (even though we have an update to process).
70  *
71  * 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:
72  *  1) MAIN THREAD:           Update Request: COUNTER = 1
73  *  2) UPDATE/RENDER THREAD:  Do Update/Render, then no Updates required -> Sleep Trigger
74  *  3) MAIN THREAD:           Update Request: COUNTER = 2
75  *  4) MAIN THREAD:           Sleep Request:  COUNTER = 1 -> We do not sleep just yet
76  *
77  * Also ensures we preserve battery life by only doing ONE update when the above use case is not triggered.
78  *  1) MAIN THREAD:           Update Request: COUNTER = 1
79  *  2) UPDATE/RENDER THREAD:  Do Update/Render, then no Updates required -> Sleep Trigger
80  *  3) MAIN THREAD:           Sleep Request:  COUNTER = 0 -> Go to sleep
81  */
82 const unsigned int MAXIMUM_UPDATE_REQUESTS = 2;
83 } // unnamed namespace
84
85 ///////////////////////////////////////////////////////////////////////////////////////////////////
86 // EVENT THREAD
87 ///////////////////////////////////////////////////////////////////////////////////////////////////
88
89 CombinedUpdateRenderController::CombinedUpdateRenderController(AdaptorInternalServices& adaptorInterfaces, const EnvironmentOptions& environmentOptions, ThreadMode threadMode)
90 : mFpsTracker(environmentOptions),
91   mUpdateStatusLogger(environmentOptions),
92   mEventThreadSemaphore(0),
93   mSurfaceSemaphore(0),
94   mUpdateRenderThreadWaitCondition(),
95   mAdaptorInterfaces(adaptorInterfaces),
96   mPerformanceInterface(adaptorInterfaces.GetPerformanceInterface()),
97   mCore(adaptorInterfaces.GetCore()),
98   mEnvironmentOptions(environmentOptions),
99   mNotificationTrigger(adaptorInterfaces.GetProcessCoreEventsTrigger()),
100   mSleepTrigger(NULL),
101   mPreRenderCallback(NULL),
102   mUpdateRenderThread(NULL),
103   mDefaultFrameDelta(0.0f),
104   mDefaultFrameDurationMilliseconds(0u),
105   mDefaultFrameDurationNanoseconds(0u),
106   mDefaultHalfFrameNanoseconds(0u),
107   mUpdateRequestCount(0u),
108   mRunning(FALSE),
109   mThreadMode(threadMode),
110   mUpdateRenderRunCount(0),
111   mDestroyUpdateRenderThread(FALSE),
112   mUpdateRenderThreadCanSleep(FALSE),
113   mPendingRequestUpdate(FALSE),
114   mUseElapsedTimeAfterWait(FALSE),
115   mNewSurface(NULL),
116   mDeletedSurface(nullptr),
117   mPostRendering(FALSE),
118   mSurfaceResized(0),
119   mForceClear(FALSE),
120   mUploadWithoutRendering(FALSE),
121   mFirstFrameAfterResume(FALSE)
122 {
123   LOG_EVENT_TRACE;
124
125   // Initialise frame delta/duration variables first
126   SetRenderRefreshRate(environmentOptions.GetRenderRefreshRate());
127
128   // Set the thread-synchronization interface on the render-surface
129   Dali::RenderSurfaceInterface* currentSurface = mAdaptorInterfaces.GetRenderSurfaceInterface();
130   if(currentSurface)
131   {
132     currentSurface->SetThreadSynchronization(*this);
133   }
134
135   mSleepTrigger = TriggerEventFactory::CreateTriggerEvent(MakeCallback(this, &CombinedUpdateRenderController::ProcessSleepRequest), TriggerEventInterface::KEEP_ALIVE_AFTER_TRIGGER);
136 }
137
138 CombinedUpdateRenderController::~CombinedUpdateRenderController()
139 {
140   LOG_EVENT_TRACE;
141
142   Stop();
143
144   delete mPreRenderCallback;
145   delete mSleepTrigger;
146 }
147
148 void CombinedUpdateRenderController::Initialize()
149 {
150   LOG_EVENT_TRACE;
151
152   // Ensure Update/Render Thread not already created
153   DALI_ASSERT_ALWAYS(!mUpdateRenderThread);
154
155   // Create Update/Render Thread
156   ConditionalWait::ScopedLock lock(mGraphicsInitializeWait);
157   mUpdateRenderThread = new pthread_t();
158   int error           = pthread_create(mUpdateRenderThread, NULL, InternalUpdateRenderThreadEntryFunc, this);
159   DALI_ASSERT_ALWAYS(!error && "Return code from pthread_create() when creating UpdateRenderThread");
160
161   // The Update/Render thread will now run and initialise the graphics interface etc. and will then wait for Start to be called
162   // When this function returns, the application initialisation on the event thread should occur
163 }
164
165 void CombinedUpdateRenderController::Start()
166 {
167   LOG_EVENT_TRACE;
168
169   DALI_ASSERT_ALWAYS(!mRunning && mUpdateRenderThread);
170
171   // Wait until all threads created in Initialise are up and running
172   for(unsigned int i = 0; i < CREATED_THREAD_COUNT; ++i)
173   {
174     mEventThreadSemaphore.Acquire();
175   }
176
177   mRunning = TRUE;
178
179   LOG_EVENT("Startup Complete, starting Update/Render Thread");
180
181   RunUpdateRenderThread(CONTINUOUS, AnimationProgression::NONE, UpdateMode::NORMAL);
182
183   Dali::RenderSurfaceInterface* currentSurface = mAdaptorInterfaces.GetRenderSurfaceInterface();
184   if(currentSurface)
185   {
186     currentSurface->StartRender();
187   }
188
189   DALI_LOG_RELEASE_INFO("CombinedUpdateRenderController::Start\n");
190 }
191
192 void CombinedUpdateRenderController::Pause()
193 {
194   LOG_EVENT_TRACE;
195
196   mRunning = FALSE;
197
198   PauseUpdateRenderThread();
199
200   AddPerformanceMarker(PerformanceInterface::PAUSED);
201
202   DALI_LOG_RELEASE_INFO("CombinedUpdateRenderController::Pause\n");
203 }
204
205 void CombinedUpdateRenderController::Resume()
206 {
207   LOG_EVENT_TRACE;
208
209   if(!mRunning && IsUpdateRenderThreadPaused())
210   {
211     LOG_EVENT("Resuming");
212
213     RunUpdateRenderThread(CONTINUOUS, AnimationProgression::USE_ELAPSED_TIME, UpdateMode::NORMAL);
214
215     AddPerformanceMarker(PerformanceInterface::RESUME);
216
217     mRunning               = TRUE;
218     mForceClear            = TRUE;
219     mFirstFrameAfterResume = TRUE;
220
221     DALI_LOG_RELEASE_INFO("CombinedUpdateRenderController::Resume\n");
222   }
223   else
224   {
225     DALI_LOG_RELEASE_INFO("CombinedUpdateRenderController::Resume: Already resumed [%d, %d, %d]\n", mRunning, mUpdateRenderRunCount, mUpdateRenderThreadCanSleep);
226   }
227 }
228
229 void CombinedUpdateRenderController::Stop()
230 {
231   LOG_EVENT_TRACE;
232
233   // Stop Rendering and the Update/Render Thread
234   Dali::RenderSurfaceInterface* currentSurface = mAdaptorInterfaces.GetRenderSurfaceInterface();
235   if(currentSurface)
236   {
237     currentSurface->StopRender();
238   }
239
240   StopUpdateRenderThread();
241
242   if(mUpdateRenderThread)
243   {
244     LOG_EVENT("Destroying UpdateRenderThread");
245
246     // wait for the thread to finish
247     pthread_join(*mUpdateRenderThread, NULL);
248
249     delete mUpdateRenderThread;
250     mUpdateRenderThread = NULL;
251   }
252
253   mRunning = FALSE;
254
255   DALI_LOG_RELEASE_INFO("CombinedUpdateRenderController::Stop\n");
256 }
257
258 void CombinedUpdateRenderController::RequestUpdate()
259 {
260   LOG_EVENT_TRACE;
261
262   // Increment the update-request count to the maximum
263   if(mUpdateRequestCount < MAXIMUM_UPDATE_REQUESTS)
264   {
265     ++mUpdateRequestCount;
266   }
267
268   if(mRunning && IsUpdateRenderThreadPaused())
269   {
270     LOG_EVENT("Processing");
271
272     RunUpdateRenderThread(CONTINUOUS, AnimationProgression::NONE, UpdateMode::NORMAL);
273   }
274
275   ConditionalWait::ScopedLock updateLock(mUpdateRenderThreadWaitCondition);
276   mPendingRequestUpdate = TRUE;
277 }
278
279 void CombinedUpdateRenderController::RequestUpdateOnce(UpdateMode updateMode)
280 {
281   // Increment the update-request count to the maximum
282   if(mUpdateRequestCount < MAXIMUM_UPDATE_REQUESTS)
283   {
284     ++mUpdateRequestCount;
285   }
286
287   if(IsUpdateRenderThreadPaused() || updateMode == UpdateMode::FORCE_RENDER)
288   {
289     LOG_EVENT_TRACE;
290
291     // Run Update/Render once
292     RunUpdateRenderThread(ONCE, AnimationProgression::NONE, updateMode);
293   }
294 }
295
296 void CombinedUpdateRenderController::ReplaceSurface(Dali::RenderSurfaceInterface* newSurface)
297 {
298   LOG_EVENT_TRACE;
299
300   if(mUpdateRenderThread)
301   {
302     // Set the ThreadSyncronizationInterface on the new surface
303     newSurface->SetThreadSynchronization(*this);
304
305     LOG_EVENT("Starting to replace the surface, event-thread blocked");
306
307     // Start replacing the surface.
308     {
309       ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
310       mPostRendering = FALSE; // Clear the post-rendering flag as Update/Render thread will replace the surface now
311       mNewSurface    = newSurface;
312       mUpdateRenderThreadWaitCondition.Notify(lock);
313     }
314
315     // Wait until the surface has been replaced
316     mSurfaceSemaphore.Acquire();
317
318     LOG_EVENT("Surface replaced, event-thread continuing");
319   }
320 }
321
322 void CombinedUpdateRenderController::DeleteSurface(Dali::RenderSurfaceInterface* surface)
323 {
324   LOG_EVENT_TRACE;
325
326   if(mUpdateRenderThread)
327   {
328     LOG_EVENT("Starting to delete the surface, event-thread blocked");
329
330     // Start replacing the surface.
331     {
332       ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
333       mPostRendering  = FALSE; // Clear the post-rendering flag as Update/Render thread will delete the surface now
334       mDeletedSurface = surface;
335       mUpdateRenderThreadWaitCondition.Notify(lock);
336     }
337
338     // Wait until the surface has been deleted
339     mSurfaceSemaphore.Acquire();
340
341     LOG_EVENT("Surface deleted, event-thread continuing");
342   }
343 }
344
345 void CombinedUpdateRenderController::WaitForGraphicsInitialization()
346 {
347   ConditionalWait::ScopedLock lk(mGraphicsInitializeWait);
348   LOG_EVENT_TRACE;
349
350   if(mUpdateRenderThread)
351   {
352     LOG_EVENT("Waiting for graphics initialisation, event-thread blocked");
353
354     // Wait until the graphics has been initialised
355     mGraphicsInitializeWait.Wait(lk);
356
357     LOG_EVENT("graphics initialised, event-thread continuing");
358   }
359 }
360
361 void CombinedUpdateRenderController::ResizeSurface()
362 {
363   LOG_EVENT_TRACE;
364
365   LOG_EVENT("Resize the surface");
366
367   {
368     ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
369     mPostRendering = FALSE; // Clear the post-rendering flag as Update/Render thread will resize the surface now
370     // Surface is resized and the surface resized count is increased.
371     mSurfaceResized++;
372     mUpdateRenderThreadWaitCondition.Notify(lock);
373   }
374 }
375
376 void CombinedUpdateRenderController::SetRenderRefreshRate(unsigned int numberOfFramesPerRender)
377 {
378   // Not protected by lock, but written to rarely so not worth adding a lock when reading
379   mDefaultFrameDelta                = numberOfFramesPerRender * DEFAULT_FRAME_DURATION_IN_SECONDS;
380   mDefaultFrameDurationMilliseconds = uint64_t(numberOfFramesPerRender) * DEFAULT_FRAME_DURATION_IN_MILLISECONDS;
381   mDefaultFrameDurationNanoseconds  = uint64_t(numberOfFramesPerRender) * DEFAULT_FRAME_DURATION_IN_NANOSECONDS;
382   mDefaultHalfFrameNanoseconds      = mDefaultFrameDurationNanoseconds / 2u;
383
384   LOG_EVENT("mDefaultFrameDelta(%.6f), mDefaultFrameDurationMilliseconds(%lld), mDefaultFrameDurationNanoseconds(%lld)", mDefaultFrameDelta, mDefaultFrameDurationMilliseconds, mDefaultFrameDurationNanoseconds);
385 }
386
387 void CombinedUpdateRenderController::SetPreRenderCallback(CallbackBase* callback)
388 {
389   LOG_EVENT_TRACE;
390   LOG_EVENT("Set PreRender Callback");
391
392   ConditionalWait::ScopedLock updateLock(mUpdateRenderThreadWaitCondition);
393   if(mPreRenderCallback)
394   {
395     delete mPreRenderCallback;
396   }
397   mPreRenderCallback = callback;
398 }
399
400 void CombinedUpdateRenderController::AddSurface(Dali::RenderSurfaceInterface* surface)
401 {
402   LOG_EVENT_TRACE;
403   LOG_EVENT("Surface is added");
404   if(mUpdateRenderThread)
405   {
406     // Set the ThreadSyncronizationInterface on the added surface
407     surface->SetThreadSynchronization(*this);
408   }
409 }
410
411 ///////////////////////////////////////////////////////////////////////////////////////////////////
412 // EVENT THREAD
413 ///////////////////////////////////////////////////////////////////////////////////////////////////
414
415 void CombinedUpdateRenderController::RunUpdateRenderThread(int numberOfCycles, AnimationProgression animationProgression, UpdateMode updateMode)
416 {
417   ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
418
419   switch(mThreadMode)
420   {
421     case ThreadMode::NORMAL:
422     {
423       mUpdateRenderRunCount    = numberOfCycles;
424       mUseElapsedTimeAfterWait = (animationProgression == AnimationProgression::USE_ELAPSED_TIME);
425       break;
426     }
427     case ThreadMode::RUN_IF_REQUESTED:
428     {
429       if(updateMode != UpdateMode::FORCE_RENDER)
430       {
431         // Render only if the update mode is FORCE_RENDER which means the application requests it.
432         // We don't want to awake the update thread.
433         return;
434       }
435
436       mUpdateRenderRunCount++;         // Increase the update request count
437       mUseElapsedTimeAfterWait = TRUE; // The elapsed time should be used. We want animations to proceed.
438       break;
439     }
440   }
441
442   mUpdateRenderThreadCanSleep = FALSE;
443   mUploadWithoutRendering     = (updateMode == UpdateMode::SKIP_RENDER);
444   LOG_COUNTER_EVENT("mUpdateRenderRunCount: %d, mUseElapsedTimeAfterWait: %d", mUpdateRenderRunCount, mUseElapsedTimeAfterWait);
445   mUpdateRenderThreadWaitCondition.Notify(lock);
446 }
447
448 void CombinedUpdateRenderController::PauseUpdateRenderThread()
449 {
450   ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
451   mUpdateRenderRunCount = 0;
452 }
453
454 void CombinedUpdateRenderController::StopUpdateRenderThread()
455 {
456   ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
457   mDestroyUpdateRenderThread = TRUE;
458   mUpdateRenderThreadWaitCondition.Notify(lock);
459 }
460
461 bool CombinedUpdateRenderController::IsUpdateRenderThreadPaused()
462 {
463   ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
464
465   if(mThreadMode == ThreadMode::RUN_IF_REQUESTED)
466   {
467     return !mRunning || mUpdateRenderThreadCanSleep;
468   }
469
470   return (mUpdateRenderRunCount != CONTINUOUS) || // Report paused if NOT continuously running
471          mUpdateRenderThreadCanSleep;             // Report paused if sleeping
472 }
473
474 void CombinedUpdateRenderController::ProcessSleepRequest()
475 {
476   LOG_EVENT_TRACE;
477
478   // Decrement Update request count
479   if(mUpdateRequestCount > 0)
480   {
481     --mUpdateRequestCount;
482   }
483
484   // Can sleep if our update-request count is 0
485   // Update/Render thread can choose to carry on updating if it determines more update/renders are required
486   if(mUpdateRequestCount == 0)
487   {
488     LOG_EVENT("Going to sleep");
489
490     ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
491     mUpdateRenderThreadCanSleep = TRUE;
492   }
493 }
494
495 ///////////////////////////////////////////////////////////////////////////////////////////////////
496 // UPDATE/RENDER THREAD
497 ///////////////////////////////////////////////////////////////////////////////////////////////////
498
499 void CombinedUpdateRenderController::UpdateRenderThread()
500 {
501   SetThreadName("RenderThread\0");
502
503   // Install a function for logging
504   mEnvironmentOptions.InstallLogFunction();
505
506   // Install a function for tracing
507   mEnvironmentOptions.InstallTraceFunction();
508
509   LOG_UPDATE_RENDER("THREAD CREATED");
510
511   // Initialize graphics
512   GraphicsInterface& graphics = mAdaptorInterfaces.GetGraphicsInterface();
513   graphics.Initialize();
514
515   Dali::DisplayConnection& displayConnection = mAdaptorInterfaces.GetDisplayConnectionInterface();
516   displayConnection.Initialize(); //@todo Move InitializeGraphics code into graphics implementation
517
518   NotifyGraphicsInitialised();
519
520   //@todo Vk swaps this around, but we need to support surfaceless context for multi-window
521   graphics.ConfigureSurface(mAdaptorInterfaces.GetRenderSurfaceInterface());
522
523   // Tell core it has a context
524   mCore.ContextCreated();
525
526   NotifyThreadInitialised();
527
528   // Update time
529   uint64_t lastFrameTime;
530   TimeService::GetNanoseconds(lastFrameTime);
531
532   LOG_UPDATE_RENDER("THREAD INITIALISED");
533
534   bool     useElapsedTime     = true;
535   bool     updateRequired     = true;
536   uint64_t timeToSleepUntil   = 0;
537   int      extraFramesDropped = 0;
538
539   const unsigned int renderToFboInterval = mEnvironmentOptions.GetRenderToFboInterval();
540   const bool         renderToFboEnabled  = 0u != renderToFboInterval;
541   unsigned int       frameCount          = 0u;
542
543   while(UpdateRenderReady(useElapsedTime, updateRequired, timeToSleepUntil))
544   {
545     LOG_UPDATE_RENDER_TRACE;
546
547     // Performance statistics are logged upon a VSYNC tick so use this point for a VSync marker
548     AddPerformanceMarker(PerformanceInterface::VSYNC);
549
550     uint64_t currentFrameStartTime = 0;
551     TimeService::GetNanoseconds(currentFrameStartTime);
552
553     uint64_t timeSinceLastFrame = currentFrameStartTime - lastFrameTime;
554
555     // Optional FPS Tracking when continuously rendering
556     if(useElapsedTime && mFpsTracker.Enabled())
557     {
558       float absoluteTimeSinceLastRender = timeSinceLastFrame * NANOSECONDS_TO_SECOND;
559       mFpsTracker.Track(absoluteTimeSinceLastRender);
560     }
561
562     lastFrameTime = currentFrameStartTime; // Store frame start time
563
564     //////////////////////////////
565     // REPLACE SURFACE
566     //////////////////////////////
567
568     Dali::RenderSurfaceInterface* newSurface = ShouldSurfaceBeReplaced();
569     if(DALI_UNLIKELY(newSurface))
570     {
571       LOG_UPDATE_RENDER_TRACE_FMT("Replacing Surface");
572       // This is designed for replacing pixmap surfaces, but should work for window as well
573       // we need to delete the surface and renderable (pixmap / window)
574       // Then create a new pixmap/window and new surface
575       // If the new surface has a different display connection, then the context will be lost
576       mAdaptorInterfaces.GetDisplayConnectionInterface().Initialize();
577       newSurface->InitializeGraphics();
578       newSurface->MakeContextCurrent();
579       // TODO: ReplaceGraphicsSurface doesn't work, InitializeGraphics()
580       // already creates new surface window, the surface and the context.
581       // We probably don't need ReplaceGraphicsSurface at all.
582       // newSurface->ReplaceGraphicsSurface();
583       SurfaceReplaced();
584     }
585
586     const bool isRenderingToFbo = renderToFboEnabled && ((0u == frameCount) || (0u != frameCount % renderToFboInterval));
587     ++frameCount;
588
589     //////////////////////////////
590     // UPDATE
591     //////////////////////////////
592
593     const unsigned int currentTime   = currentFrameStartTime / NANOSECONDS_PER_MILLISECOND;
594     const unsigned int nextFrameTime = currentTime + mDefaultFrameDurationMilliseconds;
595
596     uint64_t noOfFramesSinceLastUpdate = 1;
597     float    frameDelta                = 0.0f;
598     if(useElapsedTime)
599     {
600       if(mThreadMode == ThreadMode::RUN_IF_REQUESTED)
601       {
602         extraFramesDropped = 0;
603         while(timeSinceLastFrame >= mDefaultFrameDurationNanoseconds)
604         {
605           timeSinceLastFrame -= mDefaultFrameDurationNanoseconds;
606           extraFramesDropped++;
607         }
608       }
609
610       // If using the elapsed time, then calculate frameDelta as a multiple of mDefaultFrameDelta
611       noOfFramesSinceLastUpdate += extraFramesDropped;
612
613       frameDelta = mDefaultFrameDelta * noOfFramesSinceLastUpdate;
614     }
615     LOG_UPDATE_RENDER("timeSinceLastFrame(%llu) noOfFramesSinceLastUpdate(%u) frameDelta(%.6f)", timeSinceLastFrame, noOfFramesSinceLastUpdate, frameDelta);
616
617     Integration::UpdateStatus updateStatus;
618
619     AddPerformanceMarker(PerformanceInterface::UPDATE_START);
620     mCore.Update(frameDelta,
621                  currentTime,
622                  nextFrameTime,
623                  updateStatus,
624                  renderToFboEnabled,
625                  isRenderingToFbo);
626     AddPerformanceMarker(PerformanceInterface::UPDATE_END);
627
628     unsigned int keepUpdatingStatus = updateStatus.KeepUpdating();
629
630     // Tell the event-thread to wake up (if asleep) and send a notification event to Core if required
631     if(updateStatus.NeedsNotification())
632     {
633       mNotificationTrigger.Trigger();
634       LOG_UPDATE_RENDER("Notification Triggered");
635     }
636
637     // Optional logging of update/render status
638     mUpdateStatusLogger.Log(keepUpdatingStatus);
639
640     //////////////////////////////
641     // RENDER
642     //////////////////////////////
643
644     mAdaptorInterfaces.GetDisplayConnectionInterface().ConsumeEvents();
645
646     if(mPreRenderCallback != NULL)
647     {
648       bool keepCallback = CallbackBase::ExecuteReturn<bool>(*mPreRenderCallback);
649       if(!keepCallback)
650       {
651         delete mPreRenderCallback;
652         mPreRenderCallback = NULL;
653       }
654     }
655
656     graphics.ActivateResourceContext();
657
658     if(mFirstFrameAfterResume)
659     {
660       // mFirstFrameAfterResume is set to true when the thread is resumed
661       // Let graphics know the first frame after thread initialized or resumed.
662       graphics.SetFirstFrameAfterResume();
663       mFirstFrameAfterResume = FALSE;
664     }
665
666     Integration::RenderStatus renderStatus;
667
668     AddPerformanceMarker(PerformanceInterface::RENDER_START);
669
670     // Upload shared resources
671     mCore.PreRender(renderStatus, mForceClear, mUploadWithoutRendering);
672
673     if(!mUploadWithoutRendering)
674     {
675       // Go through each window
676       WindowContainer windows;
677       mAdaptorInterfaces.GetWindowContainerInterface(windows);
678
679       bool sceneSurfaceResized;
680
681       for(auto&& window : windows)
682       {
683         Dali::Integration::Scene      scene         = window->GetScene();
684         Dali::RenderSurfaceInterface* windowSurface = window->GetSurface();
685
686         if(scene && windowSurface)
687         {
688           Integration::RenderStatus windowRenderStatus;
689
690           // Get Surface Resized flag
691           sceneSurfaceResized = scene.IsSurfaceRectChanged();
692
693           windowSurface->InitializeGraphics();
694
695           // clear previous frame damaged render items rects, buffer history is tracked on surface level
696           mDamagedRects.clear();
697
698           // Collect damage rects
699           mCore.PreRender(scene, mDamagedRects);
700
701           // Render off-screen frame buffers first if any
702           mCore.RenderScene(windowRenderStatus, scene, true);
703
704           Rect<int> clippingRect; // Empty for fbo rendering
705
706           // Switch to the context of the surface, merge damaged areas for previous frames
707           windowSurface->PreRender(sceneSurfaceResized, mDamagedRects, clippingRect); // Switch GL context
708
709           if(clippingRect.IsEmpty())
710           {
711             mDamagedRects.clear();
712           }
713
714           // Render the surface
715           mCore.RenderScene(windowRenderStatus, scene, false, clippingRect);
716
717           if(windowRenderStatus.NeedsPostRender())
718           {
719             windowSurface->PostRender(false, false, sceneSurfaceResized, mDamagedRects); // Swap Buffer with damage
720           }
721
722           // If surface is resized, the surface resized count is decreased.
723           if(DALI_UNLIKELY(sceneSurfaceResized))
724           {
725             SurfaceResized();
726           }
727         }
728       }
729     }
730
731     mCore.PostRender(mUploadWithoutRendering);
732
733     //////////////////////////////
734     // DELETE SURFACE
735     //////////////////////////////
736
737     Dali::RenderSurfaceInterface* deletedSurface = ShouldSurfaceBeDeleted();
738     if(DALI_UNLIKELY(deletedSurface))
739     {
740       LOG_UPDATE_RENDER_TRACE_FMT("Deleting Surface");
741
742       deletedSurface->DestroySurface();
743
744       SurfaceDeleted();
745     }
746
747     AddPerformanceMarker(PerformanceInterface::RENDER_END);
748
749     mForceClear = false;
750
751     // Trigger event thread to request Update/Render thread to sleep if update not required
752     if((Integration::KeepUpdating::NOT_REQUESTED == keepUpdatingStatus) && !renderStatus.NeedsUpdate())
753     {
754       mSleepTrigger->Trigger();
755       updateRequired = false;
756       LOG_UPDATE_RENDER("Sleep Triggered");
757     }
758     else
759     {
760       updateRequired = true;
761     }
762
763     //////////////////////////////
764     // FRAME TIME
765     //////////////////////////////
766
767     extraFramesDropped = 0;
768
769     if(timeToSleepUntil == 0)
770     {
771       // If this is the first frame after the thread is initialized or resumed, we
772       // use the actual time the current frame starts from to calculate the time to
773       // sleep until the next frame.
774       timeToSleepUntil = currentFrameStartTime + mDefaultFrameDurationNanoseconds;
775     }
776     else
777     {
778       // Otherwise, always use the sleep-until time calculated in the last frame to
779       // calculate the time to sleep until the next frame. In this way, if there is
780       // any time gap between the current frame and the next frame, or if update or
781       // rendering in the current frame takes too much time so that the specified
782       // sleep-until time has already passed, it will try to keep the frames syncing
783       // by shortening the duration of the next frame.
784       timeToSleepUntil += mDefaultFrameDurationNanoseconds;
785
786       // Check the current time at the end of the frame
787       uint64_t currentFrameEndTime = 0;
788       TimeService::GetNanoseconds(currentFrameEndTime);
789       while(currentFrameEndTime > timeToSleepUntil + mDefaultFrameDurationNanoseconds)
790       {
791         // We are more than one frame behind already, so just drop the next frames
792         // until the sleep-until time is later than the current time so that we can
793         // catch up.
794         timeToSleepUntil += mDefaultFrameDurationNanoseconds;
795         extraFramesDropped++;
796       }
797     }
798
799     // Render to FBO is intended to measure fps above 60 so sleep is not wanted.
800     if(0u == renderToFboInterval)
801     {
802       // Sleep until at least the the default frame duration has elapsed. This will return immediately if the specified end-time has already passed.
803       TimeService::SleepUntil(timeToSleepUntil);
804     }
805   }
806
807   // Inform core of context destruction
808   mCore.ContextDestroyed();
809
810   WindowContainer windows;
811   mAdaptorInterfaces.GetWindowContainerInterface(windows);
812
813   // Destroy surfaces
814   for(auto&& window : windows)
815   {
816     Dali::RenderSurfaceInterface* surface = window->GetSurface();
817     surface->DestroySurface();
818   }
819
820   graphics.Shutdown();
821
822   LOG_UPDATE_RENDER("THREAD DESTROYED");
823
824   // Uninstall the logging function
825   mEnvironmentOptions.UnInstallLogFunction();
826 }
827
828 bool CombinedUpdateRenderController::UpdateRenderReady(bool& useElapsedTime, bool updateRequired, uint64_t& timeToSleepUntil)
829 {
830   useElapsedTime = true;
831
832   ConditionalWait::ScopedLock updateLock(mUpdateRenderThreadWaitCondition);
833   while((!mUpdateRenderRunCount ||                                                      // Should try to wait if event-thread has paused the Update/Render thread
834          (mUpdateRenderThreadCanSleep && !updateRequired && !mPendingRequestUpdate)) && // Ensure we wait if we're supposed to be sleeping AND do not require another update
835         !mDestroyUpdateRenderThread &&                                                  // Ensure we don't wait if the update-render-thread is supposed to be destroyed
836         !mNewSurface &&                                                                 // Ensure we don't wait if we need to replace the surface
837         !mDeletedSurface &&                                                             // Ensure we don't wait if we need to delete the surface
838         !mSurfaceResized)                                                               // Ensure we don't wait if we need to resize the surface
839   {
840     LOG_UPDATE_RENDER("WAIT: mUpdateRenderRunCount:       %d", mUpdateRenderRunCount);
841     LOG_UPDATE_RENDER("      mUpdateRenderThreadCanSleep: %d, updateRequired: %d, mPendingRequestUpdate: %d", mUpdateRenderThreadCanSleep, updateRequired, mPendingRequestUpdate);
842     LOG_UPDATE_RENDER("      mDestroyUpdateRenderThread:  %d", mDestroyUpdateRenderThread);
843     LOG_UPDATE_RENDER("      mNewSurface:                 %d", mNewSurface);
844     LOG_UPDATE_RENDER("      mDeletedSurface:             %d", mDeletedSurface);
845     LOG_UPDATE_RENDER("      mSurfaceResized:             %d", mSurfaceResized);
846
847     // Reset the time when the thread is waiting, so the sleep-until time for
848     // the first frame after resuming should be based on the actual start time
849     // of the first frame.
850     timeToSleepUntil = 0;
851
852     mUpdateRenderThreadWaitCondition.Wait(updateLock);
853
854     if(!mUseElapsedTimeAfterWait)
855     {
856       useElapsedTime = false;
857     }
858   }
859
860   LOG_COUNTER_UPDATE_RENDER("mUpdateRenderRunCount:       %d", mUpdateRenderRunCount);
861   LOG_COUNTER_UPDATE_RENDER("mUpdateRenderThreadCanSleep: %d, updateRequired: %d, mPendingRequestUpdate: %d", mUpdateRenderThreadCanSleep, updateRequired, mPendingRequestUpdate);
862   LOG_COUNTER_UPDATE_RENDER("mDestroyUpdateRenderThread:  %d", mDestroyUpdateRenderThread);
863   LOG_COUNTER_UPDATE_RENDER("mNewSurface:                 %d", mNewSurface);
864   LOG_COUNTER_UPDATE_RENDER("mDeletedSurface:             %d", mDeletedSurface);
865   LOG_COUNTER_UPDATE_RENDER("mSurfaceResized:             %d", mSurfaceResized);
866
867   mUseElapsedTimeAfterWait    = FALSE;
868   mUpdateRenderThreadCanSleep = FALSE;
869   mPendingRequestUpdate       = FALSE;
870
871   // If we've been asked to run Update/Render cycles a finite number of times then decrement so we wait after the
872   // requested number of cycles
873   if(mUpdateRenderRunCount > 0)
874   {
875     --mUpdateRenderRunCount;
876   }
877
878   // Keep the update-render thread alive if this thread is NOT to be destroyed
879   return !mDestroyUpdateRenderThread;
880 }
881
882 Dali::RenderSurfaceInterface* CombinedUpdateRenderController::ShouldSurfaceBeReplaced()
883 {
884   ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
885
886   Dali::RenderSurfaceInterface* newSurface = mNewSurface;
887   mNewSurface                              = NULL;
888
889   return newSurface;
890 }
891
892 void CombinedUpdateRenderController::SurfaceReplaced()
893 {
894   // Just increment the semaphore
895   mSurfaceSemaphore.Release(1);
896 }
897
898 Dali::RenderSurfaceInterface* CombinedUpdateRenderController::ShouldSurfaceBeDeleted()
899 {
900   ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
901
902   Dali::RenderSurfaceInterface* deletedSurface = mDeletedSurface;
903   mDeletedSurface                              = NULL;
904
905   return deletedSurface;
906 }
907
908 void CombinedUpdateRenderController::SurfaceDeleted()
909 {
910   // Just increment the semaphore
911   mSurfaceSemaphore.Release(1);
912 }
913
914 void CombinedUpdateRenderController::SurfaceResized()
915 {
916   ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
917   if(mSurfaceResized)
918   {
919     mSurfaceResized--;
920   }
921 }
922
923 ///////////////////////////////////////////////////////////////////////////////////////////////////
924 // ALL THREADS
925 ///////////////////////////////////////////////////////////////////////////////////////////////////
926
927 void CombinedUpdateRenderController::NotifyThreadInitialised()
928 {
929   // Just increment the semaphore
930   mEventThreadSemaphore.Release(1);
931 }
932
933 void CombinedUpdateRenderController::NotifyGraphicsInitialised()
934 {
935   mGraphicsInitializeWait.Notify();
936 }
937
938 void CombinedUpdateRenderController::AddPerformanceMarker(PerformanceInterface::MarkerType type)
939 {
940   if(mPerformanceInterface)
941   {
942     mPerformanceInterface->AddMarker(type);
943   }
944 }
945
946 /////////////////////////////////////////////////////////////////////////////////////////////////
947 // POST RENDERING: EVENT THREAD
948 /////////////////////////////////////////////////////////////////////////////////////////////////
949
950 void CombinedUpdateRenderController::PostRenderComplete()
951 {
952   ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
953   mPostRendering = FALSE;
954   mUpdateRenderThreadWaitCondition.Notify(lock);
955 }
956
957 ///////////////////////////////////////////////////////////////////////////////////////////////////
958 // POST RENDERING: RENDER THREAD
959 ///////////////////////////////////////////////////////////////////////////////////////////////////
960
961 void CombinedUpdateRenderController::PostRenderStarted()
962 {
963   ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
964   mPostRendering = TRUE;
965 }
966
967 void CombinedUpdateRenderController::PostRenderWaitForCompletion()
968 {
969   ConditionalWait::ScopedLock lock(mUpdateRenderThreadWaitCondition);
970   while(mPostRendering &&
971         !mNewSurface &&     // We should NOT wait if we're replacing the surface
972         !mDeletedSurface && // We should NOT wait if we're deleting the surface
973         !mDestroyUpdateRenderThread)
974   {
975     mUpdateRenderThreadWaitCondition.Wait(lock);
976   }
977 }
978
979 } // namespace Adaptor
980
981 } // namespace Internal
982
983 } // namespace Dali