blob: 9bb68e3464e025971c88a7359dcce082b53f5b2d [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;
70static const bool kFlushAfterEveryLayer = false;
71} // 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
299void SkiaGLRenderEngine::assertShadersCompiled(int numShaders) {
300 const int cached = mSkSLCacheMonitor.shadersCachedSinceLastCall();
301 LOG_ALWAYS_FATAL_IF(cached != numShaders, "Attempted to cache %i shaders; cached %i",
302 numShaders, cached);
303}
304
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400305int SkiaGLRenderEngine::reportShadersCompiled() {
306 return mSkSLCacheMonitor.shadersCachedSinceLastCall();
307}
308
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700309SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000310 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700311 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800312 : SkiaRenderEngine(args.renderEngineType),
313 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700314 mEGLContext(ctxt),
315 mPlaceholderSurface(placeholder),
316 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700317 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400318 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800319 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700320 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
321 LOG_ALWAYS_FATAL_IF(!glInterface.get());
322
323 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400324 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700325 options.fDisableDistanceFieldPaths = true;
Nathaniel Nifongf8d35e92021-06-08 15:02:25 -0400326 options.fReducedShaderVariations = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400327 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000328 mGrContext = GrDirectContext::MakeGL(glInterface, options);
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400329 if (supportsProtectedContent()) {
330 useProtectedContext(true);
Lucas Dupind508e472020-11-04 04:32:06 +0000331 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
332 useProtectedContext(false);
333 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700334
335 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500336 ALOGD("Background Blurs Enabled");
Robin Lee026680a2021-07-26 12:49:53 +0200337 mBlurFilter = new KawaseBlurFilter();
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700338 }
Alec Mouric0aae732021-01-12 13:32:18 -0800339 mCapture = std::make_unique<SkiaCapture>();
340}
341
342SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100343 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800344 if (mBlurFilter) {
345 delete mBlurFilter;
346 }
347
348 mCapture = nullptr;
349
350 mGrContext->flushAndSubmit(true);
351 mGrContext->abandonContext();
352
353 if (mProtectedGrContext) {
354 mProtectedGrContext->flushAndSubmit(true);
355 mProtectedGrContext->abandonContext();
356 }
357
358 if (mPlaceholderSurface != EGL_NO_SURFACE) {
359 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
360 }
361 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
362 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
363 }
364 if (mEGLContext != EGL_NO_CONTEXT) {
365 eglDestroyContext(mEGLDisplay, mEGLContext);
366 }
367 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
368 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
369 }
370 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
371 eglTerminate(mEGLDisplay);
372 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700373}
374
Lucas Dupind508e472020-11-04 04:32:06 +0000375bool SkiaGLRenderEngine::supportsProtectedContent() const {
376 return mProtectedEGLContext != EGL_NO_CONTEXT;
377}
378
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400379GrDirectContext* SkiaGLRenderEngine::getActiveGrContext() const {
380 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
381}
382
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400383void SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
384 if (useProtectedContext == mInProtectedContext ||
385 (useProtectedContext && !supportsProtectedContent())) {
386 return;
Lucas Dupind508e472020-11-04 04:32:06 +0000387 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400388
389 // release any scratch resources before switching into a new mode
390 if (getActiveGrContext()) {
391 getActiveGrContext()->purgeUnlockedResources(true);
392 }
393
Lucas Dupind508e472020-11-04 04:32:06 +0000394 const EGLSurface surface =
395 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
396 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
Alec Mouric0aae732021-01-12 13:32:18 -0800397
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400398 if (eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE) {
Lucas Dupind508e472020-11-04 04:32:06 +0000399 mInProtectedContext = useProtectedContext;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400400 // given that we are sharing the same thread between two GrContexts we need to
401 // make sure that the thread state is reset when switching between the two.
402 if (getActiveGrContext()) {
403 getActiveGrContext()->resetContext();
404 }
Lucas Dupind508e472020-11-04 04:32:06 +0000405 }
Lucas Dupind508e472020-11-04 04:32:06 +0000406}
407
John Reck67b1e2b2020-08-26 13:17:24 -0700408base::unique_fd SkiaGLRenderEngine::flush() {
409 ATRACE_CALL();
410 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
411 return base::unique_fd();
412 }
413
414 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
415 if (sync == EGL_NO_SYNC_KHR) {
416 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
417 return base::unique_fd();
418 }
419
420 // native fence fd will not be populated until flush() is done.
421 glFlush();
422
423 // get the fence fd
424 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
425 eglDestroySyncKHR(mEGLDisplay, sync);
426 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
427 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
428 }
429
430 return fenceFd;
431}
432
Alec Mouri4ee7b492021-08-11 10:36:55 -0700433void SkiaGLRenderEngine::waitFence(base::borrowed_fd fenceFd) {
434 if (fenceFd.get() >= 0 && !waitGpuFence(fenceFd)) {
435 ATRACE_NAME("SkiaGLRenderEngine::waitFence");
436 sync_wait(fenceFd.get(), -1);
437 }
438}
439
440bool SkiaGLRenderEngine::waitGpuFence(base::borrowed_fd fenceFd) {
John Reck67b1e2b2020-08-26 13:17:24 -0700441 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
442 !gl::GLExtensions::getInstance().hasWaitSync()) {
443 return false;
444 }
445
Alec Mouri4ee7b492021-08-11 10:36:55 -0700446 // Duplicate the fence for passing to eglCreateSyncKHR.
447 base::unique_fd fenceDup(dup(fenceFd.get()));
448 if (fenceDup.get() < 0) {
449 ALOGE("failed to create duplicate fence fd: %d", fenceDup.get());
450 return false;
451 }
452
John Reck67b1e2b2020-08-26 13:17:24 -0700453 // release the fd and transfer the ownership to EGLSync
Alec Mouri4ee7b492021-08-11 10:36:55 -0700454 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceDup.release(), EGL_NONE};
John Reck67b1e2b2020-08-26 13:17:24 -0700455 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
456 if (sync == EGL_NO_SYNC_KHR) {
457 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
458 return false;
459 }
460
461 // XXX: The spec draft is inconsistent as to whether this should return an
462 // EGLint or void. Ignore the return value for now, as it's not strictly
463 // needed.
464 eglWaitSyncKHR(mEGLDisplay, sync, 0);
465 EGLint error = eglGetError();
466 eglDestroySyncKHR(mEGLDisplay, sync);
467 if (error != EGL_SUCCESS) {
468 ALOGE("failed to wait for EGL native fence sync: %#x", error);
469 return false;
470 }
471
472 return true;
473}
474
Alec Mouri678245d2020-09-30 16:58:23 -0700475static float toDegrees(uint32_t transform) {
476 switch (transform) {
477 case ui::Transform::ROT_90:
478 return 90.0;
479 case ui::Transform::ROT_180:
480 return 180.0;
481 case ui::Transform::ROT_270:
482 return 270.0;
483 default:
484 return 0.0;
485 }
486}
487
Alec Mourib34f0b72020-10-02 13:18:34 -0700488static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
489 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
490 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
491 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
492 matrix[3][3], 0);
493}
494
Alec Mouri029d1952020-10-12 10:37:08 -0700495static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
496 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
497 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
498
499 // Treat unsupported dataspaces as srgb
500 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
501 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
502 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
503 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
504 }
505
506 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
507 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
508 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
509 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
510 }
511
512 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
513 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
514 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
515 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
516
517 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
518 sourceTransfer != destTransfer;
519}
520
Alec Mouria90a5702021-04-16 16:36:21 +0000521void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
522 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800523 // Only run this if RE is running on its own thread. This way the access to GL
524 // operations is guaranteed to be happening on the same thread.
525 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
526 return;
527 }
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400528 // We currently don't attempt to map a buffer if the buffer contains protected content
Derek Sollenberger45007182021-06-10 14:47:21 -0400529 // because GPU resources for protected buffers is much more limited.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400530 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Derek Sollenberger45007182021-06-10 14:47:21 -0400531 if (isProtectedBuffer) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400532 return;
533 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800534 ATRACE_CALL();
535
Derek Sollenberger45007182021-06-10 14:47:21 -0400536 // If we were to support caching protected buffers then we will need to switch the
537 // currently bound context if we are not already using the protected context (and subsequently
538 // switch back after the buffer is cached). However, for non-protected content we can bind
539 // the texture in either GL context because they are initialized with the same share_context
540 // which allows the texture state to be shared between them.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400541 auto grContext = getActiveGrContext();
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400542 auto& cache = mTextureCache;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400543
544 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000545 mGraphicBufferExternalRefs[buffer->getId()]++;
546
547 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800548 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400549 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400550 buffer->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400551 isRenderable, mTextureCleanupMgr);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400552 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800553 }
554}
555
Alec Mouria90a5702021-04-16 16:36:21 +0000556void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800557 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700558 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000559 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
560 iter != mGraphicBufferExternalRefs.end()) {
561 if (iter->second == 0) {
562 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
563 "> from RenderEngine texture, but the "
564 "ref count was already zero!",
565 buffer->getId());
566 mGraphicBufferExternalRefs.erase(buffer->getId());
567 return;
568 }
569
570 iter->second--;
571
Alec Mouric2ffeb42021-06-17 17:42:27 -0700572 // Swap contexts if needed prior to deleting this buffer
573 // See Issue 1 of
574 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
575 // when a protected context and an unprotected context are part of the same share group,
576 // protected surfaces may not be accessed by an unprotected context, implying that protected
577 // surfaces may only be freed when a protected context is active.
578 const bool inProtected = mInProtectedContext;
579 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
580
Alec Mouria90a5702021-04-16 16:36:21 +0000581 if (iter->second == 0) {
582 mTextureCache.erase(buffer->getId());
Alec Mouria90a5702021-04-16 16:36:21 +0000583 mGraphicBufferExternalRefs.erase(buffer->getId());
584 }
Alec Mouric2ffeb42021-06-17 17:42:27 -0700585
586 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
587 // are up-to-date.
588 if (inProtected != mInProtectedContext) {
589 useProtectedContext(inProtected);
590 }
Alec Mouria90a5702021-04-16 16:36:21 +0000591 }
John Reck67b1e2b2020-08-26 13:17:24 -0700592}
593
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400594bool SkiaGLRenderEngine::canSkipPostRenderCleanup() const {
595 std::lock_guard<std::mutex> lock(mRenderingMutex);
596 return mTextureCleanupMgr.isEmpty();
597}
598
599void SkiaGLRenderEngine::cleanupPostRender() {
600 ATRACE_CALL();
601 std::lock_guard<std::mutex> lock(mRenderingMutex);
602 mTextureCleanupMgr.cleanup();
603}
604
605// Helper class intended to be used on the stack to ensure that texture cleanup
606// is deferred until after this class goes out of scope.
607class DeferTextureCleanup final {
608public:
609 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
610 mMgr.setDeferredStatus(true);
611 }
612 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
613
614private:
615 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
616 AutoBackendTexture::CleanupManager& mMgr;
617};
618
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700619sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
620 const RuntimeEffectShaderParameters& parameters) {
Nader Jawad63644d32021-05-07 10:44:21 -0700621 // The given surface will be stretched by HWUI via matrix transformation
622 // which gets similar results for most surfaces
623 // Determine later on if we need to leverage the stertch shader within
624 // surface flinger
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700625 const auto& stretchEffect = parameters.layer.stretchEffect;
626 auto shader = parameters.shader;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700627 if (stretchEffect.hasEffect()) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700628 const auto targetBuffer = parameters.layer.source.buffer.buffer;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700629 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700630 if (graphicBuffer && parameters.shader) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700631 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
632 }
John Reckcdb4ed72021-02-04 13:39:33 -0500633 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700634
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700635 if (parameters.requiresLinearEffect) {
636 const ui::Dataspace inputDataspace = mUseColorManagement ? parameters.layer.sourceDataspace
637 : ui::Dataspace::V0_SRGB_LINEAR;
638 const ui::Dataspace outputDataspace = mUseColorManagement
639 ? parameters.display.outputDataspace
640 : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500641
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700642 auto effect =
643 shaders::LinearEffect{.inputDataspace = inputDataspace,
644 .outputDataspace = outputDataspace,
645 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha};
Ana Krulec47814212021-01-06 19:00:10 -0800646
647 auto effectIter = mRuntimeEffects.find(effect);
648 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
649 if (effectIter == mRuntimeEffects.end()) {
650 runtimeEffect = buildRuntimeEffect(effect);
651 mRuntimeEffects.insert({effect, runtimeEffect});
652 } else {
653 runtimeEffect = effectIter->second;
654 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700655 mat4 colorTransform = parameters.layer.colorTransform;
656
657 colorTransform *=
658 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
659 parameters.layerDimmingRatio, 1.f));
Alec Mouri1a3c5452022-03-04 22:44:51 +0000660 const auto targetBuffer = parameters.layer.source.buffer.buffer;
661 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
662 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700663 return createLinearEffectShader(parameters.shader, effect, runtimeEffect, colorTransform,
664 parameters.display.maxLuminance,
Alec Mourib21d94e2022-01-13 17:44:10 -0800665 parameters.display.currentLuminanceNits,
Alec Mouri1a3c5452022-03-04 22:44:51 +0000666 parameters.layer.source.buffer.maxLuminanceNits,
Alec Mourifcedb9c2022-04-11 20:02:17 +0000667 hardwareBuffer, parameters.display.renderIntent);
Ana Krulec47814212021-01-06 19:00:10 -0800668 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700669 return parameters.shader;
Ana Krulec47814212021-01-06 19:00:10 -0800670}
671
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500672void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500673 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500674 // Record display settings when capture is running.
675 std::stringstream displaySettings;
676 PrintTo(display, &displaySettings);
677 // Store the DisplaySettings in additional information.
678 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
679 SkData::MakeWithCString(displaySettings.str().c_str()));
680 }
681
682 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
683 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
684 // displays might have different scaling when compared to the physical screen.
685
686 canvas->clipRect(getSkRect(display.physicalDisplay));
687 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
688
689 const auto clipWidth = display.clip.width();
690 const auto clipHeight = display.clip.height();
691 auto rotatedClipWidth = clipWidth;
692 auto rotatedClipHeight = clipHeight;
693 // Scale is contingent on the rotation result.
694 if (display.orientation & ui::Transform::ROT_90) {
695 std::swap(rotatedClipWidth, rotatedClipHeight);
696 }
697 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
698 static_cast<SkScalar>(rotatedClipWidth);
699 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
700 static_cast<SkScalar>(rotatedClipHeight);
701 canvas->scale(scaleX, scaleY);
702
703 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
704 // back so that the top left corner of the clip is at (0, 0).
705 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
706 canvas->rotate(toDegrees(display.orientation));
707 canvas->translate(-clipWidth / 2, -clipHeight / 2);
708 canvas->translate(-display.clip.left, -display.clip.top);
709}
710
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500711class AutoSaveRestore {
712public:
713 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
714 ~AutoSaveRestore() { restore(); }
715 void replace(SkCanvas* canvas) {
716 mCanvas = canvas;
717 mSaveCount = canvas->save();
718 }
719 void restore() {
720 if (mCanvas) {
721 mCanvas->restoreToCount(mSaveCount);
722 mCanvas = nullptr;
723 }
724 }
725
726private:
727 SkCanvas* mCanvas;
728 int mSaveCount;
729};
730
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400731static SkRRect getBlurRRect(const BlurRegion& region) {
732 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
733 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
734 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
735 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
736 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
737 SkRRect roundedRect;
738 roundedRect.setRectRadii(rect, radii);
739 return roundedRect;
740}
741
Alec Mouri85065692022-03-18 00:58:26 +0000742// Arbitrary default margin which should be close enough to zero.
743constexpr float kDefaultMargin = 0.0001f;
744static bool equalsWithinMargin(float expected, float value, float margin = kDefaultMargin) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700745 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
746 return std::abs(expected - value) < margin;
747}
748
Sally Qi4cabdd02021-08-05 16:45:57 -0700749void SkiaGLRenderEngine::drawLayersInternal(
750 const std::shared_ptr<std::promise<RenderEngineResult>>&& resultPromise,
Sally Qi59a9f502021-10-12 18:53:23 +0000751 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
Sally Qi4cabdd02021-08-05 16:45:57 -0700752 const std::shared_ptr<ExternalTexture>& buffer, const bool /*useFramebufferCache*/,
753 base::unique_fd&& bufferFence) {
John Reck67b1e2b2020-08-26 13:17:24 -0700754 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800755
John Reck67b1e2b2020-08-26 13:17:24 -0700756 std::lock_guard<std::mutex> lock(mRenderingMutex);
757 if (layers.empty()) {
758 ALOGV("Drawing empty layer stack");
Sally Qi4cabdd02021-08-05 16:45:57 -0700759 resultPromise->set_value({NO_ERROR, base::unique_fd()});
760 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700761 }
762
John Reck67b1e2b2020-08-26 13:17:24 -0700763 if (buffer == nullptr) {
764 ALOGE("No output buffer provided. Aborting GPU composition.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700765 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
766 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700767 }
768
Alec Mouria90a5702021-04-16 16:36:21 +0000769 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800770
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400771 auto grContext = getActiveGrContext();
Derek Sollenberger45007182021-06-10 14:47:21 -0400772 auto& cache = mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700773
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400774 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
775 DeferTextureCleanup dtc(mTextureCleanupMgr);
776
Alec Mouria90a5702021-04-16 16:36:21 +0000777 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
778 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
779 surfaceTextureRef = it->second;
780 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400781 surfaceTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400782 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
783 buffer->getBuffer()
784 ->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400785 true, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -0700786 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800787
Alec Mouri4ee7b492021-08-11 10:36:55 -0700788 // wait on the buffer to be ready to use prior to using it
789 waitFence(bufferFence);
790
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500791 const ui::Dataspace dstDataspace =
Alec Mourid2bcbae2021-06-28 17:02:17 -0700792 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400793 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700794
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500795 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
796 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800797 ALOGE("Cannot acquire canvas from Skia.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700798 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
799 return;
Ana Krulec6eab17a2020-12-09 15:52:36 -0800800 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500801
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400802 // setup color filter if necessary
803 sk_sp<SkColorFilter> displayColorTransform;
Leon Scroggins III745dcaa2022-01-26 11:55:58 -0500804 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400805 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
806 }
807 const bool ctModifiesAlpha =
808 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
809
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700810 // Find the max layer white point to determine the max luminance of the scene...
811 const float maxLayerWhitePoint = std::transform_reduce(
812 layers.cbegin(), layers.cend(), 0.f,
813 [](float left, float right) { return std::max(left, right); },
814 [&](const auto& l) { return l.whitePointNits; });
815
816 // ...and compute the dimming ratio if dimming is requested
817 const float displayDimmingRatio = display.targetLuminanceNits > 0.f &&
818 maxLayerWhitePoint > 0.f && display.targetLuminanceNits > maxLayerWhitePoint
819 ? maxLayerWhitePoint / display.targetLuminanceNits
820 : 1.f;
821
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500822 // Find if any layers have requested blur, we'll use that info to decide when to render to an
823 // offscreen buffer and when to render to the native buffer.
824 sk_sp<SkSurface> activeSurface(dstSurface);
825 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500826 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500827 const LayerSettings* blurCompositionLayer = nullptr;
828 if (mBlurFilter) {
829 bool requiresCompositionLayer = false;
830 for (const auto& layer : layers) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400831 // if the layer doesn't have blur or it is not visible then continue
832 if (!layerHasBlur(layer, ctModifiesAlpha)) {
833 continue;
834 }
Sally Qi59a9f502021-10-12 18:53:23 +0000835 if (layer.backgroundBlurRadius > 0 &&
Robin Lee26dacab2021-08-09 14:31:01 +0200836 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500837 requiresCompositionLayer = true;
838 }
Sally Qi59a9f502021-10-12 18:53:23 +0000839 for (auto region : layer.blurRegions) {
Robin Lee26dacab2021-08-09 14:31:01 +0200840 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500841 requiresCompositionLayer = true;
842 }
843 }
844 if (requiresCompositionLayer) {
845 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500846 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Sally Qi59a9f502021-10-12 18:53:23 +0000847 blurCompositionLayer = &layer;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500848 break;
849 }
850 }
851 }
852
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500853 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700854 // Clear the entire canvas with a transparent black to prevent ghost images.
855 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500856 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800857
John Reck67b1e2b2020-08-26 13:17:24 -0700858 for (const auto& layer : layers) {
Sally Qi59a9f502021-10-12 18:53:23 +0000859 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
Galia Peychevaf7889b32020-11-25 22:22:40 +0100860
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400861 if (kPrintLayerSettings) {
862 std::stringstream ls;
Sally Qi59a9f502021-10-12 18:53:23 +0000863 PrintTo(layer, &ls);
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400864 auto debugs = ls.str();
865 int pos = 0;
866 while (pos < debugs.size()) {
867 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
868 pos += 1000;
869 }
870 }
871
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500872 sk_sp<SkImage> blurInput;
Sally Qi59a9f502021-10-12 18:53:23 +0000873 if (blurCompositionLayer == &layer) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500874 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
875 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
876
877 // save a snapshot of the activeSurface to use as input to the blur shaders
878 blurInput = activeSurface->makeImageSnapshot();
879
Leon Scroggins III55bf4742022-03-17 14:11:17 -0400880 // blit the offscreen framebuffer into the destination AHB, but only
881 // if there are blur regions. backgroundBlurRadius blurs the entire
882 // image below, so it can skip this step.
883 if (layer.blurRegions.size()) {
884 SkPaint paint;
885 paint.setBlendMode(SkBlendMode::kSrc);
886 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
887 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
888 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
889 String8::format("SurfaceID|%" PRId64, id).c_str(),
890 nullptr);
891 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
892 } else {
893 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
894 }
Derek Sollenberger76664d62021-02-04 11:13:09 -0500895 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500896
897 // assign dstCanvas to canvas and ensure that the canvas state is up to date
898 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500899 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500900 initCanvas(canvas, display);
901
902 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
903 dstSurface->getCanvas()->getSaveCount());
904 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
905 dstSurface->getCanvas()->getTotalMatrix());
906
907 // assign dstSurface to activeSurface
908 activeSurface = dstSurface;
909 }
910
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500911 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500912 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800913 // Record the name of the layer if the capture is running.
914 std::stringstream layerSettings;
Sally Qi59a9f502021-10-12 18:53:23 +0000915 PrintTo(layer, &layerSettings);
Ana Krulec6eab17a2020-12-09 15:52:36 -0800916 // Store the LayerSettings in additional information.
Sally Qi59a9f502021-10-12 18:53:23 +0000917 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
Ana Krulec6eab17a2020-12-09 15:52:36 -0800918 SkData::MakeWithCString(layerSettings.str().c_str()));
919 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100920 // Layers have a local transform that should be applied to them
Sally Qi59a9f502021-10-12 18:53:23 +0000921 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100922
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400923 const auto [bounds, roundRectClip] =
Sally Qi59a9f502021-10-12 18:53:23 +0000924 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
925 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400926 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500927 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
928
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500929 // if multiple layers have blur, then we need to take a snapshot now because
930 // only the lowest layer will have blurImage populated earlier
931 if (!blurInput) {
932 blurInput = activeSurface->makeImageSnapshot();
933 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500934 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400935 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
936
937 // if the clip needs to be applied then apply it now and make sure
938 // it is restored before we attempt to draw any shadows.
939 SkAutoCanvasRestore acr(canvas, true);
940 if (!roundRectClip.isEmpty()) {
941 canvas->clipRRect(roundRectClip, true);
942 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500943
Galia Peychevae425ac82021-03-15 17:12:03 +0100944 // TODO(b/182216890): Filter out empty layers earlier
945 if (blurRect.width() > 0 && blurRect.height() > 0) {
Sally Qi59a9f502021-10-12 18:53:23 +0000946 if (layer.backgroundBlurRadius > 0) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100947 ATRACE_NAME("BackgroundBlur");
Sally Qi59a9f502021-10-12 18:53:23 +0000948 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
949 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100950
Sally Qi59a9f502021-10-12 18:53:23 +0000951 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500952
Sally Qi59a9f502021-10-12 18:53:23 +0000953 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400954 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700955 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400956
Sally Qi59a9f502021-10-12 18:53:23 +0000957 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
958 for (auto region : layer.blurRegions) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100959 if (cachedBlurs[region.blurRadius] == nullptr) {
960 ATRACE_NAME("BlurRegion");
961 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400962 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100963 blurRect);
964 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500965
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400966 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
967 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100968 cachedBlurs[region.blurRadius], blurInput);
969 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700970 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700971 }
972
Sally Qi59a9f502021-10-12 18:53:23 +0000973 if (layer.shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400974 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
Sally Qi59a9f502021-10-12 18:53:23 +0000975 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
Leon Scroggins III63e86952021-05-12 10:45:08 -0400976
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400977 SkRRect shadowBounds, shadowClip;
Sally Qi59a9f502021-10-12 18:53:23 +0000978 if (layer.geometry.boundaries == layer.shadow.boundaries) {
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400979 shadowBounds = bounds;
980 shadowClip = roundRectClip;
981 } else {
982 std::tie(shadowBounds, shadowClip) =
Sally Qi59a9f502021-10-12 18:53:23 +0000983 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
984 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400985 }
986
Leon Scroggins III63e86952021-05-12 10:45:08 -0400987 // Technically, if bounds is a rect and roundRectClip is not empty,
988 // it means that the bounds and roundedCornersCrop were different
989 // enough that we should intersect them to find the proper shadow.
990 // In practice, this often happens when the two rectangles appear to
991 // not match due to rounding errors. Draw the rounded version, which
992 // looks more like the intent.
993 const auto& rrect =
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400994 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
Sally Qi59a9f502021-10-12 18:53:23 +0000995 drawShadow(canvas, rrect, layer.shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500996 }
997
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700998 const float layerDimmingRatio = layer.whitePointNits <= 0.f
999 ? displayDimmingRatio
1000 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
1001
Alec Mouri85065692022-03-18 00:58:26 +00001002 const bool dimInLinearSpace = display.dimmingStage !=
1003 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
1004
Sally Qi59a9f502021-10-12 18:53:23 +00001005 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001006 (mUseColorManagement &&
Sally Qi59a9f502021-10-12 18:53:23 +00001007 needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
Alec Mouri85065692022-03-18 00:58:26 +00001008 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio));
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001009
1010 // quick abort from drawing the remaining portion of the layer
Sally Qi59a9f502021-10-12 18:53:23 +00001011 if (layer.skipContentDraw ||
1012 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001013 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001014 continue;
1015 }
1016
1017 // If we need to map to linear space or color management is disabled, then mark the source
1018 // image with the same colorspace as the destination surface so that Skia's color
1019 // management is a no-op.
1020 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
1021 ? dstDataspace
Sally Qi59a9f502021-10-12 18:53:23 +00001022 : layer.sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -08001023
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001024 SkPaint paint;
Sally Qi59a9f502021-10-12 18:53:23 +00001025 if (layer.source.buffer.buffer) {
John Reck67b1e2b2020-08-26 13:17:24 -07001026 ATRACE_NAME("DrawImage");
Sally Qi59a9f502021-10-12 18:53:23 +00001027 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
1028 const auto& item = layer.source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001029 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +00001030
1031 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
1032 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001033 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -07001034 } else {
Alec Mouria90a5702021-04-16 16:36:21 +00001035 // If we didn't find the image in the cache, then create a local ref but don't cache
1036 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
1037 // we didn't find anything in the cache then we intentionally did not cache this
1038 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001039 imageTextureRef = std::make_shared<
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001040 AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001041 item.buffer->getBuffer()->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -04001042 false, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -07001043 }
Alec Mouri1a4d0642020-11-13 17:42:01 -08001044
Alec Mouri4ee7b492021-08-11 10:36:55 -07001045 // if the layer's buffer has a fence, then we must must respect the fence prior to using
1046 // the buffer.
Sally Qi59a9f502021-10-12 18:53:23 +00001047 if (layer.source.buffer.fence != nullptr) {
1048 waitFence(layer.source.buffer.fence->get());
Alec Mouri4ee7b492021-08-11 10:36:55 -07001049 }
1050
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001051 // isOpaque means we need to ignore the alpha in the image,
1052 // replacing it with the alpha specified by the LayerSettings. See
1053 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
1054 // The proper way to do this is to use an SkColorType that ignores
1055 // alpha, like kRGB_888x_SkColorType, and that is used if the
1056 // incoming image is kRGBA_8888_SkColorType. However, the incoming
1057 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
1058 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
1059 // kRGB_101010x_SkColorType, but it is not yet supported as a source
1060 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
1061 // meantime, we'll use a workaround that works unless we need to do
1062 // any color conversion. The workaround requires that we pretend the
1063 // image is already premultiplied, so that we do not premultiply it
1064 // before applying SkBlendMode::kPlus.
1065 const bool useIsOpaqueWorkaround = item.isOpaque &&
1066 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
1067 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
1068 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
1069 : item.isOpaque ? kOpaque_SkAlphaType
1070 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
1071 : kUnpremul_SkAlphaType;
1072 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -07001073
1074 auto texMatrix = getSkM44(item.textureTransform).asM33();
1075 // textureTansform was intended to be passed directly into a shader, so when
1076 // building the total matrix with the textureTransform we need to first
1077 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001078 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001079 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -07001080
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001081 SkMatrix matrix;
1082 if (!texMatrix.invert(&matrix)) {
1083 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -07001084 }
Ana Krulecf9a15d92020-12-11 08:35:00 -08001085 // The shader does not respect the translation, so we add it to the texture
1086 // transform for the SkImage. This will make sure that the correct layer contents
1087 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001088 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -07001089
Ana Krulecb7b28b22020-11-23 14:48:58 -08001090 sk_sp<SkShader> shader;
1091
Sally Qi59a9f502021-10-12 18:53:23 +00001092 if (layer.source.buffer.useTextureFiltering) {
Ana Krulecb7b28b22020-11-23 14:48:58 -08001093 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1094 SkSamplingOptions(
1095 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1096 &matrix);
1097 } else {
Mike Reed711e1f02020-12-11 13:06:19 -05001098 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -08001099 }
Alec Mouri029d1952020-10-12 10:37:08 -07001100
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001101 if (useIsOpaqueWorkaround) {
Alec Mouric0aae732021-01-12 13:32:18 -08001102 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1103 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001104 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001105 }
1106
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001107 paint.setShader(createRuntimeEffectShader(
1108 RuntimeEffectShaderParameters{.shader = shader,
1109 .layer = layer,
1110 .display = display,
1111 .undoPremultipliedAlpha = !item.isOpaque &&
1112 item.usePremultipliedAlpha,
1113 .requiresLinearEffect = requiresLinearEffect,
Alec Mouri85065692022-03-18 00:58:26 +00001114 .layerDimmingRatio = dimInLinearSpace
1115 ? layerDimmingRatio
1116 : 1.f}));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001117
Alec Mouri88acab92022-03-24 23:41:01 +00001118 // Turn on dithering when dimming beyond this (arbitrary) threshold...
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001119 static constexpr float kDimmingThreshold = 0.2f;
Alec Mouri88acab92022-03-24 23:41:01 +00001120 // ...or we're rendering an HDR layer down to an 8-bit target
1121 // Most HDR standards require at least 10-bits of color depth for source content, so we
1122 // can just extract the transfer function rather than dig into precise gralloc layout.
1123 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
1124 const bool requiresDownsample = isHdrDataspace(layer.sourceDataspace) &&
1125 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
1126 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001127 paint.setDither(true);
1128 }
Sally Qi59a9f502021-10-12 18:53:23 +00001129 paint.setAlphaf(layer.alpha);
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001130
1131 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1132 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001133
1134 // SysUI creates the alpha layer as a coverage layer, which is
1135 // appropriate for the DPU. Use a color matrix to convert it to
1136 // a mask.
1137 // TODO (b/219525258): Handle input as a mask.
1138 //
1139 // The color matrix will convert A8 pixels with no alpha to
1140 // black, as described by this vector. If the display handles
1141 // the color transform, we need to invert it to find the color
1142 // that will result in black after the DPU applies the transform.
1143 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1144 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1145 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1146 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1147 black = colorSpaceMatrix * black;
1148 } else {
1149 // We'll just have to use 0,0,0 as black, which should
1150 // be close to correct.
1151 ALOGI("Could not invert colorTransform!");
1152 }
1153 }
1154 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1155 0, 0, 0, 0, black[1],
1156 0, 0, 0, 0, black[2],
1157 0, 0, 0, -1, 1);
1158 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1159 // On the other hand, if the device doesn't handle it, we
1160 // have to apply it ourselves.
1161 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1162 }
1163 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001164 }
John Reck67b1e2b2020-08-26 13:17:24 -07001165 } else {
1166 ATRACE_NAME("DrawColor");
Sally Qi59a9f502021-10-12 18:53:23 +00001167 const auto color = layer.source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001168 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1169 .fG = color.g,
1170 .fB = color.b,
Sally Qi59a9f502021-10-12 18:53:23 +00001171 .fA = layer.alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001172 toSkColorSpace(layerDataspace));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001173 paint.setShader(createRuntimeEffectShader(
1174 RuntimeEffectShaderParameters{.shader = shader,
1175 .layer = layer,
1176 .display = display,
1177 .undoPremultipliedAlpha = false,
1178 .requiresLinearEffect = requiresLinearEffect,
1179 .layerDimmingRatio = layerDimmingRatio}));
John Reck67b1e2b2020-08-26 13:17:24 -07001180 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001181
Sally Qi59a9f502021-10-12 18:53:23 +00001182 if (layer.disableBlending) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001183 paint.setBlendMode(SkBlendMode::kSrc);
1184 }
1185
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001186 // An A8 buffer will already have the proper color filter attached to
1187 // its paint, including the displayColorTransform as needed.
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001188 if (!paint.getColorFilter()) {
Alec Mouri85065692022-03-18 00:58:26 +00001189 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1190 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1191 // can assume a gamma 2.2 transfer function.
1192 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1193 const auto gammaCorrectedDimmingRatio =
1194 std::pow(layerDimmingRatio, kInverseGamma22);
1195 const auto dimmingMatrix =
1196 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1197 gammaCorrectedDimmingRatio, 1.f));
1198 paint.setColorFilter(SkColorFilters::Matrix(
1199 toSkColorMatrix(display.colorTransform * dimmingMatrix)));
1200 } else {
1201 paint.setColorFilter(displayColorTransform);
1202 }
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001203 }
Alec Mourib34f0b72020-10-02 13:18:34 -07001204
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001205 if (!roundRectClip.isEmpty()) {
1206 canvas->clipRRect(roundRectClip, true);
1207 }
1208
1209 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001210 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001211 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001212 } else {
Nader Jawad63644d32021-05-07 10:44:21 -07001213 canvas->drawRect(bounds.rect(), paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -07001214 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001215 if (kFlushAfterEveryLayer) {
1216 ATRACE_NAME("flush surface");
1217 activeSurface->flush();
1218 }
John Reck67b1e2b2020-08-26 13:17:24 -07001219 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001220 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001221 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001222 {
1223 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001224 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1225 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001226 }
1227
Sally Qi4cabdd02021-08-05 16:45:57 -07001228 base::unique_fd drawFence = flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001229
1230 // If flush failed or we don't support native fences, we need to force the
1231 // gl command stream to be executed.
Sally Qi4cabdd02021-08-05 16:45:57 -07001232 bool requireSync = drawFence.get() < 0;
John Reck67b1e2b2020-08-26 13:17:24 -07001233 if (requireSync) {
1234 ATRACE_BEGIN("Submit(sync=true)");
1235 } else {
1236 ATRACE_BEGIN("Submit(sync=false)");
1237 }
Lucas Dupind508e472020-11-04 04:32:06 +00001238 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001239 ATRACE_END();
1240 if (!success) {
1241 ALOGE("Failed to flush RenderEngine commands");
1242 // Chances are, something illegal happened (either the caller passed
1243 // us bad parameters, or we messed up our shader generation).
Sally Qi4cabdd02021-08-05 16:45:57 -07001244 resultPromise->set_value({INVALID_OPERATION, std::move(drawFence)});
1245 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001246 }
1247
1248 // checkErrors();
Sally Qi4cabdd02021-08-05 16:45:57 -07001249 resultPromise->set_value({NO_ERROR, std::move(drawFence)});
1250 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001251}
1252
Lucas Dupin3f11e922020-09-22 17:31:04 -07001253inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1254 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1255}
1256
1257inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1258 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1259}
1260
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001261/**
1262 * Verifies that common, simple bounds + clip combinations can be converted into
1263 * a single RRect draw call returning true if possible. If true the radii parameter
1264 * will be filled with the correct radii values that combined with bounds param will
1265 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
1266 */
1267static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
1268 const SkRect& insetCrop, float cornerRadius,
1269 SkVector radii[4]) {
1270 const bool leftEqual = bounds.fLeft == crop.fLeft;
1271 const bool topEqual = bounds.fTop == crop.fTop;
1272 const bool rightEqual = bounds.fRight == crop.fRight;
1273 const bool bottomEqual = bounds.fBottom == crop.fBottom;
1274
1275 // In the event that the corners of the bounds only partially align with the crop we
1276 // need to ensure that the resulting shape can still be represented as a round rect.
1277 // In particular the round rect implementation will scale the value of all corner radii
1278 // if the sum of the radius along any edge is greater than the length of that edge.
1279 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
1280 const bool requiredWidth = bounds.width() > (cornerRadius * 2);
1281 const bool requiredHeight = bounds.height() > (cornerRadius * 2);
1282 if (!requiredWidth || !requiredHeight) {
1283 return false;
1284 }
1285
1286 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
1287 // contained within the cropped shape and does not need rounded.
1288 // compute the UpperLeft corner radius
1289 if (leftEqual && topEqual) {
1290 radii[0].set(cornerRadius, cornerRadius);
1291 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
1292 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
1293 radii[0].set(0, 0);
1294 } else {
1295 return false;
1296 }
1297 // compute the UpperRight corner radius
1298 if (rightEqual && topEqual) {
1299 radii[1].set(cornerRadius, cornerRadius);
1300 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
1301 (topEqual && bounds.fRight <= insetCrop.fRight)) {
1302 radii[1].set(0, 0);
1303 } else {
1304 return false;
1305 }
1306 // compute the BottomRight corner radius
1307 if (rightEqual && bottomEqual) {
1308 radii[2].set(cornerRadius, cornerRadius);
1309 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
1310 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
1311 radii[2].set(0, 0);
1312 } else {
1313 return false;
1314 }
1315 // compute the BottomLeft corner radius
1316 if (leftEqual && bottomEqual) {
1317 radii[3].set(cornerRadius, cornerRadius);
1318 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
1319 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
1320 radii[3].set(0, 0);
1321 } else {
1322 return false;
1323 }
1324
1325 return true;
1326}
1327
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001328inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(const FloatRect& boundsRect,
1329 const FloatRect& cropRect,
1330 const float cornerRadius) {
1331 const SkRect bounds = getSkRect(boundsRect);
1332 const SkRect crop = getSkRect(cropRect);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001333
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001334 SkRRect clip;
1335 if (cornerRadius > 0) {
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001336 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
1337 if (bounds == crop || crop.isEmpty()) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001338 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1339 }
1340
1341 // This makes an effort to speed up common, simple bounds + clip combinations by
1342 // converting them to a single RRect draw. It is possible there are other cases
1343 // that can be converted.
1344 if (crop.contains(bounds)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001345 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001346 if (insetCrop.contains(bounds)) {
1347 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001348 }
1349
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001350 SkVector radii[4];
1351 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001352 SkRRect intersectionBounds;
1353 intersectionBounds.setRectRadii(bounds, radii);
1354 return {intersectionBounds, clip};
1355 }
1356 }
1357
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001358 // we didn't hit any of our fast paths so set the clip to the cropRect
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001359 clip.setRectXY(crop, cornerRadius, cornerRadius);
1360 }
1361
1362 // if we hit this point then we either don't have rounded corners or we are going to rely
1363 // on the clip to round the corners for us
1364 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001365}
1366
Sally Qi59a9f502021-10-12 18:53:23 +00001367inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings& layer,
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001368 bool colorTransformModifiesAlpha) {
Sally Qi59a9f502021-10-12 18:53:23 +00001369 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001370 // return false if the content is opaque and would therefore occlude the blur
Sally Qi59a9f502021-10-12 18:53:23 +00001371 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
1372 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
1373 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001374 }
1375 return false;
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001376}
1377
Lucas Dupin3f11e922020-09-22 17:31:04 -07001378inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1379 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1380}
1381
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001382inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1383 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1384 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1385 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1386 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1387}
1388
Lucas Dupin3f11e922020-09-22 17:31:04 -07001389inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1390 return SkPoint3::Make(vector.x, vector.y, vector.z);
1391}
1392
John Reck67b1e2b2020-08-26 13:17:24 -07001393size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1394 return mGrContext->maxTextureSize();
1395}
1396
1397size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1398 return mGrContext->maxRenderTargetSize();
1399}
1400
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001401void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001402 const ShadowSettings& settings) {
1403 ATRACE_CALL();
1404 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001405 const auto flags =
1406 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1407
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001408 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001409 getSkPoint3(settings.lightPos), settings.lightRadius,
1410 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1411 flags);
1412}
1413
John Reck67b1e2b2020-08-26 13:17:24 -07001414EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001415 EGLContext shareContext,
1416 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001417 Protection protection) {
1418 EGLint renderableType = 0;
1419 if (config == EGL_NO_CONFIG_KHR) {
1420 renderableType = EGL_OPENGL_ES3_BIT;
1421 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1422 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1423 }
1424 EGLint contextClientVersion = 0;
1425 if (renderableType & EGL_OPENGL_ES3_BIT) {
1426 contextClientVersion = 3;
1427 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1428 contextClientVersion = 2;
1429 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1430 contextClientVersion = 1;
1431 } else {
1432 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1433 }
1434
1435 std::vector<EGLint> contextAttributes;
1436 contextAttributes.reserve(7);
1437 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1438 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001439 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001440 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001441 switch (*contextPriority) {
1442 case ContextPriority::REALTIME:
1443 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1444 break;
1445 case ContextPriority::MEDIUM:
1446 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1447 break;
1448 case ContextPriority::LOW:
1449 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1450 break;
1451 case ContextPriority::HIGH:
1452 default:
1453 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1454 break;
1455 }
John Reck67b1e2b2020-08-26 13:17:24 -07001456 }
1457 if (protection == Protection::PROTECTED) {
1458 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1459 contextAttributes.push_back(EGL_TRUE);
1460 }
1461 contextAttributes.push_back(EGL_NONE);
1462
1463 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1464
1465 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1466 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1467 // EGL_NO_CONTEXT so that we can abort.
1468 if (config != EGL_NO_CONFIG_KHR) {
1469 return context;
1470 }
1471 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1472 // should try to fall back to GLES 2.
1473 contextAttributes[1] = 2;
1474 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1475 }
1476
1477 return context;
1478}
1479
Alec Mourid6f09462020-12-07 11:18:17 -08001480std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1481 const RenderEngineCreationArgs& args) {
1482 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1483 return std::nullopt;
1484 }
1485
1486 switch (args.contextPriority) {
1487 case RenderEngine::ContextPriority::REALTIME:
1488 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1489 return RenderEngine::ContextPriority::REALTIME;
1490 } else {
1491 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1492 return RenderEngine::ContextPriority::HIGH;
1493 }
1494 case RenderEngine::ContextPriority::HIGH:
1495 case RenderEngine::ContextPriority::MEDIUM:
1496 case RenderEngine::ContextPriority::LOW:
1497 return args.contextPriority;
1498 default:
1499 return std::nullopt;
1500 }
1501}
1502
John Reck67b1e2b2020-08-26 13:17:24 -07001503EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1504 EGLConfig config, int hwcFormat,
1505 Protection protection) {
1506 EGLConfig placeholderConfig = config;
1507 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1508 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1509 }
1510 std::vector<EGLint> attributes;
1511 attributes.reserve(7);
1512 attributes.push_back(EGL_WIDTH);
1513 attributes.push_back(1);
1514 attributes.push_back(EGL_HEIGHT);
1515 attributes.push_back(1);
1516 if (protection == Protection::PROTECTED) {
1517 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1518 attributes.push_back(EGL_TRUE);
1519 }
1520 attributes.push_back(EGL_NONE);
1521
1522 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1523}
1524
Alec Mourid6f09462020-12-07 11:18:17 -08001525int SkiaGLRenderEngine::getContextPriority() {
1526 int value;
1527 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1528 return value;
1529}
1530
Ady Abrahamed3290f2021-05-17 15:12:14 -07001531void SkiaGLRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001532 // This cache multiplier was selected based on review of cache sizes relative
1533 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1534 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1535 // conservative default based on that analysis.
1536 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1537 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1538
1539 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001540 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001541
1542 // if it is possible to switch contexts then we will resize the other context
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001543 const bool originalProtectedState = mInProtectedContext;
1544 useProtectedContext(!mInProtectedContext);
1545 if (mInProtectedContext != originalProtectedState) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001546 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001547 // reset back to the initial context that was active when this method was called
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001548 useProtectedContext(originalProtectedState);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001549 }
1550}
1551
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001552void SkiaGLRenderEngine::dump(std::string& result) {
1553 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1554
1555 StringAppendF(&result, "\n ------------RE-----------------\n");
1556 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1557 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1558 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1559 extensions.getVersion());
1560 StringAppendF(&result, "%s\n", extensions.getExtensions());
1561 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1562 supportsProtectedContent());
1563 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001564 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1565 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001566
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001567 std::vector<ResourcePair> cpuResourceMap = {
1568 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1569 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1570 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1571 {"skia/sk_resource_cache/tessellated", "Shadows"},
1572 {"skia", "Other"},
1573 };
1574 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1575 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1576 StringAppendF(&result, "Skia CPU Caches: ");
1577 cpuReporter.logTotals(result);
1578 cpuReporter.logOutput(result);
1579
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001580 {
1581 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001582
1583 std::vector<ResourcePair> gpuResourceMap = {
1584 {"texture_renderbuffer", "Texture/RenderBuffer"},
1585 {"texture", "Texture"},
1586 {"gr_text_blob_cache", "Text"},
1587 {"skia", "Other"},
1588 };
1589 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1590 mGrContext->dumpMemoryStatistics(&gpuReporter);
1591 StringAppendF(&result, "Skia's GPU Caches: ");
1592 gpuReporter.logTotals(result);
1593 gpuReporter.logOutput(result);
1594 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1595 gpuReporter.logOutput(result, true);
1596
Alec Mouria90a5702021-04-16 16:36:21 +00001597 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1598 mGraphicBufferExternalRefs.size());
1599 StringAppendF(&result, "Dumping buffer ids...\n");
1600 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1601 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1602 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001603 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1604 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001605 StringAppendF(&result, "Dumping buffer ids...\n");
1606 // TODO(178539829): It would be nice to know which layer these are coming from and what
1607 // the texture sizes are.
1608 for (const auto& [id, unused] : mTextureCache) {
1609 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1610 }
1611 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001612
1613 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001614 if (mProtectedGrContext) {
1615 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1616 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001617 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1618 gpuProtectedReporter.logTotals(result);
1619 gpuProtectedReporter.logOutput(result);
1620 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1621 gpuProtectedReporter.logOutput(result, true);
1622
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001623 StringAppendF(&result, "\n");
1624 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1625 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1626 StringAppendF(&result, "- inputDataspace: %s\n",
1627 dataspaceDetails(
1628 static_cast<android_dataspace>(linearEffect.inputDataspace))
1629 .c_str());
1630 StringAppendF(&result, "- outputDataspace: %s\n",
1631 dataspaceDetails(
1632 static_cast<android_dataspace>(linearEffect.outputDataspace))
1633 .c_str());
1634 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1635 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1636 }
1637 }
1638 StringAppendF(&result, "\n");
1639}
1640
John Reck67b1e2b2020-08-26 13:17:24 -07001641} // namespace skia
1642} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001643} // namespace android