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