2 * Copyright (C) 2014 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "EglManager.h"
21 #include "utils/StringUtils.h"
22 #include <cutils/properties.h>
26 #include "DeviceInfo.h"
28 #include "Properties.h"
29 #include "RenderThread.h"
30 #include "renderstate/RenderState.h"
33 #include <EGL/eglext.h>
34 #include <GrContextOptions.h>
35 #include <gl/GrGLInterface.h>
37 #ifdef HWUI_GLES_WRAP_ENABLED
38 #include "debug/GlesDriver.h"
41 #define GLES_VERSION 2
43 // Android-specific addition that is used to show when frames began in systrace
44 EGLAPI void EGLAPIENTRY eglBeginFrame(EGLDisplay dpy, EGLSurface surface);
47 namespace uirenderer {
48 namespace renderthread {
50 #define ERROR_CASE(x) case x: return #x;
51 static const char* egl_error_str(EGLint error) {
53 ERROR_CASE(EGL_SUCCESS)
54 ERROR_CASE(EGL_NOT_INITIALIZED)
55 ERROR_CASE(EGL_BAD_ACCESS)
56 ERROR_CASE(EGL_BAD_ALLOC)
57 ERROR_CASE(EGL_BAD_ATTRIBUTE)
58 ERROR_CASE(EGL_BAD_CONFIG)
59 ERROR_CASE(EGL_BAD_CONTEXT)
60 ERROR_CASE(EGL_BAD_CURRENT_SURFACE)
61 ERROR_CASE(EGL_BAD_DISPLAY)
62 ERROR_CASE(EGL_BAD_MATCH)
63 ERROR_CASE(EGL_BAD_NATIVE_PIXMAP)
64 ERROR_CASE(EGL_BAD_NATIVE_WINDOW)
65 ERROR_CASE(EGL_BAD_PARAMETER)
66 ERROR_CASE(EGL_BAD_SURFACE)
67 ERROR_CASE(EGL_CONTEXT_LOST)
69 return "Unknown error";
72 const char* EglManager::eglErrorString() {
73 return egl_error_str(eglGetError());
77 bool bufferAge = false;
78 bool setDamage = false;
79 bool noConfigContext = false;
80 bool pixelFormatFloat = false;
81 bool glColorSpace = false;
85 EglManager::EglManager(RenderThread& thread)
86 : mRenderThread(thread)
87 , mEglDisplay(EGL_NO_DISPLAY)
89 , mEglConfigWideGamut(nullptr)
90 , mEglContext(EGL_NO_CONTEXT)
91 , mPBufferSurface(EGL_NO_SURFACE)
92 , mCurrentSurface(EGL_NO_SURFACE) {
95 void EglManager::initialize() {
96 if (hasEglContext()) return;
98 ATRACE_NAME("Creating EGLContext");
100 mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
101 LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY,
102 "Failed to get EGL_DEFAULT_DISPLAY! err=%s", eglErrorString());
105 LOG_ALWAYS_FATAL_IF(eglInitialize(mEglDisplay, &major, &minor) == EGL_FALSE,
106 "Failed to initialize display %p! err=%s", mEglDisplay, eglErrorString());
108 ALOGI("Initialized EGL, version %d.%d", (int)major, (int)minor);
112 // Now that extensions are loaded, pick a swap behavior
113 if (Properties::enablePartialUpdates) {
114 // An Adreno driver bug is causing rendering problems for SkiaGL with
115 // buffer age swap behavior (b/31957043). To temporarily workaround,
116 // we will use preserved swap behavior.
117 if (Properties::useBufferAge && EglExtensions.bufferAge) {
118 mSwapBehavior = SwapBehavior::BufferAge;
120 mSwapBehavior = SwapBehavior::Preserved;
126 createPBufferSurface();
127 makeCurrent(mPBufferSurface);
128 DeviceInfo::initialize();
129 mRenderThread.renderState().onGLContextCreated();
131 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
132 #ifdef HWUI_GLES_WRAP_ENABLED
133 debug::GlesDriver* driver = debug::GlesDriver::get();
134 sk_sp<const GrGLInterface> glInterface(driver->getSkiaInterface());
136 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
138 LOG_ALWAYS_FATAL_IF(!glInterface.get());
140 GrContextOptions options;
141 options.fGpuPathRenderers &= ~GrContextOptions::GpuPathRenderers::kDistanceField;
142 mRenderThread.cacheManager().configureContext(&options);
143 mRenderThread.setGrContext(GrContext::Create(GrBackend::kOpenGL_GrBackend,
144 (GrBackendContext)glInterface.get(), options));
148 void EglManager::initExtensions() {
149 auto extensions = StringUtils::split(
150 eglQueryString(mEglDisplay, EGL_EXTENSIONS));
152 // For our purposes we don't care if EGL_BUFFER_AGE is a result of
153 // EGL_EXT_buffer_age or EGL_KHR_partial_update as our usage is covered
154 // under EGL_KHR_partial_update and we don't need the expanded scope
155 // that EGL_EXT_buffer_age provides.
156 EglExtensions.bufferAge = extensions.has("EGL_EXT_buffer_age")
157 || extensions.has("EGL_KHR_partial_update");
158 EglExtensions.setDamage = extensions.has("EGL_KHR_partial_update");
159 LOG_ALWAYS_FATAL_IF(!extensions.has("EGL_KHR_swap_buffers_with_damage"),
160 "Missing required extension EGL_KHR_swap_buffers_with_damage");
162 EglExtensions.glColorSpace = extensions.has("EGL_KHR_gl_colorspace");
163 EglExtensions.noConfigContext = extensions.has("EGL_KHR_no_config_context");
164 EglExtensions.pixelFormatFloat = extensions.has("EGL_EXT_pixel_format_float");
165 #ifdef ANDROID_ENABLE_LINEAR_BLENDING
166 EglExtensions.scRGB = extensions.has("EGL_EXT_gl_colorspace_scrgb_linear");
168 EglExtensions.scRGB = extensions.has("EGL_EXT_gl_colorspace_scrgb");
172 bool EglManager::hasEglContext() {
173 return mEglDisplay != EGL_NO_DISPLAY;
176 void EglManager::loadConfigs() {
177 ALOGD("Swap behavior %d", static_cast<int>(mSwapBehavior));
178 EGLint swapBehavior = (mSwapBehavior == SwapBehavior::Preserved)
179 ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
181 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
187 EGL_CONFIG_CAVEAT, EGL_NONE,
188 EGL_STENCIL_SIZE, Stencil::getStencilSize(),
189 EGL_SURFACE_TYPE, EGL_WINDOW_BIT | swapBehavior,
193 EGLint numConfigs = 1;
194 if (!eglChooseConfig(mEglDisplay, attribs, &mEglConfig, numConfigs, &numConfigs)
195 || numConfigs != 1) {
196 if (mSwapBehavior == SwapBehavior::Preserved) {
197 // Try again without dirty regions enabled
198 ALOGW("Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...");
199 mSwapBehavior = SwapBehavior::Discard;
201 return; // the call to loadConfigs() we just made picks the wide gamut config
203 // Failed to get a valid config
204 LOG_ALWAYS_FATAL("Failed to choose config, error = %s", eglErrorString());
208 if (EglExtensions.pixelFormatFloat) {
209 // If we reached this point, we have a valid swap behavior
210 EGLint attribs16F[] = {
211 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
212 EGL_COLOR_COMPONENT_TYPE_EXT, EGL_COLOR_COMPONENT_TYPE_FLOAT_EXT,
218 EGL_STENCIL_SIZE, Stencil::getStencilSize(),
219 EGL_SURFACE_TYPE, EGL_WINDOW_BIT | swapBehavior,
224 if (!eglChooseConfig(mEglDisplay, attribs16F, &mEglConfigWideGamut, numConfigs, &numConfigs)
225 || numConfigs != 1) {
226 ALOGE("Device claims wide gamut support, cannot find matching config, error = %s",
228 EglExtensions.pixelFormatFloat = false;
233 void EglManager::createContext() {
235 EGL_CONTEXT_CLIENT_VERSION, GLES_VERSION,
238 mEglContext = eglCreateContext(mEglDisplay,
239 EglExtensions.noConfigContext ? ((EGLConfig) nullptr) : mEglConfig,
240 EGL_NO_CONTEXT, attribs);
241 LOG_ALWAYS_FATAL_IF(mEglContext == EGL_NO_CONTEXT,
242 "Failed to create context, error = %s", eglErrorString());
245 void EglManager::createPBufferSurface() {
246 LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY,
247 "usePBufferSurface() called on uninitialized GlobalContext!");
249 if (mPBufferSurface == EGL_NO_SURFACE) {
250 EGLint attribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE };
251 mPBufferSurface = eglCreatePbufferSurface(mEglDisplay, mEglConfig, attribs);
255 EGLSurface EglManager::createSurface(EGLNativeWindowType window, bool wideColorGamut) {
258 wideColorGamut = wideColorGamut && EglExtensions.glColorSpace && EglExtensions.scRGB
259 && EglExtensions.pixelFormatFloat && EglExtensions.noConfigContext;
261 // The color space we want to use depends on whether linear blending is turned
262 // on and whether the app has requested wide color gamut rendering. When wide
263 // color gamut rendering is off, the app simply renders in the display's native
266 // When wide gamut rendering is off:
267 // - Blending is done by default in gamma space, which requires using a
268 // linear EGL color space (the GPU uses the color values as is)
269 // - If linear blending is on, we must use the sRGB EGL color space (the
270 // GPU will perform sRGB to linear and linear to SRGB conversions before
271 // and after blending)
273 // When wide gamut rendering is on we cannot rely on the GPU performing
274 // linear blending for us. We use two different color spaces to tag the
275 // surface appropriately for SurfaceFlinger:
276 // - Gamma blending (default) requires the use of the scRGB-nl color space
277 // - Linear blending requires the use of the scRGB color space
279 // Not all Android targets support the EGL_GL_COLOR_SPACE_KHR extension
280 // We insert to placeholders to set EGL_GL_COLORSPACE_KHR and its value.
281 // According to section 3.4.1 of the EGL specification, the attributes
282 // list is considered empty if the first entry is EGL_NONE
288 if (EglExtensions.glColorSpace) {
289 attribs[0] = EGL_GL_COLORSPACE_KHR;
290 #ifdef ANDROID_ENABLE_LINEAR_BLENDING
291 if (wideColorGamut) {
292 attribs[1] = EGL_GL_COLORSPACE_SCRGB_LINEAR_EXT;
294 attribs[1] = EGL_GL_COLORSPACE_SRGB_KHR;
297 if (wideColorGamut) {
298 attribs[1] = EGL_GL_COLORSPACE_SCRGB_EXT;
300 attribs[1] = EGL_GL_COLORSPACE_LINEAR_KHR;
305 EGLSurface surface = eglCreateWindowSurface(mEglDisplay,
306 wideColorGamut ? mEglConfigWideGamut : mEglConfig, window, attribs);
307 LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE,
308 "Failed to create EGLSurface for window %p, eglErr = %s",
309 (void*) window, eglErrorString());
311 if (mSwapBehavior != SwapBehavior::Preserved) {
312 LOG_ALWAYS_FATAL_IF(eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, EGL_BUFFER_DESTROYED) == EGL_FALSE,
313 "Failed to set swap behavior to destroyed for window %p, eglErr = %s",
314 (void*) window, eglErrorString());
320 void EglManager::destroySurface(EGLSurface surface) {
321 if (isCurrent(surface)) {
322 makeCurrent(EGL_NO_SURFACE);
324 if (!eglDestroySurface(mEglDisplay, surface)) {
325 ALOGW("Failed to destroy surface %p, error=%s", (void*)surface, eglErrorString());
329 void EglManager::destroy() {
330 if (mEglDisplay == EGL_NO_DISPLAY) return;
332 mRenderThread.setGrContext(nullptr);
333 mRenderThread.renderState().onGLContextDestroyed();
334 eglDestroyContext(mEglDisplay, mEglContext);
335 eglDestroySurface(mEglDisplay, mPBufferSurface);
336 eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
337 eglTerminate(mEglDisplay);
340 mEglDisplay = EGL_NO_DISPLAY;
341 mEglContext = EGL_NO_CONTEXT;
342 mPBufferSurface = EGL_NO_SURFACE;
343 mCurrentSurface = EGL_NO_SURFACE;
346 bool EglManager::makeCurrent(EGLSurface surface, EGLint* errOut) {
347 if (isCurrent(surface)) return false;
349 if (surface == EGL_NO_SURFACE) {
350 // Ensure we always have a valid surface & context
351 surface = mPBufferSurface;
353 if (!eglMakeCurrent(mEglDisplay, surface, surface, mEglContext)) {
355 *errOut = eglGetError();
356 ALOGW("Failed to make current on surface %p, error=%s",
357 (void*)surface, egl_error_str(*errOut));
359 LOG_ALWAYS_FATAL("Failed to make current on surface %p, error=%s",
360 (void*)surface, eglErrorString());
363 mCurrentSurface = surface;
364 if (Properties::disableVsync) {
365 eglSwapInterval(mEglDisplay, 0);
370 EGLint EglManager::queryBufferAge(EGLSurface surface) {
371 switch (mSwapBehavior) {
372 case SwapBehavior::Discard:
374 case SwapBehavior::Preserved:
376 case SwapBehavior::BufferAge:
378 eglQuerySurface(mEglDisplay, surface, EGL_BUFFER_AGE_EXT, &bufferAge);
384 Frame EglManager::beginFrame(EGLSurface surface) {
385 LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE,
386 "Tried to beginFrame on EGL_NO_SURFACE!");
387 makeCurrent(surface);
389 frame.mSurface = surface;
390 eglQuerySurface(mEglDisplay, surface, EGL_WIDTH, &frame.mWidth);
391 eglQuerySurface(mEglDisplay, surface, EGL_HEIGHT, &frame.mHeight);
392 frame.mBufferAge = queryBufferAge(surface);
393 eglBeginFrame(mEglDisplay, surface);
397 void EglManager::damageFrame(const Frame& frame, const SkRect& dirty) {
398 #ifdef EGL_KHR_partial_update
399 if (EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge) {
401 frame.map(dirty, rects);
402 if (!eglSetDamageRegionKHR(mEglDisplay, frame.mSurface, rects, 1)) {
403 LOG_ALWAYS_FATAL("Failed to set damage region on surface %p, error=%s",
404 (void*)frame.mSurface, eglErrorString());
410 bool EglManager::damageRequiresSwap() {
411 return EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge;
414 bool EglManager::swapBuffers(const Frame& frame, const SkRect& screenDirty) {
416 if (CC_UNLIKELY(Properties::waitForGpuCompletion)) {
417 ATRACE_NAME("Finishing GPU work");
422 frame.map(screenDirty, rects);
423 eglSwapBuffersWithDamageKHR(mEglDisplay, frame.mSurface, rects,
424 screenDirty.isEmpty() ? 0 : 1);
426 EGLint err = eglGetError();
427 if (CC_LIKELY(err == EGL_SUCCESS)) {
430 if (err == EGL_BAD_SURFACE || err == EGL_BAD_NATIVE_WINDOW) {
431 // For some reason our surface was destroyed out from under us
432 // This really shouldn't happen, but if it does we can recover easily
433 // by just not trying to use the surface anymore
434 ALOGW("swapBuffers encountered EGL error %d on %p, halting rendering...",
435 err, frame.mSurface);
438 LOG_ALWAYS_FATAL("Encountered EGL error %d %s during rendering",
439 err, egl_error_str(err));
440 // Impossible to hit this, but the compiler doesn't know that
444 void EglManager::fence() {
445 EGLSyncKHR fence = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_FENCE_KHR, NULL);
446 eglClientWaitSyncKHR(mEglDisplay, fence,
447 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, EGL_FOREVER_KHR);
448 eglDestroySyncKHR(mEglDisplay, fence);
451 bool EglManager::setPreserveBuffer(EGLSurface surface, bool preserve) {
452 if (mSwapBehavior != SwapBehavior::Preserved) return false;
454 bool preserved = eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
455 preserve ? EGL_BUFFER_PRESERVED : EGL_BUFFER_DESTROYED);
457 ALOGW("Failed to set EGL_SWAP_BEHAVIOR on surface %p, error=%s",
458 (void*) surface, eglErrorString());
459 // Maybe it's already set?
461 if (eglQuerySurface(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, &swapBehavior)) {
462 preserved = (swapBehavior == EGL_BUFFER_PRESERVED);
464 ALOGW("Failed to query EGL_SWAP_BEHAVIOR on surface %p, error=%p",
465 (void*) surface, eglErrorString());
472 } /* namespace renderthread */
473 } /* namespace uirenderer */
474 } /* namespace android */