Merge "Remove RenderThread::mSurface pointer before mWindow.Reset()" into devel/master
[platform/core/uifw/dali-adaptor.git] / adaptors / base / render-thread.cpp
1 /*
2  * Copyright (c) 2014 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 "render-thread.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/integration-api/debug.h>
23
24 // INTERNAL INCLUDES
25 #include <base/interfaces/adaptor-internal-services.h>
26 #include <base/update-render-synchronization.h>
27 #include <base/environment-options.h>
28 #include <base/display-connection.h>
29
30 namespace Dali
31 {
32
33 namespace Internal
34 {
35
36 namespace Adaptor
37 {
38
39 namespace
40 {
41 #if defined(DEBUG_ENABLED)
42 Integration::Log::Filter* gRenderLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_RENDER_THREAD");
43 #endif
44 }
45
46 RenderRequest::RenderRequest(RenderRequest::Request type)
47 : mRequestType(type)
48 {
49 }
50
51 RenderRequest::Request RenderRequest::GetType()
52 {
53   return mRequestType;
54 }
55
56 ReplaceSurfaceRequest::ReplaceSurfaceRequest()
57 : RenderRequest(RenderRequest::REPLACE_SURFACE),
58   mNewSurface( NULL ),
59   mReplaceCompleted(false)
60 {
61 }
62
63 void ReplaceSurfaceRequest::SetSurface(RenderSurface* newSurface)
64 {
65   mNewSurface = newSurface;
66 }
67
68 RenderSurface* ReplaceSurfaceRequest::GetSurface()
69 {
70   return mNewSurface;
71 }
72
73 void ReplaceSurfaceRequest::ReplaceCompleted()
74 {
75   mReplaceCompleted = true;
76 }
77
78 bool ReplaceSurfaceRequest::GetReplaceCompleted()
79 {
80   return mReplaceCompleted != 0u;
81 }
82
83
84 RenderThread::RenderThread( UpdateRenderSynchronization& sync,
85                             AdaptorInternalServices& adaptorInterfaces,
86                             const EnvironmentOptions& environmentOptions )
87 : mUpdateRenderSync( sync ),
88   mCore( adaptorInterfaces.GetCore() ),
89   mGLES( adaptorInterfaces.GetGlesInterface() ),
90   mEglFactory( &adaptorInterfaces.GetEGLFactoryInterface()),
91   mEGL( NULL ),
92   mThread( NULL ),
93   mEnvironmentOptions( environmentOptions ),
94   mSurfaceReplaced(false)
95 {
96   // set the initial values before render thread starts
97   mSurface = adaptorInterfaces.GetRenderSurfaceInterface();
98
99   mDisplayConnection = Dali::DisplayConnection::New();
100 }
101
102 RenderThread::~RenderThread()
103 {
104   if (mDisplayConnection)
105   {
106     delete mDisplayConnection;
107     mDisplayConnection = NULL;
108   }
109
110   DALI_ASSERT_ALWAYS( mThread == NULL && "RenderThread is still alive");
111   mEglFactory->Destroy();
112 }
113
114 void RenderThread::Start()
115 {
116   DALI_LOG_INFO( gRenderLogFilter, Debug::Verbose, "RenderThread::Start()\n");
117
118   // initialise GL and kick off render thread
119   DALI_ASSERT_ALWAYS( !mEGL && "Egl already initialized" );
120
121   // create the render thread, initially we are rendering
122   mThread = new pthread_t();
123   int error = pthread_create( mThread, NULL, InternalThreadEntryFunc, this );
124   DALI_ASSERT_ALWAYS( !error && "Return code from pthread_create() in RenderThread" );
125
126   if( mSurface )
127   {
128     mSurface->StartRender();
129   }
130 }
131
132 void RenderThread::Stop()
133 {
134   DALI_LOG_INFO( gRenderLogFilter, Debug::Verbose, "RenderThread::Stop()\n");
135
136   if( mSurface )
137   {
138     // Tell surface we have stopped rendering
139     mSurface->StopRender();
140
141     // The surface will be destroyed soon; this pointer will become invalid
142     mSurface = NULL;
143   }
144
145   // shutdown the render thread and destroy the opengl context
146   if( mThread )
147   {
148     // wait for the thread to finish
149     pthread_join(*mThread, NULL);
150
151     delete mThread;
152     mThread = NULL;
153   }
154 }
155
156 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
157 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
158 // The following methods are all executed inside render thread !!!
159 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
160 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
161
162 bool RenderThread::Run()
163 {
164   // install a function for logging
165   mEnvironmentOptions.InstallLogFunction();
166
167   InitializeEgl();
168
169   bool running( true );
170
171   Dali::Integration::RenderStatus renderStatus;
172
173   uint64_t currentTime( 0 );
174
175   // render loop, we stay inside here when rendering
176   while( running )
177   {
178     // Sync with update thread and get any outstanding requests from UpdateRenderSynchronization
179     DALI_LOG_INFO( gRenderLogFilter, Debug::Verbose, "RenderThread::Run. 1 - RenderSyncWithUpdate()\n");
180     RenderRequest* request = NULL;
181     running = mUpdateRenderSync.RenderSyncWithUpdate( request );
182
183     DALI_LOG_INFO( gRenderLogFilter, Debug::Verbose, "RenderThread::Run. 2 - Process requests\n");
184
185     // Consume any pending events to avoid memory leaks
186     mDisplayConnection->ConsumeEvents();
187
188     bool processRequests = true;
189     bool requestProcessed = false;
190     while( processRequests && running)
191     {
192       // Check if we've got any requests from the main thread (e.g. replace surface)
193       requestProcessed = ProcessRequest( request );
194
195       // perform any pre-render operations
196       DALI_LOG_INFO( gRenderLogFilter, Debug::Verbose, "RenderThread::Run. 3 - PreRender\n");
197       bool preRendered = PreRender(); // Returns false if no surface onto which to render
198       if( preRendered )
199       {
200         processRequests = false;
201       }
202       else
203       {
204         // Block until new surface... - cleared by ReplaceSurface code in UpdateRenderController
205         running = mUpdateRenderSync.RenderSyncWithRequest(request);
206       }
207     }
208
209     if( running )
210     {
211        // Render
212       DALI_LOG_INFO( gRenderLogFilter, Debug::Verbose, "RenderThread::Run. 4 - Core.Render()\n");
213       mCore.Render( renderStatus );
214
215       // Notify the update-thread that a render has completed
216       DALI_LOG_INFO( gRenderLogFilter, Debug::Verbose, "RenderThread::Run. 5 - Sync.RenderFinished()\n");
217       mUpdateRenderSync.RenderFinished( renderStatus.NeedsUpdate(), requestProcessed );
218
219       uint64_t newTime( mUpdateRenderSync.GetTimeMicroseconds() );
220
221       // perform any post-render operations
222       if ( renderStatus.HasRendered() )
223       {
224         DALI_LOG_INFO( gRenderLogFilter, Debug::Verbose, "RenderThread::Run. 6 - PostRender()\n");
225         PostRender( static_cast< unsigned int >(newTime - currentTime) );
226       }
227
228       currentTime = newTime;
229     }
230   }
231
232   // shut down egl
233   ShutdownEgl();
234
235   // install a function for logging
236   mEnvironmentOptions.UnInstallLogFunction();
237
238   return true;
239 }
240
241 void RenderThread::InitializeEgl()
242 {
243   mEGL = mEglFactory->Create();
244
245   DALI_ASSERT_ALWAYS( mSurface && "NULL surface" );
246
247   // initialize egl & OpenGL
248   mDisplayConnection->InitializeEgl( *mEGL );
249   mSurface->InitializeEgl( *mEGL );
250
251   // create the OpenGL context
252   mEGL->CreateContext();
253
254   // create the OpenGL surface
255   mSurface->CreateEglSurface(*mEGL);
256
257   // Make it current
258   mEGL->MakeContextCurrent();
259
260   // set the initial sync mode
261
262   // tell core it has a context
263   mCore.ContextCreated();
264
265 }
266
267 bool RenderThread::ProcessRequest( RenderRequest* request )
268 {
269   bool processedRequest = false;
270
271   if( request != NULL )
272   {
273     switch(request->GetType())
274     {
275       case RenderRequest::REPLACE_SURFACE:
276       {
277         // change the surface
278         ReplaceSurfaceRequest* replaceSurfaceRequest = static_cast<ReplaceSurfaceRequest*>(request);
279         ReplaceSurface( replaceSurfaceRequest->GetSurface() );
280         replaceSurfaceRequest->ReplaceCompleted();
281         processedRequest = true;
282         break;
283       }
284     }
285   }
286   return processedRequest;
287 }
288
289 void RenderThread::ReplaceSurface( RenderSurface* newSurface )
290 {
291   // This is designed for replacing pixmap surfaces, but should work for window as well
292   // we need to delete the egl surface and renderable (pixmap / window)
293   // Then create a new pixmap/window and new egl surface
294   // If the new surface has a different display connection, then the context will be lost
295   DALI_ASSERT_ALWAYS(newSurface && "NULL surface");
296
297   mDisplayConnection->InitializeEgl(*mEGL);
298
299   bool contextLost = newSurface->ReplaceEGLSurface(*mEGL);
300   if( contextLost )
301   {
302     DALI_LOG_WARNING("Context lost\n");
303     mCore.ContextDestroyed();
304     mCore.ContextCreated();
305   }
306
307   // use the new surface from now on
308   mSurface = newSurface;
309   mSurfaceReplaced = true;
310 }
311
312 void RenderThread::ShutdownEgl()
313 {
314   // inform core of context destruction
315   mCore.ContextDestroyed();
316
317   if( mSurface )
318   {
319     // give a chance to destroy the OpenGL surface that created externally
320     mSurface->DestroyEglSurface( *mEGL );
321   }
322
323   // delete the GL context / egl surface
324   mEGL->TerminateGles();
325 }
326
327 bool RenderThread::PreRender()
328 {
329   bool success( false );
330   if( mSurface )
331   {
332     success = mSurface->PreRender( *mEGL, mGLES );
333   }
334
335   if( success )
336   {
337     mGLES.PreRender();
338   }
339   return success;
340 }
341
342 void RenderThread::PostRender( unsigned int timeDelta )
343 {
344   // Inform the gl implementation that rendering has finished before informing the surface
345   mGLES.PostRender(timeDelta);
346
347   if( mSurface )
348   {
349     // Inform the surface that rendering this frame has finished.
350     mSurface->PostRender( *mEGL, mGLES, mDisplayConnection, timeDelta, mSurfaceReplaced );
351   }
352   mSurfaceReplaced = false;
353 }
354
355 } // namespace Adaptor
356
357 } // namespace Internal
358
359 } // namespace Dali