blob: 1665550696d788f12b2de3b7b6207154d8ad424a [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>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070049#include <numeric>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080050
51#include "../gl/GLExtensions.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040052#include "Cache.h"
Alec Mouric0aae732021-01-12 13:32:18 -080053#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080054#include "SkBlendMode.h"
55#include "SkImageInfo.h"
56#include "filters/BlurFilter.h"
Robin Lee26dacab2021-08-09 14:31:01 +020057#include "filters/GaussianBlurFilter.h"
Robin Lee026680a2021-07-26 12:49:53 +020058#include "filters/KawaseBlurFilter.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080059#include "filters/LinearEffect.h"
60#include "log/log_main.h"
61#include "skia/debug/SkiaCapture.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040062#include "skia/debug/SkiaMemoryReporter.h"
Nader Jawad2dfc98b2021-04-08 20:35:39 -070063#include "skia/filters/StretchShaderFactory.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080064#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070065
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040066namespace {
67// Debugging settings
68static const bool kPrintLayerSettings = false;
69static const bool kFlushAfterEveryLayer = false;
70} // namespace
71
John Reck67b1e2b2020-08-26 13:17:24 -070072bool checkGlError(const char* op, int lineNumber);
73
74namespace android {
75namespace renderengine {
76namespace skia {
77
Ana Krulec1d12b3b2021-01-27 16:49:51 -080078using base::StringAppendF;
79
John Reck67b1e2b2020-08-26 13:17:24 -070080static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
81 EGLint wanted, EGLConfig* outConfig) {
82 EGLint numConfigs = -1, n = 0;
83 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
84 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
85 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
86 configs.resize(n);
87
88 if (!configs.empty()) {
89 if (attribute != EGL_NONE) {
90 for (EGLConfig config : configs) {
91 EGLint value = 0;
92 eglGetConfigAttrib(dpy, config, attribute, &value);
93 if (wanted == value) {
94 *outConfig = config;
95 return NO_ERROR;
96 }
97 }
98 } else {
99 // just pick the first one
100 *outConfig = configs[0];
101 return NO_ERROR;
102 }
103 }
104
105 return NAME_NOT_FOUND;
106}
107
108static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
109 EGLConfig* config) {
110 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
111 // it is to be used with WIFI displays
112 status_t err;
113 EGLint wantedAttribute;
114 EGLint wantedAttributeValue;
115
116 std::vector<EGLint> attribs;
117 if (renderableType) {
118 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
119 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
120
121 // Default to 8 bits per channel.
122 const EGLint tmpAttribs[] = {
123 EGL_RENDERABLE_TYPE,
124 renderableType,
125 EGL_RECORDABLE_ANDROID,
126 EGL_TRUE,
127 EGL_SURFACE_TYPE,
128 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
129 EGL_FRAMEBUFFER_TARGET_ANDROID,
130 EGL_TRUE,
131 EGL_RED_SIZE,
132 is1010102 ? 10 : 8,
133 EGL_GREEN_SIZE,
134 is1010102 ? 10 : 8,
135 EGL_BLUE_SIZE,
136 is1010102 ? 10 : 8,
137 EGL_ALPHA_SIZE,
138 is1010102 ? 2 : 8,
139 EGL_NONE,
140 };
141 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
142 std::back_inserter(attribs));
143 wantedAttribute = EGL_NONE;
144 wantedAttributeValue = EGL_NONE;
145 } else {
146 // if no renderable type specified, fallback to a simplified query
147 wantedAttribute = EGL_NATIVE_VISUAL_ID;
148 wantedAttributeValue = format;
149 }
150
151 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
152 config);
153 if (err == NO_ERROR) {
154 EGLint caveat;
155 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
156 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
157 }
158
159 return err;
160}
161
162std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
163 const RenderEngineCreationArgs& args) {
164 // initialize EGL for the default display
165 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
166 if (!eglInitialize(display, nullptr, nullptr)) {
167 LOG_ALWAYS_FATAL("failed to initialize EGL");
168 }
169
Yiwei Zhange2650962020-12-01 23:27:58 +0000170 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700171 if (!eglVersion) {
172 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000173 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700174 }
175
Yiwei Zhange2650962020-12-01 23:27:58 +0000176 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700177 if (!eglExtensions) {
178 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000179 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700180 }
181
182 auto& extensions = gl::GLExtensions::getInstance();
183 extensions.initWithEGLStrings(eglVersion, eglExtensions);
184
185 // The code assumes that ES2 or later is available if this extension is
186 // supported.
187 EGLConfig config = EGL_NO_CONFIG_KHR;
188 if (!extensions.hasNoConfigContext()) {
189 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
190 }
191
John Reck67b1e2b2020-08-26 13:17:24 -0700192 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800193 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700194 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800195 protectedContext =
196 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700197 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
198 }
199
Alec Mourid6f09462020-12-07 11:18:17 -0800200 EGLContext ctxt =
201 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700202
203 // if can't create a GL context, we can only abort.
204 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
205
206 EGLSurface placeholder = EGL_NO_SURFACE;
207 if (!extensions.hasSurfacelessContext()) {
208 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
209 Protection::UNPROTECTED);
210 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
211 }
212 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
213 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
214 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
215 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
216
217 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
218 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
219 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
220 Protection::PROTECTED);
221 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
222 "can't create protected placeholder pbuffer");
223 }
224
225 // initialize the renderer while GL is current
226 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000227 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
228 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700229
230 ALOGI("OpenGL ES informations:");
231 ALOGI("vendor : %s", extensions.getVendor());
232 ALOGI("renderer : %s", extensions.getRenderer());
233 ALOGI("version : %s", extensions.getVersion());
234 ALOGI("extensions: %s", extensions.getExtensions());
235 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
236 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
237
238 return engine;
239}
240
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700241std::future<void> SkiaGLRenderEngine::primeCache() {
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500242 Cache::primeShaderCache(this);
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700243 return {};
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500244}
245
John Reck67b1e2b2020-08-26 13:17:24 -0700246EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
247 status_t err;
248 EGLConfig config;
249
250 // First try to get an ES3 config
251 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
252 if (err != NO_ERROR) {
253 // If ES3 fails, try to get an ES2 config
254 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
255 if (err != NO_ERROR) {
256 // If ES2 still doesn't work, probably because we're on the emulator.
257 // try a simplified query
258 ALOGW("no suitable EGLConfig found, trying a simpler query");
259 err = selectEGLConfig(display, format, 0, &config);
260 if (err != NO_ERROR) {
261 // this EGL is too lame for android
262 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
263 }
264 }
265 }
266
267 if (logConfig) {
268 // print some debugging info
269 EGLint r, g, b, a;
270 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
271 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
272 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
273 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
274 ALOGI("EGL information:");
275 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
276 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
277 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
278 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
279 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
280 }
281
282 return config;
283}
284
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400285sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
286 // This "cache" does not actually cache anything. It just allows us to
287 // monitor Skia's internal cache. So this method always returns null.
288 return nullptr;
289}
290
291void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
292 const SkString& description) {
293 mShadersCachedSinceLastCall++;
294}
295
296void SkiaGLRenderEngine::assertShadersCompiled(int numShaders) {
297 const int cached = mSkSLCacheMonitor.shadersCachedSinceLastCall();
298 LOG_ALWAYS_FATAL_IF(cached != numShaders, "Attempted to cache %i shaders; cached %i",
299 numShaders, cached);
300}
301
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400302int SkiaGLRenderEngine::reportShadersCompiled() {
303 return mSkSLCacheMonitor.shadersCachedSinceLastCall();
304}
305
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700306SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000307 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700308 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800309 : SkiaRenderEngine(args.renderEngineType),
310 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700311 mEGLContext(ctxt),
312 mPlaceholderSurface(placeholder),
313 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700314 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400315 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800316 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700317 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
318 LOG_ALWAYS_FATAL_IF(!glInterface.get());
319
320 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400321 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700322 options.fDisableDistanceFieldPaths = true;
Nathaniel Nifongf8d35e92021-06-08 15:02:25 -0400323 options.fReducedShaderVariations = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400324 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000325 mGrContext = GrDirectContext::MakeGL(glInterface, options);
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400326 if (supportsProtectedContent()) {
327 useProtectedContext(true);
Lucas Dupind508e472020-11-04 04:32:06 +0000328 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
329 useProtectedContext(false);
330 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700331
332 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500333 ALOGD("Background Blurs Enabled");
Robin Lee026680a2021-07-26 12:49:53 +0200334 mBlurFilter = new KawaseBlurFilter();
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700335 }
Alec Mouric0aae732021-01-12 13:32:18 -0800336 mCapture = std::make_unique<SkiaCapture>();
337}
338
339SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100340 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800341 if (mBlurFilter) {
342 delete mBlurFilter;
343 }
344
345 mCapture = nullptr;
346
347 mGrContext->flushAndSubmit(true);
348 mGrContext->abandonContext();
349
350 if (mProtectedGrContext) {
351 mProtectedGrContext->flushAndSubmit(true);
352 mProtectedGrContext->abandonContext();
353 }
354
355 if (mPlaceholderSurface != EGL_NO_SURFACE) {
356 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
357 }
358 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
359 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
360 }
361 if (mEGLContext != EGL_NO_CONTEXT) {
362 eglDestroyContext(mEGLDisplay, mEGLContext);
363 }
364 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
365 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
366 }
367 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
368 eglTerminate(mEGLDisplay);
369 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700370}
371
Lucas Dupind508e472020-11-04 04:32:06 +0000372bool SkiaGLRenderEngine::supportsProtectedContent() const {
373 return mProtectedEGLContext != EGL_NO_CONTEXT;
374}
375
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400376GrDirectContext* SkiaGLRenderEngine::getActiveGrContext() const {
377 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
378}
379
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400380void SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
381 if (useProtectedContext == mInProtectedContext ||
382 (useProtectedContext && !supportsProtectedContent())) {
383 return;
Lucas Dupind508e472020-11-04 04:32:06 +0000384 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400385
386 // release any scratch resources before switching into a new mode
387 if (getActiveGrContext()) {
388 getActiveGrContext()->purgeUnlockedResources(true);
389 }
390
Lucas Dupind508e472020-11-04 04:32:06 +0000391 const EGLSurface surface =
392 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
393 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
Alec Mouric0aae732021-01-12 13:32:18 -0800394
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400395 if (eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE) {
Lucas Dupind508e472020-11-04 04:32:06 +0000396 mInProtectedContext = useProtectedContext;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400397 // given that we are sharing the same thread between two GrContexts we need to
398 // make sure that the thread state is reset when switching between the two.
399 if (getActiveGrContext()) {
400 getActiveGrContext()->resetContext();
401 }
Lucas Dupind508e472020-11-04 04:32:06 +0000402 }
Lucas Dupind508e472020-11-04 04:32:06 +0000403}
404
John Reck67b1e2b2020-08-26 13:17:24 -0700405base::unique_fd SkiaGLRenderEngine::flush() {
406 ATRACE_CALL();
407 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
408 return base::unique_fd();
409 }
410
411 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
412 if (sync == EGL_NO_SYNC_KHR) {
413 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
414 return base::unique_fd();
415 }
416
417 // native fence fd will not be populated until flush() is done.
418 glFlush();
419
420 // get the fence fd
421 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
422 eglDestroySyncKHR(mEGLDisplay, sync);
423 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
424 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
425 }
426
427 return fenceFd;
428}
429
Alec Mouri4ee7b492021-08-11 10:36:55 -0700430void SkiaGLRenderEngine::waitFence(base::borrowed_fd fenceFd) {
431 if (fenceFd.get() >= 0 && !waitGpuFence(fenceFd)) {
432 ATRACE_NAME("SkiaGLRenderEngine::waitFence");
433 sync_wait(fenceFd.get(), -1);
434 }
435}
436
437bool SkiaGLRenderEngine::waitGpuFence(base::borrowed_fd fenceFd) {
John Reck67b1e2b2020-08-26 13:17:24 -0700438 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
439 !gl::GLExtensions::getInstance().hasWaitSync()) {
440 return false;
441 }
442
Alec Mouri4ee7b492021-08-11 10:36:55 -0700443 // Duplicate the fence for passing to eglCreateSyncKHR.
444 base::unique_fd fenceDup(dup(fenceFd.get()));
445 if (fenceDup.get() < 0) {
446 ALOGE("failed to create duplicate fence fd: %d", fenceDup.get());
447 return false;
448 }
449
John Reck67b1e2b2020-08-26 13:17:24 -0700450 // release the fd and transfer the ownership to EGLSync
Alec Mouri4ee7b492021-08-11 10:36:55 -0700451 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceDup.release(), EGL_NONE};
John Reck67b1e2b2020-08-26 13:17:24 -0700452 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
453 if (sync == EGL_NO_SYNC_KHR) {
454 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
455 return false;
456 }
457
458 // XXX: The spec draft is inconsistent as to whether this should return an
459 // EGLint or void. Ignore the return value for now, as it's not strictly
460 // needed.
461 eglWaitSyncKHR(mEGLDisplay, sync, 0);
462 EGLint error = eglGetError();
463 eglDestroySyncKHR(mEGLDisplay, sync);
464 if (error != EGL_SUCCESS) {
465 ALOGE("failed to wait for EGL native fence sync: %#x", error);
466 return false;
467 }
468
469 return true;
470}
471
Alec Mouri678245d2020-09-30 16:58:23 -0700472static float toDegrees(uint32_t transform) {
473 switch (transform) {
474 case ui::Transform::ROT_90:
475 return 90.0;
476 case ui::Transform::ROT_180:
477 return 180.0;
478 case ui::Transform::ROT_270:
479 return 270.0;
480 default:
481 return 0.0;
482 }
483}
484
Alec Mourib34f0b72020-10-02 13:18:34 -0700485static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
486 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
487 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
488 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
489 matrix[3][3], 0);
490}
491
Alec Mouri029d1952020-10-12 10:37:08 -0700492static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
493 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
494 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
495
496 // Treat unsupported dataspaces as srgb
497 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
498 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
499 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
500 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
501 }
502
503 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
504 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
505 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
506 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
507 }
508
509 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
510 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
511 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
512 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
513
514 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
515 sourceTransfer != destTransfer;
516}
517
Alec Mouria90a5702021-04-16 16:36:21 +0000518void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
519 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800520 // Only run this if RE is running on its own thread. This way the access to GL
521 // operations is guaranteed to be happening on the same thread.
522 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
523 return;
524 }
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400525 // We currently don't attempt to map a buffer if the buffer contains protected content
Derek Sollenberger45007182021-06-10 14:47:21 -0400526 // because GPU resources for protected buffers is much more limited.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400527 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Derek Sollenberger45007182021-06-10 14:47:21 -0400528 if (isProtectedBuffer) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400529 return;
530 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800531 ATRACE_CALL();
532
Derek Sollenberger45007182021-06-10 14:47:21 -0400533 // If we were to support caching protected buffers then we will need to switch the
534 // currently bound context if we are not already using the protected context (and subsequently
535 // switch back after the buffer is cached). However, for non-protected content we can bind
536 // the texture in either GL context because they are initialized with the same share_context
537 // which allows the texture state to be shared between them.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400538 auto grContext = getActiveGrContext();
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400539 auto& cache = mTextureCache;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400540
541 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000542 mGraphicBufferExternalRefs[buffer->getId()]++;
543
544 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800545 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400546 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400547 buffer->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400548 isRenderable, mTextureCleanupMgr);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400549 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800550 }
551}
552
Alec Mouria90a5702021-04-16 16:36:21 +0000553void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800554 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700555 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000556 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
557 iter != mGraphicBufferExternalRefs.end()) {
558 if (iter->second == 0) {
559 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
560 "> from RenderEngine texture, but the "
561 "ref count was already zero!",
562 buffer->getId());
563 mGraphicBufferExternalRefs.erase(buffer->getId());
564 return;
565 }
566
567 iter->second--;
568
Alec Mouric2ffeb42021-06-17 17:42:27 -0700569 // Swap contexts if needed prior to deleting this buffer
570 // See Issue 1 of
571 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
572 // when a protected context and an unprotected context are part of the same share group,
573 // protected surfaces may not be accessed by an unprotected context, implying that protected
574 // surfaces may only be freed when a protected context is active.
575 const bool inProtected = mInProtectedContext;
576 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
577
Alec Mouria90a5702021-04-16 16:36:21 +0000578 if (iter->second == 0) {
579 mTextureCache.erase(buffer->getId());
Alec Mouria90a5702021-04-16 16:36:21 +0000580 mGraphicBufferExternalRefs.erase(buffer->getId());
581 }
Alec Mouric2ffeb42021-06-17 17:42:27 -0700582
583 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
584 // are up-to-date.
585 if (inProtected != mInProtectedContext) {
586 useProtectedContext(inProtected);
587 }
Alec Mouria90a5702021-04-16 16:36:21 +0000588 }
John Reck67b1e2b2020-08-26 13:17:24 -0700589}
590
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400591bool SkiaGLRenderEngine::canSkipPostRenderCleanup() const {
592 std::lock_guard<std::mutex> lock(mRenderingMutex);
593 return mTextureCleanupMgr.isEmpty();
594}
595
596void SkiaGLRenderEngine::cleanupPostRender() {
597 ATRACE_CALL();
598 std::lock_guard<std::mutex> lock(mRenderingMutex);
599 mTextureCleanupMgr.cleanup();
600}
601
602// Helper class intended to be used on the stack to ensure that texture cleanup
603// is deferred until after this class goes out of scope.
604class DeferTextureCleanup final {
605public:
606 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
607 mMgr.setDeferredStatus(true);
608 }
609 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
610
611private:
612 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
613 AutoBackendTexture::CleanupManager& mMgr;
614};
615
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700616sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
617 const RuntimeEffectShaderParameters& parameters) {
Nader Jawad63644d32021-05-07 10:44:21 -0700618 // The given surface will be stretched by HWUI via matrix transformation
619 // which gets similar results for most surfaces
620 // Determine later on if we need to leverage the stertch shader within
621 // surface flinger
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700622 const auto& stretchEffect = parameters.layer.stretchEffect;
623 auto shader = parameters.shader;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700624 if (stretchEffect.hasEffect()) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700625 const auto targetBuffer = parameters.layer.source.buffer.buffer;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700626 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700627 if (graphicBuffer && parameters.shader) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700628 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
629 }
John Reckcdb4ed72021-02-04 13:39:33 -0500630 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700631
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700632 if (parameters.requiresLinearEffect) {
633 const ui::Dataspace inputDataspace = mUseColorManagement ? parameters.layer.sourceDataspace
634 : ui::Dataspace::V0_SRGB_LINEAR;
635 const ui::Dataspace outputDataspace = mUseColorManagement
636 ? parameters.display.outputDataspace
637 : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500638
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700639 auto effect =
640 shaders::LinearEffect{.inputDataspace = inputDataspace,
641 .outputDataspace = outputDataspace,
642 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha};
Ana Krulec47814212021-01-06 19:00:10 -0800643
644 auto effectIter = mRuntimeEffects.find(effect);
645 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
646 if (effectIter == mRuntimeEffects.end()) {
647 runtimeEffect = buildRuntimeEffect(effect);
648 mRuntimeEffects.insert({effect, runtimeEffect});
649 } else {
650 runtimeEffect = effectIter->second;
651 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700652 mat4 colorTransform = parameters.layer.colorTransform;
653
654 colorTransform *=
655 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
656 parameters.layerDimmingRatio, 1.f));
Alec Mouri1a3c5452022-03-04 22:44:51 +0000657 const auto targetBuffer = parameters.layer.source.buffer.buffer;
658 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
659 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700660 return createLinearEffectShader(parameters.shader, effect, runtimeEffect, colorTransform,
661 parameters.display.maxLuminance,
Alec Mourib21d94e2022-01-13 17:44:10 -0800662 parameters.display.currentLuminanceNits,
Alec Mouri1a3c5452022-03-04 22:44:51 +0000663 parameters.layer.source.buffer.maxLuminanceNits,
664 hardwareBuffer);
Ana Krulec47814212021-01-06 19:00:10 -0800665 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700666 return parameters.shader;
Ana Krulec47814212021-01-06 19:00:10 -0800667}
668
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500669void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500670 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500671 // Record display settings when capture is running.
672 std::stringstream displaySettings;
673 PrintTo(display, &displaySettings);
674 // Store the DisplaySettings in additional information.
675 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
676 SkData::MakeWithCString(displaySettings.str().c_str()));
677 }
678
679 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
680 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
681 // displays might have different scaling when compared to the physical screen.
682
683 canvas->clipRect(getSkRect(display.physicalDisplay));
684 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
685
686 const auto clipWidth = display.clip.width();
687 const auto clipHeight = display.clip.height();
688 auto rotatedClipWidth = clipWidth;
689 auto rotatedClipHeight = clipHeight;
690 // Scale is contingent on the rotation result.
691 if (display.orientation & ui::Transform::ROT_90) {
692 std::swap(rotatedClipWidth, rotatedClipHeight);
693 }
694 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
695 static_cast<SkScalar>(rotatedClipWidth);
696 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
697 static_cast<SkScalar>(rotatedClipHeight);
698 canvas->scale(scaleX, scaleY);
699
700 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
701 // back so that the top left corner of the clip is at (0, 0).
702 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
703 canvas->rotate(toDegrees(display.orientation));
704 canvas->translate(-clipWidth / 2, -clipHeight / 2);
705 canvas->translate(-display.clip.left, -display.clip.top);
706}
707
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500708class AutoSaveRestore {
709public:
710 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
711 ~AutoSaveRestore() { restore(); }
712 void replace(SkCanvas* canvas) {
713 mCanvas = canvas;
714 mSaveCount = canvas->save();
715 }
716 void restore() {
717 if (mCanvas) {
718 mCanvas->restoreToCount(mSaveCount);
719 mCanvas = nullptr;
720 }
721 }
722
723private:
724 SkCanvas* mCanvas;
725 int mSaveCount;
726};
727
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400728static SkRRect getBlurRRect(const BlurRegion& region) {
729 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
730 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
731 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
732 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
733 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
734 SkRRect roundedRect;
735 roundedRect.setRectRadii(rect, radii);
736 return roundedRect;
737}
738
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700739static bool equalsWithinMargin(float expected, float value, float margin) {
740 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
741 return std::abs(expected - value) < margin;
742}
743
Sally Qi4cabdd02021-08-05 16:45:57 -0700744void SkiaGLRenderEngine::drawLayersInternal(
745 const std::shared_ptr<std::promise<RenderEngineResult>>&& resultPromise,
Sally Qi59a9f502021-10-12 18:53:23 +0000746 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
Sally Qi4cabdd02021-08-05 16:45:57 -0700747 const std::shared_ptr<ExternalTexture>& buffer, const bool /*useFramebufferCache*/,
748 base::unique_fd&& bufferFence) {
John Reck67b1e2b2020-08-26 13:17:24 -0700749 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800750
John Reck67b1e2b2020-08-26 13:17:24 -0700751 std::lock_guard<std::mutex> lock(mRenderingMutex);
752 if (layers.empty()) {
753 ALOGV("Drawing empty layer stack");
Sally Qi4cabdd02021-08-05 16:45:57 -0700754 resultPromise->set_value({NO_ERROR, base::unique_fd()});
755 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700756 }
757
John Reck67b1e2b2020-08-26 13:17:24 -0700758 if (buffer == nullptr) {
759 ALOGE("No output buffer provided. Aborting GPU composition.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700760 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
761 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700762 }
763
Alec Mouria90a5702021-04-16 16:36:21 +0000764 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800765
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400766 auto grContext = getActiveGrContext();
Derek Sollenberger45007182021-06-10 14:47:21 -0400767 auto& cache = mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700768
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400769 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
770 DeferTextureCleanup dtc(mTextureCleanupMgr);
771
Alec Mouria90a5702021-04-16 16:36:21 +0000772 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
773 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
774 surfaceTextureRef = it->second;
775 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400776 surfaceTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400777 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
778 buffer->getBuffer()
779 ->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400780 true, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -0700781 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800782
Alec Mouri4ee7b492021-08-11 10:36:55 -0700783 // wait on the buffer to be ready to use prior to using it
784 waitFence(bufferFence);
785
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500786 const ui::Dataspace dstDataspace =
Alec Mourid2bcbae2021-06-28 17:02:17 -0700787 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400788 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700789
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500790 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
791 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800792 ALOGE("Cannot acquire canvas from Skia.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700793 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
794 return;
Ana Krulec6eab17a2020-12-09 15:52:36 -0800795 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500796
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400797 // setup color filter if necessary
798 sk_sp<SkColorFilter> displayColorTransform;
Leon Scroggins III745dcaa2022-01-26 11:55:58 -0500799 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400800 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
801 }
802 const bool ctModifiesAlpha =
803 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
804
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700805 // Find the max layer white point to determine the max luminance of the scene...
806 const float maxLayerWhitePoint = std::transform_reduce(
807 layers.cbegin(), layers.cend(), 0.f,
808 [](float left, float right) { return std::max(left, right); },
809 [&](const auto& l) { return l.whitePointNits; });
810
811 // ...and compute the dimming ratio if dimming is requested
812 const float displayDimmingRatio = display.targetLuminanceNits > 0.f &&
813 maxLayerWhitePoint > 0.f && display.targetLuminanceNits > maxLayerWhitePoint
814 ? maxLayerWhitePoint / display.targetLuminanceNits
815 : 1.f;
816
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500817 // Find if any layers have requested blur, we'll use that info to decide when to render to an
818 // offscreen buffer and when to render to the native buffer.
819 sk_sp<SkSurface> activeSurface(dstSurface);
820 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500821 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500822 const LayerSettings* blurCompositionLayer = nullptr;
823 if (mBlurFilter) {
824 bool requiresCompositionLayer = false;
825 for (const auto& layer : layers) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400826 // if the layer doesn't have blur or it is not visible then continue
827 if (!layerHasBlur(layer, ctModifiesAlpha)) {
828 continue;
829 }
Sally Qi59a9f502021-10-12 18:53:23 +0000830 if (layer.backgroundBlurRadius > 0 &&
Robin Lee26dacab2021-08-09 14:31:01 +0200831 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500832 requiresCompositionLayer = true;
833 }
Sally Qi59a9f502021-10-12 18:53:23 +0000834 for (auto region : layer.blurRegions) {
Robin Lee26dacab2021-08-09 14:31:01 +0200835 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500836 requiresCompositionLayer = true;
837 }
838 }
839 if (requiresCompositionLayer) {
840 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500841 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Sally Qi59a9f502021-10-12 18:53:23 +0000842 blurCompositionLayer = &layer;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500843 break;
844 }
845 }
846 }
847
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500848 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700849 // Clear the entire canvas with a transparent black to prevent ghost images.
850 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500851 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800852
John Reck67b1e2b2020-08-26 13:17:24 -0700853 for (const auto& layer : layers) {
Sally Qi59a9f502021-10-12 18:53:23 +0000854 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
Galia Peychevaf7889b32020-11-25 22:22:40 +0100855
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400856 if (kPrintLayerSettings) {
857 std::stringstream ls;
Sally Qi59a9f502021-10-12 18:53:23 +0000858 PrintTo(layer, &ls);
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400859 auto debugs = ls.str();
860 int pos = 0;
861 while (pos < debugs.size()) {
862 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
863 pos += 1000;
864 }
865 }
866
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500867 sk_sp<SkImage> blurInput;
Sally Qi59a9f502021-10-12 18:53:23 +0000868 if (blurCompositionLayer == &layer) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500869 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
870 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
871
872 // save a snapshot of the activeSurface to use as input to the blur shaders
873 blurInput = activeSurface->makeImageSnapshot();
874
Leon Scroggins III55bf4742022-03-17 14:11:17 -0400875 // blit the offscreen framebuffer into the destination AHB, but only
876 // if there are blur regions. backgroundBlurRadius blurs the entire
877 // image below, so it can skip this step.
878 if (layer.blurRegions.size()) {
879 SkPaint paint;
880 paint.setBlendMode(SkBlendMode::kSrc);
881 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
882 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
883 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
884 String8::format("SurfaceID|%" PRId64, id).c_str(),
885 nullptr);
886 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
887 } else {
888 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
889 }
Derek Sollenberger76664d62021-02-04 11:13:09 -0500890 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500891
892 // assign dstCanvas to canvas and ensure that the canvas state is up to date
893 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500894 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500895 initCanvas(canvas, display);
896
897 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
898 dstSurface->getCanvas()->getSaveCount());
899 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
900 dstSurface->getCanvas()->getTotalMatrix());
901
902 // assign dstSurface to activeSurface
903 activeSurface = dstSurface;
904 }
905
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500906 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500907 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800908 // Record the name of the layer if the capture is running.
909 std::stringstream layerSettings;
Sally Qi59a9f502021-10-12 18:53:23 +0000910 PrintTo(layer, &layerSettings);
Ana Krulec6eab17a2020-12-09 15:52:36 -0800911 // Store the LayerSettings in additional information.
Sally Qi59a9f502021-10-12 18:53:23 +0000912 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
Ana Krulec6eab17a2020-12-09 15:52:36 -0800913 SkData::MakeWithCString(layerSettings.str().c_str()));
914 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100915 // Layers have a local transform that should be applied to them
Sally Qi59a9f502021-10-12 18:53:23 +0000916 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100917
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400918 const auto [bounds, roundRectClip] =
Sally Qi59a9f502021-10-12 18:53:23 +0000919 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
920 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400921 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500922 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
923
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500924 // if multiple layers have blur, then we need to take a snapshot now because
925 // only the lowest layer will have blurImage populated earlier
926 if (!blurInput) {
927 blurInput = activeSurface->makeImageSnapshot();
928 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500929 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400930 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
931
932 // if the clip needs to be applied then apply it now and make sure
933 // it is restored before we attempt to draw any shadows.
934 SkAutoCanvasRestore acr(canvas, true);
935 if (!roundRectClip.isEmpty()) {
936 canvas->clipRRect(roundRectClip, true);
937 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500938
Galia Peychevae425ac82021-03-15 17:12:03 +0100939 // TODO(b/182216890): Filter out empty layers earlier
940 if (blurRect.width() > 0 && blurRect.height() > 0) {
Sally Qi59a9f502021-10-12 18:53:23 +0000941 if (layer.backgroundBlurRadius > 0) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100942 ATRACE_NAME("BackgroundBlur");
Sally Qi59a9f502021-10-12 18:53:23 +0000943 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
944 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100945
Sally Qi59a9f502021-10-12 18:53:23 +0000946 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500947
Sally Qi59a9f502021-10-12 18:53:23 +0000948 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400949 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700950 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400951
Sally Qi59a9f502021-10-12 18:53:23 +0000952 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
953 for (auto region : layer.blurRegions) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100954 if (cachedBlurs[region.blurRadius] == nullptr) {
955 ATRACE_NAME("BlurRegion");
956 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400957 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100958 blurRect);
959 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500960
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400961 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
962 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100963 cachedBlurs[region.blurRadius], blurInput);
964 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700965 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700966 }
967
Sally Qi59a9f502021-10-12 18:53:23 +0000968 if (layer.shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400969 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
Sally Qi59a9f502021-10-12 18:53:23 +0000970 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
Leon Scroggins III63e86952021-05-12 10:45:08 -0400971
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400972 SkRRect shadowBounds, shadowClip;
Sally Qi59a9f502021-10-12 18:53:23 +0000973 if (layer.geometry.boundaries == layer.shadow.boundaries) {
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400974 shadowBounds = bounds;
975 shadowClip = roundRectClip;
976 } else {
977 std::tie(shadowBounds, shadowClip) =
Sally Qi59a9f502021-10-12 18:53:23 +0000978 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
979 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400980 }
981
Leon Scroggins III63e86952021-05-12 10:45:08 -0400982 // Technically, if bounds is a rect and roundRectClip is not empty,
983 // it means that the bounds and roundedCornersCrop were different
984 // enough that we should intersect them to find the proper shadow.
985 // In practice, this often happens when the two rectangles appear to
986 // not match due to rounding errors. Draw the rounded version, which
987 // looks more like the intent.
988 const auto& rrect =
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400989 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
Sally Qi59a9f502021-10-12 18:53:23 +0000990 drawShadow(canvas, rrect, layer.shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500991 }
992
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700993 const float layerDimmingRatio = layer.whitePointNits <= 0.f
994 ? displayDimmingRatio
995 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
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 Mouricdf6cbc2021-11-01 17:21:15 -07001000 !equalsWithinMargin(1.f, layerDimmingRatio, 0.001f);
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,
1106 .layerDimmingRatio = layerDimmingRatio}));
1107
1108 // Turn on dithering when dimming beyond this threshold.
1109 static constexpr float kDimmingThreshold = 0.2f;
1110 if (layerDimmingRatio <= kDimmingThreshold) {
1111 paint.setDither(true);
1112 }
Sally Qi59a9f502021-10-12 18:53:23 +00001113 paint.setAlphaf(layer.alpha);
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001114
1115 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1116 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001117
1118 // SysUI creates the alpha layer as a coverage layer, which is
1119 // appropriate for the DPU. Use a color matrix to convert it to
1120 // a mask.
1121 // TODO (b/219525258): Handle input as a mask.
1122 //
1123 // The color matrix will convert A8 pixels with no alpha to
1124 // black, as described by this vector. If the display handles
1125 // the color transform, we need to invert it to find the color
1126 // that will result in black after the DPU applies the transform.
1127 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1128 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1129 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1130 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1131 black = colorSpaceMatrix * black;
1132 } else {
1133 // We'll just have to use 0,0,0 as black, which should
1134 // be close to correct.
1135 ALOGI("Could not invert colorTransform!");
1136 }
1137 }
1138 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1139 0, 0, 0, 0, black[1],
1140 0, 0, 0, 0, black[2],
1141 0, 0, 0, -1, 1);
1142 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1143 // On the other hand, if the device doesn't handle it, we
1144 // have to apply it ourselves.
1145 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1146 }
1147 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001148 }
John Reck67b1e2b2020-08-26 13:17:24 -07001149 } else {
1150 ATRACE_NAME("DrawColor");
Sally Qi59a9f502021-10-12 18:53:23 +00001151 const auto color = layer.source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001152 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1153 .fG = color.g,
1154 .fB = color.b,
Sally Qi59a9f502021-10-12 18:53:23 +00001155 .fA = layer.alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001156 toSkColorSpace(layerDataspace));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001157 paint.setShader(createRuntimeEffectShader(
1158 RuntimeEffectShaderParameters{.shader = shader,
1159 .layer = layer,
1160 .display = display,
1161 .undoPremultipliedAlpha = false,
1162 .requiresLinearEffect = requiresLinearEffect,
1163 .layerDimmingRatio = layerDimmingRatio}));
John Reck67b1e2b2020-08-26 13:17:24 -07001164 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001165
Sally Qi59a9f502021-10-12 18:53:23 +00001166 if (layer.disableBlending) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001167 paint.setBlendMode(SkBlendMode::kSrc);
1168 }
1169
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001170 // An A8 buffer will already have the proper color filter attached to
1171 // its paint, including the displayColorTransform as needed.
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001172 if (!paint.getColorFilter()) {
1173 paint.setColorFilter(displayColorTransform);
1174 }
Alec Mourib34f0b72020-10-02 13:18:34 -07001175
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001176 if (!roundRectClip.isEmpty()) {
1177 canvas->clipRRect(roundRectClip, true);
1178 }
1179
1180 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001181 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001182 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001183 } else {
Nader Jawad63644d32021-05-07 10:44:21 -07001184 canvas->drawRect(bounds.rect(), paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -07001185 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001186 if (kFlushAfterEveryLayer) {
1187 ATRACE_NAME("flush surface");
1188 activeSurface->flush();
1189 }
John Reck67b1e2b2020-08-26 13:17:24 -07001190 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001191 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001192 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001193 {
1194 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001195 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1196 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001197 }
1198
Sally Qi4cabdd02021-08-05 16:45:57 -07001199 base::unique_fd drawFence = flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001200
1201 // If flush failed or we don't support native fences, we need to force the
1202 // gl command stream to be executed.
Sally Qi4cabdd02021-08-05 16:45:57 -07001203 bool requireSync = drawFence.get() < 0;
John Reck67b1e2b2020-08-26 13:17:24 -07001204 if (requireSync) {
1205 ATRACE_BEGIN("Submit(sync=true)");
1206 } else {
1207 ATRACE_BEGIN("Submit(sync=false)");
1208 }
Lucas Dupind508e472020-11-04 04:32:06 +00001209 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001210 ATRACE_END();
1211 if (!success) {
1212 ALOGE("Failed to flush RenderEngine commands");
1213 // Chances are, something illegal happened (either the caller passed
1214 // us bad parameters, or we messed up our shader generation).
Sally Qi4cabdd02021-08-05 16:45:57 -07001215 resultPromise->set_value({INVALID_OPERATION, std::move(drawFence)});
1216 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001217 }
1218
1219 // checkErrors();
Sally Qi4cabdd02021-08-05 16:45:57 -07001220 resultPromise->set_value({NO_ERROR, std::move(drawFence)});
1221 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001222}
1223
Lucas Dupin3f11e922020-09-22 17:31:04 -07001224inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1225 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1226}
1227
1228inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1229 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1230}
1231
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001232/**
1233 * Verifies that common, simple bounds + clip combinations can be converted into
1234 * a single RRect draw call returning true if possible. If true the radii parameter
1235 * will be filled with the correct radii values that combined with bounds param will
1236 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
1237 */
1238static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
1239 const SkRect& insetCrop, float cornerRadius,
1240 SkVector radii[4]) {
1241 const bool leftEqual = bounds.fLeft == crop.fLeft;
1242 const bool topEqual = bounds.fTop == crop.fTop;
1243 const bool rightEqual = bounds.fRight == crop.fRight;
1244 const bool bottomEqual = bounds.fBottom == crop.fBottom;
1245
1246 // In the event that the corners of the bounds only partially align with the crop we
1247 // need to ensure that the resulting shape can still be represented as a round rect.
1248 // In particular the round rect implementation will scale the value of all corner radii
1249 // if the sum of the radius along any edge is greater than the length of that edge.
1250 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
1251 const bool requiredWidth = bounds.width() > (cornerRadius * 2);
1252 const bool requiredHeight = bounds.height() > (cornerRadius * 2);
1253 if (!requiredWidth || !requiredHeight) {
1254 return false;
1255 }
1256
1257 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
1258 // contained within the cropped shape and does not need rounded.
1259 // compute the UpperLeft corner radius
1260 if (leftEqual && topEqual) {
1261 radii[0].set(cornerRadius, cornerRadius);
1262 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
1263 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
1264 radii[0].set(0, 0);
1265 } else {
1266 return false;
1267 }
1268 // compute the UpperRight corner radius
1269 if (rightEqual && topEqual) {
1270 radii[1].set(cornerRadius, cornerRadius);
1271 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
1272 (topEqual && bounds.fRight <= insetCrop.fRight)) {
1273 radii[1].set(0, 0);
1274 } else {
1275 return false;
1276 }
1277 // compute the BottomRight corner radius
1278 if (rightEqual && bottomEqual) {
1279 radii[2].set(cornerRadius, cornerRadius);
1280 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
1281 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
1282 radii[2].set(0, 0);
1283 } else {
1284 return false;
1285 }
1286 // compute the BottomLeft corner radius
1287 if (leftEqual && bottomEqual) {
1288 radii[3].set(cornerRadius, cornerRadius);
1289 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
1290 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
1291 radii[3].set(0, 0);
1292 } else {
1293 return false;
1294 }
1295
1296 return true;
1297}
1298
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001299inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(const FloatRect& boundsRect,
1300 const FloatRect& cropRect,
1301 const float cornerRadius) {
1302 const SkRect bounds = getSkRect(boundsRect);
1303 const SkRect crop = getSkRect(cropRect);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001304
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001305 SkRRect clip;
1306 if (cornerRadius > 0) {
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001307 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
1308 if (bounds == crop || crop.isEmpty()) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001309 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1310 }
1311
1312 // This makes an effort to speed up common, simple bounds + clip combinations by
1313 // converting them to a single RRect draw. It is possible there are other cases
1314 // that can be converted.
1315 if (crop.contains(bounds)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001316 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001317 if (insetCrop.contains(bounds)) {
1318 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001319 }
1320
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001321 SkVector radii[4];
1322 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001323 SkRRect intersectionBounds;
1324 intersectionBounds.setRectRadii(bounds, radii);
1325 return {intersectionBounds, clip};
1326 }
1327 }
1328
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001329 // we didn't hit any of our fast paths so set the clip to the cropRect
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001330 clip.setRectXY(crop, cornerRadius, cornerRadius);
1331 }
1332
1333 // if we hit this point then we either don't have rounded corners or we are going to rely
1334 // on the clip to round the corners for us
1335 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001336}
1337
Sally Qi59a9f502021-10-12 18:53:23 +00001338inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings& layer,
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001339 bool colorTransformModifiesAlpha) {
Sally Qi59a9f502021-10-12 18:53:23 +00001340 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001341 // return false if the content is opaque and would therefore occlude the blur
Sally Qi59a9f502021-10-12 18:53:23 +00001342 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
1343 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
1344 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001345 }
1346 return false;
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001347}
1348
Lucas Dupin3f11e922020-09-22 17:31:04 -07001349inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1350 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1351}
1352
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001353inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1354 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1355 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1356 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1357 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1358}
1359
Lucas Dupin3f11e922020-09-22 17:31:04 -07001360inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1361 return SkPoint3::Make(vector.x, vector.y, vector.z);
1362}
1363
John Reck67b1e2b2020-08-26 13:17:24 -07001364size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1365 return mGrContext->maxTextureSize();
1366}
1367
1368size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1369 return mGrContext->maxRenderTargetSize();
1370}
1371
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001372void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001373 const ShadowSettings& settings) {
1374 ATRACE_CALL();
1375 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001376 const auto flags =
1377 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1378
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001379 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001380 getSkPoint3(settings.lightPos), settings.lightRadius,
1381 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1382 flags);
1383}
1384
John Reck67b1e2b2020-08-26 13:17:24 -07001385EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001386 EGLContext shareContext,
1387 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001388 Protection protection) {
1389 EGLint renderableType = 0;
1390 if (config == EGL_NO_CONFIG_KHR) {
1391 renderableType = EGL_OPENGL_ES3_BIT;
1392 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1393 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1394 }
1395 EGLint contextClientVersion = 0;
1396 if (renderableType & EGL_OPENGL_ES3_BIT) {
1397 contextClientVersion = 3;
1398 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1399 contextClientVersion = 2;
1400 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1401 contextClientVersion = 1;
1402 } else {
1403 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1404 }
1405
1406 std::vector<EGLint> contextAttributes;
1407 contextAttributes.reserve(7);
1408 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1409 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001410 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001411 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001412 switch (*contextPriority) {
1413 case ContextPriority::REALTIME:
1414 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1415 break;
1416 case ContextPriority::MEDIUM:
1417 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1418 break;
1419 case ContextPriority::LOW:
1420 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1421 break;
1422 case ContextPriority::HIGH:
1423 default:
1424 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1425 break;
1426 }
John Reck67b1e2b2020-08-26 13:17:24 -07001427 }
1428 if (protection == Protection::PROTECTED) {
1429 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1430 contextAttributes.push_back(EGL_TRUE);
1431 }
1432 contextAttributes.push_back(EGL_NONE);
1433
1434 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1435
1436 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1437 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1438 // EGL_NO_CONTEXT so that we can abort.
1439 if (config != EGL_NO_CONFIG_KHR) {
1440 return context;
1441 }
1442 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1443 // should try to fall back to GLES 2.
1444 contextAttributes[1] = 2;
1445 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1446 }
1447
1448 return context;
1449}
1450
Alec Mourid6f09462020-12-07 11:18:17 -08001451std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1452 const RenderEngineCreationArgs& args) {
1453 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1454 return std::nullopt;
1455 }
1456
1457 switch (args.contextPriority) {
1458 case RenderEngine::ContextPriority::REALTIME:
1459 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1460 return RenderEngine::ContextPriority::REALTIME;
1461 } else {
1462 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1463 return RenderEngine::ContextPriority::HIGH;
1464 }
1465 case RenderEngine::ContextPriority::HIGH:
1466 case RenderEngine::ContextPriority::MEDIUM:
1467 case RenderEngine::ContextPriority::LOW:
1468 return args.contextPriority;
1469 default:
1470 return std::nullopt;
1471 }
1472}
1473
John Reck67b1e2b2020-08-26 13:17:24 -07001474EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1475 EGLConfig config, int hwcFormat,
1476 Protection protection) {
1477 EGLConfig placeholderConfig = config;
1478 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1479 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1480 }
1481 std::vector<EGLint> attributes;
1482 attributes.reserve(7);
1483 attributes.push_back(EGL_WIDTH);
1484 attributes.push_back(1);
1485 attributes.push_back(EGL_HEIGHT);
1486 attributes.push_back(1);
1487 if (protection == Protection::PROTECTED) {
1488 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1489 attributes.push_back(EGL_TRUE);
1490 }
1491 attributes.push_back(EGL_NONE);
1492
1493 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1494}
1495
Alec Mourid6f09462020-12-07 11:18:17 -08001496int SkiaGLRenderEngine::getContextPriority() {
1497 int value;
1498 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1499 return value;
1500}
1501
Ady Abrahamed3290f2021-05-17 15:12:14 -07001502void SkiaGLRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001503 // This cache multiplier was selected based on review of cache sizes relative
1504 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1505 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1506 // conservative default based on that analysis.
1507 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1508 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1509
1510 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001511 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001512
1513 // if it is possible to switch contexts then we will resize the other context
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001514 const bool originalProtectedState = mInProtectedContext;
1515 useProtectedContext(!mInProtectedContext);
1516 if (mInProtectedContext != originalProtectedState) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001517 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001518 // reset back to the initial context that was active when this method was called
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001519 useProtectedContext(originalProtectedState);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001520 }
1521}
1522
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001523void SkiaGLRenderEngine::dump(std::string& result) {
1524 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1525
1526 StringAppendF(&result, "\n ------------RE-----------------\n");
1527 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1528 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1529 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1530 extensions.getVersion());
1531 StringAppendF(&result, "%s\n", extensions.getExtensions());
1532 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1533 supportsProtectedContent());
1534 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001535 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1536 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001537
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001538 std::vector<ResourcePair> cpuResourceMap = {
1539 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1540 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1541 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1542 {"skia/sk_resource_cache/tessellated", "Shadows"},
1543 {"skia", "Other"},
1544 };
1545 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1546 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1547 StringAppendF(&result, "Skia CPU Caches: ");
1548 cpuReporter.logTotals(result);
1549 cpuReporter.logOutput(result);
1550
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001551 {
1552 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001553
1554 std::vector<ResourcePair> gpuResourceMap = {
1555 {"texture_renderbuffer", "Texture/RenderBuffer"},
1556 {"texture", "Texture"},
1557 {"gr_text_blob_cache", "Text"},
1558 {"skia", "Other"},
1559 };
1560 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1561 mGrContext->dumpMemoryStatistics(&gpuReporter);
1562 StringAppendF(&result, "Skia's GPU Caches: ");
1563 gpuReporter.logTotals(result);
1564 gpuReporter.logOutput(result);
1565 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1566 gpuReporter.logOutput(result, true);
1567
Alec Mouria90a5702021-04-16 16:36:21 +00001568 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1569 mGraphicBufferExternalRefs.size());
1570 StringAppendF(&result, "Dumping buffer ids...\n");
1571 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1572 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1573 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001574 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1575 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001576 StringAppendF(&result, "Dumping buffer ids...\n");
1577 // TODO(178539829): It would be nice to know which layer these are coming from and what
1578 // the texture sizes are.
1579 for (const auto& [id, unused] : mTextureCache) {
1580 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1581 }
1582 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001583
1584 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001585 if (mProtectedGrContext) {
1586 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1587 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001588 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1589 gpuProtectedReporter.logTotals(result);
1590 gpuProtectedReporter.logOutput(result);
1591 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1592 gpuProtectedReporter.logOutput(result, true);
1593
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001594 StringAppendF(&result, "\n");
1595 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1596 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1597 StringAppendF(&result, "- inputDataspace: %s\n",
1598 dataspaceDetails(
1599 static_cast<android_dataspace>(linearEffect.inputDataspace))
1600 .c_str());
1601 StringAppendF(&result, "- outputDataspace: %s\n",
1602 dataspaceDetails(
1603 static_cast<android_dataspace>(linearEffect.outputDataspace))
1604 .c_str());
1605 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1606 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1607 }
1608 }
1609 StringAppendF(&result, "\n");
1610}
1611
John Reck67b1e2b2020-08-26 13:17:24 -07001612} // namespace skia
1613} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001614} // namespace android