blob: 540e36a60307a991a01d6e75ca5b37be3e305cfa [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 Mouri4ce5ec02021-01-07 17:33:21 -080039#include <sync/sync.h>
40#include <ui/BlurRegion.h>
Ana Krulec1d12b3b2021-01-27 16:49:51 -080041#include <ui/DebugUtils.h>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080042#include <ui/GraphicBuffer.h>
43#include <utils/Trace.h>
Alec Mourib5777452020-09-28 11:32:42 -070044
45#include <cmath>
Alec Mouri4ce5ec02021-01-07 17:33:21 -080046#include <cstdint>
47#include <memory>
48
49#include "../gl/GLExtensions.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040050#include "Cache.h"
Alec Mouric0aae732021-01-12 13:32:18 -080051#include "ColorSpaces.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080052#include "SkBlendMode.h"
53#include "SkImageInfo.h"
54#include "filters/BlurFilter.h"
55#include "filters/LinearEffect.h"
56#include "log/log_main.h"
57#include "skia/debug/SkiaCapture.h"
Derek Sollenberger0e6d3562021-04-07 19:34:39 -040058#include "skia/debug/SkiaMemoryReporter.h"
Nader Jawad2dfc98b2021-04-08 20:35:39 -070059#include "skia/filters/StretchShaderFactory.h"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080060#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070061
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040062namespace {
63// Debugging settings
64static const bool kPrintLayerSettings = false;
65static const bool kFlushAfterEveryLayer = false;
66} // namespace
67
John Reck67b1e2b2020-08-26 13:17:24 -070068bool checkGlError(const char* op, int lineNumber);
69
70namespace android {
71namespace renderengine {
72namespace skia {
73
Ana Krulec1d12b3b2021-01-27 16:49:51 -080074using base::StringAppendF;
75
John Reck67b1e2b2020-08-26 13:17:24 -070076static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
77 EGLint wanted, EGLConfig* outConfig) {
78 EGLint numConfigs = -1, n = 0;
79 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
80 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
81 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
82 configs.resize(n);
83
84 if (!configs.empty()) {
85 if (attribute != EGL_NONE) {
86 for (EGLConfig config : configs) {
87 EGLint value = 0;
88 eglGetConfigAttrib(dpy, config, attribute, &value);
89 if (wanted == value) {
90 *outConfig = config;
91 return NO_ERROR;
92 }
93 }
94 } else {
95 // just pick the first one
96 *outConfig = configs[0];
97 return NO_ERROR;
98 }
99 }
100
101 return NAME_NOT_FOUND;
102}
103
104static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
105 EGLConfig* config) {
106 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
107 // it is to be used with WIFI displays
108 status_t err;
109 EGLint wantedAttribute;
110 EGLint wantedAttributeValue;
111
112 std::vector<EGLint> attribs;
113 if (renderableType) {
114 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
115 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
116
117 // Default to 8 bits per channel.
118 const EGLint tmpAttribs[] = {
119 EGL_RENDERABLE_TYPE,
120 renderableType,
121 EGL_RECORDABLE_ANDROID,
122 EGL_TRUE,
123 EGL_SURFACE_TYPE,
124 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
125 EGL_FRAMEBUFFER_TARGET_ANDROID,
126 EGL_TRUE,
127 EGL_RED_SIZE,
128 is1010102 ? 10 : 8,
129 EGL_GREEN_SIZE,
130 is1010102 ? 10 : 8,
131 EGL_BLUE_SIZE,
132 is1010102 ? 10 : 8,
133 EGL_ALPHA_SIZE,
134 is1010102 ? 2 : 8,
135 EGL_NONE,
136 };
137 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
138 std::back_inserter(attribs));
139 wantedAttribute = EGL_NONE;
140 wantedAttributeValue = EGL_NONE;
141 } else {
142 // if no renderable type specified, fallback to a simplified query
143 wantedAttribute = EGL_NATIVE_VISUAL_ID;
144 wantedAttributeValue = format;
145 }
146
147 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
148 config);
149 if (err == NO_ERROR) {
150 EGLint caveat;
151 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
152 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
153 }
154
155 return err;
156}
157
158std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
159 const RenderEngineCreationArgs& args) {
160 // initialize EGL for the default display
161 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
162 if (!eglInitialize(display, nullptr, nullptr)) {
163 LOG_ALWAYS_FATAL("failed to initialize EGL");
164 }
165
Yiwei Zhange2650962020-12-01 23:27:58 +0000166 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700167 if (!eglVersion) {
168 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000169 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700170 }
171
Yiwei Zhange2650962020-12-01 23:27:58 +0000172 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700173 if (!eglExtensions) {
174 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000175 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700176 }
177
178 auto& extensions = gl::GLExtensions::getInstance();
179 extensions.initWithEGLStrings(eglVersion, eglExtensions);
180
181 // The code assumes that ES2 or later is available if this extension is
182 // supported.
183 EGLConfig config = EGL_NO_CONFIG_KHR;
184 if (!extensions.hasNoConfigContext()) {
185 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
186 }
187
John Reck67b1e2b2020-08-26 13:17:24 -0700188 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800189 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700190 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800191 protectedContext =
192 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700193 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
194 }
195
Alec Mourid6f09462020-12-07 11:18:17 -0800196 EGLContext ctxt =
197 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700198
199 // if can't create a GL context, we can only abort.
200 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
201
202 EGLSurface placeholder = EGL_NO_SURFACE;
203 if (!extensions.hasSurfacelessContext()) {
204 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
205 Protection::UNPROTECTED);
206 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
207 }
208 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
209 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
210 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
211 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
212
213 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
214 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
215 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
216 Protection::PROTECTED);
217 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
218 "can't create protected placeholder pbuffer");
219 }
220
221 // initialize the renderer while GL is current
222 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000223 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
224 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700225
226 ALOGI("OpenGL ES informations:");
227 ALOGI("vendor : %s", extensions.getVendor());
228 ALOGI("renderer : %s", extensions.getRenderer());
229 ALOGI("version : %s", extensions.getVersion());
230 ALOGI("extensions: %s", extensions.getExtensions());
231 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
232 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
233
234 return engine;
235}
236
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500237void SkiaGLRenderEngine::primeCache() {
238 Cache::primeShaderCache(this);
239}
240
John Reck67b1e2b2020-08-26 13:17:24 -0700241EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
242 status_t err;
243 EGLConfig config;
244
245 // First try to get an ES3 config
246 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
247 if (err != NO_ERROR) {
248 // If ES3 fails, try to get an ES2 config
249 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
250 if (err != NO_ERROR) {
251 // If ES2 still doesn't work, probably because we're on the emulator.
252 // try a simplified query
253 ALOGW("no suitable EGLConfig found, trying a simpler query");
254 err = selectEGLConfig(display, format, 0, &config);
255 if (err != NO_ERROR) {
256 // this EGL is too lame for android
257 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
258 }
259 }
260 }
261
262 if (logConfig) {
263 // print some debugging info
264 EGLint r, g, b, a;
265 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
266 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
267 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
268 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
269 ALOGI("EGL information:");
270 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
271 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
272 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
273 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
274 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
275 }
276
277 return config;
278}
279
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400280sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
281 // This "cache" does not actually cache anything. It just allows us to
282 // monitor Skia's internal cache. So this method always returns null.
283 return nullptr;
284}
285
286void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
287 const SkString& description) {
288 mShadersCachedSinceLastCall++;
289}
290
291void SkiaGLRenderEngine::assertShadersCompiled(int numShaders) {
292 const int cached = mSkSLCacheMonitor.shadersCachedSinceLastCall();
293 LOG_ALWAYS_FATAL_IF(cached != numShaders, "Attempted to cache %i shaders; cached %i",
294 numShaders, cached);
295}
296
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400297int SkiaGLRenderEngine::reportShadersCompiled() {
298 return mSkSLCacheMonitor.shadersCachedSinceLastCall();
299}
300
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700301SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000302 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700303 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800304 : SkiaRenderEngine(args.renderEngineType),
305 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700306 mEGLContext(ctxt),
307 mPlaceholderSurface(placeholder),
308 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700309 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400310 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800311 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700312 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
313 LOG_ALWAYS_FATAL_IF(!glInterface.get());
314
315 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400316 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700317 options.fDisableDistanceFieldPaths = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400318 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000319 mGrContext = GrDirectContext::MakeGL(glInterface, options);
320 if (useProtectedContext(true)) {
321 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
322 useProtectedContext(false);
323 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700324
325 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500326 ALOGD("Background Blurs Enabled");
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700327 mBlurFilter = new BlurFilter();
328 }
Alec Mouric0aae732021-01-12 13:32:18 -0800329 mCapture = std::make_unique<SkiaCapture>();
330}
331
332SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100333 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800334 if (mBlurFilter) {
335 delete mBlurFilter;
336 }
337
338 mCapture = nullptr;
339
340 mGrContext->flushAndSubmit(true);
341 mGrContext->abandonContext();
342
343 if (mProtectedGrContext) {
344 mProtectedGrContext->flushAndSubmit(true);
345 mProtectedGrContext->abandonContext();
346 }
347
348 if (mPlaceholderSurface != EGL_NO_SURFACE) {
349 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
350 }
351 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
352 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
353 }
354 if (mEGLContext != EGL_NO_CONTEXT) {
355 eglDestroyContext(mEGLDisplay, mEGLContext);
356 }
357 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
358 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
359 }
360 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
361 eglTerminate(mEGLDisplay);
362 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700363}
364
Lucas Dupind508e472020-11-04 04:32:06 +0000365bool SkiaGLRenderEngine::supportsProtectedContent() const {
366 return mProtectedEGLContext != EGL_NO_CONTEXT;
367}
368
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400369GrDirectContext* SkiaGLRenderEngine::getActiveGrContext() const {
370 return mInProtectedContext ? mProtectedGrContext.get() : mGrContext.get();
371}
372
Lucas Dupind508e472020-11-04 04:32:06 +0000373bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
374 if (useProtectedContext == mInProtectedContext) {
375 return true;
376 }
Alec Mourif6a07812021-02-11 21:07:55 -0800377 if (useProtectedContext && !supportsProtectedContent()) {
Lucas Dupind508e472020-11-04 04:32:06 +0000378 return false;
379 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400380
381 // release any scratch resources before switching into a new mode
382 if (getActiveGrContext()) {
383 getActiveGrContext()->purgeUnlockedResources(true);
384 }
385
Lucas Dupind508e472020-11-04 04:32:06 +0000386 const EGLSurface surface =
387 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
388 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
389 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800390
Lucas Dupind508e472020-11-04 04:32:06 +0000391 if (success) {
392 mInProtectedContext = useProtectedContext;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400393 // given that we are sharing the same thread between two GrContexts we need to
394 // make sure that the thread state is reset when switching between the two.
395 if (getActiveGrContext()) {
396 getActiveGrContext()->resetContext();
397 }
Lucas Dupind508e472020-11-04 04:32:06 +0000398 }
399 return success;
400}
401
John Reck67b1e2b2020-08-26 13:17:24 -0700402base::unique_fd SkiaGLRenderEngine::flush() {
403 ATRACE_CALL();
404 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
405 return base::unique_fd();
406 }
407
408 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
409 if (sync == EGL_NO_SYNC_KHR) {
410 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
411 return base::unique_fd();
412 }
413
414 // native fence fd will not be populated until flush() is done.
415 glFlush();
416
417 // get the fence fd
418 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
419 eglDestroySyncKHR(mEGLDisplay, sync);
420 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
421 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
422 }
423
424 return fenceFd;
425}
426
427bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
428 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
429 !gl::GLExtensions::getInstance().hasWaitSync()) {
430 return false;
431 }
432
433 // release the fd and transfer the ownership to EGLSync
434 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
435 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
436 if (sync == EGL_NO_SYNC_KHR) {
437 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
438 return false;
439 }
440
441 // XXX: The spec draft is inconsistent as to whether this should return an
442 // EGLint or void. Ignore the return value for now, as it's not strictly
443 // needed.
444 eglWaitSyncKHR(mEGLDisplay, sync, 0);
445 EGLint error = eglGetError();
446 eglDestroySyncKHR(mEGLDisplay, sync);
447 if (error != EGL_SUCCESS) {
448 ALOGE("failed to wait for EGL native fence sync: %#x", error);
449 return false;
450 }
451
452 return true;
453}
454
Alec Mouri678245d2020-09-30 16:58:23 -0700455static float toDegrees(uint32_t transform) {
456 switch (transform) {
457 case ui::Transform::ROT_90:
458 return 90.0;
459 case ui::Transform::ROT_180:
460 return 180.0;
461 case ui::Transform::ROT_270:
462 return 270.0;
463 default:
464 return 0.0;
465 }
466}
467
Alec Mourib34f0b72020-10-02 13:18:34 -0700468static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
469 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
470 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
471 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
472 matrix[3][3], 0);
473}
474
Alec Mouri029d1952020-10-12 10:37:08 -0700475static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
476 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
477 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
478
479 // Treat unsupported dataspaces as srgb
480 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
481 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
482 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
483 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
484 }
485
486 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
487 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
488 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
489 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
490 }
491
492 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
493 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
494 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
495 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
496
497 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
498 sourceTransfer != destTransfer;
499}
500
Alec Mouria90a5702021-04-16 16:36:21 +0000501void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
502 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800503 // Only run this if RE is running on its own thread. This way the access to GL
504 // operations is guaranteed to be happening on the same thread.
505 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
506 return;
507 }
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400508 // we currently don't attempt to map a buffer if the buffer contains protected content
509 // because GPU resources for protected buffers is much more limited.
510 const bool isProtectedBuffer = buffer->getUsage() & GRALLOC_USAGE_PROTECTED;
511 if (isProtectedBuffer) {
512 return;
513 }
Ana Krulecdfec8f52021-01-13 12:51:47 -0800514 ATRACE_CALL();
515
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400516 // We need to switch the currently bound context if the buffer is protected but the current
517 // context is not. The current state must then be restored after the buffer is cached.
518 const bool protectedContextState = mInProtectedContext;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400519 if (!useProtectedContext(protectedContextState || isProtectedBuffer)) {
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400520 ALOGE("Attempting to cache a buffer into a different context than what is currently bound");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800521 return;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400522 }
523
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400524 auto grContext = getActiveGrContext();
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400525 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
526
527 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000528 mGraphicBufferExternalRefs[buffer->getId()]++;
529
530 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800531 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400532 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400533 buffer->toAHardwareBuffer(),
534 isRenderable);
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400535 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800536 }
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400537 // restore the original state of the protected context if necessary
538 useProtectedContext(protectedContextState);
Ana Krulecdfec8f52021-01-13 12:51:47 -0800539}
540
Alec Mouria90a5702021-04-16 16:36:21 +0000541void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800542 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700543 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouria90a5702021-04-16 16:36:21 +0000544 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
545 iter != mGraphicBufferExternalRefs.end()) {
546 if (iter->second == 0) {
547 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
548 "> from RenderEngine texture, but the "
549 "ref count was already zero!",
550 buffer->getId());
551 mGraphicBufferExternalRefs.erase(buffer->getId());
552 return;
553 }
554
555 iter->second--;
556
557 if (iter->second == 0) {
558 mTextureCache.erase(buffer->getId());
559 mProtectedTextureCache.erase(buffer->getId());
560 mGraphicBufferExternalRefs.erase(buffer->getId());
561 }
562 }
John Reck67b1e2b2020-08-26 13:17:24 -0700563}
564
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700565sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(
566 sk_sp<SkShader> shader,
567 const LayerSettings* layer, const DisplaySettings& display, bool undoPremultipliedAlpha,
568 bool requiresLinearEffect) {
569 const auto stretchEffect = layer->stretchEffect;
570 if (stretchEffect.hasEffect()) {
571 const auto targetBuffer = layer->source.buffer.buffer;
572 const auto graphicsBuffer = targetBuffer ? targetBuffer->getBuffer() : nullptr;
573 if (graphicsBuffer && shader) {
574 shader = mStretchShaderFactory.createSkShader(shader, stretchEffect);
575 }
John Reckcdb4ed72021-02-04 13:39:33 -0500576 }
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700577
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500578 if (requiresLinearEffect) {
579 const ui::Dataspace inputDataspace =
580 mUseColorManagement ? layer->sourceDataspace : ui::Dataspace::UNKNOWN;
581 const ui::Dataspace outputDataspace =
582 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
583
584 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
585 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800586 .undoPremultipliedAlpha = undoPremultipliedAlpha};
587
588 auto effectIter = mRuntimeEffects.find(effect);
589 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
590 if (effectIter == mRuntimeEffects.end()) {
591 runtimeEffect = buildRuntimeEffect(effect);
592 mRuntimeEffects.insert({effect, runtimeEffect});
593 } else {
594 runtimeEffect = effectIter->second;
595 }
596 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
597 display.maxLuminance,
598 layer->source.buffer.maxMasteringLuminance,
599 layer->source.buffer.maxContentLuminance);
600 }
601 return shader;
602}
603
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500604void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500605 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500606 // Record display settings when capture is running.
607 std::stringstream displaySettings;
608 PrintTo(display, &displaySettings);
609 // Store the DisplaySettings in additional information.
610 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
611 SkData::MakeWithCString(displaySettings.str().c_str()));
612 }
613
614 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
615 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
616 // displays might have different scaling when compared to the physical screen.
617
618 canvas->clipRect(getSkRect(display.physicalDisplay));
619 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
620
621 const auto clipWidth = display.clip.width();
622 const auto clipHeight = display.clip.height();
623 auto rotatedClipWidth = clipWidth;
624 auto rotatedClipHeight = clipHeight;
625 // Scale is contingent on the rotation result.
626 if (display.orientation & ui::Transform::ROT_90) {
627 std::swap(rotatedClipWidth, rotatedClipHeight);
628 }
629 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
630 static_cast<SkScalar>(rotatedClipWidth);
631 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
632 static_cast<SkScalar>(rotatedClipHeight);
633 canvas->scale(scaleX, scaleY);
634
635 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
636 // back so that the top left corner of the clip is at (0, 0).
637 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
638 canvas->rotate(toDegrees(display.orientation));
639 canvas->translate(-clipWidth / 2, -clipHeight / 2);
640 canvas->translate(-display.clip.left, -display.clip.top);
641}
642
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500643class AutoSaveRestore {
644public:
645 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
646 ~AutoSaveRestore() { restore(); }
647 void replace(SkCanvas* canvas) {
648 mCanvas = canvas;
649 mSaveCount = canvas->save();
650 }
651 void restore() {
652 if (mCanvas) {
653 mCanvas->restoreToCount(mSaveCount);
654 mCanvas = nullptr;
655 }
656 }
657
658private:
659 SkCanvas* mCanvas;
660 int mSaveCount;
661};
662
Nader Jawad2dfc98b2021-04-08 20:35:39 -0700663void drawStretch(const SkRect& bounds, const StretchEffect& stretchEffect,
664 SkCanvas* canvas, const SkPaint& paint) {
665 float top = bounds.top();
666 float left = bounds.left();
667 float bottom = bounds.bottom();
668 float right = bounds.right();
669 // Adjust the drawing bounds based on the stretch itself.
670 float stretchOffsetX =
671 round(bounds.width() * stretchEffect.getStretchWidthMultiplier());
672 float stretchOffsetY =
673 round(bounds.height() * stretchEffect.getStretchHeightMultiplier());
674 if (stretchEffect.vectorY < 0.f) {
675 top -= stretchOffsetY;
676 } else if (stretchEffect.vectorY > 0.f){
677 bottom += stretchOffsetY;
678 }
679
680 if (stretchEffect.vectorX < 0.f) {
681 left -= stretchOffsetX;
682 } else if (stretchEffect.vectorX > 0.f) {
683 right += stretchOffsetX;
684 }
685
686 auto stretchBounds = SkRect::MakeLTRB(left, top, right, bottom);
687 canvas->drawRect(stretchBounds, paint);
688}
689
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400690static SkRRect getBlurRRect(const BlurRegion& region) {
691 const auto rect = SkRect::MakeLTRB(region.left, region.top, region.right, region.bottom);
692 const SkVector radii[4] = {SkVector::Make(region.cornerRadiusTL, region.cornerRadiusTL),
693 SkVector::Make(region.cornerRadiusTR, region.cornerRadiusTR),
694 SkVector::Make(region.cornerRadiusBR, region.cornerRadiusBR),
695 SkVector::Make(region.cornerRadiusBL, region.cornerRadiusBL)};
696 SkRRect roundedRect;
697 roundedRect.setRectRadii(rect, radii);
698 return roundedRect;
699}
700
John Reck67b1e2b2020-08-26 13:17:24 -0700701status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
702 const std::vector<const LayerSettings*>& layers,
Alec Mouria90a5702021-04-16 16:36:21 +0000703 const std::shared_ptr<ExternalTexture>& buffer,
704 const bool /*useFramebufferCache*/,
John Reck67b1e2b2020-08-26 13:17:24 -0700705 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
706 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800707
John Reck67b1e2b2020-08-26 13:17:24 -0700708 std::lock_guard<std::mutex> lock(mRenderingMutex);
709 if (layers.empty()) {
710 ALOGV("Drawing empty layer stack");
711 return NO_ERROR;
712 }
713
714 if (bufferFence.get() >= 0) {
715 // Duplicate the fence for passing to waitFence.
716 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
717 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
718 ATRACE_NAME("Waiting before draw");
719 sync_wait(bufferFence.get(), -1);
720 }
721 }
722 if (buffer == nullptr) {
723 ALOGE("No output buffer provided. Aborting GPU composition.");
724 return BAD_VALUE;
725 }
726
Alec Mouria90a5702021-04-16 16:36:21 +0000727 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800728
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400729 auto grContext = getActiveGrContext();
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800730 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700731
Alec Mouria90a5702021-04-16 16:36:21 +0000732 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
733 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
734 surfaceTextureRef = it->second;
735 } else {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400736 surfaceTextureRef =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400737 std::make_shared<AutoBackendTexture::LocalRef>(grContext,
738 buffer->getBuffer()
739 ->toAHardwareBuffer(),
740 true);
John Reck67b1e2b2020-08-26 13:17:24 -0700741 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800742
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500743 const ui::Dataspace dstDataspace =
744 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400745 sk_sp<SkSurface> dstSurface = surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700746
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500747 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
748 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800749 ALOGE("Cannot acquire canvas from Skia.");
750 return BAD_VALUE;
751 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500752
753 // Find if any layers have requested blur, we'll use that info to decide when to render to an
754 // offscreen buffer and when to render to the native buffer.
755 sk_sp<SkSurface> activeSurface(dstSurface);
756 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500757 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500758 const LayerSettings* blurCompositionLayer = nullptr;
759 if (mBlurFilter) {
760 bool requiresCompositionLayer = false;
761 for (const auto& layer : layers) {
Derek Sollenberger3134ec32021-02-12 11:26:23 -0500762 if (layer->backgroundBlurRadius > 0 &&
763 layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500764 requiresCompositionLayer = true;
765 }
766 for (auto region : layer->blurRegions) {
767 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
768 requiresCompositionLayer = true;
769 }
770 }
771 if (requiresCompositionLayer) {
772 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500773 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500774 blurCompositionLayer = layer;
775 break;
776 }
777 }
778 }
779
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500780 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700781 // Clear the entire canvas with a transparent black to prevent ghost images.
782 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500783 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800784
785 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
786 // view is still on-screen. The clear region could be re-specified as a black color layer,
787 // however.
788 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500789 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800790 size_t numRects = 0;
791 Rect const* rects = display.clearRegion.getArray(&numRects);
792 SkIRect skRects[numRects];
793 for (int i = 0; i < numRects; ++i) {
794 skRects[i] =
795 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
796 }
797 SkRegion clearRegion;
798 SkPaint paint;
799 sk_sp<SkShader> shader =
800 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500801 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800802 paint.setShader(shader);
803 clearRegion.setRects(skRects, numRects);
804 canvas->drawRegion(clearRegion, paint);
805 }
806
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500807 // setup color filter if necessary
808 sk_sp<SkColorFilter> displayColorTransform;
809 if (display.colorTransform != mat4()) {
810 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
811 }
812
John Reck67b1e2b2020-08-26 13:17:24 -0700813 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500814 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100815
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400816 if (kPrintLayerSettings) {
817 std::stringstream ls;
818 PrintTo(*layer, &ls);
819 auto debugs = ls.str();
820 int pos = 0;
821 while (pos < debugs.size()) {
822 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
823 pos += 1000;
824 }
825 }
826
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500827 sk_sp<SkImage> blurInput;
828 if (blurCompositionLayer == layer) {
829 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
830 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
831
832 // save a snapshot of the activeSurface to use as input to the blur shaders
833 blurInput = activeSurface->makeImageSnapshot();
834
835 // TODO we could skip this step if we know the blur will cover the entire image
836 // blit the offscreen framebuffer into the destination AHB
837 SkPaint paint;
838 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500839 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
840 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
841 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
842 String8::format("SurfaceID|%" PRId64, id).c_str(),
843 nullptr);
844 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
845 } else {
846 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
847 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500848
849 // assign dstCanvas to canvas and ensure that the canvas state is up to date
850 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500851 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500852 initCanvas(canvas, display);
853
854 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
855 dstSurface->getCanvas()->getSaveCount());
856 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
857 dstSurface->getCanvas()->getTotalMatrix());
858
859 // assign dstSurface to activeSurface
860 activeSurface = dstSurface;
861 }
862
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500863 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500864 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800865 // Record the name of the layer if the capture is running.
866 std::stringstream layerSettings;
867 PrintTo(*layer, &layerSettings);
868 // Store the LayerSettings in additional information.
869 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
870 SkData::MakeWithCString(layerSettings.str().c_str()));
871 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100872 // Layers have a local transform that should be applied to them
873 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100874
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400875 const auto [bounds, roundRectClip] = getBoundsAndClip(layer);
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500876 if (mBlurFilter && layerHasBlur(layer)) {
877 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
878
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500879 // if multiple layers have blur, then we need to take a snapshot now because
880 // only the lowest layer will have blurImage populated earlier
881 if (!blurInput) {
882 blurInput = activeSurface->makeImageSnapshot();
883 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500884 // rect to be blurred in the coordinate space of blurInput
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400885 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds.rect());
886
887 // if the clip needs to be applied then apply it now and make sure
888 // it is restored before we attempt to draw any shadows.
889 SkAutoCanvasRestore acr(canvas, true);
890 if (!roundRectClip.isEmpty()) {
891 canvas->clipRRect(roundRectClip, true);
892 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500893
Galia Peychevae425ac82021-03-15 17:12:03 +0100894 // TODO(b/182216890): Filter out empty layers earlier
895 if (blurRect.width() > 0 && blurRect.height() > 0) {
896 if (layer->backgroundBlurRadius > 0) {
897 ATRACE_NAME("BackgroundBlur");
898 auto blurredImage =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400899 mBlurFilter->generate(grContext, layer->backgroundBlurRadius, blurInput,
900 blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100901
Galia Peychevae425ac82021-03-15 17:12:03 +0100902 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500903
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400904 mBlurFilter->drawBlurRegion(canvas, bounds, layer->backgroundBlurRadius, 1.0f,
905 blurRect, blurredImage, blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700906 }
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400907
Derek Sollenberger39feade2021-04-27 16:08:40 -0400908 canvas->concat(getSkM44(layer->blurRegionTransform).asM33());
Galia Peychevae425ac82021-03-15 17:12:03 +0100909 for (auto region : layer->blurRegions) {
910 if (cachedBlurs[region.blurRadius] == nullptr) {
911 ATRACE_NAME("BlurRegion");
912 cachedBlurs[region.blurRadius] =
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400913 mBlurFilter->generate(grContext, region.blurRadius, blurInput,
Galia Peychevae425ac82021-03-15 17:12:03 +0100914 blurRect);
915 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500916
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400917 mBlurFilter->drawBlurRegion(canvas, getBlurRRect(region), region.blurRadius,
918 region.alpha, blurRect,
Galia Peychevae425ac82021-03-15 17:12:03 +0100919 cachedBlurs[region.blurRadius], blurInput);
920 }
Lucas Dupinc3800b82020-10-02 16:24:48 -0700921 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700922 }
923
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500924 // Shadows are assumed to live only on their own layer - it's not valid
925 // to draw the boundary rectangles when there is already a caster shadow
926 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
927 // composition - using a well-defined invalid color is long-term less error-prone.
928 if (layer->shadow.length > 0) {
929 const auto rect = layer->geometry.roundedCornersRadius > 0
930 ? getSkRect(layer->geometry.roundedCornersCrop)
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400931 : bounds.rect();
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400932 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
933 LOG_ALWAYS_FATAL_IF(layer->disableBlending, "Cannot disableBlending with a shadow");
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500934 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
935 continue;
936 }
937
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500938 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
939 (mUseColorManagement &&
940 needsToneMapping(layer->sourceDataspace, display.outputDataspace));
941
942 // quick abort from drawing the remaining portion of the layer
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400943 if (layer->alpha == 0 && !requiresLinearEffect && !layer->disableBlending &&
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500944 (!displayColorTransform || displayColorTransform->isAlphaUnchanged())) {
945 continue;
946 }
947
948 // If we need to map to linear space or color management is disabled, then mark the source
949 // image with the same colorspace as the destination surface so that Skia's color
950 // management is a no-op.
951 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
952 ? dstDataspace
953 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800954
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500955 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700956 if (layer->source.buffer.buffer) {
957 ATRACE_NAME("DrawImage");
Alec Mouria90a5702021-04-16 16:36:21 +0000958 validateInputBufferUsage(layer->source.buffer.buffer->getBuffer());
John Reck67b1e2b2020-08-26 13:17:24 -0700959 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800960 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +0000961
962 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
963 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800964 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700965 } else {
Alec Mouria90a5702021-04-16 16:36:21 +0000966 // If we didn't find the image in the cache, then create a local ref but don't cache
967 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
968 // we didn't find anything in the cache then we intentionally did not cache this
969 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400970 imageTextureRef = std::make_shared<
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400971 AutoBackendTexture::LocalRef>(grContext,
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400972 item.buffer->getBuffer()->toAHardwareBuffer(),
973 false);
John Reck67b1e2b2020-08-26 13:17:24 -0700974 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800975
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800976 sk_sp<SkImage> image =
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400977 imageTextureRef->makeImage(layerDataspace,
978 item.usePremultipliedAlpha ? kPremul_SkAlphaType
979 : kUnpremul_SkAlphaType,
Derek Sollenbergerb24258c2021-05-04 13:47:34 -0400980 grContext);
Alec Mouri678245d2020-09-30 16:58:23 -0700981
982 auto texMatrix = getSkM44(item.textureTransform).asM33();
983 // textureTansform was intended to be passed directly into a shader, so when
984 // building the total matrix with the textureTransform we need to first
985 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500986 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800987 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700988
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800989 SkMatrix matrix;
990 if (!texMatrix.invert(&matrix)) {
991 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700992 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800993 // The shader does not respect the translation, so we add it to the texture
994 // transform for the SkImage. This will make sure that the correct layer contents
995 // are drawn in the correct part of the screen.
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -0400996 matrix.postTranslate(bounds.rect().fLeft, bounds.rect().fTop);
Alec Mouri678245d2020-09-30 16:58:23 -0700997
Ana Krulecb7b28b22020-11-23 14:48:58 -0800998 sk_sp<SkShader> shader;
999
1000 if (layer->source.buffer.useTextureFiltering) {
1001 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
1002 SkSamplingOptions(
1003 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
1004 &matrix);
1005 } else {
Mike Reed711e1f02020-12-11 13:06:19 -05001006 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -08001007 }
Alec Mouri029d1952020-10-12 10:37:08 -07001008
Alec Mouric0aae732021-01-12 13:32:18 -08001009 // Handle opaque images - it's a little nonstandard how we do this.
1010 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
1011 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
1012 // The important language is that when isOpaque is set, opacity is not sampled from the
1013 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
1014 // here's the conundrum:
1015 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
1016 // as an internal hint - composition is undefined when there are alpha bits present.
1017 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
1018 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
1019 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
1020 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
1021 // of a hack anyways.
1022 // 3. We can't change the blendmode to src, because while this satisfies the requirement
1023 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
1024 // because src always clobbers the destination content.
1025 //
1026 // So, what we do here instead is an additive blend mode where we compose the input
1027 // image with a solid black. This might need to be reassess if this does not support
1028 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
1029 if (item.isOpaque) {
1030 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
1031 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001032 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -08001033 }
1034
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001035 paint.setShader(createRuntimeEffectShader(shader, layer, display,
1036 !item.isOpaque && item.usePremultipliedAlpha,
1037 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -08001038 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -07001039 } else {
1040 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -07001041 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -08001042 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
1043 .fG = color.g,
1044 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -08001045 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001046 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -08001047 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001048 /* undoPremultipliedAlpha */ false,
1049 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -07001050 }
Lucas Dupin21f348e2020-09-16 17:31:26 -07001051
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -04001052 if (layer->disableBlending) {
1053 paint.setBlendMode(SkBlendMode::kSrc);
1054 }
1055
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -05001056 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -07001057
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001058 if (!roundRectClip.isEmpty()) {
1059 canvas->clipRRect(roundRectClip, true);
1060 }
1061
1062 if (!bounds.isRect()) {
Derek Sollenberger4c331c82021-02-23 13:09:50 -05001063 paint.setAntiAlias(true);
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001064 canvas->drawRRect(bounds, paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -08001065 } else {
Nader Jawad2dfc98b2021-04-08 20:35:39 -07001066 auto& stretchEffect = layer->stretchEffect;
1067 // TODO (njawad) temporarily disable manipulation of geometry
1068 // the layer bounds will be updated in HWUI instead of RenderEngine
1069 // in a subsequent CL
1070 // Keep the method call in a dead code path to make -Werror happy
1071 // with unused methods
1072 if (stretchEffect.hasEffect() && /* DISABLES CODE */ (false)) {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001073 drawStretch(bounds.rect(), stretchEffect, canvas, paint);
Nader Jawad2dfc98b2021-04-08 20:35:39 -07001074 } else {
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001075 canvas->drawRect(bounds.rect(), paint);
Nader Jawad2dfc98b2021-04-08 20:35:39 -07001076 }
Lucas Dupin3f11e922020-09-22 17:31:04 -07001077 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -04001078 if (kFlushAfterEveryLayer) {
1079 ATRACE_NAME("flush surface");
1080 activeSurface->flush();
1081 }
John Reck67b1e2b2020-08-26 13:17:24 -07001082 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -05001083 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -08001084 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -07001085 {
1086 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -05001087 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
1088 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -07001089 }
1090
1091 if (drawFence != nullptr) {
1092 *drawFence = flush();
1093 }
1094
1095 // If flush failed or we don't support native fences, we need to force the
1096 // gl command stream to be executed.
1097 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
1098 if (requireSync) {
1099 ATRACE_BEGIN("Submit(sync=true)");
1100 } else {
1101 ATRACE_BEGIN("Submit(sync=false)");
1102 }
Lucas Dupind508e472020-11-04 04:32:06 +00001103 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001104 ATRACE_END();
1105 if (!success) {
1106 ALOGE("Failed to flush RenderEngine commands");
1107 // Chances are, something illegal happened (either the caller passed
1108 // us bad parameters, or we messed up our shader generation).
1109 return INVALID_OPERATION;
1110 }
1111
1112 // checkErrors();
1113 return NO_ERROR;
1114}
1115
Lucas Dupin3f11e922020-09-22 17:31:04 -07001116inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1117 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1118}
1119
1120inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1121 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1122}
1123
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001124inline std::pair<SkRRect, SkRRect> SkiaGLRenderEngine::getBoundsAndClip(
1125 const LayerSettings* layer) {
1126 const auto bounds = getSkRect(layer->geometry.boundaries);
1127 const auto crop = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001128 const auto cornerRadius = layer->geometry.roundedCornersRadius;
Lucas Dupin21f348e2020-09-16 17:31:26 -07001129
Derek Sollenberger8e8b3bf2021-04-29 15:35:28 -04001130 SkRRect clip;
1131 if (cornerRadius > 0) {
1132 // it the crop and the bounds are equivalent then we don't need a clip
1133 if (bounds == crop) {
1134 return {SkRRect::MakeRectXY(bounds, cornerRadius, cornerRadius), clip};
1135 }
1136
1137 // This makes an effort to speed up common, simple bounds + clip combinations by
1138 // converting them to a single RRect draw. It is possible there are other cases
1139 // that can be converted.
1140 if (crop.contains(bounds)) {
1141 bool intersectionIsRoundRect = true;
1142 // check each cropped corner to ensure that it exactly matches the crop or is full
1143 SkVector radii[4];
1144
1145 const auto insetCrop = crop.makeInset(cornerRadius, cornerRadius);
1146
1147 // compute the UpperLeft corner radius
1148 if (bounds.fLeft == crop.fLeft && bounds.fTop == crop.fTop) {
1149 radii[0].set(cornerRadius, cornerRadius);
1150 } else if (bounds.fLeft > insetCrop.fLeft && bounds.fTop > insetCrop.fTop) {
1151 radii[0].set(0, 0);
1152 } else {
1153 intersectionIsRoundRect = false;
1154 }
1155 // compute the UpperRight corner radius
1156 if (bounds.fRight == crop.fRight && bounds.fTop == crop.fTop) {
1157 radii[1].set(cornerRadius, cornerRadius);
1158 } else if (bounds.fRight < insetCrop.fRight && bounds.fTop > insetCrop.fTop) {
1159 radii[1].set(0, 0);
1160 } else {
1161 intersectionIsRoundRect = false;
1162 }
1163 // compute the BottomRight corner radius
1164 if (bounds.fRight == crop.fRight && bounds.fBottom == crop.fBottom) {
1165 radii[2].set(cornerRadius, cornerRadius);
1166 } else if (bounds.fRight < insetCrop.fRight && bounds.fBottom < insetCrop.fBottom) {
1167 radii[2].set(0, 0);
1168 } else {
1169 intersectionIsRoundRect = false;
1170 }
1171 // compute the BottomLeft corner radius
1172 if (bounds.fLeft == crop.fLeft && bounds.fBottom == crop.fBottom) {
1173 radii[3].set(cornerRadius, cornerRadius);
1174 } else if (bounds.fLeft > insetCrop.fLeft && bounds.fBottom < insetCrop.fBottom) {
1175 radii[3].set(0, 0);
1176 } else {
1177 intersectionIsRoundRect = false;
1178 }
1179
1180 if (intersectionIsRoundRect) {
1181 SkRRect intersectionBounds;
1182 intersectionBounds.setRectRadii(bounds, radii);
1183 return {intersectionBounds, clip};
1184 }
1185 }
1186
1187 // we didn't it any of our fast paths so set the clip to the cropRect
1188 clip.setRectXY(crop, cornerRadius, cornerRadius);
1189 }
1190
1191 // if we hit this point then we either don't have rounded corners or we are going to rely
1192 // on the clip to round the corners for us
1193 return {SkRRect::MakeRect(bounds), clip};
Galia Peycheva80116e52020-11-06 11:57:25 +01001194}
1195
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001196inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
1197 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
1198}
1199
Lucas Dupin3f11e922020-09-22 17:31:04 -07001200inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1201 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1202}
1203
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001204inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1205 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1206 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1207 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1208 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1209}
1210
Lucas Dupin3f11e922020-09-22 17:31:04 -07001211inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1212 return SkPoint3::Make(vector.x, vector.y, vector.z);
1213}
1214
John Reck67b1e2b2020-08-26 13:17:24 -07001215size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1216 return mGrContext->maxTextureSize();
1217}
1218
1219size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1220 return mGrContext->maxRenderTargetSize();
1221}
1222
Lucas Dupin3f11e922020-09-22 17:31:04 -07001223void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
1224 const ShadowSettings& settings) {
1225 ATRACE_CALL();
1226 const float casterZ = settings.length / 2.0f;
1227 const auto shadowShape = cornerRadius > 0
1228 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
1229 : SkPath::Rect(casterRect);
1230 const auto flags =
1231 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1232
1233 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
1234 getSkPoint3(settings.lightPos), settings.lightRadius,
1235 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1236 flags);
1237}
1238
John Reck67b1e2b2020-08-26 13:17:24 -07001239EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001240 EGLContext shareContext,
1241 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001242 Protection protection) {
1243 EGLint renderableType = 0;
1244 if (config == EGL_NO_CONFIG_KHR) {
1245 renderableType = EGL_OPENGL_ES3_BIT;
1246 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1247 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1248 }
1249 EGLint contextClientVersion = 0;
1250 if (renderableType & EGL_OPENGL_ES3_BIT) {
1251 contextClientVersion = 3;
1252 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1253 contextClientVersion = 2;
1254 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1255 contextClientVersion = 1;
1256 } else {
1257 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1258 }
1259
1260 std::vector<EGLint> contextAttributes;
1261 contextAttributes.reserve(7);
1262 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1263 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001264 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001265 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001266 switch (*contextPriority) {
1267 case ContextPriority::REALTIME:
1268 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1269 break;
1270 case ContextPriority::MEDIUM:
1271 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1272 break;
1273 case ContextPriority::LOW:
1274 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1275 break;
1276 case ContextPriority::HIGH:
1277 default:
1278 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1279 break;
1280 }
John Reck67b1e2b2020-08-26 13:17:24 -07001281 }
1282 if (protection == Protection::PROTECTED) {
1283 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1284 contextAttributes.push_back(EGL_TRUE);
1285 }
1286 contextAttributes.push_back(EGL_NONE);
1287
1288 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1289
1290 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1291 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1292 // EGL_NO_CONTEXT so that we can abort.
1293 if (config != EGL_NO_CONFIG_KHR) {
1294 return context;
1295 }
1296 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1297 // should try to fall back to GLES 2.
1298 contextAttributes[1] = 2;
1299 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1300 }
1301
1302 return context;
1303}
1304
Alec Mourid6f09462020-12-07 11:18:17 -08001305std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1306 const RenderEngineCreationArgs& args) {
1307 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1308 return std::nullopt;
1309 }
1310
1311 switch (args.contextPriority) {
1312 case RenderEngine::ContextPriority::REALTIME:
1313 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1314 return RenderEngine::ContextPriority::REALTIME;
1315 } else {
1316 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1317 return RenderEngine::ContextPriority::HIGH;
1318 }
1319 case RenderEngine::ContextPriority::HIGH:
1320 case RenderEngine::ContextPriority::MEDIUM:
1321 case RenderEngine::ContextPriority::LOW:
1322 return args.contextPriority;
1323 default:
1324 return std::nullopt;
1325 }
1326}
1327
John Reck67b1e2b2020-08-26 13:17:24 -07001328EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1329 EGLConfig config, int hwcFormat,
1330 Protection protection) {
1331 EGLConfig placeholderConfig = config;
1332 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1333 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1334 }
1335 std::vector<EGLint> attributes;
1336 attributes.reserve(7);
1337 attributes.push_back(EGL_WIDTH);
1338 attributes.push_back(1);
1339 attributes.push_back(EGL_HEIGHT);
1340 attributes.push_back(1);
1341 if (protection == Protection::PROTECTED) {
1342 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1343 attributes.push_back(EGL_TRUE);
1344 }
1345 attributes.push_back(EGL_NONE);
1346
1347 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1348}
1349
Alec Mourid6f09462020-12-07 11:18:17 -08001350int SkiaGLRenderEngine::getContextPriority() {
1351 int value;
1352 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1353 return value;
1354}
1355
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001356void SkiaGLRenderEngine::onPrimaryDisplaySizeChanged(ui::Size size) {
1357 // This cache multiplier was selected based on review of cache sizes relative
1358 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1359 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1360 // conservative default based on that analysis.
1361 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1362 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1363
1364 // start by resizing the current context
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001365 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001366
1367 // if it is possible to switch contexts then we will resize the other context
1368 if (useProtectedContext(!mInProtectedContext)) {
Derek Sollenbergerb24258c2021-05-04 13:47:34 -04001369 getActiveGrContext()->setResourceCacheLimit(maxResourceBytes);
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001370 // reset back to the initial context that was active when this method was called
1371 useProtectedContext(!mInProtectedContext);
1372 }
1373}
1374
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001375void SkiaGLRenderEngine::dump(std::string& result) {
1376 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1377
1378 StringAppendF(&result, "\n ------------RE-----------------\n");
1379 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1380 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1381 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1382 extensions.getVersion());
1383 StringAppendF(&result, "%s\n", extensions.getExtensions());
1384 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1385 supportsProtectedContent());
1386 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001387 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1388 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001389
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001390 std::vector<ResourcePair> cpuResourceMap = {
1391 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1392 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1393 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1394 {"skia/sk_resource_cache/tessellated", "Shadows"},
1395 {"skia", "Other"},
1396 };
1397 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1398 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1399 StringAppendF(&result, "Skia CPU Caches: ");
1400 cpuReporter.logTotals(result);
1401 cpuReporter.logOutput(result);
1402
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001403 {
1404 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001405
1406 std::vector<ResourcePair> gpuResourceMap = {
1407 {"texture_renderbuffer", "Texture/RenderBuffer"},
1408 {"texture", "Texture"},
1409 {"gr_text_blob_cache", "Text"},
1410 {"skia", "Other"},
1411 };
1412 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1413 mGrContext->dumpMemoryStatistics(&gpuReporter);
1414 StringAppendF(&result, "Skia's GPU Caches: ");
1415 gpuReporter.logTotals(result);
1416 gpuReporter.logOutput(result);
1417 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1418 gpuReporter.logOutput(result, true);
1419
Alec Mouria90a5702021-04-16 16:36:21 +00001420 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1421 mGraphicBufferExternalRefs.size());
1422 StringAppendF(&result, "Dumping buffer ids...\n");
1423 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1424 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1425 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001426 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1427 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001428 StringAppendF(&result, "Dumping buffer ids...\n");
1429 // TODO(178539829): It would be nice to know which layer these are coming from and what
1430 // the texture sizes are.
1431 for (const auto& [id, unused] : mTextureCache) {
1432 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1433 }
1434 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001435
1436 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001437 if (mProtectedGrContext) {
1438 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1439 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001440 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1441 gpuProtectedReporter.logTotals(result);
1442 gpuProtectedReporter.logOutput(result);
1443 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1444 gpuProtectedReporter.logOutput(result, true);
1445
1446 StringAppendF(&result, "RenderEngine protected AHB/BackendTexture cache size: %zu\n",
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001447 mProtectedTextureCache.size());
1448 StringAppendF(&result, "Dumping buffer ids...\n");
1449 for (const auto& [id, unused] : mProtectedTextureCache) {
1450 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1451 }
1452 StringAppendF(&result, "\n");
1453 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1454 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1455 StringAppendF(&result, "- inputDataspace: %s\n",
1456 dataspaceDetails(
1457 static_cast<android_dataspace>(linearEffect.inputDataspace))
1458 .c_str());
1459 StringAppendF(&result, "- outputDataspace: %s\n",
1460 dataspaceDetails(
1461 static_cast<android_dataspace>(linearEffect.outputDataspace))
1462 .c_str());
1463 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1464 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1465 }
1466 }
1467 StringAppendF(&result, "\n");
1468}
1469
John Reck67b1e2b2020-08-26 13:17:24 -07001470} // namespace skia
1471} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001472} // namespace android