EglManager.cpp revision 98f75d53dbe243b1661c616643698e025d4978f6
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 "Caches.h"
20#include "DeviceInfo.h"
21#include "Properties.h"
22#include "RenderThread.h"
23#include "renderstate/RenderState.h"
24#include "utils/StringUtils.h"
25#include <cutils/log.h>
26#include <cutils/properties.h>
27#include <EGL/eglext.h>
28#include <GrContextOptions.h>
29#include <gl/GrGLInterface.h>
30#include <string>
31
32#define GLES_VERSION 2
33
34// Android-specific addition that is used to show when frames began in systrace
35EGLAPI void EGLAPIENTRY eglBeginFrame(EGLDisplay dpy, EGLSurface surface);
36
37namespace android {
38namespace uirenderer {
39namespace renderthread {
40
41#define ERROR_CASE(x) case x: return #x;
42static const char* egl_error_str(EGLint error) {
43    switch (error) {
44        ERROR_CASE(EGL_SUCCESS)
45        ERROR_CASE(EGL_NOT_INITIALIZED)
46        ERROR_CASE(EGL_BAD_ACCESS)
47        ERROR_CASE(EGL_BAD_ALLOC)
48        ERROR_CASE(EGL_BAD_ATTRIBUTE)
49        ERROR_CASE(EGL_BAD_CONFIG)
50        ERROR_CASE(EGL_BAD_CONTEXT)
51        ERROR_CASE(EGL_BAD_CURRENT_SURFACE)
52        ERROR_CASE(EGL_BAD_DISPLAY)
53        ERROR_CASE(EGL_BAD_MATCH)
54        ERROR_CASE(EGL_BAD_NATIVE_PIXMAP)
55        ERROR_CASE(EGL_BAD_NATIVE_WINDOW)
56        ERROR_CASE(EGL_BAD_PARAMETER)
57        ERROR_CASE(EGL_BAD_SURFACE)
58        ERROR_CASE(EGL_CONTEXT_LOST)
59    default:
60        return "Unknown error";
61    }
62}
63static const char* egl_error_str() {
64    return egl_error_str(eglGetError());
65}
66
67static struct {
68    bool bufferAge = false;
69    bool setDamage = false;
70} EglExtensions;
71
72void Frame::map(const SkRect& in, EGLint* out) const {
73    /* The rectangles are specified relative to the bottom-left of the surface
74     * and the x and y components of each rectangle specify the bottom-left
75     * position of that rectangle.
76     *
77     * HWUI does everything with 0,0 being top-left, so need to map
78     * the rect
79     */
80    SkIRect idirty;
81    in.roundOut(&idirty);
82    EGLint y = mHeight - (idirty.y() + idirty.height());
83    // layout: {x, y, width, height}
84    out[0] = idirty.x();
85    out[1] = y;
86    out[2] = idirty.width();
87    out[3] = idirty.height();
88}
89
90EglManager::EglManager(RenderThread& thread)
91        : mRenderThread(thread)
92        , mEglDisplay(EGL_NO_DISPLAY)
93        , mEglConfig(nullptr)
94        , mEglContext(EGL_NO_CONTEXT)
95        , mPBufferSurface(EGL_NO_SURFACE)
96        , mCurrentSurface(EGL_NO_SURFACE) {
97}
98
99void EglManager::initialize() {
100    if (hasEglContext()) return;
101
102    ATRACE_NAME("Creating EGLContext");
103
104    mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
105    LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY,
106            "Failed to get EGL_DEFAULT_DISPLAY! err=%s", egl_error_str());
107
108    EGLint major, minor;
109    LOG_ALWAYS_FATAL_IF(eglInitialize(mEglDisplay, &major, &minor) == EGL_FALSE,
110            "Failed to initialize display %p! err=%s", mEglDisplay, egl_error_str());
111
112    ALOGI("Initialized EGL, version %d.%d", (int)major, (int)minor);
113
114    initExtensions();
115
116    // Now that extensions are loaded, pick a swap behavior
117    if (Properties::enablePartialUpdates) {
118        if (Properties::useBufferAge && EglExtensions.bufferAge) {
119            mSwapBehavior = SwapBehavior::BufferAge;
120        } else {
121            mSwapBehavior = SwapBehavior::Preserved;
122        }
123    }
124
125    loadConfig();
126    createContext();
127    createPBufferSurface();
128    makeCurrent(mPBufferSurface);
129    DeviceInfo::initialize();
130    mRenderThread.renderState().onGLContextCreated();
131
132    if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
133        sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
134        LOG_ALWAYS_FATAL_IF(!glInterface.get());
135
136        GrContextOptions options;
137        options.fDisableDistanceFieldPaths = true;
138        options.fAllowPathMaskCaching = true;
139        mRenderThread.setGrContext(GrContext::Create(GrBackend::kOpenGL_GrBackend,
140                (GrBackendContext)glInterface.get(), options));
141    }
142}
143
144void EglManager::initExtensions() {
145    auto extensions = StringUtils::split(
146            eglQueryString(mEglDisplay, EGL_EXTENSIONS));
147    // For our purposes we don't care if EGL_BUFFER_AGE is a result of
148    // EGL_EXT_buffer_age or EGL_KHR_partial_update as our usage is covered
149    // under EGL_KHR_partial_update and we don't need the expanded scope
150    // that EGL_EXT_buffer_age provides.
151    EglExtensions.bufferAge = extensions.has("EGL_EXT_buffer_age")
152            || extensions.has("EGL_KHR_partial_update");
153    EglExtensions.setDamage = extensions.has("EGL_KHR_partial_update");
154    LOG_ALWAYS_FATAL_IF(!extensions.has("EGL_KHR_swap_buffers_with_damage"),
155            "Missing required extension EGL_KHR_swap_buffers_with_damage");
156}
157
158bool EglManager::hasEglContext() {
159    return mEglDisplay != EGL_NO_DISPLAY;
160}
161
162void EglManager::loadConfig() {
163    ALOGD("Swap behavior %d", static_cast<int>(mSwapBehavior));
164    EGLint swapBehavior = (mSwapBehavior == SwapBehavior::Preserved)
165            ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
166    EGLint attribs[] = {
167            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
168            EGL_RED_SIZE, 8,
169            EGL_GREEN_SIZE, 8,
170            EGL_BLUE_SIZE, 8,
171            EGL_ALPHA_SIZE, 8,
172            EGL_DEPTH_SIZE, 0,
173            EGL_CONFIG_CAVEAT, EGL_NONE,
174            EGL_STENCIL_SIZE, Stencil::getStencilSize(),
175            EGL_SURFACE_TYPE, EGL_WINDOW_BIT | swapBehavior,
176            EGL_NONE
177    };
178
179    EGLint num_configs = 1;
180    if (!eglChooseConfig(mEglDisplay, attribs, &mEglConfig, num_configs, &num_configs)
181            || num_configs != 1) {
182        if (mSwapBehavior == SwapBehavior::Preserved) {
183            // Try again without dirty regions enabled
184            ALOGW("Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...");
185            mSwapBehavior = SwapBehavior::Discard;
186            loadConfig();
187        } else {
188            // Failed to get a valid config
189            LOG_ALWAYS_FATAL("Failed to choose config, error = %s", egl_error_str());
190        }
191    }
192}
193
194void EglManager::createContext() {
195    EGLint attribs[] = {
196            EGL_CONTEXT_CLIENT_VERSION, GLES_VERSION,
197            EGL_NONE
198    };
199    mEglContext = eglCreateContext(mEglDisplay, mEglConfig, EGL_NO_CONTEXT, attribs);
200    LOG_ALWAYS_FATAL_IF(mEglContext == EGL_NO_CONTEXT,
201        "Failed to create context, error = %s", egl_error_str());
202}
203
204void EglManager::createPBufferSurface() {
205    LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY,
206            "usePBufferSurface() called on uninitialized GlobalContext!");
207
208    if (mPBufferSurface == EGL_NO_SURFACE) {
209        EGLint attribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE };
210        mPBufferSurface = eglCreatePbufferSurface(mEglDisplay, mEglConfig, attribs);
211    }
212}
213
214EGLSurface EglManager::createSurface(EGLNativeWindowType window) {
215    initialize();
216
217    EGLint attribs[] = {
218#ifdef ANDROID_ENABLE_LINEAR_BLENDING
219            EGL_GL_COLORSPACE_KHR, EGL_GL_COLORSPACE_SRGB_KHR,
220            EGL_COLORSPACE, EGL_COLORSPACE_sRGB,
221#endif
222            EGL_NONE
223    };
224
225    EGLSurface surface = eglCreateWindowSurface(mEglDisplay, mEglConfig, window, attribs);
226    LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE,
227            "Failed to create EGLSurface for window %p, eglErr = %s",
228            (void*) window, egl_error_str());
229
230    if (mSwapBehavior != SwapBehavior::Preserved) {
231        LOG_ALWAYS_FATAL_IF(eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, EGL_BUFFER_DESTROYED) == EGL_FALSE,
232                            "Failed to set swap behavior to destroyed for window %p, eglErr = %s",
233                            (void*) window, egl_error_str());
234    }
235
236    return surface;
237}
238
239void EglManager::destroySurface(EGLSurface surface) {
240    if (isCurrent(surface)) {
241        makeCurrent(EGL_NO_SURFACE);
242    }
243    if (!eglDestroySurface(mEglDisplay, surface)) {
244        ALOGW("Failed to destroy surface %p, error=%s", (void*)surface, egl_error_str());
245    }
246}
247
248void EglManager::destroy() {
249    if (mEglDisplay == EGL_NO_DISPLAY) return;
250
251    mRenderThread.setGrContext(nullptr);
252    mRenderThread.renderState().onGLContextDestroyed();
253    eglDestroyContext(mEglDisplay, mEglContext);
254    eglDestroySurface(mEglDisplay, mPBufferSurface);
255    eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
256    eglTerminate(mEglDisplay);
257    eglReleaseThread();
258
259    mEglDisplay = EGL_NO_DISPLAY;
260    mEglContext = EGL_NO_CONTEXT;
261    mPBufferSurface = EGL_NO_SURFACE;
262    mCurrentSurface = EGL_NO_SURFACE;
263}
264
265bool EglManager::makeCurrent(EGLSurface surface, EGLint* errOut) {
266    if (isCurrent(surface)) return false;
267
268    if (surface == EGL_NO_SURFACE) {
269        // Ensure we always have a valid surface & context
270        surface = mPBufferSurface;
271    }
272    if (!eglMakeCurrent(mEglDisplay, surface, surface, mEglContext)) {
273        if (errOut) {
274            *errOut = eglGetError();
275            ALOGW("Failed to make current on surface %p, error=%s",
276                    (void*)surface, egl_error_str(*errOut));
277        } else {
278            LOG_ALWAYS_FATAL("Failed to make current on surface %p, error=%s",
279                    (void*)surface, egl_error_str());
280        }
281    }
282    mCurrentSurface = surface;
283    return true;
284}
285
286EGLint EglManager::queryBufferAge(EGLSurface surface) {
287    switch (mSwapBehavior) {
288    case SwapBehavior::Discard:
289        return 0;
290    case SwapBehavior::Preserved:
291        return 1;
292    case SwapBehavior::BufferAge:
293        EGLint bufferAge;
294        eglQuerySurface(mEglDisplay, surface, EGL_BUFFER_AGE_EXT, &bufferAge);
295        return bufferAge;
296    }
297    return 0;
298}
299
300Frame EglManager::beginFrame(EGLSurface surface) {
301    LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE,
302            "Tried to beginFrame on EGL_NO_SURFACE!");
303    makeCurrent(surface);
304    Frame frame;
305    frame.mSurface = surface;
306    eglQuerySurface(mEglDisplay, surface, EGL_WIDTH, &frame.mWidth);
307    eglQuerySurface(mEglDisplay, surface, EGL_HEIGHT, &frame.mHeight);
308    frame.mBufferAge = queryBufferAge(surface);
309    eglBeginFrame(mEglDisplay, surface);
310    return frame;
311}
312
313void EglManager::damageFrame(const Frame& frame, const SkRect& dirty) {
314#ifdef EGL_KHR_partial_update
315    if (EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge) {
316        EGLint rects[4];
317        frame.map(dirty, rects);
318        if (!eglSetDamageRegionKHR(mEglDisplay, frame.mSurface, rects, 1)) {
319            LOG_ALWAYS_FATAL("Failed to set damage region on surface %p, error=%s",
320                    (void*)frame.mSurface, egl_error_str());
321        }
322    }
323#endif
324}
325
326bool EglManager::damageRequiresSwap() {
327    return EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge;
328}
329
330bool EglManager::swapBuffers(const Frame& frame, const SkRect& screenDirty) {
331
332    if (CC_UNLIKELY(Properties::waitForGpuCompletion)) {
333        ATRACE_NAME("Finishing GPU work");
334        fence();
335    }
336
337    EGLint rects[4];
338    frame.map(screenDirty, rects);
339    eglSwapBuffersWithDamageKHR(mEglDisplay, frame.mSurface, rects,
340            screenDirty.isEmpty() ? 0 : 1);
341
342    EGLint err = eglGetError();
343    if (CC_LIKELY(err == EGL_SUCCESS)) {
344        return true;
345    }
346    if (err == EGL_BAD_SURFACE || err == EGL_BAD_NATIVE_WINDOW) {
347        // For some reason our surface was destroyed out from under us
348        // This really shouldn't happen, but if it does we can recover easily
349        // by just not trying to use the surface anymore
350        ALOGW("swapBuffers encountered EGL error %d on %p, halting rendering...",
351                err, frame.mSurface);
352        return false;
353    }
354    LOG_ALWAYS_FATAL("Encountered EGL error %d %s during rendering",
355            err, egl_error_str(err));
356    // Impossible to hit this, but the compiler doesn't know that
357    return false;
358}
359
360void EglManager::fence() {
361    EGLSyncKHR fence = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_FENCE_KHR, NULL);
362    eglClientWaitSyncKHR(mEglDisplay, fence,
363            EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, EGL_FOREVER_KHR);
364    eglDestroySyncKHR(mEglDisplay, fence);
365}
366
367bool EglManager::setPreserveBuffer(EGLSurface surface, bool preserve) {
368    if (mSwapBehavior != SwapBehavior::Preserved) return false;
369
370    bool preserved = eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
371            preserve ? EGL_BUFFER_PRESERVED : EGL_BUFFER_DESTROYED);
372    if (!preserved) {
373        ALOGW("Failed to set EGL_SWAP_BEHAVIOR on surface %p, error=%s",
374                (void*) surface, egl_error_str());
375        // Maybe it's already set?
376        EGLint swapBehavior;
377        if (eglQuerySurface(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, &swapBehavior)) {
378            preserved = (swapBehavior == EGL_BUFFER_PRESERVED);
379        } else {
380            ALOGW("Failed to query EGL_SWAP_BEHAVIOR on surface %p, error=%p",
381                                (void*) surface, egl_error_str());
382        }
383    }
384
385    return preserved;
386}
387
388} /* namespace renderthread */
389} /* namespace uirenderer */
390} /* namespace android */
391