Fix DestroyContext bug
[platform/core/uifw/dali-adaptor.git] / dali / internal / graphics / gles / egl-implementation.cpp
1 /*
2  * Copyright (c) 2019 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
19 // CLASS HEADER
20 #include <dali/internal/graphics/gles/egl-implementation.h>
21
22 // EXTERNAL INCLUDES
23 #include <sstream>
24 #include <dali/integration-api/debug.h>
25 #include <dali/public-api/common/dali-vector.h>
26
27 // INTERNAL INCLUDES
28 #include <dali/public-api/dali-adaptor-common.h>
29 #include <dali/internal/graphics/gles/gl-implementation.h>
30 #include <dali/internal/graphics/gles/egl-debug.h>
31
32 // EGL constants use C style casts
33 #pragma GCC diagnostic push
34 #pragma GCC diagnostic ignored "-Wold-style-cast"
35
36 namespace
37 {
38   const uint32_t THRESHOLD_SWAPBUFFER_COUNT = 5;
39   const uint32_t CHECK_EXTENSION_NUMBER = 2;
40   const std::string EGL_KHR_SURFACELESS_CONTEXT = "EGL_KHR_surfaceless_context";
41   const std::string EGL_KHR_CREATE_CONTEXT = "EGL_KHR_create_context";
42 }
43
44 namespace Dali
45 {
46
47 namespace Internal
48 {
49
50 namespace Adaptor
51 {
52
53 #define TEST_EGL_ERROR(lastCommand) \
54 { \
55   EGLint err = eglGetError(); \
56   if (err != EGL_SUCCESS) \
57   { \
58     DALI_LOG_ERROR("EGL error after %s\n", lastCommand); \
59     Egl::PrintError(err); \
60     DALI_ASSERT_ALWAYS(0 && "EGL error"); \
61   } \
62 }
63
64 EglImplementation::EglImplementation( int multiSamplingLevel,
65                                       Integration::DepthBufferAvailable depthBufferRequired,
66                                       Integration::StencilBufferAvailable stencilBufferRequired )
67 : mContextAttribs(),
68   mEglNativeDisplay( 0 ),
69   mEglNativeWindow( 0 ),
70   mCurrentEglNativePixmap( 0 ),
71   mEglDisplay( 0 ),
72   mEglConfig( 0 ),
73   mEglContext( 0 ),
74   mCurrentEglSurface( 0 ),
75   mCurrentEglContext( EGL_NO_CONTEXT ),
76   mMultiSamplingLevel( multiSamplingLevel ),
77   mGlesVersion( 30 ),
78   mColorDepth( COLOR_DEPTH_24 ),
79   mGlesInitialized( false ),
80   mIsOwnSurface( true ),
81   mIsWindow( true ),
82   mDepthBufferRequired( depthBufferRequired == Integration::DepthBufferAvailable::TRUE ),
83   mStencilBufferRequired( stencilBufferRequired == Integration::StencilBufferAvailable::TRUE ),
84   mIsSurfacelessContextSupported( false ),
85   mIsKhrCreateContextSupported( false ),
86   mSwapBufferCountAfterResume( 0 )
87 {
88 }
89
90 EglImplementation::~EglImplementation()
91 {
92   TerminateGles();
93 }
94
95 bool EglImplementation::InitializeGles( EGLNativeDisplayType display, bool isOwnSurface )
96 {
97   if ( !mGlesInitialized )
98   {
99     mEglNativeDisplay = display;
100
101     //@todo see if we can just EGL_DEFAULT_DISPLAY instead
102     mEglDisplay = eglGetDisplay(mEglNativeDisplay);
103     EGLint error = eglGetError();
104
105     if( mEglDisplay == NULL && error != EGL_SUCCESS )
106     {
107       throw Dali::DaliException( "", "OpenGL ES is not supported");
108     }
109
110     EGLint majorVersion = 0;
111     EGLint minorVersion = 0;
112     if ( !eglInitialize( mEglDisplay, &majorVersion, &minorVersion ) )
113     {
114       return false;
115     }
116     eglBindAPI(EGL_OPENGL_ES_API);
117
118     mIsOwnSurface = isOwnSurface;
119   }
120
121   // Query EGL extensions to check whether surfaceless context is supported
122   const char* const extensionStr = eglQueryString( mEglDisplay, EGL_EXTENSIONS );
123   std::istringstream stream( extensionStr );
124   std::string currentExtension;
125   uint32_t extensionCheckCount = 0;
126   while( std::getline( stream, currentExtension, ' ' ) && extensionCheckCount < CHECK_EXTENSION_NUMBER )
127   {
128     if( currentExtension == EGL_KHR_SURFACELESS_CONTEXT )
129     {
130       mIsSurfacelessContextSupported = true;
131       extensionCheckCount++;
132     }
133     if( currentExtension == EGL_KHR_CREATE_CONTEXT )
134     {
135       mIsKhrCreateContextSupported = true;
136       extensionCheckCount++;
137     }
138   }
139
140   mGlesInitialized = true;
141
142   // We want to display this information all the time, so use the LogMessage directly
143   Integration::Log::LogMessage(Integration::Log::DebugInfo, "EGL Information\n"
144       "            Vendor:        %s\n"
145       "            Version:       %s\n"
146       "            Client APIs:   %s\n"
147       "            Extensions:    %s\n",
148       eglQueryString( mEglDisplay, EGL_VENDOR ),
149       eglQueryString( mEglDisplay, EGL_VERSION ),
150       eglQueryString( mEglDisplay, EGL_CLIENT_APIS ),
151       extensionStr);
152
153   return mGlesInitialized;
154 }
155
156 bool EglImplementation::CreateContext()
157 {
158   // make sure a context isn't created twice
159   DALI_ASSERT_ALWAYS( (mEglContext == 0) && "EGL context recreated" );
160
161   mEglContext = eglCreateContext(mEglDisplay, mEglConfig, NULL, &(mContextAttribs[0]));
162   TEST_EGL_ERROR("eglCreateContext render thread");
163
164   DALI_ASSERT_ALWAYS( EGL_NO_CONTEXT != mEglContext && "EGL context not created" );
165
166   DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VENDOR : %s ***\n", glGetString(GL_VENDOR));
167   DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_RENDERER : %s ***\n", glGetString(GL_RENDERER));
168   DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VERSION : %s ***\n", glGetString(GL_VERSION));
169   DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_SHADING_LANGUAGE_VERSION : %s***\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
170   DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** Supported Extensions ***\n%s\n\n", glGetString(GL_EXTENSIONS));
171
172   return true;
173 }
174
175 bool EglImplementation::CreateWindowContext( EGLContext& eglContext )
176 {
177   // make sure a context isn't created twice
178   DALI_ASSERT_ALWAYS( (eglContext == 0) && "EGL context recreated" );
179
180   eglContext = eglCreateContext(mEglDisplay, mEglConfig, mEglContext, &(mContextAttribs[0]));
181   TEST_EGL_ERROR("eglCreateContext render thread");
182
183   DALI_ASSERT_ALWAYS( EGL_NO_CONTEXT != eglContext && "EGL context not created" );
184
185   DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VENDOR : %s ***\n", glGetString(GL_VENDOR));
186   DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_RENDERER : %s ***\n", glGetString(GL_RENDERER));
187   DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_VERSION : %s ***\n", glGetString(GL_VERSION));
188   DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** GL_SHADING_LANGUAGE_VERSION : %s***\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
189   DALI_LOG_INFO(Debug::Filter::gShader, Debug::General, "*** Supported Extensions ***\n%s\n\n", glGetString(GL_EXTENSIONS));
190
191   mEglWindowContexts.push_back( eglContext );
192
193   return true;
194 }
195
196 void EglImplementation::DestroyContext( EGLContext& eglContext )
197 {
198   if( eglContext )
199   {
200     eglDestroyContext( mEglDisplay, eglContext );
201     eglContext = 0;
202   }
203 }
204
205 void EglImplementation::DestroySurface( EGLSurface& eglSurface )
206 {
207   if(mIsOwnSurface && eglSurface)
208   {
209     // Make context null to prevent crash in driver side
210     MakeContextNull();
211     eglDestroySurface( mEglDisplay, eglSurface );
212     eglSurface = 0;
213   }
214 }
215
216 void EglImplementation::MakeContextCurrent( EGLSurface eglSurface, EGLContext eglContext )
217 {
218   if (mCurrentEglContext == eglContext)
219   {
220     return;
221   }
222
223   mCurrentEglSurface = eglSurface;
224
225   if(mIsOwnSurface)
226   {
227     eglMakeCurrent( mEglDisplay, eglSurface, eglSurface, eglContext );
228
229     mCurrentEglContext = eglContext;
230   }
231
232   EGLint error = eglGetError();
233
234   if ( error != EGL_SUCCESS )
235   {
236     Egl::PrintError(error);
237
238     DALI_ASSERT_ALWAYS(false && "MakeContextCurrent failed!");
239   }
240 }
241
242 void EglImplementation::MakeCurrent( EGLNativePixmapType pixmap, EGLSurface eglSurface )
243 {
244   if (mCurrentEglContext == mEglContext)
245   {
246     return;
247   }
248
249   mCurrentEglNativePixmap = pixmap;
250   mCurrentEglSurface = eglSurface;
251
252   if(mIsOwnSurface)
253   {
254     eglMakeCurrent( mEglDisplay, eglSurface, eglSurface, mEglContext );
255
256     mCurrentEglContext = mEglContext;
257   }
258
259   EGLint error = eglGetError();
260
261   if ( error != EGL_SUCCESS )
262   {
263     Egl::PrintError(error);
264
265     DALI_ASSERT_ALWAYS(false && "MakeCurrent failed!");
266   }
267 }
268
269 void EglImplementation::MakeContextNull()
270 {
271   // clear the current context
272   eglMakeCurrent( mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT );
273   mCurrentEglContext = EGL_NO_CONTEXT;
274 }
275
276 void EglImplementation::TerminateGles()
277 {
278   if ( mGlesInitialized )
279   {
280     // Make context null to prevent crash in driver side
281     MakeContextNull();
282
283     for ( auto eglSurface : mEglWindowSurfaces )
284     {
285       if(mIsOwnSurface && eglSurface)
286       {
287         eglDestroySurface(mEglDisplay, eglSurface);
288       }
289     }
290     eglDestroyContext(mEglDisplay, mEglContext);
291     for ( auto eglContext : mEglWindowContexts )
292     {
293       eglDestroyContext(mEglDisplay, eglContext);
294     }
295
296     eglTerminate(mEglDisplay);
297
298     mEglDisplay = NULL;
299     mEglConfig  = NULL;
300     mEglContext = NULL;
301     mCurrentEglSurface = NULL;
302     mCurrentEglContext = EGL_NO_CONTEXT;
303
304     mGlesInitialized = false;
305   }
306 }
307
308 bool EglImplementation::IsGlesInitialized() const
309 {
310   return mGlesInitialized;
311 }
312
313 void EglImplementation::SwapBuffers( EGLSurface& eglSurface )
314 {
315   if ( eglSurface != EGL_NO_SURFACE ) // skip if using surfaceless context
316   {
317 #ifndef DALI_PROFILE_UBUNTU
318     if( mSwapBufferCountAfterResume < THRESHOLD_SWAPBUFFER_COUNT )
319     {
320       DALI_LOG_RELEASE_INFO( "EglImplementation::SwapBuffers started.\n" );
321     }
322 #endif //DALI_PROFILE_UBUNTU
323
324     eglSwapBuffers( mEglDisplay, eglSurface );
325
326 #ifndef DALI_PROFILE_UBUNTU
327     if( mSwapBufferCountAfterResume < THRESHOLD_SWAPBUFFER_COUNT )
328     {
329       DALI_LOG_RELEASE_INFO( "EglImplementation::SwapBuffers finished.\n" );
330       mSwapBufferCountAfterResume++;
331     }
332 #endif //DALI_PROFILE_UBUNTU
333   }
334 }
335
336 void EglImplementation::CopyBuffers( EGLSurface& eglSurface )
337 {
338   eglCopyBuffers( mEglDisplay, eglSurface, mCurrentEglNativePixmap );
339 }
340
341 void EglImplementation::WaitGL()
342 {
343   eglWaitGL();
344 }
345
346 bool EglImplementation::ChooseConfig( bool isWindowType, ColorDepth depth )
347 {
348   if(mEglConfig && isWindowType == mIsWindow && mColorDepth == depth)
349   {
350     return true;
351   }
352
353   mColorDepth = depth;
354   mIsWindow = isWindowType;
355
356   EGLint numConfigs;
357   Vector<EGLint> configAttribs;
358   configAttribs.Reserve(31);
359
360   if(isWindowType)
361   {
362     configAttribs.PushBack( EGL_SURFACE_TYPE );
363     configAttribs.PushBack( EGL_WINDOW_BIT );
364   }
365   else
366   {
367     configAttribs.PushBack( EGL_SURFACE_TYPE );
368     configAttribs.PushBack( EGL_PIXMAP_BIT );
369   }
370
371   configAttribs.PushBack( EGL_RENDERABLE_TYPE );
372
373   if( mGlesVersion >= 30 )
374   {
375     configAttribs.PushBack( EGL_OPENGL_ES3_BIT_KHR );
376   }
377   else
378   {
379     configAttribs.PushBack( EGL_OPENGL_ES2_BIT );
380   }
381
382 // TODO: enable this flag when it becomes supported
383 //  configAttribs.PushBack( EGL_CONTEXT_FLAGS_KHR );
384 //  configAttribs.PushBack( EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR );
385
386   configAttribs.PushBack( EGL_RED_SIZE );
387   configAttribs.PushBack( 8 );
388   configAttribs.PushBack( EGL_GREEN_SIZE );
389   configAttribs.PushBack( 8 );
390   configAttribs.PushBack( EGL_BLUE_SIZE );
391   configAttribs.PushBack( 8 );
392
393 //  For underlay video playback, we also need to set the alpha value of the 24/32bit window.
394   configAttribs.PushBack( EGL_ALPHA_SIZE );
395   configAttribs.PushBack( 8 );
396
397   configAttribs.PushBack( EGL_DEPTH_SIZE );
398   configAttribs.PushBack( mDepthBufferRequired ? 24 : 0 );
399   configAttribs.PushBack( EGL_STENCIL_SIZE );
400   configAttribs.PushBack( mStencilBufferRequired ? 8 : 0 );
401
402 #ifndef DALI_PROFILE_UBUNTU
403   if( mMultiSamplingLevel != EGL_DONT_CARE )
404   {
405     configAttribs.PushBack( EGL_SAMPLES );
406     configAttribs.PushBack( mMultiSamplingLevel );
407     configAttribs.PushBack( EGL_SAMPLE_BUFFERS );
408     configAttribs.PushBack( 1 );
409   }
410 #endif // DALI_PROFILE_UBUNTU
411   configAttribs.PushBack( EGL_NONE );
412
413   // Ensure number of configs is set to 1 as on some drivers,
414   // eglChooseConfig succeeds but does not actually create a proper configuration.
415   if ( ( eglChooseConfig( mEglDisplay, &(configAttribs[0]), &mEglConfig, 1, &numConfigs ) != EGL_TRUE ) ||
416        ( numConfigs != 1 ) )
417   {
418     if( mGlesVersion >= 30 )
419     {
420       mEglConfig = NULL;
421       DALI_LOG_ERROR("Fail to use OpenGL es 3.0. Retrying to use OpenGL es 2.0.");
422       return false;
423     }
424
425     if ( numConfigs != 1 )
426     {
427       DALI_LOG_ERROR("No configurations found.\n");
428
429       TEST_EGL_ERROR("eglChooseConfig");
430     }
431
432     EGLint error = eglGetError();
433     switch (error)
434     {
435       case EGL_BAD_DISPLAY:
436       {
437         DALI_LOG_ERROR("Display is not an EGL display connection\n");
438         break;
439       }
440       case EGL_BAD_ATTRIBUTE:
441       {
442         DALI_LOG_ERROR("The parameter configAttribs contains an invalid frame buffer configuration attribute or an attribute value that is unrecognized or out of range\n");
443         break;
444       }
445       case EGL_NOT_INITIALIZED:
446       {
447         DALI_LOG_ERROR("Display has not been initialized\n");
448         break;
449       }
450       case EGL_BAD_PARAMETER:
451       {
452         DALI_LOG_ERROR("The parameter numConfig is NULL\n");
453         break;
454       }
455       default:
456       {
457         DALI_LOG_ERROR("Unknown error.\n");
458       }
459     }
460     DALI_ASSERT_ALWAYS(false && "eglChooseConfig failed!");
461     return false;
462   }
463   Integration::Log::LogMessage(Integration::Log::DebugInfo, "Using OpenGL es %d.%d.\n", mGlesVersion / 10, mGlesVersion % 10 );
464
465   mContextAttribs.Clear();
466   if( mIsKhrCreateContextSupported )
467   {
468     mContextAttribs.Reserve(5);
469     mContextAttribs.PushBack( EGL_CONTEXT_MAJOR_VERSION_KHR );
470     mContextAttribs.PushBack( mGlesVersion / 10 );
471     mContextAttribs.PushBack( EGL_CONTEXT_MINOR_VERSION_KHR );
472     mContextAttribs.PushBack( mGlesVersion % 10 );
473   }
474   else
475   {
476     mContextAttribs.Reserve(3);
477     mContextAttribs.PushBack( EGL_CONTEXT_CLIENT_VERSION );
478     mContextAttribs.PushBack( mGlesVersion / 10 );
479   }
480   mContextAttribs.PushBack( EGL_NONE );
481
482   return true;
483 }
484
485 EGLSurface EglImplementation::CreateSurfaceWindow( EGLNativeWindowType window, ColorDepth depth )
486 {
487   mEglNativeWindow = window;
488   mColorDepth = depth;
489   mIsWindow = true;
490
491   // egl choose config
492   ChooseConfig(mIsWindow, mColorDepth);
493
494   mCurrentEglSurface = eglCreateWindowSurface( mEglDisplay, mEglConfig, mEglNativeWindow, NULL );
495   TEST_EGL_ERROR("eglCreateWindowSurface");
496
497   DALI_ASSERT_ALWAYS( mCurrentEglSurface && "Create window surface failed" );
498
499   return mCurrentEglSurface;
500 }
501
502 EGLSurface EglImplementation::CreateSurfacePixmap( EGLNativePixmapType pixmap, ColorDepth depth )
503 {
504   mCurrentEglNativePixmap = pixmap;
505   mColorDepth = depth;
506   mIsWindow = false;
507
508   // egl choose config
509   ChooseConfig(mIsWindow, mColorDepth);
510
511   mCurrentEglSurface = eglCreatePixmapSurface( mEglDisplay, mEglConfig, mCurrentEglNativePixmap, NULL );
512   TEST_EGL_ERROR("eglCreatePixmapSurface");
513
514   DALI_ASSERT_ALWAYS( mCurrentEglSurface && "Create pixmap surface failed" );
515
516   return mCurrentEglSurface;
517 }
518
519 bool EglImplementation::ReplaceSurfaceWindow( EGLNativeWindowType window, EGLSurface& eglSurface, EGLContext& eglContext )
520 {
521   bool contextLost = false;
522
523   // display connection has not changed, then we can just create a new surface
524   //  the surface is bound to the context, so set the context to null
525   MakeContextNull();
526
527   if( eglSurface )
528   {
529     // destroy the surface
530     DestroySurface( eglSurface );
531   }
532
533   // create the EGL surface
534   EGLSurface newEglSurface = CreateSurfaceWindow( window, mColorDepth );
535
536   // set the context to be current with the new surface
537   MakeContextCurrent( newEglSurface, eglContext );
538
539   return contextLost;
540 }
541
542 bool EglImplementation::ReplaceSurfacePixmap( EGLNativePixmapType pixmap, EGLSurface& eglSurface )
543 {
544   bool contextLost = false;
545
546   // display connection has not changed, then we can just create a new surface
547   // create the EGL surface
548   eglSurface = CreateSurfacePixmap( pixmap, mColorDepth );
549
550   // set the eglSurface to be current
551   MakeCurrent( pixmap, eglSurface );
552
553   return contextLost;
554 }
555
556 void EglImplementation::SetGlesVersion( const int32_t glesVersion )
557 {
558   mGlesVersion = glesVersion;
559 }
560
561 void EglImplementation::SetFirstFrameAfterResume()
562 {
563   mSwapBufferCountAfterResume = 0;
564 }
565
566 EGLDisplay EglImplementation::GetDisplay() const
567 {
568   return mEglDisplay;
569 }
570
571 EGLContext EglImplementation::GetContext() const
572 {
573   return mEglContext;
574 }
575
576 int32_t EglImplementation::GetGlesVersion() const
577 {
578   return mGlesVersion;
579 }
580
581 bool EglImplementation::IsSurfacelessContextSupported() const
582 {
583   return mIsSurfacelessContextSupported;
584 }
585
586 void EglImplementation::WaitClient()
587 {
588   // Wait for EGL to finish executing all rendering calls for the current context
589   if ( eglWaitClient() != EGL_TRUE )
590   {
591     TEST_EGL_ERROR("eglWaitClient");
592   }
593 }
594
595 } // namespace Adaptor
596
597 } // namespace Internal
598
599 } // namespace Dali
600
601 #pragma GCC diagnostic pop