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