blob: 1f98a46472a51834e082a5dd6b470febb636f3cd [file] [log] [blame]
John Reck67b1e2b2020-08-26 13:17:24 -07001/*
2 * Copyright 2020 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//#define LOG_NDEBUG 0
Ana Krulec70d15b1b2020-12-01 10:05:15 -080018#undef LOG_TAG
19#define LOG_TAG "RenderEngine"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
Alec Mouri678245d2020-09-30 16:58:23 -070022#include <cstdint>
Alec Mouric7f6c8b2020-11-09 18:35:20 -080023#include <memory>
Alec Mouri029d1952020-10-12 10:37:08 -070024
25#include "SkImageInfo.h"
Alec Mouric7f6c8b2020-11-09 18:35:20 -080026#include "log/log_main.h"
Alec Mouri029d1952020-10-12 10:37:08 -070027#include "system/graphics-base-v1.0.h"
John Reck67b1e2b2020-08-26 13:17:24 -070028
John Reck67b1e2b2020-08-26 13:17:24 -070029#include <EGL/egl.h>
30#include <EGL/eglext.h>
Lucas Dupinc3800b82020-10-02 16:24:48 -070031#include <sync/sync.h>
32#include <ui/BlurRegion.h>
33#include <ui/GraphicBuffer.h>
34#include <utils/Trace.h>
35#include "../gl/GLExtensions.h"
36#include "SkiaGLRenderEngine.h"
37#include "filters/BlurFilter.h"
Ana Krulec70d15b1b2020-12-01 10:05:15 -080038#include "filters/LinearEffect.h"
39#include "skia/debug/SkiaCapture.h"
Lucas Dupinc3800b82020-10-02 16:24:48 -070040
John Reck67b1e2b2020-08-26 13:17:24 -070041#include <GrContextOptions.h>
John Reck67b1e2b2020-08-26 13:17:24 -070042#include <SkCanvas.h>
Alec Mourib34f0b72020-10-02 13:18:34 -070043#include <SkColorFilter.h>
44#include <SkColorMatrix.h>
Alec Mourib5777452020-09-28 11:32:42 -070045#include <SkColorSpace.h>
John Reck67b1e2b2020-08-26 13:17:24 -070046#include <SkImage.h>
Lucas Dupinf4cb4a02020-09-22 14:19:26 -070047#include <SkImageFilters.h>
Lucas Dupin3f11e922020-09-22 17:31:04 -070048#include <SkShadowUtils.h>
John Reck67b1e2b2020-08-26 13:17:24 -070049#include <SkSurface.h>
Alec Mourib5777452020-09-28 11:32:42 -070050#include <gl/GrGLInterface.h>
Alec Mourib5777452020-09-28 11:32:42 -070051
52#include <cmath>
53
John Reck67b1e2b2020-08-26 13:17:24 -070054bool checkGlError(const char* op, int lineNumber);
55
56namespace android {
57namespace renderengine {
58namespace skia {
59
60static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
61 EGLint wanted, EGLConfig* outConfig) {
62 EGLint numConfigs = -1, n = 0;
63 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
64 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
65 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
66 configs.resize(n);
67
68 if (!configs.empty()) {
69 if (attribute != EGL_NONE) {
70 for (EGLConfig config : configs) {
71 EGLint value = 0;
72 eglGetConfigAttrib(dpy, config, attribute, &value);
73 if (wanted == value) {
74 *outConfig = config;
75 return NO_ERROR;
76 }
77 }
78 } else {
79 // just pick the first one
80 *outConfig = configs[0];
81 return NO_ERROR;
82 }
83 }
84
85 return NAME_NOT_FOUND;
86}
87
88static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
89 EGLConfig* config) {
90 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
91 // it is to be used with WIFI displays
92 status_t err;
93 EGLint wantedAttribute;
94 EGLint wantedAttributeValue;
95
96 std::vector<EGLint> attribs;
97 if (renderableType) {
98 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
99 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
100
101 // Default to 8 bits per channel.
102 const EGLint tmpAttribs[] = {
103 EGL_RENDERABLE_TYPE,
104 renderableType,
105 EGL_RECORDABLE_ANDROID,
106 EGL_TRUE,
107 EGL_SURFACE_TYPE,
108 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
109 EGL_FRAMEBUFFER_TARGET_ANDROID,
110 EGL_TRUE,
111 EGL_RED_SIZE,
112 is1010102 ? 10 : 8,
113 EGL_GREEN_SIZE,
114 is1010102 ? 10 : 8,
115 EGL_BLUE_SIZE,
116 is1010102 ? 10 : 8,
117 EGL_ALPHA_SIZE,
118 is1010102 ? 2 : 8,
119 EGL_NONE,
120 };
121 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
122 std::back_inserter(attribs));
123 wantedAttribute = EGL_NONE;
124 wantedAttributeValue = EGL_NONE;
125 } else {
126 // if no renderable type specified, fallback to a simplified query
127 wantedAttribute = EGL_NATIVE_VISUAL_ID;
128 wantedAttributeValue = format;
129 }
130
131 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
132 config);
133 if (err == NO_ERROR) {
134 EGLint caveat;
135 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
136 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
137 }
138
139 return err;
140}
141
142std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
143 const RenderEngineCreationArgs& args) {
144 // initialize EGL for the default display
145 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
146 if (!eglInitialize(display, nullptr, nullptr)) {
147 LOG_ALWAYS_FATAL("failed to initialize EGL");
148 }
149
Yiwei Zhange2650962020-12-01 23:27:58 +0000150 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700151 if (!eglVersion) {
152 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000153 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700154 }
155
Yiwei Zhange2650962020-12-01 23:27:58 +0000156 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700157 if (!eglExtensions) {
158 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000159 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700160 }
161
162 auto& extensions = gl::GLExtensions::getInstance();
163 extensions.initWithEGLStrings(eglVersion, eglExtensions);
164
165 // The code assumes that ES2 or later is available if this extension is
166 // supported.
167 EGLConfig config = EGL_NO_CONFIG_KHR;
168 if (!extensions.hasNoConfigContext()) {
169 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
170 }
171
172 bool useContextPriority =
173 extensions.hasContextPriority() && args.contextPriority == ContextPriority::HIGH;
174 EGLContext protectedContext = EGL_NO_CONTEXT;
175 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
176 protectedContext = createEglContext(display, config, nullptr, useContextPriority,
177 Protection::PROTECTED);
178 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
179 }
180
181 EGLContext ctxt = createEglContext(display, config, protectedContext, useContextPriority,
182 Protection::UNPROTECTED);
183
184 // if can't create a GL context, we can only abort.
185 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
186
187 EGLSurface placeholder = EGL_NO_SURFACE;
188 if (!extensions.hasSurfacelessContext()) {
189 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
190 Protection::UNPROTECTED);
191 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
192 }
193 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
194 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
195 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
196 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
197
198 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
199 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
200 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
201 Protection::PROTECTED);
202 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
203 "can't create protected placeholder pbuffer");
204 }
205
206 // initialize the renderer while GL is current
207 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000208 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
209 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700210
211 ALOGI("OpenGL ES informations:");
212 ALOGI("vendor : %s", extensions.getVendor());
213 ALOGI("renderer : %s", extensions.getRenderer());
214 ALOGI("version : %s", extensions.getVersion());
215 ALOGI("extensions: %s", extensions.getExtensions());
216 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
217 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
218
219 return engine;
220}
221
222EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
223 status_t err;
224 EGLConfig config;
225
226 // First try to get an ES3 config
227 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
228 if (err != NO_ERROR) {
229 // If ES3 fails, try to get an ES2 config
230 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
231 if (err != NO_ERROR) {
232 // If ES2 still doesn't work, probably because we're on the emulator.
233 // try a simplified query
234 ALOGW("no suitable EGLConfig found, trying a simpler query");
235 err = selectEGLConfig(display, format, 0, &config);
236 if (err != NO_ERROR) {
237 // this EGL is too lame for android
238 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
239 }
240 }
241 }
242
243 if (logConfig) {
244 // print some debugging info
245 EGLint r, g, b, a;
246 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
247 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
248 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
249 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
250 ALOGI("EGL information:");
251 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
252 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
253 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
254 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
255 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
256 }
257
258 return config;
259}
260
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700261SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000262 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700263 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri081be4c2020-09-16 10:24:47 -0700264 : mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700265 mEGLContext(ctxt),
266 mPlaceholderSurface(placeholder),
267 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700268 mProtectedPlaceholderSurface(protectedPlaceholder),
269 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700270 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
271 LOG_ALWAYS_FATAL_IF(!glInterface.get());
272
273 GrContextOptions options;
274 options.fPreferExternalImagesOverES3 = true;
275 options.fDisableDistanceFieldPaths = true;
Lucas Dupind508e472020-11-04 04:32:06 +0000276 mGrContext = GrDirectContext::MakeGL(glInterface, options);
277 if (useProtectedContext(true)) {
278 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
279 useProtectedContext(false);
280 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700281
282 if (args.supportsBackgroundBlur) {
283 mBlurFilter = new BlurFilter();
284 }
John Reck67b1e2b2020-08-26 13:17:24 -0700285}
286
Lucas Dupind508e472020-11-04 04:32:06 +0000287bool SkiaGLRenderEngine::supportsProtectedContent() const {
288 return mProtectedEGLContext != EGL_NO_CONTEXT;
289}
290
291bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
292 if (useProtectedContext == mInProtectedContext) {
293 return true;
294 }
295 if (useProtectedContext && supportsProtectedContent()) {
296 return false;
297 }
298 const EGLSurface surface =
299 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
300 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
301 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
302 if (success) {
303 mInProtectedContext = useProtectedContext;
304 }
305 return success;
306}
307
John Reck67b1e2b2020-08-26 13:17:24 -0700308base::unique_fd SkiaGLRenderEngine::flush() {
309 ATRACE_CALL();
310 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
311 return base::unique_fd();
312 }
313
314 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
315 if (sync == EGL_NO_SYNC_KHR) {
316 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
317 return base::unique_fd();
318 }
319
320 // native fence fd will not be populated until flush() is done.
321 glFlush();
322
323 // get the fence fd
324 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
325 eglDestroySyncKHR(mEGLDisplay, sync);
326 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
327 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
328 }
329
330 return fenceFd;
331}
332
333bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
334 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
335 !gl::GLExtensions::getInstance().hasWaitSync()) {
336 return false;
337 }
338
339 // release the fd and transfer the ownership to EGLSync
340 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
341 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
342 if (sync == EGL_NO_SYNC_KHR) {
343 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
344 return false;
345 }
346
347 // XXX: The spec draft is inconsistent as to whether this should return an
348 // EGLint or void. Ignore the return value for now, as it's not strictly
349 // needed.
350 eglWaitSyncKHR(mEGLDisplay, sync, 0);
351 EGLint error = eglGetError();
352 eglDestroySyncKHR(mEGLDisplay, sync);
353 if (error != EGL_SUCCESS) {
354 ALOGE("failed to wait for EGL native fence sync: %#x", error);
355 return false;
356 }
357
358 return true;
359}
360
361static bool hasUsage(const AHardwareBuffer_Desc& desc, uint64_t usage) {
362 return !!(desc.usage & usage);
363}
364
Alec Mouri678245d2020-09-30 16:58:23 -0700365static float toDegrees(uint32_t transform) {
366 switch (transform) {
367 case ui::Transform::ROT_90:
368 return 90.0;
369 case ui::Transform::ROT_180:
370 return 180.0;
371 case ui::Transform::ROT_270:
372 return 270.0;
373 default:
374 return 0.0;
375 }
376}
377
Alec Mourib34f0b72020-10-02 13:18:34 -0700378static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
379 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
380 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
381 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
382 matrix[3][3], 0);
383}
384
Alec Mouri029d1952020-10-12 10:37:08 -0700385static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
386 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
387 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
388
389 // Treat unsupported dataspaces as srgb
390 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
391 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
392 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
393 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
394 }
395
396 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
397 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
398 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
399 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
400 }
401
402 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
403 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
404 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
405 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
406
407 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
408 sourceTransfer != destTransfer;
409}
410
Alec Mouri1a4d0642020-11-13 17:42:01 -0800411static bool needsLinearEffect(const mat4& colorTransform, ui::Dataspace sourceDataspace,
412 ui::Dataspace destinationDataspace) {
413 return colorTransform != mat4() || needsToneMapping(sourceDataspace, destinationDataspace);
414}
415
John Reck67b1e2b2020-08-26 13:17:24 -0700416void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
417 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800418 mTextureCache.erase(bufferId);
419 mProtectedTextureCache.erase(bufferId);
John Reck67b1e2b2020-08-26 13:17:24 -0700420}
421
422status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
423 const std::vector<const LayerSettings*>& layers,
424 const sp<GraphicBuffer>& buffer,
425 const bool useFramebufferCache,
426 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
427 ATRACE_NAME("SkiaGL::drawLayers");
428 std::lock_guard<std::mutex> lock(mRenderingMutex);
429 if (layers.empty()) {
430 ALOGV("Drawing empty layer stack");
431 return NO_ERROR;
432 }
433
434 if (bufferFence.get() >= 0) {
435 // Duplicate the fence for passing to waitFence.
436 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
437 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
438 ATRACE_NAME("Waiting before draw");
439 sync_wait(bufferFence.get(), -1);
440 }
441 }
442 if (buffer == nullptr) {
443 ALOGE("No output buffer provided. Aborting GPU composition.");
444 return BAD_VALUE;
445 }
446
Lucas Dupind508e472020-11-04 04:32:06 +0000447 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800448 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700449 AHardwareBuffer_Desc bufferDesc;
450 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700451 LOG_ALWAYS_FATAL_IF(!hasUsage(bufferDesc, AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE),
452 "missing usage");
453
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800454 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700455 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000456 auto iter = cache.find(buffer->getId());
457 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700458 ALOGV("Cache hit!");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800459 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700460 }
461 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800462
463 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
464 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
465 surfaceTextureRef->setTexture(
466 new AutoBackendTexture(mGrContext.get(), buffer->toAHardwareBuffer(), true));
467 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700468 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800469 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700470 }
471 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800472
473 sk_sp<SkSurface> surface =
474 surfaceTextureRef->getTexture()->getOrCreateSurface(mUseColorManagement
475 ? display.outputDataspace
476 : ui::Dataspace::SRGB,
477 mGrContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700478
Ana Krulec70d15b1b2020-12-01 10:05:15 -0800479 SkCanvas* canvas = mCapture.tryCapture(surface.get());
Ana Krulec6eab17a2020-12-09 15:52:36 -0800480 if (canvas == nullptr) {
481 ALOGE("Cannot acquire canvas from Skia.");
482 return BAD_VALUE;
483 }
Alec Mouri678245d2020-09-30 16:58:23 -0700484 // Clear the entire canvas with a transparent black to prevent ghost images.
485 canvas->clear(SK_ColorTRANSPARENT);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700486 canvas->save();
John Reck67b1e2b2020-08-26 13:17:24 -0700487
Ana Krulec6eab17a2020-12-09 15:52:36 -0800488 if (mCapture.isCaptureRunning()) {
489 // Record display settings when capture is running.
490 std::stringstream displaySettings;
491 PrintTo(display, &displaySettings);
492 // Store the DisplaySettings in additional information.
493 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
494 SkData::MakeWithCString(displaySettings.str().c_str()));
495 }
496
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700497 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
498 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
499 // displays might have different scaling when compared to the physical screen.
Alec Mouri678245d2020-09-30 16:58:23 -0700500
501 canvas->clipRect(getSkRect(display.physicalDisplay));
Galia Peychevaf7889b32020-11-25 22:22:40 +0100502 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700503
504 const auto clipWidth = display.clip.width();
505 const auto clipHeight = display.clip.height();
506 auto rotatedClipWidth = clipWidth;
507 auto rotatedClipHeight = clipHeight;
508 // Scale is contingent on the rotation result.
509 if (display.orientation & ui::Transform::ROT_90) {
510 std::swap(rotatedClipWidth, rotatedClipHeight);
511 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700512 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700513 static_cast<SkScalar>(rotatedClipWidth);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700514 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700515 static_cast<SkScalar>(rotatedClipHeight);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100516 canvas->scale(scaleX, scaleY);
Alec Mouri678245d2020-09-30 16:58:23 -0700517
518 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
519 // back so that the top left corner of the clip is at (0, 0).
Galia Peychevaf7889b32020-11-25 22:22:40 +0100520 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
521 canvas->rotate(toDegrees(display.orientation));
522 canvas->translate(-clipWidth / 2, -clipHeight / 2);
523 canvas->translate(-display.clip.left, -display.clip.top);
John Reck67b1e2b2020-08-26 13:17:24 -0700524 for (const auto& layer : layers) {
Galia Peychevaf7889b32020-11-25 22:22:40 +0100525 canvas->save();
526
Ana Krulec6eab17a2020-12-09 15:52:36 -0800527 if (mCapture.isCaptureRunning()) {
528 // Record the name of the layer if the capture is running.
529 std::stringstream layerSettings;
530 PrintTo(*layer, &layerSettings);
531 // Store the LayerSettings in additional information.
532 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
533 SkData::MakeWithCString(layerSettings.str().c_str()));
534 }
535
Galia Peychevaf7889b32020-11-25 22:22:40 +0100536 // Layers have a local transform that should be applied to them
537 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100538
Lucas Dupin21f348e2020-09-16 17:31:26 -0700539 SkPaint paint;
540 const auto& bounds = layer->geometry.boundaries;
Lucas Dupin3f11e922020-09-22 17:31:04 -0700541 const auto dest = getSkRect(bounds);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100542 const auto layerRect = canvas->getTotalMatrix().mapRect(dest);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700543 std::unordered_map<uint32_t, sk_sp<SkSurface>> cachedBlurs;
Lucas Dupinc3800b82020-10-02 16:24:48 -0700544 if (mBlurFilter) {
545 if (layer->backgroundBlurRadius > 0) {
546 ATRACE_NAME("BackgroundBlur");
Galia Peycheva80116e52020-11-06 11:57:25 +0100547 auto blurredSurface = mBlurFilter->generate(canvas, surface,
548 layer->backgroundBlurRadius, layerRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700549 cachedBlurs[layer->backgroundBlurRadius] = blurredSurface;
Galia Peycheva80116e52020-11-06 11:57:25 +0100550
Galia Peychevaf7889b32020-11-25 22:22:40 +0100551 drawBlurRegion(canvas, getBlurRegion(layer), layerRect, blurredSurface);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700552 }
553 if (layer->blurRegions.size() > 0) {
554 for (auto region : layer->blurRegions) {
555 if (cachedBlurs[region.blurRadius]) {
556 continue;
557 }
558 ATRACE_NAME("BlurRegion");
Galia Peycheva6c460652020-11-03 19:42:42 +0100559 auto blurredSurface =
560 mBlurFilter->generate(canvas, surface, region.blurRadius, layerRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700561 cachedBlurs[region.blurRadius] = blurredSurface;
562 }
563 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700564 }
565
John Reck67b1e2b2020-08-26 13:17:24 -0700566 if (layer->source.buffer.buffer) {
567 ATRACE_NAME("DrawImage");
568 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800569 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
570 auto iter = mTextureCache.find(item.buffer->getId());
571 if (iter != mTextureCache.end()) {
572 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700573 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800574 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
575 imageTextureRef->setTexture(new AutoBackendTexture(mGrContext.get(),
576 item.buffer->toAHardwareBuffer(),
577 false));
578 mTextureCache.insert({buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700579 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800580
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800581 sk_sp<SkImage> image =
582 imageTextureRef->getTexture()
583 ->makeImage(mUseColorManagement
Alec Mouri1a4d0642020-11-13 17:42:01 -0800584 ? (needsLinearEffect(layer->colorTransform,
585 layer->sourceDataspace,
586 display.outputDataspace)
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800587 // If we need to map to linear space,
588 // then mark the source image with the
589 // same colorspace as the destination
590 // surface so that Skia's color
591 // management is a no-op.
592 ? display.outputDataspace
593 : layer->sourceDataspace)
594 : ui::Dataspace::SRGB,
595 item.isOpaque ? kOpaque_SkAlphaType
596 : (item.usePremultipliedAlpha
597 ? kPremul_SkAlphaType
598 : kUnpremul_SkAlphaType),
599 mGrContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700600
601 auto texMatrix = getSkM44(item.textureTransform).asM33();
602 // textureTansform was intended to be passed directly into a shader, so when
603 // building the total matrix with the textureTransform we need to first
604 // normalize it, then apply the textureTransform, then scale back up.
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800605 texMatrix.preScale(1.0f / bounds.getWidth(), 1.0f / bounds.getHeight());
606 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700607
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800608 SkMatrix matrix;
609 if (!texMatrix.invert(&matrix)) {
610 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700611 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800612 // The shader does not respect the translation, so we add it to the texture
613 // transform for the SkImage. This will make sure that the correct layer contents
614 // are drawn in the correct part of the screen.
615 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700616
Ana Krulecb7b28b22020-11-23 14:48:58 -0800617 sk_sp<SkShader> shader;
618
619 if (layer->source.buffer.useTextureFiltering) {
620 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
621 SkSamplingOptions(
622 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
623 &matrix);
624 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500625 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800626 }
Alec Mouri029d1952020-10-12 10:37:08 -0700627
628 if (mUseColorManagement &&
Alec Mouri1a4d0642020-11-13 17:42:01 -0800629 needsLinearEffect(layer->colorTransform, layer->sourceDataspace,
630 display.outputDataspace)) {
Alec Mouri029d1952020-10-12 10:37:08 -0700631 LinearEffect effect = LinearEffect{.inputDataspace = layer->sourceDataspace,
632 .outputDataspace = display.outputDataspace,
633 .undoPremultipliedAlpha = !item.isOpaque &&
634 item.usePremultipliedAlpha};
Alec Mouric16a77d2020-11-13 13:20:11 -0800635
636 auto effectIter = mRuntimeEffects.find(effect);
637 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
638 if (effectIter == mRuntimeEffects.end()) {
639 runtimeEffect = buildRuntimeEffect(effect);
640 mRuntimeEffects.insert({effect, runtimeEffect});
641 } else {
642 runtimeEffect = effectIter->second;
643 }
644
Alec Mouri029d1952020-10-12 10:37:08 -0700645 paint.setShader(createLinearEffectShader(shader, effect, runtimeEffect,
Alec Mouri1a4d0642020-11-13 17:42:01 -0800646 layer->colorTransform,
Alec Mouri029d1952020-10-12 10:37:08 -0700647 display.maxLuminance,
648 layer->source.buffer.maxMasteringLuminance,
649 layer->source.buffer.maxContentLuminance));
650 } else {
651 paint.setShader(shader);
652 }
Ana Krulec1768bd22020-11-23 14:51:31 -0800653 // Make sure to take into the account the alpha set on the layer.
654 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700655 } else {
656 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700657 const auto color = layer->source.solidColor;
Lucas Dupinc3800b82020-10-02 16:24:48 -0700658 paint.setShader(SkShaders::Color(SkColor4f{.fR = color.r,
659 .fG = color.g,
660 .fB = color.b,
661 layer->alpha},
662 nullptr));
John Reck67b1e2b2020-08-26 13:17:24 -0700663 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700664
Alec Mourib34f0b72020-10-02 13:18:34 -0700665 paint.setColorFilter(SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform)));
666
Lucas Dupinc3800b82020-10-02 16:24:48 -0700667 for (const auto effectRegion : layer->blurRegions) {
Galia Peychevaf7889b32020-11-25 22:22:40 +0100668 drawBlurRegion(canvas, effectRegion, layerRect, cachedBlurs[effectRegion.blurRadius]);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700669 }
670
Lucas Dupin3f11e922020-09-22 17:31:04 -0700671 if (layer->shadow.length > 0) {
672 const auto rect = layer->geometry.roundedCornersRadius > 0
673 ? getSkRect(layer->geometry.roundedCornersCrop)
674 : dest;
675 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
676 }
677
Ana Krulecf9a15d92020-12-11 08:35:00 -0800678 // Push the clipRRect onto the clip stack. Draw the image. Pop the clip.
Lucas Dupin21f348e2020-09-16 17:31:26 -0700679 if (layer->geometry.roundedCornersRadius > 0) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800680 canvas->clipRRect(getRoundedRect(layer), true);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700681 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800682 canvas->drawRect(dest, paint);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700683 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700684 }
Ana Krulec70d15b1b2020-12-01 10:05:15 -0800685 canvas->restore();
686 mCapture.endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700687 {
688 ATRACE_NAME("flush surface");
689 surface->flush();
690 }
691
692 if (drawFence != nullptr) {
693 *drawFence = flush();
694 }
695
696 // If flush failed or we don't support native fences, we need to force the
697 // gl command stream to be executed.
698 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
699 if (requireSync) {
700 ATRACE_BEGIN("Submit(sync=true)");
701 } else {
702 ATRACE_BEGIN("Submit(sync=false)");
703 }
Lucas Dupind508e472020-11-04 04:32:06 +0000704 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -0700705 ATRACE_END();
706 if (!success) {
707 ALOGE("Failed to flush RenderEngine commands");
708 // Chances are, something illegal happened (either the caller passed
709 // us bad parameters, or we messed up our shader generation).
710 return INVALID_OPERATION;
711 }
712
713 // checkErrors();
714 return NO_ERROR;
715}
716
Lucas Dupin3f11e922020-09-22 17:31:04 -0700717inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
718 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
719}
720
721inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
722 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
723}
724
Lucas Dupin21f348e2020-09-16 17:31:26 -0700725inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800726 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700727 const auto cornerRadius = layer->geometry.roundedCornersRadius;
728 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
729}
730
Galia Peycheva80116e52020-11-06 11:57:25 +0100731inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
732 const auto rect = getSkRect(layer->geometry.boundaries);
733 const auto cornersRadius = layer->geometry.roundedCornersRadius;
734 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
735 .cornerRadiusTL = cornersRadius,
736 .cornerRadiusTR = cornersRadius,
737 .cornerRadiusBL = cornersRadius,
738 .cornerRadiusBR = cornersRadius,
739 .alpha = 1,
740 .left = static_cast<int>(rect.fLeft),
741 .top = static_cast<int>(rect.fTop),
742 .right = static_cast<int>(rect.fRight),
743 .bottom = static_cast<int>(rect.fBottom)};
744}
745
Lucas Dupin3f11e922020-09-22 17:31:04 -0700746inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
747 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
748}
749
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700750inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
751 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
752 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
753 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
754 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
755}
756
Lucas Dupin3f11e922020-09-22 17:31:04 -0700757inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
758 return SkPoint3::Make(vector.x, vector.y, vector.z);
759}
760
John Reck67b1e2b2020-08-26 13:17:24 -0700761size_t SkiaGLRenderEngine::getMaxTextureSize() const {
762 return mGrContext->maxTextureSize();
763}
764
765size_t SkiaGLRenderEngine::getMaxViewportDims() const {
766 return mGrContext->maxRenderTargetSize();
767}
768
Lucas Dupin3f11e922020-09-22 17:31:04 -0700769void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
770 const ShadowSettings& settings) {
771 ATRACE_CALL();
772 const float casterZ = settings.length / 2.0f;
773 const auto shadowShape = cornerRadius > 0
774 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
775 : SkPath::Rect(casterRect);
776 const auto flags =
777 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
778
779 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
780 getSkPoint3(settings.lightPos), settings.lightRadius,
781 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
782 flags);
783}
784
Lucas Dupinc3800b82020-10-02 16:24:48 -0700785void SkiaGLRenderEngine::drawBlurRegion(SkCanvas* canvas, const BlurRegion& effectRegion,
Galia Peychevaf7889b32020-11-25 22:22:40 +0100786 const SkRect& layerRect, sk_sp<SkSurface> blurredSurface) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700787 ATRACE_CALL();
Galia Peycheva80116e52020-11-06 11:57:25 +0100788
Lucas Dupinc3800b82020-10-02 16:24:48 -0700789 SkPaint paint;
Lyn Han1bdedb32020-11-23 20:33:57 +0000790 paint.setAlpha(static_cast<int>(effectRegion.alpha * 255));
Robin Leef180f412020-12-07 02:51:41 +0100791 const auto matrix = getBlurShaderTransform(canvas, layerRect);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100792 paint.setShader(blurredSurface->makeImageSnapshot()->makeShader(
Robin Leef180f412020-12-07 02:51:41 +0100793 SkTileMode::kClamp,
794 SkTileMode::kClamp,
795 SkSamplingOptions({SkFilterMode::kLinear, SkMipmapMode::kNone}),
796 &matrix));
Lucas Dupinc3800b82020-10-02 16:24:48 -0700797
Galia Peycheva80116e52020-11-06 11:57:25 +0100798 auto rect = SkRect::MakeLTRB(effectRegion.left, effectRegion.top, effectRegion.right,
799 effectRegion.bottom);
Galia Peycheva80116e52020-11-06 11:57:25 +0100800
Lucas Dupinc3800b82020-10-02 16:24:48 -0700801 if (effectRegion.cornerRadiusTL > 0 || effectRegion.cornerRadiusTR > 0 ||
802 effectRegion.cornerRadiusBL > 0 || effectRegion.cornerRadiusBR > 0) {
803 const SkVector radii[4] =
804 {SkVector::Make(effectRegion.cornerRadiusTL, effectRegion.cornerRadiusTL),
805 SkVector::Make(effectRegion.cornerRadiusTR, effectRegion.cornerRadiusTR),
806 SkVector::Make(effectRegion.cornerRadiusBL, effectRegion.cornerRadiusBL),
807 SkVector::Make(effectRegion.cornerRadiusBR, effectRegion.cornerRadiusBR)};
808 SkRRect roundedRect;
809 roundedRect.setRectRadii(rect, radii);
810 canvas->drawRRect(roundedRect, paint);
811 } else {
812 canvas->drawRect(rect, paint);
813 }
814}
815
Galia Peychevaf7889b32020-11-25 22:22:40 +0100816SkMatrix SkiaGLRenderEngine::getBlurShaderTransform(const SkCanvas* canvas,
817 const SkRect& layerRect) {
818 // 1. Apply the blur shader matrix, which scales up the blured surface to its real size
819 auto matrix = mBlurFilter->getShaderMatrix();
820 // 2. Since the blurred surface has the size of the layer, we align it with the
821 // top left corner of the layer position.
822 matrix.postConcat(SkMatrix::Translate(layerRect.fLeft, layerRect.fTop));
823 // 3. Finally, apply the inverse canvas matrix. The snapshot made in the BlurFilter is in the
824 // original surface orientation. The inverse matrix has to be applied to align the blur
825 // surface with the current orientation/position of the canvas.
826 SkMatrix drawInverse;
827 if (canvas->getTotalMatrix().invert(&drawInverse)) {
828 matrix.postConcat(drawInverse);
829 }
830
831 return matrix;
832}
833
John Reck67b1e2b2020-08-26 13:17:24 -0700834EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
835 EGLContext shareContext, bool useContextPriority,
836 Protection protection) {
837 EGLint renderableType = 0;
838 if (config == EGL_NO_CONFIG_KHR) {
839 renderableType = EGL_OPENGL_ES3_BIT;
840 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
841 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
842 }
843 EGLint contextClientVersion = 0;
844 if (renderableType & EGL_OPENGL_ES3_BIT) {
845 contextClientVersion = 3;
846 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
847 contextClientVersion = 2;
848 } else if (renderableType & EGL_OPENGL_ES_BIT) {
849 contextClientVersion = 1;
850 } else {
851 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
852 }
853
854 std::vector<EGLint> contextAttributes;
855 contextAttributes.reserve(7);
856 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
857 contextAttributes.push_back(contextClientVersion);
858 if (useContextPriority) {
859 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
860 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
861 }
862 if (protection == Protection::PROTECTED) {
863 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
864 contextAttributes.push_back(EGL_TRUE);
865 }
866 contextAttributes.push_back(EGL_NONE);
867
868 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
869
870 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
871 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
872 // EGL_NO_CONTEXT so that we can abort.
873 if (config != EGL_NO_CONFIG_KHR) {
874 return context;
875 }
876 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
877 // should try to fall back to GLES 2.
878 contextAttributes[1] = 2;
879 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
880 }
881
882 return context;
883}
884
885EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
886 EGLConfig config, int hwcFormat,
887 Protection protection) {
888 EGLConfig placeholderConfig = config;
889 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
890 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
891 }
892 std::vector<EGLint> attributes;
893 attributes.reserve(7);
894 attributes.push_back(EGL_WIDTH);
895 attributes.push_back(1);
896 attributes.push_back(EGL_HEIGHT);
897 attributes.push_back(1);
898 if (protection == Protection::PROTECTED) {
899 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
900 attributes.push_back(EGL_TRUE);
901 }
902 attributes.push_back(EGL_NONE);
903
904 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
905}
906
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800907void SkiaGLRenderEngine::cleanFramebufferCache() {}
John Reck67b1e2b2020-08-26 13:17:24 -0700908
909} // namespace skia
910} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +0100911} // namespace android