EglManager.cpp revision 950ff1b88cc1330f8e80d62ed3aa15bee6be0556
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 <cutils/log.h>
20#include <cutils/properties.h>
21
22#include "../RenderState.h"
23#include "RenderThread.h"
24
25#define PROPERTY_RENDER_DIRTY_REGIONS "debug.hwui.render_dirty_regions"
26#define GLES_VERSION 2
27
28// Android-specific addition that is used to show when frames began in systrace
29EGLAPI void EGLAPIENTRY eglBeginFrame(EGLDisplay dpy, EGLSurface surface);
30
31namespace android {
32namespace uirenderer {
33namespace renderthread {
34
35#define ERROR_CASE(x) case x: return #x;
36static const char* egl_error_str(EGLint error) {
37    switch (error) {
38        ERROR_CASE(EGL_SUCCESS)
39        ERROR_CASE(EGL_NOT_INITIALIZED)
40        ERROR_CASE(EGL_BAD_ACCESS)
41        ERROR_CASE(EGL_BAD_ALLOC)
42        ERROR_CASE(EGL_BAD_ATTRIBUTE)
43        ERROR_CASE(EGL_BAD_CONFIG)
44        ERROR_CASE(EGL_BAD_CONTEXT)
45        ERROR_CASE(EGL_BAD_CURRENT_SURFACE)
46        ERROR_CASE(EGL_BAD_DISPLAY)
47        ERROR_CASE(EGL_BAD_MATCH)
48        ERROR_CASE(EGL_BAD_NATIVE_PIXMAP)
49        ERROR_CASE(EGL_BAD_NATIVE_WINDOW)
50        ERROR_CASE(EGL_BAD_PARAMETER)
51        ERROR_CASE(EGL_BAD_SURFACE)
52        ERROR_CASE(EGL_CONTEXT_LOST)
53    default:
54        return "Unknown error";
55    }
56}
57static const char* egl_error_str() {
58    return egl_error_str(eglGetError());
59}
60
61static bool load_dirty_regions_property() {
62    char buf[PROPERTY_VALUE_MAX];
63    int len = property_get(PROPERTY_RENDER_DIRTY_REGIONS, buf, "true");
64    return !strncasecmp("true", buf, len);
65}
66
67EglManager::EglManager(RenderThread& thread)
68        : mRenderThread(thread)
69        , mEglDisplay(EGL_NO_DISPLAY)
70        , mEglConfig(0)
71        , mEglContext(EGL_NO_CONTEXT)
72        , mPBufferSurface(EGL_NO_SURFACE)
73        , mAllowPreserveBuffer(load_dirty_regions_property())
74        , mCurrentSurface(EGL_NO_SURFACE)
75        , mAtlasMap(NULL)
76        , mAtlasMapSize(0) {
77    mCanSetPreserveBuffer = mAllowPreserveBuffer;
78    ALOGD("Use EGL_SWAP_BEHAVIOR_PRESERVED: %s", mAllowPreserveBuffer ? "true" : "false");
79}
80
81void EglManager::initialize() {
82    if (hasEglContext()) return;
83
84    mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
85    LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY,
86            "Failed to get EGL_DEFAULT_DISPLAY! err=%s", egl_error_str());
87
88    EGLint major, minor;
89    LOG_ALWAYS_FATAL_IF(eglInitialize(mEglDisplay, &major, &minor) == EGL_FALSE,
90            "Failed to initialize display %p! err=%s", mEglDisplay, egl_error_str());
91
92    ALOGI("Initialized EGL, version %d.%d", (int)major, (int)minor);
93
94    loadConfig();
95    createContext();
96    usePBufferSurface();
97    mRenderThread.renderState().onGLContextCreated();
98    initAtlas();
99}
100
101bool EglManager::hasEglContext() {
102    return mEglDisplay != EGL_NO_DISPLAY;
103}
104
105void EglManager::requireGlContext() {
106    LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY, "No EGL context");
107
108    // We can't be certain about the state of the current surface (whether
109    // or not it is destroyed, for example), so err on the side of using
110    // the pbuffer surface which we fully control
111    usePBufferSurface();
112}
113
114void EglManager::loadConfig() {
115    EGLint swapBehavior = mCanSetPreserveBuffer ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
116    EGLint attribs[] = {
117            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
118            EGL_RED_SIZE, 8,
119            EGL_GREEN_SIZE, 8,
120            EGL_BLUE_SIZE, 8,
121            EGL_ALPHA_SIZE, 8,
122            EGL_DEPTH_SIZE, 0,
123            EGL_CONFIG_CAVEAT, EGL_NONE,
124            EGL_STENCIL_SIZE, Stencil::getStencilSize(),
125            EGL_SURFACE_TYPE, EGL_WINDOW_BIT | swapBehavior,
126            EGL_NONE
127    };
128
129    EGLint num_configs = 1;
130    if (!eglChooseConfig(mEglDisplay, attribs, &mEglConfig, num_configs, &num_configs)
131            || num_configs != 1) {
132        // Failed to get a valid config
133        if (mCanSetPreserveBuffer) {
134            ALOGW("Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...");
135            // Try again without dirty regions enabled
136            mCanSetPreserveBuffer = false;
137            loadConfig();
138        } else {
139            LOG_ALWAYS_FATAL("Failed to choose config, error = %s", egl_error_str());
140        }
141    }
142}
143
144void EglManager::createContext() {
145    EGLint attribs[] = { EGL_CONTEXT_CLIENT_VERSION, GLES_VERSION, EGL_NONE };
146    mEglContext = eglCreateContext(mEglDisplay, mEglConfig, EGL_NO_CONTEXT, attribs);
147    LOG_ALWAYS_FATAL_IF(mEglContext == EGL_NO_CONTEXT,
148        "Failed to create context, error = %s", egl_error_str());
149}
150
151void EglManager::setTextureAtlas(const sp<GraphicBuffer>& buffer,
152        int64_t* map, size_t mapSize) {
153
154    // Already initialized
155    if (mAtlasBuffer.get()) {
156        ALOGW("Multiple calls to setTextureAtlas!");
157        delete map;
158        return;
159    }
160
161    mAtlasBuffer = buffer;
162    mAtlasMap = map;
163    mAtlasMapSize = mapSize;
164
165    if (hasEglContext()) {
166        usePBufferSurface();
167        initAtlas();
168    }
169}
170
171void EglManager::initAtlas() {
172    if (mAtlasBuffer.get()) {
173        Caches::getInstance().assetAtlas.init(mAtlasBuffer, mAtlasMap, mAtlasMapSize);
174    }
175}
176
177void EglManager::usePBufferSurface() {
178    LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY,
179            "usePBufferSurface() called on uninitialized GlobalContext!");
180
181    if (mPBufferSurface == EGL_NO_SURFACE) {
182        EGLint attribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE };
183        mPBufferSurface = eglCreatePbufferSurface(mEglDisplay, mEglConfig, attribs);
184    }
185    makeCurrent(mPBufferSurface);
186}
187
188EGLSurface EglManager::createSurface(EGLNativeWindowType window) {
189    initialize();
190    EGLSurface surface = eglCreateWindowSurface(mEglDisplay, mEglConfig, window, NULL);
191    LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE,
192            "Failed to create EGLSurface for window %p, eglErr = %s",
193            (void*) window, egl_error_str());
194    return surface;
195}
196
197void EglManager::destroySurface(EGLSurface surface) {
198    if (isCurrent(surface)) {
199        makeCurrent(EGL_NO_SURFACE);
200    }
201    if (!eglDestroySurface(mEglDisplay, surface)) {
202        ALOGW("Failed to destroy surface %p, error=%s", (void*)surface, egl_error_str());
203    }
204}
205
206void EglManager::destroy() {
207    if (mEglDisplay == EGL_NO_DISPLAY) return;
208
209    usePBufferSurface();
210    if (Caches::hasInstance()) {
211        Caches::getInstance().terminate();
212    }
213
214    mRenderThread.renderState().onGLContextDestroyed();
215    eglDestroyContext(mEglDisplay, mEglContext);
216    eglDestroySurface(mEglDisplay, mPBufferSurface);
217    eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
218    eglTerminate(mEglDisplay);
219    eglReleaseThread();
220
221    mEglDisplay = EGL_NO_DISPLAY;
222    mEglContext = EGL_NO_CONTEXT;
223    mPBufferSurface = EGL_NO_SURFACE;
224    mCurrentSurface = EGL_NO_SURFACE;
225}
226
227bool EglManager::makeCurrent(EGLSurface surface) {
228    if (isCurrent(surface)) return false;
229
230    if (surface == EGL_NO_SURFACE) {
231        // If we are setting EGL_NO_SURFACE we don't care about any of the potential
232        // return errors, which would only happen if mEglDisplay had already been
233        // destroyed in which case the current context is already NO_CONTEXT
234        eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
235    } else if (!eglMakeCurrent(mEglDisplay, surface, surface, mEglContext)) {
236        LOG_ALWAYS_FATAL("Failed to make current on surface %p, error=%s",
237                (void*)surface, egl_error_str());
238    }
239    mCurrentSurface = surface;
240    return true;
241}
242
243void EglManager::beginFrame(EGLSurface surface, EGLint* width, EGLint* height) {
244    LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE,
245            "Tried to beginFrame on EGL_NO_SURFACE!");
246    makeCurrent(surface);
247    if (width) {
248        eglQuerySurface(mEglDisplay, surface, EGL_WIDTH, width);
249    }
250    if (height) {
251        eglQuerySurface(mEglDisplay, surface, EGL_HEIGHT, height);
252    }
253    eglBeginFrame(mEglDisplay, surface);
254}
255
256bool EglManager::swapBuffers(EGLSurface surface) {
257    eglSwapBuffers(mEglDisplay, surface);
258    EGLint err = eglGetError();
259    if (CC_LIKELY(err == EGL_SUCCESS)) {
260        return true;
261    }
262    if (err == EGL_BAD_SURFACE) {
263        // For some reason our surface was destroyed out from under us
264        // This really shouldn't happen, but if it does we can recover easily
265        // by just not trying to use the surface anymore
266        ALOGW("swapBuffers encountered EGL_BAD_SURFACE on %p, halting rendering...", surface);
267        return false;
268    }
269    LOG_ALWAYS_FATAL("Encountered EGL error %d %s during rendering",
270            err, egl_error_str(err));
271    // Impossible to hit this, but the compiler doesn't know that
272    return false;
273}
274
275bool EglManager::setPreserveBuffer(EGLSurface surface, bool preserve) {
276    if (CC_UNLIKELY(!mAllowPreserveBuffer)) return false;
277
278    bool preserved = false;
279    if (mCanSetPreserveBuffer) {
280        preserved = eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
281                preserve ? EGL_BUFFER_PRESERVED : EGL_BUFFER_DESTROYED);
282        if (CC_UNLIKELY(!preserved)) {
283            ALOGW("Failed to set EGL_SWAP_BEHAVIOR on surface %p, error=%s",
284                    (void*) surface, egl_error_str());
285        }
286    }
287    if (CC_UNLIKELY(!preserved)) {
288        // Maybe it's already set?
289        EGLint swapBehavior;
290        if (eglQuerySurface(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, &swapBehavior)) {
291            preserved = (swapBehavior == EGL_BUFFER_PRESERVED);
292        } else {
293            ALOGW("Failed to query EGL_SWAP_BEHAVIOR on surface %p, error=%p",
294                                (void*) surface, egl_error_str());
295        }
296    }
297
298    return preserved;
299}
300
301} /* namespace renderthread */
302} /* namespace uirenderer */
303} /* namespace android */
304