1/*
2 * Copyright (C) 2014 The Android Open Source Project
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#include "EglManager.h"
18
19#include <string>
20
21#include "utils/StringUtils.h"
22#include <cutils/properties.h>
23#include <log/log.h>
24
25#include "Caches.h"
26#include "DeviceInfo.h"
27#include "Frame.h"
28#include "Properties.h"
29#include "RenderThread.h"
30#include "renderstate/RenderState.h"
31#include "Texture.h"
32
33#include <EGL/eglext.h>
34#include <GrContextOptions.h>
35#include <gl/GrGLInterface.h>
36
37#ifdef HWUI_GLES_WRAP_ENABLED
38#include "debug/GlesDriver.h"
39#endif
40
41#define GLES_VERSION 2
42
43// Android-specific addition that is used to show when frames began in systrace
44EGLAPI void EGLAPIENTRY eglBeginFrame(EGLDisplay dpy, EGLSurface surface);
45
46namespace android {
47namespace uirenderer {
48namespace renderthread {
49
50#define ERROR_CASE(x) case x: return #x;
51static const char* egl_error_str(EGLint error) {
52    switch (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)
68    default:
69        return "Unknown error";
70    }
71}
72const char* EglManager::eglErrorString() {
73    return egl_error_str(eglGetError());
74}
75
76static struct {
77    bool bufferAge = false;
78    bool setDamage = false;
79    bool noConfigContext = false;
80    bool pixelFormatFloat = false;
81    bool glColorSpace = false;
82    bool scRGB = false;
83} EglExtensions;
84
85EglManager::EglManager(RenderThread& thread)
86        : mRenderThread(thread)
87        , mEglDisplay(EGL_NO_DISPLAY)
88        , mEglConfig(nullptr)
89        , mEglConfigWideGamut(nullptr)
90        , mEglContext(EGL_NO_CONTEXT)
91        , mPBufferSurface(EGL_NO_SURFACE)
92        , mCurrentSurface(EGL_NO_SURFACE) {
93}
94
95void EglManager::initialize() {
96    if (hasEglContext()) return;
97
98    ATRACE_NAME("Creating EGLContext");
99
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());
103
104    EGLint major, minor;
105    LOG_ALWAYS_FATAL_IF(eglInitialize(mEglDisplay, &major, &minor) == EGL_FALSE,
106            "Failed to initialize display %p! err=%s", mEglDisplay, eglErrorString());
107
108    ALOGI("Initialized EGL, version %d.%d", (int)major, (int)minor);
109
110    initExtensions();
111
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;
119        } else {
120            mSwapBehavior = SwapBehavior::Preserved;
121        }
122    }
123
124    loadConfigs();
125    createContext();
126    createPBufferSurface();
127    makeCurrent(mPBufferSurface);
128    DeviceInfo::initialize();
129    mRenderThread.renderState().onGLContextCreated();
130
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());
135#else
136        sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
137#endif
138        LOG_ALWAYS_FATAL_IF(!glInterface.get());
139
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));
145    }
146}
147
148void EglManager::initExtensions() {
149    auto extensions = StringUtils::split(
150            eglQueryString(mEglDisplay, EGL_EXTENSIONS));
151
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");
161
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");
167#else
168    EglExtensions.scRGB = extensions.has("EGL_EXT_gl_colorspace_scrgb");
169#endif
170}
171
172bool EglManager::hasEglContext() {
173    return mEglDisplay != EGL_NO_DISPLAY;
174}
175
176void EglManager::loadConfigs() {
177    ALOGD("Swap behavior %d", static_cast<int>(mSwapBehavior));
178    EGLint swapBehavior = (mSwapBehavior == SwapBehavior::Preserved)
179            ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
180    EGLint attribs[] = {
181            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
182            EGL_RED_SIZE, 8,
183            EGL_GREEN_SIZE, 8,
184            EGL_BLUE_SIZE, 8,
185            EGL_ALPHA_SIZE, 8,
186            EGL_DEPTH_SIZE, 0,
187            EGL_CONFIG_CAVEAT, EGL_NONE,
188            EGL_STENCIL_SIZE, Stencil::getStencilSize(),
189            EGL_SURFACE_TYPE, EGL_WINDOW_BIT | swapBehavior,
190            EGL_NONE
191    };
192
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;
200            loadConfigs();
201            return; // the call to loadConfigs() we just made picks the wide gamut config
202        } else {
203            // Failed to get a valid config
204            LOG_ALWAYS_FATAL("Failed to choose config, error = %s", eglErrorString());
205        }
206    }
207
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,
213                EGL_RED_SIZE, 16,
214                EGL_GREEN_SIZE, 16,
215                EGL_BLUE_SIZE, 16,
216                EGL_ALPHA_SIZE, 16,
217                EGL_DEPTH_SIZE, 0,
218                EGL_STENCIL_SIZE, Stencil::getStencilSize(),
219                EGL_SURFACE_TYPE, EGL_WINDOW_BIT | swapBehavior,
220                EGL_NONE
221        };
222
223        numConfigs = 1;
224        if (!eglChooseConfig(mEglDisplay, attribs16F, &mEglConfigWideGamut, numConfigs, &numConfigs)
225                || numConfigs != 1) {
226            LOG_ALWAYS_FATAL(
227                    "Device claims wide gamut support, cannot find matching config, error = %s",
228                    eglErrorString());
229        }
230    }
231}
232
233void EglManager::createContext() {
234    EGLint attribs[] = {
235            EGL_CONTEXT_CLIENT_VERSION, GLES_VERSION,
236            EGL_NONE
237    };
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());
243}
244
245void EglManager::createPBufferSurface() {
246    LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY,
247            "usePBufferSurface() called on uninitialized GlobalContext!");
248
249    if (mPBufferSurface == EGL_NO_SURFACE) {
250        EGLint attribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE };
251        mPBufferSurface = eglCreatePbufferSurface(mEglDisplay, mEglConfig, attribs);
252    }
253}
254
255EGLSurface EglManager::createSurface(EGLNativeWindowType window, bool wideColorGamut) {
256    initialize();
257
258    wideColorGamut = wideColorGamut && EglExtensions.glColorSpace && EglExtensions.scRGB
259            && EglExtensions.pixelFormatFloat && EglExtensions.noConfigContext;
260
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
264    // color gamut.
265    //
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)
272    //
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
278
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
283    EGLint attribs[] = {
284            EGL_NONE, EGL_NONE,
285            EGL_NONE
286    };
287
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;
293        } else {
294            attribs[1] = EGL_GL_COLORSPACE_SRGB_KHR;
295        }
296#else
297        if (wideColorGamut) {
298            attribs[1] = EGL_GL_COLORSPACE_SCRGB_EXT;
299        } else {
300            attribs[1] = EGL_GL_COLORSPACE_LINEAR_KHR;
301        }
302#endif
303    }
304
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());
310
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());
315    }
316
317    return surface;
318}
319
320void EglManager::destroySurface(EGLSurface surface) {
321    if (isCurrent(surface)) {
322        makeCurrent(EGL_NO_SURFACE);
323    }
324    if (!eglDestroySurface(mEglDisplay, surface)) {
325        ALOGW("Failed to destroy surface %p, error=%s", (void*)surface, eglErrorString());
326    }
327}
328
329void EglManager::destroy() {
330    if (mEglDisplay == EGL_NO_DISPLAY) return;
331
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);
338    eglReleaseThread();
339
340    mEglDisplay = EGL_NO_DISPLAY;
341    mEglContext = EGL_NO_CONTEXT;
342    mPBufferSurface = EGL_NO_SURFACE;
343    mCurrentSurface = EGL_NO_SURFACE;
344}
345
346bool EglManager::makeCurrent(EGLSurface surface, EGLint* errOut) {
347    if (isCurrent(surface)) return false;
348
349    if (surface == EGL_NO_SURFACE) {
350        // Ensure we always have a valid surface & context
351        surface = mPBufferSurface;
352    }
353    if (!eglMakeCurrent(mEglDisplay, surface, surface, mEglContext)) {
354        if (errOut) {
355            *errOut = eglGetError();
356            ALOGW("Failed to make current on surface %p, error=%s",
357                    (void*)surface, egl_error_str(*errOut));
358        } else {
359            LOG_ALWAYS_FATAL("Failed to make current on surface %p, error=%s",
360                    (void*)surface, eglErrorString());
361        }
362    }
363    mCurrentSurface = surface;
364    if (Properties::disableVsync) {
365        eglSwapInterval(mEglDisplay, 0);
366    }
367    return true;
368}
369
370EGLint EglManager::queryBufferAge(EGLSurface surface) {
371    switch (mSwapBehavior) {
372    case SwapBehavior::Discard:
373        return 0;
374    case SwapBehavior::Preserved:
375        return 1;
376    case SwapBehavior::BufferAge:
377        EGLint bufferAge;
378        eglQuerySurface(mEglDisplay, surface, EGL_BUFFER_AGE_EXT, &bufferAge);
379        return bufferAge;
380    }
381    return 0;
382}
383
384Frame EglManager::beginFrame(EGLSurface surface) {
385    LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE,
386            "Tried to beginFrame on EGL_NO_SURFACE!");
387    makeCurrent(surface);
388    Frame frame;
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);
394    return frame;
395}
396
397void EglManager::damageFrame(const Frame& frame, const SkRect& dirty) {
398#ifdef EGL_KHR_partial_update
399    if (EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge) {
400        EGLint rects[4];
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());
405        }
406    }
407#endif
408}
409
410bool EglManager::damageRequiresSwap() {
411    return EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge;
412}
413
414bool EglManager::swapBuffers(const Frame& frame, const SkRect& screenDirty) {
415
416    if (CC_UNLIKELY(Properties::waitForGpuCompletion)) {
417        ATRACE_NAME("Finishing GPU work");
418        fence();
419    }
420
421    EGLint rects[4];
422    frame.map(screenDirty, rects);
423    eglSwapBuffersWithDamageKHR(mEglDisplay, frame.mSurface, rects,
424            screenDirty.isEmpty() ? 0 : 1);
425
426    EGLint err = eglGetError();
427    if (CC_LIKELY(err == EGL_SUCCESS)) {
428        return true;
429    }
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);
436        return false;
437    }
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
441    return false;
442}
443
444void 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);
449}
450
451bool EglManager::setPreserveBuffer(EGLSurface surface, bool preserve) {
452    if (mSwapBehavior != SwapBehavior::Preserved) return false;
453
454    bool preserved = eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
455            preserve ? EGL_BUFFER_PRESERVED : EGL_BUFFER_DESTROYED);
456    if (!preserved) {
457        ALOGW("Failed to set EGL_SWAP_BEHAVIOR on surface %p, error=%s",
458                (void*) surface, eglErrorString());
459        // Maybe it's already set?
460        EGLint swapBehavior;
461        if (eglQuerySurface(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, &swapBehavior)) {
462            preserved = (swapBehavior == EGL_BUFFER_PRESERVED);
463        } else {
464            ALOGW("Failed to query EGL_SWAP_BEHAVIOR on surface %p, error=%p",
465                                (void*) surface, eglErrorString());
466        }
467    }
468
469    return preserved;
470}
471
472} /* namespace renderthread */
473} /* namespace uirenderer */
474} /* namespace android */
475