blob: dc04f69dc60397b39997926846124102a2012ed7 [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>
Alec Mouric0aae732021-01-12 13:32:18 -080033#include <SkRegion.h>
Lucas Dupin3f11e922020-09-22 17:31:04 -070034#include <SkShadowUtils.h>
John Reck67b1e2b2020-08-26 13:17:24 -070035#include <SkSurface.h>
Alec Mourib5777452020-09-28 11:32:42 -070036#include <gl/GrGLInterface.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080037#include <sync/sync.h>
38#include <ui/BlurRegion.h>
39#include <ui/GraphicBuffer.h>
40#include <utils/Trace.h>
Alec Mourib5777452020-09-28 11:32:42 -070041
42#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080043#include <cstdint>
44#include <memory>
45
46#include "../gl/GLExtensions.h"
Alec Mouric0aae732021-01-12 13:32:18 -080047#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080048#include "SkBlendMode.h"
49#include "SkImageInfo.h"
50#include "filters/BlurFilter.h"
51#include "filters/LinearEffect.h"
52#include "log/log_main.h"
53#include "skia/debug/SkiaCapture.h"
54#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070055
John Reck67b1e2b2020-08-26 13:17:24 -070056bool checkGlError(const char* op, int lineNumber);
57
58namespace android {
59namespace renderengine {
60namespace skia {
61
62static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
63 EGLint wanted, EGLConfig* outConfig) {
64 EGLint numConfigs = -1, n = 0;
65 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
66 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
67 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
68 configs.resize(n);
69
70 if (!configs.empty()) {
71 if (attribute != EGL_NONE) {
72 for (EGLConfig config : configs) {
73 EGLint value = 0;
74 eglGetConfigAttrib(dpy, config, attribute, &value);
75 if (wanted == value) {
76 *outConfig = config;
77 return NO_ERROR;
78 }
79 }
80 } else {
81 // just pick the first one
82 *outConfig = configs[0];
83 return NO_ERROR;
84 }
85 }
86
87 return NAME_NOT_FOUND;
88}
89
90static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
91 EGLConfig* config) {
92 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
93 // it is to be used with WIFI displays
94 status_t err;
95 EGLint wantedAttribute;
96 EGLint wantedAttributeValue;
97
98 std::vector<EGLint> attribs;
99 if (renderableType) {
100 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
101 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
102
103 // Default to 8 bits per channel.
104 const EGLint tmpAttribs[] = {
105 EGL_RENDERABLE_TYPE,
106 renderableType,
107 EGL_RECORDABLE_ANDROID,
108 EGL_TRUE,
109 EGL_SURFACE_TYPE,
110 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
111 EGL_FRAMEBUFFER_TARGET_ANDROID,
112 EGL_TRUE,
113 EGL_RED_SIZE,
114 is1010102 ? 10 : 8,
115 EGL_GREEN_SIZE,
116 is1010102 ? 10 : 8,
117 EGL_BLUE_SIZE,
118 is1010102 ? 10 : 8,
119 EGL_ALPHA_SIZE,
120 is1010102 ? 2 : 8,
121 EGL_NONE,
122 };
123 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
124 std::back_inserter(attribs));
125 wantedAttribute = EGL_NONE;
126 wantedAttributeValue = EGL_NONE;
127 } else {
128 // if no renderable type specified, fallback to a simplified query
129 wantedAttribute = EGL_NATIVE_VISUAL_ID;
130 wantedAttributeValue = format;
131 }
132
133 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
134 config);
135 if (err == NO_ERROR) {
136 EGLint caveat;
137 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
138 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
139 }
140
141 return err;
142}
143
144std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
145 const RenderEngineCreationArgs& args) {
146 // initialize EGL for the default display
147 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
148 if (!eglInitialize(display, nullptr, nullptr)) {
149 LOG_ALWAYS_FATAL("failed to initialize EGL");
150 }
151
Yiwei Zhange2650962020-12-01 23:27:58 +0000152 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700153 if (!eglVersion) {
154 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000155 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700156 }
157
Yiwei Zhange2650962020-12-01 23:27:58 +0000158 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700159 if (!eglExtensions) {
160 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000161 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700162 }
163
164 auto& extensions = gl::GLExtensions::getInstance();
165 extensions.initWithEGLStrings(eglVersion, eglExtensions);
166
167 // The code assumes that ES2 or later is available if this extension is
168 // supported.
169 EGLConfig config = EGL_NO_CONFIG_KHR;
170 if (!extensions.hasNoConfigContext()) {
171 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
172 }
173
John Reck67b1e2b2020-08-26 13:17:24 -0700174 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800175 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700176 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800177 protectedContext =
178 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700179 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
180 }
181
Alec Mourid6f09462020-12-07 11:18:17 -0800182 EGLContext ctxt =
183 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700184
185 // if can't create a GL context, we can only abort.
186 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
187
188 EGLSurface placeholder = EGL_NO_SURFACE;
189 if (!extensions.hasSurfacelessContext()) {
190 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
191 Protection::UNPROTECTED);
192 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
193 }
194 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
195 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
196 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
197 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
198
199 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
200 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
201 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
202 Protection::PROTECTED);
203 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
204 "can't create protected placeholder pbuffer");
205 }
206
207 // initialize the renderer while GL is current
208 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000209 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
210 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700211
212 ALOGI("OpenGL ES informations:");
213 ALOGI("vendor : %s", extensions.getVendor());
214 ALOGI("renderer : %s", extensions.getRenderer());
215 ALOGI("version : %s", extensions.getVersion());
216 ALOGI("extensions: %s", extensions.getExtensions());
217 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
218 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
219
220 return engine;
221}
222
223EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
224 status_t err;
225 EGLConfig config;
226
227 // First try to get an ES3 config
228 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
229 if (err != NO_ERROR) {
230 // If ES3 fails, try to get an ES2 config
231 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
232 if (err != NO_ERROR) {
233 // If ES2 still doesn't work, probably because we're on the emulator.
234 // try a simplified query
235 ALOGW("no suitable EGLConfig found, trying a simpler query");
236 err = selectEGLConfig(display, format, 0, &config);
237 if (err != NO_ERROR) {
238 // this EGL is too lame for android
239 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
240 }
241 }
242 }
243
244 if (logConfig) {
245 // print some debugging info
246 EGLint r, g, b, a;
247 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
248 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
249 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
250 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
251 ALOGI("EGL information:");
252 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
253 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
254 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
255 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
256 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
257 }
258
259 return config;
260}
261
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700262SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000263 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700264 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri081be4c2020-09-16 10:24:47 -0700265 : mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700266 mEGLContext(ctxt),
267 mPlaceholderSurface(placeholder),
268 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700269 mProtectedPlaceholderSurface(protectedPlaceholder),
270 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700271 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
272 LOG_ALWAYS_FATAL_IF(!glInterface.get());
273
274 GrContextOptions options;
275 options.fPreferExternalImagesOverES3 = true;
276 options.fDisableDistanceFieldPaths = true;
Lucas Dupind508e472020-11-04 04:32:06 +0000277 mGrContext = GrDirectContext::MakeGL(glInterface, options);
278 if (useProtectedContext(true)) {
279 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
280 useProtectedContext(false);
281 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700282
283 if (args.supportsBackgroundBlur) {
284 mBlurFilter = new BlurFilter();
285 }
Alec Mouric0aae732021-01-12 13:32:18 -0800286 mCapture = std::make_unique<SkiaCapture>();
287}
288
289SkiaGLRenderEngine::~SkiaGLRenderEngine() {
290 std::lock_guard<std::mutex> lock(mRenderingMutex);
291 mRuntimeEffects.clear();
292 mProtectedTextureCache.clear();
293 mTextureCache.clear();
294
295 if (mBlurFilter) {
296 delete mBlurFilter;
297 }
298
299 mCapture = nullptr;
300
301 mGrContext->flushAndSubmit(true);
302 mGrContext->abandonContext();
303
304 if (mProtectedGrContext) {
305 mProtectedGrContext->flushAndSubmit(true);
306 mProtectedGrContext->abandonContext();
307 }
308
309 if (mPlaceholderSurface != EGL_NO_SURFACE) {
310 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
311 }
312 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
313 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
314 }
315 if (mEGLContext != EGL_NO_CONTEXT) {
316 eglDestroyContext(mEGLDisplay, mEGLContext);
317 }
318 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
319 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
320 }
321 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
322 eglTerminate(mEGLDisplay);
323 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700324}
325
Lucas Dupind508e472020-11-04 04:32:06 +0000326bool SkiaGLRenderEngine::supportsProtectedContent() const {
327 return mProtectedEGLContext != EGL_NO_CONTEXT;
328}
329
330bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
331 if (useProtectedContext == mInProtectedContext) {
332 return true;
333 }
334 if (useProtectedContext && supportsProtectedContent()) {
335 return false;
336 }
337 const EGLSurface surface =
338 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
339 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
340 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800341
Lucas Dupind508e472020-11-04 04:32:06 +0000342 if (success) {
343 mInProtectedContext = useProtectedContext;
344 }
345 return success;
346}
347
John Reck67b1e2b2020-08-26 13:17:24 -0700348base::unique_fd SkiaGLRenderEngine::flush() {
349 ATRACE_CALL();
350 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
351 return base::unique_fd();
352 }
353
354 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
355 if (sync == EGL_NO_SYNC_KHR) {
356 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
357 return base::unique_fd();
358 }
359
360 // native fence fd will not be populated until flush() is done.
361 glFlush();
362
363 // get the fence fd
364 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
365 eglDestroySyncKHR(mEGLDisplay, sync);
366 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
367 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
368 }
369
370 return fenceFd;
371}
372
373bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
374 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
375 !gl::GLExtensions::getInstance().hasWaitSync()) {
376 return false;
377 }
378
379 // release the fd and transfer the ownership to EGLSync
380 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
381 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
382 if (sync == EGL_NO_SYNC_KHR) {
383 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
384 return false;
385 }
386
387 // XXX: The spec draft is inconsistent as to whether this should return an
388 // EGLint or void. Ignore the return value for now, as it's not strictly
389 // needed.
390 eglWaitSyncKHR(mEGLDisplay, sync, 0);
391 EGLint error = eglGetError();
392 eglDestroySyncKHR(mEGLDisplay, sync);
393 if (error != EGL_SUCCESS) {
394 ALOGE("failed to wait for EGL native fence sync: %#x", error);
395 return false;
396 }
397
398 return true;
399}
400
401static bool hasUsage(const AHardwareBuffer_Desc& desc, uint64_t usage) {
402 return !!(desc.usage & usage);
403}
404
Alec Mouri678245d2020-09-30 16:58:23 -0700405static float toDegrees(uint32_t transform) {
406 switch (transform) {
407 case ui::Transform::ROT_90:
408 return 90.0;
409 case ui::Transform::ROT_180:
410 return 180.0;
411 case ui::Transform::ROT_270:
412 return 270.0;
413 default:
414 return 0.0;
415 }
416}
417
Alec Mourib34f0b72020-10-02 13:18:34 -0700418static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
419 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
420 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
421 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
422 matrix[3][3], 0);
423}
424
Alec Mouri029d1952020-10-12 10:37:08 -0700425static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
426 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
427 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
428
429 // Treat unsupported dataspaces as srgb
430 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
431 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
432 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
433 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
434 }
435
436 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
437 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
438 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
439 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
440 }
441
442 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
443 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
444 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
445 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
446
447 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
448 sourceTransfer != destTransfer;
449}
450
Alec Mouri1a4d0642020-11-13 17:42:01 -0800451static bool needsLinearEffect(const mat4& colorTransform, ui::Dataspace sourceDataspace,
452 ui::Dataspace destinationDataspace) {
453 return colorTransform != mat4() || needsToneMapping(sourceDataspace, destinationDataspace);
454}
455
John Reck67b1e2b2020-08-26 13:17:24 -0700456void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
457 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800458 mTextureCache.erase(bufferId);
459 mProtectedTextureCache.erase(bufferId);
John Reck67b1e2b2020-08-26 13:17:24 -0700460}
461
Ana Krulec47814212021-01-06 19:00:10 -0800462sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
463 const LayerSettings* layer,
464 const DisplaySettings& display,
465 bool undoPremultipliedAlpha) {
466 if (mUseColorManagement &&
467 needsLinearEffect(layer->colorTransform, layer->sourceDataspace, display.outputDataspace)) {
468 LinearEffect effect = LinearEffect{.inputDataspace = layer->sourceDataspace,
469 .outputDataspace = display.outputDataspace,
470 .undoPremultipliedAlpha = undoPremultipliedAlpha};
471
472 auto effectIter = mRuntimeEffects.find(effect);
473 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
474 if (effectIter == mRuntimeEffects.end()) {
475 runtimeEffect = buildRuntimeEffect(effect);
476 mRuntimeEffects.insert({effect, runtimeEffect});
477 } else {
478 runtimeEffect = effectIter->second;
479 }
480 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
481 display.maxLuminance,
482 layer->source.buffer.maxMasteringLuminance,
483 layer->source.buffer.maxContentLuminance);
484 }
485 return shader;
486}
487
John Reck67b1e2b2020-08-26 13:17:24 -0700488status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
489 const std::vector<const LayerSettings*>& layers,
490 const sp<GraphicBuffer>& buffer,
491 const bool useFramebufferCache,
492 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
493 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800494
John Reck67b1e2b2020-08-26 13:17:24 -0700495 std::lock_guard<std::mutex> lock(mRenderingMutex);
496 if (layers.empty()) {
497 ALOGV("Drawing empty layer stack");
498 return NO_ERROR;
499 }
500
501 if (bufferFence.get() >= 0) {
502 // Duplicate the fence for passing to waitFence.
503 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
504 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
505 ATRACE_NAME("Waiting before draw");
506 sync_wait(bufferFence.get(), -1);
507 }
508 }
509 if (buffer == nullptr) {
510 ALOGE("No output buffer provided. Aborting GPU composition.");
511 return BAD_VALUE;
512 }
513
Lucas Dupind508e472020-11-04 04:32:06 +0000514 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800515 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700516 AHardwareBuffer_Desc bufferDesc;
517 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700518 LOG_ALWAYS_FATAL_IF(!hasUsage(bufferDesc, AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE),
519 "missing usage");
520
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800521 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700522 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000523 auto iter = cache.find(buffer->getId());
524 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700525 ALOGV("Cache hit!");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800526 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700527 }
528 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800529
530 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
531 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
532 surfaceTextureRef->setTexture(
Alec Mouric0aae732021-01-12 13:32:18 -0800533 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), true));
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800534 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700535 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800536 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700537 }
538 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800539
540 sk_sp<SkSurface> surface =
541 surfaceTextureRef->getTexture()->getOrCreateSurface(mUseColorManagement
542 ? display.outputDataspace
Alec Mouric0aae732021-01-12 13:32:18 -0800543 : ui::Dataspace::UNKNOWN,
544 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700545
Alec Mouric0aae732021-01-12 13:32:18 -0800546 SkCanvas* canvas = mCapture->tryCapture(surface.get());
Ana Krulec6eab17a2020-12-09 15:52:36 -0800547 if (canvas == nullptr) {
548 ALOGE("Cannot acquire canvas from Skia.");
549 return BAD_VALUE;
550 }
Alec Mouri678245d2020-09-30 16:58:23 -0700551 // Clear the entire canvas with a transparent black to prevent ghost images.
552 canvas->clear(SK_ColorTRANSPARENT);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700553 canvas->save();
John Reck67b1e2b2020-08-26 13:17:24 -0700554
Alec Mouric0aae732021-01-12 13:32:18 -0800555 if (mCapture->isCaptureRunning()) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800556 // Record display settings when capture is running.
557 std::stringstream displaySettings;
558 PrintTo(display, &displaySettings);
559 // Store the DisplaySettings in additional information.
560 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
561 SkData::MakeWithCString(displaySettings.str().c_str()));
562 }
563
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700564 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
565 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
566 // displays might have different scaling when compared to the physical screen.
Alec Mouri678245d2020-09-30 16:58:23 -0700567
568 canvas->clipRect(getSkRect(display.physicalDisplay));
Galia Peychevaf7889b32020-11-25 22:22:40 +0100569 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700570
571 const auto clipWidth = display.clip.width();
572 const auto clipHeight = display.clip.height();
573 auto rotatedClipWidth = clipWidth;
574 auto rotatedClipHeight = clipHeight;
575 // Scale is contingent on the rotation result.
576 if (display.orientation & ui::Transform::ROT_90) {
577 std::swap(rotatedClipWidth, rotatedClipHeight);
578 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700579 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700580 static_cast<SkScalar>(rotatedClipWidth);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700581 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700582 static_cast<SkScalar>(rotatedClipHeight);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100583 canvas->scale(scaleX, scaleY);
Alec Mouri678245d2020-09-30 16:58:23 -0700584
585 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
586 // back so that the top left corner of the clip is at (0, 0).
Galia Peychevaf7889b32020-11-25 22:22:40 +0100587 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
588 canvas->rotate(toDegrees(display.orientation));
589 canvas->translate(-clipWidth / 2, -clipHeight / 2);
590 canvas->translate(-display.clip.left, -display.clip.top);
Alec Mouric0aae732021-01-12 13:32:18 -0800591
592 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
593 // view is still on-screen. The clear region could be re-specified as a black color layer,
594 // however.
595 if (!display.clearRegion.isEmpty()) {
596 size_t numRects = 0;
597 Rect const* rects = display.clearRegion.getArray(&numRects);
598 SkIRect skRects[numRects];
599 for (int i = 0; i < numRects; ++i) {
600 skRects[i] =
601 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
602 }
603 SkRegion clearRegion;
604 SkPaint paint;
605 sk_sp<SkShader> shader =
606 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
607 toSkColorSpace(mUseColorManagement ? display.outputDataspace
608 : ui::Dataspace::UNKNOWN));
609 paint.setShader(shader);
610 clearRegion.setRects(skRects, numRects);
611 canvas->drawRegion(clearRegion, paint);
612 }
613
John Reck67b1e2b2020-08-26 13:17:24 -0700614 for (const auto& layer : layers) {
Galia Peychevaf7889b32020-11-25 22:22:40 +0100615 canvas->save();
616
Alec Mouric0aae732021-01-12 13:32:18 -0800617 if (mCapture->isCaptureRunning()) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800618 // Record the name of the layer if the capture is running.
619 std::stringstream layerSettings;
620 PrintTo(*layer, &layerSettings);
621 // Store the LayerSettings in additional information.
622 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
623 SkData::MakeWithCString(layerSettings.str().c_str()));
624 }
625
Galia Peychevaf7889b32020-11-25 22:22:40 +0100626 // Layers have a local transform that should be applied to them
627 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100628
Lucas Dupin21f348e2020-09-16 17:31:26 -0700629 SkPaint paint;
630 const auto& bounds = layer->geometry.boundaries;
Lucas Dupin3f11e922020-09-22 17:31:04 -0700631 const auto dest = getSkRect(bounds);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100632 const auto layerRect = canvas->getTotalMatrix().mapRect(dest);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700633 std::unordered_map<uint32_t, sk_sp<SkSurface>> cachedBlurs;
Lucas Dupinc3800b82020-10-02 16:24:48 -0700634 if (mBlurFilter) {
635 if (layer->backgroundBlurRadius > 0) {
636 ATRACE_NAME("BackgroundBlur");
Galia Peycheva80116e52020-11-06 11:57:25 +0100637 auto blurredSurface = mBlurFilter->generate(canvas, surface,
638 layer->backgroundBlurRadius, layerRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700639 cachedBlurs[layer->backgroundBlurRadius] = blurredSurface;
Galia Peycheva80116e52020-11-06 11:57:25 +0100640
Galia Peychevaf7889b32020-11-25 22:22:40 +0100641 drawBlurRegion(canvas, getBlurRegion(layer), layerRect, blurredSurface);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700642 }
643 if (layer->blurRegions.size() > 0) {
644 for (auto region : layer->blurRegions) {
645 if (cachedBlurs[region.blurRadius]) {
646 continue;
647 }
648 ATRACE_NAME("BlurRegion");
Galia Peycheva6c460652020-11-03 19:42:42 +0100649 auto blurredSurface =
650 mBlurFilter->generate(canvas, surface, region.blurRadius, layerRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700651 cachedBlurs[region.blurRadius] = blurredSurface;
652 }
653 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700654 }
655
Alec Mouric0aae732021-01-12 13:32:18 -0800656 const ui::Dataspace targetDataspace = mUseColorManagement
657 ? (needsLinearEffect(layer->colorTransform, layer->sourceDataspace,
658 display.outputDataspace)
659 // If we need to map to linear space, then mark the source image with the
660 // same colorspace as the destination surface so that Skia's color
661 // management is a no-op.
662 ? display.outputDataspace
663 : layer->sourceDataspace)
664 : ui::Dataspace::UNKNOWN;
665
John Reck67b1e2b2020-08-26 13:17:24 -0700666 if (layer->source.buffer.buffer) {
667 ATRACE_NAME("DrawImage");
668 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800669 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
670 auto iter = mTextureCache.find(item.buffer->getId());
671 if (iter != mTextureCache.end()) {
672 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700673 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800674 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
Alec Mouric0aae732021-01-12 13:32:18 -0800675 imageTextureRef->setTexture(new AutoBackendTexture(grContext.get(),
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800676 item.buffer->toAHardwareBuffer(),
677 false));
Alec Mouric0aae732021-01-12 13:32:18 -0800678 mTextureCache.insert({item.buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700679 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800680
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800681 sk_sp<SkImage> image =
Alec Mouric0aae732021-01-12 13:32:18 -0800682 imageTextureRef->getTexture()->makeImage(targetDataspace,
683 item.usePremultipliedAlpha
684 ? kPremul_SkAlphaType
685 : kUnpremul_SkAlphaType,
686 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700687
688 auto texMatrix = getSkM44(item.textureTransform).asM33();
689 // textureTansform was intended to be passed directly into a shader, so when
690 // building the total matrix with the textureTransform we need to first
691 // normalize it, then apply the textureTransform, then scale back up.
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800692 texMatrix.preScale(1.0f / bounds.getWidth(), 1.0f / bounds.getHeight());
693 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700694
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800695 SkMatrix matrix;
696 if (!texMatrix.invert(&matrix)) {
697 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700698 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800699 // The shader does not respect the translation, so we add it to the texture
700 // transform for the SkImage. This will make sure that the correct layer contents
701 // are drawn in the correct part of the screen.
702 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700703
Ana Krulecb7b28b22020-11-23 14:48:58 -0800704 sk_sp<SkShader> shader;
705
706 if (layer->source.buffer.useTextureFiltering) {
707 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
708 SkSamplingOptions(
709 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
710 &matrix);
711 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500712 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800713 }
Alec Mouri029d1952020-10-12 10:37:08 -0700714
Alec Mouric0aae732021-01-12 13:32:18 -0800715 // Handle opaque images - it's a little nonstandard how we do this.
716 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
717 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
718 // The important language is that when isOpaque is set, opacity is not sampled from the
719 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
720 // here's the conundrum:
721 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
722 // as an internal hint - composition is undefined when there are alpha bits present.
723 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
724 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
725 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
726 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
727 // of a hack anyways.
728 // 3. We can't change the blendmode to src, because while this satisfies the requirement
729 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
730 // because src always clobbers the destination content.
731 //
732 // So, what we do here instead is an additive blend mode where we compose the input
733 // image with a solid black. This might need to be reassess if this does not support
734 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
735 if (item.isOpaque) {
736 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
737 SkShaders::Color(SkColors::kBlack,
738 toSkColorSpace(targetDataspace)));
739 }
740
Ana Krulec47814212021-01-06 19:00:10 -0800741 paint.setShader(
742 createRuntimeEffectShader(shader, layer, display,
743 !item.isOpaque && item.usePremultipliedAlpha));
Ana Krulec1768bd22020-11-23 14:51:31 -0800744 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700745 } else {
746 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700747 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800748 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
749 .fG = color.g,
750 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800751 .fA = layer->alpha},
752 toSkColorSpace(targetDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800753 paint.setShader(createRuntimeEffectShader(shader, layer, display,
754 /* undoPremultipliedAlpha */ false));
John Reck67b1e2b2020-08-26 13:17:24 -0700755 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700756
Alec Mouri4ce5ec02021-01-07 17:33:21 -0800757 sk_sp<SkColorFilter> filter =
758 SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
759
Alec Mouri4ce5ec02021-01-07 17:33:21 -0800760 paint.setColorFilter(filter);
Alec Mourib34f0b72020-10-02 13:18:34 -0700761
Lucas Dupinc3800b82020-10-02 16:24:48 -0700762 for (const auto effectRegion : layer->blurRegions) {
Galia Peychevaf7889b32020-11-25 22:22:40 +0100763 drawBlurRegion(canvas, effectRegion, layerRect, cachedBlurs[effectRegion.blurRadius]);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700764 }
765
Lucas Dupin3f11e922020-09-22 17:31:04 -0700766 if (layer->shadow.length > 0) {
767 const auto rect = layer->geometry.roundedCornersRadius > 0
768 ? getSkRect(layer->geometry.roundedCornersCrop)
769 : dest;
770 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800771 } else {
772 // Shadows are assumed to live only on their own layer - it's not valid
773 // to draw the boundary retangles when there is already a caster shadow
774 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
775 // composition - using a well-defined invalid color is long-term less error-prone.
776 // Push the clipRRect onto the clip stack. Draw the image. Pop the clip.
777 if (layer->geometry.roundedCornersRadius > 0) {
778 canvas->clipRRect(getRoundedRect(layer), true);
779 }
780 canvas->drawRect(dest, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700781 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700782 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700783 }
Ana Krulec70d15b1b2020-12-01 10:05:15 -0800784 canvas->restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800785 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700786 {
787 ATRACE_NAME("flush surface");
788 surface->flush();
789 }
790
791 if (drawFence != nullptr) {
792 *drawFence = flush();
793 }
794
795 // If flush failed or we don't support native fences, we need to force the
796 // gl command stream to be executed.
797 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
798 if (requireSync) {
799 ATRACE_BEGIN("Submit(sync=true)");
800 } else {
801 ATRACE_BEGIN("Submit(sync=false)");
802 }
Lucas Dupind508e472020-11-04 04:32:06 +0000803 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -0700804 ATRACE_END();
805 if (!success) {
806 ALOGE("Failed to flush RenderEngine commands");
807 // Chances are, something illegal happened (either the caller passed
808 // us bad parameters, or we messed up our shader generation).
809 return INVALID_OPERATION;
810 }
811
812 // checkErrors();
813 return NO_ERROR;
814}
815
Lucas Dupin3f11e922020-09-22 17:31:04 -0700816inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
817 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
818}
819
820inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
821 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
822}
823
Lucas Dupin21f348e2020-09-16 17:31:26 -0700824inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800825 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700826 const auto cornerRadius = layer->geometry.roundedCornersRadius;
827 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
828}
829
Galia Peycheva80116e52020-11-06 11:57:25 +0100830inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
831 const auto rect = getSkRect(layer->geometry.boundaries);
832 const auto cornersRadius = layer->geometry.roundedCornersRadius;
833 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
834 .cornerRadiusTL = cornersRadius,
835 .cornerRadiusTR = cornersRadius,
836 .cornerRadiusBL = cornersRadius,
837 .cornerRadiusBR = cornersRadius,
838 .alpha = 1,
839 .left = static_cast<int>(rect.fLeft),
840 .top = static_cast<int>(rect.fTop),
841 .right = static_cast<int>(rect.fRight),
842 .bottom = static_cast<int>(rect.fBottom)};
843}
844
Lucas Dupin3f11e922020-09-22 17:31:04 -0700845inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
846 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
847}
848
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700849inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
850 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
851 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
852 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
853 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
854}
855
Lucas Dupin3f11e922020-09-22 17:31:04 -0700856inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
857 return SkPoint3::Make(vector.x, vector.y, vector.z);
858}
859
John Reck67b1e2b2020-08-26 13:17:24 -0700860size_t SkiaGLRenderEngine::getMaxTextureSize() const {
861 return mGrContext->maxTextureSize();
862}
863
864size_t SkiaGLRenderEngine::getMaxViewportDims() const {
865 return mGrContext->maxRenderTargetSize();
866}
867
Lucas Dupin3f11e922020-09-22 17:31:04 -0700868void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
869 const ShadowSettings& settings) {
870 ATRACE_CALL();
871 const float casterZ = settings.length / 2.0f;
872 const auto shadowShape = cornerRadius > 0
873 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
874 : SkPath::Rect(casterRect);
875 const auto flags =
876 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
877
878 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
879 getSkPoint3(settings.lightPos), settings.lightRadius,
880 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
881 flags);
882}
883
Lucas Dupinc3800b82020-10-02 16:24:48 -0700884void SkiaGLRenderEngine::drawBlurRegion(SkCanvas* canvas, const BlurRegion& effectRegion,
Galia Peychevaf7889b32020-11-25 22:22:40 +0100885 const SkRect& layerRect, sk_sp<SkSurface> blurredSurface) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700886 ATRACE_CALL();
Galia Peycheva80116e52020-11-06 11:57:25 +0100887
Lucas Dupinc3800b82020-10-02 16:24:48 -0700888 SkPaint paint;
Lyn Han1bdedb32020-11-23 20:33:57 +0000889 paint.setAlpha(static_cast<int>(effectRegion.alpha * 255));
Robin Leef180f412020-12-07 02:51:41 +0100890 const auto matrix = getBlurShaderTransform(canvas, layerRect);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100891 paint.setShader(blurredSurface->makeImageSnapshot()->makeShader(
Robin Leef180f412020-12-07 02:51:41 +0100892 SkTileMode::kClamp,
893 SkTileMode::kClamp,
894 SkSamplingOptions({SkFilterMode::kLinear, SkMipmapMode::kNone}),
895 &matrix));
Lucas Dupinc3800b82020-10-02 16:24:48 -0700896
Galia Peycheva80116e52020-11-06 11:57:25 +0100897 auto rect = SkRect::MakeLTRB(effectRegion.left, effectRegion.top, effectRegion.right,
898 effectRegion.bottom);
Galia Peycheva80116e52020-11-06 11:57:25 +0100899
Lucas Dupinc3800b82020-10-02 16:24:48 -0700900 if (effectRegion.cornerRadiusTL > 0 || effectRegion.cornerRadiusTR > 0 ||
901 effectRegion.cornerRadiusBL > 0 || effectRegion.cornerRadiusBR > 0) {
902 const SkVector radii[4] =
903 {SkVector::Make(effectRegion.cornerRadiusTL, effectRegion.cornerRadiusTL),
904 SkVector::Make(effectRegion.cornerRadiusTR, effectRegion.cornerRadiusTR),
905 SkVector::Make(effectRegion.cornerRadiusBL, effectRegion.cornerRadiusBL),
906 SkVector::Make(effectRegion.cornerRadiusBR, effectRegion.cornerRadiusBR)};
907 SkRRect roundedRect;
908 roundedRect.setRectRadii(rect, radii);
909 canvas->drawRRect(roundedRect, paint);
910 } else {
911 canvas->drawRect(rect, paint);
912 }
913}
914
Galia Peychevaf7889b32020-11-25 22:22:40 +0100915SkMatrix SkiaGLRenderEngine::getBlurShaderTransform(const SkCanvas* canvas,
916 const SkRect& layerRect) {
917 // 1. Apply the blur shader matrix, which scales up the blured surface to its real size
918 auto matrix = mBlurFilter->getShaderMatrix();
919 // 2. Since the blurred surface has the size of the layer, we align it with the
920 // top left corner of the layer position.
921 matrix.postConcat(SkMatrix::Translate(layerRect.fLeft, layerRect.fTop));
922 // 3. Finally, apply the inverse canvas matrix. The snapshot made in the BlurFilter is in the
923 // original surface orientation. The inverse matrix has to be applied to align the blur
924 // surface with the current orientation/position of the canvas.
925 SkMatrix drawInverse;
926 if (canvas->getTotalMatrix().invert(&drawInverse)) {
927 matrix.postConcat(drawInverse);
928 }
929
930 return matrix;
931}
932
John Reck67b1e2b2020-08-26 13:17:24 -0700933EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -0800934 EGLContext shareContext,
935 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -0700936 Protection protection) {
937 EGLint renderableType = 0;
938 if (config == EGL_NO_CONFIG_KHR) {
939 renderableType = EGL_OPENGL_ES3_BIT;
940 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
941 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
942 }
943 EGLint contextClientVersion = 0;
944 if (renderableType & EGL_OPENGL_ES3_BIT) {
945 contextClientVersion = 3;
946 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
947 contextClientVersion = 2;
948 } else if (renderableType & EGL_OPENGL_ES_BIT) {
949 contextClientVersion = 1;
950 } else {
951 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
952 }
953
954 std::vector<EGLint> contextAttributes;
955 contextAttributes.reserve(7);
956 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
957 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -0800958 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -0700959 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -0800960 switch (*contextPriority) {
961 case ContextPriority::REALTIME:
962 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
963 break;
964 case ContextPriority::MEDIUM:
965 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
966 break;
967 case ContextPriority::LOW:
968 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
969 break;
970 case ContextPriority::HIGH:
971 default:
972 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
973 break;
974 }
John Reck67b1e2b2020-08-26 13:17:24 -0700975 }
976 if (protection == Protection::PROTECTED) {
977 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
978 contextAttributes.push_back(EGL_TRUE);
979 }
980 contextAttributes.push_back(EGL_NONE);
981
982 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
983
984 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
985 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
986 // EGL_NO_CONTEXT so that we can abort.
987 if (config != EGL_NO_CONFIG_KHR) {
988 return context;
989 }
990 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
991 // should try to fall back to GLES 2.
992 contextAttributes[1] = 2;
993 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
994 }
995
996 return context;
997}
998
Alec Mourid6f09462020-12-07 11:18:17 -0800999std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1000 const RenderEngineCreationArgs& args) {
1001 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1002 return std::nullopt;
1003 }
1004
1005 switch (args.contextPriority) {
1006 case RenderEngine::ContextPriority::REALTIME:
1007 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1008 return RenderEngine::ContextPriority::REALTIME;
1009 } else {
1010 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1011 return RenderEngine::ContextPriority::HIGH;
1012 }
1013 case RenderEngine::ContextPriority::HIGH:
1014 case RenderEngine::ContextPriority::MEDIUM:
1015 case RenderEngine::ContextPriority::LOW:
1016 return args.contextPriority;
1017 default:
1018 return std::nullopt;
1019 }
1020}
1021
John Reck67b1e2b2020-08-26 13:17:24 -07001022EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1023 EGLConfig config, int hwcFormat,
1024 Protection protection) {
1025 EGLConfig placeholderConfig = config;
1026 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1027 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1028 }
1029 std::vector<EGLint> attributes;
1030 attributes.reserve(7);
1031 attributes.push_back(EGL_WIDTH);
1032 attributes.push_back(1);
1033 attributes.push_back(EGL_HEIGHT);
1034 attributes.push_back(1);
1035 if (protection == Protection::PROTECTED) {
1036 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1037 attributes.push_back(EGL_TRUE);
1038 }
1039 attributes.push_back(EGL_NONE);
1040
1041 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1042}
1043
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001044void SkiaGLRenderEngine::cleanFramebufferCache() {}
John Reck67b1e2b2020-08-26 13:17:24 -07001045
Alec Mourid6f09462020-12-07 11:18:17 -08001046int SkiaGLRenderEngine::getContextPriority() {
1047 int value;
1048 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1049 return value;
1050}
1051
John Reck67b1e2b2020-08-26 13:17:24 -07001052} // namespace skia
1053} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001054} // namespace android