blob: 5cde369cdee008d4a9bd6b15961ab28467108bb5 [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 Mouri4ce5ec02021-01-07 17:33:21 -080022#include "SkiaGLRenderEngine.h"
John Reck67b1e2b2020-08-26 13:17:24 -070023
John Reck67b1e2b2020-08-26 13:17:24 -070024#include <EGL/egl.h>
25#include <EGL/eglext.h>
John Reck67b1e2b2020-08-26 13:17:24 -070026#include <GrContextOptions.h>
John Reck67b1e2b2020-08-26 13:17:24 -070027#include <SkCanvas.h>
Alec Mourib34f0b72020-10-02 13:18:34 -070028#include <SkColorFilter.h>
29#include <SkColorMatrix.h>
Alec Mourib5777452020-09-28 11:32:42 -070030#include <SkColorSpace.h>
John Reck67b1e2b2020-08-26 13:17:24 -070031#include <SkImage.h>
Lucas Dupinf4cb4a02020-09-22 14:19:26 -070032#include <SkImageFilters.h>
Lucas Dupin3f11e922020-09-22 17:31:04 -070033#include <SkShadowUtils.h>
John Reck67b1e2b2020-08-26 13:17:24 -070034#include <SkSurface.h>
Alec Mourib5777452020-09-28 11:32:42 -070035#include <gl/GrGLInterface.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080036#include <sync/sync.h>
37#include <ui/BlurRegion.h>
38#include <ui/GraphicBuffer.h>
39#include <utils/Trace.h>
Alec Mourib5777452020-09-28 11:32:42 -070040
41#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080042#include <cstdint>
43#include <memory>
44
45#include "../gl/GLExtensions.h"
46#include "SkBlendMode.h"
47#include "SkImageInfo.h"
48#include "filters/BlurFilter.h"
49#include "filters/LinearEffect.h"
50#include "log/log_main.h"
51#include "skia/debug/SkiaCapture.h"
52#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070053
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
John Reck67b1e2b2020-08-26 13:17:24 -0700172 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800173 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700174 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800175 protectedContext =
176 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700177 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
178 }
179
Alec Mourid6f09462020-12-07 11:18:17 -0800180 EGLContext ctxt =
181 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700182
183 // if can't create a GL context, we can only abort.
184 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
185
186 EGLSurface placeholder = EGL_NO_SURFACE;
187 if (!extensions.hasSurfacelessContext()) {
188 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
189 Protection::UNPROTECTED);
190 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
191 }
192 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
193 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
194 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
195 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
196
197 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
198 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
199 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
200 Protection::PROTECTED);
201 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
202 "can't create protected placeholder pbuffer");
203 }
204
205 // initialize the renderer while GL is current
206 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000207 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
208 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700209
210 ALOGI("OpenGL ES informations:");
211 ALOGI("vendor : %s", extensions.getVendor());
212 ALOGI("renderer : %s", extensions.getRenderer());
213 ALOGI("version : %s", extensions.getVersion());
214 ALOGI("extensions: %s", extensions.getExtensions());
215 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
216 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
217
218 return engine;
219}
220
221EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
222 status_t err;
223 EGLConfig config;
224
225 // First try to get an ES3 config
226 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
227 if (err != NO_ERROR) {
228 // If ES3 fails, try to get an ES2 config
229 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
230 if (err != NO_ERROR) {
231 // If ES2 still doesn't work, probably because we're on the emulator.
232 // try a simplified query
233 ALOGW("no suitable EGLConfig found, trying a simpler query");
234 err = selectEGLConfig(display, format, 0, &config);
235 if (err != NO_ERROR) {
236 // this EGL is too lame for android
237 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
238 }
239 }
240 }
241
242 if (logConfig) {
243 // print some debugging info
244 EGLint r, g, b, a;
245 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
246 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
247 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
248 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
249 ALOGI("EGL information:");
250 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
251 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
252 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
253 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
254 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
255 }
256
257 return config;
258}
259
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700260SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000261 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700262 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri081be4c2020-09-16 10:24:47 -0700263 : mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700264 mEGLContext(ctxt),
265 mPlaceholderSurface(placeholder),
266 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700267 mProtectedPlaceholderSurface(protectedPlaceholder),
268 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700269 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
270 LOG_ALWAYS_FATAL_IF(!glInterface.get());
271
272 GrContextOptions options;
273 options.fPreferExternalImagesOverES3 = true;
274 options.fDisableDistanceFieldPaths = true;
Lucas Dupind508e472020-11-04 04:32:06 +0000275 mGrContext = GrDirectContext::MakeGL(glInterface, options);
276 if (useProtectedContext(true)) {
277 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
278 useProtectedContext(false);
279 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700280
281 if (args.supportsBackgroundBlur) {
282 mBlurFilter = new BlurFilter();
283 }
John Reck67b1e2b2020-08-26 13:17:24 -0700284}
285
Lucas Dupind508e472020-11-04 04:32:06 +0000286bool SkiaGLRenderEngine::supportsProtectedContent() const {
287 return mProtectedEGLContext != EGL_NO_CONTEXT;
288}
289
290bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
291 if (useProtectedContext == mInProtectedContext) {
292 return true;
293 }
294 if (useProtectedContext && supportsProtectedContent()) {
295 return false;
296 }
297 const EGLSurface surface =
298 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
299 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
300 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
301 if (success) {
302 mInProtectedContext = useProtectedContext;
303 }
304 return success;
305}
306
John Reck67b1e2b2020-08-26 13:17:24 -0700307base::unique_fd SkiaGLRenderEngine::flush() {
308 ATRACE_CALL();
309 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
310 return base::unique_fd();
311 }
312
313 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
314 if (sync == EGL_NO_SYNC_KHR) {
315 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
316 return base::unique_fd();
317 }
318
319 // native fence fd will not be populated until flush() is done.
320 glFlush();
321
322 // get the fence fd
323 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
324 eglDestroySyncKHR(mEGLDisplay, sync);
325 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
326 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
327 }
328
329 return fenceFd;
330}
331
332bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
333 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
334 !gl::GLExtensions::getInstance().hasWaitSync()) {
335 return false;
336 }
337
338 // release the fd and transfer the ownership to EGLSync
339 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
340 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
341 if (sync == EGL_NO_SYNC_KHR) {
342 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
343 return false;
344 }
345
346 // XXX: The spec draft is inconsistent as to whether this should return an
347 // EGLint or void. Ignore the return value for now, as it's not strictly
348 // needed.
349 eglWaitSyncKHR(mEGLDisplay, sync, 0);
350 EGLint error = eglGetError();
351 eglDestroySyncKHR(mEGLDisplay, sync);
352 if (error != EGL_SUCCESS) {
353 ALOGE("failed to wait for EGL native fence sync: %#x", error);
354 return false;
355 }
356
357 return true;
358}
359
360static bool hasUsage(const AHardwareBuffer_Desc& desc, uint64_t usage) {
361 return !!(desc.usage & usage);
362}
363
Alec Mouri678245d2020-09-30 16:58:23 -0700364static float toDegrees(uint32_t transform) {
365 switch (transform) {
366 case ui::Transform::ROT_90:
367 return 90.0;
368 case ui::Transform::ROT_180:
369 return 180.0;
370 case ui::Transform::ROT_270:
371 return 270.0;
372 default:
373 return 0.0;
374 }
375}
376
Alec Mourib34f0b72020-10-02 13:18:34 -0700377static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
378 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
379 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
380 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
381 matrix[3][3], 0);
382}
383
Alec Mouri029d1952020-10-12 10:37:08 -0700384static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
385 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
386 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
387
388 // Treat unsupported dataspaces as srgb
389 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
390 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
391 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
392 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
393 }
394
395 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
396 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
397 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
398 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
399 }
400
401 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
402 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
403 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
404 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
405
406 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
407 sourceTransfer != destTransfer;
408}
409
Alec Mouri1a4d0642020-11-13 17:42:01 -0800410static bool needsLinearEffect(const mat4& colorTransform, ui::Dataspace sourceDataspace,
411 ui::Dataspace destinationDataspace) {
412 return colorTransform != mat4() || needsToneMapping(sourceDataspace, destinationDataspace);
413}
414
John Reck67b1e2b2020-08-26 13:17:24 -0700415void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
416 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800417 mTextureCache.erase(bufferId);
418 mProtectedTextureCache.erase(bufferId);
John Reck67b1e2b2020-08-26 13:17:24 -0700419}
420
421status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
422 const std::vector<const LayerSettings*>& layers,
423 const sp<GraphicBuffer>& buffer,
424 const bool useFramebufferCache,
425 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
426 ATRACE_NAME("SkiaGL::drawLayers");
427 std::lock_guard<std::mutex> lock(mRenderingMutex);
428 if (layers.empty()) {
429 ALOGV("Drawing empty layer stack");
430 return NO_ERROR;
431 }
432
433 if (bufferFence.get() >= 0) {
434 // Duplicate the fence for passing to waitFence.
435 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
436 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
437 ATRACE_NAME("Waiting before draw");
438 sync_wait(bufferFence.get(), -1);
439 }
440 }
441 if (buffer == nullptr) {
442 ALOGE("No output buffer provided. Aborting GPU composition.");
443 return BAD_VALUE;
444 }
445
Lucas Dupind508e472020-11-04 04:32:06 +0000446 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800447 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700448 AHardwareBuffer_Desc bufferDesc;
449 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700450 LOG_ALWAYS_FATAL_IF(!hasUsage(bufferDesc, AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE),
451 "missing usage");
452
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800453 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700454 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000455 auto iter = cache.find(buffer->getId());
456 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700457 ALOGV("Cache hit!");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800458 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700459 }
460 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800461
462 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
463 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
464 surfaceTextureRef->setTexture(
465 new AutoBackendTexture(mGrContext.get(), buffer->toAHardwareBuffer(), true));
466 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700467 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800468 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700469 }
470 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800471
472 sk_sp<SkSurface> surface =
473 surfaceTextureRef->getTexture()->getOrCreateSurface(mUseColorManagement
474 ? display.outputDataspace
475 : ui::Dataspace::SRGB,
476 mGrContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700477
Ana Krulec70d15b1b2020-12-01 10:05:15 -0800478 SkCanvas* canvas = mCapture.tryCapture(surface.get());
Ana Krulec6eab17a2020-12-09 15:52:36 -0800479 if (canvas == nullptr) {
480 ALOGE("Cannot acquire canvas from Skia.");
481 return BAD_VALUE;
482 }
Alec Mouri678245d2020-09-30 16:58:23 -0700483 // Clear the entire canvas with a transparent black to prevent ghost images.
484 canvas->clear(SK_ColorTRANSPARENT);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700485 canvas->save();
John Reck67b1e2b2020-08-26 13:17:24 -0700486
Ana Krulec6eab17a2020-12-09 15:52:36 -0800487 if (mCapture.isCaptureRunning()) {
488 // Record display settings when capture is running.
489 std::stringstream displaySettings;
490 PrintTo(display, &displaySettings);
491 // Store the DisplaySettings in additional information.
492 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
493 SkData::MakeWithCString(displaySettings.str().c_str()));
494 }
495
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700496 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
497 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
498 // displays might have different scaling when compared to the physical screen.
Alec Mouri678245d2020-09-30 16:58:23 -0700499
500 canvas->clipRect(getSkRect(display.physicalDisplay));
Galia Peychevaf7889b32020-11-25 22:22:40 +0100501 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700502
503 const auto clipWidth = display.clip.width();
504 const auto clipHeight = display.clip.height();
505 auto rotatedClipWidth = clipWidth;
506 auto rotatedClipHeight = clipHeight;
507 // Scale is contingent on the rotation result.
508 if (display.orientation & ui::Transform::ROT_90) {
509 std::swap(rotatedClipWidth, rotatedClipHeight);
510 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700511 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700512 static_cast<SkScalar>(rotatedClipWidth);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700513 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700514 static_cast<SkScalar>(rotatedClipHeight);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100515 canvas->scale(scaleX, scaleY);
Alec Mouri678245d2020-09-30 16:58:23 -0700516
517 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
518 // back so that the top left corner of the clip is at (0, 0).
Galia Peychevaf7889b32020-11-25 22:22:40 +0100519 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
520 canvas->rotate(toDegrees(display.orientation));
521 canvas->translate(-clipWidth / 2, -clipHeight / 2);
522 canvas->translate(-display.clip.left, -display.clip.top);
John Reck67b1e2b2020-08-26 13:17:24 -0700523 for (const auto& layer : layers) {
Galia Peychevaf7889b32020-11-25 22:22:40 +0100524 canvas->save();
525
Ana Krulec6eab17a2020-12-09 15:52:36 -0800526 if (mCapture.isCaptureRunning()) {
527 // Record the name of the layer if the capture is running.
528 std::stringstream layerSettings;
529 PrintTo(*layer, &layerSettings);
530 // Store the LayerSettings in additional information.
531 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
532 SkData::MakeWithCString(layerSettings.str().c_str()));
533 }
534
Galia Peychevaf7889b32020-11-25 22:22:40 +0100535 // Layers have a local transform that should be applied to them
536 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100537
Lucas Dupin21f348e2020-09-16 17:31:26 -0700538 SkPaint paint;
539 const auto& bounds = layer->geometry.boundaries;
Lucas Dupin3f11e922020-09-22 17:31:04 -0700540 const auto dest = getSkRect(bounds);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100541 const auto layerRect = canvas->getTotalMatrix().mapRect(dest);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700542 std::unordered_map<uint32_t, sk_sp<SkSurface>> cachedBlurs;
Lucas Dupinc3800b82020-10-02 16:24:48 -0700543 if (mBlurFilter) {
544 if (layer->backgroundBlurRadius > 0) {
545 ATRACE_NAME("BackgroundBlur");
Galia Peycheva80116e52020-11-06 11:57:25 +0100546 auto blurredSurface = mBlurFilter->generate(canvas, surface,
547 layer->backgroundBlurRadius, layerRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700548 cachedBlurs[layer->backgroundBlurRadius] = blurredSurface;
Galia Peycheva80116e52020-11-06 11:57:25 +0100549
Galia Peychevaf7889b32020-11-25 22:22:40 +0100550 drawBlurRegion(canvas, getBlurRegion(layer), layerRect, blurredSurface);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700551 }
552 if (layer->blurRegions.size() > 0) {
553 for (auto region : layer->blurRegions) {
554 if (cachedBlurs[region.blurRadius]) {
555 continue;
556 }
557 ATRACE_NAME("BlurRegion");
Galia Peycheva6c460652020-11-03 19:42:42 +0100558 auto blurredSurface =
559 mBlurFilter->generate(canvas, surface, region.blurRadius, layerRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700560 cachedBlurs[region.blurRadius] = blurredSurface;
561 }
562 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700563 }
564
John Reck67b1e2b2020-08-26 13:17:24 -0700565 if (layer->source.buffer.buffer) {
566 ATRACE_NAME("DrawImage");
567 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800568 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
569 auto iter = mTextureCache.find(item.buffer->getId());
570 if (iter != mTextureCache.end()) {
571 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700572 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800573 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
574 imageTextureRef->setTexture(new AutoBackendTexture(mGrContext.get(),
575 item.buffer->toAHardwareBuffer(),
576 false));
577 mTextureCache.insert({buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700578 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800579
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800580 sk_sp<SkImage> image =
581 imageTextureRef->getTexture()
582 ->makeImage(mUseColorManagement
Alec Mouri1a4d0642020-11-13 17:42:01 -0800583 ? (needsLinearEffect(layer->colorTransform,
584 layer->sourceDataspace,
585 display.outputDataspace)
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800586 // If we need to map to linear space,
587 // then mark the source image with the
588 // same colorspace as the destination
589 // surface so that Skia's color
590 // management is a no-op.
591 ? display.outputDataspace
592 : layer->sourceDataspace)
593 : ui::Dataspace::SRGB,
594 item.isOpaque ? kOpaque_SkAlphaType
595 : (item.usePremultipliedAlpha
596 ? kPremul_SkAlphaType
597 : kUnpremul_SkAlphaType),
598 mGrContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700599
600 auto texMatrix = getSkM44(item.textureTransform).asM33();
601 // textureTansform was intended to be passed directly into a shader, so when
602 // building the total matrix with the textureTransform we need to first
603 // normalize it, then apply the textureTransform, then scale back up.
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800604 texMatrix.preScale(1.0f / bounds.getWidth(), 1.0f / bounds.getHeight());
605 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700606
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800607 SkMatrix matrix;
608 if (!texMatrix.invert(&matrix)) {
609 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700610 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800611 // The shader does not respect the translation, so we add it to the texture
612 // transform for the SkImage. This will make sure that the correct layer contents
613 // are drawn in the correct part of the screen.
614 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700615
Ana Krulecb7b28b22020-11-23 14:48:58 -0800616 sk_sp<SkShader> shader;
617
618 if (layer->source.buffer.useTextureFiltering) {
619 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
620 SkSamplingOptions(
621 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
622 &matrix);
623 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500624 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800625 }
Alec Mouri029d1952020-10-12 10:37:08 -0700626
627 if (mUseColorManagement &&
Alec Mouri1a4d0642020-11-13 17:42:01 -0800628 needsLinearEffect(layer->colorTransform, layer->sourceDataspace,
629 display.outputDataspace)) {
Alec Mouri029d1952020-10-12 10:37:08 -0700630 LinearEffect effect = LinearEffect{.inputDataspace = layer->sourceDataspace,
631 .outputDataspace = display.outputDataspace,
632 .undoPremultipliedAlpha = !item.isOpaque &&
633 item.usePremultipliedAlpha};
Alec Mouric16a77d2020-11-13 13:20:11 -0800634
635 auto effectIter = mRuntimeEffects.find(effect);
636 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
637 if (effectIter == mRuntimeEffects.end()) {
638 runtimeEffect = buildRuntimeEffect(effect);
639 mRuntimeEffects.insert({effect, runtimeEffect});
640 } else {
641 runtimeEffect = effectIter->second;
642 }
643
Alec Mouri029d1952020-10-12 10:37:08 -0700644 paint.setShader(createLinearEffectShader(shader, effect, runtimeEffect,
Alec Mouri1a4d0642020-11-13 17:42:01 -0800645 layer->colorTransform,
Alec Mouri029d1952020-10-12 10:37:08 -0700646 display.maxLuminance,
647 layer->source.buffer.maxMasteringLuminance,
648 layer->source.buffer.maxContentLuminance));
649 } else {
650 paint.setShader(shader);
651 }
Ana Krulec1768bd22020-11-23 14:51:31 -0800652 // Make sure to take into the account the alpha set on the layer.
653 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700654 } else {
655 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700656 const auto color = layer->source.solidColor;
Lucas Dupinc3800b82020-10-02 16:24:48 -0700657 paint.setShader(SkShaders::Color(SkColor4f{.fR = color.r,
658 .fG = color.g,
659 .fB = color.b,
660 layer->alpha},
661 nullptr));
John Reck67b1e2b2020-08-26 13:17:24 -0700662 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700663
Alec Mouri4ce5ec02021-01-07 17:33:21 -0800664 sk_sp<SkColorFilter> filter =
665 SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
666
667 // Handle opaque images - it's a little nonstandard how we do this.
668 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
669 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
670 // The important language is that when isOpaque is set, opacity is not sampled from the
671 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
672 // here's the conundrum:
673 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated as
674 // an internal hint - composition is undefined when there are alpha bits present.
675 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888 buffers,
676 // i.e., treating them as RGBx8888 instead. But we can't do the same for RGBA1010102 because
677 // RGBx1010102 is not supported as a pixel layout for SkImages. It's also not clear what to
678 // use for F16 either, and lying about the pixel layout is a bit of a hack anyways.
679 // 3. We can't change the blendmode to src, because while this satisfies the requirement for
680 // ignoring the alpha channel, it doesn't quite satisfy the blending requirement because
681 // src always clobbers the destination content.
682 //
683 // So, what we do here instead is an additive blend mode where we compose the input image
684 // with a solid black. This might need to be reassess if this does not support FP16
685 // incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
686 if (layer->source.buffer.buffer && layer->source.buffer.isOpaque) {
687 filter = SkColorFilters::Compose(filter,
688 SkColorFilters::Blend(SK_ColorBLACK,
689 SkBlendMode::kPlus));
690 }
691
692 paint.setColorFilter(filter);
Alec Mourib34f0b72020-10-02 13:18:34 -0700693
Lucas Dupinc3800b82020-10-02 16:24:48 -0700694 for (const auto effectRegion : layer->blurRegions) {
Galia Peychevaf7889b32020-11-25 22:22:40 +0100695 drawBlurRegion(canvas, effectRegion, layerRect, cachedBlurs[effectRegion.blurRadius]);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700696 }
697
Lucas Dupin3f11e922020-09-22 17:31:04 -0700698 if (layer->shadow.length > 0) {
699 const auto rect = layer->geometry.roundedCornersRadius > 0
700 ? getSkRect(layer->geometry.roundedCornersCrop)
701 : dest;
702 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800703 } else {
704 // Shadows are assumed to live only on their own layer - it's not valid
705 // to draw the boundary retangles when there is already a caster shadow
706 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
707 // composition - using a well-defined invalid color is long-term less error-prone.
708 // Push the clipRRect onto the clip stack. Draw the image. Pop the clip.
709 if (layer->geometry.roundedCornersRadius > 0) {
710 canvas->clipRRect(getRoundedRect(layer), true);
711 }
712 canvas->drawRect(dest, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700713 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700714 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700715 }
Ana Krulec70d15b1b2020-12-01 10:05:15 -0800716 canvas->restore();
717 mCapture.endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700718 {
719 ATRACE_NAME("flush surface");
720 surface->flush();
721 }
722
723 if (drawFence != nullptr) {
724 *drawFence = flush();
725 }
726
727 // If flush failed or we don't support native fences, we need to force the
728 // gl command stream to be executed.
729 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
730 if (requireSync) {
731 ATRACE_BEGIN("Submit(sync=true)");
732 } else {
733 ATRACE_BEGIN("Submit(sync=false)");
734 }
Lucas Dupind508e472020-11-04 04:32:06 +0000735 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -0700736 ATRACE_END();
737 if (!success) {
738 ALOGE("Failed to flush RenderEngine commands");
739 // Chances are, something illegal happened (either the caller passed
740 // us bad parameters, or we messed up our shader generation).
741 return INVALID_OPERATION;
742 }
743
744 // checkErrors();
745 return NO_ERROR;
746}
747
Lucas Dupin3f11e922020-09-22 17:31:04 -0700748inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
749 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
750}
751
752inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
753 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
754}
755
Lucas Dupin21f348e2020-09-16 17:31:26 -0700756inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800757 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700758 const auto cornerRadius = layer->geometry.roundedCornersRadius;
759 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
760}
761
Galia Peycheva80116e52020-11-06 11:57:25 +0100762inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
763 const auto rect = getSkRect(layer->geometry.boundaries);
764 const auto cornersRadius = layer->geometry.roundedCornersRadius;
765 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
766 .cornerRadiusTL = cornersRadius,
767 .cornerRadiusTR = cornersRadius,
768 .cornerRadiusBL = cornersRadius,
769 .cornerRadiusBR = cornersRadius,
770 .alpha = 1,
771 .left = static_cast<int>(rect.fLeft),
772 .top = static_cast<int>(rect.fTop),
773 .right = static_cast<int>(rect.fRight),
774 .bottom = static_cast<int>(rect.fBottom)};
775}
776
Lucas Dupin3f11e922020-09-22 17:31:04 -0700777inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
778 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
779}
780
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700781inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
782 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
783 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
784 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
785 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
786}
787
Lucas Dupin3f11e922020-09-22 17:31:04 -0700788inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
789 return SkPoint3::Make(vector.x, vector.y, vector.z);
790}
791
John Reck67b1e2b2020-08-26 13:17:24 -0700792size_t SkiaGLRenderEngine::getMaxTextureSize() const {
793 return mGrContext->maxTextureSize();
794}
795
796size_t SkiaGLRenderEngine::getMaxViewportDims() const {
797 return mGrContext->maxRenderTargetSize();
798}
799
Lucas Dupin3f11e922020-09-22 17:31:04 -0700800void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
801 const ShadowSettings& settings) {
802 ATRACE_CALL();
803 const float casterZ = settings.length / 2.0f;
804 const auto shadowShape = cornerRadius > 0
805 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
806 : SkPath::Rect(casterRect);
807 const auto flags =
808 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
809
810 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
811 getSkPoint3(settings.lightPos), settings.lightRadius,
812 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
813 flags);
814}
815
Lucas Dupinc3800b82020-10-02 16:24:48 -0700816void SkiaGLRenderEngine::drawBlurRegion(SkCanvas* canvas, const BlurRegion& effectRegion,
Galia Peychevaf7889b32020-11-25 22:22:40 +0100817 const SkRect& layerRect, sk_sp<SkSurface> blurredSurface) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700818 ATRACE_CALL();
Galia Peycheva80116e52020-11-06 11:57:25 +0100819
Lucas Dupinc3800b82020-10-02 16:24:48 -0700820 SkPaint paint;
Lyn Han1bdedb32020-11-23 20:33:57 +0000821 paint.setAlpha(static_cast<int>(effectRegion.alpha * 255));
Robin Leef180f412020-12-07 02:51:41 +0100822 const auto matrix = getBlurShaderTransform(canvas, layerRect);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100823 paint.setShader(blurredSurface->makeImageSnapshot()->makeShader(
Robin Leef180f412020-12-07 02:51:41 +0100824 SkTileMode::kClamp,
825 SkTileMode::kClamp,
826 SkSamplingOptions({SkFilterMode::kLinear, SkMipmapMode::kNone}),
827 &matrix));
Lucas Dupinc3800b82020-10-02 16:24:48 -0700828
Galia Peycheva80116e52020-11-06 11:57:25 +0100829 auto rect = SkRect::MakeLTRB(effectRegion.left, effectRegion.top, effectRegion.right,
830 effectRegion.bottom);
Galia Peycheva80116e52020-11-06 11:57:25 +0100831
Lucas Dupinc3800b82020-10-02 16:24:48 -0700832 if (effectRegion.cornerRadiusTL > 0 || effectRegion.cornerRadiusTR > 0 ||
833 effectRegion.cornerRadiusBL > 0 || effectRegion.cornerRadiusBR > 0) {
834 const SkVector radii[4] =
835 {SkVector::Make(effectRegion.cornerRadiusTL, effectRegion.cornerRadiusTL),
836 SkVector::Make(effectRegion.cornerRadiusTR, effectRegion.cornerRadiusTR),
837 SkVector::Make(effectRegion.cornerRadiusBL, effectRegion.cornerRadiusBL),
838 SkVector::Make(effectRegion.cornerRadiusBR, effectRegion.cornerRadiusBR)};
839 SkRRect roundedRect;
840 roundedRect.setRectRadii(rect, radii);
841 canvas->drawRRect(roundedRect, paint);
842 } else {
843 canvas->drawRect(rect, paint);
844 }
845}
846
Galia Peychevaf7889b32020-11-25 22:22:40 +0100847SkMatrix SkiaGLRenderEngine::getBlurShaderTransform(const SkCanvas* canvas,
848 const SkRect& layerRect) {
849 // 1. Apply the blur shader matrix, which scales up the blured surface to its real size
850 auto matrix = mBlurFilter->getShaderMatrix();
851 // 2. Since the blurred surface has the size of the layer, we align it with the
852 // top left corner of the layer position.
853 matrix.postConcat(SkMatrix::Translate(layerRect.fLeft, layerRect.fTop));
854 // 3. Finally, apply the inverse canvas matrix. The snapshot made in the BlurFilter is in the
855 // original surface orientation. The inverse matrix has to be applied to align the blur
856 // surface with the current orientation/position of the canvas.
857 SkMatrix drawInverse;
858 if (canvas->getTotalMatrix().invert(&drawInverse)) {
859 matrix.postConcat(drawInverse);
860 }
861
862 return matrix;
863}
864
John Reck67b1e2b2020-08-26 13:17:24 -0700865EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -0800866 EGLContext shareContext,
867 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -0700868 Protection protection) {
869 EGLint renderableType = 0;
870 if (config == EGL_NO_CONFIG_KHR) {
871 renderableType = EGL_OPENGL_ES3_BIT;
872 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
873 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
874 }
875 EGLint contextClientVersion = 0;
876 if (renderableType & EGL_OPENGL_ES3_BIT) {
877 contextClientVersion = 3;
878 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
879 contextClientVersion = 2;
880 } else if (renderableType & EGL_OPENGL_ES_BIT) {
881 contextClientVersion = 1;
882 } else {
883 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
884 }
885
886 std::vector<EGLint> contextAttributes;
887 contextAttributes.reserve(7);
888 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
889 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -0800890 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -0700891 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -0800892 switch (*contextPriority) {
893 case ContextPriority::REALTIME:
894 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
895 break;
896 case ContextPriority::MEDIUM:
897 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
898 break;
899 case ContextPriority::LOW:
900 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
901 break;
902 case ContextPriority::HIGH:
903 default:
904 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
905 break;
906 }
John Reck67b1e2b2020-08-26 13:17:24 -0700907 }
908 if (protection == Protection::PROTECTED) {
909 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
910 contextAttributes.push_back(EGL_TRUE);
911 }
912 contextAttributes.push_back(EGL_NONE);
913
914 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
915
916 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
917 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
918 // EGL_NO_CONTEXT so that we can abort.
919 if (config != EGL_NO_CONFIG_KHR) {
920 return context;
921 }
922 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
923 // should try to fall back to GLES 2.
924 contextAttributes[1] = 2;
925 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
926 }
927
928 return context;
929}
930
Alec Mourid6f09462020-12-07 11:18:17 -0800931std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
932 const RenderEngineCreationArgs& args) {
933 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
934 return std::nullopt;
935 }
936
937 switch (args.contextPriority) {
938 case RenderEngine::ContextPriority::REALTIME:
939 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
940 return RenderEngine::ContextPriority::REALTIME;
941 } else {
942 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
943 return RenderEngine::ContextPriority::HIGH;
944 }
945 case RenderEngine::ContextPriority::HIGH:
946 case RenderEngine::ContextPriority::MEDIUM:
947 case RenderEngine::ContextPriority::LOW:
948 return args.contextPriority;
949 default:
950 return std::nullopt;
951 }
952}
953
John Reck67b1e2b2020-08-26 13:17:24 -0700954EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
955 EGLConfig config, int hwcFormat,
956 Protection protection) {
957 EGLConfig placeholderConfig = config;
958 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
959 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
960 }
961 std::vector<EGLint> attributes;
962 attributes.reserve(7);
963 attributes.push_back(EGL_WIDTH);
964 attributes.push_back(1);
965 attributes.push_back(EGL_HEIGHT);
966 attributes.push_back(1);
967 if (protection == Protection::PROTECTED) {
968 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
969 attributes.push_back(EGL_TRUE);
970 }
971 attributes.push_back(EGL_NONE);
972
973 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
974}
975
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800976void SkiaGLRenderEngine::cleanFramebufferCache() {}
John Reck67b1e2b2020-08-26 13:17:24 -0700977
Alec Mourid6f09462020-12-07 11:18:17 -0800978int SkiaGLRenderEngine::getContextPriority() {
979 int value;
980 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
981 return value;
982}
983
John Reck67b1e2b2020-08-26 13:17:24 -0700984} // namespace skia
985} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +0100986} // namespace android