blob: 9fbbdc34ba243e03a489e38759d27eb657b69750 [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
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700238std::future<void> SkiaGLRenderEngine::primeCache() {
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500239 Cache::primeShaderCache(this);
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700240 return {};
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500241}
242
John Reck67b1e2b2020-08-26 13:17:24 -0700243EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
244 status_t err;
245 EGLConfig config;
246
247 // First try to get an ES3 config
248 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
249 if (err != NO_ERROR) {
250 // If ES3 fails, try to get an ES2 config
251 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
252 if (err != NO_ERROR) {
253 // If ES2 still doesn't work, probably because we're on the emulator.
254 // try a simplified query
255 ALOGW("no suitable EGLConfig found, trying a simpler query");
256 err = selectEGLConfig(display, format, 0, &config);
257 if (err != NO_ERROR) {
258 // this EGL is too lame for android
259 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
260 }
261 }
262 }
263
264 if (logConfig) {
265 // print some debugging info
266 EGLint r, g, b, a;
267 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
268 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
269 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
270 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
271 ALOGI("EGL information:");
272 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
273 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
274 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
275 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
276 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
277 }
278
279 return config;
280}
281
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400282sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
283 // This "cache" does not actually cache anything. It just allows us to
284 // monitor Skia's internal cache. So this method always returns null.
285 return nullptr;
286}
287
288void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
289 const SkString& description) {
290 mShadersCachedSinceLastCall++;
291}
292
293void SkiaGLRenderEngine::assertShadersCompiled(int numShaders) {
294 const int cached = mSkSLCacheMonitor.shadersCachedSinceLastCall();
295 LOG_ALWAYS_FATAL_IF(cached != numShaders, "Attempted to cache %i shaders; cached %i",
296 numShaders, cached);
297}
298
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400299int SkiaGLRenderEngine::reportShadersCompiled() {
300 return mSkSLCacheMonitor.shadersCachedSinceLastCall();
301}
302
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700303SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000304 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700305 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800306 : SkiaRenderEngine(args.renderEngineType),
307 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700308 mEGLContext(ctxt),
309 mPlaceholderSurface(placeholder),
310 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700311 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400312 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800313 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700314 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
315 LOG_ALWAYS_FATAL_IF(!glInterface.get());
316
317 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400318 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700319 options.fDisableDistanceFieldPaths = true;
Nathaniel Nifongf8d35e92021-06-08 15:02:25 -0400320 options.fReducedShaderVariations = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400321 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000322 mGrContext = GrDirectContext::MakeGL(glInterface, options);
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400323 if (supportsProtectedContent()) {
324 useProtectedContext(true);
Lucas Dupind508e472020-11-04 04:32:06 +0000325 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
326 useProtectedContext(false);
327 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700328
329 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500330 ALOGD("Background Blurs Enabled");
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700331 mBlurFilter = new BlurFilter();
332 }
Alec Mouric0aae732021-01-12 13:32:18 -0800333 mCapture = std::make_unique<SkiaCapture>();
334}
335
336SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100337 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800338 if (mBlurFilter) {
339 delete mBlurFilter;
340 }
341
342 mCapture = nullptr;
343
344 mGrContext->flushAndSubmit(true);
345 mGrContext->abandonContext();
346
347 if (mProtectedGrContext) {
348 mProtectedGrContext->flushAndSubmit(true);
349 mProtectedGrContext->abandonContext();
350 }
351
352 if (mPlaceholderSurface != EGL_NO_SURFACE) {
353 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
354 }
355 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
356 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
357 }
358 if (mEGLContext != EGL_NO_CONTEXT) {
359 eglDestroyContext(mEGLDisplay, mEGLContext);
360 }
361 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
362 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
363 }
364 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
365 eglTerminate(mEGLDisplay);
366 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700367}
368
Lucas Dupind508e472020-11-04 04:32:06 +0000369bool SkiaGLRenderEngine::supportsProtectedContent() const {
370 return mProtectedEGLContext != EGL_NO_CONTEXT;
371}
372
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400373GrDirectContext* SkiaGLRenderEngine::getActiveGrContext() const {
374 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
375}
376
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400377void SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
378 if (useProtectedContext == mInProtectedContext ||
379 (useProtectedContext && !supportsProtectedContent())) {
380 return;
Lucas Dupind508e472020-11-04 04:32:06 +0000381 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400382
383 // release any scratch resources before switching into a new mode
384 if (getActiveGrContext()) {
385 getActiveGrContext()->purgeUnlockedResources(true);
386 }
387
Lucas Dupind508e472020-11-04 04:32:06 +0000388 const EGLSurface surface =
389 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
390 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
Alec Mouric0aae732021-01-12 13:32:18 -0800391
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400392 if (eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE) {
Lucas Dupind508e472020-11-04 04:32:06 +0000393 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 }
Lucas Dupind508e472020-11-04 04:32:06 +0000400}
401
John Reck67b1e2b2020-08-26 13:17:24 -0700402base::unique_fd SkiaGLRenderEngine::flush() {
403 ATRACE_CALL();
404 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
405 return base::unique_fd();
406 }
407
408 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
409 if (sync == EGL_NO_SYNC_KHR) {
410 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
411 return base::unique_fd();
412 }
413
414 // native fence fd will not be populated until flush() is done.
415 glFlush();
416
417 // get the fence fd
418 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
419 eglDestroySyncKHR(mEGLDisplay, sync);
420 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
421 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
422 }
423
424 return fenceFd;
425}
426
427bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
428 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
429 !gl::GLExtensions::getInstance().hasWaitSync()) {
430 return false;
431 }
432
433 // release the fd and transfer the ownership to EGLSync
434 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
435 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
436 if (sync == EGL_NO_SYNC_KHR) {
437 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
438 return false;
439 }
440
441 // XXX: The spec draft is inconsistent as to whether this should return an
442 // EGLint or void. Ignore the return value for now, as it's not strictly
443 // needed.
444 eglWaitSyncKHR(mEGLDisplay, sync, 0);
445 EGLint error = eglGetError();
446 eglDestroySyncKHR(mEGLDisplay, sync);
447 if (error != EGL_SUCCESS) {
448 ALOGE("failed to wait for EGL native fence sync: %#x", error);
449 return false;
450 }
451
452 return true;
453}
454
Alec Mouri678245d2020-09-30 16:58:23 -0700455static float toDegrees(uint32_t transform) {
456 switch (transform) {
457 case ui::Transform::ROT_90:
458 return 90.0;
459 case ui::Transform::ROT_180:
460 return 180.0;
461 case ui::Transform::ROT_270:
462 return 270.0;
463 default:
464 return 0.0;
465 }
466}
467
Alec Mourib34f0b72020-10-02 13:18:34 -0700468static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
469 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
470 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
471 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
472 matrix[3][3], 0);
473}
474
Alec Mouri029d1952020-10-12 10:37:08 -0700475static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
476 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
477 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
478
479 // Treat unsupported dataspaces as srgb
480 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
481 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
482 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
483 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
484 }
485
486 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
487 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
488 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
489 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
490 }
491
492 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
493 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
494 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
495 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
496
497 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
498 sourceTransfer != destTransfer;
499}
500
Alec Mouria90a5702021-04-16 16:36:21 +0000501void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
502 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800503 // Only run this if RE is running on its own thread. This way the access to GL
504 // operations is guaranteed to be happening on the same thread.
505 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
506 return;
507 }
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400508 // We currently don't attempt to map a buffer if the buffer contains protected content
Derek Sollenberger45007182021-06-10 14:47:21 -0400509 // because GPU resources for protected buffers is much more limited.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400510 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Derek Sollenberger45007182021-06-10 14:47:21 -0400511 if (isProtectedBuffer) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400512 return;
513 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800514 ATRACE_CALL();
515
Derek Sollenberger45007182021-06-10 14:47:21 -0400516 // If we were to support caching protected buffers then we will need to switch the
517 // currently bound context if we are not already using the protected context (and subsequently
518 // switch back after the buffer is cached). However, for non-protected content we can bind
519 // the texture in either GL context because they are initialized with the same share_context
520 // which allows the texture state to be shared between them.
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(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400531 isRenderable, mTextureCleanupMgr);
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
Alec Mouric2ffeb42021-06-17 17:42:27 -0700552 // Swap contexts if needed prior to deleting this buffer
553 // See Issue 1 of
554 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
555 // when a protected context and an unprotected context are part of the same share group,
556 // protected surfaces may not be accessed by an unprotected context, implying that protected
557 // surfaces may only be freed when a protected context is active.
558 const bool inProtected = mInProtectedContext;
559 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
560
Alec Mouria90a5702021-04-16 16:36:21 +0000561 if (iter->second == 0) {
562 mTextureCache.erase(buffer->getId());
Alec Mouria90a5702021-04-16 16:36:21 +0000563 mGraphicBufferExternalRefs.erase(buffer->getId());
564 }
Alec Mouric2ffeb42021-06-17 17:42:27 -0700565
566 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
567 // are up-to-date.
568 if (inProtected != mInProtectedContext) {
569 useProtectedContext(inProtected);
570 }
Alec Mouria90a5702021-04-16 16:36:21 +0000571 }
John Reck67b1e2b2020-08-26 13:17:24 -0700572}
573
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400574bool SkiaGLRenderEngine::canSkipPostRenderCleanup() const {
575 std::lock_guard<std::mutex> lock(mRenderingMutex);
576 return mTextureCleanupMgr.isEmpty();
577}
578
579void SkiaGLRenderEngine::cleanupPostRender() {
580 ATRACE_CALL();
581 std::lock_guard<std::mutex> lock(mRenderingMutex);
582 mTextureCleanupMgr.cleanup();
583}
584
585// Helper class intended to be used on the stack to ensure that texture cleanup
586// is deferred until after this class goes out of scope.
587class DeferTextureCleanup final {
588public:
589 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
590 mMgr.setDeferredStatus(true);
591 }
592 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
593
594private:
595 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
596 AutoBackendTexture::CleanupManager& mMgr;
597};
598
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700599sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
600 sk_sp<SkShader> shader,
601 const LayerSettings* layer, const DisplaySettings& display, bool undoPremultipliedAlpha,
602 bool requiresLinearEffect) {
603 const auto stretchEffect = layer->stretchEffect;
Nader Jawad63644d32021-05-07 10:44:21 -0700604 // The given surface will be stretched by HWUI via matrix transformation
605 // which gets similar results for most surfaces
606 // Determine later on if we need to leverage the stertch shader within
607 // surface flinger
Nader Jawadc088bdc2021-05-10 13:24:46 -0700608 if (stretchEffect.hasEffect()) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700609 const auto targetBuffer = layer->source.buffer.buffer;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700610 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
611 if (graphicBuffer && shader) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700612 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
613 }
John Reckcdb4ed72021-02-04 13:39:33 -0500614 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700615
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500616 if (requiresLinearEffect) {
617 const ui::Dataspace inputDataspace =
Alec Mourid2bcbae2021-06-28 17:02:17 -0700618 mUseColorManagement ? layer->sourceDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500619 const ui::Dataspace outputDataspace =
Alec Mourid2bcbae2021-06-28 17:02:17 -0700620 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500621
622 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
623 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800624 .undoPremultipliedAlpha = undoPremultipliedAlpha};
625
626 auto effectIter = mRuntimeEffects.find(effect);
627 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
628 if (effectIter == mRuntimeEffects.end()) {
629 runtimeEffect = buildRuntimeEffect(effect);
630 mRuntimeEffects.insert({effect, runtimeEffect});
631 } else {
632 runtimeEffect = effectIter->second;
633 }
John Reckac09e452021-04-07 16:35:37 -0400634 float maxLuminance = layer->source.buffer.maxLuminanceNits;
635 // If the buffer doesn't have a max luminance, treat it as SDR & use the display's SDR
636 // white point
637 if (maxLuminance <= 0.f) {
638 maxLuminance = display.sdrWhitePointNits;
639 }
Ana Krulec47814212021-01-06 19:00:10 -0800640 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
John Reckac09e452021-04-07 16:35:37 -0400641 display.maxLuminance, maxLuminance);
Ana Krulec47814212021-01-06 19:00:10 -0800642 }
643 return shader;
644}
645
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500646void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500647 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500648 // Record display settings when capture is running.
649 std::stringstream displaySettings;
650 PrintTo(display, &displaySettings);
651 // Store the DisplaySettings in additional information.
652 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
653 SkData::MakeWithCString(displaySettings.str().c_str()));
654 }
655
656 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
657 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
658 // displays might have different scaling when compared to the physical screen.
659
660 canvas->clipRect(getSkRect(display.physicalDisplay));
661 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
662
663 const auto clipWidth = display.clip.width();
664 const auto clipHeight = display.clip.height();
665 auto rotatedClipWidth = clipWidth;
666 auto rotatedClipHeight = clipHeight;
667 // Scale is contingent on the rotation result.
668 if (display.orientation & ui::Transform::ROT_90) {
669 std::swap(rotatedClipWidth, rotatedClipHeight);
670 }
671 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
672 static_cast<SkScalar>(rotatedClipWidth);
673 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
674 static_cast<SkScalar>(rotatedClipHeight);
675 canvas->scale(scaleX, scaleY);
676
677 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
678 // back so that the top left corner of the clip is at (0, 0).
679 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
680 canvas->rotate(toDegrees(display.orientation));
681 canvas->translate(-clipWidth / 2, -clipHeight / 2);
682 canvas->translate(-display.clip.left, -display.clip.top);
683}
684
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500685class AutoSaveRestore {
686public:
687 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
688 ~AutoSaveRestore() { restore(); }
689 void replace(SkCanvas* canvas) {
690 mCanvas = canvas;
691 mSaveCount = canvas->save();
692 }
693 void restore() {
694 if (mCanvas) {
695 mCanvas->restoreToCount(mSaveCount);
696 mCanvas = nullptr;
697 }
698 }
699
700private:
701 SkCanvas* mCanvas;
702 int mSaveCount;
703};
704
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400705static SkRRect getBlurRRect(const BlurRegion& region) {
706 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
707 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
708 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
709 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
710 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
711 SkRRect roundedRect;
712 roundedRect.setRectRadii(rect, radii);
713 return roundedRect;
714}
715
John Reck67b1e2b2020-08-26 13:17:24 -0700716status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
717 const std::vector<const LayerSettings*>& layers,
Alec Mouria90a5702021-04-16 16:36:21 +0000718 const std::shared_ptr<ExternalTexture>& buffer,
719 const bool /*useFramebufferCache*/,
John Reck67b1e2b2020-08-26 13:17:24 -0700720 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
721 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800722
John Reck67b1e2b2020-08-26 13:17:24 -0700723 std::lock_guard<std::mutex> lock(mRenderingMutex);
724 if (layers.empty()) {
725 ALOGV("Drawing empty layer stack");
726 return NO_ERROR;
727 }
728
729 if (bufferFence.get() >= 0) {
730 // Duplicate the fence for passing to waitFence.
731 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
732 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
733 ATRACE_NAME("Waiting before draw");
734 sync_wait(bufferFence.get(), -1);
735 }
736 }
737 if (buffer == nullptr) {
738 ALOGE("No output buffer provided. Aborting GPU composition.");
739 return BAD_VALUE;
740 }
741
Alec Mouria90a5702021-04-16 16:36:21 +0000742 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800743
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400744 auto grContext = getActiveGrContext();
Derek Sollenberger45007182021-06-10 14:47:21 -0400745 auto& cache = mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700746
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400747 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
748 DeferTextureCleanup dtc(mTextureCleanupMgr);
749
Alec Mouria90a5702021-04-16 16:36:21 +0000750 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
751 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
752 surfaceTextureRef = it->second;
753 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400754 surfaceTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400755 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
756 buffer->getBuffer()
757 ->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400758 true, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -0700759 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800760
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500761 const ui::Dataspace dstDataspace =
Alec Mourid2bcbae2021-06-28 17:02:17 -0700762 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400763 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700764
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500765 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
766 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800767 ALOGE("Cannot acquire canvas from Skia.");
768 return BAD_VALUE;
769 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500770
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400771 // setup color filter if necessary
772 sk_sp<SkColorFilter> displayColorTransform;
773 if (display.colorTransform != mat4()) {
774 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
775 }
776 const bool ctModifiesAlpha =
777 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
778
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500779 // Find if any layers have requested blur, we'll use that info to decide when to render to an
780 // offscreen buffer and when to render to the native buffer.
781 sk_sp<SkSurface> activeSurface(dstSurface);
782 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500783 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500784 const LayerSettings* blurCompositionLayer = nullptr;
785 if (mBlurFilter) {
786 bool requiresCompositionLayer = false;
787 for (const auto& layer : layers) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400788 // if the layer doesn't have blur or it is not visible then continue
789 if (!layerHasBlur(layer, ctModifiesAlpha)) {
790 continue;
791 }
Derek Sollenberger3134ec32021-02-12 11:26:23 -0500792 if (layer->backgroundBlurRadius > 0 &&
793 layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500794 requiresCompositionLayer = true;
795 }
796 for (auto region : layer->blurRegions) {
797 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
798 requiresCompositionLayer = true;
799 }
800 }
801 if (requiresCompositionLayer) {
802 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500803 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500804 blurCompositionLayer = layer;
805 break;
806 }
807 }
808 }
809
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500810 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700811 // Clear the entire canvas with a transparent black to prevent ghost images.
812 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500813 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800814
John Reck67b1e2b2020-08-26 13:17:24 -0700815 for (const auto& layer : layers) {
Alec Mouricbd30932021-06-09 15:52:25 -0700816 ATRACE_FORMAT("DrawLayer: %s", layer->name.c_str());
Galia Peychevaf7889b32020-11-25 22:22:40 +0100817
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400818 if (kPrintLayerSettings) {
819 std::stringstream ls;
820 PrintTo(*layer, &ls);
821 auto debugs = ls.str();
822 int pos = 0;
823 while (pos < debugs.size()) {
824 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
825 pos += 1000;
826 }
827 }
828
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500829 sk_sp<SkImage> blurInput;
830 if (blurCompositionLayer == layer) {
831 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
832 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
833
834 // save a snapshot of the activeSurface to use as input to the blur shaders
835 blurInput = activeSurface->makeImageSnapshot();
836
837 // TODO we could skip this step if we know the blur will cover the entire image
838 // blit the offscreen framebuffer into the destination AHB
839 SkPaint paint;
840 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500841 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
842 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
843 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
844 String8::format("SurfaceID|%" PRId64, id).c_str(),
845 nullptr);
846 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
847 } else {
848 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
849 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500850
851 // assign dstCanvas to canvas and ensure that the canvas state is up to date
852 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500853 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500854 initCanvas(canvas, display);
855
856 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
857 dstSurface->getCanvas()->getSaveCount());
858 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
859 dstSurface->getCanvas()->getTotalMatrix());
860
861 // assign dstSurface to activeSurface
862 activeSurface = dstSurface;
863 }
864
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500865 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500866 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800867 // Record the name of the layer if the capture is running.
868 std::stringstream layerSettings;
869 PrintTo(*layer, &layerSettings);
870 // Store the LayerSettings in additional information.
871 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
872 SkData::MakeWithCString(layerSettings.str().c_str()));
873 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100874 // Layers have a local transform that should be applied to them
875 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100876
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400877 const auto [bounds, roundRectClip] =
878 getBoundsAndClip(layer->geometry.boundaries, layer->geometry.roundedCornersCrop,
879 layer->geometry.roundedCornersRadius);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400880 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500881 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
882
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500883 // if multiple layers have blur, then we need to take a snapshot now because
884 // only the lowest layer will have blurImage populated earlier
885 if (!blurInput) {
886 blurInput = activeSurface->makeImageSnapshot();
887 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500888 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400889 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
890
891 // if the clip needs to be applied then apply it now and make sure
892 // it is restored before we attempt to draw any shadows.
893 SkAutoCanvasRestore acr(canvas, true);
894 if (!roundRectClip.isEmpty()) {
895 canvas->clipRRect(roundRectClip, true);
896 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500897
Galia Peychevae425ac82021-03-15 17:12:03 +0100898 // TODO(b/182216890): Filter out empty layers earlier
899 if (blurRect.width() > 0 && blurRect.height() > 0) {
900 if (layer->backgroundBlurRadius > 0) {
901 ATRACE_NAME("BackgroundBlur");
902 auto blurredImage =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400903 mBlurFilter->generate(grContext, layer->backgroundBlurRadius, blurInput,
904 blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100905
Galia Peychevae425ac82021-03-15 17:12:03 +0100906 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500907
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400908 mBlurFilter->drawBlurRegion(canvas, bounds, layer->backgroundBlurRadius, 1.0f,
909 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700910 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400911
Derek Sollenberger39feade2021-04-27 16:08:40 -0400912 canvas->concat(getSkM44(layer->blurRegionTransform).asM33());
Galia Peychevae425ac82021-03-15 17:12:03 +0100913 for (auto region : layer->blurRegions) {
914 if (cachedBlurs[region.blurRadius] == nullptr) {
915 ATRACE_NAME("BlurRegion");
916 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400917 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100918 blurRect);
919 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500920
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400921 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
922 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100923 cachedBlurs[region.blurRadius], blurInput);
924 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700925 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700926 }
927
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500928 if (layer->shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400929 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
930 LOG_ALWAYS_FATAL_IF(layer->disableBlending, "Cannot disableBlending with a shadow");
Leon Scroggins III63e86952021-05-12 10:45:08 -0400931
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400932 SkRRect shadowBounds, shadowClip;
933 if (layer->geometry.boundaries == layer->shadow.boundaries) {
934 shadowBounds = bounds;
935 shadowClip = roundRectClip;
936 } else {
937 std::tie(shadowBounds, shadowClip) =
938 getBoundsAndClip(layer->shadow.boundaries,
939 layer->geometry.roundedCornersCrop,
940 layer->geometry.roundedCornersRadius);
941 }
942
Leon Scroggins III63e86952021-05-12 10:45:08 -0400943 // Technically, if bounds is a rect and roundRectClip is not empty,
944 // it means that the bounds and roundedCornersCrop were different
945 // enough that we should intersect them to find the proper shadow.
946 // In practice, this often happens when the two rectangles appear to
947 // not match due to rounding errors. Draw the rounded version, which
948 // looks more like the intent.
949 const auto& rrect =
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400950 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
Leon Scroggins III63e86952021-05-12 10:45:08 -0400951 drawShadow(canvas, rrect, layer->shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500952 }
953
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500954 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
955 (mUseColorManagement &&
John Reckac09e452021-04-07 16:35:37 -0400956 needsToneMapping(layer->sourceDataspace, display.outputDataspace)) ||
957 (display.sdrWhitePointNits > 0.f &&
958 display.sdrWhitePointNits != display.maxLuminance);
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500959
960 // quick abort from drawing the remaining portion of the layer
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400961 if (layer->skipContentDraw ||
962 (layer->alpha == 0 && !requiresLinearEffect && !layer->disableBlending &&
963 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500964 continue;
965 }
966
967 // If we need to map to linear space or color management is disabled, then mark the source
968 // image with the same colorspace as the destination surface so that Skia's color
969 // management is a no-op.
970 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
971 ? dstDataspace
972 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800973
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500974 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700975 if (layer->source.buffer.buffer) {
976 ATRACE_NAME("DrawImage");
Alec Mouria90a5702021-04-16 16:36:21 +0000977 validateInputBufferUsage(layer->source.buffer.buffer->getBuffer());
John Reck67b1e2b2020-08-26 13:17:24 -0700978 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800979 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +0000980
981 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
982 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800983 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700984 } else {
Alec Mouria90a5702021-04-16 16:36:21 +0000985 // If we didn't find the image in the cache, then create a local ref but don't cache
986 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
987 // we didn't find anything in the cache then we intentionally did not cache this
988 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400989 imageTextureRef = std::make_shared<
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400990 AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400991 item.buffer->getBuffer()->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400992 false, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -0700993 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800994
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -0400995 // isOpaque means we need to ignore the alpha in the image,
996 // replacing it with the alpha specified by the LayerSettings. See
997 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
998 // The proper way to do this is to use an SkColorType that ignores
999 // alpha, like kRGB_888x_SkColorType, and that is used if the
1000 // incoming image is kRGBA_8888_SkColorType. However, the incoming
1001 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
1002 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
1003 // kRGB_101010x_SkColorType, but it is not yet supported as a source
1004 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
1005 // meantime, we'll use a workaround that works unless we need to do
1006 // any color conversion. The workaround requires that we pretend the
1007 // image is already premultiplied, so that we do not premultiply it
1008 // before applying SkBlendMode::kPlus.
1009 const bool useIsOpaqueWorkaround = item.isOpaque &&
1010 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
1011 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
1012 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
1013 : item.isOpaque ? kOpaque_SkAlphaType
1014 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
1015 : kUnpremul_SkAlphaType;
1016 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -07001017
1018 auto texMatrix = getSkM44(item.textureTransform).asM33();
1019 // textureTansform was intended to be passed directly into a shader, so when
1020 // building the total matrix with the textureTransform we need to first
1021 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001022 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001023 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -07001024
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001025 SkMatrix matrix;
1026 if (!texMatrix.invert(&matrix)) {
1027 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -07001028 }
Ana Krulecf9a15d92020-12-11 08:35:00 -08001029 // The shader does not respect the translation, so we add it to the texture
1030 // transform for the SkImage. This will make sure that the correct layer contents
1031 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001032 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -07001033
Ana Krulecb7b28b22020-11-23 14:48:58 -08001034 sk_sp<SkShader> shader;
1035
1036 if (layer->source.buffer.useTextureFiltering) {
1037 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1038 SkSamplingOptions(
1039 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1040 &matrix);
1041 } else {
Mike Reed711e1f02020-12-11 13:06:19 -05001042 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -08001043 }
Alec Mouri029d1952020-10-12 10:37:08 -07001044
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001045 if (useIsOpaqueWorkaround) {
Alec Mouric0aae732021-01-12 13:32:18 -08001046 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1047 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001048 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001049 }
1050
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001051 paint.setShader(createRuntimeEffectShader(shader, layer, display,
1052 !item.isOpaque && item.usePremultipliedAlpha,
1053 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -08001054 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -07001055 } else {
1056 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -07001057 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001058 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1059 .fG = color.g,
1060 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -08001061 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001062 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -08001063 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001064 /* undoPremultipliedAlpha */ false,
1065 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -07001066 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001067
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001068 if (layer->disableBlending) {
1069 paint.setBlendMode(SkBlendMode::kSrc);
1070 }
1071
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001072 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -07001073
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001074 if (!roundRectClip.isEmpty()) {
1075 canvas->clipRRect(roundRectClip, true);
1076 }
1077
1078 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001079 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001080 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001081 } else {
Nader Jawad63644d32021-05-07 10:44:21 -07001082 canvas->drawRect(bounds.rect(), paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -07001083 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001084 if (kFlushAfterEveryLayer) {
1085 ATRACE_NAME("flush surface");
1086 activeSurface->flush();
1087 }
John Reck67b1e2b2020-08-26 13:17:24 -07001088 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001089 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001090 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001091 {
1092 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001093 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1094 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001095 }
1096
1097 if (drawFence != nullptr) {
1098 *drawFence = flush();
1099 }
1100
1101 // If flush failed or we don't support native fences, we need to force the
1102 // gl command stream to be executed.
1103 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
1104 if (requireSync) {
1105 ATRACE_BEGIN("Submit(sync=true)");
1106 } else {
1107 ATRACE_BEGIN("Submit(sync=false)");
1108 }
Lucas Dupind508e472020-11-04 04:32:06 +00001109 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001110 ATRACE_END();
1111 if (!success) {
1112 ALOGE("Failed to flush RenderEngine commands");
1113 // Chances are, something illegal happened (either the caller passed
1114 // us bad parameters, or we messed up our shader generation).
1115 return INVALID_OPERATION;
1116 }
1117
1118 // checkErrors();
1119 return NO_ERROR;
1120}
1121
Lucas Dupin3f11e922020-09-22 17:31:04 -07001122inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1123 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1124}
1125
1126inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1127 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1128}
1129
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001130/**
1131 * Verifies that common, simple bounds + clip combinations can be converted into
1132 * a single RRect draw call returning true if possible. If true the radii parameter
1133 * will be filled with the correct radii values that combined with bounds param will
1134 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
1135 */
1136static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
1137 const SkRect& insetCrop, float cornerRadius,
1138 SkVector radii[4]) {
1139 const bool leftEqual = bounds.fLeft == crop.fLeft;
1140 const bool topEqual = bounds.fTop == crop.fTop;
1141 const bool rightEqual = bounds.fRight == crop.fRight;
1142 const bool bottomEqual = bounds.fBottom == crop.fBottom;
1143
1144 // In the event that the corners of the bounds only partially align with the crop we
1145 // need to ensure that the resulting shape can still be represented as a round rect.
1146 // In particular the round rect implementation will scale the value of all corner radii
1147 // if the sum of the radius along any edge is greater than the length of that edge.
1148 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
1149 const bool requiredWidth = bounds.width() > (cornerRadius * 2);
1150 const bool requiredHeight = bounds.height() > (cornerRadius * 2);
1151 if (!requiredWidth || !requiredHeight) {
1152 return false;
1153 }
1154
1155 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
1156 // contained within the cropped shape and does not need rounded.
1157 // compute the UpperLeft corner radius
1158 if (leftEqual && topEqual) {
1159 radii[0].set(cornerRadius, cornerRadius);
1160 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
1161 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
1162 radii[0].set(0, 0);
1163 } else {
1164 return false;
1165 }
1166 // compute the UpperRight corner radius
1167 if (rightEqual && topEqual) {
1168 radii[1].set(cornerRadius, cornerRadius);
1169 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
1170 (topEqual && bounds.fRight <= insetCrop.fRight)) {
1171 radii[1].set(0, 0);
1172 } else {
1173 return false;
1174 }
1175 // compute the BottomRight corner radius
1176 if (rightEqual && bottomEqual) {
1177 radii[2].set(cornerRadius, cornerRadius);
1178 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
1179 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
1180 radii[2].set(0, 0);
1181 } else {
1182 return false;
1183 }
1184 // compute the BottomLeft corner radius
1185 if (leftEqual && bottomEqual) {
1186 radii[3].set(cornerRadius, cornerRadius);
1187 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
1188 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
1189 radii[3].set(0, 0);
1190 } else {
1191 return false;
1192 }
1193
1194 return true;
1195}
1196
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001197inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(const FloatRect& boundsRect,
1198 const FloatRect& cropRect,
1199 const float cornerRadius) {
1200 const SkRect bounds = getSkRect(boundsRect);
1201 const SkRect crop = getSkRect(cropRect);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001202
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001203 SkRRect clip;
1204 if (cornerRadius > 0) {
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001205 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
1206 if (bounds == crop || crop.isEmpty()) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001207 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1208 }
1209
1210 // This makes an effort to speed up common, simple bounds + clip combinations by
1211 // converting them to a single RRect draw. It is possible there are other cases
1212 // that can be converted.
1213 if (crop.contains(bounds)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001214 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001215 if (insetCrop.contains(bounds)) {
1216 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001217 }
1218
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001219 SkVector radii[4];
1220 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001221 SkRRect intersectionBounds;
1222 intersectionBounds.setRectRadii(bounds, radii);
1223 return {intersectionBounds, clip};
1224 }
1225 }
1226
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001227 // we didn't hit any of our fast paths so set the clip to the cropRect
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001228 clip.setRectXY(crop, cornerRadius, cornerRadius);
1229 }
1230
1231 // if we hit this point then we either don't have rounded corners or we are going to rely
1232 // on the clip to round the corners for us
1233 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001234}
1235
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001236inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer,
1237 bool colorTransformModifiesAlpha) {
1238 if (layer->backgroundBlurRadius > 0 || layer->blurRegions.size()) {
1239 // return false if the content is opaque and would therefore occlude the blur
1240 const bool opaqueContent = !layer->source.buffer.buffer || layer->source.buffer.isOpaque;
1241 const bool opaqueAlpha = layer->alpha == 1.0f && !colorTransformModifiesAlpha;
1242 return layer->skipContentDraw || !(opaqueContent && opaqueAlpha);
1243 }
1244 return false;
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001245}
1246
Lucas Dupin3f11e922020-09-22 17:31:04 -07001247inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1248 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1249}
1250
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001251inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1252 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1253 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1254 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1255 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1256}
1257
Lucas Dupin3f11e922020-09-22 17:31:04 -07001258inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1259 return SkPoint3::Make(vector.x, vector.y, vector.z);
1260}
1261
John Reck67b1e2b2020-08-26 13:17:24 -07001262size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1263 return mGrContext->maxTextureSize();
1264}
1265
1266size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1267 return mGrContext->maxRenderTargetSize();
1268}
1269
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001270void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001271 const ShadowSettings& settings) {
1272 ATRACE_CALL();
1273 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001274 const auto flags =
1275 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1276
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001277 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001278 getSkPoint3(settings.lightPos), settings.lightRadius,
1279 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1280 flags);
1281}
1282
John Reck67b1e2b2020-08-26 13:17:24 -07001283EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001284 EGLContext shareContext,
1285 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001286 Protection protection) {
1287 EGLint renderableType = 0;
1288 if (config == EGL_NO_CONFIG_KHR) {
1289 renderableType = EGL_OPENGL_ES3_BIT;
1290 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1291 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1292 }
1293 EGLint contextClientVersion = 0;
1294 if (renderableType & EGL_OPENGL_ES3_BIT) {
1295 contextClientVersion = 3;
1296 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1297 contextClientVersion = 2;
1298 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1299 contextClientVersion = 1;
1300 } else {
1301 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1302 }
1303
1304 std::vector<EGLint> contextAttributes;
1305 contextAttributes.reserve(7);
1306 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1307 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001308 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001309 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001310 switch (*contextPriority) {
1311 case ContextPriority::REALTIME:
1312 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1313 break;
1314 case ContextPriority::MEDIUM:
1315 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1316 break;
1317 case ContextPriority::LOW:
1318 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1319 break;
1320 case ContextPriority::HIGH:
1321 default:
1322 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1323 break;
1324 }
John Reck67b1e2b2020-08-26 13:17:24 -07001325 }
1326 if (protection == Protection::PROTECTED) {
1327 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1328 contextAttributes.push_back(EGL_TRUE);
1329 }
1330 contextAttributes.push_back(EGL_NONE);
1331
1332 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1333
1334 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1335 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1336 // EGL_NO_CONTEXT so that we can abort.
1337 if (config != EGL_NO_CONFIG_KHR) {
1338 return context;
1339 }
1340 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1341 // should try to fall back to GLES 2.
1342 contextAttributes[1] = 2;
1343 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1344 }
1345
1346 return context;
1347}
1348
Alec Mourid6f09462020-12-07 11:18:17 -08001349std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1350 const RenderEngineCreationArgs& args) {
1351 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1352 return std::nullopt;
1353 }
1354
1355 switch (args.contextPriority) {
1356 case RenderEngine::ContextPriority::REALTIME:
1357 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1358 return RenderEngine::ContextPriority::REALTIME;
1359 } else {
1360 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1361 return RenderEngine::ContextPriority::HIGH;
1362 }
1363 case RenderEngine::ContextPriority::HIGH:
1364 case RenderEngine::ContextPriority::MEDIUM:
1365 case RenderEngine::ContextPriority::LOW:
1366 return args.contextPriority;
1367 default:
1368 return std::nullopt;
1369 }
1370}
1371
John Reck67b1e2b2020-08-26 13:17:24 -07001372EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1373 EGLConfig config, int hwcFormat,
1374 Protection protection) {
1375 EGLConfig placeholderConfig = config;
1376 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1377 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1378 }
1379 std::vector<EGLint> attributes;
1380 attributes.reserve(7);
1381 attributes.push_back(EGL_WIDTH);
1382 attributes.push_back(1);
1383 attributes.push_back(EGL_HEIGHT);
1384 attributes.push_back(1);
1385 if (protection == Protection::PROTECTED) {
1386 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1387 attributes.push_back(EGL_TRUE);
1388 }
1389 attributes.push_back(EGL_NONE);
1390
1391 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1392}
1393
Alec Mourid6f09462020-12-07 11:18:17 -08001394int SkiaGLRenderEngine::getContextPriority() {
1395 int value;
1396 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1397 return value;
1398}
1399
Ady Abrahamed3290f2021-05-17 15:12:14 -07001400void SkiaGLRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001401 // This cache multiplier was selected based on review of cache sizes relative
1402 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1403 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1404 // conservative default based on that analysis.
1405 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1406 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1407
1408 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001409 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001410
1411 // if it is possible to switch contexts then we will resize the other context
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001412 const bool originalProtectedState = mInProtectedContext;
1413 useProtectedContext(!mInProtectedContext);
1414 if (mInProtectedContext != originalProtectedState) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001415 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001416 // reset back to the initial context that was active when this method was called
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001417 useProtectedContext(originalProtectedState);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001418 }
1419}
1420
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001421void SkiaGLRenderEngine::dump(std::string& result) {
1422 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1423
1424 StringAppendF(&result, "\n ------------RE-----------------\n");
1425 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1426 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1427 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1428 extensions.getVersion());
1429 StringAppendF(&result, "%s\n", extensions.getExtensions());
1430 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1431 supportsProtectedContent());
1432 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001433 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1434 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001435
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001436 std::vector<ResourcePair> cpuResourceMap = {
1437 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1438 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1439 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1440 {"skia/sk_resource_cache/tessellated", "Shadows"},
1441 {"skia", "Other"},
1442 };
1443 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1444 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1445 StringAppendF(&result, "Skia CPU Caches: ");
1446 cpuReporter.logTotals(result);
1447 cpuReporter.logOutput(result);
1448
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001449 {
1450 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001451
1452 std::vector<ResourcePair> gpuResourceMap = {
1453 {"texture_renderbuffer", "Texture/RenderBuffer"},
1454 {"texture", "Texture"},
1455 {"gr_text_blob_cache", "Text"},
1456 {"skia", "Other"},
1457 };
1458 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1459 mGrContext->dumpMemoryStatistics(&gpuReporter);
1460 StringAppendF(&result, "Skia's GPU Caches: ");
1461 gpuReporter.logTotals(result);
1462 gpuReporter.logOutput(result);
1463 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1464 gpuReporter.logOutput(result, true);
1465
Alec Mouria90a5702021-04-16 16:36:21 +00001466 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1467 mGraphicBufferExternalRefs.size());
1468 StringAppendF(&result, "Dumping buffer ids...\n");
1469 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1470 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1471 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001472 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1473 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001474 StringAppendF(&result, "Dumping buffer ids...\n");
1475 // TODO(178539829): It would be nice to know which layer these are coming from and what
1476 // the texture sizes are.
1477 for (const auto& [id, unused] : mTextureCache) {
1478 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1479 }
1480 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001481
1482 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001483 if (mProtectedGrContext) {
1484 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1485 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001486 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1487 gpuProtectedReporter.logTotals(result);
1488 gpuProtectedReporter.logOutput(result);
1489 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1490 gpuProtectedReporter.logOutput(result, true);
1491
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001492 StringAppendF(&result, "\n");
1493 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1494 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1495 StringAppendF(&result, "- inputDataspace: %s\n",
1496 dataspaceDetails(
1497 static_cast<android_dataspace>(linearEffect.inputDataspace))
1498 .c_str());
1499 StringAppendF(&result, "- outputDataspace: %s\n",
1500 dataspaceDetails(
1501 static_cast<android_dataspace>(linearEffect.outputDataspace))
1502 .c_str());
1503 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1504 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1505 }
1506 }
1507 StringAppendF(&result, "\n");
1508}
1509
John Reck67b1e2b2020-08-26 13:17:24 -07001510} // namespace skia
1511} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001512} // namespace android