blob: df40dd9c2dc135aaf67984c40493f858996bdd81 [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() {
Alec Mouri617752f2021-04-15 16:27:01 +0000332 cleanFramebufferCache();
333
Marin Shalamanovcea12ef2021-03-15 17:00:51 +0100334 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouric0aae732021-01-12 13:32:18 -0800335 if (mBlurFilter) {
336 delete mBlurFilter;
337 }
338
339 mCapture = nullptr;
340
341 mGrContext->flushAndSubmit(true);
342 mGrContext->abandonContext();
343
344 if (mProtectedGrContext) {
345 mProtectedGrContext->flushAndSubmit(true);
346 mProtectedGrContext->abandonContext();
347 }
348
349 if (mPlaceholderSurface != EGL_NO_SURFACE) {
350 eglDestroySurface(mEGLDisplay, mPlaceholderSurface);
351 }
352 if (mProtectedPlaceholderSurface != EGL_NO_SURFACE) {
353 eglDestroySurface(mEGLDisplay, mProtectedPlaceholderSurface);
354 }
355 if (mEGLContext != EGL_NO_CONTEXT) {
356 eglDestroyContext(mEGLDisplay, mEGLContext);
357 }
358 if (mProtectedEGLContext != EGL_NO_CONTEXT) {
359 eglDestroyContext(mEGLDisplay, mProtectedEGLContext);
360 }
361 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
362 eglTerminate(mEGLDisplay);
363 eglReleaseThread();
John Reck67b1e2b2020-08-26 13:17:24 -0700364}
365
Lucas Dupind508e472020-11-04 04:32:06 +0000366bool SkiaGLRenderEngine::supportsProtectedContent() const {
367 return mProtectedEGLContext != EGL_NO_CONTEXT;
368}
369
370bool SkiaGLRenderEngine::useProtectedContext(bool useProtectedContext) {
371 if (useProtectedContext == mInProtectedContext) {
372 return true;
373 }
Alec Mourif6a07812021-02-11 21:07:55 -0800374 if (useProtectedContext && !supportsProtectedContent()) {
Lucas Dupind508e472020-11-04 04:32:06 +0000375 return false;
376 }
377 const EGLSurface surface =
378 useProtectedContext ? mProtectedPlaceholderSurface : mPlaceholderSurface;
379 const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
380 const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
Alec Mouric0aae732021-01-12 13:32:18 -0800381
Lucas Dupind508e472020-11-04 04:32:06 +0000382 if (success) {
383 mInProtectedContext = useProtectedContext;
384 }
385 return success;
386}
387
John Reck67b1e2b2020-08-26 13:17:24 -0700388base::unique_fd SkiaGLRenderEngine::flush() {
389 ATRACE_CALL();
390 if (!gl::GLExtensions::getInstance().hasNativeFenceSync()) {
391 return base::unique_fd();
392 }
393
394 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
395 if (sync == EGL_NO_SYNC_KHR) {
396 ALOGW("failed to create EGL native fence sync: %#x", eglGetError());
397 return base::unique_fd();
398 }
399
400 // native fence fd will not be populated until flush() is done.
401 glFlush();
402
403 // get the fence fd
404 base::unique_fd fenceFd(eglDupNativeFenceFDANDROID(mEGLDisplay, sync));
405 eglDestroySyncKHR(mEGLDisplay, sync);
406 if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
407 ALOGW("failed to dup EGL native fence sync: %#x", eglGetError());
408 }
409
410 return fenceFd;
411}
412
413bool SkiaGLRenderEngine::waitFence(base::unique_fd fenceFd) {
414 if (!gl::GLExtensions::getInstance().hasNativeFenceSync() ||
415 !gl::GLExtensions::getInstance().hasWaitSync()) {
416 return false;
417 }
418
419 // release the fd and transfer the ownership to EGLSync
420 EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd.release(), EGL_NONE};
421 EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
422 if (sync == EGL_NO_SYNC_KHR) {
423 ALOGE("failed to create EGL native fence sync: %#x", eglGetError());
424 return false;
425 }
426
427 // XXX: The spec draft is inconsistent as to whether this should return an
428 // EGLint or void. Ignore the return value for now, as it's not strictly
429 // needed.
430 eglWaitSyncKHR(mEGLDisplay, sync, 0);
431 EGLint error = eglGetError();
432 eglDestroySyncKHR(mEGLDisplay, sync);
433 if (error != EGL_SUCCESS) {
434 ALOGE("failed to wait for EGL native fence sync: %#x", error);
435 return false;
436 }
437
438 return true;
439}
440
Alec Mouri678245d2020-09-30 16:58:23 -0700441static float toDegrees(uint32_t transform) {
442 switch (transform) {
443 case ui::Transform::ROT_90:
444 return 90.0;
445 case ui::Transform::ROT_180:
446 return 180.0;
447 case ui::Transform::ROT_270:
448 return 270.0;
449 default:
450 return 0.0;
451 }
452}
453
Alec Mourib34f0b72020-10-02 13:18:34 -0700454static SkColorMatrix toSkColorMatrix(const mat4& matrix) {
455 return SkColorMatrix(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0], 0, matrix[0][1],
456 matrix[1][1], matrix[2][1], matrix[3][1], 0, matrix[0][2], matrix[1][2],
457 matrix[2][2], matrix[3][2], 0, matrix[0][3], matrix[1][3], matrix[2][3],
458 matrix[3][3], 0);
459}
460
Alec Mouri029d1952020-10-12 10:37:08 -0700461static bool needsToneMapping(ui::Dataspace sourceDataspace, ui::Dataspace destinationDataspace) {
462 int64_t sourceTransfer = sourceDataspace & HAL_DATASPACE_TRANSFER_MASK;
463 int64_t destTransfer = destinationDataspace & HAL_DATASPACE_TRANSFER_MASK;
464
465 // Treat unsupported dataspaces as srgb
466 if (destTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
467 destTransfer != HAL_DATASPACE_TRANSFER_HLG &&
468 destTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
469 destTransfer = HAL_DATASPACE_TRANSFER_SRGB;
470 }
471
472 if (sourceTransfer != HAL_DATASPACE_TRANSFER_LINEAR &&
473 sourceTransfer != HAL_DATASPACE_TRANSFER_HLG &&
474 sourceTransfer != HAL_DATASPACE_TRANSFER_ST2084) {
475 sourceTransfer = HAL_DATASPACE_TRANSFER_SRGB;
476 }
477
478 const bool isSourceLinear = sourceTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
479 const bool isSourceSRGB = sourceTransfer == HAL_DATASPACE_TRANSFER_SRGB;
480 const bool isDestLinear = destTransfer == HAL_DATASPACE_TRANSFER_LINEAR;
481 const bool isDestSRGB = destTransfer == HAL_DATASPACE_TRANSFER_SRGB;
482
483 return !(isSourceLinear && isDestSRGB) && !(isSourceSRGB && isDestLinear) &&
484 sourceTransfer != destTransfer;
485}
486
Alec Mouri617752f2021-04-15 16:27:01 +0000487void SkiaGLRenderEngine::cacheExternalTextureBuffer(const sp<GraphicBuffer>& buffer) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800488 // Only run this if RE is running on its own thread. This way the access to GL
489 // operations is guaranteed to be happening on the same thread.
490 if (mRenderEngineType != RenderEngineType::SKIA_GL_THREADED) {
491 return;
492 }
493 ATRACE_CALL();
494
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400495 // We need to switch the currently bound context if the buffer is protected but the current
496 // context is not. The current state must then be restored after the buffer is cached.
497 const bool protectedContextState = mInProtectedContext;
498 if (!useProtectedContext(protectedContextState ||
499 (buffer->getUsage() & GRALLOC_USAGE_PROTECTED))) {
500 ALOGE("Attempting to cache a buffer into a different context than what is currently bound");
Ana Krulecdfec8f52021-01-13 12:51:47 -0800501 return;
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400502 }
503
504 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
505 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
506
507 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouri617752f2021-04-15 16:27:01 +0000508 auto iter = cache.find(buffer->getId());
509 if (iter != cache.end()) {
510 ALOGV("Texture already exists in cache.");
511 } else {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800512 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef =
Alec Mouri617752f2021-04-15 16:27:01 +0000513 std::make_shared<AutoBackendTexture::LocalRef>();
514 imageTextureRef->setTexture(
515 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), false));
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400516 cache.insert({buffer->getId(), imageTextureRef});
Ana Krulecdfec8f52021-01-13 12:51:47 -0800517 }
Derek Sollenbergereb904d42021-03-22 12:58:53 -0400518 // restore the original state of the protected context if necessary
519 useProtectedContext(protectedContextState);
Ana Krulecdfec8f52021-01-13 12:51:47 -0800520}
521
Alec Mouri617752f2021-04-15 16:27:01 +0000522void SkiaGLRenderEngine::unbindExternalTextureBuffer(uint64_t bufferId) {
Ana Krulecdfec8f52021-01-13 12:51:47 -0800523 ATRACE_CALL();
John Reck67b1e2b2020-08-26 13:17:24 -0700524 std::lock_guard<std::mutex> lock(mRenderingMutex);
Alec Mouri617752f2021-04-15 16:27:01 +0000525 mTextureCache.erase(bufferId);
526 mProtectedTextureCache.erase(bufferId);
John Reck67b1e2b2020-08-26 13:17:24 -0700527}
528
Ana Krulec47814212021-01-06 19:00:10 -0800529sk_sp<SkShader> SkiaGLRenderEngine::createRuntimeEffectShader(sk_sp<SkShader> shader,
530 const LayerSettings* layer,
531 const DisplaySettings& display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500532 bool undoPremultipliedAlpha,
533 bool requiresLinearEffect) {
John Reckcdb4ed72021-02-04 13:39:33 -0500534 if (layer->stretchEffect.hasEffect()) {
535 // TODO: Implement
536 }
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500537 if (requiresLinearEffect) {
538 const ui::Dataspace inputDataspace =
539 mUseColorManagement ? layer->sourceDataspace : ui::Dataspace::UNKNOWN;
540 const ui::Dataspace outputDataspace =
541 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
542
543 LinearEffect effect = LinearEffect{.inputDataspace = inputDataspace,
544 .outputDataspace = outputDataspace,
Ana Krulec47814212021-01-06 19:00:10 -0800545 .undoPremultipliedAlpha = undoPremultipliedAlpha};
546
547 auto effectIter = mRuntimeEffects.find(effect);
548 sk_sp<SkRuntimeEffect> runtimeEffect = nullptr;
549 if (effectIter == mRuntimeEffects.end()) {
550 runtimeEffect = buildRuntimeEffect(effect);
551 mRuntimeEffects.insert({effect, runtimeEffect});
552 } else {
553 runtimeEffect = effectIter->second;
554 }
555 return createLinearEffectShader(shader, effect, runtimeEffect, layer->colorTransform,
556 display.maxLuminance,
557 layer->source.buffer.maxMasteringLuminance,
558 layer->source.buffer.maxContentLuminance);
559 }
560 return shader;
561}
562
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500563void SkiaGLRenderEngine::initCanvas(SkCanvas* canvas, const DisplaySettings& display) {
Derek Sollenberger76664d62021-02-04 11:13:09 -0500564 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500565 // Record display settings when capture is running.
566 std::stringstream displaySettings;
567 PrintTo(display, &displaySettings);
568 // Store the DisplaySettings in additional information.
569 canvas->drawAnnotation(SkRect::MakeEmpty(), "DisplaySettings",
570 SkData::MakeWithCString(displaySettings.str().c_str()));
571 }
572
573 // Before doing any drawing, let's make sure that we'll start at the origin of the display.
574 // Some displays don't start at 0,0 for example when we're mirroring the screen. Also, virtual
575 // displays might have different scaling when compared to the physical screen.
576
577 canvas->clipRect(getSkRect(display.physicalDisplay));
578 canvas->translate(display.physicalDisplay.left, display.physicalDisplay.top);
579
580 const auto clipWidth = display.clip.width();
581 const auto clipHeight = display.clip.height();
582 auto rotatedClipWidth = clipWidth;
583 auto rotatedClipHeight = clipHeight;
584 // Scale is contingent on the rotation result.
585 if (display.orientation & ui::Transform::ROT_90) {
586 std::swap(rotatedClipWidth, rotatedClipHeight);
587 }
588 const auto scaleX = static_cast<SkScalar>(display.physicalDisplay.width()) /
589 static_cast<SkScalar>(rotatedClipWidth);
590 const auto scaleY = static_cast<SkScalar>(display.physicalDisplay.height()) /
591 static_cast<SkScalar>(rotatedClipHeight);
592 canvas->scale(scaleX, scaleY);
593
594 // Canvas rotation is done by centering the clip window at the origin, rotating, translating
595 // back so that the top left corner of the clip is at (0, 0).
596 canvas->translate(rotatedClipWidth / 2, rotatedClipHeight / 2);
597 canvas->rotate(toDegrees(display.orientation));
598 canvas->translate(-clipWidth / 2, -clipHeight / 2);
599 canvas->translate(-display.clip.left, -display.clip.top);
600}
601
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500602class AutoSaveRestore {
603public:
604 AutoSaveRestore(SkCanvas* canvas) : mCanvas(canvas) { mSaveCount = canvas->save(); }
605 ~AutoSaveRestore() { restore(); }
606 void replace(SkCanvas* canvas) {
607 mCanvas = canvas;
608 mSaveCount = canvas->save();
609 }
610 void restore() {
611 if (mCanvas) {
612 mCanvas->restoreToCount(mSaveCount);
613 mCanvas = nullptr;
614 }
615 }
616
617private:
618 SkCanvas* mCanvas;
619 int mSaveCount;
620};
621
John Reck67b1e2b2020-08-26 13:17:24 -0700622status_t SkiaGLRenderEngine::drawLayers(const DisplaySettings& display,
623 const std::vector<const LayerSettings*>& layers,
Alec Mouri617752f2021-04-15 16:27:01 +0000624 const sp<GraphicBuffer>& buffer,
625 const bool useFramebufferCache,
John Reck67b1e2b2020-08-26 13:17:24 -0700626 base::unique_fd&& bufferFence, base::unique_fd* drawFence) {
627 ATRACE_NAME("SkiaGL::drawLayers");
Alec Mouric0aae732021-01-12 13:32:18 -0800628
John Reck67b1e2b2020-08-26 13:17:24 -0700629 std::lock_guard<std::mutex> lock(mRenderingMutex);
630 if (layers.empty()) {
631 ALOGV("Drawing empty layer stack");
632 return NO_ERROR;
633 }
634
635 if (bufferFence.get() >= 0) {
636 // Duplicate the fence for passing to waitFence.
637 base::unique_fd bufferFenceDup(dup(bufferFence.get()));
638 if (bufferFenceDup < 0 || !waitFence(std::move(bufferFenceDup))) {
639 ATRACE_NAME("Waiting before draw");
640 sync_wait(bufferFence.get(), -1);
641 }
642 }
643 if (buffer == nullptr) {
644 ALOGE("No output buffer provided. Aborting GPU composition.");
645 return BAD_VALUE;
646 }
647
Alec Mouri617752f2021-04-15 16:27:01 +0000648 validateOutputBufferUsage(buffer);
Ady Abraham193426d2021-02-18 14:01:53 -0800649
Lucas Dupind508e472020-11-04 04:32:06 +0000650 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800651 auto& cache = mInProtectedContext ? mProtectedTextureCache : mTextureCache;
Alec Mouri617752f2021-04-15 16:27:01 +0000652 AHardwareBuffer_Desc bufferDesc;
653 AHardwareBuffer_describe(buffer->toAHardwareBuffer(), &bufferDesc);
John Reck67b1e2b2020-08-26 13:17:24 -0700654
Alec Mouri617752f2021-04-15 16:27:01 +0000655 std::shared_ptr<AutoBackendTexture::LocalRef> surfaceTextureRef = nullptr;
656 if (useFramebufferCache) {
657 auto iter = cache.find(buffer->getId());
658 if (iter != cache.end()) {
659 ALOGV("Cache hit!");
660 ATRACE_NAME("Cache hit");
661 surfaceTextureRef = iter->second;
662 }
663 }
664
665 if (surfaceTextureRef == nullptr || surfaceTextureRef->getTexture() == nullptr) {
666 ATRACE_NAME("Cache miss");
667 surfaceTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
668 surfaceTextureRef->setTexture(
669 new AutoBackendTexture(grContext.get(), buffer->toAHardwareBuffer(), true));
670 if (useFramebufferCache) {
671 ALOGD("Adding to cache");
672 cache.insert({buffer->getId(), surfaceTextureRef});
673 }
John Reck67b1e2b2020-08-26 13:17:24 -0700674 }
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800675
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500676 const ui::Dataspace dstDataspace =
677 mUseColorManagement ? display.outputDataspace : ui::Dataspace::UNKNOWN;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500678 sk_sp<SkSurface> dstSurface =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500679 surfaceTextureRef->getTexture()->getOrCreateSurface(dstDataspace, grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700680
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500681 SkCanvas* dstCanvas = mCapture->tryCapture(dstSurface.get());
682 if (dstCanvas == nullptr) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800683 ALOGE("Cannot acquire canvas from Skia.");
684 return BAD_VALUE;
685 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500686
687 // Find if any layers have requested blur, we'll use that info to decide when to render to an
688 // offscreen buffer and when to render to the native buffer.
689 sk_sp<SkSurface> activeSurface(dstSurface);
690 SkCanvas* canvas = dstCanvas;
Derek Sollenberger76664d62021-02-04 11:13:09 -0500691 SkiaCapture::OffscreenState offscreenCaptureState;
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500692 const LayerSettings* blurCompositionLayer = nullptr;
693 if (mBlurFilter) {
694 bool requiresCompositionLayer = false;
695 for (const auto& layer : layers) {
Derek Sollenberger3134ec32021-02-12 11:26:23 -0500696 if (layer->backgroundBlurRadius > 0 &&
697 layer->backgroundBlurRadius < BlurFilter::kMaxCrossFadeRadius) {
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500698 requiresCompositionLayer = true;
699 }
700 for (auto region : layer->blurRegions) {
701 if (region.blurRadius < BlurFilter::kMaxCrossFadeRadius) {
702 requiresCompositionLayer = true;
703 }
704 }
705 if (requiresCompositionLayer) {
706 activeSurface = dstSurface->makeSurface(dstSurface->imageInfo());
Derek Sollenberger76664d62021-02-04 11:13:09 -0500707 canvas = mCapture->tryOffscreenCapture(activeSurface.get(), &offscreenCaptureState);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500708 blurCompositionLayer = layer;
709 break;
710 }
711 }
712 }
713
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500714 AutoSaveRestore surfaceAutoSaveRestore(canvas);
Alec Mouri678245d2020-09-30 16:58:23 -0700715 // Clear the entire canvas with a transparent black to prevent ghost images.
716 canvas->clear(SK_ColorTRANSPARENT);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500717 initCanvas(canvas, display);
Alec Mouric0aae732021-01-12 13:32:18 -0800718
719 // TODO: clearRegion was required for SurfaceView when a buffer is not yet available but the
720 // view is still on-screen. The clear region could be re-specified as a black color layer,
721 // however.
722 if (!display.clearRegion.isEmpty()) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500723 ATRACE_NAME("ClearRegion");
Alec Mouric0aae732021-01-12 13:32:18 -0800724 size_t numRects = 0;
725 Rect const* rects = display.clearRegion.getArray(&numRects);
726 SkIRect skRects[numRects];
727 for (int i = 0; i < numRects; ++i) {
728 skRects[i] =
729 SkIRect::MakeLTRB(rects[i].left, rects[i].top, rects[i].right, rects[i].bottom);
730 }
731 SkRegion clearRegion;
732 SkPaint paint;
733 sk_sp<SkShader> shader =
734 SkShaders::Color(SkColor4f{.fR = 0., .fG = 0., .fB = 0., .fA = 1.0},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500735 toSkColorSpace(dstDataspace));
Alec Mouric0aae732021-01-12 13:32:18 -0800736 paint.setShader(shader);
737 clearRegion.setRects(skRects, numRects);
738 canvas->drawRegion(clearRegion, paint);
739 }
740
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500741 // setup color filter if necessary
742 sk_sp<SkColorFilter> displayColorTransform;
743 if (display.colorTransform != mat4()) {
744 displayColorTransform = SkColorFilters::Matrix(toSkColorMatrix(display.colorTransform));
745 }
746
John Reck67b1e2b2020-08-26 13:17:24 -0700747 for (const auto& layer : layers) {
Derek Sollenberger545ec442021-01-25 10:02:23 -0500748 ATRACE_NAME("DrawLayer");
Galia Peychevaf7889b32020-11-25 22:22:40 +0100749
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400750 if (kPrintLayerSettings) {
751 std::stringstream ls;
752 PrintTo(*layer, &ls);
753 auto debugs = ls.str();
754 int pos = 0;
755 while (pos < debugs.size()) {
756 ALOGD("cache_debug %s", debugs.substr(pos, 1000).c_str());
757 pos += 1000;
758 }
759 }
760
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500761 sk_sp<SkImage> blurInput;
762 if (blurCompositionLayer == layer) {
763 LOG_ALWAYS_FATAL_IF(activeSurface == dstSurface);
764 LOG_ALWAYS_FATAL_IF(canvas == dstCanvas);
765
766 // save a snapshot of the activeSurface to use as input to the blur shaders
767 blurInput = activeSurface->makeImageSnapshot();
768
769 // TODO we could skip this step if we know the blur will cover the entire image
770 // blit the offscreen framebuffer into the destination AHB
771 SkPaint paint;
772 paint.setBlendMode(SkBlendMode::kSrc);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500773 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
774 uint64_t id = mCapture->endOffscreenCapture(&offscreenCaptureState);
775 dstCanvas->drawAnnotation(SkRect::Make(dstCanvas->imageInfo().dimensions()),
776 String8::format("SurfaceID|%" PRId64, id).c_str(),
777 nullptr);
778 dstCanvas->drawImage(blurInput, 0, 0, SkSamplingOptions(), &paint);
779 } else {
780 activeSurface->draw(dstCanvas, 0, 0, SkSamplingOptions(), &paint);
781 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500782
783 // assign dstCanvas to canvas and ensure that the canvas state is up to date
784 canvas = dstCanvas;
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500785 surfaceAutoSaveRestore.replace(canvas);
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500786 initCanvas(canvas, display);
787
788 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getSaveCount() !=
789 dstSurface->getCanvas()->getSaveCount());
790 LOG_ALWAYS_FATAL_IF(activeSurface->getCanvas()->getTotalMatrix() !=
791 dstSurface->getCanvas()->getTotalMatrix());
792
793 // assign dstSurface to activeSurface
794 activeSurface = dstSurface;
795 }
796
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500797 SkAutoCanvasRestore layerAutoSaveRestore(canvas, true);
Derek Sollenberger76664d62021-02-04 11:13:09 -0500798 if (CC_UNLIKELY(mCapture->isCaptureRunning())) {
Ana Krulec6eab17a2020-12-09 15:52:36 -0800799 // Record the name of the layer if the capture is running.
800 std::stringstream layerSettings;
801 PrintTo(*layer, &layerSettings);
802 // Store the LayerSettings in additional information.
803 canvas->drawAnnotation(SkRect::MakeEmpty(), layer->name.c_str(),
804 SkData::MakeWithCString(layerSettings.str().c_str()));
805 }
Galia Peychevaf7889b32020-11-25 22:22:40 +0100806 // Layers have a local transform that should be applied to them
807 canvas->concat(getSkM44(layer->geometry.positionTransform).asM33());
Galia Peycheva6c460652020-11-03 19:42:42 +0100808
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500809 const auto bounds = getSkRect(layer->geometry.boundaries);
810 if (mBlurFilter && layerHasBlur(layer)) {
811 std::unordered_map<uint32_t, sk_sp<SkImage>> cachedBlurs;
812
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500813 // if multiple layers have blur, then we need to take a snapshot now because
814 // only the lowest layer will have blurImage populated earlier
815 if (!blurInput) {
816 blurInput = activeSurface->makeImageSnapshot();
817 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500818 // rect to be blurred in the coordinate space of blurInput
819 const auto blurRect = canvas->getTotalMatrix().mapRect(bounds);
820
Lucas Dupinc3800b82020-10-02 16:24:48 -0700821 if (layer->backgroundBlurRadius > 0) {
822 ATRACE_NAME("BackgroundBlur");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500823 auto blurredImage =
824 mBlurFilter->generate(grContext.get(), layer->backgroundBlurRadius,
825 blurInput, blurRect);
Galia Peycheva80116e52020-11-06 11:57:25 +0100826
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500827 cachedBlurs[layer->backgroundBlurRadius] = blurredImage;
828
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500829 mBlurFilter->drawBlurRegion(canvas, getBlurRegion(layer), blurRect, blurredImage,
830 blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700831 }
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500832 for (auto region : layer->blurRegions) {
Galia Peychevaa600b972021-02-19 15:50:12 +0100833 if (cachedBlurs[region.blurRadius] == nullptr) {
Lucas Dupinc3800b82020-10-02 16:24:48 -0700834 ATRACE_NAME("BlurRegion");
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500835 cachedBlurs[region.blurRadius] =
836 mBlurFilter->generate(grContext.get(), region.blurRadius, blurInput,
837 blurRect);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700838 }
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500839
840 mBlurFilter->drawBlurRegion(canvas, region, blurRect,
841 cachedBlurs[region.blurRadius], blurInput);
Lucas Dupinc3800b82020-10-02 16:24:48 -0700842 }
Lucas Dupinf4cb4a02020-09-22 14:19:26 -0700843 }
844
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500845 // Shadows are assumed to live only on their own layer - it's not valid
846 // to draw the boundary rectangles when there is already a caster shadow
847 // TODO(b/175915334): consider relaxing this restriction to enable more flexible
848 // composition - using a well-defined invalid color is long-term less error-prone.
849 if (layer->shadow.length > 0) {
850 const auto rect = layer->geometry.roundedCornersRadius > 0
851 ? getSkRect(layer->geometry.roundedCornersCrop)
852 : bounds;
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400853 // This would require a new parameter/flag to SkShadowUtils::DrawShadow
854 LOG_ALWAYS_FATAL_IF(layer->disableBlending, "Cannot disableBlending with a shadow");
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500855 drawShadow(canvas, rect, layer->geometry.roundedCornersRadius, layer->shadow);
856 continue;
857 }
858
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500859 const bool requiresLinearEffect = layer->colorTransform != mat4() ||
860 (mUseColorManagement &&
861 needsToneMapping(layer->sourceDataspace, display.outputDataspace));
862
863 // quick abort from drawing the remaining portion of the layer
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400864 if (layer->alpha == 0 && !requiresLinearEffect && !layer->disableBlending &&
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500865 (!displayColorTransform || displayColorTransform->isAlphaUnchanged())) {
866 continue;
867 }
868
869 // If we need to map to linear space or color management is disabled, then mark the source
870 // image with the same colorspace as the destination surface so that Skia's color
871 // management is a no-op.
872 const ui::Dataspace layerDataspace = (!mUseColorManagement || requiresLinearEffect)
873 ? dstDataspace
874 : layer->sourceDataspace;
Alec Mouric0aae732021-01-12 13:32:18 -0800875
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500876 SkPaint paint;
John Reck67b1e2b2020-08-26 13:17:24 -0700877 if (layer->source.buffer.buffer) {
878 ATRACE_NAME("DrawImage");
Alec Mouri617752f2021-04-15 16:27:01 +0000879 validateInputBufferUsage(layer->source.buffer.buffer);
John Reck67b1e2b2020-08-26 13:17:24 -0700880 const auto& item = layer->source.buffer;
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800881 std::shared_ptr<AutoBackendTexture::LocalRef> imageTextureRef = nullptr;
Alec Mouri617752f2021-04-15 16:27:01 +0000882 auto iter = cache.find(item.buffer->getId());
883 if (iter != cache.end()) {
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800884 imageTextureRef = iter->second;
John Reck67b1e2b2020-08-26 13:17:24 -0700885 } else {
Alec Mouri617752f2021-04-15 16:27:01 +0000886 imageTextureRef = std::make_shared<AutoBackendTexture::LocalRef>();
887 imageTextureRef->setTexture(new AutoBackendTexture(grContext.get(),
888 item.buffer->toAHardwareBuffer(),
889 false));
890 cache.insert({item.buffer->getId(), imageTextureRef});
John Reck67b1e2b2020-08-26 13:17:24 -0700891 }
Alec Mouri1a4d0642020-11-13 17:42:01 -0800892
Alec Mouric7f6c8b2020-11-09 18:35:20 -0800893 sk_sp<SkImage> image =
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500894 imageTextureRef->getTexture()->makeImage(layerDataspace,
Alec Mouric0aae732021-01-12 13:32:18 -0800895 item.usePremultipliedAlpha
896 ? kPremul_SkAlphaType
897 : kUnpremul_SkAlphaType,
898 grContext.get());
Alec Mouri678245d2020-09-30 16:58:23 -0700899
900 auto texMatrix = getSkM44(item.textureTransform).asM33();
901 // textureTansform was intended to be passed directly into a shader, so when
902 // building the total matrix with the textureTransform we need to first
903 // normalize it, then apply the textureTransform, then scale back up.
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500904 texMatrix.preScale(1.0f / bounds.width(), 1.0f / bounds.height());
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800905 texMatrix.postScale(image->width(), image->height());
Alec Mouri678245d2020-09-30 16:58:23 -0700906
Huihong Luo3a3cf3c2020-12-07 17:05:41 -0800907 SkMatrix matrix;
908 if (!texMatrix.invert(&matrix)) {
909 matrix = texMatrix;
Alec Mouri678245d2020-09-30 16:58:23 -0700910 }
Ana Krulecf9a15d92020-12-11 08:35:00 -0800911 // The shader does not respect the translation, so we add it to the texture
912 // transform for the SkImage. This will make sure that the correct layer contents
913 // are drawn in the correct part of the screen.
914 matrix.postTranslate(layer->geometry.boundaries.left, layer->geometry.boundaries.top);
Alec Mouri678245d2020-09-30 16:58:23 -0700915
Ana Krulecb7b28b22020-11-23 14:48:58 -0800916 sk_sp<SkShader> shader;
917
918 if (layer->source.buffer.useTextureFiltering) {
919 shader = image->makeShader(SkTileMode::kClamp, SkTileMode::kClamp,
920 SkSamplingOptions(
921 {SkFilterMode::kLinear, SkMipmapMode::kNone}),
922 &matrix);
923 } else {
Mike Reed711e1f02020-12-11 13:06:19 -0500924 shader = image->makeShader(SkSamplingOptions(), matrix);
Ana Krulecb7b28b22020-11-23 14:48:58 -0800925 }
Alec Mouri029d1952020-10-12 10:37:08 -0700926
Alec Mouric0aae732021-01-12 13:32:18 -0800927 // Handle opaque images - it's a little nonstandard how we do this.
928 // Fundamentally we need to support SurfaceControl.Builder#setOpaque:
929 // https://developer.android.com/reference/android/view/SurfaceControl.Builder#setOpaque(boolean)
930 // The important language is that when isOpaque is set, opacity is not sampled from the
931 // alpha channel, but blending may still be supported on a transaction via setAlpha. So,
932 // here's the conundrum:
933 // 1. We can't force the SkImage alpha type to kOpaque_SkAlphaType, because it's treated
934 // as an internal hint - composition is undefined when there are alpha bits present.
935 // 2. We can try to lie about the pixel layout, but that only works for RGBA8888
936 // buffers, i.e., treating them as RGBx8888 instead. But we can't do the same for
937 // RGBA1010102 because RGBx1010102 is not supported as a pixel layout for SkImages. It's
938 // also not clear what to use for F16 either, and lying about the pixel layout is a bit
939 // of a hack anyways.
940 // 3. We can't change the blendmode to src, because while this satisfies the requirement
941 // for ignoring the alpha channel, it doesn't quite satisfy the blending requirement
942 // because src always clobbers the destination content.
943 //
944 // So, what we do here instead is an additive blend mode where we compose the input
945 // image with a solid black. This might need to be reassess if this does not support
946 // FP16 incredibly well, but FP16 end-to-end isn't well supported anyway at the moment.
947 if (item.isOpaque) {
948 shader = SkShaders::Blend(SkBlendMode::kPlus, shader,
949 SkShaders::Color(SkColors::kBlack,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500950 toSkColorSpace(layerDataspace)));
Alec Mouric0aae732021-01-12 13:32:18 -0800951 }
952
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500953 paint.setShader(createRuntimeEffectShader(shader, layer, display,
954 !item.isOpaque && item.usePremultipliedAlpha,
955 requiresLinearEffect));
Ana Krulec1768bd22020-11-23 14:51:31 -0800956 paint.setAlphaf(layer->alpha);
John Reck67b1e2b2020-08-26 13:17:24 -0700957 } else {
958 ATRACE_NAME("DrawColor");
John Reck67b1e2b2020-08-26 13:17:24 -0700959 const auto color = layer->source.solidColor;
Ana Krulec47814212021-01-06 19:00:10 -0800960 sk_sp<SkShader> shader = SkShaders::Color(SkColor4f{.fR = color.r,
961 .fG = color.g,
962 .fB = color.b,
Alec Mouric0aae732021-01-12 13:32:18 -0800963 .fA = layer->alpha},
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500964 toSkColorSpace(layerDataspace));
Ana Krulec47814212021-01-06 19:00:10 -0800965 paint.setShader(createRuntimeEffectShader(shader, layer, display,
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500966 /* undoPremultipliedAlpha */ false,
967 requiresLinearEffect));
John Reck67b1e2b2020-08-26 13:17:24 -0700968 }
Lucas Dupin21f348e2020-09-16 17:31:26 -0700969
Leon Scroggins IIIcf3d95c2021-03-19 13:06:32 -0400970 if (layer->disableBlending) {
971 paint.setBlendMode(SkBlendMode::kSrc);
972 }
973
Derek Sollenbergere2fe78c2021-02-23 13:22:54 -0500974 paint.setColorFilter(displayColorTransform);
Alec Mourib34f0b72020-10-02 13:18:34 -0700975
Derek Sollenberger4c331c82021-02-23 13:09:50 -0500976 if (layer->geometry.roundedCornersRadius > 0) {
977 paint.setAntiAlias(true);
978 canvas->drawRRect(getRoundedRect(layer), paint);
Alec Mouribd17b3b2020-12-17 11:08:30 -0800979 } else {
Derek Sollenbergerecb21462021-01-29 16:53:49 -0500980 canvas->drawRect(bounds, paint);
Lucas Dupin3f11e922020-09-22 17:31:04 -0700981 }
Nathaniel Nifongb9f27ef2021-04-01 16:44:12 -0400982 if (kFlushAfterEveryLayer) {
983 ATRACE_NAME("flush surface");
984 activeSurface->flush();
985 }
John Reck67b1e2b2020-08-26 13:17:24 -0700986 }
Derek Sollenberger7c42bef2021-02-23 13:01:39 -0500987 surfaceAutoSaveRestore.restore();
Alec Mouric0aae732021-01-12 13:32:18 -0800988 mCapture->endCapture();
John Reck67b1e2b2020-08-26 13:17:24 -0700989 {
990 ATRACE_NAME("flush surface");
Derek Sollenberger3f77aa42021-02-04 11:06:34 -0500991 LOG_ALWAYS_FATAL_IF(activeSurface != dstSurface);
992 activeSurface->flush();
John Reck67b1e2b2020-08-26 13:17:24 -0700993 }
994
995 if (drawFence != nullptr) {
996 *drawFence = flush();
997 }
998
999 // If flush failed or we don't support native fences, we need to force the
1000 // gl command stream to be executed.
1001 bool requireSync = drawFence == nullptr || drawFence->get() < 0;
1002 if (requireSync) {
1003 ATRACE_BEGIN("Submit(sync=true)");
1004 } else {
1005 ATRACE_BEGIN("Submit(sync=false)");
1006 }
Lucas Dupind508e472020-11-04 04:32:06 +00001007 bool success = grContext->submit(requireSync);
John Reck67b1e2b2020-08-26 13:17:24 -07001008 ATRACE_END();
1009 if (!success) {
1010 ALOGE("Failed to flush RenderEngine commands");
1011 // Chances are, something illegal happened (either the caller passed
1012 // us bad parameters, or we messed up our shader generation).
1013 return INVALID_OPERATION;
1014 }
1015
1016 // checkErrors();
1017 return NO_ERROR;
1018}
1019
Lucas Dupin3f11e922020-09-22 17:31:04 -07001020inline SkRect SkiaGLRenderEngine::getSkRect(const FloatRect& rect) {
1021 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1022}
1023
1024inline SkRect SkiaGLRenderEngine::getSkRect(const Rect& rect) {
1025 return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
1026}
1027
Lucas Dupin21f348e2020-09-16 17:31:26 -07001028inline SkRRect SkiaGLRenderEngine::getRoundedRect(const LayerSettings* layer) {
Ana Krulecf9a15d92020-12-11 08:35:00 -08001029 const auto rect = getSkRect(layer->geometry.roundedCornersCrop);
Lucas Dupin21f348e2020-09-16 17:31:26 -07001030 const auto cornerRadius = layer->geometry.roundedCornersRadius;
1031 return SkRRect::MakeRectXY(rect, cornerRadius, cornerRadius);
1032}
1033
Galia Peycheva80116e52020-11-06 11:57:25 +01001034inline BlurRegion SkiaGLRenderEngine::getBlurRegion(const LayerSettings* layer) {
1035 const auto rect = getSkRect(layer->geometry.boundaries);
1036 const auto cornersRadius = layer->geometry.roundedCornersRadius;
1037 return BlurRegion{.blurRadius = static_cast<uint32_t>(layer->backgroundBlurRadius),
1038 .cornerRadiusTL = cornersRadius,
1039 .cornerRadiusTR = cornersRadius,
1040 .cornerRadiusBL = cornersRadius,
1041 .cornerRadiusBR = cornersRadius,
1042 .alpha = 1,
1043 .left = static_cast<int>(rect.fLeft),
1044 .top = static_cast<int>(rect.fTop),
1045 .right = static_cast<int>(rect.fRight),
1046 .bottom = static_cast<int>(rect.fBottom)};
1047}
1048
Derek Sollenbergerecb21462021-01-29 16:53:49 -05001049inline bool SkiaGLRenderEngine::layerHasBlur(const LayerSettings* layer) {
1050 return layer->backgroundBlurRadius > 0 || layer->blurRegions.size();
1051}
1052
Lucas Dupin3f11e922020-09-22 17:31:04 -07001053inline SkColor SkiaGLRenderEngine::getSkColor(const vec4& color) {
1054 return SkColorSetARGB(color.a * 255, color.r * 255, color.g * 255, color.b * 255);
1055}
1056
Lucas Dupinbb1a1d42020-09-18 15:17:02 -07001057inline SkM44 SkiaGLRenderEngine::getSkM44(const mat4& matrix) {
1058 return SkM44(matrix[0][0], matrix[1][0], matrix[2][0], matrix[3][0],
1059 matrix[0][1], matrix[1][1], matrix[2][1], matrix[3][1],
1060 matrix[0][2], matrix[1][2], matrix[2][2], matrix[3][2],
1061 matrix[0][3], matrix[1][3], matrix[2][3], matrix[3][3]);
1062}
1063
Lucas Dupin3f11e922020-09-22 17:31:04 -07001064inline SkPoint3 SkiaGLRenderEngine::getSkPoint3(const vec3& vector) {
1065 return SkPoint3::Make(vector.x, vector.y, vector.z);
1066}
1067
John Reck67b1e2b2020-08-26 13:17:24 -07001068size_t SkiaGLRenderEngine::getMaxTextureSize() const {
1069 return mGrContext->maxTextureSize();
1070}
1071
1072size_t SkiaGLRenderEngine::getMaxViewportDims() const {
1073 return mGrContext->maxRenderTargetSize();
1074}
1075
Lucas Dupin3f11e922020-09-22 17:31:04 -07001076void SkiaGLRenderEngine::drawShadow(SkCanvas* canvas, const SkRect& casterRect, float cornerRadius,
1077 const ShadowSettings& settings) {
1078 ATRACE_CALL();
1079 const float casterZ = settings.length / 2.0f;
1080 const auto shadowShape = cornerRadius > 0
1081 ? SkPath::RRect(SkRRect::MakeRectXY(casterRect, cornerRadius, cornerRadius))
1082 : SkPath::Rect(casterRect);
1083 const auto flags =
1084 settings.casterIsTranslucent ? kTransparentOccluder_ShadowFlag : kNone_ShadowFlag;
1085
1086 SkShadowUtils::DrawShadow(canvas, shadowShape, SkPoint3::Make(0, 0, casterZ),
1087 getSkPoint3(settings.lightPos), settings.lightRadius,
1088 getSkColor(settings.ambientColor), getSkColor(settings.spotColor),
1089 flags);
1090}
1091
John Reck67b1e2b2020-08-26 13:17:24 -07001092EGLContext SkiaGLRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
Alec Mourid6f09462020-12-07 11:18:17 -08001093 EGLContext shareContext,
1094 std::optional<ContextPriority> contextPriority,
John Reck67b1e2b2020-08-26 13:17:24 -07001095 Protection protection) {
1096 EGLint renderableType = 0;
1097 if (config == EGL_NO_CONFIG_KHR) {
1098 renderableType = EGL_OPENGL_ES3_BIT;
1099 } else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
1100 LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
1101 }
1102 EGLint contextClientVersion = 0;
1103 if (renderableType & EGL_OPENGL_ES3_BIT) {
1104 contextClientVersion = 3;
1105 } else if (renderableType & EGL_OPENGL_ES2_BIT) {
1106 contextClientVersion = 2;
1107 } else if (renderableType & EGL_OPENGL_ES_BIT) {
1108 contextClientVersion = 1;
1109 } else {
1110 LOG_ALWAYS_FATAL("no supported EGL_RENDERABLE_TYPEs");
1111 }
1112
1113 std::vector<EGLint> contextAttributes;
1114 contextAttributes.reserve(7);
1115 contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
1116 contextAttributes.push_back(contextClientVersion);
Alec Mourid6f09462020-12-07 11:18:17 -08001117 if (contextPriority) {
John Reck67b1e2b2020-08-26 13:17:24 -07001118 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
Alec Mourid6f09462020-12-07 11:18:17 -08001119 switch (*contextPriority) {
1120 case ContextPriority::REALTIME:
1121 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_REALTIME_NV);
1122 break;
1123 case ContextPriority::MEDIUM:
1124 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_MEDIUM_IMG);
1125 break;
1126 case ContextPriority::LOW:
1127 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LOW_IMG);
1128 break;
1129 case ContextPriority::HIGH:
1130 default:
1131 contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
1132 break;
1133 }
John Reck67b1e2b2020-08-26 13:17:24 -07001134 }
1135 if (protection == Protection::PROTECTED) {
1136 contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1137 contextAttributes.push_back(EGL_TRUE);
1138 }
1139 contextAttributes.push_back(EGL_NONE);
1140
1141 EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1142
1143 if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
1144 // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
1145 // EGL_NO_CONTEXT so that we can abort.
1146 if (config != EGL_NO_CONFIG_KHR) {
1147 return context;
1148 }
1149 // If |config| is EGL_NO_CONFIG_KHR, we speculatively try to create GLES 3 context, so we
1150 // should try to fall back to GLES 2.
1151 contextAttributes[1] = 2;
1152 context = eglCreateContext(display, config, shareContext, contextAttributes.data());
1153 }
1154
1155 return context;
1156}
1157
Alec Mourid6f09462020-12-07 11:18:17 -08001158std::optional<RenderEngine::ContextPriority> SkiaGLRenderEngine::createContextPriority(
1159 const RenderEngineCreationArgs& args) {
1160 if (!gl::GLExtensions::getInstance().hasContextPriority()) {
1161 return std::nullopt;
1162 }
1163
1164 switch (args.contextPriority) {
1165 case RenderEngine::ContextPriority::REALTIME:
1166 if (gl::GLExtensions::getInstance().hasRealtimePriority()) {
1167 return RenderEngine::ContextPriority::REALTIME;
1168 } else {
1169 ALOGI("Realtime priority unsupported, degrading gracefully to high priority");
1170 return RenderEngine::ContextPriority::HIGH;
1171 }
1172 case RenderEngine::ContextPriority::HIGH:
1173 case RenderEngine::ContextPriority::MEDIUM:
1174 case RenderEngine::ContextPriority::LOW:
1175 return args.contextPriority;
1176 default:
1177 return std::nullopt;
1178 }
1179}
1180
John Reck67b1e2b2020-08-26 13:17:24 -07001181EGLSurface SkiaGLRenderEngine::createPlaceholderEglPbufferSurface(EGLDisplay display,
1182 EGLConfig config, int hwcFormat,
1183 Protection protection) {
1184 EGLConfig placeholderConfig = config;
1185 if (placeholderConfig == EGL_NO_CONFIG_KHR) {
1186 placeholderConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
1187 }
1188 std::vector<EGLint> attributes;
1189 attributes.reserve(7);
1190 attributes.push_back(EGL_WIDTH);
1191 attributes.push_back(1);
1192 attributes.push_back(EGL_HEIGHT);
1193 attributes.push_back(1);
1194 if (protection == Protection::PROTECTED) {
1195 attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
1196 attributes.push_back(EGL_TRUE);
1197 }
1198 attributes.push_back(EGL_NONE);
1199
1200 return eglCreatePbufferSurface(display, placeholderConfig, attributes.data());
1201}
1202
Alec Mouri617752f2021-04-15 16:27:01 +00001203void SkiaGLRenderEngine::cleanFramebufferCache() {
1204 // TODO(b/180767535) Remove this method and use b/180767535 instead, which would allow
1205 // SF to control texture lifecycle more tightly rather than through custom hooks into RE.
1206 std::lock_guard<std::mutex> lock(mRenderingMutex);
1207 mRuntimeEffects.clear();
1208 mProtectedTextureCache.clear();
1209 mTextureCache.clear();
1210}
1211
Alec Mourid6f09462020-12-07 11:18:17 -08001212int SkiaGLRenderEngine::getContextPriority() {
1213 int value;
1214 eglQueryContext(mEGLDisplay, mEGLContext, EGL_CONTEXT_PRIORITY_LEVEL_IMG, &value);
1215 return value;
1216}
1217
Derek Sollenbergerc4a05e12021-03-24 16:45:20 -04001218void SkiaGLRenderEngine::onPrimaryDisplaySizeChanged(ui::Size size) {
1219 // This cache multiplier was selected based on review of cache sizes relative
1220 // to the screen resolution. Looking at the worst case memory needed by blur (~1.5x),
1221 // shadows (~1x), and general data structures (e.g. vertex buffers) we selected this as a
1222 // conservative default based on that analysis.
1223 const float SURFACE_SIZE_MULTIPLIER = 3.5f * bytesPerPixel(mDefaultPixelFormat);
1224 const int maxResourceBytes = size.width * size.height * SURFACE_SIZE_MULTIPLIER;
1225
1226 // start by resizing the current context
1227 auto grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
1228 grContext->setResourceCacheLimit(maxResourceBytes);
1229
1230 // if it is possible to switch contexts then we will resize the other context
1231 if (useProtectedContext(!mInProtectedContext)) {
1232 grContext = mInProtectedContext ? mProtectedGrContext : mGrContext;
1233 grContext->setResourceCacheLimit(maxResourceBytes);
1234 // reset back to the initial context that was active when this method was called
1235 useProtectedContext(!mInProtectedContext);
1236 }
1237}
1238
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001239void SkiaGLRenderEngine::dump(std::string& result) {
1240 const gl::GLExtensions& extensions = gl::GLExtensions::getInstance();
1241
1242 StringAppendF(&result, "\n ------------RE-----------------\n");
1243 StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
1244 StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
1245 StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
1246 extensions.getVersion());
1247 StringAppendF(&result, "%s\n", extensions.getExtensions());
1248 StringAppendF(&result, "RenderEngine supports protected context: %d\n",
1249 supportsProtectedContent());
1250 StringAppendF(&result, "RenderEngine is in protected context: %d\n", mInProtectedContext);
Leon Scroggins III9f3072c2021-03-22 10:42:47 -04001251 StringAppendF(&result, "RenderEngine shaders cached since last dump/primeCache: %d\n",
1252 mSkSLCacheMonitor.shadersCachedSinceLastCall());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001253
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001254 std::vector<ResourcePair> cpuResourceMap = {
1255 {"skia/sk_resource_cache/bitmap_", "Bitmaps"},
1256 {"skia/sk_resource_cache/rrect-blur_", "Masks"},
1257 {"skia/sk_resource_cache/rects-blur_", "Masks"},
1258 {"skia/sk_resource_cache/tessellated", "Shadows"},
1259 {"skia", "Other"},
1260 };
1261 SkiaMemoryReporter cpuReporter(cpuResourceMap, false);
1262 SkGraphics::DumpMemoryStatistics(&cpuReporter);
1263 StringAppendF(&result, "Skia CPU Caches: ");
1264 cpuReporter.logTotals(result);
1265 cpuReporter.logOutput(result);
1266
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001267 {
1268 std::lock_guard<std::mutex> lock(mRenderingMutex);
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001269
1270 std::vector<ResourcePair> gpuResourceMap = {
1271 {"texture_renderbuffer", "Texture/RenderBuffer"},
1272 {"texture", "Texture"},
1273 {"gr_text_blob_cache", "Text"},
1274 {"skia", "Other"},
1275 };
1276 SkiaMemoryReporter gpuReporter(gpuResourceMap, true);
1277 mGrContext->dumpMemoryStatistics(&gpuReporter);
1278 StringAppendF(&result, "Skia's GPU Caches: ");
1279 gpuReporter.logTotals(result);
1280 gpuReporter.logOutput(result);
1281 StringAppendF(&result, "Skia's Wrapped Objects:\n");
1282 gpuReporter.logOutput(result, true);
1283
1284 StringAppendF(&result, "RenderEngine AHB/BackendTexture cache size: %zu\n",
1285 mTextureCache.size());
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001286 StringAppendF(&result, "Dumping buffer ids...\n");
1287 // TODO(178539829): It would be nice to know which layer these are coming from and what
1288 // the texture sizes are.
1289 for (const auto& [id, unused] : mTextureCache) {
1290 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1291 }
1292 StringAppendF(&result, "\n");
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001293
1294 SkiaMemoryReporter gpuProtectedReporter(gpuResourceMap, true);
Derek Sollenberger80a7a762021-04-14 10:22:58 -04001295 if (mProtectedGrContext) {
1296 mProtectedGrContext->dumpMemoryStatistics(&gpuProtectedReporter);
1297 }
Derek Sollenberger0e6d3562021-04-07 19:34:39 -04001298 StringAppendF(&result, "Skia's GPU Protected Caches: ");
1299 gpuProtectedReporter.logTotals(result);
1300 gpuProtectedReporter.logOutput(result);
1301 StringAppendF(&result, "Skia's Protected Wrapped Objects:\n");
1302 gpuProtectedReporter.logOutput(result, true);
1303
1304 StringAppendF(&result, "RenderEngine protected AHB/BackendTexture cache size: %zu\n",
Ana Krulec1d12b3b2021-01-27 16:49:51 -08001305 mProtectedTextureCache.size());
1306 StringAppendF(&result, "Dumping buffer ids...\n");
1307 for (const auto& [id, unused] : mProtectedTextureCache) {
1308 StringAppendF(&result, "- 0x%" PRIx64 "\n", id);
1309 }
1310 StringAppendF(&result, "\n");
1311 StringAppendF(&result, "RenderEngine runtime effects: %zu\n", mRuntimeEffects.size());
1312 for (const auto& [linearEffect, unused] : mRuntimeEffects) {
1313 StringAppendF(&result, "- inputDataspace: %s\n",
1314 dataspaceDetails(
1315 static_cast<android_dataspace>(linearEffect.inputDataspace))
1316 .c_str());
1317 StringAppendF(&result, "- outputDataspace: %s\n",
1318 dataspaceDetails(
1319 static_cast<android_dataspace>(linearEffect.outputDataspace))
1320 .c_str());
1321 StringAppendF(&result, "undoPremultipliedAlpha: %s\n",
1322 linearEffect.undoPremultipliedAlpha ? "true" : "false");
1323 }
1324 }
1325 StringAppendF(&result, "\n");
1326}
1327
John Reck67b1e2b2020-08-26 13:17:24 -07001328} // namespace skia
1329} // namespace renderengine
Galia Peycheva6c460652020-11-03 19:42:42 +01001330} // namespace android