blob: 37d98a3a8f96be21ea1600ad8767e0f94c6b7616 [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"
Alec Mouri4ce5ec02021-01-07 17:33:21 -080059#include "system/graphics-base-v1.0.h"
Alec Mourib5777452020-09-28 11:32:42 -070060
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -040061namespace {
62// Debugging settings
63static const bool kPrintLayerSettings = false;
64static const bool kFlushAfterEveryLayer = false;
65} // namespace
66
John Reck67b1e2b2020-08-26 13:17:24 -070067bool checkGlError(const char* op, int lineNumber);
68
69namespace android {
70namespace renderengine {
71namespace skia {
72
Ana Krulec1d12b3b2021-01-27 16:49:51 -080073using base::StringAppendF;
74
John Reck67b1e2b2020-08-26 13:17:24 -070075static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
76 EGLint wanted, EGLConfig* outConfig) {
77 EGLint numConfigs = -1, n = 0;
78 eglGetConfigs(dpy, nullptr, 0, &numConfigs);
79 std::vector<EGLConfig> configs(numConfigs, EGL_NO_CONFIG_KHR);
80 eglChooseConfig(dpy, attrs, configs.data(), configs.size(), &n);
81 configs.resize(n);
82
83 if (!configs.empty()) {
84 if (attribute != EGL_NONE) {
85 for (EGLConfig config : configs) {
86 EGLint value = 0;
87 eglGetConfigAttrib(dpy, config, attribute, &value);
88 if (wanted == value) {
89 *outConfig = config;
90 return NO_ERROR;
91 }
92 }
93 } else {
94 // just pick the first one
95 *outConfig = configs[0];
96 return NO_ERROR;
97 }
98 }
99
100 return NAME_NOT_FOUND;
101}
102
103static status_t selectEGLConfig(EGLDisplay display, EGLint format, EGLint renderableType,
104 EGLConfig* config) {
105 // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
106 // it is to be used with WIFI displays
107 status_t err;
108 EGLint wantedAttribute;
109 EGLint wantedAttributeValue;
110
111 std::vector<EGLint> attribs;
112 if (renderableType) {
113 const ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(format);
114 const bool is1010102 = pixelFormat == ui::PixelFormat::RGBA_1010102;
115
116 // Default to 8 bits per channel.
117 const EGLint tmpAttribs[] = {
118 EGL_RENDERABLE_TYPE,
119 renderableType,
120 EGL_RECORDABLE_ANDROID,
121 EGL_TRUE,
122 EGL_SURFACE_TYPE,
123 EGL_WINDOW_BIT | EGL_PBUFFER_BIT,
124 EGL_FRAMEBUFFER_TARGET_ANDROID,
125 EGL_TRUE,
126 EGL_RED_SIZE,
127 is1010102 ? 10 : 8,
128 EGL_GREEN_SIZE,
129 is1010102 ? 10 : 8,
130 EGL_BLUE_SIZE,
131 is1010102 ? 10 : 8,
132 EGL_ALPHA_SIZE,
133 is1010102 ? 2 : 8,
134 EGL_NONE,
135 };
136 std::copy(tmpAttribs, tmpAttribs + (sizeof(tmpAttribs) / sizeof(EGLint)),
137 std::back_inserter(attribs));
138 wantedAttribute = EGL_NONE;
139 wantedAttributeValue = EGL_NONE;
140 } else {
141 // if no renderable type specified, fallback to a simplified query
142 wantedAttribute = EGL_NATIVE_VISUAL_ID;
143 wantedAttributeValue = format;
144 }
145
146 err = selectConfigForAttribute(display, attribs.data(), wantedAttribute, wantedAttributeValue,
147 config);
148 if (err == NO_ERROR) {
149 EGLint caveat;
150 if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
151 ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
152 }
153
154 return err;
155}
156
157std::unique_ptr<SkiaGLRenderEngine> SkiaGLRenderEngine::create(
158 const RenderEngineCreationArgs& args) {
159 // initialize EGL for the default display
160 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
161 if (!eglInitialize(display, nullptr, nullptr)) {
162 LOG_ALWAYS_FATAL("failed to initialize EGL");
163 }
164
Yiwei Zhange2650962020-12-01 23:27:58 +0000165 const auto eglVersion = eglQueryString(display, EGL_VERSION);
John Reck67b1e2b2020-08-26 13:17:24 -0700166 if (!eglVersion) {
167 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000168 LOG_ALWAYS_FATAL("eglQueryString(EGL_VERSION) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700169 }
170
Yiwei Zhange2650962020-12-01 23:27:58 +0000171 const auto eglExtensions = eglQueryString(display, EGL_EXTENSIONS);
John Reck67b1e2b2020-08-26 13:17:24 -0700172 if (!eglExtensions) {
173 checkGlError(__FUNCTION__, __LINE__);
Yiwei Zhange2650962020-12-01 23:27:58 +0000174 LOG_ALWAYS_FATAL("eglQueryString(EGL_EXTENSIONS) failed");
John Reck67b1e2b2020-08-26 13:17:24 -0700175 }
176
177 auto& extensions = gl::GLExtensions::getInstance();
178 extensions.initWithEGLStrings(eglVersion, eglExtensions);
179
180 // The code assumes that ES2 or later is available if this extension is
181 // supported.
182 EGLConfig config = EGL_NO_CONFIG_KHR;
183 if (!extensions.hasNoConfigContext()) {
184 config = chooseEglConfig(display, args.pixelFormat, /*logConfig*/ true);
185 }
186
John Reck67b1e2b2020-08-26 13:17:24 -0700187 EGLContext protectedContext = EGL_NO_CONTEXT;
Alec Mourid6f09462020-12-07 11:18:17 -0800188 const std::optional<RenderEngine::ContextPriority> priority = createContextPriority(args);
John Reck67b1e2b2020-08-26 13:17:24 -0700189 if (args.enableProtectedContext && extensions.hasProtectedContent()) {
Alec Mourid6f09462020-12-07 11:18:17 -0800190 protectedContext =
191 createEglContext(display, config, nullptr, priority, Protection::PROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700192 ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
193 }
194
Alec Mourid6f09462020-12-07 11:18:17 -0800195 EGLContext ctxt =
196 createEglContext(display, config, protectedContext, priority, Protection::UNPROTECTED);
John Reck67b1e2b2020-08-26 13:17:24 -0700197
198 // if can't create a GL context, we can only abort.
199 LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
200
201 EGLSurface placeholder = EGL_NO_SURFACE;
202 if (!extensions.hasSurfacelessContext()) {
203 placeholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
204 Protection::UNPROTECTED);
205 LOG_ALWAYS_FATAL_IF(placeholder == EGL_NO_SURFACE, "can't create placeholder pbuffer");
206 }
207 EGLBoolean success = eglMakeCurrent(display, placeholder, placeholder, ctxt);
208 LOG_ALWAYS_FATAL_IF(!success, "can't make placeholder pbuffer current");
209 extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
210 glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
211
212 EGLSurface protectedPlaceholder = EGL_NO_SURFACE;
213 if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
214 protectedPlaceholder = createPlaceholderEglPbufferSurface(display, config, args.pixelFormat,
215 Protection::PROTECTED);
216 ALOGE_IF(protectedPlaceholder == EGL_NO_SURFACE,
217 "can't create protected placeholder pbuffer");
218 }
219
220 // initialize the renderer while GL is current
221 std::unique_ptr<SkiaGLRenderEngine> engine =
Lucas Dupind508e472020-11-04 04:32:06 +0000222 std::make_unique<SkiaGLRenderEngine>(args, display, ctxt, placeholder, protectedContext,
223 protectedPlaceholder);
John Reck67b1e2b2020-08-26 13:17:24 -0700224
225 ALOGI("OpenGL ES informations:");
226 ALOGI("vendor : %s", extensions.getVendor());
227 ALOGI("renderer : %s", extensions.getRenderer());
228 ALOGI("version : %s", extensions.getVersion());
229 ALOGI("extensions: %s", extensions.getExtensions());
230 ALOGI("GL_MAX_TEXTURE_SIZE = %zu", engine->getMaxTextureSize());
231 ALOGI("GL_MAX_VIEWPORT_DIMS = %zu", engine->getMaxViewportDims());
232
233 return engine;
234}
235
Leon Scroggins IIIb9216dc2021-03-08 17:19:01 -0500236void SkiaGLRenderEngine::primeCache() {
237 Cache::primeShaderCache(this);
238}
239
John Reck67b1e2b2020-08-26 13:17:24 -0700240EGLConfig SkiaGLRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
241 status_t err;
242 EGLConfig config;
243
244 // First try to get an ES3 config
245 err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
246 if (err != NO_ERROR) {
247 // If ES3 fails, try to get an ES2 config
248 err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
249 if (err != NO_ERROR) {
250 // If ES2 still doesn't work, probably because we're on the emulator.
251 // try a simplified query
252 ALOGW("no suitable EGLConfig found, trying a simpler query");
253 err = selectEGLConfig(display, format, 0, &config);
254 if (err != NO_ERROR) {
255 // this EGL is too lame for android
256 LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
257 }
258 }
259 }
260
261 if (logConfig) {
262 // print some debugging info
263 EGLint r, g, b, a;
264 eglGetConfigAttrib(display, config, EGL_RED_SIZE, &r);
265 eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &g);
266 eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &b);
267 eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &a);
268 ALOGI("EGL information:");
269 ALOGI("vendor : %s", eglQueryString(display, EGL_VENDOR));
270 ALOGI("version : %s", eglQueryString(display, EGL_VERSION));
271 ALOGI("extensions: %s", eglQueryString(display, EGL_EXTENSIONS));
272 ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS) ?: "Not Supported");
273 ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, config);
274 }
275
276 return config;
277}
278
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400279sk_sp<SkData> SkiaGLRenderEngine::SkSLCacheMonitor::load(const SkData& key) {
280 // This "cache" does not actually cache anything. It just allows us to
281 // monitor Skia's internal cache. So this method always returns null.
282 return nullptr;
283}
284
285void SkiaGLRenderEngine::SkSLCacheMonitor::store(const SkData& key, const SkData& data,
286 const SkString& description) {
287 mShadersCachedSinceLastCall++;
288}
289
290void SkiaGLRenderEngine::assertShadersCompiled(int numShaders) {
291 const int cached = mSkSLCacheMonitor.shadersCachedSinceLastCall();
292 LOG_ALWAYS_FATAL_IF(cached != numShaders, "Attempted to cache %i shaders; cached %i",
293 numShaders, cached);
294}
295
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400296int SkiaGLRenderEngine::reportShadersCompiled() {
297 return mSkSLCacheMonitor.shadersCachedSinceLastCall();
298}
299
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700300SkiaGLRenderEngine::SkiaGLRenderEngine(const RenderEngineCreationArgs& args, EGLDisplay display,
Lucas Dupind508e472020-11-04 04:32:06 +0000301 EGLContext ctxt, EGLSurface placeholder,
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700302 EGLContext protectedContext, EGLSurface protectedPlaceholder)
Alec Mouri0d995102021-02-24 16:53:38 -0800303 : SkiaRenderEngine(args.renderEngineType),
304 mEGLDisplay(display),
John Reck67b1e2b2020-08-26 13:17:24 -0700305 mEGLContext(ctxt),
306 mPlaceholderSurface(placeholder),
307 mProtectedEGLContext(protectedContext),
Alec Mourib5777452020-09-28 11:32:42 -0700308 mProtectedPlaceholderSurface(protectedPlaceholder),
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400309 mDefaultPixelFormat(static_cast<PixelFormat>(args.pixelFormat)),
Alec Mouri0d995102021-02-24 16:53:38 -0800310 mUseColorManagement(args.useColorManagement) {
John Reck67b1e2b2020-08-26 13:17:24 -0700311 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
312 LOG_ALWAYS_FATAL_IF(!glInterface.get());
313
314 GrContextOptions options;
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -0400315 options.fDisableDriverCorrectnessWorkarounds = true;
John Reck67b1e2b2020-08-26 13:17:24 -0700316 options.fDisableDistanceFieldPaths = true;
Leon Scroggins III9f3072c2021-03-22 10:42:47 -0400317 options.fPersistentCache = &mSkSLCacheMonitor;
Lucas Dupind508e472020-11-04 04:32:06 +0000318 mGrContext = GrDirectContext::MakeGL(glInterface, options);
319 if (useProtectedContext(true)) {
320 mProtectedGrContext = GrDirectContext::MakeGL(glInterface, options);
321 useProtectedContext(false);
322 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700323
324 if (args.supportsBackgroundBlur) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500325 ALOGD("Background Blurs Enabled");
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700326 mBlurFilter = new BlurFilter();
327 }
Alec Mouric0aae732021-01-12 13:32:18 -0800328 mCapture = std::make_unique<SkiaCapture>();
329}
330
331SkiaGLRenderEngine::~SkiaGLRenderEngine() {
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100332 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800333 if (mBlurFilter) {
334 delete mBlurFilter;
335 }
336
337 mCapture = nullptr;
338
339 mGrContext->flushAndSubmit(true);
340 mGrContext->abandonContext();
341
342 if (mProtectedGrContext) {
343 mProtectedGrContext->flushAndSubmit(true);
344 mProtectedGrContext->abandonContext();
345 }
346
347 if (mPlaceholderSurface != EGL_NO_SURFACE) {
348 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
349 }
350 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
351 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
352 }
353 if (mEGLContext != EGL_NO_CONTEXT) {
354 eglDestroyContext(mEGLDisplay, mEGLContext);
355 }
356 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
357 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
358 }
359 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
360 eglTerminate(mEGLDisplay);
361 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700362}
363
Lucas Dupind508e472020-11-04 04:32:06 +0000364bool SkiaGLRenderEngine::supportsProtectedContent() const {
365 return mProtectedEGLContext != EGL_NO_CONTEXT;
366}
367
368bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
369 if (useProtectedContext == mInProtectedContext) {
370 return true;
371 }
Alec Mourif6a07812021-02-11 21:07:55 -0800372 if (useProtectedContext && !supportsProtectedContent()) {
Lucas Dupind508e472020-11-04 04:32:06 +0000373 return false;
374 }
375 const EGLSurface surface =
376 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
377 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
378 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800379
Lucas Dupind508e472020-11-04 04:32:06 +0000380 if (success) {
381 mInProtectedContext = useProtectedContext;
382 }
383 return success;
384}
385
John Reck67b1e2b2020-08-26 13:17:24 -0700386base::unique_fd SkiaGLRenderEngine::flush() {
387 ATRACE_CALL();
388 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
389 return base::unique_fd();
390 }
391
392 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
393 if (sync == EGL_NO_SYNC_KHR) {
394 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
395 return base::unique_fd();
396 }
397
398 // native fence fd will not be populated until flush() is done.
399 glFlush();
400
401 // get the fence fd
402 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
403 eglDestroySyncKHR(mEGLDisplay, sync);
404 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
405 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
406 }
407
408 return fenceFd;
409}
410
411bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
412 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
413 !gl::GLExtensions::getInstance().hasWaitSync()) {
414 return false;
415 }
416
417 // release the fd and transfer the ownership to EGLSync
418 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
419 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
420 if (sync == EGL_NO_SYNC_KHR) {
421 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
422 return false;
423 }
424
425 // XXX: The spec draft is inconsistent as to whether this should return an
426 // EGLint or void. Ignore the return value for now, as it's not strictly
427 // needed.
428 eglWaitSyncKHR(mEGLDisplay, sync, 0);
429 EGLint error = eglGetError();
430 eglDestroySyncKHR(mEGLDisplay, sync);
431 if (error != EGL_SUCCESS) {
432 ALOGE("failed to wait for EGL native fence sync: %#x", error);
433 return false;
434 }
435
436 return true;
437}
438
Alec Mouri678245d2020-09-30 16:58:23 -0700439static float toDegrees(uint32_t transform) {
440 switch (transform) {
441 case ui::Transform::ROT_90:
442 return 90.0;
443 case ui::Transform::ROT_180:
444 return 180.0;
445 case ui::Transform::ROT_270:
446 return 270.0;
447 default:
448 return 0.0;
449 }
450}
451
Alec Mourib34f0b72020-10-02 13:18:34 -0700452static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
453 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
454 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
455 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
456 matrix[3][3], 0);
457}
458
Alec Mouri029d1952020-10-12 10:37:08 -0700459static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
460 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
461 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
462
463 // Treat unsupported dataspaces as srgb
464 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
465 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
466 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
467 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
468 }
469
470 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
471 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
472 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
473 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
474 }
475
476 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
477 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
478 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
479 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
480
481 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
482 sourceTransfer != destTransfer;
483}
484
Alec Mouri2daef3c2021-04-02 16:29:27 -0700485void SkiaGLRenderEngine::mapExternalTextureBuffer(const sp<GraphicBuffer>& buffer,
486 bool isRenderable) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800487 // Only run this if RE is running on its own thread. This way the access to GL
488 // operations is guaranteed to be happening on the same thread.
489 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
490 return;
491 }
492 ATRACE_CALL();
493
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400494 // We need to switch the currently bound context if the buffer is protected but the current
495 // context is not. The current state must then be restored after the buffer is cached.
496 const bool protectedContextState = mInProtectedContext;
497 if (!useProtectedContext(protectedContextState ||
498 (buffer->getUsage() & GRALLOC_USAGE_PROTECTED))) {
499 ALOGE("Attempting to cache a buffer into a different context than what is currently bound");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800500 return;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400501 }
502
503 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
504 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
505
506 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouri2daef3c2021-04-02 16:29:27 -0700507 mGraphicBufferExternalRefs[buffer->getId()]++;
508
509 if (const auto& iter = cache.find(buffer->getId()); iter == cache.end()) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800510 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Alec Mouri2daef3c2021-04-02 16:29:27 -0700511 std::make_shared<AutoBackendTexture::LocalRef>(
512 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(),
513 isRenderable));
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400514 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800515 }
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400516 // restore the original state of the protected context if necessary
517 useProtectedContext(protectedContextState);
Ana Krulecdfec8f52021-01-13 12:51:47 -0800518}
519
Alec Mouri2daef3c2021-04-02 16:29:27 -0700520void SkiaGLRenderEngine::unmapExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800521 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700522 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouri2daef3c2021-04-02 16:29:27 -0700523 if (const auto& iter = mGraphicBufferExternalRefs.find(buffer->getId());
524 iter != mGraphicBufferExternalRefs.end()) {
525 if (iter->second == 0) {
526 ALOGW("Attempted to unmap GraphicBuffer <id: %" PRId64
527 "> from RenderEngine texture, but the "
528 "ref count was already zero!",
529 buffer->getId());
530 mGraphicBufferExternalRefs.erase(buffer->getId());
531 return;
532 }
533
534 iter->second--;
535
536 if (iter->second == 0) {
537 mTextureCache.erase(buffer->getId());
538 mProtectedTextureCache.erase(buffer->getId());
539 mGraphicBufferExternalRefs.erase(buffer->getId());
540 }
541 }
John Reck67b1e2b2020-08-26 13:17:24 -0700542}
543
Ana Krulec47814212021-01-06 19:00:10 -0800544sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
545 const LayerSettings* layer,
546 const DisplaySettings& display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500547 bool undoPremultipliedAlpha,
548 bool requiresLinearEffect) {
John Reckcdb4ed72021-02-04 13:39:33 -0500549 if (layer->stretchEffect.hasEffect()) {
550 // TODO: Implement
551 }
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500552 if (requiresLinearEffect) {
553 const ui::Dataspace inputDataspace =
554 mUseColorManagement ? layer->sourceDataspace : ui::Dataspace::UNKNOWN;
555 const ui::Dataspace outputDataspace =
556 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
557
558 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
559 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800560 .undoPremultipliedAlpha = undoPremultipliedAlpha};
561
562 auto effectIter = mRuntimeEffects.find(effect);
563 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
564 if (effectIter == mRuntimeEffects.end()) {
565 runtimeEffect = buildRuntimeEffect(effect);
566 mRuntimeEffects.insert({effect, runtimeEffect});
567 } else {
568 runtimeEffect = effectIter->second;
569 }
570 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
571 display.maxLuminance,
572 layer->source.buffer.maxMasteringLuminance,
573 layer->source.buffer.maxContentLuminance);
574 }
575 return shader;
576}
577
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500578void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500579 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500580 // Record display settings when capture is running.
581 std::stringstream displaySettings;
582 PrintTo(display, &displaySettings);
583 // Store the DisplaySettings in additional information.
584 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
585 SkData::MakeWithCString(displaySettings.str().c_str()));
586 }
587
588 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
589 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
590 // displays might have different scaling when compared to the physical screen.
591
592 canvas->clipRect(getSkRect(display.physicalDisplay));
593 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
594
595 const auto clipWidth = display.clip.width();
596 const auto clipHeight = display.clip.height();
597 auto rotatedClipWidth = clipWidth;
598 auto rotatedClipHeight = clipHeight;
599 // Scale is contingent on the rotation result.
600 if (display.orientation & ui::Transform::ROT_90) {
601 std::swap(rotatedClipWidth, rotatedClipHeight);
602 }
603 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
604 static_cast<SkScalar>(rotatedClipWidth);
605 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
606 static_cast<SkScalar>(rotatedClipHeight);
607 canvas->scale(scaleX, scaleY);
608
609 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
610 // back so that the top left corner of the clip is at (0, 0).
611 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
612 canvas->rotate(toDegrees(display.orientation));
613 canvas->translate(-clipWidth / 2, -clipHeight / 2);
614 canvas->translate(-display.clip.left, -display.clip.top);
615}
616
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500617class AutoSaveRestore {
618public:
619 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
620 ~AutoSaveRestore() { restore(); }
621 void replace(SkCanvas* canvas) {
622 mCanvas = canvas;
623 mSaveCount = canvas->save();
624 }
625 void restore() {
626 if (mCanvas) {
627 mCanvas->restoreToCount(mSaveCount);
628 mCanvas = nullptr;
629 }
630 }
631
632private:
633 SkCanvas* mCanvas;
634 int mSaveCount;
635};
636
John Reck67b1e2b2020-08-26 13:17:24 -0700637status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
638 const std::vector<const LayerSettings*>& layers,
Alec Mouri2daef3c2021-04-02 16:29:27 -0700639 const std::shared_ptr<ExternalTexture>& buffer,
640 const bool /*useFramebufferCache*/,
John Reck67b1e2b2020-08-26 13:17:24 -0700641 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
642 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800643
John Reck67b1e2b2020-08-26 13:17:24 -0700644 std::lock_guard<std::mutex> lock(mRenderingMutex);
645 if (layers.empty()) {
646 ALOGV("Drawing empty layer stack");
647 return NO_ERROR;
648 }
649
650 if (bufferFence.get() >= 0) {
651 // Duplicate the fence for passing to waitFence.
652 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
653 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
654 ATRACE_NAME("Waiting before draw");
655 sync_wait(bufferFence.get(), -1);
656 }
657 }
658 if (buffer == nullptr) {
659 ALOGE("No output buffer provided. Aborting GPU composition.");
660 return BAD_VALUE;
661 }
662
Alec Mouri2daef3c2021-04-02 16:29:27 -0700663 validateOutputBufferUsage(buffer->getBuffer());
Ady Abraham193426d2021-02-18 14:01:53 -0800664
Lucas Dupind508e472020-11-04 04:32:06 +0000665 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800666 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
John Reck67b1e2b2020-08-26 13:17:24 -0700667
Alec Mouri2daef3c2021-04-02 16:29:27 -0700668 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef;
669 if (const auto& it = cache.find(buffer->getBuffer()->getId()); it != cache.end()) {
670 surfaceTextureRef = it->second;
671 } else {
672 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>(
673 new AutoBackendTexture(grContext.get(), buffer->getBuffer()->toAHardwareBuffer(),
674 true));
John Reck67b1e2b2020-08-26 13:17:24 -0700675 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800676
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500677 const ui::Dataspace dstDataspace =
678 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500679 sk_sp<SkSurface> dstSurface =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500680 surfaceTextureRef->getTexture()->getOrCreateSurface(dstDataspace, grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700681
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500682 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
683 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800684 ALOGE("Cannot acquire canvas from Skia.");
685 return BAD_VALUE;
686 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500687
688 // Find if any layers have requested blur, we'll use that info to decide when to render to an
689 // offscreen buffer and when to render to the native buffer.
690 sk_sp<SkSurface> activeSurface(dstSurface);
691 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500692 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500693 const LayerSettings* blurCompositionLayer = nullptr;
694 if (mBlurFilter) {
695 bool requiresCompositionLayer = false;
696 for (const auto& layer : layers) {
Derek Sollenberger3134ec32021-02-12 11:26:23 -0500697 if (layer->backgroundBlurRadius > 0 &&
698 layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500699 requiresCompositionLayer = true;
700 }
701 for (auto region : layer->blurRegions) {
702 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
703 requiresCompositionLayer = true;
704 }
705 }
706 if (requiresCompositionLayer) {
707 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500708 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500709 blurCompositionLayer = layer;
710 break;
711 }
712 }
713 }
714
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500715 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700716 // Clear the entire canvas with a transparent black to prevent ghost images.
717 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500718 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800719
720 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
721 // view is still on-screen. The clear region could be re-specified as a black color layer,
722 // however.
723 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500724 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800725 size_t numRects = 0;
726 Rect const* rects = display.clearRegion.getArray(&numRects);
727 SkIRect skRects[numRects];
728 for (int i = 0; i < numRects; ++i) {
729 skRects[i] =
730 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
731 }
732 SkRegion clearRegion;
733 SkPaint paint;
734 sk_sp<SkShader> shader =
735 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500736 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800737 paint.setShader(shader);
738 clearRegion.setRects(skRects, numRects);
739 canvas->drawRegion(clearRegion, paint);
740 }
741
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500742 // setup color filter if necessary
743 sk_sp<SkColorFilter> displayColorTransform;
744 if (display.colorTransform != mat4()) {
745 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
746 }
747
John Reck67b1e2b2020-08-26 13:17:24 -0700748 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500749 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100750
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400751 if (kPrintLayerSettings) {
752 std::stringstream ls;
753 PrintTo(*layer, &ls);
754 auto debugs = ls.str();
755 int pos = 0;
756 while (pos < debugs.size()) {
757 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
758 pos += 1000;
759 }
760 }
761
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500762 sk_sp<SkImage> blurInput;
763 if (blurCompositionLayer == layer) {
764 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
765 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
766
767 // save a snapshot of the activeSurface to use as input to the blur shaders
768 blurInput = activeSurface->makeImageSnapshot();
769
770 // TODO we could skip this step if we know the blur will cover the entire image
771 // blit the offscreen framebuffer into the destination AHB
772 SkPaint paint;
773 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500774 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
775 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
776 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
777 String8::format("SurfaceID|%" PRId64, id).c_str(),
778 nullptr);
779 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
780 } else {
781 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
782 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500783
784 // assign dstCanvas to canvas and ensure that the canvas state is up to date
785 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500786 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500787 initCanvas(canvas, display);
788
789 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
790 dstSurface->getCanvas()->getSaveCount());
791 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
792 dstSurface->getCanvas()->getTotalMatrix());
793
794 // assign dstSurface to activeSurface
795 activeSurface = dstSurface;
796 }
797
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500798 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500799 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800800 // Record the name of the layer if the capture is running.
801 std::stringstream layerSettings;
802 PrintTo(*layer, &layerSettings);
803 // Store the LayerSettings in additional information.
804 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
805 SkData::MakeWithCString(layerSettings.str().c_str()));
806 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100807 // Layers have a local transform that should be applied to them
808 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100809
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500810 const auto bounds = getSkRect(layer->geometry.boundaries);
811 if (mBlurFilter && layerHasBlur(layer)) {
812 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
813
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500814 // if multiple layers have blur, then we need to take a snapshot now because
815 // only the lowest layer will have blurImage populated earlier
816 if (!blurInput) {
817 blurInput = activeSurface->makeImageSnapshot();
818 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500819 // rect to be blurred in the coordinate space of blurInput
820 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds);
821
Lucas Dupinc3800b82020-10-02 16:24:48 -0700822 if (layer->backgroundBlurRadius > 0) {
823 ATRACE_NAME("BackgroundBlur");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500824 auto blurredImage =
825 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
826 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100827
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500828 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
829
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500830 mBlurFilter->drawBlurRegion(canvas, getBlurRegion(layer), blurRect, blurredImage,
831 blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700832 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500833 for (auto region : layer->blurRegions) {
Galia Peychevaa600b972021-02-19 15:50:12 +0100834 if (cachedBlurs[region.blurRadius] == nullptr) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700835 ATRACE_NAME("BlurRegion");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500836 cachedBlurs[region.blurRadius] =
837 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
838 blurRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700839 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500840
841 mBlurFilter->drawBlurRegion(canvas, region, blurRect,
842 cachedBlurs[region.blurRadius], blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700843 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700844 }
845
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500846 // Shadows are assumed to live only on their own layer - it's not valid
847 // to draw the boundary rectangles when there is already a caster shadow
848 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
849 // composition - using a well-defined invalid color is long-term less error-prone.
850 if (layer->shadow.length > 0) {
851 const auto rect = layer->geometry.roundedCornersRadius > 0
852 ? getSkRect(layer->geometry.roundedCornersCrop)
853 : bounds;
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400854 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
855 LOG_ALWAYS_FATAL_IF(layer->disableBlending, "Cannot disableBlending with a shadow");
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500856 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
857 continue;
858 }
859
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500860 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
861 (mUseColorManagement &&
862 needsToneMapping(layer->sourceDataspace, display.outputDataspace));
863
864 // quick abort from drawing the remaining portion of the layer
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400865 if (layer->alpha == 0 && !requiresLinearEffect && !layer->disableBlending &&
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500866 (!displayColorTransform || displayColorTransform->isAlphaUnchanged())) {
867 continue;
868 }
869
870 // If we need to map to linear space or color management is disabled, then mark the source
871 // image with the same colorspace as the destination surface so that Skia's color
872 // management is a no-op.
873 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
874 ? dstDataspace
875 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800876
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500877 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700878 if (layer->source.buffer.buffer) {
879 ATRACE_NAME("DrawImage");
Alec Mouri2daef3c2021-04-02 16:29:27 -0700880 validateInputBufferUsage(layer->source.buffer.buffer->getBuffer());
John Reck67b1e2b2020-08-26 13:17:24 -0700881 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800882 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouri2daef3c2021-04-02 16:29:27 -0700883
884 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
885 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800886 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700887 } else {
Alec Mouri2daef3c2021-04-02 16:29:27 -0700888 // If we didn't find the image in the cache, then create a local ref but don't cache
889 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
890 // we didn't find anything in the cache then we intentionally did not cache this
891 // buffer's resources.
892 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>(
893 new AutoBackendTexture(grContext.get(),
894 item.buffer->getBuffer()->toAHardwareBuffer(),
895 false));
John Reck67b1e2b2020-08-26 13:17:24 -0700896 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800897
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800898 sk_sp<SkImage> image =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500899 imageTextureRef->getTexture()->makeImage(layerDataspace,
Alec Mouric0aae732021-01-12 13:32:18 -0800900 item.usePremultipliedAlpha
901 ? kPremul_SkAlphaType
902 : kUnpremul_SkAlphaType,
903 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700904
905 auto texMatrix = getSkM44(item.textureTransform).asM33();
906 // textureTansform was intended to be passed directly into a shader, so when
907 // building the total matrix with the textureTransform we need to first
908 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500909 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800910 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700911
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800912 SkMatrix matrix;
913 if (!texMatrix.invert(&matrix)) {
914 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700915 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800916 // The shader does not respect the translation, so we add it to the texture
917 // transform for the SkImage. This will make sure that the correct layer contents
918 // are drawn in the correct part of the screen.
919 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700920
Ana Krulecb7b28b22020-11-23 14:48:58 -0800921 sk_sp<SkShader> shader;
922
923 if (layer->source.buffer.useTextureFiltering) {
924 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
925 SkSamplingOptions(
926 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
927 &matrix);
928 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500929 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800930 }
Alec Mouri029d1952020-10-12 10:37:08 -0700931
Alec Mouric0aae732021-01-12 13:32:18 -0800932 // Handle opaque images - it's a little nonstandard how we do this.
933 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
934 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
935 // The important language is that when isOpaque is set, opacity is not sampled from the
936 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
937 // here's the conundrum:
938 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
939 // as an internal hint - composition is undefined when there are alpha bits present.
940 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
941 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
942 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
943 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
944 // of a hack anyways.
945 // 3. We can't change the blendmode to src, because while this satisfies the requirement
946 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
947 // because src always clobbers the destination content.
948 //
949 // So, what we do here instead is an additive blend mode where we compose the input
950 // image with a solid black. This might need to be reassess if this does not support
951 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
952 if (item.isOpaque) {
953 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
954 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500955 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -0800956 }
957
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500958 paint.setShader(createRuntimeEffectShader(shader, layer, display,
959 !item.isOpaque && item.usePremultipliedAlpha,
960 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -0800961 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700962 } else {
963 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700964 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800965 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
966 .fG = color.g,
967 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800968 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500969 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800970 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500971 /* undoPremultipliedAlpha */ false,
972 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -0700973 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700974
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400975 if (layer->disableBlending) {
976 paint.setBlendMode(SkBlendMode::kSrc);
977 }
978
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500979 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -0700980
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500981 if (layer->geometry.roundedCornersRadius > 0) {
982 paint.setAntiAlias(true);
983 canvas->drawRRect(getRoundedRect(layer), paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800984 } else {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500985 canvas->drawRect(bounds, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700986 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400987 if (kFlushAfterEveryLayer) {
988 ATRACE_NAME("flush surface");
989 activeSurface->flush();
990 }
John Reck67b1e2b2020-08-26 13:17:24 -0700991 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500992 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800993 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700994 {
995 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500996 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
997 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -0700998 }
999
1000 if (drawFence != nullptr) {
1001 *drawFence = flush();
1002 }
1003
1004 // If flush failed or we don't support native fences, we need to force the
1005 // gl command stream to be executed.
1006 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
1007 if (requireSync) {
1008 ATRACE_BEGIN("Submit(sync=true)");
1009 } else {
1010 ATRACE_BEGIN("Submit(sync=false)");
1011 }
Lucas Dupind508e472020-11-04 04:32:06 +00001012 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001013 ATRACE_END();
1014 if (!success) {
1015 ALOGE("Failed to flush RenderEngine commands");
1016 // Chances are, something illegal happened (either the caller passed
1017 // us bad parameters, or we messed up our shader generation).
1018 return INVALID_OPERATION;
1019 }
1020
1021 // checkErrors();
1022 return NO_ERROR;
1023}
1024
Lucas Dupin3f11e922020-09-22 17:31:04 -07001025inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1026 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1027}
1028
1029inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1030 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1031}
1032
Lucas Dupin21f348e2020-09-16 17:31:26 -07001033inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -08001034 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001035 const auto cornerRadius = layer->geometry.roundedCornersRadius;
1036 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
1037}
1038
Galia Peycheva80116e52020-11-06 11:57:25 +01001039inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
1040 const auto rect = getSkRect(layer->geometry.boundaries);
1041 const auto cornersRadius = layer->geometry.roundedCornersRadius;
1042 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
1043 .cornerRadiusTL = cornersRadius,
1044 .cornerRadiusTR = cornersRadius,
1045 .cornerRadiusBL = cornersRadius,
1046 .cornerRadiusBR = cornersRadius,
1047 .alpha = 1,
1048 .left = static_cast<int>(rect.fLeft),
1049 .top = static_cast<int>(rect.fTop),
1050 .right = static_cast<int>(rect.fRight),
1051 .bottom = static_cast<int>(rect.fBottom)};
1052}
1053
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001054inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
1055 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
1056}
1057
Lucas Dupin3f11e922020-09-22 17:31:04 -07001058inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1059 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1060}
1061
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001062inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1063 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1064 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1065 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1066 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1067}
1068
Lucas Dupin3f11e922020-09-22 17:31:04 -07001069inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1070 return SkPoint3::Make(vector.x, vector.y, vector.z);
1071}
1072
John Reck67b1e2b2020-08-26 13:17:24 -07001073size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1074 return mGrContext->maxTextureSize();
1075}
1076
1077size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1078 return mGrContext->maxRenderTargetSize();
1079}
1080
Lucas Dupin3f11e922020-09-22 17:31:04 -07001081void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
1082 const ShadowSettings& settings) {
1083 ATRACE_CALL();
1084 const float casterZ = settings.length / 2.0f;
1085 const auto shadowShape = cornerRadius > 0
1086 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
1087 : SkPath::Rect(casterRect);
1088 const auto flags =
1089 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1090
1091 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
1092 getSkPoint3(settings.lightPos), settings.lightRadius,
1093 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1094 flags);
1095}
1096
John Reck67b1e2b2020-08-26 13:17:24 -07001097EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001098 EGLContext shareContext,
1099 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001100 Protection protection) {
1101 EGLint renderableType = 0;
1102 if (config == EGL_NO_CONFIG_KHR) {
1103 renderableType = EGL_OPENGL_ES3_BIT;
1104 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1105 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1106 }
1107 EGLint contextClientVersion = 0;
1108 if (renderableType & EGL_OPENGL_ES3_BIT) {
1109 contextClientVersion = 3;
1110 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1111 contextClientVersion = 2;
1112 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1113 contextClientVersion = 1;
1114 } else {
1115 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1116 }
1117
1118 std::vector<EGLint> contextAttributes;
1119 contextAttributes.reserve(7);
1120 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1121 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001122 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001123 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001124 switch (*contextPriority) {
1125 case ContextPriority::REALTIME:
1126 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1127 break;
1128 case ContextPriority::MEDIUM:
1129 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1130 break;
1131 case ContextPriority::LOW:
1132 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1133 break;
1134 case ContextPriority::HIGH:
1135 default:
1136 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1137 break;
1138 }
John Reck67b1e2b2020-08-26 13:17:24 -07001139 }
1140 if (protection == Protection::PROTECTED) {
1141 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1142 contextAttributes.push_back(EGL_TRUE);
1143 }
1144 contextAttributes.push_back(EGL_NONE);
1145
1146 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1147
1148 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1149 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1150 // EGL_NO_CONTEXT so that we can abort.
1151 if (config != EGL_NO_CONFIG_KHR) {
1152 return context;
1153 }
1154 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1155 // should try to fall back to GLES 2.
1156 contextAttributes[1] = 2;
1157 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1158 }
1159
1160 return context;
1161}
1162
Alec Mourid6f09462020-12-07 11:18:17 -08001163std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1164 const RenderEngineCreationArgs& args) {
1165 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1166 return std::nullopt;
1167 }
1168
1169 switch (args.contextPriority) {
1170 case RenderEngine::ContextPriority::REALTIME:
1171 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1172 return RenderEngine::ContextPriority::REALTIME;
1173 } else {
1174 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1175 return RenderEngine::ContextPriority::HIGH;
1176 }
1177 case RenderEngine::ContextPriority::HIGH:
1178 case RenderEngine::ContextPriority::MEDIUM:
1179 case RenderEngine::ContextPriority::LOW:
1180 return args.contextPriority;
1181 default:
1182 return std::nullopt;
1183 }
1184}
1185
John Reck67b1e2b2020-08-26 13:17:24 -07001186EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1187 EGLConfig config, int hwcFormat,
1188 Protection protection) {
1189 EGLConfig placeholderConfig = config;
1190 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1191 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1192 }
1193 std::vector<EGLint> attributes;
1194 attributes.reserve(7);
1195 attributes.push_back(EGL_WIDTH);
1196 attributes.push_back(1);
1197 attributes.push_back(EGL_HEIGHT);
1198 attributes.push_back(1);
1199 if (protection == Protection::PROTECTED) {
1200 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1201 attributes.push_back(EGL_TRUE);
1202 }
1203 attributes.push_back(EGL_NONE);
1204
1205 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1206}
1207
Alec Mourid6f09462020-12-07 11:18:17 -08001208int SkiaGLRenderEngine::getContextPriority() {
1209 int value;
1210 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1211 return value;
1212}
1213
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001214void SkiaGLRenderEngine::onPrimaryDisplaySizeChanged(ui::Size size) {
1215 // This cache multiplier was selected based on review of cache sizes relative
1216 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1217 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1218 // conservative default based on that analysis.
1219 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1220 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1221
1222 // start by resizing the current context
1223 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
1224 grContext->setResourceCacheLimit(maxResourceBytes);
1225
1226 // if it is possible to switch contexts then we will resize the other context
1227 if (useProtectedContext(!mInProtectedContext)) {
1228 grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
1229 grContext->setResourceCacheLimit(maxResourceBytes);
1230 // reset back to the initial context that was active when this method was called
1231 useProtectedContext(!mInProtectedContext);
1232 }
1233}
1234
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001235void SkiaGLRenderEngine::dump(std::string& result) {
1236 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1237
1238 StringAppendF(&result, "\n ------------RE-----------------\n");
1239 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1240 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1241 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1242 extensions.getVersion());
1243 StringAppendF(&result, "%s\n", extensions.getExtensions());
1244 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1245 supportsProtectedContent());
1246 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001247 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1248 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001249
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001250 std::vector<ResourcePair> cpuResourceMap = {
1251 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1252 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1253 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1254 {"skia/sk_resource_cache/tessellated", "Shadows"},
1255 {"skia", "Other"},
1256 };
1257 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1258 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1259 StringAppendF(&result, "Skia CPU Caches: ");
1260 cpuReporter.logTotals(result);
1261 cpuReporter.logOutput(result);
1262
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001263 {
1264 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001265
1266 std::vector<ResourcePair> gpuResourceMap = {
1267 {"texture_renderbuffer", "Texture/RenderBuffer"},
1268 {"texture", "Texture"},
1269 {"gr_text_blob_cache", "Text"},
1270 {"skia", "Other"},
1271 };
1272 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1273 mGrContext->dumpMemoryStatistics(&gpuReporter);
1274 StringAppendF(&result, "Skia's GPU Caches: ");
1275 gpuReporter.logTotals(result);
1276 gpuReporter.logOutput(result);
1277 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1278 gpuReporter.logOutput(result, true);
1279
Alec Mouri2daef3c2021-04-02 16:29:27 -07001280 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1281 mGraphicBufferExternalRefs.size());
1282 StringAppendF(&result, "Dumping buffer ids...\n");
1283 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1284 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1285 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001286 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1287 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001288 StringAppendF(&result, "Dumping buffer ids...\n");
1289 // TODO(178539829): It would be nice to know which layer these are coming from and what
1290 // the texture sizes are.
1291 for (const auto& [id, unused] : mTextureCache) {
1292 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1293 }
1294 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001295
1296 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001297 if (mProtectedGrContext) {
1298 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1299 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001300 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1301 gpuProtectedReporter.logTotals(result);
1302 gpuProtectedReporter.logOutput(result);
1303 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1304 gpuProtectedReporter.logOutput(result, true);
1305
1306 StringAppendF(&result, "RenderEngine protected AHB/BackendTexture cache size: %zu\n",
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001307 mProtectedTextureCache.size());
1308 StringAppendF(&result, "Dumping buffer ids...\n");
1309 for (const auto& [id, unused] : mProtectedTextureCache) {
1310 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1311 }
1312 StringAppendF(&result, "\n");
1313 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1314 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1315 StringAppendF(&result, "- inputDataspace: %s\n",
1316 dataspaceDetails(
1317 static_cast<android_dataspace>(linearEffect.inputDataspace))
1318 .c_str());
1319 StringAppendF(&result, "- outputDataspace: %s\n",
1320 dataspaceDetails(
1321 static_cast<android_dataspace>(linearEffect.outputDataspace))
1322 .c_str());
1323 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1324 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1325 }
1326 }
1327 StringAppendF(&result, "\n");
1328}
1329
John Reck67b1e2b2020-08-26 13:17:24 -07001330} // namespace skia
1331} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001332} // namespace android