blob: 20c4c5bb359d69c2c19c735f1e824fba75a59dd5 [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>
Kevin Lubick1d530202022-02-26 13:48:04 +000027#include <SkBlendMode.h>
John Reck67b1e2b2020-08-26 13:17:24 -070028#include <SkCanvas.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000029#include <SkColor.h>
Alec Mourib34f0b72020-10-02 13:18:34 -070030#include <SkColorFilter.h>
31#include <SkColorMatrix.h>
Alec Mourib5777452020-09-28 11:32:42 -070032#include <SkColorSpace.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000033#include <SkData.h>
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040034#include <SkGraphics.h>
John Reck67b1e2b2020-08-26 13:17:24 -070035#include <SkImage.h>
Lucas Dupinf4cb4a02020-09-22 14:19:26 -070036#include <SkImageFilters.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000037#include <SkImageInfo.h>
38#include <SkM44.h>
39#include <SkMatrix.h>
40#include <SkPaint.h>
41#include <SkPath.h>
42#include <SkPoint.h>
43#include <SkRect.h>
44#include <SkRefCnt.h>
Alec Mouric0aae732021-01-12 13:32:18 -080045#include <SkRegion.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000046#include <SkRRect.h>
47#include <SkRuntimeEffect.h>
48#include <SkSamplingOptions.h>
49#include <SkScalar.h>
50#include <SkShader.h>
Lucas Dupin3f11e922020-09-22 17:31:04 -070051#include <SkShadowUtils.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000052#include <SkString.h>
John Reck67b1e2b2020-08-26 13:17:24 -070053#include <SkSurface.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000054#include <SkTileMode.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080055#include <android-base/stringprintf.h>
Alec Mourib5777452020-09-28 11:32:42 -070056#include <gl/GrGLInterface.h>
Alec Mouricbd30932021-06-09 15:52:25 -070057#include <gui/TraceUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080058#include <sync/sync.h>
59#include <ui/BlurRegion.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080060#include <ui/DebugUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080061#include <ui/GraphicBuffer.h>
62#include <utils/Trace.h>
Alec Mourib5777452020-09-28 11:32:42 -070063
64#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080065#include <cstdint>
66#include <memory>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070067#include <numeric>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080068
69#include "../gl/GLExtensions.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040070#include "Cache.h"
Alec Mouric0aae732021-01-12 13:32:18 -080071#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080072#include "filters/BlurFilter.h"
Robin Lee26dacab2021-08-09 14:31:01 +020073#include "filters/GaussianBlurFilter.h"
Robin Lee026680a2021-07-26 12:49:53 +020074#include "filters/KawaseBlurFilter.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080075#include "filters/LinearEffect.h"
76#include "log/log_main.h"
77#include "skia/debug/SkiaCapture.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040078#include "skia/debug/SkiaMemoryReporter.h"
Nader Jawad2dfc98b2021-04-08 20:35:39 -070079#include "skia/filters/StretchShaderFactory.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080080#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070081
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040082namespace {
83// Debugging settings
84static const bool kPrintLayerSettings = false;
85static const bool kFlushAfterEveryLayer = false;
86} // namespace
87
John Reck67b1e2b2020-08-26 13:17:24 -070088bool checkGlError(const char* op, int lineNumber);
89
90namespace android {
91namespace renderengine {
92namespace skia {
93
Ana Krulec1d12b3b2021-01-27 16:49:51 -080094using base::StringAppendF;
95
John Reck67b1e2b2020-08-26 13:17:24 -070096static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
97 EGLint wanted, EGLConfig* outConfig) {
98 EGLint numConfigs = -1, n = 0;
99 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
100 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
101 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
102 configs.resize(n);
103
104 if (!configs.empty()) {
105 if (attribute != EGL_NONE) {
106 for (EGLConfig config : configs) {
107 EGLint value = 0;
108 eglGetConfigAttrib(dpy, config, attribute, &value);
109 if (wanted == value) {
110 *outConfig = config;
111 return NO_ERROR;
112 }
113 }
114 } else {
115 // just pick the first one
116 *outConfig = configs[0];
117 return NO_ERROR;
118 }
119 }
120
121 return NAME_NOT_FOUND;
122}
123
124static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
125 EGLConfig* config) {
126 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
127 // it is to be used with WIFI displays
128 status_t err;
129 EGLint wantedAttribute;
130 EGLint wantedAttributeValue;
131
132 std::vector<EGLint> attribs;
133 if (renderableType) {
134 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
135 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
136
137 // Default to 8 bits per channel.
138 const EGLint tmpAttribs[] = {
139 EGL_RENDERABLE_TYPE,
140 renderableType,
141 EGL_RECORDABLE_ANDROID,
142 EGL_TRUE,
143 EGL_SURFACE_TYPE,
144 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
145 EGL_FRAMEBUFFER_TARGET_ANDROID,
146 EGL_TRUE,
147 EGL_RED_SIZE,
148 is1010102 ? 10 : 8,
149 EGL_GREEN_SIZE,
150 is1010102 ? 10 : 8,
151 EGL_BLUE_SIZE,
152 is1010102 ? 10 : 8,
153 EGL_ALPHA_SIZE,
154 is1010102 ? 2 : 8,
155 EGL_NONE,
156 };
157 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
158 std::back_inserter(attribs));
159 wantedAttribute = EGL_NONE;
160 wantedAttributeValue = EGL_NONE;
161 } else {
162 // if no renderable type specified, fallback to a simplified query
163 wantedAttribute = EGL_NATIVE_VISUAL_ID;
164 wantedAttributeValue = format;
165 }
166
167 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
168 config);
169 if (err == NO_ERROR) {
170 EGLint caveat;
171 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
172 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
173 }
174
175 return err;
176}
177
178std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
179 const RenderEngineCreationArgs& args) {
180 // initialize EGL for the default display
181 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
182 if (!eglInitialize(display, nullptr, nullptr)) {
183 LOG_ALWAYS_FATAL("failed to initialize EGL");
184 }
185
Yiwei Zhange2650962020-12-01 23:27:58 +0000186 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700187 if (!eglVersion) {
188 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000189 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700190 }
191
Yiwei Zhange2650962020-12-01 23:27:58 +0000192 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700193 if (!eglExtensions) {
194 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000195 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700196 }
197
198 auto& extensions = gl::GLExtensions::getInstance();
199 extensions.initWithEGLStrings(eglVersion, eglExtensions);
200
201 // The code assumes that ES2 or later is available if this extension is
202 // supported.
203 EGLConfig config = EGL_NO_CONFIG_KHR;
204 if (!extensions.hasNoConfigContext()) {
205 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
206 }
207
John Reck67b1e2b2020-08-26 13:17:24 -0700208 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800209 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700210 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800211 protectedContext =
212 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700213 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
214 }
215
Alec Mourid6f09462020-12-07 11:18:17 -0800216 EGLContext ctxt =
217 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700218
219 // if can't create a GL context, we can only abort.
220 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
221
222 EGLSurface placeholder = EGL_NO_SURFACE;
223 if (!extensions.hasSurfacelessContext()) {
224 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
225 Protection::UNPROTECTED);
226 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
227 }
228 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
229 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
230 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
231 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
232
233 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
234 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
235 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
236 Protection::PROTECTED);
237 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
238 "can't create protected placeholder pbuffer");
239 }
240
241 // initialize the renderer while GL is current
242 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000243 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
244 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700245
246 ALOGI("OpenGL ES informations:");
247 ALOGI("vendor : %s", extensions.getVendor());
248 ALOGI("renderer : %s", extensions.getRenderer());
249 ALOGI("version : %s", extensions.getVersion());
250 ALOGI("extensions: %s", extensions.getExtensions());
251 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
252 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
253
254 return engine;
255}
256
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700257std::future<void> SkiaGLRenderEngine::primeCache() {
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500258 Cache::primeShaderCache(this);
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700259 return {};
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500260}
261
John Reck67b1e2b2020-08-26 13:17:24 -0700262EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
263 status_t err;
264 EGLConfig config;
265
266 // First try to get an ES3 config
267 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
268 if (err != NO_ERROR) {
269 // If ES3 fails, try to get an ES2 config
270 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
271 if (err != NO_ERROR) {
272 // If ES2 still doesn't work, probably because we're on the emulator.
273 // try a simplified query
274 ALOGW("no suitable EGLConfig found, trying a simpler query");
275 err = selectEGLConfig(display, format, 0, &config);
276 if (err != NO_ERROR) {
277 // this EGL is too lame for android
278 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
279 }
280 }
281 }
282
283 if (logConfig) {
284 // print some debugging info
285 EGLint r, g, b, a;
286 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
287 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
288 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
289 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
290 ALOGI("EGL information:");
291 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
292 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
293 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
294 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
295 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
296 }
297
298 return config;
299}
300
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400301sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
302 // This "cache" does not actually cache anything. It just allows us to
303 // monitor Skia's internal cache. So this method always returns null.
304 return nullptr;
305}
306
307void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
308 const SkString& description) {
309 mShadersCachedSinceLastCall++;
310}
311
312void SkiaGLRenderEngine::assertShadersCompiled(int numShaders) {
313 const int cached = mSkSLCacheMonitor.shadersCachedSinceLastCall();
314 LOG_ALWAYS_FATAL_IF(cached != numShaders, "Attempted to cache %i shaders; cached %i",
315 numShaders, cached);
316}
317
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400318int SkiaGLRenderEngine::reportShadersCompiled() {
319 return mSkSLCacheMonitor.shadersCachedSinceLastCall();
320}
321
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700322SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000323 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700324 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800325 : SkiaRenderEngine(args.renderEngineType),
326 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700327 mEGLContext(ctxt),
328 mPlaceholderSurface(placeholder),
329 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700330 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400331 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800332 mUseColorManagement(args.useColorManagement) {
Brian Salomon40de6ba2022-03-22 19:38:53 +0000333 sk_sp<const GrGLInterface> glInterface = GrGLMakeNativeInterface();
John Reck67b1e2b2020-08-26 13:17:24 -0700334 LOG_ALWAYS_FATAL_IF(!glInterface.get());
335
336 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400337 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700338 options.fDisableDistanceFieldPaths = true;
Nathaniel Nifongf8d35e92021-06-08 15:02:25 -0400339 options.fReducedShaderVariations = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400340 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000341 mGrContext = GrDirectContext::MakeGL(glInterface, options);
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400342 if (supportsProtectedContent()) {
343 useProtectedContext(true);
Lucas Dupind508e472020-11-04 04:32:06 +0000344 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
345 useProtectedContext(false);
346 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700347
348 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500349 ALOGD("Background Blurs Enabled");
Robin Lee026680a2021-07-26 12:49:53 +0200350 mBlurFilter = new KawaseBlurFilter();
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700351 }
Alec Mouric0aae732021-01-12 13:32:18 -0800352 mCapture = std::make_unique<SkiaCapture>();
353}
354
355SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100356 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800357 if (mBlurFilter) {
358 delete mBlurFilter;
359 }
360
361 mCapture = nullptr;
362
363 mGrContext->flushAndSubmit(true);
364 mGrContext->abandonContext();
365
366 if (mProtectedGrContext) {
367 mProtectedGrContext->flushAndSubmit(true);
368 mProtectedGrContext->abandonContext();
369 }
370
371 if (mPlaceholderSurface != EGL_NO_SURFACE) {
372 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
373 }
374 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
375 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
376 }
377 if (mEGLContext != EGL_NO_CONTEXT) {
378 eglDestroyContext(mEGLDisplay, mEGLContext);
379 }
380 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
381 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
382 }
383 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
384 eglTerminate(mEGLDisplay);
385 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700386}
387
Lucas Dupind508e472020-11-04 04:32:06 +0000388bool SkiaGLRenderEngine::supportsProtectedContent() const {
389 return mProtectedEGLContext != EGL_NO_CONTEXT;
390}
391
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400392GrDirectContext* SkiaGLRenderEngine::getActiveGrContext() const {
393 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
394}
395
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400396void SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
397 if (useProtectedContext == mInProtectedContext ||
398 (useProtectedContext && !supportsProtectedContent())) {
399 return;
Lucas Dupind508e472020-11-04 04:32:06 +0000400 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400401
402 // release any scratch resources before switching into a new mode
403 if (getActiveGrContext()) {
404 getActiveGrContext()->purgeUnlockedResources(true);
405 }
406
Lucas Dupind508e472020-11-04 04:32:06 +0000407 const EGLSurface surface =
408 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
409 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
Alec Mouric0aae732021-01-12 13:32:18 -0800410
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400411 if (eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE) {
Lucas Dupind508e472020-11-04 04:32:06 +0000412 mInProtectedContext = useProtectedContext;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400413 // given that we are sharing the same thread between two GrContexts we need to
414 // make sure that the thread state is reset when switching between the two.
415 if (getActiveGrContext()) {
416 getActiveGrContext()->resetContext();
417 }
Lucas Dupind508e472020-11-04 04:32:06 +0000418 }
Lucas Dupind508e472020-11-04 04:32:06 +0000419}
420
John Reck67b1e2b2020-08-26 13:17:24 -0700421base::unique_fd SkiaGLRenderEngine::flush() {
422 ATRACE_CALL();
423 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
424 return base::unique_fd();
425 }
426
427 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
428 if (sync == EGL_NO_SYNC_KHR) {
429 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
430 return base::unique_fd();
431 }
432
433 // native fence fd will not be populated until flush() is done.
434 glFlush();
435
436 // get the fence fd
437 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
438 eglDestroySyncKHR(mEGLDisplay, sync);
439 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
440 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
441 }
442
443 return fenceFd;
444}
445
Alec Mouri4ee7b492021-08-11 10:36:55 -0700446void SkiaGLRenderEngine::waitFence(base::borrowed_fd fenceFd) {
447 if (fenceFd.get() >= 0 && !waitGpuFence(fenceFd)) {
448 ATRACE_NAME("SkiaGLRenderEngine::waitFence");
449 sync_wait(fenceFd.get(), -1);
450 }
451}
452
453bool SkiaGLRenderEngine::waitGpuFence(base::borrowed_fd fenceFd) {
John Reck67b1e2b2020-08-26 13:17:24 -0700454 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
455 !gl::GLExtensions::getInstance().hasWaitSync()) {
456 return false;
457 }
458
Alec Mouri4ee7b492021-08-11 10:36:55 -0700459 // Duplicate the fence for passing to eglCreateSyncKHR.
460 base::unique_fd fenceDup(dup(fenceFd.get()));
461 if (fenceDup.get() < 0) {
462 ALOGE("failed to create duplicate fence fd: %d", fenceDup.get());
463 return false;
464 }
465
John Reck67b1e2b2020-08-26 13:17:24 -0700466 // release the fd and transfer the ownership to EGLSync
Alec Mouri4ee7b492021-08-11 10:36:55 -0700467 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceDup.release(), EGL_NONE};
John Reck67b1e2b2020-08-26 13:17:24 -0700468 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
469 if (sync == EGL_NO_SYNC_KHR) {
470 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
471 return false;
472 }
473
474 // XXX: The spec draft is inconsistent as to whether this should return an
475 // EGLint or void. Ignore the return value for now, as it's not strictly
476 // needed.
477 eglWaitSyncKHR(mEGLDisplay, sync, 0);
478 EGLint error = eglGetError();
479 eglDestroySyncKHR(mEGLDisplay, sync);
480 if (error != EGL_SUCCESS) {
481 ALOGE("failed to wait for EGL native fence sync: %#x", error);
482 return false;
483 }
484
485 return true;
486}
487
Alec Mouri678245d2020-09-30 16:58:23 -0700488static float toDegrees(uint32_t transform) {
489 switch (transform) {
490 case ui::Transform::ROT_90:
491 return 90.0;
492 case ui::Transform::ROT_180:
493 return 180.0;
494 case ui::Transform::ROT_270:
495 return 270.0;
496 default:
497 return 0.0;
498 }
499}
500
Alec Mourib34f0b72020-10-02 13:18:34 -0700501static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
502 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
503 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
504 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
505 matrix[3][3], 0);
506}
507
Alec Mouri029d1952020-10-12 10:37:08 -0700508static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
509 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
510 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
511
512 // Treat unsupported dataspaces as srgb
513 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
514 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
515 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
516 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
517 }
518
519 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
520 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
521 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
522 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
523 }
524
525 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
526 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
527 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
528 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
529
530 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
531 sourceTransfer != destTransfer;
532}
533
Alec Mouria90a5702021-04-16 16:36:21 +0000534void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
535 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800536 // Only run this if RE is running on its own thread. This way the access to GL
537 // operations is guaranteed to be happening on the same thread.
538 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
539 return;
540 }
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400541 // We currently don't attempt to map a buffer if the buffer contains protected content
Derek Sollenberger45007182021-06-10 14:47:21 -0400542 // because GPU resources for protected buffers is much more limited.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400543 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Derek Sollenberger45007182021-06-10 14:47:21 -0400544 if (isProtectedBuffer) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400545 return;
546 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800547 ATRACE_CALL();
548
Derek Sollenberger45007182021-06-10 14:47:21 -0400549 // If we were to support caching protected buffers then we will need to switch the
550 // currently bound context if we are not already using the protected context (and subsequently
551 // switch back after the buffer is cached). However, for non-protected content we can bind
552 // the texture in either GL context because they are initialized with the same share_context
553 // which allows the texture state to be shared between them.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400554 auto grContext = getActiveGrContext();
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400555 auto& cache = mTextureCache;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400556
557 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000558 mGraphicBufferExternalRefs[buffer->getId()]++;
559
560 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800561 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400562 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400563 buffer->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400564 isRenderable, mTextureCleanupMgr);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400565 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800566 }
567}
568
Alec Mouria90a5702021-04-16 16:36:21 +0000569void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800570 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700571 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000572 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
573 iter != mGraphicBufferExternalRefs.end()) {
574 if (iter->second == 0) {
575 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
576 "> from RenderEngine texture, but the "
577 "ref count was already zero!",
578 buffer->getId());
579 mGraphicBufferExternalRefs.erase(buffer->getId());
580 return;
581 }
582
583 iter->second--;
584
Alec Mouric2ffeb42021-06-17 17:42:27 -0700585 // Swap contexts if needed prior to deleting this buffer
586 // See Issue 1 of
587 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
588 // when a protected context and an unprotected context are part of the same share group,
589 // protected surfaces may not be accessed by an unprotected context, implying that protected
590 // surfaces may only be freed when a protected context is active.
591 const bool inProtected = mInProtectedContext;
592 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
593
Alec Mouria90a5702021-04-16 16:36:21 +0000594 if (iter->second == 0) {
595 mTextureCache.erase(buffer->getId());
Alec Mouria90a5702021-04-16 16:36:21 +0000596 mGraphicBufferExternalRefs.erase(buffer->getId());
597 }
Alec Mouric2ffeb42021-06-17 17:42:27 -0700598
599 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
600 // are up-to-date.
601 if (inProtected != mInProtectedContext) {
602 useProtectedContext(inProtected);
603 }
Alec Mouria90a5702021-04-16 16:36:21 +0000604 }
John Reck67b1e2b2020-08-26 13:17:24 -0700605}
606
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400607bool SkiaGLRenderEngine::canSkipPostRenderCleanup() const {
608 std::lock_guard<std::mutex> lock(mRenderingMutex);
609 return mTextureCleanupMgr.isEmpty();
610}
611
612void SkiaGLRenderEngine::cleanupPostRender() {
613 ATRACE_CALL();
614 std::lock_guard<std::mutex> lock(mRenderingMutex);
615 mTextureCleanupMgr.cleanup();
616}
617
618// Helper class intended to be used on the stack to ensure that texture cleanup
619// is deferred until after this class goes out of scope.
620class DeferTextureCleanup final {
621public:
622 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
623 mMgr.setDeferredStatus(true);
624 }
625 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
626
627private:
628 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
629 AutoBackendTexture::CleanupManager& mMgr;
630};
631
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700632sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
633 const RuntimeEffectShaderParameters& parameters) {
Nader Jawad63644d32021-05-07 10:44:21 -0700634 // The given surface will be stretched by HWUI via matrix transformation
635 // which gets similar results for most surfaces
636 // Determine later on if we need to leverage the stertch shader within
637 // surface flinger
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700638 const auto& stretchEffect = parameters.layer.stretchEffect;
639 auto shader = parameters.shader;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700640 if (stretchEffect.hasEffect()) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700641 const auto targetBuffer = parameters.layer.source.buffer.buffer;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700642 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700643 if (graphicBuffer && parameters.shader) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700644 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
645 }
John Reckcdb4ed72021-02-04 13:39:33 -0500646 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700647
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700648 if (parameters.requiresLinearEffect) {
649 const ui::Dataspace inputDataspace = mUseColorManagement ? parameters.layer.sourceDataspace
650 : ui::Dataspace::V0_SRGB_LINEAR;
651 const ui::Dataspace outputDataspace = mUseColorManagement
652 ? parameters.display.outputDataspace
653 : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500654
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700655 auto effect =
656 shaders::LinearEffect{.inputDataspace = inputDataspace,
657 .outputDataspace = outputDataspace,
658 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha};
Ana Krulec47814212021-01-06 19:00:10 -0800659
660 auto effectIter = mRuntimeEffects.find(effect);
661 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
662 if (effectIter == mRuntimeEffects.end()) {
663 runtimeEffect = buildRuntimeEffect(effect);
664 mRuntimeEffects.insert({effect, runtimeEffect});
665 } else {
666 runtimeEffect = effectIter->second;
667 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700668 mat4 colorTransform = parameters.layer.colorTransform;
669
670 colorTransform *=
671 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
672 parameters.layerDimmingRatio, 1.f));
Alec Mouri1a3c5452022-03-04 22:44:51 +0000673 const auto targetBuffer = parameters.layer.source.buffer.buffer;
674 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
675 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700676 return createLinearEffectShader(parameters.shader, effect, runtimeEffect, colorTransform,
677 parameters.display.maxLuminance,
Alec Mourib21d94e2022-01-13 17:44:10 -0800678 parameters.display.currentLuminanceNits,
Alec Mouri1a3c5452022-03-04 22:44:51 +0000679 parameters.layer.source.buffer.maxLuminanceNits,
680 hardwareBuffer);
Ana Krulec47814212021-01-06 19:00:10 -0800681 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700682 return parameters.shader;
Ana Krulec47814212021-01-06 19:00:10 -0800683}
684
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500685void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500686 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500687 // Record display settings when capture is running.
688 std::stringstream displaySettings;
689 PrintTo(display, &displaySettings);
690 // Store the DisplaySettings in additional information.
691 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
692 SkData::MakeWithCString(displaySettings.str().c_str()));
693 }
694
695 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
696 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
697 // displays might have different scaling when compared to the physical screen.
698
699 canvas->clipRect(getSkRect(display.physicalDisplay));
700 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
701
702 const auto clipWidth = display.clip.width();
703 const auto clipHeight = display.clip.height();
704 auto rotatedClipWidth = clipWidth;
705 auto rotatedClipHeight = clipHeight;
706 // Scale is contingent on the rotation result.
707 if (display.orientation & ui::Transform::ROT_90) {
708 std::swap(rotatedClipWidth, rotatedClipHeight);
709 }
710 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
711 static_cast<SkScalar>(rotatedClipWidth);
712 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
713 static_cast<SkScalar>(rotatedClipHeight);
714 canvas->scale(scaleX, scaleY);
715
716 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
717 // back so that the top left corner of the clip is at (0, 0).
718 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
719 canvas->rotate(toDegrees(display.orientation));
720 canvas->translate(-clipWidth / 2, -clipHeight / 2);
721 canvas->translate(-display.clip.left, -display.clip.top);
722}
723
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500724class AutoSaveRestore {
725public:
726 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
727 ~AutoSaveRestore() { restore(); }
728 void replace(SkCanvas* canvas) {
729 mCanvas = canvas;
730 mSaveCount = canvas->save();
731 }
732 void restore() {
733 if (mCanvas) {
734 mCanvas->restoreToCount(mSaveCount);
735 mCanvas = nullptr;
736 }
737 }
738
739private:
740 SkCanvas* mCanvas;
741 int mSaveCount;
742};
743
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400744static SkRRect getBlurRRect(const BlurRegion& region) {
745 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
746 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
747 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
748 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
749 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
750 SkRRect roundedRect;
751 roundedRect.setRectRadii(rect, radii);
752 return roundedRect;
753}
754
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700755static bool equalsWithinMargin(float expected, float value, float margin) {
756 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
757 return std::abs(expected - value) < margin;
758}
759
Sally Qi4cabdd02021-08-05 16:45:57 -0700760void SkiaGLRenderEngine::drawLayersInternal(
761 const std::shared_ptr<std::promise<RenderEngineResult>>&& resultPromise,
Sally Qi59a9f502021-10-12 18:53:23 +0000762 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
Sally Qi4cabdd02021-08-05 16:45:57 -0700763 const std::shared_ptr<ExternalTexture>& buffer, const bool /*useFramebufferCache*/,
764 base::unique_fd&& bufferFence) {
John Reck67b1e2b2020-08-26 13:17:24 -0700765 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800766
John Reck67b1e2b2020-08-26 13:17:24 -0700767 std::lock_guard<std::mutex> lock(mRenderingMutex);
768 if (layers.empty()) {
769 ALOGV("Drawing empty layer stack");
Sally Qi4cabdd02021-08-05 16:45:57 -0700770 resultPromise->set_value({NO_ERROR, base::unique_fd()});
771 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700772 }
773
John Reck67b1e2b2020-08-26 13:17:24 -0700774 if (buffer == nullptr) {
775 ALOGE("No output buffer provided. Aborting GPU composition.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700776 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
777 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700778 }
779
Alec Mouria90a5702021-04-16 16:36:21 +0000780 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800781
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400782 auto grContext = getActiveGrContext();
Derek Sollenberger45007182021-06-10 14:47:21 -0400783 auto& cache = mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700784
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400785 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
786 DeferTextureCleanup dtc(mTextureCleanupMgr);
787
Alec Mouria90a5702021-04-16 16:36:21 +0000788 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
789 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
790 surfaceTextureRef = it->second;
791 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400792 surfaceTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400793 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
794 buffer->getBuffer()
795 ->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400796 true, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -0700797 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800798
Alec Mouri4ee7b492021-08-11 10:36:55 -0700799 // wait on the buffer to be ready to use prior to using it
800 waitFence(bufferFence);
801
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500802 const ui::Dataspace dstDataspace =
Alec Mourid2bcbae2021-06-28 17:02:17 -0700803 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400804 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700805
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500806 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
807 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800808 ALOGE("Cannot acquire canvas from Skia.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700809 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
810 return;
Ana Krulec6eab17a2020-12-09 15:52:36 -0800811 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500812
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400813 // setup color filter if necessary
814 sk_sp<SkColorFilter> displayColorTransform;
Leon Scroggins III745dcaa2022-01-26 11:55:58 -0500815 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400816 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
817 }
818 const bool ctModifiesAlpha =
819 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
820
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700821 // Find the max layer white point to determine the max luminance of the scene...
822 const float maxLayerWhitePoint = std::transform_reduce(
823 layers.cbegin(), layers.cend(), 0.f,
824 [](float left, float right) { return std::max(left, right); },
825 [&](const auto& l) { return l.whitePointNits; });
826
827 // ...and compute the dimming ratio if dimming is requested
828 const float displayDimmingRatio = display.targetLuminanceNits > 0.f &&
829 maxLayerWhitePoint > 0.f && display.targetLuminanceNits > maxLayerWhitePoint
830 ? maxLayerWhitePoint / display.targetLuminanceNits
831 : 1.f;
832
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500833 // Find if any layers have requested blur, we'll use that info to decide when to render to an
834 // offscreen buffer and when to render to the native buffer.
835 sk_sp<SkSurface> activeSurface(dstSurface);
836 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500837 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500838 const LayerSettings* blurCompositionLayer = nullptr;
839 if (mBlurFilter) {
840 bool requiresCompositionLayer = false;
841 for (const auto& layer : layers) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400842 // if the layer doesn't have blur or it is not visible then continue
843 if (!layerHasBlur(layer, ctModifiesAlpha)) {
844 continue;
845 }
Sally Qi59a9f502021-10-12 18:53:23 +0000846 if (layer.backgroundBlurRadius > 0 &&
Robin Lee26dacab2021-08-09 14:31:01 +0200847 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500848 requiresCompositionLayer = true;
849 }
Sally Qi59a9f502021-10-12 18:53:23 +0000850 for (auto region : layer.blurRegions) {
Robin Lee26dacab2021-08-09 14:31:01 +0200851 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500852 requiresCompositionLayer = true;
853 }
854 }
855 if (requiresCompositionLayer) {
856 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500857 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Sally Qi59a9f502021-10-12 18:53:23 +0000858 blurCompositionLayer = &layer;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500859 break;
860 }
861 }
862 }
863
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500864 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700865 // Clear the entire canvas with a transparent black to prevent ghost images.
866 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500867 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800868
John Reck67b1e2b2020-08-26 13:17:24 -0700869 for (const auto& layer : layers) {
Sally Qi59a9f502021-10-12 18:53:23 +0000870 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
Galia Peychevaf7889b32020-11-25 22:22:40 +0100871
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400872 if (kPrintLayerSettings) {
873 std::stringstream ls;
Sally Qi59a9f502021-10-12 18:53:23 +0000874 PrintTo(layer, &ls);
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400875 auto debugs = ls.str();
876 int pos = 0;
877 while (pos < debugs.size()) {
878 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
879 pos += 1000;
880 }
881 }
882
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500883 sk_sp<SkImage> blurInput;
Sally Qi59a9f502021-10-12 18:53:23 +0000884 if (blurCompositionLayer == &layer) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500885 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
886 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
887
888 // save a snapshot of the activeSurface to use as input to the blur shaders
889 blurInput = activeSurface->makeImageSnapshot();
890
891 // TODO we could skip this step if we know the blur will cover the entire image
892 // blit the offscreen framebuffer into the destination AHB
893 SkPaint paint;
894 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500895 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
896 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
897 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
898 String8::format("SurfaceID|%" PRId64, id).c_str(),
899 nullptr);
900 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
901 } else {
902 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
903 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500904
905 // assign dstCanvas to canvas and ensure that the canvas state is up to date
906 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500907 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500908 initCanvas(canvas, display);
909
910 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
911 dstSurface->getCanvas()->getSaveCount());
912 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
913 dstSurface->getCanvas()->getTotalMatrix());
914
915 // assign dstSurface to activeSurface
916 activeSurface = dstSurface;
917 }
918
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500919 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500920 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800921 // Record the name of the layer if the capture is running.
922 std::stringstream layerSettings;
Sally Qi59a9f502021-10-12 18:53:23 +0000923 PrintTo(layer, &layerSettings);
Ana Krulec6eab17a2020-12-09 15:52:36 -0800924 // Store the LayerSettings in additional information.
Sally Qi59a9f502021-10-12 18:53:23 +0000925 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
Ana Krulec6eab17a2020-12-09 15:52:36 -0800926 SkData::MakeWithCString(layerSettings.str().c_str()));
927 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100928 // Layers have a local transform that should be applied to them
Sally Qi59a9f502021-10-12 18:53:23 +0000929 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100930
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400931 const auto [bounds, roundRectClip] =
Sally Qi59a9f502021-10-12 18:53:23 +0000932 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
933 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400934 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500935 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
936
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500937 // if multiple layers have blur, then we need to take a snapshot now because
938 // only the lowest layer will have blurImage populated earlier
939 if (!blurInput) {
940 blurInput = activeSurface->makeImageSnapshot();
941 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500942 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400943 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
944
945 // if the clip needs to be applied then apply it now and make sure
946 // it is restored before we attempt to draw any shadows.
947 SkAutoCanvasRestore acr(canvas, true);
948 if (!roundRectClip.isEmpty()) {
949 canvas->clipRRect(roundRectClip, true);
950 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500951
Galia Peychevae425ac82021-03-15 17:12:03 +0100952 // TODO(b/182216890): Filter out empty layers earlier
953 if (blurRect.width() > 0 && blurRect.height() > 0) {
Sally Qi59a9f502021-10-12 18:53:23 +0000954 if (layer.backgroundBlurRadius > 0) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100955 ATRACE_NAME("BackgroundBlur");
Sally Qi59a9f502021-10-12 18:53:23 +0000956 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
957 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100958
Sally Qi59a9f502021-10-12 18:53:23 +0000959 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500960
Sally Qi59a9f502021-10-12 18:53:23 +0000961 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400962 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700963 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400964
Sally Qi59a9f502021-10-12 18:53:23 +0000965 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
966 for (auto region : layer.blurRegions) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100967 if (cachedBlurs[region.blurRadius] == nullptr) {
968 ATRACE_NAME("BlurRegion");
969 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400970 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100971 blurRect);
972 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500973
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400974 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
975 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100976 cachedBlurs[region.blurRadius], blurInput);
977 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700978 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700979 }
980
Sally Qi59a9f502021-10-12 18:53:23 +0000981 if (layer.shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400982 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
Sally Qi59a9f502021-10-12 18:53:23 +0000983 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
Leon Scroggins III63e86952021-05-12 10:45:08 -0400984
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400985 SkRRect shadowBounds, shadowClip;
Sally Qi59a9f502021-10-12 18:53:23 +0000986 if (layer.geometry.boundaries == layer.shadow.boundaries) {
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400987 shadowBounds = bounds;
988 shadowClip = roundRectClip;
989 } else {
990 std::tie(shadowBounds, shadowClip) =
Sally Qi59a9f502021-10-12 18:53:23 +0000991 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
992 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400993 }
994
Leon Scroggins III63e86952021-05-12 10:45:08 -0400995 // Technically, if bounds is a rect and roundRectClip is not empty,
996 // it means that the bounds and roundedCornersCrop were different
997 // enough that we should intersect them to find the proper shadow.
998 // In practice, this often happens when the two rectangles appear to
999 // not match due to rounding errors. Draw the rounded version, which
1000 // looks more like the intent.
1001 const auto& rrect =
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001002 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
Sally Qi59a9f502021-10-12 18:53:23 +00001003 drawShadow(canvas, rrect, layer.shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001004 }
1005
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001006 const float layerDimmingRatio = layer.whitePointNits <= 0.f
1007 ? displayDimmingRatio
1008 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
1009
Sally Qi59a9f502021-10-12 18:53:23 +00001010 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001011 (mUseColorManagement &&
Sally Qi59a9f502021-10-12 18:53:23 +00001012 needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001013 !equalsWithinMargin(1.f, layerDimmingRatio, 0.001f);
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001014
1015 // quick abort from drawing the remaining portion of the layer
Sally Qi59a9f502021-10-12 18:53:23 +00001016 if (layer.skipContentDraw ||
1017 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001018 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001019 continue;
1020 }
1021
1022 // If we need to map to linear space or color management is disabled, then mark the source
1023 // image with the same colorspace as the destination surface so that Skia's color
1024 // management is a no-op.
1025 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
1026 ? dstDataspace
Sally Qi59a9f502021-10-12 18:53:23 +00001027 : layer.sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -08001028
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001029 SkPaint paint;
Sally Qi59a9f502021-10-12 18:53:23 +00001030 if (layer.source.buffer.buffer) {
John Reck67b1e2b2020-08-26 13:17:24 -07001031 ATRACE_NAME("DrawImage");
Sally Qi59a9f502021-10-12 18:53:23 +00001032 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
1033 const auto& item = layer.source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001034 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +00001035
1036 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
1037 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001038 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -07001039 } else {
Alec Mouria90a5702021-04-16 16:36:21 +00001040 // If we didn't find the image in the cache, then create a local ref but don't cache
1041 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
1042 // we didn't find anything in the cache then we intentionally did not cache this
1043 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001044 imageTextureRef = std::make_shared<
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001045 AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001046 item.buffer->getBuffer()->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -04001047 false, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -07001048 }
Alec Mouri1a4d0642020-11-13 17:42:01 -08001049
Alec Mouri4ee7b492021-08-11 10:36:55 -07001050 // if the layer's buffer has a fence, then we must must respect the fence prior to using
1051 // the buffer.
Sally Qi59a9f502021-10-12 18:53:23 +00001052 if (layer.source.buffer.fence != nullptr) {
1053 waitFence(layer.source.buffer.fence->get());
Alec Mouri4ee7b492021-08-11 10:36:55 -07001054 }
1055
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001056 // isOpaque means we need to ignore the alpha in the image,
1057 // replacing it with the alpha specified by the LayerSettings. See
1058 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
1059 // The proper way to do this is to use an SkColorType that ignores
1060 // alpha, like kRGB_888x_SkColorType, and that is used if the
1061 // incoming image is kRGBA_8888_SkColorType. However, the incoming
1062 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
1063 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
1064 // kRGB_101010x_SkColorType, but it is not yet supported as a source
1065 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
1066 // meantime, we'll use a workaround that works unless we need to do
1067 // any color conversion. The workaround requires that we pretend the
1068 // image is already premultiplied, so that we do not premultiply it
1069 // before applying SkBlendMode::kPlus.
1070 const bool useIsOpaqueWorkaround = item.isOpaque &&
1071 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
1072 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
1073 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
1074 : item.isOpaque ? kOpaque_SkAlphaType
1075 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
1076 : kUnpremul_SkAlphaType;
1077 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -07001078
1079 auto texMatrix = getSkM44(item.textureTransform).asM33();
1080 // textureTansform was intended to be passed directly into a shader, so when
1081 // building the total matrix with the textureTransform we need to first
1082 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001083 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001084 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -07001085
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001086 SkMatrix matrix;
1087 if (!texMatrix.invert(&matrix)) {
1088 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -07001089 }
Ana Krulecf9a15d92020-12-11 08:35:00 -08001090 // The shader does not respect the translation, so we add it to the texture
1091 // transform for the SkImage. This will make sure that the correct layer contents
1092 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001093 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -07001094
Ana Krulecb7b28b22020-11-23 14:48:58 -08001095 sk_sp<SkShader> shader;
1096
Sally Qi59a9f502021-10-12 18:53:23 +00001097 if (layer.source.buffer.useTextureFiltering) {
Ana Krulecb7b28b22020-11-23 14:48:58 -08001098 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1099 SkSamplingOptions(
1100 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1101 &matrix);
1102 } else {
Mike Reed711e1f02020-12-11 13:06:19 -05001103 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -08001104 }
Alec Mouri029d1952020-10-12 10:37:08 -07001105
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001106 if (useIsOpaqueWorkaround) {
Alec Mouric0aae732021-01-12 13:32:18 -08001107 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1108 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001109 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001110 }
1111
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001112 paint.setShader(createRuntimeEffectShader(
1113 RuntimeEffectShaderParameters{.shader = shader,
1114 .layer = layer,
1115 .display = display,
1116 .undoPremultipliedAlpha = !item.isOpaque &&
1117 item.usePremultipliedAlpha,
1118 .requiresLinearEffect = requiresLinearEffect,
1119 .layerDimmingRatio = layerDimmingRatio}));
1120
1121 // Turn on dithering when dimming beyond this threshold.
1122 static constexpr float kDimmingThreshold = 0.2f;
1123 if (layerDimmingRatio <= kDimmingThreshold) {
1124 paint.setDither(true);
1125 }
Sally Qi59a9f502021-10-12 18:53:23 +00001126 paint.setAlphaf(layer.alpha);
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001127
1128 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1129 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001130
1131 // SysUI creates the alpha layer as a coverage layer, which is
1132 // appropriate for the DPU. Use a color matrix to convert it to
1133 // a mask.
1134 // TODO (b/219525258): Handle input as a mask.
1135 //
1136 // The color matrix will convert A8 pixels with no alpha to
1137 // black, as described by this vector. If the display handles
1138 // the color transform, we need to invert it to find the color
1139 // that will result in black after the DPU applies the transform.
1140 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1141 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1142 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1143 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1144 black = colorSpaceMatrix * black;
1145 } else {
1146 // We'll just have to use 0,0,0 as black, which should
1147 // be close to correct.
1148 ALOGI("Could not invert colorTransform!");
1149 }
1150 }
1151 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1152 0, 0, 0, 0, black[1],
1153 0, 0, 0, 0, black[2],
1154 0, 0, 0, -1, 1);
1155 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1156 // On the other hand, if the device doesn't handle it, we
1157 // have to apply it ourselves.
1158 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1159 }
1160 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001161 }
John Reck67b1e2b2020-08-26 13:17:24 -07001162 } else {
1163 ATRACE_NAME("DrawColor");
Sally Qi59a9f502021-10-12 18:53:23 +00001164 const auto color = layer.source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001165 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1166 .fG = color.g,
1167 .fB = color.b,
Sally Qi59a9f502021-10-12 18:53:23 +00001168 .fA = layer.alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001169 toSkColorSpace(layerDataspace));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001170 paint.setShader(createRuntimeEffectShader(
1171 RuntimeEffectShaderParameters{.shader = shader,
1172 .layer = layer,
1173 .display = display,
1174 .undoPremultipliedAlpha = false,
1175 .requiresLinearEffect = requiresLinearEffect,
1176 .layerDimmingRatio = layerDimmingRatio}));
John Reck67b1e2b2020-08-26 13:17:24 -07001177 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001178
Sally Qi59a9f502021-10-12 18:53:23 +00001179 if (layer.disableBlending) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001180 paint.setBlendMode(SkBlendMode::kSrc);
1181 }
1182
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001183 // An A8 buffer will already have the proper color filter attached to
1184 // its paint, including the displayColorTransform as needed.
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001185 if (!paint.getColorFilter()) {
1186 paint.setColorFilter(displayColorTransform);
1187 }
Alec Mourib34f0b72020-10-02 13:18:34 -07001188
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001189 if (!roundRectClip.isEmpty()) {
1190 canvas->clipRRect(roundRectClip, true);
1191 }
1192
1193 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001194 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001195 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001196 } else {
Nader Jawad63644d32021-05-07 10:44:21 -07001197 canvas->drawRect(bounds.rect(), paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -07001198 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001199 if (kFlushAfterEveryLayer) {
1200 ATRACE_NAME("flush surface");
1201 activeSurface->flush();
1202 }
John Reck67b1e2b2020-08-26 13:17:24 -07001203 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001204 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001205 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001206 {
1207 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001208 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1209 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001210 }
1211
Sally Qi4cabdd02021-08-05 16:45:57 -07001212 base::unique_fd drawFence = flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001213
1214 // If flush failed or we don't support native fences, we need to force the
1215 // gl command stream to be executed.
Sally Qi4cabdd02021-08-05 16:45:57 -07001216 bool requireSync = drawFence.get() < 0;
John Reck67b1e2b2020-08-26 13:17:24 -07001217 if (requireSync) {
1218 ATRACE_BEGIN("Submit(sync=true)");
1219 } else {
1220 ATRACE_BEGIN("Submit(sync=false)");
1221 }
Lucas Dupind508e472020-11-04 04:32:06 +00001222 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001223 ATRACE_END();
1224 if (!success) {
1225 ALOGE("Failed to flush RenderEngine commands");
1226 // Chances are, something illegal happened (either the caller passed
1227 // us bad parameters, or we messed up our shader generation).
Sally Qi4cabdd02021-08-05 16:45:57 -07001228 resultPromise->set_value({INVALID_OPERATION, std::move(drawFence)});
1229 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001230 }
1231
1232 // checkErrors();
Sally Qi4cabdd02021-08-05 16:45:57 -07001233 resultPromise->set_value({NO_ERROR, std::move(drawFence)});
1234 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001235}
1236
Lucas Dupin3f11e922020-09-22 17:31:04 -07001237inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1238 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1239}
1240
1241inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1242 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1243}
1244
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001245/**
1246 * Verifies that common, simple bounds + clip combinations can be converted into
1247 * a single RRect draw call returning true if possible. If true the radii parameter
1248 * will be filled with the correct radii values that combined with bounds param will
1249 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
1250 */
1251static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
1252 const SkRect& insetCrop, float cornerRadius,
1253 SkVector radii[4]) {
1254 const bool leftEqual = bounds.fLeft == crop.fLeft;
1255 const bool topEqual = bounds.fTop == crop.fTop;
1256 const bool rightEqual = bounds.fRight == crop.fRight;
1257 const bool bottomEqual = bounds.fBottom == crop.fBottom;
1258
1259 // In the event that the corners of the bounds only partially align with the crop we
1260 // need to ensure that the resulting shape can still be represented as a round rect.
1261 // In particular the round rect implementation will scale the value of all corner radii
1262 // if the sum of the radius along any edge is greater than the length of that edge.
1263 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
1264 const bool requiredWidth = bounds.width() > (cornerRadius * 2);
1265 const bool requiredHeight = bounds.height() > (cornerRadius * 2);
1266 if (!requiredWidth || !requiredHeight) {
1267 return false;
1268 }
1269
1270 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
1271 // contained within the cropped shape and does not need rounded.
1272 // compute the UpperLeft corner radius
1273 if (leftEqual && topEqual) {
1274 radii[0].set(cornerRadius, cornerRadius);
1275 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
1276 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
1277 radii[0].set(0, 0);
1278 } else {
1279 return false;
1280 }
1281 // compute the UpperRight corner radius
1282 if (rightEqual && topEqual) {
1283 radii[1].set(cornerRadius, cornerRadius);
1284 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
1285 (topEqual && bounds.fRight <= insetCrop.fRight)) {
1286 radii[1].set(0, 0);
1287 } else {
1288 return false;
1289 }
1290 // compute the BottomRight corner radius
1291 if (rightEqual && bottomEqual) {
1292 radii[2].set(cornerRadius, cornerRadius);
1293 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
1294 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
1295 radii[2].set(0, 0);
1296 } else {
1297 return false;
1298 }
1299 // compute the BottomLeft corner radius
1300 if (leftEqual && bottomEqual) {
1301 radii[3].set(cornerRadius, cornerRadius);
1302 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
1303 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
1304 radii[3].set(0, 0);
1305 } else {
1306 return false;
1307 }
1308
1309 return true;
1310}
1311
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001312inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(const FloatRect& boundsRect,
1313 const FloatRect& cropRect,
1314 const float cornerRadius) {
1315 const SkRect bounds = getSkRect(boundsRect);
1316 const SkRect crop = getSkRect(cropRect);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001317
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001318 SkRRect clip;
1319 if (cornerRadius > 0) {
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001320 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
1321 if (bounds == crop || crop.isEmpty()) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001322 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1323 }
1324
1325 // This makes an effort to speed up common, simple bounds + clip combinations by
1326 // converting them to a single RRect draw. It is possible there are other cases
1327 // that can be converted.
1328 if (crop.contains(bounds)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001329 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001330 if (insetCrop.contains(bounds)) {
1331 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001332 }
1333
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001334 SkVector radii[4];
1335 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001336 SkRRect intersectionBounds;
1337 intersectionBounds.setRectRadii(bounds, radii);
1338 return {intersectionBounds, clip};
1339 }
1340 }
1341
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001342 // we didn't hit any of our fast paths so set the clip to the cropRect
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001343 clip.setRectXY(crop, cornerRadius, cornerRadius);
1344 }
1345
1346 // if we hit this point then we either don't have rounded corners or we are going to rely
1347 // on the clip to round the corners for us
1348 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001349}
1350
Sally Qi59a9f502021-10-12 18:53:23 +00001351inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings& layer,
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001352 bool colorTransformModifiesAlpha) {
Sally Qi59a9f502021-10-12 18:53:23 +00001353 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001354 // return false if the content is opaque and would therefore occlude the blur
Sally Qi59a9f502021-10-12 18:53:23 +00001355 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
1356 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
1357 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001358 }
1359 return false;
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001360}
1361
Lucas Dupin3f11e922020-09-22 17:31:04 -07001362inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1363 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1364}
1365
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001366inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1367 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1368 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1369 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1370 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1371}
1372
Lucas Dupin3f11e922020-09-22 17:31:04 -07001373inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1374 return SkPoint3::Make(vector.x, vector.y, vector.z);
1375}
1376
John Reck67b1e2b2020-08-26 13:17:24 -07001377size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1378 return mGrContext->maxTextureSize();
1379}
1380
1381size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1382 return mGrContext->maxRenderTargetSize();
1383}
1384
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001385void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001386 const ShadowSettings& settings) {
1387 ATRACE_CALL();
1388 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001389 const auto flags =
1390 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1391
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001392 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001393 getSkPoint3(settings.lightPos), settings.lightRadius,
1394 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1395 flags);
1396}
1397
John Reck67b1e2b2020-08-26 13:17:24 -07001398EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001399 EGLContext shareContext,
1400 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001401 Protection protection) {
1402 EGLint renderableType = 0;
1403 if (config == EGL_NO_CONFIG_KHR) {
1404 renderableType = EGL_OPENGL_ES3_BIT;
1405 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1406 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1407 }
1408 EGLint contextClientVersion = 0;
1409 if (renderableType & EGL_OPENGL_ES3_BIT) {
1410 contextClientVersion = 3;
1411 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1412 contextClientVersion = 2;
1413 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1414 contextClientVersion = 1;
1415 } else {
1416 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1417 }
1418
1419 std::vector<EGLint> contextAttributes;
1420 contextAttributes.reserve(7);
1421 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1422 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001423 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001424 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001425 switch (*contextPriority) {
1426 case ContextPriority::REALTIME:
1427 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1428 break;
1429 case ContextPriority::MEDIUM:
1430 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1431 break;
1432 case ContextPriority::LOW:
1433 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1434 break;
1435 case ContextPriority::HIGH:
1436 default:
1437 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1438 break;
1439 }
John Reck67b1e2b2020-08-26 13:17:24 -07001440 }
1441 if (protection == Protection::PROTECTED) {
1442 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1443 contextAttributes.push_back(EGL_TRUE);
1444 }
1445 contextAttributes.push_back(EGL_NONE);
1446
1447 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1448
1449 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1450 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1451 // EGL_NO_CONTEXT so that we can abort.
1452 if (config != EGL_NO_CONFIG_KHR) {
1453 return context;
1454 }
1455 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1456 // should try to fall back to GLES 2.
1457 contextAttributes[1] = 2;
1458 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1459 }
1460
1461 return context;
1462}
1463
Alec Mourid6f09462020-12-07 11:18:17 -08001464std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1465 const RenderEngineCreationArgs& args) {
1466 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1467 return std::nullopt;
1468 }
1469
1470 switch (args.contextPriority) {
1471 case RenderEngine::ContextPriority::REALTIME:
1472 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1473 return RenderEngine::ContextPriority::REALTIME;
1474 } else {
1475 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1476 return RenderEngine::ContextPriority::HIGH;
1477 }
1478 case RenderEngine::ContextPriority::HIGH:
1479 case RenderEngine::ContextPriority::MEDIUM:
1480 case RenderEngine::ContextPriority::LOW:
1481 return args.contextPriority;
1482 default:
1483 return std::nullopt;
1484 }
1485}
1486
John Reck67b1e2b2020-08-26 13:17:24 -07001487EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1488 EGLConfig config, int hwcFormat,
1489 Protection protection) {
1490 EGLConfig placeholderConfig = config;
1491 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1492 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1493 }
1494 std::vector<EGLint> attributes;
1495 attributes.reserve(7);
1496 attributes.push_back(EGL_WIDTH);
1497 attributes.push_back(1);
1498 attributes.push_back(EGL_HEIGHT);
1499 attributes.push_back(1);
1500 if (protection == Protection::PROTECTED) {
1501 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1502 attributes.push_back(EGL_TRUE);
1503 }
1504 attributes.push_back(EGL_NONE);
1505
1506 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1507}
1508
Alec Mourid6f09462020-12-07 11:18:17 -08001509int SkiaGLRenderEngine::getContextPriority() {
1510 int value;
1511 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1512 return value;
1513}
1514
Ady Abrahamed3290f2021-05-17 15:12:14 -07001515void SkiaGLRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001516 // This cache multiplier was selected based on review of cache sizes relative
1517 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1518 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1519 // conservative default based on that analysis.
1520 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1521 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1522
1523 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001524 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001525
1526 // if it is possible to switch contexts then we will resize the other context
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001527 const bool originalProtectedState = mInProtectedContext;
1528 useProtectedContext(!mInProtectedContext);
1529 if (mInProtectedContext != originalProtectedState) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001530 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001531 // reset back to the initial context that was active when this method was called
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001532 useProtectedContext(originalProtectedState);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001533 }
1534}
1535
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001536void SkiaGLRenderEngine::dump(std::string& result) {
1537 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1538
1539 StringAppendF(&result, "\n ------------RE-----------------\n");
1540 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1541 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1542 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1543 extensions.getVersion());
1544 StringAppendF(&result, "%s\n", extensions.getExtensions());
1545 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1546 supportsProtectedContent());
1547 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001548 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1549 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001550
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001551 std::vector<ResourcePair> cpuResourceMap = {
1552 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1553 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1554 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1555 {"skia/sk_resource_cache/tessellated", "Shadows"},
1556 {"skia", "Other"},
1557 };
1558 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1559 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1560 StringAppendF(&result, "Skia CPU Caches: ");
1561 cpuReporter.logTotals(result);
1562 cpuReporter.logOutput(result);
1563
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001564 {
1565 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001566
1567 std::vector<ResourcePair> gpuResourceMap = {
1568 {"texture_renderbuffer", "Texture/RenderBuffer"},
1569 {"texture", "Texture"},
1570 {"gr_text_blob_cache", "Text"},
1571 {"skia", "Other"},
1572 };
1573 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1574 mGrContext->dumpMemoryStatistics(&gpuReporter);
1575 StringAppendF(&result, "Skia's GPU Caches: ");
1576 gpuReporter.logTotals(result);
1577 gpuReporter.logOutput(result);
1578 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1579 gpuReporter.logOutput(result, true);
1580
Alec Mouria90a5702021-04-16 16:36:21 +00001581 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1582 mGraphicBufferExternalRefs.size());
1583 StringAppendF(&result, "Dumping buffer ids...\n");
1584 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1585 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1586 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001587 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1588 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001589 StringAppendF(&result, "Dumping buffer ids...\n");
1590 // TODO(178539829): It would be nice to know which layer these are coming from and what
1591 // the texture sizes are.
1592 for (const auto& [id, unused] : mTextureCache) {
1593 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1594 }
1595 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001596
1597 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001598 if (mProtectedGrContext) {
1599 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1600 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001601 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1602 gpuProtectedReporter.logTotals(result);
1603 gpuProtectedReporter.logOutput(result);
1604 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1605 gpuProtectedReporter.logOutput(result, true);
1606
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001607 StringAppendF(&result, "\n");
1608 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1609 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1610 StringAppendF(&result, "- inputDataspace: %s\n",
1611 dataspaceDetails(
1612 static_cast<android_dataspace>(linearEffect.inputDataspace))
1613 .c_str());
1614 StringAppendF(&result, "- outputDataspace: %s\n",
1615 dataspaceDetails(
1616 static_cast<android_dataspace>(linearEffect.outputDataspace))
1617 .c_str());
1618 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1619 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1620 }
1621 }
1622 StringAppendF(&result, "\n");
1623}
1624
John Reck67b1e2b2020-08-26 13:17:24 -07001625} // namespace skia
1626} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001627} // namespace android