blob: a0bba593e39f9f026b60342e3bdc5a9902bb3896 [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>
Kevin Lubickbd9374e2022-04-22 15:09:19 -040043#include <SkPoint3.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000044#include <SkRect.h>
45#include <SkRefCnt.h>
Alec Mouric0aae732021-01-12 13:32:18 -080046#include <SkRegion.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000047#include <SkRRect.h>
48#include <SkRuntimeEffect.h>
49#include <SkSamplingOptions.h>
50#include <SkScalar.h>
51#include <SkShader.h>
Lucas Dupin3f11e922020-09-22 17:31:04 -070052#include <SkShadowUtils.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000053#include <SkString.h>
John Reck67b1e2b2020-08-26 13:17:24 -070054#include <SkSurface.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000055#include <SkTileMode.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080056#include <android-base/stringprintf.h>
Alec Mourib5777452020-09-28 11:32:42 -070057#include <gl/GrGLInterface.h>
Alec Mouricbd30932021-06-09 15:52:25 -070058#include <gui/TraceUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080059#include <sync/sync.h>
60#include <ui/BlurRegion.h>
Alec Mouri88acab92022-03-24 23:41:01 +000061#include <ui/DataspaceUtils.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080062#include <ui/DebugUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080063#include <ui/GraphicBuffer.h>
64#include <utils/Trace.h>
Alec Mourib5777452020-09-28 11:32:42 -070065
66#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080067#include <cstdint>
68#include <memory>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070069#include <numeric>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080070
71#include "../gl/GLExtensions.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040072#include "Cache.h"
Alec Mouric0aae732021-01-12 13:32:18 -080073#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080074#include "filters/BlurFilter.h"
Robin Lee26dacab2021-08-09 14:31:01 +020075#include "filters/GaussianBlurFilter.h"
Robin Lee026680a2021-07-26 12:49:53 +020076#include "filters/KawaseBlurFilter.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080077#include "filters/LinearEffect.h"
78#include "log/log_main.h"
79#include "skia/debug/SkiaCapture.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040080#include "skia/debug/SkiaMemoryReporter.h"
Nader Jawad2dfc98b2021-04-08 20:35:39 -070081#include "skia/filters/StretchShaderFactory.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080082#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070083
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040084namespace {
85// Debugging settings
86static const bool kPrintLayerSettings = false;
Leon Scroggins III191b8772022-04-06 14:38:22 -040087static const bool kFlushAfterEveryLayer = kPrintLayerSettings;
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040088} // namespace
89
John Reck67b1e2b2020-08-26 13:17:24 -070090bool checkGlError(const char* op, int lineNumber);
91
92namespace android {
93namespace renderengine {
94namespace skia {
95
Ana Krulec1d12b3b2021-01-27 16:49:51 -080096using base::StringAppendF;
97
John Reck67b1e2b2020-08-26 13:17:24 -070098static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
99 EGLint wanted, EGLConfig* outConfig) {
100 EGLint numConfigs = -1, n = 0;
101 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
102 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
103 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
104 configs.resize(n);
105
106 if (!configs.empty()) {
107 if (attribute != EGL_NONE) {
108 for (EGLConfig config : configs) {
109 EGLint value = 0;
110 eglGetConfigAttrib(dpy, config, attribute, &value);
111 if (wanted == value) {
112 *outConfig = config;
113 return NO_ERROR;
114 }
115 }
116 } else {
117 // just pick the first one
118 *outConfig = configs[0];
119 return NO_ERROR;
120 }
121 }
122
123 return NAME_NOT_FOUND;
124}
125
126static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
127 EGLConfig* config) {
128 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
129 // it is to be used with WIFI displays
130 status_t err;
131 EGLint wantedAttribute;
132 EGLint wantedAttributeValue;
133
134 std::vector<EGLint> attribs;
135 if (renderableType) {
136 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
137 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
138
139 // Default to 8 bits per channel.
140 const EGLint tmpAttribs[] = {
141 EGL_RENDERABLE_TYPE,
142 renderableType,
143 EGL_RECORDABLE_ANDROID,
144 EGL_TRUE,
145 EGL_SURFACE_TYPE,
146 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
147 EGL_FRAMEBUFFER_TARGET_ANDROID,
148 EGL_TRUE,
149 EGL_RED_SIZE,
150 is1010102 ? 10 : 8,
151 EGL_GREEN_SIZE,
152 is1010102 ? 10 : 8,
153 EGL_BLUE_SIZE,
154 is1010102 ? 10 : 8,
155 EGL_ALPHA_SIZE,
156 is1010102 ? 2 : 8,
157 EGL_NONE,
158 };
159 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
160 std::back_inserter(attribs));
161 wantedAttribute = EGL_NONE;
162 wantedAttributeValue = EGL_NONE;
163 } else {
164 // if no renderable type specified, fallback to a simplified query
165 wantedAttribute = EGL_NATIVE_VISUAL_ID;
166 wantedAttributeValue = format;
167 }
168
169 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
170 config);
171 if (err == NO_ERROR) {
172 EGLint caveat;
173 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
174 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
175 }
176
177 return err;
178}
179
180std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
181 const RenderEngineCreationArgs& args) {
182 // initialize EGL for the default display
183 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
184 if (!eglInitialize(display, nullptr, nullptr)) {
185 LOG_ALWAYS_FATAL("failed to initialize EGL");
186 }
187
Yiwei Zhange2650962020-12-01 23:27:58 +0000188 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700189 if (!eglVersion) {
190 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000191 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700192 }
193
Yiwei Zhange2650962020-12-01 23:27:58 +0000194 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700195 if (!eglExtensions) {
196 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000197 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700198 }
199
200 auto& extensions = gl::GLExtensions::getInstance();
201 extensions.initWithEGLStrings(eglVersion, eglExtensions);
202
203 // The code assumes that ES2 or later is available if this extension is
204 // supported.
205 EGLConfig config = EGL_NO_CONFIG_KHR;
206 if (!extensions.hasNoConfigContext()) {
207 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
208 }
209
John Reck67b1e2b2020-08-26 13:17:24 -0700210 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800211 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700212 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800213 protectedContext =
214 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700215 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
216 }
217
Alec Mourid6f09462020-12-07 11:18:17 -0800218 EGLContext ctxt =
219 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700220
221 // if can't create a GL context, we can only abort.
222 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
223
224 EGLSurface placeholder = EGL_NO_SURFACE;
225 if (!extensions.hasSurfacelessContext()) {
226 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
227 Protection::UNPROTECTED);
228 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
229 }
230 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
231 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
232 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
233 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
234
235 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
236 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
237 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
238 Protection::PROTECTED);
239 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
240 "can't create protected placeholder pbuffer");
241 }
242
243 // initialize the renderer while GL is current
244 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000245 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
246 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700247
248 ALOGI("OpenGL ES informations:");
249 ALOGI("vendor : %s", extensions.getVendor());
250 ALOGI("renderer : %s", extensions.getRenderer());
251 ALOGI("version : %s", extensions.getVersion());
252 ALOGI("extensions: %s", extensions.getExtensions());
253 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
254 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
255
256 return engine;
257}
258
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700259std::future<void> SkiaGLRenderEngine::primeCache() {
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500260 Cache::primeShaderCache(this);
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700261 return {};
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500262}
263
John Reck67b1e2b2020-08-26 13:17:24 -0700264EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
265 status_t err;
266 EGLConfig config;
267
268 // First try to get an ES3 config
269 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
270 if (err != NO_ERROR) {
271 // If ES3 fails, try to get an ES2 config
272 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
273 if (err != NO_ERROR) {
274 // If ES2 still doesn't work, probably because we're on the emulator.
275 // try a simplified query
276 ALOGW("no suitable EGLConfig found, trying a simpler query");
277 err = selectEGLConfig(display, format, 0, &config);
278 if (err != NO_ERROR) {
279 // this EGL is too lame for android
280 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
281 }
282 }
283 }
284
285 if (logConfig) {
286 // print some debugging info
287 EGLint r, g, b, a;
288 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
289 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
290 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
291 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
292 ALOGI("EGL information:");
293 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
294 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
295 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
296 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
297 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
298 }
299
300 return config;
301}
302
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400303sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
304 // This "cache" does not actually cache anything. It just allows us to
305 // monitor Skia's internal cache. So this method always returns null.
306 return nullptr;
307}
308
309void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
310 const SkString& description) {
311 mShadersCachedSinceLastCall++;
Leon Scroggins IIIadf18d82022-04-22 13:23:05 -0400312 mTotalShadersCompiled++;
313 ATRACE_FORMAT("SF cache: %i shaders", mTotalShadersCompiled);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400314}
315
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400316int SkiaGLRenderEngine::reportShadersCompiled() {
Leon Scroggins III45be9182022-04-27 10:37:11 -0400317 return mSkSLCacheMonitor.totalShadersCompiled();
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400318}
319
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700320SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000321 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700322 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800323 : SkiaRenderEngine(args.renderEngineType),
324 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700325 mEGLContext(ctxt),
326 mPlaceholderSurface(placeholder),
327 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700328 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400329 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800330 mUseColorManagement(args.useColorManagement) {
Brian Salomon40de6ba2022-03-22 19:38:53 +0000331 sk_sp<const GrGLInterface> glInterface = GrGLMakeNativeInterface();
John Reck67b1e2b2020-08-26 13:17:24 -0700332 LOG_ALWAYS_FATAL_IF(!glInterface.get());
333
334 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400335 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700336 options.fDisableDistanceFieldPaths = true;
Nathaniel Nifongf8d35e92021-06-08 15:02:25 -0400337 options.fReducedShaderVariations = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400338 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000339 mGrContext = GrDirectContext::MakeGL(glInterface, options);
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400340 if (supportsProtectedContent()) {
341 useProtectedContext(true);
Lucas Dupind508e472020-11-04 04:32:06 +0000342 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
343 useProtectedContext(false);
344 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700345
346 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500347 ALOGD("Background Blurs Enabled");
Robin Lee026680a2021-07-26 12:49:53 +0200348 mBlurFilter = new KawaseBlurFilter();
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700349 }
Alec Mouric0aae732021-01-12 13:32:18 -0800350 mCapture = std::make_unique<SkiaCapture>();
351}
352
353SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100354 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800355 if (mBlurFilter) {
356 delete mBlurFilter;
357 }
358
359 mCapture = nullptr;
360
361 mGrContext->flushAndSubmit(true);
362 mGrContext->abandonContext();
363
364 if (mProtectedGrContext) {
365 mProtectedGrContext->flushAndSubmit(true);
366 mProtectedGrContext->abandonContext();
367 }
368
369 if (mPlaceholderSurface != EGL_NO_SURFACE) {
370 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
371 }
372 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
373 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
374 }
375 if (mEGLContext != EGL_NO_CONTEXT) {
376 eglDestroyContext(mEGLDisplay, mEGLContext);
377 }
378 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
379 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
380 }
381 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
382 eglTerminate(mEGLDisplay);
383 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700384}
385
Lucas Dupind508e472020-11-04 04:32:06 +0000386bool SkiaGLRenderEngine::supportsProtectedContent() const {
387 return mProtectedEGLContext != EGL_NO_CONTEXT;
388}
389
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400390GrDirectContext* SkiaGLRenderEngine::getActiveGrContext() const {
391 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
392}
393
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400394void SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
395 if (useProtectedContext == mInProtectedContext ||
396 (useProtectedContext && !supportsProtectedContent())) {
397 return;
Lucas Dupind508e472020-11-04 04:32:06 +0000398 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400399
400 // release any scratch resources before switching into a new mode
401 if (getActiveGrContext()) {
402 getActiveGrContext()->purgeUnlockedResources(true);
403 }
404
Lucas Dupind508e472020-11-04 04:32:06 +0000405 const EGLSurface surface =
406 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
407 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
Alec Mouric0aae732021-01-12 13:32:18 -0800408
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400409 if (eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE) {
Lucas Dupind508e472020-11-04 04:32:06 +0000410 mInProtectedContext = useProtectedContext;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400411 // given that we are sharing the same thread between two GrContexts we need to
412 // make sure that the thread state is reset when switching between the two.
413 if (getActiveGrContext()) {
414 getActiveGrContext()->resetContext();
415 }
Lucas Dupind508e472020-11-04 04:32:06 +0000416 }
Lucas Dupind508e472020-11-04 04:32:06 +0000417}
418
John Reck67b1e2b2020-08-26 13:17:24 -0700419base::unique_fd SkiaGLRenderEngine::flush() {
420 ATRACE_CALL();
421 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
422 return base::unique_fd();
423 }
424
425 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
426 if (sync == EGL_NO_SYNC_KHR) {
427 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
428 return base::unique_fd();
429 }
430
431 // native fence fd will not be populated until flush() is done.
432 glFlush();
433
434 // get the fence fd
435 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
436 eglDestroySyncKHR(mEGLDisplay, sync);
437 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
438 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
439 }
440
441 return fenceFd;
442}
443
Alec Mouri4ee7b492021-08-11 10:36:55 -0700444void SkiaGLRenderEngine::waitFence(base::borrowed_fd fenceFd) {
445 if (fenceFd.get() >= 0 && !waitGpuFence(fenceFd)) {
446 ATRACE_NAME("SkiaGLRenderEngine::waitFence");
447 sync_wait(fenceFd.get(), -1);
448 }
449}
450
451bool SkiaGLRenderEngine::waitGpuFence(base::borrowed_fd fenceFd) {
John Reck67b1e2b2020-08-26 13:17:24 -0700452 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
453 !gl::GLExtensions::getInstance().hasWaitSync()) {
454 return false;
455 }
456
Alec Mouri4ee7b492021-08-11 10:36:55 -0700457 // Duplicate the fence for passing to eglCreateSyncKHR.
458 base::unique_fd fenceDup(dup(fenceFd.get()));
459 if (fenceDup.get() < 0) {
460 ALOGE("failed to create duplicate fence fd: %d", fenceDup.get());
461 return false;
462 }
463
John Reck67b1e2b2020-08-26 13:17:24 -0700464 // release the fd and transfer the ownership to EGLSync
Alec Mouri4ee7b492021-08-11 10:36:55 -0700465 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceDup.release(), EGL_NONE};
John Reck67b1e2b2020-08-26 13:17:24 -0700466 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
467 if (sync == EGL_NO_SYNC_KHR) {
468 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
469 return false;
470 }
471
472 // XXX: The spec draft is inconsistent as to whether this should return an
473 // EGLint or void. Ignore the return value for now, as it's not strictly
474 // needed.
475 eglWaitSyncKHR(mEGLDisplay, sync, 0);
476 EGLint error = eglGetError();
477 eglDestroySyncKHR(mEGLDisplay, sync);
478 if (error != EGL_SUCCESS) {
479 ALOGE("failed to wait for EGL native fence sync: %#x", error);
480 return false;
481 }
482
483 return true;
484}
485
Alec Mouri678245d2020-09-30 16:58:23 -0700486static float toDegrees(uint32_t transform) {
487 switch (transform) {
488 case ui::Transform::ROT_90:
489 return 90.0;
490 case ui::Transform::ROT_180:
491 return 180.0;
492 case ui::Transform::ROT_270:
493 return 270.0;
494 default:
495 return 0.0;
496 }
497}
498
Alec Mourib34f0b72020-10-02 13:18:34 -0700499static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
500 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
501 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
502 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
503 matrix[3][3], 0);
504}
505
Alec Mouri029d1952020-10-12 10:37:08 -0700506static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
507 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
508 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
509
510 // Treat unsupported dataspaces as srgb
511 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
512 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
513 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
514 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
515 }
516
517 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
518 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
519 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
520 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
521 }
522
523 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
524 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
525 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
526 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
527
528 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
529 sourceTransfer != destTransfer;
530}
531
Alec Mouria90a5702021-04-16 16:36:21 +0000532void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
533 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800534 // Only run this if RE is running on its own thread. This way the access to GL
535 // operations is guaranteed to be happening on the same thread.
536 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
537 return;
538 }
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400539 // We currently don't attempt to map a buffer if the buffer contains protected content
Derek Sollenberger45007182021-06-10 14:47:21 -0400540 // because GPU resources for protected buffers is much more limited.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400541 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Derek Sollenberger45007182021-06-10 14:47:21 -0400542 if (isProtectedBuffer) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400543 return;
544 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800545 ATRACE_CALL();
546
Derek Sollenberger45007182021-06-10 14:47:21 -0400547 // If we were to support caching protected buffers then we will need to switch the
548 // currently bound context if we are not already using the protected context (and subsequently
549 // switch back after the buffer is cached). However, for non-protected content we can bind
550 // the texture in either GL context because they are initialized with the same share_context
551 // which allows the texture state to be shared between them.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400552 auto grContext = getActiveGrContext();
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400553 auto& cache = mTextureCache;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400554
555 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000556 mGraphicBufferExternalRefs[buffer->getId()]++;
557
558 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800559 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400560 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400561 buffer->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400562 isRenderable, mTextureCleanupMgr);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400563 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800564 }
565}
566
Alec Mouria90a5702021-04-16 16:36:21 +0000567void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800568 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700569 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000570 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
571 iter != mGraphicBufferExternalRefs.end()) {
572 if (iter->second == 0) {
573 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
574 "> from RenderEngine texture, but the "
575 "ref count was already zero!",
576 buffer->getId());
577 mGraphicBufferExternalRefs.erase(buffer->getId());
578 return;
579 }
580
581 iter->second--;
582
Alec Mouric2ffeb42021-06-17 17:42:27 -0700583 // Swap contexts if needed prior to deleting this buffer
584 // See Issue 1 of
585 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
586 // when a protected context and an unprotected context are part of the same share group,
587 // protected surfaces may not be accessed by an unprotected context, implying that protected
588 // surfaces may only be freed when a protected context is active.
589 const bool inProtected = mInProtectedContext;
590 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
591
Alec Mouria90a5702021-04-16 16:36:21 +0000592 if (iter->second == 0) {
593 mTextureCache.erase(buffer->getId());
Alec Mouria90a5702021-04-16 16:36:21 +0000594 mGraphicBufferExternalRefs.erase(buffer->getId());
595 }
Alec Mouric2ffeb42021-06-17 17:42:27 -0700596
597 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
598 // are up-to-date.
599 if (inProtected != mInProtectedContext) {
600 useProtectedContext(inProtected);
601 }
Alec Mouria90a5702021-04-16 16:36:21 +0000602 }
John Reck67b1e2b2020-08-26 13:17:24 -0700603}
604
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400605bool SkiaGLRenderEngine::canSkipPostRenderCleanup() const {
606 std::lock_guard<std::mutex> lock(mRenderingMutex);
607 return mTextureCleanupMgr.isEmpty();
608}
609
610void SkiaGLRenderEngine::cleanupPostRender() {
611 ATRACE_CALL();
612 std::lock_guard<std::mutex> lock(mRenderingMutex);
613 mTextureCleanupMgr.cleanup();
614}
615
616// Helper class intended to be used on the stack to ensure that texture cleanup
617// is deferred until after this class goes out of scope.
618class DeferTextureCleanup final {
619public:
620 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
621 mMgr.setDeferredStatus(true);
622 }
623 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
624
625private:
626 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
627 AutoBackendTexture::CleanupManager& mMgr;
628};
629
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700630sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
631 const RuntimeEffectShaderParameters& parameters) {
Nader Jawad63644d32021-05-07 10:44:21 -0700632 // The given surface will be stretched by HWUI via matrix transformation
633 // which gets similar results for most surfaces
634 // Determine later on if we need to leverage the stertch shader within
635 // surface flinger
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700636 const auto& stretchEffect = parameters.layer.stretchEffect;
637 auto shader = parameters.shader;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700638 if (stretchEffect.hasEffect()) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700639 const auto targetBuffer = parameters.layer.source.buffer.buffer;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700640 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700641 if (graphicBuffer && parameters.shader) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700642 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
643 }
John Reckcdb4ed72021-02-04 13:39:33 -0500644 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700645
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700646 if (parameters.requiresLinearEffect) {
647 const ui::Dataspace inputDataspace = mUseColorManagement ? parameters.layer.sourceDataspace
648 : ui::Dataspace::V0_SRGB_LINEAR;
649 const ui::Dataspace outputDataspace = mUseColorManagement
650 ? parameters.display.outputDataspace
651 : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500652
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700653 auto effect =
654 shaders::LinearEffect{.inputDataspace = inputDataspace,
655 .outputDataspace = outputDataspace,
656 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha};
Ana Krulec47814212021-01-06 19:00:10 -0800657
658 auto effectIter = mRuntimeEffects.find(effect);
659 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
660 if (effectIter == mRuntimeEffects.end()) {
661 runtimeEffect = buildRuntimeEffect(effect);
662 mRuntimeEffects.insert({effect, runtimeEffect});
663 } else {
664 runtimeEffect = effectIter->second;
665 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700666 mat4 colorTransform = parameters.layer.colorTransform;
667
668 colorTransform *=
669 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
670 parameters.layerDimmingRatio, 1.f));
Alec Mouri1a3c5452022-03-04 22:44:51 +0000671 const auto targetBuffer = parameters.layer.source.buffer.buffer;
672 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
673 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700674 return createLinearEffectShader(parameters.shader, effect, runtimeEffect, colorTransform,
675 parameters.display.maxLuminance,
Alec Mourib21d94e2022-01-13 17:44:10 -0800676 parameters.display.currentLuminanceNits,
Alec Mouri1a3c5452022-03-04 22:44:51 +0000677 parameters.layer.source.buffer.maxLuminanceNits,
Alec Mourifcedb9c2022-04-11 20:02:17 +0000678 hardwareBuffer, parameters.display.renderIntent);
Ana Krulec47814212021-01-06 19:00:10 -0800679 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700680 return parameters.shader;
Ana Krulec47814212021-01-06 19:00:10 -0800681}
682
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500683void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500684 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500685 // Record display settings when capture is running.
686 std::stringstream displaySettings;
687 PrintTo(display, &displaySettings);
688 // Store the DisplaySettings in additional information.
689 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
690 SkData::MakeWithCString(displaySettings.str().c_str()));
691 }
692
693 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
694 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
695 // displays might have different scaling when compared to the physical screen.
696
697 canvas->clipRect(getSkRect(display.physicalDisplay));
698 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
699
700 const auto clipWidth = display.clip.width();
701 const auto clipHeight = display.clip.height();
702 auto rotatedClipWidth = clipWidth;
703 auto rotatedClipHeight = clipHeight;
704 // Scale is contingent on the rotation result.
705 if (display.orientation & ui::Transform::ROT_90) {
706 std::swap(rotatedClipWidth, rotatedClipHeight);
707 }
708 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
709 static_cast<SkScalar>(rotatedClipWidth);
710 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
711 static_cast<SkScalar>(rotatedClipHeight);
712 canvas->scale(scaleX, scaleY);
713
714 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
715 // back so that the top left corner of the clip is at (0, 0).
716 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
717 canvas->rotate(toDegrees(display.orientation));
718 canvas->translate(-clipWidth / 2, -clipHeight / 2);
719 canvas->translate(-display.clip.left, -display.clip.top);
720}
721
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500722class AutoSaveRestore {
723public:
724 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
725 ~AutoSaveRestore() { restore(); }
726 void replace(SkCanvas* canvas) {
727 mCanvas = canvas;
728 mSaveCount = canvas->save();
729 }
730 void restore() {
731 if (mCanvas) {
732 mCanvas->restoreToCount(mSaveCount);
733 mCanvas = nullptr;
734 }
735 }
736
737private:
738 SkCanvas* mCanvas;
739 int mSaveCount;
740};
741
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400742static SkRRect getBlurRRect(const BlurRegion& region) {
743 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
744 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
745 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
746 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
747 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
748 SkRRect roundedRect;
749 roundedRect.setRectRadii(rect, radii);
750 return roundedRect;
751}
752
Alec Mouri30835f22022-03-18 00:58:26 +0000753// Arbitrary default margin which should be close enough to zero.
754constexpr float kDefaultMargin = 0.0001f;
755static bool equalsWithinMargin(float expected, float value, float margin = kDefaultMargin) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700756 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
757 return std::abs(expected - value) < margin;
758}
759
Leon Scroggins III191b8772022-04-06 14:38:22 -0400760namespace {
761template <typename T>
762void logSettings(const T& t) {
763 std::stringstream stream;
764 PrintTo(t, &stream);
765 auto string = stream.str();
766 size_t pos = 0;
767 // Perfetto ignores \n, so split up manually into separate ALOGD statements.
768 const size_t size = string.size();
769 while (pos < size) {
770 const size_t end = std::min(string.find("\n", pos), size);
771 ALOGD("%s", string.substr(pos, end - pos).c_str());
772 pos = end + 1;
773 }
774}
775} // namespace
776
Sally Qi4cabdd02021-08-05 16:45:57 -0700777void SkiaGLRenderEngine::drawLayersInternal(
778 const std::shared_ptr<std::promise<RenderEngineResult>>&& resultPromise,
Sally Qi59a9f502021-10-12 18:53:23 +0000779 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
Sally Qi4cabdd02021-08-05 16:45:57 -0700780 const std::shared_ptr<ExternalTexture>& buffer, const bool /*useFramebufferCache*/,
781 base::unique_fd&& bufferFence) {
Sally Qi722c8562022-06-09 21:54:06 -0700782 ATRACE_NAME("SkiaGL::drawLayersInternal");
Alec Mouric0aae732021-01-12 13:32:18 -0800783
John Reck67b1e2b2020-08-26 13:17:24 -0700784 std::lock_guard<std::mutex> lock(mRenderingMutex);
John Reck67b1e2b2020-08-26 13:17:24 -0700785 if (buffer == nullptr) {
786 ALOGE("No output buffer provided. Aborting GPU composition.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700787 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
788 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700789 }
790
Alec Mouria90a5702021-04-16 16:36:21 +0000791 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800792
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400793 auto grContext = getActiveGrContext();
Derek Sollenberger45007182021-06-10 14:47:21 -0400794 auto& cache = mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700795
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400796 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
797 DeferTextureCleanup dtc(mTextureCleanupMgr);
798
Alec Mouria90a5702021-04-16 16:36:21 +0000799 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
800 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
801 surfaceTextureRef = it->second;
802 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400803 surfaceTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400804 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
805 buffer->getBuffer()
806 ->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400807 true, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -0700808 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800809
Alec Mouri4ee7b492021-08-11 10:36:55 -0700810 // wait on the buffer to be ready to use prior to using it
811 waitFence(bufferFence);
812
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500813 const ui::Dataspace dstDataspace =
Alec Mourid2bcbae2021-06-28 17:02:17 -0700814 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400815 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700816
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500817 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
818 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800819 ALOGE("Cannot acquire canvas from Skia.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700820 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
821 return;
Ana Krulec6eab17a2020-12-09 15:52:36 -0800822 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500823
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400824 // setup color filter if necessary
825 sk_sp<SkColorFilter> displayColorTransform;
Leon Scroggins III745dcaa2022-01-26 11:55:58 -0500826 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400827 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
828 }
829 const bool ctModifiesAlpha =
830 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
831
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700832 // Find the max layer white point to determine the max luminance of the scene...
833 const float maxLayerWhitePoint = std::transform_reduce(
834 layers.cbegin(), layers.cend(), 0.f,
835 [](float left, float right) { return std::max(left, right); },
836 [&](const auto& l) { return l.whitePointNits; });
837
838 // ...and compute the dimming ratio if dimming is requested
839 const float displayDimmingRatio = display.targetLuminanceNits > 0.f &&
840 maxLayerWhitePoint > 0.f && display.targetLuminanceNits > maxLayerWhitePoint
841 ? maxLayerWhitePoint / display.targetLuminanceNits
842 : 1.f;
843
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500844 // Find if any layers have requested blur, we'll use that info to decide when to render to an
845 // offscreen buffer and when to render to the native buffer.
846 sk_sp<SkSurface> activeSurface(dstSurface);
847 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500848 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500849 const LayerSettings* blurCompositionLayer = nullptr;
850 if (mBlurFilter) {
851 bool requiresCompositionLayer = false;
852 for (const auto& layer : layers) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400853 // if the layer doesn't have blur or it is not visible then continue
854 if (!layerHasBlur(layer, ctModifiesAlpha)) {
855 continue;
856 }
Sally Qi59a9f502021-10-12 18:53:23 +0000857 if (layer.backgroundBlurRadius > 0 &&
Robin Lee26dacab2021-08-09 14:31:01 +0200858 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500859 requiresCompositionLayer = true;
860 }
Sally Qi59a9f502021-10-12 18:53:23 +0000861 for (auto region : layer.blurRegions) {
Robin Lee26dacab2021-08-09 14:31:01 +0200862 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500863 requiresCompositionLayer = true;
864 }
865 }
866 if (requiresCompositionLayer) {
867 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500868 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Sally Qi59a9f502021-10-12 18:53:23 +0000869 blurCompositionLayer = &layer;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500870 break;
871 }
872 }
873 }
874
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500875 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700876 // Clear the entire canvas with a transparent black to prevent ghost images.
877 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500878 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800879
Leon Scroggins III191b8772022-04-06 14:38:22 -0400880 if (kPrintLayerSettings) {
881 logSettings(display);
882 }
John Reck67b1e2b2020-08-26 13:17:24 -0700883 for (const auto& layer : layers) {
Sally Qi59a9f502021-10-12 18:53:23 +0000884 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
Galia Peychevaf7889b32020-11-25 22:22:40 +0100885
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400886 if (kPrintLayerSettings) {
Leon Scroggins III191b8772022-04-06 14:38:22 -0400887 logSettings(layer);
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400888 }
889
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500890 sk_sp<SkImage> blurInput;
Sally Qi59a9f502021-10-12 18:53:23 +0000891 if (blurCompositionLayer == &layer) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500892 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
893 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
894
895 // save a snapshot of the activeSurface to use as input to the blur shaders
896 blurInput = activeSurface->makeImageSnapshot();
897
Leon Scroggins III55bf4742022-03-17 14:11:17 -0400898 // blit the offscreen framebuffer into the destination AHB, but only
899 // if there are blur regions. backgroundBlurRadius blurs the entire
900 // image below, so it can skip this step.
901 if (layer.blurRegions.size()) {
902 SkPaint paint;
903 paint.setBlendMode(SkBlendMode::kSrc);
904 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
905 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
906 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
907 String8::format("SurfaceID|%" PRId64, id).c_str(),
908 nullptr);
909 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
910 } else {
911 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
912 }
Derek Sollenberger76664d62021-02-04 11:13:09 -0500913 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500914
915 // assign dstCanvas to canvas and ensure that the canvas state is up to date
916 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500917 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500918 initCanvas(canvas, display);
919
920 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
921 dstSurface->getCanvas()->getSaveCount());
922 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
923 dstSurface->getCanvas()->getTotalMatrix());
924
925 // assign dstSurface to activeSurface
926 activeSurface = dstSurface;
927 }
928
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500929 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500930 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800931 // Record the name of the layer if the capture is running.
932 std::stringstream layerSettings;
Sally Qi59a9f502021-10-12 18:53:23 +0000933 PrintTo(layer, &layerSettings);
Ana Krulec6eab17a2020-12-09 15:52:36 -0800934 // Store the LayerSettings in additional information.
Sally Qi59a9f502021-10-12 18:53:23 +0000935 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
Ana Krulec6eab17a2020-12-09 15:52:36 -0800936 SkData::MakeWithCString(layerSettings.str().c_str()));
937 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100938 // Layers have a local transform that should be applied to them
Sally Qi59a9f502021-10-12 18:53:23 +0000939 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100940
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400941 const auto [bounds, roundRectClip] =
Sally Qi59a9f502021-10-12 18:53:23 +0000942 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
943 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400944 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500945 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
946
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500947 // if multiple layers have blur, then we need to take a snapshot now because
948 // only the lowest layer will have blurImage populated earlier
949 if (!blurInput) {
950 blurInput = activeSurface->makeImageSnapshot();
951 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500952 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400953 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
954
955 // if the clip needs to be applied then apply it now and make sure
956 // it is restored before we attempt to draw any shadows.
957 SkAutoCanvasRestore acr(canvas, true);
958 if (!roundRectClip.isEmpty()) {
959 canvas->clipRRect(roundRectClip, true);
960 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500961
Galia Peychevae425ac82021-03-15 17:12:03 +0100962 // TODO(b/182216890): Filter out empty layers earlier
963 if (blurRect.width() > 0 && blurRect.height() > 0) {
Sally Qi59a9f502021-10-12 18:53:23 +0000964 if (layer.backgroundBlurRadius > 0) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100965 ATRACE_NAME("BackgroundBlur");
Sally Qi59a9f502021-10-12 18:53:23 +0000966 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
967 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100968
Sally Qi59a9f502021-10-12 18:53:23 +0000969 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500970
Sally Qi59a9f502021-10-12 18:53:23 +0000971 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400972 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700973 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400974
Sally Qi59a9f502021-10-12 18:53:23 +0000975 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
976 for (auto region : layer.blurRegions) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100977 if (cachedBlurs[region.blurRadius] == nullptr) {
978 ATRACE_NAME("BlurRegion");
979 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400980 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100981 blurRect);
982 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500983
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400984 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
985 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100986 cachedBlurs[region.blurRadius], blurInput);
987 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700988 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700989 }
990
Sally Qi59a9f502021-10-12 18:53:23 +0000991 if (layer.shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400992 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
Sally Qi59a9f502021-10-12 18:53:23 +0000993 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
Leon Scroggins III63e86952021-05-12 10:45:08 -0400994
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400995 SkRRect shadowBounds, shadowClip;
Sally Qi59a9f502021-10-12 18:53:23 +0000996 if (layer.geometry.boundaries == layer.shadow.boundaries) {
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400997 shadowBounds = bounds;
998 shadowClip = roundRectClip;
999 } else {
1000 std::tie(shadowBounds, shadowClip) =
Sally Qi59a9f502021-10-12 18:53:23 +00001001 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
1002 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001003 }
1004
Leon Scroggins III63e86952021-05-12 10:45:08 -04001005 // Technically, if bounds is a rect and roundRectClip is not empty,
1006 // it means that the bounds and roundedCornersCrop were different
1007 // enough that we should intersect them to find the proper shadow.
1008 // In practice, this often happens when the two rectangles appear to
1009 // not match due to rounding errors. Draw the rounded version, which
1010 // looks more like the intent.
1011 const auto& rrect =
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001012 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
Sally Qi59a9f502021-10-12 18:53:23 +00001013 drawShadow(canvas, rrect, layer.shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001014 }
1015
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001016 const float layerDimmingRatio = layer.whitePointNits <= 0.f
1017 ? displayDimmingRatio
1018 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
1019
Alec Mouri30835f22022-03-18 00:58:26 +00001020 const bool dimInLinearSpace = display.dimmingStage !=
1021 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
1022
Sally Qi59a9f502021-10-12 18:53:23 +00001023 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001024 (mUseColorManagement &&
Sally Qi59a9f502021-10-12 18:53:23 +00001025 needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
Alec Mouri30835f22022-03-18 00:58:26 +00001026 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio));
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001027
1028 // quick abort from drawing the remaining portion of the layer
Sally Qi59a9f502021-10-12 18:53:23 +00001029 if (layer.skipContentDraw ||
1030 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001031 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001032 continue;
1033 }
1034
1035 // If we need to map to linear space or color management is disabled, then mark the source
1036 // image with the same colorspace as the destination surface so that Skia's color
1037 // management is a no-op.
1038 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
1039 ? dstDataspace
Sally Qi59a9f502021-10-12 18:53:23 +00001040 : layer.sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -08001041
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001042 SkPaint paint;
Sally Qi59a9f502021-10-12 18:53:23 +00001043 if (layer.source.buffer.buffer) {
John Reck67b1e2b2020-08-26 13:17:24 -07001044 ATRACE_NAME("DrawImage");
Sally Qi59a9f502021-10-12 18:53:23 +00001045 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
1046 const auto& item = layer.source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001047 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +00001048
1049 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
1050 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001051 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -07001052 } else {
Alec Mouria90a5702021-04-16 16:36:21 +00001053 // If we didn't find the image in the cache, then create a local ref but don't cache
1054 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
1055 // we didn't find anything in the cache then we intentionally did not cache this
1056 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001057 imageTextureRef = std::make_shared<
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001058 AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001059 item.buffer->getBuffer()->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -04001060 false, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -07001061 }
Alec Mouri1a4d0642020-11-13 17:42:01 -08001062
Alec Mouri4ee7b492021-08-11 10:36:55 -07001063 // if the layer's buffer has a fence, then we must must respect the fence prior to using
1064 // the buffer.
Sally Qi59a9f502021-10-12 18:53:23 +00001065 if (layer.source.buffer.fence != nullptr) {
1066 waitFence(layer.source.buffer.fence->get());
Alec Mouri4ee7b492021-08-11 10:36:55 -07001067 }
1068
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001069 // isOpaque means we need to ignore the alpha in the image,
1070 // replacing it with the alpha specified by the LayerSettings. See
1071 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
1072 // The proper way to do this is to use an SkColorType that ignores
1073 // alpha, like kRGB_888x_SkColorType, and that is used if the
1074 // incoming image is kRGBA_8888_SkColorType. However, the incoming
1075 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
1076 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
1077 // kRGB_101010x_SkColorType, but it is not yet supported as a source
1078 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
1079 // meantime, we'll use a workaround that works unless we need to do
1080 // any color conversion. The workaround requires that we pretend the
1081 // image is already premultiplied, so that we do not premultiply it
1082 // before applying SkBlendMode::kPlus.
1083 const bool useIsOpaqueWorkaround = item.isOpaque &&
1084 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
1085 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
1086 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
1087 : item.isOpaque ? kOpaque_SkAlphaType
1088 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
1089 : kUnpremul_SkAlphaType;
1090 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -07001091
1092 auto texMatrix = getSkM44(item.textureTransform).asM33();
1093 // textureTansform was intended to be passed directly into a shader, so when
1094 // building the total matrix with the textureTransform we need to first
1095 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001096 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001097 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -07001098
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001099 SkMatrix matrix;
1100 if (!texMatrix.invert(&matrix)) {
1101 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -07001102 }
Ana Krulecf9a15d92020-12-11 08:35:00 -08001103 // The shader does not respect the translation, so we add it to the texture
1104 // transform for the SkImage. This will make sure that the correct layer contents
1105 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001106 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -07001107
Ana Krulecb7b28b22020-11-23 14:48:58 -08001108 sk_sp<SkShader> shader;
1109
Sally Qi59a9f502021-10-12 18:53:23 +00001110 if (layer.source.buffer.useTextureFiltering) {
Ana Krulecb7b28b22020-11-23 14:48:58 -08001111 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1112 SkSamplingOptions(
1113 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1114 &matrix);
1115 } else {
Mike Reed711e1f02020-12-11 13:06:19 -05001116 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -08001117 }
Alec Mouri029d1952020-10-12 10:37:08 -07001118
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001119 if (useIsOpaqueWorkaround) {
Alec Mouric0aae732021-01-12 13:32:18 -08001120 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1121 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001122 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001123 }
1124
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001125 paint.setShader(createRuntimeEffectShader(
1126 RuntimeEffectShaderParameters{.shader = shader,
1127 .layer = layer,
1128 .display = display,
1129 .undoPremultipliedAlpha = !item.isOpaque &&
1130 item.usePremultipliedAlpha,
1131 .requiresLinearEffect = requiresLinearEffect,
Alec Mouri30835f22022-03-18 00:58:26 +00001132 .layerDimmingRatio = dimInLinearSpace
1133 ? layerDimmingRatio
1134 : 1.f}));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001135
Alec Mouri88acab92022-03-24 23:41:01 +00001136 // Turn on dithering when dimming beyond this (arbitrary) threshold...
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001137 static constexpr float kDimmingThreshold = 0.2f;
Alec Mouri88acab92022-03-24 23:41:01 +00001138 // ...or we're rendering an HDR layer down to an 8-bit target
1139 // Most HDR standards require at least 10-bits of color depth for source content, so we
1140 // can just extract the transfer function rather than dig into precise gralloc layout.
1141 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
1142 const bool requiresDownsample = isHdrDataspace(layer.sourceDataspace) &&
1143 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
1144 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001145 paint.setDither(true);
1146 }
Sally Qi59a9f502021-10-12 18:53:23 +00001147 paint.setAlphaf(layer.alpha);
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001148
1149 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1150 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001151
1152 // SysUI creates the alpha layer as a coverage layer, which is
1153 // appropriate for the DPU. Use a color matrix to convert it to
1154 // a mask.
1155 // TODO (b/219525258): Handle input as a mask.
1156 //
1157 // The color matrix will convert A8 pixels with no alpha to
1158 // black, as described by this vector. If the display handles
1159 // the color transform, we need to invert it to find the color
1160 // that will result in black after the DPU applies the transform.
1161 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1162 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1163 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1164 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1165 black = colorSpaceMatrix * black;
1166 } else {
1167 // We'll just have to use 0,0,0 as black, which should
1168 // be close to correct.
1169 ALOGI("Could not invert colorTransform!");
1170 }
1171 }
1172 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1173 0, 0, 0, 0, black[1],
1174 0, 0, 0, 0, black[2],
1175 0, 0, 0, -1, 1);
1176 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1177 // On the other hand, if the device doesn't handle it, we
1178 // have to apply it ourselves.
1179 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1180 }
1181 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001182 }
John Reck67b1e2b2020-08-26 13:17:24 -07001183 } else {
1184 ATRACE_NAME("DrawColor");
Sally Qi59a9f502021-10-12 18:53:23 +00001185 const auto color = layer.source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001186 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1187 .fG = color.g,
1188 .fB = color.b,
Sally Qi59a9f502021-10-12 18:53:23 +00001189 .fA = layer.alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001190 toSkColorSpace(layerDataspace));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001191 paint.setShader(createRuntimeEffectShader(
1192 RuntimeEffectShaderParameters{.shader = shader,
1193 .layer = layer,
1194 .display = display,
1195 .undoPremultipliedAlpha = false,
1196 .requiresLinearEffect = requiresLinearEffect,
1197 .layerDimmingRatio = layerDimmingRatio}));
John Reck67b1e2b2020-08-26 13:17:24 -07001198 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001199
Sally Qi59a9f502021-10-12 18:53:23 +00001200 if (layer.disableBlending) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001201 paint.setBlendMode(SkBlendMode::kSrc);
1202 }
1203
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001204 // An A8 buffer will already have the proper color filter attached to
1205 // its paint, including the displayColorTransform as needed.
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001206 if (!paint.getColorFilter()) {
Alec Mouri30835f22022-03-18 00:58:26 +00001207 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1208 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1209 // can assume a gamma 2.2 transfer function.
1210 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1211 const auto gammaCorrectedDimmingRatio =
1212 std::pow(layerDimmingRatio, kInverseGamma22);
Alec Mouri9bcd1d12022-04-21 22:16:56 +00001213 auto dimmingMatrix =
Alec Mouri30835f22022-03-18 00:58:26 +00001214 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1215 gammaCorrectedDimmingRatio, 1.f));
Alec Mouri9bcd1d12022-04-21 22:16:56 +00001216
1217 const auto colorFilter =
1218 SkColorFilters::Matrix(toSkColorMatrix(std::move(dimmingMatrix)));
1219 paint.setColorFilter(displayColorTransform
1220 ? displayColorTransform->makeComposed(colorFilter)
1221 : colorFilter);
Alec Mouri30835f22022-03-18 00:58:26 +00001222 } else {
1223 paint.setColorFilter(displayColorTransform);
1224 }
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001225 }
Alec Mourib34f0b72020-10-02 13:18:34 -07001226
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001227 if (!roundRectClip.isEmpty()) {
1228 canvas->clipRRect(roundRectClip, true);
1229 }
1230
1231 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001232 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001233 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001234 } else {
Nader Jawad63644d32021-05-07 10:44:21 -07001235 canvas->drawRect(bounds.rect(), paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -07001236 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001237 if (kFlushAfterEveryLayer) {
1238 ATRACE_NAME("flush surface");
1239 activeSurface->flush();
1240 }
John Reck67b1e2b2020-08-26 13:17:24 -07001241 }
Tianhao Yao67dd7122022-02-22 17:48:33 +00001242 for (const auto& borderRenderInfo : display.borderInfoList) {
1243 SkPaint p;
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001244 p.setColor(SkColor4f{borderRenderInfo.color.r, borderRenderInfo.color.g,
1245 borderRenderInfo.color.b, borderRenderInfo.color.a});
Tianhao Yao67dd7122022-02-22 17:48:33 +00001246 p.setAntiAlias(true);
1247 p.setStyle(SkPaint::kStroke_Style);
Tianhao Yao10cea3c2022-03-30 01:37:22 +00001248 p.setStrokeWidth(borderRenderInfo.width);
Tianhao Yao67dd7122022-02-22 17:48:33 +00001249 SkRegion sk_region;
1250 SkPath path;
1251
1252 // Construct a final SkRegion using Regions
1253 for (const auto& r : borderRenderInfo.combinedRegion) {
1254 sk_region.op({r.left, r.top, r.right, r.bottom}, SkRegion::kUnion_Op);
1255 }
1256
1257 sk_region.getBoundaryPath(&path);
1258 canvas->drawPath(path, p);
1259 path.close();
1260 }
1261
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001262 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001263 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001264 {
1265 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001266 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1267 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001268 }
1269
Sally Qi4cabdd02021-08-05 16:45:57 -07001270 base::unique_fd drawFence = flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001271
1272 // If flush failed or we don't support native fences, we need to force the
1273 // gl command stream to be executed.
Sally Qi4cabdd02021-08-05 16:45:57 -07001274 bool requireSync = drawFence.get() < 0;
John Reck67b1e2b2020-08-26 13:17:24 -07001275 if (requireSync) {
1276 ATRACE_BEGIN("Submit(sync=true)");
1277 } else {
1278 ATRACE_BEGIN("Submit(sync=false)");
1279 }
Lucas Dupind508e472020-11-04 04:32:06 +00001280 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001281 ATRACE_END();
1282 if (!success) {
1283 ALOGE("Failed to flush RenderEngine commands");
1284 // Chances are, something illegal happened (either the caller passed
1285 // us bad parameters, or we messed up our shader generation).
Sally Qi4cabdd02021-08-05 16:45:57 -07001286 resultPromise->set_value({INVALID_OPERATION, std::move(drawFence)});
1287 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001288 }
1289
1290 // checkErrors();
Sally Qi4cabdd02021-08-05 16:45:57 -07001291 resultPromise->set_value({NO_ERROR, std::move(drawFence)});
1292 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001293}
1294
Lucas Dupin3f11e922020-09-22 17:31:04 -07001295inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1296 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1297}
1298
1299inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1300 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1301}
1302
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001303/**
1304 * Verifies that common, simple bounds + clip combinations can be converted into
1305 * a single RRect draw call returning true if possible. If true the radii parameter
1306 * will be filled with the correct radii values that combined with bounds param will
1307 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
1308 */
1309static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001310 const SkRect& insetCrop, const vec2& cornerRadius,
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001311 SkVector radii[4]) {
1312 const bool leftEqual = bounds.fLeft == crop.fLeft;
1313 const bool topEqual = bounds.fTop == crop.fTop;
1314 const bool rightEqual = bounds.fRight == crop.fRight;
1315 const bool bottomEqual = bounds.fBottom == crop.fBottom;
1316
1317 // In the event that the corners of the bounds only partially align with the crop we
1318 // need to ensure that the resulting shape can still be represented as a round rect.
1319 // In particular the round rect implementation will scale the value of all corner radii
1320 // if the sum of the radius along any edge is greater than the length of that edge.
1321 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001322 const bool requiredWidth = bounds.width() > (cornerRadius.x * 2);
1323 const bool requiredHeight = bounds.height() > (cornerRadius.y * 2);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001324 if (!requiredWidth || !requiredHeight) {
1325 return false;
1326 }
1327
1328 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
1329 // contained within the cropped shape and does not need rounded.
1330 // compute the UpperLeft corner radius
1331 if (leftEqual && topEqual) {
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001332 radii[0].set(cornerRadius.x, cornerRadius.y);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001333 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
1334 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
1335 radii[0].set(0, 0);
1336 } else {
1337 return false;
1338 }
1339 // compute the UpperRight corner radius
1340 if (rightEqual && topEqual) {
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001341 radii[1].set(cornerRadius.x, cornerRadius.y);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001342 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
1343 (topEqual && bounds.fRight <= insetCrop.fRight)) {
1344 radii[1].set(0, 0);
1345 } else {
1346 return false;
1347 }
1348 // compute the BottomRight corner radius
1349 if (rightEqual && bottomEqual) {
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001350 radii[2].set(cornerRadius.x, cornerRadius.y);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001351 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
1352 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
1353 radii[2].set(0, 0);
1354 } else {
1355 return false;
1356 }
1357 // compute the BottomLeft corner radius
1358 if (leftEqual && bottomEqual) {
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001359 radii[3].set(cornerRadius.x, cornerRadius.y);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001360 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
1361 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
1362 radii[3].set(0, 0);
1363 } else {
1364 return false;
1365 }
1366
1367 return true;
1368}
1369
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001370inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(const FloatRect& boundsRect,
1371 const FloatRect& cropRect,
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001372 const vec2& cornerRadius) {
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001373 const SkRect bounds = getSkRect(boundsRect);
1374 const SkRect crop = getSkRect(cropRect);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001375
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001376 SkRRect clip;
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001377 if (cornerRadius.x > 0 && cornerRadius.y > 0) {
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001378 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
1379 if (bounds == crop || crop.isEmpty()) {
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001380 return {SkRRect::MakeRectXY(bounds, cornerRadius.x, cornerRadius.y), clip};
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001381 }
1382
1383 // This makes an effort to speed up common, simple bounds + clip combinations by
1384 // converting them to a single RRect draw. It is possible there are other cases
1385 // that can be converted.
1386 if (crop.contains(bounds)) {
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001387 const auto insetCrop = crop.makeInset(cornerRadius.x, cornerRadius.y);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001388 if (insetCrop.contains(bounds)) {
1389 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001390 }
1391
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001392 SkVector radii[4];
1393 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001394 SkRRect intersectionBounds;
1395 intersectionBounds.setRectRadii(bounds, radii);
1396 return {intersectionBounds, clip};
1397 }
1398 }
1399
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001400 // we didn't hit any of our fast paths so set the clip to the cropRect
Vishnu Nair50c0afe2022-07-11 15:04:07 -07001401 clip.setRectXY(crop, cornerRadius.x, cornerRadius.y);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001402 }
1403
1404 // if we hit this point then we either don't have rounded corners or we are going to rely
1405 // on the clip to round the corners for us
1406 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001407}
1408
Sally Qi59a9f502021-10-12 18:53:23 +00001409inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings& layer,
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001410 bool colorTransformModifiesAlpha) {
Sally Qi59a9f502021-10-12 18:53:23 +00001411 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001412 // return false if the content is opaque and would therefore occlude the blur
Sally Qi59a9f502021-10-12 18:53:23 +00001413 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
1414 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
1415 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001416 }
1417 return false;
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001418}
1419
Lucas Dupin3f11e922020-09-22 17:31:04 -07001420inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1421 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1422}
1423
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001424inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1425 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1426 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1427 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1428 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1429}
1430
Lucas Dupin3f11e922020-09-22 17:31:04 -07001431inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1432 return SkPoint3::Make(vector.x, vector.y, vector.z);
1433}
1434
John Reck67b1e2b2020-08-26 13:17:24 -07001435size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1436 return mGrContext->maxTextureSize();
1437}
1438
1439size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1440 return mGrContext->maxRenderTargetSize();
1441}
1442
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001443void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001444 const ShadowSettings& settings) {
1445 ATRACE_CALL();
1446 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001447 const auto flags =
1448 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1449
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001450 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001451 getSkPoint3(settings.lightPos), settings.lightRadius,
1452 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1453 flags);
1454}
1455
John Reck67b1e2b2020-08-26 13:17:24 -07001456EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001457 EGLContext shareContext,
1458 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001459 Protection protection) {
1460 EGLint renderableType = 0;
1461 if (config == EGL_NO_CONFIG_KHR) {
1462 renderableType = EGL_OPENGL_ES3_BIT;
1463 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1464 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1465 }
1466 EGLint contextClientVersion = 0;
1467 if (renderableType & EGL_OPENGL_ES3_BIT) {
1468 contextClientVersion = 3;
1469 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1470 contextClientVersion = 2;
1471 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1472 contextClientVersion = 1;
1473 } else {
1474 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1475 }
1476
1477 std::vector<EGLint> contextAttributes;
1478 contextAttributes.reserve(7);
1479 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1480 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001481 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001482 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001483 switch (*contextPriority) {
1484 case ContextPriority::REALTIME:
1485 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1486 break;
1487 case ContextPriority::MEDIUM:
1488 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1489 break;
1490 case ContextPriority::LOW:
1491 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1492 break;
1493 case ContextPriority::HIGH:
1494 default:
1495 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1496 break;
1497 }
John Reck67b1e2b2020-08-26 13:17:24 -07001498 }
1499 if (protection == Protection::PROTECTED) {
1500 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1501 contextAttributes.push_back(EGL_TRUE);
1502 }
1503 contextAttributes.push_back(EGL_NONE);
1504
1505 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1506
1507 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1508 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1509 // EGL_NO_CONTEXT so that we can abort.
1510 if (config != EGL_NO_CONFIG_KHR) {
1511 return context;
1512 }
1513 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1514 // should try to fall back to GLES 2.
1515 contextAttributes[1] = 2;
1516 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1517 }
1518
1519 return context;
1520}
1521
Alec Mourid6f09462020-12-07 11:18:17 -08001522std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1523 const RenderEngineCreationArgs& args) {
1524 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1525 return std::nullopt;
1526 }
1527
1528 switch (args.contextPriority) {
1529 case RenderEngine::ContextPriority::REALTIME:
1530 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1531 return RenderEngine::ContextPriority::REALTIME;
1532 } else {
1533 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1534 return RenderEngine::ContextPriority::HIGH;
1535 }
1536 case RenderEngine::ContextPriority::HIGH:
1537 case RenderEngine::ContextPriority::MEDIUM:
1538 case RenderEngine::ContextPriority::LOW:
1539 return args.contextPriority;
1540 default:
1541 return std::nullopt;
1542 }
1543}
1544
John Reck67b1e2b2020-08-26 13:17:24 -07001545EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1546 EGLConfig config, int hwcFormat,
1547 Protection protection) {
1548 EGLConfig placeholderConfig = config;
1549 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1550 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1551 }
1552 std::vector<EGLint> attributes;
1553 attributes.reserve(7);
1554 attributes.push_back(EGL_WIDTH);
1555 attributes.push_back(1);
1556 attributes.push_back(EGL_HEIGHT);
1557 attributes.push_back(1);
1558 if (protection == Protection::PROTECTED) {
1559 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1560 attributes.push_back(EGL_TRUE);
1561 }
1562 attributes.push_back(EGL_NONE);
1563
1564 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1565}
1566
Alec Mourid6f09462020-12-07 11:18:17 -08001567int SkiaGLRenderEngine::getContextPriority() {
1568 int value;
1569 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1570 return value;
1571}
1572
Ady Abrahamed3290f2021-05-17 15:12:14 -07001573void SkiaGLRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001574 // This cache multiplier was selected based on review of cache sizes relative
1575 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1576 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1577 // conservative default based on that analysis.
1578 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1579 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1580
1581 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001582 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001583
1584 // if it is possible to switch contexts then we will resize the other context
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001585 const bool originalProtectedState = mInProtectedContext;
1586 useProtectedContext(!mInProtectedContext);
1587 if (mInProtectedContext != originalProtectedState) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001588 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001589 // reset back to the initial context that was active when this method was called
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001590 useProtectedContext(originalProtectedState);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001591 }
1592}
1593
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001594void SkiaGLRenderEngine::dump(std::string& result) {
1595 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1596
1597 StringAppendF(&result, "\n ------------RE-----------------\n");
1598 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1599 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1600 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1601 extensions.getVersion());
1602 StringAppendF(&result, "%s\n", extensions.getExtensions());
1603 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1604 supportsProtectedContent());
1605 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001606 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1607 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001608
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001609 std::vector<ResourcePair> cpuResourceMap = {
1610 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1611 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1612 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1613 {"skia/sk_resource_cache/tessellated", "Shadows"},
1614 {"skia", "Other"},
1615 };
1616 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1617 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1618 StringAppendF(&result, "Skia CPU Caches: ");
1619 cpuReporter.logTotals(result);
1620 cpuReporter.logOutput(result);
1621
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001622 {
1623 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001624
1625 std::vector<ResourcePair> gpuResourceMap = {
1626 {"texture_renderbuffer", "Texture/RenderBuffer"},
1627 {"texture", "Texture"},
1628 {"gr_text_blob_cache", "Text"},
1629 {"skia", "Other"},
1630 };
1631 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1632 mGrContext->dumpMemoryStatistics(&gpuReporter);
1633 StringAppendF(&result, "Skia's GPU Caches: ");
1634 gpuReporter.logTotals(result);
1635 gpuReporter.logOutput(result);
1636 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1637 gpuReporter.logOutput(result, true);
1638
Alec Mouria90a5702021-04-16 16:36:21 +00001639 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1640 mGraphicBufferExternalRefs.size());
1641 StringAppendF(&result, "Dumping buffer ids...\n");
1642 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1643 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1644 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001645 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1646 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001647 StringAppendF(&result, "Dumping buffer ids...\n");
1648 // TODO(178539829): It would be nice to know which layer these are coming from and what
1649 // the texture sizes are.
1650 for (const auto& [id, unused] : mTextureCache) {
1651 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1652 }
1653 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001654
1655 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001656 if (mProtectedGrContext) {
1657 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1658 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001659 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1660 gpuProtectedReporter.logTotals(result);
1661 gpuProtectedReporter.logOutput(result);
1662 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1663 gpuProtectedReporter.logOutput(result, true);
1664
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001665 StringAppendF(&result, "\n");
1666 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1667 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1668 StringAppendF(&result, "- inputDataspace: %s\n",
1669 dataspaceDetails(
1670 static_cast<android_dataspace>(linearEffect.inputDataspace))
1671 .c_str());
1672 StringAppendF(&result, "- outputDataspace: %s\n",
1673 dataspaceDetails(
1674 static_cast<android_dataspace>(linearEffect.outputDataspace))
1675 .c_str());
1676 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1677 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1678 }
1679 }
1680 StringAppendF(&result, "\n");
1681}
1682
John Reck67b1e2b2020-08-26 13:17:24 -07001683} // namespace skia
1684} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001685} // namespace android