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