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