blob: d4b139c59e17551efdbcd1de8babbe852449675b [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>
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040031#include <SkGraphics.h>
John Reck67b1e2b2020-08-26 13:17:24 -070032#include <SkImage.h>
Lucas Dupinf4cb4a02020-09-22 14:19:26 -070033#include <SkImageFilters.h>
Alec Mouric0aae732021-01-12 13:32:18 -080034#include <SkRegion.h>
Lucas Dupin3f11e922020-09-22 17:31:04 -070035#include <SkShadowUtils.h>
John Reck67b1e2b2020-08-26 13:17:24 -070036#include <SkSurface.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080037#include <android-base/stringprintf.h>
Alec Mourib5777452020-09-28 11:32:42 -070038#include <gl/GrGLInterface.h>
Alec Mouricbd30932021-06-09 15:52:25 -070039#include <gui/TraceUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080040#include <sync/sync.h>
41#include <ui/BlurRegion.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080042#include <ui/DebugUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080043#include <ui/GraphicBuffer.h>
44#include <utils/Trace.h>
Alec Mourib5777452020-09-28 11:32:42 -070045
46#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080047#include <cstdint>
48#include <memory>
49
50#include "../gl/GLExtensions.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040051#include "Cache.h"
Alec Mouric0aae732021-01-12 13:32:18 -080052#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080053#include "SkBlendMode.h"
54#include "SkImageInfo.h"
55#include "filters/BlurFilter.h"
56#include "filters/LinearEffect.h"
57#include "log/log_main.h"
58#include "skia/debug/SkiaCapture.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040059#include "skia/debug/SkiaMemoryReporter.h"
Nader Jawad2dfc98b2021-04-08 20:35:39 -070060#include "skia/filters/StretchShaderFactory.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080061#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070062
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040063namespace {
64// Debugging settings
65static const bool kPrintLayerSettings = false;
66static const bool kFlushAfterEveryLayer = false;
67} // namespace
68
John Reck67b1e2b2020-08-26 13:17:24 -070069bool checkGlError(const char* op, int lineNumber);
70
71namespace android {
72namespace renderengine {
73namespace skia {
74
Ana Krulec1d12b3b2021-01-27 16:49:51 -080075using base::StringAppendF;
76
John Reck67b1e2b2020-08-26 13:17:24 -070077static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
78 EGLint wanted, EGLConfig* outConfig) {
79 EGLint numConfigs = -1, n = 0;
80 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
81 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
82 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
83 configs.resize(n);
84
85 if (!configs.empty()) {
86 if (attribute != EGL_NONE) {
87 for (EGLConfig config : configs) {
88 EGLint value = 0;
89 eglGetConfigAttrib(dpy, config, attribute, &value);
90 if (wanted == value) {
91 *outConfig = config;
92 return NO_ERROR;
93 }
94 }
95 } else {
96 // just pick the first one
97 *outConfig = configs[0];
98 return NO_ERROR;
99 }
100 }
101
102 return NAME_NOT_FOUND;
103}
104
105static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
106 EGLConfig* config) {
107 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
108 // it is to be used with WIFI displays
109 status_t err;
110 EGLint wantedAttribute;
111 EGLint wantedAttributeValue;
112
113 std::vector<EGLint> attribs;
114 if (renderableType) {
115 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
116 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
117
118 // Default to 8 bits per channel.
119 const EGLint tmpAttribs[] = {
120 EGL_RENDERABLE_TYPE,
121 renderableType,
122 EGL_RECORDABLE_ANDROID,
123 EGL_TRUE,
124 EGL_SURFACE_TYPE,
125 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
126 EGL_FRAMEBUFFER_TARGET_ANDROID,
127 EGL_TRUE,
128 EGL_RED_SIZE,
129 is1010102 ? 10 : 8,
130 EGL_GREEN_SIZE,
131 is1010102 ? 10 : 8,
132 EGL_BLUE_SIZE,
133 is1010102 ? 10 : 8,
134 EGL_ALPHA_SIZE,
135 is1010102 ? 2 : 8,
136 EGL_NONE,
137 };
138 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
139 std::back_inserter(attribs));
140 wantedAttribute = EGL_NONE;
141 wantedAttributeValue = EGL_NONE;
142 } else {
143 // if no renderable type specified, fallback to a simplified query
144 wantedAttribute = EGL_NATIVE_VISUAL_ID;
145 wantedAttributeValue = format;
146 }
147
148 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
149 config);
150 if (err == NO_ERROR) {
151 EGLint caveat;
152 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
153 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
154 }
155
156 return err;
157}
158
159std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
160 const RenderEngineCreationArgs& args) {
161 // initialize EGL for the default display
162 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
163 if (!eglInitialize(display, nullptr, nullptr)) {
164 LOG_ALWAYS_FATAL("failed to initialize EGL");
165 }
166
Yiwei Zhange2650962020-12-01 23:27:58 +0000167 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700168 if (!eglVersion) {
169 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000170 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700171 }
172
Yiwei Zhange2650962020-12-01 23:27:58 +0000173 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700174 if (!eglExtensions) {
175 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000176 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700177 }
178
179 auto& extensions = gl::GLExtensions::getInstance();
180 extensions.initWithEGLStrings(eglVersion, eglExtensions);
181
182 // The code assumes that ES2 or later is available if this extension is
183 // supported.
184 EGLConfig config = EGL_NO_CONFIG_KHR;
185 if (!extensions.hasNoConfigContext()) {
186 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
187 }
188
John Reck67b1e2b2020-08-26 13:17:24 -0700189 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800190 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700191 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800192 protectedContext =
193 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700194 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
195 }
196
Alec Mourid6f09462020-12-07 11:18:17 -0800197 EGLContext ctxt =
198 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700199
200 // if can't create a GL context, we can only abort.
201 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
202
203 EGLSurface placeholder = EGL_NO_SURFACE;
204 if (!extensions.hasSurfacelessContext()) {
205 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
206 Protection::UNPROTECTED);
207 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
208 }
209 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
210 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
211 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
212 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
213
214 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
215 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
216 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
217 Protection::PROTECTED);
218 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
219 "can't create protected placeholder pbuffer");
220 }
221
222 // initialize the renderer while GL is current
223 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000224 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
225 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700226
227 ALOGI("OpenGL ES informations:");
228 ALOGI("vendor : %s", extensions.getVendor());
229 ALOGI("renderer : %s", extensions.getRenderer());
230 ALOGI("version : %s", extensions.getVersion());
231 ALOGI("extensions: %s", extensions.getExtensions());
232 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
233 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
234
235 return engine;
236}
237
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500238void SkiaGLRenderEngine::primeCache() {
239 Cache::primeShaderCache(this);
240}
241
John Reck67b1e2b2020-08-26 13:17:24 -0700242EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
243 status_t err;
244 EGLConfig config;
245
246 // First try to get an ES3 config
247 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
248 if (err != NO_ERROR) {
249 // If ES3 fails, try to get an ES2 config
250 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
251 if (err != NO_ERROR) {
252 // If ES2 still doesn't work, probably because we're on the emulator.
253 // try a simplified query
254 ALOGW("no suitable EGLConfig found, trying a simpler query");
255 err = selectEGLConfig(display, format, 0, &config);
256 if (err != NO_ERROR) {
257 // this EGL is too lame for android
258 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
259 }
260 }
261 }
262
263 if (logConfig) {
264 // print some debugging info
265 EGLint r, g, b, a;
266 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
267 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
268 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
269 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
270 ALOGI("EGL information:");
271 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
272 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
273 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
274 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
275 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
276 }
277
278 return config;
279}
280
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400281sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
282 // This "cache" does not actually cache anything. It just allows us to
283 // monitor Skia's internal cache. So this method always returns null.
284 return nullptr;
285}
286
287void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
288 const SkString& description) {
289 mShadersCachedSinceLastCall++;
290}
291
292void SkiaGLRenderEngine::assertShadersCompiled(int numShaders) {
293 const int cached = mSkSLCacheMonitor.shadersCachedSinceLastCall();
294 LOG_ALWAYS_FATAL_IF(cached != numShaders, "Attempted to cache %i shaders; cached %i",
295 numShaders, cached);
296}
297
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400298int SkiaGLRenderEngine::reportShadersCompiled() {
299 return mSkSLCacheMonitor.shadersCachedSinceLastCall();
300}
301
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700302SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000303 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700304 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800305 : SkiaRenderEngine(args.renderEngineType),
306 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700307 mEGLContext(ctxt),
308 mPlaceholderSurface(placeholder),
309 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700310 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400311 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800312 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700313 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
314 LOG_ALWAYS_FATAL_IF(!glInterface.get());
315
316 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400317 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700318 options.fDisableDistanceFieldPaths = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400319 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000320 mGrContext = GrDirectContext::MakeGL(glInterface, options);
321 if (useProtectedContext(true)) {
322 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
323 useProtectedContext(false);
324 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700325
326 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500327 ALOGD("Background Blurs Enabled");
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700328 mBlurFilter = new BlurFilter();
329 }
Alec Mouric0aae732021-01-12 13:32:18 -0800330 mCapture = std::make_unique<SkiaCapture>();
331}
332
333SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100334 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800335 if (mBlurFilter) {
336 delete mBlurFilter;
337 }
338
339 mCapture = nullptr;
340
341 mGrContext->flushAndSubmit(true);
342 mGrContext->abandonContext();
343
344 if (mProtectedGrContext) {
345 mProtectedGrContext->flushAndSubmit(true);
346 mProtectedGrContext->abandonContext();
347 }
348
349 if (mPlaceholderSurface != EGL_NO_SURFACE) {
350 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
351 }
352 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
353 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
354 }
355 if (mEGLContext != EGL_NO_CONTEXT) {
356 eglDestroyContext(mEGLDisplay, mEGLContext);
357 }
358 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
359 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
360 }
361 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
362 eglTerminate(mEGLDisplay);
363 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700364}
365
Lucas Dupind508e472020-11-04 04:32:06 +0000366bool SkiaGLRenderEngine::supportsProtectedContent() const {
367 return mProtectedEGLContext != EGL_NO_CONTEXT;
368}
369
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400370GrDirectContext* SkiaGLRenderEngine::getActiveGrContext() const {
371 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
372}
373
Lucas Dupind508e472020-11-04 04:32:06 +0000374bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
375 if (useProtectedContext == mInProtectedContext) {
376 return true;
377 }
Alec Mourif6a07812021-02-11 21:07:55 -0800378 if (useProtectedContext && !supportsProtectedContent()) {
Lucas Dupind508e472020-11-04 04:32:06 +0000379 return false;
380 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400381
382 // release any scratch resources before switching into a new mode
383 if (getActiveGrContext()) {
384 getActiveGrContext()->purgeUnlockedResources(true);
385 }
386
Lucas Dupind508e472020-11-04 04:32:06 +0000387 const EGLSurface surface =
388 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
389 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
390 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800391
Lucas Dupind508e472020-11-04 04:32:06 +0000392 if (success) {
393 mInProtectedContext = useProtectedContext;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400394 // given that we are sharing the same thread between two GrContexts we need to
395 // make sure that the thread state is reset when switching between the two.
396 if (getActiveGrContext()) {
397 getActiveGrContext()->resetContext();
398 }
Lucas Dupind508e472020-11-04 04:32:06 +0000399 }
400 return success;
401}
402
John Reck67b1e2b2020-08-26 13:17:24 -0700403base::unique_fd SkiaGLRenderEngine::flush() {
404 ATRACE_CALL();
405 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
406 return base::unique_fd();
407 }
408
409 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
410 if (sync == EGL_NO_SYNC_KHR) {
411 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
412 return base::unique_fd();
413 }
414
415 // native fence fd will not be populated until flush() is done.
416 glFlush();
417
418 // get the fence fd
419 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
420 eglDestroySyncKHR(mEGLDisplay, sync);
421 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
422 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
423 }
424
425 return fenceFd;
426}
427
428bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
429 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
430 !gl::GLExtensions::getInstance().hasWaitSync()) {
431 return false;
432 }
433
434 // release the fd and transfer the ownership to EGLSync
435 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
436 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
437 if (sync == EGL_NO_SYNC_KHR) {
438 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
439 return false;
440 }
441
442 // XXX: The spec draft is inconsistent as to whether this should return an
443 // EGLint or void. Ignore the return value for now, as it's not strictly
444 // needed.
445 eglWaitSyncKHR(mEGLDisplay, sync, 0);
446 EGLint error = eglGetError();
447 eglDestroySyncKHR(mEGLDisplay, sync);
448 if (error != EGL_SUCCESS) {
449 ALOGE("failed to wait for EGL native fence sync: %#x", error);
450 return false;
451 }
452
453 return true;
454}
455
Alec Mouri678245d2020-09-30 16:58:23 -0700456static float toDegrees(uint32_t transform) {
457 switch (transform) {
458 case ui::Transform::ROT_90:
459 return 90.0;
460 case ui::Transform::ROT_180:
461 return 180.0;
462 case ui::Transform::ROT_270:
463 return 270.0;
464 default:
465 return 0.0;
466 }
467}
468
Alec Mourib34f0b72020-10-02 13:18:34 -0700469static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
470 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
471 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
472 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
473 matrix[3][3], 0);
474}
475
Alec Mouri029d1952020-10-12 10:37:08 -0700476static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
477 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
478 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
479
480 // Treat unsupported dataspaces as srgb
481 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
482 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
483 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
484 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
485 }
486
487 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
488 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
489 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
490 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
491 }
492
493 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
494 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
495 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
496 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
497
498 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
499 sourceTransfer != destTransfer;
500}
501
Alec Mouria90a5702021-04-16 16:36:21 +0000502void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
503 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800504 // Only run this if RE is running on its own thread. This way the access to GL
505 // operations is guaranteed to be happening on the same thread.
506 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
507 return;
508 }
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400509 // We currently don't attempt to map a buffer if the buffer contains protected content
510 // or we are using a protected context because GPU resources for protected buffers is
511 // much more limited.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400512 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400513 if (isProtectedBuffer || mInProtectedContext) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400514 return;
515 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800516 ATRACE_CALL();
517
Derek Sollenberger0ad873b2021-05-05 11:35:52 -0400518 // If we were to support caching protected buffers then we will need to switch the currently
519 // bound context if we are not already using the protected context (and subsequently switch
520 // back after the buffer is cached).
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400521 auto grContext = getActiveGrContext();
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400522 auto& cache = mTextureCache;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400523
524 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000525 mGraphicBufferExternalRefs[buffer->getId()]++;
526
527 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800528 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400529 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400530 buffer->toAHardwareBuffer(),
531 isRenderable);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400532 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800533 }
534}
535
Alec Mouria90a5702021-04-16 16:36:21 +0000536void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800537 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700538 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000539 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
540 iter != mGraphicBufferExternalRefs.end()) {
541 if (iter->second == 0) {
542 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
543 "> from RenderEngine texture, but the "
544 "ref count was already zero!",
545 buffer->getId());
546 mGraphicBufferExternalRefs.erase(buffer->getId());
547 return;
548 }
549
550 iter->second--;
551
552 if (iter->second == 0) {
553 mTextureCache.erase(buffer->getId());
554 mProtectedTextureCache.erase(buffer->getId());
555 mGraphicBufferExternalRefs.erase(buffer->getId());
556 }
557 }
John Reck67b1e2b2020-08-26 13:17:24 -0700558}
559
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700560sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
561 sk_sp<SkShader> shader,
562 const LayerSettings* layer, const DisplaySettings& display, bool undoPremultipliedAlpha,
563 bool requiresLinearEffect) {
564 const auto stretchEffect = layer->stretchEffect;
Nader Jawad63644d32021-05-07 10:44:21 -0700565 // The given surface will be stretched by HWUI via matrix transformation
566 // which gets similar results for most surfaces
567 // Determine later on if we need to leverage the stertch shader within
568 // surface flinger
Nader Jawadc088bdc2021-05-10 13:24:46 -0700569 if (stretchEffect.hasEffect()) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700570 const auto targetBuffer = layer->source.buffer.buffer;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700571 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
572 if (graphicBuffer && shader) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700573 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
574 }
John Reckcdb4ed72021-02-04 13:39:33 -0500575 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700576
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500577 if (requiresLinearEffect) {
578 const ui::Dataspace inputDataspace =
579 mUseColorManagement ? layer->sourceDataspace : ui::Dataspace::UNKNOWN;
580 const ui::Dataspace outputDataspace =
581 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
582
583 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
584 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800585 .undoPremultipliedAlpha = undoPremultipliedAlpha};
586
587 auto effectIter = mRuntimeEffects.find(effect);
588 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
589 if (effectIter == mRuntimeEffects.end()) {
590 runtimeEffect = buildRuntimeEffect(effect);
591 mRuntimeEffects.insert({effect, runtimeEffect});
592 } else {
593 runtimeEffect = effectIter->second;
594 }
John Reckac09e452021-04-07 16:35:37 -0400595 float maxLuminance = layer->source.buffer.maxLuminanceNits;
596 // If the buffer doesn't have a max luminance, treat it as SDR & use the display's SDR
597 // white point
598 if (maxLuminance <= 0.f) {
599 maxLuminance = display.sdrWhitePointNits;
600 }
Ana Krulec47814212021-01-06 19:00:10 -0800601 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
John Reckac09e452021-04-07 16:35:37 -0400602 display.maxLuminance, maxLuminance);
Ana Krulec47814212021-01-06 19:00:10 -0800603 }
604 return shader;
605}
606
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500607void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500608 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500609 // Record display settings when capture is running.
610 std::stringstream displaySettings;
611 PrintTo(display, &displaySettings);
612 // Store the DisplaySettings in additional information.
613 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
614 SkData::MakeWithCString(displaySettings.str().c_str()));
615 }
616
617 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
618 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
619 // displays might have different scaling when compared to the physical screen.
620
621 canvas->clipRect(getSkRect(display.physicalDisplay));
622 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
623
624 const auto clipWidth = display.clip.width();
625 const auto clipHeight = display.clip.height();
626 auto rotatedClipWidth = clipWidth;
627 auto rotatedClipHeight = clipHeight;
628 // Scale is contingent on the rotation result.
629 if (display.orientation & ui::Transform::ROT_90) {
630 std::swap(rotatedClipWidth, rotatedClipHeight);
631 }
632 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
633 static_cast<SkScalar>(rotatedClipWidth);
634 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
635 static_cast<SkScalar>(rotatedClipHeight);
636 canvas->scale(scaleX, scaleY);
637
638 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
639 // back so that the top left corner of the clip is at (0, 0).
640 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
641 canvas->rotate(toDegrees(display.orientation));
642 canvas->translate(-clipWidth / 2, -clipHeight / 2);
643 canvas->translate(-display.clip.left, -display.clip.top);
644}
645
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500646class AutoSaveRestore {
647public:
648 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
649 ~AutoSaveRestore() { restore(); }
650 void replace(SkCanvas* canvas) {
651 mCanvas = canvas;
652 mSaveCount = canvas->save();
653 }
654 void restore() {
655 if (mCanvas) {
656 mCanvas->restoreToCount(mSaveCount);
657 mCanvas = nullptr;
658 }
659 }
660
661private:
662 SkCanvas* mCanvas;
663 int mSaveCount;
664};
665
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400666static SkRRect getBlurRRect(const BlurRegion& region) {
667 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
668 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
669 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
670 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
671 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
672 SkRRect roundedRect;
673 roundedRect.setRectRadii(rect, radii);
674 return roundedRect;
675}
676
John Reck67b1e2b2020-08-26 13:17:24 -0700677status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
678 const std::vector<const LayerSettings*>& layers,
Alec Mouria90a5702021-04-16 16:36:21 +0000679 const std::shared_ptr<ExternalTexture>& buffer,
680 const bool /*useFramebufferCache*/,
John Reck67b1e2b2020-08-26 13:17:24 -0700681 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
682 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800683
John Reck67b1e2b2020-08-26 13:17:24 -0700684 std::lock_guard<std::mutex> lock(mRenderingMutex);
685 if (layers.empty()) {
686 ALOGV("Drawing empty layer stack");
687 return NO_ERROR;
688 }
689
690 if (bufferFence.get() >= 0) {
691 // Duplicate the fence for passing to waitFence.
692 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
693 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
694 ATRACE_NAME("Waiting before draw");
695 sync_wait(bufferFence.get(), -1);
696 }
697 }
698 if (buffer == nullptr) {
699 ALOGE("No output buffer provided. Aborting GPU composition.");
700 return BAD_VALUE;
701 }
702
Alec Mouria90a5702021-04-16 16:36:21 +0000703 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800704
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400705 auto grContext = getActiveGrContext();
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800706 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700707
Alec Mouria90a5702021-04-16 16:36:21 +0000708 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
709 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
710 surfaceTextureRef = it->second;
711 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400712 surfaceTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400713 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
714 buffer->getBuffer()
715 ->toAHardwareBuffer(),
716 true);
John Reck67b1e2b2020-08-26 13:17:24 -0700717 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800718
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500719 const ui::Dataspace dstDataspace =
720 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400721 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700722
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500723 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
724 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800725 ALOGE("Cannot acquire canvas from Skia.");
726 return BAD_VALUE;
727 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500728
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400729 // setup color filter if necessary
730 sk_sp<SkColorFilter> displayColorTransform;
731 if (display.colorTransform != mat4()) {
732 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
733 }
734 const bool ctModifiesAlpha =
735 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
736
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500737 // Find if any layers have requested blur, we'll use that info to decide when to render to an
738 // offscreen buffer and when to render to the native buffer.
739 sk_sp<SkSurface> activeSurface(dstSurface);
740 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500741 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500742 const LayerSettings* blurCompositionLayer = nullptr;
743 if (mBlurFilter) {
744 bool requiresCompositionLayer = false;
745 for (const auto& layer : layers) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400746 // if the layer doesn't have blur or it is not visible then continue
747 if (!layerHasBlur(layer, ctModifiesAlpha)) {
748 continue;
749 }
Derek Sollenberger3134ec32021-02-12 11:26:23 -0500750 if (layer->backgroundBlurRadius > 0 &&
751 layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500752 requiresCompositionLayer = true;
753 }
754 for (auto region : layer->blurRegions) {
755 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
756 requiresCompositionLayer = true;
757 }
758 }
759 if (requiresCompositionLayer) {
760 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500761 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500762 blurCompositionLayer = layer;
763 break;
764 }
765 }
766 }
767
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500768 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700769 // Clear the entire canvas with a transparent black to prevent ghost images.
770 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500771 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800772
773 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
774 // view is still on-screen. The clear region could be re-specified as a black color layer,
775 // however.
776 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500777 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800778 size_t numRects = 0;
779 Rect const* rects = display.clearRegion.getArray(&numRects);
780 SkIRect skRects[numRects];
781 for (int i = 0; i < numRects; ++i) {
782 skRects[i] =
783 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
784 }
785 SkRegion clearRegion;
786 SkPaint paint;
787 sk_sp<SkShader> shader =
788 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500789 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800790 paint.setShader(shader);
791 clearRegion.setRects(skRects, numRects);
792 canvas->drawRegion(clearRegion, paint);
793 }
794
John Reck67b1e2b2020-08-26 13:17:24 -0700795 for (const auto& layer : layers) {
Alec Mouricbd30932021-06-09 15:52:25 -0700796 ATRACE_FORMAT("DrawLayer: %s", layer->name.c_str());
Galia Peychevaf7889b32020-11-25 22:22:40 +0100797
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400798 if (kPrintLayerSettings) {
799 std::stringstream ls;
800 PrintTo(*layer, &ls);
801 auto debugs = ls.str();
802 int pos = 0;
803 while (pos < debugs.size()) {
804 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
805 pos += 1000;
806 }
807 }
808
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500809 sk_sp<SkImage> blurInput;
810 if (blurCompositionLayer == layer) {
811 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
812 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
813
814 // save a snapshot of the activeSurface to use as input to the blur shaders
815 blurInput = activeSurface->makeImageSnapshot();
816
817 // TODO we could skip this step if we know the blur will cover the entire image
818 // blit the offscreen framebuffer into the destination AHB
819 SkPaint paint;
820 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500821 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
822 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
823 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
824 String8::format("SurfaceID|%" PRId64, id).c_str(),
825 nullptr);
826 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
827 } else {
828 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
829 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500830
831 // assign dstCanvas to canvas and ensure that the canvas state is up to date
832 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500833 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500834 initCanvas(canvas, display);
835
836 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
837 dstSurface->getCanvas()->getSaveCount());
838 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
839 dstSurface->getCanvas()->getTotalMatrix());
840
841 // assign dstSurface to activeSurface
842 activeSurface = dstSurface;
843 }
844
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500845 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500846 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800847 // Record the name of the layer if the capture is running.
848 std::stringstream layerSettings;
849 PrintTo(*layer, &layerSettings);
850 // Store the LayerSettings in additional information.
851 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
852 SkData::MakeWithCString(layerSettings.str().c_str()));
853 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100854 // Layers have a local transform that should be applied to them
855 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100856
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400857 const auto [bounds, roundRectClip] =
858 getBoundsAndClip(layer->geometry.boundaries, layer->geometry.roundedCornersCrop,
859 layer->geometry.roundedCornersRadius);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400860 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500861 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
862
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500863 // if multiple layers have blur, then we need to take a snapshot now because
864 // only the lowest layer will have blurImage populated earlier
865 if (!blurInput) {
866 blurInput = activeSurface->makeImageSnapshot();
867 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500868 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400869 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
870
871 // if the clip needs to be applied then apply it now and make sure
872 // it is restored before we attempt to draw any shadows.
873 SkAutoCanvasRestore acr(canvas, true);
874 if (!roundRectClip.isEmpty()) {
875 canvas->clipRRect(roundRectClip, true);
876 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500877
Galia Peychevae425ac82021-03-15 17:12:03 +0100878 // TODO(b/182216890): Filter out empty layers earlier
879 if (blurRect.width() > 0 && blurRect.height() > 0) {
880 if (layer->backgroundBlurRadius > 0) {
881 ATRACE_NAME("BackgroundBlur");
882 auto blurredImage =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400883 mBlurFilter->generate(grContext, layer->backgroundBlurRadius, blurInput,
884 blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100885
Galia Peychevae425ac82021-03-15 17:12:03 +0100886 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500887
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400888 mBlurFilter->drawBlurRegion(canvas, bounds, layer->backgroundBlurRadius, 1.0f,
889 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700890 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400891
Derek Sollenberger39feade2021-04-27 16:08:40 -0400892 canvas->concat(getSkM44(layer->blurRegionTransform).asM33());
Galia Peychevae425ac82021-03-15 17:12:03 +0100893 for (auto region : layer->blurRegions) {
894 if (cachedBlurs[region.blurRadius] == nullptr) {
895 ATRACE_NAME("BlurRegion");
896 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400897 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100898 blurRect);
899 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500900
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400901 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
902 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100903 cachedBlurs[region.blurRadius], blurInput);
904 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700905 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700906 }
907
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500908 if (layer->shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400909 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
910 LOG_ALWAYS_FATAL_IF(layer->disableBlending, "Cannot disableBlending with a shadow");
Leon Scroggins III63e86952021-05-12 10:45:08 -0400911
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400912 SkRRect shadowBounds, shadowClip;
913 if (layer->geometry.boundaries == layer->shadow.boundaries) {
914 shadowBounds = bounds;
915 shadowClip = roundRectClip;
916 } else {
917 std::tie(shadowBounds, shadowClip) =
918 getBoundsAndClip(layer->shadow.boundaries,
919 layer->geometry.roundedCornersCrop,
920 layer->geometry.roundedCornersRadius);
921 }
922
Leon Scroggins III63e86952021-05-12 10:45:08 -0400923 // Technically, if bounds is a rect and roundRectClip is not empty,
924 // it means that the bounds and roundedCornersCrop were different
925 // enough that we should intersect them to find the proper shadow.
926 // In practice, this often happens when the two rectangles appear to
927 // not match due to rounding errors. Draw the rounded version, which
928 // looks more like the intent.
929 const auto& rrect =
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400930 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
Leon Scroggins III63e86952021-05-12 10:45:08 -0400931 drawShadow(canvas, rrect, layer->shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500932 }
933
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500934 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
935 (mUseColorManagement &&
John Reckac09e452021-04-07 16:35:37 -0400936 needsToneMapping(layer->sourceDataspace, display.outputDataspace)) ||
937 (display.sdrWhitePointNits > 0.f &&
938 display.sdrWhitePointNits != display.maxLuminance);
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500939
940 // quick abort from drawing the remaining portion of the layer
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400941 if (layer->skipContentDraw ||
942 (layer->alpha == 0 && !requiresLinearEffect && !layer->disableBlending &&
943 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500944 continue;
945 }
946
947 // If we need to map to linear space or color management is disabled, then mark the source
948 // image with the same colorspace as the destination surface so that Skia's color
949 // management is a no-op.
950 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
951 ? dstDataspace
952 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800953
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500954 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700955 if (layer->source.buffer.buffer) {
956 ATRACE_NAME("DrawImage");
Alec Mouria90a5702021-04-16 16:36:21 +0000957 validateInputBufferUsage(layer->source.buffer.buffer->getBuffer());
John Reck67b1e2b2020-08-26 13:17:24 -0700958 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800959 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +0000960
961 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
962 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800963 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700964 } else {
Alec Mouria90a5702021-04-16 16:36:21 +0000965 // If we didn't find the image in the cache, then create a local ref but don't cache
966 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
967 // we didn't find anything in the cache then we intentionally did not cache this
968 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400969 imageTextureRef = std::make_shared<
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400970 AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400971 item.buffer->getBuffer()->toAHardwareBuffer(),
972 false);
John Reck67b1e2b2020-08-26 13:17:24 -0700973 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800974
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -0400975 // isOpaque means we need to ignore the alpha in the image,
976 // replacing it with the alpha specified by the LayerSettings. See
977 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
978 // The proper way to do this is to use an SkColorType that ignores
979 // alpha, like kRGB_888x_SkColorType, and that is used if the
980 // incoming image is kRGBA_8888_SkColorType. However, the incoming
981 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
982 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
983 // kRGB_101010x_SkColorType, but it is not yet supported as a source
984 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
985 // meantime, we'll use a workaround that works unless we need to do
986 // any color conversion. The workaround requires that we pretend the
987 // image is already premultiplied, so that we do not premultiply it
988 // before applying SkBlendMode::kPlus.
989 const bool useIsOpaqueWorkaround = item.isOpaque &&
990 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
991 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
992 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
993 : item.isOpaque ? kOpaque_SkAlphaType
994 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
995 : kUnpremul_SkAlphaType;
996 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700997
998 auto texMatrix = getSkM44(item.textureTransform).asM33();
999 // textureTansform was intended to be passed directly into a shader, so when
1000 // building the total matrix with the textureTransform we need to first
1001 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001002 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001003 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -07001004
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001005 SkMatrix matrix;
1006 if (!texMatrix.invert(&matrix)) {
1007 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -07001008 }
Ana Krulecf9a15d92020-12-11 08:35:00 -08001009 // The shader does not respect the translation, so we add it to the texture
1010 // transform for the SkImage. This will make sure that the correct layer contents
1011 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001012 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -07001013
Ana Krulecb7b28b22020-11-23 14:48:58 -08001014 sk_sp<SkShader> shader;
1015
1016 if (layer->source.buffer.useTextureFiltering) {
1017 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1018 SkSamplingOptions(
1019 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1020 &matrix);
1021 } else {
Mike Reed711e1f02020-12-11 13:06:19 -05001022 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -08001023 }
Alec Mouri029d1952020-10-12 10:37:08 -07001024
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001025 if (useIsOpaqueWorkaround) {
Alec Mouric0aae732021-01-12 13:32:18 -08001026 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1027 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001028 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001029 }
1030
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001031 paint.setShader(createRuntimeEffectShader(shader, layer, display,
1032 !item.isOpaque && item.usePremultipliedAlpha,
1033 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -08001034 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -07001035 } else {
1036 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -07001037 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001038 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1039 .fG = color.g,
1040 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -08001041 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001042 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -08001043 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001044 /* undoPremultipliedAlpha */ false,
1045 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -07001046 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001047
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001048 if (layer->disableBlending) {
1049 paint.setBlendMode(SkBlendMode::kSrc);
1050 }
1051
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001052 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -07001053
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001054 if (!roundRectClip.isEmpty()) {
1055 canvas->clipRRect(roundRectClip, true);
1056 }
1057
1058 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001059 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001060 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001061 } else {
Nader Jawad63644d32021-05-07 10:44:21 -07001062 canvas->drawRect(bounds.rect(), paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -07001063 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001064 if (kFlushAfterEveryLayer) {
1065 ATRACE_NAME("flush surface");
1066 activeSurface->flush();
1067 }
John Reck67b1e2b2020-08-26 13:17:24 -07001068 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001069 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001070 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001071 {
1072 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001073 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1074 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001075 }
1076
1077 if (drawFence != nullptr) {
1078 *drawFence = flush();
1079 }
1080
1081 // If flush failed or we don't support native fences, we need to force the
1082 // gl command stream to be executed.
1083 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
1084 if (requireSync) {
1085 ATRACE_BEGIN("Submit(sync=true)");
1086 } else {
1087 ATRACE_BEGIN("Submit(sync=false)");
1088 }
Lucas Dupind508e472020-11-04 04:32:06 +00001089 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001090 ATRACE_END();
1091 if (!success) {
1092 ALOGE("Failed to flush RenderEngine commands");
1093 // Chances are, something illegal happened (either the caller passed
1094 // us bad parameters, or we messed up our shader generation).
1095 return INVALID_OPERATION;
1096 }
1097
1098 // checkErrors();
1099 return NO_ERROR;
1100}
1101
Lucas Dupin3f11e922020-09-22 17:31:04 -07001102inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1103 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1104}
1105
1106inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1107 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1108}
1109
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001110inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(const FloatRect& boundsRect,
1111 const FloatRect& cropRect,
1112 const float cornerRadius) {
1113 const SkRect bounds = getSkRect(boundsRect);
1114 const SkRect crop = getSkRect(cropRect);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001115
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001116 SkRRect clip;
1117 if (cornerRadius > 0) {
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001118 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
1119 if (bounds == crop || crop.isEmpty()) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001120 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1121 }
1122
1123 // This makes an effort to speed up common, simple bounds + clip combinations by
1124 // converting them to a single RRect draw. It is possible there are other cases
1125 // that can be converted.
1126 if (crop.contains(bounds)) {
1127 bool intersectionIsRoundRect = true;
1128 // check each cropped corner to ensure that it exactly matches the crop or is full
1129 SkVector radii[4];
1130
1131 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
1132
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001133 const bool leftEqual = bounds.fLeft == crop.fLeft;
1134 const bool topEqual = bounds.fTop == crop.fTop;
1135 const bool rightEqual = bounds.fRight == crop.fRight;
1136 const bool bottomEqual = bounds.fBottom == crop.fBottom;
1137
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001138 // compute the UpperLeft corner radius
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001139 if (leftEqual && topEqual) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001140 radii[0].set(cornerRadius, cornerRadius);
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001141 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
1142 (topEqual && bounds.fLeft >= insetCrop.fLeft) ||
1143 insetCrop.contains(bounds.fLeft, bounds.fTop)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001144 radii[0].set(0, 0);
1145 } else {
1146 intersectionIsRoundRect = false;
1147 }
1148 // compute the UpperRight corner radius
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001149 if (rightEqual && topEqual) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001150 radii[1].set(cornerRadius, cornerRadius);
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001151 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
1152 (topEqual && bounds.fRight <= insetCrop.fRight) ||
1153 insetCrop.contains(bounds.fRight, bounds.fTop)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001154 radii[1].set(0, 0);
1155 } else {
1156 intersectionIsRoundRect = false;
1157 }
1158 // compute the BottomRight corner radius
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001159 if (rightEqual && bottomEqual) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001160 radii[2].set(cornerRadius, cornerRadius);
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001161 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
1162 (bottomEqual && bounds.fRight <= insetCrop.fRight) ||
1163 insetCrop.contains(bounds.fRight, bounds.fBottom)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001164 radii[2].set(0, 0);
1165 } else {
1166 intersectionIsRoundRect = false;
1167 }
1168 // compute the BottomLeft corner radius
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001169 if (leftEqual && bottomEqual) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001170 radii[3].set(cornerRadius, cornerRadius);
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001171 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
1172 (bottomEqual && bounds.fLeft >= insetCrop.fLeft) ||
1173 insetCrop.contains(bounds.fLeft, bounds.fBottom)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001174 radii[3].set(0, 0);
1175 } else {
1176 intersectionIsRoundRect = false;
1177 }
1178
1179 if (intersectionIsRoundRect) {
1180 SkRRect intersectionBounds;
1181 intersectionBounds.setRectRadii(bounds, radii);
1182 return {intersectionBounds, clip};
1183 }
1184 }
1185
1186 // we didn't it any of our fast paths so set the clip to the cropRect
1187 clip.setRectXY(crop, cornerRadius, cornerRadius);
1188 }
1189
1190 // if we hit this point then we either don't have rounded corners or we are going to rely
1191 // on the clip to round the corners for us
1192 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001193}
1194
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001195inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer,
1196 bool colorTransformModifiesAlpha) {
1197 if (layer->backgroundBlurRadius > 0 || layer->blurRegions.size()) {
1198 // return false if the content is opaque and would therefore occlude the blur
1199 const bool opaqueContent = !layer->source.buffer.buffer || layer->source.buffer.isOpaque;
1200 const bool opaqueAlpha = layer->alpha == 1.0f && !colorTransformModifiesAlpha;
1201 return layer->skipContentDraw || !(opaqueContent && opaqueAlpha);
1202 }
1203 return false;
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001204}
1205
Lucas Dupin3f11e922020-09-22 17:31:04 -07001206inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1207 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1208}
1209
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001210inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1211 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1212 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1213 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1214 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1215}
1216
Lucas Dupin3f11e922020-09-22 17:31:04 -07001217inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1218 return SkPoint3::Make(vector.x, vector.y, vector.z);
1219}
1220
John Reck67b1e2b2020-08-26 13:17:24 -07001221size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1222 return mGrContext->maxTextureSize();
1223}
1224
1225size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1226 return mGrContext->maxRenderTargetSize();
1227}
1228
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001229void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001230 const ShadowSettings& settings) {
1231 ATRACE_CALL();
1232 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001233 const auto flags =
1234 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1235
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001236 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001237 getSkPoint3(settings.lightPos), settings.lightRadius,
1238 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1239 flags);
1240}
1241
John Reck67b1e2b2020-08-26 13:17:24 -07001242EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001243 EGLContext shareContext,
1244 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001245 Protection protection) {
1246 EGLint renderableType = 0;
1247 if (config == EGL_NO_CONFIG_KHR) {
1248 renderableType = EGL_OPENGL_ES3_BIT;
1249 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1250 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1251 }
1252 EGLint contextClientVersion = 0;
1253 if (renderableType & EGL_OPENGL_ES3_BIT) {
1254 contextClientVersion = 3;
1255 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1256 contextClientVersion = 2;
1257 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1258 contextClientVersion = 1;
1259 } else {
1260 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1261 }
1262
1263 std::vector<EGLint> contextAttributes;
1264 contextAttributes.reserve(7);
1265 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1266 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001267 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001268 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001269 switch (*contextPriority) {
1270 case ContextPriority::REALTIME:
1271 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1272 break;
1273 case ContextPriority::MEDIUM:
1274 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1275 break;
1276 case ContextPriority::LOW:
1277 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1278 break;
1279 case ContextPriority::HIGH:
1280 default:
1281 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1282 break;
1283 }
John Reck67b1e2b2020-08-26 13:17:24 -07001284 }
1285 if (protection == Protection::PROTECTED) {
1286 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1287 contextAttributes.push_back(EGL_TRUE);
1288 }
1289 contextAttributes.push_back(EGL_NONE);
1290
1291 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1292
1293 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1294 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1295 // EGL_NO_CONTEXT so that we can abort.
1296 if (config != EGL_NO_CONFIG_KHR) {
1297 return context;
1298 }
1299 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1300 // should try to fall back to GLES 2.
1301 contextAttributes[1] = 2;
1302 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1303 }
1304
1305 return context;
1306}
1307
Alec Mourid6f09462020-12-07 11:18:17 -08001308std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1309 const RenderEngineCreationArgs& args) {
1310 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1311 return std::nullopt;
1312 }
1313
1314 switch (args.contextPriority) {
1315 case RenderEngine::ContextPriority::REALTIME:
1316 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1317 return RenderEngine::ContextPriority::REALTIME;
1318 } else {
1319 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1320 return RenderEngine::ContextPriority::HIGH;
1321 }
1322 case RenderEngine::ContextPriority::HIGH:
1323 case RenderEngine::ContextPriority::MEDIUM:
1324 case RenderEngine::ContextPriority::LOW:
1325 return args.contextPriority;
1326 default:
1327 return std::nullopt;
1328 }
1329}
1330
John Reck67b1e2b2020-08-26 13:17:24 -07001331EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1332 EGLConfig config, int hwcFormat,
1333 Protection protection) {
1334 EGLConfig placeholderConfig = config;
1335 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1336 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1337 }
1338 std::vector<EGLint> attributes;
1339 attributes.reserve(7);
1340 attributes.push_back(EGL_WIDTH);
1341 attributes.push_back(1);
1342 attributes.push_back(EGL_HEIGHT);
1343 attributes.push_back(1);
1344 if (protection == Protection::PROTECTED) {
1345 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1346 attributes.push_back(EGL_TRUE);
1347 }
1348 attributes.push_back(EGL_NONE);
1349
1350 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1351}
1352
Alec Mourid6f09462020-12-07 11:18:17 -08001353int SkiaGLRenderEngine::getContextPriority() {
1354 int value;
1355 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1356 return value;
1357}
1358
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001359void SkiaGLRenderEngine::onPrimaryDisplaySizeChanged(ui::Size size) {
1360 // This cache multiplier was selected based on review of cache sizes relative
1361 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1362 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1363 // conservative default based on that analysis.
1364 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1365 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1366
1367 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001368 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001369
1370 // if it is possible to switch contexts then we will resize the other context
1371 if (useProtectedContext(!mInProtectedContext)) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001372 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001373 // reset back to the initial context that was active when this method was called
1374 useProtectedContext(!mInProtectedContext);
1375 }
1376}
1377
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001378void SkiaGLRenderEngine::dump(std::string& result) {
1379 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1380
1381 StringAppendF(&result, "\n ------------RE-----------------\n");
1382 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1383 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1384 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1385 extensions.getVersion());
1386 StringAppendF(&result, "%s\n", extensions.getExtensions());
1387 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1388 supportsProtectedContent());
1389 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001390 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1391 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001392
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001393 std::vector<ResourcePair> cpuResourceMap = {
1394 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1395 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1396 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1397 {"skia/sk_resource_cache/tessellated", "Shadows"},
1398 {"skia", "Other"},
1399 };
1400 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1401 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1402 StringAppendF(&result, "Skia CPU Caches: ");
1403 cpuReporter.logTotals(result);
1404 cpuReporter.logOutput(result);
1405
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001406 {
1407 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001408
1409 std::vector<ResourcePair> gpuResourceMap = {
1410 {"texture_renderbuffer", "Texture/RenderBuffer"},
1411 {"texture", "Texture"},
1412 {"gr_text_blob_cache", "Text"},
1413 {"skia", "Other"},
1414 };
1415 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1416 mGrContext->dumpMemoryStatistics(&gpuReporter);
1417 StringAppendF(&result, "Skia's GPU Caches: ");
1418 gpuReporter.logTotals(result);
1419 gpuReporter.logOutput(result);
1420 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1421 gpuReporter.logOutput(result, true);
1422
Alec Mouria90a5702021-04-16 16:36:21 +00001423 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1424 mGraphicBufferExternalRefs.size());
1425 StringAppendF(&result, "Dumping buffer ids...\n");
1426 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1427 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1428 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001429 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1430 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001431 StringAppendF(&result, "Dumping buffer ids...\n");
1432 // TODO(178539829): It would be nice to know which layer these are coming from and what
1433 // the texture sizes are.
1434 for (const auto& [id, unused] : mTextureCache) {
1435 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1436 }
1437 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001438
1439 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001440 if (mProtectedGrContext) {
1441 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1442 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001443 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1444 gpuProtectedReporter.logTotals(result);
1445 gpuProtectedReporter.logOutput(result);
1446 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1447 gpuProtectedReporter.logOutput(result, true);
1448
1449 StringAppendF(&result, "RenderEngine protected AHB/BackendTexture cache size: %zu\n",
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001450 mProtectedTextureCache.size());
1451 StringAppendF(&result, "Dumping buffer ids...\n");
1452 for (const auto& [id, unused] : mProtectedTextureCache) {
1453 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1454 }
1455 StringAppendF(&result, "\n");
1456 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1457 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1458 StringAppendF(&result, "- inputDataspace: %s\n",
1459 dataspaceDetails(
1460 static_cast<android_dataspace>(linearEffect.inputDataspace))
1461 .c_str());
1462 StringAppendF(&result, "- outputDataspace: %s\n",
1463 dataspaceDetails(
1464 static_cast<android_dataspace>(linearEffect.outputDataspace))
1465 .c_str());
1466 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1467 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1468 }
1469 }
1470 StringAppendF(&result, "\n");
1471}
1472
John Reck67b1e2b2020-08-26 13:17:24 -07001473} // namespace skia
1474} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001475} // namespace android