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