• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <EGL/eglext.h>
20 #include <GLES/gl.h>
21 #include <cutils/properties.h>
22 #include <log/log.h>
23 #include <sync/sync.h>
24 #include <utils/Trace.h>
25 
26 #include <string>
27 #include <vector>
28 
29 #include "Frame.h"
30 #include "Properties.h"
31 #include "utils/Color.h"
32 #include "utils/StringUtils.h"
33 
34 #define GLES_VERSION 2
35 
36 // Android-specific addition that is used to show when frames began in systrace
37 EGLAPI void EGLAPIENTRY eglBeginFrame(EGLDisplay dpy, EGLSurface surface);
38 
39 namespace android {
40 namespace uirenderer {
41 namespace renderthread {
42 
43 #define ERROR_CASE(x) \
44     case x:           \
45         return #x;
egl_error_str(EGLint error)46 static const char* egl_error_str(EGLint error) {
47     switch (error) {
48         ERROR_CASE(EGL_SUCCESS)
49         ERROR_CASE(EGL_NOT_INITIALIZED)
50         ERROR_CASE(EGL_BAD_ACCESS)
51         ERROR_CASE(EGL_BAD_ALLOC)
52         ERROR_CASE(EGL_BAD_ATTRIBUTE)
53         ERROR_CASE(EGL_BAD_CONFIG)
54         ERROR_CASE(EGL_BAD_CONTEXT)
55         ERROR_CASE(EGL_BAD_CURRENT_SURFACE)
56         ERROR_CASE(EGL_BAD_DISPLAY)
57         ERROR_CASE(EGL_BAD_MATCH)
58         ERROR_CASE(EGL_BAD_NATIVE_PIXMAP)
59         ERROR_CASE(EGL_BAD_NATIVE_WINDOW)
60         ERROR_CASE(EGL_BAD_PARAMETER)
61         ERROR_CASE(EGL_BAD_SURFACE)
62         ERROR_CASE(EGL_CONTEXT_LOST)
63         default:
64             return "Unknown error";
65     }
66 }
eglErrorString()67 const char* EglManager::eglErrorString() {
68     return egl_error_str(eglGetError());
69 }
70 
71 static struct {
72     bool bufferAge = false;
73     bool setDamage = false;
74     bool noConfigContext = false;
75     bool pixelFormatFloat = false;
76     bool glColorSpace = false;
77     bool scRGB = false;
78     bool displayP3 = false;
79     bool hdr = false;
80     bool contextPriority = false;
81     bool surfacelessContext = false;
82     bool nativeFenceSync = false;
83     bool fenceSync = false;
84     bool waitSync = false;
85 } EglExtensions;
86 
EglManager()87 EglManager::EglManager()
88         : mEglDisplay(EGL_NO_DISPLAY)
89         , mEglConfig(nullptr)
90         , mEglConfigF16(nullptr)
91         , mEglConfig1010102(nullptr)
92         , mEglContext(EGL_NO_CONTEXT)
93         , mPBufferSurface(EGL_NO_SURFACE)
94         , mCurrentSurface(EGL_NO_SURFACE)
95         , mHasWideColorGamutSupport(false) {}
96 
~EglManager()97 EglManager::~EglManager() {
98     if (hasEglContext()) {
99         ALOGW("~EglManager() leaked an EGL context");
100     }
101 }
102 
initialize()103 void EglManager::initialize() {
104     if (hasEglContext()) return;
105 
106     ATRACE_NAME("Creating EGLContext");
107 
108     mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
109     LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY, "Failed to get EGL_DEFAULT_DISPLAY! err=%s",
110                         eglErrorString());
111 
112     EGLint major, minor;
113     LOG_ALWAYS_FATAL_IF(eglInitialize(mEglDisplay, &major, &minor) == EGL_FALSE,
114                         "Failed to initialize display %p! err=%s", mEglDisplay, eglErrorString());
115 
116     ALOGV("Initialized EGL, version %d.%d", (int)major, (int)minor);
117 
118     initExtensions();
119 
120     // Now that extensions are loaded, pick a swap behavior
121     if (Properties::enablePartialUpdates) {
122         // An Adreno driver bug is causing rendering problems for SkiaGL with
123         // buffer age swap behavior (b/31957043).  To temporarily workaround,
124         // we will use preserved swap behavior.
125         if (Properties::useBufferAge && EglExtensions.bufferAge) {
126             mSwapBehavior = SwapBehavior::BufferAge;
127         } else {
128             mSwapBehavior = SwapBehavior::Preserved;
129         }
130     }
131 
132     loadConfigs();
133     createContext();
134     createPBufferSurface();
135     makeCurrent(mPBufferSurface, nullptr, /* force */ true);
136 
137     skcms_Matrix3x3 wideColorGamut;
138     LOG_ALWAYS_FATAL_IF(!DeviceInfo::get()->getWideColorSpace()->toXYZD50(&wideColorGamut),
139                         "Could not get gamut matrix from wideColorSpace");
140     bool hasWideColorSpaceExtension = false;
141     if (memcmp(&wideColorGamut, &SkNamedGamut::kDisplayP3, sizeof(wideColorGamut)) == 0) {
142         hasWideColorSpaceExtension = EglExtensions.displayP3;
143     } else if (memcmp(&wideColorGamut, &SkNamedGamut::kSRGB, sizeof(wideColorGamut)) == 0) {
144         hasWideColorSpaceExtension = EglExtensions.scRGB;
145     } else {
146         LOG_ALWAYS_FATAL("Unsupported wide color space.");
147     }
148     mHasWideColorGamutSupport = EglExtensions.glColorSpace && hasWideColorSpaceExtension;
149 
150     auto* vendor = reinterpret_cast<const char*>(glGetString(GL_VENDOR));
151     Properties::enableRenderEffectCache = (strcmp(vendor, "Qualcomm") != 0);
152 }
153 
load8BitsConfig(EGLDisplay display,EglManager::SwapBehavior swapBehavior)154 EGLConfig EglManager::load8BitsConfig(EGLDisplay display, EglManager::SwapBehavior swapBehavior) {
155     EGLint eglSwapBehavior =
156             (swapBehavior == SwapBehavior::Preserved) ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
157     EGLint attribs[] = {EGL_RENDERABLE_TYPE,
158                         EGL_OPENGL_ES2_BIT,
159                         EGL_RED_SIZE,
160                         8,
161                         EGL_GREEN_SIZE,
162                         8,
163                         EGL_BLUE_SIZE,
164                         8,
165                         EGL_ALPHA_SIZE,
166                         8,
167                         EGL_DEPTH_SIZE,
168                         0,
169                         EGL_CONFIG_CAVEAT,
170                         EGL_NONE,
171                         EGL_STENCIL_SIZE,
172                         STENCIL_BUFFER_SIZE,
173                         EGL_SURFACE_TYPE,
174                         EGL_WINDOW_BIT | eglSwapBehavior,
175                         EGL_NONE};
176     EGLConfig config = EGL_NO_CONFIG_KHR;
177     EGLint numConfigs = 1;
178     if (!eglChooseConfig(display, attribs, &config, numConfigs, &numConfigs) || numConfigs != 1) {
179         return EGL_NO_CONFIG_KHR;
180     }
181     return config;
182 }
183 
load1010102Config(EGLDisplay display,SwapBehavior swapBehavior)184 EGLConfig EglManager::load1010102Config(EGLDisplay display, SwapBehavior swapBehavior) {
185     EGLint eglSwapBehavior =
186             (swapBehavior == SwapBehavior::Preserved) ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
187     // If we reached this point, we have a valid swap behavior
188     EGLint attribs[] = {EGL_RENDERABLE_TYPE,
189                         EGL_OPENGL_ES2_BIT,
190                         EGL_RED_SIZE,
191                         10,
192                         EGL_GREEN_SIZE,
193                         10,
194                         EGL_BLUE_SIZE,
195                         10,
196                         EGL_ALPHA_SIZE,
197                         2,
198                         EGL_DEPTH_SIZE,
199                         0,
200                         EGL_STENCIL_SIZE,
201                         STENCIL_BUFFER_SIZE,
202                         EGL_SURFACE_TYPE,
203                         EGL_WINDOW_BIT | eglSwapBehavior,
204                         EGL_NONE};
205     EGLConfig config = EGL_NO_CONFIG_KHR;
206     EGLint numConfigs = 1;
207     if (!eglChooseConfig(display, attribs, &config, numConfigs, &numConfigs) || numConfigs != 1) {
208         return EGL_NO_CONFIG_KHR;
209     }
210     return config;
211 }
212 
loadFP16Config(EGLDisplay display,SwapBehavior swapBehavior)213 EGLConfig EglManager::loadFP16Config(EGLDisplay display, SwapBehavior swapBehavior) {
214     EGLint eglSwapBehavior =
215             (swapBehavior == SwapBehavior::Preserved) ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
216     // If we reached this point, we have a valid swap behavior
217     EGLint attribs[] = {EGL_RENDERABLE_TYPE,
218                         EGL_OPENGL_ES2_BIT,
219                         EGL_COLOR_COMPONENT_TYPE_EXT,
220                         EGL_COLOR_COMPONENT_TYPE_FLOAT_EXT,
221                         EGL_RED_SIZE,
222                         16,
223                         EGL_GREEN_SIZE,
224                         16,
225                         EGL_BLUE_SIZE,
226                         16,
227                         EGL_ALPHA_SIZE,
228                         16,
229                         EGL_DEPTH_SIZE,
230                         0,
231                         EGL_STENCIL_SIZE,
232                         STENCIL_BUFFER_SIZE,
233                         EGL_SURFACE_TYPE,
234                         EGL_WINDOW_BIT | eglSwapBehavior,
235                         EGL_NONE};
236     EGLConfig config = EGL_NO_CONFIG_KHR;
237     EGLint numConfigs = 1;
238     if (!eglChooseConfig(display, attribs, &config, numConfigs, &numConfigs) || numConfigs != 1) {
239         return EGL_NO_CONFIG_KHR;
240     }
241     return config;
242 }
243 
initExtensions()244 void EglManager::initExtensions() {
245     auto extensions = StringUtils::split(eglQueryString(mEglDisplay, EGL_EXTENSIONS));
246 
247     // For our purposes we don't care if EGL_BUFFER_AGE is a result of
248     // EGL_EXT_buffer_age or EGL_KHR_partial_update as our usage is covered
249     // under EGL_KHR_partial_update and we don't need the expanded scope
250     // that EGL_EXT_buffer_age provides.
251     EglExtensions.bufferAge =
252             extensions.has("EGL_EXT_buffer_age") || extensions.has("EGL_KHR_partial_update");
253     EglExtensions.setDamage = extensions.has("EGL_KHR_partial_update");
254     LOG_ALWAYS_FATAL_IF(!extensions.has("EGL_KHR_swap_buffers_with_damage"),
255                         "Missing required extension EGL_KHR_swap_buffers_with_damage");
256 
257     EglExtensions.glColorSpace = extensions.has("EGL_KHR_gl_colorspace");
258     EglExtensions.noConfigContext = extensions.has("EGL_KHR_no_config_context");
259     EglExtensions.pixelFormatFloat = extensions.has("EGL_EXT_pixel_format_float");
260     EglExtensions.scRGB = extensions.has("EGL_EXT_gl_colorspace_scrgb");
261     EglExtensions.displayP3 = extensions.has("EGL_EXT_gl_colorspace_display_p3_passthrough");
262     EglExtensions.hdr = extensions.has("EGL_EXT_gl_colorspace_bt2020_pq");
263     EglExtensions.contextPriority = extensions.has("EGL_IMG_context_priority");
264     EglExtensions.surfacelessContext = extensions.has("EGL_KHR_surfaceless_context");
265     EglExtensions.fenceSync = extensions.has("EGL_KHR_fence_sync");
266     EglExtensions.waitSync = extensions.has("EGL_KHR_wait_sync");
267     EglExtensions.nativeFenceSync = extensions.has("EGL_ANDROID_native_fence_sync");
268 }
269 
hasEglContext()270 bool EglManager::hasEglContext() {
271     return mEglDisplay != EGL_NO_DISPLAY;
272 }
273 
loadConfigs()274 void EglManager::loadConfigs() {
275     // Note: The default pixel format is RGBA_8888, when other formats are
276     // available, we should check the target pixel format and configure the
277     // attributes list properly.
278     mEglConfig = load8BitsConfig(mEglDisplay, mSwapBehavior);
279     if (mEglConfig == EGL_NO_CONFIG_KHR) {
280         if (mSwapBehavior == SwapBehavior::Preserved) {
281             // Try again without dirty regions enabled
282             ALOGW("Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...");
283             mSwapBehavior = SwapBehavior::Discard;
284             mEglConfig = load8BitsConfig(mEglDisplay, mSwapBehavior);
285         } else {
286             // Failed to get a valid config
287             LOG_ALWAYS_FATAL("Failed to choose config, error = %s", eglErrorString());
288         }
289     }
290 
291     // When we reach this point, we have a valid swap behavior
292     if (EglExtensions.pixelFormatFloat) {
293         mEglConfigF16 = loadFP16Config(mEglDisplay, mSwapBehavior);
294         if (mEglConfigF16 == EGL_NO_CONFIG_KHR) {
295             ALOGE("Device claims wide gamut support, cannot find matching config, error = %s",
296                   eglErrorString());
297             EglExtensions.pixelFormatFloat = false;
298         }
299     }
300     mEglConfig1010102 = load1010102Config(mEglDisplay, mSwapBehavior);
301     if (mEglConfig1010102 == EGL_NO_CONFIG_KHR) {
302         ALOGW("Failed to initialize 101010-2 format, error = %s",
303               eglErrorString());
304     }
305 }
306 
createContext()307 void EglManager::createContext() {
308     std::vector<EGLint> contextAttributes;
309     contextAttributes.reserve(5);
310     contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
311     contextAttributes.push_back(GLES_VERSION);
312     if (Properties::contextPriority != 0 && EglExtensions.contextPriority) {
313         contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
314         contextAttributes.push_back(Properties::contextPriority);
315     }
316     contextAttributes.push_back(EGL_NONE);
317     mEglContext = eglCreateContext(
318             mEglDisplay, EglExtensions.noConfigContext ? ((EGLConfig) nullptr) : mEglConfig,
319             EGL_NO_CONTEXT, contextAttributes.data());
320     LOG_ALWAYS_FATAL_IF(mEglContext == EGL_NO_CONTEXT, "Failed to create context, error = %s",
321                         eglErrorString());
322 }
323 
createPBufferSurface()324 void EglManager::createPBufferSurface() {
325     LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY,
326                         "usePBufferSurface() called on uninitialized GlobalContext!");
327 
328     if (mPBufferSurface == EGL_NO_SURFACE && !EglExtensions.surfacelessContext) {
329         EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
330         mPBufferSurface = eglCreatePbufferSurface(mEglDisplay, mEglConfig, attribs);
331         LOG_ALWAYS_FATAL_IF(mPBufferSurface == EGL_NO_SURFACE,
332                             "Failed to create a pixel buffer display=%p, "
333                             "mEglConfig=%p, error=%s",
334                             mEglDisplay, mEglConfig, eglErrorString());
335     }
336 }
337 
createSurface(EGLNativeWindowType window,ColorMode colorMode,sk_sp<SkColorSpace> colorSpace)338 Result<EGLSurface, EGLint> EglManager::createSurface(EGLNativeWindowType window,
339                                                      ColorMode colorMode,
340                                                      sk_sp<SkColorSpace> colorSpace) {
341     LOG_ALWAYS_FATAL_IF(!hasEglContext(), "Not initialized");
342 
343     if (!mHasWideColorGamutSupport || !EglExtensions.noConfigContext) {
344         colorMode = ColorMode::Default;
345     }
346 
347     // The color space we want to use depends on whether linear blending is turned
348     // on and whether the app has requested wide color gamut rendering. When wide
349     // color gamut rendering is off, the app simply renders in the display's native
350     // color gamut.
351     //
352     // When wide gamut rendering is off:
353     // - Blending is done by default in gamma space, which requires using a
354     //   linear EGL color space (the GPU uses the color values as is)
355     // - If linear blending is on, we must use the non-linear EGL color space
356     //   (the GPU will perform sRGB to linear and linear to SRGB conversions
357     //   before and after blending)
358     //
359     // When wide gamut rendering is on we cannot rely on the GPU performing
360     // linear blending for us. We use two different color spaces to tag the
361     // surface appropriately for SurfaceFlinger:
362     // - Gamma blending (default) requires the use of the non-linear color space
363     // - Linear blending requires the use of the linear color space
364 
365     // Not all Android targets support the EGL_GL_COLORSPACE_KHR extension
366     // We insert to placeholders to set EGL_GL_COLORSPACE_KHR and its value.
367     // According to section 3.4.1 of the EGL specification, the attributes
368     // list is considered empty if the first entry is EGL_NONE
369     EGLint attribs[] = {EGL_NONE, EGL_NONE, EGL_NONE};
370 
371     EGLConfig config = mEglConfig;
372     if (DeviceInfo::get()->getWideColorType() == kRGBA_F16_SkColorType) {
373         if (mEglConfigF16 == EGL_NO_CONFIG_KHR) {
374             colorMode = ColorMode::Default;
375         } else {
376             config = mEglConfigF16;
377         }
378     }
379     if (EglExtensions.glColorSpace) {
380         attribs[0] = EGL_GL_COLORSPACE_KHR;
381         switch (colorMode) {
382             case ColorMode::Default:
383                 attribs[1] = EGL_GL_COLORSPACE_LINEAR_KHR;
384                 break;
385             case ColorMode::WideColorGamut: {
386                 skcms_Matrix3x3 colorGamut;
387                 LOG_ALWAYS_FATAL_IF(!colorSpace->toXYZD50(&colorGamut),
388                                     "Could not get gamut matrix from color space");
389                 if (memcmp(&colorGamut, &SkNamedGamut::kDisplayP3, sizeof(colorGamut)) == 0) {
390                     attribs[1] = EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT;
391                 } else if (memcmp(&colorGamut, &SkNamedGamut::kSRGB, sizeof(colorGamut)) == 0) {
392                     attribs[1] = EGL_GL_COLORSPACE_SCRGB_EXT;
393                 } else if (memcmp(&colorGamut, &SkNamedGamut::kRec2020, sizeof(colorGamut)) == 0) {
394                     attribs[1] = EGL_GL_COLORSPACE_BT2020_PQ_EXT;
395                 } else {
396                     LOG_ALWAYS_FATAL("Unreachable: unsupported wide color space.");
397                 }
398                 break;
399             }
400             case ColorMode::Hdr:
401                 config = mEglConfigF16;
402                 attribs[1] = EGL_GL_COLORSPACE_BT2020_PQ_EXT;
403                 break;
404             case ColorMode::Hdr10:
405                 config = mEglConfig1010102;
406                 attribs[1] = EGL_GL_COLORSPACE_BT2020_PQ_EXT;
407                 break;
408         }
409     }
410 
411     EGLSurface surface = eglCreateWindowSurface(mEglDisplay, config, window, attribs);
412     if (surface == EGL_NO_SURFACE) {
413         return Error<EGLint>{eglGetError()};
414     }
415 
416     if (mSwapBehavior != SwapBehavior::Preserved) {
417         LOG_ALWAYS_FATAL_IF(eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
418                                              EGL_BUFFER_DESTROYED) == EGL_FALSE,
419                             "Failed to set swap behavior to destroyed for window %p, eglErr = %s",
420                             (void*)window, eglErrorString());
421     }
422 
423     return surface;
424 }
425 
destroySurface(EGLSurface surface)426 void EglManager::destroySurface(EGLSurface surface) {
427     if (isCurrent(surface)) {
428         makeCurrent(EGL_NO_SURFACE);
429     }
430     if (!eglDestroySurface(mEglDisplay, surface)) {
431         ALOGW("Failed to destroy surface %p, error=%s", (void*)surface, eglErrorString());
432     }
433 }
434 
destroy()435 void EglManager::destroy() {
436     if (mEglDisplay == EGL_NO_DISPLAY) return;
437 
438     eglDestroyContext(mEglDisplay, mEglContext);
439     if (mPBufferSurface != EGL_NO_SURFACE) {
440         eglDestroySurface(mEglDisplay, mPBufferSurface);
441     }
442     eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
443     eglTerminate(mEglDisplay);
444     eglReleaseThread();
445 
446     mEglDisplay = EGL_NO_DISPLAY;
447     mEglContext = EGL_NO_CONTEXT;
448     mPBufferSurface = EGL_NO_SURFACE;
449     mCurrentSurface = EGL_NO_SURFACE;
450 }
451 
makeCurrent(EGLSurface surface,EGLint * errOut,bool force)452 bool EglManager::makeCurrent(EGLSurface surface, EGLint* errOut, bool force) {
453     if (!force && isCurrent(surface)) return false;
454 
455     if (surface == EGL_NO_SURFACE) {
456         // Ensure we always have a valid surface & context
457         surface = mPBufferSurface;
458     }
459     if (!eglMakeCurrent(mEglDisplay, surface, surface, mEglContext)) {
460         if (errOut) {
461             *errOut = eglGetError();
462             ALOGW("Failed to make current on surface %p, error=%s", (void*)surface,
463                   egl_error_str(*errOut));
464         } else {
465             LOG_ALWAYS_FATAL("Failed to make current on surface %p, error=%s", (void*)surface,
466                              eglErrorString());
467         }
468     }
469     mCurrentSurface = surface;
470     if (Properties::disableVsync) {
471         eglSwapInterval(mEglDisplay, 0);
472     }
473     return true;
474 }
475 
queryBufferAge(EGLSurface surface)476 EGLint EglManager::queryBufferAge(EGLSurface surface) {
477     switch (mSwapBehavior) {
478         case SwapBehavior::Discard:
479             return 0;
480         case SwapBehavior::Preserved:
481             return 1;
482         case SwapBehavior::BufferAge:
483             EGLint bufferAge;
484             eglQuerySurface(mEglDisplay, surface, EGL_BUFFER_AGE_EXT, &bufferAge);
485             return bufferAge;
486     }
487     return 0;
488 }
489 
beginFrame(EGLSurface surface)490 Frame EglManager::beginFrame(EGLSurface surface) {
491     LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE, "Tried to beginFrame on EGL_NO_SURFACE!");
492     makeCurrent(surface);
493     Frame frame;
494     frame.mSurface = surface;
495     eglQuerySurface(mEglDisplay, surface, EGL_WIDTH, &frame.mWidth);
496     eglQuerySurface(mEglDisplay, surface, EGL_HEIGHT, &frame.mHeight);
497     frame.mBufferAge = queryBufferAge(surface);
498     eglBeginFrame(mEglDisplay, surface);
499     return frame;
500 }
501 
damageFrame(const Frame & frame,const SkRect & dirty)502 void EglManager::damageFrame(const Frame& frame, const SkRect& dirty) {
503 #ifdef EGL_KHR_partial_update
504     if (EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge) {
505         EGLint rects[4];
506         frame.map(dirty, rects);
507         if (!eglSetDamageRegionKHR(mEglDisplay, frame.mSurface, rects, 1)) {
508             LOG_ALWAYS_FATAL("Failed to set damage region on surface %p, error=%s",
509                              (void*)frame.mSurface, eglErrorString());
510         }
511     }
512 #endif
513 }
514 
damageRequiresSwap()515 bool EglManager::damageRequiresSwap() {
516     return EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge;
517 }
518 
swapBuffers(const Frame & frame,const SkRect & screenDirty)519 bool EglManager::swapBuffers(const Frame& frame, const SkRect& screenDirty) {
520     if (CC_UNLIKELY(Properties::waitForGpuCompletion)) {
521         ATRACE_NAME("Finishing GPU work");
522         fence();
523     }
524 
525     EGLint rects[4];
526     frame.map(screenDirty, rects);
527     eglSwapBuffersWithDamageKHR(mEglDisplay, frame.mSurface, rects, screenDirty.isEmpty() ? 0 : 1);
528 
529     EGLint err = eglGetError();
530     if (CC_LIKELY(err == EGL_SUCCESS)) {
531         return true;
532     }
533     if (err == EGL_BAD_SURFACE || err == EGL_BAD_NATIVE_WINDOW) {
534         // For some reason our surface was destroyed out from under us
535         // This really shouldn't happen, but if it does we can recover easily
536         // by just not trying to use the surface anymore
537         ALOGW("swapBuffers encountered EGL error %d on %p, halting rendering...", err,
538               frame.mSurface);
539         return false;
540     }
541     LOG_ALWAYS_FATAL("Encountered EGL error %d %s during rendering", err, egl_error_str(err));
542     // Impossible to hit this, but the compiler doesn't know that
543     return false;
544 }
545 
fence()546 void EglManager::fence() {
547     EGLSyncKHR fence = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_FENCE_KHR, NULL);
548     eglClientWaitSyncKHR(mEglDisplay, fence, EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, EGL_FOREVER_KHR);
549     eglDestroySyncKHR(mEglDisplay, fence);
550 }
551 
setPreserveBuffer(EGLSurface surface,bool preserve)552 bool EglManager::setPreserveBuffer(EGLSurface surface, bool preserve) {
553     if (mSwapBehavior != SwapBehavior::Preserved) return false;
554 
555     bool preserved = eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
556                                       preserve ? EGL_BUFFER_PRESERVED : EGL_BUFFER_DESTROYED);
557     if (!preserved) {
558         ALOGW("Failed to set EGL_SWAP_BEHAVIOR on surface %p, error=%s", (void*)surface,
559               eglErrorString());
560         // Maybe it's already set?
561         EGLint swapBehavior;
562         if (eglQuerySurface(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, &swapBehavior)) {
563             preserved = (swapBehavior == EGL_BUFFER_PRESERVED);
564         } else {
565             ALOGW("Failed to query EGL_SWAP_BEHAVIOR on surface %p, error=%p", (void*)surface,
566                   eglErrorString());
567         }
568     }
569 
570     return preserved;
571 }
572 
waitForeverOnFence(int fence,const char * logname)573 static status_t waitForeverOnFence(int fence, const char* logname) {
574     ATRACE_CALL();
575     if (fence == -1) {
576         return NO_ERROR;
577     }
578     constexpr int warningTimeout = 3000;
579     int err = sync_wait(fence, warningTimeout);
580     if (err < 0 && errno == ETIME) {
581         ALOGE("%s: fence %d didn't signal in %d ms", logname, fence, warningTimeout);
582         err = sync_wait(fence, -1);
583     }
584     return err < 0 ? -errno : status_t(NO_ERROR);
585 }
586 
fenceWait(int fence)587 status_t EglManager::fenceWait(int fence) {
588     if (!hasEglContext()) {
589         ALOGE("EglManager::fenceWait: EGLDisplay not initialized");
590         return INVALID_OPERATION;
591     }
592 
593     if (EglExtensions.waitSync && EglExtensions.nativeFenceSync) {
594         // Block GPU on the fence.
595         // Create an EGLSyncKHR from the current fence.
596         int fenceFd = ::dup(fence);
597         if (fenceFd == -1) {
598             ALOGE("EglManager::fenceWait: error dup'ing fence fd: %d", errno);
599             return -errno;
600         }
601         EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd, EGL_NONE};
602         EGLSyncKHR sync = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
603         if (sync == EGL_NO_SYNC_KHR) {
604             close(fenceFd);
605             ALOGE("EglManager::fenceWait: error creating EGL fence: %#x", eglGetError());
606             return UNKNOWN_ERROR;
607         }
608 
609         // XXX: The spec draft is inconsistent as to whether this should
610         // return an EGLint or void.  Ignore the return value for now, as
611         // it's not strictly needed.
612         eglWaitSyncKHR(mEglDisplay, sync, 0);
613         EGLint eglErr = eglGetError();
614         eglDestroySyncKHR(mEglDisplay, sync);
615         if (eglErr != EGL_SUCCESS) {
616             ALOGE("EglManager::fenceWait: error waiting for EGL fence: %#x", eglErr);
617             return UNKNOWN_ERROR;
618         }
619     } else {
620         // Block CPU on the fence.
621         status_t err = waitForeverOnFence(fence, "EglManager::fenceWait");
622         if (err != NO_ERROR) {
623             ALOGE("EglManager::fenceWait: error waiting for fence: %d", err);
624             return err;
625         }
626     }
627     return OK;
628 }
629 
createReleaseFence(bool useFenceSync,EGLSyncKHR * eglFence,int * nativeFence)630 status_t EglManager::createReleaseFence(bool useFenceSync, EGLSyncKHR* eglFence, int* nativeFence) {
631     *nativeFence = -1;
632     if (!hasEglContext()) {
633         ALOGE("EglManager::createReleaseFence: EGLDisplay not initialized");
634         return INVALID_OPERATION;
635     }
636 
637     if (EglExtensions.nativeFenceSync) {
638         EGLSyncKHR sync = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
639         if (sync == EGL_NO_SYNC_KHR) {
640             ALOGE("EglManager::createReleaseFence: error creating EGL fence: %#x", eglGetError());
641             return UNKNOWN_ERROR;
642         }
643         glFlush();
644         int fenceFd = eglDupNativeFenceFDANDROID(mEglDisplay, sync);
645         eglDestroySyncKHR(mEglDisplay, sync);
646         if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
647             ALOGE("EglManager::createReleaseFence: error dup'ing native fence "
648                   "fd: %#x",
649                   eglGetError());
650             return UNKNOWN_ERROR;
651         }
652         *nativeFence = fenceFd;
653         *eglFence = EGL_NO_SYNC_KHR;
654     } else if (useFenceSync && EglExtensions.fenceSync) {
655         if (*eglFence != EGL_NO_SYNC_KHR) {
656             // There is already a fence for the current slot.  We need to
657             // wait on that before replacing it with another fence to
658             // ensure that all outstanding buffer accesses have completed
659             // before the producer accesses it.
660             EGLint result = eglClientWaitSyncKHR(mEglDisplay, *eglFence, 0, 1000000000);
661             if (result == EGL_FALSE) {
662                 ALOGE("EglManager::createReleaseFence: error waiting for previous fence: %#x",
663                       eglGetError());
664                 return UNKNOWN_ERROR;
665             } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
666                 ALOGE("EglManager::createReleaseFence: timeout waiting for previous fence");
667                 return TIMED_OUT;
668             }
669             eglDestroySyncKHR(mEglDisplay, *eglFence);
670         }
671 
672         // Create a fence for the outstanding accesses in the current
673         // OpenGL ES context.
674         *eglFence = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_FENCE_KHR, nullptr);
675         if (*eglFence == EGL_NO_SYNC_KHR) {
676             ALOGE("EglManager::createReleaseFence: error creating fence: %#x", eglGetError());
677             return UNKNOWN_ERROR;
678         }
679         glFlush();
680     }
681     return OK;
682 }
683 
684 } /* namespace renderthread */
685 } /* namespace uirenderer */
686 } /* namespace android */
687