blob: d5ec774e9ca922d492f331bac8cc9a3b8de7761e [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
Alec Mouri4ee7b492021-08-11 10:36:55 -0700427void SkiaGLRenderEngine::waitFence(base::borrowed_fd fenceFd) {
428 if (fenceFd.get() >= 0 && !waitGpuFence(fenceFd)) {
429 ATRACE_NAME("SkiaGLRenderEngine::waitFence");
430 sync_wait(fenceFd.get(), -1);
431 }
432}
433
434bool SkiaGLRenderEngine::waitGpuFence(base::borrowed_fd fenceFd) {
John Reck67b1e2b2020-08-26 13:17:24 -0700435 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
436 !gl::GLExtensions::getInstance().hasWaitSync()) {
437 return false;
438 }
439
Alec Mouri4ee7b492021-08-11 10:36:55 -0700440 // Duplicate the fence for passing to eglCreateSyncKHR.
441 base::unique_fd fenceDup(dup(fenceFd.get()));
442 if (fenceDup.get() < 0) {
443 ALOGE("failed to create duplicate fence fd: %d", fenceDup.get());
444 return false;
445 }
446
John Reck67b1e2b2020-08-26 13:17:24 -0700447 // release the fd and transfer the ownership to EGLSync
Alec Mouri4ee7b492021-08-11 10:36:55 -0700448 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceDup.release(), EGL_NONE};
John Reck67b1e2b2020-08-26 13:17:24 -0700449 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
450 if (sync == EGL_NO_SYNC_KHR) {
451 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
452 return false;
453 }
454
455 // XXX: The spec draft is inconsistent as to whether this should return an
456 // EGLint or void. Ignore the return value for now, as it's not strictly
457 // needed.
458 eglWaitSyncKHR(mEGLDisplay, sync, 0);
459 EGLint error = eglGetError();
460 eglDestroySyncKHR(mEGLDisplay, sync);
461 if (error != EGL_SUCCESS) {
462 ALOGE("failed to wait for EGL native fence sync: %#x", error);
463 return false;
464 }
465
466 return true;
467}
468
Alec Mouri678245d2020-09-30 16:58:23 -0700469static float toDegrees(uint32_t transform) {
470 switch (transform) {
471 case ui::Transform::ROT_90:
472 return 90.0;
473 case ui::Transform::ROT_180:
474 return 180.0;
475 case ui::Transform::ROT_270:
476 return 270.0;
477 default:
478 return 0.0;
479 }
480}
481
Alec Mourib34f0b72020-10-02 13:18:34 -0700482static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
483 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
484 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
485 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
486 matrix[3][3], 0);
487}
488
Alec Mouri029d1952020-10-12 10:37:08 -0700489static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
490 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
491 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
492
493 // Treat unsupported dataspaces as srgb
494 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
495 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
496 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
497 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
498 }
499
500 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
501 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
502 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
503 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
504 }
505
506 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
507 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
508 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
509 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
510
511 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
512 sourceTransfer != destTransfer;
513}
514
Alec Mouria90a5702021-04-16 16:36:21 +0000515void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
516 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800517 // Only run this if RE is running on its own thread. This way the access to GL
518 // operations is guaranteed to be happening on the same thread.
519 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
520 return;
521 }
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400522 // We currently don't attempt to map a buffer if the buffer contains protected content
Derek Sollenberger45007182021-06-10 14:47:21 -0400523 // because GPU resources for protected buffers is much more limited.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400524 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Derek Sollenberger45007182021-06-10 14:47:21 -0400525 if (isProtectedBuffer) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400526 return;
527 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800528 ATRACE_CALL();
529
Derek Sollenberger45007182021-06-10 14:47:21 -0400530 // If we were to support caching protected buffers then we will need to switch the
531 // currently bound context if we are not already using the protected context (and subsequently
532 // switch back after the buffer is cached). However, for non-protected content we can bind
533 // the texture in either GL context because they are initialized with the same share_context
534 // which allows the texture state to be shared between them.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400535 auto grContext = getActiveGrContext();
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400536 auto& cache = mTextureCache;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400537
538 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000539 mGraphicBufferExternalRefs[buffer->getId()]++;
540
541 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800542 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400543 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400544 buffer->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400545 isRenderable, mTextureCleanupMgr);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400546 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800547 }
548}
549
Alec Mouria90a5702021-04-16 16:36:21 +0000550void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800551 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700552 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000553 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
554 iter != mGraphicBufferExternalRefs.end()) {
555 if (iter->second == 0) {
556 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
557 "> from RenderEngine texture, but the "
558 "ref count was already zero!",
559 buffer->getId());
560 mGraphicBufferExternalRefs.erase(buffer->getId());
561 return;
562 }
563
564 iter->second--;
565
Alec Mouric2ffeb42021-06-17 17:42:27 -0700566 // Swap contexts if needed prior to deleting this buffer
567 // See Issue 1 of
568 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
569 // when a protected context and an unprotected context are part of the same share group,
570 // protected surfaces may not be accessed by an unprotected context, implying that protected
571 // surfaces may only be freed when a protected context is active.
572 const bool inProtected = mInProtectedContext;
573 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
574
Alec Mouria90a5702021-04-16 16:36:21 +0000575 if (iter->second == 0) {
576 mTextureCache.erase(buffer->getId());
Alec Mouria90a5702021-04-16 16:36:21 +0000577 mGraphicBufferExternalRefs.erase(buffer->getId());
578 }
Alec Mouric2ffeb42021-06-17 17:42:27 -0700579
580 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
581 // are up-to-date.
582 if (inProtected != mInProtectedContext) {
583 useProtectedContext(inProtected);
584 }
Alec Mouria90a5702021-04-16 16:36:21 +0000585 }
John Reck67b1e2b2020-08-26 13:17:24 -0700586}
587
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400588bool SkiaGLRenderEngine::canSkipPostRenderCleanup() const {
589 std::lock_guard<std::mutex> lock(mRenderingMutex);
590 return mTextureCleanupMgr.isEmpty();
591}
592
593void SkiaGLRenderEngine::cleanupPostRender() {
594 ATRACE_CALL();
595 std::lock_guard<std::mutex> lock(mRenderingMutex);
596 mTextureCleanupMgr.cleanup();
597}
598
599// Helper class intended to be used on the stack to ensure that texture cleanup
600// is deferred until after this class goes out of scope.
601class DeferTextureCleanup final {
602public:
603 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
604 mMgr.setDeferredStatus(true);
605 }
606 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
607
608private:
609 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
610 AutoBackendTexture::CleanupManager& mMgr;
611};
612
Sally Qi59a9f502021-10-12 18:53:23 +0000613sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
614 const LayerSettings& layer,
615 const DisplaySettings& display,
616 bool undoPremultipliedAlpha,
617 bool requiresLinearEffect) {
618 const auto stretchEffect = layer.stretchEffect;
Nader Jawad63644d32021-05-07 10:44:21 -0700619 // The given surface will be stretched by HWUI via matrix transformation
620 // which gets similar results for most surfaces
621 // Determine later on if we need to leverage the stertch shader within
622 // surface flinger
Nader Jawadc088bdc2021-05-10 13:24:46 -0700623 if (stretchEffect.hasEffect()) {
Sally Qi59a9f502021-10-12 18:53:23 +0000624 const auto targetBuffer = layer.source.buffer.buffer;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700625 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
626 if (graphicBuffer && shader) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700627 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
628 }
John Reckcdb4ed72021-02-04 13:39:33 -0500629 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700630
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500631 if (requiresLinearEffect) {
632 const ui::Dataspace inputDataspace =
Sally Qi59a9f502021-10-12 18:53:23 +0000633 mUseColorManagement ? layer.sourceDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500634 const ui::Dataspace outputDataspace =
Alec Mourid2bcbae2021-06-28 17:02:17 -0700635 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500636
637 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
638 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800639 .undoPremultipliedAlpha = undoPremultipliedAlpha};
640
641 auto effectIter = mRuntimeEffects.find(effect);
642 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
643 if (effectIter == mRuntimeEffects.end()) {
644 runtimeEffect = buildRuntimeEffect(effect);
645 mRuntimeEffects.insert({effect, runtimeEffect});
646 } else {
647 runtimeEffect = effectIter->second;
648 }
Sally Qi59a9f502021-10-12 18:53:23 +0000649 float maxLuminance = layer.source.buffer.maxLuminanceNits;
John Reckac09e452021-04-07 16:35:37 -0400650 // If the buffer doesn't have a max luminance, treat it as SDR & use the display's SDR
651 // white point
652 if (maxLuminance <= 0.f) {
653 maxLuminance = display.sdrWhitePointNits;
654 }
Sally Qi59a9f502021-10-12 18:53:23 +0000655 return createLinearEffectShader(shader, effect, runtimeEffect, layer.colorTransform,
John Reckac09e452021-04-07 16:35:37 -0400656 display.maxLuminance, maxLuminance);
Ana Krulec47814212021-01-06 19:00:10 -0800657 }
658 return shader;
659}
660
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500661void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500662 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500663 // Record display settings when capture is running.
664 std::stringstream displaySettings;
665 PrintTo(display, &displaySettings);
666 // Store the DisplaySettings in additional information.
667 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
668 SkData::MakeWithCString(displaySettings.str().c_str()));
669 }
670
671 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
672 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
673 // displays might have different scaling when compared to the physical screen.
674
675 canvas->clipRect(getSkRect(display.physicalDisplay));
676 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
677
678 const auto clipWidth = display.clip.width();
679 const auto clipHeight = display.clip.height();
680 auto rotatedClipWidth = clipWidth;
681 auto rotatedClipHeight = clipHeight;
682 // Scale is contingent on the rotation result.
683 if (display.orientation & ui::Transform::ROT_90) {
684 std::swap(rotatedClipWidth, rotatedClipHeight);
685 }
686 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
687 static_cast<SkScalar>(rotatedClipWidth);
688 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
689 static_cast<SkScalar>(rotatedClipHeight);
690 canvas->scale(scaleX, scaleY);
691
692 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
693 // back so that the top left corner of the clip is at (0, 0).
694 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
695 canvas->rotate(toDegrees(display.orientation));
696 canvas->translate(-clipWidth / 2, -clipHeight / 2);
697 canvas->translate(-display.clip.left, -display.clip.top);
698}
699
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500700class AutoSaveRestore {
701public:
702 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
703 ~AutoSaveRestore() { restore(); }
704 void replace(SkCanvas* canvas) {
705 mCanvas = canvas;
706 mSaveCount = canvas->save();
707 }
708 void restore() {
709 if (mCanvas) {
710 mCanvas->restoreToCount(mSaveCount);
711 mCanvas = nullptr;
712 }
713 }
714
715private:
716 SkCanvas* mCanvas;
717 int mSaveCount;
718};
719
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400720static SkRRect getBlurRRect(const BlurRegion& region) {
721 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
722 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
723 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
724 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
725 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
726 SkRRect roundedRect;
727 roundedRect.setRectRadii(rect, radii);
728 return roundedRect;
729}
730
Sally Qi4cabdd02021-08-05 16:45:57 -0700731void SkiaGLRenderEngine::drawLayersInternal(
732 const std::shared_ptr<std::promise<RenderEngineResult>>&& resultPromise,
Sally Qi59a9f502021-10-12 18:53:23 +0000733 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
Sally Qi4cabdd02021-08-05 16:45:57 -0700734 const std::shared_ptr<ExternalTexture>& buffer, const bool /*useFramebufferCache*/,
735 base::unique_fd&& bufferFence) {
John Reck67b1e2b2020-08-26 13:17:24 -0700736 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800737
John Reck67b1e2b2020-08-26 13:17:24 -0700738 std::lock_guard<std::mutex> lock(mRenderingMutex);
739 if (layers.empty()) {
740 ALOGV("Drawing empty layer stack");
Sally Qi4cabdd02021-08-05 16:45:57 -0700741 resultPromise->set_value({NO_ERROR, base::unique_fd()});
742 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700743 }
744
John Reck67b1e2b2020-08-26 13:17:24 -0700745 if (buffer == nullptr) {
746 ALOGE("No output buffer provided. Aborting GPU composition.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700747 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
748 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700749 }
750
Alec Mouria90a5702021-04-16 16:36:21 +0000751 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800752
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400753 auto grContext = getActiveGrContext();
Derek Sollenberger45007182021-06-10 14:47:21 -0400754 auto& cache = mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700755
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400756 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
757 DeferTextureCleanup dtc(mTextureCleanupMgr);
758
Alec Mouria90a5702021-04-16 16:36:21 +0000759 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
760 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
761 surfaceTextureRef = it->second;
762 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400763 surfaceTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400764 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
765 buffer->getBuffer()
766 ->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400767 true, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -0700768 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800769
Alec Mouri4ee7b492021-08-11 10:36:55 -0700770 // wait on the buffer to be ready to use prior to using it
771 waitFence(bufferFence);
772
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500773 const ui::Dataspace dstDataspace =
Alec Mourid2bcbae2021-06-28 17:02:17 -0700774 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400775 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700776
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500777 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
778 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800779 ALOGE("Cannot acquire canvas from Skia.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700780 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
781 return;
Ana Krulec6eab17a2020-12-09 15:52:36 -0800782 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500783
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400784 // setup color filter if necessary
785 sk_sp<SkColorFilter> displayColorTransform;
786 if (display.colorTransform != mat4()) {
787 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
788 }
789 const bool ctModifiesAlpha =
790 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
791
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500792 // Find if any layers have requested blur, we'll use that info to decide when to render to an
793 // offscreen buffer and when to render to the native buffer.
794 sk_sp<SkSurface> activeSurface(dstSurface);
795 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500796 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500797 const LayerSettings* blurCompositionLayer = nullptr;
798 if (mBlurFilter) {
799 bool requiresCompositionLayer = false;
800 for (const auto& layer : layers) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400801 // if the layer doesn't have blur or it is not visible then continue
802 if (!layerHasBlur(layer, ctModifiesAlpha)) {
803 continue;
804 }
Sally Qi59a9f502021-10-12 18:53:23 +0000805 if (layer.backgroundBlurRadius > 0 &&
806 layer.backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500807 requiresCompositionLayer = true;
808 }
Sally Qi59a9f502021-10-12 18:53:23 +0000809 for (auto region : layer.blurRegions) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500810 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
811 requiresCompositionLayer = true;
812 }
813 }
814 if (requiresCompositionLayer) {
815 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500816 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Sally Qi59a9f502021-10-12 18:53:23 +0000817 blurCompositionLayer = &layer;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500818 break;
819 }
820 }
821 }
822
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500823 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700824 // Clear the entire canvas with a transparent black to prevent ghost images.
825 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500826 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800827
John Reck67b1e2b2020-08-26 13:17:24 -0700828 for (const auto& layer : layers) {
Sally Qi59a9f502021-10-12 18:53:23 +0000829 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
Galia Peychevaf7889b32020-11-25 22:22:40 +0100830
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400831 if (kPrintLayerSettings) {
832 std::stringstream ls;
Sally Qi59a9f502021-10-12 18:53:23 +0000833 PrintTo(layer, &ls);
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400834 auto debugs = ls.str();
835 int pos = 0;
836 while (pos < debugs.size()) {
837 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
838 pos += 1000;
839 }
840 }
841
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500842 sk_sp<SkImage> blurInput;
Sally Qi59a9f502021-10-12 18:53:23 +0000843 if (blurCompositionLayer == &layer) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500844 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
845 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
846
847 // save a snapshot of the activeSurface to use as input to the blur shaders
848 blurInput = activeSurface->makeImageSnapshot();
849
850 // TODO we could skip this step if we know the blur will cover the entire image
851 // blit the offscreen framebuffer into the destination AHB
852 SkPaint paint;
853 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500854 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
855 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
856 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
857 String8::format("SurfaceID|%" PRId64, id).c_str(),
858 nullptr);
859 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
860 } else {
861 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
862 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500863
864 // assign dstCanvas to canvas and ensure that the canvas state is up to date
865 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500866 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500867 initCanvas(canvas, display);
868
869 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
870 dstSurface->getCanvas()->getSaveCount());
871 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
872 dstSurface->getCanvas()->getTotalMatrix());
873
874 // assign dstSurface to activeSurface
875 activeSurface = dstSurface;
876 }
877
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500878 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500879 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800880 // Record the name of the layer if the capture is running.
881 std::stringstream layerSettings;
Sally Qi59a9f502021-10-12 18:53:23 +0000882 PrintTo(layer, &layerSettings);
Ana Krulec6eab17a2020-12-09 15:52:36 -0800883 // Store the LayerSettings in additional information.
Sally Qi59a9f502021-10-12 18:53:23 +0000884 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
Ana Krulec6eab17a2020-12-09 15:52:36 -0800885 SkData::MakeWithCString(layerSettings.str().c_str()));
886 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100887 // Layers have a local transform that should be applied to them
Sally Qi59a9f502021-10-12 18:53:23 +0000888 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100889
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400890 const auto [bounds, roundRectClip] =
Sally Qi59a9f502021-10-12 18:53:23 +0000891 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
892 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400893 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500894 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
895
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500896 // if multiple layers have blur, then we need to take a snapshot now because
897 // only the lowest layer will have blurImage populated earlier
898 if (!blurInput) {
899 blurInput = activeSurface->makeImageSnapshot();
900 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500901 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400902 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
903
904 // if the clip needs to be applied then apply it now and make sure
905 // it is restored before we attempt to draw any shadows.
906 SkAutoCanvasRestore acr(canvas, true);
907 if (!roundRectClip.isEmpty()) {
908 canvas->clipRRect(roundRectClip, true);
909 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500910
Galia Peychevae425ac82021-03-15 17:12:03 +0100911 // TODO(b/182216890): Filter out empty layers earlier
912 if (blurRect.width() > 0 && blurRect.height() > 0) {
Sally Qi59a9f502021-10-12 18:53:23 +0000913 if (layer.backgroundBlurRadius > 0) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100914 ATRACE_NAME("BackgroundBlur");
Sally Qi59a9f502021-10-12 18:53:23 +0000915 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
916 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100917
Sally Qi59a9f502021-10-12 18:53:23 +0000918 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500919
Sally Qi59a9f502021-10-12 18:53:23 +0000920 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400921 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700922 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400923
Sally Qi59a9f502021-10-12 18:53:23 +0000924 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
925 for (auto region : layer.blurRegions) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100926 if (cachedBlurs[region.blurRadius] == nullptr) {
927 ATRACE_NAME("BlurRegion");
928 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400929 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100930 blurRect);
931 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500932
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400933 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
934 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100935 cachedBlurs[region.blurRadius], blurInput);
936 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700937 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700938 }
939
Sally Qi59a9f502021-10-12 18:53:23 +0000940 if (layer.shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400941 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
Sally Qi59a9f502021-10-12 18:53:23 +0000942 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
Leon Scroggins III63e86952021-05-12 10:45:08 -0400943
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400944 SkRRect shadowBounds, shadowClip;
Sally Qi59a9f502021-10-12 18:53:23 +0000945 if (layer.geometry.boundaries == layer.shadow.boundaries) {
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400946 shadowBounds = bounds;
947 shadowClip = roundRectClip;
948 } else {
949 std::tie(shadowBounds, shadowClip) =
Sally Qi59a9f502021-10-12 18:53:23 +0000950 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
951 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400952 }
953
Leon Scroggins III63e86952021-05-12 10:45:08 -0400954 // Technically, if bounds is a rect and roundRectClip is not empty,
955 // it means that the bounds and roundedCornersCrop were different
956 // enough that we should intersect them to find the proper shadow.
957 // In practice, this often happens when the two rectangles appear to
958 // not match due to rounding errors. Draw the rounded version, which
959 // looks more like the intent.
960 const auto& rrect =
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400961 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
Sally Qi59a9f502021-10-12 18:53:23 +0000962 drawShadow(canvas, rrect, layer.shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500963 }
964
Sally Qi59a9f502021-10-12 18:53:23 +0000965 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500966 (mUseColorManagement &&
Sally Qi59a9f502021-10-12 18:53:23 +0000967 needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
John Reckac09e452021-04-07 16:35:37 -0400968 (display.sdrWhitePointNits > 0.f &&
969 display.sdrWhitePointNits != display.maxLuminance);
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500970
971 // quick abort from drawing the remaining portion of the layer
Sally Qi59a9f502021-10-12 18:53:23 +0000972 if (layer.skipContentDraw ||
973 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400974 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500975 continue;
976 }
977
978 // If we need to map to linear space or color management is disabled, then mark the source
979 // image with the same colorspace as the destination surface so that Skia's color
980 // management is a no-op.
981 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
982 ? dstDataspace
Sally Qi59a9f502021-10-12 18:53:23 +0000983 : layer.sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800984
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500985 SkPaint paint;
Sally Qi59a9f502021-10-12 18:53:23 +0000986 if (layer.source.buffer.buffer) {
John Reck67b1e2b2020-08-26 13:17:24 -0700987 ATRACE_NAME("DrawImage");
Sally Qi59a9f502021-10-12 18:53:23 +0000988 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
989 const auto& item = layer.source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800990 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +0000991
992 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
993 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800994 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700995 } else {
Alec Mouria90a5702021-04-16 16:36:21 +0000996 // If we didn't find the image in the cache, then create a local ref but don't cache
997 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
998 // we didn't find anything in the cache then we intentionally did not cache this
999 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001000 imageTextureRef = std::make_shared<
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001001 AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001002 item.buffer->getBuffer()->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -04001003 false, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -07001004 }
Alec Mouri1a4d0642020-11-13 17:42:01 -08001005
Alec Mouri4ee7b492021-08-11 10:36:55 -07001006 // if the layer's buffer has a fence, then we must must respect the fence prior to using
1007 // the buffer.
Sally Qi59a9f502021-10-12 18:53:23 +00001008 if (layer.source.buffer.fence != nullptr) {
1009 waitFence(layer.source.buffer.fence->get());
Alec Mouri4ee7b492021-08-11 10:36:55 -07001010 }
1011
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001012 // isOpaque means we need to ignore the alpha in the image,
1013 // replacing it with the alpha specified by the LayerSettings. See
1014 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
1015 // The proper way to do this is to use an SkColorType that ignores
1016 // alpha, like kRGB_888x_SkColorType, and that is used if the
1017 // incoming image is kRGBA_8888_SkColorType. However, the incoming
1018 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
1019 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
1020 // kRGB_101010x_SkColorType, but it is not yet supported as a source
1021 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
1022 // meantime, we'll use a workaround that works unless we need to do
1023 // any color conversion. The workaround requires that we pretend the
1024 // image is already premultiplied, so that we do not premultiply it
1025 // before applying SkBlendMode::kPlus.
1026 const bool useIsOpaqueWorkaround = item.isOpaque &&
1027 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
1028 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
1029 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
1030 : item.isOpaque ? kOpaque_SkAlphaType
1031 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
1032 : kUnpremul_SkAlphaType;
1033 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -07001034
1035 auto texMatrix = getSkM44(item.textureTransform).asM33();
1036 // textureTansform was intended to be passed directly into a shader, so when
1037 // building the total matrix with the textureTransform we need to first
1038 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001039 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001040 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -07001041
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001042 SkMatrix matrix;
1043 if (!texMatrix.invert(&matrix)) {
1044 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -07001045 }
Ana Krulecf9a15d92020-12-11 08:35:00 -08001046 // The shader does not respect the translation, so we add it to the texture
1047 // transform for the SkImage. This will make sure that the correct layer contents
1048 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001049 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -07001050
Ana Krulecb7b28b22020-11-23 14:48:58 -08001051 sk_sp<SkShader> shader;
1052
Sally Qi59a9f502021-10-12 18:53:23 +00001053 if (layer.source.buffer.useTextureFiltering) {
Ana Krulecb7b28b22020-11-23 14:48:58 -08001054 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1055 SkSamplingOptions(
1056 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1057 &matrix);
1058 } else {
Mike Reed711e1f02020-12-11 13:06:19 -05001059 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -08001060 }
Alec Mouri029d1952020-10-12 10:37:08 -07001061
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001062 if (useIsOpaqueWorkaround) {
Alec Mouric0aae732021-01-12 13:32:18 -08001063 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1064 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001065 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001066 }
1067
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001068 paint.setShader(createRuntimeEffectShader(shader, layer, display,
1069 !item.isOpaque && item.usePremultipliedAlpha,
1070 requiresLinearEffect));
Sally Qi59a9f502021-10-12 18:53:23 +00001071 paint.setAlphaf(layer.alpha);
John Reck67b1e2b2020-08-26 13:17:24 -07001072 } else {
1073 ATRACE_NAME("DrawColor");
Sally Qi59a9f502021-10-12 18:53:23 +00001074 const auto color = layer.source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001075 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1076 .fG = color.g,
1077 .fB = color.b,
Sally Qi59a9f502021-10-12 18:53:23 +00001078 .fA = layer.alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001079 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -08001080 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001081 /* undoPremultipliedAlpha */ false,
1082 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -07001083 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001084
Sally Qi59a9f502021-10-12 18:53:23 +00001085 if (layer.disableBlending) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001086 paint.setBlendMode(SkBlendMode::kSrc);
1087 }
1088
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001089 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -07001090
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001091 if (!roundRectClip.isEmpty()) {
1092 canvas->clipRRect(roundRectClip, true);
1093 }
1094
1095 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001096 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001097 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001098 } else {
Nader Jawad63644d32021-05-07 10:44:21 -07001099 canvas->drawRect(bounds.rect(), paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -07001100 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001101 if (kFlushAfterEveryLayer) {
1102 ATRACE_NAME("flush surface");
1103 activeSurface->flush();
1104 }
John Reck67b1e2b2020-08-26 13:17:24 -07001105 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001106 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001107 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001108 {
1109 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001110 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1111 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001112 }
1113
Sally Qi4cabdd02021-08-05 16:45:57 -07001114 base::unique_fd drawFence = flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001115
1116 // If flush failed or we don't support native fences, we need to force the
1117 // gl command stream to be executed.
Sally Qi4cabdd02021-08-05 16:45:57 -07001118 bool requireSync = drawFence.get() < 0;
John Reck67b1e2b2020-08-26 13:17:24 -07001119 if (requireSync) {
1120 ATRACE_BEGIN("Submit(sync=true)");
1121 } else {
1122 ATRACE_BEGIN("Submit(sync=false)");
1123 }
Lucas Dupind508e472020-11-04 04:32:06 +00001124 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001125 ATRACE_END();
1126 if (!success) {
1127 ALOGE("Failed to flush RenderEngine commands");
1128 // Chances are, something illegal happened (either the caller passed
1129 // us bad parameters, or we messed up our shader generation).
Sally Qi4cabdd02021-08-05 16:45:57 -07001130 resultPromise->set_value({INVALID_OPERATION, std::move(drawFence)});
1131 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001132 }
1133
1134 // checkErrors();
Sally Qi4cabdd02021-08-05 16:45:57 -07001135 resultPromise->set_value({NO_ERROR, std::move(drawFence)});
1136 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001137}
1138
Lucas Dupin3f11e922020-09-22 17:31:04 -07001139inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1140 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1141}
1142
1143inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1144 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1145}
1146
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001147/**
1148 * Verifies that common, simple bounds + clip combinations can be converted into
1149 * a single RRect draw call returning true if possible. If true the radii parameter
1150 * will be filled with the correct radii values that combined with bounds param will
1151 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
1152 */
1153static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
1154 const SkRect& insetCrop, float cornerRadius,
1155 SkVector radii[4]) {
1156 const bool leftEqual = bounds.fLeft == crop.fLeft;
1157 const bool topEqual = bounds.fTop == crop.fTop;
1158 const bool rightEqual = bounds.fRight == crop.fRight;
1159 const bool bottomEqual = bounds.fBottom == crop.fBottom;
1160
1161 // In the event that the corners of the bounds only partially align with the crop we
1162 // need to ensure that the resulting shape can still be represented as a round rect.
1163 // In particular the round rect implementation will scale the value of all corner radii
1164 // if the sum of the radius along any edge is greater than the length of that edge.
1165 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
1166 const bool requiredWidth = bounds.width() > (cornerRadius * 2);
1167 const bool requiredHeight = bounds.height() > (cornerRadius * 2);
1168 if (!requiredWidth || !requiredHeight) {
1169 return false;
1170 }
1171
1172 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
1173 // contained within the cropped shape and does not need rounded.
1174 // compute the UpperLeft corner radius
1175 if (leftEqual && topEqual) {
1176 radii[0].set(cornerRadius, cornerRadius);
1177 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
1178 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
1179 radii[0].set(0, 0);
1180 } else {
1181 return false;
1182 }
1183 // compute the UpperRight corner radius
1184 if (rightEqual && topEqual) {
1185 radii[1].set(cornerRadius, cornerRadius);
1186 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
1187 (topEqual && bounds.fRight <= insetCrop.fRight)) {
1188 radii[1].set(0, 0);
1189 } else {
1190 return false;
1191 }
1192 // compute the BottomRight corner radius
1193 if (rightEqual && bottomEqual) {
1194 radii[2].set(cornerRadius, cornerRadius);
1195 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
1196 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
1197 radii[2].set(0, 0);
1198 } else {
1199 return false;
1200 }
1201 // compute the BottomLeft corner radius
1202 if (leftEqual && bottomEqual) {
1203 radii[3].set(cornerRadius, cornerRadius);
1204 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
1205 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
1206 radii[3].set(0, 0);
1207 } else {
1208 return false;
1209 }
1210
1211 return true;
1212}
1213
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001214inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(const FloatRect& boundsRect,
1215 const FloatRect& cropRect,
1216 const float cornerRadius) {
1217 const SkRect bounds = getSkRect(boundsRect);
1218 const SkRect crop = getSkRect(cropRect);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001219
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001220 SkRRect clip;
1221 if (cornerRadius > 0) {
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001222 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
1223 if (bounds == crop || crop.isEmpty()) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001224 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1225 }
1226
1227 // This makes an effort to speed up common, simple bounds + clip combinations by
1228 // converting them to a single RRect draw. It is possible there are other cases
1229 // that can be converted.
1230 if (crop.contains(bounds)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001231 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001232 if (insetCrop.contains(bounds)) {
1233 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001234 }
1235
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001236 SkVector radii[4];
1237 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001238 SkRRect intersectionBounds;
1239 intersectionBounds.setRectRadii(bounds, radii);
1240 return {intersectionBounds, clip};
1241 }
1242 }
1243
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001244 // we didn't hit any of our fast paths so set the clip to the cropRect
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001245 clip.setRectXY(crop, cornerRadius, cornerRadius);
1246 }
1247
1248 // if we hit this point then we either don't have rounded corners or we are going to rely
1249 // on the clip to round the corners for us
1250 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001251}
1252
Sally Qi59a9f502021-10-12 18:53:23 +00001253inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings& layer,
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001254 bool colorTransformModifiesAlpha) {
Sally Qi59a9f502021-10-12 18:53:23 +00001255 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001256 // return false if the content is opaque and would therefore occlude the blur
Sally Qi59a9f502021-10-12 18:53:23 +00001257 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
1258 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
1259 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001260 }
1261 return false;
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001262}
1263
Lucas Dupin3f11e922020-09-22 17:31:04 -07001264inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1265 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1266}
1267
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001268inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1269 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1270 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1271 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1272 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1273}
1274
Lucas Dupin3f11e922020-09-22 17:31:04 -07001275inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1276 return SkPoint3::Make(vector.x, vector.y, vector.z);
1277}
1278
John Reck67b1e2b2020-08-26 13:17:24 -07001279size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1280 return mGrContext->maxTextureSize();
1281}
1282
1283size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1284 return mGrContext->maxRenderTargetSize();
1285}
1286
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001287void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001288 const ShadowSettings& settings) {
1289 ATRACE_CALL();
1290 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001291 const auto flags =
1292 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1293
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001294 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001295 getSkPoint3(settings.lightPos), settings.lightRadius,
1296 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1297 flags);
1298}
1299
John Reck67b1e2b2020-08-26 13:17:24 -07001300EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001301 EGLContext shareContext,
1302 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001303 Protection protection) {
1304 EGLint renderableType = 0;
1305 if (config == EGL_NO_CONFIG_KHR) {
1306 renderableType = EGL_OPENGL_ES3_BIT;
1307 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1308 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1309 }
1310 EGLint contextClientVersion = 0;
1311 if (renderableType & EGL_OPENGL_ES3_BIT) {
1312 contextClientVersion = 3;
1313 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1314 contextClientVersion = 2;
1315 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1316 contextClientVersion = 1;
1317 } else {
1318 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1319 }
1320
1321 std::vector<EGLint> contextAttributes;
1322 contextAttributes.reserve(7);
1323 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1324 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001325 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001326 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001327 switch (*contextPriority) {
1328 case ContextPriority::REALTIME:
1329 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1330 break;
1331 case ContextPriority::MEDIUM:
1332 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1333 break;
1334 case ContextPriority::LOW:
1335 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1336 break;
1337 case ContextPriority::HIGH:
1338 default:
1339 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1340 break;
1341 }
John Reck67b1e2b2020-08-26 13:17:24 -07001342 }
1343 if (protection == Protection::PROTECTED) {
1344 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1345 contextAttributes.push_back(EGL_TRUE);
1346 }
1347 contextAttributes.push_back(EGL_NONE);
1348
1349 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1350
1351 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1352 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1353 // EGL_NO_CONTEXT so that we can abort.
1354 if (config != EGL_NO_CONFIG_KHR) {
1355 return context;
1356 }
1357 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1358 // should try to fall back to GLES 2.
1359 contextAttributes[1] = 2;
1360 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1361 }
1362
1363 return context;
1364}
1365
Alec Mourid6f09462020-12-07 11:18:17 -08001366std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1367 const RenderEngineCreationArgs& args) {
1368 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1369 return std::nullopt;
1370 }
1371
1372 switch (args.contextPriority) {
1373 case RenderEngine::ContextPriority::REALTIME:
1374 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1375 return RenderEngine::ContextPriority::REALTIME;
1376 } else {
1377 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1378 return RenderEngine::ContextPriority::HIGH;
1379 }
1380 case RenderEngine::ContextPriority::HIGH:
1381 case RenderEngine::ContextPriority::MEDIUM:
1382 case RenderEngine::ContextPriority::LOW:
1383 return args.contextPriority;
1384 default:
1385 return std::nullopt;
1386 }
1387}
1388
John Reck67b1e2b2020-08-26 13:17:24 -07001389EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1390 EGLConfig config, int hwcFormat,
1391 Protection protection) {
1392 EGLConfig placeholderConfig = config;
1393 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1394 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1395 }
1396 std::vector<EGLint> attributes;
1397 attributes.reserve(7);
1398 attributes.push_back(EGL_WIDTH);
1399 attributes.push_back(1);
1400 attributes.push_back(EGL_HEIGHT);
1401 attributes.push_back(1);
1402 if (protection == Protection::PROTECTED) {
1403 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1404 attributes.push_back(EGL_TRUE);
1405 }
1406 attributes.push_back(EGL_NONE);
1407
1408 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1409}
1410
Alec Mourid6f09462020-12-07 11:18:17 -08001411int SkiaGLRenderEngine::getContextPriority() {
1412 int value;
1413 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1414 return value;
1415}
1416
Ady Abrahamed3290f2021-05-17 15:12:14 -07001417void SkiaGLRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001418 // This cache multiplier was selected based on review of cache sizes relative
1419 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1420 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1421 // conservative default based on that analysis.
1422 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1423 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1424
1425 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001426 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001427
1428 // if it is possible to switch contexts then we will resize the other context
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001429 const bool originalProtectedState = mInProtectedContext;
1430 useProtectedContext(!mInProtectedContext);
1431 if (mInProtectedContext != originalProtectedState) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001432 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001433 // reset back to the initial context that was active when this method was called
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001434 useProtectedContext(originalProtectedState);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001435 }
1436}
1437
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001438void SkiaGLRenderEngine::dump(std::string& result) {
1439 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1440
1441 StringAppendF(&result, "\n ------------RE-----------------\n");
1442 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1443 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1444 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1445 extensions.getVersion());
1446 StringAppendF(&result, "%s\n", extensions.getExtensions());
1447 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1448 supportsProtectedContent());
1449 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001450 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1451 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001452
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001453 std::vector<ResourcePair> cpuResourceMap = {
1454 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1455 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1456 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1457 {"skia/sk_resource_cache/tessellated", "Shadows"},
1458 {"skia", "Other"},
1459 };
1460 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1461 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1462 StringAppendF(&result, "Skia CPU Caches: ");
1463 cpuReporter.logTotals(result);
1464 cpuReporter.logOutput(result);
1465
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001466 {
1467 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001468
1469 std::vector<ResourcePair> gpuResourceMap = {
1470 {"texture_renderbuffer", "Texture/RenderBuffer"},
1471 {"texture", "Texture"},
1472 {"gr_text_blob_cache", "Text"},
1473 {"skia", "Other"},
1474 };
1475 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1476 mGrContext->dumpMemoryStatistics(&gpuReporter);
1477 StringAppendF(&result, "Skia's GPU Caches: ");
1478 gpuReporter.logTotals(result);
1479 gpuReporter.logOutput(result);
1480 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1481 gpuReporter.logOutput(result, true);
1482
Alec Mouria90a5702021-04-16 16:36:21 +00001483 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1484 mGraphicBufferExternalRefs.size());
1485 StringAppendF(&result, "Dumping buffer ids...\n");
1486 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1487 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1488 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001489 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1490 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001491 StringAppendF(&result, "Dumping buffer ids...\n");
1492 // TODO(178539829): It would be nice to know which layer these are coming from and what
1493 // the texture sizes are.
1494 for (const auto& [id, unused] : mTextureCache) {
1495 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1496 }
1497 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001498
1499 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001500 if (mProtectedGrContext) {
1501 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1502 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001503 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1504 gpuProtectedReporter.logTotals(result);
1505 gpuProtectedReporter.logOutput(result);
1506 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1507 gpuProtectedReporter.logOutput(result, true);
1508
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001509 StringAppendF(&result, "\n");
1510 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1511 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1512 StringAppendF(&result, "- inputDataspace: %s\n",
1513 dataspaceDetails(
1514 static_cast<android_dataspace>(linearEffect.inputDataspace))
1515 .c_str());
1516 StringAppendF(&result, "- outputDataspace: %s\n",
1517 dataspaceDetails(
1518 static_cast<android_dataspace>(linearEffect.outputDataspace))
1519 .c_str());
1520 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1521 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1522 }
1523 }
1524 StringAppendF(&result, "\n");
1525}
1526
John Reck67b1e2b2020-08-26 13:17:24 -07001527} // namespace skia
1528} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001529} // namespace android