blob: 0a84754d2250798b9ec3f2017603134effe1828e [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 Mouria90a5702021-04-16 16:36:21 +0000485void 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 Mouria90a5702021-04-16 16:36:21 +0000507 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 =
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400511 std::make_shared<AutoBackendTexture::LocalRef>(grContext.get(),
512 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 Mouria90a5702021-04-16 16:36:21 +0000520void 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 Mouria90a5702021-04-16 16:36:21 +0000523 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 Mouria90a5702021-04-16 16:36:21 +0000639 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 Mouria90a5702021-04-16 16:36:21 +0000663 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 Mouria90a5702021-04-16 16:36:21 +0000668 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 {
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400672 surfaceTextureRef =
673 std::make_shared<AutoBackendTexture::LocalRef>(grContext.get(),
674 buffer->getBuffer()
675 ->toAHardwareBuffer(),
676 true);
John Reck67b1e2b2020-08-26 13:17:24 -0700677 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800678
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500679 const ui::Dataspace dstDataspace =
680 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500681 sk_sp<SkSurface> dstSurface =
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400682 surfaceTextureRef->getOrCreateSurface(dstDataspace, grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700683
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500684 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
685 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800686 ALOGE("Cannot acquire canvas from Skia.");
687 return BAD_VALUE;
688 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500689
690 // Find if any layers have requested blur, we'll use that info to decide when to render to an
691 // offscreen buffer and when to render to the native buffer.
692 sk_sp<SkSurface> activeSurface(dstSurface);
693 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500694 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500695 const LayerSettings* blurCompositionLayer = nullptr;
696 if (mBlurFilter) {
697 bool requiresCompositionLayer = false;
698 for (const auto& layer : layers) {
Derek Sollenberger3134ec32021-02-12 11:26:23 -0500699 if (layer->backgroundBlurRadius > 0 &&
700 layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500701 requiresCompositionLayer = true;
702 }
703 for (auto region : layer->blurRegions) {
704 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
705 requiresCompositionLayer = true;
706 }
707 }
708 if (requiresCompositionLayer) {
709 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500710 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500711 blurCompositionLayer = layer;
712 break;
713 }
714 }
715 }
716
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500717 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700718 // Clear the entire canvas with a transparent black to prevent ghost images.
719 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500720 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800721
722 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
723 // view is still on-screen. The clear region could be re-specified as a black color layer,
724 // however.
725 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500726 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800727 size_t numRects = 0;
728 Rect const* rects = display.clearRegion.getArray(&numRects);
729 SkIRect skRects[numRects];
730 for (int i = 0; i < numRects; ++i) {
731 skRects[i] =
732 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
733 }
734 SkRegion clearRegion;
735 SkPaint paint;
736 sk_sp<SkShader> shader =
737 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500738 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800739 paint.setShader(shader);
740 clearRegion.setRects(skRects, numRects);
741 canvas->drawRegion(clearRegion, paint);
742 }
743
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500744 // setup color filter if necessary
745 sk_sp<SkColorFilter> displayColorTransform;
746 if (display.colorTransform != mat4()) {
747 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
748 }
749
John Reck67b1e2b2020-08-26 13:17:24 -0700750 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500751 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100752
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400753 if (kPrintLayerSettings) {
754 std::stringstream ls;
755 PrintTo(*layer, &ls);
756 auto debugs = ls.str();
757 int pos = 0;
758 while (pos < debugs.size()) {
759 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
760 pos += 1000;
761 }
762 }
763
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500764 sk_sp<SkImage> blurInput;
765 if (blurCompositionLayer == layer) {
766 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
767 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
768
769 // save a snapshot of the activeSurface to use as input to the blur shaders
770 blurInput = activeSurface->makeImageSnapshot();
771
772 // TODO we could skip this step if we know the blur will cover the entire image
773 // blit the offscreen framebuffer into the destination AHB
774 SkPaint paint;
775 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500776 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
777 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
778 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
779 String8::format("SurfaceID|%" PRId64, id).c_str(),
780 nullptr);
781 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
782 } else {
783 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
784 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500785
786 // assign dstCanvas to canvas and ensure that the canvas state is up to date
787 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500788 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500789 initCanvas(canvas, display);
790
791 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
792 dstSurface->getCanvas()->getSaveCount());
793 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
794 dstSurface->getCanvas()->getTotalMatrix());
795
796 // assign dstSurface to activeSurface
797 activeSurface = dstSurface;
798 }
799
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500800 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500801 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800802 // Record the name of the layer if the capture is running.
803 std::stringstream layerSettings;
804 PrintTo(*layer, &layerSettings);
805 // Store the LayerSettings in additional information.
806 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
807 SkData::MakeWithCString(layerSettings.str().c_str()));
808 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100809 // Layers have a local transform that should be applied to them
810 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100811
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500812 const auto bounds = getSkRect(layer->geometry.boundaries);
813 if (mBlurFilter && layerHasBlur(layer)) {
814 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
815
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500816 // if multiple layers have blur, then we need to take a snapshot now because
817 // only the lowest layer will have blurImage populated earlier
818 if (!blurInput) {
819 blurInput = activeSurface->makeImageSnapshot();
820 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500821 // rect to be blurred in the coordinate space of blurInput
822 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds);
823
Lucas Dupinc3800b82020-10-02 16:24:48 -0700824 if (layer->backgroundBlurRadius > 0) {
825 ATRACE_NAME("BackgroundBlur");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500826 auto blurredImage =
827 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
828 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100829
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500830 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
831
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500832 mBlurFilter->drawBlurRegion(canvas, getBlurRegion(layer), blurRect, blurredImage,
833 blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700834 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500835 for (auto region : layer->blurRegions) {
Galia Peychevaa600b972021-02-19 15:50:12 +0100836 if (cachedBlurs[region.blurRadius] == nullptr) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700837 ATRACE_NAME("BlurRegion");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500838 cachedBlurs[region.blurRadius] =
839 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
840 blurRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700841 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500842
843 mBlurFilter->drawBlurRegion(canvas, region, blurRect,
844 cachedBlurs[region.blurRadius], blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700845 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700846 }
847
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500848 // Shadows are assumed to live only on their own layer - it's not valid
849 // to draw the boundary rectangles when there is already a caster shadow
850 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
851 // composition - using a well-defined invalid color is long-term less error-prone.
852 if (layer->shadow.length > 0) {
853 const auto rect = layer->geometry.roundedCornersRadius > 0
854 ? getSkRect(layer->geometry.roundedCornersCrop)
855 : bounds;
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400856 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
857 LOG_ALWAYS_FATAL_IF(layer->disableBlending, "Cannot disableBlending with a shadow");
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500858 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
859 continue;
860 }
861
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500862 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
863 (mUseColorManagement &&
864 needsToneMapping(layer->sourceDataspace, display.outputDataspace));
865
866 // quick abort from drawing the remaining portion of the layer
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400867 if (layer->alpha == 0 && !requiresLinearEffect && !layer->disableBlending &&
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500868 (!displayColorTransform || displayColorTransform->isAlphaUnchanged())) {
869 continue;
870 }
871
872 // If we need to map to linear space or color management is disabled, then mark the source
873 // image with the same colorspace as the destination surface so that Skia's color
874 // management is a no-op.
875 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
876 ? dstDataspace
877 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800878
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500879 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700880 if (layer->source.buffer.buffer) {
881 ATRACE_NAME("DrawImage");
Alec Mouria90a5702021-04-16 16:36:21 +0000882 validateInputBufferUsage(layer->source.buffer.buffer->getBuffer());
John Reck67b1e2b2020-08-26 13:17:24 -0700883 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800884 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouria90a5702021-04-16 16:36:21 +0000885
886 if (const auto& iter = cache.find(item.buffer->getBuffer()->getId());
887 iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800888 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700889 } else {
Alec Mouria90a5702021-04-16 16:36:21 +0000890 // If we didn't find the image in the cache, then create a local ref but don't cache
891 // it. If we're using skia, we're guaranteed to run on a dedicated GPU thread so if
892 // we didn't find anything in the cache then we intentionally did not cache this
893 // buffer's resources.
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400894 imageTextureRef = std::make_shared<
895 AutoBackendTexture::LocalRef>(grContext.get(),
896 item.buffer->getBuffer()->toAHardwareBuffer(),
897 false);
John Reck67b1e2b2020-08-26 13:17:24 -0700898 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800899
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800900 sk_sp<SkImage> image =
Derek Sollenbergerd8fdae32021-04-09 13:52:59 -0400901 imageTextureRef->makeImage(layerDataspace,
902 item.usePremultipliedAlpha ? kPremul_SkAlphaType
903 : kUnpremul_SkAlphaType,
904 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700905
906 auto texMatrix = getSkM44(item.textureTransform).asM33();
907 // textureTansform was intended to be passed directly into a shader, so when
908 // building the total matrix with the textureTransform we need to first
909 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500910 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800911 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700912
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800913 SkMatrix matrix;
914 if (!texMatrix.invert(&matrix)) {
915 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700916 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800917 // The shader does not respect the translation, so we add it to the texture
918 // transform for the SkImage. This will make sure that the correct layer contents
919 // are drawn in the correct part of the screen.
920 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700921
Ana Krulecb7b28b22020-11-23 14:48:58 -0800922 sk_sp<SkShader> shader;
923
924 if (layer->source.buffer.useTextureFiltering) {
925 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
926 SkSamplingOptions(
927 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
928 &matrix);
929 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500930 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800931 }
Alec Mouri029d1952020-10-12 10:37:08 -0700932
Alec Mouric0aae732021-01-12 13:32:18 -0800933 // Handle opaque images - it's a little nonstandard how we do this.
934 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
935 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
936 // The important language is that when isOpaque is set, opacity is not sampled from the
937 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
938 // here's the conundrum:
939 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
940 // as an internal hint - composition is undefined when there are alpha bits present.
941 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
942 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
943 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
944 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
945 // of a hack anyways.
946 // 3. We can't change the blendmode to src, because while this satisfies the requirement
947 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
948 // because src always clobbers the destination content.
949 //
950 // So, what we do here instead is an additive blend mode where we compose the input
951 // image with a solid black. This might need to be reassess if this does not support
952 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
953 if (item.isOpaque) {
954 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
955 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500956 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -0800957 }
958
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500959 paint.setShader(createRuntimeEffectShader(shader, layer, display,
960 !item.isOpaque && item.usePremultipliedAlpha,
961 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -0800962 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700963 } else {
964 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700965 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800966 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
967 .fG = color.g,
968 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800969 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500970 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800971 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500972 /* undoPremultipliedAlpha */ false,
973 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -0700974 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700975
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400976 if (layer->disableBlending) {
977 paint.setBlendMode(SkBlendMode::kSrc);
978 }
979
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500980 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -0700981
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500982 if (layer->geometry.roundedCornersRadius > 0) {
983 paint.setAntiAlias(true);
984 canvas->drawRRect(getRoundedRect(layer), paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800985 } else {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500986 canvas->drawRect(bounds, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700987 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400988 if (kFlushAfterEveryLayer) {
989 ATRACE_NAME("flush surface");
990 activeSurface->flush();
991 }
John Reck67b1e2b2020-08-26 13:17:24 -0700992 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500993 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800994 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700995 {
996 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500997 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
998 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -0700999 }
1000
1001 if (drawFence != nullptr) {
1002 *drawFence = flush();
1003 }
1004
1005 // If flush failed or we don't support native fences, we need to force the
1006 // gl command stream to be executed.
1007 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
1008 if (requireSync) {
1009 ATRACE_BEGIN("Submit(sync=true)");
1010 } else {
1011 ATRACE_BEGIN("Submit(sync=false)");
1012 }
Lucas Dupind508e472020-11-04 04:32:06 +00001013 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001014 ATRACE_END();
1015 if (!success) {
1016 ALOGE("Failed to flush RenderEngine commands");
1017 // Chances are, something illegal happened (either the caller passed
1018 // us bad parameters, or we messed up our shader generation).
1019 return INVALID_OPERATION;
1020 }
1021
1022 // checkErrors();
1023 return NO_ERROR;
1024}
1025
Lucas Dupin3f11e922020-09-22 17:31:04 -07001026inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1027 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1028}
1029
1030inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1031 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1032}
1033
Lucas Dupin21f348e2020-09-16 17:31:26 -07001034inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -08001035 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001036 const auto cornerRadius = layer->geometry.roundedCornersRadius;
1037 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
1038}
1039
Galia Peycheva80116e52020-11-06 11:57:25 +01001040inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
1041 const auto rect = getSkRect(layer->geometry.boundaries);
1042 const auto cornersRadius = layer->geometry.roundedCornersRadius;
1043 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
1044 .cornerRadiusTL = cornersRadius,
1045 .cornerRadiusTR = cornersRadius,
1046 .cornerRadiusBL = cornersRadius,
1047 .cornerRadiusBR = cornersRadius,
1048 .alpha = 1,
1049 .left = static_cast<int>(rect.fLeft),
1050 .top = static_cast<int>(rect.fTop),
1051 .right = static_cast<int>(rect.fRight),
1052 .bottom = static_cast<int>(rect.fBottom)};
1053}
1054
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001055inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
1056 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
1057}
1058
Lucas Dupin3f11e922020-09-22 17:31:04 -07001059inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1060 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1061}
1062
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001063inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1064 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1065 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1066 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1067 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1068}
1069
Lucas Dupin3f11e922020-09-22 17:31:04 -07001070inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1071 return SkPoint3::Make(vector.x, vector.y, vector.z);
1072}
1073
John Reck67b1e2b2020-08-26 13:17:24 -07001074size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1075 return mGrContext->maxTextureSize();
1076}
1077
1078size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1079 return mGrContext->maxRenderTargetSize();
1080}
1081
Lucas Dupin3f11e922020-09-22 17:31:04 -07001082void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
1083 const ShadowSettings& settings) {
1084 ATRACE_CALL();
1085 const float casterZ = settings.length / 2.0f;
1086 const auto shadowShape = cornerRadius > 0
1087 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
1088 : SkPath::Rect(casterRect);
1089 const auto flags =
1090 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1091
1092 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
1093 getSkPoint3(settings.lightPos), settings.lightRadius,
1094 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1095 flags);
1096}
1097
John Reck67b1e2b2020-08-26 13:17:24 -07001098EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001099 EGLContext shareContext,
1100 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001101 Protection protection) {
1102 EGLint renderableType = 0;
1103 if (config == EGL_NO_CONFIG_KHR) {
1104 renderableType = EGL_OPENGL_ES3_BIT;
1105 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1106 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1107 }
1108 EGLint contextClientVersion = 0;
1109 if (renderableType & EGL_OPENGL_ES3_BIT) {
1110 contextClientVersion = 3;
1111 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1112 contextClientVersion = 2;
1113 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1114 contextClientVersion = 1;
1115 } else {
1116 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1117 }
1118
1119 std::vector<EGLint> contextAttributes;
1120 contextAttributes.reserve(7);
1121 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1122 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001123 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001124 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001125 switch (*contextPriority) {
1126 case ContextPriority::REALTIME:
1127 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1128 break;
1129 case ContextPriority::MEDIUM:
1130 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1131 break;
1132 case ContextPriority::LOW:
1133 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1134 break;
1135 case ContextPriority::HIGH:
1136 default:
1137 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1138 break;
1139 }
John Reck67b1e2b2020-08-26 13:17:24 -07001140 }
1141 if (protection == Protection::PROTECTED) {
1142 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1143 contextAttributes.push_back(EGL_TRUE);
1144 }
1145 contextAttributes.push_back(EGL_NONE);
1146
1147 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1148
1149 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1150 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1151 // EGL_NO_CONTEXT so that we can abort.
1152 if (config != EGL_NO_CONFIG_KHR) {
1153 return context;
1154 }
1155 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1156 // should try to fall back to GLES 2.
1157 contextAttributes[1] = 2;
1158 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1159 }
1160
1161 return context;
1162}
1163
Alec Mourid6f09462020-12-07 11:18:17 -08001164std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1165 const RenderEngineCreationArgs& args) {
1166 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1167 return std::nullopt;
1168 }
1169
1170 switch (args.contextPriority) {
1171 case RenderEngine::ContextPriority::REALTIME:
1172 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1173 return RenderEngine::ContextPriority::REALTIME;
1174 } else {
1175 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1176 return RenderEngine::ContextPriority::HIGH;
1177 }
1178 case RenderEngine::ContextPriority::HIGH:
1179 case RenderEngine::ContextPriority::MEDIUM:
1180 case RenderEngine::ContextPriority::LOW:
1181 return args.contextPriority;
1182 default:
1183 return std::nullopt;
1184 }
1185}
1186
John Reck67b1e2b2020-08-26 13:17:24 -07001187EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1188 EGLConfig config, int hwcFormat,
1189 Protection protection) {
1190 EGLConfig placeholderConfig = config;
1191 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1192 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1193 }
1194 std::vector<EGLint> attributes;
1195 attributes.reserve(7);
1196 attributes.push_back(EGL_WIDTH);
1197 attributes.push_back(1);
1198 attributes.push_back(EGL_HEIGHT);
1199 attributes.push_back(1);
1200 if (protection == Protection::PROTECTED) {
1201 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1202 attributes.push_back(EGL_TRUE);
1203 }
1204 attributes.push_back(EGL_NONE);
1205
1206 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1207}
1208
Alec Mourid6f09462020-12-07 11:18:17 -08001209int SkiaGLRenderEngine::getContextPriority() {
1210 int value;
1211 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1212 return value;
1213}
1214
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001215void SkiaGLRenderEngine::onPrimaryDisplaySizeChanged(ui::Size size) {
1216 // This cache multiplier was selected based on review of cache sizes relative
1217 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1218 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1219 // conservative default based on that analysis.
1220 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1221 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1222
1223 // start by resizing the current context
1224 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
1225 grContext->setResourceCacheLimit(maxResourceBytes);
1226
1227 // if it is possible to switch contexts then we will resize the other context
1228 if (useProtectedContext(!mInProtectedContext)) {
1229 grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
1230 grContext->setResourceCacheLimit(maxResourceBytes);
1231 // reset back to the initial context that was active when this method was called
1232 useProtectedContext(!mInProtectedContext);
1233 }
1234}
1235
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001236void SkiaGLRenderEngine::dump(std::string& result) {
1237 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1238
1239 StringAppendF(&result, "\n ------------RE-----------------\n");
1240 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1241 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1242 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1243 extensions.getVersion());
1244 StringAppendF(&result, "%s\n", extensions.getExtensions());
1245 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1246 supportsProtectedContent());
1247 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001248 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1249 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001250
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001251 std::vector<ResourcePair> cpuResourceMap = {
1252 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1253 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1254 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1255 {"skia/sk_resource_cache/tessellated", "Shadows"},
1256 {"skia", "Other"},
1257 };
1258 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1259 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1260 StringAppendF(&result, "Skia CPU Caches: ");
1261 cpuReporter.logTotals(result);
1262 cpuReporter.logOutput(result);
1263
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001264 {
1265 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001266
1267 std::vector<ResourcePair> gpuResourceMap = {
1268 {"texture_renderbuffer", "Texture/RenderBuffer"},
1269 {"texture", "Texture"},
1270 {"gr_text_blob_cache", "Text"},
1271 {"skia", "Other"},
1272 };
1273 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1274 mGrContext->dumpMemoryStatistics(&gpuReporter);
1275 StringAppendF(&result, "Skia's GPU Caches: ");
1276 gpuReporter.logTotals(result);
1277 gpuReporter.logOutput(result);
1278 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1279 gpuReporter.logOutput(result, true);
1280
Alec Mouria90a5702021-04-16 16:36:21 +00001281 StringAppendF(&result, "RenderEngine tracked buffers: %zu\n",
1282 mGraphicBufferExternalRefs.size());
1283 StringAppendF(&result, "Dumping buffer ids...\n");
1284 for (const auto& [id, refCounts] : mGraphicBufferExternalRefs) {
1285 StringAppendF(&result, "- 0x%" PRIx64 " - %d refs \n", id, refCounts);
1286 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001287 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1288 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001289 StringAppendF(&result, "Dumping buffer ids...\n");
1290 // TODO(178539829): It would be nice to know which layer these are coming from and what
1291 // the texture sizes are.
1292 for (const auto& [id, unused] : mTextureCache) {
1293 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1294 }
1295 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001296
1297 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001298 if (mProtectedGrContext) {
1299 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1300 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001301 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1302 gpuProtectedReporter.logTotals(result);
1303 gpuProtectedReporter.logOutput(result);
1304 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1305 gpuProtectedReporter.logOutput(result, true);
1306
1307 StringAppendF(&result, "RenderEngine protected AHB/BackendTexture cache size: %zu\n",
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001308 mProtectedTextureCache.size());
1309 StringAppendF(&result, "Dumping buffer ids...\n");
1310 for (const auto& [id, unused] : mProtectedTextureCache) {
1311 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1312 }
1313 StringAppendF(&result, "\n");
1314 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1315 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1316 StringAppendF(&result, "- inputDataspace: %s\n",
1317 dataspaceDetails(
1318 static_cast<android_dataspace>(linearEffect.inputDataspace))
1319 .c_str());
1320 StringAppendF(&result, "- outputDataspace: %s\n",
1321 dataspaceDetails(
1322 static_cast<android_dataspace>(linearEffect.outputDataspace))
1323 .c_str());
1324 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1325 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1326 }
1327 }
1328 StringAppendF(&result, "\n");
1329}
1330
John Reck67b1e2b2020-08-26 13:17:24 -07001331} // namespace skia
1332} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001333} // namespace android