blob: 97271cb32dc0236ceaa11ed575d737784c772965 [file] [log] [blame]
John Reck67b1e2b2020-08-26 13:17:24 -07001/*
2 * Copyright 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
Ana Krulec70d15b1b2020-12-01 10:05:15 -080018#undef LOG_TAG
19#define LOG_TAG "RenderEngine"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
Alec Mouri4ce5ec02021-01-07 17:33:21 -080022#include "SkiaGLRenderEngine.h"
John Reck67b1e2b2020-08-26 13:17:24 -070023
John Reck67b1e2b2020-08-26 13:17:24 -070024#include <EGL/egl.h>
25#include <EGL/eglext.h>
John Reck67b1e2b2020-08-26 13:17:24 -070026#include <GrContextOptions.h>
John Reck67b1e2b2020-08-26 13:17:24 -070027#include <SkCanvas.h>
Alec Mourib34f0b72020-10-02 13:18:34 -070028#include <SkColorFilter.h>
29#include <SkColorMatrix.h>
Alec Mourib5777452020-09-28 11:32:42 -070030#include <SkColorSpace.h>
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040031#include <SkGraphics.h>
John Reck67b1e2b2020-08-26 13:17:24 -070032#include <SkImage.h>
Lucas Dupinf4cb4a02020-09-22 14:19:26 -070033#include <SkImageFilters.h>
Alec Mouric0aae732021-01-12 13:32:18 -080034#include <SkRegion.h>
Lucas Dupin3f11e922020-09-22 17:31:04 -070035#include <SkShadowUtils.h>
John Reck67b1e2b2020-08-26 13:17:24 -070036#include <SkSurface.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080037#include <android-base/stringprintf.h>
Alec Mourib5777452020-09-28 11:32:42 -070038#include <gl/GrGLInterface.h>
Alec Mouricbd30932021-06-09 15:52:25 -070039#include <gui/TraceUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080040#include <sync/sync.h>
41#include <ui/BlurRegion.h>
Alec Mouri88acab92022-03-24 23:41:01 +000042#include <ui/DataspaceUtils.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080043#include <ui/DebugUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080044#include <ui/GraphicBuffer.h>
45#include <utils/Trace.h>
Alec Mourib5777452020-09-28 11:32:42 -070046
47#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080048#include <cstdint>
49#include <memory>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070050#include <numeric>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080051
52#include "../gl/GLExtensions.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040053#include "Cache.h"
Alec Mouric0aae732021-01-12 13:32:18 -080054#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080055#include "SkBlendMode.h"
56#include "SkImageInfo.h"
57#include "filters/BlurFilter.h"
Robin Lee26dacab2021-08-09 14:31:01 +020058#include "filters/GaussianBlurFilter.h"
Robin Lee026680a2021-07-26 12:49:53 +020059#include "filters/KawaseBlurFilter.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080060#include "filters/LinearEffect.h"
61#include "log/log_main.h"
62#include "skia/debug/SkiaCapture.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040063#include "skia/debug/SkiaMemoryReporter.h"
Nader Jawad2dfc98b2021-04-08 20:35:39 -070064#include "skia/filters/StretchShaderFactory.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080065#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070066
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040067namespace {
68// Debugging settings
69static const bool kPrintLayerSettings = false;
Leon Scroggins III191b8772022-04-06 14:38:22 -040070static const bool kFlushAfterEveryLayer = kPrintLayerSettings;
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040071} // namespace
72
John Reck67b1e2b2020-08-26 13:17:24 -070073bool checkGlError(const char* op, int lineNumber);
74
75namespace android {
76namespace renderengine {
77namespace skia {
78
Ana Krulec1d12b3b2021-01-27 16:49:51 -080079using base::StringAppendF;
80
John Reck67b1e2b2020-08-26 13:17:24 -070081static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
82 EGLint wanted, EGLConfig* outConfig) {
83 EGLint numConfigs = -1, n = 0;
84 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
85 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
86 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
87 configs.resize(n);
88
89 if (!configs.empty()) {
90 if (attribute != EGL_NONE) {
91 for (EGLConfig config : configs) {
92 EGLint value = 0;
93 eglGetConfigAttrib(dpy, config, attribute, &value);
94 if (wanted == value) {
95 *outConfig = config;
96 return NO_ERROR;
97 }
98 }
99 } else {
100 // just pick the first one
101 *outConfig = configs[0];
102 return NO_ERROR;
103 }
104 }
105
106 return NAME_NOT_FOUND;
107}
108
109static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
110 EGLConfig* config) {
111 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
112 // it is to be used with WIFI displays
113 status_t err;
114 EGLint wantedAttribute;
115 EGLint wantedAttributeValue;
116
117 std::vector<EGLint> attribs;
118 if (renderableType) {
119 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
120 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
121
122 // Default to 8 bits per channel.
123 const EGLint tmpAttribs[] = {
124 EGL_RENDERABLE_TYPE,
125 renderableType,
126 EGL_RECORDABLE_ANDROID,
127 EGL_TRUE,
128 EGL_SURFACE_TYPE,
129 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
130 EGL_FRAMEBUFFER_TARGET_ANDROID,
131 EGL_TRUE,
132 EGL_RED_SIZE,
133 is1010102 ? 10 : 8,
134 EGL_GREEN_SIZE,
135 is1010102 ? 10 : 8,
136 EGL_BLUE_SIZE,
137 is1010102 ? 10 : 8,
138 EGL_ALPHA_SIZE,
139 is1010102 ? 2 : 8,
140 EGL_NONE,
141 };
142 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
143 std::back_inserter(attribs));
144 wantedAttribute = EGL_NONE;
145 wantedAttributeValue = EGL_NONE;
146 } else {
147 // if no renderable type specified, fallback to a simplified query
148 wantedAttribute = EGL_NATIVE_VISUAL_ID;
149 wantedAttributeValue = format;
150 }
151
152 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
153 config);
154 if (err == NO_ERROR) {
155 EGLint caveat;
156 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
157 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
158 }
159
160 return err;
161}
162
163std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
164 const RenderEngineCreationArgs& args) {
165 // initialize EGL for the default display
166 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
167 if (!eglInitialize(display, nullptr, nullptr)) {
168 LOG_ALWAYS_FATAL("failed to initialize EGL");
169 }
170
Yiwei Zhange2650962020-12-01 23:27:58 +0000171 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700172 if (!eglVersion) {
173 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000174 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700175 }
176
Yiwei Zhange2650962020-12-01 23:27:58 +0000177 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700178 if (!eglExtensions) {
179 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000180 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700181 }
182
183 auto& extensions = gl::GLExtensions::getInstance();
184 extensions.initWithEGLStrings(eglVersion, eglExtensions);
185
186 // The code assumes that ES2 or later is available if this extension is
187 // supported.
188 EGLConfig config = EGL_NO_CONFIG_KHR;
189 if (!extensions.hasNoConfigContext()) {
190 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
191 }
192
John Reck67b1e2b2020-08-26 13:17:24 -0700193 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800194 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700195 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800196 protectedContext =
197 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700198 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
199 }
200
Alec Mourid6f09462020-12-07 11:18:17 -0800201 EGLContext ctxt =
202 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700203
204 // if can't create a GL context, we can only abort.
205 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
206
207 EGLSurface placeholder = EGL_NO_SURFACE;
208 if (!extensions.hasSurfacelessContext()) {
209 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
210 Protection::UNPROTECTED);
211 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
212 }
213 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
214 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
215 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
216 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
217
218 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
219 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
220 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
221 Protection::PROTECTED);
222 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
223 "can't create protected placeholder pbuffer");
224 }
225
226 // initialize the renderer while GL is current
227 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000228 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
229 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700230
231 ALOGI("OpenGL ES informations:");
232 ALOGI("vendor : %s", extensions.getVendor());
233 ALOGI("renderer : %s", extensions.getRenderer());
234 ALOGI("version : %s", extensions.getVersion());
235 ALOGI("extensions: %s", extensions.getExtensions());
236 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
237 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
238
239 return engine;
240}
241
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700242std::future<void> SkiaGLRenderEngine::primeCache() {
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500243 Cache::primeShaderCache(this);
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700244 return {};
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500245}
246
John Reck67b1e2b2020-08-26 13:17:24 -0700247EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
248 status_t err;
249 EGLConfig config;
250
251 // First try to get an ES3 config
252 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
253 if (err != NO_ERROR) {
254 // If ES3 fails, try to get an ES2 config
255 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
256 if (err != NO_ERROR) {
257 // If ES2 still doesn't work, probably because we're on the emulator.
258 // try a simplified query
259 ALOGW("no suitable EGLConfig found, trying a simpler query");
260 err = selectEGLConfig(display, format, 0, &config);
261 if (err != NO_ERROR) {
262 // this EGL is too lame for android
263 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
264 }
265 }
266 }
267
268 if (logConfig) {
269 // print some debugging info
270 EGLint r, g, b, a;
271 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
272 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
273 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
274 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
275 ALOGI("EGL information:");
276 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
277 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
278 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
279 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
280 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
281 }
282
283 return config;
284}
285
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400286sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
287 // This "cache" does not actually cache anything. It just allows us to
288 // monitor Skia's internal cache. So this method always returns null.
289 return nullptr;
290}
291
292void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
293 const SkString& description) {
294 mShadersCachedSinceLastCall++;
Leon Scroggins IIIadf18d82022-04-22 13:23:05 -0400295 mTotalShadersCompiled++;
296 ATRACE_FORMAT("SF cache: %i shaders", mTotalShadersCompiled);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400297}
298
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400299int SkiaGLRenderEngine::reportShadersCompiled() {
Leon Scroggins III45be9182022-04-27 10:37:11 -0400300 return mSkSLCacheMonitor.totalShadersCompiled();
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400301}
302
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700303SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000304 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700305 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800306 : SkiaRenderEngine(args.renderEngineType),
307 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700308 mEGLContext(ctxt),
309 mPlaceholderSurface(placeholder),
310 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700311 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400312 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800313 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700314 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
315 LOG_ALWAYS_FATAL_IF(!glInterface.get());
316
317 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400318 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700319 options.fDisableDistanceFieldPaths = true;
Nathaniel Nifongf8d35e92021-06-08 15:02:25 -0400320 options.fReducedShaderVariations = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400321 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000322 mGrContext = GrDirectContext::MakeGL(glInterface, options);
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400323 if (supportsProtectedContent()) {
324 useProtectedContext(true);
Lucas Dupind508e472020-11-04 04:32:06 +0000325 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
326 useProtectedContext(false);
327 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700328
329 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500330 ALOGD("Background Blurs Enabled");
Robin Lee026680a2021-07-26 12:49:53 +0200331 mBlurFilter = new KawaseBlurFilter();
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700332 }
Alec Mouric0aae732021-01-12 13:32:18 -0800333 mCapture = std::make_unique<SkiaCapture>();
334}
335
336SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100337 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800338 if (mBlurFilter) {
339 delete mBlurFilter;
340 }
341
342 mCapture = nullptr;
343
344 mGrContext->flushAndSubmit(true);
345 mGrContext->abandonContext();
346
347 if (mProtectedGrContext) {
348 mProtectedGrContext->flushAndSubmit(true);
349 mProtectedGrContext->abandonContext();
350 }
351
352 if (mPlaceholderSurface != EGL_NO_SURFACE) {
353 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
354 }
355 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
356 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
357 }
358 if (mEGLContext != EGL_NO_CONTEXT) {
359 eglDestroyContext(mEGLDisplay, mEGLContext);
360 }
361 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
362 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
363 }
364 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
365 eglTerminate(mEGLDisplay);
366 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700367}
368
Lucas Dupind508e472020-11-04 04:32:06 +0000369bool SkiaGLRenderEngine::supportsProtectedContent() const {
370 return mProtectedEGLContext != EGL_NO_CONTEXT;
371}
372
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400373GrDirectContext* SkiaGLRenderEngine::getActiveGrContext() const {
374 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
375}
376
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400377void SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
378 if (useProtectedContext == mInProtectedContext ||
379 (useProtectedContext && !supportsProtectedContent())) {
380 return;
Lucas Dupind508e472020-11-04 04:32:06 +0000381 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400382
383 // release any scratch resources before switching into a new mode
384 if (getActiveGrContext()) {
385 getActiveGrContext()->purgeUnlockedResources(true);
386 }
387
Lucas Dupind508e472020-11-04 04:32:06 +0000388 const EGLSurface surface =
389 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
390 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
Alec Mouric0aae732021-01-12 13:32:18 -0800391
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400392 if (eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE) {
Lucas Dupind508e472020-11-04 04:32:06 +0000393 mInProtectedContext = useProtectedContext;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400394 // given that we are sharing the same thread between two GrContexts we need to
395 // make sure that the thread state is reset when switching between the two.
396 if (getActiveGrContext()) {
397 getActiveGrContext()->resetContext();
398 }
Lucas Dupind508e472020-11-04 04:32:06 +0000399 }
Lucas Dupind508e472020-11-04 04:32:06 +0000400}
401
John Reck67b1e2b2020-08-26 13:17:24 -0700402base::unique_fd SkiaGLRenderEngine::flush() {
403 ATRACE_CALL();
404 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
405 return base::unique_fd();
406 }
407
408 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
409 if (sync == EGL_NO_SYNC_KHR) {
410 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
411 return base::unique_fd();
412 }
413
414 // native fence fd will not be populated until flush() is done.
415 glFlush();
416
417 // get the fence fd
418 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
419 eglDestroySyncKHR(mEGLDisplay, sync);
420 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
421 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
422 }
423
424 return fenceFd;
425}
426
Alec Mouri4ee7b492021-08-11 10:36:55 -0700427void SkiaGLRenderEngine::waitFence(base::borrowed_fd fenceFd) {
428 if (fenceFd.get() >= 0 && !waitGpuFence(fenceFd)) {
429 ATRACE_NAME("SkiaGLRenderEngine::waitFence");
430 sync_wait(fenceFd.get(), -1);
431 }
432}
433
434bool SkiaGLRenderEngine::waitGpuFence(base::borrowed_fd fenceFd) {
John Reck67b1e2b2020-08-26 13:17:24 -0700435 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
436 !gl::GLExtensions::getInstance().hasWaitSync()) {
437 return false;
438 }
439
Alec Mouri4ee7b492021-08-11 10:36:55 -0700440 // Duplicate the fence for passing to eglCreateSyncKHR.
441 base::unique_fd fenceDup(dup(fenceFd.get()));
442 if (fenceDup.get() < 0) {
443 ALOGE("failed to create duplicate fence fd: %d", fenceDup.get());
444 return false;
445 }
446
John Reck67b1e2b2020-08-26 13:17:24 -0700447 // release the fd and transfer the ownership to EGLSync
Alec Mouri4ee7b492021-08-11 10:36:55 -0700448 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceDup.release(), EGL_NONE};
John Reck67b1e2b2020-08-26 13:17:24 -0700449 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
450 if (sync == EGL_NO_SYNC_KHR) {
451 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
452 return false;
453 }
454
455 // XXX: The spec draft is inconsistent as to whether this should return an
456 // EGLint or void. Ignore the return value for now, as it's not strictly
457 // needed.
458 eglWaitSyncKHR(mEGLDisplay, sync, 0);
459 EGLint error = eglGetError();
460 eglDestroySyncKHR(mEGLDisplay, sync);
461 if (error != EGL_SUCCESS) {
462 ALOGE("failed to wait for EGL native fence sync: %#x", error);
463 return false;
464 }
465
466 return true;
467}
468
Alec Mouri678245d2020-09-30 16:58:23 -0700469static float toDegrees(uint32_t transform) {
470 switch (transform) {
471 case ui::Transform::ROT_90:
472 return 90.0;
473 case ui::Transform::ROT_180:
474 return 180.0;
475 case ui::Transform::ROT_270:
476 return 270.0;
477 default:
478 return 0.0;
479 }
480}
481
Alec Mourib34f0b72020-10-02 13:18:34 -0700482static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
483 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
484 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
485 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
486 matrix[3][3], 0);
487}
488
Alec Mouri029d1952020-10-12 10:37:08 -0700489static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
490 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
491 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
492
493 // Treat unsupported dataspaces as srgb
494 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
495 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
496 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
497 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
498 }
499
500 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
501 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
502 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
503 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
504 }
505
506 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
507 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
508 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
509 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
510
511 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
512 sourceTransfer != destTransfer;
513}
514
Alec Mouria90a5702021-04-16 16:36:21 +0000515void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
516 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800517 // Only run this if RE is running on its own thread. This way the access to GL
518 // operations is guaranteed to be happening on the same thread.
519 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
520 return;
521 }
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400522 // We currently don't attempt to map a buffer if the buffer contains protected content
Derek Sollenberger45007182021-06-10 14:47:21 -0400523 // because GPU resources for protected buffers is much more limited.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400524 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Derek Sollenberger45007182021-06-10 14:47:21 -0400525 if (isProtectedBuffer) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400526 return;
527 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800528 ATRACE_CALL();
529
Derek Sollenberger45007182021-06-10 14:47:21 -0400530 // If we were to support caching protected buffers then we will need to switch the
531 // currently bound context if we are not already using the protected context (and subsequently
532 // switch back after the buffer is cached). However, for non-protected content we can bind
533 // the texture in either GL context because they are initialized with the same share_context
534 // which allows the texture state to be shared between them.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400535 auto grContext = getActiveGrContext();
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400536 auto& cache = mTextureCache;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400537
538 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000539 mGraphicBufferExternalRefs[buffer->getId()]++;
540
541 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800542 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400543 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400544 buffer->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400545 isRenderable, mTextureCleanupMgr);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400546 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800547 }
548}
549
Alec Mouria90a5702021-04-16 16:36:21 +0000550void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800551 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700552 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000553 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
554 iter != mGraphicBufferExternalRefs.end()) {
555 if (iter->second == 0) {
556 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
557 "> from RenderEngine texture, but the "
558 "ref count was already zero!",
559 buffer->getId());
560 mGraphicBufferExternalRefs.erase(buffer->getId());
561 return;
562 }
563
564 iter->second--;
565
Alec Mouric2ffeb42021-06-17 17:42:27 -0700566 // Swap contexts if needed prior to deleting this buffer
567 // See Issue 1 of
568 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
569 // when a protected context and an unprotected context are part of the same share group,
570 // protected surfaces may not be accessed by an unprotected context, implying that protected
571 // surfaces may only be freed when a protected context is active.
572 const bool inProtected = mInProtectedContext;
573 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
574
Alec Mouria90a5702021-04-16 16:36:21 +0000575 if (iter->second == 0) {
576 mTextureCache.erase(buffer->getId());
Alec Mouria90a5702021-04-16 16:36:21 +0000577 mGraphicBufferExternalRefs.erase(buffer->getId());
578 }
Alec Mouric2ffeb42021-06-17 17:42:27 -0700579
580 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
581 // are up-to-date.
582 if (inProtected != mInProtectedContext) {
583 useProtectedContext(inProtected);
584 }
Alec Mouria90a5702021-04-16 16:36:21 +0000585 }
John Reck67b1e2b2020-08-26 13:17:24 -0700586}
587
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400588bool SkiaGLRenderEngine::canSkipPostRenderCleanup() const {
589 std::lock_guard<std::mutex> lock(mRenderingMutex);
590 return mTextureCleanupMgr.isEmpty();
591}
592
593void SkiaGLRenderEngine::cleanupPostRender() {
594 ATRACE_CALL();
595 std::lock_guard<std::mutex> lock(mRenderingMutex);
596 mTextureCleanupMgr.cleanup();
597}
598
599// Helper class intended to be used on the stack to ensure that texture cleanup
600// is deferred until after this class goes out of scope.
601class DeferTextureCleanup final {
602public:
603 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
604 mMgr.setDeferredStatus(true);
605 }
606 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
607
608private:
609 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
610 AutoBackendTexture::CleanupManager& mMgr;
611};
612
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700613sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
614 const RuntimeEffectShaderParameters& parameters) {
Nader Jawad63644d32021-05-07 10:44:21 -0700615 // The given surface will be stretched by HWUI via matrix transformation
616 // which gets similar results for most surfaces
617 // Determine later on if we need to leverage the stertch shader within
618 // surface flinger
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700619 const auto& stretchEffect = parameters.layer.stretchEffect;
620 auto shader = parameters.shader;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700621 if (stretchEffect.hasEffect()) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700622 const auto targetBuffer = parameters.layer.source.buffer.buffer;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700623 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700624 if (graphicBuffer && parameters.shader) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700625 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
626 }
John Reckcdb4ed72021-02-04 13:39:33 -0500627 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700628
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700629 if (parameters.requiresLinearEffect) {
630 const ui::Dataspace inputDataspace = mUseColorManagement ? parameters.layer.sourceDataspace
631 : ui::Dataspace::V0_SRGB_LINEAR;
632 const ui::Dataspace outputDataspace = mUseColorManagement
633 ? parameters.display.outputDataspace
634 : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500635
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700636 auto effect =
637 shaders::LinearEffect{.inputDataspace = inputDataspace,
638 .outputDataspace = outputDataspace,
639 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha};
Ana Krulec47814212021-01-06 19:00:10 -0800640
641 auto effectIter = mRuntimeEffects.find(effect);
642 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
643 if (effectIter == mRuntimeEffects.end()) {
644 runtimeEffect = buildRuntimeEffect(effect);
645 mRuntimeEffects.insert({effect, runtimeEffect});
646 } else {
647 runtimeEffect = effectIter->second;
648 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700649 mat4 colorTransform = parameters.layer.colorTransform;
650
651 colorTransform *=
652 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
653 parameters.layerDimmingRatio, 1.f));
Alec Mouri1a3c5452022-03-04 22:44:51 +0000654 const auto targetBuffer = parameters.layer.source.buffer.buffer;
655 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
656 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700657 return createLinearEffectShader(parameters.shader, effect, runtimeEffect, colorTransform,
658 parameters.display.maxLuminance,
Alec Mourib21d94e2022-01-13 17:44:10 -0800659 parameters.display.currentLuminanceNits,
Alec Mouri1a3c5452022-03-04 22:44:51 +0000660 parameters.layer.source.buffer.maxLuminanceNits,
Alec Mourifcedb9c2022-04-11 20:02:17 +0000661 hardwareBuffer, parameters.display.renderIntent);
Ana Krulec47814212021-01-06 19:00:10 -0800662 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700663 return parameters.shader;
Ana Krulec47814212021-01-06 19:00:10 -0800664}
665
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500666void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500667 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500668 // Record display settings when capture is running.
669 std::stringstream displaySettings;
670 PrintTo(display, &displaySettings);
671 // Store the DisplaySettings in additional information.
672 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
673 SkData::MakeWithCString(displaySettings.str().c_str()));
674 }
675
676 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
677 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
678 // displays might have different scaling when compared to the physical screen.
679
680 canvas->clipRect(getSkRect(display.physicalDisplay));
681 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
682
683 const auto clipWidth = display.clip.width();
684 const auto clipHeight = display.clip.height();
685 auto rotatedClipWidth = clipWidth;
686 auto rotatedClipHeight = clipHeight;
687 // Scale is contingent on the rotation result.
688 if (display.orientation & ui::Transform::ROT_90) {
689 std::swap(rotatedClipWidth, rotatedClipHeight);
690 }
691 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
692 static_cast<SkScalar>(rotatedClipWidth);
693 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
694 static_cast<SkScalar>(rotatedClipHeight);
695 canvas->scale(scaleX, scaleY);
696
697 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
698 // back so that the top left corner of the clip is at (0, 0).
699 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
700 canvas->rotate(toDegrees(display.orientation));
701 canvas->translate(-clipWidth / 2, -clipHeight / 2);
702 canvas->translate(-display.clip.left, -display.clip.top);
703}
704
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500705class AutoSaveRestore {
706public:
707 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
708 ~AutoSaveRestore() { restore(); }
709 void replace(SkCanvas* canvas) {
710 mCanvas = canvas;
711 mSaveCount = canvas->save();
712 }
713 void restore() {
714 if (mCanvas) {
715 mCanvas->restoreToCount(mSaveCount);
716 mCanvas = nullptr;
717 }
718 }
719
720private:
721 SkCanvas* mCanvas;
722 int mSaveCount;
723};
724
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400725static SkRRect getBlurRRect(const BlurRegion& region) {
726 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
727 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
728 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
729 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
730 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
731 SkRRect roundedRect;
732 roundedRect.setRectRadii(rect, radii);
733 return roundedRect;
734}
735
Alec Mouri85065692022-03-18 00:58:26 +0000736// Arbitrary default margin which should be close enough to zero.
737constexpr float kDefaultMargin = 0.0001f;
738static bool equalsWithinMargin(float expected, float value, float margin = kDefaultMargin) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700739 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
740 return std::abs(expected - value) < margin;
741}
742
Leon Scroggins III191b8772022-04-06 14:38:22 -0400743namespace {
744template <typename T>
745void logSettings(const T& t) {
746 std::stringstream stream;
747 PrintTo(t, &stream);
748 auto string = stream.str();
749 size_t pos = 0;
750 // Perfetto ignores \n, so split up manually into separate ALOGD statements.
751 const size_t size = string.size();
752 while (pos < size) {
753 const size_t end = std::min(string.find("\n", pos), size);
754 ALOGD("%s", string.substr(pos, end - pos).c_str());
755 pos = end + 1;
756 }
757}
758} // namespace
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
Leon Scroggins III191b8772022-04-06 14:38:22 -0400869 if (kPrintLayerSettings) {
870 logSettings(display);
871 }
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) {
Leon Scroggins III191b8772022-04-06 14:38:22 -0400876 logSettings(layer);
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400877 }
878
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500879 sk_sp<SkImage> blurInput;
Sally Qi59a9f502021-10-12 18:53:23 +0000880 if (blurCompositionLayer == &layer) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500881 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
882 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
883
884 // save a snapshot of the activeSurface to use as input to the blur shaders
885 blurInput = activeSurface->makeImageSnapshot();
886
Leon Scroggins III55bf4742022-03-17 14:11:17 -0400887 // blit the offscreen framebuffer into the destination AHB, but only
888 // if there are blur regions. backgroundBlurRadius blurs the entire
889 // image below, so it can skip this step.
890 if (layer.blurRegions.size()) {
891 SkPaint paint;
892 paint.setBlendMode(SkBlendMode::kSrc);
893 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
894 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
895 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
896 String8::format("SurfaceID|%" PRId64, id).c_str(),
897 nullptr);
898 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
899 } else {
900 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
901 }
Derek Sollenberger76664d62021-02-04 11:13:09 -0500902 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500903
904 // assign dstCanvas to canvas and ensure that the canvas state is up to date
905 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500906 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500907 initCanvas(canvas, display);
908
909 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
910 dstSurface->getCanvas()->getSaveCount());
911 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
912 dstSurface->getCanvas()->getTotalMatrix());
913
914 // assign dstSurface to activeSurface
915 activeSurface = dstSurface;
916 }
917
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500918 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500919 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800920 // Record the name of the layer if the capture is running.
921 std::stringstream layerSettings;
Sally Qi59a9f502021-10-12 18:53:23 +0000922 PrintTo(layer, &layerSettings);
Ana Krulec6eab17a2020-12-09 15:52:36 -0800923 // Store the LayerSettings in additional information.
Sally Qi59a9f502021-10-12 18:53:23 +0000924 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
Ana Krulec6eab17a2020-12-09 15:52:36 -0800925 SkData::MakeWithCString(layerSettings.str().c_str()));
926 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100927 // Layers have a local transform that should be applied to them
Sally Qi59a9f502021-10-12 18:53:23 +0000928 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100929
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400930 const auto [bounds, roundRectClip] =
Sally Qi59a9f502021-10-12 18:53:23 +0000931 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
932 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400933 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500934 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
935
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500936 // if multiple layers have blur, then we need to take a snapshot now because
937 // only the lowest layer will have blurImage populated earlier
938 if (!blurInput) {
939 blurInput = activeSurface->makeImageSnapshot();
940 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500941 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400942 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
943
944 // if the clip needs to be applied then apply it now and make sure
945 // it is restored before we attempt to draw any shadows.
946 SkAutoCanvasRestore acr(canvas, true);
947 if (!roundRectClip.isEmpty()) {
948 canvas->clipRRect(roundRectClip, true);
949 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500950
Galia Peychevae425ac82021-03-15 17:12:03 +0100951 // TODO(b/182216890): Filter out empty layers earlier
952 if (blurRect.width() > 0 && blurRect.height() > 0) {
Sally Qi59a9f502021-10-12 18:53:23 +0000953 if (layer.backgroundBlurRadius > 0) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100954 ATRACE_NAME("BackgroundBlur");
Sally Qi59a9f502021-10-12 18:53:23 +0000955 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
956 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100957
Sally Qi59a9f502021-10-12 18:53:23 +0000958 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500959
Sally Qi59a9f502021-10-12 18:53:23 +0000960 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400961 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700962 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400963
Sally Qi59a9f502021-10-12 18:53:23 +0000964 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
965 for (auto region : layer.blurRegions) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100966 if (cachedBlurs[region.blurRadius] == nullptr) {
967 ATRACE_NAME("BlurRegion");
968 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400969 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100970 blurRect);
971 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500972
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400973 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
974 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100975 cachedBlurs[region.blurRadius], blurInput);
976 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700977 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700978 }
979
Sally Qi59a9f502021-10-12 18:53:23 +0000980 if (layer.shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400981 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
Sally Qi59a9f502021-10-12 18:53:23 +0000982 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
Leon Scroggins III63e86952021-05-12 10:45:08 -0400983
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400984 SkRRect shadowBounds, shadowClip;
Sally Qi59a9f502021-10-12 18:53:23 +0000985 if (layer.geometry.boundaries == layer.shadow.boundaries) {
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400986 shadowBounds = bounds;
987 shadowClip = roundRectClip;
988 } else {
989 std::tie(shadowBounds, shadowClip) =
Sally Qi59a9f502021-10-12 18:53:23 +0000990 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
991 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400992 }
993
Leon Scroggins III63e86952021-05-12 10:45:08 -0400994 // Technically, if bounds is a rect and roundRectClip is not empty,
995 // it means that the bounds and roundedCornersCrop were different
996 // enough that we should intersect them to find the proper shadow.
997 // In practice, this often happens when the two rectangles appear to
998 // not match due to rounding errors. Draw the rounded version, which
999 // looks more like the intent.
1000 const auto& rrect =
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001001 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
Sally Qi59a9f502021-10-12 18:53:23 +00001002 drawShadow(canvas, rrect, layer.shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001003 }
1004
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001005 const float layerDimmingRatio = layer.whitePointNits <= 0.f
1006 ? displayDimmingRatio
1007 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
1008
Alec Mouri85065692022-03-18 00:58:26 +00001009 const bool dimInLinearSpace = display.dimmingStage !=
1010 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
1011
Sally Qi59a9f502021-10-12 18:53:23 +00001012 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001013 (mUseColorManagement &&
Sally Qi59a9f502021-10-12 18:53:23 +00001014 needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
Alec Mouri85065692022-03-18 00:58:26 +00001015 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio));
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001016
1017 // quick abort from drawing the remaining portion of the layer
Sally Qi59a9f502021-10-12 18:53:23 +00001018 if (layer.skipContentDraw ||
1019 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001020 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001021 continue;
1022 }
1023
1024 // If we need to map to linear space or color management is disabled, then mark the source
1025 // image with the same colorspace as the destination surface so that Skia's color
1026 // management is a no-op.
1027 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
1028 ? dstDataspace
Sally Qi59a9f502021-10-12 18:53:23 +00001029 : layer.sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -08001030
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001031 SkPaint paint;
Sally Qi59a9f502021-10-12 18:53:23 +00001032 if (layer.source.buffer.buffer) {
John Reck67b1e2b2020-08-26 13:17:24 -07001033 ATRACE_NAME("DrawImage");
Sally Qi59a9f502021-10-12 18:53:23 +00001034 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
1035 const auto& item = layer.source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001036 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +00001037
1038 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
1039 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001040 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -07001041 } else {
Alec Mouria90a5702021-04-16 16:36:21 +00001042 // If we didn't find the image in the cache, then create a local ref but don't cache
1043 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
1044 // we didn't find anything in the cache then we intentionally did not cache this
1045 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001046 imageTextureRef = std::make_shared<
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001047 AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001048 item.buffer->getBuffer()->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -04001049 false, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -07001050 }
Alec Mouri1a4d0642020-11-13 17:42:01 -08001051
Alec Mouri4ee7b492021-08-11 10:36:55 -07001052 // if the layer's buffer has a fence, then we must must respect the fence prior to using
1053 // the buffer.
Sally Qi59a9f502021-10-12 18:53:23 +00001054 if (layer.source.buffer.fence != nullptr) {
1055 waitFence(layer.source.buffer.fence->get());
Alec Mouri4ee7b492021-08-11 10:36:55 -07001056 }
1057
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001058 // isOpaque means we need to ignore the alpha in the image,
1059 // replacing it with the alpha specified by the LayerSettings. See
1060 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
1061 // The proper way to do this is to use an SkColorType that ignores
1062 // alpha, like kRGB_888x_SkColorType, and that is used if the
1063 // incoming image is kRGBA_8888_SkColorType. However, the incoming
1064 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
1065 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
1066 // kRGB_101010x_SkColorType, but it is not yet supported as a source
1067 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
1068 // meantime, we'll use a workaround that works unless we need to do
1069 // any color conversion. The workaround requires that we pretend the
1070 // image is already premultiplied, so that we do not premultiply it
1071 // before applying SkBlendMode::kPlus.
1072 const bool useIsOpaqueWorkaround = item.isOpaque &&
1073 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
1074 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
1075 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
1076 : item.isOpaque ? kOpaque_SkAlphaType
1077 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
1078 : kUnpremul_SkAlphaType;
1079 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -07001080
1081 auto texMatrix = getSkM44(item.textureTransform).asM33();
1082 // textureTansform was intended to be passed directly into a shader, so when
1083 // building the total matrix with the textureTransform we need to first
1084 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001085 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001086 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -07001087
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001088 SkMatrix matrix;
1089 if (!texMatrix.invert(&matrix)) {
1090 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -07001091 }
Ana Krulecf9a15d92020-12-11 08:35:00 -08001092 // The shader does not respect the translation, so we add it to the texture
1093 // transform for the SkImage. This will make sure that the correct layer contents
1094 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001095 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -07001096
Ana Krulecb7b28b22020-11-23 14:48:58 -08001097 sk_sp<SkShader> shader;
1098
Sally Qi59a9f502021-10-12 18:53:23 +00001099 if (layer.source.buffer.useTextureFiltering) {
Ana Krulecb7b28b22020-11-23 14:48:58 -08001100 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1101 SkSamplingOptions(
1102 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1103 &matrix);
1104 } else {
Mike Reed711e1f02020-12-11 13:06:19 -05001105 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -08001106 }
Alec Mouri029d1952020-10-12 10:37:08 -07001107
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001108 if (useIsOpaqueWorkaround) {
Alec Mouric0aae732021-01-12 13:32:18 -08001109 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1110 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001111 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001112 }
1113
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001114 paint.setShader(createRuntimeEffectShader(
1115 RuntimeEffectShaderParameters{.shader = shader,
1116 .layer = layer,
1117 .display = display,
1118 .undoPremultipliedAlpha = !item.isOpaque &&
1119 item.usePremultipliedAlpha,
1120 .requiresLinearEffect = requiresLinearEffect,
Alec Mouri85065692022-03-18 00:58:26 +00001121 .layerDimmingRatio = dimInLinearSpace
1122 ? layerDimmingRatio
1123 : 1.f}));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001124
Alec Mouri88acab92022-03-24 23:41:01 +00001125 // Turn on dithering when dimming beyond this (arbitrary) threshold...
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001126 static constexpr float kDimmingThreshold = 0.2f;
Alec Mouri88acab92022-03-24 23:41:01 +00001127 // ...or we're rendering an HDR layer down to an 8-bit target
1128 // Most HDR standards require at least 10-bits of color depth for source content, so we
1129 // can just extract the transfer function rather than dig into precise gralloc layout.
1130 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
1131 const bool requiresDownsample = isHdrDataspace(layer.sourceDataspace) &&
1132 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
1133 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001134 paint.setDither(true);
1135 }
Sally Qi59a9f502021-10-12 18:53:23 +00001136 paint.setAlphaf(layer.alpha);
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001137
1138 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1139 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001140
1141 // SysUI creates the alpha layer as a coverage layer, which is
1142 // appropriate for the DPU. Use a color matrix to convert it to
1143 // a mask.
1144 // TODO (b/219525258): Handle input as a mask.
1145 //
1146 // The color matrix will convert A8 pixels with no alpha to
1147 // black, as described by this vector. If the display handles
1148 // the color transform, we need to invert it to find the color
1149 // that will result in black after the DPU applies the transform.
1150 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1151 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1152 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1153 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1154 black = colorSpaceMatrix * black;
1155 } else {
1156 // We'll just have to use 0,0,0 as black, which should
1157 // be close to correct.
1158 ALOGI("Could not invert colorTransform!");
1159 }
1160 }
1161 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1162 0, 0, 0, 0, black[1],
1163 0, 0, 0, 0, black[2],
1164 0, 0, 0, -1, 1);
1165 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1166 // On the other hand, if the device doesn't handle it, we
1167 // have to apply it ourselves.
1168 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1169 }
1170 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001171 }
John Reck67b1e2b2020-08-26 13:17:24 -07001172 } else {
1173 ATRACE_NAME("DrawColor");
Sally Qi59a9f502021-10-12 18:53:23 +00001174 const auto color = layer.source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001175 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1176 .fG = color.g,
1177 .fB = color.b,
Sally Qi59a9f502021-10-12 18:53:23 +00001178 .fA = layer.alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001179 toSkColorSpace(layerDataspace));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001180 paint.setShader(createRuntimeEffectShader(
1181 RuntimeEffectShaderParameters{.shader = shader,
1182 .layer = layer,
1183 .display = display,
1184 .undoPremultipliedAlpha = false,
1185 .requiresLinearEffect = requiresLinearEffect,
1186 .layerDimmingRatio = layerDimmingRatio}));
John Reck67b1e2b2020-08-26 13:17:24 -07001187 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001188
Sally Qi59a9f502021-10-12 18:53:23 +00001189 if (layer.disableBlending) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001190 paint.setBlendMode(SkBlendMode::kSrc);
1191 }
1192
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001193 // An A8 buffer will already have the proper color filter attached to
1194 // its paint, including the displayColorTransform as needed.
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001195 if (!paint.getColorFilter()) {
Alec Mouri85065692022-03-18 00:58:26 +00001196 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1197 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1198 // can assume a gamma 2.2 transfer function.
1199 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1200 const auto gammaCorrectedDimmingRatio =
1201 std::pow(layerDimmingRatio, kInverseGamma22);
Alec Mouri9bcd1d12022-04-21 22:16:56 +00001202 auto dimmingMatrix =
Alec Mouri85065692022-03-18 00:58:26 +00001203 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1204 gammaCorrectedDimmingRatio, 1.f));
Alec Mouri9bcd1d12022-04-21 22:16:56 +00001205
1206 const auto colorFilter =
1207 SkColorFilters::Matrix(toSkColorMatrix(std::move(dimmingMatrix)));
1208 paint.setColorFilter(displayColorTransform
1209 ? displayColorTransform->makeComposed(colorFilter)
1210 : colorFilter);
Alec Mouri85065692022-03-18 00:58:26 +00001211 } else {
1212 paint.setColorFilter(displayColorTransform);
1213 }
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001214 }
Alec Mourib34f0b72020-10-02 13:18:34 -07001215
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001216 if (!roundRectClip.isEmpty()) {
1217 canvas->clipRRect(roundRectClip, true);
1218 }
1219
1220 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001221 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001222 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001223 } else {
Nader Jawad63644d32021-05-07 10:44:21 -07001224 canvas->drawRect(bounds.rect(), paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -07001225 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001226 if (kFlushAfterEveryLayer) {
1227 ATRACE_NAME("flush surface");
1228 activeSurface->flush();
1229 }
John Reck67b1e2b2020-08-26 13:17:24 -07001230 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001231 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001232 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001233 {
1234 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001235 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1236 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001237 }
1238
Sally Qi4cabdd02021-08-05 16:45:57 -07001239 base::unique_fd drawFence = flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001240
1241 // If flush failed or we don't support native fences, we need to force the
1242 // gl command stream to be executed.
Sally Qi4cabdd02021-08-05 16:45:57 -07001243 bool requireSync = drawFence.get() < 0;
John Reck67b1e2b2020-08-26 13:17:24 -07001244 if (requireSync) {
1245 ATRACE_BEGIN("Submit(sync=true)");
1246 } else {
1247 ATRACE_BEGIN("Submit(sync=false)");
1248 }
Lucas Dupind508e472020-11-04 04:32:06 +00001249 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001250 ATRACE_END();
1251 if (!success) {
1252 ALOGE("Failed to flush RenderEngine commands");
1253 // Chances are, something illegal happened (either the caller passed
1254 // us bad parameters, or we messed up our shader generation).
Sally Qi4cabdd02021-08-05 16:45:57 -07001255 resultPromise->set_value({INVALID_OPERATION, std::move(drawFence)});
1256 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001257 }
1258
1259 // checkErrors();
Sally Qi4cabdd02021-08-05 16:45:57 -07001260 resultPromise->set_value({NO_ERROR, std::move(drawFence)});
1261 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001262}
1263
Lucas Dupin3f11e922020-09-22 17:31:04 -07001264inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1265 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1266}
1267
1268inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1269 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1270}
1271
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001272/**
1273 * Verifies that common, simple bounds + clip combinations can be converted into
1274 * a single RRect draw call returning true if possible. If true the radii parameter
1275 * will be filled with the correct radii values that combined with bounds param will
1276 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
1277 */
1278static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
1279 const SkRect& insetCrop, float cornerRadius,
1280 SkVector radii[4]) {
1281 const bool leftEqual = bounds.fLeft == crop.fLeft;
1282 const bool topEqual = bounds.fTop == crop.fTop;
1283 const bool rightEqual = bounds.fRight == crop.fRight;
1284 const bool bottomEqual = bounds.fBottom == crop.fBottom;
1285
1286 // In the event that the corners of the bounds only partially align with the crop we
1287 // need to ensure that the resulting shape can still be represented as a round rect.
1288 // In particular the round rect implementation will scale the value of all corner radii
1289 // if the sum of the radius along any edge is greater than the length of that edge.
1290 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
1291 const bool requiredWidth = bounds.width() > (cornerRadius * 2);
1292 const bool requiredHeight = bounds.height() > (cornerRadius * 2);
1293 if (!requiredWidth || !requiredHeight) {
1294 return false;
1295 }
1296
1297 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
1298 // contained within the cropped shape and does not need rounded.
1299 // compute the UpperLeft corner radius
1300 if (leftEqual && topEqual) {
1301 radii[0].set(cornerRadius, cornerRadius);
1302 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
1303 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
1304 radii[0].set(0, 0);
1305 } else {
1306 return false;
1307 }
1308 // compute the UpperRight corner radius
1309 if (rightEqual && topEqual) {
1310 radii[1].set(cornerRadius, cornerRadius);
1311 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
1312 (topEqual && bounds.fRight <= insetCrop.fRight)) {
1313 radii[1].set(0, 0);
1314 } else {
1315 return false;
1316 }
1317 // compute the BottomRight corner radius
1318 if (rightEqual && bottomEqual) {
1319 radii[2].set(cornerRadius, cornerRadius);
1320 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
1321 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
1322 radii[2].set(0, 0);
1323 } else {
1324 return false;
1325 }
1326 // compute the BottomLeft corner radius
1327 if (leftEqual && bottomEqual) {
1328 radii[3].set(cornerRadius, cornerRadius);
1329 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
1330 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
1331 radii[3].set(0, 0);
1332 } else {
1333 return false;
1334 }
1335
1336 return true;
1337}
1338
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001339inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(const FloatRect& boundsRect,
1340 const FloatRect& cropRect,
1341 const float cornerRadius) {
1342 const SkRect bounds = getSkRect(boundsRect);
1343 const SkRect crop = getSkRect(cropRect);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001344
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001345 SkRRect clip;
1346 if (cornerRadius > 0) {
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001347 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
1348 if (bounds == crop || crop.isEmpty()) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001349 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1350 }
1351
1352 // This makes an effort to speed up common, simple bounds + clip combinations by
1353 // converting them to a single RRect draw. It is possible there are other cases
1354 // that can be converted.
1355 if (crop.contains(bounds)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001356 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001357 if (insetCrop.contains(bounds)) {
1358 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001359 }
1360
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001361 SkVector radii[4];
1362 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001363 SkRRect intersectionBounds;
1364 intersectionBounds.setRectRadii(bounds, radii);
1365 return {intersectionBounds, clip};
1366 }
1367 }
1368
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001369 // we didn't hit any of our fast paths so set the clip to the cropRect
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001370 clip.setRectXY(crop, cornerRadius, cornerRadius);
1371 }
1372
1373 // if we hit this point then we either don't have rounded corners or we are going to rely
1374 // on the clip to round the corners for us
1375 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001376}
1377
Sally Qi59a9f502021-10-12 18:53:23 +00001378inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings& layer,
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001379 bool colorTransformModifiesAlpha) {
Sally Qi59a9f502021-10-12 18:53:23 +00001380 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001381 // return false if the content is opaque and would therefore occlude the blur
Sally Qi59a9f502021-10-12 18:53:23 +00001382 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
1383 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
1384 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001385 }
1386 return false;
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001387}
1388
Lucas Dupin3f11e922020-09-22 17:31:04 -07001389inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1390 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1391}
1392
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001393inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1394 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1395 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1396 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1397 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1398}
1399
Lucas Dupin3f11e922020-09-22 17:31:04 -07001400inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1401 return SkPoint3::Make(vector.x, vector.y, vector.z);
1402}
1403
John Reck67b1e2b2020-08-26 13:17:24 -07001404size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1405 return mGrContext->maxTextureSize();
1406}
1407
1408size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1409 return mGrContext->maxRenderTargetSize();
1410}
1411
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001412void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001413 const ShadowSettings& settings) {
1414 ATRACE_CALL();
1415 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001416 const auto flags =
1417 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1418
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001419 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001420 getSkPoint3(settings.lightPos), settings.lightRadius,
1421 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1422 flags);
1423}
1424
John Reck67b1e2b2020-08-26 13:17:24 -07001425EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001426 EGLContext shareContext,
1427 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001428 Protection protection) {
1429 EGLint renderableType = 0;
1430 if (config == EGL_NO_CONFIG_KHR) {
1431 renderableType = EGL_OPENGL_ES3_BIT;
1432 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1433 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1434 }
1435 EGLint contextClientVersion = 0;
1436 if (renderableType & EGL_OPENGL_ES3_BIT) {
1437 contextClientVersion = 3;
1438 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1439 contextClientVersion = 2;
1440 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1441 contextClientVersion = 1;
1442 } else {
1443 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1444 }
1445
1446 std::vector<EGLint> contextAttributes;
1447 contextAttributes.reserve(7);
1448 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1449 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001450 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001451 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001452 switch (*contextPriority) {
1453 case ContextPriority::REALTIME:
1454 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1455 break;
1456 case ContextPriority::MEDIUM:
1457 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1458 break;
1459 case ContextPriority::LOW:
1460 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1461 break;
1462 case ContextPriority::HIGH:
1463 default:
1464 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1465 break;
1466 }
John Reck67b1e2b2020-08-26 13:17:24 -07001467 }
1468 if (protection == Protection::PROTECTED) {
1469 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1470 contextAttributes.push_back(EGL_TRUE);
1471 }
1472 contextAttributes.push_back(EGL_NONE);
1473
1474 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1475
1476 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1477 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1478 // EGL_NO_CONTEXT so that we can abort.
1479 if (config != EGL_NO_CONFIG_KHR) {
1480 return context;
1481 }
1482 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1483 // should try to fall back to GLES 2.
1484 contextAttributes[1] = 2;
1485 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1486 }
1487
1488 return context;
1489}
1490
Alec Mourid6f09462020-12-07 11:18:17 -08001491std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1492 const RenderEngineCreationArgs& args) {
1493 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1494 return std::nullopt;
1495 }
1496
1497 switch (args.contextPriority) {
1498 case RenderEngine::ContextPriority::REALTIME:
1499 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1500 return RenderEngine::ContextPriority::REALTIME;
1501 } else {
1502 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1503 return RenderEngine::ContextPriority::HIGH;
1504 }
1505 case RenderEngine::ContextPriority::HIGH:
1506 case RenderEngine::ContextPriority::MEDIUM:
1507 case RenderEngine::ContextPriority::LOW:
1508 return args.contextPriority;
1509 default:
1510 return std::nullopt;
1511 }
1512}
1513
John Reck67b1e2b2020-08-26 13:17:24 -07001514EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1515 EGLConfig config, int hwcFormat,
1516 Protection protection) {
1517 EGLConfig placeholderConfig = config;
1518 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1519 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1520 }
1521 std::vector<EGLint> attributes;
1522 attributes.reserve(7);
1523 attributes.push_back(EGL_WIDTH);
1524 attributes.push_back(1);
1525 attributes.push_back(EGL_HEIGHT);
1526 attributes.push_back(1);
1527 if (protection == Protection::PROTECTED) {
1528 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1529 attributes.push_back(EGL_TRUE);
1530 }
1531 attributes.push_back(EGL_NONE);
1532
1533 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1534}
1535
Alec Mourid6f09462020-12-07 11:18:17 -08001536int SkiaGLRenderEngine::getContextPriority() {
1537 int value;
1538 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1539 return value;
1540}
1541
Ady Abrahamed3290f2021-05-17 15:12:14 -07001542void SkiaGLRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001543 // This cache multiplier was selected based on review of cache sizes relative
1544 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1545 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1546 // conservative default based on that analysis.
1547 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1548 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1549
1550 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001551 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001552
1553 // if it is possible to switch contexts then we will resize the other context
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001554 const bool originalProtectedState = mInProtectedContext;
1555 useProtectedContext(!mInProtectedContext);
1556 if (mInProtectedContext != originalProtectedState) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001557 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001558 // reset back to the initial context that was active when this method was called
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001559 useProtectedContext(originalProtectedState);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001560 }
1561}
1562
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001563void SkiaGLRenderEngine::dump(std::string& result) {
1564 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1565
1566 StringAppendF(&result, "\n ------------RE-----------------\n");
1567 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1568 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1569 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1570 extensions.getVersion());
1571 StringAppendF(&result, "%s\n", extensions.getExtensions());
1572 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1573 supportsProtectedContent());
1574 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001575 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1576 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001577
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001578 std::vector<ResourcePair> cpuResourceMap = {
1579 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1580 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1581 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1582 {"skia/sk_resource_cache/tessellated", "Shadows"},
1583 {"skia", "Other"},
1584 };
1585 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1586 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1587 StringAppendF(&result, "Skia CPU Caches: ");
1588 cpuReporter.logTotals(result);
1589 cpuReporter.logOutput(result);
1590
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001591 {
1592 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001593
1594 std::vector<ResourcePair> gpuResourceMap = {
1595 {"texture_renderbuffer", "Texture/RenderBuffer"},
1596 {"texture", "Texture"},
1597 {"gr_text_blob_cache", "Text"},
1598 {"skia", "Other"},
1599 };
1600 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1601 mGrContext->dumpMemoryStatistics(&gpuReporter);
1602 StringAppendF(&result, "Skia's GPU Caches: ");
1603 gpuReporter.logTotals(result);
1604 gpuReporter.logOutput(result);
1605 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1606 gpuReporter.logOutput(result, true);
1607
Alec Mouria90a5702021-04-16 16:36:21 +00001608 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1609 mGraphicBufferExternalRefs.size());
1610 StringAppendF(&result, "Dumping buffer ids...\n");
1611 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1612 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1613 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001614 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1615 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001616 StringAppendF(&result, "Dumping buffer ids...\n");
1617 // TODO(178539829): It would be nice to know which layer these are coming from and what
1618 // the texture sizes are.
1619 for (const auto& [id, unused] : mTextureCache) {
1620 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1621 }
1622 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001623
1624 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001625 if (mProtectedGrContext) {
1626 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1627 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001628 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1629 gpuProtectedReporter.logTotals(result);
1630 gpuProtectedReporter.logOutput(result);
1631 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1632 gpuProtectedReporter.logOutput(result, true);
1633
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001634 StringAppendF(&result, "\n");
1635 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1636 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1637 StringAppendF(&result, "- inputDataspace: %s\n",
1638 dataspaceDetails(
1639 static_cast<android_dataspace>(linearEffect.inputDataspace))
1640 .c_str());
1641 StringAppendF(&result, "- outputDataspace: %s\n",
1642 dataspaceDetails(
1643 static_cast<android_dataspace>(linearEffect.outputDataspace))
1644 .c_str());
1645 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1646 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1647 }
1648 }
1649 StringAppendF(&result, "\n");
1650}
1651
John Reck67b1e2b2020-08-26 13:17:24 -07001652} // namespace skia
1653} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001654} // namespace android