blob: d28d623b7f321c328c6cbba29f825898fad1f4b5 [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);
323 if (useProtectedContext(true)) {
324 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
325 useProtectedContext(false);
326 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700327
328 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500329 ALOGD("Background Blurs Enabled");
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700330 mBlurFilter = new BlurFilter();
331 }
Alec Mouric0aae732021-01-12 13:32:18 -0800332 mCapture = std::make_unique<SkiaCapture>();
333}
334
335SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100336 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800337 if (mBlurFilter) {
338 delete mBlurFilter;
339 }
340
341 mCapture = nullptr;
342
343 mGrContext->flushAndSubmit(true);
344 mGrContext->abandonContext();
345
346 if (mProtectedGrContext) {
347 mProtectedGrContext->flushAndSubmit(true);
348 mProtectedGrContext->abandonContext();
349 }
350
351 if (mPlaceholderSurface != EGL_NO_SURFACE) {
352 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
353 }
354 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
355 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
356 }
357 if (mEGLContext != EGL_NO_CONTEXT) {
358 eglDestroyContext(mEGLDisplay, mEGLContext);
359 }
360 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
361 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
362 }
363 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
364 eglTerminate(mEGLDisplay);
365 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700366}
367
Lucas Dupind508e472020-11-04 04:32:06 +0000368bool SkiaGLRenderEngine::supportsProtectedContent() const {
369 return mProtectedEGLContext != EGL_NO_CONTEXT;
370}
371
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400372GrDirectContext* SkiaGLRenderEngine::getActiveGrContext() const {
373 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
374}
375
Lucas Dupind508e472020-11-04 04:32:06 +0000376bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
377 if (useProtectedContext == mInProtectedContext) {
378 return true;
379 }
Alec Mourif6a07812021-02-11 21:07:55 -0800380 if (useProtectedContext && !supportsProtectedContent()) {
Lucas Dupind508e472020-11-04 04:32:06 +0000381 return false;
382 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400383
384 // release any scratch resources before switching into a new mode
385 if (getActiveGrContext()) {
386 getActiveGrContext()->purgeUnlockedResources(true);
387 }
388
Lucas Dupind508e472020-11-04 04:32:06 +0000389 const EGLSurface surface =
390 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
391 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
392 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800393
Lucas Dupind508e472020-11-04 04:32:06 +0000394 if (success) {
395 mInProtectedContext = useProtectedContext;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400396 // given that we are sharing the same thread between two GrContexts we need to
397 // make sure that the thread state is reset when switching between the two.
398 if (getActiveGrContext()) {
399 getActiveGrContext()->resetContext();
400 }
Lucas Dupind508e472020-11-04 04:32:06 +0000401 }
402 return success;
403}
404
John Reck67b1e2b2020-08-26 13:17:24 -0700405base::unique_fd SkiaGLRenderEngine::flush() {
406 ATRACE_CALL();
407 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
408 return base::unique_fd();
409 }
410
411 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
412 if (sync == EGL_NO_SYNC_KHR) {
413 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
414 return base::unique_fd();
415 }
416
417 // native fence fd will not be populated until flush() is done.
418 glFlush();
419
420 // get the fence fd
421 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
422 eglDestroySyncKHR(mEGLDisplay, sync);
423 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
424 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
425 }
426
427 return fenceFd;
428}
429
430bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
431 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
432 !gl::GLExtensions::getInstance().hasWaitSync()) {
433 return false;
434 }
435
436 // release the fd and transfer the ownership to EGLSync
437 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
438 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
439 if (sync == EGL_NO_SYNC_KHR) {
440 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
441 return false;
442 }
443
444 // XXX: The spec draft is inconsistent as to whether this should return an
445 // EGLint or void. Ignore the return value for now, as it's not strictly
446 // needed.
447 eglWaitSyncKHR(mEGLDisplay, sync, 0);
448 EGLint error = eglGetError();
449 eglDestroySyncKHR(mEGLDisplay, sync);
450 if (error != EGL_SUCCESS) {
451 ALOGE("failed to wait for EGL native fence sync: %#x", error);
452 return false;
453 }
454
455 return true;
456}
457
Alec Mouri678245d2020-09-30 16:58:23 -0700458static float toDegrees(uint32_t transform) {
459 switch (transform) {
460 case ui::Transform::ROT_90:
461 return 90.0;
462 case ui::Transform::ROT_180:
463 return 180.0;
464 case ui::Transform::ROT_270:
465 return 270.0;
466 default:
467 return 0.0;
468 }
469}
470
Alec Mourib34f0b72020-10-02 13:18:34 -0700471static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
472 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
473 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
474 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
475 matrix[3][3], 0);
476}
477
Alec Mouri029d1952020-10-12 10:37:08 -0700478static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
479 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
480 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
481
482 // Treat unsupported dataspaces as srgb
483 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
484 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
485 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
486 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
487 }
488
489 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
490 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
491 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
492 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
493 }
494
495 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
496 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
497 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
498 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
499
500 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
501 sourceTransfer != destTransfer;
502}
503
Alec Mouria90a5702021-04-16 16:36:21 +0000504void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
505 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800506 // Only run this if RE is running on its own thread. This way the access to GL
507 // operations is guaranteed to be happening on the same thread.
508 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
509 return;
510 }
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400511 // We currently don't attempt to map a buffer if the buffer contains protected content
Derek Sollenberger45007182021-06-10 14:47:21 -0400512 // because GPU resources for protected buffers is much more limited.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400513 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Derek Sollenberger45007182021-06-10 14:47:21 -0400514 if (isProtectedBuffer) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400515 return;
516 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800517 ATRACE_CALL();
518
Derek Sollenberger45007182021-06-10 14:47:21 -0400519 // If we were to support caching protected buffers then we will need to switch the
520 // currently bound context if we are not already using the protected context (and subsequently
521 // switch back after the buffer is cached). However, for non-protected content we can bind
522 // the texture in either GL context because they are initialized with the same share_context
523 // which allows the texture state to be shared between them.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400524 auto grContext = getActiveGrContext();
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400525 auto& cache = mTextureCache;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400526
527 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000528 mGraphicBufferExternalRefs[buffer->getId()]++;
529
530 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800531 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400532 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400533 buffer->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400534 isRenderable, mTextureCleanupMgr);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400535 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800536 }
537}
538
Alec Mouria90a5702021-04-16 16:36:21 +0000539void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800540 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700541 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000542 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
543 iter != mGraphicBufferExternalRefs.end()) {
544 if (iter->second == 0) {
545 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
546 "> from RenderEngine texture, but the "
547 "ref count was already zero!",
548 buffer->getId());
549 mGraphicBufferExternalRefs.erase(buffer->getId());
550 return;
551 }
552
553 iter->second--;
554
555 if (iter->second == 0) {
556 mTextureCache.erase(buffer->getId());
Alec Mouria90a5702021-04-16 16:36:21 +0000557 mGraphicBufferExternalRefs.erase(buffer->getId());
558 }
559 }
John Reck67b1e2b2020-08-26 13:17:24 -0700560}
561
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400562bool SkiaGLRenderEngine::canSkipPostRenderCleanup() const {
563 std::lock_guard<std::mutex> lock(mRenderingMutex);
564 return mTextureCleanupMgr.isEmpty();
565}
566
567void SkiaGLRenderEngine::cleanupPostRender() {
568 ATRACE_CALL();
569 std::lock_guard<std::mutex> lock(mRenderingMutex);
570 mTextureCleanupMgr.cleanup();
571}
572
573// Helper class intended to be used on the stack to ensure that texture cleanup
574// is deferred until after this class goes out of scope.
575class DeferTextureCleanup final {
576public:
577 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
578 mMgr.setDeferredStatus(true);
579 }
580 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
581
582private:
583 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
584 AutoBackendTexture::CleanupManager& mMgr;
585};
586
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700587sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
588 sk_sp<SkShader> shader,
589 const LayerSettings* layer, const DisplaySettings& display, bool undoPremultipliedAlpha,
590 bool requiresLinearEffect) {
591 const auto stretchEffect = layer->stretchEffect;
Nader Jawad63644d32021-05-07 10:44:21 -0700592 // The given surface will be stretched by HWUI via matrix transformation
593 // which gets similar results for most surfaces
594 // Determine later on if we need to leverage the stertch shader within
595 // surface flinger
Nader Jawadc088bdc2021-05-10 13:24:46 -0700596 if (stretchEffect.hasEffect()) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700597 const auto targetBuffer = layer->source.buffer.buffer;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700598 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
599 if (graphicBuffer && shader) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700600 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
601 }
John Reckcdb4ed72021-02-04 13:39:33 -0500602 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700603
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500604 if (requiresLinearEffect) {
605 const ui::Dataspace inputDataspace =
606 mUseColorManagement ? layer->sourceDataspace : ui::Dataspace::UNKNOWN;
607 const ui::Dataspace outputDataspace =
608 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
609
610 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
611 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800612 .undoPremultipliedAlpha = undoPremultipliedAlpha};
613
614 auto effectIter = mRuntimeEffects.find(effect);
615 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
616 if (effectIter == mRuntimeEffects.end()) {
617 runtimeEffect = buildRuntimeEffect(effect);
618 mRuntimeEffects.insert({effect, runtimeEffect});
619 } else {
620 runtimeEffect = effectIter->second;
621 }
John Reckac09e452021-04-07 16:35:37 -0400622 float maxLuminance = layer->source.buffer.maxLuminanceNits;
623 // If the buffer doesn't have a max luminance, treat it as SDR & use the display's SDR
624 // white point
625 if (maxLuminance <= 0.f) {
626 maxLuminance = display.sdrWhitePointNits;
627 }
Ana Krulec47814212021-01-06 19:00:10 -0800628 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
John Reckac09e452021-04-07 16:35:37 -0400629 display.maxLuminance, maxLuminance);
Ana Krulec47814212021-01-06 19:00:10 -0800630 }
631 return shader;
632}
633
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500634void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500635 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500636 // Record display settings when capture is running.
637 std::stringstream displaySettings;
638 PrintTo(display, &displaySettings);
639 // Store the DisplaySettings in additional information.
640 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
641 SkData::MakeWithCString(displaySettings.str().c_str()));
642 }
643
644 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
645 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
646 // displays might have different scaling when compared to the physical screen.
647
648 canvas->clipRect(getSkRect(display.physicalDisplay));
649 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
650
651 const auto clipWidth = display.clip.width();
652 const auto clipHeight = display.clip.height();
653 auto rotatedClipWidth = clipWidth;
654 auto rotatedClipHeight = clipHeight;
655 // Scale is contingent on the rotation result.
656 if (display.orientation & ui::Transform::ROT_90) {
657 std::swap(rotatedClipWidth, rotatedClipHeight);
658 }
659 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
660 static_cast<SkScalar>(rotatedClipWidth);
661 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
662 static_cast<SkScalar>(rotatedClipHeight);
663 canvas->scale(scaleX, scaleY);
664
665 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
666 // back so that the top left corner of the clip is at (0, 0).
667 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
668 canvas->rotate(toDegrees(display.orientation));
669 canvas->translate(-clipWidth / 2, -clipHeight / 2);
670 canvas->translate(-display.clip.left, -display.clip.top);
671}
672
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500673class AutoSaveRestore {
674public:
675 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
676 ~AutoSaveRestore() { restore(); }
677 void replace(SkCanvas* canvas) {
678 mCanvas = canvas;
679 mSaveCount = canvas->save();
680 }
681 void restore() {
682 if (mCanvas) {
683 mCanvas->restoreToCount(mSaveCount);
684 mCanvas = nullptr;
685 }
686 }
687
688private:
689 SkCanvas* mCanvas;
690 int mSaveCount;
691};
692
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400693static SkRRect getBlurRRect(const BlurRegion& region) {
694 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
695 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
696 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
697 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
698 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
699 SkRRect roundedRect;
700 roundedRect.setRectRadii(rect, radii);
701 return roundedRect;
702}
703
John Reck67b1e2b2020-08-26 13:17:24 -0700704status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
705 const std::vector<const LayerSettings*>& layers,
Alec Mouria90a5702021-04-16 16:36:21 +0000706 const std::shared_ptr<ExternalTexture>& buffer,
707 const bool /*useFramebufferCache*/,
John Reck67b1e2b2020-08-26 13:17:24 -0700708 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
709 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800710
John Reck67b1e2b2020-08-26 13:17:24 -0700711 std::lock_guard<std::mutex> lock(mRenderingMutex);
712 if (layers.empty()) {
713 ALOGV("Drawing empty layer stack");
714 return NO_ERROR;
715 }
716
717 if (bufferFence.get() >= 0) {
718 // Duplicate the fence for passing to waitFence.
719 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
720 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
721 ATRACE_NAME("Waiting before draw");
722 sync_wait(bufferFence.get(), -1);
723 }
724 }
725 if (buffer == nullptr) {
726 ALOGE("No output buffer provided. Aborting GPU composition.");
727 return BAD_VALUE;
728 }
729
Alec Mouria90a5702021-04-16 16:36:21 +0000730 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800731
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400732 auto grContext = getActiveGrContext();
Derek Sollenberger45007182021-06-10 14:47:21 -0400733 auto& cache = mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700734
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400735 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
736 DeferTextureCleanup dtc(mTextureCleanupMgr);
737
Alec Mouria90a5702021-04-16 16:36:21 +0000738 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
739 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
740 surfaceTextureRef = it->second;
741 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400742 surfaceTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400743 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
744 buffer->getBuffer()
745 ->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400746 true, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -0700747 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800748
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500749 const ui::Dataspace dstDataspace =
750 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400751 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700752
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500753 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
754 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800755 ALOGE("Cannot acquire canvas from Skia.");
756 return BAD_VALUE;
757 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500758
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400759 // setup color filter if necessary
760 sk_sp<SkColorFilter> displayColorTransform;
761 if (display.colorTransform != mat4()) {
762 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
763 }
764 const bool ctModifiesAlpha =
765 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
766
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500767 // Find if any layers have requested blur, we'll use that info to decide when to render to an
768 // offscreen buffer and when to render to the native buffer.
769 sk_sp<SkSurface> activeSurface(dstSurface);
770 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500771 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500772 const LayerSettings* blurCompositionLayer = nullptr;
773 if (mBlurFilter) {
774 bool requiresCompositionLayer = false;
775 for (const auto& layer : layers) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400776 // if the layer doesn't have blur or it is not visible then continue
777 if (!layerHasBlur(layer, ctModifiesAlpha)) {
778 continue;
779 }
Derek Sollenberger3134ec32021-02-12 11:26:23 -0500780 if (layer->backgroundBlurRadius > 0 &&
781 layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500782 requiresCompositionLayer = true;
783 }
784 for (auto region : layer->blurRegions) {
785 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
786 requiresCompositionLayer = true;
787 }
788 }
789 if (requiresCompositionLayer) {
790 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500791 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500792 blurCompositionLayer = layer;
793 break;
794 }
795 }
796 }
797
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500798 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700799 // Clear the entire canvas with a transparent black to prevent ghost images.
800 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500801 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800802
803 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
804 // view is still on-screen. The clear region could be re-specified as a black color layer,
805 // however.
806 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500807 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800808 size_t numRects = 0;
809 Rect const* rects = display.clearRegion.getArray(&numRects);
810 SkIRect skRects[numRects];
811 for (int i = 0; i < numRects; ++i) {
812 skRects[i] =
813 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
814 }
815 SkRegion clearRegion;
816 SkPaint paint;
817 sk_sp<SkShader> shader =
818 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500819 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800820 paint.setShader(shader);
821 clearRegion.setRects(skRects, numRects);
822 canvas->drawRegion(clearRegion, paint);
823 }
824
John Reck67b1e2b2020-08-26 13:17:24 -0700825 for (const auto& layer : layers) {
Alec Mouricbd30932021-06-09 15:52:25 -0700826 ATRACE_FORMAT("DrawLayer: %s", layer->name.c_str());
Galia Peychevaf7889b32020-11-25 22:22:40 +0100827
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400828 if (kPrintLayerSettings) {
829 std::stringstream ls;
830 PrintTo(*layer, &ls);
831 auto debugs = ls.str();
832 int pos = 0;
833 while (pos < debugs.size()) {
834 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
835 pos += 1000;
836 }
837 }
838
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500839 sk_sp<SkImage> blurInput;
840 if (blurCompositionLayer == layer) {
841 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
842 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
843
844 // save a snapshot of the activeSurface to use as input to the blur shaders
845 blurInput = activeSurface->makeImageSnapshot();
846
847 // TODO we could skip this step if we know the blur will cover the entire image
848 // blit the offscreen framebuffer into the destination AHB
849 SkPaint paint;
850 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500851 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
852 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
853 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
854 String8::format("SurfaceID|%" PRId64, id).c_str(),
855 nullptr);
856 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
857 } else {
858 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
859 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500860
861 // assign dstCanvas to canvas and ensure that the canvas state is up to date
862 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500863 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500864 initCanvas(canvas, display);
865
866 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
867 dstSurface->getCanvas()->getSaveCount());
868 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
869 dstSurface->getCanvas()->getTotalMatrix());
870
871 // assign dstSurface to activeSurface
872 activeSurface = dstSurface;
873 }
874
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500875 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500876 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800877 // Record the name of the layer if the capture is running.
878 std::stringstream layerSettings;
879 PrintTo(*layer, &layerSettings);
880 // Store the LayerSettings in additional information.
881 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
882 SkData::MakeWithCString(layerSettings.str().c_str()));
883 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100884 // Layers have a local transform that should be applied to them
885 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100886
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400887 const auto [bounds, roundRectClip] =
888 getBoundsAndClip(layer->geometry.boundaries, layer->geometry.roundedCornersCrop,
889 layer->geometry.roundedCornersRadius);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400890 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500891 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
892
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500893 // if multiple layers have blur, then we need to take a snapshot now because
894 // only the lowest layer will have blurImage populated earlier
895 if (!blurInput) {
896 blurInput = activeSurface->makeImageSnapshot();
897 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500898 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400899 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
900
901 // if the clip needs to be applied then apply it now and make sure
902 // it is restored before we attempt to draw any shadows.
903 SkAutoCanvasRestore acr(canvas, true);
904 if (!roundRectClip.isEmpty()) {
905 canvas->clipRRect(roundRectClip, true);
906 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500907
Galia Peychevae425ac82021-03-15 17:12:03 +0100908 // TODO(b/182216890): Filter out empty layers earlier
909 if (blurRect.width() > 0 && blurRect.height() > 0) {
910 if (layer->backgroundBlurRadius > 0) {
911 ATRACE_NAME("BackgroundBlur");
912 auto blurredImage =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400913 mBlurFilter->generate(grContext, layer->backgroundBlurRadius, blurInput,
914 blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100915
Galia Peychevae425ac82021-03-15 17:12:03 +0100916 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500917
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400918 mBlurFilter->drawBlurRegion(canvas, bounds, layer->backgroundBlurRadius, 1.0f,
919 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700920 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400921
Derek Sollenberger39feade2021-04-27 16:08:40 -0400922 canvas->concat(getSkM44(layer->blurRegionTransform).asM33());
Galia Peychevae425ac82021-03-15 17:12:03 +0100923 for (auto region : layer->blurRegions) {
924 if (cachedBlurs[region.blurRadius] == nullptr) {
925 ATRACE_NAME("BlurRegion");
926 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400927 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100928 blurRect);
929 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500930
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400931 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
932 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100933 cachedBlurs[region.blurRadius], blurInput);
934 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700935 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700936 }
937
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500938 if (layer->shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400939 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
940 LOG_ALWAYS_FATAL_IF(layer->disableBlending, "Cannot disableBlending with a shadow");
Leon Scroggins III63e86952021-05-12 10:45:08 -0400941
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400942 SkRRect shadowBounds, shadowClip;
943 if (layer->geometry.boundaries == layer->shadow.boundaries) {
944 shadowBounds = bounds;
945 shadowClip = roundRectClip;
946 } else {
947 std::tie(shadowBounds, shadowClip) =
948 getBoundsAndClip(layer->shadow.boundaries,
949 layer->geometry.roundedCornersCrop,
950 layer->geometry.roundedCornersRadius);
951 }
952
Leon Scroggins III63e86952021-05-12 10:45:08 -0400953 // Technically, if bounds is a rect and roundRectClip is not empty,
954 // it means that the bounds and roundedCornersCrop were different
955 // enough that we should intersect them to find the proper shadow.
956 // In practice, this often happens when the two rectangles appear to
957 // not match due to rounding errors. Draw the rounded version, which
958 // looks more like the intent.
959 const auto& rrect =
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400960 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
Leon Scroggins III63e86952021-05-12 10:45:08 -0400961 drawShadow(canvas, rrect, layer->shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500962 }
963
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500964 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
965 (mUseColorManagement &&
John Reckac09e452021-04-07 16:35:37 -0400966 needsToneMapping(layer->sourceDataspace, display.outputDataspace)) ||
967 (display.sdrWhitePointNits > 0.f &&
968 display.sdrWhitePointNits != display.maxLuminance);
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500969
970 // quick abort from drawing the remaining portion of the layer
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400971 if (layer->skipContentDraw ||
972 (layer->alpha == 0 && !requiresLinearEffect && !layer->disableBlending &&
973 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500974 continue;
975 }
976
977 // If we need to map to linear space or color management is disabled, then mark the source
978 // image with the same colorspace as the destination surface so that Skia's color
979 // management is a no-op.
980 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
981 ? dstDataspace
982 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800983
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500984 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700985 if (layer->source.buffer.buffer) {
986 ATRACE_NAME("DrawImage");
Alec Mouria90a5702021-04-16 16:36:21 +0000987 validateInputBufferUsage(layer->source.buffer.buffer->getBuffer());
John Reck67b1e2b2020-08-26 13:17:24 -0700988 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800989 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +0000990
991 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
992 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800993 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700994 } else {
Alec Mouria90a5702021-04-16 16:36:21 +0000995 // If we didn't find the image in the cache, then create a local ref but don't cache
996 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
997 // we didn't find anything in the cache then we intentionally did not cache this
998 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400999 imageTextureRef = std::make_shared<
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001000 AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001001 item.buffer->getBuffer()->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -04001002 false, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -07001003 }
Alec Mouri1a4d0642020-11-13 17:42:01 -08001004
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001005 // isOpaque means we need to ignore the alpha in the image,
1006 // replacing it with the alpha specified by the LayerSettings. See
1007 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
1008 // The proper way to do this is to use an SkColorType that ignores
1009 // alpha, like kRGB_888x_SkColorType, and that is used if the
1010 // incoming image is kRGBA_8888_SkColorType. However, the incoming
1011 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
1012 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
1013 // kRGB_101010x_SkColorType, but it is not yet supported as a source
1014 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
1015 // meantime, we'll use a workaround that works unless we need to do
1016 // any color conversion. The workaround requires that we pretend the
1017 // image is already premultiplied, so that we do not premultiply it
1018 // before applying SkBlendMode::kPlus.
1019 const bool useIsOpaqueWorkaround = item.isOpaque &&
1020 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
1021 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
1022 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
1023 : item.isOpaque ? kOpaque_SkAlphaType
1024 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
1025 : kUnpremul_SkAlphaType;
1026 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -07001027
1028 auto texMatrix = getSkM44(item.textureTransform).asM33();
1029 // textureTansform was intended to be passed directly into a shader, so when
1030 // building the total matrix with the textureTransform we need to first
1031 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001032 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001033 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -07001034
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001035 SkMatrix matrix;
1036 if (!texMatrix.invert(&matrix)) {
1037 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -07001038 }
Ana Krulecf9a15d92020-12-11 08:35:00 -08001039 // The shader does not respect the translation, so we add it to the texture
1040 // transform for the SkImage. This will make sure that the correct layer contents
1041 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001042 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -07001043
Ana Krulecb7b28b22020-11-23 14:48:58 -08001044 sk_sp<SkShader> shader;
1045
1046 if (layer->source.buffer.useTextureFiltering) {
1047 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1048 SkSamplingOptions(
1049 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1050 &matrix);
1051 } else {
Mike Reed711e1f02020-12-11 13:06:19 -05001052 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -08001053 }
Alec Mouri029d1952020-10-12 10:37:08 -07001054
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001055 if (useIsOpaqueWorkaround) {
Alec Mouric0aae732021-01-12 13:32:18 -08001056 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1057 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001058 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001059 }
1060
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001061 paint.setShader(createRuntimeEffectShader(shader, layer, display,
1062 !item.isOpaque && item.usePremultipliedAlpha,
1063 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -08001064 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -07001065 } else {
1066 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -07001067 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001068 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1069 .fG = color.g,
1070 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -08001071 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001072 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -08001073 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001074 /* undoPremultipliedAlpha */ false,
1075 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -07001076 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001077
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001078 if (layer->disableBlending) {
1079 paint.setBlendMode(SkBlendMode::kSrc);
1080 }
1081
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001082 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -07001083
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001084 if (!roundRectClip.isEmpty()) {
1085 canvas->clipRRect(roundRectClip, true);
1086 }
1087
1088 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001089 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001090 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001091 } else {
Nader Jawad63644d32021-05-07 10:44:21 -07001092 canvas->drawRect(bounds.rect(), paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -07001093 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001094 if (kFlushAfterEveryLayer) {
1095 ATRACE_NAME("flush surface");
1096 activeSurface->flush();
1097 }
John Reck67b1e2b2020-08-26 13:17:24 -07001098 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001099 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001100 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001101 {
1102 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001103 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1104 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001105 }
1106
1107 if (drawFence != nullptr) {
1108 *drawFence = flush();
1109 }
1110
1111 // If flush failed or we don't support native fences, we need to force the
1112 // gl command stream to be executed.
1113 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
1114 if (requireSync) {
1115 ATRACE_BEGIN("Submit(sync=true)");
1116 } else {
1117 ATRACE_BEGIN("Submit(sync=false)");
1118 }
Lucas Dupind508e472020-11-04 04:32:06 +00001119 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001120 ATRACE_END();
1121 if (!success) {
1122 ALOGE("Failed to flush RenderEngine commands");
1123 // Chances are, something illegal happened (either the caller passed
1124 // us bad parameters, or we messed up our shader generation).
1125 return INVALID_OPERATION;
1126 }
1127
1128 // checkErrors();
1129 return NO_ERROR;
1130}
1131
Lucas Dupin3f11e922020-09-22 17:31:04 -07001132inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1133 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1134}
1135
1136inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1137 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1138}
1139
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001140inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(const FloatRect& boundsRect,
1141 const FloatRect& cropRect,
1142 const float cornerRadius) {
1143 const SkRect bounds = getSkRect(boundsRect);
1144 const SkRect crop = getSkRect(cropRect);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001145
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001146 SkRRect clip;
1147 if (cornerRadius > 0) {
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001148 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
1149 if (bounds == crop || crop.isEmpty()) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001150 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1151 }
1152
1153 // This makes an effort to speed up common, simple bounds + clip combinations by
1154 // converting them to a single RRect draw. It is possible there are other cases
1155 // that can be converted.
1156 if (crop.contains(bounds)) {
1157 bool intersectionIsRoundRect = true;
1158 // check each cropped corner to ensure that it exactly matches the crop or is full
1159 SkVector radii[4];
1160
1161 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
1162
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001163 const bool leftEqual = bounds.fLeft == crop.fLeft;
1164 const bool topEqual = bounds.fTop == crop.fTop;
1165 const bool rightEqual = bounds.fRight == crop.fRight;
1166 const bool bottomEqual = bounds.fBottom == crop.fBottom;
1167
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001168 // compute the UpperLeft corner radius
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001169 if (leftEqual && topEqual) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001170 radii[0].set(cornerRadius, cornerRadius);
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001171 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
1172 (topEqual && bounds.fLeft >= insetCrop.fLeft) ||
1173 insetCrop.contains(bounds.fLeft, bounds.fTop)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001174 radii[0].set(0, 0);
1175 } else {
1176 intersectionIsRoundRect = false;
1177 }
1178 // compute the UpperRight corner radius
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001179 if (rightEqual && topEqual) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001180 radii[1].set(cornerRadius, cornerRadius);
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001181 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
1182 (topEqual && bounds.fRight <= insetCrop.fRight) ||
1183 insetCrop.contains(bounds.fRight, bounds.fTop)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001184 radii[1].set(0, 0);
1185 } else {
1186 intersectionIsRoundRect = false;
1187 }
1188 // compute the BottomRight corner radius
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001189 if (rightEqual && bottomEqual) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001190 radii[2].set(cornerRadius, cornerRadius);
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001191 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
1192 (bottomEqual && bounds.fRight <= insetCrop.fRight) ||
1193 insetCrop.contains(bounds.fRight, bounds.fBottom)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001194 radii[2].set(0, 0);
1195 } else {
1196 intersectionIsRoundRect = false;
1197 }
1198 // compute the BottomLeft corner radius
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001199 if (leftEqual && bottomEqual) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001200 radii[3].set(cornerRadius, cornerRadius);
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001201 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
1202 (bottomEqual && bounds.fLeft >= insetCrop.fLeft) ||
1203 insetCrop.contains(bounds.fLeft, bounds.fBottom)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001204 radii[3].set(0, 0);
1205 } else {
1206 intersectionIsRoundRect = false;
1207 }
1208
1209 if (intersectionIsRoundRect) {
1210 SkRRect intersectionBounds;
1211 intersectionBounds.setRectRadii(bounds, radii);
1212 return {intersectionBounds, clip};
1213 }
1214 }
1215
1216 // we didn't it any of our fast paths so set the clip to the cropRect
1217 clip.setRectXY(crop, cornerRadius, cornerRadius);
1218 }
1219
1220 // if we hit this point then we either don't have rounded corners or we are going to rely
1221 // on the clip to round the corners for us
1222 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001223}
1224
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001225inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer,
1226 bool colorTransformModifiesAlpha) {
1227 if (layer->backgroundBlurRadius > 0 || layer->blurRegions.size()) {
1228 // return false if the content is opaque and would therefore occlude the blur
1229 const bool opaqueContent = !layer->source.buffer.buffer || layer->source.buffer.isOpaque;
1230 const bool opaqueAlpha = layer->alpha == 1.0f && !colorTransformModifiesAlpha;
1231 return layer->skipContentDraw || !(opaqueContent && opaqueAlpha);
1232 }
1233 return false;
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001234}
1235
Lucas Dupin3f11e922020-09-22 17:31:04 -07001236inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1237 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1238}
1239
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001240inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1241 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1242 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1243 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1244 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1245}
1246
Lucas Dupin3f11e922020-09-22 17:31:04 -07001247inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1248 return SkPoint3::Make(vector.x, vector.y, vector.z);
1249}
1250
John Reck67b1e2b2020-08-26 13:17:24 -07001251size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1252 return mGrContext->maxTextureSize();
1253}
1254
1255size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1256 return mGrContext->maxRenderTargetSize();
1257}
1258
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001259void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001260 const ShadowSettings& settings) {
1261 ATRACE_CALL();
1262 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001263 const auto flags =
1264 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1265
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001266 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001267 getSkPoint3(settings.lightPos), settings.lightRadius,
1268 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1269 flags);
1270}
1271
John Reck67b1e2b2020-08-26 13:17:24 -07001272EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001273 EGLContext shareContext,
1274 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001275 Protection protection) {
1276 EGLint renderableType = 0;
1277 if (config == EGL_NO_CONFIG_KHR) {
1278 renderableType = EGL_OPENGL_ES3_BIT;
1279 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1280 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1281 }
1282 EGLint contextClientVersion = 0;
1283 if (renderableType & EGL_OPENGL_ES3_BIT) {
1284 contextClientVersion = 3;
1285 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1286 contextClientVersion = 2;
1287 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1288 contextClientVersion = 1;
1289 } else {
1290 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1291 }
1292
1293 std::vector<EGLint> contextAttributes;
1294 contextAttributes.reserve(7);
1295 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1296 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001297 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001298 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001299 switch (*contextPriority) {
1300 case ContextPriority::REALTIME:
1301 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1302 break;
1303 case ContextPriority::MEDIUM:
1304 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1305 break;
1306 case ContextPriority::LOW:
1307 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1308 break;
1309 case ContextPriority::HIGH:
1310 default:
1311 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1312 break;
1313 }
John Reck67b1e2b2020-08-26 13:17:24 -07001314 }
1315 if (protection == Protection::PROTECTED) {
1316 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1317 contextAttributes.push_back(EGL_TRUE);
1318 }
1319 contextAttributes.push_back(EGL_NONE);
1320
1321 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1322
1323 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1324 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1325 // EGL_NO_CONTEXT so that we can abort.
1326 if (config != EGL_NO_CONFIG_KHR) {
1327 return context;
1328 }
1329 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1330 // should try to fall back to GLES 2.
1331 contextAttributes[1] = 2;
1332 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1333 }
1334
1335 return context;
1336}
1337
Alec Mourid6f09462020-12-07 11:18:17 -08001338std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1339 const RenderEngineCreationArgs& args) {
1340 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1341 return std::nullopt;
1342 }
1343
1344 switch (args.contextPriority) {
1345 case RenderEngine::ContextPriority::REALTIME:
1346 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1347 return RenderEngine::ContextPriority::REALTIME;
1348 } else {
1349 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1350 return RenderEngine::ContextPriority::HIGH;
1351 }
1352 case RenderEngine::ContextPriority::HIGH:
1353 case RenderEngine::ContextPriority::MEDIUM:
1354 case RenderEngine::ContextPriority::LOW:
1355 return args.contextPriority;
1356 default:
1357 return std::nullopt;
1358 }
1359}
1360
John Reck67b1e2b2020-08-26 13:17:24 -07001361EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1362 EGLConfig config, int hwcFormat,
1363 Protection protection) {
1364 EGLConfig placeholderConfig = config;
1365 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1366 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1367 }
1368 std::vector<EGLint> attributes;
1369 attributes.reserve(7);
1370 attributes.push_back(EGL_WIDTH);
1371 attributes.push_back(1);
1372 attributes.push_back(EGL_HEIGHT);
1373 attributes.push_back(1);
1374 if (protection == Protection::PROTECTED) {
1375 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1376 attributes.push_back(EGL_TRUE);
1377 }
1378 attributes.push_back(EGL_NONE);
1379
1380 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1381}
1382
Alec Mourid6f09462020-12-07 11:18:17 -08001383int SkiaGLRenderEngine::getContextPriority() {
1384 int value;
1385 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1386 return value;
1387}
1388
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001389void SkiaGLRenderEngine::onPrimaryDisplaySizeChanged(ui::Size size) {
1390 // This cache multiplier was selected based on review of cache sizes relative
1391 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1392 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1393 // conservative default based on that analysis.
1394 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1395 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1396
1397 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001398 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001399
1400 // if it is possible to switch contexts then we will resize the other context
1401 if (useProtectedContext(!mInProtectedContext)) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001402 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001403 // reset back to the initial context that was active when this method was called
1404 useProtectedContext(!mInProtectedContext);
1405 }
1406}
1407
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001408void SkiaGLRenderEngine::dump(std::string& result) {
1409 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1410
1411 StringAppendF(&result, "\n ------------RE-----------------\n");
1412 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1413 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1414 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1415 extensions.getVersion());
1416 StringAppendF(&result, "%s\n", extensions.getExtensions());
1417 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1418 supportsProtectedContent());
1419 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001420 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1421 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001422
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001423 std::vector<ResourcePair> cpuResourceMap = {
1424 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1425 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1426 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1427 {"skia/sk_resource_cache/tessellated", "Shadows"},
1428 {"skia", "Other"},
1429 };
1430 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1431 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1432 StringAppendF(&result, "Skia CPU Caches: ");
1433 cpuReporter.logTotals(result);
1434 cpuReporter.logOutput(result);
1435
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001436 {
1437 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001438
1439 std::vector<ResourcePair> gpuResourceMap = {
1440 {"texture_renderbuffer", "Texture/RenderBuffer"},
1441 {"texture", "Texture"},
1442 {"gr_text_blob_cache", "Text"},
1443 {"skia", "Other"},
1444 };
1445 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1446 mGrContext->dumpMemoryStatistics(&gpuReporter);
1447 StringAppendF(&result, "Skia's GPU Caches: ");
1448 gpuReporter.logTotals(result);
1449 gpuReporter.logOutput(result);
1450 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1451 gpuReporter.logOutput(result, true);
1452
Alec Mouria90a5702021-04-16 16:36:21 +00001453 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1454 mGraphicBufferExternalRefs.size());
1455 StringAppendF(&result, "Dumping buffer ids...\n");
1456 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1457 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1458 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001459 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1460 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001461 StringAppendF(&result, "Dumping buffer ids...\n");
1462 // TODO(178539829): It would be nice to know which layer these are coming from and what
1463 // the texture sizes are.
1464 for (const auto& [id, unused] : mTextureCache) {
1465 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1466 }
1467 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001468
1469 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001470 if (mProtectedGrContext) {
1471 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1472 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001473 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1474 gpuProtectedReporter.logTotals(result);
1475 gpuProtectedReporter.logOutput(result);
1476 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1477 gpuProtectedReporter.logOutput(result, true);
1478
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001479 StringAppendF(&result, "\n");
1480 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1481 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1482 StringAppendF(&result, "- inputDataspace: %s\n",
1483 dataspaceDetails(
1484 static_cast<android_dataspace>(linearEffect.inputDataspace))
1485 .c_str());
1486 StringAppendF(&result, "- outputDataspace: %s\n",
1487 dataspaceDetails(
1488 static_cast<android_dataspace>(linearEffect.outputDataspace))
1489 .c_str());
1490 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1491 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1492 }
1493 }
1494 StringAppendF(&result, "\n");
1495}
1496
John Reck67b1e2b2020-08-26 13:17:24 -07001497} // namespace skia
1498} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001499} // namespace android