blob: c482fa4f403bf4fdf6f3cd46cce3c3c8d380ac33 [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>
Alec Mouri88acab92022-03-24 23:41:01 +000060#include <ui/DataspaceUtils.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080061#include <ui/DebugUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080062#include <ui/GraphicBuffer.h>
63#include <utils/Trace.h>
Alec Mourib5777452020-09-28 11:32:42 -070064
65#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080066#include <cstdint>
67#include <memory>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070068#include <numeric>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080069
70#include "../gl/GLExtensions.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040071#include "Cache.h"
Alec Mouric0aae732021-01-12 13:32:18 -080072#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080073#include "filters/BlurFilter.h"
Robin Lee26dacab2021-08-09 14:31:01 +020074#include "filters/GaussianBlurFilter.h"
Robin Lee026680a2021-07-26 12:49:53 +020075#include "filters/KawaseBlurFilter.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080076#include "filters/LinearEffect.h"
77#include "log/log_main.h"
78#include "skia/debug/SkiaCapture.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040079#include "skia/debug/SkiaMemoryReporter.h"
Nader Jawad2dfc98b2021-04-08 20:35:39 -070080#include "skia/filters/StretchShaderFactory.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080081#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070082
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040083namespace {
84// Debugging settings
85static const bool kPrintLayerSettings = false;
86static const bool kFlushAfterEveryLayer = false;
87} // namespace
88
John Reck67b1e2b2020-08-26 13:17:24 -070089bool checkGlError(const char* op, int lineNumber);
90
91namespace android {
92namespace renderengine {
93namespace skia {
94
Ana Krulec1d12b3b2021-01-27 16:49:51 -080095using base::StringAppendF;
96
John Reck67b1e2b2020-08-26 13:17:24 -070097static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
98 EGLint wanted, EGLConfig* outConfig) {
99 EGLint numConfigs = -1, n = 0;
100 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
101 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
102 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
103 configs.resize(n);
104
105 if (!configs.empty()) {
106 if (attribute != EGL_NONE) {
107 for (EGLConfig config : configs) {
108 EGLint value = 0;
109 eglGetConfigAttrib(dpy, config, attribute, &value);
110 if (wanted == value) {
111 *outConfig = config;
112 return NO_ERROR;
113 }
114 }
115 } else {
116 // just pick the first one
117 *outConfig = configs[0];
118 return NO_ERROR;
119 }
120 }
121
122 return NAME_NOT_FOUND;
123}
124
125static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
126 EGLConfig* config) {
127 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
128 // it is to be used with WIFI displays
129 status_t err;
130 EGLint wantedAttribute;
131 EGLint wantedAttributeValue;
132
133 std::vector<EGLint> attribs;
134 if (renderableType) {
135 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
136 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
137
138 // Default to 8 bits per channel.
139 const EGLint tmpAttribs[] = {
140 EGL_RENDERABLE_TYPE,
141 renderableType,
142 EGL_RECORDABLE_ANDROID,
143 EGL_TRUE,
144 EGL_SURFACE_TYPE,
145 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
146 EGL_FRAMEBUFFER_TARGET_ANDROID,
147 EGL_TRUE,
148 EGL_RED_SIZE,
149 is1010102 ? 10 : 8,
150 EGL_GREEN_SIZE,
151 is1010102 ? 10 : 8,
152 EGL_BLUE_SIZE,
153 is1010102 ? 10 : 8,
154 EGL_ALPHA_SIZE,
155 is1010102 ? 2 : 8,
156 EGL_NONE,
157 };
158 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
159 std::back_inserter(attribs));
160 wantedAttribute = EGL_NONE;
161 wantedAttributeValue = EGL_NONE;
162 } else {
163 // if no renderable type specified, fallback to a simplified query
164 wantedAttribute = EGL_NATIVE_VISUAL_ID;
165 wantedAttributeValue = format;
166 }
167
168 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
169 config);
170 if (err == NO_ERROR) {
171 EGLint caveat;
172 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
173 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
174 }
175
176 return err;
177}
178
179std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
180 const RenderEngineCreationArgs& args) {
181 // initialize EGL for the default display
182 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
183 if (!eglInitialize(display, nullptr, nullptr)) {
184 LOG_ALWAYS_FATAL("failed to initialize EGL");
185 }
186
Yiwei Zhange2650962020-12-01 23:27:58 +0000187 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700188 if (!eglVersion) {
189 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000190 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700191 }
192
Yiwei Zhange2650962020-12-01 23:27:58 +0000193 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700194 if (!eglExtensions) {
195 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000196 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700197 }
198
199 auto& extensions = gl::GLExtensions::getInstance();
200 extensions.initWithEGLStrings(eglVersion, eglExtensions);
201
202 // The code assumes that ES2 or later is available if this extension is
203 // supported.
204 EGLConfig config = EGL_NO_CONFIG_KHR;
205 if (!extensions.hasNoConfigContext()) {
206 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
207 }
208
John Reck67b1e2b2020-08-26 13:17:24 -0700209 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800210 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700211 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800212 protectedContext =
213 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700214 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
215 }
216
Alec Mourid6f09462020-12-07 11:18:17 -0800217 EGLContext ctxt =
218 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700219
220 // if can't create a GL context, we can only abort.
221 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
222
223 EGLSurface placeholder = EGL_NO_SURFACE;
224 if (!extensions.hasSurfacelessContext()) {
225 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
226 Protection::UNPROTECTED);
227 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
228 }
229 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
230 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
231 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
232 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
233
234 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
235 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
236 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
237 Protection::PROTECTED);
238 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
239 "can't create protected placeholder pbuffer");
240 }
241
242 // initialize the renderer while GL is current
243 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000244 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
245 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700246
247 ALOGI("OpenGL ES informations:");
248 ALOGI("vendor : %s", extensions.getVendor());
249 ALOGI("renderer : %s", extensions.getRenderer());
250 ALOGI("version : %s", extensions.getVersion());
251 ALOGI("extensions: %s", extensions.getExtensions());
252 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
253 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
254
255 return engine;
256}
257
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700258std::future<void> SkiaGLRenderEngine::primeCache() {
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500259 Cache::primeShaderCache(this);
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700260 return {};
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500261}
262
John Reck67b1e2b2020-08-26 13:17:24 -0700263EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
264 status_t err;
265 EGLConfig config;
266
267 // First try to get an ES3 config
268 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
269 if (err != NO_ERROR) {
270 // If ES3 fails, try to get an ES2 config
271 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
272 if (err != NO_ERROR) {
273 // If ES2 still doesn't work, probably because we're on the emulator.
274 // try a simplified query
275 ALOGW("no suitable EGLConfig found, trying a simpler query");
276 err = selectEGLConfig(display, format, 0, &config);
277 if (err != NO_ERROR) {
278 // this EGL is too lame for android
279 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
280 }
281 }
282 }
283
284 if (logConfig) {
285 // print some debugging info
286 EGLint r, g, b, a;
287 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
288 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
289 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
290 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
291 ALOGI("EGL information:");
292 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
293 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
294 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
295 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
296 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
297 }
298
299 return config;
300}
301
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400302sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
303 // This "cache" does not actually cache anything. It just allows us to
304 // monitor Skia's internal cache. So this method always returns null.
305 return nullptr;
306}
307
308void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
309 const SkString& description) {
310 mShadersCachedSinceLastCall++;
311}
312
313void SkiaGLRenderEngine::assertShadersCompiled(int numShaders) {
314 const int cached = mSkSLCacheMonitor.shadersCachedSinceLastCall();
315 LOG_ALWAYS_FATAL_IF(cached != numShaders, "Attempted to cache %i shaders; cached %i",
316 numShaders, cached);
317}
318
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400319int SkiaGLRenderEngine::reportShadersCompiled() {
320 return mSkSLCacheMonitor.shadersCachedSinceLastCall();
321}
322
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700323SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000324 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700325 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800326 : SkiaRenderEngine(args.renderEngineType),
327 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700328 mEGLContext(ctxt),
329 mPlaceholderSurface(placeholder),
330 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700331 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400332 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800333 mUseColorManagement(args.useColorManagement) {
Brian Salomon40de6ba2022-03-22 19:38:53 +0000334 sk_sp<const GrGLInterface> glInterface = GrGLMakeNativeInterface();
John Reck67b1e2b2020-08-26 13:17:24 -0700335 LOG_ALWAYS_FATAL_IF(!glInterface.get());
336
337 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400338 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700339 options.fDisableDistanceFieldPaths = true;
Nathaniel Nifongf8d35e92021-06-08 15:02:25 -0400340 options.fReducedShaderVariations = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400341 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000342 mGrContext = GrDirectContext::MakeGL(glInterface, options);
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400343 if (supportsProtectedContent()) {
344 useProtectedContext(true);
Lucas Dupind508e472020-11-04 04:32:06 +0000345 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
346 useProtectedContext(false);
347 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700348
349 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500350 ALOGD("Background Blurs Enabled");
Robin Lee026680a2021-07-26 12:49:53 +0200351 mBlurFilter = new KawaseBlurFilter();
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700352 }
Alec Mouric0aae732021-01-12 13:32:18 -0800353 mCapture = std::make_unique<SkiaCapture>();
354}
355
356SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100357 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800358 if (mBlurFilter) {
359 delete mBlurFilter;
360 }
361
362 mCapture = nullptr;
363
364 mGrContext->flushAndSubmit(true);
365 mGrContext->abandonContext();
366
367 if (mProtectedGrContext) {
368 mProtectedGrContext->flushAndSubmit(true);
369 mProtectedGrContext->abandonContext();
370 }
371
372 if (mPlaceholderSurface != EGL_NO_SURFACE) {
373 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
374 }
375 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
376 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
377 }
378 if (mEGLContext != EGL_NO_CONTEXT) {
379 eglDestroyContext(mEGLDisplay, mEGLContext);
380 }
381 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
382 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
383 }
384 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
385 eglTerminate(mEGLDisplay);
386 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700387}
388
Lucas Dupind508e472020-11-04 04:32:06 +0000389bool SkiaGLRenderEngine::supportsProtectedContent() const {
390 return mProtectedEGLContext != EGL_NO_CONTEXT;
391}
392
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400393GrDirectContext* SkiaGLRenderEngine::getActiveGrContext() const {
394 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
395}
396
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400397void SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
398 if (useProtectedContext == mInProtectedContext ||
399 (useProtectedContext && !supportsProtectedContent())) {
400 return;
Lucas Dupind508e472020-11-04 04:32:06 +0000401 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400402
403 // release any scratch resources before switching into a new mode
404 if (getActiveGrContext()) {
405 getActiveGrContext()->purgeUnlockedResources(true);
406 }
407
Lucas Dupind508e472020-11-04 04:32:06 +0000408 const EGLSurface surface =
409 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
410 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
Alec Mouric0aae732021-01-12 13:32:18 -0800411
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400412 if (eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE) {
Lucas Dupind508e472020-11-04 04:32:06 +0000413 mInProtectedContext = useProtectedContext;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400414 // given that we are sharing the same thread between two GrContexts we need to
415 // make sure that the thread state is reset when switching between the two.
416 if (getActiveGrContext()) {
417 getActiveGrContext()->resetContext();
418 }
Lucas Dupind508e472020-11-04 04:32:06 +0000419 }
Lucas Dupind508e472020-11-04 04:32:06 +0000420}
421
John Reck67b1e2b2020-08-26 13:17:24 -0700422base::unique_fd SkiaGLRenderEngine::flush() {
423 ATRACE_CALL();
424 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
425 return base::unique_fd();
426 }
427
428 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
429 if (sync == EGL_NO_SYNC_KHR) {
430 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
431 return base::unique_fd();
432 }
433
434 // native fence fd will not be populated until flush() is done.
435 glFlush();
436
437 // get the fence fd
438 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
439 eglDestroySyncKHR(mEGLDisplay, sync);
440 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
441 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
442 }
443
444 return fenceFd;
445}
446
Alec Mouri4ee7b492021-08-11 10:36:55 -0700447void SkiaGLRenderEngine::waitFence(base::borrowed_fd fenceFd) {
448 if (fenceFd.get() >= 0 && !waitGpuFence(fenceFd)) {
449 ATRACE_NAME("SkiaGLRenderEngine::waitFence");
450 sync_wait(fenceFd.get(), -1);
451 }
452}
453
454bool SkiaGLRenderEngine::waitGpuFence(base::borrowed_fd fenceFd) {
John Reck67b1e2b2020-08-26 13:17:24 -0700455 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
456 !gl::GLExtensions::getInstance().hasWaitSync()) {
457 return false;
458 }
459
Alec Mouri4ee7b492021-08-11 10:36:55 -0700460 // Duplicate the fence for passing to eglCreateSyncKHR.
461 base::unique_fd fenceDup(dup(fenceFd.get()));
462 if (fenceDup.get() < 0) {
463 ALOGE("failed to create duplicate fence fd: %d", fenceDup.get());
464 return false;
465 }
466
John Reck67b1e2b2020-08-26 13:17:24 -0700467 // release the fd and transfer the ownership to EGLSync
Alec Mouri4ee7b492021-08-11 10:36:55 -0700468 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceDup.release(), EGL_NONE};
John Reck67b1e2b2020-08-26 13:17:24 -0700469 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
470 if (sync == EGL_NO_SYNC_KHR) {
471 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
472 return false;
473 }
474
475 // XXX: The spec draft is inconsistent as to whether this should return an
476 // EGLint or void. Ignore the return value for now, as it's not strictly
477 // needed.
478 eglWaitSyncKHR(mEGLDisplay, sync, 0);
479 EGLint error = eglGetError();
480 eglDestroySyncKHR(mEGLDisplay, sync);
481 if (error != EGL_SUCCESS) {
482 ALOGE("failed to wait for EGL native fence sync: %#x", error);
483 return false;
484 }
485
486 return true;
487}
488
Alec Mouri678245d2020-09-30 16:58:23 -0700489static float toDegrees(uint32_t transform) {
490 switch (transform) {
491 case ui::Transform::ROT_90:
492 return 90.0;
493 case ui::Transform::ROT_180:
494 return 180.0;
495 case ui::Transform::ROT_270:
496 return 270.0;
497 default:
498 return 0.0;
499 }
500}
501
Alec Mourib34f0b72020-10-02 13:18:34 -0700502static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
503 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
504 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
505 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
506 matrix[3][3], 0);
507}
508
Alec Mouri029d1952020-10-12 10:37:08 -0700509static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
510 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
511 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
512
513 // Treat unsupported dataspaces as srgb
514 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
515 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
516 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
517 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
518 }
519
520 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
521 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
522 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
523 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
524 }
525
526 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
527 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
528 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
529 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
530
531 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
532 sourceTransfer != destTransfer;
533}
534
Alec Mouria90a5702021-04-16 16:36:21 +0000535void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
536 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800537 // Only run this if RE is running on its own thread. This way the access to GL
538 // operations is guaranteed to be happening on the same thread.
539 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
540 return;
541 }
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400542 // We currently don't attempt to map a buffer if the buffer contains protected content
Derek Sollenberger45007182021-06-10 14:47:21 -0400543 // because GPU resources for protected buffers is much more limited.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400544 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Derek Sollenberger45007182021-06-10 14:47:21 -0400545 if (isProtectedBuffer) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400546 return;
547 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800548 ATRACE_CALL();
549
Derek Sollenberger45007182021-06-10 14:47:21 -0400550 // If we were to support caching protected buffers then we will need to switch the
551 // currently bound context if we are not already using the protected context (and subsequently
552 // switch back after the buffer is cached). However, for non-protected content we can bind
553 // the texture in either GL context because they are initialized with the same share_context
554 // which allows the texture state to be shared between them.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400555 auto grContext = getActiveGrContext();
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400556 auto& cache = mTextureCache;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400557
558 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000559 mGraphicBufferExternalRefs[buffer->getId()]++;
560
561 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800562 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400563 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400564 buffer->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400565 isRenderable, mTextureCleanupMgr);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400566 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800567 }
568}
569
Alec Mouria90a5702021-04-16 16:36:21 +0000570void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800571 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700572 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000573 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
574 iter != mGraphicBufferExternalRefs.end()) {
575 if (iter->second == 0) {
576 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
577 "> from RenderEngine texture, but the "
578 "ref count was already zero!",
579 buffer->getId());
580 mGraphicBufferExternalRefs.erase(buffer->getId());
581 return;
582 }
583
584 iter->second--;
585
Alec Mouric2ffeb42021-06-17 17:42:27 -0700586 // Swap contexts if needed prior to deleting this buffer
587 // See Issue 1 of
588 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
589 // when a protected context and an unprotected context are part of the same share group,
590 // protected surfaces may not be accessed by an unprotected context, implying that protected
591 // surfaces may only be freed when a protected context is active.
592 const bool inProtected = mInProtectedContext;
593 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
594
Alec Mouria90a5702021-04-16 16:36:21 +0000595 if (iter->second == 0) {
596 mTextureCache.erase(buffer->getId());
Alec Mouria90a5702021-04-16 16:36:21 +0000597 mGraphicBufferExternalRefs.erase(buffer->getId());
598 }
Alec Mouric2ffeb42021-06-17 17:42:27 -0700599
600 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
601 // are up-to-date.
602 if (inProtected != mInProtectedContext) {
603 useProtectedContext(inProtected);
604 }
Alec Mouria90a5702021-04-16 16:36:21 +0000605 }
John Reck67b1e2b2020-08-26 13:17:24 -0700606}
607
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400608bool SkiaGLRenderEngine::canSkipPostRenderCleanup() const {
609 std::lock_guard<std::mutex> lock(mRenderingMutex);
610 return mTextureCleanupMgr.isEmpty();
611}
612
613void SkiaGLRenderEngine::cleanupPostRender() {
614 ATRACE_CALL();
615 std::lock_guard<std::mutex> lock(mRenderingMutex);
616 mTextureCleanupMgr.cleanup();
617}
618
619// Helper class intended to be used on the stack to ensure that texture cleanup
620// is deferred until after this class goes out of scope.
621class DeferTextureCleanup final {
622public:
623 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
624 mMgr.setDeferredStatus(true);
625 }
626 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
627
628private:
629 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
630 AutoBackendTexture::CleanupManager& mMgr;
631};
632
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700633sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
634 const RuntimeEffectShaderParameters& parameters) {
Nader Jawad63644d32021-05-07 10:44:21 -0700635 // The given surface will be stretched by HWUI via matrix transformation
636 // which gets similar results for most surfaces
637 // Determine later on if we need to leverage the stertch shader within
638 // surface flinger
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700639 const auto& stretchEffect = parameters.layer.stretchEffect;
640 auto shader = parameters.shader;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700641 if (stretchEffect.hasEffect()) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700642 const auto targetBuffer = parameters.layer.source.buffer.buffer;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700643 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700644 if (graphicBuffer && parameters.shader) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700645 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
646 }
John Reckcdb4ed72021-02-04 13:39:33 -0500647 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700648
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700649 if (parameters.requiresLinearEffect) {
650 const ui::Dataspace inputDataspace = mUseColorManagement ? parameters.layer.sourceDataspace
651 : ui::Dataspace::V0_SRGB_LINEAR;
652 const ui::Dataspace outputDataspace = mUseColorManagement
653 ? parameters.display.outputDataspace
654 : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500655
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700656 auto effect =
657 shaders::LinearEffect{.inputDataspace = inputDataspace,
658 .outputDataspace = outputDataspace,
659 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha};
Ana Krulec47814212021-01-06 19:00:10 -0800660
661 auto effectIter = mRuntimeEffects.find(effect);
662 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
663 if (effectIter == mRuntimeEffects.end()) {
664 runtimeEffect = buildRuntimeEffect(effect);
665 mRuntimeEffects.insert({effect, runtimeEffect});
666 } else {
667 runtimeEffect = effectIter->second;
668 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700669 mat4 colorTransform = parameters.layer.colorTransform;
670
671 colorTransform *=
672 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
673 parameters.layerDimmingRatio, 1.f));
Alec Mouri1a3c5452022-03-04 22:44:51 +0000674 const auto targetBuffer = parameters.layer.source.buffer.buffer;
675 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
676 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700677 return createLinearEffectShader(parameters.shader, effect, runtimeEffect, colorTransform,
678 parameters.display.maxLuminance,
Alec Mourib21d94e2022-01-13 17:44:10 -0800679 parameters.display.currentLuminanceNits,
Alec Mouri1a3c5452022-03-04 22:44:51 +0000680 parameters.layer.source.buffer.maxLuminanceNits,
Alec Mourifcedb9c2022-04-11 20:02:17 +0000681 hardwareBuffer, parameters.display.renderIntent);
Ana Krulec47814212021-01-06 19:00:10 -0800682 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700683 return parameters.shader;
Ana Krulec47814212021-01-06 19:00:10 -0800684}
685
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500686void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500687 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500688 // Record display settings when capture is running.
689 std::stringstream displaySettings;
690 PrintTo(display, &displaySettings);
691 // Store the DisplaySettings in additional information.
692 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
693 SkData::MakeWithCString(displaySettings.str().c_str()));
694 }
695
696 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
697 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
698 // displays might have different scaling when compared to the physical screen.
699
700 canvas->clipRect(getSkRect(display.physicalDisplay));
701 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
702
703 const auto clipWidth = display.clip.width();
704 const auto clipHeight = display.clip.height();
705 auto rotatedClipWidth = clipWidth;
706 auto rotatedClipHeight = clipHeight;
707 // Scale is contingent on the rotation result.
708 if (display.orientation & ui::Transform::ROT_90) {
709 std::swap(rotatedClipWidth, rotatedClipHeight);
710 }
711 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
712 static_cast<SkScalar>(rotatedClipWidth);
713 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
714 static_cast<SkScalar>(rotatedClipHeight);
715 canvas->scale(scaleX, scaleY);
716
717 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
718 // back so that the top left corner of the clip is at (0, 0).
719 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
720 canvas->rotate(toDegrees(display.orientation));
721 canvas->translate(-clipWidth / 2, -clipHeight / 2);
722 canvas->translate(-display.clip.left, -display.clip.top);
723}
724
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500725class AutoSaveRestore {
726public:
727 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
728 ~AutoSaveRestore() { restore(); }
729 void replace(SkCanvas* canvas) {
730 mCanvas = canvas;
731 mSaveCount = canvas->save();
732 }
733 void restore() {
734 if (mCanvas) {
735 mCanvas->restoreToCount(mSaveCount);
736 mCanvas = nullptr;
737 }
738 }
739
740private:
741 SkCanvas* mCanvas;
742 int mSaveCount;
743};
744
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400745static SkRRect getBlurRRect(const BlurRegion& region) {
746 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
747 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
748 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
749 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
750 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
751 SkRRect roundedRect;
752 roundedRect.setRectRadii(rect, radii);
753 return roundedRect;
754}
755
Alec Mouri30835f22022-03-18 00:58:26 +0000756// Arbitrary default margin which should be close enough to zero.
757constexpr float kDefaultMargin = 0.0001f;
758static bool equalsWithinMargin(float expected, float value, float margin = kDefaultMargin) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700759 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
760 return std::abs(expected - value) < margin;
761}
762
Sally Qi4cabdd02021-08-05 16:45:57 -0700763void SkiaGLRenderEngine::drawLayersInternal(
764 const std::shared_ptr<std::promise<RenderEngineResult>>&& resultPromise,
Sally Qi59a9f502021-10-12 18:53:23 +0000765 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
Sally Qi4cabdd02021-08-05 16:45:57 -0700766 const std::shared_ptr<ExternalTexture>& buffer, const bool /*useFramebufferCache*/,
767 base::unique_fd&& bufferFence) {
John Reck67b1e2b2020-08-26 13:17:24 -0700768 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800769
John Reck67b1e2b2020-08-26 13:17:24 -0700770 std::lock_guard<std::mutex> lock(mRenderingMutex);
771 if (layers.empty()) {
772 ALOGV("Drawing empty layer stack");
Sally Qi4cabdd02021-08-05 16:45:57 -0700773 resultPromise->set_value({NO_ERROR, base::unique_fd()});
774 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700775 }
776
John Reck67b1e2b2020-08-26 13:17:24 -0700777 if (buffer == nullptr) {
778 ALOGE("No output buffer provided. Aborting GPU composition.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700779 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
780 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700781 }
782
Alec Mouria90a5702021-04-16 16:36:21 +0000783 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800784
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400785 auto grContext = getActiveGrContext();
Derek Sollenberger45007182021-06-10 14:47:21 -0400786 auto& cache = mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700787
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400788 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
789 DeferTextureCleanup dtc(mTextureCleanupMgr);
790
Alec Mouria90a5702021-04-16 16:36:21 +0000791 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
792 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
793 surfaceTextureRef = it->second;
794 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400795 surfaceTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400796 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
797 buffer->getBuffer()
798 ->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400799 true, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -0700800 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800801
Alec Mouri4ee7b492021-08-11 10:36:55 -0700802 // wait on the buffer to be ready to use prior to using it
803 waitFence(bufferFence);
804
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500805 const ui::Dataspace dstDataspace =
Alec Mourid2bcbae2021-06-28 17:02:17 -0700806 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400807 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700808
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500809 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
810 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800811 ALOGE("Cannot acquire canvas from Skia.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700812 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
813 return;
Ana Krulec6eab17a2020-12-09 15:52:36 -0800814 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500815
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400816 // setup color filter if necessary
817 sk_sp<SkColorFilter> displayColorTransform;
Leon Scroggins III745dcaa2022-01-26 11:55:58 -0500818 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400819 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
820 }
821 const bool ctModifiesAlpha =
822 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
823
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700824 // Find the max layer white point to determine the max luminance of the scene...
825 const float maxLayerWhitePoint = std::transform_reduce(
826 layers.cbegin(), layers.cend(), 0.f,
827 [](float left, float right) { return std::max(left, right); },
828 [&](const auto& l) { return l.whitePointNits; });
829
830 // ...and compute the dimming ratio if dimming is requested
831 const float displayDimmingRatio = display.targetLuminanceNits > 0.f &&
832 maxLayerWhitePoint > 0.f && display.targetLuminanceNits > maxLayerWhitePoint
833 ? maxLayerWhitePoint / display.targetLuminanceNits
834 : 1.f;
835
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500836 // Find if any layers have requested blur, we'll use that info to decide when to render to an
837 // offscreen buffer and when to render to the native buffer.
838 sk_sp<SkSurface> activeSurface(dstSurface);
839 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500840 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500841 const LayerSettings* blurCompositionLayer = nullptr;
842 if (mBlurFilter) {
843 bool requiresCompositionLayer = false;
844 for (const auto& layer : layers) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400845 // if the layer doesn't have blur or it is not visible then continue
846 if (!layerHasBlur(layer, ctModifiesAlpha)) {
847 continue;
848 }
Sally Qi59a9f502021-10-12 18:53:23 +0000849 if (layer.backgroundBlurRadius > 0 &&
Robin Lee26dacab2021-08-09 14:31:01 +0200850 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500851 requiresCompositionLayer = true;
852 }
Sally Qi59a9f502021-10-12 18:53:23 +0000853 for (auto region : layer.blurRegions) {
Robin Lee26dacab2021-08-09 14:31:01 +0200854 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500855 requiresCompositionLayer = true;
856 }
857 }
858 if (requiresCompositionLayer) {
859 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500860 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Sally Qi59a9f502021-10-12 18:53:23 +0000861 blurCompositionLayer = &layer;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500862 break;
863 }
864 }
865 }
866
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500867 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700868 // Clear the entire canvas with a transparent black to prevent ghost images.
869 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500870 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800871
John Reck67b1e2b2020-08-26 13:17:24 -0700872 for (const auto& layer : layers) {
Sally Qi59a9f502021-10-12 18:53:23 +0000873 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
Galia Peychevaf7889b32020-11-25 22:22:40 +0100874
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400875 if (kPrintLayerSettings) {
876 std::stringstream ls;
Sally Qi59a9f502021-10-12 18:53:23 +0000877 PrintTo(layer, &ls);
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400878 auto debugs = ls.str();
879 int pos = 0;
880 while (pos < debugs.size()) {
881 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
882 pos += 1000;
883 }
884 }
885
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500886 sk_sp<SkImage> blurInput;
Sally Qi59a9f502021-10-12 18:53:23 +0000887 if (blurCompositionLayer == &layer) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500888 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
889 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
890
891 // save a snapshot of the activeSurface to use as input to the blur shaders
892 blurInput = activeSurface->makeImageSnapshot();
893
Leon Scroggins III55bf4742022-03-17 14:11:17 -0400894 // blit the offscreen framebuffer into the destination AHB, but only
895 // if there are blur regions. backgroundBlurRadius blurs the entire
896 // image below, so it can skip this step.
897 if (layer.blurRegions.size()) {
898 SkPaint paint;
899 paint.setBlendMode(SkBlendMode::kSrc);
900 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
901 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
902 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
903 String8::format("SurfaceID|%" PRId64, id).c_str(),
904 nullptr);
905 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
906 } else {
907 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
908 }
Derek Sollenberger76664d62021-02-04 11:13:09 -0500909 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500910
911 // assign dstCanvas to canvas and ensure that the canvas state is up to date
912 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500913 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500914 initCanvas(canvas, display);
915
916 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
917 dstSurface->getCanvas()->getSaveCount());
918 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
919 dstSurface->getCanvas()->getTotalMatrix());
920
921 // assign dstSurface to activeSurface
922 activeSurface = dstSurface;
923 }
924
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500925 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500926 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800927 // Record the name of the layer if the capture is running.
928 std::stringstream layerSettings;
Sally Qi59a9f502021-10-12 18:53:23 +0000929 PrintTo(layer, &layerSettings);
Ana Krulec6eab17a2020-12-09 15:52:36 -0800930 // Store the LayerSettings in additional information.
Sally Qi59a9f502021-10-12 18:53:23 +0000931 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
Ana Krulec6eab17a2020-12-09 15:52:36 -0800932 SkData::MakeWithCString(layerSettings.str().c_str()));
933 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100934 // Layers have a local transform that should be applied to them
Sally Qi59a9f502021-10-12 18:53:23 +0000935 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100936
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400937 const auto [bounds, roundRectClip] =
Sally Qi59a9f502021-10-12 18:53:23 +0000938 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
939 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400940 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500941 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
942
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500943 // if multiple layers have blur, then we need to take a snapshot now because
944 // only the lowest layer will have blurImage populated earlier
945 if (!blurInput) {
946 blurInput = activeSurface->makeImageSnapshot();
947 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500948 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400949 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
950
951 // if the clip needs to be applied then apply it now and make sure
952 // it is restored before we attempt to draw any shadows.
953 SkAutoCanvasRestore acr(canvas, true);
954 if (!roundRectClip.isEmpty()) {
955 canvas->clipRRect(roundRectClip, true);
956 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500957
Galia Peychevae425ac82021-03-15 17:12:03 +0100958 // TODO(b/182216890): Filter out empty layers earlier
959 if (blurRect.width() > 0 && blurRect.height() > 0) {
Sally Qi59a9f502021-10-12 18:53:23 +0000960 if (layer.backgroundBlurRadius > 0) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100961 ATRACE_NAME("BackgroundBlur");
Sally Qi59a9f502021-10-12 18:53:23 +0000962 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
963 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100964
Sally Qi59a9f502021-10-12 18:53:23 +0000965 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500966
Sally Qi59a9f502021-10-12 18:53:23 +0000967 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400968 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700969 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400970
Sally Qi59a9f502021-10-12 18:53:23 +0000971 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
972 for (auto region : layer.blurRegions) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100973 if (cachedBlurs[region.blurRadius] == nullptr) {
974 ATRACE_NAME("BlurRegion");
975 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400976 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100977 blurRect);
978 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500979
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400980 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
981 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100982 cachedBlurs[region.blurRadius], blurInput);
983 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700984 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700985 }
986
Sally Qi59a9f502021-10-12 18:53:23 +0000987 if (layer.shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400988 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
Sally Qi59a9f502021-10-12 18:53:23 +0000989 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
Leon Scroggins III63e86952021-05-12 10:45:08 -0400990
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400991 SkRRect shadowBounds, shadowClip;
Sally Qi59a9f502021-10-12 18:53:23 +0000992 if (layer.geometry.boundaries == layer.shadow.boundaries) {
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400993 shadowBounds = bounds;
994 shadowClip = roundRectClip;
995 } else {
996 std::tie(shadowBounds, shadowClip) =
Sally Qi59a9f502021-10-12 18:53:23 +0000997 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
998 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400999 }
1000
Leon Scroggins III63e86952021-05-12 10:45:08 -04001001 // Technically, if bounds is a rect and roundRectClip is not empty,
1002 // it means that the bounds and roundedCornersCrop were different
1003 // enough that we should intersect them to find the proper shadow.
1004 // In practice, this often happens when the two rectangles appear to
1005 // not match due to rounding errors. Draw the rounded version, which
1006 // looks more like the intent.
1007 const auto& rrect =
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001008 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
Sally Qi59a9f502021-10-12 18:53:23 +00001009 drawShadow(canvas, rrect, layer.shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001010 }
1011
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001012 const float layerDimmingRatio = layer.whitePointNits <= 0.f
1013 ? displayDimmingRatio
1014 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
1015
Alec Mouri30835f22022-03-18 00:58:26 +00001016 const bool dimInLinearSpace = display.dimmingStage !=
1017 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
1018
Sally Qi59a9f502021-10-12 18:53:23 +00001019 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001020 (mUseColorManagement &&
Sally Qi59a9f502021-10-12 18:53:23 +00001021 needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
Alec Mouri30835f22022-03-18 00:58:26 +00001022 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio));
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001023
1024 // quick abort from drawing the remaining portion of the layer
Sally Qi59a9f502021-10-12 18:53:23 +00001025 if (layer.skipContentDraw ||
1026 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001027 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001028 continue;
1029 }
1030
1031 // If we need to map to linear space or color management is disabled, then mark the source
1032 // image with the same colorspace as the destination surface so that Skia's color
1033 // management is a no-op.
1034 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
1035 ? dstDataspace
Sally Qi59a9f502021-10-12 18:53:23 +00001036 : layer.sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -08001037
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001038 SkPaint paint;
Sally Qi59a9f502021-10-12 18:53:23 +00001039 if (layer.source.buffer.buffer) {
John Reck67b1e2b2020-08-26 13:17:24 -07001040 ATRACE_NAME("DrawImage");
Sally Qi59a9f502021-10-12 18:53:23 +00001041 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
1042 const auto& item = layer.source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001043 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +00001044
1045 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
1046 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001047 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -07001048 } else {
Alec Mouria90a5702021-04-16 16:36:21 +00001049 // If we didn't find the image in the cache, then create a local ref but don't cache
1050 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
1051 // we didn't find anything in the cache then we intentionally did not cache this
1052 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001053 imageTextureRef = std::make_shared<
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001054 AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001055 item.buffer->getBuffer()->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -04001056 false, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -07001057 }
Alec Mouri1a4d0642020-11-13 17:42:01 -08001058
Alec Mouri4ee7b492021-08-11 10:36:55 -07001059 // if the layer's buffer has a fence, then we must must respect the fence prior to using
1060 // the buffer.
Sally Qi59a9f502021-10-12 18:53:23 +00001061 if (layer.source.buffer.fence != nullptr) {
1062 waitFence(layer.source.buffer.fence->get());
Alec Mouri4ee7b492021-08-11 10:36:55 -07001063 }
1064
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001065 // isOpaque means we need to ignore the alpha in the image,
1066 // replacing it with the alpha specified by the LayerSettings. See
1067 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
1068 // The proper way to do this is to use an SkColorType that ignores
1069 // alpha, like kRGB_888x_SkColorType, and that is used if the
1070 // incoming image is kRGBA_8888_SkColorType. However, the incoming
1071 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
1072 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
1073 // kRGB_101010x_SkColorType, but it is not yet supported as a source
1074 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
1075 // meantime, we'll use a workaround that works unless we need to do
1076 // any color conversion. The workaround requires that we pretend the
1077 // image is already premultiplied, so that we do not premultiply it
1078 // before applying SkBlendMode::kPlus.
1079 const bool useIsOpaqueWorkaround = item.isOpaque &&
1080 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
1081 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
1082 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
1083 : item.isOpaque ? kOpaque_SkAlphaType
1084 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
1085 : kUnpremul_SkAlphaType;
1086 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -07001087
1088 auto texMatrix = getSkM44(item.textureTransform).asM33();
1089 // textureTansform was intended to be passed directly into a shader, so when
1090 // building the total matrix with the textureTransform we need to first
1091 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001092 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001093 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -07001094
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001095 SkMatrix matrix;
1096 if (!texMatrix.invert(&matrix)) {
1097 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -07001098 }
Ana Krulecf9a15d92020-12-11 08:35:00 -08001099 // The shader does not respect the translation, so we add it to the texture
1100 // transform for the SkImage. This will make sure that the correct layer contents
1101 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001102 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -07001103
Ana Krulecb7b28b22020-11-23 14:48:58 -08001104 sk_sp<SkShader> shader;
1105
Sally Qi59a9f502021-10-12 18:53:23 +00001106 if (layer.source.buffer.useTextureFiltering) {
Ana Krulecb7b28b22020-11-23 14:48:58 -08001107 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1108 SkSamplingOptions(
1109 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1110 &matrix);
1111 } else {
Mike Reed711e1f02020-12-11 13:06:19 -05001112 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -08001113 }
Alec Mouri029d1952020-10-12 10:37:08 -07001114
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001115 if (useIsOpaqueWorkaround) {
Alec Mouric0aae732021-01-12 13:32:18 -08001116 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1117 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001118 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001119 }
1120
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001121 paint.setShader(createRuntimeEffectShader(
1122 RuntimeEffectShaderParameters{.shader = shader,
1123 .layer = layer,
1124 .display = display,
1125 .undoPremultipliedAlpha = !item.isOpaque &&
1126 item.usePremultipliedAlpha,
1127 .requiresLinearEffect = requiresLinearEffect,
Alec Mouri30835f22022-03-18 00:58:26 +00001128 .layerDimmingRatio = dimInLinearSpace
1129 ? layerDimmingRatio
1130 : 1.f}));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001131
Alec Mouri88acab92022-03-24 23:41:01 +00001132 // Turn on dithering when dimming beyond this (arbitrary) threshold...
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001133 static constexpr float kDimmingThreshold = 0.2f;
Alec Mouri88acab92022-03-24 23:41:01 +00001134 // ...or we're rendering an HDR layer down to an 8-bit target
1135 // Most HDR standards require at least 10-bits of color depth for source content, so we
1136 // can just extract the transfer function rather than dig into precise gralloc layout.
1137 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
1138 const bool requiresDownsample = isHdrDataspace(layer.sourceDataspace) &&
1139 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
1140 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001141 paint.setDither(true);
1142 }
Sally Qi59a9f502021-10-12 18:53:23 +00001143 paint.setAlphaf(layer.alpha);
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001144
1145 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1146 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001147
1148 // SysUI creates the alpha layer as a coverage layer, which is
1149 // appropriate for the DPU. Use a color matrix to convert it to
1150 // a mask.
1151 // TODO (b/219525258): Handle input as a mask.
1152 //
1153 // The color matrix will convert A8 pixels with no alpha to
1154 // black, as described by this vector. If the display handles
1155 // the color transform, we need to invert it to find the color
1156 // that will result in black after the DPU applies the transform.
1157 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1158 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1159 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1160 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1161 black = colorSpaceMatrix * black;
1162 } else {
1163 // We'll just have to use 0,0,0 as black, which should
1164 // be close to correct.
1165 ALOGI("Could not invert colorTransform!");
1166 }
1167 }
1168 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1169 0, 0, 0, 0, black[1],
1170 0, 0, 0, 0, black[2],
1171 0, 0, 0, -1, 1);
1172 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1173 // On the other hand, if the device doesn't handle it, we
1174 // have to apply it ourselves.
1175 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1176 }
1177 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001178 }
John Reck67b1e2b2020-08-26 13:17:24 -07001179 } else {
1180 ATRACE_NAME("DrawColor");
Sally Qi59a9f502021-10-12 18:53:23 +00001181 const auto color = layer.source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001182 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1183 .fG = color.g,
1184 .fB = color.b,
Sally Qi59a9f502021-10-12 18:53:23 +00001185 .fA = layer.alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001186 toSkColorSpace(layerDataspace));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001187 paint.setShader(createRuntimeEffectShader(
1188 RuntimeEffectShaderParameters{.shader = shader,
1189 .layer = layer,
1190 .display = display,
1191 .undoPremultipliedAlpha = false,
1192 .requiresLinearEffect = requiresLinearEffect,
1193 .layerDimmingRatio = layerDimmingRatio}));
John Reck67b1e2b2020-08-26 13:17:24 -07001194 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001195
Sally Qi59a9f502021-10-12 18:53:23 +00001196 if (layer.disableBlending) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001197 paint.setBlendMode(SkBlendMode::kSrc);
1198 }
1199
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001200 // An A8 buffer will already have the proper color filter attached to
1201 // its paint, including the displayColorTransform as needed.
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001202 if (!paint.getColorFilter()) {
Alec Mouri30835f22022-03-18 00:58:26 +00001203 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1204 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1205 // can assume a gamma 2.2 transfer function.
1206 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1207 const auto gammaCorrectedDimmingRatio =
1208 std::pow(layerDimmingRatio, kInverseGamma22);
1209 const auto dimmingMatrix =
1210 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1211 gammaCorrectedDimmingRatio, 1.f));
1212 paint.setColorFilter(SkColorFilters::Matrix(
1213 toSkColorMatrix(display.colorTransform * dimmingMatrix)));
1214 } else {
1215 paint.setColorFilter(displayColorTransform);
1216 }
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001217 }
Alec Mourib34f0b72020-10-02 13:18:34 -07001218
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001219 if (!roundRectClip.isEmpty()) {
1220 canvas->clipRRect(roundRectClip, true);
1221 }
1222
1223 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001224 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001225 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001226 } else {
Nader Jawad63644d32021-05-07 10:44:21 -07001227 canvas->drawRect(bounds.rect(), paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -07001228 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001229 if (kFlushAfterEveryLayer) {
1230 ATRACE_NAME("flush surface");
1231 activeSurface->flush();
1232 }
John Reck67b1e2b2020-08-26 13:17:24 -07001233 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001234 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001235 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001236 {
1237 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001238 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1239 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001240 }
1241
Sally Qi4cabdd02021-08-05 16:45:57 -07001242 base::unique_fd drawFence = flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001243
1244 // If flush failed or we don't support native fences, we need to force the
1245 // gl command stream to be executed.
Sally Qi4cabdd02021-08-05 16:45:57 -07001246 bool requireSync = drawFence.get() < 0;
John Reck67b1e2b2020-08-26 13:17:24 -07001247 if (requireSync) {
1248 ATRACE_BEGIN("Submit(sync=true)");
1249 } else {
1250 ATRACE_BEGIN("Submit(sync=false)");
1251 }
Lucas Dupind508e472020-11-04 04:32:06 +00001252 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001253 ATRACE_END();
1254 if (!success) {
1255 ALOGE("Failed to flush RenderEngine commands");
1256 // Chances are, something illegal happened (either the caller passed
1257 // us bad parameters, or we messed up our shader generation).
Sally Qi4cabdd02021-08-05 16:45:57 -07001258 resultPromise->set_value({INVALID_OPERATION, std::move(drawFence)});
1259 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001260 }
1261
1262 // checkErrors();
Sally Qi4cabdd02021-08-05 16:45:57 -07001263 resultPromise->set_value({NO_ERROR, std::move(drawFence)});
1264 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001265}
1266
Lucas Dupin3f11e922020-09-22 17:31:04 -07001267inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1268 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1269}
1270
1271inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1272 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1273}
1274
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001275/**
1276 * Verifies that common, simple bounds + clip combinations can be converted into
1277 * a single RRect draw call returning true if possible. If true the radii parameter
1278 * will be filled with the correct radii values that combined with bounds param will
1279 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
1280 */
1281static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
1282 const SkRect& insetCrop, float cornerRadius,
1283 SkVector radii[4]) {
1284 const bool leftEqual = bounds.fLeft == crop.fLeft;
1285 const bool topEqual = bounds.fTop == crop.fTop;
1286 const bool rightEqual = bounds.fRight == crop.fRight;
1287 const bool bottomEqual = bounds.fBottom == crop.fBottom;
1288
1289 // In the event that the corners of the bounds only partially align with the crop we
1290 // need to ensure that the resulting shape can still be represented as a round rect.
1291 // In particular the round rect implementation will scale the value of all corner radii
1292 // if the sum of the radius along any edge is greater than the length of that edge.
1293 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
1294 const bool requiredWidth = bounds.width() > (cornerRadius * 2);
1295 const bool requiredHeight = bounds.height() > (cornerRadius * 2);
1296 if (!requiredWidth || !requiredHeight) {
1297 return false;
1298 }
1299
1300 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
1301 // contained within the cropped shape and does not need rounded.
1302 // compute the UpperLeft corner radius
1303 if (leftEqual && topEqual) {
1304 radii[0].set(cornerRadius, cornerRadius);
1305 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
1306 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
1307 radii[0].set(0, 0);
1308 } else {
1309 return false;
1310 }
1311 // compute the UpperRight corner radius
1312 if (rightEqual && topEqual) {
1313 radii[1].set(cornerRadius, cornerRadius);
1314 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
1315 (topEqual && bounds.fRight <= insetCrop.fRight)) {
1316 radii[1].set(0, 0);
1317 } else {
1318 return false;
1319 }
1320 // compute the BottomRight corner radius
1321 if (rightEqual && bottomEqual) {
1322 radii[2].set(cornerRadius, cornerRadius);
1323 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
1324 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
1325 radii[2].set(0, 0);
1326 } else {
1327 return false;
1328 }
1329 // compute the BottomLeft corner radius
1330 if (leftEqual && bottomEqual) {
1331 radii[3].set(cornerRadius, cornerRadius);
1332 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
1333 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
1334 radii[3].set(0, 0);
1335 } else {
1336 return false;
1337 }
1338
1339 return true;
1340}
1341
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001342inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(const FloatRect& boundsRect,
1343 const FloatRect& cropRect,
1344 const float cornerRadius) {
1345 const SkRect bounds = getSkRect(boundsRect);
1346 const SkRect crop = getSkRect(cropRect);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001347
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001348 SkRRect clip;
1349 if (cornerRadius > 0) {
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001350 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
1351 if (bounds == crop || crop.isEmpty()) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001352 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1353 }
1354
1355 // This makes an effort to speed up common, simple bounds + clip combinations by
1356 // converting them to a single RRect draw. It is possible there are other cases
1357 // that can be converted.
1358 if (crop.contains(bounds)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001359 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001360 if (insetCrop.contains(bounds)) {
1361 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001362 }
1363
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001364 SkVector radii[4];
1365 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001366 SkRRect intersectionBounds;
1367 intersectionBounds.setRectRadii(bounds, radii);
1368 return {intersectionBounds, clip};
1369 }
1370 }
1371
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001372 // we didn't hit any of our fast paths so set the clip to the cropRect
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001373 clip.setRectXY(crop, cornerRadius, cornerRadius);
1374 }
1375
1376 // if we hit this point then we either don't have rounded corners or we are going to rely
1377 // on the clip to round the corners for us
1378 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001379}
1380
Sally Qi59a9f502021-10-12 18:53:23 +00001381inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings& layer,
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001382 bool colorTransformModifiesAlpha) {
Sally Qi59a9f502021-10-12 18:53:23 +00001383 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001384 // return false if the content is opaque and would therefore occlude the blur
Sally Qi59a9f502021-10-12 18:53:23 +00001385 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
1386 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
1387 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001388 }
1389 return false;
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001390}
1391
Lucas Dupin3f11e922020-09-22 17:31:04 -07001392inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1393 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1394}
1395
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001396inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1397 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1398 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1399 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1400 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1401}
1402
Lucas Dupin3f11e922020-09-22 17:31:04 -07001403inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1404 return SkPoint3::Make(vector.x, vector.y, vector.z);
1405}
1406
John Reck67b1e2b2020-08-26 13:17:24 -07001407size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1408 return mGrContext->maxTextureSize();
1409}
1410
1411size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1412 return mGrContext->maxRenderTargetSize();
1413}
1414
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001415void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001416 const ShadowSettings& settings) {
1417 ATRACE_CALL();
1418 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001419 const auto flags =
1420 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1421
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001422 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001423 getSkPoint3(settings.lightPos), settings.lightRadius,
1424 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1425 flags);
1426}
1427
John Reck67b1e2b2020-08-26 13:17:24 -07001428EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001429 EGLContext shareContext,
1430 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001431 Protection protection) {
1432 EGLint renderableType = 0;
1433 if (config == EGL_NO_CONFIG_KHR) {
1434 renderableType = EGL_OPENGL_ES3_BIT;
1435 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1436 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1437 }
1438 EGLint contextClientVersion = 0;
1439 if (renderableType & EGL_OPENGL_ES3_BIT) {
1440 contextClientVersion = 3;
1441 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1442 contextClientVersion = 2;
1443 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1444 contextClientVersion = 1;
1445 } else {
1446 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1447 }
1448
1449 std::vector<EGLint> contextAttributes;
1450 contextAttributes.reserve(7);
1451 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1452 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001453 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001454 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001455 switch (*contextPriority) {
1456 case ContextPriority::REALTIME:
1457 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1458 break;
1459 case ContextPriority::MEDIUM:
1460 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1461 break;
1462 case ContextPriority::LOW:
1463 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1464 break;
1465 case ContextPriority::HIGH:
1466 default:
1467 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1468 break;
1469 }
John Reck67b1e2b2020-08-26 13:17:24 -07001470 }
1471 if (protection == Protection::PROTECTED) {
1472 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1473 contextAttributes.push_back(EGL_TRUE);
1474 }
1475 contextAttributes.push_back(EGL_NONE);
1476
1477 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1478
1479 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1480 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1481 // EGL_NO_CONTEXT so that we can abort.
1482 if (config != EGL_NO_CONFIG_KHR) {
1483 return context;
1484 }
1485 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1486 // should try to fall back to GLES 2.
1487 contextAttributes[1] = 2;
1488 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1489 }
1490
1491 return context;
1492}
1493
Alec Mourid6f09462020-12-07 11:18:17 -08001494std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1495 const RenderEngineCreationArgs& args) {
1496 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1497 return std::nullopt;
1498 }
1499
1500 switch (args.contextPriority) {
1501 case RenderEngine::ContextPriority::REALTIME:
1502 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1503 return RenderEngine::ContextPriority::REALTIME;
1504 } else {
1505 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1506 return RenderEngine::ContextPriority::HIGH;
1507 }
1508 case RenderEngine::ContextPriority::HIGH:
1509 case RenderEngine::ContextPriority::MEDIUM:
1510 case RenderEngine::ContextPriority::LOW:
1511 return args.contextPriority;
1512 default:
1513 return std::nullopt;
1514 }
1515}
1516
John Reck67b1e2b2020-08-26 13:17:24 -07001517EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1518 EGLConfig config, int hwcFormat,
1519 Protection protection) {
1520 EGLConfig placeholderConfig = config;
1521 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1522 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1523 }
1524 std::vector<EGLint> attributes;
1525 attributes.reserve(7);
1526 attributes.push_back(EGL_WIDTH);
1527 attributes.push_back(1);
1528 attributes.push_back(EGL_HEIGHT);
1529 attributes.push_back(1);
1530 if (protection == Protection::PROTECTED) {
1531 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1532 attributes.push_back(EGL_TRUE);
1533 }
1534 attributes.push_back(EGL_NONE);
1535
1536 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1537}
1538
Alec Mourid6f09462020-12-07 11:18:17 -08001539int SkiaGLRenderEngine::getContextPriority() {
1540 int value;
1541 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1542 return value;
1543}
1544
Ady Abrahamed3290f2021-05-17 15:12:14 -07001545void SkiaGLRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001546 // This cache multiplier was selected based on review of cache sizes relative
1547 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1548 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1549 // conservative default based on that analysis.
1550 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1551 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1552
1553 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001554 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001555
1556 // if it is possible to switch contexts then we will resize the other context
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001557 const bool originalProtectedState = mInProtectedContext;
1558 useProtectedContext(!mInProtectedContext);
1559 if (mInProtectedContext != originalProtectedState) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001560 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001561 // reset back to the initial context that was active when this method was called
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001562 useProtectedContext(originalProtectedState);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001563 }
1564}
1565
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001566void SkiaGLRenderEngine::dump(std::string& result) {
1567 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1568
1569 StringAppendF(&result, "\n ------------RE-----------------\n");
1570 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1571 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1572 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1573 extensions.getVersion());
1574 StringAppendF(&result, "%s\n", extensions.getExtensions());
1575 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1576 supportsProtectedContent());
1577 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001578 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1579 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001580
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001581 std::vector<ResourcePair> cpuResourceMap = {
1582 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1583 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1584 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1585 {"skia/sk_resource_cache/tessellated", "Shadows"},
1586 {"skia", "Other"},
1587 };
1588 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1589 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1590 StringAppendF(&result, "Skia CPU Caches: ");
1591 cpuReporter.logTotals(result);
1592 cpuReporter.logOutput(result);
1593
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001594 {
1595 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001596
1597 std::vector<ResourcePair> gpuResourceMap = {
1598 {"texture_renderbuffer", "Texture/RenderBuffer"},
1599 {"texture", "Texture"},
1600 {"gr_text_blob_cache", "Text"},
1601 {"skia", "Other"},
1602 };
1603 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1604 mGrContext->dumpMemoryStatistics(&gpuReporter);
1605 StringAppendF(&result, "Skia's GPU Caches: ");
1606 gpuReporter.logTotals(result);
1607 gpuReporter.logOutput(result);
1608 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1609 gpuReporter.logOutput(result, true);
1610
Alec Mouria90a5702021-04-16 16:36:21 +00001611 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1612 mGraphicBufferExternalRefs.size());
1613 StringAppendF(&result, "Dumping buffer ids...\n");
1614 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1615 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1616 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001617 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1618 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001619 StringAppendF(&result, "Dumping buffer ids...\n");
1620 // TODO(178539829): It would be nice to know which layer these are coming from and what
1621 // the texture sizes are.
1622 for (const auto& [id, unused] : mTextureCache) {
1623 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1624 }
1625 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001626
1627 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001628 if (mProtectedGrContext) {
1629 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1630 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001631 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1632 gpuProtectedReporter.logTotals(result);
1633 gpuProtectedReporter.logOutput(result);
1634 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1635 gpuProtectedReporter.logOutput(result, true);
1636
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001637 StringAppendF(&result, "\n");
1638 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1639 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1640 StringAppendF(&result, "- inputDataspace: %s\n",
1641 dataspaceDetails(
1642 static_cast<android_dataspace>(linearEffect.inputDataspace))
1643 .c_str());
1644 StringAppendF(&result, "- outputDataspace: %s\n",
1645 dataspaceDetails(
1646 static_cast<android_dataspace>(linearEffect.outputDataspace))
1647 .c_str());
1648 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1649 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1650 }
1651 }
1652 StringAppendF(&result, "\n");
1653}
1654
John Reck67b1e2b2020-08-26 13:17:24 -07001655} // namespace skia
1656} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001657} // namespace android