blob: dd26b17eb42ae06ed69ce655beebda0f44b9a81c [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>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080036#include <android-base/stringprintf.h>
Alec Mourib5777452020-09-28 11:32:42 -070037#include <gl/GrGLInterface.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080038#include <sync/sync.h>
39#include <ui/BlurRegion.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080040#include <ui/DebugUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080041#include <ui/GraphicBuffer.h>
42#include <utils/Trace.h>
Alec Mourib5777452020-09-28 11:32:42 -070043
44#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080045#include <cstdint>
46#include <memory>
47
48#include "../gl/GLExtensions.h"
Alec Mouric0aae732021-01-12 13:32:18 -080049#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080050#include "SkBlendMode.h"
51#include "SkImageInfo.h"
52#include "filters/BlurFilter.h"
53#include "filters/LinearEffect.h"
54#include "log/log_main.h"
55#include "skia/debug/SkiaCapture.h"
56#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070057
John Reck67b1e2b2020-08-26 13:17:24 -070058bool checkGlError(const char* op, int lineNumber);
59
60namespace android {
61namespace renderengine {
62namespace skia {
63
Ana Krulec1d12b3b2021-01-27 16:49:51 -080064using base::StringAppendF;
65
John Reck67b1e2b2020-08-26 13:17:24 -070066static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
67 EGLint wanted, EGLConfig* outConfig) {
68 EGLint numConfigs = -1, n = 0;
69 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
70 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
71 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
72 configs.resize(n);
73
74 if (!configs.empty()) {
75 if (attribute != EGL_NONE) {
76 for (EGLConfig config : configs) {
77 EGLint value = 0;
78 eglGetConfigAttrib(dpy, config, attribute, &value);
79 if (wanted == value) {
80 *outConfig = config;
81 return NO_ERROR;
82 }
83 }
84 } else {
85 // just pick the first one
86 *outConfig = configs[0];
87 return NO_ERROR;
88 }
89 }
90
91 return NAME_NOT_FOUND;
92}
93
94static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
95 EGLConfig* config) {
96 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
97 // it is to be used with WIFI displays
98 status_t err;
99 EGLint wantedAttribute;
100 EGLint wantedAttributeValue;
101
102 std::vector<EGLint> attribs;
103 if (renderableType) {
104 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
105 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
106
107 // Default to 8 bits per channel.
108 const EGLint tmpAttribs[] = {
109 EGL_RENDERABLE_TYPE,
110 renderableType,
111 EGL_RECORDABLE_ANDROID,
112 EGL_TRUE,
113 EGL_SURFACE_TYPE,
114 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
115 EGL_FRAMEBUFFER_TARGET_ANDROID,
116 EGL_TRUE,
117 EGL_RED_SIZE,
118 is1010102 ? 10 : 8,
119 EGL_GREEN_SIZE,
120 is1010102 ? 10 : 8,
121 EGL_BLUE_SIZE,
122 is1010102 ? 10 : 8,
123 EGL_ALPHA_SIZE,
124 is1010102 ? 2 : 8,
125 EGL_NONE,
126 };
127 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
128 std::back_inserter(attribs));
129 wantedAttribute = EGL_NONE;
130 wantedAttributeValue = EGL_NONE;
131 } else {
132 // if no renderable type specified, fallback to a simplified query
133 wantedAttribute = EGL_NATIVE_VISUAL_ID;
134 wantedAttributeValue = format;
135 }
136
137 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
138 config);
139 if (err == NO_ERROR) {
140 EGLint caveat;
141 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
142 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
143 }
144
145 return err;
146}
147
148std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
149 const RenderEngineCreationArgs& args) {
150 // initialize EGL for the default display
151 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
152 if (!eglInitialize(display, nullptr, nullptr)) {
153 LOG_ALWAYS_FATAL("failed to initialize EGL");
154 }
155
Yiwei Zhange2650962020-12-01 23:27:58 +0000156 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700157 if (!eglVersion) {
158 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000159 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700160 }
161
Yiwei Zhange2650962020-12-01 23:27:58 +0000162 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700163 if (!eglExtensions) {
164 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000165 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700166 }
167
168 auto& extensions = gl::GLExtensions::getInstance();
169 extensions.initWithEGLStrings(eglVersion, eglExtensions);
170
171 // The code assumes that ES2 or later is available if this extension is
172 // supported.
173 EGLConfig config = EGL_NO_CONFIG_KHR;
174 if (!extensions.hasNoConfigContext()) {
175 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
176 }
177
John Reck67b1e2b2020-08-26 13:17:24 -0700178 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800179 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700180 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800181 protectedContext =
182 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700183 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
184 }
185
Alec Mourid6f09462020-12-07 11:18:17 -0800186 EGLContext ctxt =
187 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700188
189 // if can't create a GL context, we can only abort.
190 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
191
192 EGLSurface placeholder = EGL_NO_SURFACE;
193 if (!extensions.hasSurfacelessContext()) {
194 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
195 Protection::UNPROTECTED);
196 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
197 }
198 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
199 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
200 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
201 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
202
203 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
204 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
205 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
206 Protection::PROTECTED);
207 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
208 "can't create protected placeholder pbuffer");
209 }
210
211 // initialize the renderer while GL is current
212 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000213 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
214 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700215
216 ALOGI("OpenGL ES informations:");
217 ALOGI("vendor : %s", extensions.getVendor());
218 ALOGI("renderer : %s", extensions.getRenderer());
219 ALOGI("version : %s", extensions.getVersion());
220 ALOGI("extensions: %s", extensions.getExtensions());
221 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
222 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
223
224 return engine;
225}
226
227EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
228 status_t err;
229 EGLConfig config;
230
231 // First try to get an ES3 config
232 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
233 if (err != NO_ERROR) {
234 // If ES3 fails, try to get an ES2 config
235 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
236 if (err != NO_ERROR) {
237 // If ES2 still doesn't work, probably because we're on the emulator.
238 // try a simplified query
239 ALOGW("no suitable EGLConfig found, trying a simpler query");
240 err = selectEGLConfig(display, format, 0, &config);
241 if (err != NO_ERROR) {
242 // this EGL is too lame for android
243 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
244 }
245 }
246 }
247
248 if (logConfig) {
249 // print some debugging info
250 EGLint r, g, b, a;
251 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
252 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
253 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
254 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
255 ALOGI("EGL information:");
256 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
257 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
258 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
259 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
260 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
261 }
262
263 return config;
264}
265
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700266SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000267 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700268 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri081be4c2020-09-16 10:24:47 -0700269 : mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700270 mEGLContext(ctxt),
271 mPlaceholderSurface(placeholder),
272 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700273 mProtectedPlaceholderSurface(protectedPlaceholder),
Ana Krulecdfec8f52021-01-13 12:51:47 -0800274 mUseColorManagement(args.useColorManagement),
275 mRenderEngineType(args.renderEngineType) {
John Reck67b1e2b2020-08-26 13:17:24 -0700276 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
277 LOG_ALWAYS_FATAL_IF(!glInterface.get());
278
279 GrContextOptions options;
280 options.fPreferExternalImagesOverES3 = true;
281 options.fDisableDistanceFieldPaths = true;
Lucas Dupind508e472020-11-04 04:32:06 +0000282 mGrContext = GrDirectContext::MakeGL(glInterface, options);
283 if (useProtectedContext(true)) {
284 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
285 useProtectedContext(false);
286 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700287
288 if (args.supportsBackgroundBlur) {
289 mBlurFilter = new BlurFilter();
290 }
Alec Mouric0aae732021-01-12 13:32:18 -0800291 mCapture = std::make_unique<SkiaCapture>();
292}
293
294SkiaGLRenderEngine::~SkiaGLRenderEngine() {
295 std::lock_guard<std::mutex> lock(mRenderingMutex);
296 mRuntimeEffects.clear();
297 mProtectedTextureCache.clear();
298 mTextureCache.clear();
299
300 if (mBlurFilter) {
301 delete mBlurFilter;
302 }
303
304 mCapture = nullptr;
305
306 mGrContext->flushAndSubmit(true);
307 mGrContext->abandonContext();
308
309 if (mProtectedGrContext) {
310 mProtectedGrContext->flushAndSubmit(true);
311 mProtectedGrContext->abandonContext();
312 }
313
314 if (mPlaceholderSurface != EGL_NO_SURFACE) {
315 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
316 }
317 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
318 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
319 }
320 if (mEGLContext != EGL_NO_CONTEXT) {
321 eglDestroyContext(mEGLDisplay, mEGLContext);
322 }
323 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
324 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
325 }
326 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
327 eglTerminate(mEGLDisplay);
328 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700329}
330
Lucas Dupind508e472020-11-04 04:32:06 +0000331bool SkiaGLRenderEngine::supportsProtectedContent() const {
332 return mProtectedEGLContext != EGL_NO_CONTEXT;
333}
334
335bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
336 if (useProtectedContext == mInProtectedContext) {
337 return true;
338 }
339 if (useProtectedContext && supportsProtectedContent()) {
340 return false;
341 }
342 const EGLSurface surface =
343 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
344 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
345 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800346
Lucas Dupind508e472020-11-04 04:32:06 +0000347 if (success) {
348 mInProtectedContext = useProtectedContext;
349 }
350 return success;
351}
352
John Reck67b1e2b2020-08-26 13:17:24 -0700353base::unique_fd SkiaGLRenderEngine::flush() {
354 ATRACE_CALL();
355 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
356 return base::unique_fd();
357 }
358
359 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
360 if (sync == EGL_NO_SYNC_KHR) {
361 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
362 return base::unique_fd();
363 }
364
365 // native fence fd will not be populated until flush() is done.
366 glFlush();
367
368 // get the fence fd
369 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
370 eglDestroySyncKHR(mEGLDisplay, sync);
371 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
372 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
373 }
374
375 return fenceFd;
376}
377
378bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
379 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
380 !gl::GLExtensions::getInstance().hasWaitSync()) {
381 return false;
382 }
383
384 // release the fd and transfer the ownership to EGLSync
385 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
386 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
387 if (sync == EGL_NO_SYNC_KHR) {
388 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
389 return false;
390 }
391
392 // XXX: The spec draft is inconsistent as to whether this should return an
393 // EGLint or void. Ignore the return value for now, as it's not strictly
394 // needed.
395 eglWaitSyncKHR(mEGLDisplay, sync, 0);
396 EGLint error = eglGetError();
397 eglDestroySyncKHR(mEGLDisplay, sync);
398 if (error != EGL_SUCCESS) {
399 ALOGE("failed to wait for EGL native fence sync: %#x", error);
400 return false;
401 }
402
403 return true;
404}
405
406static bool hasUsage(const AHardwareBuffer_Desc& desc, uint64_t usage) {
407 return !!(desc.usage & usage);
408}
409
Alec Mouri678245d2020-09-30 16:58:23 -0700410static float toDegrees(uint32_t transform) {
411 switch (transform) {
412 case ui::Transform::ROT_90:
413 return 90.0;
414 case ui::Transform::ROT_180:
415 return 180.0;
416 case ui::Transform::ROT_270:
417 return 270.0;
418 default:
419 return 0.0;
420 }
421}
422
Alec Mourib34f0b72020-10-02 13:18:34 -0700423static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
424 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
425 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
426 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
427 matrix[3][3], 0);
428}
429
Alec Mouri029d1952020-10-12 10:37:08 -0700430static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
431 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
432 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
433
434 // Treat unsupported dataspaces as srgb
435 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
436 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
437 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
438 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
439 }
440
441 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
442 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
443 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
444 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
445 }
446
447 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
448 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
449 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
450 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
451
452 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
453 sourceTransfer != destTransfer;
454}
455
Alec Mouri1a4d0642020-11-13 17:42:01 -0800456static bool needsLinearEffect(const mat4& colorTransform, ui::Dataspace sourceDataspace,
457 ui::Dataspace destinationDataspace) {
458 return colorTransform != mat4() || needsToneMapping(sourceDataspace, destinationDataspace);
459}
460
Ana Krulecdfec8f52021-01-13 12:51:47 -0800461void SkiaGLRenderEngine::cacheExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
462 // Only run this if RE is running on its own thread. This way the access to GL
463 // operations is guaranteed to be happening on the same thread.
464 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
465 return;
466 }
467 ATRACE_CALL();
468
469 std::lock_guard<std::mutex> lock(mRenderingMutex);
470 auto iter = mTextureCache.find(buffer->getId());
471 if (iter != mTextureCache.end()) {
472 ALOGV("Texture already exists in cache.");
473 return;
474 } else {
475 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
476 std::make_shared<AutoBackendTexture::LocalRef>();
477 imageTextureRef->setTexture(
478 new AutoBackendTexture(mGrContext.get(), buffer->toAHardwareBuffer(), false));
479 mTextureCache.insert({buffer->getId(), imageTextureRef});
480 }
481}
482
John Reck67b1e2b2020-08-26 13:17:24 -0700483void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800484 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700485 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800486 mTextureCache.erase(bufferId);
487 mProtectedTextureCache.erase(bufferId);
John Reck67b1e2b2020-08-26 13:17:24 -0700488}
489
Ana Krulec47814212021-01-06 19:00:10 -0800490sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
491 const LayerSettings* layer,
492 const DisplaySettings& display,
493 bool undoPremultipliedAlpha) {
494 if (mUseColorManagement &&
495 needsLinearEffect(layer->colorTransform, layer->sourceDataspace, display.outputDataspace)) {
496 LinearEffect effect = LinearEffect{.inputDataspace = layer->sourceDataspace,
497 .outputDataspace = display.outputDataspace,
498 .undoPremultipliedAlpha = undoPremultipliedAlpha};
499
500 auto effectIter = mRuntimeEffects.find(effect);
501 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
502 if (effectIter == mRuntimeEffects.end()) {
503 runtimeEffect = buildRuntimeEffect(effect);
504 mRuntimeEffects.insert({effect, runtimeEffect});
505 } else {
506 runtimeEffect = effectIter->second;
507 }
508 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
509 display.maxLuminance,
510 layer->source.buffer.maxMasteringLuminance,
511 layer->source.buffer.maxContentLuminance);
512 }
513 return shader;
514}
515
John Reck67b1e2b2020-08-26 13:17:24 -0700516status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
517 const std::vector<const LayerSettings*>& layers,
518 const sp<GraphicBuffer>& buffer,
519 const bool useFramebufferCache,
520 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
521 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800522
John Reck67b1e2b2020-08-26 13:17:24 -0700523 std::lock_guard<std::mutex> lock(mRenderingMutex);
524 if (layers.empty()) {
525 ALOGV("Drawing empty layer stack");
526 return NO_ERROR;
527 }
528
529 if (bufferFence.get() >= 0) {
530 // Duplicate the fence for passing to waitFence.
531 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
532 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
533 ATRACE_NAME("Waiting before draw");
534 sync_wait(bufferFence.get(), -1);
535 }
536 }
537 if (buffer == nullptr) {
538 ALOGE("No output buffer provided. Aborting GPU composition.");
539 return BAD_VALUE;
540 }
541
Lucas Dupind508e472020-11-04 04:32:06 +0000542 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800543 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700544 AHardwareBuffer_Desc bufferDesc;
545 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700546 LOG_ALWAYS_FATAL_IF(!hasUsage(bufferDesc, AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE),
547 "missing usage");
548
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800549 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
John Reck67b1e2b2020-08-26 13:17:24 -0700550 if (useFramebufferCache) {
Lucas Dupind508e472020-11-04 04:32:06 +0000551 auto iter = cache.find(buffer->getId());
552 if (iter != cache.end()) {
John Reck67b1e2b2020-08-26 13:17:24 -0700553 ALOGV("Cache hit!");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800554 ATRACE_NAME("Cache hit");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800555 surfaceTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700556 }
557 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800558
559 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800560 ATRACE_NAME("Cache miss");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800561 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
562 surfaceTextureRef->setTexture(
Alec Mouric0aae732021-01-12 13:32:18 -0800563 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), true));
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800564 if (useFramebufferCache) {
John Reck67b1e2b2020-08-26 13:17:24 -0700565 ALOGD("Adding to cache");
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800566 cache.insert({buffer->getId(), surfaceTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700567 }
568 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800569
570 sk_sp<SkSurface> surface =
571 surfaceTextureRef->getTexture()->getOrCreateSurface(mUseColorManagement
572 ? display.outputDataspace
Alec Mouric0aae732021-01-12 13:32:18 -0800573 : ui::Dataspace::UNKNOWN,
574 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700575
Alec Mouric0aae732021-01-12 13:32:18 -0800576 SkCanvas* canvas = mCapture->tryCapture(surface.get());
Ana Krulec6eab17a2020-12-09 15:52:36 -0800577 if (canvas == nullptr) {
578 ALOGE("Cannot acquire canvas from Skia.");
579 return BAD_VALUE;
580 }
Alec Mouri678245d2020-09-30 16:58:23 -0700581 // Clear the entire canvas with a transparent black to prevent ghost images.
582 canvas->clear(SK_ColorTRANSPARENT);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700583 canvas->save();
John Reck67b1e2b2020-08-26 13:17:24 -0700584
Alec Mouric0aae732021-01-12 13:32:18 -0800585 if (mCapture->isCaptureRunning()) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800586 // Record display settings when capture is running.
587 std::stringstream displaySettings;
588 PrintTo(display, &displaySettings);
589 // Store the DisplaySettings in additional information.
590 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
591 SkData::MakeWithCString(displaySettings.str().c_str()));
592 }
593
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700594 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
595 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
596 // displays might have different scaling when compared to the physical screen.
Alec Mouri678245d2020-09-30 16:58:23 -0700597
598 canvas->clipRect(getSkRect(display.physicalDisplay));
Galia Peychevaf7889b32020-11-25 22:22:40 +0100599 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700600
601 const auto clipWidth = display.clip.width();
602 const auto clipHeight = display.clip.height();
603 auto rotatedClipWidth = clipWidth;
604 auto rotatedClipHeight = clipHeight;
605 // Scale is contingent on the rotation result.
606 if (display.orientation & ui::Transform::ROT_90) {
607 std::swap(rotatedClipWidth, rotatedClipHeight);
608 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700609 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700610 static_cast<SkScalar>(rotatedClipWidth);
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700611 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
Alec Mouri678245d2020-09-30 16:58:23 -0700612 static_cast<SkScalar>(rotatedClipHeight);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100613 canvas->scale(scaleX, scaleY);
Alec Mouri678245d2020-09-30 16:58:23 -0700614
615 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
616 // back so that the top left corner of the clip is at (0, 0).
Galia Peychevaf7889b32020-11-25 22:22:40 +0100617 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
618 canvas->rotate(toDegrees(display.orientation));
619 canvas->translate(-clipWidth / 2, -clipHeight / 2);
620 canvas->translate(-display.clip.left, -display.clip.top);
Alec Mouric0aae732021-01-12 13:32:18 -0800621
622 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
623 // view is still on-screen. The clear region could be re-specified as a black color layer,
624 // however.
625 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500626 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800627 size_t numRects = 0;
628 Rect const* rects = display.clearRegion.getArray(&numRects);
629 SkIRect skRects[numRects];
630 for (int i = 0; i < numRects; ++i) {
631 skRects[i] =
632 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
633 }
634 SkRegion clearRegion;
635 SkPaint paint;
636 sk_sp<SkShader> shader =
637 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
638 toSkColorSpace(mUseColorManagement ? display.outputDataspace
639 : ui::Dataspace::UNKNOWN));
640 paint.setShader(shader);
641 clearRegion.setRects(skRects, numRects);
642 canvas->drawRegion(clearRegion, paint);
643 }
644
John Reck67b1e2b2020-08-26 13:17:24 -0700645 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500646 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100647 canvas->save();
648
Alec Mouric0aae732021-01-12 13:32:18 -0800649 if (mCapture->isCaptureRunning()) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800650 // Record the name of the layer if the capture is running.
651 std::stringstream layerSettings;
652 PrintTo(*layer, &layerSettings);
653 // Store the LayerSettings in additional information.
654 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
655 SkData::MakeWithCString(layerSettings.str().c_str()));
656 }
657
Galia Peychevaf7889b32020-11-25 22:22:40 +0100658 // Layers have a local transform that should be applied to them
659 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100660
Lucas Dupin21f348e2020-09-16 17:31:26 -0700661 SkPaint paint;
662 const auto& bounds = layer->geometry.boundaries;
Lucas Dupin3f11e922020-09-22 17:31:04 -0700663 const auto dest = getSkRect(bounds);
Galia Peychevaf7889b32020-11-25 22:22:40 +0100664 const auto layerRect = canvas->getTotalMatrix().mapRect(dest);
Derek Sollenberger545ec442021-01-25 10:02:23 -0500665 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
Lucas Dupinc3800b82020-10-02 16:24:48 -0700666 if (mBlurFilter) {
667 if (layer->backgroundBlurRadius > 0) {
668 ATRACE_NAME("BackgroundBlur");
Galia Peycheva80116e52020-11-06 11:57:25 +0100669 auto blurredSurface = mBlurFilter->generate(canvas, surface,
670 layer->backgroundBlurRadius, layerRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700671 cachedBlurs[layer->backgroundBlurRadius] = blurredSurface;
Galia Peycheva80116e52020-11-06 11:57:25 +0100672
Galia Peychevaf7889b32020-11-25 22:22:40 +0100673 drawBlurRegion(canvas, getBlurRegion(layer), layerRect, blurredSurface);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700674 }
675 if (layer->blurRegions.size() > 0) {
676 for (auto region : layer->blurRegions) {
677 if (cachedBlurs[region.blurRadius]) {
678 continue;
679 }
680 ATRACE_NAME("BlurRegion");
Galia Peycheva6c460652020-11-03 19:42:42 +0100681 auto blurredSurface =
682 mBlurFilter->generate(canvas, surface, region.blurRadius, layerRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700683 cachedBlurs[region.blurRadius] = blurredSurface;
684 }
685 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700686 }
687
Alec Mouric0aae732021-01-12 13:32:18 -0800688 const ui::Dataspace targetDataspace = mUseColorManagement
689 ? (needsLinearEffect(layer->colorTransform, layer->sourceDataspace,
690 display.outputDataspace)
691 // If we need to map to linear space, then mark the source image with the
692 // same colorspace as the destination surface so that Skia's color
693 // management is a no-op.
694 ? display.outputDataspace
695 : layer->sourceDataspace)
696 : ui::Dataspace::UNKNOWN;
697
John Reck67b1e2b2020-08-26 13:17:24 -0700698 if (layer->source.buffer.buffer) {
699 ATRACE_NAME("DrawImage");
700 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800701 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
702 auto iter = mTextureCache.find(item.buffer->getId());
703 if (iter != mTextureCache.end()) {
704 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700705 } else {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800706 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
Alec Mouric0aae732021-01-12 13:32:18 -0800707 imageTextureRef->setTexture(new AutoBackendTexture(grContext.get(),
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800708 item.buffer->toAHardwareBuffer(),
709 false));
Alec Mouric0aae732021-01-12 13:32:18 -0800710 mTextureCache.insert({item.buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700711 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800712
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800713 sk_sp<SkImage> image =
Alec Mouric0aae732021-01-12 13:32:18 -0800714 imageTextureRef->getTexture()->makeImage(targetDataspace,
715 item.usePremultipliedAlpha
716 ? kPremul_SkAlphaType
717 : kUnpremul_SkAlphaType,
718 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700719
720 auto texMatrix = getSkM44(item.textureTransform).asM33();
721 // textureTansform was intended to be passed directly into a shader, so when
722 // building the total matrix with the textureTransform we need to first
723 // normalize it, then apply the textureTransform, then scale back up.
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800724 texMatrix.preScale(1.0f / bounds.getWidth(), 1.0f / bounds.getHeight());
725 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700726
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800727 SkMatrix matrix;
728 if (!texMatrix.invert(&matrix)) {
729 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700730 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800731 // The shader does not respect the translation, so we add it to the texture
732 // transform for the SkImage. This will make sure that the correct layer contents
733 // are drawn in the correct part of the screen.
734 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700735
Ana Krulecb7b28b22020-11-23 14:48:58 -0800736 sk_sp<SkShader> shader;
737
738 if (layer->source.buffer.useTextureFiltering) {
739 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
740 SkSamplingOptions(
741 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
742 &matrix);
743 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500744 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800745 }
Alec Mouri029d1952020-10-12 10:37:08 -0700746
Alec Mouric0aae732021-01-12 13:32:18 -0800747 // Handle opaque images - it's a little nonstandard how we do this.
748 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
749 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
750 // The important language is that when isOpaque is set, opacity is not sampled from the
751 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
752 // here's the conundrum:
753 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
754 // as an internal hint - composition is undefined when there are alpha bits present.
755 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
756 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
757 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
758 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
759 // of a hack anyways.
760 // 3. We can't change the blendmode to src, because while this satisfies the requirement
761 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
762 // because src always clobbers the destination content.
763 //
764 // So, what we do here instead is an additive blend mode where we compose the input
765 // image with a solid black. This might need to be reassess if this does not support
766 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
767 if (item.isOpaque) {
768 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
769 SkShaders::Color(SkColors::kBlack,
770 toSkColorSpace(targetDataspace)));
771 }
772
Ana Krulec47814212021-01-06 19:00:10 -0800773 paint.setShader(
774 createRuntimeEffectShader(shader, layer, display,
775 !item.isOpaque && item.usePremultipliedAlpha));
Ana Krulec1768bd22020-11-23 14:51:31 -0800776 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700777 } else {
778 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700779 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800780 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
781 .fG = color.g,
782 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800783 .fA = layer->alpha},
784 toSkColorSpace(targetDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800785 paint.setShader(createRuntimeEffectShader(shader, layer, display,
786 /* undoPremultipliedAlpha */ false));
John Reck67b1e2b2020-08-26 13:17:24 -0700787 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700788
Alec Mouri4ce5ec02021-01-07 17:33:21 -0800789 sk_sp<SkColorFilter> filter =
790 SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
791
Alec Mouri4ce5ec02021-01-07 17:33:21 -0800792 paint.setColorFilter(filter);
Alec Mourib34f0b72020-10-02 13:18:34 -0700793
Lucas Dupinc3800b82020-10-02 16:24:48 -0700794 for (const auto effectRegion : layer->blurRegions) {
Galia Peychevaf7889b32020-11-25 22:22:40 +0100795 drawBlurRegion(canvas, effectRegion, layerRect, cachedBlurs[effectRegion.blurRadius]);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700796 }
797
Lucas Dupin3f11e922020-09-22 17:31:04 -0700798 if (layer->shadow.length > 0) {
799 const auto rect = layer->geometry.roundedCornersRadius > 0
800 ? getSkRect(layer->geometry.roundedCornersCrop)
801 : dest;
802 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800803 } else {
804 // Shadows are assumed to live only on their own layer - it's not valid
805 // to draw the boundary retangles when there is already a caster shadow
806 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
807 // composition - using a well-defined invalid color is long-term less error-prone.
808 // Push the clipRRect onto the clip stack. Draw the image. Pop the clip.
809 if (layer->geometry.roundedCornersRadius > 0) {
810 canvas->clipRRect(getRoundedRect(layer), true);
811 }
812 canvas->drawRect(dest, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700813 }
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700814 canvas->restore();
John Reck67b1e2b2020-08-26 13:17:24 -0700815 }
Ana Krulec70d15b1b2020-12-01 10:05:15 -0800816 canvas->restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800817 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700818 {
819 ATRACE_NAME("flush surface");
820 surface->flush();
821 }
822
823 if (drawFence != nullptr) {
824 *drawFence = flush();
825 }
826
827 // If flush failed or we don't support native fences, we need to force the
828 // gl command stream to be executed.
829 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
830 if (requireSync) {
831 ATRACE_BEGIN("Submit(sync=true)");
832 } else {
833 ATRACE_BEGIN("Submit(sync=false)");
834 }
Lucas Dupind508e472020-11-04 04:32:06 +0000835 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -0700836 ATRACE_END();
837 if (!success) {
838 ALOGE("Failed to flush RenderEngine commands");
839 // Chances are, something illegal happened (either the caller passed
840 // us bad parameters, or we messed up our shader generation).
841 return INVALID_OPERATION;
842 }
843
844 // checkErrors();
845 return NO_ERROR;
846}
847
Lucas Dupin3f11e922020-09-22 17:31:04 -0700848inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
849 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
850}
851
852inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
853 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
854}
855
Lucas Dupin21f348e2020-09-16 17:31:26 -0700856inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -0800857 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -0700858 const auto cornerRadius = layer->geometry.roundedCornersRadius;
859 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
860}
861
Galia Peycheva80116e52020-11-06 11:57:25 +0100862inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
863 const auto rect = getSkRect(layer->geometry.boundaries);
864 const auto cornersRadius = layer->geometry.roundedCornersRadius;
865 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
866 .cornerRadiusTL = cornersRadius,
867 .cornerRadiusTR = cornersRadius,
868 .cornerRadiusBL = cornersRadius,
869 .cornerRadiusBR = cornersRadius,
870 .alpha = 1,
871 .left = static_cast<int>(rect.fLeft),
872 .top = static_cast<int>(rect.fTop),
873 .right = static_cast<int>(rect.fRight),
874 .bottom = static_cast<int>(rect.fBottom)};
875}
876
Lucas Dupin3f11e922020-09-22 17:31:04 -0700877inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
878 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
879}
880
Lucas Dupinbb1a1d42020-09-18 15:17:02 -0700881inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
882 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
883 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
884 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
885 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
886}
887
Lucas Dupin3f11e922020-09-22 17:31:04 -0700888inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
889 return SkPoint3::Make(vector.x, vector.y, vector.z);
890}
891
John Reck67b1e2b2020-08-26 13:17:24 -0700892size_t SkiaGLRenderEngine::getMaxTextureSize() const {
893 return mGrContext->maxTextureSize();
894}
895
896size_t SkiaGLRenderEngine::getMaxViewportDims() const {
897 return mGrContext->maxRenderTargetSize();
898}
899
Lucas Dupin3f11e922020-09-22 17:31:04 -0700900void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
901 const ShadowSettings& settings) {
902 ATRACE_CALL();
903 const float casterZ = settings.length / 2.0f;
904 const auto shadowShape = cornerRadius > 0
905 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
906 : SkPath::Rect(casterRect);
907 const auto flags =
908 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
909
910 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
911 getSkPoint3(settings.lightPos), settings.lightRadius,
912 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
913 flags);
914}
915
Lucas Dupinc3800b82020-10-02 16:24:48 -0700916void SkiaGLRenderEngine::drawBlurRegion(SkCanvas* canvas, const BlurRegion& effectRegion,
Derek Sollenberger545ec442021-01-25 10:02:23 -0500917 const SkRect& layerRect, sk_sp<SkImage> blurredImage) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700918 ATRACE_CALL();
Galia Peycheva80116e52020-11-06 11:57:25 +0100919
Lucas Dupinc3800b82020-10-02 16:24:48 -0700920 SkPaint paint;
Lyn Han1bdedb32020-11-23 20:33:57 +0000921 paint.setAlpha(static_cast<int>(effectRegion.alpha * 255));
Robin Leef180f412020-12-07 02:51:41 +0100922 const auto matrix = getBlurShaderTransform(canvas, layerRect);
Derek Sollenberger545ec442021-01-25 10:02:23 -0500923 SkSamplingOptions linearSampling(SkFilterMode::kLinear, SkMipmapMode::kNone);
924 paint.setShader(blurredImage->makeShader(SkTileMode::kClamp, SkTileMode::kClamp, linearSampling,
925 &matrix));
Lucas Dupinc3800b82020-10-02 16:24:48 -0700926
Galia Peycheva80116e52020-11-06 11:57:25 +0100927 auto rect = SkRect::MakeLTRB(effectRegion.left, effectRegion.top, effectRegion.right,
928 effectRegion.bottom);
Galia Peycheva80116e52020-11-06 11:57:25 +0100929
Lucas Dupinc3800b82020-10-02 16:24:48 -0700930 if (effectRegion.cornerRadiusTL > 0 || effectRegion.cornerRadiusTR > 0 ||
931 effectRegion.cornerRadiusBL > 0 || effectRegion.cornerRadiusBR > 0) {
932 const SkVector radii[4] =
933 {SkVector::Make(effectRegion.cornerRadiusTL, effectRegion.cornerRadiusTL),
934 SkVector::Make(effectRegion.cornerRadiusTR, effectRegion.cornerRadiusTR),
935 SkVector::Make(effectRegion.cornerRadiusBL, effectRegion.cornerRadiusBL),
936 SkVector::Make(effectRegion.cornerRadiusBR, effectRegion.cornerRadiusBR)};
937 SkRRect roundedRect;
938 roundedRect.setRectRadii(rect, radii);
939 canvas->drawRRect(roundedRect, paint);
940 } else {
941 canvas->drawRect(rect, paint);
942 }
943}
944
Galia Peychevaf7889b32020-11-25 22:22:40 +0100945SkMatrix SkiaGLRenderEngine::getBlurShaderTransform(const SkCanvas* canvas,
946 const SkRect& layerRect) {
947 // 1. Apply the blur shader matrix, which scales up the blured surface to its real size
948 auto matrix = mBlurFilter->getShaderMatrix();
949 // 2. Since the blurred surface has the size of the layer, we align it with the
950 // top left corner of the layer position.
951 matrix.postConcat(SkMatrix::Translate(layerRect.fLeft, layerRect.fTop));
952 // 3. Finally, apply the inverse canvas matrix. The snapshot made in the BlurFilter is in the
953 // original surface orientation. The inverse matrix has to be applied to align the blur
954 // surface with the current orientation/position of the canvas.
955 SkMatrix drawInverse;
956 if (canvas->getTotalMatrix().invert(&drawInverse)) {
957 matrix.postConcat(drawInverse);
958 }
959
960 return matrix;
961}
962
John Reck67b1e2b2020-08-26 13:17:24 -0700963EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -0800964 EGLContext shareContext,
965 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -0700966 Protection protection) {
967 EGLint renderableType = 0;
968 if (config == EGL_NO_CONFIG_KHR) {
969 renderableType = EGL_OPENGL_ES3_BIT;
970 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
971 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
972 }
973 EGLint contextClientVersion = 0;
974 if (renderableType & EGL_OPENGL_ES3_BIT) {
975 contextClientVersion = 3;
976 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
977 contextClientVersion = 2;
978 } else if (renderableType & EGL_OPENGL_ES_BIT) {
979 contextClientVersion = 1;
980 } else {
981 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
982 }
983
984 std::vector<EGLint> contextAttributes;
985 contextAttributes.reserve(7);
986 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
987 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -0800988 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -0700989 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -0800990 switch (*contextPriority) {
991 case ContextPriority::REALTIME:
992 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
993 break;
994 case ContextPriority::MEDIUM:
995 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
996 break;
997 case ContextPriority::LOW:
998 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
999 break;
1000 case ContextPriority::HIGH:
1001 default:
1002 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1003 break;
1004 }
John Reck67b1e2b2020-08-26 13:17:24 -07001005 }
1006 if (protection == Protection::PROTECTED) {
1007 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1008 contextAttributes.push_back(EGL_TRUE);
1009 }
1010 contextAttributes.push_back(EGL_NONE);
1011
1012 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1013
1014 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1015 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1016 // EGL_NO_CONTEXT so that we can abort.
1017 if (config != EGL_NO_CONFIG_KHR) {
1018 return context;
1019 }
1020 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1021 // should try to fall back to GLES 2.
1022 contextAttributes[1] = 2;
1023 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1024 }
1025
1026 return context;
1027}
1028
Alec Mourid6f09462020-12-07 11:18:17 -08001029std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1030 const RenderEngineCreationArgs& args) {
1031 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1032 return std::nullopt;
1033 }
1034
1035 switch (args.contextPriority) {
1036 case RenderEngine::ContextPriority::REALTIME:
1037 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1038 return RenderEngine::ContextPriority::REALTIME;
1039 } else {
1040 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1041 return RenderEngine::ContextPriority::HIGH;
1042 }
1043 case RenderEngine::ContextPriority::HIGH:
1044 case RenderEngine::ContextPriority::MEDIUM:
1045 case RenderEngine::ContextPriority::LOW:
1046 return args.contextPriority;
1047 default:
1048 return std::nullopt;
1049 }
1050}
1051
John Reck67b1e2b2020-08-26 13:17:24 -07001052EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1053 EGLConfig config, int hwcFormat,
1054 Protection protection) {
1055 EGLConfig placeholderConfig = config;
1056 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1057 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1058 }
1059 std::vector<EGLint> attributes;
1060 attributes.reserve(7);
1061 attributes.push_back(EGL_WIDTH);
1062 attributes.push_back(1);
1063 attributes.push_back(EGL_HEIGHT);
1064 attributes.push_back(1);
1065 if (protection == Protection::PROTECTED) {
1066 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1067 attributes.push_back(EGL_TRUE);
1068 }
1069 attributes.push_back(EGL_NONE);
1070
1071 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1072}
1073
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001074void SkiaGLRenderEngine::cleanFramebufferCache() {}
John Reck67b1e2b2020-08-26 13:17:24 -07001075
Alec Mourid6f09462020-12-07 11:18:17 -08001076int SkiaGLRenderEngine::getContextPriority() {
1077 int value;
1078 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1079 return value;
1080}
1081
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001082void SkiaGLRenderEngine::dump(std::string& result) {
1083 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1084
1085 StringAppendF(&result, "\n ------------RE-----------------\n");
1086 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1087 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1088 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1089 extensions.getVersion());
1090 StringAppendF(&result, "%s\n", extensions.getExtensions());
1091 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1092 supportsProtectedContent());
1093 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
1094
1095 {
1096 std::lock_guard<std::mutex> lock(mRenderingMutex);
1097 StringAppendF(&result, "RenderEngine texture cache size: %zu\n", mTextureCache.size());
1098 StringAppendF(&result, "Dumping buffer ids...\n");
1099 // TODO(178539829): It would be nice to know which layer these are coming from and what
1100 // the texture sizes are.
1101 for (const auto& [id, unused] : mTextureCache) {
1102 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1103 }
1104 StringAppendF(&result, "\n");
1105 StringAppendF(&result, "RenderEngine protected texture cache size: %zu\n",
1106 mProtectedTextureCache.size());
1107 StringAppendF(&result, "Dumping buffer ids...\n");
1108 for (const auto& [id, unused] : mProtectedTextureCache) {
1109 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1110 }
1111 StringAppendF(&result, "\n");
1112 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1113 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1114 StringAppendF(&result, "- inputDataspace: %s\n",
1115 dataspaceDetails(
1116 static_cast<android_dataspace>(linearEffect.inputDataspace))
1117 .c_str());
1118 StringAppendF(&result, "- outputDataspace: %s\n",
1119 dataspaceDetails(
1120 static_cast<android_dataspace>(linearEffect.outputDataspace))
1121 .c_str());
1122 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1123 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1124 }
1125 }
1126 StringAppendF(&result, "\n");
1127}
1128
John Reck67b1e2b2020-08-26 13:17:24 -07001129} // namespace skia
1130} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001131} // namespace android