blob: 99d39325d46373ec43c67ed56f3d6a88dc296da1 [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>
Alec Mouri88acab92022-03-24 23:41:01 +000042#include <ui/DataspaceUtils.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080043#include <ui/DebugUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080044#include <ui/GraphicBuffer.h>
45#include <utils/Trace.h>
Alec Mourib5777452020-09-28 11:32:42 -070046
47#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080048#include <cstdint>
49#include <memory>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070050#include <numeric>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080051
52#include "../gl/GLExtensions.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040053#include "Cache.h"
Alec Mouric0aae732021-01-12 13:32:18 -080054#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080055#include "SkBlendMode.h"
56#include "SkImageInfo.h"
57#include "filters/BlurFilter.h"
Robin Lee26dacab2021-08-09 14:31:01 +020058#include "filters/GaussianBlurFilter.h"
Robin Lee026680a2021-07-26 12:49:53 +020059#include "filters/KawaseBlurFilter.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080060#include "filters/LinearEffect.h"
61#include "log/log_main.h"
62#include "skia/debug/SkiaCapture.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040063#include "skia/debug/SkiaMemoryReporter.h"
Nader Jawad2dfc98b2021-04-08 20:35:39 -070064#include "skia/filters/StretchShaderFactory.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080065#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070066
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040067namespace {
68// Debugging settings
69static const bool kPrintLayerSettings = false;
70static const bool kFlushAfterEveryLayer = false;
71} // namespace
72
John Reck67b1e2b2020-08-26 13:17:24 -070073bool checkGlError(const char* op, int lineNumber);
74
75namespace android {
76namespace renderengine {
77namespace skia {
78
Ana Krulec1d12b3b2021-01-27 16:49:51 -080079using base::StringAppendF;
80
John Reck67b1e2b2020-08-26 13:17:24 -070081static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
82 EGLint wanted, EGLConfig* outConfig) {
83 EGLint numConfigs = -1, n = 0;
84 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
85 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
86 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
87 configs.resize(n);
88
89 if (!configs.empty()) {
90 if (attribute != EGL_NONE) {
91 for (EGLConfig config : configs) {
92 EGLint value = 0;
93 eglGetConfigAttrib(dpy, config, attribute, &value);
94 if (wanted == value) {
95 *outConfig = config;
96 return NO_ERROR;
97 }
98 }
99 } else {
100 // just pick the first one
101 *outConfig = configs[0];
102 return NO_ERROR;
103 }
104 }
105
106 return NAME_NOT_FOUND;
107}
108
109static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
110 EGLConfig* config) {
111 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
112 // it is to be used with WIFI displays
113 status_t err;
114 EGLint wantedAttribute;
115 EGLint wantedAttributeValue;
116
117 std::vector<EGLint> attribs;
118 if (renderableType) {
119 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
120 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
121
122 // Default to 8 bits per channel.
123 const EGLint tmpAttribs[] = {
124 EGL_RENDERABLE_TYPE,
125 renderableType,
126 EGL_RECORDABLE_ANDROID,
127 EGL_TRUE,
128 EGL_SURFACE_TYPE,
129 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
130 EGL_FRAMEBUFFER_TARGET_ANDROID,
131 EGL_TRUE,
132 EGL_RED_SIZE,
133 is1010102 ? 10 : 8,
134 EGL_GREEN_SIZE,
135 is1010102 ? 10 : 8,
136 EGL_BLUE_SIZE,
137 is1010102 ? 10 : 8,
138 EGL_ALPHA_SIZE,
139 is1010102 ? 2 : 8,
140 EGL_NONE,
141 };
142 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
143 std::back_inserter(attribs));
144 wantedAttribute = EGL_NONE;
145 wantedAttributeValue = EGL_NONE;
146 } else {
147 // if no renderable type specified, fallback to a simplified query
148 wantedAttribute = EGL_NATIVE_VISUAL_ID;
149 wantedAttributeValue = format;
150 }
151
152 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
153 config);
154 if (err == NO_ERROR) {
155 EGLint caveat;
156 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
157 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
158 }
159
160 return err;
161}
162
163std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
164 const RenderEngineCreationArgs& args) {
165 // initialize EGL for the default display
166 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
167 if (!eglInitialize(display, nullptr, nullptr)) {
168 LOG_ALWAYS_FATAL("failed to initialize EGL");
169 }
170
Yiwei Zhange2650962020-12-01 23:27:58 +0000171 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700172 if (!eglVersion) {
173 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000174 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700175 }
176
Yiwei Zhange2650962020-12-01 23:27:58 +0000177 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700178 if (!eglExtensions) {
179 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000180 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700181 }
182
183 auto& extensions = gl::GLExtensions::getInstance();
184 extensions.initWithEGLStrings(eglVersion, eglExtensions);
185
186 // The code assumes that ES2 or later is available if this extension is
187 // supported.
188 EGLConfig config = EGL_NO_CONFIG_KHR;
189 if (!extensions.hasNoConfigContext()) {
190 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
191 }
192
John Reck67b1e2b2020-08-26 13:17:24 -0700193 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800194 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700195 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800196 protectedContext =
197 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700198 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
199 }
200
Alec Mourid6f09462020-12-07 11:18:17 -0800201 EGLContext ctxt =
202 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700203
204 // if can't create a GL context, we can only abort.
205 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
206
207 EGLSurface placeholder = EGL_NO_SURFACE;
208 if (!extensions.hasSurfacelessContext()) {
209 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
210 Protection::UNPROTECTED);
211 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
212 }
213 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
214 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
215 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
216 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
217
218 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
219 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
220 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
221 Protection::PROTECTED);
222 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
223 "can't create protected placeholder pbuffer");
224 }
225
226 // initialize the renderer while GL is current
227 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000228 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
229 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700230
231 ALOGI("OpenGL ES informations:");
232 ALOGI("vendor : %s", extensions.getVendor());
233 ALOGI("renderer : %s", extensions.getRenderer());
234 ALOGI("version : %s", extensions.getVersion());
235 ALOGI("extensions: %s", extensions.getExtensions());
236 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
237 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
238
239 return engine;
240}
241
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700242std::future<void> SkiaGLRenderEngine::primeCache() {
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500243 Cache::primeShaderCache(this);
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700244 return {};
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500245}
246
John Reck67b1e2b2020-08-26 13:17:24 -0700247EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
248 status_t err;
249 EGLConfig config;
250
251 // First try to get an ES3 config
252 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
253 if (err != NO_ERROR) {
254 // If ES3 fails, try to get an ES2 config
255 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
256 if (err != NO_ERROR) {
257 // If ES2 still doesn't work, probably because we're on the emulator.
258 // try a simplified query
259 ALOGW("no suitable EGLConfig found, trying a simpler query");
260 err = selectEGLConfig(display, format, 0, &config);
261 if (err != NO_ERROR) {
262 // this EGL is too lame for android
263 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
264 }
265 }
266 }
267
268 if (logConfig) {
269 // print some debugging info
270 EGLint r, g, b, a;
271 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
272 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
273 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
274 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
275 ALOGI("EGL information:");
276 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
277 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
278 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
279 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
280 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
281 }
282
283 return config;
284}
285
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400286sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
287 // This "cache" does not actually cache anything. It just allows us to
288 // monitor Skia's internal cache. So this method always returns null.
289 return nullptr;
290}
291
292void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
293 const SkString& description) {
294 mShadersCachedSinceLastCall++;
295}
296
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400297int SkiaGLRenderEngine::reportShadersCompiled() {
Leon Scroggins III45be9182022-04-27 10:37:11 -0400298 return mSkSLCacheMonitor.totalShadersCompiled();
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400299}
300
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700301SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000302 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700303 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800304 : SkiaRenderEngine(args.renderEngineType),
305 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700306 mEGLContext(ctxt),
307 mPlaceholderSurface(placeholder),
308 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700309 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400310 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800311 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700312 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
313 LOG_ALWAYS_FATAL_IF(!glInterface.get());
314
315 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400316 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700317 options.fDisableDistanceFieldPaths = true;
Nathaniel Nifongf8d35e92021-06-08 15:02:25 -0400318 options.fReducedShaderVariations = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400319 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000320 mGrContext = GrDirectContext::MakeGL(glInterface, options);
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400321 if (supportsProtectedContent()) {
322 useProtectedContext(true);
Lucas Dupind508e472020-11-04 04:32:06 +0000323 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
324 useProtectedContext(false);
325 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700326
327 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500328 ALOGD("Background Blurs Enabled");
Robin Lee026680a2021-07-26 12:49:53 +0200329 mBlurFilter = new KawaseBlurFilter();
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700330 }
Alec Mouric0aae732021-01-12 13:32:18 -0800331 mCapture = std::make_unique<SkiaCapture>();
332}
333
334SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100335 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800336 if (mBlurFilter) {
337 delete mBlurFilter;
338 }
339
340 mCapture = nullptr;
341
342 mGrContext->flushAndSubmit(true);
343 mGrContext->abandonContext();
344
345 if (mProtectedGrContext) {
346 mProtectedGrContext->flushAndSubmit(true);
347 mProtectedGrContext->abandonContext();
348 }
349
350 if (mPlaceholderSurface != EGL_NO_SURFACE) {
351 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
352 }
353 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
354 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
355 }
356 if (mEGLContext != EGL_NO_CONTEXT) {
357 eglDestroyContext(mEGLDisplay, mEGLContext);
358 }
359 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
360 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
361 }
362 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
363 eglTerminate(mEGLDisplay);
364 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700365}
366
Lucas Dupind508e472020-11-04 04:32:06 +0000367bool SkiaGLRenderEngine::supportsProtectedContent() const {
368 return mProtectedEGLContext != EGL_NO_CONTEXT;
369}
370
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400371GrDirectContext* SkiaGLRenderEngine::getActiveGrContext() const {
372 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
373}
374
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400375void SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
376 if (useProtectedContext == mInProtectedContext ||
377 (useProtectedContext && !supportsProtectedContent())) {
378 return;
Lucas Dupind508e472020-11-04 04:32:06 +0000379 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400380
381 // release any scratch resources before switching into a new mode
382 if (getActiveGrContext()) {
383 getActiveGrContext()->purgeUnlockedResources(true);
384 }
385
Lucas Dupind508e472020-11-04 04:32:06 +0000386 const EGLSurface surface =
387 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
388 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
Alec Mouric0aae732021-01-12 13:32:18 -0800389
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400390 if (eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE) {
Lucas Dupind508e472020-11-04 04:32:06 +0000391 mInProtectedContext = useProtectedContext;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400392 // given that we are sharing the same thread between two GrContexts we need to
393 // make sure that the thread state is reset when switching between the two.
394 if (getActiveGrContext()) {
395 getActiveGrContext()->resetContext();
396 }
Lucas Dupind508e472020-11-04 04:32:06 +0000397 }
Lucas Dupind508e472020-11-04 04:32:06 +0000398}
399
John Reck67b1e2b2020-08-26 13:17:24 -0700400base::unique_fd SkiaGLRenderEngine::flush() {
401 ATRACE_CALL();
402 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
403 return base::unique_fd();
404 }
405
406 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
407 if (sync == EGL_NO_SYNC_KHR) {
408 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
409 return base::unique_fd();
410 }
411
412 // native fence fd will not be populated until flush() is done.
413 glFlush();
414
415 // get the fence fd
416 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
417 eglDestroySyncKHR(mEGLDisplay, sync);
418 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
419 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
420 }
421
422 return fenceFd;
423}
424
Alec Mouri4ee7b492021-08-11 10:36:55 -0700425void SkiaGLRenderEngine::waitFence(base::borrowed_fd fenceFd) {
426 if (fenceFd.get() >= 0 && !waitGpuFence(fenceFd)) {
427 ATRACE_NAME("SkiaGLRenderEngine::waitFence");
428 sync_wait(fenceFd.get(), -1);
429 }
430}
431
432bool SkiaGLRenderEngine::waitGpuFence(base::borrowed_fd fenceFd) {
John Reck67b1e2b2020-08-26 13:17:24 -0700433 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
434 !gl::GLExtensions::getInstance().hasWaitSync()) {
435 return false;
436 }
437
Alec Mouri4ee7b492021-08-11 10:36:55 -0700438 // Duplicate the fence for passing to eglCreateSyncKHR.
439 base::unique_fd fenceDup(dup(fenceFd.get()));
440 if (fenceDup.get() < 0) {
441 ALOGE("failed to create duplicate fence fd: %d", fenceDup.get());
442 return false;
443 }
444
John Reck67b1e2b2020-08-26 13:17:24 -0700445 // release the fd and transfer the ownership to EGLSync
Alec Mouri4ee7b492021-08-11 10:36:55 -0700446 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceDup.release(), EGL_NONE};
John Reck67b1e2b2020-08-26 13:17:24 -0700447 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
448 if (sync == EGL_NO_SYNC_KHR) {
449 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
450 return false;
451 }
452
453 // XXX: The spec draft is inconsistent as to whether this should return an
454 // EGLint or void. Ignore the return value for now, as it's not strictly
455 // needed.
456 eglWaitSyncKHR(mEGLDisplay, sync, 0);
457 EGLint error = eglGetError();
458 eglDestroySyncKHR(mEGLDisplay, sync);
459 if (error != EGL_SUCCESS) {
460 ALOGE("failed to wait for EGL native fence sync: %#x", error);
461 return false;
462 }
463
464 return true;
465}
466
Alec Mouri678245d2020-09-30 16:58:23 -0700467static float toDegrees(uint32_t transform) {
468 switch (transform) {
469 case ui::Transform::ROT_90:
470 return 90.0;
471 case ui::Transform::ROT_180:
472 return 180.0;
473 case ui::Transform::ROT_270:
474 return 270.0;
475 default:
476 return 0.0;
477 }
478}
479
Alec Mourib34f0b72020-10-02 13:18:34 -0700480static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
481 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
482 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
483 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
484 matrix[3][3], 0);
485}
486
Alec Mouri029d1952020-10-12 10:37:08 -0700487static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
488 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
489 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
490
491 // Treat unsupported dataspaces as srgb
492 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
493 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
494 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
495 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
496 }
497
498 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
499 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
500 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
501 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
502 }
503
504 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
505 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
506 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
507 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
508
509 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
510 sourceTransfer != destTransfer;
511}
512
Alec Mouria90a5702021-04-16 16:36:21 +0000513void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
514 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800515 // Only run this if RE is running on its own thread. This way the access to GL
516 // operations is guaranteed to be happening on the same thread.
517 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
518 return;
519 }
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400520 // We currently don't attempt to map a buffer if the buffer contains protected content
Derek Sollenberger45007182021-06-10 14:47:21 -0400521 // because GPU resources for protected buffers is much more limited.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400522 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Derek Sollenberger45007182021-06-10 14:47:21 -0400523 if (isProtectedBuffer) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400524 return;
525 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800526 ATRACE_CALL();
527
Derek Sollenberger45007182021-06-10 14:47:21 -0400528 // If we were to support caching protected buffers then we will need to switch the
529 // currently bound context if we are not already using the protected context (and subsequently
530 // switch back after the buffer is cached). However, for non-protected content we can bind
531 // the texture in either GL context because they are initialized with the same share_context
532 // which allows the texture state to be shared between them.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400533 auto grContext = getActiveGrContext();
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400534 auto& cache = mTextureCache;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400535
536 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000537 mGraphicBufferExternalRefs[buffer->getId()]++;
538
539 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800540 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400541 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400542 buffer->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400543 isRenderable, mTextureCleanupMgr);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400544 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800545 }
546}
547
Alec Mouria90a5702021-04-16 16:36:21 +0000548void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800549 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700550 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000551 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
552 iter != mGraphicBufferExternalRefs.end()) {
553 if (iter->second == 0) {
554 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
555 "> from RenderEngine texture, but the "
556 "ref count was already zero!",
557 buffer->getId());
558 mGraphicBufferExternalRefs.erase(buffer->getId());
559 return;
560 }
561
562 iter->second--;
563
Alec Mouric2ffeb42021-06-17 17:42:27 -0700564 // Swap contexts if needed prior to deleting this buffer
565 // See Issue 1 of
566 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
567 // when a protected context and an unprotected context are part of the same share group,
568 // protected surfaces may not be accessed by an unprotected context, implying that protected
569 // surfaces may only be freed when a protected context is active.
570 const bool inProtected = mInProtectedContext;
571 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
572
Alec Mouria90a5702021-04-16 16:36:21 +0000573 if (iter->second == 0) {
574 mTextureCache.erase(buffer->getId());
Alec Mouria90a5702021-04-16 16:36:21 +0000575 mGraphicBufferExternalRefs.erase(buffer->getId());
576 }
Alec Mouric2ffeb42021-06-17 17:42:27 -0700577
578 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
579 // are up-to-date.
580 if (inProtected != mInProtectedContext) {
581 useProtectedContext(inProtected);
582 }
Alec Mouria90a5702021-04-16 16:36:21 +0000583 }
John Reck67b1e2b2020-08-26 13:17:24 -0700584}
585
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400586bool SkiaGLRenderEngine::canSkipPostRenderCleanup() const {
587 std::lock_guard<std::mutex> lock(mRenderingMutex);
588 return mTextureCleanupMgr.isEmpty();
589}
590
591void SkiaGLRenderEngine::cleanupPostRender() {
592 ATRACE_CALL();
593 std::lock_guard<std::mutex> lock(mRenderingMutex);
594 mTextureCleanupMgr.cleanup();
595}
596
597// Helper class intended to be used on the stack to ensure that texture cleanup
598// is deferred until after this class goes out of scope.
599class DeferTextureCleanup final {
600public:
601 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
602 mMgr.setDeferredStatus(true);
603 }
604 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
605
606private:
607 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
608 AutoBackendTexture::CleanupManager& mMgr;
609};
610
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700611sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
612 const RuntimeEffectShaderParameters& parameters) {
Nader Jawad63644d32021-05-07 10:44:21 -0700613 // The given surface will be stretched by HWUI via matrix transformation
614 // which gets similar results for most surfaces
615 // Determine later on if we need to leverage the stertch shader within
616 // surface flinger
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700617 const auto& stretchEffect = parameters.layer.stretchEffect;
618 auto shader = parameters.shader;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700619 if (stretchEffect.hasEffect()) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700620 const auto targetBuffer = parameters.layer.source.buffer.buffer;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700621 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700622 if (graphicBuffer && parameters.shader) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700623 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
624 }
John Reckcdb4ed72021-02-04 13:39:33 -0500625 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700626
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700627 if (parameters.requiresLinearEffect) {
628 const ui::Dataspace inputDataspace = mUseColorManagement ? parameters.layer.sourceDataspace
629 : ui::Dataspace::V0_SRGB_LINEAR;
630 const ui::Dataspace outputDataspace = mUseColorManagement
631 ? parameters.display.outputDataspace
632 : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500633
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700634 auto effect =
635 shaders::LinearEffect{.inputDataspace = inputDataspace,
636 .outputDataspace = outputDataspace,
637 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha};
Ana Krulec47814212021-01-06 19:00:10 -0800638
639 auto effectIter = mRuntimeEffects.find(effect);
640 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
641 if (effectIter == mRuntimeEffects.end()) {
642 runtimeEffect = buildRuntimeEffect(effect);
643 mRuntimeEffects.insert({effect, runtimeEffect});
644 } else {
645 runtimeEffect = effectIter->second;
646 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700647 mat4 colorTransform = parameters.layer.colorTransform;
648
649 colorTransform *=
650 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
651 parameters.layerDimmingRatio, 1.f));
Alec Mouri1a3c5452022-03-04 22:44:51 +0000652 const auto targetBuffer = parameters.layer.source.buffer.buffer;
653 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
654 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700655 return createLinearEffectShader(parameters.shader, effect, runtimeEffect, colorTransform,
656 parameters.display.maxLuminance,
Alec Mourib21d94e2022-01-13 17:44:10 -0800657 parameters.display.currentLuminanceNits,
Alec Mouri1a3c5452022-03-04 22:44:51 +0000658 parameters.layer.source.buffer.maxLuminanceNits,
Alec Mourifcedb9c2022-04-11 20:02:17 +0000659 hardwareBuffer, parameters.display.renderIntent);
Ana Krulec47814212021-01-06 19:00:10 -0800660 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700661 return parameters.shader;
Ana Krulec47814212021-01-06 19:00:10 -0800662}
663
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500664void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500665 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500666 // Record display settings when capture is running.
667 std::stringstream displaySettings;
668 PrintTo(display, &displaySettings);
669 // Store the DisplaySettings in additional information.
670 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
671 SkData::MakeWithCString(displaySettings.str().c_str()));
672 }
673
674 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
675 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
676 // displays might have different scaling when compared to the physical screen.
677
678 canvas->clipRect(getSkRect(display.physicalDisplay));
679 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
680
681 const auto clipWidth = display.clip.width();
682 const auto clipHeight = display.clip.height();
683 auto rotatedClipWidth = clipWidth;
684 auto rotatedClipHeight = clipHeight;
685 // Scale is contingent on the rotation result.
686 if (display.orientation & ui::Transform::ROT_90) {
687 std::swap(rotatedClipWidth, rotatedClipHeight);
688 }
689 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
690 static_cast<SkScalar>(rotatedClipWidth);
691 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
692 static_cast<SkScalar>(rotatedClipHeight);
693 canvas->scale(scaleX, scaleY);
694
695 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
696 // back so that the top left corner of the clip is at (0, 0).
697 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
698 canvas->rotate(toDegrees(display.orientation));
699 canvas->translate(-clipWidth / 2, -clipHeight / 2);
700 canvas->translate(-display.clip.left, -display.clip.top);
701}
702
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500703class AutoSaveRestore {
704public:
705 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
706 ~AutoSaveRestore() { restore(); }
707 void replace(SkCanvas* canvas) {
708 mCanvas = canvas;
709 mSaveCount = canvas->save();
710 }
711 void restore() {
712 if (mCanvas) {
713 mCanvas->restoreToCount(mSaveCount);
714 mCanvas = nullptr;
715 }
716 }
717
718private:
719 SkCanvas* mCanvas;
720 int mSaveCount;
721};
722
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400723static SkRRect getBlurRRect(const BlurRegion& region) {
724 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
725 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
726 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
727 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
728 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
729 SkRRect roundedRect;
730 roundedRect.setRectRadii(rect, radii);
731 return roundedRect;
732}
733
Alec Mouri85065692022-03-18 00:58:26 +0000734// Arbitrary default margin which should be close enough to zero.
735constexpr float kDefaultMargin = 0.0001f;
736static bool equalsWithinMargin(float expected, float value, float margin = kDefaultMargin) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700737 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
738 return std::abs(expected - value) < margin;
739}
740
Sally Qi4cabdd02021-08-05 16:45:57 -0700741void SkiaGLRenderEngine::drawLayersInternal(
742 const std::shared_ptr<std::promise<RenderEngineResult>>&& resultPromise,
Sally Qi59a9f502021-10-12 18:53:23 +0000743 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
Sally Qi4cabdd02021-08-05 16:45:57 -0700744 const std::shared_ptr<ExternalTexture>& buffer, const bool /*useFramebufferCache*/,
745 base::unique_fd&& bufferFence) {
John Reck67b1e2b2020-08-26 13:17:24 -0700746 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800747
John Reck67b1e2b2020-08-26 13:17:24 -0700748 std::lock_guard<std::mutex> lock(mRenderingMutex);
749 if (layers.empty()) {
750 ALOGV("Drawing empty layer stack");
Sally Qi4cabdd02021-08-05 16:45:57 -0700751 resultPromise->set_value({NO_ERROR, base::unique_fd()});
752 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700753 }
754
John Reck67b1e2b2020-08-26 13:17:24 -0700755 if (buffer == nullptr) {
756 ALOGE("No output buffer provided. Aborting GPU composition.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700757 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
758 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700759 }
760
Alec Mouria90a5702021-04-16 16:36:21 +0000761 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800762
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400763 auto grContext = getActiveGrContext();
Derek Sollenberger45007182021-06-10 14:47:21 -0400764 auto& cache = mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700765
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400766 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
767 DeferTextureCleanup dtc(mTextureCleanupMgr);
768
Alec Mouria90a5702021-04-16 16:36:21 +0000769 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
770 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
771 surfaceTextureRef = it->second;
772 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400773 surfaceTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400774 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
775 buffer->getBuffer()
776 ->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400777 true, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -0700778 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800779
Alec Mouri4ee7b492021-08-11 10:36:55 -0700780 // wait on the buffer to be ready to use prior to using it
781 waitFence(bufferFence);
782
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500783 const ui::Dataspace dstDataspace =
Alec Mourid2bcbae2021-06-28 17:02:17 -0700784 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400785 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700786
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500787 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
788 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800789 ALOGE("Cannot acquire canvas from Skia.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700790 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
791 return;
Ana Krulec6eab17a2020-12-09 15:52:36 -0800792 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500793
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400794 // setup color filter if necessary
795 sk_sp<SkColorFilter> displayColorTransform;
Leon Scroggins III745dcaa2022-01-26 11:55:58 -0500796 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400797 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
798 }
799 const bool ctModifiesAlpha =
800 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
801
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700802 // Find the max layer white point to determine the max luminance of the scene...
803 const float maxLayerWhitePoint = std::transform_reduce(
804 layers.cbegin(), layers.cend(), 0.f,
805 [](float left, float right) { return std::max(left, right); },
806 [&](const auto& l) { return l.whitePointNits; });
807
808 // ...and compute the dimming ratio if dimming is requested
809 const float displayDimmingRatio = display.targetLuminanceNits > 0.f &&
810 maxLayerWhitePoint > 0.f && display.targetLuminanceNits > maxLayerWhitePoint
811 ? maxLayerWhitePoint / display.targetLuminanceNits
812 : 1.f;
813
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500814 // Find if any layers have requested blur, we'll use that info to decide when to render to an
815 // offscreen buffer and when to render to the native buffer.
816 sk_sp<SkSurface> activeSurface(dstSurface);
817 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500818 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500819 const LayerSettings* blurCompositionLayer = nullptr;
820 if (mBlurFilter) {
821 bool requiresCompositionLayer = false;
822 for (const auto& layer : layers) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400823 // if the layer doesn't have blur or it is not visible then continue
824 if (!layerHasBlur(layer, ctModifiesAlpha)) {
825 continue;
826 }
Sally Qi59a9f502021-10-12 18:53:23 +0000827 if (layer.backgroundBlurRadius > 0 &&
Robin Lee26dacab2021-08-09 14:31:01 +0200828 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500829 requiresCompositionLayer = true;
830 }
Sally Qi59a9f502021-10-12 18:53:23 +0000831 for (auto region : layer.blurRegions) {
Robin Lee26dacab2021-08-09 14:31:01 +0200832 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500833 requiresCompositionLayer = true;
834 }
835 }
836 if (requiresCompositionLayer) {
837 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500838 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Sally Qi59a9f502021-10-12 18:53:23 +0000839 blurCompositionLayer = &layer;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500840 break;
841 }
842 }
843 }
844
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500845 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700846 // Clear the entire canvas with a transparent black to prevent ghost images.
847 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500848 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800849
John Reck67b1e2b2020-08-26 13:17:24 -0700850 for (const auto& layer : layers) {
Sally Qi59a9f502021-10-12 18:53:23 +0000851 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
Galia Peychevaf7889b32020-11-25 22:22:40 +0100852
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400853 if (kPrintLayerSettings) {
854 std::stringstream ls;
Sally Qi59a9f502021-10-12 18:53:23 +0000855 PrintTo(layer, &ls);
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400856 auto debugs = ls.str();
857 int pos = 0;
858 while (pos < debugs.size()) {
859 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
860 pos += 1000;
861 }
862 }
863
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500864 sk_sp<SkImage> blurInput;
Sally Qi59a9f502021-10-12 18:53:23 +0000865 if (blurCompositionLayer == &layer) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500866 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
867 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
868
869 // save a snapshot of the activeSurface to use as input to the blur shaders
870 blurInput = activeSurface->makeImageSnapshot();
871
Leon Scroggins III55bf4742022-03-17 14:11:17 -0400872 // blit the offscreen framebuffer into the destination AHB, but only
873 // if there are blur regions. backgroundBlurRadius blurs the entire
874 // image below, so it can skip this step.
875 if (layer.blurRegions.size()) {
876 SkPaint paint;
877 paint.setBlendMode(SkBlendMode::kSrc);
878 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
879 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
880 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
881 String8::format("SurfaceID|%" PRId64, id).c_str(),
882 nullptr);
883 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
884 } else {
885 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
886 }
Derek Sollenberger76664d62021-02-04 11:13:09 -0500887 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500888
889 // assign dstCanvas to canvas and ensure that the canvas state is up to date
890 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500891 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500892 initCanvas(canvas, display);
893
894 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
895 dstSurface->getCanvas()->getSaveCount());
896 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
897 dstSurface->getCanvas()->getTotalMatrix());
898
899 // assign dstSurface to activeSurface
900 activeSurface = dstSurface;
901 }
902
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500903 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500904 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800905 // Record the name of the layer if the capture is running.
906 std::stringstream layerSettings;
Sally Qi59a9f502021-10-12 18:53:23 +0000907 PrintTo(layer, &layerSettings);
Ana Krulec6eab17a2020-12-09 15:52:36 -0800908 // Store the LayerSettings in additional information.
Sally Qi59a9f502021-10-12 18:53:23 +0000909 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
Ana Krulec6eab17a2020-12-09 15:52:36 -0800910 SkData::MakeWithCString(layerSettings.str().c_str()));
911 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100912 // Layers have a local transform that should be applied to them
Sally Qi59a9f502021-10-12 18:53:23 +0000913 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100914
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400915 const auto [bounds, roundRectClip] =
Sally Qi59a9f502021-10-12 18:53:23 +0000916 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
917 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400918 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500919 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
920
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500921 // if multiple layers have blur, then we need to take a snapshot now because
922 // only the lowest layer will have blurImage populated earlier
923 if (!blurInput) {
924 blurInput = activeSurface->makeImageSnapshot();
925 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500926 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400927 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
928
929 // if the clip needs to be applied then apply it now and make sure
930 // it is restored before we attempt to draw any shadows.
931 SkAutoCanvasRestore acr(canvas, true);
932 if (!roundRectClip.isEmpty()) {
933 canvas->clipRRect(roundRectClip, true);
934 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500935
Galia Peychevae425ac82021-03-15 17:12:03 +0100936 // TODO(b/182216890): Filter out empty layers earlier
937 if (blurRect.width() > 0 && blurRect.height() > 0) {
Sally Qi59a9f502021-10-12 18:53:23 +0000938 if (layer.backgroundBlurRadius > 0) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100939 ATRACE_NAME("BackgroundBlur");
Sally Qi59a9f502021-10-12 18:53:23 +0000940 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
941 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100942
Sally Qi59a9f502021-10-12 18:53:23 +0000943 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500944
Sally Qi59a9f502021-10-12 18:53:23 +0000945 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400946 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700947 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400948
Sally Qi59a9f502021-10-12 18:53:23 +0000949 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
950 for (auto region : layer.blurRegions) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100951 if (cachedBlurs[region.blurRadius] == nullptr) {
952 ATRACE_NAME("BlurRegion");
953 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400954 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100955 blurRect);
956 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500957
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400958 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
959 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100960 cachedBlurs[region.blurRadius], blurInput);
961 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700962 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700963 }
964
Sally Qi59a9f502021-10-12 18:53:23 +0000965 if (layer.shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400966 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
Sally Qi59a9f502021-10-12 18:53:23 +0000967 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
Leon Scroggins III63e86952021-05-12 10:45:08 -0400968
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400969 SkRRect shadowBounds, shadowClip;
Sally Qi59a9f502021-10-12 18:53:23 +0000970 if (layer.geometry.boundaries == layer.shadow.boundaries) {
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400971 shadowBounds = bounds;
972 shadowClip = roundRectClip;
973 } else {
974 std::tie(shadowBounds, shadowClip) =
Sally Qi59a9f502021-10-12 18:53:23 +0000975 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
976 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400977 }
978
Leon Scroggins III63e86952021-05-12 10:45:08 -0400979 // Technically, if bounds is a rect and roundRectClip is not empty,
980 // it means that the bounds and roundedCornersCrop were different
981 // enough that we should intersect them to find the proper shadow.
982 // In practice, this often happens when the two rectangles appear to
983 // not match due to rounding errors. Draw the rounded version, which
984 // looks more like the intent.
985 const auto& rrect =
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400986 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
Sally Qi59a9f502021-10-12 18:53:23 +0000987 drawShadow(canvas, rrect, layer.shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500988 }
989
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700990 const float layerDimmingRatio = layer.whitePointNits <= 0.f
991 ? displayDimmingRatio
992 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
993
Alec Mouri85065692022-03-18 00:58:26 +0000994 const bool dimInLinearSpace = display.dimmingStage !=
995 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
996
Sally Qi59a9f502021-10-12 18:53:23 +0000997 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500998 (mUseColorManagement &&
Sally Qi59a9f502021-10-12 18:53:23 +0000999 needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
Alec Mouri85065692022-03-18 00:58:26 +00001000 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio));
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001001
1002 // quick abort from drawing the remaining portion of the layer
Sally Qi59a9f502021-10-12 18:53:23 +00001003 if (layer.skipContentDraw ||
1004 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001005 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001006 continue;
1007 }
1008
1009 // If we need to map to linear space or color management is disabled, then mark the source
1010 // image with the same colorspace as the destination surface so that Skia's color
1011 // management is a no-op.
1012 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
1013 ? dstDataspace
Sally Qi59a9f502021-10-12 18:53:23 +00001014 : layer.sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -08001015
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001016 SkPaint paint;
Sally Qi59a9f502021-10-12 18:53:23 +00001017 if (layer.source.buffer.buffer) {
John Reck67b1e2b2020-08-26 13:17:24 -07001018 ATRACE_NAME("DrawImage");
Sally Qi59a9f502021-10-12 18:53:23 +00001019 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
1020 const auto& item = layer.source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001021 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +00001022
1023 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
1024 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001025 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -07001026 } else {
Alec Mouria90a5702021-04-16 16:36:21 +00001027 // If we didn't find the image in the cache, then create a local ref but don't cache
1028 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
1029 // we didn't find anything in the cache then we intentionally did not cache this
1030 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001031 imageTextureRef = std::make_shared<
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001032 AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001033 item.buffer->getBuffer()->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -04001034 false, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -07001035 }
Alec Mouri1a4d0642020-11-13 17:42:01 -08001036
Alec Mouri4ee7b492021-08-11 10:36:55 -07001037 // if the layer's buffer has a fence, then we must must respect the fence prior to using
1038 // the buffer.
Sally Qi59a9f502021-10-12 18:53:23 +00001039 if (layer.source.buffer.fence != nullptr) {
1040 waitFence(layer.source.buffer.fence->get());
Alec Mouri4ee7b492021-08-11 10:36:55 -07001041 }
1042
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001043 // isOpaque means we need to ignore the alpha in the image,
1044 // replacing it with the alpha specified by the LayerSettings. See
1045 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
1046 // The proper way to do this is to use an SkColorType that ignores
1047 // alpha, like kRGB_888x_SkColorType, and that is used if the
1048 // incoming image is kRGBA_8888_SkColorType. However, the incoming
1049 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
1050 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
1051 // kRGB_101010x_SkColorType, but it is not yet supported as a source
1052 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
1053 // meantime, we'll use a workaround that works unless we need to do
1054 // any color conversion. The workaround requires that we pretend the
1055 // image is already premultiplied, so that we do not premultiply it
1056 // before applying SkBlendMode::kPlus.
1057 const bool useIsOpaqueWorkaround = item.isOpaque &&
1058 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
1059 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
1060 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
1061 : item.isOpaque ? kOpaque_SkAlphaType
1062 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
1063 : kUnpremul_SkAlphaType;
1064 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -07001065
1066 auto texMatrix = getSkM44(item.textureTransform).asM33();
1067 // textureTansform was intended to be passed directly into a shader, so when
1068 // building the total matrix with the textureTransform we need to first
1069 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001070 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001071 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -07001072
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001073 SkMatrix matrix;
1074 if (!texMatrix.invert(&matrix)) {
1075 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -07001076 }
Ana Krulecf9a15d92020-12-11 08:35:00 -08001077 // The shader does not respect the translation, so we add it to the texture
1078 // transform for the SkImage. This will make sure that the correct layer contents
1079 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001080 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -07001081
Ana Krulecb7b28b22020-11-23 14:48:58 -08001082 sk_sp<SkShader> shader;
1083
Sally Qi59a9f502021-10-12 18:53:23 +00001084 if (layer.source.buffer.useTextureFiltering) {
Ana Krulecb7b28b22020-11-23 14:48:58 -08001085 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1086 SkSamplingOptions(
1087 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1088 &matrix);
1089 } else {
Mike Reed711e1f02020-12-11 13:06:19 -05001090 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -08001091 }
Alec Mouri029d1952020-10-12 10:37:08 -07001092
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001093 if (useIsOpaqueWorkaround) {
Alec Mouric0aae732021-01-12 13:32:18 -08001094 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1095 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001096 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001097 }
1098
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001099 paint.setShader(createRuntimeEffectShader(
1100 RuntimeEffectShaderParameters{.shader = shader,
1101 .layer = layer,
1102 .display = display,
1103 .undoPremultipliedAlpha = !item.isOpaque &&
1104 item.usePremultipliedAlpha,
1105 .requiresLinearEffect = requiresLinearEffect,
Alec Mouri85065692022-03-18 00:58:26 +00001106 .layerDimmingRatio = dimInLinearSpace
1107 ? layerDimmingRatio
1108 : 1.f}));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001109
Alec Mouri88acab92022-03-24 23:41:01 +00001110 // Turn on dithering when dimming beyond this (arbitrary) threshold...
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001111 static constexpr float kDimmingThreshold = 0.2f;
Alec Mouri88acab92022-03-24 23:41:01 +00001112 // ...or we're rendering an HDR layer down to an 8-bit target
1113 // Most HDR standards require at least 10-bits of color depth for source content, so we
1114 // can just extract the transfer function rather than dig into precise gralloc layout.
1115 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
1116 const bool requiresDownsample = isHdrDataspace(layer.sourceDataspace) &&
1117 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
1118 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001119 paint.setDither(true);
1120 }
Sally Qi59a9f502021-10-12 18:53:23 +00001121 paint.setAlphaf(layer.alpha);
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001122
1123 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1124 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001125
1126 // SysUI creates the alpha layer as a coverage layer, which is
1127 // appropriate for the DPU. Use a color matrix to convert it to
1128 // a mask.
1129 // TODO (b/219525258): Handle input as a mask.
1130 //
1131 // The color matrix will convert A8 pixels with no alpha to
1132 // black, as described by this vector. If the display handles
1133 // the color transform, we need to invert it to find the color
1134 // that will result in black after the DPU applies the transform.
1135 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1136 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1137 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1138 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1139 black = colorSpaceMatrix * black;
1140 } else {
1141 // We'll just have to use 0,0,0 as black, which should
1142 // be close to correct.
1143 ALOGI("Could not invert colorTransform!");
1144 }
1145 }
1146 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1147 0, 0, 0, 0, black[1],
1148 0, 0, 0, 0, black[2],
1149 0, 0, 0, -1, 1);
1150 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1151 // On the other hand, if the device doesn't handle it, we
1152 // have to apply it ourselves.
1153 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1154 }
1155 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001156 }
John Reck67b1e2b2020-08-26 13:17:24 -07001157 } else {
1158 ATRACE_NAME("DrawColor");
Sally Qi59a9f502021-10-12 18:53:23 +00001159 const auto color = layer.source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001160 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1161 .fG = color.g,
1162 .fB = color.b,
Sally Qi59a9f502021-10-12 18:53:23 +00001163 .fA = layer.alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001164 toSkColorSpace(layerDataspace));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001165 paint.setShader(createRuntimeEffectShader(
1166 RuntimeEffectShaderParameters{.shader = shader,
1167 .layer = layer,
1168 .display = display,
1169 .undoPremultipliedAlpha = false,
1170 .requiresLinearEffect = requiresLinearEffect,
1171 .layerDimmingRatio = layerDimmingRatio}));
John Reck67b1e2b2020-08-26 13:17:24 -07001172 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001173
Sally Qi59a9f502021-10-12 18:53:23 +00001174 if (layer.disableBlending) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001175 paint.setBlendMode(SkBlendMode::kSrc);
1176 }
1177
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001178 // An A8 buffer will already have the proper color filter attached to
1179 // its paint, including the displayColorTransform as needed.
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001180 if (!paint.getColorFilter()) {
Alec Mouri85065692022-03-18 00:58:26 +00001181 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1182 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1183 // can assume a gamma 2.2 transfer function.
1184 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1185 const auto gammaCorrectedDimmingRatio =
1186 std::pow(layerDimmingRatio, kInverseGamma22);
1187 const auto dimmingMatrix =
1188 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1189 gammaCorrectedDimmingRatio, 1.f));
1190 paint.setColorFilter(SkColorFilters::Matrix(
1191 toSkColorMatrix(display.colorTransform * dimmingMatrix)));
1192 } else {
1193 paint.setColorFilter(displayColorTransform);
1194 }
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001195 }
Alec Mourib34f0b72020-10-02 13:18:34 -07001196
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001197 if (!roundRectClip.isEmpty()) {
1198 canvas->clipRRect(roundRectClip, true);
1199 }
1200
1201 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001202 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001203 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001204 } else {
Nader Jawad63644d32021-05-07 10:44:21 -07001205 canvas->drawRect(bounds.rect(), paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -07001206 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001207 if (kFlushAfterEveryLayer) {
1208 ATRACE_NAME("flush surface");
1209 activeSurface->flush();
1210 }
John Reck67b1e2b2020-08-26 13:17:24 -07001211 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001212 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001213 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001214 {
1215 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001216 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1217 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001218 }
1219
Sally Qi4cabdd02021-08-05 16:45:57 -07001220 base::unique_fd drawFence = flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001221
1222 // If flush failed or we don't support native fences, we need to force the
1223 // gl command stream to be executed.
Sally Qi4cabdd02021-08-05 16:45:57 -07001224 bool requireSync = drawFence.get() < 0;
John Reck67b1e2b2020-08-26 13:17:24 -07001225 if (requireSync) {
1226 ATRACE_BEGIN("Submit(sync=true)");
1227 } else {
1228 ATRACE_BEGIN("Submit(sync=false)");
1229 }
Lucas Dupind508e472020-11-04 04:32:06 +00001230 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001231 ATRACE_END();
1232 if (!success) {
1233 ALOGE("Failed to flush RenderEngine commands");
1234 // Chances are, something illegal happened (either the caller passed
1235 // us bad parameters, or we messed up our shader generation).
Sally Qi4cabdd02021-08-05 16:45:57 -07001236 resultPromise->set_value({INVALID_OPERATION, std::move(drawFence)});
1237 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001238 }
1239
1240 // checkErrors();
Sally Qi4cabdd02021-08-05 16:45:57 -07001241 resultPromise->set_value({NO_ERROR, std::move(drawFence)});
1242 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001243}
1244
Lucas Dupin3f11e922020-09-22 17:31:04 -07001245inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1246 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1247}
1248
1249inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1250 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1251}
1252
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001253/**
1254 * Verifies that common, simple bounds + clip combinations can be converted into
1255 * a single RRect draw call returning true if possible. If true the radii parameter
1256 * will be filled with the correct radii values that combined with bounds param will
1257 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
1258 */
1259static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
1260 const SkRect& insetCrop, float cornerRadius,
1261 SkVector radii[4]) {
1262 const bool leftEqual = bounds.fLeft == crop.fLeft;
1263 const bool topEqual = bounds.fTop == crop.fTop;
1264 const bool rightEqual = bounds.fRight == crop.fRight;
1265 const bool bottomEqual = bounds.fBottom == crop.fBottom;
1266
1267 // In the event that the corners of the bounds only partially align with the crop we
1268 // need to ensure that the resulting shape can still be represented as a round rect.
1269 // In particular the round rect implementation will scale the value of all corner radii
1270 // if the sum of the radius along any edge is greater than the length of that edge.
1271 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
1272 const bool requiredWidth = bounds.width() > (cornerRadius * 2);
1273 const bool requiredHeight = bounds.height() > (cornerRadius * 2);
1274 if (!requiredWidth || !requiredHeight) {
1275 return false;
1276 }
1277
1278 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
1279 // contained within the cropped shape and does not need rounded.
1280 // compute the UpperLeft corner radius
1281 if (leftEqual && topEqual) {
1282 radii[0].set(cornerRadius, cornerRadius);
1283 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
1284 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
1285 radii[0].set(0, 0);
1286 } else {
1287 return false;
1288 }
1289 // compute the UpperRight corner radius
1290 if (rightEqual && topEqual) {
1291 radii[1].set(cornerRadius, cornerRadius);
1292 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
1293 (topEqual && bounds.fRight <= insetCrop.fRight)) {
1294 radii[1].set(0, 0);
1295 } else {
1296 return false;
1297 }
1298 // compute the BottomRight corner radius
1299 if (rightEqual && bottomEqual) {
1300 radii[2].set(cornerRadius, cornerRadius);
1301 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
1302 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
1303 radii[2].set(0, 0);
1304 } else {
1305 return false;
1306 }
1307 // compute the BottomLeft corner radius
1308 if (leftEqual && bottomEqual) {
1309 radii[3].set(cornerRadius, cornerRadius);
1310 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
1311 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
1312 radii[3].set(0, 0);
1313 } else {
1314 return false;
1315 }
1316
1317 return true;
1318}
1319
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001320inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(const FloatRect& boundsRect,
1321 const FloatRect& cropRect,
1322 const float cornerRadius) {
1323 const SkRect bounds = getSkRect(boundsRect);
1324 const SkRect crop = getSkRect(cropRect);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001325
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001326 SkRRect clip;
1327 if (cornerRadius > 0) {
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001328 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
1329 if (bounds == crop || crop.isEmpty()) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001330 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1331 }
1332
1333 // This makes an effort to speed up common, simple bounds + clip combinations by
1334 // converting them to a single RRect draw. It is possible there are other cases
1335 // that can be converted.
1336 if (crop.contains(bounds)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001337 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001338 if (insetCrop.contains(bounds)) {
1339 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001340 }
1341
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001342 SkVector radii[4];
1343 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001344 SkRRect intersectionBounds;
1345 intersectionBounds.setRectRadii(bounds, radii);
1346 return {intersectionBounds, clip};
1347 }
1348 }
1349
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001350 // we didn't hit any of our fast paths so set the clip to the cropRect
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001351 clip.setRectXY(crop, cornerRadius, cornerRadius);
1352 }
1353
1354 // if we hit this point then we either don't have rounded corners or we are going to rely
1355 // on the clip to round the corners for us
1356 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001357}
1358
Sally Qi59a9f502021-10-12 18:53:23 +00001359inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings& layer,
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001360 bool colorTransformModifiesAlpha) {
Sally Qi59a9f502021-10-12 18:53:23 +00001361 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001362 // return false if the content is opaque and would therefore occlude the blur
Sally Qi59a9f502021-10-12 18:53:23 +00001363 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
1364 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
1365 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001366 }
1367 return false;
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001368}
1369
Lucas Dupin3f11e922020-09-22 17:31:04 -07001370inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1371 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1372}
1373
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001374inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1375 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1376 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1377 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1378 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1379}
1380
Lucas Dupin3f11e922020-09-22 17:31:04 -07001381inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1382 return SkPoint3::Make(vector.x, vector.y, vector.z);
1383}
1384
John Reck67b1e2b2020-08-26 13:17:24 -07001385size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1386 return mGrContext->maxTextureSize();
1387}
1388
1389size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1390 return mGrContext->maxRenderTargetSize();
1391}
1392
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001393void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001394 const ShadowSettings& settings) {
1395 ATRACE_CALL();
1396 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001397 const auto flags =
1398 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1399
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001400 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001401 getSkPoint3(settings.lightPos), settings.lightRadius,
1402 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1403 flags);
1404}
1405
John Reck67b1e2b2020-08-26 13:17:24 -07001406EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001407 EGLContext shareContext,
1408 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001409 Protection protection) {
1410 EGLint renderableType = 0;
1411 if (config == EGL_NO_CONFIG_KHR) {
1412 renderableType = EGL_OPENGL_ES3_BIT;
1413 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1414 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1415 }
1416 EGLint contextClientVersion = 0;
1417 if (renderableType & EGL_OPENGL_ES3_BIT) {
1418 contextClientVersion = 3;
1419 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1420 contextClientVersion = 2;
1421 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1422 contextClientVersion = 1;
1423 } else {
1424 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1425 }
1426
1427 std::vector<EGLint> contextAttributes;
1428 contextAttributes.reserve(7);
1429 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1430 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001431 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001432 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001433 switch (*contextPriority) {
1434 case ContextPriority::REALTIME:
1435 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1436 break;
1437 case ContextPriority::MEDIUM:
1438 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1439 break;
1440 case ContextPriority::LOW:
1441 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1442 break;
1443 case ContextPriority::HIGH:
1444 default:
1445 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1446 break;
1447 }
John Reck67b1e2b2020-08-26 13:17:24 -07001448 }
1449 if (protection == Protection::PROTECTED) {
1450 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1451 contextAttributes.push_back(EGL_TRUE);
1452 }
1453 contextAttributes.push_back(EGL_NONE);
1454
1455 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1456
1457 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1458 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1459 // EGL_NO_CONTEXT so that we can abort.
1460 if (config != EGL_NO_CONFIG_KHR) {
1461 return context;
1462 }
1463 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1464 // should try to fall back to GLES 2.
1465 contextAttributes[1] = 2;
1466 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1467 }
1468
1469 return context;
1470}
1471
Alec Mourid6f09462020-12-07 11:18:17 -08001472std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1473 const RenderEngineCreationArgs& args) {
1474 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1475 return std::nullopt;
1476 }
1477
1478 switch (args.contextPriority) {
1479 case RenderEngine::ContextPriority::REALTIME:
1480 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1481 return RenderEngine::ContextPriority::REALTIME;
1482 } else {
1483 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1484 return RenderEngine::ContextPriority::HIGH;
1485 }
1486 case RenderEngine::ContextPriority::HIGH:
1487 case RenderEngine::ContextPriority::MEDIUM:
1488 case RenderEngine::ContextPriority::LOW:
1489 return args.contextPriority;
1490 default:
1491 return std::nullopt;
1492 }
1493}
1494
John Reck67b1e2b2020-08-26 13:17:24 -07001495EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1496 EGLConfig config, int hwcFormat,
1497 Protection protection) {
1498 EGLConfig placeholderConfig = config;
1499 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1500 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1501 }
1502 std::vector<EGLint> attributes;
1503 attributes.reserve(7);
1504 attributes.push_back(EGL_WIDTH);
1505 attributes.push_back(1);
1506 attributes.push_back(EGL_HEIGHT);
1507 attributes.push_back(1);
1508 if (protection == Protection::PROTECTED) {
1509 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1510 attributes.push_back(EGL_TRUE);
1511 }
1512 attributes.push_back(EGL_NONE);
1513
1514 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1515}
1516
Alec Mourid6f09462020-12-07 11:18:17 -08001517int SkiaGLRenderEngine::getContextPriority() {
1518 int value;
1519 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1520 return value;
1521}
1522
Ady Abrahamed3290f2021-05-17 15:12:14 -07001523void SkiaGLRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001524 // This cache multiplier was selected based on review of cache sizes relative
1525 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1526 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1527 // conservative default based on that analysis.
1528 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1529 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1530
1531 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001532 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001533
1534 // if it is possible to switch contexts then we will resize the other context
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001535 const bool originalProtectedState = mInProtectedContext;
1536 useProtectedContext(!mInProtectedContext);
1537 if (mInProtectedContext != originalProtectedState) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001538 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001539 // reset back to the initial context that was active when this method was called
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001540 useProtectedContext(originalProtectedState);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001541 }
1542}
1543
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001544void SkiaGLRenderEngine::dump(std::string& result) {
1545 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1546
1547 StringAppendF(&result, "\n ------------RE-----------------\n");
1548 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1549 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1550 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1551 extensions.getVersion());
1552 StringAppendF(&result, "%s\n", extensions.getExtensions());
1553 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1554 supportsProtectedContent());
1555 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001556 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1557 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001558
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001559 std::vector<ResourcePair> cpuResourceMap = {
1560 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1561 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1562 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1563 {"skia/sk_resource_cache/tessellated", "Shadows"},
1564 {"skia", "Other"},
1565 };
1566 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1567 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1568 StringAppendF(&result, "Skia CPU Caches: ");
1569 cpuReporter.logTotals(result);
1570 cpuReporter.logOutput(result);
1571
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001572 {
1573 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001574
1575 std::vector<ResourcePair> gpuResourceMap = {
1576 {"texture_renderbuffer", "Texture/RenderBuffer"},
1577 {"texture", "Texture"},
1578 {"gr_text_blob_cache", "Text"},
1579 {"skia", "Other"},
1580 };
1581 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1582 mGrContext->dumpMemoryStatistics(&gpuReporter);
1583 StringAppendF(&result, "Skia's GPU Caches: ");
1584 gpuReporter.logTotals(result);
1585 gpuReporter.logOutput(result);
1586 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1587 gpuReporter.logOutput(result, true);
1588
Alec Mouria90a5702021-04-16 16:36:21 +00001589 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1590 mGraphicBufferExternalRefs.size());
1591 StringAppendF(&result, "Dumping buffer ids...\n");
1592 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1593 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1594 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001595 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1596 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001597 StringAppendF(&result, "Dumping buffer ids...\n");
1598 // TODO(178539829): It would be nice to know which layer these are coming from and what
1599 // the texture sizes are.
1600 for (const auto& [id, unused] : mTextureCache) {
1601 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1602 }
1603 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001604
1605 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001606 if (mProtectedGrContext) {
1607 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1608 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001609 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1610 gpuProtectedReporter.logTotals(result);
1611 gpuProtectedReporter.logOutput(result);
1612 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1613 gpuProtectedReporter.logOutput(result, true);
1614
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001615 StringAppendF(&result, "\n");
1616 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1617 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1618 StringAppendF(&result, "- inputDataspace: %s\n",
1619 dataspaceDetails(
1620 static_cast<android_dataspace>(linearEffect.inputDataspace))
1621 .c_str());
1622 StringAppendF(&result, "- outputDataspace: %s\n",
1623 dataspaceDetails(
1624 static_cast<android_dataspace>(linearEffect.outputDataspace))
1625 .c_str());
1626 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1627 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1628 }
1629 }
1630 StringAppendF(&result, "\n");
1631}
1632
John Reck67b1e2b2020-08-26 13:17:24 -07001633} // namespace skia
1634} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001635} // namespace android