blob: 79505bac20fbdd094e0ceac350a94fbe2594c82f [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),
Ana Krulecdfec8f52021-01-13 12:51:47 -0800270 mUseColorManagement(args.useColorManagement),
271 mRenderEngineType(args.renderEngineType) {
John Reck67b1e2b2020-08-26 13:17:24 -0700272 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
273 LOG_ALWAYS_FATAL_IF(!glInterface.get());
274
275 GrContextOptions options;
276 options.fPreferExternalImagesOverES3 = true;
277 options.fDisableDistanceFieldPaths = true;
Lucas Dupind508e472020-11-04 04:32:06 +0000278 mGrContext = GrDirectContext::MakeGL(glInterface, options);
279 if (useProtectedContext(true)) {
280 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
281 useProtectedContext(false);
282 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700283
284 if (args.supportsBackgroundBlur) {
285 mBlurFilter = new BlurFilter();
286 }
Alec Mouric0aae732021-01-12 13:32:18 -0800287 mCapture = std::make_unique<SkiaCapture>();
288}
289
290SkiaGLRenderEngine::~SkiaGLRenderEngine() {
291 std::lock_guard<std::mutex> lock(mRenderingMutex);
292 mRuntimeEffects.clear();
293 mProtectedTextureCache.clear();
294 mTextureCache.clear();
295
296 if (mBlurFilter) {
297 delete mBlurFilter;
298 }
299
300 mCapture = nullptr;
301
302 mGrContext->flushAndSubmit(true);
303 mGrContext->abandonContext();
304
305 if (mProtectedGrContext) {
306 mProtectedGrContext->flushAndSubmit(true);
307 mProtectedGrContext->abandonContext();
308 }
309
310 if (mPlaceholderSurface != EGL_NO_SURFACE) {
311 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
312 }
313 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
314 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
315 }
316 if (mEGLContext != EGL_NO_CONTEXT) {
317 eglDestroyContext(mEGLDisplay, mEGLContext);
318 }
319 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
320 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
321 }
322 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
323 eglTerminate(mEGLDisplay);
324 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700325}
326
Lucas Dupind508e472020-11-04 04:32:06 +0000327bool SkiaGLRenderEngine::supportsProtectedContent() const {
328 return mProtectedEGLContext != EGL_NO_CONTEXT;
329}
330
331bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
332 if (useProtectedContext == mInProtectedContext) {
333 return true;
334 }
335 if (useProtectedContext && supportsProtectedContent()) {
336 return false;
337 }
338 const EGLSurface surface =
339 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
340 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
341 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800342
Lucas Dupind508e472020-11-04 04:32:06 +0000343 if (success) {
344 mInProtectedContext = useProtectedContext;
345 }
346 return success;
347}
348
John Reck67b1e2b2020-08-26 13:17:24 -0700349base::unique_fd SkiaGLRenderEngine::flush() {
350 ATRACE_CALL();
351 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
352 return base::unique_fd();
353 }
354
355 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
356 if (sync == EGL_NO_SYNC_KHR) {
357 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
358 return base::unique_fd();
359 }
360
361 // native fence fd will not be populated until flush() is done.
362 glFlush();
363
364 // get the fence fd
365 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
366 eglDestroySyncKHR(mEGLDisplay, sync);
367 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
368 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
369 }
370
371 return fenceFd;
372}
373
374bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
375 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
376 !gl::GLExtensions::getInstance().hasWaitSync()) {
377 return false;
378 }
379
380 // release the fd and transfer the ownership to EGLSync
381 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
382 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
383 if (sync == EGL_NO_SYNC_KHR) {
384 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
385 return false;
386 }
387
388 // XXX: The spec draft is inconsistent as to whether this should return an
389 // EGLint or void. Ignore the return value for now, as it's not strictly
390 // needed.
391 eglWaitSyncKHR(mEGLDisplay, sync, 0);
392 EGLint error = eglGetError();
393 eglDestroySyncKHR(mEGLDisplay, sync);
394 if (error != EGL_SUCCESS) {
395 ALOGE("failed to wait for EGL native fence sync: %#x", error);
396 return false;
397 }
398
399 return true;
400}
401
402static bool hasUsage(const AHardwareBuffer_Desc& desc, uint64_t usage) {
403 return !!(desc.usage & usage);
404}
405
Alec Mouri678245d2020-09-30 16:58:23 -0700406static float toDegrees(uint32_t transform) {
407 switch (transform) {
408 case ui::Transform::ROT_90:
409 return 90.0;
410 case ui::Transform::ROT_180:
411 return 180.0;
412 case ui::Transform::ROT_270:
413 return 270.0;
414 default:
415 return 0.0;
416 }
417}
418
Alec Mourib34f0b72020-10-02 13:18:34 -0700419static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
420 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
421 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
422 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
423 matrix[3][3], 0);
424}
425
Alec Mouri029d1952020-10-12 10:37:08 -0700426static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
427 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
428 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
429
430 // Treat unsupported dataspaces as srgb
431 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
432 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
433 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
434 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
435 }
436
437 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
438 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
439 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
440 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
441 }
442
443 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
444 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
445 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
446 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
447
448 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
449 sourceTransfer != destTransfer;
450}
451
Alec Mouri1a4d0642020-11-13 17:42:01 -0800452static bool needsLinearEffect(const mat4& colorTransform, ui::Dataspace sourceDataspace,
453 ui::Dataspace destinationDataspace) {
454 return colorTransform != mat4() || needsToneMapping(sourceDataspace, destinationDataspace);
455}
456
Ana Krulecdfec8f52021-01-13 12:51:47 -0800457void SkiaGLRenderEngine::cacheExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
458 // Only run this if RE is running on its own thread. This way the access to GL
459 // operations is guaranteed to be happening on the same thread.
460 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
461 return;
462 }
463 ATRACE_CALL();
464
465 std::lock_guard<std::mutex> lock(mRenderingMutex);
466 auto iter = mTextureCache.find(buffer->getId());
467 if (iter != mTextureCache.end()) {
468 ALOGV("Texture already exists in cache.");
469 return;
470 } else {
471 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
472 std::make_shared<AutoBackendTexture::LocalRef>();
473 imageTextureRef->setTexture(
474 new AutoBackendTexture(mGrContext.get(), buffer->toAHardwareBuffer(), false));
475 mTextureCache.insert({buffer->getId(), imageTextureRef});
476 }
477}
478
John Reck67b1e2b2020-08-26 13:17:24 -0700479void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800480 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700481 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800482 mTextureCache.erase(bufferId);
483 mProtectedTextureCache.erase(bufferId);
John Reck67b1e2b2020-08-26 13:17:24 -0700484}
485
Ana Krulec47814212021-01-06 19:00:10 -0800486sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
487 const LayerSettings* layer,
488 const DisplaySettings& display,
489 bool undoPremultipliedAlpha) {
490 if (mUseColorManagement &&
491 needsLinearEffect(layer->colorTransform, layer->sourceDataspace, display.outputDataspace)) {
492 LinearEffect effect = LinearEffect{.inputDataspace = layer->sourceDataspace,
493 .outputDataspace = display.outputDataspace,
494 .undoPremultipliedAlpha = undoPremultipliedAlpha};
495
496 auto effectIter = mRuntimeEffects.find(effect);
497 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
498 if (effectIter == mRuntimeEffects.end()) {
499 runtimeEffect = buildRuntimeEffect(effect);
500 mRuntimeEffects.insert({effect, runtimeEffect});
501 } else {
502 runtimeEffect = effectIter->second;
503 }
504 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
505 display.maxLuminance,
506 layer->source.buffer.maxMasteringLuminance,
507 layer->source.buffer.maxContentLuminance);
508 }
509 return shader;
510}
511
John Reck67b1e2b2020-08-26 13:17:24 -0700512status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
513 const std::vector<const LayerSettings*>& layers,
514 const sp<GraphicBuffer>& buffer,
515 const bool useFramebufferCache,
516 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
517 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800518
John Reck67b1e2b2020-08-26 13:17:24 -0700519 std::lock_guard<std::mutex> lock(mRenderingMutex);
520 if (layers.empty()) {
521 ALOGV("Drawing empty layer stack");
522 return NO_ERROR;
523 }
524
525 if (bufferFence.get() >= 0) {
526 // Duplicate the fence for passing to waitFence.
527 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
528 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
529 ATRACE_NAME("Waiting before draw");
530 sync_wait(bufferFence.get(), -1);
531 }
532 }
533 if (buffer == nullptr) {
534 ALOGE("No output buffer provided. Aborting GPU composition.");
535 return BAD_VALUE;
536 }
537
Lucas Dupind508e472020-11-04 04:32:06 +0000538 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800539 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700540 AHardwareBuffer_Desc bufferDesc;
541 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700542 LOG_ALWAYS_FATAL_IF(!hasUsage(bufferDesc, AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE),
543 "missing usage");
544
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800545 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700546 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000547 auto iter = cache.find(buffer->getId());
548 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700549 ALOGV("Cache hit!");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800550 ATRACE_NAME("Cache hit");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800551 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700552 }
553 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800554
555 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800556 ATRACE_NAME("Cache miss");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800557 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
558 surfaceTextureRef->setTexture(
Alec Mouric0aae732021-01-12 13:32:18 -0800559 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), true));
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800560 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700561 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800562 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700563 }
564 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800565
566 sk_sp<SkSurface> surface =
567 surfaceTextureRef->getTexture()->getOrCreateSurface(mUseColorManagement
568 ? display.outputDataspace
Alec Mouric0aae732021-01-12 13:32:18 -0800569 : ui::Dataspace::UNKNOWN,
570 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700571
Alec Mouric0aae732021-01-12 13:32:18 -0800572 SkCanvas* canvas = mCapture->tryCapture(surface.get());
Ana Krulec6eab17a2020-12-09 15:52:36 -0800573 if (canvas == nullptr) {
574 ALOGE("Cannot acquire canvas from Skia.");
575 return BAD_VALUE;
576 }
Alec Mouri678245d2020-09-30 16:58:23 -0700577 // Clear the entire canvas with a transparent black to prevent ghost images.
578 canvas->clear(SK_ColorTRANSPARENT);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700579 canvas->save();
John Reck67b1e2b2020-08-26 13:17:24 -0700580
Alec Mouric0aae732021-01-12 13:32:18 -0800581 if (mCapture->isCaptureRunning()) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800582 // Record display settings when capture is running.
583 std::stringstream displaySettings;
584 PrintTo(display, &displaySettings);
585 // Store the DisplaySettings in additional information.
586 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
587 SkData::MakeWithCString(displaySettings.str().c_str()));
588 }
589
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700590 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
591 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
592 // displays might have different scaling when compared to the physical screen.
Alec Mouri678245d2020-09-30 16:58:23 -0700593
594 canvas->clipRect(getSkRect(display.physicalDisplay));
Galia Peychevaf7889b32020-11-25 22:22:40 +0100595 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700596
597 const auto clipWidth = display.clip.width();
598 const auto clipHeight = display.clip.height();
599 auto rotatedClipWidth = clipWidth;
600 auto rotatedClipHeight = clipHeight;
601 // Scale is contingent on the rotation result.
602 if (display.orientation & ui::Transform::ROT_90) {
603 std::swap(rotatedClipWidth, rotatedClipHeight);
604 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700605 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700606 static_cast<SkScalar>(rotatedClipWidth);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700607 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700608 static_cast<SkScalar>(rotatedClipHeight);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100609 canvas->scale(scaleX, scaleY);
Alec Mouri678245d2020-09-30 16:58:23 -0700610
611 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
612 // back so that the top left corner of the clip is at (0, 0).
Galia Peychevaf7889b32020-11-25 22:22:40 +0100613 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
614 canvas->rotate(toDegrees(display.orientation));
615 canvas->translate(-clipWidth / 2, -clipHeight / 2);
616 canvas->translate(-display.clip.left, -display.clip.top);
Alec Mouric0aae732021-01-12 13:32:18 -0800617
618 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
619 // view is still on-screen. The clear region could be re-specified as a black color layer,
620 // however.
621 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500622 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800623 size_t numRects = 0;
624 Rect const* rects = display.clearRegion.getArray(&numRects);
625 SkIRect skRects[numRects];
626 for (int i = 0; i < numRects; ++i) {
627 skRects[i] =
628 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
629 }
630 SkRegion clearRegion;
631 SkPaint paint;
632 sk_sp<SkShader> shader =
633 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
634 toSkColorSpace(mUseColorManagement ? display.outputDataspace
635 : ui::Dataspace::UNKNOWN));
636 paint.setShader(shader);
637 clearRegion.setRects(skRects, numRects);
638 canvas->drawRegion(clearRegion, paint);
639 }
640
John Reck67b1e2b2020-08-26 13:17:24 -0700641 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500642 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100643 canvas->save();
644
Alec Mouric0aae732021-01-12 13:32:18 -0800645 if (mCapture->isCaptureRunning()) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800646 // Record the name of the layer if the capture is running.
647 std::stringstream layerSettings;
648 PrintTo(*layer, &layerSettings);
649 // Store the LayerSettings in additional information.
650 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
651 SkData::MakeWithCString(layerSettings.str().c_str()));
652 }
653
Galia Peychevaf7889b32020-11-25 22:22:40 +0100654 // Layers have a local transform that should be applied to them
655 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100656
Lucas Dupin21f348e2020-09-16 17:31:26 -0700657 SkPaint paint;
658 const auto& bounds = layer->geometry.boundaries;
Lucas Dupin3f11e922020-09-22 17:31:04 -0700659 const auto dest = getSkRect(bounds);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100660 const auto layerRect = canvas->getTotalMatrix().mapRect(dest);
Derek Sollenberger545ec442021-01-25 10:02:23 -0500661 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
Lucas Dupinc3800b82020-10-02 16:24:48 -0700662 if (mBlurFilter) {
663 if (layer->backgroundBlurRadius > 0) {
664 ATRACE_NAME("BackgroundBlur");
Galia Peycheva80116e52020-11-06 11:57:25 +0100665 auto blurredSurface = mBlurFilter->generate(canvas, surface,
666 layer->backgroundBlurRadius, layerRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700667 cachedBlurs[layer->backgroundBlurRadius] = blurredSurface;
Galia Peycheva80116e52020-11-06 11:57:25 +0100668
Galia Peychevaf7889b32020-11-25 22:22:40 +0100669 drawBlurRegion(canvas, getBlurRegion(layer), layerRect, blurredSurface);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700670 }
671 if (layer->blurRegions.size() > 0) {
672 for (auto region : layer->blurRegions) {
673 if (cachedBlurs[region.blurRadius]) {
674 continue;
675 }
676 ATRACE_NAME("BlurRegion");
Galia Peycheva6c460652020-11-03 19:42:42 +0100677 auto blurredSurface =
678 mBlurFilter->generate(canvas, surface, region.blurRadius, layerRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700679 cachedBlurs[region.blurRadius] = blurredSurface;
680 }
681 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700682 }
683
Alec Mouric0aae732021-01-12 13:32:18 -0800684 const ui::Dataspace targetDataspace = mUseColorManagement
685 ? (needsLinearEffect(layer->colorTransform, layer->sourceDataspace,
686 display.outputDataspace)
687 // If we need to map to linear space, then mark the source image with the
688 // same colorspace as the destination surface so that Skia's color
689 // management is a no-op.
690 ? display.outputDataspace
691 : layer->sourceDataspace)
692 : ui::Dataspace::UNKNOWN;
693
John Reck67b1e2b2020-08-26 13:17:24 -0700694 if (layer->source.buffer.buffer) {
695 ATRACE_NAME("DrawImage");
696 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800697 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
698 auto iter = mTextureCache.find(item.buffer->getId());
699 if (iter != mTextureCache.end()) {
700 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700701 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800702 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
Alec Mouric0aae732021-01-12 13:32:18 -0800703 imageTextureRef->setTexture(new AutoBackendTexture(grContext.get(),
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800704 item.buffer->toAHardwareBuffer(),
705 false));
Alec Mouric0aae732021-01-12 13:32:18 -0800706 mTextureCache.insert({item.buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700707 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800708
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800709 sk_sp<SkImage> image =
Alec Mouric0aae732021-01-12 13:32:18 -0800710 imageTextureRef->getTexture()->makeImage(targetDataspace,
711 item.usePremultipliedAlpha
712 ? kPremul_SkAlphaType
713 : kUnpremul_SkAlphaType,
714 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700715
716 auto texMatrix = getSkM44(item.textureTransform).asM33();
717 // textureTansform was intended to be passed directly into a shader, so when
718 // building the total matrix with the textureTransform we need to first
719 // normalize it, then apply the textureTransform, then scale back up.
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800720 texMatrix.preScale(1.0f / bounds.getWidth(), 1.0f / bounds.getHeight());
721 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700722
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800723 SkMatrix matrix;
724 if (!texMatrix.invert(&matrix)) {
725 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700726 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800727 // The shader does not respect the translation, so we add it to the texture
728 // transform for the SkImage. This will make sure that the correct layer contents
729 // are drawn in the correct part of the screen.
730 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700731
Ana Krulecb7b28b22020-11-23 14:48:58 -0800732 sk_sp<SkShader> shader;
733
734 if (layer->source.buffer.useTextureFiltering) {
735 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
736 SkSamplingOptions(
737 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
738 &matrix);
739 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500740 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800741 }
Alec Mouri029d1952020-10-12 10:37:08 -0700742
Alec Mouric0aae732021-01-12 13:32:18 -0800743 // Handle opaque images - it's a little nonstandard how we do this.
744 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
745 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
746 // The important language is that when isOpaque is set, opacity is not sampled from the
747 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
748 // here's the conundrum:
749 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
750 // as an internal hint - composition is undefined when there are alpha bits present.
751 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
752 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
753 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
754 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
755 // of a hack anyways.
756 // 3. We can't change the blendmode to src, because while this satisfies the requirement
757 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
758 // because src always clobbers the destination content.
759 //
760 // So, what we do here instead is an additive blend mode where we compose the input
761 // image with a solid black. This might need to be reassess if this does not support
762 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
763 if (item.isOpaque) {
764 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
765 SkShaders::Color(SkColors::kBlack,
766 toSkColorSpace(targetDataspace)));
767 }
768
Ana Krulec47814212021-01-06 19:00:10 -0800769 paint.setShader(
770 createRuntimeEffectShader(shader, layer, display,
771 !item.isOpaque && item.usePremultipliedAlpha));
Ana Krulec1768bd22020-11-23 14:51:31 -0800772 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700773 } else {
774 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700775 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800776 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
777 .fG = color.g,
778 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800779 .fA = layer->alpha},
780 toSkColorSpace(targetDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800781 paint.setShader(createRuntimeEffectShader(shader, layer, display,
782 /* undoPremultipliedAlpha */ false));
John Reck67b1e2b2020-08-26 13:17:24 -0700783 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700784
Alec Mouri4ce5ec02021-01-07 17:33:21 -0800785 sk_sp<SkColorFilter> filter =
786 SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
787
Alec Mouri4ce5ec02021-01-07 17:33:21 -0800788 paint.setColorFilter(filter);
Alec Mourib34f0b72020-10-02 13:18:34 -0700789
Lucas Dupinc3800b82020-10-02 16:24:48 -0700790 for (const auto effectRegion : layer->blurRegions) {
Galia Peychevaf7889b32020-11-25 22:22:40 +0100791 drawBlurRegion(canvas, effectRegion, layerRect, cachedBlurs[effectRegion.blurRadius]);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700792 }
793
Lucas Dupin3f11e922020-09-22 17:31:04 -0700794 if (layer->shadow.length > 0) {
795 const auto rect = layer->geometry.roundedCornersRadius > 0
796 ? getSkRect(layer->geometry.roundedCornersCrop)
797 : dest;
798 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800799 } else {
800 // Shadows are assumed to live only on their own layer - it's not valid
801 // to draw the boundary retangles when there is already a caster shadow
802 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
803 // composition - using a well-defined invalid color is long-term less error-prone.
804 // Push the clipRRect onto the clip stack. Draw the image. Pop the clip.
805 if (layer->geometry.roundedCornersRadius > 0) {
806 canvas->clipRRect(getRoundedRect(layer), true);
807 }
808 canvas->drawRect(dest, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700809 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700810 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700811 }
Ana Krulec70d15b1b2020-12-01 10:05:15 -0800812 canvas->restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800813 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700814 {
815 ATRACE_NAME("flush surface");
816 surface->flush();
817 }
818
819 if (drawFence != nullptr) {
820 *drawFence = flush();
821 }
822
823 // If flush failed or we don't support native fences, we need to force the
824 // gl command stream to be executed.
825 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
826 if (requireSync) {
827 ATRACE_BEGIN("Submit(sync=true)");
828 } else {
829 ATRACE_BEGIN("Submit(sync=false)");
830 }
Lucas Dupind508e472020-11-04 04:32:06 +0000831 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -0700832 ATRACE_END();
833 if (!success) {
834 ALOGE("Failed to flush RenderEngine commands");
835 // Chances are, something illegal happened (either the caller passed
836 // us bad parameters, or we messed up our shader generation).
837 return INVALID_OPERATION;
838 }
839
840 // checkErrors();
841 return NO_ERROR;
842}
843
Lucas Dupin3f11e922020-09-22 17:31:04 -0700844inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
845 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
846}
847
848inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
849 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
850}
851
Lucas Dupin21f348e2020-09-16 17:31:26 -0700852inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800853 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700854 const auto cornerRadius = layer->geometry.roundedCornersRadius;
855 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
856}
857
Galia Peycheva80116e52020-11-06 11:57:25 +0100858inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
859 const auto rect = getSkRect(layer->geometry.boundaries);
860 const auto cornersRadius = layer->geometry.roundedCornersRadius;
861 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
862 .cornerRadiusTL = cornersRadius,
863 .cornerRadiusTR = cornersRadius,
864 .cornerRadiusBL = cornersRadius,
865 .cornerRadiusBR = cornersRadius,
866 .alpha = 1,
867 .left = static_cast<int>(rect.fLeft),
868 .top = static_cast<int>(rect.fTop),
869 .right = static_cast<int>(rect.fRight),
870 .bottom = static_cast<int>(rect.fBottom)};
871}
872
Lucas Dupin3f11e922020-09-22 17:31:04 -0700873inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
874 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
875}
876
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700877inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
878 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
879 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
880 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
881 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
882}
883
Lucas Dupin3f11e922020-09-22 17:31:04 -0700884inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
885 return SkPoint3::Make(vector.x, vector.y, vector.z);
886}
887
John Reck67b1e2b2020-08-26 13:17:24 -0700888size_t SkiaGLRenderEngine::getMaxTextureSize() const {
889 return mGrContext->maxTextureSize();
890}
891
892size_t SkiaGLRenderEngine::getMaxViewportDims() const {
893 return mGrContext->maxRenderTargetSize();
894}
895
Lucas Dupin3f11e922020-09-22 17:31:04 -0700896void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
897 const ShadowSettings& settings) {
898 ATRACE_CALL();
899 const float casterZ = settings.length / 2.0f;
900 const auto shadowShape = cornerRadius > 0
901 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
902 : SkPath::Rect(casterRect);
903 const auto flags =
904 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
905
906 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
907 getSkPoint3(settings.lightPos), settings.lightRadius,
908 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
909 flags);
910}
911
Lucas Dupinc3800b82020-10-02 16:24:48 -0700912void SkiaGLRenderEngine::drawBlurRegion(SkCanvas* canvas, const BlurRegion& effectRegion,
Derek Sollenberger545ec442021-01-25 10:02:23 -0500913 const SkRect& layerRect, sk_sp<SkImage> blurredImage) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700914 ATRACE_CALL();
Galia Peycheva80116e52020-11-06 11:57:25 +0100915
Lucas Dupinc3800b82020-10-02 16:24:48 -0700916 SkPaint paint;
Lyn Han1bdedb32020-11-23 20:33:57 +0000917 paint.setAlpha(static_cast<int>(effectRegion.alpha * 255));
Robin Leef180f412020-12-07 02:51:41 +0100918 const auto matrix = getBlurShaderTransform(canvas, layerRect);
Derek Sollenberger545ec442021-01-25 10:02:23 -0500919 SkSamplingOptions linearSampling(SkFilterMode::kLinear, SkMipmapMode::kNone);
920 paint.setShader(blurredImage->makeShader(SkTileMode::kClamp, SkTileMode::kClamp, linearSampling,
921 &matrix));
Lucas Dupinc3800b82020-10-02 16:24:48 -0700922
Galia Peycheva80116e52020-11-06 11:57:25 +0100923 auto rect = SkRect::MakeLTRB(effectRegion.left, effectRegion.top, effectRegion.right,
924 effectRegion.bottom);
Galia Peycheva80116e52020-11-06 11:57:25 +0100925
Lucas Dupinc3800b82020-10-02 16:24:48 -0700926 if (effectRegion.cornerRadiusTL > 0 || effectRegion.cornerRadiusTR > 0 ||
927 effectRegion.cornerRadiusBL > 0 || effectRegion.cornerRadiusBR > 0) {
928 const SkVector radii[4] =
929 {SkVector::Make(effectRegion.cornerRadiusTL, effectRegion.cornerRadiusTL),
930 SkVector::Make(effectRegion.cornerRadiusTR, effectRegion.cornerRadiusTR),
931 SkVector::Make(effectRegion.cornerRadiusBL, effectRegion.cornerRadiusBL),
932 SkVector::Make(effectRegion.cornerRadiusBR, effectRegion.cornerRadiusBR)};
933 SkRRect roundedRect;
934 roundedRect.setRectRadii(rect, radii);
935 canvas->drawRRect(roundedRect, paint);
936 } else {
937 canvas->drawRect(rect, paint);
938 }
939}
940
Galia Peychevaf7889b32020-11-25 22:22:40 +0100941SkMatrix SkiaGLRenderEngine::getBlurShaderTransform(const SkCanvas* canvas,
942 const SkRect& layerRect) {
943 // 1. Apply the blur shader matrix, which scales up the blured surface to its real size
944 auto matrix = mBlurFilter->getShaderMatrix();
945 // 2. Since the blurred surface has the size of the layer, we align it with the
946 // top left corner of the layer position.
947 matrix.postConcat(SkMatrix::Translate(layerRect.fLeft, layerRect.fTop));
948 // 3. Finally, apply the inverse canvas matrix. The snapshot made in the BlurFilter is in the
949 // original surface orientation. The inverse matrix has to be applied to align the blur
950 // surface with the current orientation/position of the canvas.
951 SkMatrix drawInverse;
952 if (canvas->getTotalMatrix().invert(&drawInverse)) {
953 matrix.postConcat(drawInverse);
954 }
955
956 return matrix;
957}
958
John Reck67b1e2b2020-08-26 13:17:24 -0700959EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -0800960 EGLContext shareContext,
961 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -0700962 Protection protection) {
963 EGLint renderableType = 0;
964 if (config == EGL_NO_CONFIG_KHR) {
965 renderableType = EGL_OPENGL_ES3_BIT;
966 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
967 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
968 }
969 EGLint contextClientVersion = 0;
970 if (renderableType & EGL_OPENGL_ES3_BIT) {
971 contextClientVersion = 3;
972 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
973 contextClientVersion = 2;
974 } else if (renderableType & EGL_OPENGL_ES_BIT) {
975 contextClientVersion = 1;
976 } else {
977 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
978 }
979
980 std::vector<EGLint> contextAttributes;
981 contextAttributes.reserve(7);
982 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
983 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -0800984 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -0700985 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -0800986 switch (*contextPriority) {
987 case ContextPriority::REALTIME:
988 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
989 break;
990 case ContextPriority::MEDIUM:
991 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
992 break;
993 case ContextPriority::LOW:
994 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
995 break;
996 case ContextPriority::HIGH:
997 default:
998 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
999 break;
1000 }
John Reck67b1e2b2020-08-26 13:17:24 -07001001 }
1002 if (protection == Protection::PROTECTED) {
1003 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1004 contextAttributes.push_back(EGL_TRUE);
1005 }
1006 contextAttributes.push_back(EGL_NONE);
1007
1008 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1009
1010 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1011 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1012 // EGL_NO_CONTEXT so that we can abort.
1013 if (config != EGL_NO_CONFIG_KHR) {
1014 return context;
1015 }
1016 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1017 // should try to fall back to GLES 2.
1018 contextAttributes[1] = 2;
1019 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1020 }
1021
1022 return context;
1023}
1024
Alec Mourid6f09462020-12-07 11:18:17 -08001025std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1026 const RenderEngineCreationArgs& args) {
1027 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1028 return std::nullopt;
1029 }
1030
1031 switch (args.contextPriority) {
1032 case RenderEngine::ContextPriority::REALTIME:
1033 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1034 return RenderEngine::ContextPriority::REALTIME;
1035 } else {
1036 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1037 return RenderEngine::ContextPriority::HIGH;
1038 }
1039 case RenderEngine::ContextPriority::HIGH:
1040 case RenderEngine::ContextPriority::MEDIUM:
1041 case RenderEngine::ContextPriority::LOW:
1042 return args.contextPriority;
1043 default:
1044 return std::nullopt;
1045 }
1046}
1047
John Reck67b1e2b2020-08-26 13:17:24 -07001048EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1049 EGLConfig config, int hwcFormat,
1050 Protection protection) {
1051 EGLConfig placeholderConfig = config;
1052 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1053 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1054 }
1055 std::vector<EGLint> attributes;
1056 attributes.reserve(7);
1057 attributes.push_back(EGL_WIDTH);
1058 attributes.push_back(1);
1059 attributes.push_back(EGL_HEIGHT);
1060 attributes.push_back(1);
1061 if (protection == Protection::PROTECTED) {
1062 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1063 attributes.push_back(EGL_TRUE);
1064 }
1065 attributes.push_back(EGL_NONE);
1066
1067 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1068}
1069
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001070void SkiaGLRenderEngine::cleanFramebufferCache() {}
John Reck67b1e2b2020-08-26 13:17:24 -07001071
Alec Mourid6f09462020-12-07 11:18:17 -08001072int SkiaGLRenderEngine::getContextPriority() {
1073 int value;
1074 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1075 return value;
1076}
1077
John Reck67b1e2b2020-08-26 13:17:24 -07001078} // namespace skia
1079} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001080} // namespace android