blob: d9495a90897ddc87524a378e778544b950ece9c2 [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
Ana Krulec47814212021-01-06 19:00:10 -0800421sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
422 const LayerSettings* layer,
423 const DisplaySettings& display,
424 bool undoPremultipliedAlpha) {
425 if (mUseColorManagement &&
426 needsLinearEffect(layer->colorTransform, layer->sourceDataspace, display.outputDataspace)) {
427 LinearEffect effect = LinearEffect{.inputDataspace = layer->sourceDataspace,
428 .outputDataspace = display.outputDataspace,
429 .undoPremultipliedAlpha = undoPremultipliedAlpha};
430
431 auto effectIter = mRuntimeEffects.find(effect);
432 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
433 if (effectIter == mRuntimeEffects.end()) {
434 runtimeEffect = buildRuntimeEffect(effect);
435 mRuntimeEffects.insert({effect, runtimeEffect});
436 } else {
437 runtimeEffect = effectIter->second;
438 }
439 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
440 display.maxLuminance,
441 layer->source.buffer.maxMasteringLuminance,
442 layer->source.buffer.maxContentLuminance);
443 }
444 return shader;
445}
446
John Reck67b1e2b2020-08-26 13:17:24 -0700447status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
448 const std::vector<const LayerSettings*>& layers,
449 const sp<GraphicBuffer>& buffer,
450 const bool useFramebufferCache,
451 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
452 ATRACE_NAME("SkiaGL::drawLayers");
453 std::lock_guard<std::mutex> lock(mRenderingMutex);
454 if (layers.empty()) {
455 ALOGV("Drawing empty layer stack");
456 return NO_ERROR;
457 }
458
459 if (bufferFence.get() >= 0) {
460 // Duplicate the fence for passing to waitFence.
461 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
462 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
463 ATRACE_NAME("Waiting before draw");
464 sync_wait(bufferFence.get(), -1);
465 }
466 }
467 if (buffer == nullptr) {
468 ALOGE("No output buffer provided. Aborting GPU composition.");
469 return BAD_VALUE;
470 }
471
Lucas Dupind508e472020-11-04 04:32:06 +0000472 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800473 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700474 AHardwareBuffer_Desc bufferDesc;
475 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700476 LOG_ALWAYS_FATAL_IF(!hasUsage(bufferDesc, AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE),
477 "missing usage");
478
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800479 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700480 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000481 auto iter = cache.find(buffer->getId());
482 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700483 ALOGV("Cache hit!");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800484 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700485 }
486 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800487
488 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
489 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
490 surfaceTextureRef->setTexture(
491 new AutoBackendTexture(mGrContext.get(), buffer->toAHardwareBuffer(), true));
492 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700493 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800494 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700495 }
496 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800497
498 sk_sp<SkSurface> surface =
499 surfaceTextureRef->getTexture()->getOrCreateSurface(mUseColorManagement
500 ? display.outputDataspace
501 : ui::Dataspace::SRGB,
502 mGrContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700503
Ana Krulec70d15b1b2020-12-01 10:05:15 -0800504 SkCanvas* canvas = mCapture.tryCapture(surface.get());
Ana Krulec6eab17a2020-12-09 15:52:36 -0800505 if (canvas == nullptr) {
506 ALOGE("Cannot acquire canvas from Skia.");
507 return BAD_VALUE;
508 }
Alec Mouri678245d2020-09-30 16:58:23 -0700509 // Clear the entire canvas with a transparent black to prevent ghost images.
510 canvas->clear(SK_ColorTRANSPARENT);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700511 canvas->save();
John Reck67b1e2b2020-08-26 13:17:24 -0700512
Ana Krulec6eab17a2020-12-09 15:52:36 -0800513 if (mCapture.isCaptureRunning()) {
514 // Record display settings when capture is running.
515 std::stringstream displaySettings;
516 PrintTo(display, &displaySettings);
517 // Store the DisplaySettings in additional information.
518 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
519 SkData::MakeWithCString(displaySettings.str().c_str()));
520 }
521
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700522 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
523 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
524 // displays might have different scaling when compared to the physical screen.
Alec Mouri678245d2020-09-30 16:58:23 -0700525
526 canvas->clipRect(getSkRect(display.physicalDisplay));
Galia Peychevaf7889b32020-11-25 22:22:40 +0100527 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700528
529 const auto clipWidth = display.clip.width();
530 const auto clipHeight = display.clip.height();
531 auto rotatedClipWidth = clipWidth;
532 auto rotatedClipHeight = clipHeight;
533 // Scale is contingent on the rotation result.
534 if (display.orientation & ui::Transform::ROT_90) {
535 std::swap(rotatedClipWidth, rotatedClipHeight);
536 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700537 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700538 static_cast<SkScalar>(rotatedClipWidth);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700539 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700540 static_cast<SkScalar>(rotatedClipHeight);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100541 canvas->scale(scaleX, scaleY);
Alec Mouri678245d2020-09-30 16:58:23 -0700542
543 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
544 // back so that the top left corner of the clip is at (0, 0).
Galia Peychevaf7889b32020-11-25 22:22:40 +0100545 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
546 canvas->rotate(toDegrees(display.orientation));
547 canvas->translate(-clipWidth / 2, -clipHeight / 2);
548 canvas->translate(-display.clip.left, -display.clip.top);
John Reck67b1e2b2020-08-26 13:17:24 -0700549 for (const auto& layer : layers) {
Galia Peychevaf7889b32020-11-25 22:22:40 +0100550 canvas->save();
551
Ana Krulec6eab17a2020-12-09 15:52:36 -0800552 if (mCapture.isCaptureRunning()) {
553 // Record the name of the layer if the capture is running.
554 std::stringstream layerSettings;
555 PrintTo(*layer, &layerSettings);
556 // Store the LayerSettings in additional information.
557 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
558 SkData::MakeWithCString(layerSettings.str().c_str()));
559 }
560
Galia Peychevaf7889b32020-11-25 22:22:40 +0100561 // Layers have a local transform that should be applied to them
562 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100563
Lucas Dupin21f348e2020-09-16 17:31:26 -0700564 SkPaint paint;
565 const auto& bounds = layer->geometry.boundaries;
Lucas Dupin3f11e922020-09-22 17:31:04 -0700566 const auto dest = getSkRect(bounds);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100567 const auto layerRect = canvas->getTotalMatrix().mapRect(dest);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700568 std::unordered_map<uint32_t, sk_sp<SkSurface>> cachedBlurs;
Lucas Dupinc3800b82020-10-02 16:24:48 -0700569 if (mBlurFilter) {
570 if (layer->backgroundBlurRadius > 0) {
571 ATRACE_NAME("BackgroundBlur");
Galia Peycheva80116e52020-11-06 11:57:25 +0100572 auto blurredSurface = mBlurFilter->generate(canvas, surface,
573 layer->backgroundBlurRadius, layerRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700574 cachedBlurs[layer->backgroundBlurRadius] = blurredSurface;
Galia Peycheva80116e52020-11-06 11:57:25 +0100575
Galia Peychevaf7889b32020-11-25 22:22:40 +0100576 drawBlurRegion(canvas, getBlurRegion(layer), layerRect, blurredSurface);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700577 }
578 if (layer->blurRegions.size() > 0) {
579 for (auto region : layer->blurRegions) {
580 if (cachedBlurs[region.blurRadius]) {
581 continue;
582 }
583 ATRACE_NAME("BlurRegion");
Galia Peycheva6c460652020-11-03 19:42:42 +0100584 auto blurredSurface =
585 mBlurFilter->generate(canvas, surface, region.blurRadius, layerRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700586 cachedBlurs[region.blurRadius] = blurredSurface;
587 }
588 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700589 }
590
John Reck67b1e2b2020-08-26 13:17:24 -0700591 if (layer->source.buffer.buffer) {
592 ATRACE_NAME("DrawImage");
593 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800594 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
595 auto iter = mTextureCache.find(item.buffer->getId());
596 if (iter != mTextureCache.end()) {
597 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700598 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800599 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
600 imageTextureRef->setTexture(new AutoBackendTexture(mGrContext.get(),
601 item.buffer->toAHardwareBuffer(),
602 false));
603 mTextureCache.insert({buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700604 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800605
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800606 sk_sp<SkImage> image =
607 imageTextureRef->getTexture()
608 ->makeImage(mUseColorManagement
Alec Mouri1a4d0642020-11-13 17:42:01 -0800609 ? (needsLinearEffect(layer->colorTransform,
610 layer->sourceDataspace,
611 display.outputDataspace)
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800612 // If we need to map to linear space,
613 // then mark the source image with the
614 // same colorspace as the destination
615 // surface so that Skia's color
616 // management is a no-op.
617 ? display.outputDataspace
618 : layer->sourceDataspace)
619 : ui::Dataspace::SRGB,
620 item.isOpaque ? kOpaque_SkAlphaType
621 : (item.usePremultipliedAlpha
622 ? kPremul_SkAlphaType
623 : kUnpremul_SkAlphaType),
624 mGrContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700625
626 auto texMatrix = getSkM44(item.textureTransform).asM33();
627 // textureTansform was intended to be passed directly into a shader, so when
628 // building the total matrix with the textureTransform we need to first
629 // normalize it, then apply the textureTransform, then scale back up.
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800630 texMatrix.preScale(1.0f / bounds.getWidth(), 1.0f / bounds.getHeight());
631 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700632
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800633 SkMatrix matrix;
634 if (!texMatrix.invert(&matrix)) {
635 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700636 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800637 // The shader does not respect the translation, so we add it to the texture
638 // transform for the SkImage. This will make sure that the correct layer contents
639 // are drawn in the correct part of the screen.
640 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700641
Ana Krulecb7b28b22020-11-23 14:48:58 -0800642 sk_sp<SkShader> shader;
643
644 if (layer->source.buffer.useTextureFiltering) {
645 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
646 SkSamplingOptions(
647 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
648 &matrix);
649 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500650 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800651 }
Alec Mouri029d1952020-10-12 10:37:08 -0700652
Ana Krulec47814212021-01-06 19:00:10 -0800653 paint.setShader(
654 createRuntimeEffectShader(shader, layer, display,
655 !item.isOpaque && item.usePremultipliedAlpha));
Alec Mouric16a77d2020-11-13 13:20:11 -0800656
Ana Krulec1768bd22020-11-23 14:51:31 -0800657 // Make sure to take into the account the alpha set on the layer.
658 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700659 } else {
660 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700661 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800662 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
663 .fG = color.g,
664 .fB = color.b,
665 layer->alpha},
666 nullptr);
667 paint.setShader(createRuntimeEffectShader(shader, layer, display,
668 /* undoPremultipliedAlpha */ false));
John Reck67b1e2b2020-08-26 13:17:24 -0700669 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700670
Alec Mouri4ce5ec02021-01-07 17:33:21 -0800671 sk_sp<SkColorFilter> filter =
672 SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
673
674 // Handle opaque images - it's a little nonstandard how we do this.
675 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
676 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
677 // The important language is that when isOpaque is set, opacity is not sampled from the
678 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
679 // here's the conundrum:
680 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated as
681 // an internal hint - composition is undefined when there are alpha bits present.
682 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888 buffers,
683 // i.e., treating them as RGBx8888 instead. But we can't do the same for RGBA1010102 because
684 // RGBx1010102 is not supported as a pixel layout for SkImages. It's also not clear what to
685 // use for F16 either, and lying about the pixel layout is a bit of a hack anyways.
686 // 3. We can't change the blendmode to src, because while this satisfies the requirement for
687 // ignoring the alpha channel, it doesn't quite satisfy the blending requirement because
688 // src always clobbers the destination content.
689 //
690 // So, what we do here instead is an additive blend mode where we compose the input image
691 // with a solid black. This might need to be reassess if this does not support FP16
692 // incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
693 if (layer->source.buffer.buffer && layer->source.buffer.isOpaque) {
694 filter = SkColorFilters::Compose(filter,
695 SkColorFilters::Blend(SK_ColorBLACK,
696 SkBlendMode::kPlus));
697 }
698
699 paint.setColorFilter(filter);
Alec Mourib34f0b72020-10-02 13:18:34 -0700700
Lucas Dupinc3800b82020-10-02 16:24:48 -0700701 for (const auto effectRegion : layer->blurRegions) {
Galia Peychevaf7889b32020-11-25 22:22:40 +0100702 drawBlurRegion(canvas, effectRegion, layerRect, cachedBlurs[effectRegion.blurRadius]);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700703 }
704
Lucas Dupin3f11e922020-09-22 17:31:04 -0700705 if (layer->shadow.length > 0) {
706 const auto rect = layer->geometry.roundedCornersRadius > 0
707 ? getSkRect(layer->geometry.roundedCornersCrop)
708 : dest;
709 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800710 } else {
711 // Shadows are assumed to live only on their own layer - it's not valid
712 // to draw the boundary retangles when there is already a caster shadow
713 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
714 // composition - using a well-defined invalid color is long-term less error-prone.
715 // Push the clipRRect onto the clip stack. Draw the image. Pop the clip.
716 if (layer->geometry.roundedCornersRadius > 0) {
717 canvas->clipRRect(getRoundedRect(layer), true);
718 }
719 canvas->drawRect(dest, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700720 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700721 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700722 }
Ana Krulec70d15b1b2020-12-01 10:05:15 -0800723 canvas->restore();
724 mCapture.endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700725 {
726 ATRACE_NAME("flush surface");
727 surface->flush();
728 }
729
730 if (drawFence != nullptr) {
731 *drawFence = flush();
732 }
733
734 // If flush failed or we don't support native fences, we need to force the
735 // gl command stream to be executed.
736 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
737 if (requireSync) {
738 ATRACE_BEGIN("Submit(sync=true)");
739 } else {
740 ATRACE_BEGIN("Submit(sync=false)");
741 }
Lucas Dupind508e472020-11-04 04:32:06 +0000742 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -0700743 ATRACE_END();
744 if (!success) {
745 ALOGE("Failed to flush RenderEngine commands");
746 // Chances are, something illegal happened (either the caller passed
747 // us bad parameters, or we messed up our shader generation).
748 return INVALID_OPERATION;
749 }
750
751 // checkErrors();
752 return NO_ERROR;
753}
754
Lucas Dupin3f11e922020-09-22 17:31:04 -0700755inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
756 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
757}
758
759inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
760 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
761}
762
Lucas Dupin21f348e2020-09-16 17:31:26 -0700763inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800764 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700765 const auto cornerRadius = layer->geometry.roundedCornersRadius;
766 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
767}
768
Galia Peycheva80116e52020-11-06 11:57:25 +0100769inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
770 const auto rect = getSkRect(layer->geometry.boundaries);
771 const auto cornersRadius = layer->geometry.roundedCornersRadius;
772 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
773 .cornerRadiusTL = cornersRadius,
774 .cornerRadiusTR = cornersRadius,
775 .cornerRadiusBL = cornersRadius,
776 .cornerRadiusBR = cornersRadius,
777 .alpha = 1,
778 .left = static_cast<int>(rect.fLeft),
779 .top = static_cast<int>(rect.fTop),
780 .right = static_cast<int>(rect.fRight),
781 .bottom = static_cast<int>(rect.fBottom)};
782}
783
Lucas Dupin3f11e922020-09-22 17:31:04 -0700784inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
785 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
786}
787
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700788inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
789 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
790 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
791 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
792 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
793}
794
Lucas Dupin3f11e922020-09-22 17:31:04 -0700795inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
796 return SkPoint3::Make(vector.x, vector.y, vector.z);
797}
798
John Reck67b1e2b2020-08-26 13:17:24 -0700799size_t SkiaGLRenderEngine::getMaxTextureSize() const {
800 return mGrContext->maxTextureSize();
801}
802
803size_t SkiaGLRenderEngine::getMaxViewportDims() const {
804 return mGrContext->maxRenderTargetSize();
805}
806
Lucas Dupin3f11e922020-09-22 17:31:04 -0700807void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
808 const ShadowSettings& settings) {
809 ATRACE_CALL();
810 const float casterZ = settings.length / 2.0f;
811 const auto shadowShape = cornerRadius > 0
812 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
813 : SkPath::Rect(casterRect);
814 const auto flags =
815 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
816
817 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
818 getSkPoint3(settings.lightPos), settings.lightRadius,
819 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
820 flags);
821}
822
Lucas Dupinc3800b82020-10-02 16:24:48 -0700823void SkiaGLRenderEngine::drawBlurRegion(SkCanvas* canvas, const BlurRegion& effectRegion,
Galia Peychevaf7889b32020-11-25 22:22:40 +0100824 const SkRect& layerRect, sk_sp<SkSurface> blurredSurface) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700825 ATRACE_CALL();
Galia Peycheva80116e52020-11-06 11:57:25 +0100826
Lucas Dupinc3800b82020-10-02 16:24:48 -0700827 SkPaint paint;
Lyn Han1bdedb32020-11-23 20:33:57 +0000828 paint.setAlpha(static_cast<int>(effectRegion.alpha * 255));
Robin Leef180f412020-12-07 02:51:41 +0100829 const auto matrix = getBlurShaderTransform(canvas, layerRect);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100830 paint.setShader(blurredSurface->makeImageSnapshot()->makeShader(
Robin Leef180f412020-12-07 02:51:41 +0100831 SkTileMode::kClamp,
832 SkTileMode::kClamp,
833 SkSamplingOptions({SkFilterMode::kLinear, SkMipmapMode::kNone}),
834 &matrix));
Lucas Dupinc3800b82020-10-02 16:24:48 -0700835
Galia Peycheva80116e52020-11-06 11:57:25 +0100836 auto rect = SkRect::MakeLTRB(effectRegion.left, effectRegion.top, effectRegion.right,
837 effectRegion.bottom);
Galia Peycheva80116e52020-11-06 11:57:25 +0100838
Lucas Dupinc3800b82020-10-02 16:24:48 -0700839 if (effectRegion.cornerRadiusTL > 0 || effectRegion.cornerRadiusTR > 0 ||
840 effectRegion.cornerRadiusBL > 0 || effectRegion.cornerRadiusBR > 0) {
841 const SkVector radii[4] =
842 {SkVector::Make(effectRegion.cornerRadiusTL, effectRegion.cornerRadiusTL),
843 SkVector::Make(effectRegion.cornerRadiusTR, effectRegion.cornerRadiusTR),
844 SkVector::Make(effectRegion.cornerRadiusBL, effectRegion.cornerRadiusBL),
845 SkVector::Make(effectRegion.cornerRadiusBR, effectRegion.cornerRadiusBR)};
846 SkRRect roundedRect;
847 roundedRect.setRectRadii(rect, radii);
848 canvas->drawRRect(roundedRect, paint);
849 } else {
850 canvas->drawRect(rect, paint);
851 }
852}
853
Galia Peychevaf7889b32020-11-25 22:22:40 +0100854SkMatrix SkiaGLRenderEngine::getBlurShaderTransform(const SkCanvas* canvas,
855 const SkRect& layerRect) {
856 // 1. Apply the blur shader matrix, which scales up the blured surface to its real size
857 auto matrix = mBlurFilter->getShaderMatrix();
858 // 2. Since the blurred surface has the size of the layer, we align it with the
859 // top left corner of the layer position.
860 matrix.postConcat(SkMatrix::Translate(layerRect.fLeft, layerRect.fTop));
861 // 3. Finally, apply the inverse canvas matrix. The snapshot made in the BlurFilter is in the
862 // original surface orientation. The inverse matrix has to be applied to align the blur
863 // surface with the current orientation/position of the canvas.
864 SkMatrix drawInverse;
865 if (canvas->getTotalMatrix().invert(&drawInverse)) {
866 matrix.postConcat(drawInverse);
867 }
868
869 return matrix;
870}
871
John Reck67b1e2b2020-08-26 13:17:24 -0700872EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -0800873 EGLContext shareContext,
874 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -0700875 Protection protection) {
876 EGLint renderableType = 0;
877 if (config == EGL_NO_CONFIG_KHR) {
878 renderableType = EGL_OPENGL_ES3_BIT;
879 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
880 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
881 }
882 EGLint contextClientVersion = 0;
883 if (renderableType & EGL_OPENGL_ES3_BIT) {
884 contextClientVersion = 3;
885 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
886 contextClientVersion = 2;
887 } else if (renderableType & EGL_OPENGL_ES_BIT) {
888 contextClientVersion = 1;
889 } else {
890 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
891 }
892
893 std::vector<EGLint> contextAttributes;
894 contextAttributes.reserve(7);
895 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
896 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -0800897 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -0700898 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -0800899 switch (*contextPriority) {
900 case ContextPriority::REALTIME:
901 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
902 break;
903 case ContextPriority::MEDIUM:
904 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
905 break;
906 case ContextPriority::LOW:
907 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
908 break;
909 case ContextPriority::HIGH:
910 default:
911 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
912 break;
913 }
John Reck67b1e2b2020-08-26 13:17:24 -0700914 }
915 if (protection == Protection::PROTECTED) {
916 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
917 contextAttributes.push_back(EGL_TRUE);
918 }
919 contextAttributes.push_back(EGL_NONE);
920
921 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
922
923 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
924 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
925 // EGL_NO_CONTEXT so that we can abort.
926 if (config != EGL_NO_CONFIG_KHR) {
927 return context;
928 }
929 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
930 // should try to fall back to GLES 2.
931 contextAttributes[1] = 2;
932 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
933 }
934
935 return context;
936}
937
Alec Mourid6f09462020-12-07 11:18:17 -0800938std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
939 const RenderEngineCreationArgs& args) {
940 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
941 return std::nullopt;
942 }
943
944 switch (args.contextPriority) {
945 case RenderEngine::ContextPriority::REALTIME:
946 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
947 return RenderEngine::ContextPriority::REALTIME;
948 } else {
949 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
950 return RenderEngine::ContextPriority::HIGH;
951 }
952 case RenderEngine::ContextPriority::HIGH:
953 case RenderEngine::ContextPriority::MEDIUM:
954 case RenderEngine::ContextPriority::LOW:
955 return args.contextPriority;
956 default:
957 return std::nullopt;
958 }
959}
960
John Reck67b1e2b2020-08-26 13:17:24 -0700961EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
962 EGLConfig config, int hwcFormat,
963 Protection protection) {
964 EGLConfig placeholderConfig = config;
965 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
966 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
967 }
968 std::vector<EGLint> attributes;
969 attributes.reserve(7);
970 attributes.push_back(EGL_WIDTH);
971 attributes.push_back(1);
972 attributes.push_back(EGL_HEIGHT);
973 attributes.push_back(1);
974 if (protection == Protection::PROTECTED) {
975 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
976 attributes.push_back(EGL_TRUE);
977 }
978 attributes.push_back(EGL_NONE);
979
980 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
981}
982
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800983void SkiaGLRenderEngine::cleanFramebufferCache() {}
John Reck67b1e2b2020-08-26 13:17:24 -0700984
Alec Mourid6f09462020-12-07 11:18:17 -0800985int SkiaGLRenderEngine::getContextPriority() {
986 int value;
987 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
988 return value;
989}
990
John Reck67b1e2b2020-08-26 13:17:24 -0700991} // namespace skia
992} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +0100993} // namespace android