blob: 8943db0294964764e8b177138387ea103f25b118 [file] [log] [blame]
John Reck67b1e2b2020-08-26 13:17:24 -07001/*
2 * Copyright 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
Ana Krulec70d15b1b2020-12-01 10:05:15 -080018#undef LOG_TAG
19#define LOG_TAG "RenderEngine"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
Alec Mouri4ce5ec02021-01-07 17:33:21 -080022#include "SkiaGLRenderEngine.h"
John Reck67b1e2b2020-08-26 13:17:24 -070023
John Reck67b1e2b2020-08-26 13:17:24 -070024#include <EGL/egl.h>
25#include <EGL/eglext.h>
John Reck67b1e2b2020-08-26 13:17:24 -070026#include <GrContextOptions.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000027#include <SkBlendMode.h>
John Reck67b1e2b2020-08-26 13:17:24 -070028#include <SkCanvas.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000029#include <SkColor.h>
Alec Mourib34f0b72020-10-02 13:18:34 -070030#include <SkColorFilter.h>
31#include <SkColorMatrix.h>
Alec Mourib5777452020-09-28 11:32:42 -070032#include <SkColorSpace.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000033#include <SkData.h>
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040034#include <SkGraphics.h>
John Reck67b1e2b2020-08-26 13:17:24 -070035#include <SkImage.h>
Lucas Dupinf4cb4a02020-09-22 14:19:26 -070036#include <SkImageFilters.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000037#include <SkImageInfo.h>
38#include <SkM44.h>
39#include <SkMatrix.h>
40#include <SkPaint.h>
41#include <SkPath.h>
42#include <SkPoint.h>
43#include <SkRect.h>
44#include <SkRefCnt.h>
Alec Mouric0aae732021-01-12 13:32:18 -080045#include <SkRegion.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000046#include <SkRRect.h>
47#include <SkRuntimeEffect.h>
48#include <SkSamplingOptions.h>
49#include <SkScalar.h>
50#include <SkShader.h>
Lucas Dupin3f11e922020-09-22 17:31:04 -070051#include <SkShadowUtils.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000052#include <SkString.h>
John Reck67b1e2b2020-08-26 13:17:24 -070053#include <SkSurface.h>
Kevin Lubick1d530202022-02-26 13:48:04 +000054#include <SkTileMode.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080055#include <android-base/stringprintf.h>
Alec Mourib5777452020-09-28 11:32:42 -070056#include <gl/GrGLInterface.h>
Alec Mouricbd30932021-06-09 15:52:25 -070057#include <gui/TraceUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080058#include <sync/sync.h>
59#include <ui/BlurRegion.h>
Alec Mouri88acab92022-03-24 23:41:01 +000060#include <ui/DataspaceUtils.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080061#include <ui/DebugUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080062#include <ui/GraphicBuffer.h>
63#include <utils/Trace.h>
Alec Mourib5777452020-09-28 11:32:42 -070064
65#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080066#include <cstdint>
67#include <memory>
Alec Mouricdf6cbc2021-11-01 17:21:15 -070068#include <numeric>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080069
70#include "../gl/GLExtensions.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040071#include "Cache.h"
Alec Mouric0aae732021-01-12 13:32:18 -080072#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080073#include "filters/BlurFilter.h"
Robin Lee26dacab2021-08-09 14:31:01 +020074#include "filters/GaussianBlurFilter.h"
Robin Lee026680a2021-07-26 12:49:53 +020075#include "filters/KawaseBlurFilter.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080076#include "filters/LinearEffect.h"
77#include "log/log_main.h"
78#include "skia/debug/SkiaCapture.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040079#include "skia/debug/SkiaMemoryReporter.h"
Nader Jawad2dfc98b2021-04-08 20:35:39 -070080#include "skia/filters/StretchShaderFactory.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080081#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070082
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040083namespace {
84// Debugging settings
85static const bool kPrintLayerSettings = false;
86static const bool kFlushAfterEveryLayer = false;
87} // namespace
88
John Reck67b1e2b2020-08-26 13:17:24 -070089bool checkGlError(const char* op, int lineNumber);
90
91namespace android {
92namespace renderengine {
93namespace skia {
94
Ana Krulec1d12b3b2021-01-27 16:49:51 -080095using base::StringAppendF;
96
John Reck67b1e2b2020-08-26 13:17:24 -070097static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
98 EGLint wanted, EGLConfig* outConfig) {
99 EGLint numConfigs = -1, n = 0;
100 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
101 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
102 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
103 configs.resize(n);
104
105 if (!configs.empty()) {
106 if (attribute != EGL_NONE) {
107 for (EGLConfig config : configs) {
108 EGLint value = 0;
109 eglGetConfigAttrib(dpy, config, attribute, &value);
110 if (wanted == value) {
111 *outConfig = config;
112 return NO_ERROR;
113 }
114 }
115 } else {
116 // just pick the first one
117 *outConfig = configs[0];
118 return NO_ERROR;
119 }
120 }
121
122 return NAME_NOT_FOUND;
123}
124
125static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
126 EGLConfig* config) {
127 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
128 // it is to be used with WIFI displays
129 status_t err;
130 EGLint wantedAttribute;
131 EGLint wantedAttributeValue;
132
133 std::vector<EGLint> attribs;
134 if (renderableType) {
135 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
136 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
137
138 // Default to 8 bits per channel.
139 const EGLint tmpAttribs[] = {
140 EGL_RENDERABLE_TYPE,
141 renderableType,
142 EGL_RECORDABLE_ANDROID,
143 EGL_TRUE,
144 EGL_SURFACE_TYPE,
145 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
146 EGL_FRAMEBUFFER_TARGET_ANDROID,
147 EGL_TRUE,
148 EGL_RED_SIZE,
149 is1010102 ? 10 : 8,
150 EGL_GREEN_SIZE,
151 is1010102 ? 10 : 8,
152 EGL_BLUE_SIZE,
153 is1010102 ? 10 : 8,
154 EGL_ALPHA_SIZE,
155 is1010102 ? 2 : 8,
156 EGL_NONE,
157 };
158 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
159 std::back_inserter(attribs));
160 wantedAttribute = EGL_NONE;
161 wantedAttributeValue = EGL_NONE;
162 } else {
163 // if no renderable type specified, fallback to a simplified query
164 wantedAttribute = EGL_NATIVE_VISUAL_ID;
165 wantedAttributeValue = format;
166 }
167
168 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
169 config);
170 if (err == NO_ERROR) {
171 EGLint caveat;
172 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
173 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
174 }
175
176 return err;
177}
178
179std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
180 const RenderEngineCreationArgs& args) {
181 // initialize EGL for the default display
182 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
183 if (!eglInitialize(display, nullptr, nullptr)) {
184 LOG_ALWAYS_FATAL("failed to initialize EGL");
185 }
186
Yiwei Zhange2650962020-12-01 23:27:58 +0000187 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700188 if (!eglVersion) {
189 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000190 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700191 }
192
Yiwei Zhange2650962020-12-01 23:27:58 +0000193 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700194 if (!eglExtensions) {
195 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000196 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700197 }
198
199 auto& extensions = gl::GLExtensions::getInstance();
200 extensions.initWithEGLStrings(eglVersion, eglExtensions);
201
202 // The code assumes that ES2 or later is available if this extension is
203 // supported.
204 EGLConfig config = EGL_NO_CONFIG_KHR;
205 if (!extensions.hasNoConfigContext()) {
206 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
207 }
208
John Reck67b1e2b2020-08-26 13:17:24 -0700209 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800210 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700211 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800212 protectedContext =
213 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700214 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
215 }
216
Alec Mourid6f09462020-12-07 11:18:17 -0800217 EGLContext ctxt =
218 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700219
220 // if can't create a GL context, we can only abort.
221 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
222
223 EGLSurface placeholder = EGL_NO_SURFACE;
224 if (!extensions.hasSurfacelessContext()) {
225 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
226 Protection::UNPROTECTED);
227 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
228 }
229 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
230 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
231 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
232 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
233
234 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
235 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
236 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
237 Protection::PROTECTED);
238 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
239 "can't create protected placeholder pbuffer");
240 }
241
242 // initialize the renderer while GL is current
243 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000244 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
245 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700246
247 ALOGI("OpenGL ES informations:");
248 ALOGI("vendor : %s", extensions.getVendor());
249 ALOGI("renderer : %s", extensions.getRenderer());
250 ALOGI("version : %s", extensions.getVersion());
251 ALOGI("extensions: %s", extensions.getExtensions());
252 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
253 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
254
255 return engine;
256}
257
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700258std::future<void> SkiaGLRenderEngine::primeCache() {
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500259 Cache::primeShaderCache(this);
Ady Abrahamfe2a6db2021-06-09 15:41:37 -0700260 return {};
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500261}
262
John Reck67b1e2b2020-08-26 13:17:24 -0700263EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
264 status_t err;
265 EGLConfig config;
266
267 // First try to get an ES3 config
268 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
269 if (err != NO_ERROR) {
270 // If ES3 fails, try to get an ES2 config
271 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
272 if (err != NO_ERROR) {
273 // If ES2 still doesn't work, probably because we're on the emulator.
274 // try a simplified query
275 ALOGW("no suitable EGLConfig found, trying a simpler query");
276 err = selectEGLConfig(display, format, 0, &config);
277 if (err != NO_ERROR) {
278 // this EGL is too lame for android
279 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
280 }
281 }
282 }
283
284 if (logConfig) {
285 // print some debugging info
286 EGLint r, g, b, a;
287 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
288 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
289 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
290 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
291 ALOGI("EGL information:");
292 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
293 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
294 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
295 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
296 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
297 }
298
299 return config;
300}
301
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400302sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
303 // This "cache" does not actually cache anything. It just allows us to
304 // monitor Skia's internal cache. So this method always returns null.
305 return nullptr;
306}
307
308void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
309 const SkString& description) {
310 mShadersCachedSinceLastCall++;
Leon Scroggins IIIadf18d82022-04-22 13:23:05 -0400311 mTotalShadersCompiled++;
312 ATRACE_FORMAT("SF cache: %i shaders", mTotalShadersCompiled);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400313}
314
315void SkiaGLRenderEngine::assertShadersCompiled(int numShaders) {
316 const int cached = mSkSLCacheMonitor.shadersCachedSinceLastCall();
317 LOG_ALWAYS_FATAL_IF(cached != numShaders, "Attempted to cache %i shaders; cached %i",
318 numShaders, cached);
319}
320
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400321int SkiaGLRenderEngine::reportShadersCompiled() {
322 return mSkSLCacheMonitor.shadersCachedSinceLastCall();
323}
324
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700325SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000326 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700327 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800328 : SkiaRenderEngine(args.renderEngineType),
329 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700330 mEGLContext(ctxt),
331 mPlaceholderSurface(placeholder),
332 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700333 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400334 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800335 mUseColorManagement(args.useColorManagement) {
Brian Salomon40de6ba2022-03-22 19:38:53 +0000336 sk_sp<const GrGLInterface> glInterface = GrGLMakeNativeInterface();
John Reck67b1e2b2020-08-26 13:17:24 -0700337 LOG_ALWAYS_FATAL_IF(!glInterface.get());
338
339 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400340 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700341 options.fDisableDistanceFieldPaths = true;
Nathaniel Nifongf8d35e92021-06-08 15:02:25 -0400342 options.fReducedShaderVariations = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400343 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000344 mGrContext = GrDirectContext::MakeGL(glInterface, options);
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400345 if (supportsProtectedContent()) {
346 useProtectedContext(true);
Lucas Dupind508e472020-11-04 04:32:06 +0000347 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
348 useProtectedContext(false);
349 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700350
351 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500352 ALOGD("Background Blurs Enabled");
Robin Lee026680a2021-07-26 12:49:53 +0200353 mBlurFilter = new KawaseBlurFilter();
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700354 }
Alec Mouric0aae732021-01-12 13:32:18 -0800355 mCapture = std::make_unique<SkiaCapture>();
356}
357
358SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100359 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800360 if (mBlurFilter) {
361 delete mBlurFilter;
362 }
363
364 mCapture = nullptr;
365
366 mGrContext->flushAndSubmit(true);
367 mGrContext->abandonContext();
368
369 if (mProtectedGrContext) {
370 mProtectedGrContext->flushAndSubmit(true);
371 mProtectedGrContext->abandonContext();
372 }
373
374 if (mPlaceholderSurface != EGL_NO_SURFACE) {
375 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
376 }
377 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
378 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
379 }
380 if (mEGLContext != EGL_NO_CONTEXT) {
381 eglDestroyContext(mEGLDisplay, mEGLContext);
382 }
383 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
384 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
385 }
386 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
387 eglTerminate(mEGLDisplay);
388 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700389}
390
Lucas Dupind508e472020-11-04 04:32:06 +0000391bool SkiaGLRenderEngine::supportsProtectedContent() const {
392 return mProtectedEGLContext != EGL_NO_CONTEXT;
393}
394
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400395GrDirectContext* SkiaGLRenderEngine::getActiveGrContext() const {
396 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
397}
398
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400399void SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
400 if (useProtectedContext == mInProtectedContext ||
401 (useProtectedContext && !supportsProtectedContent())) {
402 return;
Lucas Dupind508e472020-11-04 04:32:06 +0000403 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400404
405 // release any scratch resources before switching into a new mode
406 if (getActiveGrContext()) {
407 getActiveGrContext()->purgeUnlockedResources(true);
408 }
409
Lucas Dupind508e472020-11-04 04:32:06 +0000410 const EGLSurface surface =
411 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
412 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
Alec Mouric0aae732021-01-12 13:32:18 -0800413
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -0400414 if (eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE) {
Lucas Dupind508e472020-11-04 04:32:06 +0000415 mInProtectedContext = useProtectedContext;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400416 // given that we are sharing the same thread between two GrContexts we need to
417 // make sure that the thread state is reset when switching between the two.
418 if (getActiveGrContext()) {
419 getActiveGrContext()->resetContext();
420 }
Lucas Dupind508e472020-11-04 04:32:06 +0000421 }
Lucas Dupind508e472020-11-04 04:32:06 +0000422}
423
John Reck67b1e2b2020-08-26 13:17:24 -0700424base::unique_fd SkiaGLRenderEngine::flush() {
425 ATRACE_CALL();
426 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
427 return base::unique_fd();
428 }
429
430 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
431 if (sync == EGL_NO_SYNC_KHR) {
432 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
433 return base::unique_fd();
434 }
435
436 // native fence fd will not be populated until flush() is done.
437 glFlush();
438
439 // get the fence fd
440 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
441 eglDestroySyncKHR(mEGLDisplay, sync);
442 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
443 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
444 }
445
446 return fenceFd;
447}
448
Alec Mouri4ee7b492021-08-11 10:36:55 -0700449void SkiaGLRenderEngine::waitFence(base::borrowed_fd fenceFd) {
450 if (fenceFd.get() >= 0 && !waitGpuFence(fenceFd)) {
451 ATRACE_NAME("SkiaGLRenderEngine::waitFence");
452 sync_wait(fenceFd.get(), -1);
453 }
454}
455
456bool SkiaGLRenderEngine::waitGpuFence(base::borrowed_fd fenceFd) {
John Reck67b1e2b2020-08-26 13:17:24 -0700457 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
458 !gl::GLExtensions::getInstance().hasWaitSync()) {
459 return false;
460 }
461
Alec Mouri4ee7b492021-08-11 10:36:55 -0700462 // Duplicate the fence for passing to eglCreateSyncKHR.
463 base::unique_fd fenceDup(dup(fenceFd.get()));
464 if (fenceDup.get() < 0) {
465 ALOGE("failed to create duplicate fence fd: %d", fenceDup.get());
466 return false;
467 }
468
John Reck67b1e2b2020-08-26 13:17:24 -0700469 // release the fd and transfer the ownership to EGLSync
Alec Mouri4ee7b492021-08-11 10:36:55 -0700470 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceDup.release(), EGL_NONE};
John Reck67b1e2b2020-08-26 13:17:24 -0700471 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
472 if (sync == EGL_NO_SYNC_KHR) {
473 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
474 return false;
475 }
476
477 // XXX: The spec draft is inconsistent as to whether this should return an
478 // EGLint or void. Ignore the return value for now, as it's not strictly
479 // needed.
480 eglWaitSyncKHR(mEGLDisplay, sync, 0);
481 EGLint error = eglGetError();
482 eglDestroySyncKHR(mEGLDisplay, sync);
483 if (error != EGL_SUCCESS) {
484 ALOGE("failed to wait for EGL native fence sync: %#x", error);
485 return false;
486 }
487
488 return true;
489}
490
Alec Mouri678245d2020-09-30 16:58:23 -0700491static float toDegrees(uint32_t transform) {
492 switch (transform) {
493 case ui::Transform::ROT_90:
494 return 90.0;
495 case ui::Transform::ROT_180:
496 return 180.0;
497 case ui::Transform::ROT_270:
498 return 270.0;
499 default:
500 return 0.0;
501 }
502}
503
Alec Mourib34f0b72020-10-02 13:18:34 -0700504static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
505 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
506 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
507 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
508 matrix[3][3], 0);
509}
510
Alec Mouri029d1952020-10-12 10:37:08 -0700511static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
512 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
513 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
514
515 // Treat unsupported dataspaces as srgb
516 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
517 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
518 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
519 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
520 }
521
522 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
523 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
524 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
525 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
526 }
527
528 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
529 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
530 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
531 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
532
533 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
534 sourceTransfer != destTransfer;
535}
536
Alec Mouria90a5702021-04-16 16:36:21 +0000537void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
538 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800539 // Only run this if RE is running on its own thread. This way the access to GL
540 // operations is guaranteed to be happening on the same thread.
541 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
542 return;
543 }
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400544 // We currently don't attempt to map a buffer if the buffer contains protected content
Derek Sollenberger45007182021-06-10 14:47:21 -0400545 // because GPU resources for protected buffers is much more limited.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400546 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
Derek Sollenberger45007182021-06-10 14:47:21 -0400547 if (isProtectedBuffer) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400548 return;
549 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800550 ATRACE_CALL();
551
Derek Sollenberger45007182021-06-10 14:47:21 -0400552 // If we were to support caching protected buffers then we will need to switch the
553 // currently bound context if we are not already using the protected context (and subsequently
554 // switch back after the buffer is cached). However, for non-protected content we can bind
555 // the texture in either GL context because they are initialized with the same share_context
556 // which allows the texture state to be shared between them.
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400557 auto grContext = getActiveGrContext();
Derek Sollenbergerbc14f3c2021-05-21 14:29:16 -0400558 auto& cache = mTextureCache;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400559
560 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000561 mGraphicBufferExternalRefs[buffer->getId()]++;
562
563 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800564 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400565 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400566 buffer->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400567 isRenderable, mTextureCleanupMgr);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400568 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800569 }
570}
571
Alec Mouria90a5702021-04-16 16:36:21 +0000572void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800573 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700574 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000575 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
576 iter != mGraphicBufferExternalRefs.end()) {
577 if (iter->second == 0) {
578 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
579 "> from RenderEngine texture, but the "
580 "ref count was already zero!",
581 buffer->getId());
582 mGraphicBufferExternalRefs.erase(buffer->getId());
583 return;
584 }
585
586 iter->second--;
587
Alec Mouric2ffeb42021-06-17 17:42:27 -0700588 // Swap contexts if needed prior to deleting this buffer
589 // See Issue 1 of
590 // https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_protected_content.txt: even
591 // when a protected context and an unprotected context are part of the same share group,
592 // protected surfaces may not be accessed by an unprotected context, implying that protected
593 // surfaces may only be freed when a protected context is active.
594 const bool inProtected = mInProtectedContext;
595 useProtectedContext(buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
596
Alec Mouria90a5702021-04-16 16:36:21 +0000597 if (iter->second == 0) {
598 mTextureCache.erase(buffer->getId());
Alec Mouria90a5702021-04-16 16:36:21 +0000599 mGraphicBufferExternalRefs.erase(buffer->getId());
600 }
Alec Mouric2ffeb42021-06-17 17:42:27 -0700601
602 // Swap back to the previous context so that cached values of isProtected in SurfaceFlinger
603 // are up-to-date.
604 if (inProtected != mInProtectedContext) {
605 useProtectedContext(inProtected);
606 }
Alec Mouria90a5702021-04-16 16:36:21 +0000607 }
John Reck67b1e2b2020-08-26 13:17:24 -0700608}
609
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400610bool SkiaGLRenderEngine::canSkipPostRenderCleanup() const {
611 std::lock_guard<std::mutex> lock(mRenderingMutex);
612 return mTextureCleanupMgr.isEmpty();
613}
614
615void SkiaGLRenderEngine::cleanupPostRender() {
616 ATRACE_CALL();
617 std::lock_guard<std::mutex> lock(mRenderingMutex);
618 mTextureCleanupMgr.cleanup();
619}
620
621// Helper class intended to be used on the stack to ensure that texture cleanup
622// is deferred until after this class goes out of scope.
623class DeferTextureCleanup final {
624public:
625 DeferTextureCleanup(AutoBackendTexture::CleanupManager& mgr) : mMgr(mgr) {
626 mMgr.setDeferredStatus(true);
627 }
628 ~DeferTextureCleanup() { mMgr.setDeferredStatus(false); }
629
630private:
631 DISALLOW_COPY_AND_ASSIGN(DeferTextureCleanup);
632 AutoBackendTexture::CleanupManager& mMgr;
633};
634
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700635sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
636 const RuntimeEffectShaderParameters& parameters) {
Nader Jawad63644d32021-05-07 10:44:21 -0700637 // The given surface will be stretched by HWUI via matrix transformation
638 // which gets similar results for most surfaces
639 // Determine later on if we need to leverage the stertch shader within
640 // surface flinger
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700641 const auto& stretchEffect = parameters.layer.stretchEffect;
642 auto shader = parameters.shader;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700643 if (stretchEffect.hasEffect()) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700644 const auto targetBuffer = parameters.layer.source.buffer.buffer;
Nader Jawadc088bdc2021-05-10 13:24:46 -0700645 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700646 if (graphicBuffer && parameters.shader) {
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700647 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
648 }
John Reckcdb4ed72021-02-04 13:39:33 -0500649 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700650
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700651 if (parameters.requiresLinearEffect) {
652 const ui::Dataspace inputDataspace = mUseColorManagement ? parameters.layer.sourceDataspace
653 : ui::Dataspace::V0_SRGB_LINEAR;
654 const ui::Dataspace outputDataspace = mUseColorManagement
655 ? parameters.display.outputDataspace
656 : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500657
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700658 auto effect =
659 shaders::LinearEffect{.inputDataspace = inputDataspace,
660 .outputDataspace = outputDataspace,
661 .undoPremultipliedAlpha = parameters.undoPremultipliedAlpha};
Ana Krulec47814212021-01-06 19:00:10 -0800662
663 auto effectIter = mRuntimeEffects.find(effect);
664 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
665 if (effectIter == mRuntimeEffects.end()) {
666 runtimeEffect = buildRuntimeEffect(effect);
667 mRuntimeEffects.insert({effect, runtimeEffect});
668 } else {
669 runtimeEffect = effectIter->second;
670 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700671 mat4 colorTransform = parameters.layer.colorTransform;
672
673 colorTransform *=
674 mat4::scale(vec4(parameters.layerDimmingRatio, parameters.layerDimmingRatio,
675 parameters.layerDimmingRatio, 1.f));
Alec Mouri1a3c5452022-03-04 22:44:51 +0000676 const auto targetBuffer = parameters.layer.source.buffer.buffer;
677 const auto graphicBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
678 const auto hardwareBuffer = graphicBuffer ? graphicBuffer->toAHardwareBuffer() : nullptr;
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700679 return createLinearEffectShader(parameters.shader, effect, runtimeEffect, colorTransform,
680 parameters.display.maxLuminance,
Alec Mourib21d94e2022-01-13 17:44:10 -0800681 parameters.display.currentLuminanceNits,
Alec Mouri1a3c5452022-03-04 22:44:51 +0000682 parameters.layer.source.buffer.maxLuminanceNits,
Alec Mourifcedb9c2022-04-11 20:02:17 +0000683 hardwareBuffer, parameters.display.renderIntent);
Ana Krulec47814212021-01-06 19:00:10 -0800684 }
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700685 return parameters.shader;
Ana Krulec47814212021-01-06 19:00:10 -0800686}
687
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500688void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500689 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500690 // Record display settings when capture is running.
691 std::stringstream displaySettings;
692 PrintTo(display, &displaySettings);
693 // Store the DisplaySettings in additional information.
694 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
695 SkData::MakeWithCString(displaySettings.str().c_str()));
696 }
697
698 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
699 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
700 // displays might have different scaling when compared to the physical screen.
701
702 canvas->clipRect(getSkRect(display.physicalDisplay));
703 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
704
705 const auto clipWidth = display.clip.width();
706 const auto clipHeight = display.clip.height();
707 auto rotatedClipWidth = clipWidth;
708 auto rotatedClipHeight = clipHeight;
709 // Scale is contingent on the rotation result.
710 if (display.orientation & ui::Transform::ROT_90) {
711 std::swap(rotatedClipWidth, rotatedClipHeight);
712 }
713 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
714 static_cast<SkScalar>(rotatedClipWidth);
715 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
716 static_cast<SkScalar>(rotatedClipHeight);
717 canvas->scale(scaleX, scaleY);
718
719 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
720 // back so that the top left corner of the clip is at (0, 0).
721 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
722 canvas->rotate(toDegrees(display.orientation));
723 canvas->translate(-clipWidth / 2, -clipHeight / 2);
724 canvas->translate(-display.clip.left, -display.clip.top);
725}
726
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500727class AutoSaveRestore {
728public:
729 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
730 ~AutoSaveRestore() { restore(); }
731 void replace(SkCanvas* canvas) {
732 mCanvas = canvas;
733 mSaveCount = canvas->save();
734 }
735 void restore() {
736 if (mCanvas) {
737 mCanvas->restoreToCount(mSaveCount);
738 mCanvas = nullptr;
739 }
740 }
741
742private:
743 SkCanvas* mCanvas;
744 int mSaveCount;
745};
746
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400747static SkRRect getBlurRRect(const BlurRegion& region) {
748 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
749 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
750 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
751 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
752 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
753 SkRRect roundedRect;
754 roundedRect.setRectRadii(rect, radii);
755 return roundedRect;
756}
757
Alec Mouri30835f22022-03-18 00:58:26 +0000758// Arbitrary default margin which should be close enough to zero.
759constexpr float kDefaultMargin = 0.0001f;
760static bool equalsWithinMargin(float expected, float value, float margin = kDefaultMargin) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700761 LOG_ALWAYS_FATAL_IF(margin < 0.f, "Margin is negative!");
762 return std::abs(expected - value) < margin;
763}
764
Sally Qi4cabdd02021-08-05 16:45:57 -0700765void SkiaGLRenderEngine::drawLayersInternal(
766 const std::shared_ptr<std::promise<RenderEngineResult>>&& resultPromise,
Sally Qi59a9f502021-10-12 18:53:23 +0000767 const DisplaySettings& display, const std::vector<LayerSettings>& layers,
Sally Qi4cabdd02021-08-05 16:45:57 -0700768 const std::shared_ptr<ExternalTexture>& buffer, const bool /*useFramebufferCache*/,
769 base::unique_fd&& bufferFence) {
John Reck67b1e2b2020-08-26 13:17:24 -0700770 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800771
John Reck67b1e2b2020-08-26 13:17:24 -0700772 std::lock_guard<std::mutex> lock(mRenderingMutex);
773 if (layers.empty()) {
774 ALOGV("Drawing empty layer stack");
Sally Qi4cabdd02021-08-05 16:45:57 -0700775 resultPromise->set_value({NO_ERROR, base::unique_fd()});
776 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700777 }
778
John Reck67b1e2b2020-08-26 13:17:24 -0700779 if (buffer == nullptr) {
780 ALOGE("No output buffer provided. Aborting GPU composition.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700781 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
782 return;
John Reck67b1e2b2020-08-26 13:17:24 -0700783 }
784
Alec Mouria90a5702021-04-16 16:36:21 +0000785 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800786
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400787 auto grContext = getActiveGrContext();
Derek Sollenberger45007182021-06-10 14:47:21 -0400788 auto& cache = mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700789
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400790 // any AutoBackendTexture deletions will now be deferred until cleanupPostRender is called
791 DeferTextureCleanup dtc(mTextureCleanupMgr);
792
Alec Mouria90a5702021-04-16 16:36:21 +0000793 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
794 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
795 surfaceTextureRef = it->second;
796 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400797 surfaceTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400798 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
799 buffer->getBuffer()
800 ->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -0400801 true, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -0700802 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800803
Alec Mouri4ee7b492021-08-11 10:36:55 -0700804 // wait on the buffer to be ready to use prior to using it
805 waitFence(bufferFence);
806
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500807 const ui::Dataspace dstDataspace =
Alec Mourid2bcbae2021-06-28 17:02:17 -0700808 mUseColorManagement ? display.outputDataspace : ui::Dataspace::V0_SRGB_LINEAR;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400809 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700810
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500811 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
812 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800813 ALOGE("Cannot acquire canvas from Skia.");
Sally Qi4cabdd02021-08-05 16:45:57 -0700814 resultPromise->set_value({BAD_VALUE, base::unique_fd()});
815 return;
Ana Krulec6eab17a2020-12-09 15:52:36 -0800816 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500817
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400818 // setup color filter if necessary
819 sk_sp<SkColorFilter> displayColorTransform;
Leon Scroggins III745dcaa2022-01-26 11:55:58 -0500820 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400821 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
822 }
823 const bool ctModifiesAlpha =
824 displayColorTransform && !displayColorTransform->isAlphaUnchanged();
825
Alec Mouricdf6cbc2021-11-01 17:21:15 -0700826 // Find the max layer white point to determine the max luminance of the scene...
827 const float maxLayerWhitePoint = std::transform_reduce(
828 layers.cbegin(), layers.cend(), 0.f,
829 [](float left, float right) { return std::max(left, right); },
830 [&](const auto& l) { return l.whitePointNits; });
831
832 // ...and compute the dimming ratio if dimming is requested
833 const float displayDimmingRatio = display.targetLuminanceNits > 0.f &&
834 maxLayerWhitePoint > 0.f && display.targetLuminanceNits > maxLayerWhitePoint
835 ? maxLayerWhitePoint / display.targetLuminanceNits
836 : 1.f;
837
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500838 // Find if any layers have requested blur, we'll use that info to decide when to render to an
839 // offscreen buffer and when to render to the native buffer.
840 sk_sp<SkSurface> activeSurface(dstSurface);
841 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500842 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500843 const LayerSettings* blurCompositionLayer = nullptr;
844 if (mBlurFilter) {
845 bool requiresCompositionLayer = false;
846 for (const auto& layer : layers) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400847 // if the layer doesn't have blur or it is not visible then continue
848 if (!layerHasBlur(layer, ctModifiesAlpha)) {
849 continue;
850 }
Sally Qi59a9f502021-10-12 18:53:23 +0000851 if (layer.backgroundBlurRadius > 0 &&
Robin Lee26dacab2021-08-09 14:31:01 +0200852 layer.backgroundBlurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500853 requiresCompositionLayer = true;
854 }
Sally Qi59a9f502021-10-12 18:53:23 +0000855 for (auto region : layer.blurRegions) {
Robin Lee26dacab2021-08-09 14:31:01 +0200856 if (region.blurRadius < mBlurFilter->getMaxCrossFadeRadius()) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500857 requiresCompositionLayer = true;
858 }
859 }
860 if (requiresCompositionLayer) {
861 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500862 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Sally Qi59a9f502021-10-12 18:53:23 +0000863 blurCompositionLayer = &layer;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500864 break;
865 }
866 }
867 }
868
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500869 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700870 // Clear the entire canvas with a transparent black to prevent ghost images.
871 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500872 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800873
John Reck67b1e2b2020-08-26 13:17:24 -0700874 for (const auto& layer : layers) {
Sally Qi59a9f502021-10-12 18:53:23 +0000875 ATRACE_FORMAT("DrawLayer: %s", layer.name.c_str());
Galia Peychevaf7889b32020-11-25 22:22:40 +0100876
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400877 if (kPrintLayerSettings) {
878 std::stringstream ls;
Sally Qi59a9f502021-10-12 18:53:23 +0000879 PrintTo(layer, &ls);
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400880 auto debugs = ls.str();
881 int pos = 0;
882 while (pos < debugs.size()) {
883 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
884 pos += 1000;
885 }
886 }
887
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500888 sk_sp<SkImage> blurInput;
Sally Qi59a9f502021-10-12 18:53:23 +0000889 if (blurCompositionLayer == &layer) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500890 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
891 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
892
893 // save a snapshot of the activeSurface to use as input to the blur shaders
894 blurInput = activeSurface->makeImageSnapshot();
895
Leon Scroggins III55bf4742022-03-17 14:11:17 -0400896 // blit the offscreen framebuffer into the destination AHB, but only
897 // if there are blur regions. backgroundBlurRadius blurs the entire
898 // image below, so it can skip this step.
899 if (layer.blurRegions.size()) {
900 SkPaint paint;
901 paint.setBlendMode(SkBlendMode::kSrc);
902 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
903 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
904 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
905 String8::format("SurfaceID|%" PRId64, id).c_str(),
906 nullptr);
907 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
908 } else {
909 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
910 }
Derek Sollenberger76664d62021-02-04 11:13:09 -0500911 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500912
913 // assign dstCanvas to canvas and ensure that the canvas state is up to date
914 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500915 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500916 initCanvas(canvas, display);
917
918 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
919 dstSurface->getCanvas()->getSaveCount());
920 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
921 dstSurface->getCanvas()->getTotalMatrix());
922
923 // assign dstSurface to activeSurface
924 activeSurface = dstSurface;
925 }
926
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500927 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500928 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800929 // Record the name of the layer if the capture is running.
930 std::stringstream layerSettings;
Sally Qi59a9f502021-10-12 18:53:23 +0000931 PrintTo(layer, &layerSettings);
Ana Krulec6eab17a2020-12-09 15:52:36 -0800932 // Store the LayerSettings in additional information.
Sally Qi59a9f502021-10-12 18:53:23 +0000933 canvas->drawAnnotation(SkRect::MakeEmpty(), layer.name.c_str(),
Ana Krulec6eab17a2020-12-09 15:52:36 -0800934 SkData::MakeWithCString(layerSettings.str().c_str()));
935 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100936 // Layers have a local transform that should be applied to them
Sally Qi59a9f502021-10-12 18:53:23 +0000937 canvas->concat(getSkM44(layer.geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100938
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400939 const auto [bounds, roundRectClip] =
Sally Qi59a9f502021-10-12 18:53:23 +0000940 getBoundsAndClip(layer.geometry.boundaries, layer.geometry.roundedCornersCrop,
941 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -0400942 if (mBlurFilter && layerHasBlur(layer, ctModifiesAlpha)) {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500943 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
944
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500945 // if multiple layers have blur, then we need to take a snapshot now because
946 // only the lowest layer will have blurImage populated earlier
947 if (!blurInput) {
948 blurInput = activeSurface->makeImageSnapshot();
949 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500950 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400951 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
952
953 // if the clip needs to be applied then apply it now and make sure
954 // it is restored before we attempt to draw any shadows.
955 SkAutoCanvasRestore acr(canvas, true);
956 if (!roundRectClip.isEmpty()) {
957 canvas->clipRRect(roundRectClip, true);
958 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500959
Galia Peychevae425ac82021-03-15 17:12:03 +0100960 // TODO(b/182216890): Filter out empty layers earlier
961 if (blurRect.width() > 0 && blurRect.height() > 0) {
Sally Qi59a9f502021-10-12 18:53:23 +0000962 if (layer.backgroundBlurRadius > 0) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100963 ATRACE_NAME("BackgroundBlur");
Sally Qi59a9f502021-10-12 18:53:23 +0000964 auto blurredImage = mBlurFilter->generate(grContext, layer.backgroundBlurRadius,
965 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100966
Sally Qi59a9f502021-10-12 18:53:23 +0000967 cachedBlurs[layer.backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500968
Sally Qi59a9f502021-10-12 18:53:23 +0000969 mBlurFilter->drawBlurRegion(canvas, bounds, layer.backgroundBlurRadius, 1.0f,
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400970 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700971 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400972
Sally Qi59a9f502021-10-12 18:53:23 +0000973 canvas->concat(getSkM44(layer.blurRegionTransform).asM33());
974 for (auto region : layer.blurRegions) {
Galia Peychevae425ac82021-03-15 17:12:03 +0100975 if (cachedBlurs[region.blurRadius] == nullptr) {
976 ATRACE_NAME("BlurRegion");
977 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400978 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100979 blurRect);
980 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500981
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400982 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
983 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100984 cachedBlurs[region.blurRadius], blurInput);
985 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700986 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700987 }
988
Sally Qi59a9f502021-10-12 18:53:23 +0000989 if (layer.shadow.length > 0) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400990 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
Sally Qi59a9f502021-10-12 18:53:23 +0000991 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with a shadow");
Leon Scroggins III63e86952021-05-12 10:45:08 -0400992
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400993 SkRRect shadowBounds, shadowClip;
Sally Qi59a9f502021-10-12 18:53:23 +0000994 if (layer.geometry.boundaries == layer.shadow.boundaries) {
Derek Sollenbergerc31985e2021-05-18 16:38:17 -0400995 shadowBounds = bounds;
996 shadowClip = roundRectClip;
997 } else {
998 std::tie(shadowBounds, shadowClip) =
Sally Qi59a9f502021-10-12 18:53:23 +0000999 getBoundsAndClip(layer.shadow.boundaries, layer.geometry.roundedCornersCrop,
1000 layer.geometry.roundedCornersRadius);
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001001 }
1002
Leon Scroggins III63e86952021-05-12 10:45:08 -04001003 // Technically, if bounds is a rect and roundRectClip is not empty,
1004 // it means that the bounds and roundedCornersCrop were different
1005 // enough that we should intersect them to find the proper shadow.
1006 // In practice, this often happens when the two rectangles appear to
1007 // not match due to rounding errors. Draw the rounded version, which
1008 // looks more like the intent.
1009 const auto& rrect =
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001010 shadowBounds.isRect() && !shadowClip.isEmpty() ? shadowClip : shadowBounds;
Sally Qi59a9f502021-10-12 18:53:23 +00001011 drawShadow(canvas, rrect, layer.shadow);
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001012 }
1013
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001014 const float layerDimmingRatio = layer.whitePointNits <= 0.f
1015 ? displayDimmingRatio
1016 : (layer.whitePointNits / maxLayerWhitePoint) * displayDimmingRatio;
1017
Alec Mouri30835f22022-03-18 00:58:26 +00001018 const bool dimInLinearSpace = display.dimmingStage !=
1019 aidl::android::hardware::graphics::composer3::DimmingStage::GAMMA_OETF;
1020
Sally Qi59a9f502021-10-12 18:53:23 +00001021 const bool requiresLinearEffect = layer.colorTransform != mat4() ||
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001022 (mUseColorManagement &&
Sally Qi59a9f502021-10-12 18:53:23 +00001023 needsToneMapping(layer.sourceDataspace, display.outputDataspace)) ||
Alec Mouri30835f22022-03-18 00:58:26 +00001024 (dimInLinearSpace && !equalsWithinMargin(1.f, layerDimmingRatio));
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001025
1026 // quick abort from drawing the remaining portion of the layer
Sally Qi59a9f502021-10-12 18:53:23 +00001027 if (layer.skipContentDraw ||
1028 (layer.alpha == 0 && !requiresLinearEffect && !layer.disableBlending &&
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001029 (!displayColorTransform || displayColorTransform->isAlphaUnchanged()))) {
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001030 continue;
1031 }
1032
1033 // If we need to map to linear space or color management is disabled, then mark the source
1034 // image with the same colorspace as the destination surface so that Skia's color
1035 // management is a no-op.
1036 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
1037 ? dstDataspace
Sally Qi59a9f502021-10-12 18:53:23 +00001038 : layer.sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -08001039
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001040 SkPaint paint;
Sally Qi59a9f502021-10-12 18:53:23 +00001041 if (layer.source.buffer.buffer) {
John Reck67b1e2b2020-08-26 13:17:24 -07001042 ATRACE_NAME("DrawImage");
Sally Qi59a9f502021-10-12 18:53:23 +00001043 validateInputBufferUsage(layer.source.buffer.buffer->getBuffer());
1044 const auto& item = layer.source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001045 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +00001046
1047 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
1048 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -08001049 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -07001050 } else {
Alec Mouria90a5702021-04-16 16:36:21 +00001051 // If we didn't find the image in the cache, then create a local ref but don't cache
1052 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
1053 // we didn't find anything in the cache then we intentionally did not cache this
1054 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001055 imageTextureRef = std::make_shared<
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001056 AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -04001057 item.buffer->getBuffer()->toAHardwareBuffer(),
Derek Sollenbergerd3f60652021-06-11 15:34:36 -04001058 false, mTextureCleanupMgr);
John Reck67b1e2b2020-08-26 13:17:24 -07001059 }
Alec Mouri1a4d0642020-11-13 17:42:01 -08001060
Alec Mouri4ee7b492021-08-11 10:36:55 -07001061 // if the layer's buffer has a fence, then we must must respect the fence prior to using
1062 // the buffer.
Sally Qi59a9f502021-10-12 18:53:23 +00001063 if (layer.source.buffer.fence != nullptr) {
1064 waitFence(layer.source.buffer.fence->get());
Alec Mouri4ee7b492021-08-11 10:36:55 -07001065 }
1066
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001067 // isOpaque means we need to ignore the alpha in the image,
1068 // replacing it with the alpha specified by the LayerSettings. See
1069 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
1070 // The proper way to do this is to use an SkColorType that ignores
1071 // alpha, like kRGB_888x_SkColorType, and that is used if the
1072 // incoming image is kRGBA_8888_SkColorType. However, the incoming
1073 // image may be kRGBA_F16_SkColorType, for which there is no RGBX
1074 // SkColorType, or kRGBA_1010102_SkColorType, for which we have
1075 // kRGB_101010x_SkColorType, but it is not yet supported as a source
1076 // on the GPU. (Adding both is tracked in skbug.com/12048.) In the
1077 // meantime, we'll use a workaround that works unless we need to do
1078 // any color conversion. The workaround requires that we pretend the
1079 // image is already premultiplied, so that we do not premultiply it
1080 // before applying SkBlendMode::kPlus.
1081 const bool useIsOpaqueWorkaround = item.isOpaque &&
1082 (imageTextureRef->colorType() == kRGBA_1010102_SkColorType ||
1083 imageTextureRef->colorType() == kRGBA_F16_SkColorType);
1084 const auto alphaType = useIsOpaqueWorkaround ? kPremul_SkAlphaType
1085 : item.isOpaque ? kOpaque_SkAlphaType
1086 : item.usePremultipliedAlpha ? kPremul_SkAlphaType
1087 : kUnpremul_SkAlphaType;
1088 sk_sp<SkImage> image = imageTextureRef->makeImage(layerDataspace, alphaType, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -07001089
1090 auto texMatrix = getSkM44(item.textureTransform).asM33();
1091 // textureTansform was intended to be passed directly into a shader, so when
1092 // building the total matrix with the textureTransform we need to first
1093 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001094 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001095 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -07001096
Huihong Luo3a3cf3c2020-12-07 17:05:41 -08001097 SkMatrix matrix;
1098 if (!texMatrix.invert(&matrix)) {
1099 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -07001100 }
Ana Krulecf9a15d92020-12-11 08:35:00 -08001101 // The shader does not respect the translation, so we add it to the texture
1102 // transform for the SkImage. This will make sure that the correct layer contents
1103 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001104 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -07001105
Ana Krulecb7b28b22020-11-23 14:48:58 -08001106 sk_sp<SkShader> shader;
1107
Sally Qi59a9f502021-10-12 18:53:23 +00001108 if (layer.source.buffer.useTextureFiltering) {
Ana Krulecb7b28b22020-11-23 14:48:58 -08001109 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1110 SkSamplingOptions(
1111 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1112 &matrix);
1113 } else {
Mike Reed711e1f02020-12-11 13:06:19 -05001114 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -08001115 }
Alec Mouri029d1952020-10-12 10:37:08 -07001116
Leon Scroggins IIIc4e0cbd2021-05-25 10:25:20 -04001117 if (useIsOpaqueWorkaround) {
Alec Mouric0aae732021-01-12 13:32:18 -08001118 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1119 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001120 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001121 }
1122
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001123 paint.setShader(createRuntimeEffectShader(
1124 RuntimeEffectShaderParameters{.shader = shader,
1125 .layer = layer,
1126 .display = display,
1127 .undoPremultipliedAlpha = !item.isOpaque &&
1128 item.usePremultipliedAlpha,
1129 .requiresLinearEffect = requiresLinearEffect,
Alec Mouri30835f22022-03-18 00:58:26 +00001130 .layerDimmingRatio = dimInLinearSpace
1131 ? layerDimmingRatio
1132 : 1.f}));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001133
Alec Mouri88acab92022-03-24 23:41:01 +00001134 // Turn on dithering when dimming beyond this (arbitrary) threshold...
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001135 static constexpr float kDimmingThreshold = 0.2f;
Alec Mouri88acab92022-03-24 23:41:01 +00001136 // ...or we're rendering an HDR layer down to an 8-bit target
1137 // Most HDR standards require at least 10-bits of color depth for source content, so we
1138 // can just extract the transfer function rather than dig into precise gralloc layout.
1139 // Furthermore, we can assume that the only 8-bit target we support is RGBA8888.
1140 const bool requiresDownsample = isHdrDataspace(layer.sourceDataspace) &&
1141 buffer->getPixelFormat() == PIXEL_FORMAT_RGBA_8888;
1142 if (layerDimmingRatio <= kDimmingThreshold || requiresDownsample) {
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001143 paint.setDither(true);
1144 }
Sally Qi59a9f502021-10-12 18:53:23 +00001145 paint.setAlphaf(layer.alpha);
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001146
1147 if (imageTextureRef->colorType() == kAlpha_8_SkColorType) {
1148 LOG_ALWAYS_FATAL_IF(layer.disableBlending, "Cannot disableBlending with A8");
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001149
1150 // SysUI creates the alpha layer as a coverage layer, which is
1151 // appropriate for the DPU. Use a color matrix to convert it to
1152 // a mask.
1153 // TODO (b/219525258): Handle input as a mask.
1154 //
1155 // The color matrix will convert A8 pixels with no alpha to
1156 // black, as described by this vector. If the display handles
1157 // the color transform, we need to invert it to find the color
1158 // that will result in black after the DPU applies the transform.
1159 SkV4 black{0.0f, 0.0f, 0.0f, 1.0f}; // r, g, b, a
1160 if (display.colorTransform != mat4() && display.deviceHandlesColorTransform) {
1161 SkM44 colorSpaceMatrix = getSkM44(display.colorTransform);
1162 if (colorSpaceMatrix.invert(&colorSpaceMatrix)) {
1163 black = colorSpaceMatrix * black;
1164 } else {
1165 // We'll just have to use 0,0,0 as black, which should
1166 // be close to correct.
1167 ALOGI("Could not invert colorTransform!");
1168 }
1169 }
1170 SkColorMatrix colorMatrix(0, 0, 0, 0, black[0],
1171 0, 0, 0, 0, black[1],
1172 0, 0, 0, 0, black[2],
1173 0, 0, 0, -1, 1);
1174 if (display.colorTransform != mat4() && !display.deviceHandlesColorTransform) {
1175 // On the other hand, if the device doesn't handle it, we
1176 // have to apply it ourselves.
1177 colorMatrix.postConcat(toSkColorMatrix(display.colorTransform));
1178 }
1179 paint.setColorFilter(SkColorFilters::Matrix(colorMatrix));
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001180 }
John Reck67b1e2b2020-08-26 13:17:24 -07001181 } else {
1182 ATRACE_NAME("DrawColor");
Sally Qi59a9f502021-10-12 18:53:23 +00001183 const auto color = layer.source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001184 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1185 .fG = color.g,
1186 .fB = color.b,
Sally Qi59a9f502021-10-12 18:53:23 +00001187 .fA = layer.alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001188 toSkColorSpace(layerDataspace));
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001189 paint.setShader(createRuntimeEffectShader(
1190 RuntimeEffectShaderParameters{.shader = shader,
1191 .layer = layer,
1192 .display = display,
1193 .undoPremultipliedAlpha = false,
1194 .requiresLinearEffect = requiresLinearEffect,
1195 .layerDimmingRatio = layerDimmingRatio}));
John Reck67b1e2b2020-08-26 13:17:24 -07001196 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001197
Sally Qi59a9f502021-10-12 18:53:23 +00001198 if (layer.disableBlending) {
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001199 paint.setBlendMode(SkBlendMode::kSrc);
1200 }
1201
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001202 // An A8 buffer will already have the proper color filter attached to
1203 // its paint, including the displayColorTransform as needed.
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001204 if (!paint.getColorFilter()) {
Alec Mouri30835f22022-03-18 00:58:26 +00001205 if (!dimInLinearSpace && !equalsWithinMargin(1.0, layerDimmingRatio)) {
1206 // If we don't dim in linear space, then when we gamma correct the dimming ratio we
1207 // can assume a gamma 2.2 transfer function.
1208 static constexpr float kInverseGamma22 = 1.f / 2.2f;
1209 const auto gammaCorrectedDimmingRatio =
1210 std::pow(layerDimmingRatio, kInverseGamma22);
Alec Mouri9bcd1d12022-04-21 22:16:56 +00001211 auto dimmingMatrix =
Alec Mouri30835f22022-03-18 00:58:26 +00001212 mat4::scale(vec4(gammaCorrectedDimmingRatio, gammaCorrectedDimmingRatio,
1213 gammaCorrectedDimmingRatio, 1.f));
Alec Mouri9bcd1d12022-04-21 22:16:56 +00001214
1215 const auto colorFilter =
1216 SkColorFilters::Matrix(toSkColorMatrix(std::move(dimmingMatrix)));
1217 paint.setColorFilter(displayColorTransform
1218 ? displayColorTransform->makeComposed(colorFilter)
1219 : colorFilter);
Alec Mouri30835f22022-03-18 00:58:26 +00001220 } else {
1221 paint.setColorFilter(displayColorTransform);
1222 }
Leon Scroggins III2c1d9ef2022-01-21 13:46:56 -05001223 }
Alec Mourib34f0b72020-10-02 13:18:34 -07001224
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001225 if (!roundRectClip.isEmpty()) {
1226 canvas->clipRRect(roundRectClip, true);
1227 }
1228
1229 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001230 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001231 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001232 } else {
Nader Jawad63644d32021-05-07 10:44:21 -07001233 canvas->drawRect(bounds.rect(), paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -07001234 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001235 if (kFlushAfterEveryLayer) {
1236 ATRACE_NAME("flush surface");
1237 activeSurface->flush();
1238 }
John Reck67b1e2b2020-08-26 13:17:24 -07001239 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001240 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001241 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001242 {
1243 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001244 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1245 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001246 }
1247
Sally Qi4cabdd02021-08-05 16:45:57 -07001248 base::unique_fd drawFence = flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001249
1250 // If flush failed or we don't support native fences, we need to force the
1251 // gl command stream to be executed.
Sally Qi4cabdd02021-08-05 16:45:57 -07001252 bool requireSync = drawFence.get() < 0;
John Reck67b1e2b2020-08-26 13:17:24 -07001253 if (requireSync) {
1254 ATRACE_BEGIN("Submit(sync=true)");
1255 } else {
1256 ATRACE_BEGIN("Submit(sync=false)");
1257 }
Lucas Dupind508e472020-11-04 04:32:06 +00001258 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001259 ATRACE_END();
1260 if (!success) {
1261 ALOGE("Failed to flush RenderEngine commands");
1262 // Chances are, something illegal happened (either the caller passed
1263 // us bad parameters, or we messed up our shader generation).
Sally Qi4cabdd02021-08-05 16:45:57 -07001264 resultPromise->set_value({INVALID_OPERATION, std::move(drawFence)});
1265 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001266 }
1267
1268 // checkErrors();
Sally Qi4cabdd02021-08-05 16:45:57 -07001269 resultPromise->set_value({NO_ERROR, std::move(drawFence)});
1270 return;
John Reck67b1e2b2020-08-26 13:17:24 -07001271}
1272
Lucas Dupin3f11e922020-09-22 17:31:04 -07001273inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1274 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1275}
1276
1277inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1278 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1279}
1280
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001281/**
1282 * Verifies that common, simple bounds + clip combinations can be converted into
1283 * a single RRect draw call returning true if possible. If true the radii parameter
1284 * will be filled with the correct radii values that combined with bounds param will
1285 * produce the insected roundRect. If false, the returned state of the radii param is undefined.
1286 */
1287static bool intersectionIsRoundRect(const SkRect& bounds, const SkRect& crop,
1288 const SkRect& insetCrop, float cornerRadius,
1289 SkVector radii[4]) {
1290 const bool leftEqual = bounds.fLeft == crop.fLeft;
1291 const bool topEqual = bounds.fTop == crop.fTop;
1292 const bool rightEqual = bounds.fRight == crop.fRight;
1293 const bool bottomEqual = bounds.fBottom == crop.fBottom;
1294
1295 // In the event that the corners of the bounds only partially align with the crop we
1296 // need to ensure that the resulting shape can still be represented as a round rect.
1297 // In particular the round rect implementation will scale the value of all corner radii
1298 // if the sum of the radius along any edge is greater than the length of that edge.
1299 // See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
1300 const bool requiredWidth = bounds.width() > (cornerRadius * 2);
1301 const bool requiredHeight = bounds.height() > (cornerRadius * 2);
1302 if (!requiredWidth || !requiredHeight) {
1303 return false;
1304 }
1305
1306 // Check each cropped corner to ensure that it exactly matches the crop or its corner is
1307 // contained within the cropped shape and does not need rounded.
1308 // compute the UpperLeft corner radius
1309 if (leftEqual && topEqual) {
1310 radii[0].set(cornerRadius, cornerRadius);
1311 } else if ((leftEqual && bounds.fTop >= insetCrop.fTop) ||
1312 (topEqual && bounds.fLeft >= insetCrop.fLeft)) {
1313 radii[0].set(0, 0);
1314 } else {
1315 return false;
1316 }
1317 // compute the UpperRight corner radius
1318 if (rightEqual && topEqual) {
1319 radii[1].set(cornerRadius, cornerRadius);
1320 } else if ((rightEqual && bounds.fTop >= insetCrop.fTop) ||
1321 (topEqual && bounds.fRight <= insetCrop.fRight)) {
1322 radii[1].set(0, 0);
1323 } else {
1324 return false;
1325 }
1326 // compute the BottomRight corner radius
1327 if (rightEqual && bottomEqual) {
1328 radii[2].set(cornerRadius, cornerRadius);
1329 } else if ((rightEqual && bounds.fBottom <= insetCrop.fBottom) ||
1330 (bottomEqual && bounds.fRight <= insetCrop.fRight)) {
1331 radii[2].set(0, 0);
1332 } else {
1333 return false;
1334 }
1335 // compute the BottomLeft corner radius
1336 if (leftEqual && bottomEqual) {
1337 radii[3].set(cornerRadius, cornerRadius);
1338 } else if ((leftEqual && bounds.fBottom <= insetCrop.fBottom) ||
1339 (bottomEqual && bounds.fLeft >= insetCrop.fLeft)) {
1340 radii[3].set(0, 0);
1341 } else {
1342 return false;
1343 }
1344
1345 return true;
1346}
1347
Derek Sollenbergerc31985e2021-05-18 16:38:17 -04001348inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(const FloatRect& boundsRect,
1349 const FloatRect& cropRect,
1350 const float cornerRadius) {
1351 const SkRect bounds = getSkRect(boundsRect);
1352 const SkRect crop = getSkRect(cropRect);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001353
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001354 SkRRect clip;
1355 if (cornerRadius > 0) {
Derek Sollenberger4f9959f2021-05-12 16:47:37 -04001356 // it the crop and the bounds are equivalent or there is no crop then we don't need a clip
1357 if (bounds == crop || crop.isEmpty()) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001358 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1359 }
1360
1361 // This makes an effort to speed up common, simple bounds + clip combinations by
1362 // converting them to a single RRect draw. It is possible there are other cases
1363 // that can be converted.
1364 if (crop.contains(bounds)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001365 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001366 if (insetCrop.contains(bounds)) {
1367 return {SkRRect::MakeRect(bounds), clip}; // clip is empty - no rounding required
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001368 }
1369
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001370 SkVector radii[4];
1371 if (intersectionIsRoundRect(bounds, crop, insetCrop, cornerRadius, radii)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001372 SkRRect intersectionBounds;
1373 intersectionBounds.setRectRadii(bounds, radii);
1374 return {intersectionBounds, clip};
1375 }
1376 }
1377
Derek Sollenberger547d0a62021-07-27 14:09:17 -04001378 // we didn't hit any of our fast paths so set the clip to the cropRect
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001379 clip.setRectXY(crop, cornerRadius, cornerRadius);
1380 }
1381
1382 // if we hit this point then we either don't have rounded corners or we are going to rely
1383 // on the clip to round the corners for us
1384 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001385}
1386
Sally Qi59a9f502021-10-12 18:53:23 +00001387inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings& layer,
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001388 bool colorTransformModifiesAlpha) {
Sally Qi59a9f502021-10-12 18:53:23 +00001389 if (layer.backgroundBlurRadius > 0 || layer.blurRegions.size()) {
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001390 // return false if the content is opaque and would therefore occlude the blur
Sally Qi59a9f502021-10-12 18:53:23 +00001391 const bool opaqueContent = !layer.source.buffer.buffer || layer.source.buffer.isOpaque;
1392 const bool opaqueAlpha = layer.alpha == 1.0f && !colorTransformModifiesAlpha;
1393 return layer.skipContentDraw || !(opaqueContent && opaqueAlpha);
Derek Sollenbergerc20e0802021-05-19 16:20:59 -04001394 }
1395 return false;
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001396}
1397
Lucas Dupin3f11e922020-09-22 17:31:04 -07001398inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1399 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1400}
1401
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001402inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1403 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1404 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1405 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1406 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1407}
1408
Lucas Dupin3f11e922020-09-22 17:31:04 -07001409inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1410 return SkPoint3::Make(vector.x, vector.y, vector.z);
1411}
1412
John Reck67b1e2b2020-08-26 13:17:24 -07001413size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1414 return mGrContext->maxTextureSize();
1415}
1416
1417size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1418 return mGrContext->maxRenderTargetSize();
1419}
1420
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001421void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRRect& casterRRect,
Lucas Dupin3f11e922020-09-22 17:31:04 -07001422 const ShadowSettings& settings) {
1423 ATRACE_CALL();
1424 const float casterZ = settings.length / 2.0f;
Lucas Dupin3f11e922020-09-22 17:31:04 -07001425 const auto flags =
1426 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1427
Derek Sollenbergerb0e764c2021-05-04 14:31:37 -04001428 SkShadowUtils::DrawShadow(canvas, SkPath::RRect(casterRRect), SkPoint3::Make(0, 0, casterZ),
Lucas Dupin3f11e922020-09-22 17:31:04 -07001429 getSkPoint3(settings.lightPos), settings.lightRadius,
1430 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1431 flags);
1432}
1433
John Reck67b1e2b2020-08-26 13:17:24 -07001434EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001435 EGLContext shareContext,
1436 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001437 Protection protection) {
1438 EGLint renderableType = 0;
1439 if (config == EGL_NO_CONFIG_KHR) {
1440 renderableType = EGL_OPENGL_ES3_BIT;
1441 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1442 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1443 }
1444 EGLint contextClientVersion = 0;
1445 if (renderableType & EGL_OPENGL_ES3_BIT) {
1446 contextClientVersion = 3;
1447 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1448 contextClientVersion = 2;
1449 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1450 contextClientVersion = 1;
1451 } else {
1452 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1453 }
1454
1455 std::vector<EGLint> contextAttributes;
1456 contextAttributes.reserve(7);
1457 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1458 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001459 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001460 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001461 switch (*contextPriority) {
1462 case ContextPriority::REALTIME:
1463 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1464 break;
1465 case ContextPriority::MEDIUM:
1466 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1467 break;
1468 case ContextPriority::LOW:
1469 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1470 break;
1471 case ContextPriority::HIGH:
1472 default:
1473 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1474 break;
1475 }
John Reck67b1e2b2020-08-26 13:17:24 -07001476 }
1477 if (protection == Protection::PROTECTED) {
1478 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1479 contextAttributes.push_back(EGL_TRUE);
1480 }
1481 contextAttributes.push_back(EGL_NONE);
1482
1483 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1484
1485 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1486 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1487 // EGL_NO_CONTEXT so that we can abort.
1488 if (config != EGL_NO_CONFIG_KHR) {
1489 return context;
1490 }
1491 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1492 // should try to fall back to GLES 2.
1493 contextAttributes[1] = 2;
1494 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1495 }
1496
1497 return context;
1498}
1499
Alec Mourid6f09462020-12-07 11:18:17 -08001500std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1501 const RenderEngineCreationArgs& args) {
1502 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1503 return std::nullopt;
1504 }
1505
1506 switch (args.contextPriority) {
1507 case RenderEngine::ContextPriority::REALTIME:
1508 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1509 return RenderEngine::ContextPriority::REALTIME;
1510 } else {
1511 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1512 return RenderEngine::ContextPriority::HIGH;
1513 }
1514 case RenderEngine::ContextPriority::HIGH:
1515 case RenderEngine::ContextPriority::MEDIUM:
1516 case RenderEngine::ContextPriority::LOW:
1517 return args.contextPriority;
1518 default:
1519 return std::nullopt;
1520 }
1521}
1522
John Reck67b1e2b2020-08-26 13:17:24 -07001523EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1524 EGLConfig config, int hwcFormat,
1525 Protection protection) {
1526 EGLConfig placeholderConfig = config;
1527 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1528 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1529 }
1530 std::vector<EGLint> attributes;
1531 attributes.reserve(7);
1532 attributes.push_back(EGL_WIDTH);
1533 attributes.push_back(1);
1534 attributes.push_back(EGL_HEIGHT);
1535 attributes.push_back(1);
1536 if (protection == Protection::PROTECTED) {
1537 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1538 attributes.push_back(EGL_TRUE);
1539 }
1540 attributes.push_back(EGL_NONE);
1541
1542 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1543}
1544
Alec Mourid6f09462020-12-07 11:18:17 -08001545int SkiaGLRenderEngine::getContextPriority() {
1546 int value;
1547 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1548 return value;
1549}
1550
Ady Abrahamed3290f2021-05-17 15:12:14 -07001551void SkiaGLRenderEngine::onActiveDisplaySizeChanged(ui::Size size) {
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001552 // This cache multiplier was selected based on review of cache sizes relative
1553 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1554 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1555 // conservative default based on that analysis.
1556 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1557 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1558
1559 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001560 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001561
1562 // if it is possible to switch contexts then we will resize the other context
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001563 const bool originalProtectedState = mInProtectedContext;
1564 useProtectedContext(!mInProtectedContext);
1565 if (mInProtectedContext != originalProtectedState) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001566 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001567 // reset back to the initial context that was active when this method was called
Derek Sollenberger1ec2fb52021-06-16 15:11:27 -04001568 useProtectedContext(originalProtectedState);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001569 }
1570}
1571
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001572void SkiaGLRenderEngine::dump(std::string& result) {
1573 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1574
1575 StringAppendF(&result, "\n ------------RE-----------------\n");
1576 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1577 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1578 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1579 extensions.getVersion());
1580 StringAppendF(&result, "%s\n", extensions.getExtensions());
1581 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1582 supportsProtectedContent());
1583 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001584 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1585 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001586
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001587 std::vector<ResourcePair> cpuResourceMap = {
1588 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1589 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1590 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1591 {"skia/sk_resource_cache/tessellated", "Shadows"},
1592 {"skia", "Other"},
1593 };
1594 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1595 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1596 StringAppendF(&result, "Skia CPU Caches: ");
1597 cpuReporter.logTotals(result);
1598 cpuReporter.logOutput(result);
1599
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001600 {
1601 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001602
1603 std::vector<ResourcePair> gpuResourceMap = {
1604 {"texture_renderbuffer", "Texture/RenderBuffer"},
1605 {"texture", "Texture"},
1606 {"gr_text_blob_cache", "Text"},
1607 {"skia", "Other"},
1608 };
1609 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1610 mGrContext->dumpMemoryStatistics(&gpuReporter);
1611 StringAppendF(&result, "Skia's GPU Caches: ");
1612 gpuReporter.logTotals(result);
1613 gpuReporter.logOutput(result);
1614 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1615 gpuReporter.logOutput(result, true);
1616
Alec Mouria90a5702021-04-16 16:36:21 +00001617 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1618 mGraphicBufferExternalRefs.size());
1619 StringAppendF(&result, "Dumping buffer ids...\n");
1620 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1621 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1622 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001623 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1624 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001625 StringAppendF(&result, "Dumping buffer ids...\n");
1626 // TODO(178539829): It would be nice to know which layer these are coming from and what
1627 // the texture sizes are.
1628 for (const auto& [id, unused] : mTextureCache) {
1629 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1630 }
1631 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001632
1633 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001634 if (mProtectedGrContext) {
1635 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1636 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001637 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1638 gpuProtectedReporter.logTotals(result);
1639 gpuProtectedReporter.logOutput(result);
1640 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1641 gpuProtectedReporter.logOutput(result, true);
1642
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001643 StringAppendF(&result, "\n");
1644 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1645 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1646 StringAppendF(&result, "- inputDataspace: %s\n",
1647 dataspaceDetails(
1648 static_cast<android_dataspace>(linearEffect.inputDataspace))
1649 .c_str());
1650 StringAppendF(&result, "- outputDataspace: %s\n",
1651 dataspaceDetails(
1652 static_cast<android_dataspace>(linearEffect.outputDataspace))
1653 .c_str());
1654 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1655 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1656 }
1657 }
1658 StringAppendF(&result, "\n");
1659}
1660
John Reck67b1e2b2020-08-26 13:17:24 -07001661} // namespace skia
1662} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001663} // namespace android