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